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/<buildId>/ 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 <noreply@anthropic.com>
This commit is contained in:
+21
-1
@@ -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)
|
||||
|
||||
@@ -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 <build dir>
|
||||
//
|
||||
// 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 <build dir>");
|
||||
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.`);
|
||||
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user