aorecomp

Anarchy Online classic in the browser

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


commit 69af9454a4eda3d7468a2617fb5e72efac71b044
parent d4499d2524b0740b9adabf30a7280aaf2db6137b
Author: anon <anon@example.com>
Date:   Tue, 10 Nov 2026 22:37:18 +0000

Stream fixed startup database chunks before loading the browser client

Diffstat:
Mclient/browser/index.html | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mclient/tests/browser_loading.mjs | 100+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Aserver/browser_startup.go | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_startup_test.go | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/http.go | 1+
Mtests/e2e/startup.test.mjs | 40+++++++++++++++++++++++++++++++++++-----
6 files changed, 381 insertions(+), 7 deletions(-)

diff --git a/client/browser/index.html b/client/browser/index.html @@ -324,6 +324,70 @@ receive(result.instance, result.module); } + // Receive the fixed startup ranges in one stream before the game starts reading assets. + async function preloadStartupAssets() { + if (!globalThis.caches) return; + let cache; + try { + cache = await caches.open('ao-asset-chunks-v1'); + } catch (error) { + console.warn('Startup asset cache unavailable:', error); + return; + } + status.textContent = 'Downloading game assets...'; + const response = await fetch('browser-startup', {cache: 'no-store'}); + if (!response.ok) throw new Error(`Game assets: HTTP ${response.status}`); + const reader = response.body.getReader(); + try { + const chunkSize = 1048576; + const indices = (response.headers.get('X-AO-Chunks') || '').split(',').map(Number); + const version = response.headers.get('X-AO-Asset-Version'); + const total = Number(response.headers.get('Content-Length')); + if (!response.headers.get('X-AO-Chunks') || !version || total !== indices.length * chunkSize || + indices.some((index, i) => !Number.isSafeInteger(index) || index < 0 || + (i > 0 && index <= indices[i - 1]))) + throw new Error('Invalid startup asset manifest'); + + // Keep only one assembled chunk in memory, with the same key and ETag as range fetches. + const url = new URL('browser-assets/cd_image/data/db/ResourceDatabase.dat', document.baseURI); + let chunk = new Uint8Array(chunkSize), offset = 0, completed = 0; + downloadProgress.hidden = false; + for (;;) { + const {value, done} = await reader.read(); + if (done) break; + let cursor = 0; + while (cursor < value.byteLength) { + if (completed === indices.length) throw new Error('Unexpected extra startup asset data'); + const count = Math.min(chunkSize - offset, value.byteLength - cursor); + chunk.set(value.subarray(cursor, cursor + count), offset); + offset += count; + cursor += count; + if (offset !== chunkSize) continue; + url.searchParams.set('ao-chunk', `${chunkSize}:${indices[completed]}`); + try { + await cache.put(url.href, new Response(chunk, {headers: {'ETag': version}})); + } catch (error) { + console.warn('Startup asset cache write failed:', error); + return; + } + completed++; + offset = 0; + chunk = new Uint8Array(chunkSize); + const percent = completed / indices.length * 100; + status.textContent = `Downloading game assets...\n${completed} / ${indices.length} MiB`; + downloadFill.style.width = `${percent}%`; + downloadProgress.setAttribute('aria-valuenow', Math.round(percent)); + } + } + if (completed !== indices.length || offset) throw new Error('Incomplete startup asset download'); + console.info('Startup asset chunks cached:', indices); + } finally { + await reader.cancel(); + downloadProgress.hidden = true; + } + status.textContent = 'Downloading Anarchy Online client...'; + } + // Console capture keeps every frame and input time for inspecting motion glitches. for (const type of ['keydown', 'keyup', 'mousedown', 'mouseup', 'mousemove']) { canvas.addEventListener(type, event => { @@ -437,6 +501,7 @@ show(); Module.loadAccount(); // The render worker owns the backing canvas after startup. [canvas.width, canvas.height] = renderSize(); + await preloadStartupAssets(); // Keep the script available when later pthreads start during a server outage. const clientScript = await fetch('wasm/game.js'); if (!clientScript.ok) throw new Error(`Client script: HTTP ${clientScript.status}`); diff --git a/client/tests/browser_loading.mjs b/client/tests/browser_loading.mjs @@ -20,7 +20,7 @@ function fixture(response) { updateTouchControls() {}, localStorage: {getItem() { return null; }}, window: {addEventListener() {}}, - document: {querySelector: selector => ({ + document: {baseURI: 'http://localhost/ao/', querySelector: selector => ({ '#loading': loading, '#download-progress': downloadProgress, '#download-fill': downloadFill })[selector] ?? canvas}, fetch: async url => { @@ -141,6 +141,11 @@ async function startsWithMainThreadGraphicsWithoutOffscreenCanvas(creating) { canvas.clientWidth = 1024; canvas.clientHeight = 768; const scripts = []; + let preloaded = false; + test.context.preloadStartupAssets = async () => { + await new Promise(resolve => setImmediate(resolve)); + preloaded = true; + }; let clientScript; test.context.URL = class extends URL { static createObjectURL(blob) { clientScript = blob; return 'blob:client'; } @@ -150,7 +155,10 @@ async function startsWithMainThreadGraphicsWithoutOffscreenCanvas(creating) { test.context.document.createElement = () => ({}); test.context.document.body = {append: script => scripts.push(script.src)}; test.context.fetch = async (url, options) => { - if (url === 'wasm/game.js') return new Response('client code', {headers: {'Content-Type': 'text/javascript'}}); + if (url === 'wasm/game.js') { + assert.equal(preloaded, true, 'startup cache must be ready before loading game code'); + return new Response('client code', {headers: {'Content-Type': 'text/javascript'}}); + } assert.equal(url, 'browser-launch' + (creating ? '?create=1' : '')); assert.equal(options.method, 'POST'); return new Response('Clientr.exe localtest localtest ' + (creating ? '0' : '73') + ' 2130706433 7600 0 0', @@ -185,6 +193,94 @@ async function rejectsFailedClientScript() { await assert.rejects(test.context.startGame(), /Client script: HTTP 404/); } +function startupFixture() { + const test = fixture(); + const written = new Map(), warnings = []; + test.context.console = {info() {}, warn: (...args) => warnings.push(args)}; + test.context.caches = {open: async name => { + assert.equal(name, 'ao-asset-chunks-v1'); + return {put: async (url, response) => written.set(url, response)}; + }}; + const bytes = new Uint8Array(3 * 1048576); + bytes.fill(11, 0, 1048576); + bytes.fill(22, 1048576, 2 * 1048576); + bytes.fill(33, 2 * 1048576); + const headers = {'X-AO-Chunks': '0,7,554', 'X-AO-Asset-Version': '"database-revision"', + 'Content-Length': String(bytes.length)}; + test.context.fetch = async (url, options) => { + assert.equal(url, 'browser-startup'); + assert.equal(options.cache, 'no-store'); + return new Response(new ReadableStream({start(controller) { + // Split both within a chunk and across boundaries, as an HTTP stream can do. + controller.enqueue(bytes.subarray(0, 17)); + controller.enqueue(bytes.subarray(17, 1048607)); + controller.enqueue(bytes.subarray(1048607)); + controller.close(); + }}), {headers}); + }; + return {...test, written, warnings, bytes, headers}; +} + +async function cachesStreamedStartupChunks() { + const test = startupFixture(); + await test.context.preloadStartupAssets(); + + const urls = [...test.written.keys()]; + assert.deepEqual(urls, [ + 'http://localhost/ao/browser-assets/cd_image/data/db/ResourceDatabase.dat?ao-chunk=1048576%3A0', + 'http://localhost/ao/browser-assets/cd_image/data/db/ResourceDatabase.dat?ao-chunk=1048576%3A7', + 'http://localhost/ao/browser-assets/cd_image/data/db/ResourceDatabase.dat?ao-chunk=1048576%3A554' + ]); + for (const [i, url] of urls.entries()) { + const response = test.written.get(url); + assert.equal(response.headers.get('ETag'), '"database-revision"'); + assert.deepEqual(new Uint8Array(await response.arrayBuffer()), test.bytes.subarray(i * 1048576, (i + 1) * 1048576)); + } + assert.deepEqual(test.percentages, [33, 67, 100]); + assert.equal(test.downloadProgress.hidden, true); + assert.deepEqual(test.warnings, []); +} + +async function rejectsIncompleteStartupStream() { + const test = startupFixture(); + test.context.fetch = async () => new Response(test.bytes.subarray(0, 1048579), {headers: test.headers}); + + await assert.rejects(test.context.preloadStartupAssets(), /Incomplete startup asset download/); + + assert.equal(test.written.size, 1, 'partial chunks must never enter the cache'); + assert.equal(test.downloadProgress.hidden, true); +} + +async function fallsBackWhenStartupCacheIsUnavailable() { + const test = startupFixture(); + test.context.caches.open = async () => { throw new Error('storage denied'); }; + test.context.fetch = () => assert.fail('must not download without a writable cache'); + + await test.context.preloadStartupAssets(); + + assert.equal(test.written.size, 0); + assert.equal(test.warnings.length, 1); +} + +async function cancelsStartupStreamWhenCacheFills() { + const test = startupFixture(); + let cancelled = false; + test.context.caches.open = async () => ({put: async () => { throw new Error('quota exceeded'); }}); + test.context.fetch = async () => new Response(new ReadableStream({start(controller) { + controller.enqueue(test.bytes.subarray(0, 1048576)); + }, cancel() { cancelled = true; }}), {headers: test.headers}); + + await test.context.preloadStartupAssets(); + + assert.equal(cancelled, true); + assert.equal(test.warnings.length, 1); + assert.equal(test.downloadProgress.hidden, true); +} + +await cachesStreamedStartupChunks(); +await rejectsIncompleteStartupStream(); +await fallsBackWhenStartupCacheIsUnavailable(); +await cancelsStartupStreamWhenCacheFills(); await streamsDecodedClientAndTracksProgress(); hidesProgressWhenDownloadStops(); await rejectsFailedClientDownload(); diff --git a/server/browser_startup.go b/server/browser_startup.go @@ -0,0 +1,74 @@ +package main + +import ( + "io" + "net/http" + "strconv" + "strings" +) + +// ResourceDatabase.dat chunks observed through playable startup in playfield 705. +// Each index identifies a 1 MiB range; keep these sorted for sequential disk reads. +var browserStartupChunks = [...]int64{ + 0, 1, 2, 3, 4, 6, 7, 8, 10, 12, 14, 15, 17, 18, 19, + 20, 21, 22, 24, 26, 31, 32, 33, 35, 36, 37, 38, 39, 40, 42, + 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61, 65, + 66, 71, 80, 82, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, + 97, 98, 102, 104, 105, 106, 107, 108, 110, 111, 112, 113, 114, 115, 116, + 117, 118, 119, 121, 122, 123, 124, 129, 142, 145, 147, 148, 150, 151, 152, + 153, 157, 158, 162, 165, 168, 171, 175, 176, 177, 178, 179, 180, 181, 182, + 183, 185, 186, 187, 189, 190, 191, 197, 198, 199, 200, 201, 202, 203, 204, + 205, 206, 207, 208, 209, 210, 211, 212, 216, 217, 220, 221, 224, 229, 230, + 232, 239, 243, 247, 284, 309, 313, 320, 350, 351, 353, 354, 362, 368, 372, + 373, 374, 375, 376, 377, 378, 379, 380, 382, 397, 399, 411, 435, 437, 463, + 464, 465, 473, 474, 475, 476, 477, 478, 479, 483, 494, 495, 498, 536, 537, + 541, 542, 548, 552, 554, +} + +func browserStartup(w http.ResponseWriter, r *http.Request) { + const name = "anarchy-assets-14.9.1/cd_image/data/db/ResourceDatabase.dat" + const chunkSize = 1048576 + file, err := resources.Open(name) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + defer file.Close() + info, err := file.Stat() + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + if info.Size() < (browserStartupChunks[len(browserStartupChunks)-1]+1)*chunkSize { + http.Error(w, "Resource database is too small for startup chunks", http.StatusInternalServerError) + return + } + + // Describe the concatenated ranges so the page can populate the normal asset cache. + indices := make([]string, len(browserStartupChunks)) + for i, chunk := range browserStartupChunks { + indices[i] = strconv.FormatInt(chunk, 10) + } + w.Header().Set("X-AO-Chunks", strings.Join(indices, ",")) + w.Header().Set("X-AO-Asset-Version", browserAssetVersion(name, info)) + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Length", strconv.Itoa(len(browserStartupChunks)*chunkSize)) + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Cross-Origin-Resource-Policy", "same-origin") + if r.Method == "HEAD" { + return + } + + // Copy directly from the asset file without assembling a 185 MiB server buffer. + for _, chunk := range browserStartupChunks { + if r.Context().Err() != nil { + return + } + if _, err := file.(io.ReadSeeker).Seek(chunk*chunkSize, io.SeekStart); err != nil { + panic(http.ErrAbortHandler) + } + if _, err := io.CopyN(w, file, chunkSize); err != nil { + panic(http.ErrAbortHandler) + } + } +} diff --git a/server/browser_startup_test.go b/server/browser_startup_test.go @@ -0,0 +1,108 @@ +package main + +import ( + "bytes" + "crypto/sha256" + "encoding/binary" + "hash" + "net/http" + "net/http/httptest" + "os" + "strconv" + "strings" + "testing" +) + +// Hash the streamed body without retaining the entire startup bundle in the test. +type startupResponse struct { + header http.Header + hash hash.Hash + size int +} + +func (response *startupResponse) Header() http.Header { return response.header } +func (response *startupResponse) WriteHeader(status int) {} +func (response *startupResponse) Write(data []byte) (int, error) { + response.size += len(data) + return response.hash.Write(data) +} + +func TestBrowserStartupStream(t *testing.T) { + t.Chdir(t.TempDir()) + useDiskResources(t) + if err := os.MkdirAll("anarchy-assets-14.9.1/cd_image/data/db", 0755); err != nil { + t.Fatal(err) + } + file, err := os.Create("anarchy-assets-14.9.1/cd_image/data/db/ResourceDatabase.dat") + if err != nil { + t.Fatal(err) + } + defer file.Close() + if err := file.Truncate(555 * 1048576); err != nil { + t.Fatal(err) + } + + // Mark every database chunk, including gaps, to catch wrong seeks and ordering. + marker := make([]byte, 8) + for chunk := int64(0); chunk < 555; chunk++ { + binary.LittleEndian.PutUint64(marker, uint64(chunk)) + if _, err := file.WriteAt(marker, chunk*1048576); err != nil { + t.Fatal(err) + } + } + response := &startupResponse{header: make(http.Header), hash: sha256.New()} + browserStartup(response, httptest.NewRequest("GET", "/browser-startup", nil)) + + if response.size != 193986560 || response.Header().Get("Content-Length") != "193986560" { + t.Fatalf("bundle size: %d, headers: %v", response.size, response.Header()) + } + indices := strings.Split(response.Header().Get("X-AO-Chunks"), ",") + if len(indices) != 185 || indices[0] != "0" || indices[184] != "554" { + t.Fatalf("startup indices: %v", indices) + } + expected := sha256.New() + chunkBytes := make([]byte, 1048576) + previous := -1 + for _, value := range indices { + index, err := strconv.Atoi(value) + if err != nil || index <= previous { + t.Fatalf("unsorted chunk index: %q after %d", value, previous) + } + previous = index + binary.LittleEndian.PutUint64(chunkBytes, uint64(index)) + expected.Write(chunkBytes) + } + if !bytes.Equal(response.hash.Sum(nil), expected.Sum(nil)) { + t.Fatal("streamed ranges do not match the advertised chunks") + } + + // The cache must accept these bytes as the same revision as ordinary range requests. + asset := httptest.NewRecorder() + request := httptest.NewRequest("HEAD", "/browser-assets/cd_image/data/db/ResourceDatabase.dat", nil) + request.SetPathValue("path", "cd_image/data/db/ResourceDatabase.dat") + browserAsset(asset, request) + if response.Header().Get("X-AO-Asset-Version") != asset.Header().Get("ETag") { + t.Fatalf("startup and range versions differ: %v, %v", response.Header(), asset.Header()) + } + head := httptest.NewRecorder() + browserStartup(head, httptest.NewRequest("HEAD", "/browser-startup", nil)) + if head.Code != http.StatusOK || head.Body.Len() != 0 || head.Header().Get("X-AO-Chunks") != response.Header().Get("X-AO-Chunks") { + t.Fatalf("HEAD response: %d %v (%d bytes)", head.Code, head.Header(), head.Body.Len()) + } +} + +func TestBrowserStartupRejectsIncompleteDatabase(t *testing.T) { + t.Chdir(t.TempDir()) + useDiskResources(t) + if err := os.MkdirAll("anarchy-assets-14.9.1/cd_image/data/db", 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile("anarchy-assets-14.9.1/cd_image/data/db/ResourceDatabase.dat", []byte("short"), 0644); err != nil { + t.Fatal(err) + } + response := httptest.NewRecorder() + browserStartup(response, httptest.NewRequest("GET", "/browser-startup", nil)) + if response.Code != http.StatusInternalServerError || response.Header().Get("X-AO-Chunks") != "" { + t.Fatalf("incomplete database response: %d %v", response.Code, response.Header()) + } +} diff --git a/server/http.go b/server/http.go @@ -29,6 +29,7 @@ func (server *server) httpHandler() http.Handler { mux.Handle("POST /browser-create", http.NewCrossOriginProtection().Handler(http.HandlerFunc(server.prepareBrowserCreation))) mux.HandleFunc("GET /browser-manifest", browserManifest) mux.HandleFunc("GET /browser-resource-index", browserResourceIndex) + mux.HandleFunc("GET /browser-startup", browserStartup) mux.HandleFunc("GET /wasm/", server.browserClient) mux.HandleFunc("GET /{$}", server.browserClient) protectedAdmin := http.NewCrossOriginProtection().Handler(server.adminAuth(server.adminHandler())) diff --git a/tests/e2e/startup.test.mjs b/tests/e2e/startup.test.mjs @@ -19,12 +19,20 @@ 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)/, async route => { + await context.route(/\/browser-(assets|manifest|resource-index|startup)/, async route => { const request = route.request(); - requests.push({path: new URL(request.url()).pathname, - range: request.headers().range, time: Date.now()}); + const entry = {path: new URL(request.url()).pathname, + 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 === '/browser-startup') { + const response = await request.response(); + const headers = await response.allHeaders(); + entry.chunks = headers['x-ao-chunks'].split(',').map(Number); + entry.bytes = Number(headers['content-length']); + entry.version = headers['x-ao-asset-version']; + } }); const page = await context.newPage(); const game = await GameTest.attach(page); @@ -42,7 +50,28 @@ for (const latency of [0, 120]) { game.local(state).position[2] < position[2] - 0.5); await game.waitFor('server accepts startup movement', async () => (await fixture.state(context)).position[2] < position[2] - 0.4); - results.push({cache, ready, playable: Date.now() - start, requests}); + const playable = Date.now() - start; + const preload = await page.evaluate(() => { + const bundle = performance.getEntriesByType('resource').find(entry => entry.name.endsWith('/browser-startup')); + const script = performance.getEntriesByType('resource').find(entry => entry.name.endsWith('/wasm/game.js')); + return {start: bundle.startTime, end: bundle.responseEnd, bytes: bundle.decodedBodySize, + clientStart: script.startTime}; + }); + assert.ok(preload.end <= preload.clientStart, 'bundle must finish before game code downloads'); + const bundles = requests.filter(request => request.path === '/browser-startup'); + assert.equal(bundles.length, 1); + assert.equal(bundles[0].chunks.length, 185); + assert.equal(bundles[0].bytes, 193986560); + assert.equal(preload.bytes, 193986560); + 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); + return Array.from({length: Math.floor(last / 1048576) - first / 1048576 + 1}, + (_, i) => first / 1048576 + i); + }); + assert.deepEqual(requestedChunks.filter(index => bundles[0].chunks.includes(index)), [], + 'preloaded database chunks must not be downloaded again'); + results.push({cache, ready, playable, preload, requestedChunks, requests}); await game.save(fixture.output + '/' + cache); } @@ -55,7 +84,8 @@ for (const latency of [0, 120]) { request.path.startsWith('/browser-assets/cd_image/OCC/')).length, 0); await fs.writeFile(fixture.output + '/startup.json', JSON.stringify({latency, results}, null, 2)); console.log(JSON.stringify({latency, output: fixture.output, results: results.map(result => ({ - cache: result.cache, ready: result.ready, playable: result.playable, requests: result.requests.length + cache: result.cache, ready: result.ready, playable: result.playable, requests: result.requests.length, + preload: result.preload, requestedChunks: result.requestedChunks }))})); }); });