fix: enforce notification reservations and evidence based retry
This commit is contained in:
1 parent
0951dd451d
commit
acba28c879
10 files changed
+205
-83
No files matched your search
@@ -7,6 +7,7 @@ async function notificationApi({notifications,workspace,user,route,method,body,r
|
||||
if(user.role==='viewer')fail('只读成员不能提交通知数据或修改配置。',403);
|
||||
if(route==='/api/notifications/settings'){if(user.role!=='admin')fail('仅管理员可以修改业务通知配置。',403);const saved=notifications.saveSettings(body);workspace?.record(user,'保存业务通知配置',saved.enabled?'已启用':'已暂停');reply(200,saved);return true;}
|
||||
if(route==='/api/notifications/preview'||route==='/api/notifications/events'){if(!body||Object.keys(body).some(k=>k!=='data'))fail('请提交来源数据对象。');const preview=route.endsWith('/preview');const result=preview?notifications.preview(body.data):notifications.ingest(body.data);if(!preview)workspace?.record(user,'通知数据入队',result.sourceId);reply(preview?200:201,result);return true;}
|
||||
const retry=/^\/api\/notifications\/items\/([\w-]+)\/retry$/.exec(route);if(retry){if(user.role!=='admin')fail('仅管理员可以重新入队次数耗尽通知。',403);const result=notifications.retryItem(retry[1],body,user.username);workspace?.record(user,'重新入队次数耗尽通知',retry[1]+':'+body.note.trim());reply(200,result);return true;}
|
||||
const match=/^\/api\/notifications\/batches\/([\w-]+)\/resolve$/.exec(route);if(match){if(user.role!=='admin')fail('仅管理员可以核验发送结果。',403);const result=notifications.resolve(match[1],body,user.username);workspace?.record(user,'核验通知发送结果',match[1]);reply(200,result);return true;}
|
||||
fail('没有找到此通知操作。',404);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
const crypto=require('node:crypto');
|
||||
const hash=value=>crypto.createHash('sha256').update(value).digest('hex');
|
||||
const DEFAULT_MAP={id:'id',version:'version',industry:'industry',brief:'brief',subject:'subject',occurredAt:'occurredAt'};
|
||||
function validateMap(map){if(!map||typeof map!=='object'||Array.isArray(map)||Object.keys(map).some(k=>!Object.hasOwn(DEFAULT_MAP,k)))fail('通知字段映射无效。');for(const key of Object.keys(DEFAULT_MAP)){const p=map[key];if(typeof p!=='string'||p.length>200||(p&&!/^[\p{L}\p{N}_-]+(?:\.[\p{L}\p{N}_-]+)*$/u.test(p))||p.split('.').some(s=>['__proto__','constructor','prototype'].includes(s)))fail('字段路径只支持普通对象的点分隔路径。');if(['id','industry','brief'].includes(key)&&!p)fail('请配置通知 ID、产业与简要说明字段。');}return {...map};}
|
||||
function valueAt(data,p){if(!p)return undefined;for(const part of p.split('.')){if(!data||typeof data!=='object'||!Object.hasOwn(data,part))return undefined;data=data[part];}return data;}
|
||||
function mapEvent(data,config,clock=()=>new Date()){if(!data||typeof data!=='object'||Array.isArray(data))fail('通知来源必须是 JSON 对象。');const raw=Object.fromEntries(Object.entries(config.fieldMap).map(([key,p])=>[key,valueAt(data,p)]));if(!['string','number'].includes(typeof raw.id)||!String(raw.id).trim()||String(raw.id).length>200||/[\x00-\x1f]/.test(String(raw.id))||typeof raw.industry!=='string'||!raw.industry.trim()||raw.industry.length>100||/[\x00-\x1f]/.test(raw.industry)||typeof raw.brief!=='string'||!raw.brief.trim()||raw.brief.length>20000)fail('通知 ID、产业和简要说明不能为空,正文最多 20000 字。');if(raw.subject!==undefined&&(typeof raw.subject!=='string'||raw.subject.length>300||/[\r\n\x00]/.test(raw.subject)))fail('通知标题最多 300 字,不能包含换行。');if(raw.version!==undefined&&(!['string','number'].includes(typeof raw.version)||String(raw.version).length>200||/[\x00-\x1f]/.test(String(raw.version))))fail('来源版本无效。');if(raw.occurredAt!==undefined&&(typeof raw.occurredAt!=='string'||!Number.isFinite(Date.parse(raw.occurredAt))))fail('业务时间无效。');return {source:config.sourceName,sourceKey:config.sourceKey,sourceId:String(raw.id).trim(),sourceVersion:raw.version===undefined||raw.version===''?hash(raw.brief):String(raw.version),industry:raw.industry.trim(),brief:raw.brief,subject:raw.subject||raw.industry.trim()+'业务通知',occurredAt:raw.occurredAt||clock().toISOString()};}
|
||||
|
||||
module.exports={DEFAULT_MAP,validateMap,hash,mapEvent};
|
||||
@@ -1,76 +0,0 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('../../platform/security/vault.cjs');const {nextSlots}=require('../../shared/schedule.cjs');
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
const hash=value=>crypto.createHash('sha256').update(value).digest('hex');
|
||||
const DEFAULT_MAP={id:'id',version:'version',industry:'industry',brief:'brief',subject:'subject',occurredAt:'occurredAt'};
|
||||
function validateMap(map){if(!map||typeof map!=='object'||Array.isArray(map)||Object.keys(map).some(k=>!Object.hasOwn(DEFAULT_MAP,k)))fail('通知字段映射无效。');for(const key of Object.keys(DEFAULT_MAP)){const p=map[key];if(typeof p!=='string'||p.length>200||(p&&!/^[\p{L}\p{N}_-]+(?:\.[\p{L}\p{N}_-]+)*$/u.test(p))||p.split('.').some(s=>['__proto__','constructor','prototype'].includes(s)))fail('字段路径只支持普通对象的点分隔路径。');if(['id','industry','brief'].includes(key)&&!p)fail('请配置通知 ID、产业与简要说明字段。');}return {...map};}
|
||||
function valueAt(data,p){if(!p)return undefined;for(const part of p.split('.')){if(!data||typeof data!=='object'||!Object.hasOwn(data,part))return undefined;data=data[part];}return data;}
|
||||
class NotificationStore{
|
||||
constructor(dir){fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});this.db=new DatabaseSync(path.join(dir,'notifications.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
|
||||
CREATE TABLE IF NOT EXISTS settings(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS items(id TEXT PRIMARY KEY,payload BLOB NOT NULL,status TEXT NOT NULL,attempts INTEGER NOT NULL DEFAULT 0,error TEXT,batch_id TEXT,created_at TEXT NOT NULL,industry TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS batches(id TEXT PRIMARY KEY,status TEXT NOT NULL,payload BLOB NOT NULL,error TEXT,created_at TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
|
||||
UPDATE items SET status='pending',batch_id=NULL WHERE batch_id IN(SELECT id FROM batches WHERE status='prepared');
|
||||
UPDATE items SET status='unknown',error='服务重启,发送结果需要核实。' WHERE batch_id IN(SELECT id FROM batches WHERE status='sending');
|
||||
UPDATE batches SET status='cancelled' WHERE status='prepared';
|
||||
UPDATE batches SET status='unknown',error='服务重启,发送结果需要核实。' WHERE status='sending';`);
|
||||
this.db.prepare('INSERT OR IGNORE INTO settings VALUES(1,?)').run(JSON.stringify({version:1,enabled:false,sourceKey:crypto.randomUUID(),sourceName:'业务来源',channelId:'',fieldMap:DEFAULT_MAP,maxAttempts:3}));
|
||||
if(!this.db.prepare('PRAGMA table_info(items)').all().some(c=>c.name==='industry')){this.db.exec("ALTER TABLE items ADD COLUMN industry TEXT NOT NULL DEFAULT ''");for(const row of this.db.prepare('SELECT id,payload FROM items').all())this.db.prepare('UPDATE items SET industry=? WHERE id=?').run(this.decode(row.id,row.payload).industry,row.id);}
|
||||
this.db.exec('CREATE INDEX IF NOT EXISTS notification_pending ON items(status,industry,attempts)');
|
||||
}
|
||||
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(e){this.db.exec('ROLLBACK');throw e;}}
|
||||
encode(id,data){try{return this.vault.encode(id,data);}catch{fail('通知内容加密不可用,请联系管理员。',503);}}
|
||||
decode(id,data){try{return this.vault.decode(id,data);}catch{fail('通知内容无法解密,请联系管理员。',503);}}
|
||||
settings(){return JSON.parse(this.db.prepare('SELECT value FROM settings WHERE id=1').get().value);}
|
||||
saveSettings(input){const old=this.settings();if(!input||Object.keys(input).some(k=>!['version','enabled','sourceKey','sourceName','channelId','fieldMap','maxAttempts'].includes(k)))fail('通知配置无效。');if(input.version!==old.version)fail('通知配置已被修改,请刷新。',409);if(typeof input.enabled!=='boolean'||typeof input.sourceName!=='string'||!input.sourceName.trim()||input.sourceName.length>80||typeof input.channelId!=='string'||input.channelId.length>100||!Number.isInteger(input.maxAttempts)||input.maxAttempts<1||input.maxAttempts>10)fail('请检查来源、邮箱和尝试次数(1–10)。');if(input.sourceKey&&input.sourceKey!==old.sourceKey)fail('来源标识不能更改。');const saved={...input,sourceKey:old.sourceKey,sourceName:input.sourceName.trim(),fieldMap:validateMap(input.fieldMap),version:old.version+1};this.db.prepare('UPDATE settings SET value=? WHERE id=1').run(JSON.stringify(saved));return saved;}
|
||||
scheduleState(){const row=this.db.prepare("SELECT value FROM metadata WHERE key='schedule'").get();return row?JSON.parse(row.value):null;}
|
||||
setSchedule(value){this.db.prepare("INSERT INTO metadata VALUES('schedule',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(JSON.stringify(value));}
|
||||
ingest(event){const id=hash([event.sourceKey,event.sourceId,event.sourceVersion,event.industry].join('\0')),old=this.db.prepare('SELECT * FROM items WHERE id=?').get(id);if(old){const value=this.decode(id,old.payload);if(value.brief!==event.brief||value.subject!==event.subject)fail('同一通知版本的内容已变化,请核实来源版本。',409);return this.item(old);}this.db.prepare('INSERT INTO items(id,payload,status,created_at,industry) VALUES(?,?,?,?,?)').run(id,this.encode(id,event),'pending',new Date().toISOString(),event.industry);return this.item(this.db.prepare('SELECT * FROM items WHERE id=?').get(id));}
|
||||
item({payload,...row}){return {...this.decode(row.id,payload),...row};}
|
||||
items(){return this.db.prepare('SELECT * FROM items ORDER BY rowid DESC LIMIT 100').all().map(r=>this.item(r));}
|
||||
pending(attempts,industries){if(!industries.length)return [];return this.db.prepare("SELECT * FROM items WHERE status IN('pending','blocked') AND attempts<? AND industry IN("+industries.map(()=>'?').join(',')+") ORDER BY rowid LIMIT 200").all(attempts,...industries).map(r=>this.item(r));}
|
||||
blockUnmapped(industries){this.db.prepare("UPDATE items SET status='blocked',error='此产业尚未配置接口人收件组。' WHERE status IN('pending','blocked')"+(industries.length?' AND industry NOT IN('+industries.map(()=>'?').join(',')+')':'')).run(...industries);}
|
||||
block(id,message){this.db.prepare("UPDATE items SET status='blocked',error=? WHERE id=? AND status IN('pending','blocked')").run(message,id);}
|
||||
prepare(items,snapshot){return this.transaction(()=>{const id=crypto.randomUUID();this.db.prepare('INSERT INTO batches VALUES(?,?,?,?,?)').run(id,'prepared',this.encode(id,snapshot),null,new Date().toISOString());for(const item of items){const result=this.db.prepare("UPDATE items SET status='reserved',attempts=attempts+1,error=NULL,batch_id=? WHERE id=? AND status IN('pending','blocked')").run(id,item.id);if(!result.changes)fail('通知队列已变化,请重试。',409);}return id;});}
|
||||
mark(id,status,message=null){this.transaction(()=>{this.db.prepare('UPDATE batches SET status=?,error=? WHERE id=?').run(status,message,id);if(status!=='sending')this.db.prepare('UPDATE items SET status=?,error=? WHERE batch_id=?').run(status==='failed'?'pending':status,message,id);});}
|
||||
batches(){return this.db.prepare("SELECT * FROM batches ORDER BY CASE status WHEN 'unknown' THEN 0 ELSE 1 END,rowid DESC LIMIT 100").all().map(({payload,...r})=>({...this.decode(r.id,payload),...r}));}
|
||||
resolve(id,input,actor){return this.transaction(()=>{const row=this.db.prepare('SELECT * FROM batches WHERE id=?').get(id);if(!row||row.status!=='unknown')fail('只能核验结果待核实的批次。',409);if(!input||!['sent','retry'].includes(input.resolution)||typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请选择核验结果并填写至少 5 字的核验依据。');const data={...this.decode(id,row.payload),resolution:input.resolution,note:input.note.trim(),resolvedBy:actor,resolvedAt:new Date().toISOString()};this.db.prepare('UPDATE batches SET status=?,payload=? WHERE id=?').run('resolved_'+input.resolution,this.encode(id,data),id);this.db.prepare('UPDATE items SET status=?,error=NULL,attempts=CASE WHEN ? THEN 0 ELSE attempts END WHERE batch_id=?').run(input.resolution==='sent'?'sent':'pending',input.resolution==='retry'?1:0,id);return {ok:true};});}
|
||||
close(){if(this.db){this.db.close();this.db=null;}this.vault.destroy();}
|
||||
}
|
||||
class NotificationService{
|
||||
constructor({store,mail,settings,calendar=()=>[],clock=()=>new Date()}){this.store=store;this.mail=mail;this.settings=settings;this.calendar=calendar;this.clock=clock;this.running=null;this.stopped=false;}
|
||||
map(data){if(!data||typeof data!=='object'||Array.isArray(data))fail('通知来源必须是 JSON 对象。');const config=this.store.settings(),raw=Object.fromEntries(Object.entries(config.fieldMap).map(([key,p])=>[key,valueAt(data,p)]));if(!['string','number'].includes(typeof raw.id)||!String(raw.id).trim()||String(raw.id).length>200||/[\x00-\x1f]/.test(String(raw.id))||typeof raw.industry!=='string'||!raw.industry.trim()||raw.industry.length>100||/[\x00-\x1f]/.test(raw.industry)||typeof raw.brief!=='string'||!raw.brief.trim()||raw.brief.length>20000)fail('通知 ID、产业和简要说明不能为空,正文最多 20000 字。');if(raw.subject!==undefined&&(typeof raw.subject!=='string'||raw.subject.length>300||/[\r\n\x00]/.test(raw.subject)))fail('通知标题最多 300 字,不能包含换行。');if(raw.version!==undefined&&(!['string','number'].includes(typeof raw.version)||String(raw.version).length>200||/[\x00-\x1f]/.test(String(raw.version))))fail('来源版本无效。');if(raw.occurredAt!==undefined&&(typeof raw.occurredAt!=='string'||!Number.isFinite(Date.parse(raw.occurredAt))))fail('业务时间无效。');return {source:config.sourceName,sourceKey:config.sourceKey,sourceId:String(raw.id).trim(),sourceVersion:raw.version===undefined||raw.version===''?hash(raw.brief):String(raw.version),industry:raw.industry.trim(),brief:raw.brief,subject:raw.subject||raw.industry.trim()+'业务通知',occurredAt:raw.occurredAt||this.clock().toISOString()};}
|
||||
preview(data){try{const event=this.map(data),group=this.settings().groups.find(g=>g.productLine===event.industry);return {valid:!!group,event,to:group?.to||[],cc:group?.cc||[],issues:group?[]:['此产业尚未配置接口人收件组。']};}catch(e){if(!e.status)throw e;return {valid:false,issues:[e.message]};}}
|
||||
ingest(data){return this.store.ingest(this.map(data));}
|
||||
saveSettings(input){if(this.running)fail('通知正在发送,请稍后修改配置。',409);if(input?.enabled){const c=this.mail.store.publicChannel(input.channelId);if(!c.state.smtp)fail('请先验证发件邮箱的 SMTP 连接。',409);if(!this.settings().groups.length)fail('请先配置产业接口人收件组。',409);}const old=this.store.settings(),saved=this.store.saveSettings(input);if(saved.enabled&&!old.enabled)this.resetSchedule(this.clock());return saved;}
|
||||
resetSchedule(now){const schedule=this.settings().schedule,calendar=this.calendar();const state={signature:JSON.stringify([schedule,calendar]),next:nextSlots(schedule,now,1,calendar)[0]};this.store.setSchedule(state);return state;}
|
||||
tick(now=this.clock()){
|
||||
if(this.stopped||this.running)return this.running||Promise.resolve();
|
||||
const task=this.perform(now);this.running=task;task.finally(()=>{if(this.running===task)this.running=null;}).catch(()=>{});return task;
|
||||
}
|
||||
async perform(now){
|
||||
const config=this.store.settings();if(!config.enabled)return;
|
||||
const settings=this.settings(),calendar=this.calendar(),signature=JSON.stringify([settings.schedule,calendar]);let schedule=this.store.scheduleState();
|
||||
if(!schedule||schedule.signature!==signature){this.resetSchedule(now);return;}if(!schedule.next||Date.parse(schedule.next)>now.getTime())return;
|
||||
const due=Date.parse(schedule.next);if(now.getTime()-due>60000){this.resetSchedule(now);return;}
|
||||
const industries=settings.groups.filter(g=>g.to?.length).map(g=>g.productLine);this.store.blockUnmapped(industries);const grouped=new Map();for(const item of this.store.pending(config.maxAttempts,industries)){const group=settings.groups.find(g=>g.productLine===item.industry);if(!group||!group.to?.length){this.store.block(item.id,'此产业尚未配置接口人收件组。');continue;}const key=settings.schedule.mode==='order'?item.id:item.industry;if(!grouped.has(key))grouped.set(key,{items:[],group});if(grouped.get(key).items.length<50)grouped.get(key).items.push(item);}
|
||||
if(!grouped.size){this.resetSchedule(now);return;}
|
||||
await this.mail.exclusive(config.channelId,async()=>{
|
||||
this.resetSchedule(now);
|
||||
for(const {items,group}of grouped.values()){
|
||||
if(this.stopped)break;
|
||||
const channel=this.mail.store.channelSecret(config.channelId),snapshot={channelId:channel.id,industry:items[0].industry,sourceIds:items.map(i=>i.sourceId),subject:items.length===1?items[0].subject:items[0].industry+'业务通知',text:items.map(i=>i.brief).join('\n\n'),to:[...group.to],cc:[...group.cc],slot:new Date(due).toISOString()};
|
||||
const batch=this.store.prepare(items,snapshot);let transport,sending=false;
|
||||
try{transport=this.mail.smtpFactory(channel.smtp);await transport.verify();this.mail.store.guard(channel.id,channel.version);this.store.mark(batch,'sending');sending=true;
|
||||
const result=await transport.sendMail({from:{address:channel.email,name:channel.name},to:snapshot.to,cc:snapshot.cc,subject:snapshot.subject,text:snapshot.text,attachments:[],messageId:`<${batch}@${channel.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true});
|
||||
const accepted=new Set((result.accepted||[]).map(a=>String(a.address||a).toLowerCase()));if(result.rejected?.length||[...snapshot.to,...snapshot.cc].some(a=>!accepted.has(a.toLowerCase()))){this.store.mark(batch,'unknown','部分收件人未被邮件服务器接受,请核实后处理。');}else this.store.mark(batch,'sent');
|
||||
}catch{this.store.mark(batch,sending?'unknown':'failed',sending?'发信结果待核实,请查询邮件服务器记录。':'SMTP 检查失败,等待下个时段按次数上限重试。');}finally{transport?.close?.();}
|
||||
}
|
||||
}).catch(e=>{if(e.status!==409)throw e;});
|
||||
}
|
||||
resolve(id,input,actor){if(this.running)fail('通知正在发送,请稍后核验。',409);return this.store.resolve(id,input,actor);}
|
||||
start(){this.timer=setInterval(()=>this.tick().catch(()=>{}),30000);this.timer.unref?.();}
|
||||
async stop(){this.stopped=true;clearInterval(this.timer);if(this.running)await this.running.catch(()=>{});}
|
||||
}
|
||||
module.exports={NotificationStore,NotificationService};
|
||||
@@ -0,0 +1,41 @@
|
||||
'use strict';
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
const {nextSlots}=require('../../shared/schedule.cjs');const {mapEvent}=require('./mapping.cjs');
|
||||
class NotificationService{
|
||||
constructor({store,mail,settings,calendar=()=>[],clock=()=>new Date()}){this.store=store;this.mail=mail;this.settings=settings;this.calendar=calendar;this.clock=clock;this.running=null;this.stopped=false;}
|
||||
map(data){return mapEvent(data,this.store.settings(),this.clock);}
|
||||
preview(data){try{const event=this.map(data),group=this.settings().groups.find(g=>g.productLine===event.industry);return {valid:!!group,event,to:group?.to||[],cc:group?.cc||[],issues:group?[]:['此产业尚未配置接口人收件组。']};}catch(e){if(!e.status)throw e;return {valid:false,issues:[e.message]};}}
|
||||
ingest(data){return this.store.ingest(this.map(data));}
|
||||
saveSettings(input){if(this.running)fail('通知正在发送,请稍后修改配置。',409);if(input?.enabled){const c=this.mail.store.publicChannel(input.channelId);if(!c.state.smtp)fail('请先验证发件邮箱的 SMTP 连接。',409);if(!this.settings().groups.length)fail('请先配置产业接口人收件组。',409);}const old=this.store.settings(),saved=this.store.saveSettings(input);if(saved.enabled&&!old.enabled)this.resetSchedule(this.clock());return saved;}
|
||||
resetSchedule(now){const schedule=this.settings().schedule,calendar=this.calendar();const state={signature:JSON.stringify([schedule,calendar]),next:nextSlots(schedule,now,1,calendar)[0]};this.store.setSchedule(state);return state;}
|
||||
tick(now=this.clock()){
|
||||
if(this.stopped||this.running)return this.running||Promise.resolve();
|
||||
const task=this.perform(now);this.running=task;task.finally(()=>{if(this.running===task)this.running=null;}).catch(()=>{});return task;
|
||||
}
|
||||
async perform(now){
|
||||
const config=this.store.settings();if(!config.enabled)return;
|
||||
const settings=this.settings(),calendar=this.calendar(),signature=JSON.stringify([settings.schedule,calendar]);let schedule=this.store.scheduleState();
|
||||
if(!schedule||schedule.signature!==signature){this.resetSchedule(now);return;}if(!schedule.next||Date.parse(schedule.next)>now.getTime())return;
|
||||
const due=Date.parse(schedule.next);if(now.getTime()-due>60000){this.resetSchedule(now);return;}
|
||||
const industries=settings.groups.filter(g=>g.to?.length).map(g=>g.productLine);this.store.blockUnmapped(industries);const grouped=new Map();for(const item of this.store.pending(config.maxAttempts,industries)){const group=settings.groups.find(g=>g.productLine===item.industry);if(!group||!group.to?.length){this.store.block(item.id,'此产业尚未配置接口人收件组。');continue;}const key=settings.schedule.mode==='order'?item.id:item.industry;if(!grouped.has(key))grouped.set(key,{items:[],group});if(grouped.get(key).items.length<50)grouped.get(key).items.push(item);}
|
||||
if(!grouped.size){this.resetSchedule(now);return;}
|
||||
await this.mail.exclusive(config.channelId,async()=>{
|
||||
this.resetSchedule(now);
|
||||
for(const {items,group}of grouped.values()){
|
||||
if(this.stopped)break;
|
||||
const channel=this.mail.store.channelSecret(config.channelId),snapshot={channelId:channel.id,industry:items[0].industry,sourceIds:items.map(i=>i.sourceId),subject:items.length===1?items[0].subject:items[0].industry+'业务通知',text:items.map(i=>i.brief).join('\n\n'),to:[...group.to],cc:[...group.cc],slot:new Date(due).toISOString()};
|
||||
const batch=this.store.prepare(items,snapshot);let transport,sending=false;
|
||||
try{transport=this.mail.smtpFactory(channel.smtp);await transport.verify();this.mail.store.guard(channel.id,channel.version);this.store.beginSending(batch);sending=true;
|
||||
const result=await transport.sendMail({from:{address:channel.email,name:channel.name},to:snapshot.to,cc:snapshot.cc,subject:snapshot.subject,text:snapshot.text,attachments:[],messageId:`<${batch}@${channel.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true});
|
||||
const accepted=new Set((result.accepted||[]).map(a=>String(a.address||a).toLowerCase()));if(result.rejected?.length||[...snapshot.to,...snapshot.cc].some(a=>!accepted.has(a.toLowerCase()))){this.store.mark(batch,'unknown','部分收件人未被邮件服务器接受,请核实后处理。');}else this.store.mark(batch,'sent');
|
||||
}catch{this.store.mark(batch,sending?'unknown':'failed',sending?'发信结果待核实,请查询邮件服务器记录。':'SMTP 连接检查失败,请查看通知队列的重试状态。');}finally{transport?.close?.();}
|
||||
}
|
||||
}).catch(e=>{if(e.status!==409)throw e;});
|
||||
}
|
||||
retryItem(id,input,actor){if(this.running)fail('通知正在发送,请稍后重新入队。',409);return this.store.retryItem(id,input,actor);}
|
||||
resolve(id,input,actor){if(this.running)fail('通知正在发送,请稍后核验。',409);return this.store.resolve(id,input,actor);}
|
||||
start(){this.timer=setInterval(()=>this.tick().catch(()=>{}),30000);this.timer.unref?.();}
|
||||
async stop(){this.stopped=true;clearInterval(this.timer);if(this.running)await this.running.catch(()=>{});}
|
||||
}
|
||||
|
||||
module.exports={NotificationService};
|
||||
@@ -0,0 +1,58 @@
|
||||
'use strict';
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('../../platform/security/vault.cjs');const {DEFAULT_MAP,validateMap,hash}=require('./mapping.cjs');
|
||||
class NotificationStore{
|
||||
constructor(dir){fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});this.db=new DatabaseSync(path.join(dir,'notifications.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
|
||||
CREATE TABLE IF NOT EXISTS settings(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS items(id TEXT PRIMARY KEY,payload BLOB NOT NULL,status TEXT NOT NULL,attempts INTEGER NOT NULL DEFAULT 0,error TEXT,batch_id TEXT,created_at TEXT NOT NULL,industry TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS batches(id TEXT PRIMARY KEY,status TEXT NOT NULL,payload BLOB NOT NULL,error TEXT,created_at TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
|
||||
`);
|
||||
this.db.exec('CREATE TABLE IF NOT EXISTS retry_audit(id TEXT PRIMARY KEY,item_id TEXT NOT NULL,payload BLOB NOT NULL)');
|
||||
this.db.prepare('INSERT OR IGNORE INTO settings VALUES(1,?)').run(JSON.stringify({version:1,enabled:false,sourceKey:crypto.randomUUID(),sourceName:'业务来源',channelId:'',fieldMap:DEFAULT_MAP,maxAttempts:3}));
|
||||
if(!this.db.prepare('PRAGMA table_info(items)').all().some(c=>c.name==='industry')){this.db.exec("ALTER TABLE items ADD COLUMN industry TEXT NOT NULL DEFAULT ''");for(const row of this.db.prepare('SELECT id,payload FROM items').all())this.db.prepare('UPDATE items SET industry=? WHERE id=?').run(this.decode(row.id,row.payload).industry,row.id);}
|
||||
this.db.exec('CREATE INDEX IF NOT EXISTS notification_pending ON items(status,industry,attempts)');
|
||||
}
|
||||
recover(){return this.transaction(()=>{
|
||||
this.db.exec("UPDATE items SET status='pending' WHERE status='reserved' AND batch_id IN(SELECT id FROM batches WHERE status='prepared'); UPDATE items SET status='unknown',error='服务重启,发送结果需要核实。' WHERE batch_id IN(SELECT id FROM batches WHERE status='sending') AND status IN('reserved','sending'); UPDATE batches SET status='cancelled' WHERE status='prepared'; UPDATE batches SET status='unknown',error='服务重启,发送结果需要核实。' WHERE status='sending';");this.exhaustEligible();
|
||||
});}
|
||||
exhaustEligible(){this.db.prepare("UPDATE items SET status='exhausted',error='SMTP 检查尝试次数已耗尽,请管理员核实修复后单项重新入队。' WHERE status IN('pending','blocked') AND attempts>=?").run(this.settings().maxAttempts);}
|
||||
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(e){this.db.exec('ROLLBACK');throw e;}}
|
||||
encode(id,data){try{return this.vault.encode(id,data);}catch{fail('通知内容加密不可用,请联系管理员。',503);}}
|
||||
decode(id,data){try{return this.vault.decode(id,data);}catch{fail('通知内容无法解密,请联系管理员。',503);}}
|
||||
settings(){return JSON.parse(this.db.prepare('SELECT value FROM settings WHERE id=1').get().value);}
|
||||
saveSettings(input){const old=this.settings();if(!input||Object.keys(input).some(k=>!['version','enabled','sourceKey','sourceName','channelId','fieldMap','maxAttempts'].includes(k)))fail('通知配置无效。');if(input.version!==old.version)fail('通知配置已被修改,请刷新。',409);if(typeof input.enabled!=='boolean'||typeof input.sourceName!=='string'||!input.sourceName.trim()||input.sourceName.length>80||typeof input.channelId!=='string'||input.channelId.length>100||!Number.isInteger(input.maxAttempts)||input.maxAttempts<1||input.maxAttempts>10)fail('请检查来源、邮箱和尝试次数(1–10)。');if(input.sourceKey&&input.sourceKey!==old.sourceKey)fail('来源标识不能更改。');const saved={...input,sourceKey:old.sourceKey,sourceName:input.sourceName.trim(),fieldMap:validateMap(input.fieldMap),version:old.version+1};return this.transaction(()=>{this.db.prepare('UPDATE settings SET value=? WHERE id=1').run(JSON.stringify(saved));this.exhaustEligible();return saved;});}
|
||||
scheduleState(){const row=this.db.prepare("SELECT value FROM metadata WHERE key='schedule'").get();return row?JSON.parse(row.value):null;}
|
||||
setSchedule(value){this.db.prepare("INSERT INTO metadata VALUES('schedule',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(JSON.stringify(value));}
|
||||
ingest(event){const id=hash([event.sourceKey,event.sourceId,event.sourceVersion,event.industry].join('\0')),old=this.db.prepare('SELECT * FROM items WHERE id=?').get(id);if(old){const value=this.decode(id,old.payload);if(value.brief!==event.brief||value.subject!==event.subject)fail('同一通知版本的内容已变化,请核实来源版本。',409);return this.item(old);}this.db.prepare('INSERT INTO items(id,payload,status,created_at,industry) VALUES(?,?,?,?,?)').run(id,this.encode(id,event),'pending',new Date().toISOString(),event.industry);return this.item(this.db.prepare('SELECT * FROM items WHERE id=?').get(id));}
|
||||
item({payload,...row}){return {...this.decode(row.id,payload),...row};}
|
||||
items(){return this.db.prepare('SELECT * FROM items ORDER BY rowid DESC LIMIT 100').all().map(r=>this.item(r));}
|
||||
pending(attempts,industries){if(!industries.length)return [];return this.db.prepare("SELECT * FROM items WHERE status IN('pending','blocked') AND attempts<? AND industry IN("+industries.map(()=>'?').join(',')+") ORDER BY rowid LIMIT 200").all(attempts,...industries).map(r=>this.item(r));}
|
||||
blockUnmapped(industries){this.db.prepare("UPDATE items SET status='blocked',error='此产业尚未配置接口人收件组。' WHERE status IN('pending','blocked')"+(industries.length?' AND industry NOT IN('+industries.map(()=>'?').join(',')+')':'')).run(...industries);}
|
||||
block(id,message){this.db.prepare("UPDATE items SET status='blocked',error=? WHERE id=? AND status IN('pending','blocked')").run(message,id);}
|
||||
prepare(items,snapshot){return this.transaction(()=>{const id=crypto.randomUUID();this.db.prepare('INSERT INTO batches VALUES(?,?,?,?,?)').run(id,'prepared',this.encode(id,{...snapshot,itemIds:items.map(item=>item.id)}),null,new Date().toISOString());for(const item of items){const result=this.db.prepare("UPDATE items SET status='reserved',attempts=attempts+1,error=NULL,batch_id=? WHERE id=? AND status IN('pending','blocked') AND attempts<?").run(id,item.id,this.settings().maxAttempts);if(!result.changes)fail('通知队列已变化,请重试。',409);}return id;});}
|
||||
beginSending(id){return this.transaction(()=>{
|
||||
const batch=this.db.prepare('SELECT * FROM batches WHERE id=?').get(id);if(!batch||batch.status!=='prepared')fail('通知批次预留已失效。',409);
|
||||
const expected=this.decode(id,batch.payload).itemIds,rows=this.db.prepare('SELECT id,status FROM items WHERE batch_id=?').all(id);
|
||||
if(!expected?.length||rows.length!==expected.length||rows.some(row=>row.status!=='reserved'||!expected.includes(row.id)))fail('通知队列预留归属已变化。',409);
|
||||
const changed=this.db.prepare("UPDATE batches SET status='sending' WHERE id=? AND status='prepared'").run(id);if(!changed.changes)fail('通知批次已变化。',409);
|
||||
this.db.prepare("UPDATE items SET status='sending' WHERE batch_id=? AND status='reserved'").run(id);return true;
|
||||
});}
|
||||
mark(id,status,message=null){if(status==='sending')return this.beginSending(id);return this.transaction(()=>{
|
||||
const row=this.db.prepare('SELECT status FROM batches WHERE id=?').get(id);if(!row||!['prepared','sending'].includes(row.status))return false;
|
||||
if(status==='failed'&&row.status!=='prepared')return false;
|
||||
this.db.prepare('UPDATE batches SET status=?,error=? WHERE id=?').run(status,message,id);
|
||||
this.db.prepare("UPDATE items SET status=?,error=? WHERE batch_id=? AND status IN('reserved','sending')").run(status==='failed'?'pending':status,message,id);if(status==='failed')this.exhaustEligible();return true;
|
||||
});}
|
||||
retryItem(id,input,actor){return this.transaction(()=>{
|
||||
if(!input||typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000||!(input.batchId===null||typeof input.batchId==='string')||!actor)fail('请填写至少 5 字的修复核验依据及当前批次。');
|
||||
const row=this.db.prepare('SELECT * FROM items WHERE id=?').get(id);if(!row||row.status!=='exhausted'||row.batch_id!==input.batchId)fail('只能重新入队当前次数耗尽的通知,请刷新。',409);
|
||||
const changed=this.db.prepare("UPDATE items SET status='pending',attempts=0,error=NULL,batch_id=NULL WHERE id=? AND status='exhausted' AND batch_id IS ?").run(id,input.batchId);if(!changed.changes)fail('通知已被修改,请刷新。',409);
|
||||
const auditId=crypto.randomUUID();this.db.prepare('INSERT INTO retry_audit VALUES(?,?,?)').run(auditId,id,this.encode(auditId,{itemId:id,batchId:input.batchId,note:input.note.trim(),actor,at:new Date().toISOString()}));return {ok:true};
|
||||
});}
|
||||
batches(){return this.db.prepare("SELECT * FROM batches ORDER BY CASE status WHEN 'unknown' THEN 0 ELSE 1 END,rowid DESC LIMIT 100").all().map(({payload,...r})=>({...this.decode(r.id,payload),...r}));}
|
||||
resolve(id,input,actor){return this.transaction(()=>{const row=this.db.prepare('SELECT * FROM batches WHERE id=?').get(id);if(!row||row.status!=='unknown')fail('只能核验结果待核实的批次。',409);if(!input||!['sent','retry'].includes(input.resolution)||typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请选择核验结果并填写至少 5 字的核验依据。');const data={...this.decode(id,row.payload),resolution:input.resolution,note:input.note.trim(),resolvedBy:actor,resolvedAt:new Date().toISOString()};this.db.prepare('UPDATE batches SET status=?,payload=? WHERE id=?').run('resolved_'+input.resolution,this.encode(id,data),id);this.db.prepare('UPDATE items SET status=?,error=NULL,attempts=CASE WHEN ? THEN 0 ELSE attempts END WHERE batch_id=?').run(input.resolution==='sent'?'sent':'pending',input.resolution==='retry'?1:0,id);return {ok:true};});}
|
||||
close(){if(this.db){this.db.close();this.db=null;}this.vault.destroy();}
|
||||
}
|
||||
|
||||
module.exports={NotificationStore};
|
||||
Reference in new issue
Block a user