client/tests/browser_loading.mjs (19383B)
1 import assert from 'node:assert/strict'; 2 import fs from 'node:fs'; 3 import vm from 'node:vm'; 4 5 function fixture(response) { 6 const progress = []; 7 const loading = {hidden: false, set textContent(value) { progress.push(value); }}; 8 const percentages = [], widths = [], visibility = []; 9 let progressHidden = true; 10 const downloadProgress = {get hidden() { return progressHidden; }, 11 set hidden(value) { progressHidden = value; visibility.push(value); }, setAttribute(name, value) { 12 assert.equal(name, 'aria-valuenow'); 13 assert.equal(this.hidden, false); 14 percentages.push(value); 15 }}; 16 const downloadFill = {style: {set width(value) { widths.push(value); }}}; 17 const canvas = {style: {}, dataset: {}, addEventListener() {}, getContext() { return null; }}; 18 const context = vm.createContext({ 19 console, WebAssembly, Response, TransformStream, URL, crossOriginIsolated: true, 20 location: {href: 'http://localhost/'}, history: {replaceState() {}}, 21 navigator: {userAgent: 'Mozilla/5.0 (X11; Linux x86_64)'}, 22 updateTouchControls() {}, 23 localStorage: {getItem() { return null; }}, 24 window: {addEventListener() {}}, 25 document: {baseURI: 'http://localhost/ao/', querySelector: selector => ({ 26 '#loading': loading, '#download-progress': downloadProgress, '#download-fill': downloadFill 27 })[selector] ?? canvas}, 28 fetch: async url => { 29 assert.equal(url, 'wasm/game.wasm'); 30 return response; 31 } 32 }); 33 const html = fs.readFileSync(new URL('../browser/index.html', import.meta.url), 'utf8'); 34 const script = html.match(/<script>([\s\S]*?)<\/script>/)[1] 35 .replace('__WASM_DOWNLOAD_MB__', '11.57').replace('__WASM_DECODED_BYTES__', '65549'); 36 vm.runInContext(script, context); 37 context.Module.loadAccount = () => {}; 38 return {context, progress, loading, downloadProgress, percentages, widths, visibility}; 39 } 40 41 function clientDownloadResponse() { 42 // Fetch exposes the decoded body after HTTP handles Content-Encoding. 43 const wasm = new Uint8Array(65549); 44 wasm.set([0, 97, 115, 109, 1, 0, 0, 0, 0, 129, 128, 4, 0]); 45 return new Response(new ReadableStream({start(controller) { 46 controller.enqueue(wasm.subarray(0, 32768)); 47 controller.enqueue(wasm.subarray(32768)); 48 controller.close(); 49 }}), {headers: {'Content-Type': 'application/wasm', 'ETag': '"client-revision"'}}); 50 } 51 52 async function streamsDecodedClientAndTracksProgress() { 53 const test = fixture(clientDownloadResponse()); 54 let instance, module; 55 56 await test.context.instantiateClient({}, (loadedInstance, loadedModule) => { 57 instance = loadedInstance; 58 module = loadedModule; 59 }); 60 test.context.Module.onFirstFrame(); 61 62 assert.ok(instance instanceof WebAssembly.Instance); 63 assert.ok(module instanceof WebAssembly.Module); 64 assert.deepEqual(test.progress, [ 65 'Downloading Anarchy Online...\n0.00 / 11.57 MB', 66 'Downloading Anarchy Online...\n5.78 / 11.57 MB', 67 'Downloading Anarchy Online...\n11.57 / 11.57 MB', 68 'Starting Anarchy Online...' 69 ]); 70 assert.deepEqual(test.percentages, [0, 50, 100]); 71 assert.equal(Math.round(parseFloat(test.widths[1])), 50); 72 assert.equal(test.widths[2], '100%'); 73 assert.equal(test.downloadProgress.hidden, true); 74 assert.equal(test.loading.hidden, true); 75 } 76 77 function hidesProgressWhenDownloadStops() { 78 const test = fixture(); 79 test.downloadProgress.hidden = false; 80 test.context.console = {error() {}}; 81 82 test.context.Module.onAbort('connection lost'); 83 84 assert.equal(test.downloadProgress.hidden, true); 85 assert.deepEqual(test.progress, ['Stopped: connection lost']); 86 } 87 88 async function rejectsFailedClientDownload() { 89 const test = fixture(new Response('missing', {status: 404})); 90 91 await assert.rejects(test.context.instantiateClient({}, () => assert.fail('instantiated missing client')), 92 /Client download: HTTP 404/); 93 } 94 95 async function reportsMissingWebGL() { 96 const test = fixture(); 97 98 await test.context.startGame(); 99 100 assert.deepEqual(test.progress, ['This browser could not initialize WebGL 2. Check graphics settings or try another browser.']); 101 } 102 103 async function reportsUnavailableWebGLOnBothThreadsBeforeDownloading() { 104 const test = fixture(); 105 test.context.location.href = 'http://localhost/?create=1'; 106 let restoredURL; 107 test.context.history.replaceState = (state, title, url) => { restoredURL = String(url); }; 108 test.context.document.querySelector('#canvas').transferControlToOffscreen = () => {}; 109 let terminated = false, revoked = null; 110 test.context.Blob = Blob; 111 test.context.URL = class extends URL { 112 static createObjectURL() { return 'blob:graphics-probe'; } 113 static revokeObjectURL(url) { revoked = url; } 114 }; 115 test.context.Worker = class { 116 constructor(url) { 117 assert.equal(url, 'blob:graphics-probe'); 118 assert.equal(restoredURL, 'http://localhost/'); 119 queueMicrotask(() => this.onmessage({data: false})); 120 } 121 terminate() { terminated = true; } 122 }; 123 124 await test.context.startGame(); 125 126 assert.deepEqual(test.progress, [ 127 'This browser could not initialize WebGL 2. Check graphics settings or try another browser.' 128 ]); 129 assert.equal(terminated, true); 130 assert.equal(revoked, 'blob:graphics-probe'); 131 } 132 133 async function startsWithMainThreadGraphicsWithoutOffscreenCanvas(creating) { 134 const test = fixture(); 135 let accountLoads = 0; 136 test.context.Module.loadAccount = () => { ++accountLoads; }; 137 test.context.location.href = 'http://localhost/?profile=1' + (creating ? '&create=1' : ''); 138 let restoredURL; 139 test.context.history.replaceState = (state, title, url) => { restoredURL = String(url); }; 140 const canvas = test.context.document.querySelector('#canvas'); 141 canvas.getContext = (type, attributes) => { 142 assert.equal(type, 'webgl2'); 143 assert.equal(attributes.preserveDrawingBuffer, true); 144 return {}; 145 }; 146 canvas.clientWidth = 1024; 147 canvas.clientHeight = 768; 148 const scripts = []; 149 let preloaded = false; 150 test.context.preloadStartupAssets = async () => { 151 await new Promise(resolve => setImmediate(resolve)); 152 preloaded = true; 153 }; 154 let clientScript; 155 test.context.URL = class extends URL { 156 static createObjectURL(blob) { clientScript = blob; return 'blob:client'; } 157 }; 158 test.context.AudioContext = class {}; 159 test.context.document.addEventListener = () => {}; 160 test.context.document.createElement = () => ({}); 161 test.context.document.body = {append: script => scripts.push(script.src)}; 162 test.context.fetch = async (url, options) => { 163 if (url === 'wasm/game.js') { 164 assert.equal(preloaded, true, 'startup cache must be ready before loading game code'); 165 return new Response('client code', {headers: {'Content-Type': 'text/javascript'}}); 166 } 167 assert.equal(url, 'browser-launch' + (creating ? '?create=1' : '')); 168 assert.equal(options.method, 'POST'); 169 return new Response('Clientr.exe localtest localtest ' + (creating ? '0' : '73') + ' 2130706433 7600 0 0', 170 {headers: creating ? {'X-AO-World-Port': '7700'} : {}}); 171 }; 172 173 await test.context.startGame(); 174 175 assert.deepEqual(scripts, ['blob:client']); 176 assert.equal(accountLoads, 0); 177 test.context.Module.onFirstFrame(); 178 assert.equal(accountLoads, 0); 179 assert.equal(await clientScript.text(), 'client code'); 180 assert.equal(clientScript.type, 'text/javascript'); 181 assert.equal(canvas.transferControlToOffscreen, undefined); 182 assert.equal(canvas.width, 1024); 183 assert.equal(canvas.height, 768); 184 assert.equal(restoredURL, 'http://localhost/?profile=1'); 185 assert.equal(test.context.Module.worldPort, creating ? 7700 : 7600); 186 assert.equal(test.context.Module.arguments[2], creating ? '0' : '73'); 187 } 188 189 async function rejectsFailedClientScript() { 190 const test = fixture(); 191 test.context.document.querySelector('#canvas').getContext = () => ({}); 192 test.context.AudioContext = class {}; 193 test.context.document.addEventListener = () => {}; 194 test.context.fetch = async url => { 195 if (url === 'browser-launch') return new Response('Clientr.exe localtest localtest 73'); 196 assert.equal(url, 'wasm/game.js'); 197 return new Response('missing', {status: 404}); 198 }; 199 200 await assert.rejects(test.context.startGame(), /Client script: HTTP 404/); 201 } 202 203 function startupFixture() { 204 const test = fixture(); 205 const written = new Map(), warnings = [], requests = []; 206 test.context.console = {info() {}, warn: (...args) => warnings.push(args)}; 207 test.context.caches = {open: async name => { 208 assert.equal(name, 'ao-asset-chunks-v1'); 209 return {match: async url => written.get(url)?.clone(), 210 put: async (url, response) => written.set(url, response)}; 211 }}; 212 const bytes = new Uint8Array(3 * 1048576); 213 bytes.fill(11, 0, 1048576); 214 bytes.fill(22, 1048576, 2 * 1048576); 215 bytes.fill(33, 2 * 1048576); 216 const headers = {'X-AO-Chunks': '0,7,554', 'X-AO-Asset-Version': '"database-revision"', 217 'Content-Length': String(bytes.length)}; 218 test.context.fetch = async (url, options) => { 219 assert.equal(url, 'browser-startup'); 220 assert.equal(options.cache, 'no-store'); 221 requests.push(options.method || 'GET'); 222 if (options.method === 'HEAD') return new Response(null, {headers}); 223 return new Response(new ReadableStream({start(controller) { 224 // Split both within a chunk and across boundaries, as an HTTP stream can do. 225 controller.enqueue(bytes.subarray(0, 17)); 226 controller.enqueue(bytes.subarray(17, 1048607)); 227 controller.enqueue(bytes.subarray(1048607)); 228 controller.close(); 229 }}), {headers}); 230 }; 231 return {...test, written, warnings, requests, bytes, headers}; 232 } 233 234 async function cachesStreamedStartupChunks() { 235 const test = startupFixture(); 236 await test.context.preloadStartupAssets(); 237 238 const urls = [...test.written.keys()]; 239 assert.deepEqual(urls, [ 240 'http://localhost/ao/browser-assets/cd_image/data/db/ResourceDatabase.dat?ao-chunk=1048576%3A0', 241 'http://localhost/ao/browser-assets/cd_image/data/db/ResourceDatabase.dat?ao-chunk=1048576%3A7', 242 'http://localhost/ao/browser-assets/cd_image/data/db/ResourceDatabase.dat?ao-chunk=1048576%3A554' 243 ]); 244 for (const [i, url] of urls.entries()) { 245 const response = test.written.get(url); 246 assert.equal(response.headers.get('ETag'), '"database-revision"'); 247 assert.deepEqual(new Uint8Array(await response.arrayBuffer()), test.bytes.subarray(i * 1048576, (i + 1) * 1048576)); 248 } 249 assert.deepEqual(test.percentages, [0, 7, 14, 21]); 250 assert.equal(test.downloadProgress.hidden, false); 251 assert.deepEqual(test.warnings, []); 252 assert.deepEqual(test.requests, ['HEAD', 'GET']); 253 } 254 255 async function skipsCachedStartupStream() { 256 const test = startupFixture(); 257 await test.context.preloadStartupAssets(); 258 test.requests.length = 0; 259 260 await test.context.preloadStartupAssets(); 261 262 assert.deepEqual(test.requests, ['HEAD']); 263 assert.equal(test.written.size, 3); 264 } 265 266 async function reloadsStartupStreamAfterCacheEviction() { 267 const test = startupFixture(); 268 await test.context.preloadStartupAssets(); 269 test.written.delete([...test.written.keys()][1]); 270 test.requests.length = 0; 271 272 await test.context.preloadStartupAssets(); 273 274 assert.deepEqual(test.requests, ['HEAD', 'GET']); 275 assert.equal(test.written.size, 3); 276 } 277 278 async function reloadsStartupStreamAfterDatabaseChange() { 279 const test = startupFixture(); 280 await test.context.preloadStartupAssets(); 281 test.headers['X-AO-Asset-Version'] = '"new-database-revision"'; 282 test.requests.length = 0; 283 284 await test.context.preloadStartupAssets(); 285 286 assert.deepEqual(test.requests, ['HEAD', 'GET']); 287 for (const response of test.written.values()) 288 assert.equal(response.headers.get('ETag'), '"new-database-revision"'); 289 } 290 291 async function rejectsIncompleteStartupStream() { 292 const test = startupFixture(); 293 const fetch = test.context.fetch; 294 test.context.fetch = async (url, options) => options.method === 'HEAD' ? fetch(url, options) : 295 new Response(test.bytes.subarray(0, 1048579), {headers: test.headers}); 296 297 await assert.rejects(test.context.preloadStartupAssets(), /Incomplete startup asset download/); 298 299 assert.equal(test.written.size, 1, 'partial chunks must never enter the cache'); 300 test.context.console.error = () => {}; 301 test.context.Module.onAbort('Incomplete startup asset download'); 302 assert.equal(test.downloadProgress.hidden, true); 303 test.context.fetch = fetch; 304 test.requests.length = 0; 305 await test.context.preloadStartupAssets(); 306 assert.deepEqual(test.requests, ['HEAD', 'GET']); 307 assert.equal(test.written.size, 3); 308 } 309 310 async function fallsBackWhenStartupCacheIsUnavailable() { 311 const test = startupFixture(); 312 test.context.caches.open = async () => { throw new Error('storage denied'); }; 313 test.context.fetch = () => assert.fail('must not download without a writable cache'); 314 315 await test.context.preloadStartupAssets(); 316 317 assert.equal(test.written.size, 0); 318 assert.equal(test.warnings.length, 1); 319 } 320 321 async function cancelsStartupStreamWhenCacheFills() { 322 const test = startupFixture(); 323 let cancelled = false; 324 test.context.caches.open = async () => ({match: async () => undefined, 325 put: async () => { throw new Error('quota exceeded'); }}); 326 const fetch = test.context.fetch; 327 test.context.fetch = async (url, options) => options.method === 'HEAD' ? fetch(url, options) : 328 new Response(new ReadableStream({start(controller) { 329 controller.enqueue(test.bytes.subarray(0, 1048576)); 330 }, cancel() { cancelled = true; }}), {headers: test.headers}); 331 332 await test.context.preloadStartupAssets(); 333 334 assert.equal(cancelled, true); 335 assert.equal(test.warnings.length, 1); 336 assert.equal(test.downloadProgress.hidden, false); 337 test.context.fetch = async () => clientDownloadResponse(); 338 await test.context.instantiateClient({}, () => {}); 339 assert.equal(test.percentages.at(-1), 100); 340 } 341 342 async function combinesAssetAndClientProgress(warm) { 343 const test = startupFixture(); 344 if (warm) { 345 await test.context.preloadStartupAssets(); 346 test.percentages.length = test.progress.length = test.visibility.length = 0; 347 } 348 349 await test.context.preloadStartupAssets(); 350 test.context.fetch = async () => clientDownloadResponse(); 351 await test.context.instantiateClient({}, () => {}); 352 353 assert.deepEqual(test.percentages, warm ? [0, 50, 100] : [0, 7, 14, 21, 21, 61, 100]); 354 assert.equal(test.visibility.at(-1), true); 355 assert.ok(test.visibility.slice(0, -1).every(hidden => !hidden), 'bar must stay visible between downloads'); 356 const downloads = test.progress.filter(message => message.includes(' MB')); 357 assert.ok(downloads.every(message => message.startsWith('Downloading Anarchy Online...'))); 358 assert.equal(downloads.at(-1), warm ? 'Downloading Anarchy Online...\n11.57 / 11.57 MB' : 359 'Downloading Anarchy Online...\n14.72 / 14.72 MB'); 360 } 361 362 async function revalidatesCachedClientWithoutDownloadProgress() { 363 const test = startupFixture(); 364 const requests = []; 365 test.context.fetch = async (url, options) => { 366 assert.equal(url, 'wasm/game.wasm'); 367 assert.equal(options.cache, 'no-store'); 368 requests.push(options.method || 'GET'); 369 if (options.method === 'HEAD') { 370 assert.equal(options.headers['If-None-Match'], '"client-revision"'); 371 return new Response(null, {status: 304}); 372 } 373 return clientDownloadResponse(); 374 }; 375 376 await test.context.prepareClientDownload(); 377 await test.context.instantiateClient({}, () => {}); 378 assert.equal(test.written.get('http://localhost/ao/wasm/game.wasm').headers.get('ETag'), '"client-revision"'); 379 test.visibility.length = test.progress.length = test.percentages.length = 0; 380 await test.context.prepareClientDownload(); 381 await test.context.instantiateClient({}, instance => assert.ok(instance instanceof WebAssembly.Instance)); 382 383 assert.deepEqual(requests, ['GET', 'HEAD']); 384 assert.deepEqual(test.percentages, []); 385 assert.deepEqual(test.visibility, [true]); 386 assert.deepEqual(test.progress, ['Starting Anarchy Online...']); 387 } 388 389 async function downloadsChangedClient() { 390 const test = startupFixture(); 391 const url = 'http://localhost/ao/wasm/game.wasm'; 392 test.written.set(url, clientDownloadResponse()); 393 const requests = []; 394 test.context.fetch = async (url, options) => { 395 requests.push(options.method || 'GET'); 396 const response = options.method === 'HEAD' ? new Response(null) : clientDownloadResponse(); 397 response.headers.set('ETag', '"changed-client"'); 398 return response; 399 }; 400 401 await test.context.prepareClientDownload(); 402 await test.context.instantiateClient({}, () => {}); 403 404 assert.deepEqual(requests, ['HEAD', 'GET']); 405 assert.deepEqual(test.percentages, [0, 50, 100]); 406 assert.equal(test.written.get(url).headers.get('ETag'), '"changed-client"'); 407 } 408 409 async function excludesCachedClientFromAssetProgress(quotaExceeded) { 410 const test = startupFixture(); 411 const url = 'http://localhost/ao/wasm/game.wasm'; 412 test.written.set(url, clientDownloadResponse()); 413 const fetch = test.context.fetch; 414 test.context.fetch = async (url, options) => url === 'wasm/game.wasm' ? 415 new Response(null, {status: 304}) : fetch(url, options); 416 if (quotaExceeded) { 417 test.context.caches.open = async () => ({match: async key => test.written.get(key)?.clone(), 418 put: async () => { throw new Error('quota exceeded'); }}); 419 } 420 421 await test.context.prepareClientDownload(); 422 await test.context.preloadStartupAssets(); 423 await test.context.instantiateClient({}, () => {}); 424 425 assert.deepEqual(test.percentages, quotaExceeded ? [0] : [0, 33, 67, 100]); 426 assert.equal(test.downloadProgress.hidden, true); 427 assert.ok(test.progress.every(message => !message.includes('NaN'))); 428 assert.equal(test.warnings.length, quotaExceeded ? 1 : 0); 429 } 430 431 async function startsClientWhenCacheUnavailable(writeFailure) { 432 const test = startupFixture(); 433 test.context.caches.open = async () => { 434 if (!writeFailure) throw new Error('storage denied'); 435 return {match: async () => undefined, put: async () => { throw new Error('quota exceeded'); }}; 436 }; 437 test.context.fetch = async () => clientDownloadResponse(); 438 439 await test.context.prepareClientDownload(); 440 await test.context.instantiateClient({}, instance => assert.ok(instance instanceof WebAssembly.Instance)); 441 442 assert.deepEqual(test.percentages, [0, 50, 100]); 443 assert.equal(test.warnings.length, 1); 444 } 445 446 await revalidatesCachedClientWithoutDownloadProgress(); 447 await downloadsChangedClient(); 448 await excludesCachedClientFromAssetProgress(false); 449 await excludesCachedClientFromAssetProgress(true); 450 await startsClientWhenCacheUnavailable(false); 451 await startsClientWhenCacheUnavailable(true); 452 await combinesAssetAndClientProgress(false); 453 await combinesAssetAndClientProgress(true); 454 await cachesStreamedStartupChunks(); 455 await skipsCachedStartupStream(); 456 await reloadsStartupStreamAfterCacheEviction(); 457 await reloadsStartupStreamAfterDatabaseChange(); 458 await rejectsIncompleteStartupStream(); 459 await fallsBackWhenStartupCacheIsUnavailable(); 460 await cancelsStartupStreamWhenCacheFills(); 461 await streamsDecodedClientAndTracksProgress(); 462 hidesProgressWhenDownloadStops(); 463 await rejectsFailedClientDownload(); 464 await reportsMissingWebGL(); 465 await reportsUnavailableWebGLOnBothThreadsBeforeDownloading(); 466 await startsWithMainThreadGraphicsWithoutOffscreenCanvas(false); 467 await startsWithMainThreadGraphicsWithoutOffscreenCanvas(true); 468 await rejectsFailedClientScript(); 469 console.log('PASS: loading progress, streaming compilation, first frame, download failure and missing browser graphics');