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

electric.ts

592 lines19.1 KB

1import {
2 ShapeStream,
3 isChangeMessage,
4 isControlMessage,
5} from "@electric-sql/client"
6import { Store } from "@tanstack/store"
7import DebugModule from "debug"
8import {
9 ElectricDeleteHandlerMustReturnTxIdError,
10 ElectricInsertHandlerMustReturnTxIdError,
11 ElectricUpdateHandlerMustReturnTxIdError,
12 ExpectedNumberInAwaitTxIdError,
13 TimeoutWaitingForTxIdError,
14} from "./errors"
15import type {
16 CollectionConfig,
17 DeleteMutationFnParams,
18 InsertMutationFnParams,
19 SyncConfig,
20 UpdateMutationFnParams,
21 UtilsRecord,
22} from "@tanstack/db"
23import type { StandardSchemaV1 } from "@standard-schema/spec"
24import type {
25 ControlMessage,
26 GetExtensions,
27 Message,
28 Row,
29 ShapeStreamOptions,
30} from "@electric-sql/client"
31​
32const debug = DebugModule.debug(`ts/db:electric`)
33​
34/**
35 * Type representing a transaction ID in ElectricSQL
36 */
37export type Txid = number
38​
39// The `InferSchemaOutput` and `ResolveType` are copied from the `@tanstack/db` package
40// but we modified `InferSchemaOutput` slightly to restrict the schema output to `Row<unknown>`
41// This is needed in order for `GetExtensions` to be able to infer the parser extensions type from the schema
42type InferSchemaOutput<T> = T extends StandardSchemaV1
43 ? StandardSchemaV1.InferOutput<T> extends Row<unknown>
44 ? StandardSchemaV1.InferOutput<T>
45 : Record<string, unknown>
46 : Record<string, unknown>
47​
48type ResolveType<
49 TExplicit extends Row<unknown> = Row<unknown>,
50 TSchema extends StandardSchemaV1 = never,
51 TFallback extends object = Record<string, unknown>,
52> =
53 unknown extends GetExtensions<TExplicit>
54 ? [TSchema] extends [never]
55 ? TFallback
56 : InferSchemaOutput<TSchema>
57 : TExplicit
58​
59/**
60 * Configuration interface for Electric collection options
61 * @template TExplicit - The explicit type of items in the collection (highest priority)
62 * @template TSchema - The schema type for validation and type inference (second priority)
63 * @template TFallback - The fallback type if no explicit or schema type is provided
64 *
65 * @remarks
66 * Type resolution follows a priority order:
67 * 1. If you provide an explicit type via generic parameter, it will be used
68 * 2. If no explicit type is provided but a schema is, the schema's output type will be inferred
69 * 3. If neither explicit type nor schema is provided, the fallback type will be used
70 *
71 * You should provide EITHER an explicit type OR a schema, but not both, as they would conflict.
72 */
73export interface ElectricCollectionConfig<
74 TExplicit extends Row<unknown> = Row<unknown>,
75 TSchema extends StandardSchemaV1 = never,
76 TFallback extends Row<unknown> = Row<unknown>,
77> {
78 /**
79 * Configuration options for the ElectricSQL ShapeStream
80 */
81 shapeOptions: ShapeStreamOptions<
82 GetExtensions<ResolveType<TExplicit, TSchema, TFallback>>
83 >
84​
85 /**
86 * All standard Collection configuration properties
87 */
88 id?: string
89 schema?: TSchema
90 getKey: CollectionConfig<ResolveType<TExplicit, TSchema, TFallback>>[`getKey`]
91 sync?: CollectionConfig<ResolveType<TExplicit, TSchema, TFallback>>[`sync`]
92​
93 /**
94 * Optional asynchronous handler function called before an insert operation
95 * Must return an object containing a txid number or array of txids
96 * @param params Object containing transaction and collection information
97 * @returns Promise resolving to an object with txid or txids
98 * @example
99 * // Basic Electric insert handler - MUST return { txid: number }
100 * onInsert: async ({ transaction }) => {
101 * const newItem = transaction.mutations[0].modified
102 * const result = await api.todos.create({
103 * data: newItem
104 * })
105 * return { txid: result.txid } // Required for Electric sync matching
106 * }
107 *
108 * @example
109 * // Insert handler with multiple items - return array of txids
110 * onInsert: async ({ transaction }) => {
111 * const items = transaction.mutations.map(m => m.modified)
112 * const results = await Promise.all(
113 * items.map(item => api.todos.create({ data: item }))
114 * )
115 * return { txid: results.map(r => r.txid) } // Array of txids
116 * }
117 *
118 * @example
119 * // Insert handler with error handling
120 * onInsert: async ({ transaction }) => {
121 * try {
122 * const newItem = transaction.mutations[0].modified
123 * const result = await api.createTodo(newItem)
124 * return { txid: result.txid }
125 * } catch (error) {
126 * console.error('Insert failed:', error)
127 * throw error // This will cause the transaction to fail
128 * }
129 * }
130 *
131 * @example
132 * // Insert handler with batch operation - single txid
133 * onInsert: async ({ transaction }) => {
134 * const items = transaction.mutations.map(m => m.modified)
135 * const result = await api.todos.createMany({
136 * data: items
137 * })
138 * return { txid: result.txid } // Single txid for batch operation
139 * }
140 */
141 onInsert?: (
142 params: InsertMutationFnParams<ResolveType<TExplicit, TSchema, TFallback>>
143 ) => Promise<{ txid: Txid | Array<Txid> }>
144​
145 /**
146 * Optional asynchronous handler function called before an update operation
147 * Must return an object containing a txid number or array of txids
148 * @param params Object containing transaction and collection information
149 * @returns Promise resolving to an object with txid or txids
150 * @example
151 * // Basic Electric update handler - MUST return { txid: number }
152 * onUpdate: async ({ transaction }) => {
153 * const { original, changes } = transaction.mutations[0]
154 * const result = await api.todos.update({
155 * where: { id: original.id },
156 * data: changes // Only the changed fields
157 * })
158 * return { txid: result.txid } // Required for Electric sync matching
159 * }
160 *
161 * @example
162 * // Update handler with multiple items - return array of txids
163 * onUpdate: async ({ transaction }) => {
164 * const updates = await Promise.all(
165 * transaction.mutations.map(m =>
166 * api.todos.update({
167 * where: { id: m.original.id },
168 * data: m.changes
169 * })
170 * )
171 * )
172 * return { txid: updates.map(u => u.txid) } // Array of txids
173 * }
174 *
175 * @example
176 * // Update handler with optimistic rollback
177 * onUpdate: async ({ transaction }) => {
178 * const mutation = transaction.mutations[0]
179 * try {
180 * const result = await api.updateTodo(mutation.original.id, mutation.changes)
181 * return { txid: result.txid }
182 * } catch (error) {
183 * // Transaction will automatically rollback optimistic changes
184 * console.error('Update failed, rolling back:', error)
185 * throw error
186 * }
187 * }
188 */
189 onUpdate?: (
190 params: UpdateMutationFnParams<ResolveType<TExplicit, TSchema, TFallback>>
191 ) => Promise<{ txid: Txid | Array<Txid> }>
192​
193 /**
194 * Optional asynchronous handler function called before a delete operation
195 * Must return an object containing a txid number or array of txids
196 * @param params Object containing transaction and collection information
197 * @returns Promise resolving to an object with txid or txids
198 * @example
199 * // Basic Electric delete handler - MUST return { txid: number }
200 * onDelete: async ({ transaction }) => {
201 * const mutation = transaction.mutations[0]
202 * const result = await api.todos.delete({
203 * id: mutation.original.id
204 * })
205 * return { txid: result.txid } // Required for Electric sync matching
206 * }
207 *
208 * @example
209 * // Delete handler with multiple items - return array of txids
210 * onDelete: async ({ transaction }) => {
211 * const deletes = await Promise.all(
212 * transaction.mutations.map(m =>
213 * api.todos.delete({
214 * where: { id: m.key }
215 * })
216 * )
217 * )
218 * return { txid: deletes.map(d => d.txid) } // Array of txids
219 * }
220 *
221 * @example
222 * // Delete handler with batch operation - single txid
223 * onDelete: async ({ transaction }) => {
224 * const idsToDelete = transaction.mutations.map(m => m.original.id)
225 * const result = await api.todos.deleteMany({
226 * ids: idsToDelete
227 * })
228 * return { txid: result.txid } // Single txid for batch operation
229 * }
230 *
231 * @example
232 * // Delete handler with optimistic rollback
233 * onDelete: async ({ transaction }) => {
234 * const mutation = transaction.mutations[0]
235 * try {
236 * const result = await api.deleteTodo(mutation.original.id)
237 * return { txid: result.txid }
238 * } catch (error) {
239 * // Transaction will automatically rollback optimistic changes
240 * console.error('Delete failed, rolling back:', error)
241 * throw error
242 * }
243 * }
244 *
245 */
246 onDelete?: (
247 params: DeleteMutationFnParams<ResolveType<TExplicit, TSchema, TFallback>>
248 ) => Promise<{ txid: Txid | Array<Txid> }>
250​
251function isUpToDateMessage<T extends Row<unknown>>(
252 message: Message<T>
253): message is ControlMessage & { up_to_date: true } {
254 return isControlMessage(message) && message.headers.control === `up-to-date`
256​
257function isMustRefetchMessage<T extends Row<unknown>>(
258 message: Message<T>
259): message is ControlMessage & { headers: { control: `must-refetch` } } {
260 return isControlMessage(message) && message.headers.control === `must-refetch`
262​
263// Check if a message contains txids in its headers
264function hasTxids<T extends Row<unknown>>(
265 message: Message<T>
266): message is Message<T> & { headers: { txids?: Array<Txid> } } {
267 return `txids` in message.headers && Array.isArray(message.headers.txids)
269​
270/**
271 * Type for the awaitTxId utility function
272 */
273export type AwaitTxIdFn = (txId: Txid, timeout?: number) => Promise<boolean>
274​
275/**
276 * Electric collection utilities type
277 */
278export interface ElectricCollectionUtils extends UtilsRecord {
279 awaitTxId: AwaitTxIdFn
281​
282/**
283 * Creates Electric collection options for use with a standard Collection
284 *
285 * @template TExplicit - The explicit type of items in the collection (highest priority)
286 * @template TSchema - The schema type for validation and type inference (second priority)
287 * @template TFallback - The fallback type if no explicit or schema type is provided
288 * @param config - Configuration options for the Electric collection
289 * @returns Collection options with utilities
290 */
291export function electricCollectionOptions<
292 TExplicit extends Row<unknown> = Row<unknown>,
293 TSchema extends StandardSchemaV1 = never,
294 TFallback extends Row<unknown> = Row<unknown>,
295>(config: ElectricCollectionConfig<TExplicit, TSchema, TFallback>) {
296 const seenTxids = new Store<Set<Txid>>(new Set([]))
297 const sync = createElectricSync<ResolveType<TExplicit, TSchema, TFallback>>(
298 config.shapeOptions,
299 {
300 seenTxids,
301 }
302 )
303​
304 /**
305 * Wait for a specific transaction ID to be synced
306 * @param txId The transaction ID to wait for as a number
307 * @param timeout Optional timeout in milliseconds (defaults to 30000ms)
308 * @returns Promise that resolves when the txId is synced
309 */
310 const awaitTxId: AwaitTxIdFn = async (
311 txId: Txid,
312 timeout: number = 30000
313 ): Promise<boolean> => {
314 debug(`awaitTxId called with txid %d`, txId)
315 if (typeof txId !== `number`) {
316 throw new ExpectedNumberInAwaitTxIdError(typeof txId)
317 }
318​
319 const hasTxid = seenTxids.state.has(txId)
320 if (hasTxid) return true
321​
322 return new Promise((resolve, reject) => {
323 const timeoutId = setTimeout(() => {
324 unsubscribe()
325 reject(new TimeoutWaitingForTxIdError(txId))
326 }, timeout)
327​
328 const unsubscribe = seenTxids.subscribe(() => {
329 if (seenTxids.state.has(txId)) {
330 debug(`awaitTxId found match for txid %o`, txId)
331 clearTimeout(timeoutId)
332 unsubscribe()
333 resolve(true)
334 }
335 })
336 })
337 }
338​
339 // Create wrapper handlers for direct persistence operations that handle txid awaiting
340 const wrappedOnInsert = config.onInsert
341 ? async (
342 params: InsertMutationFnParams<
343 ResolveType<TExplicit, TSchema, TFallback>
344 >
345 ) => {
346 // Runtime check (that doesn't follow type)
347 // eslint-disable-next-line
348 const handlerResult = (await config.onInsert!(params)) ?? {}
349 const txid = (handlerResult as { txid?: Txid | Array<Txid> }).txid
350​
351 if (!txid) {
352 throw new ElectricInsertHandlerMustReturnTxIdError()
353 }
354​
355 // Handle both single txid and array of txids
356 if (Array.isArray(txid)) {
357 await Promise.all(txid.map((id) => awaitTxId(id)))
358 } else {
359 await awaitTxId(txid)
360 }
361​
362 return handlerResult
363 }
364 : undefined
365​
366 const wrappedOnUpdate = config.onUpdate
367 ? async (
368 params: UpdateMutationFnParams<
369 ResolveType<TExplicit, TSchema, TFallback>
370 >
371 ) => {
372 // Runtime check (that doesn't follow type)
373 // eslint-disable-next-line
374 const handlerResult = (await config.onUpdate!(params)) ?? {}
375 const txid = (handlerResult as { txid?: Txid | Array<Txid> }).txid
376​
377 if (!txid) {
378 throw new ElectricUpdateHandlerMustReturnTxIdError()
379 }
380​
381 // Handle both single txid and array of txids
382 if (Array.isArray(txid)) {
383 await Promise.all(txid.map((id) => awaitTxId(id)))
384 } else {
385 await awaitTxId(txid)
386 }
387​
388 return handlerResult
389 }
390 : undefined
391​
392 const wrappedOnDelete = config.onDelete
393 ? async (
394 params: DeleteMutationFnParams<
395 ResolveType<TExplicit, TSchema, TFallback>
396 >
397 ) => {
398 const handlerResult = await config.onDelete!(params)
399 if (!handlerResult.txid) {
400 throw new ElectricDeleteHandlerMustReturnTxIdError()
401 }
402​
403 // Handle both single txid and array of txids
404 if (Array.isArray(handlerResult.txid)) {
405 await Promise.all(handlerResult.txid.map((id) => awaitTxId(id)))
406 } else {
407 await awaitTxId(handlerResult.txid)
408 }
409​
410 return handlerResult
411 }
412 : undefined
413​
414 // Extract standard Collection config properties
415 const {
416 shapeOptions: _shapeOptions,
417 onInsert: _onInsert,
418 onUpdate: _onUpdate,
419 onDelete: _onDelete,
420 ...restConfig
421 } = config
422​
423 return {
424 ...restConfig,
425 sync,
426 onInsert: wrappedOnInsert,
427 onUpdate: wrappedOnUpdate,
428 onDelete: wrappedOnDelete,
429 utils: {
430 awaitTxId,
431 },
432 }
434​
435/**
436 * Internal function to create ElectricSQL sync configuration
437 */
438function createElectricSync<T extends Row<unknown>>(
439 shapeOptions: ShapeStreamOptions<GetExtensions<T>>,
440 options: {
441 seenTxids: Store<Set<Txid>>
442 }
443): SyncConfig<T> {
444 const { seenTxids } = options
445​
446 // Store for the relation schema information
447 const relationSchema = new Store<string | undefined>(undefined)
448​
449 /**
450 * Get the sync metadata for insert operations
451 * @returns Record containing relation information
452 */
453 const getSyncMetadata = (): Record<string, unknown> => {
454 // Use the stored schema if available, otherwise default to 'public'
455 const schema = relationSchema.state || `public`
456​
457 return {
458 relation: shapeOptions.params?.table
459 ? [schema, shapeOptions.params.table]
460 : undefined,
461 }
462 }
463​
464 // Abort controller for the stream - wraps the signal if provided
465 const abortController = new AbortController()
466 if (shapeOptions.signal) {
467 shapeOptions.signal.addEventListener(`abort`, () => {
468 abortController.abort()
469 })
470 if (shapeOptions.signal.aborted) {
471 abortController.abort()
472 }
473 }
474​
475 let unsubscribeStream: () => void
476​
477 return {
478 sync: (params: Parameters<SyncConfig<T>[`sync`]>[0]) => {
479 const { begin, write, commit, markReady, truncate, collection } = params
480 const stream = new ShapeStream({
481 ...shapeOptions,
482 signal: abortController.signal,
483 onError: (errorParams) => {
484 // Just immediately mark ready if there's an error to avoid blocking
485 // apps waiting for `.preload()` to finish.
486 // Note that Electric sends a 409 error on a `must-refetch` message, but the
487 // ShapeStream handled this and it will not reach this handler, therefor
488 // this markReady will not be triggers by a `must-refetch`.
489 markReady()
490​
491 if (shapeOptions.onError) {
492 return shapeOptions.onError(errorParams)
493 } else {
494 console.error(
495 `An error occurred while syncing collection: ${collection.id}, \n` +
496 `it has been marked as ready to avoid blocking apps waiting for '.preload()' to finish. \n` +
497 `You can provide an 'onError' handler on the shapeOptions to handle this error, and this message will not be logged.`,
498 errorParams
499 )
500 }
501​
502 return
503 },
504 })
505 let transactionStarted = false
506 const newTxids = new Set<Txid>()
507​
508 unsubscribeStream = stream.subscribe((messages: Array<Message<T>>) => {
509 let hasUpToDate = false
510​
511 for (const message of messages) {
512 // Check for txids in the message and add them to our store
513 if (hasTxids(message)) {
514 message.headers.txids?.forEach((txid) => newTxids.add(txid))
515 }
516​
517 if (isChangeMessage(message)) {
518 // Check if the message contains schema information
519 const schema = message.headers.schema
520 if (schema && typeof schema === `string`) {
521 // Store the schema for future use if it's a valid string
522 relationSchema.setState(() => schema)
523 }
524​
525 if (!transactionStarted) {
526 begin()
527 transactionStarted = true
528 }
529​
530 write({
531 type: message.headers.operation,
532 value: message.value,
533 // Include the primary key and relation info in the metadata
534 metadata: {
535 ...message.headers,
536 },
537 })
538 } else if (isUpToDateMessage(message)) {
539 hasUpToDate = true
540 } else if (isMustRefetchMessage(message)) {
541 debug(
542 `Received must-refetch message, starting transaction with truncate`
543 )
544​
545 // Start a transaction and truncate the collection
546 if (!transactionStarted) {
547 begin()
548 transactionStarted = true
549 }
550​
551 truncate()
552​
553 // Reset hasUpToDate so we continue accumulating changes until next up-to-date
554 hasUpToDate = false
555 }
556 }
557​
558 if (hasUpToDate) {
559 // Commit transaction if one was started
560 if (transactionStarted) {
561 commit()
562 transactionStarted = false
563 }
564​
565 // Mark the collection as ready now that sync is up to date
566 markReady()
567​
568 // Always commit txids when we receive up-to-date, regardless of transaction state
569 seenTxids.setState((currentTxids) => {
570 const clonedSeen = new Set<Txid>(currentTxids)
571 if (newTxids.size > 0) {
572 debug(`new txids synced from pg %O`, Array.from(newTxids))
573 }
574 newTxids.forEach((txid) => clonedSeen.add(txid))
575 newTxids.clear()
576 return clonedSeen
577 })
578 }
579 })
580​
581 // Return the unsubscribe function
582 return () => {
583 // Unsubscribe from the stream
584 unsubscribeStream()
585 // Abort the abort controller to stop the stream
586 abortController.abort()
587 }
588 },
589 // Expose the getSyncMetadata function
590 getSyncMetadata,
591 }