client/runtime/browser_fetch.js (17644B)
1 addToLibrary({ 2 browser_prefetch_startup_js__deps: ['$AOResourcePrefetch', '$UTF8ToString'], 3 browser_prefetch_startup_js: (configuration, inode) => 4 AOResourcePrefetch.startup(JSON.parse(UTF8ToString(configuration)), inode), 5 $AOResourcePrefetch: {}, 6 browser_prefetch_resource_js__deps: ['$AOResourcePrefetch'], 7 browser_prefetch_resource_js: (kind, identity) => AOResourcePrefetch.request(kind, identity), 8 _wasmfs_create_fetch_backend_js__deps: [ 9 '$wasmFS$backends', '_wasmfs_fetch_get_file_url', '_wasmfs_fetch_get_chunk_size', 10 '$AOResourcePrefetch', '$AOProfile', '$AOAssetRequest', 'browser_prefetch_resource_ready', 11 'malloc', 'browser_store_startup_chunk' 12 ], 13 _wasmfs_create_fetch_backend_js: async function(backend) { 14 const files = new Map(); 15 const cachedChunks = new Map(); 16 let cachedBytes = 0; 17 18 // Active reads retain their bytes until copying into Wasm has finished. 19 function trimChunks() { 20 for (const [bytes, entry] of cachedChunks) { 21 if (cachedBytes <= 16 * 1024 * 1024) break; 22 if (entry.file.readers) continue; 23 delete entry.file.chunks[entry.index]; 24 cachedChunks.delete(bytes); 25 cachedBytes -= bytes.byteLength; 26 } 27 } 28 function rememberChunk(file, index, bytes) { 29 const previous = file.chunks[index]; 30 if (cachedChunks.delete(previous)) cachedBytes -= previous.byteLength; 31 file.chunks[index] = bytes; 32 cachedChunks.set(bytes, {file, index}); 33 cachedBytes += bytes.byteLength; 34 trimChunks(); 35 } 36 // File URLs are valid only after their WasmFS constructor has returned. 37 const allocatedFiles = new Set(), prefetchedFamilies = new Set(), prefetchQueue = []; 38 let prefetching = 0, soundGroups = null; 39 40 // FetchFS joins its base and path with two slashes; avoid a server redirect. 41 function fileURL(handle) { 42 const url = new URL(UTF8ToString(__wasmfs_fetch_get_file_url(handle))); 43 url.pathname = url.pathname.replace(/\/+/g, '/'); 44 return url.href; 45 } 46 47 function pumpPrefetch() { 48 while (prefetching < 2 && prefetchQueue.length) { 49 const handle = prefetchQueue.shift(); 50 if (!allocatedFiles.has(handle) || files.has(handle)) continue; 51 ++prefetching; 52 // Failed speculation is retried if the game later requests this file. 53 getFile(handle).catch(() => {}).finally(() => { 54 --prefetching; 55 pumpPrefetch(); 56 }); 57 } 58 } 59 60 let startupPrefetched = false; 61 const startupFiles = new Set(); 62 function prefetchStartup() { 63 if (startupPrefetched) return; 64 startupPrefetched = true; 65 // The initializer registers the whole tree before copying its writable files. 66 for (const handle of allocatedFiles) { 67 const path = new URL(fileURL(handle)).pathname; 68 if (/\/browser-assets\/(Prefs\/|cd_image\/OCC\/|Setupf\/|fonts\/|cd_image\/textures\/(Archives\/|fonts\/))/.test(path) || 69 path.endsWith('/ResourceDatabase.idx')) startupFiles.add(handle); 70 } 71 // These fixed bootstrap files total about 12 MiB and are needed in every zone. 72 for (const handle of startupFiles) getFile(handle).catch(() => {}); 73 } 74 75 function soundFamily(url) { 76 // Terrain and action variants share one footwear directory. 77 const footsteps = /^(.*\/sound\/sfx\/foots\/[^/]+\/)[^/]+\.wav$/i.exec(url); 78 if (footsteps) return footsteps[1]; 79 const numbered = /^(.*\/sound\/.*?)(\d+)\.wav$/i.exec(url); 80 return numbered && numbered[1]; 81 } 82 83 function prefetchSounds(url) { 84 const family = soundFamily(url); 85 if (!family || prefetchedFamilies.has(family)) return; 86 prefetchedFamilies.add(family); 87 // Return the requested sound first; find and fetch siblings in the background. 88 setTimeout(() => { 89 if (!soundGroups) { 90 // Sound reads begin after browser_initialize has built the remote file tree. 91 soundGroups = new Map(); 92 for (const handle of allocatedFiles) { 93 const other = soundFamily(fileURL(handle)); 94 if (!other) continue; 95 if (!soundGroups.has(other)) soundGroups.set(other, []); 96 soundGroups.get(other).push(handle); 97 } 98 } 99 for (const handle of soundGroups.get(family) || []) 100 if (!files.has(handle)) prefetchQueue.push(handle); 101 pumpPrefetch(); 102 }); 103 } 104 105 let cache, metadata; 106 function disableCache(error) { 107 cache = null; 108 console.warn('Asset disk cache unavailable; continuing with network reads', error); 109 } 110 // Storage can be denied or exhausted; it must not prevent the game from loading. 111 const cacheReady = globalThis.caches 112 ? caches.open('ao-asset-chunks-v1').then(result => { cache = result; }).catch(disableCache) 113 : Promise.resolve(); 114 115 function chunkURL(file, index) { 116 const url = new URL(file.url); 117 url.searchParams.set('ao-chunk', `${file.chunkSize}:${index}`); 118 return url.href; 119 } 120 121 // Fetch the bytes and file size together, without a separate HEAD request. 122 async function fetchChunks(file, first, last) { 123 const start = AOProfile.begin('asset network'); 124 try { 125 return await fetchChunkBytes(file, first, last); 126 } finally { 127 AOProfile.end('asset network', start, 128 `${new URL(file.url).pathname} bytes ${first * file.chunkSize}-${(last + 1) * file.chunkSize - 1}`); 129 } 130 } 131 132 async function fetchChunkBytes(file, first, last) { 133 const start = first * file.chunkSize; 134 const end = (last + 1) * file.chunkSize - 1; 135 // Validate against the server, not an older partial response in the HTTP cache. 136 const {response, bytes: buffer} = await AOAssetRequest(file.url, 137 {cache: 'no-store', headers: {Range: `bytes=${start}-${end}`}}); 138 // Browser HTTP caches can describe an empty range as 0-0/0 instead of */0. 139 if (response.status === 416 && /^bytes (\*|0-0)\/0$/.test(response.headers.get('Content-Range'))) { 140 file.size = 0; 141 return; 142 } 143 if (!response.ok) throw response; 144 const version = response.headers.get('ETag'); 145 if (file.version !== undefined && file.version !== version) 146 throw new Error('Asset changed during play'); 147 file.version = version; 148 const bytes = new Uint8Array(buffer); 149 if (response.status === 200) { 150 file.size = bytes.length; 151 for (let offset = 0; offset < bytes.length; offset += file.chunkSize) 152 rememberChunk(file, offset / file.chunkSize, 153 bytes.length <= file.chunkSize ? bytes : bytes.slice(offset, offset + file.chunkSize)); 154 return; 155 } 156 const range = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(response.headers.get('Content-Range')); 157 if (!range || Number(range[1]) !== start || Number(range[2]) !== start + bytes.length - 1 || 158 Number(range[2]) !== Math.min(end, Number(range[3]) - 1)) 159 throw new Error('Invalid asset range response'); 160 file.size = Number(range[3]); 161 for (let index = first; index <= last && index * file.chunkSize < file.size; ++index) { 162 const offset = (index - first) * file.chunkSize; 163 const chunk = bytes.length <= file.chunkSize ? bytes : bytes.slice(offset, offset + file.chunkSize); 164 rememberChunk(file, index, chunk); 165 // Store complete chunks as ordinary responses; Cache Storage rejects HTTP 206. 166 if (cache && file.version) 167 cache.put(chunkURL(file, index), new Response(chunk, { 168 headers: {ETag: file.version} 169 })).catch(disableCache); 170 } 171 } 172 173 async function loadChunks(file, first, last) { 174 const cached = []; 175 if (cache && file.version) { 176 await Promise.all(Array.from({length: last - first + 1}, async (_, offset) => { 177 const index = first + offset; 178 const response = await cache.match(chunkURL(file, index)); 179 if (response && response.headers.get('ETag') === file.version) { 180 const bytes = new Uint8Array(await response.arrayBuffer()); 181 if (bytes.length === Math.min(file.chunkSize, file.size - index * file.chunkSize)) { 182 rememberChunk(file, index, bytes); 183 cached[index] = true; 184 } 185 } 186 })).catch(disableCache); 187 } 188 // The startup manifest supplies versions before any disk-cache reads. 189 for (let index = first; index <= last; ++index) { 190 if (cached[index]) continue; 191 const start = index; 192 while (index < last && !cached[index + 1]) ++index; 193 await fetchChunks(file, start, index); 194 } 195 } 196 197 // Validate all file versions together; size queries need no asset bytes. 198 function serverURL(name, assetURL) { 199 return assetURL.slice(0, assetURL.lastIndexOf('/browser-assets/') + 1) + name; 200 } 201 async function fileMetadata(url) { 202 if (!metadata) { 203 metadata = AOAssetRequest(serverURL('browser-manifest', url), { 204 cache: 'no-store', headers: {Accept: 'application/json'} 205 }).then(({response, bytes}) => { 206 if (!response.ok) throw response; 207 return JSON.parse(new TextDecoder().decode(bytes)); 208 }).catch(error => { 209 metadata = null; 210 throw error; 211 }); 212 } 213 const listing = await metadata; 214 const pathname = new URL(url).pathname; 215 const name = decodeURIComponent(pathname.slice(pathname.lastIndexOf('/browser-assets/') + '/browser-assets/'.length)); 216 return listing[name]; 217 } 218 219 // Share the first request and cached chunks between concurrent readers. 220 function getFile(handle) { 221 if (!files.has(handle)) { 222 const url = fileURL(handle); 223 const file = { 224 url, handle, readers: 0, 225 chunkSize: __wasmfs_fetch_get_chunk_size(handle), chunks: [] 226 }; 227 const pending = Promise.all([cacheReady, fileMetadata(url)]).then(async ([, info]) => { 228 if (info) { 229 file.size = info.size; 230 file.version = info.version; 231 // Small startup archives are cheaper as one transfer than serial ranges. 232 if (file.size) await loadChunks(file, 0, 233 startupFiles.has(handle) ? Math.ceil(file.size / file.chunkSize) - 1 : 0); 234 } else { 235 await fetchChunks(file, 0, 0); 236 } 237 prefetchSounds(url); 238 return file; 239 }); 240 files.set(handle, pending); 241 pending.catch(() => files.delete(handle)); 242 prefetchStartup(); 243 } 244 return files.get(handle); 245 } 246 247 async function ensureChunks(file, first, last) { 248 // Foreground reads and speculation join the same in-flight requests. 249 const pending = []; 250 for (let index = first; index <= last; ++index) { 251 if (!file.chunks[index]) { 252 const start = index; 253 while (index < last && !file.chunks[index + 1]) ++index; 254 const end = index; 255 const request = loadChunks(file, start, end); 256 for (let chunk = start; chunk <= end; ++chunk) file.chunks[chunk] = request; 257 request.catch(() => { 258 for (let chunk = start; chunk <= end; ++chunk) delete file.chunks[chunk]; 259 }); 260 pending.push(request); 261 } else if (file.chunks[index] instanceof Promise) { 262 pending.push(file.chunks[index]); 263 } 264 } 265 await Promise.all(pending); 266 } 267 268 let resourceIndex, databaseHandle, resourceReads = 0; 269 const resources = []; 270 async function readResourceIndex() { 271 let indexURL; 272 for (const file of allocatedFiles) { 273 const url = fileURL(file); 274 if (url.endsWith('/ResourceDatabase.idx')) indexURL = url; 275 if (url.endsWith('/ResourceDatabase.dat')) databaseHandle = file; 276 } 277 const info = await fileMetadata(indexURL); 278 const {response, bytes} = await AOAssetRequest(serverURL('browser-resource-index', indexURL), 279 {headers: {'If-Match': info.version}}); 280 if (!response.ok) throw new Error(`Resource prefetch index: HTTP ${response.status}`); 281 const records = new DataView(bytes); 282 if (records.byteLength % 12) throw new Error('Invalid resource prefetch index'); 283 return records; 284 } 285 286 async function prefetchResource(offset) { 287 if (!allocatedFiles.has(databaseHandle)) return; 288 const file = await getFile(databaseHandle); 289 const chunk = Math.floor(offset / file.chunkSize); 290 if (offset < file.size) await ensureChunks(file, chunk, chunk); 291 } 292 293 function pumpResources() { 294 while (resourceReads < 4 && resources.length) { 295 ++resourceReads; 296 // Failed speculation leaves the normal read path free to retry. 297 prefetchResource(resources.shift()).catch(() => {}).finally(() => { 298 --resourceReads; 299 pumpResources(); 300 }); 301 } 302 } 303 304 AOResourcePrefetch.request = (kind, identity) => { 305 kind >>>= 0; 306 identity >>>= 0; 307 if (!resourceIndex) resourceIndex = readResourceIndex().catch(error => { 308 console.warn('Resource prefetch unavailable; continuing with demand reads', error); 309 return null; 310 }); 311 resourceIndex.then(records => { 312 if (!records) return; 313 // The server sorts fixed-size uint32 triples; no string-keyed map is needed. 314 let first = 0, last = records.byteLength / 12; 315 while (first < last) { 316 const middle = (first + last) >>> 1; 317 const recordKind = records.getUint32(middle * 12, true); 318 const recordIdentity = records.getUint32(middle * 12 + 4, true); 319 if (recordKind < kind || (recordKind === kind && recordIdentity <= identity)) first = middle + 1; 320 else last = middle; 321 } 322 const offset = (first - 1) * 12; 323 if (first && records.getUint32(offset, true) === kind && records.getUint32(offset + 4, true) === identity) { 324 resources.push(records.getUint32(offset + 8, true)); 325 pumpResources(); 326 } 327 }); 328 }; 329 AOResourcePrefetch.startup = async ({url, version, indices}, inode) => { 330 const start = AOProfile.begin('startup RAM prefetch'); 331 let completed = 0; 332 try { 333 const cache = await caches.open('ao-asset-chunks-v1'); 334 if ((await fileMetadata(url))?.version !== version) return; 335 let next = 0; 336 const results = await Promise.allSettled(Array.from({length: 4}, async () => { 337 while (next < indices.length) { 338 const index = indices[next++], chunkURL = new URL(url); 339 chunkURL.searchParams.set('ao-chunk', `1048576:${index}`); 340 const response = await cache.match(chunkURL.href); 341 if (response?.headers.get('ETag') !== version) continue; 342 const bytes = new Uint8Array(await response.arrayBuffer()); 343 if (bytes.byteLength !== 1048576) continue; 344 const pointer = _malloc(bytes.byteLength); 345 if (!pointer) throw new Error('Could not allocate startup chunk'); 346 HEAPU8.set(bytes, pointer); 347 _browser_store_startup_chunk(inode, index, pointer); 348 ++completed; 349 } 350 })); 351 const failed = results.find(result => result.status === 'rejected'); 352 if (failed) throw failed.reason; 353 } catch (error) { 354 // Storage can disappear or be denied; demand reads remain authoritative. 355 console.warn('Startup RAM prefetch unavailable:', error); 356 } finally { 357 AOProfile.end('startup RAM prefetch', start, {chunks: completed}); 358 } 359 }; 360 _browser_prefetch_resource_ready(); 361 362 wasmFS$backends[backend] = { 363 allocFile: async (file) => { allocatedFiles.add(file); soundGroups = null; }, 364 freeFile: async (file) => { 365 allocatedFiles.delete(file); files.delete(file); soundGroups = null; 366 for (const [bytes, entry] of cachedChunks) { 367 if (entry.file.handle !== file) continue; 368 cachedChunks.delete(bytes); 369 cachedBytes -= bytes.byteLength; 370 } 371 }, 372 write: async () => -{{{ cDefs.EROFS }}}, 373 getSize: async (handle) => { 374 try { 375 const info = await fileMetadata(fileURL(handle)); 376 return info ? info.size : (await getFile(handle)).size; 377 } catch (error) { 378 return 0; 379 } 380 }, 381 read: async (handle, buffer, length, offset) => { 382 if (offset < 0 || length <= 0) return 0; 383 try { 384 const file = await getFile(handle); 385 length = Math.min(length, file.size - offset); 386 if (length <= 0) return 0; 387 const first = Math.floor(offset / file.chunkSize); 388 const last = Math.floor((offset + length - 1) / file.chunkSize); 389 390 ++file.readers; 391 try { 392 await ensureChunks(file, first, last); 393 for (let index = first; index <= last; ++index) { 394 const start = Math.max(offset, index * file.chunkSize); 395 const end = Math.min(offset + length, (index + 1) * file.chunkSize); 396 const bytes = file.chunks[index], entry = cachedChunks.get(bytes); 397 cachedChunks.delete(bytes); 398 cachedChunks.set(bytes, entry); 399 HEAPU8.set(bytes.subarray(start - index * file.chunkSize, 400 end - index * file.chunkSize), buffer + start - offset); 401 } 402 } finally { 403 --file.readers; 404 trimChunks(); 405 } 406 return length; 407 } catch (error) { 408 return error.status === 404 ? -{{{ cDefs.ENOENT }}} : -{{{ cDefs.EBADF }}}; 409 } 410 } 411 }; 412 } 413 });