Add BridgeEventBus and network manager

Introduce a typed per-kind BridgeEventBus and migrate away from the legacy single-callback firehose. Bridge now exposes `events` and emits via the bus; BridgeManager/OneBotManager no longer wire a global event callback. Add a focused onebot event pipeline (event-pipeline.ts) that subscribes per-kind handlers on instance construction. Replace the in-memory MediaCache with a persistent MediaStore and update all lookups accordingly. Replace the old Http/Ws/HttpPost transport implementations with a unified OneBotNetworkManager and pluggable adapters (server/client/post), and update OneBotInstance to install and manage adapters from config. Remove several legacy files (http-transport, http-post-transport, ws-transport, media-cache) and update imports across the codebase. Also add tests for the bridge event bus, event pipeline, network manager, and rename media tests to reflect MediaStore usage. The bus dispatches handlers in parallel and reports handler errors via an onError hook to avoid one faulty listener blocking others.
This commit is contained in:
手瓜一十雪 committed 2026-05-09 16:30:06 +08:00
1 parent 1565749105
commit 144e0fdd59
27 files changed
+2357 -1234

No files matched your search

@@ -0,0 +1,65 @@
// Base abstractions for OneBot network adapters.
//
// Modeled on NapCat's `IOB11NetworkAdapter` so each entry under
// `config.networks.{httpServers,httpClients,wsServers,wsClients}` becomes
// exactly one adapter instance, identified by `name`. The previous design
// rolled multiple servers/clients into a single transport class; the
// per-entry split makes hot-reload, lifecycle, and event isolation much
// simpler to reason about.
import type { ApiHandler } from '../api-handler';
import type { JsonObject, NetworkBase } from '../types';
import type { DispatchPayload } from '../event-filter';
export interface NetworkAdapterContext {
/** Self UIN as string — written into outbound headers. */
uin: string;
/** Shared API dispatcher used by request/response style adapters. */
api: ApiHandler;
/** Build a lifecycle event payload (connect/enable/disable). */
buildLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject;
/** Build a heartbeat event payload. */
buildHeartbeatEvent(): JsonObject;
}
export enum NetworkReloadType {
/** Configuration unchanged or only soft fields updated. */
Normal = 0,
/** Underlying socket/listener restarted in place. */
Reopened = 1,
/** Was running, now closed. */
Closed = 2,
/** Was idle, now opened. */
Opened = 3,
}
export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
readonly name: string;
protected config: C;
protected readonly ctx: NetworkAdapterContext;
protected isEnabled = false;
constructor(name: string, config: C, ctx: NetworkAdapterContext) {
this.name = name;
// Defensive copy so reload diffs never mutate the caller's object.
this.config = structuredClone(config);
this.ctx = ctx;
}
/** Whether the adapter is currently accepting/relaying events. */
get isActive(): boolean { return this.isEnabled; }
/** Snapshot of the active config (read-only). */
get currentConfig(): Readonly<C> { return this.config; }
abstract open(): void | Promise<void>;
abstract close(): void | Promise<void>;
abstract reload(config: C): NetworkReloadType | Promise<NetworkReloadType>;
/**
* Receive one fully-shaped OneBot event for forwarding. Adapters that
* don't push events (e.g. HTTP request-response servers) override with a
* no-op.
*/
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
}
@@ -0,0 +1,136 @@
// Outbound HTTP webhook adapter — one instance per `httpClients[]` entry.
//
// Forwards every event to the configured URL via HTTP POST and interprets
// any JSON response body as a OneBot v11 quick-operation.
import type { HttpClientNetwork, JsonObject } from '../types';
import {
pickDispatchJson,
resolveReportOptions,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import { createLogger } from '../../utils/logger';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { executeQuickOperation } from './quick-operation';
const log = createLogger('OneBot.POST');
const DEFAULT_TIMEOUT_MS = 5000;
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
private options: EventReportOptions;
private signature_: string;
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
this.options = resolveReportOptions(config);
this.signature_ = bindingSignature(config);
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
if (this.config.enabled === false) return;
if (!this.config.url) return;
this.isEnabled = true;
}
close(): void {
this.isEnabled = false;
}
async reload(next: HttpClientNetwork): Promise<NetworkReloadType> {
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
this.config = structuredClone(next);
this.options = resolveReportOptions(next);
const newSig = bindingSignature(next);
const sigChanged = newSig !== this.signature_;
this.signature_ = newSig;
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled) return;
const json = pickDispatchJson(payload, this.options);
if (json === null) return;
void this.postEvent(json, event);
}
private async postEvent(payload: string, event: JsonObject): Promise<void> {
if (!this.isEnabled) return;
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'User-Agent': 'OneBot',
'X-Self-ID': this.ctx.uin,
};
if (this.config.accessToken) {
headers['X-Signature'] = await computeHmacSha1(this.config.accessToken, payload);
}
const timeoutMs = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
try {
const response = await fetch(this.config.url, {
method: 'POST',
headers,
body: payload,
signal: AbortSignal.timeout(timeoutMs),
});
if (response.ok) {
const contentType = response.headers.get('content-type') ?? '';
if (contentType.includes('application/json')) {
const body = await response.text();
if (body.trim()) {
await this.handleQuickOperation(event, body);
}
}
} else {
log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
}
} catch (error) {
if (this.isEnabled) {
log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
}
}
}
private async handleQuickOperation(event: JsonObject, responseBody: string): Promise<void> {
try {
const operation = JSON.parse(responseBody) as Record<string, unknown>;
if (!operation || typeof operation !== 'object') return;
await executeQuickOperation(event, operation, this.ctx.api);
} catch (error) {
log.warn('[%s] quick operation failed: %s', this.name, error instanceof Error ? error.message : String(error));
}
}
}
function bindingSignature(net: HttpClientNetwork): string {
return `${net.url}#${net.accessToken ?? ''}#${net.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
}
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
const { createHmac } = await import('crypto');
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
}
@@ -0,0 +1,203 @@
// Inbound HTTP API server — one instance per `httpServers[]` entry.
//
// Pure request/response: incoming POST/GET maps to `ApiHandler.handle`,
// the response body is JSON-serialized back. `onEvent` is a deliberate
// no-op since this transport never pushes events.
import {
createServer,
type IncomingMessage,
type Server,
type ServerResponse,
} from 'http';
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
import type { DispatchPayload } from '../event-filter';
import { createLogger } from '../../utils/logger';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath } from './utils';
const log = createLogger('OneBot.HTTP');
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
private server: Server | null = null;
override get isActive(): boolean {
// HTTP server never receives events — `isActive` purely tracks the
// bound listener so the network manager can skip dispatch cleanly.
return this.isEnabled;
}
open(): void {
if (this.isEnabled) return;
if (this.config.enabled === false) return;
this.startServer();
this.isEnabled = true;
}
close(): void {
if (!this.isEnabled && !this.server) return;
this.isEnabled = false;
this.server?.close();
this.server = null;
}
async reload(next: HttpServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false;
this.config = structuredClone(next);
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
// HTTP server only acts on inbound requests; it doesn't push events.
onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ }
private startServer(): void {
const expectedPath = normalizePath(this.config.path ?? '/');
const accessToken = this.config.accessToken ?? '';
const server = createServer((req, res) => {
void this.handleRequest(expectedPath, accessToken, req, res);
});
this.server = server;
server.on('listening', () => {
log.success(
'[%s] listening %s:%d%s',
this.name,
this.config.host ?? '0.0.0.0',
this.config.port,
expectedPath,
);
});
server.on('error', (err) => {
log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
});
server.listen(this.config.port, this.config.host ?? '0.0.0.0');
}
private async handleRequest(expectedPath: string, accessToken: string, req: IncomingMessage, res: ServerResponse): Promise<void> {
const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1');
const incomingPath = parsedUrl.pathname;
const ep = expectedPath.endsWith('/') ? expectedPath : expectedPath + '/';
let action = '';
if (incomingPath === expectedPath || incomingPath === expectedPath + '/') {
action = '';
} else if (incomingPath.startsWith(ep)) {
action = incomingPath.substring(ep.length);
} else {
writeJson(res, 404, { status: 'failed', retcode: 1404, data: null, wording: 'not found' });
return;
}
if (!isAuthorized(req, accessToken)) {
writeJson(res, 401, { status: 'failed', retcode: 1401, data: null, wording: 'unauthorized' });
return;
}
if (req.method === 'GET' && !action) {
writeJson(res, 200, { status: 'ok', retcode: 0, data: { online: true } });
return;
}
try {
let params: Record<string, unknown> = {};
let echo: unknown;
if (req.method === 'GET') {
parsedUrl.searchParams.forEach((value, key) => {
try {
params[key] = JSON.parse(value);
} catch {
params[key] = value;
}
});
} else if (req.method === 'POST') {
const bodyContent = await readRequestBody(req);
if (bodyContent.trim()) {
try {
const parsedBody = JSON.parse(bodyContent);
if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) {
if (parsedBody.action && !action) action = String(parsedBody.action);
if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) {
params = parsedBody.params as Record<string, unknown>;
} else {
params = parsedBody as Record<string, unknown>;
}
echo = parsedBody.echo;
}
} catch {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
return;
}
}
} else {
writeJson(res, 405, { status: 'failed', retcode: 1400, data: null, wording: 'method not allowed' });
return;
}
if (!action) {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: missing action' });
return;
}
const response = await this.ctx.api.handle(action, params as JsonObject);
if (echo !== undefined) {
response.echo = echo as JsonValue;
}
writeJson(res, 200, response);
} catch (error) {
const wording = error instanceof Error ? error.message : 'internal error';
writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording });
}
}
}
function bindingSignature(net: HttpServerNetwork): string {
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}#${net.accessToken ?? ''}`;
}
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let total = 0;
req.on('data', (chunk: Buffer) => {
total += chunk.length;
if (total > maxBytes) {
reject(new Error('request body too large'));
req.destroy();
return;
}
chunks.push(chunk);
});
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
req.on('error', reject);
});
}
function writeJson(res: ServerResponse, statusCode: number, data: unknown): void {
res.statusCode = statusCode;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(data));
}
@@ -0,0 +1,9 @@
// Public surface for the OneBot network package.
export { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
export { OneBotNetworkManager } from './network-manager';
export { WsServerAdapter } from './ws-server-adapter';
export { WsClientAdapter } from './ws-client-adapter';
export { HttpServerAdapter } from './http-server-adapter';
export { HttpPostAdapter } from './http-post-adapter';
export { executeQuickOperation } from './quick-operation';
@@ -0,0 +1,105 @@
// OneBot network manager.
//
// Mirrors NapCat's `OB11NetworkManager`: holds a `Map<name, adapter>`, fans
// events out to every active adapter in parallel, and provides primitives
// the OneBot instance uses to register, hot-reload, and tear adapters down.
import type { JsonObject, NetworkBase } from '../types';
import { buildDispatchPayload } from '../event-filter';
import { IOneBotNetworkAdapter } from './adapter';
import { createLogger } from '../../utils/logger';
const log = createLogger('OneBot.Network');
type AnyAdapter = IOneBotNetworkAdapter<NetworkBase>;
export class OneBotNetworkManager {
private readonly adapters = new Map<string, AnyAdapter>();
register<C extends NetworkBase>(adapter: IOneBotNetworkAdapter<C>): void {
const existing = this.adapters.get(adapter.name);
if (existing) {
// Replacing an adapter under the same name — close the previous one
// before storing the new instance to keep ports/sockets clean.
log.info('replacing adapter [%s]', adapter.name);
void Promise.resolve(existing.close()).catch(() => { /* best-effort */ });
}
this.adapters.set(adapter.name, adapter as AnyAdapter);
}
has(name: string): boolean { return this.adapters.has(name); }
get(name: string): AnyAdapter | null {
return this.adapters.get(name) ?? null;
}
list(): AnyAdapter[] { return [...this.adapters.values()]; }
hasActiveAdapters(): boolean {
for (const a of this.adapters.values()) if (a.isActive) return true;
return false;
}
async openAll(): Promise<void> {
const tasks = this.list().map(async (a) => {
try {
await a.open();
} catch (err) {
log.error('adapter [%s] open failed: %s', a.name, errMessage(err));
}
});
await Promise.all(tasks);
}
async closeAll(): Promise<void> {
const tasks = this.list().map(async (a) => {
try {
await a.close();
} catch (err) {
log.warn('adapter [%s] close failed: %s', a.name, errMessage(err));
}
});
await Promise.all(tasks);
this.adapters.clear();
}
async closeOne(name: string): Promise<void> {
const adapter = this.adapters.get(name);
if (!adapter) return;
this.adapters.delete(name);
try {
await adapter.close();
} catch (err) {
log.warn('adapter [%s] close failed: %s', adapter.name, errMessage(err));
}
}
/**
* Dispatch one canonical OneBot event to every active adapter in parallel.
* The dispatch payload is built once so each adapter pays only the cost
* of picking the right pre-serialized variant.
*
* Errors thrown inside an adapter are isolated — one bad adapter never
* blocks the others.
*/
async emitEvent(event: JsonObject): Promise<void> {
if (!this.hasActiveAdapters()) return;
const payload = buildDispatchPayload(event);
const tasks: Promise<unknown>[] = [];
for (const adapter of this.adapters.values()) {
if (!adapter.isActive) continue;
tasks.push(
Promise.resolve()
.then(() => adapter.onEvent(event, payload))
.catch((err) => {
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(err));
}),
);
}
await Promise.allSettled(tasks);
}
}
function errMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
@@ -0,0 +1,89 @@
// OneBot v11 hidden API: `.handle_quick_operation`.
//
// When an HTTP POST event report receives a JSON body in response, that body
// is interpreted as a "quick operation" — short-cuts to common follow-up
// API calls (reply, recall, ban, kick, approve/reject). Spec:
// https://github.com/botuniverse/onebot-11/blob/master/api/hidden.md
import type { ApiHandler } from '../api-handler';
import type { JsonObject, JsonValue } from '../types';
export async function executeQuickOperation(
event: JsonObject,
operation: Record<string, unknown>,
api: ApiHandler,
): Promise<void> {
const postType = event.post_type as string;
if (postType === 'message') {
if (operation.reply !== undefined && operation.reply !== null && operation.reply !== '') {
const messageType = event.message_type as string;
const autoEscape = !!operation.auto_escape;
if (messageType === 'group') {
const params: JsonObject = {
group_id: event.group_id as number,
message: operation.reply as JsonValue,
auto_escape: autoEscape,
};
if (operation.at_sender !== false && event.user_id) {
const atSegment = { type: 'at', data: { qq: String(event.user_id) } };
if (typeof operation.reply === 'string') {
params.message = [atSegment, { type: 'text', data: { text: operation.reply as string } }] as JsonValue;
params.auto_escape = false;
} else if (Array.isArray(operation.reply)) {
params.message = [atSegment, ...(operation.reply as unknown[])] as JsonValue;
}
}
await api.handle('send_group_msg', params);
} else if (messageType === 'private') {
await api.handle('send_private_msg', {
user_id: event.user_id as number,
message: operation.reply as JsonValue,
auto_escape: autoEscape,
});
}
}
if (operation.delete) {
await api.handle('delete_msg', { message_id: event.message_id as number });
}
if (operation.ban && event.message_type === 'group') {
const duration = typeof operation.ban_duration === 'number' ? operation.ban_duration : 1800;
await api.handle('set_group_ban', {
group_id: event.group_id as number,
user_id: event.user_id as number,
duration: duration as JsonValue,
});
}
if (operation.kick && event.message_type === 'group') {
await api.handle('set_group_kick', {
group_id: event.group_id as number,
user_id: event.user_id as number,
reject_add_request: !!operation.reject_add_request,
});
}
}
if (postType === 'request') {
if (operation.approve !== undefined) {
const requestType = event.request_type as string;
if (requestType === 'friend') {
await api.handle('set_friend_add_request', {
flag: event.flag as string,
approve: operation.approve as JsonValue,
remark: (operation.remark ?? '') as JsonValue,
});
} else if (requestType === 'group') {
await api.handle('set_group_add_request', {
flag: event.flag as string,
sub_type: event.sub_type as string,
approve: operation.approve as JsonValue,
reason: (operation.reason ?? '') as JsonValue,
});
}
}
}
}
+59
View File
@@ -0,0 +1,59 @@
// Helpers shared between OneBot network adapters.
import type { IncomingMessage } from 'http';
import type { WebSocket } from '@snowluma/websocket';
/** Validate a request's bearer token / `?access_token=` query against the configured token. */
export function isAuthorized(request: IncomingMessage, token: string): boolean {
if (!token) return true;
const rawAuth = request.headers.authorization;
const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? '';
if (auth === `Bearer ${token}`) return true;
try {
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
if (url.searchParams.get('access_token') === token) return true;
} catch { /* ignore malformed URLs */ }
return false;
}
/** Convert anything ws can hand us into a UTF-8 string. */
export function rawDataToString(raw: Buffer | string | ArrayBuffer | ArrayBufferView | Buffer[]): string {
if (typeof raw === 'string') return raw;
if (Buffer.isBuffer(raw)) return raw.toString('utf8');
if (Array.isArray(raw)) return Buffer.concat(raw).toString('utf8');
if (raw instanceof ArrayBuffer) return Buffer.from(new Uint8Array(raw)).toString('utf8');
if (ArrayBuffer.isView(raw)) {
return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8');
}
return '';
}
/** Best-effort send: drops payload if the socket isn't OPEN, reports send errors. */
export function safeSend(socket: WebSocket, payload: string, onError?: (err: Error) => void): void {
if (socket.readyState !== 1 /* WebSocket.OPEN */) return;
socket.send(payload, (error?: Error | null) => {
if (error && onError) onError(error);
});
}
/** Best-effort close, treats already-closed sockets as a no-op. */
export function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void {
if (socket.readyState === 3 /* CLOSED */ || socket.readyState === 2 /* CLOSING */) return;
socket.close(code, reason);
}
/** Normalize an HTTP/WS path to a comparable form (strip trailing slash, default to "/"). */
export function normalizePath(pathValue: string | undefined): string {
const path = (pathValue ?? '/').trim() || '/';
if (path === '/') return '/';
return path.endsWith('/') ? path.slice(0, -1) : path;
}
/** Parse the `pathname` from a (potentially relative) WebSocket request URL. */
export function parseRequestPath(urlValue: string): string {
try {
return new URL(urlValue, 'ws://127.0.0.1').pathname;
} catch {
return '/';
}
}
@@ -0,0 +1,177 @@
// Reverse (client) WebSocket adapter — one instance per `wsClients[]` entry.
//
// Connects out to a remote OneBot endpoint, manages reconnects, forwards
// pushed events on `onEvent`, and dispatches incoming API messages to the
// shared ApiHandler.
import { WebSocket } from '@snowluma/websocket';
import type { WsClientNetwork, WsRole, JsonObject } from '../types';
import {
pickDispatchJson,
resolveReportOptions,
shapeEventForAdapter,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import { createLogger } from '../../utils/logger';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { rawDataToString, safeClose, safeSend } from './utils';
const log = createLogger('OneBot.WS-Client');
const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
private socket: WebSocket | null = null;
private reconnectTimer: NodeJS.Timeout | null = null;
private options: EventReportOptions;
private role: WsRole;
private explicitlyClosed = false;
constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
this.options = resolveReportOptions(config);
this.role = config.role ?? 'Universal';
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
if (this.isEnabled) return;
if (this.config.enabled === false) return;
if (!this.config.url) return;
this.explicitlyClosed = false;
this.isEnabled = true;
this.connect();
}
close(): void {
this.explicitlyClosed = true;
this.isEnabled = false;
this.cancelReconnect();
if (this.socket) {
safeClose(this.socket);
this.socket = null;
}
}
async reload(next: WsClientNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
this.config = structuredClone(next);
this.options = resolveReportOptions(next);
this.role = next.role ?? 'Universal';
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled || !this.socket) return;
if (this.role !== 'Event' && this.role !== 'Universal') return;
const json = pickDispatchJson(payload, this.options);
if (json === null) return;
safeSend(this.socket, json);
}
private connect(): void {
if (this.explicitlyClosed) return;
if (!this.config.url) return;
if (this.socket) return;
const headers: Record<string, string> = {
'User-Agent': 'OneBot/11',
'X-Self-ID': this.ctx.uin,
'X-Client-Role': this.role,
};
if (this.config.accessToken) {
headers.Authorization = `Bearer ${this.config.accessToken}`;
}
const socket = new WebSocket(this.config.url, { headers });
this.socket = socket;
socket.on('open', () => {
log.info('[%s] connected %s', this.name, this.config.url);
this.sendBootstrapMetaEvents(socket);
});
socket.on('message', (raw: Buffer) => {
void this.handleApiMessage(socket, raw);
});
socket.on('close', () => {
this.socket = null;
if (this.explicitlyClosed || !this.isEnabled) return;
this.scheduleReconnect();
});
socket.on('error', (err: Error) => {
log.warn('[%s] error %s: %s', this.name, this.config.url, err instanceof Error ? err.message : String(err));
});
}
private scheduleReconnect(): void {
if (this.reconnectTimer) return;
if (this.explicitlyClosed) return;
const interval = Math.max(1000, this.config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS);
const timer = setTimeout(() => {
this.reconnectTimer = null;
if (this.explicitlyClosed || !this.isEnabled) return;
this.connect();
}, interval);
timer.unref?.();
this.reconnectTimer = timer;
}
private cancelReconnect(): void {
if (!this.reconnectTimer) return;
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
private async handleApiMessage(socket: WebSocket, raw: Buffer | string): Promise<void> {
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);
}
private sendBootstrapMetaEvents(socket: WebSocket): void {
if (this.role !== 'Event' && this.role !== 'Universal') return;
const events = [
this.ctx.buildLifecycleEvent('connect'),
this.ctx.buildLifecycleEvent('enable'),
this.ctx.buildHeartbeatEvent(),
];
for (const event of events) {
const shaped = shapeEventForAdapter(event, this.options);
if (!shaped) continue;
safeSend(socket, JSON.stringify(shaped));
}
}
}
function bindingSignature(net: WsClientNetwork): string {
return `${net.url}#${net.role ?? 'Universal'}#${Math.max(1000, net.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${net.accessToken ?? ''}`;
}
@@ -0,0 +1,187 @@
// Forward (server) WebSocket adapter — one instance per `wsServers[]` entry.
//
// Each adapter owns its own `WebSocketServer`, accepts inbound forward
// connections (api / event / universal roles), and pushes events to all live
// event-receiving sockets when `onEvent` fires.
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
import type { IncomingMessage } from 'http';
import type { WsRole, WsServerNetwork, JsonObject } from '../types';
import {
pickDispatchJson,
resolveReportOptions,
shapeEventForAdapter,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import { createLogger } from '../../utils/logger';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { isAuthorized, parseRequestPath, rawDataToString, safeClose, safeSend, normalizePath } from './utils';
const log = createLogger('OneBot.WS-Server');
interface ForwardConn {
socket: WebSocket;
role: WsRole;
options: EventReportOptions;
}
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
private wss: WebSocketServer | null = null;
private connections = new Map<WebSocket, ForwardConn>();
private options: EventReportOptions;
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
this.options = resolveReportOptions(config);
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
if (this.isEnabled) return;
if (this.config.enabled === false) return;
this.startServer();
this.isEnabled = true;
}
close(): void {
if (!this.isEnabled && this.connections.size === 0 && !this.wss) return;
// Final lifecycle broadcast before tearing down so attached event clients
// see the disable transition.
const lifecycle = this.ctx.buildLifecycleEvent('disable');
for (const conn of this.connections.values()) {
if (conn.role === 'Api') continue;
const shaped = shapeEventForAdapter(lifecycle, conn.options);
if (!shaped) continue;
safeSend(conn.socket, JSON.stringify(shaped));
}
this.isEnabled = false;
for (const ws of [...this.connections.keys()]) safeClose(ws);
this.connections.clear();
this.wss?.close();
this.wss = null;
}
async reload(next: WsServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false;
this.config = structuredClone(next);
this.options = resolveReportOptions(next);
for (const conn of this.connections.values()) conn.options = this.options;
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled || this.connections.size === 0) return;
for (const conn of this.connections.values()) {
if (conn.role !== 'Event' && conn.role !== 'Universal') continue;
const json = pickDispatchJson(payload, conn.options);
if (json === null) continue;
safeSend(conn.socket, json);
}
}
private startServer(): void {
const wss = new WebSocketServer({
host: this.config.host ?? '0.0.0.0',
port: this.config.port,
path: this.config.path ?? '/',
});
this.wss = wss;
wss.on('listening', () => {
log.success(
'[%s] listening %s:%d%s',
this.name,
this.config.host ?? '0.0.0.0',
this.config.port,
this.config.path ?? '/',
);
});
wss.on('error', (err: Error) => {
log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
});
wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request));
}
private onConnection(socket: WebSocket, request: IncomingMessage): void {
if (!isAuthorized(request, this.config.accessToken ?? '')) {
safeClose(socket, 1008, 'invalid access token');
return;
}
const role = this.config.role ?? classifyForwardRole(request);
const conn: ForwardConn = { socket, role, options: this.options };
this.connections.set(socket, conn);
socket.on('message', (raw: Buffer) => {
void this.handleApiMessage(socket, role, raw);
});
socket.on('close', () => this.connections.delete(socket));
socket.on('error', (err: Error) => {
log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err));
});
if (role === 'Event' || role === 'Universal') {
this.sendBootstrapMetaEvents(socket);
}
}
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
if (role !== 'Api' && role !== 'Universal') return;
const text = rawDataToString(raw);
if (!text) return;
const response = await this.ctx.api.processRequest(text);
safeSend(socket, response);
}
private sendBootstrapMetaEvents(socket: WebSocket): void {
const events = [
this.ctx.buildLifecycleEvent('connect'),
this.ctx.buildLifecycleEvent('enable'),
this.ctx.buildHeartbeatEvent(),
];
for (const event of events) {
const shaped = shapeEventForAdapter(event, this.options);
if (!shaped) continue;
safeSend(socket, JSON.stringify(shaped));
}
}
}
function classifyForwardRole(request: IncomingMessage): WsRole {
const path = parseRequestPath(request.url ?? '/');
if (path.endsWith('/api')) return 'Api';
if (path.endsWith('/event')) return 'Event';
return 'Universal';
}
function bindingSignature(net: WsServerNetwork): string {
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path)}#${net.role ?? 'auto'}#${net.accessToken ?? ''}`;
}