peppa/apps/observer/src/observer.ts
peppa-bot ffd4e4c171 PEP-202: Observability — сервис мониторингов peppa-observer, раздел для суперадмина, MCP
Сервис peppa-observer (своя база observe.db, журнал 7 дней): мониторинги HTTP(S),
TCP, DNS (системный против 1.1.1.1), «Интернет», heartbeat; состояние меняется
после N неудач/удач подряд, одно сообщение в канал платформы на смену, упавшие
вместе с интернетом молчат. Раздел /observability и MCP-инструменты — только
суперадмину и агентам платформы. Встроенные: «Интернет», «eGov relay» (HTTP, DNS).
Проверка сети из вачдога (PEP-201) переехала сюда.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:15:36 +05:00

42 lines
1.8 KiB
TypeScript

// PEP-202: the `peppa-observer` service — runs the monitors of Observability. Every second it
// starts the checks that are due (they run in the background, each with its own timeout), every
// 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 type { Db } from "@peppa/db";
export interface ObserverOptions {
log?: (m: string) => void;
tickMs?: number;
probes?: ObserveProbes;
}
export async function runObserver(db: Db, o: ObserverOptions = {}, signal?: AbortSignal): Promise<void> {
const log = o.log ?? (() => {});
const made = seedMonitors();
if (made.length) log(`observer: built-in monitors created: ${made.map((m) => m.name).join(", ")}`);
log("observer started");
let lastBeat = 0;
let lastPrune = 0;
while (!signal?.aborted) {
const now = Date.now();
if (now - lastBeat >= 30_000) {
lastBeat = now;
await beat(db, "observer").catch((e: Error) => log(`observer: heartbeat failed: ${e.message}`));
}
if (now - lastPrune >= 3_600_000) {
lastPrune = now;
try {
const n = pruneObserve();
if (n) log(`observer: ${n} old checks deleted`);
} catch (e) {
log(`observer: prune failed: ${(e as Error).message}`);
}
}
// 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}`));
await new Promise((r) => setTimeout(r, o.tickMs ?? 1_000));
}
}