Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { createCollection } from '@tanstack/db'
3import {
4 IndexedDBAdapter,
5 LocalStorageAdapter,
6 startOfflineExecutor,
7} from '../src/index'
8import type { OfflineConfig, StorageDiagnostic } from '../src/types'
9
10const waitUntil = async (
11 predicate: () => boolean | Promise<boolean>,
12 timeoutMs = 5000,
13 intervalMs = 20,
14) => {
15 const deadline = Date.now() + timeoutMs
16 while (Date.now() < deadline) {
17 if (await predicate()) {
18 return
19 }
20 await new Promise((resolve) => setTimeout(resolve, intervalMs))
21 }
22 throw new Error(`Timed out waiting for condition`)
23}
24
25describe(`storage failure handling`, () => {
26 let mockCollection: any
27 let mockMutationFn: any
28 let baseConfig: OfflineConfig
29
30 beforeEach(() => {
31 mockCollection = createCollection({
32 id: `test-collection`,
33 getKey: (item: any) => item.id,
34 sync: {
35 sync: () => {},
36 },
37 })
38
39 mockMutationFn = vi.fn().mockResolvedValue(undefined)
40
41 baseConfig = {
42 collections: {
43 'test-collection': mockCollection,
44 },
45 mutationFns: {
46 syncData: mockMutationFn,
47 },
48 }
49 })
50
51 afterEach(() => {
52 vi.restoreAllMocks()
53 })
54
55 it(`falls back to localStorage when IndexedDB fails with SecurityError`, async () => {
56 // Mock IndexedDB to fail with SecurityError
57 const securityError = new Error(`IndexedDB blocked`)
58 securityError.name = `SecurityError`
59
60 vi.spyOn(IndexedDBAdapter, `probe`).mockResolvedValue({
61 available: false,
62 error: securityError,
63 })
64
65 // Mock localStorage to succeed
66 vi.spyOn(LocalStorageAdapter, `probe`).mockReturnValue({
67 available: true,
68 })
69
70 const executor = startOfflineExecutor(baseConfig)
71
72 // Wait for initialization to complete
73 await waitUntil(
74 () => executor.storageDiagnostic.message !== `Initializing storage...`,
75 )
76
77 // Should be in offline mode using localStorage
78 expect(executor.mode).toBe(`offline`)
79 expect(executor.storageDiagnostic.code).toBe(`INDEXEDDB_UNAVAILABLE`)
80 expect(executor.storageDiagnostic.message).toContain(
81 `localStorage fallback`,
82 )
83 expect(executor.storageDiagnostic.error).toBe(securityError)
84
85 executor.dispose()
86 })
87
88 it(`goes online-only when both storage types fail with SecurityError`, async () => {
89 const idbSecurityError = new Error(`IndexedDB blocked`)
90 idbSecurityError.name = `SecurityError`
91
92 const lsSecurityError = new Error(`localStorage blocked`)
93 lsSecurityError.name = `SecurityError`
94
95 vi.spyOn(IndexedDBAdapter, `probe`).mockResolvedValue({
96 available: false,
97 error: idbSecurityError,
98 })
99
100 vi.spyOn(LocalStorageAdapter, `probe`).mockReturnValue({
101 available: false,
102 error: lsSecurityError,
103 })
104
105 let capturedDiagnostic: StorageDiagnostic | undefined
106
107 const config: OfflineConfig = {
108 ...baseConfig,
109 onStorageFailure: (diagnostic) => {
110 capturedDiagnostic = diagnostic
111 },
112 }
113
114 const executor = startOfflineExecutor(config)
115
116 await waitUntil(
117 () => executor.storageDiagnostic.message !== `Initializing storage...`,
118 )
119
120 // Should be in online-only mode
121 expect(executor.mode).toBe(`online-only`)
122 expect(executor.storageDiagnostic.code).toBe(`STORAGE_BLOCKED`)
123 expect(executor.storageDiagnostic.message).toContain(`private mode`)
124 expect(executor.isOfflineEnabled).toBe(false)
125
126 // onStorageFailure callback should have been called
127 expect(capturedDiagnostic).toBeDefined()
128 expect(capturedDiagnostic?.code).toBe(`STORAGE_BLOCKED`)
129
130 executor.dispose()
131 })
132
133 it(`goes online-only when storage quota is exceeded`, async () => {
134 const idbQuotaError = new Error(`Quota exceeded`)
135 idbQuotaError.name = `QuotaExceededError`
136
137 const lsQuotaError = new Error(`Quota exceeded`)
138 lsQuotaError.name = `QuotaExceededError`
139
140 vi.spyOn(IndexedDBAdapter, `probe`).mockResolvedValue({
141 available: false,
142 error: idbQuotaError,
143 })
144
145 vi.spyOn(LocalStorageAdapter, `probe`).mockReturnValue({
146 available: false,
147 error: lsQuotaError,
148 })
149
150 let capturedDiagnostic: StorageDiagnostic | undefined
151
152 const config: OfflineConfig = {
153 ...baseConfig,
154 onStorageFailure: (diagnostic) => {
155 capturedDiagnostic = diagnostic
156 },
157 }
158
159 const executor = startOfflineExecutor(config)
160
161 await waitUntil(
162 () => executor.storageDiagnostic.message !== `Initializing storage...`,
163 )
164
165 // Should be in online-only mode with QUOTA_EXCEEDED
166 expect(executor.mode).toBe(`online-only`)
167 expect(executor.storageDiagnostic.code).toBe(`QUOTA_EXCEEDED`)
168 expect(executor.storageDiagnostic.message).toContain(`quota exceeded`)
169
170 // onStorageFailure callback should have been called
171 expect(capturedDiagnostic).toBeDefined()
172 expect(capturedDiagnostic?.code).toBe(`QUOTA_EXCEEDED`)
173
174 executor.dispose()
175 })
176
177 it(`goes online-only with unknown error for other storage failures`, async () => {
178 const idbUnknownError = new Error(`Something went wrong`)
179 idbUnknownError.name = `InvalidStateError`
180
181 const lsUnknownError = new Error(`Something else went wrong`)
182
183 vi.spyOn(IndexedDBAdapter, `probe`).mockResolvedValue({
184 available: false,
185 error: idbUnknownError,
186 })
187
188 vi.spyOn(LocalStorageAdapter, `probe`).mockReturnValue({
189 available: false,
190 error: lsUnknownError,
191 })
192
193 const executor = startOfflineExecutor(baseConfig)
194
195 await waitUntil(
196 () => executor.storageDiagnostic.message !== `Initializing storage...`,
197 )
198
199 // Should be in online-only mode with UNKNOWN_ERROR
200 expect(executor.mode).toBe(`online-only`)
201 expect(executor.storageDiagnostic.code).toBe(`UNKNOWN_ERROR`)
202 expect(executor.storageDiagnostic.message).toContain(`unknown error`)
203
204 executor.dispose()
205 })
206
207 it(`bypasses probe when custom storage adapter is provided`, async () => {
208 const probeSpy = vi.spyOn(IndexedDBAdapter, `probe`)
209 const lsProbeSpy = vi.spyOn(LocalStorageAdapter, `probe`)
210
211 // Create a custom storage adapter
212 const customStorage = {
213 get: vi.fn().mockResolvedValue(null),
214 set: vi.fn().mockResolvedValue(undefined),
215 delete: vi.fn().mockResolvedValue(undefined),
216 keys: vi.fn().mockResolvedValue([]),
217 clear: vi.fn().mockResolvedValue(undefined),
218 }
219
220 const config: OfflineConfig = {
221 ...baseConfig,
222 storage: customStorage,
223 }
224
225 const executor = startOfflineExecutor(config)
226
227 await waitUntil(
228 () => executor.storageDiagnostic.message !== `Initializing storage...`,
229 )
230
231 // Should be in offline mode
232 expect(executor.mode).toBe(`offline`)
233 expect(executor.storageDiagnostic.code).toBe(`STORAGE_AVAILABLE`)
234 expect(executor.storageDiagnostic.message).toContain(`custom storage`)
235
236 // Probe methods should NOT have been called
237 expect(probeSpy).not.toHaveBeenCalled()
238 expect(lsProbeSpy).not.toHaveBeenCalled()
239
240 executor.dispose()
241 })
242
243 it(`executes transactions online-only when storage fails`, async () => {
244 // Force both storage types to fail
245 const error = new Error(`Storage blocked`)
246 error.name = `SecurityError`
247
248 vi.spyOn(IndexedDBAdapter, `probe`).mockResolvedValue({
249 available: false,
250 error,
251 })
252
253 vi.spyOn(LocalStorageAdapter, `probe`).mockReturnValue({
254 available: false,
255 error,
256 })
257
258 let mutationCalled = false
259 const mutationFn = vi.fn().mockImplementation(() => {
260 mutationCalled = true
261 return Promise.resolve({ ok: true })
262 })
263
264 const config: OfflineConfig = {
265 ...baseConfig,
266 mutationFns: {
267 syncData: mutationFn,
268 },
269 }
270
271 const executor = startOfflineExecutor(config)
272
273 await waitUntil(() => executor.mode === `online-only`)
274
275 // Create and execute a transaction
276 const tx = executor.createOfflineTransaction({
277 mutationFnName: `syncData`,
278 autoCommit: false,
279 })
280
281 tx.mutate(() => {
282 mockCollection.insert({ id: `test-1`, value: `test` })
283 })
284
285 await tx.commit()
286
287 // Transaction should have executed immediately
288 expect(mutationCalled).toBe(true)
289 expect(mutationFn).toHaveBeenCalledOnce()
290
291 // Should NOT be in outbox (no storage available)
292 const outbox = await executor.peekOutbox()
293 expect(outbox).toEqual([])
294
295 executor.dispose()
296 })
297
298 it(`allows transactions to succeed even without outbox persistence`, async () => {
299 // Simulate storage failure
300 const error = new Error(`Storage unavailable`)
301 error.name = `SecurityError`
302
303 vi.spyOn(IndexedDBAdapter, `probe`).mockResolvedValue({
304 available: false,
305 error,
306 })
307
308 vi.spyOn(LocalStorageAdapter, `probe`).mockReturnValue({
309 available: false,
310 error,
311 })
312
313 const results: Array<string> = []
314
315 const mutationFn = vi.fn().mockImplementation(() => {
316 results.push(`mutation-executed`)
317 return Promise.resolve({ ok: true })
318 })
319
320 const config: OfflineConfig = {
321 ...baseConfig,
322 mutationFns: {
323 syncData: mutationFn,
324 },
325 }
326
327 const executor = startOfflineExecutor(config)
328
329 await waitUntil(() => executor.mode === `online-only`)
330
331 // Create multiple transactions
332 const tx1 = executor.createOfflineTransaction({
333 mutationFnName: `syncData`,
334 autoCommit: false,
335 })
336 tx1.mutate(() => {
337 mockCollection.insert({ id: `test-1`, value: `first` })
338 })
339
340 const tx2 = executor.createOfflineTransaction({
341 mutationFnName: `syncData`,
342 autoCommit: false,
343 })
344 tx2.mutate(() => {
345 mockCollection.insert({ id: `test-2`, value: `second` })
346 })
347
348 // Both should execute and complete
349 await tx1.commit()
350 await tx2.commit()
351
352 expect(results).toHaveLength(2)
353 expect(mutationFn).toHaveBeenCalledTimes(2)
354
355 executor.dispose()
356 })
357
358 it(`handles mixed failure scenarios - IndexedDB generic error, localStorage SecurityError`, async () => {
359 const idbError = new Error(`Database corrupted`)
360 idbError.name = `DatabaseError`
361
362 const lsError = new Error(`localStorage blocked`)
363 lsError.name = `SecurityError`
364
365 vi.spyOn(IndexedDBAdapter, `probe`).mockResolvedValue({
366 available: false,
367 error: idbError,
368 })
369
370 vi.spyOn(LocalStorageAdapter, `probe`).mockReturnValue({
371 available: false,
372 error: lsError,
373 })
374
375 const executor = startOfflineExecutor(baseConfig)
376
377 await waitUntil(
378 () => executor.storageDiagnostic.message !== `Initializing storage...`,
379 )
380
381 // Should detect SecurityError and use STORAGE_BLOCKED
382 expect(executor.mode).toBe(`online-only`)
383 expect(executor.storageDiagnostic.code).toBe(`STORAGE_BLOCKED`)
384
385 executor.dispose()
386 })
387})