peppa/apps/web/components/Observability.tsx
peppa-bot acb6e3fb81
All checks were successful
peppa/lint lint: success за 1с
peppa/typecheck typecheck: success за 46с
peppa/build build: success за 34с
peppa/test test: success за 1325с
peppa-ci / ci (pull_request) Successful in 24m11s
PEP-224: статус функций из мониторинга (сведено с main после PEP-225)
Функция → мониторинги (core/feature-status.ts), серая кнопка входа через eGov и статус MCP,
отказ startEgovFlow, журнал и сообщения в канал. После переезда живых обновлений на
WebSocket (PEP-225): область `features` в LIVE_PLAIN_SCOPES, открыта без входа (SSE и
WebSocket с `anonymous: true` — только открытые области), смотрится по таймеру вместе с
`observe`, смена сбрасывает кэш статусов.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 15:00:03 +00:00

129 lines
7.3 KiB
TypeScript
Raw Permalink 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 { durationText, FEATURE_NAMES, FEATURES, type MonitorKind, type MonitorState, type 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, remindDefault }: { t: Translator; m?: MonitorView; kindFixed?: boolean; remindDefault: number }) {
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("Напоминать раз в, мин (0 — не напоминать)")}
<Input name="remindMin" type="number" min={0} max={1440} defaultValue={m?.remindMin != null ? String(m.remindMin) : ""} placeholder={String(remindDefault)} className="h-8" />
</Label>
<label className="flex items-center gap-2 self-end pb-1.5 text-sm">
<input type="checkbox" name="remindDegraded" value="1" defaultChecked={m?.remindDegraded ?? false} />
{t("Напоминать и когда нестабилен")}
</label>
<Label>
{t("Запас heartbeat, с")}
<Input name="graceSec" type="number" min={0} defaultValue={tg.graceSec != null ? String(tg.graceSec) : ""} placeholder="60" className="h-8" />
</Label>
<fieldset className="m-0 flex flex-col gap-1 border-0 p-0 sm:col-span-2">
<legend className="mb-1 text-sm font-medium">{t("Что отключать при сбое")}</legend>
<span className="flex flex-wrap gap-x-4 gap-y-1">
{FEATURE_NAMES.map((f) => (
<label key={f} className="flex items-center gap-1.5 text-sm">
<input type="checkbox" name="features" value={f} defaultChecked={m?.features.includes(f)} className="size-4 accent-primary" />
{t(FEATURES[f].label)}
</label>
))}
</span>
</fieldset>
</div>
);
}
/** PEP-223: «не работает 1 ч 30 мин · напоминаний: 3 · следующее в 14:30». */
export function OutageLine({ m, t, now = new Date() }: { m: MonitorView; t: Translator; now?: Date }) {
if (!m.outage || m.paused || (m.state !== "down" && m.state !== "degraded")) return null;
const o = m.outage;
const duration = t.text(durationText(now.getTime() - Date.parse(o.startedAt)));
const parts = [
m.state === "down" ? t("не работает {duration}", { duration }) : t("нестабилен {duration}", { duration }),
t("напоминаний: {n}", { n: o.reminders }),
o.nextRemindAt ? t("следующее в {time}", { time: hhmm(o.nextRemindAt) }) : o.quiet ? t("без напоминаний: вместе с интернетом") : t("без напоминаний"),
];
return <span className={m.state === "down" ? "text-destructive" : "text-warn"}>{parts.join(" · ")}</span>;
}
const hhmm = (iso: string) => new Date(iso).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });