// 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 { execFile } from "node:child_process"; import { promisify } from "node:util"; import { beat, checkServices, getPlatformChannel, getSetting, portKey, postToChannel, setSetting, type PortState, markOutboxRetry, markOutboxSent, pendingMonitorMessages, serviceStatus, type MonitorOptions } from "@peppa/core"; import { m as tr } from "@peppa/shared/i18n"; 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 { const log = o.log ?? (() => {}); await beat(db, "watchdog", { now: o.now }); await checkServices(db, { ...o, self: "watchdog" }); await webRestartTick(db, o).catch((e) => log(`monitor: web restart: ${(e as Error).message}`)); 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); } const run = promisify(execFile); /** * PEP-168: the web process is alive but its port stays closed for `PEPPA_WEB_RESTART_AFTER` * (default 6) checks in a row → `launchctl kickstart -k`, at most `PEPPA_WEB_RESTART_MAX` (2) * times per hour; the platform channel hears about it. `PEPPA_WEB_RESTART=off` disables. */ export async function webRestartTick(db: Db, o: MonitorTickOptions = {}): Promise { if (process.env.PEPPA_WEB_RESTART === "off") return false; const port = await getSetting(db, portKey("web")); if (!port || port.fails < Number(process.env.PEPPA_WEB_RESTART_AFTER ?? 6)) return false; const now = o.now ?? new Date(); const key = "monitor.web-restarts"; const recent = ((await getSetting(db, key)) ?? []).filter((t) => now.getTime() - Date.parse(t) < 3600_000); if (recent.length >= Number(process.env.PEPPA_WEB_RESTART_MAX ?? 2)) return false; await setSetting(db, key, [...recent, now.toISOString()]); // The streak starts over: the next verdict is about the restarted process. await setSetting(db, portKey("web"), { fails: 0, since: port.since, lastAt: now.toISOString() } satisfies PortState); const bin = process.env.PEPPA_LAUNCHCTL_BIN ?? "launchctl"; await run(bin, ["kickstart", "-k", `gui/${process.getuid?.() ?? 501}/quest.telecom.peppa.web`], { timeout: 30_000 }); o.log?.("monitor: веб не слушал порт — перезапущен (launchctl kickstart -k)"); await postToChannel(db, "services", `mon:ch:web:kick:${now.toISOString()}`, tr("🔄 FORGE: веб не слушал порт — перезапускаю."), await getPlatformChannel(db)); return true; } /** 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); } } }