Open History to see the last commit
1import { DiffTriggerOperation, LogLevels, sanitizeSQL } from '@powersync/common'
2import { or, whenSyncAccepted, 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 {
329 begin,
330 write,
331 collection,
332 commit,
333 fail,
334 reportError,
335 reportHealthy,
336 } = params
337 // Readiness of this sync run: a reload runs `sync` again while the
338 // Collection still shows the previous run's status.
339 let ready = false
340 const markReady = () => {
341 ready = true
342 params.markReady()
343 }
344 const abortController = new AbortController()
345
346 let disposeTracking:
347 ((options?: { context?: LockContext }) => Promise<void>) | null = null
348 let trackingSetup: Promise<void> | null = null
349 let activeTrackingDisposal: Promise<void> | null = null
350 let abortTrackingDisposal: Promise<void> | null = null
351
352 if (syncMode === `eager`) {
353 return runEagerSync()
354 } else {
355 return runOnDemandSync()
356 }
357
358 /**
359 * Disposes the current diff trigger, if one is active, and clears the
360 * tracking state.
361 */
362 async function safelyDisposeTracking(
363 context?: LockContext,
364 ): Promise<void> {
365 // Cleanup can race trigger creation. Wait until the disposer has been
366 // published so an abort cannot strand a freshly-created trigger.
367 const setup = trackingSetup
368 if (setup) {
369 await setup.catch(() => undefined)
370 }
371
372 const dispose = disposeTracking
373 if (!dispose) {
374 // Reconciliation may have claimed the disposer after this caller
375 // observed setup. Join that invocation instead of settling early.
376 await activeTrackingDisposal
377 return
378 }
379
380 disposeTracking = null
381 let disposal: Promise<void>
382 try {
383 disposal = Promise.resolve(dispose(context ? { context } : undefined))
384 } catch (error) {
385 disposal = Promise.reject(error)
386 }
387 activeTrackingDisposal = disposal
388 try {
389 await disposal
390 } finally {
391 if (activeTrackingDisposal === disposal) {
392 activeTrackingDisposal = null
393 }
394 }
395 }
396
397 function disposeTrackingAfterAbort(): Promise<void> {
398 const disposal = (abortTrackingDisposal ??= safelyDisposeTracking())
399 // Abort event dispatch does not observe a listener's returned promise.
400 // The eager cleanup callback awaits this same promise below.
401 void disposal.catch(() => undefined)
402 return disposal
403 }
404
405 async function establishTracking(
406 options: Parameters<typeof createDiffTrigger>[0],
407 appliedReceipts: Array<SyncAppliedReceipt>,
408 ): Promise<void> {
409 const setup = (async () => {
410 const dispose = await createDiffTrigger(options, appliedReceipts)
411 disposeTracking = dispose
412 })()
413 trackingSetup = setup
414
415 try {
416 await setup
417 } finally {
418 if (trackingSetup === setup) {
419 trackingSetup = null
420 }
421 }
422 }
423
424 async function createDiffTrigger(
425 options: {
426 setupContext?: LockContext
427 // The load reads every row and replaces the rows the Collection
428 // holds.
429 snapshot?: boolean
430 when: Record<DiffTriggerOperation, string>
431 writeType: (rowId: string) => OperationType
432 batchQuery: (
433 lockContext: LockContext,
434 batchSize: number,
435 cursor: number,
436 ) => Promise<Array<TableType>>
437 },
438 appliedReceipts: Array<SyncAppliedReceipt>,
439 ) {
440 const { setupContext, snapshot, when, writeType, batchQuery } = options
441
442 return await database.triggers.createDiffTrigger({
443 source: viewName,
444 destination: trackedTableName,
445 columns: table.columns.map((column) => column.name),
446 setupContext,
447 when,
448 hooks: {
449 beforeCreate: async (context) => {
450 // A load of every row is one snapshot transaction: during a
451 // reload it replaces the kept rows, so a row the table no
452 // longer has goes. A subset load commits each batch. A
453 // transaction begins only once its rows are read, so a batch
454 // that fails leaves none open.
455 const batches: Array<Array<TableType>> = []
456 const apply = () => {
457 begin({ snapshot })
458 for (const row of batches.splice(0).flat()) {
459 write({
460 type: writeType(row.id),
461 value: deserializeSyncRow(row),
462 })
463 }
464 appliedReceipts.push(commit())
465 }
466 let currentBatchCount = syncBatchSize
467 let cursor = 0
468 while (currentBatchCount == syncBatchSize) {
469 const batchItems = await batchQuery(
470 context,
471 syncBatchSize,
472 cursor,
473 )
474 currentBatchCount = batchItems.length
475 cursor += currentBatchCount
476 batches.push(batchItems)
477 if (!snapshot) apply()
478 }
479 if (snapshot) apply()
480 database.logger.log({
481 level: LogLevels.info,
482 message: `Sync is ready for ${viewName} into ${trackedTableName}`,
483 })
484 },
485 },
486 })
487 }
488
489 async function flushDiffRecords(): Promise<void> {
490 // PowerSync can notify after creating the tracking table but before its
491 // create call returns. Preserve that notification until the disposer,
492 // which proves the trigger is usable, has been published.
493 const setup = trackingSetup
494 if (setup) {
495 await setup.catch(() => undefined)
496 }
497 if (!disposeTracking) {
498 return
499 }
500
501 const ignoredReceipts: Array<SyncAppliedReceipt> = []
502 await database
503 .writeTransaction(async (context) => {
504 await flushDiffRecordsWithContext(context, ignoredReceipts)
505 })
506 .catch((error) => {
507 database.logger.log({
508 level: LogLevels.error,
509 message: `An error has been detected in the sync handler`,
510 error,
511 })
512 })
513 }
514
515 // We can use this directly if we want to pair a flush with dispose+recreate diff trigger.
516 async function flushDiffRecordsWithContext(
517 context: LockContext,
518 appliedReceipts: Array<SyncAppliedReceipt>,
519 ): Promise<void> {
520 // There is nothing to flush if no tracking table is currently active.
521 if (!disposeTracking) {
522 return
523 }
524
525 try {
526 begin()
527 const operations = await context.getAll<TriggerDiffRecord>(
528 `SELECT * FROM ${trackedTableName} ORDER BY operation_id ASC`,
529 )
530 const pendingOperations: Array<PendingOperation> = []
531
532 for (const op of operations) {
533 const { id, operation, timestamp, value } = op
534 const parsedValue = deserializeSyncRow({
535 id,
536 ...JSON.parse(value),
537 })
538 const parsedPreviousValue =
539 op.operation == DiffTriggerOperation.UPDATE
540 ? deserializeSyncRow({
541 id,
542 ...JSON.parse(op.previous_value),
543 })
544 : undefined
545 write({
546 type: mapOperation(operation),
547 value: parsedValue,
548 previousValue: parsedPreviousValue,
549 })
550 pendingOperations.push({
551 id,
552 operation,
553 timestamp,
554 tableName: viewName,
555 })
556 }
557
558 // clear the current operations
559 await context.execute(`DELETE FROM ${trackedTableName}`)
560
561 const applied = commit()
562 appliedReceipts.push(applied)
563 // Mutation persistence is what releases the Collection's FIFO gate.
564 // Confirm these local operations after the sync transaction is
565 // staged; waiting for its applied receipt would deadlock the user
566 // transaction that currently parks it.
567 pendingOperationStore.resolvePendingFor(pendingOperations)
568 } catch (error) {
569 database.logger.log({
570 level: LogLevels.error,
571 message: `An error has been detected in the sync handler`,
572 error,
573 })
574 }
575 }
576
577 // The sync function needs to be synchronous.
578 async function start(afterOnChangeRegistered?: () => Promise<void>) {
579 database.logger.log({
580 level: LogLevels.info,
581 message: `Sync is starting for ${viewName} into ${trackedTableName}`,
582 })
583 database.onChangeWithCallback(
584 {
585 onChange: async () => {
586 await flushDiffRecords()
587 },
588 },
589 {
590 signal: abortController.signal,
591 triggerImmediate: false,
592 tables: [trackedTableName],
593 },
594 )
595
596 await afterOnChangeRegistered?.()
597
598 // If the abort controller was aborted while processing the request above
599 if (abortController.signal.aborted) {
600 await disposeTrackingAfterAbort()
601 } else {
602 abortController.signal.addEventListener(
603 `abort`,
604 () => {
605 void disposeTrackingAfterAbort()
606 },
607 { once: true },
608 )
609 }
610 }
611
612 // Eager mode.
613 // Registers a diff trigger for the entire table.
614 function runEagerSync() {
615 let onUnload: CleanupFn | void | null = null
616 let onUnloadStarted = false
617
618 const startup = start(async () => {
619 const cleanup = await restConfig.onLoad?.()
620 onUnload = cleanup
621 if (abortController.signal.aborted) {
622 return
623 }
624
625 const appliedReceipts: Array<SyncAppliedReceipt> = []
626 await establishTracking(
627 {
628 // When the Collection holds rows, such as a reload's kept rows,
629 // the load of every row replaces them.
630 snapshot: !collection._state.acceptedSyncedEntries().next().done,
631 when: {
632 [DiffTriggerOperation.INSERT]: `TRUE`,
633 [DiffTriggerOperation.UPDATE]: `TRUE`,
634 [DiffTriggerOperation.DELETE]: `TRUE`,
635 },
636 writeType: (_rowId: string) => `insert`,
637 batchQuery: (
638 lockContext: LockContext,
639 batchSize: number,
640 cursor: number,
641 ) =>
642 lockContext.getAll<TableType>(
643 sanitizeSQL`SELECT * FROM ${viewName} LIMIT ? OFFSET ?`,
644 [batchSize, cursor],
645 ),
646 },
647 appliedReceipts,
648 )
649 // Readiness counts accepted rows. A mutation handler waits for it,
650 // and its own persisting transaction holds the startup rows.
651 await Promise.all(appliedReceipts.map(whenSyncAccepted))
652 markReady()
653 }).catch((error) => {
654 database.logger.log({
655 level: LogLevels.error,
656 message: `Could not start syncing process for ${viewName} into ${trackedTableName}`,
657 error,
658 })
659 if (!ready) fail(error)
660 })
661
662 const invokeOnUnload = (): void | Promise<void> => {
663 if (onUnloadStarted || !onUnload) return
664 onUnloadStarted = true
665 const cleanup = onUnload
666 onUnload = null
667 return cleanup()
668 }
669
670 return async () => {
671 database.logger.log({
672 level: LogLevels.info,
673 message: `Sync has been stopped for ${viewName} into ${trackedTableName}`,
674 })
675 abortController.abort()
676 const trackingDisposal = disposeTrackingAfterAbort()
677
678 let onUnloadFailure: { error: unknown } | undefined
679 const settleOnUnload = async () => {
680 try {
681 await invokeOnUnload()
682 } catch (error) {
683 onUnloadFailure ??= { error }
684 }
685 }
686
687 // Invoke an already-installed callback in this stack, but also wait
688 // for startup to publish a callback acquired concurrently with abort.
689 const settlements = await Promise.allSettled([
690 startup,
691 trackingDisposal,
692 settleOnUnload(),
693 ])
694 const disposalSettlement = settlements[1]
695 await settleOnUnload()
696 if (disposalSettlement.status === `rejected` && onUnloadFailure) {
697 throw new AggregateError(
698 [disposalSettlement.reason, onUnloadFailure.error],
699 `PowerSync tracking disposal and load-hook cleanup both failed`,
700 { cause: disposalSettlement.reason },
701 )
702 }
703 if (disposalSettlement.status === `rejected`) {
704 throw disposalSettlement.reason
705 }
706 if (onUnloadFailure) throw onUnloadFailure.error
707 }
708 }
709
710 // On-demand mode.
711 // Registers a diff trigger for the active WHERE expressions.
712 function runOnDemandSync() {
713 type DemandRecord = {
714 options: LoadSubsetOptions
715 active: boolean
716 cleanup?: CleanupFn
717 }
718 type PendingRelease = {
719 options: LoadSubsetOptions
720 failures: number
721 }
722 type DemandCleanupTask = {
723 order: number
724 promise: Promise<unknown>
725 }
726 type DemandCleanupFailure = {
727 order: number
728 error: unknown
729 }
730 type DemandCleanupCollector = {
731 tasks: Array<DemandCleanupTask>
732 ownedTasks: Set<Promise<unknown>>
733 failures: Array<DemandCleanupFailure>
734 nextOrder: number
735 }
736
737 const demands = new Map<LoadSubsetOptions, DemandRecord>()
738 const releasedSubsets = new WeakSet<LoadSubsetOptions>()
739 const pendingReleases: Array<PendingRelease> = []
740 const pendingDemandLoads = new Set<Promise<void>>()
741 const pendingDemandCleanups = new Set<Promise<unknown>>()
742 let stopped = false
743 let trackingRevision = 0
744 let reconciledTrackingRevision = 0
745 let rebuildPromise: Promise<void> | null = null
746 let drainingReleases = false
747 let releaseRetryTimer: ReturnType<typeof setTimeout> | undefined
748 let demandCleanupCollector: DemandCleanupCollector | null = null
749 const startup = start()
750 void startup.catch((error) =>
751 database.logger.log({
752 level: LogLevels.error,
753 message: `Could not start syncing process for ${viewName} into ${trackedTableName}`,
754 error,
755 }),
756 )
757
758 const activeWhereExpressions = () =>
759 Array.from(demands.values())
760 .filter((demand) => demand.active)
761 .map((demand) => demand.options.where)
762
763 // One reconciliation owns every queued revision so callers cannot
764 // settle against a stale trigger configuration.
765 // Set while a failed rebuild may have left the source untracked.
766 let trackingOutage = false
767 const reconcileTracking = async (): Promise<void> => {
768 while (!stopped && reconciledTrackingRevision !== trackingRevision) {
769 const revision = trackingRevision
770 const isCurrent = () => !stopped && trackingRevision === revision
771 const appliedReceipts: Array<SyncAppliedReceipt> = []
772
773 await database.writeLock(async (ctx) => {
774 if (!isCurrent()) return
775 await flushDiffRecordsWithContext(ctx, appliedReceipts)
776 if (!isCurrent()) return
777 await safelyDisposeTracking(ctx)
778 if (!isCurrent()) return
779
780 const active = activeWhereExpressions()
781 // Tracking was absent during an outage. Positive baseline rows
782 // alone cannot reveal deletes or predicate exits from that gap.
783 const missing = trackingOutage
784 ? new Set(collection.keys())
785 : undefined
786 if (active.length > 0) {
787 const combinedWhere =
788 active.length === 1
789 ? active[0]
790 : or(active[0], active[1], ...active.slice(2))
791 const compiledNewData = compileSQLite(
792 { where: combinedWhere },
793 { jsonColumn: 'NEW.data' },
794 )
795 const compiledOldData = compileSQLite(
796 { where: combinedWhere },
797 { jsonColumn: 'OLD.data' },
798 )
799 const compiledView = compileSQLite({ where: combinedWhere })
800 const newDataWhenClause = toInlinedWhereClause(compiledNewData)
801 const oldDataWhenClause = toInlinedWhereClause(compiledOldData)
802 const viewWhereClause = toInlinedWhereClause(compiledView)
803 await establishTracking(
804 {
805 setupContext: ctx,
806 when: {
807 [DiffTriggerOperation.INSERT]: newDataWhenClause,
808 [DiffTriggerOperation.UPDATE]: `(${newDataWhenClause}) OR (${oldDataWhenClause})`,
809 [DiffTriggerOperation.DELETE]: oldDataWhenClause,
810 },
811 writeType: (rowId: string) =>
812 collection.has(rowId) ? `update` : `insert`,
813 batchQuery: (
814 lockContext: LockContext,
815 batchSize: number,
816 cursor: number,
817 ) =>
818 lockContext
819 .getAll<TableType>(
820 `SELECT * FROM ${viewName} WHERE ${viewWhereClause} LIMIT ? OFFSET ?`,
821 [batchSize, cursor],
822 )
823 .then((rows) => {
824 for (const row of rows) missing?.delete(row.id)
825 return rows
826 }),
827 },
828 appliedReceipts,
829 )
830 }
831 if (!isCurrent()) await safelyDisposeTracking(ctx)
832 else if (missing?.size) {
833 begin()
834 for (const key of missing) write({ type: `delete`, key })
835 appliedReceipts.push(commit())
836 }
837 })
838 await Promise.all(appliedReceipts)
839 if (isCurrent()) {
840 reconciledTrackingRevision = revision
841 // Replacing the trigger alone does not restore change tracking:
842 // its baseline writes must also apply before sync works again.
843 if (trackingOutage) {
844 trackingOutage = false
845 reportHealthy()
846 }
847 }
848 }
849 }
850
851 const rebuildTracking = async (): Promise<void> => {
852 // New demand can join after reconciliation exits but before its
853 // shared promise clears. Each waiter must check its revision again.
854 while (!stopped && reconciledTrackingRevision !== trackingRevision) {
855 await (rebuildPromise ??= reconcileTracking()
856 .catch((error) => {
857 // A rebuild may already have removed every active diff trigger,
858 // so rows can grow stale. Later demand rebuilds again, so after
859 // Collection readiness this is a failureReason, not fail().
860 if (stopped) {
861 // Cleanup owns the outcome.
862 } else if (ready) {
863 trackingOutage = true
864 reportError(error)
865 } else fail(error)
866 throw error
867 })
868 .finally(() => {
869 rebuildPromise = null
870 }))
871 }
872 }
873
874 const loadSubset = async (
875 options: LoadSubsetOptions,
876 ): Promise<void> => {
877 if (stopped) return
878 // Never create a trigger that has no observer to drain its diff table.
879 await startup
880 if (
881 // Cleanup can run while startup is pending.
882 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
883 stopped ||
884 releasedSubsets.has(options) ||
885 options.signal?.aborted
886 ) {
887 return
888 }
889
890 const demand: DemandRecord = { options, active: false }
891 demands.set(options, demand)
892 try {
893 const cleanup = await restConfig.onLoadSubset?.(options)
894 if (cleanup) demand.cleanup = cleanup
895 } catch (error) {
896 demands.delete(options)
897 const collector = demandCleanupCollector
898 if (collector) {
899 collector.failures.push({
900 order: collector.nextOrder++,
901 error,
902 })
903 }
904 throw error
905 }
906
907 if (
908 // The user hook can reenter cleanup.
909 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
910 stopped ||
911 releasedSubsets.has(options) ||
912 options.signal?.aborted ||
913 demands.get(options) !== demand
914 ) {
915 cleanupDemand(demand)
916 return
917 }
918
919 demand.active = true
920 trackingRevision++
921 await rebuildTracking()
922 }
923
924 const trackLoadSubset = (options: LoadSubsetOptions): Promise<void> => {
925 const task = loadSubset(options)
926 pendingDemandLoads.add(task)
927 const finish = () => pendingDemandLoads.delete(task)
928 void task.then(finish, finish)
929 return task
930 }
931
932 const toInlinedWhereClause = (compiled: {
933 where?: string
934 params: Array<unknown>
935 }): string => {
936 if (!compiled.where) return 'TRUE'
937 const sqlParts = compiled.where.split('?')
938 return sanitizeSQL(
939 sqlParts as unknown as TemplateStringsArray,
940 ...compiled.params,
941 )
942 }
943
944 const reportDemandCleanupFailure = (error: unknown): void => {
945 database.logger.log({
946 level: LogLevels.error,
947 message: `Could not clean up subset hook for ${viewName}`,
948 error,
949 })
950 }
951
952 const cleanupDemand = (demand: DemandRecord): void => {
953 demands.delete(demand.options)
954 const collector = demandCleanupCollector
955 const order = collector ? collector.nextOrder++ : undefined
956 try {
957 const cleanup = demand.cleanup
958 demand.cleanup = undefined
959 const result: unknown = cleanup?.()
960 if (!isPromiseLike(result)) return
961
962 const task = Promise.resolve(result)
963 pendingDemandCleanups.add(task)
964 const finish = () => pendingDemandCleanups.delete(task)
965 void task.then(finish, finish)
966 if (collector) {
967 collector.tasks.push({ order: order!, promise: task })
968 collector.ownedTasks.add(task)
969 void task.catch(() => undefined)
970 } else {
971 void task.catch((error) => {
972 if (!demandCleanupCollector?.ownedTasks.has(task)) {
973 reportDemandCleanupFailure(error)
974 }
975 })
976 }
977 } catch (error) {
978 if (collector) {
979 collector.failures.push({ order: order!, error })
980 } else {
981 reportDemandCleanupFailure(error)
982 }
983 }
984 }
985
986 const throwDemandCleanupFailures = (
987 collector: DemandCleanupCollector,
988 primaryFailures: ReadonlyArray<unknown> = [],
989 ): void => {
990 const errors = [
991 ...primaryFailures,
992 ...collector.failures
993 .slice()
994 .sort((left, right) => left.order - right.order)
995 .map(({ error }) => error),
996 ]
997 if (errors.length === 1) throw errors[0]
998 if (errors.length > 1) {
999 throw new AggregateError(errors, `PowerSync cleanup failed`, {
1000 cause: errors[0],
1001 })
1002 }
1003 }
1004
1005 const performPhysicalRelease = async (
1006 options: LoadSubsetOptions,
1007 ): Promise<void> => {
1008 const compiledDeparting = compileSQLite({ where: options.where })
1009 const departingWhereSQL = toInlinedWhereClause(compiledDeparting)
1010 let rowsToEvict: Array<{ id: string }>
1011 for (;;) {
1012 if (stopped) return
1013 const revision = trackingRevision
1014 const active = activeWhereExpressions()
1015 let evictionSQL: string
1016 if (active.length === 0) {
1017 evictionSQL = `SELECT id FROM ${viewName} WHERE ${departingWhereSQL}`
1018 } else {
1019 const combinedRemaining =
1020 active.length === 1
1021 ? active[0]!
1022 : or(active[0], active[1], ...active.slice(2))
1023 const compiledRemaining = compileSQLite({
1024 where: combinedRemaining,
1025 })
1026 const remainingWhereSQL = toInlinedWhereClause(compiledRemaining)
1027 evictionSQL = `SELECT id FROM ${viewName} WHERE (${departingWhereSQL}) AND NOT (${remainingWhereSQL})`
1028 }
1029
1030 rowsToEvict = await database.getAll<{ id: string }>(evictionSQL)
1031 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- cleanup can run during the query
1032 if (stopped) return
1033 if (trackingRevision === revision) break
1034 }
1035 if (rowsToEvict.length > 0) {
1036 begin()
1037 for (const { id } of rowsToEvict) {
1038 write({ type: `delete`, key: id })
1039 }
1040 void commit()
1041 }
1042 await rebuildTracking()
1043 }
1044
1045 function scheduleReleaseDrain(delay = 0): void {
1046 if (stopped || drainingReleases || releaseRetryTimer) return
1047 if (delay > 0) {
1048 releaseRetryTimer = setTimeout(() => {
1049 releaseRetryTimer = undefined
1050 void drainReleases()
1051 }, delay)
1052 return
1053 }
1054 void drainReleases()
1055 }
1056
1057 async function drainReleases(): Promise<void> {
1058 if (stopped || drainingReleases) return
1059 drainingReleases = true
1060 let retryDelay = 0
1061 try {
1062 const attempts = pendingReleases.length
1063 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- each release can reenter cleanup
1064 for (let index = 0; !stopped && index < attempts; index++) {
1065 const pending = pendingReleases.shift()!
1066 try {
1067 await performPhysicalRelease(pending.options)
1068 } catch (error) {
1069 pending.failures++
1070 pendingReleases.push(pending)
1071 const delay = Math.min(
1072 1000 * 2 ** (pending.failures - 1),
1073 30000,
1074 )
1075 retryDelay =
1076 retryDelay === 0 ? delay : Math.min(retryDelay, delay)
1077 database.logger.log({
1078 level: LogLevels.error,
1079 message: `Could not release subset tracking for ${viewName}; retrying`,
1080 error,
1081 })
1082 }
1083 }
1084 } finally {
1085 drainingReleases = false
1086 }
1087 if (pendingReleases.length > 0) scheduleReleaseDrain(retryDelay)
1088 }
1089
1090 const unloadSubset = (options: LoadSubsetOptions): void => {
1091 releasedSubsets.add(options)
1092 const demand = demands.get(options)
1093 if (!demand) return
1094
1095 const wasActive = demand.active
1096 if (wasActive) trackingRevision++
1097 cleanupDemand(demand)
1098
1099 if (wasActive) {
1100 pendingReleases.push({ options, failures: 0 })
1101 // New work must not wait for another release's backoff.
1102 clearTimeout(releaseRetryTimer)
1103 releaseRetryTimer = undefined
1104 scheduleReleaseDrain()
1105 }
1106 }
1107
1108 markReady()
1109
1110 return {
1111 cleanup: () => {
1112 stopped = true
1113 clearTimeout(releaseRetryTimer)
1114 releaseRetryTimer = undefined
1115 database.logger.log({
1116 level: LogLevels.info,
1117 message: `Sync has been stopped for ${viewName} into ${trackedTableName}`,
1118 })
1119 abortController.abort()
1120 const trackingDisposal = disposeTrackingAfterAbort()
1121 const pendingLoads = [...pendingDemandLoads]
1122 const pendingTasks = [...pendingDemandCleanups]
1123 const collector: DemandCleanupCollector = {
1124 tasks: pendingTasks.map((promise, order) => ({ order, promise })),
1125 ownedTasks: new Set(pendingTasks),
1126 failures: [],
1127 nextOrder: pendingTasks.length,
1128 }
1129 demandCleanupCollector = collector
1130 for (const demand of demands.values()) {
1131 cleanupDemand(demand)
1132 }
1133 pendingReleases.length = 0
1134
1135 return (async () => {
1136 const ownershipSettlements = await Promise.allSettled([
1137 trackingDisposal,
1138 ...pendingLoads,
1139 ])
1140 const disposalSettlement = ownershipSettlements[0]
1141
1142 let settledTasks = 0
1143 while (settledTasks < collector.tasks.length) {
1144 const tasks = collector.tasks.slice(settledTasks)
1145 settledTasks = collector.tasks.length
1146 const outcomes = await Promise.allSettled(
1147 tasks.map(({ promise }) => promise),
1148 )
1149 for (const [index, outcome] of outcomes.entries()) {
1150 if (outcome.status === `rejected`) {
1151 collector.failures.push({
1152 order: tasks[index]!.order,
1153 error: outcome.reason,
1154 })
1155 }
1156 }
1157 }
1158 throwDemandCleanupFailures(
1159 collector,
1160 disposalSettlement.status === `rejected`
1161 ? [disposalSettlement.reason]
1162 : [],
1163 )
1164 })().finally(() => {
1165 if (demandCleanupCollector === collector) {
1166 demandCleanupCollector = null
1167 }
1168 })
1169 },
1170 loadSubset: trackLoadSubset,
1171 unloadSubset,
1172 }
1173 }
1174 },
1175 // Expose the getSyncMetadata function
1176 getSyncMetadata: undefined,
1177 }
1178
1179 const getKey = (record: OutputType) => asPowerSyncRecord(record).id
1180
1181 // Keep adapter hooks and serialization options out of the core config.
1182 const {
1183 onLoad: _onLoad,
1184 onLoadSubset: _onLoadSubset,
1185 deserializationSchema: _deserializationSchema,
1186 serializer: _serializer,
1187 onDeserializationError: _onDeserializationError,
1188 ...collectionConfig
1189 } = {
1190 deserializationSchema,
1191 serializer,
1192 onDeserializationError,
1193 ...restConfig,
1194 }
1195
1196 const outputConfig: EnhancedPowerSyncCollectionConfig<
1197 TTable,
1198 OutputType,
1199 TSchema
1200 > = {
1201 ...collectionConfig,
1202 schema,
1203 getKey,
1204 // Syncing should start immediately since we need to monitor the changes for mutations
1205 startSync: true,
1206 syncMode,
1207 sync,
1208 onInsert: async (params) => {
1209 // The transaction here should only ever contain a single insert mutation
1210 return await transactor.applyTransaction(params.transaction)
1211 },
1212 onUpdate: async (params) => {
1213 // The transaction here should only ever contain a single update mutation
1214 return await transactor.applyTransaction(params.transaction)
1215 },
1216 onDelete: async (params) => {
1217 // The transaction here should only ever contain a single delete mutation
1218 return await transactor.applyTransaction(params.transaction)
1219 },
1220 utils: {
1221 getMeta: () => ({
1222 tableName: viewName,
1223 trackedTableName,
1224 metadataIsTracked,
1225 serializeValue: (value) =>
1226 serializeForSQLite<TTable>(value, table, serializer),
1227 }),
1228 },
1229 }
1230 return outputConfig
1231}