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

powersync.ts

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