fix: restore archived task progress and runtime gates after restart
This commit is contained in:
1 parent
eb92a4f033
commit
cc1ade2261
3 files changed
+102
-8
No files matched your search
@@ -7,9 +7,10 @@ const clone=value=>structuredClone(value);
|
||||
class OrderExecutionCoordinator{
|
||||
constructor({store,workspace,provider,archive,mail,dashboard,clock=()=>new Date(),settings=()=>({}),calendar=()=>[],onException,systemPrincipal}){
|
||||
Object.assign(this,{store,workspace,provider,archive,mail,dashboard,clock,settings,calendar,onException,systemPrincipal});
|
||||
this.tail=Promise.resolve();this.stopped=false;this.timer=null;this.query=store.get('execution-query','main')||{id:'main',status:'idle'};this.blockers=[];
|
||||
this.tail=Promise.resolve();this.stopped=false;this.timer=null;this.query=store.get('execution-query','main')||{id:'main',status:'idle'};this.blockers=[];this.runtimeRuleChecks=new Set();
|
||||
if(this.query.status==='scanning'){this.query={...this.query,status:'failed',error:'服务重启中断了上次只读扫描,请重新扫描。',finishedAt:this.now()};store.put('execution-query',this.query);}
|
||||
for(const task of store.all('execution-tasks')){
|
||||
if(this.reconcileArchive(task))continue;
|
||||
if(task.status==='archiving'){task.status=archive.supportsRecovery===true?'failed':'unknown';task.step='archive';task.error='归档中断,结果待核验,需人工受控恢复。';this.persist(task);}
|
||||
else if(task.status==='capturing'){task.status='failed';task.error='只读采集已中断,可重新采集。';this.persist(task);}
|
||||
}
|
||||
@@ -18,6 +19,50 @@ class OrderExecutionCoordinator{
|
||||
}
|
||||
now(){return this.clock().toISOString();}
|
||||
persist(task){task.version=(task.version||0)+1;task.updatedAt=this.now();task.history=[...(task.history||[]),{at:task.updatedAt,status:task.status,step:task.step,error:task.error||null}].slice(-100);this.store.put('execution-tasks',task);return task;}
|
||||
reconcileArchive(task){
|
||||
if(task.conflict||task.step!=='archive'||!['archiving','unknown','failed'].includes(task.status))return false;
|
||||
const order=task.orderId&&this.store.get('orders',task.orderId);
|
||||
// recordArchive commits its validated receipt and pending state together. That
|
||||
// committed progress is authoritative even when the following task write died.
|
||||
if(!order?.archive||!['pending','batched','sent','unknown','ignored'].includes(order.status))return false;
|
||||
task.status=order.status;
|
||||
task.step='complete';
|
||||
task.error=order.error||null;
|
||||
task.reconciledAt=this.now();
|
||||
this.persist(task);
|
||||
return true;
|
||||
}
|
||||
validateCapture(task,connection,{sample,snapshot}){
|
||||
for(const key of ['source','instanceId','taskId','revision','processName','nodeName','receivedAt']){
|
||||
if(String(sample?.[key])!==String(task.row[key]))throw Error('采集样本与待办事件身份不一致。');
|
||||
}
|
||||
if(sample.connectionId!==connection.id)throw Error('采集样本连接身份不一致。');
|
||||
if(!snapshot||snapshot.processVersion!==sample.processVersion||!Array.isArray(snapshot.fields))throw Error('采集样本流程版本或实际字段证据不一致。');
|
||||
}
|
||||
async checkArchivedRuntime(task,order,connection,principal,{forceCapture=false}={}){
|
||||
const published=this.store.get('rules',order.ruleSnapshot?.id)?.published;
|
||||
if(published?.status!=='enabled')return;
|
||||
try{
|
||||
// A cold provider must really read the authorized form to establish its
|
||||
// capture capability; successful stored archives are never exported again.
|
||||
if(forceCapture||(await this.provider.capabilities()).pdfExport!==true){
|
||||
const captured=await this.provider.capture(connection,principal,clone(task.row));
|
||||
this.validateCapture(task,connection,captured);
|
||||
}
|
||||
const ruleKey=hash([order.ruleSnapshot.id,order.ruleSnapshot.version,order.ruleSnapshot.archiveDirectory]);
|
||||
const probeRule=this.runtimeRuleChecks.has(ruleKey)&&this.store.providersReady()?undefined:order.ruleSnapshot;
|
||||
await this.refreshCapabilities(probeRule);
|
||||
if(this.store.providersReady())this.runtimeRuleChecks.add(ruleKey);
|
||||
task.runtimeCheck={at:this.now(),status:this.store.providersReady()?'ready':'blocked'};
|
||||
task.error=this.store.providersReady()?order.error||null:'已归档订单的待办采集或归档运行条件尚未通过复核。';
|
||||
}catch(error){
|
||||
this.store.capabilities={...this.store.capabilities,pdfExport:false,automaticArchive:false};
|
||||
this.blockers.push('已归档订单运行条件复核失败:'+error.message);
|
||||
task.runtimeCheck={at:this.now(),status:'blocked',error:error.message};
|
||||
task.error='已归档订单运行条件复核失败:'+error.message;
|
||||
}
|
||||
this.persist(task);
|
||||
}
|
||||
serialize(work){if(this.stopped)return Promise.reject(Object.assign(Error('订单执行服务正在关闭。'),{status:503}));const operation=this.tail.catch(()=>{}).then(work);this.tail=operation;return operation;}
|
||||
connection(id,principal){const c=this.workspace.getConnection(id);if(!principal?.sessionId||!['admin','operator'].includes(principal?.user?.role)||(principal.user.role!=='admin'&&c.owner!==principal.user.username))fail('仅连接负责人或管理员可以扫描或重试。',403);if(c.status==='disabled')fail('连接已停用。',409);return c;}
|
||||
async refreshCapabilities(rule){
|
||||
@@ -41,7 +86,7 @@ class OrderExecutionCoordinator{
|
||||
this.query={id:'main',status:'scanning',connectionId:connection.id,startedAt:this.now()};this.store.put('execution-query',this.query);
|
||||
try{
|
||||
const rows=await this.provider.scan(connection,principal);if(!Array.isArray(rows))throw Error('待办提供器返回格式无效。');
|
||||
await this.refreshCapabilities();let considered=0;
|
||||
await this.refreshCapabilities();let considered=0;const observed=new Set();
|
||||
for(const row of rows){
|
||||
if(row.source!=='todo')continue;
|
||||
const rules=this.store.all('rules').map(r=>r.published?.status==='enabled'?r.published:r.draft).filter(rule=>rule.processNames.includes(row.processName)&&rule.nodeNames.includes(row.nodeName));
|
||||
@@ -49,14 +94,34 @@ class OrderExecutionCoordinator{
|
||||
// Historical rows are ignored before any capture or export.
|
||||
const window=this.store.snapshot().window;if(window&&Number.isFinite(Date.parse(row.receivedAt))&&Date.parse(row.receivedAt)<Date.parse(window.start))continue;
|
||||
considered++;const id=hash([connection.id,row.source,String(row.instanceId),String(row.taskId),String(row.revision)]);
|
||||
observed.add(id);
|
||||
let task=this.store.get('execution-tasks',id);
|
||||
if(!task){task={id,version:0,connectionId:connection.id,owner:connection.owner||'',row:clone(row),categoryIds:[...new Set(rules.map(r=>r.categoryId))],status:'identified',step:'capture',createdAt:this.now()};this.persist(task);}
|
||||
if(hash(task.row)!==hash(row)){task.status='blocked';task.error='同一事件修订内容冲突,需核对源版本。';task.conflict=true;this.persist(task);await this.exception(task,connection,false);continue;}
|
||||
this.reconcileArchive(task);
|
||||
if(task.conflict||task.status==='unknown'||task.step==='archive'&&task.status==='failed')continue;
|
||||
const order=task.orderId&&this.store.get('orders',task.orderId);
|
||||
if(order&&['pending','batched','sent','unknown','ignored'].includes(order.status)){task.status=order.status;this.persist(task);continue;}
|
||||
if(order&&['pending','batched','sent','unknown','ignored'].includes(order.status)){
|
||||
task.status=order.status;
|
||||
task.error=order.error||null;
|
||||
this.persist(task);
|
||||
if(['pending','batched'].includes(order.status))await this.checkArchivedRuntime(task,order,connection,principal);
|
||||
continue;
|
||||
}
|
||||
await this.execute(task,connection,principal);
|
||||
}
|
||||
// Already archived work can outlive its todo row. Recheck its original
|
||||
// read-only source through the provider; an unavailable source remains an
|
||||
// explicit runtime blocker and never causes another archive export.
|
||||
for(const task of this.store.all('execution-tasks')){
|
||||
if(task.connectionId!==connection.id||observed.has(task.id)||task.conflict)continue;
|
||||
this.reconcileArchive(task);
|
||||
const order=task.orderId&&this.store.get('orders',task.orderId);
|
||||
if(!order?.archive||!['pending','batched'].includes(order.status))continue;
|
||||
const window=this.store.snapshot().window;
|
||||
if(window&&Date.parse(order.event.receivedAt)<Date.parse(window.start))continue;
|
||||
await this.checkArchivedRuntime(task,order,connection,principal,{forceCapture:true});
|
||||
}
|
||||
this.query={...this.query,status:'complete',finishedAt:this.now(),rowCount:rows.length,targetCount:considered};this.store.put('execution-requests',{id:key,at:this.now()});
|
||||
}catch(error){this.query={...this.query,status:'failed',error:error.message,finishedAt:this.now()};throw error;}
|
||||
finally{this.store.put('execution-query',this.query);}
|
||||
@@ -68,8 +133,7 @@ class OrderExecutionCoordinator{
|
||||
if(!task.sampleId){
|
||||
task.status='capturing';task.step='capture';this.persist(task);
|
||||
const {sample,snapshot}=await this.provider.capture(connection,principal,clone(task.row));
|
||||
for(const key of ['source','instanceId','taskId','revision','processName','nodeName','receivedAt'])if(String(sample[key])!==String(task.row[key]))throw Error('采集样本与待办事件身份不一致。');
|
||||
if(sample.connectionId!==connection.id)throw Error('采集样本连接身份不一致。');
|
||||
this.validateCapture(task,connection,{sample,snapshot});
|
||||
const captured=this.store.recordCapture({sample,snapshot,taskId:task.id});task.sampleId=captured.id;task.step='identify';this.persist(task);
|
||||
}
|
||||
const captured=this.store.get('capture-samples',task.sampleId);let order;
|
||||
|
||||
@@ -161,7 +161,7 @@ class RuleStore{
|
||||
if(!grouped.has(order.categoryId))grouped.set(order.categoryId,[]);grouped.get(order.categoryId).push(order);
|
||||
}
|
||||
for(const orders of grouped.values()){
|
||||
if(this.all('execution-tasks').some(task=>task.categoryIds?.includes(orders[0].categoryId)&&['blocked','failed','unknown','capturing','archiving'].includes(task.status)&&inWindow(task.row?.receivedAt,window)))continue;
|
||||
if(this.all('execution-tasks').some(task=>task.categoryIds?.includes(orders[0].categoryId)&&(['blocked','failed','unknown','capturing','archiving'].includes(task.status)||task.runtimeCheck?.status==='blocked')&&inWindow(task.row?.receivedAt,window)))continue;
|
||||
const rule=orders[0].ruleSnapshot;if(!rule)continue;
|
||||
if(this.all('batches').some(b=>b.categoryId===rule.categoryId&&Date.parse(b.cutoff)===Date.parse(cutoff)&&!(b.status==='cancelled'&&b.resolution?.resolution==='retry')))continue;
|
||||
const published=this.get('rules',rule.id)?.published;
|
||||
@@ -182,6 +182,7 @@ class RuleStore{
|
||||
const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
|
||||
if(!(manual&&batch.manual)&&this.get('rules',batch.ruleSnapshot.id)?.published?.status!=='enabled')fail('该类别规则已暂停,批次不能进入发送。',409);
|
||||
const orders=batch.orderIds.map(oid=>this.get('orders',oid));
|
||||
if(this.all('execution-tasks').some(task=>batch.orderIds.includes(task.orderId)&&task.runtimeCheck?.status==='blocked'))fail('已归档订单的运行条件复核未通过,批次不能进入发送。',409);
|
||||
if(orders.some(o=>!o||o.batchId!==id||o.status!=='batched'))fail('批次订单预留已变化。',409);
|
||||
batch.version=(batch.version||1)+1;batch.status=transition('batch',batch.status,'send');this.put('batches',batch);return batch;
|
||||
});}
|
||||
|
||||
Reference in new issue
Block a user