peppa/packages/testkit/test/rollout.test.ts

122 lines
6.9 KiB
TypeScript

// PEP-278, spec delivery-pipeline «"Готово" — когда изменения работают»: an accepted story is
// «Принято, ждёт обновления» until its merge commit runs (platform: the live web's commit;
// a project: a healthy staging/prod version). Mock Gitea, no agents.
import assert from "node:assert/strict";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, describe, test } from "node:test";
import { core, db, project, runner, teardown } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
import { chatMessages, events, releases } from "@peppa/db";
import { stripAsIs } from "@peppa/shared/i18n";
import { and, eq } from "drizzle-orm";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-rollout-")), "gitea"));
const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" };
const CHECKS = { test: "pnpm test" };
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
gitea.addUser(BOT);
});
after(async () => {
delete process.env.PEPPA_PLATFORM_KEY;
await gitea.stop();
await teardown();
});
/** A story in review with a green PR in mock Gitea; `platform` — the project is the platform's. */
async function storyInReview(o: { platform?: boolean } = {}) {
const tp = await project({ turns: [] });
if (o.platform) process.env.PEPPA_PLATFORM_KEY = tp.key;
const proj = await core.getProject(db, tp.key);
const pj = JSON.stringify({ slug: proj.slug, key: tp.key, name: tp.key, peppaUrl: "http://test", checks: CHECKS });
writeFileSync(join(tp.dir, ".peppa/project.json"), pj);
gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj } });
gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write";
const head = gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { "f.txt": "1" }, `${tp.taskKey}: change`);
gitea.setStatus(proj.giteaOwner, proj.giteaRepo, head, "peppa/test", "success");
const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`);
const prUrl = `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}`;
const ref = () => core.resolveTask(db, tp.taskKey);
await core.updateTask(db, await ref(), { status: "review", prUrl });
const oldMain = gitea.sha(proj.giteaOwner, proj.giteaRepo, "main");
const repoPath = gitea.repo(proj.giteaOwner, proj.giteaRepo).path;
const waiting = async () => (await core.awaitingRollout(db)).has((await ref()).task.id);
const taskEvents = async (type: string) => db.select().from(events).where(and(eq(events.taskId, (await ref()).task.id), eq(events.type, type)));
const thread = async () => {
await core.syncChats(db);
const rows = await db.select().from(chatMessages).where(eq(chatMessages.threadKey, `task:${(await ref()).task.id}`));
return rows.map((r) => stripAsIs(r.text));
};
const release = (env: "staging" | "prod", status: "healthy" | "rolled_back", tasks: string[], sha = "f".repeat(40)) =>
db.insert(releases).values({ projectId: proj.id, env, sha, tasks, status });
return { tp, proj, ref, oldMain, repoPath, waiting, taskEvents, thread, release, main: () => gitea.sha(proj.giteaOwner, proj.giteaRepo, "main") };
}
const liveWeb = (commit: string) => core.setSetting(db, "heartbeat:web", { at: new Date().toISOString(), commit });
describe("«Готово» только когда изменения работают", () => {
test("Платформа: принята, но не выкачена", async () => {
const s = await storyInReview({ platform: true });
await liveWeb(s.oldMain);
await runner.acceptStory(db, await s.ref());
assert.equal((await s.ref()).task.status, "done", "the status machine is unchanged");
assert.equal(await s.waiting(), true);
await runner.rolloutTick(db, { root: s.repoPath });
assert.equal(await s.waiting(), true, "the live web runs a commit without the merge");
assert.ok((await s.thread()).some((t) => t.includes("Задача принята — изменения заработают после обновления версии")));
// Платформа: выкачена — the web restarts on the merge commit.
await liveWeb(s.main());
await runner.rolloutTick(db, { root: s.repoPath });
assert.equal(await s.waiting(), false);
assert.equal((await s.taskEvents("task_rolled_out")).length, 1);
await runner.rolloutTick(db, { root: s.repoPath });
assert.equal((await s.taskEvents("task_rolled_out")).length, 1, "said once");
assert.equal((await s.thread()).filter((t) => t.includes("Изменения задачи уже работают — задача готова")).length, 1);
delete process.env.PEPPA_PLATFORM_KEY;
});
test("Проект: здоровая версия для проверки; сломанная версия не считается", async () => {
const s = await storyInReview();
await s.release("staging", "healthy", []);
await runner.acceptStory(db, await s.ref());
assert.equal(await s.waiting(), true);
await s.release("staging", "rolled_back", [s.tp.taskKey]);
await runner.rolloutTick(db);
assert.equal(await s.waiting(), true, "a rolled back version does not count");
await s.release("staging", "healthy", [s.tp.taskKey]);
await runner.rolloutTick(db);
assert.equal(await s.waiting(), false);
assert.equal((await s.taskEvents("task_rolled_out"))[0]?.payload && ((await s.taskEvents("task_rolled_out"))[0]!.payload as { env: string }).env, "staging");
});
test("Проект без выкладки — сразу «Готово»", async () => {
const s = await storyInReview();
await runner.acceptStory(db, await s.ref());
assert.equal((await s.ref()).task.status, "done");
assert.equal(await s.waiting(), false);
assert.ok((await s.thread()).some((t) => t.includes("Задача принята и закрыта")));
});
test("Задача ушла из «Готово» — ожидание снято", async () => {
const s = await storyInReview();
await s.release("prod", "healthy", []);
await runner.acceptStory(db, await s.ref());
assert.equal(await s.waiting(), true);
await core.updateTask(db, await s.ref(), { status: "in_progress" });
assert.equal(await s.waiting(), false);
});
test("Карточка «Продакта» говорит, что изменения скоро заработают", () => {
const v = core.storyProductView({ status: "done", rollout: true, agentWorking: false, openQuestions: 0 });
assert.equal(v.now, core.STORY_PRODUCT_TEXT.rollout.now);
assert.equal(core.storyProductView({ status: "done", agentWorking: false, openQuestions: 0 }).now, core.STORY_PRODUCT_TEXT.done.now);
});
});