diff --git a/packages/core/package.json b/packages/core/package.json index ed6d2353..24b5932b 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -14,6 +14,14 @@ "types": "./src/bridge/bridge.ts", "default": "./src/bridge/bridge.ts" }, + "./inject-bridge": { + "types": "./src/bridge/inject-bridge.ts", + "default": "./src/bridge/inject-bridge.ts" + }, + "./protocol-bridge": { + "types": "./src/bridge/protocol-bridge.ts", + "default": "./src/bridge/protocol-bridge.ts" + }, "./bridge-interface": { "types": "./src/bridge/bridge-interface.ts", "default": "./src/bridge/bridge-interface.ts" @@ -26,6 +34,18 @@ "types": "./src/bridge/manager.ts", "default": "./src/bridge/manager.ts" }, + "./adapter": { + "types": "./src/bridge/adapter.ts", + "default": "./src/bridge/adapter.ts" + }, + "./inject-adapter": { + "types": "./src/bridge/inject-adapter.ts", + "default": "./src/bridge/inject-adapter.ts" + }, + "./protocol-adapter": { + "types": "./src/bridge/protocol-adapter.ts", + "default": "./src/bridge/protocol-adapter.ts" + }, "./apis": { "types": "./src/bridge/apis/index.ts", "default": "./src/bridge/apis/index.ts" diff --git a/packages/core/src/bridge/adapter.ts b/packages/core/src/bridge/adapter.ts new file mode 100644 index 00000000..c4e40830 --- /dev/null +++ b/packages/core/src/bridge/adapter.ts @@ -0,0 +1,65 @@ +import type { Logger } from '@snowluma/common/logger'; +import type { Bridge } from './bridge'; +import type { BridgeKind } from './bridge-interface'; + +/** + * Sink that `BridgeManager` exposes to a `BridgeAdapter` so the adapter + * can publish discovered bridges and tear them down when the underlying + * runtime says they're gone. + * + * The host is intentionally narrow: adapters cannot reach into the + * manager's session bookkeeping, only emit `addBridge` / `removeBridge` + * events. Anything else (lookup, primary selection, callback wiring) + * is the manager's concern. + */ +export interface BridgeAdapterHost { + /** Publish a freshly-online bridge. The manager dedupes by + * `bridge.id`; calling this with an already-registered id is a + * no-op (and logs a warning in dev mode). */ + addBridge(bridge: Bridge): void; + /** Tear down the bridge with the given `id`. The manager calls + * `bridge.dispose()` on its way out and notifies session-closed + * subscribers if this was the last bridge for the UIN. */ + removeBridge(bridgeId: string): void; + /** Adapter-scoped logger. Adapters should prefer this over a + * module-level logger so `BridgeManager` can label log lines per + * adapter kind. */ + readonly log: Logger; +} + +/** + * A `BridgeAdapter` is the bridge between an external login source + * (NTQQ hook, future pure-protocol client, …) and the manager's pool + * of `AccountBridge`s. Each adapter encapsulates: + * + * - how its runtime is started / stopped, + * - how it discovers new logins (events from a watcher, polling, + * manual `start` from WebUI, …), + * - how it materialises a concrete `Bridge` subclass for each login, + * - how it cleans up when a login disappears. + * + * The manager itself remains transport-agnostic: it only knows about + * `Bridge` instances coming and going through `BridgeAdapterHost`. + * + * Lifecycle expectations: + * + * - `start(host)` is called once when the manager initialises. The + * adapter retains the `host` and is free to call into it from any + * point until `dispose()` is invoked. + * - `dispose()` MUST be idempotent and MUST tear down every bridge + * the adapter previously published (the manager calls + * `removeBridge` for them in turn). + */ +export interface BridgeAdapter { + /** Discriminator that mirrors the `kind` of the bridges this + * adapter produces. Used by the manager for diagnostics and to + * refuse duplicate registrations of the same kind. */ + readonly kind: BridgeKind; + + /** Hook the adapter into a freshly-built manager. Called exactly + * once per adapter instance. */ + start(host: BridgeAdapterHost): Promise | void; + + /** Stop the adapter and tear down every bridge it produced. */ + dispose(): Promise | void; +} diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index 8e455a39..b208ea15 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -1,5 +1,43 @@ +import type { PacketInfo } from '@snowluma/common/protocol-types'; import type { BridgeContext } from './bridge-context'; +/** + * Discriminator for the two bridge implementations: + * + * - `'inject'` — backed by an in-process NTQQ hook (one or more + * QQ.exe processes injected with the SnowLuma DLL, + * talking over named pipes). + * - `'protocol'` — backed by a direct protocol client (no QQ.exe, + * no hook). Reserved for the future pure-protocol + * runtime; the concrete `ProtocolBridge` is a stub + * until that runtime lands. + * + * The kind is part of `BridgeInterface` so any consumer that genuinely + * needs to branch on transport (diagnostics, runtime-specific WebUI + * panels, …) can do so without `instanceof` checks against a concrete + * subclass. Day-to-day callers (OneBot, protocol APIs) MUST stay kind- + * agnostic — that's the whole point of the abstraction. + */ +export type BridgeKind = 'inject' | 'protocol'; + +/** + * The public surface every concrete bridge exposes. OneBot, protocol + * APIs and tests all consume this — never the concrete `Bridge` class + * — so swapping in a `ProtocolBridge` later is a transport change, not + * a business-logic change. + */ export interface BridgeInterface extends BridgeContext { - readonly activePid: number | null; + /** Transport family this bridge is backed by. */ + readonly kind: BridgeKind; + /** Stable identity of the bridge inside `BridgeManager` (e.g. + * `'inject:3161592748'`). Unique per live bridge. */ + readonly id: string; + /** QQ number this bridge represents. Mirrors `identity.uin`. */ + readonly uin: string; + /** Inject a freshly received packet into the per-cmd dispatch + * pipeline. Called by the owning `BridgeAdapter`; never by OneBot. */ + onPacket(packet: PacketInfo): void; + /** Release identity DB handles, event subscribers, and any + * transport-side resources. Idempotent. */ + dispose(): void; } diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index f4e560a8..a627f3d7 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -1,4 +1,4 @@ -import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; import type { PacketInfo } from '@snowluma/common/protocol-types'; import { BridgeEventBus } from '@snowluma/protocol/event-bus'; import { IdentityService } from '@snowluma/protocol/identity-service'; @@ -10,23 +10,53 @@ import { type AiVoiceCategory, type StrangerStatus, } from './apis/extras'; -import type { BridgeInterface } from './bridge-interface'; +import type { BridgeInterface, BridgeKind } from './bridge-interface'; +/** + * Abstract base for every concrete account bridge (`InjectBridge`, + * `ProtocolBridge`, …). Owns everything that is transport-agnostic: + * + * - the per-account `IdentityService` (friend/group/uid cache + DB), + * - the typed `BridgeEventBus` (per-kind subscribers), + * - the `ApiHub` (typed wrappers around `sendRawPacket`), + * - the `IncomingPacketPipeline` (cmd → decoder dispatch), + * - the uploaded-file cache shared between `upload_*_file` and + * `send_msg`, + * - the monotonic `clientSequence` / `messageRandom` counters. + * + * Subclasses only have to provide: + * + * 1. `kind` / `id` — discriminators for `BridgeManager` bookkeeping + * and diagnostics. + * 2. `sendRawPacket` — the actual wire-level transport. `InjectBridge` + * forwards to a `PacketSender` (the hook named-pipe client); + * `ProtocolBridge` will eventually forward to a long-lived TCP + * protocol client. + * + * The base class is intentionally abstract: callers never write + * `new Bridge(...)`. Tests that want to exercise the common + * pipeline / identity logic subclass `Bridge` (supplying the two + * abstract members) or instantiate `InjectBridge` directly. + */ +export abstract class Bridge implements BridgeInterface { + abstract readonly kind: BridgeKind; + abstract readonly id: string; -export class Bridge implements BridgeInterface { + readonly uin: string; readonly identity: IdentityService; - private pids_ = new Set(); readonly events = new BridgeEventBus(); readonly apis: ApiHub; + private readonly pipeline: IncomingPacketPipeline; - private packetClient_: PacketSender | null = null; private static readonly UPLOADED_FILE_CACHE_MAX = 1024; - private uploadedFileMeta_ = new Map(); + private readonly uploadedFileMeta_ = new Map(); private clientSeq_ = 100000000 + (Date.now() % 1000000000); private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0; + private disposed_ = false; constructor(identity: IdentityService) { this.identity = identity; + this.uin = identity.uin; this.apis = buildApiHub(this); this.identity.setFetcher({ fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin), @@ -63,14 +93,30 @@ export class Bridge implements BridgeInterface { this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush); } + // ─── BridgeInterface plumbing ────────────────────────────── + + onPacket(packet: PacketInfo): void { + this.pipeline.process(packet); + } + dispose(): void { + if (this.disposed_) return; + this.disposed_ = true; this.identity.close(); this.events.clear(); } - setPacketClient(client: PacketSender): void { - this.packetClient_ = client; - } + get isDisposed(): boolean { return this.disposed_; } + + // ─── Transport (abstract — implemented per-subclass) ──────────── + + abstract sendRawPacket( + serviceCmd: string, + body: Uint8Array, + timeoutMs?: number, + ): Promise; + + // ─── Pipeline registration (used by tests + extra cmd modules) ────── registerCmd(cmd: string, parser: CmdParser): void { this.pipeline.registerCmd(cmd, parser); @@ -80,30 +126,19 @@ export class Bridge implements BridgeInterface { return this.pipeline.handlesCmd(cmd); } - attachPid(pid: number): void { - this.pids_.add(pid); - } - detachPid(pid: number): void { - this.pids_.delete(pid); - } - hasPid(pid: number): boolean { return this.pids_.has(pid); } - get empty(): boolean { return this.pids_.size === 0; } - get activePid(): number | null { - for (const pid of this.pids_) return pid; - return null; - } - onPacket(pkt: PacketInfo): void { - this.pipeline.process(pkt); + // ─── Send-side protocol helpers (shared sequence generators) ──────── + + nextClientSequence(): number { + return ++this.clientSeq_; } - private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise { - if (refreshGroupList) { - try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ } - } - if (!this.identity.findGroup(groupId)) return false; - await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList }); - return true; + nextMessageRandom(): number { + this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0; + return this.msgRandom_ & 0x7FFFFFFF; } + + // ─── Uploaded-file cache ────────────────────────────────── + rememberUploadedFile(meta: UploadedFileMeta): void { if (!meta.fileId) return; if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) { @@ -119,26 +154,26 @@ export class Bridge implements BridgeInterface { return this.uploadedFileMeta_.get(fileId); } - nextClientSequence(): number { - return ++this.clientSeq_; - } + // ─── Identity convenience ────────────────────────────────── - nextMessageRandom(): number { - this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0; - return this.msgRandom_ & 0x7FFFFFFF; - } - async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise { - if (!this.packetClient_) { - return { - success: false, gotResponse: false, errorCode: -1, - errorMessage: 'no packet sender attached', responseData: null, - }; - } - return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs); - } async resolveUserUid(uin: number, groupId?: number): Promise { return this.identity.resolveUid(uin, groupId); } + + // ─── Internal helpers ───────────────────────────────────── + + private async refreshMemberCache( + groupId: number, + refreshGroupList: boolean, + forceMemberList: boolean, + ): Promise { + if (refreshGroupList) { + try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ } + } + if (!this.identity.findGroup(groupId)) return false; + await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList }); + return true; + } } export interface SendMessageReceipt { messageId: number; diff --git a/packages/core/src/bridge/inject-adapter.ts b/packages/core/src/bridge/inject-adapter.ts new file mode 100644 index 00000000..467e2283 --- /dev/null +++ b/packages/core/src/bridge/inject-adapter.ts @@ -0,0 +1,176 @@ +import { HookManager, type BridgeManagerSink, type HookManagerDeps } from '@snowluma/bridge'; +import type { PacketSender } from '@snowluma/common/packet-sender'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; +import type { BridgeAdapter, BridgeAdapterHost } from './adapter'; +import { InjectBridge } from './inject-bridge'; + +/** Subset of `HookManagerDeps` the operator is allowed to forward + * through the adapter. The `bridgeManager` sink is owned by the + * adapter itself and intentionally not exposed. */ +export type InjectBridgeAdapterOptions = Omit; + +/** + * `InjectBridgeAdapter` — the `BridgeAdapter` for the NTQQ hook + * runtime. It owns the `HookManager` and translates its three sink + * callbacks (`onHookLogin` / `onPacket` / `onPidDisconnected`) into + * lifecycle events on a per-UIN `InjectBridge`. + * + * Why an adapter rather than letting `BridgeManager` keep the hook + * sink: this is the only place in the codebase that legitimately needs + * to know about PIDs. Quarantining that knowledge here keeps + * `BridgeManager` (and everything above it) free of `pid`, leaving the + * door open for a future `ProtocolBridgeAdapter` that doesn't have the + * concept at all. + * + * Internal bookkeeping: + * + * - `pidToUin` — quick "which UIN does this PID feed?" lookup, + * populated on login (and lazily during defensive + * packet routing for PIDs that arrived ahead of + * their login notification). + * - `pidToSender` — the live `PacketSender` per PID, so a re-login + * from the same PID rotates the outbound sender + * without dropping the bridge. + * - `uinToPids` — reverse index for fast "did this UIN lose its + * last PID?" checks on disconnect. + * - `bridgesByUin` — one `InjectBridge` per UIN; the manager only + * sees `Bridge` instances, never the PID set + * living inside them. + */ +export class InjectBridgeAdapter implements BridgeAdapter, BridgeManagerSink { + readonly kind = 'inject' as const; + + private readonly hookManager_: HookManager; + + private readonly pidToUin = new Map(); + private readonly pidToSender = new Map(); + private readonly uinToPids = new Map>(); + private readonly bridgesByUin = new Map(); + + private host_: BridgeAdapterHost | null = null; + private disposed_ = false; + + constructor(opts: InjectBridgeAdapterOptions = {}) { + // `bridgeManager: this` wires HookManager → adapter sink. The + // HookManager doesn't know about the broader BridgeAdapter + // contract; it only sees the three sink methods we implement + // below. + this.hookManager_ = new HookManager({ ...opts, bridgeManager: this }); + } + + /** The underlying `HookManager`, exposed so WebUI can keep its + * `/api/processes/*` endpoints pointing at the hook process table. + * Higher-level code (OneBot, bridge consumers) MUST NOT reach into + * this — that's the whole point of the adapter layer. */ + get hookManager(): HookManager { return this.hookManager_; } + + // ─── BridgeAdapter contract ────────────────────────────────────── + + start(host: BridgeAdapterHost): void { + this.host_ = host; + host.log.debug('inject bridge adapter started'); + } + + dispose(): void { + if (this.disposed_) return; + this.disposed_ = true; + // Tear down hook sessions first so no more sink callbacks fire. + this.hookManager_.dispose(); + // Then proactively remove every bridge we published; the manager + // will call `bridge.dispose()` on its way out. + for (const id of [...this.bridgesByUin.values()].map(b => b.id)) { + this.host_?.removeBridge(id); + } + this.pidToUin.clear(); + this.pidToSender.clear(); + this.uinToPids.clear(); + this.bridgesByUin.clear(); + this.host_ = null; + } + + // ─── BridgeManagerSink contract (called by HookManager) ────────── + + onHookLogin(pid: number, uin: string, packetClient: PacketSender): void { + if (this.disposed_ || !isRealUin(uin)) return; + + this.recordPidMapping(pid, uin, packetClient); + const bridge = this.ensureBridge(uin); + bridge.attachPid(pid, packetClient); + } + + onPacket(pkt: PacketInfo): void { + if (this.disposed_ || !pkt.uin || !isRealUin(pkt.uin)) return; + + const uin = pkt.uin; + const bridge = this.ensureBridge(uin); + + // Defensive: a packet may arrive before its login notification + // when the bridge is being re-adopted (SnowLuma restarted while + // the hook stayed resident in QQ.exe). If we have a sender for + // this PID, weave it in so subsequent sends through this bridge + // succeed. + if (pkt.pid) { + const sender = this.pidToSender.get(pkt.pid); + if (sender && !this.pidToUin.has(pkt.pid)) { + this.recordPidMapping(pkt.pid, uin, sender); + bridge.attachPid(pkt.pid, sender); + } + } + + bridge.onPacket(pkt); + } + + onPidDisconnected(pid: number): void { + if (this.disposed_) return; + this.pidToSender.delete(pid); + + const uin = this.pidToUin.get(pid); + if (!uin) return; + this.pidToUin.delete(pid); + + const pids = this.uinToPids.get(uin); + if (pids) { + pids.delete(pid); + if (pids.size === 0) this.uinToPids.delete(uin); + } + + const bridge = this.bridgesByUin.get(uin); + if (!bridge) return; + bridge.detachPid(pid); + + if (bridge.isEmpty) { + this.bridgesByUin.delete(uin); + this.host_?.removeBridge(bridge.id); + } + } + + // ─── internal ──────────────────────────────────────────────────── + + private recordPidMapping(pid: number, uin: string, sender: PacketSender): void { + this.pidToUin.set(pid, uin); + this.pidToSender.set(pid, sender); + let pids = this.uinToPids.get(uin); + if (!pids) { + pids = new Set(); + this.uinToPids.set(uin, pids); + } + pids.add(pid); + } + + private ensureBridge(uin: string): InjectBridge { + let bridge = this.bridgesByUin.get(uin); + if (bridge) return bridge; + bridge = new InjectBridge(uin); + this.bridgesByUin.set(uin, bridge); + this.host_?.addBridge(bridge); + return bridge; + } +} + +// QQ uins are 5-12 decimal digits; "0" is the hook's "no login yet" +// sentinel. Anything else (empty, alpha, too short) is a sign the hook +// callback fired before login info was probed — we ignore those. +function isRealUin(uin: string): boolean { + if (!uin || uin === '0') return false; + return /^\d+$/.test(uin) && uin.length >= 5; +} diff --git a/packages/core/src/bridge/inject-bridge.ts b/packages/core/src/bridge/inject-bridge.ts new file mode 100644 index 00000000..b8e8c411 --- /dev/null +++ b/packages/core/src/bridge/inject-bridge.ts @@ -0,0 +1,85 @@ +import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender'; +import { IdentityService } from '@snowluma/protocol/identity-service'; +import { Bridge } from './bridge'; + +/** + * `InjectBridge` — the concrete account bridge backed by the in-process + * NTQQ hook (one or more QQ.exe processes injected with the SnowLuma + * DLL talking over named pipes). + * + * One UIN may be served simultaneously by several injected processes; + * the bridge therefore tracks an unordered set of PIDs and keeps a + * single live `PacketSender` (the most recently logged-in pipe) for + * outbound traffic. PID bookkeeping is intentionally kept here rather + * than on the abstract `Bridge` so the protocol-only runtime never + * sees the concept. + * + * The owning `InjectBridgeAdapter` is responsible for: + * - calling `attachPid(pid, sender)` on every successful hook login, + * - calling `detachPid(pid)` when the watcher reports a pipe drop, + * - calling `dispose()` when the last PID drops. + */ +export class InjectBridge extends Bridge { + readonly kind = 'inject' as const; + + private readonly pids_ = new Set(); + private packetClient_: PacketSender | null = null; + + /** + * @param uin QQ number this bridge represents. + * @param identity Optional pre-built `IdentityService`. The default + * opens the on-disk SQLite store at + * `data//snowluma_identity.db`; tests usually + * pass `IdentityService.memory(uin)` to avoid touching + * the filesystem. + */ + constructor(uin: string, identity: IdentityService = IdentityService.openForUin(uin)) { + super(identity); + } + + /** Stable, unique-per-account id used by `BridgeManager`. */ + get id(): string { return `inject:${this.uin}`; } + + /** PIDs currently routing packets into this bridge. Read-only view + * for diagnostics — mutate only via `attachPid` / `detachPid`. */ + get pids(): ReadonlySet { return this.pids_; } + + /** True iff no PID is currently bound; the adapter uses this to + * decide when to remove the bridge from `BridgeManager`. */ + get isEmpty(): boolean { return this.pids_.size === 0; } + + /** Bind a freshly-logged-in PID (and its outbound `PacketSender`) + * to this bridge. Idempotent — re-binding the same PID just rotates + * the active sender. */ + attachPid(pid: number, sender: PacketSender): void { + this.pids_.add(pid); + this.packetClient_ = sender; + } + + /** Forget a PID. If it owned the active sender we drop it; the next + * `attachPid` (or pipe-up) will install a fresh one. */ + detachPid(pid: number): void { + this.pids_.delete(pid); + if (this.pids_.size === 0) { + this.packetClient_ = null; + } + } + + override async sendRawPacket( + serviceCmd: string, + body: Uint8Array, + timeoutMs = 15000, + ): Promise { + const client = this.packetClient_; + if (!client) { + return { + success: false, + gotResponse: false, + errorCode: -1, + errorMessage: 'inject bridge has no live packet sender', + responseData: null, + }; + } + return client.sendPacket(serviceCmd, Buffer.from(body), timeoutMs); + } +} diff --git a/packages/core/src/bridge/manager.ts b/packages/core/src/bridge/manager.ts index 48a9101e..ece222f2 100644 --- a/packages/core/src/bridge/manager.ts +++ b/packages/core/src/bridge/manager.ts @@ -1,117 +1,271 @@ import { createLogger } from '@snowluma/common/logger'; -import type { PacketSender } from '@snowluma/common/packet-sender'; -import type { PacketInfo } from '@snowluma/common/protocol-types'; -import { IdentityService } from '@snowluma/protocol/identity-service'; -import { Bridge } from './bridge'; +import type { BridgeAdapter, BridgeAdapterHost } from './adapter'; +import type { Bridge } from './bridge'; +import type { BridgeKind } from './bridge-interface'; export type SessionStartedCallback = (uin: string, bridge: Bridge) => void; export type SessionClosedCallback = (uin: string) => void; -interface QQSession { - bridge: Bridge; -} - const log = createLogger('Bridge'); +/** + * `BridgeManager` — the multi-account host that wires bridge + * **adapters** (transport sources) up to bridge **consumers** (OneBot, + * WebUI status panels). + * + * The manager is intentionally transport-agnostic: it knows nothing + * about PIDs, named pipes, or future protocol clients. Each adapter + * (`InjectBridgeAdapter`, `ProtocolBridgeAdapter`, …) translates its + * own runtime into `addBridge` / `removeBridge` calls; the manager + * just keeps the `bridgeId → Bridge` and `uin → bridgeId[]` indices + * up to date and fires the session callbacks consumers subscribe to. + * + * Multiple bridges per UIN are explicitly supported (e.g. hook + pure + * protocol on the same account). The primary bridge for a UIN is the + * one that wins `primaryPriority`, which currently prefers `inject` + * over `protocol` (operators trust the in-process hook more than the + * stand-alone protocol client today). OneBot sees the primary; non- + * primary bridges still receive packets normally but their events are + * dropped at the manager level so the user never sees duplicates. + */ export class BridgeManager { - private sessions_ = new Map(); - private pidToUin_ = new Map(); - private pidPacketClients_ = new Map(); + private readonly adapters_ = new Map(); + private readonly bridgesById_ = new Map(); + private readonly bridgesByUin_ = new Map>(); + private readonly primaryByUin_ = new Map(); private onSessionStarted_: SessionStartedCallback | null = null; private onSessionClosed_: SessionClosedCallback | null = null; + private started_ = false; + private disposed_ = false; + + // ─── callback wiring (consumed by OneBotManager) ───────────────── + setSessionStartedCallback(cb: SessionStartedCallback): void { this.onSessionStarted_ = cb; } setSessionClosedCallback(cb: SessionClosedCallback): void { this.onSessionClosed_ = cb; } - onPidDisconnected(pid: number): void { - this.pidPacketClients_.delete(pid); - const uin = this.pidToUin_.get(pid); - if (!uin) return; + // ─── adapter registration ──────────────────────────────────────── - this.pidToUin_.delete(pid); - const session = this.sessions_.get(uin); - if (!session) return; - - session.bridge.detachPid(pid); - if (session.bridge.empty) { - this.sessions_.delete(uin); - log.debug('session closed: UIN=%s', uin); - if (this.onSessionClosed_) this.onSessionClosed_(uin); - session.bridge.dispose(); + /** + * Register an adapter. Adapters may only be registered before + * `start()` is called; we surface a clear error otherwise so a + * mis-ordered bootstrap fails fast in dev. + * + * The manager enforces at most one adapter per `kind` — adapters are + * the singleton runtime owners (one hook runtime, one protocol + * runtime, …); multiple instances would race on the same login + * source. + */ + registerAdapter(adapter: BridgeAdapter): void { + if (this.started_) { + throw new Error('BridgeManager: cannot register adapters after start()'); } + if (this.adapters_.has(adapter.kind)) { + throw new Error(`BridgeManager: adapter of kind '${adapter.kind}' is already registered`); + } + this.adapters_.set(adapter.kind, adapter); } - private static isRealUin(uin: string): boolean { - if (!uin || uin === '0') return false; - return /^\d+$/.test(uin) && uin.length >= 5; + /** Look up an adapter by kind; returns `null` when not registered. */ + getAdapter(kind: BridgeKind): BridgeAdapter | null { + return this.adapters_.get(kind) ?? null; } - onHookLogin(pid: number, uin: string, packetClient: PacketSender): void { - if (!BridgeManager.isRealUin(uin)) return; + // ─── lifecycle ─────────────────────────────────────────────────── - this.pidPacketClients_.set(pid, packetClient); - - const { session, created } = this.ensureSession(uin); - session.bridge.attachPid(pid); - session.bridge.setPacketClient(packetClient); - this.pidToUin_.set(pid, uin); - - if (created) { - log.debug('session started: UIN=%s', uin); - if (this.onSessionStarted_) { - this.onSessionStarted_(uin, session.bridge); + /** Start every registered adapter, passing each one its scoped + * `BridgeAdapterHost`. Idempotent. */ + async start(): Promise { + if (this.started_) return; + this.started_ = true; + for (const [kind, adapter] of this.adapters_) { + const host = this.makeHost(kind); + try { + await adapter.start(host); + } catch (err) { + log.warn( + 'adapter [%s] failed to start: %s', + kind, + err instanceof Error ? (err.stack ?? err.message) : String(err), + ); } } } - onPacket(pkt: PacketInfo): void { - if (!pkt.uin || !BridgeManager.isRealUin(pkt.uin)) return; - const uin = pkt.uin; - - // Ensure session exists - const { session, created } = this.ensureSession(uin); - - // Attach PID if known - if (pkt.pid && this.pidPacketClients_.has(pkt.pid)) { - session.bridge.attachPid(pkt.pid); - this.pidToUin_.set(pkt.pid, uin); - - const client = this.pidPacketClients_.get(pkt.pid); - if (client) session.bridge.setPacketClient(client); - } - - // Notify session started on first real packet - if (created) { - log.debug('session started: UIN=%s', uin); - if (this.onSessionStarted_) { - this.onSessionStarted_(uin, session.bridge); + /** Dispose every adapter (which removes their bridges via the host), + * then dispose any bridges that somehow remain. Idempotent. */ + async dispose(): Promise { + if (this.disposed_) return; + this.disposed_ = true; + for (const [kind, adapter] of this.adapters_) { + try { + await adapter.dispose(); + } catch (err) { + log.warn( + 'adapter [%s] failed to dispose: %s', + kind, + err instanceof Error ? err.message : String(err), + ); } } - - // Dispatch packet to bridge - session.bridge.onPacket(pkt); + for (const bridge of this.bridgesById_.values()) { + try { bridge.dispose(); } catch { /* ignore */ } + } + this.bridgesById_.clear(); + this.bridgesByUin_.clear(); + this.primaryByUin_.clear(); } - private ensureSession(uin: string): { session: QQSession; created: boolean } { - let session = this.sessions_.get(uin); - if (session) return { session, created: false }; + // ─── queries (used by WebUI / OneBot lookups) ──────────────────── - const bridge = new Bridge(IdentityService.openForUin(uin)); - session = { bridge }; - this.sessions_.set(uin, session); - - // 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 }; + /** Primary bridge for a UIN (the one OneBot is bound to), or `null` + * if the UIN is currently offline. */ + getBridge(uin: string): Bridge | null { + const id = this.primaryByUin_.get(uin); + return id ? this.bridgesById_.get(id) ?? null : null; } - getSession(uin: string): QQSession | null { - return this.sessions_.get(uin) ?? null; + /** Every live bridge across every adapter. Iteration order is + * insertion order. */ + getBridges(): readonly Bridge[] { + return [...this.bridgesById_.values()]; } - get sessions(): Map { - return this.sessions_; + /** All bridges currently servicing a given UIN (one per adapter + * kind at most). The primary is `getBridge(uin)`. */ + getBridgesForUin(uin: string): readonly Bridge[] { + const ids = this.bridgesByUin_.get(uin); + if (!ids) return []; + const out: Bridge[] = []; + for (const id of ids) { + const bridge = this.bridgesById_.get(id); + if (bridge) out.push(bridge); + } + return out; + } + + /** UINs currently online (at least one bridge). */ + getOnlineUins(): readonly string[] { + return [...this.bridgesByUin_.keys()]; + } + + // ─── BridgeAdapterHost implementation (per-adapter) ────────────── + + private makeHost(kind: BridgeKind): BridgeAdapterHost { + const adapterLog = log.child({ adapter: kind }); + return { + log: adapterLog, + addBridge: (bridge) => this.addBridge(bridge, adapterLog), + removeBridge: (id) => this.removeBridge(id, adapterLog), + }; + } + + private addBridge(bridge: Bridge, adapterLog: { warn: (msg: string, ...args: unknown[]) => void }): void { + if (this.disposed_) return; + if (this.bridgesById_.has(bridge.id)) { + adapterLog.warn('addBridge: bridge id=%s is already registered, ignoring', bridge.id); + return; + } + this.bridgesById_.set(bridge.id, bridge); + + let ids = this.bridgesByUin_.get(bridge.uin); + if (!ids) { + ids = new Set(); + this.bridgesByUin_.set(bridge.uin, ids); + } + ids.add(bridge.id); + + const prevPrimaryId = this.primaryByUin_.get(bridge.uin); + const newPrimary = this.pickPrimary(bridge.uin); + if (!newPrimary) return; + this.primaryByUin_.set(bridge.uin, newPrimary.id); + + const isFirst = prevPrimaryId === undefined; + const primaryChanged = !isFirst && prevPrimaryId !== newPrimary.id; + + if (isFirst) { + log.debug('session started: UIN=%s via %s', bridge.uin, newPrimary.id); + this.onSessionStarted_?.(bridge.uin, newPrimary); + } else if (primaryChanged) { + // A higher-priority transport (e.g. protocol overtaking inject) + // came online. Treat it as restart-in-place: notify closed for + // the old primary, then started for the new one. OneBot already + // tears down + rebuilds its instance on closed→started, which + // is the only safe way to swap a bridge under it today. + log.debug('primary switched: UIN=%s %s → %s', + bridge.uin, prevPrimaryId, newPrimary.id); + this.onSessionClosed_?.(bridge.uin); + this.onSessionStarted_?.(bridge.uin, newPrimary); + } + } + + private removeBridge(id: string, adapterLog: { debug: (msg: string, ...args: unknown[]) => void }): void { + const bridge = this.bridgesById_.get(id); + if (!bridge) return; + this.bridgesById_.delete(id); + + const ids = this.bridgesByUin_.get(bridge.uin); + if (ids) { + ids.delete(id); + if (ids.size === 0) this.bridgesByUin_.delete(bridge.uin); + } + + const wasPrimary = this.primaryByUin_.get(bridge.uin) === id; + if (wasPrimary) this.primaryByUin_.delete(bridge.uin); + + const replacement = this.pickPrimary(bridge.uin); + if (replacement) { + // Another transport is still online for this UIN. Update primary + // and, if we just demoted the previously-primary, notify + // consumers so OneBot rebinds to the survivor. + this.primaryByUin_.set(bridge.uin, replacement.id); + if (wasPrimary) { + adapterLog.debug('primary failover: UIN=%s %s → %s', + bridge.uin, id, replacement.id); + this.onSessionClosed_?.(bridge.uin); + this.onSessionStarted_?.(bridge.uin, replacement); + } + } else if (wasPrimary) { + // Last bridge for this UIN is gone — session truly closed. + log.debug('session closed: UIN=%s', bridge.uin); + this.onSessionClosed_?.(bridge.uin); + } + + try { bridge.dispose(); } catch (err) { + adapterLog.debug('bridge.dispose() threw: %s', err instanceof Error ? err.message : String(err)); + } + } + + private pickPrimary(uin: string): Bridge | null { + const ids = this.bridgesByUin_.get(uin); + if (!ids || ids.size === 0) return null; + + let best: Bridge | null = null; + let bestRank = -Infinity; + for (const id of ids) { + const bridge = this.bridgesById_.get(id); + if (!bridge) continue; + const rank = primaryPriority(bridge.kind); + if (rank > bestRank) { + best = bridge; + bestRank = rank; + } + } + return best; + } +} + +/** + * Higher wins. Today we prefer the in-process hook over the future + * pure protocol — operators with QQ.exe running tend to trust the + * hook path more, and the pure-protocol runtime is unproven. This + * single function is the only knob to flip later (or to surface as + * config) when the protocol runtime is hardened. + */ +function primaryPriority(kind: BridgeKind): number { + switch (kind) { + case 'inject': return 100; + case 'protocol': return 50; } } diff --git a/packages/core/src/bridge/protocol-adapter.ts b/packages/core/src/bridge/protocol-adapter.ts new file mode 100644 index 00000000..5fc9ba6f --- /dev/null +++ b/packages/core/src/bridge/protocol-adapter.ts @@ -0,0 +1,30 @@ +import type { BridgeAdapter, BridgeAdapterHost } from './adapter'; + +/** + * `ProtocolBridgeAdapter` — placeholder for the future pure-protocol + * runtime. Once a `ProtocolClient` (long-lived TCP login session, + * heartbeat, reconnect loop, …) lands, this adapter will: + * + * 1. Read its account list from runtime config. + * 2. Spin up one `ProtocolClient` per configured account. + * 3. On successful login, materialise a `ProtocolBridge` and call + * `host.addBridge(bridge)`. + * 4. On logout / fatal error, call `host.removeBridge(bridge.id)`. + * + * Until that lands the adapter is registered as a no-op so the wider + * architecture (BridgeManager → BridgeAdapter[] → AccountBridge) is + * already in place and exercised in production. Registering it is + * harmless: `start()` does nothing, `dispose()` does nothing, no + * bridges are ever produced. + */ +export class ProtocolBridgeAdapter implements BridgeAdapter { + readonly kind = 'protocol' as const; + + start(host: BridgeAdapterHost): void { + host.log.debug('protocol bridge adapter is a stub; no protocol clients will be opened'); + } + + dispose(): void { + // Nothing to tear down yet. + } +} diff --git a/packages/core/src/bridge/protocol-bridge.ts b/packages/core/src/bridge/protocol-bridge.ts new file mode 100644 index 00000000..a37534ea --- /dev/null +++ b/packages/core/src/bridge/protocol-bridge.ts @@ -0,0 +1,52 @@ +import type { SendPacketResult } from '@snowluma/common/packet-sender'; +import { IdentityService } from '@snowluma/protocol/identity-service'; +import { Bridge } from './bridge'; + +/** + * `ProtocolBridge` — the placeholder concrete bridge for the future + * pure-protocol runtime (no QQ.exe, no hook). It already participates + * in `BridgeManager` and `BridgeInterface` so the rest of the system + * (OneBot, protocol APIs, WebUI) can be wired against the abstract + * surface today and gain real protocol traffic later without further + * refactor. + * + * Until a `ProtocolClient` is wired in, `sendRawPacket` returns a + * structured "not implemented" failure rather than throwing, so the + * surrounding code still treats it as a regular transport-down result. + * + * NOTE: kept deliberately small. When the real protocol runtime lands, + * the constructor will accept a `ProtocolClient` (or similar transport + * handle), `sendRawPacket` will forward to it, and an inbound packet + * dispatcher will pump received frames through the inherited + * `onPacket` pipeline. + */ +export class ProtocolBridge extends Bridge { + readonly kind = 'protocol' as const; + + /** + * @param uin QQ number this bridge represents. + * @param identity Optional pre-built `IdentityService`. Defaults to + * the on-disk SQLite store keyed by `uin`. + */ + constructor(uin: string, identity: IdentityService = IdentityService.openForUin(uin)) { + super(identity); + } + + /** Stable, unique-per-account id used by `BridgeManager`. */ + get id(): string { return `protocol:${this.uin}`; } + + override async sendRawPacket( + serviceCmd: string, + body: Uint8Array, + timeoutMs?: number, + ): Promise { + void serviceCmd; void body; void timeoutMs; + return { + success: false, + gotResponse: false, + errorCode: -1, + errorMessage: 'protocol bridge transport is not yet implemented', + responseData: null, + }; + } +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 26f84eae..a192db85 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,8 +1,9 @@ -import { HookManager } from '@snowluma/bridge'; import { closeLogger, createLogger } from '@snowluma/common/logger'; import { loadRuntimeConfig } from '@snowluma/common/runtime'; import { OneBotManager } from '@snowluma/onebot/manager'; +import { InjectBridgeAdapter } from './bridge/inject-adapter'; import { BridgeManager } from './bridge/manager'; +import { ProtocolBridgeAdapter } from './bridge/protocol-adapter'; const runtimeConfig = loadRuntimeConfig(); const log = createLogger('App'); @@ -10,23 +11,40 @@ const log = createLogger('App'); async function main() { log.info('SnowLuma starting'); + // BridgeManager is a transport-agnostic host: it learns about live + // accounts only through registered BridgeAdapters. Today we have + // two adapters — `inject` (NTQQ in-process hook, fully wired) and + // `protocol` (future pure-protocol runtime, registered as a stub + // so the architecture is exercised end-to-end). Both must be + // registered BEFORE bridgeManager.start(). const bridgeManager = new BridgeManager(); const oneBotManager = new OneBotManager(); + const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad); - const hookManager = new HookManager({ bridgeManager, autoLoadOnDiscovery }); if (autoLoadOnDiscovery) { log.info('hook auto-load enabled: every discovered QQ process will be injected'); } + const injectAdapter = new InjectBridgeAdapter({ autoLoadOnDiscovery }); + bridgeManager.registerAdapter(injectAdapter); + bridgeManager.registerAdapter(new ProtocolBridgeAdapter()); + // OneBot subscribes to BridgeManager session events; bind before + // start() so the very first login is delivered. oneBotManager.bind(bridgeManager); + await bridgeManager.start(); + if ( (typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) || process.env.SNOWLUMA_DEV_WEBUI === '1' ) { try { const { initWebUI } = await import('./webui/server'); - await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager); + // The WebUI's process management surface is hook-specific (it + // exposes load/unload/refresh by PID); we hand it the + // adapter-owned HookManager directly. Future protocol-only + // panels would receive their adapter through the same channel. + await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, injectAdapter.hookManager); } catch (err) { log.error('Failed to start WebUI: ', err); } @@ -37,7 +55,7 @@ async function main() { const shutdown = (signal: string) => async () => { log.warn(`Shutting down (${signal})...`); oneBotManager.dispose(); - hookManager.dispose(); + await bridgeManager.dispose(); await closeLogger(); process.exit(0); }; diff --git a/packages/core/tests/bridge-member-identity.test.ts b/packages/core/tests/bridge-member-identity.test.ts index fbe3f25e..58250bfb 100644 --- a/packages/core/tests/bridge-member-identity.test.ts +++ b/packages/core/tests/bridge-member-identity.test.ts @@ -1,9 +1,9 @@ -import { describe, expect, it } from 'vitest'; -import { Bridge } from '../src/bridge/bridge'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; +import type { GroupMemberJoin, QQEventVariant } from '@snowluma/protocol/events'; import { IdentityService } from '@snowluma/protocol/identity-service'; import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info'; -import type { GroupMemberJoin, QQEventVariant } from '@snowluma/protocol/events'; -import type { PacketInfo } from '@snowluma/common/protocol-types'; +import { describe, expect, it } from 'vitest'; +import { InjectBridge } from '../src/bridge/inject-bridge'; const SELF_UIN = '10001'; const GROUP_ID = 123456789; @@ -34,11 +34,11 @@ function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo { }; } -class RefreshingBridge extends Bridge { +class RefreshingBridge extends InjectBridge { readonly memberFetches: Array<{ groupId: number; force: boolean }> = []; constructor(identity: IdentityService, private readonly refreshedMembers: GroupMemberInfo[]) { - super(identity); + super(identity.uin, identity); // `fetchGroupMemberList` moved from Bridge onto `apis.contacts` // under the #6 refactor — patch the method on the constructed // ContactsApi instance to intercept calls + record them for @@ -116,7 +116,7 @@ describe('Bridge group member identity refresh', () => { }); it('remembers UID mappings from realtime request events', () => { - const bridge = new Bridge(IdentityService.memory(SELF_UIN)); + const bridge = new InjectBridge(SELF_UIN, IdentityService.memory(SELF_UIN)); const events: QQEventVariant[] = [ { kind: 'friend_request', diff --git a/packages/core/tests/bridge-private-routing.test.ts b/packages/core/tests/bridge-private-routing.test.ts index d2b1d5fd..42e57015 100644 --- a/packages/core/tests/bridge-private-routing.test.ts +++ b/packages/core/tests/bridge-private-routing.test.ts @@ -1,8 +1,8 @@ -import { describe, expect, it, vi } from 'vitest'; -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { SendPacketResult } from '@snowluma/common/packet-sender'; import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action'; import type { FileExtra } from '@snowluma/proto-defs/message'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { describe, expect, it, vi } from 'vitest'; vi.mock('@snowluma/protocol/element-builder', () => ({ buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]), @@ -14,6 +14,8 @@ describe('Bridge private media routing', () => { const { IdentityService } = await import('@snowluma/protocol/identity-service'); class TestBridge extends Bridge { + readonly kind = 'inject' as const; + readonly id = 'inject:test'; capturedBody: Uint8Array | null = null; override async resolveUserUid(uin: number): Promise { @@ -63,6 +65,8 @@ describe('Bridge private media routing', () => { const { IdentityService } = await import('@snowluma/protocol/identity-service'); class TestBridge extends Bridge { + readonly kind = 'inject' as const; + readonly id = 'inject:test'; capturedBody: Uint8Array | null = null; override async sendRawPacket(_cmd: string, body: Uint8Array): Promise { this.capturedBody = body; diff --git a/packages/core/vitest.config.ts b/packages/core/vitest.config.ts index a7afd6b4..0a26dbab 100644 --- a/packages/core/vitest.config.ts +++ b/packages/core/vitest.config.ts @@ -1,12 +1,12 @@ -import { defineConfig } from 'vitest/config'; +import protobufVitePlugin from '@snowluma/proton/vite'; import path from 'path'; import { fileURLToPath } from 'url'; -import protobufVitePlugin from '@snowluma/proton/vite'; +import { defineConfig } from 'vitest/config'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); export default defineConfig({ - plugins: [protobufVitePlugin()], + plugins: [protobufVitePlugin({ root: path.resolve(__dirname, '../..') })], resolve: { alias: { '@': path.resolve(__dirname, 'src') diff --git a/packages/onebot/src/instance.ts b/packages/onebot/src/instance.ts index 81c5a286..92d3d3e6 100644 --- a/packages/onebot/src/instance.ts +++ b/packages/onebot/src/instance.ts @@ -38,7 +38,6 @@ export class OneBotInstance { private readonly rkeyCache: RKeyCache; private disposeEventPipeline: (() => void) | null = null; - private readonly pids = new Set(); private online = true; private heartbeatTimer: NodeJS.Timeout | null = null; private static readonly HEARTBEAT_INTERVAL = 30000; @@ -116,26 +115,6 @@ export class OneBotInstance { this.reactionStore.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); diff --git a/packages/onebot/src/manager.ts b/packages/onebot/src/manager.ts index ed52586a..8d1d7d54 100644 --- a/packages/onebot/src/manager.ts +++ b/packages/onebot/src/manager.ts @@ -51,10 +51,6 @@ export class OneBotManager { const config = loadOneBotConfig(uin, { persistDefaults: true }); const instance = new OneBotInstance(uin, bridge, config); - const activePid = bridge.activePid; - if (activePid !== null) { - instance.addPid(activePid); - } if (!bridge.identity.nickname) bridge.identity.nickname = uin; this.instances.set(uin, instance);