From 63034e10c42bcceb7416480e8a3942a73f209446 Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 21 Oct 2026 00:26:06 +0200 Subject: [PATCH] fix(tests): recette server sends the nginx.conf Cache-Control lines (env.js no-store, /assets/ immutable) so an offline import reuses the cached worker chunk; r4-offline-import.mjs re-runs J1.7 on three engines and two network cuts --- scripts/browser/r4-offline-import.mjs | 199 ++++++++++++++++++ .../results/2026-10-20-r4-offline-import.json | 37 ++++ scripts/browser/serve.mjs | 15 +- 3 files changed, 247 insertions(+), 4 deletions(-) create mode 100644 scripts/browser/r4-offline-import.mjs create mode 100644 scripts/browser/results/2026-10-20-r4-offline-import.json diff --git a/scripts/browser/r4-offline-import.mjs b/scripts/browser/r4-offline-import.mjs new file mode 100644 index 00000000..4bc0e076 --- /dev/null +++ b/scripts/browser/r4-offline-import.mjs @@ -0,0 +1,199 @@ +// Offline import of the application (R4.10, recette J1.7): one reference +// PDF picked on Home while online (the editor opens, the worker chunk is +// fetched once), then the network goes, back to Home (« Accueil »), the +// same PDF picked again through « Remplacer le bilan en cours ? ». The +// import must open the editor from the cached worker chunk and the page's +// compiled module. Two ways to lose the network, a fresh browser each: +// emulate Playwright's offline mode (context.setOffline) +// stop the server process killed (connection refused, as a LAN host +// that went away) +// The server is serve.mjs in its own process, so `stop` kills its sockets +// too; its Cache-Control lines are checked first against docker/nginx.conf +// (env.js no-store, /assets/ immutable). Headless WebKit never reuses the +// HTTP cache for a worker script offline (R4.10 finding): its rows are +// reported, not counted. Exit code 1 when a Chromium or Firefox row does +// not open the editor, or any row shows a page error or leaves the page +// without an answer (no editor, no inline line). +// +// PLAYWRIGHT_NODE_MODULES=... node scripts/browser/r4-offline-import.mjs \ +// [--engines chromium,firefox,webkit] [--out ] +import { spawn } from 'node:child_process' +import { readdirSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { parseArgs } from 'node:util' +import { IMPORT_ERROR, PICK_LABEL } from './import-baseline.mjs' +import { checkBuild } from './lib/app-build.mjs' +import { tagged, timeoutAfter } from './lib/async.mjs' +import { probedPage } from './lib/page-probes.mjs' +import { + DIST_DIR, + FIXTURES_DIR, + HARNESS_DIR, + RESULTS_DIR, +} from './lib/paths.mjs' +import { + ENGINES, + closeEngine, + launchEngine, + loadPlaywright, +} from './lib/playwright.mjs' +import { resultsJson } from './lib/results-json.mjs' +import { IMMUTABLE, NO_STORE } from './serve.mjs' + +const REFERENCE = join(FIXTURES_DIR, 'pdf/r3/demo.fr.logos.pdf') +const MODES = ['emulate', 'stop'] +const REPLACE_LABEL = 'Remplacer' // fr.ts session.replace.confirm +const HOME_LABEL = 'Accueil' // fr.ts common.home +const CANVAS = '.svg-canvas [data-anno-id]' +// The import's two timers (10 s start, 20 s task) and a margin. +const ANSWER_TIMEOUT_MS = 40_000 +const LOAD_TIMEOUT_MS = 60_000 +const COUNTED = new Set(['chromium', 'firefox']) + +const today = () => new Date().toISOString().slice(0, 10) +const log = (line) => console.error(`[${new Date().toISOString()}] ${line}`) + +function options() { + const { values } = parseArgs({ + options: { + engines: { type: 'string', default: ENGINES.join(',') }, + out: { + type: 'string', + default: join(RESULTS_DIR, `${today()}-r4-offline-import.json`), + }, + }, + }) + const engines = values.engines.split(',').filter(Boolean) + const unknown = engines.filter((e) => !ENGINES.includes(e)) + if (unknown.length) throw new Error(`unknown engines: ${unknown.join(', ')}`) + return { engines, out: values.out } +} + +/** serve.mjs in a child process on a free port; resolves with its URL. */ +function startChildServer() { + const child = spawn( + process.execPath, + [join(HARNESS_DIR, 'serve.mjs'), '--port', '0'], + { stdio: ['ignore', 'pipe', 'inherit'] }, + ) + const url = new Promise((done, fail) => { + child.once('exit', (code) => fail(new Error(`serve.mjs exited ${code}`))) + child.stdout.on('data', (chunk) => { + const match = String(chunk).match(/serving apps\/app\/dist on (\S+)/) + if (match) done(match[1]) + }) + }) + return { child, url } +} + +/** The Cache-Control lines nginx.conf sets, read back from the server. */ +async function cacheHeaders(baseUrl) { + const worker = readdirSync(join(DIST_DIR, 'assets')).find((name) => + /^import\.worker-.*\.js$/.test(name), + ) + const read = async (path) => + (await fetch(`${baseUrl}${path}`)).headers.get('cache-control') + const envJs = await read('/env.js') + const workerChunk = await read(`/assets/${worker}`) + return { + envJs, + workerChunk, + asNginx: envJs === NO_STORE && workerChunk === IMMUTABLE, + } +} + +/** One pick through the button (the replace dialog when a bilan is open). */ +async function pickReference(page) { + const chooser = page.waitForEvent('filechooser', { timeout: 10_000 }) + await page.getByRole('button', { name: PICK_LABEL }).click() + const replace = page.getByRole('button', { name: REPLACE_LABEL }) + const replaced = await replace + .waitFor({ timeout: 2000 }) + .then(() => replace.click()) + .then(() => true) + .catch(() => false) + await (await chooser).setFiles(REFERENCE) + return replaced +} + +/** The first answer of an import: the editor or the inline line. */ +function answerOf(page) { + return Promise.race([ + tagged('editor', page.waitForURL('**/editor', { timeout: 0 })), + tagged('error_text', page.locator(IMPORT_ERROR).waitFor({ timeout: 0 })), + timeoutAfter(ANSWER_TIMEOUT_MS), + ]) +} + +/** Online import, then the network goes, then the offline import. */ +async function offlineRun(page, context, server, mode) { + await page.waitForSelector(`button:has-text("${PICK_LABEL}"):enabled`) + await pickReference(page) + const online = await answerOf(page) + if (online.kind !== 'editor') return { online: online.kind } + await page.waitForSelector(CANVAS, { timeout: LOAD_TIMEOUT_MS }) + if (mode === 'emulate') await context.setOffline(true) + else server.child.kill('SIGKILL') + await page.getByRole('link', { name: HOME_LABEL }).first().click() + const replaced = await pickReference(page) + const offline = await answerOf(page) + const errorText = await page + .locator(IMPORT_ERROR) + .textContent({ timeout: 300 }) + .catch(() => null) + return { online: 'editor', replaced, offline: offline.kind, errorText } +} + +/** One engine and mode: its own server, browser and context. */ +async function runOne(pw, engine, mode) { + const server = startChildServer() + const baseUrl = await server.url + const headers = await cacheHeaders(baseUrl) + const session = await launchEngine(pw, engine) + try { + const context = await session.browser.newContext({ locale: 'fr-FR' }) + const seed = { draft: null, locale: 'fr', skipDisclaimer: true } + const { page, events } = await probedPage(context, seed) + await page.goto(`${baseUrl}/`) + const run = await offlineRun(page, context, server, mode) + return { engine, mode, headers, ...run, pageErrors: events.pageErrors } + } finally { + await closeEngine(session) + server.child.kill('SIGKILL') + } +} + +/** Why a row fails (header comment); empty when as expected. */ +function problemsOf(row) { + const problems = [] + if (!row.headers.asNginx) problems.push('cache headers differ from nginx') + if (row.online !== 'editor') problems.push(`online ${row.online}`) + if (row.pageErrors.length) problems.push('page errors') + if (row.offline === 'timeout') problems.push('no answer offline') + if (COUNTED.has(row.engine) && row.offline !== 'editor') { + problems.push(`offline ${row.offline}`) + } + return problems +} + +async function main() { + const { engines, out } = options() + const build = checkBuild() + const { pw, version } = loadPlaywright() + const runs = [] + for (const engine of engines) { + for (const mode of MODES) { + log(`${engine} ${mode}`) + const row = await runOne(pw, engine, mode) + runs.push({ ...row, problems: problemsOf(row) }) + log(`${engine} ${mode}: offline ${row.offline} ${row.errorText ?? ''}`) + } + } + const failed = runs.filter((r) => r.problems.length > 0) + const result = { date: today(), playwright: version, build, runs } + writeFileSync(out, `${resultsJson(result)}\n`) + log(`${runs.length} runs, ${failed.length} not as expected → ${out}`) + process.exitCode = failed.length ? 1 : 0 +} + +await main() diff --git a/scripts/browser/results/2026-10-20-r4-offline-import.json b/scripts/browser/results/2026-10-20-r4-offline-import.json new file mode 100644 index 00000000..857c0637 --- /dev/null +++ b/scripts/browser/results/2026-10-20-r4-offline-import.json @@ -0,0 +1,37 @@ +{ + "date": "2026-10-20", + "playwright": "1.64.0", + "build": { + "distDir": "/home/bchanot/Documents/faunosteo/apps/app/dist", + "builtAt": "2026-10-20T20:25:44.011Z", + "sheetChunk": { + "name": "_virtual_faunosteo-sheet-vxifkiH_.js", + "bytes": 377259, + "sha256": "44ef9bf7c6f64dd621f6656dd1de88689f2f74c998ec0b0822483674721d26b8" + }, + "entryChunk": { + "name": "index-D85_yER7.js", + "bytes": 921784, + "sha256": "6a233753827074a30c48b69b209a431b6f23c94f1f4cd59f5fc2660034466b99" + }, + "wasm": { + "name": "faunosteo_wasm_bg-9CH7GQ4e.wasm", + "bytes": 1535289, + "sha256": "8abfe5d7392fdca75e624a358b070ad577e21da9f550d3cdd96a9538ac167b54" + }, + "importWorker": { + "name": "import.worker-BSrH6NM8.js", + "bytes": 8175, + "sha256": "f667c4c5222bc7cd3311da788e3ecd6cf6156a4a9757b21c8730d93463ac5200" + }, + "headCommit": "4509313" + }, + "runs": [ +{"engine":"chromium","mode":"emulate","headers":{"envJs":"no-store, no-cache, must-revalidate","workerChunk":"public, max-age=31536000, immutable","asNginx":true},"online":"editor","replaced":true,"offline":"editor","errorText":null,"pageErrors":[],"problems":[]}, +{"engine":"chromium","mode":"stop","headers":{"envJs":"no-store, no-cache, must-revalidate","workerChunk":"public, max-age=31536000, immutable","asNginx":true},"online":"editor","replaced":true,"offline":"editor","errorText":null,"pageErrors":[],"problems":[]}, +{"engine":"firefox","mode":"emulate","headers":{"envJs":"no-store, no-cache, must-revalidate","workerChunk":"public, max-age=31536000, immutable","asNginx":true},"online":"editor","replaced":true,"offline":"editor","errorText":null,"pageErrors":[],"problems":[]}, +{"engine":"firefox","mode":"stop","headers":{"envJs":"no-store, no-cache, must-revalidate","workerChunk":"public, max-age=31536000, immutable","asNginx":true},"online":"editor","replaced":true,"offline":"editor","errorText":null,"pageErrors":[],"problems":[]}, +{"engine":"webkit","mode":"emulate","headers":{"envJs":"no-store, no-cache, must-revalidate","workerChunk":"public, max-age=31536000, immutable","asNginx":true},"online":"editor","replaced":true,"offline":"error_text","errorText":"Le moteur de lecture n'a pas pu être chargé. Réessayez l'import.","pageErrors":[],"problems":[]}, +{"engine":"webkit","mode":"stop","headers":{"envJs":"no-store, no-cache, must-revalidate","workerChunk":"public, max-age=31536000, immutable","asNginx":true},"online":"editor","replaced":true,"offline":"error_text","errorText":"Le moteur de lecture n'a pas pu être chargé. Réessayez l'import.","pageErrors":[],"problems":[]} +] +} diff --git a/scripts/browser/serve.mjs b/scripts/browser/serve.mjs index f295d29a..f391e29f 100644 --- a/scripts/browser/serve.mjs +++ b/scripts/browser/serve.mjs @@ -1,5 +1,6 @@ // Static server of the production build for the browser harness (R4.1e): -// apps/app/dist with the SPA fallback of docker/nginx.conf, `.wasm` as +// apps/app/dist with the SPA fallback and the Cache-Control lines of +// docker/nginx.conf (an offline import reuses the cached worker chunk), `.wasm` as // application/wasm, the production CSP of DEPLOY.md on every response, and // the env.js docker/entrypoint.sh writes when no APP_* variable is set (the // local tool, no Supabase). Binds 127.0.0.1 by default, or the one address @@ -56,6 +57,9 @@ async function bindAddress(host) { return results[0] } const WASM_KEYWORD = "'wasm-unsafe-eval'" +// The Cache-Control values of docker/nginx.conf (env.js, /assets/). +export const NO_STORE = 'no-store, no-cache, must-revalidate' +export const IMMUTABLE = 'public, max-age=31536000, immutable' const REPORT_PATH = '/__csp-report' const MAX_REPORT_BYTES = 64 * 1024 const MIME = { @@ -132,10 +136,10 @@ async function fileUnder(root, path) { } } -function send(res, { status, body = '', type, csp, noStore = false, head }) { +function send(res, { status, body = '', type, csp, cache, head }) { const headers = { 'Content-Security-Policy': csp } if (type) headers['Content-Type'] = type - if (noStore) headers['Cache-Control'] = 'no-store, no-cache, must-revalidate' + if (cache) headers['Cache-Control'] = cache headers['Content-Length'] = Buffer.byteLength(body) res.writeHead(status, headers) res.end(head ? undefined : body) @@ -163,9 +167,12 @@ async function route(root, path, mounts) { const mounted = await mountedAnswer(mounts, path) if (mounted) return mounted if (path === '/env.js') { - return { body: LOCAL_TOOL_ENV_JS, type: MIME['.js'], noStore: true } + return { body: LOCAL_TOOL_ENV_JS, type: MIME['.js'], cache: NO_STORE } } const file = await fileUnder(root, path) + if (file && path.startsWith('/assets/')) { + return { ...(await fileAnswer(file)), cache: IMMUTABLE } + } if (file) return fileAnswer(file) if (path.startsWith('/assets/')) return { status: 404 } return { body: await readFile(join(root, 'index.html')), type: MIME['.html'] }