feat(core): wire HookManager/BridgeManager edges into the StateBus
Phase 2 of switching processes/qq-list/connections from REST polling to SSE push. Sinks the three publisher edges into a fresh StateBus: - HookManager grows an OPTIONAL `onSessionsChanged: () => void` dep; called from pipe-watcher process-discovered/process-gone and from the previously unsubscribed HookSession 'status-changed' event (login/disconnected reach it transitively via applyStatus, so a single subscription covers every transition the WebUI processes view cares about). Throwing subscribers are caught + logged so the watcher loop is never aborted. - New packages/core/src/webui/state-wiring.ts owns the coupling: produces the bus + the `onSessionsChanged` callback to feed HookManager, and registers BridgeManager session-started / session-closed listeners that publish 'qq-list' + 'connections' (in source-of-truth order: account first, then adapters). - index.ts threads stateWiring.bus into initWebUI so the phase-3 SSE handler has something to subscribe to; dispose runs on SIGINT/SIGTERM. Bridge: 62/62 (was 57). Core: 419/419 (was 414). 10 new tests cover all publish points + exception isolation + the optional-dep contract.
This commit is contained in:
6 files changed
+376
-2
No files matched your search
@@ -49,6 +49,13 @@ export type HookManagerDeps = {
|
|||||||
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
|
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
|
||||||
* Failed loads are logged and leave the session in the 'error' state. */
|
* Failed loads are logged and leave the session in the 'error' state. */
|
||||||
autoLoadOnDiscovery?: boolean;
|
autoLoadOnDiscovery?: boolean;
|
||||||
|
/** Optional hook fired whenever the set of HookProcessInfo observable to
|
||||||
|
* `listProcesses()` changes — new process discovered, process gone, or
|
||||||
|
* any session's status mutated. Used by the WebUI SSE wiring to push a
|
||||||
|
* fresh processes snapshot to connected clients without REST polling.
|
||||||
|
* Exceptions thrown by the callback are caught and logged; they do not
|
||||||
|
* break the watcher / session event loops. */
|
||||||
|
onSessionsChanged?: () => void;
|
||||||
log?: Logger;
|
log?: Logger;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -76,6 +83,7 @@ export class HookManager {
|
|||||||
private readonly ownsPipeWatcher: boolean;
|
private readonly ownsPipeWatcher: boolean;
|
||||||
private readonly listProcessesNative: () => HookProcessBaseInfo[];
|
private readonly listProcessesNative: () => HookProcessBaseInfo[];
|
||||||
private readonly autoLoadOnDiscovery: boolean;
|
private readonly autoLoadOnDiscovery: boolean;
|
||||||
|
private readonly onSessionsChangedRaw?: () => void;
|
||||||
private readonly log: Logger;
|
private readonly log: Logger;
|
||||||
private readonly sessions = new Map<number, HookSession>();
|
private readonly sessions = new Map<number, HookSession>();
|
||||||
private readonly startPromise: Promise<void>;
|
private readonly startPromise: Promise<void>;
|
||||||
@@ -85,6 +93,7 @@ export class HookManager {
|
|||||||
constructor(deps: HookManagerDeps) {
|
constructor(deps: HookManagerDeps) {
|
||||||
this.bridgeManager = deps.bridgeManager;
|
this.bridgeManager = deps.bridgeManager;
|
||||||
this.onPacket = deps.onPacket ?? ((pkt) => deps.bridgeManager.onPacket(pkt));
|
this.onPacket = deps.onPacket ?? ((pkt) => deps.bridgeManager.onPacket(pkt));
|
||||||
|
this.onSessionsChangedRaw = deps.onSessionsChanged;
|
||||||
this.log = deps.log ?? createLogger('Hook');
|
this.log = deps.log ?? createLogger('Hook');
|
||||||
|
|
||||||
this.injector = deps.injector ?? {
|
this.injector = deps.injector ?? {
|
||||||
@@ -193,11 +202,13 @@ export class HookManager {
|
|||||||
this.log.warn('auto-load failed: PID=%d err=%s', info.pid, errMsg(err));
|
this.log.warn('auto-load failed: PID=%d err=%s', info.pid, errMsg(err));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
this.notifySessionsChanged();
|
||||||
});
|
});
|
||||||
this.pipeWatcher.on('process-gone', (pid: number) => {
|
this.pipeWatcher.on('process-gone', (pid: number) => {
|
||||||
if (this.disposed) return;
|
if (this.disposed) return;
|
||||||
const session = this.sessions.get(pid);
|
const session = this.sessions.get(pid);
|
||||||
if (session) session.notifyProcessGone();
|
if (session) session.notifyProcessGone();
|
||||||
|
this.notifySessionsChanged();
|
||||||
});
|
});
|
||||||
this.pipeWatcher.on('pipe-up', (pid: number) => {
|
this.pipeWatcher.on('pipe-up', (pid: number) => {
|
||||||
if (this.disposed) return;
|
if (this.disposed) return;
|
||||||
@@ -253,6 +264,12 @@ export class HookManager {
|
|||||||
session.on('disconnected', (wasLoggedIn: boolean) => {
|
session.on('disconnected', (wasLoggedIn: boolean) => {
|
||||||
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
||||||
});
|
});
|
||||||
|
// status-changed fires on EVERY internal status mutation, including the
|
||||||
|
// ones reached via login / disconnected / refresh — subscribing here
|
||||||
|
// alone covers every transition the WebUI processes view cares about.
|
||||||
|
session.on('status-changed', () => {
|
||||||
|
this.notifySessionsChanged();
|
||||||
|
});
|
||||||
session.on('disposed', () => {
|
session.on('disposed', () => {
|
||||||
this.sessions.delete(pid);
|
this.sessions.delete(pid);
|
||||||
});
|
});
|
||||||
@@ -261,6 +278,19 @@ export class HookManager {
|
|||||||
return session;
|
return session;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Fire the optional sessions-changed hook with exceptions isolated.
|
||||||
|
* A throwing subscriber must not abort the watcher's emit loop or break
|
||||||
|
* a HookSession event handler in flight. */
|
||||||
|
private notifySessionsChanged(): void {
|
||||||
|
if (this.disposed) return;
|
||||||
|
if (!this.onSessionsChangedRaw) return;
|
||||||
|
try {
|
||||||
|
this.onSessionsChangedRaw();
|
||||||
|
} catch (err) {
|
||||||
|
this.log.warn('onSessionsChanged threw: %s', errMsg(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private assertValidPid(pid: number): void {
|
private assertValidPid(pid: number): void {
|
||||||
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
|
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,173 @@
|
|||||||
|
import { describe, it, expect, vi } from 'vitest';
|
||||||
|
import { EventEmitter } from 'events';
|
||||||
|
import { HookManager } from '../src/hook-manager';
|
||||||
|
import { PipeWatcher } from '../src/pipe-watcher';
|
||||||
|
import type { ManualMapHandle } from '../src/injector';
|
||||||
|
import type { BridgeManagerSink } from '../src/hook-manager';
|
||||||
|
import type { QqHookClient } from '../src/qq-hook-client';
|
||||||
|
|
||||||
|
// Regression cover for the WebUI SSE wiring: HookManager must call its
|
||||||
|
// optional `onSessionsChanged` callback every time the observable set of
|
||||||
|
// HookProcessInfo (what `listProcesses()` would return) changes, so the
|
||||||
|
// /api/state/stream handler can push a fresh processes snapshot to the
|
||||||
|
// browser without REST polling.
|
||||||
|
|
||||||
|
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||||
|
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||||
|
|
||||||
|
interface Harness {
|
||||||
|
manager: HookManager;
|
||||||
|
pipeWatcher: PipeWatcher;
|
||||||
|
setProcesses: (next: number[]) => void;
|
||||||
|
setLivePipes: (next: number[]) => void;
|
||||||
|
onSessionsChanged: ReturnType<typeof vi.fn>;
|
||||||
|
clientFactory: ReturnType<typeof vi.fn>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}): Harness {
|
||||||
|
let pids = opts.processes ?? [];
|
||||||
|
let live = new Set<number>(opts.livePipes ?? []);
|
||||||
|
const pipeWatcher = new PipeWatcher({
|
||||||
|
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||||
|
listLivePipes: async () => new Set(live),
|
||||||
|
intervalMs: 60_000,
|
||||||
|
});
|
||||||
|
const clientFactory = vi.fn(() => {
|
||||||
|
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
|
||||||
|
(c as any).isClosed = false;
|
||||||
|
(c as any).isLoggedIn = false;
|
||||||
|
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||||
|
(c as any).connectAll = async () => { /* succeed without doing anything */ };
|
||||||
|
(c as any).close = () => { (c as any).isClosed = true; };
|
||||||
|
return c as unknown as QqHookClient;
|
||||||
|
});
|
||||||
|
const bridgeManager = {
|
||||||
|
onPacket: vi.fn(),
|
||||||
|
onHookLogin: vi.fn(),
|
||||||
|
onPidDisconnected: vi.fn(),
|
||||||
|
} as unknown as BridgeManagerSink;
|
||||||
|
const onSessionsChanged = vi.fn();
|
||||||
|
const manager = new HookManager({
|
||||||
|
bridgeManager,
|
||||||
|
pipeWatcher,
|
||||||
|
injector: {
|
||||||
|
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||||
|
unload: vi.fn(),
|
||||||
|
},
|
||||||
|
makeClient: clientFactory,
|
||||||
|
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||||
|
onSessionsChanged,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
manager,
|
||||||
|
pipeWatcher,
|
||||||
|
onSessionsChanged,
|
||||||
|
clientFactory,
|
||||||
|
setProcesses: (next) => { pids = next; },
|
||||||
|
setLivePipes: (next) => { live = new Set(next); },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('HookManager.onSessionsChanged', () => {
|
||||||
|
it('fires when the watcher discovers a new QQ process', async () => {
|
||||||
|
const ctx = makeManager({ processes: [] });
|
||||||
|
await ctx.pipeWatcher.start();
|
||||||
|
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
ctx.setProcesses([4242]);
|
||||||
|
await ctx.pipeWatcher.tickNow();
|
||||||
|
await flush();
|
||||||
|
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||||
|
|
||||||
|
ctx.manager.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fires when the watcher reports a process is gone', async () => {
|
||||||
|
const ctx = makeManager({ processes: [4242] });
|
||||||
|
await ctx.pipeWatcher.start();
|
||||||
|
await flush();
|
||||||
|
ctx.onSessionsChanged.mockClear();
|
||||||
|
|
||||||
|
ctx.setProcesses([]);
|
||||||
|
await ctx.pipeWatcher.tickNow();
|
||||||
|
await flush();
|
||||||
|
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||||
|
|
||||||
|
ctx.manager.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fires when the watcher reports the pipe came up (status: connecting → loaded)', async () => {
|
||||||
|
const ctx = makeManager({ processes: [4242] });
|
||||||
|
await ctx.pipeWatcher.start();
|
||||||
|
await flush();
|
||||||
|
// Inject so the session is in 'connecting' state; the next pipe-up
|
||||||
|
// makes attemptConnect succeed and status flips to 'loaded'.
|
||||||
|
await ctx.manager.loadProcess(4242);
|
||||||
|
await flush();
|
||||||
|
ctx.onSessionsChanged.mockClear();
|
||||||
|
|
||||||
|
ctx.setLivePipes([4242]);
|
||||||
|
await ctx.pipeWatcher.tickNow();
|
||||||
|
await flush();
|
||||||
|
await flush();
|
||||||
|
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||||
|
|
||||||
|
ctx.manager.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('survives a throwing onSessionsChanged callback — the watcher loop keeps running', async () => {
|
||||||
|
const ctx = makeManager({ processes: [] });
|
||||||
|
ctx.onSessionsChanged.mockImplementation(() => { throw new Error('listener boom'); });
|
||||||
|
await ctx.pipeWatcher.start();
|
||||||
|
ctx.setProcesses([4242]);
|
||||||
|
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
|
||||||
|
await flush();
|
||||||
|
// A second tick still fires the callback — it wasn't unregistered by
|
||||||
|
// the prior throw.
|
||||||
|
ctx.onSessionsChanged.mockClear();
|
||||||
|
ctx.setProcesses([4242, 5555]);
|
||||||
|
await ctx.pipeWatcher.tickNow();
|
||||||
|
await flush();
|
||||||
|
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||||
|
|
||||||
|
ctx.manager.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is OPTIONAL — omitting it leaves the manager fully functional', async () => {
|
||||||
|
const pids = [4242];
|
||||||
|
const pipeWatcher = new PipeWatcher({
|
||||||
|
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||||
|
listLivePipes: async () => new Set(),
|
||||||
|
intervalMs: 60_000,
|
||||||
|
});
|
||||||
|
const manager = new HookManager({
|
||||||
|
bridgeManager: {
|
||||||
|
onPacket: vi.fn(),
|
||||||
|
onHookLogin: vi.fn(),
|
||||||
|
onPidDisconnected: vi.fn(),
|
||||||
|
} as unknown as BridgeManagerSink,
|
||||||
|
pipeWatcher,
|
||||||
|
injector: {
|
||||||
|
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||||
|
unload: vi.fn(),
|
||||||
|
},
|
||||||
|
makeClient: vi.fn(() => {
|
||||||
|
const c = new EventEmitter() as any;
|
||||||
|
c.isClosed = false; c.isLoggedIn = false;
|
||||||
|
c.getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||||
|
c.connectAll = async () => undefined;
|
||||||
|
c.close = () => { c.isClosed = true; };
|
||||||
|
return c;
|
||||||
|
}),
|
||||||
|
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||||
|
// onSessionsChanged deliberately omitted
|
||||||
|
});
|
||||||
|
await pipeWatcher.start();
|
||||||
|
await pipeWatcher.tickNow();
|
||||||
|
await flush();
|
||||||
|
const list = await manager.listProcesses();
|
||||||
|
expect(list).toHaveLength(1);
|
||||||
|
expect(list[0].pid).toBe(4242);
|
||||||
|
manager.dispose();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,6 +4,7 @@ import { loadRuntimeConfig } from '@snowluma/common/runtime';
|
|||||||
import { OneBotManager } from '@snowluma/onebot/manager';
|
import { OneBotManager } from '@snowluma/onebot/manager';
|
||||||
import { BridgeManager } from './bridge/manager';
|
import { BridgeManager } from './bridge/manager';
|
||||||
import { createNotificationManager } from './notifications/manager';
|
import { createNotificationManager } from './notifications/manager';
|
||||||
|
import { createStateWiring } from './webui/state-wiring';
|
||||||
|
|
||||||
const runtimeConfig = loadRuntimeConfig();
|
const runtimeConfig = loadRuntimeConfig();
|
||||||
const log = createLogger('App');
|
const log = createLogger('App');
|
||||||
@@ -30,12 +31,22 @@ async function main() {
|
|||||||
const bridgeManager = new BridgeManager();
|
const bridgeManager = new BridgeManager();
|
||||||
const oneBotManager = new OneBotManager();
|
const oneBotManager = new OneBotManager();
|
||||||
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
|
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
|
||||||
const hookManager = new HookManager({ bridgeManager, autoLoadOnDiscovery });
|
|
||||||
|
// WebUI state-push wiring: HookManager + BridgeManager edges publish
|
||||||
|
// `processes` / `qq-list` / `connections` invalidations into a bus the
|
||||||
|
// /api/state/stream SSE handler subscribes to (no REST polling required).
|
||||||
|
const stateWiring = createStateWiring();
|
||||||
|
const hookManager = new HookManager({
|
||||||
|
bridgeManager,
|
||||||
|
autoLoadOnDiscovery,
|
||||||
|
onSessionsChanged: stateWiring.onSessionsChanged,
|
||||||
|
});
|
||||||
if (autoLoadOnDiscovery) {
|
if (autoLoadOnDiscovery) {
|
||||||
log.info('hook auto-load enabled: every discovered QQ process will be injected');
|
log.info('hook auto-load enabled: every discovered QQ process will be injected');
|
||||||
}
|
}
|
||||||
|
|
||||||
oneBotManager.bind(bridgeManager);
|
oneBotManager.bind(bridgeManager);
|
||||||
|
stateWiring.bindBridgeManager(bridgeManager);
|
||||||
|
|
||||||
// Global notification subsystem (account up/down → webhook). Bound AFTER
|
// Global notification subsystem (account up/down → webhook). Bound AFTER
|
||||||
// OneBotManager so the nickname fallback is already populated when it observes.
|
// OneBotManager so the nickname fallback is already populated when it observes.
|
||||||
@@ -52,6 +63,7 @@ async function main() {
|
|||||||
host: runtimeConfig.webuiHost,
|
host: runtimeConfig.webuiHost,
|
||||||
tlsEnabled: runtimeConfig.webuiTls?.enabled,
|
tlsEnabled: runtimeConfig.webuiTls?.enabled,
|
||||||
trustProxy: runtimeConfig.trustProxy,
|
trustProxy: runtimeConfig.trustProxy,
|
||||||
|
stateBus: stateWiring.bus,
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log.error('Failed to start WebUI: ', err);
|
log.error('Failed to start WebUI: ', err);
|
||||||
@@ -65,6 +77,7 @@ async function main() {
|
|||||||
oneBotManager.dispose();
|
oneBotManager.dispose();
|
||||||
notificationManager.dispose();
|
notificationManager.dispose();
|
||||||
hookManager.dispose();
|
hookManager.dispose();
|
||||||
|
stateWiring.dispose();
|
||||||
await closeLogger();
|
await closeLogger();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -313,7 +313,10 @@ export async function initWebUI(
|
|||||||
oneBotManager: OneBotManager,
|
oneBotManager: OneBotManager,
|
||||||
hookManager?: HookManager,
|
hookManager?: HookManager,
|
||||||
notificationManager?: NotificationManager,
|
notificationManager?: NotificationManager,
|
||||||
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string } = {},
|
// `stateBus` is consumed in phase 3 by the /api/state/stream handler.
|
||||||
|
// Threading it through here in phase 2 so the wiring in index.ts can stay
|
||||||
|
// committed independently of the SSE endpoint.
|
||||||
|
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string; stateBus?: import('./state-bus').StateBus } = {},
|
||||||
): Promise<{ port: number }> {
|
): Promise<{ port: number }> {
|
||||||
// Resolve the client IP for per-IP rate limiting from the configured
|
// Resolve the client IP for per-IP rate limiting from the configured
|
||||||
// trust-proxy directive (runtime.json `trustProxy`, env-overridable via
|
// trust-proxy directive (runtime.json `trustProxy`, env-overridable via
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
/**
|
||||||
|
* State-wiring — couples the publisher edges (HookManager session events,
|
||||||
|
* BridgeManager session-started / session-closed) to a fresh StateBus so the
|
||||||
|
* `/api/state/stream` SSE handler can push snapshot invalidations to the
|
||||||
|
* WebUI without REST polling.
|
||||||
|
*
|
||||||
|
* Decoupling rationale:
|
||||||
|
* - HookManager owns the per-process state-machine; it knows when a
|
||||||
|
* session's `listProcesses()` view changes. We feed it `onSessionsChanged`
|
||||||
|
* (callable from outside the bridge package) so this file is the ONLY
|
||||||
|
* place that imports both the bus and HookManager's dep shape.
|
||||||
|
* - BridgeManager fires `session-started` / `session-closed` listeners on
|
||||||
|
* account edges (the OneBot instance list mutates around these). We add
|
||||||
|
* listeners directly so `qq-list` + `connections` invalidate at the right
|
||||||
|
* moment without modifying BridgeManager.
|
||||||
|
*
|
||||||
|
* `dispose()` unwires everything so a test (or a future hot-reload) can
|
||||||
|
* recreate the wiring without leaking listeners.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { StateBus } from './state-bus';
|
||||||
|
import type { BridgeManager } from '../bridge/manager';
|
||||||
|
|
||||||
|
export interface StateWiring {
|
||||||
|
/** The bus the SSE handler subscribes to. */
|
||||||
|
readonly bus: StateBus;
|
||||||
|
/** Pass as the HookManager `onSessionsChanged` dep — publishes 'processes'. */
|
||||||
|
onSessionsChanged: () => void;
|
||||||
|
/** Hook into a BridgeManager so its session edges publish 'qq-list' and
|
||||||
|
* 'connections'. Can be called at most once per wiring (subsequent calls
|
||||||
|
* add duplicate listeners). */
|
||||||
|
bindBridgeManager(bm: BridgeManager): void;
|
||||||
|
/** Drop every listener + neuter the bus so further publishes do nothing. */
|
||||||
|
dispose(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createStateWiring(): StateWiring {
|
||||||
|
const bus = new StateBus();
|
||||||
|
let disposed = false;
|
||||||
|
|
||||||
|
const publish = (resource: Parameters<StateBus['publish']>[0]): void => {
|
||||||
|
if (disposed) return;
|
||||||
|
bus.publish(resource);
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
bus,
|
||||||
|
onSessionsChanged: () => publish('processes'),
|
||||||
|
bindBridgeManager(bm: BridgeManager): void {
|
||||||
|
// Account appeared: the qq-list response gains an entry and the
|
||||||
|
// connections response gains the new account's adapter row. Two
|
||||||
|
// distinct resource invalidations, in source-of-truth order
|
||||||
|
// (account exists → only then can adapters be enumerated for it).
|
||||||
|
bm.addSessionStartedListener(() => {
|
||||||
|
publish('qq-list');
|
||||||
|
publish('connections');
|
||||||
|
});
|
||||||
|
// Account disappeared: same two resources shrink, same order so a
|
||||||
|
// racy WebUI receiving both events independently sees the qq-list
|
||||||
|
// shrink before it tries to render connections for a uin that's
|
||||||
|
// about to vanish.
|
||||||
|
bm.addSessionClosedListener(() => {
|
||||||
|
publish('qq-list');
|
||||||
|
publish('connections');
|
||||||
|
});
|
||||||
|
},
|
||||||
|
dispose(): void {
|
||||||
|
if (disposed) return;
|
||||||
|
disposed = true;
|
||||||
|
bus.dispose();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import { StateBus } from '../src/webui/state-bus';
|
||||||
|
import { createStateWiring } from '../src/webui/state-wiring';
|
||||||
|
import { BridgeManager } from '../src/bridge/manager';
|
||||||
|
|
||||||
|
describe('createStateWiring', () => {
|
||||||
|
it('provides a fresh StateBus and an onSessionsChanged that publishes "processes"', () => {
|
||||||
|
const wiring = createStateWiring();
|
||||||
|
expect(wiring.bus).toBeInstanceOf(StateBus);
|
||||||
|
const sub = vi.fn();
|
||||||
|
wiring.bus.subscribe(sub);
|
||||||
|
wiring.onSessionsChanged();
|
||||||
|
expect(sub).toHaveBeenCalledExactlyOnceWith('processes');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('binds a BridgeManager so session-started publishes both "qq-list" and "connections"', () => {
|
||||||
|
const wiring = createStateWiring();
|
||||||
|
const bm = new BridgeManager();
|
||||||
|
wiring.bindBridgeManager(bm);
|
||||||
|
const seen: string[] = [];
|
||||||
|
wiring.bus.subscribe((r) => seen.push(r));
|
||||||
|
|
||||||
|
// Real onHookLogin path — fires the session-started listener internally
|
||||||
|
// exactly once (per uin).
|
||||||
|
bm.onHookLogin(4242, '12345', {} as never);
|
||||||
|
expect(seen).toEqual(['qq-list', 'connections']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('publishes "qq-list" + "connections" on session-closed', () => {
|
||||||
|
const wiring = createStateWiring();
|
||||||
|
const bm = new BridgeManager();
|
||||||
|
wiring.bindBridgeManager(bm);
|
||||||
|
bm.onHookLogin(4242, '12345', {} as never);
|
||||||
|
const sub = vi.fn();
|
||||||
|
wiring.bus.subscribe(sub);
|
||||||
|
|
||||||
|
bm.onPidDisconnected(4242);
|
||||||
|
|
||||||
|
// Order is qq-list first (account list shrinks) then connections
|
||||||
|
// (adapter status list shrinks). Two distinct resource invalidations.
|
||||||
|
expect(sub).toHaveBeenCalledTimes(2);
|
||||||
|
expect(sub).toHaveBeenNthCalledWith(1, 'qq-list');
|
||||||
|
expect(sub).toHaveBeenNthCalledWith(2, 'connections');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dispose() unwires onSessionsChanged + BridgeManager listeners (no further publishes)', () => {
|
||||||
|
const wiring = createStateWiring();
|
||||||
|
const bm = new BridgeManager();
|
||||||
|
wiring.bindBridgeManager(bm);
|
||||||
|
const sub = vi.fn();
|
||||||
|
wiring.bus.subscribe(sub);
|
||||||
|
|
||||||
|
wiring.dispose();
|
||||||
|
|
||||||
|
// onSessionsChanged becomes a no-op.
|
||||||
|
wiring.onSessionsChanged();
|
||||||
|
expect(sub).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
// BridgeManager listener fires nothing into a disposed bus.
|
||||||
|
bm.onHookLogin(4242, '12345', {} as never);
|
||||||
|
expect(sub).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('survives a BridgeManager listener throw — the OTHER listeners on the same BridgeManager keep working', () => {
|
||||||
|
const wiring = createStateWiring();
|
||||||
|
const bm = new BridgeManager();
|
||||||
|
wiring.bindBridgeManager(bm);
|
||||||
|
|
||||||
|
// A peer subscriber (e.g. OneBotManager) added AFTER state-wiring throws.
|
||||||
|
const peer = vi.fn(() => { throw new Error('peer down'); });
|
||||||
|
bm.addSessionStartedListener(peer);
|
||||||
|
|
||||||
|
const sub = vi.fn();
|
||||||
|
wiring.bus.subscribe(sub);
|
||||||
|
|
||||||
|
expect(() => bm.onHookLogin(4242, '12345', {} as never)).not.toThrow();
|
||||||
|
// The state-wiring listener still ran (BridgeManager isolates exceptions
|
||||||
|
// per listener).
|
||||||
|
expect(sub).toHaveBeenCalledWith('qq-list');
|
||||||
|
expect(sub).toHaveBeenCalledWith('connections');
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user