diff --git a/docs/startup-stability-2026-10-28.md b/docs/startup-stability-2026-10-28.md new file mode 100644 index 0000000..8993864 --- /dev/null +++ b/docs/startup-stability-2026-10-28.md @@ -0,0 +1,40 @@ +# 启动稳定性与首屏加载优化 + +本轮在 `codex/system-update` 继续处理两类资源问题:首次打开工作台加载过多页面脚本,以及 Windows 启动阶段反复拉起已经确定会失败的业务进程。 + +## 路由脚本按需加载 + +`index.html` 只保留 Tabler、导航、生命周期、记录状态、模块加载器和 `app.js`。BPM、邮箱、订单、规则、存储、健康、助手等页面脚本由 `web/modules/navigation/module-loader.js` 在进入对应路由前按组加载,并在同一个工作台文档内复用脚本 Promise。分组及依赖在 `module-manifest.json` 定义;服务端把实际内容指纹写入 HTML 的非执行元数据,延迟资源仍使用原长期缓存。 + +下载通过带完整性校验的 preload 并行,脚本使用 async 独立执行,每个路由按自己的依赖顺序等待;避免某个未完成的助手脚本阻塞新打开的首页。脚本 SRI 由指纹派生,部署切换后旧页面不能执行与其清单不符的新脚本;加载失败提供重试和重新加载工作台入口。CSS 保持公共加载,避免页面切换时出现布局闪烁;业务 API、权限和数据读取顺序保持。 + +加载器 VM 与真实 HTTP 测试覆盖分组选择、重复加载去重、依赖顺序、失败重试、核心资源预算和延迟资源的指纹缓存。浏览器专项覆盖 18 个页面入口、冷助手脚本卡住后切到未加载首页、离页旧结果不能挂载、资源字节被替换时不执行及重试恢复。用例只使用隔离账号、合成数据与本机服务。 + +相同隔离 HTTP 与首页合成响应、Chromium、每个版本 3 个新浏览器上下文,取中位数: + +| 场景 | 基线 `73773f9` | 本轮 | +| --- | ---: | ---: | +| 冷首页静态资源网络请求 | 44 | 13 | +| 冷首页静态响应正文(压缩后) | 299130 B | 169652 B | +| 冷首页 HTML 正文(压缩后) | 2267 B | 3056 B | +| 冷首页就绪耗时 | 589.7 ms | 399.0 ms | +| 重复刷新静态请求 / 正文 | 0 / 0 B | 0 / 0 B | +| 重复刷新首页就绪耗时 | 180.7 ms | 183.5 ms | + +延迟资源元数据增加了少量 HTML 字节,换取冷打开约 43% 的静态正文减少。重复刷新耗时基本相当,未声称继续加速。上述是本机合成 API 与固定页面的测量,不代表生产网络、CPU、内存或真实 BPM/SMB 的 SLA。脚本及聚合原始结果保存在忽略目录 `output/lazy-startup-20261028/`,未提交业务数据库或凭据。 + +## 启动失败冷却 + +监督器把“子进程尚未通过第一次健康检查就退出”记录为 `startupFailure`,本次守护运行内连续 3 次启动失败后进入已有 5 分钟冷却窗口;健康检查成功会清零该计数,人工重启也会清零。子进程通过现有 IPC 传递安全启动诊断,守护进程再次过滤字段,仅持久化阶段、错误代码与耗时,不接受原始消息或堆栈。 + +普通运行期间的健康超时继续使用原有失败阈值和退避。冷却只减少重复启动和 Windows ACL/DPAPI 超时造成的资源浪费,不跳过端口检查、健康检查或加密目录保护。`restartCount` 是跨守护启动保留的历史累计数,不能据此推断本次启动发生同样次数的故障。 + +专项监督器测试覆盖启动失败冷却、普通崩溃恢复、健康超时、端口变化和手动停止。旧服务配置与加密数据格式不变。 + +## 避免重复传播合规 ACL + +完整测试过程中定位到共享键目录已有约 2.2 万个文件,且已经具备正确的受保护 ACL。原逻辑在每个新进程中仍重设目录 ACL,可能重新传播到所有继承权限的子文件。现在先以 SID 读取并核验:DACL 受保护、所有者为当前用户、只有一条当前用户的显式 Allow FullControl 规则,且同时继承给文件和子目录、传播标志为 None;全部匹配才跳过重复写入。任何不一致仍按原策略重新保护,读失败仍报错,路径身份前后核验与 DPAPI 格式不变。 + +真实 Windows/.NET ACL 测试覆盖正确策略、未保护、其他所有者、权限不足、缺少继承、仅继承、Deny、其他用户及额外规则;使用真实目录 ctime 确认合规检查没有重写权限,另验证被取消保护后会修复。最初因初始化超时失败的 Excel 执行业务切片与该策略测试重跑 12/12 通过,未跳过原断言。 + +在含 3000 个合成文件的临时目录中,交替执行每项 3 次、取含 PowerShell 启动的跨进程中位耗时:原强制重写 1142 ms,核验后复用 587 ms。临时目录均已删除,原始聚合数据见忽略的 `output/lazy-startup-20261028/acl-benchmark.json`。这证明减少了一类重复权限写入;没有声称已经消除所有 Windows 超时,也未测量真实服务完整启动耗时。 diff --git a/package.json b/package.json index dc383e6..5a43fa8 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "service:stop": "node scripts/service.cjs stop", "service:restart": "node scripts/service.cjs restart", "test": "npm run test:business", - "test:business": "node --test --test-concurrency=1 tests/app/business-home-ui.test.cjs tests/order-rules/home-summary.test.cjs tests/order-rules/carry-forward-core.test.cjs tests/order-rules/carry-forward-integration.test.cjs tests/order-rules/dispatch-unsent-proof.test.cjs tests/order-rules/dismiss-task.test.cjs tests/app/carry-dismiss-ui.test.cjs tests/workspace/business-issues.test.cjs tests/mail/unified-account.test.cjs tests/mail/unified-account-ui.test.cjs tests/assistant/assistant.test.cjs tests/assistant/assistant-http-ui.test.cjs tests/assistant/controlled-operations.test.cjs tests/assistant/dsh-runtime.test.cjs tests/assistant/dsh-runtime-installer.test.cjs tests/assistant/repair-runner.test.cjs tests/app/automatic-pdf-ledger.test.cjs tests/app/job-records.test.cjs tests/order-rules/version-compatibility.test.cjs tests/bpm-display-policy.test.cjs tests/bpm-dynamicarea.test.cjs tests/bpm-readonly-form.test.cjs tests/bpm-form-contracts.test.cjs tests/bpm-obsolete-display-fields.test.cjs tests/order-rules/snapshot-read-context.test.cjs tests/order-rules/summary.test.cjs tests/order-rules/execution-single-flight.test.cjs tests/order-rules/execution-responsiveness.test.cjs tests/order-rules/readiness-pending-ui.test.cjs tests/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/collecting-batches.test.cjs tests/order-rules/collecting-batches-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs tests/system-update/checker.test.cjs tests/system-update/system-update.test.cjs tests/order-rules/configuration.test.cjs tests/order-rules/configuration-ui.test.cjs tests/order-rules/workbench-ui.test.cjs tests/app/asset-delivery.test.cjs tests/app/authentication-responsiveness.test.cjs tests/app/backend-refresh-performance.test.cjs tests/app/read-refresh-performance.test.cjs tests/app/polling-performance-ui.test.cjs tests/order-rules/query-read-performance.test.cjs tests/mail/history.test.cjs tests/storage/storage-range.test.cjs tests/app/region-revisions.test.cjs tests/app/region-revisions-http.test.cjs tests/app/region-refresh.test.cjs tests/app/region-refresh-ui.test.cjs tests/app/region-selection.test.cjs", + "test:business": "node --test --test-concurrency=1 tests/app/business-home-ui.test.cjs tests/order-rules/home-summary.test.cjs tests/order-rules/carry-forward-core.test.cjs tests/order-rules/carry-forward-integration.test.cjs tests/order-rules/dispatch-unsent-proof.test.cjs tests/order-rules/dismiss-task.test.cjs tests/app/carry-dismiss-ui.test.cjs tests/workspace/business-issues.test.cjs tests/mail/unified-account.test.cjs tests/mail/unified-account-ui.test.cjs tests/assistant/assistant.test.cjs tests/assistant/assistant-http-ui.test.cjs tests/assistant/controlled-operations.test.cjs tests/assistant/dsh-runtime.test.cjs tests/assistant/dsh-runtime-installer.test.cjs tests/assistant/repair-runner.test.cjs tests/app/automatic-pdf-ledger.test.cjs tests/app/job-records.test.cjs tests/order-rules/version-compatibility.test.cjs tests/bpm-display-policy.test.cjs tests/bpm-dynamicarea.test.cjs tests/bpm-readonly-form.test.cjs tests/bpm-form-contracts.test.cjs tests/bpm-obsolete-display-fields.test.cjs tests/order-rules/snapshot-read-context.test.cjs tests/order-rules/summary.test.cjs tests/order-rules/execution-single-flight.test.cjs tests/order-rules/execution-responsiveness.test.cjs tests/order-rules/readiness-pending-ui.test.cjs tests/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/collecting-batches.test.cjs tests/order-rules/collecting-batches-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs tests/system-update/checker.test.cjs tests/system-update/system-update.test.cjs tests/order-rules/configuration.test.cjs tests/order-rules/configuration-ui.test.cjs tests/order-rules/workbench-ui.test.cjs tests/app/asset-delivery.test.cjs tests/app/authentication-responsiveness.test.cjs tests/app/backend-refresh-performance.test.cjs tests/app/read-refresh-performance.test.cjs tests/app/polling-performance-ui.test.cjs tests/order-rules/query-read-performance.test.cjs tests/mail/history.test.cjs tests/storage/storage-range.test.cjs tests/app/region-revisions.test.cjs tests/app/region-revisions-http.test.cjs tests/app/region-refresh.test.cjs tests/app/region-refresh-ui.test.cjs tests/app/region-selection.test.cjs tests/app/module-loader.test.cjs tests/app/module-loader-ui.test.cjs tests/service/service-supervisor.test.cjs tests/bpm/windows-directory.test.cjs", "test:full": "node --test --test-concurrency=2 \"tests/**/*.test.cjs\"" }, "engines": { diff --git a/src/app/asset-delivery.cjs b/src/app/asset-delivery.cjs index fe9020d..a5f6c4a 100644 --- a/src/app/asset-delivery.cjs +++ b/src/app/asset-delivery.cjs @@ -17,7 +17,7 @@ function requestedFingerprint(request){ } // Only public assets from createAssets enter this bounded cache; APIs and managed // files retain no-store. Stat validation allows an edited installation to update. -function createAssetDelivery({maxBytes=32*1024*1024,resolveAsset}={}){ +function createAssetDelivery({maxBytes=32*1024*1024,resolveAsset,moduleManifest}={}){ const cache=new Map(),pending=new Map();let size=0; let documentValue=null,documentKey=null; const valueFor=(bytes,version)=>{const fingerprint=crypto.createHash('sha256').update(bytes).digest('hex');return {version,bytes,fingerprint,etag:'W/"'+fingerprint+'"',encodings:new Map()};}; @@ -33,10 +33,13 @@ function createAssetDelivery({maxBytes=32*1024*1024,resolveAsset}={}){ } async function documentWithVersions(asset,value){ if(asset.type!=='text/html'||asset.preview||!resolveAsset)return value; - const source=value.bytes.toString('utf8'),urls=[...new Set([...source.matchAll(/(?:src|href)="(\/(?!\/)[^"#]+)"/g)].map(match=>match[1]))]; + const source=value.bytes.toString('utf8'),modules=moduleManifest&&source.includes('')?moduleManifest:null; + const urls=[...new Set([...Array.from(source.matchAll(/(?:src|href)="(\/(?!\/)[^"#]+)"/g),match=>match[1]),...Object.values(modules||{}).flat().filter(route=>!route.startsWith('$')).map(route=>'/'+route)])]; const versions=await Promise.all(urls.map(async route=>{const url=new URL(route,'http://localhost'),dependency=resolveAsset(url.pathname);if(!dependency||dependency.type==='text/html')return [route,route];const content=await load(dependency);url.searchParams.set('v',content.fingerprint);return [route,url.pathname+url.search];})); - const key=JSON.stringify([asset.path,value.fingerprint,versions]);if(key===documentKey)return documentValue; - const replacements=new Map(versions),bytes=Buffer.from(source.replace(/((?:src|href)=")(\/(?!\/)[^"#]+)(")/g,(_,prefix,route,suffix)=>prefix+(replacements.get(route)||route)+suffix)); + const key=JSON.stringify([asset.path,value.fingerprint,versions,modules]);if(key===documentKey)return documentValue; + const replacements=new Map(versions);let html=source.replace(/((?:src|href)=")(\/(?!\/)[^"#]+)(")/g,(_,prefix,route,suffix)=>prefix+(replacements.get(route)||route)+suffix); + if(modules){const data=JSON.stringify({groups:modules,urls:Object.fromEntries(versions)}).replaceAll('&','&').replaceAll('"','"').replaceAll('<','<').replaceAll('>','>');html=html.replace('',()=>'');} + const bytes=Buffer.from(html); documentKey=key;documentValue=valueFor(bytes,key);return documentValue; } function trim(){while(size>maxBytes&&cache.size){const [key,value]=cache.entries().next().value;size-=value.size;cache.delete(key);}} diff --git a/src/app/assets.cjs b/src/app/assets.cjs index dc82854..502cff9 100644 --- a/src/app/assets.cjs +++ b/src/app/assets.cjs @@ -7,6 +7,7 @@ function createAssets(){ '/app.js':{path:path.join(webRoot,'app.js'),type:'text/javascript'}, '/account.js':{path:path.join(webRoot,'modules/account/view.js'),type:'text/javascript'}, '/page-lifecycle.js':{path:path.join(webRoot,'modules/navigation/lifecycle.js'),type:'text/javascript'}, + '/modules/navigation/module-loader.js':{path:path.join(webRoot,'modules/navigation/module-loader.js'),type:'text/javascript'}, '/navigation.js':{path:path.join(webRoot,'modules/navigation/view.js'),type:'text/javascript'}, '/workspace.js':{path:path.join(webRoot,'modules/workspace/view.js'),type:'text/javascript'}, '/bpm-sync-settings.js':{path:path.join(webRoot,'modules/bpm/sync-settings.js'),type:'text/javascript'}, diff --git a/src/app/dashboard.cjs b/src/app/dashboard.cjs index a6ee590..c5fbcc1 100644 --- a/src/app/dashboard.cjs +++ b/src/app/dashboard.cjs @@ -23,7 +23,7 @@ function createDashboard({store,outputDir,workspace,bpmSessions,bpmMonitor,mail, const bpmLifecycle=workspace?new BpmConnectionLifecycle({workspace,manager:bpmSessions,monitor:bpmMonitor}):null; const auth=createAuth({store,workspace,bpmSessions,bpmMonitor,bpmLifecycle}); let assetFor;try{assetFor=createAssets();}catch(error){auth.close();throw error;} - const deliverAsset=createAssetDelivery({resolveAsset:assetFor}); + const deliverAsset=createAssetDelivery({resolveAsset:assetFor,moduleManifest:require('../../web/modules/navigation/module-manifest.json')}); const regionRevisions=createRegionRevisions({store,workspace,bpmSessions,bpmMonitor,mail,scanner,storage,orderRules,orderExecution,assistant,health}); const server=http.createServer(async(request,response)=>{ if(respondToPing(request,response,watchdog))return; diff --git a/src/platform/security/vault.cjs b/src/platform/security/vault.cjs index 4d2eaf4..b73da9e 100644 --- a/src/platform/security/vault.cjs +++ b/src/platform/security/vault.cjs @@ -5,6 +5,7 @@ const path = require('node:path'); const crypto = require('node:crypto'); const { execFileSync } = require('node:child_process'); const { DatabaseSync } = require('node:sqlite'); +const {secureDirectoryScript}=require('./windows-directory.cjs'); const fail = (cause,stage) => cause?.code==='STORAGE_UNAVAILABLE'&&!stage?cause:Object.assign(new Error('加密存储暂时不可用,请查看系统诊断。',cause?{cause}:undefined), { status: 503,code:'STORAGE_UNAVAILABLE',stage:stage||'db_read' }); const duplicate = () => Object.assign(new Error('该 BPM 账号已开启自动续登,请使用已有连接或先解除原账号托管。'), { status: 409, code: 'BPM_ACCOUNT_DUPLICATE' }); const digest = value => crypto.createHash('sha256').update(value).digest('hex'); @@ -29,7 +30,7 @@ function secureDirectory(dir) { if (process.platform === 'win32') { const key=path.resolve(dir).toLowerCase(),identity=directoryIdentity(dir); if(securedDirectories.get(key)===identity)return; - powershell('$ErrorActionPreference="Stop"; $p=[Console]::In.ReadToEnd(); $s=[System.Security.Principal.WindowsIdentity]::GetCurrent().User; $a=New-Object System.Security.AccessControl.DirectorySecurity; $a.SetAccessRuleProtection($true,$false); $a.SetOwner($s); $r=New-Object System.Security.AccessControl.FileSystemAccessRule($s,"FullControl","ContainerInherit,ObjectInherit","None","Allow"); $a.AddAccessRule($r); [System.IO.Directory]::SetAccessControl($p,$a)', dir); + powershell(secureDirectoryScript, dir); if(directoryIdentity(dir)!==identity)throw Object.assign(Error('Storage directory changed during protection'),{code:'ESTORAGECHANGED'}); securedDirectories.set(key,identity);if(securedDirectories.size>512)securedDirectories.delete(securedDirectories.keys().next().value); } else fs.chmodSync(dir, 0o700); diff --git a/src/platform/security/windows-directory.cjs b/src/platform/security/windows-directory.cjs new file mode 100644 index 0000000..6964da0 --- /dev/null +++ b/src/platform/security/windows-directory.cjs @@ -0,0 +1,26 @@ +'use strict'; +// Read SIDs directly: do not resolve account names or weaken an existing policy. +const privateDirectoryAcl=String.raw` +function Test-PrivateDirectoryAcl($acl,$sid) { + if(-not $acl.AreAccessRulesProtected -or -not $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Equals($sid)){return $false} + $rules=$acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier]) + if($rules.Count -ne 1){return $false} + $rule=$rules[0] + return (-not $rule.IsInherited -and $rule.IdentityReference.Equals($sid) -and $rule.FileSystemRights -eq [System.Security.AccessControl.FileSystemRights]::FullControl -and $rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and $rule.InheritanceFlags -eq [System.Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit' -and $rule.PropagationFlags -eq [System.Security.AccessControl.PropagationFlags]::None) +} +`; +const secureDirectoryScript=privateDirectoryAcl+String.raw` +$ErrorActionPreference="Stop" +$p=[Console]::In.ReadToEnd() +$s=[System.Security.Principal.WindowsIdentity]::GetCurrent().User +$current=[System.IO.Directory]::GetAccessControl($p) +if(-not (Test-PrivateDirectoryAcl $current $s)){ + $a=New-Object System.Security.AccessControl.DirectorySecurity + $a.SetAccessRuleProtection($true,$false) + $a.SetOwner($s) + $r=New-Object System.Security.AccessControl.FileSystemAccessRule($s,"FullControl","ContainerInherit,ObjectInherit","None","Allow") + $a.AddAccessRule($r) + [System.IO.Directory]::SetAccessControl($p,$a) +} +`; +module.exports={privateDirectoryAcl,secureDirectoryScript}; diff --git a/src/platform/service/supervisor.cjs b/src/platform/service/supervisor.cjs index 33efac1..1f7bd8e 100644 --- a/src/platform/service/supervisor.cjs +++ b/src/platform/service/supervisor.cjs @@ -1,11 +1,12 @@ 'use strict'; const fs=require('node:fs'),path=require('node:path'),net=require('node:net'),crypto=require('node:crypto'),{spawn,execFile}=require('node:child_process'),{promisify}=require('node:util'); const {SupervisorStore}=require('./store.cjs'),{controlAddress}=require('./control.cjs'),{checkPing,sameToken}=require('./ping.cjs'); -const execFileAsync=promisify(execFile),DEFAULTS={intervalMs:10000,pingTimeoutMs:5000,startupGraceMs:120000,failureThreshold:4,stopGraceMs:15000,backoffMs:[2000,5000,10000,30000,60000],windowMs:900000,maxRestarts:8,cooldownMs:300000}; -function restartPlan({failures=0,recent=0,...options}={}){const t={...DEFAULTS,...options},cooldown=recent>=t.maxRestarts;return {cooldown,delayMs:cooldown?t.cooldownMs:t.backoffMs[Math.min(failures,t.backoffMs.length-1)]};} +const {safeDiagnostic}=require('../../shared/diagnostics.cjs'); +const execFileAsync=promisify(execFile),DEFAULTS={intervalMs:10000,pingTimeoutMs:5000,startupGraceMs:120000,failureThreshold:4,stopGraceMs:15000,backoffMs:[2000,5000,10000,30000,60000],windowMs:900000,maxRestarts:8,cooldownMs:300000,startupFailureThreshold:3}; +function restartPlan({failures=0,recent=0,startupFailures=0,...options}={}){const t={...DEFAULTS,...options},cooldown=recent>=t.maxRestarts||startupFailures>=t.startupFailureThreshold;return {cooldown,delayMs:cooldown?t.cooldownMs:t.backoffMs[Math.min(failures,t.backoffMs.length-1)]};} async function portsAvailable(ports){for(const port of ports){const server=net.createServer();await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(port,'127.0.0.1',resolve);});await new Promise(r=>server.close(r));}} class ServiceSupervisor { - constructor({stateDir,entry=path.join(require('../../shared/paths.cjs').PROJECT_ROOT,'src/server.cjs'),ports=[18765,18766],portsProvider,env={},timing={}}){Object.assign(this,{stateDir:path.resolve(stateDir),entry:path.resolve(entry),ports,portsProvider,env});this.timing={...DEFAULTS,...timing};this.state={};this.restarts=[];this.failures=0;this.stopping=false;this.started=false;} + constructor({stateDir,entry=path.join(require('../../shared/paths.cjs').PROJECT_ROOT,'src/server.cjs'),ports=[18765,18766],portsProvider,env={},timing={}}){Object.assign(this,{stateDir:path.resolve(stateDir),entry:path.resolve(entry),ports,portsProvider,env});this.timing={...DEFAULTS,...timing};this.state={};this.restarts=[];this.failures=0;this.startupFailures=0;this.ready=false;this.stopping=false;this.started=false;} snapshot(){return {...this.state};} update(patch){Object.assign(this.state,patch,{updatedAt:new Date().toISOString()});this.store.set('state',this.state);} async start(){ @@ -43,18 +44,24 @@ class ServiceSupervisor { await portsAvailable(ports);if(this.stopping)return;this.ports=[...ports];this.misses=0;this.spawnedAt=Date.now();const instanceId=crypto.randomUUID(),heartbeatToken=crypto.randomBytes(32).toString('hex'),logFile=path.join(this.store.dir,'service.log');this.rotateLog(); const fd=fs.openSync(logFile,'a',0o600);let child; try{child=spawn(process.execPath,[this.entry],{cwd:require('../../shared/paths.cjs').PROJECT_ROOT,env:{...process.env,...this.env,ORDER_SUPERVISOR_TOKEN:heartbeatToken,ORDER_SUPERVISOR_INSTANCE:instanceId},windowsHide:true,shell:false,stdio:['ignore',fd,fd,'ipc']});}finally{fs.closeSync(fd);} - this.child=child;this.instanceId=instanceId;this.heartbeatToken=heartbeatToken;this.childClosed=new Promise(resolve=>{this.resolveClosed=resolve;}); - this.update({status:'starting',childPid:child.pid||null,childInstanceId:instanceId,childStartedAt:new Date().toISOString(),heartbeatAt:null,nextRestartAt:null}); + this.child=child;this.instanceId=instanceId;this.heartbeatToken=heartbeatToken;this.ready=false;this.startupError=null;this.childClosed=new Promise(resolve=>{this.resolveClosed=resolve;}); + this.update({status:'starting',childPid:child.pid||null,childInstanceId:instanceId,childStartedAt:new Date().toISOString(),heartbeatAt:null,nextRestartAt:null,startupError:null,consecutiveStartupFailures:this.startupFailures}); + child.on('message',message=>{ + if(this.child!==child||this.ready||message?.type!=='order:startup-failed'||!message.diagnostic||typeof message.diagnostic!=='object'||Array.isArray(message.diagnostic))return; + const d=message.diagnostic;this.startupError=safeDiagnostic({name:d.type,stage:d.stage,code:d.code,cause:{code:d.causeCode}},{durationMs:d.durationMs}); + this.update({startupError:this.startupError});this.store.event('startup_failed',this.startupError); + }); child.on('error',()=>{this.store?.event('spawn_failed');}); child.once('close',(code,signal)=>{const resolve=this.resolveClosed;resolve?.();if(this.child!==child)return;this.child=null; if(this.stopping||this.manualRestart)return; - this.store.event('child_exit',{code,signal:signal||null});this.update({childPid:null,lastExitAt:new Date().toISOString(),lastExitCode:code,reason:this.exitReason||'unexpected_exit'});this.exitReason=null;this.scheduleRestart(); + const startupFailure=!this.ready;this.store.event('child_exit',{code,signal:signal||null,startupFailure});this.update({childPid:null,lastExitAt:new Date().toISOString(),lastExitCode:code,reason:this.exitReason||(this.startupError?'startup_failed':'unexpected_exit'),startupFailure});this.exitReason=null;this.scheduleRestart({startupFailure}); }); } - scheduleRestart(){ + scheduleRestart({startupFailure=false}={}){ if(this.stopping)return;clearTimeout(this.restartTimer);const now=Date.now();this.restarts=this.restarts.filter(t=>now-t{if(this.stopping)return;this.restarts.push(Date.now());this.update({restartCount:this.state.restartCount+1});this.launch().catch(()=>{this.update({reason:'spawn_failed'});this.scheduleRestart();});},plan.delayMs); } async tick(){ @@ -64,7 +71,7 @@ class ServiceSupervisor { const child=this.child,instanceId=this.instanceId,token=this.heartbeatToken; const results=await Promise.allSettled(this.ports.map(port=>checkPing(port,{token,instanceId,timeout:this.timing.pingTimeoutMs}))); if(this.stopping||this.child!==child||this.manualRestart)return; - if(results.every(r=>r.status==='fulfilled')){this.misses=0;if(Date.now()-this.spawnedAt>300000)this.failures=0;this.update({status:'running',heartbeatAt:new Date().toISOString(),reason:'healthy'});return;} + if(results.every(r=>r.status==='fulfilled')){this.misses=0;this.ready=true;this.startupFailures=0;this.startupError=null;if(Date.now()-this.spawnedAt>300000)this.failures=0;this.update({status:'running',heartbeatAt:new Date().toISOString(),reason:'healthy',startupFailure:false,startupError:null,consecutiveStartupFailures:0});return;} this.update({});if(this.state.status==='starting'&&Date.now()-this.spawnedAt{ process.once('SIGINT',stop);process.once('SIGTERM',stop); process.on('message',message=>{if(message==='order:shutdown')stop();}); console.info('启动耗时(ms):'+Math.round(performance.now()-startupAt)); -}).catch(error => { console.error('启动失败:'+JSON.stringify(safeDiagnostic(error,{durationMs:performance.now()-startupAt}))); process.exitCode=1; }); +}).catch(error => { const diagnostic=safeDiagnostic(error,{durationMs:performance.now()-startupAt});console.error('启动失败:'+JSON.stringify(diagnostic));if(process.connected)try{process.send({type:'order:startup-failed',diagnostic},()=>{});}catch{}process.exitCode=1; }); module.exports = { createServer, startService, main }; diff --git a/tests/app/asset-delivery.test.cjs b/tests/app/asset-delivery.test.cjs index 4d58a49..a7a21d6 100644 --- a/tests/app/asset-delivery.test.cjs +++ b/tests/app/asset-delivery.test.cjs @@ -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=/').replaceAll('&','&')); + for(const route of ['/assistant.js','/business-home.js','/order-rules.js']){ + assert.ok(manifest.urls[route]);assert.equal(html.includes('');fs.writeFileSync(one,'old()');fs.writeFileSync(two,'body{}'); diff --git a/tests/app/module-loader-ui.test.cjs b/tests/app/module-loader-ui.test.cjs new file mode 100644 index 0000000..c0607f8 --- /dev/null +++ b/tests/app/module-loader-ui.test.cjs @@ -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'}); +}); diff --git a/tests/app/module-loader.test.cjs b/tests/app/module-loader.test.cjs new file mode 100644 index 0000000..69a9f42 --- /dev/null +++ b/tests/app/module-loader.test.cjs @@ -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'){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); +}); diff --git a/tests/bpm/windows-directory.test.cjs b/tests/bpm/windows-directory.test.cjs new file mode 100644 index 0000000..bd99108 --- /dev/null +++ b/tests/bpm/windows-directory.test.cjs @@ -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'); +}); diff --git a/tests/fixtures/startup-failure-service.cjs b/tests/fixtures/startup-failure-service.cjs new file mode 100644 index 0000000..d9c75e4 --- /dev/null +++ b/tests/fixtures/startup-failure-service.cjs @@ -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));}}); +} diff --git a/tests/service/service-supervisor.test.cjs b/tests/service/service-supervisor.test.cjs index 04f989d..db34159 100644 --- a/tests/service/service-supervisor.test.cjs +++ b/tests/service/service-supervisor.test.cjs @@ -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); }); diff --git a/web/app.js b/web/app.js index c3be195..22579dc 100644 --- a/web/app.js +++ b/web/app.js @@ -174,6 +174,7 @@ async function renderView() { document.querySelector('#view-title').textContent=views[currentView][0];document.querySelector('#view-description').textContent=views[currentView][1]; const container=document.querySelector('#content');if(!(wasRecord&&['records','records-pdf'].includes(currentView)))container.innerHTML='
正在加载…
'; + try{await window.AppModules.load(currentView);if(!isActive())return;configureLoadedViews();}catch(error){if(isActive()){container.innerHTML=``;container.querySelector('[data-module-retry]').onclick=()=>renderView();container.querySelector('[data-module-reload]').onclick=()=>location.reload();}return;} const notificationSections={'order-notifications':'workbench','notification-execution':'execution','notification-orders':'orders','notification-batches':'pending','notification-history':'history','notification-settings':'settings'}; const fn={'rule-fields':(host,active)=>window.OrderRuleViews.render(host,active,'fields'),...Object.fromEntries(Object.entries(notificationSections).map(([route,section])=>[route,(host,active)=>window.OrderNotificationViews.render(host,active,section)])),'assistant-settings':window.AssistantViews?.settings,account:window.AccountViews?.account,'order-rules':window.OrderRuleViews?.render,health:window.HealthViews?.render,assistant:window.AssistantViews?.render,storage:window.StorageViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,records:viewRecords,'records-pdf':viewPdfRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,users:window.AccountViews?.users,audit:viewAudit,rules:viewRules}[currentView]; void refreshTimer?.run().catch(()=>{}); @@ -186,7 +187,8 @@ async function authScreen() { } async function passwordChanged(actorId){if(currentUser&¤tUser.id!==actorId)return false;currentUser=null;++viewGeneration;refreshTimer?.dispose();await window.PageLifecycle?.dispose();await window.BpmLogin?.dispose().catch(()=>{});await boot();return true;} -function enter(){window.PageLifecycle.configureRegions({read:(signal,region)=>api('/refresh/revisions?regions='+encodeURIComponent(region),undefined,{signal}),user:()=>currentUser});window.RecordState.configure(currentUser,({hash,push})=>{if(push&&location.hash!==hash)history.pushState({appIndex:++historyIndex},'',hash);else history.replaceState({...history.state,appIndex:historyIndex},'',hash);});window.PdfRecordViews?.configure({api,esc,formatDate,notify,user:currentUser});window.AccountViews?.configure({api,esc,formatDate,notify,user:currentUser,onPasswordChanged:passwordChanged});window.OrderRuleViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderNotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.HealthViews?.configure({api,esc,formatDate,user:currentUser});window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();refreshTimer?.dispose();const statusUser=currentUser;refreshTimer=window.PageLifecycle.regionPoll('orderRules',{refresh:signal=>updateAutomationStatus(()=>currentUser===statusUser,{signal}),onError:error=>{const node=document.querySelector('#automation-status');if(node&¤tUser===statusUser){node.textContent='通知状态待确认';node.className='badge bg-yellow-lt text-decoration-none';node.title=error.message+';请刷新重试。';}}},15000,{isActive:()=>!!currentUser&¤tUser===statusUser,owned:false});renderView();void checkSystemUpdate(()=>!!currentUser);} +function configureLoadedViews(){window.PdfRecordViews?.configure({api,esc,formatDate,notify,user:currentUser});window.AccountViews?.configure({api,esc,formatDate,notify,user:currentUser,onPasswordChanged:passwordChanged});window.OrderRuleViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderNotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.HealthViews?.configure({api,esc,formatDate,user:currentUser});window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});} +function enter(){window.PageLifecycle.configureRegions({read:(signal,region)=>api('/refresh/revisions?regions='+encodeURIComponent(region),undefined,{signal}),user:()=>currentUser});window.RecordState.configure(currentUser,({hash,push})=>{if(push&&location.hash!==hash)history.pushState({appIndex:++historyIndex},'',hash);else history.replaceState({...history.state,appIndex:historyIndex},'',hash);});configureLoadedViews();shell();refreshTimer?.dispose();const statusUser=currentUser;refreshTimer=window.PageLifecycle.regionPoll('orderRules',{refresh:signal=>updateAutomationStatus(()=>currentUser===statusUser,{signal}),onError:error=>{const node=document.querySelector('#automation-status');if(node&¤tUser===statusUser){node.textContent='通知状态待确认';node.className='badge bg-yellow-lt text-decoration-none';node.title=error.message+';请刷新重试。';}}},15000,{isActive:()=>!!currentUser&¤tUser===statusUser,owned:false});renderView();void checkSystemUpdate(()=>!!currentUser);} async function boot(){try{currentUser=(await api('/me')).user;enter();}catch{await authScreen();}} window.addEventListener('page-operation-error',event=>notify(event.detail.message,'danger')); window.addEventListener('pagehide',()=>{window.BpmLogin?.dispose({unload:true});}); diff --git a/web/index.html b/web/index.html index 71c0580..3f5ffc9 100644 --- a/web/index.html +++ b/web/index.html @@ -1,3 +1,3 @@ -订单通知中心 -
正在连接订单通知中心…
+订单通知中心 +
正在连接订单通知中心…
diff --git a/web/modules/navigation/module-loader.js b/web/modules/navigation/module-loader.js new file mode 100644 index 0000000..74d08ea --- /dev/null +++ b/web/modules/navigation/module-loader.js @@ -0,0 +1,40 @@ +'use strict'; +window.AppModules=(()=>{ + const manifest=JSON.parse(document.querySelector('meta[name="app-modules"]')?.content||'{}'); + const groups=manifest.groups||{},urls=manifest.urls||{},loaded=new Map(),preloads=new Map(); + function assetFor(route){ + const src=urls['/'+route]; + if(typeof src!=='string'||!/^\/(?!\/)[\w./-]+\.js\?v=[a-f0-9]{64}$/.test(src))throw Error('页面资源版本无效,请重新加载工作台。'); + const hash=src.slice(src.lastIndexOf('=')+1),integrity='sha256-'+btoa(String.fromCharCode(...hash.match(/../g).map(byte=>parseInt(byte,16)))); + return {src,integrity}; + } + function preload(asset){ + if(loaded.has(asset.src)||preloads.has(asset.src))return; + const link=document.createElement('link');link.rel='preload';link.as='script';link.href=asset.src;link.integrity=asset.integrity;link.crossOrigin='anonymous';preloads.set(asset.src,link);document.head.appendChild(link); + } + function loadOne(route,asset){ + const {src,integrity}=asset; + if(loaded.has(src))return loaded.get(src); + const script=document.createElement('script');script.async=true;script.src=src;script.integrity=integrity;script.crossOrigin='anonymous'; + const promise=new Promise((resolve,reject)=>{script.onload=resolve;script.onerror=()=>reject(Error('无法加载页面资源:/'+route));}); + loaded.set(src,promise); + document.head.appendChild(script); + promise.catch(()=>{if(loaded.get(src)===promise){loaded.delete(src);script.remove();}}); + const cleanup=()=>{preloads.get(src)?.remove();preloads.delete(src);};promise.then(cleanup,cleanup); + return promise; + } + function filesFor(route,parents=new Set()){ + if(parents.has(route)||!Object.hasOwn(groups,route))throw Error('页面模块配置无效,请重新加载工作台。'); + const next=new Set(parents).add(route); + return groups[route].flatMap(item=>item.startsWith('$')?filesFor(item,next):[item]); + } + async function load(route){ + const files=[...new Set(filesFor(route))].map(file=>({file,asset:assetFor(file)})); + // Download dependencies together, but execute only this route's sequence. + // A stalled script from an abandoned route cannot block another route. + for(const {asset} of files)preload(asset); + try{for(const {file,asset} of files)await loadOne(file,asset);} + finally{for(const {asset} of files){preloads.get(asset.src)?.remove();preloads.delete(asset.src);}} + } + return {load}; +})(); diff --git a/web/modules/navigation/module-manifest.json b/web/modules/navigation/module-manifest.json new file mode 100644 index 0000000..ccb6f54 --- /dev/null +++ b/web/modules/navigation/module-manifest.json @@ -0,0 +1,27 @@ +{ + "$records": ["record-ui.js", "record-table.js"], + "$business": ["$records", "order-notifications-shared.js", "mail-template-editor.js", "modules/order-notifications/batch-editor.js", "modules/order-notifications/detail.js", "modules/order-notifications/records.js", "order-notifications.js"], + "$mail": ["mail-history.js", "mail-template-editor.js", "mail.js"], + "$rules": ["vendor/tom-select.js", "order-notifications-shared.js", "field-sample-picker.js", "field-recognition-panel.js", "order-rules-scopes.js", "order-rules-resources.js", "order-rules-import.js", "order-rules-editor.js", "order-rules-preview.js", "field-mappings.js", "order-execution.js", "order-rules.js"], + "overview": ["business-home.js", "order-notifications.js"], + "notification-orders": ["$business"], + "notification-batches": ["$business"], + "notification-settings": ["order-notifications.js"], + "assistant": ["assistant-operations.js", "assistant.js"], + "assistant-settings": ["assistant-operations.js", "assistant.js"], + "bpm": ["workspace.js", "bpm-sync-settings.js", "bpm.js"], + "mail": ["$mail"], + "storage": ["storage-preview-host.js", "storage.js"], + "records": ["$records", "orders.js", "notifications.js"], + "records-pdf": ["$records", "pdf-records.js", "notifications.js"], + "rule-fields": ["$rules"], + "order-rules": ["$rules"], + "schedule": [], + "templates": ["$mail"], + "calendar": ["workspace.js"], + "exceptions": ["workspace.js"], + "audit": ["workspace.js"], + "users": ["account.js"], + "account": ["account.js"], + "health": ["health.js"] +}