'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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.logRotator = logRotator;
const fs_1 = require("fs");
const zlib_1 = require("zlib");
const util_1 = require("util");
const stream_1 = require("stream");
const pipe = (0, util_1.promisify)(stream_1.pipeline);
const path = __importStar(require("path"));
const envMgr = __importStar(require("../environment/environmentManager.js"));
envMgr.initSync();
const harper_logger_ts_1 = __importDefault(require("./harper_logger.js"));
const hdbTerms_ts_1 = require("../hdbTerms.js");
const common_utils_ts_1 = require("../common_utils.js");
const storageReclamation_ts_1 = require("../../server/storageReclamation.js");
// Interval in ms to check log file and decide if it should be rotated.
const LOG_AUDIT_INTERVAL = 60000;
const INT_SIZE_UNDEFINED_MSG = "'interval' and 'maxSize' are both undefined, to enable logging rotation at least one of these values must be defined in harperdb-config.yaml";
/**
 * Rotates hdb.log using an interval and/or maxSize param to determine if log should be rotated.
 * Uses an unref setInterval to periodically check time passed since rotation and size of log file.
 * If log file is within the values set in config, log file will be renamed/moved and a new empty hdb.log created.
 * @returns LogRotator
 */
function logRotator({ logger, maxSize, interval, retention, enabled, path: rotatedLogDir, auditInterval }) {
    if (enabled === false)
        return;
    let reclamationPriority = 0;
    (0, storageReclamation_ts_1.onStorageReclamation)(logger.path, (priority) => {
        reclamationPriority = priority;
    }, true);
    if (!maxSize && !interval) {
        throw new Error(INT_SIZE_UNDEFINED_MSG);
    }
    if (!rotatedLogDir) {
        rotatedLogDir = path.join(path.dirname(logger.path), 'rotated');
    }
    (0, fs_1.mkdirSync)(rotatedLogDir, { recursive: true });
    // Convert maxSize param to bytes.
    let maxBytes;
    if (maxSize) {
        const unit = maxSize.slice(-1);
        const size = maxSize.slice(0, -1);
        if (unit === 'G')
            maxBytes = size * 1000000000;
        else if (unit === 'M')
            maxBytes = size * 1000000;
        else
            maxBytes = size * 1000;
    }
    // Convert interval param to ms.
    let maxInterval;
    if (interval) {
        maxInterval = (0, common_utils_ts_1.convertToMS)(interval);
    }
    let lastRotatedLogPath;
    // convert date.now to minutes
    let lastRotationTime = Date.now();
    harper_logger_ts_1.default.trace('Log rotate enabled, maxSize:', maxSize, 'interval:', interval);
    const setIntervalId = setInterval(async () => {
        if (maxBytes) {
            let fileStats;
            try {
                fileStats = await fs_1.promises.stat(logger.path);
            }
            catch (err) {
                // If the log file doesn't exist, skip rotation check
                if (err.code === 'ENOENT')
                    return;
                throw err;
            }
            if (fileStats.size >= maxBytes) {
                try {
                    lastRotatedLogPath = await moveLogFile(logger.path, rotatedLogDir);
                }
                catch (err) {
                    // If the log file doesn't exist, skip rotation
                    if (err.code === 'ENOENT')
                        return;
                    throw err;
                }
            }
        }
        if (maxInterval) {
            const minSinceLastRotate = Date.now() - lastRotationTime;
            if (minSinceLastRotate >= maxInterval) {
                try {
                    lastRotatedLogPath = await moveLogFile(logger.path, rotatedLogDir);
                    lastRotationTime = Date.now();
                }
                catch (err) {
                    // If the log file doesn't exist, skip rotation
                    if (err.code === 'ENOENT')
                        return;
                    throw err;
                }
            }
        }
        if (retention || reclamationPriority) {
            // remove old logs after retention time
            // adjust retention time if there is a reclamation priority in place
            const retentionMs = (0, common_utils_ts_1.convertToMS)(retention ?? '1M') / (1 + reclamationPriority);
            reclamationPriority = 0; // reset it after use
            const files = await fs_1.promises.readdir(rotatedLogDir);
            for (const file of files) {
                try {
                    const fileStats = await fs_1.promises.stat(path.join(rotatedLogDir, file));
                    if (Date.now() - fileStats.mtimeMs > retentionMs) {
                        await fs_1.promises.unlink(path.join(rotatedLogDir, file));
                    }
                }
                catch (err) {
                    harper_logger_ts_1.default.error('Error trying to remove log', file, err);
                }
            }
        }
    }, auditInterval ?? LOG_AUDIT_INTERVAL).unref();
    return {
        end() {
            clearInterval(setIntervalId);
        },
        getLastRotatedLogPath() {
            return lastRotatedLogPath;
        },
    };
}
async function moveLogFile(logPath, rotatedLogPath) {
    const compress = envMgr.get(hdbTerms_ts_1.CONFIG_PARAMS.LOGGING_ROTATION_COMPRESS);
    let fullRotateLogPath = path.join(rotatedLogPath, `HDB-${new Date(Date.now()).toISOString().replaceAll(':', '-')}.log`);
    // Move log file to rotated log path first (if we crash
    // during compression, we don't want to restart the compression with a new file)
    await fs_1.promises.rename(logPath, fullRotateLogPath);
    if (compress) {
        logPath = fullRotateLogPath;
        fullRotateLogPath += '.gz';
        await pipe((0, fs_1.createReadStream)(logPath), (0, zlib_1.createGzip)(), (0, fs_1.createWriteStream)(fullRotateLogPath));
        await fs_1.promises.unlink(logPath);
    }
    // Close old log file.
    harper_logger_ts_1.default.closeLogFile();
    // This notify log will create a new log file after the previous one has been rotated. It's important to keep this log as notify
    harper_logger_ts_1.default.notify(`hdb.log rotated, old log moved to ${fullRotateLogPath}`);
    return fullRotateLogPath;
}
//# sourceMappingURL=logRotator.js.map