Files
order-notification-automation/src/service-supervisor.cjs
T

90 lines
8.8 KiB
JavaScript

'use strict';
const fs=require('node:fs'),path=require('node:path'),net=require('node:net'),crypto=require('node:crypto'),{spawn,execFile}=require('node:child_process'),{promisify}=require('node:util');
const {SupervisorStore}=require('./supervisor-store.cjs'),{controlAddress}=require('./service-control.cjs'),{checkPing,sameToken}=require('./service-ping.cjs');
const execFileAsync=promisify(execFile),DEFAULTS={intervalMs:10000,pingTimeoutMs:5000,startupGraceMs:120000,failureThreshold:4,stopGraceMs:15000,backoffMs:[2000,5000,10000,30000,60000],windowMs:900000,maxRestarts:8,cooldownMs:300000};
function restartPlan({failures=0,recent=0,...options}={}){const t={...DEFAULTS,...options},cooldown=recent>=t.maxRestarts;return {cooldown,delayMs:cooldown?t.cooldownMs:t.backoffMs[Math.min(failures,t.backoffMs.length-1)]};}
async function portsAvailable(ports){for(const port of ports){const server=net.createServer();await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(port,'127.0.0.1',resolve);});await new Promise(r=>server.close(r));}}
class ServiceSupervisor {
constructor({stateDir,entry=path.resolve(__dirname,'server.cjs'),ports=[18765,18766],env={},timing={}}){Object.assign(this,{stateDir:path.resolve(stateDir),entry:path.resolve(entry),ports,env});this.timing={...DEFAULTS,...timing};this.state={};this.restarts=[];this.failures=0;this.stopping=false;this.started=false;}
snapshot(){return {...this.state};}
update(patch){Object.assign(this.state,patch,{updatedAt:new Date().toISOString()});this.store.set('state',this.state);}
async start(){
this.store=new SupervisorStore(this.stateDir);this.server=net.createServer(socket=>this.control(socket));
try{
const address=controlAddress(this.stateDir);
if(process.platform!=='win32'&&fs.existsSync(address)){
const alive=await new Promise(resolve=>{const s=net.createConnection(address);s.once('connect',()=>{s.destroy();resolve(true);});s.once('error',()=>resolve(false));});if(!alive&&fs.statSync(address).isSocket())fs.unlinkSync(address);
}
await new Promise((resolve,reject)=>{this.server.once('error',reject);this.server.listen(address,resolve);});this.started=true;
const previous=this.store.get('state');this.state={supervisorPid:process.pid,startedAt:new Date().toISOString(),status:'starting',restartCount:previous?.restartCount||0,childPid:null,heartbeatAt:null,reason:'initial_start'};
this.store.event('guard_started');this.update({});await portsAvailable(this.ports);await this.launch();
this.timer=setInterval(()=>this.tick().catch(()=>{this.store?.event('monitor_error');}),this.timing.intervalMs);
this.logTimer=setInterval(()=>{try{this.rotateLog();}catch{}},30000);
return this;
}catch(e){if(this.started){this.update({status:'stopped',reason:e.code==='EADDRINUSE'?'port_conflict':'startup_failed'});await new Promise(r=>this.server.close(r));}this.store.close();this.store=null;throw e;}
}
control(socket){
let raw='',handled=false;socket.setTimeout(5000,()=>socket.destroy());socket.on('error',()=>{});
socket.on('data',chunk=>{if(handled)return;raw+=chunk.toString('utf8');if(raw.length>4096){handled=true;socket.end(JSON.stringify({status:413,error:'请求过大。'})+'\n');return;}if(!raw.includes('\n'))return;handled=true;
let request;try{request=JSON.parse(raw.split('\n')[0]);if(!request||typeof request!=='object'||Array.isArray(request))throw Error('invalid object');}catch{socket.end('{"status":400,"error":"请求无效。"}\n');return;}
if(!sameToken(request.token,this.store.token)){socket.end('{"status":403,"error":"控制令牌无效。"}\n');return;}
if(!['status','stop','restart'].includes(request.action)||Object.keys(request).some(k=>!['action','token'].includes(k))){socket.end('{"status":400,"error":"操作无效。"}\n');return;}
socket.end(JSON.stringify({state:this.snapshot(),ok:true})+'\n');
if(request.action==='stop')setImmediate(()=>this.stop().catch(()=>{}));
if(request.action==='restart')setImmediate(()=>this.restart().catch(()=>{}));
});
}
async launch(){
if(this.stopping)return;this.misses=0;this.spawnedAt=Date.now();const instanceId=crypto.randomUUID(),heartbeatToken=crypto.randomBytes(32).toString('hex'),logFile=path.join(this.store.dir,'service.log');this.rotateLog();
const fd=fs.openSync(logFile,'a',0o600);let child;
try{child=spawn(process.execPath,[this.entry],{cwd:path.resolve(__dirname,'..'),env:{...process.env,...this.env,ORDER_SUPERVISOR_TOKEN:heartbeatToken,ORDER_SUPERVISOR_INSTANCE:instanceId},windowsHide:true,shell:false,stdio:['ignore',fd,fd,'ipc']});}finally{fs.closeSync(fd);}
this.child=child;this.instanceId=instanceId;this.heartbeatToken=heartbeatToken;this.childClosed=new Promise(resolve=>{this.resolveClosed=resolve;});
this.update({status:'starting',childPid:child.pid||null,childInstanceId:instanceId,childStartedAt:new Date().toISOString(),heartbeatAt:null,nextRestartAt:null});
child.on('error',()=>{this.store?.event('spawn_failed');});
child.once('close',(code,signal)=>{const resolve=this.resolveClosed;resolve?.();if(this.child!==child)return;this.child=null;
if(this.stopping||this.manualRestart)return;
this.store.event('child_exit',{code,signal:signal||null});this.update({childPid:null,lastExitAt:new Date().toISOString(),lastExitCode:code,reason:this.exitReason||'unexpected_exit'});this.exitReason=null;this.scheduleRestart();
});
}
scheduleRestart(){
if(this.stopping)return;clearTimeout(this.restartTimer);const now=Date.now();this.restarts=this.restarts.filter(t=>now-t<this.timing.windowMs);
const plan=restartPlan({...this.timing,failures:this.failures++,recent:this.restarts.length});
this.update({status:plan.cooldown?'cooldown':'backoff',nextRestartAt:new Date(now+plan.delayMs).toISOString()});this.store.event(plan.cooldown?'cooldown':'restarting',{delayMs:plan.delayMs,reason:this.state.reason});
this.restartTimer=setTimeout(()=>{if(this.stopping)return;this.restarts.push(Date.now());this.update({restartCount:this.state.restartCount+1});this.launch().catch(()=>{this.update({reason:'spawn_failed'});this.scheduleRestart();});},plan.delayMs);
}
async tick(){
if(this.stopping||this.ticking)return;this.ticking=true;
try{
if(!this.child){this.update({});return;}
const child=this.child,instanceId=this.instanceId,token=this.heartbeatToken;
const results=await Promise.allSettled(this.ports.map(port=>checkPing(port,{token,instanceId,timeout:this.timing.pingTimeoutMs})));
if(this.stopping||this.child!==child||this.manualRestart)return;
if(results.every(r=>r.status==='fulfilled')){this.misses=0;if(Date.now()-this.spawnedAt>300000)this.failures=0;this.update({status:'running',heartbeatAt:new Date().toISOString(),reason:'healthy'});return;}
this.update({});if(this.state.status==='starting'&&Date.now()-this.spawnedAt<this.timing.startupGraceMs)return;
if(++this.misses<this.timing.failureThreshold)return;
this.exitReason='health_timeout';this.store.event('unresponsive');await this.endChild(false);
}finally{this.ticking=false;}
}
async endChild(graceful=true){
const child=this.child;if(!child)return;const closed=this.childClosed;
if(graceful&&child.connected)try{child.send('order:shutdown');}catch{}
if(graceful){let timer;await Promise.race([closed,new Promise(r=>{timer=setTimeout(r,this.timing.stopGraceMs);})]);clearTimeout(timer);if(this.child!==child)return;}
if(process.platform==='win32')await execFileAsync('taskkill.exe',['/PID',String(child.pid),'/T','/F'],{windowsHide:true,timeout:7000}).catch(()=>{try{child.kill('SIGKILL');}catch{}});else try{child.kill('SIGKILL');}catch{}
let timer;await Promise.race([closed,new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error('无法确认业务进程已停止。')),8000);})]).finally(()=>clearTimeout(timer));
}
async restart(){
if(this.stopping||this.manualRestart)return;this.manualRestart=true;clearTimeout(this.restartTimer);this.store.event('manual_restart');
try{await this.endChild();this.child=null;this.update({restartCount:this.state.restartCount+1,reason:'manual_restart'});this.failures=0;this.restarts=[];await this.launch();}finally{this.manualRestart=false;}
}
stop(){return this.stopPromise||=(async()=>{
this.stopping=true;clearInterval(this.timer);clearInterval(this.logTimer);clearTimeout(this.restartTimer);if(!this.started)return;
this.update({status:'stopping',reason:'manual_stop'});await this.endChild();while(this.ticking)await new Promise(r=>setTimeout(r,10));
this.update({status:'stopped',childPid:null,nextRestartAt:null});this.store.event('guard_stopped');await new Promise(r=>this.server.close(r));this.store.close();this.store=null;
})();}
rotateLog(){
const file=path.join(this.store.dir,'service.log');if(!fs.existsSync(file)||fs.statSync(file).size<5*1024*1024)return;
for(let i=2;i>=1;i--)if(fs.existsSync(file+'.'+i))fs.copyFileSync(file+'.'+i,file+'.'+(i+1));fs.copyFileSync(file,file+'.1');fs.truncateSync(file,0);
}
}
module.exports={ServiceSupervisor,restartPlan};