peppa/apps/web/components/Observability.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

95 lines
4.9 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.

// Observability (PEP-202): shared pieces of the monitors list and the monitor page.
// glossary-ignore-file: the section is for the superadmin only.
import type { MonitorKind, MonitorState, MonitorView } from "@peppa/core";
import type { Translator } from "@peppa/shared/i18n";
import { Badge } from "@/components/ui/badge";
import { Input, Label, NativeSelect } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import { m } from "@peppa/shared/i18n";
export const KIND_LABEL: Record<MonitorKind, string> = { http: "HTTP(S)", tcp: "TCP", dns: "DNS", internet: m("Интернет"), heartbeat: "Heartbeat" };
const STATE_LABEL: Record<MonitorState, string> = { up: m("работает"), down: m("не работает"), degraded: m("нестабилен"), unknown: m("проверяется") };
const STATE_VARIANT = { up: "ok", down: "danger", degraded: "warn", unknown: "muted" } as const;
export function StateBadge({ m, t }: { m: Pick<MonitorView, "state" | "paused">; t: Translator }) {
if (m.paused) return <Badge variant="muted">{t("на паузе")}</Badge>;
return <Badge variant={STATE_VARIANT[m.state]}>{t(STATE_LABEL[m.state])}</Badge>;
}
export const pct = (v: number | null) => (v == null ? "—" : `${(v * 100).toFixed(v >= 0.9995 ? 0 : 2)}%`);
/** The last checks as a strip of bars, oldest left. */
export function CheckStrip({ recent, t }: { recent: MonitorView["recent"]; t: Translator }) {
return (
<div className="flex h-5 items-end gap-px" aria-label={t("Последние проверки")}>
{Array.from({ length: Math.max(0, 30 - recent.length) }, (_, i) => (
<span key={`e${i}`} className="h-full w-1.5 rounded-sm bg-muted" />
))}
{recent.map((c) => (
<span key={c.at} title={new Date(c.at).toLocaleString("ru-RU")} className={cn("h-full w-1.5 rounded-sm", !c.ok ? "bg-destructive" : c.degraded ? "bg-warn" : "bg-ok")} />
))}
</div>
);
}
/** Fields of the create / edit form; `where` is read by the kind (address, host, host:port, hosts). */
export function MonitorFields({ t, m, kindFixed }: { t: Translator; m?: MonitorView; kindFixed?: boolean }) {
const tg = (m?.target ?? {}) as Record<string, unknown>;
const where = !m ? "" : m.kind === "http" ? String(tg.url) : m.kind === "tcp" ? `${tg.host}:${tg.port}` : m.kind === "dns" ? String(tg.host) : m.kind === "internet" ? (tg.hosts as string[]).join(", ") : "";
return (
<div className="grid gap-2 sm:grid-cols-2">
<Label>
{t("Название")}
<Input name="name" required maxLength={80} defaultValue={m?.name} placeholder="eGov relay" className="h-8" />
</Label>
<Label>
{t("Вид")}
{kindFixed && m ? (
<>
<input type="hidden" name="kind" value={m.kind} />
<Input value={t(KIND_LABEL[m.kind])} disabled className="h-8" />
</>
) : (
<NativeSelect name="kind" defaultValue={m?.kind ?? "http"} className="h-8">
{(Object.keys(KIND_LABEL) as MonitorKind[]).map((k) => (
<option key={k} value={k}>{t(KIND_LABEL[k])}</option>
))}
</NativeSelect>
)}
</Label>
<Label className="sm:col-span-2">
{t("Адрес")}
<Input name="where" defaultValue={where} placeholder={t("https://… · хост · хост:порт · адреса через запятую (у heartbeat пусто)")} className="h-8 font-mono" />
</Label>
<Label>
{t("Проверять раз в, с")}
<Input name="intervalSec" type="number" min={30} defaultValue={m?.intervalSec ?? 60} className="h-8" />
</Label>
<Label>
{t("Текст в ответе (HTTP)")}
<Input name="contains" defaultValue={String(tg.contains ?? "")} className="h-8" />
</Label>
<Label>
{t("Коды ответа (HTTP), через запятую")}
<Input name="expectStatus" defaultValue={Array.isArray(tg.expectStatus) ? (tg.expectStatus as number[]).join(", ") : ""} placeholder="200–399" className="h-8" />
</Label>
<Label>
{t("Медленнее, мс — нестабилен (HTTP)")}
<Input name="maxLatencyMs" type="number" min={1} defaultValue={tg.maxLatencyMs != null ? String(tg.maxLatencyMs) : ""} className="h-8" />
</Label>
<Label>
{t("Неудач подряд до «не работает»")}
<Input name="failThreshold" type="number" min={1} max={20} defaultValue={m?.failThreshold ?? 3} className="h-8" />
</Label>
<Label>
{t("Удач подряд до «работает»")}
<Input name="recoverThreshold" type="number" min={1} max={20} defaultValue={m?.recoverThreshold ?? 2} className="h-8" />
</Label>
<Label>
{t("Запас heartbeat, с")}
<Input name="graceSec" type="number" min={0} defaultValue={tg.graceSec != null ? String(tg.graceSec) : ""} placeholder="60" className="h-8" />
</Label>
</div>
);
}