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
This commit is contained in:
1 parent
bd40ac3522
commit
8d9f44b6b0
16 files changed
+1035
-77
No files matched your search
@@ -24,6 +24,11 @@ const CONFIG_DIR = 'config';
|
||||
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
|
||||
const DEFAULT_ACCESS_TOKEN_BYTES = 32;
|
||||
const NODE_TIMER_MAX_MS = 2_147_483_647;
|
||||
/** Bounds for a per-adapter inbound WebSocket frame cap. 2 GiB is several
|
||||
* orders of magnitude past any real OneBot frame; above that a sender has to
|
||||
* split its payload instead of expecting a single buffer to hold it. */
|
||||
const MAX_PAYLOAD_BYTES_MIN = 1024;
|
||||
const MAX_PAYLOAD_BYTES_MAX = 2 * 1024 * 1024 * 1024;
|
||||
const PER_UIN_SNAPSHOT_MARKER = 'snapshot';
|
||||
|
||||
const DEFAULT_STATUS_COMMAND: StatusCommandConfig = {
|
||||
@@ -412,11 +417,15 @@ function validateRestoreAdapterArray(
|
||||
: ['url', 'role', 'reconnectIntervalMs'];
|
||||
|
||||
if (kind === 'httpServers') {
|
||||
specific.push('enableWebSocket');
|
||||
specific.push('enableWebSocket', 'maxPayloadBytes');
|
||||
}
|
||||
|
||||
if (kind === 'wsServers') {
|
||||
specific.push('role');
|
||||
specific.push('role', 'maxPayloadBytes');
|
||||
}
|
||||
|
||||
if (kind === 'wsClients') {
|
||||
specific.push('maxPayloadBytes');
|
||||
}
|
||||
|
||||
const allowed = new Set<string>([...RESTORE_BASE_ADAPTER_KEYS, ...specific]);
|
||||
@@ -453,6 +462,20 @@ function validateRestoreAdapterArray(
|
||||
invalid(`${pathAt}.reportSelfMessage must be a boolean`);
|
||||
}
|
||||
|
||||
if (kind !== 'httpClients' && raw.maxPayloadBytes !== undefined) {
|
||||
const maxPayload = parseRestoreInteger(raw.maxPayloadBytes);
|
||||
|
||||
if (
|
||||
maxPayload === null ||
|
||||
maxPayload < MAX_PAYLOAD_BYTES_MIN ||
|
||||
maxPayload > MAX_PAYLOAD_BYTES_MAX
|
||||
) {
|
||||
invalid(
|
||||
`${pathAt}.maxPayloadBytes must be an integer between ${MAX_PAYLOAD_BYTES_MIN} and ${MAX_PAYLOAD_BYTES_MAX}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (kind === 'httpServers' || kind === 'wsServers') {
|
||||
const port = parseRestoreInteger(raw.port);
|
||||
|
||||
@@ -656,6 +679,7 @@ export function assertValidOneBotConfig(value: unknown): asserts value is OneBot
|
||||
const serverBindings = new Map<string, string>();
|
||||
validateNetworkList(value.networks, 'httpServers', seen, (item, at) => {
|
||||
validateServer(item, at);
|
||||
validateMaxPayloadBytes(item, at);
|
||||
|
||||
if (item.enableWebSocket !== undefined && typeof item.enableWebSocket !== 'boolean') {
|
||||
invalid(`${at}.enableWebSocket must be a boolean`);
|
||||
@@ -666,6 +690,11 @@ export function assertValidOneBotConfig(value: unknown): asserts value is OneBot
|
||||
validateNetworkList(value.networks, 'httpClients', seen, (item, at) => {
|
||||
validateClient(item, at, new Set(['http:', 'https:']));
|
||||
|
||||
// A frame cap on the pure HTTP POST adapter would be saved and ignored.
|
||||
if (item.maxPayloadBytes !== undefined) {
|
||||
invalid(`${at}.maxPayloadBytes is only supported by WebSocket adapters`);
|
||||
}
|
||||
|
||||
if (
|
||||
item.timeoutMs !== undefined &&
|
||||
(typeof item.timeoutMs !== 'number' ||
|
||||
@@ -680,10 +709,12 @@ export function assertValidOneBotConfig(value: unknown): asserts value is OneBot
|
||||
validateServer(item, at);
|
||||
validateServerBinding(item, at, serverBindings);
|
||||
validateRole(item.role, `${at}.role`);
|
||||
validateMaxPayloadBytes(item, at);
|
||||
});
|
||||
validateNetworkList(value.networks, 'wsClients', seen, (item, at) => {
|
||||
validateClient(item, at, new Set(['ws:', 'wss:']));
|
||||
validateRole(item.role, `${at}.role`);
|
||||
validateMaxPayloadBytes(item, at);
|
||||
|
||||
if (
|
||||
item.reconnectIntervalMs !== undefined &&
|
||||
@@ -816,6 +847,24 @@ function validateNetworkBase(item: JsonObject, at: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** Strict gate for the WebSocket-only frame cap; `httpClients` must not carry it. */
|
||||
function validateMaxPayloadBytes(item: JsonObject, at: string): void {
|
||||
if (item.maxPayloadBytes === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
typeof item.maxPayloadBytes !== 'number' ||
|
||||
!Number.isSafeInteger(item.maxPayloadBytes) ||
|
||||
item.maxPayloadBytes < MAX_PAYLOAD_BYTES_MIN ||
|
||||
item.maxPayloadBytes > MAX_PAYLOAD_BYTES_MAX
|
||||
) {
|
||||
invalid(
|
||||
`${at}.maxPayloadBytes must be an integer between ${MAX_PAYLOAD_BYTES_MIN} and ${MAX_PAYLOAD_BYTES_MAX}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function validateServer(item: JsonObject, at: string): void {
|
||||
if (
|
||||
!Number.isInteger(item.port) ||
|
||||
@@ -1030,6 +1079,7 @@ function applyBase(
|
||||
accessToken?: string;
|
||||
messageFormat: MessageFormat;
|
||||
reportSelfMessage: boolean;
|
||||
maxPayloadBytes?: number;
|
||||
},
|
||||
): void {
|
||||
out.name = n.name;
|
||||
@@ -1044,6 +1094,10 @@ function applyBase(
|
||||
|
||||
out.messageFormat = n.messageFormat;
|
||||
out.reportSelfMessage = n.reportSelfMessage;
|
||||
|
||||
if (n.maxPayloadBytes !== undefined) {
|
||||
out.maxPayloadBytes = n.maxPayloadBytes;
|
||||
}
|
||||
}
|
||||
|
||||
function httpServerToJson(n: HttpServerNetwork): JsonObject {
|
||||
@@ -1361,6 +1415,22 @@ function parseBase(value: JsonObject, defaults: AdapterDefaults) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Compatibility parser for the optional frame cap. Clamps like its neighbours
|
||||
* (`timeoutMs`, `reconnectIntervalMs`) so an on-disk value written by an
|
||||
* older/newer build still loads; `assertValidOneBotConfig` is the strict gate
|
||||
* for values saved through the API/WebUI.
|
||||
*/
|
||||
function parseMaxPayloadBytes(value: unknown): number | undefined {
|
||||
const parsed = asNumber(value, 0);
|
||||
|
||||
if (parsed <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return Math.min(Math.max(parsed, MAX_PAYLOAD_BYTES_MIN), MAX_PAYLOAD_BYTES_MAX);
|
||||
}
|
||||
|
||||
function parseHttpServer(value: JsonObject, defaults: AdapterDefaults): HttpServerNetwork | null {
|
||||
if (value.enableWebSocket !== undefined && typeof value.enableWebSocket !== 'boolean') {
|
||||
invalid('http server enableWebSocket must be a boolean');
|
||||
@@ -1378,6 +1448,7 @@ function parseHttpServer(value: JsonObject, defaults: AdapterDefaults): HttpServ
|
||||
port,
|
||||
path: asString(value.path, '/'),
|
||||
enableWebSocket: value.enableWebSocket === true,
|
||||
maxPayloadBytes: parseMaxPayloadBytes(value.maxPayloadBytes),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1410,6 +1481,7 @@ function parseWsServer(value: JsonObject, defaults: AdapterDefaults): WsServerNe
|
||||
port,
|
||||
path: asString(value.path, '/'),
|
||||
role: asRole(value.role, 'Universal'),
|
||||
maxPayloadBytes: parseMaxPayloadBytes(value.maxPayloadBytes),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1427,6 +1499,7 @@ function parseWsClient(value: JsonObject, defaults: AdapterDefaults): WsClientNe
|
||||
url,
|
||||
role: asRole(value.role, 'Universal'),
|
||||
reconnectIntervalMs: Math.max(1000, reconnectIntervalMs),
|
||||
maxPayloadBytes: parseMaxPayloadBytes(value.maxPayloadBytes),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -215,7 +215,12 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
|
||||
protected override bindingSignature(config: HttpServerNetwork): string {
|
||||
const webSocket = config.enableWebSocket === true ? 'ws' : 'http';
|
||||
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path ?? '/')}#${webSocket}`;
|
||||
// The frame cap is fixed when the WebSocketServer is constructed, so a
|
||||
// change must rebind instead of silently keeping the old limit — but only
|
||||
// when this adapter actually owns a WebSocket transport, otherwise the
|
||||
// HTTP listener would be torn down for a value it never uses.
|
||||
const maxPayload = config.enableWebSocket === true ? (config.maxPayloadBytes ?? '') : '';
|
||||
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path ?? '/')}#${webSocket}#${maxPayload}`;
|
||||
}
|
||||
|
||||
protected override onConfigReplaced(next: HttpServerNetwork): void {
|
||||
@@ -242,6 +247,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
if (this.config.enableWebSocket === true) {
|
||||
webSocketServer = new WebSocketServer({
|
||||
server,
|
||||
maxPayload: this.config.maxPayloadBytes,
|
||||
verifyClient: ({ req }: { req: IncomingMessage }) =>
|
||||
this.webSocketConnections.authorizeUpgrade(req),
|
||||
});
|
||||
|
||||
@@ -2,6 +2,13 @@ import { StreamTransportClosedError } from '../streaming';
|
||||
import type { WebSocket } from '@snowluma/websocket';
|
||||
import type { IncomingMessage } from 'http';
|
||||
|
||||
/**
|
||||
* Appended to a 1009 (frame-over-cap) log line. Shared so the client and server
|
||||
* adapters cannot drift apart on the advice they give.
|
||||
*/
|
||||
export const MAX_PAYLOAD_HINT =
|
||||
"Raise this adapter's maxPayloadBytes, or have the peer send a smaller frame (a URL/file reference or SILK instead of inline PCM)";
|
||||
|
||||
export function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||
if (!token) {
|
||||
return true;
|
||||
|
||||
@@ -8,7 +8,14 @@ import {
|
||||
} from '../event-filter';
|
||||
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
|
||||
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||||
import { rawDataToString, safeClose, safeSend, safeSendAsync, startHeartbeat } from './utils';
|
||||
import {
|
||||
MAX_PAYLOAD_HINT,
|
||||
rawDataToString,
|
||||
safeClose,
|
||||
safeSend,
|
||||
safeSendAsync,
|
||||
startHeartbeat,
|
||||
} from './utils';
|
||||
|
||||
const moduleLog = createLogger('OneBot.WS-Client');
|
||||
const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
|
||||
@@ -107,7 +114,9 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
}
|
||||
|
||||
protected override bindingSignature(config: WsClientNetwork): string {
|
||||
return `${config.url}#${config.role ?? 'Universal'}#${Math.max(1000, config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${config.accessToken ?? ''}`;
|
||||
// The frame cap is baked into the socket when it is created, so a change
|
||||
// must reconnect instead of silently keeping the old limit.
|
||||
return `${config.url}#${config.role ?? 'Universal'}#${Math.max(1000, config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${config.accessToken ?? ''}#${config.maxPayloadBytes ?? ''}`;
|
||||
}
|
||||
|
||||
protected override willEnable(config: WsClientNetwork): boolean {
|
||||
@@ -160,7 +169,10 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
headers.Authorization = `Bearer ${this.config.accessToken}`;
|
||||
}
|
||||
|
||||
const socket = new WebSocket(this.config.url, { headers });
|
||||
const socket = new WebSocket(this.config.url, {
|
||||
headers,
|
||||
maxPayload: this.config.maxPayloadBytes,
|
||||
});
|
||||
this.socket = socket;
|
||||
// Per-socket so a hot-reload overlap (old close firing after the new socket
|
||||
// is assigned, see #97) can only ever stop its own keepalive.
|
||||
@@ -255,11 +267,16 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
});
|
||||
|
||||
socket.on('error', (err: Error) => {
|
||||
// Keep the established `error <url>:` line intact (deployments grep
|
||||
// it); the actionable hint is appended, never substituted.
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
this.log.warn(
|
||||
'[%s] error %s: %s',
|
||||
this.name,
|
||||
this.config.url,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
(err as Error & { code?: number }).code === 1009
|
||||
? `${message}. ${MAX_PAYLOAD_HINT}`
|
||||
: message,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -154,7 +154,9 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
}
|
||||
|
||||
protected override bindingSignature(config: WsServerNetwork): string {
|
||||
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path)}#${config.role ?? 'auto'}#${config.accessToken ?? ''}`;
|
||||
// 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 {
|
||||
@@ -177,6 +179,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
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,
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import type { JsonObject, NetworkBase, WsRole } from '../types';
|
||||
import type { NetworkAdapterContext } from './adapter';
|
||||
import {
|
||||
MAX_PAYLOAD_HINT,
|
||||
isAuthorized,
|
||||
normalizePath,
|
||||
parseRequestPath,
|
||||
@@ -211,10 +212,15 @@ export class WsServerConnections {
|
||||
this.connections.delete(socket);
|
||||
});
|
||||
socket.on('error', (error: Error) => {
|
||||
// Keep the established `socket error:` line intact (deployments grep
|
||||
// it); the actionable hint is appended, never substituted.
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
this.log.warn(
|
||||
'[%s] socket error: %s',
|
||||
this.name,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
(error as Error & { code?: number }).code === 1009
|
||||
? `${message}. ${MAX_PAYLOAD_HINT}`
|
||||
: message,
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -38,7 +38,28 @@ export interface NetworkBase {
|
||||
reportSelfMessage: boolean;
|
||||
}
|
||||
|
||||
export interface HttpServerNetwork extends NetworkBase {
|
||||
/**
|
||||
* Inbound WebSocket frame cap, shared by the three adapters that read WebSocket
|
||||
* frames: `wsServers`, `wsClients`, and `httpServers` with `enableWebSocket`.
|
||||
* It is deliberately not part of {@link NetworkBase}: `httpClients` has no
|
||||
* WebSocket transport, and a saved-but-ignored option is worse than none.
|
||||
*/
|
||||
export interface WsFrameLimitConfig {
|
||||
/**
|
||||
* Cap on one inbound WebSocket message, in bytes (all fragments included).
|
||||
* Omitted means the transport default of 100 MiB
|
||||
* (`DEFAULT_MAX_PAYLOAD_BYTES`).
|
||||
*
|
||||
* Frames larger than the cap close the connection with 1009. A OneBot peer
|
||||
* that sends media inline has to fit the whole payload into one frame: at
|
||||
* 44.1 kHz stereo 16-bit PCM (176 400 B/s), 100 MiB is ~445 s (7:26), so
|
||||
* longer audio must arrive as a URL/file reference or be compressed (SILK).
|
||||
* Raising this value raises peak memory by the frame size.
|
||||
*/
|
||||
maxPayloadBytes?: number;
|
||||
}
|
||||
|
||||
export interface HttpServerNetwork extends NetworkBase, WsFrameLimitConfig {
|
||||
host?: string;
|
||||
port: number;
|
||||
path?: string;
|
||||
@@ -51,14 +72,14 @@ export interface HttpClientNetwork extends NetworkBase {
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface WsServerNetwork extends NetworkBase {
|
||||
export interface WsServerNetwork extends NetworkBase, WsFrameLimitConfig {
|
||||
host?: string;
|
||||
port: number;
|
||||
path?: string;
|
||||
role?: WsRole;
|
||||
}
|
||||
|
||||
export interface WsClientNetwork extends NetworkBase {
|
||||
export interface WsClientNetwork extends NetworkBase, WsFrameLimitConfig {
|
||||
url: string;
|
||||
role?: WsRole;
|
||||
reconnectIntervalMs?: number;
|
||||
|
||||
@@ -148,6 +148,44 @@ describe('assertValidOneBotConfig', () => {
|
||||
expect(() => assertValidOneBotConfig(ws)).toThrow(/reconnectIntervalMs/);
|
||||
});
|
||||
|
||||
it('bounds maxPayloadBytes when one is configured', () => {
|
||||
for (const invalid of [0, 1023, 2 * 1024 * 1024 * 1024 + 1, 1024.5, '104857600']) {
|
||||
const config = makeDefaultOneBotConfig();
|
||||
config.networks.wsServers[0].maxPayloadBytes = invalid as unknown as number;
|
||||
expect(() => assertValidOneBotConfig(config), String(invalid)).toThrow(
|
||||
/maxPayloadBytes/,
|
||||
);
|
||||
}
|
||||
|
||||
const accepted = makeDefaultOneBotConfig();
|
||||
accepted.networks.wsServers[0].maxPayloadBytes = 1024;
|
||||
expect(() => assertValidOneBotConfig(accepted)).not.toThrow();
|
||||
|
||||
// The third WebSocket-capable adapter: httpServers with the embedded WS.
|
||||
const httpWs = makeDefaultOneBotConfig();
|
||||
httpWs.networks.httpServers[0].enableWebSocket = true;
|
||||
httpWs.networks.httpServers[0].maxPayloadBytes = 2048;
|
||||
expect(() => assertValidOneBotConfig(httpWs)).not.toThrow();
|
||||
});
|
||||
|
||||
it('rejects maxPayloadBytes on the pure HTTP client adapter', () => {
|
||||
const config = makeDefaultOneBotConfig();
|
||||
config.networks.httpClients.push({
|
||||
name: 'mirror',
|
||||
url: 'http://127.0.0.1:9000',
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
});
|
||||
// HttpPostAdapter has no WebSocket transport, so the value could only be
|
||||
// saved and silently ignored.
|
||||
(config.networks.httpClients[0] as unknown as Record<string, unknown>).maxPayloadBytes =
|
||||
1024;
|
||||
|
||||
expect(() => assertValidOneBotConfig(config)).toThrow(
|
||||
/maxPayloadBytes is only supported by WebSocket adapters/,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects server paths that cannot match a URL pathname', () => {
|
||||
for (const invalidPath of ['api', '/api?token=x', '/api#fragment', ' /api']) {
|
||||
const config = makeDefaultOneBotConfig();
|
||||
@@ -365,6 +403,102 @@ describe('loadOneBotConfig', () => {
|
||||
expect(reloaded.networks.httpClients[0].reportSelfMessage).toBe(true);
|
||||
});
|
||||
|
||||
it('round-trips maxPayloadBytes (both directions) and omits it when unset', () => {
|
||||
const uin = '10020';
|
||||
const config = makeDefaultOneBotConfig();
|
||||
config.networks.wsServers[0].maxPayloadBytes = 512 * 1024 * 1024;
|
||||
config.networks.wsClients.push({
|
||||
name: 'astrbot',
|
||||
url: 'ws://127.0.0.1:6199/ws',
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
maxPayloadBytes: 256 * 1024 * 1024,
|
||||
});
|
||||
saveOneBotConfig(uin, config);
|
||||
|
||||
const onDisk = JSON.parse(
|
||||
fs.readFileSync(path.join(tempDir, 'config', `onebot_${uin}.json`), 'utf8'),
|
||||
);
|
||||
expect(onDisk.networks.wsServers[0].maxPayloadBytes).toBe(512 * 1024 * 1024);
|
||||
expect(onDisk.networks.wsClients[0].maxPayloadBytes).toBe(256 * 1024 * 1024);
|
||||
// Unset adapters must not gain the key, so existing configs stay byte-stable.
|
||||
expect(onDisk.networks.httpServers[0].maxPayloadBytes).toBeUndefined();
|
||||
|
||||
const reloaded = loadOneBotConfig(uin);
|
||||
expect(reloaded.networks.wsServers[0].maxPayloadBytes).toBe(512 * 1024 * 1024);
|
||||
expect(reloaded.networks.wsClients[0]!.maxPayloadBytes).toBe(256 * 1024 * 1024);
|
||||
|
||||
const prepared = prepareOneBotConfigForRestore(onDisk, 'per-uin');
|
||||
const preparedNetworks = prepared.value.networks as {
|
||||
wsClients: Array<Record<string, unknown>>;
|
||||
};
|
||||
expect(preparedNetworks.wsClients[0]!.maxPayloadBytes).toBe(256 * 1024 * 1024);
|
||||
|
||||
const junk = structuredClone(onDisk) as {
|
||||
networks: { wsClients: Array<Record<string, unknown>> };
|
||||
};
|
||||
junk.networks.wsClients[0]!.maxPayloadBytes = 0;
|
||||
expect(() => prepareOneBotConfigForRestore(junk, 'per-uin')).toThrow(/maxPayloadBytes/);
|
||||
});
|
||||
|
||||
it('persists maxPayloadBytes for httpServers and drops it for httpClients', () => {
|
||||
const uin = '10021';
|
||||
const config = makeDefaultOneBotConfig();
|
||||
config.networks.httpServers[0].enableWebSocket = true;
|
||||
config.networks.httpServers[0].maxPayloadBytes = 4096;
|
||||
saveOneBotConfig(uin, config);
|
||||
|
||||
const onDisk = JSON.parse(
|
||||
fs.readFileSync(path.join(tempDir, 'config', `onebot_${uin}.json`), 'utf8'),
|
||||
);
|
||||
expect(onDisk.networks.httpServers[0].maxPayloadBytes).toBe(4096);
|
||||
expect(loadOneBotConfig(uin).networks.httpServers[0].maxPayloadBytes).toBe(4096);
|
||||
expect(() => prepareOneBotConfigForRestore(onDisk, 'per-uin')).not.toThrow();
|
||||
|
||||
// A restore source that carries the key on a non-WS adapter is rejected
|
||||
// rather than accepted into a config where it can never apply.
|
||||
const withHttpClient = structuredClone(onDisk) as {
|
||||
networks: { httpClients: Array<Record<string, unknown>> };
|
||||
};
|
||||
withHttpClient.networks.httpClients.push({
|
||||
name: 'mirror',
|
||||
url: 'http://127.0.0.1:9000',
|
||||
maxPayloadBytes: 4096,
|
||||
});
|
||||
expect(() => prepareOneBotConfigForRestore(withHttpClient, 'per-uin')).toThrow(
|
||||
/maxPayloadBytes is not supported/,
|
||||
);
|
||||
|
||||
// A hand-written file is parsed permissively, but the key is not carried
|
||||
// into the canonical config (nor written back).
|
||||
const dir = path.join(tempDir, 'config');
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'onebot_10022.json'),
|
||||
JSON.stringify({
|
||||
mode: 'snapshot',
|
||||
networks: {
|
||||
httpServers: [],
|
||||
httpClients: [
|
||||
{
|
||||
name: 'mirror',
|
||||
url: 'http://127.0.0.1:9000',
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
maxPayloadBytes: 4096,
|
||||
},
|
||||
],
|
||||
wsServers: [],
|
||||
wsClients: [],
|
||||
},
|
||||
}),
|
||||
'utf8',
|
||||
);
|
||||
const loaded = loadOneBotConfig('10022');
|
||||
expect(
|
||||
(loaded.networks.httpClients[0] as unknown as Record<string, unknown>).maxPayloadBytes,
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it('replays a saved per-UIN snapshot without reviving deleted global adapters', () => {
|
||||
const dir = path.join(tempDir, 'config');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
// The native WebSocket addon is not built in a plain checkout, so the
|
||||
// transport is faked (same pattern as network-bootstrap-meta.test.ts). These
|
||||
// tests pin the config → transport wiring for `maxPayloadBytes`: the value must
|
||||
// reach both WebSocketServer and WebSocket, an unset value must leave the
|
||||
// transport default alone, and changing it must rebind/reconnect because the
|
||||
// cap is fixed when the socket is created.
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { FakeWebSocket, FakeWebSocketServer, clientInstances, clientOptions, servers } = vi.hoisted(
|
||||
() => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const { EventEmitter } = require('node:events') as typeof import('node:events');
|
||||
const clientInstances: FakeWebSocket[] = [];
|
||||
const clientOptions: unknown[] = [];
|
||||
const servers: FakeWebSocketServer[] = [];
|
||||
|
||||
class FakeWebSocket extends EventEmitter {
|
||||
public readyState = 1;
|
||||
constructor(
|
||||
public readonly url = '',
|
||||
options?: unknown,
|
||||
) {
|
||||
super();
|
||||
clientInstances.push(this);
|
||||
clientOptions.push(options);
|
||||
}
|
||||
send(): void {}
|
||||
close(): void {
|
||||
this.readyState = 3;
|
||||
}
|
||||
terminate(): void {
|
||||
this.readyState = 3;
|
||||
}
|
||||
}
|
||||
|
||||
class FakeWebSocketServer extends EventEmitter {
|
||||
public closed = false;
|
||||
constructor(public readonly options?: unknown) {
|
||||
super();
|
||||
servers.push(this);
|
||||
}
|
||||
close(cb?: (error?: Error) => void): void {
|
||||
this.closed = true;
|
||||
cb?.();
|
||||
}
|
||||
}
|
||||
|
||||
return { FakeWebSocket, FakeWebSocketServer, clientInstances, clientOptions, servers };
|
||||
},
|
||||
);
|
||||
|
||||
vi.mock('@snowluma/websocket', () => ({
|
||||
WebSocket: FakeWebSocket,
|
||||
WebSocketServer: FakeWebSocketServer,
|
||||
}));
|
||||
|
||||
import type { NetworkAdapterContext } from '../src/network/adapter';
|
||||
import { HttpServerAdapter } from '../src/network/http-server-adapter';
|
||||
import { WsClientAdapter } from '../src/network/ws-client-adapter';
|
||||
import { WsServerAdapter } from '../src/network/ws-server-adapter';
|
||||
import type { HttpServerNetwork, WsClientNetwork, WsServerNetwork } from '../src/types';
|
||||
|
||||
function ctx(): NetworkAdapterContext {
|
||||
return {
|
||||
uin: '10001',
|
||||
api: { processStreamRequest: async () => {}, isAcceptingActions: true } as never,
|
||||
buildLifecycleEvent: () => ({ post_type: 'meta_event' }),
|
||||
buildHeartbeatEvent: () => ({ post_type: 'meta_event' }),
|
||||
};
|
||||
}
|
||||
|
||||
function serverConfig(over: Partial<WsServerNetwork> = {}): WsServerNetwork {
|
||||
return {
|
||||
name: 'ws-in',
|
||||
enabled: true,
|
||||
host: '127.0.0.1',
|
||||
port: 3001,
|
||||
path: '/',
|
||||
role: 'Universal',
|
||||
accessToken: '',
|
||||
maxPayloadBytes: undefined,
|
||||
...over,
|
||||
} as WsServerNetwork;
|
||||
}
|
||||
|
||||
function clientConfig(over: Partial<WsClientNetwork> = {}): WsClientNetwork {
|
||||
return {
|
||||
name: 'ws-out',
|
||||
enabled: true,
|
||||
url: 'ws://127.0.0.1:6199/ws',
|
||||
role: 'Universal',
|
||||
reconnectIntervalMs: 1000,
|
||||
maxPayloadBytes: undefined,
|
||||
...over,
|
||||
} as WsClientNetwork;
|
||||
}
|
||||
|
||||
async function openServer(adapter: WsServerAdapter): Promise<void> {
|
||||
const opening = adapter.open();
|
||||
servers[servers.length - 1]!.emit('listening');
|
||||
await opening;
|
||||
}
|
||||
|
||||
describe('WsServerAdapter — maxPayloadBytes wiring', () => {
|
||||
beforeEach(() => {
|
||||
servers.length = 0;
|
||||
});
|
||||
|
||||
it('forwards the configured cap to the WebSocketServer', async () => {
|
||||
const adapter = new WsServerAdapter(
|
||||
'ws-in',
|
||||
serverConfig({ maxPayloadBytes: 262_144_000 }),
|
||||
ctx(),
|
||||
);
|
||||
await openServer(adapter);
|
||||
|
||||
expect(servers[0]!.options).toMatchObject({ maxPayload: 262_144_000 });
|
||||
await adapter.close();
|
||||
});
|
||||
|
||||
it('leaves the transport default in place when the cap is unset', async () => {
|
||||
const adapter = new WsServerAdapter('ws-in', serverConfig(), ctx());
|
||||
await openServer(adapter);
|
||||
|
||||
expect((servers[0]!.options as { maxPayload?: number }).maxPayload).toBeUndefined();
|
||||
await adapter.close();
|
||||
});
|
||||
|
||||
it('rebinds when only maxPayloadBytes changes', async () => {
|
||||
const adapter = new WsServerAdapter(
|
||||
'ws-in',
|
||||
serverConfig({ maxPayloadBytes: 1024 }),
|
||||
ctx(),
|
||||
);
|
||||
await openServer(adapter);
|
||||
|
||||
const reloading = adapter.reload(serverConfig({ maxPayloadBytes: 2048 }));
|
||||
await vi.waitFor(() => expect(servers).toHaveLength(2));
|
||||
servers[1]!.emit('listening');
|
||||
expect(await reloading).toBe(1); // NetworkReloadType.Reopened
|
||||
|
||||
expect(servers[1]!.options).toMatchObject({ maxPayload: 2048 });
|
||||
expect(servers[0]!.closed).toBe(true);
|
||||
await adapter.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('WsClientAdapter — maxPayloadBytes wiring', () => {
|
||||
beforeEach(() => {
|
||||
clientInstances.length = 0;
|
||||
clientOptions.length = 0;
|
||||
});
|
||||
|
||||
it('forwards the configured cap to the WebSocket client', () => {
|
||||
const adapter = new WsClientAdapter(
|
||||
'ws-out',
|
||||
clientConfig({ maxPayloadBytes: 524_288_000 }),
|
||||
ctx(),
|
||||
);
|
||||
adapter.open();
|
||||
|
||||
expect(clientOptions[0]).toMatchObject({ maxPayload: 524_288_000 });
|
||||
adapter.forceClose();
|
||||
});
|
||||
|
||||
it('leaves the transport default in place when the cap is unset', () => {
|
||||
const adapter = new WsClientAdapter('ws-out', clientConfig(), ctx());
|
||||
adapter.open();
|
||||
|
||||
expect((clientOptions[0] as { maxPayload?: number }).maxPayload).toBeUndefined();
|
||||
adapter.forceClose();
|
||||
});
|
||||
|
||||
it('reconnects when only maxPayloadBytes changes', async () => {
|
||||
const adapter = new WsClientAdapter(
|
||||
'ws-out',
|
||||
clientConfig({ maxPayloadBytes: 1024 }),
|
||||
ctx(),
|
||||
);
|
||||
adapter.open();
|
||||
const first = clientInstances[0]!;
|
||||
first.emit('open');
|
||||
|
||||
// The old socket's close event fires after the new one exists; the
|
||||
// adapter ignores it (#97), so the reconnect must come from reload().
|
||||
await adapter.reload(clientConfig({ maxPayloadBytes: 4096 }));
|
||||
|
||||
expect(clientInstances).toHaveLength(2);
|
||||
expect(clientOptions[1]).toMatchObject({ maxPayload: 4096 });
|
||||
adapter.forceClose();
|
||||
});
|
||||
});
|
||||
|
||||
// The third place that reads WebSocket frames: the WebSocket server embedded in
|
||||
// an HTTP listener. It has no fake-specific seam beyond the WebSocketServer mock,
|
||||
// so these cases run the real HTTP listener on an ephemeral port.
|
||||
describe('HttpServerAdapter (embedded WebSocket) — maxPayloadBytes wiring', () => {
|
||||
beforeEach(() => {
|
||||
servers.length = 0;
|
||||
});
|
||||
|
||||
function httpConfig(over: Partial<HttpServerNetwork> = {}): HttpServerNetwork {
|
||||
return {
|
||||
name: 'http-in',
|
||||
enabled: true,
|
||||
host: '127.0.0.1',
|
||||
port: 0,
|
||||
path: '/',
|
||||
enableWebSocket: true,
|
||||
accessToken: '',
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
maxPayloadBytes: undefined,
|
||||
...over,
|
||||
} as HttpServerNetwork;
|
||||
}
|
||||
|
||||
it('forwards the configured cap to the embedded WebSocketServer', async () => {
|
||||
const adapter = new HttpServerAdapter(
|
||||
'http-in',
|
||||
httpConfig({ maxPayloadBytes: 131_072 }),
|
||||
ctx(),
|
||||
);
|
||||
await adapter.open();
|
||||
|
||||
expect(servers[0]!.options).toMatchObject({ maxPayload: 131_072 });
|
||||
await adapter.close();
|
||||
});
|
||||
|
||||
it('leaves the transport default in place when the cap is unset', async () => {
|
||||
const adapter = new HttpServerAdapter('http-in', httpConfig(), ctx());
|
||||
await adapter.open();
|
||||
|
||||
expect((servers[0]!.options as { maxPayload?: number }).maxPayload).toBeUndefined();
|
||||
await adapter.close();
|
||||
});
|
||||
|
||||
it('rebinds when only maxPayloadBytes changes', async () => {
|
||||
const adapter = new HttpServerAdapter(
|
||||
'http-in',
|
||||
httpConfig({ maxPayloadBytes: 1024 }),
|
||||
ctx(),
|
||||
);
|
||||
await adapter.open();
|
||||
|
||||
const reloading = adapter.reload(httpConfig({ maxPayloadBytes: 2048 }));
|
||||
await vi.waitFor(() => expect(servers).toHaveLength(2));
|
||||
expect(await reloading).toBe(1); // NetworkReloadType.Reopened
|
||||
expect(servers[1]!.options).toMatchObject({ maxPayload: 2048 });
|
||||
await adapter.close();
|
||||
});
|
||||
|
||||
it('does not rebind for a cap change while the adapter has no WebSocket transport', async () => {
|
||||
const adapter = new HttpServerAdapter(
|
||||
'http-in',
|
||||
httpConfig({ enableWebSocket: false, maxPayloadBytes: 1024 }),
|
||||
ctx(),
|
||||
);
|
||||
await adapter.open();
|
||||
expect(servers).toHaveLength(0); // no WS server without the opt-in
|
||||
|
||||
const reloading = adapter.reload(
|
||||
httpConfig({ enableWebSocket: false, maxPayloadBytes: 2048 }),
|
||||
);
|
||||
expect(await reloading).toBe(0); // NetworkReloadType.Normal: listener untouched
|
||||
await adapter.close();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user