Search / tests /reader /transport /test_reader_engine_preload.js
vomebook
Preload the DjVu reader module graph on open
7127e28
Raw History Blame Contribute Delete
7.56 kB
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const assert = require('assert');
const root = process.argv[2] ? path.resolve(process.argv[2]) : path.resolve(__dirname,'../../..');
const script = fs.readFileSync(path.join(root,'static/reader/pdf/reader-engine-preload.js'),'utf8');
const resources = require(path.join(root,'static/reader-resources.js'));
const tick=()=>new Promise(resolve=>setImmediate(resolve));
function fixture(prefix,query,{saveData=false,held=false,httpFailure=false,readFailure=false,simd=true}={}){
const links=[],fetches=[],events=new Map(),timers=new Map();
const resourceContext={WebAssembly:{validate:()=>simd}};
vm.runInNewContext(fs.readFileSync(path.join(root,'static/reader-resources.js'),'utf8'),resourceContext);
let reads=0;
vm.runInNewContext(script,{URL,URLSearchParams,AbortController,Promise,
navigator:{connection:{saveData}},location:{search:query},VoiceOfMLReaderResources:resourceContext.VoiceOfMLReaderResources,
VoiceOfMLReaderSecurity:{async readBytes(_response,limit){assert.equal(limit,1024*1024);reads++;
if(readFailure)throw Error('optional bytes failed');return new Uint8Array();}},
setTimeout(fn,ms){assert.equal(ms,8000);timers.set(1,fn);return 1;},clearTimeout:id=>timers.delete(id),
addEventListener:(name,fn)=>events.set(name,fn),removeEventListener:name=>events.delete(name),
fetch(url,options){
fetches.push({url,options});
assert.ok(/\/static\/(?:reader\/pdf\/pdf-worker-wrapper\.[a-f0-9.]*mjs|reader\/pdf\/pdf-worker-wrapper\.mjs|vendor\/wasm\/qcms_bg\.wasm|vendor\/djvu-rs-reader\/release-06c82c74447d-03087b1edf0c\/(?:scalar|simd128)\/djvu_rs_bg\.wasm)$/.test(url),'byte warming is restricted to component paths');
assert.equal(options.mode,url.includes('/djvu-rs-reader/')?'cors':'same-origin');assert.equal(options.credentials,'same-origin');
if(held)return new Promise((_,reject)=>options.signal.addEventListener('abort',()=>reject(options.signal.reason),{once:true}));
return Promise.resolve({ok:!httpFailure,body:{cancel:async()=>{}}});
},
document:{currentScript:{src:'https://site.test'+prefix+'reader/pdf/reader-engine-preload.abcdef123456.js'},
createElement:()=>({}),head:{appendChild:node=>links.push(node)}}});
return {links,fetches,events,timers,get reads(){return reads;}};
}
(async()=>{
for(const prefix of ['/static/','/search/static/']){
for(const [query,pdf] of [['?ext=pdf',true],['?ext=PDF',true],['?ext=txt',false],['?id=abc',false],
['?url='+encodeURIComponent('https://example.test/Book.PDF'),true],['?url=invalid&ext=txt',false]]){
const f=fixture(prefix,query),base='https://site.test'+prefix;
assert.deepStrictEqual(f.links.map(link=>link.href),pdf?['pdf','pdfWorker'].map(name=>resources.vendorUrl(name,base)):[]);
assert.ok(f.links.every(link=>link.rel==='modulepreload'));
assert.deepStrictEqual(f.fetches.map(row=>row.url),pdf?[base+'reader/pdf/pdf-worker-wrapper.mjs',...resources.pdfSupportAssets(base)]:[]);
await tick();assert.equal(f.reads,pdf?2:0);assert.equal(f.timers.size,0);assert.equal(f.events.size,0);
}
for(const extension of ['md','markdown','html','htm','epub']){
const f=fixture(prefix,'?ext='+extension),base='https://site.test'+prefix;
assert.deepStrictEqual(f.links.map(link=>link.href),resources.engineAssets(extension,base));
assert.equal(f.fetches.length,0);
if(extension==='epub') assert.deepStrictEqual(f.links, [], 'removed raw EPUB engine must not be warmed');
else {
assert.ok(f.links.every(link=>link.rel==='preload'&&link.as==='script'));
if(extension==='html'||extension==='htm')assert.equal(f.links.length,1);
}
}
}
for(const prefix of ['/static/','/search/static/']) for(const simd of [true,false]) for(const extension of ['djvu','djv']) {
const f=fixture(prefix,'?ext='+extension,{simd});await tick();
const modules = ['loader','adapter','identity','range','worker','scheduler'].map(name =>
'https://site.test'+prefix+'reader/pdf/reader-djvu-'+name+'.mjs');
assert.deepEqual(f.links.map(link=>link.href),modules,'warm only the known DjVu reader dependency graph');
assert.ok(f.links.every(link=>link.rel==='modulepreload'));
assert.equal(f.fetches.length,1);
assert.ok(f.fetches[0].url.endsWith('/'+(simd?'simd128':'scalar')+'/djvu_rs_bg.wasm'));
assert.equal(f.reads,1);assert.equal(f.timers.size,0);assert.equal(f.events.size,0);
assert.equal(fixture(prefix,'?ext='+extension,{simd,saveData:true}).fetches.length,0);
}
// Execute the actual worker bootstrap against the same shared probe. Only
// module loading and fetch are substituted; the decoder choice remains real.
const workerSource=fs.readFileSync(path.join(root,'static/reader/pdf/reader-djvu-engine-worker.mjs'),'utf8');
for(const simd of [true,false]) {
const calls=[],probes=[];
const context={URL,AbortController,Uint8Array,WebAssembly:{validate:bytes=>{probes.push([...bytes]);return simd;}},
loadModule:async url=>{calls.push(String(url));return {default:async({module_or_path})=>assert.ok(module_or_path.ok)};},
fetch:async url=>{calls.push(String(url));return {ok:true};},self:{postMessage(){}}};
vm.createContext(context);
vm.runInContext(fs.readFileSync(path.join(root,'static/reader-resources.js'),'utf8').replace('typeof self !== "undefined" ? self : globalThis','globalThis'),context);
const warm=vm.runInContext('VoiceOfMLReaderResources.engineAssets("djvu","https://site.test/static/")',context);
const bootstrap=workerSource.slice(0,workerSource.indexOf('self.onmessage ='))
.replace(/^import '\.\.\/\.\.\/reader-resources\.js';$/m,'')
.replaceAll('import.meta.url','"https://site.test/static/reader/pdf/reader-djvu-engine-worker.mjs"')
.replaceAll('import(', 'loadModule(');
await vm.runInContext(bootstrap+'\nprepareEngine()',context);
assert.equal(probes.length,2);assert.deepStrictEqual(probes[0],probes[1]);
assert.ok(WebAssembly.validate(new Uint8Array(probes[0])),'probe must be a valid native SIMD module');
assert.ok(calls.includes(warm[0]),'actual worker consumes the exact warmed WASM URL');
assert.ok(calls.every(url=>url.includes('/'+(simd?'simd128':'scalar')+'/')));
assert.equal(calls.length,2);
}
const lean=fixture('/static/','?ext=pdf',{saveData:true});await tick();assert.equal(lean.fetches.length,1);
assert.ok(lean.fetches[0].url.endsWith('pdf-worker-wrapper.mjs'));
for(const event of ['pagehide','voice-reader-dispose','timeout']){
const f=fixture('/static/','?ext=pdf',{held:true});
if(event==='timeout')f.timers.get(1)();else f.events.get(event)();
await tick();assert.ok(f.fetches.every(row=>row.options.signal.aborted));assert.equal(f.events.size,0);assert.equal(f.timers.size,0);
}
for(const options of [{httpFailure:true},{readFailure:true}]){
const f=fixture('/static/','?ext=pdf',options);await tick();
assert.equal(f.timers.size,0);assert.equal(f.events.size,0,'optional failure must release warming ownership');
}
assert.ok(resources.readerFiles.indexOf('reader/pdf/pdf-worker-wrapper.mjs')<resources.readerFiles.indexOf('reader/pdf/reader-engine-preload.js'),
'topological hashing must know the Worker demand path before rewriting its warmup');
console.log('Pinned PDF/DjVu/Markdown/HTML warming, shared SIMD probe, worker demand URLs and both prefixes passed');
})().catch(error=>{console.error(error);process.exitCode=1;});