fix: close discovery dispatch and persistent UI state races
This commit is contained in:
1 parent
0a366f43d6
commit
9d8d6971c1
19 files changed
+237
-77
No files matched your search
@@ -102,7 +102,7 @@ function dispatchFixture(t,{ready=true,capabilities=true,enabled=true,verify,sen
|
||||
const record={prepared:0,begun:0,smtp:0,locked:0,status:'prepared',messages:[],sent:[]};
|
||||
const config={version:1,enabled,channelId:'channel1'};
|
||||
const caps={liveTodo:capabilities,pdfExport:capabilities,automaticArchive:capabilities};
|
||||
const store={settings:()=>({...config}),snapshot:()=>({capabilities:{...caps},batches:[structuredClone({...batch,status:record.status})]}),prepare:(date,actor,window)=>{record.prepared++;assert.equal(date,dispatchCutoff);assert.equal(actor,'系统调度');assert.equal(window.start,'2026-10-19T16:00:00.000Z');assert.equal(window.end,dispatchCutoff);assert.equal(window.startInclusive,true);assert.equal(window.endInclusive,false);return [batch];},beginSending:id=>{assert.equal(id,'batch1');record.begun++;record.status='sending';},finishSending:(id,status,message)=>{assert.equal(id,'batch1');record.status=status;record.messages.push(message);}};
|
||||
const store={discoveryBlockers:()=>[],batchIncomplete:()=>false,settings:()=>({...config}),snapshot:()=>({capabilities:{...caps},batches:[structuredClone({...batch,status:record.status})]}),prepare:(date,actor,window)=>{record.prepared++;assert.equal(date,dispatchCutoff);assert.equal(actor,'系统调度');assert.equal(window.start,'2026-10-19T16:00:00.000Z');assert.equal(window.end,dispatchCutoff);assert.equal(window.startInclusive,true);assert.equal(window.endInclusive,false);return [batch];},beginSending:id=>{assert.equal(id,'batch1');record.begun++;record.status='sending';},finishSending:(id,status,message)=>{assert.equal(id,'batch1');record.status=status;record.messages.push(message);}};
|
||||
const mail={exclusive:async(id,fn)=>{assert.equal(id,'channel1');record.locked++;return fn();},store:{channelSecret:id=>({id,version:2,email:'sender@example.com',name:'通知',smtp:{host:'unused.invalid'}}),guard:(id,version)=>{assert.equal(id,'channel1');assert.equal(version,2);}},smtpFactory:()=>{record.smtp++;return {verify:async()=>{if(verify)await verify({batch,config,caps,file});},sendMail:async message=>{record.sent.push(message);if(send)return send(message);return result||{accepted:['user@example.com','copy@example.com'],rejected:[]};},close:()=>{}};}};
|
||||
const schedule={times:['09:00','17:00'],timezone:'Asia/Shanghai',weekends:false,mode:'product_line',missed:'next_window'};
|
||||
let now=new Date('2026-10-20T00:59:00.000Z');
|
||||
|
||||
@@ -5,7 +5,7 @@ const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coo
|
||||
const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');
|
||||
const admin={username:'admin',role:'admin'},principal={user:admin,sessionId:'test-session'};
|
||||
function fixture(t){
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'execution-'));const now=()=>new Date('2026-10-19T02:00:00Z');
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'execution-'));const now=()=>new Date('2026-10-19T03:00:00Z');
|
||||
const store=new RuleStore(dir,{clock:now});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const connection={id:'c1',owner:'admin',status:'connected'},workspace={getConnection:()=>connection,snapshot:()=>({connections:[connection]})};
|
||||
let captures=0,exports=0,failCapture=false;
|
||||
@@ -165,3 +165,46 @@ for(const partial of [false,true])test(`real loopback SMTP ${partial?'partial re
|
||||
await dispatcher.tick();now=new Date('2026-10-19T03:00:00Z');await dispatcher.tick();await dispatcher.stop();assert.equal(f.store.all('batches')[0].status,partial?'unknown':'failed');assert.equal(messages,partial?1:0);
|
||||
assert.equal(f.store.prepare('2026-10-19T03:00:00Z','system').length,0);
|
||||
});
|
||||
|
||||
function deferred(){let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};}
|
||||
test('discovery barrier covers queued scan, complete persisted set, late failure and rebuild of prepared category',async t=>{
|
||||
const f=fixture(t);f.execution.clock=f.store.clock=()=>new Date('2026-10-19T03:00:00Z');await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'ready'},principal);
|
||||
const cutoff='2026-10-19T03:00:00Z',batch=f.store.prepare(cutoff,'admin')[0];assert.ok(batch);
|
||||
const discovery=deferred(),capture=deferred(),entered=deferred(),original={...f.row};let fail=true;
|
||||
f.provider.scan=()=>discovery.promise;
|
||||
f.provider.capture=async(c,p,row)=>{entered.resolve();await capture.promise;if(fail)throw Error('late capture failed');return {sample:{...row,connectionId:c.id,brief:'摘要',fields:{order:row.taskId,brief:'真实摘要'}},snapshot:{processVersion:'1.4',html:'<p>fixture</p>',fields:[{path:'order',label:'订单号',value:row.taskId},{path:'brief',label:'摘要',value:'真实摘要'}]}};};
|
||||
const scanning=f.execution.scan({connectionId:'c1',idempotencyKey:'gated'},principal);
|
||||
assert.throws(()=>f.store.beginSending(batch.id),/扫描|完整/,'even a just queued discovery blocks existing batch');
|
||||
assert.equal(f.store.prepare(cutoff,'admin').length,0);
|
||||
discovery.resolve([original,{...original,taskId:'late1',instanceId:'late1'},{...original,taskId:'late2',instanceId:'late2'}]);await entered.promise;
|
||||
assert.equal(f.store.all('execution-tasks').length,3,'all relevant identities persisted before first awaited capture');
|
||||
assert.equal(f.store.prepare(cutoff,'admin').length,0);capture.resolve();await scanning;
|
||||
assert.throws(()=>f.store.beginSending(batch.id),/扫描|完整/);assert.equal(f.store.prepare(cutoff,'admin').length,0);
|
||||
fail=false;await f.execution.scan({connectionId:'c1',idempotencyKey:'recovered'},principal);
|
||||
assert.throws(()=>f.store.beginSending(batch.id),/完整/,'new same-category orders cannot be omitted by old frozen batch');
|
||||
const replacement=f.store.prepare(cutoff,'admin')[0];assert.ok(replacement);assert.equal(replacement.orderIds.length,3);assert.equal(f.store.get('batches',batch.id).status,'cancelled');assert.equal(f.store.beginSending(replacement.id).status,'sending');
|
||||
});
|
||||
test('cutoff requires a successful post-cutoff discovery for every source and failed zero-row scans stay blocked',async t=>{
|
||||
const f=fixture(t);f.execution.clock=f.store.clock=()=>new Date('2026-10-19T02:00:00Z');await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'ready'},principal);
|
||||
const cutoff='2026-10-19T03:00:00Z';assert.equal(f.store.prepare(cutoff,'admin').length,0,'pre-cutoff snapshot cannot certify all arrivals');
|
||||
f.execution.clock=f.store.clock=()=>new Date(cutoff);const original=f.provider.scan;f.provider.scan=async()=>{throw Error('list unavailable');};
|
||||
await assert.rejects(f.execution.scan({connectionId:'c1',idempotencyKey:'failed-list'},principal),/list unavailable/);assert.equal(f.store.prepare(cutoff,'admin').length,0);assert.equal(f.execution.snapshot().query.status,'failed');
|
||||
f.provider.scan=original;await f.execution.scan({connectionId:'c1',idempotencyKey:'recovered-list'},principal);assert.equal(f.store.prepare(cutoff,'admin').length,1);
|
||||
});
|
||||
|
||||
test('dispatcher rechecks discovery after SMTP verification and keeps an unsent reservation recoverable',async t=>{
|
||||
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'ready'},principal);f.store.saveSettings({...f.store.settings(),enabled:true,channelId:'channel1'},'admin');const batch=f.store.prepare('2026-10-19T03:00:00Z','admin')[0];
|
||||
const verified=deferred(),verifyGate=deferred(),discovery=deferred();let sends=0;const mail={clients:new Set(),store:{channelSecret:id=>({id,version:1,email:'sender@example.test',smtp:{}}),guard(){}},smtpFactory:()=>({verify:async()=>{verified.resolve();await verifyGate.promise;},sendMail:async()=>{sends++;return {accepted:['orders@example.test']};},close(){}})};
|
||||
const dispatcher=new OrderRuleDispatcher({store:f.store,mail,clock:f.execution.clock,providersReady:()=>true});const dispatch=dispatcher.dispatch(batch,f.store.settings());await verified.promise;
|
||||
f.provider.scan=()=>discovery.promise;const scan=f.execution.scan({connectionId:'c1',idempotencyKey:'during-verify'},principal);f.store.capabilities.pdfExport=false;verifyGate.resolve();assert.equal(await dispatch,false);assert.equal(sends,0);assert.equal(f.store.get('batches',batch.id).status,'prepared');
|
||||
discovery.resolve([f.row]);await scan;await dispatcher.dispatch(batch,f.store.settings());assert.equal(sends,1);assert.equal(f.store.get('batches',batch.id).status,'sent');await dispatcher.stop();
|
||||
});
|
||||
test('all configured sources require independent complete cutoff discovery and task retry capability matches owner authorization',async t=>{
|
||||
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'ready'},principal);
|
||||
const connections=[{id:'c1',owner:'admin',status:'connected'},{id:'c2',owner:'operator',status:'connected'}];f.execution.workspace={getConnection:id=>connections.find(c=>c.id===id),snapshot:()=>({connections})};const cutoff='2026-10-19T03:00:00Z';assert.equal(f.store.prepare(cutoff,'admin').length,0);
|
||||
f.provider.scan=async()=>[];await f.execution.scan({connectionId:'c2',idempotencyKey:'second-source'},principal);assert.equal(f.store.prepare(cutoff,'admin').length,1);
|
||||
const task=f.store.all('execution-tasks')[0];task.status='failed';task.step='archive';f.store.put('execution-tasks',task);const owner={user:{username:'admin',role:'operator'},sessionId:'owner'};
|
||||
assert.equal(f.execution.snapshot(owner).tasks[0].canRetry,true);assert.equal(f.execution.snapshot({user:{username:'admin',role:'viewer'},sessionId:'reader'}).tasks[0].canRetry,false);
|
||||
await assert.rejects(f.execution.retry(task.id,{version:task.version,note:'已经确认恢复条件',idempotencyKey:'denied'}, {user:{username:'operator',role:'operator'},sessionId:'other'}),{status:403});
|
||||
task.conflict=true;f.store.put('execution-tasks',task);assert.equal(f.execution.snapshot(owner).tasks[0].canRetry,false);task.conflict=false;task.status='unknown';f.store.put('execution-tasks',task);assert.equal(f.execution.snapshot(owner).tasks[0].canRetry,false);
|
||||
});
|
||||
@@ -87,11 +87,12 @@ test('pausing a rule prevents a prepared batch from entering SMTP sending',t=>{
|
||||
store.pause(rule.id,{version:rule.version},'admin');assert.throws(()=>store.beginSending(batch.id),e=>e.status===409);
|
||||
assert.equal(store.snapshot().batches[0].status,'prepared');
|
||||
});
|
||||
test('late discovered pre-cutoff orders cannot create a second email for an already frozen category and slot',t=>{
|
||||
test('late discovery rebuilds an unsent reservation as one complete batch and never carries it into a later slot',t=>{
|
||||
const {store}=fixture(t,{capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),sample=configure(store);
|
||||
const archive=(sample)=>{const order=store.ingest(sample,'system');store.recordArchive(order.id,{files:[{name:order.id+'.pdf',path:'C:\\archive\\'+order.id+'.pdf',sha256:'a'.repeat(64),size:42,kind:'pdf'}],archivedAt:'2026-10-19T01:05:00Z'},'archive-executor');return order;};
|
||||
archive(sample);assert.equal(store.prepare('2026-10-19T03:00:00Z','admin').length,1);
|
||||
archive({...sample,instanceId:'late',taskId:'late'});
|
||||
const replacement=store.prepare('2026-10-19T03:00:00Z','admin');assert.equal(replacement.length,1);assert.equal(replacement[0].orderIds.length,2);assert.equal(store.snapshot().batches.filter(b=>b.status==='prepared').length,1);
|
||||
assert.equal(store.prepare('2026-10-19T03:00:00Z','admin').length,0);
|
||||
assert.equal(store.prepare('2026-10-19T09:00:00Z','admin').length,0);
|
||||
assert.equal(store.snapshot().orders.filter(o=>o.status==='ignored').length,2);
|
||||
|
||||
Reference in new issue
Block a user