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

persisted-demand-coverage.electron.e2e.test.ts

227 lines8.1 KB

1/**
2 * # Receiving witness: persisted demand coverage over Electron
3 *
4 * Law and authority: the receiving contract
5 * (`packages/db-sqlite-persistence-core/tests/contracts/persisted-demand-coverage-receiving-contract.ts`)
6 * holds the histories and records the sessions. The law is
7 * `docs/contributing/oracle-reviews/2026-10-20-on-demand-network-first-law.md`,
8 * and the primary oracle `packages/db-sqlite-persistence-core/tests/persisted-demand-coverage-oracle.test.ts`
9 * owns it across its cells. This file is the Electron host. It runs the
10 * histories through the real Electron persistence path: the renderer's
11 * `createElectronSQLitePersistence` over real IPC to the main process's
12 * `exposeElectronSQLitePersistence`, with `node:sqlite` in main (Electron's
13 * ABI cannot load better-sqlite3). The node witness covers better-sqlite3.
14 *
15 * Histories: every history of `RECEIVING_HISTORIES`, each with its own
16 * database file, one per history. The test launches Electron twice. Phase 1
17 * is an online app launch that records each history's session 1 log. Phase 2
18 * is a later, separate app launch over the same files that records each
19 * history's session 2. Session 2's upstream behavior is the history's.
20 *
21 * Production path: the renderer driver
22 * (`tests/e2e/persisted-demand-coverage/renderer.ts`) calls the contract's
23 * recorders in a real renderer, and each history opens its main-process session
24 * over IPC.
25 *
26 * Observations: the records carry the source log, the loads the source
27 * received, and two session 2 checkpoints with their elapsed time since the
28 * forward. The shared judge compares them with the law.
29 *
30 * Limits: one driver (Electron renderer over IPC to a node:sqlite main
31 * process, one window, single-process coordinator). It does not cover
32 * `ElectronCollectionCoordinator`, multi-window coordination, or the
33 * better-sqlite3 driver (the node witness covers it).
34 */
35import { spawn } from 'node:child_process'
36import { copyFileSync, existsSync, mkdtempSync, rmSync } from 'node:fs'
37import { tmpdir } from 'node:os'
38import { dirname, join, resolve } from 'node:path'
39import { fileURLToPath } from 'node:url'
40import { build } from 'esbuild'
41import electronPath from 'electron'
42import { expect, it, onTestFinished } from 'vitest'
43import {
44 RECEIVING_HISTORIES,
45 coverageRecords,
46} from '../../db-sqlite-persistence-core/tests/contracts/persisted-demand-coverage-receiving-contract'
47import { coverageViolations } from '../../db-sqlite-persistence-core/tests/persisted-demand-coverage-model-oracle'
48import type {
49 Session1Record,
50 Session2Record,
51} from '../../db-sqlite-persistence-core/tests/contracts/persisted-demand-coverage-receiving-contract'
52​
53const fixture = join(
54 dirname(fileURLToPath(import.meta.url)),
55 `e2e`,
56 `persisted-demand-coverage`,
58const packages = resolve(fixture, `../../../..`)
59const RESULT_PREFIX = `__TANSTACK_DB_DEMAND_COVERAGE__:`
60const APP_TIMEOUT_MS = 240_000
61​
62type PhaseResult = {
63 phase: `1` | `2`
64 results: Array<{
65 name: string
66 error?: string
67 session1?: Session1Record
68 session2?: Session2Record
69 }>
71​
72async function bundle(out: string) {
73 const alias = {
74 '@tanstack/db': join(packages, `db/src`),
75 '@tanstack/db-ivm': join(packages, `db-ivm/src`),
76 '@tanstack/db-sqlite-persistence-core': join(
77 packages,
78 `db-sqlite-persistence-core/src`,
79 ),
80 // Electron's ABI cannot load the native module; main passes a database.
81 'better-sqlite3': join(
82 fixture,
83 `..`,
84 `reload-class`,
85 `better-sqlite3-unavailable.cjs`,
86 ),
87 }
88 await build({
89 entryPoints: [join(fixture, `main.ts`)],
90 outfile: join(out, `main.mjs`),
91 bundle: true,
92 platform: `node`,
93 format: `esm`,
94 external: [`electron`],
95 alias,
96 banner: {
97 js: `import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);`,
98 },
99 })
100 await build({
101 entryPoints: [join(fixture, `renderer.ts`)],
102 outfile: join(out, `renderer.js`),
103 bundle: true,
104 platform: `browser`,
105 format: `iife`,
106 alias,
107 })
108 copyFileSync(join(fixture, `preload.cjs`), join(out, `preload.cjs`))
109 copyFileSync(join(fixture, `page.html`), join(out, `page.html`))
111​
112// One real Electron app launch per phase. Phase 2 is a new process, so it
113// shares nothing with phase 1 except the database files on disk.
114function runPhase(
115 out: string,
116 databases: string,
117 phase: `1` | `2`,
118): Promise<PhaseResult> {
119 return new Promise((resolveResult, reject) => {
120 // Launch as the reload class and runtime bridge e2e do: Linux CI has no
121 // display and no configured setuid sandbox.
122 const electronArgs = [
123 `--disable-gpu`,
124 `--disable-dev-shm-usage`,
125 `--no-sandbox`,
126 join(out, `main.mjs`),
127 ]
128 const xvfbRun = `/usr/bin/xvfb-run`
129 const useXvfb = existsSync(xvfbRun)
130 const child = spawn(
131 useXvfb ? xvfbRun : (electronPath as unknown as string),
132 useXvfb
133 ? [
134 `-a`,
135 `--server-args=-screen 0 1280x720x24`,
136 electronPath as unknown as string,
137 ...electronArgs,
138 ]
139 : electronArgs,
140 {
141 env: {
142 ...process.env,
143 ELECTRON_RUN_AS_NODE: undefined,
144 DEMAND_COVERAGE_PHASE: phase,
145 DEMAND_COVERAGE_PRELOAD: join(out, `preload.cjs`),
146 DEMAND_COVERAGE_PAGE: join(out, `page.html`),
147 DEMAND_COVERAGE_DIR: databases,
148 },
149 },
150 )
151 let stdout = ``
152 let stderr = ``
153 child.stdout.on(`data`, (chunk) => (stdout += String(chunk)))
154 child.stderr.on(`data`, (chunk) => (stderr += String(chunk)))
155 // A hung app is reported with its stderr before the test times out.
156 const timer = setTimeout(() => {
157 child.kill()
158 reject(new Error(`phase ${phase} had no result: ${stderr.slice(-2_000)}`))
159 }, APP_TIMEOUT_MS)
160 child.on(`error`, (error) => {
161 clearTimeout(timer)
162 reject(error)
163 })
164 child.on(`exit`, (code) => {
165 clearTimeout(timer)
166 const line = stdout.split(`\n`).find((l) => l.startsWith(RESULT_PREFIX))
167 if (!line) {
168 reject(
169 new Error(
170 `phase ${phase} had no result (exit ${code}): ${stderr.slice(-2_000)}`,
171 ),
172 )
173 return
174 }
175 resolveResult(JSON.parse(line.slice(RESULT_PREFIX.length)) as PhaseResult)
176 })
177 })
179​
180it(`real Electron records every persisted demand coverage history across two app launches`, async () => {
181 const out = mkdtempSync(join(tmpdir(), `demand-coverage-app-`))
182 const databases = mkdtempSync(join(tmpdir(), `demand-coverage-db-`))
183 onTestFinished(() => {
184 rmSync(out, { recursive: true, force: true })
185 rmSync(databases, { recursive: true, force: true })
186 })
187 await bundle(out)
188​
189 const session1 = await runPhase(out, databases, `1`)
190 expect(session1.results.map(({ name }) => name)).toEqual(
191 RECEIVING_HISTORIES.map(({ id }) => id),
192 )
193 expect(session1.results.filter(({ error }) => error !== undefined)).toEqual(
194 [],
195 )
196​
197 const session2 = await runPhase(out, databases, `2`)
198 expect(session2.results.map(({ name }) => name)).toEqual(
199 RECEIVING_HISTORIES.map(({ id }) => id),
200 )
201 expect(session2.results.filter(({ error }) => error !== undefined)).toEqual(
202 [],
203 )
204 // Positive witness: each session 2 asked the offline source for the demand.
205 for (const result of session2.results) {
206 expect(result.session2?.sent.length ?? 0).toBeGreaterThan(0)
207 }
208 // Each history's session 1 log and session 2 record go to the shared judge,
209 // one judgment per checkpoint.
210 for (const history of RECEIVING_HISTORIES) {
211 const session1Record = session1.results.find(
212 ({ name }) => name === history.id,
213 )?.session1
214 const session2Record = session2.results.find(
215 ({ name }) => name === history.id,
216 )?.session2
217 expect(session1Record).toBeDefined()
218 expect(session2Record).toBeDefined()
219 const records = coverageRecords(
220 history,
221 session1Record as Session1Record,
222 session2Record as Session2Record,
223 )
224 expect(coverageViolations(records.beforeDeadline), history.id).toEqual([])
225 expect(coverageViolations(records.afterDeadline), history.id).toEqual([])
226 }
227}, 600_000)