Open History to see the last commit
1import { DiffTriggerOperation, LogLevels, sanitizeSQL } from '@powersync/common'
2import { or, withCollectionConfigFactory } from '@tanstack/db'
3import { compileSQLite } from './sqlite-compiler'
4import { PendingOperationStore } from './PendingOperationStore'
5import { PowerSyncTransactor } from './PowerSyncTransactor'
6import { DEFAULT_BATCH_SIZE } from './definitions'
7import { asPowerSyncRecord, mapOperation } from './helpers'
8import { convertTableToSchema } from './schema'
9import { serializeForSQLite } from './serialization'
10import type {
11 CleanupFn,
12 LoadSubsetOptions,
13 OperationType,
14 SyncAppliedReceipt,
15 SyncConfig,
16} from '@tanstack/db'
17import type {
18 AnyTableColumnType,
19 ExtractedTable,
20 OptionalExtractedTable,
21} from './helpers'
22import type {
23 BasePowerSyncCollectionConfig,
24 ConfigWithArbitraryCollectionTypes,
25 ConfigWithSQLiteInputType,
26 ConfigWithSQLiteTypes,
27 EnhancedPowerSyncCollectionConfig,
28 InferPowerSyncOutputType,
29 PowerSyncCollectionConfig,
30 PowerSyncCollectionUtils,
31} from './definitions'
32import type { PendingOperation } from './PendingOperationStore'
33import type { StandardSchemaV1 } from '@standard-schema/spec'
34import type { LockContext, Table, TriggerDiffRecord } from '@powersync/common'
35
36function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
37 return (
38 !!value &&
39 (typeof value === `object` || typeof value === `function`) &&
40 typeof (value as { then?: unknown }).then === `function`
41 )
42}
43
44/**
45 * Creates PowerSync collection options for use with a standard Collection.
46 *
47 * @template TTable - The SQLite-based typing
48 * @template TSchema - The validation schema type (optionally supports a custom input type)
49 * @param config - Configuration options for the PowerSync collection
50 * @returns Collection options with utilities
51 */
52
53// Overload 1: No schema is provided
54
55/**
56 * Creates a PowerSync collection configuration with basic default validation.
57 * Input and Output types are the SQLite column types.
58 *
59 * @example
60 * ```typescript
61 * const APP_SCHEMA = new Schema({
62 * documents: new Table({
63 * name: column.text,
64 * }),
65 * })
66 *
67 * type Document = (typeof APP_SCHEMA)["types"]["documents"]
68 *
69 * const db = new PowerSyncDatabase({
70 * database: {
71 * dbFilename: "test.sqlite",
72 * },
73 * schema: APP_SCHEMA,
74 * })
75 *
76 * const collection = createCollection(
77 * powerSyncCollectionOptions({
78 * database: db,
79 * table: APP_SCHEMA.props.documents
80 * })
81 * )
82 * ```
83 */
84export function powerSyncCollectionOptions<TTable extends Table = Table>(
85 config: BasePowerSyncCollectionConfig<TTable, never> & ConfigWithSQLiteTypes,
86): EnhancedPowerSyncCollectionConfig<
87 TTable,
88 OptionalExtractedTable<TTable>,
89 never
90>
91
92// Overload 2: Schema is provided and the TInput matches SQLite types.
93
94/**
95 * Creates a PowerSync collection configuration with schema validation.
96 *
97 * The input types satisfy the SQLite column types.
98 *
99 * The output types are defined by the provided schema. This schema can enforce additional
100 * validation or type transforms.
101 * Arbitrary output typed mutations are encoded to SQLite for persistence. We provide a basic standard
102 * serialization implementation to serialize column values. Custom or advanced types require providing additional
103 * serializer specifications. Partial column overrides can be supplied to `serializer`.
104 *
105 * @example
106 * ```typescript
107 * import { z } from "zod"
108 *
109 * // The PowerSync SQLite schema
110 * const APP_SCHEMA = new Schema({
111 * documents: new Table({
112 * name: column.text,
113 * // Dates are stored as ISO date strings in SQLite
114 * created_at: column.text
115 * }),
116 * })
117 *
118 * // Advanced Zod validations. The output type of this schema
119 * // is constrained to the SQLite schema of APP_SCHEMA
120 * const schema = z.object({
121 * id: z.string(),
122 * // Notice that `name` is not nullable (is required) here and it has additional validation
123 * name: z.string().min(3, { message: "Should be at least 3 characters" }).nullable(),
124 * // The input type is still the SQLite string type. While collections will output smart Date instances.
125 * created_at: z.string().transform(val => new Date(val))
126 * })
127 *
128 * const collection = createCollection(
129 * powerSyncCollectionOptions({
130 * database: db,
131 * table: APP_SCHEMA.props.documents,
132 * schema,
133 * serializer: {
134 * // The default is toISOString, this is just to demonstrate custom overrides
135 * created_at: (outputValue) => outputValue.toISOString(),
136 * },
137 * })
138 * )
139 * ```
140 */
141export function powerSyncCollectionOptions<
142 TTable extends Table,
143 TSchema extends StandardSchemaV1<
144 // TInput is the SQLite types. We can use the supplied schema to validate sync input
145 OptionalExtractedTable<TTable>,
146 AnyTableColumnType<TTable>
147 >,
148>(
149 config: BasePowerSyncCollectionConfig<TTable, TSchema> &
150 ConfigWithSQLiteInputType<TTable, TSchema>,
151): EnhancedPowerSyncCollectionConfig<
152 TTable,
153 InferPowerSyncOutputType<TTable, TSchema>,
154 TSchema
155> & {
156 schema: TSchema
157}
158
159// Overload 3: Schema is provided with arbitrary TInput and TOutput
160/**
161 * Creates a PowerSync collection configuration with schema validation.
162 *
163 * The input types are not linked to the internal SQLite table types. This can
164 * give greater flexibility, e.g. by accepting rich types as input for `insert` or `update` operations.
165 * An additional `deserializationSchema` is required in order to process incoming SQLite updates to the output type.
166 *
167 * The output types are defined by the provided schema. This schema can enforce additional
168 * validation or type transforms.
169 * Arbitrary output typed mutations are encoded to SQLite for persistence. We provide a basic standard
170 * serialization implementation to serialize column values. Custom or advanced types require providing additional
171 * serializer specifications. Partial column overrides can be supplied to `serializer`.
172 *
173 * @example
174 * ```typescript
175 * import { z } from "zod"
176 *
177 * // The PowerSync SQLite schema
178 * const APP_SCHEMA = new Schema({
179 * documents: new Table({
180 * name: column.text,
181 * // Booleans are represented as integers in SQLite
182 * is_active: column.integer
183 * }),
184 * })
185 *
186 * // Advanced Zod validations.
187 * // We accept boolean values as input for operations and expose Booleans in query results
188 * const schema = z.object({
189 * id: z.string(),
190 * isActive: z.boolean(), // TInput and TOutput are boolean
191 * })
192 *
193 * // The deserializationSchema converts the SQLite synced INTEGER (0/1) values to booleans.
194 * const deserializationSchema = z.object({
195 * id: z.string(),
196 * isActive: z.number().nullable().transform((val) => val == null ? true : val > 0),
197 * })
198 *
199 * const collection = createCollection(
200 * powerSyncCollectionOptions({
201 * database: db,
202 * table: APP_SCHEMA.props.documents,
203 * schema,
204 * deserializationSchema,
205 * })
206 * )
207 * ```
208 */
209export function powerSyncCollectionOptions<
210 TTable extends Table,
211 TSchema extends StandardSchemaV1<
212 // The input and output must have the same keys, the value types can be arbitrary
213 AnyTableColumnType<TTable>,
214 AnyTableColumnType<TTable>
215 >,
216>(
217 config: BasePowerSyncCollectionConfig<TTable, TSchema> &
218 ConfigWithArbitraryCollectionTypes<TTable, TSchema>,
219): EnhancedPowerSyncCollectionConfig<
220 TTable,
221 InferPowerSyncOutputType<TTable, TSchema>,
222 TSchema
223> & {
224 utils: PowerSyncCollectionUtils<TTable>
225 schema: TSchema
226}
227
228/**
229 * Implementation of powerSyncCollectionOptions that handles both schema and non-schema configurations.
230 */
231
232export function powerSyncCollectionOptions<
233 TTable extends Table,
234 TSchema extends StandardSchemaV1<any> = never,
235>(
236 config: PowerSyncCollectionConfig<TTable, TSchema>,
237): ReturnType<typeof createPowerSyncCollectionConfig<TTable, TSchema>> {
238 const outputConfig = createPowerSyncCollectionConfig(config)
239 return withCollectionConfigFactory(outputConfig, () =>
240 createPowerSyncCollectionConfig(config),
241 )
242}
243
244function createPowerSyncCollectionConfig<
245 TTable extends Table,
246 TSchema extends StandardSchemaV1<any> = never,
247>(config: PowerSyncCollectionConfig<TTable, TSchema>) {
248 const {
249 database,
250 table,
251 schema: inputSchema,
252 syncBatchSize = DEFAULT_BATCH_SIZE,
253 syncMode = 'eager',
254 ...restConfig
255 } = config
256
257 const deserializationSchema =
258 `deserializationSchema` in config ? config.deserializationSchema : null
259 const serializer = `serializer` in config ? config.serializer : undefined
260 const onDeserializationError =
261 `onDeserializationError` in config
262 ? config.onDeserializationError
263 : undefined
264
265 // The SQLite table type
266 type TableType = ExtractedTable<TTable>
267
268 // The collection output type
269 type OutputType = InferPowerSyncOutputType<TTable, TSchema>
270
271 const { viewName, trackMetadata: metadataIsTracked } = table
272
273 /**
274 * Deserializes data from the incoming sync stream
275 */
276 const deserializeSyncRow = (value: TableType): OutputType => {
277 const validationSchema = deserializationSchema || schema
278 const validation = validationSchema[`~standard`].validate(value)
279 if (`value` in validation) {
280 return validation.value
281 } else if (`issues` in validation) {
282 const issueMessage = `Failed to validate incoming data for ${viewName}. Issues: ${validation.issues.map((issue) => `${issue.path} - ${issue.message}`)}`
283 database.logger.log({ level: LogLevels.error, message: issueMessage })
284 onDeserializationError!(validation)
285 throw new Error(issueMessage)
286 } else {
287 const unknownErrorMessage = `Unknown deserialization error for ${viewName}`
288 database.logger.log({
289 level: LogLevels.error,
290 message: unknownErrorMessage,
291 })
292 onDeserializationError!({ issues: [{ message: unknownErrorMessage }] })
293 throw new Error(unknownErrorMessage)
294 }
295 }
296
297 // We can do basic runtime validations for columns if not explicit schema has been provided
298 const schema = inputSchema ?? (convertTableToSchema(table) as TSchema)
299 /**
300 * The onInsert, onUpdate, and onDelete handlers should only return
301 * after we have written the changes to TanStack DB.
302 * We currently only write to TanStack DB from a diff trigger.
303 * We wait for the diff trigger to observe the change,
304 * and only then return from the on[X] handlers.
305 * This ensures that when the transaction is reported as
306 * complete to the caller, the in-memory state is already
307 * consistent with the database.
308 */
309 const pendingOperationStore = PendingOperationStore.GLOBAL
310 // Keep the tracked table unique in case of multiple tabs.
311 const trackedTableName = `__${viewName}_tracking_${Math.floor(
312 Math.random() * 0xffffffff,
313 )
314 .toString(16)
315 .padStart(8, `0`)}`
316
317 const transactor = new PowerSyncTransactor({
318 database,
319 })
320
321 /**
322 * "sync"
323 * Notice that this describes the Sync between the local SQLite table
324 * and the in-memory tanstack-db collection.
325 */
326 const sync: SyncConfig<OutputType, string> = {
327 sync: (params) => {
328 const { begin, write, collection, commit, markReady, markError } = params
329 const abortController = new AbortController()
330
331 let disposeTracking:
332 | ((options?: { context?: LockContext }) => Promise<void>)
333 | null = null
334 let trackingSetup: Promise<void> | null = null
335 let activeTrackingDisposal: Promise<void> | null = null
336 let abortTrackingDisposal: Promise<void> | null = null
337
338 if (syncMode === `eager`) {
339 return runEagerSync()
340 } else {
341 return runOnDemandSync()
342 }
343
344 /**
345 * Disposes the current diff trigger, if one is active, and clears the
346 * tracking state.
347 */
348 async function safelyDisposeTracking(
349 context?: LockContext,
350 ): Promise<void> {
351 // Cleanup can race trigger creation. Wait until the disposer has been
352 // published so an abort cannot strand a freshly-created trigger.
353 const setup = trackingSetup
354 if (setup) {
355 await setup.catch(() => undefined)
356 }
357
358 const dispose = disposeTracking
359 if (!dispose) {
360 // Reconciliation may have claimed the disposer after this caller
361 // observed setup. Join that invocation instead of settling early.
362 await activeTrackingDisposal
363 return
364 }
365
366 disposeTracking = null
367 let disposal: Promise<void>
368 try {
369 disposal = Promise.resolve(dispose(context ? { context } : undefined))
370 } catch (error) {
371 disposal = Promise.reject(error)
372 }
373 activeTrackingDisposal = disposal
374 try {
375 await disposal
376 } finally {
377 if (activeTrackingDisposal === disposal) {
378 activeTrackingDisposal = null
379 }
380 }
381 }
382
383 function disposeTrackingAfterAbort(): Promise<void> {
384 const disposal = (abortTrackingDisposal ??= safelyDisposeTracking())
385 // Abort event dispatch does not observe a listener's returned promise.
386 // The eager cleanup callback awaits this same promise below.
387 void disposal.catch(() => undefined)
388 return disposal
389 }
390
391 async function establishTracking(
392 options: Parameters<typeof createDiffTrigger>[0],
393 appliedReceipts: Array<SyncAppliedReceipt>,
394 ): Promise<void> {
395 const setup = (async () => {
396 const dispose = await createDiffTrigger(options, appliedReceipts)
397 disposeTracking = dispose
398 })()
399 trackingSetup = setup
400
401 try {
402 await setup
403 } finally {
404 if (trackingSetup === setup) {
405 trackingSetup = null
406 }
407 }
408 }
409
410 async function createDiffTrigger(
411 options: {
412 setupContext?: LockContext
413 immediate?: boolean
414 when: Record<DiffTriggerOperation, string>
415 writeType: (rowId: string) => OperationType
416 batchQuery: (
417 lockContext: LockContext,
418 batchSize: number,
419 cursor: number,
420 ) => Promise<Array<TableType>>
421 },
422 appliedReceipts: Array<SyncAppliedReceipt>,
423 ) {
424 const { setupContext, immediate, when, writeType, batchQuery } = options
425
426 return await database.triggers.createDiffTrigger({
427 source: viewName,
428 destination: trackedTableName,
429 columns: table.columns.map((column) => column.name),
430 setupContext,
431 when,
432 hooks: {
433 beforeCreate: async (context) => {
434 let currentBatchCount = syncBatchSize
435 let cursor = 0
436 while (currentBatchCount == syncBatchSize) {
437 begin(immediate ? { immediate: true } : undefined)
438
439 const batchItems = await batchQuery(
440 context,
441 syncBatchSize,
442 cursor,
443 )
444 currentBatchCount = batchItems.length
445 cursor += currentBatchCount
446 for (const row of batchItems) {
447 write({
448 type: writeType(row.id),
449 value: deserializeSyncRow(row),
450 })
451 }
452 appliedReceipts.push(commit())
453 }
454 database.logger.log({
455 level: LogLevels.info,
456 message: `Sync is ready for ${viewName} into ${trackedTableName}`,
457 })
458 },
459 },
460 })
461 }
462
463 async function flushDiffRecords(): Promise<void> {
464 // PowerSync can notify after creating the tracking table but before its
465 // create call returns. Preserve that notification until the disposer,
466 // which proves the trigger is usable, has been published.
467 const setup = trackingSetup
468 if (setup) {
469 await setup.catch(() => undefined)
470 }
471 if (!disposeTracking) {
472 return
473 }
474
475 const ignoredReceipts: Array<SyncAppliedReceipt> = []
476 await database
477 .writeTransaction(async (context) => {
478 await flushDiffRecordsWithContext(context, ignoredReceipts)
479 })
480 .catch((error) => {
481 database.logger.log({
482 level: LogLevels.error,
483 message: `An error has been detected in the sync handler`,
484 error,
485 })
486 })
487 }
488
489 // We can use this directly if we want to pair a flush with dispose+recreate diff trigger.
490 async function flushDiffRecordsWithContext(
491 context: LockContext,
492 appliedReceipts: Array<SyncAppliedReceipt>,
493 ): Promise<void> {
494 // There is nothing to flush if no tracking table is currently active.
495 if (!disposeTracking) {
496 return
497 }
498
499 try {
500 begin()
501 const operations = await context.getAll<TriggerDiffRecord>(
502 `SELECT * FROM ${trackedTableName} ORDER BY operation_id ASC`,
503 )
504 const pendingOperations: Array<PendingOperation> = []
505
506 for (const op of operations) {
507 const { id, operation, timestamp, value } = op
508 const parsedValue = deserializeSyncRow({
509 id,
510 ...JSON.parse(value),
511 })
512 const parsedPreviousValue =
513 op.operation == DiffTriggerOperation.UPDATE
514 ? deserializeSyncRow({
515 id,
516 ...JSON.parse(op.previous_value),
517 })
518 : undefined
519 write({
520 type: mapOperation(operation),
521 value: parsedValue,
522 previousValue: parsedPreviousValue,
523 })
524 pendingOperations.push({
525 id,
526 operation,
527 timestamp,
528 tableName: viewName,
529 })
530 }
531
532 // clear the current operations
533 await context.execute(`DELETE FROM ${trackedTableName}`)
534
535 const applied = commit()
536 appliedReceipts.push(applied)
537 // Mutation persistence is what releases the Collection's FIFO gate.
538 // Confirm these local operations after the sync transaction is
539 // staged; waiting for its applied receipt would deadlock the user
540 // transaction that currently parks it.
541 pendingOperationStore.resolvePendingFor(pendingOperations)
542 } catch (error) {
543 database.logger.log({
544 level: LogLevels.error,
545 message: `An error has been detected in the sync handler`,
546 error,
547 })
548 }
549 }
550
551 // The sync function needs to be synchronous.
552 async function start(afterOnChangeRegistered?: () => Promise<void>) {
553 database.logger.log({
554 level: LogLevels.info,
555 message: `Sync is starting for ${viewName} into ${trackedTableName}`,
556 })
557 database.onChangeWithCallback(
558 {
559 onChange: async () => {
560 await flushDiffRecords()
561 },
562 },
563 {
564 signal: abortController.signal,
565 triggerImmediate: false,
566 tables: [trackedTableName],
567 },
568 )
569
570 await afterOnChangeRegistered?.()
571
572 // If the abort controller was aborted while processing the request above
573 if (abortController.signal.aborted) {
574 await disposeTrackingAfterAbort()
575 } else {
576 abortController.signal.addEventListener(
577 `abort`,
578 () => {
579 void disposeTrackingAfterAbort()
580 },
581 { once: true },
582 )
583 }
584 }
585
586 // Eager mode.
587 // Registers a diff trigger for the entire table.
588 function runEagerSync() {
589 let onUnload: CleanupFn | void | null = null
590 let onUnloadStarted = false
591
592 const startup = start(async () => {
593 const cleanup = await restConfig.onLoad?.()
594 onUnload = cleanup
595 if (abortController.signal.aborted) {
596 return
597 }
598
599 const appliedReceipts: Array<SyncAppliedReceipt> = []
600 await establishTracking(
601 {
602 // Initial eager hydration must make the source usable before
603 // PowerSync can persist a mutation queued during startup.
604 immediate: true,
605 when: {
606 [DiffTriggerOperation.INSERT]: `TRUE`,
607 [DiffTriggerOperation.UPDATE]: `TRUE`,
608 [DiffTriggerOperation.DELETE]: `TRUE`,
609 },
610 writeType: (_rowId: string) => `insert`,
611 batchQuery: (
612 lockContext: LockContext,
613 batchSize: number,
614 cursor: number,
615 ) =>
616 lockContext.getAll<TableType>(
617 sanitizeSQL`SELECT * FROM ${viewName} LIMIT ? OFFSET ?`,
618 [batchSize, cursor],
619 ),
620 },
621 appliedReceipts,
622 )
623 await Promise.all(appliedReceipts)
624 markReady()
625 }).catch((error) => {
626 database.logger.log({
627 level: LogLevels.error,
628 message: `Could not start syncing process for ${viewName} into ${trackedTableName}`,
629 error,
630 })
631 if (collection.status === `loading`) {
632 markError(error)
633 }
634 })
635
636 const invokeOnUnload = (): void | Promise<void> => {
637 if (onUnloadStarted || !onUnload) return
638 onUnloadStarted = true
639 const cleanup = onUnload
640 onUnload = null
641 return cleanup()
642 }
643
644 return async () => {
645 database.logger.log({
646 level: LogLevels.info,
647 message: `Sync has been stopped for ${viewName} into ${trackedTableName}`,
648 })
649 abortController.abort()
650 const trackingDisposal = disposeTrackingAfterAbort()
651
652 let firstFailure: { error: unknown } | undefined
653 const settleOnUnload = async () => {
654 try {
655 await invokeOnUnload()
656 } catch (error) {
657 firstFailure ??= { error }
658 }
659 }
660
661 // Invoke an already-installed callback in this stack, but also wait
662 // for startup to publish a callback acquired concurrently with abort.
663 const settlements = await Promise.allSettled([
664 startup,
665 trackingDisposal,
666 settleOnUnload(),
667 ])
668 const disposalSettlement = settlements[1]
669 if (disposalSettlement.status === `rejected`) {
670 firstFailure ??= { error: disposalSettlement.reason }
671 }
672 await settleOnUnload()
673 if (firstFailure) throw firstFailure.error
674 }
675 }
676
677 // On-demand mode.
678 // Registers a diff trigger for the active WHERE expressions.
679 function runOnDemandSync() {
680 type DemandRecord = {
681 options: LoadSubsetOptions
682 active: boolean
683 cleanup?: CleanupFn
684 }
685 type PendingRelease = {
686 options: LoadSubsetOptions
687 failures: number
688 }
689 type DemandCleanupCollector = {
690 tasks: Array<Promise<unknown>>
691 ownedTasks: Set<Promise<unknown>>
692 failure?: { error: unknown }
693 }
694
695 const demands = new Map<LoadSubsetOptions, DemandRecord>()
696 const releasedSubsets = new WeakSet<LoadSubsetOptions>()
697 const pendingReleases: Array<PendingRelease> = []
698 const pendingDemandLoads = new Set<Promise<void>>()
699 const pendingDemandCleanups = new Set<Promise<unknown>>()
700 let stopped = false
701 let trackingRevision = 0
702 let reconciledTrackingRevision = 0
703 let rebuildPromise: Promise<void> | null = null
704 let drainingReleases = false
705 let releaseRetryTimer: ReturnType<typeof setTimeout> | undefined
706 let demandCleanupCollector: DemandCleanupCollector | null = null
707 const startup = start()
708 void startup.catch((error) =>
709 database.logger.log({
710 level: LogLevels.error,
711 message: `Could not start syncing process for ${viewName} into ${trackedTableName}`,
712 error,
713 }),
714 )
715
716 const activeWhereExpressions = () =>
717 Array.from(demands.values())
718 .filter((demand) => demand.active)
719 .map((demand) => demand.options.where)
720
721 // One reconciliation owns every queued revision so callers cannot
722 // settle against a stale trigger configuration.
723 const reconcileTracking = async (): Promise<void> => {
724 while (!stopped && reconciledTrackingRevision !== trackingRevision) {
725 const revision = trackingRevision
726 const isCurrent = () => !stopped && trackingRevision === revision
727 const appliedReceipts: Array<SyncAppliedReceipt> = []
728
729 await database.writeLock(async (ctx) => {
730 if (!isCurrent()) return
731 await flushDiffRecordsWithContext(ctx, appliedReceipts)
732 if (!isCurrent()) return
733 await safelyDisposeTracking(ctx)
734 if (!isCurrent()) return
735
736 const active = activeWhereExpressions()
737 // Tracking was absent during an error. Positive baseline rows
738 // alone cannot reveal deletes or predicate exits from that gap.
739 const missing =
740 collection.status === `error`
741 ? new Set(collection.keys())
742 : undefined
743 if (active.length > 0) {
744 const combinedWhere =
745 active.length === 1
746 ? active[0]
747 : or(active[0], active[1], ...active.slice(2))
748 const compiledNewData = compileSQLite(
749 { where: combinedWhere },
750 { jsonColumn: 'NEW.data' },
751 )
752 const compiledOldData = compileSQLite(
753 { where: combinedWhere },
754 { jsonColumn: 'OLD.data' },
755 )
756 const compiledView = compileSQLite({ where: combinedWhere })
757 const newDataWhenClause = toInlinedWhereClause(compiledNewData)
758 const oldDataWhenClause = toInlinedWhereClause(compiledOldData)
759 const viewWhereClause = toInlinedWhereClause(compiledView)
760 await establishTracking(
761 {
762 setupContext: ctx,
763 when: {
764 [DiffTriggerOperation.INSERT]: newDataWhenClause,
765 [DiffTriggerOperation.UPDATE]: `(${newDataWhenClause}) OR (${oldDataWhenClause})`,
766 [DiffTriggerOperation.DELETE]: oldDataWhenClause,
767 },
768 writeType: (rowId: string) =>
769 collection.has(rowId) ? `update` : `insert`,
770 batchQuery: (
771 lockContext: LockContext,
772 batchSize: number,
773 cursor: number,
774 ) =>
775 lockContext
776 .getAll<TableType>(
777 `SELECT * FROM ${viewName} WHERE ${viewWhereClause} LIMIT ? OFFSET ?`,
778 [batchSize, cursor],
779 )
780 .then((rows) => {
781 for (const row of rows) missing?.delete(row.id)
782 return rows
783 }),
784 },
785 appliedReceipts,
786 )
787 }
788 if (!isCurrent()) await safelyDisposeTracking(ctx)
789 else if (missing?.size) {
790 begin()
791 for (const key of missing) write({ type: `delete`, key })
792 appliedReceipts.push(commit())
793 }
794 })
795 await Promise.all(appliedReceipts)
796 if (isCurrent()) {
797 reconciledTrackingRevision = revision
798 // Replacing the trigger alone is not recovery: its baseline
799 // writes must also be applied before the source is ready again.
800 if (collection.status === `error`) markReady()
801 }
802 }
803 }
804
805 const rebuildTracking = async (): Promise<void> => {
806 // New demand can join after reconciliation exits but before its
807 // shared promise clears. Each waiter must check its revision again.
808 while (!stopped && reconciledTrackingRevision !== trackingRevision) {
809 await (rebuildPromise ??= reconcileTracking()
810 .catch((error) => {
811 // A rebuild may already have removed every active diff trigger.
812 // Do not leave healthy consumers ready against a stale source.
813 if (!stopped) markError(error)
814 throw error
815 })
816 .finally(() => {
817 rebuildPromise = null
818 }))
819 }
820 }
821
822 const loadSubset = async (
823 options: LoadSubsetOptions,
824 ): Promise<void> => {
825 if (stopped) return
826 // Never create a trigger that has no observer to drain its diff table.
827 await startup
828 if (
829 // Cleanup can run while startup is pending.
830 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
831 stopped ||
832 releasedSubsets.has(options) ||
833 options.signal?.aborted
834 ) {
835 return
836 }
837
838 const demand: DemandRecord = { options, active: false }
839 demands.set(options, demand)
840 try {
841 const cleanup = await restConfig.onLoadSubset?.(options)
842 if (cleanup) demand.cleanup = cleanup
843 } catch (error) {
844 demands.delete(options)
845 if (demandCleanupCollector) {
846 demandCleanupCollector.failure ??= { error }
847 }
848 throw error
849 }
850
851 if (
852 // The user hook can reenter cleanup.
853 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
854 stopped ||
855 releasedSubsets.has(options) ||
856 options.signal?.aborted ||
857 demands.get(options) !== demand
858 ) {
859 cleanupDemand(demand)
860 return
861 }
862
863 demand.active = true
864 trackingRevision++
865 await rebuildTracking()
866 }
867
868 const trackLoadSubset = (options: LoadSubsetOptions): Promise<void> => {
869 const task = loadSubset(options)
870 pendingDemandLoads.add(task)
871 const finish = () => pendingDemandLoads.delete(task)
872 void task.then(finish, finish)
873 return task
874 }
875
876 const toInlinedWhereClause = (compiled: {
877 where?: string
878 params: Array<unknown>
879 }): string => {
880 if (!compiled.where) return 'TRUE'
881 const sqlParts = compiled.where.split('?')
882 return sanitizeSQL(
883 sqlParts as unknown as TemplateStringsArray,
884 ...compiled.params,
885 )
886 }
887
888 const reportDemandCleanupFailure = (error: unknown): void => {
889 database.logger.log({
890 level: LogLevels.error,
891 message: `Could not clean up subset hook for ${viewName}`,
892 error,
893 })
894 }
895
896 const cleanupDemand = (demand: DemandRecord): void => {
897 demands.delete(demand.options)
898 try {
899 const cleanup = demand.cleanup
900 demand.cleanup = undefined
901 const result: unknown = cleanup?.()
902 if (!isPromiseLike(result)) return
903
904 const task = Promise.resolve(result)
905 pendingDemandCleanups.add(task)
906 const finish = () => pendingDemandCleanups.delete(task)
907 void task.then(finish, finish)
908 if (demandCleanupCollector) {
909 demandCleanupCollector.tasks.push(task)
910 demandCleanupCollector.ownedTasks.add(task)
911 void task.catch(() => undefined)
912 } else {
913 void task.catch((error) => {
914 if (!demandCleanupCollector?.ownedTasks.has(task)) {
915 reportDemandCleanupFailure(error)
916 }
917 })
918 }
919 } catch (error) {
920 if (demandCleanupCollector) {
921 demandCleanupCollector.failure ??= { error }
922 } else {
923 reportDemandCleanupFailure(error)
924 }
925 }
926 }
927
928 const performPhysicalRelease = async (
929 options: LoadSubsetOptions,
930 ): Promise<void> => {
931 const compiledDeparting = compileSQLite({ where: options.where })
932 const departingWhereSQL = toInlinedWhereClause(compiledDeparting)
933 let rowsToEvict: Array<{ id: string }>
934 for (;;) {
935 if (stopped) return
936 const revision = trackingRevision
937 const active = activeWhereExpressions()
938 let evictionSQL: string
939 if (active.length === 0) {
940 evictionSQL = `SELECT id FROM ${viewName} WHERE ${departingWhereSQL}`
941 } else {
942 const combinedRemaining =
943 active.length === 1
944 ? active[0]!
945 : or(active[0], active[1], ...active.slice(2))
946 const compiledRemaining = compileSQLite({
947 where: combinedRemaining,
948 })
949 const remainingWhereSQL = toInlinedWhereClause(compiledRemaining)
950 evictionSQL = `SELECT id FROM ${viewName} WHERE (${departingWhereSQL}) AND NOT (${remainingWhereSQL})`
951 }
952
953 rowsToEvict = await database.getAll<{ id: string }>(evictionSQL)
954 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- cleanup can run during the query
955 if (stopped) return
956 if (trackingRevision === revision) break
957 }
958 if (rowsToEvict.length > 0) {
959 begin()
960 for (const { id } of rowsToEvict) {
961 write({ type: `delete`, key: id })
962 }
963 void commit()
964 }
965 await rebuildTracking()
966 }
967
968 function scheduleReleaseDrain(delay = 0): void {
969 if (stopped || drainingReleases || releaseRetryTimer) return
970 if (delay > 0) {
971 releaseRetryTimer = setTimeout(() => {
972 releaseRetryTimer = undefined
973 void drainReleases()
974 }, delay)
975 return
976 }
977 void drainReleases()
978 }
979
980 async function drainReleases(): Promise<void> {
981 if (stopped || drainingReleases) return
982 drainingReleases = true
983 let retryDelay = 0
984 try {
985 const attempts = pendingReleases.length
986 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- each release can reenter cleanup
987 for (let index = 0; !stopped && index < attempts; index++) {
988 const pending = pendingReleases.shift()!
989 try {
990 await performPhysicalRelease(pending.options)
991 } catch (error) {
992 pending.failures++
993 pendingReleases.push(pending)
994 const delay = Math.min(
995 1000 * 2 ** (pending.failures - 1),
996 30000,
997 )
998 retryDelay =
999 retryDelay === 0 ? delay : Math.min(retryDelay, delay)
1000 database.logger.log({
1001 level: LogLevels.error,
1002 message: `Could not release subset tracking for ${viewName}; retrying`,
1003 error,
1004 })
1005 }
1006 }
1007 } finally {
1008 drainingReleases = false
1009 }
1010 if (pendingReleases.length > 0) scheduleReleaseDrain(retryDelay)
1011 }
1012
1013 const unloadSubset = (options: LoadSubsetOptions): void => {
1014 releasedSubsets.add(options)
1015 const demand = demands.get(options)
1016 if (!demand) return
1017
1018 const wasActive = demand.active
1019 if (wasActive) trackingRevision++
1020 cleanupDemand(demand)
1021
1022 if (wasActive) {
1023 pendingReleases.push({ options, failures: 0 })
1024 // New work must not wait for another release's backoff.
1025 clearTimeout(releaseRetryTimer)
1026 releaseRetryTimer = undefined
1027 scheduleReleaseDrain()
1028 }
1029 }
1030
1031 markReady()
1032
1033 return {
1034 cleanup: () => {
1035 stopped = true
1036 clearTimeout(releaseRetryTimer)
1037 releaseRetryTimer = undefined
1038 database.logger.log({
1039 level: LogLevels.info,
1040 message: `Sync has been stopped for ${viewName} into ${trackedTableName}`,
1041 })
1042 abortController.abort()
1043 const trackingDisposal = disposeTrackingAfterAbort()
1044 const pendingLoads = [...pendingDemandLoads]
1045 const collector: DemandCleanupCollector = {
1046 tasks: [],
1047 ownedTasks: new Set(),
1048 }
1049 demandCleanupCollector = collector
1050 collector.tasks.push(...pendingDemandCleanups)
1051 for (const task of pendingDemandCleanups) {
1052 collector.ownedTasks.add(task)
1053 }
1054 for (const demand of demands.values()) {
1055 cleanupDemand(demand)
1056 }
1057 pendingReleases.length = 0
1058
1059 return (async () => {
1060 const ownershipSettlements = await Promise.allSettled([
1061 trackingDisposal,
1062 ...pendingLoads,
1063 ])
1064 const disposalSettlement = ownershipSettlements[0]
1065
1066 let settledTasks = 0
1067 while (settledTasks < collector.tasks.length) {
1068 const tasks = collector.tasks.slice(settledTasks)
1069 settledTasks = collector.tasks.length
1070 const outcomes = await Promise.allSettled(tasks)
1071 const rejected = outcomes.find(
1072 (outcome): outcome is PromiseRejectedResult =>
1073 outcome.status === `rejected`,
1074 )
1075 if (rejected) {
1076 collector.failure ??= { error: rejected.reason }
1077 }
1078 }
1079 if (disposalSettlement.status === `rejected`) {
1080 throw disposalSettlement.reason
1081 }
1082 if (collector.failure) throw collector.failure.error
1083 })().finally(() => {
1084 if (demandCleanupCollector === collector) {
1085 demandCleanupCollector = null
1086 }
1087 })
1088 },
1089 loadSubset: trackLoadSubset,
1090 unloadSubset,
1091 }
1092 }
1093 },
1094 // Expose the getSyncMetadata function
1095 getSyncMetadata: undefined,
1096 }
1097
1098 const getKey = (record: OutputType) => asPowerSyncRecord(record).id
1099
1100 const outputConfig: EnhancedPowerSyncCollectionConfig<
1101 TTable,
1102 OutputType,
1103 TSchema
1104 > = {
1105 ...restConfig,
1106 schema,
1107 getKey,
1108 // Syncing should start immediately since we need to monitor the changes for mutations
1109 startSync: true,
1110 syncMode,
1111 sync,
1112 onInsert: async (params) => {
1113 // The transaction here should only ever contain a single insert mutation
1114 return await transactor.applyTransaction(params.transaction)
1115 },
1116 onUpdate: async (params) => {
1117 // The transaction here should only ever contain a single update mutation
1118 return await transactor.applyTransaction(params.transaction)
1119 },
1120 onDelete: async (params) => {
1121 // The transaction here should only ever contain a single delete mutation
1122 return await transactor.applyTransaction(params.transaction)
1123 },
1124 utils: {
1125 getMeta: () => ({
1126 tableName: viewName,
1127 trackedTableName,
1128 metadataIsTracked,
1129 serializeValue: (value) =>
1130 serializeForSQLite<TTable>(value, table, serializer),
1131 }),
1132 },
1133 }
1134 return outputConfig
1135}