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

persisted-startup.test.ts

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