import { existsSync, readFileSync } from 'node:fs';
import { availableParallelism, totalmem } from 'node:os';
export const MIN_AUTO_MAX_LIVE_WORKERS = 4;
export const MAX_AUTO_MAX_LIVE_WORKERS = 32;
export const DEFAULT_IDLE_SUSPEND_MS = 30 * 60_000;
function clamp(n, min, max) {
    return Math.max(min, Math.min(max, n));
}
function readMemoryLimitFile(path) {
    if (!existsSync(path))
        return undefined;
    const raw = readFileSync(path, 'utf-8').trim();
    if (!raw || raw === 'max')
        return undefined;
    const n = Number(raw);
    return Number.isFinite(n) && n > 0 ? n : undefined;
}
function cgroupMemoryLimitBytes(hostMemoryBytes) {
    const limits = [
        readMemoryLimitFile('/sys/fs/cgroup/memory.max'),
        readMemoryLimitFile('/sys/fs/cgroup/memory/memory.limit_in_bytes'),
    ].filter((n) => n !== undefined);
    if (limits.length === 0)
        return undefined;
    const limit = Math.min(...limits);
    return limit < hostMemoryBytes ? limit : undefined;
}
export function detectWorkerResources() {
    const hostMemoryBytes = totalmem();
    return {
        cpuCount: Math.max(1, availableParallelism?.() ?? 1),
        memoryBytes: cgroupMemoryLimitBytes(hostMemoryBytes) ?? hostMemoryBytes,
    };
}
export function autoMaxLiveWorkers(resources = detectWorkerResources()) {
    const cpuBudget = Math.max(1, resources.cpuCount) * 2;
    const memoryBudget = Math.max(1, Math.round(resources.memoryBytes / 1024 ** 3));
    return clamp(Math.min(cpuBudget, memoryBudget), MIN_AUTO_MAX_LIVE_WORKERS, MAX_AUTO_MAX_LIVE_WORKERS);
}
export function resolveWorkerBudget(workerConfig, resources = detectWorkerResources()) {
    const auto = autoMaxLiveWorkers(resources);
    return {
        maxLiveWorkers: workerConfig?.maxLiveWorkers ?? auto,
        idleSuspendMs: workerConfig?.idleSuspendMs ?? DEFAULT_IDLE_SUSPEND_MS,
        autoMaxLiveWorkers: auto,
        maxLiveWorkersSource: workerConfig?.maxLiveWorkers === undefined ? 'auto' : 'config',
        idleSuspendMsSource: workerConfig?.idleSuspendMs === undefined ? 'default' : 'config',
    };
}
//# sourceMappingURL=worker-budget.js.map