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