88 lines
12 KiB
JavaScript
88 lines
12 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');
|
|
function todoArrival(row){
|
|
if(row.source!=='todo'||!['portal-v4','portal-v8'].includes(row.portalSource)||row.instanceId==null||row.revision==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),revision:row.revision,processVersion:row.processVersion||'',recordKey:JSON.stringify([row.instanceId,row.taskId,row.revision])};
|
|
}
|
|
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;
|
|
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?.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:{}};
|
|
}
|
|
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,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(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;entry.status=status;entry.nextRetry=this.clock()+(delay??this.retryMs[Math.min(entry.failures++,this.retryMs.length-1)]);}
|
|
connect(entry,connection){
|
|
const attempt=++entry.attempt;let closed=false;entry.status=entry.failures?'reconnecting':'connecting';
|
|
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))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.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.attempt===attempt){entry.handle=null;this.retry(entry);}}});
|
|
});
|
|
if(!handle)return;if(!this.active(entry)||closed){await handle.stop();return;}
|
|
entry.handle=handle;entry.connectedAt=this.clock();entry.status='listening';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))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{
|
|
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;
|
|
}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){
|
|
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'||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};
|
|
}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()]);}
|
|
}
|
|
module.exports={BpmArrivalMonitor,todoArrival};
|