fix: reconcile BPM sources and retain safe storage diagnostics
This commit is contained in:
1 parent
7e42a6dcc6
commit
33e9e9c108
9 files changed
+179
-40
No files matched your search
@@ -1,12 +1,13 @@
|
||||
'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');
|
||||
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='',...sources}){
|
||||
constructor({stateDir,startedAt=new Date().toISOString(),instanceId='',clock=()=>Date.now(),...sources}){
|
||||
try {
|
||||
Object.assign(this,{stateDir,startedAt,instanceId,sources});const dir=path.join(stateDir,'health');fs.mkdirSync(dir,{recursive:true,mode:0o700});this.db=new DatabaseSync(path.join(dir,'health.sqlite'));
|
||||
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) {
|
||||
@@ -29,9 +30,20 @@ class RuntimeHealth {
|
||||
});});
|
||||
safe('scan','BPM 扫描','#records',()=>{
|
||||
const {config={},runs=[]}=this.sources.scanner?.store.status()||{};
|
||||
for(const r of runs)this.remember('scan',r.connectionId,{successAt:r.status==='success'?r.finishedAt:null,failureAt:['error','interrupted'].includes(r.status)?r.finishedAt:null});
|
||||
return connections.filter(c=>c.status!=='disabled').map(c=>{const run=runs.find(r=>r.connectionId===c.id),status=run?.status==='running'?'running':config.enabled===false?'paused':!run?'pending':run.status==='success'?'healthy':'error';return {id:c.id,name:redact(c.name||'BPM 连接'),owner:c.owner,status,checkedAt:timestamp(run?.finishedAt||run?.startedAt),detail:config.enabled===false?'定时扫描已暂停,保留最近运行记录。':run?.message?redact(run.message):run?.status==='success'?`最近扫描 ${run.seen||0} 条,新增 ${run.added||0} 条。`:'等待扫描结果。',...this.remember('scan',c.id)};});
|
||||
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.filter(c=>c.status!=='disabled').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=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'?'待办':'待阅',detail=config.enabled===false?'自动同步已暂停,保留最近观测。':status==='error'?redact(run?.message||label+'上次读取失败,等待重试。'):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.filter(c=>c.status!=='disabled').map(c=>{
|
||||
const observed=this.sources.monitor.snapshot(c.id),status=observed.status==='listening'?'healthy':['login_required','error'].includes(observed.status)?'error':observed.status==='paused'?'paused':'pending';
|
||||
return {id:c.id,owner:c.owner,name:redact(c.name||'BPM 连接'),status,checkedAt:timestamp(observed.lastSignalAt||observed.lastSyncAt),nextReconcileAt:timestamp(observed.nextReconcileAt),detail:status==='healthy'?'推送已连接;实际读取结果请查看待办/待阅对账。':status==='error'?'监听不可用,请核对连接;完整对账继续作为补偿。':'等待监听或通过完整对账发现到达。'};
|
||||
}));
|
||||
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})};
|
||||
@@ -50,14 +62,15 @@ class RuntimeHealth {
|
||||
return groups;
|
||||
}
|
||||
snapshot(user){
|
||||
const now=Date.now(),groups=this.collect().map(g=>{if(!['bpm','scan','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)};});
|
||||
const now=this.clock(),groups=this.collect().map(g=>{if(!['bpm','scan','listener','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};
|
||||
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},groups};
|
||||
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;const observe=()=>{try{this.collect();}catch{}};observe();this.timer=setInterval(observe,15000);this.timer.unref?.();}
|
||||
close(){clearInterval(this.timer);this.timer=null;this.db?.close();this.db=null;}
|
||||
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};
|
||||
Reference in new issue
Block a user