Open History to see the last commit
1import { fc } from '@fast-check/vitest'
2import { afterEach, describe, expect, it, vi } from 'vitest'
3import type {
4 BrowserOPFSWorkerRequest,
5 BrowserOPFSWorkerResponse,
6} from '../src/opfs-worker-protocol'
7
8/**
9 * # Does an OPFS worker retain the useful cause of initialization failure?
10 *
11 * Opening may fail with an Error or TypeError while the VFS exposes a separate
12 * Error or DOMException cause. The worker response must preserve the primary
13 * message and, when present, the cause name and message in stable order.
14 *
15 * A tiny string-concatenation model supplies the expected diagnostic. Generated
16 * error classes and messages drive the real worker module through mocked
17 * wa-sqlite and OPFS boundaries. Exact response comparison catches a dropped,
18 * reordered, or replaced cause without claiming native lock behavior.
19 */
20
21type DiagnosticInput = {
22 primaryKind: `Error` | `TypeError`
23 primaryMessage: string
24 cause: null | {
25 kind: `Error` | `NoModificationAllowedError`
26 message: string
27 }
28}
29
30const mocks = vi.hoisted(() => ({
31 open: vi.fn(),
32 vfs: { lastError: null as Error | null },
33}))
34
35vi.mock('@journeyapps/wa-sqlite/dist/wa-sqlite.mjs', () => ({
36 default: () => Promise.resolve({}),
37}))
38vi.mock('@journeyapps/wa-sqlite', () => ({
39 Factory: () => ({ open_v2: mocks.open, vfs_register: vi.fn() }),
40 SQLITE_OPEN_CREATE: 4,
41 SQLITE_OPEN_READWRITE: 2,
42 SQLITE_OPEN_URI: 64,
43}))
44vi.mock('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js', () => ({
45 OPFSCoopSyncVFS: { create: () => Promise.resolve(mocks.vfs) },
46}))
47
48function makePrimary(input: DiagnosticInput): Error {
49 return input.primaryKind === `TypeError`
50 ? new TypeError(input.primaryMessage)
51 : new Error(input.primaryMessage)
52}
53
54function makeCause(input: DiagnosticInput): Error | null {
55 if (!input.cause) return null
56 return input.cause.kind === `NoModificationAllowedError`
57 ? new DOMException(input.cause.message, input.cause.kind)
58 : new Error(input.cause.message)
59}
60
61function referenceMessage(input: DiagnosticInput): string {
62 const fields = [input.primaryMessage]
63 if (input.cause) {
64 fields.push(input.cause.kind, input.cause.message)
65 }
66 return fields.join(`: `)
67}
68
69async function initialize(
70 primary: Error,
71 cause: Error | null,
72): Promise<BrowserOPFSWorkerResponse> {
73 let receive:
74 | ((event: MessageEvent<BrowserOPFSWorkerRequest>) => void)
75 | undefined
76 vi.resetModules()
77 mocks.open.mockReset()
78 mocks.open.mockRejectedValue(primary)
79 mocks.vfs.lastError = cause
80 vi.stubGlobal(`navigator`, {
81 storage: { getDirectory: () => Promise.resolve({}) },
82 })
83 vi.stubGlobal(`FileSystemFileHandle`, {
84 prototype: { createSyncAccessHandle: () => Promise.resolve({}) },
85 })
86 vi.stubGlobal(
87 `addEventListener`,
88 (
89 _type: string,
90 listener: (event: MessageEvent<BrowserOPFSWorkerRequest>) => void,
91 ) => {
92 receive = listener
93 },
94 )
95 const response = new Promise<BrowserOPFSWorkerResponse>((resolve) => {
96 vi.stubGlobal(`postMessage`, resolve)
97 })
98
99 await import('../src/opfs-worker')
100 receive?.({
101 data: {
102 requestId: `diagnostic-oracle`,
103 type: `init`,
104 databaseName: `locked.sqlite`,
105 vfsName: `opfs`,
106 },
107 } as MessageEvent<BrowserOPFSWorkerRequest>)
108
109 const result = await response
110 expect(mocks.open).toHaveBeenCalledOnce()
111 return result
112}
113
114afterEach(() => {
115 vi.unstubAllGlobals()
116 vi.resetAllMocks()
117 vi.resetModules()
118 mocks.vfs.lastError = null
119})
120
121const message = fc
122 .array(fc.constantFrom(...`abcXYZ019 _/-.[]:`), {
123 minLength: 1,
124 maxLength: 12,
125 })
126 .map((characters) => characters.join(``))
127
128const diagnosticInput = fc.record({
129 primaryKind: fc.constantFrom<DiagnosticInput[`primaryKind`]>(
130 `Error`,
131 `TypeError`,
132 ),
133 primaryMessage: message,
134 cause: fc.option(
135 fc.record({
136 kind: fc.constantFrom<NonNullable<DiagnosticInput[`cause`]>[`kind`]>(
137 `Error`,
138 `NoModificationAllowedError`,
139 ),
140 message,
141 }),
142 { nil: null },
143 ),
144})
145
146const replaySeed = process.env.TANSTACK_DB_OPFS_DIAGNOSTIC_ORACLE_SEED
147const diagnosticSeed = Number(replaySeed ?? 1846)
148const diagnosticRuns = Number(
149 process.env.TANSTACK_DB_OPFS_DIAGNOSTIC_ORACLE_RUNS ?? 40,
150)
151const diagnosticPath = process.env.TANSTACK_DB_OPFS_DIAGNOSTIC_ORACLE_PATH
152const replayRequested = replaySeed !== undefined || diagnosticPath !== undefined
153const campaigns = replayRequested
154 ? [{ name: `replay`, seed: diagnosticSeed }]
155 : [
156 { name: `fixed`, seed: diagnosticSeed },
157 { name: `random`, seed: undefined },
158 ]
159
160const diagnosticExamples: Array<[DiagnosticInput]> = [
161 [
162 {
163 primaryKind: `Error`,
164 primaryMessage: `original open failure`,
165 cause: null,
166 },
167 ],
168 [
169 {
170 primaryKind: `TypeError`,
171 primaryMessage: `typed open failure`,
172 cause: null,
173 },
174 ],
175 [
176 {
177 primaryKind: `Error`,
178 primaryMessage: `sqlite3_open_v2`,
179 cause: { kind: `Error`, message: `plain VFS failure` },
180 },
181 ],
182 [
183 {
184 primaryKind: `TypeError`,
185 primaryMessage: `typed open failure`,
186 cause: { kind: `Error`, message: `plain VFS failure` },
187 },
188 ],
189 [
190 {
191 primaryKind: `Error`,
192 primaryMessage: `sqlite3_open_v2`,
193 cause: {
194 kind: `NoModificationAllowedError`,
195 message: `Access handle is locked [/locked.sqlite-wal]`,
196 },
197 },
198 ],
199 [
200 {
201 primaryKind: `TypeError`,
202 primaryMessage: `typed open failure`,
203 cause: {
204 kind: `NoModificationAllowedError`,
205 message: `access handle locked`,
206 },
207 },
208 ],
209]
210
211async function checkDiagnostic(input: DiagnosticInput): Promise<void> {
212 const expectedMessage = referenceMessage(input)
213 const primary = makePrimary(input)
214 const cause = makeCause(input)
215
216 expect(await initialize(primary, cause)).toEqual({
217 type: `response`,
218 requestId: `diagnostic-oracle`,
219 ok: false,
220 code: `INTERNAL`,
221 error: expectedMessage,
222 })
223}
224
225/*
226Law/source: the README Notes section promises that SQLite open failures include
227the underlying VFS error name/message when available; without one, the primary
228error is preserved. The worker protocol owns the INTERNAL classification.
229Domain: generated safe primary/cause messages, Error and TypeError primaries,
230plain Error and NoModificationAllowedError causes, plus no cause.
231Reference/path/checkpoint: expected text is projected from immutable scalar
232input before Error objects cross the production boundary. A field-list model is
233compared to the complete response after the real init-message handler observes
234a mocked open_v2 rejection; call reach is asserted.
235Observed: exact response kind, request ID, status, error code, and text. Mocked
236wasm/VFS objects do not prove native open or handle release, and this does not
237cover the separate upstream partial-open race.
238Grammar: the bounded message alphabet has lengths 1–12; the six fixed examples
239reconstruct every primary kind × absent/plain/DOMException cause class. A
240non-Error cause is outside this promise. Removing either class or the absent
241case loses one of those fixed witnesses.
242Challenge/replay: the present-cause examples reject a response that drops the
243cause; the absent-cause examples reject an invented cause. Pinned examples run
244separately so both generated campaigns share one property and budget, and a
245reported shrink path selects its generated case directly. Verbose FastCheck
246output retains original/reduced traces. Set
247TANSTACK_DB_OPFS_DIAGNOSTIC_ORACLE_SEED and
248TANSTACK_DB_OPFS_DIAGNOSTIC_ORACLE_PATH for direct replay.
249*/
250describe(`OPFS worker diagnostics oracle`, () => {
251 if (!replayRequested) {
252 it.each(diagnosticExamples)(
253 `preserves the pinned open-failure diagnostic (%#)`,
254 checkDiagnostic,
255 )
256 }
257
258 it.skipIf(replayRequested)(
259 `rejects a diagnostic that drops an exposed VFS cause`,
260 async () => {
261 const input = diagnosticExamples[4]![0]
262 const response = await initialize(makePrimary(input), makeCause(input))
263 const expected = {
264 type: `response`,
265 requestId: `diagnostic-oracle`,
266 ok: false,
267 code: `INTERNAL`,
268 error: referenceMessage(input),
269 }
270
271 expect(response).toEqual(expected)
272 expect({ ...response, error: input.primaryMessage }).not.toEqual(expected)
273 },
274 )
275
276 it.each(campaigns)(
277 `matches the independent diagnostic formatter ($name campaign)`,
278 async ({ seed }) => {
279 await fc.assert(fc.asyncProperty(diagnosticInput, checkDiagnostic), {
280 ...(seed === undefined ? {} : { seed }),
281 numRuns: diagnosticRuns,
282 ...(diagnosticPath ? { path: diagnosticPath } : {}),
283 verbose: true,
284 })
285 },
286 15_000,
287 )
288})