peppa/packages/runner/src/monitor.ts
Асель 1085474c78 PEP-20: service monitoring — health, heartbeats, alerts to platform admins
- web/bot/watchdog heartbeats in settings (heartbeat:<service>)
- watchdog checks bot+web, bot checks watchdog+web; quiet > 5 min → Telegram alert
  to platform admins via outbox (platform.admins, default allowlist), recovery message,
  hourly reminder, 15 min cooldown, deterministic dedupe; watchdog sends directly
  when the bot is down
- GET /api/health (DB, version, services; 503 without DB)
- peppa status, peppa platform admins
- OpenSpec change pep-20-monitoring (archived), e2e monitor.test.ts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 14:06:54 +05:00

41 lines
2.1 KiB
TypeScript

// Watchdog side of service monitoring (PEP-20): heartbeat, check the bot and the web, and
// deliver monitor alerts straight to the Bot API when the bot itself is the one that's down.
import { beat, checkServices, markOutboxRetry, markOutboxSent, pendingMonitorMessages, serviceStatus, type MonitorOptions } from "@peppa/core";
import type { Db } from "@peppa/db";
export interface MonitorTickOptions extends MonitorOptions {
/** Bot API access for direct delivery (defaults: TELEGRAM_BOT_TOKEN, TELEGRAM_API_URL). */
telegram?: { token?: string; apiUrl?: string };
}
export async function monitorTick(db: Db, o: MonitorTickOptions = {}): Promise<void> {
const log = o.log ?? (() => {});
await beat(db, "watchdog", { now: o.now });
await checkServices(db, { ...o, self: "watchdog" });
const bot = (await serviceStatus(db, { now: o.now, staleMs: o.staleMs })).find((s) => s.service === "bot");
if (bot?.heartbeat && !bot.ok) await deliverDirect(db, o.telegram ?? {}, log);
}
/** Sends pending `mon:` outbox rows itself; marks them sent so the bot won't repeat them. */
async function deliverDirect(db: Db, tg: { token?: string; apiUrl?: string }, log: (m: string) => void) {
const token = tg.token ?? process.env.TELEGRAM_BOT_TOKEN;
if (!token) return;
const base = tg.apiUrl ?? process.env.TELEGRAM_API_URL ?? "https://api.telegram.org";
for (const row of await pendingMonitorMessages(db)) {
try {
const res = await fetch(`${base}/bot${token}/${row.method}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(row.params),
signal: AbortSignal.timeout(15_000),
});
const body = (await res.json().catch(() => ({}))) as { ok?: boolean; result?: { message_id?: number }; description?: string };
if (!body.ok) throw new Error(body.description ?? res.statusText);
await markOutboxSent(db, row, body.result?.message_id ?? null);
} catch (e) {
log(`monitor: direct send #${row.id}: ${(e as Error).message}`);
await markOutboxRetry(db, row, (e as Error).message);
}
}
}