fix: keep BPM reconciliation responsive and task based

This commit is contained in:
abaishu0730 committed 2026-10-23 13:00:34 +08:00
1 parent 8cb6a32876
commit 1848a6c10b
5 files changed
+165 -9

No files matched your search

+83
View File
@@ -0,0 +1,83 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {normalizeTodo}=require('../../src/modules/bpm/todo-client.cjs');
const {normalizeArrival}=require('../../src/modules/bpm/list-client.cjs');
const {BpmArrivalMonitor,todoArrival}=require('../../src/modules/bpm/arrival-monitor.cjs');
const {BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs');
const {BpmScanner}=require('../../src/modules/bpm/scanner.cjs');
const raw={taskId:'T1',processInstanceId:'I1',processName:'测试订单评审',activityName:'订单专员',processVersion:'2',serialNum:'TEST-1',processInstanceSubject:'测试订单',startTime:'2026-10-23T09:00:00'};
test('native todo arrivals accept absent business revision without inventing zero and retain a reported zero',()=>{
for(const portalSource of ['portal-v4','portal-v8']){
for(const value of [undefined,null]){
const arrival=todoArrival(normalizeTodo({...raw,revision:value},portalSource));
assert.equal(arrival.taskId,'T1');assert.equal(arrival.source,'todo:'+portalSource);
assert.equal(Object.hasOwn(arrival,'revision'),false);
assert.equal(arrival.arrivalDay,'2026-10-23');
}
const zero=todoArrival(normalizeTodo({...raw,revision:0},portalSource));
assert.equal(zero.revision,0);
assert.equal(todoArrival(normalizeTodo({...raw,revision:'2'},portalSource)).revision,'2');
}
for(const patch of [{source:'history'},{portalSource:'untrusted'},{instanceId:null},{taskId:''},{receivedAt:'invalid'}])assert.throws(()=>todoArrival({...normalizeTodo(raw,'portal-v4'),...patch}),error=>error.status===502);
});
function fixture(t){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'todo-arrival-identity-'));
let store=new BpmScanStore(dir),monitor,scanner,rows=[normalizeTodo(raw,'portal-v4')],calls=0;
const connection={id:'c1',name:'原始连接',owner:'admin',status:'connected'},principal={user:{username:'admin',role:'admin'},sessionId:'test'};
const workspace={getConnection:()=>({...connection}),snapshot:()=>({connections:[{...connection}],calendar:{overrides:[]}})};
const manager={sessions:new Map(),epoch:()=>0,ensure:async()=>({status:'connected'}),authorize(){},run:async(id,work)=>work(),vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})}),scanArrivals:async()=>[]};
const hints=[];
function open(){scanner=new BpmScanner({store,workspace,manager,settings:()=>({schedule:{weekends:true}})});monitor=new BpmArrivalMonitor({workspace,manager,scanner,provider:{scan:async()=>{calls++;return structuredClone(rows);}},onTodoReconciled:payload=>hints.push(payload),settings:()=>({schedule:{weekends:true}}),hubClient:{connect:async()=>({stop:async()=>{}})},clock:()=>Date.parse('2026-10-23T02:00:00Z'),debounceMs:1});}
open();
t.after(async()=>{await monitor.stop();await scanner.stop();store.close();fs.rmSync(dir,{recursive:true,force:true});});
return {connection,principal,hints,get store(){return store;},get monitor(){return monitor;},get calls(){return calls;},setRows:value=>rows=value,async restart(){await monitor.stop();await scanner.stop();store.close();store=new BpmScanStore(dir);open();}};
}
async function reconciled(f){await f.monitor.tick();await f.monitor.entries.get('c1').connecting;const deadline=Date.now()+2500;while(f.monitor.snapshot('c1').sources.todo.status!=='healthy'||f.monitor.entries.get('c1').sync){if(Date.now()>deadline)assert.fail('todo read did not reach a committed healthy state');await new Promise(resolve=>setTimeout(resolve,5));}}
test('monitor commits native missing-revision todos once and later reported revisions update the same persisted task',async t=>{
const f=fixture(t);await reconciled(f);
assert.equal(f.calls,1);assert.equal(f.store.status().runs.find(run=>run.kind==='todo').status,'success');
const first=f.store.list({kind:'todo'}).groups[0].items[0];assert.equal(Object.hasOwn(first,'revision'),false);
assert.equal(f.hints.length,1);assert.equal(Object.hasOwn(f.hints[0].rows[0],'revision'),false);
const firstRecord=f.store.ledger({scope:'all',kind:'todo',business:'all',page:1,pageSize:25},[],[]).items[0].recordId;
f.setRows([normalizeTodo({...raw,revision:0},'portal-v4')]);
assert.equal((await f.monitor.startTodoScan('c1',f.principal).promise).added,0);
assert.equal(f.store.list({kind:'todo'}).total,1);assert.equal(f.store.list({kind:'todo'}).groups[0].items[0].revision,0);
await f.restart();f.setRows([normalizeTodo({...raw,revision:'2'},'portal-v4')]);
assert.equal((await f.monitor.startTodoScan('c1',f.principal).promise).added,0);
assert.equal(f.store.list({kind:'todo'}).total,1);
const current=f.store.ledger({scope:'all',kind:'todo',business:'all',page:1,pageSize:25},[],[]).items[0];assert.equal(current.recordId,firstRecord);assert.equal(current.revision,'2');
f.setRows([normalizeTodo({...raw,revision:'2'},'portal-v8'),normalizeTodo({...raw,taskId:'T2'},'portal-v4')]);
assert.equal((await f.monitor.startTodoScan('c1',f.principal).promise).added,2);assert.equal(f.store.list({kind:'todo'}).total,3);
assert.equal(f.calls,4);assert.equal(f.store.status().runs.some(run=>run.status==='error'),false);
});
test('monitor reuses legacy todo storage identity without duplicating the task or rewriting unrelated inform evidence',async t=>{
const f=fixture(t),legacy={...normalizeArrival(raw,'todo:portal-v4'),kind:'todo',instanceId:'I1',revision:7,processVersion:'2',recordKey:'["I1","T1",7]'},inform=normalizeArrival(raw,'portal-v4');
f.store.complete(f.store.begin('c1','admin','todo'),'c1',[legacy],f.connection);
// Seed the pre-fix persisted key independently of the current writer.
f.store.db.prepare("UPDATE arrivals SET task_id=? WHERE source='todo:portal-v4'").run('["I1","T1",7]');
f.store.complete(f.store.begin('c1','admin'),'c1',[inform],f.connection);
const before=f.store.db.prepare('SELECT * FROM arrivals ORDER BY source').all();await f.restart();f.connection.name='连接已改名';
const result=await f.monitor.startTodoScan('c1',f.principal).promise;
assert.equal(result.added,0);assert.equal(f.store.list({kind:'todo'}).total,1);assert.equal(f.store.list().total,1);
const todo=f.store.db.prepare("SELECT * FROM arrivals WHERE source='todo:portal-v4'").get(),oldTodo=before.find(row=>row.source==='todo:portal-v4');
assert.equal(todo.task_id,'["I1","T1",7]');assert.equal(todo.first_seen,oldTodo.first_seen);
assert.deepEqual(JSON.parse(todo.value).origin,JSON.parse(oldTodo.value).origin);assert.equal(Object.hasOwn(JSON.parse(todo.value),'revision'),false);
assert.deepEqual(f.store.db.prepare("SELECT * FROM arrivals WHERE source='portal-v4'").get(),before.find(row=>row.source==='portal-v4'));
});
test('ambiguous legacy task identities require manual review and roll back every row and delivery in the read',async t=>{
const f=fixture(t),arrival={...normalizeArrival(raw,'todo:portal-v4'),kind:'todo',instanceId:'I1',processVersion:'2'};
const insert=f.store.db.prepare('INSERT INTO arrivals VALUES(?,?,?,?,?,?,?)');
for(const revision of [7,8])insert.run('c1','todo:portal-v4',JSON.stringify(['I1','T1',revision]),'2026-10-23',JSON.stringify({...arrival,revision,origin:{id:'c1',name:'旧连接',owner:'admin'}}),'2026-10-23T01:00:00Z','2026-10-23T01:00:00Z');
const before=f.store.db.prepare('SELECT * FROM arrivals ORDER BY task_id').all();
// A valid earlier row must not survive when a later row is ambiguous.
f.setRows([normalizeTodo({...raw,taskId:'T2'},'portal-v4'),normalizeTodo(raw,'portal-v4')]);
await assert.rejects(f.monitor.startTodoScan('c1',f.principal).promise,error=>error.status===409&&error.code==='TODO_IDENTITY_AMBIGUOUS'&&/人工核验/.test(error.message));
assert.deepEqual(f.store.db.prepare('SELECT * FROM arrivals ORDER BY task_id').all(),before);
assert.equal(f.store.deliveries.summary('c1').pending,0);assert.deepEqual(f.hints,[]);
const run=f.store.status().runs[0];assert.equal(run.status,'error');assert.match(run.message,/人工核验/);
});
@@ -0,0 +1,61 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs');
const principal={user:{username:'admin',role:'admin'},sessionId:'responsiveness-test'};
function fixture(t){
const records=new Map(),connection={id:'c1',owner:'admin',status:'connected'};
let processingEnabled=true,transactionDepth=0,snapshots=0;
const store={
all:kind=>[...(records.get(kind)?.values()||[])].map(item=>structuredClone(item)),
get:(kind,id)=>structuredClone(records.get(kind)?.get(id)||null),
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}),
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:()=>[],
};
const provider={capabilities:async()=>({liveTodo:true,pdfExport:true}),scan:async()=>{throw Error('Unexpected live scan');},capture:async()=>{throw Error('Synthetic capture unavailable');}};
const execution=new OrderExecutionCoordinator({store,systemPrincipal:principal,clock:()=>new Date('2026-10-23T02:00:00Z'),
workspace:{getConnection:()=>connection,snapshot:()=>({connections:[connection]})},provider,
archive:{capabilities:async()=>({automaticArchive:true,pdfExport:true})},onException:async()=>{},
});
t.after(()=>execution.stop());
return {store,execution,provider,connection,setProcessing:value=>{processingEnabled=value;},get snapshots(){return snapshots;},get inTransaction(){return transactionDepth!==0;}};
}
test('one discovery set resolves its window once and registers every row before external work',async t=>{
const f=fixture(t),rows=Array.from({length:17},(_,index)=>({source:'todo',portalSource:'portal-v4',taskId:String(index+1),instanceId:'i'+index,processName:'Synthetic process',nodeName:'Notification',receivedAt:'2026-10-23T01:00:00Z',title:'订单号:TEST-'+index}));
f.store.put('rules',{id:'r',draft:{id:'r',categoryId:'r',processNames:['Synthetic process'],scopes:[{processName:'Synthetic process',nodeName:'Notification'}]}});
let firstProbe;
f.provider.capabilities=async()=>{
firstProbe||={snapshots:f.snapshots,inTransaction:f.inTransaction,tasks:f.store.all('execution-tasks'),targetCount:f.store.get('execution-scans','c1').targetCount};
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.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);
});
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);
for(let index=0;index<20;index++)f.execution.notifyDiscovery({connectionId:'c1',runId:'run-'+index,rows:[],startedAt:new Date(Date.parse('2026-10-23T01:00:00Z')+index*1000).toISOString(),finishedAt:new Date(Date.parse('2026-10-23T01:00:01Z')+index*1000).toISOString()});
let completedAtSignal;
const signal=new Promise(resolve=>setImmediate(()=>{
completedAtSignal=f.store.all('execution-discovery-runs').filter(item=>item.status==='complete').length;
if(action==='pause')f.setProcessing(false);else void f.execution.stop();
resolve();
}));
await f.execution.background();await signal;
assert.equal(completedAtSignal,1,'an independent event-loop callback must run before consuming a second historical hint');
const hints=f.store.all('execution-discovery-runs');
assert.equal(hints.filter(item=>item.status==='complete').length,1);
assert.equal(hints.filter(item=>item.status==='pending').length,19);
assert.deepEqual(hints.filter(item=>item.status==='pending').map(item=>item.runId),Array.from({length:19},(_,index)=>'run-'+(index+1)));
assert.equal(f.store.get('execution-discoveries','c1').status,'pending');
if(action==='pause'){
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');
}
});