fix: keep BPM reconciliation responsive and task based

This commit is contained in:
abaishu0730 committed 2026-10-23 13:00:34 +08:00
1 parent 8cb6a32876
commit 1848a6c10b
5 files changed
+165 -9

No files matched your search

+4 -4
View File
@@ -4,8 +4,8 @@ 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])};
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]}){
@@ -16,7 +16,7 @@ class BpmArrivalMonitor{
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);}
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,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)};
@@ -85,7 +85,7 @@ class BpmArrivalMonitor{
// 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;}
}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){
+10 -1
View File
@@ -27,7 +27,16 @@ class BpmScanStore{
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);}
// Older todo rows used an instance/task/revision storage key. Reuse their
// original key so an absent or newly reported revision cannot duplicate a task.
const priorTodo=this.db.prepare("SELECT task_id AS storageKey,value FROM arrivals WHERE connection_id=? AND source=? AND CAST(json_extract(value,'$.taskId') AS TEXT)=? LIMIT 2");
for(const row of rows){
if(!row.arrivalDay||!row.taskId||!row.source)throw invalid('流程记录无效。');
const todo=row.source.startsWith('todo:'),matches=todo?priorTodo.all(connectionId,row.source,String(row.taskId)):[];
if(matches.length>1)throw Object.assign(new Error('此待办对应多条旧到达记录,请人工核验任务身份后再同步。'),{status:409,code:'TODO_IDENTITY_AMBIGUOUS'});
const existing=matches[0],key=todo?(existing?.storageKey||String(row.taskId)):(row.recordKey||row.taskId),old=existing||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};
});}
+7 -4
View File
@@ -167,6 +167,7 @@ class OrderExecutionCoordinator{
const rows=trustedRows===undefined?await this.provider.scan(connection,principal):clone(trustedRows);if(!Array.isArray(rows))throw Error('待办提供器返回格式无效。');
if(trustedRows===undefined&&eligibility.state(this.store))eligibility.recordCurrentScan(this.store,{connectionId:connection.id,rows,startedAt:this.query.startedAt,finishedAt:this.now()});
let considered=0;const observed=new Set(),discovered=[];
const window=this.store.snapshot().window;
// Commit the entire discovery set before probes, captures, exceptions or archives yield.
this.store.transaction(()=>{
for(const raw of rows){
@@ -186,7 +187,6 @@ class OrderExecutionCoordinator{
const rules=this.store.all('rules').map(r=>this.store.executionRule(r)||(!testing?r.draft:null)).filter(rule=>rule&&matchesScope(rule,row));
if(!rules.length&&!task)continue;
const id=task?.id||taskIdentity.taskIdentity(row);
const window=this.store.snapshot().window;
const baseline=this.store.settings().processingSince;
const received=Date.parse(eligibleAt);
// Pre-activation backlog requires explicit admission. Eligible missed-window work is
@@ -251,7 +251,6 @@ class OrderExecutionCoordinator{
this.reconcileArchive(task);
const order=task.orderId&&this.store.get('orders',task.orderId);
if(!needsRuntimeCheck(order))continue;
const window=this.store.snapshot().window;
if(window&&!reserved(order)&&Date.parse(eligibility.orderTime(this.store,order))<Date.parse(window.start))continue;
await this.checkArchivedRuntime(task,order,connection,principal);
}
@@ -427,7 +426,7 @@ class OrderExecutionCoordinator{
}
}
async background(){
if(!this.systemPrincipal||!this.store.settings().processingEnabled)return;
if(this.stopped||!this.systemPrincipal||!this.store.settings().processingEnabled)return;
const day=new Date(this.clock().getTime()+8*3600000).toISOString().slice(0,10);
if(!dayPolicy(day,this.settings()?.schedule||{},this.calendar()).scan)return;
for(const connection of this.workspace.snapshot().connections||[]){
@@ -437,8 +436,12 @@ class OrderExecutionCoordinator{
.filter(hint=>hint.connectionId===connection.id&&hint.status==='pending')
.sort((a,b)=>Date.parse(a.startedAt)-Date.parse(b.startedAt));
for(const hint of pending){
if(!this.store.settings().processingEnabled)return;
if(this.stopped||!this.store.settings().processingEnabled)return;
await this.consumeDiscovery(hint,connection);
// Trusted scans may finish entirely in microtasks. Let health checks and
// pause/stop requests run before consuming the next durable delivery.
await new Promise(resolve=>setImmediate(resolve));
if(this.stopped||!this.store.settings().processingEnabled)return;
}
const last=this.store.get('execution-scans',connection.id);
const window=this.store.snapshot().window;