refactor: use native async discovery and simplify shared state

This commit is contained in:
手瓜一十雪 committed 2026-10-18 12:57:18 +08:00
1 parent 5032cbb8c0
commit 4e2b6b1200
87 files changed
+2063 -2002

No files matched your search

+1 -1
View File
@@ -318,7 +318,7 @@ export class ExtrasApi {
),
);
}, receiptTimeoutMs);
timeout.unref?.();
timeout.unref();
}),
]));
@@ -17,3 +17,12 @@ export interface BridgeInterface extends BridgeContext {
* QQ has not emitted its cache notification since SnowLuma attached. */
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null;
}
export interface BridgeSessionListener {
started?(uin: string, bridge: BridgeInterface): void;
closed?(uin: string, bridge: BridgeInterface, pid: number): void;
}
export interface BridgeSessionSource {
subscribeSessions(listener: BridgeSessionListener): () => void;
}
+47 -70
View File
@@ -4,31 +4,28 @@ import type { PacketInfo } from '@snowluma/common/protocol-types';
import { isRealUin } from '@snowluma/common/uin';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { Bridge } from './bridge';
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
export type SessionClosedCallback = (uin: string, bridge: Bridge, pid: number) => void;
interface QQSession {
bridge: Bridge;
}
import type { BridgeSessionListener, BridgeSessionSource } from './bridge-interface';
const log = createLogger('Bridge');
const packetLog = createLogger('Bridge.Packet');
const runtimeLog = createLogger('Bridge.Runtime');
export class BridgeManager {
private sessions_ = new Map<string, QQSession>();
private pidToUin_ = new Map<number, string>();
export class BridgeManager implements BridgeSessionSource {
private readonly bridges = new Map<string, Bridge>();
private readonly pidToUin_ = new Map<number, string>();
private readonly closingSessions_ = new Map<string, Promise<void>>();
private readonly closeErrors_: unknown[] = [];
private readonly sessionSubscriptions = new Set<{ listener: BridgeSessionListener }>();
/** Hook callbacks remain synchronous; shutdown awaits every detached account. */
async dispose(): Promise<void> {
for (const [uin, session] of this.sessions_) {
this.closeSession(uin, session.bridge);
this.sessionSubscriptions.clear();
for (const [uin, session] of this.bridges) {
this.closeSession(uin, session);
}
this.sessions_.clear();
this.bridges.clear();
this.pidToUin_.clear();
await Promise.allSettled(this.closingSessions_.values());
@@ -58,33 +55,21 @@ export class BridgeManager {
);
}
private readonly sessionStartedListeners_ = new Set<SessionStartedCallback>();
private readonly sessionClosedListeners_ = new Set<SessionClosedCallback>();
/** Each subscription has an independent, idempotent unsubscribe handle. */
addSessionStartedListener(cb: SessionStartedCallback): () => void {
const listener: SessionStartedCallback = (...args) => cb(...args);
this.sessionStartedListeners_.add(listener);
/** Listener changes take effect on the next event. Close observers run before
* Bridge disposal, so the final process and account identity remain readable. */
subscribeSessions(listener: BridgeSessionListener): () => void {
const subscription = { listener };
this.sessionSubscriptions.add(subscription);
return () => {
this.sessionStartedListeners_.delete(listener);
};
}
/** 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);
this.sessionSubscriptions.delete(subscription);
};
}
private fireSessionStarted(uin: string, bridge: Bridge): void {
for (const cb of [...this.sessionStartedListeners_]) {
for (const { listener } of [...this.sessionSubscriptions]) {
try {
cb(uin, bridge);
listener.started?.(uin, bridge);
} catch (err) {
log.warn(
'session-started listener threw: %s',
@@ -95,9 +80,9 @@ export class BridgeManager {
}
private fireSessionClosed(uin: string, bridge: Bridge, pid: number): void {
for (const cb of [...this.sessionClosedListeners_]) {
for (const { listener } of [...this.sessionSubscriptions]) {
try {
cb(uin, bridge, pid);
listener.closed?.(uin, bridge, pid);
} catch (err) {
log.warn(
'session-closed listener threw: %s',
@@ -120,7 +105,7 @@ export class BridgeManager {
try {
const closed = this.detachPidFromSession(pid, uin);
const activePid = this.sessions_.get(uin)?.bridge.activePid ?? null;
const activePid = this.bridges.get(uin)?.activePid ?? null;
if (closed) {
runtimeLog.trace(
@@ -160,15 +145,15 @@ export class BridgeManager {
throw new Error(message);
}
const session = this.sessions_.get(uin);
const session = this.bridges.get(uin);
if (!session || !session.bridge.hasPid(pid)) {
if (!session || !session.hasPid(pid)) {
const message = `BridgeManager invariant violated: receive health PID=${pid} is not owned by UIN=${uin}`;
log.error(message);
throw new Error(message);
}
session.bridge.setPidReceiveHealthy(pid, healthy);
session.setPidReceiveHealthy(pid, healthy);
}
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
@@ -196,14 +181,14 @@ export class BridgeManager {
uin,
previousUin,
);
const previousSession = this.sessions_.get(previousUin);
const previousSession = this.bridges.get(previousUin);
runtimeLog.trace(
'bridge_binding_branch pid=%d uin=%j branch=%s previousUin=%j activePid=%j',
pid,
uin,
previousSession ? 'previous_session_retained' : 'previous_session_closed',
previousUin,
previousSession?.bridge.activePid ?? null,
previousSession?.activePid ?? null,
);
}
@@ -214,7 +199,7 @@ export class BridgeManager {
uin,
);
log.debug('session started: UIN=%s', uin);
this.fireSessionStarted(uin, session.bridge);
this.fireSessionStarted(uin, session);
}
runtimeLog.trace(
@@ -223,7 +208,7 @@ export class BridgeManager {
uin,
previousUin && previousUin !== uin ? 'rebound' : 'bound',
created,
session.bridge.activePid,
session.activePid,
Date.now() - startedAt,
);
} catch (error) {
@@ -284,13 +269,13 @@ export class BridgeManager {
// Notify session started on first real packet
if (created) {
log.debug('session started: UIN=%s', uin);
this.fireSessionStarted(uin, session.bridge);
this.fireSessionStarted(uin, session);
}
// Dispatch packet to bridge. The pipeline preserves synchronous parsing and
// dispatch; its promise only marks completion of any async enrichment.
handedToPipeline = true;
completion = session.bridge.onPacket(pkt);
completion = session.onPacket(pkt);
} catch (error) {
this.tracePacketFailure(
pkt,
@@ -336,7 +321,7 @@ export class BridgeManager {
uin: string,
packetClient: PacketSender,
source: 'login' | 'packet',
): { session: QQSession; created: boolean } {
): { session: Bridge; created: boolean } {
const previousUin = this.pidToUin_.get(pid);
if (previousUin && previousUin !== uin) {
@@ -351,7 +336,7 @@ export class BridgeManager {
}
const result = this.ensureSession(uin);
result.session.bridge.bindPid(pid, packetClient);
result.session.bindPid(pid, packetClient);
this.pidToUin_.set(pid, uin);
return result;
}
@@ -363,7 +348,7 @@ export class BridgeManager {
return null;
}
const session = this.sessions_.get(uin);
const session = this.bridges.get(uin);
if (!session) {
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
@@ -371,7 +356,7 @@ export class BridgeManager {
throw new Error(message);
}
const packetClient = session.bridge.packetClientForPid(pid);
const packetClient = session.packetClientForPid(pid);
if (packetClient) {
return packetClient;
@@ -391,7 +376,7 @@ export class BridgeManager {
throw new Error(message);
}
const session = this.sessions_.get(uin);
const session = this.bridges.get(uin);
if (!session) {
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
@@ -399,7 +384,7 @@ export class BridgeManager {
throw new Error(message);
}
if (!session.bridge.hasPid(pid)) {
if (!session.hasPid(pid)) {
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge does not own the PID`;
log.error(message);
throw new Error(message);
@@ -408,22 +393,22 @@ export class BridgeManager {
// Validation is complete. Mutate both sides only after the ownership
// invariant is known to hold, so a fail-fast error preserves the evidence.
this.pidToUin_.delete(pid);
session.bridge.detachPid(pid);
session.detachPid(pid);
if (!session.bridge.empty) {
if (!session.empty) {
return false;
}
this.sessions_.delete(uin);
this.bridges.delete(uin);
log.debug('session closed: UIN=%s', uin);
// Fire before dispose() so listeners can still read bridge.identity.
this.fireSessionClosed(uin, session.bridge, pid);
this.closeSession(uin, session.bridge);
this.fireSessionClosed(uin, session, pid);
this.closeSession(uin, session);
return true;
}
private ensureSession(uin: string): { session: QQSession; created: boolean } {
let session = this.sessions_.get(uin);
private ensureSession(uin: string): { session: Bridge; created: boolean } {
const session = this.bridges.get(uin);
if (session) {
return { session, created: false };
@@ -432,20 +417,12 @@ export class BridgeManager {
const bridge = new Bridge(
IdentityService.openForUin(uin, 'data', this.closingSessions_.get(uin)),
);
session = { bridge };
this.sessions_.set(uin, session);
this.bridges.set(uin, bridge);
// 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 };
return { session: bridge, created: true };
}
getSession(uin: string): QQSession | null {
return this.sessions_.get(uin) ?? null;
}
get sessions(): Map<string, { bridge: Bridge }> {
return this.sessions_;
getBridge(uin: string): Bridge | null {
return this.bridges.get(uin) ?? null;
}
}
+2 -4
View File
@@ -77,12 +77,13 @@ async function main() {
const bridgeManager = new BridgeManager();
bindSystemFaceCatalog(bridgeManager);
const oneBotManager = new OneBotManager();
oneBotManager.bind(bridgeManager);
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
// 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 stateWiring = createStateWiring(bridgeManager);
const hookManager = new HookManager({
bridgeManager,
autoLoadOnDiscovery,
@@ -93,9 +94,6 @@ async function main() {
log.info('hook auto-load enabled: every discovered QQ process will be injected');
}
oneBotManager.bind(bridgeManager);
stateWiring.bindBridgeManager(bridgeManager);
// Global notification subsystem (account up/down → webhook). Bound AFTER
// OneBotManager so the nickname fallback is already populated when it observes.
// Lifecycle events identify their PID; an older process with the same UIN
+1 -1
View File
@@ -337,7 +337,7 @@ export function startNativeStageSync(options: StageSyncOptions): { stop: () => v
tick();
const timer = setInterval(tick, options.intervalMs ?? 500);
timer.unref?.();
timer.unref();
return {
stop() {
stopped = true;
+27 -18
View File
@@ -9,10 +9,11 @@
// SMTP send, the clock) are injected so the class is fully unit-testable; the
// real wiring lives in `createNotificationManager()` at the bottom.
import { positiveIntEnv } from '@snowluma/common/env';
import { errorMessage } from '@snowluma/common/errors';
import type { HookProcessInfo } from '@snowluma/bridge/types';
import { createLogger } from '@snowluma/common/logger';
import { loadOneBotConfig } from '@snowluma/onebot/config';
import type { BridgeManager } from '../bridge/manager';
import type { BridgeSessionSource } from '../bridge/bridge-interface';
import {
isEmailChannel,
loadNotificationsConfig,
@@ -93,10 +94,6 @@ interface AccountNotificationContext {
pid: number | null;
}
function errMsg(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
/**
* Pure: the channels a UIN should be notified through — globally enabled AND
* opted into by the UIN — preserving config order. Exported for unit tests.
@@ -118,6 +115,7 @@ export class NotificationManager {
private readonly deliveries = new Map<string, Promise<void>>();
private readonly historyLimit: number;
private disposed = false;
private unsubscribeSessions: (() => void) | null = null;
constructor(deps: NotificationManagerDeps) {
this.deps = deps;
@@ -126,13 +124,17 @@ export class NotificationManager {
/** Subscribe to the global session online/offline edges. Register AFTER
* OneBotManager so the nickname fallback is already populated. */
bind(bridgeManager: BridgeManager): void {
bridgeManager.addSessionStartedListener((uin, bridge) =>
this.handleOnline(uin, bridge.identity.nickname, bridge.activePid),
);
bridgeManager.addSessionClosedListener((uin, bridge, pid) =>
this.handleOffline(uin, bridge.identity.nickname, pid),
);
bind(bridgeManager: BridgeSessionSource): void {
if (this.disposed) {
return;
}
this.unsubscribeSessions?.();
this.unsubscribeSessions = bridgeManager.subscribeSessions({
started: (uin, bridge) =>
this.handleOnline(uin, bridge.identity.nickname, bridge.activePid),
closed: (uin, bridge, pid) => this.handleOffline(uin, bridge.identity.nickname, pid),
});
}
handleOnline(uin: string, nickname?: string, pid: number | null = null): void {
@@ -158,7 +160,7 @@ export class NotificationManager {
try {
debounceSeconds = this.deps.loadConfig().debounceSeconds;
} catch (err) {
log.warn('offline(%s) skipped — config load failed: %s', uin, errMsg(err));
log.warn('offline(%s) skipped — config load failed: %s', uin, errorMessage(err));
return;
}
@@ -234,7 +236,12 @@ export class NotificationManager {
const cfg = this.deps.loadConfig();
channels = selectChannels(cfg.channels, this.deps.loadChannelIds(uin));
} catch (err) {
log.warn('notify(%s, %s) skipped — config load failed: %s', uin, event, errMsg(err));
log.warn(
'notify(%s, %s) skipped — config load failed: %s',
uin,
event,
errorMessage(err),
);
return;
}
@@ -247,7 +254,7 @@ export class NotificationManager {
try {
facts = await this.deps.resolveProcess?.(uin, account.pid);
} catch (err) {
log.warn('resolveProcess(%s, %s) failed: %s', uin, account.pid, errMsg(err));
log.warn('resolveProcess(%s, %s) failed: %s', uin, account.pid, errorMessage(err));
}
const vars: Record<string, string> = {
@@ -318,7 +325,7 @@ export class NotificationManager {
return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers);
} catch (err) {
return { ok: false, error: errMsg(err) };
return { ok: false, error: errorMessage(err) };
}
}
@@ -332,7 +339,7 @@ export class NotificationManager {
try {
channel = this.deps.loadConfig().channels.find((c) => c.id === channelId);
} catch (err) {
return { ok: false, found: false, error: errMsg(err) };
return { ok: false, found: false, error: errorMessage(err) };
}
if (!channel) {
@@ -371,6 +378,8 @@ export class NotificationManager {
}
this.disposed = true;
this.unsubscribeSessions?.();
this.unsubscribeSessions = null;
for (const timer of this.timers.values()) {
clearTimeout(timer);
@@ -399,7 +408,7 @@ export function createDefaultPost(
error: res.ok ? undefined : `HTTP ${res.status}`,
};
} catch (err) {
return { ok: false, error: errMsg(err) };
return { ok: false, error: errorMessage(err) };
}
};
}
+12 -10
View File
@@ -6,7 +6,7 @@ import {
type SysFaceCatalogStorage,
} from '@snowluma/protocol/sys-face-store';
import { JsonSysFaceCatalogStorage } from '@snowluma/protocol/sys-face-storage';
import type { BridgeManager } from './bridge/manager';
import type { BridgeSessionSource } from './bridge/bridge-interface';
const log = createLogger('SysFace');
@@ -19,7 +19,7 @@ export interface SystemFaceCatalogBindingOptions {
/** Attach the shared system-face catalog to Bridge login edges. The first
* account restores + refreshes it; later accounts reuse the same result. */
export function bindSystemFaceCatalog(
manager: BridgeManager,
manager: BridgeSessionSource,
options: SystemFaceCatalogBindingOptions = {},
): void {
const store = options.store ?? sysFaceStore;
@@ -30,13 +30,15 @@ export function bindSystemFaceCatalog(
);
store.configureStorage(storage);
manager.addSessionStartedListener((uin, bridge) => {
void store.prewarm(bridge).catch((error) => {
log.error(
'system face catalog login prewarm failed: uin=%s error=%s',
uin,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
});
manager.subscribeSessions({
started: (uin, bridge) => {
void store.prewarm(bridge).catch((error) => {
log.error(
'system face catalog login prewarm failed: uin=%s error=%s',
uin,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
});
},
});
}
@@ -40,8 +40,7 @@ export interface ConnectionDiffLoopHandle {
export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): ConnectionDiffLoopHandle {
const intervalMs = opts.intervalMs ?? 500;
let lastSerialized = '';
let haveBaseline = false;
let lastSerialized: string | undefined | null = null;
let disposed = false;
// One-shot diagnostic latch: a projector that starts throwing only after
// a shape regression would otherwise wedge the baseline silently — no
@@ -112,13 +111,12 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
const serialized = JSON.stringify(comparable);
if (!haveBaseline) {
if (lastSerialized === null) {
// First successful observation. The SSE handler's sendAllInitial
// already shipped a `connections` frame to every connected client
// on connect, so the baseline is what they already have — emitting
// it again would be a duplicate. Just store it.
lastSerialized = serialized;
haveBaseline = true;
return;
}
@@ -144,7 +142,7 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
// lifetime by design, but tests / a future hot-reload scenario must be
// able to exit cleanly without an outstanding interval ref. Mirrors the
// tokenJanitor pattern in server.ts.
timer.unref?.();
timer.unref();
return {
dispose(): void {
+1 -4
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger } from '@snowluma/common/logger';
import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
@@ -434,10 +435,6 @@ function invoke(options: RestoreBackupOptions, operation: RestoreOperation): voi
options.beforeOperation?.(operation);
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function isMissingPathError(error: unknown): boolean {
return (
typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT'
+1 -1
View File
@@ -853,7 +853,7 @@ export async function initWebUI(
// Periodic janitor — keeps sessionTokens / loginAttempts from growing
// unbounded and replaces the per-request O(n) sweep we used to do.
const tokenJanitor = setInterval(purgeExpiredTokens, 60_000);
tokenJanitor.unref?.();
tokenJanitor.unref();
// ─── Login ───────────────────────────────────────────────────────────────
app.post('/api/login', async (c) => {
+65 -101
View File
@@ -1,21 +1,9 @@
/**
* Bind a StateBus to an SSE-friendly `send` callback: every publish becomes
* a debounced fresh-snapshot frame, and `sendAllInitial()` primes a new
* connection with one frame per resource.
*
* Decoupled from the HTTP layer so the route handler in server.ts can drop
* its responsibility down to "open a ReadableStream, hand its enqueue to
* bindStateStream, abort tears it down". Pure logic = unit-testable with
* fake timers; no Response/controller mocking needed.
*
* Per-resource debounce, not global: an 'qq-list' churn during a slow
* 'processes' burst must not delay the qq-list frame, and a 'connections'
* diff loop running at 500ms must not coalesce 10 unrelated processes
* events into one. Each resource is its own timer.
*/
import { errorMessage } from '@snowluma/common/errors';
import { createLogger } from '@snowluma/common/logger';
import type { StateBus, StateResource } from './state-bus';
const log = createLogger('WebUI.StateStream');
export interface StateStreamFrame {
resource: StateResource;
data: unknown;
@@ -45,112 +33,88 @@ const ALL_RESOURCES: readonly StateResource[] = ['processes', 'qq-list', 'connec
export function bindStateStream(opts: BindStateStreamOptions): StateStreamHandle {
const debounceMs = opts.debounceMs ?? 50;
const timers = new Map<StateResource, ReturnType<typeof setTimeout>>();
// Single-flight per resource: at most one in-flight flush per resource so
// an uneven snapshot latency cannot interleave sends out of order (a slow
// earlier snapshot landing AFTER a later one, leaving the client's last
// observed frame stale). Publishes arriving while a flush is in flight
// mark `pending` and rearm the debounce timer once the flush completes.
const inFlight = new Set<StateResource>();
const pending = new Set<StateResource>();
let disposed = false;
const flush = async (resource: StateResource): Promise<void> => {
if (disposed) {
return;
function resourceStream(resource: StateResource) {
let timer: ReturnType<typeof setTimeout> | null = null;
let task: Promise<void> | null = null;
let pending = false;
function clearTimer() {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
}
inFlight.add(resource);
try {
let data: unknown;
try {
data = await opts.snapshot(resource);
} catch {
// Per-resource snapshot failure (e.g. listProcesses threw): skip
// this frame so siblings keep flowing. The next publish for the
// same resource gets a fresh attempt.
return;
function flush(): Promise<void> {
if (disposed) {
return Promise.resolve();
}
if (task) {
return task;
}
clearTimer();
task = Promise.resolve()
.then(async () => {
if (disposed) {
return;
}
const data = await opts.snapshot(resource);
if (!disposed) {
opts.send({ resource, data });
}
})
.catch((error) => {
log.warn('state stream %s failed: %s', resource, errorMessage(error));
})
.finally(() => {
task = null;
if (pending) {
pending = false;
schedule();
}
});
return task;
}
function schedule(): void {
if (disposed) {
return;
}
try {
opts.send({ resource, data });
} catch {
// Downstream consumer (e.g. closed SSE controller) — same isolation
// contract as snapshot failures.
if (task) {
pending = true;
return;
}
} finally {
inFlight.delete(resource);
// If a publish arrived during the in-flight window, schedule one
// follow-up flush. Re-uses the debounce so a sustained publish
// stream produces at most one frame per (debounceMs + flushLatency),
// not back-to-back frames.
if (!disposed && pending.has(resource)) {
pending.delete(resource);
schedule(resource);
}
clearTimer();
timer = setTimeout(() => void flush(), debounceMs);
}
return { flush, schedule, clearTimer };
}
const streams = {
processes: resourceStream('processes'),
'qq-list': resourceStream('qq-list'),
connections: resourceStream('connections'),
};
const schedule = (resource: StateResource): void => {
if (disposed) {
return;
}
if (inFlight.has(resource)) {
// Defer to the post-flush re-arm; no new timer until the in-flight
// send completes. This is the load-bearing invariant for ordering.
pending.add(resource);
return;
}
const existing = timers.get(resource);
if (existing) {
clearTimeout(existing);
}
const t = setTimeout(() => {
timers.delete(resource);
void flush(resource);
}, debounceMs);
timers.set(resource, t);
};
const unsubscribe = opts.bus.subscribe(schedule);
const unsubscribe = opts.bus.subscribe((resource) => streams[resource].schedule());
return {
async sendAllInitial(): Promise<void> {
if (disposed) {
return;
}
// Fire all three in parallel. Each resource's snapshot is independent
// so a slow listProcesses() doesn't gate qq-list/connections. Each
// call goes through the single-flight gate so a concurrent bus
// publish during this initial fan-out coalesces correctly.
await Promise.all(ALL_RESOURCES.map((r) => flush(r)));
await Promise.all(ALL_RESOURCES.map((resource) => streams[resource].flush()));
},
dispose(): void {
if (disposed) {
return;
}
disposed = true;
unsubscribe();
for (const t of timers.values()) {
clearTimeout(t);
}
timers.clear();
pending.clear();
ALL_RESOURCES.forEach((resource) => streams[resource].clearTimer());
},
};
}
+10 -24
View File
@@ -1,45 +1,31 @@
import { StateBus } from './state-bus';
import type { BridgeManager } from '../bridge/manager';
import type { BridgeSessionSource } from '../bridge/bridge-interface';
export interface StateWiring {
/** The bus the SSE handler subscribes to. */
readonly bus: StateBus;
/** Pass as the HookManager `onSessionsChanged` dep — publishes 'processes'. */
onSessionsChanged: () => void;
/** Replace the bridge subscription for account and connection invalidations. */
bindBridgeManager(bm: BridgeManager): void;
/** Unsubscribe and stop publishing. */
onSessionsChanged(): void;
dispose(): void;
}
export function createStateWiring(): StateWiring {
export function createStateWiring(bridgeManager: BridgeSessionSource): StateWiring {
const bus = new StateBus();
let subscriptions: (() => void)[] | null = [];
const publishAccount = (): void => {
// Publish the account list before its adapters are enumerated.
const publishAccountChange = (): void => {
bus.publish('qq-list');
bus.publish('connections');
};
const unsubscribe = bridgeManager.subscribeSessions({
started: publishAccountChange,
closed: publishAccountChange,
});
return {
bus,
onSessionsChanged: () => bus.publish('processes'),
bindBridgeManager(bm: BridgeManager): void {
if (!subscriptions) {
return;
}
subscriptions.forEach((unsubscribe) => unsubscribe());
subscriptions = [
bm.addSessionStartedListener(publishAccount),
bm.addSessionClosedListener(publishAccount),
];
},
dispose(): void {
subscriptions?.forEach((unsubscribe) => unsubscribe());
subscriptions = null;
bus.dispose();
unsubscribe();
},
};
}
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import fs from 'node:fs';
import path from 'node:path';
import type { LogCleanupResult, LogStorageStatus } from '@snowluma/common/log-file-transport';
@@ -377,10 +378,6 @@ function validateAccountStorageCategory(value: string): AccountStorageCategory {
throw new StorageManagementInputError(`unsupported account storage category: ${value}`);
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function redactFilesystemPath(message: string, filePath: string, label: string): string {
const absolute = path.resolve(filePath);
return message.split(absolute).join(label).split(filePath).join(label);
+3 -6
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
// WebUI TLS helpers. Cert/key live as config/cert.pem + config/key.pem
// (NapCat-aligned, self-contained, travels in A2 backups). Two pure-ish
// helpers: validate a pasted pair (save path) and resolve the on-disk pair
@@ -25,10 +26,6 @@ export interface RequiredTlsContext {
key: Buffer;
}
function errMsg(e: unknown): string {
return e instanceof Error ? e.message : String(e);
}
/** Parse-validate a cert/key pair (used by the save endpoint before writing). */
export function validateTlsPair(cert: string | Buffer, key: string | Buffer): TlsValidation {
if (!cert || !cert.toString().trim()) {
@@ -43,7 +40,7 @@ export function validateTlsPair(cert: string | Buffer, key: string | Buffer): Tl
tls.createSecureContext({ cert, key });
return { ok: true };
} catch (e) {
return { ok: false, reason: `invalid cert/key: ${errMsg(e)}` };
return { ok: false, reason: `invalid cert/key: ${errorMessage(e)}` };
}
}
@@ -63,7 +60,7 @@ export function resolveTlsContext(configDir: string): TlsResolution {
cert = fs.readFileSync(certPath);
key = fs.readFileSync(keyPath);
} catch (e) {
return { ok: false, reason: `failed to read cert/key: ${errMsg(e)}` };
return { ok: false, reason: `failed to read cert/key: ${errorMessage(e)}` };
}
const valid = validateTlsPair(cert, key);
@@ -138,7 +138,7 @@ describe('BridgeManager PID ownership', () => {
try {
manager.onHookLogin(101, '10001', makeSender().client);
manager.getSession('10001')!.bridge.detachPid(101);
manager.getBridge('10001')!.detachPid(101);
expect(() => manager.onPidDisconnected(101)).toThrowError(
'BridgeManager invariant violated: PID=101 is mapped to UIN=10001, but Bridge does not own the PID',
);
@@ -239,7 +239,7 @@ describe('BridgeManager PID ownership', () => {
}),
]),
);
expect(manager.getSession('0')).toBeNull();
expect(manager.getBridge('0')).toBeNull();
} finally {
unsubscribe();
}
@@ -295,20 +295,20 @@ describe('BridgeManager PID ownership', () => {
const first = makeSender();
const second = makeSender();
const lifecycle: string[] = [];
manager.addSessionStartedListener((uin) => lifecycle.push(`started:${uin}`));
manager.addSessionClosedListener((uin) => lifecycle.push(`closed:${uin}`));
manager.subscribeSessions({ started: (uin) => lifecycle.push(`started:${uin}`) });
manager.subscribeSessions({ closed: (uin) => lifecycle.push(`closed:${uin}`) });
manager.onHookLogin(101, '10001', first.client);
const oldBridge = manager.getSession('10001')!.bridge;
const oldBridge = manager.getBridge('10001')!;
const dispose = vi.spyOn(oldBridge, 'dispose');
manager.onHookLogin(101, '20002', second.client);
expect(lifecycle).toEqual(['started:10001', 'closed:10001', 'started:20002']);
expect(manager.getSession('10001')).toBeNull();
expect(manager.getBridge('10001')).toBeNull();
expect(oldBridge.hasPid(101)).toBe(false);
expect(dispose).toHaveBeenCalledOnce();
expect(manager.getSession('20002')!.bridge.hasPid(101)).toBe(true);
expect(manager.getBridge('20002')!.hasPid(101)).toBe(true);
});
it('keeps a multi-PID UIN alive and falls back to the remaining sender', async () => {
@@ -316,11 +316,11 @@ describe('BridgeManager PID ownership', () => {
const first = makeSender();
const second = makeSender();
const closed = vi.fn();
manager.addSessionClosedListener(closed);
manager.subscribeSessions({ closed: closed });
manager.onHookLogin(101, '10001', first.client);
manager.onHookLogin(202, '10001', second.client);
const bridge = manager.getSession('10001')!.bridge;
const bridge = manager.getBridge('10001')!;
expect(bridge.activePid).toBe(202);
await bridge.sendRawPacket('Test.BeforeDisconnect', new Uint8Array([1]));
@@ -329,7 +329,7 @@ describe('BridgeManager PID ownership', () => {
manager.onPidDisconnected(202);
expect(manager.getSession('10001')!.bridge).toBe(bridge);
expect(manager.getBridge('10001')!).toBe(bridge);
expect(bridge.activePid).toBe(101);
expect(closed).not.toHaveBeenCalled();
await bridge.sendRawPacket('Test.AfterDisconnect', new Uint8Array([2]));
@@ -337,7 +337,7 @@ describe('BridgeManager PID ownership', () => {
expect(testSends(second.sendPacket)).toHaveLength(1);
manager.onPidDisconnected(101);
expect(manager.getSession('10001')).toBeNull();
expect(manager.getBridge('10001')).toBeNull();
expect(closed).toHaveBeenCalledOnce();
expect(closed).toHaveBeenCalledWith('10001', bridge, 101);
await expect(
@@ -363,7 +363,7 @@ describe('BridgeManager PID ownership', () => {
manager.onHookLogin(202, '10001', second.client);
manager.onPacket(packet(202, '10001'));
manager.onPidDisconnected(202);
const bridge = manager.getSession('10001')!.bridge;
const bridge = manager.getBridge('10001')!;
manager.onPidDisconnected(101);
await bridge.sendRawPacket('Test.NoSender', new Uint8Array([0x00, 0xff]));
@@ -393,7 +393,7 @@ describe('BridgeManager PID ownership', () => {
const manager = new BridgeManager();
manager.onHookLogin(101, '10001', makeSender().client);
manager.onHookLogin(202, '10001', makeSender().client);
const bridge = manager.getSession('10001')!.bridge;
const bridge = manager.getBridge('10001')!;
expect(bridge.receiveHealthy).toBe(true);
@@ -414,13 +414,13 @@ describe('BridgeManager PID ownership', () => {
const third = makeSender();
const reboundFirst = makeSender();
const started = vi.fn();
manager.addSessionStartedListener(started);
manager.subscribeSessions({ started: started });
manager.onHookLogin(101, '10001', first.client);
manager.onHookLogin(202, '10001', second.client);
manager.onHookLogin(303, '10001', third.client);
manager.onHookLogin(101, '10001', reboundFirst.client);
const bridge = manager.getSession('10001')!.bridge;
const bridge = manager.getBridge('10001')!;
expect(started).toHaveBeenCalledOnce();
expect(bridge.activePid).toBe(101);
@@ -442,15 +442,15 @@ describe('BridgeManager PID ownership', () => {
const manager = new BridgeManager();
const sender = makeSender();
const lifecycle: string[] = [];
manager.addSessionStartedListener((uin) => lifecycle.push(`started:${uin}`));
manager.addSessionClosedListener((uin) => lifecycle.push(`closed:${uin}`));
manager.subscribeSessions({ started: (uin) => lifecycle.push(`started:${uin}`) });
manager.subscribeSessions({ closed: (uin) => lifecycle.push(`closed:${uin}`) });
manager.onHookLogin(101, '10001', sender.client);
manager.onPacket(packet(101, '20002'));
expect(lifecycle).toEqual(['started:10001', 'closed:10001', 'started:20002']);
expect(manager.getSession('10001')).toBeNull();
const replacement = manager.getSession('20002')!.bridge;
expect(manager.getBridge('10001')).toBeNull();
const replacement = manager.getBridge('20002')!;
expect(replacement.hasPid(101)).toBe(true);
await replacement.sendRawPacket('Test.AfterPacketRebind', new Uint8Array([1]));
expect(testSends(sender.sendPacket)).toHaveLength(1);
@@ -462,24 +462,24 @@ describe('BridgeManager PID ownership', () => {
const moving = makeSender();
const rebound = makeSender();
const lifecycle: string[] = [];
manager.addSessionStartedListener((uin) => lifecycle.push(`started:${uin}`));
manager.addSessionClosedListener((uin) => lifecycle.push(`closed:${uin}`));
manager.subscribeSessions({ started: (uin) => lifecycle.push(`started:${uin}`) });
manager.subscribeSessions({ closed: (uin) => lifecycle.push(`closed:${uin}`) });
manager.onHookLogin(101, '10001', fallback.client);
manager.onHookLogin(202, '10001', moving.client);
const oldBridge = manager.getSession('10001')!.bridge;
const oldBridge = manager.getBridge('10001')!;
expect(oldBridge.activePid).toBe(202);
manager.onHookLogin(202, '20002', rebound.client);
expect(lifecycle).toEqual(['started:10001', 'started:20002']);
expect(manager.getSession('10001')!.bridge).toBe(oldBridge);
expect(manager.getBridge('10001')!).toBe(oldBridge);
expect(oldBridge.hasPid(202)).toBe(false);
expect(oldBridge.activePid).toBe(101);
await oldBridge.sendRawPacket('Test.OldUinFallback', new Uint8Array([1]));
expect(testSends(fallback.sendPacket)).toHaveLength(1);
const newBridge = manager.getSession('20002')!.bridge;
const newBridge = manager.getBridge('20002')!;
expect(newBridge.activePid).toBe(202);
await newBridge.sendRawPacket('Test.NewUinSender', new Uint8Array([2]));
expect(testSends(rebound.sendPacket)).toHaveLength(1);
@@ -502,20 +502,20 @@ describe('BridgeManager PID ownership', () => {
const reboundFirst = makeSender();
const started = vi.fn();
const closed = vi.fn();
manager.addSessionStartedListener(started);
manager.addSessionClosedListener(closed);
manager.subscribeSessions({ started: started });
manager.subscribeSessions({ closed: closed });
manager.onHookLogin(101, '10001', first.client);
manager.onHookLogin(202, '20002', second.client);
const targetBridge = manager.getSession('20002')!.bridge;
const targetBridge = manager.getBridge('20002')!;
manager.onHookLogin(101, '20002', reboundFirst.client);
expect(started).toHaveBeenCalledTimes(2);
expect(closed).toHaveBeenCalledOnce();
expect(closed).toHaveBeenCalledWith('10001', expect.anything(), 101);
expect(manager.getSession('10001')).toBeNull();
expect(manager.getSession('20002')!.bridge).toBe(targetBridge);
expect(manager.getBridge('10001')).toBeNull();
expect(manager.getBridge('20002')!).toBe(targetBridge);
expect(targetBridge.activePid).toBe(101);
manager.onPidDisconnected(101);
@@ -533,8 +533,8 @@ describe('BridgeManager PID ownership', () => {
const sender = makeSender();
const started = vi.fn();
const closed = vi.fn();
manager.addSessionStartedListener(started);
manager.addSessionClosedListener(closed);
manager.subscribeSessions({ started: started });
manager.subscribeSessions({ closed: closed });
manager.onHookLogin(101, '10001', sender.client);
manager.onHookLogin(101, '10001', sender.client);
@@ -563,7 +563,7 @@ describe('BridgeManager PID ownership', () => {
manager.onHookLogin(101, '10001', sender.client);
// Remove the connection without updating the manager's ownership index.
manager.getSession('10001')!.bridge.detachPid(101);
manager.getBridge('10001')!.detachPid(101);
expect(() => manager.onPacket(packet(101, '10001'))).toThrowError(
'BridgeManager invariant violated: PID=101 has no sender in UIN=10001 session',
@@ -0,0 +1,80 @@
import { IdentityService } from '@snowluma/protocol/identity-service';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { BridgeManager } from '../src/bridge/manager';
describe('BridgeManager subscriptions', () => {
let manager: BridgeManager;
const sender = { sendPacket: vi.fn() } as never;
beforeEach(() => {
vi.spyOn(IdentityService, 'openForUin').mockImplementation((uin) =>
IdentityService.memory(uin),
);
manager = new BridgeManager();
});
afterEach(async () => {
await manager.dispose();
vi.restoreAllMocks();
});
it('unsubscribes both session edges without removing another observer', () => {
const started = vi.fn();
const closed = vi.fn();
const peer = { started: vi.fn(), closed: vi.fn() };
const unsubscribe = manager.subscribeSessions({ started, closed });
manager.subscribeSessions(peer);
manager.onHookLogin(101, '10001', sender);
unsubscribe();
manager.onPidDisconnected(101);
manager.onHookLogin(202, '20002', sender);
expect(started).toHaveBeenCalledOnce();
expect(closed).not.toHaveBeenCalled();
expect(peer.started).toHaveBeenCalledTimes(2);
expect(peer.closed).toHaveBeenCalledOnce();
});
it('keeps subscription handles independent when an observer is reused', () => {
const listener = { started: vi.fn() };
const unsubscribeFirst = manager.subscribeSessions(listener);
const unsubscribeSecond = manager.subscribeSessions(listener);
unsubscribeFirst();
unsubscribeFirst();
manager.onHookLogin(101, '10001', sender);
expect(listener.started).toHaveBeenCalledOnce();
unsubscribeSecond();
manager.onHookLogin(202, '20002', sender);
expect(listener.started).toHaveBeenCalledOnce();
});
it('applies listener changes to the next event while preserving dispatch order', () => {
const seen: string[] = [];
let unsubscribeSecond: () => void;
manager.subscribeSessions({
started: () => {
seen.push('first');
unsubscribeSecond();
manager.subscribeSessions({ started: () => seen.push('later') });
},
});
unsubscribeSecond = manager.subscribeSessions({ started: () => seen.push('second') });
manager.onHookLogin(101, '10001', sender);
expect(seen).toEqual(['first', 'second']);
seen.length = 0;
manager.onHookLogin(202, '20002', sender);
expect(seen).toEqual(['first', 'later']);
});
it('releases its observers when disposed', async () => {
const started = vi.fn();
manager.subscribeSessions({ started });
await manager.dispose();
manager.onHookLogin(101, '10001', sender);
expect(started).not.toHaveBeenCalled();
});
});
@@ -6,10 +6,10 @@ describe('BridgeManager session subscriptions', () => {
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);
const offStarted = manager.subscribeSessions({ started });
manager.subscribeSessions({ started });
const offClosed = manager.subscribeSessions({ closed });
manager.subscribeSessions({ closed });
offStarted();
offStarted();
offClosed();
@@ -25,8 +25,8 @@ describe('BridgeManager session subscriptions', () => {
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.subscribeSessions({ started: () => offPeer() });
const offPeer = manager.subscribeSessions({ started: peer });
manager.onHookLogin(4002, '12345', {} as never);
manager.onHookLogin(4003, '23456', {} as never);
@@ -63,6 +63,28 @@ describe('notification lifecycle PID', () => {
vi.useRealTimers();
});
it('detaches from session events when disposed and cannot be rebound afterward', () => {
const online = vi.spyOn(notifications, 'handleOnline');
const offline = vi.spyOn(notifications, 'handleOffline');
notifications.dispose();
notifications.bind(bridges);
bridges.onHookLogin(1001, '12345', sender);
bridges.onPidDisconnected(1001);
expect(online).not.toHaveBeenCalled();
expect(offline).not.toHaveBeenCalled();
});
it('replaces its existing binding instead of delivering each event twice', () => {
const online = vi.spyOn(notifications, 'handleOnline');
notifications.bind(bridges);
bridges.onHookLogin(1001, '12345', sender);
expect(online).toHaveBeenCalledOnce();
});
it('retains the final detached PID through debounce and uses the new PID on recovery', async () => {
bridges.onHookLogin(1001, '12345', sender);
bridges.onHookLogin(2002, '12345', sender);
@@ -71,7 +93,7 @@ describe('notification lifecycle PID', () => {
expect(posts).toEqual([]);
bridges.onPidDisconnected(2002);
expect(bridges.getSession('12345')).toBeNull();
expect(bridges.getBridge('12345')).toBeNull();
await vi.advanceTimersByTimeAsync(30_000);
expect(resolveProcess).toHaveBeenNthCalledWith(1, '12345', 2002);
@@ -7,6 +7,20 @@ import { comparableConnectionSnapshot } from '../src/webui/connection-snapshot';
const previousLogLevel = getLogLevel();
describe('startConnectionDiffLoop', () => {
it('treats an undefined snapshot as an established baseline', () => {
vi.useFakeTimers();
const bus = new StateBus();
const publish = vi.spyOn(bus, 'publish');
let snapshot: unknown = undefined;
const handle = startConnectionDiffLoop({ bus, getSnapshot: () => snapshot });
vi.advanceTimersByTime(1000);
expect(publish).not.toHaveBeenCalled();
snapshot = null;
vi.advanceTimersByTime(500);
expect(publish).toHaveBeenCalledOnce();
handle.dispose();
});
beforeEach(() => {
vi.useFakeTimers();
});
@@ -19,6 +19,50 @@ describe('bindStateStream', () => {
vi.useRealTimers();
});
it('joins concurrent initial snapshots for the same resource', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
let resolve!: (data: unknown) => void;
const slow = new Promise((done) => {
resolve = done;
});
const snapshot = vi.fn((resource: StateResource) =>
resource === 'processes' ? slow : resource,
);
const handle = bindStateStream({ bus, snapshot, send: (frame) => sent.push(frame) });
const first = handle.sendAllInitial();
const second = handle.sendAllInitial();
await vi.advanceTimersByTimeAsync(0);
expect(snapshot).toHaveBeenCalledTimes(3);
resolve('processes');
await Promise.all([first, second]);
expect(sent).toHaveLength(3);
handle.dispose();
});
it('absorbs a scheduled publish into an initial snapshot without starting another request', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
let resolve!: (data: unknown) => void;
const slow = new Promise((done) => {
resolve = done;
});
const snapshot = vi.fn((resource: StateResource) =>
resource === 'processes' ? slow : resource,
);
const handle = bindStateStream({ bus, snapshot, send: (frame) => sent.push(frame) });
bus.publish('processes');
const initial = handle.sendAllInitial();
await vi.advanceTimersByTimeAsync(100);
expect(snapshot).toHaveBeenCalledTimes(3);
resolve('fresh');
await initial;
expect(sent.filter((frame) => frame.resource === 'processes')).toEqual([
{ resource: 'processes', data: 'fresh' },
]);
handle.dispose();
});
it('sendAllInitial emits one frame per resource with the snapshot data', async () => {
const bus = new StateBus();
const sent: CapturedFrame[] = [];
+25 -20
View File
@@ -4,15 +4,15 @@ 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();
it('keeps a replacement wiring independent of its disposed predecessor', async () => {
const old = new BridgeManager();
const current = new BridgeManager();
const listener = vi.fn();
const previousWiring = createStateWiring(old);
previousWiring.bus.subscribe(listener);
previousWiring.dispose();
const wiring = createStateWiring(current);
wiring.bus.subscribe(listener);
wiring.bindBridgeManager(old);
wiring.bindBridgeManager(current);
wiring.bindBridgeManager(current);
old.onHookLogin(4100, '12345', {} as never);
expect(listener).not.toHaveBeenCalled();
@@ -24,15 +24,13 @@ describe('createStateWiring', () => {
await current.dispose();
});
it('unsubscribes on disposal and does not bind again', async () => {
const wiring = createStateWiring();
it('unsubscribes on disposal before another account starts', async () => {
const bm = new BridgeManager();
const subscribe = vi.spyOn(bm, 'addSessionStartedListener');
const subscribe = vi.spyOn(bm, 'subscribeSessions');
const wiring = createStateWiring(bm);
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();
@@ -40,8 +38,19 @@ describe('createStateWiring', () => {
await bm.dispose();
});
it('releases its session subscription when disposed', () => {
const unsubscribe = vi.fn();
const source = { subscribeSessions: vi.fn(() => unsubscribe) };
const wiring = createStateWiring(source);
wiring.dispose();
expect(source.subscribeSessions).toHaveBeenCalledOnce();
expect(unsubscribe).toHaveBeenCalledOnce();
});
it('provides a fresh StateBus and an onSessionsChanged that publishes "processes"', () => {
const wiring = createStateWiring();
const wiring = createStateWiring(new BridgeManager());
expect(wiring.bus).toBeInstanceOf(StateBus);
const sub = vi.fn();
wiring.bus.subscribe(sub);
@@ -50,9 +59,8 @@ describe('createStateWiring', () => {
});
it('binds a BridgeManager so session-started publishes both "qq-list" and "connections"', () => {
const wiring = createStateWiring();
const bm = new BridgeManager();
wiring.bindBridgeManager(bm);
const wiring = createStateWiring(bm);
const seen: string[] = [];
wiring.bus.subscribe((r) => seen.push(r));
@@ -63,9 +71,8 @@ describe('createStateWiring', () => {
});
it('publishes "qq-list" + "connections" on session-closed', () => {
const wiring = createStateWiring();
const bm = new BridgeManager();
wiring.bindBridgeManager(bm);
const wiring = createStateWiring(bm);
bm.onHookLogin(4242, '12345', {} as never);
const sub = vi.fn();
wiring.bus.subscribe(sub);
@@ -80,9 +87,8 @@ describe('createStateWiring', () => {
});
it('dispose() latches so later Hook/Bridge edges publish nothing', () => {
const wiring = createStateWiring();
const bm = new BridgeManager();
wiring.bindBridgeManager(bm);
const wiring = createStateWiring(bm);
const sub = vi.fn();
wiring.bus.subscribe(sub);
@@ -98,15 +104,14 @@ describe('createStateWiring', () => {
});
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);
const wiring = createStateWiring(bm);
// A peer subscriber (e.g. OneBotManager) added AFTER state-wiring throws.
const peer = vi.fn(() => {
throw new Error('peer down');
});
bm.addSessionStartedListener(peer);
bm.subscribeSessions({ started: peer });
const sub = vi.fn();
wiring.bus.subscribe(sub);
+1
View File
@@ -2,6 +2,7 @@
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist",
"allowImportingTsExtensions": true,
// Tests live outside src/ so we don't pin rootDir; tsc --noEmit doesn't write output anyway.
"types": ["node", "vitest/globals"],
"paths": {