feat(ops): auto-poll server for live analytics/monitor updates

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-16 00:34:15 -05:00
parent d8bf5658e6
commit 993433d380

View File

@ -1,6 +1,6 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
Activity,
Bell,
@ -15,11 +15,13 @@ import {
Server,
ShieldCheck,
Users,
Wifi,
} from "lucide-react";
import { Shell } from "@/components/Shell";
import { useToast } from "@/components/Toast";
import { fetchJson, fmtTs } from "@/lib/api";
import { useAutoRefresh, useNow, type RefreshOpts } from "@/lib/realtime";
type Probe = {
ok?: boolean | null;
@ -196,6 +198,7 @@ function MetricList({ title, rows }: { title: string; rows?: { name: string; val
export default function OpsPage() {
const toast = useToast();
const now = useNow(1000);
const [tab, setTab] = useState<"analytics" | "monitor">("analytics");
const [data, setData] = useState<OpsSnapshot | null>(null);
const [overview, setOverview] = useState<OverviewSite[]>([]);
@ -203,39 +206,83 @@ export default function OpsPage() {
const [domain, setDomain] = useState("dylive.nomadro.com");
const [range, setRange] = useState("7d");
const [loading, setLoading] = useState(true);
const [syncing, setSyncing] = useState(false);
const [live, setLive] = useState(true);
const [lastOkAt, setLastOkAt] = useState(0);
const [lastErr, setLastErr] = useState("");
const [busy, setBusy] = useState("");
const [title, setTitle] = useState("DouyinWEB 测试");
const [message, setMessage] = useState("来自 /ops 控制台的 ntfy 测试消息");
const [priority, setPriority] = useState("default");
const loadMonitor = useCallback(async () => {
const r = await fetchJson("/api/ops");
setData(r);
}, []);
const loadAnalytics = useCallback(async () => {
const ov = await fetchJson(`/api/ops/analytics?range=${encodeURIComponent(range)}`);
setOverview(ov?.sites || []);
const d = await fetchJson(
`/api/ops/analytics?range=${encodeURIComponent(range)}&domain=${encodeURIComponent(domain)}`
);
setDetail(d);
}, [domain, range]);
const loadAll = useCallback(async () => {
setLoading(true);
try {
await Promise.all([loadMonitor(), loadAnalytics()]);
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setLoading(false);
}
}, [loadAnalytics, loadMonitor, toast]);
const [pageVisible, setPageVisible] = useState(true);
const inFlight = useRef(false);
const domainRef = useRef(domain);
const rangeRef = useRef(range);
const tabRef = useRef(tab);
domainRef.current = domain;
rangeRef.current = range;
tabRef.current = tab;
useEffect(() => {
void loadAll();
}, [loadAll]);
const onVis = () => setPageVisible(document.visibilityState === "visible");
onVis();
document.addEventListener("visibilitychange", onVis);
return () => document.removeEventListener("visibilitychange", onVis);
}, []);
const loadSilent = useCallback(async (opts?: RefreshOpts) => {
const silent = Boolean(opts?.silent);
if (inFlight.current) return;
inFlight.current = true;
if (!silent) setLoading(true);
else setSyncing(true);
try {
const tasks: Promise<void>[] = [];
// Always keep analytics fresh on analytics tab; monitor on monitor tab;
// still refresh both lightly so switching tabs feels live.
tasks.push(
(async () => {
const ov = await fetchJson(`/api/ops/analytics?range=${encodeURIComponent(rangeRef.current)}`);
setOverview(ov?.sites || []);
const d = await fetchJson(
`/api/ops/analytics?range=${encodeURIComponent(rangeRef.current)}&domain=${encodeURIComponent(domainRef.current)}`
);
setDetail(d);
})()
);
tasks.push(
(async () => {
const r = await fetchJson("/api/ops");
setData(r);
})()
);
await Promise.all(tasks);
setLastOkAt(Date.now());
setLastErr("");
setLive(true);
} catch (e) {
setLive(false);
setLastErr((e as Error).message || "同步失败");
if (!silent) toast.push((e as Error).message, "err");
} finally {
inFlight.current = false;
setLoading(false);
setSyncing(false);
}
}, [toast]);
// Poll server continuously while page is visible (no manual refresh required).
useAutoRefresh(loadSilent, {
intervalMs: tab === "analytics" ? 10000 : 12000,
eventKinds: false,
enabled: pageVisible,
});
// When domain/range/tab changes, pull immediately (silent).
useEffect(() => {
if (!pageVisible) return;
void loadSilent({ silent: true });
}, [domain, range, tab, pageVisible, loadSilent]);
const dnsOkCount = useMemo(() => (data?.sites || []).filter((s) => s.dns_ok).length, [data]);
const svcOkCount = useMemo(() => (data?.services || []).filter((s) => s.ok).length, [data]);
@ -244,6 +291,8 @@ export default function OpsPage() {
[data]
);
const agoSec = lastOkAt ? Math.max(0, Math.floor((now - lastOkAt) / 1000)) : null;
async function sendNtfy() {
setBusy("ntfy");
try {
@ -264,7 +313,7 @@ export default function OpsPage() {
try {
const r = await fetchJson("/api/ops/healthcheck", { method: "POST" });
toast.push(r?.ok ? "健康检查已执行" : `健康检查结束 code=${r?.returncode}`, r?.ok ? "ok" : "err");
await loadMonitor();
await loadSilent({ silent: true });
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
@ -283,18 +332,33 @@ export default function OpsPage() {
<div className="text-[11px] uppercase tracking-[0.18em] text-teal-200/70">Analytics + Ops</div>
<h1 className="font-display text-2xl font-semibold text-white">访问数据与运维</h1>
<p className="mt-1 max-w-2xl text-sm text-slate-400">
Umami 提供类似 Google Analytics 的 PV / 访客 / 来源 / 设备统计(偏隐私、无广告画像)。下方可切换「访问数据」与「监控」。
页面打开时自动与服务器同步(访问数据约 10s、监控约 12s),无需手动刷新。切换标签页离开时暂停轮询。
</p>
<div className="mt-2 flex flex-wrap items-center gap-2 text-[11px]">
<span
className={`inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 ${
live ? "bg-teal-400/15 text-teal-200" : "bg-rose-400/15 text-rose-200"
}`}
>
<Wifi className={`h-3 w-3 ${syncing ? "animate-pulse" : ""}`} />
{pageVisible ? (live ? "实时同步中" : "同步异常") : "已暂停(标签页不可见)"}
</span>
<span className="text-slate-500">
{syncing ? "拉取中…" : agoSec == null ? "等待首次同步" : `上次更新 ${agoSec}s 前`}
</span>
{lastErr ? <span className="truncate text-rose-300">{lastErr}</span> : null}
</div>
</div>
<div className="flex flex-wrap gap-2">
<button
type="button"
disabled={!!busy || loading}
onClick={() => void loadAll()}
disabled={!!busy || syncing}
onClick={() => void loadSilent({ silent: false })}
className="inline-flex items-center gap-1.5 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-slate-200"
title="立即同步一次"
>
<RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
刷新
<RefreshCw className={`h-3.5 w-3.5 ${loading || syncing ? "animate-spin" : ""}`} />
立即同步
</button>
<a
href={data?.umami?.url || "https://umami.nomadro.com"}