fix(webui): stop idle polling and release background timers

This commit is contained in:
手瓜一十雪 committed 2026-10-18 13:49:48 +08:00
1 parent 652b9c4eda
commit 0f358b2ac2
8 files changed
+257 -131

No files matched your search

+24 -33
View File
@@ -1,16 +1,3 @@
/**
* Connection-status diff loop. OneBot adapters don't have an internal
* event-emitter for connection state (listening / connected / client-count
* changes), so this loop polls `getConnectionStatuses()` and publishes
* `connections` to the StateBus when the JSON-serialised snapshot changes
* vs the previous tick.
*
* Cheap (500ms default cadence, 1-3 accounts, ~hundreds of bytes), only
* fires the StateBus when state actually moves — so the SSE handler only
* pushes a fresh `connections` frame when the user would actually see
* something update.
*/
import { createLogger, runWithTraceRequest } from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import type { StateBus } from './state-bus';
@@ -33,15 +20,12 @@ export interface ConnectionDiffLoopOptions {
intervalMs?: number;
}
export interface ConnectionDiffLoopHandle {
/** Stop the loop. Subsequent snapshot mutations produce nothing. */
dispose(): void;
}
export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): ConnectionDiffLoopHandle {
/** One shared loop while clients subscribe; each subscription returns its release handle. */
export function createConnectionPoller(opts: ConnectionDiffLoopOptions): () => () => void {
const intervalMs = opts.intervalMs ?? 500;
let lastSerialized: string | undefined | null = null;
let disposed = false;
let subscribers = 0;
let timer: ReturnType<typeof setInterval> | null = null;
// One-shot diagnostic latch: a projector that starts throwing only after
// a shape regression would otherwise wedge the baseline silently — no
// publishes, no log, no symptom besides "the dashboard's connections
@@ -50,7 +34,7 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
let warnedProjectorThrew = false;
const tick = (): void => {
if (disposed) {
if (subscribers === 0) {
return;
}
@@ -137,21 +121,28 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
});
};
const timer = setInterval(tick, intervalMs);
// Don't pin the Node event loop: the loop is permanent for the server
// 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();
return () => {
if (subscribers++ === 0) {
lastSerialized = null;
tick();
timer = setInterval(tick, intervalMs);
timer.unref();
}
return {
dispose(): void {
if (disposed) {
let subscribed = true;
return () => {
if (!subscribed) {
return;
}
disposed = true;
clearInterval(timer);
},
subscribed = false;
if (--subscribers === 0 && timer !== null) {
clearInterval(timer);
timer = null;
lastSerialized = null;
}
};
};
}
+13 -42
View File
@@ -81,7 +81,7 @@ import { buildStreamInvokeResponse, streamUploadToDisk } from './debug-tools';
import { sseResponse as createSseResponse } from './sse-response';
import { bindStateStream } from './state-stream';
import type { StateBus, StateResource } from './state-bus';
import { startConnectionDiffLoop } from './connection-diff-loop';
import { createConnectionPoller } from './connection-diff-loop';
import { comparableConnectionSnapshot } from './connection-snapshot';
import { traceAuthenticatedWebuiMutation } from './mutation-trace';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
@@ -663,40 +663,6 @@ export async function initWebUI(
// rate-limit bucketing; this resolver fails closed with an empty address.
const getSecurityClientIp = makeClientIpResolver(trustProxyMode, '');
// Connection-status diff loop: OneBot adapters don't emit events for
// listening/connected/client-count changes, so we poll the snapshot at
// 500ms and publish 'connections' to the StateBus when it actually
// moves. One loop per server lifetime, lives until process exit (the
// setInterval is .unref'd inside the loop so it doesn't pin the event
// loop on shutdown).
//
// `pickComparable` strips `adapter.detail` — that's a localised human
// string assembled with HH:MM:SS timestamps from the last webhook
// delivery; including it in the diff would make every webhook event
// produce a publish (defeating the diff). We compare name + kind + status,
// plus the structured `lastErrorAt`: a new apply failure must refresh its
// error/time even when the adapter was already degraded. The SSE handler
// still ships the FULL snapshot (with `detail` and `lastError`) — it's only
// the diff key that's pruned.
//
// Trade-off: the rendered detail string (e.g. "3 个客户端", "上次推送
// 14:53:01") only refreshes on the next SSE push or on the 30s REST
// reconcile — not in real time. The user's original reported bugs were
// about process / account edges (which DO push instantly); refreshing
// adapter detail strings at sub-second cadence wasn't required. If it
// becomes one, surface client-count as a structured field on
// AdapterStatus and include it in the comparable.
let connectionDiffLoop: ReturnType<typeof startConnectionDiffLoop> | undefined;
if (listener.stateBus) {
connectionDiffLoop = startConnectionDiffLoop({
bus: listener.stateBus,
getSnapshot: () => oneBotManager.getConnectionStatuses(),
pickComparable: comparableConnectionSnapshot,
intervalMs: 500,
});
}
// Actual bound port (set just before serve; findAvailablePort may bump it).
// Read by GET /api/system/settings so the panel shows what's really live.
let boundPort = desiredPort;
@@ -850,11 +816,6 @@ 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();
// ─── Login ───────────────────────────────────────────────────────────────
app.post('/api/login', async (c) => {
const ip = getClientIp(c);
@@ -1802,8 +1763,15 @@ export async function initWebUI(
// connection-status diff loop). 50ms per-resource debounce coalesces a
// burst (e.g. multiple HookSessions flipping status simultaneously).
const stateBus = listener.stateBus;
const subscribeConnections =
stateBus &&
createConnectionPoller({
bus: stateBus,
getSnapshot: () => oneBotManager.getConnectionStatuses(),
pickComparable: comparableConnectionSnapshot,
});
app.get('/api/state/stream', (c) => {
if (!stateBus) {
if (!stateBus || !subscribeConnections) {
// Build without state-wiring (e.g. a future headless mode) — clients
// fall back to the REST endpoints. Treat as endpoint-not-here.
return c.text('state stream not configured', 503);
@@ -1811,6 +1779,7 @@ export async function initWebUI(
const liveBus = stateBus;
return sseResponse(c, (ch) => {
ch.onClose(subscribeConnections());
const pushFrame = createFramePusher({
desiredSize: ch.desiredSize,
enqueue: ch.raw,
@@ -2352,10 +2321,12 @@ export async function initWebUI(
},
);
});
const tokenJanitor = setInterval(purgeExpiredTokens, 60_000);
tokenJanitor.unref();
return {
port: finalPort,
async stop() {
connectionDiffLoop?.dispose();
clearInterval(tokenJanitor);
shutdownStreams.abort();
await new Promise<void>((resolve, reject) => {
listeningServer.close((err) => (err ? reject(err) : resolve()));
@@ -1,12 +1,57 @@
import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { StateBus } from '../src/webui/state-bus';
import { startConnectionDiffLoop } from '../src/webui/connection-diff-loop';
import {
createConnectionPoller,
type ConnectionDiffLoopOptions,
} from '../src/webui/connection-diff-loop';
import { comparableConnectionSnapshot } from '../src/webui/connection-snapshot';
const previousLogLevel = getLogLevel();
describe('startConnectionDiffLoop', () => {
function startConnectionDiffLoop(options: ConnectionDiffLoopOptions) {
return { dispose: createConnectionPoller(options)() };
}
describe('connection polling', () => {
it('shares one timer and releases it with the last subscriber', () => {
const bus = new StateBus();
const getSnapshot = vi.fn(() => []);
const subscribe = createConnectionPoller({ bus, getSnapshot });
vi.advanceTimersByTime(1000);
expect(getSnapshot).not.toHaveBeenCalled();
expect(vi.getTimerCount()).toBe(0);
const releaseFirst = subscribe();
const releaseSecond = subscribe();
expect(getSnapshot).toHaveBeenCalledOnce();
expect(vi.getTimerCount()).toBe(1);
releaseFirst();
releaseFirst();
vi.advanceTimersByTime(500);
expect(getSnapshot).toHaveBeenCalledTimes(2);
releaseSecond();
expect(vi.getTimerCount()).toBe(0);
vi.advanceTimersByTime(1000);
expect(getSnapshot).toHaveBeenCalledTimes(2);
});
it('takes a fresh baseline on resubscription and detects changes from the first interval', () => {
const bus = new StateBus();
const publish = vi.spyOn(bus, 'publish');
let snapshot = 'initial';
const subscribe = createConnectionPoller({ bus, getSnapshot: () => snapshot });
const release = subscribe();
snapshot = 'connected';
vi.advanceTimersByTime(500);
expect(publish).toHaveBeenCalledOnce();
release();
snapshot = 'offline';
const releaseNext = subscribe();
vi.advanceTimersByTime(500);
expect(publish).toHaveBeenCalledOnce();
releaseNext();
});
it('treats an undefined snapshot as an established baseline', () => {
vi.useFakeTimers();
const bus = new StateBus();
@@ -26,6 +71,7 @@ describe('startConnectionDiffLoop', () => {
});
afterEach(() => {
setLogLevel(previousLogLevel);
vi.clearAllTimers();
vi.useRealTimers();
});
@@ -169,7 +215,7 @@ describe('startConnectionDiffLoop', () => {
}
});
it('first tick baselines the snapshot (no publish); only the second tick with a different value publishes', () => {
it('publishes only when the current snapshot differs from the subscription baseline', () => {
const bus = new StateBus();
const seen: string[] = [];
bus.subscribe((r) => seen.push(r));
@@ -181,7 +227,7 @@ describe('startConnectionDiffLoop', () => {
getSnapshot: () => snap,
intervalMs: 500,
});
vi.advanceTimersByTime(500); // first observation — baseline, no publish
vi.advanceTimersByTime(500);
expect(seen).toEqual([]);
snap = [
{ uin: '12345', nickname: 'me', adapters: [{ kind: 'http', status: 'connected' }] },
@@ -0,0 +1,63 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { OneBotManager } from '@snowluma/onebot/manager';
import { initWebUI } from '../src/webui/server';
import { StateBus } from '../src/webui/state-bus';
import { findAvailablePort } from '../src/webui/port';
vi.mock('@hono/node-server', () => ({
serve: vi.fn((_options: unknown, onListen: (info: { port: number }) => void) => {
queueMicrotask(() => onListen({ port: 5099 }));
return { close: (done: () => void) => done() };
}),
}));
vi.mock('../src/webui/port', () => ({
findAvailablePort: vi.fn(async () => 5099),
}));
beforeEach(() => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });
vi.stubEnv('SNOWLUMA_DEV_MODE', '1');
});
afterEach(() => {
vi.clearAllTimers();
vi.useRealTimers();
vi.unstubAllEnvs();
});
describe('WebUI background tasks', () => {
it('releases token maintenance when the server stops', async () => {
const server = await initWebUI(5099, {} as OneBotManager);
expect(vi.getTimerCount()).toBe(1);
await server.stop();
expect(vi.getTimerCount()).toBe(0);
});
it('does not poll connections without a client and releases maintenance on stop', async () => {
const getConnectionStatuses = vi.fn(() => []);
const manager = { getConnectionStatuses } as unknown as OneBotManager;
const server = await initWebUI(5099, manager, undefined, undefined, {
stateBus: new StateBus(),
});
try {
await vi.advanceTimersByTimeAsync(60_000);
expect(getConnectionStatuses).not.toHaveBeenCalled();
} finally {
await server.stop();
}
expect(vi.getTimerCount()).toBe(0);
});
it('does not leave background tasks after startup fails', async () => {
vi.mocked(findAvailablePort).mockRejectedValueOnce(new Error('no port'));
await expect(
initWebUI(5099, {} as OneBotManager, undefined, undefined, {
stateBus: new StateBus(),
}),
).rejects.toThrow('no port');
expect(vi.getTimerCount()).toBe(0);
});
});