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

TransactionManager.test.ts

627 lines21.3 KB

1import { beforeEach, describe, expect, it } from "vitest"
2import { TransactionManager } from "./TransactionManager"
3import { TransactionStore } from "./TransactionStore"
4import "fake-indexeddb/auto"
5import { Collection } from "./collection"
6import type { MutationStrategy, PendingMutation } from "./types"
7​
8describe(`TransactionManager`, () => {
9 let store: TransactionStore
10 let collection: Collection
11 let manager: TransactionManager
12​
13 beforeEach(() => {
14 // Reset indexedDB for each test using the fake-indexeddb implementation
15 store = new TransactionStore()
16 collection = new Collection({
17 sync: {
18 id: `mock`,
19 sync: () => {},
20 },
21 mutationFn: {
22 persist: async () => {
23 await new Promise((resolve) => setTimeout(resolve, 1))
24 },
25 },
26 })
27 manager = new TransactionManager(store, collection)
28 store.clearAll()
29 })
30​
31 const createMockMutation = (id: string): PendingMutation => ({
32 mutationId: id,
33 original: { id, value: `original` },
34 modified: { id, value: `modified` },
35 changes: { value: `modified` },
36 type: `insert`,
37 key: id,
38 metadata: null,
39 createdAt: new Date(),
40 updatedAt: new Date(),
41 state: `created`,
42 })
43​
44 const orderedStrategy: MutationStrategy = {
45 type: `ordered`,
46 }
47​
48 const parallelStrategy: MutationStrategy = {
49 type: `parallel`,
50 }
51​
52 describe(`Basic Transaction Management`, () => {
53 it(`should create a transaction in pending state`, () => {
54 const mutations = [createMockMutation(`test-1`)]
55 const transaction = manager.applyTransaction(mutations, orderedStrategy)
56​
57 expect(transaction.id).toBeDefined()
58 expect(transaction.state).toBe(`pending`)
59 expect(transaction.mutations).toEqual(mutations)
60 })
61​
62 it(`should update transaction state`, () => {
63 const mutations = [createMockMutation(`test-2`)]
64 const transaction = manager.applyTransaction(mutations, orderedStrategy)
65​
66 // Add a small delay to ensure timestamps are different
67 const beforeUpdate = transaction.updatedAt
68 manager.setTransactionState(transaction.id, `pending`)
69​
70 const updated = manager.getTransaction(transaction.id)
71 expect(updated?.state).toBe(`pending`)
72 expect(updated?.updatedAt.getTime()).toBeGreaterThan(
73 beforeUpdate.getTime()
74 )
75 })
76​
77 it(`should throw when updating non-existent transaction`, () => {
78 expect(() =>
79 manager.setTransactionState(`non-existent`, `completed`)
80 ).toThrow(`Transaction non-existent not found`)
81 })
82 })
83​
84 describe(`Ordered vs Parallel Transactions`, () => {
85 it(`should queue ordered transactions with overlapping mutations`, () => {
86 // Create first transaction modifying object 1
87 const tx1 = manager.applyTransaction(
88 [createMockMutation(`object-1`)],
89 orderedStrategy
90 )
91 expect(tx1.state).toBe(`pending`)
92 expect(tx1.queuedBehind).toBeUndefined()
93​
94 // Create second transaction also modifying object 1 - should be queued
95 const tx2 = manager.applyTransaction(
96 [createMockMutation(`object-1`)],
97 orderedStrategy
98 )
99 expect(tx2.state).toBe(`queued`)
100 expect(tx2.queuedBehind).toBe(tx1.id)
101​
102 // Create third transaction modifying different object - should not be queued
103 const tx3 = manager.applyTransaction(
104 [createMockMutation(`object-2`)],
105 orderedStrategy
106 )
107 expect(tx3.state).toBe(`pending`)
108 expect(tx3.queuedBehind).toBeUndefined()
109​
110 // Complete first transaction
111 manager.setTransactionState(tx1.id, `completed`)
112​
113 // Check that second transaction is now pending
114 const updatedTx2 = manager.getTransaction(tx2.id)!
115 expect(updatedTx2.state).toBe(`persisting`)
116 })
117​
118 it(`should not queue parallel transactions`, () => {
119 // Create multiple parallel transactions modifying same object
120 const tx1 = manager.applyTransaction(
121 [createMockMutation(`object-1`)],
122 parallelStrategy
123 )
124 const tx2 = manager.applyTransaction(
125 [createMockMutation(`object-1`)],
126 parallelStrategy
127 )
128 const tx3 = manager.applyTransaction(
129 [createMockMutation(`object-1`)],
130 parallelStrategy
131 )
132​
133 // All should be in pending state and not queued
134 expect(tx1.state).toBe(`pending`)
135 expect(tx1.queuedBehind).toBeUndefined()
136 expect(tx2.state).toBe(`pending`)
137 expect(tx2.queuedBehind).toBeUndefined()
138 expect(tx3.state).toBe(`pending`)
139 expect(tx3.queuedBehind).toBeUndefined()
140 })
141​
142 it(`should mix ordered and parallel transactions correctly`, () => {
143 // Create an ordered transaction modifying object 1
144 const ordered1 = manager.applyTransaction(
145 [createMockMutation(`object-1`)],
146 orderedStrategy
147 )
148​
149 // Create a parallel transaction modifying object 1 - should not queue
150 const parallel1 = manager.applyTransaction(
151 [createMockMutation(`object-1`)],
152 parallelStrategy
153 )
154​
155 // Create another ordered transaction modifying object 1 - should queue behind ordered1
156 const ordered2 = manager.applyTransaction(
157 [createMockMutation(`object-1`)],
158 orderedStrategy
159 )
160​
161 expect(ordered1.state).toBe(`pending`)
162 expect(ordered1.queuedBehind).toBeUndefined()
163 expect(parallel1.state).toBe(`pending`)
164 expect(parallel1.queuedBehind).toBeUndefined()
165 expect(ordered2.state).toBe(`queued`)
166 expect(ordered2.queuedBehind).toBe(ordered1.id)
167​
168 // Complete ordered1, ordered2 should become pending
169 manager.setTransactionState(ordered1.id, `completed`)
170​
171 const updatedOrdered2 = manager.getTransaction(ordered2.id)!
172 expect(updatedOrdered2.state).toBe(`persisting`)
173 expect(updatedOrdered2.queuedBehind).toBeUndefined()
174 })
175 })
176​
177 describe(`Transaction Ordering`, () => {
178 it(`should maintain transactions sorted by createdAt`, async () => {
179 // Create transactions with different timestamps
180 const now = Date.now()
181 const timestamps = [now, now - 1000, now - 2000]
182​
183 // Create transactions in reverse chronological order
184 await Promise.all(
185 timestamps.map((timestamp, i) => {
186 const tx = manager.applyTransaction(
187 [createMockMutation(`test-${i + 1}`)],
188 parallelStrategy
189 )
190 // Force the createdAt time
191 const updatedTx = {
192 ...tx.toObject(),
193 createdAt: new Date(timestamp),
194 }
195 manager.transactions.setState((sortedMap) => {
196 sortedMap.set(updatedTx.id, updatedTx)
197 return sortedMap
198 })
199 return updatedTx
200 })
201 )
202​
203 // Verify transactions are returned in chronological order (oldest first)
204 const sortedTransactions = Array.from(manager.transactions.state.values())
205 expect(sortedTransactions[0].createdAt.getTime()).toBe(timestamps[2]) // Oldest
206 expect(sortedTransactions[1].createdAt.getTime()).toBe(timestamps[1])
207 expect(sortedTransactions[2].createdAt.getTime()).toBe(timestamps[0]) // Newest
208 })
209​
210 it(`should create a new transaction when no existing transactions with overlapping keys exist`, () => {
211 // Create a new transaction
212 const mutations = [createMockMutation(`test-apply-1`)]
213 const transaction = manager.applyTransaction(mutations, orderedStrategy)
214​
215 // Verify transaction was created with the expected properties
216 expect(transaction.id).toBeDefined()
217 expect(transaction.state).toBe(`pending`)
218 expect(transaction.mutations).toEqual(mutations)
219 })
220​
221 it(`should overwrite mutations for the same key in existing pending transactions`, () => {
222 // Create first transaction with a mutation
223 const originalMutation = {
224 ...createMockMutation(`test-apply-2`),
225 modified: { id: `test-apply-2`, value: `original-value` },
226 changes: { value: `original-value` },
227 }
228​
229 manager.applyTransaction([originalMutation], orderedStrategy)
230​
231 // Create second transaction with a mutation - this should be queued behind the first.
232 const tx1 = manager.applyTransaction([originalMutation], orderedStrategy)
233 expect(tx1.mutations[0].modified.value).toBe(`original-value`)
234​
235 // Apply a new transaction with a mutation for the same key but different value.
236 const newMutation = {
237 ...createMockMutation(`test-apply-2`),
238 modified: { id: `test-apply-2`, value: `updated-value` },
239 changes: { value: `updated-value` },
240 }
241​
242 const tx2 = manager.applyTransaction([newMutation], orderedStrategy)
243​
244 // Should reuse the same transaction ID
245 expect(tx2.id).toBe(tx1.id)
246​
247 // Should have updated the mutation
248 expect(tx2.mutations.length).toBe(1)
249 expect(tx2.mutations[0].modified.value).toBe(`updated-value`)
250 expect(tx2.mutations[0].changes.value).toBe(`updated-value`)
251 })
252​
253 it(`should add new mutations while preserving existing ones for different keys`, () => {
254 // Create first transaction with a mutation
255 const mutation1 = createMockMutation(`test-apply-3a`)
256 const tx1 = manager.applyTransaction([mutation1], orderedStrategy)
257​
258 // Apply a new transaction with a mutation for a different key
259 const mutation2 = createMockMutation(`test-apply-3b`)
260 const tx2 = manager.applyTransaction([mutation2], orderedStrategy)
261​
262 // Should create a new transaction since keys don't overlap
263 expect(tx2.id).not.toBe(tx1.id)
264 expect(tx2.mutations.length).toBe(1)
265 expect(tx2.mutations[0].key).toBe(`test-apply-3b`)
266 })
267​
268 it(`should handle multiple transactions with overlapping keys`, () => {
269 // Create first transaction with mutations for keys A and B
270 const mutationA1 = {
271 ...createMockMutation(`key-A`),
272 modified: { id: `key-A`, value: `A-original` },
273 changes: { value: `A-original` },
274 }
275​
276 const mutationB1 = {
277 ...createMockMutation(`key-B`),
278 modified: { id: `key-B`, value: `B-original` },
279 changes: { value: `B-original` },
280 }
281​
282 // Apply an initial one so the second is queued behind it.
283 manager.applyTransaction([mutationA1, mutationB1], orderedStrategy)
284 const tx1 = manager.applyTransaction(
285 [mutationA1, mutationB1],
286 orderedStrategy
287 )
288​
289 // Create second transaction with mutations for keys B and C
290 const mutationB2 = {
291 ...createMockMutation(`key-B`),
292 modified: { id: `key-B`, value: `B-updated` },
293 changes: { value: `B-updated` },
294 }
295​
296 const mutationC1 = {
297 ...createMockMutation(`key-C`),
298 modified: { id: `key-C`, value: `C-original` },
299 changes: { value: `C-original` },
300 }
301​
302 // Apply the new transaction
303 const tx2 = manager.applyTransaction(
304 [mutationB2, mutationC1],
305 orderedStrategy
306 )
307​
308 // Should update tx1 since it has an overlapping key (B)
309 expect(tx2.id).toBe(tx1.id)
310​
311 // Should have 3 mutations now (A, B-updated, C)
312 expect(tx2.mutations.length).toBe(3)
313​
314 // Find each mutation by key
315 const mutationA = tx2.mutations.find((m) => m.key === `key-A`)
316 const mutationB = tx2.mutations.find((m) => m.key === `key-B`)
317 const mutationC = tx2.mutations.find((m) => m.key === `key-C`)
318​
319 // Verify A is unchanged
320 expect(mutationA).toBeDefined()
321 expect(mutationA?.modified.value).toBe(`A-original`)
322​
323 // Verify B is updated
324 expect(mutationB).toBeDefined()
325 expect(mutationB?.modified.value).toBe(`B-updated`)
326​
327 // Verify C is added
328 expect(mutationC).toBeDefined()
329 expect(mutationC?.modified.value).toBe(`C-original`)
330 })
331​
332 it(`should handle the case where mutations don't overlap at all`, () => {
333 // Create three transactions with non-overlapping mutations
334 const tx1 = manager.applyTransaction(
335 [createMockMutation(`key-1`)],
336 orderedStrategy
337 )
338 const tx2 = manager.applyTransaction(
339 [createMockMutation(`key-2`)],
340 orderedStrategy
341 )
342​
343 // Apply a transaction with a new non-overlapping key
344 const tx3 = manager.applyTransaction(
345 [createMockMutation(`key-3`)],
346 orderedStrategy
347 )
348​
349 // Should be a new transaction
350 expect(tx3.id).not.toBe(tx1.id)
351 expect(tx3.id).not.toBe(tx2.id)
352 expect(tx3.mutations.length).toBe(1)
353 expect(tx3.mutations[0].key).toBe(`key-3`)
354​
355 // Original transactions should be unchanged
356 const updatedTx1 = manager.getTransaction(tx1.id)
357 const updatedTx2 = manager.getTransaction(tx2.id)
358​
359 expect(updatedTx1?.mutations.length).toBe(1)
360 expect(updatedTx1?.mutations[0].key).toBe(`key-1`)
361​
362 expect(updatedTx2?.mutations.length).toBe(1)
363 expect(updatedTx2?.mutations[0].key).toBe(`key-2`)
364 })
365​
366 it(`should only consider active transactions for applying updates`, () => {
367 // Create a transaction and mark it as completed
368 const mutation1 = createMockMutation(`completed-key`)
369 const tx1 = manager.applyTransaction([mutation1], orderedStrategy)
370 manager.setTransactionState(tx1.id, `completed`)
371​
372 // Apply a new transaction with the same key
373 const mutation2 = {
374 ...createMockMutation(`completed-key`),
375 modified: { id: `completed-key`, value: `new-value` },
376 changes: { value: `new-value` },
377 }
378​
379 const tx2 = manager.applyTransaction([mutation2], orderedStrategy)
380​
381 // Should create a new transaction since the existing one is completed
382 expect(tx2.id).not.toBe(tx1.id)
383 expect(tx2.mutations.length).toBe(1)
384 expect(tx2.mutations[0].modified.value).toBe(`new-value`)
385 })
386 })
387​
388 describe(`Error Handling`, () => {
389 it(`should reject both isPersisted and isSynced promises when persist fails`, async () => {
390 // Create a collection with a persist function that throws an error
391 const errorCollection = new Collection({
392 id: `foo`,
393 sync: {
394 sync: () => {},
395 },
396 mutationFn: {
397 // eslint-disable-next-line
398 persist: async () => {
399 throw new Error(`Persist error affecting both promises`)
400 },
401 // Add awaitSync to ensure isSynced is initialized
402 awaitSync: async () => {},
403 },
404 })
405 const errorManager = new TransactionManager(store, errorCollection)
406​
407 // Apply a transaction
408 const mutations = [createMockMutation(`error-test-5`)]
409 const transaction = errorManager.applyTransaction(
410 mutations,
411 orderedStrategy
412 )
413​
414 await expect(transaction.isPersisted?.promise).rejects.toThrow(
415 `Persist error affecting both promises`
416 )
417 await expect(transaction.isSynced?.promise).rejects.toThrow(
418 `Persist error affecting both promises`
419 )
420​
421 // Verify the transaction state
422 expect(transaction.state).toBe(`failed`)
423 expect(transaction.error?.message).toBe(
424 `Persist error affecting both promises`
425 )
426 })
427​
428 it(`should reject the isSynced promise when awaitSync fails`, async () => {
429 // Define the type for our persist result
430 type PersistResult = { testData: string }
431​
432 // Create a collection with an awaitSync function that throws an error
433 const syncErrorCollection = new Collection({
434 id: `failing-sync`,
435 sync: {
436 sync: () => {},
437 },
438 // Explicitly specify the MutationFn with proper generic types
439 mutationFn: {
440 persist: () => {
441 // Return some test data that should be passed to awaitSync
442 return Promise.resolve({ testData: `persist-data` })
443 },
444 awaitSync: async ({
445 persistResult,
446 }: {
447 persistResult: PersistResult
448 }) => {
449 // Now TypeScript knows that persistResult has a testData property
450 return Promise.reject(
451 new Error(`Sync promise error - ${persistResult.testData}`)
452 )
453 },
454 },
455 })
456 const syncErrorManager = new TransactionManager(
457 store,
458 syncErrorCollection
459 )
460​
461 // Apply a transaction
462 const mutations = [createMockMutation(`error-test-4`)]
463 const transaction = syncErrorManager.applyTransaction(
464 mutations,
465 orderedStrategy
466 )
467​
468 await expect(transaction.isSynced?.promise).rejects.toThrow(
469 `Sync promise error - persist-data`
470 )
471​
472 // Verify the transaction state
473 expect(transaction.state).toBe(`failed`)
474 expect(transaction.error?.message).toBe(
475 `Sync promise error - persist-data`
476 )
477 })
478​
479 it(`should timeout and reject the isSynced promise when awaitSync takes too long`, async () => {
480 // Create a collection with an awaitSync function that takes longer than the timeout
481 const timeoutCollection = new Collection({
482 id: `timeout-sync`,
483 sync: {
484 sync: () => {},
485 },
486 mutationFn: {
487 persist: () => {
488 return Promise.resolve({ testData: `persist-data` })
489 },
490 awaitSyncTimeoutMs: 10,
491 awaitSync: async () => {
492 // This promise will never resolve within the timeout period
493 return new Promise((resolve) => {
494 setTimeout(() => {
495 return resolve()
496 }, 10000)
497 })
498 },
499 },
500 })
501 const timeoutManager = new TransactionManager(store, timeoutCollection)
502​
503 // Apply a transaction
504 const mutations = [createMockMutation(`timeout-test`)]
505 const transaction = timeoutManager.applyTransaction(
506 mutations,
507 orderedStrategy
508 )
509​
510 // The promise should reject with a timeout error
511 await expect(transaction.isSynced?.promise).rejects.toThrow(
512 `Sync operation timed out after 2 seconds`
513 )
514​
515 // Verify the transaction state
516 expect(transaction.state).toBe(`failed`)
517 expect(transaction.error?.message).toBe(
518 `Sync operation timed out after 2 seconds`
519 )
520 })
521​
522 it(`should capture errors from queued transactions when they're persisted`, async () => {
523 // Define the type for our persist result
524 type PersistResult = { testData: string }
525​
526 let transactionCount = 0
527 // Create a collection with an awaitSync function that throws an error
528 const syncErrorCollection = new Collection({
529 id: `failing-sync`,
530 sync: {
531 sync: () => {},
532 },
533 // Explicitly specify the MutationFn with proper generic types
534 mutationFn: {
535 persist: () => {
536 // Return some test data that should be passed to awaitSync
537 return Promise.resolve({ testData: `persist-data` })
538 },
539 awaitSync: async ({
540 persistResult,
541 }: {
542 persistResult: PersistResult
543 }) => {
544 if (transactionCount === 1) {
545 // Now TypeScript knows that persistResult has a testData property
546 return Promise.reject(
547 new Error(`Sync promise error - ${persistResult.testData}`)
548 )
549 }
550​
551 transactionCount += 1
552 },
553 },
554 })
555 const syncErrorManager = new TransactionManager(
556 store,
557 syncErrorCollection
558 )
559​
560 // Apply a transaction
561 const mutations = [createMockMutation(`object-1`)]
562 const tx1 = syncErrorManager.applyTransaction(mutations, orderedStrategy)
563​
564 expect(tx1.state).toBe(`pending`)
565 expect(tx1.queuedBehind).toBeUndefined()
566​
567 // Create second transaction also modifying object 1 - should be queued
568 const tx2 = syncErrorManager.applyTransaction(
569 [createMockMutation(`object-1`)],
570 orderedStrategy
571 )
572 expect(tx2.state).toBe(`queued`)
573 expect(tx2.queuedBehind).toBe(tx1.id)
574​
575 await expect(tx2.isSynced?.promise).rejects.toThrow(
576 `Sync promise error - persist-data`
577 )
578​
579 // Verify the transaction state
580 expect(tx2.state).toBe(`failed`)
581 expect(tx2.error?.message).toBe(`Sync promise error - persist-data`)
582 })
583 })
584​
585 describe(`Terminal State Handling`, () => {
586 it(`should delete transactions from IndexedDB when they reach a terminal state`, async () => {
587 // Clear all existing transactions first
588 await store.clearAll()
589​
590 // Create a transaction
591 const tx = manager.applyTransaction(
592 [createMockMutation(`test-object`)],
593 parallelStrategy
594 )
595​
596 // Verify transaction exists in IndexedDB
597 let transactions = await store.getTransactions()
598 expect(transactions.length).toBe(1)
599 expect(transactions[0].id).toBe(tx.id)
600​
601 // Update to 'completed' state (terminal)
602 manager.setTransactionState(tx.id, `completed`)
603​
604 // Verify transaction is deleted from IndexedDB
605 transactions = await store.getTransactions()
606 expect(transactions.length).toBe(0)
607​
608 // Create another transaction
609 const tx2 = manager.applyTransaction(
610 [createMockMutation(`test-object-2`)],
611 parallelStrategy
612 )
613​
614 // Verify transaction exists in IndexedDB
615 transactions = await store.getTransactions()
616 expect(transactions.length).toBe(1)
617 expect(transactions[0].id).toBe(tx2.id)
618​
619 // Update to 'failed' state (terminal)
620 manager.setTransactionState(tx2.id, `failed`)
621​
622 // Verify transaction is deleted from IndexedDB
623 transactions = await store.getTransactions()
624 expect(transactions.length).toBe(0)
625 })
626 })
627})