velocious 1.0.721 → 1.0.722

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/build/background-jobs/main.js +10 -2
  2. package/build/configuration-types.js +1 -1
  3. package/build/database/advisory-lock-reentrancy-node.js +9 -0
  4. package/build/database/advisory-lock-reentrancy.js +66 -0
  5. package/build/database/advisory-lock-runner.js +9 -12
  6. package/build/environment-handlers/node.js +1 -0
  7. package/build/src/background-jobs/main.d.ts.map +1 -1
  8. package/build/src/background-jobs/main.js +11 -4
  9. package/build/src/configuration-types.d.ts +2 -2
  10. package/build/src/configuration-types.js +2 -2
  11. package/build/src/database/advisory-lock-reentrancy-node.d.ts +2 -0
  12. package/build/src/database/advisory-lock-reentrancy-node.d.ts.map +1 -0
  13. package/build/src/database/advisory-lock-reentrancy-node.js +7 -0
  14. package/build/src/database/advisory-lock-reentrancy.d.ts +67 -0
  15. package/build/src/database/advisory-lock-reentrancy.d.ts.map +1 -0
  16. package/build/src/database/advisory-lock-reentrancy.js +60 -0
  17. package/build/src/database/advisory-lock-runner.d.ts +25 -33
  18. package/build/src/database/advisory-lock-runner.d.ts.map +1 -1
  19. package/build/src/database/advisory-lock-runner.js +10 -13
  20. package/build/src/environment-handlers/node.d.ts +1 -0
  21. package/build/src/environment-handlers/node.d.ts.map +1 -1
  22. package/build/src/environment-handlers/node.js +2 -1
  23. package/build/src/sync/sync-cursor.d.ts +30 -0
  24. package/build/src/sync/sync-cursor.d.ts.map +1 -0
  25. package/build/src/sync/sync-cursor.js +54 -0
  26. package/build/src/sync/sync-realtime-bridge.d.ts +127 -24
  27. package/build/src/sync/sync-realtime-bridge.d.ts.map +1 -1
  28. package/build/src/sync/sync-realtime-bridge.js +92 -56
  29. package/build/src/sync/sync-websocket-channel.d.ts +49 -0
  30. package/build/src/sync/sync-websocket-channel.d.ts.map +1 -1
  31. package/build/src/sync/sync-websocket-channel.js +138 -2
  32. package/build/sync/sync-cursor.js +56 -0
  33. package/build/sync/sync-realtime-bridge.js +97 -51
  34. package/build/sync/sync-websocket-channel.js +153 -1
  35. package/package.json +1 -1
  36. package/src/background-jobs/main.js +10 -2
  37. package/src/configuration-types.js +1 -1
  38. package/src/database/advisory-lock-reentrancy-node.js +9 -0
  39. package/src/database/advisory-lock-reentrancy.js +66 -0
  40. package/src/database/advisory-lock-runner.js +9 -12
  41. package/src/environment-handlers/node.js +1 -0
  42. package/src/sync/sync-cursor.js +56 -0
  43. package/src/sync/sync-realtime-bridge.js +97 -51
  44. package/src/sync/sync-websocket-channel.js +153 -1
@@ -5,10 +5,46 @@ import {mergeRemoteRequestContext} from "../remote-request-context.js"
5
5
 
6
6
  import SyncApiClient from "./sync-api-client.js"
7
7
  import {VELOCIOUS_SYNC_CHANNEL} from "./sync-channel-name.js"
8
+ import {cursorFromSyncEntry, isCursorAfter} from "./sync-cursor.js"
8
9
 
9
10
  /** @typedef {import("../configuration-types.js").VelociousSyncRealtimeChannelDescriptor} VelociousSyncRealtimeChannelDescriptor */
10
11
  /** @typedef {import("../configuration-types.js").VelociousSyncRealtimeWebsocketClient} VelociousSyncRealtimeWebsocketClient */
11
12
 
13
+ /**
14
+ * The persisted scope row the bridge carries so it can advance the scope's cursor
15
+ * on applied pushes. Mirrors the framework-owned scope store row shape.
16
+ * @typedef {object} SyncRealtimeScopeRow
17
+ * @property {Record<string, ReturnType<typeof JSON.parse>>} conditions - Scope attribute conditions.
18
+ * @property {string | null} cursorPayload - Persisted cursor JSON payload.
19
+ * @property {string} id - Scope row id.
20
+ * @property {string | null} resourceType - Scope resource type.
21
+ * @property {string} scopeDigest - Fixed-size scope digest.
22
+ * @property {string} state - Scope state.
23
+ * @property {string} storeIdentity - Physical store identity.
24
+ */
25
+
26
+ /**
27
+ * One derived channel subscription carrying its owning scope row (null for legacy
28
+ * app channels) and the in-memory cursor watermark advanced by applied pushes.
29
+ * @typedef {object} DerivedSyncChannel
30
+ * @property {string} channel - Channel name.
31
+ * @property {import("./sync-api-client-types.js").SyncCursor} cursor - In-memory cursor watermark.
32
+ * @property {string | null} resourceType - Default resource type for pushed changes.
33
+ * @property {SyncRealtimeScopeRow | null} scopeRow - Owning scope row, or null for legacy channels.
34
+ * @property {import("../configuration-types.js").VelociousSyncRealtimeSubscription} subscription - Subscription handle.
35
+ */
36
+
37
+ /**
38
+ * One derived channel to subscribe, carrying its owning scope row and cursor for
39
+ * framework sync channel subscriptions (null scope row for legacy app channels).
40
+ * @typedef {object} DerivedSyncChannelDescriptor
41
+ * @property {string} channel - Channel name.
42
+ * @property {import("./sync-api-client-types.js").SyncCursor} cursor - In-memory cursor watermark (null for legacy channels).
43
+ * @property {Record<string, ReturnType<typeof JSON.parse>>} params - Subscribe params (without the framework-injected auth token).
44
+ * @property {string | null} resourceType - Default resource type for pushed changes.
45
+ * @property {SyncRealtimeScopeRow | null} scopeRow - Owning scope row, or null for legacy channels.
46
+ */
47
+
12
48
  /**
13
49
  * Derived realtime push bridge for the sync client. Subscribes every declared
14
50
  * pull scope to the framework sync channel ({@link VELOCIOUS_SYNC_CHANNEL})
@@ -29,7 +65,7 @@ export default class SyncRealtimeBridge {
29
65
  */
30
66
  constructor({syncClient}) {
31
67
  this.syncClient = syncClient
32
- /** @type {Array<{channel: string, resourceType: string | null, subscription: import("../configuration-types.js").VelociousSyncRealtimeSubscription}>} */
68
+ /** @type {Array<DerivedSyncChannel>} */
33
69
  this._channels = []
34
70
  /** @type {VelociousSyncRealtimeWebsocketClient | null} */
35
71
  this._client = null
@@ -40,8 +76,6 @@ export default class SyncRealtimeBridge {
40
76
  /** @type {number} Subscription generation - bumped by unsubscribe so in-flight subscribes detect they became stale. */
41
77
  this._generation = 0
42
78
  /** @type {Promise<void> | null} */
43
- this._scheduledPull = null
44
- /** @type {Promise<void> | null} */
45
79
  this._subscribePromise = null
46
80
  /** @type {"subscribed" | "subscribing" | "unsubscribed"} */
47
81
  this._state = "unsubscribed"
@@ -83,7 +117,7 @@ export default class SyncRealtimeBridge {
83
117
 
84
118
  this._state = "subscribing"
85
119
 
86
- /** @type {Array<{channel: string, resourceType: string | null, subscription: import("../configuration-types.js").VelociousSyncRealtimeSubscription}>} */
120
+ /** @type {Array<DerivedSyncChannel>} */
87
121
  const channels = []
88
122
  /** @type {VelociousSyncRealtimeWebsocketClient | null} */
89
123
  let client = null
@@ -154,13 +188,19 @@ export default class SyncRealtimeBridge {
154
188
  label: "Sync client request context",
155
189
  params: {...channelDescriptor.params, authenticationToken}
156
190
  })
157
- const subscription = client.subscribeChannel(channelDescriptor.channel, {
158
- onMessage: (body) => this.enqueueApply({body, generation, resourceType}),
159
- onResume: () => this.schedulePull(generation),
160
- params
161
- })
191
+ /** @type {DerivedSyncChannel} */
192
+ const channel = {
193
+ channel: channelDescriptor.channel,
194
+ cursor: channelDescriptor.cursor,
195
+ resourceType,
196
+ scopeRow: channelDescriptor.scopeRow,
197
+ subscription: client.subscribeChannel(channelDescriptor.channel, {
198
+ onMessage: (body) => this.enqueueApply({body, channel, generation}),
199
+ params
200
+ })
201
+ }
162
202
 
163
- channels.push({channel: channelDescriptor.channel, resourceType, subscription})
203
+ channels.push(channel)
164
204
  }
165
205
 
166
206
  await Promise.all(channels.map(({subscription}) => subscription.waitForReady({signal})))
@@ -175,7 +215,6 @@ export default class SyncRealtimeBridge {
175
215
  this._client = client
176
216
  this._ownsClient = ownsClient
177
217
  this._state = "subscribed"
178
- this.schedulePull(generation)
179
218
  } catch (error) {
180
219
  await teardown()
181
220
 
@@ -225,12 +264,11 @@ export default class SyncRealtimeBridge {
225
264
  }
226
265
 
227
266
  /**
228
- * Awaits all enqueued message applies and any scheduled pull (tests, shutdown flows).
267
+ * Awaits all enqueued message applies (tests, shutdown flows).
229
268
  * @returns {Promise<void>}
230
269
  */
231
270
  async waitForApplied() {
232
271
  await this._applyPromise
233
- if (this._scheduledPull) await this._scheduledPull
234
272
  }
235
273
 
236
274
  /**
@@ -266,33 +304,44 @@ export default class SyncRealtimeBridge {
266
304
  * model-level static realtime declarations and the config channels callback.
267
305
  * Fails loudly when nothing is subscribable.
268
306
  * @param {ReturnType<typeof JSON.parse>} context - App context passed to the deprecated channels callback.
269
- * @returns {Promise<Array<VelociousSyncRealtimeChannelDescriptor>>} Channel descriptors.
307
+ * @returns {Promise<Array<DerivedSyncChannelDescriptor>>} Channel descriptors.
270
308
  */
271
309
  async channelDescriptors(context) {
272
310
  const realtime = this.realtimeConfiguration()
273
- /** @type {Array<VelociousSyncRealtimeChannelDescriptor>} */
311
+ /** @type {Array<DerivedSyncChannelDescriptor>} */
274
312
  const channelDescriptors = []
275
313
 
276
314
  for (const scopeRow of await this.syncClient.scopeStore().activeScopes()) {
315
+ const cursorPayload = await this.syncClient.scopeStore().loadCursor(scopeRow)
316
+ const cursor = SyncApiClient.syncCursorFromPayload(cursorPayload)
317
+
277
318
  channelDescriptors.push({
278
319
  channel: VELOCIOUS_SYNC_CHANNEL,
320
+ cursor,
279
321
  params: {
280
322
  conditions: this.attributeNamedConditions(scopeRow),
281
323
  resourceType: scopeRow.resourceType,
282
324
  // Only the all-types scope carries the type list; a type-declared scope needs none.
283
- ...(scopeRow.resourceType === null ? {resourceTypes: this.syncClient.userScopeResourceTypes()} : {})
284
- }
325
+ ...(scopeRow.resourceType === null ? {resourceTypes: this.syncClient.userScopeResourceTypes()} : {}),
326
+ // Reuse the changes-endpoint cursor fields so the server replays the
327
+ // catch-up backlog from the scope's persisted cursor on subscribe.
328
+ ...SyncApiClient.cursorPayload("after", cursor)
329
+ },
330
+ resourceType: scopeRow.resourceType,
331
+ scopeRow
285
332
  })
286
333
  }
287
334
 
288
335
  for (const [resourceType, resourceConfig] of Object.entries(this.syncClient.config.resources)) {
289
336
  if (!resourceConfig.realtime) continue
290
337
 
291
- channelDescriptors.push({channel: resourceConfig.realtime.channel, params: resourceConfig.realtime.params, resourceType})
338
+ channelDescriptors.push({channel: resourceConfig.realtime.channel, cursor: null, params: resourceConfig.realtime.params ?? {}, resourceType, scopeRow: null})
292
339
  }
293
340
 
294
341
  if (realtime?.channels) {
295
- channelDescriptors.push(...await realtime.channels(context))
342
+ const legacyChannels = await realtime.channels(context)
343
+
344
+ channelDescriptors.push(...legacyChannels.map((descriptor) => ({channel: descriptor.channel, cursor: null, params: descriptor.params ?? {}, resourceType: descriptor.resourceType ?? null, scopeRow: null})))
296
345
  }
297
346
 
298
347
  if (channelDescriptors.length === 0) {
@@ -341,15 +390,15 @@ export default class SyncRealtimeBridge {
341
390
  /**
342
391
  * Chains one pushed message onto the serialized apply queue so changes apply
343
392
  * in arrival order; failures go to the sync client's error reporting.
344
- * @param {{body: ReturnType<typeof JSON.parse>, generation?: number, resourceType: string | null}} args - Message args.
393
+ * @param {{body: ReturnType<typeof JSON.parse>, channel: DerivedSyncChannel, generation?: number}} args - Message args.
345
394
  * @returns {void}
346
395
  */
347
- enqueueApply({body, generation = this._generation, resourceType}) {
396
+ enqueueApply({body, channel, generation = this._generation}) {
348
397
  this._applyPromise = this._applyPromise.then(async () => {
349
398
  if (generation !== this._generation) return
350
399
 
351
400
  try {
352
- await this.applyMessage({body, resourceType})
401
+ await this.applyMessage({body, channel})
353
402
  } catch (error) {
354
403
  this.syncClient.reportError(/** @type {Error} */ (error))
355
404
  }
@@ -359,11 +408,12 @@ export default class SyncRealtimeBridge {
359
408
  /**
360
409
  * Applies one pushed message through the derived resource applier: drops
361
410
  * own-device messages by echo origin, defaults the channel's resourceType onto
362
- * envelopes without one, and fails loudly on unknown resource types.
363
- * @param {{body: ReturnType<typeof JSON.parse>, resourceType: string | null}} args - Message args.
411
+ * envelopes without one, fails loudly on unknown resource types, and advances
412
+ * the owning scope's cursor so a later replay resumes after the applied rows.
413
+ * @param {{body: ReturnType<typeof JSON.parse>, channel: DerivedSyncChannel}} args - Message args.
364
414
  * @returns {Promise<void>}
365
415
  */
366
- async applyMessage({body, resourceType}) {
416
+ async applyMessage({body, channel}) {
367
417
  if (!body || typeof body !== "object" || Array.isArray(body)) {
368
418
  throw new Error(`Realtime sync messages must be envelope objects, got: ${JSON.stringify(body)}`)
369
419
  }
@@ -382,44 +432,40 @@ export default class SyncRealtimeBridge {
382
432
  // Coalesce record-change events across the pushed batch so it triggers one live-query re-run.
383
433
  await recordChanges.batch(async () => {
384
434
  for (const syncPayload of syncPayloads) {
385
- const sync = SyncApiClient.syncEnvelopeFromPayload({resourceType, ...syncPayload})
435
+ const sync = SyncApiClient.syncEnvelopeFromPayload({resourceType: channel.resourceType, ...syncPayload})
386
436
 
387
437
  await applySync(sync)
388
438
  }
389
439
  })
440
+
441
+ await this.advanceScopeCursor(channel, syncPayloads)
390
442
  }
391
443
 
392
444
  /**
393
- * Schedules a coalesced background pull closing offline gaps after
394
- * (re)subscription readiness. Resumes arriving while a pull is already
395
- * scheduled or in flight coalesce into that pull instead of stacking.
396
- * @param {number} [generation] - Subscription generation owning the resume/readiness callback.
397
- * @returns {void}
445
+ * Advances the owning scope's persisted cursor to the newest applied row,
446
+ * monotonically (never backwards) so an out-of-order or duplicate push cannot
447
+ * regress the cursor and re-deliver already-applied rows on a later replay.
448
+ * Legacy channels with no owning scope are skipped.
449
+ * @param {DerivedSyncChannel} channel - Channel owning the scope.
450
+ * @param {Array<ReturnType<typeof JSON.parse>>} syncPayloads - Applied sync entries.
451
+ * @returns {Promise<void>}
398
452
  */
399
- schedulePull(generation = this._generation) {
400
- if (generation !== this._generation) return
401
- if (this.realtimeConfiguration()?.pullOnReconnect === false) return
453
+ async advanceScopeCursor(channel, syncPayloads) {
454
+ if (!channel.scopeRow) return
402
455
 
403
- const coordinatorRun = this.syncClient.requestCoordinatorSync("realtime")
456
+ let latestCursor = channel.cursor
404
457
 
405
- if (coordinatorRun) {
406
- this._scheduledPull ||= coordinatorRun.finally(() => {
407
- this._scheduledPull = null
408
- })
409
- return
458
+ for (const syncPayload of syncPayloads) {
459
+ const entry = /** @type {Record<string, ReturnType<typeof JSON.parse>>} */ (syncPayload)
460
+ const cursor = cursorFromSyncEntry(entry)
461
+
462
+ if (cursor && isCursorAfter(cursor, latestCursor)) latestCursor = cursor
410
463
  }
411
464
 
412
- this._scheduledPull ||= (async () => {
413
- try {
414
- await this.syncClient.pull()
415
- } catch (error) {
416
- if (!this.syncClient.isLifecycleAbort(error)) {
417
- this.syncClient.reportError(/** @type {Error} */ (error))
418
- }
419
- } finally {
420
- this._scheduledPull = null
421
- }
422
- })()
465
+ if (latestCursor && latestCursor !== channel.cursor) {
466
+ channel.cursor = latestCursor
467
+ await this.syncClient.scopeStore().saveCursor(channel.scopeRow, latestCursor)
468
+ }
423
469
  }
424
470
  }
425
471
 
@@ -2,10 +2,53 @@
2
2
 
3
3
  import VelociousWebsocketChannel from "../http-server/websocket-channel.js"
4
4
  import {VELOCIOUS_SYNC_CHANNEL} from "./sync-channel-name.js"
5
+ import {cursorFromSyncEntry, isCursorAfter} from "./sync-cursor.js"
6
+ import SyncModelChangeFeedService from "./sync-model-change-feed-service.js"
5
7
 
6
8
  /** Configurations whose framework sync channel has already been registered. */
7
9
  const registeredConfigurations = new WeakSet()
8
10
 
11
+ /** Default catch-up replay page size when the subscriber sends no `limit` param. */
12
+ const DEFAULT_REPLAY_LIMIT = 1000
13
+
14
+ /**
15
+ * Serializes a cursor into the change-feed request params under the given prefix.
16
+ * @param {"after" | "upTo"} prefix - Request field prefix.
17
+ * @param {import("./sync-api-client-types.js").SyncCursor} cursor - Cursor to serialize.
18
+ * @returns {Record<string, string | number | null>} Serialized cursor params.
19
+ */
20
+ function cursorParams(prefix, cursor) {
21
+ if (!cursor) return {}
22
+
23
+ return {
24
+ [`${prefix}Id`]: cursor.id,
25
+ ...(cursor.serverSequence !== null ? {[`${prefix}ServerSequence`]: cursor.serverSequence} : {}),
26
+ [`${prefix}UpdatedAt`]: cursor.updatedAt
27
+ }
28
+ }
29
+
30
+ /**
31
+ * Reads the after-cursor the subscriber declared in its subscribe params, or null
32
+ * when it sent none (a fresh subscription replays the whole scope).
33
+ * @param {Record<string, ReturnType<typeof JSON.parse>>} params - Subscribe params.
34
+ * @returns {import("./sync-api-client-types.js").SyncCursor} Declared after-cursor, or null.
35
+ */
36
+ function cursorFromParams(params) {
37
+ const updatedAt = typeof params.afterUpdatedAt === "string" ? params.afterUpdatedAt : null
38
+
39
+ if (!updatedAt) return null
40
+
41
+ const serverSequence = params.afterServerSequence === null || params.afterServerSequence === undefined
42
+ ? null
43
+ : Number(params.afterServerSequence)
44
+
45
+ return {
46
+ id: params.afterId === null || params.afterId === undefined ? null : String(params.afterId),
47
+ serverSequence,
48
+ updatedAt
49
+ }
50
+ }
51
+
9
52
  /**
10
53
  * Framework-owned websocket channel for synced resources
11
54
  * ({@link VELOCIOUS_SYNC_CHANNEL}).
@@ -25,6 +68,14 @@ export default class SyncWebsocketChannel extends VelociousWebsocketChannel {
25
68
  */
26
69
  _scope = null
27
70
 
71
+ /**
72
+ * Cursor of the last sync entry delivered to this subscription, advanced by
73
+ * live broadcasts and catch-up replay so a resume replays only the rows missed
74
+ * while the socket was down.
75
+ * @type {import("./sync-api-client-types.js").SyncCursor}
76
+ */
77
+ _deliveredCursor = null
78
+
28
79
  /**
29
80
  * Registers the framework sync channel on a configuration declaring a
30
81
  * `sync.api` block (guarded so repeated server boots with the same
@@ -169,13 +220,17 @@ export default class SyncWebsocketChannel extends VelociousWebsocketChannel {
169
220
  async deliverBroadcast(body, meta) {
170
221
  if (!this._isUserScope()) {
171
222
  this.sendMessage(body, meta)
223
+ this._trackDeliveredCursor(body)
172
224
 
173
225
  return
174
226
  }
175
227
 
176
228
  const deliverableBody = await this._userScopeDeliverableBody(body)
177
229
 
178
- if (deliverableBody !== null) this.sendMessage(deliverableBody, meta)
230
+ if (deliverableBody !== null) {
231
+ this.sendMessage(deliverableBody, meta)
232
+ this._trackDeliveredCursor(deliverableBody)
233
+ }
179
234
  }
180
235
 
181
236
  /**
@@ -245,6 +300,103 @@ export default class SyncWebsocketChannel extends VelociousWebsocketChannel {
245
300
  return deliverableSyncs[0]
246
301
  }
247
302
 
303
+ /**
304
+ * Replays the catch-up backlog to this subscriber once its subscription is
305
+ * authorized: pages the scoped change feed from the cursor the client declared
306
+ * in its subscribe params and sends each page as a standard sync envelope, then
307
+ * live broadcasts continue from there. A fresh subscription with no cursor
308
+ * replays the whole authorized scope.
309
+ * @returns {Promise<void>}
310
+ */
311
+ async subscribed() {
312
+ if (!this._scope) return
313
+
314
+ await this._replayFrom(cursorFromParams(this.params))
315
+ }
316
+
317
+ /**
318
+ * Replays rows missed while the socket was down, resuming from the cursor of
319
+ * the last entry this subscription delivered instead of re-reading the whole
320
+ * scope from the subscribe-time cursor.
321
+ * @returns {Promise<void>}
322
+ */
323
+ async onResume() {
324
+ if (!this._scope) return
325
+
326
+ await this._replayFrom(this._deliveredCursor ?? cursorFromParams(this.params))
327
+ }
328
+
329
+ /**
330
+ * Pages the scoped change feed from a cursor and delivers each page to this
331
+ * subscriber as a `{echoOrigin, syncs}` envelope. The snapshot high-water is
332
+ * resolved once and pinned across pages so rows arriving mid-replay are left to
333
+ * the live broadcast path instead of looping the replay. The delivered cursor
334
+ * advances so a later resume resumes from here.
335
+ * @param {import("./sync-api-client-types.js").SyncCursor} afterCursor - Cursor to replay after.
336
+ * @returns {Promise<void>}
337
+ */
338
+ async _replayFrom(afterCursor) {
339
+ const configuration = this.session.configuration
340
+ const scope = this._scope
341
+
342
+ await configuration.ensureConnections({name: `${VELOCIOUS_SYNC_CHANNEL} catch-up replay`}, async () => {
343
+ const resource = await this.buildSyncResource()
344
+ const limit = this._replayLimit(resource)
345
+ /** @type {import("./sync-api-client-types.js").SyncCursor} */
346
+ let upToCursor = null
347
+
348
+ while (true) {
349
+ const page = await resource.changeFeedService({
350
+ params: {...this.params, ...cursorParams("after", afterCursor), ...(upToCursor ? cursorParams("upTo", upToCursor) : {})},
351
+ scope
352
+ }).changes()
353
+
354
+ if (!upToCursor) upToCursor = page.upToCursor
355
+
356
+ if (page.syncs.length === 0) break
357
+
358
+ await this.deliverBroadcast({echoOrigin: null, syncs: page.syncs})
359
+
360
+ afterCursor = page.nextCursor
361
+ if (afterCursor) this._deliveredCursor = afterCursor
362
+
363
+ if (page.syncs.length < limit) break
364
+ }
365
+ })
366
+ }
367
+
368
+ /**
369
+ * Resolves the catch-up replay page size from the subscriber's `limit` param
370
+ * (defaulting to {@link DEFAULT_REPLAY_LIMIT}).
371
+ * @param {import("./sync-resource-base.js").default} resource - Authorizing sync resource.
372
+ * @returns {number} Replay page size.
373
+ */
374
+ _replayLimit(resource) {
375
+ return new SyncModelChangeFeedService({modelClass: resource.syncModelClass(), params: this.params}).normalizedLimit(this.params.limit)
376
+ }
377
+
378
+ /**
379
+ * Advances the delivered-cursor watermark from a delivered envelope so a resume
380
+ * resumes after the newest row actually sent to this subscriber. Broadcasts may
381
+ * arrive out of order across resources, so each entry only advances the
382
+ * watermark when it is later than the current one.
383
+ * @param {import("../http-server/websocket-channel.js").WebsocketJsonValue} body - Delivered envelope.
384
+ * @returns {void}
385
+ */
386
+ _trackDeliveredCursor(body) {
387
+ if (!body || typeof body !== "object" || Array.isArray(body)) return
388
+
389
+ const envelope = /** @type {Record<string, ReturnType<typeof JSON.parse>>} */ (body)
390
+ const syncs = Array.isArray(envelope.syncs) ? envelope.syncs : [envelope]
391
+
392
+ for (const entry of syncs) {
393
+ const syncEntry = /** @type {Record<string, ReturnType<typeof JSON.parse>>} */ (entry)
394
+ const cursor = cursorFromSyncEntry(syncEntry)
395
+
396
+ if (cursor && isCursorAfter(cursor, this._deliveredCursor)) this._deliveredCursor = cursor
397
+ }
398
+ }
399
+
248
400
  /**
249
401
  * Returns the authorized scope for debug snapshots.
250
402
  * @returns {Record<string, ReturnType<typeof JSON.parse>>} Debug-safe subscription details.