Files
order-notification-automation/web/health.js
T

30 lines
6.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(() => {
'use strict';
let api,esc,formatDate;
const statuses={healthy:['上次正常','green'],error:['上次失败','red'],pending:['待检查','yellow'],disabled:['已停用','secondary'],paused:['已暂停','secondary'],running:['执行中','blue'],unknown:['状态未知','orange'],unconfigured:['未配置','secondary']};
const guards={running:['守护正常','green'],starting:['启动中','blue'],backoff:['等待恢复','orange'],cooldown:['恢复冷却中','orange'],stale:['守护心跳过期','red'],unmanaged:['未通过守护启动','yellow'],stopped:['已停止','secondary'],stopping:['停止中','secondary']};
const reasons={healthy:'两个服务端口心跳正常',initial_start:'首次启动',unexpected_exit:'业务进程意外退出',health_timeout:'服务持续无响应',manual_restart:'手动重启',manual_stop:'手动停止',port_conflict:'服务端口已被占用',spawn_failed:'进程启动失败',startup_failed:'启动失败'};
const events={guard_started:'守护启动',child_exit:'业务进程退出',unresponsive:'服务持续无响应',restarting:'准备自动恢复',cooldown:'多次失败,进入冷却',manual_restart:'手动重启',guard_stopped:'守护停止',monitor_error:'守护检查异常',spawn_failed:'业务进程启动失败',autostart_installed:'启用 Windows 登录自启',autostart_removed:'移除 Windows 登录自启'};
function duration(seconds){seconds=Math.max(0,Math.floor(seconds));const days=Math.floor(seconds/86400),hours=Math.floor(seconds%86400/3600),minutes=Math.floor(seconds%3600/60);return (days?days+' 天 ':'')+(hours?hours+' 小时 ':'')+(minutes?minutes+' 分钟 ':seconds%60+' 秒');}
function badge(status,map=statuses){const [label,color]=map[status]||['状态未知','secondary'];return `<span class="badge bg-${color}-lt">${label}</span>`;}
async function render(container,isActive=()=>true){
const live=()=>isActive()&&container.isConnected;let pending=false,timer;
container.innerHTML=`<div class="card mb-3"><div class="card-body d-flex gap-3 flex-wrap align-items-center"><div class="flex-fill"><h2 class="card-title mb-1">服务守护与健康状态</h2><div class="text-secondary small">上次检查结果,非实时连通性检测</div></div><button class="btn" type="button" id="health-refresh">刷新健康状态</button></div><div class="card-footer small" id="health-refresh-state" role="status" aria-live="polite">正在读取健康状态…</div></div><div id="health-runtime" class="mb-3"></div><div id="health-groups" class="row row-cards"></div><div id="health-events" class="mt-3"></div>`;
const button=container.querySelector('#health-refresh'),notice=container.querySelector('#health-refresh-state');
function draw(data){
const {runtime}=data,guard=runtime.guard;
container.querySelector('#health-runtime').innerHTML=`<div class="row row-cards"><div class="col-md-6"><section class="card h-100"><div class="card-header"><h3 class="card-title">工作台服务</h3><span class="badge bg-green-lt ms-auto" id="health-access">当前可访问</span></div><div class="card-body"><div class="h2 mb-3">${esc(duration(runtime.uptimeSeconds))}</div><div class="small text-secondary">本次启动:${esc(formatDate(runtime.startedAt))}</div><div class="small text-secondary mt-2">Windows 登录自启:${runtime.autostart.enabled?'已启用(当前用户)':'未启用'}</div></div></section></div><div class="col-md-6"><section class="card h-100"><div class="card-header"><h3 class="card-title">独立服务守护</h3><span class="ms-auto">${badge(guard.status,guards)}</span></div><div class="card-body"><div class="mb-2">累计恢复 / 重启:<strong>${Number(guard.restartCount)||0}</strong> 次</div><div class="small text-secondary">最近心跳:${esc(formatDate(guard.heartbeatAt))}</div><div class="small text-secondary mt-2">${esc(runtime.managed?(reasons[guard.reason]||'等待健康检查结果'):'当前服务直接启动,尚未由守护程序接管。')}</div>${guard.nextRestartAt?`<div class="small mt-2">下次尝试:${esc(formatDate(guard.nextRestartAt))}</div>`:''}</div></section></div></div>`;
container.querySelector('#health-groups').innerHTML=data.groups.map(group=>`<div class="col-xl-6"><section class="card h-100"><div class="card-header"><h3 class="card-title">${esc(group.title)}</h3><span class="ms-auto">${badge(group.status)}</span></div><div class="card-body">${group.message?`<div class="text-secondary">${esc(group.message)}</div>`:group.items.length?group.items.map(item=>`<div class="health-check-item"><div class="d-flex align-items-start gap-2"><strong class="text-break flex-fill">${esc(item.name)}</strong>${badge(item.status)}</div><div class="small text-secondary text-break mt-2">${esc(item.detail)}</div><dl class="health-check-times small mt-3 mb-0"><dt>最近检查</dt><dd>${esc(formatDate(item.checkedAt))}</dd><dt>最近成功</dt><dd>${esc(formatDate(item.lastSuccessAt))}</dd><dt>最近失败</dt><dd>${esc(formatDate(item.lastFailureAt))}</dd></dl></div>`).join(''):'<div class="text-secondary">尚无可查看的配置。</div>'}</div><div class="card-footer"><a href="${esc(group.link)}">打开${esc(group.title)}页面</a></div></section></div>`).join('');
container.querySelector('#health-events').innerHTML=`<section class="card"><div class="card-header"><h3 class="card-title">最近守护事件</h3></div><div class="card-body">${guard.events?.length?guard.events.slice(0,12).map(event=>`<div class="d-flex flex-wrap gap-2 mb-2 small"><span class="text-secondary">${esc(formatDate(event.at))}</span><span>${esc(events[event.kind]||'运行状态变化')}${event.code!==undefined&&event.code!==null?'(退出码 '+esc(event.code)+')':''}${event.delayMs?','+Math.ceil(event.delayMs/1000)+' 秒后尝试':''}</span></div>`).join(''):'<span class="text-secondary small">暂无守护事件。</span>'}</div><div class="card-footer small text-secondary">模块状态来自已保存的检查结果;成功与失败时间会持续记录。此页面每 10 秒更新,不触发外部连接检查。</div></section>`;
}
async function refresh(){
if(pending||!live())return;pending=true;button.disabled=true;clearTimeout(timer);
try{const data=await api('/health',undefined,{signal:AbortSignal.timeout(8000)});if(!live())return;draw(data);notice.className='card-footer small text-secondary';notice.innerHTML=`<span>健康状态已更新</span><span class="ms-2">${esc(formatDate(data.at))}</span>`;}
catch{if(live()){const access=container.querySelector('#health-access');if(access){access.className='badge bg-red-lt ms-auto';access.textContent='连接中断';}notice.className='card-footer small text-danger';notice.textContent='暂时无法连接服务,保留上次状态;恢复后会自动更新。';}}
finally{pending=false;if(live()){button.disabled=false;timer=setTimeout(refresh,10000);}}
}
button.onclick=refresh;await refresh();
}
window.HealthViews={configure:options=>({api,esc,formatDate}=options),render};
})();