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

reload-class.opfs.ts

138 lines4.2 KB

1/**
2 * Chromium driver for the reload class oracle in
3 * `packages/db-sqlite-persistence-core/tests/reload-class-oracle.ts`, which
4 * owns the law, model, histories, driver loop, and comparison. It runs every
5 * fixed history against real OPFS: each tab is the real Browser persistence
6 * over its own OPFS connection and worker, with a real
7 * BrowserCollectionCoordinator over Chromium's Web Locks and BroadcastChannel.
8 * Statement latency is the real worker round trip, not a driver control. A
9 * separate OPFS connection applies setup damage and inspects the result.
10 */
11import {
12 BrowserCollectionCoordinator,
13 createBrowserWASQLitePersistence,
14 openBrowserWASQLiteOPFSDatabase,
15} from '../src/index'
16import {
17 fixedReloadHistories,
18 inProcessSeams,
19 observeReload,
20 reloadViolations,
21} from '../../db-sqlite-persistence-core/tests/reload-class-oracle'
22import type { BrowserWASQLiteDatabase } from '../src/index'
23import type {
24 ReloadHistory,
25 ReloadHost,
26} from '../../db-sqlite-persistence-core/tests/reload-class-oracle'
27​
28export type ReloadClassResult =
29 | {
30 status: `complete`
31 /** Every fixed history name in the oracle, in order. */
32 expected: Array<string>
33 results: Array<{
34 name: string
35 history: ReloadHistory
36 violations: Array<string>
37 }>
38 }
39 | { status: `failed-before-checkpoint`; name: string; primaryFailure: string }
40​
41declare global {
42 interface Window {
43 __tanstackReloadClassOracle?: ReloadClassResult
44 }
46​
47function chromiumHost(databaseName: string): {
48 host: ReloadHost
49 close: () => Promise<void>
50} {
51 let recorder: ((sql: string, params: ReadonlyArray<unknown>) => void) | null =
52 null
53 let raw: Promise<BrowserWASQLiteDatabase> | undefined
54 const rawDatabase = () =>
55 (raw ??= openBrowserWASQLiteOPFSDatabase({ databaseName }))
56 const host: ReloadHost = {
57 controlsLatency: false,
58 seams: inProcessSeams,
59 adapterPerTab: true,
60 record: (next) => {
61 recorder = next
62 },
63 setStatementLatency: () => {},
64 rawQuery: async (sql, params = []) =>
65 [...(await (await rawDatabase()).execute(sql, params))] as Array<
66 Record<string, unknown>
67 >,
68 rawExec: async (sql) => {
69 await (await rawDatabase()).execute(sql)
70 },
71 openTab: async (dbName) => {
72 const database = await openBrowserWASQLiteOPFSDatabase({ databaseName })
73 const execute = database.execute.bind(database)
74 database.execute = <TRow>(
75 sql: string,
76 params: ReadonlyArray<unknown> = [],
77 ) => {
78 recorder?.(sql, params)
79 return execute<TRow>(sql, params)
80 }
81 const coordinator = new BrowserCollectionCoordinator({ dbName })
82 return {
83 persistence: createBrowserWASQLitePersistence({
84 database,
85 coordinator,
86 schemaMismatchPolicy: `reset`,
87 }),
88 isLeader: (storageId) => coordinator.isLeader(storageId),
89 close: async () => {
90 coordinator.dispose()
91 await database.close?.()
92 },
93 }
94 },
95 }
96 return {
97 host,
98 close: async () => {
99 if (raw) await (await raw).close?.()
100 },
101 }
103​
104async function run(): Promise<void> {
105 const status = document.querySelector<HTMLOutputElement>(`#oracle-status`)
106 const results = []
107 for (const [index, [name, history]] of fixedReloadHistories.entries()) {
108 // OPFS database names near 63 characters fail to open; keep them short.
109 const databaseName = `rc-${index}-${crypto.randomUUID().slice(0, 8)}.sqlite`
110 const { host, close } = chromiumHost(databaseName)
111 try {
112 const observation = await observeReload(host, history)
113 results.push({
114 name,
115 history,
116 violations: reloadViolations(history, observation),
117 })
118 } catch (error) {
119 window.__tanstackReloadClassOracle = {
120 status: `failed-before-checkpoint`,
121 name,
122 primaryFailure: error instanceof Error ? error.message : String(error),
123 }
124 if (status) status.value = `failed-before-checkpoint`
125 return
126 } finally {
127 await close()
128 }
129 }
130 window.__tanstackReloadClassOracle = {
131 status: `complete`,
132 expected: fixedReloadHistories.map(([name]) => name),
133 results,
134 }
135 if (status) status.value = `complete`
137​
138void run()