commit d4499d2524b0740b9adabf30a7280aaf2db6137b
parent 481aef79f341831185a975417d4c540d95cf1360
Author: anon <anon@example.com>
Date: Tue, 10 Nov 2026 21:59:14 +0000
Overlap browser bootstrap asset reads to shorten cold startup
Diffstat:
4 files changed, 169 insertions(+), 11 deletions(-)
diff --git a/client/runtime/browser_fetch.js b/client/runtime/browser_fetch.js
@@ -53,6 +53,21 @@ addToLibrary({
}
}
+ let startupPrefetched = false;
+ const startupFiles = new Set();
+ function prefetchStartup() {
+ if (startupPrefetched) return;
+ startupPrefetched = true;
+ // The initializer registers the whole tree before copying its writable files.
+ for (const handle of allocatedFiles) {
+ const path = new URL(fileURL(handle)).pathname;
+ if (/\/browser-assets\/(Prefs\/|cd_image\/OCC\/|Setupf\/|fonts\/|cd_image\/textures\/(Archives\/|fonts\/))/.test(path) ||
+ path.endsWith('/ResourceDatabase.idx')) startupFiles.add(handle);
+ }
+ // These fixed bootstrap files total about 12 MiB and are needed in every zone.
+ for (const handle of startupFiles) getFile(handle).catch(() => {});
+ }
+
function soundFamily(url) {
// Terrain and action variants share one footwear directory.
const footsteps = /^(.*\/sound\/sfx\/foots\/[^/]+\/)[^/]+\.wav$/i.exec(url);
@@ -209,7 +224,9 @@ addToLibrary({
if (info) {
file.size = info.size;
file.version = info.version;
- if (file.size) await loadChunks(file, 0, 0);
+ // Small startup archives are cheaper as one transfer than serial ranges.
+ if (file.size) await loadChunks(file, 0,
+ startupFiles.has(handle) ? Math.ceil(file.size / file.chunkSize) - 1 : 0);
} else {
await fetchChunks(file, 0, 0);
}
@@ -218,6 +235,7 @@ addToLibrary({
});
files.set(handle, pending);
pending.catch(() => files.delete(handle));
+ prefetchStartup();
}
return files.get(handle);
}
diff --git a/client/runtime/browser_host.c b/client/runtime/browser_host.c
@@ -102,6 +102,8 @@ void browser_initialize(unsigned character_id)
assert(mkdir("/proc", 0755) == 0);
assert(mkdir("/proc/self", 0755) == 0);
assert(symlink("/game/game.wasm", "/proc/self/exe") == 0);
+ char *copy_manifest = strdup(manifest);
+ assert(copy_manifest);
for (char *name = strtok(manifest, "\n"); name; name = strtok(NULL, "\n")) {
char path[4096];
snprintf(path, sizeof(path), "/remote/%s", name);
@@ -120,16 +122,6 @@ void browser_initialize(unsigned character_id)
if (directory) {
name[length - 1] = 0;
assert(mkdir(name, 0755) == 0);
- } else {
- FILE *source = fopen(path, "rb"), *destination = fopen(name, "wb");
- assert(source && destination);
- unsigned char buffer[8192];
- size_t size;
- while ((size = fread(buffer, 1, sizeof(buffer), source)))
- assert(fwrite(buffer, 1, size, destination) == size);
- assert(!ferror(source));
- fclose(source);
- fclose(destination);
}
} else if (!strncmp(name, "cd_image/", 9) && name[9]) {
/* Link the other immediate children to their HTTP-backed asset tree. */
@@ -141,6 +133,24 @@ void browser_initialize(unsigned character_id)
}
}
free(manifest);
+
+ /* Register all remote files first so startup reads can prefetch their siblings. */
+ for (char *name = strtok(copy_manifest, "\n"); name; name = strtok(NULL, "\n")) {
+ if (name[strlen(name) - 1] == '/' ||
+ (strncmp(name, "Prefs/", 6) && strncmp(name, "cd_image/OCC/", 13))) continue;
+ char path[4096];
+ snprintf(path, sizeof(path), "/remote/%s", name);
+ FILE *source = fopen(path, "rb"), *destination = fopen(name, "wb");
+ assert(source && destination);
+ unsigned char buffer[8192];
+ size_t size;
+ while ((size = fread(buffer, 1, sizeof(buffer), source)))
+ assert(fwrite(buffer, 1, size, destination) == size);
+ assert(!ferror(source));
+ fclose(source);
+ fclose(destination);
+ }
+ free(copy_manifest);
/* Private browsing can deny OPFS; native preferences still need writable files. */
int storage_available = -1;
em_proxying_queue *queue = em_proxying_queue_create();
diff --git a/client/tests/browser_startup_prefetch.mjs b/client/tests/browser_startup_prefetch.mjs
@@ -0,0 +1,68 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import vm from 'node:vm';
+import {test} from 'node:test';
+
+test('startup files overlap, whole archives share demand reads, and failures retry', async () => {
+ const names = ['Prefs/Main.cfg', 'cd_image/OCC/OCCV.i',
+ 'cd_image/data/db/ResourceDatabase.idx', 'cd_image/textures/Archives/GUIGFX.UVGA',
+ 'cd_image/data/db/ResourceDatabase.dat', 'cd_image/sound/music/unrelated.wav'];
+ const requests = [], pending = new Map();
+ let library;
+ const context = vm.createContext({
+ AOProfile: {begin: () => 0, end: () => {}},
+ Map, Set, URL, Response, Uint8Array, TextDecoder, AbortController, TypeError,
+ setTimeout, clearTimeout, console, HEAPU8: new Uint8Array(64),
+ UTF8ToString: value => value,
+ __wasmfs_fetch_get_file_url: handle => 'http://example.test/browser-assets//' + names[handle],
+ __wasmfs_fetch_get_chunk_size: () => 4,
+ wasmFS$backends: {}, AOResourcePrefetch: {}, _browser_prefetch_resource_ready: () => {},
+ addToLibrary: value => { library = value; },
+ fetch: async (url, options) => {
+ if (url.endsWith('/browser-manifest')) return Response.json(Object.fromEntries(
+ names.map(name => [name, {size: 12, version: '"one"'}])));
+ const name = url.split('/browser-assets/')[1];
+ requests.push([name, options.headers.Range]);
+ const status = await new Promise(resolve => pending.set(name, resolve));
+ pending.delete(name);
+ return new Response(status === 206 ? 'abcdefghijkl' : null, {status,
+ headers: {'Content-Range': 'bytes 0-11/12', ETag: '"one"'}});
+ }
+ });
+ vm.runInContext(fs.readFileSync(new URL('../runtime/browser_host.js', import.meta.url), 'utf8'), context);
+ context.AOAssetRequest = library.$AOAssetRequest;
+ const source = fs.readFileSync(new URL('../runtime/browser_fetch.js', import.meta.url), 'utf8')
+ .replaceAll('{{{ cDefs.EROFS }}}', '69').replaceAll('{{{ cDefs.ENOENT }}}', '44')
+ .replaceAll('{{{ cDefs.EBADF }}}', '8');
+ vm.runInContext(source, context);
+ await library._wasmfs_create_fetch_backend_js(1);
+ const backend = context.wasmFS$backends[1];
+ for (let handle = 0; handle < names.length; ++handle) await backend.allocFile(handle);
+
+ const preferences = backend.read(0, 0, 12, 0);
+ await new Promise(setImmediate);
+ const index = backend.read(2, 16, 4, 8);
+ await new Promise(setImmediate);
+
+ assert.deepEqual(requests, [
+ ['Prefs/Main.cfg', 'bytes=0-11'],
+ ['cd_image/OCC/OCCV.i', 'bytes=0-11'],
+ ['cd_image/data/db/ResourceDatabase.idx', 'bytes=0-11'],
+ ['cd_image/textures/Archives/GUIGFX.UVGA', 'bytes=0-11']
+ ]);
+ pending.get(names[3])(404);
+ for (const name of names.slice(0, 3)) pending.get(name)(206);
+ assert.equal(await preferences, 12);
+ assert.equal(await index, 4);
+ assert.equal(new TextDecoder().decode(context.HEAPU8.subarray(0, 12)), 'abcdefghijkl');
+ assert.equal(new TextDecoder().decode(context.HEAPU8.subarray(16, 20)), 'ijkl');
+
+ // Failed speculation leaves the ordinary read free to retry the same archive.
+ const retry = backend.read(3, 32, 12, 0);
+ await new Promise(setImmediate);
+ assert.equal(requests.length, 5);
+ assert.deepEqual(requests[4], ['cd_image/textures/Archives/GUIGFX.UVGA', 'bytes=0-11']);
+ pending.get(names[3])(206);
+ assert.equal(await retry, 12);
+ assert.equal(new TextDecoder().decode(context.HEAPU8.subarray(32, 44)), 'abcdefghijkl');
+});
diff --git a/tests/e2e/startup.test.mjs b/tests/e2e/startup.test.mjs
@@ -0,0 +1,62 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import {before, test} from 'node:test';
+import {buildServer, withFixture} from './fixture.mjs';
+import {GameTest} from '../../tools/client/game_test.mjs';
+
+before(buildServer);
+
+for (const latency of [0, 120]) {
+ test(`cold and cached startup with ${latency} ms asset latency`, {timeout: 180_000}, async () => {
+ await withFixture('startup-' + latency, async fixture => {
+ const context = await fixture.visitor();
+ const account = await context.request.post(fixture.url + '/browser-account/create', {form: {
+ name: 'Startupbench', password: 'startup regression password', head_mesh: '40681',
+ profession: '9', side: '2', build: '1', height: '100'
+ }});
+ assert.equal(account.status(), 204, await account.text());
+ await fixture.setup(context, 'position', {
+ playfield: 705, position: [960, 16.5, 510], rotation: [0, 0, 0, 1]
+ });
+ let requests = [];
+ await context.route(/\/browser-(assets|manifest|resource-index)/, async route => {
+ const request = route.request();
+ requests.push({path: new URL(request.url()).pathname,
+ range: request.headers().range, time: Date.now()});
+ if (latency) await new Promise(resolve => setTimeout(resolve, latency));
+ await route.continue();
+ });
+ const page = await context.newPage();
+ const game = await GameTest.attach(page);
+ fixture.games.push(game);
+ const results = [];
+
+ for (const cache of ['cold', 'warm']) {
+ requests = [];
+ const start = Date.now();
+ await page.goto(fixture.url);
+ await game.ready();
+ const ready = Date.now() - start;
+ const position = game.local().position;
+ await game.hold('KeyS', 'startup accepts movement', state =>
+ 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});
+ await game.save(fixture.output + '/' + cache);
+ }
+
+ assert.deepEqual(game.errors, []);
+ const indexPath = '/browser-assets/cd_image/data/db/ResourceDatabase.idx';
+ assert.deepEqual(results[0].requests.filter(request => request.path === indexPath)
+ .map(request => request.range), ['bytes=0-7340031']);
+ assert.equal(results[1].requests.filter(request => request.path === indexPath).length, 0);
+ assert.equal(results[1].requests.filter(request => request.path.startsWith('/browser-assets/Prefs/') ||
+ 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
+ }))}));
+ });
+ });
+}