fix: close discovery dispatch and persistent UI state races

This commit is contained in:
abaishu0730 committed 2026-10-19 14:33:09 +08:00
1 parent 0a366f43d6
commit 9d8d6971c1
19 files changed
+237 -77

No files matched your search

+8 -3
View File
@@ -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{
+29 -1
View File
@@ -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);