Open History to see the last commit
1import { beforeEach, describe, expect, it } from "vitest"
2import { TransactionManager } from "../src/TransactionManager"
3import { TransactionStore } from "../src/TransactionStore"
4import "fake-indexeddb/auto"
5import { Collection } from "../src/collection"
6import type { MutationStrategy, PendingMutation } from "../src/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 id: `foo`,
18 sync: {
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 syncMetadata: {},
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
196 manager.transactions.setState((sortedMap) => {
197 // @ts-expect-error this is fine for a test
198 sortedMap.set(updatedTx.id, updatedTx)
199 return sortedMap
200 })
201 return updatedTx
202 })
203 )
204
205 // Verify transactions are returned in chronological order (oldest first)
206 const sortedTransactions = Array.from(manager.transactions.state.values())
207 expect(sortedTransactions[0]?.createdAt.getTime()).toBe(timestamps[2]) // Oldest
208 expect(sortedTransactions[1]?.createdAt.getTime()).toBe(timestamps[1])
209 expect(sortedTransactions[2]?.createdAt.getTime()).toBe(timestamps[0]) // Newest
210 })
211
212 it(`should create a new transaction when no existing transactions with overlapping keys exist`, () => {
213 // Create a new transaction
214 const mutations = [createMockMutation(`test-apply-1`)]
215 const transaction = manager.applyTransaction(mutations, orderedStrategy)
216
217 // Verify transaction was created with the expected properties
218 expect(transaction.id).toBeDefined()
219 expect(transaction.state).toBe(`pending`)
220 expect(transaction.mutations).toEqual(mutations)
221 })
222
223 it(`should overwrite mutations for the same key in existing pending transactions`, () => {
224 // Create first transaction with a mutation
225 const originalMutation = {
226 ...createMockMutation(`test-apply-2`),
227 modified: { id: `test-apply-2`, value: `original-value` },
228 changes: { value: `original-value` },
229 }
230
231 manager.applyTransaction([originalMutation], orderedStrategy)
232
233 // Create second transaction with a mutation - this should be queued behind the first.
234 const tx1 = manager.applyTransaction([originalMutation], orderedStrategy)
235 expect(tx1.mutations[0]?.modified.value).toBe(`original-value`)
236
237 // Apply a new transaction with a mutation for the same key but different value.
238 const newMutation = {
239 ...createMockMutation(`test-apply-2`),
240 modified: { id: `test-apply-2`, value: `updated-value` },
241 changes: { value: `updated-value` },
242 }
243
244 const tx2 = manager.applyTransaction([newMutation], orderedStrategy)
245
246 // Should reuse the same transaction ID
247 expect(tx2.id).toBe(tx1.id)
248
249 // Should have updated the mutation
250 expect(tx2.mutations.length).toBe(1)
251 expect(tx2.mutations[0]?.modified.value).toBe(`updated-value`)
252 expect(tx2.mutations[0]?.changes.value).toBe(`updated-value`)
253 })
254
255 it(`should add new mutations while preserving existing ones for different keys`, () => {
256 // Create first transaction with a mutation
257 const mutation1 = createMockMutation(`test-apply-3a`)
258 const tx1 = manager.applyTransaction([mutation1], orderedStrategy)
259
260 // Apply a new transaction with a mutation for a different key
261 const mutation2 = createMockMutation(`test-apply-3b`)
262 const tx2 = manager.applyTransaction([mutation2], orderedStrategy)
263
264 // Should create a new transaction since keys don't overlap
265 expect(tx2.id).not.toBe(tx1.id)
266 expect(tx2.mutations.length).toBe(1)
267 expect(tx2.mutations[0]?.key).toBe(`test-apply-3b`)
268 })
269
270 it(`should handle multiple transactions with overlapping keys`, () => {
271 // Create first transaction with mutations for keys A and B
272 const mutationA1 = {
273 ...createMockMutation(`key-A`),
274 modified: { id: `key-A`, value: `A-original` },
275 changes: { value: `A-original` },
276 }
277
278 const mutationB1 = {
279 ...createMockMutation(`key-B`),
280 modified: { id: `key-B`, value: `B-original` },
281 changes: { value: `B-original` },
282 }
283
284 // Apply an initial one so the second is queued behind it.
285 manager.applyTransaction([mutationA1, mutationB1], orderedStrategy)
286 const tx1 = manager.applyTransaction(
287 [mutationA1, mutationB1],
288 orderedStrategy
289 )
290
291 // Create second transaction with mutations for keys B and C
292 const mutationB2 = {
293 ...createMockMutation(`key-B`),
294 modified: { id: `key-B`, value: `B-updated` },
295 changes: { value: `B-updated` },
296 }
297
298 const mutationC1 = {
299 ...createMockMutation(`key-C`),
300 modified: { id: `key-C`, value: `C-original` },
301 changes: { value: `C-original` },
302 }
303
304 // Apply the new transaction
305 const tx2 = manager.applyTransaction(
306 [mutationB2, mutationC1],
307 orderedStrategy
308 )
309
310 // Should update tx1 since it has an overlapping key (B)
311 expect(tx2.id).toBe(tx1.id)
312
313 // Should have 3 mutations now (A, B-updated, C)
314 expect(tx2.mutations.length).toBe(3)
315
316 // Find each mutation by key
317 const mutationA = tx2.mutations.find((m) => m.key === `key-A`)
318 const mutationB = tx2.mutations.find((m) => m.key === `key-B`)
319 const mutationC = tx2.mutations.find((m) => m.key === `key-C`)
320
321 // Verify A is unchanged
322 expect(mutationA).toBeDefined()
323 expect(mutationA?.modified.value).toBe(`A-original`)
324
325 // Verify B is updated
326 expect(mutationB).toBeDefined()
327 expect(mutationB?.modified.value).toBe(`B-updated`)
328
329 // Verify C is added
330 expect(mutationC).toBeDefined()
331 expect(mutationC?.modified.value).toBe(`C-original`)
332 })
333
334 it(`should handle the case where mutations don't overlap at all`, () => {
335 // Create three transactions with non-overlapping mutations
336 const tx1 = manager.applyTransaction(
337 [createMockMutation(`key-1`)],
338 orderedStrategy
339 )
340 const tx2 = manager.applyTransaction(
341 [createMockMutation(`key-2`)],
342 orderedStrategy
343 )
344
345 // Apply a transaction with a new non-overlapping key
346 const tx3 = manager.applyTransaction(
347 [createMockMutation(`key-3`)],
348 orderedStrategy
349 )
350
351 // Should be a new transaction
352 expect(tx3.id).not.toBe(tx1.id)
353 expect(tx3.id).not.toBe(tx2.id)
354 expect(tx3.mutations.length).toBe(1)
355 expect(tx3.mutations[0]?.key).toBe(`key-3`)
356
357 // Original transactions should be unchanged
358 const updatedTx1 = manager.getTransaction(tx1.id)
359 const updatedTx2 = manager.getTransaction(tx2.id)
360
361 expect(updatedTx1?.mutations.length).toBe(1)
362 expect(updatedTx1?.mutations[0]?.key).toBe(`key-1`)
363
364 expect(updatedTx2?.mutations.length).toBe(1)
365 expect(updatedTx2?.mutations[0]?.key).toBe(`key-2`)
366 })
367
368 it(`should only consider active transactions for applying updates`, () => {
369 // Create a transaction and mark it as completed
370 const mutation1 = createMockMutation(`completed-key`)
371 const tx1 = manager.applyTransaction([mutation1], orderedStrategy)
372 manager.setTransactionState(tx1.id, `completed`)
373
374 // Apply a new transaction with the same key
375 const mutation2 = {
376 ...createMockMutation(`completed-key`),
377 modified: { id: `completed-key`, value: `new-value` },
378 changes: { value: `new-value` },
379 }
380
381 const tx2 = manager.applyTransaction([mutation2], orderedStrategy)
382
383 // Should create a new transaction since the existing one is completed
384 expect(tx2.id).not.toBe(tx1.id)
385 expect(tx2.mutations.length).toBe(1)
386 expect(tx2.mutations[0]?.modified.value).toBe(`new-value`)
387 })
388 })
389
390 describe(`Error Handling`, () => {
391 it(`should reject both isPersisted and isSynced promises when persist fails`, async () => {
392 // Create a collection with a persist function that throws an error
393 const errorCollection = new Collection({
394 id: `foo`,
395 sync: {
396 sync: () => {},
397 },
398 mutationFn: {
399 // eslint-disable-next-line
400 persist: async () => {
401 throw new Error(`Persist error affecting both promises`)
402 },
403 // Add awaitSync to ensure isSynced is initialized
404 awaitSync: async () => {},
405 },
406 })
407 const errorManager = new TransactionManager(store, errorCollection)
408
409 // Apply a transaction
410 const mutations = [createMockMutation(`error-test-5`)]
411 const transaction = errorManager.applyTransaction(
412 mutations,
413 orderedStrategy
414 )
415
416 await expect(transaction.isPersisted?.promise).rejects.toThrow(
417 `Persist error affecting both promises`
418 )
419 await expect(transaction.isSynced?.promise).rejects.toThrow(
420 `Persist error affecting both promises`
421 )
422
423 // Verify the transaction state
424 expect(transaction.state).toBe(`failed`)
425 expect(transaction.error?.message).toBe(
426 `Persist error affecting both promises`
427 )
428 })
429
430 it(`should reject the isSynced promise when awaitSync fails`, async () => {
431 // Define the type for our persist result
432 type PersistResult = { testData: string }
433
434 // Create a collection with an awaitSync function that throws an error
435 const syncErrorCollection = new Collection({
436 id: `failing-sync`,
437 sync: {
438 sync: () => {},
439 },
440 // Explicitly specify the MutationFn with proper generic types
441 mutationFn: {
442 persist: () => {
443 // Return some test data that should be passed to awaitSync
444 return Promise.resolve({ testData: `persist-data` })
445 },
446 awaitSync: async ({
447 persistResult,
448 }: {
449 persistResult: PersistResult
450 }) => {
451 // Now TypeScript knows that persistResult has a testData property
452 return Promise.reject(
453 new Error(`Sync promise error - ${persistResult.testData}`)
454 )
455 },
456 },
457 })
458 const syncErrorManager = new TransactionManager(
459 store,
460 syncErrorCollection
461 )
462
463 // Apply a transaction
464 const mutations = [createMockMutation(`error-test-4`)]
465 const transaction = syncErrorManager.applyTransaction(
466 mutations,
467 orderedStrategy
468 )
469
470 await expect(transaction.isSynced?.promise).rejects.toThrow(
471 `Sync promise error - persist-data`
472 )
473
474 // Verify the transaction state
475 expect(transaction.state).toBe(`failed`)
476 expect(transaction.error?.message).toBe(
477 `Sync promise error - persist-data`
478 )
479 })
480
481 it(`should timeout and reject the isSynced promise when awaitSync takes too long`, async () => {
482 // Create a collection with an awaitSync function that takes longer than the timeout
483 const timeoutCollection = new Collection({
484 id: `timeout-sync`,
485 sync: {
486 sync: () => {},
487 },
488 mutationFn: {
489 persist: () => {
490 return Promise.resolve({ testData: `persist-data` })
491 },
492 awaitSyncTimeoutMs: 10,
493 awaitSync: async () => {
494 // This promise will never resolve within the timeout period
495 return new Promise((resolve) => {
496 setTimeout(() => {
497 return resolve()
498 }, 10000)
499 })
500 },
501 },
502 })
503 const timeoutManager = new TransactionManager(store, timeoutCollection)
504
505 // Apply a transaction
506 const mutations = [createMockMutation(`timeout-test`)]
507 const transaction = timeoutManager.applyTransaction(
508 mutations,
509 orderedStrategy
510 )
511
512 // The promise should reject with a timeout error
513 await expect(transaction.isSynced?.promise).rejects.toThrow(
514 `Sync operation timed out after 2 seconds`
515 )
516
517 // Verify the transaction state
518 expect(transaction.state).toBe(`failed`)
519 expect(transaction.error?.message).toBe(
520 `Sync operation timed out after 2 seconds`
521 )
522 })
523
524 it(`should capture errors from queued transactions when they're persisted`, async () => {
525 // Define the type for our persist result
526 type PersistResult = { testData: string }
527
528 let transactionCount = 0
529 // Create a collection with an awaitSync function that throws an error
530 const syncErrorCollection = new Collection({
531 id: `failing-sync`,
532 sync: {
533 sync: () => {},
534 },
535 // Explicitly specify the MutationFn with proper generic types
536 mutationFn: {
537 persist: () => {
538 // Return some test data that should be passed to awaitSync
539 return Promise.resolve({ testData: `persist-data` })
540 },
541 awaitSync: async ({
542 persistResult,
543 }: {
544 persistResult: PersistResult
545 }) => {
546 if (transactionCount === 1) {
547 // Now TypeScript knows that persistResult has a testData property
548 return Promise.reject(
549 new Error(`Sync promise error - ${persistResult.testData}`)
550 )
551 }
552
553 transactionCount += 1
554 },
555 },
556 })
557 const syncErrorManager = new TransactionManager(
558 store,
559 syncErrorCollection
560 )
561
562 // Apply a transaction
563 const mutations = [createMockMutation(`object-1`)]
564 const tx1 = syncErrorManager.applyTransaction(mutations, orderedStrategy)
565
566 expect(tx1.state).toBe(`pending`)
567 expect(tx1.queuedBehind).toBeUndefined()
568
569 // Create second transaction also modifying object 1 - should be queued
570 const tx2 = syncErrorManager.applyTransaction(
571 [createMockMutation(`object-1`)],
572 orderedStrategy
573 )
574 expect(tx2.state).toBe(`queued`)
575 expect(tx2.queuedBehind).toBe(tx1.id)
576
577 await expect(tx2.isSynced?.promise).rejects.toThrow(
578 `Sync promise error - persist-data`
579 )
580
581 // Verify the transaction state
582 expect(tx2.state).toBe(`failed`)
583 expect(tx2.error?.message).toBe(`Sync promise error - persist-data`)
584 })
585 })
586
587 describe(`Terminal State Handling`, () => {
588 it(`should delete transactions from IndexedDB when they reach a terminal state`, async () => {
589 // Clear all existing transactions first
590 await store.clearAll()
591
592 // Create a transaction
593 const tx = manager.applyTransaction(
594 [createMockMutation(`test-object`)],
595 parallelStrategy
596 )
597
598 // Verify transaction exists in IndexedDB
599 let transactions = await store.getTransactions()
600 expect(transactions.length).toBe(1)
601 expect(transactions[0]?.id).toBe(tx.id)
602
603 // Update to 'completed' state (terminal)
604 manager.setTransactionState(tx.id, `completed`)
605
606 // Verify transaction is deleted from IndexedDB
607 transactions = await store.getTransactions()
608 expect(transactions.length).toBe(0)
609
610 // Create another transaction
611 const tx2 = manager.applyTransaction(
612 [createMockMutation(`test-object-2`)],
613 parallelStrategy
614 )
615
616 // Verify transaction exists in IndexedDB
617 transactions = await store.getTransactions()
618 expect(transactions.length).toBe(1)
619 expect(transactions[0]?.id).toBe(tx2.id)
620
621 // Update to 'failed' state (terminal)
622 manager.setTransactionState(tx2.id, `failed`)
623
624 // Verify transaction is deleted from IndexedDB
625 transactions = await store.getTransactions()
626 expect(transactions.length).toBe(0)
627 })
628 })
629})