peppa/packages/core/src/monitor.ts
2026-11-16 17:29:29 +05:00

372 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Service monitoring (PEP-20): web, bot and watchdog write heartbeats into `settings`; the
// watchdog and the bot check each other (and the web) and alert the platform admins in
// Telegram through the outbox when a service goes quiet, without spamming.
import { m as tr } from "@peppa/shared/i18n";
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { hostname } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { telegramOutbox, users, type Db } from "@peppa/db";
import { and, count, eq, inArray, isNotNull, sql } from "drizzle-orm";
import { allowedLogins } from "./access.ts";
import { deliverToUser } from "./notifications.ts";
import { getPlatformChannel, postToChannel } from "./platform-channel.ts";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
import type { User } from "./users.ts";
export const SERVICES = ["web", "bot", "watchdog"] as const;
export type Service = (typeof SERVICES)[number];
export const SERVICE_NAMES: Record<Service, string> = { web: tr("веб"), bot: tr("бот"), watchdog: tr("вачдог") };
export interface Heartbeat {
at: string;
startedAt: string;
pid: number;
host: string;
version: string;
/** Commit the process runs (PEP-60); absent in heartbeats of older processes. */
commit?: string | null;
}
export interface ServiceState {
service: Service;
heartbeat: Heartbeat | null;
/** Ms since the last heartbeat; null if the service never reported. */
ageMs: number | null;
ok: boolean;
/** PEP-168: the heartbeat is fresh but the web port does not answer (process alive, site down). */
portDown?: boolean;
}
interface AlertState {
since: string | null; // heartbeat time before the current outage (its id); null = no outage
alerted: boolean;
reminders: number;
lastAlertAt: string | null;
/** PEP-60: the outage was posted to the platform channel (then its recovery is too). */
channelPosted?: boolean;
/** PEP-168: the outage is «process alive, port closed». */
portDown?: boolean;
}
export interface MonitorOptions {
now?: Date;
/** Quiet for longer than this = down (default PEPPA_MONITOR_STALE_MIN or 5 min). */
staleMs?: number;
/** Reminder about the same outage (default 60 min). */
remindMs?: number;
/** At most one alert about a service per this period (default 15 min). */
cooldownMs?: number;
log?: (msg: string) => void;
/** PEP-168: answers whether the web port responds (default: HTTP GET /api/health; PEPPA_WEB_PROBE=off disables). */
probe?: () => Promise<boolean | null>;
/** Consecutive failed port checks that make the web «down» (default PEPPA_MONITOR_PORT_FAILS or 3). */
portFails?: number;
}
// ── web port probe (PEP-168) ───────────────────────────────────────────────────────
// The web heartbeat is written by the Next process itself: it keeps beating after a rebuild of
// `.next` under a live `next start` made it stop listening. So the port is asked directly.
export function webProbeUrl(): string {
return process.env.PEPPA_WEB_PROBE_URL ?? `http://127.0.0.1:${process.env.PEPPA_WEB_PORT ?? 3100}/api/health`;
}
/** true — answers (any HTTP reply), false — refused/timeout, null — probe disabled. */
export async function probeWebPort(): Promise<boolean | null> {
if (process.env.PEPPA_WEB_PROBE === "off") return null;
try {
await fetch(webProbeUrl(), { signal: AbortSignal.timeout(5000), redirect: "manual" });
return true;
} catch {
return false;
}
}
export interface PortState {
/** Consecutive failed checks. */
fails: number;
/** Time of the first failed check of the current streak. */
since: string | null;
lastAt: string | null;
}
export const portKey = (s: Service) => `monitor.port:${s}`;
export const portFailLimit = () => Number(process.env.PEPPA_MONITOR_PORT_FAILS ?? 3);
const ADMINS = "platform.admins";
const hbKey = (s: Service) => `heartbeat:${s}`;
const alertKey = (s: Service) => `monitor.alert:${s}`;
const MIN = 60_000;
const startedAt = new Date().toISOString();
export const defaultStaleMs = () => Number(process.env.PEPPA_MONITOR_STALE_MIN ?? 5) * MIN;
/** Peppa version from the root package.json (bot, watchdog, CLI run from the checkout). */
export function peppaVersion(root = join(dirname(fileURLToPath(import.meta.url)), "../../..")): string {
try {
return (JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { version?: string }).version ?? "0.0.0";
} catch {
return "0.0.0";
}
}
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../..");
/** HEAD of Peppa's checkout right now (null outside git). */
export function headCommit(root = ROOT): string | null {
try {
return execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || null;
} catch {
return null;
}
}
let processCommit: string | null | undefined;
/** Commit this process runs: PEPPA_COMMIT, the web's build-time commit, or HEAD at first call. */
export function peppaCommit(): string | null {
if (processCommit === undefined) processCommit = process.env.PEPPA_COMMIT || process.env.NEXT_PUBLIC_PEPPA_COMMIT_FULL || headCommit();
return processCommit;
}
/** "I'm alive": called every 30–60 s by each service. */
export async function beat(db: Db, service: Service, o: { now?: Date; version?: string } = {}): Promise<void> {
const hb: Heartbeat = {
at: (o.now ?? new Date()).toISOString(),
startedAt,
pid: process.pid,
host: hostname(),
version: o.version ?? peppaVersion(),
commit: peppaCommit(),
};
await setSetting(db, hbKey(service), hb);
}
export async function serviceStatus(db: Db, o: { now?: Date; staleMs?: number; probe?: boolean | (() => Promise<boolean | null>) } = {}): Promise<ServiceState[]> {
const now = (o.now ?? new Date()).getTime();
const stale = o.staleMs ?? defaultStaleMs();
return Promise.all(
SERVICES.map(async (service) => {
const heartbeat = await getSetting<Heartbeat>(db, hbKey(service));
const ageMs = heartbeat ? Math.max(0, now - Date.parse(heartbeat.at)) : null;
const ok = ageMs != null && ageMs <= stale;
// PEP-168 (`peppa status`): ask the port right now, not only the heartbeat.
let portDown = false;
if (o.probe && service === "web" && ok) portDown = (await (typeof o.probe === "function" ? o.probe() : probeWebPort())) === false;
return { service, heartbeat, ageMs, ok: ok && !portDown, ...(portDown ? { portDown } : {}) };
}),
);
}
export const minutes = (ms: number) => Math.round(ms / MIN);
/** "ok" / "молчит 7 мин" / "нет данных". */
export function describeState(s: ServiceState): string {
if (s.ageMs == null) return tr("нет данных");
// glossary-ignore: «peppa status» читает только админ платформы
if (s.portDown) return tr("процесс жив, порт не отвечает");
return s.ok ? "ok" : tr("молчит {n} мин", { n: minutes(s.ageMs) });
}
// ── admins ─────────────────────────────────────────────────────────────────────────
/** Platform admins: `platform.admins`, or everyone allowlisted if it is not set. */
export async function platformAdmins(db: Db): Promise<string[]> {
return (await getSetting<string[]>(db, ADMINS)) ?? (await allowedLogins(db));
}
/** Superadmin of the platform (PEP-68, PEP-67): login in `platform.admins`. */
export async function isSuperadmin(db: Db, user: Pick<User, "login"> | null | undefined): Promise<boolean> {
if (!user) return false;
return (await platformAdmins(db)).includes(user.login.toLowerCase());
}
export async function setPlatformAdmins(db: Db, logins: string[] | null): Promise<void> {
if (logins === null) return deleteSetting(db, ADMINS);
await setSetting(db, ADMINS, [...new Set(logins.map((l) => l.trim().toLowerCase()).filter(Boolean))].sort());
}
/** Admins who paired Telegram: they get service alerts. */
export async function adminRecipients(db: Db): Promise<User[]> {
const logins = await platformAdmins(db);
if (!logins.length) return [];
return db.select().from(users).where(and(inArray(users.login, logins), isNotNull(users.telegramChatId)));
}
// ── checks ─────────────────────────────────────────────────────────────────────────
export async function alertAdmins(db: Db, key: string, text: string, log: (m: string) => void): Promise<number> {
const logins = await platformAdmins(db);
const admins = logins.length ? (await db.select().from(users).where(inArray(users.login, logins))).filter((u) => !u.disabledAt) : [];
let queued = 0;
let reached = 0;
for (const u of admins) {
// Monitoring goes by each admin's notification settings (PEP-35).
const r = await deliverToUser(db, u, {
event: "monitoring",
dedupeKey: `${key}:${u.telegramChatId}`,
pushKey: `${key}:u${u.id}`,
telegram: { params: { text } },
push: { title: tr("Мониторинг Peppa FACTORY"), body: text, url: "/", tag: key.split(":").slice(0, 2).join(":") },
urgency: "high",
});
if (r.telegram) queued++;
if (r.telegram || r.push || (u.telegramChatId && !r.muted)) reached++;
}
log(reached ? `monitor: ${text}` : `monitor: ${text} (нет админа с Telegram)`);
return queued;
}
const hhmm = (iso: string) => new Date(iso).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
/**
* Checks every service but `self` and alerts admins about outages and recoveries.
* Outbox keys are derived from the outage, so the watchdog and the bot checking at the
* same time queue one message. Returns the number of messages queued.
*/
export async function checkServices(db: Db, o: MonitorOptions & { self: Service }): Promise<number> {
const now = o.now ?? new Date();
const remindMs = o.remindMs ?? 60 * MIN;
const cooldownMs = o.cooldownMs ?? 15 * MIN;
const log = o.log ?? (() => {});
let queued = 0;
const channel = await getPlatformChannel(db);
for (const s of await serviceStatus(db, { now, staleMs: o.staleMs })) {
if (s.service === o.self || !s.heartbeat) continue;
// PEP-168: fresh heartbeat, but the port refuses several checks in a row = down.
let portSince: string | null = null;
if (s.service === "web" && s.ok) {
portSince = await trackPort(db, s.service, now, o);
if (portSince) {
s.ok = false;
s.portDown = true;
}
}
const name = SERVICE_NAMES[s.service];
const st = await getSetting<AlertState>(db, alertKey(s.service));
if (s.ok) {
const restarted = await noteProcess(db, s.service, s.heartbeat);
if (!st?.since) {
// PEP-60: a new process without an outage = a restart (an outage ends with «снова на связи»).
if (restarted) {
const build = `v${s.heartbeat.version}${s.heartbeat.commit ? ` · ${s.heartbeat.commit.slice(0, 7)}` : ""}`;
await postToChannel(db, "services", `mon:ch:${s.service}:restart:${s.heartbeat.host}:${s.heartbeat.pid}`, tr("🔄 Peppa FACTORY: {name} перезапущен ({build}).", { name, build }), channel);
}
continue;
}
// lastAlertAt survives the recovery: it is what the cooldown against flapping counts from.
await setSetting(db, alertKey(s.service), { since: null, alerted: false, reminders: 0, lastAlertAt: st.lastAlertAt });
const quiet = minutes(Math.max(Date.parse(s.heartbeat.at), st.portDown ? now.getTime() : 0) - Date.parse(st.since));
if (st.alerted) {
queued += await alertAdmins(db, `mon:${s.service}:up:${st.since}`, tr("✅ Peppa FACTORY: {name} снова на связи (молчал {n} мин).", { name, n: quiet }), log);
}
if (st.channelPosted && (await postToChannel(db, "services", `mon:ch:${s.service}:up:${st.since}`, tr("✅ Peppa FACTORY: {name} снова работает — простой {n} мин.", { name, n: quiet }), channel))) queued++;
continue;
}
// Down. A new outage starts when the last heartbeat differs from the remembered one.
// A port outage is identified by its first failed check (the heartbeat keeps changing).
const sinceId = portSince ?? s.heartbeat.at;
const cur: AlertState =
st?.since === sinceId ? st : { since: sinceId, alerted: false, reminders: 0, lastAlertAt: st?.lastAlertAt ?? null, ...(portSince ? { portDown: true } : {}) };
// PEP-60: the channel hears about an outage once (no reminders, no cooldown games).
if (!cur.channelPosted && (await postToChannel(db, "services", `mon:ch:${s.service}:down:${cur.since}`, tr("⚠️ Peppa FACTORY: {name} не отвечает с {time}.", { name, time: hhmm(portSince ?? s.heartbeat.at) }), channel))) {
cur.channelPosted = true;
queued++;
if (cur === st) await setSetting(db, alertKey(s.service), cur);
}
const sinceLast = cur.lastAlertAt ? now.getTime() - Date.parse(cur.lastAlertAt) : Infinity;
const due = cur.alerted ? sinceLast >= remindMs : sinceLast >= cooldownMs;
if (due) {
const n = cur.alerted ? cur.reminders + 1 : 0;
const text = portSince
// glossary-ignore: алерт мониторинга — только админам платформы
? tr("⚠️ Peppa FACTORY: {name} не отвечает: процесс жив (pid {pid}, {host}), но порт закрыт уже {n} мин.", { name, n: minutes(now.getTime() - Date.parse(portSince)), pid: s.heartbeat.pid, host: s.heartbeat.host })
: tr("⚠️ Peppa FACTORY: {name} молчит {n} мин (последний heartbeat {time}, pid {pid}, {host}).", { name, n: minutes(s.ageMs!), time: hhmm(s.heartbeat.at), pid: s.heartbeat.pid, host: s.heartbeat.host });
queued += await alertAdmins(db, `mon:${s.service}:down:${cur.since}:${n}`, text, log);
Object.assign(cur, { alerted: true, reminders: n, lastAlertAt: now.toISOString() });
}
if (cur !== st || due) await setSetting(db, alertKey(s.service), cur);
}
return queued;
}
/**
* PEP-168: one port check. Returns the start of the failure streak once it reaches the limit
* (the service counts as down), else null. A good answer resets the streak.
*/
async function trackPort(db: Db, service: Service, now: Date, o: MonitorOptions): Promise<string | null> {
const up = await (o.probe ?? probeWebPort)();
if (up == null) return null;
const prev = (await getSetting<PortState>(db, portKey(service))) ?? { fails: 0, since: null, lastAt: null };
if (up) {
if (prev.fails) await setSetting(db, portKey(service), { fails: 0, since: null, lastAt: now.toISOString() } satisfies PortState);
return null;
}
const next: PortState = { fails: prev.fails + 1, since: prev.since ?? now.toISOString(), lastAt: now.toISOString() };
await setSetting(db, portKey(service), next);
return next.fails >= (o.portFails ?? portFailLimit()) ? next.since : null;
}
/** Remembers the service's process; true when it differs from a previously seen one. */
async function noteProcess(db: Db, service: Service, hb: Heartbeat): Promise<boolean> {
const key = `monitor.process:${service}`;
const id = `${hb.host}:${hb.pid}:${hb.startedAt}`;
const prev = await getSetting<string>(db, key);
if (prev === id) return false;
await setSetting(db, key, id);
return prev != null;
}
/** Monitor messages not delivered yet (the watchdog sends them itself when the bot is down). */
export async function pendingMonitorMessages(db: Db) {
return db
.select()
.from(telegramOutbox)
.where(and(eq(telegramOutbox.status, "pending"), sql`${telegramOutbox.dedupeKey} like 'mon:%'`));
}
// ── summaries ──────────────────────────────────────────────────────────────────────
export interface HealthReport {
ok: boolean;
version: string;
commit: string | null;
db: { ok: boolean; latencyMs?: number; error?: string };
services: { service: Service; ok: boolean; lastHeartbeat: string | null; ageSec: number | null; version: string | null }[];
}
/** `/api/health`: DB reachability (3 s timeout), version, service freshness. No user data. */
export async function healthReport(db: Db, o: { now?: Date; version?: string; commit?: string | null; timeoutMs?: number } = {}): Promise<HealthReport> {
const base = { version: o.version ?? peppaVersion(), commit: o.commit ?? null };
const t0 = Date.now();
let timer: NodeJS.Timeout | undefined;
try {
await Promise.race([
(async () => db.get(sql`select 1 from settings limit 1`))(),
new Promise((_, rej) => (timer = setTimeout(() => rej(new Error("database timeout")), o.timeoutMs ?? 3000))),
]);
} catch (e) {
return { ok: false, ...base, db: { ok: false, error: (e as Error).message }, services: [] };
} finally {
clearTimeout(timer);
}
const latencyMs = Date.now() - t0;
const services = (await serviceStatus(db, { now: o.now })).map((s) => ({
service: s.service,
ok: s.ok,
lastHeartbeat: s.heartbeat?.at ?? null,
ageSec: s.ageMs == null ? null : Math.round(s.ageMs / 1000),
version: s.heartbeat?.version ?? null,
}));
return { ok: true, ...base, db: { ok: true, latencyMs }, services };
}
/** Outbox queue: pending (waiting to be sent) and failed (gave up). */
export async function outboxStats(db: Db): Promise<{ pending: number; failed: number }> {
const rows = await db.select({ status: telegramOutbox.status, n: count() }).from(telegramOutbox).groupBy(telegramOutbox.status);
const by = Object.fromEntries(rows.map((r) => [r.status, Number(r.n)]));
return { pending: by.pending ?? 0, failed: by.failed ?? 0 };
}