162 lines
9.7 KiB
TypeScript
162 lines
9.7 KiB
TypeScript
// PEP-158, spec delivery-pipeline «Проверка здоровья и откат»: an update of the product that
|
||
// did not come up goes back to the agent of its story with the reason and the log; the owner
|
||
// gets nothing but the delay line, the superadmin hears at the limits.
|
||
import assert from "node:assert/strict";
|
||
import { after, before, describe, test } from "node:test";
|
||
import { core, db, project, runner, setDefaultOwner, teardown, type TestProject } from "./helpers.ts";
|
||
import { questions, telegramOutbox, users } from "@peppa/db";
|
||
import { eq, sql } from "drizzle-orm";
|
||
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
const OWNER_CHAT = 9201;
|
||
const ADMIN_CHAT = 9202;
|
||
const REASON = "healthz не ответил за 2 минуты";
|
||
const LOG = "Error: listen EADDRINUSE: address already in use :::3000";
|
||
|
||
before(async () => {
|
||
const owner = await core.upsertUserFromGitea(db, { id: 9201, login: "mock-owner-deploy" }, { access_token: "x" });
|
||
const admin = await core.upsertUserFromGitea(db, { id: 9202, login: "mock-admin-deploy" }, { access_token: "x" });
|
||
await db.update(users).set({ telegramChatId: OWNER_CHAT, telegramUserId: OWNER_CHAT }).where(eq(users.id, owner.id));
|
||
await db.update(users).set({ telegramChatId: ADMIN_CHAT, telegramUserId: ADMIN_CHAT }).where(eq(users.id, admin.id));
|
||
await core.setPlatformAdmins(db, ["mock-admin-deploy"]);
|
||
setDefaultOwner(owner.id);
|
||
});
|
||
after(teardown);
|
||
|
||
const sentTo = async (chat: number) => (await db.select().from(telegramOutbox).where(eq(sql`json_extract(${telegramOutbox.params}, '$.chat_id')`, chat))).map((r) => String(r.params.text));
|
||
/** What the owner was asked or told about the failed version (the agent's own turn ends are not it). */
|
||
const ownerHeard = async (projectId: number) => {
|
||
const about = (t: string) => /healthz|EADDRINUSE|не прошло проверку|не обновил/.test(t);
|
||
const qs = (await db.select().from(questions).where(eq(questions.projectId, projectId))).filter((q) => about(q.text));
|
||
return qs.length + (await sentTo(OWNER_CHAT)).filter(about).length;
|
||
};
|
||
const adminHeard = async (key: string) => (await sentTo(ADMIN_CHAT)).filter((t) => t.includes(key));
|
||
|
||
async function story(turns: Parameters<typeof project>[0]["turns"], status: "in_progress" | "done" | "backlog" = "in_progress") {
|
||
const tp = await project({ turns });
|
||
await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status });
|
||
const proj = await core.getProject(db, tp.key);
|
||
const rel = (sha: string, status: "rolled_back" | "healthy" | "failed", o: { env?: "staging" | "prod"; tasks?: boolean } = {}) =>
|
||
runner.recordRelease(db, proj, {
|
||
env: o.env ?? "staging",
|
||
sha,
|
||
previousSha: "a1b2c3d4",
|
||
image: null,
|
||
host: `${proj.slug}-staging.test`,
|
||
prNumber: null,
|
||
status,
|
||
reason: status === "healthy" ? null : REASON,
|
||
runUrl: null,
|
||
commits: o.tasks === false ? [] : [`Merge pull request 'x' from task/${tp.taskKey} into main`],
|
||
logTail: status === "healthy" ? null : `step 1\n${LOG}`,
|
||
});
|
||
const id = (await tp.task()).id;
|
||
return { tp, proj, rel, id, scope: { projectId: proj.id, taskId: id } };
|
||
}
|
||
const stopAll = async (_tp: TestProject, projectId: number) => {
|
||
for (const s of await core.listSessions(db, { active: true, projectId })) await runner.stopSession(db, s.id);
|
||
};
|
||
const said = (tp: TestProject, text: string) => tp.log().some((e) => JSON.stringify(e).includes(text));
|
||
|
||
describe("Проверка здоровья и откат", () => {
|
||
test("Неудачный релиз: работающий агент получает причину и лог, владелец и суперадмин — ничего", async () => {
|
||
const s = await story([[{ say: "Работаю." }], [{ say: "Чиню." }], [{ say: "Чиню." }]]);
|
||
await s.tp.start();
|
||
await s.tp.waitLog("turn 0", (e) => e.ev === "prompt");
|
||
await s.rel("d4e5f6a7", "rolled_back");
|
||
await s.tp.waitLog("the agent got the reason", (e) => JSON.stringify(e).includes(REASON));
|
||
assert.ok(said(s.tp, "EADDRINUSE"), "the log tail is in the message");
|
||
assert.equal((await s.tp.task()).status, "in_progress");
|
||
assert.equal(await core.taskDelayed(db, s.id), true, "the story shows the delay line");
|
||
assert.equal(await ownerHeard(s.proj.id), 0);
|
||
assert.equal((await adminHeard(s.proj.name)).length, 0, "the first failure is the agent's to fix");
|
||
assert.equal((await core.getPlatformDelay(db, s.scope, "deploy"))!.attempts, 1);
|
||
|
||
// The same version reported again is not another attempt.
|
||
await s.rel("d4e5f6a7", "rolled_back");
|
||
assert.equal((await core.getPlatformDelay(db, s.scope, "deploy"))!.attempts, 1);
|
||
await stopAll(s.tp, s.proj.id);
|
||
});
|
||
|
||
test("Следующая версия здорова: задержка снята, счётчик попыток начинается заново", async () => {
|
||
const s = await story([[{ say: "Работаю." }], [{ say: "Чиню." }], [{ say: "Чиню." }], [{ say: "Чиню." }]]);
|
||
await s.tp.start();
|
||
await s.tp.waitLog("turn 0", (e) => e.ev === "prompt");
|
||
await s.rel("11111111", "rolled_back");
|
||
await s.rel("22222222", "failed");
|
||
assert.equal((await core.getPlatformDelay(db, s.scope, "deploy"))!.attempts, 2);
|
||
await s.rel("33333333", "healthy", { env: "prod" });
|
||
assert.equal(await core.taskDelayed(db, s.id), true, "another environment does not lift it");
|
||
await s.rel("33333333", "healthy");
|
||
assert.equal(await core.taskDelayed(db, s.id), false);
|
||
await s.rel("44444444", "rolled_back");
|
||
assert.equal((await core.getPlatformDelay(db, s.scope, "deploy"))!.attempts, 1);
|
||
assert.equal(await ownerHeard(s.proj.id), 0);
|
||
await stopAll(s.tp, s.proj.id);
|
||
await core.clearPlatformDelay(db, s.scope);
|
||
});
|
||
|
||
test("Агента нет — принятая задача возвращается в работу с новым агентом", async () => {
|
||
const s = await story([[{ say: "Чиню." }]], "done");
|
||
const out = await s.rel("d4e5f6a7", "rolled_back");
|
||
assert.equal(out.status, "rolled_back");
|
||
await s.tp.waitLog("a new agent got the reason", (e) => JSON.stringify(e).includes(REASON));
|
||
assert.ok(said(s.tp, "EADDRINUSE"));
|
||
assert.ok(said(s.tp, "новой ветке"), "the result is merged: a new branch and a new result");
|
||
assert.equal((await s.tp.task()).status, "in_progress");
|
||
assert.equal(await core.taskDelayed(db, s.id), true);
|
||
assert.equal(await ownerHeard(s.proj.id), 0);
|
||
assert.equal((await adminHeard(s.proj.name)).length, 0);
|
||
// PEP-145: the system story is not filed while the agent of the story is on it.
|
||
assert.equal(await runner.ensureProductLinkTask(db, s.proj), null);
|
||
await stopAll(s.tp, s.proj.id);
|
||
});
|
||
|
||
test("Три и шесть неудачных релизов подряд: суперадмин — на пределах, агент остановлен", async () => {
|
||
const s = await story(Array.from({ length: 9 }, () => [{ say: "Чиню." }]));
|
||
await s.tp.start();
|
||
await s.tp.waitLog("turn 0", (e) => e.ev === "prompt");
|
||
const mine = () => adminHeard(s.tp.taskKey);
|
||
await s.rel("00000001", "rolled_back");
|
||
await s.rel("00000002", "rolled_back");
|
||
assert.equal((await mine()).length, 0);
|
||
await s.rel("00000003", "rolled_back");
|
||
assert.equal((await mine()).length, 1, "three in a row: the superadmin is told once");
|
||
assert.match((await mine())[0]!, /healthz не ответил/);
|
||
assert.match((await mine())[0]!, /Агент продолжает чинить/);
|
||
await s.rel("00000004", "rolled_back");
|
||
await s.rel("00000005", "rolled_back");
|
||
assert.equal((await mine()).length, 1, "retries are not news");
|
||
await s.rel("00000006", "rolled_back");
|
||
assert.equal((await mine()).length, 2);
|
||
assert.match((await mine())[1]!, /остановлен/);
|
||
assert.match((await mine())[1]!, /больше не пробует/);
|
||
// Six messages reach the busy agent one turn at a time (~4 s each with the mock): the sixth
|
||
// comes ~25 s in, so the default 25 s wait is a coin toss on a loaded CI runner.
|
||
await s.tp.waitLog("the agent is told to stop", (e) => JSON.stringify(e).includes("это предел"), 90_000);
|
||
assert.equal((await core.getPlatformDelay(db, s.scope, "deploy"))!.exhausted, true);
|
||
await s.rel("00000007", "rolled_back");
|
||
assert.equal((await mine()).length, 2, "after the limit nothing new");
|
||
assert.equal(await ownerHeard(s.proj.id), 0);
|
||
await s.rel("00000008", "healthy");
|
||
assert.equal(await core.taskDelayed(db, s.id), false);
|
||
await stopAll(s.tp, s.proj.id);
|
||
});
|
||
|
||
test("Вернуть некому: суперадмин получает одно сообщение сразу", async () => {
|
||
// No stories in the version; and a story the owner took off work is left alone.
|
||
for (const s of [await story([]), await story([], "backlog")]) {
|
||
await s.rel("d4e5f6a7", "rolled_back", { tasks: (await s.tp.task()).status === "backlog" });
|
||
const mine = (await sentTo(ADMIN_CHAT)).filter((t) => t.includes(s.proj.name) && t.includes("не прошло проверку"));
|
||
assert.equal(mine.length, 1);
|
||
assert.match(mine[0]!, /healthz не ответил/);
|
||
assert.equal(await core.taskDelayed(db, s.id), false);
|
||
assert.equal((await core.platformDelayOverview(db)).some((d) => d.projectId === s.proj.id && d.reason === "deploy" && d.taskId == null), true);
|
||
assert.equal(await ownerHeard(s.proj.id), 0);
|
||
assert.equal((await s.tp.task()).status === "backlog" || (await core.listSessions(db, { active: true, projectId: s.proj.id })).length === 0, true);
|
||
await s.rel("e5f6a7b8", "healthy");
|
||
assert.equal((await core.platformDelayOverview(db)).some((d) => d.projectId === s.proj.id && d.reason === "deploy"), false);
|
||
}
|
||
});
|
||
});
|