commit d49b764358686e10d27f112ead52a4df9fa98fa2
parent 69af9454a4eda3d7468a2617fb5e72efac71b044
Author: anon <anon@example.com>
Date: Tue, 10 Nov 2026 22:48:27 +0000
Skip the startup bundle when database chunks are already cached
Diffstat:
3 files changed, 97 insertions(+), 14 deletions(-)
diff --git a/client/browser/index.html b/client/browser/index.html
@@ -334,12 +334,34 @@
console.warn('Startup asset cache unavailable:', error);
return;
}
+ // Check cached chunk headers without reading the 185 MiB of cached bodies.
+ status.textContent = 'Checking game assets...';
+ const chunkSize = 1048576;
+ const url = new URL('browser-assets/cd_image/data/db/ResourceDatabase.dat', document.baseURI);
+ const manifest = await fetch('browser-startup', {method: 'HEAD', cache: 'no-store'});
+ if (!manifest.ok) throw new Error(`Game assets: HTTP ${manifest.status}`);
+ let cached;
+ try {
+ cached = await Promise.all(manifest.headers.get('X-AO-Chunks').split(',').map(async index => {
+ const chunkURL = new URL(url);
+ chunkURL.searchParams.set('ao-chunk', `${chunkSize}:${index}`);
+ const response = await cache.match(chunkURL.href);
+ return response?.headers.get('ETag') === manifest.headers.get('X-AO-Asset-Version');
+ }));
+ } catch (error) {
+ console.warn('Startup asset cache read failed:', error);
+ return;
+ }
+ if (cached.every(Boolean)) {
+ status.textContent = 'Downloading Anarchy Online client...';
+ 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'));
@@ -349,7 +371,6 @@
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 (;;) {
diff --git a/client/tests/browser_loading.mjs b/client/tests/browser_loading.mjs
@@ -195,11 +195,12 @@ async function rejectsFailedClientScript() {
function startupFixture() {
const test = fixture();
- const written = new Map(), warnings = [];
+ const written = new Map(), warnings = [], requests = [];
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)};
+ return {match: async url => written.get(url)?.clone(),
+ put: async (url, response) => written.set(url, response)};
}};
const bytes = new Uint8Array(3 * 1048576);
bytes.fill(11, 0, 1048576);
@@ -210,6 +211,8 @@ function startupFixture() {
test.context.fetch = async (url, options) => {
assert.equal(url, 'browser-startup');
assert.equal(options.cache, 'no-store');
+ requests.push(options.method || 'GET');
+ if (options.method === 'HEAD') return new Response(null, {headers});
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));
@@ -218,7 +221,7 @@ function startupFixture() {
controller.close();
}}), {headers});
};
- return {...test, written, warnings, bytes, headers};
+ return {...test, written, warnings, requests, bytes, headers};
}
async function cachesStreamedStartupChunks() {
@@ -239,16 +242,60 @@ async function cachesStreamedStartupChunks() {
assert.deepEqual(test.percentages, [33, 67, 100]);
assert.equal(test.downloadProgress.hidden, true);
assert.deepEqual(test.warnings, []);
+ assert.deepEqual(test.requests, ['HEAD', 'GET']);
+}
+
+async function skipsCachedStartupStream() {
+ const test = startupFixture();
+ await test.context.preloadStartupAssets();
+ test.requests.length = 0;
+
+ await test.context.preloadStartupAssets();
+
+ assert.deepEqual(test.requests, ['HEAD']);
+ assert.equal(test.written.size, 3);
+}
+
+async function reloadsStartupStreamAfterCacheEviction() {
+ const test = startupFixture();
+ await test.context.preloadStartupAssets();
+ test.written.delete([...test.written.keys()][1]);
+ test.requests.length = 0;
+
+ await test.context.preloadStartupAssets();
+
+ assert.deepEqual(test.requests, ['HEAD', 'GET']);
+ assert.equal(test.written.size, 3);
+}
+
+async function reloadsStartupStreamAfterDatabaseChange() {
+ const test = startupFixture();
+ await test.context.preloadStartupAssets();
+ test.headers['X-AO-Asset-Version'] = '"new-database-revision"';
+ test.requests.length = 0;
+
+ await test.context.preloadStartupAssets();
+
+ assert.deepEqual(test.requests, ['HEAD', 'GET']);
+ for (const response of test.written.values())
+ assert.equal(response.headers.get('ETag'), '"new-database-revision"');
}
async function rejectsIncompleteStartupStream() {
const test = startupFixture();
- test.context.fetch = async () => new Response(test.bytes.subarray(0, 1048579), {headers: test.headers});
+ const fetch = test.context.fetch;
+ test.context.fetch = async (url, options) => options.method === 'HEAD' ? fetch(url, options) :
+ 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);
+ test.context.fetch = fetch;
+ test.requests.length = 0;
+ await test.context.preloadStartupAssets();
+ assert.deepEqual(test.requests, ['HEAD', 'GET']);
+ assert.equal(test.written.size, 3);
}
async function fallsBackWhenStartupCacheIsUnavailable() {
@@ -265,8 +312,11 @@ async function fallsBackWhenStartupCacheIsUnavailable() {
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) {
+ test.context.caches.open = async () => ({match: async () => undefined,
+ put: async () => { throw new Error('quota exceeded'); }});
+ const fetch = test.context.fetch;
+ test.context.fetch = async (url, options) => options.method === 'HEAD' ? fetch(url, options) :
+ new Response(new ReadableStream({start(controller) {
controller.enqueue(test.bytes.subarray(0, 1048576));
}, cancel() { cancelled = true; }}), {headers: test.headers});
@@ -278,6 +328,9 @@ async function cancelsStartupStreamWhenCacheFills() {
}
await cachesStreamedStartupChunks();
+await skipsCachedStartupStream();
+await reloadsStartupStreamAfterCacheEviction();
+await reloadsStartupStreamAfterDatabaseChange();
await rejectsIncompleteStartupStream();
await fallsBackWhenStartupCacheIsUnavailable();
await cancelsStartupStreamWhenCacheFills();
diff --git a/tests/e2e/startup.test.mjs b/tests/e2e/startup.test.mjs
@@ -21,7 +21,7 @@ for (const latency of [0, 120]) {
let requests = [];
await context.route(/\/browser-(assets|manifest|resource-index|startup)/, async route => {
const request = route.request();
- const entry = {path: new URL(request.url()).pathname,
+ 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));
@@ -39,7 +39,15 @@ for (const latency of [0, 120]) {
fixture.games.push(game);
const results = [];
- for (const cache of ['cold', 'warm']) {
+ for (const cache of ['cold', 'warm', 'evicted']) {
+ if (cache === 'evicted') {
+ await page.evaluate(async () => {
+ const cache = await caches.open('ao-asset-chunks-v1');
+ const url = new URL('browser-assets/cd_image/data/db/ResourceDatabase.dat', document.baseURI);
+ url.searchParams.set('ao-chunk', '1048576:7');
+ if (!await cache.delete(url.href)) throw new Error('Expected startup chunk in cache');
+ });
+ }
requests = [];
const start = Date.now();
await page.goto(fixture.url);
@@ -52,17 +60,18 @@ for (const latency of [0, 120]) {
(await fixture.state(context)).position[2] < position[2] - 0.4);
const playable = Date.now() - start;
const preload = await page.evaluate(() => {
- const bundle = performance.getEntriesByType('resource').find(entry => entry.name.endsWith('/browser-startup'));
+ const bundles = performance.getEntriesByType('resource').filter(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,
+ return {start: bundles[0].startTime, end: bundles.at(-1).responseEnd,
+ bytes: bundles.reduce((sum, entry) => sum + entry.decodedBodySize, 0),
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.deepEqual(bundles.map(request => request.method), cache === 'warm' ? ['HEAD'] : ['HEAD', 'GET']);
assert.equal(bundles[0].chunks.length, 185);
assert.equal(bundles[0].bytes, 193986560);
- assert.equal(preload.bytes, 193986560);
+ assert.equal(preload.bytes, cache === 'warm' ? 0 : 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);