peppa/packages/core/src/observe.ts
peppa-bot acb6e3fb81
All checks were successful
peppa/lint lint: success за 1с
peppa/typecheck typecheck: success за 46с
peppa/build build: success за 34с
peppa/test test: success за 1325с
peppa-ci / ci (pull_request) Successful in 24m11s
PEP-224: статус функций из мониторинга (сведено с main после PEP-225)
Функция → мониторинги (core/feature-status.ts), серая кнопка входа через eGov и статус MCP,
отказ startEgovFlow, журнал и сообщения в канал. После переезда живых обновлений на
WebSocket (PEP-225): область `features` в LIVE_PLAIN_SCOPES, открыта без входа (SSE и
WebSocket с `anonymous: true` — только открытые области), смотрится по таймеру вместе с
`observe`, смена сбрасывает кэш статусов.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 15:00:03 +00:00

814 lines
37 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 { asIs, m as tr } from "@peppa/shared/i18n";
import { pushOutbox, telegramOutbox, type Db } from "@peppa/db";
import { and, eq, like, or } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
import { alertAdmins, observeRemindMin } from "./monitor.ts";
import { getPlatformChannel, postToChannel } from "./platform-channel.ts";
import { FEATURE_NAMES, isFeatureName, type FeatureName } from "./feature-names.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;
/** PEP-223: minutes between reminders about an ongoing outage; null — the common default, 0 — none. */
remindMin: number | null;
/** PEP-223: remind about «degraded» too (by default only «down»). */
remindDegraded: boolean;
/** PEP-224: features switched off while this monitor is down. */
features: FeatureName[];
}
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;
/** PEP-223: reminders sent about this incident. */
reminders: number;
/** PEP-223: time of the last message about it (the first one, a state change or a reminder). */
notifiedAt: string | null;
}
export interface MonitorInput {
name: string;
kind: MonitorKind;
target: MonitorTarget;
intervalSec?: number;
timeoutMs?: number;
failThreshold?: number;
recoverThreshold?: number;
/** PEP-223: null/undefined — the common default, 0 — no reminders. */
remindMin?: number | null;
remindDegraded?: boolean;
/** PEP-224: features to switch off while this monitor is down. */
features?: string[];
}
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;
export const MAX_REMIND_MIN = 1440;
// ── 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,
// PEP-223: reminders about an ongoing outage.
[
`ALTER TABLE monitors ADD COLUMN remind_min INTEGER`,
`ALTER TABLE monitors ADD COLUMN remind_degraded INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE monitor_incidents ADD COLUMN reminders INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE monitor_incidents ADD COLUMN notified_at TEXT`,
],
// PEP-224: monitor → features, per-feature threshold and the announced state, their journal.
[
`ALTER TABLE monitors ADD COLUMN features TEXT NOT NULL DEFAULT '[]'`,
`CREATE TABLE features (
name TEXT PRIMARY KEY,
disable_after_min INTEGER,
state TEXT,
since TEXT,
reason TEXT,
changed_at TEXT
)`,
`CREATE TABLE feature_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
state TEXT NOT NULL,
reason TEXT NOT NULL,
at TEXT NOT NULL
)`,
`CREATE INDEX feature_log_at ON feature_log (at)`,
`UPDATE monitors SET features = '["egov_login"]' WHERE name IN ('eGov relay', 'eGov relay — DNS') AND created_by = 'system'`,
],
];
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),
remindMin: r.remind_min == null ? null : Number(r.remind_min),
remindDegraded: Number(r.remind_degraded) === 1,
features: (json(r.features, []) as unknown[]).filter(isFeatureName),
};
}
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,
reminders: Number(r.reminders ?? 0),
notifiedAt: (r.notified_at as string | null) ?? null,
});
// ── 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") } : {};
}
}
/** PEP-224: known feature names, without repeats; an unknown one is refused. */
export function normalizeFeatures(v: unknown): FeatureName[] {
const list = (Array.isArray(v) ? v : String(v ?? "").split(/[\s,]+/)).map((x) => String(x).trim()).filter(Boolean);
for (const f of list) if (!isFeatureName(f)) bad("Неизвестная функция: {name}. Есть: {list}", { name: f, list: FEATURE_NAMES.join(", ") });
return [...new Set(list)] as FeatureName[];
}
function normalize(input: MonitorInput): Required<Omit<MonitorInput, "target" | "remindMin" | "features">> & { target: MonitorTarget; remindMin: number | null; features: FeatureName[] } {
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"),
remindMin: input.remindMin == null || String(input.remindMin) === "" ? null : int(input.remindMin, 0, MAX_REMIND_MIN, "remindMin"),
remindDegraded: !!input.remindDegraded,
features: normalizeFeatures(input.features ?? []),
};
}
// ── 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, remind_min, remind_degraded, token, created_by, created_at, updated_at, state_since, last_ping_at, features)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *`,
)
.get(n.name, n.kind, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, n.remindMin, n.remindDegraded ? 1 : 0, token, author, iso, iso, iso, n.kind === "heartbeat" ? iso : null, JSON.stringify(n.features)) 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,
// undefined — keep; null — back to the common default.
remindMin: patch.remindMin === undefined ? cur.remindMin : patch.remindMin,
remindDegraded: patch.remindDegraded ?? cur.remindDegraded,
features: patch.features ?? cur.features,
});
const r = observeDb()
.prepare(`UPDATE monitors SET name = ?, target = ?, interval_sec = ?, timeout_ms = ?, fail_threshold = ?, recover_threshold = ?, remind_min = ?, remind_degraded = ?, features = ?, updated_at = ?, last_check_at = NULL WHERE id = ? RETURNING *`)
.get(n.name, JSON.stringify(n.target), n.intervalSec, n.timeoutMs, n.failThreshold, n.recoverThreshold, n.remindMin, n.remindDegraded ? 1 : 0, JSON.stringify(n.features), 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 }>;
/** PEP-223: the open incident with its reminders (null — none or paused). */
outage: { startedAt: string; reminders: number; nextRemindAt: string | null; quiet: boolean } | null;
}
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();
const inc = m.incidentId && !m.paused ? openIncident(m.incidentId) : null;
const outage = inc ? { startedAt: inc.startedAt, reminders: inc.reminders, nextRemindAt: nextRemindAt(m, inc), quiet: inc.quiet } : null;
return { ...m, uptime24h: monitorUptime(m.id, 86_400_000, now), uptime7d: monitorUptime(m.id, 7 * 86_400_000, now), recent, outage };
}
export const listMonitorViews = (now = new Date()) => listMonitors().map((m) => monitorView(m, now));
function openIncident(id: number): MonitorIncident | null {
const r = observeDb().prepare("SELECT * FROM monitor_incidents WHERE id = ? AND ended_at IS NULL").get(id) as Row | undefined;
return r ? toIncident(r) : null;
}
/** PEP-223: the reminder period of a monitor in its current state, minutes (0 — no reminders). */
export function remindPeriodMin(m: Pick<Monitor, "state" | "remindMin" | "remindDegraded">): number {
if (m.state !== "down" && !(m.state === "degraded" && m.remindDegraded)) return 0;
return m.remindMin ?? observeRemindMin();
}
/** PEP-223: when the next reminder about an open incident is due; null — none will come. */
export function nextRemindAt(m: Pick<Monitor, "state" | "paused" | "remindMin" | "remindDegraded">, inc: Pick<MonitorIncident, "quiet" | "notifiedAt" | "startedAt" | "endedAt">): string | null {
const period = remindPeriodMin(m);
if (m.paused || inc.quiet || inc.endedAt || !period) return null;
return new Date(Date.parse(inc.notifiedAt ?? inc.startedAt) + period * 60_000).toISOString();
}
/** «45 мин», «1 ч», «1 ч 30 мин» (PEP-223). */
export function durationText(ms: number): string {
const total = Math.max(1, Math.round(ms / 60_000));
const h = Math.floor(total / 60);
const min = total % 60;
if (!h) return tr("{n} мин", { n: min });
return min ? tr("{h} ч {n} мин", { h, n: min }) : tr("{h} ч", { h });
}
/** 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 = ?, notified_at = ? WHERE id = ?").run(to, r.reason, iso, 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, notified_at) VALUES (?, ?, ?, ?, ?, ?) RETURNING *").get(m.id, to, r.reason, iso, o.quiet ? 1 : 0, iso) 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;
await send(db, `obs:${m.id}:${inc}:${t.to}`, text, log);
}
/** The platform channel «services», without it — the superadmins (PEP-202). */
async function send(db: Db, key: string, text: string, log: (s: string) => void): Promise<void> {
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 clock = (iso: string) => {
const d = new Date(iso);
try {
return d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
} catch {
return d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
}
};
/** PEP-223: text of a reminder about an ongoing outage. */
export function reminderText(m: Pick<Monitor, "name" | "state" | "lastCheckAt" | "lastDetail">, inc: Pick<MonitorIncident, "startedAt" | "reason">, now = new Date()): string {
const vars = {
name: m.name,
duration: durationText(now.getTime() - Date.parse(inc.startedAt)),
since: clock(inc.startedAt),
reason: asIs(String(m.lastDetail?.reason ?? inc.reason)),
time: clock(m.lastCheckAt ?? now.toISOString()),
};
return m.state === "down"
? tr("🔴 {name} не работает уже {duration} (с {since}): {reason}. Последняя проверка {time}.", vars)
: tr("🟡 {name} нестабилен уже {duration} (с {since}): {reason}. Последняя проверка {time}.", vars);
}
/**
* PEP-223: the night silence (PEP-208) holds new messages until the morning — an unsent reminder
* about the same incident is replaced by the new one, so the morning brings one, not a pile.
*/
async function dropUnsentReminders(db: Db, monitorId: number, incidentId: number): Promise<void> {
const base = `obs:${monitorId}:${incidentId}:r`;
await db.delete(telegramOutbox).where(and(eq(telegramOutbox.status, "pending"), or(like(telegramOutbox.dedupeKey, `mon:ch:${base}%`), like(telegramOutbox.dedupeKey, `mon:${base}%`))));
await db.delete(pushOutbox).where(and(eq(pushOutbox.status, "pending"), like(pushOutbox.dedupeKey, `mon:${base}%`)));
}
/**
* PEP-223: one reminder per due open incident (down, or degraded when the monitor asks for it),
* every `remind_min` after the last message. The claim is atomic on the incident's counter, so
* parallel ticks and a restarted service never send the same reminder twice. Quiet incidents and
* paused monitors stay silent. Returns the number of reminders sent.
*/
export async function remindIncidents(db: Db, o: { now?: Date; log?: (s: string) => void } = {}): Promise<number> {
const now = o.now ?? new Date();
const log = o.log ?? (() => {});
const odb = observeDb();
let sent = 0;
for (const m of listMonitors()) {
if (m.paused || !m.incidentId) continue;
const inc = openIncident(m.incidentId);
if (!inc) continue;
const due = nextRemindAt(m, inc);
if (!due || Date.parse(due) > now.getTime()) continue;
const claimed = odb
.prepare("UPDATE monitor_incidents SET reminders = reminders + 1, notified_at = ? WHERE id = ? AND reminders = ? AND ended_at IS NULL RETURNING reminders")
.get(now.toISOString(), inc.id, inc.reminders) as Row | undefined;
if (!claimed) continue;
const n = Number(claimed.reminders);
try {
await dropUnsentReminders(db, m.id, inc.id);
await send(db, `obs:${m.id}:${inc.id}:r${n}`, reminderText(m, inc, now), log);
sent++;
} catch (e) {
log(`observe: reminder failed: ${(e as Error).message}`);
}
}
return sent;
}
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 remindIncidents(db, { now: o.now, log: o.log }).catch((e: Error) => (o.log ?? (() => {}))(`observe: reminders failed: ${e.message}`));
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, features: ["egov_login"] }, "system", now),
createMonitor({ name: "eGov relay — DNS", kind: "dns", target: { host: "sign.aitu.uz" }, intervalSec: 300, features: ["egov_login"] }, "system", now),
];
db.prepare("INSERT INTO observe_meta (key, value) VALUES ('seeded', ?)").run(now.toISOString());
return made;
}
/**
* PEP-224: «MCP-сервер /mcp» and «MCP — вход OAuth» (they switch off `mcp`), once, when the web has
* a public address. Without a token /mcp answers 401 — that is the sign it is alive.
*/
export function seedFeatureMonitors(webUrl: string | undefined, now = new Date()): Monitor[] {
const db = observeDb();
if (db.prepare("SELECT 1 FROM observe_meta WHERE key = 'seeded:mcp'").get()) return [];
let base: URL;
try {
base = new URL(webUrl ?? "");
} catch {
return [];
}
if (/^(localhost|127\.|\[::1\])/.test(base.hostname)) return [];
const names = new Set(listMonitors().map((m) => m.name));
const made: Monitor[] = [];
if (!names.has("MCP-сервер /mcp")) made.push(createMonitor({ name: "MCP-сервер /mcp", kind: "http", target: { url: new URL("/mcp", base).toString(), expectStatus: [401] }, intervalSec: 60, features: ["mcp"] }, "system", now));
if (!names.has("MCP — вход OAuth"))
made.push(createMonitor({ name: "MCP — вход OAuth", kind: "http", target: { url: new URL("/.well-known/oauth-authorization-server", base).toString(), contains: "token_endpoint" }, intervalSec: 60, features: ["mcp"] }, "system", now));
db.prepare("INSERT INTO observe_meta (key, value) VALUES ('seeded:mcp', ?)").run(now.toISOString());
return made;
}