perf: streamline rule reads and unblock background discovery
This commit is contained in:
1 parent
b14fa2f4d1
commit
b17b975812
19 files changed
+263
-42
No files matched your search
@@ -86,7 +86,7 @@ class OrderExecutionCoordinator{
|
||||
}
|
||||
markUnavailableCaptures(rows,connection,{notAfter}={}){
|
||||
const absent=[];
|
||||
const currentWindow=this.store.snapshot().window;
|
||||
const currentWindow=upcomingWindow(this.store.clock(),this.store.schedule(),this.store.calendar());
|
||||
this.store.transaction(()=>{
|
||||
for(const task of this.store.all('execution-tasks')){
|
||||
const dueDeferred=task.step==='waiting_window'&&task.status==='identified'&&Number.isFinite(Date.parse(task.deferredUntil))&&+this.clock()>=Date.parse(task.deferredUntil);
|
||||
@@ -160,7 +160,8 @@ class OrderExecutionCoordinator{
|
||||
canRetry:this.canRetry(task,principal),status:activeStatus?task.status:order?.status||task.status,
|
||||
error:task.error||order?.error||null};
|
||||
}).reverse();
|
||||
const blockers=[...(!principal||principal.user?.role==='admin'?this.blockers:[]),...this.store.discoveryBlockers(this.store.snapshot().window?.end,allowed)];
|
||||
const window=upcomingWindow(this.store.clock(),this.store.schedule(),this.store.calendar());
|
||||
const blockers=[...(!principal||principal.user?.role==='admin'?this.blockers:[]),...this.store.discoveryBlockers(window?.end,allowed)];
|
||||
const candidates=this.store.all('execution-candidates').filter(item=>item.status==='candidate'&&allowed(item.connectionId));
|
||||
return {tasks,candidates,capabilities:clone(this.store.capabilities),fields,query,blockers};
|
||||
}
|
||||
@@ -517,7 +518,16 @@ class OrderExecutionCoordinator{
|
||||
this.store.put('execution-discoveries',{...latest,status:'complete',consumedAt:this.now()});
|
||||
}
|
||||
}
|
||||
async background(){
|
||||
background(){
|
||||
if(this.backgroundRunning)return this.backgroundRunning;
|
||||
// Slow captures can outlive the timer interval. Share the complete pass,
|
||||
// rather than queuing the same durable discoveries behind each scan.
|
||||
const operation=Promise.resolve().then(()=>this.performBackground());
|
||||
this.backgroundRunning=operation;
|
||||
operation.finally(()=>{if(this.backgroundRunning===operation)this.backgroundRunning=null;}).catch(()=>{});
|
||||
return operation;
|
||||
}
|
||||
async performBackground(){
|
||||
if(this.stopped||!this.systemPrincipal||!this.store.settings().processingEnabled)return;
|
||||
const day=new Date(this.clock().getTime()+8*3600000).toISOString().slice(0,10);
|
||||
if(!dayPolicy(day,this.settings()?.schedule||{},this.calendar()).scan)return;
|
||||
@@ -536,7 +546,7 @@ class OrderExecutionCoordinator{
|
||||
if(this.stopped||!this.store.settings().processingEnabled)return;
|
||||
}
|
||||
const last=this.store.get('execution-scans',connection.id);
|
||||
const window=this.store.snapshot().window;
|
||||
const window=upcomingWindow(this.store.clock(),this.store.schedule(),this.store.calendar());
|
||||
const cutoffDue=window?.available&&(last?.status!=='complete'||!last?.startedAt||Date.parse(last.startedAt)<Date.parse(window.end));
|
||||
const fresh=last?.status==='complete'&&+this.clock()-Date.parse(last.finishedAt)<300000;
|
||||
if(!cutoffDue&&fresh)continue;
|
||||
@@ -550,6 +560,6 @@ class OrderExecutionCoordinator{
|
||||
}
|
||||
}
|
||||
async drain(){await this.tail.catch(()=>{});}
|
||||
async stop(){this.stopped=true;clearInterval(this.timer);this.timer=null;await this.drain();}
|
||||
async stop(){this.stopped=true;clearInterval(this.timer);this.timer=null;if(this.backgroundRunning)await this.backgroundRunning.catch(()=>{});await this.drain();}
|
||||
}
|
||||
module.exports={OrderExecutionCoordinator};
|
||||
@@ -0,0 +1,23 @@
|
||||
'use strict';
|
||||
const {windowForCutoff}=require('./window.cjs');
|
||||
const eligibility=require('./restricted-test.cjs');
|
||||
function discoveryBlockers(store,cutoff,allowed=()=>true){
|
||||
if(!store.executionSources)return (store.deliveryBlockers?.(allowed)||[]).map(id=>'连接 '+id+' 本地执行线索尚未交付。');
|
||||
const window=cutoff?windowForCutoff(cutoff,store.schedule(),store.calendar()):null;
|
||||
const relevant=store.all('execution-tasks').filter(task=>!task.removedAt&&!['sent','ignored'].includes(task.status)&&(!window||eligibility.eventInWindow(store,task.row,window)));
|
||||
const sources=new Set([...store.executionSources(),...relevant.map(task=>task.connectionId)].filter(allowed));
|
||||
// Inactive sources cannot consume hints. Retain their evidence without
|
||||
// blocking unrelated work, unless a retained task still needs that source.
|
||||
const included=id=>sources.has(id);
|
||||
const blockers=(store.deliveryBlockers?.(included)||[]).filter(included).map(id=>'连接 '+id+' 本地执行线索尚未交付。');
|
||||
const pendingSources=new Set([...store.all('execution-discoveries'),...store.all('execution-discovery-runs')].filter(hint=>hint.status==='pending'&&included(hint.connectionId)).map(hint=>hint.connectionId));
|
||||
for(const id of pendingSources)blockers.push('连接 '+id+' 完整对账线索尚未处理。');
|
||||
if(store.activeDiscoveries>0)blockers.push('待办扫描尚未完成,不能冻结或发送不完整类别。');
|
||||
for(const id of sources){
|
||||
const scan=store.get('execution-scans',id);
|
||||
if(scan?.status!=='complete')blockers.push('连接 '+id+' 尚无完整成功扫描'+(scan?.error?':'+scan.error:'。'));
|
||||
else if(cutoff&&Date.parse(scan.startedAt)<Date.parse(cutoff))blockers.push('连接 '+id+' 需要截止时点之后启动的完整扫描。');
|
||||
}
|
||||
return blockers;
|
||||
}
|
||||
module.exports={discoveryBlockers};
|
||||
@@ -58,11 +58,11 @@ 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?.removedAt&&!task?.removedAt&&!!(order?.categoryId||order?.ruleSnapshot?.categoryId||order?.ruleSnapshot?.id||task?.categoryIds?.length);
|
||||
function visibleOrders(context,user){
|
||||
function visibleOrders(context,user,collectingGroups){
|
||||
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)));
|
||||
for(const task of data.tasks)if(!task.orderId&&!task.supersededBy&&classified(null,task)&&canReadConnection(context.workspace,user,task.connectionId))rows.push(orderRow(null,task));
|
||||
const collecting=require('./collecting-batches.cjs').list(context.orderRules).filter(b=>canReadBatch(context.workspace,user,b,context.orderRules));
|
||||
const collecting=(collectingGroups||require('./collecting-batches.cjs').list(context.orderRules)).filter(b=>canReadBatch(context.workspace,user,b,context.orderRules));
|
||||
for(const row of rows)row.collectingBatches=collecting.filter(b=>b.orderIds.includes(row.id)).map(b=>({id:b.id,subject:b.subject,cutoff:b.cutoff}));
|
||||
return rows;
|
||||
}
|
||||
@@ -128,7 +128,7 @@ async function readOrderFile(context,id,index,user){
|
||||
function summary(context,user){
|
||||
const result=context.orderRules.snapshot({includeRecords:false});
|
||||
delete result.orders;delete result.batches;delete result.audit;delete result.fields;
|
||||
const rows=visibleOrders(context,user),data=records(context.orderRules),batches=[...data.batches,...require('./collecting-batches.cjs').list(context.orderRules)].filter(b=>canReadBatch(context.workspace,user,b,context.orderRules));
|
||||
const collecting=require('./collecting-batches.cjs').list(context.orderRules),rows=visibleOrders(context,user,collecting),data=records(context.orderRules),batches=[...data.batches,...collecting].filter(b=>canReadBatch(context.workspace,user,b,context.orderRules));
|
||||
const count=(items,status)=>items.filter(i=>status.includes(i.status)).length;
|
||||
result.scans=context.orderRules.all('execution-scans').filter(s=>canReadConnection(context.workspace,user,s.connectionId||s.id)).map(s=>pick(s,['id','connectionId','status','startedAt','finishedAt','rowCount','targetCount','error']));
|
||||
result.counts={orders:rows.length,blocked:rows.filter(row=>['blocked','failed'].includes(row.status)||row.notifications?.huizhou?.status==='blocked').length,unknown:count(batches,['unknown']),activeBatches:count(batches,['collecting','prepared','sending','unknown','failed'])};
|
||||
|
||||
@@ -23,19 +23,24 @@ function evidence(store,adapter){
|
||||
const result=require('./field-mappings.cjs').evaluateMapping(store,{...adapter,version:adapter.version},captured,{relatedRules:[]});
|
||||
return result.valid;
|
||||
}
|
||||
function uncoveredFlows(store,run){
|
||||
const adapters=store.adapters();
|
||||
function uncoveredFlows(store,run,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;const period=require('./stability-period.cjs').period(store);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),...(period?{period}:{})};}
|
||||
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;
|
||||
// A synchronous snapshot may share these reads; never retain this across calls.
|
||||
function readContext(store,adapters){
|
||||
const saved=typeof store?.get==='function'?store.get('restricted-test','main')?.value||null:null;
|
||||
const period=saved?require('./stability-period.cjs').period(store):null;
|
||||
return {run:saved&&period?.expired?{...saved,enabled:false}:saved,period,adapters:adapters??(saved?store.adapters():[])};
|
||||
}
|
||||
function summary(store,context=readContext(store)){const {run,period,adapters}=context;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,adapters)).length,uncovered:uncoveredFlows(store,run,adapters),...(period?{period}:{})};}
|
||||
function validRule(store,rule,run,adapters){if(!run.enabled)return false;adapters??=store.adapters();return hash(rule.adapterIds.map(id=>adapters.find(a=>a.id===id)))===run.adapterHashes[rule.id];}
|
||||
function executionRule(store,record,context){
|
||||
const run=context?context.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,context?.adapters)?structuredClone(rule):null;
|
||||
}
|
||||
function applyDrafts(store,input,actor){
|
||||
if(actor?.role!=='admin'||!actor.username)fail('仅管理员可应用测试规则。',403);
|
||||
@@ -190,4 +195,4 @@ function admitCurrent(store,rows,actor){
|
||||
return structuredClone(entries);
|
||||
});
|
||||
}
|
||||
module.exports={state,summary,save,applyDrafts,executionRule,assertPath,assertRule,assertEvent,assertOrder,assertBatch,recordCurrentScan,admitCurrent,eventTime,orderTime,isAdmitted,eventInWindow,orderInWindow};
|
||||
module.exports={state,readContext,summary,save,applyDrafts,executionRule,assertPath,assertRule,assertEvent,assertOrder,assertBatch,recordCurrentScan,admitCurrent,eventTime,orderTime,isAdmitted,eventInWindow,orderInWindow};
|
||||
@@ -47,10 +47,10 @@ 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);}
|
||||
restrictedTest(context){return require('./restricted-test.cjs').summary(this,context);}
|
||||
saveRestrictedTest(input,actor){return require('./restricted-test.cjs').save(this,input,actor);}
|
||||
applyRestrictedDrafts(input,actor){return require('./restricted-test.cjs').applyDrafts(this,input,actor);}
|
||||
executionRule(record){return require('./restricted-test.cjs').executionRule(this,record);}
|
||||
executionRule(record,context){return require('./restricted-test.cjs').executionRule(this,record,context);}
|
||||
providersReady(){return ['liveTodo','pdfExport','automaticArchive'].every(key=>this.capabilities[key]===true);}
|
||||
adapters(){return registry.registry(this);}
|
||||
fields(){return registry.fields(this);}
|
||||
@@ -85,7 +85,7 @@ 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)}));
|
||||
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';rule.testVersion=active?.version||null;rule.testHasDraft=!active||active.version!==rule.version;}
|
||||
const readContext=eligibility.readContext(this,adapters),restrictedTest=typeof this.restrictedTest==='function'?this.restrictedTest(readContext):null;for(const rule of rules)if(restrictedTest){const active=typeof this.executionRule==='function'?this.executionRule({id:rule.id},readContext):null;rule.testStatus=active?'enabled':'paused';rule.testVersion=active?.version||null;rule.testHasDraft=!active||active.version!==rule.version;}
|
||||
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(()=>{
|
||||
@@ -240,21 +240,7 @@ class RuleStore{
|
||||
this.put('orders',order);require('./migrations.cjs').synchronizeTasks(this,order);this.audit(actor,'应用当前规则重新识别',id+':'+input.note.trim());return order;
|
||||
});}
|
||||
discoveryBlockers(cutoff,allowed=()=>true){
|
||||
const blockers=(this.deliveryBlockers?.(allowed)||[]).map(id=>'连接 '+id+' 本地执行线索尚未交付。');
|
||||
if(!this.executionSources)return blockers;
|
||||
const pendingSources=new Set([...this.all('execution-discoveries'),...this.all('execution-discovery-runs')].filter(hint=>hint.status==='pending'&&allowed(hint.connectionId)).map(hint=>hint.connectionId));
|
||||
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=>!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;
|
||||
const scan=this.get('execution-scans',id);
|
||||
if(scan?.status!=='complete')blockers.push('连接 '+id+' 尚无完整成功扫描'+(scan?.error?':'+scan.error:'。'));
|
||||
else if(cutoff&&Date.parse(scan.startedAt)<Date.parse(cutoff))blockers.push('连接 '+id+' 需要截止时点之后启动的完整扫描。');
|
||||
}
|
||||
return blockers;
|
||||
return require('./discovery-barrier.cjs').discoveryBlockers(this,cutoff,allowed);
|
||||
}
|
||||
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)||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'));
|
||||
|
||||
Reference in new issue
Block a user