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
@@ -39,7 +39,7 @@ test('rule editor exposes explicit test application while drafts remain editable
|
||||
runtime.orderRules.snapshot=()=>({...original(),restrictedTest:run});
|
||||
await page.goto(base+'/#order-rules');await login(page);
|
||||
await page.getByRole('button',{name:'保存草稿',exact:true}).waitFor();
|
||||
assert.match(await page.locator('#order-rules-panel').innerText(),/受限稳定性测试:15 \/ 15 类可用/);
|
||||
assert.match(await page.locator('#order-rules-panel').innerText(),/受限稳定性测试:15 类纳入测试,15 类当前生效/);
|
||||
assert.equal(await page.getByRole('button',{name:'应用到测试',exact:true}).isEnabled(),true);
|
||||
assert.equal(await page.getByRole('button',{name:'保存草稿',exact:true}).isEnabled(),true);
|
||||
await page.getByLabel('规则名称',{exact:true}).fill('仍可编辑的草稿');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();
|
||||
|
||||
@@ -11,6 +11,8 @@ function fixture(t){
|
||||
put(kind,item){if(!records.has(kind))records.set(kind,new Map());records.get(kind).set(item.id,structuredClone(item));return item;},
|
||||
transaction(work){transactionDepth++;try{return work();}finally{transactionDepth--; }},
|
||||
settings:()=>({processingEnabled,processingSince:null}),
|
||||
now:()=> '2026-10-23T02:00:00.000Z',clock:()=>new Date('2026-10-23T02:00:00Z'),
|
||||
schedule:()=>({times:['11:00','17:00'],weekends:false}),calendar:()=>[],intakeWindow:()=>null,
|
||||
snapshot(){snapshots++;return {window:{start:'2026-10-23T00:00:00Z',end:'2026-10-23T03:00:00Z',available:false}};},
|
||||
executionRule:record=>record?.draft,
|
||||
fields:()=>({samples:[],processes:[]}),discoveryBlockers:()=>[],
|
||||
@@ -32,10 +34,13 @@ test('one discovery set resolves its window once and registers every row before
|
||||
return {liveTodo:true,pdfExport:true};
|
||||
};
|
||||
await f.execution.scan({connectionId:'c1',idempotencyKey:'complete-discovery'},principal,{rows});
|
||||
assert.equal(firstProbe.snapshots,1,'the complete discovery set must use one window snapshot');
|
||||
assert.equal(firstProbe.snapshots,0,'discovery resolves its window without building a full store snapshot');
|
||||
assert.equal(new Set(firstProbe.tasks.map(task=>JSON.stringify(task.intakeWindow))).size,1,'all tasks must share the window resolved at scan start');
|
||||
assert.equal(firstProbe.tasks[0].intakeWindow.end,'2026-10-23T03:00:00.000Z');
|
||||
assert.equal(firstProbe.inTransaction,false,'external work must start after the discovery transaction');
|
||||
assert.equal(firstProbe.tasks.length,17,'all task rows must be committed before any probe or capture');
|
||||
assert.equal(firstProbe.targetCount,17);assert.equal(f.store.all('execution-tasks').length,17);
|
||||
assert.equal(f.snapshots,0,'capture absence checks and execution views must not assemble unrelated store snapshots');
|
||||
});
|
||||
for(const action of ['pause','stop'])test(`historical delivery drain yields before the second hint so an event-loop ${action} preserves pending work`,async t=>{
|
||||
const f=fixture(t);
|
||||
@@ -57,5 +62,6 @@ for(const action of ['pause','stop'])test(`historical delivery drain yields befo
|
||||
f.setProcessing(true);await f.execution.background();
|
||||
assert.equal(f.store.all('execution-discovery-runs').filter(item=>item.status==='complete').length,20);
|
||||
assert.equal(f.store.get('execution-discoveries','c1').status,'complete');
|
||||
assert.equal(f.snapshots,0,'background freshness checks must resolve only the schedule window');
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs');
|
||||
const now='2026-10-26T02:00:00.000Z';
|
||||
function deferred(){let resolve,reject;const promise=new Promise((yes,no)=>{resolve=yes;reject=no;});return {promise,resolve,reject};}
|
||||
function fixture(t){
|
||||
const records=new Map(),connection={id:'c1',owner:'admin',status:'connected'};
|
||||
const store={
|
||||
all:kind=>[...(records.get(kind)?.values()||[])].map(value=>structuredClone(value)),
|
||||
get:(kind,id)=>structuredClone(records.get(kind)?.get(id)||null),
|
||||
put(kind,value){if(!records.has(kind))records.set(kind,new Map());records.get(kind).set(value.id,structuredClone(value));},
|
||||
transaction:work=>work(),settings:()=>({processingEnabled:true}),
|
||||
clock:()=>new Date(now),schedule:()=>({times:['11:00','17:00'],weekends:false}),calendar:()=>[],
|
||||
snapshot:()=>({window:{available:false}}),
|
||||
};
|
||||
const execution=new OrderExecutionCoordinator({store,workspace:{snapshot:()=>({connections:[connection]})},archive:{},clock:()=>new Date(now),systemPrincipal:{user:{username:'admin',role:'admin'},sessionId:'isolated-test'}});
|
||||
t.after(()=>execution.stop());
|
||||
return {execution,store,notify:runId=>execution.notifyDiscovery({connectionId:connection.id,runId,rows:[],startedAt:now,finishedAt:now})};
|
||||
}
|
||||
|
||||
test('overlapping background ticks share the running discovery pass without duplicate scans',async t=>{
|
||||
const f=fixture(t),entered=deferred(),release=deferred(),calls=[];
|
||||
f.notify('first');f.notify('second');
|
||||
f.execution.scan=async(input,principal,hint)=>{
|
||||
calls.push(hint.runId);
|
||||
if(calls.length===1){entered.resolve();await release.promise;}
|
||||
f.store.put('execution-scans',{id:'c1',status:'complete',startedAt:now,finishedAt:now});
|
||||
};
|
||||
const first=f.execution.background();await entered.promise;
|
||||
const overlap=Array.from({length:4},()=>f.execution.background());
|
||||
const callsWhileBlocked=[...calls];
|
||||
// Arrivals during a pass remain durable and are processed by the next pass.
|
||||
f.notify('third');release.resolve();await Promise.all([first,...overlap]);
|
||||
assert.deepEqual(callsWhileBlocked,['first'],'a slow capture must not queue the same discovery again');
|
||||
assert.deepEqual(calls,['first','second']);
|
||||
assert.equal(f.store.all('execution-discovery-runs').find(hint=>hint.runId==='third').status,'pending');
|
||||
await f.execution.background();
|
||||
assert.deepEqual(calls,['first','second','third']);
|
||||
assert.ok(f.store.all('execution-discovery-runs').every(hint=>hint.status==='complete'));
|
||||
});
|
||||
|
||||
test('background guard releases after an unexpected failure so the next tick can recover',async t=>{
|
||||
const f=fixture(t),entered=deferred(),release=deferred();let calls=0;
|
||||
f.execution.performBackground=async()=>{calls++;entered.resolve();await release.promise;throw Error('isolated background failure');};
|
||||
const first=f.execution.background();await entered.promise;
|
||||
const second=f.execution.background();release.resolve();
|
||||
const results=await Promise.allSettled([first,second]);
|
||||
assert.equal(calls,1);assert.ok(results.every(result=>result.status==='rejected'));
|
||||
f.execution.performBackground=async()=>{calls++;};
|
||||
await f.execution.background();assert.equal(calls,2);
|
||||
});
|
||||
|
||||
test('stop waits for the background pass to persist its final discovery receipt',async t=>{
|
||||
const f=fixture(t),entered=deferred(),release=deferred();
|
||||
f.notify('shutdown');
|
||||
f.execution.scan=async()=>{entered.resolve();await release.promise;};
|
||||
const running=f.execution.background();await entered.promise;
|
||||
let stopped=false;
|
||||
const stopping=f.execution.stop().then(()=>{stopped=true;});
|
||||
// Allow a drain-only stop to resolve while its background continuation is pending.
|
||||
await new Promise(resolve=>setImmediate(resolve));
|
||||
const premature=stopped;
|
||||
release.resolve();await Promise.all([running,stopping]);
|
||||
assert.equal(premature,false,'shutdown must not close the store before final background writes');
|
||||
assert.equal(f.store.all('execution-discovery-runs')[0].status,'complete');
|
||||
assert.equal(f.store.get('execution-discoveries','c1').status,'complete');
|
||||
});
|
||||
@@ -9,6 +9,12 @@ function fixture(){
|
||||
return {orderRules:store,workspace:{recordSources:()=>[{id:'a',owner:'alice'},{id:'b',owner:'bob'}]},execution:{archive:{read:async()=>Buffer.from('%PDF-x')}}};
|
||||
}
|
||||
const user={username:'alice',role:'operator'};
|
||||
|
||||
test('summary computes dynamic collecting batches once per request and never retains a previous result',t=>{
|
||||
const c=fixture(),collecting=require('../../src/modules/order-rules/collecting-batches.cjs');let reads=0;
|
||||
t.mock.method(collecting,'list',()=>{reads++;return [];});
|
||||
summary(c,user);assert.equal(reads,1);summary(c,user);assert.equal(reads,2);
|
||||
});
|
||||
test('failed task detail exposes bounded read-only evidence only for the same authorized capture',()=>{
|
||||
const c=fixture(),task={id:'capture-failed',connectionId:'a',categoryIds:['cat'],status:'failed',step:'capture',errorCode:'FORM_STRUCTURE_UNSUPPORTED',retryPolicy:'manual',nextRetryAt:null,diagnostics:[{code:'ROW_MAPPING',table:'OrderItems',reason:'明细行关系不明确',rowCount:2,cookie:'SECRET'}],captureEvidenceId:'evidence',row:{taskId:'T1',instanceId:'I1'}};
|
||||
c.orderRules.all('execution-tasks').push(task);
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {orderDrivenUI}=require('../fixtures/order-driven-ui.cjs');
|
||||
test('healthy todo without matched orders shows pending verification without loosening capability gates',{timeout:60000},async t=>{
|
||||
const {page,runtime}=await orderDrivenUI(t,'#notification-settings'),s=runtime.orderRules;
|
||||
s.put('settings',{...s.get('settings','main'),enabled:true,processingEnabled:true});s.capabilities={liveTodo:true,pdfExport:false,automaticArchive:false};
|
||||
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByRole('link',{name:'自动通知待验证',exact:true}).waitFor();
|
||||
assert.equal(s.providersReady(),false);assert.equal(s.settings().enabled,true);
|
||||
s.put('execution-scans',{id:'failed-source',status:'failed',error:'fixture failure'});
|
||||
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByRole('link',{name:'自动通知受阻',exact:true}).waitFor();
|
||||
assert.equal(s.providersReady(),false);
|
||||
});
|
||||
@@ -13,3 +13,33 @@ test('retained live uncertain tasks and active incomplete sources still block di
|
||||
const s=fixture(false);assert.match(RuleStore.prototype.discoveryBlockers.call(s,cutoff).join(' '),/disabled-old/);
|
||||
const active=fixture();active.get=()=>null;assert.match(RuleStore.prototype.discoveryBlockers.call(active,cutoff).join(' '),/active/);
|
||||
});
|
||||
|
||||
function pendingFixture({connectionId='disabled-old',removed=true,retained=false}={}){
|
||||
const s=fixture(removed),hints=[{id:'hint',connectionId,status:'pending',rows:[]}];
|
||||
if(!retained)s.tasks.length=0;
|
||||
s.all=kind=>kind==='execution-tasks'?s.tasks:kind==='execution-discoveries'||kind==='execution-discovery-runs'?hints:[];
|
||||
s.deliveryBlockers=allowed=>[connectionId].filter(allowed);
|
||||
return {s,hints};
|
||||
}
|
||||
for(const retained of [false,true])test(`inactive pending discovery and producer delivery with ${retained?'removed unknown task':'no retained task'} do not block other sources`,()=>{
|
||||
const {s,hints}=pendingFixture({retained}),before=structuredClone(hints);
|
||||
assert.deepEqual(RuleStore.prototype.discoveryBlockers.call(s,cutoff),[]);
|
||||
assert.deepEqual(hints,before,'pending evidence must remain available for source reactivation');
|
||||
});
|
||||
test('active pending evidence and deliveries continue blocking despite a completed scan',()=>{
|
||||
const {s}=pendingFixture({connectionId:'active'}),blockers=RuleStore.prototype.discoveryBlockers.call(s,cutoff);
|
||||
assert.ok(blockers.some(message=>message.includes('本地执行线索')));
|
||||
assert.ok(blockers.some(message=>message.includes('完整对账线索')));
|
||||
});
|
||||
test('inactive source with retained uncertain task still requires pending evidence and successful scan',()=>{
|
||||
const {s}=pendingFixture({removed:false,retained:true}),blockers=RuleStore.prototype.discoveryBlockers.call(s,cutoff);
|
||||
assert.ok(blockers.some(message=>message.includes('本地执行线索')));
|
||||
assert.ok(blockers.some(message=>message.includes('完整对账线索')));
|
||||
assert.ok(blockers.some(message=>message.includes('尚无完整成功扫描')));
|
||||
assert.deepEqual(RuleStore.prototype.discoveryBlockers.call(s,cutoff,id=>id==='active'),[]);
|
||||
});
|
||||
test('standalone store without execution source registration retains producer delivery blockers',()=>{
|
||||
const {s}=pendingFixture();delete s.executionSources;
|
||||
assert.match(RuleStore.prototype.discoveryBlockers.call(s,cutoff).join(' '),/本地执行线索/);
|
||||
assert.deepEqual(RuleStore.prototype.discoveryBlockers.call(s,cutoff,()=>false),[]);
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),crypto=require('node:crypto');
|
||||
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
|
||||
const {seedRules}=require('../../src/modules/order-rules/catalog.cjs');
|
||||
const access=require('../../src/modules/order-rules/access.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');
|
||||
function fixture(){
|
||||
const store=Object.create(RuleStore.prototype),counts={},records={rules:seedRules().slice(0,2).map(draft=>({id:draft.id,draft:{...draft,adapterIds:['a','b']},published:null}))};
|
||||
let now='2026-10-26T01:00:00Z';
|
||||
records['field-adapters']=['a','b'].map((id,i)=>({id,processName:records.rules[0].draft.processNames[0],processVersion:String(i),version:1,verified:true,status:'active'}));
|
||||
records.settings=[{id:'main',enabled:true,processingEnabled:true}];
|
||||
records['stability-test']=[{id:'main',enabled:true,startedAt:'2026-10-25T01:00:00Z',endsAt:'2026-10-26T02:00:00Z'}];
|
||||
store.all=kind=>{counts['all:'+kind]=(counts['all:'+kind]||0)+1;return structuredClone(records[kind]||[]);};
|
||||
store.get=(kind,id)=>{counts['get:'+kind]=(counts['get:'+kind]||0)+1;return structuredClone(records[kind]?.find(r=>r.id===id)||null);};
|
||||
store.clock=()=>new Date(now);store.schedule=()=>({times:['11:00','17:00'],weekends:false});store.calendar=()=>[];store.capabilities={};
|
||||
const adapters=store.adapters(),rules=records.rules.map(r=>({...r.draft,status:'enabled'}));
|
||||
records['restricted-test']=[{id:'main',value:{id:'run',version:1,enabled:true,rules,adapterHashes:Object.fromEntries(rules.map(r=>[r.id,hash(r.adapterIds.map(id=>adapters.find(a=>a.id===id)))]))}}];
|
||||
const reset=()=>{for(const key of Object.keys(counts))delete counts[key];};reset();
|
||||
return {store,records,counts,reset,setTime:time=>{now=time;}};
|
||||
}
|
||||
test('one snapshot reads adapters and restricted run once while preserving standalone results',()=>{
|
||||
const f=fixture(),summary=f.store.restrictedTest(),active=f.records.rules.map(r=>f.store.executionRule(r));f.reset();
|
||||
const result=f.store.snapshot({includeRecords:false});
|
||||
assert.deepEqual(result.restrictedTest,summary);
|
||||
assert.deepEqual(result.rules.map(r=>[r.testStatus,r.testVersion]),active.map(r=>[r?'enabled':'paused',r?.version||null]));
|
||||
assert.equal(f.counts['all:field-adapters'],1);
|
||||
assert.equal(f.counts['get:restricted-test'],1);
|
||||
assert.equal(f.counts['all:orders']||0,0);
|
||||
});
|
||||
test('standalone execution checks read adapters once per rule and observe next-read changes',()=>{
|
||||
const f=fixture(),record=f.records.rules[0];assert.ok(f.store.executionRule(record));
|
||||
assert.equal(f.counts['all:field-adapters'],1);
|
||||
f.records['field-adapters'][0].version++;
|
||||
assert.equal(f.store.executionRule(record),null);
|
||||
assert.equal(f.store.snapshot({includeRecords:false}).restrictedTest.readyCount,0);
|
||||
});
|
||||
test('snapshot context expires after each call and observes the exact stability boundary',()=>{
|
||||
const f=fixture();assert.equal(f.store.snapshot({includeRecords:false}).restrictedTest.readyCount,2);
|
||||
f.setTime('2026-10-26T02:00:00Z');
|
||||
const expired=f.store.snapshot({includeRecords:false});
|
||||
assert.equal(expired.restrictedTest.enabled,false);assert.equal(expired.restrictedTest.readyCount,0);
|
||||
assert.ok(expired.rules.every(r=>r.testStatus==='paused'));assert.equal(expired.settings.processingEnabled,false);
|
||||
f.setTime('2026-10-26T01:00:00Z');f.records['restricted-test'][0].value.enabled=false;
|
||||
assert.equal(f.store.snapshot({includeRecords:false}).restrictedTest.readyCount,0);
|
||||
});
|
||||
test('snapshot reuse does not change admin/operator ownership filtering or expose private rows',()=>{
|
||||
const f=fixture();f.records.orders=[{id:'own',sample:{connectionId:'a'}},{id:'private',sample:{connectionId:'b'}}];
|
||||
f.records.batches=[{id:'own-batch',orderIds:['own']},{id:'private-batch',orderIds:['private']}];
|
||||
const sources=[{id:'a',owner:'alice'},{id:'b',owner:'bob'}],workspace={recordSources:()=>sources};
|
||||
const admin=access.publicSnapshot(f.store,workspace,{role:'admin',username:'admin'}),operator=access.publicSnapshot(f.store,workspace,{role:'operator',username:'alice'});
|
||||
assert.deepEqual(admin.orders.map(r=>r.id),['private','own']);assert.deepEqual(operator.orders.map(r=>r.id),['own']);
|
||||
assert.deepEqual(operator.batches.map(r=>r.id),['own-batch']);assert.deepEqual(operator.rules,admin.rules);
|
||||
sources[0].owner='bob';assert.equal(access.publicSnapshot(f.store,workspace,{role:'operator',username:'alice'}).orders.length,0);
|
||||
});
|
||||
Reference in new issue
Block a user