velocious 1.0.500 → 1.0.501

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.
@@ -6,6 +6,7 @@ import restArgsError from "../utils/rest-args-error.js"
6
6
 
7
7
  import {serializedScopeFromQuery} from "./query-scope.js"
8
8
  import SyncApiClient from "./sync-api-client.js"
9
+ import SyncRealtimeBridge from "./sync-realtime-bridge.js"
9
10
  import SyncScopeStore from "./sync-scope-store.js"
10
11
  import {currentSyncClient, setCurrentSyncClient} from "./sync-client-registry.js"
11
12
 
@@ -87,10 +88,13 @@ export default class SyncClient {
87
88
  onError: clientConfiguration.onError,
88
89
  postChanges: transportPoster({path: `${clientConfiguration.mountPath}/changes`, transport: clientConfiguration.transport}),
89
90
  postReplay: transportPoster({path: `${clientConfiguration.mountPath}/replay`, transport: clientConfiguration.transport}),
91
+ realtime: clientConfiguration.realtime,
90
92
  resources,
91
93
  syncModel: resolvedSyncModel
92
94
  }
93
95
  this._clientNumber = ++clientCounter
96
+ /** @type {SyncRealtimeBridge | null} */
97
+ this._realtimeBridge = null
94
98
  /** @type {import("./sync-scope-store.js").default | null} */
95
99
  this._scopeStore = scopeStore || null
96
100
  /** @type {Promise<void> | null} */
@@ -265,26 +269,7 @@ export default class SyncClient {
265
269
  await SyncApiClient.singleFlight(`velocious-sync-client-pull-${this._clientNumber}`, async () => {
266
270
  const authenticationToken = await this.config.authenticationToken()
267
271
  const scopeStore = this.scopeStore()
268
- const pullResourceConfigs = this.pullResourceConfigs()
269
- const applier = SyncApiClient.resourceApplier(pullResourceConfigs, (record) => {
270
- this._remoteApplyRecords.add(record)
271
-
272
- return () => this._remoteApplyRecords.delete(record)
273
- })
274
- /**
275
- * Applies one pulled change, failing loudly instead of silently skipping unconfigured resources.
276
- * @param {import("./sync-api-client-types.js").SyncChangeEnvelope} sync - Pulled change.
277
- * @returns {Promise<import("./sync-api-client-types.js").SyncChangeApplyResult>} Apply result.
278
- */
279
- const applySync = async (sync) => {
280
- const resourceType = sync.resourceType()
281
-
282
- if (!resourceType || !pullResourceConfigs[resourceType]) {
283
- throw new Error(`No sync resource with pull attributes configured for pulled change: ${String(resourceType)}`)
284
- }
285
-
286
- return await applier(sync)
287
- }
272
+ const applySync = this.remoteApplySync()
288
273
  const result = {
289
274
  changed: false,
290
275
  pages: 0,
@@ -324,6 +309,78 @@ export default class SyncClient {
324
309
  return combinedResult
325
310
  }
326
311
 
312
+ /**
313
+ * Builds the derived remote-change applier shared by pulls and realtime pushes:
314
+ * applies through the declared resource configs, registers each written record
315
+ * for echo suppression (tracked resources do not re-queue applied changes), and
316
+ * fails loudly instead of silently skipping unconfigured resources.
317
+ * @param {{source?: string}} [args] - Error context describing where the change came from.
318
+ * @returns {(sync: import("./sync-api-client-types.js").SyncChangeEnvelope) => Promise<import("./sync-api-client-types.js").SyncChangeApplyResult>} Loud remote-change applier.
319
+ */
320
+ remoteApplySync({source = "pulled change"} = {}) {
321
+ const pullResourceConfigs = this.pullResourceConfigs()
322
+ const applier = SyncApiClient.resourceApplier(pullResourceConfigs, (record) => {
323
+ this._remoteApplyRecords.add(record)
324
+
325
+ return () => this._remoteApplyRecords.delete(record)
326
+ })
327
+
328
+ return async (sync) => {
329
+ const resourceType = sync.resourceType()
330
+
331
+ if (!resourceType || !pullResourceConfigs[resourceType]) {
332
+ throw new Error(`No sync resource with pull attributes configured for ${source}: ${String(resourceType)}`)
333
+ }
334
+
335
+ return await applier(sync)
336
+ }
337
+ }
338
+
339
+ /**
340
+ * Subscribes the derived realtime channels so pushed websocket changes apply
341
+ * through the same derived applier as pulls (idempotent, single-flighted).
342
+ * @param {?} [context] - App context passed to the `sync.client.realtime.channels` callback (runtime values like eventId).
343
+ * @returns {Promise<void>}
344
+ */
345
+ async subscribeRealtime(context) {
346
+ await this.realtimeBridge().subscribe(context)
347
+ }
348
+
349
+ /**
350
+ * Unsubscribes the realtime channels and disconnects the websocket client (idempotent).
351
+ * @returns {Promise<void>}
352
+ */
353
+ async unsubscribeRealtime() {
354
+ await this.realtimeBridge().unsubscribe()
355
+ }
356
+
357
+ /**
358
+ * Reports the realtime subscription state and per-channel readiness.
359
+ * @returns {ReturnType<SyncRealtimeBridge["status"]>} Realtime status.
360
+ */
361
+ realtimeStatus() {
362
+ return this.realtimeBridge().status()
363
+ }
364
+
365
+ /**
366
+ * Awaits all pending realtime message applies and any scheduled
367
+ * pull-on-reconnect (useful in tests and shutdown flows).
368
+ * @returns {Promise<void>}
369
+ */
370
+ async waitForRealtimeApplied() {
371
+ await this.realtimeBridge().waitForApplied()
372
+ }
373
+
374
+ /**
375
+ * Returns the lazily built realtime bridge.
376
+ * @returns {SyncRealtimeBridge} Realtime bridge.
377
+ */
378
+ realtimeBridge() {
379
+ this._realtimeBridge ||= new SyncRealtimeBridge({syncClient: this})
380
+
381
+ return this._realtimeBridge
382
+ }
383
+
327
384
  /**
328
385
  * Queues a local model change as a pending sync row and schedules an immediate
329
386
  * replay attempt (kept pending while offline or when the backend rejects it).
@@ -491,11 +548,11 @@ function resourceConfigFromSyncDeclaration({declaration, modelClass, resourceTyp
491
548
  throw new Error(`${resourceType} static sync must be true or a sync declaration object, got: ${String(declaration)}`)
492
549
  }
493
550
 
494
- const {afterApply, attributes, booleanAttributes, findRecord, findRecordForDelete, localOnlyAttributes, syncType, track, trackedData, ...restDeclaration} = normalizedDeclaration
551
+ const {afterApply, attributes, booleanAttributes, findRecord, findRecordForDelete, localOnlyAttributes, realtime, syncType, track, trackedData, ...restDeclaration} = normalizedDeclaration
495
552
  const unknownKeys = Object.keys(restDeclaration)
496
553
 
497
554
  if (unknownKeys.length > 0) {
498
- throw new Error(`${resourceType} static sync received unknown keys: ${unknownKeys.join(", ")} (supported: afterApply, attributes, booleanAttributes, findRecord, findRecordForDelete, localOnlyAttributes, syncType, track, trackedData)`)
555
+ throw new Error(`${resourceType} static sync received unknown keys: ${unknownKeys.join(", ")} (supported: afterApply, attributes, booleanAttributes, findRecord, findRecordForDelete, localOnlyAttributes, realtime, syncType, track, trackedData)`)
499
556
  }
500
557
  if (syncType !== undefined && typeof syncType !== "function" && syncType !== "upsert") {
501
558
  throw new Error(`${resourceType} static sync syncType must be a function or the string "upsert", got: ${String(syncType)}`)
@@ -511,6 +568,7 @@ function resourceConfigFromSyncDeclaration({declaration, modelClass, resourceTyp
511
568
  findRecordForDelete,
512
569
  localOnlyAttributes: mergedAttributeNames(derived.localOnlyAttributes, localOnlyAttributes),
513
570
  modelClass,
571
+ realtime,
514
572
  syncType,
515
573
  track: normalizedTrack(track),
516
574
  trackedData
@@ -0,0 +1,299 @@
1
+ // @ts-check
2
+
3
+ import SyncApiClient from "./sync-api-client.js"
4
+
5
+ /** @typedef {import("../configuration-types.js").VelociousSyncRealtimeChannelDescriptor} VelociousSyncRealtimeChannelDescriptor */
6
+ /** @typedef {import("../configuration-types.js").VelociousSyncRealtimeWebsocketClient} VelociousSyncRealtimeWebsocketClient */
7
+
8
+ /**
9
+ * Derived realtime push bridge for the sync client. Subscribes the declared
10
+ * websocket channels (config `sync.client.realtime.channels` callback plus
11
+ * model-level `static sync = {realtime: {channel}}` declarations), applies
12
+ * pushed changes through the same derived resource applier as pulls (with echo
13
+ * suppression against tracked re-queueing), drops own-device messages by echo
14
+ * origin, and fires a coalesced `pull()` when subscriptions become ready or
15
+ * resume so offline gaps close.
16
+ */
17
+ export default class SyncRealtimeBridge {
18
+ /**
19
+ * Builds the bridge for a sync client.
20
+ * @param {{syncClient: import("./sync-client.js").default}} args - Bridge args.
21
+ */
22
+ constructor({syncClient}) {
23
+ this.syncClient = syncClient
24
+ /** @type {Array<{channel: string, resourceType: string | null, subscription: import("../configuration-types.js").VelociousSyncRealtimeSubscription}>} */
25
+ this._channels = []
26
+ /** @type {VelociousSyncRealtimeWebsocketClient | null} */
27
+ this._client = null
28
+ /** @type {Promise<void>} */
29
+ this._applyPromise = Promise.resolve()
30
+ /** @type {number} Subscription generation - bumped by unsubscribe so in-flight subscribes detect they became stale. */
31
+ this._generation = 0
32
+ /** @type {Promise<void> | null} */
33
+ this._scheduledPull = null
34
+ /** @type {Promise<void> | null} */
35
+ this._subscribePromise = null
36
+ /** @type {"subscribed" | "subscribing" | "unsubscribed"} */
37
+ this._state = "unsubscribed"
38
+ }
39
+
40
+ /**
41
+ * Subscribes the derived realtime channels (idempotent and single-flighted):
42
+ * an active subscription is kept as-is and a concurrent subscribe awaits the
43
+ * in-flight attempt. Call `unsubscribe()` first to change the context.
44
+ * @param {?} [context] - App context passed to the `sync.client.realtime.channels` callback (runtime values like eventId).
45
+ * @returns {Promise<void>}
46
+ */
47
+ async subscribe(context) {
48
+ if (this._state === "subscribed") return
49
+
50
+ if (!this._subscribePromise) {
51
+ this._subscribePromise = this._subscribe(context).finally(() => {
52
+ this._subscribePromise = null
53
+ })
54
+ }
55
+
56
+ await this._subscribePromise
57
+ }
58
+
59
+ /**
60
+ * Connects the websocket client, subscribes every derived channel, and waits
61
+ * for each subscription's server acknowledgement before the gap-closing pull,
62
+ * so no change can land between the pull and the subscriptions going live.
63
+ * Locally created resources are only promoted to the bridge once everything
64
+ * is live; an unsubscribe arriving during any await marks this attempt stale
65
+ * and it tears its own resources down instead of resubscribing.
66
+ * @param {?} context - App context passed to the channels callback.
67
+ * @returns {Promise<void>}
68
+ */
69
+ async _subscribe(context) {
70
+ const generation = this._generation
71
+
72
+ this._state = "subscribing"
73
+
74
+ /** @type {Array<{channel: string, resourceType: string | null, subscription: import("../configuration-types.js").VelociousSyncRealtimeSubscription}>} */
75
+ const channels = []
76
+ /** @type {VelociousSyncRealtimeWebsocketClient | null} */
77
+ let client = null
78
+ /**
79
+ * Tears down everything this stale/failed subscribe attempt created itself.
80
+ * @returns {Promise<void>}
81
+ */
82
+ const teardown = async () => {
83
+ for (const {subscription} of channels) {
84
+ subscription.close()
85
+ }
86
+
87
+ if (client) await client.disconnectAndStopReconnect()
88
+ }
89
+
90
+ try {
91
+ const realtime = this.realtimeConfiguration()
92
+ const channelDescriptors = await this.channelDescriptors(context)
93
+
94
+ if (generation !== this._generation) return
95
+
96
+ client = await realtime.createClient()
97
+
98
+ if (generation !== this._generation) return
99
+
100
+ await client.connect()
101
+
102
+ if (generation !== this._generation) {
103
+ await teardown()
104
+ return
105
+ }
106
+
107
+ const authenticationToken = await this.syncClient.config.authenticationToken()
108
+
109
+ if (generation !== this._generation) {
110
+ await teardown()
111
+ return
112
+ }
113
+
114
+ for (const channelDescriptor of channelDescriptors) {
115
+ if (channelDescriptor.params && "authenticationToken" in channelDescriptor.params) {
116
+ throw new Error(`Realtime channel "${channelDescriptor.channel}" params must not include authenticationToken - the framework injects the sync.client authenticationToken automatically`)
117
+ }
118
+
119
+ const resourceType = channelDescriptor.resourceType ?? null
120
+ const subscription = client.subscribeChannel(channelDescriptor.channel, {
121
+ onMessage: (body) => this.enqueueApply({body, resourceType}),
122
+ onResume: () => this.schedulePull(),
123
+ params: {...channelDescriptor.params, authenticationToken}
124
+ })
125
+
126
+ channels.push({channel: channelDescriptor.channel, resourceType, subscription})
127
+ }
128
+
129
+ await Promise.all(channels.map(({subscription}) => subscription.waitForReady()))
130
+
131
+ if (generation !== this._generation) {
132
+ await teardown()
133
+ return
134
+ }
135
+
136
+ this._channels = channels
137
+ this._client = client
138
+ this._state = "subscribed"
139
+ this.schedulePull()
140
+ } catch (error) {
141
+ await teardown()
142
+
143
+ if (generation === this._generation) this._state = "unsubscribed"
144
+
145
+ throw error
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Closes every channel subscription and disconnects the websocket client
151
+ * (idempotent). Also marks any in-flight subscribe attempt stale so it tears
152
+ * itself down instead of finishing the subscription afterwards.
153
+ * @returns {Promise<void>}
154
+ */
155
+ async unsubscribe() {
156
+ this._generation += 1
157
+
158
+ const channels = this._channels
159
+ const client = this._client
160
+
161
+ this._channels = []
162
+ this._client = null
163
+ this._state = "unsubscribed"
164
+
165
+ for (const {subscription} of channels) {
166
+ subscription.close()
167
+ }
168
+
169
+ if (client) await client.disconnectAndStopReconnect()
170
+ }
171
+
172
+ /**
173
+ * Reports the bridge subscription state and per-channel readiness.
174
+ * @returns {{channels: Array<{channel: string, ready: boolean, resourceType: string | null}>, state: "subscribed" | "subscribing" | "unsubscribed"}} Realtime status.
175
+ */
176
+ status() {
177
+ return {
178
+ channels: this._channels.map(({channel, resourceType, subscription}) => ({channel, ready: subscription.isReady(), resourceType})),
179
+ state: this._state
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Awaits all enqueued message applies and any scheduled pull (tests, shutdown flows).
185
+ * @returns {Promise<void>}
186
+ */
187
+ async waitForApplied() {
188
+ await this._applyPromise
189
+ if (this._scheduledPull) await this._scheduledPull
190
+ }
191
+
192
+ /**
193
+ * Resolves the realtime configuration, failing loudly when it is missing.
194
+ * @returns {import("../configuration-types.js").VelociousSyncClientRealtimeConfiguration} Realtime configuration.
195
+ */
196
+ realtimeConfiguration() {
197
+ const realtime = this.syncClient.config.realtime
198
+
199
+ if (!realtime) {
200
+ throw new Error("subscribeRealtime requires a sync.client.realtime configuration block with a createClient callback")
201
+ }
202
+
203
+ return realtime
204
+ }
205
+
206
+ /**
207
+ * Derives the channel descriptors to subscribe: model-level static realtime
208
+ * declarations plus the config channels callback, failing loudly when none exist.
209
+ * @param {?} context - App context passed to the channels callback.
210
+ * @returns {Promise<Array<VelociousSyncRealtimeChannelDescriptor>>} Channel descriptors.
211
+ */
212
+ async channelDescriptors(context) {
213
+ const realtime = this.realtimeConfiguration()
214
+ /** @type {Array<VelociousSyncRealtimeChannelDescriptor>} */
215
+ const channelDescriptors = []
216
+
217
+ for (const [resourceType, resourceConfig] of Object.entries(this.syncClient.config.resources)) {
218
+ if (!resourceConfig.realtime) continue
219
+
220
+ channelDescriptors.push({channel: resourceConfig.realtime.channel, params: resourceConfig.realtime.params, resourceType})
221
+ }
222
+
223
+ if (realtime.channels) {
224
+ channelDescriptors.push(...await realtime.channels(context))
225
+ }
226
+
227
+ if (channelDescriptors.length === 0) {
228
+ throw new Error("subscribeRealtime found no realtime channels - declare sync.client.realtime.channels or static sync = {realtime: {channel}} on a model")
229
+ }
230
+
231
+ return channelDescriptors
232
+ }
233
+
234
+ /**
235
+ * Chains one pushed message onto the serialized apply queue so changes apply
236
+ * in arrival order; failures go to the sync client's error reporting.
237
+ * @param {{body: ?, resourceType: string | null}} args - Message args.
238
+ * @returns {void}
239
+ */
240
+ enqueueApply({body, resourceType}) {
241
+ this._applyPromise = this._applyPromise.then(async () => {
242
+ try {
243
+ await this.applyMessage({body, resourceType})
244
+ } catch (error) {
245
+ this.syncClient.reportError(/** @type {Error} */ (error))
246
+ }
247
+ })
248
+ }
249
+
250
+ /**
251
+ * Applies one pushed message through the derived resource applier: drops
252
+ * own-device messages by echo origin, defaults the channel's resourceType onto
253
+ * envelopes without one, and fails loudly on unknown resource types.
254
+ * @param {{body: ?, resourceType: string | null}} args - Message args.
255
+ * @returns {Promise<void>}
256
+ */
257
+ async applyMessage({body, resourceType}) {
258
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
259
+ throw new Error(`Realtime sync messages must be envelope objects, got: ${JSON.stringify(body)}`)
260
+ }
261
+
262
+ const realtime = this.realtimeConfiguration()
263
+
264
+ if (realtime.localOrigin && body.echoOrigin !== undefined && body.echoOrigin !== null) {
265
+ const localOrigin = String(await realtime.localOrigin())
266
+
267
+ if (String(body.echoOrigin) === localOrigin) return
268
+ }
269
+
270
+ const syncPayloads = Array.isArray(body.syncs) ? body.syncs : [body]
271
+ const applySync = this.syncClient.remoteApplySync({source: "remote change"})
272
+
273
+ for (const syncPayload of syncPayloads) {
274
+ const sync = SyncApiClient.syncEnvelopeFromPayload({resourceType, ...syncPayload})
275
+
276
+ await applySync(sync)
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Schedules a coalesced background pull closing offline gaps after
282
+ * (re)subscription readiness. Resumes arriving while a pull is already
283
+ * scheduled or in flight coalesce into that pull instead of stacking.
284
+ * @returns {void}
285
+ */
286
+ schedulePull() {
287
+ if (this.realtimeConfiguration().pullOnReconnect === false) return
288
+
289
+ this._scheduledPull ||= (async () => {
290
+ try {
291
+ await this.syncClient.pull()
292
+ } catch (error) {
293
+ this.syncClient.reportError(/** @type {Error} */ (error))
294
+ } finally {
295
+ this._scheduledPull = null
296
+ }
297
+ })()
298
+ }
299
+ }