feat(onebot): debug subscribe seams for NetworkManager + ApiHandler
Add NetworkManager.subscribeDebug (notified for every emitEvent, before the
adapter check, so the debug stream sees events even with no adapter) and
ApiHandler.setObserver (fires after every handled action with
{action,params,response,ms}, success or failure). Both Set-based, return an
unsubscribe, and swallow subscriber throws so they never break dispatch.
OneBotInstance exposes subscribeDebugEvents / observeActions / invokeAction.
Foundation for the Wave A3 debug stream + action tester.
This commit is contained in:
@@ -81,9 +81,27 @@ export interface ApiActionContext {
|
||||
|
||||
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
|
||||
|
||||
/** A handled-action record handed to debug observers. */
|
||||
export interface ActionRecord {
|
||||
action: string;
|
||||
params: JsonObject;
|
||||
response: import('./types').ApiResponse;
|
||||
ms: number;
|
||||
}
|
||||
export type ActionObserver = (rec: ActionRecord) => void;
|
||||
|
||||
export class ApiHandler {
|
||||
private readonly handlers = new Map<string, ActionHandler>();
|
||||
private readonly log: Logger;
|
||||
/** Debug-stream taps — notified after every handled action. Attached
|
||||
* on-demand (ref-counted) by the WebUI debug stream. */
|
||||
private readonly observers = new Set<ActionObserver>();
|
||||
|
||||
/** Observe handled actions (debug). Returns an unsubscribe. */
|
||||
setObserver(cb: ActionObserver): () => void {
|
||||
this.observers.add(cb);
|
||||
return () => { this.observers.delete(cb); };
|
||||
}
|
||||
|
||||
constructor(context: ApiActionContext, uin?: number) {
|
||||
this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
@@ -132,10 +150,10 @@ export class ApiHandler {
|
||||
this.log.trace(() => [`${action} ⇐ %s`, renderParamsVerbose(params)]);
|
||||
|
||||
const startedAt = Date.now();
|
||||
let response: import('./types').ApiResponse;
|
||||
try {
|
||||
const response = await handler(params);
|
||||
response = await handler(params);
|
||||
this.log.trace(() => [`${action} ⇒ ${response.status} (${Date.now() - startedAt}ms)`]);
|
||||
return response;
|
||||
} catch (error) {
|
||||
// Action failures are almost always param-shape problems coming
|
||||
// from the OneBot client; warn (not error) is the right level so
|
||||
@@ -145,7 +163,23 @@ export class ApiHandler {
|
||||
error instanceof Error ? error.message : String(error),
|
||||
error instanceof Error ? (error.stack ?? '') : '');
|
||||
const message = error instanceof Error ? error.message : 'internal error';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
response = failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
this.notifyObservers(action, params, response, Date.now() - startedAt);
|
||||
return response;
|
||||
}
|
||||
|
||||
private notifyObservers(
|
||||
action: string,
|
||||
params: JsonObject,
|
||||
response: import('./types').ApiResponse,
|
||||
ms: number,
|
||||
): void {
|
||||
if (!this.observers.size) return;
|
||||
for (const cb of this.observers) {
|
||||
try { cb({ action, params, response, ms }); } catch (err) {
|
||||
this.log.warn('action observer error: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/protocol/format';
|
||||
import path from 'path';
|
||||
import { ApiHandler } from './api-handler';
|
||||
import { ApiHandler, type ActionObserver } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import { registerEventPipeline } from './event-pipeline';
|
||||
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
type NetworkAdapterContext,
|
||||
} from './network';
|
||||
import { ReactionStore } from './reaction-store';
|
||||
import type { JsonObject, JsonValue, MessageMeta, NetworkBase, OneBotConfig } from './types';
|
||||
import type { ApiResponse, JsonObject, JsonValue, MessageMeta, NetworkBase, OneBotConfig } from './types';
|
||||
|
||||
const moduleLog = createLogger('Event');
|
||||
|
||||
@@ -59,6 +59,20 @@ export class OneBotInstance {
|
||||
return this.networkManager.describeStatuses();
|
||||
}
|
||||
|
||||
// ── Debug taps (WebUI debug stream / tester) ──
|
||||
/** Tap every emitted OneBot event for this account. Returns an unsubscribe. */
|
||||
subscribeDebugEvents(cb: (event: JsonObject) => void): () => void {
|
||||
return this.networkManager.subscribeDebug(cb);
|
||||
}
|
||||
/** Observe every handled action for this account. Returns an unsubscribe. */
|
||||
observeActions(cb: ActionObserver): () => void {
|
||||
return this.apiHandler.setObserver(cb);
|
||||
}
|
||||
/** Invoke an OneBot action against this account (debug tester). */
|
||||
invokeAction(action: string, params: JsonObject): Promise<ApiResponse> {
|
||||
return this.apiHandler.handle(action, params);
|
||||
}
|
||||
|
||||
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
|
||||
this.uin = uin;
|
||||
this.bridge = bridge;
|
||||
|
||||
@@ -9,6 +9,14 @@ type AnyAdapter = IOneBotNetworkAdapter<NetworkBase>;
|
||||
|
||||
export class OneBotNetworkManager {
|
||||
private readonly adapters = new Map<string, AnyAdapter>();
|
||||
/** Debug-stream taps — notified for every emitted event regardless of adapter
|
||||
* state. Attached on-demand (ref-counted) by the WebUI debug stream. */
|
||||
private readonly debugSubscribers = new Set<(event: JsonObject) => void>();
|
||||
|
||||
subscribeDebug(cb: (event: JsonObject) => void): () => void {
|
||||
this.debugSubscribers.add(cb);
|
||||
return () => { this.debugSubscribers.delete(cb); };
|
||||
}
|
||||
|
||||
register<C extends NetworkBase>(adapter: IOneBotNetworkAdapter<C>): void {
|
||||
const existing = this.adapters.get(adapter.name);
|
||||
@@ -75,6 +83,14 @@ export class OneBotNetworkManager {
|
||||
}
|
||||
|
||||
async emitEvent(event: JsonObject): Promise<void> {
|
||||
// Notify debug taps first — before the adapter check — so the debug stream
|
||||
// sees every event even when no adapter is connected. Never let a tap throw
|
||||
// into the dispatch path.
|
||||
if (this.debugSubscribers.size) {
|
||||
for (const cb of this.debugSubscribers) {
|
||||
try { cb(event); } catch (err) { log.warn('debug subscriber error: %s', errMessage(err)); }
|
||||
}
|
||||
}
|
||||
if (!this.hasActiveAdapters()) return;
|
||||
const payload = buildDispatchPayload(event);
|
||||
const tasks: Promise<unknown>[] = [];
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { OneBotNetworkManager } from '../src/network/network-manager';
|
||||
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
|
||||
|
||||
// ApiHandler's register* only define handlers (closures) at construction — they
|
||||
// don't touch ctx — so a throwing proxy is a safe minimal context.
|
||||
function fakeCtx(): ApiActionContext {
|
||||
return new Proxy({} as ApiActionContext, {
|
||||
get(_t, prop) { throw new Error(`ctx.${String(prop)} not stubbed`); },
|
||||
});
|
||||
}
|
||||
|
||||
describe('OneBotNetworkManager.subscribeDebug', () => {
|
||||
it('notifies debug subscribers on emitEvent even with no active adapters', async () => {
|
||||
const nm = new OneBotNetworkManager();
|
||||
const seen: unknown[] = [];
|
||||
nm.subscribeDebug((e) => seen.push(e));
|
||||
await nm.emitEvent({ post_type: 'meta_event', x: 1 });
|
||||
expect(seen).toEqual([{ post_type: 'meta_event', x: 1 }]);
|
||||
});
|
||||
|
||||
it('stops notifying after unsubscribe', async () => {
|
||||
const nm = new OneBotNetworkManager();
|
||||
const cb = vi.fn();
|
||||
const off = nm.subscribeDebug(cb);
|
||||
await nm.emitEvent({ a: 1 });
|
||||
off();
|
||||
await nm.emitEvent({ a: 2 });
|
||||
expect(cb).toHaveBeenCalledTimes(1);
|
||||
expect(cb).toHaveBeenCalledWith({ a: 1 });
|
||||
});
|
||||
|
||||
it('a throwing subscriber does not break emitEvent', async () => {
|
||||
const nm = new OneBotNetworkManager();
|
||||
nm.subscribeDebug(() => { throw new Error('boom'); });
|
||||
await expect(nm.emitEvent({ a: 1 })).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ApiHandler.setObserver', () => {
|
||||
it('fires after a successful action with {action, params, response, ms}', async () => {
|
||||
const h = new ApiHandler(fakeCtx());
|
||||
h.registerAction('ping', async () => ({ status: 'ok', retcode: 0, data: 'pong' }));
|
||||
const recs: Array<{ action: string; response: { status: string } }> = [];
|
||||
h.setObserver((r) => recs.push(r as any));
|
||||
const res = await h.handle('ping', { x: 1 });
|
||||
expect(res).toMatchObject({ status: 'ok', data: 'pong' });
|
||||
expect(recs).toHaveLength(1);
|
||||
expect(recs[0]).toMatchObject({ action: 'ping', params: { x: 1 }, response: { status: 'ok' } });
|
||||
expect(typeof (recs[0] as any).ms).toBe('number');
|
||||
});
|
||||
|
||||
it('fires on a thrown action with the failure response', async () => {
|
||||
const h = new ApiHandler(fakeCtx());
|
||||
h.registerAction('boom', async () => { throw new Error('kaboom'); });
|
||||
const recs: any[] = [];
|
||||
h.setObserver((r) => recs.push(r));
|
||||
await h.handle('boom', {});
|
||||
expect(recs).toHaveLength(1);
|
||||
expect(recs[0].response.status).toBe('failed');
|
||||
});
|
||||
|
||||
it('unsubscribe stops observation', async () => {
|
||||
const h = new ApiHandler(fakeCtx());
|
||||
h.registerAction('ping', async () => ({ status: 'ok', retcode: 0 }));
|
||||
const cb = vi.fn();
|
||||
const off = h.setObserver(cb);
|
||||
await h.handle('ping', {});
|
||||
off();
|
||||
await h.handle('ping', {});
|
||||
expect(cb).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('a throwing observer does not break handle', async () => {
|
||||
const h = new ApiHandler(fakeCtx());
|
||||
h.registerAction('ping', async () => ({ status: 'ok', retcode: 0 }));
|
||||
h.setObserver(() => { throw new Error('observer boom'); });
|
||||
await expect(h.handle('ping', {})).resolves.toMatchObject({ status: 'ok' });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user