feat: supervise local service and expose persistent health dashboard
This commit is contained in:
1 parent
e2bd8c390f
commit
9a23197ecf
27 files changed
+512
-21
No files matched your search
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),http=require('node:http'),{respondToPing}=require('../../src/service-ping.cjs');
|
||||
const file=process.env.ORDER_FIXTURE_COUNT,generation=(fs.existsSync(file)?Number(fs.readFileSync(file,'utf8')):0)+1;fs.writeFileSync(file,String(generation));
|
||||
const startedAt=new Date().toISOString();let hang=false;
|
||||
const server=http.createServer((req,res)=>{fs.writeFileSync(file+'.heartbeat',String(req.headers['x-order-watchdog']||''));if(hang)return;respondToPing(req,res,{token:process.env.ORDER_SUPERVISOR_TOKEN,instanceId:process.env.ORDER_SUPERVISOR_INSTANCE,startedAt});});
|
||||
server.listen(Number(process.env.ORDER_FIXTURE_PORT),'127.0.0.1',()=>{if(generation===1||process.env.ORDER_FIXTURE_ALWAYS_CRASH==='1')setTimeout(()=>process.exit(17),150);if(generation===2)setTimeout(()=>{hang=true;},250);});
|
||||
process.on('message',m=>{if(m==='order:shutdown'){server.closeAllConnections();server.close(()=>process.exit(0));}});
|
||||
@@ -0,0 +1,23 @@
|
||||
'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');
|
||||
async function fixture(t){
|
||||
const {Store}=require('../src/dashboard-store.cjs'),{RuntimeHealth}=require('../src/runtime-health.cjs'),{createDashboard}=require('../src/dashboard.cjs');
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'health-http-')),store=new Store(path.join(dir,'dashboard'));store.bootstrap('admin','Health-test-password-123');
|
||||
const health=new RuntimeHealth({stateDir:dir,workspace:{snapshot:()=>({connections:[{id:'c',owner:'admin',name:'<img src=x onerror=alert(1)>',status:'connected',checkedAt:new Date().toISOString(),lastConnectedAt:new Date().toISOString()}]})}}),watchdog={token:'a'.repeat(64),instanceId:'health-fixture',startedAt:new Date().toISOString()};
|
||||
const server=createDashboard({store,health,watchdog,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r));health.close();await fs.rm(dir,{recursive:true,force:true});});
|
||||
const base='http://127.0.0.1:'+server.address().port;return {base};
|
||||
}
|
||||
test('health API is authenticated and watchdog requires a secret token and exact instance',async t=>{
|
||||
const {base}=await fixture(t);assert.equal((await fetch(base+'/api/health')).status,401);assert.equal((await fetch(base+'/_internal/health')).status,404);
|
||||
const ping=await fetch(base+'/_internal/health',{headers:{'x-order-watchdog':'a'.repeat(64)}});assert.equal(ping.status,200);assert.equal((await ping.json()).instanceId,'health-fixture');
|
||||
const login=await fetch(base+'/api/login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:JSON.stringify({username:'admin',password:'Health-test-password-123'})}),cookie=login.headers.get('set-cookie').split(';')[0];
|
||||
const response=await fetch(base+'/api/health',{headers:{Cookie:cookie}});assert.equal(response.status,200);assert.doesNotMatch(await response.text(),/a{64}|password|health-fixture/);
|
||||
});
|
||||
test('health page shows historical checks, escapes labels, and recovers from an offline refresh',{timeout:60000},async t=>{
|
||||
const {base}=await fixture(t),{loadPlaywright,browserOptions}=require('../src/runtime.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1280,height:900}}),errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||
await page.goto(base+'/#health');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Health-test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();
|
||||
await page.getByRole('heading',{name:'系统健康',exact:true}).waitFor();await page.getByText('上次检查结果,非实时连通性检测',{exact:true}).waitFor();assert.equal(await page.locator('#health-groups img').count(),0);
|
||||
await page.route('**/api/health',route=>route.abort());await page.getByRole('button',{name:'刷新健康状态',exact:true}).click();await page.getByText('暂时无法连接服务,保留上次状态;恢复后会自动更新。',{exact:true}).waitFor();
|
||||
await page.unroute('**/api/health');await page.getByRole('button',{name:'刷新健康状态',exact:true}).click();await page.getByText('健康状态已更新',{exact:true}).waitFor();
|
||||
await fs.mkdir('output/verification',{recursive:true});await page.screenshot({path:'output/verification/service-health-desktop.png',fullPage:true});await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
'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');
|
||||
test('health keeps success/failure history across restart, filters BPM ownership, and never checks external systems',async t=>{
|
||||
const {RuntimeHealth}=require('../src/runtime-health.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-health-'));let health;
|
||||
t.after(async()=>{health?.close();await fs.rm(stateDir,{recursive:true,force:true});});
|
||||
const connections=[{id:'mine',name:'我的连接',owner:'worker',status:'connected',checkedAt:'2026-10-18T01:00:00Z',lastConnectedAt:'2026-10-18T01:00:00Z',password:'PRIVATE'},{id:'other',name:'PRIVATE_OTHER',owner:'other',status:'connected'}];
|
||||
const deps={stateDir,workspace:{snapshot:()=>({connections})},scanner:{store:{status:()=>({config:{enabled:false},runs:[{connectionId:'mine',status:'error',finishedAt:'2026-10-18T02:00:00Z'}]})},scan:()=>assert.fail('must not scan')},storage:{store:{servers:()=>[{id:'s',name:'共享',enabled:true,state:{checkedAt:'2026-10-18T01:00:00Z',readable:true,writable:true,message:'password=PRIVATE C:/PRIVATE/file'}}]},check:()=>assert.fail('must not write/check')},mail:{store:{channels:()=>[]},verify:()=>assert.fail('must not verify/send')}};
|
||||
health=new RuntimeHealth(deps);let data=health.snapshot({username:'worker',role:'operator'});assert.doesNotMatch(JSON.stringify(data),/PRIVATE|OTHER/);assert.equal(data.groups.find(g=>g.key==='bpm').items.length,1);assert.equal(data.groups.find(g=>g.key==='mail').status,'unconfigured');
|
||||
connections[0].status='error';connections[0].checkedAt='2026-10-18T03:00:00Z';data=health.snapshot({username:'worker',role:'operator'});const item=data.groups.find(g=>g.key==='bpm').items[0];assert.equal(item.status,'error');assert.equal(item.lastSuccessAt,'2026-10-18T01:00:00.000Z');assert.equal(item.lastFailureAt,'2026-10-18T03:00:00.000Z');
|
||||
health.close();health=new RuntimeHealth(deps);assert.equal(health.snapshot({username:'worker',role:'operator'}).groups.find(g=>g.key==='bpm').items[0].lastSuccessAt,item.lastSuccessAt);
|
||||
assert.equal(health.snapshot({username:'admin',role:'admin'}).groups.find(g=>g.key==='bpm').items.length,2);
|
||||
});
|
||||
test('a damaged module is reported unknown without hiding other modules or claiming real-time connectivity',async t=>{
|
||||
const {RuntimeHealth}=require('../src/runtime-health.cjs'),stateDir=await fs.mkdtemp(path.join(os.tmpdir(),'order-health-errors-'));const health=new RuntimeHealth({stateDir,workspace:{snapshot:()=>({connections:[]})},storage:{store:{servers:()=>{throw Error('PRIVATE failure');}}},mail:{store:{channels:()=>[{id:'m',name:'邮箱',enabled:false,state:{checkedAt:null,smtp:false,imap:false}}]}}});t.after(async()=>{health.close();await fs.rm(stateDir,{recursive:true,force:true});});
|
||||
const data=health.snapshot({role:'admin'});assert.equal(data.groups.find(g=>g.key==='storage').status,'unknown');assert.equal(data.groups.find(g=>g.key==='mail').items[0].status,'pending');assert.equal(data.runtime.managed,false);assert.doesNotMatch(JSON.stringify(data),/PRIVATE/);
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict');
|
||||
test('stop confirmation rejects timeouts, authentication errors and stale states',()=>{
|
||||
const {canConfirmStopped}=require('../src/service-control.cjs'),expected={supervisorPid:123,childInstanceId:'expected'},state={...expected,status:'stopped',childPid:null,reason:'manual_stop'};
|
||||
assert.equal(canConfirmStopped(Error('timeout'),state,expected),false);assert.equal(canConfirmStopped({status:403},state,expected),false);assert.equal(canConfirmStopped({code:'ECONNREFUSED'},{...state,status:'running'},expected),false);
|
||||
assert.equal(canConfirmStopped({code:'ENOENT'},{...state,childInstanceId:'another'},expected),false);assert.equal(canConfirmStopped({code:'ENOENT'},state,expected),true);
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
'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);
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
'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');
|
||||
test('Windows login shortcut uses the current account, supports spaces and can be removed without deleting service state',{skip:process.platform!=='win32',timeout:30000},async t=>{
|
||||
const {installAutostart,uninstallAutostart,readShortcut}=require('../src/windows-startup.cjs'),root=await fs.mkdtemp(path.join(os.tmpdir(),'order startup ')),startupDir=path.join(root,'登录启动'),stateDir=path.join(root,'状态库');t.after(()=>fs.rm(root,{recursive:true,force:true}));
|
||||
const projectRoot=path.join(root,'项目 带空格'),marker=path.join(root,'started.txt');await fs.mkdir(path.join(projectRoot,'scripts'),{recursive:true});await fs.writeFile(path.join(projectRoot,'scripts','service.cjs'),'require("node:fs").writeFileSync('+JSON.stringify(marker)+',process.argv[2]);');
|
||||
const installed=installAutostart({stateDir,startupDir,projectRoot,nodePath:process.execPath});const shortcut=readShortcut(installed.linkPath);
|
||||
assert.match(shortcut.target,/wscript\.exe$/i);assert.ok(shortcut.args.includes(installed.launcherPath));assert.equal(installed.enabled,true);
|
||||
require('node:child_process').execFileSync('cscript.exe',['//Nologo','//B',installed.launcherPath],{windowsHide:true,timeout:5000});
|
||||
const deadline=Date.now()+5000;while(Date.now()<deadline){try{if(await fs.readFile(marker,'utf8')==='run')break;}catch{}await new Promise(r=>setTimeout(r,100));}assert.equal(await fs.readFile(marker,'utf8'),'run');
|
||||
const twice=installAutostart({stateDir,startupDir,projectRoot,nodePath:process.execPath});assert.equal(twice.linkPath,installed.linkPath);
|
||||
uninstallAutostart({stateDir,startupDir});await assert.rejects(fs.access(installed.linkPath));assert.ok(await fs.stat(path.join(stateDir,'supervisor','supervisor.sqlite')));
|
||||
});
|
||||
test('failed shortcut creation never reports enabled, and foreign shortcuts are preserved',{skip:process.platform!=='win32',timeout:30000},async t=>{
|
||||
const {installAutostart,uninstallAutostart}=require('../src/windows-startup.cjs'),{readSupervisor}=require('../src/service-control.cjs'),root=await fs.mkdtemp(path.join(os.tmpdir(),'order-startup-ownership-')),stateDir=path.join(root,'state'),startupDir=path.join(root,'startup');t.after(()=>fs.rm(root,{recursive:true,force:true}));
|
||||
assert.throws(()=>installAutostart({stateDir,startupDir,shortcutWriter:()=>{}}),/验证失败/);assert.equal(readSupervisor(stateDir).autostart,null);
|
||||
const record=installAutostart({stateDir,startupDir});
|
||||
const script='$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; $s=(New-Object -ComObject WScript.Shell).CreateShortcut($d.file); $s.TargetPath=$d.target; $s.Arguments=""; $s.Save()';
|
||||
require('node:child_process').execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{input:JSON.stringify({file:record.linkPath,target:path.join(process.env.SystemRoot,'System32','notepad.exe')}),encoding:'utf8',windowsHide:true,timeout:10000});
|
||||
const before=await fs.readFile(record.linkPath);assert.throws(()=>installAutostart({stateDir,startupDir}),/其他程序/);assert.throws(()=>uninstallAutostart({stateDir,startupDir}),/已被更改/);assert.deepEqual(await fs.readFile(record.linkPath),before);
|
||||
});
|
||||
Reference in new issue
Block a user