fix: preserve rule coverage and verify isolated sample delivery
This commit is contained in:
1 parent
5c34851347
commit
f936940ec0
9 files changed
+65
-5
No files matched your search
@@ -1,11 +1,25 @@
|
||||
'use strict';
|
||||
const {ImapFlow}=require('imapflow');const nodemailer=require('nodemailer');const {parseTemplate,renderTemplate,MAX_MAIL}=require('./parser.cjs');
|
||||
const {ImapFlow}=require('imapflow');const nodemailer=require('nodemailer');const {parseTemplate,renderTemplate,escape,MAX_MAIL}=require('./parser.cjs');
|
||||
const fail=(message,status=502)=>{throw Object.assign(new Error(message),{status});};
|
||||
const safeError=(error,kind)=>error?.code==='EAUTH'||error?.authenticationFailed?`${kind} 登录失败,请检查账号和授权密码。`:/CERT|TLS|SSL|SELF_SIGNED/.test(error?.code||'')?`${kind} 加密连接失败,请检查服务器地址和证书。`:`${kind} 连接失败,请检查服务器、端口和网络后重试。`;
|
||||
class MailService{
|
||||
constructor({store,imapFactory,smtpFactory,interval=60000}){this.store=store;this.imapFactory=imapFactory||((c)=>new ImapFlow({host:c.host,port:c.port,secure:c.security==='tls',doSTARTTLS:c.security==='starttls',auth:{user:c.user,pass:c.password},logger:false,disableAutoIdle:true,connectionTimeout:15000,greetingTimeout:15000,socketTimeout:30000,maxLiteralSize:MAX_MAIL,tls:{rejectUnauthorized:true,minVersion:'TLSv1.2'}}));this.smtpFactory=smtpFactory||((c)=>nodemailer.createTransport({host:c.host,port:c.port,secure:c.security==='tls',requireTLS:c.security==='starttls',auth:{user:c.user,pass:c.password},logger:false,debug:false,connectionTimeout:15000,greetingTimeout:15000,socketTimeout:30000,disableFileAccess:true,disableUrlAccess:true,tls:{rejectUnauthorized:true,minVersion:'TLSv1.2'}}));this.interval=interval;this.running=new Map();this.clients=new Set();this.stopped=false;}
|
||||
busy(id){return this.running.has(id);}
|
||||
async exclusive(id,work){if(this.stopped)fail('邮件服务正在停止。',503);if(this.busy(id))fail('此邮箱正在执行操作,请稍后重试。',409);const promise=Promise.resolve().then(work);this.running.set(id,promise);return promise.finally(()=>this.running.delete(id));}
|
||||
sendSample(id,input){return this.exclusive(id,async()=>{
|
||||
if(!input||Object.keys(input).some(k=>!['idempotencyKey','subject','text'].includes(k))||typeof input.idempotencyKey!=='string'||!/^[\w-]{1,80}$/.test(input.idempotencyKey)||typeof input.subject!=='string'||!input.subject.trim()||input.subject.length>250||/[\x00-\x1f]/.test(input.subject)||typeof input.text!=='string'||!input.text.trim()||input.text.length>20000||input.text.includes('\0'))fail('样例测试内容无效。',400);
|
||||
const marker='sample:'+require('node:crypto').createHash('sha256').update(id+'\0'+input.idempotencyKey).digest('hex'),previous=this.store.findSampleSend(id,marker);
|
||||
if(previous){if(previous.status==='sent')return {id:previous.id,status:'sent',to:'2639266652@qq.com',reused:true};fail('此样例发送已有结果待核实,不会自动重发。',409);}
|
||||
const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能发信。',409);
|
||||
const text='本邮件仅用于样例测试,不表示BPM已处理或PDF已归档。\n\n'+input.text,transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;
|
||||
try{
|
||||
await transport.verify();this.store.guard(id,c.version);sendId=this.store.beginSend(id,marker);
|
||||
const result=await transport.sendMail({from:{address:c.email,name:c.name},to:['2639266652@qq.com'],cc:[],subject:'[样例测试] '+input.subject,text,html:'<div>'+escape(text).replace(/\r?\n/g,'<br>')+'</div>',attachments:[],messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true});
|
||||
if(result?.rejected?.length||!result?.accepted?.some(a=>String(a.address||a).toLowerCase()==='2639266652@qq.com'))throw Error('Sample recipient not fully accepted');
|
||||
this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:'2639266652@qq.com',messageId:result.messageId};
|
||||
}catch(error){if(sendId)this.store.finishSend(sendId,'unknown');if(error.status===409)throw error;fail(sendId?'样例发信结果待核实,禁止自动重发。':safeError(error,'SMTP'));}
|
||||
finally{transport.close?.();this.clients.delete(transport);}
|
||||
});}
|
||||
async withImap(config,work){const client=this.imapFactory(config);client.on?.('error',()=>{});this.clients.add(client);try{await client.connect();return await work(client);}finally{try{await client.logout();}catch{}client.close?.();this.clients.delete(client);}}
|
||||
history(id,input){return this.exclusive(id,async()=>{
|
||||
const config=this.store.channelSecret(id);
|
||||
|
||||
@@ -82,6 +82,7 @@ class MailStore{
|
||||
source(id){return Buffer.from(this.template(id).raw||'','base64');}
|
||||
migrateLegacy(legacy){if(this.db.prepare("SELECT 1 FROM meta WHERE key='legacy'").get())return;this.transaction(()=>{if(legacy?.subject?.trim()&&legacy?.body?.trim()){const id=crypto.randomUUID(),payload={subject:legacy.subject,text:legacy.body,html:'',sender:'工作台旧草稿',sourceSubject:legacy.subject,attachments:[],notes:['从原模板草稿迁入,请选择托管邮箱后确认。']};this.db.prepare('INSERT INTO templates(id,channel_id,source_key,scope,status,version,base_id,payload,created_at,summary,notification_mode) VALUES(?,?,?,?,?,?,?,?,?,?,?)').run(id,'legacy','legacy','','pending',1,null,this.encode(id,payload),at(),this.summary(payload),'normal');}this.db.prepare("INSERT INTO meta VALUES('legacy','1')").run();});}
|
||||
beginSend(channelId,templateId){const id=crypto.randomUUID();this.db.prepare('INSERT INTO sends VALUES(?,?,?,?,?)').run(id,channelId,templateId,'sending',at());return id;}
|
||||
findSampleSend(channelId,key){return this.db.prepare('SELECT id,status FROM sends WHERE channel_id=? AND template_id=? ORDER BY at DESC LIMIT 1').get(channelId,key);}
|
||||
finishSend(id,status){this.db.prepare('UPDATE sends SET status=? WHERE id=?').run(status,id);}
|
||||
sends(){return this.db.prepare('SELECT * FROM sends ORDER BY at DESC LIMIT 50').all();}
|
||||
close(){if(this.db){this.db.close();this.db=null;}this.vault.destroy();}
|
||||
|
||||
@@ -46,7 +46,7 @@ function orderRow(order,task){
|
||||
function currentTasks(context,user){
|
||||
const tasks=new Map();for(const task of records(context.orderRules).tasks){if(task.supersededBy||!task.orderId||!canReadConnection(context.workspace,user,task.connectionId))continue;const old=tasks.get(task.orderId);if(!old||Number(!!task.conflict)>Number(!!old.conflict)||!!task.conflict===!!old.conflict&&String(task.createdAt||'')>=String(old.createdAt||''))tasks.set(task.orderId,task);}return tasks;
|
||||
}
|
||||
const classified=(order,task)=>!!(order?.categoryId||order?.ruleSnapshot?.categoryId||order?.ruleSnapshot?.id||task?.categoryIds?.length);
|
||||
const classified=(order,task)=>!order?.removedAt&&!!(order?.categoryId||order?.ruleSnapshot?.categoryId||order?.ruleSnapshot?.id||task?.categoryIds?.length);
|
||||
function visibleOrders(context,user){
|
||||
const data=records(context.orderRules),tasks=currentTasks(context,user);
|
||||
const rows=data.orders.filter(o=>classified(o,tasks.get(o.id))&&canReadOrder(context.workspace,user,o)).map(o=>orderRow(o,tasks.get(o.id)));
|
||||
|
||||
@@ -23,7 +23,15 @@ function evidence(store,adapter){
|
||||
const result=require('./field-mappings.cjs').evaluateMapping(store,{...adapter,version:adapter.version},captured,{relatedRules:[]});
|
||||
return result.valid;
|
||||
}
|
||||
function summary(store){const run=state(store);if(!run)return null;return {id:run.id,version:run.version,enabled:run.enabled,recipient:run.recipient,archiveRoot:run.archiveRoot,channelId:run.channelId,since:run.since,ruleCount:run.rules.length,readyCount:run.rules.filter(r=>validRule(store,r,run)).length,uncovered:run.uncovered};}
|
||||
function uncoveredFlows(store,run){
|
||||
const adapters=store.adapters();
|
||||
return run.rules.flatMap(rule=>{
|
||||
const draft=store.get('rules',rule.id)?.draft;
|
||||
const processes=draft?.version===rule.version?draft.processNames:[...rule.processNames,...(run.uncovered||[]).filter(row=>row.categoryId===rule.id).map(row=>row.processName)];
|
||||
return [...new Set(processes)].filter(processName=>!adapters.some(a=>a.verified&&!a.reference&&rule.adapterIds.includes(a.id)&&a.processName===processName)).map(processName=>({categoryId:rule.id,processName}));
|
||||
});
|
||||
}
|
||||
function summary(store){const run=state(store);if(!run)return null;return {id:run.id,version:run.version,enabled:run.enabled,recipient:run.recipient,archiveRoot:run.archiveRoot,channelId:run.channelId,since:run.since,ruleCount:run.rules.length,readyCount:run.rules.filter(r=>validRule(store,r,run)).length,uncovered:uncoveredFlows(store,run)};}
|
||||
function validRule(store,rule,run){return run.enabled&&hash(rule.adapterIds.map(id=>store.adapters().find(a=>a.id===id)))===run.adapterHashes[rule.id];}
|
||||
function executionRule(store,record){
|
||||
const run=state(store);if(!run)return record?.published||null;
|
||||
@@ -58,7 +66,7 @@ function applyDrafts(store,input,actor){
|
||||
assertPath(store,rule.archiveDirectory,run);next.rules[index]=rule;next.adapterHashes[rule.id]=hash(rule.adapterIds.map(id=>adapters.find(a=>a.id===id)));
|
||||
}
|
||||
for(let i=0;i<next.rules.length;i++)for(let j=i+1;j<next.rules.length;j++)if(require('./scopes.cjs').scopesOverlap(next.rules[i],next.rules[j]))fail('分类存在相同流程和节点,不能应用。',409);
|
||||
next.uncovered=next.rules.flatMap(rule=>rule.processNames.filter(p=>!adapters.some(a=>rule.adapterIds.includes(a.id)&&a.processName===p)).map(processName=>({categoryId:rule.id,processName})));
|
||||
next.uncovered=uncoveredFlows(store,next);
|
||||
// Keep the previous approved versions for existing tasks and frozen batches.
|
||||
// The current execution snapshot alone changes; identities and baseline do not.
|
||||
store.put('restricted-test-history',{id:run.id+':'+run.version,value:run});next.version++;
|
||||
|
||||
Reference in new issue
Block a user