Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { NonRetriableError } from '../src/types'
3import { DefaultRetryPolicy } from '../src/retry/RetryPolicy'
4import { FakeStorageAdapter, createTestOfflineEnvironment } from './harness'
5import type { OfflineMutationFnParams, OnlineDetector } from '../src/types'
6
7const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 0))
8
9const waitUntil = async (
10 predicate: () => boolean | Promise<boolean>,
11 timeoutMs = 5000,
12 intervalMs = 20,
13) => {
14 const deadline = Date.now() + timeoutMs
15 while (Date.now() < deadline) {
16 if (await predicate()) {
17 return
18 }
19 await new Promise((resolve) => setTimeout(resolve, intervalMs))
20 }
21 throw new Error(`Timed out waiting for condition`)
22}
23
24class ManualOnlineDetector implements OnlineDetector {
25 private listeners = new Set<() => void>()
26 private online: boolean
27
28 constructor(initialOnline: boolean) {
29 this.online = initialOnline
30 }
31
32 subscribe(callback: () => void): () => void {
33 this.listeners.add(callback)
34
35 return () => {
36 this.listeners.delete(callback)
37 }
38 }
39
40 notifyOnline(): void {
41 for (const listener of this.listeners) {
42 listener()
43 }
44 }
45
46 isOnline(): boolean {
47 return this.online
48 }
49
50 setOnline(isOnline: boolean): void {
51 this.online = isOnline
52
53 if (isOnline) {
54 this.notifyOnline()
55 }
56 }
57
58 dispose(): void {
59 this.listeners.clear()
60 }
61}
62
63describe(`offline executor end-to-end`, () => {
64 it(`resolves waiting promises for successful transactions`, async () => {
65 const env = createTestOfflineEnvironment()
66
67 await env.waitForLeader()
68
69 const offlineTx = env.executor.createOfflineTransaction({
70 mutationFnName: env.mutationFnName,
71 autoCommit: false,
72 })
73
74 const waitPromise = env.executor.waitForTransactionCompletion(offlineTx.id)
75
76 const now = new Date()
77 offlineTx.mutate(() => {
78 env.collection.insert({
79 id: `item-1`,
80 value: `hello`,
81 completed: false,
82 updatedAt: now,
83 })
84 })
85
86 await offlineTx.commit()
87
88 await expect(waitPromise).resolves.toBeUndefined()
89
90 const outboxEntries = await env.executor.peekOutbox()
91 expect(outboxEntries).toEqual([])
92
93 expect(env.mutationCalls.length).toBeGreaterThanOrEqual(1)
94 const call = env.mutationCalls[env.mutationCalls.length - 1]!
95 expect(call.transaction.mutations).toHaveLength(1)
96 expect(call.transaction.mutations[0].key).toBe(`item-1`)
97 const stored = env.collection.get(`item-1`)
98 expect(stored?.value).toBe(`hello`)
99 expect(env.serverState.get(`item-1`)?.value).toBe(`hello`)
100
101 env.executor.dispose()
102 })
103
104 it(`retries queued transactions when backend resumes`, async () => {
105 let online = false
106 const env = createTestOfflineEnvironment({
107 mutationFn: (params) => {
108 const runtimeOnline = online
109 const mutations = params.transaction.mutations
110 if (!runtimeOnline) {
111 throw new Error(`offline`)
112 }
113 env.applyMutations(mutations)
114 return { ok: true, mutations }
115 },
116 })
117
118 await env.waitForLeader()
119
120 const offlineTx = env.executor.createOfflineTransaction({
121 mutationFnName: env.mutationFnName,
122 autoCommit: false,
123 })
124
125 const now = new Date()
126 offlineTx.mutate(() => {
127 env.collection.insert({
128 id: `queued-item`,
129 value: `queued`,
130 completed: false,
131 updatedAt: now,
132 })
133 })
134
135 // Commit should not throw for retriable errors - it persists to outbox
136 const commitPromise = offlineTx.commit()
137
138 // Wait a bit for the transaction to be processed
139 await flushMicrotasks()
140
141 // Check that the transaction was attempted once
142 expect(env.mutationCalls.length).toBe(1)
143
144 // Check that the transaction is in the outbox (persisted for retry)
145 let outboxEntries = await env.executor.peekOutbox()
146 expect(outboxEntries.length).toBe(1)
147 expect(outboxEntries[0]!.id).toBe(offlineTx.id)
148
149 // Now bring the system back online
150 online = true
151 env.executor.getOnlineDetector().notifyOnline()
152
153 // Wait for the retry to succeed
154 await waitUntil(() => env.mutationCalls.length >= 2)
155
156 // The original commit promise should now resolve
157 await expect(commitPromise).resolves.toBeDefined()
158
159 // Check that the transaction completed successfully
160 outboxEntries = await env.executor.peekOutbox()
161 expect(outboxEntries).toEqual([])
162
163 outboxEntries = await env.executor.peekOutbox()
164 expect(outboxEntries).toEqual([])
165 expect(env.mutationCalls.length).toBeGreaterThanOrEqual(2)
166 expect(env.serverState.get(`queued-item`)?.value).toBe(`queued`)
167
168 env.executor.dispose()
169 })
170
171 it(`retries beyond 10 attempts by default`, () => {
172 const policy = new DefaultRetryPolicy()
173 const error = new Error(`transient`)
174
175 for (let i = 0; i < 50; i++) {
176 expect(policy.shouldRetry(error, i)).toBe(true)
177 }
178
179 expect(policy.shouldRetry(new NonRetriableError(`permanent`), 0)).toBe(
180 false,
181 )
182 })
183
184 it(`does not execute mutations while offline`, async () => {
185 const onlineDetector = new ManualOnlineDetector(false)
186 const env = createTestOfflineEnvironment({
187 config: {
188 onlineDetector,
189 },
190 })
191
192 await env.waitForLeader()
193
194 const offlineTx = env.executor.createOfflineTransaction({
195 mutationFnName: env.mutationFnName,
196 autoCommit: false,
197 })
198
199 offlineTx.mutate(() => {
200 env.collection.insert({
201 id: `queued-while-offline`,
202 value: `queued`,
203 completed: false,
204 updatedAt: new Date(),
205 })
206 })
207
208 const commitPromise = offlineTx.commit()
209
210 await flushMicrotasks()
211 expect(env.mutationCalls).toHaveLength(0)
212 expect(await env.executor.peekOutbox()).toHaveLength(1)
213
214 onlineDetector.setOnline(true)
215
216 await expect(commitPromise).resolves.toBeDefined()
217 expect(env.mutationCalls).toHaveLength(1)
218 expect(await env.executor.peekOutbox()).toEqual([])
219
220 env.executor.dispose()
221 })
222
223 it(`rejects waiting promises for permanent failures and rolls back optimistic state`, async () => {
224 const error = new NonRetriableError(`permanent`)
225 const env = createTestOfflineEnvironment({
226 mutationFn: () => {
227 throw error
228 },
229 })
230
231 await env.waitForLeader()
232
233 const offlineTx = env.executor.createOfflineTransaction({
234 mutationFnName: env.mutationFnName,
235 autoCommit: false,
236 })
237
238 const waitPromise = env.executor.waitForTransactionCompletion(offlineTx.id)
239
240 offlineTx.mutate(() => {
241 env.collection.insert({
242 id: `perm-item`,
243 value: `nope`,
244 completed: false,
245 updatedAt: new Date(),
246 })
247 })
248
249 await expect(offlineTx.commit()).rejects.toThrow(`permanent`)
250 await expect(waitPromise).rejects.toThrow(`permanent`)
251
252 const outboxEntries = await env.executor.peekOutbox()
253 expect(outboxEntries).toEqual([])
254 expect(env.collection.get(`perm-item`)).toBeUndefined()
255 expect(env.serverState.get(`perm-item`)).toBeUndefined()
256
257 env.executor.dispose()
258 })
259
260 it(`replays persisted transactions on startup`, async () => {
261 const storage = new FakeStorageAdapter()
262
263 const offlineErrorEnv = createTestOfflineEnvironment({
264 storage,
265 mutationFn: () => {
266 throw new Error(`offline`)
267 },
268 })
269
270 await offlineErrorEnv.waitForLeader()
271
272 const offlineTx = offlineErrorEnv.executor.createOfflineTransaction({
273 mutationFnName: offlineErrorEnv.mutationFnName,
274 autoCommit: false,
275 })
276
277 offlineTx.mutate(() => {
278 offlineErrorEnv.collection.insert({
279 id: `persisted`,
280 value: `from-outbox`,
281 completed: false,
282 updatedAt: new Date(),
283 })
284 })
285
286 // Start the commit - it will persist to outbox and keep retrying
287 // We don't await it because it will never complete (mutation always fails)
288 offlineTx.commit()
289
290 // Wait for the transaction to be persisted to outbox
291 await waitUntil(async () => {
292 const pendingEntries = await offlineErrorEnv.executor.peekOutbox()
293 return pendingEntries.length === 1
294 }, 5000)
295
296 // Verify it's in the outbox
297 const outboxEntries = await offlineErrorEnv.executor.peekOutbox()
298 expect(outboxEntries.length).toBe(1)
299 expect(outboxEntries[0]!.id).toBe(offlineTx.id)
300
301 offlineErrorEnv.executor.dispose()
302
303 const replayEnv = createTestOfflineEnvironment({
304 storage,
305 mutationFn: (params: OfflineMutationFnParams & { attempt: number }) => {
306 const mutations = params.transaction.mutations
307 replayEnv.applyMutations(mutations)
308 return { ok: true, mutations }
309 },
310 })
311
312 await replayEnv.waitForLeader()
313 await waitUntil(async () => {
314 const entries = await replayEnv.executor.peekOutbox()
315 return entries.length === 0
316 })
317 expect(replayEnv.serverState.get(`persisted`)?.value).toBe(`from-outbox`)
318
319 replayEnv.executor.dispose()
320 })
321
322 it(`processes mutations sequentially regardless of keys`, async () => {
323 const pendingResolvers: Array<() => void> = []
324 // eslint-disable-next-line prefer-const
325 let env: ReturnType<typeof createTestOfflineEnvironment> | undefined
326
327 const deferredMutation = async (
328 params: OfflineMutationFnParams & { attempt: number },
329 ) => {
330 const runtimeEnv = env
331 if (!runtimeEnv) {
332 throw new Error(`env not initialized`)
333 }
334
335 const mutations = params.transaction.mutations
336
337 await new Promise<void>((resolve) => {
338 pendingResolvers.push(() => {
339 runtimeEnv.applyMutations(mutations)
340 resolve()
341 })
342 })
343
344 return { ok: true, mutations }
345 }
346
347 env = createTestOfflineEnvironment({
348 mutationFn: deferredMutation,
349 })
350
351 const runtimeEnv = env
352
353 await runtimeEnv.waitForLeader()
354
355 const firstTx = runtimeEnv.executor.createOfflineTransaction({
356 mutationFnName: runtimeEnv.mutationFnName,
357 autoCommit: false,
358 })
359 const waitFirst = runtimeEnv.executor.waitForTransactionCompletion(
360 firstTx.id,
361 )
362 firstTx.mutate(() => {
363 runtimeEnv.collection.insert({
364 id: `first`,
365 value: `1`,
366 completed: false,
367 updatedAt: new Date(),
368 })
369 })
370 const commitFirst = firstTx.commit()
371
372 const secondTx = runtimeEnv.executor.createOfflineTransaction({
373 mutationFnName: runtimeEnv.mutationFnName,
374 autoCommit: false,
375 })
376 const waitSecond = runtimeEnv.executor.waitForTransactionCompletion(
377 secondTx.id,
378 )
379 secondTx.mutate(() => {
380 runtimeEnv.collection.insert({
381 id: `second`,
382 value: `2`,
383 completed: false,
384 updatedAt: new Date(),
385 })
386 })
387 const commitSecond = secondTx.commit()
388
389 await flushMicrotasks()
390 // With sequential processing, only one transaction executes at a time
391 expect(runtimeEnv.mutationCalls.length).toBe(1)
392 expect(pendingResolvers.length).toBe(1)
393
394 // Resolve the first transaction
395 pendingResolvers.shift()?.()
396 // Wait for the second transaction to start
397 await waitUntil(() => runtimeEnv.mutationCalls.length >= 2)
398 expect(pendingResolvers.length).toBe(1)
399
400 // Resolve the second transaction
401 pendingResolvers.shift()?.()
402 await Promise.all([commitFirst, commitSecond, waitFirst, waitSecond])
403
404 expect(runtimeEnv.serverState.get(`first`)?.value).toBe(`1`)
405 expect(runtimeEnv.serverState.get(`second`)?.value).toBe(`2`)
406
407 runtimeEnv.executor.dispose()
408 })
409
410 it(`executes transactions online-only when not leader`, async () => {
411 const env = createTestOfflineEnvironment()
412
413 // Set this tab to not be leader
414 env.leader.setLeader(false)
415
416 // Give the executor a moment to react to leadership change
417 await flushMicrotasks()
418
419 // Should not be offline enabled when not leader
420 expect(env.executor.isOfflineEnabled).toBe(false)
421
422 const offlineTx = env.executor.createOfflineTransaction({
423 mutationFnName: env.mutationFnName,
424 autoCommit: false,
425 })
426
427 const now = new Date()
428 offlineTx.mutate(() => {
429 env.collection.insert({
430 id: `non-leader-item`,
431 value: `online-only`,
432 completed: false,
433 updatedAt: now,
434 })
435 })
436
437 // Should execute immediately online without persisting to outbox
438 await offlineTx.commit()
439
440 // Should have called the mutation function
441 expect(env.mutationCalls.length).toBe(1)
442 const call = env.mutationCalls[0]!
443 expect(call.transaction.mutations).toHaveLength(1)
444 expect(call.transaction.mutations[0].key).toBe(`non-leader-item`)
445
446 // Should have applied to both local and server state
447 expect(env.collection.get(`non-leader-item`)?.value).toBe(`online-only`)
448 expect(env.serverState.get(`non-leader-item`)?.value).toBe(`online-only`)
449
450 // Should NOT have persisted to outbox
451 const outboxEntries = await env.executor.peekOutbox()
452 expect(outboxEntries).toEqual([])
453
454 env.executor.dispose()
455 })
456
457 it(`should restore optimistic state to collection on startup`, async () => {
458 // This test verifies that optimistic state IS restored to the collection
459 // when the page is refreshed while offline (e.g., with pending transactions).
460 //
461 // After page refresh, the collection should still show the optimistic data
462 // from pending transactions, providing a seamless offline UX.
463
464 const storage = new FakeStorageAdapter()
465
466 // Create a promise that never resolves - simulates offline/stuck mutation
467 const mutationPromise = () => new Promise<void>(() => {})
468
469 // First environment: Create a transaction that gets stuck (simulating offline)
470 const firstEnv = createTestOfflineEnvironment({
471 storage,
472 mutationFn: async () => {
473 // This mutation will hang forever, simulating offline state
474 await mutationPromise()
475 throw new Error(`Should not reach here in first env`)
476 },
477 })
478
479 await firstEnv.waitForLeader()
480
481 const offlineTx = firstEnv.executor.createOfflineTransaction({
482 mutationFnName: firstEnv.mutationFnName,
483 autoCommit: false,
484 })
485
486 // Apply optimistic update
487 offlineTx.mutate(() => {
488 firstEnv.collection.insert({
489 id: `optimistic-item`,
490 value: `should-persist`,
491 completed: false,
492 updatedAt: new Date(),
493 })
494 })
495
496 // Verify the optimistic update is visible in the collection
497 expect(firstEnv.collection.get(`optimistic-item`)?.value).toBe(
498 `should-persist`,
499 )
500
501 // Start commit - it will persist to outbox and start (but not complete) execution
502 offlineTx.commit()
503
504 // Wait for the transaction to be persisted to outbox
505 await waitUntil(async () => {
506 const pendingEntries = await firstEnv.executor.peekOutbox()
507 return pendingEntries.length === 1
508 }, 5000)
509
510 // Verify it's in the outbox
511 const outboxEntries = await firstEnv.executor.peekOutbox()
512 expect(outboxEntries.length).toBe(1)
513 expect(outboxEntries[0]!.id).toBe(offlineTx.id)
514
515 // Verify the mutation data is properly serialized
516 expect(outboxEntries[0]!.mutations.length).toBe(1)
517 expect(outboxEntries[0]!.mutations[0]!.type).toBe(`insert`)
518
519 // Dispose first environment (simulating page refresh)
520 firstEnv.executor.dispose()
521
522 // Create a new environment with a deferred mutation to control timing
523 let secondEnvResolveMutation: (() => void) | null = null
524 const secondEnvMutationPromise = () =>
525 new Promise<void>((resolve) => {
526 secondEnvResolveMutation = resolve
527 })
528
529 const secondEnv = createTestOfflineEnvironment({
530 storage,
531 mutationFn: async (params) => {
532 // Wait for explicit resolution
533 await secondEnvMutationPromise()
534 const mutations = params.transaction.mutations
535 secondEnv.applyMutations(mutations)
536 return { ok: true, mutations }
537 },
538 })
539
540 await secondEnv.waitForLeader()
541
542 // At this point, the optimistic state should be restored to the collection
543 // The transaction is loaded from storage, and the optimistic mutations
544 // are applied to the collection immediately
545 const restoredItem = secondEnv.collection.get(`optimistic-item`)
546
547 // The optimistic state should be restored from persisted transactions
548 expect(restoredItem?.value).toBe(`should-persist`)
549
550 // Verify the transaction IS still in the outbox (data was persisted correctly)
551 const secondEnvOutbox = await secondEnv.executor.peekOutbox()
552 expect(secondEnvOutbox.length).toBe(1)
553 expect(secondEnvOutbox[0]!.mutations[0]!.type).toBe(`insert`)
554
555 // Now complete the mutation to verify the data eventually syncs
556 secondEnvResolveMutation!()
557
558 await waitUntil(async () => {
559 const entries = await secondEnv.executor.peekOutbox()
560 return entries.length === 0
561 })
562
563 // After sync completes, the item appears (but this is too late for offline UX)
564 expect(secondEnv.serverState.get(`optimistic-item`)?.value).toBe(
565 `should-persist`,
566 )
567
568 secondEnv.executor.dispose()
569 })
570
571 it(`should rollback restored optimistic state on permanent failure after page refresh`, async () => {
572 // This test verifies that optimistic state restored from persisted transactions
573 // is properly rolled back when the transaction fails permanently (NonRetriableError).
574 //
575 // Scenario: User creates transaction offline, refreshes page, transaction fails permanently
576 // Expected: Optimistic state should be visible initially, then removed after failure
577
578 const storage = new FakeStorageAdapter()
579
580 // First environment: Create a transaction that gets stuck (simulating offline)
581 const mutationPromise = () => new Promise<void>(() => {})
582
583 const firstEnv = createTestOfflineEnvironment({
584 storage,
585 mutationFn: async () => {
586 await mutationPromise()
587 throw new Error(`Should not reach here in first env`)
588 },
589 })
590
591 await firstEnv.waitForLeader()
592
593 const offlineTx = firstEnv.executor.createOfflineTransaction({
594 mutationFnName: firstEnv.mutationFnName,
595 autoCommit: false,
596 })
597
598 // Apply optimistic update
599 offlineTx.mutate(() => {
600 firstEnv.collection.insert({
601 id: `ghost-item`,
602 value: `will-fail`,
603 completed: false,
604 updatedAt: new Date(),
605 })
606 })
607
608 // Verify the optimistic update is visible
609 expect(firstEnv.collection.get(`ghost-item`)?.value).toBe(`will-fail`)
610
611 // Start commit - it will persist to outbox
612 offlineTx.commit()
613
614 // Wait for the transaction to be persisted
615 await waitUntil(async () => {
616 const pendingEntries = await firstEnv.executor.peekOutbox()
617 return pendingEntries.length === 1
618 }, 5000)
619
620 // Dispose first environment (simulating page refresh)
621 firstEnv.executor.dispose()
622
623 // Create a new environment where the mutation fails permanently
624 const secondEnv = createTestOfflineEnvironment({
625 storage,
626 mutationFn: () => {
627 throw new NonRetriableError(`Server rejected mutation permanently`)
628 },
629 })
630
631 await secondEnv.waitForLeader()
632
633 // Optimistic state should be restored immediately after initialization
634 expect(secondEnv.collection.get(`ghost-item`)?.value).toBe(`will-fail`)
635
636 // Wait for the transaction to fail and be removed from outbox
637 await waitUntil(async () => {
638 const entries = await secondEnv.executor.peekOutbox()
639 return entries.length === 0
640 }, 5000)
641
642 // After permanent failure, the optimistic state should be rolled back
643 // The item should no longer exist in the collection
644 expect(secondEnv.collection.get(`ghost-item`)).toBeUndefined()
645
646 // And it should not exist on the server either
647 expect(secondEnv.serverState.get(`ghost-item`)).toBeUndefined()
648
649 secondEnv.executor.dispose()
650 })
651})