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
@@ -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