Files
order-notification-automation/tests/service-supervisor.test.cjs
T

34 lines
5.1 KiB
JavaScript

'use strict';
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('external guard recovers a crashed child and a live but unresponsive child, then stops without respawning',{timeout:60000},async t=>{
const {ServiceSupervisor}=require('../src/service-supervisor.cjs'),{requestControl,readSupervisor}=require('../src/service-control.cjs');
const stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-guard-')),listenPort=await port(),countFile=path.join(stateDir,'count');let guard;
t.after(async()=>{await guard?.stop();await fs.rm(stateDir,{recursive:true,force:true});});
guard=new ServiceSupervisor({stateDir,entry:path.resolve('tests/fixtures/managed-service.cjs'),ports:[listenPort],env:{ORDER_FIXTURE_PORT:String(listenPort),ORDER_FIXTURE_COUNT:countFile},timing:{intervalMs:50,pingTimeoutMs:80,startupGraceMs:1800,failureThreshold:2,stopGraceMs:500,backoffMs:[30,50,80],cooldownMs:500,windowMs:30000,maxRestarts:8}});
await guard.start();await until(()=>guard.snapshot().status==='running'&&guard.snapshot().restartCount>=2,30000);
const state=guard.snapshot();assert.ok(state.childPid>0);assert.ok(state.heartbeatAt);assert.ok(Number(await fs.readFile(countFile,'utf8'))>=3);
assert.equal(await fs.readFile(countFile+'.heartbeat','utf8')===await fs.readFile(path.join(stateDir,'supervisor','control.key'),'utf8'),false,'HTTP heartbeats must never send the management token');
const {controlAddress}=require('../src/service-control.cjs');
for(const value of [null,42,'text',[],true,{token:{toString:null},action:'stop'}]){
const reply=await new Promise((resolve,reject)=>{const s=net.createConnection(controlAddress(stateDir));s.setTimeout(600,()=>{s.destroy();reject(Error('malformed control request was not rejected'));});s.on('error',reject);s.on('connect',()=>s.write(JSON.stringify(value)+'\n'));s.on('data',data=>{s.destroy();resolve(JSON.parse(data.toString('utf8')));});});assert.equal(reply.status,value&&typeof value==='object'&&!Array.isArray(value)?403:400);
}
assert.equal((await requestControl({stateDir,action:'status'})).state.childPid,state.childPid);
assert.ok(readSupervisor(stateDir).events.some(e=>e.kind==='unresponsive'));
await assert.rejects(requestControl({stateDir,action:'stop',token:'bad-token'}),e=>e.status===403);
assert.equal((await requestControl({stateDir,action:'status'})).state.childPid,state.childPid);
const duplicate=new ServiceSupervisor({stateDir,entry:path.resolve('tests/fixtures/managed-service.cjs'),ports:[listenPort]});await assert.rejects(duplicate.start(),e=>e.code==='EADDRINUSE');assert.equal(guard.snapshot().childPid,state.childPid);
await requestControl({stateDir,action:'restart'});await until(()=>guard.snapshot().status==='running'&&guard.snapshot().childInstanceId!==state.childInstanceId);assert.ok(guard.snapshot().restartCount>=3);
await guard.stop();const generations=await fs.readFile(countFile,'utf8');await new Promise(r=>setTimeout(r,250));assert.equal(await fs.readFile(countFile,'utf8'),generations);assert.equal(readSupervisor(stateDir).state.status,'stopped');
});
test('unknown port owners remain running, and repeated real exits enter cooldown',{timeout:60000},async t=>{
const {ServiceSupervisor}=require('../src/service-supervisor.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-guard-conflict-')),listenPort=await port(),owner=net.createServer(socket=>socket.end('owner'));await new Promise(r=>owner.listen(listenPort,'127.0.0.1',r));let guard;
t.after(async()=>{await guard?.stop();if(owner.listening)await new Promise(r=>owner.close(r));await fs.rm(stateDir,{recursive:true,force:true});});
const blocked=new ServiceSupervisor({stateDir,ports:[listenPort]});await assert.rejects(blocked.start(),e=>e.code==='EADDRINUSE');assert.equal(owner.listening,true);await new Promise(r=>owner.close(r));
guard=new ServiceSupervisor({stateDir,entry:path.resolve('tests/fixtures/managed-service.cjs'),ports:[listenPort],env:{ORDER_FIXTURE_PORT:String(listenPort),ORDER_FIXTURE_COUNT:path.join(stateDir,'count'),ORDER_FIXTURE_ALWAYS_CRASH:'1'},timing:{intervalMs:40,pingTimeoutMs:50,startupGraceMs:1000,backoffMs:[30],maxRestarts:1,cooldownMs:1000,windowMs:30000,stopGraceMs:500}});await guard.start();await until(()=>guard.snapshot().status==='cooldown');assert.ok(guard.snapshot().nextRestartAt);await guard.stop();
});
test('restart backoff is bounded and repeated failures enter a cooldown',()=>{
const {restartPlan}=require('../src/service-supervisor.cjs');assert.deepEqual([0,1,2,20].map(failures=>restartPlan({failures,recent:0}).delayMs),[2000,5000,10000,60000]);assert.equal(restartPlan({failures:9,recent:8}).cooldown,true);assert.equal(restartPlan({failures:9,recent:8}).delayMs,300000);
});