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. A direct write is not a
231 // snapshot, so during a reload it applies to the kept rows.
232 ctx.begin()
233
234 for (const op of normalized) {
235 switch (op.type) {
236 case `insert`: {
237 const resolved = ctx.collection.validateData(op.data, `insert`)
238 ctx.write({
239 type: `insert`,
240 value: resolved,
241 })
242 break
243 }
244 case `update`: {
245 const currentItem = ctx.collection._state.getAcceptedSyncedRow(op.key)!
246 const updatedItem = {
247 ...currentItem,
248 ...op.data,
249 }
250 const resolved = ctx.collection.validateData(
251 updatedItem,
252 `update`,
253 op.key,
254 )
255 ctx.write({
256 type: `update`,
257 value: resolved,
258 })
259 break
260 }
261 case `delete`: {
262 const currentItem = ctx.collection._state.getAcceptedSyncedRow(op.key)!
263 ctx.write({
264 type: `delete`,
265 value: currentItem,
266 })
267 break
268 }
269 case `upsert`: {
270 const existsInSyncedStore =
271 ctx.collection._state.getAcceptedSyncedRow(op.key) !== undefined
272 const resolved = ctx.collection.validateData(
273 op.data,
274 existsInSyncedStore ? `update` : `insert`,
275 op.key,
276 )
277 if (existsInSyncedStore) {
278 ctx.write({
279 type: `update`,
280 value: resolved,
281 })
282 } else {
283 ctx.write({
284 type: `insert`,
285 value: resolved,
286 })
287 }
288 break
289 }
290 }
291 }
292
293 const applied = ctx.commit()
294
295 // A handler awaits this write, so it resolves once the transaction is
296 // accepted, including any durable step; while the handler's own mutation
297 // persists, the rows become visible when that mutation settles. The Query
298 // cache holds accepted rows.
299 const accepted = whenSyncAccepted(applied)
300 const updateCache = () => {
301 const getItems = (keys?: Array<TKey>): Array<TRow> =>
302 keys
303 ? keys
304 .map((key) => ctx.collection._state.getAcceptedSyncedRow(key))
305 .filter((row): row is TRow => row !== undefined)
306 : Array.from(
307 ctx.collection._state.acceptedSyncedEntries(),
308 ([, row]) => row,
309 )
310 if (ctx.updateCacheData)
311 ctx.updateCacheData(
312 getItems,
313 normalized.map((op) => op.key),
314 position,
315 )
316 else ctx.queryClient.setQueryData(ctx.queryKey, getItems())
317 }
318 if (accepted === true) updateCache()
319 const completion = Promise.resolve(accepted).then(() => {
320 if (accepted !== true) updateCache()
321 })
322 void completion.catch(() => undefined)
323 return completion
324}
325
326// Factory function to create write utils
327export function createWriteUtils<
328 TRow extends object,
329 TKey extends string | number = string | number,
330 TInsertInput extends object = TRow,
331>(getContext: () => SyncContext<TRow, TKey> | null) {
332 function ensureContext(): SyncContext<TRow, TKey> {
333 const context = getContext()
334 if (!context) {
335 throw new SyncNotInitializedError()
336 }
337 return context
338 }
339
340 function write(operation: SyncOperation<TRow, TKey, TInsertInput>) {
341 const ctx = ensureContext()
342 const batchContext = activeBatchContexts.get(ctx)
343 if (batchContext) {
344 batchContext.operations.push(operation)
345 return batchContext.completion
346 }
347 const completion = performWriteOperations(
348 operation,
349 ctx,
350 () => getContext() === ctx,
351 )
352 writeCompletionPromises.add(completion)
353 return completion
354 }
355
356 return {
357 writeInsert(data: TInsertInput | Array<TInsertInput>) {
358 return write({ type: `insert`, data })
359 },
360
361 writeUpdate(data: Partial<TRow> | Array<Partial<TRow>>) {
362 return write({ type: `update`, data })
363 },
364
365 writeDelete(key: TKey | Array<TKey>) {
366 return write({ type: `delete`, key })
367 },
368
369 writeUpsert(data: Partial<TRow> | Array<Partial<TRow>>) {
370 return write({ type: `upsert`, data })
371 },
372
373 writeBatch(callback: () => void) {
374 const ctx = ensureContext()
375
376 // Check if we're already in a batch (nested batch)
377 const existingBatch = activeBatchContexts.get(ctx)
378 if (existingBatch) {
379 throw new Error(
380 `Cannot nest writeBatch calls. Complete the current batch before starting a new one.`,
381 )
382 }
383
384 let resolveBatch!: (completion: Promise<void>) => void
385 let rejectBatch!: (reason: unknown) => void
386 const completion = new Promise<void>((resolve, reject) => {
387 resolveBatch = resolve
388 rejectBatch = reject
389 })
390 writeCompletionPromises.add(completion)
391 void completion.catch(() => undefined)
392
393 // Set up the batch context for this specific collection
394 const batchContext = {
395 operations: [] as Array<SyncOperation<TRow, TKey, TInsertInput>>,
396 completion,
397 }
398 activeBatchContexts.set(ctx, batchContext)
399
400 try {
401 // Execute the callback - any write operations will be collected
402 const result: unknown = callback()
403
404 // A direct write in another collection may be returned incidentally.
405 if (
406 result !== null &&
407 typeof result === `object` &&
408 `then` in result &&
409 typeof result.then === `function` &&
410 !writeCompletionPromises.has(result)
411 ) {
412 // Rejecting the batch can also reject an async callback awaiting it.
413 void Promise.resolve(result).catch(() => undefined)
414 throw new Error(
415 `writeBatch does not support async callbacks. The callback must be synchronous.`,
416 )
417 }
418
419 // A subscriber called during commit starts a separate write or batch.
420 activeBatchContexts.delete(ctx)
421
422 // Perform all collected operations
423 resolveBatch(
424 batchContext.operations.length > 0
425 ? performWriteOperations(
426 batchContext.operations,
427 ctx,
428 () => getContext() === ctx,
429 )
430 : Promise.resolve(),
431 )
432 return completion
433 } catch (error) {
434 rejectBatch(error)
435 throw error
436 } finally {
437 if (activeBatchContexts.get(ctx) === batchContext) {
438 activeBatchContexts.delete(ctx)
439 }
440 }
441 },
442 }
443}