peppa/apps/web/app/(app)/observability/[id]/page.tsx
peppa-bot ffd4e4c171 PEP-202: Observability — сервис мониторингов peppa-observer, раздел для суперадмина, MCP
Сервис peppa-observer (своя база observe.db, журнал 7 дней): мониторинги HTTP(S),
TCP, DNS (системный против 1.1.1.1), «Интернет», heartbeat; состояние меняется
после N неудач/удач подряд, одно сообщение в канал платформы на смену, упавшие
вместе с интернетом молчат. Раздел /observability и MCP-инструменты — только
суперадмину и агентам платформы. Встроенные: «Интернет», «eGov relay» (HTTP, DNS).
Проверка сети из вачдога (PEP-201) переехала сюда.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:15:36 +05:00

136 lines
7.4 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, Trash2 } from "lucide-react";
import { describeTarget, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } 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 { deleteMonitorAction, pauseMonitorAction, updateMonitorAction } from "../actions";
export const dynamic = "force-dynamic";
const PAGE = 100;
const when = (iso: string) => new Date(iso).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" });
export default async function MonitorPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; page?: string }> }) {
const user = await requireUser();
const t = await getT();
if (!(await isSuperadmin(db, user))) notFound();
const { id } = await params;
const { error, page } = await searchParams;
const found = getMonitor(Number(id));
if (!found) notFound();
const m = monitorView(found);
const p = Math.max(0, Number(page) || 0);
const checks = monitorChecks(m.id, { limit: PAGE + 1, offset: p * PAGE });
const incidents = monitorIncidents(m.id);
const web = loadEnv().PEPPA_WEB_URL;
return (
<Workspace>
<AutoRefresh everyMs={15_000} />
<div className="max-w-4xl">
<Flash error={error} />
<PageHeader
crumbs={<Link href="/observability" className="hover:underline">{t("Observability")}</Link>}
title={<><Activity className="mr-1 inline size-5 text-primary" />{m.name}</>}
>
<span className="flex flex-wrap items-center gap-2">
<StateBadge m={m} t={t} />
<span>{t(KIND_LABEL[m.kind])}</span>
<span className="font-mono text-xs break-all">{describeTarget(m, web)}</span>
</span>
</PageHeader>
<Card className="mb-4 gap-2 py-3">
<div className="flex flex-wrap items-center gap-4 text-sm">
<span>{t("Аптайм 24 ч:")} <b>{pct(m.uptime24h)}</b></span>
<span>{t("7 дней:")} <b>{pct(m.uptime7d)}</b></span>
<span className="text-muted-foreground">{m.stateSince ? t("в этом состоянии {ago}", { ago: ago(new Date(m.stateSince), t) }) : ""}</span>
<span className="ml-auto"><CheckStrip recent={m.recent} t={t} /></span>
</div>
{m.lastDetail?.reason ? <p className="m-0 text-sm text-destructive">{String(m.lastDetail.reason)}</p> : null}
{m.kind === "heartbeat" && (
<p className="m-0 text-xs text-muted-foreground">
{t("Сервис отмечается запросом GET или POST по адресу:")} <code className="break-all">{describeTarget(m, web)}</code>
</p>
)}
<p className="m-0 text-xs text-muted-foreground">
{t("Раз в {n} с · «не работает» после {f} неудач подряд · «работает» после {r} удач · создал {who}", { n: m.intervalSec, f: m.failThreshold, r: m.recoverThreshold, who: m.createdBy })}
</p>
<div className="flex flex-wrap gap-2">
<form action={pauseMonitorAction}>
<Hidden fields={{ id: m.id, paused: m.paused ? "0" : "1", back: `/observability/${m.id}` }} />
<Button size="sm" variant="outline">{m.paused ? <><Play />{t("Продолжить")}</> : <><Pause />{t("Пауза")}</>}</Button>
</form>
<Disclosure summary={<span className="flex items-center gap-1.5 text-sm"><Trash2 className="size-4" />{t("Удалить")}</span>}>
<form action={deleteMonitorAction} className="flex items-center gap-2">
<Hidden fields={{ id: m.id, confirm: "1" }} />
<span className="text-sm">{t("Удалить мониторинг вместе с журналом?")}</span>
<Button size="sm" variant="destructive">{t("Да, удалить")}</Button>
</form>
</Disclosure>
</div>
<Disclosure summary={t("Изменить")}>
<form action={updateMonitorAction} className="flex flex-col gap-2">
<Hidden fields={{ id: m.id }} />
<MonitorFields t={t} m={m} kindFixed />
<Button size="sm" variant="default" className="self-start">{t("Сохранить")}</Button>
</form>
</Disclosure>
</Card>
<Section title={t("Сбои за неделю")} count={incidents.length}>
{incidents.length === 0 ? (
<Empty>{t("Сбоев не было.")}</Empty>
) : (
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
{incidents.map((i) => (
<li key={i.id} className="flex flex-wrap gap-2">
<StateBadge m={{ state: i.state, paused: false }} t={t} />
<span>{when(i.startedAt)} → {i.endedAt ? when(i.endedAt) : t("сейчас")}</span>
<span className="text-muted-foreground">{i.reason}</span>
{i.quiet && <span className="text-xs text-muted-foreground">{t("(вместе с интернетом, без сообщения)")}</span>}
</li>
))}
</ul>
)}
</Section>
<Section title={t("Журнал проверок")}>
{checks.length === 0 ? (
<Empty>{t("Проверок ещё не было.")}</Empty>
) : (
<div className="overflow-x-auto">
<table className="w-full text-xs">
<tbody>
{checks.slice(0, PAGE).map((c) => (
<tr key={c.id} className="border-b border-border/50">
<td className="py-1 pr-3 whitespace-nowrap text-muted-foreground">{when(c.at)}</td>
<td className={`py-1 pr-3 whitespace-nowrap ${!c.ok ? "text-destructive" : c.degraded ? "text-warn" : "text-ok"}`}>{!c.ok ? t("неудача") : c.degraded ? t("нестабильно") : "ok"}</td>
<td className="py-1 pr-3 whitespace-nowrap text-muted-foreground">{c.latencyMs != null ? t("{n} мс", { n: c.latencyMs }) : ""}</td>
<td className="py-1">{String(c.detail.reason ?? "")}{c.detail.status != null ? ` · ${c.detail.status}` : ""}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="mt-2 flex gap-3 text-sm">
{p > 0 && <Link href={`/observability/${m.id}?page=${p - 1}`} className="hover:underline">{t("← новее")}</Link>}
{checks.length > PAGE && <Link href={`/observability/${m.id}?page=${p + 1}`} className="hover:underline">{t("старее →")}</Link>}
</div>
</Section>
</div>
</Workspace>
);
}