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