peppa/apps/web/app/(app)/observability/page.tsx
2026-11-23 14:56:43 +00:00

198 lines
12 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.

// 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, observeRemindMin, egovLoginSummary, errorScope, errorsOverview, getLastRetention, isSuperadmin, listErrors, listMonitorViews, requestSummary } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { LiveRefresh } from "@/components/LiveRefresh";
import { Hidden } from "@/components/cards";
import { CheckStrip, KIND_LABEL, MonitorFields, OutageLine, pct, StateBadge } from "@/components/Observability";
import { ErrorFilters, errorFilterFrom, ErrorRows, ErrorsDown, ErrorsSummary } from "@/components/Errors";
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 — FORGE") };
}
type Search = { error?: string; tab?: string; bp?: string; state?: string; env?: string; rel?: string; q?: string; sort?: string; cursor?: string };
/** Tabs «Мониторинги» · «Ошибки» (PEP-218). */
function Tabs({ tab, t }: { tab: "monitors" | "errors"; t: Awaited<ReturnType<typeof getT>> }) {
const cls = (on: boolean) => `border-b-2 px-3 py-1.5 text-sm ${on ? "border-primary font-semibold" : "border-transparent text-muted-foreground hover:text-foreground"}`;
return (
<nav className="mb-4 flex gap-1 border-b">
<Link href="/observability" className={cls(tab === "monitors")}>{t("Мониторинги")}</Link>
<Link href="/observability?tab=errors" className={cls(tab === "errors")}>{t("Ошибки")}</Link>
</nav>
);
}
/** PEP-218: errors of every Bugsink project, read from its REST API on the server. */
async function ErrorsTab({ user, sp }: { user: Awaited<ReturnType<typeof requireUser>>; sp: Search }) {
const t = await getT();
const scope = await errorScope(db, user);
const f = errorFilterFrom(sp);
const [ov, list] = await Promise.all([errorsOverview(db, scope), listErrors(db, scope, f)]);
const query = new URLSearchParams(Object.entries({ tab: "errors", bp: sp.bp, state: sp.state, env: sp.env, rel: sp.rel, q: sp.q, sort: sp.sort }).filter((e): e is [string, string] => !!e[1]));
const from = `/observability?${query}`;
return (
<>
<ErrorsDown down={ov.down || list.down} at={list.at ?? ov.at} tech t={t} />
<Section title={t("Сводка")}>
<ErrorsSummary ov={ov} t={t} hrefFor={(id) => `/observability?tab=errors&bp=${id}`} />
</Section>
{ov.top.length ? (
<Section title={t("Частые и свежие")} count={ov.top.length}>
<ErrorRows rows={ov.top} tech from={from} t={t} />
</Section>
) : null}
<Section title={t("Все ошибки")} count={list.rows.length}>
<ErrorFilters action="/observability" scope={scope} f={f} keep={{ tab: "errors" }} t={t} />
<ErrorRows rows={list.rows} tech from={from} t={t} />
{list.next ? (
<Link href={`/observability?${new URLSearchParams([...query, ["cursor", list.next]])}`} className="mt-2 inline-block text-sm text-primary hover:underline">{t("Дальше →")}</Link>
) : null}
</Section>
</>
);
}
export default async function Observability({ searchParams }: { searchParams: Promise<Search> }) {
const user = await requireUser();
const t = await getT();
if (!(await isSuperadmin(db, user))) notFound();
const sp = await searchParams;
const { error } = sp;
if (sp.tab === "errors") {
return (
<Workspace>
<div className="max-w-4xl">
<Flash error={error} />
<PageHeader title={<><Activity className="mr-1 inline size-5 text-primary" />{t("Observability")}</>}>
{t("Ошибки всех проектов из учёта ошибок (Bugsink): сводка, самые частые и свежие, список с фильтрами. Данные обновляются раз в минуту.")}
</PageHeader>
<Tabs tab="errors" t={t} />
<ErrorsTab user={user} sp={sp} />
</div>
</Workspace>
);
}
const monitors = listMonitorViews();
const egov = await egovLoginSummary(db);
const retention = await getLastRetention(db);
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>
<LiveRefresh scope="observe" />
<div className="max-w-4xl">
<Flash error={error} />
<PageHeader title={<><Activity className="mr-1 inline size-5 text-primary" />{t("Observability")}</>}>
{t("Мониторинги сервисов, от которых зависит FORGE, и интернета на её сервере. Смена состояния — одно сообщение в Telegram-канал платформы, пока не работает — напоминание раз в 30 минут (настраивается у мониторинга). Журнал проверок хранится 7 дней. Мониторинги можно создавать здесь и через MCP; раздел видят только суперадмины.")}
</PageHeader>
<Tabs tab="monitors" t={t} />
{retention && (
<p className="mb-3 text-sm text-muted-foreground">
{t("Уборка журналов: {ago} — удалено строк {n}, база {size} МБ, свободно внутри {free} МБ", { ago: ago(new Date(retention.at), t), n: retention.total, size: (retention.dbBytes / 1048576).toFixed(1), free: (retention.freedBytes / 1048576).toFixed(1) })}
</p>
)}
<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>
{m.name === "eGov relay" ? (
<div className="text-xs text-muted-foreground">
{egov.failed > 0
? t("Входы за сутки: {n}, неудачных {m} ({reasons})", { n: egov.total, m: egov.failed, reasons: egov.byReason.map((r) => `${t(r.reason)}: ${r.n}`).join(", ") })
: t("Входы за сутки: {n}, неудачных нет", { n: egov.total })}
</div>
) : null}
<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}
<OutageLine m={m} t={t} />
<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} remindDefault={observeRemindMin()} />
<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>
);
}