13 files changed
+866
-73
No files matched your search
@@ -0,0 +1,86 @@
|
||||
# OneBot HTTP event streams
|
||||
|
||||
An HTTP server can serve actions and Server-Sent Events on the same listener.
|
||||
Enable **SSE** in the WebUI's HTTP API adapter, or set `enableSse: true` on an
|
||||
entry in `networks.httpServers`. The default is `false`; existing HTTP and
|
||||
WebSocket configurations keep their behavior. SSE and `enableWebSocket` may both
|
||||
be enabled.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "web-client",
|
||||
"host": "127.0.0.1",
|
||||
"port": 3000,
|
||||
"path": "/api",
|
||||
"enableSse": true,
|
||||
"accessToken": "replace-with-your-token",
|
||||
"messageFormat": "array",
|
||||
"reportSelfMessage": false
|
||||
}
|
||||
```
|
||||
|
||||
`GET /api/_events?access_token=<token>` opens the event stream. Actions continue
|
||||
to use `POST /api/<action>` with a JSON parameter object. HTTP requests accept
|
||||
`Authorization: Bearer <token>`, `Authorization: <token>` (for Stapxs QQ Lite), or
|
||||
the `access_token` query parameter. The configured token and bind address still
|
||||
apply. Empty tokens retain the existing unauthenticated HTTP behavior.
|
||||
|
||||
```js
|
||||
const events = new EventSource(`api/_events?access_token=${encodeURIComponent(token)}`);
|
||||
events.onmessage = ({ data }) => console.log(JSON.parse(data));
|
||||
events.onerror = () =>
|
||||
console.error('Event connection interrupted; check connection and authentication');
|
||||
|
||||
const response = await fetch('api/get_status', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: token },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
if (!response.ok) throw new Error(`Action failed: HTTP ${response.status}`);
|
||||
console.log(await response.json());
|
||||
// Close the stream when the owning page/component is disposed.
|
||||
// events.close();
|
||||
```
|
||||
|
||||
Configure Stapxs's SSE event address as `api/_events` and HTTP address as `api`
|
||||
when both are exposed under that same-origin proxy prefix. Forward the request
|
||||
path, query string, authorization and `Last-Event-ID` headers unchanged. SnowLuma
|
||||
does not add cross-origin access grants. TLS and any additional proxy
|
||||
authentication remain the proxy's responsibility.
|
||||
|
||||
Responses use `text/event-stream`, `Cache-Control: no-cache, no-transform`, and
|
||||
`X-Accel-Buffering: no`. Events are ordinary unnamed `data:` frames containing
|
||||
OneBot JSON. Connection lifecycle and current heartbeat events bootstrap each
|
||||
subscription. Transport comments (`: ping`) are sent every 15 seconds; they are
|
||||
not OneBot events. The browser's reconnect delay is 3 seconds.
|
||||
|
||||
## Reconnect and resource limits
|
||||
|
||||
Every broadcast event has an opaque `id`. A reconnect with `Last-Event-ID`
|
||||
replays events after that cursor, in order, before connection bootstrap events
|
||||
and subsequent live events. Native EventSource sends this header automatically
|
||||
when reconnecting the same object. A new subscription without the header starts
|
||||
at the present and does not receive old messages.
|
||||
|
||||
Each adapter retains at most 256 events and 8 MiB in memory, including while no
|
||||
client is connected. This is a short reconnect window, not durable message
|
||||
history. Accounts and adapter instances have independent histories. Event IDs
|
||||
are invalidated on restart, shutdown, token rotation, report-policy changes or
|
||||
disabling SSE. Neither replay nor live delivery bypasses `messageFormat` or
|
||||
`reportSelfMessage`.
|
||||
|
||||
An invalid cursor returns HTTP 400. An expired, future or foreign cursor returns
|
||||
HTTP 409 with `wording` explaining that replay is unavailable. There is no silent
|
||||
fallback to live-only delivery. After reconciling the application's state/history,
|
||||
close and recreate EventSource to subscribe without the old cursor. EventSource's
|
||||
error callback does not expose the HTTP error body; fetch-based consumers can
|
||||
inspect it directly. Bootstrap events can share the latest broadcast cursor and
|
||||
must not be treated as newly persisted message events.
|
||||
|
||||
Each client's pending output is limited to 8 MiB. Slow readers are disconnected
|
||||
with a warning instead of retaining unbounded events or blocking other clients.
|
||||
A single frame exceeding this limit also disconnects that client. Reconnection
|
||||
is subject to the same replay limits. Disconnect, hot reload and shutdown release
|
||||
connections and heartbeat timers; rotating the token revokes existing streams.
|
||||
|
||||
Tests: `pnpm --filter @snowluma/onebot exec vitest run tests/http-server-sse.test.ts tests/http-sse-backpressure.test.ts tests/http-server-websocket-config.test.ts`.
|
||||
@@ -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,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import http, { type IncomingMessage } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { HttpServerAdapter } from '../src/network/http-server-adapter';
|
||||
import type { NetworkAdapterContext } from '../src/network/adapter';
|
||||
import { buildDispatchPayload } from '../src/event-filter';
|
||||
import type { HttpServerNetwork, JsonObject } from '../src/types';
|
||||
|
||||
const adapters: HttpServerAdapter[] = [];
|
||||
const responses: IncomingMessage[] = [];
|
||||
|
||||
async function start(overrides: Partial<HttpServerNetwork> = {}, uin = '10001') {
|
||||
const config: HttpServerNetwork = {
|
||||
name: 'sse',
|
||||
host: '127.0.0.1',
|
||||
port: 0,
|
||||
path: '/api',
|
||||
enableSse: true,
|
||||
accessToken: 'test-secret',
|
||||
...overrides,
|
||||
};
|
||||
const api = {
|
||||
isAcceptingActions: true,
|
||||
isStreamAction: () => false,
|
||||
handle: vi.fn(async () => ({ status: 'ok', retcode: 0, data: { self_id: uin } })),
|
||||
};
|
||||
const adapter = new HttpServerAdapter(config.name, config, {
|
||||
uin,
|
||||
api,
|
||||
buildLifecycleEvent: (subType: string) => ({
|
||||
self_id: uin,
|
||||
post_type: 'meta_event',
|
||||
meta_event_type: 'lifecycle',
|
||||
sub_type: subType,
|
||||
}),
|
||||
buildHeartbeatEvent: () => ({
|
||||
self_id: uin,
|
||||
post_type: 'meta_event',
|
||||
meta_event_type: 'heartbeat',
|
||||
}),
|
||||
} as unknown as NetworkAdapterContext);
|
||||
adapters.push(adapter);
|
||||
await adapter.open();
|
||||
const port = ((adapter as unknown as { server: http.Server }).server.address() as AddressInfo)
|
||||
.port;
|
||||
const request = (
|
||||
path = '/api/_events?access_token=test-secret',
|
||||
headers: Record<string, string> = {},
|
||||
method = 'GET',
|
||||
): Promise<IncomingMessage> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const req = http.request(
|
||||
{ hostname: '127.0.0.1', port, path, headers, method },
|
||||
(res) => {
|
||||
responses.push(res);
|
||||
// A stream closed intentionally by the test/server can be aborted.
|
||||
res.on('error', () => undefined);
|
||||
resolve(res);
|
||||
},
|
||||
);
|
||||
req.on('error', reject);
|
||||
req.end();
|
||||
});
|
||||
|
||||
const emit = (id: number, postType = 'message') => {
|
||||
const event: JsonObject = {
|
||||
self_id: uin,
|
||||
post_type: postType,
|
||||
message_id: id,
|
||||
message: [{ type: 'text', data: { text: `line\n${id}` } }],
|
||||
raw_message: `line\n${id}`,
|
||||
};
|
||||
adapter.onEvent(event, buildDispatchPayload(event));
|
||||
};
|
||||
|
||||
return { adapter, config, request, emit, api };
|
||||
}
|
||||
|
||||
function collect(response: IncomingMessage) {
|
||||
let text = '';
|
||||
response.setEncoding('utf8');
|
||||
response.on('data', (chunk: string) => {
|
||||
text += chunk;
|
||||
});
|
||||
const frames = () =>
|
||||
text
|
||||
.split('\n\n')
|
||||
.filter((frame) => frame.includes('data: '))
|
||||
.map((frame) => {
|
||||
const id = /^id: (.+)$/m.exec(frame)?.[1];
|
||||
const data = JSON.parse(/^data: (.+)$/m.exec(frame)![1]) as JsonObject;
|
||||
return { id, data };
|
||||
});
|
||||
return { frames, text: () => text };
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
responses.splice(0).forEach((res) => res.destroy());
|
||||
await Promise.all(adapters.splice(0).map((adapter) => adapter.close()));
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('HTTP OneBot SSE', () => {
|
||||
it('shares HTTP actions and prefix, authenticates all supported token forms, and frames events', async () => {
|
||||
const { adapter, request, emit, api } = await start();
|
||||
expect((await request('/wrong/_events?access_token=test-secret')).statusCode).toBe(404);
|
||||
expect((await request('/api/_events')).statusCode).toBe(401);
|
||||
expect((await request('/api/_events?access_token=wrong')).statusCode).toBe(401);
|
||||
expect((await request(undefined, {}, 'POST')).statusCode).toBe(405);
|
||||
const streams = [];
|
||||
|
||||
for (const [path, headers] of [
|
||||
['/api/_events?access_token=test-secret', {}],
|
||||
['/api/_events', { authorization: 'Bearer test-secret' }],
|
||||
['/api/_events', { authorization: 'test-secret' }],
|
||||
] as Array<[string, Record<string, string>]>) {
|
||||
const res = await request(path, headers);
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.headers['content-type']).toContain('text/event-stream');
|
||||
expect(res.headers['cache-control']).toBe('no-cache, no-transform');
|
||||
expect(res.headers['x-accel-buffering']).toBe('no');
|
||||
streams.push(collect(res));
|
||||
}
|
||||
|
||||
emit(1);
|
||||
emit(2, 'message_sent');
|
||||
emit(3);
|
||||
await vi.waitFor(() =>
|
||||
expect(streams.every((stream) => stream.frames().length === 5)).toBe(true),
|
||||
);
|
||||
expect(
|
||||
streams[0]
|
||||
.frames()
|
||||
.slice(3)
|
||||
.map((frame) => frame.data.message_id),
|
||||
).toEqual([1, 3]);
|
||||
expect(streams[0].frames()[3].data.message).toEqual([
|
||||
{ type: 'text', data: { text: 'line\n1' } },
|
||||
]);
|
||||
expect(streams[0].text()).toContain('retry: 3000\n\n');
|
||||
const action = await request('/api/get_status', { authorization: 'test-secret' }, 'POST');
|
||||
expect(action.statusCode).toBe(200);
|
||||
expect(api.handle).toHaveBeenCalledWith('get_status', {});
|
||||
expect(adapter.describeStatus().detail).toContain('SSE 3 个客户端');
|
||||
});
|
||||
|
||||
it('replays exactly the missing events and maintains report format and self-message policy', async () => {
|
||||
const { request, emit } = await start({ messageFormat: 'string', reportSelfMessage: true });
|
||||
const initial = await request();
|
||||
const first = collect(initial);
|
||||
emit(1);
|
||||
await vi.waitFor(() => expect(first.frames()).toHaveLength(4));
|
||||
const cursor = first.frames()[3].id!;
|
||||
initial.destroy();
|
||||
emit(2, 'message_sent');
|
||||
emit(3);
|
||||
const resumed = collect(await request(undefined, { 'Last-Event-ID': cursor }));
|
||||
await vi.waitFor(() => expect(resumed.frames()).toHaveLength(5));
|
||||
expect(
|
||||
resumed
|
||||
.frames()
|
||||
.slice(0, 2)
|
||||
.map((frame) => frame.data.message_id),
|
||||
).toEqual([2, 3]);
|
||||
expect(resumed.frames()[0].data.message).toBe('line\n2');
|
||||
expect(resumed.frames()[0].data.post_type).toBe('message_sent');
|
||||
});
|
||||
|
||||
it('rejects expired, malformed, future and other-account cursors without silently losing events', async () => {
|
||||
const first = await start();
|
||||
const second = await start({}, '10002');
|
||||
const stream = collect(await first.request());
|
||||
await vi.waitFor(() => expect(stream.frames()).toHaveLength(3));
|
||||
const cursor = stream.frames()[0].id!;
|
||||
const header = { 'Last-Event-ID': cursor };
|
||||
expect((await second.request(undefined, header)).statusCode).toBe(409);
|
||||
expect((await first.request(undefined, { 'Last-Event-ID': 'broken' })).statusCode).toBe(
|
||||
400,
|
||||
);
|
||||
expect(
|
||||
(await first.request(undefined, { 'Last-Event-ID': cursor.replace(/:0$/, ':99') }))
|
||||
.statusCode,
|
||||
).toBe(409);
|
||||
|
||||
for (let i = 0; i < 257; i += 1) {
|
||||
first.emit(i);
|
||||
}
|
||||
|
||||
expect((await first.request(undefined, header)).statusCode).toBe(409);
|
||||
// A new subscription remains possible after explicit resynchronization.
|
||||
expect((await first.request()).statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('revokes live streams on token/report policy changes and closes without waiting on SSE', async () => {
|
||||
const { adapter, config, request } = await start();
|
||||
const res = await request();
|
||||
const closed = new Promise<void>((resolve) => res.once('close', resolve));
|
||||
await adapter.reload({ ...config, accessToken: 'rotated' });
|
||||
await closed;
|
||||
expect((await request()).statusCode).toBe(401);
|
||||
const next = await request('/api/_events?access_token=rotated');
|
||||
const changed = new Promise<void>((resolve) => next.once('close', resolve));
|
||||
await adapter.reload({ ...config, accessToken: 'rotated', reportSelfMessage: true });
|
||||
await changed;
|
||||
const last = await request('/api/_events?access_token=rotated');
|
||||
const ended = new Promise<void>((resolve) => last.once('close', resolve));
|
||||
await adapter.close();
|
||||
await ended;
|
||||
expect(adapter.describeStatus().status).toBe('disabled');
|
||||
});
|
||||
|
||||
it('is opt-in and can be enabled/disabled live without replacing the HTTP listener', async () => {
|
||||
const { adapter, config, request } = await start({ enableSse: false });
|
||||
expect((await request()).statusCode).toBe(404);
|
||||
await adapter.reload({ ...config, enableSse: true });
|
||||
const stream = await request();
|
||||
expect(stream.statusCode).toBe(200);
|
||||
const closed = new Promise<void>((resolve) => stream.once('close', resolve));
|
||||
await adapter.reload(config);
|
||||
await closed;
|
||||
expect((await request()).statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('sends comment heartbeats and releases their timer when the client leaves', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
|
||||
const { adapter, request } = await start();
|
||||
const res = await request();
|
||||
const stream = collect(res);
|
||||
await vi.waitFor(() => expect(stream.frames()).toHaveLength(3));
|
||||
await vi.advanceTimersByTimeAsync(15_000);
|
||||
await vi.waitFor(() => expect(stream.text()).toContain(': ping\n\n'));
|
||||
res.destroy();
|
||||
await vi.waitFor(() => expect(adapter.describeStatus().detail).toContain('SSE 0 个客户端'));
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -10,44 +10,75 @@ import {
|
||||
saveOneBotConfig,
|
||||
} from '../src/config';
|
||||
|
||||
describe('HTTP server WebSocket configuration', () => {
|
||||
let previousCwd: string;
|
||||
let tempDir: string;
|
||||
describe.each(['enableWebSocket', 'enableSse'] as const)(
|
||||
'HTTP server %s configuration',
|
||||
(switchName) => {
|
||||
let previousCwd: string;
|
||||
let tempDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
previousCwd = process.cwd();
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-http-ws-config-'));
|
||||
process.chdir(tempDir);
|
||||
});
|
||||
beforeEach(() => {
|
||||
previousCwd = process.cwd();
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-http-ws-config-'));
|
||||
process.chdir(tempDir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
afterEach(() => {
|
||||
process.chdir(previousCwd);
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('persists the opt-in switch through save and load', () => {
|
||||
const config = makeDefaultOneBotConfig();
|
||||
expect(config.networks.httpServers[0].enableWebSocket).toBe(false);
|
||||
config.networks.httpServers[0].enableWebSocket = true;
|
||||
it('persists the opt-in switch through save and load', () => {
|
||||
const config = makeDefaultOneBotConfig();
|
||||
expect(config.networks.httpServers[0][switchName]).toBe(false);
|
||||
config.networks.httpServers[0][switchName] = true;
|
||||
|
||||
saveOneBotConfig('10001', config);
|
||||
saveOneBotConfig('10001', config);
|
||||
|
||||
const onDisk = JSON.parse(
|
||||
fs.readFileSync(path.join(tempDir, 'config', 'onebot_10001.json'), 'utf8'),
|
||||
) as { networks: { httpServers: Array<{ enableWebSocket?: boolean }> } };
|
||||
expect(onDisk.networks.httpServers[0].enableWebSocket).toBe(true);
|
||||
expect(loadOneBotConfig('10001').networks.httpServers[0].enableWebSocket).toBe(true);
|
||||
});
|
||||
const onDisk = JSON.parse(
|
||||
fs.readFileSync(path.join(tempDir, 'config', 'onebot_10001.json'), 'utf8'),
|
||||
) as {
|
||||
networks: {
|
||||
httpServers: Array<{ enableWebSocket?: boolean; enableSse?: boolean }>;
|
||||
};
|
||||
};
|
||||
expect(onDisk.networks.httpServers[0][switchName]).toBe(true);
|
||||
expect(loadOneBotConfig('10001').networks.httpServers[0][switchName]).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects non-boolean values at public save and restore boundaries', () => {
|
||||
const config = makeDefaultOneBotConfig();
|
||||
(config.networks.httpServers[0] as unknown as Record<string, unknown>).enableWebSocket =
|
||||
'yes';
|
||||
expect(() => assertValidOneBotConfig(config)).toThrow(/enableWebSocket must be a boolean/);
|
||||
it('rejects non-boolean values at public save and restore boundaries', () => {
|
||||
const config = makeDefaultOneBotConfig();
|
||||
(config.networks.httpServers[0] as unknown as Record<string, unknown>)[switchName] =
|
||||
'yes';
|
||||
expect(() => assertValidOneBotConfig(config)).toThrow(
|
||||
`${switchName} must be a boolean`,
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
prepareOneBotConfigForRestore(
|
||||
{
|
||||
expect(() =>
|
||||
prepareOneBotConfigForRestore(
|
||||
{
|
||||
networks: {
|
||||
httpServers: [
|
||||
{
|
||||
name: 'http',
|
||||
host: '127.0.0.1',
|
||||
port: 3000,
|
||||
path: '/',
|
||||
[switchName]: 'yes',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
'per-uin',
|
||||
),
|
||||
).toThrow(`${switchName} must be a boolean`);
|
||||
});
|
||||
|
||||
it('fails fast when a hand-written config contains a non-boolean switch', () => {
|
||||
fs.mkdirSync(path.join(tempDir, 'config'), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(tempDir, 'config', 'onebot_10002.json'),
|
||||
JSON.stringify({
|
||||
mode: 'snapshot',
|
||||
networks: {
|
||||
httpServers: [
|
||||
{
|
||||
@@ -55,40 +86,18 @@ describe('HTTP server WebSocket configuration', () => {
|
||||
host: '127.0.0.1',
|
||||
port: 3000,
|
||||
path: '/',
|
||||
enableWebSocket: 'yes',
|
||||
[switchName]: 'yes',
|
||||
},
|
||||
],
|
||||
httpClients: [],
|
||||
wsServers: [],
|
||||
wsClients: [],
|
||||
},
|
||||
},
|
||||
'per-uin',
|
||||
),
|
||||
).toThrow(/enableWebSocket must be a boolean/);
|
||||
});
|
||||
}),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
it('fails fast when a hand-written config contains a non-boolean switch', () => {
|
||||
fs.mkdirSync(path.join(tempDir, 'config'), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(tempDir, 'config', 'onebot_10002.json'),
|
||||
JSON.stringify({
|
||||
mode: 'snapshot',
|
||||
networks: {
|
||||
httpServers: [
|
||||
{
|
||||
name: 'http',
|
||||
host: '127.0.0.1',
|
||||
port: 3000,
|
||||
path: '/',
|
||||
enableWebSocket: 'yes',
|
||||
},
|
||||
],
|
||||
httpClients: [],
|
||||
wsServers: [],
|
||||
wsClients: [],
|
||||
},
|
||||
}),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
expect(() => loadOneBotConfig('10002')).toThrow(/enableWebSocket must be a boolean/);
|
||||
});
|
||||
});
|
||||
expect(() => loadOneBotConfig('10002')).toThrow(`${switchName} must be a boolean`);
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import type { IncomingMessage, ServerResponse } from 'node:http';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { HttpSseConnections } from '../src/network/http-sse-connections';
|
||||
import { buildDispatchPayload } from '../src/event-filter';
|
||||
|
||||
class Response extends EventEmitter {
|
||||
writableLength = 0;
|
||||
destroyed = false;
|
||||
blocked = false;
|
||||
throwOnWrite = false;
|
||||
readonly frames: string[] = [];
|
||||
writeHead = vi.fn();
|
||||
flushHeaders = vi.fn();
|
||||
write(text: string): boolean {
|
||||
if (this.throwOnWrite) {
|
||||
throw new Error('test write failure');
|
||||
}
|
||||
|
||||
this.frames.push(text);
|
||||
return !this.blocked;
|
||||
}
|
||||
destroy(): void {
|
||||
this.destroyed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
end = vi.fn();
|
||||
}
|
||||
|
||||
describe('SSE bounded buffers', () => {
|
||||
it('pauses until drain, disconnects only the overflowing peer, and bounds replay by bytes', () => {
|
||||
const owner = new HttpSseConnections(
|
||||
{ name: 'bounded', port: 0 },
|
||||
createLogger('SseTest'),
|
||||
() => ['{}'],
|
||||
);
|
||||
const request = {
|
||||
headers: {},
|
||||
socket: { setTimeout: vi.fn() },
|
||||
} as unknown as IncomingMessage;
|
||||
const slow = new Response();
|
||||
const fast = new Response();
|
||||
owner.accept(request, slow as unknown as ServerResponse);
|
||||
owner.accept(request, fast as unknown as ServerResponse);
|
||||
const cursor = /^id: (.+)$/m.exec(fast.frames[1])![1];
|
||||
slow.blocked = true;
|
||||
owner.onEvent(buildDispatchPayload({ index: 1 }));
|
||||
owner.onEvent(buildDispatchPayload({ index: 2 }));
|
||||
expect(slow.frames).toHaveLength(3);
|
||||
slow.blocked = false;
|
||||
slow.emit('drain');
|
||||
expect(slow.frames).toHaveLength(4);
|
||||
slow.blocked = true;
|
||||
owner.onEvent(buildDispatchPayload({ index: 3 }));
|
||||
|
||||
for (let index = 4; index < 8; index += 1) {
|
||||
owner.onEvent(buildDispatchPayload({ index, text: 'x'.repeat(3 * 1024 * 1024) }));
|
||||
}
|
||||
|
||||
expect(slow.destroyed).toBe(true);
|
||||
expect(fast.destroyed).toBe(false);
|
||||
expect(fast.frames.at(-1)).toContain('"index":7');
|
||||
expect(owner.connectionCount).toBe(1);
|
||||
const expired = new Response();
|
||||
owner.accept(
|
||||
{ ...request, headers: { 'last-event-id': cursor } } as IncomingMessage,
|
||||
expired as unknown as ServerResponse,
|
||||
);
|
||||
expect(expired.writeHead).toHaveBeenCalledWith(409, expect.anything());
|
||||
owner.close('test finished');
|
||||
expect(fast.destroyed).toBe(true);
|
||||
expect(owner.connectionCount).toBe(0);
|
||||
});
|
||||
|
||||
it('reports a synchronous write failure and continues serving other clients', () => {
|
||||
const log = createLogger('SseTest');
|
||||
const warning = vi.spyOn(log, 'warn');
|
||||
const owner = new HttpSseConnections({ name: 'errors', port: 0 }, log, () => ['{}']);
|
||||
const request = {
|
||||
headers: {},
|
||||
socket: { setTimeout: vi.fn() },
|
||||
} as unknown as IncomingMessage;
|
||||
const failed = new Response();
|
||||
const healthy = new Response();
|
||||
owner.accept(request, failed as unknown as ServerResponse);
|
||||
owner.accept(request, healthy as unknown as ServerResponse);
|
||||
failed.throwOnWrite = true;
|
||||
owner.onEvent(buildDispatchPayload({ index: 1 }));
|
||||
expect(warning).toHaveBeenCalledWith(
|
||||
expect.stringContaining('SSE write failed'),
|
||||
'errors',
|
||||
'test write failure',
|
||||
);
|
||||
expect(failed.destroyed).toBe(true);
|
||||
expect(healthy.frames.at(-1)).toContain('"index":1');
|
||||
owner.close('test finished');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user