fix: make order processing authorized and recoverable
This commit is contained in:
1 parent
0ab7d62aa6
commit
7e42a6dcc6
15 files changed
+219
-129
No files matched your search
@@ -6,10 +6,6 @@ const {nextSlots}=require('../../shared/schedule.cjs');
|
||||
const {windowForCutoff}=require('./window.cjs');
|
||||
const {fail}=require('./validation.cjs');
|
||||
|
||||
function sameWindow(batch,cutoff,window){
|
||||
return batch.status==='prepared'&&Date.parse(batch.cutoff)===Date.parse(cutoff)&&batch.window?.start===window.start&&batch.window?.end===window.end&&batch.window?.startInclusive===true&&batch.window?.endInclusive===false;
|
||||
}
|
||||
|
||||
function freeze(value){
|
||||
if(value&&typeof value==='object'){for(const item of Object.values(value))freeze(item);Object.freeze(value);}
|
||||
return value;
|
||||
@@ -32,35 +28,28 @@ class OrderRuleDispatcher{
|
||||
return task;
|
||||
}
|
||||
async perform(now){
|
||||
for(const batch of this.store.snapshot().batches||[])if(batch.status==='prepared'&&!batch.manual&&now-Date.parse(batch.cutoff)>1800000)this.store.finishSending(batch.id,'failed','冻结发送队列超过30分钟,请负责人核验后受控补发。');
|
||||
if(!this.ready())return;
|
||||
const config=freeze(structuredClone(this.store.settings()));
|
||||
const schedule=this.settings()?.schedule,calendar=this.calendar();
|
||||
const config=freeze(structuredClone(this.store.settings())),schedule=this.settings()?.schedule,calendar=this.calendar();
|
||||
if(!schedule?.times?.length)return;
|
||||
const signature=JSON.stringify([schedule,calendar]);
|
||||
if(!this.schedule||this.schedule.signature!==signature){this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};return;}
|
||||
if(!this.schedule.next||Date.parse(this.schedule.next)>now.getTime())return;
|
||||
const cutoff=this.schedule.next;
|
||||
if(now.getTime()-Date.parse(cutoff)>60000){this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};return;}
|
||||
if(!this.ready())return;
|
||||
try{
|
||||
await this.mail.exclusive(config.channelId,async()=>{
|
||||
if(!this.ready())return;
|
||||
// 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);
|
||||
if(this.store.discoveryBlockers(cutoff).length)return;
|
||||
const fresh=this.store.prepare(cutoff,'系统调度',window).filter(batch=>sameWindow(batch,cutoff,window));
|
||||
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;
|
||||
if(await this.dispatch(batch,config)===false){interrupted=true;break;}
|
||||
}
|
||||
if(!interrupted)this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};
|
||||
});
|
||||
}catch(error){if(error.status!==409)throw error;}
|
||||
if(!this.schedule||this.schedule.signature!==signature){const current=require('./window.cjs').upcomingWindow(now,schedule,calendar);this.schedule={signature,next:current?.available?current.end:nextSlots(schedule,now,1,calendar)[0]};}
|
||||
const cutoff=this.schedule.next,canPrepare=cutoff&&now-Date.parse(cutoff)>=0&&now-Date.parse(cutoff)<=60000;
|
||||
const queued=(this.store.snapshot().batches||[]).some(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
|
||||
if(!canPrepare&&!queued)return;
|
||||
try{await this.mail.exclusive(config.channelId,async()=>{
|
||||
if(!this.ready())return;
|
||||
if(canPrepare&&!this.store.discoveryBlockers(cutoff).length){const window=windowForCutoff(cutoff,schedule,calendar);this.store.prepare(cutoff,'系统调度',window);}
|
||||
// A frozen collection is immutable. Queue time is distinct from collection time.
|
||||
const batches=(this.store.snapshot().batches||[]).filter(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
|
||||
for(const batch of batches){if(!this.ready())break;
|
||||
let expected;try{expected=windowForCutoff(batch.cutoff,schedule,calendar);}catch{continue;}
|
||||
const legacyStart=new Date(Date.parse(batch.cutoff)+8*3600000).toISOString().slice(0,10)+'T00:00:00+08:00';
|
||||
if(!batch.window||batch.window.end!==expected.end||![Date.parse(expected.start),Date.parse(legacyStart)].includes(Date.parse(batch.window.start))||batch.window.startInclusive!==true||batch.window.endInclusive!==false)continue;
|
||||
if(batch.createdAt&&(Date.parse(batch.createdAt)>Date.parse(batch.cutoff)+60000||Date.parse(batch.createdAt)<Date.parse(batch.cutoff)))continue;if(await this.dispatch(freeze(structuredClone(batch)),config)===false)continue;}
|
||||
});}catch(error){this.store.recordIssue?.('dispatch:'+String(cutoff),{component:'mail',error:error.message,cutoff});if(error.status!==409)throw error;}
|
||||
// Keep the current slot during its collection allowance so repaired categories retry.
|
||||
if(cutoff&&this.clock()-Date.parse(cutoff)>60000)this.schedule={signature,next:nextSlots(schedule,this.clock(),1,calendar)[0]};
|
||||
}
|
||||
async attachments(batch,config){
|
||||
const result=[];let total=0;
|
||||
@@ -83,7 +72,7 @@ class OrderRuleDispatcher{
|
||||
this.store.finishSending(batch.id,'failed','批次固定的发件邮箱与当前渠道不同,请核实邮箱设置后生成新批次。');return;
|
||||
}
|
||||
const attachments=await this.attachments(batch,config);
|
||||
if(!manual&&this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。');
|
||||
if(!manual&&this.clock().getTime()-Date.parse(batch.cutoff)>1800000)throw Error('冻结发送队列超过30分钟。');
|
||||
const channel=freeze(structuredClone(this.mail.store.channelSecret(config.channelId)));
|
||||
if(channel.readOnly)throw Error('只读邮箱不能用于分类通知发送。');
|
||||
transport=this.mail.smtpFactory(channel.smtp);
|
||||
@@ -93,7 +82,7 @@ class OrderRuleDispatcher{
|
||||
// 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('本时段发送宽限已结束。');
|
||||
if(!manual&&this.clock().getTime()-Date.parse(batch.cutoff)>1800000)throw Error('冻结发送队列超过30分钟。');
|
||||
this.mail.store.guard(channel.id,channel.version);
|
||||
this.store.beginSending(batch.id,{manual});sending=true;
|
||||
const result=await transport.sendMail({from:{address:channel.email,name:channel.name},to:[...batch.to],cc:[...batch.cc],subject:batch.subject,text:batch.text,html:batch.html,attachments,messageId:`<${batch.id}@${channel.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true});
|
||||
@@ -135,7 +124,7 @@ class OrderRuleDispatcher{
|
||||
}
|
||||
start(){
|
||||
if(this.timer||this.stopped)return;
|
||||
this.timer=setInterval(()=>this.tick().catch(()=>{}),30000);this.timer.unref?.();
|
||||
this.timer=setInterval(()=>this.tick().catch(error=>this.store.recordIssue?.('dispatcher-background',{component:'mail',error:error.message})),30000);this.timer.unref?.();
|
||||
}
|
||||
async stop(){
|
||||
this.stopped=true;clearInterval(this.timer);this.timer=null;
|
||||
|
||||
Reference in new issue
Block a user