Open History to see the last commit
1import { createTransaction } from '@tanstack/db'
2import { DefaultRetryPolicy } from '../retry/RetryPolicy'
3import { NonRetriableError } from '../types'
4import { withNestedSpan } from '../telemetry/tracer'
5import type { KeyScheduler } from './KeyScheduler'
6import type { OutboxManager } from '../outbox/OutboxManager'
7import type {
8 OfflineConfig,
9 OfflineTransaction,
10 TransactionSignaler,
11} from '../types'
12
13const HANDLED_EXECUTION_ERROR = Symbol(`HandledExecutionError`)
14
15export class TransactionExecutor {
16 private scheduler: KeyScheduler
17 private outbox: OutboxManager
18 private config: OfflineConfig
19 private retryPolicy: DefaultRetryPolicy
20 private isExecuting = false
21 private executionPromise: Promise<void> | null = null
22 private offlineExecutor: TransactionSignaler
23 private retryTimer: ReturnType<typeof setTimeout> | null = null
24
25 constructor(
26 scheduler: KeyScheduler,
27 outbox: OutboxManager,
28 config: OfflineConfig,
29 offlineExecutor: TransactionSignaler,
30 ) {
31 this.scheduler = scheduler
32 this.outbox = outbox
33 this.config = config
34 this.retryPolicy = new DefaultRetryPolicy(
35 Number.POSITIVE_INFINITY,
36 config.jitter ?? true,
37 )
38 this.offlineExecutor = offlineExecutor
39 }
40
41 async execute(transaction: OfflineTransaction): Promise<void> {
42 this.scheduler.schedule(transaction)
43 await this.executeAll()
44 }
45
46 async executeAll(): Promise<void> {
47 if (this.isExecuting) {
48 return this.executionPromise!
49 }
50
51 this.isExecuting = true
52 this.executionPromise = this.runExecution()
53
54 try {
55 await this.executionPromise
56 } finally {
57 this.isExecuting = false
58 this.executionPromise = null
59 }
60 }
61
62 private async runExecution(): Promise<void> {
63 while (this.scheduler.getPendingCount() > 0) {
64 if (!this.isOnline()) {
65 break
66 }
67
68 const transaction = this.scheduler.getNext()
69
70 if (!transaction) {
71 break
72 }
73
74 await this.executeTransaction(transaction)
75 }
76
77 // Schedule next retry after execution completes
78 this.scheduleNextRetry()
79 }
80
81 private async executeTransaction(
82 transaction: OfflineTransaction,
83 ): Promise<void> {
84 try {
85 await withNestedSpan(
86 `transaction.execute`,
87 {
88 'transaction.id': transaction.id,
89 'transaction.mutationFnName': transaction.mutationFnName,
90 'transaction.retryCount': transaction.retryCount,
91 'transaction.keyCount': transaction.keys.length,
92 },
93 async (span) => {
94 this.scheduler.markStarted(transaction)
95
96 if (transaction.retryCount > 0) {
97 span.setAttribute(`retry.attempt`, transaction.retryCount)
98 }
99
100 try {
101 const result = await this.runMutationFn(transaction)
102
103 this.scheduler.markCompleted(transaction)
104 await this.outbox.remove(transaction.id)
105
106 span.setAttribute(`result`, `success`)
107 this.offlineExecutor.resolveTransaction(transaction.id, result)
108 } catch (error) {
109 const err =
110 error instanceof Error ? error : new Error(String(error))
111
112 span.setAttribute(`result`, `error`)
113
114 await this.handleError(transaction, err)
115 ;(err as any)[HANDLED_EXECUTION_ERROR] = true
116 throw err
117 }
118 },
119 )
120 } catch (error) {
121 if (
122 error instanceof Error &&
123 (error as any)[HANDLED_EXECUTION_ERROR] === true
124 ) {
125 return
126 }
127
128 throw error
129 }
130 }
131
132 private async runMutationFn(transaction: OfflineTransaction): Promise<void> {
133 const mutationFn = this.config.mutationFns[transaction.mutationFnName]
134
135 if (!mutationFn) {
136 const errorMessage = `Unknown mutation function: ${transaction.mutationFnName}`
137
138 if (this.config.onUnknownMutationFn) {
139 this.config.onUnknownMutationFn(transaction.mutationFnName, transaction)
140 }
141
142 throw new NonRetriableError(errorMessage)
143 }
144
145 // Mutations are already PendingMutation objects with collections attached
146 // from the deserializer, so we can use them directly
147 const transactionWithMutations = {
148 id: transaction.id,
149 mutations: transaction.mutations,
150 metadata: transaction.metadata ?? {},
151 }
152
153 await mutationFn({
154 transaction: transactionWithMutations as any,
155 idempotencyKey: transaction.idempotencyKey,
156 })
157 }
158
159 private async handleError(
160 transaction: OfflineTransaction,
161 error: Error,
162 ): Promise<void> {
163 return withNestedSpan(
164 `transaction.handleError`,
165 {
166 'transaction.id': transaction.id,
167 'error.name': error.name,
168 'error.message': error.message,
169 },
170 async (span) => {
171 const shouldRetry = this.retryPolicy.shouldRetry(
172 error,
173 transaction.retryCount,
174 )
175
176 span.setAttribute(`shouldRetry`, shouldRetry)
177
178 if (!shouldRetry) {
179 this.scheduler.markCompleted(transaction)
180 await this.outbox.remove(transaction.id)
181 console.warn(
182 `Transaction ${transaction.id} failed permanently:`,
183 error,
184 )
185
186 span.setAttribute(`result`, `permanent_failure`)
187 // Signal permanent failure to the waiting transaction
188 this.offlineExecutor.rejectTransaction(transaction.id, error)
189 return
190 }
191
192 const delay = Math.max(
193 0,
194 this.retryPolicy.calculateDelay(transaction.retryCount),
195 )
196 const updatedTransaction: OfflineTransaction = {
197 ...transaction,
198 retryCount: transaction.retryCount + 1,
199 nextAttemptAt: Date.now() + delay,
200 lastError: {
201 name: error.name,
202 message: error.message,
203 stack: error.stack,
204 },
205 }
206
207 span.setAttribute(`retryDelay`, delay)
208 span.setAttribute(`nextRetryCount`, updatedTransaction.retryCount)
209
210 this.scheduler.markFailed(transaction)
211 this.scheduler.updateTransaction(updatedTransaction)
212
213 try {
214 await this.outbox.update(transaction.id, updatedTransaction)
215 span.setAttribute(`result`, `scheduled_retry`)
216 } catch (persistError) {
217 span.recordException(persistError as Error)
218 span.setAttribute(`result`, `persist_failed`)
219 throw persistError
220 }
221
222 // Schedule retry timer
223 this.scheduleNextRetry()
224 },
225 )
226 }
227
228 async loadPendingTransactions(): Promise<void> {
229 const transactions = await this.outbox.getAll()
230 let filteredTransactions = transactions
231
232 if (this.config.beforeRetry) {
233 filteredTransactions = this.config.beforeRetry(transactions)
234 }
235
236 for (const transaction of filteredTransactions) {
237 this.scheduler.schedule(transaction)
238 }
239
240 // Restore optimistic state for loaded transactions
241 // This ensures the UI shows the optimistic data while transactions are pending
242 this.restoreOptimisticState(filteredTransactions)
243
244 // Reset retry delays for all loaded transactions so they can run immediately
245 this.resetRetryDelays()
246
247 // Schedule retry timer for loaded transactions
248 this.scheduleNextRetry()
249
250 const removedTransactions = transactions.filter(
251 (tx) => !filteredTransactions.some((filtered) => filtered.id === tx.id),
252 )
253
254 if (removedTransactions.length > 0) {
255 await this.outbox.removeMany(removedTransactions.map((tx) => tx.id))
256 }
257 }
258
259 /**
260 * Restore optimistic state from loaded transactions.
261 * Creates internal transactions to hold the mutations so the collection's
262 * state manager can show optimistic data while waiting for sync.
263 */
264 private restoreOptimisticState(
265 transactions: Array<OfflineTransaction>,
266 ): void {
267 for (const offlineTx of transactions) {
268 if (offlineTx.mutations.length === 0) {
269 continue
270 }
271
272 try {
273 // Create a restoration transaction that holds mutations for optimistic state display.
274 // It will never commit - the real mutation is handled by the offline executor.
275 const restorationTx = createTransaction({
276 id: offlineTx.id,
277 autoCommit: false,
278 mutationFn: async () => {},
279 })
280
281 // Prevent unhandled promise rejection when cleanup calls rollback()
282 // We don't care about this promise - it's just for holding mutations
283 restorationTx.isPersisted.promise.catch(() => {
284 // Intentionally ignored - restoration transactions are cleaned up
285 // via cleanupRestorationTransaction, not through normal commit flow
286 })
287
288 restorationTx.applyMutations(offlineTx.mutations)
289
290 // Register with each affected collection's state manager
291 const touchedCollections = new Set<string>()
292 for (const mutation of offlineTx.mutations) {
293 // Defensive check for corrupted deserialized data
294 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
295 if (!mutation.collection) {
296 continue
297 }
298 const collectionId = mutation.collection.id
299 if (touchedCollections.has(collectionId)) {
300 continue
301 }
302 touchedCollections.add(collectionId)
303
304 mutation.collection._state.transactions.set(
305 restorationTx.id,
306 restorationTx,
307 )
308 mutation.collection._state.recomputeOptimisticState(true)
309 }
310
311 this.offlineExecutor.registerRestorationTransaction(
312 offlineTx.id,
313 restorationTx,
314 )
315 } catch (error) {
316 console.warn(
317 `Failed to restore optimistic state for transaction ${offlineTx.id}:`,
318 error,
319 )
320 }
321 }
322 }
323
324 clear(): void {
325 this.scheduler.clear()
326 this.clearRetryTimer()
327 }
328
329 getPendingCount(): number {
330 return this.scheduler.getPendingCount()
331 }
332
333 private scheduleNextRetry(): void {
334 // Clear existing timer
335 this.clearRetryTimer()
336
337 if (!this.isOnline()) {
338 return
339 }
340
341 // Find the earliest retry time among pending transactions
342 const earliestRetryTime = this.getEarliestRetryTime()
343
344 if (earliestRetryTime === null) {
345 return // No transactions pending retry
346 }
347
348 const delay = Math.max(0, earliestRetryTime - Date.now())
349
350 this.retryTimer = setTimeout(() => {
351 this.executeAll().catch((error) => {
352 console.warn(`Failed to execute retry batch:`, error)
353 })
354 }, delay)
355 }
356
357 private getEarliestRetryTime(): number | null {
358 const allTransactions = this.scheduler.getAllPendingTransactions()
359
360 if (allTransactions.length === 0) {
361 return null
362 }
363
364 return Math.min(...allTransactions.map((tx) => tx.nextAttemptAt))
365 }
366
367 private clearRetryTimer(): void {
368 if (this.retryTimer) {
369 clearTimeout(this.retryTimer)
370 this.retryTimer = null
371 }
372 }
373
374 private isOnline(): boolean {
375 return this.offlineExecutor.isOnline()
376 }
377
378 getRunningCount(): number {
379 return this.scheduler.getRunningCount()
380 }
381
382 resetRetryDelays(): void {
383 const allTransactions = this.scheduler.getAllPendingTransactions()
384 const updatedTransactions = allTransactions.map((transaction) => ({
385 ...transaction,
386 nextAttemptAt: Date.now(),
387 }))
388
389 this.scheduler.updateTransactions(updatedTransactions)
390 }
391}