PEP-168: мониторинг проверяет порт веба, а не только heartbeat; авто-перезапуск

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-16 17:29:29 +05:00
parent 09f9381271
commit e4391c29cd
13 changed files with 278 additions and 10 deletions

25
docs/web-rebuild.md Normal file
View File

@ -0,0 +1,25 @@
# Пересборка веба под работающим сервером
**Правило:** не запускайте `next build` в `apps/web`, пока работает `next start` (launchd
`quest.telecom.peppa.web`). Порядок выкатки: `git pull` → миграции → сборка → `launchctl kickstart -k`
веба → `/api/health` с новым коммитом.
## Что случилось 16.11.2026 (PEP-168)
Процесс `next start` остался жив и продолжал писать heartbeat из `instrumentation.ts`, но порт 3100
перестал отвечать (ECONNREFUSED; в `~/.peppa/web.log` повторное «Ready»). Сборка стирает и
переписывает `apps/web/.next`, а работающий сервер держит пути и манифесты именно этого каталога;
после подмены он оказывается в неработоспособном состоянии. Точная внутренняя причина в Next не
разбиралась — правило выше проверено практикой. Помог `launchctl kickstart -k`.
## Что теперь следит за этим
- Вачдог и бот проверяют не только heartbeat веба, но и `GET http://127.0.0.1:3100/api/health`
(`PEPPA_WEB_PORT`, `PEPPA_WEB_PROBE_URL`; `PEPPA_WEB_PROBE=off` выключает). Порт не отвечает
`PEPPA_MONITOR_PORT_FAILS` (3) проверок подряд — алерт админам «веб не отвечает: процесс жив, но порт закрыт»
и запись в канал платформы; потом «снова на связи».
- `peppa status` спрашивает порт сразу и пишет «процесс жив, порт не отвечает».
- Вачдог сам делает `launchctl kickstart -k` после `PEPPA_WEB_RESTART_AFTER` (6) неудачных проверок подряд,
не больше `PEPPA_WEB_RESTART_MAX` (2) раз в час; `PEPPA_WEB_RESTART=off` выключает.
## Если нужно собрать без простоя
Собирайте в отдельный каталог (копия рабочей копии или worktree), затем переключите и перезапустите
веб одним `kickstart`. Скрипт `scripts/peppa-release.sh` для будущего прода уже работает так.

View File

@ -0,0 +1,5 @@
## Решения
- Проба — `probeWebPort` (core/monitor.ts), `fetch` с таймаутом 5 с; любой HTTP-ответ = порт жив. В тестах `PEPPA_WEB_PROBE=off`, монитор-тест передаёт свою пробу.
- Счётчик подряд идущих неудач — `settings` `monitor.port:web` `{fails, since, lastAt}`; порог `PEPPA_MONITOR_PORT_FAILS` (3). Бот и вачдог считают в один счётчик.
- Отказ порта оформляется как обычная недоступность сервиса: тот же `AlertState` (`monitor.alert:web`), идентификатор простоя — начало серии неудач, а не heartbeat (он меняется каждую минуту).
- Авто-перезапуск — `webRestartTick` вачдога: порог 6, не более 2 в час, `PEPPA_LAUNCHCTL_BIN` для тестов.

View File

@ -0,0 +1,8 @@
## Why
16.11.2026 веб отдавал 502: процесс жив и писал heartbeat, порт 3100 не слушался. Мониторинг показывал «веб ok», алерта не было.
## What Changes
- `checkServices` вачдога и бота проверяют веб HTTP-запросом к `/api/health`; несколько неудач подряд = «не отвечает».
- `peppa status` показывает «процесс жив, порт не отвечает».
- Вачдог перезапускает веб `launchctl kickstart -k` после устойчивого отказа (с пределом) и пишет в канал платформы.
- `docs/web-rebuild.md`: нельзя пересобирать под живым сервером.

View File

@ -0,0 +1,16 @@
## ADDED Requirements
### Requirement: Проверка порта веба
Мониторинг SHALL считать веб недоступным, если его heartbeat свежий, но порт не отвечает несколько проверок подряд.
#### Scenario: Порт закрыт при свежем heartbeat
- **GIVEN** веб пишет heartbeat каждую минуту
- **AND** порт веба не отвечает три проверки подряд
- **WHEN** вачдог выполняет проверку сервисов
- **THEN** админам уходит алерт «веб не отвечает: процесс жив, но порт закрыт»
- **AND** `peppa status` показывает «процесс жив, порт не отвечает»
#### Scenario: Одиночный сбой
- **GIVEN** порт веба не ответил один раз, затем ответил
- **WHEN** вачдог выполняет следующую проверку
- **THEN** алерта нет

View File

@ -0,0 +1,6 @@
## 1. Реализация
- [x] 1.1 Проба порта и счётчик в `checkServices`, состояние в `serviceStatus`
- [x] 1.2 `peppa status`
- [x] 1.3 Авто-перезапуск веба в вачдоге
- [x] 1.4 Тесты на моках, переводы
- [x] 1.5 docs/web-rebuild.md

View File

@ -0,0 +1,21 @@
# monitoring Specification
## Purpose
TBD - created by archiving change pep-168-web-port-monitor. Update Purpose after archive.
## Requirements
### Requirement: Проверка порта веба
Мониторинг SHALL считать веб недоступным, если его heartbeat свежий, но порт не отвечает несколько проверок подряд.
#### Scenario: Порт закрыт при свежем heartbeat
- **GIVEN** веб пишет heartbeat каждую минуту
- **AND** порт веба не отвечает три проверки подряд
- **WHEN** вачдог выполняет проверку сервисов
- **THEN** админам уходит алерт «веб не отвечает: процесс жив, но порт закрыт»
- **AND** `peppa status` показывает «процесс жив, порт не отвечает»
#### Scenario: Одиночный сбой
- **GIVEN** порт веба не ответил один раз, затем ответил
- **WHEN** вачдог выполняет следующую проверку
- **THEN** алерта нет

View File

@ -667,7 +667,7 @@ async function main(): Promise<void> {
break;
}
case "status": {
for (const s of await serviceStatus(db)) {
for (const s of await serviceStatus(db, { probe: true })) {
const hb = s.heartbeat;
const info = hb ? ` v${hb.version} pid ${hb.pid} ${hb.host}, с ${hb.startedAt.slice(0, 16).replace("T", " ")}` : "";
console.log(`${SERVICE_NAMES[s.service].padEnd(7)} ${describeState(s).padEnd(16)}${info}`);

View File

@ -36,6 +36,8 @@ export interface ServiceState {
/** 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 {
@ -45,6 +47,8 @@ interface AlertState {
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 {
@ -56,8 +60,41 @@ export interface MonitorOptions {
/** 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}`;
@ -107,14 +144,18 @@ export async function beat(db: Db, service: Service, o: { now?: Date; version?:
await setSetting(db, hbKey(service), hb);
}
export async function serviceStatus(db: Db, o: { now?: Date; staleMs?: number } = {}): Promise<ServiceState[]> {
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;
return { service, heartbeat, ageMs, ok: ageMs != null && ageMs <= stale };
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 } : {}) };
}),
);
}
@ -124,6 +165,8 @@ 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) });
}
@ -192,6 +235,15 @@ export async function checkServices(db: Db, o: MonitorOptions & { self: Service
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) {
@ -206,7 +258,7 @@ export async function checkServices(db: Db, o: MonitorOptions & { self: Service
}
// 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(Date.parse(s.heartbeat.at) - Date.parse(st.since));
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);
}
@ -214,10 +266,12 @@ export async function checkServices(db: Db, o: MonitorOptions & { self: Service
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 === s.heartbeat.at ? st : { since: s.heartbeat.at, alerted: false, reminders: 0, lastAlertAt: st?.lastAlertAt ?? null };
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(s.heartbeat.at) }), channel))) {
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);
@ -226,7 +280,10 @@ export async function checkServices(db: Db, o: MonitorOptions & { self: Service
const due = cur.alerted ? sinceLast >= remindMs : sinceLast >= cooldownMs;
if (due) {
const n = cur.alerted ? cur.reminders + 1 : 0;
const text = 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 });
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() });
}
@ -235,6 +292,23 @@ export async function checkServices(db: Db, o: MonitorOptions & { self: Service
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}`;

View File

@ -1,6 +1,9 @@
// Watchdog side of service monitoring (PEP-20): heartbeat, check the bot and the web, and
// deliver monitor alerts straight to the Bot API when the bot itself is the one that's down.
import { beat, checkServices, markOutboxRetry, markOutboxSent, pendingMonitorMessages, serviceStatus, type MonitorOptions } from "@peppa/core";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { beat, checkServices, getPlatformChannel, getSetting, portKey, postToChannel, setSetting, type PortState, markOutboxRetry, markOutboxSent, pendingMonitorMessages, serviceStatus, type MonitorOptions } from "@peppa/core";
import { m as tr } from "@peppa/shared/i18n";
import type { Db } from "@peppa/db";
export interface MonitorTickOptions extends MonitorOptions {
@ -12,10 +15,36 @@ export async function monitorTick(db: Db, o: MonitorTickOptions = {}): Promise<v
const log = o.log ?? (() => {});
await beat(db, "watchdog", { now: o.now });
await checkServices(db, { ...o, self: "watchdog" });
await webRestartTick(db, o).catch((e) => log(`monitor: web restart: ${(e as Error).message}`));
const bot = (await serviceStatus(db, { now: o.now, staleMs: o.staleMs })).find((s) => s.service === "bot");
if (bot?.heartbeat && !bot.ok) await deliverDirect(db, o.telegram ?? {}, log);
}
const run = promisify(execFile);
/**
* PEP-168: the web process is alive but its port stays closed for `PEPPA_WEB_RESTART_AFTER`
* (default 6) checks in a row → `launchctl kickstart -k`, at most `PEPPA_WEB_RESTART_MAX` (2)
* times per hour; the platform channel hears about it. `PEPPA_WEB_RESTART=off` disables.
*/
export async function webRestartTick(db: Db, o: MonitorTickOptions = {}): Promise<boolean> {
if (process.env.PEPPA_WEB_RESTART === "off") return false;
const port = await getSetting<PortState>(db, portKey("web"));
if (!port || port.fails < Number(process.env.PEPPA_WEB_RESTART_AFTER ?? 6)) return false;
const now = o.now ?? new Date();
const key = "monitor.web-restarts";
const recent = ((await getSetting<string[]>(db, key)) ?? []).filter((t) => now.getTime() - Date.parse(t) < 3600_000);
if (recent.length >= Number(process.env.PEPPA_WEB_RESTART_MAX ?? 2)) return false;
await setSetting(db, key, [...recent, now.toISOString()]);
// The streak starts over: the next verdict is about the restarted process.
await setSetting(db, portKey("web"), { fails: 0, since: port.since, lastAt: now.toISOString() } satisfies PortState);
const bin = process.env.PEPPA_LAUNCHCTL_BIN ?? "launchctl";
await run(bin, ["kickstart", "-k", `gui/${process.getuid?.() ?? 501}/quest.telecom.peppa.web`], { timeout: 30_000 });
o.log?.("monitor: веб не слушал порт — перезапущен (launchctl kickstart -k)");
await postToChannel(db, "services", `mon:ch:web:kick:${now.toISOString()}`, tr("🔄 Peppa FACTORY: веб не слушал порт — перезапускаю."), await getPlatformChannel(db));
return true;
}
/** Sends pending `mon:` outbox rows itself; marks them sent so the bot won't repeat them. */
async function deliverDirect(db: Db, tg: { token?: string; apiUrl?: string }, log: (m: string) => void) {
const token = tg.token ?? process.env.TELEGRAM_BOT_TOKEN;

View File

@ -219,6 +219,9 @@ export const bot: Dict = {
"«{name}» — {status} до {until}": "«{name}» — {status} until {until}",
"у проекта нет рабочей подписки: {why}": "the project has no working subscription: {why}",
"бот": "bot",
"процесс жив, порт не отвечает": "process alive, port not responding",
"⚠️ Peppa FACTORY: {name} не отвечает: процесс жив (pid {pid}, {host}), но порт закрыт уже {n} мин.": "⚠️ Peppa FACTORY: {name} not responding: the process is alive (pid {pid}, {host}) but the port has been closed for {n} min.",
"🔄 Peppa FACTORY: веб не слушал порт — перезапускаю.": "🔄 Peppa FACTORY: the web stopped listening on its port — restarting it.",
"молчит {n} мин": "silent for {n} min",
"Мониторинг Peppa FACTORY": "Peppa FACTORY monitoring",
"🔄 Peppa FACTORY: {name} перезапущен ({build}).": "🔄 Peppa FACTORY: {name} restarted ({build}).",

View File

@ -218,6 +218,9 @@ export const bot: Dict = {
"«{name}» — {status} до {until}": "«{name}» — {status}, мерзімі: {until}",
"у проекта нет рабочей подписки: {why}": "жобада жұмыс істейтін жазылым жоқ: {why}",
"бот": "бот",
"процесс жив, порт не отвечает": "процесс тірі, порт жауап бермейді",
"⚠️ Peppa FACTORY: {name} не отвечает: процесс жив (pid {pid}, {host}), но порт закрыт уже {n} мин.": "⚠️ Peppa FACTORY: {name} жауап бермейді: процесс тірі (pid {pid}, {host}), бірақ порт {n} мин жабық.",
"🔄 Peppa FACTORY: веб не слушал порт — перезапускаю.": "🔄 Peppa FACTORY: веб портты тыңдамай қалды — қайта іске қосып жатырмын.",
"молчит {n} мин": "үнсіз: {n} мин",
"Мониторинг Peppa FACTORY": "Peppa FACTORY мониторингі",
"🔄 Peppa FACTORY: {name} перезапущен ({build}).": "🔄 Peppa FACTORY: {name} қайта іске қосылды ({build}).",

View File

@ -31,6 +31,8 @@ Object.assign(process.env, {
// PEP-145: the watchdog files «Продукт должен открываться по ссылке» for any project with
// accepted stories and no deploy — every suite's projects. product-link.test.ts turns it on.
PEPPA_PRODUCT_LINK: "off",
// PEP-168: no real HTTP probe of the live site :3100 from tests; monitor tests pass their own probe.
PEPPA_WEB_PROBE: "off",
});
mkdirSync(process.env.PEPPA_HOME!, { recursive: true });

View File

@ -2,7 +2,7 @@
// (controlled clock, mock-telegram, the real bot), `peppa status`.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdtempSync } from "node:fs";
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@ -55,7 +55,7 @@ before(async () => {
await core.setAllowedLogins(db, [ADMIN.login, OTHER.login]);
});
beforeEach(async () => {
db.run(sql`delete from settings where key like 'heartbeat:%' or key like 'monitor.alert:%' or key = 'platform.admins'`);
db.run(sql`delete from settings where key like 'heartbeat:%' or key like 'monitor.alert:%' or key like 'monitor.port:%' or key = 'platform.admins'`);
await db.delete(telegramOutbox);
await core.setPlatformAdmins(db, [ADMIN.login]);
await pair(ADMIN.login, ADMIN.chatId, 9001);
@ -117,6 +117,82 @@ describe("Health-эндпоинт", () => {
});
});
describe("PEP-168: веб жив по heartbeat, но порт закрыт", () => {
let open = false;
const probe = async () => open;
const checkPort = (m: number) => core.checkServices(db, { self: "watchdog", now: at(m), log, probe });
test("Порт закрыт несколько проверок подряд — алерт, в status «порт не отвечает», потом «снова на связи»", async () => {
open = false;
for (const m of [0, 1]) {
await beatAt("web", m);
await checkPort(m);
}
assert.deepEqual(await queued(ADMIN.chatId), [], "две проверки — ещё не отказ");
await beatAt("web", 2);
await checkPort(2);
const msgs = await queued(ADMIN.chatId);
assert.equal(msgs.length, 1);
assert.match(msgs[0]!, /веб не отвечает: процесс жив .* порт закрыт/);
// heartbeat is fresh, yet the state says so
const s = (await core.serviceStatus(db, { now: at(2), probe })).find((x) => x.service === "web")!;
assert.equal(s.portDown, true);
assert.equal(core.describeState(s), "процесс жив, порт не отвечает");
// the same outage is not repeated by the next checks
await beatAt("web", 3);
await checkPort(3);
assert.equal((await queued(ADMIN.chatId)).length, 1);
// the port is back
open = true;
await beatAt("web", 4);
await checkPort(4);
const after = await queued(ADMIN.chatId);
assert.equal(after.length, 2);
assert.match(after[1]!, /веб снова на связи/);
});
test("Устойчивый отказ порта — вачдог перезапускает веб (с пределом)", async () => {
const bin = join(mkdtempSync(join(tmpdir(), "peppa-launchctl-")), "mock-launchctl");
const calls = join(mkdtempSync(join(tmpdir(), "peppa-launchctl-log-")), "calls.txt");
writeFileSync(bin, `#!/bin/sh\necho "$@" >> "${calls}"\n`, { mode: 0o755 });
process.env.PEPPA_LAUNCHCTL_BIN = bin;
process.env.PEPPA_WEB_RESTART_AFTER = "4";
process.env.PEPPA_WEB_RESTART_MAX = "1";
try {
open = false;
for (const m of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) {
await beatAt("web", m);
await checkPort(m);
await runner.webRestartTick(db, { now: at(m), log });
}
const lines = readFileSync(calls, "utf8").trim().split("\n");
assert.equal(lines.length, 1, "в час не больше одного перезапуска");
assert.match(lines[0]!, /^kickstart -k gui\/\d+\/quest\.telecom\.peppa\.web$/);
} finally {
delete process.env.PEPPA_LAUNCHCTL_BIN;
delete process.env.PEPPA_WEB_RESTART_AFTER;
delete process.env.PEPPA_WEB_RESTART_MAX;
}
});
test("Порт открыт — тишина; одиночный сбой не считается", async () => {
open = true;
await beatAt("web", 0);
await checkPort(0);
open = false;
await checkPort(1);
open = true;
await checkPort(2);
open = false;
await checkPort(3);
await checkPort(4);
assert.deepEqual(await queued(ADMIN.chatId), []);
open = true;
const s = (await core.serviceStatus(db, { now: at(5), probe })).find((x) => x.service === "web")!;
assert.equal(s.portDown, undefined);
});
});
describe("Алерт админу о молчащем сервисе", () => {
test("Бот молчит", async () => {
await beatAt("bot", 0);