feat(center): 新增通知实时推送 WS /ws/notifications,管理台建单秒达

挂到 Koa 同一 http.Server 的 upgrade 事件(复用 8800,不占新端口、不改 nginx),X-API-Token 握手鉴权,帧格式对齐执行机 notifier.js;新建通知后立即广播(target=all / account),GET /api/notifications 轮询继续兜底。

连接状态放模块作用域(生命周期挂载与请求内推送的 provider 实例不保证同一个),心跳 30s 清理半开连接;src/index.ts 补导出(bundle 关闭 moduleDetector 时必须显式导出)。

部署 SOP 增加 WS 端点探针,客户端交接文档补 /ws/notifications 契约。
This commit is contained in:
2026-11-10 16:38:00 +08:00
parent 41ffbf30d3
commit 066bbe4989
6 changed files with 296 additions and 2 deletions
@@ -22,6 +22,7 @@ import * as upload from '@midwayjs/upload';
// import * as rpc from '@cool-midway/rpc';
import { FileserverMonitorService } from './modules/center/service/fileserver-monitor';
import { CenterLogService } from './modules/center/service/logstore';
import { CenterNotifyWsService } from './modules/center/service/notify-ws';
@Configuration({
imports: [
@@ -77,7 +78,27 @@ export class MainConfiguration {
logStore.start();
}
/** HTTP server 起来后挂载通知 WebSocket(与 8800 共用端口,执行机 notifier.js 直连) */
async onServerReady() {
try {
const framework: any = (this.app as any).getFramework?.();
const server = typeof framework?.getServer === 'function' ? framework.getServer() : null;
const wsService = await this.app.getApplicationContext().getAsync(CenterNotifyWsService);
if (!wsService.attach(server)) {
console.warn('[notify-ws] 未取到 http.Server,通知 WS 未启用(轮询兜底仍然可用)');
}
} catch (e: any) {
console.warn(`[notify-ws] 挂载异常:${e?.message || e}(轮询兜底仍然可用)`);
}
}
async onStop() {
try {
const wsService = await this.app.getApplicationContext().getAsync(CenterNotifyWsService);
wsService.stop();
} catch (e) {
/* ignore */
}
try {
const monitor = await this.app.getApplicationContext().getAsync(FileserverMonitorService);
monitor.stop();
@@ -1,5 +1,5 @@
/** This file generated by @midwayjs/bundle-helper */
␍export { MainConfiguration as Configuration } from './configuration';
export { MainConfiguration as Configuration } from './configuration';
export * from './comm/path';
export * from './comm/port';
export * from './comm/utils';
@@ -41,6 +41,7 @@ export * from './modules/center/comm/conf';
export * from './modules/center/service/crypto';
export * from './modules/center/service/dingtalk';
export * from './modules/center/service/notify';
export * from './modules/center/service/notify-ws';
export * from './modules/center/service/fileserver-monitor';
export * from './modules/center/service/logstore';
export * from './modules/center/service/rbac';
@@ -15,6 +15,7 @@ import { ClientCredEntity } from '../../entity/account';
import { CenterAuthService, ApiError } from '../../service/auth';
import { rsaEncrypt } from '../../service/crypto';
import { CenterLogService } from '../../service/logstore';
import { CenterNotifyWsService } from '../../service/notify-ws';
import { PKG_DIR, SHELL_DIR, AVATAR_DIR } from '../../comm/conf';
import { pageBounds, readUploadFile } from '../../comm/util';
@@ -39,6 +40,9 @@ export class AdminOpsController extends BaseController {
@Inject()
centerLogService: CenterLogService;
@Inject()
centerNotifyWsService: CenterNotifyWsService;
@InjectEntityModel(PluginEntity) pluginRepo: Repository<PluginEntity>;
@InjectEntityModel(PluginVersionEntity) pluginVersionRepo: Repository<PluginVersionEntity>;
@InjectEntityModel(AccountPluginEntity) accountPluginRepo: Repository<AccountPluginEntity>;
@@ -552,7 +556,16 @@ export class AdminOpsController extends BaseController {
'INSERT INTO notifications(title, content, level, target, account, expires_at) VALUES (?,?,?,?,?,?)',
[title, (b?.content || '').trim(), b?.level, b?.target, (b?.account || '').trim(), b?.expires_at ? String(b.expires_at).replace('T', ' ').slice(0, 19) : null]);
await this.centerAuthService.audit(login, 'notify-create', `通知 #${r.insertId} ${title} → ${b?.target}`);
return { ok: true, id: r.insertId, title, target: b?.target, pushed: 0 };
// 实时推送:在线执行机秒达;未在线的由 GET /api/notifications 轮询兜底
const pushed = this.centerNotifyWsService.pushNotification({
id: r.insertId,
title,
content: (b?.content || '').trim(),
level: b?.level,
target: b?.target,
account: b?.target === 'account' ? (b?.account || '').trim() : '',
});
return { ok: true, id: r.insertId, title, target: b?.target, pushed };
}
@Put('/notifications/:nid')
@@ -0,0 +1,253 @@
import { Provide } from '@midwayjs/core';
import type { IncomingMessage, Server } from 'http';
import type { Duplex } from 'stream';
// ws 未自带类型声明(项目未装 @types/ws),用 require 引入,避免多一个构建期依赖
const { WebSocketServer } = require('ws');
export const NOTIFY_WS_PATH = '/ws/notifications';
const HEARTBEAT_MS = 30 * 1000;
const WS_OPEN = 1;
function log(msg: string) {
console.log(`[notify-ws] ${msg}`);
}
function warn(msg: string) {
console.warn(`[notify-ws] ${msg}`);
}
export interface NotifyFrame {
id: number;
title: string;
content?: string;
level?: string;
target?: string;
account?: string;
}
// ==================== 连接状态(模块级单例) ====================
// 挂载发生在上游生命周期、推送发生在控制器请求里,两处取到的 provider 实例不保证同一个,
// 因此状态放在模块作用域,保证「谁调都是同一份连接表」,与容器 scope 无关。
let WSS: any = null;
let HEARTBEAT: NodeJS.Timeout | null = null;
// account → 该账号当前在线的连接集合(同账号多台执行机/多次连接都保留)
const CLIENTS: Map<string, Set<any>> = new Map();
function online(): number {
let n = 0;
for (const set of CLIENTS.values()) n += set.size;
return n;
}
function rejectUpgrade(socket: Duplex, code: number, text: string) {
try {
socket.write(`HTTP/1.1 ${code} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
} catch (e) {
/* 忽略 */
}
try {
socket.destroy();
} catch (e) {
/* 忽略 */
}
}
function drop(account: string, ws: any) {
const set = CLIENTS.get(account);
if (!set) return;
if (!set.delete(ws)) return;
if (!set.size) {
CLIENTS.delete(account);
log(`连接断开(${account}),当前 ${online()} 个连接`);
}
}
/** 心跳:30s 未回 pong 视为半开连接,terminate 掉让客户端重连 */
function sweep() {
for (const [account, set] of CLIENTS) {
for (const ws of [...set]) {
if (ws.isAlive === false) {
try {
ws.terminate();
} catch (e) {
/* 忽略 */
}
drop(account, ws);
continue;
}
ws.isAlive = false;
try {
ws.ping();
} catch (e) {
/* 忽略,下轮按 isAlive 清理 */
}
}
}
}
function onConnection(ws: any, req: IncomingMessage) {
const account = String(ws.__account || '');
let set = CLIENTS.get(account);
if (!set) {
set = new Set();
CLIENTS.set(account, set);
}
set.add(ws);
ws.isAlive = true;
ws.on('pong', () => {
ws.isAlive = true;
});
// 客户端不上行业务消息(ws 库默认自动回 pong),忽略即可
ws.on('message', () => {});
ws.on('close', () => drop(account, ws));
ws.on('error', () => drop(account, ws));
log(`连接建立(${account},${req.socket?.remoteAddress || '-'}),当前 ${online()} 个连接`);
}
function handleUpgrade(wss: any, req: IncomingMessage, socket: Duplex, head: Buffer) {
let url: URL;
try {
url = new URL(req.url || '/', 'http://localhost');
} catch (e) {
return rejectUpgrade(socket, 400, 'Bad Request');
}
// 本服务只接通知通道;其它 upgrade 请求直接拒绝(避免 socket 悬挂)
if (url.pathname !== NOTIFY_WS_PATH) return rejectUpgrade(socket, 404, 'Not Found');
// 机器凭证:与 REST 侧 checkApiToken 一致(CONTROLPLANE_TOKEN 为空时不校验)
const token = (process.env.CONTROLPLANE_TOKEN || '').trim();
if (token) {
const got = String(req.headers['x-api-token'] || '').trim();
if (got !== token) {
warn(`拒绝连接:X-API-Token 无效(${req.socket?.remoteAddress || '-'})`);
return rejectUpgrade(socket, 401, 'Unauthorized');
}
}
const account = (url.searchParams.get('account') || '').trim();
if (!account) return rejectUpgrade(socket, 400, 'Missing account');
wss.handleUpgrade(req, socket, head, (ws: any) => {
ws.__account = account;
wss.emit('connection', ws, req);
});
}
/**
* 通知实时推送(WebSocket `/ws/notifications`)—— 对齐执行机壳 `electron/notifier.js` 契约:
* - 连接:`ws://<控制面>/ws/notifications?account=<账号>`,握手头 `X-API-Token`(CONTROLPLANE_TOKEN,非空时强制)
* - 下行帧:`{"type":"notify","notification":{id,title,content,level,target,account}}`
* - 与 `GET /api/notifications` 轮询兜底并存;客户端按通知 id 去重,重复推送无副作用
*
* 实现:挂到 Koa 的同一个 http.Server(8800)的 `upgrade` 事件上,不额外占端口;
* 进程内广播(现网 systemd 单实例);若将来多实例部署需换 Redis pub/sub。
*/
@Provide()
export class CenterNotifyWsService {
/** 挂载到已启动的 http.Server(onServerReady 阶段调用,幂等) */
attach(server: Server): boolean {
if (WSS) return true;
if (!server) {
warn('挂载失败:未拿到 http.Server');
return false;
}
const wss = new WebSocketServer({ noServer: true });
WSS = wss;
server.on('upgrade', (req: IncomingMessage, socket: Duplex, head: Buffer) => {
try {
handleUpgrade(wss, req, socket, head);
} catch (e: any) {
warn(`upgrade 处理异常:${e?.message || e}`);
rejectUpgrade(socket, 400, 'Bad Request');
}
});
wss.on('connection', (ws: any, req: IncomingMessage) => onConnection(ws, req));
HEARTBEAT = setInterval(() => sweep(), HEARTBEAT_MS);
HEARTBEAT.unref?.();
log(`已挂载 ${NOTIFY_WS_PATH}(与 HTTP 共用端口)`);
return true;
}
stop(): void {
if (HEARTBEAT) {
clearInterval(HEARTBEAT);
HEARTBEAT = null;
}
for (const set of CLIENTS.values()) {
for (const ws of set) {
try {
ws.terminate();
} catch (e) {
/* 忽略 */
}
}
}
CLIENTS.clear();
if (WSS) {
try {
WSS.close();
} catch (e) {
/* 忽略 */
}
WSS = null;
}
}
/**
* 推送一条通知(管理台新建通知时调用)。
* @returns 实际送达的连接数(0 = 无在线执行机,客户端下次轮询会兜底拿到)
*/
pushNotification(n: NotifyFrame): number {
const id = Number(n?.id);
if (!id) return 0;
const total = online();
if (!WSS || !total) {
log(`通知 #${id} 无在线连接,跳过实时推送(等客户端轮询兜底)`);
return 0;
}
const frame = JSON.stringify({
type: 'notify',
notification: {
id,
title: n.title || '',
content: n.content || '',
level: n.level || 'info',
target: n.target || 'all',
account: n.account || '',
},
});
const sets: Set<any>[] = [];
if ((n.target || 'all') === 'account') {
const hit = CLIENTS.get(String(n.account || '').trim());
if (hit) sets.push(hit);
} else {
for (const set of CLIENTS.values()) sets.push(set);
}
let sent = 0;
for (const set of sets) {
for (const ws of set) {
if (ws.readyState !== WS_OPEN) continue;
try {
ws.send(frame);
sent++;
} catch (e) {
/* 单条失败不影响其它连接 */
}
}
}
log(`通知 #${id} 实时推送 → ${sent}/${total} 个连接(target=${n.target || 'all'})`);
return sent;
}
/** 运行状态(运维排查用) */
stats() {
return {
path: NOTIFY_WS_PATH,
mounted: !!WSS,
accounts: CLIENTS.size,
connections: online(),
};
}
}
@@ -168,6 +168,7 @@ powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build-python-env.ps1
| 定时/流程备份 | `POST/GET /api/schedules/backup`(同一槽位含 `schedules` + `flows`) |
| 运行备注 | `GET/POST /api/plugin-notes` |
| 通知 / 头像 / 文件源列表 | `GET /api/notifications`、`GET /api/avatar/{account}`、`GET /api/file-sources/{category}` |
| 通知实时推送(WS) | `WS /ws/notifications?account=<账号>`(握手头 `X-API-Token`),下行帧 `{"type":"notify","notification":{id,title,content,level,target,account}}`;与 HTTP 共用 8800 端口,连不上时仍由 `GET /api/notifications` 60s 轮询兜底 |
| 凭证下发 | `POST /api/creds/register`、`GET /api/creds` |
| 钉钉扫码 | `GET /api/dingtalk/login-url`、`POST /auth/exchange`(钉钉 code → 建号 + 云端 token) |
@@ -143,6 +143,11 @@ curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8800/api/shell/version
curl -s http://127.0.0.1:8090/ | head -c 200
# 文件服务器
curl -s http://127.0.0.1:8802/
# 通知 WS 端点已挂载(未带票据应为 401;返回 404 说明该版本后端还没有 /ws/notifications)
curl -s -o /dev/null -w '%{http_code}\n' \
-H 'Connection: Upgrade' -H 'Upgrade: websocket' -H 'Sec-WebSocket-Version: 13' \
-H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' \
'http://127.0.0.1:8800/ws/notifications?account=test'
```
本机发版 CLI 预检: