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

+48 -21
View File
@@ -2,29 +2,56 @@ import type { Bridge } from '../bridge/bridge';
import type { ForwardNodePayload, MessageElement } from '../bridge/events';
import type { QQInfo } from '../bridge/qq-info';
import type { ApiActionContext, MessageSendResult } from './api-handler';
import type { EventConverter } from './event-converter';
import { elementsToOneBotSegments } from './event-converter';
import { MessageStore } from './message-store';
import { parseMessage } from './message-parser';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
import type { MediaCache } from './media-cache';
import type { JsonObject, JsonValue, MessageMeta } from './types';
import type { MediaStore } from './media-store';
import type { JsonObject, JsonValue, MessageMeta, OneBotConfig } from './types';
import { createLogger } from '../utils/logger';
import {WebHonorType} from "@/bridge/web/group-honor";
const log = createLogger('OneBot');
export interface InstanceRef {
/**
* Single shared context bag that flows through every OneBot instance-internal
* subsystem: API builder and the per-kind event pipeline.
*
* Only fields that are actually read through this bag live here — the api
* handler and network manager are owned by `OneBotInstance` directly because
* nothing reads them via ctx, and including them here would force a
* chicken-and-egg `late-bound` field dance during construction.
*
* `dispatchEvent` is the indirection used by the event pipeline to hand a
* converted OneBot event back to the instance for caching + adapter fan-out;
* it lets the pipeline stay decoupled from the network manager.
*/
export interface OneBotInstanceContext {
/** Self UIN as string (matches what's on disk and on the wire). */
uin: string;
/** Self UIN parsed once, used in event payloads. */
selfId: number;
qqInfo: QQInfo;
bridge: Bridge;
messageStore: MessageStore;
mediaCache: MediaCache;
mediaStore: MediaStore;
eventConverter: EventConverter;
config: OneBotConfig;
musicSignUrl?: string;
/** Persist meta about a message id; safe to call any number of times. */
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
/** Hand a fully-converted OneBot event to the network manager + caches. */
dispatchEvent(event: JsonObject): void;
}
export function buildApiContext(ref: InstanceRef): ApiActionContext {
const { bridge, qqInfo, messageStore, mediaCache } = ref;
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
const { bridge, qqInfo, messageStore, mediaStore } = ref;
return {
getLoginInfo: () => getLoginInfo(ref),
@@ -138,18 +165,18 @@ export function buildApiContext(ref: InstanceRef): ApiActionContext {
getCsrfToken: () => bridge.getCsrfToken(),
getCredentials: (domain: string) => bridge.getCredentials(domain),
// Media lookup
getImageInfo: (file) => handleGetImageInfo(mediaCache, file),
getRecordInfo: (file) => handleGetRecordInfo(bridge, mediaCache, file),
getImageInfo: (file) => handleGetImageInfo(mediaStore, file),
getRecordInfo: (file) => handleGetRecordInfo(bridge, mediaStore, file),
};
}
// --- Media lookup ---
async function handleGetImageInfo(
mediaCache: MediaCache,
mediaStore: MediaStore,
file: string,
): Promise<JsonObject | null> {
const cached = mediaCache.findImage(file);
const cached = mediaStore.findImage(file);
if (!cached) return null;
const url = cached.url || cached.imageUrl || '';
return {
@@ -162,10 +189,10 @@ async function handleGetImageInfo(
async function handleGetRecordInfo(
bridge: Bridge,
mediaCache: MediaCache,
mediaStore: MediaStore,
file: string,
): Promise<JsonObject | null> {
const cached = mediaCache.findRecord(file);
const cached = mediaStore.findRecord(file);
if (!cached) return null;
// Re-resolve via OIDB if the cached URL is missing or empty.
@@ -177,7 +204,7 @@ async function handleGetRecordInfo(
? await bridge.fetchGroupPttUrlByNode(cached.sessionId, cached.mediaNode)
: await bridge.fetchPrivatePttUrlByNode(cached.mediaNode);
if (url) {
mediaCache.updateRecordUrl(file, url);
mediaStore.updateRecordUrl(file, url);
}
} catch (err) {
log.warn('get_record url refetch failed: %s', err instanceof Error ? err.message : String(err));
@@ -194,7 +221,7 @@ async function handleGetRecordInfo(
// --- Login info ---
function getLoginInfo(ref: InstanceRef): { userId: number; nickname: string } {
function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nickname: string } {
const userId = parseInt(ref.uin, 10) || 0;
const nickname = ref.qqInfo.nickname || ref.uin;
return { userId, nickname };
@@ -550,7 +577,7 @@ function logSentMessage(isGroup: boolean, targetId: number, elements: MessageEle
// --- Send message ---
async function handleSendPrivate(
ref: InstanceRef,
ref: OneBotInstanceContext,
userId: number,
message: JsonValue,
autoEscape: boolean,
@@ -596,7 +623,7 @@ async function handleSendPrivate(
}
async function handleSendGroup(
ref: InstanceRef,
ref: OneBotInstanceContext,
groupId: number,
message: JsonValue,
autoEscape: boolean,
@@ -642,7 +669,7 @@ async function handleSendGroup(
}
async function handleSendGroupForward(
ref: InstanceRef,
ref: OneBotInstanceContext,
groupId: number,
messages: JsonValue,
): Promise<{ messageId: number; forwardId: string }> {
@@ -665,7 +692,7 @@ async function handleSendGroupForward(
}
async function handleSendPrivateForward(
ref: InstanceRef,
ref: OneBotInstanceContext,
userId: number,
messages: JsonValue,
): Promise<{ messageId: number; forwardId: string }> {
@@ -688,7 +715,7 @@ async function handleSendPrivateForward(
}
async function handleUploadForward(
ref: InstanceRef,
ref: OneBotInstanceContext,
messages: JsonValue,
): Promise<{ forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
@@ -697,7 +724,7 @@ async function handleUploadForward(
}
async function handleGetForward(
ref: InstanceRef,
ref: OneBotInstanceContext,
resId: string,
): Promise<JsonObject[]> {
const nodes = await ref.bridge.fetchForwardNodes(resId);
@@ -717,7 +744,7 @@ async function handleGetForward(
return results;
}
async function parseForwardNodes(ref: InstanceRef, messages: JsonValue): Promise<ForwardNodePayload[]> {
async function parseForwardNodes(ref: OneBotInstanceContext, messages: JsonValue): Promise<ForwardNodePayload[]> {
if (!Array.isArray(messages)) {
throw new Error('forward messages must be an array');
}