perf: load page modules on demand and avoid repeated startup ACL writes

This commit is contained in:
abaishu0730 committed 2026-10-28 15:20:28 +08:00
1 parent 73773f9526
commit 7ead1e7cb7
19 files changed
+330 -24

No files matched your search

+11 -1
View File
@@ -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('&quot;','"').replaceAll('&lt;','<').replaceAll('&gt;','>').replaceAll('&amp;','&'));
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{}');
+46
View File
@@ -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'});
});
+36
View File
@@ -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);
});
+43
View File
@@ -0,0 +1,43 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),cp=require('node:child_process');
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
test('native ACL policy accepts only the current owner and one protected inheritable full-control allow rule',{skip:process.platform!=='win32'},()=>{
const {privateDirectoryAcl}=require('../../src/platform/security/windows-directory.cjs');
const cases=`
$sid=[System.Security.Principal.WindowsIdentity]::GetCurrent().User
function Make-Acl($protected,$owner,$rights,$inherit,$propagation,$type,$identity) {
$acl=New-Object System.Security.AccessControl.DirectorySecurity
$acl.SetOwner($owner);$acl.SetAccessRuleProtection($protected,$false)
$rule=New-Object System.Security.AccessControl.FileSystemAccessRule($identity,$rights,$inherit,$propagation,$type)
$acl.AddAccessRule($rule);return $acl
}
$other=New-Object System.Security.Principal.SecurityIdentifier('S-1-1-0')
$rows=@(
(Test-PrivateDirectoryAcl (Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid) $sid),
(Test-PrivateDirectoryAcl (Make-Acl $false $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid) $sid),
(Test-PrivateDirectoryAcl (Make-Acl $true $other 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid) $sid),
(Test-PrivateDirectoryAcl (Make-Acl $true $sid 'Read' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid) $sid),
(Test-PrivateDirectoryAcl (Make-Acl $true $sid 'FullControl' 'None' 'None' 'Allow' $sid) $sid),
(Test-PrivateDirectoryAcl (Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'InheritOnly' 'Allow' $sid) $sid),
(Test-PrivateDirectoryAcl (Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Deny' $sid) $sid),
(Test-PrivateDirectoryAcl (Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $other) $sid)
)
$extra=Make-Acl $true $sid 'FullControl' 'ContainerInherit,ObjectInherit' 'None' 'Allow' $sid
$extra.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($other,'Read','ContainerInherit,ObjectInherit','None','Allow')))
$rows+=(Test-PrivateDirectoryAcl $extra $sid)
ConvertTo-Json -Compress -InputObject $rows
`;
const output=cp.execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command','$ErrorActionPreference="Stop";'+privateDirectoryAcl+cases],{encoding:'utf8',windowsHide:true,timeout:15000});
assert.deepEqual(JSON.parse(output),[true,false,false,false,false,false,false,false,false]);
});
test('a compliant real directory is not rewritten and an unprotected directory is repaired',{skip:process.platform!=='win32'},t=>{
const {privateDirectoryAcl,secureDirectoryScript}=require('../../src/platform/security/windows-directory.cjs'),parent=path.resolve(os.tmpdir()),dir=fs.mkdtempSync(path.join(parent,'acl-policy-'));
assert.equal(path.dirname(dir),parent);t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
const run=script=>cp.execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command','$ErrorActionPreference="Stop";'+script],{input:dir,encoding:'utf8',windowsHide:true,timeout:15000}).trim();
run(secureDirectoryScript);const protectedAt=fs.statSync(dir,{bigint:true}).ctimeNs;run(secureDirectoryScript);assert.equal(fs.statSync(dir,{bigint:true}).ctimeNs,protectedAt,'read verification must not rewrite the DACL');
run('$p=[Console]::In.ReadToEnd();$acl=[IO.Directory]::GetAccessControl($p);$acl.SetAccessRuleProtection($false,$true);[IO.Directory]::SetAccessControl($p,$acl)');
run(secureDirectoryScript);
const verified=run(privateDirectoryAcl+';$p=[Console]::In.ReadToEnd();Test-PrivateDirectoryAcl ([IO.Directory]::GetAccessControl($p)) ([System.Security.Principal.WindowsIdentity]::GetCurrent().User)');assert.equal(verified,'True');
});
+13
View File
@@ -0,0 +1,13 @@
'use strict';
const fs=require('node:fs'),http=require('node:http');
const {respondToPing}=require('../../src/platform/service/ping.cjs');
const file=process.env.ORDER_FIXTURE_COUNT;
fs.writeFileSync(file,String((fs.existsSync(file)?Number(fs.readFileSync(file,'utf8')):0)+1));
if(!fs.existsSync(file+'.ready')){
process.send({type:'order:startup-failed',diagnostic:{type:'Error',stage:'key_directory',code:'STORAGE_UNAVAILABLE',causeCode:'ETIMEDOUT',durationMs:30000,message:'SECRET_FIXTURE_NOT_FOR_STATE'}});
process.exitCode=1;
}else{
const server=http.createServer((request,response)=>respondToPing(request,response,{token:process.env.ORDER_SUPERVISOR_TOKEN,instanceId:process.env.ORDER_SUPERVISOR_INSTANCE,startedAt:new Date().toISOString()}));
server.listen(Number(process.env.ORDER_FIXTURE_PORT),'127.0.0.1');
process.on('message',message=>{if(message==='order:shutdown'){server.closeAllConnections();server.close(()=>process.exit(0));}});
}
+12 -1
View File
@@ -53,5 +53,16 @@ test('unknown port owners remain running, and repeated real exits enter cooldown
guard=new ServiceSupervisor({stateDir,entry:path.resolve('tests/fixtures/managed-service.cjs'),ports:[listenPort],env:{ORDER_FIXTURE_PORT:String(listenPort),ORDER_FIXTURE_COUNT:path.join(stateDir,'count'),ORDER_FIXTURE_ALWAYS_CRASH:'1'},timing:{intervalMs:40,pingTimeoutMs:50,startupGraceMs:1000,backoffMs:[30],maxRestarts:1,cooldownMs:1000,windowMs:30000,stopGraceMs:500}});await guard.start();await until(()=>guard.snapshot().status==='cooldown');assert.ok(guard.snapshot().nextRestartAt);await guard.stop();
});
test('restart backoff is bounded and repeated failures enter a cooldown',()=>{
const {restartPlan}=require('../../src/platform/service/supervisor.cjs');assert.deepEqual([0,1,2,20].map(failures=>restartPlan({failures,recent:0}).delayMs),[2000,5000,10000,60000]);assert.equal(restartPlan({failures:9,recent:8}).cooldown,true);assert.equal(restartPlan({failures:9,recent:8}).delayMs,300000);
const {restartPlan}=require('../../src/platform/service/supervisor.cjs');assert.deepEqual([0,1,2,20].map(failures=>restartPlan({failures,recent:0}).delayMs),[2000,5000,10000,60000]);assert.equal(restartPlan({failures:9,recent:8}).cooldown,true);assert.equal(restartPlan({failures:9,recent:8}).delayMs,300000);assert.equal(restartPlan({failures:0,recent:0,startupFailures:3}).cooldown,true);
});
test('three failed startups retain safe diagnostics and enter cooldown, then explicit retry can recover',{timeout:30000},async t=>{
const {ServiceSupervisor}=require('../../src/platform/service/supervisor.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'startup-cooldown-')),listenPort=await port(),count=path.join(stateDir,'count');let guard;
t.after(async()=>{await guard?.stop();await fs.rm(stateDir,{recursive:true,force:true});});
guard=new ServiceSupervisor({stateDir,entry:path.resolve('tests/fixtures/startup-failure-service.cjs'),ports:[listenPort],env:{ORDER_FIXTURE_PORT:String(listenPort),ORDER_FIXTURE_COUNT:count},timing:{intervalMs:30,pingTimeoutMs:60,startupGraceMs:500,stopGraceMs:1000,backoffMs:[20],cooldownMs:5000,maxRestarts:99}});
await guard.start();await until(()=>guard.snapshot().status==='cooldown');
assert.equal(await fs.readFile(count,'utf8'),'3');assert.equal(guard.snapshot().consecutiveStartupFailures,3);
assert.equal(guard.snapshot().reason,'startup_failed');assert.equal(guard.snapshot().startupError.stage,'key_directory');assert.equal(guard.snapshot().startupError.causeCode,'ETIMEDOUT');assert.doesNotMatch(JSON.stringify(guard.snapshot()),/SECRET/);
await fs.writeFile(count+'.ready','ready');await guard.restart();await until(()=>guard.snapshot().status==='running');
assert.equal(guard.snapshot().consecutiveStartupFailures,0);assert.equal(guard.snapshot().startupError,null);
});