feat(onebot): Stream API transport plumbing (#163 phase 1)

Foundation for NapCat-compatible Stream API actions (chunked file
upload/download): a single request answered by many response frames.

- streaming.ts: StreamSink + frame wrappers (wrapStreamFrame /
  wrapStreamTerminal) matching NapCat's wire — each frame an OB11 envelope
  with stream:'stream-action', data.type ∈ stream/response/error, and
  message mirrored into wording.
- ApiHandler: registerStreamAction / isStreamAction; handle() threads a
  sink; processStreamRequest drives WS multi-frame dispatch with optional
  liveness-based abort; dead processRequest removed.
- action-kit: defineStreamAction (sink-aware run, registers as a stream
  action) reusing defineAction's parse/describe.
- adapters: HTTP server streams chunked \r\n\r\n-delimited frames (no
  Content-Length, no false application/json), aborting on client
  disconnect; WS server/client use a backpressure-aware safeSendAsync and
  abort a stream once the socket closes.

No stream actions are registered yet — those land in the next phases.
Verified by two adversarial review passes. 480 onebot tests green.
This commit is contained in:
DrSmoothl committed 2026-06-30 14:40:39 +08:00
1 parent 62eb8fd763
commit 01ef98abb6
13 files changed
+452 -38

No files matched your search

@@ -5,8 +5,10 @@ import {
type Server,
type ServerResponse,
} from 'http';
import type { ApiHandler } from '../api-handler';
import type { DispatchPayload } from '../event-filter';
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
import type { ApiResponse, HttpServerNetwork, JsonObject, JsonValue } from '../types';
import { type StreamSink, wrapStreamFrame, wrapStreamTerminal } from '../streaming';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath } from './utils';
@@ -181,6 +183,13 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
return;
}
// Stream API (#163): answer with chunked multi-frame output — each frame
// a JSON envelope delimited by `\r\n\r\n`, terminated by the final frame.
if (this.ctx.api.isStreamAction(action)) {
await streamHttpResponse(res, this.ctx.api, action, params as JsonObject, echo as JsonValue | undefined);
return;
}
const response = await this.ctx.api.handle(action, params as JsonObject);
if (echo !== undefined) {
response.echo = echo as JsonValue;
@@ -212,7 +221,41 @@ function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Prom
}
function writeJson(res: ServerResponse, statusCode: number, data: unknown): void {
// A streaming response may already have flushed headers (and even ended); a
// late error must not double-send and trip ERR_HTTP_HEADERS_SENT.
if (res.headersSent || res.writableEnded) return;
res.statusCode = statusCode;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(data));
}
/** Stream a multi-frame Stream API response (#163): chunked transfer (no
* Content-Length → Node frames it), each frame a JSON envelope delimited by
* `\r\n\r\n`, the action's terminal response written last. Matches NapCat:
* the body is `\r\n\r\n`-joined JSON objects, NOT a single JSON document, so
* no `application/json` Content-Type is claimed. Each `res.write` is awaited
* (flush callback) for backpressure, and the sink aborts the action once the
* client disconnects so a big download stops pumping into a dead socket. */
async function streamHttpResponse(
res: ServerResponse,
api: ApiHandler,
action: string,
params: JsonObject,
echo: JsonValue | undefined,
): Promise<void> {
res.statusCode = 200;
const writeFrame = (frame: ApiResponse): Promise<void> =>
new Promise((resolve) => {
if (res.writableEnded || res.destroyed) { resolve(); return; }
res.write(JSON.stringify(frame) + '\r\n\r\n', () => resolve());
});
const sink: StreamSink = {
send: async (frame) => {
if (res.writableEnded || res.destroyed) throw new Error('stream client disconnected');
await writeFrame(wrapStreamFrame(frame, echo));
},
};
const response = await api.handle(action, params, sink);
await writeFrame(wrapStreamTerminal(response, echo));
if (!res.writableEnded && !res.destroyed) res.end();
}
+13
View File
@@ -31,6 +31,19 @@ export function safeSend(socket: WebSocket, payload: string, onError?: (err: Err
});
}
/** Backpressure-aware send: resolves only once `ws` has flushed `payload` to
* the socket (the `send` callback fires post-write), so a streaming producer
* that awaits this won't outrun a slow client and balloon the send buffer.
* Never rejects — a closed socket or send error resolves quietly (the stream
* sink handles liveness/abort separately so a dead client can't crash the
* per-message handler with an unhandled rejection). */
export function safeSendAsync(socket: WebSocket, payload: string): Promise<void> {
return new Promise((resolve) => {
if (socket.readyState !== 1 /* WebSocket.OPEN */) { resolve(); return; }
socket.send(payload, () => resolve());
});
}
export function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void {
if (socket.readyState === 3 /* CLOSED */ || socket.readyState === 2 /* CLOSING */) return;
socket.close(code, reason);
@@ -8,7 +8,7 @@ import {
} from '../event-filter';
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { rawDataToString, safeClose, safeSend } from './utils';
import { rawDataToString, safeClose, safeSend, safeSendAsync } from './utils';
const moduleLog = createLogger('OneBot.WS-Client');
const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
@@ -146,8 +146,13 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
if (this.role !== 'Api' && this.role !== 'Universal') return;
const text = rawDataToString(raw);
if (!text) return;
const response = await this.ctx.api.processRequest(text);
safeSend(socket, response);
// Stream API (#163): one frame for a normal action, N for a streaming one.
// Async send = backpressure; liveness check aborts on disconnect.
await this.ctx.api.processStreamRequest(
text,
(frame) => safeSendAsync(socket, frame),
() => socket.readyState === 1,
);
}
private sendBootstrapMetaEvents(socket: WebSocket): void {
@@ -9,7 +9,7 @@ import {
} from '../event-filter';
import type { JsonObject, WsRole, WsServerNetwork } from '../types';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend } from './utils';
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend, safeSendAsync } from './utils';
const moduleLog = createLogger('OneBot.WS-Server');
@@ -119,7 +119,9 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
this.connections.set(socket, conn);
socket.on('message', (raw: Buffer) => {
void this.handleApiMessage(socket, role, raw);
void this.handleApiMessage(socket, role, raw).catch((err) => {
this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
});
});
socket.on('close', () => this.connections.delete(socket));
socket.on('error', (err: Error) => {
@@ -135,8 +137,15 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
if (role !== 'Api' && role !== 'Universal') return;
const text = rawDataToString(raw);
if (!text) return;
const response = await this.ctx.api.processRequest(text);
safeSend(socket, response);
// Stream API (#163) emits multiple frames per request; processStreamRequest
// sends one frame for a normal action and N for a streaming one. The async
// send applies backpressure (awaits flush); the liveness check aborts a
// streaming action once the client goes away.
await this.ctx.api.processStreamRequest(
text,
(frame) => safeSendAsync(socket, frame),
() => socket.readyState === 1,
);
}
private sendBootstrapMetaEvents(socket: WebSocket): void {