peppa/packages/testkit/test/accept-queue.test.ts
peppa-bot bcee434ed9
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 49с
peppa/build build: success за 35с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1637с
peppa-ci / ci (pull_request) Successful in 29m38s
PEP-318: недоступная служба запуска — не отказ; на паузе решение выполняется
Замечания координатора: RunnerUnavailableError оставляет задачу в очереди без причины,
веб отпускает аренду, вачдог доводит; проверка паузы убрана из processAcceptQueue
(отложенное по PEP-127 по-прежнему ждёт «Продолжить»). Тесты и спека.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 11:02:48 +00:00

203 lines
11 KiB
TypeScript

// PEP-318, spec product-acceptance «Принять всё»: the decision is queued and answered at once;
// the stories are accepted in the background one by one — on a slow Gitea, after a restart in the
// middle, on a second press, and not while the project is on pause.
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, waitFor } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
import { events } from "@peppa/db";
import { and, eq, inArray } 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-accept-queue-")), "gitea"));
const BOT = { id: 74, login: "peppa-bot", token: "mock-token-bot" };
let owner: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
gitea.addUser(BOT);
owner = await core.upsertUserFromGitea(db, { id: 9318, login: "mock-owner-accept-queue" }, { access_token: "x" });
setDefaultOwner(owner.id);
});
after(async () => {
gitea.delayMs = 0;
await gitea.stop();
await teardown();
});
/** A project with `n` stories in review, each with an open PR; `red` — indexes with red checks. */
async function inReview(n: number, red: 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: { test: "pnpm test" } });
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 refs = [];
for (let i = 0; i < n; i++) {
const ref = i === 0 ? await core.resolveTask(db, tp.taskKey) : await core.createTask(db, { projectId: proj.id, title: `Подпись кнопки ${i}` });
const branch = `task/${ref.key}`;
const sha = gitea.commit(proj.giteaOwner, proj.giteaRepo, branch, { [`f${i}.txt`]: String(i) });
const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, branch);
gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, "peppa/test", red.includes(i) ? "failure" : "success");
await core.updateTask(db, ref, { status: "review", prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` });
refs.push(await core.resolveTask(db, ref.key));
}
return { tp, proj, refs };
}
const status = async (key: string) => (await core.resolveTask(db, key)).task.status;
/**
* Stories accepted while behind the main branch are carried to the merge by FORGE (PEP-127):
* the checks of each new head go green and the watchdog's pass merges them, as live.
*/
async function drain(proj: Awaited<ReturnType<typeof inReview>>["proj"], keys: string[]) {
await waitFor(
"every story «Готово»",
async () => {
const left = [];
for (const k of keys) if ((await status(k)) !== "done") left.push(k);
if (!left.length) return true;
for (const k of left) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, gitea.sha(proj.giteaOwner, proj.giteaRepo, `task/${k}`), "peppa/test", "success");
await runner.pendingAcceptTick(db);
return null;
},
60_000,
);
}
describe("«Принять всё» в фоне", () => {
test("Scenario: Шесть задач при медленном сервере кода", async () => {
const { proj, refs } = await inReview(6);
gitea.delayMs = 150;
try {
const t0 = Date.now();
// What the page's action does: queue, answer, carry on after the answer.
const { run, added } = runner.startAcceptAll(db, refs, owner.id, "web");
const work = runner.processAcceptQueue(db, proj.id);
const answered = Date.now() - t0;
assert.ok(answered < 1000, `the action answers at once (${answered} ms)`);
assert.equal(added, 6);
assert.equal(run.keys.length, 6);
const screen = await core.acceptScreen(db, proj);
assert.ok(screen.run && !screen.run.finishedAt, "the page shows the progress");
assert.match(stripAsIs(core.acceptRunLine(screen.run!)), /Принимаем по очереди: принято \d из 6/);
assert.equal(await work, 6, "all six in the background, one by one");
assert.ok(Date.now() - t0 > answered * 3, "the work took far longer than the answer");
const done = await core.acceptRun(db, proj.id);
assert.ok(done?.finishedAt, "the run is finished");
assert.equal(done!.accepted.length + done!.pending.length, 6);
assert.equal(done!.failed.length, 0);
assert.match(stripAsIs(core.acceptRunLine(done!)), /^Принято \d+/);
} finally {
gitea.delayMs = 0;
}
await drain(proj, refs.map((r) => r.key));
assert.equal((await core.queuedAccepts(db, proj.id)).length, 0);
});
test("Scenario: Одна не принялась — причина видна", async () => {
const { proj, refs } = await inReview(2, [1]);
runner.startAcceptAll(db, refs, owner.id);
await runner.processAcceptQueue(db, proj.id);
assert.equal(await status(refs[0]!.key), "done");
assert.equal(await status(refs[1]!.key), "review");
const run = (await core.acceptRun(db, proj.id))!;
assert.deepEqual(run.failed.map((f) => f.key), [refs[1]!.key]);
assert.match(stripAsIs(run.failed[0]!.reason), /проверки не пройдены/);
const item = (await core.acceptScreen(db, proj)).groups.flatMap((g) => g.items).find((i) => i.key === refs[1]!.key)!;
assert.match(stripAsIs(item.failed!), /проверки не пройдены/, "the page shows why it stayed");
assert.equal(item.queued, false);
assert.match(stripAsIs(core.acceptRunLine(run)), /Принято 1, на доработке 1/);
});
test("Scenario: Перезапуск посреди приёмки", async () => {
const { proj, refs } = await inReview(3);
runner.startAcceptAll(db, refs, owner.id);
// A worker took the project and stopped (the web restarted) right after merging the first story.
await runner.mergeTaskPr(refs[0]!);
await core.setSetting(db, `accept.worker:${proj.id}`, { owner: "mock-dead-worker", at: Date.now() });
await runner.acceptQueueTick(db, { wait: true });
assert.equal((await core.queuedAccepts(db, proj.id)).length, 3, "a live lease: nobody else touches the project");
await core.setSetting(db, `accept.worker:${proj.id}`, { owner: "mock-dead-worker", at: Date.now() - core.ACCEPT_LEASE_MS - 1000 });
await runner.acceptQueueTick(db, { wait: true });
assert.equal((await core.queuedAccepts(db, proj.id)).length, 0, "the watchdog carried the queue on");
assert.equal(await status(refs[0]!.key), "done", "the merged one closes without a second merge");
const run = (await core.acceptRun(db, proj.id))!;
assert.equal(run.failed.length, 0);
await drain(proj, refs.map((r) => r.key));
const failed = await db.select().from(events).where(and(inArray(events.taskId, refs.map((r) => r.task.id)), eq(events.type, "accept_failed")));
assert.equal(failed.length, 0);
});
test("Scenario: Двойное нажатие", async () => {
const { proj, refs } = await inReview(2);
const first = runner.startAcceptAll(db, refs, owner.id);
const second = runner.startAcceptAll(db, refs, owner.id);
assert.equal(first.added, 2);
assert.equal(second.added, 0, "the same stories are not queued again");
assert.equal((await core.queuedAccepts(db, proj.id)).length, 2);
assert.equal((await core.acceptRun(db, proj.id))!.keys.length, 2);
assert.ok((await core.acceptScreen(db, proj)).groups.flatMap((g) => g.items).every((i) => i.queued), "the page shows them as being accepted");
// Two workers at once (the web and the watchdog): each story once.
const [a, b] = await Promise.all([runner.processAcceptQueue(db, proj.id), runner.processAcceptQueue(db, proj.id)]);
assert.equal(a + b, 2);
const run = (await core.acceptRun(db, proj.id))!;
assert.equal(run.accepted.length + run.pending.length, 2);
assert.equal(run.failed.length, 0, "nothing refused as «not in review» by a second worker");
await drain(proj, refs.map((r) => r.key));
assert.equal((await core.queuedAccepts(db, proj.id)).length, 0);
});
test("Scenario: Проект на паузе", async () => {
const { proj, refs } = await inReview(2);
await core.setProjectPause(db, proj.id, { since: Date.now(), by: owner.id, sessions: [] });
try {
runner.startAcceptAll(db, refs, owner.id);
await runner.acceptQueueTick(db, { wait: true });
assert.equal((await core.queuedAccepts(db, proj.id)).length, 0, "a person's decision is carried out on pause too");
assert.equal(await status(refs[0]!.key), "done", "accepted like the single «Принять»");
// The second is behind the main branch after the first merge: FORGE carries it (PEP-127) — that waits.
const second = (await core.resolveTask(db, refs[1]!.key)).task;
assert.ok(await core.getPendingAccept(db, second.id), "the deferred accept is remembered");
gitea.setStatus(proj.giteaOwner, proj.giteaRepo, gitea.sha(proj.giteaOwner, proj.giteaRepo, `task/${refs[1]!.key}`), "peppa/test", "success");
await runner.pendingAcceptTick(db);
assert.equal(await status(refs[1]!.key), "review", "the deferred accept waits for «Продолжить»");
} finally {
await core.clearProjectPause(db, proj.id);
}
await drain(proj, [refs[1]!.key]);
});
test("Scenario: Служба запуска недоступна, пока очередь ведёт веб", async () => {
const { proj, refs } = await inReview(2);
runner.startAcceptAll(db, refs, owner.id);
// The web is a client of the runner service; the service is restarting (no socket).
runner.setRunnerClient(true, db);
try {
assert.equal(await runner.processAcceptQueue(db, proj.id), 0, "the web stops");
} finally {
runner.setRunnerClient(false);
}
assert.equal((await core.queuedAccepts(db, proj.id)).length, 2, "the decision stays queued");
const run = (await core.acceptRun(db, proj.id))!;
assert.equal(run.failed.length, 0, "not a refusal");
assert.ok(!run.finishedAt);
for (const r of refs) assert.equal(await core.acceptFailure(db, r.task.id), null, "no reason on the page");
assert.equal(await core.getSetting(db, `accept.worker:${proj.id}`), null, "the lease is let go");
// The watchdog accepts in place.
await runner.acceptQueueTick(db, { wait: true });
assert.equal((await core.queuedAccepts(db, proj.id)).length, 0);
assert.equal(await status(refs[0]!.key), "done");
await drain(proj, refs.map((r) => r.key));
assert.equal((await core.acceptRun(db, proj.id))!.failed.length, 0);
});
});