client/tests/browser_fetch.mjs (20368B)
1 import assert from 'node:assert/strict'; 2 import fs from 'node:fs'; 3 import vm from 'node:vm'; 4 5 // Exercise the WasmFS callbacks with small chunks and observable HTTP requests. 6 async function fixture(bytes, wholeFile = false, storage, version = '"one"', chunkSize = 4) { 7 const requests = []; 8 const manifests = []; 9 const warnings = []; 10 const heap = new Uint8Array(Math.max(64, bytes?.length || 0)); 11 let library; 12 const context = vm.createContext({ 13 AOProfile: {begin: () => 0, end: () => {}}, 14 Map, Uint8Array, Error, TypeError, Number, Math, URL, Response, TextDecoder, 15 AbortController, setTimeout, clearTimeout, HEAPU8: heap, 16 caches: storage, console: {warn: (...args) => warnings.push(args)}, 17 UTF8ToString: value => value, 18 __wasmfs_fetch_get_file_url: () => 'http://example.test/browser-assets//asset', 19 __wasmfs_fetch_get_chunk_size: () => chunkSize, 20 wasmFS$backends: {}, AOResourcePrefetch: {}, _browser_prefetch_resource_ready: () => {}, 21 addToLibrary: value => { library = value; }, 22 fetch: async (url, options) => { 23 if (url === 'http://example.test/browser-manifest') { 24 assert.equal(options.cache, 'no-store'); 25 assert.equal(options.headers.Accept, 'application/json'); 26 manifests.push(url); 27 return Response.json(bytes === null || wholeFile ? {} : { 28 asset: {size: bytes.length, version} 29 }); 30 } 31 assert.equal(url, 'http://example.test/browser-assets/asset'); 32 assert.equal(options.method, undefined); 33 requests.push(options.headers.Range); 34 if (bytes === null) return new Response(null, {status: 404}); 35 if (wholeFile) return new Response(bytes); 36 const [start, end] = options.headers.Range.slice(6).split('-').map(Number); 37 if (start >= bytes.length) 38 return new Response(null, {status: 416, headers: {'Content-Range': `bytes 0-0/${bytes.length}`}}); 39 const stop = Math.min(end + 1, bytes.length); 40 return new Response(bytes.slice(start, stop), {status: 206, 41 headers: {'Content-Range': `bytes ${start}-${stop - 1}/${bytes.length}`, ETag: version}}); 42 } 43 }); 44 vm.runInContext(fs.readFileSync(new URL('../runtime/browser_host.js', import.meta.url), 'utf8'), context); 45 context.AOAssetRequest = library.$AOAssetRequest; 46 const source = fs.readFileSync(new URL('../runtime/browser_fetch.js', import.meta.url), 'utf8') 47 .replaceAll('{{{ cDefs.EROFS }}}', '69').replaceAll('{{{ cDefs.ENOENT }}}', '44') 48 .replaceAll('{{{ cDefs.EBADF }}}', '8'); 49 vm.runInContext(source, context); 50 const initializing = library._wasmfs_create_fetch_backend_js(1); 51 assert.ok(context.wasmFS$backends[1], 'WasmFS requires synchronous callback registration'); 52 await initializing; 53 return {backend: context.wasmFS$backends[1], requests, manifests, heap, warnings, context, 54 prefetchStartup: library.browser_prefetch_startup_js}; 55 } 56 57 function diskCache() { 58 const entries = new Map(); 59 const cache = { 60 match: async url => entries.get(url)?.clone(), 61 put: async (url, response) => { entries.set(url, response.clone()); } 62 }; 63 return {open: async () => cache}; 64 } 65 66 async function overlappingReads() { 67 const {backend, requests, heap} = await fixture(new TextEncoder().encode('abcdefghijklmn')); 68 assert.equal(await backend.getSize(1), 14); 69 assert.equal(await backend.read(1, 0, 4, 8), 4); 70 71 const length = await backend.read(1, 0, 20, 2); 72 73 assert.equal(length, 12); 74 assert.equal(new TextDecoder().decode(heap.subarray(0, 12)), 'cdefghijklmn'); 75 assert.deepEqual(requests, ['bytes=0-3', 'bytes=8-11', 'bytes=4-7', 'bytes=12-15']); 76 assert.equal(await backend.read(1, 0, 4, 14), 0); 77 assert.equal(requests.length, 4); 78 } 79 80 async function metadataOnlySizes() { 81 const {backend, requests, manifests} = await fixture(new TextEncoder().encode('abcdef')); 82 83 const sizes = await Promise.all([backend.getSize(1), backend.getSize(2), backend.getSize(1)]); 84 85 assert.deepEqual(sizes, [6, 6, 6]); 86 assert.deepEqual(requests, []); 87 assert.equal(manifests.length, 1); 88 assert.equal(await backend.read(1, 0, 4, 0), 4); 89 assert.deepEqual(requests, ['bytes=0-3']); 90 assert.equal(manifests.length, 1); 91 } 92 93 async function concurrentReads() { 94 const {backend, requests, heap} = await fixture(new TextEncoder().encode('abcdefghijkl')); 95 96 const lengths = await Promise.all([backend.read(1, 0, 8, 4), backend.read(1, 16, 8, 4)]); 97 98 assert.deepEqual(lengths, [8, 8]); 99 assert.equal(new TextDecoder().decode(heap.subarray(0, 8)), 'efghijkl'); 100 assert.equal(new TextDecoder().decode(heap.subarray(16, 24)), 'efghijkl'); 101 assert.deepEqual(requests, ['bytes=0-3', 'bytes=4-11']); 102 } 103 104 async function mediumFileBoundary() { 105 const {backend, requests, heap} = await fixture(new TextEncoder().encode('abcdef')); 106 assert.equal(await backend.getSize(1), 6); 107 heap.fill(0xa5); 108 109 const length = await backend.read(1, 0, 3, 3); 110 111 assert.equal(length, 3); 112 assert.equal(new TextDecoder().decode(heap.subarray(0, 3)), 'def'); 113 assert.deepEqual(requests, ['bytes=0-3', 'bytes=4-7']); 114 } 115 116 async function wholeFileResponse() { 117 const {backend, requests, heap} = await fixture(new TextEncoder().encode('abcdef'), true); 118 119 const size = await backend.getSize(1); 120 const length = await backend.read(1, 0, 6, 0); 121 122 assert.equal(size, 6); 123 assert.equal(length, 6); 124 assert.equal(new TextDecoder().decode(heap.subarray(0, 6)), 'abcdef'); 125 assert.deepEqual(requests, ['bytes=0-3']); 126 } 127 128 async function emptyAndMissingFiles() { 129 const empty = await fixture(new Uint8Array()); 130 const missing = await fixture(null); 131 132 const size = await empty.backend.getSize(1); 133 const length = await empty.backend.read(1, 0, 4, 0); 134 const failure = await missing.backend.read(1, 0, 4, 0); 135 136 assert.equal(size, 0); 137 assert.equal(length, 0); 138 assert.equal(failure, -44); 139 assert.deepEqual(empty.requests, []); 140 } 141 142 await overlappingReads(); 143 await metadataOnlySizes(); 144 await concurrentReads(); 145 await mediumFileBoundary(); 146 await wholeFileResponse(); 147 await emptyAndMissingFiles(); 148 149 async function cachedReadAfterReload() { 150 const storage = diskCache(); 151 const bytes = new TextEncoder().encode('abcdefghijklmn'); 152 const first = await fixture(bytes, false, storage); 153 assert.equal(await first.backend.read(1, 0, 12, 4), 10); 154 const second = await fixture(bytes, false, storage); 155 156 const length = await second.backend.read(1, 0, 12, 2); 157 158 assert.equal(length, 12); 159 assert.equal(new TextDecoder().decode(second.heap.subarray(0, 12)), 'cdefghijklmn'); 160 assert.deepEqual(second.requests, []); 161 } 162 163 async function changedFileAfterReload() { 164 const storage = diskCache(); 165 const first = await fixture(new TextEncoder().encode('abcdefgh'), false, storage); 166 assert.equal(await first.backend.read(1, 0, 8, 0), 8); 167 const second = await fixture(new TextEncoder().encode('ABCDEFGH'), false, storage, '"two"'); 168 169 const length = await second.backend.read(1, 0, 8, 0); 170 171 assert.equal(length, 8); 172 assert.equal(new TextDecoder().decode(second.heap.subarray(0, 8)), 'ABCDEFGH'); 173 assert.deepEqual(second.requests, ['bytes=0-3', 'bytes=4-7']); 174 } 175 176 async function unavailableStorage() { 177 const storage = {open: async () => { throw new Error('Storage denied'); }}; 178 const {backend, heap, warnings} = await fixture(new TextEncoder().encode('abcdefgh'), false, storage); 179 180 const length = await backend.read(1, 0, 8, 0); 181 182 assert.equal(length, 8); 183 assert.equal(new TextDecoder().decode(heap.subarray(0, 8)), 'abcdefgh'); 184 assert.equal(warnings.length, 1); 185 } 186 187 async function partiallyCachedRead() { 188 const storage = diskCache(); 189 const bytes = new TextEncoder().encode('abcdefghijklmn'); 190 const first = await fixture(bytes, false, storage); 191 assert.equal(await first.backend.read(1, 0, 4, 8), 4); 192 const second = await fixture(bytes, false, storage); 193 194 const length = await second.backend.read(1, 0, 14, 0); 195 196 assert.equal(length, 14); 197 assert.equal(new TextDecoder().decode(second.heap.subarray(0, 14)), 'abcdefghijklmn'); 198 assert.deepEqual(second.requests, ['bytes=4-7', 'bytes=12-15']); 199 } 200 201 async function exhaustedStorage() { 202 const storage = {open: async () => ({ 203 match: async () => undefined, 204 put: async () => { throw new Error('Storage quota exceeded'); } 205 })}; 206 const {backend, heap, warnings} = await fixture(new TextEncoder().encode('abcdefghijkl'), false, storage); 207 208 assert.equal(await backend.read(1, 0, 4, 4), 4); 209 const length = await backend.read(1, 4, 4, 8); 210 211 assert.equal(length, 4); 212 assert.equal(new TextDecoder().decode(heap.subarray(0, 8)), 'efghijkl'); 213 assert.equal(warnings.length, 1); 214 } 215 216 async function incompleteCachedChunk() { 217 const storage = diskCache(); 218 await (await storage.open()).put('http://example.test/browser-assets/asset?ao-chunk=4%3A1', 219 new Response('e', {headers: {ETag: '"one"'}})); 220 const {backend, heap, requests} = await fixture(new TextEncoder().encode('abcdefgh'), false, storage); 221 222 const length = await backend.read(1, 0, 4, 4); 223 224 assert.equal(length, 4); 225 assert.equal(new TextDecoder().decode(heap.subarray(0, 4)), 'efgh'); 226 assert.deepEqual(requests, ['bytes=0-3', 'bytes=4-7']); 227 } 228 229 await cachedReadAfterReload(); 230 await changedFileAfterReload(); 231 await unavailableStorage(); 232 await partiallyCachedRead(); 233 await exhaustedStorage(); 234 await incompleteCachedChunk(); 235 236 async function cachedSmallFileAfterReload() { 237 const storage = diskCache(); 238 const bytes = new TextEncoder().encode('abc'); 239 const first = await fixture(bytes, false, storage); 240 assert.equal(await first.backend.read(1, 0, 3, 0), 3); 241 const second = await fixture(bytes, false, storage); 242 243 const length = await second.backend.read(1, 0, 3, 0); 244 const reopened = await second.backend.read(2, 4, 3, 0); 245 246 assert.equal(length, 3); 247 assert.equal(reopened, 3); 248 assert.equal(new TextDecoder().decode(second.heap.subarray(0, 3)), 'abc'); 249 assert.equal(new TextDecoder().decode(second.heap.subarray(4, 7)), 'abc'); 250 assert.deepEqual(second.requests, []); 251 assert.equal(second.manifests.length, 1); 252 } 253 254 await cachedSmallFileAfterReload(); 255 256 async function leastRecentlyUsedChunksAreFetchedAgain() { 257 const bytes = new Uint8Array(17 * 1024 * 1024); 258 bytes[0] = 11; 259 bytes[1048576] = 22; 260 const {backend, requests, heap} = await fixture(bytes, false, undefined, undefined, 1048576); 261 for (let index = 0; index < 16; ++index) 262 assert.equal(await backend.read(1, 0, 1, index * 1048576), 1); 263 264 await backend.read(1, 0, 1, 0); 265 await backend.read(1, 0, 1, 16777216); 266 await backend.read(1, 0, 1, 0); 267 assert.equal(heap[0], 11); 268 await backend.read(1, 0, 1, 1048576); 269 270 assert.equal(heap[0], 22); 271 assert.equal(requests.filter(range => range === 'bytes=0-1048575').length, 1); 272 assert.equal(requests.filter(range => range === 'bytes=1048576-2097151').length, 2); 273 } 274 275 async function readsLargerThanCacheKeepAllBytesUntilCopied() { 276 const bytes = new Uint8Array(18 * 1024 * 1024); 277 bytes[0] = 11; 278 bytes[18874367] = 33; 279 const {backend, requests, heap} = await fixture(bytes, false, undefined, undefined, 1048576); 280 281 const length = await backend.read(1, 0, bytes.length, 0); 282 assert.equal(heap[0], 11); 283 assert.equal(heap[18874367], 33); 284 await backend.read(1, 0, 1, 0); 285 286 assert.equal(length, 18874368); 287 assert.equal(heap[0], 11); 288 assert.deepEqual(requests, ['bytes=0-1048575', 'bytes=1048576-18874367', 'bytes=0-1048575']); 289 } 290 291 await leastRecentlyUsedChunksAreFetchedAgain(); 292 await readsLargerThanCacheKeepAllBytesUntilCopied(); 293 console.log('PASS: browser asset ranges, concurrent reads, persistent chunks, memory eviction, large reads and storage denial'); 294 295 // Advance request deadlines and backoff without waiting for real network time. 296 function retryClock(context) { 297 const timers = new Map(); 298 let next = 0; 299 context.Math = Object.create(Math); 300 context.Math.random = () => 0.5; 301 context.setTimeout = (callback, delay) => { 302 timers.set(++next, {callback, delay}); 303 return next; 304 }; 305 context.clearTimeout = id => timers.delete(id); 306 return { 307 timers, 308 async tick(delay) { 309 assert.equal(timers.size, 1); 310 const [id, timer] = timers.entries().next().value; 311 assert.equal(timer.delay, delay); 312 timers.delete(id); 313 timer.callback(); 314 await new Promise(setImmediate); 315 } 316 }; 317 } 318 319 async function manifestRetriesUntilConnectivityReturns() { 320 const {backend, context, heap, manifests, warnings} = await fixture(new TextEncoder().encode('abcd')); 321 const clock = retryClock(context); 322 const fetch = context.fetch; 323 const failures = [new TypeError('Offline'), 408, 429, 500, 502, 503, 504, new TypeError('Offline')]; 324 let attempts = 0, completed = false; 325 context.fetch = async (url, options) => { 326 if (url.endsWith('/browser-manifest') && attempts++ < failures.length) { 327 const failure = failures[attempts - 1]; 328 if (failure instanceof Error) throw failure; 329 return new Response(null, {status: failure}); 330 } 331 return fetch(url, options); 332 }; 333 334 const pending = Promise.all([backend.getSize(1), backend.getSize(2), backend.read(1, 0, 4, 0)]) 335 .then(result => { completed = true; return result; }); 336 await new Promise(setImmediate); 337 for (const delay of [750, 1500, 3000, 6000, 12000, 22500, 22500, 22500]) { 338 assert.equal(completed, false); 339 await clock.tick(delay); 340 } 341 const result = await pending; 342 343 assert.deepEqual(result, [4, 4, 4]); 344 assert.equal(new TextDecoder().decode(heap.subarray(0, 4)), 'abcd'); 345 assert.equal(attempts, 9); 346 assert.equal(manifests.length, 1); 347 assert.equal(warnings.length, 8); 348 assert.equal(clock.timers.size, 0); 349 } 350 351 async function concurrentChunkReadsSurviveTransferFailures() { 352 const {backend, context, heap, requests} = await fixture(new TextEncoder().encode('abcdefgh')); 353 await backend.read(1, 0, 4, 0); 354 const clock = retryClock(context); 355 const fetch = context.fetch; 356 let attempts = 0; 357 context.fetch = async (url, options) => { 358 ++attempts; 359 if (attempts === 1) throw new TypeError('Offline'); 360 if (attempts === 2) return new Response(null, {status: 503}); 361 if (attempts === 3) return new Response(new ReadableStream({start(controller) { 362 controller.error(new TypeError('Connection lost during transfer')); 363 }})); 364 return fetch(url, options); 365 }; 366 367 const pending = Promise.all([backend.read(1, 0, 4, 4), backend.read(1, 8, 4, 4)]); 368 await new Promise(setImmediate); 369 for (const delay of [750, 1500, 3000]) await clock.tick(delay); 370 const lengths = await pending; 371 372 assert.deepEqual(lengths, [4, 4]); 373 assert.equal(new TextDecoder().decode(heap.subarray(0, 4)), 'efgh'); 374 assert.equal(new TextDecoder().decode(heap.subarray(8, 12)), 'efgh'); 375 assert.equal(attempts, 4); 376 assert.deepEqual(requests, ['bytes=0-3', 'bytes=4-7']); 377 assert.equal(clock.timers.size, 0); 378 } 379 380 async function stalledRequestsAreAbortedAndRetried() { 381 for (const phase of ['headers', 'body']) { 382 const {backend, context, heap} = await fixture(new TextEncoder().encode('abcd')); 383 const clock = retryClock(context); 384 const fetch = context.fetch; 385 let attempts = 0, signal; 386 context.fetch = async (url, options) => { 387 if (url.endsWith('/browser-manifest') || ++attempts > 1) return fetch(url, options); 388 signal = options.signal; 389 if (phase === 'headers') return new Promise((resolve, reject) => { 390 signal.addEventListener('abort', () => reject(signal.reason)); 391 }); 392 return new Response(new ReadableStream({start(controller) { 393 signal.addEventListener('abort', () => controller.error(signal.reason)); 394 }})); 395 }; 396 397 const pending = backend.read(1, 0, 4, 0); 398 await new Promise(setImmediate); 399 await clock.tick(30000); 400 assert.equal(signal.aborted, true); 401 await clock.tick(750); 402 const length = await pending; 403 404 assert.equal(length, 4); 405 assert.equal(new TextDecoder().decode(heap.subarray(0, 4)), 'abcd'); 406 assert.equal(attempts, 2); 407 assert.equal(clock.timers.size, 0); 408 } 409 } 410 411 async function permanentFailuresDoNotRetry() { 412 for (const [response, expected] of [ 413 [new Response(null, {status: 404}), -44], 414 [new Response(null, {status: 403}), -8], 415 [new Response('abcd', {status: 206, headers: {ETag: '"one"', 'Content-Range': 'invalid'}}), -8], 416 [new Response('abcd', {headers: {ETag: '"changed"'}}), -8] 417 ]) { 418 const {backend, context, warnings} = await fixture(new TextEncoder().encode('abcd')); 419 const clock = retryClock(context); 420 const fetch = context.fetch; 421 let attempts = 0; 422 context.fetch = async (url, options) => { 423 if (url.endsWith('/browser-manifest')) return fetch(url, options); 424 ++attempts; 425 return response; 426 }; 427 428 const length = await backend.read(1, 0, 4, 0); 429 430 assert.equal(length, expected); 431 assert.equal(attempts, 1); 432 assert.equal(warnings.length, 0); 433 assert.equal(clock.timers.size, 0); 434 } 435 } 436 437 async function rejectedManifestDoesNotPoisonLaterReads() { 438 for (const response of [new Response(null, {status: 404}), new Response('invalid JSON')]) { 439 const {backend, context, heap, warnings} = await fixture(new TextEncoder().encode('abcd')); 440 const clock = retryClock(context); 441 const fetch = context.fetch; 442 let attempts = 0; 443 context.fetch = async (url, options) => { 444 if (url.endsWith('/browser-manifest') && ++attempts === 1) return response; 445 return fetch(url, options); 446 }; 447 448 const size = await backend.getSize(1); 449 const length = await backend.read(1, 0, 4, 0); 450 451 assert.equal(size, 0); 452 assert.equal(length, 4); 453 assert.equal(new TextDecoder().decode(heap.subarray(0, 4)), 'abcd'); 454 assert.equal(attempts, 2); 455 assert.equal(warnings.length, 0); 456 assert.equal(clock.timers.size, 0); 457 } 458 } 459 460 await manifestRetriesUntilConnectivityReturns(); 461 await concurrentChunkReadsSurviveTransferFailures(); 462 await stalledRequestsAreAbortedAndRetried(); 463 await permanentFailuresDoNotRetry(); 464 await rejectedManifestDoesNotPoisonLaterReads(); 465 console.log('PASS: indefinite retries, capped jittered backoff, shared recovery, transfer deadlines and permanent failures'); 466 467 468 async function startupChunksPrefetchInParallel() { 469 const stored = [], spans = []; 470 let active = 0, maximum = 0; 471 const test = await fixture(new Uint8Array(1048577), false, {open: async () => ({ 472 match: async url => { 473 const index = Number(new URL(url).searchParams.get('ao-chunk').split(':')[1]); 474 ++active; 475 maximum = Math.max(maximum, active); 476 await new Promise(resolve => setTimeout(resolve, 1)); 477 --active; 478 if (index === 4) return undefined; 479 return new Response(new Uint8Array(index === 5 ? 3 : 1048576).fill(index), { 480 headers: {ETag: index === 6 ? '"old"' : '"one"'}}); 481 } 482 })}); 483 test.context._malloc = size => { assert.equal(size, 1048576); return 1; }; 484 test.context._browser_store_startup_chunk = (inode, index, pointer) => { 485 assert.equal(inode, 42); 486 assert.equal(pointer, 1); 487 assert.equal(test.heap[1], index); 488 assert.equal(test.heap[1048576], index); 489 stored.push(index); 490 }; 491 test.context.AOProfile = {begin: () => 1, end: (name, start, detail) => spans.push(detail)}; 492 493 await test.prefetchStartup(JSON.stringify({url: 'http://example.test/browser-assets/asset', 494 version: '"one"', indices: [0, 1, 2, 3, 4, 5, 6, 7]}), 42); 495 496 assert.equal(maximum, 4); 497 assert.deepEqual(stored.sort((a, b) => a - b), [0, 1, 2, 3, 7]); 498 assert.equal(spans[0].chunks, 5); 499 assert.deepEqual(test.requests, []); 500 assert.deepEqual(test.warnings, []); 501 502 // A startup HEAD from an older deployment must not seed the current file. 503 stored.length = 0; 504 await test.prefetchStartup(JSON.stringify({url: 'http://example.test/browser-assets/asset', 505 version: '"old"', indices: [6]}), 42); 506 assert.deepEqual(stored, []); 507 } 508 509 async function startupPrefetchToleratesDeniedStorage() { 510 const test = await fixture(new Uint8Array(1), false, { 511 open: async () => { throw new Error('Storage denied'); } 512 }); 513 test.warnings.length = 0; 514 515 await test.prefetchStartup(JSON.stringify({url: 'http://example.test/browser-assets/asset', 516 version: '"one"', indices: [0]}), 42); 517 518 assert.equal(test.warnings.length, 1); 519 assert.deepEqual(test.requests, []); 520 } 521 522 await startupChunksPrefetchInParallel(); 523 await startupPrefetchToleratesDeniedStorage(); 524 console.log('PASS: four parallel startup reads publish only valid cached chunks and tolerate denied storage');