// 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 { 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); } } }