"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.getQuotaStatus = getQuotaStatus;
exports.onStorageReclamation = onStorageReclamation;
exports.runReclamationHandlers = runReclamationHandlers;
exports.setAvailableSpaceRatioGetter = setAvailableSpaceRatioGetter;
const promises_1 = require("node:fs/promises");
const promises_2 = require("node:fs/promises");
const node_path_1 = require("node:path");
const manageThreads_js_1 = require("../server/threads/manageThreads.js");
const logger_ts_1 = require("../utility/logging/logger.js");
const hdbTerms_ts_1 = require("../utility/hdbTerms.js");
const envMgr = __importStar(require("../utility/environment/environmentManager.js"));
const common_utils_ts_1 = require("../utility/common_utils.js");
envMgr.initSync();
const reclamationHandlers = new Map();
const RECLAMATION_THRESHOLD = envMgr.get(hdbTerms_ts_1.CONFIG_PARAMS.STORAGE_RECLAMATION_THRESHOLD) ?? 0.4; // 40% remaining free space is the default
const RECLAMATION_INTERVAL = (0, common_utils_ts_1.convertToMS)(envMgr.get(hdbTerms_ts_1.CONFIG_PARAMS.STORAGE_RECLAMATION_INTERVAL)) || 3600000; // 1 hour is the default
// Written by host-manager every ~90s alongside the instance's hdb root
const QUOTA_STATUS_FILE = 'quota-status.json';
// Use statfs fallback if the file is older than this (host-manager outage, container start race, etc.)
const QUOTA_STATUS_MAX_AGE_MS = 5 * 60 * 1000;
/**
 * Reads the quota-status.json file written by host-manager.
 * Returns undefined if the file is absent or malformed; does not apply age filtering.
 */
async function getQuotaStatus() {
    const rootPath = envMgr.get(hdbTerms_ts_1.CONFIG_PARAMS.ROOTPATH);
    if (!rootPath)
        return undefined;
    try {
        const raw = await (0, promises_1.readFile)((0, node_path_1.join)(rootPath, QUOTA_STATUS_FILE), 'utf8');
        return JSON.parse(raw);
    }
    catch {
        return undefined;
    }
}
/**
 * Register a handler to be called when storage free space is low and reclamation is needed. The callback is called
 * with the priority of the reclamation, which is the ratio of the threshold to the available space ratio. If space is
 * low, the priority will be greater than 1. If the reclamation is successful, the callback will be called again with
 * a priority of 0.
 * @param path
 * @param handler
 * @param skipThreadCheck
 */
function onStorageReclamation(path, handler, skipThreadCheck) {
    if (skipThreadCheck || (0, manageThreads_js_1.getWorkerIndex)() === (0, manageThreads_js_1.getWorkerCount)() - 1) {
        // only run on one thread (last one)
        if (!path) {
            throw new Error('Storage reclamation path cannot be empty');
        }
        if (!reclamationHandlers.has(path)) {
            reclamationHandlers.set(path, []);
        }
        reclamationHandlers.get(path).push({ priority: 0, handler });
        if (!reclamationTimer)
            reclamationTimer = setTimeout(runReclamationHandlers, RECLAMATION_INTERVAL).unref();
    }
}
let reclamationTimer;
// If a fresh quota-status.json exists (written by host-manager every ~90s), use quota-based ratio.
// Otherwise fall back to statfs for the registered path.
const defaultGetAvailableSpaceRatio = async (path) => {
    const status = await getQuotaStatus();
    if (status?.quotaBytes && Date.now() - status.updatedAt < QUOTA_STATUS_MAX_AGE_MS) {
        return Math.max(0, status.quotaBytes - status.usedBytes) / status.quotaBytes;
    }
    const fsStats = await (0, promises_2.statfs)(path);
    return fsStats.bavail / fsStats.blocks;
};
let getAvailableSpaceRatio = defaultGetAvailableSpaceRatio;
/**
 * Run the registered reclamation handlers, if any disk drives are below the threshold
 */
async function runReclamationHandlers() {
    for (const [path, handlers] of reclamationHandlers) {
        try {
            const availableRatio = await getAvailableSpaceRatio(path);
            const priority = RECLAMATION_THRESHOLD / availableRatio;
            for (const entry of handlers) {
                const { priority: previousPriority, handler } = entry;
                entry.priority = priority;
                if (priority > 1 || previousPriority > 1) {
                    const resolution = handler(priority > 1 ? priority : 0);
                    if (resolution) {
                        // if the handler returns a promise, wait for it, otherwise it is probably not doing anything worth logging
                        logger_ts_1.logger.info?.(`Running storage reclamation handler for ${path} with priority ${priority}`);
                        await resolution;
                    }
                }
            }
        }
        catch (e) {
            logger_ts_1.logger.error?.('Error running storage reclamation handlers', e);
        }
    }
    reclamationTimer = setTimeout(runReclamationHandlers, RECLAMATION_INTERVAL).unref();
}
/**
 * Set the function used to get the available space ratio (for testing and backfill for Node v16)
 * @param newGetter
 */
function setAvailableSpaceRatioGetter(newGetter) {
    getAvailableSpaceRatio = newGetter ?? defaultGetAvailableSpaceRatio;
}
//# sourceMappingURL=storageReclamation.js.map