refactor: organize source web and tests by business module
This commit is contained in:
1 parent
9854d2d5c2
commit
2aed328774
113 files changed
+189
-183
No files matched your search
@@ -0,0 +1,24 @@
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
function loadPlaywright() {
|
||||
const candidates = [
|
||||
'playwright-core',
|
||||
process.env.ORDER_PLAYWRIGHT_MODULE,
|
||||
path.join(os.homedir(), '.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright-core')
|
||||
].filter(Boolean);
|
||||
for (const candidate of candidates) {
|
||||
try { return require(candidate); } catch (error) { if (error.code !== 'MODULE_NOT_FOUND') throw error; }
|
||||
}
|
||||
throw new Error('缺少 playwright-core,请先运行 npm install。');
|
||||
}
|
||||
function browserOptions() {
|
||||
const candidates = [process.env.ORDER_CHROME_PATH,
|
||||
process.env.PROGRAMFILES && path.join(process.env.PROGRAMFILES, 'Google/Chrome/Application/chrome.exe'),
|
||||
process.env['PROGRAMFILES(X86)'] && path.join(process.env['PROGRAMFILES(X86)'], 'Google/Chrome/Application/chrome.exe'),
|
||||
process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Google/Chrome/Application/chrome.exe')].filter(Boolean);
|
||||
const executablePath = candidates.find(candidate => fs.existsSync(candidate));
|
||||
return executablePath ? { executablePath, headless: true } : { channel: 'chrome', headless: true };
|
||||
}
|
||||
module.exports = { loadPlaywright, browserOptions };
|
||||
@@ -0,0 +1,134 @@
|
||||
'use strict';
|
||||
const fs = require('node:fs');
|
||||
const fsp = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
const { DatabaseSync } = require('node:sqlite');
|
||||
const fail = () => Object.assign(new Error('BPM 会话存储不可用,请重新登录或联系管理员。'), { status: 503 });
|
||||
const duplicate = () => Object.assign(new Error('该 BPM 账号已开启自动续登,请使用已有连接或先解除原账号托管。'), { status: 409, code: 'BPM_ACCOUNT_DUPLICATE' });
|
||||
const digest = value => crypto.createHash('sha256').update(value).digest('hex');
|
||||
|
||||
function powershell(script, input) {
|
||||
const utf8='[Console]::InputEncoding=New-Object System.Text.UTF8Encoding; [Console]::OutputEncoding=New-Object System.Text.UTF8Encoding; ';
|
||||
return execFileSync('powershell.exe', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', utf8+script], {
|
||||
input, encoding: 'utf8', windowsHide: true, timeout: 15000, stdio: ['pipe', 'pipe', 'pipe']
|
||||
}).trim();
|
||||
}
|
||||
function secureDirectory(dir) {
|
||||
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
if (process.platform === 'win32') {
|
||||
powershell('$ErrorActionPreference="Stop"; $p=[Console]::In.ReadToEnd(); $s=[System.Security.Principal.WindowsIdentity]::GetCurrent().User; $a=New-Object System.Security.AccessControl.DirectorySecurity; $a.SetAccessRuleProtection($true,$false); $a.SetOwner($s); $r=New-Object System.Security.AccessControl.FileSystemAccessRule($s,"FullControl","ContainerInherit,ObjectInherit","None","Allow"); $a.AddAccessRule($r); [System.IO.Directory]::SetAccessControl($p,$a)', dir);
|
||||
} else fs.chmodSync(dir, 0o700);
|
||||
}
|
||||
function dpapi(value, decrypt = false) {
|
||||
const operation = decrypt ? 'Unprotect' : 'Protect';
|
||||
return Buffer.from(powershell(`$ErrorActionPreference="Stop"; Add-Type -AssemblyName System.Security; $b=[Convert]::FromBase64String([Console]::In.ReadToEnd()); $r=[System.Security.Cryptography.ProtectedData]::${operation}($b,$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser); [Console]::Out.Write([Convert]::ToBase64String($r))`, value.toString('base64')), 'base64');
|
||||
}
|
||||
|
||||
class BpmVault {
|
||||
constructor({ stateDir }) {
|
||||
try {
|
||||
this.stateDir = path.resolve(stateDir);
|
||||
secureDirectory(this.stateDir);
|
||||
} catch { throw fail(); }
|
||||
}
|
||||
ensureKey() {
|
||||
if (this.key) return this.key;
|
||||
try {
|
||||
// The key always stays on the service user's local disk, even when project code is on a shared drive.
|
||||
const keyDir = process.platform === 'win32'
|
||||
? path.join(process.env.LOCALAPPDATA, 'OrderNotificationAutomation', 'bpm-keys')
|
||||
: path.join(this.stateDir, '.keys');
|
||||
secureDirectory(keyDir);
|
||||
const keyFile = path.join(keyDir, digest(this.stateDir.toLowerCase()) + '.key');
|
||||
if (!fs.existsSync(keyFile)) {
|
||||
const raw = crypto.randomBytes(32);
|
||||
const protectedKey = process.platform === 'win32' ? dpapi(raw) : raw;
|
||||
try { fs.writeFileSync(keyFile, protectedKey, { flag: 'wx', mode: 0o600 }); }
|
||||
catch (error) { if (error.code !== 'EEXIST') throw error; }
|
||||
finally { raw.fill(0); }
|
||||
}
|
||||
const protectedKey = fs.readFileSync(keyFile);
|
||||
this.key = process.platform === 'win32' ? dpapi(protectedKey, true) : protectedKey;
|
||||
if (this.key.length !== 32) throw fail();
|
||||
return this.key;
|
||||
} catch { throw fail(); }
|
||||
}
|
||||
filename(id) {
|
||||
if (typeof id !== 'string' || !id || id.length > 200) throw Object.assign(new Error('连接标识无效。'), { status: 400 });
|
||||
return path.join(this.stateDir, digest(id) + '.enc');
|
||||
}
|
||||
accounts() {
|
||||
if(this.db)return this.db;
|
||||
const db=new DatabaseSync(path.join(this.stateDir,'accounts.sqlite'));
|
||||
try{db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA secure_delete=ON;
|
||||
CREATE TABLE IF NOT EXISTS accounts(connection_id TEXT PRIMARY KEY,username_key TEXT NOT NULL UNIQUE,payload BLOB NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS sessions(connection_id TEXT PRIMARY KEY,payload BLOB NOT NULL);`);this.db=db;return db;}
|
||||
catch{db.close();throw fail();}
|
||||
}
|
||||
accountKey(username) {
|
||||
if(typeof username!=='string'||!username.trim()||username.length>150)throw Object.assign(new Error('请输入有效的 BPM 账号。'),{status:400});
|
||||
return crypto.createHmac('sha256',this.ensureKey()).update(username.trim().toLowerCase()).digest('hex');
|
||||
}
|
||||
encode(id,state) {
|
||||
const iv=crypto.randomBytes(12),cipher=crypto.createCipheriv('aes-256-gcm',this.ensureKey(),iv);cipher.setAAD(Buffer.from(id));
|
||||
const encrypted=Buffer.concat([cipher.update(JSON.stringify(state),'utf8'),cipher.final()]);
|
||||
return Buffer.concat([Buffer.from('BPM1'),iv,cipher.getAuthTag(),encrypted]);
|
||||
}
|
||||
decode(id,bytes) {
|
||||
const data=Buffer.from(bytes);
|
||||
if(data.length<33||data.subarray(0,4).toString()!=='BPM1')throw fail();
|
||||
const decipher=crypto.createDecipheriv('aes-256-gcm',this.ensureKey(),data.subarray(4,16));
|
||||
decipher.setAAD(Buffer.from(id));decipher.setAuthTag(data.subarray(16,32));
|
||||
return JSON.parse(Buffer.concat([decipher.update(data.subarray(32)),decipher.final()]).toString('utf8'));
|
||||
}
|
||||
putAccount(id,state) {
|
||||
try{this.accounts().prepare('INSERT INTO accounts(connection_id,username_key,payload) VALUES(?,?,?) ON CONFLICT(connection_id) DO UPDATE SET username_key=excluded.username_key,payload=excluded.payload').run(id.slice(8),this.accountKey(state.username),this.encode(id,state));}
|
||||
catch(cause){if(cause.errcode===2067)throw duplicate();if(cause.status)throw cause;throw fail();}
|
||||
}
|
||||
async accountAvailability(connectionId,username) {
|
||||
try{const row=this.accounts().prepare('SELECT connection_id FROM accounts WHERE username_key=?').get(this.accountKey(username));return {available:!row||row.connection_id===connectionId};}
|
||||
catch(cause){if(cause.status)throw cause;throw fail();}
|
||||
}
|
||||
async migrateAccounts(connectionIds) {
|
||||
const db=this.accounts(),legacy=[];
|
||||
try{
|
||||
for(const connectionId of connectionIds){const id='account:'+connectionId;if(db.prepare('SELECT 1 FROM accounts WHERE connection_id=?').get(connectionId))continue;try{const payload=await fsp.readFile(this.filename(id));legacy.push({id,state:this.decode(id,payload)});}catch(cause){if(cause.code!=='ENOENT')throw cause;}}
|
||||
db.exec('BEGIN IMMEDIATE');
|
||||
try{for(const item of legacy)this.putAccount(item.id,item.state);db.exec('COMMIT');}catch(cause){db.exec('ROLLBACK');throw cause;}
|
||||
// Committed database rows become authoritative before legacy ciphertext is removed.
|
||||
for(const item of legacy)await fsp.rm(this.filename(item.id),{force:true});
|
||||
}catch(cause){if(cause.status)throw cause;throw fail();}
|
||||
}
|
||||
async read(id) {
|
||||
const filename = this.filename(id);
|
||||
try {
|
||||
if(id.startsWith('account:')){const row=this.accounts().prepare('SELECT payload FROM accounts WHERE connection_id=?').get(id.slice(8));if(row)return this.decode(id,row.payload);}
|
||||
else{const row=this.accounts().prepare('SELECT payload FROM sessions WHERE connection_id=?').get(id);if(row)return this.decode(id,row.payload);}
|
||||
const state=this.decode(id,await fsp.readFile(filename));
|
||||
if(id.startsWith('account:')){this.putAccount(id,state);await fsp.rm(filename,{force:true});}
|
||||
else{
|
||||
// Commit legacy ciphertext before removing its file. An existing database
|
||||
// session is authoritative if another process completed migration first.
|
||||
this.accounts().prepare('INSERT OR IGNORE INTO sessions(connection_id,payload) VALUES(?,?)').run(id,this.encode(id,state));
|
||||
const saved=this.decode(id,this.accounts().prepare('SELECT payload FROM sessions WHERE connection_id=?').get(id).payload);
|
||||
await fsp.rm(filename,{force:true});return saved;
|
||||
}
|
||||
return state;
|
||||
} catch (error) { if (error.code === 'ENOENT') return null;if(error.code==='BPM_ACCOUNT_DUPLICATE')throw error;throw fail(); }
|
||||
}
|
||||
async write(id, state) {
|
||||
const filename = this.filename(id);
|
||||
if(id.startsWith('account:')){this.putAccount(id,state);await fsp.rm(filename,{force:true}).catch(()=>{});return;}
|
||||
try {
|
||||
// Some Windows state directories reject even same-directory renames with
|
||||
// EXDEV. SQLite publishes the encrypted payload in one atomic transaction.
|
||||
this.accounts().prepare('INSERT INTO sessions(connection_id,payload) VALUES(?,?) ON CONFLICT(connection_id) DO UPDATE SET payload=excluded.payload').run(id,this.encode(id,state));
|
||||
await fsp.rm(filename,{force:true}).catch(()=>{});
|
||||
} catch { throw fail(); }
|
||||
}
|
||||
async remove(id) { try { await fsp.rm(this.filename(id), { force: true });if(id.startsWith('account:'))this.accounts().prepare('DELETE FROM accounts WHERE connection_id=?').run(id.slice(8));else this.accounts().prepare('DELETE FROM sessions WHERE connection_id=?').run(id); } catch { throw fail(); } }
|
||||
destroy() { this.db?.close();this.db=null;this.key?.fill(0);this.key=null; }
|
||||
}
|
||||
module.exports = { BpmVault };
|
||||
@@ -0,0 +1,18 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),crypto=require('node:crypto'),net=require('node:net'),{DatabaseSync}=require('node:sqlite');
|
||||
const defaultStateDir=()=>path.join(process.env.LOCALAPPDATA||os.homedir(),'OrderNotificationAutomation');
|
||||
function controlAddress(stateDir){const digest=crypto.createHash('sha256').update(path.resolve(stateDir).toLowerCase()).digest('hex').slice(0,24);return process.platform==='win32'?'\\\\.\\pipe\\order-service-'+digest:path.join(path.resolve(stateDir),'supervisor','control.sock');}
|
||||
function readSupervisor(stateDir){
|
||||
const file=path.join(stateDir,'supervisor','supervisor.sqlite');if(!fs.existsSync(file))return {state:null,events:[],autostart:null};let db;
|
||||
try{db=new DatabaseSync(file,{readOnly:true});db.exec('PRAGMA busy_timeout=1000');const get=key=>{const r=db.prepare('SELECT value FROM metadata WHERE key=?').get(key);return r?JSON.parse(r.value):null;};return {state:get('state'),autostart:get('autostart'),events:db.prepare('SELECT at,kind,detail FROM events ORDER BY id DESC LIMIT 20').all().map(r=>({...r,detail:JSON.parse(r.detail)}))};}finally{db?.close();}
|
||||
}
|
||||
function requestControl({stateDir=defaultStateDir(),action='status',token,timeout=3000}){
|
||||
return new Promise((resolve,reject)=>{
|
||||
try{token??=fs.readFileSync(path.join(stateDir,'supervisor','control.key'),'utf8').trim();}catch(e){reject(e);return;}
|
||||
const socket=net.createConnection(controlAddress(stateDir));let raw='',done=false;const finish=(error,value)=>{if(done)return;done=true;socket.destroy();error?reject(error):resolve(value);};
|
||||
socket.setTimeout(timeout,()=>finish(Error('服务守护未响应。')));socket.on('error',e=>finish(e));socket.on('connect',()=>socket.write(JSON.stringify({token,action})+'\n'));
|
||||
socket.on('data',chunk=>{raw+=chunk.toString('utf8');if(raw.length>65536)return finish(Error('守护响应超出限制。'));if(!raw.includes('\n'))return;try{const result=JSON.parse(raw.split('\n')[0]);result.error?finish(Object.assign(Error(result.error),{status:result.status})):finish(null,result);}catch(e){finish(e);}});socket.on('end',()=>{if(!done)finish(Error('服务守护连接已关闭。'));});
|
||||
});
|
||||
}
|
||||
function canConfirmStopped(error,state,expected){return !!(error&&['ENOENT','ECONNREFUSED'].includes(error.code)&&state?.status==='stopped'&&state.reason==='manual_stop'&&state.childPid===null&&state.supervisorPid===expected?.supervisorPid&&state.childInstanceId===expected?.childInstanceId);}
|
||||
module.exports={defaultStateDir,controlAddress,requestControl,readSupervisor,canConfirmStopped};
|
||||
@@ -0,0 +1,14 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto');
|
||||
const isLoopback=address=>['127.0.0.1','::1','::ffff:127.0.0.1'].includes(address);
|
||||
function sameToken(actual,expected){if(typeof actual!=='string'||typeof expected!=='string')return false;const a=Buffer.from(actual),b=Buffer.from(expected);return b.length===64&&a.length===b.length&&crypto.timingSafeEqual(a,b);}
|
||||
function respondToPing(request,response,{token,instanceId,startedAt}={}){
|
||||
if(request.url!=='/_internal/health')return false;
|
||||
const allowed=request.method==='GET'&&token&&isLoopback(request.socket.remoteAddress)&&sameToken(request.headers['x-order-watchdog'],token);
|
||||
response.writeHead(allowed?200:404,{'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store'});response.end(JSON.stringify(allowed?{ok:true,instanceId,startedAt}:{error:'资源不存在。'}));return true;
|
||||
}
|
||||
async function checkPing(port,{token,instanceId,timeout=5000}){
|
||||
const response=await fetch('http://127.0.0.1:'+port+'/_internal/health',{headers:{'x-order-watchdog':token},signal:AbortSignal.timeout(timeout),redirect:'error'});
|
||||
if(response.status!==200)throw Error('heartbeat rejected');const body=await response.text();if(body.length>2048)throw Error('heartbeat too large');const result=JSON.parse(body);if(result.ok!==true||result.instanceId!==instanceId)throw Error('heartbeat instance mismatch');return result;
|
||||
}
|
||||
module.exports={respondToPing,checkPing,sameToken};
|
||||
@@ -0,0 +1,18 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto'),{DatabaseSync}=require('node:sqlite'),{BpmVault}=require('../security/vault.cjs');
|
||||
class SupervisorStore {
|
||||
constructor(stateDir){
|
||||
this.dir=path.join(path.resolve(stateDir),'supervisor');new BpmVault({stateDir:this.dir}).destroy();
|
||||
this.db=new DatabaseSync(path.join(this.dir,'supervisor.sqlite'));
|
||||
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=2000;
|
||||
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS events(id INTEGER PRIMARY KEY,at TEXT NOT NULL,kind TEXT NOT NULL,detail TEXT NOT NULL);`);
|
||||
const file=path.join(this.dir,'control.key');try{fs.writeFileSync(file,crypto.randomBytes(32).toString('hex'),{flag:'wx',mode:0o600});}catch(e){if(e.code!=='EEXIST')throw e;}
|
||||
this.token=fs.readFileSync(file,'utf8').trim();if(!/^[a-f0-9]{64}$/.test(this.token))throw Error('服务守护控制文件无效。');
|
||||
}
|
||||
get(key){const r=this.db.prepare('SELECT value FROM metadata WHERE key=?').get(key);return r?JSON.parse(r.value):null;}
|
||||
set(key,value){this.db.prepare('INSERT INTO metadata VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(key,JSON.stringify(value));}
|
||||
event(kind,detail={}){this.db.prepare('INSERT INTO events(at,kind,detail) VALUES(?,?,?)').run(new Date().toISOString(),kind,JSON.stringify(detail));this.db.exec('DELETE FROM events WHERE id NOT IN(SELECT id FROM events ORDER BY id DESC LIMIT 200)');}
|
||||
close(){this.db?.close();this.db=null;}
|
||||
}
|
||||
module.exports={SupervisorStore};
|
||||
@@ -0,0 +1,89 @@
|
||||
'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('./store.cjs'),{controlAddress}=require('./control.cjs'),{checkPing,sameToken}=require('./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.join(require('../../shared/paths.cjs').PROJECT_ROOT,'src/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:require('../../shared/paths.cjs').PROJECT_ROOT,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};
|
||||
@@ -0,0 +1,31 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),{execFileSync}=require('node:child_process'),{SupervisorStore}=require('./store.cjs');
|
||||
function powershell(script,data){return execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command','$ErrorActionPreference="Stop"; [Console]::InputEncoding=New-Object System.Text.UTF8Encoding; [Console]::OutputEncoding=New-Object System.Text.UTF8Encoding; '+script],{input:JSON.stringify(data),encoding:'utf8',windowsHide:true,timeout:15000,stdio:['pipe','pipe','pipe']}).trim();}
|
||||
function locations({stateDir,startupDir}){
|
||||
if(process.platform!=='win32')throw Error('登录自启动仅支持 Windows。');
|
||||
const root=path.resolve(startupDir||path.join(process.env.APPDATA,'Microsoft','Windows','Start Menu','Programs','Startup'));
|
||||
return {linkPath:path.join(root,'OrderNotificationAutomation.lnk'),launcherPath:path.join(path.resolve(stateDir),'supervisor','logon-launch.vbs'),wscript:path.join(process.env.SystemRoot,'System32','wscript.exe')};
|
||||
}
|
||||
function readShortcut(file){const raw=powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; $s=(New-Object -ComObject WScript.Shell).CreateShortcut($d.file); @{target=$s.TargetPath;args=$s.Arguments}|ConvertTo-Json -Compress',{file});return JSON.parse(raw);}
|
||||
function ownedShortcut(paths){if(!fs.existsSync(paths.linkPath))return true;const old=readShortcut(paths.linkPath);return path.resolve(old.target).toLowerCase()===path.resolve(paths.wscript).toLowerCase()&&old.args==='//B "'+paths.launcherPath+'"';}
|
||||
function removeFile(file){try{fs.unlinkSync(file);}catch(e){if(e.code!=='ENOENT')throw e;}if(fs.existsSync(file))throw Error('无法确认自启动文件已移除。');}
|
||||
function writeShortcut({paths,projectRoot}){powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; $s=(New-Object -ComObject WScript.Shell).CreateShortcut($d.link); $s.TargetPath=$d.target; $s.Arguments=$d.args; $s.WorkingDirectory=$d.cwd; $s.Description="Order workspace service supervisor"; $s.Save()',{link:paths.linkPath,target:paths.wscript,args:'//B "'+paths.launcherPath+'"',cwd:path.resolve(projectRoot)});}
|
||||
function installAutostart({stateDir,projectRoot=require('../../shared/paths.cjs').PROJECT_ROOT,nodePath=process.execPath,startupDir,shortcutWriter=writeShortcut}={}){
|
||||
const paths=locations({stateDir,startupDir}),store=new SupervisorStore(stateDir);
|
||||
try{
|
||||
if(!ownedShortcut(paths))throw Error('同名启动快捷方式属于其他程序,未覆盖。');
|
||||
const cli=path.join(path.resolve(projectRoot),'scripts','service.cjs');fs.accessSync(nodePath);fs.accessSync(cli);
|
||||
const command='"'+nodePath+'" "'+cli+'" run';
|
||||
const source='Set shell = CreateObject("WScript.Shell")\r\nshell.Run "'+command.replace(/"/g,'""')+'", 0, False\r\n';
|
||||
fs.writeFileSync(paths.launcherPath,Buffer.concat([Buffer.from([0xff,0xfe]),Buffer.from(source,'utf16le')]),{mode:0o600});
|
||||
fs.mkdirSync(path.dirname(paths.linkPath),{recursive:true});
|
||||
shortcutWriter({paths,projectRoot});
|
||||
if(!fs.existsSync(paths.linkPath)||!ownedShortcut(paths))throw Error('启动快捷方式验证失败。');
|
||||
const record={enabled:true,method:'current_user_logon',installedAt:new Date().toISOString(),...paths};store.set('autostart',record);store.event('autostart_installed');return record;
|
||||
}finally{store.close();}
|
||||
}
|
||||
function uninstallAutostart({stateDir,startupDir}={}){
|
||||
const paths=locations({stateDir,startupDir}),store=new SupervisorStore(stateDir);
|
||||
try{if(!ownedShortcut(paths))throw Error('启动快捷方式已被更改,未删除。');removeFile(paths.linkPath);removeFile(paths.launcherPath);store.set('autostart',{enabled:false,method:'current_user_logon',removedAt:new Date().toISOString()});store.event('autostart_removed');return {enabled:false};}finally{store.close();}
|
||||
}
|
||||
module.exports={installAutostart,uninstallAutostart,readShortcut};
|
||||
Reference in new issue
Block a user