346 lines
19 KiB
TypeScript
346 lines
19 KiB
TypeScript
// PEP-202, spec observability: monitors of the platform — checks on a mock network, states after
|
||
// N bad/good checks in a row, one message per change (the platform channel or the superadmins),
|
||
// quiet while the internet is down, heartbeat, 7-day retention, built-in monitors, access via MCP.
|
||
import assert from "node:assert/strict";
|
||
import { after, describe, test } from "node:test";
|
||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||
import { events, telegramOutbox, users } from "@peppa/db";
|
||
import { and, eq, like } from "drizzle-orm";
|
||
import { stripAsIs } from "@peppa/shared/i18n";
|
||
import type { ObserveProbes } from "@peppa/core";
|
||
import { core, db, project, teardown } from "./helpers.ts";
|
||
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
process.env.PEPPA_WEB_URL = "http://peppa.test";
|
||
const { createAgentServer } = await import("@peppa/mcp/agent");
|
||
const { createManagerServer } = await import("@peppa/mcp/manager");
|
||
after(async () => {
|
||
core.closeObserveDb();
|
||
await teardown();
|
||
});
|
||
|
||
/** Mock network: per host the system / fallback addresses, which addresses answer, HTTP answers. */
|
||
function mockNet() {
|
||
const system = new Map<string, string[]>();
|
||
const fallback = new Map<string, string[]>();
|
||
const up = new Set<string>();
|
||
const http = new Map<string, { status: number; body: string } | "timeout">();
|
||
const probes: ObserveProbes = {
|
||
async http(url) {
|
||
const a = http.get(url) ?? { status: 200, body: "ok" };
|
||
if (a === "timeout") throw Object.assign(new Error("timeout"), { name: "TimeoutError" });
|
||
return a;
|
||
},
|
||
certDaysLeft: async () => 90,
|
||
systemLookup: async (h) => system.get(h) ?? [],
|
||
fallbackLookup: async (h) => fallback.get(h) ?? [],
|
||
reachable: async (ip) => up.has(ip),
|
||
};
|
||
return { system, fallback, up, http, probes };
|
||
}
|
||
|
||
const sent = async (prefix: string) =>
|
||
(await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, `${prefix}%`))).map((r) => ({ chat: r.params.chat_id, text: stripAsIs(String(r.params.text)) }));
|
||
|
||
let clock = Date.parse("2026-11-17T10:00:00Z");
|
||
const net = mockNet();
|
||
/** One pass of the service a minute later (every monitor here checks once a minute). */
|
||
async function pass(minutes = 1) {
|
||
clock += minutes * 60_000;
|
||
await core.observeTick(db, { probes: net.probes, now: new Date(clock) });
|
||
}
|
||
|
||
async function mcp(server: { connect: (t: never) => Promise<void> }) {
|
||
const [a, b] = InMemoryTransport.createLinkedPair();
|
||
await server.connect(a as never);
|
||
const client = new Client({ name: "mock", version: "0" });
|
||
await client.connect(b);
|
||
return async (name: string, args: Record<string, unknown> = {}) => {
|
||
const r = await client.callTool({ name, arguments: args });
|
||
return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError };
|
||
};
|
||
}
|
||
|
||
describe("Observability", () => {
|
||
test("Scenario: built-in monitors on the first start; a deleted one does not come back", () => {
|
||
const made = core.seedMonitors(new Date(clock));
|
||
assert.deepEqual(made.map((m) => m.name), ["Интернет", "eGov relay", "eGov relay — DNS"]);
|
||
for (const m of made) core.deleteMonitor(m.id);
|
||
assert.deepEqual(core.seedMonitors(new Date(clock)), [], "seeded once");
|
||
assert.equal(core.listMonitors().length, 0);
|
||
});
|
||
|
||
test("Scenario: validation — a bad address, a short interval, an unknown kind", () => {
|
||
assert.throws(() => core.createMonitor({ name: "x", kind: "http", target: { url: "ftp://a" } }, "system"), /http:\/\/ или https:\/\//);
|
||
assert.throws(() => core.createMonitor({ name: "x", kind: "tcp", target: { host: "a.example", port: 1 }, intervalSec: 5 }, "system"), /intervalSec/);
|
||
assert.throws(() => core.createMonitor({ name: "x", kind: "nope" as never, target: {} }, "system"), /Неизвестный вид/);
|
||
});
|
||
|
||
test("Scenario: down after 3 bad checks, up after 2 good — one message each, with the downtime; a single failure says nothing", async () => {
|
||
const chat = 880_101;
|
||
const u = await core.upsertUserFromGitea(db, { id: chat, login: "mock-obs-admin" }, { access_token: "x" });
|
||
await db.update(users).set({ telegramChatId: chat, telegramUserId: chat }).where(eq(users.id, u.id));
|
||
await core.setPlatformAdmins(db, ["mock-obs-admin"]);
|
||
|
||
const m = core.createMonitor({ name: "mock relay", kind: "http", target: { url: "https://mock-relay.example/" }, intervalSec: 60 }, "system", new Date(clock));
|
||
await pass();
|
||
assert.equal(core.getMonitor(m.id)!.state, "up", "the first good check: up without a message");
|
||
net.http.set("https://mock-relay.example/", "timeout");
|
||
await pass();
|
||
net.http.delete("https://mock-relay.example/");
|
||
await pass();
|
||
assert.equal(core.getMonitor(m.id)!.state, "up");
|
||
assert.equal((await sent("mon:obs:")).length, 0, "a single failure — no message");
|
||
|
||
net.http.set("https://mock-relay.example/", { status: 503, body: "" });
|
||
await pass();
|
||
await pass();
|
||
assert.equal((await sent("mon:obs:")).length, 0, "two bad checks are not enough");
|
||
await pass();
|
||
assert.equal(core.getMonitor(m.id)!.state, "down");
|
||
let msgs = await sent("mon:obs:");
|
||
assert.equal(msgs.length, 1);
|
||
assert.equal(msgs[0]!.chat, chat);
|
||
assert.match(msgs[0]!.text, /🔴 mock relay не работает: ответ 503/);
|
||
await pass();
|
||
assert.equal((await sent("mon:obs:")).length, 1, "still down — nothing new");
|
||
|
||
net.http.delete("https://mock-relay.example/");
|
||
await pass();
|
||
assert.equal(core.getMonitor(m.id)!.state, "down", "one good check is not enough");
|
||
await pass();
|
||
msgs = await sent("mon:obs:");
|
||
assert.equal(msgs.length, 2);
|
||
assert.match(msgs[1]!.text, /✅ mock relay снова работает — простой 3 мин/);
|
||
const inc = core.monitorIncidents(m.id);
|
||
assert.equal(inc.length, 1);
|
||
assert.ok(inc[0]!.endedAt);
|
||
const view = core.monitorView(core.getMonitor(m.id)!, new Date(clock));
|
||
assert.ok(view.uptime24h! > 0 && view.uptime24h! < 1);
|
||
assert.equal(view.recent.length, 9);
|
||
core.deleteMonitor(m.id);
|
||
});
|
||
|
||
test("Scenario: the system DNS gives unreachable addresses — «unstable» with both address sets", async () => {
|
||
net.system.set("mock-sign.example", ["10.0.0.1"]);
|
||
net.fallback.set("mock-sign.example", ["10.0.0.9"]);
|
||
net.up.add("10.0.0.9");
|
||
const m = core.createMonitor({ name: "mock sign DNS", kind: "dns", target: { host: "mock-sign.example" }, intervalSec: 60, failThreshold: 2 }, "system", new Date(clock));
|
||
await pass();
|
||
await pass();
|
||
const cur = core.getMonitor(m.id)!;
|
||
assert.equal(cur.state, "degraded");
|
||
const msgs = await sent("mon:obs:");
|
||
assert.match(msgs.at(-1)!.text, /🟡 mock sign DNS нестабилен: системный DNS отдаёт недоступные адреса 10\.0\.0\.1, рабочие — 10\.0\.0\.9/);
|
||
core.deleteMonitor(m.id);
|
||
});
|
||
|
||
test("Scenario: the channel is connected — messages go there; while the internet is down others stay quiet", async () => {
|
||
await core.setSetting(db, "platform.telegram_channel", { chatId: -100555, title: "mock", check: { ok: true, error: null, at: new Date().toISOString() }, events: { releases: true, services: true, digest: true }, digest: { time: "09:00", timezone: "UTC", users: false } });
|
||
for (const h of ["mock-a.example", "mock-b.example"]) net.system.set(h, [`10.1.0.${h.length}`]);
|
||
net.up.add("10.1.0.14");
|
||
const inet = core.createMonitor({ name: "mock internet", kind: "internet", target: { hosts: ["mock-a.example", "mock-b.example"] }, intervalSec: 60, failThreshold: 2 }, "system", new Date(clock));
|
||
const svc = core.createMonitor({ name: "mock service", kind: "tcp", target: { host: "10.1.0.14", port: 443 }, intervalSec: 60, failThreshold: 2 }, "system", new Date(clock));
|
||
await pass();
|
||
assert.equal(core.getMonitor(inet.id)!.state, "up");
|
||
assert.equal(core.getMonitor(svc.id)!.state, "up");
|
||
net.up.clear();
|
||
await pass();
|
||
await pass();
|
||
let msgs = await sent("mon:ch:obs:");
|
||
assert.equal(msgs.length, 1, "one message — about the internet");
|
||
assert.equal(msgs[0]!.chat, -100555);
|
||
assert.match(msgs[0]!.text, /mock internet не работает: не открывается ни один из адресов mock-a\.example, mock-b\.example/);
|
||
assert.equal(core.getMonitor(svc.id)!.state, "down", "the service is down too, quietly");
|
||
assert.ok(core.monitorIncidents(svc.id)[0]!.quiet);
|
||
net.up.add("10.1.0.14");
|
||
await pass();
|
||
await pass();
|
||
msgs = await sent("mon:ch:obs:");
|
||
assert.equal(msgs.length, 2, "only the internet's recovery");
|
||
assert.match(msgs[1]!.text, /mock internet снова работает — простой 2 мин/);
|
||
core.deleteMonitor(inet.id);
|
||
core.deleteMonitor(svc.id);
|
||
});
|
||
|
||
test("Scenario: heartbeat — silent longer than interval + grace = a failed check; a ping fixes it", async () => {
|
||
const m = core.createMonitor({ name: "mock cron", kind: "heartbeat", target: { graceSec: 60 }, intervalSec: 300, failThreshold: 1 }, "system", new Date(clock));
|
||
assert.ok(m.token);
|
||
assert.equal(core.pingHeartbeat("nope-nope-nope"), false);
|
||
clock += 7 * 60_000;
|
||
await core.observeTick(db, { probes: net.probes, now: new Date(clock) });
|
||
assert.equal(core.getMonitor(m.id)!.state, "down");
|
||
assert.equal(core.pingHeartbeat(m.token!, new Date(clock)), true);
|
||
clock += 5 * 60_000;
|
||
await core.observeTick(db, { probes: net.probes, now: new Date(clock) });
|
||
assert.equal(core.monitorChecks(m.id)[0]!.ok, true);
|
||
core.deleteMonitor(m.id);
|
||
});
|
||
|
||
test("Scenario: retention — checks older than 7 days are deleted, newer stay; a paused monitor is not checked", async () => {
|
||
const m = core.createMonitor({ name: "mock old", kind: "tcp", target: { host: "10.9.9.9", port: 80 }, intervalSec: 60 }, "system", new Date(clock));
|
||
await pass();
|
||
const old = new Date(clock);
|
||
clock += 8 * 86_400_000;
|
||
await pass();
|
||
assert.equal(core.monitorChecks(m.id).length, 2);
|
||
core.pruneObserve(new Date(clock));
|
||
const left = core.monitorChecks(m.id);
|
||
assert.equal(left.length, 1);
|
||
assert.ok(left[0]!.at > old.toISOString());
|
||
core.setMonitorPaused(m.id, true, new Date(clock));
|
||
await pass();
|
||
assert.equal(core.monitorChecks(m.id).length, 1, "paused — no check");
|
||
core.deleteMonitor(m.id);
|
||
});
|
||
|
||
test("Scenario: MCP — the platform's agent creates a monitor (journal with the author), another project's agent and a non-superadmin are refused", async () => {
|
||
const platform = await project({ turns: [[{ say: "ok" }]] });
|
||
const other = await project({ turns: [[{ say: "ok" }]] });
|
||
process.env.PEPPA_PLATFORM_KEY = platform.key;
|
||
try {
|
||
const own = await mcp(createAgentServer(db, { defaultKey: platform.key }));
|
||
const r = await own("create_monitor", { name: "mock from agent", kind: "http", target: { url: "https://mock-agent.example/" } });
|
||
assert.equal(r.isError, false, r.text);
|
||
assert.match(r.text, /Created #\d+ mock from agent/);
|
||
const proj = await core.getProject(db, platform.key);
|
||
const ev = await db.select().from(events).where(and(eq(events.projectId, proj.id), eq(events.type, "monitor_created")));
|
||
assert.equal(ev.length, 1);
|
||
assert.equal((ev[0]!.payload as { author: string }).author, "agent");
|
||
assert.match((await own("list_monitors")).text, /mock from agent/);
|
||
|
||
const foreign = await mcp(createAgentServer(db, { defaultKey: other.key }));
|
||
const no = await foreign("create_monitor", { name: "mock foreign", kind: "dns", target: { host: "a.example" } });
|
||
assert.equal(no.isError, true);
|
||
assert.match(no.text, /Access denied/);
|
||
assert.ok(!core.listMonitors().some((m) => m.name === "mock foreign"));
|
||
|
||
const pm = await core.upsertUserFromGitea(db, { id: 880_202, login: "mock-obs-pm" }, { access_token: "x" });
|
||
const remote = await mcp(createManagerServer(db, pm, "http://peppa.test"));
|
||
const refused = await remote("list_monitors");
|
||
assert.equal(refused.isError, true);
|
||
assert.match(refused.text, /superadmin only/);
|
||
const admin = await core.getUserByLogin(db, "mock-obs-admin");
|
||
if (admin) {
|
||
const ok = await mcp(createManagerServer(db, admin, "http://peppa.test"));
|
||
assert.match((await ok("list_monitors")).text, /mock from agent/);
|
||
}
|
||
} finally {
|
||
delete process.env.PEPPA_PLATFORM_KEY;
|
||
}
|
||
});
|
||
|
||
test("Scenario: the observer is a watched service only once it has reported", async () => {
|
||
let names = (await core.serviceStatus(db)).map((s) => s.service);
|
||
assert.ok(!names.includes("observer"), "not installed — not counted");
|
||
await core.beat(db, "observer");
|
||
names = (await core.serviceStatus(db)).map((s) => s.service);
|
||
assert.ok(names.includes("observer"));
|
||
});
|
||
|
||
// PEP-223: reminders while an outage lasts.
|
||
const reminders = async (id: number) =>
|
||
(await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, `mon:ch:obs:${id}:%:r%`))).map((r) => ({ key: r.dedupeKey, status: r.status, text: stripAsIs(String(r.params.text)) }));
|
||
/** The bot in daytime: everything queued goes out. */
|
||
const deliverAll = () => db.update(telegramOutbox).set({ status: "sent", sentAt: new Date(clock) }).where(eq(telegramOutbox.status, "pending"));
|
||
|
||
test("Scenario: a 95-minute outage — the first message and 3 reminders; recovery stops them; a restart does not repeat one", async () => {
|
||
process.env.PEPPA_TZ = "UTC";
|
||
const url = "https://mock-remind.example/";
|
||
const m = core.createMonitor({ name: "mock remind", kind: "http", target: { url }, intervalSec: 60, failThreshold: 1 }, "system", new Date(clock));
|
||
await pass();
|
||
net.http.set(url, { status: 502, body: "" });
|
||
await pass();
|
||
const startedAt = clock;
|
||
assert.equal(core.getMonitor(m.id)!.state, "down");
|
||
for (let i = 0; i < 95; i++) {
|
||
await pass();
|
||
await deliverAll();
|
||
}
|
||
const list = await reminders(m.id);
|
||
assert.deepEqual(list.map((r) => r.key.split(":").at(-1)), ["r1", "r2", "r3"]);
|
||
assert.match(list[0]!.text, /^🔴 mock remind не работает уже 30 мин \(с \d\d:\d\d\): ответ 502\. Последняя проверка \d\d:\d\d\.$/);
|
||
assert.match(list[1]!.text, /не работает уже 1 ч \(/);
|
||
assert.match(list[2]!.text, /не работает уже 1 ч 30 мин \(/);
|
||
const view = core.monitorView(core.getMonitor(m.id)!, new Date(clock));
|
||
assert.equal(view.outage!.reminders, 3);
|
||
assert.equal(view.outage!.nextRemindAt, new Date(startedAt + 120 * 60_000).toISOString(), "the next — 30 min after the third");
|
||
|
||
// A restarted service (a second tick at the same moment) does not send the same reminder again.
|
||
clock += 25 * 60_000;
|
||
const due = new Date(startedAt + 120 * 60_000);
|
||
assert.equal(await core.remindIncidents(db, { now: due }), 1);
|
||
assert.equal(await core.remindIncidents(db, { now: due }), 0);
|
||
assert.equal((await reminders(m.id)).length, 4);
|
||
|
||
net.http.delete(url);
|
||
await pass();
|
||
await deliverAll();
|
||
for (let i = 0; i < 40; i++) await pass();
|
||
assert.equal((await reminders(m.id)).length, 4, "up again — no reminders");
|
||
assert.match((await sent("mon:ch:obs:")).at(-1)!.text, /✅ mock remind снова работает/);
|
||
assert.equal(core.monitorIncidents(m.id)[0]!.reminders, 4);
|
||
core.deleteMonitor(m.id);
|
||
});
|
||
|
||
test("Scenario: at night the reminders do not pile up — one waits for the morning, with the start of the outage", async () => {
|
||
process.env.PEPPA_TZ = "UTC";
|
||
process.env.PEPPA_NIGHT_QUIET = "23:00-08:00";
|
||
try {
|
||
clock = Date.parse("2026-11-19T02:09:00Z");
|
||
const url = "https://mock-night.example/";
|
||
const m = core.createMonitor({ name: "mock night", kind: "http", target: { url }, intervalSec: 60, failThreshold: 1 }, "system", new Date(clock));
|
||
net.http.set(url, "timeout");
|
||
await pass(); // 02:10 — down
|
||
await deliverAll(); // the first message (the test bot sends it; the real one would hold it till 08:00 too)
|
||
while (clock < Date.parse("2026-11-19T07:59:00Z")) await pass(10);
|
||
const list = await reminders(m.id);
|
||
assert.equal(list.length, 1, "one unsent reminder instead of a pile");
|
||
assert.equal(list[0]!.status, "pending");
|
||
assert.match(list[0]!.text, /не работает уже 5 ч \d+ мин \(с 02:10\)/);
|
||
assert.ok(core.monitorIncidents(m.id)[0]!.reminders >= 10, "the counter keeps counting");
|
||
const night = await core.pendingMonitorMessages(db, new Date(Date.parse("2026-11-19T07:30:00Z")));
|
||
assert.ok(!night.some((r) => r.dedupeKey.startsWith(`mon:ch:obs:${m.id}:`)), "nothing goes out at night");
|
||
const morning = await core.pendingMonitorMessages(db, new Date(Date.parse("2026-11-19T08:01:00Z")));
|
||
assert.equal(morning.filter((r) => r.dedupeKey.startsWith(`mon:ch:obs:${m.id}:`) && /:r\d+$/.test(r.dedupeKey)).length, 1, "the morning brings one");
|
||
core.deleteMonitor(m.id);
|
||
} finally {
|
||
process.env.PEPPA_NIGHT_QUIET = "off";
|
||
}
|
||
});
|
||
|
||
test("Scenario: no reminders for a quiet outage, with remind_min = 0, for «degraded» by default and on pause", async () => {
|
||
const off = core.createMonitor({ name: "mock off", kind: "tcp", target: { host: "10.7.0.1", port: 80 }, intervalSec: 60, failThreshold: 1, remindMin: 0 }, "system", new Date(clock));
|
||
const paused = core.createMonitor({ name: "mock paused", kind: "tcp", target: { host: "10.7.0.2", port: 80 }, intervalSec: 60, failThreshold: 1 }, "system", new Date(clock));
|
||
net.system.set("mock-slow.example", ["10.7.0.9"]);
|
||
net.fallback.set("mock-slow.example", ["10.7.0.8"]);
|
||
net.up.add("10.7.0.8");
|
||
const slow = core.createMonitor({ name: "mock slow", kind: "dns", target: { host: "mock-slow.example" }, intervalSec: 60, failThreshold: 1 }, "system", new Date(clock));
|
||
await pass();
|
||
assert.equal(core.getMonitor(off.id)!.state, "down");
|
||
assert.equal(core.getMonitor(slow.id)!.state, "degraded");
|
||
core.setMonitorPaused(paused.id, true, new Date(clock));
|
||
for (let i = 0; i < 12; i++) {
|
||
await pass(10);
|
||
await deliverAll();
|
||
}
|
||
for (const m of [off, paused, slow]) assert.equal((await reminders(m.id)).length, 0, m.name);
|
||
assert.equal(core.monitorView(core.getMonitor(off.id)!).outage!.nextRemindAt, null);
|
||
// «degraded» reminds once the monitor asks for it.
|
||
core.updateMonitor(slow.id, { remindDegraded: true, remindMin: 30 });
|
||
await pass();
|
||
assert.match((await reminders(slow.id))[0]!.text, /^🟡 mock slow нестабилен уже 2 ч/);
|
||
for (const m of [off, paused, slow]) core.deleteMonitor(m.id);
|
||
net.up.delete("10.7.0.8");
|
||
});
|
||
|
||
test("Scenario: the platform services remind every 30 minutes too", async () => {
|
||
// The default period is the monitors' one.
|
||
assert.equal(core.observeRemindMin(), 30);
|
||
process.env.PEPPA_OBSERVE_REMIND_MIN = "0";
|
||
assert.equal(core.observeRemindMin(), 0);
|
||
delete process.env.PEPPA_OBSERVE_REMIND_MIN;
|
||
});
|
||
});
|