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

opfs-request-order-oracle.test.ts

295 lines8.8 KB

1/**
2 * Node driver for the OPFS request-order oracle in `opfs-request-order-oracle.ts`.
3 *
4 * The public connection talks to the real worker module through a bridge
5 * `Worker` that delivers each message in its own task, as a real Worker does.
6 * The worker runs the real wa-sqlite WASM build. Only the VFS is replaced: an
7 * in-memory VFS with OPFSCoopSyncVFS's lock protocol, whose files outlive a
8 * connection so that a reopen reads them. "Taking the handle" makes the next
9 * lock queue its reacquisition on retryOps and return SQLITE_BUSY, which is
10 * what OPFSCoopSyncVFS does after it hands the handle to another connection.
11 */
12import { readFileSync } from 'node:fs'
13import { createRequire } from 'node:module'
14import { fc, test as fcTest } from '@fast-check/vitest'
15import { afterAll, beforeAll, describe, expect, vi } from 'vitest'
16import {
17 oraclePropertyOptions,
18 oracleReplayTest,
19 oracleRuns,
20} from '../../db/tests/oracle-config'
21import { openBrowserWASQLiteOPFSDatabase } from '../src/opfs-database'
22import {
23 findRequestOrderViolation,
24 observeRequestOrder,
25 requestOrderExamples,
26} from './opfs-request-order-oracle'
27import type {
28 AccessHandleControl,
29 ExecuteKind,
30 RequestOrderHistory,
31} from './opfs-request-order-oracle'
32import type {
33 BrowserOPFSWorkerRequest,
34 BrowserOPFSWorkerResponse,
35} from '../src/opfs-worker-protocol'
36​
37type CoopVFSHandle = {
38 takeHandle: () => void
39 returnHandle: () => void
40 isWaiting: () => boolean
42​
43// The compiled WASM, the shared VFS files, and the current VFS survive module
44// re-evaluation.
45const harness = vi.hoisted(() => ({
46 compiled: undefined as Promise<WebAssembly.Module> | undefined,
47 files: new Map<string, unknown>(),
48 vfs: undefined as CoopVFSHandle | undefined,
49}))
50​
51vi.mock(`@journeyapps/wa-sqlite/dist/wa-sqlite.mjs`, async (importOriginal) => {
52 const real = await importOriginal<{
53 default: (options: object) => Promise<unknown>
54 }>()
55 const require = createRequire(import.meta.url)
56 harness.compiled ??= WebAssembly.compile(
57 readFileSync(require.resolve(`@journeyapps/wa-sqlite/dist/wa-sqlite.wasm`)),
58 )
59 const compiled = harness.compiled
60 return {
61 default: () =>
62 real.default({
63 instantiateWasm(
64 imports: WebAssembly.Imports,
65 receive: (
66 instance: WebAssembly.Instance,
67 module: WebAssembly.Module,
68 ) => void,
69 ) {
70 void compiled.then(async (module) =>
71 receive(await WebAssembly.instantiate(module, imports), module),
72 )
73 return {}
74 },
75 }),
76 }
77})
78​
79// OPFSCoopSyncVFS's lock protocol over MemoryVFS storage. While another
80// connection holds the handle, the first lock queues its reacquisition on
81// retryOps and returns SQLITE_BUSY. A lock while that request is in progress
82// returns SQLITE_BUSY without queuing more work.
83vi.mock(`@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js`, async () => {
84 const { MemoryVFS } = (await import(
85 `@journeyapps/wa-sqlite/src/examples/MemoryVFS.js`
86 )) as unknown as {
87 MemoryVFS: new (
88 name: string,
89 module: unknown,
90 ) => {
91 isReady: () => Promise<void>
92 mapNameToFile: Map<string, unknown>
93 _module: { retryOps: Array<Promise<void>> }
94 }
95 }
96 const SQLITE_OK = 0
97 const SQLITE_BUSY = 5
98​
99 class CoopMemoryVFS extends MemoryVFS implements CoopVFSHandle {
100 private handleTaken = false
101 private reacquisition: undefined | (() => void)
102​
103 static async create(name: string, module: unknown) {
104 const vfs = new CoopMemoryVFS(name, module)
105 await vfs.isReady()
106 vfs.mapNameToFile = harness.files
107 harness.vfs = vfs
108 return vfs
109 }
110​
111 takeHandle(): void {
112 this.handleTaken = true
113 }
114​
115 returnHandle(): void {
116 this.handleTaken = false
117 this.reacquisition?.()
118 this.reacquisition = undefined
119 }
120​
121 isWaiting(): boolean {
122 return this.reacquisition !== undefined
123 }
124​
125 jLock(): number {
126 if (!this.handleTaken) return SQLITE_OK
127 if (this.reacquisition === undefined) {
128 this._module.retryOps.push(
129 new Promise<void>((resolve) => {
130 this.reacquisition = resolve
131 }),
132 )
133 }
134 return SQLITE_BUSY
135 }
136 }
137 return { OPFSCoopSyncVFS: CoopMemoryVFS }
138})
139​
140const nextTask = () => new Promise((resolve) => setTimeout(resolve, 0))
141​
142// The worker module listens on this global. Each request and each response
143// crosses the bridge in its own task, and a terminated bridge delivers nothing.
144let deliverToWorker: (request: BrowserOPFSWorkerRequest) => void
145const requestOwners = new Map<string, BridgeWorker>()
146​
147class BridgeWorker {
148 private readonly listeners = new Set<(event: Event) => void>()
149 private terminated = false
150​
151 addEventListener(type: string, listener: (event: Event) => void): void {
152 if (type === `message`) this.listeners.add(listener)
153 }
154​
155 removeEventListener(type: string, listener: (event: Event) => void): void {
156 if (type === `message`) this.listeners.delete(listener)
157 }
158​
159 postMessage(request: BrowserOPFSWorkerRequest): void {
160 if (this.terminated) return
161 requestOwners.set(request.requestId, this)
162 setTimeout(() => {
163 if (!this.terminated) deliverToWorker(request)
164 }, 0)
165 }
166​
167 receive(response: BrowserOPFSWorkerResponse): void {
168 setTimeout(() => {
169 if (this.terminated) return
170 for (const listener of [...this.listeners]) {
171 listener({ data: response } as MessageEvent<BrowserOPFSWorkerResponse>)
172 }
173 }, 0)
174 }
175​
176 terminate(): void {
177 this.terminated = true
178 }
180​
181const nodeHandleControl: AccessHandleControl = {
182 take: () => {
183 harness.vfs!.takeHandle()
184 return Promise.resolve()
185 },
186 untilWaiting: async () => {
187 for (let task = 0; task < 200; task++) {
188 if (harness.vfs!.isWaiting()) return true
189 await nextTask()
190 }
191 return false
192 },
193 // The bridge delivers a message in one task; a few tasks cover the
194 // connection's microtasks before it posts.
195 untilDelivered: async () => {
196 for (let task = 0; task < 5; task++) await nextTask()
197 },
198 give: () => {
199 harness.vfs!.returnHandle()
200 return Promise.resolve()
201 },
203​
204beforeAll(async () => {
205 vi.stubGlobal(`Worker`, BridgeWorker)
206 vi.stubGlobal(`navigator`, {
207 storage: { getDirectory: () => Promise.resolve({}) },
208 })
209 vi.stubGlobal(`FileSystemFileHandle`, {
210 prototype: { createSyncAccessHandle: () => {} },
211 })
212 vi.stubGlobal(`location`, { href: `https://example.test/` })
213 // The connection registers pagehide here; the worker registers message.
214 vi.stubGlobal(
215 `addEventListener`,
216 (type: string, listener: (event: MessageEvent) => void) => {
217 if (type === `message`) {
218 deliverToWorker = (data) => listener({ data } as MessageEvent)
219 }
220 },
221 )
222 vi.stubGlobal(`removeEventListener`, () => {})
223 vi.stubGlobal(`postMessage`, (response: BrowserOPFSWorkerResponse) => {
224 const owner = requestOwners.get(response.requestId)
225 requestOwners.delete(response.requestId)
226 owner?.receive(response)
227 })
228 await import(`../src/opfs-worker`)
229})
230​
231afterAll(() => {
232 vi.unstubAllGlobals()
233})
234​
235let databaseSequence = 0
236​
237async function runRequestOrderHistory(
238 history: RequestOrderHistory,
239): Promise<void> {
240 databaseSequence++
241 const observation = await observeRequestOrder(
242 (databaseName) => openBrowserWASQLiteOPFSDatabase({ databaseName }),
243 nodeHandleControl,
244 history,
245 `order-${databaseSequence}.sqlite`,
246 )
247 expect(findRequestOrderViolation(history, observation)).toBeUndefined()
249​
250const requestOrderHistory = fc
251 .array(fc.constantFrom<ExecuteKind>(`insert`, `select`), {
252 minLength: 1,
253 maxLength: 3,
254 })
255 .chain((executes) =>
256 fc.record({
257 executes: fc.constant(executes),
258 handleTakenBefore: fc.option(
259 fc.integer({ min: 0, max: executes.length - 1 }),
260 { nil: undefined },
261 ),
262 handleReturns: fc.constantFrom<RequestOrderHistory[`handleReturns`]>(
263 `before-close`,
264 `after-close`,
265 ),
266 executeAfterClose: fc.boolean(),
267 }),
268 )
269​
270const requestOrderProperty = `opfs.request-order`
271​
272describe(`OPFS request order oracle (Node driver)`, () => {
273 // A path replay of this property selects only its random campaign.
274 oracleReplayTest(fcTest).prop([requestOrderHistory], {
275 seed: 1849,
276 numRuns: oracleRuns(24),
277 examples: requestOrderExamples.map((history): [RequestOrderHistory] => [
278 history,
279 ]),
280 verbose: true,
281 })(
282 `answers requests in order and closes after them (fixed)`,
283 runRequestOrderHistory,
284 )
285 oracleReplayTest(fcTest, requestOrderProperty).prop([requestOrderHistory], {
286 ...oraclePropertyOptions(24, requestOrderProperty),
287 examples: requestOrderExamples.map((history): [RequestOrderHistory] => [
288 history,
289 ]),
290 verbose: true,
291 })(
292 `answers requests in order and closes after them (random)`,
293 runRequestOrderHistory,
294 )
295})