Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

persisted-startup.test.ts

1,069 lines32.7 KB

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 // Each branch creates its Collection from one options type, so the
307 // call never resolves overloads against a union.
308 const syncOptions =
309 mode === `sync-present`
310 ? persistedCollectionOptions<Todo, string>({
311 ...base,
312 sync: {
313 sync: (params) => {
314 source = params
315 params.markReady()
316 },
317 },
318 })
319 : undefined
320 const localOptions = syncOptions
321 ? undefined
322 : persistedCollectionOptions<Todo, string>(base)
323 const options = syncOptions ?? localOptions!
324 const first = syncOptions
325 ? createCollection(syncOptions)
326 : createCollection(localOptions!)
327 const second = createCollection({
328 id: `unclaimed-${mode}`,
329 getKey: (row: Todo) => row.id,
330 sync: options.sync,
331 startSync: false,
332 })
333 let hasPrimaryFailure = false
334 try {
335 await first.stateWhenReady()
336 if (mode === `sync-present`) {
337 source.begin()
338 source.write({
339 type: `insert`,
340 value: { id: `owned`, title: `First source` },
341 })
342 }
343 expect(() => second.startSyncImmediate()).toThrow(
344 InvalidPersistedCollectionConfigError,
345 )
346​
347 if (mode === `sync-present`) {
348 await Promise.resolve(source.commit())
349 } else {
350 await first.insert({ id: `owned`, title: `First owner` }).isPersisted
351 .promise
352 }
353 expect(first.has(`owned`)).toBe(true)
354 expect(second.has(`owned`)).toBe(false)
355 expect(adapter.rows.get(`owned`)?.id).toBe(`owned`)
356 } catch (error) {
357 hasPrimaryFailure = true
358 throw error
359 } finally {
360 await cleanupPersistedOracle(
361 [() => second.cleanup(), () => first.cleanup()],
362 hasPrimaryFailure,
363 )
364 }
365 },
366 )
367​
368 // Construction, rather than first sync startup, assigns the descriptor's
369 // Collection owner. A lazy wrapped source leaves a legal interval in which a
370 // second Collection can select only its public sync field and start first.
371 // The independent admission rule still gives the first constructed owner
372 // the runtime; the selected copy must fail before it installs controls.
373 it(`rejects a selected sync that starts before its lazy descriptor owner`, async () => {
374 const adapter = createRecordingAdapter()
375 let source!: TodoSyncParams
376 const options = persistedCollectionOptions<Todo, string>({
377 id: `lazy-selected-sync-owner`,
378 getKey: (row) => row.id,
379 startSync: false,
380 sync: {
381 sync: (params) => {
382 source = params
383 params.markReady()
384 },
385 },
386 persistence: { adapter },
387 })
388 const first = createCollection(options)
389 const selected = createCollection({
390 id: `lazy-selected-sync-copy`,
391 getKey: (row: Todo) => row.id,
392 sync: options.sync,
393 startSync: false,
394 })
395 let hasPrimaryFailure = false
396 try {
397 expect(() => selected.startSyncImmediate()).toThrow(
398 InvalidPersistedCollectionConfigError,
399 )
400 first.startSyncImmediate()
401 await first.stateWhenReady()
402 source.begin()
403 source.write({
404 type: `insert`,
405 value: { id: `owned`, title: `Original owner` },
406 })
407 await Promise.resolve(source.commit())
408 expect(stripVirtualProps(first.get(`owned`))).toEqual({
409 id: `owned`,
410 title: `Original owner`,
411 })
412 expect(selected.has(`owned`)).toBe(false)
413 expect(adapter.rows.get(`owned`)).toEqual({
414 id: `owned`,
415 title: `Original owner`,
416 })
417 } catch (error) {
418 hasPrimaryFailure = true
419 throw error
420 } finally {
421 await cleanupPersistedOracle(
422 [() => selected.cleanup(), () => first.cleanup()],
423 hasPrimaryFailure,
424 )
425 }
426 })
427​
428 it(`does not reuse a persisted runtime after its Collection cleans up`, async () => {
429 const options = persistedCollectionOptions<Todo, string>({
430 id: `cleaned-up-owner`,
431 getKey: (row) => row.id,
432 persistence: { adapter: createRecordingAdapter() },
433 })
434 const first = createCollection(options)
435 await first.cleanup()
436 expect(() => createCollection(options)).toThrow(
437 InvalidPersistedCollectionConfigError,
438 )
439 })
440​
441 // Cleanup ends a sync run, not the descriptor's permanent Collection claim.
442 // Selecting only the wrapped sync field omits the public claim hook, so this
443 // history checks the runtime guard after cleanup and the original owner's
444 // ability to restart. The two modes cross local and upstream source controls.
445 it.each([`local-only`, `sync-present`] as const)(
446 `rejects a copied sync owner after cleanup and permits the first owner to restart (%s)`,
447 async (mode) => {
448 const adapter = createRecordingAdapter()
449 let source!: TodoSyncParams
450 const base = {
451 id: `cleaned-selected-sync-${mode}`,
452 getKey: (row: Todo) => row.id,
453 persistence: { adapter },
454 }
455 // Each branch creates its Collection from one options type, so the
456 // call never resolves overloads against a union.
457 const syncOptions =
458 mode === `sync-present`
459 ? persistedCollectionOptions<Todo, string>({
460 ...base,
461 sync: {
462 sync: (params) => {
463 source = params
464 params.markReady()
465 },
466 },
467 })
468 : undefined
469 const localOptions = syncOptions
470 ? undefined
471 : persistedCollectionOptions<Todo, string>(base)
472 const options = syncOptions ?? localOptions!
473 const first = syncOptions
474 ? createCollection(syncOptions)
475 : createCollection(localOptions!)
476 const second = createCollection({
477 id: `post-cleanup-copy-${mode}`,
478 getKey: (row: Todo) => row.id,
479 sync: options.sync,
480 startSync: false,
481 })
482 let hasPrimaryFailure = false
483 try {
484 await first.stateWhenReady()
485 await first.cleanup()
486 expect(() => second.startSyncImmediate()).toThrow(
487 InvalidPersistedCollectionConfigError,
488 )
489​
490 const replacementReady = createEventGate()
491 const unsubscribe = first.on(`status:ready`, () =>
492 replacementReady.resolve(),
493 )
494 try {
495 first.startSyncImmediate()
496 await atPersistedOracleCheckpoint(
497 replacementReady.promise,
498 `original persisted owner restarts`,
499 )
500 } finally {
501 unsubscribe()
502 }
503​
504 if (mode === `sync-present`) {
505 source.begin()
506 source.write({
507 type: `insert`,
508 value: { id: `after-restart`, title: `First source` },
509 })
510 await Promise.resolve(source.commit())
511 } else {
512 await first.insert({ id: `after-restart`, title: `First owner` })
513 .isPersisted.promise
514 }
515 expect(first.has(`after-restart`)).toBe(true)
516 expect(second.has(`after-restart`)).toBe(false)
517 expect(adapter.rows.get(`after-restart`)?.id).toBe(`after-restart`)
518 } catch (error) {
519 hasPrimaryFailure = true
520 throw error
521 } finally {
522 await cleanupPersistedOracle(
523 [() => second.cleanup(), () => first.cleanup()],
524 hasPrimaryFailure,
525 )
526 }
527 },
528 )
529​
530 it(`materializes one independent persisted runtime for each DbClient`, async () => {
531 const adapter = createRecordingAdapter([{ id: `stored`, title: `Stored` }])
532 const descriptor = collectionOptions(
533 persistedCollectionOptions<Todo, string>({
534 id: `client-owned-persistence`,
535 getKey: (row) => row.id,
536 persistence: { adapter },
537 }),
538 )
539 const firstClient = new DbClient()
540 const secondClient = new DbClient()
541 let hasPrimaryFailure = false
542 try {
543 const first = firstClient.collection(descriptor)
544 const second = secondClient.collection(descriptor)
545 expect(first).not.toBe(second)
546 await Promise.all([first.stateWhenReady(), second.stateWhenReady()])
547 expect(stripVirtualProps(first.get(`stored`))).toEqual({
548 id: `stored`,
549 title: `Stored`,
550 })
551 expect(stripVirtualProps(second.get(`stored`))).toEqual({
552 id: `stored`,
553 title: `Stored`,
554 })
555 } catch (error) {
556 hasPrimaryFailure = true
557 throw error
558 } finally {
559 await cleanupPersistedOracle(
560 [() => secondClient.cleanup(), () => firstClient.cleanup()],
561 hasPrimaryFailure,
562 )
563 }
564 })
565​
566 it(`preserves exact reconciliation context for an indeterminate commit`, () => {
567 const cause = new Error(`response channel closed`)
568 const error = new IndeterminateCommitError({
569 collectionId: `todos`,
570 requestType: `rpc:applyCommittedTx:req`,
571 previousLeaderId: `leader-a`,
572 previousTerm: 4,
573 currentLeaderId: `leader-b`,
574 currentTerm: 5,
575 cause,
576 })
577​
578 expect(error).toMatchObject({
579 name: `IndeterminateCommitError`,
580 code: `INDETERMINATE_COMMIT`,
581 collectionId: `todos`,
582 requestType: `rpc:applyCommittedTx:req`,
583 previousLeaderId: `leader-a`,
584 previousTerm: 4,
585 currentLeaderId: `leader-b`,
586 currentTerm: 5,
587 cause,
588 })
589 expect(error.message).toContain(
590 `rpc:applyCommittedTx:req crossed leadership from leader-a (term 4) to leader-b (term 5)`,
591 )
592 })
593​
594 it(`provides a sync-absent loopback configuration with persisted utils`, async () => {
595 const adapter = createRecordingAdapter()
596 const collection = createCollection(
597 persistedCollectionOptions<Todo, string>({
598 id: `persisted-loopback`,
599 getKey: (item) => item.id,
600 persistence: {
601 adapter,
602 },
603 }),
604 )
605​
606 const insertTx = collection.insert({
607 id: `1`,
608 title: `Phase 0`,
609 })
610​
611 await insertTx.isPersisted.promise
612​
613 expect(stripVirtualProps(collection.get(`1`))).toEqual({
614 id: `1`,
615 title: `Phase 0`,
616 })
617 expect(adapter.applyCommittedTxCalls).toHaveLength(1)
618 expect(adapter.applyCommittedTxCalls[0]?.tx.mutations[0]?.type).toBe(
619 `insert`,
620 )
621 expect(typeof collection.utils.acceptMutations).toBe(`function`)
622 expect(collection.utils.getLeadershipState?.().isLeader).toBe(true)
623 })
624​
625 it(`hydrates a local-only baseline after a managed write advances startup evidence`, async () => {
626 const adapter = createRecordingAdapter([
627 { id: `baseline`, title: `Persisted before startup` },
628 ])
629 const loadResumeSnapshot = adapter.loadResumeSnapshot.bind(adapter)
630 let releaseInitialSnapshot!: () => void
631 const initialSnapshotRelease = new Promise<void>((resolve) => {
632 releaseInitialSnapshot = resolve
633 })
634 let reportInitialSnapshot!: () => void
635 const initialSnapshotCaptured = new Promise<void>((resolve) => {
636 reportInitialSnapshot = resolve
637 })
638 let snapshotCalls = 0
639 adapter.loadResumeSnapshot = async (...args) => {
640 const snapshot = await loadResumeSnapshot(...args)
641 snapshotCalls++
642 if (snapshotCalls === 1) {
643 reportInitialSnapshot()
644 await initialSnapshotRelease
645 }
646 return snapshot
647 }
648​
649 const collection = createCollection(
650 persistedCollectionOptions<Todo, string>({
651 id: `local-only-startup-write`,
652 startSync: false,
653 getKey: (item) => item.id,
654 persistence: { adapter },
655 }),
656 )
657​
658 try {
659 collection.startSyncImmediate()
660 await initialSnapshotCaptured
661​
662 const insert = collection.insert({
663 id: `concurrent`,
664 title: `Managed during startup`,
665 })
666 releaseInitialSnapshot()
667 await insert.isPersisted.promise
668 await collection.stateWhenReady()
669 await vi.waitFor(() => expect(snapshotCalls).toBeGreaterThanOrEqual(2))
670​
671 expect(
672 Array.from(collection.values(), (row) => stripVirtualProps(row)).sort(
673 (left, right) => left.id.localeCompare(right.id),
674 ),
675 ).toEqual([
676 { id: `baseline`, title: `Persisted before startup` },
677 { id: `concurrent`, title: `Managed during startup` },
678 ])
679 } finally {
680 releaseInitialSnapshot()
681 await collection.cleanup()
682 }
683 })
684​
685 it(`supports acceptMutations for manual transactions`, async () => {
686 const adapter = createRecordingAdapter()
687 const collection = createCollection(
688 persistedCollectionOptions<Todo, string>({
689 id: `persisted-manual`,
690 getKey: (item) => item.id,
691 persistence: {
692 adapter,
693 },
694 }),
695 )
696​
697 const tx = createTransaction({
698 autoCommit: false,
699 mutationFn: async ({ transaction }) => {
700 await collection.utils.acceptMutations(transaction)
701 },
702 })
703​
704 tx.mutate(() => {
705 collection.insert({
706 id: `manual-1`,
707 title: `Manual`,
708 })
709 })
710​
711 await tx.commit()
712​
713 expect(stripVirtualProps(collection.get(`manual-1`))).toEqual({
714 id: `manual-1`,
715 title: `Manual`,
716 })
717 expect(adapter.applyCommittedTxCalls).toHaveLength(1)
718 })
719​
720 it(`loads collection metadata into collection state during startup`, async () => {
721 const adapter = createRecordingAdapter()
722 adapter.collectionMetadata.set(`electric:resume`, {
723 kind: `resume`,
724 offset: `10_0`,
725 handle: `handle-1`,
726 shapeId: `shape-1`,
727 updatedAt: 1,
728 })
729​
730 const collection = createCollection(
731 persistedCollectionOptions<Todo, string>({
732 id: `persisted-startup-metadata`,
733 getKey: (item) => item.id,
734 persistence: {
735 adapter,
736 },
737 }),
738 )
739​
740 await collection.stateWhenReady()
741​
742 expect(adapter.loadResumeSnapshotCalls[0]).toMatchObject({
743 collectionId: `persisted-startup-metadata`,
744 includeRows: false,
745 })
746 expect(
747 collection._state.syncedCollectionMetadata.get(`electric:resume`),
748 ).toEqual({
749 kind: `resume`,
750 offset: `10_0`,
751 handle: `handle-1`,
752 shapeId: `shape-1`,
753 updatedAt: 1,
754 })
755 })
756​
757 it(`restores row and collection metadata after metadata-bearing full reload`, async () => {
758 const adapter = createRecordingAdapter([
759 {
760 id: `1`,
761 title: `Tracked`,
762 },
763 ])
764 adapter.rowMetadata.set(`1`, {
765 source: `initial`,
766 })
767 adapter.collectionMetadata.set(`electric:resume`, {
768 kind: `resume`,
769 offset: `10_0`,
770 handle: `handle-1`,
771 shapeId: `shape-1`,
772 updatedAt: 1,
773 })
774 const coordinator = createCoordinatorHarness()
775​
776 const collection = createCollection(
777 persistedCollectionOptions<Todo, string>({
778 id: `sync-present`,
779 getKey: (item) => item.id,
780 sync: {
781 sync: ({ markReady }) => {
782 markReady()
783 },
784 },
785 persistence: {
786 adapter,
787 coordinator,
788 },
789 }),
790 )
791​
792 await collection.preload()
793 await flushAsyncWork()
794​
795 expect(collection._state.syncedMetadata.get(`1`)).toEqual({
796 source: `initial`,
797 })
798 expect(
799 collection._state.syncedCollectionMetadata.get(`electric:resume`),
800 ).toEqual({
801 kind: `resume`,
802 offset: `10_0`,
803 handle: `handle-1`,
804 shapeId: `shape-1`,
805 updatedAt: 1,
806 })
807​
808 adapter.rowMetadata.set(`1`, {
809 source: `reloaded`,
810 })
811 adapter.collectionMetadata.delete(`electric:resume`)
812 adapter.collectionMetadata.set(`queryCollection:gc:q1`, {
813 queryHash: `q1`,
814 mode: `until-revalidated`,
815 })
816​
817 coordinator.emit({
818 type: `tx:committed`,
819 term: 1,
820 seq: 1,
821 txId: `tx-reload`,
822 latestRowVersion: 1,
823 requiresFullReload: true,
824 })
825​
826 await flushAsyncWork()
827 await flushAsyncWork()
828​
829 expect(collection._state.syncedMetadata.get(`1`)).toEqual({
830 source: `reloaded`,
831 })
832 expect(
833 collection._state.syncedCollectionMetadata.has(`electric:resume`),
834 ).toBe(false)
835 expect(
836 collection._state.syncedCollectionMetadata.get(`queryCollection:gc:q1`),
837 ).toEqual({
838 queryHash: `q1`,
839 mode: `until-revalidated`,
840 })
841 })
842​
843 it(`persists metadata-only wrapped sync transactions`, async () => {
844 const adapter = createRecordingAdapter()
845​
846 const collection = createCollection(
847 persistedCollectionOptions<Todo, string>({
848 id: `persisted-metadata-only`,
849 getKey: (item) => item.id,
850 sync: {
851 sync: ({ begin, commit, markReady, metadata }) => {
852 begin()
853 metadata?.collection.set(`runtime:key`, { persisted: true })
854 commit()
855 markReady()
856 },
857 },
858 persistence: {
859 adapter,
860 },
861 }),
862 )
863​
864 await collection.stateWhenReady()
865 await flushAsyncWork()
866​
867 expect(adapter.applyCommittedTxCalls).toHaveLength(1)
868 expect(adapter.applyCommittedTxCalls[0]?.tx.mutations).toEqual([])
869 expect(adapter.collectionMetadata.get(`runtime:key`)).toEqual({
870 persisted: true,
871 })
872 expect(
873 collection._state.syncedCollectionMetadata.get(`runtime:key`),
874 ).toEqual({
875 persisted: true,
876 })
877 })
878​
879 it(`replays metadata-only tx:committed deltas without full reload`, async () => {
880 const adapter = createRecordingAdapter([
881 {
882 id: `1`,
883 title: `Tracked`,
884 },
885 ])
886 adapter.rowMetadata.set(`1`, { source: `initial` })
887 const coordinator = createCoordinatorHarness()
888​
889 const collection = createCollection(
890 persistedCollectionOptions<Todo, string>({
891 id: `sync-present`,
892 getKey: (item) => item.id,
893 sync: {
894 sync: ({ markReady }) => {
895 markReady()
896 },
897 },
898 persistence: {
899 adapter,
900 coordinator,
901 },
902 }),
903 )
904​
905 await collection.preload()
906 await flushAsyncWork()
907 const loadSubsetCallsAfterPreload = adapter.loadSubsetCalls.length
908​
909 coordinator.emit({
910 type: `tx:committed`,
911 term: 1,
912 seq: 1,
913 txId: `tx-metadata-only`,
914 // The seeded row has no stream position; this is its first contiguous
915 // notification. A jump to version 2 would correctly require recovery.
916 latestRowVersion: 1,
917 requiresFullReload: false,
918 changedRows: [],
919 deletedKeys: [],
920 rowMetadataMutations: [
921 {
922 type: `set`,
923 key: `1`,
924 value: { source: `replayed` },
925 },
926 ],
927 collectionMetadataMutations: [
928 {
929 type: `set`,
930 key: `electric:resume`,
931 value: {
932 kind: `reset`,
933 updatedAt: 2,
934 },
935 },
936 ],
937 })
938​
939 await flushAsyncWork()
940 await flushAsyncWork()
941​
942 expect(adapter.loadSubsetCalls.length).toBe(loadSubsetCallsAfterPreload)
943 expect(collection._state.syncedMetadata.get(`1`)).toEqual({
944 source: `replayed`,
945 })
946 expect(
947 collection._state.syncedCollectionMetadata.get(`electric:resume`),
948 ).toEqual({
949 kind: `reset`,
950 updatedAt: 2,
951 })
952 })
953​
954 it(`uses pullSince replay deltas for metadata-bearing seq-gap recovery`, async () => {
955 const adapter = createRecordingAdapter([
956 {
957 id: `1`,
958 title: `Tracked`,
959 },
960 ])
961 adapter.rowMetadata.set(`1`, { source: `initial` })
962 const coordinator = createCoordinatorHarness()
963 coordinator.setPullSinceResponse({
964 type: `rpc:pullSince:res`,
965 rpcId: `pull-metadata`,
966 ok: true,
967 latestTerm: 1,
968 latestSeq: 3,
969 latestRowVersion: 3,
970 requiresFullReload: false,
971 changedKeys: [],
972 deletedKeys: [],
973 deltas: [
974 {
975 txId: `tx-gap-1`,
976 latestRowVersion: 2,
977 changedRows: [],
978 deletedKeys: [],
979 rowMetadataMutations: [
980 {
981 type: `set`,
982 key: `1`,
983 value: { source: `gap-replayed` },
984 },
985 ],
986 collectionMetadataMutations: [],
987 },
988 {
989 txId: `tx-gap-2`,
990 latestRowVersion: 3,
991 changedRows: [],
992 deletedKeys: [],
993 rowMetadataMutations: [],
994 collectionMetadataMutations: [
995 {
996 type: `set`,
997 key: `queryCollection:gc:q1`,
998 value: {
999 queryHash: `q1`,
1000 mode: `until-revalidated`,
1001 },
1002 },
1003 ],
1004 },
1005 ],
1006 })
1007​
1008 const collection = createCollection(
1009 persistedCollectionOptions<Todo, string>({
1010 id: `sync-present`,
1011 getKey: (item) => item.id,
1012 sync: {
1013 sync: ({ markReady }) => {
1014 markReady()
1015 },
1016 },
1017 persistence: {
1018 adapter,
1019 coordinator,
1020 },
1021 }),
1023​
1024 await collection.preload()
1025 await flushAsyncWork()
1026 const loadSubsetCallsAfterPreload = adapter.loadSubsetCalls.length
1027​
1028 coordinator.emit({
1029 type: `tx:committed`,
1030 term: 1,
1031 seq: 3,
1032 txId: `tx-gap-trigger`,
1033 latestRowVersion: 3,
1034 requiresFullReload: false,
1035 changedRows: [],
1036 deletedKeys: [],
1037 })
1038​
1039 await flushAsyncWork()
1040 await flushAsyncWork()
1041​
1042 expect(coordinator.pullSinceCalls).toBe(1)
1043 expect(adapter.loadSubsetCalls.length).toBe(loadSubsetCallsAfterPreload)
1044 expect(collection._state.syncedMetadata.get(`1`)).toEqual({
1045 source: `gap-replayed`,
1046 })
1047 expect(
1048 collection._state.syncedCollectionMetadata.get(`queryCollection:gc:q1`),
1049 ).toEqual({
1050 queryHash: `q1`,
1051 mode: `until-revalidated`,
1052 })
1053 })
1054​
1055 it(`throws InvalidSyncConfigError when sync key is present but null`, () => {
1056 const invalidOptions = {
1057 id: `invalid-sync-null`,
1058 getKey: (item: Todo) => item.id,
1059 sync: null,
1060 persistence: {
1061 adapter: createNoopAdapter(),
1062 },
1063 } as unknown as PersistedSyncWrappedOptions<Todo, string>
1064​
1065 expect(() => persistedCollectionOptions(invalidOptions)).toThrow(
1066 InvalidSyncConfigError,
1068 })