Files
photoreport/apps/api/src/lib/capacity.ts
T
spark ac88d2445d
ci / rust (pull_request) Successful in 12m25s
ci / typescript (pull_request) Failing after 14m4s
Recognize a player from the club they were at that season.
The same person keeps one record when they change club, and the shirt number stays the one worn that season. Liga squads are read for every season still published, and face processes grow until the CPU is about 99% full.
2026-10-21 20:37:41 +01:00

175 lines
8.0 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.
import { readFileSync } from "node:fs";
import { availableParallelism, freemem, loadavg, totalmem } from "node:os";
/**
* How much the worker runs at once, from the machine it is on: the CPUs the container has and its memory. Give the
* container more cores and it does more at once, with nothing to configure; a value set in the environment wins.
*
* Shares when everything is busy together (a live game arriving while the archive indexes): faces and previews are
* CPU-bound and get the most; deliveries mostly wait on the network; the archive is bulk work that steps aside
* (see `Pressure`).
*/
export interface Capacity {
cpus: number;
memoryGb: number;
ingest: number;
archive: number;
/** The archive with a big backlog (a first import): most of the machine, until the backlog is gone. */
archiveBurst: number;
/**
* Archive images in flight at once with a big backlog: most of each one is waiting for the cloud's download, so
* many more than the CPUs; only `archiveBurst` of them make previews at the same time.
*/
archiveDownloads: number;
faces: number;
render: number;
/** Photos the autopilot analyses and edits at once. */
autopilot: number;
delivery: number;
}
/** Roughly what one task holds in memory (GB): a face process with its models, a sharp preview of a 50 MP file. */
const MEMORY_PER = { faces: 0.8, render: 0.6, ingest: 0.4, archive: 0.4 };
const clamp = (n: number, min: number, max: number) => Math.max(min, Math.min(max, Math.floor(n)));
export function planCapacity(
set: { ingest?: number | undefined; archive?: number | undefined; faces?: number | undefined; render?: number | undefined; autopilot?: number | undefined; delivery?: number | undefined },
machine: { cpus: number; memoryBytes: number } = { cpus: availableParallelism(), memoryBytes: totalmem() },
): Capacity {
const cpus = Math.max(1, machine.cpus);
const memoryGb = machine.memoryBytes / 1e9;
// Memory left for the work once the API, Postgres and Node themselves have theirs.
const spare = Math.max(1, memoryGb - 3);
const byMemory = (kind: keyof typeof MEMORY_PER, share: number) => Math.max(1, Math.floor((spare * share) / MEMORY_PER[kind]));
return {
cpus,
memoryGb: Math.round(memoryGb * 10) / 10,
// One face process per core, added while the CPU is under about 99% (GrowingFacePool). The model is
// about 0.8 GB, so a small container stops sooner. FACES_PROCESSES in the environment still overrides.
faces: set.faces ?? Math.max(1, Math.min(Math.max(1, Math.floor(cpus * 0.99)), byMemory("faces", 0.7))),
ingest: set.ingest ?? clamp(Math.min(cpus * 0.25, byMemory("ingest", 0.15)), 4, 32),
archive: set.archive ?? clamp(Math.min(cpus * 0.3, byMemory("archive", 0.2)), 2, 32),
// A fixed ARCHIVE_CONCURRENCY sets the everyday pace; a big backlog still gets the machine's share.
// A backlog to clear gets as much as the machine has: previews several per core (each waits on disk and the
// database too), and many more images in flight, which mostly wait for the cloud.
archiveBurst: Math.max(set.archive ?? 0, clamp(Math.min(cpus * 3, byMemory("archive", 0.6)), 2, 192)),
archiveDownloads: clamp(Math.max(16, cpus * 20), 16, 1000),
// A render used to take a small slice of the machine, so a backlog of edits crawled. Use the cores, and stop
// when memory (a decoded photo) runs short.
render: set.render ?? clamp(Math.min(cpus * 0.5, byMemory("render", 0.45)), 2, 16),
autopilot: set.autopilot ?? clamp(Math.min(cpus * 0.75, byMemory("render", 0.35)), 2, 16),
delivery: set.delivery ?? clamp(cpus * 0.25, 4, 16),
};
}
/** What the container sees of itself: CPU stall (cgroup v2 pressure, % of time tasks waited for a CPU) and memory. */
export interface Reading {
/** 0–100, or null when the kernel does not tell (then the load average is used). */
cpuStall: number | null;
load: number;
cpus: number;
free: number;
total: number;
}
const readFile = (path: string): string | null => {
try {
return readFileSync(path, "utf8");
} catch {
return null;
}
};
/** The container's own numbers where cgroup v2 gives them (an LXC sees the host's load average otherwise). */
export function readMachine(): Reading {
const psi = readFile("/sys/fs/cgroup/cpu.pressure");
const stall = psi ? Number(/some avg10=([\d.]+)/.exec(psi)?.[1]) : NaN;
const max = Number(readFile("/sys/fs/cgroup/memory.max")?.trim());
const current = Number(readFile("/sys/fs/cgroup/memory.current")?.trim());
const limited = Number.isFinite(max) && max > 0 && Number.isFinite(current);
// File cache the kernel can drop counts as free (reading thousands of photos fills it).
const cache = Number(/^inactive_file (\d+)$/m.exec(readFile("/sys/fs/cgroup/memory.stat") ?? "")?.[1] ?? 0);
return {
cpuStall: Number.isFinite(stall) ? stall : null,
load: loadavg()[0] ?? 0,
cpus: availableParallelism(),
free: limited ? max - current + cache : freemem(),
total: limited ? max : totalmem(),
};
}
/**
* Whether the machine is busy right now (tasks waiting for a CPU, or memory running out): bulk work (the archive)
* takes less while live work (FTP ingest, faces of a game, deliveries, the editor) needs the room, and more again
* when it is quiet.
*/
export class Pressure {
constructor(private readonly read: () => Reading = readMachine) {}
/**
* The share (0.25–1) of its full concurrency bulk work may use now. In a burst (a big backlog to clear) it keeps
* going while the CPUs are merely saturated, and only steps back when memory runs short or tasks pile up waiting.
*/
share(burst = false): number {
const r = this.read();
const memory = r.free / Math.max(1, r.total);
if (memory < 0.08) return 0.25;
if (burst) {
if (memory < 0.12 || (r.cpuStall !== null && r.cpuStall > 90)) return 0.5;
return 1;
}
if (r.cpuStall !== null) {
if (r.cpuStall > 60) return 0.25;
if (r.cpuStall > 30 || memory < 0.15) return 0.5;
return 1;
}
const busy = r.load / Math.max(1, r.cpus);
if (busy > 1.2) return 0.25;
if (busy > 0.9 || memory < 0.15) return 0.5;
return 1;
}
/** How many of `full` bulk tasks may run now (at least one, so it never stalls). */
allow(full: number, burst = false): number {
return Math.max(1, Math.floor(full * this.share(burst)));
}
}
/**
* How many Postgres connections the worker's pool may open for `wanted`, leaving room under `max` (Postgres'
* `max_connections`) for: the API's own Prisma pool, one per PM2 cluster instance; each of those instances'
* realtime connections (`attachRealtime` in `realtime.ts`: a 2-connection publish pool plus one dedicated
* `LISTEN` client, so 3 per instance — not just the worker's own 1-connection remote broadcaster); one extra
* instance's worth of API connections during a deploy (`pm2 startOrReload` on the clustered `photoreport-api`
* app brings a new instance online and confirms it before stopping an old one, so for a few seconds there are
* `apiInstances + 1` live, not just `apiInstances` — BIT-31550 was this exact overlap tipping the API's steady
* -state budget into Postgres' `superuser_reserved_connections`); Postgres' `superuser_reserved_connections`
* itself (reserved below `max_connections`, never available to the app no matter how much headroom is left —
* this is what "reserved for roles with the SUPERUSER attribute" means); and extra headroom for ad hoc
* connections (migrations, scripts, psql, admin tools) that aren't sized here.
*/
export function dbConnectionBudget(
wanted: number,
{
max = 100,
apiInstances = 2,
apiPoolSize = 10,
realtimePerInstance = 3,
apiReloadOverlap = 1,
superuserReserved = 3,
headroom = 10,
}: {
max?: number;
apiInstances?: number;
apiPoolSize?: number;
realtimePerInstance?: number;
apiReloadOverlap?: number;
superuserReserved?: number;
headroom?: number;
} = {},
): number {
const available = max - superuserReserved - (apiInstances + apiReloadOverlap) * (apiPoolSize + realtimePerInstance) - 1 - headroom;
return Math.max(1, Math.min(wanted, available));
}