Open History to see the last commit
1/**
2 * Ordinary tests for persistedCollectionOptions startup: descriptor and runtime ownership, startup metadata reload, and sync-config validation, as fixed scenarios. The startup and ownership laws they touch are owned by persisted-oracle.test.ts, which keeps its generated and model-checked cases.
3 */
4import { describe, expect, it, vi } from 'vitest'
5import {
6 BasicIndex,
7 DbClient,
8 collectionOptions,
9 createCollection,
10 createTransaction,
11} from '@tanstack/db'
12import {
13 IndeterminateCommitError,
14 InvalidPersistedCollectionConfigError,
15 InvalidSyncConfigError,
16 persistedCollectionOptions,
17} from '../src'
18import {
19 atPersistedOracleCheckpoint,
20 cleanupPersistedOracle,
21 createCoordinatorHarness,
22 createEventGate,
23 createNoopAdapter,
24 createRecordingAdapter,
25 flushAsyncWork,
26 stripVirtualProps,
27} from './persisted-support'
28import type { PersistedSyncWrappedOptions } from '../src'
29import type { Todo, TodoSyncParams } from './persisted-support'
30
31describe(`persistedCollectionOptions`, () => {
32 // A descriptor's one-owner claim is consumed by a constructed Collection,
33 // not by a constructor attempt that failed before binding the runtime.
34 // The independent admission model has unclaimed and claimed states; this
35 // invalid-then-corrected history must remain unclaimed after the first
36 // throw. The checkpoint is the second createCollection call and its later
37 // durable write. A successful first construction is checked below.
38 it(`permits a corrected descriptor after construction fails before owner binding`, async () => {
39 const adapter = createRecordingAdapter()
40 const options = persistedCollectionOptions<Todo, string>({
41 id: `failed-construction-retry`,
42 getKey: (row) => row.id,
43 autoIndex: `eager`,
44 persistence: { adapter },
45 })
46 expect(() => createCollection(options)).toThrow(/autoIndex/)
47 options.defaultIndexType = BasicIndex
48 const collection = createCollection(options)
49 let unexpectedThird: typeof collection | undefined
50 let hasPrimaryFailure = false
51 try {
52 await collection.stateWhenReady()
53 expect(() => {
54 unexpectedThird = createCollection(options)
55 }).toThrow(InvalidPersistedCollectionConfigError)
56 const receipt = collection.insert({ id: `owned`, title: `Retried owner` })
57 await receipt.isPersisted.promise
58 expect(stripVirtualProps(collection.get(`owned`))).toEqual({
59 id: `owned`,
60 title: `Retried owner`,
61 })
62 expect(adapter.rows.get(`owned`)).toEqual({
63 id: `owned`,
64 title: `Retried owner`,
65 })
66 } catch (error) {
67 hasPrimaryFailure = true
68 throw error
69 } finally {
70 await cleanupPersistedOracle(
71 [() => unexpectedThird?.cleanup(), () => collection.cleanup()],
72 hasPrimaryFailure,
73 )
74 }
75 })
76
77 // Law: only a successfully constructed Collection consumes an options
78 // descriptor. The same unclaimed -> claimed admission model applies if a
79 // synchronous collaborator fails after sync startup begins. The first
80 // attempt must expose that failure; after correction, the same descriptor
81 // must construct and persist normally. This tests the public constructor
82 // and durability receipt, rather than inspecting the private claim flag.
83 // Both local-only and wrapped-source startup bind through distinct paths.
84 // A subscription ledger checks that the failed attempt has no live listener,
85 // the corrected owner has one, and cleanup releases it.
86 it.each([`local-only`, `wrapped source`] as const)(
87 `permits a corrected %s descriptor after sync-start construction fails`,
88 async (mode) => {
89 const adapter = createRecordingAdapter()
90 const coordinator = createCoordinatorHarness()
91 coordinator.requestApplyCommittedTx = async (collectionId, tx) => {
92 await adapter.applyCommittedTx({ kind: `eager`, collectionId }, tx)
93 return {
94 type: `rpc:applyCommittedTx:res`,
95 rpcId: tx.txId,
96 ok: true,
97 term: tx.term,
98 seq: tx.seq,
99 latestRowVersion: tx.rowVersion,
100 }
101 }
102 const subscribe = coordinator.subscribe.bind(coordinator)
103 const fault = new Error(`coordinator subscription failed`)
104 let failSubscription = true
105 let activeSubscriptions = 0
106 coordinator.subscribe = (...args) => {
107 if (failSubscription) throw fault
108 const unsubscribe = subscribe(...args)
109 activeSubscriptions++
110 return () => {
111 activeSubscriptions--
112 unsubscribe()
113 }
114 }
115 const base = {
116 id: `failed-sync-start-construction-retry-${mode}`,
117 getKey: (row: Todo) => row.id,
118 startSync: true as const,
119 persistence: { adapter, coordinator },
120 }
121 let source!: TodoSyncParams
122 const construct =
123 mode === `wrapped source`
124 ? (() => {
125 const options = persistedCollectionOptions<Todo, string>({
126 ...base,
127 sync: {
128 sync: (params) => {
129 source = params
130 params.markReady()
131 },
132 },
133 })
134 return () => createCollection(options)
135 })()
136 : (() => {
137 const options = persistedCollectionOptions<Todo, string>(base)
138 return () => createCollection(options)
139 })()
140 expect(construct).toThrow(fault)
141 expect(activeSubscriptions).toBe(0)
142 failSubscription = false
143 const collection = construct()
144 let unexpectedThird: typeof collection | undefined
145 let hasPrimaryFailure = false
146 try {
147 await collection.stateWhenReady()
148 expect(activeSubscriptions).toBe(1)
149 if (mode === `wrapped source`) await flushAsyncWork()
150 expect(() => {
151 unexpectedThird = construct()
152 }).toThrow(InvalidPersistedCollectionConfigError)
153 const row = { id: `owned`, title: `Retried owner` }
154 if (mode === `wrapped source`) {
155 source.begin()
156 source.write({ type: `insert`, value: row })
157 await source.commit()
158 } else {
159 await collection.insert(row).isPersisted.promise
160 }
161 expect(stripVirtualProps(collection.get(`owned`))).toEqual({
162 id: `owned`,
163 title: `Retried owner`,
164 })
165 expect(adapter.rows.get(`owned`)).toEqual({
166 id: `owned`,
167 title: `Retried owner`,
168 })
169 } catch (error) {
170 hasPrimaryFailure = true
171 throw error
172 } finally {
173 await cleanupPersistedOracle(
174 [
175 () => unexpectedThird?.cleanup(),
176 () => collection.cleanup(),
177 () => {
178 expect(activeSubscriptions).toBe(0)
179 },
180 ],
181 hasPrimaryFailure,
182 )
183 }
184 },
185 )
186
187 // A persisted options descriptor owns one mutable runtime. The independent
188 // ownership rule is one Collection per descriptor, including a spread copy:
189 // copying fields cannot create a second runtime. The public creation boundary
190 // must reject the second Collection before it can redirect the first one's
191 // writes. Fresh descriptors remain legal and are covered elsewhere here and
192 // by DbClient materialization. The checkpoint is createCollection itself,
193 // then the first owner's durable receipt and public row after the rejection.
194 it.each([`same object`, `spread copy`] as const)(
195 `keeps one persisted options runtime bound to its first Collection (%s)`,
196 async (reuse) => {
197 const adapter = createRecordingAdapter()
198 const options = persistedCollectionOptions<Todo, string>({
199 id: `one-owner-${reuse}`,
200 getKey: (row) => row.id,
201 persistence: { adapter },
202 })
203 const first = createCollection(options)
204 let second: typeof first | undefined
205 let hasPrimaryFailure = false
206 try {
207 await first.stateWhenReady()
208 expect(() => {
209 second = createCollection(
210 reuse === `same object` ? options : { ...options },
211 )
212 }).toThrow(InvalidPersistedCollectionConfigError)
213
214 const receipt = first.insert({ id: `owned`, title: `First owner` })
215 await receipt.isPersisted.promise
216 expect(stripVirtualProps(first.get(`owned`))).toEqual({
217 id: `owned`,
218 title: `First owner`,
219 })
220 expect(adapter.rows.get(`owned`)).toEqual({
221 id: `owned`,
222 title: `First owner`,
223 })
224 } catch (error) {
225 hasPrimaryFailure = true
226 throw error
227 } finally {
228 await cleanupPersistedOracle(
229 [() => second?.cleanup(), () => first.cleanup()],
230 hasPrimaryFailure,
231 )
232 }
233 },
234 )
235
236 // The same ownership rule applies when an upstream sync source is wrapped.
237 // A source commit through the first Collection must remain public and durable
238 // after a second Collection is rejected at admission.
239 it.each([`same object`, `spread copy`] as const)(
240 `keeps a wrapped sync source bound to its first Collection (%s)`,
241 async (reuse) => {
242 const adapter = createRecordingAdapter()
243 let source!: TodoSyncParams
244 const options = persistedCollectionOptions<Todo, string>({
245 id: `one-source-owner-${reuse}`,
246 getKey: (row) => row.id,
247 sync: {
248 sync: (params) => {
249 source = params
250 params.markReady()
251 },
252 },
253 persistence: { adapter },
254 })
255 const first = createCollection(options)
256 let second: typeof first | undefined
257 let hasPrimaryFailure = false
258 try {
259 await first.stateWhenReady()
260 expect(() => {
261 second = createCollection(
262 reuse === `same object` ? options : { ...options },
263 )
264 }).toThrow(InvalidPersistedCollectionConfigError)
265
266 source.begin()
267 source.write({
268 type: `insert`,
269 value: { id: `owned`, title: `First source` },
270 })
271 await Promise.resolve(source.commit())
272 expect(stripVirtualProps(first.get(`owned`))).toEqual({
273 id: `owned`,
274 title: `First source`,
275 })
276 expect(adapter.rows.get(`owned`)).toEqual({
277 id: `owned`,
278 title: `First source`,
279 })
280 } catch (error) {
281 hasPrimaryFailure = true
282 throw error
283 } finally {
284 await cleanupPersistedOracle(
285 [() => second?.cleanup(), () => first.cleanup()],
286 hasPrimaryFailure,
287 )
288 }
289 },
290 )
291
292 // Selecting only the public sync config bypasses the descriptor's claim.
293 // The runtime's fallback guard must reject that second Collection before
294 // changing the first owner's controls. This is a legal JavaScript copy of
295 // the exposed config, not a second independent persisted options runtime.
296 it.each([`local-only`, `sync-present`] as const)(
297 `preserves the first owner after a copied sync config is rejected (%s)`,
298 async (mode) => {
299 const adapter = createRecordingAdapter()
300 let source!: TodoSyncParams
301 const base = {
302 id: `selected-sync-${mode}`,
303 getKey: (row: Todo) => row.id,
304 persistence: { adapter },
305 }
306 const options =
307 mode === `sync-present`
308 ? persistedCollectionOptions<Todo, string>({
309 ...base,
310 sync: {
311 sync: (params) => {
312 source = params
313 params.markReady()
314 },
315 },
316 })
317 : persistedCollectionOptions<Todo, string>(base)
318 const first = createCollection(options)
319 const second = createCollection({
320 id: `unclaimed-${mode}`,
321 getKey: (row: Todo) => row.id,
322 sync: options.sync,
323 startSync: false,
324 })
325 let hasPrimaryFailure = false
326 try {
327 await first.stateWhenReady()
328 if (mode === `sync-present`) {
329 source.begin()
330 source.write({
331 type: `insert`,
332 value: { id: `owned`, title: `First source` },
333 })
334 }
335 expect(() => second.startSyncImmediate()).toThrow(
336 InvalidPersistedCollectionConfigError,
337 )
338
339 if (mode === `sync-present`) {
340 await Promise.resolve(source.commit())
341 } else {
342 await first.insert({ id: `owned`, title: `First owner` }).isPersisted
343 .promise
344 }
345 expect(first.has(`owned`)).toBe(true)
346 expect(second.has(`owned`)).toBe(false)
347 expect(adapter.rows.get(`owned`)?.id).toBe(`owned`)
348 } catch (error) {
349 hasPrimaryFailure = true
350 throw error
351 } finally {
352 await cleanupPersistedOracle(
353 [() => second.cleanup(), () => first.cleanup()],
354 hasPrimaryFailure,
355 )
356 }
357 },
358 )
359
360 // Construction, rather than first sync startup, assigns the descriptor's
361 // Collection owner. A lazy wrapped source leaves a legal interval in which a
362 // second Collection can select only its public sync field and start first.
363 // The independent admission rule still gives the first constructed owner
364 // the runtime; the selected copy must fail before it installs controls.
365 it(`rejects a selected sync that starts before its lazy descriptor owner`, async () => {
366 const adapter = createRecordingAdapter()
367 let source!: TodoSyncParams
368 const options = persistedCollectionOptions<Todo, string>({
369 id: `lazy-selected-sync-owner`,
370 getKey: (row) => row.id,
371 startSync: false,
372 sync: {
373 sync: (params) => {
374 source = params
375 params.markReady()
376 },
377 },
378 persistence: { adapter },
379 })
380 const first = createCollection(options)
381 const selected = createCollection({
382 id: `lazy-selected-sync-copy`,
383 getKey: (row: Todo) => row.id,
384 sync: options.sync,
385 startSync: false,
386 })
387 let hasPrimaryFailure = false
388 try {
389 expect(() => selected.startSyncImmediate()).toThrow(
390 InvalidPersistedCollectionConfigError,
391 )
392 first.startSyncImmediate()
393 await first.stateWhenReady()
394 source.begin()
395 source.write({
396 type: `insert`,
397 value: { id: `owned`, title: `Original owner` },
398 })
399 await Promise.resolve(source.commit())
400 expect(stripVirtualProps(first.get(`owned`))).toEqual({
401 id: `owned`,
402 title: `Original owner`,
403 })
404 expect(selected.has(`owned`)).toBe(false)
405 expect(adapter.rows.get(`owned`)).toEqual({
406 id: `owned`,
407 title: `Original owner`,
408 })
409 } catch (error) {
410 hasPrimaryFailure = true
411 throw error
412 } finally {
413 await cleanupPersistedOracle(
414 [() => selected.cleanup(), () => first.cleanup()],
415 hasPrimaryFailure,
416 )
417 }
418 })
419
420 it(`does not reuse a persisted runtime after its Collection cleans up`, async () => {
421 const options = persistedCollectionOptions<Todo, string>({
422 id: `cleaned-up-owner`,
423 getKey: (row) => row.id,
424 persistence: { adapter: createRecordingAdapter() },
425 })
426 const first = createCollection(options)
427 await first.cleanup()
428 expect(() => createCollection(options)).toThrow(
429 InvalidPersistedCollectionConfigError,
430 )
431 })
432
433 // Cleanup ends a sync run, not the descriptor's permanent Collection claim.
434 // Selecting only the wrapped sync field omits the public claim hook, so this
435 // history checks the runtime guard after cleanup and the original owner's
436 // ability to restart. The two modes cross local and upstream source controls.
437 it.each([`local-only`, `sync-present`] as const)(
438 `rejects a copied sync owner after cleanup and permits the first owner to restart (%s)`,
439 async (mode) => {
440 const adapter = createRecordingAdapter()
441 let source!: TodoSyncParams
442 const base = {
443 id: `cleaned-selected-sync-${mode}`,
444 getKey: (row: Todo) => row.id,
445 persistence: { adapter },
446 }
447 const options =
448 mode === `sync-present`
449 ? persistedCollectionOptions<Todo, string>({
450 ...base,
451 sync: {
452 sync: (params) => {
453 source = params
454 params.markReady()
455 },
456 },
457 })
458 : persistedCollectionOptions<Todo, string>(base)
459 const first = createCollection(options)
460 const second = createCollection({
461 id: `post-cleanup-copy-${mode}`,
462 getKey: (row: Todo) => row.id,
463 sync: options.sync,
464 startSync: false,
465 })
466 let hasPrimaryFailure = false
467 try {
468 await first.stateWhenReady()
469 await first.cleanup()
470 expect(() => second.startSyncImmediate()).toThrow(
471 InvalidPersistedCollectionConfigError,
472 )
473
474 const replacementReady = createEventGate()
475 const unsubscribe = first.on(`status:ready`, () =>
476 replacementReady.resolve(),
477 )
478 try {
479 first.startSyncImmediate()
480 await atPersistedOracleCheckpoint(
481 replacementReady.promise,
482 `original persisted owner restarts`,
483 )
484 } finally {
485 unsubscribe()
486 }
487
488 if (mode === `sync-present`) {
489 source.begin()
490 source.write({
491 type: `insert`,
492 value: { id: `after-restart`, title: `First source` },
493 })
494 await Promise.resolve(source.commit())
495 } else {
496 await first.insert({ id: `after-restart`, title: `First owner` })
497 .isPersisted.promise
498 }
499 expect(first.has(`after-restart`)).toBe(true)
500 expect(second.has(`after-restart`)).toBe(false)
501 expect(adapter.rows.get(`after-restart`)?.id).toBe(`after-restart`)
502 } catch (error) {
503 hasPrimaryFailure = true
504 throw error
505 } finally {
506 await cleanupPersistedOracle(
507 [() => second.cleanup(), () => first.cleanup()],
508 hasPrimaryFailure,
509 )
510 }
511 },
512 )
513
514 it(`materializes one independent persisted runtime for each DbClient`, async () => {
515 const adapter = createRecordingAdapter([{ id: `stored`, title: `Stored` }])
516 const descriptor = collectionOptions(
517 persistedCollectionOptions<Todo, string>({
518 id: `client-owned-persistence`,
519 getKey: (row) => row.id,
520 persistence: { adapter },
521 }),
522 )
523 const firstClient = new DbClient()
524 const secondClient = new DbClient()
525 let hasPrimaryFailure = false
526 try {
527 const first = firstClient.collection(descriptor)
528 const second = secondClient.collection(descriptor)
529 expect(first).not.toBe(second)
530 await Promise.all([first.stateWhenReady(), second.stateWhenReady()])
531 expect(stripVirtualProps(first.get(`stored`))).toEqual({
532 id: `stored`,
533 title: `Stored`,
534 })
535 expect(stripVirtualProps(second.get(`stored`))).toEqual({
536 id: `stored`,
537 title: `Stored`,
538 })
539 } catch (error) {
540 hasPrimaryFailure = true
541 throw error
542 } finally {
543 await cleanupPersistedOracle(
544 [() => secondClient.cleanup(), () => firstClient.cleanup()],
545 hasPrimaryFailure,
546 )
547 }
548 })
549
550 it(`preserves exact reconciliation context for an indeterminate commit`, () => {
551 const cause = new Error(`response channel closed`)
552 const error = new IndeterminateCommitError({
553 collectionId: `todos`,
554 requestType: `rpc:applyCommittedTx:req`,
555 previousLeaderId: `leader-a`,
556 previousTerm: 4,
557 currentLeaderId: `leader-b`,
558 currentTerm: 5,
559 cause,
560 })
561
562 expect(error).toMatchObject({
563 name: `IndeterminateCommitError`,
564 code: `INDETERMINATE_COMMIT`,
565 collectionId: `todos`,
566 requestType: `rpc:applyCommittedTx:req`,
567 previousLeaderId: `leader-a`,
568 previousTerm: 4,
569 currentLeaderId: `leader-b`,
570 currentTerm: 5,
571 cause,
572 })
573 expect(error.message).toContain(
574 `rpc:applyCommittedTx:req crossed leadership from leader-a (term 4) to leader-b (term 5)`,
575 )
576 })
577
578 it(`provides a sync-absent loopback configuration with persisted utils`, async () => {
579 const adapter = createRecordingAdapter()
580 const collection = createCollection(
581 persistedCollectionOptions<Todo, string>({
582 id: `persisted-loopback`,
583 getKey: (item) => item.id,
584 persistence: {
585 adapter,
586 },
587 }),
588 )
589
590 const insertTx = collection.insert({
591 id: `1`,
592 title: `Phase 0`,
593 })
594
595 await insertTx.isPersisted.promise
596
597 expect(stripVirtualProps(collection.get(`1`))).toEqual({
598 id: `1`,
599 title: `Phase 0`,
600 })
601 expect(adapter.applyCommittedTxCalls).toHaveLength(1)
602 expect(adapter.applyCommittedTxCalls[0]?.tx.mutations[0]?.type).toBe(
603 `insert`,
604 )
605 expect(typeof collection.utils.acceptMutations).toBe(`function`)
606 expect(collection.utils.getLeadershipState?.().isLeader).toBe(true)
607 })
608
609 it(`hydrates a local-only baseline after a managed write advances startup evidence`, async () => {
610 const adapter = createRecordingAdapter([
611 { id: `baseline`, title: `Persisted before startup` },
612 ])
613 const loadResumeSnapshot = adapter.loadResumeSnapshot.bind(adapter)
614 let releaseInitialSnapshot!: () => void
615 const initialSnapshotRelease = new Promise<void>((resolve) => {
616 releaseInitialSnapshot = resolve
617 })
618 let reportInitialSnapshot!: () => void
619 const initialSnapshotCaptured = new Promise<void>((resolve) => {
620 reportInitialSnapshot = resolve
621 })
622 let snapshotCalls = 0
623 adapter.loadResumeSnapshot = async (...args) => {
624 const snapshot = await loadResumeSnapshot(...args)
625 snapshotCalls++
626 if (snapshotCalls === 1) {
627 reportInitialSnapshot()
628 await initialSnapshotRelease
629 }
630 return snapshot
631 }
632
633 const collection = createCollection(
634 persistedCollectionOptions<Todo, string>({
635 id: `local-only-startup-write`,
636 startSync: false,
637 getKey: (item) => item.id,
638 persistence: { adapter },
639 }),
640 )
641
642 try {
643 collection.startSyncImmediate()
644 await initialSnapshotCaptured
645
646 const insert = collection.insert({
647 id: `concurrent`,
648 title: `Managed during startup`,
649 })
650 releaseInitialSnapshot()
651 await insert.isPersisted.promise
652 await collection.stateWhenReady()
653 await vi.waitFor(() => expect(snapshotCalls).toBeGreaterThanOrEqual(2))
654
655 expect(
656 Array.from(collection.values(), (row) => stripVirtualProps(row)).sort(
657 (left, right) => left.id.localeCompare(right.id),
658 ),
659 ).toEqual([
660 { id: `baseline`, title: `Persisted before startup` },
661 { id: `concurrent`, title: `Managed during startup` },
662 ])
663 } finally {
664 releaseInitialSnapshot()
665 await collection.cleanup()
666 }
667 })
668
669 it(`supports acceptMutations for manual transactions`, async () => {
670 const adapter = createRecordingAdapter()
671 const collection = createCollection(
672 persistedCollectionOptions<Todo, string>({
673 id: `persisted-manual`,
674 getKey: (item) => item.id,
675 persistence: {
676 adapter,
677 },
678 }),
679 )
680
681 const tx = createTransaction({
682 autoCommit: false,
683 mutationFn: async ({ transaction }) => {
684 await collection.utils.acceptMutations(transaction)
685 },
686 })
687
688 tx.mutate(() => {
689 collection.insert({
690 id: `manual-1`,
691 title: `Manual`,
692 })
693 })
694
695 await tx.commit()
696
697 expect(stripVirtualProps(collection.get(`manual-1`))).toEqual({
698 id: `manual-1`,
699 title: `Manual`,
700 })
701 expect(adapter.applyCommittedTxCalls).toHaveLength(1)
702 })
703
704 it(`loads collection metadata into collection state during startup`, async () => {
705 const adapter = createRecordingAdapter()
706 adapter.collectionMetadata.set(`electric:resume`, {
707 kind: `resume`,
708 offset: `10_0`,
709 handle: `handle-1`,
710 shapeId: `shape-1`,
711 updatedAt: 1,
712 })
713
714 const collection = createCollection(
715 persistedCollectionOptions<Todo, string>({
716 id: `persisted-startup-metadata`,
717 getKey: (item) => item.id,
718 persistence: {
719 adapter,
720 },
721 }),
722 )
723
724 await collection.stateWhenReady()
725
726 expect(adapter.loadResumeSnapshotCalls[0]).toMatchObject({
727 collectionId: `persisted-startup-metadata`,
728 includeRows: false,
729 })
730 expect(
731 collection._state.syncedCollectionMetadata.get(`electric:resume`),
732 ).toEqual({
733 kind: `resume`,
734 offset: `10_0`,
735 handle: `handle-1`,
736 shapeId: `shape-1`,
737 updatedAt: 1,
738 })
739 })
740
741 it(`restores row and collection metadata after metadata-bearing full reload`, async () => {
742 const adapter = createRecordingAdapter([
743 {
744 id: `1`,
745 title: `Tracked`,
746 },
747 ])
748 adapter.rowMetadata.set(`1`, {
749 source: `initial`,
750 })
751 adapter.collectionMetadata.set(`electric:resume`, {
752 kind: `resume`,
753 offset: `10_0`,
754 handle: `handle-1`,
755 shapeId: `shape-1`,
756 updatedAt: 1,
757 })
758 const coordinator = createCoordinatorHarness()
759
760 const collection = createCollection(
761 persistedCollectionOptions<Todo, string>({
762 id: `sync-present`,
763 getKey: (item) => item.id,
764 sync: {
765 sync: ({ markReady }) => {
766 markReady()
767 },
768 },
769 persistence: {
770 adapter,
771 coordinator,
772 },
773 }),
774 )
775
776 await collection.preload()
777 await flushAsyncWork()
778
779 expect(collection._state.syncedMetadata.get(`1`)).toEqual({
780 source: `initial`,
781 })
782 expect(
783 collection._state.syncedCollectionMetadata.get(`electric:resume`),
784 ).toEqual({
785 kind: `resume`,
786 offset: `10_0`,
787 handle: `handle-1`,
788 shapeId: `shape-1`,
789 updatedAt: 1,
790 })
791
792 adapter.rowMetadata.set(`1`, {
793 source: `reloaded`,
794 })
795 adapter.collectionMetadata.delete(`electric:resume`)
796 adapter.collectionMetadata.set(`queryCollection:gc:q1`, {
797 queryHash: `q1`,
798 mode: `until-revalidated`,
799 })
800
801 coordinator.emit({
802 type: `tx:committed`,
803 term: 1,
804 seq: 1,
805 txId: `tx-reload`,
806 latestRowVersion: 1,
807 requiresFullReload: true,
808 })
809
810 await flushAsyncWork()
811 await flushAsyncWork()
812
813 expect(collection._state.syncedMetadata.get(`1`)).toEqual({
814 source: `reloaded`,
815 })
816 expect(
817 collection._state.syncedCollectionMetadata.has(`electric:resume`),
818 ).toBe(false)
819 expect(
820 collection._state.syncedCollectionMetadata.get(`queryCollection:gc:q1`),
821 ).toEqual({
822 queryHash: `q1`,
823 mode: `until-revalidated`,
824 })
825 })
826
827 it(`persists metadata-only wrapped sync transactions`, async () => {
828 const adapter = createRecordingAdapter()
829
830 const collection = createCollection(
831 persistedCollectionOptions<Todo, string>({
832 id: `persisted-metadata-only`,
833 getKey: (item) => item.id,
834 sync: {
835 sync: ({ begin, commit, markReady, metadata }) => {
836 begin()
837 metadata?.collection.set(`runtime:key`, { persisted: true })
838 commit()
839 markReady()
840 },
841 },
842 persistence: {
843 adapter,
844 },
845 }),
846 )
847
848 await collection.stateWhenReady()
849 await flushAsyncWork()
850
851 expect(adapter.applyCommittedTxCalls).toHaveLength(1)
852 expect(adapter.applyCommittedTxCalls[0]?.tx.mutations).toEqual([])
853 expect(adapter.collectionMetadata.get(`runtime:key`)).toEqual({
854 persisted: true,
855 })
856 expect(
857 collection._state.syncedCollectionMetadata.get(`runtime:key`),
858 ).toEqual({
859 persisted: true,
860 })
861 })
862
863 it(`replays metadata-only tx:committed deltas without full reload`, async () => {
864 const adapter = createRecordingAdapter([
865 {
866 id: `1`,
867 title: `Tracked`,
868 },
869 ])
870 adapter.rowMetadata.set(`1`, { source: `initial` })
871 const coordinator = createCoordinatorHarness()
872
873 const collection = createCollection(
874 persistedCollectionOptions<Todo, string>({
875 id: `sync-present`,
876 getKey: (item) => item.id,
877 sync: {
878 sync: ({ markReady }) => {
879 markReady()
880 },
881 },
882 persistence: {
883 adapter,
884 coordinator,
885 },
886 }),
887 )
888
889 await collection.preload()
890 await flushAsyncWork()
891 const loadSubsetCallsAfterPreload = adapter.loadSubsetCalls.length
892
893 coordinator.emit({
894 type: `tx:committed`,
895 term: 1,
896 seq: 1,
897 txId: `tx-metadata-only`,
898 // The seeded row has no stream position; this is its first contiguous
899 // notification. A jump to version 2 would correctly require recovery.
900 latestRowVersion: 1,
901 requiresFullReload: false,
902 changedRows: [],
903 deletedKeys: [],
904 rowMetadataMutations: [
905 {
906 type: `set`,
907 key: `1`,
908 value: { source: `replayed` },
909 },
910 ],
911 collectionMetadataMutations: [
912 {
913 type: `set`,
914 key: `electric:resume`,
915 value: {
916 kind: `reset`,
917 updatedAt: 2,
918 },
919 },
920 ],
921 })
922
923 await flushAsyncWork()
924 await flushAsyncWork()
925
926 expect(adapter.loadSubsetCalls.length).toBe(loadSubsetCallsAfterPreload)
927 expect(collection._state.syncedMetadata.get(`1`)).toEqual({
928 source: `replayed`,
929 })
930 expect(
931 collection._state.syncedCollectionMetadata.get(`electric:resume`),
932 ).toEqual({
933 kind: `reset`,
934 updatedAt: 2,
935 })
936 })
937
938 it(`uses pullSince replay deltas for metadata-bearing seq-gap recovery`, async () => {
939 const adapter = createRecordingAdapter([
940 {
941 id: `1`,
942 title: `Tracked`,
943 },
944 ])
945 adapter.rowMetadata.set(`1`, { source: `initial` })
946 const coordinator = createCoordinatorHarness()
947 coordinator.setPullSinceResponse({
948 type: `rpc:pullSince:res`,
949 rpcId: `pull-metadata`,
950 ok: true,
951 latestTerm: 1,
952 latestSeq: 3,
953 latestRowVersion: 3,
954 requiresFullReload: false,
955 changedKeys: [],
956 deletedKeys: [],
957 deltas: [
958 {
959 txId: `tx-gap-1`,
960 latestRowVersion: 2,
961 changedRows: [],
962 deletedKeys: [],
963 rowMetadataMutations: [
964 {
965 type: `set`,
966 key: `1`,
967 value: { source: `gap-replayed` },
968 },
969 ],
970 collectionMetadataMutations: [],
971 },
972 {
973 txId: `tx-gap-2`,
974 latestRowVersion: 3,
975 changedRows: [],
976 deletedKeys: [],
977 rowMetadataMutations: [],
978 collectionMetadataMutations: [
979 {
980 type: `set`,
981 key: `queryCollection:gc:q1`,
982 value: {
983 queryHash: `q1`,
984 mode: `until-revalidated`,
985 },
986 },
987 ],
988 },
989 ],
990 })
991
992 const collection = createCollection(
993 persistedCollectionOptions<Todo, string>({
994 id: `sync-present`,
995 getKey: (item) => item.id,
996 sync: {
997 sync: ({ markReady }) => {
998 markReady()
999 },
1000 },
1001 persistence: {
1002 adapter,
1003 coordinator,
1004 },
1005 }),
1006 )
1007
1008 await collection.preload()
1009 await flushAsyncWork()
1010 const loadSubsetCallsAfterPreload = adapter.loadSubsetCalls.length
1011
1012 coordinator.emit({
1013 type: `tx:committed`,
1014 term: 1,
1015 seq: 3,
1016 txId: `tx-gap-trigger`,
1017 latestRowVersion: 3,
1018 requiresFullReload: false,
1019 changedRows: [],
1020 deletedKeys: [],
1021 })
1022
1023 await flushAsyncWork()
1024 await flushAsyncWork()
1025
1026 expect(coordinator.pullSinceCalls).toBe(1)
1027 expect(adapter.loadSubsetCalls.length).toBe(loadSubsetCallsAfterPreload)
1028 expect(collection._state.syncedMetadata.get(`1`)).toEqual({
1029 source: `gap-replayed`,
1030 })
1031 expect(
1032 collection._state.syncedCollectionMetadata.get(`queryCollection:gc:q1`),
1033 ).toEqual({
1034 queryHash: `q1`,
1035 mode: `until-revalidated`,
1036 })
1037 })
1038
1039 it(`throws InvalidSyncConfigError when sync key is present but null`, () => {
1040 const invalidOptions = {
1041 id: `invalid-sync-null`,
1042 getKey: (item: Todo) => item.id,
1043 sync: null,
1044 persistence: {
1045 adapter: createNoopAdapter(),
1046 },
1047 } as unknown as PersistedSyncWrappedOptions<Todo, string>
1048
1049 expect(() => persistedCollectionOptions(invalidOptions)).toThrow(
1050 InvalidSyncConfigError,
1051 )
1052 })
1053})