douyinWEB/frontend/src/app/ops/page.tsx
eric 993433d380 feat(ops): auto-poll server for live analytics/monitor updates
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 00:34:15 -05:00

668 lines
27 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
Activity,
Bell,
BarChart3,
ExternalLink,
Eye,
Globe2,
Loader2,
MousePointerClick,
Radar,
RefreshCw,
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;
status?: number | null;
ms?: number | null;
error?: string;
};
type SiteRow = {
domain: string;
role: string;
kind: string;
ips: string[];
dns_ok: boolean;
expected_ip: string;
umami_website_id?: string;
health: Probe;
};
type ServiceRow = {
unit: string;
label: string;
state: string;
ok: boolean;
};
type OverviewSite = {
domain: string;
role: string;
website_id: string;
ok: boolean;
active: number;
pageviews: number;
visitors: number;
visits: number;
bounces: number;
};
type AnalyticsDetail = {
domain?: string;
website_id?: string;
range?: string;
ok?: boolean;
active?: number;
stats?: {
pageviews?: number;
visitors?: number;
visits?: number;
bounces?: number;
bounce_rate?: number;
avg_visit_sec?: number;
};
series?: { x: string; y: number }[];
top_paths?: { name: string; value: number }[];
top_referrers?: { name: string; value: number }[];
top_countries?: { name: string; value: number }[];
top_devices?: { name: string; value: number }[];
top_browsers?: { name: string; value: number }[];
umami_url?: string;
};
type OpsSnapshot = {
generated_at?: number;
server_ip?: string;
host?: string;
umami?: {
url?: string;
user?: string;
script?: string;
sites?: Record<string, string>;
heartbeat?: Probe;
};
ntfy?: {
configured?: boolean;
base_url?: string;
topic?: string;
user?: string;
has_token?: boolean;
token_suffix?: string;
health?: Probe;
};
sites?: SiteRow[];
services?: ServiceRow[];
paths?: Record<string, string>;
};
const RANGES = [
{ id: "24h", label: "24小时" },
{ id: "7d", label: "7天" },
{ id: "30d", label: "30天" },
{ id: "90d", label: "90天" },
];
function StatusDot({ ok }: { ok?: boolean | null }) {
const color =
ok === true ? "bg-teal-400 shadow-[0_0_10px_rgba(45,212,191,0.55)]" : ok === false ? "bg-rose-400" : "bg-slate-500";
return <span className={`inline-block h-2 w-2 rounded-full ${color}`} />;
}
function ProbeText({ p }: { p?: Probe }) {
if (!p) return <span className="text-slate-500">—</span>;
if (p.ok === true) return <span className="text-teal-300">{p.status ?? "ok"} · {p.ms ?? "?"}ms</span>;
if (p.ok === false)
return (
<span className="text-rose-300">
{p.status ?? "fail"} {p.error ? `· ${p.error}` : ""} {p.ms != null ? `· ${p.ms}ms` : ""}
</span>
);
return <span className="text-slate-500">n/a</span>;
}
function fmtNum(n?: number) {
const v = Number(n || 0);
if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)}M`;
if (v >= 1_000) return `${(v / 1_000).toFixed(1)}k`;
return String(v);
}
function fmtDuration(sec?: number) {
const s = Math.max(0, Math.round(Number(sec || 0)));
if (s < 60) return `${s}s`;
const m = Math.floor(s / 60);
const r = s % 60;
return `${m}m ${r}s`;
}
function Sparkline({ series }: { series?: { x: string; y: number }[] }) {
const pts = series || [];
if (pts.length < 2) {
return <div className="flex h-16 items-center text-xs text-slate-500">暂无趋势数据(站点刚接入时常见)</div>;
}
const ys = pts.map((p) => Number(p.y || 0));
const max = Math.max(...ys, 1);
const min = Math.min(...ys, 0);
const w = 320;
const h = 64;
const path = pts
.map((p, i) => {
const x = (i / (pts.length - 1)) * w;
const y = h - ((Number(p.y || 0) - min) / (max - min || 1)) * (h - 4) - 2;
return `${i === 0 ? "M" : "L"}${x.toFixed(1)},${y.toFixed(1)}`;
})
.join(" ");
return (
<svg viewBox={`0 0 ${w} ${h}`} className="h-16 w-full overflow-visible">
<path d={path} fill="none" stroke="rgba(45,212,191,0.9)" strokeWidth="2" />
</svg>
);
}
function MetricList({ title, rows }: { title: string; rows?: { name: string; value: number }[] }) {
const list = rows || [];
const max = Math.max(...list.map((r) => Number(r.value || 0)), 1);
return (
<div className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="mb-2 text-xs font-medium text-slate-300">{title}</div>
{!list.length && <div className="text-xs text-slate-500">暂无数据</div>}
<ul className="space-y-2">
{list.map((r) => (
<li key={`${title}-${r.name}`}>
<div className="mb-0.5 flex justify-between gap-2 text-[11px]">
<span className="truncate text-slate-200">{r.name || "(direct)"}</span>
<span className="shrink-0 text-slate-400">{fmtNum(r.value)}</span>
</div>
<div className="h-1 overflow-hidden rounded bg-white/5">
<div className="h-full rounded bg-gradient-to-r from-teal-400/80 to-sky-400/70" style={{ width: `${(Number(r.value) / max) * 100}%` }} />
</div>
</li>
))}
</ul>
</div>
);
}
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[]>([]);
const [detail, setDetail] = useState<AnalyticsDetail | null>(null);
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 [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(() => {
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]);
const trackedDomains = useMemo(
() => (data?.sites || []).filter((s) => s.kind !== "infra" && s.umami_website_id).map((s) => s.domain),
[data]
);
const agoSec = lastOkAt ? Math.max(0, Math.floor((now - lastOkAt) / 1000)) : null;
async function sendNtfy() {
setBusy("ntfy");
try {
await fetchJson("/api/ops/ntfy", {
method: "POST",
body: JSON.stringify({ title, message, priority, tags: "bell,desktop" }),
});
toast.push("已发送到 ntfy", "ok");
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy("");
}
}
async function runHealth() {
setBusy("health");
try {
const r = await fetchJson("/api/ops/healthcheck", { method: "POST" });
toast.push(r?.ok ? "健康检查已执行" : `健康检查结束 code=${r?.returncode}`, r?.ok ? "ok" : "err");
await loadSilent({ silent: true });
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy("");
}
}
const st = detail?.stats;
return (
<Shell>
<div className="mx-auto max-w-6xl space-y-5 pb-8">
<div className="rounded-3xl border border-white/10 bg-black/30 p-5">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<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">
页面打开时自动与服务器同步(访问数据约 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 || 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 || syncing ? "animate-spin" : ""}`} />
立即同步
</button>
<a
href={data?.umami?.url || "https://umami.nomadro.com"}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1.5 rounded-xl bg-gradient-to-br from-teal-400 to-sky-500 px-3 py-2 text-xs font-semibold text-[#0b1220]"
>
打开 Umami 完整后台 <ExternalLink className="h-3.5 w-3.5" />
</a>
</div>
</div>
<div className="mt-4 flex flex-wrap gap-2">
<button
type="button"
onClick={() => setTab("analytics")}
className={`rounded-xl px-3 py-1.5 text-xs ${tab === "analytics" ? "bg-teal-400/20 text-teal-200 ring-1 ring-teal-300/30" : "bg-white/5 text-slate-400"}`}
>
<BarChart3 className="mr-1 inline h-3.5 w-3.5" />
访问数据
</button>
<button
type="button"
onClick={() => setTab("monitor")}
className={`rounded-xl px-3 py-1.5 text-xs ${tab === "monitor" ? "bg-amber-400/20 text-amber-100 ring-1 ring-amber-300/30" : "bg-white/5 text-slate-400"}`}
>
<ShieldCheck className="mr-1 inline h-3.5 w-3.5" />
监控 / DNS / ntfy
</button>
</div>
</div>
{tab === "analytics" && (
<>
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<div className="text-sm font-medium text-white">各站点概览</div>
<div className="flex flex-wrap gap-1.5">
{RANGES.map((r) => (
<button
key={r.id}
type="button"
onClick={() => setRange(r.id)}
className={`rounded-lg px-2.5 py-1 text-[11px] ${range === r.id ? "bg-sky-400/20 text-sky-200" : "bg-white/5 text-slate-400"}`}
>
{r.label}
</button>
))}
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{overview.map((s) => (
<button
key={s.domain}
type="button"
onClick={() => setDomain(s.domain)}
className={`rounded-2xl border p-3 text-left transition ${
domain === s.domain ? "border-teal-300/40 bg-teal-400/10" : "border-white/10 bg-white/[0.03] hover:bg-white/[0.05]"
}`}
>
<div className="flex items-center justify-between gap-2">
<div className="truncate text-sm font-medium text-white">{s.domain}</div>
<span className="text-[10px] text-teal-300">在线 {s.active}</span>
</div>
<div className="mt-0.5 truncate text-[11px] text-slate-500">{s.role}</div>
<div className="mt-3 grid grid-cols-3 gap-2 text-center">
<div>
<div className="text-base font-semibold text-white">{fmtNum(s.pageviews)}</div>
<div className="text-[10px] text-slate-500">浏览量</div>
</div>
<div>
<div className="text-base font-semibold text-white">{fmtNum(s.visitors)}</div>
<div className="text-[10px] text-slate-500">访客</div>
</div>
<div>
<div className="text-base font-semibold text-white">{fmtNum(s.visits)}</div>
<div className="text-[10px] text-slate-500">访问</div>
</div>
</div>
</button>
))}
{!overview.length && (
<div className="col-span-full py-8 text-center text-sm text-slate-500">
{loading ? "加载访问数据…" : "暂无概览(确认 Umami 已采集到流量)"}
</div>
)}
</div>
</section>
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<div>
<div className="text-sm font-medium text-white">站点详情 · {domain}</div>
<div className="text-[11px] text-slate-500">类似 GA 的摘要指标与排行</div>
</div>
<select
value={domain}
onChange={(e) => setDomain(e.target.value)}
className="rounded-xl border border-white/10 bg-black/40 px-3 py-1.5 text-xs text-white"
>
{(trackedDomains.length ? trackedDomains : [domain]).map((d) => (
<option key={d} value={d}>
{d}
</option>
))}
</select>
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
{[
{ label: "浏览量 PV", value: fmtNum(st?.pageviews), icon: Eye },
{ label: "独立访客", value: fmtNum(st?.visitors), icon: Users },
{ label: "访问次数", value: fmtNum(st?.visits), icon: MousePointerClick },
{ label: "跳出率", value: `${st?.bounce_rate ?? 0}%`, icon: Activity },
{ label: "平均停留", value: fmtDuration(st?.avg_visit_sec), icon: Radar },
].map((card) => (
<div key={card.label} className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="flex items-center gap-1.5 text-[11px] text-slate-400">
<card.icon className="h-3.5 w-3.5 text-teal-300" />
{card.label}
</div>
<div className="mt-1 text-xl font-semibold text-white">{card.value}</div>
</div>
))}
</div>
<div className="mt-4 rounded-2xl border border-white/10 bg-white/[0.03] p-3">
<div className="mb-1 flex items-center justify-between text-xs text-slate-400">
<span>浏览量趋势</span>
<span className="text-teal-300">当前在线 {detail?.active ?? 0}</span>
</div>
<Sparkline series={detail?.series} />
</div>
<div className="mt-4 grid gap-3 lg:grid-cols-2">
<MetricList title="热门页面" rows={detail?.top_paths} />
<MetricList title="来源 Referrer" rows={detail?.top_referrers} />
<MetricList title="国家 / 地区" rows={detail?.top_countries} />
<MetricList title="设备" rows={detail?.top_devices} />
<MetricList title="浏览器" rows={detail?.top_browsers} />
</div>
</section>
</>
)}
{tab === "monitor" && (
<>
<div className="grid gap-3 sm:grid-cols-3">
<div className="rounded-2xl border border-white/10 bg-black/25 p-3">
<div className="flex items-center gap-2 text-xs text-slate-400">
<Radar className="h-3.5 w-3.5 text-teal-300" /> Umami
</div>
<div className="mt-1 flex items-center gap-2 text-sm text-white">
<StatusDot ok={data?.umami?.heartbeat?.ok} />
<ProbeText p={data?.umami?.heartbeat} />
</div>
</div>
<div className="rounded-2xl border border-white/10 bg-black/25 p-3">
<div className="flex items-center gap-2 text-xs text-slate-400">
<Bell className="h-3.5 w-3.5 text-amber-300" /> ntfy
</div>
<div className="mt-1 flex items-center gap-2 text-sm text-white">
<StatusDot ok={data?.ntfy?.health?.ok} />
<ProbeText p={data?.ntfy?.health} />
</div>
<div className="mt-1 text-[11px] text-slate-500">topic {data?.ntfy?.topic}</div>
</div>
<div className="rounded-2xl border border-white/10 bg-black/25 p-3">
<div className="flex items-center gap-2 text-xs text-slate-400">
<ShieldCheck className="h-3.5 w-3.5 text-sky-300" /> DNS / 服务
</div>
<div className="mt-1 text-sm text-white">
DNS {dnsOkCount}/{data?.sites?.length ?? 0} · 服务 {svcOkCount}/{data?.services?.length ?? 0}
</div>
<button
type="button"
disabled={!!busy}
onClick={() => void runHealth()}
className="mt-2 inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-slate-200"
>
{busy === "health" ? <Loader2 className="h-3 w-3 animate-spin" /> : <Activity className="h-3 w-3" />}
跑健康检查
</button>
</div>
</div>
<div className="grid gap-5 lg:grid-cols-5">
<div className="space-y-5 lg:col-span-3">
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
<Globe2 className="h-4 w-4 text-sky-300" />
域名 · DNS · 探测
</div>
<div className="overflow-x-auto">
<table className="w-full min-w-[640px] text-left text-xs">
<thead className="text-slate-500">
<tr className="border-b border-white/10">
<th className="py-2 pr-2 font-medium">域名</th>
<th className="py-2 pr-2 font-medium">DNS</th>
<th className="py-2 pr-2 font-medium">健康</th>
<th className="py-2 font-medium">Umami ID</th>
</tr>
</thead>
<tbody>
{(data?.sites || []).map((s) => (
<tr key={s.domain} className="border-b border-white/5 align-top">
<td className="py-2.5 pr-2">
<div className="font-medium text-sky-200">{s.domain}</div>
<div className="mt-0.5 text-[11px] text-slate-500">{s.role}</div>
</td>
<td className="py-2.5 pr-2">
<div className="flex items-center gap-1.5">
<StatusDot ok={s.dns_ok} />
<span className={s.dns_ok ? "text-teal-300" : "text-rose-300"}>
{(s.ips || []).join(", ") || "—"}
</span>
</div>
</td>
<td className="py-2.5 pr-2">
<ProbeText p={s.health} />
</td>
<td className="py-2.5 font-mono text-[10px] text-slate-400">{s.umami_website_id || "—"}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
<Server className="h-4 w-4 text-amber-300" />
systemd 服务
</div>
<div className="grid gap-2 sm:grid-cols-2">
{(data?.services || []).map((s) => (
<div
key={s.unit}
className="flex items-center justify-between rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2"
>
<div>
<div className="text-sm text-slate-100">{s.label}</div>
<div className="font-mono text-[10px] text-slate-500">{s.unit}</div>
</div>
<div className="flex items-center gap-2 text-xs">
<StatusDot ok={s.ok} />
<span className={s.ok ? "text-teal-300" : "text-rose-300"}>{s.state}</span>
</div>
</div>
))}
</div>
</section>
</div>
<div className="space-y-5 lg:col-span-2">
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
<Bell className="h-4 w-4 text-amber-300" />
发送 ntfy
</div>
<div className="space-y-2">
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white outline-none"
placeholder="标题"
/>
<textarea
value={message}
onChange={(e) => setMessage(e.target.value)}
rows={4}
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white outline-none"
/>
<select
value={priority}
onChange={(e) => setPriority(e.target.value)}
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white"
>
<option value="min">min</option>
<option value="low">low</option>
<option value="default">default</option>
<option value="high">high</option>
<option value="max">max</option>
</select>
<button
type="button"
disabled={!!busy || !data?.ntfy?.configured}
onClick={() => void sendNtfy()}
className="inline-flex w-full items-center justify-center gap-1.5 rounded-xl bg-gradient-to-br from-amber-300 to-orange-500 px-3 py-2.5 text-sm font-semibold text-[#1a1208] disabled:opacity-50"
>
{busy === "ntfy" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Bell className="h-4 w-4" />}
推送到 {data?.ntfy?.topic || "server-alerts"}
</button>
</div>
<div className="mt-3 text-[11px] text-slate-500">
主机 {data?.host} · {data?.generated_at ? fmtTs(data.generated_at) : ""}
</div>
</section>
</div>
</div>
</>
)}
</div>
</Shell>
);
}