feat(onebot): add HTTP event streaming

Refs #593
This commit is contained in:
DrSmoothl committed 2026-11-01 23:15:51 +08:00
1 parent 54038c775a
commit 5f1700fc1b
13 files changed
+866 -73

No files matched your search

+20 -1
View File
@@ -56,6 +56,7 @@ export function makeDefaultOneBotConfig(): OneBotConfig {
port: 3000,
path: '/',
enableWebSocket: false,
enableSse: false,
accessToken: generateAccessToken(),
messageFormat: 'array',
reportSelfMessage: false,
@@ -417,7 +418,7 @@ function validateRestoreAdapterArray(
: ['url', 'role', 'reconnectIntervalMs'];
if (kind === 'httpServers') {
specific.push('enableWebSocket', 'maxPayloadBytes');
specific.push('enableWebSocket', 'enableSse', 'maxPayloadBytes');
}
if (kind === 'wsServers') {
@@ -488,6 +489,14 @@ function validateRestoreAdapterArray(
) {
invalid(`${pathAt}.enableWebSocket must be a boolean`);
}
if (
kind === 'httpServers' &&
raw.enableSse !== undefined &&
typeof raw.enableSse !== 'boolean'
) {
invalid(`${pathAt}.enableSse must be a boolean`);
}
} else {
if (raw.url !== undefined && typeof raw.url !== 'string') {
invalid(`${pathAt}.url must be a string`);
@@ -675,6 +684,10 @@ export function assertValidOneBotConfig(value: unknown): asserts value is OneBot
invalid(`${at}.enableWebSocket must be a boolean`);
}
if (item.enableSse !== undefined && typeof item.enableSse !== 'boolean') {
invalid(`${at}.enableSse must be a boolean`);
}
validateServerBinding(item, at, serverBindings);
});
validateNetworkList(value.networks, 'httpClients', seen, (item, at) => {
@@ -1103,6 +1116,7 @@ function httpServerToJson(n: HttpServerNetwork): JsonObject {
out.port = n.port;
out.path = n.path ?? '/';
out.enableWebSocket = n.enableWebSocket === true;
out.enableSse = n.enableSse === true;
return out;
}
@@ -1418,6 +1432,10 @@ function parseHttpServer(value: JsonObject, defaults: AdapterDefaults): HttpServ
invalid('http server enableWebSocket must be a boolean');
}
if (value.enableSse !== undefined && typeof value.enableSse !== 'boolean') {
invalid('http server enableSse must be a boolean');
}
const port = asNumber(value.port, 0);
if (port <= 0) {
@@ -1430,6 +1448,7 @@ function parseHttpServer(value: JsonObject, defaults: AdapterDefaults): HttpServ
port,
path: asString(value.path, '/'),
enableWebSocket: value.enableWebSocket === true,
enableSse: value.enableSse === true,
maxPayloadBytes,
});
}
@@ -2,7 +2,7 @@ import { createLogger, runWithTraceRequest } from '@snowluma/common/logger';
import { WebSocketServer } from '@snowluma/websocket';
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http';
import type { ApiHandler } from '../api-handler';
import type { DispatchPayload } from '../event-filter';
import { resolveReportOptions, type DispatchPayload } from '../event-filter';
import type { ApiResponse, HttpServerNetwork, JsonObject, JsonValue } from '../types';
import {
StreamTransportClosedError,
@@ -14,6 +14,7 @@ import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext }
import { isAuthorized, normalizePath } from './utils';
import { WsServerConnections } from './ws-server-connections';
import { httpTraceparent } from './http-trace';
import { HttpSseConnections } from './http-sse-connections';
const moduleLog = createLogger('OneBot.HTTP');
@@ -26,9 +27,13 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
private acceptingActions = false;
private readonly inFlightActions = new Set<Promise<void>>();
private readonly webSocketConnections: WsServerConnections;
private readonly sseConnections: HttpSseConnections;
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx, moduleLog);
this.sseConnections = new HttpSseConnections(config, this.log, () =>
this.bootstrapMetaFrames(resolveReportOptions(this.config)),
);
this.webSocketConnections = new WsServerConnections(name, config, ctx, this.log, {
frame: (event, options) => this.metaFrame(event, options),
bootstrap: (options) => this.bootstrapMetaFrames(options),
@@ -80,6 +85,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
const wasAcceptingWebSocketActions = this.webSocketConnections.isAcceptingActions;
this.acceptingActions = false;
this.webSocketConnections.stopAccepting();
this.sseConnections.close('server closing');
this.isEnabled = false;
this.listening = false;
const server = this.server;
@@ -161,6 +167,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
this.releaseForced = true;
this.acceptingActions = false;
this.webSocketConnections.stopAccepting();
this.sseConnections.close('server closing');
this.isEnabled = false;
this.listening = false;
this.webSocketConnections.terminateAll();
@@ -206,10 +213,15 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
};
}
const detail =
let detail =
this.config.enableWebSocket === true
? `监听中 · WebSocket ${this.webSocketConnections.connectionCount} 个客户端`
: '监听中';
if (this.config.enableSse === true) {
detail += ` · SSE ${this.sseConnections.connectionCount} 个客户端`;
}
return { name: this.name, kind: 'httpServer', status: 'ok', detail };
}
@@ -225,14 +237,21 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
protected override onConfigReplaced(next: HttpServerNetwork): void {
this.webSocketConnections.updateConfig(next);
this.sseConnections.updateConfig(next);
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
if (this.config.enableWebSocket !== true || !this.isEnabled) {
if (!this.isEnabled) {
return;
}
this.webSocketConnections.onEvent(payload);
if (this.config.enableWebSocket === true) {
this.webSocketConnections.onEvent(payload);
}
if (this.config.enableSse === true) {
this.sseConnections.onEvent(payload);
}
}
private startServer(): Promise<void> {
@@ -307,6 +326,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
this.isEnabled = false;
this.acceptingActions = false;
this.webSocketConnections.stopAccepting();
this.sseConnections.close('server closing');
this.recordTransportFailure(error);
if (opening) {
@@ -388,11 +408,38 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
return;
}
if (!isAuthorized(req, accessToken)) {
if (!isAuthorized(req, accessToken, true)) {
respond(401, { status: 'failed', retcode: 1401, data: null, wording: 'unauthorized' });
return;
}
if (action === '_events') {
if (apiQuiescedAtIngress) {
return;
}
if (this.config.enableSse !== true) {
respond(404, {
status: 'failed',
retcode: 1404,
data: null,
wording: 'SSE is disabled',
});
} else if (req.method !== 'GET') {
res.setHeader('Allow', 'GET');
respond(405, {
status: 'failed',
retcode: 1405,
data: null,
wording: 'SSE requires GET',
});
} else {
this.sseConnections.accept(req, res);
}
return;
}
if (req.headers.traceparent !== undefined) {
const traceparent = httpTraceparent(req.headers.traceparent);
@@ -0,0 +1,275 @@
import { randomUUID } from 'node:crypto';
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { Logger } from '@snowluma/common/logger';
import { pickDispatchJson, resolveReportOptions, type DispatchPayload } from '../event-filter';
import type { HttpServerNetwork } from '../types';
const REPLAY_EVENTS = 256;
const REPLAY_BYTES = 8 * 1024 * 1024;
const CLIENT_BYTES = 8 * 1024 * 1024;
const HEARTBEAT_MS = 15_000;
interface Frame {
sequence: number;
text: string;
bytes: number;
}
interface Connection {
response: ServerResponse;
queue: Frame[];
bytes: number;
blocked: boolean;
dispose(): void;
}
/** Per-adapter event history and connections; never shared between accounts. */
export class HttpSseConnections {
private config: HttpServerNetwork;
private epoch = randomUUID();
private sequence = 0;
private droppedThrough = 0;
private history: Frame[] = [];
private historyBytes = 0;
private readonly connections = new Set<Connection>();
private heartbeat: ReturnType<typeof setInterval> | undefined;
constructor(
config: HttpServerNetwork,
private readonly log: Logger,
private readonly bootstrap: () => string[],
) {
this.config = structuredClone(config);
}
get connectionCount(): number {
return this.connections.size;
}
updateConfig(next: HttpServerNetwork): void {
if (
this.config.enableSse !== next.enableSse ||
(this.config.accessToken ?? '') !== (next.accessToken ?? '') ||
(this.config.messageFormat ?? 'array') !== (next.messageFormat ?? 'array') ||
(this.config.reportSelfMessage ?? false) !== (next.reportSelfMessage ?? false)
) {
// Replaying frames shaped under the previous policy could disclose
// events which the new report policy excludes.
this.close('configuration changed');
}
this.config = structuredClone(next);
}
accept(request: IncomingMessage, response: ServerResponse): void {
const cursor = request.headers['last-event-id'];
let after = this.sequence;
if (cursor !== undefined && cursor !== '') {
const match =
typeof cursor === 'string'
? /^([0-9a-f-]{36}):(0|[1-9]\d{0,15})$/.exec(cursor)
: null;
const value = match ? Number(match[2]) : NaN;
if (!match || !Number.isSafeInteger(value)) {
this.rejectCursor(response, 400, 'invalid Last-Event-ID');
return;
}
if (match[1] !== this.epoch || value < this.droppedThrough || value > this.sequence) {
this.rejectCursor(
response,
409,
'SSE replay unavailable; resync and reconnect without Last-Event-ID',
);
return;
}
after = value;
}
response.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
'X-Accel-Buffering': 'no',
Connection: 'keep-alive',
});
response.flushHeaders();
request.socket.setTimeout(0);
const onDrain = (): void => {
connection.blocked = false;
this.flush(connection);
};
const onError = (error: Error): void => {
this.log.warn('[%s] SSE connection failed: %s', this.config.name, error.message);
this.drop(connection);
};
const onClose = (): void => this.drop(connection);
const connection: Connection = {
response,
queue: [],
bytes: 0,
blocked: false,
dispose: () => {
response.off('drain', onDrain);
response.off('close', onClose);
response.off('error', onError);
},
};
response.on('drain', onDrain);
response.once('close', onClose);
response.on('error', onError);
this.connections.add(connection);
this.log.debug('[%s] SSE connected (%d clients)', this.config.name, this.connectionCount);
this.enqueue(connection, this.frame('retry: 3000\n\n'));
for (const frame of this.history) {
if (frame.sequence > after) {
this.enqueue(connection, frame);
}
}
// Bootstrap supplies a cursor even when there has not been a message.
// Only broadcast events consume sequence numbers and enter history.
for (const json of this.bootstrap()) {
this.enqueue(connection, this.eventFrame(json));
}
if (!this.heartbeat && this.connections.size > 0) {
this.heartbeat = setInterval(() => {
const frame = this.frame(': ping\n\n');
for (const client of this.connections) {
this.enqueue(client, frame);
}
}, HEARTBEAT_MS);
this.heartbeat.unref();
}
}
onEvent(payload: DispatchPayload): void {
const json = pickDispatchJson(payload, resolveReportOptions(this.config));
if (json === null) {
return;
}
this.sequence += 1;
const frame = this.eventFrame(json);
this.history.push(frame);
this.historyBytes += frame.bytes;
while (this.history.length > REPLAY_EVENTS || this.historyBytes > REPLAY_BYTES) {
const removed = this.history.shift()!;
this.historyBytes -= removed.bytes;
this.droppedThrough = removed.sequence;
}
for (const connection of this.connections) {
this.enqueue(connection, frame);
}
}
close(reason: string): void {
if (this.connections.size > 0) {
this.log.debug('[%s] SSE closing: %s', this.config.name, reason);
}
for (const connection of this.connections) {
this.drop(connection);
}
this.history = [];
this.historyBytes = 0;
this.sequence = 0;
this.droppedThrough = 0;
this.epoch = randomUUID();
}
private eventFrame(json: string): Frame {
return this.frame(`id: ${this.epoch}:${this.sequence}\ndata: ${json}\n\n`);
}
private frame(text: string): Frame {
return { sequence: this.sequence, text, bytes: Buffer.byteLength(text) };
}
private enqueue(connection: Connection, frame: Frame): void {
if (!this.connections.has(connection)) {
return;
}
if (connection.bytes + connection.response.writableLength + frame.bytes > CLIENT_BYTES) {
this.log.warn(
'[%s] SSE client exceeded %d buffered bytes; disconnecting',
this.config.name,
CLIENT_BYTES,
);
this.drop(connection);
return;
}
connection.queue.push(frame);
connection.bytes += frame.bytes;
this.flush(connection);
}
private flush(connection: Connection): void {
while (!connection.blocked && connection.queue.length > 0) {
const frame = connection.queue.shift()!;
connection.bytes -= frame.bytes;
try {
connection.blocked = !connection.response.write(frame.text);
} catch (error) {
this.log.warn(
'[%s] SSE write failed: %s',
this.config.name,
error instanceof Error ? error.message : String(error),
);
this.drop(connection);
return;
}
}
}
private drop(connection: Connection): void {
if (!this.connections.delete(connection)) {
return;
}
connection.queue = [];
connection.bytes = 0;
// The response error handler remains until close, including when a
// previously queued write fails during destruction.
if (connection.response.destroyed) {
connection.dispose();
} else {
connection.response.once('close', connection.dispose);
connection.response.destroy();
}
if (this.connections.size === 0 && this.heartbeat) {
clearInterval(this.heartbeat);
this.heartbeat = undefined;
}
}
private rejectCursor(response: ServerResponse, status: number, wording: string): void {
this.log.warn('[%s] rejected SSE reconnect: %s', this.config.name, wording);
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
response.end(
JSON.stringify({
status: 'failed',
retcode: status === 400 ? 1400 : 1409,
data: null,
wording,
}),
);
}
}
+6 -2
View File
@@ -9,14 +9,18 @@ import type { IncomingMessage } from 'http';
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 {
export function isAuthorized(
request: IncomingMessage,
token: string,
allowRawToken = false,
): boolean {
if (!token) {
return true;
}
const auth = request.headers.authorization ?? '';
if (auth === `Bearer ${token}`) {
if (auth === `Bearer ${token}` || (allowRawToken && auth === token)) {
return true;
}
+2
View File
@@ -65,6 +65,8 @@ export interface HttpServerNetwork extends NetworkBase, WsFrameLimitConfig {
path?: string;
/** Accept OneBot WebSocket clients on the same HTTP listener. */
enableWebSocket?: boolean;
/** Serve OneBot events at <path>/_events, with bounded reconnect replay. */
enableSse?: boolean;
}
export interface HttpClientNetwork extends NetworkBase {