diff --git a/apps/observer/src/observer.ts b/apps/observer/src/observer.ts index fb098c12..fe8ce840 100644 --- a/apps/observer/src/observer.ts +++ b/apps/observer/src/observer.ts @@ -3,7 +3,8 @@ // 30 s it writes its heartbeat (the watchdog watches it like the bot and the web), every hour it // deletes checks older than the retention (7 days). Monitors are rows in observe.db: the web and // MCP change them, the service picks the change up on its next pass — no restart. -import { beat, observeTick, pruneObserve, seedMonitors, type ObserveProbes } from "@peppa/core"; +import { beat, featureTick, observeTick, pruneObserve, seedFeatureMonitors, seedMonitors, type ObserveProbes } from "@peppa/core"; +import { loadEnv } from "@peppa/shared"; import type { Db } from "@peppa/db"; export interface ObserverOptions { @@ -16,6 +17,10 @@ export async function runObserver(db: Db, o: ObserverOptions = {}, signal?: Abor const log = o.log ?? (() => {}); const made = seedMonitors(); if (made.length) log(`observer: built-in monitors created: ${made.map((m) => m.name).join(", ")}`); + // PEP-224: MCP monitors switch the «mcp» feature off; created once, when the web has a public address. + const mcp = seedFeatureMonitors(loadEnv().PEPPA_WEB_URL); + if (mcp.length) log(`observer: built-in monitors created: ${mcp.map((m) => m.name).join(", ")}`); + let featuresBusy = false; log("observer started"); let lastBeat = 0; let lastPrune = 0; @@ -36,6 +41,13 @@ export async function runObserver(db: Db, o: ObserverOptions = {}, signal?: Abor } // Not awaited: a slow check must not hold the others or the heartbeat. void observeTick(db, { log, probes: o.probes }).catch((e: Error) => log(`observer: tick failed: ${e.message}`)); + // PEP-224: features follow their monitors — announce a change (journal, channel, live pages). + if (!featuresBusy) { + featuresBusy = true; + void featureTick(db, { log }) + .catch((e: Error) => log(`observer: features failed: ${e.message}`)) + .finally(() => (featuresBusy = false)); + } await new Promise((r) => setTimeout(r, o.tickMs ?? 1_000)); } } diff --git a/apps/web/app/(app)/help/connect/page.tsx b/apps/web/app/(app)/help/connect/page.tsx index 2e690ae0..3ba60b9a 100644 --- a/apps/web/app/(app)/help/connect/page.tsx +++ b/apps/web/app/(app)/help/connect/page.tsx @@ -1,27 +1,33 @@ import Link from "next/link"; -import { CONNECT_HELP } from "@peppa/core"; +import { CONNECT_HELP, featureGateView } from "@peppa/core"; +import { FeatureGate } from "@/components/FeatureGate"; +import { LiveRefresh } from "@/components/LiveRefresh"; import { PageHeader } from "@/components/common"; import { CopyText } from "@/components/CopyText"; import { Workspace } from "@/components/Workspace"; import { publicOrigin } from "@/lib/auth"; -import { getLocale } from "@/lib/i18n"; +import { getLocale, getT } from "@/lib/i18n"; /** PEP-135: how to connect Peppa FACTORY to one's own Claude or ChatGPT — step by step; texts live in core/connect-texts.ts. */ export default async function ConnectHelp() { const t = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru; const address = `${await publicOrigin()}/mcp`; + const tr = await getT(); const card = "flex flex-col gap-2 rounded-lg border bg-card px-4 py-3"; const h2 = "m-0 text-[15px] font-semibold"; return (
+ {t.back}} title={t.title}> {t.lead}

{t.addressTitle}

- + + +

{t.addressNote}

{t.apps.map((app) => ( diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index ebe7ef67..2649bd6c 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -1,6 +1,8 @@ import Link from "next/link"; import type { ReactNode } from "react"; -import { CONNECT_HELP, PRODUCT_HELP } from "@peppa/core"; +import { CONNECT_HELP, featureGateView, PRODUCT_HELP } from "@peppa/core"; +import { FeatureGate } from "@/components/FeatureGate"; +import { LiveRefresh } from "@/components/LiveRefresh"; import { m } from "@peppa/shared/i18n"; import { getLocale, getT } from "@/lib/i18n"; import { publicOrigin, uiMode } from "@/lib/auth"; @@ -172,8 +174,11 @@ export default async function Help() {
-

{t("Адрес сервера:")}

- {mcp} + + +

{t("Адрес сервера:")}

+ {mcp} +
  • {rich(t("ChatGPT: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Peppa FACTORY — войдите через eGov и нажмите «Разрешить». В чате включите коннектор Peppa."))}
  • {rich(t("Инструкция для ИИ: первым делом ИИ-клиент вызывает инструмент get_started — памятка менеджера: код пишут только агенты, напрямую в код проекта не лезть, «Готово» — только после «Принять». Те же слова — на открытой странице /mcp-guide (кнопка «Скопировать» — для «Инструкций» проекта ChatGPT или системного сообщения другого ИИ). Первый ответ list_projects и get_task напоминает о ней."))}
  • diff --git a/apps/web/app/(app)/observability/[id]/page.tsx b/apps/web/app/(app)/observability/[id]/page.tsx index 3bc634a2..3cd7bb19 100644 --- a/apps/web/app/(app)/observability/[id]/page.tsx +++ b/apps/web/app/(app)/observability/[id]/page.tsx @@ -2,7 +2,7 @@ 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 { describeTarget, FEATURES, getMonitor, isSuperadmin, monitorChecks, monitorIncidents, monitorView } from "@peppa/core"; import { loadEnv } from "@peppa/shared"; import { AutoRefresh } from "@/components/AutoRefresh"; import { Hidden } from "@/components/cards"; @@ -66,6 +66,9 @@ export default async function MonitorPage({ params, searchParams }: { params: Pr

    {t("Раз в {n} с · «не работает» после {f} неудач подряд · «работает» после {r} удач · создал {who}", { n: m.intervalSec, f: m.failThreshold, r: m.recoverThreshold, who: m.createdBy })}

    +

    + {t("Что отключать при сбое:")} {m.features.length ? m.features.map((f) => t(FEATURES[f].label)).join(", ") : t("ничего")} +

    diff --git a/apps/web/app/(app)/observability/actions.ts b/apps/web/app/(app)/observability/actions.ts index 2fef8ad1..4de90a5f 100644 --- a/apps/web/app/(app)/observability/actions.ts +++ b/apps/web/app/(app)/observability/actions.ts @@ -1,7 +1,7 @@ "use server"; // Observability (PEP-202): every action is superadmin-only (others get "not found"). -import { createMonitor, deleteMonitor, getProject, logEvent, MONITOR_KINDS, PeppaError, platformProjectKey, requireSuperadmin, setMonitorPaused, updateMonitor, type MonitorKind, type MonitorTarget } from "@peppa/core"; +import { createMonitor, deleteMonitor, resetFeatureCache, setFeatureThreshold, getProject, logEvent, MONITOR_KINDS, PeppaError, platformProjectKey, requireSuperadmin, setMonitorPaused, updateMonitor, type MonitorKind, type MonitorTarget } from "@peppa/core"; import type { Db } from "@peppa/db"; import { m } from "@peppa/shared/i18n"; import { revalidatePath } from "next/cache"; @@ -53,6 +53,8 @@ function targetOf(kind: MonitorKind, f: FormData): MonitorTarget { } const numbers = (f: FormData) => ({ + // PEP-224: «Что отключать при сбое» — the checked features. + features: f.getAll("features").map(String), intervalSec: str(f, "intervalSec") ? Number(str(f, "intervalSec")) : undefined, failThreshold: str(f, "failThreshold") ? Number(str(f, "failThreshold")) : undefined, recoverThreshold: str(f, "recoverThreshold") ? Number(str(f, "recoverThreshold")) : undefined, @@ -95,3 +97,14 @@ export async function deleteMonitorAction(f: FormData) { return BASE; }); } + +/** PEP-224: how long a linked monitor may be down before the feature turns grey. */ +export async function setFeatureThresholdAction(f: FormData) { + await attempt(f, BASE, async (login) => { + const name = str(f, "name"); + const minutes = Number(str(f, "disableAfterMin")); + setFeatureThreshold(name, minutes); + resetFeatureCache(); + await journal(db, "feature_updated", { feature: name, disableAfterMin: minutes, author: `user:${login}` }); + }); +} diff --git a/apps/web/app/(app)/observability/page.tsx b/apps/web/app/(app)/observability/page.tsx index 992ba8a3..5179dbf1 100644 --- a/apps/web/app/(app)/observability/page.tsx +++ b/apps/web/app/(app)/observability/page.tsx @@ -2,7 +2,7 @@ import Link from "next/link"; import { notFound } from "next/navigation"; import { Activity, Pause, Play, Plus } from "lucide-react"; -import { describeTarget, egovLoginSummary, isSuperadmin, listMonitorViews } from "@peppa/core"; +import { describeTarget, egovLoginSummary, FEATURE_NAMES, FEATURES, featureLog, featureStatuses, isSuperadmin, listMonitorViews } from "@peppa/core"; import { loadEnv } from "@peppa/shared"; import { AutoRefresh } from "@/components/AutoRefresh"; import { Hidden } from "@/components/cards"; @@ -14,7 +14,9 @@ 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"; +import { createMonitorAction, pauseMonitorAction, setFeatureThresholdAction } from "./actions"; +import { Input } from "@/components/ui/input"; +import { Badge } from "@/components/ui/badge"; export const dynamic = "force-dynamic"; @@ -33,6 +35,10 @@ export default async function Observability({ searchParams }: { searchParams: Pr 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 ( @@ -88,6 +94,63 @@ export default async function Observability({ searchParams }: { searchParams: Pr
+ +
+

{t("Функция становится серой у пользователей, когда связанный мониторинг не работает дольше порога, и включается сама после восстановления. Связка — «Что отключать при сбое» у мониторинга или поле features в MCP update_monitor.")}

+
+ {FEATURE_NAMES.map((name) => { + const f = features[name]; + const [label, cls] = FEATURE_STATE[f.state]; + return ( + +
+ {label} + {t(FEATURES[name].label)} + {name} +
+ + {t("отключать через, мин")} + + + +
+
+ {f.monitors.length ? ( + <> + {t("Мониторинги:")}{" "} + {f.monitors.map((mm, i) => ( + + {i ? ", " : ""} + {mm.name} + + ))} + + ) : ( + t("Не связана ни с одним мониторингом — всегда доступна.") + )} + {f.failing.length ? · {f.failing.map((x) => `${x.name}${x.reason ? `: ${x.reason}` : ""}`).join("; ")} : null} +
+
+ ); + })} +
+ + {flog.length === 0 ? ( + {t("Функции ещё не отключались.")} + ) : ( +
    + {flog.map((e) => ( +
  • + {new Date(e.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })} + {e.state === "unavailable" ? t("отключена") : t("снова включена")} + {t(FEATURES[e.name].label)} + {e.reason && {e.reason}} +
  • + ))} +
+ )} +
+
); diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index a0aaa588..5aaeb525 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -1,4 +1,4 @@ -import { CONNECT_HELP, googleEnabled, connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core"; +import { CONNECT_HELP, featureGateView, googleEnabled, connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core"; import { Hidden } from "@/components/cards"; import { ago, Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common"; import { Button } from "@/components/ui/button"; @@ -6,6 +6,8 @@ import { Card } from "@/components/ui/card"; import { Input, Label } from "@/components/ui/input"; import { GoogleSignIn } from "@/components/GoogleSignIn"; import { EgovSign } from "@/components/EgovSign"; +import { FeatureGate } from "@/components/FeatureGate"; +import { LiveRefresh } from "@/components/LiveRefresh"; import { OwnBotSteps } from "@/components/OwnBotSteps"; import { voiceStoriesEnabled } from "@peppa/shared"; import { Workspace } from "@/components/Workspace"; @@ -50,10 +52,14 @@ export default async function Settings({ searchParams }: { searchParams: Promise const vapid = await vapidPublicKey(db); const t = await getT(); const connect = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru; + // PEP-224: features whose service is down are grey here (eGov binding, connecting AI clients). + const egovGate = featureGateView("egov_login"); + const mcpGate = featureGateView("mcp"); const ownBotSteps = ; return (
+
@@ -146,7 +152,9 @@ export default async function Settings({ searchParams }: { searchParams: Promise

{t("Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. Вход в Peppa FACTORY — только через eGov.")}

- + + +
@@ -309,12 +317,14 @@ export default async function Settings({ searchParams }: { searchParams: Promise

{w.engineer ? t("Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране Peppa FACTORY.") : t("Подключите Peppa FACTORY к своему чату — и ставьте задачи и отвечайте агентам прямо из него. Понадобится этот адрес; доступ вы подтвердите на экране Peppa FACTORY.")}

- -

- {connect.linkLabel} → - {" · "} - {t("Инструкция для ИИ")} → -

+ + +

+ {connect.linkLabel} → + {" · "} + {t("Инструкция для ИИ")} → +

+
{apps.length === 0 ? ( diff --git a/apps/web/app/api/live/route.ts b/apps/web/app/api/live/route.ts index 82ba53cc..88116941 100644 --- a/apps/web/app/api/live/route.ts +++ b/apps/web/app/api/live/route.ts @@ -12,9 +12,11 @@ const fail = async (status: number, error: string) => Response.json({ error: (aw export async function GET(req: Request) { const user = await currentUser(); - if (!user) return fail(401, m("Нужен вход")); try { - return await liveSse(db, user, parseScopes(new URL(req.url).searchParams.get("scope")), req.signal); + const scopes = parseScopes(new URL(req.url).searchParams.get("scope")); + // PEP-224: only `features` (state of platform features, no user data) is open without a sign-in. + if (!user && scopes.some((s) => s !== "features")) return fail(401, m("Нужен вход")); + return await liveSse(db, user, scopes, req.signal); } catch (e) { if (e instanceof LiveError) return fail(e.status, e.message); console.error("live:", e); diff --git a/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsx index 2f5ab6fd..6b988469 100644 --- a/apps/web/app/login/page.tsx +++ b/apps/web/app/login/page.tsx @@ -1,6 +1,8 @@ import { redirect } from "next/navigation"; import { Check, Laptop, MessageCircle, ShieldCheck, Sparkles } from "lucide-react"; -import { googleEnabled } from "@peppa/core"; +import { featureGateView, googleEnabled } from "@peppa/core"; +import { FeatureGate } from "@/components/FeatureGate"; +import { LiveRefresh } from "@/components/LiveRefresh"; import { currentUser, safeNext } from "@/lib/auth"; import { Brand } from "@/components/Brand"; import { GoogleSignIn } from "@/components/GoogleSignIn"; @@ -40,6 +42,11 @@ export default async function Login({ searchParams }: { searchParams: Promise<{ const { error, next } = await searchParams; if (await currentUser()) redirect(safeNext(next)); const t = await getT(); + // PEP-224: eGov known to be down — a grey button with a caption; Google (if on) becomes the main way in. + const egov = featureGateView("egov_login"); + const egovDown = egov.state === "unavailable"; + const google = googleEnabled(); + const googleButton = google && ; return (
@@ -57,8 +64,13 @@ export default async function Login({ searchParams }: { searchParams: Promise<{

{t("Начать — одна минута")}

{t("Вход через eGov или Google. Первый вход сам создаёт учётку — регистрироваться отдельно не нужно.")}

- - {googleEnabled() && } + + {egovDown && googleButton} + + + + {!egovDown && googleButton} + {egovDown && !google &&

{t("Другого способа входа сейчас нет. Откройте эту страницу позже — кнопка заработает сама, как только eGov снова будет доступен.")}

}

{t("Вы с телефона? Войти можно и отсюда, но управлять фабрикой удобнее с ноутбука.")}

diff --git a/apps/web/app/mcp-guide/page.tsx b/apps/web/app/mcp-guide/page.tsx index cabd8652..d2476281 100644 --- a/apps/web/app/mcp-guide/page.tsx +++ b/apps/web/app/mcp-guide/page.tsx @@ -1,4 +1,6 @@ -import { MCP_GUIDE } from "@peppa/core"; +import { featureGateView, MCP_GUIDE } from "@peppa/core"; +import { FeatureGate } from "@/components/FeatureGate"; +import { LiveRefresh } from "@/components/LiveRefresh"; import { Brand } from "@/components/Brand"; import { GuideCopy } from "@/components/GuideCopy"; import { getT } from "@/lib/i18n"; @@ -13,7 +15,10 @@ export default async function McpGuide() {

{t("Инструкция для ИИ")}

{t("Памятка для ИИ, подключённого к Peppa FACTORY. Вставьте её в «Инструкции» проекта ChatGPT или в системное сообщение другого ИИ.")}

- + + + +
); } diff --git a/apps/web/app/mcp/route.ts b/apps/web/app/mcp/route.ts index e4e3e7fe..e41fd951 100644 --- a/apps/web/app/mcp/route.ts +++ b/apps/web/app/mcp/route.ts @@ -1,5 +1,6 @@ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"; -import { enterActor, getUser, isUserAllowed, verifyAccessToken } from "@peppa/core"; +import { enterActor, FEATURES, featureStatus, getUser, isUserAllowed, verifyAccessToken } from "@peppa/core"; +import { stripAsIs, t as translate } from "@peppa/shared/i18n"; import { createManagerServer } from "@peppa/mcp/manager"; import { publicOrigin } from "@/lib/auth"; import { db } from "@/lib/db"; @@ -20,6 +21,15 @@ export async function POST(req: Request) { const auth = await verifyAccessToken(db, token); const user = auth && (await getUser(db, auth.userId)); if (!user || !(await isUserAllowed(db, user))) return unauthorized(); + // PEP-224: a service MCP depends on is down (Observability) — say so plainly instead of failing midway. + // HTTP 200 with a JSON-RPC error: a 5xx is replaced by Cloudflare's own page (PEP-194). + if (featureStatus("mcp").state === "unavailable") { + const body = (await req.clone().json().catch(() => null)) as { id?: unknown } | Array<{ id?: unknown }> | null; + const id = (Array.isArray(body) ? body[0]?.id : body?.id) ?? null; + const text = FEATURES.mcp.unavailableText; + const message = `${stripAsIs(text)} / ${stripAsIs(translate("en", text))}`; + return json({ jsonrpc: "2.0", id, error: { code: -32001, message } }, 200, { "Access-Control-Allow-Origin": "*", "Retry-After": "300" }); + } // PEP-48: everything this request does is done by the user through this OAuth client. enterActor({ kind: "user", userId: user.id, channel: "mcp", clientId: auth.clientId }); const server = createManagerServer(db, user, await publicOrigin()); diff --git a/apps/web/components/FeatureGate.tsx b/apps/web/components/FeatureGate.tsx new file mode 100644 index 00000000..a8b60070 --- /dev/null +++ b/apps/web/components/FeatureGate.tsx @@ -0,0 +1,41 @@ +// PEP-224: a feature that depends on a failing service (Observability) — grey, inactive, with a +// plain caption and the time it failed. Available — its children as they are; unstable — the +// children with a note «может работать с задержками». For any new feature: pass `featureGateView`. +import type { ReactNode } from "react"; +import { CircleSlash, Clock } from "lucide-react"; +import { serverTimezone, type FeatureGateView } from "@peppa/core"; +import { getLocale, getT } from "@/lib/i18n"; +import { intlLocale } from "@peppa/shared/i18n"; +import { cn } from "@/lib/utils"; + +export async function FeatureGate({ view, label, title, children, className }: { view: FeatureGateView; /** The grey button's text (a button-like control). */ label?: ReactNode; /** A grey status instead (an instruction, a section). */ title?: ReactNode; children: ReactNode; className?: string }) { + if (view.state === "available") return <>{children}; + const t = await getT(); + if (view.state === "degraded") + return ( + <> + {children} +

+ {t.text(view.text)} +

+ + ); + const since = view.since ? new Date(view.since).toLocaleTimeString(intlLocale(await getLocale()), { hour: "2-digit", minute: "2-digit", timeZone: serverTimezone() }) : null; + return ( +
+ {label ? ( + + ) : ( +
+ {title} +
+ )} +

+ {t.text(view.text)} + {since ? ` · ${t("с {time}", { time: since })}` : ""} +

+
+ ); +} diff --git a/apps/web/components/GoogleSignIn.tsx b/apps/web/components/GoogleSignIn.tsx index 0418446c..c1571bc0 100644 --- a/apps/web/components/GoogleSignIn.tsx +++ b/apps/web/components/GoogleSignIn.tsx @@ -1,12 +1,12 @@ import { Button } from "@/components/ui/button"; /** «Войти через Google» / «Привязать Google» (PEP-90): обычная форма, браузер уходит на Google. */ -export function GoogleSignIn({ purpose, next, label }: { purpose: "login" | "link"; next?: string; label: string }) { +export function GoogleSignIn({ purpose, next, label, primary = false }: { purpose: "login" | "link"; next?: string; label: string; /** PEP-224: the main way in while eGov is unavailable. */ primary?: boolean }) { return (
{next && } -
); } diff --git a/openspec/changes/pep-224-feature-status/design.md b/openspec/changes/pep-224-feature-status/design.md new file mode 100644 index 00000000..81f7335f --- /dev/null +++ b/openspec/changes/pep-224-feature-status/design.md @@ -0,0 +1,52 @@ +# Design: PEP-224 + +## Где хранить связку +Связка «мониторинг → функции» — колонка `monitors.features` (JSON-массив имён) в +`observe.db`: её меняют вместе с мониторингом («Что отключать при сбое» на странице +мониторинга, `features` в MCP `create_monitor`/`update_monitor`). Порог на функцию и +последнее объявленное состояние — таблица `features (name, disable_after_min, state, +since, reason, changed_at)`; журнал — `feature_log`. Основная БД не меняется: всё, что +касается мониторингов, живёт в `observe.db` (PEP-202). + +## Правило (чистая функция `computeFeatures`) +Для каждой функции берутся её мониторинги не на паузе: +- `unavailable` — хотя бы один в `down` дольше `disableAfterMin` (от `state_since`); + тихие сбои (весь интернет) тоже считаются — пользователю всё равно недоступно; +- `degraded` — хотя бы один `degraded` (или `down` моложе порога не считается); +- иначе `available`. Восстановление — по состоянию мониторинга, т.е. после его + `recover_threshold` хороших проверок. +`since` — самое раннее `state_since` упавших мониторингов (время, с которого сбой). + +## Чтение +`featureStatus(name)` / `featureStatuses()` считают на лету из `observe.db` (одно чтение +таблицы мониторингов) с кэшем 15 с на процесс. Любая ошибка (файла нет, повреждён, +занят) → функция доступна: сбой мониторинга не блокирует вход. Сервер проверяет сам: +`startEgovFlow` при `unavailable` — `PeppaError` до запроса к relay; `/mcp` — ошибка +JSON-RPC с тем же текстом и 503. + +## Объявление и живое обновление +`featureTick` в сервисе мониторингов (каждую секунду, после проверок) сравнивает +посчитанное с `features.state`; смена → `feature_log`, событие `feature_disabled` / +`feature_enabled` в журнале платформенного проекта (запись в основную БД будит +`LiveHub` через `data_version`), сообщение в канал «services» (`postToChannel`, без +канала — `alertAdmins`) и `notify()`. Первое вычисление только запоминает состояние +(«доступна» не объявляется). Новая живая область `features` — отпечаток из +`features.state`; `/api/live?scope=features` открыт без входа (только эта область: +в ней нет данных пользователей), страница входа её слушает. + +## Тексты +Пользователю — без «relay», «DNS», «OAuth»: «Временно недоступно — технические +неполадки на стороне eGov. Попробуйте позже», «MCP временно недоступен». Сообщения в +канал «services» и `/observability` — для суперадмина, там названия мониторингов как есть. + +## Встроенные мониторинги MCP +`seedFeatureMonitors` (один раз, `observe_meta 'seeded:mcp'`): при `PEPPA_WEB_URL` не на +localhost создаёт «MCP-сервер /mcp» (GET `/mcp`, ожидается 401 — без токена сервер +отвечает «нужен вход») и «MCP — вход OAuth» (`/.well-known/oauth-authorization-server`, +текст `token_endpoint`), оба с `features: ["mcp"]`. Миграция v2 проставляет +`egov_login` встроенным «eGov relay» и «eGov relay — DNS». + +## Остальные функции +`google_login`, `bot`, `voice`, `bugsink` есть в списке, но без связанных мониторингов +— доступны, пока суперадмин не свяжет мониторинг. Серой в интерфейсе пока делаются только +eGov и MCP; `FeatureGate` — для следующих. diff --git a/openspec/changes/pep-224-feature-status/proposal.md b/openspec/changes/pep-224-feature-status/proposal.md new file mode 100644 index 00000000..98de6e67 --- /dev/null +++ b/openspec/changes/pep-224-feature-status/proposal.md @@ -0,0 +1,31 @@ +# PEP-224: статус функций из мониторинга + +## Why +Мониторинг (PEP-202) знает, что eGov relay или MCP не работает, а интерфейс — нет: человек +сканирует QR, ждёт пять минут и получает ошибку. Функция, зависящая от упавшего сервиса, +должна сама становиться серой с понятной подписью и сама возвращаться после восстановления. + +## What Changes +- `core/feature-status.ts`: список функций платформы (`egov_login`, `mcp`, `google_login`, + `bot`, `voice`, `bugsink`), связка «мониторинг → функции» (поле `features` мониторинга), + порог `disableAfterMin` на функцию (по умолчанию 5), чистое правило `computeFeatures` + и дешёвое чтение `featureStatus(name)` (кэш 15 с, сбой `observe.db` → доступна). +- `observe.db` v2: колонка `monitors.features`, таблицы `features` (порог, объявленное + состояние) и `feature_log` (журнал включений/выключений). Встроенные мониторинги eGov + получают `egov_login`; новые встроенные «MCP-сервер /mcp» и «MCP — вход OAuth» — `mcp`. +- Сервис мониторингов: `featureTick` — смена статуса функции → запись в журнал, событие + платформенного проекта, одно сообщение в канал «services» (иначе админам), `notify()`. +- Сервер: `startEgovFlow` при недоступности отказывает `PeppaError` без запроса к relay; + `/mcp` при недоступности отвечает понятной ошибкой JSON-RPC. +- Интерфейс: компонент `FeatureGate`; вход (eGov серый, Google — основной, нет других + способов — подпись), «Настройки → eGov», «Настройки → Peppa FACTORY в вашем Claude или + ChatGPT», `/mcp-guide`, «Помощь → Подключение» — серый статус. Живая область `features` + (доступна и без входа) — кнопка оживает без перезагрузки. +- `/observability`: «Функции» (статус, порог, журнал), у мониторинга «Что отключать при + сбое»; MCP `create_monitor`/`update_monitor` принимают `features`. + +## Impact +- Код: `packages/core` (feature-status, observe), `apps/observer`, `packages/mcp` + (monitors), `packages/runner` (live), `apps/web` (вход, настройки, mcp-guide, помощь, + observability, /mcp, /auth/egov/start, /api/live). +- Данные: миграция `observe.db` (user_version 2), основная БД не меняется. diff --git a/openspec/changes/pep-224-feature-status/specs/feature-status/spec.md b/openspec/changes/pep-224-feature-status/specs/feature-status/spec.md new file mode 100644 index 00000000..1ee950eb --- /dev/null +++ b/openspec/changes/pep-224-feature-status/specs/feature-status/spec.md @@ -0,0 +1,63 @@ +## ADDED Requirements + +### Requirement: Статус функции из мониторингов +Peppa SHALL считать функцию платформы недоступной, если связанный с ней мониторинг находится в состоянии «не работает» дольше порога функции (по умолчанию 5 минут), и SHALL снова считать её доступной после восстановления мониторинга. Состояние «нестабильно» SHALL давать только пометку о возможных задержках. Сбой чтения базы мониторингов SHALL оставлять функцию доступной. + +#### Scenario: eGov relay лежит дольше порога +- **GIVEN** мониторинг «eGov relay» связан с функцией «Вход через eGov», порог 5 мин +- **AND** мониторинг в состоянии «не работает» 6 минут +- **WHEN** страница входа читает статус функции +- **THEN** функция «Вход через eGov» недоступна с временем начала сбоя + +#### Scenario: Сбой короче порога +- **GIVEN** мониторинг «eGov relay» в состоянии «не работает» 2 минуты +- **WHEN** читается статус функции «Вход через eGov» +- **THEN** функция доступна + +#### Scenario: Мониторинг восстановился +- **GIVEN** функция «Вход через eGov» недоступна +- **WHEN** мониторинг «eGov relay» после двух удачных проверок снова «работает» +- **THEN** функция доступна + +#### Scenario: База мониторингов недоступна +- **GIVEN** файл базы мониторингов не открывается +- **WHEN** читается статус функции «Вход через eGov» +- **THEN** функция доступна + +### Requirement: Сервер не начинает недоступное +Начало входа через eGov SHALL отказывать понятным сообщением, не обращаясь к eGov, когда функция «Вход через eGov» недоступна. Удалённый MCP SHALL отвечать клиенту понятной ошибкой, когда функция «MCP» недоступна. + +#### Scenario: Отказ без запроса к eGov +- **GIVEN** функция «Вход через eGov» недоступна +- **WHEN** пользователь нажимает «Войти через eGov» +- **THEN** приходит ответ «Временно недоступно — технические неполадки на стороне eGov. Попробуйте позже» +- **AND** запроса к eGov не было + +### Requirement: Недоступное серое в интерфейсе +Кнопка или инструкция недоступной функции SHALL быть серой и неактивной с подписью «временно недоступно» и временем начала сбоя и SHALL оживать без перезагрузки страницы после восстановления. На странице входа при недоступном eGov другой способ входа SHALL оставаться рабочим и выделенным; если других способов нет, страница SHALL говорить об этом. + +#### Scenario: Вход при упавшем eGov +- **GIVEN** функция «Вход через eGov» недоступна +- **AND** вход через Google включён +- **WHEN** человек открывает страницу входа +- **THEN** кнопка «Войти через eGov» серая с подписью «Временно недоступно — технические неполадки на стороне eGov. Попробуйте позже» +- **AND** кнопка «Войти через Google» активна и выделена + +#### Scenario: MCP недоступен +- **GIVEN** функция «MCP» недоступна +- **WHEN** пользователь открывает «Настройки» +- **THEN** вместо адреса подключения — серый статус «MCP временно недоступен» + +### Requirement: Журнал включений и выключений +Смена статуса функции SHALL записываться в журнал на странице Observability и SHALL давать одно сообщение в канал платформы «services». Связку функции с мониторингами SHALL менять суперадмин на странице мониторинга и через MCP. + +#### Scenario: Функция отключена и включена +- **GIVEN** канал платформы настроен +- **WHEN** функция «Вход через eGov» становится недоступной, а потом доступной +- **THEN** в канал ушли два сообщения: «отключён для пользователей» и «снова включён» +- **AND** на Observability в журнале функций две записи + +#### Scenario: Связка через MCP +- **GIVEN** мониторинг «Bugsink» без связанных функций +- **WHEN** суперадмин вызывает `update_monitor` с `features: ["bugsink"]` +- **THEN** мониторинг связан с функцией «Отслеживание ошибок» diff --git a/openspec/changes/pep-224-feature-status/tasks.md b/openspec/changes/pep-224-feature-status/tasks.md new file mode 100644 index 00000000..0c2f30bc --- /dev/null +++ b/openspec/changes/pep-224-feature-status/tasks.md @@ -0,0 +1,16 @@ +## 1. Ядро +- [ ] 1.1 `observe.db` v2: `monitors.features`, `features`, `feature_log`; eGov-мониторингам `egov_login`; `features` в create/update мониторинга +- [ ] 1.2 `core/feature-status.ts`: список функций, `computeFeatures`, `featureStatus(es)` с кэшем, `setFeatureThreshold`, `featureTick`, тексты +- [ ] 1.3 Встроенные мониторинги MCP (`seedFeatureMonitors`), `featureTick` в сервисе мониторингов +- [ ] 1.4 `startEgovFlow` отказывает при недоступности + +## 2. Веб и MCP +- [ ] 2.1 Живая область `features` (без входа) +- [ ] 2.2 `FeatureGate`; вход, «Настройки → eGov», подключение ИИ-клиентов, `/mcp-guide`, помощь +- [ ] 2.3 `/mcp` — понятная ошибка при недоступности +- [ ] 2.4 `/observability`: «Функции», «Что отключать при сбое»; MCP `features` +- [ ] 2.5 Переводы en/kk, словарь + +## 3. Проверка +- [ ] 3.1 Тест `feature-status.test.ts` +- [ ] 3.2 Проверки (lint, typecheck, тесты), браузер diff --git a/packages/core/src/egov.ts b/packages/core/src/egov.ts index 15136969..6218fb2f 100644 --- a/packages/core/src/egov.ts +++ b/packages/core/src/egov.ts @@ -2,6 +2,7 @@ // short-lived , reads the signed XML from the relay itself and takes // the signer's IIN from the certificate. The XMLDSig itself is not verified here — the relay is // trusted (PM decision, see openspec design); the challenge and nonce never leave the server. +import { assertFeatureAvailable } from "./feature-status.ts"; import { m as tr } from "@peppa/shared/i18n"; import { randomBytes, randomInt, randomUUID } from "node:crypto"; import { and, eq, gte, inArray, sql } from "drizzle-orm"; @@ -193,6 +194,8 @@ export async function startEgovFlow(db: Db, purpose: EgovPurpose, userId: number async function startEgovFlowInner(db: Db, purpose: EgovPurpose, userId: number | null): Promise { if (purpose === "link" && !userId) throw new PeppaError(tr("Привязать eGov можно только после входа")); + // PEP-224: eGov is known to be down — say so now instead of a QR that never signs. + assertFeatureAvailable("egov_login"); const env = loadEnv(); const nonce = randomUUID(); const challenge = randomBytes(32).toString("base64url"); diff --git a/packages/core/src/feature-names.ts b/packages/core/src/feature-names.ts new file mode 100644 index 00000000..a17ed62b --- /dev/null +++ b/packages/core/src/feature-names.ts @@ -0,0 +1,5 @@ +// PEP-224: the platform features a monitor can switch off (no imports: observe.ts and +// feature-status.ts both use it). +export const FEATURE_NAMES = ["egov_login", "mcp", "google_login", "bot", "voice", "bugsink"] as const; +export type FeatureName = (typeof FEATURE_NAMES)[number]; +export const isFeatureName = (v: unknown): v is FeatureName => (FEATURE_NAMES as readonly string[]).includes(String(v)); diff --git a/packages/core/src/feature-status.ts b/packages/core/src/feature-status.ts new file mode 100644 index 00000000..debc5eff --- /dev/null +++ b/packages/core/src/feature-status.ts @@ -0,0 +1,227 @@ +// PEP-224: platform features follow their monitors (PEP-202). A feature is `unavailable` while one +// of its monitors has been down longer than the feature's threshold (default 5 min), `degraded` +// while one is unstable, `available` otherwise — recovery follows the monitor's own +// recover_threshold. Reading is cheap (one query of observe.db, cached 15 s per process) and never +// blocks: any trouble with observe.db means «available». The observer announces changes +// (`featureTick`): the journal, one message to the «services» channel, a poke for live pages. +import type { Db } from "@peppa/db"; +import { m as tr } from "@peppa/shared/i18n"; +import { PeppaError } from "./errors.ts"; +import { FEATURE_NAMES, isFeatureName, type FeatureName } from "./feature-names.ts"; +import { alertAdmins } from "./monitor.ts"; +import { notify } from "./notify.ts"; +import { listMonitors, observeDb, type Monitor } from "./observe.ts"; +import { getPlatformChannel, platformProjectKey, postToChannel } from "./platform-channel.ts"; +import { logEvent } from "./audit.ts"; +import { getProject } from "./projects.ts"; + +export { FEATURE_NAMES, isFeatureName, type FeatureName } from "./feature-names.ts"; + +export type FeatureState = "available" | "degraded" | "unavailable"; + +export interface FeatureInfo { + /** For people (a key of the translations). */ + label: string; + /** What a person sees on a grey button. */ + unavailableText: string; +} + +const GENERIC = tr("Временно недоступно — технические неполадки. Попробуйте позже"); + +export const FEATURES: Record = { + egov_login: { label: tr("Вход через eGov"), unavailableText: tr("Временно недоступно — технические неполадки на стороне eGov. Попробуйте позже") }, + mcp: { label: tr("Подключение к Claude и ChatGPT"), unavailableText: tr("MCP временно недоступен — технические неполадки. Попробуйте позже") }, + google_login: { label: tr("Вход через Google"), unavailableText: tr("Временно недоступно — технические неполадки на стороне Google. Попробуйте позже") }, + bot: { label: tr("Telegram-бот"), unavailableText: GENERIC }, + voice: { label: tr("Голосовой ввод"), unavailableText: GENERIC }, + bugsink: { label: tr("Отслеживание ошибок"), unavailableText: GENERIC }, +}; + +export const DEGRADED_TEXT = tr("Может работать с задержками"); +export const DEFAULT_DISABLE_AFTER_MIN = 5; +const CACHE_MS = 15_000; + +export interface FeatureStatus { + name: FeatureName; + state: FeatureState; + /** Since when the linked service fails (unavailable / degraded). */ + since: string | null; + disableAfterMin: number; + /** Linked monitors (not on pause). */ + monitors: Array>; + /** Monitors that make the state, with their last reason. */ + failing: Array<{ id: number; name: string; state: Monitor["state"]; since: string | null; reason: string }>; +} + +type MonitorLike = Pick; + +/** The rule, pure: monitors + thresholds → the state of every feature. */ +export function computeFeatures(monitors: MonitorLike[], thresholds: Partial>, now = new Date()): Record { + const out = {} as Record; + for (const name of FEATURE_NAMES) { + const disableAfterMin = thresholds[name] ?? DEFAULT_DISABLE_AFTER_MIN; + const linked = monitors.filter((m) => !m.paused && m.features.includes(name)); + const longDown = linked.filter((m) => m.state === "down" && now.getTime() - Date.parse(m.stateSince ?? now.toISOString()) >= disableAfterMin * 60_000); + const shaky = linked.filter((m) => m.state === "degraded"); + const state: FeatureState = longDown.length ? "unavailable" : shaky.length ? "degraded" : "available"; + const failing = (state === "unavailable" ? longDown : state === "degraded" ? shaky : []).map((m) => ({ + id: m.id, + name: m.name, + state: m.state, + since: m.stateSince, + reason: String(m.lastDetail?.reason ?? ""), + })); + const since = failing.map((f) => f.since).filter((s): s is string => !!s).sort()[0] ?? null; + out[name] = { name, state, since, disableAfterMin, monitors: linked.map((m) => ({ id: m.id, name: m.name, state: m.state, stateSince: m.stateSince })), failing }; + } + return out; +} + +const allAvailable = (): Record => computeFeatures([], {}); + +/** Per-feature thresholds set by the superadmin (no row = 5 min). */ +export function featureThresholds(): Partial> { + const out: Partial> = {}; + for (const r of observeDb().prepare("SELECT name, disable_after_min FROM features WHERE disable_after_min IS NOT NULL").all() as Array<{ name: string; disable_after_min: number }>) + if (isFeatureName(r.name)) out[r.name] = Number(r.disable_after_min); + return out; +} + +let cache: { at: number; value: Record } | null = null; + +/** Tests and the superadmin's changes: read afresh next time. */ +export function resetFeatureCache(): void { + cache = null; +} + +/** Every feature's state (cached 15 s); trouble with observe.db = everything available. */ +export function featureStatuses(o: { now?: Date; fresh?: boolean } = {}): Record { + const now = o.now ?? new Date(); + if (!o.fresh && !o.now && cache && Date.now() - cache.at < CACHE_MS) return cache.value; + let value: Record; + try { + value = computeFeatures(listMonitors(), featureThresholds(), now); + } catch (e) { + console.error("feature-status: observe.db unavailable, everything counts as available:", (e as Error).message); + value = allAvailable(); + } + if (!o.now) cache = { at: Date.now(), value }; + return value; +} + +export const featureStatus = (name: FeatureName, o: { now?: Date; fresh?: boolean } = {}): FeatureStatus => featureStatuses(o)[name]; + +/** Servers check too: refuses (PeppaError with the person's text) when the feature is unavailable. */ +export function assertFeatureAvailable(name: FeatureName, o: { now?: Date } = {}): void { + if (featureStatus(name, o).state === "unavailable") throw new PeppaError(FEATURES[name].unavailableText); +} + +/** A grey control's data for the web (kept small: it goes to client components). */ +export interface FeatureGateView { + name: FeatureName; + state: FeatureState; + since: string | null; + text: string; +} +export function featureGateView(name: FeatureName, o: { now?: Date } = {}): FeatureGateView { + const s = featureStatus(name, o); + return { name, state: s.state, since: s.since, text: s.state === "unavailable" ? FEATURES[name].unavailableText : s.state === "degraded" ? DEGRADED_TEXT : "" }; +} + +export function setFeatureThreshold(name: string, minutes: number): void { + if (!isFeatureName(name)) throw new PeppaError(tr("Неизвестная функция: {name}. Есть: {list}", { name, list: FEATURE_NAMES.join(", ") })); + if (!Number.isInteger(minutes) || minutes < 0 || minutes > 1440) throw new PeppaError(tr("{field}: целое число от {min} до {max}", { field: "disableAfterMin", min: 0, max: 1440 })); + observeDb().prepare("INSERT INTO features (name, disable_after_min) VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET disable_after_min = excluded.disable_after_min").run(name, minutes); + resetFeatureCache(); +} + +export interface FeatureLogEntry { + id: number; + name: FeatureName; + state: FeatureState; + reason: string; + at: string; +} + +export function featureLog(limit = 50): FeatureLogEntry[] { + return (observeDb().prepare("SELECT * FROM feature_log ORDER BY at DESC, id DESC LIMIT ?").all(limit) as Array>) + .filter((r) => isFeatureName(r.name)) + .map((r) => ({ id: Number(r.id), name: r.name as FeatureName, state: r.state as FeatureState, reason: String(r.reason), at: String(r.at) })); +} + +/** Live pages (scope `features`): the announced states; "" when observe.db is unavailable. */ +export function featureFingerprint(): string { + try { + return (observeDb().prepare("SELECT coalesce(group_concat(name || ':' || coalesce(state,'') || ':' || coalesce(changed_at,''), ','), '') AS f FROM features").get() as { f: string }).f; + } catch { + return ""; + } +} + +const esc = (s: string) => s.replace(/&/g, "&").replace(//g, ">"); + +function why(s: FeatureStatus, now: Date): string { + return s.failing + .map((f) => { + const n = Math.max(1, Math.round((now.getTime() - Date.parse(f.since ?? now.toISOString())) / 60_000)); + return f.reason ? `${f.name} — ${f.reason}, ${n} мин` : `${f.name}, ${n} мин`; + }) + .join("; "); +} + +/** Text of the message to the «services» channel (superadmin's: monitor names as they are). */ +export function featureChangeText(s: FeatureStatus, now = new Date()): string { + return s.state === "unavailable" + ? tr("⛔ «{feature}» отключено для пользователей: не работает {why}", { feature: FEATURES[s.name].label, why: why(s, now) }) + : tr("✅ «{feature}» снова включено для пользователей", { feature: FEATURES[s.name].label }); +} + +export interface FeatureTickOptions { + now?: Date; + log?: (s: string) => void; +} + +/** + * The observer, after its checks: compares the computed states with the announced ones. A change + * to/from «unavailable» goes to the feature journal, the platform project's events and the + * «services» channel (no channel — the superadmins); every change pokes live pages. The first + * computation only remembers. Returns the changed features. + */ +export async function featureTick(db: Db, o: FeatureTickOptions = {}): Promise { + const now = o.now ?? new Date(); + const log = o.log ?? (() => {}); + const iso = now.toISOString(); + const odb = observeDb(); + const statuses = computeFeatures(listMonitors(), featureThresholds(), now); + const known = new Map((odb.prepare("SELECT name, state FROM features").all() as Array<{ name: string; state: string | null }>).map((r) => [r.name, r.state])); + const changed: FeatureName[] = []; + for (const name of FEATURE_NAMES) { + const s = statuses[name]; + const prev = known.get(name) ?? null; + if (prev === s.state) continue; + const reason = s.state === "available" ? "" : why(s, now); + odb + .prepare("INSERT INTO features (name, state, since, reason, changed_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(name) DO UPDATE SET state = excluded.state, since = excluded.since, reason = excluded.reason, changed_at = excluded.changed_at") + .run(name, s.state, s.since, reason, iso); + changed.push(name); + // The first computation (no state yet) and degraded ↔ available are not announced. + if (prev === null || (prev === "unavailable") === (s.state === "unavailable")) continue; + odb.prepare("INSERT INTO feature_log (name, state, reason, at) VALUES (?, ?, ?, ?)").run(name, s.state === "unavailable" ? "unavailable" : "available", reason, iso); + const text = featureChangeText(s, now); + log(`feature: ${name} ${prev} → ${s.state}${reason ? ` (${reason})` : ""}`); + const p = await getProject(db, platformProjectKey()).catch(() => null); + if (p) await logEvent(db, { projectId: p.id, type: s.state === "unavailable" ? "feature_disabled" : "feature_enabled", payload: { feature: name, reason, since: s.since } }).catch(() => {}); + const key = `feature:${name}:${s.state === "unavailable" ? "off" : "on"}:${iso}`; + try { + const channel = await getPlatformChannel(db); + if (!(await postToChannel(db, "services", `mon:ch:${key}`, esc(text), channel))) await alertAdmins(db, `mon:${key}`, text, log); + } catch (e) { + log(`feature: announce failed: ${(e as Error).message}`); + } + } + if (changed.length) { + resetFeatureCache(); + for (const name of changed) await notify(db, { type: "feature", name }).catch(() => {}); + } + return changed; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a89e413a..04a895d9 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -101,5 +101,6 @@ export * from "./egress.ts"; export * from "./fallback-fetch.ts"; export * from "./observe.ts"; export * from "./observe-checks.ts"; +export * from "./feature-status.ts"; export * from "./accept-screen.ts"; export * from "./accept-digest.ts"; diff --git a/packages/core/src/notify.ts b/packages/core/src/notify.ts index ca816d39..7a51f435 100644 --- a/packages/core/src/notify.ts +++ b/packages/core/src/notify.ts @@ -11,7 +11,8 @@ export type PeppaNotification = | { type: "progress"; eventId: number } | { type: "session_updated"; sessionId: number } | { type: "incident"; incidentId: number } - | { type: "chat_message"; messageId: number }; + | { type: "chat_message"; messageId: number } + | { type: "feature"; name: string }; /** Services that want live updates; each listens on its own unix socket in PEPPA_HOME (web: PEP-37). */ export const SUBSCRIBERS = ["bot", "web"] as const; diff --git a/packages/core/src/observe.ts b/packages/core/src/observe.ts index 8358d0c9..18ab40db 100644 --- a/packages/core/src/observe.ts +++ b/packages/core/src/observe.ts @@ -14,6 +14,7 @@ import type { Db } from "@peppa/db"; import { PeppaError } from "./errors.ts"; import { alertAdmins } from "./monitor.ts"; import { getPlatformChannel, postToChannel } from "./platform-channel.ts"; +import { FEATURE_NAMES, isFeatureName, type FeatureName } from "./feature-names.ts"; import { realObserveProbes, runCheck, type CheckResult, type ObserveProbes } from "./observe-checks.ts"; export type MonitorKind = "http" | "tcp" | "dns" | "internet" | "heartbeat"; @@ -71,6 +72,8 @@ export interface Monitor { lastPingAt: string | null; lastDetail: Record | null; incidentId: number | null; + /** PEP-224: features switched off while this monitor is down. */ + features: FeatureName[]; } export interface MonitorCheck { @@ -102,6 +105,8 @@ export interface MonitorInput { timeoutMs?: number; failThreshold?: number; recoverThreshold?: number; + /** PEP-224: features to switch off while this monitor is down. */ + features?: string[]; } export const MIN_INTERVAL_SEC = 30; @@ -158,7 +163,30 @@ const SCHEMA = [ `CREATE TABLE observe_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)`, ]; /** Each entry upgrades the file by one version (PRAGMA user_version). */ -const MIGRATIONS: string[][] = [SCHEMA]; +const MIGRATIONS: string[][] = [ + SCHEMA, + // PEP-224: monitor → features, per-feature threshold and the announced state, their journal. + [ + `ALTER TABLE monitors ADD COLUMN features TEXT NOT NULL DEFAULT '[]'`, + `CREATE TABLE features ( + name TEXT PRIMARY KEY, + disable_after_min INTEGER, + state TEXT, + since TEXT, + reason TEXT, + changed_at TEXT + )`, + `CREATE TABLE feature_log ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + state TEXT NOT NULL, + reason TEXT NOT NULL, + at TEXT NOT NULL + )`, + `CREATE INDEX feature_log_at ON feature_log (at)`, + `UPDATE monitors SET features = '["egov_login"]' WHERE name IN ('eGov relay', 'eGov relay — DNS') AND created_by = 'system'`, + ], +]; const opened = new Map(); @@ -228,6 +256,7 @@ function toMonitor(r: Row): Monitor { lastPingAt: (r.last_ping_at as string | null) ?? null, lastDetail: json(r.last_detail, null), incidentId: r.incident_id == null ? null : Number(r.incident_id), + features: (json(r.features, []) as unknown[]).filter(isFeatureName), }; } @@ -304,7 +333,14 @@ export function normalizeTarget(kind: MonitorKind, t: Record): } } -function normalize(input: MonitorInput): Required> & { target: MonitorTarget } { +/** PEP-224: known feature names, without repeats; an unknown one is refused. */ +export function normalizeFeatures(v: unknown): FeatureName[] { + const list = (Array.isArray(v) ? v : String(v ?? "").split(/[\s,]+/)).map((x) => String(x).trim()).filter(Boolean); + for (const f of list) if (!isFeatureName(f)) bad("Неизвестная функция: {name}. Есть: {list}", { name: f, list: FEATURE_NAMES.join(", ") }); + return [...new Set(list)] as FeatureName[]; +} + +function normalize(input: MonitorInput): Required> & { target: MonitorTarget; features: FeatureName[] } { const name = String(input.name ?? "").trim(); if (!name || name.length > 80) bad("Название: от 1 до 80 символов"); if (!MONITOR_KINDS.includes(input.kind)) bad("Неизвестный вид мониторинга: {kind}", { kind: String(input.kind) }); @@ -317,6 +353,7 @@ function normalize(input: MonitorInput): Required> timeoutMs: int(input.timeoutMs ?? 10_000, 1_000, 30_000, "timeoutMs"), failThreshold: int(input.failThreshold ?? 3, 1, 20, "failThreshold"), recoverThreshold: int(input.recoverThreshold ?? 2, 1, 20, "recoverThreshold"), + features: normalizeFeatures(input.features ?? []), }; } @@ -341,10 +378,10 @@ export function createMonitor(input: MonitorInput, author: string, now = new Dat const token = n.kind === "heartbeat" ? randomBytes(18).toString("base64url") : null; const r = db .prepare( - `INSERT INTO monitors (name, kind, target, interval_sec, timeout_ms, fail_threshold, recover_threshold, token, created_by, created_at, updated_at, state_since, last_ping_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`, + `INSERT INTO monitors (name, kind, target, interval_sec, timeout_ms, fail_threshold, recover_threshold, token, created_by, created_at, updated_at, state_since, last_ping_at, features) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`, ) - .get(n.name, n.kind, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, token, author, iso, iso, iso, n.kind === "heartbeat" ? iso : null) as Row; + .get(n.name, n.kind, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, token, author, iso, iso, iso, n.kind === "heartbeat" ? iso : null, JSON.stringify(n.features)) as Row; return toMonitor(r); } @@ -360,10 +397,11 @@ export function updateMonitor(id: number, patch: Partial, now = ne timeoutMs: patch.timeoutMs ?? cur.timeoutMs, failThreshold: patch.failThreshold ?? cur.failThreshold, recoverThreshold: patch.recoverThreshold ?? cur.recoverThreshold, + features: patch.features ?? cur.features, }); const r = observeDb() - .prepare(`UPDATE monitors SET name = ?, target = ?, interval_sec = ?, timeout_ms = ?, fail_threshold = ?, recover_threshold = ?, updated_at = ?, last_check_at = NULL WHERE id = ? RETURNING *`) - .get(n.name, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, now.toISOString(), id) as Row; + .prepare(`UPDATE monitors SET name = ?, target = ?, interval_sec = ?, timeout_ms = ?, fail_threshold = ?, recover_threshold = ?, features = ?, updated_at = ?, last_check_at = NULL WHERE id = ? RETURNING *`) + .get(n.name, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, JSON.stringify(n.features), now.toISOString(), id) as Row; return toMonitor(r); } @@ -612,10 +650,33 @@ export function seedMonitors(now = new Date()): Monitor[] { if (db.prepare("SELECT 1 FROM observe_meta WHERE key = 'seeded'").get()) return []; const made = [ createMonitor({ name: "Интернет", kind: "internet", target: { hosts: DEFAULT_INTERNET_HOSTS }, intervalSec: 60 }, "system", now), - createMonitor({ name: "eGov relay", kind: "http", target: { url: "https://sign.aitu.uz/" }, intervalSec: 60 }, "system", now), - createMonitor({ name: "eGov relay — DNS", kind: "dns", target: { host: "sign.aitu.uz" }, intervalSec: 300 }, "system", now), + createMonitor({ name: "eGov relay", kind: "http", target: { url: "https://sign.aitu.uz/" }, intervalSec: 60, features: ["egov_login"] }, "system", now), + createMonitor({ name: "eGov relay — DNS", kind: "dns", target: { host: "sign.aitu.uz" }, intervalSec: 300, features: ["egov_login"] }, "system", now), ]; db.prepare("INSERT INTO observe_meta (key, value) VALUES ('seeded', ?)").run(now.toISOString()); return made; } + +/** + * PEP-224: «MCP-сервер /mcp» and «MCP — вход OAuth» (they switch off `mcp`), once, when the web has + * a public address. Without a token /mcp answers 401 — that is the sign it is alive. + */ +export function seedFeatureMonitors(webUrl: string | undefined, now = new Date()): Monitor[] { + const db = observeDb(); + if (db.prepare("SELECT 1 FROM observe_meta WHERE key = 'seeded:mcp'").get()) return []; + let base: URL; + try { + base = new URL(webUrl ?? ""); + } catch { + return []; + } + if (/^(localhost|127\.|\[::1\])/.test(base.hostname)) return []; + const names = new Set(listMonitors().map((m) => m.name)); + const made: Monitor[] = []; + if (!names.has("MCP-сервер /mcp")) made.push(createMonitor({ name: "MCP-сервер /mcp", kind: "http", target: { url: new URL("/mcp", base).toString(), expectStatus: [401] }, intervalSec: 60, features: ["mcp"] }, "system", now)); + if (!names.has("MCP — вход OAuth")) + made.push(createMonitor({ name: "MCP — вход OAuth", kind: "http", target: { url: new URL("/.well-known/oauth-authorization-server", base).toString(), contains: "token_endpoint" }, intervalSec: 60, features: ["mcp"] }, "system", now)); + db.prepare("INSERT INTO observe_meta (key, value) VALUES ('seeded:mcp', ?)").run(now.toISOString()); + return made; +} diff --git a/packages/mcp/src/monitors.ts b/packages/mcp/src/monitors.ts index 00215d34..8a7b0c9c 100644 --- a/packages/mcp/src/monitors.ts +++ b/packages/mcp/src/monitors.ts @@ -6,6 +6,8 @@ import { createMonitor, deleteMonitor, describeTarget, + FEATURE_NAMES, + featureStatuses, getMonitor, getProject, logEvent, @@ -51,11 +53,15 @@ const common = { timeout_ms: z.number().int().optional().describe("Per check, 1000–30000 (default 10000)"), fail_threshold: z.number().int().optional().describe("Bad checks in a row before «down» (default 3)"), recover_threshold: z.number().int().optional().describe("Good checks in a row before «up» again (default 2)"), + features: z + .array(z.enum(FEATURE_NAMES)) + .optional() + .describe(`PEP-224: platform features to switch off for users (grey, «temporarily unavailable») while this monitor is down longer than the feature's threshold (default 5 min): ${FEATURE_NAMES.join(", ")}. [] — none; left out — unchanged`), }; const pct = (v: number | null) => (v == null ? "—" : `${(v * 100).toFixed(v >= 0.9995 ? 0 : 2)}%`); const line = (m: MonitorView) => - `- #${m.id} ${m.name} [${m.kind}] ${describeTarget(m, loadEnv().PEPPA_WEB_URL)} — ${m.paused ? "paused" : m.state}${m.lastDetail?.reason ? ` (${m.lastDetail.reason})` : ""} · uptime 24h ${pct(m.uptime24h)}, 7d ${pct(m.uptime7d)}`; + `- #${m.id} ${m.name} [${m.kind}] ${describeTarget(m, loadEnv().PEPPA_WEB_URL)} — ${m.paused ? "paused" : m.state}${m.lastDetail?.reason ? ` (${m.lastDetail.reason})` : ""} · uptime 24h ${pct(m.uptime24h)}, 7d ${pct(m.uptime7d)}${m.features.length ? ` · switches off: ${m.features.join(", ")}` : ""}`; async function journal(db: Db, type: string, sessionId: number | null | undefined, payload: Record) { const p = await getProject(db, platformProjectKey()).catch(() => null); @@ -68,7 +74,9 @@ export function registerMonitorTools(db: Db, define: Define, access: MonitorAcce define("list_monitors", "Observability (PEP-202): every monitor of the Peppa platform with its state, last reason and uptime for 24 h and 7 days.", {}, true, async () => { await access.check(); const list = listMonitorViews(); - return list.length ? list.map(line).join("\n") : "No monitors."; + const f = Object.values(featureStatuses({ fresh: true })); + const features = ["", "Features (PEP-224):", ...f.map((x) => `- ${x.name}: ${x.state}${x.since ? ` since ${x.since}` : ""} · off after ${x.disableAfterMin} min down · monitors: ${x.monitors.map((mm) => mm.name).join(", ") || "none"}`)]; + return [list.length ? list.map(line).join("\n") : "No monitors.", ...features].join("\n"); }); define("get_monitor", "Observability: one monitor — state, uptime, incidents of the week and the last checks.", { id: z.number().int(), checks: z.number().int().min(1).max(500).optional().describe("How many last checks (default 50)") }, true, async ({ id, checks }) => { @@ -95,7 +103,7 @@ export function registerMonitorTools(db: Db, define: Define, access: MonitorAcce false, async (a) => { const who = await access.check(); - const m = createMonitor({ name: a.name, kind: a.kind as MonitorKind, target: a.target, intervalSec: a.interval_sec, timeoutMs: a.timeout_ms, failThreshold: a.fail_threshold, recoverThreshold: a.recover_threshold }, who.author); + const m = createMonitor({ name: a.name, kind: a.kind as MonitorKind, target: a.target, intervalSec: a.interval_sec, timeoutMs: a.timeout_ms, failThreshold: a.fail_threshold, recoverThreshold: a.recover_threshold, features: a.features }, who.author); await journal(db, "monitor_created", who.sessionId, { id: m.id, name: m.name, kind: m.kind, target: m.target, author: who.author }); return `Created #${m.id} ${m.name} [${m.kind}] ${describeTarget(m, loadEnv().PEPPA_WEB_URL)}; first check within a few seconds.`; }, @@ -104,9 +112,9 @@ export function registerMonitorTools(db: Db, define: Define, access: MonitorAcce define("update_monitor", "Observability: change a monitor (the kind stays). Fields left out stay.", { id: z.number().int(), name: z.string().min(1).max(80).optional(), target: target.optional(), ...common }, false, async (a) => { const who = await access.check(); found(a.id); - const m = updateMonitor(a.id, { name: a.name, target: a.target, intervalSec: a.interval_sec, timeoutMs: a.timeout_ms, failThreshold: a.fail_threshold, recoverThreshold: a.recover_threshold }); - await journal(db, "monitor_updated", who.sessionId, { id: m.id, name: m.name, author: who.author }); - return `Updated #${m.id} ${m.name}.`; + const m = updateMonitor(a.id, { name: a.name, target: a.target, intervalSec: a.interval_sec, timeoutMs: a.timeout_ms, failThreshold: a.fail_threshold, recoverThreshold: a.recover_threshold, features: a.features }); + await journal(db, "monitor_updated", who.sessionId, { id: m.id, name: m.name, features: m.features, author: who.author }); + return `Updated #${m.id} ${m.name}${m.features.length ? `; switches off: ${m.features.join(", ")}` : ""}.`; }); define("pause_monitor", "Observability: pause (no checks, no messages) or resume a monitor.", { id: z.number().int(), paused: z.boolean() }, false, async ({ id, paused }) => { diff --git a/packages/runner/src/live.ts b/packages/runner/src/live.ts index 4a67a8f7..624e0eef 100644 --- a/packages/runner/src/live.ts +++ b/packages/runner/src/live.ts @@ -6,11 +6,11 @@ import { m } from "@peppa/shared/i18n"; import { existsSync, statSync } from "node:fs"; import { join } from "node:path"; -import { findChangeDir, listenEvents, projectForUser, STEP_EVENT, stepView, type StepView, type User } from "@peppa/core"; +import { featureFingerprint, findChangeDir, resetFeatureCache, listenEvents, projectForUser, STEP_EVENT, stepView, type StepView, type User } from "@peppa/core"; import { events, sessions, tasks, type Db } from "@peppa/db"; import { and, eq, gt } from "drizzle-orm"; -export type LiveScope = "home" | "runners" | "chats" | "team" | `project:${number}` | `task:${number}` | `steps:${number}`; +export type LiveScope = "home" | "runners" | "chats" | "team" | "features" | `project:${number}` | `task:${number}` | `steps:${number}`; export type LiveEvent = { type: "change"; scope: LiveScope } | { type: "step"; scope: LiveScope; step: StepView }; type Listener = (e: LiveEvent) => void; @@ -30,7 +30,7 @@ const WAKE_DEBOUNCE_MS = 250; export function parseScopes(raw: string | null): LiveScope[] { const out = new Set(); for (const part of (raw ?? "").split(",").map((s) => s.trim()).filter(Boolean)) { - if (part === "home" || part === "runners" || part === "chats" || part === "team") out.add(part); + if (part === "home" || part === "runners" || part === "chats" || part === "team" || part === "features") out.add(part); else if (/^(project|task|steps):[1-9]\d{0,9}$/.test(part)) out.add(part as LiveScope); else throw new LiveError(m("Неизвестная область: {scope}", { scope: part }), 400); } @@ -38,8 +38,10 @@ export function parseScopes(raw: string | null): LiveScope[] { return [...out]; } -/** Access: project/story/runner scopes need the project; home/runners only a user. */ -export async function checkScopeAccess(db: Db, user: User, scope: LiveScope): Promise { +/** Access: project/story/runner scopes need the project; home/runners only a user; `features` (PEP-224) nobody. */ +export async function checkScopeAccess(db: Db, user: User | null, scope: LiveScope): Promise { + if (scope === "features") return; + if (!user) throw new LiveError(m("Нужен вход"), 401); const [kind, raw] = scope.split(":") as [string, string?]; const id = Number(raw); let projectId: number | undefined; @@ -57,6 +59,8 @@ const ACTIVE_SESSIONS = `group_concat(CASE WHEN ended_at IS NULL THEN id || ':' /** One SQL per scope; frequent fields (last_activity_at, steps, heartbeats) are left out. */ function fingerprint(db: Db, scope: LiveScope): string { + // PEP-224: features follow monitors (observe.db) — no user data, the login page watches it too. + if (scope === "features") return featureFingerprint(); const c = db.$client; const [kind, raw] = scope.split(":") as [string, string?]; const id = Number(raw); @@ -252,6 +256,8 @@ class LiveHub { const fp = fingerprint(this.db, scope); if (fp === this.prints.get(scope)) continue; this.prints.set(scope, fp); + // PEP-224: the observer announced a feature change — pages must not read the 15 s cache. + if (scope === "features") resetFeatureCache(); for (const fn of set) fn({ type: "change", scope }); } catch (e) { console.error(`live: ${scope} check failed`, e); @@ -271,7 +277,7 @@ export function liveHub(db: Db): LiveHub { } /** SSE response for /api/live: `change` / `step` events, pings for Cloudflare. */ -export async function liveSse(db: Db, user: User, scopes: LiveScope[], signal: AbortSignal, opts: { pingMs?: number } = {}): Promise { +export async function liveSse(db: Db, user: User | null, scopes: LiveScope[], signal: AbortSignal, opts: { pingMs?: number } = {}): Promise { for (const s of scopes) await checkScopeAccess(db, user, s); const enc = new TextEncoder(); let cleanup = () => {};