import { cpus } from "node:os"; import { LeastBusy, LineProcess } from "../lib/line-process.js"; /** Stop adding face processes once the machine is this full. */ const CPU_TARGET = 0.97; interface CpuTimes { idle: number; total: number; } function cpuTimes(): CpuTimes { let idle = 0; let total = 0; for (const cpu of cpus()) { const t = cpu.times; idle += t.idle; total += t.user + t.nice + t.sys + t.idle + t.irq; } return { idle, total }; } export interface DetectedFace { x0: number; y0: number; x1: number; y1: number; score: number; /** Variance of the Laplacian of the aligned face; absent from older workers. */ sharpness?: number | null; landmarks: [number, number][]; embedding: number[] | null; } export interface FaceAnalysis { width: number; height: number; faces: DetectedFace[]; } export interface FaceEngine { readonly model: string; analyse(path: string): Promise; close(): Promise; } export const MODEL_IDS = { auraface: "auraface-v1", sface: "sface-2021dec" } as const; export type EmbedderName = keyof typeof MODEL_IDS; /** * The Rust face worker (`workers/faces`), kept running: one photo at a time over stdin/stdout. Restarts after a * crash; a request that hangs is failed after `timeoutMs`. */ export class FaceProcess implements FaceEngine { readonly model: string; private readonly proc: LineProcess; constructor(opts: { bin: string; modelsDir: string; embedder: EmbedderName; minScore?: number; timeoutMs?: number }) { this.model = MODEL_IDS[opts.embedder]; this.proc = new LineProcess({ name: "face worker", bin: opts.bin, args: ["--models", opts.modelsDir, "--embedder", opts.embedder, "--min-score", String(opts.minScore ?? 0.6)], timeoutMs: opts.timeoutMs ?? 120_000, }); } async analyse(path: string): Promise { const msg = (await this.proc.request({ path })) as Partial; return { width: msg.width ?? 0, height: msg.height ?? 0, faces: msg.faces ?? [] }; } close(): Promise { return this.proc.close(); } } /** Several face processes behind one engine; each request goes to the least busy one. */ export class FacePool implements FaceEngine { readonly model: string; private readonly pool: LeastBusy; constructor(private readonly engines: FaceEngine[]) { this.pool = new LeastBusy(engines); this.model = engines[0]!.model; } analyse(path: string): Promise { return this.pool.use((e) => e.analyse(path)); } async close(): Promise { await Promise.all(this.engines.map((e) => e.close())); } } /** * Face processes that start a few at a time and keep being added while the CPU is under {@link CPU_TARGET}. * Each process is one core. `cap` is the most this machine should run. */ export class GrowingFacePool implements FaceEngine { readonly model: string; private readonly engines: FaceEngine[] = []; private readonly busy: number[] = []; private last: CpuTimes = cpuTimes(); private lastGrow = 0; constructor( private readonly make: () => FaceEngine, private readonly cap: number, ) { const first = make(); this.model = first.model; this.engines.push(first); this.busy.push(0); this.add(Math.min(3, Math.max(0, cap - 1))); } get size(): number { return this.engines.length; } private add(count: number): void { const room = Math.max(0, this.cap - this.engines.length); const n = Math.min(count, room); for (let i = 0; i < n; i++) { this.engines.push(this.make()); this.busy.push(0); } } /** Add more processes when every current one is busy and the CPU is not full yet. */ private grow(): void { if (this.engines.length >= this.cap) return; const now = Date.now(); if (now - this.lastGrow < 1500) return; const allBusy = this.busy.every((n) => n > 0); if (!allBusy && this.engines.length >= 4) return; const sample = cpuTimes(); const idle = sample.idle - this.last.idle; const total = sample.total - this.last.total; this.last = sample; const used = total > 0 ? 1 - idle / total : 0; if (used >= CPU_TARGET) return; const step = Math.max(2, Math.floor(this.engines.length / 2)); this.add(step); this.lastGrow = now; } async analyse(path: string): Promise { this.grow(); let index = 0; for (let i = 1; i < this.busy.length; i++) { if (this.busy[i]! < this.busy[index]!) index = i; } this.busy[index]!++; try { return await this.engines[index]!.analyse(path); } finally { this.busy[index]!--; } } async close(): Promise { await Promise.all(this.engines.map((e) => e.close())); } }