fix: make order processing authorized and recoverable
This commit is contained in:
1 parent
0ab7d62aa6
commit
7e42a6dcc6
15 files changed
+219
-129
No files matched your search
@@ -12,7 +12,7 @@ function fixture(t){
|
||||
let captures=0,exports=0,failCapture=false;
|
||||
const row={source:'todo',instanceId:'i1',taskId:'t1',revision:'1',processName:'备损订单更改评审',nodeName:'订单专员(订单通知书)',processVersion:'1.4',receivedAt:'2026-10-19T01:00:00Z',serialNum:'S1',title:'订单号:SO-1 客户简称:真实客户'};
|
||||
const provider={capabilities:()=>({liveTodo:true,pdfExport:true,message:'actual probe'}),scan:async(c,p)=>{assert.equal(p.sessionId,'test-session');return [row];},capture:async()=>{captures++;if(failCapture)throw Error('capture unavailable');return {sample:{...row,connectionId:'c1',brief:'摘要',fields:{order:'SO-1',brief:'真实摘要'}},snapshot:{processVersion:'1.4',html:'<p>real fixture</p>',fields:[{path:'order',label:'订单号',value:'SO-1'},{path:'brief',label:'摘要',value:'真实摘要'}]}};}};
|
||||
const archive={probe:async()=>({automaticArchive:true,pdfExport:true,message:'runtime'}),capabilities:()=>({automaticArchive:true,pdfExport:true}),archive:async()=>{exports++;const content=Buffer.from('%PDF-1.7\nfixture');const file=path.join(dir,'order.pdf');fs.writeFileSync(file,content);return {archivedAt:now().toISOString(),files:[{name:'order.pdf',path:file,size:content.length,sha256:crypto.createHash('sha256').update(content).digest('hex'),kind:'pdf'}]};}};
|
||||
const archive={read:async file=>fs.promises.readFile(file.path),probe:async()=>({automaticArchive:true,pdfExport:true,message:'runtime'}),capabilities:()=>({automaticArchive:true,pdfExport:true}),archive:async()=>{exports++;const content=Buffer.from('%PDF-1.7\nfixture');const file=path.join(dir,'order.pdf');fs.writeFileSync(file,content);return {archivedAt:now().toISOString(),files:[{name:'order.pdf',path:file,size:content.length,sha256:crypto.createHash('sha256').update(content).digest('hex'),kind:'pdf'}]};}};
|
||||
const execution=new OrderExecutionCoordinator({store,workspace,provider,archive,clock:now});
|
||||
return {store,execution,row,provider,archive,principal,setFail:v=>{failCapture=v;},counts:()=>({captures,exports})};
|
||||
}
|
||||
@@ -51,11 +51,11 @@ test('cold restart probes archived pending work and restores dispatch gates with
|
||||
const execution=new OrderExecutionCoordinator({...f.execution,provider,archive});
|
||||
assert.equal(execution.snapshot().capabilities.pdfExport,false);
|
||||
await execution.scan({connectionId:'c1',idempotencyKey:'cold-restart'},principal);
|
||||
assert.deepEqual(execution.snapshot().capabilities,{liveTodo:true,pdfExport:true,automaticArchive:true});assert.equal(captured,true);assert.equal(probed,true);assert.equal(f.counts().exports,before.exports);assert.equal(f.store.all('orders')[0].status,'pending');
|
||||
assert.deepEqual(execution.snapshot().capabilities,{liveTodo:true,pdfExport:true,automaticArchive:true});assert.equal(captured,false);assert.equal(probed,true);assert.equal(f.counts().exports,before.exports);assert.equal(f.store.all('orders')[0].status,'pending');
|
||||
await execution.stop();
|
||||
f.store.prepare('2026-10-19T03:00:00Z','admin');captured=false;probed=false;
|
||||
const batchedRestart=new OrderExecutionCoordinator({...f.execution,provider,archive});await batchedRestart.scan({connectionId:'c1',idempotencyKey:'cold-batched-restart'},principal);
|
||||
assert.equal(batchedRestart.snapshot().tasks[0].status,'batched');assert.equal(f.store.providersReady(),true);assert.equal(f.counts().exports,before.exports);assert.equal(captured,true);assert.equal(probed,true);await batchedRestart.stop();
|
||||
assert.equal(batchedRestart.snapshot().tasks[0].status,'batched');assert.equal(f.store.providersReady(),true);assert.equal(f.counts().exports,before.exports);assert.equal(captured,false);assert.equal(probed,true);await batchedRestart.stop();
|
||||
});
|
||||
for(const supportsRecovery of [false,true])test(`committed archive receipt reconciles interrupted task before uncertainty classification (recovery=${supportsRecovery})`,async t=>{
|
||||
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archived'},principal);
|
||||
@@ -65,12 +65,12 @@ for(const supportsRecovery of [false,true])test(`committed archive receipt recon
|
||||
await execution.scan({connectionId:'c1',idempotencyKey:'reconciled'},principal);assert.equal(f.counts().exports,before.exports);assert.deepEqual(f.store.get('orders',order.id).archive,order.archive);assert.equal(f.store.prepare('2026-10-19T03:00:00Z','admin').length,1);
|
||||
await execution.stop();
|
||||
});
|
||||
test('unavailable original source leaves archived work blocked without replay or discarding its receipt',async t=>{
|
||||
test('unavailable original source does not block valid archived receipts',async t=>{
|
||||
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archived'},principal);
|
||||
const before=f.counts(),receipt=f.store.all('orders')[0].archive;
|
||||
const provider={scan:async()=>[],capabilities:()=>({liveTodo:true,pdfExport:false}),capture:async()=>{throw Error('原任务已不在已核验节点');}};
|
||||
const execution=new OrderExecutionCoordinator({...f.execution,provider});await execution.scan({connectionId:'c1',idempotencyKey:'source-unavailable'},principal);
|
||||
assert.equal(f.store.providersReady(),false);assert.equal(execution.snapshot().tasks[0].runtimeCheck.status,'blocked');assert.match(execution.snapshot().tasks[0].error,/原任务已不在/);assert.equal(f.counts().exports,before.exports);assert.deepEqual(f.store.all('orders')[0].archive,receipt);assert.equal(f.store.prepare('2026-10-19T03:00:00Z','admin').length,0);await execution.stop();
|
||||
assert.equal(f.store.providersReady(),true);assert.equal(execution.snapshot().tasks[0].runtimeCheck.status,'ready');assert.equal(f.counts().exports,before.exports);assert.deepEqual(f.store.all('orders')[0].archive,receipt);assert.equal(f.store.prepare('2026-10-19T03:00:00Z','admin').length,1);await execution.stop();
|
||||
});
|
||||
test('failed frozen batch resend is versioned admin-only idempotent and cannot replay unknown',async t=>{
|
||||
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal);
|
||||
@@ -93,7 +93,7 @@ test('scope, calendar and pause gates survive actual persisted capture provenanc
|
||||
f.execution.systemPrincipal=principal;await f.execution.background();assert.equal(scans,0);
|
||||
f.store.saveSettings({...f.store.settings(),enabled:true,channelId:'channel1'},'admin');f.execution.settings=()=>({schedule:{times:['11:00','17:00'],weekends:false}});f.execution.calendar=()=>[{date:'2026-10-19',kind:'pause',scan:false,send:false}];
|
||||
await f.execution.background();assert.equal(scans,0);
|
||||
f.execution.calendar=()=>[];await f.execution.background();assert.equal(scans,1);
|
||||
f.execution.calendar=()=>[];f.store.put('settings',{...f.store.get('settings','main'),processingEnabled:true,processingSince:'2026-10-19T00:00:00Z'});await f.execution.notifyDiscovery({connectionId:'c1',runId:'calendar-resume',rows:[f.row],startedAt:f.execution.now(),finishedAt:f.execution.now()});await f.execution.background();assert.equal(scans,0);
|
||||
const captured=f.store.fields().samples[0],adapter=f.store.fields().adapters.find(a=>a.sampleId===captured.id);
|
||||
activateFieldMapping(f.store,{sampleId:captured.id,processName:captured.processName,processVersion:captured.processVersion,fields:adapter.fields,version:adapter.draftVersion},admin);
|
||||
assert.equal(f.store.get('rules','bs-change').published.status,'paused');
|
||||
@@ -159,7 +159,7 @@ test('all fifteen categories capture actual fixture fields, archive to temporary
|
||||
let now=new Date('2026-10-19T02:59:00Z');const dispatcher=new OrderRuleDispatcher({store:f.store,mail,settings:()=>({schedule:{times:['11:00','17:00'],weekends:false}}),clock:()=>now,providersReady:()=>true,templateResolver:()=>({id:'template',version:1,subject:'ignored',text:'模板{{订单列表}}',html:'<div>{{订单列表}}</div>',to:['intruder@example.test'],attachments:[]})});
|
||||
await dispatcher.tick();now=new Date('2026-10-19T03:00:00Z');await dispatcher.tick();await dispatcher.stop();
|
||||
assert.equal(messages.length,15);assert.equal(f.store.all('batches').filter(b=>b.status==='sent').length,15);
|
||||
for(const [index,raw] of messages.entries()){const message=await simpleParser(raw);assert.deepEqual(message.to.value.map(x=>x.address),['orders@example.test']);assert.match(message.text,/模板/);assert.match(message.text,/SO-/);assert.equal(message.attachments.length,f.store.all('batches')[index].ruleSnapshot.attachPdf?1:0);}
|
||||
for(const [index,raw] of messages.entries()){const message=await simpleParser(raw);assert.deepEqual(message.to.value.map(x=>x.address),['orders@example.test']);assert.match(message.text,/模板/);assert.match(message.text,/SO-/);assert.equal(message.attachments.length,f.store.all('batches').find(b=>b.subject===message.subject).ruleSnapshot.attachPdf?1:0);}
|
||||
assert.equal(f.counts().exports,15);
|
||||
});
|
||||
for(const partial of [false,true])test(`real loopback SMTP ${partial?'partial refusal stays unknown':'complete envelope refusal is explicitly failed'}`,async t=>{
|
||||
@@ -176,7 +176,7 @@ for(const partial of [false,true])test(`real loopback SMTP ${partial?'partial re
|
||||
});
|
||||
|
||||
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=>{
|
||||
test('discovery barrier preserves frozen collection and explicitly blocks late same-window arrivals',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;
|
||||
@@ -188,10 +188,9 @@ test('discovery barrier covers queued scan, complete persisted set, late failure
|
||||
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);
|
||||
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');
|
||||
const replacement=f.store.prepare(cutoff,'admin');assert.equal(replacement.length,0);assert.equal(f.store.get('batches',batch.id).status,'prepared');assert.equal(f.store.get('batches',batch.id).orderIds.length,1);assert.equal(f.store.all('orders').filter(o=>o.blockedByBatchId===batch.id).length,2);assert.equal(f.store.all('business-issues').filter(i=>i.id.startsWith('late:')).length,2);assert.equal(f.store.beginSending(batch.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);
|
||||
@@ -217,3 +216,9 @@ test('all configured sources require independent complete cutoff discovery and t
|
||||
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);
|
||||
});
|
||||
test('trusted discovery persists while paused and is consumed without a second list read',async t=>{const f=fixture(t);await configure(f);let scans=0;f.provider.scan=async()=>{scans++;return [f.row];};f.execution.systemPrincipal=principal;await f.execution.notifyDiscovery({connectionId:'c1',runId:'watch1',rows:[f.row],startedAt:'2026-10-19T03:00:00Z',finishedAt:'2026-10-19T03:00:00Z'});await f.execution.background();assert.equal(scans,0);assert.equal(f.store.all('execution-discoveries')[0].status,'pending');assert.ok(f.store.discoveryBlockers('2026-10-19T03:00:00Z').length);f.store.put('settings',{...f.store.get('settings','main'),processingEnabled:true,processingSince:'2026-10-19T00:00:00Z'});await f.execution.background();assert.equal(scans,0);assert.equal(f.counts().exports,1);assert.equal(f.store.all('execution-discoveries')[0].status,'complete');await f.execution.background();assert.equal(scans,0);});
|
||||
test('archived todo disappearance uses receipt readback and never calls capture',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);f.archive.read=async file=>fs.promises.readFile(file.path);f.provider.scan=async()=>[];f.provider.capture=async()=>{throw Error('must not capture completed source');};await f.execution.scan({connectionId:'c1',idempotencyKey:'gone'},principal);assert.equal(f.execution.snapshot().tasks[0].runtimeCheck.status,'ready');assert.equal(f.counts().exports,1);});
|
||||
test('published migration is atomic versioned idempotent and preserves distribution-only archive',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);const before=f.store.all('orders')[0],record=f.store.get('rules','bs-change');record.published={...record.published,version:record.published.version+1,to:['new@example.test']};f.store.put('rules',record);const input={version:record.published.version,idempotencyKey:'migration1',note:'更新分发范围依据'};const preview=f.store.previewMigration(record.id,input,'admin');assert.equal(preview.items[0].archiveChanged,false);f.store.applyMigration(record.id,input,'admin');assert.deepEqual(f.store.get('orders',before.id).archive,before.archive);assert.deepEqual(f.store.get('orders',before.id).ruleSnapshot.to,['new@example.test']);f.store.applyMigration(record.id,input,'admin');assert.throws(()=>f.store.applyMigration(record.id,{...input,note:'另一不同处理依据'},'admin'),{status:409});const changed=f.store.get('orders',before.id);changed.status='unknown';f.store.put('orders',changed);assert.equal(f.store.previewMigration(record.id,{...input,idempotencyKey:'m2'},'admin').excluded.length,1);});
|
||||
test('revision resolution preserves identity, suppresses ignored repeat, blocks frozen orders',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);f.row.title='changed revision content';await f.execution.scan({connectionId:'c1',idempotencyKey:'conflict'},principal);let task=f.store.all('execution-tasks')[0];assert.equal(task.conflict,true);await f.execution.resolve(task.id,{version:task.version,idempotencyKey:'ignore1',resolution:'ignore',note:'人工比对确认忽略变化'},principal);await f.execution.scan({connectionId:'c1',idempotencyKey:'repeat'},principal);task=f.store.get('execution-tasks',task.id);assert.equal(task.conflict,false);const o=f.store.get('orders',task.orderId);o.status='unknown';f.store.put('orders',o);task.conflict=true;task.conflictRow={...task.row,title:'another'};f.store.put('execution-tasks',task);await assert.rejects(f.execution.resolve(task.id,{version:task.version,idempotencyKey:'adopt1',resolution:'adopt',note:'人工确认采用新修订'},principal),{status:409});});
|
||||
test('a new BPM revision is held against the prior identity and cannot bypass a frozen batch',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive-old'},principal);const batch=f.store.prepare('2026-10-19T03:00:00Z','admin')[0];f.row.revision='2';await f.execution.scan({connectionId:'c1',idempotencyKey:'revision2'},principal);const task=f.store.all('execution-tasks').find(t=>t.row.revision==='2');assert.equal(task.conflict,true);assert.equal(f.counts().exports,1);await assert.rejects(f.execution.resolve(task.id,{version:task.version,idempotencyKey:'adopt',resolution:'adopt',note:'核对新修订仍不能重发'},principal),{status:409});assert.equal(f.store.get('batches',batch.id).status,'prepared');});
|
||||
test('adopting a new unfrozen revision preserves original evidence and requires fresh archive',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'original'},principal);const original=f.store.all('orders')[0];f.row.revision='2';await f.execution.scan({connectionId:'c1',idempotencyKey:'changed'},principal);const task=f.store.all('execution-tasks').find(t=>t.row.revision==='2');await f.execution.resolve(task.id,{version:task.version,idempotencyKey:'adopt2',resolution:'adopt',note:'人工确认新版业务修订'},principal);await f.execution.scan({connectionId:'c1',idempotencyKey:'process-new'},principal);const order=f.store.get('orders',original.id);assert.equal(order.sample.revision,'2');assert.equal(order.archiveHistory.length,1);assert.equal(f.counts().exports,2);assert.equal(f.store.all('execution-tasks').find(t=>t.row.revision==='1').status,'ignored');assert.equal(f.store.get('execution-tasks',task.id).conflict,false);});
|
||||
Reference in new issue
Block a user