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 // Repeated calls add to the same transaction: one offline transaction is
37 // one transaction, and its id is unique among live transactions.
38 this.transaction ??= createTransaction({
39 id: this.offlineId,
40 autoCommit: false,
41 mutationFn: async () => {
42 // This is the blocking mutationFn that waits for the executor
43 // First persist the transaction to the outbox
44 const offlineTransaction: OfflineTransactionType = {
45 id: this.offlineId,
46 mutationFnName: this.mutationFnName,
47 mutations: this.transaction!.mutations,
48 keys: this.extractKeys(this.transaction!.mutations),
49 idempotencyKey: this.idempotencyKey,
50 createdAt: new Date(),
51 retryCount: 0,
52 nextAttemptAt: Date.now(),
53 metadata: this.metadata,
54 spanContext: undefined,
55 version: 1,
56 }
57
58 const completionPromise = this.executor.waitForTransactionCompletion(
59 this.offlineId,
60 )
61
62 try {
63 // Persistence also drives the shared queue. This transaction can finish
64 // before that queue drains; observe both promises from the outset.
65 await Promise.race([
66 this.persistTransaction(offlineTransaction),
67 completionPromise,
68 ])
69 // A queue pause (offline or retry) is not transaction completion.
70 await completionPromise
71 } catch (error) {
72 const normalizedError =
73 error instanceof Error ? error : new Error(String(error))
74 this.executor.rejectTransaction(this.offlineId, normalizedError)
75 throw error
76 }
77
78 return
79 },
80 metadata: this.metadata,
81 })
82
83 this.transaction.mutate(() => {
84 callback()
85 })
86
87 if (this.autoCommit) {
88 // Auto-commit for direct OfflineTransaction usage
89 this.commit().catch((error) => {
90 console.error(`Auto-commit failed:`, error)
91 throw error
92 })
93 }
94
95 return this.transaction
96 }
97
98 async commit(): Promise<Transaction> {
99 if (!this.transaction) {
100 throw new Error(`No mutations to commit. Call mutate() first.`)
101 }
102
103 try {
104 // Commit the TanStack DB transaction
105 // This will trigger the mutationFn which handles persistence and waiting
106 await this.transaction.commit()
107 return this.transaction
108 } catch (error) {
109 // Only rollback for NonRetriableError - other errors should allow retry
110 if (error instanceof NonRetriableError) {
111 this.transaction.rollback()
112 }
113 throw error
114 }
115 }
116
117 rollback(): void {
118 if (this.transaction) {
119 this.transaction.rollback()
120 }
121 }
122
123 private extractKeys(mutations: Array<PendingMutation>): Array<string> {
124 return mutations.map((mutation) => mutation.globalKey)
125 }
126
127 get id(): string {
128 return this.offlineId
129 }
130}