Open History to see the last commit
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 BaseCollectionConfig,
17 CollectionConfig,
18 DeleteMutationFnParams,
19 Fn,
20 InsertMutationFnParams,
21 SyncConfig,
22 UpdateMutationFnParams,
23 UtilsRecord,
24} from "@tanstack/db"
25import type { StandardSchemaV1 } from "@standard-schema/spec"
26import type {
27 ControlMessage,
28 GetExtensions,
29 Message,
30 Row,
31 ShapeStreamOptions,
32} from "@electric-sql/client"
33
34const debug = DebugModule.debug(`ts/db:electric`)
35
36/**
37 * Type representing a transaction ID in ElectricSQL
38 */
39export type Txid = number
40
41// The `InferSchemaOutput` and `ResolveType` are copied from the `@tanstack/db` package
42// but we modified `InferSchemaOutput` slightly to restrict the schema output to `Row<unknown>`
43// This is needed in order for `GetExtensions` to be able to infer the parser extensions type from the schema
44type InferSchemaOutput<T> = T extends StandardSchemaV1
45 ? StandardSchemaV1.InferOutput<T> extends Row<unknown>
46 ? StandardSchemaV1.InferOutput<T>
47 : Record<string, unknown>
48 : Record<string, unknown>
49
50/**
51 * Configuration interface for Electric collection options
52 * @template T - The type of items in the collection
53 * @template TSchema - The schema type for validation
54 */
55export interface ElectricCollectionConfig<
56 T extends Row<unknown> = Row<unknown>,
57 TSchema extends StandardSchemaV1 = never,
58> extends BaseCollectionConfig<
59 T,
60 string | number,
61 TSchema,
62 Record<string, Fn>,
63 { txid: Txid | Array<Txid> }
64 > {
65 /**
66 * Configuration options for the ElectricSQL ShapeStream
67 */
68 shapeOptions: ShapeStreamOptions<GetExtensions<T>>
69}
70
71function isUpToDateMessage<T extends Row<unknown>>(
72 message: Message<T>
73): message is ControlMessage & { up_to_date: true } {
74 return isControlMessage(message) && message.headers.control === `up-to-date`
75}
76
77function isMustRefetchMessage<T extends Row<unknown>>(
78 message: Message<T>
79): message is ControlMessage & { headers: { control: `must-refetch` } } {
80 return isControlMessage(message) && message.headers.control === `must-refetch`
81}
82
83// Check if a message contains txids in its headers
84function hasTxids<T extends Row<unknown>>(
85 message: Message<T>
86): message is Message<T> & { headers: { txids?: Array<Txid> } } {
87 return `txids` in message.headers && Array.isArray(message.headers.txids)
88}
89
90/**
91 * Type for the awaitTxId utility function
92 */
93export type AwaitTxIdFn = (txId: Txid, timeout?: number) => Promise<boolean>
94
95/**
96 * Electric collection utilities type
97 */
98export interface ElectricCollectionUtils extends UtilsRecord {
99 awaitTxId: AwaitTxIdFn
100}
101
102/**
103 * Creates Electric collection options for use with a standard Collection
104 *
105 * @template T - The explicit type of items in the collection (highest priority)
106 * @template TSchema - The schema type for validation and type inference (second priority)
107 * @template TFallback - The fallback type if no explicit or schema type is provided
108 * @param config - Configuration options for the Electric collection
109 * @returns Collection options with utilities
110 */
111
112// Overload for when schema is provided
113export function electricCollectionOptions<T extends StandardSchemaV1>(
114 config: ElectricCollectionConfig<InferSchemaOutput<T>, T> & {
115 schema: T
116 }
117): CollectionConfig<InferSchemaOutput<T>, string | number, T> & {
118 id?: string
119 utils: ElectricCollectionUtils
120 schema: T
121}
122
123// Overload for when no schema is provided
124export function electricCollectionOptions<T extends Row<unknown>>(
125 config: ElectricCollectionConfig<T> & {
126 schema?: never // prohibit schema
127 }
128): CollectionConfig<T, string | number> & {
129 id?: string
130 utils: ElectricCollectionUtils
131 schema?: never // no schema in the result
132}
133
134export function electricCollectionOptions(
135 config: ElectricCollectionConfig<any, any>
136): CollectionConfig<any, string | number, any> & {
137 id?: string
138 utils: ElectricCollectionUtils
139 schema?: any
140} {
141 const seenTxids = new Store<Set<Txid>>(new Set([]))
142 const sync = createElectricSync<any>(config.shapeOptions, {
143 seenTxids,
144 })
145
146 /**
147 * Wait for a specific transaction ID to be synced
148 * @param txId The transaction ID to wait for as a number
149 * @param timeout Optional timeout in milliseconds (defaults to 30000ms)
150 * @returns Promise that resolves when the txId is synced
151 */
152 const awaitTxId: AwaitTxIdFn = async (
153 txId: Txid,
154 timeout: number = 30000
155 ): Promise<boolean> => {
156 debug(`awaitTxId called with txid %d`, txId)
157 if (typeof txId !== `number`) {
158 throw new ExpectedNumberInAwaitTxIdError(typeof txId)
159 }
160
161 const hasTxid = seenTxids.state.has(txId)
162 if (hasTxid) return true
163
164 return new Promise((resolve, reject) => {
165 const timeoutId = setTimeout(() => {
166 unsubscribe()
167 reject(new TimeoutWaitingForTxIdError(txId))
168 }, timeout)
169
170 const unsubscribe = seenTxids.subscribe(() => {
171 if (seenTxids.state.has(txId)) {
172 debug(`awaitTxId found match for txid %o`, txId)
173 clearTimeout(timeoutId)
174 unsubscribe()
175 resolve(true)
176 }
177 })
178 })
179 }
180
181 // Create wrapper handlers for direct persistence operations that handle txid awaiting
182 const wrappedOnInsert = config.onInsert
183 ? async (params: InsertMutationFnParams<any>) => {
184 // Runtime check (that doesn't follow type)
185
186 const handlerResult = (await config.onInsert!(params)) ?? {}
187 const txid = (handlerResult as { txid?: Txid | Array<Txid> }).txid
188
189 if (!txid) {
190 throw new ElectricInsertHandlerMustReturnTxIdError()
191 }
192
193 // Handle both single txid and array of txids
194 if (Array.isArray(txid)) {
195 await Promise.all(txid.map((id) => awaitTxId(id)))
196 } else {
197 await awaitTxId(txid)
198 }
199
200 return handlerResult
201 }
202 : undefined
203
204 const wrappedOnUpdate = config.onUpdate
205 ? async (params: UpdateMutationFnParams<any>) => {
206 // Runtime check (that doesn't follow type)
207
208 const handlerResult = (await config.onUpdate!(params)) ?? {}
209 const txid = (handlerResult as { txid?: Txid | Array<Txid> }).txid
210
211 if (!txid) {
212 throw new ElectricUpdateHandlerMustReturnTxIdError()
213 }
214
215 // Handle both single txid and array of txids
216 if (Array.isArray(txid)) {
217 await Promise.all(txid.map((id) => awaitTxId(id)))
218 } else {
219 await awaitTxId(txid)
220 }
221
222 return handlerResult
223 }
224 : undefined
225
226 const wrappedOnDelete = config.onDelete
227 ? async (params: DeleteMutationFnParams<any>) => {
228 const handlerResult = await config.onDelete!(params)
229 if (!handlerResult.txid) {
230 throw new ElectricDeleteHandlerMustReturnTxIdError()
231 }
232
233 // Handle both single txid and array of txids
234 if (Array.isArray(handlerResult.txid)) {
235 await Promise.all(handlerResult.txid.map((id) => awaitTxId(id)))
236 } else {
237 await awaitTxId(handlerResult.txid)
238 }
239
240 return handlerResult
241 }
242 : undefined
243
244 // Extract standard Collection config properties
245 const {
246 shapeOptions: _shapeOptions,
247 onInsert: _onInsert,
248 onUpdate: _onUpdate,
249 onDelete: _onDelete,
250 ...restConfig
251 } = config
252
253 return {
254 ...restConfig,
255 sync,
256 onInsert: wrappedOnInsert,
257 onUpdate: wrappedOnUpdate,
258 onDelete: wrappedOnDelete,
259 utils: {
260 awaitTxId,
261 },
262 }
263}
264
265/**
266 * Internal function to create ElectricSQL sync configuration
267 */
268function createElectricSync<T extends Row<unknown>>(
269 shapeOptions: ShapeStreamOptions<GetExtensions<T>>,
270 options: {
271 seenTxids: Store<Set<Txid>>
272 }
273): SyncConfig<T> {
274 const { seenTxids } = options
275
276 // Store for the relation schema information
277 const relationSchema = new Store<string | undefined>(undefined)
278
279 /**
280 * Get the sync metadata for insert operations
281 * @returns Record containing relation information
282 */
283 const getSyncMetadata = (): Record<string, unknown> => {
284 // Use the stored schema if available, otherwise default to 'public'
285 const schema = relationSchema.state || `public`
286
287 return {
288 relation: shapeOptions.params?.table
289 ? [schema, shapeOptions.params.table]
290 : undefined,
291 }
292 }
293
294 let unsubscribeStream: () => void
295
296 return {
297 sync: (params: Parameters<SyncConfig<T>[`sync`]>[0]) => {
298 const { begin, write, commit, markReady, truncate, collection } = params
299
300 // Abort controller for the stream - wraps the signal if provided
301 const abortController = new AbortController()
302
303 if (shapeOptions.signal) {
304 shapeOptions.signal.addEventListener(
305 `abort`,
306 () => {
307 abortController.abort()
308 },
309 {
310 once: true,
311 }
312 )
313 if (shapeOptions.signal.aborted) {
314 abortController.abort()
315 }
316 }
317
318 const stream = new ShapeStream({
319 ...shapeOptions,
320 signal: abortController.signal,
321 onError: (errorParams) => {
322 // Just immediately mark ready if there's an error to avoid blocking
323 // apps waiting for `.preload()` to finish.
324 // Note that Electric sends a 409 error on a `must-refetch` message, but the
325 // ShapeStream handled this and it will not reach this handler, therefor
326 // this markReady will not be triggers by a `must-refetch`.
327 markReady()
328
329 if (shapeOptions.onError) {
330 return shapeOptions.onError(errorParams)
331 } else {
332 console.error(
333 `An error occurred while syncing collection: ${collection.id}, \n` +
334 `it has been marked as ready to avoid blocking apps waiting for '.preload()' to finish. \n` +
335 `You can provide an 'onError' handler on the shapeOptions to handle this error, and this message will not be logged.`,
336 errorParams
337 )
338 }
339
340 return
341 },
342 })
343 let transactionStarted = false
344 const newTxids = new Set<Txid>()
345
346 unsubscribeStream = stream.subscribe((messages: Array<Message<T>>) => {
347 let hasUpToDate = false
348
349 for (const message of messages) {
350 // Check for txids in the message and add them to our store
351 if (hasTxids(message)) {
352 message.headers.txids?.forEach((txid) => newTxids.add(txid))
353 }
354
355 if (isChangeMessage(message)) {
356 // Check if the message contains schema information
357 const schema = message.headers.schema
358 if (schema && typeof schema === `string`) {
359 // Store the schema for future use if it's a valid string
360 relationSchema.setState(() => schema)
361 }
362
363 if (!transactionStarted) {
364 begin()
365 transactionStarted = true
366 }
367
368 write({
369 type: message.headers.operation,
370 value: message.value,
371 // Include the primary key and relation info in the metadata
372 metadata: {
373 ...message.headers,
374 },
375 })
376 } else if (isUpToDateMessage(message)) {
377 hasUpToDate = true
378 } else if (isMustRefetchMessage(message)) {
379 debug(
380 `Received must-refetch message, starting transaction with truncate`
381 )
382
383 // Start a transaction and truncate the collection
384 if (!transactionStarted) {
385 begin()
386 transactionStarted = true
387 }
388
389 truncate()
390
391 // Reset hasUpToDate so we continue accumulating changes until next up-to-date
392 hasUpToDate = false
393 }
394 }
395
396 if (hasUpToDate) {
397 // Commit transaction if one was started
398 if (transactionStarted) {
399 commit()
400 transactionStarted = false
401 }
402
403 // Mark the collection as ready now that sync is up to date
404 markReady()
405
406 // Always commit txids when we receive up-to-date, regardless of transaction state
407 seenTxids.setState((currentTxids) => {
408 const clonedSeen = new Set<Txid>(currentTxids)
409 if (newTxids.size > 0) {
410 debug(`new txids synced from pg %O`, Array.from(newTxids))
411 }
412 newTxids.forEach((txid) => clonedSeen.add(txid))
413 newTxids.clear()
414 return clonedSeen
415 })
416 }
417 })
418
419 // Return the unsubscribe function
420 return () => {
421 // Unsubscribe from the stream
422 unsubscribeStream()
423 // Abort the abort controller to stop the stream
424 abortController.abort()
425 }
426 },
427 // Expose the getSyncMetadata function
428 getSyncMetadata,
429 }
430}