peppa/packages/testkit/test/orphan-conflicts.test.ts

176 lines
11 KiB
TypeScript
Raw Permalink 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-301, spec platform-delays: a conflict nobody works on. The TPTIP-73 case — the checks queue
// held the request to rebase and nobody repeated it; stories in review with a conflict and no agent;
// a week-old question that switched the stuck healing off; week-old results go to the owner.
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, setDefaultOwner, teardown } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
import { events, questions, sessions, tasks } from "@peppa/db";
import { and, eq } from "drizzle-orm";
import { stripAsIs } from "@peppa/shared/i18n";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-orphan-")), "gitea"));
const BOT = { id: 74, login: "peppa-bot", token: "mock-token-bot" };
const CHECKS = { test: "pnpm test" };
const MIN = 60_000;
const DAY = 86_400_000;
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
process.env.PEPPA_STUCK_TASKS = "on";
process.env.PEPPA_ORPHAN_CONFLICTS = "on";
gitea.addUser(BOT);
const owner = await core.upsertUserFromGitea(db, { id: 9401, login: "mock-owner-orphan" }, { access_token: "x" });
setDefaultOwner(owner.id);
runner.setConflictFilesLister(async () => ["a.txt"]);
});
after(async () => {
delete process.env.PEPPA_STUCK_TASKS;
delete process.env.PEPPA_ORPHAN_CONFLICTS;
runner.setConflictFilesLister(null);
await gitea.stop();
await teardown();
});
/** A story with a green result in Gitea; its agent idle for 40 min (`agent: false` — no agent at all). */
async function story(o: { status: "in_progress" | "review"; conflict?: boolean; agent?: "idle" | "running" | false; resultAgeDays?: number }) {
const tp = await project({ turns: [] });
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 branch = `task/${tp.taskKey}`;
const sha = gitea.commit(proj.giteaOwner, proj.giteaRepo, branch, { "f.txt": "1" });
gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, "peppa/test", "success");
const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, branch);
let ref = await core.resolveTask(db, tp.taskKey);
await core.updateTask(db, ref, { status: o.status, prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` });
if (o.resultAgeDays) await db.update(tasks).set({ updatedAt: new Date(Date.now() - o.resultAgeDays * DAY) }).where(eq(tasks.id, ref.task.id));
ref = await core.resolveTask(db, tp.taskKey);
let sid: number | null = null;
if (o.agent !== false) {
const s = await core.createSession(db, { projectId: proj.id, taskId: ref.task.id });
await db.update(sessions).set({ status: o.agent ?? "idle", lastActivityAt: new Date(Date.now() - 40 * MIN) }).where(eq(sessions.id, s.id));
sid = s.id;
}
const pull = () => gitea.repo(proj.giteaOwner, proj.giteaRepo).pulls[pr.number - 1]!;
if (o.conflict !== false) pull().mergeable = false;
const requests = async () => (await db.select().from(events).where(and(eq(events.taskId, ref.task.id), eq(events.type, "conflict_rebase_requested")))).length;
return { tp, proj, ref, sha, pr, pull, sid, requests };
}
const ownerQuestions = async (projectId: number) => (await db.select().from(questions).where(eq(questions.projectId, projectId))).filter((q) => q.taskId == null);
describe("Конфликтом, которым никто не занимается, занимается FORGE", () => {
test("Scenario: Очередь проверок подавила просьбу — после её конца просьба отправлена (TPTIP-73)", async () => {
const t = await story({ status: "in_progress" });
// The checks queue of the project stands.
await core.setSetting(db, "checks.queue", { since: Date.now(), projects: [t.proj.id] });
// Green checks: the agent is woken, the conflict seen — the request is held.
await runner.wakeOnGreen(db, t.ref, { sha: t.sha, prNumber: t.pr.number, branch: `task/${t.tp.taskKey}` }, core.giteaForBot());
assert.equal(await t.requests(), 0, "the queue holds the request");
assert.ok(await runner.getConflictHeld(db, t.ref.task.id), "the held request is remembered");
const T = Date.now();
await runner.conflictStepTick(db, { now: new Date(T + 5 * MIN) });
assert.equal(await t.requests(), 0, "still the queue");
// The queue is over: the next minute sends the request — once.
await core.deleteSetting(db, "checks.queue");
await runner.conflictStepTick(db, { now: new Date(T + 6 * MIN) });
assert.equal(await t.requests(), 1, "the request went once the queue was over");
assert.equal(await runner.getConflictHeld(db, t.ref.task.id), null);
await runner.conflictStepTick(db, { now: new Date(T + 7 * MIN) });
assert.equal(await t.requests(), 1, "only one request");
});
test("Scenario: Конфликт ушёл, пока просьба ждала", async () => {
const t = await story({ status: "in_progress" });
await core.setSetting(db, "checks.queue", { since: Date.now(), projects: [t.proj.id] });
const pull = await core.giteaForBot().getPullRequest(t.proj.giteaOwner, t.proj.giteaRepo, t.pr.number);
assert.equal(await runner.conflictStep(db, t.ref, pull), "held");
t.pull().mergeable = true;
await core.deleteSetting(db, "checks.queue");
await runner.conflictStepTick(db, {});
assert.equal(await t.requests(), 0);
assert.equal(await runner.getConflictHeld(db, t.ref.task.id), null, "the mark goes");
});
test("Scenario: Задача в «Ревью» с конфликтом и без агента получает шаг конфликта на сверке", async () => {
const t = await story({ status: "review", resultAgeDays: 2, agent: false });
const T = Date.now();
const r = await runner.orphanConflictTick(db, { now: new Date(T), force: true });
assert.ok(r.stepped.includes(t.tp.taskKey), "the sweep took the story");
assert.equal(await t.requests(), 1, "one request to the agent");
assert.ok(await runner.getConflictStep(db, t.ref.task.id), "the conflict step started");
assert.equal((await t.tp.task()).status, "in_progress");
// The step goes on: the sweep does not ask again.
await runner.orphanConflictTick(db, { now: new Date(T + 2 * 3600_000) });
assert.equal(await t.requests(), 1);
});
test("Scenario: Агент уже работает — сверка не трогает", async () => {
const t = await story({ status: "in_progress", agent: "running" });
const r = await runner.orphanConflictTick(db, { force: true });
assert.ok(!r.stepped.includes(t.tp.taskKey));
assert.equal(await runner.getConflictStep(db, t.ref.task.id), null);
});
test("Сверка — раз в час", async () => {
const T = Date.now();
await runner.orphanConflictTick(db, { now: new Date(T), force: true });
const t = await story({ status: "review", resultAgeDays: 1 });
const r = await runner.orphanConflictTick(db, { now: new Date(T + 30 * MIN) });
assert.equal(r.stepped.length, 0, "not yet an hour");
assert.ok((await runner.orphanConflictTick(db, { now: new Date(T + 61 * MIN) })).stepped.includes(t.tp.taskKey));
});
test("Scenario: Вопросу владельцу неделя — сторож застрявших задач чинит задачу", async () => {
const t = await story({ status: "in_progress", conflict: false });
await db.insert(questions).values({ projectId: t.proj.id, taskId: t.ref.task.id, kind: "question", text: "Какой цвет кнопки?", options: ["синий", "зелёный"], msgType: "question", createdAt: new Date(Date.now() - 7 * DAY) });
await runner.stuckTaskTick(db, { now: new Date() });
assert.equal((await t.tp.task()).status, "review", "healed despite the old question");
});
test("Scenario: Вопрос задан час назад — задача ждёт ответа", async () => {
const t = await story({ status: "in_progress", conflict: false });
await db.insert(questions).values({ projectId: t.proj.id, taskId: t.ref.task.id, kind: "question", text: "Какой цвет кнопки?", options: ["синий", "зелёный"], msgType: "question", createdAt: new Date(Date.now() - 60 * MIN) });
await runner.stuckTaskTick(db, { now: new Date() });
assert.equal((await t.tp.task()).status, "in_progress");
});
test("Scenario: Старый результат в «Ревью» — владелец выбирает «Закрыть»", async () => {
const t = await story({ status: "review", resultAgeDays: 9 });
const r = await runner.orphanConflictTick(db, { force: true });
assert.ok(r.stale.includes(t.tp.taskKey));
assert.equal(await t.requests(), 0, "no agent for a week-old result");
const qs = await ownerQuestions(t.proj.id);
assert.equal(qs.length, 1, "one message per project");
assert.ok(stripAsIs(qs[0]!.text).includes(t.tp.taskKey), "the story is listed");
assert.deepEqual(qs[0]!.options, [stripAsIs(runner.STALE_UPDATE_OPTION), stripAsIs(runner.STALE_CLOSE_OPTION)]);
// While it is open — nothing more.
await runner.orphanConflictTick(db, { force: true });
assert.equal((await ownerQuestions(t.proj.id)).length, 1);
await runner.answerAndDeliver(db, qs[0]!.id, runner.STALE_CLOSE_OPTION, "web");
assert.ok((await t.tp.task()).archivedAt, "the story went to the archive");
assert.equal(t.pull().state, "closed", "the result is closed");
await runner.orphanConflictTick(db, { force: true });
assert.equal((await ownerQuestions(t.proj.id)).length, 1, "not asked again");
});
test("Scenario: Старый результат в «Ревью» — владелец выбирает «Обновить и показать»", async () => {
const t = await story({ status: "review", resultAgeDays: 9 });
await runner.orphanConflictTick(db, { force: true });
const [q] = await ownerQuestions(t.proj.id);
assert.ok(q);
await runner.answerAndDeliver(db, q.id, runner.STALE_UPDATE_OPTION, "web");
assert.equal(await t.requests(), 1, "the agent is asked to update");
assert.equal((await t.tp.task()).status, "in_progress");
});
});