挂到 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 契约。
254 lines
7.5 KiB
TypeScript
254 lines
7.5 KiB
TypeScript
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(),
|
||
};
|
||
}
|
||
}
|