fix: retain capture evidence and control failed task recovery

This commit is contained in:
abaishu0730 committed 2026-10-26 11:00:11 +08:00
1 parent c19be938fc
commit 5bae83922c
17 files changed
+333 -35

No files matched your search

+12 -2
View File
@@ -141,13 +141,23 @@ class BpmOrderProvider{
return this.saved(connection,principal,async storageState=>{
if(row.source!=='todo'||row.configurationOnly||row.demo)throw fail('只读执行只接受真实当前通知任务。');
const rows=await this.client.scan(storageState),same=rows.filter(fresh=>fresh.source===row.source&&String(fresh.taskId)===String(row.taskId)&&(!row.portalSource||fresh.portalSource===row.portalSource));
if(same.length!==1)throw fail('此任务已不在当前列表或来源存在歧义,请重新扫描。');
if(same.length!==1)throw Object.assign(fail('此任务已不在当前列表或来源存在歧义,请核验原通知任务后再恢复。'),{code:'BPM_TASK_NOT_CURRENT'});
const current=same[0];
if(['instanceId','processName','nodeName','processVersion','revision','receivedAt','serialNum','title'].some(key=>String(current[key]??'')!==String(row[key]??'')))throw fail('当前通知任务的节点、版本、摘要或时间已变化,请重新核对。');
const original=row.detailUrl?safeEntry(row.detailUrl):null,fresh=current.detailUrl?safeEntry(current.detailUrl):null;
if(!fresh||original&&(original.target.searchParams.get('tid')!==fresh.target.searchParams.get('tid')||original.target.searchParams.get('pid')!==fresh.target.searchParams.get('pid')))throw fail('通知任务与详情标识不一致。');
const reader=this.readonlyReader||require('../../bpm-readonly-form.cjs').captureReadonlyForm;
const captured=await reader({storageState,detailUrl:current.detailUrl,processName:current.processName,nodeName:current.nodeName,listProcessVersion:current.processVersion,fieldsOnly,browserFactory:this.browserFactory});
let captured;
try{captured=await reader({storageState,detailUrl:current.detailUrl,processName:current.processName,nodeName:current.nodeName,listProcessVersion:current.processVersion,fieldsOnly,browserFactory:this.browserFactory});}
catch(error){
if(error.partialDetail){
const partial=error.partialDetail;
const fields=Object.entries(partial.detail.fields).map(([path,value])=>({path,label:path,value}));
error.partialCapture={sample:{...row,detailUrl:fresh.target.href,connectionId:connection.id,fields:structuredClone(partial.detail.fields),brief:row.title,formVersion:partial.detail.formVersion,formPath:partial.detail.formPath,detailEvidence:{tid:partial.detail.tid,pid:partial.detail.pid,formVersion:partial.detail.formVersion,listProcessVersion:current.processVersion,readOnly:true}},snapshot:{purpose:'field-mapping',fields,sourceUrl:partial.detailUrl,processVersion:current.processVersion,formVersion:partial.detail.formVersion,formPath:partial.detail.formPath,fieldSources:partial.detail.fieldSources,capturedAt:partial.capturedAt,evidenceHash:partial.evidenceHash}};
delete error.partialDetail;
}
this.checks={...this.checks,pdfExport:false,message:error.message};throw error;
}
const fields=Object.entries(captured.detail.fields).map(([path,value])=>({path,label:path,value}));
if(!fields.length||fields.length>4000||fields.every(field=>field.value===null||field.value===''))throw fail('只读表单缺少有效字段或超过采集上限。');
const snapshot={...(captured.snapshot||{purpose:'field-mapping'}),fields,sourceUrl:captured.detailUrl,processVersion:current.processVersion,formVersion:captured.detail.formVersion,formPath:captured.detail.formPath,fieldSources:captured.detail.fieldSources,capturedAt:captured.capturedAt,evidenceHash:captured.evidenceHash};
+55 -5
View File
@@ -47,10 +47,48 @@ class OrderExecutionCoordinator{
}
validateCapture(task,connection,{sample,snapshot}){
for(const key of ['source','portalSource','instanceId','taskId','revision','processName','nodeName','receivedAt']){
if(String(sample?.[key])!==String(task.row[key]))throw Error('采集样本与待办事件身份不一致。');
if(String(sample?.[key])!==String(task.row[key]))throw Object.assign(Error('采集样本与待办事件身份不一致。'),{code:'BPM_CAPTURE_IDENTITY_MISMATCH',status:409});
}
if(sample.connectionId!==connection.id)throw Error('采集样本连接身份不一致。');
if(!snapshot||snapshot.processVersion!==sample.processVersion||!Array.isArray(snapshot.fields))throw Error('采集样本流程版本或实际字段证据不一致。');
if(sample.connectionId!==connection.id)throw Object.assign(Error('采集样本连接身份不一致。'),{code:'BPM_CAPTURE_IDENTITY_MISMATCH',status:409});
if(!snapshot||snapshot.processVersion!==sample.processVersion||!Array.isArray(snapshot.fields))throw Object.assign(Error('采集样本流程版本或实际字段证据不一致。'),{code:'BPM_CAPTURE_IDENTITY_MISMATCH',status:409});
}
captureFailure(task,connection,error){
task.errorCode=typeof error.code==='string'?error.code:'CAPTURE_FAILED';
if(error.diagnostics)task.captureDiagnostics=clone(error.diagnostics);
if(error.partialCapture){
try{
const partial=clone(error.partialCapture);this.validateCapture(task,connection,partial);
// Fields are useful diagnostic evidence, never a completed PDF snapshot.
partial.snapshot={...partial.snapshot,purpose:'field-mapping'};delete partial.snapshot.html;
task.captureEvidenceId=this.store.recordCapture({...partial,taskId:task.id}).id;
delete task.captureEvidenceError;
}catch(evidenceError){task.captureEvidenceError=evidenceError.message;}
}
task.retryCount=(task.retryCount||0)+1;
if(['FORM_STRUCTURE_UNSUPPORTED','BPM_TASK_NOT_CURRENT','BPM_CAPTURE_IDENTITY_MISMATCH'].includes(task.errorCode)||[403,409].includes(Number(error.status))){
task.retryPolicy='manual';delete task.nextRetryAt;
if(task.errorCode==='BPM_TASK_NOT_CURRENT')task.status='blocked';
}else{
task.retryPolicy='automatic';
task.nextRetryAt=new Date(+this.clock()+Math.min(1800000,60000*2**Math.min(task.retryCount-1,5))).toISOString();
}
}
resetCaptureRetry(task){delete task.retryPolicy;delete task.retryCount;delete task.nextRetryAt;delete task.errorCode;delete task.captureDiagnostics;delete task.captureEvidenceError;}
markUnavailableCaptures(rows,connection){
const absent=[];
this.store.transaction(()=>{
for(const task of this.store.all('execution-tasks')){
if(task.connectionId!==connection.id||task.step!=='capture'||!['failed','blocked'].includes(task.status)||task.sampleId||task.conflict||task.missedWindow||task.supersededBy||task.revisionIgnored)continue;
const order=task.orderId&&this.store.get('orders',task.orderId);
if(order&&(order.archive||reserved(order)||['batched','sending','sent','unknown','ignored'].includes(order.status)))continue;
if(rows.some(row=>row.source==='todo'&&taskIdentity.sameTask(task,row)))continue;
if(task.errorCode==='BPM_TASK_NOT_CURRENT'&&task.recovery?.status==='requires-history-verification')continue;
task.recovery={status:'requires-history-verification',at:this.now(),previousErrorCode:task.errorCode||null,previousError:task.error||null,reason:'完整待办对账已成功,但原通知任务不在当前待办;需核验原通知节点及历史到达证据,禁止自动补发。'};
task.sourceUnavailableAt=task.sourceUnavailableAt||this.now();task.errorCode='BPM_TASK_NOT_CURRENT';task.status='blocked';task.retryPolicy='manual';delete task.nextRetryAt;
task.error=task.recovery.reason;this.persist(task);absent.push(task);
}
});
return absent;
}
async checkArchivedRuntime(task,order,connection,principal){
const published=this.store.executionRule(this.store.get('rules',order.ruleSnapshot?.id));
@@ -239,6 +277,7 @@ class OrderExecutionCoordinator{
if(needsRuntimeCheck(order))await this.checkArchivedRuntime(task,order,connection,principal);
continue;
}
if(task.step==='capture'&&(task.retryPolicy==='manual'||input.automatic&&Date.parse(task.nextRetryAt)>+this.clock()))continue;
await this.execute(task,connection,principal,{automatic:input.automatic===true});
}finally{
this.query.processedCount++;
@@ -257,6 +296,9 @@ class OrderExecutionCoordinator{
await this.checkArchivedRuntime(task,order,connection,principal);
}
if(input.automatic&&!this.store.settings().processingEnabled)throw Error('自动处理已暂停,待处理对账保留到恢复后继续。');
// Durable discovery hints can replay an older complete list. Only a fresh,
// fully successful provider scan can establish that a retained task left.
if(trustedRows===undefined)for(const task of this.markUnavailableCaptures(rows,connection))await this.exception(task,connection,false);
this.query={...this.query,status:'complete',finishedAt:this.now(),rowCount:rows.length,targetCount:considered};this.store.put('execution-requests',{id:key,at:this.now()});
}catch(error){this.query={...this.query,status:'failed',error:error.message,finishedAt:this.now()};throw error;}
finally{
@@ -275,7 +317,12 @@ class OrderExecutionCoordinator{
task.status='capturing';task.step='capture';this.persist(task);
const {sample,snapshot}=await this.provider.capture(connection,principal,clone(task.row));
this.validateCapture(task,connection,{sample,snapshot});
const captured=this.store.recordCapture({sample,snapshot,taskId:task.id});task.sampleId=captured.id;task.step='identify';this.persist(task);
const captured=this.store.recordCapture({sample,snapshot,taskId:task.id});task.sampleId=captured.id;task.step='identify';this.resetCaptureRetry(task);
if(task.sourceUnavailableAt||task.recovery?.status==='requires-history-verification'){
task.sourceAvailabilityHistory=[...(task.sourceAvailabilityHistory||[]),{sourceUnavailableAt:task.sourceUnavailableAt||null,recovery:clone(task.recovery||null),verifiedAt:this.now()}].slice(-100);
delete task.sourceUnavailableAt;if(task.recovery?.status==='requires-history-verification')delete task.recovery;
}
this.persist(task);
}
const captured=this.store.get('capture-samples',task.sampleId);let order;
await this.refreshCapabilities(this.store.executionRule(this.store.all('rules').find(r=>task.categoryIds.includes(r.id))));
@@ -296,7 +343,9 @@ class OrderExecutionCoordinator{
await this.exception(task,connection,true);
}catch(error){
if(expectedArchive&&!require('../order-rules/migrations.cjs').archiveContextMatches(this.store,this.store.get('orders',task.orderId),expectedArchive))return;
const uncertain=task.status==='archiving';task.status=uncertain&&this.archive.supportsRecovery!==true?'unknown':'failed';task.error=uncertain?'归档结果待核验,需人工受控恢复:'+error.message:error.message;this.persist(task);await this.exception(task,connection,false);
const uncertain=task.status==='archiving';task.status=uncertain&&this.archive.supportsRecovery!==true?'unknown':'failed';task.error=uncertain?'归档结果待核验,需人工受控恢复:'+error.message:error.message;
if(task.step==='capture')this.captureFailure(task,connection,error);
this.persist(task);await this.exception(task,connection,false);
}
}
adoptRevision(task,order,captured){
@@ -401,6 +450,7 @@ class OrderExecutionCoordinator{
if(typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请填写至少5字重试依据。');
if(!['failed','blocked'].includes(task.status)||task.conflict||task.missedWindow)fail('此任务结果未明确或不允许重试。',409);
this.store.audit(principal.user.username,'人工重试订单任务',id+':'+input.note.trim());
if(task.step==='capture')this.resetCaptureRetry(task);
await this.execute(task,connection,principal);
this.store.put('execution-requests',{id:requestId,taskId:id,inputHash,at:this.now()});
return this.snapshot(principal);
+12 -2
View File
@@ -31,11 +31,21 @@ const pick=(row,keys)=>Object.fromEntries(keys.filter(k=>row?.[k]!==undefined).m
const identity=row=>pick(row,['source','connectionId','instanceId','taskId','revision','processName','nodeName','orderNo','serialNum','receivedAt','quantity','brief','model','project','title']);
function taskEvidence(task,context,user){
if(!task)return null;
const value=pick(task,['id','version','connectionId','status','step','error','exceptionId','conflict','missedWindow','recovery','updatedAt','createdAt']);
const value=pick(task,['id','version','connectionId','status','step','error','errorCode','retryPolicy','nextRetryAt','exceptionId','conflict','missedWindow','recovery','updatedAt','createdAt']);
if(Array.isArray(task.diagnostics))value.diagnostics=task.diagnostics.slice(0,100).map(d=>pick(d,['code','reason','message','table','path','field','rowCount','expectedRows','actualRows']));
if(task.captureDiagnostics)value.captureDiagnostics=pick(task.captureDiagnostics,['reason','tableName','dynamicArea','backendRows','domRows','fieldPaths']);
const previous=(task.history||[]).findLast(h=>h.step==='capture'&&h.error&&h.error!==task.error&&['failed','blocked'].includes(h.status));
if(previous)value.previousCaptureFailure=pick(previous,['at','error']);
value.row=identity(task.row);
if(task.conflictRow){const previous=task.previousTaskId?context.orderRules.get('execution-tasks',task.previousTaskId):task;value.revisionEvidence={previous:identity(previous&&canReadConnection(context.workspace,user,previous.connectionId)?previous.row:undefined),incoming:identity(task.conflictRow)};}
return value;
}
function captureEvidence(context,task,user){
if(!task?.captureEvidenceId||!canReadConnection(context.workspace,user,task.connectionId))return undefined;
const captured=context.orderRules.get('capture-samples',task.captureEvidenceId),sample=captured?.sample;
if(captured?.provenance!=='server-provider'||captured.taskId!==task.id||sample?.connectionId!==task.connectionId||sample.taskId!==task.row?.taskId||sample.instanceId!==task.row?.instanceId)return undefined;
return {id:captured.id,readOnly:true,capturedAt:captured.capturedAt,processVersion:sample.processVersion,fields:(captured.snapshot?.fields||[]).slice(0,1000).map(f=>({...pick(f,['path','label','value']),source:pick(captured.snapshot?.fieldSources?.[f.path],['source','table','column','rowIndex'])}))};
}
function orderRow(order,task){
const event=identity(order?.event||task?.row);
return {...event,...pick(order,['id','status','categoryId','error','reason','batchId','createdAt','updatedAt','orderNo','receivedAt']),...(order?{notifications:notifications(order),...(order.ruleSnapshot?.testRunId?{testRunId:order.ruleSnapshot.testRunId}:{})}:{}),
@@ -93,7 +103,7 @@ function orderDetail(context,id,user){
const order=id.startsWith('task:')?null:context.orderRules.get('orders',id);
if(!classified(order,task)||(order?!canReadOrder(context.workspace,user,order):!task||!canReadConnection(context.workspace,user,task.connectionId)))fail('订单不存在或无权查看。',404);
const files=(order?.archive?.files||[]).map((file,index)=>({...pick(file,['name','size','sha256','kind']),index,url:'/api/order-rules/orders/'+encodeURIComponent(id)+'/files/'+index}));
return {...orderRow(order,task),event:identity(order?.event||task?.row),executionTask:taskEvidence(task,context,user),files,archivedAt:order?.archive?.archivedAt,archiveGeneration:order?.archiveGeneration||1,ruleVersion:order?.ruleSnapshot?.version,batches:[...data.batches,...require('./collecting-batches.cjs').list(context.orderRules)].filter(b=>b.orderIds?.includes(id)&&canReadBatch(context.workspace,user,b,context.orderRules)).map(b=>batchRow(context,b))};
return {...orderRow(order,task),event:identity(order?.event||task?.row),executionTask:taskEvidence(task,context,user),captureEvidence:captureEvidence(context,task,user),files,archivedAt:order?.archive?.archivedAt,archiveGeneration:order?.archiveGeneration||1,ruleVersion:order?.ruleSnapshot?.version,batches:[...data.batches,...require('./collecting-batches.cjs').list(context.orderRules)].filter(b=>b.orderIds?.includes(id)&&canReadBatch(context.workspace,user,b,context.orderRules)).map(b=>batchRow(context,b))};
}
function batchDetail(context,id,user){
const batch=id.startsWith('collecting-')?require('./collecting-batches.cjs').get(context.orderRules,id):context.orderRules.get('batches',id);