// 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>; 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>["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(1); await core.setProjectPause(db, proj.id, { since: Date.now(), by: owner.id, sessions: [] }); runner.startAcceptAll(db, refs, owner.id); await runner.acceptQueueTick(db, { wait: true }); assert.equal(await status(refs[0]!.key), "review", "a project on pause merges nothing"); assert.equal((await core.queuedAccepts(db, proj.id)).length, 1, "the decision waits"); await core.clearProjectPause(db, proj.id); await runner.acceptQueueTick(db, { wait: true }); assert.equal(await status(refs[0]!.key), "done"); }); });