Open History to see the last commit
1/**
2 * Chromium receiving driver for persisted demand coverage, over real OPFS with
3 * the wa-sqlite worker driver. It runs one session per page load over the same
4 * OPFS database. The Playwright spec (`persisted-on-demand-coverage.opfs.spec.ts`)
5 * navigates the page from session 1 to session 2, so session 2 is a later page
6 * over the same storage.
7 *
8 * # Law, authority, and histories
9 *
10 * The law and the histories are the receiving contract's
11 * (`packages/db-sqlite-persistence-core/tests/contracts/persisted-demand-coverage-receiving-contract.ts`).
12 * The law is `docs/contributing/oracle-reviews/2026-10-20-on-demand-network-first-law.md`;
13 * the primary oracle `packages/db-sqlite-persistence-core/tests/persisted-demand-coverage-oracle.test.ts`
14 * owns it across its cells. This page is the browser host.
15 *
16 * # Production path
17 *
18 * Each session opens `openBrowserWASQLiteOPFSDatabase` and
19 * `createBrowserWASQLitePersistence`, and the contract builds the Collection
20 * with `persistedCollectionOptions`. The coordinated scenario also passes a
21 * `BrowserCollectionCoordinator`. Session 1 closes its database (and
22 * coordinator, if any) before the page navigates.
23 *
24 * # Observations
25 *
26 * The page records the session 1 source log, and the session 2 loads the
27 * source received with its two checkpoints. Session 2 then runs the shared
28 * judge (`persisted-demand-coverage-model-oracle.ts`) over those records and
29 * reports its violations. The page states no expected result itself.
30 *
31 * # Limits
32 *
33 * One driver (wa-sqlite over OPFS in Chromium, one tab at a time). It does not
34 * cover Firefox or WebKit, real multi-tab coordination, or the Electron and
35 * Node drivers (the node witness covers better-sqlite3).
36 */
37import {
38 BrowserCollectionCoordinator,
39 createBrowserWASQLitePersistence,
40 openBrowserWASQLiteOPFSDatabase,
41} from '../src/index'
42import {
43 coverageRecords,
44 receivingHistory,
45 recordSession1,
46 recordSession2,
47} from '../../db-sqlite-persistence-core/tests/contracts/persisted-demand-coverage-receiving-contract'
48import { coverageViolations } from '../../db-sqlite-persistence-core/tests/persisted-demand-coverage-model-oracle'
49import type {
50 ReceivingSession,
51 Session1Record,
52 Session2Record,
53} from '../../db-sqlite-persistence-core/tests/contracts/persisted-demand-coverage-receiving-contract'
54
55// Session 2's record, and the shared judge's violations at each checkpoint.
56// `violations` is absent for the coordinated run, which the law does not cover.
57export type Session2Result =
58 | {
59 record: Session2Record
60 violations?: {
61 beforeDeadline: Array<string>
62 afterDeadline: Array<string>
63 }
64 }
65 | { error: string }
66
67declare global {
68 interface Window {
69 __persistedOnDemandSession1?: Session1Record | { error: string }
70 __persistedOnDemandSession2?: Session2Result
71 }
72}
73
74// Session 1's record reaches session 2 through sessionStorage, which the tab
75// keeps across the spec's navigation.
76const storageKey = (databaseName: string) =>
77 `persisted-demand-coverage:${databaseName}`
78
79// Opens one session's storage. `close` releases the coordinator and the
80// database so that the next page can open the same OPFS file.
81async function openSession(
82 databaseName: string,
83 coordinated: boolean,
84): Promise<ReceivingSession> {
85 const database = await openBrowserWASQLiteOPFSDatabase({ databaseName })
86 // Without a coordinator the wrapper uses the default single-process
87 // coordinator, the only one the law covers (guide: sqlite-persistence.md).
88 const coordinator = coordinated
89 ? new BrowserCollectionCoordinator({ dbName: databaseName })
90 : undefined
91 const persistence = createBrowserWASQLitePersistence({
92 database,
93 ...(coordinator ? { coordinator } : {}),
94 schemaMismatchPolicy: `reset`,
95 })
96 return {
97 persistence,
98 close: async () => {
99 coordinator?.dispose()
100 await database.close?.()
101 },
102 }
103}
104
105async function main(): Promise<void> {
106 const params = new URLSearchParams(window.location.search)
107 const phase = params.get(`phase`)
108 const history = receivingHistory(params.get(`history`)!)
109 const coordinated = params.get(`coordinator`) === `browser`
110 const databaseName = params.get(`db`)
111 if (!databaseName) throw new Error(`missing db parameter`)
112 const session = await openSession(databaseName, coordinated)
113 try {
114 if (phase === `1`) {
115 const record = await recordSession1(session.persistence, history)
116 sessionStorage.setItem(storageKey(databaseName), JSON.stringify(record))
117 window.__persistedOnDemandSession1 = record
118 return
119 }
120 const session1 = JSON.parse(
121 sessionStorage.getItem(storageKey(databaseName)) ?? `null`,
122 ) as Session1Record
123 const record = await recordSession2(session.persistence, history)
124 if (coordinated) {
125 window.__persistedOnDemandSession2 = { record }
126 return
127 }
128 const records = coverageRecords(history, session1, record)
129 window.__persistedOnDemandSession2 = {
130 record,
131 violations: {
132 beforeDeadline: coverageViolations(records.beforeDeadline),
133 afterDeadline: coverageViolations(records.afterDeadline),
134 },
135 }
136 } catch (error) {
137 if (phase === `1`)
138 window.__persistedOnDemandSession1 = { error: String(error) }
139 else window.__persistedOnDemandSession2 = { error: String(error) }
140 } finally {
141 await session.close()
142 }
143}
144
145void main()