Files
SnowLuma/packages/onebot/src/network/ws-server-adapter.ts
T
KazusaUwU 8d9f44b6b0 feat(onebot): make the websocket frame cap configurable and diagnosable (#631)
- expose DEFAULT_MAX_PAYLOAD_BYTES; an inbound frame over the cap now reports its
  declared byte size, message type and the effective limit, recovered by walking
  the buffered frame stream so the number is right when a chunk carries several
  frames, the oversized header spans chunks, or control frames are interleaved;
  when the walk cannot reach a verdict the error names the cap without a size
- truncate close reasons to the RFC 6455 control-frame room on a UTF-8 boundary
  (an over-long reason previously produced an invalid control frame)
- add optional maxPayloadBytes (default 100 MiB unchanged) to the three adapters
  that read WebSocket frames: wsServers, wsClients and httpServers with
  enableWebSocket. httpClients rejects the field because it has no WebSocket
  transport, and the value is part of the binding signature so a change rebinds
  the transport instead of being saved without taking effect
- keep the existing 1009 log lines and append the actionable hint instead of
  replacing the template
- WebUI field (including httpServers once the embedded listener is on) and README
  docs for the 100 MiB => ~445 s (7:26) inline PCM consequence
2026-11-01 20:29:16 +08:00

284 lines
9.1 KiB
TypeScript

import { WebSocketServer } from '@snowluma/websocket';
import { createLogger } from '@snowluma/common/logger';
import type { IncomingMessage } from 'node:http';
import type { DispatchPayload } from '../event-filter';
import type { JsonObject, WsServerNetwork } from '../types';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { normalizePath, parseRequestPath } from './utils';
import { WsServerConnections, type WsServerConnectionConfig } from './ws-server-connections';
const moduleLog = createLogger('OneBot.WS-Server');
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
private wss: WebSocketServer | null = null;
private listening = false;
private releaseForced = false;
private closePromise: Promise<void> | null = null;
private readonly connections: WsServerConnections;
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx, moduleLog);
this.connections = new WsServerConnections(
name,
standaloneConnectionConfig(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.wss) {
throw new Error(`WebSocket adapter [${this.name}] still owns a previous server`);
}
await this.startServer();
this.isEnabled = true;
this.clearApplyFailure();
}
async close(): Promise<void> {
if (this.closePromise) {
return this.closePromise;
}
if (
!this.isEnabled &&
this.connections.connectionCount === 0 &&
!this.wss &&
!this.connections.hasInFlightActions
) {
return;
}
const wasEnabled = this.isEnabled;
const wasListening = this.listening;
const wasAcceptingActions = this.connections.isAcceptingActions;
this.isEnabled = false;
this.listening = false;
const connectionDrain = this.connections.closeConnections();
const wss = this.wss;
const releaseResult: Promise<{ error?: Error }> = wss
? new Promise<{ error?: Error }>((resolve) => {
wss.close((error) =>
resolve(error && !isAlreadyClosedError(error) ? { error } : {}),
);
})
: Promise.resolve({});
const attempt = (async () => {
await connectionDrain;
const release = await releaseResult;
if (release.error) {
throw release.error;
}
})();
this.closePromise = attempt;
try {
await attempt;
if (wss && this.wss === wss) {
this.wss = null;
}
} catch (error) {
if (this.releaseForced) {
return;
}
// A failed close callback leaves release ambiguous. Retain the server
// reference and active binding state so a later shutdown can retry.
this.isEnabled = wasEnabled;
this.listening = wasListening;
if (wasAcceptingActions) {
this.connections.startAccepting();
}
throw error;
} finally {
this.closePromise = null;
}
}
override forceClose(): void {
this.releaseForced = true;
this.isEnabled = false;
this.listening = false;
this.connections.stopAccepting();
this.connections.terminateAll();
const wss = this.wss;
this.wss = null;
if (wss) {
try {
wss.destroy();
} catch {
/* already dropping */
}
}
}
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.connectionCount} 个客户端`,
};
}
protected override bindingSignature(config: WsServerNetwork): string {
// The frame cap is fixed when the WebSocketServer is constructed, so a
// change must rebind instead of silently keeping the old limit.
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path)}#${config.role ?? 'auto'}#${config.accessToken ?? ''}#${config.maxPayloadBytes ?? ''}`;
}
protected override onConfigReplaced(next: WsServerNetwork): void {
this.connections.updateConfig(standaloneConnectionConfig(next));
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled) {
return;
}
this.connections.onEvent(payload);
}
private startServer(): Promise<void> {
return new Promise((resolve, reject) => {
let wss: WebSocketServer;
try {
wss = new WebSocketServer({
host: this.config.host ?? '0.0.0.0',
port: this.config.port,
maxPayload: this.config.maxPayloadBytes,
verifyClient: (
{ req }: { req: IncomingMessage },
done: (allow: boolean, code?: number, message?: string) => void,
) => {
const requestPath = parseRequestPath(req.url ?? '/');
if (!this.connections.acceptsUpgradePath(requestPath)) {
this.log.debug(
'[%s] rejected unknown WebSocket path %s',
this.name,
requestPath,
);
done(false, 400, 'Bad path for WebSocket');
return;
}
if (!this.connections.authorizeUpgrade(req)) {
done(false, 401, 'Unauthorized');
return;
}
done(true);
},
});
} catch (error) {
this.recordTransportFailure(error);
reject(error);
return;
}
this.wss = wss;
let opening = true;
wss.once('listening', () => {
opening = false;
if (this.wss !== wss || this.closePromise) {
wss.close();
reject(new Error(`WebSocket adapter [${this.name}] was closed while binding`));
return;
}
this.listening = true;
this.isEnabled = true;
this.connections.startAccepting();
this.log.success(
'[%s] listening %s:%d%s',
this.name,
this.config.host ?? '0.0.0.0',
this.config.port,
this.config.path ?? '/',
);
resolve();
});
wss.on('error', (error: Error) => {
if (this.wss === wss) {
this.listening = false;
this.isEnabled = false;
this.connections.stopAccepting();
this.recordTransportFailure(error);
if (opening) {
this.wss = null;
}
}
this.log.error(
'[%s] server error: %s',
this.name,
error instanceof Error ? error.message : String(error),
);
if (opening) {
opening = false;
reject(error);
}
});
wss.on('connection', (socket, request) => this.connections.accept(socket, request));
});
}
/** Kept as the adapter-level lifecycle test seam. */
protected get acceptingActions(): boolean {
return this.connections.isAcceptingActions;
}
/** 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 standaloneConnectionConfig(config: WsServerNetwork): WsServerConnectionConfig {
return { ...config, role: config.role ?? 'Universal' };
}