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

OfflineExecutor.test.ts

222 lines6.7 KB

1import { beforeEach, describe, expect, it, vi } from 'vitest'
2import { LocalStorageAdapter, startOfflineExecutor } from '../src/index'
3import { FakeStorageAdapter } from './harness'
4import type { OfflineConfig } from '../src/types'
5​
6describe(`OfflineExecutor`, () => {
7 let mockCollection: any
8 let mockMutationFn: any
9 let config: OfflineConfig
10​
11 beforeEach(() => {
12 mockCollection = {
13 id: `test-collection`,
14 insert: vi.fn(),
15 update: vi.fn(),
16 delete: vi.fn(),
17 }
18​
19 mockMutationFn = vi.fn().mockResolvedValue(undefined)
20​
21 config = {
22 collections: {
23 'test-collection': mockCollection,
24 },
25 mutationFns: {
26 syncData: mockMutationFn,
27 },
28 storage: new LocalStorageAdapter(),
29 }
30 })
31​
32 it(`should create an offline executor`, () => {
33 const executor = startOfflineExecutor(config)
34​
35 expect(executor).toBeDefined()
36 expect(executor.isOfflineEnabled).toBeDefined()
37 })
38​
39 it(`should create offline transactions`, () => {
40 const executor = startOfflineExecutor(config)
41​
42 const transaction = executor.createOfflineTransaction({
43 mutationFnName: `syncData`,
44 })
45​
46 expect(transaction).toBeDefined()
47 expect(transaction.id).toBeDefined()
48 })
49​
50 it(`should create offline actions`, () => {
51 const executor = startOfflineExecutor(config)
52​
53 const action = executor.createOfflineAction({
54 mutationFnName: `syncData`,
55 onMutate: (data: any) => {
56 mockCollection.insert(data)
57 },
58 })
59​
60 expect(action).toBeDefined()
61 expect(typeof action).toBe(`function`)
62 })
63​
64 it(`should return empty outbox initially`, async () => {
65 const executor = startOfflineExecutor(config)
66​
67 const transactions = await executor.peekOutbox()
68​
69 expect(transactions).toEqual([])
70 })
71​
72 it(`should dispose cleanly`, () => {
73 const executor = startOfflineExecutor(config)
74​
75 expect(() => executor.dispose()).not.toThrow()
76 })
77​
78 it(`keeps constructor-started initialization failures observable`, async () => {
79 const storageError = new Error(`storage unavailable`)
80 class Storage extends FakeStorageAdapter {
81 override async keys(): Promise<Array<string>> {
82 throw storageError
83 }
84 }
85 const unhandled: Array<unknown> = []
86 const onUnhandled = (error: unknown) => unhandled.push(error)
87 process.on(`unhandledRejection`, onUnhandled)
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 process.off(`unhandledRejection`, onUnhandled)
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 unhandled: Array<unknown> = []
145 const onUnhandled = (error: unknown) => unhandled.push(error)
146 process.on(`unhandledRejection`, onUnhandled)
147 const calls: Array<{ id: string; metadata: unknown }> = []
148 let firstExecutor: ReturnType<typeof startOfflineExecutor> | undefined
149 let secondExecutor: ReturnType<typeof startOfflineExecutor> | undefined
150 const leaderElection = {
151 requestLeadership: async () => true,
152 releaseLeadership: () => {},
153 isLeader: () => true,
154 onLeadershipChange: () => () => {},
155 }
156​
157 try {
158 mockMutationFn.mockImplementation(
159 ({ transaction }: { transaction: { id: string; metadata: unknown } }) =>
160 calls.push({ id: transaction.id, metadata: transaction.metadata }),
161 )
162 firstExecutor = startOfflineExecutor({
163 ...config,
164 storage,
165 leaderElection,
166 })
167 await expect(firstExecutor.waitForInit()).rejects.toThrow(
168 /transaction native-scalar/,
169 )
170 await new Promise((resolve) => setTimeout(resolve, 0))
171 expect(calls).toEqual([])
172 expect(storage.snapshot()).toHaveProperty(`tx:native-scalar`)
173 expect(storage.snapshot()).toHaveProperty(`tx:readable`)
174 expect(unhandled).toEqual([])
175​
176 await firstExecutor.removeFromOutbox(`native-scalar`)
177 firstExecutor.dispose()
178 const recoveredReplay = new Promise<void>((resolve) => {
179 mockMutationFn.mockImplementation(
180 ({
181 transaction,
182 }: {
183 transaction: { id: string; metadata: unknown }
184 }) => {
185 calls.push({ id: transaction.id, metadata: transaction.metadata })
186 if (transaction.id === `readable`) resolve()
187 },
188 )
189 })
190 secondExecutor = startOfflineExecutor({
191 ...config,
192 storage,
193 leaderElection,
194 })
195 const replayCompleted =
196 secondExecutor.waitForTransactionCompletion(`readable`)
197 await expect(secondExecutor.waitForInit()).resolves.toBeUndefined()
198 await recoveredReplay
199 await replayCompleted
200 expect(calls).toEqual([
201 {
202 id: `readable`,
203 metadata: { note: `safe` },
204 },
205 ])
206 expect(storage.snapshot()).toEqual({})
207 expect(warning).toHaveBeenCalledWith(
208 `Failed to initialize offline executor:`,
209 expect.objectContaining({
210 message: expect.stringMatching(/transaction native-scalar/),
211 }),
212 )
213 } finally {
214 firstExecutor?.dispose()
215 secondExecutor?.dispose()
216 process.off(`unhandledRejection`, onUnhandled)
217 warning.mockRestore()
218 if (previousTemporal === undefined) delete temporalGlobal.Temporal
219 else temporalGlobal.Temporal = previousTemporal
220 }
221 })
222})