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

manual-sync.ts

424 lines12.8 KB

1import {
2 DuplicateKeySyncError,
3 SyncTransactionAbortedError,
4 whenSyncAccepted,
5} from '@tanstack/db'
6import {
7 DeleteOperationItemNotFoundError,
8 DuplicateKeyInBatchError,
9 SyncNotInitializedError,
10 UpdateOperationItemNotFoundError,
11} from './errors'
12import type { QueryClient } from '@tanstack/query-core'
13import type {
14 ChangeMessage,
15 Collection,
16 SyncAppliedReceipt,
17} from '@tanstack/db'
18​
19// Track active batch operations per context to prevent cross-collection contamination
20const activeBatchContexts = new WeakMap<
21 SyncContext<any, any>,
22 {
23 operations: Array<SyncOperation<any, any, any>>
24 completion: Promise<void>
25 }
26>()
27const writeCompletionPromises = new WeakSet<object>()
28​
29// Types for sync operations
30export type SyncOperation<
31 TRow extends object,
32 TKey extends string | number = string | number,
33 TInsertInput extends object = TRow,
34> =
35 | { type: `insert`; data: TInsertInput | Array<TInsertInput> }
36 | { type: `update`; data: Partial<TRow> | Array<Partial<TRow>> }
37 | { type: `delete`; key: TKey | Array<TKey> }
38 | { type: `upsert`; data: Partial<TRow> | Array<Partial<TRow>> }
39​
40export interface SyncContext<
41 TRow extends object,
42 TKey extends string | number = string | number,
43> {
44 collection: Collection<TRow>
45 queryClient: QueryClient
46 queryKey: Array<unknown>
47 getKey: (item: TRow) => TKey
48 begin: () => void
49 write: (message: Omit<ChangeMessage<TRow>, `key`>) => void
50 commit: () => SyncAppliedReceipt
51 /**
52 * Optional function to update the query cache with the latest synced data.
53 * Handles both direct array caches and wrapped response formats (when `select` is used).
54 * If not provided, falls back to directly setting the cache with the raw array.
55 */
56 updateCacheData?: (getItems: () => Array<TRow>) => void
57 /**
58 * Gives a direct write its position when it is called. A fetch that starts
59 * later counts as newer than the write.
60 */
61 reserveDirectWrite?: () => number
62 /**
63 * Gives an accepted write's keys precedence from its reserved position.
64 * A rejected write never calls this.
65 */
66 claimDirectWriteKeys?: (keys: Array<TKey>, position: number) => void
67 /** Records a write that waits for earlier commits until it settles. */
68 noteWaitingDirectWrite?: (waiting: Promise<void>) => void
69 /** Settles once every earlier commit is accepted, or undefined if it is. */
70 earlierCommits?: () => Promise<void> | undefined
72​
73interface NormalizedOperation<
74 TRow extends object,
75 TKey extends string | number = string | number,
76> {
77 type: `insert` | `update` | `delete` | `upsert`
78 key: TKey
79 data?: TRow | Partial<TRow>
81​
82// Normalize operations into a consistent format
83function normalizeOperations<
84 TRow extends object,
85 TKey extends string | number = string | number,
86 TInsertInput extends object = TRow,
87>(
88 ops:
89 | SyncOperation<TRow, TKey, TInsertInput>
90 | Array<SyncOperation<TRow, TKey, TInsertInput>>,
91 ctx: SyncContext<TRow, TKey>,
92): Array<NormalizedOperation<TRow, TKey>> {
93 const operations = Array.isArray(ops) ? ops : [ops]
94 const normalized: Array<NormalizedOperation<TRow, TKey>> = []
95​
96 for (const op of operations) {
97 if (op.type === `delete`) {
98 const keys = Array.isArray(op.key) ? op.key : [op.key]
99 for (const key of keys) {
100 normalized.push({ type: `delete`, key })
101 }
102 } else {
103 const items = Array.isArray(op.data) ? op.data : [op.data]
104 for (const item of items) {
105 let key: TKey
106 if (op.type === `update`) {
107 // For updates, we need to get the key from the partial data
108 key = ctx.getKey(item as TRow)
109 } else {
110 // For insert/upsert, validate and resolve the full item first
111 const resolved = ctx.collection.validateData(
112 item,
113 op.type === `upsert` ? `insert` : op.type,
114 )
115 key = ctx.getKey(resolved)
116 }
117 normalized.push({ type: op.type, key, data: item })
118 }
119 }
120 }
121​
122 return normalized
124​
125// Validate operations before executing
126function validateOperations<
127 TRow extends object,
128 TKey extends string | number = string | number,
129>(
130 operations: Array<NormalizedOperation<TRow, TKey>>,
131 ctx: SyncContext<TRow, TKey>,
132): void {
133 const seenKeys = new Set<TKey>()
134​
135 for (const op of operations) {
136 // Check for duplicate keys within the batch
137 if (seenKeys.has(op.key)) {
138 throw new DuplicateKeyInBatchError(op.key)
139 }
140 seenKeys.add(op.key)
141​
142 // Validate operation-specific requirements
143 // Validate against accepted synced rows, not the optimistic view, so a
144 // write works while its row is optimistically modified or queued.
145 if (op.type === `insert`) {
146 // Persistence stores a sync insert as an update, so check here.
147 if (ctx.collection._state.getAcceptedSyncedRow(op.key)) {
148 throw new DuplicateKeySyncError(op.key, ctx.collection.id)
149 }
150 } else if (op.type === `update`) {
151 if (!ctx.collection._state.getAcceptedSyncedRow(op.key)) {
152 throw new UpdateOperationItemNotFoundError(op.key)
153 }
154 } else if (op.type === `delete`) {
155 if (!ctx.collection._state.getAcceptedSyncedRow(op.key)) {
156 throw new DeleteOperationItemNotFoundError(op.key)
157 }
158 }
159 }
161​
162// Execute a batch of operations
163export function performWriteOperations<
164 TRow extends object,
165 TKey extends string | number = string | number,
166 TInsertInput extends object = TRow,
167>(
168 operations:
169 | SyncOperation<TRow, TKey, TInsertInput>
170 | Array<SyncOperation<TRow, TKey, TInsertInput>>,
171 ctx: SyncContext<TRow, TKey>,
172 isCurrent: () => boolean,
173): Promise<void> {
174 let normalized: Array<NormalizedOperation<TRow, TKey>>
175 try {
176 normalized = normalizeOperations(operations, ctx)
177 } catch (error) {
178 return Promise.reject(error)
179 }
180 const position = ctx.reserveDirectWrite?.() ?? 0
181 // Validate against, and apply on top of, every earlier commit. A commit
182 // can wait for a persistence lock before it is accepted, so the write waits
183 // too. A validation error rejects the returned promise.
184 const earlier = ctx.earlierCommits?.()
185 if (!earlier) {
186 try {
187 return applyWriteOperations(normalized, ctx, position)
188 } catch (error) {
189 return Promise.reject(error)
190 }
191 }
192 const written = earlier.then(() => {
193 // Cleanup retired this sync run while the write waited.
194 if (!isCurrent()) throw new SyncTransactionAbortedError()
195 return applyWriteOperations(normalized, ctx, position)
196 })
197 ctx.noteWaitingDirectWrite?.(
198 written.then(
199 () => undefined,
200 () => undefined,
201 ),
202 )
203 return written
205​
206function applyWriteOperations<
207 TRow extends object,
208 TKey extends string | number = string | number,
209>(
210 normalized: Array<NormalizedOperation<TRow, TKey>>,
211 ctx: SyncContext<TRow, TKey>,
212 position: number,
213): Promise<void> {
214 validateOperations(normalized, ctx)
215 ctx.claimDirectWriteKeys?.(
216 normalized.map((op) => op.key),
217 position,
218 )
219​
220 // While an optimistic transaction persists, this sync transaction waits
221 // and applies when that transaction settles.
222 ctx.begin()
223​
224 for (const op of normalized) {
225 switch (op.type) {
226 case `insert`: {
227 const resolved = ctx.collection.validateData(op.data, `insert`)
228 ctx.write({
229 type: `insert`,
230 value: resolved,
231 })
232 break
233 }
234 case `update`: {
235 const currentItem = ctx.collection._state.getAcceptedSyncedRow(op.key)!
236 const updatedItem = {
237 ...currentItem,
238 ...op.data,
239 }
240 const resolved = ctx.collection.validateData(
241 updatedItem,
242 `update`,
243 op.key,
244 )
245 ctx.write({
246 type: `update`,
247 value: resolved,
248 })
249 break
250 }
251 case `delete`: {
252 const currentItem = ctx.collection._state.getAcceptedSyncedRow(op.key)!
253 ctx.write({
254 type: `delete`,
255 value: currentItem,
256 })
257 break
258 }
259 case `upsert`: {
260 const existsInSyncedStore =
261 ctx.collection._state.getAcceptedSyncedRow(op.key) !== undefined
262 const resolved = ctx.collection.validateData(
263 op.data,
264 existsInSyncedStore ? `update` : `insert`,
265 op.key,
266 )
267 if (existsInSyncedStore) {
268 ctx.write({
269 type: `update`,
270 value: resolved,
271 })
272 } else {
273 ctx.write({
274 type: `insert`,
275 value: resolved,
276 })
277 }
278 break
279 }
280 }
281 }
282​
283 const applied = ctx.commit()
284​
285 // A handler awaits this write, so it resolves once the transaction is
286 // accepted, including any durable step; while the handler's own mutation
287 // persists, the rows become visible when that mutation settles. The Query
288 // cache holds accepted rows.
289 const accepted = whenSyncAccepted(applied)
290 const updateCache = () => {
291 const getItems = () =>
292 Array.from(
293 ctx.collection._state.acceptedSyncedEntries(),
294 ([, row]) => row,
295 )
296 if (ctx.updateCacheData) ctx.updateCacheData(getItems)
297 else ctx.queryClient.setQueryData(ctx.queryKey, getItems())
298 }
299 if (accepted === true) updateCache()
300 const completion = Promise.resolve(accepted).then(() => {
301 if (accepted !== true) updateCache()
302 })
303 void completion.catch(() => undefined)
304 return completion
306​
307// Factory function to create write utils
308export function createWriteUtils<
309 TRow extends object,
310 TKey extends string | number = string | number,
311 TInsertInput extends object = TRow,
312>(getContext: () => SyncContext<TRow, TKey> | null) {
313 function ensureContext(): SyncContext<TRow, TKey> {
314 const context = getContext()
315 if (!context) {
316 throw new SyncNotInitializedError()
317 }
318 return context
319 }
320​
321 function write(operation: SyncOperation<TRow, TKey, TInsertInput>) {
322 const ctx = ensureContext()
323 const batchContext = activeBatchContexts.get(ctx)
324 if (batchContext) {
325 batchContext.operations.push(operation)
326 return batchContext.completion
327 }
328 const completion = performWriteOperations(
329 operation,
330 ctx,
331 () => getContext() === ctx,
332 )
333 writeCompletionPromises.add(completion)
334 return completion
335 }
336​
337 return {
338 writeInsert(data: TInsertInput | Array<TInsertInput>) {
339 return write({ type: `insert`, data })
340 },
341​
342 writeUpdate(data: Partial<TRow> | Array<Partial<TRow>>) {
343 return write({ type: `update`, data })
344 },
345​
346 writeDelete(key: TKey | Array<TKey>) {
347 return write({ type: `delete`, key })
348 },
349​
350 writeUpsert(data: Partial<TRow> | Array<Partial<TRow>>) {
351 return write({ type: `upsert`, data })
352 },
353​
354 writeBatch(callback: () => void) {
355 const ctx = ensureContext()
356​
357 // Check if we're already in a batch (nested batch)
358 const existingBatch = activeBatchContexts.get(ctx)
359 if (existingBatch) {
360 throw new Error(
361 `Cannot nest writeBatch calls. Complete the current batch before starting a new one.`,
362 )
363 }
364​
365 let resolveBatch!: (completion: Promise<void>) => void
366 let rejectBatch!: (reason: unknown) => void
367 const completion = new Promise<void>((resolve, reject) => {
368 resolveBatch = resolve
369 rejectBatch = reject
370 })
371 writeCompletionPromises.add(completion)
372 void completion.catch(() => undefined)
373​
374 // Set up the batch context for this specific collection
375 const batchContext = {
376 operations: [] as Array<SyncOperation<TRow, TKey, TInsertInput>>,
377 completion,
378 }
379 activeBatchContexts.set(ctx, batchContext)
380​
381 try {
382 // Execute the callback - any write operations will be collected
383 const result: unknown = callback()
384​
385 // A direct write in another collection may be returned incidentally.
386 if (
387 result !== null &&
388 typeof result === `object` &&
389 `then` in result &&
390 typeof result.then === `function` &&
391 !writeCompletionPromises.has(result)
392 ) {
393 // Rejecting the batch can also reject an async callback awaiting it.
394 void Promise.resolve(result).catch(() => undefined)
395 throw new Error(
396 `writeBatch does not support async callbacks. The callback must be synchronous.`,
397 )
398 }
399​
400 // A subscriber called during commit starts a separate write or batch.
401 activeBatchContexts.delete(ctx)
402​
403 // Perform all collected operations
404 resolveBatch(
405 batchContext.operations.length > 0
406 ? performWriteOperations(
407 batchContext.operations,
408 ctx,
409 () => getContext() === ctx,
410 )
411 : Promise.resolve(),
412 )
413 return completion
414 } catch (error) {
415 rejectBatch(error)
416 throw error
417 } finally {
418 if (activeBatchContexts.get(ctx) === batchContext) {
419 activeBatchContexts.delete(ctx)
420 }
421 }
422 },
423 }