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

electric.test.ts

1,134 lines31.5 KB

1import { beforeEach, describe, expect, it, vi } from "vitest"
2import {
3 CollectionImpl,
4 createCollection,
5 createTransaction,
6} from "@tanstack/db"
7import { electricCollectionOptions } from "../src/electric"
8import type { ElectricCollectionUtils } from "../src/electric"
9import type {
10 Collection,
11 InsertMutationFnParams,
12 MutationFnParams,
13 PendingMutation,
14 Transaction,
15 TransactionWithMutations,
16} from "@tanstack/db"
17import type { Message, Row } from "@electric-sql/client"
18import type { StandardSchemaV1 } from "@standard-schema/spec"
19​
20// Mock the ShapeStream module
21const mockSubscribe = vi.fn()
22const mockStream = {
23 subscribe: mockSubscribe,
25​
26vi.mock(`@electric-sql/client`, async () => {
27 const actual = await vi.importActual(`@electric-sql/client`)
28 return {
29 ...actual,
30 ShapeStream: vi.fn(() => mockStream),
31 }
32})
33​
34describe(`Electric Integration`, () => {
35 let collection: Collection<
36 Row,
37 string | number,
38 ElectricCollectionUtils,
39 StandardSchemaV1<unknown, unknown>,
40 Row
41 >
42 let subscriber: (messages: Array<Message<Row>>) => void
43​
44 beforeEach(() => {
45 vi.clearAllMocks()
46​
47 // Reset mock subscriber
48 mockSubscribe.mockImplementation((callback) => {
49 subscriber = callback
50 return () => {}
51 })
52​
53 // Create collection with Electric configuration
54 const config = {
55 id: `test`,
56 shapeOptions: {
57 url: `http://test-url`,
58 params: {
59 table: `test_table`,
60 },
61 },
62 startSync: true,
63 getKey: (item: Row) => item.id as number,
64 }
65​
66 // Get the options with utilities
67 const options = electricCollectionOptions(config)
68​
69 // Create collection with Electric configuration using the new utility exposure pattern
70 collection = createCollection(options)
71 })
72​
73 it(`should commit an empty transaction when there's an up-to-date`, () => {
74 expect(collection.status).toEqual(`loading`)
75 expect(collection.state).toEqual(new Map([]))
76​
77 // Send up-to-date control message to commit transaction
78 subscriber([
79 {
80 headers: { control: `up-to-date` },
81 },
82 ])
83 expect(collection.state).toEqual(new Map([]))
84 expect(collection.status).toEqual(`ready`)
85 })
86​
87 it(`should handle incoming insert messages and commit on up-to-date`, () => {
88 // Simulate incoming insert message
89 subscriber([
90 {
91 key: `1`,
92 value: { id: 1, name: `Test User` },
93 headers: { operation: `insert` },
94 },
95 ])
96 expect(collection.state).toEqual(new Map([]))
97​
98 // Send up-to-date control message to commit transaction
99 subscriber([
100 {
101 headers: { control: `up-to-date` },
102 },
103 ])
104​
105 expect(collection.state).toEqual(
106 new Map([[1, { id: 1, name: `Test User` }]])
107 )
108 })
109​
110 it(`should handle multiple changes before committing`, () => {
111 // First batch of changes
112 subscriber([
113 {
114 key: `1`,
115 value: { id: 1, name: `Test User` },
116 headers: { operation: `insert` },
117 },
118 ])
119​
120 // Second batch of changes
121 subscriber([
122 {
123 key: `2`,
124 value: { id: 2, name: `Another User` },
125 headers: { operation: `insert` },
126 },
127 ])
128​
129 expect(collection.state).toEqual(new Map([]))
130 expect(collection.status).toEqual(`loading`)
131​
132 // Send up-to-date to commit all changes
133 subscriber([
134 {
135 headers: { control: `up-to-date` },
136 },
137 ])
138 expect(collection.status).toEqual(`ready`)
139​
140 expect(collection.state).toEqual(
141 new Map([
142 [1, { id: 1, name: `Test User` }],
143 [2, { id: 2, name: `Another User` }],
144 ])
145 )
146 })
147​
148 it(`should handle updates across multiple messages`, () => {
149 // First insert
150 subscriber([
151 {
152 key: `1`,
153 value: { id: 1, name: `Test User` },
154 headers: { operation: `insert` },
155 },
156 ])
157​
158 // Update in a separate message
159 subscriber([
160 {
161 key: `1`,
162 value: { id: 1, name: `Updated User` },
163 headers: { operation: `update` },
164 },
165 ])
166​
167 // Commit with up-to-date
168 subscriber([
169 {
170 headers: { control: `up-to-date` },
171 },
172 ])
173​
174 expect(collection.state).toEqual(
175 new Map([[1, { id: 1, name: `Updated User` }]])
176 )
177 })
178​
179 it(`should handle delete operations`, () => {
180 // Insert and commit
181 subscriber([
182 {
183 key: `1`,
184 value: { id: 1, name: `Test User` },
185 headers: { operation: `insert` },
186 },
187 {
188 headers: { control: `up-to-date` },
189 },
190 ])
191​
192 // Delete in new transaction
193 subscriber([
194 {
195 key: `1`,
196 value: { id: 1 },
197 headers: { operation: `delete` },
198 },
199 {
200 headers: { control: `up-to-date` },
201 },
202 ])
203​
204 expect(collection.state).toEqual(new Map())
205 })
206​
207 it(`should not commit changes without up-to-date message`, () => {
208 // Send changes without up-to-date
209 subscriber([
210 {
211 key: `1`,
212 value: { id: 1, name: `Test User` },
213 headers: { operation: `insert` },
214 },
215 ])
216​
217 // Send must-refetch control message
218 subscriber([
219 {
220 headers: { control: `must-refetch` },
221 },
222 ])
223​
224 // Changes should still be pending until up-to-date is received
225 expect(collection.state).toEqual(new Map())
226 })
227​
228 it(`should handle must-refetch by clearing synced data and re-syncing`, () => {
229 // First, populate the collection with some data
230 subscriber([
231 {
232 key: `1`,
233 value: { id: 1, name: `Test User` },
234 headers: { operation: `insert` },
235 },
236 {
237 key: `2`,
238 value: { id: 2, name: `Another User` },
239 headers: { operation: `insert` },
240 },
241 {
242 headers: { control: `up-to-date` },
243 },
244 ])
245​
246 // Verify the data is in the collection
247 expect(collection.state.size).toBe(2)
248 expect(collection.status).toBe(`ready`)
249​
250 // Send must-refetch control message
251 subscriber([
252 {
253 headers: { control: `must-refetch` },
254 },
255 ])
256​
257 // The collection should still have old data because truncate is in pending
258 // transaction. This is the intended behavior of the collection, you should have
259 // the old data until the next up-to-date message.
260 expect(collection.state.size).toBe(2)
261 expect(collection.status).toBe(`ready`)
262​
263 // Send new data after must-refetch
264 subscriber([
265 {
266 key: `3`,
267 value: { id: 3, name: `New User` },
268 headers: { operation: `insert` },
269 },
270 {
271 headers: { control: `up-to-date` },
272 },
273 ])
274​
275 // The collection should now have the new data
276 expect(collection.state.size).toBe(1)
277 expect(collection.state.get(3)).toEqual({ id: 3, name: `New User` })
278 expect(collection.status).toBe(`ready`)
279 })
280​
281 // Tests for txid tracking functionality
282 describe(`txid tracking`, () => {
283 it(`should track txids from incoming messages`, async () => {
284 const testTxid = 123
285​
286 // Send a message with a txid
287 subscriber([
288 {
289 key: `1`,
290 value: { id: 1, name: `Test User` },
291 headers: {
292 operation: `insert`,
293 txids: [testTxid],
294 },
295 },
296 {
297 headers: { control: `up-to-date` },
298 },
299 ])
300​
301 // awaitTxId throws if you pass it a string
302 await expect(
303 // @ts-expect-error
304 collection.utils.awaitTxId(`123`)
305 ).rejects.toThrowErrorMatchingInlineSnapshot(
306 `[ExpectedNumberInAwaitTxIdError: Expected number in awaitTxId, received string]`
307 )
308​
309 // The txid should be tracked and awaitTxId should resolve immediately
310 await expect(collection.utils.awaitTxId(testTxid)).resolves.toBe(true)
311 })
312​
313 it(`should track multiple txids`, async () => {
314 const txid1 = 100
315 const txid2 = 200
316​
317 // Send a message with multiple txids
318 subscriber([
319 {
320 key: `1`,
321 value: { id: 1, name: `Test User` },
322 headers: {
323 operation: `insert`,
324 txids: [txid1, txid2],
325 },
326 },
327 {
328 headers: { control: `up-to-date` },
329 },
330 ])
331​
332 // Both txids should be tracked
333 await expect(collection.utils.awaitTxId(txid1)).resolves.not.toThrow()
334 await expect(collection.utils.awaitTxId(txid2)).resolves.not.toThrow()
335 })
336​
337 it(`should reject with timeout when waiting for unknown txid`, async () => {
338 // Set a short timeout for the test
339 const unknownTxid = 0
340 const shortTimeout = 100
341​
342 // Attempt to await a txid that hasn't been seen with a short timeout
343 const promise = collection.utils.awaitTxId(unknownTxid, shortTimeout)
344​
345 // The promise should reject with a timeout error
346 await expect(promise).rejects.toThrow(
347 `Timeout waiting for txId: ${unknownTxid}`
348 )
349 })
350​
351 it(`should resolve when a txid arrives after awaitTxId is called`, async () => {
352 const laterTxid = 1000
353​
354 // Start waiting for a txid that hasn't arrived yet
355 const promise = collection.utils.awaitTxId(laterTxid, 1000)
356​
357 // Send the txid after a short delay
358 setTimeout(() => {
359 subscriber([
360 {
361 key: `foo`,
362 value: { id: 1, bar: true },
363 headers: {
364 operation: `insert`,
365 },
366 },
367 {
368 headers: {
369 control: `up-to-date`,
370 txids: [laterTxid],
371 },
372 },
373 {
374 headers: {
375 control: `up-to-date`,
376 },
377 },
378 ])
379 }, 50)
380​
381 // The promise should resolve when the txid arrives
382 await expect(promise).resolves.not.toThrow()
383 })
384​
385 // Test the complete flow
386 it(`should simulate the complete flow`, async () => {
387 // Create a fake backend store to simulate server-side storage
388 const fakeBackend = {
389 data: new Map<number, { txid: number; value: unknown }>(),
390 // Simulates persisting data to a backend and returning a txid
391 persist: (mutations: Array<PendingMutation<Row>>): Promise<number> => {
392 const txid = Math.floor(Math.random() * 10000)
393​
394 // Store the changes with the txid
395 mutations.forEach((mutation) => {
396 fakeBackend.data.set(mutation.key, {
397 value: mutation.changes,
398 txid,
399 })
400 })
401​
402 return Promise.resolve(txid)
403 },
404 // Simulates the server sending sync messages with txids
405 simulateSyncMessage: (txid: number) => {
406 // Create messages for each item in the store that has this txid
407 const messages: Array<Message<Row>> = []
408​
409 fakeBackend.data.forEach((value, key) => {
410 if (value.txid === txid) {
411 messages.push({
412 key: key.toString(),
413 value: value.value as Row,
414 headers: {
415 operation: `insert`,
416 txids: [txid],
417 },
418 })
419 }
420 })
421​
422 // Add an up-to-date message to complete the sync
423 messages.push({
424 headers: {
425 control: `up-to-date`,
426 },
427 })
428​
429 // Send the messages to the subscriber
430 subscriber(messages)
431 },
432 }
433​
434 // Create a test mutation function that uses our fake backend
435 const testMutationFn = vi.fn(
436 async ({ transaction }: { transaction: Transaction }) => {
437 // Persist to fake backend and get txid
438 const txid = await fakeBackend.persist(
439 transaction.mutations as Array<PendingMutation<Row>>
440 )
441​
442 if (!txid) {
443 throw new Error(`No txid found`)
444 }
445​
446 // Start waiting for the txid
447 const promise = collection.utils.awaitTxId(txid, 1000)
448​
449 // Simulate the server sending sync messages after a delay
450 setTimeout(() => {
451 fakeBackend.simulateSyncMessage(txid)
452 }, 50)
453​
454 // Wait for the txid to be seen
455 await promise
456​
457 return Promise.resolve()
458 }
459 )
460​
461 const tx1 = createTransaction({ mutationFn: testMutationFn })
462​
463 let transaction = tx1.mutate(() =>
464 collection.insert({ id: 1, name: `Test item 1` })
465 )
466​
467 await transaction.isPersisted.promise
468​
469 transaction = collection._state.transactions.get(transaction.id)!
470​
471 // Verify the mutation function was called correctly
472 expect(testMutationFn).toHaveBeenCalledTimes(1)
473​
474 // Check that the data was added to the collection
475 // Note: In a real implementation, the collection would be updated by the sync process
476 // This is just verifying our test setup worked correctly
477 expect(fakeBackend.data.has(1)).toBe(true)
478 expect(collection.has(1)).toBe(true)
479 })
480 })
481​
482 // Tests for direct persistence handlers
483 describe(`Direct persistence handlers`, () => {
484 it(`should pass through direct persistence handlers to collection options`, () => {
485 // Create mock handlers
486 const onInsert = vi.fn().mockResolvedValue({ txid: 123 })
487 const onUpdate = vi.fn().mockResolvedValue({ txid: 456 })
488 const onDelete = vi.fn().mockResolvedValue({ txid: 789 })
489​
490 const config = {
491 id: `test-handlers`,
492 shapeOptions: {
493 url: `http://test-url`,
494 params: {
495 table: `test_table`,
496 },
497 },
498 getKey: (item: Row) => item.id as number,
499 onInsert,
500 onUpdate,
501 onDelete,
502 }
503​
504 const options = electricCollectionOptions(config)
505​
506 // Verify that the handlers were passed to the collection options
507 expect(options.onInsert).toBeDefined()
508 expect(options.onUpdate).toBeDefined()
509 expect(options.onDelete).toBeDefined()
510 })
511​
512 it(`should throw an error if handler doesn't return a txid`, async () => {
513 // Create a mock transaction for testing
514 const mockTransaction = {
515 id: `test-transaction`,
516 mutations: [],
517 } as unknown as TransactionWithMutations<Row, `insert`>
518 const mockParams: InsertMutationFnParams<Row> = {
519 transaction: mockTransaction,
520 // @ts-expect-error not relevant to test
521 collection: CollectionImpl,
522 }
523​
524 // Create a handler that doesn't return a txid
525 const onInsert = vi.fn().mockResolvedValue({})
526​
527 const config = {
528 id: `test-handlers`,
529 shapeOptions: {
530 url: `http://test-url`,
531 params: {
532 table: `test_table`,
533 },
534 },
535 getKey: (item: Row) => item.id as number,
536 onInsert,
537 }
538​
539 const options = electricCollectionOptions(config)
540​
541 // Call the wrapped handler and expect it to throw
542 await expect(options.onInsert!(mockParams)).rejects.toThrow(
543 `Electric collection onInsert handler must return a txid`
544 )
545 })
546​
547 it(`should simulate complete flow with direct persistence handlers`, async () => {
548 // Create a fake backend store to simulate server-side storage
549 const fakeBackend = {
550 data: new Map<string, { txid: number; value: unknown }>(),
551 // Simulates persisting data to a backend and returning a txid
552 persist: (mutations: Array<PendingMutation<Row>>): Promise<number> => {
553 const txid = Math.floor(Math.random() * 10000)
554​
555 // Store the changes with the txid
556 mutations.forEach((mutation) => {
557 const key = mutation.key
558 fakeBackend.data.set(key, { txid, value: mutation.changes })
559 })
560​
561 return Promise.resolve(txid)
562 },
563 // Simulates the server sending sync messages with txids
564 simulateSyncMessage: (txid: number) => {
565 // Create messages for each item in the store that has this txid
566 const messages: Array<Message<Row>> = []
567​
568 fakeBackend.data.forEach((value, key) => {
569 if (value.txid === txid) {
570 messages.push({
571 key,
572 value: value.value as Row,
573 headers: {
574 operation: `insert`,
575 txids: [txid],
576 },
577 })
578 }
579 })
580​
581 // Add up-to-date message
582 messages.push({
583 headers: { control: `up-to-date` },
584 })
585​
586 // Send the messages to the subscriber
587 subscriber(messages)
588 },
589 }
590​
591 // Create a mutation function for the transaction
592 const mutationFn = vi.fn(async (params: MutationFnParams<Row>) => {
593 const txid = await fakeBackend.persist(params.transaction.mutations)
594​
595 // Simulate server sending sync message after a delay
596 setTimeout(() => {
597 fakeBackend.simulateSyncMessage(txid)
598 }, 50)
599​
600 return txid
601 })
602​
603 // Create direct persistence handler that returns the txid
604 const onInsert = vi.fn(async (params: MutationFnParams<Row>) => {
605 return { txid: await mutationFn(params) }
606 })
607​
608 // Create a test collection with our direct persistence handler
609 const config = {
610 id: `test-direct-persistence`,
611 shapeOptions: {
612 url: `http://test-url`,
613 params: {
614 table: `test_table`,
615 },
616 },
617 startSync: true,
618 getKey: (item: Row) => item.id as number,
619 onInsert,
620 }
621​
622 const testCollection = createCollection(electricCollectionOptions(config))
623​
624 // Insert data using the transaction
625 const tx = testCollection.insert({
626 id: 1,
627 name: `Direct Persistence User`,
628 })
629​
630 // If awaitTxId wasn't called automatically, this wouldn't be true.
631 expect(testCollection._state.syncedData.size).toEqual(0)
632​
633 // Verify that our onInsert handler was called
634 expect(onInsert).toHaveBeenCalled()
635​
636 await tx.isPersisted.promise
637​
638 // Verify that the data was added to the collection via the sync process
639 expect(testCollection.has(1)).toBe(true)
640 expect(testCollection.get(1)).toEqual({
641 id: 1,
642 name: `Direct Persistence User`,
643 })
644 expect(testCollection._state.syncedData.size).toEqual(1)
645 })
646 })
647​
648 // Tests for Electric stream lifecycle management
649 describe(`Electric stream lifecycle management`, () => {
650 let mockUnsubscribe: ReturnType<typeof vi.fn>
651 let mockAbortController: {
652 abort: ReturnType<typeof vi.fn>
653 signal: AbortSignal
654 }
655​
656 beforeEach(() => {
657 // Clear all mocks before each lifecycle test
658 vi.clearAllMocks()
659​
660 // Reset mocks before each test
661 mockUnsubscribe = vi.fn()
662 mockAbortController = {
663 abort: vi.fn(),
664 signal: new AbortController().signal,
665 }
666​
667 // Update the mock to return our mock unsubscribe function
668 mockSubscribe.mockImplementation((callback) => {
669 subscriber = callback
670 return mockUnsubscribe
671 })
672​
673 // Mock AbortController
674 global.AbortController = vi
675 .fn()
676 .mockImplementation(() => mockAbortController)
677 })
678​
679 it(`should call unsubscribe and abort when collection is cleaned up`, async () => {
680 const config = {
681 id: `cleanup-test`,
682 shapeOptions: {
683 url: `http://test-url`,
684 params: {
685 table: `test_table`,
686 },
687 },
688 getKey: (item: Row) => item.id as number,
689 startSync: true,
690 }
691​
692 const testCollection = createCollection(electricCollectionOptions(config))
693​
694 // Verify stream is set up
695 expect(mockSubscribe).toHaveBeenCalled()
696​
697 // Cleanup the collection
698 await testCollection.cleanup()
699​
700 // Verify that both unsubscribe and abort were called
701 expect(mockUnsubscribe).toHaveBeenCalledTimes(1)
702 expect(mockAbortController.abort).toHaveBeenCalledTimes(1)
703 })
704​
705 it(`should properly cleanup Electric-specific resources`, async () => {
706 const config = {
707 id: `resource-cleanup-test`,
708 shapeOptions: {
709 url: `http://test-url`,
710 params: {
711 table: `test_table`,
712 },
713 },
714 getKey: (item: Row) => item.id as number,
715 startSync: true,
716 }
717​
718 const testCollection = createCollection(electricCollectionOptions(config))
719​
720 // Add some txids to track
721 subscriber([
722 {
723 key: `1`,
724 value: { id: 1, name: `Test` },
725 headers: {
726 operation: `insert`,
727 txids: [100, 200],
728 },
729 },
730 {
731 headers: { control: `up-to-date` },
732 },
733 ])
734​
735 // Verify txids are tracked
736 await expect(testCollection.utils.awaitTxId(100)).resolves.toBe(true)
737​
738 // Cleanup collection
739 await testCollection.cleanup()
740​
741 // Verify cleanup was called
742 expect(mockUnsubscribe).toHaveBeenCalled()
743 expect(mockAbortController.abort).toHaveBeenCalled()
744 })
745​
746 it(`should handle multiple cleanup calls gracefully`, async () => {
747 const config = {
748 id: `multiple-cleanup-test`,
749 shapeOptions: {
750 url: `http://test-url`,
751 params: {
752 table: `test_table`,
753 },
754 },
755 getKey: (item: Row) => item.id as number,
756 startSync: true,
757 }
758​
759 const testCollection = createCollection(electricCollectionOptions(config))
760​
761 // Call cleanup multiple times
762 await testCollection.cleanup()
763 await testCollection.cleanup()
764 await testCollection.cleanup()
765​
766 // Should only call unsubscribe once (from the first cleanup)
767 expect(mockUnsubscribe).toHaveBeenCalledTimes(1)
768 expect(mockAbortController.abort).toHaveBeenCalledTimes(1)
769 })
770​
771 it(`should restart stream when collection is accessed after cleanup`, async () => {
772 const config = {
773 id: `restart-stream-test`,
774 shapeOptions: {
775 url: `http://test-url`,
776 params: {
777 table: `test_table`,
778 },
779 },
780 getKey: (item: Row) => item.id as number,
781 startSync: true,
782 }
783​
784 const testCollection = createCollection(electricCollectionOptions(config))
785​
786 // Initial stream setup
787 expect(mockSubscribe).toHaveBeenCalledTimes(1)
788​
789 // Cleanup
790 await testCollection.cleanup()
791 expect(testCollection.status).toBe(`cleaned-up`)
792​
793 // Access collection data to restart sync
794 const subscription = testCollection.subscribeChanges(() => {})
795​
796 // Should have started a new stream
797 expect(mockSubscribe).toHaveBeenCalledTimes(2)
798 expect(testCollection.status).toBe(`loading`)
799​
800 subscription.unsubscribe()
801 })
802​
803 it(`should handle stream errors gracefully`, () => {
804 const config = {
805 id: `error-handling-test`,
806 shapeOptions: {
807 url: `http://test-url`,
808 params: {
809 table: `test_table`,
810 },
811 },
812 getKey: (item: Row) => item.id as number,
813 startSync: true,
814 }
815​
816 // Mock stream to throw an error
817 mockSubscribe.mockImplementation(() => {
818 throw new Error(`Stream connection failed`)
819 })
820​
821 expect(() => {
822 createCollection(electricCollectionOptions(config))
823 }).toThrow(`Stream connection failed`)
824 })
825​
826 it(`should handle subscriber function errors without breaking`, () => {
827 const config = {
828 id: `subscriber-error-test`,
829 shapeOptions: {
830 url: `http://test-url`,
831 params: {
832 table: `test_table`,
833 },
834 },
835 getKey: (item: Row) => item.id as number,
836 startSync: true,
837 }
838​
839 const testCollection = createCollection(electricCollectionOptions(config))
840​
841 // Mock console.error to capture error logs
842 const consoleSpy = vi.spyOn(console, `error`).mockImplementation(() => {})
843​
844 // Send messages with invalid data that might cause internal errors
845 // but shouldn't break the entire system
846 expect(() => {
847 subscriber([
848 {
849 key: `1`,
850 value: { id: 1, name: `Valid User` }, // Use valid data
851 headers: { operation: `insert` },
852 },
853 ])
854 }).not.toThrow()
855​
856 // Should have processed the valid message without issues
857 expect(testCollection._state.syncedData.size).toBe(0) // Still pending until up-to-date
858​
859 // Send up-to-date to commit
860 expect(() => {
861 subscriber([
862 {
863 headers: { control: `up-to-date` },
864 },
865 ])
866 }).not.toThrow()
867​
868 // Now the data should be committed
869 expect(testCollection.has(1)).toBe(true)
870​
871 consoleSpy.mockRestore()
872 })
873​
874 it(`should properly handle concurrent stream operations`, async () => {
875 const config = {
876 id: `concurrent-test`,
877 shapeOptions: {
878 url: `http://test-url`,
879 params: {
880 table: `test_table`,
881 },
882 },
883 getKey: (item: Row) => item.id as number,
884 startSync: true,
885 }
886​
887 const testCollection = createCollection(electricCollectionOptions(config))
888​
889 // Simulate concurrent messages
890 const promises = [
891 new Promise<void>((resolve) => {
892 setTimeout(() => {
893 subscriber([
894 {
895 key: `1`,
896 value: { id: 1, name: `User 1` },
897 headers: { operation: `insert` },
898 },
899 ])
900 resolve()
901 }, 10)
902 }),
903 new Promise<void>((resolve) => {
904 setTimeout(() => {
905 subscriber([
906 {
907 key: `2`,
908 value: { id: 2, name: `User 2` },
909 headers: { operation: `insert` },
910 },
911 ])
912 resolve()
913 }, 20)
914 }),
915 new Promise<void>((resolve) => {
916 setTimeout(() => {
917 subscriber([
918 {
919 headers: { control: `up-to-date` },
920 },
921 ])
922 resolve()
923 }, 30)
924 }),
925 ]
926​
927 await Promise.all(promises)
928​
929 // Both items should be in the collection
930 expect(testCollection.has(1)).toBe(true)
931 expect(testCollection.has(2)).toBe(true)
932 })
933​
934 it(`should handle schema information extraction from messages`, () => {
935 const config = {
936 id: `schema-test`,
937 shapeOptions: {
938 url: `http://test-url`,
939 params: {
940 table: `test_table`,
941 },
942 },
943 getKey: (item: Row) => item.id as number,
944 startSync: true,
945 }
946​
947 const testCollection = createCollection(electricCollectionOptions(config))
948​
949 // Send message with schema information
950 subscriber([
951 {
952 key: `1`,
953 value: { id: 1, name: `User 1` },
954 headers: {
955 operation: `insert`,
956 schema: `custom_schema`,
957 },
958 },
959 {
960 headers: { control: `up-to-date` },
961 },
962 ])
963​
964 // Schema should be stored and used in sync metadata
965 // This is internal behavior, but we can verify it doesn't cause errors
966 expect(testCollection.has(1)).toBe(true)
967 })
968​
969 it(`should handle invalid schema information gracefully`, () => {
970 const config = {
971 id: `invalid-schema-test`,
972 shapeOptions: {
973 url: `http://test-url`,
974 params: {
975 table: `test_table`,
976 },
977 },
978 getKey: (item: Row) => item.id as number,
979 startSync: true,
980 }
981​
982 const testCollection = createCollection(electricCollectionOptions(config))
983​
984 // Send message with invalid schema information
985 expect(() => {
986 subscriber([
987 {
988 key: `1`,
989 value: { id: 1, name: `User 1` },
990 headers: {
991 operation: `insert`,
992 schema: 123 as any, // Invalid schema type
993 },
994 },
995 {
996 headers: { control: `up-to-date` },
997 },
998 ])
999 }).not.toThrow()
1000​
1001 expect(testCollection.has(1)).toBe(true)
1002 })
1003​
1004 it(`should handle txids from control messages`, async () => {
1005 const config = {
1006 id: `control-txid-test`,
1007 shapeOptions: {
1008 url: `http://test-url`,
1009 params: {
1010 table: `test_table`,
1011 },
1012 },
1013 getKey: (item: Row) => item.id as number,
1014 startSync: true,
1016​
1017 const testCollection = createCollection(electricCollectionOptions(config))
1018​
1019 // Send control message with txids (as numbers, per Electric API)
1020 subscriber([
1022 headers: {
1023 control: `up-to-date`,
1024 txids: [300, 400],
1025 },
1026 },
1027 ])
1028​
1029 // Txids should be tracked (converted to strings internally)
1030 await expect(testCollection.utils.awaitTxId(300)).resolves.toBe(true)
1031 await expect(testCollection.utils.awaitTxId(400)).resolves.toBe(true)
1032 })
1033​
1034 it(`should resync after garbage collection and new subscription`, () => {
1035 // Use fake timers for this test
1036 vi.useFakeTimers()
1037​
1038 const config = {
1039 id: `gc-resync-test`,
1040 shapeOptions: {
1041 url: `http://test-url`,
1042 params: {
1043 table: `test_table`,
1044 },
1045 },
1046 getKey: (item: Row) => item.id as number,
1047 startSync: true,
1048 gcTime: 100, // Short GC time for testing
1050​
1051 const testCollection = createCollection(electricCollectionOptions(config))
1052​
1053 // Populate collection with initial data
1054 subscriber([
1056 key: `1`,
1057 value: { id: 1, name: `Initial User` },
1058 headers: { operation: `insert` },
1059 },
1061 key: `2`,
1062 value: { id: 2, name: `Another User` },
1063 headers: { operation: `insert` },
1064 },
1066 headers: { control: `up-to-date` },
1067 },
1068 ])
1069​
1070 // Verify initial data is present
1071 expect(testCollection.has(1)).toBe(true)
1072 expect(testCollection.has(2)).toBe(true)
1073 expect(testCollection.size).toBe(2)
1074​
1075 // Subscribe and then unsubscribe to trigger GC timer
1076 const subscription = testCollection.subscribeChanges(() => {})
1077 subscription.unsubscribe()
1078​
1079 // Collection should still be ready before GC timer fires
1080 expect(testCollection.status).toBe(`ready`)
1081 expect(testCollection.size).toBe(2)
1082​
1083 // Fast-forward time to trigger GC (past the 100ms gcTime)
1084 vi.advanceTimersByTime(150)
1085​
1086 // Collection should be cleaned up
1087 expect(testCollection.status).toBe(`cleaned-up`)
1088 expect(testCollection.size).toBe(0)
1089​
1090 // Reset mock call count for new subscription
1091 const initialMockCallCount = mockSubscribe.mock.calls.length
1092​
1093 // Subscribe again - this should restart the sync
1094 const newSubscription = testCollection.subscribeChanges(() => {})
1095​
1096 // Should have created a new stream
1097 expect(mockSubscribe.mock.calls.length).toBe(initialMockCallCount + 1)
1098 expect(testCollection.status).toBe(`loading`)
1099​
1100 // Send new data to simulate resync
1101 subscriber([
1103 key: `3`,
1104 value: { id: 3, name: `Resynced User` },
1105 headers: { operation: `insert` },
1106 },
1108 key: `1`,
1109 value: { id: 1, name: `Updated User` },
1110 headers: { operation: `insert` },
1111 },
1113 headers: { control: `up-to-date` },
1114 },
1115 ])
1116​
1117 // Verify the collection has resynced with new data
1118 expect(testCollection.status).toBe(`ready`)
1119 expect(testCollection.has(1)).toBe(true)
1120 expect(testCollection.has(3)).toBe(true)
1121 expect(testCollection.get(1)).toEqual({ id: 1, name: `Updated User` })
1122 expect(testCollection.get(3)).toEqual({ id: 3, name: `Resynced User` })
1123 expect(testCollection.size).toBe(2)
1124​
1125 // Old data should not be present (collection was cleaned)
1126 expect(testCollection.has(2)).toBe(false)
1127​
1128 newSubscription.unsubscribe()
1129​
1130 // Restore real timers
1131 vi.useRealTimers()
1132 })
1133 })