Open History to see the last commit
1import {
2 ShapeStream,
3 isChangeMessage,
4 isControlMessage,
5 isVisibleInSnapshot,
6} from "@electric-sql/client"
7import { Store } from "@tanstack/store"
8import DebugModule from "debug"
9import {
10 ExpectedNumberInAwaitTxIdError,
11 StreamAbortedError,
12 TimeoutWaitingForMatchError,
13 TimeoutWaitingForTxIdError,
14} from "./errors"
15import type {
16 BaseCollectionConfig,
17 CollectionConfig,
18 DeleteMutationFnParams,
19 InsertMutationFnParams,
20 SyncConfig,
21 UpdateMutationFnParams,
22 UtilsRecord,
23} from "@tanstack/db"
24import type { StandardSchemaV1 } from "@standard-schema/spec"
25import type {
26 ControlMessage,
27 GetExtensions,
28 Message,
29 PostgresSnapshot,
30 Row,
31 ShapeStreamOptions,
32} from "@electric-sql/client"
33
34// Re-export for user convenience in custom match functions
35export { isChangeMessage, isControlMessage } from "@electric-sql/client"
36
37const debug = DebugModule.debug(`ts/db:electric`)
38
39/**
40 * Type representing a transaction ID in ElectricSQL
41 */
42export type Txid = number
43
44/**
45 * Custom match function type - receives stream messages and returns boolean
46 * indicating if the mutation has been synchronized
47 */
48export type MatchFunction<T extends Row<unknown>> = (
49 message: Message<T>
50) => boolean
51
52/**
53 * Matching strategies for Electric synchronization
54 * Handlers can return:
55 * - Txid strategy: { txid: number | number[] } (recommended)
56 * - Void (no return value) - mutation completes without waiting
57 */
58export type MatchingStrategy = { txid: Txid | Array<Txid> } | void
59
60/**
61 * Type representing a snapshot end message
62 */
63type SnapshotEndMessage = ControlMessage & {
64 headers: { control: `snapshot-end` }
65}
66// The `InferSchemaOutput` and `ResolveType` are copied from the `@tanstack/db` package
67// but we modified `InferSchemaOutput` slightly to restrict the schema output to `Row<unknown>`
68// This is needed in order for `GetExtensions` to be able to infer the parser extensions type from the schema
69type InferSchemaOutput<T> = T extends StandardSchemaV1
70 ? StandardSchemaV1.InferOutput<T> extends Row<unknown>
71 ? StandardSchemaV1.InferOutput<T>
72 : Record<string, unknown>
73 : Record<string, unknown>
74
75/**
76 * Configuration interface for Electric collection options
77 * @template T - The type of items in the collection
78 * @template TSchema - The schema type for validation
79 */
80export interface ElectricCollectionConfig<
81 T extends Row<unknown> = Row<unknown>,
82 TSchema extends StandardSchemaV1 = never,
83> extends Omit<
84 BaseCollectionConfig<T, string | number, TSchema, UtilsRecord, any>,
85 `onInsert` | `onUpdate` | `onDelete`
86 > {
87 /**
88 * Configuration options for the ElectricSQL ShapeStream
89 */
90 shapeOptions: ShapeStreamOptions<GetExtensions<T>>
91
92 /**
93 * Optional asynchronous handler function called before an insert operation
94 * @param params Object containing transaction and collection information
95 * @returns Promise resolving to { txid } or void
96 * @example
97 * // Basic Electric insert handler with txid (recommended)
98 * onInsert: async ({ transaction }) => {
99 * const newItem = transaction.mutations[0].modified
100 * const result = await api.todos.create({
101 * data: newItem
102 * })
103 * return { txid: result.txid }
104 * }
105 *
106 * @example
107 * // Insert handler with multiple items - return array of txids
108 * onInsert: async ({ transaction }) => {
109 * const items = transaction.mutations.map(m => m.modified)
110 * const results = await Promise.all(
111 * items.map(item => api.todos.create({ data: item }))
112 * )
113 * return { txid: results.map(r => r.txid) }
114 * }
115 *
116 * @example
117 * // Use awaitMatch utility for custom matching
118 * onInsert: async ({ transaction, collection }) => {
119 * const newItem = transaction.mutations[0].modified
120 * await api.todos.create({ data: newItem })
121 * await collection.utils.awaitMatch(
122 * (message) => isChangeMessage(message) &&
123 * message.headers.operation === 'insert' &&
124 * message.value.name === newItem.name
125 * )
126 * }
127 */
128 onInsert?: (params: InsertMutationFnParams<T>) => Promise<MatchingStrategy>
129
130 /**
131 * Optional asynchronous handler function called before an update operation
132 * @param params Object containing transaction and collection information
133 * @returns Promise resolving to { txid } or void
134 * @example
135 * // Basic Electric update handler with txid (recommended)
136 * onUpdate: async ({ transaction }) => {
137 * const { original, changes } = transaction.mutations[0]
138 * const result = await api.todos.update({
139 * where: { id: original.id },
140 * data: changes
141 * })
142 * return { txid: result.txid }
143 * }
144 *
145 * @example
146 * // Use awaitMatch utility for custom matching
147 * onUpdate: async ({ transaction, collection }) => {
148 * const { original, changes } = transaction.mutations[0]
149 * await api.todos.update({ where: { id: original.id }, data: changes })
150 * await collection.utils.awaitMatch(
151 * (message) => isChangeMessage(message) &&
152 * message.headers.operation === 'update' &&
153 * message.value.id === original.id
154 * )
155 * }
156 */
157 onUpdate?: (params: UpdateMutationFnParams<T>) => Promise<MatchingStrategy>
158
159 /**
160 * Optional asynchronous handler function called before a delete operation
161 * @param params Object containing transaction and collection information
162 * @returns Promise resolving to { txid } or void
163 * @example
164 * // Basic Electric delete handler with txid (recommended)
165 * onDelete: async ({ transaction }) => {
166 * const mutation = transaction.mutations[0]
167 * const result = await api.todos.delete({
168 * id: mutation.original.id
169 * })
170 * return { txid: result.txid }
171 * }
172 *
173 * @example
174 * // Use awaitMatch utility for custom matching
175 * onDelete: async ({ transaction, collection }) => {
176 * const mutation = transaction.mutations[0]
177 * await api.todos.delete({ id: mutation.original.id })
178 * await collection.utils.awaitMatch(
179 * (message) => isChangeMessage(message) &&
180 * message.headers.operation === 'delete' &&
181 * message.value.id === mutation.original.id
182 * )
183 * }
184 */
185 onDelete?: (params: DeleteMutationFnParams<T>) => Promise<MatchingStrategy>
186}
187
188function isUpToDateMessage<T extends Row<unknown>>(
189 message: Message<T>
190): message is ControlMessage & { up_to_date: true } {
191 return isControlMessage(message) && message.headers.control === `up-to-date`
192}
193
194function isMustRefetchMessage<T extends Row<unknown>>(
195 message: Message<T>
196): message is ControlMessage & { headers: { control: `must-refetch` } } {
197 return isControlMessage(message) && message.headers.control === `must-refetch`
198}
199
200function isSnapshotEndMessage<T extends Row<unknown>>(
201 message: Message<T>
202): message is SnapshotEndMessage {
203 return isControlMessage(message) && message.headers.control === `snapshot-end`
204}
205
206function parseSnapshotMessage(message: SnapshotEndMessage): PostgresSnapshot {
207 return {
208 xmin: message.headers.xmin,
209 xmax: message.headers.xmax,
210 xip_list: message.headers.xip_list,
211 }
212}
213
214// Check if a message contains txids in its headers
215function hasTxids<T extends Row<unknown>>(
216 message: Message<T>
217): message is Message<T> & { headers: { txids?: Array<Txid> } } {
218 return `txids` in message.headers && Array.isArray(message.headers.txids)
219}
220
221/**
222 * Type for the awaitTxId utility function
223 */
224export type AwaitTxIdFn = (txId: Txid, timeout?: number) => Promise<boolean>
225
226/**
227 * Type for the awaitMatch utility function
228 */
229export type AwaitMatchFn<T extends Row<unknown>> = (
230 matchFn: MatchFunction<T>,
231 timeout?: number
232) => Promise<boolean>
233
234/**
235 * Electric collection utilities type
236 */
237export interface ElectricCollectionUtils<T extends Row<unknown> = Row<unknown>>
238 extends UtilsRecord {
239 awaitTxId: AwaitTxIdFn
240 awaitMatch: AwaitMatchFn<T>
241}
242
243/**
244 * Creates Electric collection options for use with a standard Collection
245 *
246 * @template T - The explicit type of items in the collection (highest priority)
247 * @template TSchema - The schema type for validation and type inference (second priority)
248 * @template TFallback - The fallback type if no explicit or schema type is provided
249 * @param config - Configuration options for the Electric collection
250 * @returns Collection options with utilities
251 */
252
253// Overload for when schema is provided
254export function electricCollectionOptions<T extends StandardSchemaV1>(
255 config: ElectricCollectionConfig<InferSchemaOutput<T>, T> & {
256 schema: T
257 }
258): CollectionConfig<InferSchemaOutput<T>, string | number, T> & {
259 id?: string
260 utils: ElectricCollectionUtils
261 schema: T
262}
263
264// Overload for when no schema is provided
265export function electricCollectionOptions<T extends Row<unknown>>(
266 config: ElectricCollectionConfig<T> & {
267 schema?: never // prohibit schema
268 }
269): CollectionConfig<T, string | number> & {
270 id?: string
271 utils: ElectricCollectionUtils
272 schema?: never // no schema in the result
273}
274
275export function electricCollectionOptions(
276 config: ElectricCollectionConfig<any, any>
277): CollectionConfig<any, string | number, any> & {
278 id?: string
279 utils: ElectricCollectionUtils
280 schema?: any
281} {
282 const seenTxids = new Store<Set<Txid>>(new Set([]))
283 const seenSnapshots = new Store<Array<PostgresSnapshot>>([])
284 const pendingMatches = new Store<
285 Map<
286 string,
287 {
288 matchFn: (message: Message<any>) => boolean
289 resolve: (value: boolean) => void
290 reject: (error: Error) => void
291 timeoutId: ReturnType<typeof setTimeout>
292 matched: boolean
293 }
294 >
295 >(new Map())
296
297 // Buffer messages since last up-to-date to handle race conditions
298 const currentBatchMessages = new Store<Array<Message<any>>>([])
299
300 /**
301 * Helper function to remove multiple matches from the pendingMatches store
302 */
303 const removePendingMatches = (matchIds: Array<string>) => {
304 if (matchIds.length > 0) {
305 pendingMatches.setState((current) => {
306 const newMatches = new Map(current)
307 matchIds.forEach((id) => newMatches.delete(id))
308 return newMatches
309 })
310 }
311 }
312
313 /**
314 * Helper function to resolve and cleanup matched pending matches
315 */
316 const resolveMatchedPendingMatches = () => {
317 const matchesToResolve: Array<string> = []
318 pendingMatches.state.forEach((match, matchId) => {
319 if (match.matched) {
320 clearTimeout(match.timeoutId)
321 match.resolve(true)
322 matchesToResolve.push(matchId)
323 debug(
324 `${config.id ? `[${config.id}] ` : ``}awaitMatch resolved on up-to-date for match %s`,
325 matchId
326 )
327 }
328 })
329 removePendingMatches(matchesToResolve)
330 }
331 const sync = createElectricSync<any>(config.shapeOptions, {
332 seenTxids,
333 seenSnapshots,
334 pendingMatches,
335 currentBatchMessages,
336 removePendingMatches,
337 resolveMatchedPendingMatches,
338 collectionId: config.id,
339 })
340
341 /**
342 * Wait for a specific transaction ID to be synced
343 * @param txId The transaction ID to wait for as a number
344 * @param timeout Optional timeout in milliseconds (defaults to 5000ms)
345 * @returns Promise that resolves when the txId is synced
346 */
347 const awaitTxId: AwaitTxIdFn = async (
348 txId: Txid,
349 timeout: number = 5000
350 ): Promise<boolean> => {
351 debug(
352 `${config.id ? `[${config.id}] ` : ``}awaitTxId called with txid %d`,
353 txId
354 )
355 if (typeof txId !== `number`) {
356 throw new ExpectedNumberInAwaitTxIdError(typeof txId, config.id)
357 }
358
359 // First check if the txid is in the seenTxids store
360 const hasTxid = seenTxids.state.has(txId)
361 if (hasTxid) return true
362
363 // Then check if the txid is in any of the seen snapshots
364 const hasSnapshot = seenSnapshots.state.some((snapshot) =>
365 isVisibleInSnapshot(txId, snapshot)
366 )
367 if (hasSnapshot) return true
368
369 return new Promise((resolve, reject) => {
370 const timeoutId = setTimeout(() => {
371 unsubscribeSeenTxids()
372 unsubscribeSeenSnapshots()
373 reject(new TimeoutWaitingForTxIdError(txId, config.id))
374 }, timeout)
375
376 const unsubscribeSeenTxids = seenTxids.subscribe(() => {
377 if (seenTxids.state.has(txId)) {
378 debug(
379 `${config.id ? `[${config.id}] ` : ``}awaitTxId found match for txid %o`,
380 txId
381 )
382 clearTimeout(timeoutId)
383 unsubscribeSeenTxids()
384 unsubscribeSeenSnapshots()
385 resolve(true)
386 }
387 })
388
389 const unsubscribeSeenSnapshots = seenSnapshots.subscribe(() => {
390 const visibleSnapshot = seenSnapshots.state.find((snapshot) =>
391 isVisibleInSnapshot(txId, snapshot)
392 )
393 if (visibleSnapshot) {
394 debug(
395 `${config.id ? `[${config.id}] ` : ``}awaitTxId found match for txid %o in snapshot %o`,
396 txId,
397 visibleSnapshot
398 )
399 clearTimeout(timeoutId)
400 unsubscribeSeenSnapshots()
401 unsubscribeSeenTxids()
402 resolve(true)
403 }
404 })
405 })
406 }
407
408 /**
409 * Wait for a custom match function to find a matching message
410 * @param matchFn Function that returns true when a message matches
411 * @param timeout Optional timeout in milliseconds (defaults to 5000ms)
412 * @returns Promise that resolves when a matching message is found
413 */
414 const awaitMatch: AwaitMatchFn<any> = async (
415 matchFn: MatchFunction<any>,
416 timeout: number = 3000
417 ): Promise<boolean> => {
418 debug(
419 `${config.id ? `[${config.id}] ` : ``}awaitMatch called with custom function`
420 )
421
422 return new Promise((resolve, reject) => {
423 const matchId = Math.random().toString(36)
424
425 const cleanupMatch = () => {
426 pendingMatches.setState((current) => {
427 const newMatches = new Map(current)
428 newMatches.delete(matchId)
429 return newMatches
430 })
431 }
432
433 const onTimeout = () => {
434 cleanupMatch()
435 reject(new TimeoutWaitingForMatchError(config.id))
436 }
437
438 const timeoutId = setTimeout(onTimeout, timeout)
439
440 // We need access to the stream messages to check against the match function
441 // This will be handled by the sync configuration
442 const checkMatch = (message: Message<any>) => {
443 if (matchFn(message)) {
444 debug(
445 `${config.id ? `[${config.id}] ` : ``}awaitMatch found matching message, waiting for up-to-date`
446 )
447 // Mark as matched but don't resolve yet - wait for up-to-date
448 pendingMatches.setState((current) => {
449 const newMatches = new Map(current)
450 const existing = newMatches.get(matchId)
451 if (existing) {
452 newMatches.set(matchId, { ...existing, matched: true })
453 }
454 return newMatches
455 })
456 return true
457 }
458 return false
459 }
460
461 // Check against current batch messages first to handle race conditions
462 for (const message of currentBatchMessages.state) {
463 if (matchFn(message)) {
464 debug(
465 `${config.id ? `[${config.id}] ` : ``}awaitMatch found immediate match in current batch, waiting for up-to-date`
466 )
467 // Register match as already matched
468 pendingMatches.setState((current) => {
469 const newMatches = new Map(current)
470 newMatches.set(matchId, {
471 matchFn: checkMatch,
472 resolve,
473 reject,
474 timeoutId,
475 matched: true, // Already matched
476 })
477 return newMatches
478 })
479 return
480 }
481 }
482
483 // Store the match function for the sync process to use
484 // We'll add this to a pending matches store
485 pendingMatches.setState((current) => {
486 const newMatches = new Map(current)
487 newMatches.set(matchId, {
488 matchFn: checkMatch,
489 resolve,
490 reject,
491 timeoutId,
492 matched: false,
493 })
494 return newMatches
495 })
496 })
497 }
498
499 /**
500 * Process matching strategy and wait for synchronization
501 */
502 const processMatchingStrategy = async (
503 result: MatchingStrategy
504 ): Promise<void> => {
505 // Only wait if result contains txid
506 if (result && `txid` in result) {
507 // Handle both single txid and array of txids
508 if (Array.isArray(result.txid)) {
509 await Promise.all(result.txid.map(awaitTxId))
510 } else {
511 await awaitTxId(result.txid)
512 }
513 }
514 // If result is void/undefined, don't wait - mutation completes immediately
515 }
516
517 // Create wrapper handlers for direct persistence operations that handle different matching strategies
518 const wrappedOnInsert = config.onInsert
519 ? async (params: InsertMutationFnParams<any>) => {
520 const handlerResult = await config.onInsert!(params)
521 await processMatchingStrategy(handlerResult)
522 return handlerResult
523 }
524 : undefined
525
526 const wrappedOnUpdate = config.onUpdate
527 ? async (params: UpdateMutationFnParams<any>) => {
528 const handlerResult = await config.onUpdate!(params)
529 await processMatchingStrategy(handlerResult)
530 return handlerResult
531 }
532 : undefined
533
534 const wrappedOnDelete = config.onDelete
535 ? async (params: DeleteMutationFnParams<any>) => {
536 const handlerResult = await config.onDelete!(params)
537 await processMatchingStrategy(handlerResult)
538 return handlerResult
539 }
540 : undefined
541
542 // Extract standard Collection config properties
543 const {
544 shapeOptions: _shapeOptions,
545 onInsert: _onInsert,
546 onUpdate: _onUpdate,
547 onDelete: _onDelete,
548 ...restConfig
549 } = config
550
551 return {
552 ...restConfig,
553 sync,
554 onInsert: wrappedOnInsert,
555 onUpdate: wrappedOnUpdate,
556 onDelete: wrappedOnDelete,
557 utils: {
558 awaitTxId,
559 awaitMatch,
560 } as ElectricCollectionUtils<any>,
561 }
562}
563
564/**
565 * Internal function to create ElectricSQL sync configuration
566 */
567function createElectricSync<T extends Row<unknown>>(
568 shapeOptions: ShapeStreamOptions<GetExtensions<T>>,
569 options: {
570 seenTxids: Store<Set<Txid>>
571 seenSnapshots: Store<Array<PostgresSnapshot>>
572 pendingMatches: Store<
573 Map<
574 string,
575 {
576 matchFn: (message: Message<T>) => boolean
577 resolve: (value: boolean) => void
578 reject: (error: Error) => void
579 timeoutId: ReturnType<typeof setTimeout>
580 matched: boolean
581 }
582 >
583 >
584 currentBatchMessages: Store<Array<Message<T>>>
585 removePendingMatches: (matchIds: Array<string>) => void
586 resolveMatchedPendingMatches: () => void
587 collectionId?: string
588 }
589): SyncConfig<T> {
590 const {
591 seenTxids,
592 seenSnapshots,
593 pendingMatches,
594 currentBatchMessages,
595 removePendingMatches,
596 resolveMatchedPendingMatches,
597 collectionId,
598 } = options
599 const MAX_BATCH_MESSAGES = 1000 // Safety limit for message buffer
600
601 // Store for the relation schema information
602 const relationSchema = new Store<string | undefined>(undefined)
603
604 /**
605 * Get the sync metadata for insert operations
606 * @returns Record containing relation information
607 */
608 const getSyncMetadata = (): Record<string, unknown> => {
609 // Use the stored schema if available, otherwise default to 'public'
610 const schema = relationSchema.state || `public`
611
612 return {
613 relation: shapeOptions.params?.table
614 ? [schema, shapeOptions.params.table]
615 : undefined,
616 }
617 }
618
619 let unsubscribeStream: () => void
620
621 return {
622 sync: (params: Parameters<SyncConfig<T>[`sync`]>[0]) => {
623 const { begin, write, commit, markReady, truncate, collection } = params
624
625 // Abort controller for the stream - wraps the signal if provided
626 const abortController = new AbortController()
627
628 if (shapeOptions.signal) {
629 shapeOptions.signal.addEventListener(
630 `abort`,
631 () => {
632 abortController.abort()
633 },
634 {
635 once: true,
636 }
637 )
638 if (shapeOptions.signal.aborted) {
639 abortController.abort()
640 }
641 }
642
643 // Cleanup pending matches on abort
644 abortController.signal.addEventListener(`abort`, () => {
645 pendingMatches.setState((current) => {
646 current.forEach((match) => {
647 clearTimeout(match.timeoutId)
648 match.reject(new StreamAbortedError())
649 })
650 return new Map() // Clear all pending matches
651 })
652 })
653
654 const stream = new ShapeStream({
655 ...shapeOptions,
656 signal: abortController.signal,
657 onError: (errorParams) => {
658 // Just immediately mark ready if there's an error to avoid blocking
659 // apps waiting for `.preload()` to finish.
660 // Note that Electric sends a 409 error on a `must-refetch` message, but the
661 // ShapeStream handled this and it will not reach this handler, therefor
662 // this markReady will not be triggers by a `must-refetch`.
663 markReady()
664
665 if (shapeOptions.onError) {
666 return shapeOptions.onError(errorParams)
667 } else {
668 console.error(
669 `An error occurred while syncing collection: ${collection.id}, \n` +
670 `it has been marked as ready to avoid blocking apps waiting for '.preload()' to finish. \n` +
671 `You can provide an 'onError' handler on the shapeOptions to handle this error, and this message will not be logged.`,
672 errorParams
673 )
674 }
675
676 return
677 },
678 })
679 let transactionStarted = false
680 const newTxids = new Set<Txid>()
681 const newSnapshots: Array<PostgresSnapshot> = []
682
683 unsubscribeStream = stream.subscribe((messages: Array<Message<T>>) => {
684 let hasUpToDate = false
685
686 for (const message of messages) {
687 // Add message to current batch buffer (for race condition handling)
688 if (isChangeMessage(message)) {
689 currentBatchMessages.setState((currentBuffer) => {
690 const newBuffer = [...currentBuffer, message]
691 // Limit buffer size for safety
692 if (newBuffer.length > MAX_BATCH_MESSAGES) {
693 newBuffer.splice(0, newBuffer.length - MAX_BATCH_MESSAGES)
694 }
695 return newBuffer
696 })
697 }
698
699 // Check for txids in the message and add them to our store
700 if (hasTxids(message)) {
701 message.headers.txids?.forEach((txid) => newTxids.add(txid))
702 }
703
704 // Check pending matches against this message
705 // Note: matchFn will mark matches internally, we don't resolve here
706 const matchesToRemove: Array<string> = []
707 pendingMatches.state.forEach((match, matchId) => {
708 if (!match.matched) {
709 try {
710 match.matchFn(message)
711 } catch (err) {
712 // If matchFn throws, clean up and reject the promise
713 clearTimeout(match.timeoutId)
714 match.reject(
715 err instanceof Error ? err : new Error(String(err))
716 )
717 matchesToRemove.push(matchId)
718 debug(`matchFn error: %o`, err)
719 }
720 }
721 })
722
723 // Remove matches that errored
724 removePendingMatches(matchesToRemove)
725
726 if (isChangeMessage(message)) {
727 // Check if the message contains schema information
728 const schema = message.headers.schema
729 if (schema && typeof schema === `string`) {
730 // Store the schema for future use if it's a valid string
731 relationSchema.setState(() => schema)
732 }
733
734 if (!transactionStarted) {
735 begin()
736 transactionStarted = true
737 }
738
739 write({
740 type: message.headers.operation,
741 value: message.value,
742 // Include the primary key and relation info in the metadata
743 metadata: {
744 ...message.headers,
745 },
746 })
747 } else if (isSnapshotEndMessage(message)) {
748 newSnapshots.push(parseSnapshotMessage(message))
749 } else if (isUpToDateMessage(message)) {
750 hasUpToDate = true
751 } else if (isMustRefetchMessage(message)) {
752 debug(
753 `${collectionId ? `[${collectionId}] ` : ``}Received must-refetch message, starting transaction with truncate`
754 )
755
756 // Start a transaction and truncate the collection
757 if (!transactionStarted) {
758 begin()
759 transactionStarted = true
760 }
761
762 truncate()
763
764 // Reset hasUpToDate so we continue accumulating changes until next up-to-date
765 hasUpToDate = false
766 }
767 }
768
769 if (hasUpToDate) {
770 // Clear the current batch buffer since we're now up-to-date
771 currentBatchMessages.setState(() => [])
772
773 // Commit transaction if one was started
774 if (transactionStarted) {
775 commit()
776 transactionStarted = false
777 }
778
779 // Mark the collection as ready now that sync is up to date
780 markReady()
781
782 // Always commit txids when we receive up-to-date, regardless of transaction state
783 seenTxids.setState((currentTxids) => {
784 const clonedSeen = new Set<Txid>(currentTxids)
785 if (newTxids.size > 0) {
786 debug(
787 `${collectionId ? `[${collectionId}] ` : ``}new txids synced from pg %O`,
788 Array.from(newTxids)
789 )
790 }
791 newTxids.forEach((txid) => clonedSeen.add(txid))
792 newTxids.clear()
793 return clonedSeen
794 })
795
796 // Always commit snapshots when we receive up-to-date, regardless of transaction state
797 seenSnapshots.setState((currentSnapshots) => {
798 const seen = [...currentSnapshots, ...newSnapshots]
799 newSnapshots.forEach((snapshot) =>
800 debug(
801 `${collectionId ? `[${collectionId}] ` : ``}new snapshot synced from pg %o`,
802 snapshot
803 )
804 )
805 newSnapshots.length = 0
806 return seen
807 })
808
809 // Resolve all matched pending matches on up-to-date
810 resolveMatchedPendingMatches()
811 }
812 })
813
814 // Return the unsubscribe function
815 return () => {
816 // Unsubscribe from the stream
817 unsubscribeStream()
818 // Abort the abort controller to stop the stream
819 abortController.abort()
820 }
821 },
822 // Expose the getSyncMetadata function
823 getSyncMetadata,
824 }
825}