feat(onebot): share HTTP listeners with WebSocket clients
Add an opt-in HTTP server setting that accepts OneBot WebSocket connections on the same port and access token while preserving standalone WebSocket server configurations. Reuse the existing connection lifecycle for authentication, roles, events, heartbeat, streaming actions, token rotation, and shutdown. Expose the switch in WebUI and persist it through strict configuration validation and restore paths. Refs: #281
This commit is contained in:
12 files changed
+859
-158
No files matched your search
@@ -1,4 +1,5 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { WebSocketServer } from '@snowluma/websocket';
|
||||
import {
|
||||
createServer,
|
||||
type IncomingMessage,
|
||||
@@ -11,24 +12,34 @@ import type { ApiResponse, HttpServerNetwork, JsonObject, JsonValue } from '../t
|
||||
import { type StreamSink, wrapStreamFrame, wrapStreamTerminal } from '../streaming';
|
||||
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, normalizePath } from './utils';
|
||||
import { WsServerConnections } from './ws-server-connections';
|
||||
|
||||
const moduleLog = createLogger('OneBot.HTTP');
|
||||
|
||||
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
|
||||
private server: Server | null = null;
|
||||
private webSocketServer: WebSocketServer | null = null;
|
||||
private listening = false;
|
||||
private closePromise: Promise<void> | null = null;
|
||||
private acceptingActions = false;
|
||||
private readonly inFlightActions = new Set<Promise<void>>();
|
||||
private readonly webSocketConnections: WsServerConnections;
|
||||
|
||||
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx, moduleLog);
|
||||
this.webSocketConnections = new WsServerConnections(name, config, ctx, this.log, {
|
||||
frame: (event, options) => this.metaFrame(event, options),
|
||||
bootstrap: (options) => this.bootstrapMetaFrames(options),
|
||||
});
|
||||
}
|
||||
|
||||
async open(): Promise<void> {
|
||||
if (this.isEnabled && this.listening) return;
|
||||
if (this.config.enabled === false) return;
|
||||
if (this.server) throw new Error(`HTTP adapter [${this.name}] still owns a previous server`);
|
||||
if (this.webSocketServer) {
|
||||
throw new Error(`HTTP adapter [${this.name}] still owns a previous WebSocket upgrade handler`);
|
||||
}
|
||||
await this.startServer();
|
||||
this.isEnabled = true;
|
||||
this.clearApplyFailure();
|
||||
@@ -36,15 +47,27 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.closePromise) return this.closePromise;
|
||||
if (!this.isEnabled && !this.server && this.inFlightActions.size === 0) return;
|
||||
if (
|
||||
!this.isEnabled &&
|
||||
!this.server &&
|
||||
!this.webSocketServer &&
|
||||
this.inFlightActions.size === 0 &&
|
||||
!this.webSocketConnections.hasInFlightActions
|
||||
) return;
|
||||
const wasEnabled = this.isEnabled;
|
||||
const wasListening = this.listening;
|
||||
const wasAcceptingActions = this.acceptingActions;
|
||||
const wasAcceptingWebSocketActions = this.webSocketConnections.isAcceptingActions;
|
||||
this.acceptingActions = false;
|
||||
this.webSocketConnections.stopAccepting();
|
||||
this.isEnabled = false;
|
||||
this.listening = false;
|
||||
const server = this.server;
|
||||
const release = server
|
||||
const webSocketServer = this.webSocketServer;
|
||||
const webSocketDrain = webSocketServer
|
||||
? this.webSocketConnections.closeConnections()
|
||||
: Promise.resolve();
|
||||
const releaseHttp = server
|
||||
? new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => {
|
||||
if (error && !isAlreadyClosedError(error)) reject(error);
|
||||
@@ -52,17 +75,48 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
});
|
||||
})
|
||||
: Promise.resolve();
|
||||
const attempt = Promise.all([release, Promise.all(this.inFlightActions)]).then(() => undefined);
|
||||
let httpReleased = false;
|
||||
const attempt = (async () => {
|
||||
// Close upgraded sockets so Node can release the owning HTTP listener,
|
||||
// but keep the upgrade handler attached until that release succeeds.
|
||||
// If HTTP close fails while the listener is still live, accepting can be
|
||||
// restored on the same handler; no partially released resource is
|
||||
// reported as healthy.
|
||||
await Promise.all([
|
||||
releaseHttp,
|
||||
Promise.all(this.inFlightActions),
|
||||
webSocketDrain,
|
||||
]);
|
||||
httpReleased = true;
|
||||
if (this.server === server) this.server = null;
|
||||
|
||||
if (webSocketServer) {
|
||||
const releaseWebSocket = new Promise<void>((resolve, reject) => {
|
||||
webSocketServer.close((error) => {
|
||||
if (error && !isAlreadyClosedError(error)) reject(error);
|
||||
else resolve();
|
||||
});
|
||||
});
|
||||
await Promise.all([
|
||||
releaseWebSocket,
|
||||
this.webSocketConnections.closeConnections(),
|
||||
]);
|
||||
if (this.webSocketServer === webSocketServer) this.webSocketServer = null;
|
||||
}
|
||||
})();
|
||||
this.closePromise = attempt;
|
||||
try {
|
||||
await attempt;
|
||||
if (this.server === server) this.server = null;
|
||||
} catch (error) {
|
||||
// A failed close callback cannot prove the listener was released. Keep
|
||||
// ownership and live-state truth so shutdown/reconcile can retry it.
|
||||
this.isEnabled = wasEnabled;
|
||||
this.listening = wasListening;
|
||||
this.acceptingActions = wasAcceptingActions;
|
||||
if (!httpReleased && server?.listening === true) {
|
||||
// A failed HTTP close callback cannot prove the listener was released.
|
||||
// The upgrade handler is still attached, so the old ingress can accept
|
||||
// fresh connections again while a later shutdown/reconcile retries.
|
||||
this.isEnabled = wasEnabled;
|
||||
this.listening = wasListening;
|
||||
this.acceptingActions = wasAcceptingActions;
|
||||
if (wasAcceptingWebSocketActions) this.webSocketConnections.startAccepting();
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
this.closePromise = null;
|
||||
@@ -72,14 +126,25 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
override describeStatus(): AdapterStatus {
|
||||
if (!this.isEnabled) return { name: this.name, kind: 'httpServer', status: 'disabled', detail: '未启用' };
|
||||
if (!this.listening) return { name: this.name, kind: 'httpServer', status: 'down', detail: '未监听(端口被占用?)' };
|
||||
return { name: this.name, kind: 'httpServer', status: 'ok', detail: '监听中' };
|
||||
const detail = this.config.enableWebSocket === true
|
||||
? `监听中 · WebSocket ${this.webSocketConnections.connectionCount} 个客户端`
|
||||
: '监听中';
|
||||
return { name: this.name, kind: 'httpServer', status: 'ok', detail };
|
||||
}
|
||||
|
||||
protected override bindingSignature(config: HttpServerNetwork): string {
|
||||
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path ?? '/')}`;
|
||||
const webSocket = config.enableWebSocket === true ? 'ws' : 'http';
|
||||
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path ?? '/')}#${webSocket}`;
|
||||
}
|
||||
|
||||
onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ }
|
||||
protected override onConfigReplaced(next: HttpServerNetwork): void {
|
||||
this.webSocketConnections.updateConfig(next);
|
||||
}
|
||||
|
||||
onEvent(_event: JsonObject, payload: DispatchPayload): void {
|
||||
if (this.config.enableWebSocket !== true || !this.isEnabled) return;
|
||||
this.webSocketConnections.onEvent(payload);
|
||||
}
|
||||
|
||||
private startServer(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -87,11 +152,35 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
this.trackInboundAction(req, res);
|
||||
});
|
||||
this.server = server;
|
||||
let webSocketServer: WebSocketServer | null = null;
|
||||
try {
|
||||
if (this.config.enableWebSocket === true) {
|
||||
webSocketServer = new WebSocketServer({ server });
|
||||
webSocketServer.on('connection', (socket, request) => {
|
||||
this.webSocketConnections.accept(socket, request);
|
||||
});
|
||||
webSocketServer.on('error', (error: Error) => {
|
||||
this.recordTransportFailure(error);
|
||||
this.log.error(
|
||||
'[%s] embedded WebSocket error: %s',
|
||||
this.name,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
});
|
||||
this.webSocketServer = webSocketServer;
|
||||
}
|
||||
} catch (error) {
|
||||
this.server = null;
|
||||
this.recordTransportFailure(error);
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
let opening = true;
|
||||
|
||||
server.once('listening', () => {
|
||||
opening = false;
|
||||
if (this.server !== server || this.closePromise) {
|
||||
webSocketServer?.close();
|
||||
server.close();
|
||||
reject(new Error(`HTTP adapter [${this.name}] was closed while binding`));
|
||||
return;
|
||||
@@ -99,12 +188,14 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
this.listening = true;
|
||||
this.isEnabled = true;
|
||||
this.acceptingActions = true;
|
||||
if (webSocketServer) this.webSocketConnections.startAccepting();
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
'[%s] listening %s:%d%s%s',
|
||||
this.name,
|
||||
this.config.host ?? '0.0.0.0',
|
||||
this.config.port,
|
||||
normalizePath(this.config.path ?? '/'),
|
||||
webSocketServer ? ' with WebSocket' : '',
|
||||
);
|
||||
resolve();
|
||||
});
|
||||
@@ -113,8 +204,13 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
this.listening = false;
|
||||
this.isEnabled = false;
|
||||
this.acceptingActions = false;
|
||||
this.webSocketConnections.stopAccepting();
|
||||
this.recordTransportFailure(error);
|
||||
if (opening) this.server = null;
|
||||
if (opening) {
|
||||
this.server = null;
|
||||
if (this.webSocketServer === webSocketServer) this.webSocketServer = null;
|
||||
webSocketServer?.close();
|
||||
}
|
||||
}
|
||||
this.log.error('[%s] server error: %s', this.name, error instanceof Error ? error.message : String(error));
|
||||
if (opening) {
|
||||
@@ -128,6 +224,8 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
} catch (error) {
|
||||
opening = false;
|
||||
if (this.server === server) this.server = null;
|
||||
if (this.webSocketServer === webSocketServer) this.webSocketServer = null;
|
||||
webSocketServer?.close();
|
||||
this.recordTransportFailure(error);
|
||||
reject(error);
|
||||
}
|
||||
|
||||
@@ -1,44 +1,25 @@
|
||||
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
|
||||
import type { IncomingMessage } from 'http';
|
||||
import { WebSocketServer } from '@snowluma/websocket';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
pickDispatchJson,
|
||||
resolveReportOptions,
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import type { JsonObject, WsRole, WsServerNetwork } from '../types';
|
||||
import type { DispatchPayload } from '../event-filter';
|
||||
import type { JsonObject, WsServerNetwork } from '../types';
|
||||
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend, safeSendAsync, startHeartbeat } from './utils';
|
||||
import { normalizePath } from './utils';
|
||||
import { WsServerConnections } from './ws-server-connections';
|
||||
|
||||
const moduleLog = createLogger('OneBot.WS-Server');
|
||||
// Transport keepalive for each attached client, symmetric with the ws-client
|
||||
// adapter: ping every 30s, reap a client only after 2 consecutive pings go
|
||||
// unanswered — ~90s of total silence (see startHeartbeat for the +1-interval
|
||||
// timing). Any inbound frame resets the counter — see issue #208.
|
||||
const HEARTBEAT_INTERVAL_MS = 30_000;
|
||||
const HEARTBEAT_MAX_MISSED = 2;
|
||||
const HEARTBEAT_DEAD_AFTER_S = (HEARTBEAT_INTERVAL_MS * (HEARTBEAT_MAX_MISSED + 1)) / 1000;
|
||||
|
||||
interface ForwardConn {
|
||||
socket: WebSocket;
|
||||
role: WsRole;
|
||||
options: EventReportOptions;
|
||||
stopHeartbeat: () => void;
|
||||
}
|
||||
|
||||
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
private wss: WebSocketServer | null = null;
|
||||
private listening = false;
|
||||
private closePromise: Promise<void> | null = null;
|
||||
private acceptingActions = false;
|
||||
private readonly inFlightActions = new Set<Promise<void>>();
|
||||
private connections = new Map<WebSocket, ForwardConn>();
|
||||
private options: EventReportOptions;
|
||||
private readonly connections: WsServerConnections;
|
||||
|
||||
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx, moduleLog);
|
||||
this.options = resolveReportOptions(config);
|
||||
this.connections = new WsServerConnections(name, config, ctx, this.log, {
|
||||
frame: (event, options) => this.metaFrame(event, options),
|
||||
bootstrap: (options) => this.bootstrapMetaFrames(options),
|
||||
});
|
||||
}
|
||||
|
||||
async open(): Promise<void> {
|
||||
@@ -52,27 +33,19 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.closePromise) return this.closePromise;
|
||||
if (!this.isEnabled && this.connections.size === 0 && !this.wss && this.inFlightActions.size === 0) return;
|
||||
if (
|
||||
!this.isEnabled &&
|
||||
this.connections.connectionCount === 0 &&
|
||||
!this.wss &&
|
||||
!this.connections.hasInFlightActions
|
||||
) return;
|
||||
const wasEnabled = this.isEnabled;
|
||||
const wasListening = this.listening;
|
||||
const wasAcceptingActions = this.acceptingActions;
|
||||
this.acceptingActions = false;
|
||||
// Final lifecycle broadcast before tearing down so attached event clients
|
||||
// see the disable transition.
|
||||
const lifecycle = this.ctx.buildLifecycleEvent('disable');
|
||||
for (const conn of this.connections.values()) {
|
||||
if (conn.role === 'Api') continue;
|
||||
const frame = this.metaFrame(lifecycle, conn.options);
|
||||
if (frame) safeSend(conn.socket, frame);
|
||||
}
|
||||
const wasAcceptingActions = this.connections.isAcceptingActions;
|
||||
|
||||
this.isEnabled = false;
|
||||
this.listening = false;
|
||||
for (const conn of this.connections.values()) {
|
||||
conn.stopHeartbeat();
|
||||
safeClose(conn.socket);
|
||||
}
|
||||
this.connections.clear();
|
||||
const connectionDrain = this.connections.closeConnections();
|
||||
const wss = this.wss;
|
||||
const releaseResult: Promise<{ error?: Error }> = wss
|
||||
? new Promise<{ error?: Error }>((resolve) => {
|
||||
@@ -80,7 +53,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
})
|
||||
: Promise.resolve({});
|
||||
const attempt = (async () => {
|
||||
await Promise.all(this.inFlightActions);
|
||||
await connectionDrain;
|
||||
const release = await releaseResult;
|
||||
if (release.error) throw release.error;
|
||||
})();
|
||||
@@ -93,7 +66,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
// reference and active binding state so a later shutdown can retry.
|
||||
this.isEnabled = wasEnabled;
|
||||
this.listening = wasListening;
|
||||
this.acceptingActions = wasAcceptingActions;
|
||||
if (wasAcceptingActions) this.connections.startAccepting();
|
||||
throw error;
|
||||
} finally {
|
||||
this.closePromise = null;
|
||||
@@ -103,7 +76,12 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
override describeStatus(): AdapterStatus {
|
||||
if (!this.isEnabled) return { name: this.name, kind: 'wsServer', status: 'disabled', detail: '未启用' };
|
||||
if (!this.listening) return { name: this.name, kind: 'wsServer', status: 'down', detail: '未监听(端口被占用?)' };
|
||||
return { name: this.name, kind: 'wsServer', status: 'ok', detail: `${this.connections.size} 个客户端` };
|
||||
return {
|
||||
name: this.name,
|
||||
kind: 'wsServer',
|
||||
status: 'ok',
|
||||
detail: `${this.connections.connectionCount} 个客户端`,
|
||||
};
|
||||
}
|
||||
|
||||
protected override bindingSignature(config: WsServerNetwork): string {
|
||||
@@ -111,18 +89,12 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
}
|
||||
|
||||
protected override onConfigReplaced(next: WsServerNetwork): void {
|
||||
this.options = resolveReportOptions(next);
|
||||
for (const conn of this.connections.values()) conn.options = this.options;
|
||||
this.connections.updateConfig(next);
|
||||
}
|
||||
|
||||
onEvent(_event: JsonObject, payload: DispatchPayload): void {
|
||||
if (!this.isEnabled || this.connections.size === 0) return;
|
||||
for (const conn of this.connections.values()) {
|
||||
if (conn.role !== 'Event' && conn.role !== 'Universal') continue;
|
||||
const json = pickDispatchJson(payload, conn.options);
|
||||
if (json === null) continue;
|
||||
safeSend(conn.socket, json);
|
||||
}
|
||||
if (!this.isEnabled) return;
|
||||
this.connections.onEvent(payload);
|
||||
}
|
||||
|
||||
private startServer(): Promise<void> {
|
||||
@@ -151,7 +123,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
}
|
||||
this.listening = true;
|
||||
this.isEnabled = true;
|
||||
this.acceptingActions = true;
|
||||
this.connections.startAccepting();
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
@@ -166,7 +138,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
if (this.wss === wss) {
|
||||
this.listening = false;
|
||||
this.isEnabled = false;
|
||||
this.acceptingActions = false;
|
||||
this.connections.stopAccepting();
|
||||
this.recordTransportFailure(error);
|
||||
if (opening) this.wss = null;
|
||||
}
|
||||
@@ -177,97 +149,21 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
}
|
||||
});
|
||||
|
||||
wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request));
|
||||
wss.on('connection', (socket, request) => this.connections.accept(socket, request));
|
||||
});
|
||||
}
|
||||
|
||||
private onConnection(socket: WebSocket, request: IncomingMessage): void {
|
||||
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
|
||||
safeClose(socket, 1012, 'server closing');
|
||||
return;
|
||||
}
|
||||
if (!isAuthorized(request, this.config.accessToken ?? '')) {
|
||||
safeClose(socket, 1008, 'invalid access token');
|
||||
return;
|
||||
}
|
||||
|
||||
const role = this.config.role ?? classifyForwardRole(request);
|
||||
const stopHeartbeat = startHeartbeat(
|
||||
socket,
|
||||
{ intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED },
|
||||
() => {
|
||||
this.log.warn('[%s] client silent for ~%ds, terminating half-open connection', this.name, HEARTBEAT_DEAD_AFTER_S);
|
||||
socket.terminate(); // → 'close' → connections.delete; the client reconnects on its own
|
||||
},
|
||||
);
|
||||
const conn: ForwardConn = { socket, role, options: this.options, stopHeartbeat };
|
||||
this.connections.set(socket, conn);
|
||||
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
this.trackInboundAction(() => this.handleApiMessage(socket, role, raw));
|
||||
});
|
||||
socket.on('close', () => {
|
||||
stopHeartbeat();
|
||||
this.connections.delete(socket);
|
||||
});
|
||||
socket.on('error', (err: Error) => {
|
||||
this.log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
if (role === 'Event' || role === 'Universal') {
|
||||
this.sendBootstrapMetaEvents(socket);
|
||||
}
|
||||
/** Kept as the adapter-level lifecycle test seam. */
|
||||
protected get acceptingActions(): boolean {
|
||||
return this.connections.isAcceptingActions;
|
||||
}
|
||||
|
||||
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
|
||||
if (role !== 'Api' && role !== 'Universal') return;
|
||||
const text = rawDataToString(raw);
|
||||
if (!text) return;
|
||||
// Stream API (#163) emits multiple frames per request; processStreamRequest
|
||||
// sends one frame for a normal action and N for a streaming one. The async
|
||||
// send applies backpressure (awaits flush); the liveness check aborts a
|
||||
// streaming action once the client goes away.
|
||||
await this.ctx.api.processStreamRequest(
|
||||
text,
|
||||
(frame) => safeSendAsync(socket, frame),
|
||||
() => socket.readyState === 1,
|
||||
);
|
||||
}
|
||||
|
||||
private trackInboundAction(start: () => Promise<void>): void {
|
||||
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
|
||||
this.log.warn('[%s] rejected inbound action while adapter is closing', this.name);
|
||||
return;
|
||||
}
|
||||
let action: Promise<void>;
|
||||
try {
|
||||
action = start();
|
||||
} catch (error) {
|
||||
this.log.error('[%s] inbound action start failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
return;
|
||||
}
|
||||
const tracked = action.then(
|
||||
() => undefined,
|
||||
(error) => {
|
||||
this.log.error('[%s] inbound action failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
},
|
||||
);
|
||||
this.inFlightActions.add(tracked);
|
||||
void tracked.then(() => { this.inFlightActions.delete(tracked); });
|
||||
}
|
||||
|
||||
private sendBootstrapMetaEvents(socket: WebSocket): void {
|
||||
for (const frame of this.bootstrapMetaFrames(this.options)) safeSend(socket, frame);
|
||||
/** Kept as the adapter-level lifecycle test seam. */
|
||||
protected trackInboundAction(start: () => Promise<void>): void {
|
||||
this.connections.trackInboundAction(start);
|
||||
}
|
||||
}
|
||||
|
||||
function isAlreadyClosedError(error: Error): boolean {
|
||||
return (error as NodeJS.ErrnoException).code === 'ERR_SERVER_NOT_RUNNING';
|
||||
}
|
||||
|
||||
function classifyForwardRole(request: IncomingMessage): WsRole {
|
||||
const path = parseRequestPath(request.url ?? '/');
|
||||
if (path.endsWith('/api')) return 'Api';
|
||||
if (path.endsWith('/event')) return 'Event';
|
||||
return 'Universal';
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import type { Logger } from '@snowluma/common/logger';
|
||||
import type { WebSocket } from '@snowluma/websocket';
|
||||
import type { IncomingMessage } from 'node:http';
|
||||
import {
|
||||
pickDispatchJson,
|
||||
resolveReportOptions,
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import type { JsonObject, NetworkBase, WsRole } from '../types';
|
||||
import type { NetworkAdapterContext } from './adapter';
|
||||
import {
|
||||
isAuthorized,
|
||||
parseRequestPath,
|
||||
rawDataToString,
|
||||
safeClose,
|
||||
safeSend,
|
||||
safeSendAsync,
|
||||
startHeartbeat,
|
||||
} from './utils';
|
||||
|
||||
// Transport keepalive for each attached client, symmetric with the ws-client
|
||||
// adapter: ping every 30s, reap a client only after 2 consecutive pings go
|
||||
// unanswered — ~90s of total silence (see startHeartbeat for the +1-interval
|
||||
// timing). Any inbound frame resets the counter — see issue #208.
|
||||
const HEARTBEAT_INTERVAL_MS = 30_000;
|
||||
const HEARTBEAT_MAX_MISSED = 2;
|
||||
const HEARTBEAT_DEAD_AFTER_S = (HEARTBEAT_INTERVAL_MS * (HEARTBEAT_MAX_MISSED + 1)) / 1000;
|
||||
|
||||
export type WsServerConnectionConfig = NetworkBase & { role?: WsRole };
|
||||
|
||||
interface ForwardConnection {
|
||||
socket: WebSocket;
|
||||
role: WsRole;
|
||||
options: EventReportOptions;
|
||||
stopHeartbeat: () => void;
|
||||
}
|
||||
|
||||
interface MetaFrames {
|
||||
frame(event: JsonObject, options: EventReportOptions): string | null;
|
||||
bootstrap(options: EventReportOptions): string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared OneBot WebSocket session owner.
|
||||
*
|
||||
* Listener ownership deliberately stays in the network adapter: a standalone
|
||||
* WS adapter owns its TCP listener, while an HTTP adapter owns the shared
|
||||
* listener and only attaches an upgrade handler. This class owns everything
|
||||
* after a WebSocket connection is accepted so both transports keep identical
|
||||
* auth, role, event, heartbeat, stream, and shutdown semantics.
|
||||
*/
|
||||
export class WsServerConnections {
|
||||
private acceptingActions = false;
|
||||
private readonly inFlightActions = new Set<Promise<void>>();
|
||||
private readonly connections = new Map<WebSocket, ForwardConnection>();
|
||||
private config: WsServerConnectionConfig;
|
||||
private options: EventReportOptions;
|
||||
|
||||
constructor(
|
||||
private readonly name: string,
|
||||
config: WsServerConnectionConfig,
|
||||
private readonly ctx: NetworkAdapterContext,
|
||||
private readonly log: Logger,
|
||||
private readonly meta: MetaFrames,
|
||||
) {
|
||||
this.config = structuredClone(config);
|
||||
this.options = resolveReportOptions(config);
|
||||
}
|
||||
|
||||
get connectionCount(): number {
|
||||
return this.connections.size;
|
||||
}
|
||||
|
||||
get isAcceptingActions(): boolean {
|
||||
return this.acceptingActions;
|
||||
}
|
||||
|
||||
get hasInFlightActions(): boolean {
|
||||
return this.inFlightActions.size > 0;
|
||||
}
|
||||
|
||||
startAccepting(): void {
|
||||
this.acceptingActions = true;
|
||||
}
|
||||
|
||||
stopAccepting(): void {
|
||||
this.acceptingActions = false;
|
||||
}
|
||||
|
||||
updateConfig(next: WsServerConnectionConfig): void {
|
||||
const tokenChanged = (this.config.accessToken ?? '') !== (next.accessToken ?? '');
|
||||
this.config = structuredClone(next);
|
||||
this.options = resolveReportOptions(next);
|
||||
for (const connection of this.connections.values()) connection.options = this.options;
|
||||
|
||||
// An already-authorized socket must not retain access after token
|
||||
// rotation. Drop it immediately; the client can reconnect with the new
|
||||
// credential without forcing the shared HTTP listener to rebind.
|
||||
if (tokenChanged) this.disconnectAll(1008, 'access token changed');
|
||||
}
|
||||
|
||||
onEvent(payload: DispatchPayload): void {
|
||||
if (!this.acceptingActions || this.connections.size === 0) return;
|
||||
for (const connection of this.connections.values()) {
|
||||
if (connection.role !== 'Event' && connection.role !== 'Universal') continue;
|
||||
const json = pickDispatchJson(payload, connection.options);
|
||||
if (json === null) continue;
|
||||
safeSend(connection.socket, json);
|
||||
}
|
||||
}
|
||||
|
||||
accept(socket: WebSocket, request: IncomingMessage): void {
|
||||
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
|
||||
safeClose(socket, 1012, 'server closing');
|
||||
return;
|
||||
}
|
||||
if (!isAuthorized(request, this.config.accessToken ?? '')) {
|
||||
safeClose(socket, 1008, 'invalid access token');
|
||||
return;
|
||||
}
|
||||
|
||||
const role = this.config.role ?? classifyForwardRole(request);
|
||||
const stopHeartbeat = startHeartbeat(
|
||||
socket,
|
||||
{ intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED },
|
||||
() => {
|
||||
this.log.warn(
|
||||
'[%s] client silent for ~%ds, terminating half-open connection',
|
||||
this.name,
|
||||
HEARTBEAT_DEAD_AFTER_S,
|
||||
);
|
||||
socket.terminate();
|
||||
},
|
||||
);
|
||||
const connection: ForwardConnection = {
|
||||
socket,
|
||||
role,
|
||||
options: this.options,
|
||||
stopHeartbeat,
|
||||
};
|
||||
this.connections.set(socket, connection);
|
||||
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
// Token rotation removes the connection synchronously, before the close
|
||||
// handshake necessarily reaches the peer. Ignore any frame arriving in
|
||||
// that interval so old credentials cannot start another Action.
|
||||
if (!this.connections.has(socket)) return;
|
||||
this.trackInboundAction(() => this.handleApiMessage(socket, role, raw));
|
||||
});
|
||||
socket.on('close', () => {
|
||||
stopHeartbeat();
|
||||
this.connections.delete(socket);
|
||||
});
|
||||
socket.on('error', (error: Error) => {
|
||||
this.log.warn(
|
||||
'[%s] socket error: %s',
|
||||
this.name,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
});
|
||||
|
||||
if (role === 'Event' || role === 'Universal') {
|
||||
for (const frame of this.meta.bootstrap(this.options)) safeSend(socket, frame);
|
||||
}
|
||||
}
|
||||
|
||||
async closeConnections(): Promise<void> {
|
||||
this.stopAccepting();
|
||||
const lifecycle = this.ctx.buildLifecycleEvent('disable');
|
||||
for (const connection of this.connections.values()) {
|
||||
if (connection.role === 'Api') continue;
|
||||
const frame = this.meta.frame(lifecycle, connection.options);
|
||||
if (frame) safeSend(connection.socket, frame);
|
||||
}
|
||||
this.disconnectAll();
|
||||
await Promise.all(this.inFlightActions);
|
||||
}
|
||||
|
||||
private disconnectAll(code = 1000, reason = 'normal'): void {
|
||||
for (const connection of this.connections.values()) {
|
||||
connection.stopHeartbeat();
|
||||
safeClose(connection.socket, code, reason);
|
||||
}
|
||||
this.connections.clear();
|
||||
}
|
||||
|
||||
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
|
||||
const text = rawDataToString(raw);
|
||||
if (!text) {
|
||||
this.log.debug('[%s] ignored empty WebSocket frame', this.name);
|
||||
return;
|
||||
}
|
||||
if (role !== 'Api' && role !== 'Universal') {
|
||||
this.log.warn('[%s] rejected Action frame from Event-only connection', this.name);
|
||||
return;
|
||||
}
|
||||
await this.ctx.api.processStreamRequest(
|
||||
text,
|
||||
(frame) => safeSendAsync(socket, frame),
|
||||
() => socket.readyState === 1 && this.connections.has(socket),
|
||||
);
|
||||
}
|
||||
|
||||
trackInboundAction(start: () => Promise<void>): void {
|
||||
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
|
||||
this.log.warn('[%s] rejected inbound action while adapter is closing', this.name);
|
||||
return;
|
||||
}
|
||||
let action: Promise<void>;
|
||||
try {
|
||||
action = start();
|
||||
} catch (error) {
|
||||
this.log.error(
|
||||
'[%s] inbound action start failed: %s',
|
||||
this.name,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const tracked = action.then(
|
||||
() => undefined,
|
||||
(error) => {
|
||||
this.log.error(
|
||||
'[%s] inbound action failed: %s',
|
||||
this.name,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
},
|
||||
);
|
||||
this.inFlightActions.add(tracked);
|
||||
void tracked.then(() => { this.inFlightActions.delete(tracked); });
|
||||
}
|
||||
}
|
||||
|
||||
function classifyForwardRole(request: IncomingMessage): WsRole {
|
||||
const path = parseRequestPath(request.url ?? '/');
|
||||
if (path.endsWith('/api')) return 'Api';
|
||||
if (path.endsWith('/event')) return 'Event';
|
||||
return 'Universal';
|
||||
}
|
||||
Reference in new issue
Block a user