@party-stack/runtime 0.4.0 → 0.4.2

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 (57) hide show
  1. package/lib/coordinator/createPersistedCollectionCoordinator.d.ts +4 -2
  2. package/lib/coordinator/createPersistedCollectionCoordinator.d.ts.map +1 -1
  3. package/lib/coordinator/createPersistedCollectionCoordinator.js +506 -555
  4. package/lib/coordinator/createPersistedCollectionCoordinator.js.map +1 -1
  5. package/lib/coordinator/index.d.ts +2 -2
  6. package/lib/coordinator/index.js +0 -1
  7. package/lib/effection/index.d.ts +4 -2
  8. package/lib/effection/index.d.ts.map +1 -1
  9. package/lib/effection/index.js +25 -25
  10. package/lib/effection/index.js.map +1 -1
  11. package/lib/index.d.ts +11 -11
  12. package/lib/index.js +10 -9
  13. package/lib/memory/MemoryBlobBytesStore.d.ts +8 -6
  14. package/lib/memory/MemoryBlobBytesStore.d.ts.map +1 -1
  15. package/lib/memory/MemoryBlobBytesStore.js +22 -20
  16. package/lib/memory/MemoryBlobBytesStore.js.map +1 -1
  17. package/lib/types.d.ts +31 -29
  18. package/lib/types.d.ts.map +1 -1
  19. package/lib/types.js +0 -1
  20. package/lib/utils/BrowserAuthenticationCancelledError.d.ts +3 -1
  21. package/lib/utils/BrowserAuthenticationCancelledError.d.ts.map +1 -1
  22. package/lib/utils/BrowserAuthenticationCancelledError.js +10 -6
  23. package/lib/utils/BrowserAuthenticationCancelledError.js.map +1 -1
  24. package/lib/utils/createCollectionPersistence.d.ts +4 -2
  25. package/lib/utils/createCollectionPersistence.d.ts.map +1 -1
  26. package/lib/utils/createCollectionPersistence.js +20 -16
  27. package/lib/utils/createCollectionPersistence.js.map +1 -1
  28. package/lib/utils/createDefaultRuntime.d.ts +4 -1
  29. package/lib/utils/createDefaultRuntime.d.ts.map +1 -1
  30. package/lib/utils/createDefaultRuntime.js +15 -11
  31. package/lib/utils/createDefaultRuntime.js.map +1 -1
  32. package/lib/utils/createLocalCollection.d.ts +8 -6
  33. package/lib/utils/createLocalCollection.d.ts.map +1 -1
  34. package/lib/utils/createLocalCollection.js +19 -15
  35. package/lib/utils/createLocalCollection.js.map +1 -1
  36. package/lib/utils/defineRuntime.d.ts +3 -1
  37. package/lib/utils/defineRuntime.d.ts.map +1 -1
  38. package/lib/utils/defineRuntime.js +26 -30
  39. package/lib/utils/defineRuntime.js.map +1 -1
  40. package/package.json +12 -18
  41. package/lib/coordinator/index.d.ts.map +0 -1
  42. package/lib/coordinator/index.js.map +0 -1
  43. package/lib/index.d.ts.map +0 -1
  44. package/lib/index.js.map +0 -1
  45. package/lib/memory/MemoryBlobBytesStore.test.d.ts +0 -2
  46. package/lib/memory/MemoryBlobBytesStore.test.d.ts.map +0 -1
  47. package/lib/memory/MemoryBlobBytesStore.test.js +0 -12
  48. package/lib/memory/MemoryBlobBytesStore.test.js.map +0 -1
  49. package/lib/types.js.map +0 -1
  50. package/lib/utils/createLocalCollection.test.d.ts +0 -2
  51. package/lib/utils/createLocalCollection.test.d.ts.map +0 -1
  52. package/lib/utils/createLocalCollection.test.js +0 -748
  53. package/lib/utils/createLocalCollection.test.js.map +0 -1
  54. package/lib/utils/defineRuntime.test.d.ts +0 -2
  55. package/lib/utils/defineRuntime.test.d.ts.map +0 -1
  56. package/lib/utils/defineRuntime.test.js +0 -40
  57. package/lib/utils/defineRuntime.test.js.map +0 -1
@@ -1,563 +1,514 @@
1
- import { isCoordinationHost, } from "@party-stack/coordination";
2
- import { safeRandomUUID, SingleProcessCoordinator, toTransportedLoadSubsetOptions, toPersistedCollectionDurabilityError, } from "@tanstack/db-sqlite-persistence-core";
1
+ import { isCoordinationHost } from "@party-stack/coordination";
2
+ import { SingleProcessCoordinator, eagerStorageTarget, managedStorageTarget, safeRandomUUID, toPersistedCollectionDurabilityError, toTransportedLoadSubsetOptions } from "@tanstack/db-sqlite-persistence-core";
3
+ //#region src/coordinator/createPersistedCollectionCoordinator.ts
3
4
  const PERSISTENCE_SERVICE = "party-stack.persistence.v1";
4
- const MAX_DEDUPLICATION_ENTRIES = 1_000;
5
- const MAX_PENDING_RELAYS = 1_000;
5
+ const MAX_DEDUPLICATION_ENTRIES = 1e3;
6
+ const MAX_PENDING_RELAYS = 1e3;
6
7
  const MAX_COLLECTION_POSITIONS = 128;
7
- const coordinatorCache = new WeakMap();
8
+ const coordinatorCache = /* @__PURE__ */ new WeakMap();
8
9
  function isRecord(value) {
9
- return typeof value === "object" && value !== null;
10
+ return typeof value === "object" && value !== null;
10
11
  }
11
12
  function relayKey(collectionId, message) {
12
- const payload = isRecord(message.payload) ? message.payload : {};
13
- return JSON.stringify([
14
- collectionId,
15
- message.senderId,
16
- payload.type,
17
- payload.txId,
18
- payload.resetEpoch,
19
- payload.term,
20
- payload.seq,
21
- ]);
13
+ const payload = isRecord(message.payload) ? message.payload : {};
14
+ return JSON.stringify([
15
+ collectionId,
16
+ message.senderId,
17
+ payload.type,
18
+ payload.txId,
19
+ payload.resetEpoch,
20
+ payload.term,
21
+ payload.seq
22
+ ]);
22
23
  }
23
- export function createPersistedCollectionCoordinator(coordination, adapter) {
24
- let adapters = coordinatorCache.get(coordination);
25
- if (!adapters) {
26
- adapters = new WeakMap();
27
- coordinatorCache.set(coordination, adapters);
28
- }
29
- const existing = adapters.get(adapter);
30
- if (existing)
31
- return existing;
32
- const created = new CoordinationPersistenceShim(coordination, adapter);
33
- adapters.set(adapter, created);
34
- return created;
35
- }
36
- class CoordinationPersistenceShim {
37
- coordination;
38
- adapter;
39
- nodeId = safeRandomUUID();
40
- collectionAdapters = new Map();
41
- collectionSubscriptions = new Map();
42
- resumeChecks = new Map();
43
- localMutationBursts = new Map();
44
- stopResumeListeners;
45
- checkingResume = false;
46
- resumeRequested = false;
47
- requestResumeCheck = () => {
48
- this.resumeRequested = true;
49
- if (this.checkingResume)
50
- return;
51
- this.checkingResume = true;
52
- void (async () => {
53
- try {
54
- while (this.resumeRequested && this.resumeChecks.size > 0) {
55
- this.resumeRequested = false;
56
- await Promise.all([...this.resumeChecks.values()].flatMap((checks) => [...checks].map((check) => check())));
57
- }
58
- }
59
- finally {
60
- this.checkingResume = false;
61
- this.resumeRequested = false;
62
- }
63
- })();
64
- };
65
- startResumeListeners() {
66
- if (this.stopResumeListeners || typeof window === "undefined" || typeof document === "undefined")
67
- return;
68
- const page = window;
69
- const visibility = document;
70
- const onVisible = () => {
71
- if (visibility.visibilityState === "visible")
72
- this.requestResumeCheck();
73
- };
74
- page.addEventListener("pageshow", this.requestResumeCheck);
75
- page.addEventListener("focus", onVisible);
76
- visibility.addEventListener("visibilitychange", onVisible);
77
- this.stopResumeListeners = () => {
78
- page.removeEventListener("pageshow", this.requestResumeCheck);
79
- page.removeEventListener("focus", onVisible);
80
- visibility.removeEventListener("visibilitychange", onVisible);
81
- };
82
- }
83
- setAdapterForCollection(collectionId, adapter) {
84
- this.collectionAdapters.set(collectionId, adapter);
85
- this.positions.delete(collectionId);
86
- }
87
- adapterForCollection(collectionId, schemaVersion) {
88
- const adapter = this.collectionAdapters.get(collectionId) ?? this.adapter;
89
- if (schemaVersion !== undefined && this.schemaVersion(adapter) !== schemaVersion) {
90
- throw new Error(`Persistence schema mismatch for collection "${collectionId}". Reload the coordination host before writing through another schema version.`);
91
- }
92
- return adapter;
93
- }
94
- schemaVersion(adapter) {
95
- return "schemaVersion" in adapter && typeof adapter.schemaVersion === "number"
96
- ? adapter.schemaVersion
97
- : undefined;
98
- }
99
- positions = new Map();
100
- appliedEnvelopes = new Map();
101
- relayedMessages = new Set();
102
- service;
103
- server;
104
- pendingRelays = 0;
105
- remoteSubsets = new SingleProcessCoordinator();
106
- acquisitionIds = new WeakMap();
107
- remoteAcquisitions = new Map();
108
- constructor(coordination, adapter) {
109
- this.coordination = coordination;
110
- this.adapter = adapter;
111
- this.service = coordination.service(PERSISTENCE_SERVICE);
112
- this.server = isCoordinationHost(coordination)
113
- ? coordination.serve(PERSISTENCE_SERVICE, {
114
- ensureLeadership: () => Promise.resolve(),
115
- ensureRemoteSubset: async (input) => {
116
- let options = this.remoteAcquisitions.get(input.acquisitionId)?.options;
117
- if (!options) {
118
- options = input.options;
119
- this.remoteAcquisitions.set(input.acquisitionId, {
120
- collectionId: input.collectionId,
121
- options,
122
- });
123
- }
124
- try {
125
- await this.remoteSubsets.requestEnsureRemoteSubset(input.collectionId, options);
126
- }
127
- catch (error) {
128
- // Owner invocation transfers a lease even if loading fails.
129
- // Release it before dropping our strong reference to its options.
130
- if (this.remoteAcquisitions.get(input.acquisitionId)?.options === options) {
131
- this.remoteAcquisitions.delete(input.acquisitionId);
132
- await this.remoteSubsets.requestReleaseRemoteSubset(input.collectionId, options)
133
- .catch(() => undefined);
134
- }
135
- throw error;
136
- }
137
- },
138
- releaseRemoteSubset: (input) => {
139
- const options = this.remoteAcquisitions.get(input.acquisitionId)?.options;
140
- this.remoteAcquisitions.delete(input.acquisitionId);
141
- return options
142
- ? this.remoteSubsets.requestReleaseRemoteSubset(input.collectionId, options)
143
- : Promise.resolve();
144
- },
145
- applyCommittedTx: (input) => this.applyCommittedTx(input),
146
- ensurePersistedIndex: (input) => this.adapterForCollection(input.collectionId, input.schemaVersion).ensureIndex(input.collectionId, input.signature, input.spec),
147
- applyLocalMutations: (input) => this.applyMutations(input),
148
- pullSince: (input) => this.handlePullSince(input),
149
- relayMessage: (input) => this.relayMessage(input),
150
- })
151
- : undefined;
152
- }
153
- getNodeId() {
154
- return this.nodeId;
155
- }
156
- subscribe(collectionId, callback) {
157
- let active = true;
158
- let observed;
159
- const unsubscribe = this.service.events.subscribe("message", (event) => {
160
- if (!active)
161
- return;
162
- if (event.collectionId === collectionId) {
163
- const payload = event.message.payload;
164
- const burst = this.localMutationBursts.get(collectionId);
165
- if (burst && isRecord(payload) && payload.type === "tx:committed" &&
166
- typeof payload.txId === "string" && !burst.pending.has(payload.txId)) {
167
- burst.needsReload = true;
168
- }
169
- if (isRecord(payload) && payload.type === "tx:committed" &&
170
- typeof payload.term === "number" && typeof payload.seq === "number" &&
171
- typeof payload.latestRowVersion === "number" &&
172
- (!observed || payload.term > observed.latestTerm ||
173
- (payload.term === observed.latestTerm && payload.seq > observed.latestSeq))) {
174
- observed = { latestTerm: payload.term, latestSeq: payload.seq, latestRowVersion: payload.latestRowVersion };
175
- }
176
- callback(event.message);
177
- }
178
- });
179
- const checkResume = async (force = false) => {
180
- try {
181
- if (!active)
182
- return;
183
- const adapter = this.adapterForCollection(collectionId);
184
- const current = await adapter.getStreamPosition?.(collectionId);
185
- if (!active)
186
- return;
187
- if (!force && current && observed && current.latestTerm === observed.latestTerm &&
188
- current.latestSeq === observed.latestSeq && current.latestRowVersion === observed.latestRowVersion)
189
- return;
190
- // A local reset notification makes upstream reload active subsets atomically.
191
- // No storage reset or broadcast is performed. Before our first notification,
192
- // the hydration position is unknown, so a resume conservatively reloads once.
193
- callback({
194
- v: 1, dbName: this.coordinationScope(), collectionId,
195
- senderId: `resume:${this.nodeId}`, ts: Date.now(),
196
- payload: { type: "collection:reset", schemaVersion: this.schemaVersion(adapter) ?? 1, resetEpoch: 0 },
197
- });
198
- observed = current;
199
- }
200
- catch (error) {
201
- if (active)
202
- console.warn(`Failed to refresh resumed collection "${collectionId}".`, error);
203
- }
204
- };
205
- const checks = this.resumeChecks.get(collectionId) ?? new Set();
206
- checks.add(checkResume);
207
- this.resumeChecks.set(collectionId, checks);
208
- this.startResumeListeners();
209
- this.collectionSubscriptions.set(collectionId, (this.collectionSubscriptions.get(collectionId) ?? 0) + 1);
210
- return () => {
211
- if (!active)
212
- return;
213
- active = false;
214
- checks.delete(checkResume);
215
- if (checks.size === 0) {
216
- this.resumeChecks.delete(collectionId);
217
- const burst = this.localMutationBursts.get(collectionId);
218
- if (burst?.timer !== undefined)
219
- clearTimeout(burst.timer);
220
- this.localMutationBursts.delete(collectionId);
221
- }
222
- if (this.resumeChecks.size === 0) {
223
- this.stopResumeListeners?.();
224
- this.stopResumeListeners = undefined;
225
- }
226
- try {
227
- unsubscribe();
228
- }
229
- finally {
230
- const remaining = this.collectionSubscriptions.get(collectionId) - 1;
231
- if (remaining > 0) {
232
- this.collectionSubscriptions.set(collectionId, remaining);
233
- }
234
- else {
235
- this.collectionSubscriptions.delete(collectionId);
236
- this.collectionAdapters.delete(collectionId);
237
- this.positions.delete(collectionId);
238
- }
239
- }
240
- };
241
- }
242
- publish(collectionId, message) {
243
- if (this.server && isCoordinationHost(this.coordination) && this.coordination.isLeader) {
244
- this.publishMessage({
245
- collectionId,
246
- message,
247
- });
248
- return;
249
- }
250
- if (this.pendingRelays >= MAX_PENDING_RELAYS) {
251
- console.warn(`Dropping persistence relay for "${collectionId}" because the pending relay limit was reached.`);
252
- return;
253
- }
254
- this.pendingRelays += 1;
255
- void this.service.methods
256
- .relayMessage({
257
- collectionId,
258
- message,
259
- })
260
- .catch((error) => {
261
- console.warn(`Failed to relay persistence message for "${collectionId}".`, error);
262
- })
263
- .finally(() => {
264
- this.pendingRelays -= 1;
265
- });
266
- }
267
- isLeader() {
268
- return isCoordinationHost(this.coordination) && this.coordination.isLeader;
269
- }
270
- ensureLeadership() {
271
- return this.service.methods.ensureLeadership({
272
- collectionId: "*",
273
- });
274
- }
275
- requestEnsureRemoteSubset(collectionId, options) {
276
- let collectionIds = this.acquisitionIds.get(options);
277
- if (!collectionIds) {
278
- collectionIds = new Map();
279
- this.acquisitionIds.set(options, collectionIds);
280
- }
281
- let acquisitionId = collectionIds.get(collectionId);
282
- if (!acquisitionId) {
283
- acquisitionId = safeRandomUUID();
284
- collectionIds.set(collectionId, acquisitionId);
285
- }
286
- return this.service.methods.ensureRemoteSubset({
287
- collectionId,
288
- options: toTransportedLoadSubsetOptions(options),
289
- acquisitionId,
290
- });
291
- }
292
- requestReleaseRemoteSubset(collectionId, options) {
293
- const collectionIds = this.acquisitionIds.get(options);
294
- const acquisitionId = collectionIds?.get(collectionId);
295
- if (!acquisitionId)
296
- return Promise.resolve();
297
- collectionIds.delete(collectionId);
298
- if (collectionIds.size === 0)
299
- this.acquisitionIds.delete(options);
300
- return this.service.methods.releaseRemoteSubset({ collectionId, options: {}, acquisitionId });
301
- }
302
- registerRemoteSubsetOwner(collectionId, owner) {
303
- const unregister = this.remoteSubsets.registerRemoteSubsetOwner(collectionId, owner);
304
- let registered = true;
305
- return () => {
306
- if (!registered)
307
- return;
308
- registered = false;
309
- unregister();
310
- for (const [id, acquisition] of this.remoteAcquisitions) {
311
- if (acquisition.collectionId === collectionId)
312
- this.remoteAcquisitions.delete(id);
313
- }
314
- };
315
- }
316
- requestApplyCommittedTx(collectionId, tx, scopedAdapter) {
317
- return this.isLeader()
318
- ? this.applyCommittedTx({ collectionId, tx }, scopedAdapter)
319
- : this.service.methods.applyCommittedTx({
320
- collectionId,
321
- tx,
322
- schemaVersion: this.schemaVersion(scopedAdapter ?? this.adapterForCollection(collectionId)) ??
323
- this.schemaVersion(this.adapterForCollection(collectionId)),
324
- });
325
- }
326
- async applyCommittedTx({ collectionId, tx, schemaVersion }, scopedAdapter) {
327
- try {
328
- await (scopedAdapter ?? this.adapterForCollection(collectionId, schemaVersion)).applyCommittedTx(collectionId, tx);
329
- }
330
- catch (error) {
331
- throw toPersistedCollectionDurabilityError(collectionId, error);
332
- }
333
- this.positions.delete(collectionId);
334
- return {
335
- type: "rpc:applyCommittedTx:res",
336
- rpcId: safeRandomUUID(),
337
- ok: true,
338
- term: tx.term,
339
- seq: tx.seq,
340
- latestRowVersion: tx.rowVersion,
341
- };
342
- }
343
- requestEnsurePersistedIndex(collectionId, signature, spec, scopedAdapter, localEnsureCompleted) {
344
- if (this.isLeader()) {
345
- return localEnsureCompleted
346
- ? Promise.resolve()
347
- : (scopedAdapter ?? this.adapterForCollection(collectionId)).ensureIndex(collectionId, signature, spec);
348
- }
349
- return this.service.methods.ensurePersistedIndex({
350
- collectionId,
351
- signature,
352
- spec,
353
- schemaVersion: this.schemaVersion(scopedAdapter ?? this.adapterForCollection(collectionId)) ??
354
- this.schemaVersion(this.adapterForCollection(collectionId)),
355
- });
356
- }
357
- async requestApplyLocalMutations(collectionId, mutations) {
358
- const envelopeId = safeRandomUUID();
359
- const burst = this.resumeChecks.has(collectionId)
360
- ? this.localMutationBursts.get(collectionId) ?? { pending: new Set(), needsReload: false, timer: undefined }
361
- : undefined;
362
- if (burst) {
363
- if (burst.timer !== undefined)
364
- clearTimeout(burst.timer);
365
- if (burst.pending.size > 0)
366
- burst.needsReload = true;
367
- burst.pending.add(envelopeId);
368
- this.localMutationBursts.set(collectionId, burst);
369
- }
370
- try {
371
- return await this.service.methods.applyLocalMutations({
372
- collectionId,
373
- rpcId: safeRandomUUID(),
374
- envelopeId,
375
- schemaVersion: this.schemaVersion(this.adapterForCollection(collectionId)),
376
- mutations,
377
- });
378
- }
379
- finally {
380
- burst?.pending.delete(envelopeId);
381
- if (burst && burst.pending.size === 0 && this.localMutationBursts.get(collectionId) === burst) {
382
- // Upstream advances its observed sequence from local RPC acknowledgements
383
- // before queued commit messages can run. Reconcile overlapping foreign
384
- // commits after the local mutation burst, without changing RPC positions.
385
- burst.timer = setTimeout(() => {
386
- if (this.localMutationBursts.get(collectionId) !== burst)
387
- return;
388
- this.localMutationBursts.delete(collectionId);
389
- if (burst.needsReload) {
390
- for (const check of this.resumeChecks.get(collectionId) ?? [])
391
- void check(true);
392
- }
393
- }, 0);
394
- }
395
- }
396
- }
397
- pullSince(collectionId, fromRowVersion) {
398
- return this.service.methods.pullSince({
399
- collectionId,
400
- rpcId: safeRandomUUID(),
401
- fromRowVersion,
402
- schemaVersion: this.schemaVersion(this.adapterForCollection(collectionId)),
403
- });
404
- }
405
- relayMessage(input) {
406
- const key = relayKey(input.collectionId, input.message);
407
- if (this.relayedMessages.has(key)) {
408
- return Promise.resolve();
409
- }
410
- this.relayedMessages.add(key);
411
- if (this.relayedMessages.size > MAX_DEDUPLICATION_ENTRIES) {
412
- const oldest = this.relayedMessages.values().next().value;
413
- if (oldest) {
414
- this.relayedMessages.delete(oldest);
415
- }
416
- }
417
- this.publishMessage(input);
418
- return Promise.resolve();
419
- }
420
- publishMessage(input) {
421
- this.server?.events.publish("message", input);
422
- }
423
- async position(collectionId) {
424
- let position = this.positions.get(collectionId);
425
- if (!position) {
426
- const adapter = this.adapterForCollection(collectionId);
427
- position = Promise.resolve(adapter.getStreamPosition
428
- ? adapter.getStreamPosition(collectionId)
429
- : adapter.loadResumeSnapshot(collectionId, { includeRows: false })).then((current) => ({
430
- term: (current?.latestTerm ?? 0) + 1,
431
- seq: current?.latestSeq ?? 0,
432
- rowVersion: current?.latestRowVersion ?? 0,
433
- }));
434
- }
435
- this.positions.delete(collectionId);
436
- this.positions.set(collectionId, position);
437
- while (this.positions.size > MAX_COLLECTION_POSITIONS) {
438
- const oldest = this.positions.keys().next().value;
439
- if (oldest !== undefined)
440
- this.positions.delete(oldest);
441
- }
442
- void position.catch(() => {
443
- if (this.positions.get(collectionId) === position)
444
- this.positions.delete(collectionId);
445
- });
446
- return position;
447
- }
448
- async applyMutations(input) {
449
- const adapter = this.adapterForCollection(input.collectionId, input.schemaVersion);
450
- const envelopeKey = JSON.stringify([input.collectionId, input.envelopeId]);
451
- const previous = this.appliedEnvelopes.get(envelopeKey);
452
- if (previous) {
453
- return {
454
- ...previous,
455
- rpcId: input.rpcId,
456
- };
457
- }
458
- const position = await this.position(input.collectionId);
459
- const nextPosition = { ...position, seq: position.seq + 1, rowVersion: position.rowVersion + 1 };
460
- const txId = input.envelopeId;
461
- await adapter.applyCommittedTx(input.collectionId, {
462
- txId,
463
- term: nextPosition.term,
464
- seq: nextPosition.seq,
465
- rowVersion: nextPosition.rowVersion,
466
- mutations: input.mutations.map(({ mutationId, ...mutation }) => {
467
- void mutationId;
468
- return mutation;
469
- }),
470
- });
471
- Object.assign(position, nextPosition);
472
- const committed = {
473
- v: 1,
474
- dbName: this.coordinationScope(),
475
- collectionId: input.collectionId,
476
- senderId: this.nodeId,
477
- ts: Date.now(),
478
- payload: {
479
- type: "tx:committed",
480
- term: position.term,
481
- seq: position.seq,
482
- txId,
483
- latestRowVersion: position.rowVersion,
484
- requiresFullReload: false,
485
- changedRows: input.mutations
486
- .filter((mutation) => mutation.type !== "delete")
487
- .map((mutation) => ({
488
- key: mutation.key,
489
- value: mutation.value,
490
- })),
491
- deletedKeys: input.mutations
492
- .filter((mutation) => mutation.type === "delete")
493
- .map((mutation) => mutation.key),
494
- rowMetadataMutations: input.mutations.flatMap((mutation) => mutation.type !== "delete" &&
495
- (mutation.metadataChanged || mutation.metadata !== undefined)
496
- ? [
497
- mutation.metadata === undefined
498
- ? { type: "delete", key: mutation.key }
499
- : { type: "set", key: mutation.key, value: mutation.metadata },
500
- ]
501
- : []),
502
- },
503
- };
504
- this.publishMessage({
505
- collectionId: input.collectionId,
506
- message: committed,
507
- });
508
- const response = {
509
- type: "rpc:applyLocalMutations:res",
510
- rpcId: input.rpcId,
511
- ok: true,
512
- term: position.term,
513
- seq: position.seq,
514
- latestRowVersion: position.rowVersion,
515
- acceptedMutationIds: input.mutations.map((mutation) => mutation.mutationId),
516
- };
517
- this.appliedEnvelopes.set(envelopeKey, response);
518
- if (this.appliedEnvelopes.size > MAX_DEDUPLICATION_ENTRIES) {
519
- const oldest = this.appliedEnvelopes.keys().next().value;
520
- if (oldest) {
521
- this.appliedEnvelopes.delete(oldest);
522
- }
523
- }
524
- return response;
525
- }
526
- async handlePullSince(input) {
527
- const adapter = this.adapterForCollection(input.collectionId, input.schemaVersion);
528
- const current = await adapter.getStreamPosition?.(input.collectionId);
529
- const position = current
530
- ? { term: current.latestTerm, seq: current.latestSeq, rowVersion: current.latestRowVersion }
531
- : await this.position(input.collectionId);
532
- const result = await adapter.pullSince?.(input.collectionId, input.fromRowVersion);
533
- if (!result || result.requiresFullReload) {
534
- return {
535
- type: "rpc:pullSince:res",
536
- rpcId: input.rpcId,
537
- ok: true,
538
- latestTerm: result?.latestTerm ?? position.term,
539
- latestSeq: result?.latestSeq ?? position.seq,
540
- latestRowVersion: result?.latestRowVersion ?? position.rowVersion,
541
- requiresFullReload: true,
542
- };
543
- }
544
- return {
545
- type: "rpc:pullSince:res",
546
- rpcId: input.rpcId,
547
- ok: true,
548
- latestTerm: result?.latestTerm ?? position.term,
549
- latestSeq: result?.latestSeq ?? position.seq,
550
- latestRowVersion: result.latestRowVersion,
551
- requiresFullReload: false,
552
- changedKeys: result.changedKeys,
553
- deletedKeys: result.deletedKeys,
554
- deltas: result.deltas,
555
- };
556
- }
557
- coordinationScope() {
558
- return "scope" in this.coordination && typeof this.coordination.scope === "string"
559
- ? this.coordination.scope
560
- : "party-stack";
561
- }
24
+ function createPersistedCollectionCoordinator(coordination, adapter) {
25
+ let adapters = coordinatorCache.get(coordination);
26
+ if (!adapters) {
27
+ adapters = /* @__PURE__ */ new WeakMap();
28
+ coordinatorCache.set(coordination, adapters);
29
+ }
30
+ const existing = adapters.get(adapter);
31
+ if (existing) return existing;
32
+ const created = new CoordinationPersistenceShim(coordination, adapter);
33
+ adapters.set(adapter, created);
34
+ return created;
562
35
  }
36
+ var CoordinationPersistenceShim = class {
37
+ coordination;
38
+ adapter;
39
+ nodeId = safeRandomUUID();
40
+ collectionAdapters = /* @__PURE__ */ new Map();
41
+ collectionSubscriptions = /* @__PURE__ */ new Map();
42
+ resumeChecks = /* @__PURE__ */ new Map();
43
+ localMutationBursts = /* @__PURE__ */ new Map();
44
+ stopResumeListeners;
45
+ checkingResume = false;
46
+ resumeRequested = false;
47
+ requestResumeCheck = () => {
48
+ this.resumeRequested = true;
49
+ if (this.checkingResume) return;
50
+ this.checkingResume = true;
51
+ (async () => {
52
+ try {
53
+ while (this.resumeRequested && this.resumeChecks.size > 0) {
54
+ this.resumeRequested = false;
55
+ await Promise.all([...this.resumeChecks.values()].flatMap((checks) => [...checks].map((check) => check())));
56
+ }
57
+ } finally {
58
+ this.checkingResume = false;
59
+ this.resumeRequested = false;
60
+ }
61
+ })();
62
+ };
63
+ startResumeListeners() {
64
+ if (this.stopResumeListeners || typeof window === "undefined" || typeof document === "undefined") return;
65
+ const page = window;
66
+ const visibility = document;
67
+ const onVisible = () => {
68
+ if (visibility.visibilityState === "visible") this.requestResumeCheck();
69
+ };
70
+ page.addEventListener("pageshow", this.requestResumeCheck);
71
+ page.addEventListener("focus", onVisible);
72
+ visibility.addEventListener("visibilitychange", onVisible);
73
+ this.stopResumeListeners = () => {
74
+ page.removeEventListener("pageshow", this.requestResumeCheck);
75
+ page.removeEventListener("focus", onVisible);
76
+ visibility.removeEventListener("visibilitychange", onVisible);
77
+ };
78
+ }
79
+ setAdapterForCollection(collectionId, adapter, cacheGenerationClaimId) {
80
+ if (cacheGenerationClaimId) this.claims.set(collectionId, cacheGenerationClaimId);
81
+ else this.claims.delete(collectionId);
82
+ this.collectionAdapters.set(collectionId, adapter);
83
+ this.positions.delete(collectionId);
84
+ }
85
+ adapterForCollection(collectionId, schemaVersion) {
86
+ const adapter = this.collectionAdapters.get(collectionId) ?? this.adapter;
87
+ if (schemaVersion !== void 0 && this.schemaVersion(adapter) !== schemaVersion) throw new Error(`Persistence schema mismatch for collection "${collectionId}". Reload the coordination host before writing through another schema version.`);
88
+ return adapter;
89
+ }
90
+ schemaVersion(adapter) {
91
+ return "schemaVersion" in adapter && typeof adapter.schemaVersion === "number" ? adapter.schemaVersion : void 0;
92
+ }
93
+ claims = /* @__PURE__ */ new Map();
94
+ storageTarget(collectionId, claimId = this.claims.get(collectionId)) {
95
+ if (claimId) this.claims.set(collectionId, claimId);
96
+ return claimId ? managedStorageTarget(collectionId, claimId) : eagerStorageTarget(collectionId);
97
+ }
98
+ positions = /* @__PURE__ */ new Map();
99
+ appliedEnvelopes = /* @__PURE__ */ new Map();
100
+ relayedMessages = /* @__PURE__ */ new Set();
101
+ service;
102
+ server;
103
+ pendingRelays = 0;
104
+ remoteSubsets = new SingleProcessCoordinator();
105
+ acquisitionIds = /* @__PURE__ */ new WeakMap();
106
+ remoteAcquisitions = /* @__PURE__ */ new Map();
107
+ constructor(coordination, adapter) {
108
+ this.coordination = coordination;
109
+ this.adapter = adapter;
110
+ this.service = coordination.service(PERSISTENCE_SERVICE);
111
+ this.server = isCoordinationHost(coordination) ? coordination.serve(PERSISTENCE_SERVICE, {
112
+ ensureLeadership: () => Promise.resolve(),
113
+ ensureRemoteSubset: async (input) => {
114
+ let options = this.remoteAcquisitions.get(input.acquisitionId)?.options;
115
+ if (!options) {
116
+ options = input.options;
117
+ this.remoteAcquisitions.set(input.acquisitionId, {
118
+ collectionId: input.collectionId,
119
+ options
120
+ });
121
+ }
122
+ try {
123
+ await this.remoteSubsets.requestEnsureRemoteSubset(input.collectionId, options);
124
+ } catch (error) {
125
+ if (this.remoteAcquisitions.get(input.acquisitionId)?.options === options) {
126
+ this.remoteAcquisitions.delete(input.acquisitionId);
127
+ await this.remoteSubsets.requestReleaseRemoteSubset(input.collectionId, options).catch(() => void 0);
128
+ }
129
+ throw error;
130
+ }
131
+ },
132
+ releaseRemoteSubset: (input) => {
133
+ const options = this.remoteAcquisitions.get(input.acquisitionId)?.options;
134
+ this.remoteAcquisitions.delete(input.acquisitionId);
135
+ return options ? this.remoteSubsets.requestReleaseRemoteSubset(input.collectionId, options) : Promise.resolve();
136
+ },
137
+ applyCommittedTx: (input) => this.applyCommittedTx(input),
138
+ ensurePersistedIndex: (input) => this.adapterForCollection(input.collectionId, input.schemaVersion).ensureIndex(this.storageTarget(input.collectionId, input.cacheGenerationClaimId), input.signature, input.spec),
139
+ applyLocalMutations: (input) => this.applyMutations(input),
140
+ pullSince: (input) => this.handlePullSince(input),
141
+ relayMessage: (input) => this.relayMessage(input)
142
+ }) : void 0;
143
+ }
144
+ getNodeId() {
145
+ return this.nodeId;
146
+ }
147
+ subscribe(collectionId, callback) {
148
+ let active = true;
149
+ let observed;
150
+ const unsubscribe = this.service.events.subscribe("message", (event) => {
151
+ if (!active) return;
152
+ if (event.collectionId === collectionId) {
153
+ const payload = event.message.payload;
154
+ const burst = this.localMutationBursts.get(collectionId);
155
+ if (burst && isRecord(payload) && payload.type === "tx:committed" && typeof payload.txId === "string" && !burst.pending.has(payload.txId)) burst.needsReload = true;
156
+ if (isRecord(payload) && payload.type === "tx:committed" && typeof payload.term === "number" && typeof payload.seq === "number" && typeof payload.latestRowVersion === "number" && (!observed || payload.term > observed.latestTerm || payload.term === observed.latestTerm && payload.seq > observed.latestSeq)) observed = {
157
+ latestTerm: payload.term,
158
+ latestSeq: payload.seq,
159
+ latestRowVersion: payload.latestRowVersion
160
+ };
161
+ callback(event.message);
162
+ }
163
+ });
164
+ const checkResume = async (force = false) => {
165
+ try {
166
+ if (!active) return;
167
+ const adapter = this.adapterForCollection(collectionId);
168
+ const current = await adapter.getStreamPosition?.(this.storageTarget(collectionId));
169
+ if (!active) return;
170
+ if (!force && current && observed && current.latestTerm === observed.latestTerm && current.latestSeq === observed.latestSeq && current.latestRowVersion === observed.latestRowVersion) return;
171
+ callback({
172
+ v: 1,
173
+ dbName: this.coordinationScope(),
174
+ collectionId,
175
+ senderId: `resume:${this.nodeId}`,
176
+ ts: Date.now(),
177
+ payload: {
178
+ type: "collection:reset",
179
+ schemaVersion: this.schemaVersion(adapter) ?? 1,
180
+ resetEpoch: 0
181
+ }
182
+ });
183
+ observed = current;
184
+ } catch (error) {
185
+ if (active) console.warn(`Failed to refresh resumed collection "${collectionId}".`, error);
186
+ }
187
+ };
188
+ const checks = this.resumeChecks.get(collectionId) ?? /* @__PURE__ */ new Set();
189
+ checks.add(checkResume);
190
+ this.resumeChecks.set(collectionId, checks);
191
+ this.startResumeListeners();
192
+ this.collectionSubscriptions.set(collectionId, (this.collectionSubscriptions.get(collectionId) ?? 0) + 1);
193
+ return () => {
194
+ if (!active) return;
195
+ active = false;
196
+ checks.delete(checkResume);
197
+ if (checks.size === 0) {
198
+ this.resumeChecks.delete(collectionId);
199
+ const burst = this.localMutationBursts.get(collectionId);
200
+ if (burst?.timer !== void 0) clearTimeout(burst.timer);
201
+ this.localMutationBursts.delete(collectionId);
202
+ }
203
+ if (this.resumeChecks.size === 0) {
204
+ this.stopResumeListeners?.();
205
+ this.stopResumeListeners = void 0;
206
+ }
207
+ try {
208
+ unsubscribe();
209
+ } finally {
210
+ const remaining = this.collectionSubscriptions.get(collectionId) - 1;
211
+ if (remaining > 0) this.collectionSubscriptions.set(collectionId, remaining);
212
+ else {
213
+ this.collectionSubscriptions.delete(collectionId);
214
+ this.collectionAdapters.delete(collectionId);
215
+ this.claims.delete(collectionId);
216
+ this.positions.delete(collectionId);
217
+ }
218
+ }
219
+ };
220
+ }
221
+ publish(collectionId, message) {
222
+ if (this.server && isCoordinationHost(this.coordination) && this.coordination.isLeader) {
223
+ this.publishMessage({
224
+ collectionId,
225
+ message
226
+ });
227
+ return;
228
+ }
229
+ if (this.pendingRelays >= MAX_PENDING_RELAYS) {
230
+ console.warn(`Dropping persistence relay for "${collectionId}" because the pending relay limit was reached.`);
231
+ return;
232
+ }
233
+ this.pendingRelays += 1;
234
+ this.service.methods.relayMessage({
235
+ collectionId,
236
+ message
237
+ }).catch((error) => {
238
+ console.warn(`Failed to relay persistence message for "${collectionId}".`, error);
239
+ }).finally(() => {
240
+ this.pendingRelays -= 1;
241
+ });
242
+ }
243
+ isLeader() {
244
+ return isCoordinationHost(this.coordination) && this.coordination.isLeader;
245
+ }
246
+ ensureLeadership() {
247
+ return this.service.methods.ensureLeadership({ collectionId: "*" });
248
+ }
249
+ requestEnsureRemoteSubset(collectionId, options) {
250
+ let collectionIds = this.acquisitionIds.get(options);
251
+ if (!collectionIds) {
252
+ collectionIds = /* @__PURE__ */ new Map();
253
+ this.acquisitionIds.set(options, collectionIds);
254
+ }
255
+ let acquisitionId = collectionIds.get(collectionId);
256
+ if (!acquisitionId) {
257
+ acquisitionId = safeRandomUUID();
258
+ collectionIds.set(collectionId, acquisitionId);
259
+ }
260
+ return this.service.methods.ensureRemoteSubset({
261
+ collectionId,
262
+ options: toTransportedLoadSubsetOptions(options),
263
+ acquisitionId
264
+ });
265
+ }
266
+ requestReleaseRemoteSubset(collectionId, options) {
267
+ const collectionIds = this.acquisitionIds.get(options);
268
+ const acquisitionId = collectionIds?.get(collectionId);
269
+ if (!acquisitionId) return Promise.resolve();
270
+ collectionIds.delete(collectionId);
271
+ if (collectionIds.size === 0) this.acquisitionIds.delete(options);
272
+ return this.service.methods.releaseRemoteSubset({
273
+ collectionId,
274
+ options: {},
275
+ acquisitionId
276
+ });
277
+ }
278
+ registerRemoteSubsetOwner(collectionId, owner) {
279
+ const unregister = this.remoteSubsets.registerRemoteSubsetOwner(collectionId, owner);
280
+ let registered = true;
281
+ return () => {
282
+ if (!registered) return;
283
+ registered = false;
284
+ unregister();
285
+ for (const [id, acquisition] of this.remoteAcquisitions) if (acquisition.collectionId === collectionId) this.remoteAcquisitions.delete(id);
286
+ };
287
+ }
288
+ requestApplyCommittedTx(collectionId, tx, scopedAdapter) {
289
+ return this.isLeader() ? this.applyCommittedTx({
290
+ collectionId,
291
+ tx
292
+ }, scopedAdapter) : this.service.methods.applyCommittedTx({
293
+ collectionId,
294
+ tx,
295
+ schemaVersion: this.schemaVersion(scopedAdapter ?? this.adapterForCollection(collectionId)) ?? this.schemaVersion(this.adapterForCollection(collectionId))
296
+ });
297
+ }
298
+ async applyCommittedTx({ collectionId, tx, schemaVersion }, scopedAdapter) {
299
+ try {
300
+ await (scopedAdapter ?? this.adapterForCollection(collectionId, schemaVersion)).applyCommittedTx(this.storageTarget(collectionId, tx.cacheGenerationClaimId), tx);
301
+ } catch (error) {
302
+ throw toPersistedCollectionDurabilityError(collectionId, error);
303
+ }
304
+ this.positions.delete(collectionId);
305
+ return {
306
+ type: "rpc:applyCommittedTx:res",
307
+ rpcId: safeRandomUUID(),
308
+ ok: true,
309
+ term: tx.term,
310
+ seq: tx.seq,
311
+ latestRowVersion: tx.rowVersion
312
+ };
313
+ }
314
+ requestEnsurePersistedIndex(collectionId, signature, spec, scopedAdapter, localEnsureCompleted, cacheGenerationClaimId) {
315
+ if (this.isLeader()) return localEnsureCompleted ? Promise.resolve() : (scopedAdapter ?? this.adapterForCollection(collectionId)).ensureIndex(this.storageTarget(collectionId, cacheGenerationClaimId), signature, spec);
316
+ return this.service.methods.ensurePersistedIndex({
317
+ collectionId,
318
+ signature,
319
+ spec,
320
+ cacheGenerationClaimId,
321
+ schemaVersion: this.schemaVersion(scopedAdapter ?? this.adapterForCollection(collectionId)) ?? this.schemaVersion(this.adapterForCollection(collectionId))
322
+ });
323
+ }
324
+ async requestApplyLocalMutations(collectionId, mutations, cacheGenerationClaimId) {
325
+ const envelopeId = safeRandomUUID();
326
+ const burst = this.resumeChecks.has(collectionId) ? this.localMutationBursts.get(collectionId) ?? {
327
+ pending: /* @__PURE__ */ new Set(),
328
+ needsReload: false,
329
+ timer: void 0
330
+ } : void 0;
331
+ if (burst) {
332
+ if (burst.timer !== void 0) clearTimeout(burst.timer);
333
+ if (burst.pending.size > 0) burst.needsReload = true;
334
+ burst.pending.add(envelopeId);
335
+ this.localMutationBursts.set(collectionId, burst);
336
+ }
337
+ try {
338
+ return await this.service.methods.applyLocalMutations({
339
+ collectionId,
340
+ rpcId: safeRandomUUID(),
341
+ envelopeId,
342
+ schemaVersion: this.schemaVersion(this.adapterForCollection(collectionId)),
343
+ mutations,
344
+ cacheGenerationClaimId
345
+ });
346
+ } finally {
347
+ burst?.pending.delete(envelopeId);
348
+ if (burst && burst.pending.size === 0 && this.localMutationBursts.get(collectionId) === burst) burst.timer = setTimeout(() => {
349
+ if (this.localMutationBursts.get(collectionId) !== burst) return;
350
+ this.localMutationBursts.delete(collectionId);
351
+ if (burst.needsReload) for (const check of this.resumeChecks.get(collectionId) ?? []) check(true);
352
+ }, 0);
353
+ }
354
+ }
355
+ pullSince(collectionId, fromRowVersion, scopedAdapter, cacheGenerationClaimId) {
356
+ this.storageTarget(collectionId, cacheGenerationClaimId);
357
+ const input = {
358
+ collectionId,
359
+ rpcId: safeRandomUUID(),
360
+ fromRowVersion,
361
+ cacheGenerationClaimId,
362
+ schemaVersion: this.schemaVersion(this.adapterForCollection(collectionId))
363
+ };
364
+ return scopedAdapter && this.isLeader() ? this.handlePullSince(input, scopedAdapter) : this.service.methods.pullSince(input);
365
+ }
366
+ relayMessage(input) {
367
+ const key = relayKey(input.collectionId, input.message);
368
+ if (this.relayedMessages.has(key)) return Promise.resolve();
369
+ this.relayedMessages.add(key);
370
+ if (this.relayedMessages.size > MAX_DEDUPLICATION_ENTRIES) {
371
+ const oldest = this.relayedMessages.values().next().value;
372
+ if (oldest) this.relayedMessages.delete(oldest);
373
+ }
374
+ this.publishMessage(input);
375
+ return Promise.resolve();
376
+ }
377
+ publishMessage(input) {
378
+ this.server?.events.publish("message", input);
379
+ }
380
+ async position(collectionId) {
381
+ let position = this.positions.get(collectionId);
382
+ if (!position) {
383
+ const adapter = this.adapterForCollection(collectionId);
384
+ position = Promise.resolve(adapter.getStreamPosition ? adapter.getStreamPosition(this.storageTarget(collectionId)) : adapter.loadResumeSnapshot(this.storageTarget(collectionId), { includeRows: false })).then((current) => ({
385
+ term: (current?.latestTerm ?? 0) + 1,
386
+ seq: current?.latestSeq ?? 0,
387
+ rowVersion: current?.latestRowVersion ?? 0
388
+ }));
389
+ }
390
+ this.positions.delete(collectionId);
391
+ this.positions.set(collectionId, position);
392
+ while (this.positions.size > MAX_COLLECTION_POSITIONS) {
393
+ const oldest = this.positions.keys().next().value;
394
+ if (oldest !== void 0) this.positions.delete(oldest);
395
+ }
396
+ position.catch(() => {
397
+ if (this.positions.get(collectionId) === position) this.positions.delete(collectionId);
398
+ });
399
+ return position;
400
+ }
401
+ async applyMutations(input) {
402
+ const adapter = this.adapterForCollection(input.collectionId, input.schemaVersion);
403
+ const envelopeKey = JSON.stringify([input.collectionId, input.envelopeId]);
404
+ const previous = this.appliedEnvelopes.get(envelopeKey);
405
+ if (previous) return {
406
+ ...previous,
407
+ rpcId: input.rpcId
408
+ };
409
+ this.storageTarget(input.collectionId, input.cacheGenerationClaimId);
410
+ const position = await this.position(input.collectionId);
411
+ const nextPosition = {
412
+ ...position,
413
+ seq: position.seq + 1,
414
+ rowVersion: position.rowVersion + 1
415
+ };
416
+ const txId = input.envelopeId;
417
+ await adapter.applyCommittedTx(this.storageTarget(input.collectionId, input.cacheGenerationClaimId), {
418
+ cacheGenerationClaimId: input.cacheGenerationClaimId,
419
+ txId,
420
+ term: nextPosition.term,
421
+ seq: nextPosition.seq,
422
+ rowVersion: nextPosition.rowVersion,
423
+ mutations: input.mutations.map(({ mutationId, ...mutation }) => {
424
+ return mutation;
425
+ })
426
+ });
427
+ Object.assign(position, nextPosition);
428
+ const committed = {
429
+ v: 1,
430
+ dbName: this.coordinationScope(),
431
+ collectionId: input.collectionId,
432
+ senderId: this.nodeId,
433
+ ts: Date.now(),
434
+ payload: {
435
+ type: "tx:committed",
436
+ term: position.term,
437
+ seq: position.seq,
438
+ txId,
439
+ latestRowVersion: position.rowVersion,
440
+ requiresFullReload: false,
441
+ changedRows: input.mutations.filter((mutation) => mutation.type !== "delete").map((mutation) => ({
442
+ key: mutation.key,
443
+ value: mutation.value
444
+ })),
445
+ deletedKeys: input.mutations.filter((mutation) => mutation.type === "delete").map((mutation) => mutation.key),
446
+ rowMetadataMutations: input.mutations.flatMap((mutation) => mutation.type !== "delete" && (mutation.metadataChanged || mutation.metadata !== void 0) ? [mutation.metadata === void 0 ? {
447
+ type: "delete",
448
+ key: mutation.key
449
+ } : {
450
+ type: "set",
451
+ key: mutation.key,
452
+ value: mutation.metadata
453
+ }] : [])
454
+ }
455
+ };
456
+ this.publishMessage({
457
+ collectionId: input.collectionId,
458
+ message: committed
459
+ });
460
+ const response = {
461
+ type: "rpc:applyLocalMutations:res",
462
+ rpcId: input.rpcId,
463
+ ok: true,
464
+ term: position.term,
465
+ seq: position.seq,
466
+ latestRowVersion: position.rowVersion,
467
+ acceptedMutationIds: input.mutations.map((mutation) => mutation.mutationId)
468
+ };
469
+ this.appliedEnvelopes.set(envelopeKey, response);
470
+ if (this.appliedEnvelopes.size > MAX_DEDUPLICATION_ENTRIES) {
471
+ const oldest = this.appliedEnvelopes.keys().next().value;
472
+ if (oldest) this.appliedEnvelopes.delete(oldest);
473
+ }
474
+ return response;
475
+ }
476
+ async handlePullSince(input, scopedAdapter) {
477
+ const adapter = scopedAdapter ?? this.adapterForCollection(input.collectionId, input.schemaVersion);
478
+ const current = await adapter.getStreamPosition?.(this.storageTarget(input.collectionId, input.cacheGenerationClaimId));
479
+ const position = current ? {
480
+ term: current.latestTerm,
481
+ seq: current.latestSeq,
482
+ rowVersion: current.latestRowVersion
483
+ } : await this.position(input.collectionId);
484
+ const result = await adapter.pullSince?.(this.storageTarget(input.collectionId, input.cacheGenerationClaimId), input.fromRowVersion);
485
+ if (!result || result.requiresFullReload) return {
486
+ type: "rpc:pullSince:res",
487
+ rpcId: input.rpcId,
488
+ ok: true,
489
+ latestTerm: result?.latestTerm ?? position.term,
490
+ latestSeq: result?.latestSeq ?? position.seq,
491
+ latestRowVersion: result?.latestRowVersion ?? position.rowVersion,
492
+ requiresFullReload: true
493
+ };
494
+ return {
495
+ type: "rpc:pullSince:res",
496
+ rpcId: input.rpcId,
497
+ ok: true,
498
+ latestTerm: result?.latestTerm ?? position.term,
499
+ latestSeq: result?.latestSeq ?? position.seq,
500
+ latestRowVersion: result.latestRowVersion,
501
+ requiresFullReload: false,
502
+ changedKeys: result.changedKeys,
503
+ deletedKeys: result.deletedKeys,
504
+ deltas: result.deltas
505
+ };
506
+ }
507
+ coordinationScope() {
508
+ return "scope" in this.coordination && typeof this.coordination.scope === "string" ? this.coordination.scope : "party-stack";
509
+ }
510
+ };
511
+ //#endregion
512
+ export { createPersistedCollectionCoordinator };
513
+
563
514
  //# sourceMappingURL=createPersistedCollectionCoordinator.js.map