aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 2f44ef76b1b2272e96de7cda1f12e1c8e062ff2c
parent f08d2c86a02b8a7b564577cc392af790ef43639c
Author: anon <anon@example.com>
Date:   Sun, 18 Oct 2026 08:17:28 +0000

Reduce browser client downloads with cached Brotli compression

Diffstat:
MREADME.md | 6++++--
Mserver/browser_client.go | 8++++----
Mserver/browser_client_test.go | 32++++++++++----------------------
Msrc/browser/index.html | 8++++----
Msrc/tests/browser_loading.mjs | 22+++++++++++-----------
Mtools/client/publish_wasm.py | 30++++++++++++++++++++++--------
Atools/client/test_publish_wasm.py | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 125 insertions(+), 51 deletions(-)

diff --git a/README.md b/README.md @@ -5,7 +5,7 @@ Run commands from the repository root. Compressed runtime data is checked in; the compiled browser client is kept outside Git. Server development needs Go 1.24 or newer and a copy of the six matching files in `client/`: -`index.html`, `game.js`, `game.wasm.gz`, `profile-worker.js`, `audio-worklet.js`, and `build.json`. +`index.html`, `game.js`, `game.wasm.br`, `profile-worker.js`, `audio-worklet.js`, and `build.json`. Copy the entire directory from a client build machine, preserving timestamps: ```sh @@ -68,7 +68,7 @@ Only the client build machine needs this toolchain. Install the native build dependencies and the pinned Emscripten SDK once: ```sh -sudo apt-get install build-essential cmake pkg-config git python3 xz-utils ca-certificates +sudo apt-get install build-essential cmake pkg-config git python3 python3-brotli xz-utils ca-certificates mkdir -p toolchains git clone https://github.com/emscripten-core/emsdk.git toolchains/emsdk ./toolchains/emsdk/emsdk install 6.0.12 @@ -86,6 +86,8 @@ six files above to ignored `client/`, where Go serves them. The first build is heavy; allow several gigabytes of build space and substantial compilation time. ThinLTO optimizes calls across source files with eight linker workers. Keep `src/build/wasm/lto-cache/` to reuse that work on subsequent builds. +Publishing also caches Brotli compression in `src/build/wasm/web/`, so page-only +updates reuse the compressed executable. The browser decodes it over HTTP. Copy the complete matching bundle to other machines after validating it. Do not mix JavaScript and WASM from different builds or commit generated client files. diff --git a/server/browser_client.go b/server/browser_client.go @@ -16,7 +16,7 @@ func browserClient(w http.ResponseWriter, r *http.Request) { if name == "/" || name == "" { name = "index.html" } else if name == "game.wasm" { - name = "game.wasm.gz" + name = "game.wasm.br" } if filepath.IsLocal(name) { if info, err := os.Stat(filepath.Join("client", name)); err == nil && info.Mode().IsRegular() { @@ -28,11 +28,11 @@ func browserClient(w http.ResponseWriter, r *http.Request) { return } - // Browsers decode the published gzip representation before compiling WASM. + // Browsers decode the published Brotli representation before compiling WASM. if r.URL.Path == "/wasm/game.wasm" { w.Header().Set("Content-Type", "application/wasm") - w.Header().Set("Content-Encoding", "gzip") - http.ServeFile(w, r, "client/game.wasm.gz") + w.Header().Set("Content-Encoding", "br") + http.ServeFile(w, r, "client/game.wasm.br") return } http.StripPrefix("/wasm/", http.FileServer(http.Dir("client"))).ServeHTTP(w, r) diff --git a/server/browser_client_test.go b/server/browser_client_test.go @@ -2,8 +2,6 @@ package main import ( "bytes" - "compress/gzip" - "io" "net/http" "net/http/httptest" "os" @@ -16,42 +14,30 @@ func TestBrowserClientServesPublishedWasm(t *testing.T) { if err := os.Mkdir("client", 0755); err != nil { t.Fatal(err) } - var compressed bytes.Buffer - writer := gzip.NewWriter(&compressed) - if _, err := writer.Write([]byte("\x00asm\x01\x00\x00\x00")); err != nil { - t.Fatal(err) - } - if err := writer.Close(); err != nil { - t.Fatal(err) - } - if err := os.WriteFile("client/game.wasm.gz", compressed.Bytes(), 0644); err != nil { + // Brotli representation of the minimal valid WebAssembly module. + compressed := []byte{139, 3, 128, 0, 97, 115, 109, 1, 0, 0, 0, 3} + if err := os.WriteFile("client/game.wasm.br", compressed, 0644); err != nil { t.Fatal(err) } request := httptest.NewRequest("GET", "/wasm/game.wasm", nil) - request.Header.Set("Accept-Encoding", "gzip") + request.Header.Set("Accept-Encoding", "br") response := httptest.NewRecorder() browserClient(response, request) - if response.Code != http.StatusOK || response.Header().Get("Content-Type") != "application/wasm" || response.Header().Get("Content-Encoding") != "gzip" { + if response.Code != http.StatusOK || response.Header().Get("Content-Type") != "application/wasm" || response.Header().Get("Content-Encoding") != "br" { t.Fatalf("WASM response: %d %v", response.Code, response.Header()) } if response.Header().Get("Cross-Origin-Opener-Policy") != "same-origin" || response.Header().Get("Cross-Origin-Embedder-Policy") != "require-corp" || response.Header().Get("Cache-Control") != "no-cache" { t.Fatalf("isolation/cache headers: %v", response.Header()) } - reader, err := gzip.NewReader(response.Body) - if err != nil { - t.Fatal(err) - } - defer reader.Close() - contents, err := io.ReadAll(reader) - if err != nil || string(contents) != "\x00asm\x01\x00\x00\x00" { - t.Fatalf("decoded WASM: %x, %v", contents, err) + if !bytes.Equal(response.Body.Bytes(), compressed) { + t.Fatalf("compressed WASM: %x", response.Body.Bytes()) } } func TestBrowserClientRevalidatesUnchangedFiles(t *testing.T) { - for _, name := range []string{"game.js", "game.wasm.gz", "index.html", "profile-worker.js", "audio-worklet.js", "build.json"} { + for _, name := range []string{"game.js", "game.wasm.br", "index.html", "profile-worker.js", "audio-worklet.js", "build.json"} { t.Run(name, func(t *testing.T) { t.Chdir(t.TempDir()) if err := os.Mkdir("client", 0755); err != nil { @@ -63,6 +49,8 @@ func TestBrowserClientRevalidatesUnchangedFiles(t *testing.T) { path := "/wasm/" + name if name == "index.html" { path = "/" + } else if name == "game.wasm.br" { + path = "/wasm/game.wasm" } first := httptest.NewRecorder() browserClient(first, httptest.NewRequest("GET", path, nil)) diff --git a/src/browser/index.html b/src/browser/index.html @@ -101,17 +101,17 @@ canvas.focus(); }); - // Count compressed bytes and preserve streaming compilation while decoding. + // HTTP handles decompression; count prepared bytes while compilation streams. async function instantiateClient(imports, receive) { - const response = await fetch('/wasm/game.wasm.gz'); + const response = await fetch('/wasm/game.wasm'); if (!response.ok) throw new Error(`Client download: HTTP ${response.status}`); let loaded = 0; const progress = new TransformStream({transform(chunk, controller) { loaded += chunk.byteLength; - status.textContent = `Loading... ${(loaded / 1000000).toFixed(1)} MB`; + status.textContent = `Preparing client... ${(loaded / 1000000).toFixed(1)} MB`; controller.enqueue(chunk); }}); - const decoded = response.body.pipeThrough(progress).pipeThrough(new DecompressionStream('gzip')); + const decoded = response.body.pipeThrough(progress); const result = await WebAssembly.instantiateStreaming(new Response(decoded, { headers: {'Content-Type': 'application/wasm'} }), imports); diff --git a/src/tests/browser_loading.mjs b/src/tests/browser_loading.mjs @@ -1,17 +1,18 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import vm from 'node:vm'; -import zlib from 'node:zlib'; function fixture(response) { const progress = []; const loading = {hidden: false, set textContent(value) { progress.push(value); }}; const canvas = {addEventListener() {}}; const context = vm.createContext({ - console, WebAssembly, Response, TransformStream, DecompressionStream, + console, WebAssembly, Response, TransformStream, + localStorage: {getItem() { return null; }}, + window: {addEventListener() {}}, document: {querySelector: selector => selector === '#loading' ? loading : canvas}, fetch: async url => { - assert.equal(url, '/wasm/game.wasm.gz'); + assert.equal(url, '/wasm/game.wasm'); return response; } }); @@ -22,14 +23,13 @@ function fixture(response) { return {context, progress, loading}; } -async function streamsCompressedClientAndTracksProgress() { - // A valid module with one 64 KiB custom section, kept uncompressed for the test. +async function streamsDecodedClientAndTracksProgress() { + // Fetch exposes the decoded body after HTTP handles Content-Encoding. const wasm = new Uint8Array(65549); wasm.set([0, 97, 115, 109, 1, 0, 0, 0, 0, 129, 128, 4, 0]); - const compressed = zlib.gzipSync(wasm, {level: 0}); const stream = new ReadableStream({start(controller) { - controller.enqueue(compressed.subarray(0, 32768)); - controller.enqueue(compressed.subarray(32768)); + controller.enqueue(wasm.subarray(0, 32768)); + controller.enqueue(wasm.subarray(32768)); controller.close(); }}); const test = fixture(new Response(stream)); @@ -43,7 +43,7 @@ async function streamsCompressedClientAndTracksProgress() { assert.ok(instance instanceof WebAssembly.Instance); assert.ok(module instanceof WebAssembly.Module); - assert.deepEqual(test.progress, ['Loading... 0.0 MB', 'Loading... 0.1 MB']); + assert.deepEqual(test.progress, ['Preparing client... 0.0 MB', 'Preparing client... 0.1 MB']); assert.equal(test.loading.hidden, true); } @@ -54,6 +54,6 @@ async function rejectsFailedClientDownload() { /Client download: HTTP 404/); } -await streamsCompressedClientAndTracksProgress(); +await streamsDecodedClientAndTracksProgress(); await rejectsFailedClientDownload(); -console.log('PASS: compressed loading progress, streaming compilation, first frame and download failure'); +console.log('PASS: decoded preparation progress, streaming compilation, first frame and download failure'); diff --git a/tools/client/publish_wasm.py b/tools/client/publish_wasm.py @@ -1,5 +1,5 @@ """Publish the browser client for Go-only checkouts, without intermediate files.""" -import gzip +import brotli import hashlib import json import pathlib @@ -17,10 +17,21 @@ staging.mkdir(exist_ok=True) # Publish one matching JS/WASM pair, compressed for transfer to browsers and laptops. for name in ['game.js', 'index.html', 'profile-worker.js', 'audio-worklet.js']: shutil.copyfile(source / name, staging / name) -with (source / 'game.wasm').open('rb') as input_file: - with (staging / 'game.wasm.gz').open('wb') as output_file: - with gzip.GzipFile(filename='', mode='wb', fileobj=output_file, mtime=0) as compressed: - shutil.copyfileobj(input_file, compressed) + +# High-quality compression is expensive; reuse it when the executable is unchanged. +module_hash = hashlib.sha256((source / 'game.wasm').read_bytes()).hexdigest() +compressed = source / 'game.wasm.br' +stamp = source / 'game.wasm.br.sha256' +if not compressed.exists() or not stamp.exists() or stamp.read_text().strip() != module_hash: + compressor = brotli.Compressor() + temporary = source / 'game.wasm.br.tmp' + with (source / 'game.wasm').open('rb') as input_file, temporary.open('wb') as output_file: + while chunk := input_file.read(1024 * 1024): + output_file.write(compressor.process(chunk)) + output_file.write(compressor.finish()) + temporary.replace(compressed) + stamp.write_text(module_hash + '\n') +shutil.copyfile(compressed, staging / 'game.wasm.br') # Record the exact inputs and published bytes, including uncommitted source edits. inputs = subprocess.check_output( @@ -39,13 +50,16 @@ metadata = { ]).decode().splitlines()[0], 'files': {}, } -for name in ['game.js', 'game.wasm.gz', 'index.html', 'profile-worker.js', 'audio-worklet.js']: +for name in ['game.js', 'game.wasm.br', 'index.html', 'profile-worker.js', 'audio-worklet.js']: path = staging / name metadata['files'][name] = { 'bytes': path.stat().st_size, 'sha256': hashlib.sha256(path.read_bytes()).hexdigest(), } (staging / 'build.json').write_text(json.dumps(metadata, indent=2) + '\n') -for path in staging.iterdir(): - path.replace(destination / path.name) +for name in metadata['files']: + (staging / name).replace(destination / name) +(staging / 'build.json').replace(destination / 'build.json') +for directory in [staging, destination]: + (directory / 'game.wasm.gz').unlink(missing_ok=True) print('Published browser client to', destination) diff --git a/tools/client/test_publish_wasm.py b/tools/client/test_publish_wasm.py @@ -0,0 +1,70 @@ +import brotli +import hashlib +import json +import pathlib +import runpy +import shutil +import tempfile +import unittest +import unittest.mock + + +class PublishWasmTests(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = pathlib.Path(directory.name) + self.web = self.root / 'src/build/wasm/web' + self.web.mkdir(parents=True) + for name in ['game.js', 'index.html', 'profile-worker.js', 'audio-worklet.js']: + (self.web / name).write_text(name) + (self.web / 'game.wasm').write_bytes(b'\0asm\1\0\0\0') + (self.root / 'src/browser').mkdir() + (self.root / 'src/browser/index.html').write_text('source page') + self.script = self.root / 'tools/client/publish_wasm.py' + self.script.parent.mkdir(parents=True) + shutil.copyfile(pathlib.Path(__file__).with_name('publish_wasm.py'), self.script) + + def publish(self): + with unittest.mock.patch('subprocess.check_output', side_effect=[ + b'src/browser/index.html\n', b'fixture-commit\n', b'fixture compiler\n']): + runpy.run_path(str(self.script)) + + def test_publishes_matching_brotli_bundle(self): + (self.root / 'client').mkdir() + (self.root / 'client/game.wasm.gz').write_bytes(b'obsolete') + staging = self.root / 'src/build/wasm/publish' + staging.mkdir() + (staging / 'game.wasm.gz').write_bytes(b'obsolete') + + self.publish() + + published = (self.root / 'client/game.wasm.br').read_bytes() + self.assertEqual(brotli.decompress(published), b'\0asm\1\0\0\0') + self.assertEqual(sorted(path.name for path in (self.root / 'client').iterdir()), + ['audio-worklet.js', 'build.json', 'game.js', 'game.wasm.br', 'index.html', 'profile-worker.js']) + metadata = json.loads((self.root / 'client/build.json').read_text()) + self.assertEqual(metadata['files']['game.wasm.br']['sha256'], hashlib.sha256(published).hexdigest()) + self.assertEqual(metadata['files']['game.wasm.br']['bytes'], len(published)) + self.assertFalse((staging / 'game.wasm.gz').exists()) + + def test_reuses_compression_until_executable_changes(self): + self.publish() + original = (self.web / 'game.wasm.br').read_bytes() + (self.web / 'index.html').write_text('updated page') + + with unittest.mock.patch('brotli.Compressor', side_effect=AssertionError('unchanged executable recompressed')): + self.publish() + + self.assertEqual((self.root / 'client/index.html').read_text(), 'updated page') + self.assertEqual((self.root / 'client/game.wasm.br').read_bytes(), original) + + # A new executable must invalidate the cached representation. + (self.web / 'game.wasm').write_bytes(b'\0asm\1\0\0\0\0\1\0') + self.publish() + self.assertEqual(brotli.decompress((self.root / 'client/game.wasm.br').read_bytes()), + b'\0asm\1\0\0\0\0\1\0') + + +if __name__ == '__main__': + unittest.main()