refactor: organize source web and tests by business module

This commit is contained in:
abaishu0730 committed 2026-10-19 08:45:51 +08:00
1 parent 9854d2d5c2
commit 2aed328774
113 files changed
+189 -183

No files matched your search

+7
View File
@@ -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/platform/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);
});
+33
View File
@@ -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/platform/service/supervisor.cjs'),{requestControl,readSupervisor}=require('../../src/platform/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/platform/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/platform/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/platform/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);
});
+20
View File
@@ -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/platform/service/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/platform/service/windows-startup.cjs'),{readSupervisor}=require('../../src/platform/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);
});