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
@@ -3,7 +3,7 @@ const {SessionStore,SESSION_MS}=require('./sessions.cjs');
|
||||
const {isLoopback}=require('../../app/request.cjs');
|
||||
const {validateChange}=require('./passwords.cjs');
|
||||
function createAuth({store,workspace,bpmSessions,bpmMonitor,bpmLifecycle}){
|
||||
const sessions=new SessionStore(path.dirname(store.file));const failures=new Map(),passwordFailures=new Map();
|
||||
const sessions=new SessionStore(path.dirname(store.file));const failures=new Map(),passwordFailures=new Map(),pendingLogins=new Map();
|
||||
const cleanup=require('./pending-cleanup.cjs').accessCleanup({store,workspace,bpmSessions,bpmMonitor,bpmLifecycle,sessions});
|
||||
const sessionCookieName='order_session';
|
||||
const sessionCookiePattern=new RegExp('(?:^|;\\s*)'+sessionCookieName+'=([a-f0-9]{64})(?:;|$)');
|
||||
@@ -24,8 +24,12 @@ const handled=(...args)=>{reply(...args);return {handled:true};};
|
||||
if(route==='/api/login' && request.method==='POST') {
|
||||
const address=request.socket.remoteAddress;const now=Date.now();
|
||||
for(const [key,value] of failures)if(now-value.since>900000)failures.delete(key);
|
||||
if(failures.get(address)?.count>=10)fail(429,'登录失败次数过多,请 15 分钟后重试。');
|
||||
const user=store.authenticate(body.username,body.password);
|
||||
if((failures.get(address)?.count||0)+(pendingLogins.get(address)||0)>=10)fail(429,'登录失败次数过多,请 15 分钟后重试。');
|
||||
const candidate=typeof body.username==='string'?store.users().find(member=>member.username.toLowerCase()===body.username.toLowerCase()):null;
|
||||
const passwordVersion=candidate?store.passwordVersion(candidate.id):null;
|
||||
pendingLogins.set(address,(pendingLogins.get(address)||0)+1);
|
||||
let user;try{user=await store.authenticateAsync(body.username,body.password);}finally{const pending=(pendingLogins.get(address)||1)-1;if(pending)pendingLogins.set(address,pending);else pendingLogins.delete(address);}
|
||||
if(user&&(!candidate||user.id!==candidate.id||store.passwordVersion(user.id)!==passwordVersion||store.user(user.id)?.enabled===false))user=null;
|
||||
if(!user){if(failures.size>1000)failures.clear();const previous=failures.get(address);failures.set(address,{since:previous?.since || now,count:(previous?.count || 0)+1});fail(401,'账号或密码不正确。');}
|
||||
failures.delete(address);return handled(200,{user:signIn(user)});
|
||||
}
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto');
|
||||
const {promisify}=require('node:util');
|
||||
const scrypt=promisify(crypto.scrypt),passwordQueue=[];let active=0;
|
||||
function schedulePassword(work){
|
||||
if(active>=4&&passwordQueue.length>=32)return Promise.reject(Object.assign(Error('登录验证繁忙,请稍后重试。'),{status:429}));
|
||||
return new Promise((resolve,reject)=>{
|
||||
const start=()=>{active++;Promise.resolve().then(work).then(resolve,reject).finally(()=>{active--;passwordQueue.shift()?.();});};
|
||||
if(active<4)start();else passwordQueue.push(start);
|
||||
});
|
||||
}
|
||||
const fail=message=>{throw Object.assign(new Error(message),{status:400});};
|
||||
function validatePassword(password){if(typeof password!=='string'||password.length<12||password.length>128)fail('密码长度需为 12–128 位。');}
|
||||
function hashPassword(password){validatePassword(password);const salt=crypto.randomBytes(16).toString('hex');return salt+':'+crypto.scryptSync(password,salt,32).toString('hex');}
|
||||
@@ -9,10 +18,15 @@ function matchesPassword(password,encoded){
|
||||
const actual=crypto.scryptSync(password,salt,32),expected=Buffer.from(hash||'','hex');
|
||||
return expected.length===actual.length&&crypto.timingSafeEqual(actual,expected);
|
||||
}
|
||||
async function matchesPasswordAsync(password,encoded){
|
||||
if(typeof password!=='string'||password.length>128)return false;
|
||||
const [salt,hash]=(encoded||'00000000000000000000000000000000:'+ '0'.repeat(64)).split(':');
|
||||
return schedulePassword(async()=>{const actual=await scrypt(password,salt,32),expected=Buffer.from(hash||'','hex');return expected.length===actual.length&&crypto.timingSafeEqual(actual,expected);});
|
||||
}
|
||||
function validateChange(body){
|
||||
if(!body||Object.keys(body).some(key=>!['currentPassword','newPassword','confirmPassword'].includes(key)))fail('密码修改内容不正确。');
|
||||
if(typeof body.currentPassword!=='string'||!body.currentPassword||body.currentPassword.length>128)fail('请填写当前密码。');
|
||||
validatePassword(body.newPassword);
|
||||
if(body.confirmPassword!==body.newPassword)fail('两次输入的新密码不一致。');
|
||||
}
|
||||
module.exports={validatePassword,hashPassword,matchesPassword,validateChange};
|
||||
module.exports={validatePassword,hashPassword,matchesPassword,matchesPasswordAsync,validateChange};
|
||||
@@ -2,7 +2,7 @@ const fs=require('node:fs');
|
||||
const path=require('node:path');
|
||||
const crypto=require('node:crypto');
|
||||
const {DatabaseSync}=require('node:sqlite');
|
||||
const {validatePassword,hashPassword,matchesPassword}=require('./passwords.cjs');
|
||||
const {validatePassword,hashPassword,matchesPassword,matchesPasswordAsync}=require('./passwords.cjs');
|
||||
const {JobStore}=require('./job-store.cjs');
|
||||
const copy=value=>structuredClone(value);
|
||||
const safeUser=({id,username,role,createdAt,enabled=true,version=1})=>({id,username,role,createdAt,enabled,version});
|
||||
@@ -93,6 +93,16 @@ class Store {
|
||||
return safeUser(user);
|
||||
}
|
||||
passwordVersion(id){return this.data.users.find(user=>user.id===id)?.passwordVersion||0;}
|
||||
async authenticateAsync(username,password){
|
||||
if(typeof username!=='string'||typeof password!=='string'||password.length>128)return null;
|
||||
const prior=this.data.users.find(user=>user.username.toLowerCase()===username.toLowerCase());
|
||||
const passwordHash=prior?.passwordHash,version=prior?.passwordVersion||0;
|
||||
const matches=await matchesPasswordAsync(password,passwordHash);
|
||||
// Password/role changes can commit while the worker pool verifies the hash.
|
||||
const current=prior&&this.data.users.find(user=>user.id===prior.id);
|
||||
if(!matches||!current||current.enabled===false||current.passwordHash!==passwordHash||(current.passwordVersion||0)!==version)return null;
|
||||
return safeUser(current);
|
||||
}
|
||||
validateUserChange(id,input,actor){
|
||||
if(actor?.role!=='admin')fail('仅管理员可以调整账号。',403);
|
||||
const target=this.user(id);if(!target)fail('账号不存在。',404);
|
||||
|
||||
@@ -60,7 +60,7 @@ class RuntimeHealth {
|
||||
return {id:c.id,name:redact(c.name||'托管邮箱'),status,checkedAt,detail:redact(c.state?.message||'尚未检查 SMTP / IMAP。'),...this.remember('mail',c.id,{successAt:status==='healthy'?checkedAt:null,failureAt:status==='error'?checkedAt:null})};
|
||||
}));
|
||||
if(this.sources.execution)safe('execution','分类订单执行','#notification-execution',()=>{
|
||||
const data=this.sources.execution.snapshot(),names={liveTodo:'真实待办',pdfExport:'PDF 导出',automaticArchive:'归档校验'};
|
||||
const execution=this.sources.execution,data=typeof execution.healthSnapshot==='function'?execution.healthSnapshot():execution.snapshot(),names={liveTodo:'真实待办',pdfExport:'PDF 导出',automaticArchive:'归档校验'};
|
||||
const items=Object.entries(names).map(([id,name])=>({id,name,global:true,status:data.capabilities?.[id]===true?'healthy':'pending',detail:data.capabilities?.[id]===true?'实际检查已通过;各类别仍需现场核验。':'尚未通过实际接入检查,请在订单通知管理的订单执行查看阻塞原因。'}));
|
||||
for(const task of data.tasks||[]){const status=['blocked','failed'].includes(task.status)?'error':task.status==='unknown'?'unknown':['capturing','preparing','archiving','running','sending'].includes(task.status)?'running':['archived','sent','pending'].includes(task.status)?'healthy':'pending';
|
||||
items.push({id:task.id,owner:connections.find(c=>c.id===task.connectionId)?.owner,name:redact(task.processName||'订单执行任务'),status,checkedAt:timestamp(task.updatedAt),detail:redact(task.error||task.reason||task.blockedReason||'任务进度已持久保存,请在订单通知管理查看。'),...this.remember('execution',task.id,{successAt:status==='healthy'?task.updatedAt:null,failureAt:status==='error'?task.updatedAt:null})});}
|
||||
|
||||
@@ -25,11 +25,13 @@ async function readHistory(client,input={}){
|
||||
try{
|
||||
const uidValidity=String(client.mailbox.uidValidity);
|
||||
if(input.action==='search'){
|
||||
const found=await client.search(query,{uid:true}),uids=(found||[]).filter(Number.isSafeInteger).sort((a,b)=>b-a),messages=[];
|
||||
for(const uid of uids.slice(0,limit)){
|
||||
const info=await client.fetchOne(uid,{envelope:true,size:true},{uid:true});if(!info)continue;
|
||||
messages.push({uid,subject:info.envelope?.subject||'',date:info.envelope?.date?.toISOString()||null,to:addresses(info.envelope?.to),cc:addresses(info.envelope?.cc),size:info.size});
|
||||
}
|
||||
const found=await client.search(query,{uid:true}),uids=(found||[]).filter(uid=>Number.isSafeInteger(uid)&&uid>0).sort((a,b)=>b-a),selected=uids.slice(0,limit),envelopes=new Map();
|
||||
// FETCH emits mailbox sequence order; retain the selected UID order even when
|
||||
// messages disappear between SEARCH and FETCH. An empty set must never mean '*'.
|
||||
if(selected.length)for await(const info of client.fetch(selected.join(','),{uid:true,envelope:true,size:true},{uid:true}))if(selected.includes(info.uid))envelopes.set(info.uid,{...envelopes.get(info.uid),...info});
|
||||
const messages=selected.flatMap(uid=>{
|
||||
const info=envelopes.get(uid);return info?[{uid,subject:info.envelope?.subject||'',date:info.envelope?.date?.toISOString()||null,to:addresses(info.envelope?.to),cc:addresses(info.envelope?.cc),size:info.size}]:[];
|
||||
});
|
||||
return {folder:input.folder,uidValidity,messages,truncated:uids.length>limit};
|
||||
}
|
||||
if(!Number.isSafeInteger(input.uid)||input.uid<=0)fail('邮件标识无效。');
|
||||
|
||||
@@ -141,6 +141,17 @@ class OrderExecutionCoordinator{
|
||||
try{this.connection(task.connectionId,principal);return true;}
|
||||
catch{return false;}
|
||||
}
|
||||
healthSnapshot(){
|
||||
// Health consumes persisted progress, never captured fields or discovery views.
|
||||
const tasks=this.store.all('execution-tasks').map(task=>{
|
||||
const order=task.orderId&&this.store.get('orders',task.orderId);
|
||||
const activeStatus=['failed','unknown','blocked','capturing','archiving'].includes(task.status);
|
||||
return {id:task.id,connectionId:task.connectionId,processName:task.row?.processName,
|
||||
status:activeStatus?task.status:order?.status||task.status,updatedAt:task.updatedAt,
|
||||
error:task.error||order?.error||null,reason:task.reason,blockedReason:task.blockedReason};
|
||||
}).reverse();
|
||||
return {tasks,capabilities:clone(this.store.capabilities)};
|
||||
}
|
||||
snapshot(principal,{includeFieldEvidence=false}={}){
|
||||
const allowed=id=>!principal||require('../order-rules/access.cjs').canReadConnection(this.workspace,principal.user,id);
|
||||
const fields=this.store.fields();
|
||||
|
||||
@@ -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);}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use strict';
|
||||
const {secureBpmTransport}=require('../bpm/api.cjs');
|
||||
const {byteRange}=require('./files.cjs');
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
function payload(body,keys){if(!body||Object.keys(body).some(k=>!keys.includes(k)))fail('存储操作参数无效。');}
|
||||
async function storageApi({storage,workspace,user,url,route,method,body,request,response,reply,trustedProxy}){
|
||||
@@ -25,14 +26,13 @@ async function storageApi({storage,workspace,user,url,route,method,body,request,
|
||||
if(action==='archive'&&method==='POST'){payload(body,['jobId','directory']);const result=await storage.archive(id,body.jobId,body.directory??'',user.username);audit('PDF 归档完成',result.relativePath);reply(200,result);return true;}
|
||||
if(action==='preview-info'&&method==='GET'){reply(200,await storage.previewInfo(id,url.searchParams.get('path')||''));return true;}
|
||||
if((action==='file'||action==='content')&&method==='GET'){
|
||||
const preview=action==='content',file=await storage[preview?'readPreview':'readFile'](id,url.searchParams.get('path')||''),total=file.bytes.length;
|
||||
const preview=action==='content',range=request.headers.range,file=await storage[preview?'readPreview':'readFile'](id,url.searchParams.get('path')||'',range===undefined?{}:{range}),total=file.total??file.bytes.length;
|
||||
response.setHeader('Content-Type',preview?file.contentType:'application/octet-stream');response.setHeader('Content-Disposition',(preview?'inline':'attachment')+"; filename*=UTF-8''"+encodeURIComponent(file.filename));response.setHeader('Content-Security-Policy',"default-src 'none'; sandbox");response.setHeader('Cross-Origin-Resource-Policy','same-origin');response.setHeader('Accept-Ranges','bytes');
|
||||
let start=0,end=total-1,status=200;
|
||||
if(request.headers.range){const range=/^bytes=(\d*)-(\d*)$/.exec(request.headers.range);if(!range||(!range[1]&&!range[2])){response.setHeader('Content-Range','bytes */'+total);response.writeHead(416);response.end();return true;}
|
||||
if(range[1]){start=Number(range[1]);if(range[2])end=Math.min(Number(range[2]),end);}else start=Math.max(0,total-Number(range[2]));
|
||||
if(!Number.isSafeInteger(start)||!Number.isSafeInteger(end)||start>end||start>=total){response.setHeader('Content-Range','bytes */'+total);response.writeHead(416);response.end();return true;}status=206;response.setHeader('Content-Range',`bytes ${start}-${end}/${total}`);
|
||||
}
|
||||
const bytes=file.bytes.subarray(start,end+1);response.setHeader('Content-Length',bytes.length);response.writeHead(status);response.end(bytes);return true;
|
||||
const {start,end,status}=byteRange(range,total);
|
||||
if(file.total!==undefined&&(file.start!==start||file.end!==end||file.status!==status||file.bytes.length!==(status===416?0:end-start+1)))fail('存储分段响应无效。',502);
|
||||
if(status===416){response.setHeader('Content-Range','bytes */'+total);response.writeHead(416);response.end();return true;}
|
||||
if(status===206)response.setHeader('Content-Range',`bytes ${start}-${end}/${total}`);
|
||||
const bytes=file.total===undefined?file.bytes.subarray(start,end+1):file.bytes;response.setHeader('Content-Length',bytes.length);response.writeHead(status);response.end(bytes);return true;
|
||||
}
|
||||
}
|
||||
fail('没有找到此存储操作。',404);
|
||||
|
||||
@@ -15,6 +15,22 @@ function segments(relative=''){
|
||||
}
|
||||
function inside(root,file){const rel=path.relative(root,file);return !path.isAbsolute(rel)&&rel!=='..'&&!rel.startsWith('..'+path.sep);}
|
||||
function digest(bytes){return crypto.createHash('sha256').update(bytes).digest('hex');}
|
||||
function byteRange(value,total){
|
||||
if(!Number.isSafeInteger(total)||total<0)throw fail('存储文件大小无效。',502);
|
||||
const invalid={status:416,start:0,end:-1};
|
||||
if(value===undefined)return {status:200,start:0,end:total-1};
|
||||
const match=typeof value==='string'&&/^bytes=(\d*)-(\d*)$/.exec(value);if(!match||!total||(!match[1]&&!match[2]))return invalid;
|
||||
const first=match[1]?Number(match[1]):null,last=match[2]?Number(match[2]):null;
|
||||
if(first!==null&&!Number.isSafeInteger(first)||last!==null&&!Number.isSafeInteger(last))return invalid;
|
||||
const start=first===null?Math.max(0,total-last):first,end=first===null||last===null?total-1:Math.min(last,total-1);
|
||||
return start<0||start>end||start>=total?invalid:{status:206,start,end};
|
||||
}
|
||||
async function readExact(handle,start,length){
|
||||
const buffer=Buffer.alloc(length);let offset=0;
|
||||
while(offset<length){const result=await handle.read(buffer,offset,length-offset,start+offset);if(!result.bytesRead)throw fail('文件正在更新,请稍后重试。',409);offset+=result.bytesRead;}
|
||||
return buffer;
|
||||
}
|
||||
const unchanged=(a,b)=>['dev','ino','size','mtimeNs','ctimeNs'].every(key=>a[key]===b[key]);
|
||||
async function pdf(file){const info=await fs.stat(file);if(!info.isFile()||info.size>MAX_FILE)throw fail('PDF 必须为不超过 64 MiB 的文件。');const bytes=await fs.readFile(file);if(bytes.length>MAX_FILE||bytes.subarray(0,5).toString()!=='%PDF-')throw fail('文件不是有效的 PDF。');return bytes;}
|
||||
class FileArea{
|
||||
constructor(root,{boundary=root}={}){this.root=path.resolve(root);this.boundary=path.resolve(boundary);if(!inside(this.boundary,this.root))throw fail('归档根目录超出共享目录。');}
|
||||
@@ -45,16 +61,26 @@ class FileArea{
|
||||
}
|
||||
async readPdf(relative){if(path.extname(relative).toLowerCase()!=='.pdf')throw fail('仅支持下载归档 PDF。');const file=await this.resolve(relative);return {bytes:await pdf(file),filename:path.basename(file)};}
|
||||
async previewInfo(relative){const file=await this.resolve(relative),stat=await fs.stat(file);if(!stat.isFile())throw fail('请选择文件进行预览。');return describePreview(path.basename(file),stat.size);}
|
||||
async readFile(relative,limit=MAX_FILE){
|
||||
async readFile(relative,limit=MAX_FILE,{range,previewPdf=false}={}){
|
||||
const file=await this.resolve(relative),handle=await fs.open(file,'r');
|
||||
try{const stat=await handle.stat();if(!stat.isFile())throw fail('请选择要读取的文件。');if(stat.size>limit)throw fail('文件超过工作台读取上限。',413);
|
||||
const buffer=Buffer.alloc(stat.size+1);let length=0;
|
||||
while(length<buffer.length){const result=await handle.read(buffer,length,buffer.length-length,null);if(!result.bytesRead)break;length+=result.bytesRead;}
|
||||
if(length>stat.size)throw fail('文件正在更新,请稍后重试。',409);
|
||||
return {filename:path.basename(file),bytes:buffer.subarray(0,length)};
|
||||
try{const stat=await handle.stat({bigint:true}),total=Number(stat.size),filename=path.basename(file);if(!stat.isFile())throw fail('请选择要读取的文件。');if(!Number.isSafeInteger(total)||total>limit)throw fail('文件超过工作台读取上限。',413);
|
||||
if(previewPdf){const info=describePreview(filename,total);if(info.kind!=='pdf')throw fail('此格式不支持 PDF 分段预览。',415);await validatePreview(info,await readExact(handle,0,Math.min(5,total)));}
|
||||
const selected=byteRange(range,total),bytes=selected.status===416?Buffer.alloc(0):await readExact(handle,selected.start,selected.end-selected.start+1);
|
||||
// Validate both the opened file and its path after reading. Ranges and PDF
|
||||
// headers use this same handle, and no successful short/growing read escapes.
|
||||
const after=await handle.stat({bigint:true});await this.resolve(relative);const current=await fs.lstat(file,{bigint:true});
|
||||
if(current.isSymbolicLink()||!unchanged(stat,after)||!unchanged(stat,current))throw fail('文件正在更新,请稍后重试。',409);
|
||||
return {filename,bytes,total,...selected};
|
||||
}finally{await handle.close();}
|
||||
}
|
||||
async readPreview(relative){const info=await this.previewInfo(relative);if(!info.canPreview)throw fail(info.reason,info.kind==='unsupported'?415:413);const file=await this.readFile(relative,info.limit);return {...info,bytes:await validatePreview({...info,bytes:file.bytes.length,canPreview:file.bytes.length<=info.limit},file.bytes)};}
|
||||
async readPreview(relative,{range}={}){
|
||||
if(range!==undefined&&path.extname(relative).toLowerCase()==='.pdf'){
|
||||
const file=await this.readFile(relative,MAX_FILE,{range,previewPdf:true});return {...describePreview(file.filename,file.total),...file};
|
||||
}
|
||||
const info=await this.previewInfo(relative);if(!info.canPreview)throw fail(info.reason,info.kind==='unsupported'?415:413);
|
||||
const file=await this.readFile(relative,info.limit),bytes=await validatePreview({...info,bytes:file.bytes.length,canPreview:file.bytes.length<=info.limit},file.bytes),selected=byteRange(range,bytes.length);
|
||||
return {...info,total:bytes.length,...selected,bytes:selected.status===416?Buffer.alloc(0):bytes.subarray(selected.start,selected.end+1)};
|
||||
}
|
||||
async archive(source,filename,relative=''){
|
||||
if(segments(filename).length!==1||path.extname(filename).toLowerCase()!=='.pdf')throw fail('归档文件名必须为 PDF 文件名。');
|
||||
const bytes=await pdf(source),sha256=digest(bytes),directory=await this.resolve(relative,true);
|
||||
@@ -79,4 +105,4 @@ class SmbClient{
|
||||
async browse(server,options){return require('./smb-probe.cjs').probe(server,options);}
|
||||
async area(server){if(server.authMode!=='windows')await native.connect(server);const boundary=path.win32.join('\\\\'+server.host,server.share),root=path.win32.join(boundary,...segments(server.directory));return new FileArea(root,{boundary});}
|
||||
}
|
||||
module.exports={FileArea,SmbClient,segments,inside,MAX_FILE};
|
||||
module.exports={FileArea,SmbClient,segments,inside,MAX_FILE,byteRange};
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs/promises');const path=require('node:path');
|
||||
const {SmbClient,segments,inside}=require('./files.cjs');
|
||||
const {SmbClient,segments,inside,MAX_FILE}=require('./files.cjs');
|
||||
const {orderFolder}=require('./order.cjs');
|
||||
const fail=(message,status=400)=>Object.assign(new Error(message),{status});
|
||||
const safe=e=>e.status?e:fail(({ENOENT:'找不到文件或归档目录,请检查路径。',EACCES:'没有共享目录访问权限。',EPERM:'没有共享目录操作权限。',ENOSPC:'存储服务器空间不足。',ENOTDIR:'指定路径不是目录。'})[e.code]||'存储操作未完成,请检查服务器与网络。',502);
|
||||
@@ -71,8 +71,8 @@ class StorageService{
|
||||
mkdir(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'mkdir',[relative],signal));}
|
||||
readPdf(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'readPdf',[relative],signal));}
|
||||
previewInfo(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'previewInfo',[relative],signal));}
|
||||
readPreview(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'readPreview',[relative],signal));}
|
||||
readFile(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'readFile',[relative],signal));}
|
||||
readPreview(id,relative,options={}){return this.run(id,async (server,signal)=>this.operation(server,'readPreview',[relative,options],signal));}
|
||||
readFile(id,relative,options={}){return this.run(id,async (server,signal)=>this.operation(server,'readFile',[relative,MAX_FILE,options],signal));}
|
||||
archive(id,jobId,directory='',actor='自动归档'){
|
||||
return this.run(id,async (server,signal)=>{
|
||||
segments(directory);if(typeof jobId!=='string'||!jobId||jobId.length>200)throw fail('请选择已完成的 PDF 导出任务。');
|
||||
|
||||
@@ -17,6 +17,13 @@ function validate(operation,value){
|
||||
visit(value);
|
||||
if(!value||typeof value!=='object'||Array.isArray(value))throw fail('存储响应无效。',502);
|
||||
if(['readPdf','readPreview','readFile'].includes(operation)&&!Buffer.isBuffer(value.bytes))throw fail('存储文件响应无效。',502);
|
||||
if(['readPreview','readFile'].includes(operation)&&value.total!==undefined){
|
||||
const {total,start,end,status,bytes}=value,valid=Number.isSafeInteger(total)&&total>=0&&total<=MAX_FILE&&Number.isSafeInteger(start)&&Number.isSafeInteger(end);
|
||||
const layout=status===416?start===0&&end===-1&&bytes.length===0:
|
||||
status===200?start===0&&end===total-1&&bytes.length===total:
|
||||
status===206&&total>0&&start>=0&&start<=end&&end<total&&bytes.length===end-start+1;
|
||||
if(!valid||!layout)throw fail('存储分段响应无效。',502);
|
||||
}
|
||||
if(operation==='list'&&(!Array.isArray(value.entries)||value.entries.length>500||typeof value.path!=='string'||typeof value.truncated!=='boolean'||value.entries.some(e=>!e||typeof e.name!=='string'||!['directory','file','blocked'].includes(e.type))))throw fail('存储目录响应无效。',502);
|
||||
if(operation==='check'&&(value.readable!==true||value.writable!==true))throw fail('存储检查响应无效。',502);
|
||||
if(operation==='archive'&&(!Number.isSafeInteger(value.bytes)||value.bytes<0||value.bytes>MAX_FILE||!/^[a-f0-9]{64}$/.test(value.sha256)||typeof value.filename!=='string'||typeof value.relativePath!=='string'))throw fail('归档响应无效。',502);
|
||||
|
||||
@@ -66,7 +66,8 @@ async function readRelease(response){
|
||||
}
|
||||
function createUpdateChecker({currentVersion,fetchImpl=globalThis.fetch,apiUrl=RELEASES_API_URL,repositoryUrl=REPOSITORY_URL,timeoutMs=5000}={}){
|
||||
if(!versionParts(currentVersion))throw new Error('当前版本必须是 x.y.z 格式。');
|
||||
return async function checkForUpdate(){
|
||||
let inFlight=null;
|
||||
async function readUpdate(){
|
||||
const base={currentVersion,latest:null};
|
||||
if(typeof fetchImpl!=='function')return {...base,status:'unavailable'};
|
||||
const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),timeoutMs);
|
||||
@@ -76,6 +77,11 @@ function createUpdateChecker({currentVersion,fetchImpl=globalThis.fetch,apiUrl=R
|
||||
return parseRelease(await readRelease(response),currentVersion,{repositoryUrl});
|
||||
}catch{return {...base,status:'unavailable'};}
|
||||
finally{clearTimeout(timer);}
|
||||
}
|
||||
return async function checkForUpdate(){
|
||||
// Share only work still in progress; a later manual check always revalidates.
|
||||
if(!inFlight)inFlight=readUpdate().finally(()=>{inFlight=null;});
|
||||
return structuredClone(await inFlight);
|
||||
};
|
||||
}
|
||||
module.exports={REPOSITORY_URL,RELEASES_API_URL,compareVersions,parseRelease,createUpdateChecker};
|
||||
Reference in new issue
Block a user