peppa/packages/testkit/test/lost-deploy.test.ts
peppa-bot e48c82664e
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 52с
peppa/build build: success за 36с
peppa/bundle bundle: success за 1с
peppa/test test: success за 1716с
peppa-ci / ci (pull_request) Successful in 30m43s
PEP-338: потерянное обновление рабочей версии закрывается и повторяется один раз
Запись prod deploying без отчёта дольше 30 минут блокировала «Показать всем» и режим «сам»
навсегда. lostDeployTick закрывает её, повторяет ту же версию один раз; потеря после повтора —
суперадмину.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-04 13:50:43 +05:00

111 lines
6.1 KiB
TypeScript

// PEP-338, spec delivery-pipeline: an update of the working version whose job the pipeline lost
// (no report ever came) does not block «Показать всем» and «сам» forever — it is closed, started
// once more, and a second loss goes to the superadmin, not to the owner.
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, describe, test } from "node:test";
import { releases, telegramOutbox } from "@peppa/db";
import { and, asc, eq } from "drizzle-orm";
import { core, db, runner, superadmin, teardown } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-lost-")), "gitea"));
const BOT = { id: 83, login: "peppa-bot", token: "mock-token-bot" };
let heard: () => Promise<string[]>;
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
gitea.addUser(BOT);
heard = await superadmin();
});
after(async () => {
await gitea.stop();
await teardown();
});
let n = 0;
async function proj() {
n++;
const slug = `mock-lost-${n}`;
const p = await core.createProject(db, { slug, key: `LD${String.fromCharCode(64 + n)}`, name: `Витрина ${n}`, giteaOwner: BOT.login, giteaRepo: slug, workspacePath: `/tmp/${slug}` });
gitea.addRepo(BOT.login, slug, { files: { "README.md": "# shop\n" } });
return p;
}
type P = Awaited<ReturnType<typeof proj>>;
const head = (p: P) => gitea.sha(p.giteaOwner, p.giteaRepo, "main");
const prods = (p: P) => db.select().from(releases).where(and(eq(releases.projectId, p.id), eq(releases.env, "prod"))).orderBy(asc(releases.id));
const prodTags = (p: P) => gitea.repo(p.giteaOwner, p.giteaRepo).tags.filter((t) => t.name.startsWith("deploy-prod-"));
const later = (min: number) => new Date(Date.now() + min * 60_000);
const outbox = async () => (await db.select().from(telegramOutbox)).length;
describe("PEP-338: потерянное обновление рабочей версии", () => {
test("Режим «сам»: задание потерялось — запись закрыта, обновление запущено ещё раз, людям ничего", async () => {
const p = await proj();
await core.setPublishMode(db, p.id, "auto");
await runner.recordRelease(db, p, { env: "staging", sha: head(p), status: "healthy", host: "lost-staging.mock.test", commits: [] });
assert.equal((await prods(p))[0]?.status, "deploying");
assert.equal(prodTags(p).length, 1);
const before = await outbox();
assert.deepEqual(await runner.lostDeployTick(db, { now: later(10) }), [], "ten minutes is not lost yet");
assert.equal((await prods(p))[0]?.status, "deploying");
assert.deepEqual(await runner.lostDeployTick(db, { now: later(31) }), [p.key]);
const rows = await prods(p);
assert.equal(rows.length, 2);
assert.equal(rows[0]!.status, "failed");
assert.match(rows[0]!.reason ?? "", /потерялось/);
assert.equal(rows[1]!.status, "deploying", "the same version is on its way again");
assert.equal(rows[1]!.sha, head(p));
assert.equal(prodTags(p).length, 2, "a new tag for the pipeline");
assert.equal(await outbox(), before, "nobody is written to about the first loss");
assert.equal((await heard()).filter((t) => t.includes(p.key)).length, 0);
// The repeated job reports: the row turns healthy and nothing is swept later.
await runner.recordRelease(db, p, { env: "prod", sha: head(p), status: "healthy", host: "lost-prod.mock.test" });
assert.deepEqual(await runner.lostDeployTick(db, { now: later(200) }), []);
assert.equal((await prods(p)).at(-1)!.status, "healthy");
assert.equal(prodTags(p).length, 2);
});
test("Потерялось и после повтора — одно сообщение суперадмину, третьего запуска нет", async () => {
const p = await proj();
await core.setPublishMode(db, p.id, "auto");
await runner.recordRelease(db, p, { env: "staging", sha: head(p), status: "healthy", host: "lost-staging.mock.test", commits: [] });
await runner.lostDeployTick(db, { now: later(31) });
assert.equal(prodTags(p).length, 2);
assert.deepEqual(await runner.lostDeployTick(db, { now: later(62) }), []);
const rows = await prods(p);
assert.deepEqual(rows.map((r) => r.status), ["failed", "failed"]);
assert.equal(prodTags(p).length, 2, "no third start");
const msgs = (await heard()).filter((t) => t.includes(p.key));
assert.equal(msgs.length, 1);
assert.match(msgs[0]!, /не дошло до конца/);
await runner.lostDeployTick(db, { now: later(120) });
await runner.productLinkTick(db, { now: later(120) });
assert.equal(prodTags(p).length, 2, "«сам» does not start the same version in a loop");
assert.equal((await heard()).filter((t) => t.includes(p.key)).length, 1, "once");
});
test("«Показать всем» по кнопке: после потери кнопка снова работает, повтор — от того же человека", async () => {
const p = await proj();
await core.setPublishMode(db, p.id, "button");
await runner.recordRelease(db, p, { env: "staging", sha: head(p), status: "healthy", host: "lost-staging.mock.test", commits: [] });
await runner.deployProd(db, p, "mock-owner");
assert.deepEqual(await runner.lostDeployTick(db, { now: later(31) }), [p.key]);
const rows = await prods(p);
assert.deepEqual(rows.map((r) => [r.status, r.deployedBy]), [["failed", "mock-owner"], ["deploying", "mock-owner"]]);
// Lost again: the row is closed, and a new press starts a new update instead of «already running».
await runner.lostDeployTick(db, { now: later(62) });
const again = await runner.deployProd(db, p, "mock-owner");
assert.equal(again.status, "deploying");
assert.ok(!rows.some((r) => r.id === again.id), "a new update, not the lost one");
assert.equal(prodTags(p).length, 3);
});
});