Files
order-notification-automation/src/modules/bpm/arrival-monitor.cjs
T

107 lines
14 KiB
JavaScript

'use strict';
const crypto=require('node:crypto');
const {dayPolicy}=require('../../shared/schedule.cjs');
const {normalizeArrival}=require('./list-client.cjs');
const {BpmSignalRClient}=require('./signalr-client.cjs');
const {ListenerState}=require('./listener-state.cjs');
function todoArrival(row){
if(row.source!=='todo'||!['portal-v4','portal-v8'].includes(row.portalSource)||row.instanceId==null)throw Object.assign(new Error('真实待办身份不完整。'),{status:502});
return {...normalizeArrival({taskId:row.taskId,startTime:row.receivedAt,serialNum:row.serialNum,processName:row.processName,activityName:row.nodeName,processInstanceSubject:row.title},'todo:'+row.portalSource),kind:'todo',instanceId:String(row.instanceId),...(row.revision==null?{}:{revision:row.revision}),processVersion:row.processVersion||'',recordKey:String(row.taskId)};
}
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.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;}
active(entry){try{return !this.stopped&&this.entries.get(entry.id)===entry&&this.workspace.getConnection(entry.id).status!=='disabled';}catch{return false;}}
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?.code==='TODO_IDENTITY_AMBIGUOUS'?error.message:error?.status===401?'需要恢复BPM登录。':error?.status===403?'没有读取权限。':error?.status===409?'连接忙碌或已暂停。':'读取失败,等待重试。'});entry.lastFailureAt=source.lastFailureAt;entry.dirty.add(kind);}
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,sessionEpoch:e.epoch??null,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();}
start(){if(this.timer||this.stopped)return;this.timer=setInterval(()=>this.tick().catch(()=>{}),this.pollMs);this.timer.unref?.();this.tick().catch(()=>{});}
async tick(){
if(this.stopped)return;const config=this.scanner.store.config(),connections=this.workspace.snapshot().connections,ids=new Set(connections.map(c=>c.id));
for(const id of this.entries.keys())if(!ids.has(id)||!config.enabled||this.workspace.getConnection(id).status==='disabled')await this.stopConnection(id);
if(!config.enabled)return;
for(const c of connections){
if(c.status==='disabled'||c.status==='disconnected'&&!c.lastConnectedAt)continue;
let entry=this.entries.get(c.id);if(!entry){entry={id:c.id,lifecycle:new ListenerState(),get status(){return this.lifecycle.state;},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);
const session=this.manager.sessionSnapshot?.(c.id);
if(['login_required','busy'].includes(entry.status)&&session?.phase==='idle'&&session.authentication==='valid')entry.nextRetry=0;
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']);}
else if(entry.dirty.size&&!entry.sync&&!entry.debounce)this.queue(entry,[]);
}
}
retry(entry,status='polling',delay){if(!this.active(entry))return;if(entry.connectedAt&&this.clock()-entry.connectedAt>60000)entry.failures=0;if(!entry.lifecycle.transition(({polling:'NETWORK_FAILED',login_required:'AUTH_REQUIRED',busy:'BUSY'})[status]))return;entry.nextRetry=this.clock()+(delay??this.retryMs[Math.min(entry.failures++,this.retryMs.length-1)]);}
connect(entry,connection){
const ticket=entry.lifecycle.begin();if(ticket===null)return;const attempt=++entry.attempt;let closed=false,subscribed=false;
entry.connecting=(async()=>{
if(this.manager.sessions.has(entry.id))throw Object.assign(new Error('人工登录窗口正在使用。'),{status:409});
const result=await this.manager.ensure(connection,this.principal);if(!this.active(entry)||!entry.lifecycle.current(ticket))return;
if(result.status!=='connected'){this.retry(entry,result.status==='login_required'?'login_required':'polling',5*60000);return;}
entry.epoch=this.manager.epoch?.(entry.id)||0;const handle=await this.manager.run(entry.id,async()=>{
this.manager.authorize(connection,this.principal);if(this.manager.sessions.has(entry.id))throw Object.assign(new Error('人工登录窗口正在使用。'),{status:409});
const saved=await this.manager.vault().read(entry.id);
return this.hubClient.connect(saved?.storageState,{signal:entry.controller.signal,onEvent:name=>{if(!this.active(entry)||!entry.lifecycle.current(ticket)||entry.attempt!==attempt||entry.epoch!==(this.manager.epoch?.(entry.id)||0))return;entry.lastSignalAt=new Date(this.clock()).toISOString();this.queue(entry,name==='worklistChanged'?['todo']:name==='informlistChanged'?['inform']:['todo','inform']);},onClose:()=>{closed=true;if(this.active(entry)&&entry.lifecycle.current(ticket)&&entry.attempt===attempt){entry.handle=null;this.retry(entry);if(!subscribed)this.queue(entry,['todo','inform']);}}});
});
if(!handle)return;if(!this.active(entry)||closed||!entry.lifecycle.transition('CONNECTED',ticket)){await handle.stop();return;}
subscribed=true;entry.handle=handle;entry.connectedAt=this.clock();entry.nextRetry=Infinity;entry.lastReconcileAt=this.clock();entry.nextReconcile=this.clock()+this.scanner.store.config().intervalMinutes*60000;this.queue(entry,['todo','inform']);
})().catch(error=>{if(!this.active(entry)||!entry.lifecycle.current(ticket))return;if(error.status===401)this.manager.observe?.(entry.id,'portal',error);this.retry(entry,error.status===409?'busy':error.status===401?'login_required':'polling',error.status===409?5000:error.status===401?5*60000:undefined);if(![401,409].includes(error.status))this.queue(entry,['todo','inform']);}).finally(()=>{entry.connecting=null;});
}
dueKinds(entry){return [...entry.dirty].filter(kind=>this.clock()>=this.source(entry,kind).nextAttempt);}
queue(entry,kinds){if(!this.active(entry))return;for(const kind of kinds)entry.dirty.add(kind);if(entry.sync||entry.debounce||!this.dueKinds(entry).length||!this.allowed()||this.manager.sessions.has(entry.id))return;
entry.debounce=setTimeout(()=>{entry.debounce=null;if(!this.active(entry)||!this.allowed())return;const kinds=this.dueKinds(entry);for(const kind of kinds)entry.dirty.delete(kind);entry.sync=this.synchronize(entry,kinds).finally(()=>{entry.sync=null;if(entry.dirty.size&&this.active(entry))this.queue(entry,[]);});},this.debounceMs);entry.debounce.unref?.();
}
async synchronize(entry,kinds){let valid=true;
for(const kind of kinds){if(!this.active(entry))return;
try{
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,{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);
const runId=this.scanner.store.begin(id,principal.user.username,'todo'),startedAt=new Date(this.clock()).toISOString(),epoch=this.manager.epoch?.(id)||0,entry=this.entries.get(id);
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'||current.owner!==connection.owner||epoch!==(this.manager.epoch?.(id)||0)||!canCommit())fail('连接已暂停或身份已变化,本次对账未提交。',409);
if(principal.user.role!=='admin'&&current.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.code==='TODO_IDENTITY_AMBIGUOUS'?error.message: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};
}
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){entry.lifecycle.transition('STOP');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};