'use strict'; const fs=require('node:fs'),path=require('node:path'),{DatabaseSync}=require('node:sqlite'),{readSupervisor}=require('../../platform/service/control.cjs'),{redact}=require('../../shared/redact.cjs'); const {monitorEventLoopDelay}=require('node:perf_hooks'); const {connectionSnapshot}=require('../bpm/connection-status.cjs'); function timestamp(value){if(typeof value!=='string')return null;const normalized=/^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/.test(value)?value.replace(' ','T')+'Z':value;const n=Date.parse(normalized);return Number.isFinite(n)?new Date(n).toISOString():null;} const latest=(...values)=>values.map(timestamp).filter(Boolean).sort().at(-1)||null; const groupStatus=items=>!items.length?'unconfigured':['error','unknown','running','pending','healthy','paused','disabled'].find(s=>items.some(i=>i.status===s))||'pending'; class RuntimeHealth { constructor({stateDir,startedAt=new Date().toISOString(),instanceId='',clock=()=>Date.now(),...sources}){ try { Object.assign(this,{stateDir,startedAt,instanceId,sources,clock});const dir=path.join(stateDir,'health');fs.mkdirSync(dir,{recursive:true,mode:0o700});this.db=new DatabaseSync(path.join(dir,'health.sqlite')); this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=2000; CREATE TABLE IF NOT EXISTS observations(kind TEXT NOT NULL,id TEXT NOT NULL,last_success TEXT,last_failure TEXT,PRIMARY KEY(kind,id));`); } catch(error) { try { this.db?.close(); } catch {} throw error; } } remember(kind,id,{successAt,failureAt}={}){ const old=this.db.prepare('SELECT last_success AS lastSuccessAt,last_failure AS lastFailureAt FROM observations WHERE kind=? AND id=?').get(kind,id)||{}; const record={lastSuccessAt:latest(old.lastSuccessAt,successAt),lastFailureAt:latest(old.lastFailureAt,failureAt)}; if(record.lastSuccessAt!==old.lastSuccessAt||record.lastFailureAt!==old.lastFailureAt)this.db.prepare('INSERT INTO observations VALUES(?,?,?,?) ON CONFLICT(kind,id) DO UPDATE SET last_success=excluded.last_success,last_failure=excluded.last_failure').run(kind,id,record.lastSuccessAt,record.lastFailureAt); return record; } collect(){ const groups=[],safe=(key,title,link,read)=>{try{const items=read();groups.push({key,title,link,status:groupStatus(items),items});}catch{groups.push({key,title,link,status:'unknown',items:[],message:'暂时无法读取此模块状态,请到对应页面核实。'});}}; let connections=[],connectionViews=[]; safe('bpm','BPM 连接','#bpm',()=>{connections=this.sources.workspace?.snapshot().connections||[];return connections.map(c=>{ const config=()=>this.sources.monitor?.scanner?.store?.config?.()||this.sources.scanner?.store.status().config||{}; const snapshot=connectionSnapshot(c,{manager:this.sources.bpmSessions,monitor:this.sources.monitor,config,now:this.clock()});connectionViews.push(snapshot); const account=snapshot.connectionState.account,checkedAt=timestamp(account.checkedAt),status=account.status; return {id:c.id,name:redact(c.name||'BPM 连接'),owner:c.owner,status,checkedAt,reason:account.reason,detail:account.message,...this.remember('bpm',c.id,{successAt:latest(c.lastConnectedAt,status==='healthy'?checkedAt:null),failureAt:['AUTH_REQUIRED','SESSION_UNAVAILABLE'].includes(account.reason)?checkedAt:null})}; });}); safe('bpm-sync','BPM 同步','#bpm',()=>connectionViews.map(c=>{ const sync=c.connectionState.sync;return {id:c.id,name:redact(c.name||'BPM 连接'),owner:c.owner,status:sync.status,reason:sync.reason,checkedAt:timestamp(sync.checkedAt),detail:sync.message}; })); safe('scan','BPM 扫描','#records',()=>{ const {config={},runs=[]}=this.sources.scanner?.store.status()||{}; for(const r of runs)this.remember('scan',r.connectionId+':'+(r.kind||'inform'),{successAt:r.status==='success'?r.finishedAt:null,failureAt:['error','interrupted'].includes(r.status)?r.finishedAt:null}); return connections.flatMap(c=>['todo','inform'].map(kind=>{ const id=c.id+':'+kind,run=runs.find(r=>r.connectionId===c.id&&(r.kind||'inform')===kind),history=this.remember('scan',id),checkedAt=timestamp(run?.finishedAt||run?.startedAt)||latest(history.lastSuccessAt,history.lastFailureAt); const failed=history.lastFailureAt&&(!history.lastSuccessAt||Date.parse(history.lastFailureAt)>Date.parse(history.lastSuccessAt)); const stale=!!checkedAt&&this.clock()-Date.parse(checkedAt)>Math.max(60000,(config.intervalMinutes||5)*120000+30000); const status=c.status==='disabled'||config.enabled===false?'paused':run?.status==='running'?'running':failed||run&&['error','interrupted'].includes(run.status)?'error':!history.lastSuccessAt||stale?'pending':'healthy'; const label=kind==='todo'?'待办':'待阅',failureDetail=history.lastFailureAt?redact(run?.status==='error'&&run.message||label+'曾读取失败,保留历史证据。'):null,detail=status==='paused'?'自动同步已暂停,保留最近观测。'+(failureDetail?' '+failureDetail:''):status==='error'?failureDetail:stale?'最近成功已超过完整对账周期,等待核实。':history.lastSuccessAt?`最近读取 ${run?.seen||0} 条;结果仅代表最近对账。`:'等待首次完整对账。'; return {id,connectionId:c.id,kind,name:redact(c.name||'BPM 连接')+' · '+label,owner:c.owner,status,stale,checkedAt,detail,...history}; })); }); if(this.sources.monitor)safe('listener','BPM 到达监听','#bpm',()=>connections.map(c=>{ const observed=this.sources.monitor.snapshot(c.id),status=c.status==='disabled'||observed.status==='paused'?'paused':observed.status==='listening'?'healthy':['login_required','error'].includes(observed.status)?'error':'pending',history=this.remember('listener',c.id,{successAt:observed.status==='listening'?observed.lastSyncAt||observed.lastSignalAt:null,failureAt:observed.lastFailureAt}); return {id:c.id,owner:c.owner,name:redact(c.name||'BPM 连接'),status,checkedAt:timestamp(observed.lastSignalAt||observed.lastSyncAt)||latest(history.lastSuccessAt,history.lastFailureAt),nextReconcileAt:timestamp(observed.nextReconcileAt),detail:status==='paused'?'连接已暂停,最近监听失败及成功证据保留。':status==='healthy'?'推送已连接;实际读取结果请查看待办/待阅对账。':status==='error'?'监听不可用,请核对连接;完整对账继续作为补偿。':'等待监听或通过完整对账发现到达。',...history}; })); if(this.sources.monitor)safe('handoff','订单执行线索','#notification-execution',()=>connections.map(c=>{const observed=this.sources.monitor.snapshot(c.id),delivery=observed.delivery||{status:'healthy',pending:0},status=c.status==='disabled'||observed.status==='paused'?'paused':delivery.status;return {id:c.id,owner:c.owner,name:redact(c.name||'BPM 连接'),status,checkedAt:latest(delivery.lastSuccessAt,delivery.lastFailureAt),detail:delivery.message||'暂无待投递执行线索。',pending:delivery.pending||0,...this.remember('handoff',c.id,{successAt:delivery.lastSuccessAt,failureAt:delivery.lastFailureAt})};})); safe('storage','SMB 存储','#storage',()=> (this.sources.storage?.store.servers()||[]).map(s=>{ const checkedAt=timestamp(s.state?.checkedAt),status=!s.enabled?'disabled':!checkedAt?'pending':s.state.readable&&s.state.writable?'healthy':s.state.readable?'pending':'error'; return {id:s.id,name:redact(s.name||'存储服务器'),status,checkedAt,detail:redact(s.state?.message||'尚未检查连接。'),...this.remember('storage',s.id,{successAt:status==='healthy'?checkedAt:null,failureAt:status==='error'?checkedAt:null})}; })); safe('mail','邮件渠道','#mail',()=> (this.sources.mail?.store.channels()||[]).map(c=>{ const checkedAt=timestamp(c.state?.checkedAt),status=!checkedAt?'pending':c.state.smtp&&c.state.imap?'healthy':'error'; return {id:c.id,name:redact(c.name||'托管邮箱'),status,checkedAt,detail:redact(c.state?.message||'尚未检查 SMTP / IMAP。'),...this.remember('mail',c.id,{successAt:status==='healthy'?checkedAt:null,failureAt:status==='error'?checkedAt:null})}; })); if(this.sources.execution)safe('execution','分类订单执行','#notification-execution',()=>{ const execution=this.sources.execution,data=typeof execution.healthSnapshot==='function'?execution.healthSnapshot():execution.snapshot(),names={liveTodo:'真实待办',pdfExport:'PDF 导出',automaticArchive:'归档校验'}; const items=Object.entries(names).map(([id,name])=>({id,name,global:true,status:data.capabilities?.[id]===true?'healthy':'pending',detail:data.capabilities?.[id]===true?'实际检查已通过;各类别仍需现场核验。':'尚未通过实际接入检查,请在订单通知管理的订单执行查看阻塞原因。'})); for(const task of data.tasks||[]){const status=['blocked','failed'].includes(task.status)?'error':task.status==='unknown'?'unknown':['capturing','preparing','archiving','running','sending'].includes(task.status)?'running':['archived','sent','pending'].includes(task.status)?'healthy':'pending'; items.push({id:task.id,owner:connections.find(c=>c.id===task.connectionId)?.owner,name:redact(task.processName||'订单执行任务'),status,checkedAt:timestamp(task.updatedAt),detail:redact(task.error||task.reason||task.blockedReason||'任务进度已持久保存,请在订单通知管理查看。'),...this.remember('execution',task.id,{successAt:status==='healthy'?task.updatedAt:null,failureAt:status==='error'?task.updatedAt:null})});} return items; }); return groups; } snapshot(user){ const now=this.clock(),groups=this.collect().map(g=>{if(!['bpm','bpm-sync','scan','listener','handoff','execution'].includes(g.key)||user.role==='admin'||g.status==='unknown')return g;const items=g.items.filter(i=>i.global||i.owner===user.username);return {...g,items,status:groupStatus(items)};}); let saved;try{saved=readSupervisor(this.stateDir);}catch{saved={state:null,events:[],autostart:null};} const s=saved.state,managed=Boolean(this.instanceId&&s?.childInstanceId===this.instanceId),fresh=managed&&now-Date.parse(s.updatedAt)<45000; const guard=managed?{status:fresh?s.status:'stale',heartbeatAt:s.heartbeatAt,updatedAt:s.updatedAt,restartCount:s.restartCount,childStartedAt:s.childStartedAt,reason:s.reason,nextRestartAt:s.nextRestartAt,events:saved.events.map(e=>({at:e.at,kind:e.kind,code:e.detail.code,delayMs:e.detail.delayMs,reason:e.detail.reason}))}:{status:'unmanaged',restartCount:0,events:[]}; const autostart={enabled:!!(saved.autostart?.enabled&&saved.autostart?.linkPath&&fs.existsSync(saved.autostart.linkPath)),method:'current_user_logon',installedAt:saved.autostart?.installedAt||null}; const eventLoop={observed:!!this.loopDelay,since:this.loopDelay?this.loopObservedAt:null,maxMs:this.loopDelay?Math.round(this.loopDelay.max/1e4)/100:0,meanMs:this.loopDelay&&Number.isFinite(this.loopDelay.mean)?Math.round(this.loopDelay.mean/1e4)/100:0}; return {at:new Date(now).toISOString(),runtime:{startedAt:this.startedAt,uptimeSeconds:Math.max(0,Math.floor((now-Date.parse(this.startedAt))/1000)),managed,guard,autostart,eventLoop},groups}; } start(){if(this.timer)return;this.loopDelay=monitorEventLoopDelay({resolution:20});this.loopDelay.enable();this.loopObservedAt=new Date(this.clock()).toISOString();const observe=()=>{try{this.collect();}catch{}};observe();this.timer=setInterval(observe,15000);this.timer.unref?.();} close(){clearInterval(this.timer);this.timer=null;this.loopDelay?.disable();this.loopDelay=null;this.db?.close();this.db=null;} } module.exports={RuntimeHealth,timestamp};