From 0f358b2ac247eb49b3b32f1135495cc0a4fe1bc9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Sun, 18 Oct 2026 13:49:48 +0800 Subject: [PATCH] fix(webui): stop idle polling and release background timers --- .../core/src/webui/connection-diff-loop.ts | 57 +++++++---------- packages/core/src/webui/server.ts | 55 ++++------------ .../tests/webui-connection-diff-loop.test.ts | 54 ++++++++++++++-- .../core/tests/webui-server-lifecycle.test.ts | 63 +++++++++++++++++++ packages/webui/README.md | 3 + .../components/overview/deliveries-widget.tsx | 60 +++++------------- packages/webui/src/lib/polling.ts | 37 ++++++++--- packages/webui/tests/polling.test.ts | 59 +++++++++++++++++ 8 files changed, 257 insertions(+), 131 deletions(-) create mode 100644 packages/core/tests/webui-server-lifecycle.test.ts diff --git a/packages/core/src/webui/connection-diff-loop.ts b/packages/core/src/webui/connection-diff-loop.ts index 7df2d0b3..c713280e 100644 --- a/packages/core/src/webui/connection-diff-loop.ts +++ b/packages/core/src/webui/connection-diff-loop.ts @@ -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 | 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; + } + }; }; } diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 534455c8..5fd9eb74 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -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 | 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((resolve, reject) => { listeningServer.close((err) => (err ? reject(err) : resolve())); diff --git a/packages/core/tests/webui-connection-diff-loop.test.ts b/packages/core/tests/webui-connection-diff-loop.test.ts index ef6016ac..b90f6bff 100644 --- a/packages/core/tests/webui-connection-diff-loop.test.ts +++ b/packages/core/tests/webui-connection-diff-loop.test.ts @@ -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' }] }, diff --git a/packages/core/tests/webui-server-lifecycle.test.ts b/packages/core/tests/webui-server-lifecycle.test.ts new file mode 100644 index 00000000..704f5980 --- /dev/null +++ b/packages/core/tests/webui-server-lifecycle.test.ts @@ -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); + }); +}); diff --git a/packages/webui/README.md b/packages/webui/README.md index 97c308d9..c6b7c9ef 100644 --- a/packages/webui/README.md +++ b/packages/webui/README.md @@ -11,6 +11,9 @@ status, OneBot configuration, logs, storage, and server settings. automatically after a visible countdown. - Routine, high-frequency adjustments should not generate a notice for every intermediate edit. +- Foreground polling pauses in hidden tabs and waits for each request to finish + before scheduling the next. Connection-state polling runs only while SSE clients + are subscribed. - Data-backed surfaces use the Interior Skeleton Swap defaults (120 ms delay, 380 ms minimum visibility) so fast local responses do not flash a placeholder. Submission, upload, and other explicit operation progress keeps its spinner. diff --git a/packages/webui/src/components/overview/deliveries-widget.tsx b/packages/webui/src/components/overview/deliveries-widget.tsx index c902de6a..b7f866e0 100644 --- a/packages/webui/src/components/overview/deliveries-widget.tsx +++ b/packages/webui/src/components/overview/deliveries-widget.tsx @@ -7,6 +7,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { SkeletonSwap } from '@/components/interior/skeleton-swap'; import { cn } from '@/lib/utils'; import { useApi } from '@/lib/api'; +import { startPolling } from '@/lib/polling'; import { useTheme } from '@/contexts/ThemeContext'; import type { NotificationDeliveryRecord } from '@/types'; @@ -20,54 +21,27 @@ export function DeliveriesWidget() { useEffect(() => { let active = true; - let inFlight = false; + const stop = startPolling(async () => { + try { + const records = await api.notifications.recent(50); - const pull = () => { - // Skip while the tab is backgrounded, or if a request is still in flight - // (a slow endpoint must not stack overlapping polls). #185. - if (inFlight || document.hidden) { - return; + if (active) { + setLoadError(null); + setRecords(records); + } + } catch (error) { + console.error('load recent notification deliveries failed', error); + + if (active) { + setLoadError(error instanceof Error ? error.message : '加载最近投递失败'); + setRecords((prev) => prev ?? []); + } } - - inFlight = true; - api.notifications - .recent(50) - .then((r) => { - if (active) { - setLoadError(null); - setRecords(r); - } - }) - .catch((error) => { - console.error('load recent notification deliveries failed', error); - - if (active) { - setLoadError(error instanceof Error ? error.message : '加载最近投递失败'); - setRecords((prev) => prev ?? []); - } - }) - .finally(() => { - inFlight = false; - }); - }; - - void pull(); - const id = window.setInterval(() => void pull(), POLL_MS); - - // The interval keeps firing but no-ops while hidden, so refresh immediately - // when the tab becomes visible again to shed any staleness. - const onVisible = () => { - if (!document.hidden) { - pull(); - } - }; - - document.addEventListener('visibilitychange', onVisible); + }, POLL_MS); return () => { active = false; - window.clearInterval(id); - document.removeEventListener('visibilitychange', onVisible); + stop(); }; }, [api]); diff --git a/packages/webui/src/lib/polling.ts b/packages/webui/src/lib/polling.ts index 9bd50f4c..265c9e99 100644 --- a/packages/webui/src/lib/polling.ts +++ b/packages/webui/src/lib/polling.ts @@ -1,13 +1,23 @@ -/** Run immediately, then at the requested cadence without overlapping requests. */ +/** Wait between requests; keep no timer while hidden or awaiting a response. */ export function startPolling( refresh: () => Promise, intervalMs: number, pauseWhenHidden = true, ): () => void { + let stopped = false; let running = false; + let timer: ReturnType | null = null; + const paused = () => pauseWhenHidden && document.hidden; + + const clearTimer = () => { + if (timer !== null) { + clearTimeout(timer); + timer = null; + } + }; const tick = async () => { - if (running || (pauseWhenHidden && document.hidden)) { + if (stopped || running || paused()) { return; } @@ -15,31 +25,40 @@ export function startPolling( try { await refresh(); + } catch (error) { + console.error('polling failed', error); } finally { running = false; + + if (!stopped && !paused() && intervalMs > 0) { + timer = setTimeout(() => { + timer = null; + void tick(); + }, intervalMs); + } } }; void tick(); - const interval = intervalMs > 0 ? setInterval(tick, intervalMs) : null; - const onVisible = () => { + const onVisibilityChange = () => { + clearTimer(); + if (!document.hidden) { void tick(); } }; if (pauseWhenHidden) { - document.addEventListener('visibilitychange', onVisible); + document.addEventListener('visibilitychange', onVisibilityChange); } return () => { - if (interval !== null) { - clearInterval(interval); - } + stopped = true; + clearTimer(); if (pauseWhenHidden) { - document.removeEventListener('visibilitychange', onVisible); + document.removeEventListener('visibilitychange', onVisibilityChange); } }; } diff --git a/packages/webui/tests/polling.test.ts b/packages/webui/tests/polling.test.ts index 699bfd01..49a61900 100644 --- a/packages/webui/tests/polling.test.ts +++ b/packages/webui/tests/polling.test.ts @@ -10,11 +10,70 @@ beforeEach(() => { }); afterEach(() => { + vi.clearAllTimers(); vi.useRealTimers(); vi.unstubAllGlobals(); + vi.restoreAllMocks(); }); describe('resource polling', () => { + it('reports a failed refresh and retries without leaving a second timer', async () => { + const failure = new Error('refresh failed'); + const report = vi.spyOn(console, 'error').mockImplementation(() => {}); + const refresh = vi.fn().mockRejectedValueOnce(failure).mockResolvedValue(undefined); + const stop = startPolling(refresh, 1000); + await vi.advanceTimersByTimeAsync(0); + expect(report).toHaveBeenCalledExactlyOnceWith('polling failed', failure); + expect(vi.getTimerCount()).toBe(1); + await vi.advanceTimersByTimeAsync(1000); + expect(refresh).toHaveBeenCalledTimes(2); + expect(vi.getTimerCount()).toBe(1); + stop(); + }); + + it('does not keep a timer while hidden or waiting for a response', async () => { + page.hidden = true; + const pending = Promise.withResolvers(); + const refresh = vi.fn(() => pending.promise); + const stop = startPolling(refresh, 1000); + expect(vi.getTimerCount()).toBe(0); + page.hidden = false; + page.dispatchEvent(new Event('visibilitychange')); + expect(refresh).toHaveBeenCalledOnce(); + expect(vi.getTimerCount()).toBe(0); + pending.resolve(); + await vi.advanceTimersByTimeAsync(0); + expect(vi.getTimerCount()).toBe(1); + page.hidden = true; + page.dispatchEvent(new Event('visibilitychange')); + expect(vi.getTimerCount()).toBe(0); + stop(); + }); + + it('does not reschedule a request that finishes after disposal', async () => { + const pending = Promise.withResolvers(); + const refresh = vi.fn(() => pending.promise); + const stop = startPolling(refresh, 1000); + stop(); + pending.resolve(); + await vi.advanceTimersByTimeAsync(10_000); + expect(refresh).toHaveBeenCalledOnce(); + expect(vi.getTimerCount()).toBe(0); + }); + + it('waits a full interval after a slow response before polling again', async () => { + const pending = Promise.withResolvers(); + const refresh = vi.fn().mockReturnValueOnce(pending.promise).mockResolvedValue(undefined); + const stop = startPolling(refresh, 1000); + await vi.advanceTimersByTimeAsync(1500); + pending.resolve(); + await vi.advanceTimersByTimeAsync(999); + expect(refresh).toHaveBeenCalledOnce(); + await vi.advanceTimersByTimeAsync(1); + expect(refresh).toHaveBeenCalledTimes(2); + stop(); + }); + it('starts immediately and skips ticks while a request is pending', async () => { const pending = Promise.withResolvers(); const refresh = vi.fn().mockReturnValueOnce(pending.promise).mockResolvedValue(undefined);