124 lines
7.7 KiB
TypeScript
124 lines
7.7 KiB
TypeScript
// glossary-ignore-file: the section is for the superadmin only.
|
||
import Link from "next/link";
|
||
import { notFound } from "next/navigation";
|
||
import { Activity, Pause, Play, Plus } from "lucide-react";
|
||
import { describeTarget, isSuperadmin, listMonitorViews, requestSummary } from "@peppa/core";
|
||
import { loadEnv } from "@peppa/shared";
|
||
import { AutoRefresh } from "@/components/AutoRefresh";
|
||
import { Hidden } from "@/components/cards";
|
||
import { CheckStrip, KIND_LABEL, MonitorFields, pct, StateBadge } from "@/components/Observability";
|
||
import { ago, Disclosure, Empty, Flash, PageHeader, Section } from "@/components/common";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Card } from "@/components/ui/card";
|
||
import { Workspace } from "@/components/Workspace";
|
||
import { requireUser } from "@/lib/auth";
|
||
import { db } from "@/lib/db";
|
||
import { getT } from "@/lib/i18n";
|
||
import { createMonitorAction, pauseMonitorAction } from "./actions";
|
||
|
||
export const dynamic = "force-dynamic";
|
||
|
||
|
||
export async function generateMetadata() {
|
||
const t = await getT();
|
||
return { title: t("Observability — Peppa FACTORY") };
|
||
}
|
||
|
||
export default async function Observability({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||
const user = await requireUser();
|
||
const t = await getT();
|
||
if (!(await isSuperadmin(db, user))) notFound();
|
||
const { error } = await searchParams;
|
||
const monitors = listMonitorViews();
|
||
const speed = requestSummary();
|
||
const ms = (n: number) => (n >= 1000 ? t("{n} с", { n: (n / 1000).toFixed(1) }) : t("{n} мс", { n: Math.round(n) }));
|
||
const web = loadEnv().PEPPA_WEB_URL;
|
||
const down = monitors.filter((m) => !m.paused && m.state === "down").length;
|
||
const degraded = monitors.filter((m) => !m.paused && m.state === "degraded").length;
|
||
return (
|
||
<Workspace>
|
||
<AutoRefresh everyMs={15_000} />
|
||
<div className="max-w-4xl">
|
||
<Flash error={error} />
|
||
<PageHeader title={<><Activity className="mr-1 inline size-5 text-primary" />{t("Observability")}</>}>
|
||
{t("Мониторинги сервисов, от которых зависит Peppa FACTORY, и интернета на её сервере. Смена состояния — одно сообщение в Telegram-канал платформы. Журнал проверок хранится 7 дней. Мониторинги можно создавать здесь и через MCP; раздел видят только суперадмины.")}
|
||
</PageHeader>
|
||
|
||
<Section title={t("Мониторинги")} count={monitors.length} actions={down || degraded ? <span className="text-sm text-muted-foreground">{t("не работает: {n} · нестабильно: {m}", { n: down, m: degraded })}</span> : undefined}>
|
||
{monitors.length === 0 ? (
|
||
<Empty>{t("Мониторингов нет. Сервис мониторингов создаст встроенные при первом запуске.")}</Empty>
|
||
) : (
|
||
<div className="flex flex-col gap-2">
|
||
{monitors.map((m) => (
|
||
<Card key={m.id} className="gap-1.5 py-3">
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<StateBadge m={m} t={t} />
|
||
<Link href={`/observability/${m.id}`} className="font-semibold hover:underline">{m.name}</Link>
|
||
<span className="text-xs text-muted-foreground">{t(KIND_LABEL[m.kind])}</span>
|
||
<span className="ml-auto flex items-center gap-3 text-xs text-muted-foreground">
|
||
<span title={t("Аптайм за 24 часа")}>{t("24 ч")} {pct(m.uptime24h)}</span>
|
||
<span title={t("Аптайм за 7 дней")}>{t("7 д")} {pct(m.uptime7d)}</span>
|
||
</span>
|
||
</div>
|
||
<div className="flex flex-wrap items-center gap-3">
|
||
<span className="min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground">{describeTarget(m, web)}</span>
|
||
<CheckStrip recent={m.recent} t={t} />
|
||
</div>
|
||
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||
{m.lastDetail?.reason ? <span className={m.state === "down" ? "text-destructive" : "text-warn"}>{String(m.lastDetail.reason)}</span> : null}
|
||
<span>{m.lastCheckAt ? t("проверен {ago}", { ago: ago(new Date(m.lastCheckAt), t) }) : t("ещё не проверялся")}</span>
|
||
<form action={pauseMonitorAction} className="ml-auto">
|
||
<Hidden fields={{ id: m.id, paused: m.paused ? "0" : "1", back: "/observability" }} />
|
||
<Button size="sm" variant="ghost">{m.paused ? <><Play />{t("Продолжить")}</> : <><Pause />{t("Пауза")}</>}</Button>
|
||
</form>
|
||
</div>
|
||
</Card>
|
||
))}
|
||
</div>
|
||
)}
|
||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />{t("Новый мониторинг")}</span>}>
|
||
<form action={createMonitorAction} className="flex flex-col gap-2">
|
||
<MonitorFields t={t} />
|
||
<Button size="sm" variant="default" className="self-start">{t("Создать")}</Button>
|
||
</form>
|
||
</Disclosure>
|
||
</Section>
|
||
|
||
<Section title={t("Скорость страниц")} count={speed.length}>
|
||
<p className="mb-2 text-sm text-muted-foreground">{t("Страницы и действия за последние 24 часа: сколько раз открывали, как долго отвечали и какая часть времени ушла на базу данных. Медленные запросы приходят в Bugsink сами. Числа считаются с последнего перезапуска сайта.")}</p>
|
||
{speed.length === 0 ? (
|
||
<Empty>{t("Пока нет данных: сайт открывали недавно.")}</Empty>
|
||
) : (
|
||
<div className="overflow-x-auto">
|
||
<table className="w-full text-sm">
|
||
<thead>
|
||
<tr className="text-left text-xs text-muted-foreground">
|
||
<th className="py-1 pr-3 font-medium">{t("Страница")}</th>
|
||
<th className="px-2 text-right font-medium">{t("Запросов")}</th>
|
||
<th className="px-2 text-right font-medium">{t("Типичный (p50)")}</th>
|
||
<th className="px-2 text-right font-medium">{t("Медленные (p95)")}</th>
|
||
<th className="px-2 text-right font-medium">{t("Дольше всех")}</th>
|
||
<th className="pl-2 text-right font-medium">{t("Доля базы")}</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{speed.map((r) => (
|
||
<tr key={r.route} className="border-t border-border">
|
||
<td className="py-1 pr-3 font-mono text-xs">{r.route}</td>
|
||
<td className="px-2 text-right tabular-nums">{r.count}</td>
|
||
<td className="px-2 text-right tabular-nums">{ms(r.p50)}</td>
|
||
<td className={`px-2 text-right tabular-nums ${r.p95 >= 1500 ? "text-warn" : ""}`}>{ms(r.p95)}</td>
|
||
<td className="px-2 text-right tabular-nums">{ms(r.max)}</td>
|
||
<td className="pl-2 text-right tabular-nums">{Math.round(r.sqlShare * 100)}%</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
)}
|
||
</Section>
|
||
</div>
|
||
</Workspace>
|
||
);
|
||
}
|