fix(core): close Bridges on exit without a fake offline

This commit is contained in:
DrSmoothl committed 2026-08-17 00:08:21 +08:00
1 parent 27284fd79b
commit d5f1e35c31
9 files changed
+92 -8

No files matched your search

+8 -1
View File
@@ -68,7 +68,9 @@ export type HookSessionDeps = {
* *
* Emitted events: * Emitted events:
* 'login' (uin, packetSender) — real-UIN login detected * 'login' (uin, packetSender) — real-UIN login detected
* 'disconnected' (wasLoggedIn) — connection dropped or torn down * 'disconnected' (wasLoggedIn) — connection dropped, torn down, or
* dispose() of a logged-in session
* (process shutdown uses this path)
* 'receive-health-changed' (healthy) — combined receive/request path health changed * 'receive-health-changed' (healthy) — combined receive/request path health changed
* 'status-changed' (status, error) — status field mutated * 'status-changed' (status, error) — status field mutated
* 'disposed' () — session stopped tracking this PID * 'disposed' () — session stopped tracking this PID
@@ -237,8 +239,13 @@ export class HookSession extends EventEmitter {
dispose(): void { dispose(): void {
if (this.disposed) return; if (this.disposed) return;
const wasLoggedIn = this.loggedIn;
this.disposed = true; this.disposed = true;
this.tearDownClient(); this.tearDownClient();
// Process shutdown must take the same PID-detach path as a live drop.
// tearDownClient strips the pipe client first, so this emit is the only
// disconnected edge HookManager will see.
if (wasLoggedIn) this.emit('disconnected', true);
this.removeAllListeners(); this.removeAllListeners();
} }
@@ -644,6 +644,40 @@ describe('HookSession — process gone', () => {
}); });
}); });
describe('HookSession — dispose', () => {
it('emits disconnected(true) while logged in so BridgeManager can detach the PID', async () => {
const ctx = makeSession({ pipeLive: true });
const discSpy = vi.fn();
ctx.session.on('disconnected', discSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
ctx.session.dispose();
expect(discSpy).toHaveBeenCalledOnce();
expect(discSpy).toHaveBeenCalledWith(true);
expect(ctx.session.isDisposed).toBe(true);
});
it('does not emit disconnected when disposed before login', async () => {
const ctx = makeSession({ pipeLive: true });
const discSpy = vi.fn();
ctx.session.on('disconnected', discSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.session.dispose();
expect(discSpy).not.toHaveBeenCalled();
expect(ctx.session.isDisposed).toBe(true);
});
});
describe('HookSession — refresh drift fix', () => { describe('HookSession — refresh drift fix', () => {
// refresh while the pipe is down on a connected-but-never-logged-in // refresh while the pipe is down on a connected-but-never-logged-in
// session now reports 'connecting' (matching what onPipeDown gives for the // session now reports 'connecting' (matching what onPipeDown gives for the
+7 -4
View File
@@ -118,14 +118,17 @@ async function main() {
exitCode = 1; exitCode = 1;
log.error('notification shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error)); log.error('notification shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
} }
try { hookManager.dispose(); } catch (error) { // Observers go deaf before Hook teardown. Hook dispose then emits the
exitCode = 1; // same disconnected → PID detach → Bridge closed path as a live drop;
log.error('hook shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error)); // those closed edges must not look like a runtime offline.
}
try { stateWiring.dispose(); } catch (error) { try { stateWiring.dispose(); } catch (error) {
exitCode = 1; exitCode = 1;
log.error('state wiring shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error)); log.error('state wiring shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
} }
try { hookManager.dispose(); } catch (error) {
exitCode = 1;
log.error('hook shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
}
await closeLogger(); await closeLogger();
process.exit(exitCode); process.exit(exitCode);
}; };
@@ -74,6 +74,7 @@ export class NotificationManager {
private readonly nicknames = new Map<string, string>(); private readonly nicknames = new Map<string, string>();
private readonly history: DeliveryRecord[] = []; private readonly history: DeliveryRecord[] = [];
private readonly historyLimit: number; private readonly historyLimit: number;
private disposed = false;
constructor(deps: NotificationManagerDeps) { constructor(deps: NotificationManagerDeps) {
this.deps = deps; this.deps = deps;
@@ -88,11 +89,13 @@ export class NotificationManager {
} }
handleOnline(uin: string, nickname?: string): void { handleOnline(uin: string, nickname?: string): void {
if (this.disposed) return;
if (nickname) this.nicknames.set(uin, nickname); if (nickname) this.nicknames.set(uin, nickname);
this.apply(uin, this.machine.onOnline(uin)); this.apply(uin, this.machine.onOnline(uin));
} }
handleOffline(uin: string, nickname?: string): void { handleOffline(uin: string, nickname?: string): void {
if (this.disposed) return;
if (nickname) this.nicknames.set(uin, nickname); if (nickname) this.nicknames.set(uin, nickname);
this.apply(uin, this.machine.onOffline(uin, this.debounceSeconds())); this.apply(uin, this.machine.onOffline(uin, this.debounceSeconds()));
} }
@@ -221,6 +224,8 @@ export class NotificationManager {
} }
dispose(): void { dispose(): void {
if (this.disposed) return;
this.disposed = true;
for (const timer of this.timers.values()) clearTimeout(timer); for (const timer of this.timers.values()) clearTimeout(timer);
this.timers.clear(); this.timers.clear();
} }
+3 -2
View File
@@ -14,8 +14,9 @@
* listeners directly so `qq-list` + `connections` invalidate at the right * listeners directly so `qq-list` + `connections` invalidate at the right
* moment without modifying BridgeManager. * moment without modifying BridgeManager.
* *
* `dispose()` unwires everything so a test (or a future hot-reload) can * `dispose()` sets a latch and neuters the bus. BridgeManager listeners stay
* recreate the wiring without leaking listeners. * 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 { StateBus } from './state-bus';
@@ -196,4 +196,13 @@ describe('NotificationManager — debounce integration (fake timers)', () => {
await vi.advanceTimersByTimeAsync(0); await vi.advanceTimersByTimeAsync(0);
expect(events).toEqual(['offline']); expect(events).toEqual(['offline']);
}); });
it('ignores online/offline after dispose so process exit is not a runtime drop', async () => {
const { events, mgr } = setup(0);
mgr.dispose();
mgr.handleOnline('123', 'Bob');
mgr.handleOffline('123', 'Bob');
await vi.advanceTimersByTimeAsync(0);
expect(events).toEqual([]);
});
}); });
@@ -43,7 +43,7 @@ describe('createStateWiring', () => {
expect(sub).toHaveBeenNthCalledWith(2, 'connections'); expect(sub).toHaveBeenNthCalledWith(2, 'connections');
}); });
it('dispose() unwires onSessionsChanged + BridgeManager listeners (no further publishes)', () => { it('dispose() latches so later Hook/Bridge edges publish nothing', () => {
const wiring = createStateWiring(); const wiring = createStateWiring();
const bm = new BridgeManager(); const bm = new BridgeManager();
wiring.bindBridgeManager(bm); wiring.bindBridgeManager(bm);
+1
View File
@@ -382,6 +382,7 @@ export class OneBotManager {
} }
private onSessionClosed(uin: string): void { private onSessionClosed(uin: string): void {
if (this.disposed) return;
const migration = this.databaseMigrations.get(uin); const migration = this.databaseMigrations.get(uin);
if (migration) { if (migration) {
migration.cancelled = true; migration.cancelled = true;
@@ -513,4 +513,28 @@ describe('OneBotManager lifecycle failure accounting', () => {
await expect(manager.dispose()).rejects.toThrow(/failed to dispose OneBot manager cleanly/); await expect(manager.dispose()).rejects.toThrow(/failed to dispose OneBot manager cleanly/);
}); });
it('ignores session-closed after dispose so process-exit closed does not retire again', async () => {
const manager = new OneBotManager();
const dispose = vi.fn(async () => ({ closed: true, errors: [] }));
const instance = fakeInstance('10001', dispose);
const internals = manager as unknown as {
instances: Map<string, OneBotInstance>;
retiringInstances: Set<OneBotInstance>;
onSessionClosed(uin: string): void;
};
internals.instances.set('10001', instance);
await manager.dispose();
expect(dispose).toHaveBeenCalledOnce();
const lateDispose = vi.fn(async () => ({ closed: true, errors: [] }));
const late = fakeInstance('10001', lateDispose);
internals.instances.set('10001', late);
internals.onSessionClosed('10001');
expect(lateDispose).not.toHaveBeenCalled();
expect(internals.retiringInstances.has(late)).toBe(false);
expect(manager.getInstance('10001')).toBe(late);
});
}); });