refactor: clarify async state and subscription ownership
This commit is contained in:
1 parent
f6ca9d5f65
commit
c54aeffc77
20 files changed
+698
-316
No files matched your search
@@ -58,23 +58,31 @@ export class BridgeManager {
|
||||
);
|
||||
}
|
||||
|
||||
private sessionStartedListeners_: SessionStartedCallback[] = [];
|
||||
private sessionClosedListeners_: SessionClosedCallback[] = [];
|
||||
private readonly sessionStartedListeners_ = new Set<SessionStartedCallback>();
|
||||
private readonly sessionClosedListeners_ = new Set<SessionClosedCallback>();
|
||||
|
||||
/** Additive subscription: every observer (OneBotManager, NotificationManager,
|
||||
* …) receives every session edge. (Was a single `set*Callback` setter —
|
||||
* converted to N listeners so a second observer can't clobber the first.)
|
||||
* The close edge carries the final detached PID and the bridge so observers
|
||||
* can identify the process and read its nickname before disposal. */
|
||||
addSessionStartedListener(cb: SessionStartedCallback): void {
|
||||
this.sessionStartedListeners_.push(cb);
|
||||
/** Each subscription has an independent, idempotent unsubscribe handle. */
|
||||
addSessionStartedListener(cb: SessionStartedCallback): () => void {
|
||||
const listener: SessionStartedCallback = (...args) => cb(...args);
|
||||
this.sessionStartedListeners_.add(listener);
|
||||
|
||||
return () => {
|
||||
this.sessionStartedListeners_.delete(listener);
|
||||
};
|
||||
}
|
||||
addSessionClosedListener(cb: SessionClosedCallback): void {
|
||||
this.sessionClosedListeners_.push(cb);
|
||||
|
||||
/** The close edge includes the final PID and bridge before disposal. */
|
||||
addSessionClosedListener(cb: SessionClosedCallback): () => void {
|
||||
const listener: SessionClosedCallback = (...args) => cb(...args);
|
||||
this.sessionClosedListeners_.add(listener);
|
||||
|
||||
return () => {
|
||||
this.sessionClosedListeners_.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
private fireSessionStarted(uin: string, bridge: Bridge): void {
|
||||
for (const cb of this.sessionStartedListeners_) {
|
||||
for (const cb of [...this.sessionStartedListeners_]) {
|
||||
try {
|
||||
cb(uin, bridge);
|
||||
} catch (err) {
|
||||
@@ -87,7 +95,7 @@ export class BridgeManager {
|
||||
}
|
||||
|
||||
private fireSessionClosed(uin: string, bridge: Bridge, pid: number): void {
|
||||
for (const cb of this.sessionClosedListeners_) {
|
||||
for (const cb of [...this.sessionClosedListeners_]) {
|
||||
try {
|
||||
cb(uin, bridge, pid);
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,21 +1,6 @@
|
||||
/**
|
||||
* StateBus — pure pub/sub for WebUI state-resource invalidations.
|
||||
*
|
||||
* Three resources are tracked: `processes`, `qq-list`, `connections`. A
|
||||
* publisher (HookSession status change, BridgeManager session start/close,
|
||||
* the connection-status diff loop) calls `publish(resource)` to signal "the
|
||||
* snapshot for THIS resource is stale; whoever cares should re-read". The
|
||||
* `/api/state/stream` SSE handler subscribes, debounces, and pushes fresh
|
||||
* snapshots to connected WebUI clients.
|
||||
*
|
||||
* Intentionally pure pub/sub (no debounce, no snapshot caching): debounce
|
||||
* and snapshot reads live with the subscriber so different consumers can
|
||||
* coalesce on different cadences. Snapshot semantics on fan-out: the
|
||||
* subscriber set is FROZEN at the start of each publish, so a listener
|
||||
* that subscribes during the fan-out only sees the FOLLOWING publish, and
|
||||
* a listener that unsubscribes mid-fan-out does not prevent its peers
|
||||
* from completing.
|
||||
*/
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
|
||||
const log = createLogger('WebUI.State');
|
||||
|
||||
export type StateResource = 'processes' | 'qq-list' | 'connections';
|
||||
|
||||
@@ -54,18 +39,17 @@ export class StateBus {
|
||||
return;
|
||||
}
|
||||
|
||||
// Snapshot the current subscribers — any subscribe()/unsubscribe()
|
||||
// called by a listener during the fan-out takes effect only for the
|
||||
// NEXT publish, not this one.
|
||||
const snapshot = [...this.listeners];
|
||||
|
||||
for (const fn of snapshot) {
|
||||
try {
|
||||
fn(resource);
|
||||
} catch {
|
||||
// Subscriber-internal failure is its own problem. The bus's job
|
||||
// is to keep delivery moving — surfacing an error here would
|
||||
// partially abort the fan-out and create skip-the-listener bugs.
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
'state listener failed: resource=%s error=%s',
|
||||
resource,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,3 @@
|
||||
/**
|
||||
* 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()` sets a latch and neuters the bus. BridgeManager listeners stay
|
||||
* attached; further session edges publish nothing. Process shutdown disposes
|
||||
* this wiring before Hook teardown so exit-time closed is not a WebUI invalidate.
|
||||
*/
|
||||
|
||||
import { StateBus } from './state-bus';
|
||||
import type { BridgeManager } from '../bridge/manager';
|
||||
|
||||
@@ -27,53 +6,39 @@ export interface StateWiring {
|
||||
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). */
|
||||
/** Replace the bridge subscription for account and connection invalidations. */
|
||||
bindBridgeManager(bm: BridgeManager): void;
|
||||
/** Drop every listener + neuter the bus so further publishes do nothing. */
|
||||
/** Unsubscribe and stop publishing. */
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export function createStateWiring(): StateWiring {
|
||||
const bus = new StateBus();
|
||||
let disposed = false;
|
||||
let subscriptions: (() => void)[] | null = [];
|
||||
|
||||
const publish = (resource: Parameters<StateBus['publish']>[0]): void => {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
bus.publish(resource);
|
||||
const publishAccount = (): void => {
|
||||
// Publish the account list before its adapters are enumerated.
|
||||
bus.publish('qq-list');
|
||||
bus.publish('connections');
|
||||
};
|
||||
|
||||
return {
|
||||
bus,
|
||||
onSessionsChanged: () => publish('processes'),
|
||||
onSessionsChanged: () => bus.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) {
|
||||
if (!subscriptions) {
|
||||
return;
|
||||
}
|
||||
|
||||
disposed = true;
|
||||
subscriptions.forEach((unsubscribe) => unsubscribe());
|
||||
subscriptions = [
|
||||
bm.addSessionStartedListener(publishAccount),
|
||||
bm.addSessionClosedListener(publishAccount),
|
||||
];
|
||||
},
|
||||
dispose(): void {
|
||||
subscriptions?.forEach((unsubscribe) => unsubscribe());
|
||||
subscriptions = null;
|
||||
bus.dispose();
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { BridgeManager } from '../src/bridge/manager';
|
||||
|
||||
describe('BridgeManager session subscriptions', () => {
|
||||
it('unsubscribes repeated registrations independently', async () => {
|
||||
const manager = new BridgeManager();
|
||||
const started = vi.fn();
|
||||
const closed = vi.fn();
|
||||
const offStarted = manager.addSessionStartedListener(started);
|
||||
manager.addSessionStartedListener(started);
|
||||
const offClosed = manager.addSessionClosedListener(closed);
|
||||
manager.addSessionClosedListener(closed);
|
||||
offStarted();
|
||||
offStarted();
|
||||
offClosed();
|
||||
offClosed();
|
||||
|
||||
manager.onHookLogin(4001, '12345', {} as never);
|
||||
manager.onPidDisconnected(4001);
|
||||
expect(started).toHaveBeenCalledTimes(1);
|
||||
expect(closed).toHaveBeenCalledTimes(1);
|
||||
await manager.dispose();
|
||||
});
|
||||
|
||||
it('keeps the current fan-out stable when a listener unsubscribes a peer', async () => {
|
||||
const manager = new BridgeManager();
|
||||
const peer = vi.fn();
|
||||
manager.addSessionStartedListener(() => offPeer());
|
||||
const offPeer = manager.addSessionStartedListener(peer);
|
||||
|
||||
manager.onHookLogin(4002, '12345', {} as never);
|
||||
manager.onHookLogin(4003, '23456', {} as never);
|
||||
expect(peer).toHaveBeenCalledTimes(1);
|
||||
await manager.dispose();
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,42 @@ import { createStateWiring } from '../src/webui/state-wiring';
|
||||
import { BridgeManager } from '../src/bridge/manager';
|
||||
|
||||
describe('createStateWiring', () => {
|
||||
it('replaces its bridge subscription without retaining the old manager', async () => {
|
||||
const wiring = createStateWiring();
|
||||
const old = new BridgeManager();
|
||||
const current = new BridgeManager();
|
||||
const listener = vi.fn();
|
||||
wiring.bus.subscribe(listener);
|
||||
wiring.bindBridgeManager(old);
|
||||
wiring.bindBridgeManager(current);
|
||||
wiring.bindBridgeManager(current);
|
||||
|
||||
old.onHookLogin(4100, '12345', {} as never);
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
current.onHookLogin(4200, '23456', {} as never);
|
||||
expect(listener.mock.calls).toEqual([['qq-list'], ['connections']]);
|
||||
|
||||
wiring.dispose();
|
||||
await old.dispose();
|
||||
await current.dispose();
|
||||
});
|
||||
|
||||
it('unsubscribes on disposal and does not bind again', async () => {
|
||||
const wiring = createStateWiring();
|
||||
const bm = new BridgeManager();
|
||||
const subscribe = vi.spyOn(bm, 'addSessionStartedListener');
|
||||
const publish = vi.spyOn(wiring.bus, 'publish');
|
||||
wiring.bindBridgeManager(bm);
|
||||
wiring.dispose();
|
||||
wiring.dispose();
|
||||
wiring.bindBridgeManager(bm);
|
||||
|
||||
bm.onHookLogin(4300, '34567', {} as never);
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
expect(subscribe).toHaveBeenCalledTimes(1);
|
||||
await bm.dispose();
|
||||
});
|
||||
|
||||
it('provides a fresh StateBus and an onSessionsChanged that publishes "processes"', () => {
|
||||
const wiring = createStateWiring();
|
||||
expect(wiring.bus).toBeInstanceOf(StateBus);
|
||||
|
||||
Reference in new issue
Block a user