aorecomp

Anarchy Online classic in the browser

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


commit 5ffcc6519fec37a1a227633358bc3b79cab1ca3b
parent ce2fe0a9ec6894e86cf8e1879ca8927660767f11
Author: anon <anon@example.com>
Date:   Tue, 10 Nov 2026 23:28:09 +0000

Reuse validated WASM cache without download progress

Diffstat:
Mclient/browser/index.html | 77++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
Mclient/tests/browser_loading.mjs | 92++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mserver/browser_client.go | 22+++++++++++++++++++++-
Mserver/browser_client_test.go | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtests/e2e/startup.test.mjs | 20++++++++++++++------
5 files changed, 244 insertions(+), 27 deletions(-)

diff --git a/client/browser/index.html b/client/browser/index.html @@ -69,7 +69,7 @@ </style> <div id="game-surface"> <canvas id="canvas" width="1024" height="768" tabindex="0"></canvas> -<div id="loading" role="status">Downloading Anarchy Online...</div> +<div id="loading" role="status">Starting Anarchy Online...</div> <div id="download-progress" role="progressbar" aria-label="Game download" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" hidden><div id="download-fill"></div></div> <button id="reconnect" hidden>Reconnect</button> <div id="game-toolbar" hidden> @@ -299,11 +299,17 @@ } // One byte-weighted download covers the uncached assets and compressed game binary. + const clientBinaryBytes = Number('__WASM_DOWNLOAD_MB__') * 1000000; + let clientDownloadBytes = clientBinaryBytes, clientCache = null, cachedClientResponse = null; let startupAssetBytes = 0, loadedStartupAssetBytes = 0; function updateDownloadProgress(clientFraction) { - const clientBytes = Number('__WASM_DOWNLOAD_MB__') * 1000000; - const total = startupAssetBytes + clientBytes; - const loaded = loadedStartupAssetBytes + clientBytes * clientFraction; + const total = startupAssetBytes + clientDownloadBytes; + if (total === 0) { + downloadProgress.hidden = true; + status.textContent = 'Starting Anarchy Online...'; + return; + } + const loaded = loadedStartupAssetBytes + clientDownloadBytes * clientFraction; const percent = Math.min(100, loaded / total * 100); status.textContent = `Downloading Anarchy Online...\n${(loaded / 1000000).toFixed(2)} / ${(total / 1000000).toFixed(2)} MB`; downloadProgress.hidden = false; @@ -311,24 +317,56 @@ downloadProgress.setAttribute('aria-valuenow', Math.round(percent)); } + // Decide the binary's download budget before displaying any asset progress. + async function prepareClientDownload() { + clientDownloadBytes = clientBinaryBytes; + clientCache = cachedClientResponse = null; + if (!globalThis.caches) return; + try { + clientCache = await caches.open('ao-asset-chunks-v1'); + cachedClientResponse = await clientCache.match(new URL('wasm/game.wasm', document.baseURI).href); + } catch (error) { + console.warn('Client cache unavailable:', error); + clientCache = null; + return; + } + if (!cachedClientResponse) return; + const response = await fetch('wasm/game.wasm', {method: 'HEAD', cache: 'no-store', + headers: {'If-None-Match': cachedClientResponse.headers.get('ETag')}}); + if (response.status === 304) { + clientDownloadBytes = 0; + } else { + if (!response.ok) throw new Error(`Client version: HTTP ${response.status}`); + cachedClientResponse = null; + } + } + // Fetch exposes decoded WASM bytes; scale them to the published compressed size. async function instantiateClient(imports, receive) { - const response = await fetch('wasm/game.wasm'); + const response = cachedClientResponse || await fetch('wasm/game.wasm', {cache: 'no-store'}); if (!response.ok) throw new Error(`Client download: HTTP ${response.status}`); - updateDownloadProgress(0); - let loaded = 0; - const progress = new TransformStream({transform(chunk, controller) { - loaded += chunk.byteLength; - updateDownloadProgress(Math.min(1, loaded / Number('__WASM_DECODED_BYTES__'))); - controller.enqueue(chunk); - }, flush() { + const cacheWrite = !cachedClientResponse && clientCache ? + clientCache.put(new URL('wasm/game.wasm', document.baseURI).href, response.clone()) + .catch(error => console.warn('Client cache write failed:', error)) : Promise.resolve(); + let binary = response; + if (cachedClientResponse) { downloadProgress.hidden = true; status.textContent = 'Starting Anarchy Online...'; - }}); - const decoded = response.body.pipeThrough(progress); - const result = await WebAssembly.instantiateStreaming(new Response(decoded, { - headers: {'Content-Type': 'application/wasm'} - }), imports); + } else { + updateDownloadProgress(0); + let loaded = 0; + const progress = new TransformStream({transform(chunk, controller) { + loaded += chunk.byteLength; + updateDownloadProgress(Math.min(1, loaded / Number('__WASM_DECODED_BYTES__'))); + controller.enqueue(chunk); + }, flush() { + downloadProgress.hidden = true; + status.textContent = 'Starting Anarchy Online...'; + }}); + binary = new Response(response.body.pipeThrough(progress), {headers: {'Content-Type': 'application/wasm'}}); + } + const result = await WebAssembly.instantiateStreaming(binary, imports); + await cacheWrite; receive(result.instance, result.module); } @@ -362,7 +400,7 @@ return; } if (cached.every(Boolean)) { - status.textContent = 'Downloading Anarchy Online...'; + status.textContent = 'Starting Anarchy Online...'; return; } @@ -521,7 +559,7 @@ show(); for (const type of ['pointerdown', 'keydown']) { document.addEventListener(type, resumeAudio, true); } - status.textContent = 'Downloading Anarchy Online...'; + status.textContent = 'Starting Anarchy Online...'; const response = await fetch('browser-launch' + (creating ? '?create=1' : ''), {method: 'POST'}); if (!response.ok) { status.textContent = await response.text(); return; } Module.arguments = (await response.text()).trim().split(' ').slice(1); @@ -529,6 +567,7 @@ show(); Module.loadAccount(); // The render worker owns the backing canvas after startup. [canvas.width, canvas.height] = renderSize(); + await prepareClientDownload(); await preloadStartupAssets(); // Keep the script available when later pthreads start during a server outage. const clientScript = await fetch('wasm/game.js'); diff --git a/client/tests/browser_loading.mjs b/client/tests/browser_loading.mjs @@ -46,7 +46,7 @@ function clientDownloadResponse() { controller.enqueue(wasm.subarray(0, 32768)); controller.enqueue(wasm.subarray(32768)); controller.close(); - }})); + }}), {headers: {'Content-Type': 'application/wasm', 'ETag': '"client-revision"'}}); } async function streamsDecodedClientAndTracksProgress() { @@ -357,6 +357,96 @@ async function combinesAssetAndClientProgress(warm) { 'Downloading Anarchy Online...\n14.72 / 14.72 MB'); } +async function revalidatesCachedClientWithoutDownloadProgress() { + const test = startupFixture(); + const requests = []; + test.context.fetch = async (url, options) => { + assert.equal(url, 'wasm/game.wasm'); + assert.equal(options.cache, 'no-store'); + requests.push(options.method || 'GET'); + if (options.method === 'HEAD') { + assert.equal(options.headers['If-None-Match'], '"client-revision"'); + return new Response(null, {status: 304}); + } + return clientDownloadResponse(); + }; + + await test.context.prepareClientDownload(); + await test.context.instantiateClient({}, () => {}); + assert.equal(test.written.get('http://localhost/ao/wasm/game.wasm').headers.get('ETag'), '"client-revision"'); + test.visibility.length = test.progress.length = test.percentages.length = 0; + await test.context.prepareClientDownload(); + await test.context.instantiateClient({}, instance => assert.ok(instance instanceof WebAssembly.Instance)); + + assert.deepEqual(requests, ['GET', 'HEAD']); + assert.deepEqual(test.percentages, []); + assert.deepEqual(test.visibility, [true]); + assert.deepEqual(test.progress, ['Starting Anarchy Online...']); +} + +async function downloadsChangedClient() { + const test = startupFixture(); + const url = 'http://localhost/ao/wasm/game.wasm'; + test.written.set(url, clientDownloadResponse()); + const requests = []; + test.context.fetch = async (url, options) => { + requests.push(options.method || 'GET'); + const response = options.method === 'HEAD' ? new Response(null) : clientDownloadResponse(); + response.headers.set('ETag', '"changed-client"'); + return response; + }; + + await test.context.prepareClientDownload(); + await test.context.instantiateClient({}, () => {}); + + assert.deepEqual(requests, ['HEAD', 'GET']); + assert.deepEqual(test.percentages, [0, 50, 100]); + assert.equal(test.written.get(url).headers.get('ETag'), '"changed-client"'); +} + +async function excludesCachedClientFromAssetProgress(quotaExceeded) { + const test = startupFixture(); + const url = 'http://localhost/ao/wasm/game.wasm'; + test.written.set(url, clientDownloadResponse()); + const fetch = test.context.fetch; + test.context.fetch = async (url, options) => url === 'wasm/game.wasm' ? + new Response(null, {status: 304}) : fetch(url, options); + if (quotaExceeded) { + test.context.caches.open = async () => ({match: async key => test.written.get(key)?.clone(), + put: async () => { throw new Error('quota exceeded'); }}); + } + + await test.context.prepareClientDownload(); + await test.context.preloadStartupAssets(); + await test.context.instantiateClient({}, () => {}); + + assert.deepEqual(test.percentages, quotaExceeded ? [0] : [0, 33, 67, 100]); + assert.equal(test.downloadProgress.hidden, true); + assert.ok(test.progress.every(message => !message.includes('NaN'))); + assert.equal(test.warnings.length, quotaExceeded ? 1 : 0); +} + +async function startsClientWhenCacheUnavailable(writeFailure) { + const test = startupFixture(); + test.context.caches.open = async () => { + if (!writeFailure) throw new Error('storage denied'); + return {match: async () => undefined, put: async () => { throw new Error('quota exceeded'); }}; + }; + test.context.fetch = async () => clientDownloadResponse(); + + await test.context.prepareClientDownload(); + await test.context.instantiateClient({}, instance => assert.ok(instance instanceof WebAssembly.Instance)); + + assert.deepEqual(test.percentages, [0, 50, 100]); + assert.equal(test.warnings.length, 1); +} + +await revalidatesCachedClientWithoutDownloadProgress(); +await downloadsChangedClient(); +await excludesCachedClientFromAssetProgress(false); +await excludesCachedClientFromAssetProgress(true); +await startsClientWhenCacheUnavailable(false); +await startsClientWhenCacheUnavailable(true); await combinesAssetAndClientProgress(false); await combinesAssetAndClientProgress(true); await cachesStreamedStartupChunks(); diff --git a/server/browser_client.go b/server/browser_client.go @@ -3,6 +3,7 @@ package main import ( "ao/server/assets" "crypto/sha256" + "encoding/json" "fmt" "html" "io" @@ -62,7 +63,26 @@ func (server *server) browserClient(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) return } - if info.ModTime().IsZero() { + if name == "game.wasm.br" { + // The published content hash survives timestamp changes and HTML-only republishes. + data, err := fs.ReadFile(resources, "client/build.json") + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + var build struct { + Files map[string]struct{ SHA256 string } + } + if err := json.Unmarshal(data, &build); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + if build.Files[name].SHA256 == "" { + http.Error(w, "Missing published WASM hash", http.StatusInternalServerError) + return + } + w.Header().Set("ETag", fmt.Sprintf("%q", build.Files[name].SHA256)) + } else if info.ModTime().IsZero() { w.Header().Set("ETag", fmt.Sprintf("\"%s-%s\"", browserClientVersion, name)) } else { w.Header().Set("ETag", browserAssetVersion("client/"+name, info)) diff --git a/server/browser_client_test.go b/server/browser_client_test.go @@ -2,6 +2,8 @@ package main import ( "bytes" + "crypto/sha256" + "fmt" "net/http" "net/http/httptest" "os" @@ -9,6 +11,14 @@ import ( "time" ) +func writeBrowserWASMManifest(t *testing.T, contents []byte) { + t.Helper() + manifest := fmt.Sprintf(`{"files":{"game.wasm.br":{"sha256":"%x"}}}`, sha256.Sum256(contents)) + if err := os.WriteFile("client/build.json", []byte(manifest), 0644); err != nil { + t.Fatal(err) + } +} + func TestBrowserClientServesPublishedWasm(t *testing.T) { t.Chdir(t.TempDir()) useDiskResources(t) @@ -20,6 +30,7 @@ func TestBrowserClientServesPublishedWasm(t *testing.T) { if err := os.WriteFile("client/game.wasm.br", compressed, 0644); err != nil { t.Fatal(err) } + writeBrowserWASMManifest(t, compressed) request := httptest.NewRequest("GET", "/wasm/game.wasm", nil) request.Header.Set("Accept-Encoding", "br") response := httptest.NewRecorder() @@ -54,6 +65,7 @@ func TestBrowserClientRevalidatesUnchangedFiles(t *testing.T) { path = "/" } else if name == "game.wasm.br" { path = "/wasm/game.wasm" + writeBrowserWASMManifest(t, []byte("bundle")) } first := httptest.NewRecorder() (&server{ @@ -72,6 +84,54 @@ func TestBrowserClientRevalidatesUnchangedFiles(t *testing.T) { } } +func TestBrowserClientWasmContentVersion(t *testing.T) { + t.Chdir(t.TempDir()) + useDiskResources(t) + if err := os.Mkdir("client", 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile("client/game.wasm.br", []byte("module"), 0644); err != nil { + t.Fatal(err) + } + writeBrowserWASMManifest(t, []byte("module")) + server := &server{} + first := httptest.NewRecorder() + server.browserClient(first, httptest.NewRequest("HEAD", "/wasm/game.wasm", nil)) + if first.Code != http.StatusOK { + t.Fatal(first.Code, first.Body.String()) + } + + // Republishing changes timestamps and the HTML, but leaves the binary's hash intact. + stamp := time.Unix(1700000000, 0) + if err := os.Chtimes("client/game.wasm.br", stamp, stamp); err != nil { + t.Fatal(err) + } + if err := os.WriteFile("client/index.html", []byte("new page"), 0644); err != nil { + t.Fatal(err) + } + writeBrowserWASMManifest(t, []byte("module")) + request := httptest.NewRequest("HEAD", "/wasm/game.wasm", nil) + request.Header.Set("If-None-Match", first.Header().Get("ETag")) + unchanged := httptest.NewRecorder() + server.browserClient(unchanged, request) + if unchanged.Code != http.StatusNotModified || unchanged.Body.Len() != 0 { + t.Fatalf("unchanged republish: HTTP %d %q", unchanged.Code, unchanged.Body.String()) + } + + // A new published binary must invalidate that same cached version. + if err := os.WriteFile("client/game.wasm.br", []byte("changed"), 0644); err != nil { + t.Fatal(err) + } + writeBrowserWASMManifest(t, []byte("changed")) + request = httptest.NewRequest("GET", "/wasm/game.wasm", nil) + request.Header.Set("If-None-Match", first.Header().Get("ETag")) + changed := httptest.NewRecorder() + server.browserClient(changed, request) + if changed.Code != http.StatusOK || changed.Body.String() != "changed" || changed.Header().Get("ETag") == first.Header().Get("ETag") { + t.Fatalf("changed binary: HTTP %d %v %q", changed.Code, changed.Header(), changed.Body.String()) + } +} + func TestBrowserClientDetectsSameSecondReplacement(t *testing.T) { t.Chdir(t.TempDir()) useDiskResources(t) diff --git a/tests/e2e/startup.test.mjs b/tests/e2e/startup.test.mjs @@ -19,13 +19,14 @@ for (const latency of [0, 120]) { playfield: 705, position: [960, 16.5, 510], rotation: [0, 0, 0, 1] }); let requests = []; - await context.route(/\/browser-(assets|manifest|resource-index|startup)/, async route => { + await context.route(/\/browser-(assets|manifest|resource-index|startup)|\/wasm\/game\.wasm$/, async route => { const request = route.request(); const entry = {path: new URL(request.url()).pathname, method: request.method(), range: request.headers().range, time: Date.now()}; requests.push(entry); if (latency) await new Promise(resolve => setTimeout(resolve, latency)); await route.continue(); + if (entry.path === '/wasm/game.wasm') entry.status = (await request.response()).status(); if (entry.path === '/browser-startup') { const response = await request.response(); const headers = await response.allHeaders(); @@ -81,6 +82,9 @@ for (const latency of [0, 120]) { assert.equal(bundles[0].chunks.length, 185); assert.equal(bundles[0].bytes, 193986560); assert.equal(preload.bytes, cache === 'warm' ? 0 : 193986560); + const binaries = requests.filter(request => request.path === '/wasm/game.wasm'); + assert.deepEqual(binaries.map(request => [request.method, request.status]), + cache === 'cold' ? [['GET', 200]] : [['HEAD', 304]]); const database = requests.filter(request => request.path.endsWith('/ResourceDatabase.dat')); const requestedChunks = database.flatMap(request => { const [first, last] = request.range.match(/\d+/g).map(Number); @@ -90,11 +94,15 @@ for (const latency of [0, 120]) { assert.deepEqual(requestedChunks.filter(index => bundles[0].chunks.includes(index)), [], 'preloaded database chunks must not be downloaded again'); const downloadProgress = await page.evaluate(() => window.startupDownloadProgress); - assert.ok(downloadProgress.length > 1); - assert.deepEqual(downloadProgress.at(-1), {percent: 100, hidden: true}); - assert.ok(downloadProgress.every((sample, i) => (!sample.hidden || sample.percent === 100) && - (i === 0 || sample.percent >= downloadProgress[i - 1].percent)), - 'download bar must advance continuously through assets and game binary'); + if (cache === 'warm') { + assert.ok(downloadProgress.every(sample => sample.hidden), '304 must not show download progress'); + } else { + assert.ok(downloadProgress.length > 1); + assert.deepEqual(downloadProgress.at(-1), {percent: 100, hidden: true}); + assert.ok(downloadProgress.every((sample, i) => (!sample.hidden || sample.percent === 100) && + (i === 0 || sample.percent >= downloadProgress[i - 1].percent)), + 'download bar must advance continuously through assets and game binary'); + } results.push({cache, ready, playable, preload, requestedChunks, requests, downloadProgress}); await game.save(fixture.output + '/' + cache); }