fix: acknowledge fresh supervisor restart before CLI polling
This commit is contained in:
1 parent
a6b8b53b8d
commit
098fec1007
2 files changed
+18
-2
No files matched your search
@@ -29,9 +29,11 @@ class ServiceSupervisor {
|
||||
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;}
|
||||
// restart() publishes acceptance synchronously before its first await, so
|
||||
// this reply and subsequent polls cannot expose the previous failed attempt.
|
||||
if(request.action==='restart')this.restart().catch(()=>{});
|
||||
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(){
|
||||
@@ -76,7 +78,7 @@ class ServiceSupervisor {
|
||||
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');
|
||||
if(this.stopping||this.manualRestart)return;this.manualRestart=true;clearTimeout(this.restartTimer);this.update({status:'starting',reason:'manual_restart',nextRestartAt:null});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();}
|
||||
catch(cause){this.update({status:'failed',childPid:this.child?.pid||null,nextRestartAt:null,reason:cause.code==='EADDRINUSE'?'port_conflict':cause.code==='EINVALIDPORTS'?'config_invalid':'restart_failed'});this.store.event('restart_failed',{reason:this.state.reason});throw cause;}
|
||||
finally{this.manualRestart=false;}
|
||||
|
||||
@@ -2,6 +2,20 @@
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),net=require('node:net');
|
||||
async function port(){const s=net.createServer();await new Promise(r=>s.listen(0,'127.0.0.1',r));const p=s.address().port;await new Promise(r=>s.close(r));return p;}
|
||||
async function until(fn,timeout=15000){const end=Date.now()+timeout;while(Date.now()<end){if(await fn())return;await new Promise(r=>setTimeout(r,30));}assert.fail('condition did not become true');}
|
||||
test('real CLI retry acknowledges a fresh attempt before awaiting delayed port configuration', {timeout:20000},async t=>{
|
||||
const {ServiceSupervisor}=require('../../src/platform/service/supervisor.cjs'),root=await fs.mkdtemp(path.join(os.tmpdir(),'guard-cli-retry-')),stateDir=path.join(root,'OrderNotificationAutomation'),config=path.join(root,'ports.json'),listenPort=await port();let guard,release,entered=false,invalid=false,delay=false,cli,exit;
|
||||
t.after(async()=>{release?.([listenPort]);cli?.kill();await guard?.stop();await fs.rm(root,{recursive:true,force:true});});
|
||||
await fs.writeFile(config,JSON.stringify({port:listenPort}));
|
||||
guard=new ServiceSupervisor({stateDir,entry:path.resolve('tests/fixtures/reload-ports-service.cjs'),portsProvider:()=>invalid?['invalid']:delay?new Promise(resolve=>{entered=true;release=resolve;}):[listenPort],env:{ORDER_FIXTURE_CONFIG:config},timing:{intervalMs:40,pingTimeoutMs:80,startupGraceMs:2000,stopGraceMs:500}});
|
||||
await guard.start();await until(()=>guard.snapshot().status==='running');invalid=true;await assert.rejects(guard.restart());assert.equal(guard.snapshot().status,'failed');invalid=false;delay=true;
|
||||
const completed=new Promise(resolve=>{cli=require('node:child_process').execFile(process.execPath,[path.resolve('scripts/service.cjs'),'restart'],{env:{...process.env,LOCALAPPDATA:root},windowsHide:true,timeout:12000},(error,stdout,stderr)=>{exit={error,stdout,stderr};resolve(exit);});});
|
||||
await until(()=>entered);const during=guard.snapshot();await new Promise(r=>setTimeout(r,1200));const earlyExit=exit;release([listenPort]);delay=false;
|
||||
const result=await completed;await until(()=>guard.snapshot().status==='running');
|
||||
assert.equal(during.status,'starting');assert.equal(during.reason,'manual_restart');assert.equal(earlyExit,undefined,'CLI must wait for this attempt rather than fail on the previous attempt');assert.equal(result.error,null,result.stderr);assert.match(result.stdout,/服务已重启/);
|
||||
invalid=true;await assert.rejects(guard.restart());invalid=false;delay=true;entered=false;
|
||||
const reply=await require('../../src/platform/service/control.cjs').requestControl({stateDir,action:'restart'});await until(()=>entered);release([listenPort]);delay=false;await until(()=>guard.snapshot().status==='running');
|
||||
assert.equal(reply.state.status,'starting','control acknowledgement must follow publishing the new attempt');assert.equal(reply.state.reason,'manual_restart');
|
||||
});
|
||||
test('each real child launch reloads ports and refuses an unknown occupant before spawning', {timeout:30000},async t=>{
|
||||
const {ServiceSupervisor}=require('../../src/platform/service/supervisor.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'guard-reload-')),config=path.join(stateDir,'ports.json'),a=await port(),b=await port();let guard,owner;
|
||||
t.after(async()=>{await guard?.stop();if(owner?.listening)await new Promise(r=>owner.close(r));await fs.rm(stateDir,{recursive:true,force:true});});
|
||||
|
||||
Reference in new issue
Block a user