// PEP-318: «Принять всё» in the background. The action queues the decision (core/accept-queue.ts) // and answers at once; `processAcceptQueue` accepts the project's stories one by one with the // usual `acceptStory` (gate, merge, «Готово» only after a real merge — PEP-296; deferred accept — // PEP-127). The web starts it right after the answer, the watchdog picks up what nobody carries // (a restart in the middle) — one worker per project by a lease. import { randomUUID } from "node:crypto"; import { PeppaError, finishAccept, queueAccepts, queuedAccepts, releaseAcceptLease, runAsActor, setAcceptFailure, takeAcceptLease, type AcceptRun, type ActorChannel, type QueuedAccept, type TaskRef } from "@peppa/core"; import type { Db } from "@peppa/db"; import { m } from "@peppa/shared/i18n"; import { acceptStory } from "./flow.ts"; import { RunnerUnavailableError } from "./runner-client.ts"; import { resolveTaskById } from "./sessions.ts"; /** Projects this process is working on right now (one loop per project per process). */ const busy: Set = ((globalThis as { __peppaAcceptBusy?: Set }).__peppaAcceptBusy ??= new Set()); /** Queues «Принять всё» of one project; the caller starts `processAcceptQueue` without waiting. */ export function startAcceptAll(db: Db, refs: TaskRef[], by: number | null, via = "web"): { run: AcceptRun; added: number } { const projectId = refs[0]?.project.id; if (projectId == null) throw new PeppaError(m("Принимать нечего: задачи уже приняты или вернулись в работу")); if (refs.some((r) => r.project.id !== projectId)) throw new PeppaError(m("Принимать нечего: задачи уже приняты или вернулись в работу")); return queueAccepts(db, projectId, refs.map((r) => ({ taskId: r.task.id, key: r.key })), by, via); } const CHANNELS = new Set(["web", "telegram", "mcp", "cli"]); /** The runner service is not there (restart at a deploy, no pickup in 15 s): not a refusal — the queue row stays. */ const RETRY = Symbol("retry"); async function acceptOne(db: Db, q: QueuedAccept): Promise[2] | typeof RETRY> { const ref = await resolveTaskById(db, q.taskId).catch(() => null); if (!ref || ref.task.archivedAt) return { kind: "failed", reason: m("задача уже не на приёмке") }; // Merged and closed already: by the merge webhook or by a worker that stopped before writing the result. if (ref.task.status === "done") return { kind: "accepted" }; if (ref.task.status !== "review") return { kind: "failed", reason: m("задача уже не на приёмке") }; const actor = q.by != null ? { kind: "user" as const, userId: q.by, channel: (CHANNELS.has(q.via) ? q.via : "web") as ActorChannel } : { kind: "system" as const }; try { const r = await runAsActor(actor, () => acceptStory(db, ref, "web")); return { kind: r.pending ? "pending" : "accepted" }; } catch (e) { // The person's decision is kept: the watchdog (where `acceptStory` runs in place) carries it on. if (e instanceof RunnerUnavailableError) return RETRY; const reason = e instanceof PeppaError ? e.message : m("не удалось принять, попробуйте ещё раз позже"); await setAcceptFailure(db, q.taskId, reason).catch(() => {}); return { kind: "failed", reason }; } } /** * Accepts the queued stories of a project one by one. Returns at once (without work) when another * worker holds the project; stops when the runner service is not there (the lease goes, the * watchdog goes on). A project on pause accepts like the single «Принять» (a person's decision); * only the deferred accept of PEP-127 waits for «Продолжить». */ export async function processAcceptQueue(db: Db, projectId: number): Promise { if (busy.has(projectId)) return 0; busy.add(projectId); const owner = randomUUID(); let n = 0; try { for (;;) { if (!takeAcceptLease(db, projectId, owner)) break; const [q] = await queuedAccepts(db, projectId); if (!q) break; const outcome = await acceptOne(db, q); if (outcome === RETRY) break; finishAccept(db, q, outcome); n++; } } finally { releaseAcceptLease(db, projectId, owner); busy.delete(projectId); } return n; } /** Every project with a queue nobody carries. `wait` — for tests; the watchdog doesn't wait. */ export async function acceptQueueTick(db: Db, opts: { log?: (m: string) => void; wait?: boolean } = {}): Promise { const projects = [...new Set((await queuedAccepts(db)).map((q) => q.projectId))]; const runs = projects.map((id) => processAcceptQueue(db, id).catch((e) => { opts.log?.(`accept queue #${id}: ${(e as Error).message}`); return 0; }), ); if (opts.wait) await Promise.all(runs); }