peppa/packages/core/src/capacity.ts
2026-11-20 18:56:42 +05:00

271 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-182: capacity of a subscription — at most N live runners at once (9 by default, a
// superadmin changes it per set of subscriptions). A story that finds no room waits «В очереди»
// (in progress, no runner) and starts by itself once a runner finishes; the team of personas
// grows only within the capacity.
import { m as tr } from "@peppa/shared/i18n";
import { formatTaskKey } from "@peppa/shared";
import { projects, sessions, settings, subscriptionPoolMembers, subscriptions, tasks, type Db, keyPrefix } from "@peppa/db";
import { and, eq, inArray, isNotNull, like, notInArray } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
import { getPool, isUsable, requireSuperadmin } from "./subscriptions.ts";
import type { User } from "./users.ts";
export const CAPACITY_MIN = 1;
export const CAPACITY_MAX = 20;
/** Live runners per subscription when the set has no own value (`PEPPA_SUBSCRIPTION_CAPACITY` for stands). */
export const defaultCapacity = () => {
const n = Number(process.env.PEPPA_SUBSCRIPTION_CAPACITY ?? 9);
return Number.isInteger(n) && n >= CAPACITY_MIN && n <= CAPACITY_MAX ? n : 9;
};
const CAPACITY_PREFIX = "pool.capacity:";
const capacityKey = (poolId: number) => `${CAPACITY_PREFIX}${poolId}`;
/** No subscription of the set has room for one more runner: the story waits in the queue. */
export class NoCapacityError extends PeppaError {
constructor() {
super(tr("Все агенты заняты — задача начнётся, когда освободится агент"));
this.name = "NoCapacityError";
}
}
export const isNoCapacity = (e: unknown): e is NoCapacityError => e instanceof NoCapacityError || (e as Error | null)?.name === "NoCapacityError";
/** Runners per subscription of the set (its own value, else the default). */
export async function poolCapacity(db: Db, poolId: number): Promise<number> {
return (await getSetting<number>(db, capacityKey(poolId))) ?? defaultCapacity();
}
/** Own capacities of the sets: poolId → value (sets with the default are absent). */
export async function poolCapacities(db: Db): Promise<Map<number, number>> {
const rows = await db.select().from(settings).where(keyPrefix(settings.key, `${CAPACITY_PREFIX}`));
return new Map(rows.map((r) => [Number(r.key.slice(CAPACITY_PREFIX.length)), Number(r.value)]));
}
/** Superadmin's «Агентов на подписку»: 1..20, works from the next start on. */
export async function setPoolCapacity(db: Db, admin: Pick<User, "login">, poolId: number, value: number): Promise<number> {
await requireSuperadmin(db, admin);
await getPool(db, poolId);
const n = Math.floor(Number(value));
if (!(n >= CAPACITY_MIN && n <= CAPACITY_MAX)) throw new PeppaError(tr("Агентов на подписку — от {min} до {max}", { min: CAPACITY_MIN, max: CAPACITY_MAX }));
if (n === defaultCapacity()) await deleteSetting(db, capacityKey(poolId));
else await setSetting(db, capacityKey(poolId), n);
return n;
}
/**
* Capacity of each subscription: the smallest of its sets' values (a subscription may be in
* several), the default for one outside any set.
*/
export async function subscriptionCapacities(db: Db): Promise<(subscriptionId: number) => number> {
const own = await poolCapacities(db);
const members = await db.select().from(subscriptionPoolMembers);
const caps = new Map<number, number>();
for (const m of members) {
const c = own.get(m.poolId) ?? defaultCapacity();
caps.set(m.subscriptionId, Math.min(caps.get(m.subscriptionId) ?? Infinity, c));
}
return (id) => caps.get(id) ?? defaultCapacity();
}
/** Live runners (not done/failed) per subscription, over all projects. */
export async function liveBySubscription(db: Db): Promise<Map<number, number>> {
const rows = await db
.select({ id: sessions.subscriptionId })
.from(sessions)
.where(and(isNotNull(sessions.subscriptionId), notInArray(sessions.status, FINISHED_SESSION_STATUSES)));
const m = new Map<number, number>();
for (const r of rows) m.set(r.id!, (m.get(r.id!) ?? 0) + 1);
return m;
}
/**
* True when one more runner of the project can start now: some usable subscription of its set
* has fewer live runners than the capacity. A project without a set (this machine's login) — always.
*/
export async function poolHasRoom(db: Db, projectId: number, now = new Date()): Promise<boolean> {
const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, projectId));
if (p?.poolId == null) return true;
const cap = await poolCapacity(db, p.poolId);
const live = await liveBySubscription(db);
const subs = await db
.select({ s: subscriptions })
.from(subscriptionPoolMembers)
.innerJoin(subscriptions, eq(subscriptionPoolMembers.subscriptionId, subscriptions.id))
.where(eq(subscriptionPoolMembers.poolId, p.poolId));
return subs.some(({ s }) => isUsable(s, now) && (live.get(s.id) ?? 0) < cap);
}
type SyncDb = Pick<Db, "select">;
/**
* Inside `ensureSessionAgent`'s transaction: may the team get one more persona for this
* session? A runner on this machine's login (no subscription) — yes, as before. Otherwise only
* while the live runners on subscriptions (this one included) fit in the total capacity of
* the subscriptions of all sets. `extra`: runners about to be created (not in the table yet).
*/
export function teamHasRoomSync(tx: SyncDb, session: { subscriptionId: number | null }, extra = 0): boolean {
if (session.subscriptionId == null) return true;
const own = new Map(
tx
.select()
.from(settings)
.where(keyPrefix(settings.key, `${CAPACITY_PREFIX}`))
.all()
.map((r) => [Number(r.key.slice(CAPACITY_PREFIX.length)), Number(r.value)] as const),
);
const members = tx.select().from(subscriptionPoolMembers).all();
const subs = new Map(tx.select().from(subscriptions).all().map((s) => [s.id, s] as const));
const caps = new Map<number, number>();
for (const m of members) {
// Every subscription of a set counts, a limited one too: its runners wait for the reset and
// keep their personas, so they are part of how many runners can be live at once.
const s = subs.get(m.subscriptionId);
if (!s) continue;
caps.set(s.id, Math.min(caps.get(s.id) ?? Infinity, own.get(m.poolId) ?? defaultCapacity()));
}
// The session's own subscription counts even outside any set (ticked by hand).
if (!caps.has(session.subscriptionId)) caps.set(session.subscriptionId, defaultCapacity());
const total = [...caps.values()].reduce((a, b) => a + b, 0);
const live = tx
.select({ id: sessions.id })
.from(sessions)
.where(and(isNotNull(sessions.subscriptionId), notInArray(sessions.status, FINISHED_SESSION_STATUSES)))
.all().length;
return live + extra <= total;
}
// ── the queue of stories waiting for room ────────────────────────────────────────
const WAIT_PREFIX = "capacity.wait:";
const waitKey = (taskId: number) => `${WAIT_PREFIX}${taskId}`;
interface WaitRow {
at: number;
prompt?: string | null;
}
/** The story waits for room (in progress, no runner); a repeated call keeps its place. */
export async function waitForCapacity(db: Db, taskId: number, prompt?: string | null, now = new Date()): Promise<void> {
const cur = await getSetting<WaitRow>(db, waitKey(taskId));
await setSetting(db, waitKey(taskId), { at: cur?.at ?? now.getTime(), prompt: prompt ?? cur?.prompt ?? null } satisfies WaitRow);
}
export async function clearCapacityWait(db: Db, taskId: number): Promise<void> {
await deleteSetting(db, waitKey(taskId));
}
export async function isWaitingForCapacity(db: Db, taskId: number): Promise<boolean> {
return (await getSetting<WaitRow>(db, waitKey(taskId))) != null;
}
export interface CapacityQueueItem {
taskId: number;
projectId: number;
key: string;
/** The set of subscriptions the story waits on (null: the project has none). */
poolId: number | null;
/** 1-based place in the set's queue. */
position: number;
at: Date;
prompt: string | null;
}
/** Task statuses of the «В работе» column. */
const WORKING = ["proposing", "awaiting_approval", "in_progress", "blocked"] as const;
/**
* Stories waiting for room, in the order they start: one queue per set of subscriptions;
* inside a project — board order; the projects of a set take turns, the one waiting longest first.
* Rows of stories that left work or were archived are not returned (`capacityQueueTick` drops them).
*/
export async function capacityQueue(db: Db, o: { projectIds?: number[] } = {}): Promise<CapacityQueueItem[]> {
const rows = await db.select().from(settings).where(keyPrefix(settings.key, `${WAIT_PREFIX}`));
if (!rows.length) return [];
const waits = new Map(rows.map((r) => [Number(r.key.slice(WAIT_PREFIX.length)), r.value as WaitRow] as const));
const ts = await db
.select({ t: tasks, projectKey: projects.key, poolId: projects.subscriptionPoolId })
.from(tasks)
.innerJoin(projects, eq(tasks.projectId, projects.id))
.where(inArray(tasks.id, [...waits.keys()]));
// A story that already has a live runner is not waiting any more.
const running = new Set(
(await db.select({ id: sessions.taskId }).from(sessions).where(and(inArray(sessions.taskId, [...waits.keys()]), notInArray(sessions.status, FINISHED_SESSION_STATUSES)))).map((r) => r.id),
);
const live = ts.filter(({ t }) => (WORKING as readonly string[]).includes(t.status) && !t.archivedAt && !running.has(t.id));
const byPool = new Map<string, typeof live>();
for (const r of live) {
const k = r.poolId == null ? `p${r.t.projectId}` : `s${r.poolId}`;
byPool.set(k, [...(byPool.get(k) ?? []), r]);
}
const out: CapacityQueueItem[] = [];
for (const group of byPool.values()) {
const byProject = new Map<number, typeof live>();
for (const r of group) byProject.set(r.t.projectId, [...(byProject.get(r.t.projectId) ?? []), r]);
const lists = [...byProject.values()].map((l) => l.sort((a, b) => a.t.position - b.t.position || a.t.number - b.t.number));
const since = (l: typeof live) => Math.min(...l.map((r) => waits.get(r.t.id)!.at));
lists.sort((a, b) => since(a) - since(b) || a[0]!.t.projectId - b[0]!.t.projectId);
let position = 0;
for (let i = 0; lists.some((l) => l.length > i); i++) {
for (const l of lists) {
const r = l[i];
if (!r) continue;
const w = waits.get(r.t.id)!;
out.push({ taskId: r.t.id, projectId: r.t.projectId, key: formatTaskKey(r.projectKey, r.t.number), poolId: r.poolId, position: ++position, at: new Date(w.at), prompt: w.prompt ?? null });
}
}
}
return o.projectIds ? out.filter((q) => o.projectIds!.includes(q.projectId)) : out;
}
/** Stories that left the queue's reach (out of work, archived, gone) — their rows are dropped. */
export async function staleCapacityWaits(db: Db): Promise<number[]> {
const rows = await db.select().from(settings).where(keyPrefix(settings.key, `${WAIT_PREFIX}`));
if (!rows.length) return [];
const ids = rows.map((r) => Number(r.key.slice(WAIT_PREFIX.length)));
const kept = new Set((await capacityQueue(db)).map((q) => q.taskId));
return ids.filter((id) => !kept.has(id));
}
/** taskId → place in its queue, for the board and the story page. */
export async function queuePositions(db: Db, projectId: number): Promise<Map<number, number>> {
return new Map((await capacityQueue(db, { projectIds: [projectId] })).map((q) => [q.taskId, q.position]));
}
export interface WorkLine {
/** Stories with an agent working on them right now. */
doing: number;
/** Stories waiting for a free agent. */
queued: number;
}
/** «Делается: 4 · В очереди: 3» of the projects (product view: no subscriptions, no capacity). */
/**
* PEP-216: `workLine` of many project sets from one pass over the sessions and one queue —
* the Home page asks it for every project, and a query pair per project cost ~25 ms there.
*/
export async function workLineIndex(db: Db, projectIds: number[]): Promise<(ids: number[]) => WorkLine> {
if (!projectIds.length) return () => ({ doing: 0, queued: 0 });
const rows = await db
.selectDistinct({ taskId: sessions.taskId, projectId: sessions.projectId })
.from(sessions)
.innerJoin(tasks, eq(sessions.taskId, tasks.id))
.where(and(inArray(sessions.projectId, projectIds), notInArray(sessions.status, FINISHED_SESSION_STATUSES), inArray(tasks.status, [...WORKING])));
const queue = await capacityQueue(db, { projectIds });
return (ids) => {
const set = new Set(ids);
return { doing: new Set(rows.filter((r) => set.has(r.projectId)).map((r) => r.taskId)).size, queued: queue.filter((q) => set.has(q.projectId)).length };
};
}
export async function workLine(db: Db, projectIds: number[]): Promise<WorkLine> {
if (!projectIds.length) return { doing: 0, queued: 0 };
const rows = await db
.selectDistinct({ taskId: sessions.taskId })
.from(sessions)
.innerJoin(tasks, eq(sessions.taskId, tasks.id))
.where(and(inArray(sessions.projectId, projectIds), notInArray(sessions.status, FINISHED_SESSION_STATUSES), inArray(tasks.status, [...WORKING])));
return { doing: rows.length, queued: (await capacityQueue(db, { projectIds })).length };
}