fix(storage): bound saved SMB operations in cancellable workers
This commit is contained in:
1 parent
5fe42b478c
commit
0951dd451d
6 files changed
+169
-14
No files matched your search
@@ -74,7 +74,10 @@ class FileArea{
|
||||
}
|
||||
}
|
||||
class SmbClient{
|
||||
constructor(options={}){this.options=options;}
|
||||
execute(server,operation,args,options={}){return require('./smb-operation.cjs').execute(server,operation,args,{...this.options,...options});}
|
||||
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};
|
||||
|
||||
@@ -5,7 +5,7 @@ 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);
|
||||
class StorageService{
|
||||
constructor({store,jobs,outputDir,client=new SmbClient(),checkTimeoutMs=15000}){this.store=store;this.jobs=jobs;this.outputDir=outputDir;this.client=client;this.running=new Map();this.pendingChecks=new Set();this.probeControllers=new Set();this.checkTimeoutMs=checkTimeoutMs;this.stopped=false;}
|
||||
constructor({store,jobs,outputDir,client=new SmbClient(),checkTimeoutMs=15000,operationTimeoutMs=checkTimeoutMs}){this.store=store;this.jobs=jobs;this.outputDir=outputDir;this.client=client;this.running=new Map();this.pendingChecks=new Set();this.probeControllers=new Set();this.checkTimeoutMs=checkTimeoutMs;this.stopped=false;this.operationTimeoutMs=operationTimeoutMs;this.operationControllers=new Set();}
|
||||
busy(id){return this.running.has(id);}
|
||||
async saveServer(input){
|
||||
if(this.stopped)throw fail('存储服务正在停止。',503);
|
||||
@@ -41,21 +41,40 @@ class StorageService{
|
||||
return {...result,readable:true,checkedAt:new Date().toISOString(),message:'连接成功,目标目录可读取。'};
|
||||
}
|
||||
saveSettings(input){if(input?.enabled){const server=this.store.publicServer(input.serverId);if(!server.enabled||!server.state.readable||!server.state.writable)throw fail('请先启用服务器并检查读写成功。',409);}return this.store.saveSettings(input);}
|
||||
async operation(server,method,args,signal){
|
||||
if(this.client.execute)return this.client.execute(server,method,args,{signal,timeoutMs:this.operationTimeoutMs});
|
||||
// Local/injected clients must cooperate with cancellation. Production UNC I/O
|
||||
// always goes through execute(), which waits for worker exit before rejecting.
|
||||
let cancel;
|
||||
try{return await Promise.race([
|
||||
new Promise((resolve,reject)=>{cancel=()=>reject(signal.reason);if(signal.aborted)cancel();else signal.addEventListener('abort',cancel,{once:true});}),
|
||||
(async()=>{if(signal.aborted)throw signal.reason;const area=await this.client.area(server,{signal});return area[method](...args);})()
|
||||
]);}finally{signal.removeEventListener('abort',cancel);}
|
||||
}
|
||||
run(id,work){
|
||||
if(this.stopped)return Promise.reject(fail('存储服务正在停止。',503));
|
||||
const previous=this.running.get(id)||Promise.resolve();
|
||||
const task=previous.catch(()=>{}).then(async()=>{const server=this.store.secret(id);if(!server.enabled)throw fail('此存储服务器已停用。',409);try{return await work(server);}catch(e){throw safe(e);}});
|
||||
this.running.set(id,task);task.finally(()=>{if(this.running.get(id)===task)this.running.delete(id);}).catch(()=>{});return task;
|
||||
const previous=this.running.get(id)||Promise.resolve(),controller=new AbortController();
|
||||
this.operationControllers.add(controller);let started=false,rejectQueued;
|
||||
const queued=new Promise((resolve,reject)=>{rejectQueued=reject;});
|
||||
const cancel=()=>{if(!started)rejectQueued(controller.signal.reason);};
|
||||
controller.signal.addEventListener('abort',cancel);
|
||||
const timer=setTimeout(()=>controller.abort(fail('存储操作超时,请检查服务器与网络。',504)),this.operationTimeoutMs);
|
||||
const task=previous.catch(()=>{}).then(async()=>{
|
||||
started=true;if(controller.signal.aborted)throw controller.signal.reason;
|
||||
const server=this.store.secret(id);if(!server.enabled)throw fail('此存储服务器已停用。',409);
|
||||
try{return await work(server,controller.signal);}catch(e){throw safe(e);}
|
||||
}).finally(()=>{clearTimeout(timer);controller.signal.removeEventListener('abort',cancel);this.operationControllers.delete(controller);if(this.running.get(id)===task)this.running.delete(id);});
|
||||
this.running.set(id,task);return Promise.race([task,queued]);
|
||||
}
|
||||
check(id){return this.run(id,async server=>{try{const area=await this.client.area(server),result=await area.check();const state={...result,checkedAt:new Date().toISOString(),message:'共享目录读写正常'};this.store.setState(id,server.version,state);return this.store.publicServer(id);}catch(e){const error=safe(e);this.store.setState(id,server.version,{readable:false,writable:false,checkedAt:new Date().toISOString(),message:error.message});throw error;}});}
|
||||
list(id,relative){return this.run(id,async server=>(await this.client.area(server)).list(relative));}
|
||||
mkdir(id,relative){return this.run(id,async server=>(await this.client.area(server)).mkdir(relative));}
|
||||
readPdf(id,relative){return this.run(id,async server=>(await this.client.area(server)).readPdf(relative));}
|
||||
previewInfo(id,relative){return this.run(id,async server=>(await this.client.area(server)).previewInfo(relative));}
|
||||
readPreview(id,relative){return this.run(id,async server=>(await this.client.area(server)).readPreview(relative));}
|
||||
readFile(id,relative){return this.run(id,async server=>(await this.client.area(server)).readFile(relative));}
|
||||
check(id){return this.run(id,async (server,signal)=>{try{const result=await this.operation(server,'check',[],signal);const state={...result,checkedAt:new Date().toISOString(),message:'共享目录读写正常'};this.store.setState(id,server.version,state);return this.store.publicServer(id);}catch(e){const error=safe(e);this.store.setState(id,server.version,{readable:false,writable:false,checkedAt:new Date().toISOString(),message:error.message});throw error;}});}
|
||||
list(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'list',[relative],signal));}
|
||||
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));}
|
||||
archive(id,jobId,directory='',actor='自动归档'){
|
||||
return this.run(id,async server=>{
|
||||
return this.run(id,async (server,signal)=>{
|
||||
segments(directory);if(typeof jobId!=='string'||!jobId||jobId.length>200)throw fail('请选择已完成的 PDF 导出任务。');
|
||||
const job=this.jobs.jobs().find(j=>j.jobId===jobId);if(!job||job.status!=='success'||typeof job.path!=='string')throw fail('请选择已完成且存在的 PDF。');
|
||||
const record=this.store.beginArchive(id,jobId,actor,directory);
|
||||
@@ -64,13 +83,14 @@ class StorageService{
|
||||
if(!inside(root,file)||file===root||path.extname(file).toLowerCase()!=='.pdf')throw fail('PDF 不在本工具输出目录内。');
|
||||
const grouping=orderFolder(job),base=segments(directory),current=base.at(-1)||segments(server.directory).at(-1);
|
||||
const target=(current===grouping.orderFolder?base:[...base,grouping.orderFolder]).join('/');segments(target);
|
||||
const area=await this.client.area(server),result=await area.archive(file,path.basename(file),target);
|
||||
const result=await this.operation(server,'archive',[file,path.basename(file),target],signal);
|
||||
return this.store.finishArchive(record.id,'success',{...result,...grouping,baseDirectory:directory,directory:target,serverName:server.name});
|
||||
}
|
||||
catch(e){const error=safe(e);this.store.finishArchive(record.id,'error',{error:error.message,serverName:server.name});throw error;}
|
||||
});
|
||||
}
|
||||
async automatic(job){const settings=this.store.settings();if(!settings.enabled||job.status!=='success'||!job.createdAt||job.createdAt<settings.since)return null;return this.archive(settings.serverId,job.jobId,'','自动归档');}
|
||||
async stop(){this.stopped=true;for(const controller of this.probeControllers)controller.abort(fail('存储服务正在停止。',503));await Promise.allSettled([...this.running.values(),...this.pendingChecks]);}
|
||||
async stop(){this.stopped=true;for(const controller of this.operationControllers)controller.abort(fail('存储服务正在停止。',503));for(const controller of this.probeControllers)controller.abort(fail('存储服务正在停止。',503));await Promise.allSettled([...this.running.values(),...this.pendingChecks]);}
|
||||
}
|
||||
module.exports={StorageService};
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
const {SmbClient}=require('./files.cjs');
|
||||
const {validate}=require('./smb-operation.cjs');
|
||||
process.once('message',async ({server,operation,args})=>{
|
||||
try{
|
||||
if(!['check','list','mkdir','readPdf','previewInfo','readPreview','readFile','archive'].includes(operation)||!Array.isArray(args))throw new Error('Invalid operation');
|
||||
const area=await new SmbClient().area(server),value=validate(operation,await area[operation](...args));
|
||||
process.send({ok:true,value},()=>process.exit(0));
|
||||
}catch(error){process.send({ok:false,status:error.status||502},()=>process.exit(0));}
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
'use strict';
|
||||
const {fork,spawn}=require('node:child_process');
|
||||
const path=require('node:path');
|
||||
const MAX_FILE=64*1024*1024,MAX_META=512*1024;
|
||||
const operations=new Set(['check','list','mkdir','readPdf','previewInfo','readPreview','readFile','archive']);
|
||||
const fail=(message,status)=>Object.assign(new Error(message),{status});
|
||||
function validate(operation,value){
|
||||
let binary=0,metadata=0,nodes=0;
|
||||
function visit(v,depth=0){
|
||||
if(++nodes>10000||depth>20)throw fail('存储响应无效。',502);
|
||||
if(Buffer.isBuffer(v)){binary+=v.length;if(binary>MAX_FILE)throw fail('文件超过工作台读取上限。',413);return;}
|
||||
if(v===null||typeof v==='boolean'||typeof v==='number'){if(typeof v==='number'&&!Number.isFinite(v))throw fail('存储响应无效。',502);return;}
|
||||
if(typeof v==='string'){metadata+=Buffer.byteLength(v);if(metadata>MAX_META)throw fail('存储响应内容过多。',413);return;}
|
||||
if(typeof v!=='object'||Object.getPrototypeOf(v)!==Object.prototype&&!Array.isArray(v))throw fail('存储响应无效。',502);
|
||||
for(const [key,item] of Object.entries(v)){metadata+=Buffer.byteLength(key);if(metadata>MAX_META)throw fail('存储响应内容过多。',413);visit(item,depth+1);}
|
||||
}
|
||||
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(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);
|
||||
return value;
|
||||
}
|
||||
function execute(server,operation,args=[],{signal,timeoutMs=15000,deadline,workerPath=path.join(__dirname,'smb-operation-worker.cjs')}={}){
|
||||
if(!operations.has(operation))return Promise.reject(fail('存储操作无效。',400));
|
||||
if(signal?.aborted)return Promise.reject(signal.reason?.status?signal.reason:fail('已取消存储操作。',499));
|
||||
const remaining=deadline===undefined?timeoutMs:Math.min(timeoutMs,deadline-Date.now());
|
||||
if(!Number.isFinite(remaining)||remaining<=0)return Promise.reject(fail('存储操作超时。',504));
|
||||
return new Promise((resolve,reject)=>{
|
||||
// Credentials travel only on the private IPC channel, never argv/stdout/stderr.
|
||||
const child=fork(workerPath,[],{windowsHide:true,serialization:'advanced',detached:process.platform!=='win32',stdio:['ignore','ignore','ignore','ipc']});
|
||||
let response,error,received=false,closed=false,terminating=false;
|
||||
const kill=()=>{if(closed)return;if(process.platform==='win32'){
|
||||
const killer=spawn('taskkill.exe',['/PID',String(child.pid),'/T','/F'],{windowsHide:true,stdio:'ignore',timeout:1500});
|
||||
killer.once('error',()=>child.kill('SIGKILL'));killer.once('exit',code=>{if(code!==0&&!closed)child.kill('SIGKILL');});
|
||||
}else{try{process.kill(-child.pid,'SIGKILL');}catch{child.kill('SIGKILL');}}};
|
||||
const terminate=e=>{if(terminating)return;terminating=true;error ||= e;kill();};
|
||||
const cancel=()=>terminate(signal.reason?.status?signal.reason:fail('已取消存储操作。',499));
|
||||
const timer=setTimeout(()=>terminate(fail('存储操作超时,请检查服务器与网络。',504)),remaining);
|
||||
signal?.addEventListener('abort',cancel,{once:true});
|
||||
child.on('message',message=>{
|
||||
if(error)return;
|
||||
if(received)return terminate(fail('存储响应无效。',502));received=true;
|
||||
try{if(!message||typeof message.ok!=='boolean')throw fail('存储响应无效。',502);
|
||||
if(message.ok)response=validate(operation,message.value);
|
||||
else error=fail('存储操作未完成,请检查路径、权限或服务器状态。',[400,403,404,409,413,415,499,502,503,504].includes(message.status)?message.status:502);
|
||||
}catch(e){terminate(e);}
|
||||
});
|
||||
child.on('error',()=>{error ||= fail('无法启动存储工作进程。',503);});
|
||||
child.once('close',(code)=>{closed=true;clearTimeout(timer);signal?.removeEventListener('abort',cancel);if(error)reject(error);else if(code!==0||!received)reject(fail('存储工作进程未正常完成。',502));else resolve(response);});
|
||||
child.send({server,operation,args},e=>{if(e)terminate(fail('无法发送存储操作。',503));});
|
||||
if(signal?.aborted)cancel();
|
||||
});
|
||||
}
|
||||
module.exports={execute,validate};
|
||||
Reference in new issue
Block a user