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

shared-driver-fairness.opfs.ts

190 lines6.0 KB

1/**
2 * Real-provider refinement of the shared-driver fairness oracle. The page runs
3 * the same legal neutral and fixed-storm histories through public `preload()`,
4 * the browser/core adapter boundary, and Chromium's OPFSCoopSyncVFS worker. It
5 * freezes logical completions, public rows, raw dequeue reach, and the K=1
6 * violation result before cleanup, then reports provider cleanup separately.
7 * This fixture adds real OPFS/worker evidence; it does not claim multi-tab,
8 * multi-process, non-Chromium, latency, or unbounded-eventuality coverage.
9 */
10import { openBrowserWASQLiteOPFSDatabase } from '../src/index'
11import {
12 findSharedDriverFairnessLawViolations,
13 observeSharedDriverFairness,
14} from '../tests/shared-driver-fairness-oracle'
15import type {
16 SharedDriverFairnessLawViolation,
17 SharedDriverFairnessObservation,
18 SharedDriverFairnessScenario,
19} from '../tests/shared-driver-fairness-oracle'
20​
21export type OPFSOracleResult =
22 | {
23 status: `complete`
24 provider: `Chromium OPFSCoopSyncVFS worker`
25 observation: SharedDriverFairnessObservation
26 lawViolations: ReadonlyArray<SharedDriverFairnessLawViolation>
27 opfsCleanupFailures: ReadonlyArray<string>
28 }
29 | {
30 status: `failed-before-checkpoint`
31 provider: `Chromium OPFSCoopSyncVFS worker`
32 primaryFailure: string
33 opfsCleanupFailures: ReadonlyArray<string>
34 }
35​
36declare global {
37 interface Window {
38 __tanstackDriverFairnessOracle?: OPFSOracleResult
39 }
41​
42async function removeOPFSArtifacts(
43 databaseName: string,
44): Promise<ReadonlyArray<string>> {
45 const failures: Array<string> = []
46 const root = await navigator.storage.getDirectory()
47 for (const suffix of [``, `-journal`, `-wal`]) {
48 try {
49 await root.removeEntry(`${databaseName}${suffix}`)
50 } catch (error) {
51 if (!(error instanceof DOMException && error.name === `NotFoundError`)) {
52 failures.push(
53 `${databaseName}${suffix}: ${error instanceof Error ? error.message : String(error)}`,
54 )
55 }
56 }
57 }
58​
59 // OPFSCoopSyncVFS creates one private temporary access-handle directory per
60 // worker. This page owns its isolated origin for the fixture run.
61 const iterableRoot = root as FileSystemDirectoryHandle & {
62 entries: () => AsyncIterableIterator<[string, FileSystemHandle]>
63 }
64 for await (const [name, handle] of iterableRoot.entries()) {
65 if (handle.kind !== `directory` || !name.startsWith(`.ahp-`)) continue
66 try {
67 await root.removeEntry(name, { recursive: true })
68 } catch (error) {
69 failures.push(
70 `${name}: ${error instanceof Error ? error.message : String(error)}`,
71 )
72 }
73 }
74 return failures
76​
77function scenarioFromLocation(): SharedDriverFairnessScenario {
78 const mode = new URL(location.href).searchParams.get(`mode`)
79 if (mode === `neutral`) {
80 return {
81 id: `opfs-neutral-reach`,
82 work: [0, 1].map((index) => ({
83 kind: `hydrate` as const,
84 id: `hydrate-${index}`,
85 seededRows: [
86 { id: `row-${index}-0`, value: index * 10 },
87 { id: `row-${index}-1`, value: index * 10 + 1 },
88 ],
89 })),
90 }
91 }
92 if (mode === `interleaved`) {
93 // A backlog beyond K=1 before the first hydrate, then hydrates queued ahead
94 // of later persists: the hydrate-before-later-persist cell.
95 const persist = (index: number) => ({
96 kind: `persist` as const,
97 id: `persist-${index}`,
98 mutationsPerPersist: 2,
99 })
100 const hydrate = (index: number) => ({
101 kind: `hydrate` as const,
102 id: `hydrate-${index}`,
103 seededRows: [
104 { id: `row-${index}-0`, value: index * 10 },
105 { id: `row-${index}-1`, value: index * 10 + 1 },
106 ],
107 })
108 return {
109 id: `opfs-fixed-interleaved`,
110 work: [
111 persist(0),
112 persist(1),
113 persist(2),
114 hydrate(0),
115 persist(3),
116 hydrate(1),
117 persist(4),
118 hydrate(2),
119 ],
120 }
121 }
122 return {
123 id: `opfs-fixed-persist-storm`,
124 work: [
125 ...Array.from({ length: 5 }, (_, index) => ({
126 kind: `persist` as const,
127 id: `persist-${index}`,
128 mutationsPerPersist: 2,
129 })),
130 ...Array.from({ length: 4 }, (_, index) => ({
131 kind: `hydrate` as const,
132 id: `hydrate-${index}`,
133 seededRows: [
134 { id: `row-${index}-0`, value: index * 10 },
135 { id: `row-${index}-1`, value: index * 10 + 1 },
136 ],
137 })),
138 ],
139 }
141​
142async function run(): Promise<void> {
143 const status = document.querySelector<HTMLOutputElement>(`#oracle-status`)
144 const databaseName = `ws5b-${crypto.randomUUID()}.sqlite`
145 let observation: SharedDriverFairnessObservation | undefined
146 let lawViolations: ReadonlyArray<SharedDriverFairnessLawViolation> = []
147 let primaryFailure: string | undefined
148 let opfsCleanupFailures: ReadonlyArray<string> = []
149 try {
150 observation = await observeSharedDriverFairness(
151 () => openBrowserWASQLiteOPFSDatabase({ databaseName }),
152 scenarioFromLocation(),
153 )
154 // Freeze the reached semantic checkpoint before attempting OPFS cleanup.
155 lawViolations = findSharedDriverFairnessLawViolations(observation)
156 } catch (error) {
157 primaryFailure = error instanceof Error ? error.message : String(error)
158 }
159​
160 try {
161 opfsCleanupFailures = await removeOPFSArtifacts(databaseName)
162 } catch (cleanupError) {
163 opfsCleanupFailures = [
164 cleanupError instanceof Error
165 ? cleanupError.message
166 : String(cleanupError),
167 ]
168 }
169​
170 if (observation && primaryFailure === undefined) {
171 window.__tanstackDriverFairnessOracle = {
172 status: `complete`,
173 provider: `Chromium OPFSCoopSyncVFS worker`,
174 observation,
175 lawViolations,
176 opfsCleanupFailures,
177 }
178 if (status) status.value = `complete`
179 } else {
180 window.__tanstackDriverFairnessOracle = {
181 status: `failed-before-checkpoint`,
182 provider: `Chromium OPFSCoopSyncVFS worker`,
183 primaryFailure: primaryFailure ?? `unknown failure before checkpoint`,
184 opfsCleanupFailures,
185 }
186 if (status) status.value = `failed-before-checkpoint`
187 }
189​
190void run()