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,7 +2,7 @@
|
||||
|
||||
面向团队的 BPM 订单工作台,提供业务日历、异常待办与转交、连接管理和运行监管配置;保留 Chrome 已登录订单页导出本地 PDF 的能力。
|
||||
|
||||
**项目最终目标**:无人值守识别匹配订单、按模板整理、上传 210、按产品线群组每天两次自动发送邮件。当前实现团队工作台与 BPM Web 登录、会话保存,订单处理规则后续确定;BPM 知会不自动处理。已接入新版门户只读扫描;新增可配置 SMB 归档和通用通知队列。实际 BPM 简要说明字段与产业接口人规则等待同事整理后配置,ZCode 尚未接入。完整流程背景见 [无人值守系统设计](docs/unattended-system-design.md),登录实现见 [BPM 登录设计](docs/superpowers/specs/2026-10-16-bpm-login-design.md)。
|
||||
**项目最终目标**:无人值守识别匹配订单、按模板整理、上传 210、按产品线群组每天两次自动发送邮件。当前实现团队工作台与 BPM Web 登录、会话保存,订单处理规则后续确定;BPM 知会不自动处理。已接入新版门户只读扫描、可配置 SMB 归档、通用通知队列、受控 ZCode 对话,以及服务守护和健康面板。实际 BPM 简要说明字段与产业接口人规则等待同事整理后配置。完整流程背景见 [无人值守系统设计](docs/unattended-system-design.md),登录实现见 [BPM 登录设计](docs/superpowers/specs/2026-10-16-bpm-login-design.md)。
|
||||
|
||||
## 设计与部署入口
|
||||
|
||||
@@ -51,6 +51,28 @@
|
||||
|
||||
存储配置及记录位于本机 `storage/storage.sqlite`;通知配置、加密队列正文和发送批次位于 `notifications/notifications.sqlite`。与其他状态目录一起停服备份,不提交至 Git。
|
||||
|
||||
## 服务守护与系统健康
|
||||
|
||||
双击 **启动工具.cmd** 或运行 `npm start`,工作台由独立守护程序在后台运行;启动窗口关闭后服务继续运行,重复启动会复用现有实例。打开 **系统健康**(`/#health`)查看本次启动时间、连续运行时长、守护心跳、恢复次数、最近事件及 Windows 登录自启状态。
|
||||
|
||||
守护通过两个本机端口的私有心跳确认业务进程身份。启动宽限 120 秒,之后每 10 秒检查,连续 4 次失败才终止本工具启动的进程树并恢复。退出重试采用 2/5/10/30/60 秒退避,15 分钟内达到 8 次恢复尝试后冷却 5 分钟,避免反复启动。人工停止不会触发恢复,不会结束未知的占用端口进程。自动恢复仍遵守原有任务规则,邮件结果不明时保留待核实状态。
|
||||
|
||||
| 命令 | 用途 |
|
||||
|---|---|
|
||||
| `npm start` | 后台启动并等待两个端口就绪 |
|
||||
| `npm run service:status` | 查询守护实际响应和持久状态 |
|
||||
| `npm run service:restart` | 正常停止业务进程,再启动并检查心跳 |
|
||||
| `npm run service:stop` | 停止业务服务及守护;保留登录自启设置 |
|
||||
| `npm run service:install` | 安装当前 Windows 用户登录自启动 |
|
||||
| `npm run service:uninstall` | 移除登录自启;保留业务状态与日志 |
|
||||
| `npm run start:foreground` | 排错时直接前台启动,不经过守护 |
|
||||
|
||||
自启动在当前 Windows 用户登录后后台执行,沿用该账号的 DPAPI 和 SMB 权限,无须保存 Windows 登录密码。启动目录使用专用快捷方式,不覆盖其他程序的同名入口。它不是未登录即可运行的系统服务;电脑仍需开机并能访问业务网络。
|
||||
|
||||
模块卡片展示 **已保存的上次检查结果**,分开显示未配置、待检查、已暂停、失败与正常;只读采集不会新建 BPM 登录、SMB 探测文件或发送邮件。最近观测到的成功/失败时间保存在本机 `health/health.sqlite`,BPM 明细按负责人权限过滤。页面每 10 秒刷新,服务暂不可达时保留上次数据并提示,恢复后自动更新。
|
||||
|
||||
守护控制、事件和安装记录保存在本机 `supervisor/supervisor.sqlite`;当前用户 ACL 保护 `control.key` 与日志,管理令牌不发送到 HTTP,业务心跳每次启动使用独立随机令牌。`supervisor/service.log` 达 5 MiB 时轮转,保留 3 份历史。停服备份整个本机状态目录,勿将控制密钥或运行状态提交到 Git。实现与验证见 [服务守护设计](docs/superpowers/specs/2026-10-18-service-health-design.md)。
|
||||
|
||||
## ZCode 对话助手
|
||||
|
||||
工作台左侧 **ZCode 助手** 提供个人会话、连续追问、诊断依据、停止回复与操作结果。交互参考 [Open WebUI](https://github.com/open-webui/open-webui),界面在本项目内实现,共用工作台账号。
|
||||
@@ -89,7 +111,7 @@
|
||||
|
||||
## PDF 扩展首次使用
|
||||
|
||||
1. 双击本目录的 **启动工具.cmd**,或运行 `npm start`。保持服务窗口打开。本机已有 Node.js、Chrome 和依赖,可直接启动。换电脑使用时,安装 Node.js 22.13+(建议 Node.js 24)和 Chrome,然后在项目目录运行 `npm install`。框架使用 Node 内置 SQLite,部分 Node 版本会打印实验性 API 提示。
|
||||
1. 双击本目录的 **启动工具.cmd**,或运行 `npm start`。服务在后台守护运行,无须保持启动窗口打开。本机已有 Node.js、Chrome 和依赖,可直接启动。换电脑使用时,安装 Node.js 22.13+(建议 Node.js 24)和 Chrome,然后在项目目录运行 `npm install`。框架使用 Node 内置 SQLite,部分 Node 版本会打印实验性 API 提示。
|
||||
2. 在 Chrome 地址栏打开 `chrome://extensions`,启用“开发者模式”,点击“加载已解压的扩展程序”。
|
||||
3. 选择服务窗口给出的本机目录:`%LOCALAPPDATA%\OrderNotificationAutomation\extension`。**不要选择项目内的 extension 源码目录**:启动时会把源码和本机配对配置一起准备到上述目录。
|
||||
4. 在 Chrome 扩展菜单中固定“订单通知书 PDF”。在你已登录的 BPM 中打开订单详情,点击扩展,再点击 **导出当前订单**。
|
||||
@@ -124,7 +146,7 @@ Chrome 加载扩展只需做一次。修改扩展源码、重新配对或变更
|
||||
## 故障处理
|
||||
|
||||
- 无法连接本地工具:确认启动窗口仍在运行;端口或配对变更后刷新扩展。
|
||||
- 端口占用:先关闭重复启动的工具窗口;也可在 `config.json` 修改端口,重启并刷新扩展。
|
||||
- 端口占用:先运行 `npm run service:status` 确认状态;需要停止本工具时运行 `npm run service:stop`。未知程序占用端口时工具不会接管,可在 `config.json` 修改端口,再启动并刷新扩展。
|
||||
- 缺少字段:进入“海外运营订单更改评审 V7”实际订单详情;其他表单的绑定不同,需要增加映射。
|
||||
- 缺少排版依赖:在项目目录运行 `npm install`。
|
||||
- 启动入口直接运行 Node,不需要 PowerShell 脚本,也不修改系统执行策略。
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# 服务守护与健康面板 Implementation Plan
|
||||
|
||||
**Goal:** 独立守护订单服务,并展示可信、可追溯的模块健康状态。
|
||||
**Architecture:** ServiceSupervisor 管理子进程与双端口心跳;SupervisorStore/RuntimeHealth 保存非敏感状态;Windows 登录快捷方式启动守护;健康页面共用工作台身份。
|
||||
**Tech Stack:** Node 24、SQLite、Windows 命名管道/启动目录、现有 Tabler 与 Playwright。
|
||||
**Spec:** `docs/superpowers/specs/2026-10-18-service-health-design.md`
|
||||
|
||||
## Task 1: 独立守护与控制
|
||||
|
||||
- [x] 新增 `tests/service-supervisor.test.cjs` / fixture,先复现缺失:退出恢复、真实 HTTP 无响应、停止、实例互斥和令牌拒绝。
|
||||
- [x] 新增 `src/supervisor-store.cjs`、`src/service-ping.cjs`、`src/service-supervisor.cjs`、`src/service-control.cjs`,使用有限持久事件与保守恢复策略。
|
||||
- [x] 修改 `src/server.cjs` / `src/dashboard.cjs` 增加受令牌保护的回环心跳与 IPC 正常停止。
|
||||
- [x] 跑守护测试及服务启动回归。
|
||||
|
||||
## Task 2: 登录自启及启动入口
|
||||
|
||||
- [x] 新增 `src/windows-startup.cjs` 与 `scripts/service.cjs`,生成隐藏启动脚本及用户专用快捷方式,提供可逆 install/uninstall/start/stop/restart/status。
|
||||
- [x] 更新 `启动工具.cmd`、package scripts;验证引用含空格与中文的路径、重复启动和快捷方式归属。
|
||||
|
||||
## Task 3: 健康状态及页面
|
||||
|
||||
- [x] 新增 `tests/runtime-health.test.cjs` / `tests/health-http-ui.test.cjs`,先验证历史、权限、来源异常及只读采集。
|
||||
- [x] 新增 `src/runtime-health.cjs`、`web/health.js`,挂载 `/api/health` 和 `#health`,按角色过滤 BPM,持续观测与断线恢复。
|
||||
- [x] 接入启动/停止生命周期,更新运行监管入口,运行真实浏览器检查与受影响 HTTP 回归。
|
||||
|
||||
## Task 4: 交付
|
||||
|
||||
- [x] 只读代码审查并修复重要问题;保存文档与本地提交。
|
||||
- [x] 安装当前 Windows 用户登录自启,核实后接管已知本地服务;独立命令重启验证、确认页面/会话/守护恢复正常。
|
||||
- [x] 清楚报告已验证能力、登录自启动条件和真实业务连通性范围。
|
||||
@@ -0,0 +1,23 @@
|
||||
# 服务守护与健康面板
|
||||
|
||||
用户已确认优先实施“服务守护与健康面板”,本设计固化已批准方向,继续在当前开发分支实现。
|
||||
|
||||
## 服务常驻
|
||||
|
||||
独立 Node 守护进程启动业务服务,使用独立 IPC 通道发出正常停止请求,以随机令牌和实例 ID 验证两个本机 HTTP 心跳。业务进程退出或持续无响应后结束其进程树并重启;启动宽限 120 秒,运行时每 10 秒检查,连续 4 次失败才重启。重试退避 2/5/10/30/60 秒,15 分钟内 8 次失败后冷却 5 分钟。人工停止不触发恢复。
|
||||
|
||||
同一本机状态目录只允许一个守护进程,通过独占命名管道和受当前用户 ACL 保护的控制令牌实现;控制命令只接受 status/stop/restart,不暴露网页重启接口。不接管未知的占用端口进程。SQLite 保存守护状态和有限事件历史,日志轮转限制磁盘占用。业务启动脚本改为连接守护程序,重复打开不会重复启动。
|
||||
|
||||
Windows 登录自启动使用当前用户启动目录的专用快捷方式,隐藏启动独立守护程序,无须保存 Windows 密码。它在当前用户登录后启动,保留 DPAPI、SMB 会话和托管凭据的现有使用条件;不冒充未登录即可运行的系统服务。提供安装、移除、启动、停止、重启、状态 CLI。
|
||||
|
||||
## 健康面板
|
||||
|
||||
新增“系统健康”页面和登录后的只读接口,显示当前服务开始时间、连续运行时长、守护是否实际接管、最近心跳、恢复次数/原因、Windows 登录自启状态,以及 BPM 连接、扫描、SMB 检查和邮箱检查的最近已知结果。
|
||||
|
||||
健康收集只读已有状态,不为展示发起 BPM 登录、SMB 写入或邮件操作。独立健康 SQLite 保存观测到的最近成功/失败时间;扫描保留近期运行结果,BPM 使用持久 lastConnectedAt 补足成功时间。界面明确“上次检查结果”,未配置、停用、未检查与失败分开显示,不把历史成功称为实时连通。来源读取失败时单独显示该模块未知,不能阻断其他状态或心跳。BPM 明细按管理员/负责人权限过滤,不输出凭据、路径、邮件正文或完整表单。
|
||||
|
||||
浏览器在此页每 10 秒更新,离线时保留上次数据并明确显示重连状态;恢复后自动刷新,不需要反复手动刷新。
|
||||
|
||||
## 验证
|
||||
|
||||
隔离子进程测试覆盖真实退出/无响应恢复、退避限流、人工停止、重复实例和控制鉴权。健康测试覆盖历史持久化、来源异常、权限、未配置及不产生外部调用;真实浏览器验证刷新、断线提示、XSS 和窄屏。实际安装登录自启并检查快捷方式,接管本服务后通过独立控制命令重启一次验证会话及服务恢复。真实业务邮件不重发,未知结果沿用已有核验规则。
|
||||
@@ -115,3 +115,15 @@
|
||||
- 新增 `tests/bpm-route-errors.test.cjs` 先复现同样 disposed 错误,再验证修复。覆盖响应提交失败、附件/重定向/弹窗拦截失败、fetch 失败及后续有效请求恢复;没有使用全局吞错处理。
|
||||
- 正式服务已重启;首页及 bootstrap 状态 HTTP 200,真实浏览器可见登录表单、无页面脚本错误。没有使用或更改工作台密码。
|
||||
- 崩溃专项 1/1、既有 BPM 真实浏览器与服务重启回归 12/12 通过;后者日志 output/verification/bpm-route-crash-regression.log。语法与 Git diff 检查通过。
|
||||
|
||||
## 服务守护与健康面板(2026-10-18)
|
||||
|
||||
- 用户确认先实施服务守护和健康面板。新增独立进程守护、双端口实例心跳、命名管道控制、退避/冷却、Windows 当前用户登录自启及只读健康页面;没有新增邮件重发或 BPM 审批操作。
|
||||
- 最终相关测试 20/20 通过,0 跳过,日志 `output/verification/service-health-final.log`:真实子进程退出及 HTTP 无响应恢复、手动重启、停止不再拉起、重复实例、控制鉴权与畸形消息、未知端口保护、实际冷却流程、中文路径启动器执行、外来快捷方式保护、安装失败、健康历史/权限/来源异常、HTTP 与浏览器断线恢复、既有 PDF/工作台及服务重启。
|
||||
- 共用 PowerShell 助手明确 UTF-8 输入/输出,修复中文状态目录 ACL 设置失败;加密存储 7/7 与自启 2/2 重新验证通过,日志 `output/verification/startup-vault-final.log`。主回归与自启重叠 2 项,总计 27 个不同测试通过。Windows 快捷方式使用真实 COM 创建、读取、移除,并以 cscript 实际执行 UTF-16LE BOM 启动器,在中文且带空格的项目路径下启动隔离 JS。
|
||||
- 独立只读审查后修复:未认证 null/对象令牌导致守护退出、心跳复用管理令牌、停止超时误报成功、快捷方式未生成却标为启用、VBS 中文路径编码。对应复现均先失败后通过。心跳现在每轮独立随机,控制令牌只用于本机管道;停止须通道关闭且同一实例的 stopped 状态已持久保存。
|
||||
- 最初并行回归遇到一次临时端口 EACCES,独立重跑通过;最终完整相关回归串行运行 20/20 通过。中文目录 ACL 问题已明确修复,没有将失败记录算作通过。
|
||||
- 实机已安装 Windows 当前用户登录快捷方式,并核实目标和参数;未重启 Windows。业务服务改由独立守护程序在后台运行,未接管未知端口进程。启动器重复打开会复用已有实例。
|
||||
- 实机管理命令执行一次业务重启:守护 PID 47552 保持,业务 PID 从 62420 变为 59864;双端口检查通过,恢复计数为 1。使用临时测试会话验证重启后原会话仍可访问;测试会话随后撤销,没有修改账号密码。
|
||||
- 正式首页 HTTP 200;真实浏览器系统健康页显示守护正常、登录自启启用,脚本错误为空。摘要 `output/verification/service-health-live.json`;隔离截图 `service-health-desktop.png`,正式页截图 `service-health-live.png`,均留在本机忽略目录。页面 390 px 无横向溢出,断线时保留旧值并更新连接中断提示,恢复后可继续刷新。
|
||||
- 健康模块显示最近保存/观测结果,不等同实时外网连通性;未配置邮箱明确显示未配置。没有以健康展示触发 SMB 写入、BPM 登录或真实业务邮件发送。守护恢复遵循现有邮件 unknown 核验与任务中断规则。
|
||||
+7
-1
@@ -4,7 +4,13 @@
|
||||
"private": true,
|
||||
"description": "Team workspace for BPM connections, business calendars, exceptions and order PDF export",
|
||||
"scripts": {
|
||||
"start": "node src/server.cjs",
|
||||
"start": "node scripts/service.cjs start",
|
||||
"start:foreground": "node src/server.cjs",
|
||||
"service:install": "node scripts/service.cjs install",
|
||||
"service:uninstall": "node scripts/service.cjs uninstall",
|
||||
"service:status": "node scripts/service.cjs status",
|
||||
"service:stop": "node scripts/service.cjs stop",
|
||||
"service:restart": "node scripts/service.cjs restart",
|
||||
"test": "node --test --test-concurrency=2 tests/*.test.cjs",
|
||||
"preview": "node scripts/preview.cjs"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),{spawn}=require('node:child_process'),{ServiceSupervisor}=require('../src/service-supervisor.cjs'),{defaultStateDir,requestControl,readSupervisor,canConfirmStopped}=require('../src/service-control.cjs');
|
||||
const root=path.resolve(__dirname,'..'),pause=ms=>new Promise(r=>setTimeout(r,ms));
|
||||
function ports(){let config={};try{config=JSON.parse(fs.readFileSync(path.join(root,'config.json'),'utf8'));}catch(e){if(e.code!=='ENOENT')throw e;}const result=[config.port||18765,config.dashboard?.port??18766];if(result.some(p=>!Number.isInteger(p)||p<1024||p>65535)||result[0]===result[1])throw Error('服务端口配置无效。');return result;}
|
||||
async function waitRunning(stateDir,previousInstance){const end=Date.now()+130000;let last;
|
||||
while(Date.now()<end){try{last=(await requestControl({stateDir})).state;if(last.status==='running'&&(!previousInstance||last.childInstanceId!==previousInstance))return last;if(last.status==='cooldown')throw Object.assign(Error('重复启动失败,服务已进入冷却;请查看本机守护日志。'),{fatal:true});}catch(e){if(e.fatal)throw e;}await pause(1000);}throw Error('启动尚未就绪,请运行 npm run service:status 查看状态。');
|
||||
}
|
||||
async function main(action=process.argv[2]||'start'){
|
||||
const stateDir=defaultStateDir();
|
||||
if(action==='run'){
|
||||
const guard=new ServiceSupervisor({stateDir,ports:ports()});await guard.start();const stop=()=>guard.stop().then(()=>process.exit(0),()=>process.exit(1));process.once('SIGINT',stop);process.once('SIGTERM',stop);return;
|
||||
}
|
||||
if(action==='install'||action==='uninstall'){const startup=require('../src/windows-startup.cjs');const result=action==='install'?startup.installAutostart({stateDir}):startup.uninstallAutostart({stateDir});console.log(result.enabled?'Windows 登录自启动已启用(当前用户,后台运行)。':'Windows 登录自启动已移除。');return;}
|
||||
if(action==='status'){let live;try{live=await requestControl({stateDir});}catch{}const saved=readSupervisor(stateDir);console.log(JSON.stringify({supervisorResponding:!!live,state:live?.state||saved.state,autostartEnabled:!!(saved.autostart?.enabled&&fs.existsSync(saved.autostart.linkPath)),events:saved.events},null,2));return;}
|
||||
if(action==='stop'){
|
||||
let expected;try{expected=(await requestControl({stateDir,action:'stop'})).state;}catch(e){if(['ENOENT','ECONNREFUSED'].includes(e.code)){console.log('服务守护未运行。');return;}throw e;}
|
||||
const end=Date.now()+40000;while(Date.now()<end){try{await requestControl({stateDir});}catch(error){if(canConfirmStopped(error,readSupervisor(stateDir).state,expected)){console.log('服务已停止,不会自动拉起;登录自启设置保留。');return;}if(!['ENOENT','ECONNREFUSED'].includes(error.code))throw Error('停止结果尚未确认,请检查守护状态。');}await pause(500);}throw Error('停止结果尚未确认,请检查守护状态。');
|
||||
}
|
||||
if(action==='restart'){const before=(await requestControl({stateDir,action:'restart'})).state;await waitRunning(stateDir,before.childInstanceId);console.log('服务已重启并通过两个端口的健康检查。');return;}
|
||||
if(action!=='start')throw Error('支持 start / stop / restart / status / install / uninstall。');
|
||||
let existing;try{existing=(await requestControl({stateDir})).state;}catch(e){if(!['ENOENT','ECONNREFUSED'].includes(e.code))throw e;}
|
||||
if(existing?.status==='running'){console.log('服务已在守护下运行,无需重复启动。');return;}
|
||||
if(!existing){const child=spawn(process.execPath,[__filename,'run'],{cwd:root,env:process.env,detached:true,windowsHide:true,stdio:'ignore'});child.unref();}
|
||||
await waitRunning(stateDir);console.log('订单工作台已在后台运行:http://127.0.0.1:'+ports()[1]+'/#health');
|
||||
}
|
||||
if(require.main===module)main().catch(e=>{console.error('服务管理失败:'+e.message);process.exitCode=1;});
|
||||
module.exports={main};
|
||||
+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};
|
||||
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);
|
||||
});
|
||||
@@ -20,3 +20,5 @@
|
||||
/* Personal diagnostic conversations share the workspace palette. */
|
||||
.assistant-layout{display:grid;grid-template-columns:240px minmax(0,1fr);gap:1rem;align-items:start}.assistant-sidebar{max-height:780px;overflow:auto}.assistant-chat{min-width:0}.assistant-messages{min-height:360px;max-height:65vh;overflow:auto;padding:1.5rem;background:#f7f9fb}.assistant-turn{margin-bottom:1.8rem;min-width:0}.assistant-user{margin-left:12%;background:#eaf2ff;border:1px solid #dce7fa;border-radius:12px;padding:1rem;white-space:pre-wrap;overflow-wrap:anywhere}.assistant-reply{padding:1.2rem 0 0;overflow-wrap:anywhere}.assistant-answer{white-space:pre-wrap;line-height:1.85}.assistant-welcome{text-align:center;padding:4rem .5rem}.assistant-action{border:1px solid #dce3eb;border-radius:8px;padding:1rem;background:#fff;min-width:0}.assistant-action+.assistant-action{margin-top:.65rem}.assistant-action pre{white-space:pre-wrap;overflow-wrap:anywhere}.assistant-sidebar .list-group-item{border-radius:8px;margin-bottom:.4rem}.assistant-chat textarea{resize:vertical;min-height:90px}.assistant-chat .card-footer{background:#fff}
|
||||
@media(max-width:767px){.assistant-layout{grid-template-columns:minmax(0,1fr)}.assistant-sidebar{max-height:230px}.assistant-messages{min-height:340px;padding:1rem}.assistant-user{margin-left:5%}.assistant-welcome{padding:2rem .25rem}.assistant-chat .card-footer{padding:1rem}.assistant-chat .btn-list{gap:.4rem}}
|
||||
|
||||
.health-check-item+.health-check-item{border-top:1px solid var(--tblr-border-color,#dce1e7);padding-top:1rem;margin-top:1rem}.health-check-times{display:grid;grid-template-columns:5rem minmax(0,1fr);gap:.4rem .6rem}.health-check-times dt{font-weight:400;color:var(--tblr-secondary,#6c7a91)}.health-check-times dd{margin:0;overflow-wrap:anywhere}#health-runtime .card,#health-groups .card{min-width:0}
|
||||
+6
-6
@@ -5,9 +5,9 @@ const formatDate=value=>{const date=new Date(value);return value&&!Number.isNaN(
|
||||
const roles={admin:'管理员',operator:'操作员',viewer:'只读成员'};
|
||||
const statusMap={running:['处理中','blue'],success:['已完成','green'],error:['失败','red'],interrupted:['已中断','orange']};
|
||||
let currentUser=null,settings=null,currentView='overview',overview=null,refreshTimer=null,viewGeneration=0;
|
||||
const views={assistant:['ZCode 助手','对话查询运行状态、分析异常与执行受控恢复'],storage:['存储服务器','配置 SMB 共享目录、检查连接与管理 PDF 归档'],notifications:['业务通知','配置来源字段、产业接口人与通知队列'],overview:['工作总览','团队工作一目了然,每一次协作都有记录'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['订单匹配规则','管理订单筛选和匹配条件'],schedule:['发送计划','设置每日两个发送时间和批次整理方式'],templates:['模板与收件群组','预览确认发信模板,维护产品线收件群组'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']};
|
||||
async function api(route,body) {
|
||||
const response=await fetch('/api'+route,{credentials:'same-origin',keepalive:route.endsWith('/login/close'),method:body===undefined?'GET':'POST',headers:body?{'Content-Type':'application/json'}:{},body:body?JSON.stringify(body):undefined});
|
||||
const views={health:['系统健康','查看服务守护、登录自启和各模块最近检查结果'],assistant:['ZCode 助手','对话查询运行状态、分析异常与执行受控恢复'],storage:['存储服务器','配置 SMB 共享目录、检查连接与管理 PDF 归档'],notifications:['业务通知','配置来源字段、产业接口人与通知队列'],overview:['工作总览','团队工作一目了然,每一次协作都有记录'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['订单匹配规则','管理订单筛选和匹配条件'],schedule:['发送计划','设置每日两个发送时间和批次整理方式'],templates:['模板与收件群组','预览确认发信模板,维护产品线收件群组'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']};
|
||||
async function api(route,body,{signal}={}) {
|
||||
const response=await fetch('/api'+route,{signal,credentials:'same-origin',keepalive:route.endsWith('/login/close'),method:body===undefined?'GET':'POST',headers:body?{'Content-Type':'application/json'}:{},body:body?JSON.stringify(body):undefined});
|
||||
const result=await response.json();
|
||||
if(!response.ok){if(response.status===401 && currentUser){currentUser=null;++viewGeneration;window.BpmLogin?.dispose();await boot();}throw new Error(result.error || '操作失败,请重试。');}
|
||||
return result;
|
||||
@@ -19,7 +19,7 @@ function notify(message,type='success') {
|
||||
function badge(status){const [label,color]=statusMap[status] || ['待处理','secondary'];return `<span class="badge bg-${color}-lt">${label}</span>`;}
|
||||
function navItem(id,symbol){return `<li class="nav-item"><a class="nav-link ${currentView===id?'active':''}" href="#${id}" data-view="${id}"><span class="nav-link-icon" aria-hidden="true">${symbol}</span><span class="nav-link-title">${views[id][0]}</span></a></li>`;}
|
||||
function shell() {
|
||||
root.innerHTML=`<div class="page"><aside class="navbar navbar-vertical navbar-expand-lg"><div class="container-fluid"><button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#sidebar-menu" aria-controls="sidebar-menu" aria-label="展开菜单"><span class="navbar-toggler-icon"></span></button><a class="navbar-brand" href="#overview"><span class="brand-mark">单</span>订单通知中心</a><div class="collapse navbar-collapse" id="sidebar-menu"><ul class="navbar-nav pt-lg-3">${navItem('overview','▦')}${navItem('calendar','▣')}${navItem('exceptions','☷')}${navItem('bpm','⇄')}${navItem('supervisor','◎')}${navItem('assistant','Z')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">订单与通知</span></li>${navItem('records','≡')}${navItem('rules','⌕')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">通知配置</span></li>${navItem('schedule','◷')}${navItem('templates','✉')}${navItem('mail','@')}${navItem('storage','▤')}${navItem('notifications','✉')}${navItem('connections','⇄')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">团队管理</span></li>${currentUser.role==='admin'?navItem('users','♙'):''}${navItem('audit','☷')}</ul><div class="mt-auto p-3 text-secondary small d-none d-lg-block">团队共享工作台<br><span class="sidebar-status"><i></i> 本地运行 · 北京时间</span></div></div></div></aside><header class="navbar d-print-none"><div class="container-xl"><div class="d-flex gap-2 flex-wrap"><span class="badge bg-yellow-lt">自动处理未启用</span></div><div class="navbar-nav flex-row order-md-last ms-auto align-items-center gap-3"><div><div class="account-name">${esc(currentUser.username)}</div><div class="small text-secondary">${roles[currentUser.role]}</div></div><button class="btn btn-sm" id="logout">退出</button></div></div></header><div class="page-wrapper"><div class="page-header d-print-none"><div class="container-xl"><div class="row g-2 align-items-center"><div class="col"><div class="page-pretitle">订单通知自动化</div><h1 class="page-title" id="view-title"></h1><div class="text-secondary mt-2" id="view-description"></div></div><div class="col-auto ms-auto"><button class="btn" id="refresh">刷新数据</button></div></div></div></div><div class="page-body"><div class="container-xl" id="content"></div></div><footer class="footer footer-transparent d-print-none"><div class="container-xl"><div class="row text-secondary align-items-center"><div class="col">订单通知中心 · 局域网工作台</div><div class="col-auto">UI 基于 <a href="https://tabler.io" target="_blank" rel="noreferrer">Tabler</a> · MIT</div></div></div></footer></div></div>`;
|
||||
root.innerHTML=`<div class="page"><aside class="navbar navbar-vertical navbar-expand-lg"><div class="container-fluid"><button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#sidebar-menu" aria-controls="sidebar-menu" aria-label="展开菜单"><span class="navbar-toggler-icon"></span></button><a class="navbar-brand" href="#overview"><span class="brand-mark">单</span>订单通知中心</a><div class="collapse navbar-collapse" id="sidebar-menu"><ul class="navbar-nav pt-lg-3">${navItem('overview','▦')}${navItem('calendar','▣')}${navItem('exceptions','☷')}${navItem('bpm','⇄')}${navItem('health','◉')}${navItem('supervisor','◎')}${navItem('assistant','Z')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">订单与通知</span></li>${navItem('records','≡')}${navItem('rules','⌕')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">通知配置</span></li>${navItem('schedule','◷')}${navItem('templates','✉')}${navItem('mail','@')}${navItem('storage','▤')}${navItem('notifications','✉')}${navItem('connections','⇄')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">团队管理</span></li>${currentUser.role==='admin'?navItem('users','♙'):''}${navItem('audit','☷')}</ul><div class="mt-auto p-3 text-secondary small d-none d-lg-block">团队共享工作台<br><span class="sidebar-status"><i></i> 本地运行 · 北京时间</span></div></div></div></aside><header class="navbar d-print-none"><div class="container-xl"><div class="d-flex gap-2 flex-wrap"><span class="badge bg-yellow-lt">自动处理未启用</span></div><div class="navbar-nav flex-row order-md-last ms-auto align-items-center gap-3"><div><div class="account-name">${esc(currentUser.username)}</div><div class="small text-secondary">${roles[currentUser.role]}</div></div><button class="btn btn-sm" id="logout">退出</button></div></div></header><div class="page-wrapper"><div class="page-header d-print-none"><div class="container-xl"><div class="row g-2 align-items-center"><div class="col"><div class="page-pretitle">订单通知自动化</div><h1 class="page-title" id="view-title"></h1><div class="text-secondary mt-2" id="view-description"></div></div><div class="col-auto ms-auto"><button class="btn" id="refresh">刷新数据</button></div></div></div></div><div class="page-body"><div class="container-xl" id="content"></div></div><footer class="footer footer-transparent d-print-none"><div class="container-xl"><div class="row text-secondary align-items-center"><div class="col">订单通知中心 · 局域网工作台</div><div class="col-auto">UI 基于 <a href="https://tabler.io" target="_blank" rel="noreferrer">Tabler</a> · MIT</div></div></div></footer></div></div>`;
|
||||
document.querySelector('#logout').onclick=async()=>{++viewGeneration;await window.BpmLogin?.dispose();await api('/logout',{});currentUser=null;clearInterval(refreshTimer);await boot();};
|
||||
document.querySelector('#refresh').onclick=()=>renderView().catch(error=>notify(error.message,'danger'));
|
||||
document.querySelectorAll('[data-view]').forEach(link=>link.onclick=()=>{document.querySelector('#sidebar-menu').classList.remove('show');});
|
||||
@@ -77,7 +77,7 @@ async function renderView() {
|
||||
document.querySelectorAll('[data-view]').forEach(link=>link.classList.toggle('active',link.dataset.view===currentView));
|
||||
document.querySelector('#view-title').textContent=views[currentView][0];document.querySelector('#view-description').textContent=views[currentView][1];
|
||||
const container=document.querySelector('#content');container.innerHTML='<div class="card"><div class="card-body text-secondary">正在加载…</div></div>';
|
||||
const fn={assistant:window.AssistantViews?.render,storage:window.StorageViews?.render,notifications:window.NotificationViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,supervisor:window.WorkspaceViews?.supervisor,records:viewRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,connections:viewConnections,users:viewUsers,audit:viewAudit,rules:viewRules}[currentView];
|
||||
const fn={health:window.HealthViews?.render,assistant:window.AssistantViews?.render,storage:window.StorageViews?.render,notifications:window.NotificationViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,supervisor:window.WorkspaceViews?.supervisor,records:viewRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,connections:viewConnections,users:viewUsers,audit:viewAudit,rules:viewRules}[currentView];
|
||||
try{await fn(container,isActive);}catch(error){if(isActive())container.innerHTML=`<div class="alert alert-danger">${esc(error.message)}</div>`;}
|
||||
}
|
||||
async function authScreen() {
|
||||
@@ -85,7 +85,7 @@ async function authScreen() {
|
||||
root.innerHTML=`<div class="page page-center"><div class="container-tight py-4"><div class="text-center mb-4"><span class="avatar bg-blue text-white mb-3">单</span><h1 class="h2">订单通知中心</h1><div class="text-secondary">团队协同工作台</div></div><form class="card card-md" id="login-form"><div class="card-body"><h2 class="h2 text-center mb-4">${initialize?'创建管理员账号':'登录工作台'}</h2>${setup.required && !setup.canSetup?'<div class="alert alert-info">请先由部署机在本机地址创建管理员,再为团队开通账号。</div>':''}<div class="mb-3"><label class="form-label" for="username">账号</label><input class="form-control" id="username" autocomplete="username" required ${initialize?'minlength="3" maxlength="40" pattern="[a-zA-Z0-9_.-]+"':''}></div><div class="mb-3"><label class="form-label" for="password">密码</label><input class="form-control" type="password" id="password" autocomplete="${initialize?'new-password':'current-password'}" required ${initialize?'minlength="12" maxlength="128"':''}>${initialize?'<div class="form-hint">设置至少 12 位密码,后续可在看板中创建同事账号。</div>':''}</div><div class="text-danger mb-3" id="auth-error" role="alert"></div><div class="form-footer"><button class="btn btn-primary w-100" type="submit" ${setup.required && !setup.canSetup?'disabled':''}>${initialize?'创建账号并进入':'登录'}</button></div></div></form><p class="text-center text-secondary small mt-4 login-note">${initialize?'首次设置仅允许从部署机访问。':'使用管理员分配的账号访问。'}<br>界面基于 Tabler 开源模板</p></div></div>`;
|
||||
document.querySelector('#login-form').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button[type="submit"]');button.disabled=true;try{const result=await api(initialize?'/bootstrap':'/login',{username:document.querySelector('#username').value,password:document.querySelector('#password').value});currentUser=result.user;enter();}catch(error){document.querySelector('#auth-error').textContent=error.message;}finally{button.disabled=false;}};
|
||||
}
|
||||
function enter(){window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();renderView();clearInterval(refreshTimer);refreshTimer=setInterval(()=>{if(currentUser && currentView==='overview' && !document.hidden){const generation=++viewGeneration;viewOverview(document.querySelector('#content'),()=>generation===viewGeneration && !!currentUser && currentView==='overview').catch(()=>{});}},15000);}
|
||||
function enter(){window.HealthViews?.configure({api,esc,formatDate});window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();renderView();clearInterval(refreshTimer);refreshTimer=setInterval(()=>{if(currentUser && currentView==='overview' && !document.hidden){const generation=++viewGeneration;viewOverview(document.querySelector('#content'),()=>generation===viewGeneration && !!currentUser && currentView==='overview').catch(()=>{});}},15000);}
|
||||
async function boot(){try{const setup=await api('/bootstrap/status');currentUser=(await api('/me')).user;enter();}catch{await authScreen();}}
|
||||
window.addEventListener('pagehide',()=>{window.BpmLogin?.dispose({unload:true});});
|
||||
window.addEventListener('hashchange',()=>{if(currentUser)renderView();});
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
(() => {
|
||||
'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};
|
||||
})();
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>订单通知中心</title><link href="/vendor/tabler.css" rel="stylesheet"><link href="/app.css" rel="stylesheet"></head>
|
||||
<body><div id="app"><div class="page page-center"><div class="container-tight py-4"><div class="card"><div class="card-body text-center">正在连接订单通知中心…</div></div></div></div></div><script src="/vendor/tabler.js" defer></script><script src="/bpm.js" defer></script><script src="/workspace.js" defer></script><script src="/mail.js" defer></script><script src="/orders.js" defer></script><script src="/storage-preview-host.js" defer></script><script src="/storage.js" defer></script><script src="/notifications.js" defer></script><script src="/assistant.js" defer></script><script src="/app.js" defer></script></body></html>
|
||||
<body><div id="app"><div class="page page-center"><div class="container-tight py-4"><div class="card"><div class="card-body text-center">正在连接订单通知中心…</div></div></div></div></div><script src="/vendor/tabler.js" defer></script><script src="/bpm.js" defer></script><script src="/workspace.js" defer></script><script src="/mail.js" defer></script><script src="/orders.js" defer></script><script src="/storage-preview-host.js" defer></script><script src="/storage.js" defer></script><script src="/notifications.js" defer></script><script src="/health.js" defer></script><script src="/assistant.js" defer></script><script src="/app.js" defer></script></body></html>
|
||||
+1
-1
@@ -67,7 +67,7 @@ window.WorkspaceViews=(()=>{
|
||||
|
||||
async function supervisor(container,isActive=()=>true){
|
||||
const data=await api('/workspace');if(!isActive())return;let draft=data.supervisor;const assistantStatus=await api('/assistant').catch(()=>null);if(!isActive())return;
|
||||
container.innerHTML=`${readonly(admin())}<div data-feedback hidden role="alert"></div><div class="workspace-grid"><form class="card" id="supervisor-form"><div class="card-header"><h2 class="card-title">监管设置</h2><span class="badge bg-blue-lt ms-auto">未启用</span></div><div class="card-body"><fieldset ${lock(admin())}><div class="mb-3"><label class="form-label" for="supervisor-owner">默认负责人</label><select class="form-select" id="supervisor-owner">${memberOptions(data.members,draft.defaultOwner)}</select></div><div class="mb-3"><label class="form-label" for="supervisor-channel">通知方式</label><select class="form-select" id="supervisor-channel"><option value="none" ${draft.notifyChannel==='none'?'selected':''}>不通知</option><option value="manual" ${draft.notifyChannel==='manual'?'selected':''}>人工通知</option></select></div><div><label class="form-label" for="supervisor-attempts">重试上限</label><select class="form-select" id="supervisor-attempts">${[0,1,2,3].map(n=>`<option value="${n}" ${draft.maxAttempts===n?'selected':''}>${n} 次${n===0?'(不重试)':''}</option>`).join('')}</select></div></fieldset></div><div class="card-footer d-flex align-items-center"><span class="text-secondary small">整个团队共用</span><button class="btn btn-primary ms-auto" type="submit" ${lock(admin())}>保存设置</button></div></form><div><section class="card"><div class="card-header"><h3 class="card-title">业务自动处理</h3></div><div class="card-body"><div class="capability-row"><span class="status-dot status-green"></span><div><strong>异常管理</strong><div class="small text-secondary">认领、转交与处理记录</div></div></div><div class="capability-row"><span class="status-dot status-yellow"></span><div><strong>ZCode · ${assistantStatus?.settings.enabled?'已配置':'待配置'}</strong><div class="small mt-1"><a href="#assistant">打开 ZCode 助手</a></div></div></div><div class="capability-row"><span class="status-dot status-yellow"></span><div><strong>自动通知 · 未启用</strong></div></div></div></section></div></div>`;
|
||||
container.innerHTML=`<div class="alert alert-info"><a href="#health">打开系统健康</a> 查看服务守护、登录自启和最近检查结果。</div>${readonly(admin())}<div data-feedback hidden role="alert"></div><div class="workspace-grid"><form class="card" id="supervisor-form"><div class="card-header"><h2 class="card-title">监管设置</h2><span class="badge bg-blue-lt ms-auto">未启用</span></div><div class="card-body"><fieldset ${lock(admin())}><div class="mb-3"><label class="form-label" for="supervisor-owner">默认负责人</label><select class="form-select" id="supervisor-owner">${memberOptions(data.members,draft.defaultOwner)}</select></div><div class="mb-3"><label class="form-label" for="supervisor-channel">通知方式</label><select class="form-select" id="supervisor-channel"><option value="none" ${draft.notifyChannel==='none'?'selected':''}>不通知</option><option value="manual" ${draft.notifyChannel==='manual'?'selected':''}>人工通知</option></select></div><div><label class="form-label" for="supervisor-attempts">重试上限</label><select class="form-select" id="supervisor-attempts">${[0,1,2,3].map(n=>`<option value="${n}" ${draft.maxAttempts===n?'selected':''}>${n} 次${n===0?'(不重试)':''}</option>`).join('')}</select></div></fieldset></div><div class="card-footer d-flex align-items-center"><span class="text-secondary small">整个团队共用</span><button class="btn btn-primary ms-auto" type="submit" ${lock(admin())}>保存设置</button></div></form><div><section class="card"><div class="card-header"><h3 class="card-title">业务自动处理</h3></div><div class="card-body"><div class="capability-row"><span class="status-dot status-green"></span><div><strong>异常管理</strong><div class="small text-secondary">认领、转交与处理记录</div></div></div><div class="capability-row"><span class="status-dot status-yellow"></span><div><strong>ZCode · ${assistantStatus?.settings.enabled?'已配置':'待配置'}</strong><div class="small mt-1"><a href="#assistant">打开 ZCode 助手</a></div></div></div><div class="capability-row"><span class="status-dot status-yellow"></span><div><strong>自动通知 · 未启用</strong></div></div></div></section></div></div>`;
|
||||
container.querySelector('#supervisor-form').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button[type=submit]');button.disabled=true;try{const result=await api('/supervisor',{version:draft.version,defaultOwner:container.querySelector('#supervisor-owner').value,notifyChannel:container.querySelector('#supervisor-channel').value,maxAttempts:Number(container.querySelector('#supervisor-attempts').value)});if(!isActive())return;draft=result.supervisor||result;feedback(container,'设置已保存。','success');}catch(error){if(isActive())feedback(container,error.message);}finally{if(isActive())button.disabled=!admin();}};
|
||||
}
|
||||
return {configure,overview,calendar,exceptions,bpm,supervisor,activityText};
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
setlocal
|
||||
where node.exe >nul 2>nul
|
||||
if errorlevel 1 goto bundled
|
||||
node.exe "%~dp0src\server.cjs"
|
||||
node.exe "%~dp0scripts\service.cjs" start
|
||||
goto finished
|
||||
:bundled
|
||||
set "ORDER_NODE=%USERPROFILE%\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe"
|
||||
if not exist "%ORDER_NODE%" goto missing
|
||||
"%ORDER_NODE%" "%~dp0src\server.cjs"
|
||||
"%ORDER_NODE%" "%~dp0scripts\service.cjs" start
|
||||
goto finished
|
||||
:missing
|
||||
echo Node.js 22+ is required. Install from https://nodejs.org
|
||||
|
||||
Reference in new issue
Block a user