Sets the collection's sync function based on the JS code from config. Returns a boolean indicating whether the function is different from the saved one. If multiple gateway instances try to update the function at the same time (to the same new value) only one of them will get a changed=true result.
(ctx context.Context, syncFun string)
| 366 | // If multiple gateway instances try to update the function at the same time (to the same new |
| 367 | // value) only one of them will get a changed=true result. |
| 368 | func (c *DatabaseCollection) UpdateSyncFun(ctx context.Context, syncFun string) (changed bool, err error) { |
| 369 | if syncFun == "" { |
| 370 | c.ChannelMapper = nil |
| 371 | } else if c.ChannelMapper != nil { |
| 372 | _, err = c.ChannelMapper.SetFunction(syncFun) |
| 373 | } else { |
| 374 | c.ChannelMapper = channels.NewChannelMapper(ctx, syncFun, c.dbCtx.Options.JavascriptTimeout) |
| 375 | } |
| 376 | if err != nil { |
| 377 | base.WarnfCtx(ctx, "Error setting sync function: %s", err) |
| 378 | return |
| 379 | } |
| 380 | |
| 381 | var syncData struct { // format of the sync-fn document |
| 382 | Sync string |
| 383 | } |
| 384 | |
| 385 | syncFunctionDocID := base.CollectionSyncFunctionKeyWithGroupID(c.dbCtx.Options.GroupID, c.ScopeName, c.Name) |
| 386 | _, err = c.dbCtx.MetadataStore.Update(syncFunctionDocID, 0, func(currentValue []byte) ([]byte, *uint32, bool, error) { |
| 387 | // The first time opening a new db, currentValue will be nil. Don't treat this as a change. |
| 388 | if currentValue != nil { |
| 389 | parseErr := base.JSONUnmarshal(currentValue, &syncData) |
| 390 | if parseErr != nil || syncData.Sync != syncFun { |
| 391 | changed = true |
| 392 | } |
| 393 | } |
| 394 | if changed || currentValue == nil { |
| 395 | syncData.Sync = syncFun |
| 396 | bytes, err := base.JSONMarshal(syncData) |
| 397 | return bytes, nil, false, err |
| 398 | } else { |
| 399 | return nil, nil, false, base.ErrUpdateCancel // value unchanged, no need to save |
| 400 | } |
| 401 | }) |
| 402 | |
| 403 | if err == base.ErrUpdateCancel { |
| 404 | err = nil |
| 405 | } |
| 406 | return |
| 407 | } |
| 408 | |
| 409 | // DatabaseCollection helper methods for channel and role invalidation - invoke the multi-collection version on |
| 410 | // the databaseContext for a single collection. |