Open History to see the last commit
1import { beforeEach, describe, expect, it, vi } from 'vitest'
2import { LocalStorageAdapter, startOfflineExecutor } from '../src/index'
3import { FakeStorageAdapter } from './harness'
4import { captureUnhandledRejections } from './oracle-lifecycle'
5import type { OfflineConfig } from '../src/types'
6
7describe(`OfflineExecutor`, () => {
8 let mockCollection: any
9 let mockMutationFn: any
10 let config: OfflineConfig
11
12 beforeEach(() => {
13 mockCollection = {
14 id: `test-collection`,
15 insert: vi.fn(),
16 update: vi.fn(),
17 delete: vi.fn(),
18 }
19
20 mockMutationFn = vi.fn().mockResolvedValue(undefined)
21
22 config = {
23 collections: {
24 'test-collection': mockCollection,
25 },
26 mutationFns: {
27 syncData: mockMutationFn,
28 },
29 storage: new LocalStorageAdapter(),
30 }
31 })
32
33 it(`should create an offline executor`, () => {
34 const executor = startOfflineExecutor(config)
35
36 expect(executor).toBeDefined()
37 expect(executor.isOfflineEnabled).toBeDefined()
38 })
39
40 it(`should create offline transactions`, () => {
41 const executor = startOfflineExecutor(config)
42
43 const transaction = executor.createOfflineTransaction({
44 mutationFnName: `syncData`,
45 })
46
47 expect(transaction).toBeDefined()
48 expect(transaction.id).toBeDefined()
49 })
50
51 it(`should create offline actions`, () => {
52 const executor = startOfflineExecutor(config)
53
54 const action = executor.createOfflineAction({
55 mutationFnName: `syncData`,
56 onMutate: (data: any) => {
57 mockCollection.insert(data)
58 },
59 })
60
61 expect(action).toBeDefined()
62 expect(typeof action).toBe(`function`)
63 })
64
65 it(`should return empty outbox initially`, async () => {
66 const executor = startOfflineExecutor(config)
67
68 const transactions = await executor.peekOutbox()
69
70 expect(transactions).toEqual([])
71 })
72
73 it(`should dispose cleanly`, () => {
74 const executor = startOfflineExecutor(config)
75
76 expect(() => executor.dispose()).not.toThrow()
77 })
78
79 it(`keeps constructor-started initialization failures observable`, async () => {
80 const storageError = new Error(`storage unavailable`)
81 class Storage extends FakeStorageAdapter {
82 override async keys(): Promise<Array<string>> {
83 throw storageError
84 }
85 }
86 const { rejections: unhandled, cleanup: cleanupUnhandled } =
87 captureUnhandledRejections()
88 const warning = vi.spyOn(console, `warn`).mockImplementation(() => {})
89 const executor = startOfflineExecutor({
90 ...config,
91 storage: new Storage(),
92 leaderElection: {
93 requestLeadership: async () => true,
94 releaseLeadership: () => {},
95 isLeader: () => true,
96 onLeadershipChange: () => () => {},
97 },
98 })
99
100 try {
101 await new Promise((resolve) => setTimeout(resolve, 0))
102 expect(unhandled).toEqual([])
103 await expect(executor.waitForInit()).rejects.toBe(storageError)
104 } finally {
105 executor.dispose()
106 warning.mockRestore()
107 cleanupUnhandled()
108 }
109 })
110
111 it(`identifies unreadable rows for targeted removal before restart`, async () => {
112 const storage = new FakeStorageAdapter()
113 const record = (id: string, metadata: Record<string, unknown>) =>
114 JSON.stringify({
115 valueEncoding: 3,
116 id,
117 mutationFnName: `syncData`,
118 mutations: [],
119 keys: [],
120 idempotencyKey: `${id}/once`,
121 createdAt: new Date(0).toISOString(),
122 retryCount: 0,
123 nextAttemptAt: 0,
124 metadata,
125 version: 1,
126 })
127 await storage.set(
128 `tx:native-scalar`,
129 record(`native-scalar`, {
130 due: {
131 __type: `Temporal`,
132 type: `Temporal.PlainDate`,
133 value: `2026-09-16`,
134 },
135 }),
136 )
137 await storage.set(`tx:readable`, record(`readable`, { note: `safe` }))
138 const temporalGlobal = globalThis as {
139 Temporal?: Record<string, unknown>
140 }
141 const previousTemporal = temporalGlobal.Temporal
142 temporalGlobal.Temporal = {}
143 const warning = vi.spyOn(console, `warn`).mockImplementation(() => {})
144 const { rejections: unhandled, cleanup: cleanupUnhandled } =
145 captureUnhandledRejections()
146 const calls: Array<{ id: string; metadata: unknown }> = []
147 let firstExecutor: ReturnType<typeof startOfflineExecutor> | undefined
148 let secondExecutor: ReturnType<typeof startOfflineExecutor> | undefined
149 const leaderElection = {
150 requestLeadership: async () => true,
151 releaseLeadership: () => {},
152 isLeader: () => true,
153 onLeadershipChange: () => () => {},
154 }
155
156 try {
157 mockMutationFn.mockImplementation(
158 ({ transaction }: { transaction: { id: string; metadata: unknown } }) =>
159 calls.push({ id: transaction.id, metadata: transaction.metadata }),
160 )
161 firstExecutor = startOfflineExecutor({
162 ...config,
163 storage,
164 leaderElection,
165 })
166 await expect(firstExecutor.waitForInit()).rejects.toThrow(
167 /transaction native-scalar/,
168 )
169 await new Promise((resolve) => setTimeout(resolve, 0))
170 expect(calls).toEqual([])
171 expect(storage.snapshot()).toHaveProperty(`tx:native-scalar`)
172 expect(storage.snapshot()).toHaveProperty(`tx:readable`)
173 expect(unhandled).toEqual([])
174
175 await firstExecutor.removeFromOutbox(`native-scalar`)
176 firstExecutor.dispose()
177 const recoveredReplay = new Promise<void>((resolve) => {
178 mockMutationFn.mockImplementation(
179 ({
180 transaction,
181 }: {
182 transaction: { id: string; metadata: unknown }
183 }) => {
184 calls.push({ id: transaction.id, metadata: transaction.metadata })
185 if (transaction.id === `readable`) resolve()
186 },
187 )
188 })
189 secondExecutor = startOfflineExecutor({
190 ...config,
191 storage,
192 leaderElection,
193 })
194 const replayCompleted =
195 secondExecutor.waitForTransactionCompletion(`readable`)
196 await expect(secondExecutor.waitForInit()).resolves.toBeUndefined()
197 await recoveredReplay
198 await replayCompleted
199 expect(calls).toEqual([
200 {
201 id: `readable`,
202 metadata: { note: `safe` },
203 },
204 ])
205 expect(storage.snapshot()).toEqual({})
206 expect(warning).toHaveBeenCalledWith(
207 `Failed to initialize offline executor:`,
208 expect.objectContaining({
209 message: expect.stringMatching(/transaction native-scalar/),
210 }),
211 )
212 } finally {
213 firstExecutor?.dispose()
214 secondExecutor?.dispose()
215 cleanupUnhandled()
216 warning.mockRestore()
217 if (previousTemporal === undefined) delete temporalGlobal.Temporal
218 else temporalGlobal.Temporal = previousTemporal
219 }
220 })
221})