fix(webui): stop idle polling and release background timers
This commit is contained in:
1 parent
652b9c4eda
commit
0f358b2ac2
8 files changed
+257
-131
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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]);
|
||||
|
||||
|
||||
@@ -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<unknown>,
|
||||
intervalMs: number,
|
||||
pauseWhenHidden = true,
|
||||
): () => void {
|
||||
let stopped = false;
|
||||
let running = false;
|
||||
let timer: ReturnType<typeof setTimeout> | 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);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -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<void>();
|
||||
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<void>();
|
||||
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<void>();
|
||||
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<void>();
|
||||
const refresh = vi.fn().mockReturnValueOnce(pending.promise).mockResolvedValue(undefined);
|
||||
|
||||
Reference in new issue
Block a user