feat: bound restricted stability testing to five days

This commit is contained in:
abaishu0730 committed 2026-10-26 13:58:23 +08:00
1 parent 4d8f393895
commit f7426c937c
10 files changed
+125 -7

No files matched your search

+1 -1
View File
@@ -57,7 +57,7 @@ function orderRow(order,task){
function currentTasks(context,user){
const tasks=new Map();for(const task of records(context.orderRules).tasks){if(task.supersededBy||!task.orderId||!canReadConnection(context.workspace,user,task.connectionId))continue;const old=tasks.get(task.orderId);if(!old||Number(!!task.conflict)>Number(!!old.conflict)||!!task.conflict===!!old.conflict&&String(task.createdAt||'')>=String(old.createdAt||''))tasks.set(task.orderId,task);}return tasks;
}
const classified=(order,task)=>!order?.removedAt&&!!(order?.categoryId||order?.ruleSnapshot?.categoryId||order?.ruleSnapshot?.id||task?.categoryIds?.length);
const classified=(order,task)=>!order?.removedAt&&!task?.removedAt&&!!(order?.categoryId||order?.ruleSnapshot?.categoryId||order?.ruleSnapshot?.id||task?.categoryIds?.length);
function visibleOrders(context,user){
const data=records(context.orderRules),tasks=currentTasks(context,user);
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)));
+5 -3
View File
@@ -5,7 +5,7 @@ const {scopesFor}=require('./scopes.cjs');
const taskIdentity=require('./task-identity.cjs');
const canonical=v=>Array.isArray(v)?v.map(canonical):v&&typeof v==='object'?Object.fromEntries(Object.keys(v).sort().map(k=>[k,canonical(v[k])])):v;
const hash=v=>crypto.createHash('sha256').update(JSON.stringify(canonical(v))).digest('hex');
const state=store=>typeof store?.get==='function'?store.get('restricted-test','main')?.value||null:null;
const state=store=>{const run=typeof store?.get==='function'?store.get('restricted-test','main')?.value||null:null;return run&&require('./stability-period.cjs').period(store)?.expired?{...run,enabled:false}:run;};
function localPath(unc){
if(typeof unc!=='string'||/[\x00-\x1f/:]/.test(unc)||!/^\\\\localhost\\[a-z]\$\\/i.test(unc)||unc.split('\\').some(p=>p==='.'||p==='..'||/[. ]$/.test(p)))fail('受限测试仅允许当前用户桌面的localhost共享子目录。',409);
return unc[12]+':\\'+unc.slice(15);
@@ -31,7 +31,7 @@ function uncoveredFlows(store,run){
return [...new Set(processes)].filter(processName=>!adapters.some(a=>a.verified&&!a.reference&&rule.adapterIds.includes(a.id)&&a.processName===processName)).map(processName=>({categoryId:rule.id,processName}));
});
}
function summary(store){const run=state(store);if(!run)return null;return {id:run.id,version:run.version,enabled:run.enabled,recipient:run.recipient,archiveRoot:run.archiveRoot,channelId:run.channelId,since:run.since,ruleCount:run.rules.length,readyCount:run.rules.filter(r=>validRule(store,r,run)).length,uncovered:uncoveredFlows(store,run)};}
function summary(store){const run=state(store);if(!run)return null;const period=require('./stability-period.cjs').period(store);return {id:run.id,version:run.version,enabled:run.enabled,recipient:run.recipient,archiveRoot:run.archiveRoot,channelId:run.channelId,since:run.since,ruleCount:run.rules.length,readyCount:run.rules.filter(r=>validRule(store,r,run)).length,uncovered:uncoveredFlows(store,run),...(period?{period}:{})};}
function validRule(store,rule,run){return run.enabled&&hash(rule.adapterIds.map(id=>store.adapters().find(a=>a.id===id)))===run.adapterHashes[rule.id];}
function executionRule(store,record){
const run=state(store);if(!run)return record?.published||null;
@@ -111,6 +111,7 @@ function save(store,input,actor){
});
}
function assertRule(store,rule,run=state(store)){
require('./stability-period.cjs').assertActive(store);
if(!run){if(rule?.testRunId)fail('测试配置不存在,禁止按正式规则继续执行。',409);return;}
if(!run.enabled||rule?.testRunId!==run.id||rule.testArchiveRoot!==run.archiveRoot)fail('受限测试已暂停或执行快照不一致。',409);
const frozen=run.rules.find(r=>r.id===rule.id);
@@ -121,12 +122,13 @@ function assertRule(store,rule,run=state(store)){
if(rule.to?.length!==1||rule.to[0]!==run.recipient||rule.cc?.length)fail('受限测试收件人必须为固定QQ且无抄送。',409);
assertPath(store,rule.archiveDirectory,run);
}
function assertEvent(store,sample){const run=state(store);if(!run)return;
function assertEvent(store,sample){require('./stability-period.cjs').assertActive(store);const run=state(store);if(!run)return;
const at=eventTime(store,sample);
if(!run.enabled||sample?.demo||sample?.source!=='todo'||sample.configurationOnly||!Number.isFinite(Date.parse(sample.receivedAt))||Date.parse(at)<Date.parse(run.since)||Date.parse(sample.receivedAt)>Date.parse(store.now())+60000)fail('受限测试只处理启用基线之后或已明确纳入的当前真实待办通知。',409);
}
function assertOrder(store,order){assertRule(store,order?.ruleSnapshot);if(state(store)||order?.ruleSnapshot?.testRunId){assertEvent(store,order.sample||order.event);assertCurrentPresence(store,order.sample||order.event);for(const file of order.archive?.files||[])assertPath(store,file.path);}}
function assertBatch(store,batch,config){
require('./stability-period.cjs').assertActive(store);
const run=state(store);if(!run&&!batch.ruleSnapshot?.testRunId)return;
assertRule(store,batch.ruleSnapshot,run);if(batch.testRunId!==run.id||batch.channelId!==run.channelId||config.channelId!==run.channelId||batch.to?.length!==1||batch.to[0]!==run.recipient||batch.cc?.length)fail('受限测试批次目的地与固定配置不一致。',409);
for(const file of batch.attachments||[])assertPath(store,file.path,run);
@@ -0,0 +1,10 @@
'use strict';
function period(store){
const saved=typeof store?.get==='function'?store.get('stability-test','main'):null;
if(saved?.enabled!==true)return null;
const started=typeof saved.startedAt==='string'?Date.parse(saved.startedAt):NaN,end=typeof saved.endsAt==='string'?Date.parse(saved.endsAt):NaN;
const now=Date.parse(store.now());
return {startedAt:saved.startedAt,endsAt:saved.endsAt,expired:!Number.isFinite(started)||!Number.isFinite(end)||end<=started||!Number.isFinite(now)||now>=end};
}
function assertActive(store){if(period(store)?.expired)throw Object.assign(Error('五天稳定性测试已到期或期限配置无效,自动处理和发信已暂停。'),{status:409,code:'STABILITY_TEST_EXPIRED'});}
module.exports={period,assertActive};
@@ -0,0 +1,32 @@
'use strict';
const fail=message=>{throw Object.assign(new Error(message),{status:409});};
function resetForStabilityTest(store,{startedAt,endsAt},actor){
if(actor?.role!=='admin'||!actor.username)fail('仅管理员可以重新开始稳定性测试。');
if(!Number.isFinite(Date.parse(startedAt))||Date.parse(endsAt)-Date.parse(startedAt)!==5*86400000)fail('请提供连续五天的有效测试起止时间。');
return store.transaction(()=>{
const old=store.get('stability-test','main');if(old?.startedAt===startedAt&&old.endsAt===endsAt)return {...old.result,replayed:true};
const current=store.get('restricted-test','main'),run=current?.value;
if(!run?.enabled||run.recipient!=='2639266652@qq.com'||!run.rules?.length||run.rules.some(r=>r.to?.length!==1||r.to[0]!==run.recipient||r.cc?.length||r.attachPdf!==false))fail('必须保持固定QQ、无抄送、无附件的受限测试配置。');
if(store.all('batches').some(b=>['prepared','sending'].includes(b.status))||store.all('execution-tasks').some(t=>['capturing','archiving','sending'].includes(t.status)))fail('存在执行中或冻结待发任务,须先核验结果再重置测试。');
const result={orders:0,tasks:0},ids=new Set(),tasks=new Set();
for(const order of store.all('orders')){
if(order.removedAt)continue;ids.add(order.id);result.orders++;
order.removal={previousStatus:order.status,previousError:order.error,at:startedAt,note:'用户要求清理旧订单中心,开始五天稳定性测试'};order.removedAt=startedAt;
if(!['sent','unknown','sending','batched'].includes(order.status)&&!order.batchId&&!store.all('batches').some(b=>b.orderIds?.includes(order.id)))order.status='ignored';
store.put('orders',order);
}
for(const task of store.all('execution-tasks')){
if(task.removedAt)continue;tasks.add(task.id);result.tasks++;
task.removal={previousStatus:task.status,previousError:task.error,at:startedAt};task.removedAt=startedAt;task.revisionIgnored=true;
if(!['sent','unknown','sending','archiving','capturing'].includes(task.status))task.status='ignored';
task.version=(task.version||0)+1;store.put('execution-tasks',task);
}
for(const issue of store.all('business-issues'))if((issue.taskIds||[issue.taskId]).some(id=>tasks.has(id))||(issue.orderIds||[]).some(id=>ids.has(id)))store.put('business-issues',{...issue,previousStatus:issue.status,status:'retired',retiredAt:startedAt});
store.put('restricted-test-history',{id:'stability-before:'+startedAt,value:run});
const next={...run,since:startedAt,version:run.version+1};delete next.currentBacklog;delete next.enrolledAt;store.put('restricted-test',{...current,value:next});
const settings=store.get('settings','main');store.put('settings',{...settings,enabled:true,processingEnabled:true,processingSince:startedAt,version:settings.version+1});
store.put('stability-test',{id:'main',enabled:true,startedAt,endsAt,result});store.audit(actor.username,'开始五天稳定性测试',startedAt+' 至 '+endsAt+';旧记录仅移出中心,回执与归档保留。');
return result;
});
}
module.exports={resetForStabilityTest};
+2 -2
View File
@@ -69,7 +69,7 @@ class RuleStore{
all(kind){return this.db.prepare('SELECT id,payload FROM records WHERE kind=? ORDER BY rowid').all(kind).map(r=>this.vault.decode(kind+':'+r.id,r.payload));}
put(kind,value){this.db.prepare('INSERT INTO records VALUES(?,?,?) ON CONFLICT(kind,id) DO UPDATE SET payload=excluded.payload').run(kind,value.id,this.vault.encode(kind+':'+value.id,value));return value;}
audit(actor,action,detail){this.put('audit',{id:crypto.randomUUID(),at:this.now(),actor:String(actor||'系统'),action,detail});}
settings(){const {id,...settings}=this.get('settings','main');return {...settings,processingEnabled:settings.processingEnabled??settings.enabled,processingSince:settings.processingSince??null};}
settings(){const {id,...settings}=this.get('settings','main'),expired=require('./stability-period.cjs').period(this)?.expired;return {...settings,enabled:expired?false:settings.enabled,processingEnabled:expired?false:settings.processingEnabled??settings.enabled,processingSince:settings.processingSince??null};}
saveSettings(input,actor){return this.transaction(()=>{
const old=this.settings();
const testing=this.restrictedTest();if(testing&&input?.channelId!==testing.channelId)fail('受限测试发件通道已固定。',409);
@@ -223,7 +223,7 @@ class RuleStore{
return blockers;
}
categoryIncomplete(categoryId,window){
return this.all('execution-tasks').some(task=>task.categoryIds?.includes(categoryId)&&(!Number.isFinite(Date.parse(eligibility.eventTime(this,task.row)))||eligibility.eventInWindow(this,task.row,window))&&(task.conflict||['identified','blocked','failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'||task.runtimeCheck?.status==='blocked'));
return this.all('execution-tasks').some(task=>!task.removedAt&&task.categoryIds?.includes(categoryId)&&(!Number.isFinite(Date.parse(eligibility.eventTime(this,task.row)))||eligibility.eventInWindow(this,task.row,window))&&(task.conflict||['identified','blocked','failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'||task.runtimeCheck?.status==='blocked'));
}
batchIncomplete(batch){
return this.all('execution-tasks').some(task=>batch.orderIds.includes(task.orderId)&&(task.conflict||task.runtimeCheck?.status==='blocked'||['failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'));