feat: add restricted stability test mode

This commit is contained in:
abaishu0730 committed 2026-10-22 10:23:04 +08:00
1 parent 0f1631b35a
commit 0890b01d77
19 files changed
+383 -25

No files matched your search

+5 -3
View File
@@ -51,7 +51,7 @@ class OrderExecutionCoordinator{
if(!snapshot||snapshot.processVersion!==sample.processVersion||!Array.isArray(snapshot.fields))throw Error('采集样本流程版本或实际字段证据不一致。');
}
async checkArchivedRuntime(task,order,connection,principal){
const published=this.store.get('rules',order.ruleSnapshot?.id)?.published;
const published=this.store.executionRule(this.store.get('rules',order.ruleSnapshot?.id));
if(published?.status!=='enabled')return;
try{
if(!order.archive?.files?.length||typeof this.archive.read!=='function')throw Error('持久归档缺少可读回的文件证据。');
@@ -167,7 +167,9 @@ class OrderExecutionCoordinator{
this.store.transaction(()=>{
for(const row of rows){
if(row.source!=='todo')continue;
const rules=this.store.all('rules').map(r=>r.published?.status==='enabled'?r.published:r.draft).filter(rule=>matchesScope(rule,row));
const testing=require('../order-rules/restricted-test.cjs').state(this.store);
if(testing&&(row.source!=='todo'||row.configurationOnly||Date.parse(row.receivedAt)<Date.parse(testing.since)))continue;
const rules=this.store.all('rules').map(r=>this.store.executionRule(r)||(!testing?r.draft:null)).filter(rule=>rule&&matchesScope(rule,row));
if(!rules.length)continue;
const id=hash([connection.id,row.source,String(row.instanceId),String(row.taskId),String(row.revision)]);
let task=this.store.get('execution-tasks',id);
@@ -254,7 +256,7 @@ class OrderExecutionCoordinator{
const captured=this.store.recordCapture({sample,snapshot,taskId:task.id});task.sampleId=captured.id;task.step='identify';this.persist(task);
}
const captured=this.store.get('capture-samples',task.sampleId);let order;
await this.refreshCapabilities(this.store.all('rules').find(r=>task.categoryIds.includes(r.id))?.published);
await this.refreshCapabilities(this.store.executionRule(this.store.all('rules').find(r=>task.categoryIds.includes(r.id))));
if(task.orderId){order=this.store.get('orders',task.orderId);if(order?.status==='blocked'&&!order.archive)try{order=this.store.recheck(order.id,{note:'重新扫描使用当前已核验规则'},principal.user.username);}catch(error){task.status='blocked';task.error=error.message;this.persist(task);await this.exception(task,connection,false);return;}}
if(!order){order=this.store.ingest(captured.sample,principal.user.username);task.orderId=order.id;}
Object.assign(task,this.store.get('execution-tasks',task.id));
+5 -1
View File
@@ -29,7 +29,11 @@ async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,re
}
if(user.role!=='admin')fail('仅管理员可维护规则、批次与发送设置。',403);
let result;
if(route==='/api/order-rules/import/preview')result=require('./import.cjs').previewImport(orderRules,body,actor);
if(route==='/api/order-rules/restricted-test'){
if(body?.enabled){const channelId=orderRules.restrictedTest()?.channelId||body.channelId;if(!mail?.store.publicChannel(channelId)?.state.smtp)fail('请先验证测试发件邮箱SMTP。',409);for(const record of orderRules.all('rules'))if(!body.ruleIds||body.ruleIds.includes(record.id))checkTemplates(mail,orderRules.executionRule(record)||record.draft);}
result=orderRules.saveRestrictedTest(body,user);
}
else if(route==='/api/order-rules/import/preview')result=require('./import.cjs').previewImport(orderRules,body,actor);
else if(route==='/api/order-rules/import/commit')result=require('./import.cjs').commitImport(orderRules,body,actor,{mail});
else if(route==='/api/order-rules/rules'){
const old=orderRules.get('rules',body?.id)?.draft;
+3
View File
@@ -69,6 +69,7 @@ class OrderRuleDispatcher{
async dispatch(batch,config,{manual=false}={}){
let transport,sending=false;
try{
require('./restricted-test.cjs').assertBatch(this.store,batch,config);
if(batch.channelId&&batch.channelId!==config.channelId){
this.store.finishSending(batch.id,'failed','批次固定的发件邮箱与当前渠道不同,请核实邮箱设置后生成新批次。');return;
}
@@ -85,6 +86,7 @@ class OrderRuleDispatcher{
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)>1800000)throw Error('冻结发送队列超过30分钟。');
this.mail.store.guard(channel.id,channel.version);
require('./restricted-test.cjs').assertBatch(this.store,batch,config);
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()));
@@ -107,6 +109,7 @@ class OrderRuleDispatcher{
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);
require('./restricted-test.cjs').assertBatch(this.store,original,{...this.store.settings(),channelId:original.channelId});
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);
+1
View File
@@ -56,6 +56,7 @@ function synchronizeTasks(store,order){
}
}
function preview(store,id,input){
if(require('./restricted-test.cjs').state(store))fail('受限测试期间不能向正式规则迁移订单,投产须另行检查。',409);
validate(input);
const rule=store.get('rules',id)?.published;
if(!rule||rule.status!=='enabled'||input.version!==rule.version){
+2 -2
View File
@@ -38,7 +38,7 @@ function taskEvidence(task,context,user){
}
function orderRow(order,task){
const event=identity(order?.event||task?.row);
return {...event,...pick(order,['id','status','categoryId','error','reason','batchId','createdAt','updatedAt','orderNo','receivedAt']),...(order?{notifications:notifications(order)}:{}),
return {...event,...pick(order,['id','status','categoryId','error','reason','batchId','createdAt','updatedAt','orderNo','receivedAt']),...(order?{notifications:notifications(order),...(order.ruleSnapshot?.testRunId?{testRunId:order.ruleSnapshot.testRunId}:{})}:{}),
id:order?.id||'task:'+task.id,connectionId:order?.sample?.connectionId||event.connectionId||task?.connectionId,
error:task?.error||order?.error,executionTaskId:task?.id,executionStatus:task?.status,exceptionId:task?.exceptionId,orderNo:order?.orderNo||event.orderNo||event.serialNum||event.taskId,
categoryId:order?.categoryId||task?.categoryIds?.[0]||'',status:task&&['failed','blocked','unknown','capturing','archiving'].includes(task.status)?task.status:order?.status||task?.status};
@@ -77,7 +77,7 @@ function publicRevision(context,user){
}
function queryOrders(context,input,user){return page(visibleOrders(context,user),filters(input,'orders'),publicRevision(context,user));}
function batchRow(context,batch){
return {...pick(batch,['id','version','categoryId','subject','status','error','createdAt','windowStart','windowEnd','cutoff','orderNos']),notificationMode:modeOf(batch),windowStart:batch.windowStart||batch.window?.start,windowEnd:batch.windowEnd||batch.window?.end||batch.cutoff,orderCount:batch.orderIds?.length||0,connectionIds:[...new Set((batch.orderIds||[]).map(id=>{const o=context.orderRules.get('orders',id);return o?.sample?.connectionId||o?.event?.connectionId||o?.connectionId;}).filter(Boolean))]};
return {...pick(batch,['id','version','categoryId','subject','status','error','createdAt','windowStart','windowEnd','cutoff','orderNos','testRunId']),notificationMode:modeOf(batch),windowStart:batch.windowStart||batch.window?.start,windowEnd:batch.windowEnd||batch.window?.end||batch.cutoff,orderCount:batch.orderIds?.length||0,connectionIds:[...new Set((batch.orderIds||[]).map(id=>{const o=context.orderRules.get('orders',id);return o?.sample?.connectionId||o?.event?.connectionId||o?.connectionId;}).filter(Boolean))]};
}
function queryBatches(context,input,user){
const f=filters(input,'batches'),data=records(context.orderRules);
@@ -0,0 +1,82 @@
'use strict';
const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto');
const {fail,publicationIssues,addresses}=require('./validation.cjs');
const {scopesFor}=require('./scopes.cjs');
const canonical=v=>Array.isArray(v)?v.map(canonical):v&&typeof v==='object'?Object.fromEntries(Object.keys(v).sort().map(k=>[k,canonical(v[k])])):v;
const hash=v=>crypto.createHash('sha256').update(JSON.stringify(canonical(v))).digest('hex');
const state=store=>typeof store?.get==='function'?store.get('restricted-test','main')?.value||null:null;
function localPath(unc){
if(typeof unc!=='string'||/[\x00-\x1f/:]/.test(unc)||!/^\\\\localhost\\[a-z]\$\\/i.test(unc)||unc.split('\\').some(p=>p==='.'||p==='..'||/[. ]$/.test(p)))fail('受限测试仅允许当前用户桌面的localhost共享子目录。',409);
return unc[12]+':\\'+unc.slice(15);
}
function inside(root,target){const relative=path.win32.relative(root,target);return !relative.startsWith('..')&&!path.win32.isAbsolute(relative);}
function realAncestor(target){let current=target;while(!fs.existsSync(current)){const parent=path.dirname(current);if(parent===current)fail('受限测试目录不可访问。',409);current=parent;}return fs.realpathSync(current);}
function assertPath(store,directory,run=state(store)){
if(!run)return;
const root=localPath(run.archiveRoot),target=localPath(directory);
if(!inside(root,target)||!inside(fs.realpathSync(root),realAncestor(target)))fail('受限测试归档超出固定桌面目录。',409);
}
function evidence(store,adapter){
const captured=store.get('capture-samples',adapter.sampleId||'');
if(!captured||captured.provenance!=='server-provider'||captured.sample?.demo||captured.evidenceHash!==adapter.evidenceHash||captured.processName!==adapter.processName||captured.processVersion!==adapter.processVersion)return false;
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 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;
const rule=run.rules.find(r=>r.id===record?.id);return rule&&validRule(store,rule,run)?structuredClone(rule):null;
}
function save(store,input,actor){
if(actor?.role!=='admin'||!actor.username)fail('仅管理员可以维护受限测试。',403);
return store.transaction(()=>{
const old=state(store),keys=['version','enabled','recipient','archiveRoot','channelId','ruleIds'];
if(!input||Object.keys(input).some(k=>!keys.includes(k))||typeof input.enabled!=='boolean'||input.version!==(old?.version||0))fail('受限测试配置已变化,请刷新。',409);
if(old){
for(const key of ['recipient','archiveRoot','channelId'])if(input[key]!==undefined&&input[key]!==old[key])fail('受限测试目的地已固定,不能通过启停修改。',409);
if(input.ruleIds&&hash([...input.ruleIds].sort())!==hash(old.rules.map(r=>r.id).sort()))fail('受限测试类别已固定。',409);
const next={...old,enabled:input.enabled,version:old.version+1};
if(next.enabled){assertPath(store,next.archiveRoot,next);if(next.rules.some(r=>!validRule(store,r,next)))fail('测试字段配置已变化,需要重新核验,不能直接恢复。',409);}
store.put('restricted-test',{id:'main',value:next});store.audit(actor.username,next.enabled?'恢复受限测试':'暂停受限测试',next.id);return summary(store);
}
if(!input.enabled)fail('尚未建立受限测试配置。',409);
const [recipient]=addresses([input.recipient]);if(!/^[\w.!#$%&'*+\/=?^`{|}~-]+@qq\.com$/i.test(recipient))fail('受限测试只允许一个QQ收件箱。',409);
const local=localPath(input.archiveRoot),desktop=store.desktopRoot;
if(!fs.existsSync(local)||!fs.statSync(local).isDirectory()||!inside(desktop,local)||path.win32.relative(desktop,local)===''||!inside(fs.realpathSync(desktop),fs.realpathSync(local)))fail('请选择当前用户桌面内已有的测试子目录。',409);
if(typeof input.channelId!=='string'||!input.channelId||input.channelId.length>100)fail('请选择已验证的测试发件通道。',409);
if(!Array.isArray(input.ruleIds)||!input.ruleIds.length||new Set(input.ruleIds).size!==input.ruleIds.length)fail('请选择测试类别。',409);
const run={id:crypto.randomUUID(),version:1,enabled:true,recipient,archiveRoot:input.archiveRoot,channelId:input.channelId,since:store.now(),rules:[],uncovered:[],adapterHashes:{}};
for(const id of input.ruleIds){
const record=store.get('rules',id);if(!record)fail('测试类别不存在。',409);
const draft=record.draft,adapters=store.adapters().filter(a=>a.verified&&!a.reference&&draft.adapterIds.includes(a.id)&&evidence(store,a));
const covered=draft.processNames.filter(p=>adapters.some(a=>a.processName===p));
run.uncovered.push(...draft.processNames.filter(p=>!covered.includes(p)).map(processName=>({categoryId:id,processName})));
const rule={...structuredClone(draft),processNames:covered,scopes:scopesFor(draft).filter(s=>covered.includes(s.processName)),adapterIds:adapters.map(a=>a.id),status:'enabled',testRunId:run.id,testSince:run.since,testArchiveRoot:run.archiveRoot};
if(!covered.length||!rule.scopes.length)fail('类别缺少已验证的真实字段证据:'+draft.name,409);
assertRule(store,rule,run);
const issues=publicationIssues(rule,adapters);if(issues.length)fail(issues.join(';'),409);
if(run.rules.some(r=>require('./scopes.cjs').scopesOverlap(r,rule)))fail('测试类别存在流程节点冲突。',409);
run.rules.push(rule);run.adapterHashes[id]=hash(rule.adapterIds.map(id=>store.adapters().find(a=>a.id===id)));
}
store.put('restricted-test',{id:'main',value:run});store.audit(actor.username,'建立受限测试',run.id+' '+run.rules.length+'类');return summary(store);
});
}
function assertRule(store,rule,run=state(store)){
if(!run){if(rule?.testRunId)fail('测试配置不存在,禁止按正式规则继续执行。',409);return;}
if(!run.enabled||rule?.testRunId!==run.id||rule.testArchiveRoot!==run.archiveRoot)fail('受限测试已暂停或执行快照不一致。',409);
const frozen=run.rules.find(r=>r.id===rule.id);if(frozen&&(!validRule(store,frozen,run)||hash(frozen)!==hash(rule)))fail('受限测试字段或规则快照已变化。',409);
if(rule.to?.length!==1||rule.to[0]!==run.recipient||rule.cc?.length)fail('受限测试收件人必须为固定QQ且无抄送。',409);
assertPath(store,rule.archiveDirectory,run);
}
function assertEvent(store,sample){const run=state(store);if(!run)return;
if(!run.enabled||sample?.demo||sample?.source!=='todo'||sample.configurationOnly||!Number.isFinite(Date.parse(sample.receivedAt))||Date.parse(sample.receivedAt)<Date.parse(run.since)||Date.parse(sample.receivedAt)>Date.parse(store.now())+60000)fail('受限测试只处理启用基线之后新到达的真实待办通知。',409);
}
function assertOrder(store,order){assertRule(store,order?.ruleSnapshot);if(state(store)||order?.ruleSnapshot?.testRunId){assertEvent(store,order.sample||order.event);for(const file of order.archive?.files||[])assertPath(store,file.path);}}
function assertBatch(store,batch,config){
const run=state(store);if(!run&&!batch.ruleSnapshot?.testRunId)return;
assertRule(store,batch.ruleSnapshot,run);if(batch.testRunId!==run.id||batch.channelId!==run.channelId||config.channelId!==run.channelId||batch.to?.length!==1||batch.to[0]!==run.recipient||batch.cc?.length)fail('受限测试批次目的地与固定配置不一致。',409);
for(const file of batch.attachments||[])assertPath(store,file.path,run);
for(const id of batch.orderIds||[]){const order=store.get('orders',id);if(!order)fail('测试批次订单不存在。',409);assertOrder(store,order);}
}
module.exports={state,summary,save,executionRule,assertPath,assertRule,assertEvent,assertOrder,assertBatch};
+21 -7
View File
@@ -15,7 +15,8 @@ const copy=value=>structuredClone(value);
const BASE_CAPABILITIES={liveTodo:false,pdfExport:false,automaticArchive:false};
function validDate(value){return typeof value==='string'&&/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value)&&Number.isFinite(Date.parse(value));}
class RuleStore{
constructor(dir,{clock=()=>new Date(),capabilities={},seedOverrides=[],schedule=()=>({times:['11:00','17:00'],weekends:false}),calendar=()=>[]}={}){
constructor(dir,{clock=()=>new Date(),capabilities={},seedOverrides=[],schedule=()=>({times:['11:00','17:00'],weekends:false}),calendar=()=>[],desktopRoot=path.join(require('node:os').homedir(),'Desktop')}={}){
this.desktopRoot=desktopRoot;
this.clock=clock;this.schedule=schedule;this.calendar=calendar;this.capabilities={...BASE_CAPABILITIES,...capabilities};
try{
fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});
@@ -43,6 +44,9 @@ class RuleStore{
}catch(error){try{this.db?.close();}catch{}this.vault?.destroy();throw error;}
}
now(){return this.clock().toISOString();}
restrictedTest(){return require('./restricted-test.cjs').summary(this);}
saveRestrictedTest(input,actor){return require('./restricted-test.cjs').save(this,input,actor);}
executionRule(record){return require('./restricted-test.cjs').executionRule(this,record);}
providersReady(){return ['liveTodo','pdfExport','automaticArchive'].every(key=>this.capabilities[key]===true);}
adapters(){return registry.registry(this);}
fields(){return registry.fields(this);}
@@ -64,6 +68,7 @@ class RuleStore{
settings(){const {id,...settings}=this.get('settings','main');return {...settings,processingEnabled:settings.processingEnabled??settings.enabled,processingSince:settings.processingSince??null};}
saveSettings(input,actor){return this.transaction(()=>{
const old=this.settings();
const testing=this.restrictedTest();if(testing&&input?.channelId!==testing.channelId)fail('受限测试发件通道已固定。',409);
if(!input||Object.keys(input).some(k=>!['version','enabled','processingEnabled','processingSince','channelId','maxMessageBytes'].includes(k))||input.version!==old.version)fail('设置已变化,请刷新。',409);
if(typeof input.enabled!=='boolean'||typeof input.channelId!=='string'||input.channelId.length>100||!Number.isInteger(input.maxMessageBytes)||input.maxMessageBytes<1024||input.maxMessageBytes>100*1024*1024)fail('邮箱或邮件大小限制无效。');
if(input.enabled&&(!this.providersReady()||!input.channelId))fail('待办接入、PDF 导出与自动归档尚未全部联调,暂不能启用自动发送。',409);
@@ -74,7 +79,8 @@ class RuleStore{
queryRevision(){return Number(this.db.prepare('SELECT total_changes() AS revision').get().revision);}
snapshot({includeRecords=true}={}){
const adapters=this.adapters(),rules=this.all('rules').map(record=>({...record.draft,status:record.published?.status||'draft',activationVersion:record.activationVersion||0,hasDraft:!record.published||record.draft.version!==record.published.version,publishedVersion:record.published?.version||null,trialVersion:record.trialVersion,mappingIssue:record.mappingIssue||null,explanation:describeRule(record.draft),validationIssues:publicationIssues(record.draft,adapters)}));
return {rules,adapters,orders:includeRecords?this.all('orders').reverse():[],batches:includeRecords?this.all('batches').reverse():[],settings:this.settings(),audit:includeRecords?this.all('audit').slice(-100).reverse():[],capabilities:copy(this.capabilities),window:upcomingWindow(this.clock(),this.schedule(),this.calendar())};
const restrictedTest=typeof this.restrictedTest==='function'?this.restrictedTest():null;for(const rule of rules)if(restrictedTest){const active=typeof this.executionRule==='function'?this.executionRule({id:rule.id}):null;rule.testStatus=active?'enabled':'paused';}
return {rules,restrictedTest,adapters,orders:includeRecords?this.all('orders').reverse():[],batches:includeRecords?this.all('batches').reverse():[],settings:this.settings(),audit:includeRecords?this.all('audit').slice(-100).reverse():[],capabilities:copy(this.capabilities),window:upcomingWindow(this.clock(),this.schedule(),this.calendar())};
}
saveRule(input,actor){return this.transaction(()=>{
const record=this.get('rules',input?.id);if(!record)fail('规则不存在。',404);
@@ -88,6 +94,7 @@ class RuleStore{
return result;
}
publish(id,input,actor){return this.transaction(()=>{
if(this.restrictedTest()?.enabled)fail('受限测试运行期间不能发布正式分类规则;请先暂停测试并重新检查真实通知。',409);
const record=this.get('rules',id);if(!record)fail('规则不存在。',404);
if(input?.version!==record.draft.version)fail('规则已变化,请刷新。',409);
const issues=publicationIssues(record.draft,this.adapters());
@@ -119,12 +126,13 @@ class RuleStore{
record.published.status='enabled';record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);this.audit(actor,'启用已发布规则',id+' v'+record.published.version);return this.snapshot().rules.find(r=>r.id===id);
});}
matchingPublications(sample){
const rules=this.all('rules').filter(r=>r.published).map(r=>r.published);
const rules=this.all('rules').map(r=>this.executionRule(r)).filter(Boolean);
const enabled=rules.filter(r=>r.status==='enabled');
const hasEnabledMatch=enabled.some(r=>matchesScope(r,sample));
return hasEnabledMatch?enabled:rules;
}
ingest(sample,actor){return this.transaction(()=>{
require('./restricted-test.cjs').assertEvent(this,sample);
if(sample?.demo)fail('演示样本仅用于试运行,不能创建正式任务。');
if(!sample||['connectionId','source','instanceId','taskId','revision'].some(k=>!['string','number'].includes(typeof sample[k])||!String(sample[k]).trim()||String(sample[k]).length>250))fail('缺少来源、流程实例、任务及业务修订标识。');
sample=copy(sample);for(const key of ['connectionId','source','instanceId','taskId','revision'])sample[key]=String(sample[key]).trim();
@@ -134,6 +142,7 @@ class RuleStore{
const active=this.matchingPublications(sample);
const result=previewMatch(active,this.adapters(),sample),rule=active.find(r=>r.id===result.ruleId);
const ready=this.providersReady(),enabled=rule?.status==='enabled';
if(rule)require('./restricted-test.cjs').assertRule(this,rule);
const order={id,sourceHash,event:result.event||copy(sample),sample:copy(sample),ruleSnapshot:rule?copy(rule):null,categoryId:result.categoryId||rule?.categoryId||'',status:result.valid&&ready&&enabled?'identified':'blocked',error:result.valid?(!enabled?'该类别规则已暂停。':ready?null:'待办接入、PDF 导出和自动归档待联调。'):result.issues.join(';'),ingestedAt:this.now(),updatedAt:this.now(),archive:null,batchId:null,trace:result};
order.notifications={huizhou:initialNotification(rule,order.event)};
const window=upcomingWindow(this.clock(),this.schedule(),this.calendar());
@@ -145,6 +154,7 @@ class RuleStore{
recordArchive(id,evidence,actor,expected){return this.transaction(()=>{
if(!this.capabilities.automaticArchive)fail('自动归档接入待联调。',409);
const order=this.get('orders',id);if(!order)fail('订单任务不存在。',404);
require('./restricted-test.cjs').assertOrder(this,{...order,archive:evidence});
const stale=expected&&!require('./migrations.cjs').archiveContextMatches(this,order,expected);
if(!stale){
if(!['identified','preparing'].includes(order.status))fail('当前状态不允许记录归档结果。',409);
@@ -178,6 +188,7 @@ class RuleStore{
if(!order||order.blockedByBatchId||require('./migrations.cjs').frozen(this,order)||!['blocked','identified','preparing','archived','pending'].includes(order.status))fail('仅未进入批次的待处理订单可以重新识别。',409);
const published=this.matchingPublications(order.sample);
const result=previewMatch(published,this.adapters(),order.sample),rule=published.find(r=>r.id===result.ruleId);
require('./restricted-test.cjs').assertEvent(this,order.sample);if(rule)require('./restricted-test.cjs').assertRule(this,rule);
if(!result.valid||rule?.status!=='enabled')fail(result.issues.join(';')||'对应规则尚未启用。',409);
order.event=result.event;order.ruleSnapshot=copy(rule);order.categoryId=rule.categoryId;order.trace=result;
if(order.notifications)order.notifications.huizhou=initialNotification(rule,order.event);
@@ -237,7 +248,7 @@ class RuleStore{
const blockers=this.discoveryBlockers(cutoff);
const resultId=(category,mode)=>category+':'+cutoff+(mode==='normal'?'':':'+mode);
const existingBatch=(category,mode)=>this.all('batches').find(b=>b.categoryId===category&&modeOf(b)===mode&&Date.parse(b.cutoff)===Date.parse(cutoff)&&!(b.status==='cancelled'&&b.resolution?.resolution==='retry'));
for(const record of this.all('rules').filter(r=>r.published?.status==='enabled'))for(const mode of record.published.huizhouEnabled===true?['normal','huizhou']:['normal']){const categoryId=record.published.categoryId,existing=existingBatch(categoryId,mode);this.put('window-results',{id:resultId(categoryId,mode),categoryId,notificationMode:mode,cutoff,status:existing?'frozen':blockers.length?'blocked':'empty',batchId:existing?.id||null,error:blockers.join(';')||null,updatedAt:this.now()});}
for(const rule of this.all('rules').map(r=>this.executionRule(r)).filter(r=>r?.status==='enabled'))for(const mode of rule.huizhouEnabled===true?['normal','huizhou']:['normal']){const categoryId=rule.categoryId,existing=existingBatch(categoryId,mode);this.put('window-results',{id:resultId(categoryId,mode),categoryId,notificationMode:mode,cutoff,status:existing?'frozen':blockers.length?'blocked':'empty',batchId:existing?.id||null,error:blockers.join(';')||null,updatedAt:this.now()});}
if(blockers.length)return [];
const grouped=new Map(),batches=[];
for(const order of this.all('orders'))for(const mode of ['normal','huizhou']){
@@ -256,17 +267,19 @@ class RuleStore{
// companion after repairing a Hui-only blocker. Historical freezes stay closed.
const normal=mode==='huizhou'&&existingBatch(rule.categoryId,'normal');
if(normal&&normal.huizhouPlanned!==true)continue;
const published=this.get('rules',rule.id)?.published;
const published=this.executionRule(this.get('rules',rule.id));
let error=!published||published.status!=='enabled'?'该类别规则已暂停。':null;
if(!error&&published.version!==rule.version)error='本类别订单规则版本已过期,请应用当前已发布规则后处理。';
if(!error&&this.categoryIncomplete(rule.categoryId,window))error='本类别存在未完成的采集、归档或核验任务。';
if(!error&&mode==='huizhou'&&orders.some(o=>delivery(o,mode).issues?.length))error=orders.flatMap(o=>delivery(o,mode).issues||[]).join(';');
if(!error&&orders.some(o=>mode==='normal'?o.status!=='pending':!o.archive||!['pending','batched','sent','unknown'].includes(o.status)))error='本类别存在字段、文件或归档尚未准备完成的订单。';
let snapshot;
if(!error)try{const selected=ordersForMode(orders,mode);snapshot=buildBatch(rule,selected,cutoff,{maxMessageBytes:this.settings().maxMessageBytes,window,notificationMode:mode});snapshot=applyBodyTemplate(snapshot,this.templateResolver?.(rule.categoryId,rule,mode),selected,this.settings().maxMessageBytes);}catch(cause){error=cause.message;}
if(!error)try{for(const order of orders)require('./restricted-test.cjs').assertOrder(this,order);const selected=ordersForMode(orders,mode);snapshot=buildBatch(rule,selected,cutoff,{maxMessageBytes:this.settings().maxMessageBytes,window,notificationMode:mode});snapshot=applyBodyTemplate(snapshot,this.templateResolver?.(rule.categoryId,rule,mode),selected,this.settings().maxMessageBytes);}catch(cause){error=cause.message;}
const key=resultId(rule.categoryId,mode);
if(error){this.put('window-results',{id:key,categoryId:rule.categoryId,notificationMode:mode,cutoff,status:'blocked',error,updatedAt:this.now()});this.recordIssue('build:'+key,{component:'rules',notificationMode:mode,error,cutoff,categoryId:rule.categoryId,orderIds:orders.map(o=>o.id)});for(const original of orders){const order=this.get('orders',original.id);updateDelivery(order,mode,{error,...(mode==='huizhou'?{status:'blocked'}:{})});this.put('orders',order);}continue;}
const batch={...snapshot,id:crypto.randomUUID(),version:1,status:'prepared',createdAt:this.now(),ruleSnapshot:copy(rule),channelId:this.settings().channelId,error:null};
if(rule.testRunId)batch.testRunId=rule.testRunId;
require('./restricted-test.cjs').assertBatch(this,batch,this.settings());
if(mode==='normal')batch.huizhouPlanned=rule.huizhouEnabled===true&&orders.some(order=>!!order.notifications?.huizhou);
this.put('batches',batch);this.put('window-results',{id:key,categoryId:rule.categoryId,notificationMode:mode,cutoff,status:'frozen',batchId:batch.id,updatedAt:this.now()});
const issue=this.get('business-issues','build:'+key);if(issue)this.put('business-issues',{...issue,status:'awaiting_verification',updatedAt:this.now()});
@@ -279,7 +292,8 @@ class RuleStore{
releaseBatchOrders(batch){for(const id of batch.orderIds){const order=this.get('orders',id),mode=modeOf(batch);if(delivery(order,mode)?.batchId===batch.id){updateDelivery(order,mode,{batchId:null});this.put('orders',order);}}}
beginSending(id,{manual=false}={}){return this.transaction(()=>{
const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
if(!(manual&&batch.manual)&&this.get('rules',batch.ruleSnapshot.id)?.published?.status!=='enabled')fail('该类别规则已暂停,批次不能进入发送。',409);
require('./restricted-test.cjs').assertBatch(this,batch,this.settings());
if(!(manual&&batch.manual)&&this.executionRule(this.get('rules',batch.ruleSnapshot.id))?.status!=='enabled')fail('该类别规则已暂停,批次不能进入发送。',409);
if(this.batchIncomplete(batch)||!(manual&&batch.manual)&&this.discoveryBlockers(batch.cutoff).length)throw Object.assign(Error('待办扫描或类别订单尚不完整,等待完整扫描与恢复。'),{status:409,code:'DISCOVERY_INCOMPLETE'});
const orders=batch.orderIds.map(oid=>this.get('orders',oid));
if(this.all('execution-tasks').some(task=>batch.orderIds.includes(task.orderId)&&task.runtimeCheck?.status==='blocked'))fail('已归档订单的运行条件复核未通过,批次不能进入发送。',409);
+5
View File
@@ -5,6 +5,7 @@ const crypto=require('node:crypto');
const {segments,inside}=require('./files.cjs');
const {renderSnapshot}=require('../pdf/exporter.cjs');
const {archiveFilename}=require('./order-filename.cjs');
const restricted=require('../order-rules/restricted-test.cjs');
const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])])):value;
const fingerprint=value=>crypto.createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
const fail=message=>Object.assign(new Error(message),{status:409});
@@ -21,6 +22,7 @@ class OrderArchiveProvider{
constructor({storage,outputDir,renderer=renderSnapshot,clock=()=>new Date(),journal}={}){this.storage=storage;this.outputDir=path.resolve(outputDir,'order-execution');this.renderer=renderer;this.clock=clock;this.last=null;this.probes=new Map();this.journal=journal;this.supportsRecovery=!!journal;}
capabilities(){return {automaticArchive:!!this.last?.success,pdfExport:!!this.last?.success,checkedAt:this.last?.at,message:this.last?.message||'尚无经过实际生成和共享目录读回校验的订单归档。'};}
async probe(rule){
if(this.journal)restricted.assertRule(this.journal,rule);
const key=fingerprint(rule.archiveDirectory),cached=this.probes.get(key);if(cached&&+this.clock()-Date.parse(cached.checkedAt)<300000)return cached;
let temporary;
try{
@@ -34,6 +36,7 @@ class OrderArchiveProvider{
}
async archive(input){try{return await this.performArchive(input);}catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;}}
async performArchive({order,rule,snapshot,taskId}){
if(this.journal){restricted.assertRule(this.journal,rule);restricted.assertOrder(this.journal,order);}
const identity=taskId||order.id,generation=order.archiveGeneration||1,id=identity+':g'+generation;
let previous=this.journal?.get('archive-intents',id);
const legacy=generation===1&&!previous&&this.journal?.get('archive-intents',identity);
@@ -57,6 +60,7 @@ class OrderArchiveProvider{
const intent=previous||{id,archiveGeneration:generation,outputFingerprint,sourceHash:order.sourceHash,chosen:new Date(chosen).toISOString(),directory:rule.archiveDirectory,filename,localPath:file,sha256:digest,size:local.length};
if(id&&this.journal&&!previous)this.journal.put('archive-intents',intent);
if(previous?.evidence){const bytes=await this.read(previous.evidence.files[0]);if(bytes.length!==local.length||crypto.createHash('sha256').update(bytes).digest('hex')!==digest)throw fail('已归档文件读回校验失败。');this.last={success:true,at:this.clock().toISOString(),message:'已归档文件再次读回核验通过。'};return previous.evidence;}
if(this.journal){restricted.assertRule(this.journal,rule);restricted.assertPath(this.journal,path.win32.join('\\\\'+target.server.host,target.server.share,...segments(target.server.directory),...segments(target.relative)));}
const receipt=await this.storage.run(target.server.id,async(server,signal)=>{
const saved=await this.storage.operation(server,'archive',[file,intent.filename,target.relative],signal);
const check=await this.storage.operation(server,'readFile',[saved.relativePath],signal),bytes=Buffer.from(check.bytes);
@@ -68,6 +72,7 @@ class OrderArchiveProvider{
}catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;}
}
async read(file){
if(this.journal)restricted.assertPath(this.journal,file.path);
const directory=path.win32.dirname(file.path),target=targetFor(this.storage,directory);
const result=await this.storage.readFile(target.server.id,[target.relative,path.win32.basename(file.path)].filter(Boolean).join('/'));return Buffer.from(result.bytes);
}