import { m as tr } from "@peppa/shared/i18n"; import { actorColumns } from "./actor.ts"; // PEP-42: story dependencies. "PAY-3 waits for PAY-2": PAY-3 is blocked until every // predecessor reaches review/done (an archived predecessor doesn't block). Same project only, // no cycles. The backlog dispatcher (PEP-24) skips blocked stories. import { events, projects, taskDeps, tasks, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { and, eq, inArray } from "drizzle-orm"; import { PeppaError } from "./errors.ts"; import { notify } from "./notify.ts"; import { resolveTask, type Task, type TaskRef, type TaskStatus } from "./tasks.ts"; /** A predecessor in these statuses no longer blocks its successors. */ export const UNBLOCKING: TaskStatus[] = ["review", "done"]; export interface Blocker { id: number; key: string; title: string; status: TaskStatus; /** Still holds the story back (not in review/done, not archived). */ open: boolean; } const isOpen = (t: Pick) => !t.archivedAt && !UNBLOCKING.includes(t.status); /** Predecessors of each of the given stories (all of a project when `projectId` is given). */ export async function blockersMap(db: Db, projectId: number): Promise> { const projectTasks = await db.select({ id: tasks.id, number: tasks.number, title: tasks.title, status: tasks.status, archivedAt: tasks.archivedAt, projectId: tasks.projectId }).from(tasks).where(eq(tasks.projectId, projectId)); const byId = new Map(projectTasks.map((t) => [t.id, t])); if (!projectTasks.length) return new Map(); const deps = await db.select().from(taskDeps).where(inArray(taskDeps.taskId, projectTasks.map((t) => t.id))); const [project] = await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId)); if (!project) return new Map(); const out = new Map(); for (const d of deps) { const b = byId.get(d.blockedById); if (!b) continue; const list = out.get(d.taskId) ?? []; list.push({ id: b.id, key: formatTaskKey(project.key, b.number), title: b.title, status: b.status, open: isOpen(b) }); out.set(d.taskId, list); } for (const list of out.values()) list.sort((a, b) => a.id - b.id); return out; } export async function blockersOf(db: Db, ref: TaskRef): Promise { return (await blockersMap(db, ref.project.id)).get(ref.task.id) ?? []; } /** Stories that wait for this one. */ export async function dependentsOf(db: Db, ref: TaskRef): Promise> { const rows = await db .select({ id: tasks.id, number: tasks.number, title: tasks.title, status: tasks.status }) .from(taskDeps) .innerJoin(tasks, eq(taskDeps.taskId, tasks.id)) .where(eq(taskDeps.blockedById, ref.task.id)); return rows.map((r) => ({ id: r.id, key: formatTaskKey(ref.project.key, r.number), title: r.title, status: r.status })); } /** Ids of the project's stories that are blocked right now. */ export async function blockedTaskIds(db: Db, projectId: number): Promise> { const out = new Set(); for (const [id, list] of await blockersMap(db, projectId)) if (list.some((b) => b.open)) out.add(id); return out; } /** True when `from` can reach `to` following "waits for" edges. */ async function reaches(db: Db, from: number, to: number): Promise { const seen = new Set(); let frontier = [from]; while (frontier.length) { if (frontier.includes(to)) return true; frontier.forEach((x) => seen.add(x)); const rows = await db.select({ next: taskDeps.blockedById }).from(taskDeps).where(inArray(taskDeps.taskId, frontier)); frontier = [...new Set(rows.map((r) => r.next))].filter((x) => !seen.has(x)); } return false; } /** Makes `ref` wait for `blocker`. Idempotent; rejects other projects, itself and cycles. */ export async function addDependency(db: Db, ref: TaskRef, blocker: TaskRef): Promise { if (blocker.project.id !== ref.project.id) throw new PeppaError(tr("{key} из другого проекта — зависимости только внутри проекта", { key: blocker.key })); if (blocker.task.id === ref.task.id) throw new PeppaError(tr("{key} не может зависеть от самой себя", { key: ref.key })); if (await reaches(db, blocker.task.id, ref.task.id)) throw new PeppaError(tr("Цикл зависимостей: {key} уже ждёт {key2}", { key: blocker.key, key2: ref.key })); const r = await db.insert(taskDeps).values({ taskId: ref.task.id, blockedById: blocker.task.id }).onConflictDoNothing().returning(); if (r.length) await logDeps(db, ref, { added: blocker.key }); } export async function removeDependency(db: Db, ref: TaskRef, blocker: TaskRef): Promise { const r = await db.delete(taskDeps).where(and(eq(taskDeps.taskId, ref.task.id), eq(taskDeps.blockedById, blocker.task.id))).returning(); if (r.length) await logDeps(db, ref, { removed: blocker.key }); } /** Replaces the whole list of predecessors ("PAY-2", "2"). Validates everything before changing anything. */ export async function setDependencies(db: Db, ref: TaskRef, keys: string[]): Promise { const wanted: TaskRef[] = []; for (const k of [...new Set(keys.map((x) => x.trim()).filter(Boolean))]) wanted.push(await resolveTask(db, k, ref.project.key)); const current = await blockersOf(db, ref); const keep = new Set(wanted.map((w) => w.task.id)); for (const c of current) if (!keep.has(c.id)) await db.delete(taskDeps).where(and(eq(taskDeps.taskId, ref.task.id), eq(taskDeps.blockedById, c.id))); const have = new Set(current.map((c) => c.id)); const added: string[] = []; try { for (const w of wanted) { if (have.has(w.task.id)) continue; await addDependency(db, ref, w); added.push(w.key); } } catch (e) { // Roll back to the previous list: either all of it applies or none. await db.delete(taskDeps).where(eq(taskDeps.taskId, ref.task.id)); if (current.length) await db.insert(taskDeps).values(current.map((c) => ({ taskId: ref.task.id, blockedById: c.id }))); throw e; } return blockersOf(db, ref); } async function logDeps(db: Db, ref: TaskRef, payload: Record) { await db.insert(events).values({ projectId: ref.project.id, taskId: ref.task.id, type: "task_deps", payload, ...actorColumns() }); await notify(db, { type: "task_updated", taskId: ref.task.id }); } /** "ждёт PAY-2, PAY-5" for the open blockers, or null. */ export function blockedLabel(list: Blocker[] | undefined): string | null { const open = (list ?? []).filter((b) => b.open); return open.length ? tr("ждёт {list}", { list: open.map((b) => b.key).join(", ") }) : null; }