fix: close discovery dispatch and persistent UI state races
This commit is contained in:
1 parent
0a366f43d6
commit
9d8d6971c1
19 files changed
+237
-77
No files matched your search
@@ -7,6 +7,9 @@ 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});
|
||||
store.executionSources=()=>this.workspace.snapshot().connections.filter(c=>c.status!=='disabled').map(c=>c.id);
|
||||
store.activeDiscoveries=0;
|
||||
for(const scan of store.all('execution-scans'))if(scan.status==='scanning')store.put('execution-scans',{...scan,status:'failed',error:'扫描被重启中断,请重新扫描。'});
|
||||
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')){
|
||||
@@ -72,43 +75,82 @@ class OrderExecutionCoordinator{
|
||||
const capabilities={liveTodo:p.liveTodo===true,pdfExport:p.pdfExport===true&&a.pdfExport===true,automaticArchive:a.automaticArchive===true};
|
||||
for(const key of Object.keys(capabilities))if(!capabilities[key])this.blockers.push(key+' 尚未通过实际探测。');this.store.capabilities=capabilities;return capabilities;
|
||||
}
|
||||
canRetry(task,principal){
|
||||
if(task.conflict||!['failed','blocked'].includes(task.status))return false;
|
||||
try{this.connection(task.connectionId,principal);return true;}
|
||||
catch{return false;}
|
||||
}
|
||||
snapshot(principal){
|
||||
const allowed=id=>{if(!principal||principal.user?.role==='admin')return true;try{return this.workspace.getConnection(id).owner===principal.user?.username;}catch{return false;}};
|
||||
const fields=this.store.fields();fields.samples=fields.samples.filter(sample=>allowed(sample.sample.connectionId));
|
||||
const query=(!this.query.connectionId||allowed(this.query.connectionId))?clone(this.query):{id:'main',status:'idle'};
|
||||
return {tasks:this.store.all('execution-tasks').filter(task=>allowed(task.connectionId)).map(task=>{const order=task.orderId&&this.store.get('orders',task.orderId);return {...task,processName:task.row.processName,title:task.row.title,serialNum:task.row.serialNum,status:['failed','unknown','blocked','capturing','archiving'].includes(task.status)?task.status:order?.status||task.status,error:task.error||order?.error||null};}).reverse(),capabilities:clone(this.store.capabilities),fields,query,blockers:[...this.blockers]};
|
||||
const allowed=id=>{
|
||||
if(!principal||principal.user?.role==='admin')return true;
|
||||
try{return this.workspace.getConnection(id).owner===principal.user?.username;}
|
||||
catch{return false;}
|
||||
};
|
||||
const fields=this.store.fields();
|
||||
fields.samples=fields.samples.filter(sample=>allowed(sample.sample.connectionId));
|
||||
const latest=[this.query,...this.store.all('execution-scans')]
|
||||
.filter(query=>!query.connectionId||allowed(query.connectionId))
|
||||
.sort((a,b)=>String(b.startedAt||'').localeCompare(String(a.startedAt||'')))[0];
|
||||
const query=latest?clone(latest):{id:'main',status:'idle'};
|
||||
const tasks=this.store.all('execution-tasks').filter(task=>allowed(task.connectionId)).map(task=>{
|
||||
const order=task.orderId&&this.store.get('orders',task.orderId);
|
||||
const activeStatus=['failed','unknown','blocked','capturing','archiving'].includes(task.status);
|
||||
return {...task,processName:task.row.processName,title:task.row.title,serialNum:task.row.serialNum,
|
||||
canRetry:this.canRetry(task,principal),status:activeStatus?task.status:order?.status||task.status,
|
||||
error:task.error||order?.error||null};
|
||||
}).reverse();
|
||||
const blockers=[...this.blockers,...this.store.discoveryBlockers(this.store.snapshot().window?.end,allowed)];
|
||||
return {tasks,capabilities:clone(this.store.capabilities),fields,query,blockers};
|
||||
}
|
||||
request(input){if(typeof input?.idempotencyKey!=='string'||!/^[\w:.-]{1,160}$/.test(input.idempotencyKey))fail('请提供有效的操作幂等标识。');}
|
||||
scan(input,principal){
|
||||
// Reserve the shared boundary synchronously, including work queued behind a retry.
|
||||
this.store.activeDiscoveries++;
|
||||
return this.serialize(async()=>{
|
||||
this.request(input);const connection=this.connection(input.connectionId,principal),key=hash(['scan',connection.id,principal.user.username,input.idempotencyKey]);
|
||||
if(this.store.get('execution-requests',key))return this.snapshot(principal);
|
||||
this.query={id:'main',status:'scanning',connectionId:connection.id,startedAt:this.now()};this.store.put('execution-query',this.query);
|
||||
this.query={id:'main',status:'scanning',connectionId:connection.id,startedAt:this.now()};this.store.put('execution-query',this.query);this.store.put('execution-scans',{...this.query,id:connection.id});
|
||||
try{
|
||||
const rows=await this.provider.scan(connection,principal);if(!Array.isArray(rows))throw Error('待办提供器返回格式无效。');
|
||||
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));
|
||||
if(!rules.length)continue;
|
||||
// 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;
|
||||
task.error=order.error||null;
|
||||
this.persist(task);
|
||||
if(['pending','batched'].includes(order.status))await this.checkArchivedRuntime(task,order,connection,principal);
|
||||
continue;
|
||||
let considered=0;const observed=new Set(),discovered=[];
|
||||
// Commit the entire discovery set before probes, captures, exceptions or archives yield.
|
||||
this.store.transaction(()=>{
|
||||
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));
|
||||
if(!rules.length)continue;
|
||||
// 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);}
|
||||
discovered.push(task);
|
||||
}
|
||||
this.query={...this.query,rowCount:rows.length,targetCount:considered,processedCount:0,discoveredAt:this.now()};
|
||||
this.store.put('execution-query',this.query);this.store.put('execution-scans',{...this.query,id:connection.id});
|
||||
});
|
||||
await this.refreshCapabilities();
|
||||
for(const task of discovered){
|
||||
try{
|
||||
if(task.conflict){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;
|
||||
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);
|
||||
}finally{
|
||||
this.query.processedCount++;
|
||||
this.store.put('execution-query',this.query);
|
||||
this.store.put('execution-scans',{...this.query,id:connection.id});
|
||||
}
|
||||
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
|
||||
@@ -124,9 +166,9 @@ class OrderExecutionCoordinator{
|
||||
}
|
||||
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);}
|
||||
finally{this.store.put('execution-query',this.query);this.store.put('execution-scans',{...this.query,id:connection.id});}
|
||||
return this.snapshot(principal);
|
||||
});
|
||||
}).finally(()=>{this.store.activeDiscoveries--;}).then(()=>this.snapshot(principal));
|
||||
}
|
||||
async execute(task,connection,principal){
|
||||
try{
|
||||
@@ -150,13 +192,28 @@ class OrderExecutionCoordinator{
|
||||
await this.exception(task,connection,true);
|
||||
}catch(error){const uncertain=task.status==='archiving';task.status=uncertain&&this.archive.supportsRecovery!==true?'unknown':'failed';task.error=uncertain?'归档结果待核验,需人工受控恢复:'+error.message:error.message;this.persist(task);await this.exception(task,connection,false);}
|
||||
}
|
||||
retry(id,input,principal){return this.serialize(async()=>{
|
||||
this.request(input);const task=this.store.get('execution-tasks',id);if(!task)fail('执行任务不存在。',404);const connection=this.connection(task.connectionId,principal);
|
||||
const requestId=hash(['retry',id,principal.user.username,input.idempotencyKey]),inputHash=hash([input.version,input.note]),previous=this.store.get('execution-requests',requestId);if(previous){if(previous.inputHash!==inputHash)fail('幂等标识已用于不同的重试请求。',409);return this.snapshot(principal);}
|
||||
if(input.version!==task.version)fail('任务版本已变化,请刷新。',409);if(typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请填写至少5字重试依据。');
|
||||
if(!['failed','blocked'].includes(task.status)||task.conflict)fail('此任务结果未明确或不允许重试。',409);
|
||||
this.store.audit(principal.user.username,'人工重试订单任务',id+':'+input.note.trim());await this.execute(task,connection,principal);this.store.put('execution-requests',{id:requestId,taskId:id,inputHash,at:this.now()});return this.snapshot(principal);
|
||||
});}
|
||||
retry(id,input,principal){
|
||||
return this.serialize(async()=>{
|
||||
this.request(input);
|
||||
const task=this.store.get('execution-tasks',id);
|
||||
if(!task)fail('执行任务不存在。',404);
|
||||
const connection=this.connection(task.connectionId,principal);
|
||||
const requestId=hash(['retry',id,principal.user.username,input.idempotencyKey]);
|
||||
const inputHash=hash([input.version,input.note]);
|
||||
const previous=this.store.get('execution-requests',requestId);
|
||||
if(previous){
|
||||
if(previous.inputHash!==inputHash)fail('幂等标识已用于不同的重试请求。',409);
|
||||
return this.snapshot(principal);
|
||||
}
|
||||
if(input.version!==task.version)fail('任务版本已变化,请刷新。',409);
|
||||
if(typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请填写至少5字重试依据。');
|
||||
if(!['failed','blocked'].includes(task.status)||task.conflict)fail('此任务结果未明确或不允许重试。',409);
|
||||
this.store.audit(principal.user.username,'人工重试订单任务',id+':'+input.note.trim());
|
||||
await this.execute(task,connection,principal);
|
||||
this.store.put('execution-requests',{id:requestId,taskId:id,inputHash,at:this.now()});
|
||||
return this.snapshot(principal);
|
||||
});
|
||||
}
|
||||
async exception(task,connection,recovered){
|
||||
try{await this.updateException(task,connection,recovered);}catch(error){task.exceptionError=error.message;this.persist(task);this.store.audit('订单执行器','异常关联更新失败',task.id);}
|
||||
}
|
||||
|
||||
@@ -48,14 +48,15 @@ class OrderRuleDispatcher{
|
||||
// A busy mailbox cannot consume the slot or reserve any orders. Recovery
|
||||
// applies only to this exact business window, never to earlier history.
|
||||
const window=windowForCutoff(cutoff,schedule,calendar);
|
||||
const existing=(this.store.snapshot().batches||[]).filter(batch=>sameWindow(batch,cutoff,window));
|
||||
if(this.store.discoveryBlockers(cutoff).length)return;
|
||||
const fresh=this.store.prepare(cutoff,'系统调度',window).filter(batch=>sameWindow(batch,cutoff,window));
|
||||
const batches=[...new Map([...existing,...fresh].map(batch=>[batch.id,freeze(structuredClone(batch))])).values()];
|
||||
const existing=(this.store.snapshot().batches||[]).filter(batch=>sameWindow(batch,cutoff,window));
|
||||
const batches=[...new Map([...fresh,...existing].map(batch=>[batch.id,freeze(structuredClone(batch))])).values()];
|
||||
let interrupted=false;
|
||||
for(const batch of batches){
|
||||
if(!this.ready()){interrupted=true;break;}
|
||||
if(batch.status!=='prepared')continue;
|
||||
await this.dispatch(batch,config);
|
||||
if(await this.dispatch(batch,config)===false){interrupted=true;break;}
|
||||
}
|
||||
if(!interrupted)this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};
|
||||
});
|
||||
@@ -88,6 +89,9 @@ class OrderRuleDispatcher{
|
||||
transport=this.mail.smtpFactory(channel.smtp);
|
||||
this.mail.clients?.add(transport);
|
||||
await transport.verify();
|
||||
// Scan readiness may change while SMTP verification is pending. Keep this
|
||||
// unsent reservation recoverable instead of turning a scan barrier into failure.
|
||||
if(!manual&&(this.store.discoveryBlockers(batch.cutoff).length||this.store.batchIncomplete(batch)))return false;
|
||||
if(manual?this.stopped||!this.providersReady()||!this.store.providersReady():!this.ready()||this.store.settings().channelId!==config.channelId)throw Error('发送已暂停或配置已变更。');
|
||||
if(!manual&&this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。');
|
||||
this.mail.store.guard(channel.id,channel.version);
|
||||
@@ -97,6 +101,7 @@ class OrderRuleDispatcher{
|
||||
const partial=result?.rejected?.length||[...batch.to,...batch.cc].some(address=>!accepted.has(address.toLowerCase()));
|
||||
this.store.finishSending(batch.id,partial?'unknown':'sent',partial?'部分收件人未被服务器接受,请核对邮件记录后处理。':'邮件服务器已接受全部收件人;最终送达请以邮件记录为准。');
|
||||
}catch(error){
|
||||
if(!sending&&error.code==='DISCOVERY_INCOMPLETE')return false;
|
||||
const rejected=error.code==='EENVELOPE'&&error.command==='RCPT TO'&&Array.isArray(error.rejected)&&error.rejected.length>0&&(!error.accepted||error.accepted.length===0)&&[...batch.to,...batch.cc].every(address=>error.rejected.some(r=>String(r.address||r).toLowerCase()===address.toLowerCase()));
|
||||
this.store.finishSending(batch.id,sending&&!rejected?'unknown':'failed',sending&&!rejected?'发送结果待核实,请核对邮件服务器记录后决定是否重试。':`发送前验证失败:${error.code==='ENOENT'?'归档文件不存在。':error.message==='归档文件校验失败。'?error.message:'请检查归档证据、SMTP 与启用状态。'}`);
|
||||
}finally{
|
||||
|
||||
@@ -145,6 +145,27 @@ class RuleStore{
|
||||
order.error=order.status==='blocked'?'待办接入、PDF 导出和自动归档待联调。':null;order.updatedAt=this.now();
|
||||
this.put('orders',order);this.audit(actor,'应用当前规则重新识别',id+':'+input.note.trim());return order;
|
||||
});}
|
||||
discoveryBlockers(cutoff,allowed=()=>true){
|
||||
if(!this.executionSources)return [];
|
||||
const blockers=[];
|
||||
if(this.activeDiscoveries>0)blockers.push('待办扫描尚未完成,不能冻结或发送不完整类别。');
|
||||
const window=cutoff?windowForCutoff(cutoff,this.schedule(),this.calendar()):null;
|
||||
const relevant=this.all('execution-tasks').filter(t=>!window||inWindow(t.row?.receivedAt,window));
|
||||
const sources=new Set([...this.executionSources(),...relevant.filter(t=>!['sent','ignored'].includes(t.status)).map(t=>t.connectionId)]);
|
||||
for(const id of sources){
|
||||
if(!allowed(id))continue;
|
||||
const scan=this.get('execution-scans',id);
|
||||
if(scan?.status!=='complete')blockers.push('连接 '+id+' 尚无完整成功扫描'+(scan?.error?':'+scan.error:'。'));
|
||||
else if(cutoff&&Date.parse(scan.startedAt)<Date.parse(cutoff))blockers.push('连接 '+id+' 需要截止时点之后启动的完整扫描。');
|
||||
}
|
||||
return blockers;
|
||||
}
|
||||
categoryIncomplete(categoryId,window){
|
||||
return this.all('execution-tasks').some(task=>task.categoryIds?.includes(categoryId)&&(!Number.isFinite(Date.parse(task.row?.receivedAt))||inWindow(task.row?.receivedAt,window))&&(task.conflict||['identified','blocked','failed','unknown','capturing','archiving'].includes(task.status)||task.runtimeCheck?.status==='blocked'));
|
||||
}
|
||||
batchIncomplete(batch){
|
||||
return this.categoryIncomplete(batch.categoryId,batch.window)||this.all('orders').some(order=>order.categoryId===batch.categoryId&&inWindow(order.event?.receivedAt||order.sample?.receivedAt,batch.window)&&order.status!=='ignored'&&!batch.orderIds.includes(order.id));
|
||||
}
|
||||
prepare(cutoff,actor,requestedWindow){return this.transaction(()=>{
|
||||
if(!validDate(cutoff))fail('请选择包含时区的有效发送截止时间。');
|
||||
const window=windowForCutoff(cutoff,this.schedule(),this.calendar());
|
||||
@@ -152,6 +173,12 @@ class RuleStore{
|
||||
for(const batch of this.all('batches'))if(batch.status==='prepared'&&Date.parse(batch.cutoff)<Date.parse(cutoff)){
|
||||
batch.status=transition('batch',batch.status,'cancel');batch.error='已错过原发送时段,历史订单不补发。';this.put('batches',batch);this.updateBatchOrders(batch,'ignored',batch.error);
|
||||
}
|
||||
if(this.discoveryBlockers(cutoff).length)return [];
|
||||
// A never-sent partial reservation may be replaced only by one complete batch.
|
||||
for(const batch of this.all('batches'))if(batch.status==='prepared'&&!batch.manual&&Date.parse(batch.cutoff)===Date.parse(cutoff)&&this.batchIncomplete(batch)){
|
||||
batch.status='cancelled';batch.version=(batch.version||1)+1;batch.resolution={resolution:'retry',note:'发现同类别新增订单,完整重建未发送批次。'};this.put('batches',batch);
|
||||
for(const id of batch.orderIds){const order=this.get('orders',id);if(order?.batchId===batch.id){order.status='pending';order.batchId=null;this.put('orders',order);}}
|
||||
}
|
||||
const grouped=new Map(),batches=[];
|
||||
for(const order of this.all('orders')){
|
||||
if(!['identified','preparing','archived','pending','blocked'].includes(order.status)||!order.categoryId)continue;
|
||||
@@ -161,7 +188,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)||task.runtimeCheck?.status==='blocked')&&inWindow(task.row?.receivedAt,window)))continue;
|
||||
if(this.categoryIncomplete(orders[0].categoryId,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;
|
||||
@@ -181,6 +208,7 @@ class RuleStore{
|
||||
beginSending(id,{manual=false}={}){return this.transaction(()=>{
|
||||
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);
|
||||
if(!(manual&&batch.manual)&&(this.discoveryBlockers(batch.cutoff).length||this.batchIncomplete(batch)))throw Object.assign(Error('待办扫描或类别订单尚不完整,等待完整扫描与恢复。'),{status:409,code:'DISCOVERY_INCOMPLETE'});
|
||||
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);
|
||||
|
||||
Reference in new issue
Block a user