Open History to see the last commit
1import { Store } from "@tanstack/store"
2import { SortedMap } from "./SortedMap"
3import { createDeferred } from "./deferred"
4import type { TransactionStore } from "./TransactionStore"
5import type { Collection } from "./collection"
6import type {
7 MutationStrategy,
8 PendingMutation,
9 Transaction,
10 TransactionState,
11} from "./types"
12
13// Singleton instance of TransactionManager with type map
14
15const transactionManagerInstances = new Map<string, TransactionManager<any>>()
16
17/**
18 * Get the global TransactionManager instance for a specific type
19 * Creates a new instance if one doesn't exist for that type
20 *
21 * @param store - The transaction store for persistence
22 * @param collection - The collection this manager is associated with
23 * @returns The TransactionManager instance
24 */
25export function getTransactionManager<
26 T extends object = Record<string, unknown>,
27>(store?: TransactionStore, collection?: Collection<T>): TransactionManager<T> {
28 if (!store || !collection) {
29 throw new Error(
30 `TransactionManager not initialized. You must provide store and collection parameters on first call.`
31 )
32 }
33
34 if (!transactionManagerInstances.has(collection.id)) {
35 transactionManagerInstances.set(
36 collection.id,
37 new TransactionManager(store, collection)
38 )
39 }
40 return transactionManagerInstances.get(collection.id) as TransactionManager<T>
41}
42
43export class TransactionManager<T extends object = Record<string, unknown>> {
44 private store: TransactionStore
45 private collection: Collection<T>
46 public transactions: Store<SortedMap<string, Transaction>>
47
48 /**
49 * Creates a new TransactionManager instance
50 *
51 * @param store - The transaction store for persistence
52 * @param collection - The collection this manager is associated with
53 */
54 constructor(store: TransactionStore, collection: Collection<T>) {
55 this.store = store
56 this.collection = collection
57 // Initialize store with SortedMap that sorts by createdAt
58 this.transactions = new Store(
59 new SortedMap<string, Transaction>(
60 (a, b) => a.createdAt.getTime() - b.createdAt.getTime()
61 )
62 )
63
64 // Load transactions from store on init
65 this.store.getTransactions().then((transactions) => {
66 transactions.forEach((tx) => {
67 this.transactions.setState((sortedMap) => {
68 sortedMap.set(tx.id, tx as Transaction)
69 return sortedMap
70 })
71 })
72 })
73 }
74
75 /**
76 * Retrieves a transaction by its ID
77 *
78 * @param id - The unique identifier of the transaction
79 * @returns The transaction if found, undefined otherwise
80 */
81 getTransaction(id: string): Transaction | undefined {
82 const transaction = this.transactions.state.get(id)
83
84 return transaction
85 }
86
87 private setTransaction(transaction: Transaction): void {
88 this.transactions.setState((sortedMap) => {
89 sortedMap.set(transaction.id, transaction)
90 return sortedMap
91 })
92
93 this.collection.commitPendingTransactions()
94 }
95
96 /**
97 * Create a live transaction reference that always returns the latest values
98 * @param id Transaction ID
99 * @returns A proxy that always gets the latest transaction values
100 */
101 createLiveTransactionReference(id: string): Transaction {
102 const self: TransactionManager<T> = this
103 return new Proxy(
104 {
105 // Implement the toObject method directly on the proxy target
106 toObject() {
107 const transaction = self.getTransaction(id)
108 if (!transaction) {
109 throw new Error(`Transaction with id ${id} not found`)
110 }
111
112 // Create a shallow copy of the transaction without the toObject method
113
114 const { toObject, ...transactionData } = transaction
115 return { ...transactionData }
116 },
117 } as Transaction,
118 {
119 get(target, prop) {
120 // If the property is toObject, return the method from the target
121 if (prop === `toObject`) {
122 return target.toObject
123 }
124
125 // Otherwise, get the latest transaction data
126 const latest = self.getTransaction(id)
127 if (!latest) {
128 throw new Error(`Transaction with id ${id} not found`)
129 }
130 return latest[prop as keyof Transaction]
131 },
132 set() {
133 // We don't allow direct setting of properties on the transaction
134 console.warn(
135 `Direct modification of transaction properties is not allowed. Use setTransactionState if updating the state`
136 )
137 return true
138 },
139 }
140 )
141 }
142
143 /**
144 * Applies a transaction with the given mutations using the specified strategy
145 *
146 * @param mutations - Array of pending mutations to apply
147 * @param strategy - Strategy to use when applying the transaction
148 * @returns A live reference to the created or updated transaction
149 */
150 applyTransaction(
151 mutations: Array<PendingMutation>,
152 strategy: MutationStrategy
153 ): Transaction {
154 // See if there's an existing overlapping queued mutation.
155 const mutationKeys = mutations.map((m) => m.key)
156 let transaction: Transaction | undefined = Array.from(
157 this.transactions.state.values()
158 ).filter(
159 (t) =>
160 t.state === `queued` &&
161 t.mutations.some((m) => mutationKeys.includes(m.key))
162 )[0]
163
164 // If there's a transaction, overwrite matching mutations.
165 if (transaction) {
166 for (const newMutation of mutations) {
167 const existingIndex = transaction.mutations.findIndex(
168 (m) => m.key === newMutation.key
169 )
170
171 if (existingIndex >= 0) {
172 // Replace existing mutation
173 // TODO this won't work for cases where different mutations modify different keys
174 transaction.mutations[existingIndex] = newMutation
175 } else {
176 // Insert new mutation
177 transaction.mutations.push(newMutation)
178 }
179 }
180 } else {
181 // Create a new transaction if none exists
182 transaction = {
183 id: crypto.randomUUID(),
184 state: `pending`,
185 createdAt: new Date(),
186 updatedAt: new Date(),
187 mutations,
188 metadata: {},
189 strategy,
190 isSynced: createDeferred(),
191 isPersisted: createDeferred(),
192 } as Transaction
193 }
194
195 // For ordered transactions, check if we need to queue behind another transaction
196 if (strategy.type === `ordered`) {
197 const activeTransactions = this.getActiveTransactions()
198 const orderedTransactions = activeTransactions.filter(
199 (tx) => tx.strategy.type === `ordered` && tx.state !== `queued`
200 )
201
202 // Find any active transaction that has overlapping mutations
203 const conflictingTransaction = orderedTransactions.find((tx) =>
204 this.hasOverlappingMutations(tx.mutations, mutations)
205 )
206
207 if (conflictingTransaction) {
208 transaction.state = `queued`
209 transaction.queuedBehind = conflictingTransaction.id
210 } else {
211 this.setTransaction(transaction)
212 this.processTransaction(transaction.id)
213 }
214 }
215
216 this.setTransaction(transaction)
217 // Persist async
218 this.store.putTransaction(transaction)
219
220 // Return a live reference to the transaction
221 return this.createLiveTransactionReference(transaction.id)
222 }
223
224 /**
225 * Process a transaction through persist and awaitSync
226 *
227 * @param transactionId - The ID of the transaction to process
228 * @private
229 */
230 private processTransaction(transactionId: string): void {
231 const transaction = this.getTransaction(transactionId)
232 if (!transaction) return
233
234 this.setTransactionState(transactionId, `persisting`)
235
236 this.collection.config.mutationFn
237 .persist({
238 transaction: this.createLiveTransactionReference(transactionId),
239 collection: this.collection,
240 })
241 .then((persistResult) => {
242 const tx = this.getTransaction(transactionId)
243 if (!tx) return
244
245 tx.isPersisted?.resolve(true)
246 if (this.collection.config.mutationFn.awaitSync) {
247 this.setTransactionState(transactionId, `persisted_awaiting_sync`)
248
249 // Create a promise that rejects after 2 seconds
250 const timeoutPromise = new Promise<never>((_, reject) => {
251 setTimeout(() => {
252 reject(new Error(`Sync operation timed out after 2 seconds`))
253 }, this.collection.config.mutationFn.awaitSyncTimeoutMs ?? 2000)
254 })
255
256 // Race the awaitSync promise against the timeout
257 Promise.race([
258 this.collection.config.mutationFn.awaitSync({
259 transaction: this.createLiveTransactionReference(transactionId),
260 collection: this.collection,
261 persistResult,
262 }),
263 timeoutPromise,
264 ])
265 .then(() => {
266 const updatedTx = this.getTransaction(transactionId)
267 if (!updatedTx) return
268
269 updatedTx.isSynced?.resolve(true)
270 this.setTransactionState(transactionId, `completed`)
271 })
272 // Catch awaitSync errors or timeout
273 .catch((error) => {
274 const updatedTx = this.getTransaction(transactionId)
275 if (!updatedTx) return
276
277 // Update transaction with error information
278 updatedTx.error = {
279 message: error.message || `Error during sync`,
280 error:
281 error instanceof Error ? error : new Error(String(error)),
282 }
283
284 // Reject the isSynced promise
285 updatedTx.isSynced?.reject(error)
286
287 // Set transaction state to failed
288 this.setTransaction(updatedTx)
289 this.setTransactionState(transactionId, `failed`)
290 })
291 } else {
292 this.setTransactionState(transactionId, `completed`)
293 }
294 })
295 .catch((error) => {
296 const tx = this.getTransaction(transactionId)
297 if (!tx) return
298
299 // Update transaction with error information
300 tx.error = {
301 message: error.message || `Error during persist`,
302 error: error instanceof Error ? error : new Error(String(error)),
303 }
304
305 // Reject both promises
306 tx.isPersisted?.reject(error)
307 tx.isSynced?.reject(error)
308
309 // Set transaction state to failed
310 this.setTransactionState(transactionId, `failed`)
311 })
312 }
313
314 /**
315 * Updates the state of a transaction
316 *
317 * @param id - The unique identifier of the transaction
318 * @param newState - The new state to set
319 * @throws Error if the transaction is not found
320 */
321 setTransactionState(id: string, newState: TransactionState): void {
322 const transaction = this.getTransaction(id)
323 if (!transaction) {
324 throw new Error(`Transaction ${id} not found`)
325 }
326
327 // Force a small delay to ensure updatedAt is different
328 const updatedTransaction: Transaction = {
329 ...transaction,
330 state: newState,
331 updatedAt: new Date(Date.now() + 1),
332 }
333
334 this.setTransaction(updatedTransaction)
335
336 // Check if the transaction is in a terminal state
337 if (newState === `completed` || newState === `failed`) {
338 // Delete from IndexedDB if in terminal state
339 this.store.deleteTransaction(id)
340 } else {
341 // Persist async only if not in terminal state
342 this.store.putTransaction(updatedTransaction)
343 }
344
345 // If this transaction is completing, check if any are queued behind it
346 if (
347 (newState === `completed` || newState === `failed`) &&
348 transaction.strategy.type === `ordered`
349 ) {
350 // Get all ordered transactions that are queued behind this one
351 const queuedTransactions = Array.from(
352 this.transactions.state.values()
353 ).filter(
354 (tx) =>
355 tx.state === `queued` &&
356 tx.strategy.type === `ordered` &&
357 tx.queuedBehind === transaction.id
358 )
359
360 // Process each queued transaction
361 for (const queuedTransaction of queuedTransactions) {
362 queuedTransaction.queuedBehind = undefined
363 this.setTransaction(queuedTransaction)
364 this.processTransaction(queuedTransaction.id)
365 }
366 }
367 }
368
369 /**
370 * Gets all active transactions (those not in completed or failed state)
371 *
372 * @returns Array of active transactions
373 */
374 getActiveTransactions(): Array<Transaction> {
375 return Array.from(this.transactions.state.values()).filter(
376 (tx) => tx.state !== `completed` && tx.state !== `failed`
377 )
378 }
379
380 /**
381 * Checks if two sets of mutations have overlapping keys
382 *
383 * @param mutations1 - First set of mutations
384 * @param mutations2 - Second set of mutations
385 * @returns True if there are overlapping mutations, false otherwise
386 */
387 hasOverlappingMutations(
388 mutations1: Array<PendingMutation>,
389 mutations2: Array<PendingMutation>
390 ): boolean {
391 const ids1 = new Set(mutations1.map((m) => m.original.id))
392 const ids2 = new Set(mutations2.map((m) => m.original.id))
393 return Array.from(ids1).some((id) => ids2.has(id))
394 }
395}