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

opfs-worker-diagnostics-oracle.test.ts

372 lines11.6 KB

1import { fc } from '@fast-check/vitest'
2import { afterEach, describe, expect, it, vi } from 'vitest'
3import {
4 oraclePropertyOptions,
5 oracleReplayRequested,
6 oracleReplayTest,
7 oracleRuns,
8} from '../../db/tests/oracle-config'
9import { declareOracle } from '../../db/tests/oracle-declaration'
10import type {
11 BrowserOPFSWorkerRequest,
12 BrowserOPFSWorkerResponse,
13} from '../src/opfs-worker-protocol'
14​
15/**
16 * # Does an OPFS worker classify and explain initialization failure?
17 *
18 * Opening may fail with an Error or TypeError while the VFS exposes a separate
19 * Error or DOMException cause. The worker response must preserve the primary
20 * message and, when present, the cause name and message in stable order.
21 *
22 * The browser can also refuse the OPFS storage root itself: in a private
23 * window, or a browser without OPFS storage, `navigator.storage.getDirectory()`
24 * rejects. That is a capability failure, which the README surfaces as
25 * `PersistenceUnavailableError`, so the worker answers `PERSISTENCE_UNAVAILABLE`
26 * with the browser's error name and message, and SQLite never opens.
27 *
28 * A tiny string-concatenation model supplies the expected response. Generated
29 * error classes and messages drive the real worker module through mocked
30 * wa-sqlite and OPFS boundaries. Exact response comparison catches a dropped,
31 * reordered, or replaced cause, or a capability failure reported as internal,
32 * without claiming native lock behavior.
33 */
34​
35type OpenFailure = {
36 failsAt: `open`
37 primaryKind: `Error` | `TypeError`
38 primaryMessage: string
39 cause: null | {
40 kind: `Error` | `NoModificationAllowedError`
41 message: string
42 }
44​
45type StorageRootFailure = {
46 failsAt: `storage root`
47 kind: `UnknownError` | `SecurityError` | `NotAllowedError`
48 message: string
50​
51type DiagnosticInput = OpenFailure | StorageRootFailure
52​
53const mocks = vi.hoisted(() => ({
54 open: vi.fn(),
55 vfs: { lastError: null as Error | null },
56}))
57​
58vi.mock('@journeyapps/wa-sqlite/dist/wa-sqlite.mjs', () => ({
59 default: () => Promise.resolve({}),
60}))
61vi.mock('@journeyapps/wa-sqlite', () => ({
62 Factory: () => ({ open_v2: mocks.open, vfs_register: vi.fn() }),
63 SQLITE_OPEN_CREATE: 4,
64 SQLITE_OPEN_READWRITE: 2,
65 SQLITE_OPEN_URI: 64,
66}))
67// Like the real VFS, creation acquires the OPFS storage root.
68vi.mock('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js', () => ({
69 OPFSCoopSyncVFS: {
70 create: async () => {
71 await navigator.storage.getDirectory()
72 return mocks.vfs
73 },
74 },
75}))
76​
77function makePrimary(input: OpenFailure): Error {
78 return input.primaryKind === `TypeError`
79 ? new TypeError(input.primaryMessage)
80 : new Error(input.primaryMessage)
82​
83function makeCause(input: OpenFailure): Error | null {
84 if (!input.cause) return null
85 return input.cause.kind === `NoModificationAllowedError`
86 ? new DOMException(input.cause.message, input.cause.kind)
87 : new Error(input.cause.message)
89​
90function referenceMessage(input: OpenFailure): string {
91 const fields = [input.primaryMessage]
92 if (input.cause) {
93 fields.push(input.cause.kind, input.cause.message)
94 }
95 return fields.join(`: `)
97​
98// The expected response, and whether SQLite open is reached.
99function referenceResponse(input: DiagnosticInput): {
100 response: BrowserOPFSWorkerResponse
101 opens: boolean
102} {
103 return input.failsAt === `storage root`
104 ? {
105 response: {
106 type: `response`,
107 requestId: `diagnostic-oracle`,
108 ok: false,
109 code: `PERSISTENCE_UNAVAILABLE`,
110 // The protocol carries details; the opener adds the class's prefix.
111 error: `OPFS storage is unavailable: ${input.kind}: ${input.message}`,
112 },
113 opens: false,
114 }
115 : {
116 response: {
117 type: `response`,
118 requestId: `diagnostic-oracle`,
119 ok: false,
120 code: `INTERNAL`,
121 error: referenceMessage(input),
122 },
123 opens: true,
124 }
126​
127async function initialize(
128 input: DiagnosticInput,
129): Promise<BrowserOPFSWorkerResponse> {
130 const primary = input.failsAt === `open` ? makePrimary(input) : null
131 const cause = input.failsAt === `open` ? makeCause(input) : null
132 let receive:
133 ((event: MessageEvent<BrowserOPFSWorkerRequest>) => void) | undefined
134 vi.resetModules()
135 mocks.open.mockReset()
136 mocks.open.mockRejectedValue(primary)
137 mocks.vfs.lastError = cause
138 vi.stubGlobal(`navigator`, {
139 storage: {
140 getDirectory: () =>
141 input.failsAt === `storage root`
142 ? Promise.reject(new DOMException(input.message, input.kind))
143 : Promise.resolve({}),
144 },
145 })
146 vi.stubGlobal(`FileSystemFileHandle`, {
147 prototype: { createSyncAccessHandle: () => Promise.resolve({}) },
148 })
149 vi.stubGlobal(
150 `addEventListener`,
151 (
152 _type: string,
153 listener: (event: MessageEvent<BrowserOPFSWorkerRequest>) => void,
154 ) => {
155 receive = listener
156 },
157 )
158 const response = new Promise<BrowserOPFSWorkerResponse>((resolve) => {
159 vi.stubGlobal(`postMessage`, resolve)
160 })
161​
162 await import('../src/opfs-worker')
163 receive?.({
164 data: {
165 requestId: `diagnostic-oracle`,
166 type: `init`,
167 databaseName: `locked.sqlite`,
168 vfsName: `opfs`,
169 wasmUrl: `https://example.test/wa-sqlite.wasm`,
170 packageVersion: `source`,
171 },
172 } as MessageEvent<BrowserOPFSWorkerRequest>)
173​
174 const result = await response
175 // Reach: SQLite open runs exactly when the model says it is reached.
176 expect(mocks.open).toHaveBeenCalledTimes(
177 referenceResponse(input).opens ? 1 : 0,
178 )
179 return result
181​
182afterEach(() => {
183 vi.unstubAllGlobals()
184 vi.resetAllMocks()
185 vi.resetModules()
186 mocks.vfs.lastError = null
187})
188​
189const message = fc
190 .array(fc.constantFrom(...`abcXYZ019 _/-.[]:`), {
191 minLength: 1,
192 maxLength: 12,
193 })
194 .map((characters) => characters.join(``))
195​
196const openFailure: fc.Arbitrary<DiagnosticInput> = fc.record({
197 failsAt: fc.constant(`open` as const),
198 primaryKind: fc.constantFrom<OpenFailure[`primaryKind`]>(
199 `Error`,
200 `TypeError`,
201 ),
202 primaryMessage: message,
203 cause: fc.option(
204 fc.record({
205 kind: fc.constantFrom<NonNullable<OpenFailure[`cause`]>[`kind`]>(
206 `Error`,
207 `NoModificationAllowedError`,
208 ),
209 message,
210 }),
211 { nil: null },
212 ),
213})
214​
215const storageRootFailure: fc.Arbitrary<DiagnosticInput> = fc.record({
216 failsAt: fc.constant(`storage root` as const),
217 kind: fc.constantFrom<StorageRootFailure[`kind`]>(
218 `UnknownError`,
219 `SecurityError`,
220 `NotAllowedError`,
221 ),
222 message,
223})
224​
225const diagnosticInput = fc.oneof(openFailure, storageRootFailure)
226​
227const diagnosticProperty = `opfs-worker.diagnostics`
228const diagnosticRuns = 40
229// A path replay of this property runs only the random campaign, from its
230// recorded history, once. A seed without a path reseeds the random campaign
231// and keeps the fixed one.
232const diagnosticExamples: Array<[DiagnosticInput]> = [
233 // WebKit without OPFS storage rejects the root with this exact error.
234 [
235 {
236 failsAt: `storage root`,
237 kind: `UnknownError`,
238 message: `The operation failed for an unknown transient reason (e.g. out of memory).`,
239 },
240 ],
241 [{ failsAt: `storage root`, kind: `SecurityError`, message: `denied` }],
242 [
243 {
244 failsAt: `open`,
245 primaryKind: `Error`,
246 primaryMessage: `original open failure`,
247 cause: null,
248 },
249 ],
250 [
251 {
252 failsAt: `open`,
253 primaryKind: `TypeError`,
254 primaryMessage: `typed open failure`,
255 cause: null,
256 },
257 ],
258 [
259 {
260 failsAt: `open`,
261 primaryKind: `Error`,
262 primaryMessage: `sqlite3_open_v2`,
263 cause: { kind: `Error`, message: `plain VFS failure` },
264 },
265 ],
266 [
267 {
268 failsAt: `open`,
269 primaryKind: `TypeError`,
270 primaryMessage: `typed open failure`,
271 cause: { kind: `Error`, message: `plain VFS failure` },
272 },
273 ],
274 [
275 {
276 failsAt: `open`,
277 primaryKind: `Error`,
278 primaryMessage: `sqlite3_open_v2`,
279 cause: {
280 kind: `NoModificationAllowedError`,
281 message: `Access handle is locked [/locked.sqlite-wal]`,
282 },
283 },
284 ],
285 [
286 {
287 failsAt: `open`,
288 primaryKind: `TypeError`,
289 primaryMessage: `typed open failure`,
290 cause: {
291 kind: `NoModificationAllowedError`,
292 message: `access handle locked`,
293 },
294 },
295 ],
297​
298async function checkDiagnostic(input: DiagnosticInput): Promise<void> {
299 expect(await initialize(input)).toEqual(referenceResponse(input).response)
301​
302/*
303Law/source: the README Notes section promises that SQLite open failures include
304the underlying VFS error name/message when available; without one, the primary
305error is preserved. The worker protocol owns the INTERNAL classification. The
306README surfaces OPFS capability failures as PersistenceUnavailableError, so a
307rejected storage root answers PERSISTENCE_UNAVAILABLE before SQLite opens.
308Domain: generated safe primary/cause messages, Error and TypeError primaries,
309plain Error and NoModificationAllowedError causes, plus no cause; and a storage
310root rejected with UnknownError, SecurityError, or NotAllowedError.
311Reference/path/checkpoint: expected text is projected from immutable scalar
312input before Error objects cross the production boundary. A field-list model is
313compared to the complete response after the real init-message handler observes
314a mocked open_v2 rejection; call reach is asserted.
315Observed: exact response kind, request ID, status, error code, and text. Mocked
316wasm/VFS objects do not prove native open or handle release, and this does not
317cover the separate upstream partial-open race.
318Grammar: the bounded message alphabet has lengths 1–12; the six open-failure
319examples reconstruct every primary kind × absent/plain/DOMException cause
320class, and two storage-root examples include WebKit's exact UnknownError. A
321non-Error cause is outside this promise. Removing either class or the absent
322case loses one of those fixed witnesses.
323Challenge/replay: the present-cause examples reject a response that drops the
324cause; the absent-cause examples reject an invented cause. Pinned examples run
325separately so both generated campaigns share one property and budget, and a
326reported shrink path selects its generated case directly. Verbose FastCheck
327output retains original/reduced traces. Set
328TANSTACK_DB_ORACLE_SEED, TANSTACK_DB_ORACLE_PATH, and
329TANSTACK_DB_ORACLE_PROPERTY=opfs-worker.diagnostics for direct replay.
330TANSTACK_DB_ORACLE_RUNS_MULTIPLIER scales the generated campaign.
331*/
332declareOracle({ check: [checkDiagnostic], model: [referenceMessage] })
333​
334describe(`OPFS worker diagnostics oracle`, () => {
335 if (!oracleReplayRequested()) {
336 it.each(diagnosticExamples)(
337 `preserves the pinned open-failure diagnostic (%#)`,
338 checkDiagnostic,
339 )
340 }
341​
342 it.skipIf(oracleReplayRequested())(
343 `rejects a diagnostic that drops an exposed VFS cause`,
344 async () => {
345 const input = diagnosticExamples[6]![0] as OpenFailure
346 const response = await initialize(input)
347 const expected = referenceResponse(input).response
348​
349 expect(response).toEqual(expected)
350 expect({ ...response, error: input.primaryMessage }).not.toEqual(expected)
351 },
352 )
353​
354 const checkDiagnostics = (options: { numRuns: number; seed?: number }) =>
355 fc.assert(fc.asyncProperty(diagnosticInput, checkDiagnostic), {
356 ...options,
357 verbose: true,
358 })
359 oracleReplayTest(it)(
360 `matches the independent diagnostic formatter (fixed campaign)`,
361 () => checkDiagnostics({ seed: 1846, numRuns: oracleRuns(diagnosticRuns) }),
362 15_000,
363 )
364 oracleReplayTest(it, diagnosticProperty)(
365 `matches the independent diagnostic formatter (random campaign)`,
366 () =>
367 checkDiagnostics(
368 oraclePropertyOptions(diagnosticRuns, diagnosticProperty),
369 ),
370 15_000,
371 )
372})