Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

OfflineTransaction.ts

142 lines5.0 KB

1import { createTransaction, safeRandomUUID } from '@tanstack/db'
2import type { PendingMutation, Transaction } from '@tanstack/db'
3import type {
4 CreateOfflineTransactionOptions,
5 OfflineMutationFn,
6 OfflineTransaction as OfflineTransactionType,
7} from '../types'
8​
9export class OfflineTransaction {
10 private offlineId: string
11 private mutationFnName: string
12 private autoCommit: boolean | undefined
13 private idempotencyKey: string
14 private metadata: Record<string, any>
15 private transaction: Transaction | null = null
16 /** The mutation function ran, so the executor settles the waiter. */
17 private persisting = false
18 private persistTransaction: (tx: OfflineTransactionType) => Promise<void>
19 private executor: any // Will be typed properly - reference to OfflineExecutor
20​
21 constructor(
22 options: CreateOfflineTransactionOptions,
23 mutationFn: OfflineMutationFn,
24 persistTransaction: (tx: OfflineTransactionType) => Promise<void>,
25 executor: any,
26 ) {
27 this.offlineId = safeRandomUUID()
28 this.mutationFnName = options.mutationFnName
29 // The TanStack DB transaction applies the default.
30 this.autoCommit = options.autoCommit
31 this.idempotencyKey = options.idempotencyKey ?? safeRandomUUID()
32 this.metadata = options.metadata ?? {}
33 this.persistTransaction = persistTransaction
34 this.executor = executor
35 }
36​
37 mutate(callback: () => void): Transaction {
38 // One offline transaction is one transaction, and its id is unique among
39 // live transactions. Repeated calls add to it while it is pending. With
40 // autoCommit, it commits after this callback and reports a failure
41 // through `when('settled')`, so a later call throws: it is no longer pending.
42 if (!this.transaction) {
43 this.transaction = createTransaction({
44 id: this.offlineId,
45 autoCommit: this.autoCommit,
46 mutationFn: async () => {
47 this.persisting = true
48 // This is the blocking mutationFn that waits for the executor
49 // First persist the transaction to the outbox
50 const offlineTransaction: OfflineTransactionType = {
51 id: this.offlineId,
52 mutationFnName: this.mutationFnName,
53 mutations: this.transaction!.mutations,
54 keys: this.extractKeys(this.transaction!.mutations),
55 idempotencyKey: this.idempotencyKey,
56 createdAt: new Date(),
57 retryCount: 0,
58 nextAttemptAt: Date.now(),
59 metadata: this.metadata,
60 spanContext: undefined,
61 version: 1,
62 }
63​
64 const completionPromise = this.executor.waitForTransactionCompletion(
65 this.offlineId,
66 )
67​
68 try {
69 // Persistence also drives the shared queue. This transaction can finish
70 // before that queue drains; observe both promises from the outset.
71 await Promise.race([
72 this.persistTransaction(offlineTransaction),
73 completionPromise,
74 ])
75 // A queue pause (offline or retry) is not transaction completion.
76 await completionPromise
77 } catch (error) {
78 const normalizedError =
79 error instanceof Error ? error : new Error(String(error))
80 this.executor.rejectTransaction(this.offlineId, normalizedError)
81 throw error
82 }
83​
84 return
85 },
86 metadata: this.metadata,
87 })
88 // A transaction without mutations completes, and one rolled back before
89 // it commits fails, without its mutation function, so the executor never
90 // settles its waiter. Settle that waiter here with the same outcome. Once
91 // the mutation function runs, only the executor settles it.
92 void this.transaction.when(`settled`).then(
93 () => {
94 if (!this.persisting)
95 this.executor.resolveTransaction(this.offlineId, undefined)
96 },
97 (error: unknown) => {
98 if (!this.persisting)
99 this.executor.rejectTransaction(
100 this.offlineId,
101 error instanceof Error
102 ? error
103 : new Error(`Offline transaction was rolled back`),
104 )
105 },
106 )
107 }
108​
109 this.transaction.mutate(() => {
110 callback()
111 })
112​
113 return this.transaction
114 }
115​
116 async commit(): Promise<Transaction> {
117 if (!this.transaction) {
118 throw new Error(`No mutations to commit. Call mutate() first.`)
119 }
120​
121 // The mutationFn persists the transaction and waits for the executor. A
122 // commit that rejects has already rolled the transaction back. A sibling's
123 // failure can also roll it back while it waits, and then commit() resolves,
124 // so `when('settled')` is the receipt.
125 await this.transaction.commit()
126 return this.transaction
127 }
128​
129 rollback(): void {
130 if (this.transaction) {
131 this.transaction.rollback()
132 }
133 }
134​
135 private extractKeys(mutations: Array<PendingMutation>): Array<string> {
136 return mutations.map((mutation) => mutation.globalKey)
137 }
138​
139 get id(): string {
140 return this.offlineId
141 }