refactor: clarify async state and subscription ownership

This commit is contained in:
手瓜一十雪 committed 2026-10-18 12:42:54 +08:00
1 parent f6ca9d5f65
commit c54aeffc77
20 files changed
+698 -316

No files matched your search

+9 -25
View File
@@ -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),
);
}
}
}
+18 -53
View File
@@ -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();
},
};