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 onUnloadFailure: { error: unknown } | undefined
653 const settleOnUnload = async () => {
654 try {
655 await invokeOnUnload()
656 } catch (error) {
657 onUnloadFailure ??= { 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 await settleOnUnload()
670 if (disposalSettlement.status === `rejected` && onUnloadFailure) {
671 throw new AggregateError(
672 [disposalSettlement.reason, onUnloadFailure.error],
673 `PowerSync tracking disposal and load-hook cleanup both failed`,
674 { cause: disposalSettlement.reason },
675 )
676 }
677 if (disposalSettlement.status === `rejected`) {
678 throw disposalSettlement.reason
679 }
680 if (onUnloadFailure) throw onUnloadFailure.error
681 }
682 }
683
684 // On-demand mode.
685 // Registers a diff trigger for the active WHERE expressions.
686 function runOnDemandSync() {
687 type DemandRecord = {
688 options: LoadSubsetOptions
689 active: boolean
690 cleanup?: CleanupFn
691 }
692 type PendingRelease = {
693 options: LoadSubsetOptions
694 failures: number
695 }
696 type DemandCleanupTask = {
697 order: number
698 promise: Promise<unknown>
699 }
700 type DemandCleanupFailure = {
701 order: number
702 error: unknown
703 }
704 type DemandCleanupCollector = {
705 tasks: Array<DemandCleanupTask>
706 ownedTasks: Set<Promise<unknown>>
707 failures: Array<DemandCleanupFailure>
708 nextOrder: number
709 }
710
711 const demands = new Map<LoadSubsetOptions, DemandRecord>()
712 const releasedSubsets = new WeakSet<LoadSubsetOptions>()
713 const pendingReleases: Array<PendingRelease> = []
714 const pendingDemandLoads = new Set<Promise<void>>()
715 const pendingDemandCleanups = new Set<Promise<unknown>>()
716 let stopped = false
717 let trackingRevision = 0
718 let reconciledTrackingRevision = 0
719 let rebuildPromise: Promise<void> | null = null
720 let drainingReleases = false
721 let releaseRetryTimer: ReturnType<typeof setTimeout> | undefined
722 let demandCleanupCollector: DemandCleanupCollector | null = null
723 const startup = start()
724 void startup.catch((error) =>
725 database.logger.log({
726 level: LogLevels.error,
727 message: `Could not start syncing process for ${viewName} into ${trackedTableName}`,
728 error,
729 }),
730 )
731
732 const activeWhereExpressions = () =>
733 Array.from(demands.values())
734 .filter((demand) => demand.active)
735 .map((demand) => demand.options.where)
736
737 // One reconciliation owns every queued revision so callers cannot
738 // settle against a stale trigger configuration.
739 const reconcileTracking = async (): Promise<void> => {
740 while (!stopped && reconciledTrackingRevision !== trackingRevision) {
741 const revision = trackingRevision
742 const isCurrent = () => !stopped && trackingRevision === revision
743 const appliedReceipts: Array<SyncAppliedReceipt> = []
744
745 await database.writeLock(async (ctx) => {
746 if (!isCurrent()) return
747 await flushDiffRecordsWithContext(ctx, appliedReceipts)
748 if (!isCurrent()) return
749 await safelyDisposeTracking(ctx)
750 if (!isCurrent()) return
751
752 const active = activeWhereExpressions()
753 // Tracking was absent during an error. Positive baseline rows
754 // alone cannot reveal deletes or predicate exits from that gap.
755 const missing =
756 collection.status === `error`
757 ? new Set(collection.keys())
758 : undefined
759 if (active.length > 0) {
760 const combinedWhere =
761 active.length === 1
762 ? active[0]
763 : or(active[0], active[1], ...active.slice(2))
764 const compiledNewData = compileSQLite(
765 { where: combinedWhere },
766 { jsonColumn: 'NEW.data' },
767 )
768 const compiledOldData = compileSQLite(
769 { where: combinedWhere },
770 { jsonColumn: 'OLD.data' },
771 )
772 const compiledView = compileSQLite({ where: combinedWhere })
773 const newDataWhenClause = toInlinedWhereClause(compiledNewData)
774 const oldDataWhenClause = toInlinedWhereClause(compiledOldData)
775 const viewWhereClause = toInlinedWhereClause(compiledView)
776 await establishTracking(
777 {
778 setupContext: ctx,
779 when: {
780 [DiffTriggerOperation.INSERT]: newDataWhenClause,
781 [DiffTriggerOperation.UPDATE]: `(${newDataWhenClause}) OR (${oldDataWhenClause})`,
782 [DiffTriggerOperation.DELETE]: oldDataWhenClause,
783 },
784 writeType: (rowId: string) =>
785 collection.has(rowId) ? `update` : `insert`,
786 batchQuery: (
787 lockContext: LockContext,
788 batchSize: number,
789 cursor: number,
790 ) =>
791 lockContext
792 .getAll<TableType>(
793 `SELECT * FROM ${viewName} WHERE ${viewWhereClause} LIMIT ? OFFSET ?`,
794 [batchSize, cursor],
795 )
796 .then((rows) => {
797 for (const row of rows) missing?.delete(row.id)
798 return rows
799 }),
800 },
801 appliedReceipts,
802 )
803 }
804 if (!isCurrent()) await safelyDisposeTracking(ctx)
805 else if (missing?.size) {
806 begin()
807 for (const key of missing) write({ type: `delete`, key })
808 appliedReceipts.push(commit())
809 }
810 })
811 await Promise.all(appliedReceipts)
812 if (isCurrent()) {
813 reconciledTrackingRevision = revision
814 // Replacing the trigger alone is not recovery: its baseline
815 // writes must also be applied before the source is ready again.
816 if (collection.status === `error`) markReady()
817 }
818 }
819 }
820
821 const rebuildTracking = async (): Promise<void> => {
822 // New demand can join after reconciliation exits but before its
823 // shared promise clears. Each waiter must check its revision again.
824 while (!stopped && reconciledTrackingRevision !== trackingRevision) {
825 await (rebuildPromise ??= reconcileTracking()
826 .catch((error) => {
827 // A rebuild may already have removed every active diff trigger.
828 // Do not leave healthy consumers ready against a stale source.
829 if (!stopped) markError(error)
830 throw error
831 })
832 .finally(() => {
833 rebuildPromise = null
834 }))
835 }
836 }
837
838 const loadSubset = async (
839 options: LoadSubsetOptions,
840 ): Promise<void> => {
841 if (stopped) return
842 // Never create a trigger that has no observer to drain its diff table.
843 await startup
844 if (
845 // Cleanup can run while startup is pending.
846 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
847 stopped ||
848 releasedSubsets.has(options) ||
849 options.signal?.aborted
850 ) {
851 return
852 }
853
854 const demand: DemandRecord = { options, active: false }
855 demands.set(options, demand)
856 try {
857 const cleanup = await restConfig.onLoadSubset?.(options)
858 if (cleanup) demand.cleanup = cleanup
859 } catch (error) {
860 demands.delete(options)
861 const collector = demandCleanupCollector
862 if (collector) {
863 collector.failures.push({
864 order: collector.nextOrder++,
865 error,
866 })
867 }
868 throw error
869 }
870
871 if (
872 // The user hook can reenter cleanup.
873 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
874 stopped ||
875 releasedSubsets.has(options) ||
876 options.signal?.aborted ||
877 demands.get(options) !== demand
878 ) {
879 cleanupDemand(demand)
880 return
881 }
882
883 demand.active = true
884 trackingRevision++
885 await rebuildTracking()
886 }
887
888 const trackLoadSubset = (options: LoadSubsetOptions): Promise<void> => {
889 const task = loadSubset(options)
890 pendingDemandLoads.add(task)
891 const finish = () => pendingDemandLoads.delete(task)
892 void task.then(finish, finish)
893 return task
894 }
895
896 const toInlinedWhereClause = (compiled: {
897 where?: string
898 params: Array<unknown>
899 }): string => {
900 if (!compiled.where) return 'TRUE'
901 const sqlParts = compiled.where.split('?')
902 return sanitizeSQL(
903 sqlParts as unknown as TemplateStringsArray,
904 ...compiled.params,
905 )
906 }
907
908 const reportDemandCleanupFailure = (error: unknown): void => {
909 database.logger.log({
910 level: LogLevels.error,
911 message: `Could not clean up subset hook for ${viewName}`,
912 error,
913 })
914 }
915
916 const cleanupDemand = (demand: DemandRecord): void => {
917 demands.delete(demand.options)
918 const collector = demandCleanupCollector
919 const order = collector ? collector.nextOrder++ : undefined
920 try {
921 const cleanup = demand.cleanup
922 demand.cleanup = undefined
923 const result: unknown = cleanup?.()
924 if (!isPromiseLike(result)) return
925
926 const task = Promise.resolve(result)
927 pendingDemandCleanups.add(task)
928 const finish = () => pendingDemandCleanups.delete(task)
929 void task.then(finish, finish)
930 if (collector) {
931 collector.tasks.push({ order: order!, promise: task })
932 collector.ownedTasks.add(task)
933 void task.catch(() => undefined)
934 } else {
935 void task.catch((error) => {
936 if (!demandCleanupCollector?.ownedTasks.has(task)) {
937 reportDemandCleanupFailure(error)
938 }
939 })
940 }
941 } catch (error) {
942 if (collector) {
943 collector.failures.push({ order: order!, error })
944 } else {
945 reportDemandCleanupFailure(error)
946 }
947 }
948 }
949
950 const throwDemandCleanupFailures = (
951 collector: DemandCleanupCollector,
952 primaryFailures: ReadonlyArray<unknown> = [],
953 ): void => {
954 const errors = [
955 ...primaryFailures,
956 ...collector.failures
957 .slice()
958 .sort((left, right) => left.order - right.order)
959 .map(({ error }) => error),
960 ]
961 if (errors.length === 1) throw errors[0]
962 if (errors.length > 1) {
963 throw new AggregateError(errors, `PowerSync cleanup failed`, {
964 cause: errors[0],
965 })
966 }
967 }
968
969 const performPhysicalRelease = async (
970 options: LoadSubsetOptions,
971 ): Promise<void> => {
972 const compiledDeparting = compileSQLite({ where: options.where })
973 const departingWhereSQL = toInlinedWhereClause(compiledDeparting)
974 let rowsToEvict: Array<{ id: string }>
975 for (;;) {
976 if (stopped) return
977 const revision = trackingRevision
978 const active = activeWhereExpressions()
979 let evictionSQL: string
980 if (active.length === 0) {
981 evictionSQL = `SELECT id FROM ${viewName} WHERE ${departingWhereSQL}`
982 } else {
983 const combinedRemaining =
984 active.length === 1
985 ? active[0]!
986 : or(active[0], active[1], ...active.slice(2))
987 const compiledRemaining = compileSQLite({
988 where: combinedRemaining,
989 })
990 const remainingWhereSQL = toInlinedWhereClause(compiledRemaining)
991 evictionSQL = `SELECT id FROM ${viewName} WHERE (${departingWhereSQL}) AND NOT (${remainingWhereSQL})`
992 }
993
994 rowsToEvict = await database.getAll<{ id: string }>(evictionSQL)
995 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- cleanup can run during the query
996 if (stopped) return
997 if (trackingRevision === revision) break
998 }
999 if (rowsToEvict.length > 0) {
1000 begin()
1001 for (const { id } of rowsToEvict) {
1002 write({ type: `delete`, key: id })
1003 }
1004 void commit()
1005 }
1006 await rebuildTracking()
1007 }
1008
1009 function scheduleReleaseDrain(delay = 0): void {
1010 if (stopped || drainingReleases || releaseRetryTimer) return
1011 if (delay > 0) {
1012 releaseRetryTimer = setTimeout(() => {
1013 releaseRetryTimer = undefined
1014 void drainReleases()
1015 }, delay)
1016 return
1017 }
1018 void drainReleases()
1019 }
1020
1021 async function drainReleases(): Promise<void> {
1022 if (stopped || drainingReleases) return
1023 drainingReleases = true
1024 let retryDelay = 0
1025 try {
1026 const attempts = pendingReleases.length
1027 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- each release can reenter cleanup
1028 for (let index = 0; !stopped && index < attempts; index++) {
1029 const pending = pendingReleases.shift()!
1030 try {
1031 await performPhysicalRelease(pending.options)
1032 } catch (error) {
1033 pending.failures++
1034 pendingReleases.push(pending)
1035 const delay = Math.min(
1036 1000 * 2 ** (pending.failures - 1),
1037 30000,
1038 )
1039 retryDelay =
1040 retryDelay === 0 ? delay : Math.min(retryDelay, delay)
1041 database.logger.log({
1042 level: LogLevels.error,
1043 message: `Could not release subset tracking for ${viewName}; retrying`,
1044 error,
1045 })
1046 }
1047 }
1048 } finally {
1049 drainingReleases = false
1050 }
1051 if (pendingReleases.length > 0) scheduleReleaseDrain(retryDelay)
1052 }
1053
1054 const unloadSubset = (options: LoadSubsetOptions): void => {
1055 releasedSubsets.add(options)
1056 const demand = demands.get(options)
1057 if (!demand) return
1058
1059 const wasActive = demand.active
1060 if (wasActive) trackingRevision++
1061 cleanupDemand(demand)
1062
1063 if (wasActive) {
1064 pendingReleases.push({ options, failures: 0 })
1065 // New work must not wait for another release's backoff.
1066 clearTimeout(releaseRetryTimer)
1067 releaseRetryTimer = undefined
1068 scheduleReleaseDrain()
1069 }
1070 }
1071
1072 markReady()
1073
1074 return {
1075 cleanup: () => {
1076 stopped = true
1077 clearTimeout(releaseRetryTimer)
1078 releaseRetryTimer = undefined
1079 database.logger.log({
1080 level: LogLevels.info,
1081 message: `Sync has been stopped for ${viewName} into ${trackedTableName}`,
1082 })
1083 abortController.abort()
1084 const trackingDisposal = disposeTrackingAfterAbort()
1085 const pendingLoads = [...pendingDemandLoads]
1086 const pendingTasks = [...pendingDemandCleanups]
1087 const collector: DemandCleanupCollector = {
1088 tasks: pendingTasks.map((promise, order) => ({ order, promise })),
1089 ownedTasks: new Set(pendingTasks),
1090 failures: [],
1091 nextOrder: pendingTasks.length,
1092 }
1093 demandCleanupCollector = collector
1094 for (const demand of demands.values()) {
1095 cleanupDemand(demand)
1096 }
1097 pendingReleases.length = 0
1098
1099 return (async () => {
1100 const ownershipSettlements = await Promise.allSettled([
1101 trackingDisposal,
1102 ...pendingLoads,
1103 ])
1104 const disposalSettlement = ownershipSettlements[0]
1105
1106 let settledTasks = 0
1107 while (settledTasks < collector.tasks.length) {
1108 const tasks = collector.tasks.slice(settledTasks)
1109 settledTasks = collector.tasks.length
1110 const outcomes = await Promise.allSettled(
1111 tasks.map(({ promise }) => promise),
1112 )
1113 for (const [index, outcome] of outcomes.entries()) {
1114 if (outcome.status === `rejected`) {
1115 collector.failures.push({
1116 order: tasks[index]!.order,
1117 error: outcome.reason,
1118 })
1119 }
1120 }
1121 }
1122 throwDemandCleanupFailures(
1123 collector,
1124 disposalSettlement.status === `rejected`
1125 ? [disposalSettlement.reason]
1126 : [],
1127 )
1128 })().finally(() => {
1129 if (demandCleanupCollector === collector) {
1130 demandCleanupCollector = null
1131 }
1132 })
1133 },
1134 loadSubset: trackLoadSubset,
1135 unloadSubset,
1136 }
1137 }
1138 },
1139 // Expose the getSyncMetadata function
1140 getSyncMetadata: undefined,
1141 }
1142
1143 const getKey = (record: OutputType) => asPowerSyncRecord(record).id
1144
1145 const outputConfig: EnhancedPowerSyncCollectionConfig<
1146 TTable,
1147 OutputType,
1148 TSchema
1149 > = {
1150 ...restConfig,
1151 schema,
1152 getKey,
1153 // Syncing should start immediately since we need to monitor the changes for mutations
1154 startSync: true,
1155 syncMode,
1156 sync,
1157 onInsert: async (params) => {
1158 // The transaction here should only ever contain a single insert mutation
1159 return await transactor.applyTransaction(params.transaction)
1160 },
1161 onUpdate: async (params) => {
1162 // The transaction here should only ever contain a single update mutation
1163 return await transactor.applyTransaction(params.transaction)
1164 },
1165 onDelete: async (params) => {
1166 // The transaction here should only ever contain a single delete mutation
1167 return await transactor.applyTransaction(params.transaction)
1168 },
1169 utils: {
1170 getMeta: () => ({
1171 tableName: viewName,
1172 trackedTableName,
1173 metadataIsTracked,
1174 serializeValue: (value) =>
1175 serializeForSQLite<TTable>(value, table, serializer),
1176 }),
1177 },
1178 }
1179 return outputConfig
1180}