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

622 lines
26 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: Observability — monitors of the services Peppa depends on (and of the internet on the
// Peppa host). Monitors, their checks and incidents live in a separate SQLite file
// (PEPPA_OBSERVE_DB, default $PEPPA_HOME/observe.db): checks are frequent and must not compete with
// the main database. The `peppa-observer` process runs `observeTick`; the web and MCP read and
// change monitors through the functions here. Only the superadmin and the platform's agents get here.
// glossary-ignore-file: the section is for the superadmin only.
import { DatabaseSync } from "node:sqlite";
import { mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { randomBytes } from "node:crypto";
import { peppaHome } from "@peppa/shared";
import { m as tr } from "@peppa/shared/i18n";
import type { Db } from "@peppa/db";
import { PeppaError } from "./errors.ts";
import { alertAdmins } from "./monitor.ts";
import { getPlatformChannel, postToChannel } from "./platform-channel.ts";
import { realObserveProbes, runCheck, type CheckResult, type ObserveProbes } from "./observe-checks.ts";
export type MonitorKind = "http" | "tcp" | "dns" | "internet" | "heartbeat";
export type MonitorState = "unknown" | "up" | "degraded" | "down";
export const MONITOR_KINDS: MonitorKind[] = ["http", "tcp", "dns", "internet", "heartbeat"];
export interface HttpTarget {
url: string;
method?: "GET" | "HEAD";
/** Accepted codes; default 200–399. */
expectStatus?: number[];
/** Text the body must contain. */
contains?: string;
/** Slower than this = degraded. */
maxLatencyMs?: number;
/** The certificate expires sooner than this = degraded (https only; default 14). */
certDays?: number;
}
export interface TcpTarget {
host: string;
port: number;
}
export interface DnsTarget {
host: string;
}
export interface InternetTarget {
hosts: string[];
}
export interface HeartbeatTarget {
/** Extra seconds after the interval before a missing ping counts. */
graceSec?: number;
}
export type MonitorTarget = HttpTarget | TcpTarget | DnsTarget | InternetTarget | HeartbeatTarget;
export interface Monitor {
id: number;
name: string;
kind: MonitorKind;
target: MonitorTarget;
intervalSec: number;
timeoutMs: number;
failThreshold: number;
recoverThreshold: number;
paused: boolean;
/** Heartbeat monitors: the secret part of the ping address. */
token: string | null;
createdBy: string;
createdAt: string;
updatedAt: string;
state: MonitorState;
stateSince: string | null;
streakOk: number;
streakBad: number;
lastCheckAt: string | null;
lastPingAt: string | null;
lastDetail: Record<string, unknown> | null;
incidentId: number | null;
}
export interface MonitorCheck {
id: number;
monitorId: number;
at: string;
ok: boolean;
degraded: boolean;
latencyMs: number | null;
detail: Record<string, unknown>;
}
export interface MonitorIncident {
id: number;
monitorId: number;
state: MonitorState;
reason: string;
startedAt: string;
endedAt: string | null;
/** Fell together with the internet: no message about it. */
quiet: boolean;
}
export interface MonitorInput {
name: string;
kind: MonitorKind;
target: MonitorTarget;
intervalSec?: number;
timeoutMs?: number;
failThreshold?: number;
recoverThreshold?: number;
}
export const MIN_INTERVAL_SEC = 30;
export const MAX_MONITORS = 200;
export const DEFAULT_INTERVAL_SEC = 60;
export const retentionDays = () => Number(process.env.PEPPA_OBSERVE_RETENTION_DAYS) || 7;
// ── the database ───────────────────────────────────────────────────────────────────
const SCHEMA = [
`CREATE TABLE monitors (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
kind TEXT NOT NULL,
target TEXT NOT NULL,
interval_sec INTEGER NOT NULL,
timeout_ms INTEGER NOT NULL,
fail_threshold INTEGER NOT NULL,
recover_threshold INTEGER NOT NULL,
paused INTEGER NOT NULL DEFAULT 0,
token TEXT UNIQUE,
created_by TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
state TEXT NOT NULL DEFAULT 'unknown',
state_since TEXT,
streak_ok INTEGER NOT NULL DEFAULT 0,
streak_bad INTEGER NOT NULL DEFAULT 0,
last_check_at TEXT,
last_ping_at TEXT,
last_detail TEXT,
incident_id INTEGER
)`,
`CREATE TABLE monitor_checks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
monitor_id INTEGER NOT NULL REFERENCES monitors(id) ON DELETE CASCADE,
at TEXT NOT NULL,
ok INTEGER NOT NULL,
degraded INTEGER NOT NULL DEFAULT 0,
latency_ms INTEGER,
detail TEXT NOT NULL
)`,
`CREATE INDEX monitor_checks_monitor_at ON monitor_checks (monitor_id, at)`,
`CREATE TABLE monitor_incidents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
monitor_id INTEGER NOT NULL REFERENCES monitors(id) ON DELETE CASCADE,
state TEXT NOT NULL,
reason TEXT NOT NULL,
started_at TEXT NOT NULL,
ended_at TEXT,
quiet INTEGER NOT NULL DEFAULT 0
)`,
`CREATE INDEX monitor_incidents_monitor ON monitor_incidents (monitor_id, started_at)`,
`CREATE TABLE observe_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
];
/** Each entry upgrades the file by one version (PRAGMA user_version). */
const MIGRATIONS: string[][] = [SCHEMA];
const opened = new Map<string, DatabaseSync>();
export const observeDbPath = () => process.env.PEPPA_OBSERVE_DB ?? join(peppaHome(), "observe.db");
/** The observe database of this process (opened and migrated on first use). */
export function observeDb(): DatabaseSync {
const path = observeDbPath();
const known = opened.get(path);
if (known) return known;
mkdirSync(dirname(path), { recursive: true });
const db = new DatabaseSync(path);
db.exec("PRAGMA busy_timeout = 5000");
db.exec("PRAGMA journal_mode = WAL");
db.exec("PRAGMA foreign_keys = ON");
const version = Number((db.prepare("PRAGMA user_version").get() as { user_version: number }).user_version);
for (let v = version; v < MIGRATIONS.length; v++) {
db.exec("BEGIN IMMEDIATE");
try {
for (const sql of MIGRATIONS[v]!) db.exec(sql);
db.exec(`PRAGMA user_version = ${v + 1}`);
db.exec("COMMIT");
} catch (e) {
db.exec("ROLLBACK");
throw e;
}
}
opened.set(path, db);
return db;
}
/** Tests: forget opened files. */
export function closeObserveDb(): void {
for (const db of opened.values()) db.close();
opened.clear();
}
type Row = Record<string, unknown>;
const json = <T>(s: unknown, d: T): T => {
try {
return s == null ? d : (JSON.parse(String(s)) as T);
} catch {
return d;
}
};
function toMonitor(r: Row): Monitor {
return {
id: Number(r.id),
name: String(r.name),
kind: r.kind as MonitorKind,
target: json(r.target, {}) as MonitorTarget,
intervalSec: Number(r.interval_sec),
timeoutMs: Number(r.timeout_ms),
failThreshold: Number(r.fail_threshold),
recoverThreshold: Number(r.recover_threshold),
paused: Number(r.paused) === 1,
token: (r.token as string | null) ?? null,
createdBy: String(r.created_by),
createdAt: String(r.created_at),
updatedAt: String(r.updated_at),
state: r.state as MonitorState,
stateSince: (r.state_since as string | null) ?? null,
streakOk: Number(r.streak_ok),
streakBad: Number(r.streak_bad),
lastCheckAt: (r.last_check_at as string | null) ?? null,
lastPingAt: (r.last_ping_at as string | null) ?? null,
lastDetail: json(r.last_detail, null),
incidentId: r.incident_id == null ? null : Number(r.incident_id),
};
}
const toCheck = (r: Row): MonitorCheck => ({
id: Number(r.id),
monitorId: Number(r.monitor_id),
at: String(r.at),
ok: Number(r.ok) === 1,
degraded: Number(r.degraded) === 1,
latencyMs: r.latency_ms == null ? null : Number(r.latency_ms),
detail: json(r.detail, {}),
});
const toIncident = (r: Row): MonitorIncident => ({
id: Number(r.id),
monitorId: Number(r.monitor_id),
state: r.state as MonitorState,
reason: String(r.reason),
startedAt: String(r.started_at),
endedAt: (r.ended_at as string | null) ?? null,
quiet: Number(r.quiet) === 1,
});
// ── validation ─────────────────────────────────────────────────────────────────────
const HOST_RE = /^(?=.{1,253}$)([a-z0-9-]{1,63}\.)*[a-z0-9-]{1,63}$/i;
const IP_RE = /^\d{1,3}(\.\d{1,3}){3}$/;
const bad = (msg: string, vars?: Record<string, string | number>): never => {
throw new PeppaError(tr(msg, vars));
};
const int = (v: unknown, min: number, max: number, field: string): number => {
const n = Number(v);
if (!Number.isInteger(n) || n < min || n > max) bad("{field}: целое число от {min} до {max}", { field, min, max });
return n;
};
const host = (v: unknown): string => {
const h = String(v ?? "").trim().toLowerCase();
if (!HOST_RE.test(h) && !IP_RE.test(h)) bad("Неверное имя хоста: {host}", { host: h || "—" });
return h;
};
export function normalizeTarget(kind: MonitorKind, t: Record<string, unknown>): MonitorTarget {
switch (kind) {
case "http": {
let url: URL;
try {
url = new URL(String(t.url ?? ""));
} catch {
return bad("Неверный адрес: нужен http:// или https://");
}
if (url.protocol !== "http:" && url.protocol !== "https:") bad("Неверный адрес: нужен http:// или https://");
const out: HttpTarget = { url: url.toString() };
if (t.method === "HEAD") out.method = "HEAD";
if (t.expectStatus != null && (!Array.isArray(t.expectStatus) || t.expectStatus.length)) {
const list = (Array.isArray(t.expectStatus) ? t.expectStatus : String(t.expectStatus).split(/[\s,]+/)).filter((x) => String(x).trim() !== "");
if (list.length) out.expectStatus = list.map((c) => int(c, 100, 599, "expectStatus"));
}
if (t.contains != null && String(t.contains).trim()) out.contains = String(t.contains).slice(0, 200);
if (t.maxLatencyMs != null && String(t.maxLatencyMs) !== "") out.maxLatencyMs = int(t.maxLatencyMs, 1, 60_000, "maxLatencyMs");
if (t.certDays != null && String(t.certDays) !== "") out.certDays = int(t.certDays, 0, 365, "certDays");
return out;
}
case "tcp":
return { host: host(t.host), port: int(t.port, 1, 65535, "port") };
case "dns":
return { host: host(t.host) };
case "internet": {
const list = (Array.isArray(t.hosts) ? t.hosts : String(t.hosts ?? "").split(/[\s,]+/)).map(String).filter(Boolean);
if (!list.length || list.length > 10) bad("Интернет: от 1 до 10 адресов");
return { hosts: [...new Set(list.map(host))] };
}
case "heartbeat":
return t.graceSec != null && String(t.graceSec) !== "" ? { graceSec: int(t.graceSec, 0, 86_400, "graceSec") } : {};
}
}
function normalize(input: MonitorInput): Required<Omit<MonitorInput, "target">> & { target: MonitorTarget } {
const name = String(input.name ?? "").trim();
if (!name || name.length > 80) bad("Название: от 1 до 80 символов");
if (!MONITOR_KINDS.includes(input.kind)) bad("Неизвестный вид мониторинга: {kind}", { kind: String(input.kind) });
const intervalSec = int(input.intervalSec ?? DEFAULT_INTERVAL_SEC, MIN_INTERVAL_SEC, 86_400, "intervalSec");
return {
name,
kind: input.kind,
target: normalizeTarget(input.kind, (input.target ?? {}) as Record<string, unknown>),
intervalSec,
timeoutMs: int(input.timeoutMs ?? 10_000, 1_000, 30_000, "timeoutMs"),
failThreshold: int(input.failThreshold ?? 3, 1, 20, "failThreshold"),
recoverThreshold: int(input.recoverThreshold ?? 2, 1, 20, "recoverThreshold"),
};
}
// ── monitors ───────────────────────────────────────────────────────────────────────
export function getMonitor(id: number): Monitor | null {
const r = observeDb().prepare("SELECT * FROM monitors WHERE id = ?").get(id) as Row | undefined;
return r ? toMonitor(r) : null;
}
export function listMonitors(): Monitor[] {
return (observeDb().prepare("SELECT * FROM monitors ORDER BY name COLLATE NOCASE, id").all() as Row[]).map(toMonitor);
}
/** Creates a monitor; `author` is «user:<login>», «agent:s<id>» or «system». */
export function createMonitor(input: MonitorInput, author: string, now = new Date()): Monitor {
const n = normalize(input);
const db = observeDb();
const count = Number((db.prepare("SELECT count(*) AS n FROM monitors").get() as Row).n);
if (count >= MAX_MONITORS) bad("Мониторингов уже {n} — больше нельзя", { n: MAX_MONITORS });
const iso = now.toISOString();
const token = n.kind === "heartbeat" ? randomBytes(18).toString("base64url") : null;
const r = db
.prepare(
`INSERT INTO monitors (name, kind, target, interval_sec, timeout_ms, fail_threshold, recover_threshold, token, created_by, created_at, updated_at, state_since, last_ping_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`,
)
.get(n.name, n.kind, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, token, author, iso, iso, iso, n.kind === "heartbeat" ? iso : null) as Row;
return toMonitor(r);
}
export function updateMonitor(id: number, patch: Partial<MonitorInput>, now = new Date()): Monitor {
const cur = getMonitor(id);
if (!cur) return bad("Мониторинг не найден");
if (patch.kind && patch.kind !== cur.kind) bad("Вид мониторинга не меняется — создайте новый");
const n = normalize({
name: patch.name ?? cur.name,
kind: cur.kind,
target: (patch.target ?? cur.target) as MonitorTarget,
intervalSec: patch.intervalSec ?? cur.intervalSec,
timeoutMs: patch.timeoutMs ?? cur.timeoutMs,
failThreshold: patch.failThreshold ?? cur.failThreshold,
recoverThreshold: patch.recoverThreshold ?? cur.recoverThreshold,
});
const r = observeDb()
.prepare(`UPDATE monitors SET name = ?, target = ?, interval_sec = ?, timeout_ms = ?, fail_threshold = ?, recover_threshold = ?, updated_at = ?, last_check_at = NULL WHERE id = ? RETURNING *`)
.get(n.name, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, now.toISOString(), id) as Row;
return toMonitor(r);
}
/** Pause or resume; a paused monitor is not checked and says nothing. Resuming starts fresh. */
export function setMonitorPaused(id: number, paused: boolean, now = new Date()): Monitor {
const cur = getMonitor(id);
if (!cur) return bad("Мониторинг не найден");
const db = observeDb();
const iso = now.toISOString();
if (paused && cur.incidentId) db.prepare("UPDATE monitor_incidents SET ended_at = ? WHERE id = ? AND ended_at IS NULL").run(iso, cur.incidentId);
const r = db
.prepare(
paused
? `UPDATE monitors SET paused = 1, updated_at = ?, incident_id = NULL WHERE id = ? RETURNING *`
: `UPDATE monitors SET paused = 0, updated_at = ?, state = 'unknown', state_since = ?, streak_ok = 0, streak_bad = 0, last_check_at = NULL, last_ping_at = CASE WHEN kind = 'heartbeat' THEN ? ELSE last_ping_at END WHERE id = ? RETURNING *`,
)
.get(...(paused ? [iso, id] : [iso, iso, iso, id])) as Row;
return toMonitor(r);
}
export function deleteMonitor(id: number): Monitor {
const cur = getMonitor(id);
if (!cur) return bad("Мониторинг не найден");
observeDb().prepare("DELETE FROM monitors WHERE id = ?").run(id);
return cur;
}
/** A heartbeat monitor's ping (the web route `/api/observe/hb/<token>`); false — unknown token. */
export function pingHeartbeat(token: string, now = new Date()): boolean {
if (!/^[A-Za-z0-9_-]{10,64}$/.test(token)) return false;
const r = observeDb().prepare("UPDATE monitors SET last_ping_at = ? WHERE token = ? AND kind = 'heartbeat'").run(now.toISOString(), token);
return Number(r.changes) > 0;
}
export function monitorChecks(id: number, o: { limit?: number; offset?: number } = {}): MonitorCheck[] {
return (observeDb().prepare("SELECT * FROM monitor_checks WHERE monitor_id = ? ORDER BY at DESC, id DESC LIMIT ? OFFSET ?").all(id, o.limit ?? 50, o.offset ?? 0) as Row[]).map(toCheck);
}
export function monitorIncidents(id: number, limit = 50): MonitorIncident[] {
return (observeDb().prepare("SELECT * FROM monitor_incidents WHERE monitor_id = ? ORDER BY started_at DESC, id DESC LIMIT ?").all(id, limit) as Row[]).map(toIncident);
}
/** Share of good checks (degraded counts as working) since `sinceMs` ago; null without checks. */
export function monitorUptime(id: number, sinceMs: number, now = new Date()): number | null {
const r = observeDb()
.prepare("SELECT count(*) AS n, sum(ok) AS good FROM monitor_checks WHERE monitor_id = ? AND at >= ?")
.get(id, new Date(now.getTime() - sinceMs).toISOString()) as Row;
const n = Number(r.n);
return n ? Number(r.good ?? 0) / n : null;
}
export interface MonitorView extends Monitor {
uptime24h: number | null;
uptime7d: number | null;
/** The last checks, oldest first. */
recent: Array<{ at: string; ok: boolean; degraded: boolean }>;
}
export function monitorView(m: Monitor, now = new Date()): MonitorView {
const recent = (observeDb().prepare("SELECT at, ok, degraded FROM monitor_checks WHERE monitor_id = ? ORDER BY at DESC, id DESC LIMIT 30").all(m.id) as Row[])
.map((r) => ({ at: String(r.at), ok: Number(r.ok) === 1, degraded: Number(r.degraded) === 1 }))
.reverse();
return { ...m, uptime24h: monitorUptime(m.id, 86_400_000, now), uptime7d: monitorUptime(m.id, 7 * 86_400_000, now), recent };
}
export const listMonitorViews = (now = new Date()) => listMonitors().map((m) => monitorView(m, now));
/** One line about where the monitor looks. */
export function describeTarget(m: Pick<Monitor, "kind" | "target" | "token">, webUrl = ""): string {
const t = m.target as Record<string, unknown>;
switch (m.kind) {
case "http":
return String(t.url);
case "tcp":
return `${t.host}:${t.port}`;
case "dns":
return String(t.host);
case "internet":
return (t.hosts as string[]).join(", ");
case "heartbeat":
return `${webUrl}/api/observe/hb/${m.token}`;
}
}
// ── checks and states ──────────────────────────────────────────────────────────────
export interface Transition {
from: MonitorState;
to: MonitorState;
incident: MonitorIncident | null;
/** The closed incident (recovery). */
ended: MonitorIncident | null;
}
/** Records one check and moves the state machine; returns the change, if any. */
export function recordCheck(m: Monitor, r: CheckResult, o: { now?: Date; quiet?: boolean } = {}): Transition | null {
const now = o.now ?? new Date();
const iso = now.toISOString();
const db = observeDb();
const good = r.ok && !r.degraded;
db.prepare("INSERT INTO monitor_checks (monitor_id, at, ok, degraded, latency_ms, detail) VALUES (?, ?, ?, ?, ?, ?)").run(
m.id,
iso,
r.ok ? 1 : 0,
r.degraded ? 1 : 0,
r.latencyMs ?? null,
JSON.stringify({ ...r.detail, reason: r.reason }),
);
const streakOk = good ? m.streakOk + 1 : 0;
const streakBad = good ? 0 : m.streakBad + 1;
const target: MonitorState = good ? "up" : r.ok ? "degraded" : "down";
let to = m.state;
if (target === "up" && m.state !== "up" && (m.state === "unknown" || streakOk >= m.recoverThreshold)) to = "up";
if (target !== "up" && m.state !== target && streakBad >= m.failThreshold) to = target;
let transition: Transition | null = null;
let incidentId = m.incidentId;
if (to !== m.state) {
let incident: MonitorIncident | null = null;
let ended: MonitorIncident | null = null;
if (to === "up") {
if (incidentId) {
db.prepare("UPDATE monitor_incidents SET ended_at = ? WHERE id = ?").run(iso, incidentId);
ended = toIncident(db.prepare("SELECT * FROM monitor_incidents WHERE id = ?").get(incidentId) as Row);
}
incidentId = null;
} else if (incidentId) {
// down ↔ degraded: the same incident, a new state.
db.prepare("UPDATE monitor_incidents SET state = ?, reason = ? WHERE id = ?").run(to, r.reason, incidentId);
incident = toIncident(db.prepare("SELECT * FROM monitor_incidents WHERE id = ?").get(incidentId) as Row);
} else {
incident = toIncident(
db.prepare("INSERT INTO monitor_incidents (monitor_id, state, reason, started_at, quiet) VALUES (?, ?, ?, ?, ?) RETURNING *").get(m.id, to, r.reason, iso, o.quiet ? 1 : 0) as Row,
);
incidentId = incident.id;
}
transition = { from: m.state, to, incident, ended };
}
db.prepare(`UPDATE monitors SET state = ?, state_since = ?, streak_ok = ?, streak_bad = ?, last_check_at = ?, last_detail = ?, incident_id = ? WHERE id = ?`).run(
to,
to !== m.state ? iso : m.stateSince,
streakOk,
streakBad,
iso,
JSON.stringify({ ...r.detail, reason: r.reason, latencyMs: r.latencyMs ?? null }),
incidentId,
m.id,
);
return transition;
}
/** Text of the message about a change (null — nothing to say: the first «works», a quiet incident). */
export function transitionText(m: Pick<Monitor, "name">, t: Transition, now = new Date()): string | null {
if (t.to === "up") {
if (!t.ended || t.ended.quiet) return null;
const n = Math.max(1, Math.round((now.getTime() - Date.parse(t.ended.startedAt)) / 60_000));
return tr("✅ {name} снова работает — простой {n} мин.", { name: m.name, n });
}
if (t.incident?.quiet) return null;
return t.to === "down" ? tr("🔴 {name} не работает: {reason}", { name: m.name, reason: t.incident?.reason ?? "" }) : tr("🟡 {name} нестабилен: {reason}", { name: m.name, reason: t.incident?.reason ?? "" });
}
const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
async function announce(db: Db, m: Monitor, t: Transition, text: string, log: (s: string) => void): Promise<void> {
const inc = t.ended?.id ?? t.incident?.id ?? 0;
const key = `obs:${m.id}:${inc}:${t.to}`;
const channel = await getPlatformChannel(db);
if (await postToChannel(db, "services", `mon:ch:${key}`, esc(text), channel)) {
log(`observe: ${text}`);
return;
}
await alertAdmins(db, `mon:${key}`, text, log);
}
const inflight = new Set<number>();
const running: Promise<void>[] = [];
export interface ObserveTickOptions {
now?: Date;
probes?: ObserveProbes;
log?: (s: string) => void;
/** At most this many checks at once (default PEPPA_OBSERVE_CONCURRENCY or 16). */
concurrency?: number;
}
/** Is the internet down right now (an internet monitor not on pause is down)? */
function internetDown(): boolean {
return listMonitors().some((m) => m.kind === "internet" && !m.paused && (m.state === "down" || (m.streakBad > 0 && m.state !== "degraded")));
}
async function checkOne(db: Db, m: Monitor, o: ObserveTickOptions): Promise<void> {
const log = o.log ?? (() => {});
const r = await runCheck(m, o.probes ?? realObserveProbes, o.now ?? new Date()).catch((e: Error): CheckResult => ({ ok: false, degraded: false, reason: e.message, detail: {} }));
const fresh = getMonitor(m.id);
if (!fresh || fresh.paused) return; // deleted or paused while checking
const quiet = m.kind !== "internet" && !r.ok && internetDown();
const t = recordCheck(fresh, r, { now: o.now, quiet });
if (!t) return;
const text = transitionText(fresh, t, o.now);
if (text) await announce(db, fresh, t, text, log).catch((e: Error) => log(`observe: announce failed: ${e.message}`));
}
/**
* Starts the checks that are due (not on pause, interval passed, not already running). Resolves
* when the started checks are done; the service does not wait for it, tests do.
*/
export async function observeTick(db: Db, o: ObserveTickOptions = {}): Promise<number> {
const now = (o.now ?? new Date()).getTime();
const limit = o.concurrency ?? (Number(process.env.PEPPA_OBSERVE_CONCURRENCY) || 16);
const due = listMonitors().filter((m) => !m.paused && !inflight.has(m.id) && (!m.lastCheckAt || Date.parse(m.lastCheckAt) + m.intervalSec * 1000 <= now));
// The internet first: whether others are quiet depends on it.
due.sort((a, b) => Number(b.kind === "internet") - Number(a.kind === "internet"));
const started: Promise<void>[] = [];
for (const m of due) {
if (inflight.size >= limit) break;
inflight.add(m.id);
const p = checkOne(db, m, o).finally(() => inflight.delete(m.id));
started.push(p);
running.push(p);
}
await Promise.all(started);
return started.length;
}
/** Tests: wait for every check started so far. */
export async function observeSettled(): Promise<void> {
while (running.length) await Promise.all(running.splice(0));
}
/** Deletes checks and closed incidents older than the retention (default 7 days). */
export function pruneObserve(now = new Date(), days = retentionDays()): number {
const cut = new Date(now.getTime() - days * 86_400_000).toISOString();
const db = observeDb();
const r = db.prepare("DELETE FROM monitor_checks WHERE at < ?").run(cut);
db.prepare("DELETE FROM monitor_incidents WHERE ended_at IS NOT NULL AND ended_at < ?").run(cut);
return Number(r.changes);
}
// ── built-in monitors ──────────────────────────────────────────────────────────────
export const DEFAULT_INTERNET_HOSTS = ["api.telegram.org", "chatgpt.com", "api.anthropic.com", "registry.npmjs.org", "git.telecom.quest"];
/** On the first start: «eGov relay» (HTTP and DNS for sign.aitu.uz) and «Интернет». Never again. */
export function seedMonitors(now = new Date()): Monitor[] {
const db = observeDb();
if (db.prepare("SELECT 1 FROM observe_meta WHERE key = 'seeded'").get()) return [];
const made = [
createMonitor({ name: "Интернет", kind: "internet", target: { hosts: DEFAULT_INTERNET_HOSTS }, intervalSec: 60 }, "system", now),
createMonitor({ name: "eGov relay", kind: "http", target: { url: "https://sign.aitu.uz/" }, intervalSec: 60 }, "system", now),
createMonitor({ name: "eGov relay — DNS", kind: "dns", target: { host: "sign.aitu.uz" }, intervalSec: 300 }, "system", now),
];
db.prepare("INSERT INTO observe_meta (key, value) VALUES ('seeded', ?)").run(now.toISOString());
return made;
}