peppa/packages/core/src/observe-checks.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

171 lines
8.9 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.

// PEP-202: what one check of a monitor does. Network access goes through `ObserveProbes`, so tests
// replace the network with a mock. The DNS check compares the system resolver with a fallback one
// (PEPPA_FALLBACK_DNS, 1.1.1.1): «the system DNS gives unreachable addresses» is not «the host is
// down» (sign.aitu.uz, 2026-11-17; moved here from the watchdog's PEP-201 check).
// glossary-ignore-file: check results are read by the superadmin only.
import { Resolver, lookup } from "node:dns/promises";
import net from "node:net";
import tls from "node:tls";
import { m as tr } from "@peppa/shared/i18n";
import { fetchViaFallbackDns } from "./fallback-fetch.ts";
import type { DnsTarget, HeartbeatTarget, HttpTarget, InternetTarget, Monitor, TcpTarget } from "./observe.ts";
export interface CheckResult {
ok: boolean;
/** Works, but not well: slow, certificate expiring, the system DNS points at bad addresses. */
degraded: boolean;
latencyMs?: number;
/** Short reason for a bad result (shown in the message and the journal). */
reason: string;
detail: Record<string, unknown>;
}
export interface HttpAnswer {
status: number;
body: string;
}
export interface ObserveProbes {
http(url: string, o: { method: string; timeoutMs: number }): Promise<HttpAnswer & { via?: string }>;
certDaysLeft(host: string, port: number, timeoutMs: number): Promise<number | null>;
systemLookup(host: string): Promise<string[]>;
fallbackLookup(host: string): Promise<string[]>;
reachable(host: string, port: number, timeoutMs: number): Promise<boolean>;
}
const MAX_BODY = 64 * 1024;
export const realObserveProbes: ObserveProbes = {
async http(url, o) {
const init = { method: o.method, redirect: "follow" as const, signal: AbortSignal.timeout(o.timeoutMs), headers: { "User-Agent": "peppa-observer" } };
try {
const res = await fetch(url, init);
const body = o.method === "HEAD" ? "" : (await res.text()).slice(0, MAX_BODY);
return { status: res.status, body };
} catch (e) {
// No answer at all: the system resolver may point at an unreachable address (PEP-200).
const r = await fetchViaFallbackDns(url, { method: o.method }, o.timeoutMs);
if (!r) throw e;
return { status: r.status, body: "", via: "fallback-dns" };
}
},
certDaysLeft(host, port, timeoutMs) {
return new Promise((resolve) => {
const s = tls.connect({ host, port, servername: host, timeout: timeoutMs, rejectUnauthorized: false }, () => {
const c = s.getPeerCertificate();
s.destroy();
resolve(c?.valid_to ? Math.floor((Date.parse(c.valid_to) - Date.now()) / 86_400_000) : null);
});
s.once("timeout", () => (s.destroy(), resolve(null)));
s.once("error", () => resolve(null));
});
},
async systemLookup(host) {
return (await lookup(host, { all: true, family: 4 }).catch(() => [])).map((a) => a.address);
},
async fallbackLookup(host) {
const servers = (process.env.PEPPA_FALLBACK_DNS ?? "1.1.1.1,1.0.0.1").split(",").map((s) => s.trim()).filter((s) => s && s !== "off");
if (!servers.length) return [];
const r = new Resolver({ timeout: 4_000, tries: 2 });
r.setServers(servers);
return r.resolve4(host).catch(() => []);
},
reachable(host, port, timeoutMs) {
return new Promise((resolve) => {
const s = net.connect({ host, port, timeout: timeoutMs });
const done = (ok: boolean) => (s.destroy(), resolve(ok));
s.once("connect", () => done(true));
s.once("timeout", () => done(false));
s.once("error", () => done(false));
});
},
};
export type DnsState = "ok" | "dns" | "blocked" | "down";
export interface DnsProbe {
host: string;
state: DnsState;
/** System resolver's addresses. */
system: string[];
/** Fallback resolver's addresses that answered. */
working: string[];
}
/** Resolves a host both ways and tries its addresses on port 443. */
export async function probeDns(host: string, p: ObserveProbes, timeoutMs = 5_000): Promise<DnsProbe> {
const system = await p.systemLookup(host);
const sysOk = (await Promise.all(system.slice(0, 3).map((ip) => p.reachable(ip, 443, timeoutMs)))).some(Boolean);
if (sysOk) return { host, state: "ok", system, working: [] };
const fallback = (await p.fallbackLookup(host)).filter((ip) => !system.includes(ip)).slice(0, 3);
const ok = await Promise.all(fallback.map((ip) => p.reachable(ip, 443, timeoutMs)));
const working = fallback.filter((_, i) => ok[i]);
if (working.length) return { host, state: system.length ? "blocked" : "dns", system, working };
return { host, state: "down", system, working: [] };
}
async function httpCheck(t: HttpTarget, m: Monitor, p: ObserveProbes): Promise<CheckResult> {
const t0 = Date.now();
let a: HttpAnswer & { via?: string };
try {
a = await p.http(t.url, { method: t.method ?? "GET", timeoutMs: m.timeoutMs });
} catch (e) {
const msg = (e as Error).name === "TimeoutError" ? tr("нет ответа за {n} с", { n: Math.round(m.timeoutMs / 1000) }) : tr("нет ответа ({error})", { error: String((e as Error).cause ?? (e as Error).message).slice(0, 120) });
return { ok: false, degraded: false, latencyMs: Date.now() - t0, reason: msg, detail: {} };
}
const latencyMs = Date.now() - t0;
const detail: Record<string, unknown> = { status: a.status, ...(a.via ? { via: a.via } : {}) };
const okStatus = t.expectStatus?.length ? t.expectStatus.includes(a.status) : a.status >= 200 && a.status < 400;
if (!okStatus) return { ok: false, degraded: false, latencyMs, reason: tr("ответ {status}", { status: a.status }), detail };
if (t.contains && !a.via && !a.body.includes(t.contains)) return { ok: false, degraded: false, latencyMs, reason: tr("в ответе нет «{text}»", { text: t.contains }), detail };
const reasons: string[] = [];
if (a.via) reasons.push(tr("отвечает только через запасной DNS"));
if (t.maxLatencyMs && latencyMs > t.maxLatencyMs) reasons.push(tr("медленно: {n} мс", { n: latencyMs }));
const url = new URL(t.url);
if (url.protocol === "https:") {
const days = await p.certDaysLeft(url.hostname, Number(url.port) || 443, m.timeoutMs).catch(() => null);
if (days != null) {
detail.certDays = days;
if (days < (t.certDays ?? 14)) reasons.push(days < 0 ? tr("сертификат истёк") : tr("сертификат истекает через {n} дн.", { n: days }));
}
}
return { ok: true, degraded: reasons.length > 0, latencyMs, reason: reasons.join("; "), detail };
}
/** Runs one check of the monitor. */
export async function runCheck(m: Monitor, p: ObserveProbes, now = new Date()): Promise<CheckResult> {
switch (m.kind) {
case "http":
return httpCheck(m.target as HttpTarget, m, p);
case "tcp": {
const t = m.target as TcpTarget;
const t0 = Date.now();
const ok = await p.reachable(t.host, t.port, m.timeoutMs);
return { ok, degraded: false, latencyMs: Date.now() - t0, reason: ok ? "" : tr("порт {port} не открывается", { port: t.port }), detail: {} };
}
case "dns": {
const d = await probeDns((m.target as DnsTarget).host, p, Math.min(m.timeoutMs, 5_000));
const detail = { dns: d.state, system: d.system, working: d.working };
if (d.state === "ok") return { ok: true, degraded: false, reason: "", detail };
if (d.state === "blocked")
return { ok: true, degraded: true, reason: tr("системный DNS отдаёт недоступные адреса {bad}, рабочие — {ips} (их даёт 1.1.1.1)", { bad: d.system.join(", "), ips: d.working.join(", ") }), detail };
if (d.state === "dns") return { ok: true, degraded: true, reason: tr("системный DNS не отвечает, рабочие адреса {ips} даёт 1.1.1.1", { ips: d.working.join(", ") }), detail };
return { ok: false, degraded: false, reason: tr("недоступен ни по одному адресу"), detail };
}
case "internet": {
const hosts = (m.target as InternetTarget).hosts;
const probes = await Promise.all(hosts.map((h) => probeDns(h, p, Math.min(m.timeoutMs, 5_000))));
const up = probes.filter((x) => x.state !== "down").map((x) => x.host);
const detail = { up, down: probes.filter((x) => x.state === "down").map((x) => x.host) };
return up.length ? { ok: true, degraded: false, reason: "", detail } : { ok: false, degraded: false, reason: tr("не открывается ни один из адресов {hosts}", { hosts: hosts.join(", ") }), detail };
}
case "heartbeat": {
const grace = ((m.target as HeartbeatTarget).graceSec ?? 60) * 1000;
const last = m.lastPingAt ? Date.parse(m.lastPingAt) : Date.parse(m.createdAt);
const silent = now.getTime() - last;
const ok = silent <= m.intervalSec * 1000 + grace;
return { ok, degraded: false, reason: ok ? "" : tr("нет отметки {n} мин", { n: Math.round(silent / 60_000) }), detail: { lastPingAt: m.lastPingAt } };
}
}
}