From cc1ade2261e6aa470c03978a629b3a8ade2ba858 Mon Sep 17 00:00:00 2001 From: abaishu0730 Date: Mon, 19 Oct 2026 13:49:33 +0800 Subject: [PATCH] fix: restore archived task progress and runtime gates after restart --- src/modules/order-execution/coordinator.cjs | 74 +++++++++++++++++++-- src/modules/order-rules/store.cjs | 3 +- tests/order-rules/execution.test.cjs | 33 ++++++++- 3 files changed, 102 insertions(+), 8 deletions(-) diff --git a/src/modules/order-execution/coordinator.cjs b/src/modules/order-execution/coordinator.cjs index 15f0b4d..4edbf46 100644 --- a/src/modules/order-execution/coordinator.cjs +++ b/src/modules/order-execution/coordinator.cjs @@ -7,9 +7,10 @@ const clone=value=>structuredClone(value); class OrderExecutionCoordinator{ constructor({store,workspace,provider,archive,mail,dashboard,clock=()=>new Date(),settings=()=>({}),calendar=()=>[],onException,systemPrincipal}){ Object.assign(this,{store,workspace,provider,archive,mail,dashboard,clock,settings,calendar,onException,systemPrincipal}); - this.tail=Promise.resolve();this.stopped=false;this.timer=null;this.query=store.get('execution-query','main')||{id:'main',status:'idle'};this.blockers=[]; + this.tail=Promise.resolve();this.stopped=false;this.timer=null;this.query=store.get('execution-query','main')||{id:'main',status:'idle'};this.blockers=[];this.runtimeRuleChecks=new Set(); if(this.query.status==='scanning'){this.query={...this.query,status:'failed',error:'服务重启中断了上次只读扫描,请重新扫描。',finishedAt:this.now()};store.put('execution-query',this.query);} for(const task of store.all('execution-tasks')){ + if(this.reconcileArchive(task))continue; if(task.status==='archiving'){task.status=archive.supportsRecovery===true?'failed':'unknown';task.step='archive';task.error='归档中断,结果待核验,需人工受控恢复。';this.persist(task);} else if(task.status==='capturing'){task.status='failed';task.error='只读采集已中断,可重新采集。';this.persist(task);} } @@ -18,6 +19,50 @@ class OrderExecutionCoordinator{ } now(){return this.clock().toISOString();} persist(task){task.version=(task.version||0)+1;task.updatedAt=this.now();task.history=[...(task.history||[]),{at:task.updatedAt,status:task.status,step:task.step,error:task.error||null}].slice(-100);this.store.put('execution-tasks',task);return task;} + reconcileArchive(task){ + if(task.conflict||task.step!=='archive'||!['archiving','unknown','failed'].includes(task.status))return false; + const order=task.orderId&&this.store.get('orders',task.orderId); + // recordArchive commits its validated receipt and pending state together. That + // committed progress is authoritative even when the following task write died. + if(!order?.archive||!['pending','batched','sent','unknown','ignored'].includes(order.status))return false; + task.status=order.status; + task.step='complete'; + task.error=order.error||null; + task.reconciledAt=this.now(); + this.persist(task); + return true; + } + validateCapture(task,connection,{sample,snapshot}){ + for(const key of ['source','instanceId','taskId','revision','processName','nodeName','receivedAt']){ + if(String(sample?.[key])!==String(task.row[key]))throw Error('采集样本与待办事件身份不一致。'); + } + if(sample.connectionId!==connection.id)throw Error('采集样本连接身份不一致。'); + if(!snapshot||snapshot.processVersion!==sample.processVersion||!Array.isArray(snapshot.fields))throw Error('采集样本流程版本或实际字段证据不一致。'); + } + async checkArchivedRuntime(task,order,connection,principal,{forceCapture=false}={}){ + const published=this.store.get('rules',order.ruleSnapshot?.id)?.published; + if(published?.status!=='enabled')return; + try{ + // A cold provider must really read the authorized form to establish its + // capture capability; successful stored archives are never exported again. + if(forceCapture||(await this.provider.capabilities()).pdfExport!==true){ + const captured=await this.provider.capture(connection,principal,clone(task.row)); + this.validateCapture(task,connection,captured); + } + const ruleKey=hash([order.ruleSnapshot.id,order.ruleSnapshot.version,order.ruleSnapshot.archiveDirectory]); + const probeRule=this.runtimeRuleChecks.has(ruleKey)&&this.store.providersReady()?undefined:order.ruleSnapshot; + await this.refreshCapabilities(probeRule); + if(this.store.providersReady())this.runtimeRuleChecks.add(ruleKey); + task.runtimeCheck={at:this.now(),status:this.store.providersReady()?'ready':'blocked'}; + task.error=this.store.providersReady()?order.error||null:'已归档订单的待办采集或归档运行条件尚未通过复核。'; + }catch(error){ + this.store.capabilities={...this.store.capabilities,pdfExport:false,automaticArchive:false}; + this.blockers.push('已归档订单运行条件复核失败:'+error.message); + task.runtimeCheck={at:this.now(),status:'blocked',error:error.message}; + task.error='已归档订单运行条件复核失败:'+error.message; + } + this.persist(task); + } serialize(work){if(this.stopped)return Promise.reject(Object.assign(Error('订单执行服务正在关闭。'),{status:503}));const operation=this.tail.catch(()=>{}).then(work);this.tail=operation;return operation;} connection(id,principal){const c=this.workspace.getConnection(id);if(!principal?.sessionId||!['admin','operator'].includes(principal?.user?.role)||(principal.user.role!=='admin'&&c.owner!==principal.user.username))fail('仅连接负责人或管理员可以扫描或重试。',403);if(c.status==='disabled')fail('连接已停用。',409);return c;} async refreshCapabilities(rule){ @@ -41,7 +86,7 @@ class OrderExecutionCoordinator{ this.query={id:'main',status:'scanning',connectionId:connection.id,startedAt:this.now()};this.store.put('execution-query',this.query); try{ const rows=await this.provider.scan(connection,principal);if(!Array.isArray(rows))throw Error('待办提供器返回格式无效。'); - await this.refreshCapabilities();let considered=0; + await this.refreshCapabilities();let considered=0;const observed=new Set(); for(const row of rows){ if(row.source!=='todo')continue; const rules=this.store.all('rules').map(r=>r.published?.status==='enabled'?r.published:r.draft).filter(rule=>rule.processNames.includes(row.processName)&&rule.nodeNames.includes(row.nodeName)); @@ -49,14 +94,34 @@ class OrderExecutionCoordinator{ // Historical rows are ignored before any capture or export. const window=this.store.snapshot().window;if(window&&Number.isFinite(Date.parse(row.receivedAt))&&Date.parse(row.receivedAt)r.categoryId))],status:'identified',step:'capture',createdAt:this.now()};this.persist(task);} if(hash(task.row)!==hash(row)){task.status='blocked';task.error='同一事件修订内容冲突,需核对源版本。';task.conflict=true;this.persist(task);await this.exception(task,connection,false);continue;} + this.reconcileArchive(task); if(task.conflict||task.status==='unknown'||task.step==='archive'&&task.status==='failed')continue; const order=task.orderId&&this.store.get('orders',task.orderId); - if(order&&['pending','batched','sent','unknown','ignored'].includes(order.status)){task.status=order.status;this.persist(task);continue;} + if(order&&['pending','batched','sent','unknown','ignored'].includes(order.status)){ + task.status=order.status; + task.error=order.error||null; + this.persist(task); + if(['pending','batched'].includes(order.status))await this.checkArchivedRuntime(task,order,connection,principal); + continue; + } await this.execute(task,connection,principal); } + // Already archived work can outlive its todo row. Recheck its original + // read-only source through the provider; an unavailable source remains an + // explicit runtime blocker and never causes another archive export. + for(const task of this.store.all('execution-tasks')){ + if(task.connectionId!==connection.id||observed.has(task.id)||task.conflict)continue; + this.reconcileArchive(task); + const order=task.orderId&&this.store.get('orders',task.orderId); + if(!order?.archive||!['pending','batched'].includes(order.status))continue; + const window=this.store.snapshot().window; + if(window&&Date.parse(order.event.receivedAt)task.categoryIds?.includes(orders[0].categoryId)&&['blocked','failed','unknown','capturing','archiving'].includes(task.status)&&inWindow(task.row?.receivedAt,window)))continue; + if(this.all('execution-tasks').some(task=>task.categoryIds?.includes(orders[0].categoryId)&&(['blocked','failed','unknown','capturing','archiving'].includes(task.status)||task.runtimeCheck?.status==='blocked')&&inWindow(task.row?.receivedAt,window)))continue; const rule=orders[0].ruleSnapshot;if(!rule)continue; if(this.all('batches').some(b=>b.categoryId===rule.categoryId&&Date.parse(b.cutoff)===Date.parse(cutoff)&&!(b.status==='cancelled'&&b.resolution?.resolution==='retry')))continue; const published=this.get('rules',rule.id)?.published; @@ -182,6 +182,7 @@ class RuleStore{ const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404); if(!(manual&&batch.manual)&&this.get('rules',batch.ruleSnapshot.id)?.published?.status!=='enabled')fail('该类别规则已暂停,批次不能进入发送。',409); const orders=batch.orderIds.map(oid=>this.get('orders',oid)); + if(this.all('execution-tasks').some(task=>batch.orderIds.includes(task.orderId)&&task.runtimeCheck?.status==='blocked'))fail('已归档订单的运行条件复核未通过,批次不能进入发送。',409); if(orders.some(o=>!o||o.batchId!==id||o.status!=='batched'))fail('批次订单预留已变化。',409); batch.version=(batch.version||1)+1;batch.status=transition('batch',batch.status,'send');this.put('batches',batch);return batch; });} diff --git a/tests/order-rules/execution.test.cjs b/tests/order-rules/execution.test.cjs index 30b8493..4fe58d6 100644 --- a/tests/order-rules/execution.test.cjs +++ b/tests/order-rules/execution.test.cjs @@ -35,6 +35,35 @@ test('capture failures block the entire category rather than silently omitting a assert.equal(f.execution.snapshot().tasks.filter(t=>t.status==='failed').length,1); assert.equal(f.store.prepare('2026-10-19T03:00:00Z','admin').length,0); }); +test('cold restart probes archived pending work and restores dispatch gates without exporting again',async t=>{ + const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive-before-restart'},principal); + const before=f.counts();let captured=false,probed=false; + const provider={scan:f.provider.scan,capabilities:()=>({liveTodo:true,pdfExport:captured}),capture:async(...args)=>{captured=true;return f.provider.capture(...args);}}; + const archive={...f.archive,capabilities:()=>({automaticArchive:probed,pdfExport:probed}),probe:async rule=>{assert.equal(rule.id,'bs-change');probed=true;return {automaticArchive:true,pdfExport:true};}}; + 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'); + 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(); +}); +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); + const task=f.store.all('execution-tasks')[0],order=f.store.get('orders',task.orderId),before=f.counts();task.status='archiving';task.step='archive';task.error=null;f.store.put('execution-tasks',task); + const archive={...f.archive,supportsRecovery};const execution=new OrderExecutionCoordinator({...f.execution,archive}); + assert.equal(execution.snapshot().tasks[0].status,'pending');assert.equal(execution.snapshot().tasks[0].step,'complete'); + 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=>{ + 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(); +}); 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); f.store.saveSettings({...f.store.settings(),channelId:'channel1'},'admin');const batch=f.store.prepare('2026-10-19T03:00:00Z','admin')[0];f.store.finishSending(batch.id,'failed','SMTP verify failed'); @@ -84,9 +113,9 @@ test('interrupted archive recovery is explicitly retried and never silently repl f.archive.archive=archive;await f.execution.scan({connectionId:'c1',idempotencyKey:'third'},principal);assert.equal(f.counts().exports,0); await f.execution.retry(task.id,{version:task.version,idempotencyKey:'retry',note:'已核对归档幂等凭据'},principal); assert.equal(f.execution.snapshot().tasks[0].status,'pending');assert.equal(f.counts().exports,1); - const running=f.store.get('execution-tasks',task.id);running.status='archiving';f.store.put('execution-tasks',running); + const running=f.store.get('execution-tasks',task.id);running.status='archiving';running.step='archive';f.store.put('execution-tasks',running); const restarted=new OrderExecutionCoordinator({...f.execution,store:f.store,workspace:f.execution.workspace,provider:f.provider,archive:f.archive}); - assert.equal(restarted.snapshot().tasks[0].status,'failed');await restarted.stop(); + assert.equal(restarted.snapshot().tasks[0].status,'pending');await restarted.stop(); }); test('unknown send first requires recorded verification; only then frozen manual resend is reachable',async t=>{ const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal);