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) | undefined
75 vi.resetModules()
76 mocks.open.mockReset()
77 mocks.open.mockRejectedValue(primary)
78 mocks.vfs.lastError = cause
79 vi.stubGlobal(`navigator`, {
80 storage: { getDirectory: () => Promise.resolve({}) },
81 })
82 vi.stubGlobal(`FileSystemFileHandle`, {
83 prototype: { createSyncAccessHandle: () => Promise.resolve({}) },
84 })
85 vi.stubGlobal(
86 `addEventListener`,
87 (
88 _type: string,
89 listener: (event: MessageEvent<BrowserOPFSWorkerRequest>) => void,
90 ) => {
91 receive = listener
92 },
93 )
94 const response = new Promise<BrowserOPFSWorkerResponse>((resolve) => {
95 vi.stubGlobal(`postMessage`, resolve)
96 })
97
98 await import('../src/opfs-worker')
99 receive?.({
100 data: {
101 requestId: `diagnostic-oracle`,
102 type: `init`,
103 databaseName: `locked.sqlite`,
104 vfsName: `opfs`,
105 },
106 } as MessageEvent<BrowserOPFSWorkerRequest>)
107
108 const result = await response
109 expect(mocks.open).toHaveBeenCalledOnce()
110 return result
111}
112
113afterEach(() => {
114 vi.unstubAllGlobals()
115 vi.resetAllMocks()
116 vi.resetModules()
117 mocks.vfs.lastError = null
118})
119
120const message = fc
121 .array(fc.constantFrom(...`abcXYZ019 _/-.[]:`), {
122 minLength: 1,
123 maxLength: 12,
124 })
125 .map((characters) => characters.join(``))
126
127const diagnosticInput = fc.record({
128 primaryKind: fc.constantFrom<DiagnosticInput[`primaryKind`]>(
129 `Error`,
130 `TypeError`,
131 ),
132 primaryMessage: message,
133 cause: fc.option(
134 fc.record({
135 kind: fc.constantFrom<NonNullable<DiagnosticInput[`cause`]>[`kind`]>(
136 `Error`,
137 `NoModificationAllowedError`,
138 ),
139 message,
140 }),
141 { nil: null },
142 ),
143})
144
145const replaySeed = process.env.TANSTACK_DB_OPFS_DIAGNOSTIC_ORACLE_SEED
146const diagnosticSeed = Number(replaySeed ?? 1846)
147const diagnosticRuns = Number(
148 process.env.TANSTACK_DB_OPFS_DIAGNOSTIC_ORACLE_RUNS ?? 40,
149)
150const diagnosticPath = process.env.TANSTACK_DB_OPFS_DIAGNOSTIC_ORACLE_PATH
151const replayRequested = replaySeed !== undefined || diagnosticPath !== undefined
152const campaigns = replayRequested
153 ? [{ name: `replay`, seed: diagnosticSeed }]
154 : [
155 { name: `fixed`, seed: diagnosticSeed },
156 { name: `random`, seed: undefined },
157 ]
158
159const diagnosticExamples: Array<[DiagnosticInput]> = [
160 [
161 {
162 primaryKind: `Error`,
163 primaryMessage: `original open failure`,
164 cause: null,
165 },
166 ],
167 [
168 {
169 primaryKind: `TypeError`,
170 primaryMessage: `typed open failure`,
171 cause: null,
172 },
173 ],
174 [
175 {
176 primaryKind: `Error`,
177 primaryMessage: `sqlite3_open_v2`,
178 cause: { kind: `Error`, message: `plain VFS failure` },
179 },
180 ],
181 [
182 {
183 primaryKind: `TypeError`,
184 primaryMessage: `typed open failure`,
185 cause: { kind: `Error`, message: `plain VFS failure` },
186 },
187 ],
188 [
189 {
190 primaryKind: `Error`,
191 primaryMessage: `sqlite3_open_v2`,
192 cause: {
193 kind: `NoModificationAllowedError`,
194 message: `Access handle is locked [/locked.sqlite-wal]`,
195 },
196 },
197 ],
198 [
199 {
200 primaryKind: `TypeError`,
201 primaryMessage: `typed open failure`,
202 cause: {
203 kind: `NoModificationAllowedError`,
204 message: `access handle locked`,
205 },
206 },
207 ],
208]
209
210async function checkDiagnostic(input: DiagnosticInput): Promise<void> {
211 const expectedMessage = referenceMessage(input)
212 const primary = makePrimary(input)
213 const cause = makeCause(input)
214
215 expect(await initialize(primary, cause)).toEqual({
216 type: `response`,
217 requestId: `diagnostic-oracle`,
218 ok: false,
219 code: `INTERNAL`,
220 error: expectedMessage,
221 })
222}
223
224/*
225Law/source: the README Notes section promises that SQLite open failures include
226the underlying VFS error name/message when available; without one, the primary
227error is preserved. The worker protocol owns the INTERNAL classification.
228Domain: generated safe primary/cause messages, Error and TypeError primaries,
229plain Error and NoModificationAllowedError causes, plus no cause.
230Reference/path/checkpoint: expected text is projected from immutable scalar
231input before Error objects cross the production boundary. A field-list model is
232compared to the complete response after the real init-message handler observes
233a mocked open_v2 rejection; call reach is asserted.
234Observed: exact response kind, request ID, status, error code, and text. Mocked
235wasm/VFS objects do not prove native open or handle release, and this does not
236cover the separate upstream partial-open race.
237Grammar: the bounded message alphabet has lengths 1–12; the six fixed examples
238reconstruct every primary kind × absent/plain/DOMException cause class. A
239non-Error cause is outside this promise. Removing either class or the absent
240case loses one of those fixed witnesses.
241Challenge/replay: the present-cause examples reject a response that drops the
242cause; the absent-cause examples reject an invented cause. Pinned examples run
243separately so both generated campaigns share one property and budget, and a
244reported shrink path selects its generated case directly. Verbose FastCheck
245output retains original/reduced traces. Set
246TANSTACK_DB_OPFS_DIAGNOSTIC_ORACLE_SEED and
247TANSTACK_DB_OPFS_DIAGNOSTIC_ORACLE_PATH for direct replay.
248*/
249describe(`OPFS worker diagnostics oracle`, () => {
250 if (!replayRequested) {
251 it.each(diagnosticExamples)(
252 `preserves the pinned open-failure diagnostic (%#)`,
253 checkDiagnostic,
254 )
255 }
256
257 it.skipIf(replayRequested)(
258 `rejects a diagnostic that drops an exposed VFS cause`,
259 async () => {
260 const input = diagnosticExamples[4]![0]
261 const response = await initialize(makePrimary(input), makeCause(input))
262 const expected = {
263 type: `response`,
264 requestId: `diagnostic-oracle`,
265 ok: false,
266 code: `INTERNAL`,
267 error: referenceMessage(input),
268 }
269
270 expect(response).toEqual(expected)
271 expect({ ...response, error: input.primaryMessage }).not.toEqual(expected)
272 },
273 )
274
275 it.each(campaigns)(
276 `matches the independent diagnostic formatter ($name campaign)`,
277 async ({ seed }) => {
278 await fc.assert(fc.asyncProperty(diagnosticInput, checkDiagnostic), {
279 ...(seed === undefined ? {} : { seed }),
280 numRuns: diagnosticRuns,
281 ...(diagnosticPath ? { path: diagnosticPath } : {}),
282 verbose: true,
283 })
284 },
285 15_000,
286 )
287})