fix: preserve intake windows and update vulnerable dependencies

This commit is contained in:
abaishu0730 committed 2026-10-26 14:50:55 +08:00
1 parent f7426c937c
commit b14fa2f4d1
11 files changed
+353 -77

No files matched your search

+7 -4
View File
@@ -6,7 +6,7 @@ const {dayPolicy,nextSlots}=require('../../shared/schedule.cjs');
const {matchesScope}=require('../order-rules/scopes.cjs');
const taskIdentity=require('../order-rules/task-identity.cjs');
const eligibility=require('../order-rules/restricted-test.cjs');
const {collectionBounds,inWindow}=require('../order-rules/window.cjs');
const {collectionBounds,inWindow,upcomingWindow}=require('../order-rules/window.cjs');
const hash=value=>crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
const clone=value=>structuredClone(value);
class OrderExecutionCoordinator{
@@ -234,7 +234,7 @@ class OrderExecutionCoordinator{
this.store.transaction(()=>require('../order-rules/scope-catalog.cjs').observe(this.store,rows));
if(trustedRows===undefined&&eligibility.state(this.store))eligibility.recordCurrentScan(this.store,{connectionId:connection.id,rows,startedAt:this.query.startedAt,finishedAt:this.now()});
let considered=0;const observed=new Set(),discovered=[];
const window=this.store.snapshot().window;
const window=upcomingWindow(new Date(this.query.startedAt),this.store.schedule(),this.store.calendar());
// Commit the entire discovery set before probes, captures, exceptions or archives yield.
this.store.transaction(()=>{
for(const raw of rows){
@@ -259,7 +259,7 @@ class OrderExecutionCoordinator{
// Pre-activation backlog requires explicit admission. Eligible missed-window work is
// retained below without recapturing, archiving, or widening frozen mail.
if(baseline&&received<Date.parse(baseline)&&!task&&!eligibility.isAdmitted(this.store,row))continue;
const historical=window&&Number.isFinite(received)&&received<Date.parse(collectionBounds(window).start)&&!eligibility.isAdmitted(this.store,row);
const historical=window&&Number.isFinite(received)&&received<Date.parse(collectionBounds(window).start)&&!eligibility.isAdmitted(this.store,row)&&!this.store.intakeWindow(row);
const frozen=historical&&this.store.all('batches').find(batch=>rules.some(rule=>rule.categoryId===batch.categoryId)&&batch.window&&inWindow(eligibleAt,batch.window));
if(historical&&!baseline&&!frozen)continue;
considered++;
@@ -268,6 +268,9 @@ class OrderExecutionCoordinator{
task={id,taskKey:taskIdentity.taskIdentity(row),version:0,connectionId:connection.id,owner:connection.owner||'',row:clone(row),categoryIds:[...new Set(rules.map(r=>r.categoryId))],status:'identified',step:'capture',createdAt:this.now()};
this.persist(task);
}
if(!task.intakeWindow&&window&&inWindow(eligibleAt,window)&&Date.parse(this.query.startedAt)<=Date.parse(window.end)+60000){
task.intakeWindow=clone(window);task.intakeStartedAt=this.query.startedAt;this.persist(task);
}
if(taskIdentity.legacyRevisionMissing(task,row)&&taskIdentity.equivalent(task,row)){
task.legacyRow=task.legacyRow||clone(task.row);task.row=clone(row);task.sourceRevisionMissing={observedAt:this.now(),legacyRevision:'0',reason:'旧归一化默认值未由来源证明;本次真实来源未报告业务修订。'};this.persist(task);
}
@@ -328,7 +331,7 @@ class OrderExecutionCoordinator{
this.reconcileArchive(task);
const order=task.orderId&&this.store.get('orders',task.orderId);
if(!needsRuntimeCheck(order))continue;
if(window&&!reserved(order)&&Date.parse(eligibility.orderTime(this.store,order))<Date.parse(collectionBounds(window).start))continue;
if(window&&!reserved(order)&&Date.parse(eligibility.orderTime(this.store,order))<Date.parse(collectionBounds(window).start)&&!this.store.intakeWindow(task.row))continue;
await this.checkArchivedRuntime(task,order,connection,principal);
}
if(input.automatic&&!this.store.settings().processingEnabled)throw Error('自动处理已暂停,待处理对账保留到恢复后继续。');
+5 -2
View File
@@ -34,13 +34,15 @@ class OrderRuleDispatcher{
return task;
}
async perform(now){
this.store.expireIntakes?.();
for(const batch of this.store.snapshot().batches||[])if(batch.status==='prepared'&&!batch.manual&&now-Date.parse(batch.cutoff)>1800000)this.store.finishSending(batch.id,'failed','冻结发送队列超过30分钟,请负责人核验后受控补发。');
if(!this.ready())return;
const config=freeze(structuredClone(this.store.settings())),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||now-Date.parse(this.schedule.next)>60000){const current=require('./window.cjs').upcomingWindow(now,schedule,calendar);this.schedule={signature,next:current?.available?current.end:nextSlots(schedule,now,1,calendar)[0]};}
const cutoff=this.schedule.next,canPrepare=cutoff&&now-Date.parse(cutoff)>=0&&now-Date.parse(cutoff)<=60000;
const resumed=this.store.pendingIntakeCutoffs?.().filter(cutoff=>now-Date.parse(cutoff)>60000)||[];
const cutoff=resumed[0]||this.schedule.next,canPrepare=cutoff&&now-Date.parse(cutoff)>=0&&(now-Date.parse(cutoff)<=60000||resumed.includes(cutoff));
const queued=(this.store.snapshot().batches||[]).some(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
if(!canPrepare&&!queued)return;
try{await this.mail.exclusive(config.channelId,async()=>{
@@ -52,7 +54,8 @@ class OrderRuleDispatcher{
let expected;try{expected=windowForCutoff(batch.cutoff,schedule,calendar);}catch{continue;}
const legacyStart=new Date(Date.parse(batch.cutoff)+8*3600000).toISOString().slice(0,10)+'T00:00:00+08:00';
if(!batch.window||batch.window.end!==expected.end||![Date.parse(expected.start),Date.parse(legacyStart)].includes(Date.parse(batch.window.start))||batch.window.startInclusive!==true||batch.window.endInclusive!==false)continue;
if(batch.createdAt&&(Date.parse(batch.createdAt)>Date.parse(batch.cutoff)+60000||Date.parse(batch.createdAt)<Date.parse(batch.cutoff)))continue;if(await this.dispatch(freeze(structuredClone(batch)),config)===false)continue;}
const grace=batch.intakeGrace?.cutoff===batch.cutoff&&Date.parse(batch.intakeGrace.expiresAt)===Date.parse(batch.cutoff)+1800000&&Date.parse(batch.createdAt)<=Date.parse(batch.intakeGrace.expiresAt)&&batch.orderIds?.every(id=>{const order=this.store.get('orders',id);return order&&this.store.intakeWindow(order.sample||order.event)?.end===batch.cutoff;});
if(batch.createdAt&&(Date.parse(batch.createdAt)>Date.parse(batch.cutoff)+60000&&!grace||Date.parse(batch.createdAt)<Date.parse(batch.cutoff)))continue;if(await this.dispatch(freeze(structuredClone(batch)),config)===false)continue;}
});}catch(error){this.store.recordIssue?.('dispatch:'+String(cutoff),{component:'mail',error:error.message,cutoff});if(error.status!==409)throw error;}
// Keep the current slot during its collection allowance so repaired categories retry.
if(cutoff&&this.clock()-Date.parse(cutoff)>60000)this.schedule={signature,next:nextSlots(schedule,this.clock(),1,calendar)[0]};
+1 -1
View File
@@ -152,7 +152,7 @@ function eventInWindow(store,row,window){
}
return require('./window.cjs').inWindow(at,window);
}
function orderInWindow(store,order,window){return eventInWindow(store,order?.sample||order?.event,window);}
function orderInWindow(store,order,window){const row=order?.sample||order?.event;return store.intakeWindow?.(row)?.end===window.end||eventInWindow(store,row,window);}
function assertCurrentPresence(store,row){
const run=state(store),entry=(run?.currentBacklog||[]).find(item=>taskIdentity.sameTask(item.snapshot,row));if(!entry)return;
const scan=store.get('current-task-scans',entry.scanConnectionId),matches=scan?.rows.filter(observed=>taskIdentity.sameTask(observed,row))||[];
+51 -9
View File
@@ -139,6 +139,39 @@ class RuleStore{
const hasEnabledMatch=enabled.some(r=>matchesScope(r,sample));
return hasEnabledMatch?enabled:rules;
}
intakeWindow(sample,{includeExpired=false}={}){
const task=taskIdentity.lookup(this,'execution-tasks',sample);
if(!task||task.removedAt||task.revisionIgnored||task.supersededBy||task.conflict||!task.intakeWindow||!validDate(task.intakeStartedAt))return null;
if(sample?.connectionId!==undefined&&String(sample.connectionId)!==String(task.connectionId))return null;
if(['source','portalSource','instanceId','taskId','revision','processName','nodeName','receivedAt'].some(key=>String(task.row?.[key])!==String(sample?.[key])))return null;
let window;try{window=windowForCutoff(task.intakeWindow.end,this.schedule(),this.calendar());}catch{return null;}
if(task.intakeWindow.start!==window.start||task.intakeWindow.collectionEnd!==window.collectionEnd||!inWindow(eligibility.eventTime(this,sample),window))return null;
const started=Date.parse(task.intakeStartedAt),cutoff=Date.parse(window.end),now=+this.clock();
if(started>cutoff+60000||started< Date.parse(window.start)||started>now||(!includeExpired&&now>cutoff+1800000))return null;
return window;
}
pendingIntakeCutoffs(){
const now=+this.clock();
return [...new Set(this.all('execution-tasks').filter(task=>!['sent','ignored','unknown','sending'].includes(task.status)||task.step==='complete'&&this.pendingCompanion(task.orderId&&this.get('orders',task.orderId))).map(task=>this.intakeWindow(task.row)?.end).filter(cutoff=>cutoff&&now>=Date.parse(cutoff)&&now<=Date.parse(cutoff)+1800000))].sort();
}
pendingCompanion(order){
const hui=delivery(order,'huizhou'),normal=order?.batchId&&this.get('batches',order.batchId);
return !!order?.archive&&order.ruleSnapshot?.huizhouEnabled===true&&['batched','sending','sent','unknown'].includes(order.status)&&!!hui&&['pending','blocked'].includes(hui.status)&&!hui.batchId&&!hui.missedWindow&&normal?.huizhouPlanned===true&&modeOf(normal)==='normal'&&normal.orderIds?.includes(order.id)&&normal.cutoff===this.intakeWindow(order.sample||order.event,{includeExpired:true})?.end;
}
expireIntakes(){return this.transaction(()=>{
for(const order of this.all('orders')){
const window=this.intakeWindow(order.sample||order.event,{includeExpired:true});
if(!window||+this.clock()<=Date.parse(window.end)+1800000)continue;
if(this.pendingCompanion(order)){
updateDelivery(order,'huizhou',{status:'blocked',error:'原处理时段超过30分钟,等待负责人核验。',missedWindow:window});order.updatedAt=this.now();this.put('orders',order);
this.recordIssue('missed:'+order.id+':huizhou',{component:'rules',notificationMode:'huizhou',error:delivery(order,'huizhou').error,window,orderIds:[order.id]});
}
if(!['identified','preparing','archived','pending','blocked'].includes(order.status)||order.batchId||order.missedWindow)continue;
order.status='blocked';order.error='原处理时段超过30分钟,等待负责人核验。';order.missedWindow=window;order.updatedAt=this.now();this.put('orders',order);
for(const task of this.all('execution-tasks').filter(task=>task.orderId===order.id&&!['unknown','sending','sent','ignored'].includes(task.status)))this.put('execution-tasks',{...task,status:'blocked',step:'missed_window',missedWindow:window,error:order.error,version:(task.version||0)+1,updatedAt:this.now()});
this.recordIssue('missed:'+order.id,{component:'rules',error:order.error,window,orderIds:[order.id]});
}
});}
ingest(sample,actor){return this.transaction(()=>{
require('./restricted-test.cjs').assertEvent(this,sample);
if(sample?.demo)fail('演示样本仅用于试运行,不能创建正式任务。');
@@ -153,10 +186,11 @@ class RuleStore{
if(rule)require('./restricted-test.cjs').assertRule(this,rule);
const order={id,taskKey,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());
const intake=this.intakeWindow(sample),window=intake||upcomingWindow(this.clock(),this.schedule(),this.calendar());
const eligibleAt=eligibility.eventTime(this,sample);
if(window&&validDate(eligibleAt)&&Date.parse(eligibleAt)<Date.parse(collectionBounds(window).start)&&!eligibility.isAdmitted(this,sample)){order.status='ignored';order.error='早于当前处理时段的历史订单,不归档、不补发。';}
const frozen=this.all('batches').find(b=>b.categoryId===order.categoryId&&b.window&&eligibility.eventInWindow(this,sample,b.window));
if(!intake&&this.intakeWindow(sample,{includeExpired:true})){order.status='blocked';order.error='原处理时段超过30分钟,保留采集证据,等待负责人核验。';}
const frozen=this.all('batches').find(b=>b.categoryId===order.categoryId&&b.window&&(eligibility.eventInWindow(this,sample,b.window)||intake?.end===b.window.end));
if(frozen){order.status='blocked';order.blockedByBatchId=frozen.id;order.error='本接收时段的类别已冻结,新增订单须负责人核验,不能混入已冻结邮件。';this.put('orders',order);this.recordIssue('late:'+order.id,{component:'rules',error:order.error,batchId:frozen.id,orderIds:[order.id]});}
this.put('orders',order);this.audit(actor,'识别订单任务',id);return order;
});}
@@ -167,7 +201,7 @@ class RuleStore{
const stale=expected&&!require('./migrations.cjs').archiveContextMatches(this,order,expected);
if(!stale){
if(!['identified','preparing'].includes(order.status))fail('当前状态不允许记录归档结果。',409);
const window=upcomingWindow(this.clock(),this.schedule(),this.calendar());
const window=this.intakeWindow(order.sample||order.event)||upcomingWindow(this.clock(),this.schedule(),this.calendar());
if(window&&Date.parse(eligibility.orderTime(this,order))<Date.parse(collectionBounds(window).start)&&!eligibility.isAdmitted(this,order.sample||order.event))fail('该订单已超出当前时段,不再自动归档或补发。',409);
}
if(!evidence||!validDate(evidence.archivedAt)||!Array.isArray(evidence.files)||!evidence.files.length||evidence.files.some(f=>!f||typeof f.name!=='string'||!f.name||/[\\/\x00-\x1f]/.test(f.name)||typeof f.path!=='string'||!path.win32.isAbsolute(f.path)||! /^[a-f0-9]{64}$/i.test(f.sha256)||!Number.isSafeInteger(f.size)||f.size<1||!['pdf','notice'].includes(f.kind)))fail('归档证据不完整。');
@@ -212,7 +246,7 @@ class RuleStore{
for(const id of pendingSources)blockers.push('连接 '+id+' 完整对账线索尚未处理。');
if(this.activeDiscoveries>0)blockers.push('待办扫描尚未完成,不能冻结或发送不完整类别。');
const window=cutoff?windowForCutoff(cutoff,this.schedule(),this.calendar()):null;
const relevant=this.all('execution-tasks').filter(t=>!window||eligibility.eventInWindow(this,t.row,window));
const relevant=this.all('execution-tasks').filter(t=>!t.removedAt&&(!window||eligibility.eventInWindow(this,t.row,window)));
const sources=new Set([...this.executionSources(),...relevant.filter(t=>!['sent','ignored'].includes(t.status)).map(t=>t.connectionId)]);
for(const id of sources){
if(!allowed(id))continue;
@@ -223,7 +257,7 @@ class RuleStore{
return blockers;
}
categoryIncomplete(categoryId,window){
return this.all('execution-tasks').some(task=>!task.removedAt&&task.categoryIds?.includes(categoryId)&&(!Number.isFinite(Date.parse(eligibility.eventTime(this,task.row)))||eligibility.eventInWindow(this,task.row,window))&&(task.conflict||['identified','blocked','failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'||task.runtimeCheck?.status==='blocked'));
return this.all('execution-tasks').some(task=>!task.removedAt&&task.categoryIds?.includes(categoryId)&&(!Number.isFinite(Date.parse(eligibility.eventTime(this,task.row)))||eligibility.eventInWindow(this,task.row,window)||this.intakeWindow(task.row)?.end===window.end)&&(task.conflict||['identified','blocked','failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'||task.runtimeCheck?.status==='blocked'));
}
batchIncomplete(batch){
return this.all('execution-tasks').some(task=>batch.orderIds.includes(task.orderId)&&(task.conflict||task.runtimeCheck?.status==='blocked'||['failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'));
@@ -251,9 +285,11 @@ class RuleStore{
});
}
prepare(cutoff,actor,requestedWindow){return this.transaction(()=>{
this.expireIntakes();
if(!validDate(cutoff))fail('请选择包含时区的有效发送截止时间。');
const window=windowForCutoff(cutoff,this.schedule(),this.calendar());
if(eligibility.state(this)){const current=upcomingWindow(this.clock(),this.schedule(),this.calendar());if(!current?.available||current.end!==window.end)return [];}
const resuming=this.pendingIntakeCutoffs().includes(window.end)&&+this.clock()>Date.parse(window.end)+60000;
if(eligibility.state(this)){const current=upcomingWindow(this.clock(),this.schedule(),this.calendar());if((!current?.available||current.end!==window.end)&&!resuming)return [];}
if(requestedWindow&&(requestedWindow.start!==window.start||requestedWindow.end!==window.end))fail('发送时段与业务日历不一致。',409);
const blockers=this.discoveryBlockers(cutoff);
const resultId=(category,mode)=>category+':'+cutoff+(mode==='normal'?'':':'+mode);
@@ -263,11 +299,16 @@ class RuleStore{
const grouped=new Map(),batches=[];
for(const order of this.all('orders'))for(const mode of ['normal','huizhou']){
const state=delivery(order,mode);
if(!state||!['identified','preparing','archived','pending','blocked'].includes(state.status)||!order.categoryId||order.blockedByBatchId||order.missedWindow||order.status==='ignored')continue;
if(!state||!['identified','preparing','archived','pending','blocked'].includes(state.status)||state.missedWindow||!order.categoryId||order.blockedByBatchId||order.missedWindow||order.status==='ignored')continue;
if(resuming&&this.intakeWindow(order.sample||order.event)?.end!==window.end)continue;
if(mode==='huizhou'&&(order.ruleSnapshot?.huizhouEnabled!==true||(!state.orderNos?.length&&!state.issues?.length)))continue;
const at=eligibility.orderTime(this,order);
if(validDate(at)&&Date.parse(at)<Date.parse(collectionBounds(window).start)&&!eligibility.isAdmitted(this,order.sample||order.event)){this.recordIssue('missed:'+order.id+':'+mode,{component:'rules',notificationMode:mode,error:'错过整理时点,等待人工处理。',orderIds:[order.id]});updateDelivery(order,mode,{status:'ignored',error:'早于本时段的历史订单,不补发。'});this.put('orders',order);continue;}
if(!eligibility.orderInWindow(this,order,window))continue;
if(validDate(at)&&Date.parse(at)<Date.parse(collectionBounds(window).start)&&!eligibility.isAdmitted(this,order.sample||order.event)){
const expired=this.intakeWindow(order.sample||order.event,{includeExpired:true});
this.recordIssue('missed:'+order.id+':'+mode,{component:'rules',notificationMode:mode,error:'错过整理时点,等待人工处理。',orderIds:[order.id]});
updateDelivery(order,mode,{status:expired?'blocked':'ignored',error:expired?'原处理时段超过30分钟,等待负责人核验。':'早于本时段的历史订单,不补发。',...(expired?{missedWindow:expired}:{})});this.put('orders',order);continue;
}
if(!eligibility.orderInWindow(this,order,window)&&this.intakeWindow(order.sample||order.event)?.end!==window.end)continue;
const key=order.categoryId+':'+mode;if(!grouped.has(key))grouped.set(key,{mode,orders:[]});grouped.get(key).orders.push(order);
}
for(const {mode,orders} of grouped.values()){
@@ -288,6 +329,7 @@ class RuleStore{
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(resuming)batch.intakeGrace={cutoff:window.end,expiresAt:new Date(Date.parse(window.end)+1800000).toISOString()};
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);