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

opfs-worker-diagnostics-oracle.test.ts

247 lines7.0 KB

1import { fc, test as fcTest } from '@fast-check/vitest'
2import { afterEach, describe, expect, 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 }
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)
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)
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(`: `)
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
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 diagnosticSeed = Number(
147 process.env.TANSTACK_DB_OPFS_DIAGNOSTIC_ORACLE_SEED ?? 1846,
149const diagnosticRuns = Number(
150 process.env.TANSTACK_DB_OPFS_DIAGNOSTIC_ORACLE_RUNS ?? 40,
152const diagnosticPath = process.env.TANSTACK_DB_OPFS_DIAGNOSTIC_ORACLE_PATH
153​
154const diagnosticExamples: Array<[DiagnosticInput]> = [
155 [
156 {
157 primaryKind: `Error`,
158 primaryMessage: `original open failure`,
159 cause: null,
160 },
161 ],
162 [
163 {
164 primaryKind: `TypeError`,
165 primaryMessage: `typed open failure`,
166 cause: null,
167 },
168 ],
169 [
170 {
171 primaryKind: `Error`,
172 primaryMessage: `sqlite3_open_v2`,
173 cause: { kind: `Error`, message: `plain VFS failure` },
174 },
175 ],
176 [
177 {
178 primaryKind: `TypeError`,
179 primaryMessage: `typed open failure`,
180 cause: { kind: `Error`, message: `plain VFS failure` },
181 },
182 ],
183 [
184 {
185 primaryKind: `Error`,
186 primaryMessage: `sqlite3_open_v2`,
187 cause: {
188 kind: `NoModificationAllowedError`,
189 message: `Access handle is locked [/locked.sqlite-wal]`,
190 },
191 },
192 ],
193 [
194 {
195 primaryKind: `TypeError`,
196 primaryMessage: `typed open failure`,
197 cause: {
198 kind: `NoModificationAllowedError`,
199 message: `access handle locked`,
200 },
201 },
202 ],
204​
205/*
206Law/source: the README Notes section promises that SQLite open failures include
207the underlying VFS error name/message when available; without one, the primary
208error is preserved. The worker protocol owns the INTERNAL classification.
209Domain: generated safe primary/cause messages, Error and TypeError primaries,
210plain Error and NoModificationAllowedError causes, plus no cause.
211Reference/path/checkpoint: expected text is projected from immutable scalar
212input before Error objects cross the production boundary. A field-list model is
213compared to the complete response after the real init-message handler observes
214a mocked open_v2 rejection; call reach is asserted.
215Observed: exact response kind, request ID, status, error code, and text. Mocked
216wasm/VFS objects do not prove native open or handle release, and this does not
217cover the separate upstream partial-open race.
218Challenge/replay: six fixed examples exhaust primary kind × cause class and
219retain the original bracketed WAL-path diagnostic. Verbose FastCheck output
220retains original/reduced traces. Replay with TANSTACK_DB_OPFS_DIAGNOSTIC_ORACLE_*
221and this file's package-local Vitest command.
222*/
223describe(`OPFS worker diagnostics oracle`, () => {
224 fcTest.prop([diagnosticInput], {
225 seed: diagnosticSeed,
226 numRuns: diagnosticRuns,
227 ...(diagnosticPath ? { path: diagnosticPath } : {}),
228 examples: diagnosticExamples,
229 verbose: true,
230 })(
231 `matches the independent diagnostic formatter`,
232 async (input) => {
233 const expectedMessage = referenceMessage(input)
234 const primary = makePrimary(input)
235 const cause = makeCause(input)
236​
237 expect(await initialize(primary, cause)).toEqual({
238 type: `response`,
239 requestId: `diagnostic-oracle`,
240 ok: false,
241 code: `INTERNAL`,
242 error: expectedMessage,
243 })
244 },
245 15_000,
246 )
247})