perf: load page modules on demand and avoid repeated startup ACL writes
This commit is contained in:
1 parent
73773f9526
commit
7ead1e7cb7
19 files changed
+330
-24
No files matched your search
@@ -56,11 +56,21 @@ test('asset URLs become immutable only when their content fingerprint is verifie
|
||||
|
||||
test('HTML uses actual fingerprint URLs while the document itself always revalidates',async t=>{
|
||||
const get=await fixture(t),page=await get('/'),html=page.bytes.toString();
|
||||
const urls=[...html.matchAll(/(?:src|href)="(\/[^"#]+)"/g)].map(match=>match[1]);assert.ok(urls.length>=44);
|
||||
const urls=[...html.matchAll(/(?:src|href)="(\/[^"#]+)"/g)].map(match=>match[1]);assert.ok(urls.length>0&&urls.length<20,'core shell stays below twenty eager assets');
|
||||
for(const url of urls){assert.match(url,/\?v=[a-f0-9]{64}$/);const asset=await get(url);assert.equal(asset.status,200);assert.match(asset.headers['cache-control'],/immutable/);assert.equal(new URL(url,'http://local').searchParams.get('v'),asset.headers['x-asset-version']);}
|
||||
const versioned=await get('/?v='+page.headers['x-asset-version']);assert.match(versioned.headers['cache-control'],/must-revalidate/);assert.doesNotMatch(versioned.headers['cache-control'],/immutable/);
|
||||
});
|
||||
|
||||
test('HTML publishes fingerprint URLs for lazy modules without eagerly loading optional pages',async t=>{
|
||||
const get=await fixture(t),page=await get('/'),html=page.bytes.toString();
|
||||
const encoded=/<meta name="app-modules" content="([^"]+)"/.exec(html)?.[1];assert.ok(encoded,'lazy module manifest must be available in the document');
|
||||
const manifest=JSON.parse(encoded.replaceAll('"','"').replaceAll('<','<').replaceAll('>','>').replaceAll('&','&'));
|
||||
for(const route of ['/assistant.js','/business-home.js','/order-rules.js']){
|
||||
assert.ok(manifest.urls[route]);assert.equal(html.includes('<script src="'+manifest.urls[route]+'"'),false);
|
||||
const asset=await get(manifest.urls[route]);assert.equal(asset.status,200);assert.match(asset.headers['cache-control'],/immutable/);assert.equal(new URL(manifest.urls[route],'http://local').searchParams.get('v'),asset.headers['x-asset-version']);
|
||||
}
|
||||
});
|
||||
|
||||
test('changing one dependency changes its URL and HTML ETag without invalidating other assets',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'asset-dependency-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
|
||||
const documentPath=path.join(dir,'index.html'),one=path.join(dir,'one.js'),two=path.join(dir,'two.css');fs.writeFileSync(documentPath,'<!doctype html><link href="/two.css" rel="stylesheet"><script src="/one.js" defer></script>');fs.writeFileSync(one,'old()');fs.writeFileSync(two,'body{}');
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {orderDrivenUI}=require('../fixtures/order-driven-ui.cjs');
|
||||
|
||||
test('cold home omits optional pages, routes load dependencies on demand and reuse completed scripts',{timeout:120000},async t=>{
|
||||
const {page}=await orderDrivenUI(t,'#overview'),errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||
await page.route('**/api/mail',r=>r.fulfill({json:{channels:[],templates:[],receipts:[],sends:[]}}));
|
||||
await page.route('**/api/assistant',r=>r.fulfill({json:{settings:{version:1,enabled:false,model:'fixture',runtimePath:'',apiBase:'',timeoutSeconds:90,dailyLimit:100,allowActions:false},conversations:[],skills:[],usage:{calls:0,limit:100}}}));
|
||||
await page.route('**/api/assistant/conversations?*',r=>r.fulfill({json:{items:[],total:0,page:1}}));
|
||||
await page.route('**/api/assistant/operations*',r=>r.fulfill({json:{events:[]}}));
|
||||
await page.route('**/api/storage',r=>r.fulfill({json:{servers:[],archives:[],settings:{version:1,enabled:false,defaultServerId:''}}}));
|
||||
await page.route('**/api/health',r=>r.fulfill({json:{runtime:{uptimeSeconds:0,startedAt:'2026-10-28T00:00:00Z',autostart:{enabled:false},guard:{status:'unmanaged',events:[]}},groups:[]}}));
|
||||
await page.locator('[data-business-home]').waitFor();const reads=[];
|
||||
page.on('request',r=>{if(r.resourceType()==='script')reads.push(new URL(r.url()).pathname);});
|
||||
await page.reload();await page.locator('[data-business-home]').waitFor();
|
||||
for(const route of ['/assistant.js','/bpm.js','/mail.js','/storage.js','/order-rules.js'])assert.equal(reads.includes(route),false,route);
|
||||
const screens=[['notification-orders','[data-arrival-list]'],['notification-batches','[data-arrival-list]'],['rule-fields','#fm-count'],['order-rules','#order-rules-panel'],['mail','#mail-add'],['assistant','#assistant-input'],['assistant-settings','#assistant-settings-form'],['storage','#storage-add'],['health','#health-refresh'],['records-pdf','[data-pdf-list]'],['records','[data-arrival-list]'],['bpm','[data-bpm-feedback]'],['account','#account-password-form'],['calendar','#day-form'],['exceptions','#exception-new'],['templates','#mail-templates'],['schedule','#schedule-form'],['audit','.audit-detail,.empty-state,.card']];
|
||||
for(const [route,ready] of screens){await page.evaluate(hash=>location.hash=hash,route);try{await page.locator(ready).first().waitFor({state:'attached'});}catch(e){t.diagnostic(JSON.stringify({route,text:await page.locator('#content').innerText(),errors}));throw e;}assert.equal(await page.locator('[data-module-retry]').count(),0,route+' module load');}
|
||||
const before=reads.filter(r=>r==='/assistant.js').length;
|
||||
await page.evaluate(()=>location.hash='assistant');await page.locator('#assistant-input').waitFor();
|
||||
assert.equal(reads.filter(r=>r==='/assistant.js').length,before);assert.deepEqual(errors,[]);
|
||||
});
|
||||
|
||||
test('failed route scripts offer retry and an abandoned route cannot mount after a slow dependency',{timeout:60000},async t=>{
|
||||
const {page}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();let fail=true;
|
||||
await page.route('**/health.js?*',route=>fail?route.abort():route.continue());
|
||||
await page.evaluate(()=>location.hash='health');await page.locator('[data-module-retry]').waitFor();fail=false;
|
||||
await page.locator('[data-module-retry]').click();await page.locator('#health-refresh').waitFor();
|
||||
let release;const held=new Promise(resolve=>release=resolve);await page.route('**/assistant.js?*',async route=>{await held;await route.continue();});
|
||||
try{await page.evaluate(()=>location.hash='assistant');await page.waitForFunction(()=>document.querySelector('#view-title')?.textContent==='DSH 助手');await page.evaluate(()=>location.hash='overview');await page.locator('[data-business-home]').waitFor();}finally{release();}
|
||||
await page.waitForTimeout(200);assert.equal(await page.locator('[data-business-home]').count(),1);assert.equal(await page.locator('#assistant-input').count(),0);
|
||||
});
|
||||
|
||||
test('an unopened home can execute while a cold assistant script is stalled',{timeout:60000},async t=>{
|
||||
const {page,base}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();
|
||||
let release;const held=new Promise(resolve=>release=resolve);await page.route('**/assistant.js?*',async route=>{await held;await route.continue();});
|
||||
try{await page.goto('about:blank');await page.goto(base+'/#assistant',{waitUntil:'domcontentloaded'});await page.waitForFunction(()=>document.querySelector('#view-title')?.textContent==='DSH 助手');await page.evaluate(()=>location.hash='overview');await page.locator('[data-business-home]').waitFor();}finally{release();}
|
||||
await page.waitForTimeout(100);assert.equal(await page.locator('#assistant-input').count(),0);
|
||||
});
|
||||
|
||||
test('a lazy script whose bytes differ from the document fingerprint cannot execute',{timeout:60000},async t=>{
|
||||
const {page}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();let corrupt=true;
|
||||
await page.route('**/health.js?*',async route=>{if(!corrupt)return route.continue();const response=await route.fetch();await route.fulfill({response,headers:{...response.headers(),'cache-control':'no-store'},body:(await response.text())+'\nwindow.staleModuleExecuted=true;'});});
|
||||
await page.evaluate(()=>location.hash='health');await page.locator('[data-module-retry]').waitFor();assert.equal(await page.evaluate(()=>window.staleModuleExecuted),undefined);
|
||||
corrupt=false;await page.locator('[data-module-retry]').click();await page.locator('#health-refresh').waitFor({state:'attached'});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm');
|
||||
|
||||
function fixture(){
|
||||
const groups=JSON.parse(fs.readFileSync('web/modules/navigation/module-manifest.json','utf8')),urls=Object.fromEntries(Object.values(groups).flat().filter(file=>!file.startsWith('$')).map(file=>['/'+file,'/'+file+'?v='+'a'.repeat(64)]));
|
||||
const appended=[],context=vm.createContext({btoa,document:{querySelector:()=>({content:JSON.stringify({groups,urls})}),head:{appendChild(script){if(script.tagName!=='script')return;appended.push(script.src.split('?')[0]);queueMicrotask(()=>script.onload());}},createElement(tagName){return {tagName,remove(){}};}},window:{}});
|
||||
vm.runInContext(fs.readFileSync('web/modules/navigation/module-loader.js','utf8'),context);
|
||||
return {context,appended};
|
||||
}
|
||||
|
||||
test('route loader requests only the selected page group and deduplicates dependencies',async()=>{
|
||||
const f=fixture();
|
||||
await f.context.window.AppModules.load('overview');
|
||||
const first=[...f.appended];
|
||||
assert.ok(first.includes('/order-notifications.js'));
|
||||
assert.ok(first.includes('/business-home.js'));
|
||||
assert.equal(first.includes('/assistant.js'),false);
|
||||
await f.context.window.AppModules.load('overview');
|
||||
assert.deepEqual(f.appended,first);
|
||||
});
|
||||
|
||||
test('route loader keeps shared modules before route modules and reports script failures',async()=>{
|
||||
const f=fixture();await f.context.window.AppModules.load('assistant');
|
||||
const modules=f.appended;
|
||||
assert.ok(modules.indexOf('/assistant-operations.js')<modules.indexOf('/assistant.js'));
|
||||
const bad=fixture();bad.context.document.head.appendChild=script=>{if(script.tagName==='script')queueMicrotask(()=>script.onerror(new Error('missing')));};
|
||||
await assert.rejects(bad.context.window.AppModules.load('assistant'),/无法加载页面资源/);
|
||||
});
|
||||
|
||||
test('failed modules can be retried without executing successful dependencies twice',async()=>{
|
||||
const f=fixture();let fail=true;
|
||||
f.context.document.head.appendChild=script=>{if(script.tagName!=='script')return;f.appended.push(script.src.split('?')[0]);queueMicrotask(()=>fail&&script.src.startsWith('/assistant.js')?script.onerror():script.onload());};
|
||||
await assert.rejects(f.context.window.AppModules.load('assistant'),/无法加载页面资源/);fail=false;
|
||||
await f.context.window.AppModules.load('assistant');
|
||||
assert.equal(f.appended.filter(src=>src==='/assistant.js').length,2);assert.equal(f.appended.filter(src=>src==='/assistant-operations.js').length,1);
|
||||
});
|
||||
Reference in new issue
Block a user