peppa/packages/testkit/test/deploy-lag.test.ts
peppa-bot 546027bb4e
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 34с
peppa/test test: success за 1471с
peppa-ci / ci (pull_request) Successful in 29m20s
PEP-277: сторож «прод отстаёт от main» — сообщение суперадминам
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:40:49 +00:00

122 lines
5.5 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-277: the production lags behind main — one message to the superadmins. Tests are named after
// the scenarios of openspec/changes/pep-277-deploy-lag-watch/specs/platform-release.
import assert from "node:assert/strict";
import { createServer, type Server } from "node:http";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, describe, test } from "node:test";
import { like } from "drizzle-orm";
import { telegramOutbox } from "@peppa/db";
import { stripAsIs } from "@peppa/shared/i18n";
import { core, db, runner, superadmin, teardown } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
const TMP = mkdtempSync(join(tmpdir(), "peppa-deploy-lag-"));
process.env.PEPPA_SECRET = "mock-secret-for-tests";
process.env.GITEA_PLATFORM_REPO = "peppa/peppa";
const gitea = new MockGitea(join(TMP, "gitea"));
const BOT = { id: 72, login: "peppa-bot", token: "mock-token-lag-bot" };
/** What the mock site answers on /api/health (null — 502). */
let siteCommit: string | null = null;
let site: Server;
let healthUrl = "";
const H = 3600_000;
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
gitea.addUser(BOT);
gitea.addRepo("peppa", "peppa", { admins: [BOT.login], files: { "README.md": "# FORGE\n" } });
site = createServer((_req, res) => {
if (!siteCommit) {
res.writeHead(502).end("bad gateway");
return;
}
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ ok: true, commit: siteCommit }));
});
await new Promise<void>((r) => site.listen(0, "127.0.0.1", r));
healthUrl = `http://127.0.0.1:${(site.address() as { port: number }).port}/api/health`;
await superadmin();
process.env.PEPPA_DEPLOY_LAG = "on";
});
after(async () => {
process.env.PEPPA_DEPLOY_LAG = "off";
site.close();
await gitea.stop();
await teardown();
});
const alerts = async () =>
(await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, "deploy-lag:%"))).map((r) => stripAsIs(String(r.params.text)));
const merge = (n: number, title: string) =>
gitea.commit("peppa", "peppa", "main", { [`f${n}.txt`]: String(n) }, `Merge pull request '${title}' (#${n}) from task/x into main`);
const tick = (at: number) => runner.deployLagTick(db, { now: new Date(at), force: true, healthUrl });
describe("Сторож отставания прода", () => {
test("Сценарий: Сайт не отвечает", async () => {
siteCommit = null;
merge(234, "PEP-240: старое");
assert.deepEqual(await tick(Date.now() + 5 * H), { state: "skipped" });
assert.deepEqual(await alerts(), []);
});
test("Сценарий: Отставание меньше 2 ч", async () => {
siteCommit = gitea.sha("peppa", "peppa", "main");
merge(235, "PEP-248: задание, которое исполнитель не берёт");
const r = await tick(Date.now() + 1 * H);
assert.equal(r.state, "fresh");
assert.deepEqual(await alerts(), []);
});
test("Сценарий: Остановленная выкатка", async () => {
const r = await tick(Date.now() + 2 * H + 10 * 60_000);
assert.equal(r.state, "lagging");
const a = await alerts();
assert.equal(a.length, 1, "одно сообщение суперадмину");
assert.match(a[0]!, /Прод отстаёт от main на 2 ч/);
assert.match(a[0]!, /PEP-248/);
assert.doesNotMatch(a[0]!, /PEP-240/, "выкаченное не в списке");
assert.equal(await core.getSetting(db, "platform.telegram_channel"), null, "в канал платформы ничего");
});
test("Сценарий: Повтор только при новом PR или через сутки", async () => {
const t0 = Date.now() + 2 * H + 25 * 60_000;
const r = await tick(t0);
assert.equal(r.state, "lagging");
assert.equal((r as { alerted: boolean }).alerted, false);
assert.equal((await alerts()).length, 1, "новых мержей нет — второго сообщения нет");
merge(236, "PEP-259: срок у разрешения");
// The newest merge is fresh, but the oldest undeployed one is over 2 h: a new PR → a new message.
await tick(t0 + 15 * 60_000);
const a = await alerts();
assert.equal(a.length, 2);
assert.match(a[1]!, /PEP-248, PEP-259/);
await tick(t0 + 30 * 60_000);
assert.equal((await alerts()).length, 2);
await tick(t0 + 15 * 60_000 + 24 * H);
assert.equal((await alerts()).length, 3, "раз в сутки — напоминание");
});
test("Сценарий: Прод догнал main", async () => {
siteCommit = gitea.sha("peppa", "peppa", "main");
const r = await tick(Date.now() + 30 * H);
assert.deepEqual(r, { state: "caught_up", alerted: true });
const a = await alerts();
assert.match(a.at(-1)!, /Выкатка догнала main/);
assert.equal((await tick(Date.now() + 31 * H)).state, "fresh");
assert.equal((await alerts()).length, a.length, "второго «догнала» нет");
});
test("Проверка не чаще раза в 15 минут", async () => {
const t = Date.now() + 40 * H;
await runner.deployLagTick(db, { now: new Date(t), healthUrl });
assert.deepEqual(await runner.deployLagTick(db, { now: new Date(t + 5 * 60_000), healthUrl }), { state: "skipped" });
assert.notDeepEqual(await runner.deployLagTick(db, { now: new Date(t + 15 * 60_000), healthUrl }), { state: "skipped" });
});
});