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
+2
-1
@@ -10,7 +10,8 @@ const duplicate = () => Object.assign(new Error('该 BPM 账号已开启自动
|
||||
const digest = value => crypto.createHash('sha256').update(value).digest('hex');
|
||||
|
||||
function powershell(script, input) {
|
||||
return execFileSync('powershell.exe', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script], {
|
||||
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();
|
||||
}
|
||||
|
||||
+5
-1
@@ -7,12 +7,13 @@ const {bpmScanApi}=require('./bpm-scan-api.cjs');
|
||||
const {storageApi}=require('./storage-api.cjs');
|
||||
const {notificationApi}=require('./notification-api.cjs');
|
||||
const {assistantApi}=require('./assistant-api.cjs');
|
||||
const {respondToPing}=require('./service-ping.cjs');
|
||||
const {previewAsset,PREVIEW_CSP}=require('./storage-preview-assets.cjs');
|
||||
const {SessionStore,SESSION_MS}=require('./dashboard-sessions.cjs');
|
||||
const isLoopback=address=>['127.0.0.1','::1','::ffff:127.0.0.1'].includes(address);
|
||||
const publicJob=({path:ignored,...job})=>({...job,downloadable:job.status==='success'});
|
||||
|
||||
function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,storage,notifications,assistant,trustedProxy=false}) {
|
||||
function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,storage,notifications,assistant,health,watchdog,trustedProxy=false}) {
|
||||
const sessions=new SessionStore(path.dirname(store.file));const failures=new Map();
|
||||
const sessionCookieName=previewUserId?'order_preview_session':'order_session';
|
||||
const sessionCookiePattern=new RegExp('(?:^|;\\s*)'+sessionCookieName+'=([a-f0-9]{64})(?:;|$)');
|
||||
@@ -32,11 +33,13 @@ function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,ma
|
||||
'/storage-preview.css':{path:path.join(webRoot,'storage-preview.css'),type:'text/css',preview:true},
|
||||
'/notifications.js':{path:path.join(webRoot,'notifications.js'),type:'text/javascript'},
|
||||
'/assistant.js':{path:path.join(webRoot,'assistant.js'),type:'text/javascript'},
|
||||
'/health.js':{path:path.join(webRoot,'health.js'),type:'text/javascript'},
|
||||
'/app.css':{path:path.join(webRoot,'app.css'),type:'text/css'},
|
||||
'/vendor/tabler.css':{path:require.resolve('@tabler/core/dist/css/tabler.min.css'),type:'text/css'},
|
||||
'/vendor/tabler.js':{path:require.resolve('@tabler/core/dist/js/tabler.min.js'),type:'text/javascript'}
|
||||
};
|
||||
const server=http.createServer(async(request,response)=>{
|
||||
if(respondToPing(request,response,watchdog))return;
|
||||
const encryptedTransport=Boolean(request.socket.encrypted || (trustedProxy && isLoopback(request.socket.remoteAddress) && request.headers['x-forwarded-proto']==='https'));
|
||||
response.setHeader('X-Content-Type-Options','nosniff');response.setHeader('Referrer-Policy','same-origin');
|
||||
response.setHeader('Content-Security-Policy',"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'");
|
||||
@@ -93,6 +96,7 @@ function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,ma
|
||||
if(!user)fail(401,'请先登录。');
|
||||
if(session.renewed)response.setHeader('Set-Cookie',`${sessionCookieName}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_MS/1000}${encryptedTransport?'; Secure':''}`);
|
||||
if(route==='/api/me' && request.method==='GET')return reply(200,{user,preview});
|
||||
if(route==='/api/health' && request.method==='GET'){if(!health)fail(503,'健康状态服务未启动。');return reply(200,health.snapshot(user));}
|
||||
if(route==='/api/logout' && request.method==='POST'){sessions.revoke(token);response.setHeader('Set-Cookie',`${sessionCookieName}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0${encryptedTransport?'; Secure':''}`);if(bpmSessions)try{await bpmSessions.releaseSession(token);}catch{fail(502,'登录窗口关闭失败,请稍后重试。');}return reply(200,{ok:true});}
|
||||
if(await bpmApi({workspace,bpmSessions,user,sessionId:token,route,method:request.method,body,request,response,reply,trustedProxy}))return;
|
||||
if(await mailApi({mail,workspace,user,route,method:request.method,body,request,response,reply,trustedProxy}))return;
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),{DatabaseSync}=require('node:sqlite'),{readSupervisor}=require('./service-control.cjs'),{redact}=require('./assistant-policy.cjs');
|
||||
function timestamp(value){if(typeof value!=='string')return null;const normalized=/^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/.test(value)?value.replace(' ','T')+'Z':value;const n=Date.parse(normalized);return Number.isFinite(n)?new Date(n).toISOString():null;}
|
||||
const latest=(...values)=>values.map(timestamp).filter(Boolean).sort().at(-1)||null;
|
||||
const groupStatus=items=>!items.length?'unconfigured':['error','unknown','running','pending','healthy','paused','disabled'].find(s=>items.some(i=>i.status===s))||'pending';
|
||||
class RuntimeHealth {
|
||||
constructor({stateDir,startedAt=new Date().toISOString(),instanceId='',...sources}){
|
||||
Object.assign(this,{stateDir,startedAt,instanceId,sources});const dir=path.join(stateDir,'health');fs.mkdirSync(dir,{recursive:true,mode:0o700});this.db=new DatabaseSync(path.join(dir,'health.sqlite'));
|
||||
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=2000;
|
||||
CREATE TABLE IF NOT EXISTS observations(kind TEXT NOT NULL,id TEXT NOT NULL,last_success TEXT,last_failure TEXT,PRIMARY KEY(kind,id));`);
|
||||
}
|
||||
remember(kind,id,{successAt,failureAt}={}){
|
||||
const old=this.db.prepare('SELECT last_success AS lastSuccessAt,last_failure AS lastFailureAt FROM observations WHERE kind=? AND id=?').get(kind,id)||{};
|
||||
const record={lastSuccessAt:latest(old.lastSuccessAt,successAt),lastFailureAt:latest(old.lastFailureAt,failureAt)};
|
||||
if(record.lastSuccessAt!==old.lastSuccessAt||record.lastFailureAt!==old.lastFailureAt)this.db.prepare('INSERT INTO observations VALUES(?,?,?,?) ON CONFLICT(kind,id) DO UPDATE SET last_success=excluded.last_success,last_failure=excluded.last_failure').run(kind,id,record.lastSuccessAt,record.lastFailureAt);
|
||||
return record;
|
||||
}
|
||||
collect(){
|
||||
const groups=[],safe=(key,title,link,read)=>{try{const items=read();groups.push({key,title,link,status:groupStatus(items),items});}catch{groups.push({key,title,link,status:'unknown',items:[],message:'暂时无法读取此模块状态,请到对应页面核实。'});}};
|
||||
let connections=[];
|
||||
safe('bpm','BPM 连接','#bpm',()=>{connections=this.sources.workspace?.snapshot().connections||[];return connections.map(c=>{
|
||||
const checkedAt=timestamp(c.checkedAt),status=c.status==='disabled'?'disabled':c.status==='connected'?'healthy':['error','login_required'].includes(c.status)?'error':'pending';
|
||||
return {id:c.id,name:redact(c.name||'BPM 连接'),owner:c.owner,status,checkedAt,detail:status==='error'?'上次验证失败或需要重新登录。':status==='healthy'?'上次已验证登录;连接由后台托管检查。':'尚未验证或已停用。',...this.remember('bpm',c.id,{successAt:latest(c.lastConnectedAt,status==='healthy'?checkedAt:null),failureAt:status==='error'?checkedAt:null})};
|
||||
});});
|
||||
safe('scan','BPM 扫描','#records',()=>{
|
||||
const {config={},runs=[]}=this.sources.scanner?.store.status()||{};
|
||||
for(const r of runs)this.remember('scan',r.connectionId,{successAt:r.status==='success'?r.finishedAt:null,failureAt:['error','interrupted'].includes(r.status)?r.finishedAt:null});
|
||||
return connections.filter(c=>c.status!=='disabled').map(c=>{const run=runs.find(r=>r.connectionId===c.id),status=run?.status==='running'?'running':config.enabled===false?'paused':!run?'pending':run.status==='success'?'healthy':'error';return {id:c.id,name:redact(c.name||'BPM 连接'),owner:c.owner,status,checkedAt:timestamp(run?.finishedAt||run?.startedAt),detail:config.enabled===false?'定时扫描已暂停,保留最近运行记录。':run?.message?redact(run.message):run?.status==='success'?`最近扫描 ${run.seen||0} 条,新增 ${run.added||0} 条。`:'等待扫描结果。',...this.remember('scan',c.id)};});
|
||||
});
|
||||
safe('storage','SMB 存储','#storage',()=> (this.sources.storage?.store.servers()||[]).map(s=>{
|
||||
const checkedAt=timestamp(s.state?.checkedAt),status=!s.enabled?'disabled':!checkedAt?'pending':s.state.readable&&s.state.writable?'healthy':s.state.readable?'pending':'error';
|
||||
return {id:s.id,name:redact(s.name||'存储服务器'),status,checkedAt,detail:redact(s.state?.message||'尚未检查连接。'),...this.remember('storage',s.id,{successAt:status==='healthy'?checkedAt:null,failureAt:status==='error'?checkedAt:null})};
|
||||
}));
|
||||
safe('mail','邮件渠道','#mail',()=> (this.sources.mail?.store.channels()||[]).map(c=>{
|
||||
const checkedAt=timestamp(c.state?.checkedAt),status=!checkedAt?'pending':c.state.smtp&&c.state.imap?'healthy':'error';
|
||||
return {id:c.id,name:redact(c.name||'托管邮箱'),status,checkedAt,detail:redact(c.state?.message||'尚未检查 SMTP / IMAP。'),...this.remember('mail',c.id,{successAt:status==='healthy'?checkedAt:null,failureAt:status==='error'?checkedAt:null})};
|
||||
}));
|
||||
return groups;
|
||||
}
|
||||
snapshot(user){
|
||||
const now=Date.now(),groups=this.collect().map(g=>{if(!['bpm','scan'].includes(g.key)||user.role==='admin'||g.status==='unknown')return g;const items=g.items.filter(i=>i.owner===user.username);return {...g,items,status:groupStatus(items)};});
|
||||
let saved;try{saved=readSupervisor(this.stateDir);}catch{saved={state:null,events:[],autostart:null};}
|
||||
const s=saved.state,managed=Boolean(this.instanceId&&s?.childInstanceId===this.instanceId),fresh=managed&&now-Date.parse(s.updatedAt)<45000;
|
||||
const guard=managed?{status:fresh?s.status:'stale',heartbeatAt:s.heartbeatAt,updatedAt:s.updatedAt,restartCount:s.restartCount,childStartedAt:s.childStartedAt,reason:s.reason,nextRestartAt:s.nextRestartAt,events:saved.events.map(e=>({at:e.at,kind:e.kind,code:e.detail.code,delayMs:e.detail.delayMs,reason:e.detail.reason}))}:{status:'unmanaged',restartCount:0,events:[]};
|
||||
const autostart={enabled:!!(saved.autostart?.enabled&&saved.autostart?.linkPath&&fs.existsSync(saved.autostart.linkPath)),method:'current_user_logon',installedAt:saved.autostart?.installedAt||null};
|
||||
return {at:new Date(now).toISOString(),runtime:{startedAt:this.startedAt,uptimeSeconds:Math.max(0,Math.floor((now-Date.parse(this.startedAt))/1000)),managed,guard,autostart},groups};
|
||||
}
|
||||
start(){if(this.timer)return;const observe=()=>{try{this.collect();}catch{}};observe();this.timer=setInterval(observe,15000);this.timer.unref?.();}
|
||||
close(){clearInterval(this.timer);this.timer=null;this.db?.close();this.db=null;}
|
||||
}
|
||||
module.exports={RuntimeHealth,timestamp};
|
||||
+13
-5
@@ -16,6 +16,8 @@ const { BpmScanner } = require('./bpm-scanner.cjs');
|
||||
const { AssistantStore } = require('./assistant-store.cjs');
|
||||
const { AssistantService } = require('./assistant-service.cjs');
|
||||
const { ZcodeRuntime } = require('./zcode-runtime.cjs');
|
||||
const { RuntimeHealth } = require('./runtime-health.cjs');
|
||||
const { respondToPing } = require('./service-ping.cjs');
|
||||
const { StorageStore } = require('./storage-store.cjs');
|
||||
const { StorageService } = require('./storage-service.cjs');
|
||||
const { NotificationStore, NotificationService } = require('./notifications.cjs');
|
||||
@@ -25,6 +27,7 @@ function createServer(options) {
|
||||
const jobs = new Map();
|
||||
const maxBytes = options.maxBodyBytes || 20 * 1024 * 1024;
|
||||
return http.createServer(async (request, response) => {
|
||||
if(respondToPing(request,response,options.watchdog))return;
|
||||
const reply = (status, body) => { response.writeHead(status, { 'Content-Type':'application/json; charset=utf-8', 'Cache-Control':'no-store' }); response.end(JSON.stringify(body)); };
|
||||
const origin = request.headers.origin || '';
|
||||
if (!/^chrome-extension:\/\/[a-p]{32}$/.test(origin)) return reply(403, {error:'仅接受已配对的浏览器扩展。'});
|
||||
@@ -84,6 +87,7 @@ async function startService(options) {
|
||||
}
|
||||
|
||||
async function main(options = {}) {
|
||||
const startedAt=new Date().toISOString(),watchdog={token:process.env.ORDER_SUPERVISOR_TOKEN,instanceId:process.env.ORDER_SUPERVISOR_INSTANCE,startedAt};
|
||||
const root = path.resolve(__dirname,'..');
|
||||
let config = options.config;
|
||||
if(!config){
|
||||
@@ -112,7 +116,7 @@ async function main(options = {}) {
|
||||
const custodian=new BpmCustodian({workspace,manager:bpmSessions});
|
||||
let server;
|
||||
let dashboard;
|
||||
let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,assistantStore,assistant;
|
||||
let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,assistantStore,assistant,health;
|
||||
try {
|
||||
mailStore=new MailStore(path.join(stateDir,'mail'));mail=new MailService({store:mailStore});
|
||||
mailStore.migrateLegacy(store.settings().templates);
|
||||
@@ -120,13 +124,15 @@ async function main(options = {}) {
|
||||
storageStore=new StorageStore(path.join(stateDir,'storage'));storage=new StorageService({store:storageStore,jobs:store,outputDir});
|
||||
notificationStore=new NotificationStore(path.join(stateDir,'notifications'));notifications=new NotificationService({store:notificationStore,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides});
|
||||
assistantStore=new AssistantStore(path.join(stateDir,'assistant'));assistantStore.recover();assistant=new AssistantService({store:assistantStore,runtime:new ZcodeRuntime({stateDir:path.join(stateDir,'assistant','runtime')}),dashboard:store,workspace,scanner,storage});
|
||||
health=new RuntimeHealth({stateDir,startedAt,instanceId:watchdog.instanceId,workspace,scanner,storage,mail});
|
||||
await bpmSessions.migrateAccounts(workspace.snapshot().connections);
|
||||
workspace.markSessionChecksPending();
|
||||
server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage});
|
||||
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,storage,notifications,assistant,trustedProxy:dashboardConfig.trustedProxy===true});
|
||||
server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage,watchdog});
|
||||
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,storage,notifications,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true});
|
||||
await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();scanner.start();notifications.start();
|
||||
health.start();
|
||||
}
|
||||
catch(error){if(server?.listening)await new Promise(resolve=>server.close(resolve));if(dashboard?.listening)await new Promise(resolve=>dashboard.close(resolve));await assistant?.stop();assistantStore?.close();await notifications?.stop();notificationStore?.close();await storage?.stop();storageStore?.close();await scanner?.stop();scanStore?.close();await mail?.stop();mailStore?.close();await bpmSessions.shutdown();workspace.close();throw error;}
|
||||
catch(error){health?.close();if(server?.listening)await new Promise(resolve=>server.close(resolve));if(dashboard?.listening)await new Promise(resolve=>dashboard.close(resolve));await assistant?.stop();assistantStore?.close();await notifications?.stop();notificationStore?.close();await storage?.stop();storageStore?.close();await scanner?.stop();scanStore?.close();await mail?.stop();mailStore?.close();await bpmSessions.shutdown();workspace.close();throw error;}
|
||||
if(!options.quiet){
|
||||
console.log('订单通知中心已启动。\nWeb 工作台支持业务日历、异常待办与转交、BPM 连接管理。\n在 Chrome 订单页仍可点击扩展中的“导出当前订单”。');
|
||||
console.log(`首次使用:Chrome 扩展管理 → 开发者模式 → 加载已解压的扩展程序\n选择目录:${installedExtension}\n输出目录:${outputDir}\n本地服务:http://127.0.0.1:${port}`);
|
||||
@@ -135,6 +141,7 @@ async function main(options = {}) {
|
||||
}
|
||||
let stopping;
|
||||
const stop=()=>stopping ||= (async()=>{
|
||||
health.close();
|
||||
await assistant.stop();await notifications.stop();await storage.stop();await scanner.stop();await mail.stop();await custodian.stop();await bpmSessions.shutdown();
|
||||
await Promise.all([dashboard,server].map(socket=>new Promise((resolve,reject)=>socket.close(error=>error?reject(error):resolve()))));
|
||||
workspace.close();
|
||||
@@ -144,10 +151,11 @@ async function main(options = {}) {
|
||||
notificationStore.close();
|
||||
assistantStore.close();
|
||||
})();
|
||||
return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,assistant,stop};
|
||||
return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,assistant,health,stop};
|
||||
}
|
||||
if (require.main === module) main().then(app=>{
|
||||
const stop=()=>app.stop().then(()=>process.exit(0),()=>process.exit(1));
|
||||
process.once('SIGINT',stop);process.once('SIGTERM',stop);
|
||||
process.on('message',message=>{if(message==='order:shutdown')stop();});
|
||||
}).catch(error => { console.error('启动失败:'+error.message); process.exitCode=1; });
|
||||
module.exports = { createServer, startService, main };
|
||||
@@ -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,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('./supervisor-store.cjs'),{controlAddress}=require('./service-control.cjs'),{checkPing,sameToken}=require('./service-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.resolve(__dirname,'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:path.resolve(__dirname,'..'),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,18 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto'),{DatabaseSync}=require('node:sqlite'),{BpmVault}=require('./bpm-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,31 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),{execFileSync}=require('node:child_process'),{SupervisorStore}=require('./supervisor-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=path.resolve(__dirname,'..'),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