147 lines
11 KiB
JavaScript
147 lines
11 KiB
JavaScript
'use strict';
|
||
const fs=require('node:fs/promises');
|
||
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;
|
||
}
|
||
|
||
function freeze(value){
|
||
if(value&&typeof value==='object'){for(const item of Object.values(value))freeze(item);Object.freeze(value);}
|
||
return value;
|
||
}
|
||
|
||
class OrderRuleDispatcher{
|
||
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;
|
||
return !this.stopped&&config.enabled===true&&this.providersReady()===true&&cap?.liveTodo===true&&cap?.pdfExport===true&&cap?.automaticArchive===true;
|
||
}
|
||
tick(now=this.clock()){
|
||
if(this.stopped||this.running)return this.running||Promise.resolve();
|
||
const task=this.perform(new Date(now));this.running=task;
|
||
task.finally(()=>{if(this.running===task)this.running=null;}).catch(()=>{});
|
||
return task;
|
||
}
|
||
async perform(now){
|
||
if(!this.ready())return;
|
||
const config=freeze(structuredClone(this.store.settings()));
|
||
const 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;}
|
||
}
|
||
async attachments(batch,config){
|
||
const result=[];let total=0;
|
||
for(const file of batch.attachments||[]){
|
||
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('归档文件超过邮件大小限制。');
|
||
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,{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(!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();
|
||
// 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);
|
||
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){
|
||
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{
|
||
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?.();
|
||
}
|
||
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};
|