refactor(onebot): extract OneBot protocol translation into @snowluma/onebot
Phase 3 of the 4-package split (RoadMap #3). Moves the entire `packages/core/src/onebot/` subtree (43 source files + 20 test files spanning network adapters, action handlers, event converters, message parser, message store, media store, instance + manager) into the new `@snowluma/onebot` workspace package. The remaining `@snowluma/core` now hosts only the api-layer (Bridge class + 13 Api classes), the hook tooling, the WebUI server, and the runnable `index.ts`. Why --- - The OneBot adapter is the public-facing OneBot11 protocol surface; it has its own version cadence and its own consumers (third-party bots talking OneBot WS / HTTP). Splitting it lets that cadence move independently of the Api-on-ctx layer. - The two were sharing the `packages/core/` build pipeline only because they happened to live in the same directory. Nothing in the api-layer reaches into OneBot internals. - Mirrors NapCat / Lagrange.OneBot's repo split (their OneBot adapter is a separate assembly from the Core protocol library). Layout ------ Moved via `git mv` (history preserved): packages/core/src/onebot/* → @snowluma/onebot/src/<x> packages/core/tests/onebot/* (6 files) → @snowluma/onebot/tests/ packages/core/tests/{message-parser,message-store,event-pipeline, media-store,media-url-resolver,event-converter, http-server-hot-reload,http-server-content-type, api-handler-logging,message-id,group-msg-emoji-like, config,media-indexer,network-manager}.test.ts (14 files) → @snowluma/onebot/tests/ What stays in @snowluma/core ---------------------------- - `bridge/{bridge,bridge-interface,bridge-context,manager}.ts` - `bridge/apis/*` (the 13 typed Api classes) - `hook/*` (debugger/injector — tooling for the core protocol layer) - `webui/*` (admin UI server — application wiring, not the OneBot adapter itself) - `index.ts` (application entry that wires BridgeManager + OneBotManager + HookManager + WebUI together) Changes ------- - New package `packages/onebot/` (package.json with subpath exports mirroring legacy `core/src/onebot/<x>` 1:1, tsconfig.json, vitest.config.ts with `SNOWLUMA_LOG_LEVEL=debug` env so the action- dispatch logging tests see debug-level subscribers — copied verbatim from core's vitest.config.ts). - @snowluma/core grows new subpath exports for the api-layer files OneBot's type-only imports need: `./bridge`, `./bridge-interface`, `./bridge-context`, `./manager`, `./apis`. - `@snowluma/onebot` depends on `@snowluma/bridge`, `@snowluma/common`, `@snowluma/core`, `@snowluma/proto-defs`, `@snowluma/proton`, `@snowluma/websocket`. - `@snowluma/core` depends on `@snowluma/onebot` (for index.ts + webui/server.ts wiring). - 100+ import sites rewritten via sed: * OneBot → core: `'../bridge/bridge'` → `'@snowluma/core/bridge'`, `'../bridge/manager'` → `'@snowluma/core/manager'`, `'../bridge/bridge-interface'` → `'@snowluma/core/bridge-interface'`, `'@/bridge/bridge'` (vite path alias) → `'@snowluma/core/bridge'`. * Core → OneBot: `'./onebot/manager'` → `'@snowluma/onebot/manager'`, `'../onebot/config'` → `'@snowluma/onebot/config'`, etc. * Test relative paths: `'../../src/onebot/<x>'` → `'../src/<x>'` after the test file move (one level shallower). - New `packages/onebot/src/env.d.ts` declaring `__APP_VERSION__` and `__BUILD_WEBUI__` (the vite-injected globals `info.ts` reads). Workspace cycle --------------- core ↔ onebot is allowed by pnpm workspaces. The runtime direction is one-way: core → onebot (index.ts constructs OneBotManager, webui/server reads OneBot config). OneBot only reaches into core for TYPES (Bridge, BridgeInterface, BridgeManager, ClientKeyInfo, DownloadRKeyInfo); those imports use `import type` so they compile out at runtime and don't introduce a real cycle. Verification ------------ - Full workspace `pnpm -r typecheck`: all 11 projects clean. - `@snowluma/core` test suite: 302/302 pass (33 test files). - `@snowluma/onebot` test suite: 250/250 pass (20 test files; pre-existing `network-manager.test.ts` native-addon failure unchanged — same baseline as before the split). - Combined: 552/552 — identical pass count to the pre-Phase-3 baseline. - Vite build with stubbed native binary: clean, 2.84 MB bundle / 224 KB gzip (identical envelope).
This commit is contained in:
71 files changed
+286
-59
No files matched your search
@@ -0,0 +1,369 @@
|
||||
import path from 'path';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { ApiHandler } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import { MediaIndexer } from './media-indexer';
|
||||
import { MediaStore } from './media-store';
|
||||
import { MediaUrlResolver } from './media-url-resolver';
|
||||
import { MessageStore } from './message-store';
|
||||
import { RKeyCache } from './instance-rkey';
|
||||
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
|
||||
import { registerEventPipeline } from './event-pipeline';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||
import type { JsonObject, JsonValue, MessageMeta, OneBotConfig, NetworkBase } from './types';
|
||||
import {
|
||||
OneBotNetworkManager,
|
||||
WsServerAdapter,
|
||||
WsClientAdapter,
|
||||
HttpServerAdapter,
|
||||
HttpPostAdapter,
|
||||
type NetworkAdapterContext,
|
||||
} from './network';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/bridge/format';
|
||||
|
||||
const moduleLog = createLogger('Event');
|
||||
|
||||
export class OneBotInstance {
|
||||
readonly uin: string;
|
||||
|
||||
private readonly bridge: BridgeInterface;
|
||||
private readonly apiHandler: ApiHandler;
|
||||
private readonly converterCtx: ConverterContext;
|
||||
private readonly messageStore: MessageStore;
|
||||
private readonly mediaStore: MediaStore;
|
||||
private readonly networkManager: OneBotNetworkManager;
|
||||
private readonly rkeyCache: RKeyCache;
|
||||
private readonly ctx: OneBotInstanceContext;
|
||||
private disposeEventPipeline: (() => void) | null = null;
|
||||
|
||||
private readonly pids = new Set<number>();
|
||||
private online = true;
|
||||
private heartbeatTimer: NodeJS.Timeout | null = null;
|
||||
private static readonly HEARTBEAT_INTERVAL = 30000;
|
||||
private readonly log: Logger;
|
||||
|
||||
get nickname(): string { return this.bridge.identity.nickname; }
|
||||
|
||||
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
|
||||
this.uin = uin;
|
||||
this.bridge = bridge;
|
||||
const uinNum = Number.parseInt(uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLog.child({ uin: uinNum })
|
||||
: moduleLog;
|
||||
|
||||
this.rkeyCache = new RKeyCache();
|
||||
this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db'));
|
||||
this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json'));
|
||||
|
||||
// The converter context's four callbacks delegate to small, focused
|
||||
// modules so this constructor doesn't carry the bridge-URL fetch
|
||||
// branching or the mediaStore field-mapping fanout inline.
|
||||
const mediaUrlResolver = new MediaUrlResolver(this.bridge, this.rkeyCache);
|
||||
const mediaIndexer = new MediaIndexer(this.mediaStore);
|
||||
this.converterCtx = {
|
||||
selfId: parseInt(this.uin, 10) || 0,
|
||||
imageUrlResolver: (element, isGroup) =>
|
||||
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
|
||||
mediaUrlResolver: (element, isGroup, sessionId) =>
|
||||
mediaUrlResolver.resolve(element, isGroup, sessionId),
|
||||
messageIdResolver: (isGroup, sessionId, sequence, eventName) =>
|
||||
hashMessageIdInt32(sequence, sessionId, eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT)),
|
||||
mediaSegmentSink: (mediaType, element, data, isGroup, sessionId) =>
|
||||
mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
|
||||
};
|
||||
|
||||
// Shared instance context. Only carries fields that are actually read
|
||||
// through it — api handler and network manager stay as direct fields on
|
||||
// the instance because nothing reads them via ctx.
|
||||
const ctx: OneBotInstanceContext = {
|
||||
uin: this.uin,
|
||||
selfId: parseInt(this.uin, 10) || 0,
|
||||
bridge: this.bridge,
|
||||
messageStore: this.messageStore,
|
||||
mediaStore: this.mediaStore,
|
||||
converterCtx: this.converterCtx,
|
||||
config,
|
||||
musicSignUrl: config.musicSignUrl,
|
||||
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
|
||||
dispatchEvent: (event) => this.dispatchEvent(event),
|
||||
};
|
||||
this.ctx = ctx;
|
||||
|
||||
this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined);
|
||||
this.networkManager = new OneBotNetworkManager();
|
||||
this.installAdaptersFromConfig(config);
|
||||
void this.networkManager.openAll().catch((err) => {
|
||||
this.log.warn('openAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
|
||||
this.startHeartbeat();
|
||||
this.rkeyCache.warmUp(this.bridge, this.uin);
|
||||
|
||||
// Per-kind subscription on the typed event bus. Each bridge event kind
|
||||
// gets its own focused handler in `event-pipeline`; the firehose is gone.
|
||||
this.disposeEventPipeline = registerEventPipeline(ctx);
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
void this.applyConfigDiff(config).catch((err) => {
|
||||
this.log.warn('applyConfigDiff failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.online = false;
|
||||
this.stopHeartbeat();
|
||||
this.disposeEventPipeline?.();
|
||||
this.disposeEventPipeline = null;
|
||||
void this.networkManager.closeAll().catch((err) => {
|
||||
this.log.warn('closeAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
this.messageStore.close();
|
||||
this.mediaStore.close();
|
||||
}
|
||||
|
||||
addPid(pid: number): void {
|
||||
this.pids.add(pid);
|
||||
}
|
||||
|
||||
removePid(pid: number): void {
|
||||
this.pids.delete(pid);
|
||||
}
|
||||
|
||||
hasPid(pid: number): boolean {
|
||||
return this.pids.has(pid);
|
||||
}
|
||||
|
||||
getPids(): number[] {
|
||||
return [...this.pids];
|
||||
}
|
||||
|
||||
get empty(): boolean {
|
||||
return this.pids.size === 0;
|
||||
}
|
||||
|
||||
private dispatchEvent(event: JsonObject): void {
|
||||
this.cacheMessageEvent(event);
|
||||
this.logReceivedMessage(event);
|
||||
// NetworkManager builds the dispatch payload once and fans out to every
|
||||
// active adapter in parallel via Promise.allSettled — per-adapter errors
|
||||
// are already isolated, so the outer promise should never reject. The
|
||||
// .catch is a belt-and-suspenders guard against future refactors.
|
||||
void this.networkManager.emitEvent(event).catch((err) => {
|
||||
this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
private buildNetworkContext(): NetworkAdapterContext {
|
||||
return {
|
||||
uin: this.uin,
|
||||
api: this.apiHandler,
|
||||
buildLifecycleEvent: (subType) => this.makeLifecycleEvent(subType),
|
||||
buildHeartbeatEvent: () => this.makeHeartbeatEvent(),
|
||||
};
|
||||
}
|
||||
|
||||
private installAdaptersFromConfig(config: OneBotConfig): void {
|
||||
const ctx = this.buildNetworkContext();
|
||||
for (const net of config.networks.httpServers) {
|
||||
if (net.enabled === false) continue;
|
||||
this.networkManager.register(new HttpServerAdapter(net.name, net, ctx));
|
||||
}
|
||||
for (const net of config.networks.httpClients) {
|
||||
if (net.enabled === false || !net.url) continue;
|
||||
this.networkManager.register(new HttpPostAdapter(net.name, net, ctx));
|
||||
}
|
||||
for (const net of config.networks.wsServers) {
|
||||
if (net.enabled === false) continue;
|
||||
this.networkManager.register(new WsServerAdapter(net.name, net, ctx));
|
||||
}
|
||||
for (const net of config.networks.wsClients) {
|
||||
if (net.enabled === false || !net.url) continue;
|
||||
this.networkManager.register(new WsClientAdapter(net.name, net, ctx));
|
||||
}
|
||||
}
|
||||
|
||||
private async applyConfigDiff(next: OneBotConfig): Promise<void> {
|
||||
const ctx = this.buildNetworkContext();
|
||||
const desired = new Map<string, NetworkBase>();
|
||||
const factories = new Map<string, () => void>();
|
||||
|
||||
for (const net of next.networks.httpServers) {
|
||||
desired.set(net.name, net);
|
||||
factories.set(net.name, () => this.networkManager.register(new HttpServerAdapter(net.name, net, ctx)));
|
||||
}
|
||||
for (const net of next.networks.httpClients) {
|
||||
desired.set(net.name, net);
|
||||
factories.set(net.name, () => this.networkManager.register(new HttpPostAdapter(net.name, net, ctx)));
|
||||
}
|
||||
for (const net of next.networks.wsServers) {
|
||||
desired.set(net.name, net);
|
||||
factories.set(net.name, () => this.networkManager.register(new WsServerAdapter(net.name, net, ctx)));
|
||||
}
|
||||
for (const net of next.networks.wsClients) {
|
||||
desired.set(net.name, net);
|
||||
factories.set(net.name, () => this.networkManager.register(new WsClientAdapter(net.name, net, ctx)));
|
||||
}
|
||||
|
||||
// Close adapters whose entry has been removed entirely.
|
||||
for (const adapter of this.networkManager.list()) {
|
||||
if (!desired.has(adapter.name)) {
|
||||
await this.networkManager.closeOne(adapter.name);
|
||||
}
|
||||
}
|
||||
|
||||
// Reload existing adapters in place; spin up new ones the manager hasn't
|
||||
// seen before.
|
||||
for (const [name, net] of desired) {
|
||||
const existing = this.networkManager.get(name);
|
||||
if (existing) {
|
||||
try {
|
||||
await existing.reload(net as never);
|
||||
} catch (err) {
|
||||
this.log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
} else if (net.enabled !== false) {
|
||||
const factory = factories.get(name);
|
||||
if (factory) {
|
||||
factory();
|
||||
await this.networkManager.get(name)?.open();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private logReceivedMessage(event: JsonObject): void {
|
||||
const isSelf = event.post_type === 'message_sent';
|
||||
if (event.post_type !== 'message' && !isSelf) return;
|
||||
|
||||
const messageId = toInt(event.message_id);
|
||||
const isGroup = event.message_type === 'group';
|
||||
const idStr = `ID:${messageId}`;
|
||||
const selfTag = isSelf ? '[自身] ' : '';
|
||||
const identity = this.bridge.identity;
|
||||
|
||||
// Walk the segment array once: render via the shared formatter for
|
||||
// non-reply segments, and resolve `reply` segments through the
|
||||
// message store so the chain reference becomes legible
|
||||
// ("[回复 <user>: <body>...]" instead of "[回复:1234567890]").
|
||||
const renderedParts: string[] = [];
|
||||
const message = event.message;
|
||||
if (Array.isArray(message)) {
|
||||
for (const seg of message) {
|
||||
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
|
||||
const type = String((seg as JsonObject).type ?? '');
|
||||
const data = (typeof (seg as JsonObject).data === 'object' && (seg as JsonObject).data !== null && !Array.isArray((seg as JsonObject).data))
|
||||
? (seg as JsonObject).data as Record<string, unknown>
|
||||
: {};
|
||||
if (type === 'reply') {
|
||||
const replyId = toInt(data.id);
|
||||
renderedParts.push(formatReply(this.messageStore, identity, replyId));
|
||||
} else {
|
||||
renderedParts.push(formatMessageSegments([seg as JsonValue]));
|
||||
}
|
||||
}
|
||||
} else if (typeof message === 'string') {
|
||||
renderedParts.push(formatMessageSegments(message));
|
||||
}
|
||||
const content = renderedParts.join(' ').trim() || '[空消息]';
|
||||
|
||||
if (isGroup) {
|
||||
const groupId = toInt(event.group_id);
|
||||
const userId = toInt(event.user_id);
|
||||
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
|
||||
? event.sender as JsonObject
|
||||
: {};
|
||||
const nicknameFromEvent = (sender.card as string) || (sender.nickname as string) || '';
|
||||
const userPart = nicknameFromEvent
|
||||
? `[${nicknameFromEvent}(${userId})]`
|
||||
: formatUser(identity, groupId, userId);
|
||||
this.log.success(`${selfTag}群 ${formatGroup(identity, groupId)} | ${userPart}: ${idStr} ${content}`);
|
||||
} else {
|
||||
const userId = toInt(event.user_id);
|
||||
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
|
||||
? event.sender as JsonObject
|
||||
: {};
|
||||
const nicknameFromEvent = (sender.nickname as string) || '';
|
||||
const userPart = nicknameFromEvent
|
||||
? `[${nicknameFromEvent}(${userId})]`
|
||||
: formatUser(identity, undefined, userId);
|
||||
this.log.success(`${selfTag}私聊 ${userPart}: ${idStr} ${content}`);
|
||||
}
|
||||
}
|
||||
|
||||
private cacheMessageEvent(event: JsonObject): void {
|
||||
if (event.post_type !== 'message' && event.post_type !== 'message_sent') return;
|
||||
|
||||
const messageId = toInt(event.message_id);
|
||||
if (messageId === 0) return;
|
||||
|
||||
const isGroup = event.message_type === 'group';
|
||||
const sessionId = isGroup ? toInt(event.group_id) : toInt(event.user_id);
|
||||
const sequence = toInt(event.message_seq);
|
||||
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||
|
||||
if (sessionId === 0) return;
|
||||
this.messageStore.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event);
|
||||
}
|
||||
|
||||
private cacheMessageMeta(messageId: number, meta: MessageMeta): void {
|
||||
if (!Number.isInteger(messageId) || messageId === 0) return;
|
||||
this.messageStore.storeMeta(messageId, meta);
|
||||
}
|
||||
|
||||
private makeLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject {
|
||||
const selfId = parseInt(this.uin, 10) || 0;
|
||||
const time = Math.floor(Date.now() / 1000);
|
||||
return {
|
||||
time,
|
||||
self_id: selfId,
|
||||
post_type: 'meta_event',
|
||||
meta_event_type: 'lifecycle',
|
||||
sub_type: subType,
|
||||
status: {
|
||||
online: this.online,
|
||||
good: this.online,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// --- Heartbeat ---
|
||||
|
||||
private startHeartbeat(): void {
|
||||
this.heartbeatTimer = setInterval(() => {
|
||||
this.dispatchEvent(this.makeHeartbeatEvent());
|
||||
}, OneBotInstance.HEARTBEAT_INTERVAL);
|
||||
this.heartbeatTimer.unref?.();
|
||||
}
|
||||
|
||||
private makeHeartbeatEvent(): JsonObject {
|
||||
const selfId = parseInt(this.uin, 10) || 0;
|
||||
const time = Math.floor(Date.now() / 1000);
|
||||
return {
|
||||
time,
|
||||
self_id: selfId,
|
||||
post_type: 'meta_event',
|
||||
meta_event_type: 'heartbeat',
|
||||
status: { online: this.online, good: this.online },
|
||||
interval: OneBotInstance.HEARTBEAT_INTERVAL,
|
||||
};
|
||||
}
|
||||
|
||||
private stopHeartbeat(): void {
|
||||
if (this.heartbeatTimer) {
|
||||
clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toInt(value: unknown): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const parsed = Number(value);
|
||||
if (Number.isFinite(parsed)) return Math.trunc(parsed);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user