From 3b1760fe8e9e383069cddf57d68d5d924e8627ac Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 1 Dec 2026 21:05:17 +0000 Subject: [PATCH] Web: WebAssembly build served cross-origin isolated, immutable and precompressed The web app is built with --wasm (skwasm, JS/CanvasKit fallback beside it). The proxy serves it with COOP same-origin + COEP credentialless so skwasm renders on a worker; an installed build loads from /_v// cached as immutable, other files revalidate by ETag, and the installer precompresses .br/.gz variants the proxy sends by Accept-Encoding. The bootstrap no longer registers Flutter's deprecated service worker (a reload per install). Read aloud on the web uses the Web Speech API through package:web: the flutter_tts web plugin's interop casts fail under wasm. Bench kit: isolation and headed modes, renderer and memory reporting. Co-Authored-By: Claude Opus 5.5 --- app/docker/build.sh | 5 +- .../speech/flutter_tts_speech_engine.dart | 5 +- .../chat/speech/speech_controller.dart | 5 +- .../chat/speech/web_speech_engine.dart | 155 +++++++++++++++++ app/notes/web-wasm-build.md | 90 ++++++++++ app/tool/capture/README.md | 4 + app/tool/capture/browser.mjs | 3 +- app/tool/capture/serve.mjs | 8 + app/tool/perf/interaction_bench.mjs | 28 +++- app/web/flutter_bootstrap.js | 18 ++ scripts/app_build.py | 22 ++- scripts/precompress_web.mjs | 70 ++++++++ scripts/test_app_build.py | 19 +++ web/README.md | 7 + web/serve.mjs | 35 +++- web/src/appFiles.js | 156 ++++++++++++++++++ web/test/appFiles.test.mjs | 124 ++++++++++++++ 17 files changed, 737 insertions(+), 17 deletions(-) create mode 100644 app/lib/features/chat/speech/web_speech_engine.dart create mode 100644 app/notes/web-wasm-build.md create mode 100644 app/web/flutter_bootstrap.js create mode 100644 scripts/precompress_web.mjs create mode 100644 web/src/appFiles.js create mode 100644 web/test/appFiles.test.mjs diff --git a/app/docker/build.sh b/app/docker/build.sh index 8deca337..8f30af2d 100755 --- a/app/docker/build.sh +++ b/app/docker/build.sh @@ -14,7 +14,10 @@ cd /tmp/work flutter pub get case "$kind" in web) - flutter build web --release --no-web-resources-cdn "$@" + # WebAssembly (skwasm) with the JavaScript (CanvasKit) build beside it: + # the loader picks wasm where the browser has WasmGC, else JavaScript. + # No source maps: they are not served. + flutter build web --release --wasm --no-web-resources-cdn --no-source-maps "$@" cp -R build/web/. /out/ ;; apk) diff --git a/app/lib/features/chat/speech/flutter_tts_speech_engine.dart b/app/lib/features/chat/speech/flutter_tts_speech_engine.dart index 15799a06..ec2c0ce6 100644 --- a/app/lib/features/chat/speech/flutter_tts_speech_engine.dart +++ b/app/lib/features/chat/speech/flutter_tts_speech_engine.dart @@ -4,7 +4,10 @@ import 'package:flutter_tts/flutter_tts.dart'; import 'speech_engine.dart'; -/// [SpeechEngine] over the `flutter_tts` plugin (Android, Apple, web). +/// The platform engine off the web (the web uses `web_speech_engine.dart`). +SpeechEngine createSpeechEngine() => FlutterTtsSpeechEngine(); + +/// [SpeechEngine] over the `flutter_tts` plugin (Android, Apple, Windows). /// The plugin is created on first use so merely building the UI opens no /// platform channel. class FlutterTtsSpeechEngine extends SpeechEngine { diff --git a/app/lib/features/chat/speech/speech_controller.dart b/app/lib/features/chat/speech/speech_controller.dart index 757f2e3c..7fa314d6 100644 --- a/app/lib/features/chat/speech/speech_controller.dart +++ b/app/lib/features/chat/speech/speech_controller.dart @@ -2,7 +2,8 @@ import 'dart:async'; import 'package:flutter/widgets.dart'; -import 'flutter_tts_speech_engine.dart'; +import 'flutter_tts_speech_engine.dart' + if (dart.library.js_interop) 'web_speech_engine.dart'; import 'speech_document.dart'; import 'speech_engine.dart'; import 'speech_preferences.dart'; @@ -13,7 +14,7 @@ enum SpeechState { idle, speaking, paused } /// changes; the spoken word moves on the separate, frequent [word]. class SpeechController extends ChangeNotifier with WidgetsBindingObserver { SpeechController({SpeechEngine? engine, SpeechPreferencesStore? store}) - : engine = engine ?? FlutterTtsSpeechEngine(), + : engine = engine ?? createSpeechEngine(), _store = store ?? const SharedSpeechPreferencesStore() { WidgetsBinding.instance.addObserver(this); this.engine diff --git a/app/lib/features/chat/speech/web_speech_engine.dart b/app/lib/features/chat/speech/web_speech_engine.dart new file mode 100644 index 00000000..e9521a7f --- /dev/null +++ b/app/lib/features/chat/speech/web_speech_engine.dart @@ -0,0 +1,155 @@ +import 'dart:async'; +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:web/web.dart' as web; + +import 'speech_engine.dart'; + +/// The platform engine on the web: the browser's Web Speech API directly. +SpeechEngine createSpeechEngine() => WebSpeechEngine(); + +/// [SpeechEngine] over `window.speechSynthesis` through `package:web`. +/// +/// It replaces the flutter_tts web plugin, whose JS interop casts +/// (`event['charIndex'] as int`) and method-channel error payloads fail +/// under WebAssembly: word progress and error reports never arrived there. +/// The behaviour matches that plugin: speaking while paused resumes, and a +/// remote voice is kept alive with a pause/resume every 14 seconds (Chrome +/// stops a network voice after about 15 seconds of speech). +class WebSpeechEngine extends SpeechEngine { + web.SpeechSynthesisUtterance? _utterance; + web.SpeechSynthesisVoice? _voice; + double _rate = 1; + bool _paused = false; + Timer? _keepAlive; + + @override + bool get supported => web.window.has('speechSynthesis'); + + web.SpeechSynthesis get _synth => web.window.speechSynthesis; + + @override + Future speak(String text) async { + if (text.isEmpty) return; + if (_paused && _utterance != null) { + _paused = false; + _synth.resume(); + return; + } + final utterance = web.SpeechSynthesisUtterance(text)..rate = _rate; + final voice = _voice; + if (voice != null) { + utterance + ..voice = voice + ..lang = voice.lang; + } + _listen(utterance); + _utterance = utterance; + _paused = false; + _synth.speak(utterance); + } + + void _listen(web.SpeechSynthesisUtterance utterance) { + bool current() => identical(_utterance, utterance); + utterance + ..onstart = ((web.Event _) { + if (!current()) return; + onStart?.call(); + if (!(utterance.voice?.localService ?? false)) _keepAliveWhileSpeaking(); + }).toJS + ..onend = ((web.Event _) { + if (!current()) return; + _finish(); + onCompletion?.call(); + }).toJS + ..onpause = ((web.Event _) { + if (current() && _paused) onPause?.call(); + }).toJS + ..onresume = ((web.Event _) { + if (current() && !_paused) onResume?.call(); + }).toJS + ..onerror = ((web.SpeechSynthesisErrorEvent event) { + if (!current()) return; + _finish(); + onError?.call(event.error); + }).toJS + ..onboundary = ((web.SpeechSynthesisEvent event) { + if (!current() || event.name == 'sentence') return; + final text = utterance.text; + final start = event.charIndex.clamp(0, text.length); + onProgress?.call(text, start, _wordEnd(text, start, event.charLength)); + }).toJS; + } + + /// The end of the word at [start]: the browser's length when it reports + /// one, else the next space or punctuation (as flutter_tts did). + static int _wordEnd(String text, int start, int length) { + if (length > 0) return (start + length).clamp(start, text.length); + var end = start; + while (end < text.length && !RegExp(r'[\s,.!?]').hasMatch(text[end])) { + end++; + } + return end; + } + + void _keepAliveWhileSpeaking() { + _keepAlive?.cancel(); + _keepAlive = Timer.periodic(const Duration(seconds: 14), (_) { + if (_paused || _utterance == null) return; + _synth + ..pause() + ..resume(); + }); + } + + void _finish() { + _keepAlive?.cancel(); + _keepAlive = null; + _paused = false; + } + + @override + Future pause() async { + if (_utterance == null || _paused) return; + _paused = true; + _synth.pause(); + } + + @override + Future stop() async { + _paused = false; + _keepAlive?.cancel(); + _keepAlive = null; + _synth.cancel(); + } + + @override + Future setRate(double rate) async => _rate = rate; + + @override + Future setVoice(SpeechVoice? voice) async { + _voice = voice == null + ? null + : _browserVoices().where( + (item) => item.name == voice.name && item.lang == voice.locale, + ).firstOrNull; + } + + @override + Future> voices() async { + var voices = _browserVoices(); + // Browsers load their voice list asynchronously after the first request. + for (var attempt = 0; voices.isEmpty && attempt < 4; attempt++) { + await Future.delayed(const Duration(milliseconds: 250)); + voices = _browserVoices(); + } + return [ + for (final voice in voices) + SpeechVoice.fromPlatform({'name': voice.name, 'locale': voice.lang}), + ]; + } + + List _browserVoices() => + supported ? _synth.getVoices().toDart : const []; +} diff --git a/app/notes/web-wasm-build.md b/app/notes/web-wasm-build.md new file mode 100644 index 00000000..dd2a2473 --- /dev/null +++ b/app/notes/web-wasm-build.md @@ -0,0 +1,90 @@ +# Web build: WebAssembly, isolation, caching and compression + +## Decision + +The installed web app is built with `flutter build web --wasm` +(`app/docker/build.sh`): dart2wasm + skwasm in Chromium-based browsers with +WasmGC and WebGL (Flutter's loader allows wasm only on Blink by default), and +the dart2js + CanvasKit build beside it, which the loader picks otherwise +(Firefox, Safari, no WebGL). The proxy serves the app +cross-origin isolated (COOP `same-origin`, COEP `credentialless`), so skwasm +renders on a worker thread. + +`credentialless`, not `require-corp`: a sandboxed HTML artifact (srcdoc +iframe, which inherits the page's COEP) and chat markdown can show images +from other sites that send no Cross-Origin-Resource-Policy. Checked in the +browser: an HTML artifact with a cross-origin, no-CORP `` still renders +under isolation. The WebSocket, same-origin `/artifacts/` fetches, video and +the Roboto fallback font from fonts.gstatic.com (CORS) are unaffected +(WebSocket against a live server not exercised here). + +## Compatibility + +- Our own web code already used `dart:js_interop`/`package:web`; the wasm + dry run reported only `flutter_tts`'s web plugin (`event['charIndex'] as + int`, a `JSAny` error payload sent over a method channel). Both break word + highlighting and error reports under wasm, so the web now uses + `lib/features/chat/speech/web_speech_engine.dart` (Web Speech API through + `package:web`, same behaviour as the plugin). The plugin still registers + on the web, so the dry-run warning remains. Read aloud with real voices + under wasm is unverified: headless Chrome has no voices. +- `app/web/flutter_bootstrap.js` registers no service worker (Flutter's is + deprecated; it only unregistered itself and reloaded the page, a second + startup after every install). + +## Serving (web/src/appFiles.js) + +- An installed build has `release.json`; the shell page gets + `` and the + bootstrap loads the entrypoint, renderer and assets from there. Those + responses are `private, max-age=31536000, immutable`. Another build's id + (a tab left open over an install) gets the current file, `no-cache`. +- The shell is `no-store`; every other file is `no-cache` with an ETag (304). +- `scripts/precompress_web.mjs` (run by `scripts/app_build.py`, cached with + the build) writes `.br`/`.gz`; the proxy sends them by `Accept-Encoding`. + main.dart.wasm 4.8 MB -> 1.4 MB br, skwasm.wasm 3.6 -> 1.2, main.dart.js + 5.3 -> 1.2, canvaskit.wasm 7.2 -> 2.2. A first load on wasm transfers about + 2.7 MB instead of 12.5 MB uncompressed JS + CanvasKit. +- A reload transfers only the shell and a 304 for flutter_bootstrap.js. +- `./install --web` installs the build; the proxy (`lib/web`) changes take + effect after a full install restarts it. The new build also works behind the + old proxy (no isolation: skwasm single-threaded; no immutable caching). + +## Measurements (2026-12-01, Linux, RTX 2080 Ti, Chromium 155, load avg 10-20) + +`tool/perf/interaction_bench.mjs --gpu --repeat 3 --memory` over the probe +fixture (release builds), medians. A = JS/CanvasKit as installed before (with +the service-worker registration), B = JS with the new bootstrap and isolation, +C = wasm without isolation, D = wasm isolated (what is installed now). + +| scenario | metric | A js | B js+iso | C wasm | D wasm+iso | +| --- | --- | --- | --- | --- | --- | +| startup | first frame ms | 784 | 479 | 262 | 318 | +| startup | build sum ms | 184 | 109 | 49 | 73 | +| chat list -> open chat | build sum / longest ms | 48.9 / 21.4 | 22.1 / 9.6 | 6.3 / 3.5 | 8.6 / 22.1 | +| scroll a rich chat | build sum / max ms | 426 / 33.7 | 312 / 20.4 | 113 / 9.4 | 110 / 10.1 | +| scroll a rich chat | frames over 16 ms | 7 | 6 | 0 | 0 | +| switch chat | build sum / longest ms | 171 / 53.6 | 133 / 38.2 | 56 / 12.1 | 59 / 25.8 | +| open terminal panel | build sum / longest ms | 263 / 65.9 | 298 / 79.5 | 143 / 28.7 | 146 / 35.5 | +| tab runs -> chat (150) | build max / longest ms | 130 / 139 | 78 / 82 | 33 / 35 | 36 / 56 | +| memory | Chrome RSS after scroll, MB | 1477 | 1398 | 1332 | 1306 | + +Build (UI thread) time drops 2-4x with wasm. With isolation, skwasm's raster +runs on a worker, so its reported raster time (and frame span) includes the +hand-off; the main thread is what stays free. The terminal stream bench +(headless, no `--gpu`, 30 MB per workload) shows that directly in the page's +own rAF intervals (ms): + +| workload | js rAF p99 / max | wasm rAF p99 / max | wasm+iso rAF p99 / max | build p50 js / wasm | +| --- | --- | --- | --- | --- | +| seq | 33.3 / 66.6 | 33.3 / 33.3 | 16.7 / 16.7 | 2.3 / 1.0 | +| yes | 16.8 / 49.9 | 16.8 / 33.3 | 16.7 / 16.7 | 1.5 / 0.6 | +| unicode | 116.7 / 166.7 | 49.9 / 100.1 | 33.3 / 66.7 | 3.0 / 1.2 | +| colors | 33.4 / 50 | 16.8 / 33.2 | 16.7 / 16.7 | 2.6 / 1.2 | +| screen | 33.3 / 66.7 | 16.8 / 33.3 | 16.7 / 16.7 | 3.6 / 2.1 | + +Headed Chromium on Xvfb has no WebGL, so the wasm build fell back to +CanvasKit there (confirming the fallback); its numbers equal the JS build's. +Headless without `--gpu` still had WebGL (SwiftShader), so skwasm ran. +The machine was shared with other agents' builds and tests; compare columns, +not absolute values. diff --git a/app/tool/capture/README.md b/app/tool/capture/README.md index 4ff1f5b4..b7760430 100644 --- a/app/tool/capture/README.md +++ b/app/tool/capture/README.md @@ -13,6 +13,10 @@ no longer matches the app. removes Chrome, the profile and the server. - It needs no npm packages: Node 22+ (global `WebSocket` and `fetch`) and Google Chrome (`CHROME_PATH` overrides the macOS default). +- `CAPTURE_ISOLATE=1` serves the build with the web proxy's cross-origin + isolation headers, so a `--wasm` build renders multi-threaded as installed. + `CAPTURE_HEADED=1` opens a real X11 window instead of headless (run under + `xvfb-run -a`; Xvfb has no WebGL, so the wasm build falls back to CanvasKit). ## The fixture app diff --git a/app/tool/capture/browser.mjs b/app/tool/capture/browser.mjs index c44b2103..9e96c8eb 100644 --- a/app/tool/capture/browser.mjs +++ b/app/tool/capture/browser.mjs @@ -14,7 +14,8 @@ const DEFAULT_CHROME ='/Applications/Google Chrome.app/Contents/MacOS/Google Chr async function launch(chromePath, gpu, args = []) { const profile = await mkdtemp(join(tmpdir(), 'pipelines-capture-chrome-')); const chrome = spawn(chromePath, [ - '--headless=new', '--no-first-run', '--no-default-browser-check', + // CAPTURE_HEADED=1 opens a real X11 window (under xvfb-run) instead. + ...(process.env.CAPTURE_HEADED === '1' ? ['--ozone-platform=x11'] : ['--headless=new']), '--no-first-run', '--no-default-browser-check', // Without a GPU CanvasKit rasterises on the CPU; `gpu` keeps WebGL (Metal // through ANGLE on a Mac) for benches that measure raster time. // Linux keeps the GPU through ANGLE on Vulkan. diff --git a/app/tool/capture/serve.mjs b/app/tool/capture/serve.mjs index b7080441..197f07d3 100644 --- a/app/tool/capture/serve.mjs +++ b/app/tool/capture/serve.mjs @@ -21,6 +21,13 @@ const MIME = { '.woff2': 'font/woff2', }; +// `CAPTURE_ISOLATE=1` adds the Pipelines proxy's cross-origin isolation +// headers (web/src/appFiles.js), so a `--wasm` build renders multi-threaded as +// it does when installed; without them skwasm runs single-threaded. +const ISOLATE = process.env.CAPTURE_ISOLATE === '1' + ? { 'cross-origin-opener-policy': 'same-origin', 'cross-origin-embedder-policy': 'credentialless' } + : {}; + /** Serves [dir]; resolves to `{ origin, close() }`. */ export async function serveBuild(dir) { const root = resolve(dir); @@ -41,6 +48,7 @@ export async function serveBuild(dir) { res.writeHead(200, { 'content-type': MIME[extname(file)] ?? 'application/octet-stream', 'cache-control': 'no-store', + ...ISOLATE, }).end(body); } catch { res.writeHead(404).end('not found'); diff --git a/app/tool/perf/interaction_bench.mjs b/app/tool/perf/interaction_bench.mjs index 64eb5ddf..73784845 100644 --- a/app/tool/perf/interaction_bench.mjs +++ b/app/tool/perf/interaction_bench.mjs @@ -7,6 +7,9 @@ // Startup reports the first rasterised frame (ms since navigation) and the // main.dart.js / canvaskit fetch times. // +// --memory (Linux) adds `rssMB`: the resident memory of every process of the +// private Chrome (renderer, GPU, workers) once the measured steps settle. +// // --cpuprofile records a V8 CPU profile of the measured steps (first rep), // writes `.cpuprofile` and prints the functions with the most // inclusive and self time; use a `flutter build web --profile` build so the @@ -22,7 +25,7 @@ // CanvasKit rasterises on the CPU, so compare builds with each other rather // than predicting a device. --gpu keeps the GPU (WebGL), which is what a // desktop user has: use it to judge raster time. -import { mkdir, writeFile } from 'node:fs/promises'; +import { mkdir, readFile, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { parseArgs } from 'node:util'; import { setTimeout as delay } from 'node:timers/promises'; @@ -33,7 +36,7 @@ import { attribute, loadSourceMap } from './cpu_attribution.mjs'; const { values: opts } = parseArgs({ options: { build: { type: 'string' }, out: { type: 'string' }, repeat: { type: 'string', default: '5' }, - only: { type: 'string' }, cpuprofile: { type: 'boolean' }, frames: { type: 'boolean' }, shots: { type: 'boolean' }, gpu: { type: 'boolean' }, size: { type: 'string', default: '560x900' }, + only: { type: 'string' }, cpuprofile: { type: 'boolean' }, frames: { type: 'boolean' }, shots: { type: 'boolean' }, gpu: { type: 'boolean' }, memory: { type: 'boolean' }, size: { type: 'string', default: '560x900' }, }, }); if (!opts.build || !opts.out) throw new Error('usage: --build --out '); @@ -106,6 +109,16 @@ const lookup = opts.cpuprofile ? await loadSourceMap(opts.build) : null; const server = await serveBuild(opts.build); const browser = await openBrowser({ gpu: Boolean(opts.gpu) }); const { send, on } = browser; +// Sums VmRSS over the browser's processes (SystemInfo ids are OS pids). +async function chromeRssMB() { + const { processInfo } = await browser.sendBrowser('SystemInfo.getProcessInfo'); + let kb = 0; + for (const { id } of processInfo) { + const status = await readFile(`/proc/${id}/status`, 'utf8').catch(() => ''); + kb += Number(status.match(/^VmRSS:\s+(\d+)/m)?.[1] ?? 0); + } + return kb / 1024; +} const evaluate = async (expression) => (await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true })).result?.value; let frames = []; let firstFrame = null; @@ -191,8 +204,14 @@ try { await delay(2000); const startup = s.name.startsWith('startup'); const loads = startup ? await evaluate(`Object.fromEntries(performance.getEntriesByType('resource') - .filter((e) => /main\\.dart\\.js|canvaskit\\.wasm/.test(e.name)) + .filter((e) => /main\\.dart\\.(js|wasm)$|canvaskit\\.wasm|skwasm(_heavy)?\\.wasm/.test(e.name)) .map((e) => [e.name.split('/').pop(), Math.round(e.responseEnd)]))`) : null; + if (startup && rep === 0) { + // Which build the loader picked: WebAssembly (skwasm, threaded only + // when cross-origin isolated) or JavaScript (CanvasKit). + console.log(` renderer: ${await evaluate(`(window._flutter_skwasmInstance ? 'skwasm' : window.flutterCanvasKit ? 'canvaskit' : '?') + + (window.crossOriginIsolated ? ' isolated' : '')`)}`); + } await run(s.setup); await settle(); const startFrames = startup ? 0 : frames.length; @@ -218,7 +237,8 @@ try { const sum = (i) => f.reduce((a, x) => a + x[i], 0) / 1000; const max = (i) => f.reduce((a, x) => Math.max(a, x[i]), 0) / 1000; reps.push({ frames: f.length, buildSum: sum(0), buildMax: max(0), rasterSum: sum(1), rasterMax: max(1), - longest: max(2), over16: f.filter((x) => x[2] > 16667).length, firstFrame, ...loads }); + longest: max(2), over16: f.filter((x) => x[2] > 16667).length, firstFrame, ...loads, + ...(opts.memory ? { rssMB: await chromeRssMB() } : {}) }); } const keys = Object.keys(reps[0]).filter((k) => typeof reps[0][k] === 'number'); results[s.name] = Object.fromEntries(keys.map((k) => [k, r1(median(reps.map((r) => r[k])))])); diff --git a/app/web/flutter_bootstrap.js b/app/web/flutter_bootstrap.js new file mode 100644 index 00000000..1f4fda42 --- /dev/null +++ b/app/web/flutter_bootstrap.js @@ -0,0 +1,18 @@ +{{flutter_js}} +{{flutter_build_config}} + +// The Pipelines web proxy (web/serve.mjs) names an installed build's +// versioned asset base, cached as immutable: the entrypoint, the renderer +// (skwasm or CanvasKit) and the app's assets all load from it. Without it (a +// development server) everything loads from the page's own base. +// +// No service worker is registered: Flutter's is deprecated and now only +// unregisters itself and reloads the page, which cost a second startup after +// every install. HTTP caching keeps repeat loads fast instead. +(() => { + const base = document.querySelector('meta[name="pipelines-asset-base"]')?.content; + const config = base + ? { entrypointBaseUrl: base, assetBase: base, canvasKitBaseUrl: base + "canvaskit/" } + : {}; + _flutter.loader.load({ config }); +})(); diff --git a/scripts/app_build.py b/scripts/app_build.py index e51250a3..ea1b8135 100644 --- a/scripts/app_build.py +++ b/scripts/app_build.py @@ -46,7 +46,9 @@ SOURCES = { SKIPPED = {"build", ".dart_tool", ".gradle", ".cxx", "local.properties", ".DS_Store", "ephemeral", "Pods", ".symlinks"} # This is part of the web cache key so entries made before release metadata was # generated cannot be mistaken for complete web releases. -WEB_CACHE_SCHEMA = "web-release-metadata-v1" +# v2: WebAssembly beside JavaScript, precompressed (.br/.gz) assets. +WEB_CACHE_SCHEMA = "web-wasm-precompressed-v2" +PRECOMPRESS = Path(__file__).with_name("precompress_web.mjs") WEB_RELEASE_SCHEMA = 1 VERBOSE = False @@ -61,6 +63,7 @@ def digest(kind, app=APP, extra=()): hasher.update(kind.encode()) if kind == "web": hasher.update(b"\0cache-schema\0" + WEB_CACHE_SCHEMA.encode()) + hasher.update(b"\0precompress\0" + PRECOMPRESS.read_bytes()) if kind in ("linux", "macos"): hasher.update(b"\0cache-schema\0desktop-v1") for script in (Path(__file__), Path(__file__).with_name("app_desktop_build.py")): @@ -216,6 +219,7 @@ def build(kind, runner=subprocess.run, app=APP, cache=None, arguments=(), log=pr (work / "data/flutter_assets").is_dir() and (work / "lib").is_dir()): raise RuntimeError("Linux build did not produce its complete executable/data/lib bundle") if kind == "web": + precompress_web(work, runner, log) (work / "release.json").write_text(json.dumps(web_release_metadata(key)) + "\n") (work / ".complete").write_text(json.dumps({"key": key, "built": built}) + "\n") if entry.exists(): @@ -228,6 +232,22 @@ def build(kind, runner=subprocess.run, app=APP, cache=None, arguments=(), log=pr return entry +def precompress_web(directory, runner=subprocess.run, log=print): + """Writes the .br/.gz variants the web proxy serves (precompress_web.mjs). + + Node runs the web proxy, so an installation has it; without it the build + is still complete and is served uncompressed.""" + node = shutil.which("node") + if not node: + log("Node.js was not found; the web app is served uncompressed.") + return + result = runner([node, str(PRECOMPRESS), str(directory)], capture_output=True, text=True) + if result.returncode: + raise RuntimeError("precompressing the web build failed: " + (result.stderr or "").strip()[-300:]) + if VERBOSE and result.stdout: + log(result.stdout.strip()) + + def prune(cache, kind, keep): entries = sorted((p for p in cache.glob(f"{kind}-*") if (p / ".complete").is_file()), key=lambda p: p.stat().st_mtime, reverse=True) diff --git a/scripts/precompress_web.mjs b/scripts/precompress_web.mjs new file mode 100644 index 00000000..439c3441 --- /dev/null +++ b/scripts/precompress_web.mjs @@ -0,0 +1,70 @@ +#!/usr/bin/env node +// Writes brotli (.br) and gzip (.gz) siblings for the compressible files of a +// Flutter web build, which the web proxy sends to browsers that accept them +// (web/src/appFiles.js). Run once per build by scripts/app_build.py: +// +// node scripts/precompress_web.mjs +// +// A variant is kept only when it saves at least a tenth of the file. +import { readdir, readFile, stat, writeFile } from "node:fs/promises"; +import { extname, join } from "node:path"; +import { promisify } from "node:util"; +import { brotliCompress, constants, gzip } from "node:zlib"; + +const COMPRESSIBLE = new Set([".js", ".mjs", ".wasm", ".json", ".ttf", ".otf", ".html", ".css", ".svg", ".txt", ".frag", ".bin"]); +// Flutter's licence notices have no extension. +const NAMED = new Set(["NOTICES"]); +const MIN_BYTES = 1024; +const brotli = promisify(brotliCompress); +const gz = promisify(gzip); + +async function* files(dir) { + for (const entry of await readdir(dir, { withFileTypes: true })) { + const path = join(dir, entry.name); + if (entry.isDirectory()) yield* files(path); + else if (entry.isFile()) yield path; + } +} + +async function compress(path) { + const body = await readFile(path); + const [br, gzipped] = await Promise.all([ + brotli(body, { + params: { + [constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY, + [constants.BROTLI_PARAM_SIZE_HINT]: body.length, + }, + }), + gz(body, { level: 9 }), + ]); + let saved = 0; + for (const [suffix, data] of [[".br", br], [".gz", gzipped]]) { + if (data.length > body.length * 0.9) continue; + await writeFile(path + suffix, data); + saved = Math.max(saved, body.length - data.length); + } + return { size: body.length, saved }; +} + +const root = process.argv[2]; +if (!root) { + console.error("usage: precompress_web.mjs "); + process.exit(2); +} +const work = []; +for await (const path of files(root)) { + const name = path.split(/[\\/]/).pop(); + if (!(COMPRESSIBLE.has(extname(path).toLowerCase()) || NAMED.has(name))) continue; + if ((await stat(path)).size < MIN_BYTES) continue; + work.push(path); +} +// zlib's async calls run on libuv's thread pool, a few at a time. +let size = 0; +let saved = 0; +for (let i = 0; i < work.length; i += 4) { + for (const result of await Promise.all(work.slice(i, i + 4).map(compress))) { + size += result.size; + saved += result.saved; + } +} +console.log(`Precompressed ${work.length} files: ${(size / 1e6).toFixed(1)} MB, ${(saved / 1e6).toFixed(1)} MB smaller with brotli.`); diff --git a/scripts/test_app_build.py b/scripts/test_app_build.py index 27cdebe7..0bf965c4 100644 --- a/scripts/test_app_build.py +++ b/scripts/test_app_build.py @@ -116,6 +116,25 @@ class AppBuildTests(unittest.TestCase): self.assertEqual(json.loads((output / "release.json").read_text()), { "schema": 1, "platform": "web", "buildId": identity}) + def test_web_build_is_precompressed_before_it_is_cached(self): + runner = Runner() + with patch.object(app_build.shutil, "which", return_value="/usr/bin/node"): + output = app_build.build("web", runner=runner, cache=Path(self.home.name) / "cache", log=lambda *_: None) + call = next(call for call in runner.calls if call[0] == "/usr/bin/node") + self.assertEqual(call[1], str(app_build.PRECOMPRESS)) + # It ran on the build's staging directory, which became the entry. + self.assertEqual(Path(call[2]).parent, output.parent) + docker_run = next(i for i, c in enumerate(runner.calls) if c[:2] == ["docker", "run"]) + self.assertLess(docker_run, runner.calls.index(call)) + + def test_web_build_without_node_is_served_uncompressed(self): + runner = Runner() + messages = [] + with patch.object(app_build.shutil, "which", return_value=None): + app_build.build("web", runner=runner, cache=Path(self.home.name) / "cache", log=messages.append) + self.assertFalse(any("precompress_web.mjs" in " ".join(c) for c in runner.calls)) + self.assertTrue(any("uncompressed" in m for m in messages)) + def test_old_web_cache_without_release_metadata_is_rebuilt(self): runner = Runner() cache = Path(self.home.name) / "cache" diff --git a/web/README.md b/web/README.md index 14f0cbaf..1ef18b76 100644 --- a/web/README.md +++ b/web/README.md @@ -13,6 +13,13 @@ node serve.mjs --port 8082 --host 0.0.0.0 --pipelines 127.0.0.1:8080 \ - `--root` is the web app (default: `../app/build/web`). Without a build, the page explains how to make one (`./install --web`). +- The app is served cross-origin isolated (COOP `same-origin`, COEP + `credentialless`), so its WebAssembly renderer runs multi-threaded. An + installed build (with `release.json`) loads its files from + `/_v//`, cached as immutable; the shell is never cached and the + other files revalidate by ETag. Files precompressed by the installer + (`.br`, `.gz`, `scripts/precompress_web.mjs`) are sent to browsers that + accept them. See `src/appFiles.js`. - `--updates` serves the Android app's `version.json` and APK at `/updates/` (`./install --apk`), behind the same sign-in. - The password lives in `~/.config/pipelines/web-auth.json` diff --git a/web/serve.mjs b/web/serve.mjs index 1055c51b..a0ea542b 100644 --- a/web/serve.mjs +++ b/web/serve.mjs @@ -44,6 +44,7 @@ import { } from "./src/webSecurity.js"; import { PeerRelay, proxyDiscovery } from "./src/peerRelay.js"; import { accessPolicy, PLAIN_LAN_REFUSAL } from "./src/listenPolicy.js"; +import { AppFiles, ISOLATION_HEADERS, VERSIONED_PREFIX } from "./src/appFiles.js"; // The proxy's own directory holds the sign-in page's icons. const HERE = resolve(fileURLToPath(new URL(".", import.meta.url))); @@ -350,6 +351,7 @@ const MIME = { // route still serves the shell, while an asset-looking path elsewhere (`/nope.js`) // stays an honest 404 and a real file (`/src/app.js`) is still served. const ASSET_EXTENSIONS = new Set([...Object.keys(MIME), ".woff", ".woff2", ".txt"]); +const appFiles = new AppFiles(ROOT, MIME); const PAGE_PREFIXES = new Set(["pipelines", "runs", "chat", "settings", "templates"]); /** The decoded first path segment, or "" for the root. */ @@ -441,8 +443,13 @@ async function serveIndex(res) { // A deep URL such as /runs/440 would otherwise resolve the shell's relative // `./src/app.js` against /runs/. A root keeps the shell's own asset URLs // absolute without changing the address bar (and without editing index.html). - const body = html.replace(//i, '\n '); + // An installed build also names its versioned, immutable asset base, which + // the app's flutter_bootstrap.js reads (src/appFiles.js). + const base = await appFiles.assetBase(); + const meta = base ? `\n ` : ""; + const body = html.replace(//i, `\n ${meta}`); res.writeHead(200, { + ...ISOLATION_HEADERS, "Content-Type": MIME[".html"], "Cache-Control": "no-store", }); @@ -630,6 +637,20 @@ const server = createServer(async (req, res) => { const assetLike = ASSET_EXTENSIONS.has(extname(pathname).toLowerCase()); const pageLike = PAGE_PREFIXES.has(firstSegment(pathname)); const serveShell = pageLike || !assetLike; + if (pathname.startsWith(VERSIONED_PREFIX)) { + const file = await appFiles.versioned(pathname); + if (file === false) { + res.writeHead(403).end("Forbidden"); + return; + } + try { + if (!file) throw new Error("malformed"); + await appFiles.send(req, res, file.path, { immutable: file.immutable }); + } catch { + if (!res.headersSent) res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found"); + } + return; + } const target = resolvePath(req.url ?? "/"); if (target === null) { // A malformed percent escape is an unknown page route, not a handler throw. @@ -650,12 +671,12 @@ const server = createServer(async (req, res) => { let path = target; const info = await stat(path).catch(() => null); if (info?.isDirectory()) path = join(path, "index.html"); - const body = await readFile(path); - res.writeHead(200, { - "Content-Type": MIME[extname(path)] ?? "application/octet-stream", - "Cache-Control": "no-store", - }); - res.end(body); + // The shell itself always goes through serveIndex (no-store, base tags). + if (path === join(ROOT, "index.html")) { + await serveIndex(res); + return; + } + await appFiles.send(req, res, path); } catch { if (serveShell) { await serveIndex(res).catch(() => { diff --git a/web/src/appFiles.js b/web/src/appFiles.js new file mode 100644 index 00000000..bfd331e7 --- /dev/null +++ b/web/src/appFiles.js @@ -0,0 +1,156 @@ +// How the proxy serves the Flutter web build: cross-origin isolation, cache +// policy, validators and precompressed variants. +// +// Flutter's output names are not content-hashed (main.dart.js, canvaskit/…), so +// a long-lived cache needs a versioned address instead. An installed build +// carries release.json with its buildId; the shell page then names +// `/_v//` as the asset base (see app/web/flutter_bootstrap.js), and +// everything under it is immutable for a year. A new install changes the id, +// so the next page load fetches the new files. The shell, the bootstrap script +// and the small metadata files are revalidated on every load (ETag, 304). +import { createReadStream } from "node:fs"; +import { readFile, stat } from "node:fs/promises"; +import { extname, join, normalize, resolve, sep } from "node:path"; + +/** + * Cross-origin isolation, so the WebAssembly build's renderer (skwasm) can run + * multi-threaded (SharedArrayBuffer). `credentialless` rather than + * `require-corp`: images and other no-cors loads from other sites (in chat + * markdown or a sandboxed HTML preview) still load, without cookies, instead + * of being blocked for lacking a Cross-Origin-Resource-Policy header. + */ +export const ISOLATION_HEADERS = Object.freeze({ + "Cross-Origin-Opener-Policy": "same-origin", + "Cross-Origin-Embedder-Policy": "credentialless", +}); + +/** The versioned asset prefix: `/_v//`. */ +export const VERSIONED_PREFIX = "/_v/"; +const IMMUTABLE = "private, max-age=31536000, immutable"; +const REVALIDATE = "no-cache"; +const BUILD_ID = /^[A-Za-z0-9._-]{1,80}$/; + +/** Encodings precompressed at install time (scripts/app_build.py), best first. */ +const ENCODINGS = [ + ["br", ".br"], + ["gzip", ".gz"], +]; + +/** The encodings a request accepts (`q=0` excluded). */ +export function acceptedEncodings(header) { + const accepted = new Set(); + for (const part of String(header ?? "").split(",")) { + const [name, ...params] = part.trim().toLowerCase().split(";"); + const q = params.map((p) => p.trim()).find((p) => p.startsWith("q=")); + if (name && !(q && Number(q.slice(2)) === 0)) accepted.add(name); + } + return accepted; +} + +export class AppFiles { + /** [root] is the web build directory; [mime] maps extensions to types. */ + constructor(root, mime) { + this.root = resolve(root); + this.mime = mime; + this._release = { mtimeMs: -1, id: null }; + } + + /** The installed build's id from release.json, or null (a dev build). */ + async buildId() { + const path = join(this.root, "release.json"); + const info = await stat(path).catch(() => null); + if (!info?.isFile()) return null; + if (info.mtimeMs !== this._release.mtimeMs) { + let id = null; + try { + const value = JSON.parse(await readFile(path, "utf8"))?.buildId; + id = typeof value === "string" && BUILD_ID.test(value) ? value : null; + } catch { + id = null; + } + this._release = { mtimeMs: info.mtimeMs, id }; + } + return this._release.id; + } + + /** The asset base the shell page names, or null when the build has no id. */ + async assetBase() { + const id = await this.buildId(); + return id ? `${VERSIONED_PREFIX}${id}/` : null; + } + + /** + * A versioned request's file: `{ path, immutable }`, false when it escapes + * the root, or null for a malformed one. A request for another build's id + * (a tab left open across an install) gets the current file, revalidated. + */ + async versioned(pathname) { + const rest = pathname.slice(VERSIONED_PREFIX.length); + const slash = rest.indexOf("/"); + if (slash <= 0) return null; + const id = rest.slice(0, slash); + let rel; + try { + rel = decodeURIComponent(rest.slice(slash + 1)); + } catch { + return null; + } + rel = normalize(rel).replace(/^([/\\])+/, ""); + if (!rel || rel === ".") return null; + const path = resolve(join(this.root, rel)); + if (!path.startsWith(this.root + sep)) return false; + return { path, immutable: id === (await this.buildId()) }; + } + + /** + * Sends one file of the build: an ETag (304 when it matches), the cache + * policy, the isolation headers and, when the client accepts it, the + * precompressed variant beside the file. Rejects when the file is missing. + */ + async send(req, res, path, { immutable = false } = {}) { + const info = await stat(path); + if (!info.isFile()) throw new Error("not a file"); + const etag = `W/"${info.size.toString(36)}-${Math.floor(info.mtimeMs).toString(36)}"`; + const headers = { + ...ISOLATION_HEADERS, + "Content-Type": this.mime[extname(path)] ?? "application/octet-stream", + "Cache-Control": immutable ? IMMUTABLE : REVALIDATE, + ETag: etag, + Vary: "Accept-Encoding", + }; + const match = String(req.headers["if-none-match"] ?? ""); + if (match && match.split(",").some((tag) => tag.trim() === etag || tag.trim() === "*")) { + res.writeHead(304, headers).end(); + return; + } + let file = path; + let size = info.size; + const accepted = acceptedEncodings(req.headers["accept-encoding"]); + for (const [encoding, suffix] of ENCODINGS) { + if (!accepted.has(encoding)) continue; + const variant = await stat(path + suffix).catch(() => null); + // A variant older than its file is stale (a hand-copied build). + if (variant?.isFile() && variant.mtimeMs >= info.mtimeMs) { + file = path + suffix; + size = variant.size; + headers["Content-Encoding"] = encoding; + break; + } + } + headers["Content-Length"] = size; + res.writeHead(200, headers); + if (req.method === "HEAD") { + res.end(); + return; + } + await new Promise((done) => { + const stream = createReadStream(file); + stream.on("error", () => { + res.destroy(); + done(); + }); + stream.on("end", done); + stream.pipe(res); + }); + } +} diff --git a/web/test/appFiles.test.mjs b/web/test/appFiles.test.mjs new file mode 100644 index 00000000..a1e578b0 --- /dev/null +++ b/web/test/appFiles.test.mjs @@ -0,0 +1,124 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { mkdtemp, mkdir, utimes, writeFile } from "node:fs/promises"; +import { get } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import net from "node:net"; +import { brotliCompressSync, brotliDecompressSync, gzipSync } from "node:zlib"; +import { acceptedEncodings } from "../src/appFiles.js"; + +const here = fileURLToPath(new URL("..", import.meta.url)); + +async function freePort() { + const server = net.createServer().listen(0, "127.0.0.1"); + await new Promise((done) => server.once("listening", done)); + const { port } = server.address(); + await new Promise((done) => server.close(done)); + return port; +} + +async function start(root) { + const port = await freePort(); + const child = spawn(process.execPath, ["serve.mjs", "--port", String(port), "--root", root], { + cwd: here, + env: { ...process.env, PIPELINES_WEB_AUTH: "disabled" }, + stdio: ["ignore", "pipe", "inherit"], + }); + await new Promise((done) => child.stdout.once("data", done)); + return { port, stop: () => child.kill() }; +} + +/** A raw GET (fetch would decode the body and hide Content-Encoding). */ +function request(port, path, headers = {}) { + return new Promise((resolve, reject) => { + get({ host: "127.0.0.1", port, path, headers }, (res) => { + const chunks = []; + res.on("data", (chunk) => chunks.push(chunk)); + res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks) })); + }).on("error", reject); + }); +} + +async function build({ release = true } = {}) { + const root = join(await mkdtemp(join(tmpdir(), "app-files-")), "app"); + await mkdir(join(root, "canvaskit"), { recursive: true }); + await writeFile(join(root, "index.html"), ''); + await writeFile(join(root, "flutter_bootstrap.js"), "bootstrap()"); + const script = "main();".repeat(400); + await writeFile(join(root, "main.dart.js"), script); + await writeFile(join(root, "main.dart.js.br"), brotliCompressSync(script)); + await writeFile(join(root, "main.dart.js.gz"), gzipSync(script)); + await writeFile(join(root, "canvaskit", "skwasm.wasm"), "wasm"); + if (release) await writeFile(join(root, "release.json"), '{"schema":1,"platform":"web","buildId":"web-abc123"}'); + return { root, script }; +} + +test("the shell is isolated, uncached and names the versioned asset base", async (t) => { + const { root } = await build(); + const server = await start(root); + t.after(server.stop); + for (const path of ["/", "/chat/7"]) { + const page = await request(server.port, path); + assert.equal(page.status, 200); + assert.equal(page.headers["cross-origin-opener-policy"], "same-origin"); + assert.equal(page.headers["cross-origin-embedder-policy"], "credentialless"); + assert.equal(page.headers["cache-control"], "no-store"); + assert.match(page.body.toString(), //); + } +}); + +test("versioned assets of the current build are immutable; another build's revalidate", async (t) => { + const { root, script } = await build(); + const server = await start(root); + t.after(server.stop); + const current = await request(server.port, "/_v/web-abc123/main.dart.js", { "accept-encoding": "gzip, br" }); + assert.equal(current.status, 200); + assert.equal(current.headers["cache-control"], "private, max-age=31536000, immutable"); + assert.equal(current.headers["content-encoding"], "br"); + assert.equal(current.headers.vary, "Accept-Encoding"); + assert.equal(current.headers["cross-origin-embedder-policy"], "credentialless"); + assert.equal(brotliDecompressSync(current.body).toString(), script); + const wasm = await request(server.port, "/_v/web-abc123/canvaskit/skwasm.wasm"); + assert.equal(wasm.headers["content-type"], "application/wasm"); + assert.equal(wasm.body.toString(), "wasm"); + const stale = await request(server.port, "/_v/web-old/main.dart.js"); + assert.equal(stale.status, 200); + assert.equal(stale.headers["cache-control"], "no-cache"); + assert.equal(stale.body.toString(), script); + assert.equal((await request(server.port, "/_v/web-abc123/missing.js")).status, 404); + assert.equal((await request(server.port, "/_v/web-abc123/%2e%2e/%2e%2e/etc/passwd")).status, 403); + assert.equal((await request(server.port, "/_v/web-abc123/")).status, 404); +}); + +test("unversioned files revalidate with an ETag, compressed only when accepted", async (t) => { + const { root, script } = await build({ release: false }); + const server = await start(root); + t.after(server.stop); + const page = await request(server.port, "/"); + assert.doesNotMatch(page.body.toString(), /pipelines-asset-base/); + const plain = await request(server.port, "/main.dart.js"); + assert.equal(plain.headers["cache-control"], "no-cache"); + assert.equal(plain.headers["content-encoding"], undefined); + assert.equal(plain.body.toString(), script); + const gzip = await request(server.port, "/main.dart.js", { "accept-encoding": "gzip" }); + assert.equal(gzip.headers["content-encoding"], "gzip"); + const again = await request(server.port, "/main.dart.js", { "if-none-match": plain.headers.etag }); + assert.equal(again.status, 304); + assert.equal(again.body.length, 0); + const bootstrap = await request(server.port, "/flutter_bootstrap.js"); + assert.equal(bootstrap.headers["cache-control"], "no-cache"); + // A variant older than its file (a hand-edited build) is not sent. + const past = new Date(Date.now() - 60_000); + await utimes(join(root, "main.dart.js.br"), past, past); + const edited = await request(server.port, "/main.dart.js", { "accept-encoding": "br" }); + assert.equal(edited.headers["content-encoding"], undefined); +}); + +test("accepted encodings honour q=0", () => { + assert.deepEqual([...acceptedEncodings("gzip, deflate, br, zstd")], ["gzip", "deflate", "br", "zstd"]); + assert.deepEqual([...acceptedEncodings("br;q=0, gzip;q=0.5")], ["gzip"]); + assert.deepEqual([...acceptedEncodings(undefined)], []); +});