Open History to see the last commit
1import { createTransaction, safeRandomUUID } from '@tanstack/db'
2import { NonRetriableError } from '../types'
3import type { PendingMutation, Transaction } from '@tanstack/db'
4import type {
5 CreateOfflineTransactionOptions,
6 OfflineMutationFn,
7 OfflineTransaction as OfflineTransactionType,
8} from '../types'
9
10export class OfflineTransaction {
11 private offlineId: string
12 private mutationFnName: string
13 private autoCommit: boolean
14 private idempotencyKey: string
15 private metadata: Record<string, any>
16 private transaction: Transaction | null = null
17 private persistTransaction: (tx: OfflineTransactionType) => Promise<void>
18 private executor: any // Will be typed properly - reference to OfflineExecutor
19
20 constructor(
21 options: CreateOfflineTransactionOptions,
22 mutationFn: OfflineMutationFn,
23 persistTransaction: (tx: OfflineTransactionType) => Promise<void>,
24 executor: any,
25 ) {
26 this.offlineId = safeRandomUUID()
27 this.mutationFnName = options.mutationFnName
28 this.autoCommit = options.autoCommit ?? true
29 this.idempotencyKey = options.idempotencyKey ?? safeRandomUUID()
30 this.metadata = options.metadata ?? {}
31 this.persistTransaction = persistTransaction
32 this.executor = executor
33 }
34
35 mutate(callback: () => void): Transaction {
36 this.transaction = createTransaction({
37 id: this.offlineId,
38 autoCommit: false,
39 mutationFn: async () => {
40 // This is the blocking mutationFn that waits for the executor
41 // First persist the transaction to the outbox
42 const offlineTransaction: OfflineTransactionType = {
43 id: this.offlineId,
44 mutationFnName: this.mutationFnName,
45 mutations: this.transaction!.mutations,
46 keys: this.extractKeys(this.transaction!.mutations),
47 idempotencyKey: this.idempotencyKey,
48 createdAt: new Date(),
49 retryCount: 0,
50 nextAttemptAt: Date.now(),
51 metadata: this.metadata,
52 spanContext: undefined,
53 version: 1,
54 }
55
56 const completionPromise = this.executor.waitForTransactionCompletion(
57 this.offlineId,
58 )
59
60 try {
61 // Persistence also drives the shared queue. This transaction can finish
62 // before that queue drains; observe both promises from the outset.
63 await Promise.race([
64 this.persistTransaction(offlineTransaction),
65 completionPromise,
66 ])
67 // A queue pause (offline or retry) is not transaction completion.
68 await completionPromise
69 } catch (error) {
70 const normalizedError =
71 error instanceof Error ? error : new Error(String(error))
72 this.executor.rejectTransaction(this.offlineId, normalizedError)
73 throw error
74 }
75
76 return
77 },
78 metadata: this.metadata,
79 })
80
81 this.transaction.mutate(() => {
82 callback()
83 })
84
85 if (this.autoCommit) {
86 // Auto-commit for direct OfflineTransaction usage
87 this.commit().catch((error) => {
88 console.error(`Auto-commit failed:`, error)
89 throw error
90 })
91 }
92
93 return this.transaction
94 }
95
96 async commit(): Promise<Transaction> {
97 if (!this.transaction) {
98 throw new Error(`No mutations to commit. Call mutate() first.`)
99 }
100
101 try {
102 // Commit the TanStack DB transaction
103 // This will trigger the mutationFn which handles persistence and waiting
104 await this.transaction.commit()
105 return this.transaction
106 } catch (error) {
107 // Only rollback for NonRetriableError - other errors should allow retry
108 if (error instanceof NonRetriableError) {
109 this.transaction.rollback()
110 }
111 throw error
112 }
113 }
114
115 rollback(): void {
116 if (this.transaction) {
117 this.transaction.rollback()
118 }
119 }
120
121 private extractKeys(mutations: Array<PendingMutation>): Array<string> {
122 return mutations.map((mutation) => mutation.globalKey)
123 }
124
125 get id(): string {
126 return this.offlineId
127 }
128}