// PEP-182: stories waiting «В очереди» for room on the subscriptions start by themselves as // soon as a runner finishes — in each set's queue order (board order inside a project, projects // taking turns). A wait is not a failure: the owner sees the mark on the card, nobody is paged. import { capacityQueue, clearCapacityWait, isNoCapacity, platformFailure, staleCapacityWaits } from "@peppa/core"; import type { Db } from "@peppa/db"; import { resolveTaskById } from "./sessions.ts"; import { startTaskOnRunner } from "./runners.ts"; export async function capacityQueueTick(db: Db, opts: { now?: Date; log?: (m: string) => void } = {}): Promise { const log = opts.log ?? (() => {}); for (const id of await staleCapacityWaits(db)) await clearCapacityWait(db, id); const full = new Set(); let started = 0; for (const q of await capacityQueue(db)) { const set = q.poolId == null ? `p${q.projectId}` : `s${q.poolId}`; if (full.has(set)) continue; const ref = await resolveTaskById(db, q.taskId).catch(() => null); if (!ref) { await clearCapacityWait(db, q.taskId); continue; } try { // Still no room: startTaskOnRunner keeps the story in its place in the queue. const r = await startTaskOnRunner(db, ref, { prompt: q.prompt ?? undefined }); if (r.waiting) { full.add(set); continue; } await clearCapacityWait(db, q.taskId); started++; log(`${ref.key}: room on the subscriptions — started from the queue (${r.started ? `new #${r.started}` : `#${r.runner}`})`); } catch (e) { if (isNoCapacity(e)) { full.add(set); continue; } // The story keeps its place; a platform failure goes to the superadmins (once a day), not to the owner. await platformFailure(db, e, { service: "watchdog", where: `capacity queue ${ref.key}`, log, now: opts.now }); log(`${ref.key}: start from the queue failed — ${(e as Error).message}`); } } return started; }