From 10eac70745948e20c706f57364d6c7bdd3fba478 Mon Sep 17 00:00:00 2001 From: abaishu0730 Date: Wed, 21 Oct 2026 10:02:05 +0800 Subject: [PATCH] fix: separate BPM reads from durable execution delivery --- src/modules/bpm/arrival-monitor.cjs | 40 +++++++++++++++++++-------- src/modules/bpm/scan-deliveries.cjs | 33 ++++++++++++++++++++++ src/modules/bpm/scan-store.cjs | 7 +++-- src/modules/bpm/scanner.cjs | 6 ++-- src/modules/health/runtime-health.cjs | 15 +++++----- tests/app/health-source.test.cjs | 7 +++++ tests/bpm/arrival-recovery.test.cjs | 23 +++++++++++++-- tests/bpm/scan-delivery.test.cjs | 16 +++++++++++ 8 files changed, 120 insertions(+), 27 deletions(-) create mode 100644 src/modules/bpm/scan-deliveries.cjs create mode 100644 tests/bpm/scan-delivery.test.cjs diff --git a/src/modules/bpm/arrival-monitor.cjs b/src/modules/bpm/arrival-monitor.cjs index 70fbc99..8a2b2b4 100644 --- a/src/modules/bpm/arrival-monitor.cjs +++ b/src/modules/bpm/arrival-monitor.cjs @@ -9,7 +9,7 @@ function todoArrival(row){ } class BpmArrivalMonitor{ constructor({workspace,manager,scanner,provider,settings,onTodoReconciled,hubClient=new BpmSignalRClient(),clock=()=>Date.now(),debounceMs=750,pollMs=5000,retryMs=[2000,5000,15000,60000],sourceRetryMs=[2000,5000,15000,60000,300000]}){ - Object.assign(this,{workspace,manager,scanner,provider,settings,onTodoReconciled,hubClient,clock,debounceMs,pollMs,retryMs,sourceRetryMs});this.entries=new Map();this.todoPending=new Map();this.stopped=false; + Object.assign(this,{workspace,manager,scanner,provider,settings,onTodoReconciled,hubClient,clock,debounceMs,pollMs,retryMs,sourceRetryMs});this.entries=new Map();this.todoPending=new Map();this.deliveryPending=new Map();this.stopped=false; this.principal={user:{username:'系统监听',role:'admin'},sessionId:'monitor:'+crypto.randomUUID()}; } allowed(){const config=this.scanner.store.config();return config.enabled&&dayPolicy(new Date(this.clock()),this.settings().schedule,this.workspace.snapshot().calendar.overrides).scan;} @@ -17,8 +17,9 @@ class BpmArrivalMonitor{ source(entry,kind){return entry.sources[kind]||=( {status:'pending',failures:0,nextAttempt:0,lastSuccessAt:null,lastFailureAt:null} );} sourceSuccess(entry,kind){if(!entry||!this.active(entry))return;const source=this.source(entry,kind);Object.assign(source,{status:'healthy',failures:0,nextAttempt:0,lastSuccessAt:new Date(this.clock()).toISOString(),message:null});if(['todo','inform'].every(k=>this.source(entry,k).status==='healthy'))entry.lastSyncAt=new Date(this.clock()).toISOString();} sourceFailure(entry,kind,error){if(!entry||!this.active(entry))return;const source=this.source(entry,kind),delay=this.sourceRetryMs[Math.min(source.failures++,this.sourceRetryMs.length-1)];Object.assign(source,{status:'error',lastFailureAt:new Date(this.clock()).toISOString(),nextAttempt:this.clock()+delay,message:error?.status===401?'需要恢复BPM登录。':error?.status===403?'没有读取权限。':error?.status===409?'连接忙碌或已暂停。':'读取失败,等待重试。'});entry.lastFailureAt=source.lastFailureAt;entry.dirty.add(kind);} - snapshot(id){const e=this.entries.get(id);if(e)return {status:e.status,lastSignalAt:e.lastSignalAt||null,lastSyncAt:e.lastSyncAt||null,lastFailureAt:e.lastFailureAt||null,nextRetryAt:Number.isFinite(e.nextRetry)?new Date(e.nextRetry).toISOString():null,nextReconcileAt:new Date(e.nextReconcile).toISOString(),sources:Object.fromEntries(['todo','inform'].map(kind=>{const s=this.source(e,kind);return [kind,{status:s.status,lastSuccessAt:s.lastSuccessAt,lastFailureAt:s.lastFailureAt,retryAt:s.nextAttempt?new Date(s.nextAttempt).toISOString():null,message:s.message||null}];}))}; - let status='removed';try{status=this.workspace.getConnection(id).status==='disabled'||!this.scanner.store.config().enabled?'paused':'waiting';}catch{}return {status,lastSignalAt:null,lastSyncAt:null,nextReconcileAt:null,sources:{}}; + deliveryState(id){return this.scanner.store.deliveries?.summary(id)||{status:'healthy',pending:0};} + snapshot(id){const e=this.entries.get(id);if(e)return {status:e.status,lastSignalAt:e.lastSignalAt||null,lastSyncAt:e.lastSyncAt||null,lastFailureAt:e.lastFailureAt||null,nextRetryAt:Number.isFinite(e.nextRetry)?new Date(e.nextRetry).toISOString():null,nextReconcileAt:new Date(e.nextReconcile).toISOString(),delivery:this.deliveryState(id),sources:Object.fromEntries(['todo','inform'].map(kind=>{const s=this.source(e,kind);return [kind,{status:s.status,lastSuccessAt:s.lastSuccessAt,lastFailureAt:s.lastFailureAt,retryAt:s.nextAttempt?new Date(s.nextAttempt).toISOString():null,message:s.message||null}];}))}; + let status='removed';try{status=this.workspace.getConnection(id).status==='disabled'||!this.scanner.store.config().enabled?'paused':'waiting';}catch{}return {status,lastSignalAt:null,lastSyncAt:null,nextReconcileAt:null,sources:{},delivery:this.deliveryState(id)}; } updateInterval(entry,config){if(entry.intervalMinutes===config.intervalMinutes)return;entry.intervalMinutes=config.intervalMinutes;entry.nextReconcile=(entry.lastReconcileAt??this.clock())+config.intervalMinutes*60000;} async reconfigure(){await this.tick();} @@ -31,6 +32,7 @@ class BpmArrivalMonitor{ if(c.status==='disabled'||c.status==='disconnected'&&!c.lastConnectedAt)continue; let entry=this.entries.get(c.id);if(!entry){entry={id:c.id,status:'connecting',nextRetry:0,nextReconcile:this.clock()+config.intervalMinutes*60000,lastReconcileAt:this.clock(),intervalMinutes:config.intervalMinutes,sources:{},failures:0,dirty:new Set(),controller:new AbortController(),attempt:0};this.entries.set(c.id,entry);} this.updateInterval(entry,config); + if(this.allowed())this.publishPending(c.id,()=>this.active(entry)&&this.allowed()&&entry.epoch===(this.manager.epoch?.(c.id)||0)).catch(()=>{}); if(entry.handle&&entry.epoch!==(this.manager.epoch?.(c.id)||0)){await this.stopConnection(c.id);continue;} if(!entry.handle&&!entry.connecting&&this.clock()>=entry.nextRetry)this.connect(entry,c); if(this.clock()>=entry.nextReconcile){entry.nextReconcile=this.clock()+config.intervalMinutes*60000;for(const kind of ['todo','inform'])this.source(entry,kind).nextAttempt=0;this.queue(entry,['todo','inform']);} @@ -60,13 +62,14 @@ class BpmArrivalMonitor{ async synchronize(entry,kinds){let valid=true; for(const kind of kinds){if(!this.active(entry))return; try{ - if(kind==='inform'){this.source(entry,kind).status='running';await this.scanner.scan(entry.id,this.principal);this.sourceSuccess(entry,kind);} - else await this.startTodoScan(entry.id,this.principal).promise; + const canCommit=()=>this.active(entry)&&this.allowed()&&entry.epoch===(this.manager.epoch?.(entry.id)||0); + if(kind==='inform'){this.source(entry,kind).status='running';await this.scanner.scan(entry.id,this.principal,{canCommit});this.sourceSuccess(entry,kind);} + else await this.startTodoScan(entry.id,this.principal,{canCommit}).promise; }catch(error){valid=false;if(kind==='inform')this.sourceFailure(entry,kind,error);else if(this.active(entry)){entry.dirty.add(kind);const source=this.source(entry,kind);if(!source.nextAttempt)source.nextAttempt=this.clock()+this.sourceRetryMs[0];}} } if(valid&&this.active(entry)&&kinds.includes('todo')&&kinds.includes('inform')){entry.lastReconcileAt=this.clock();entry.nextReconcile=this.clock()+entry.intervalMinutes*60000;} } - startTodoScan(id,principal){ + startTodoScan(id,principal,{canCommit=()=>true}={}){ const fail=(message,status)=>{throw Object.assign(new Error(message),{status});};if(this.stopped)fail('监听服务正在停止。',503); const connection=this.workspace.getConnection(id);if(!principal?.sessionId||!['admin','operator'].includes(principal.user?.role)||principal.user.role!=='admin'&&connection.owner!==principal.user.username)fail('仅连接负责人或管理员可以同步。',403); if(connection.status==='disabled')fail('此连接已停用。',409);if(this.todoPending.has(id))fail('待办对账正在运行。',409); @@ -74,14 +77,27 @@ class BpmArrivalMonitor{ if(entry)this.source(entry,'todo').status='running'; const promise=Promise.resolve().then(async()=>{ try{let rows;try{rows=await this.provider.scan(connection,principal);}catch(error){if(error.status!==401)throw error;const result=await this.manager.ensure(connection,principal);if(result.status!=='connected')throw error;rows=await this.provider.scan(connection,principal);} - const current=this.workspace.getConnection(id);if(this.stopped||current.status==='disabled'||epoch!==(this.manager.epoch?.(id)||0))fail('连接已暂停或身份已变化,本次对账未提交。',409); - const result=this.scanner.store.complete(runId,id,rows.map(todoArrival),current),finishedAt=new Date(this.clock()).toISOString(); - if(this.onTodoReconciled)await this.onTodoReconciled({connectionId:id,runId,rows:structuredClone(rows),startedAt,finishedAt}); - this.sourceSuccess(entry,'todo');return {...result,runId}; + const current=this.workspace.getConnection(id);if(this.stopped||current.status==='disabled'||current.owner!==connection.owner||epoch!==(this.manager.epoch?.(id)||0)||!canCommit())fail('连接已暂停或身份已变化,本次对账未提交。',409); + if(principal.user.role!=='admin'&¤t.owner!==principal.user.username)fail('连接负责人已变化。',403);this.manager.authorize?.(current,principal); + const finishedAt=new Date(this.clock()).toISOString(),delivery=this.onTodoReconciled?{connectionId:id,runId,rows:structuredClone(rows),startedAt,finishedAt}:undefined; + const result=this.scanner.store.complete(runId,id,rows.map(todoArrival),current,{delivery}); + this.sourceSuccess(entry,'todo'); + // Delivery has its own persisted outcome; a callback cannot rewrite a committed read. + if(delivery)await this.publishPending(id,canCommit).catch(()=>{}); + return {...result,runId}; }catch(error){this.scanner.store.fail(runId,error.status===401?'需要恢复BPM登录。':error.status===409?'连接忙碌或已暂停。':'待办对账失败,请稍后重试。');this.sourceFailure(entry,'todo',error);throw error;} }).finally(()=>this.todoPending.delete(id));this.todoPending.set(id,promise);return {runId,promise}; } - async stopConnection(id){const entry=this.entries.get(id);if(!entry){await this.todoPending.get(id)?.catch(()=>{});return;}this.entries.delete(id);entry.controller.abort();clearTimeout(entry.debounce);await Promise.allSettled([entry.handle?.stop(),entry.connecting,entry.sync,this.todoPending.get(id)]);} - async stop(){this.stopped=true;clearInterval(this.timer);this.timer=null;await Promise.all([...this.entries.keys()].map(id=>this.stopConnection(id)));await Promise.allSettled([...this.todoPending.values()]);} + publishPending(id,canDeliver=()=>true){ + if(!this.onTodoReconciled||!this.scanner.store.deliveries)return Promise.resolve(); + if(this.deliveryPending.has(id))return this.deliveryPending.get(id); + const task=Promise.resolve().then(async()=>{for(const item of this.scanner.store.deliveries.pending(id,this.clock())){ + if(this.stopped||!canDeliver())return;let connection;try{connection=this.workspace.getConnection(id);}catch{return;}if(connection.status==='disabled')return; + try{await this.onTodoReconciled(item.payload);this.scanner.store.deliveries.acknowledge(item.id);} + catch{const delay=this.sourceRetryMs[Math.min(item.attempts,this.sourceRetryMs.length-1)];this.scanner.store.deliveries.failed(item.id,this.clock()+delay);} + }}).finally(()=>{if(this.deliveryPending.get(id)===task)this.deliveryPending.delete(id);});this.deliveryPending.set(id,task);return task; + } + async stopConnection(id){const entry=this.entries.get(id);if(entry){this.entries.delete(id);entry.controller.abort();clearTimeout(entry.debounce);}await Promise.allSettled([entry?.handle?.stop(),entry?.connecting,entry?.sync,this.todoPending.get(id),this.deliveryPending.get(id)]);} + async stop(){this.stopped=true;clearInterval(this.timer);this.timer=null;await Promise.all([...this.entries.keys()].map(id=>this.stopConnection(id)));await Promise.allSettled([...this.todoPending.values(),...this.deliveryPending.values()]);} } module.exports={BpmArrivalMonitor,todoArrival}; diff --git a/src/modules/bpm/scan-deliveries.cjs b/src/modules/bpm/scan-deliveries.cjs new file mode 100644 index 0000000..075dfcf --- /dev/null +++ b/src/modules/bpm/scan-deliveries.cjs @@ -0,0 +1,33 @@ +'use strict'; +const path=require('node:path'); +const {BpmVault}=require('../../platform/security/vault.cjs'); +class ScanDeliveries{ + constructor({db,dir}){ + this.db=db;this.dir=path.join(dir,'delivery-secrets'); + db.exec(`CREATE TABLE IF NOT EXISTS execution_deliveries(run_id TEXT PRIMARY KEY,connection_id TEXT NOT NULL,payload BLOB,status TEXT NOT NULL,attempts INTEGER NOT NULL DEFAULT 0,next_at INTEGER NOT NULL DEFAULT 0,created_at TEXT NOT NULL,updated_at TEXT NOT NULL,failed_at TEXT,delivered_at TEXT); + CREATE INDEX IF NOT EXISTS execution_delivery_pending ON execution_deliveries(connection_id,status,next_at);`); + } + vault(){return this.identity||=(new BpmVault({stateDir:this.dir}));} + enqueue(payload){ + if(this.db.prepare('SELECT 1 FROM execution_deliveries WHERE run_id=?').get(payload.runId))return; + if(Buffer.byteLength(JSON.stringify(payload))>32*1024*1024)throw Object.assign(Error('执行线索超过本地队列大小限制。'),{status:413}); + const at=new Date().toISOString(),encoded=this.vault().encode('execution-delivery:'+payload.runId,payload); + this.db.prepare('INSERT INTO execution_deliveries(run_id,connection_id,payload,status,created_at,updated_at) VALUES(?,?,?,?,?,?)').run(payload.runId,payload.connectionId,encoded,'pending',at,at); + } + pending(connectionId,now){ + const ready=[]; + for(const row of this.db.prepare("SELECT run_id AS id,payload,attempts FROM execution_deliveries WHERE connection_id=? AND status IN ('pending','error') AND next_at<=? ORDER BY created_at,rowid LIMIT 10").all(connectionId,now)){ + try{ready.push({id:row.id,attempts:row.attempts,payload:this.vault().decode('execution-delivery:'+row.id,row.payload)});} + catch{this.failed(row.id,now+60000);} + } + return ready; + } + acknowledge(id){const at=new Date().toISOString();this.db.prepare("UPDATE execution_deliveries SET status='delivered',payload=NULL,next_at=0,updated_at=?,delivered_at=? WHERE run_id=?").run(at,at,id);} + failed(id,nextAt){const at=new Date().toISOString();this.db.prepare("UPDATE execution_deliveries SET status='error',attempts=attempts+1,next_at=?,updated_at=?,failed_at=? WHERE run_id=? AND status!='delivered'").run(nextAt,at,at,id);} + summary(connectionId){ + const pending=this.db.prepare("SELECT COUNT(*) AS n,MIN(next_at) AS due,SUM(CASE WHEN status='error' THEN 1 ELSE 0 END) AS errors FROM execution_deliveries WHERE connection_id=? AND status!='delivered'").get(connectionId),history=this.db.prepare('SELECT MAX(failed_at) AS failed,MAX(delivered_at) AS delivered FROM execution_deliveries WHERE connection_id=?').get(connectionId); + return {status:pending.n?(pending.errors?'error':'pending'):'healthy',pending:pending.n,retryAt:pending.n&&pending.due?new Date(pending.due).toISOString():null,lastFailureAt:history.failed||null,lastSuccessAt:history.delivered||null,message:pending.n?'列表读取已保存,执行线索等待本地投递。':'执行线索已交付。'}; + } + close(){this.identity?.destroy();this.identity=null;} +} +module.exports={ScanDeliveries}; diff --git a/src/modules/bpm/scan-store.cjs b/src/modules/bpm/scan-store.cjs index a545a32..68f4855 100644 --- a/src/modules/bpm/scan-store.cjs +++ b/src/modules/bpm/scan-store.cjs @@ -1,6 +1,7 @@ 'use strict'; const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite'); const invalid=message=>Object.assign(new Error(message),{status:400}); +const {ScanDeliveries}=require('./scan-deliveries.cjs'); class BpmScanStore{ constructor(dir){ try { @@ -12,6 +13,7 @@ class BpmScanStore{ CREATE TABLE IF NOT EXISTS runs(id TEXT PRIMARY KEY,connection_id TEXT NOT NULL,actor TEXT NOT NULL,started_at TEXT NOT NULL,finished_at TEXT,status TEXT NOT NULL,seen INTEGER,added INTEGER,message TEXT); UPDATE runs SET status='error',message='服务重启,扫描未完成。',finished_at=CURRENT_TIMESTAMP WHERE status='running';`); if(!this.db.prepare('PRAGMA table_info(runs)').all().some(c=>c.name==='kind'))this.db.exec("ALTER TABLE runs ADD COLUMN kind TEXT NOT NULL DEFAULT 'inform'"); + this.deliveries=new ScanDeliveries({db:this.db,dir}); } catch(error) { try { this.db?.close(); } catch {} throw error; @@ -21,11 +23,12 @@ class BpmScanStore{ config(){return JSON.parse(this.db.prepare('SELECT value FROM config WHERE id=1').get().value);} saveConfig(input){if(!input||Object.keys(input).some(k=>!['enabled','intervalMinutes'].includes(k))||typeof input.enabled!=='boolean'||!Number.isInteger(input.intervalMinutes)||input.intervalMinutes<1||input.intervalMinutes>1440)throw invalid('扫描间隔需为 1–1440 分钟。');this.db.prepare('UPDATE config SET value=? WHERE id=1').run(JSON.stringify(input));return this.config();} begin(connectionId,actor,kind='inform'){if(!['inform','todo'].includes(kind))throw invalid('到达类型无效。');const id=crypto.randomUUID();this.db.prepare('INSERT INTO runs(id,connection_id,actor,started_at,status,kind) VALUES(?,?,?,?,?,?)').run(id,connectionId,actor,new Date().toISOString(),'running',kind);return id;} - complete(id,connectionId,rows,connection){return this.transaction(()=>{ + complete(id,connectionId,rows,connection,{delivery}={}){return this.transaction(()=>{ let added=0;const now=new Date().toISOString(); const insert=this.db.prepare('INSERT OR IGNORE INTO arrivals VALUES(?,?,?,?,?,?,?)');const update=this.db.prepare('UPDATE arrivals SET day=?,value=?,last_seen=? WHERE connection_id=? AND source=? AND task_id=?'); const prior=this.db.prepare('SELECT value FROM arrivals WHERE connection_id=? AND source=? AND task_id=?'); for(const row of rows){if(!row.arrivalDay||!row.taskId||!row.source)throw invalid('流程记录无效。');const key=row.recordKey||row.taskId,old=prior.get(connectionId,row.source,key),snapshot=old?JSON.parse(old.value).origin:null,saved={...row};delete saved.origin;if(snapshot||connection)saved.origin=snapshot||{id:connectionId,name:connection.name,owner:connection.owner,identity:connection.identity||''};const value=JSON.stringify(saved);added+=Number(insert.run(connectionId,row.source,key,row.arrivalDay,value,now,now).changes);update.run(row.arrivalDay,value,now,connectionId,row.source,key);} + if(delivery)this.deliveries.enqueue(delivery); this.db.prepare('UPDATE runs SET status=?,finished_at=?,seen=?,added=?,message=? WHERE id=? AND status=?').run('success',now,rows.length,added,'',id,'running');this.prune();return {seen:rows.length,added}; });} fail(id,message){this.db.prepare('UPDATE runs SET status=?,finished_at=?,message=? WHERE id=?').run('error',new Date().toISOString(),message,id);this.prune();} @@ -55,6 +58,6 @@ class BpmScanStore{ const groups=shown.map(day=>({day,items:this.db.prepare('SELECT connection_id AS connectionId,value,first_seen AS firstSeenAt,last_seen AS lastSeenAt FROM arrivals'+(filtered?filtered+' AND ':' WHERE ')+'day=? ORDER BY json_extract(value,\'$.arrivedAt\') DESC,task_id').all(...args,day).map(({value,...rest})=>({...JSON.parse(value),...rest}))})); return {total,groups,nextBefore:dates.length>days?shown.at(-1):null}; } - close(){this.db.close();} + close(){this.deliveries?.close();this.db.close();} } module.exports={BpmScanStore}; diff --git a/src/modules/bpm/scanner.cjs b/src/modules/bpm/scanner.cjs index 849e8df..1aac3d8 100644 --- a/src/modules/bpm/scanner.cjs +++ b/src/modules/bpm/scanner.cjs @@ -4,15 +4,15 @@ const fail=(message,status)=>Object.assign(new Error(message),{status}); class BpmScanner{ constructor({store,workspace,manager,settings,clock=()=>new Date()}){Object.assign(this,{store,workspace,manager,settings,clock});this.pending=new Map();this.stopped=false;this.lastTick=0;this.principal={user:{username:'系统扫描',role:'admin'},sessionId:'scan:'+crypto.randomUUID()};} start(){if(this.timer||this.stopped)return;this.timer=setInterval(()=>this.tick().catch(()=>{}),15000);this.timer.unref?.();this.tick().catch(()=>{});} - async scan(id,principal){return this.startScan(id,principal).promise;} - startScan(id,principal){ + async scan(id,principal,options){return this.startScan(id,principal,options).promise;} + startScan(id,principal,{canCommit=()=>true}={}){ if(this.stopped)throw fail('扫描服务正在关闭。',503);const connection=this.workspace.getConnection(id); if(!principal?.sessionId||!['admin','operator'].includes(principal.user?.role)||(principal.user.role!=='admin'&&connection.owner!==principal.user.username))throw fail('只有连接负责人或管理员可以扫描。',403); if(connection.status==='disabled')throw fail('此 BPM 连接已停用。',409); if(this.pending.has(id))throw fail('此连接正在扫描,请稍后查看结果。',409); const runId=this.store.begin(id,principal.user.username); const operation=Promise.resolve().then(async()=>{ - try{const rows=await this.manager.scanArrivals(connection,principal);const current=this.workspace.getConnection(id);if(current.status==='disabled')throw fail('此 BPM 连接已停用。',409);return {...this.store.complete(runId,id,rows,current),runId};} + try{const rows=await this.manager.scanArrivals(connection,principal);const current=this.workspace.getConnection(id);if(this.stopped||current.status==='disabled'||current.owner!==connection.owner||!canCommit())throw fail('连接或监听已暂停/变化,本次读取未提交。',409);if(principal.user.role!=='admin'&¤t.owner!==principal.user.username)throw fail('连接负责人已变化。',403);this.manager.authorize?.(current,principal);return {...this.store.complete(runId,id,rows,current),runId};} catch(cause){this.store.fail(runId,cause.status?cause.message:'BPM 扫描失败,请稍后重试。');throw cause;} }).finally(()=>this.pending.delete(id));this.pending.set(id,operation);return {promise:operation,runId}; } diff --git a/src/modules/health/runtime-health.cjs b/src/modules/health/runtime-health.cjs index c9f245a..647f5a8 100644 --- a/src/modules/health/runtime-health.cjs +++ b/src/modules/health/runtime-health.cjs @@ -31,19 +31,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+':'+(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=>{ + 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=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} 条;结果仅代表最近对账。`:'等待首次完整对账。'; + 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.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'?'监听不可用,请核对连接;完整对账继续作为补偿。':'等待监听或通过完整对账发现到达。'}; + 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})}; @@ -62,7 +63,7 @@ class RuntimeHealth { return groups; } snapshot(user){ - 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)};}); + const now=this.clock(),groups=this.collect().map(g=>{if(!['bpm','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:[]}; diff --git a/tests/app/health-source.test.cjs b/tests/app/health-source.test.cjs index 73045e2..3d5deb9 100644 --- a/tests/app/health-source.test.cjs +++ b/tests/app/health-source.test.cjs @@ -23,3 +23,10 @@ test('health reports process event loop observations without exposing host data' const observed=health.snapshot({role:'admin'}).runtime.eventLoop; assert.ok(observed,'process event loop observations must be available');assert.equal(observed.observed,true);assert.ok(Number.isFinite(observed.maxMs));assert.ok(observed.maxMs>=0); }); +test('paused connections retain their source and listener failure evidence',t=>{ + const stateDir=fs.mkdtempSync(path.join(os.tmpdir(),'health-paused-')),at=new Date().toISOString(),connection={id:'c',owner:'worker',status:'connected'}; + const health=new RuntimeHealth({stateDir,workspace:{snapshot:()=>({connections:[connection]})},scanner:{store:{status:()=>({config:{enabled:true},runs:[{connectionId:'c',kind:'inform',status:'error',finishedAt:at,message:'合成失败'}]})}},monitor:{snapshot:()=>({status:'error',lastFailureAt:at,sources:{}})}}); + t.after(()=>{health.close();fs.rmSync(stateDir,{recursive:true,force:true});});health.snapshot({role:'admin'});connection.status='disabled';const data=health.snapshot({role:'admin'}),scan=data.groups.find(group=>group.key==='scan'); + assert.equal(scan.items.length,2);assert.equal(scan.items.find(item=>item.kind==='inform').status,'paused');assert.equal(scan.items.find(item=>item.kind==='inform').lastFailureAt,at); + const listener=data.groups.find(group=>group.key==='listener').items[0];assert.equal(listener.status,'paused');assert.equal(listener.lastFailureAt,at); +}); diff --git a/tests/bpm/arrival-recovery.test.cjs b/tests/bpm/arrival-recovery.test.cjs index e31288b..b483903 100644 --- a/tests/bpm/arrival-recovery.test.cjs +++ b/tests/bpm/arrival-recovery.test.cjs @@ -9,15 +9,15 @@ function fixture(t,{interval=1440,onTodoReconciled}={}){ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'arrival-recovery-')),workspace=new WorkspaceStore(path.join(dir,'workspace')),scanStore=new BpmScanStore(path.join(dir,'scan')); let scanner,monitor;t.after(async()=>{await monitor?.stop();await scanner?.stop();scanStore.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});}); const admin={username:'admin',role:'admin'},connection=workspace.createConnection({name:'合成连接',owner:'admin'},admin,[admin]); - let now=Date.parse('2026-10-21T01:00:00Z'),todoCalls=0,failed=false,callbacks,hold; + let now=Date.parse('2026-10-21T01:00:00Z'),todoCalls=0,informCalls=0,failed=false,callbacks,hold,informHold; workspace.updateConnectionSession(connection.id,{status:'connected',identity:'synthetic',checkedAt:new Date(now).toISOString(),checks:{portal:{ok:true,message:'synthetic'}}},admin); scanStore.saveConfig({enabled:true,intervalMinutes:interval}); const row={source:'todo',portalSource:'portal-v4',taskId:'T',instanceId:'I',revision:1,processName:'合成订单',nodeName:'通知',processVersion:'1',serialNum:'S',title:'订单号:TEST',receivedAt:'2026-10-21T00:30:00Z'}; - const manager={sessions:new Map(),epoch:()=>0,ensure:async()=>({status:'connected'}),run:async(_,fn)=>fn(),authorize(){},vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})}),scanArrivals:async()=>[]}; + const manager={sessions:new Map(),epoch:()=>0,ensure:async()=>({status:'connected'}),run:async(_,fn)=>fn(),authorize(){},vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})}),scanArrivals:async()=>{informCalls++;if(informHold)await informHold;return [];}}; const provider={scan:async()=>{todoCalls++;if(hold)await hold;if(failed)throw Object.assign(Error('synthetic network failure'),{code:'ETIMEDOUT'});return [structuredClone(row)];}}; scanner=new BpmScanner({workspace,store:scanStore,manager,settings:()=>({schedule:{weekends:true}})}); monitor=new BpmArrivalMonitor({workspace,manager,scanner,provider,onTodoReconciled,clock:()=>now,settings:()=>({schedule:{weekends:true}}),hubClient:{connect:async(_,options)=>{callbacks=options;return {stop:async()=>{}};}},debounceMs:1,sourceRetryMs:[100,200,1000]}); - return {workspace,scanStore,connection,admin,monitor,row,get now(){return now;},get calls(){return todoCalls;},advance:ms=>now+=ms,fail:value=>failed=value,hint:()=>callbacks.onEvent('worklistChanged'),hold:value=>hold=value}; + return {workspace,scanStore,connection,admin,monitor,row,get now(){return now;},get calls(){return todoCalls;},get informCalls(){return informCalls;},advance:ms=>now+=ms,fail:value=>failed=value,hint:()=>callbacks.onEvent('worklistChanged'),hintInform:()=>callbacks.onEvent('informlistChanged'),hold:value=>hold=value,holdInform:value=>informHold=value}; } test('reducing a live reconciliation interval applies from the last completed reconciliation',async t=>{ const f=fixture(t);await f.monitor.tick();await until(()=>f.monitor.snapshot(f.connection.id).lastSyncAt); @@ -37,3 +37,20 @@ test('only fully committed authorized todo reads publish trusted execution hints let release;f.hold(new Promise(resolve=>release=resolve));f.hint();await until(()=>f.calls===2);f.workspace.disableConnection(f.connection.id,f.admin); const stopping=f.monitor.stopConnection(f.connection.id);release();await stopping;assert.equal(hints.length,1); }); +test('global automatic pause revokes the in-flight todo ticket without blocking later manual sync',async t=>{ + const hints=[],f=fixture(t,{onTodoReconciled:payload=>hints.push(payload)});await f.monitor.tick();await until(()=>f.monitor.snapshot(f.connection.id).lastSyncAt); + let release;f.hold(new Promise(resolve=>release=resolve));f.hint();await until(()=>f.calls===2);f.scanStore.saveConfig({enabled:false,intervalMinutes:1440});const stopping=f.monitor.reconfigure();release();await stopping; + assert.equal(hints.length,1);assert.equal(f.scanStore.status().runs.filter(run=>run.kind==='todo'&&run.status==='success').length,1); + f.hold(null);await f.monitor.startTodoScan(f.connection.id,{user:f.admin,sessionId:'manual'}).promise;assert.equal(hints.length,2); +}); +test('retiring the listener revokes an in-flight inform commit ticket',async t=>{ + const f=fixture(t);await f.monitor.tick();await until(()=>f.monitor.snapshot(f.connection.id).lastSyncAt); + let release;f.holdInform(new Promise(resolve=>release=resolve));f.hintInform();await until(()=>f.informCalls===2);const stopping=f.monitor.stopConnection(f.connection.id);release();await stopping; + assert.equal(f.scanStore.status().runs.filter(run=>run.kind==='inform'&&run.status==='success').length,1); +}); +test('local hint delivery retries its encrypted committed payload without re-reading BPM or changing read success',async t=>{ + let attempts=0;const f=fixture(t,{onTodoReconciled:()=>{attempts++;if(attempts===1)throw Error('synthetic queue failure');}});await f.monitor.tick();await until(()=>attempts===1&&!f.monitor.entries.get(f.connection.id).sync); + const run=f.scanStore.status().runs.find(item=>item.kind==='todo');assert.equal(run.status,'success');assert.equal(f.monitor.snapshot(f.connection.id).delivery.status,'error'); + const stored=f.scanStore.db.prepare('SELECT payload FROM execution_deliveries WHERE run_id=?').get(run.id);assert.ok(stored);assert.equal(Buffer.from(stored.payload).includes(Buffer.from(f.row.title)),false); + f.advance(101);await f.monitor.tick();await until(()=>attempts===2&&f.monitor.snapshot(f.connection.id).delivery.pending===0);assert.equal(f.calls,1);assert.equal(f.scanStore.status().runs.find(item=>item.id===run.id).status,'success'); +}); diff --git a/tests/bpm/scan-delivery.test.cjs b/tests/bpm/scan-delivery.test.cjs new file mode 100644 index 0000000..3f54218 --- /dev/null +++ b/tests/bpm/scan-delivery.test.cjs @@ -0,0 +1,16 @@ +'use strict'; +const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'); +const {BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs'); +test('committed delivery survives restart encrypted and acknowledgement releases only transport payload',t=>{ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'scan-delivery-'));let store=new BpmScanStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});}); + const runId=store.begin('c','synthetic','todo'),payload={runId,connectionId:'c',rows:[{title:'synthetic-private-title'}],startedAt:'2026-10-21T01:00:00Z',finishedAt:'2026-10-21T01:00:01Z'}; + store.complete(runId,'c',[{arrivalDay:'2026-10-21',taskId:'t',source:'todo:fixture'}],{id:'c',owner:'synthetic'},{delivery:payload}); + const bytes=store.db.prepare('SELECT payload FROM execution_deliveries WHERE run_id=?').get(runId).payload;assert.equal(Buffer.from(bytes).includes(Buffer.from('synthetic-private-title')),false); + store.close();store=new BpmScanStore(dir);assert.deepEqual(store.deliveries.pending('c',Date.now())[0].payload,payload);store.deliveries.acknowledge(runId);assert.equal(store.deliveries.summary('c').pending,0); + assert.equal(store.db.prepare('SELECT payload FROM execution_deliveries WHERE run_id=?').get(runId).payload,null);assert.equal(store.status().runs.find(run=>run.id===runId).status,'success');assert.equal(store.list({kind:'todo'}).total,1); +}); +test('a damaged transport payload remains visible as delivery failure without falsifying its successful read',t=>{ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'scan-delivery-damaged-')),store=new BpmScanStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});}); + const id=store.begin('c','synthetic','todo');store.complete(id,'c',[],{id:'c'},{delivery:{runId:id,connectionId:'c',rows:[],startedAt:'2026-10-21T01:00:00Z',finishedAt:'2026-10-21T01:00:01Z'}}); + store.db.prepare('UPDATE execution_deliveries SET payload=? WHERE run_id=?').run(Buffer.from('damaged'),id);assert.deepEqual(store.deliveries.pending('c',Date.now()),[]);assert.equal(store.deliveries.summary('c').status,'error');assert.equal(store.deliveries.summary('c').pending,1);assert.equal(store.status().runs.find(run=>run.id===id).status,'success'); +});