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

manual-sync.ts

353 lines10.5 KB

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