peppa/apps/web/app/(app)/observability/page.tsx
peppa-bot b6d3921429
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 47с
peppa/build build: success за 33с
peppa/test test: success за 1455с
peppa-ci / ci (pull_request) Successful in 26m17s
PEP-266: CLI peppa smoke, раздел «Запуск агентов» на Observability, тест, архив change
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:19:52 +00:00

333 lines
21 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, PROVIDER_LABEL, smokeStatus, smokeTimeoutMin, type SmokeRun, type SmokeStatus, egovLoginSummary, errorScope, errorsOverview, FEATURE_NAMES, FEATURES, featureLog, featureStatuses, 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, requestSmokeAction, setFeatureThresholdAction } from "./actions";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
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>
</>
);
}
/** PEP-266: the launch smoke test — every provider started the real way after a deploy and hourly. */
async function SmokeSection({ t }: { t: Awaited<ReturnType<typeof getT>> }) {
const st = await smokeStatus(db);
const shown: SmokeRun | null = st.current ?? st.history[0] ?? null;
const STATE: Record<SmokeStatus, [string, string]> = {
running: [t("идёт проверка"), "border-primary/40 text-primary"],
ok: [t("запускается"), "border-ok/40 text-ok"],
failed: [t("не запустился"), "border-destructive/40 text-destructive"],
skipped: [t("не проверен"), "text-muted-foreground"],
};
const TRIGGER = { deploy: t("после выкатки"), hourly: t("плановая"), manual: t("по запросу") } as const;
const when = (r: SmokeRun) => new Date(r.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" });
return (
<Section
title={t("Запуск агентов")}
actions={
<form action={requestSmokeAction}>
<Button size="sm" variant="outline" disabled={st.requested || !!st.current}>{st.requested ? t("Проверка запрошена") : t("Проверить сейчас")}</Button>
</form>
}
>
<p className="m-0 text-sm text-muted-foreground">{t("После каждой выкатки и раз в час FORGE запускает каждого агента (Claude, Codex, OpenCode — у кого есть подписка) так же, как для задачи, с одной просьбой: создать файл и закоммитить. Нет коммита за {n} мин — суперадминам уходит сообщение в Telegram.", { n: smokeTimeoutMin() })}</p>
{!shown ? (
<Empty>{t("Проверок ещё не было.")}</Empty>
) : (
<Card className="gap-1.5 py-3" data-smoke-run={shown.id}>
<div className="text-xs text-muted-foreground">
{t("{when} · {trigger} · версия {commit}", { when: when(shown), trigger: TRIGGER[shown.trigger], commit: shown.commit?.slice(0, 7) ?? "?" })}
</div>
{shown.items.map((i) => {
const [label, cls] = STATE[i.status];
return (
<div key={i.provider} className="flex flex-col gap-1" data-smoke-row={i.provider} data-smoke-status={i.status}>
<div className="flex flex-wrap items-center gap-2">
<Badge variant="outline" className={cls}>{label}</Badge>
<span className="font-semibold">{PROVIDER_LABEL[i.provider]}</span>
{i.sec != null && i.status !== "skipped" ? <span className="text-xs text-muted-foreground">{t("{n} с", { n: i.sec })}</span> : null}
{i.reason ? <span className={`text-xs ${i.status === "failed" ? "text-destructive" : "text-muted-foreground"}`}>{t.text(i.reason)}</span> : null}
</div>
{i.screen ? (
<Disclosure summary={t("Экран агента")}>
<pre className="m-0 max-h-60 overflow-auto whitespace-pre-wrap text-xs">{i.screen}</pre>
</Disclosure>
) : null}
</div>
);
})}
</Card>
)}
{st.history.length > 1 ? (
<Disclosure summary={t("Прошлые проверки ({n})", { n: st.history.length - (st.current ? 0 : 1) })}>
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
{st.history.slice(st.current ? 0 : 1).map((r) => (
<li key={r.id} className="flex flex-wrap gap-2">
<span className="text-muted-foreground">{when(r)}</span>
<span className="text-muted-foreground">{TRIGGER[r.trigger]}</span>
{r.items.map((i) => (
<span key={i.provider} className={i.status === "failed" ? "text-destructive" : i.status === "ok" ? "text-ok" : "text-muted-foreground"}>
{PROVIDER_LABEL[i.provider]}: {STATE[i.status][0]}
</span>
))}
</li>
))}
</ul>
</Disclosure>
) : 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;
// PEP-224: features follow their monitors.
const features = featureStatuses({ fresh: true });
const flog = featureLog(20);
const FEATURE_STATE = { available: [t("доступна"), "border-ok/40 text-ok"], degraded: [t("с задержками"), "border-warn/40 text-warn"], unavailable: [t("отключена"), "border-destructive/40 text-destructive"] } as const;
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>
<SmokeSection t={t} />
<Section title={t("Функции")} count={FEATURE_NAMES.length}>
<p className="m-0 text-sm text-muted-foreground">{t("Функция становится серой у пользователей, когда связанный мониторинг не работает дольше порога, и включается сама после восстановления. Связка — «Что отключать при сбое» у мониторинга или поле features в MCP update_monitor.")}</p>
<div className="flex flex-col gap-2">
{FEATURE_NAMES.map((name) => {
const f = features[name];
const [label, cls] = FEATURE_STATE[f.state];
return (
<Card key={name} className="gap-1.5 py-3" data-feature-row={name}>
<div className="flex flex-wrap items-center gap-2">
<Badge variant="outline" className={cls}>{label}</Badge>
<span className="font-semibold">{t(FEATURES[name].label)}</span>
<span className="font-mono text-xs text-muted-foreground">{name}</span>
<form action={setFeatureThresholdAction} className="ml-auto flex items-center gap-1.5 text-xs text-muted-foreground">
<Hidden fields={{ name }} />
{t("отключать через, мин")}
<Input name="disableAfterMin" type="number" min={0} max={1440} defaultValue={f.disableAfterMin} className="h-7 w-16" />
<Button size="sm" variant="ghost">{t("Сохранить")}</Button>
</form>
</div>
<div className="text-xs text-muted-foreground">
{f.monitors.length ? (
<>
{t("Мониторинги:")}{" "}
{f.monitors.map((mm, i) => (
<span key={mm.id}>
{i ? ", " : ""}
<Link href={`/observability/${mm.id}`} className="hover:underline">{mm.name}</Link>
</span>
))}
</>
) : (
t("Не связана ни с одним мониторингом — всегда доступна.")
)}
{f.failing.length ? <span className="text-destructive"> · {f.failing.map((x) => `${x.name}${x.reason ? `: ${x.reason}` : ""}`).join("; ")}</span> : null}
</div>
</Card>
);
})}
</div>
<Disclosure summary={t("Журнал включений и выключений ({n})", { n: flog.length })}>
{flog.length === 0 ? (
<Empty>{t("Функции ещё не отключались.")}</Empty>
) : (
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
{flog.map((e) => (
<li key={e.id} className="flex flex-wrap gap-2">
<span className="text-muted-foreground">{new Date(e.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}</span>
<span className={e.state === "unavailable" ? "text-destructive" : "text-ok"}>{e.state === "unavailable" ? t("отключена") : t("снова включена")}</span>
<span className="font-medium">{t(FEATURES[e.name].label)}</span>
{e.reason && <span className="text-muted-foreground">{e.reason}</span>}
</li>
))}
</ul>
)}
</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>
);
}