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:
1 parent
1565749105
commit
144e0fdd59
27 files changed
+2357
-1234
No files matched your search
@@ -81,8 +81,7 @@ import {
|
||||
} from './web-actions';
|
||||
import type { GroupFilesResult } from './bridge-actions';
|
||||
import type { MediaIndexNode } from './bridge-actions';
|
||||
|
||||
export type BridgeEventCallback = (event: QQEventVariant) => void;
|
||||
import { BridgeEventBus } from './event-bus';
|
||||
|
||||
type CmdParser = (pkt: PacketInfo, qqInfo: QQInfo) => QQEventVariant[];
|
||||
|
||||
@@ -116,7 +115,12 @@ export class Bridge {
|
||||
|
||||
private qqInfo_: QQInfo;
|
||||
private pids_ = new Set<number>();
|
||||
private eventCallback_: BridgeEventCallback | null = null;
|
||||
/**
|
||||
* Per-kind event subscription. Replaces the legacy single-callback
|
||||
* firehose: downstream consumers now register exactly the kinds they
|
||||
* care about and `emitEvent` fans out in parallel.
|
||||
*/
|
||||
readonly events = new BridgeEventBus();
|
||||
private cmdHandlers_ = new Map<string, CmdParser[]>();
|
||||
private packetClient_: PacketSender | null = null;
|
||||
private memberRefreshTasks_ = new Map<number, Promise<void>>();
|
||||
@@ -155,10 +159,6 @@ export class Bridge {
|
||||
this.cmdHandlers_.set(cmd, arr);
|
||||
}
|
||||
|
||||
setEventCallback(cb: BridgeEventCallback): void {
|
||||
this.eventCallback_ = cb;
|
||||
}
|
||||
|
||||
handlesCmd(cmd: string): boolean {
|
||||
return this.cmdHandlers_.has(cmd);
|
||||
}
|
||||
@@ -199,11 +199,9 @@ export class Bridge {
|
||||
}
|
||||
|
||||
private emitEvent(event: QQEventVariant): void {
|
||||
if (this.eventCallback_) {
|
||||
try { this.eventCallback_(event); } catch (e) {
|
||||
log.error('event callback error: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
||||
}
|
||||
}
|
||||
// Fire-and-forget: errors inside subscribers are surfaced via the bus's
|
||||
// own onError hook so one bad listener never blocks the others.
|
||||
void this.events.emit(event);
|
||||
}
|
||||
|
||||
private triggerMemberCacheRefresh(event: QQEventVariant): void {
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
// Typed, per-kind pub/sub for bridge-level events.
|
||||
//
|
||||
// Replaces the single-callback firehose where every consumer received every
|
||||
// event variant and had to switch on `event.kind`. Now each downstream
|
||||
// concern (OneBot dispatch, member cache refresh, etc.) registers exactly
|
||||
// the kinds it cares about, much closer to NapCat's per-listener pattern.
|
||||
//
|
||||
// `emit` is fire-and-forget: subscribers can be sync or async; async
|
||||
// rejections are surfaced via `Promise.allSettled` and reported through the
|
||||
// optional `onError` hook so one buggy handler never starves the others.
|
||||
|
||||
import type { QQEventVariant } from './events';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
type EventKind = QQEventVariant['kind'];
|
||||
type EventOf<K extends EventKind> = Extract<QQEventVariant, { kind: K }>;
|
||||
|
||||
export type EventHandler<K extends EventKind> = (event: EventOf<K>) => void | Promise<void>;
|
||||
export type AnyEventHandler = (event: QQEventVariant) => void | Promise<void>;
|
||||
|
||||
export interface EventBusOptions {
|
||||
/** Logger label for handler failures. Defaults to `Bridge.Events`. */
|
||||
loggerName?: string;
|
||||
/** Override the default error reporter (e.g. for tests). */
|
||||
onError?: (kind: EventKind | '*', err: unknown) => void;
|
||||
}
|
||||
|
||||
const DEFAULT_LOGGER = createLogger('Bridge.Events');
|
||||
|
||||
export class BridgeEventBus {
|
||||
// Per-kind subscribers are stored as `Set<unknown>` so the container
|
||||
// doesn't carry a contravariant function type that fights TS variance
|
||||
// rules. The runtime invariant is straightforward: handlers stored under
|
||||
// key `K` only ever see `EventOf<K>` events, which is what the single
|
||||
// narrowing cast at the dispatch site below relies on.
|
||||
private readonly handlers = new Map<EventKind, Set<unknown>>();
|
||||
private readonly anyHandlers = new Set<AnyEventHandler>();
|
||||
private readonly onError: (kind: EventKind | '*', err: unknown) => void;
|
||||
|
||||
constructor(opts: EventBusOptions = {}) {
|
||||
if (opts.onError) {
|
||||
this.onError = opts.onError;
|
||||
} else {
|
||||
const log = opts.loggerName ? createLogger(opts.loggerName) : DEFAULT_LOGGER;
|
||||
this.onError = (kind, err) => {
|
||||
log.error(
|
||||
'event handler error [%s]: %s',
|
||||
kind,
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err),
|
||||
);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Subscribe to one kind. Returns an unsubscribe function. */
|
||||
on<K extends EventKind>(kind: K, handler: EventHandler<K>): () => void {
|
||||
let set = this.handlers.get(kind);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
this.handlers.set(kind, set);
|
||||
}
|
||||
set.add(handler);
|
||||
return () => {
|
||||
this.handlers.get(kind)?.delete(handler);
|
||||
};
|
||||
}
|
||||
|
||||
/** Subscribe to every kind (low-volume callers like loggers). */
|
||||
onAny(handler: AnyEventHandler): () => void {
|
||||
this.anyHandlers.add(handler);
|
||||
return () => {
|
||||
this.anyHandlers.delete(handler);
|
||||
};
|
||||
}
|
||||
|
||||
off<K extends EventKind>(kind: K, handler: EventHandler<K>): void {
|
||||
this.handlers.get(kind)?.delete(handler);
|
||||
}
|
||||
|
||||
has(kind: EventKind): boolean {
|
||||
return (this.handlers.get(kind)?.size ?? 0) + this.anyHandlers.size > 0;
|
||||
}
|
||||
|
||||
/** Drop every subscriber. Mostly useful for tests. */
|
||||
clear(): void {
|
||||
this.handlers.clear();
|
||||
this.anyHandlers.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch an event in parallel to every subscriber for its kind plus every
|
||||
* onAny handler. Rejections are isolated per-handler — one bad subscriber
|
||||
* never blocks the others, and the returned promise resolves once every
|
||||
* subscriber settles.
|
||||
*/
|
||||
async emit<K extends EventKind>(event: EventOf<K>): Promise<void> {
|
||||
const kindHandlers = this.handlers.get(event.kind);
|
||||
if ((!kindHandlers || kindHandlers.size === 0) && this.anyHandlers.size === 0) {
|
||||
return;
|
||||
}
|
||||
const tasks: Promise<unknown>[] = [];
|
||||
if (kindHandlers) {
|
||||
for (const handler of kindHandlers) {
|
||||
// Single narrowing cast — the only place we re-assert that handlers
|
||||
// stored under `event.kind` accept `EventOf<event.kind>` events.
|
||||
const typed = handler as EventHandler<K>;
|
||||
tasks.push(invoke(this.onError, event.kind, () => typed(event)));
|
||||
}
|
||||
}
|
||||
for (const handler of this.anyHandlers) {
|
||||
tasks.push(invoke(this.onError, '*', () => handler(event)));
|
||||
}
|
||||
await Promise.allSettled(tasks);
|
||||
}
|
||||
}
|
||||
|
||||
async function invoke(
|
||||
onError: (kind: EventKind | '*', err: unknown) => void,
|
||||
kind: EventKind | '*',
|
||||
fn: () => unknown,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const ret = fn();
|
||||
if (ret && typeof (ret as Promise<unknown>).then === 'function') {
|
||||
await ret;
|
||||
}
|
||||
} catch (err) {
|
||||
onError(kind, err);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
import type { NtqqHandler } from '../protocol/ntqq-handler';
|
||||
import type { PacketInfo } from '../protocol/types';
|
||||
import type { QQEventVariant } from './events';
|
||||
import { Bridge } from './bridge';
|
||||
import { QQInfo } from './qq-info';
|
||||
import type { PacketSender } from '../protocol/packet-sender';
|
||||
@@ -12,7 +11,6 @@ import { createLogger } from '../utils/logger';
|
||||
|
||||
export type SessionStartedCallback = (uin: string, qqInfo: QQInfo, bridge: Bridge) => void;
|
||||
export type SessionClosedCallback = (uin: string) => void;
|
||||
export type BridgeEventCallback = (uin: string, event: QQEventVariant) => void;
|
||||
|
||||
interface QQSession {
|
||||
qqInfo: QQInfo;
|
||||
@@ -28,11 +26,9 @@ export class BridgeManager {
|
||||
|
||||
private onSessionStarted_: SessionStartedCallback | null = null;
|
||||
private onSessionClosed_: SessionClosedCallback | null = null;
|
||||
private onBridgeEvent_: BridgeEventCallback | null = null;
|
||||
|
||||
setSessionStartedCallback(cb: SessionStartedCallback): void { this.onSessionStarted_ = cb; }
|
||||
setSessionClosedCallback(cb: SessionClosedCallback): void { this.onSessionClosed_ = cb; }
|
||||
setEventCallback(cb: BridgeEventCallback): void { this.onBridgeEvent_ = cb; }
|
||||
|
||||
bind(ntqq: NtqqHandler): void {
|
||||
ntqq.registerCmdAll((pkt: PacketInfo) => this.onPacket(pkt));
|
||||
@@ -115,11 +111,9 @@ export class BridgeManager {
|
||||
session = { qqInfo, bridge };
|
||||
this.sessions_.set(uin, session);
|
||||
|
||||
// Wire event callback
|
||||
bridge.setEventCallback((event) => {
|
||||
if (this.onBridgeEvent_) this.onBridgeEvent_(uin, event);
|
||||
});
|
||||
|
||||
// Each downstream consumer (e.g. OneBotInstance) subscribes to
|
||||
// `bridge.events` directly via the per-kind bus — there is no longer a
|
||||
// generic firehose to wire here.
|
||||
return { session, created: true };
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user