"use server"; // Observability (PEP-202): every action is superadmin-only (others get "not found"). import { createMonitor, deleteMonitor, requestSmoke, 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"; import { redirect } from "next/navigation"; import { asWebActor, requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { getT } from "@/lib/i18n"; const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim(); const BASE = "/observability"; async function attempt(f: FormData, back: string, fn: (login: string) => Promise): Promise { const user = asWebActor(await requireUser()); let target = back; try { await requireSuperadmin(db, user); target = (await fn(user.login)) || target; } catch (e) { const t = await getT(); const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message }); target = `${back}?error=${encodeURIComponent(msg.slice(0, 300))}`; } revalidatePath(BASE, "layout"); redirect(target); } async function journal(d: Db, type: string, payload: Record) { const p = await getProject(d, platformProjectKey()).catch(() => null); if (p) await logEvent(d, { projectId: p.id, type, payload }).catch(() => {}); } /** The form's fields → the monitor's target for its kind. */ function targetOf(kind: MonitorKind, f: FormData): MonitorTarget { const where = str(f, "where"); switch (kind) { case "http": return { url: where, contains: str(f, "contains") || undefined, expectStatus: str(f, "expectStatus") ? (str(f, "expectStatus").split(/[\s,]+/).map(Number) as number[]) : undefined, maxLatencyMs: str(f, "maxLatencyMs") ? Number(str(f, "maxLatencyMs")) : undefined }; case "tcp": { const [host, port] = where.split(/:(?=\d+$)/); return { host: host ?? "", port: Number(port) }; } case "dns": return { host: where }; case "internet": return { hosts: where.split(/[\s,]+/).filter(Boolean) }; case "heartbeat": return { graceSec: str(f, "graceSec") ? Number(str(f, "graceSec")) : undefined }; } } 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, // PEP-223: empty — the common default; the form always carries the whole state. remindMin: str(f, "remindMin") ? Number(str(f, "remindMin")) : null, remindDegraded: f.get("remindDegraded") === "1", }); export async function createMonitorAction(f: FormData) { await attempt(f, BASE, async (login) => { const kind = str(f, "kind") as MonitorKind; if (!MONITOR_KINDS.includes(kind)) throw new PeppaError(m("Неизвестный вид мониторинга: {kind}", { kind })); const mon = createMonitor({ name: str(f, "name"), kind, target: targetOf(kind, f), ...numbers(f) }, `user:${login}`); await journal(db, "monitor_created", { id: mon.id, name: mon.name, kind: mon.kind, target: mon.target, author: `user:${login}` }); return `${BASE}/${mon.id}`; }); } export async function updateMonitorAction(f: FormData) { const id = Number(str(f, "id")); await attempt(f, `${BASE}/${id}`, async (login) => { const kind = str(f, "kind") as MonitorKind; const mon = updateMonitor(id, { name: str(f, "name"), target: targetOf(kind, f), ...numbers(f) }); await journal(db, "monitor_updated", { id: mon.id, name: mon.name, author: `user:${login}` }); }); } export async function pauseMonitorAction(f: FormData) { const id = Number(str(f, "id")); await attempt(f, str(f, "back") || BASE, async (login) => { const paused = str(f, "paused") === "1"; const mon = setMonitorPaused(id, paused); await journal(db, "monitor_updated", { id: mon.id, name: mon.name, paused, author: `user:${login}` }); }); } export async function deleteMonitorAction(f: FormData) { const id = Number(str(f, "id")); await attempt(f, `${BASE}/${id}`, async (login) => { if (str(f, "confirm") !== "1") throw new PeppaError(m("Подтвердите удаление")); const mon = deleteMonitor(id); await journal(db, "monitor_deleted", { id: mon.id, name: mon.name, author: `user:${login}` }); 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}` }); }); } /** PEP-266: «Проверить сейчас» — the runner service starts the launch smoke test on its next tick. */ export async function requestSmokeAction(f: FormData) { await attempt(f, BASE, async (login) => { await requestSmoke(db, login); }); }