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

powersync.ts

1,132 lines39.1 KB

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