@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,748 +0,0 @@
1
- import { SingleProcessCoordination } from "@party-stack/coordination";
2
- import { SharedWorkerCoordinationClient, SharedWorkerCoordinationHost, } from "@party-stack/coordination/shared-worker";
3
- import { SingleProcessCoordinator } from "@tanstack/db-sqlite-persistence-core";
4
- import { describe, expect, it, vi } from "vitest";
5
- import { createPersistedCollectionCoordinator } from "../coordinator/createPersistedCollectionCoordinator.js";
6
- import { MemoryBlobBytesStore } from "../memory/MemoryBlobBytesStore.js";
7
- import { createLocalCollection } from "./createLocalCollection.js";
8
- function memoryAdapter() {
9
- const collections = new Map();
10
- const positions = new Map();
11
- const rows = (collectionId) => {
12
- let collection = collections.get(collectionId);
13
- if (!collection) {
14
- collection = new Map();
15
- collections.set(collectionId, collection);
16
- }
17
- return collection;
18
- };
19
- return {
20
- loadResumeSnapshot: (collectionId) => Promise.resolve({
21
- rows: [...rows(collectionId)].map(([key, value]) => ({ key, value })),
22
- collectionMetadata: [],
23
- ...(positions.get(collectionId) ?? { latestTerm: 0, latestSeq: 0, latestRowVersion: 0 }),
24
- resetEpoch: 0,
25
- }),
26
- loadSubset: (collectionId) => Promise.resolve([...rows(collectionId)].map(([key, value]) => ({
27
- key,
28
- value,
29
- }))),
30
- applyCommittedTx: (collectionId, transaction) => {
31
- const collection = rows(collectionId);
32
- for (const mutation of transaction.mutations) {
33
- if (mutation.type === "delete") {
34
- collection.delete(mutation.key);
35
- }
36
- else {
37
- collection.set(mutation.key, mutation.value);
38
- }
39
- }
40
- positions.set(collectionId, {
41
- latestTerm: transaction.term,
42
- latestSeq: transaction.seq,
43
- latestRowVersion: transaction.rowVersion,
44
- });
45
- return Promise.resolve();
46
- },
47
- ensureIndex: () => Promise.resolve(),
48
- getStreamPosition: (collectionId) => Promise.resolve(positions.get(collectionId) ?? {
49
- latestTerm: 0,
50
- latestSeq: 0,
51
- latestRowVersion: 0,
52
- }),
53
- };
54
- }
55
- function coordinatedRuntime(options) {
56
- const coordination = options.coordination;
57
- const runtime = {
58
- owner: "test-owner",
59
- namespace: "test-runtime",
60
- blobBytes: new MemoryBlobBytesStore(),
61
- persistence: options.adapter,
62
- coordination,
63
- };
64
- return { runtime, coordination };
65
- }
66
- describe("createLocalCollection", () => {
67
- it("creates an in-memory collection without runtime persistence", async () => {
68
- const coordination = new SingleProcessCoordination({
69
- scope: "memory-items",
70
- });
71
- const collection = createLocalCollection({
72
- name: "memory-items",
73
- getKey: (item) => item.id,
74
- runtime: {
75
- owner: "test-owner",
76
- namespace: "memory",
77
- blobBytes: new MemoryBlobBytesStore(),
78
- coordination,
79
- },
80
- });
81
- await collection.preload();
82
- const transaction = collection.insert({
83
- id: "one",
84
- title: "In memory",
85
- });
86
- await transaction.isPersisted.promise;
87
- expect(collection.get("one")).toMatchObject({
88
- id: "one",
89
- title: "In memory",
90
- });
91
- await collection.cleanup();
92
- await coordination.close();
93
- });
94
- it("loads through the runtime persistence adapter when available", async () => {
95
- const loadSubset = vi.fn(() => Promise.resolve([
96
- {
97
- key: "one",
98
- value: {
99
- id: "one",
100
- title: "Persisted",
101
- },
102
- },
103
- ]));
104
- const loadResumeSnapshot = vi.fn(async () => ({
105
- rows: await loadSubset(),
106
- collectionMetadata: [],
107
- latestTerm: 0,
108
- latestSeq: 0,
109
- latestRowVersion: 0,
110
- resetEpoch: 0,
111
- }));
112
- const adapter = {
113
- loadResumeSnapshot,
114
- loadSubset,
115
- applyCommittedTx: vi.fn(() => Promise.resolve()),
116
- ensureIndex: vi.fn(() => Promise.resolve()),
117
- };
118
- const coordination = new SingleProcessCoordination({
119
- scope: "persisted-items",
120
- });
121
- const collection = createLocalCollection({
122
- name: "persisted-items",
123
- getKey: (item) => item.id,
124
- runtime: {
125
- owner: "test-owner",
126
- namespace: "persisted",
127
- blobBytes: new MemoryBlobBytesStore(),
128
- persistence: { adapter },
129
- coordination,
130
- },
131
- });
132
- await collection.preload();
133
- expect(loadResumeSnapshot).toHaveBeenCalledWith("party-stack:test-owner:persisted:persisted-items", expect.any(Object));
134
- expect(collection.get("one")).toMatchObject({
135
- id: "one",
136
- title: "Persisted",
137
- });
138
- await collection.cleanup();
139
- await coordination.close();
140
- });
141
- it("propagates committed mutations between coordinated contexts", async () => {
142
- const adapter = memoryAdapter();
143
- const coordination = new SingleProcessCoordination({
144
- scope: "local-collection-test",
145
- });
146
- const firstRuntime = coordinatedRuntime({
147
- adapter: { adapter },
148
- coordination,
149
- });
150
- const secondRuntime = coordinatedRuntime({
151
- adapter: { adapter },
152
- coordination,
153
- });
154
- const createItems = ({ runtime }) => createLocalCollection({
155
- name: "shared-items",
156
- getKey: (item) => item.id,
157
- runtime,
158
- });
159
- const first = createItems(firstRuntime);
160
- const second = createItems(secondRuntime);
161
- await Promise.all([first.preload(), second.preload()]);
162
- await second.insert({
163
- id: "one",
164
- title: "Shared",
165
- }).isPersisted.promise;
166
- await vi.waitFor(() => {
167
- expect(first.get("one")?.title).toBe("Shared");
168
- expect(second.get("one")?.title).toBe("Shared");
169
- });
170
- await first.cleanup();
171
- await second.cleanup();
172
- await coordination.close();
173
- });
174
- it("removes non-cloneable subscription and signal state from remote subset requests", async () => {
175
- const adapter = memoryAdapter();
176
- const coordination = new SingleProcessCoordination({
177
- scope: "remote-subset-test",
178
- });
179
- const first = coordinatedRuntime({
180
- adapter: { adapter },
181
- coordination,
182
- });
183
- const second = coordinatedRuntime({
184
- adapter: { adapter },
185
- coordination,
186
- });
187
- const firstCoordinator = createPersistedCollectionCoordinator(first.coordination, adapter);
188
- const secondCoordinator = createPersistedCollectionCoordinator(second.coordination, adapter);
189
- const load = vi.fn((options) => {
190
- expect(options).not.toHaveProperty("signal");
191
- expect(options).not.toHaveProperty("subscription");
192
- return Promise.resolve();
193
- });
194
- const unloadSubset = vi.fn();
195
- const unregister = firstCoordinator.registerRemoteSubsetOwner("items", Object.assign(load, {
196
- unloadSubset,
197
- onError: (error) => {
198
- throw error;
199
- },
200
- }));
201
- const options = {
202
- signal: new AbortController().signal,
203
- subscription: { callback: () => undefined },
204
- };
205
- await expect(secondCoordinator.requestEnsureRemoteSubset?.("items", options)).resolves.toBeUndefined();
206
- expect(load).toHaveBeenCalledWith({});
207
- await secondCoordinator.requestReleaseRemoteSubset("items", options);
208
- expect(unloadSubset).toHaveBeenCalledWith(load.mock.calls[0]?.[0]);
209
- unregister();
210
- await expect(firstCoordinator.requestEnsurePersistedIndex("items", "index", {
211
- expressionSql: [],
212
- })).resolves.toBeUndefined();
213
- await coordination.close();
214
- });
215
- it("keeps subset acquisitions independent across collections and identical query options", async () => {
216
- const coordination = new SingleProcessCoordination({ scope: "subset-identities" });
217
- const coordinator = createPersistedCollectionCoordinator(coordination, memoryAdapter());
218
- const firstLoad = vi.fn(() => Promise.resolve());
219
- const secondLoad = vi.fn(() => Promise.resolve());
220
- const firstUnload = vi.fn();
221
- const secondUnload = vi.fn();
222
- const unregisterFirst = coordinator.registerRemoteSubsetOwner("first", Object.assign(firstLoad, { unloadSubset: firstUnload, onError: vi.fn() }));
223
- const unregisterSecond = coordinator.registerRemoteSubsetOwner("second", Object.assign(secondLoad, { unloadSubset: secondUnload, onError: vi.fn() }));
224
- const sharedOptions = { limit: 10 };
225
- const otherOptions = { limit: 10 };
226
- try {
227
- await coordinator.requestEnsureRemoteSubset("first", sharedOptions);
228
- await coordinator.requestEnsureRemoteSubset("second", sharedOptions);
229
- await coordinator.requestEnsureRemoteSubset("second", otherOptions);
230
- expect(firstLoad).toHaveBeenCalledTimes(1);
231
- expect(secondLoad).toHaveBeenCalledTimes(2);
232
- await coordinator.requestReleaseRemoteSubset("first", sharedOptions);
233
- expect(firstUnload).toHaveBeenCalledOnce();
234
- expect(secondUnload).not.toHaveBeenCalled();
235
- await coordinator.requestReleaseRemoteSubset("second", sharedOptions);
236
- expect(secondUnload).toHaveBeenCalledTimes(1);
237
- await coordinator.requestReleaseRemoteSubset("second", otherOptions);
238
- expect(secondUnload).toHaveBeenCalledTimes(2);
239
- }
240
- finally {
241
- unregisterFirst();
242
- unregisterSecond();
243
- await coordination.close();
244
- }
245
- });
246
- it("releases failed subset leases and permits subsequent loads", async () => {
247
- const coordination = new SingleProcessCoordination({ scope: "failed-subsets" });
248
- const coordinator = createPersistedCollectionCoordinator(coordination, memoryAdapter());
249
- const load = vi.fn(() => Promise.reject(new Error("load failed")));
250
- const unloadSubset = vi.fn();
251
- const onError = vi.fn();
252
- const unregister = coordinator.registerRemoteSubsetOwner("items", Object.assign(load, { unloadSubset, onError }));
253
- try {
254
- for (let index = 0; index < 20; index++) {
255
- await expect(coordinator.requestEnsureRemoteSubset("items", { limit: index + 1 })).rejects.toThrow("load failed");
256
- }
257
- expect(unloadSubset).toHaveBeenCalledTimes(20);
258
- expect(onError).toHaveBeenCalledTimes(20);
259
- expect(Reflect.get(coordinator, "remoteAcquisitions").size).toBe(0);
260
- load.mockImplementation(() => Promise.resolve());
261
- const options = { limit: 50 };
262
- await coordinator.requestEnsureRemoteSubset("items", options);
263
- await coordinator.requestReleaseRemoteSubset("items", options);
264
- expect(unloadSubset).toHaveBeenCalledTimes(21);
265
- }
266
- finally {
267
- unregister();
268
- await coordination.close();
269
- }
270
- });
271
- it("bounds host positions for client-only collections and reloads evicted positions from durable storage", async () => {
272
- const coordination = new SingleProcessCoordination({ scope: "dynamic-host-positions" });
273
- const adapter = { ...memoryAdapter(), getStreamPosition: undefined };
274
- const apply = vi.spyOn(adapter, "applyCommittedTx");
275
- const coordinator = createPersistedCollectionCoordinator(coordination, adapter);
276
- try {
277
- for (let index = 0; index < 160; index++) {
278
- await coordinator.requestApplyLocalMutations(`client-${index}`, [{ mutationId: "one", type: "insert", key: "one", value: { id: "one" } }]);
279
- }
280
- expect(Reflect.get(coordinator, "positions").size).toBeLessThanOrEqual(128);
281
- await coordinator.requestApplyLocalMutations("client-0", [{ mutationId: "two", type: "insert", key: "two", value: { id: "two" } }]);
282
- expect(apply).toHaveBeenLastCalledWith("client-0", expect.objectContaining({ seq: 2, rowVersion: 2 }));
283
- }
284
- finally {
285
- await coordination.close();
286
- }
287
- });
288
- it("routes client-only persistence through a SharedWorker host", async () => {
289
- const adapter = memoryAdapter();
290
- const channel = new MessageChannel();
291
- const hostCoordination = new SharedWorkerCoordinationHost({
292
- scope: "shared-worker-persistence",
293
- });
294
- const disconnect = hostCoordination.connect(channel.port1);
295
- const clientCoordination = new SharedWorkerCoordinationClient({
296
- scope: "shared-worker-persistence",
297
- worker: channel.port2,
298
- });
299
- const host = createLocalCollection({
300
- name: "worker-items",
301
- getKey: (item) => item.id,
302
- runtime: {
303
- owner: "test-owner",
304
- namespace: "worker",
305
- blobBytes: new MemoryBlobBytesStore(),
306
- persistence: { adapter },
307
- coordination: hostCoordination,
308
- },
309
- });
310
- const client = createLocalCollection({
311
- name: "worker-items",
312
- getKey: (item) => item.id,
313
- runtime: {
314
- owner: "test-owner",
315
- namespace: "worker",
316
- blobBytes: new MemoryBlobBytesStore(),
317
- persistence: { adapter },
318
- coordination: clientCoordination,
319
- },
320
- });
321
- await Promise.all([host.preload(), client.preload()]);
322
- await client.insert({
323
- id: "one",
324
- title: "From client",
325
- }).isPersisted.promise;
326
- await vi.waitFor(() => {
327
- expect(host.get("one")?.title).toBe("From client");
328
- expect(client.get("one")?.title).toBe("From client");
329
- });
330
- expect(clientCoordination.role).toBe("client");
331
- const coordinator = createPersistedCollectionCoordinator(clientCoordination, adapter);
332
- const collectionId = "party-stack:test-owner:worker:worker-items";
333
- await expect(coordinator.requestApplyCommittedTx(collectionId, {
334
- txId: "source-commit",
335
- term: 1,
336
- seq: 2,
337
- rowVersion: 2,
338
- mutations: [{ type: "insert", key: "two", value: { id: "two", title: "From source" } }],
339
- })).resolves.toMatchObject({ ok: true, latestRowVersion: 2 });
340
- expect(await adapter.loadSubset(collectionId, {})).toEqual(expect.arrayContaining([{ key: "two", value: { id: "two", title: "From source" } }]));
341
- await client.cleanup();
342
- await host.cleanup();
343
- await clientCoordination.close();
344
- disconnect();
345
- await hostCoordination.close();
346
- });
347
- });
348
- describe("collection-scoped persistence", () => {
349
- it("forwards local mode and schema and routes writes through the scoped adapter", async () => {
350
- const coordination = new SingleProcessCoordination({ scope: "scoped-persistence" });
351
- const scoped = { ...memoryAdapter(), schemaVersion: 2 };
352
- const apply = vi.spyOn(scoped, "applyCommittedTx");
353
- const root = memoryAdapter();
354
- const coordinator = createPersistedCollectionCoordinator(coordination, root);
355
- const registerAdapter = vi.spyOn(coordinator, "setAdapterForCollection");
356
- const scopedPosition = vi.spyOn(scoped, "getStreamPosition");
357
- const rootPosition = vi.spyOn(root, "getStreamPosition");
358
- const defaultCoordinator = new SingleProcessCoordinator();
359
- const defaultApply = vi.spyOn(defaultCoordinator, "requestApplyCommittedTx");
360
- const resolvePersistenceForCollection = vi.fn(() => ({
361
- adapter: scoped,
362
- coordinator: defaultCoordinator,
363
- }));
364
- const rootApply = vi.spyOn(root, "applyCommittedTx");
365
- const collection = createLocalCollection({
366
- name: "scoped",
367
- schemaVersion: 2,
368
- getKey: (item) => item.id,
369
- runtime: coordinatedRuntime({
370
- adapter: { adapter: root, resolvePersistenceForCollection },
371
- coordination,
372
- }).runtime,
373
- });
374
- await collection.preload();
375
- expect(registerAdapter).toHaveBeenCalledExactlyOnceWith(collection.id, scoped);
376
- expect(resolvePersistenceForCollection).toHaveBeenCalledWith({
377
- collectionId: collection.id,
378
- mode: "sync-absent",
379
- schemaVersion: 2,
380
- });
381
- await collection.insert({ id: "one", title: "Scoped" }).isPersisted.promise;
382
- expect(apply).toHaveBeenCalled();
383
- expect(rootApply).not.toHaveBeenCalled();
384
- expect(defaultApply).not.toHaveBeenCalled();
385
- await collection.cleanup();
386
- scopedPosition.mockClear();
387
- rootPosition.mockClear();
388
- await coordinator.pullSince(collection.id, 0);
389
- expect(scopedPosition).not.toHaveBeenCalled();
390
- expect(rootPosition).toHaveBeenCalledWith(collection.id);
391
- await coordination.close();
392
- });
393
- it("preserves mode-only resolvers while overriding their coordinator", async () => {
394
- const coordination = new SingleProcessCoordination({ scope: "mode-only-persistence" });
395
- const root = memoryAdapter();
396
- const selected = memoryAdapter();
397
- const rootApply = vi.spyOn(root, "applyCommittedTx");
398
- const apply = vi.spyOn(selected, "applyCommittedTx");
399
- const resolvePersistenceForMode = vi.fn(() => ({ adapter: selected, coordinator: new SingleProcessCoordinator() }));
400
- const collection = createLocalCollection({
401
- name: "mode-only",
402
- runtime: coordinatedRuntime({ adapter: { adapter: root, resolvePersistenceForMode }, coordination }).runtime,
403
- getKey: (item) => item.id,
404
- });
405
- try {
406
- await collection.preload();
407
- await collection.insert({ id: "one", title: "Selected" }).isPersisted.promise;
408
- expect(resolvePersistenceForMode).toHaveBeenCalledWith("sync-absent");
409
- expect(apply).toHaveBeenCalledWith(collection.id, expect.anything());
410
- expect(rootApply).not.toHaveBeenCalled();
411
- }
412
- finally {
413
- await collection.cleanup();
414
- await coordination.close();
415
- }
416
- });
417
- it("keeps different collection versions isolated on one shared coordinator", async () => {
418
- const coordination = new SingleProcessCoordination({ scope: "different-schemas" });
419
- const root = memoryAdapter();
420
- const tasksAdapter = { ...memoryAdapter(), schemaVersion: 2 };
421
- const settingsAdapter = { ...memoryAdapter(), schemaVersion: 7 };
422
- const rootApply = vi.spyOn(root, "applyCommittedTx");
423
- const tasksApply = vi.spyOn(tasksAdapter, "applyCommittedTx");
424
- const settingsApply = vi.spyOn(settingsAdapter, "applyCommittedTx");
425
- const runtime = coordinatedRuntime({
426
- adapter: {
427
- adapter: root,
428
- resolvePersistenceForCollection: ({ schemaVersion }) => ({
429
- adapter: schemaVersion === 2 ? tasksAdapter : settingsAdapter,
430
- }),
431
- },
432
- coordination,
433
- }).runtime;
434
- const tasks = createLocalCollection({
435
- name: "tasks",
436
- schemaVersion: 2,
437
- runtime,
438
- getKey: (item) => item.id,
439
- });
440
- const settings = createLocalCollection({
441
- name: "settings",
442
- schemaVersion: 7,
443
- runtime,
444
- getKey: (item) => item.id,
445
- });
446
- await Promise.all([tasks.preload(), settings.preload()]);
447
- await tasks.insert({ id: "one", title: "Task" }).isPersisted.promise;
448
- await settings.insert({ id: "one", title: "Setting" }).isPersisted.promise;
449
- expect(tasksApply).toHaveBeenCalledWith(tasks.id, expect.anything());
450
- expect(settingsApply).toHaveBeenCalledWith(settings.id, expect.anything());
451
- expect(rootApply).not.toHaveBeenCalled();
452
- await tasks.cleanup();
453
- await settings.insert({ id: "two", title: "Still active" }).isPersisted.promise;
454
- expect(settings.get("two")?.title).toBe("Still active");
455
- expect(createPersistedCollectionCoordinator(coordination, root)).toBe(createPersistedCollectionCoordinator(coordination, root));
456
- await settings.cleanup();
457
- await coordination.close();
458
- });
459
- it("preserves row metadata in local mutation RPC and broadcasts", async () => {
460
- const coordination = new SingleProcessCoordination({ scope: "mutation-metadata" });
461
- const adapter = memoryAdapter();
462
- const apply = vi.spyOn(adapter, "applyCommittedTx");
463
- const coordinator = createPersistedCollectionCoordinator(coordination, adapter);
464
- const listener = vi.fn();
465
- const unsubscribe = coordinator.subscribe("items", listener);
466
- await coordinator.requestApplyLocalMutations("items", [
467
- {
468
- mutationId: "insert",
469
- type: "insert",
470
- key: "one",
471
- value: { id: "one" },
472
- metadata: { etag: "v1" },
473
- metadataChanged: true,
474
- },
475
- ]);
476
- expect(apply).toHaveBeenCalledWith("items", expect.objectContaining({
477
- mutations: [
478
- {
479
- type: "insert",
480
- key: "one",
481
- value: { id: "one" },
482
- metadata: { etag: "v1" },
483
- metadataChanged: true,
484
- },
485
- ],
486
- }));
487
- const broadcast = listener.mock.calls[0]?.[0];
488
- expect(broadcast).toMatchObject({
489
- payload: {
490
- rowMetadataMutations: [{ type: "set", key: "one", value: { etag: "v1" } }],
491
- },
492
- });
493
- unsubscribe();
494
- await coordination.close();
495
- });
496
- it("does not advance the persisted sequence or publish success when a write fails", async () => {
497
- const coordination = new SingleProcessCoordination({ scope: "failed-persistence" });
498
- const adapter = memoryAdapter();
499
- const write = adapter.applyCommittedTx;
500
- const apply = vi
501
- .spyOn(adapter, "applyCommittedTx")
502
- .mockRejectedValueOnce(new Error("disk full"))
503
- .mockImplementation(write);
504
- const coordinator = createPersistedCollectionCoordinator(coordination, adapter);
505
- const listener = vi.fn();
506
- const unsubscribe = coordinator.subscribe("items", listener);
507
- await expect(coordinator.requestApplyLocalMutations("items", [
508
- { mutationId: "first", type: "insert", key: "one", value: { id: "one" } },
509
- ])).rejects.toThrow("disk full");
510
- expect(listener).not.toHaveBeenCalled();
511
- await expect(coordinator.requestApplyLocalMutations("items", [
512
- { mutationId: "second", type: "insert", key: "two", value: { id: "two" } },
513
- ])).resolves.toMatchObject({ seq: 1, latestRowVersion: 1 });
514
- expect(apply).toHaveBeenCalledTimes(2);
515
- unsubscribe();
516
- await coordination.close();
517
- });
518
- it("keeps a scoped adapter until its last subscription closes and supports reopening", async () => {
519
- const coordination = new SingleProcessCoordination({ scope: "scoped-cleanup" });
520
- const root = memoryAdapter();
521
- const rootPosition = vi.spyOn(root, "getStreamPosition");
522
- const scoped = memoryAdapter();
523
- const scopedPosition = vi.spyOn(scoped, "getStreamPosition");
524
- const coordinator = createPersistedCollectionCoordinator(coordination, root);
525
- coordinator.setAdapterForCollection("items", scoped);
526
- const first = coordinator.subscribe("items", () => { });
527
- const second = coordinator.subscribe("items", () => { });
528
- first();
529
- first();
530
- await coordinator.pullSince("items", 0);
531
- expect(scopedPosition).toHaveBeenCalled();
532
- expect(rootPosition).not.toHaveBeenCalled();
533
- second();
534
- expect(Reflect.get(coordinator, "collectionAdapters").size).toBe(0);
535
- expect(Reflect.get(coordinator, "positions").size).toBe(0);
536
- scopedPosition.mockClear();
537
- await coordinator.pullSince("items", 0);
538
- expect(scopedPosition).not.toHaveBeenCalled();
539
- expect(rootPosition).toHaveBeenCalled();
540
- const reopened = memoryAdapter();
541
- const reopenedPosition = vi.spyOn(reopened, "getStreamPosition");
542
- coordinator.setAdapterForCollection("items", reopened);
543
- const close = coordinator.subscribe("items", () => { });
544
- await coordinator.pullSince("items", 0);
545
- expect(reopenedPosition).toHaveBeenCalled();
546
- close();
547
- await coordination.close();
548
- });
549
- it("routes pullSince to the scoped adapter and preserves its atomic stream position", async () => {
550
- const coordination = new SingleProcessCoordination({ scope: "scoped-replay" });
551
- const root = memoryAdapter();
552
- const coordinator = createPersistedCollectionCoordinator(coordination, root);
553
- const pullSince = vi.fn(() => Promise.resolve({
554
- latestTerm: 5,
555
- latestSeq: 7,
556
- latestRowVersion: 9,
557
- requiresFullReload: false,
558
- changedKeys: ["one"],
559
- deletedKeys: [],
560
- deltas: [],
561
- }));
562
- const scoped = { ...memoryAdapter(), pullSince };
563
- coordinator.setAdapterForCollection("items", scoped);
564
- expect(await coordinator.pullSince("items", 8)).toMatchObject({
565
- latestTerm: 5,
566
- latestSeq: 7,
567
- latestRowVersion: 9,
568
- requiresFullReload: false,
569
- changedKeys: ["one"],
570
- });
571
- expect(pullSince).toHaveBeenCalledWith("items", 8);
572
- await coordination.close();
573
- });
574
- });
575
- describe("worker schema fencing", () => {
576
- it("uses registered collection versions instead of the default adapter for worker RPCs", async () => {
577
- const channel = new MessageChannel();
578
- const hostCoordination = new SharedWorkerCoordinationHost({ scope: "resolved-worker-schema" });
579
- const disconnect = hostCoordination.connect(channel.port1);
580
- const clientCoordination = new SharedWorkerCoordinationClient({ scope: "resolved-worker-schema", worker: channel.port2 });
581
- const root = { ...memoryAdapter(), schemaVersion: 1 };
582
- const selected = { ...memoryAdapter(), schemaVersion: 2 };
583
- const apply = vi.spyOn(selected, "applyCommittedTx");
584
- const ensure = vi.spyOn(selected, "ensureIndex");
585
- const host = createPersistedCollectionCoordinator(hostCoordination, root);
586
- const client = createPersistedCollectionCoordinator(clientCoordination, root);
587
- host.setAdapterForCollection("items", selected);
588
- client.setAdapterForCollection("items", selected);
589
- const unsubscribeHost = host.subscribe("items", () => { });
590
- const unsubscribeClient = client.subscribe("items", () => { });
591
- try {
592
- await expect(client.requestApplyCommittedTx("items", { txId: "resolved", term: 1, seq: 1, rowVersion: 1, mutations: [] })).resolves.toMatchObject({ ok: true });
593
- await expect(client.requestEnsurePersistedIndex("items", "resolved-index", { expressionSql: [] })).resolves.toBeUndefined();
594
- expect(apply).toHaveBeenCalledOnce();
595
- expect(ensure).toHaveBeenCalledOnce();
596
- }
597
- finally {
598
- unsubscribeClient();
599
- unsubscribeHost();
600
- await clientCoordination.close();
601
- disconnect();
602
- await hostCoordination.close();
603
- }
604
- });
605
- it("rejects stale-schema worker writes and index requests", async () => {
606
- const channel = new MessageChannel();
607
- const hostCoordination = new SharedWorkerCoordinationHost({ scope: "schema-fencing" });
608
- const disconnect = hostCoordination.connect(channel.port1);
609
- const clientCoordination = new SharedWorkerCoordinationClient({
610
- scope: "schema-fencing",
611
- worker: channel.port2,
612
- });
613
- const current = { ...memoryAdapter(), schemaVersion: 2 };
614
- const stale = { ...memoryAdapter(), schemaVersion: 1 };
615
- const apply = vi.spyOn(current, "applyCommittedTx");
616
- const ensure = vi.spyOn(current, "ensureIndex");
617
- const host = createPersistedCollectionCoordinator(hostCoordination, current);
618
- const client = createPersistedCollectionCoordinator(clientCoordination, stale);
619
- host.setAdapterForCollection("items", current);
620
- client.setAdapterForCollection("items", stale);
621
- try {
622
- await expect(client.requestApplyLocalMutations("items", [
623
- { mutationId: "old-insert", type: "insert", key: "one", value: { id: "one" } },
624
- ])).rejects.toThrow("schema mismatch");
625
- await expect(client.requestApplyCommittedTx("items", { txId: "stale", term: 1, seq: 1, rowVersion: 1, mutations: [] }, stale)).rejects.toThrow("schema mismatch");
626
- await expect(client.requestEnsurePersistedIndex("items", "index", { expressionSql: [JSON.stringify({ type: "ref", path: ["id"] })] }, stale)).rejects.toThrow("schema mismatch");
627
- // SQLite scheduling scopes expose storage methods without schema fields.
628
- // The registered adapter must still supply the RPC's expected version.
629
- const hydrationAdapter = { ...stale, schemaVersion: undefined };
630
- await expect(client.requestApplyCommittedTx("items", { txId: "stale-scoped", term: 1, seq: 2, rowVersion: 2, mutations: [] }, hydrationAdapter)).rejects.toThrow("schema mismatch");
631
- await expect(client.requestEnsurePersistedIndex("items", "scoped-index", { expressionSql: [] }, hydrationAdapter)).rejects.toThrow("schema mismatch");
632
- expect(apply).not.toHaveBeenCalled();
633
- expect(ensure).not.toHaveBeenCalled();
634
- }
635
- finally {
636
- await clientCoordination.close();
637
- disconnect();
638
- await hostCoordination.close();
639
- }
640
- });
641
- });
642
- describe("persistence page resume", () => {
643
- it("checks durable positions, refreshes missed final writes, and releases browser listeners", async () => {
644
- const page = new EventTarget();
645
- const document = Object.assign(new EventTarget(), { visibilityState: "visible" });
646
- const removePage = vi.spyOn(page, "removeEventListener");
647
- const removeDocument = vi.spyOn(document, "removeEventListener");
648
- vi.stubGlobal("window", page);
649
- vi.stubGlobal("document", document);
650
- const coordination = new SingleProcessCoordination({ scope: "resume-final-write" });
651
- const adapter = memoryAdapter();
652
- const load = vi.spyOn(adapter, "loadSubset");
653
- const position = vi.spyOn(adapter, "getStreamPosition");
654
- const collection = createLocalCollection({
655
- name: "items", getKey: (item) => item.id,
656
- runtime: coordinatedRuntime({ adapter: { adapter }, coordination }).runtime,
657
- });
658
- try {
659
- await collection.preload();
660
- await collection.insert({ id: "one", title: "Original" }).isPersisted.promise;
661
- load.mockClear();
662
- // A durable adapter commit without its notification models a missed broadcast.
663
- await adapter.applyCommittedTx(collection.id, {
664
- txId: "missed", term: 1, seq: 2, rowVersion: 2,
665
- mutations: [{ type: "update", key: "one", value: { id: "one", title: "Final" } }],
666
- });
667
- expect(collection.get("one")?.title).toBe("Original");
668
- page.dispatchEvent(new Event("pageshow"));
669
- document.dispatchEvent(new Event("visibilitychange"));
670
- await vi.waitFor(() => expect(collection.get("one")?.title).toBe("Final"));
671
- load.mockClear();
672
- position.mockClear();
673
- page.dispatchEvent(new Event("focus"));
674
- await vi.waitFor(() => expect(position).toHaveBeenCalled());
675
- await new Promise((resolve) => setTimeout(resolve, 0));
676
- expect(load).not.toHaveBeenCalled();
677
- await collection.cleanup();
678
- expect(removePage).toHaveBeenCalledTimes(2);
679
- expect(removeDocument).toHaveBeenCalledOnce();
680
- position.mockClear();
681
- page.dispatchEvent(new Event("pageshow"));
682
- expect(position).not.toHaveBeenCalled();
683
- }
684
- finally {
685
- await collection.cleanup();
686
- await coordination.close();
687
- vi.unstubAllGlobals();
688
- }
689
- });
690
- it("ignores hidden visibility changes and pending checks after unsubscribe", async () => {
691
- const page = new EventTarget();
692
- const document = Object.assign(new EventTarget(), { visibilityState: "hidden" });
693
- vi.stubGlobal("window", page);
694
- vi.stubGlobal("document", document);
695
- const coordination = new SingleProcessCoordination({ scope: "resume-cleanup" });
696
- const adapter = memoryAdapter();
697
- let finish;
698
- const read = vi.spyOn(adapter, "getStreamPosition").mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
699
- const shim = createPersistedCollectionCoordinator(coordination, adapter);
700
- const callback = vi.fn();
701
- const unsubscribe = shim.subscribe("items", callback);
702
- try {
703
- document.dispatchEvent(new Event("visibilitychange"));
704
- page.dispatchEvent(new Event("focus"));
705
- expect(read).not.toHaveBeenCalled();
706
- page.dispatchEvent(new Event("pageshow"));
707
- expect(read).toHaveBeenCalledOnce();
708
- unsubscribe();
709
- unsubscribe();
710
- finish({ latestTerm: 1, latestSeq: 5, latestRowVersion: 5 });
711
- await new Promise((resolve) => setTimeout(resolve, 0));
712
- expect(callback).not.toHaveBeenCalled();
713
- expect(Reflect.get(shim, "resumeChecks").size).toBe(0);
714
- }
715
- finally {
716
- unsubscribe();
717
- await coordination.close();
718
- vi.unstubAllGlobals();
719
- }
720
- });
721
- });
722
- describe("overlapping local mutation consumers", () => {
723
- it("reconciles concurrent peers without retaining mutation bursts after cleanup", async () => {
724
- const coordination = new SingleProcessCoordination({ scope: "overlapping-local-peers" });
725
- const adapter = memoryAdapter();
726
- const runtime = coordinatedRuntime({ adapter: { adapter }, coordination }).runtime;
727
- const first = createLocalCollection({ name: "items", runtime, getKey: (item) => item.id });
728
- const second = createLocalCollection({ name: "items", runtime, getKey: (item) => item.id });
729
- const items = Array.from({ length: 20 }, (_, index) => ({ id: String(index), title: `Task ${index}` }));
730
- try {
731
- await Promise.all([first.preload(), second.preload()]);
732
- await Promise.all(items.map((item, index) => (index % 2 ? first : second).insert(item).isPersisted.promise));
733
- await vi.waitFor(() => {
734
- expect(first.size).toBe(20);
735
- expect(second.size).toBe(20);
736
- });
737
- await Promise.all([first.cleanup(), second.cleanup()]);
738
- const shim = createPersistedCollectionCoordinator(coordination, adapter);
739
- expect(Reflect.get(shim, "localMutationBursts").size).toBe(0);
740
- expect(Reflect.get(shim, "resumeChecks").size).toBe(0);
741
- }
742
- finally {
743
- await Promise.all([first.cleanup(), second.cleanup()]);
744
- await coordination.close();
745
- }
746
- });
747
- });
748
- //# sourceMappingURL=createLocalCollection.test.js.map