perf: optimize full interface loading and refresh paths
This commit is contained in:
1 parent
649a0df832
commit
f317314a3c
57 files changed
+791
-136
No files matched your search
@@ -11,7 +11,7 @@ function associated(store,order,mode){return store.all('batches').filter(b=>mode
|
||||
function safeHistory(batches){return batches.every(b=>proof(b)&&(b.status==='failed'||b.status==='cancelled'&&b.resolution?.resolution==='carry_forward'));}
|
||||
function qualified(store,order,{active=true}={}){
|
||||
if(!order||order.removedAt||!order.categoryId||!order.sample||!receipt(order.archive)||!order.ruleSnapshot)return null;
|
||||
const tasks=store.all('execution-tasks').filter(t=>t.orderId===order.id);if(tasks.length!==1)return null;const task=tasks[0];
|
||||
const tasks=require('./read-context.cjs').byOrder(store,'execution-tasks',order.id);if(tasks.length!==1)return null;const task=tasks[0];
|
||||
if(task.removedAt||task.supersededBy||task.revisionIgnored||task.conflict||task.blockedByBatchId||!['complete','missed_window'].includes(task.step))return null;
|
||||
if(!identity.sameTask(task.row,order.sample)||['source','portalSource','taskId','instanceId','revision','processName','nodeName','receivedAt'].some(k=>String(task.row?.[k])!==String(order.sample[k])))return null;
|
||||
const captured=store.get('capture-samples',task.sampleId||'');if(captured?.provenance!=='server-provider'||captured.taskId!==task.id||typeof captured.snapshot?.html!=='string'||!captured.snapshot.html.trim()||!captured.sample||identity.fingerprint(captured.sample)!==identity.fingerprint(order.sample))return null;
|
||||
@@ -24,6 +24,11 @@ function qualified(store,order,{active=true}={}){
|
||||
return {task,original};
|
||||
}
|
||||
function windowForOrder(store,value,mode='normal'){
|
||||
const context=require('./read-context.cjs').state(store);
|
||||
if(context&&value?.id){const key=JSON.stringify(['carry',value.id,mode]);if(!context.memo.has(key))context.memo.set(key,readWindow(store,value,mode));return context.memo.get(key);}
|
||||
return readWindow(store,value,mode);
|
||||
}
|
||||
function readWindow(store,value,mode){
|
||||
if(!['normal','huizhou'].includes(mode))return null;
|
||||
// A Hui projection replaces event/order numbers. Always validate the persisted source.
|
||||
const order=value?.id&&store.get('orders',value.id),stamp=order?.carryForward?.[mode];if(!stamp||stamp.basisHash!==basis(order)||!qualified(store,order,{active:false}))return null;
|
||||
@@ -37,11 +42,13 @@ function knownMissed(store,value,original,stamp){
|
||||
return ['start','end','collectionStart','collectionEnd','collectionLeadMinutes','policyVersion','startInclusive','endInclusive'].every(key=>value[key]===expected[key]);
|
||||
}
|
||||
function candidate(store,order,mode){
|
||||
const q=qualified(store,order),state=delivery(order,mode);if(!q||!state||order.blockedByBatchId||state.blockedByBatchId||!['pending','blocked','archived'].includes(state.status))return null;
|
||||
const state=delivery(order,mode);if(!state||order.blockedByBatchId||state.blockedByBatchId||!['pending','blocked','archived'].includes(state.status))return null;
|
||||
if(mode==='huizhou'&&(order.ruleSnapshot?.huizhouEnabled!==true||!state.orderNos?.length||state.issues?.length||!['pending','blocked','archived','batched','sent','unknown'].includes(order.status)))return null;
|
||||
const q=qualified(store,order);if(!q)return null;
|
||||
const batches=associated(store,order,mode);if(!safeHistory(batches))return null;
|
||||
const failed=batches.filter(b=>b.status==='failed');if(state.batchId&&!failed.some(b=>b.id===state.batchId))return null;
|
||||
if(mode==='normal'&&['unknown','sending','sent','ignored','archiving','capturing','failed'].includes(q.task.status))return null;
|
||||
if(mode==='huizhou'&&(order.ruleSnapshot.huizhouEnabled!==true||!state.orderNos?.length||state.issues?.length||!['pending','blocked','archived','batched','sent','unknown'].includes(order.status)||q.task.step!=='complete'&&q.task.step!=='missed_window'))return null;
|
||||
if(mode==='huizhou'&&q.task.step!=='complete'&&q.task.step!=='missed_window')return null;
|
||||
const stamp=order.carryForward?.[mode];if(stamp&&!windowForOrder(store,order,mode))return null;
|
||||
if(!knownMissed(store,mode==='normal'?order.missedWindow:state.missedWindow,q.original,stamp)||mode==='normal'&&!knownMissed(store,q.task.missedWindow,q.original,stamp))return null;
|
||||
return {...q,order,mode,state,stamp,failed,previous:stamp?.targetCutoff||q.original.end};
|
||||
|
||||
@@ -14,18 +14,19 @@ function contentFor(store,rule,cutoff,mode,template){
|
||||
if(template?.attachments?.length)fail('业务通知模板禁止附件,批次编辑不能覆盖此限制。',409);
|
||||
return {template:{...(template||{}),id:template?.id||rule.bodyTemplateId||id,version:template?.version||rule.version,notificationMode:mode,status:'active',attachments:[],subject:saved.subject,text:saved.text,html:saved.html},edit:{id,version:saved.version,updatedAt:saved.updatedAt,updatedBy:saved.updatedBy}};
|
||||
}
|
||||
function list(store,{cutoff}={}){
|
||||
function list(store,options={}){return structuredClone(readList(require('./read-context.cjs').readStore(store),options));}
|
||||
function readList(store,{cutoff}={}){
|
||||
if(typeof store.clock!=='function'||typeof store.schedule!=='function'||typeof store.calendar!=='function')return [];
|
||||
const window=cutoff?require('./window.cjs').windowForCutoff(cutoff,store.schedule(),store.calendar()):upcomingWindow(store.clock(),store.schedule(),store.calendar());if(!window)return [];
|
||||
const groups=new Map(),frozen=store.all('batches');
|
||||
const groups=new Map(),frozen=new Set(store.all('batches').filter(b=>b.cutoff===window.end).map(b=>JSON.stringify([b.categoryId,b.notificationMode||'normal'])));
|
||||
for(const order of store.all('orders')){
|
||||
const rule=order.ruleSnapshot;if(order.removedAt||!rule?.id||!rule.categoryId||!require('./scopes.cjs').matchesScope(rule,order.event||{}))continue;
|
||||
if(order.blockedByBatchId||order.status==='ignored')continue;
|
||||
for(const mode of ['normal','huizhou']){
|
||||
const carried=require('./carry-forward.cjs').windowForOrder(store,order,mode);if(order.missedWindow&&!carried||!require('./restricted-test.cjs').orderInWindow(store,order,window,mode))continue;
|
||||
const notice=delivery(order,mode);if(!notice||notice.batchId||!['identified','preparing','archived','pending','blocked','failed'].includes(notice.status))continue;
|
||||
if(mode==='huizhou'&&rule.huizhouEnabled!==true)continue;
|
||||
if(frozen.some(b=>b.categoryId===rule.categoryId&&(b.notificationMode||'normal')===mode&&b.cutoff===window.end))continue;
|
||||
if(frozen.has(JSON.stringify([rule.categoryId,mode])))continue;
|
||||
const carried=require('./carry-forward.cjs').windowForOrder(store,order,mode);if(order.missedWindow&&!carried||!require('./restricted-test.cjs').orderInWindow(store,order,window,mode))continue;
|
||||
const id=idFor(rule,window.end,mode);if(!groups.has(id))groups.set(id,{id,status:'collecting',categoryId:rule.categoryId,notificationMode:mode,cutoff:window.end,window,windowStart:window.start,windowEnd:window.end,rule,orders:[],orderIds:[],attachments:[],createdAt:order.ingestedAt||order.createdAt,...(rule.testRunId?{testRunId:rule.testRunId}:{})});const group=groups.get(id);group.orders.push(order);group.orderIds.push(order.id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,14 +39,17 @@ function restrictedReceipt(orderRules,result){
|
||||
const snapshot=orderRules.snapshot({includeRecords:false});
|
||||
return {...result,rules:snapshot.rules,restrictedTest:snapshot.restrictedTest??null};
|
||||
}
|
||||
function templateUsage(rules){return rules.map(r=>({categoryId:r.published?.categoryId||r.draft?.categoryId,name:r.draft?.name,templateId:r.published?.bodyTemplateId||'',huizhouEnabled:r.published?.huizhouEnabled===true,huizhouTemplateId:r.published?.huizhouTemplateId||'',legacyBinding:!!r.published&&r.published.bodyTemplateId===undefined,publishedVersion:r.published?.version||null,status:r.published?.status||'draft'}));}
|
||||
|
||||
function orderRuleConfigurationApi({orderRules,mail,storage,workspace,user,url,route,method,reply}){
|
||||
if(method!=='GET'||!['/api/order-rules/configuration','/api/order-rules/configuration/samples','/api/order-rules/status'].includes(route))return false;
|
||||
if(method!=='GET'||!['/api/order-rules/configuration','/api/order-rules/configuration/samples','/api/order-rules/status','/api/order-rules/catalog','/api/order-rules/notification-settings'].includes(route))return false;
|
||||
if(!user)fail('请先登录。',401);
|
||||
if(!orderRules)fail('分类通知规则服务未启动。',503);
|
||||
if(route==='/api/order-rules/configuration')reply(200,configuration(orderRules,mail,storage));
|
||||
else if(route==='/api/order-rules/status')reply(200,{settings:{enabled:orderRules.settings().enabled},capabilities:structuredClone(orderRules.capabilities)});
|
||||
else if(route==='/api/order-rules/catalog'){const rules=orderRules.all('rules');reply(200,{rules:rules.map(r=>pick(r.draft,['categoryId','name'])),templateUsage:templateUsage(rules)});}
|
||||
else if(route==='/api/order-rules/notification-settings')reply(200,{settings:orderRules.settings(),restrictedTest:orderRules.restrictedTest()});
|
||||
else reply(200,samples(orderRules,workspace,user,url.searchParams));
|
||||
return true;
|
||||
}
|
||||
module.exports={orderRuleConfigurationApi,ruleReceipt,restrictedReceipt};
|
||||
module.exports={orderRuleConfigurationApi,ruleReceipt,restrictedReceipt,templateUsage};
|
||||
@@ -24,7 +24,9 @@ class OrderRuleDispatcher{
|
||||
this.attachmentReader=attachmentReader;if(templateResolver)store.templateResolver=templateResolver;if(mail?.store?.signature)store.signatureResolver=id=>mail.store.signature(id);
|
||||
}
|
||||
ready(){
|
||||
const config=this.store.settings(),cap=this.store.snapshot().capabilities;
|
||||
// Real RuleStore exposes immutable capabilities directly; retain the small
|
||||
// snapshot fallback for adapters and older test/runtime stores.
|
||||
const config=this.store.settings(),cap=this.store.capabilities||this.store.snapshot?.().capabilities||{};
|
||||
return !this.stopped&&config.enabled===true&&this.providersReady()===true&&cap?.liveTodo===true&&cap?.pdfExport===true&&cap?.automaticArchive===true;
|
||||
}
|
||||
tick(now=this.clock()){
|
||||
@@ -35,7 +37,7 @@ class OrderRuleDispatcher{
|
||||
}
|
||||
async perform(now){
|
||||
this.store.expireIntakes?.();
|
||||
for(const batch of this.store.snapshot().batches||[])if(batch.status==='prepared'&&!batch.manual&&now-Date.parse(batch.cutoff)>1800000)this.store.finishSending(batch.id,'failed','冻结发送队列超过30分钟,请负责人核验后受控补发。',{outcome:'not_submitted',phase:'queue_expired',at:this.clock().toISOString()});
|
||||
for(const batch of this.store.all('batches').reverse())if(batch.status==='prepared'&&!batch.manual&&now-Date.parse(batch.cutoff)>1800000)this.store.finishSending(batch.id,'failed','冻结发送队列超过30分钟,请负责人核验后受控补发。',{outcome:'not_submitted',phase:'queue_expired',at:this.clock().toISOString()});
|
||||
if(!this.ready())return;
|
||||
const config=freeze(structuredClone(this.store.settings())),schedule=this.settings()?.schedule,calendar=this.calendar();
|
||||
if(!schedule?.times?.length)return;
|
||||
@@ -43,13 +45,13 @@ class OrderRuleDispatcher{
|
||||
if(!this.schedule||this.schedule.signature!==signature||now-Date.parse(this.schedule.next)>60000){const current=require('./window.cjs').upcomingWindow(now,schedule,calendar);this.schedule={signature,next:current?.available?current.end:nextSlots(schedule,now,1,calendar)[0]};}
|
||||
const resumed=this.store.pendingIntakeCutoffs?.().filter(cutoff=>now-Date.parse(cutoff)>60000)||[];
|
||||
const cutoff=resumed[0]||this.schedule.next,canPrepare=cutoff&&now-Date.parse(cutoff)>=0&&(now-Date.parse(cutoff)<=60000||resumed.includes(cutoff));
|
||||
const queued=(this.store.snapshot().batches||[]).some(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
|
||||
const queued=this.store.all('batches').some(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
|
||||
if(!canPrepare&&!queued)return;
|
||||
try{await this.mail.exclusive(config.channelId,async()=>{
|
||||
if(!this.ready())return;
|
||||
if(canPrepare&&!this.store.discoveryBlockers(cutoff).length){const window=windowForCutoff(cutoff,schedule,calendar);this.store.prepare(cutoff,'系统调度',window);}
|
||||
// A frozen collection is immutable. Queue time is distinct from collection time.
|
||||
const batches=(this.store.snapshot().batches||[]).filter(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
|
||||
const batches=this.store.all('batches').reverse().filter(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
|
||||
for(const batch of batches){if(!this.ready())break;
|
||||
let expected;try{expected=windowForCutoff(batch.cutoff,schedule,calendar);}catch{continue;}
|
||||
const legacyStart=new Date(Date.parse(batch.cutoff)+8*3600000).toISOString().slice(0,10)+'T00:00:00+08:00';
|
||||
|
||||
@@ -3,15 +3,14 @@ const crypto=require('node:crypto');
|
||||
const {canReadConnection,canReadOrder,canReadBatch}=require('./access.cjs');
|
||||
const {fail}=require('./validation.cjs');
|
||||
const {notifications,modeOf}=require('./delivery.cjs');
|
||||
const cache=new WeakMap();
|
||||
const {readStore,state:readState}=require('./read-context.cjs');
|
||||
const orderStates=['candidate','identified','preparing','archived','pending','batched','blocked','unknown','sent','failed','capturing','archiving','queued','ignored'];
|
||||
const batchStates=['collecting','prepared','sending','unknown','failed','sent','cancelled'];
|
||||
function records(store){
|
||||
const revision=store.queryRevision?.();
|
||||
const saved=cache.get(store);
|
||||
if(revision!==undefined&&saved?.revision===revision)return saved;
|
||||
const memo=readState(store)?.memo,saved=memo?.get('records');if(saved)return saved;
|
||||
const value={revision:revision??Date.now(),orders:store.all('orders'),batches:store.all('batches'),tasks:store.all('execution-tasks'),issues:store.all('business-issues')};
|
||||
if(revision!==undefined)cache.set(store,value);
|
||||
memo?.set('records',value);
|
||||
return value;
|
||||
}
|
||||
function filters(input={},kind){
|
||||
@@ -63,7 +62,8 @@ function visibleOrders(context,user,collectingGroups){
|
||||
const rows=data.orders.filter(o=>classified(o,tasks.get(o.id))&&canReadOrder(context.workspace,user,o)).map(o=>orderRow(o,tasks.get(o.id)));
|
||||
for(const task of data.tasks)if(!task.orderId&&!task.supersededBy&&classified(null,task)&&canReadConnection(context.workspace,user,task.connectionId))rows.push(orderRow(null,task));
|
||||
const collecting=(collectingGroups||require('./collecting-batches.cjs').list(context.orderRules)).filter(b=>canReadBatch(context.workspace,user,b,context.orderRules));
|
||||
for(const row of rows)row.collectingBatches=collecting.filter(b=>b.orderIds.includes(row.id)).map(b=>({id:b.id,subject:b.subject,cutoff:b.cutoff}));
|
||||
const membership=new Map();for(const batch of collecting)for(const id of batch.orderIds){if(!membership.has(id))membership.set(id,[]);membership.get(id).push({id:batch.id,subject:batch.subject,cutoff:batch.cutoff});}
|
||||
for(const row of rows)row.collectingBatches=membership.get(row.id)||[];
|
||||
return rows;
|
||||
}
|
||||
function page(rows,input,revision){
|
||||
@@ -112,14 +112,14 @@ function batchDetail(context,id,user){
|
||||
return {...batchRow(context,batch),...pick(batch,['to','cc','text','html','window','sentAt','resolvedAt','resolution','manual','originalBatchId','template','signature','contentEdit','editor','edited','context','editable']),orders:(batch.orderIds||[]).map(id=>context.orderRules.get('orders',id)).filter(Boolean).map(o=>orderRow(o)),attachments:(batch.attachments||[]).map(a=>pick(a,['name','filename','size','sha256']))};
|
||||
}
|
||||
async function readOrderFile(context,id,index,user){
|
||||
orderDetail(context,id,user);
|
||||
orderDetail({...context,orderRules:readStore(context.orderRules)},id,user);
|
||||
if(!Number.isSafeInteger(index)||index<0)fail('文件编号无效。');
|
||||
const file=context.orderRules.get('orders',id)?.archive?.files?.[index];
|
||||
if(!file||!Number.isSafeInteger(file.size)||!/^[a-f0-9]{64}$/i.test(file.sha256||''))fail('归档文件证据不完整。',409);
|
||||
if(typeof context.execution?.archive?.read!=='function')fail('归档读取服务暂不可用。',503);
|
||||
const bytes=await context.execution.archive.read(structuredClone(file));
|
||||
// Ownership may change while storage performs an asynchronous read.
|
||||
orderDetail(context,id,user);
|
||||
orderDetail({...context,orderRules:readStore(context.orderRules)},id,user);
|
||||
const current=context.orderRules.get('orders',id)?.archive?.files?.[index];
|
||||
if(!current||current.sha256!==file.sha256||current.path!==file.path||current.size!==file.size)fail('归档证据已变化,请重新读取详情。',409);
|
||||
if(!Buffer.isBuffer(bytes)||bytes.length!==file.size||bytes.subarray(0,5).toString()!=='%PDF-'||crypto.createHash('sha256').update(bytes).digest('hex')!==file.sha256)fail('归档文件读回校验失败。',409);
|
||||
@@ -145,4 +145,5 @@ function summary(context,user){
|
||||
result.revision=crypto.createHash('sha256').update(publicRevision(context,user)+JSON.stringify([result.window,result.issues])).digest('hex').slice(0,24);
|
||||
return result;
|
||||
}
|
||||
module.exports={queryOrders,queryBatches,orderDetail,batchDetail,readOrderFile,summary};
|
||||
const scoped=fn=>(context,...args)=>structuredClone(fn({...context,orderRules:readStore(context.orderRules)},...args));
|
||||
module.exports={queryOrders:scoped(queryOrders),queryBatches:scoped(queryBatches),orderDetail:scoped(orderDetail),batchDetail:scoped(batchDetail),readOrderFile,summary:scoped(summary)};
|
||||
@@ -0,0 +1,32 @@
|
||||
'use strict';
|
||||
const contextKey=Symbol('order-rules-read-context');
|
||||
// This facade lives for one synchronous read only. Cached rows are internal,
|
||||
// read-only values; public query boundaries copy their result before returning.
|
||||
function readStore(store){
|
||||
if(store[contextKey])return store;
|
||||
const rows=new Map(),values=new Map(),indexes=new Map(),memo=new Map(),view=Object.create(store);
|
||||
const state={memo,index(name,build){if(!indexes.has(name))indexes.set(name,build());return indexes.get(name);}};
|
||||
Object.defineProperty(view,contextKey,{value:state});
|
||||
view.all=function(kind){
|
||||
if(!rows.has(kind)){
|
||||
const result=store.all(kind);rows.set(kind,result);
|
||||
let found=values.get(kind);if(!found)values.set(kind,found=new Map());for(const row of result)found.set(row.id,row);
|
||||
}
|
||||
// snapshot callers may reverse/sort the array, never the cached ordering.
|
||||
return rows.get(kind).slice();
|
||||
};
|
||||
view.get=function(kind,id){
|
||||
let found=values.get(kind);if(!found)values.set(kind,found=new Map());
|
||||
if(!found.has(id))found.set(id,rows.has(kind)?null:store.get(kind,id));
|
||||
return found.get(id);
|
||||
};
|
||||
for(const method of ['put','audit','transaction'])view[method]=()=>{throw new Error('Read context cannot write.');};
|
||||
return view;
|
||||
}
|
||||
function state(store){return store?.[contextKey];}
|
||||
function byOrder(store,kind,id){
|
||||
const context=state(store);if(!context)return store.all(kind).filter(row=>row.orderId===id);
|
||||
const index=context.index('order:'+kind,()=>{const map=new Map();for(const row of store.all(kind)){if(!map.has(row.orderId))map.set(row.orderId,[]);map.get(row.orderId).push(row);}return map;});
|
||||
return index.get(id)||[];
|
||||
}
|
||||
module.exports={readStore,state,byOrder};
|
||||
@@ -17,6 +17,7 @@ const digest=value=>crypto.createHash('sha256').update(JSON.stringify(canonical(
|
||||
const copy=value=>structuredClone(value);
|
||||
const BASE_CAPABILITIES={liveTodo:false,pdfExport:false,automaticArchive:false};
|
||||
function validDate(value){return typeof value==='string'&&/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value)&&Number.isFinite(Date.parse(value));}
|
||||
function pendingCompanionState(order){const hui=delivery(order,'huizhou');return !!order?.archive&&order.ruleSnapshot?.huizhouEnabled===true&&['batched','sending','sent','unknown'].includes(order.status)&&!!hui&&['pending','blocked'].includes(hui.status)&&!hui.batchId&&!hui.missedWindow;}
|
||||
class RuleStore{
|
||||
constructor(dir,{clock=()=>new Date(),capabilities={},seedOverrides=[],schedule=()=>({times:['11:00','17:00'],weekends:false}),calendar=()=>[],desktopRoot=path.join(require('node:os').homedir(),'Desktop')}={}){
|
||||
this.desktopRoot=desktopRoot;
|
||||
@@ -158,12 +159,17 @@ class RuleStore{
|
||||
return [...new Set(cutoffs.filter(cutoff=>cutoff&&now>=Date.parse(cutoff)&&now<=Date.parse(cutoff)+1800000))].sort();
|
||||
}
|
||||
pendingCompanion(order){
|
||||
const hui=delivery(order,'huizhou'),normal=order?.batchId&&this.get('batches',order.batchId);
|
||||
return !!order?.archive&&order.ruleSnapshot?.huizhouEnabled===true&&['batched','sending','sent','unknown'].includes(order.status)&&!!hui&&['pending','blocked'].includes(hui.status)&&!hui.batchId&&!hui.missedWindow&&normal?.huizhouPlanned===true&&modeOf(normal)==='normal'&&normal.orderIds?.includes(order.id)&&normal.cutoff===this.intakeWindow(order.sample||order.event,{includeExpired:true})?.end;
|
||||
if(!pendingCompanionState(order))return false;
|
||||
const normal=order.batchId&&this.get('batches',order.batchId);
|
||||
return normal?.huizhouPlanned===true&&modeOf(normal)==='normal'&&normal.orderIds?.includes(order.id)&&normal.cutoff===this.intakeWindow(order.sample||order.event,{includeExpired:true})?.end;
|
||||
}
|
||||
expireIntakes(){return this.transaction(()=>{
|
||||
const carry=require('./carry-forward.cjs');carry.advance(this);
|
||||
for(const order of this.all('orders')){
|
||||
// Only uncompleted normal work or an independent Hui companion can expire.
|
||||
// Do this before intakeWindow's task lookup; keep carry advancement above
|
||||
// and the persisted evidence checks below on the ordinary writable store.
|
||||
if(!(['identified','preparing','archived','pending','blocked'].includes(order.status)&&!order.batchId&&!order.missedWindow)&&!pendingCompanionState(order))continue;
|
||||
const window=this.intakeWindow(order.sample||order.event,{includeExpired:true});
|
||||
if(!window||+this.clock()<=Date.parse(window.end)+1800000)continue;
|
||||
if(this.pendingCompanion(order)&&!carry.hasCarry(this,order,'huizhou')){
|
||||
|
||||
@@ -9,7 +9,15 @@ function taskIdentity(value){const item=identity(value);if(!item.source||!item.t
|
||||
// A legacy row with no native portal source is ambiguous. Treat it as an
|
||||
// overlapping namespace, never guess v4/v8 and create a second notification.
|
||||
function sameTask(a,b){a=identity(a);b=identity(b);return !!a.source&&!!a.taskId&&a.source===b.source&&a.taskId===b.taskId&&(!a.portalSource||!b.portalSource||a.portalSource===b.portalSource);}
|
||||
function records(store,kind,value){return store.all(kind).filter(row=>sameTask(row,value));}
|
||||
function records(store,kind,value){
|
||||
const context=require('./read-context.cjs').state(store);if(!context)return store.all(kind).filter(row=>sameTask(row,value));
|
||||
const key=item=>JSON.stringify([item.source,item.taskId]),index=context.index('task:'+kind,()=>{
|
||||
const groups=new Map();for(const row of store.all(kind)){const item=identity(row);if(!item.source||!item.taskId)continue;const k=key(item);if(!groups.has(k))groups.set(k,[]);groups.get(k).push(row);}return groups;
|
||||
});
|
||||
// Keep all portal variants: a legacy row without portalSource overlaps every
|
||||
// native namespace, and lookup must still reject multiple matching records.
|
||||
return (index.get(key(identity(value)))||[]).filter(row=>sameTask(row,value));
|
||||
}
|
||||
function lookup(store,kind,value){const rows=records(store,kind,value);if(rows.length>1)fail('同一通知任务存在多条旧记录,须人工核验,禁止新建或自动合并。',409);return rows[0]||null;}
|
||||
function normalize(value){const row=structuredClone(value);for(const key of ['connectionId','source','portalSource','instanceId','taskId','revision'])if(row[key]!==undefined&&row[key]!==null)row[key]=text(row[key]);if(!text(row.revision))delete row.revision;return row;}
|
||||
function fingerprint(value){const row=normalize(value);delete row.connectionId;return digest(row);}
|
||||
|
||||
Reference in new issue
Block a user