@party-stack/runtime 0.3.7 → 0.4.0

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.
@@ -1,6 +1,7 @@
1
- import { SingleProcessCoordination, } from "@party-stack/coordination";
1
+ import { SingleProcessCoordination } from "@party-stack/coordination";
2
2
  import { SharedWorkerCoordinationClient, SharedWorkerCoordinationHost, } from "@party-stack/coordination/shared-worker";
3
- import { describe, expect, it, vi, } from "vitest";
3
+ import { SingleProcessCoordinator } from "@tanstack/db-sqlite-persistence-core";
4
+ import { describe, expect, it, vi } from "vitest";
4
5
  import { createPersistedCollectionCoordinator } from "../coordinator/createPersistedCollectionCoordinator.js";
5
6
  import { MemoryBlobBytesStore } from "../memory/MemoryBlobBytesStore.js";
6
7
  import { createLocalCollection } from "./createLocalCollection.js";
@@ -16,6 +17,12 @@ function memoryAdapter() {
16
17
  return collection;
17
18
  };
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
+ }),
19
26
  loadSubset: (collectionId) => Promise.resolve([...rows(collectionId)].map(([key, value]) => ({
20
27
  key,
21
28
  value,
@@ -94,7 +101,16 @@ describe("createLocalCollection", () => {
94
101
  },
95
102
  },
96
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
+ }));
97
112
  const adapter = {
113
+ loadResumeSnapshot,
98
114
  loadSubset,
99
115
  applyCommittedTx: vi.fn(() => Promise.resolve()),
100
116
  ensureIndex: vi.fn(() => Promise.resolve()),
@@ -109,12 +125,12 @@ describe("createLocalCollection", () => {
109
125
  owner: "test-owner",
110
126
  namespace: "persisted",
111
127
  blobBytes: new MemoryBlobBytesStore(),
112
- persistence: adapter,
128
+ persistence: { adapter },
113
129
  coordination,
114
130
  },
115
131
  });
116
132
  await collection.preload();
117
- expect(loadSubset).toHaveBeenCalledWith("party-stack:test-owner:persisted:persisted-items", expect.any(Object), expect.any(Object));
133
+ expect(loadResumeSnapshot).toHaveBeenCalledWith("party-stack:test-owner:persisted:persisted-items", expect.any(Object));
118
134
  expect(collection.get("one")).toMatchObject({
119
135
  id: "one",
120
136
  title: "Persisted",
@@ -128,11 +144,11 @@ describe("createLocalCollection", () => {
128
144
  scope: "local-collection-test",
129
145
  });
130
146
  const firstRuntime = coordinatedRuntime({
131
- adapter,
147
+ adapter: { adapter },
132
148
  coordination,
133
149
  });
134
150
  const secondRuntime = coordinatedRuntime({
135
- adapter,
151
+ adapter: { adapter },
136
152
  coordination,
137
153
  });
138
154
  const createItems = ({ runtime }) => createLocalCollection({
@@ -161,26 +177,114 @@ describe("createLocalCollection", () => {
161
177
  scope: "remote-subset-test",
162
178
  });
163
179
  const first = coordinatedRuntime({
164
- adapter,
180
+ adapter: { adapter },
165
181
  coordination,
166
182
  });
167
183
  const second = coordinatedRuntime({
168
- adapter,
184
+ adapter: { adapter },
169
185
  coordination,
170
186
  });
171
187
  const firstCoordinator = createPersistedCollectionCoordinator(first.coordination, adapter);
172
188
  const secondCoordinator = createPersistedCollectionCoordinator(second.coordination, adapter);
173
- await expect(secondCoordinator.requestEnsureRemoteSubset?.("items", {
174
- signal: new AbortController().signal,
175
- subscription: {
176
- callback: () => undefined,
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;
177
199
  },
178
- })).resolves.toBeUndefined();
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();
179
210
  await expect(firstCoordinator.requestEnsurePersistedIndex("items", "index", {
180
211
  expressionSql: [],
181
212
  })).resolves.toBeUndefined();
182
213
  await coordination.close();
183
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
+ });
184
288
  it("routes client-only persistence through a SharedWorker host", async () => {
185
289
  const adapter = memoryAdapter();
186
290
  const channel = new MessageChannel();
@@ -199,7 +303,7 @@ describe("createLocalCollection", () => {
199
303
  owner: "test-owner",
200
304
  namespace: "worker",
201
305
  blobBytes: new MemoryBlobBytesStore(),
202
- persistence: adapter,
306
+ persistence: { adapter },
203
307
  coordination: hostCoordination,
204
308
  },
205
309
  });
@@ -210,14 +314,11 @@ describe("createLocalCollection", () => {
210
314
  owner: "test-owner",
211
315
  namespace: "worker",
212
316
  blobBytes: new MemoryBlobBytesStore(),
213
- persistence: adapter,
317
+ persistence: { adapter },
214
318
  coordination: clientCoordination,
215
319
  },
216
320
  });
217
- await Promise.all([
218
- host.preload(),
219
- client.preload(),
220
- ]);
321
+ await Promise.all([host.preload(), client.preload()]);
221
322
  await client.insert({
222
323
  id: "one",
223
324
  title: "From client",
@@ -227,6 +328,16 @@ describe("createLocalCollection", () => {
227
328
  expect(client.get("one")?.title).toBe("From client");
228
329
  });
229
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" } }]));
230
341
  await client.cleanup();
231
342
  await host.cleanup();
232
343
  await clientCoordination.close();
@@ -234,4 +345,404 @@ describe("createLocalCollection", () => {
234
345
  await hostCoordination.close();
235
346
  });
236
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
+ });
237
748
  //# sourceMappingURL=createLocalCollection.test.js.map