feat: persist captured order execution and controlled batch resend

This commit is contained in:
abaishu0730 committed 2026-10-19 13:37:32 +08:00
1 parent b8cb1e11c6
commit 20589dd950
12 files changed
+419 -42

No files matched your search

+39 -10
View File
@@ -4,6 +4,7 @@ const path=require('node:path');
const crypto=require('node:crypto');
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;
@@ -15,9 +16,10 @@ function freeze(value){
}
class OrderRuleDispatcher{
constructor({store,mail,settings,calendar=()=>[],clock=()=>new Date(),providersReady=()=>false}){
constructor({store,mail,settings,calendar=()=>[],clock=()=>new Date(),providersReady=()=>false,attachmentReader,templateResolver}){
this.store=store;this.mail=mail;this.settings=settings;this.calendar=calendar;this.clock=clock;this.providersReady=providersReady;
this.running=null;this.stopped=false;this.schedule=null;this.timer=null;
this.attachmentReader=attachmentReader;if(templateResolver)store.templateResolver=templateResolver;
}
ready(){
const config=this.store.settings(),cap=this.store.snapshot().capabilities;
@@ -65,41 +67,67 @@ class OrderRuleDispatcher{
if(!file||typeof file.path!=='string'||!(path.isAbsolute(file.path)||path.win32.isAbsolute(file.path))||/^[a-z]+:\/\//i.test(file.path)||!/^[a-f\d]{64}$/i.test(file.sha256)||!Number.isSafeInteger(file.size)||file.size<0)throw Error('归档文件证据无效。');
total+=file.size;
if(total>(config.maxMessageBytes||20971520))throw Error('归档文件超过邮件大小限制。');
const stat=await fs.stat(file.path);
if(!stat.isFile()||stat.size!==file.size)throw Error('归档文件大小发生变化。');
const content=await fs.readFile(file.path);
if(!this.attachmentReader){const stat=await fs.stat(file.path);if(!stat.isFile()||stat.size!==file.size)throw Error('归档文件大小发生变化。');}
const content=this.attachmentReader?await this.attachmentReader(file):await fs.readFile(file.path);
if(!Buffer.isBuffer(content))throw Error('归档读取器未返回文件字节。');
if(content.length!==file.size||crypto.createHash('sha256').update(content).digest('hex')!==file.sha256.toLowerCase())throw Error('归档文件校验失败。');
result.push({filename:file.name,content,contentType:file.kind==='pdf'?'application/pdf':'application/octet-stream',contentDisposition:'attachment'});
}
return result;
}
async dispatch(batch,config){
async dispatch(batch,config,{manual=false}={}){
let transport,sending=false;
try{
if(batch.channelId&&batch.channelId!==config.channelId){
this.store.finishSending(batch.id,'failed','批次固定的发件邮箱与当前渠道不同,请核实邮箱设置后生成新批次。');return;
}
const attachments=await this.attachments(batch,config);
if(this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。');
if(!manual&&this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。');
const channel=freeze(structuredClone(this.mail.store.channelSecret(config.channelId)));
if(channel.readOnly)throw Error('只读邮箱不能用于分类通知发送。');
transport=this.mail.smtpFactory(channel.smtp);
this.mail.clients?.add(transport);
await transport.verify();
if(!this.ready()||this.store.settings().channelId!==config.channelId)throw Error('发送已暂停或配置已变更。');
if(this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。');
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);
this.store.beginSending(batch.id);sending=true;
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});
const accepted=new Set((result?.accepted||[]).map(address=>String(address.address||address).toLowerCase()));
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){
this.store.finishSending(batch.id,sending?'unknown':'failed',sending?'发送结果待核实,请核对邮件服务器记录后决定是否重试。':`发送前验证失败:${error.code==='ENOENT'?'归档文件不存在。':error.message==='归档文件校验失败。'?error.message:'请检查归档证据、SMTP 与启用状态。'}`);
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{
try{transport?.close?.();}finally{if(transport)this.mail.clients?.delete(transport);}
}
}
async resend(id,input,actor){
if(actor?.role!=='admin')fail('仅管理员可以人工补发。',403);
if(this.stopped)fail('发送器正在关闭。',503);
if(typeof input?.idempotencyKey!=='string'||!/^[\w:.-]{1,160}$/.test(input.idempotencyKey)||typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请填写有效幂等标识与至少5字补发依据。');
const requestId=crypto.createHash('sha256').update(JSON.stringify([id,actor.username,input.idempotencyKey])).digest('hex');
const inputHash=crypto.createHash('sha256').update(JSON.stringify([input.version,input.note])).digest('hex');
const replay=record=>{if(record.inputHash!==inputHash)fail('此幂等标识已用于不同的补发请求。',409);return this.store.get('batches',record.batchId);};
const prior=this.store.get('resend-requests',requestId);if(prior)return replay(prior);
const original=this.store.get('batches',id);if(!original)fail('批次不存在。',404);
if(!original.channelId)fail('原批次未冻结发件邮箱,不能补发。',409);
const operation=this.mail.exclusive(original.channelId,async()=>{
const previous=this.store.get('resend-requests',requestId);if(previous)return replay(previous);
const batch=this.store.transaction(()=>{
const source=this.store.get('batches',id);if(input.version!==(source.version||1)||source.status!=='failed')fail('批次版本已变化,或发送结果尚未核验。',409);
const root=source.rootBatchId||source.id;
if(this.store.all('batches').some(b=>b.id!==source.id&&(b.rootBatchId||b.id)===root&&['sent','sending','unknown','prepared'].includes(b.status)))fail('此批次已发送、结果待核实或已有补发尝试。',409);
if(source.orderIds.some(oid=>{const o=this.store.get('orders',oid);return !o||['sent','unknown','batched'].includes(o.status);}))fail('原订单关联已发送或结果待核实。',409);
const next={...structuredClone(source),id:crypto.randomUUID(),version:1,parentBatchId:source.id,rootBatchId:root,status:'prepared',manual:true,createdAt:this.clock().toISOString(),error:null,resolution:null,finishedAt:null,resend:{actor:actor.username,note:input.note.trim(),at:this.clock().toISOString()}};
this.store.put('batches',next);for(const oid of next.orderIds){const o=this.store.get('orders',oid);o.batchId=next.id;o.status='batched';o.error=null;this.store.put('orders',o);}
this.store.put('resend-requests',{id:requestId,batchId:next.id,inputHash});this.store.audit(actor.username,'人工补发冻结分类邮件',source.id+':'+input.note.trim());return next;
});
await this.dispatch(freeze(structuredClone(batch)),{...this.store.settings(),channelId:batch.channelId},{manual:true});return this.store.get('batches',batch.id);
});
this.manualOperations??=new Set();this.manualOperations.add(operation);try{return await operation;}finally{this.manualOperations.delete(operation);}
}
start(){
if(this.timer||this.stopped)return;
this.timer=setInterval(()=>this.tick().catch(()=>{}),30000);this.timer.unref?.();
@@ -107,6 +135,7 @@ class OrderRuleDispatcher{
async stop(){
this.stopped=true;clearInterval(this.timer);this.timer=null;
if(this.running)await this.running.catch(()=>{});
await Promise.allSettled([...(this.manualOperations||[])]);
}
}
module.exports={OrderRuleDispatcher};