"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.get = get;
exports.set = set;
exports.init = init;
exports.cleanup = cleanup;
const tslib_1 = require("tslib");
const cacache_1 = tslib_1.__importDefault(require("cacache"));
const luxon_1 = require("luxon");
const upath_1 = tslib_1.__importDefault(require("upath"));
const logger_1 = require("../../../logger");
const compress_1 = require("../../compress");
function getKey(namespace, key) {
    return `${namespace}-${key}`;
}
let cacheFileName;
async function rm(namespace, key) {
    logger_1.logger.trace({ namespace, key }, 'Removing cache entry');
    await cacache_1.default.rm.entry(cacheFileName, getKey(namespace, key));
}
async function get(namespace, key) {
    if (!cacheFileName) {
        return undefined;
    }
    try {
        const res = await cacache_1.default.get(cacheFileName, getKey(namespace, key));
        const cachedValue = JSON.parse(res.data.toString());
        if (cachedValue) {
            if (luxon_1.DateTime.local() < luxon_1.DateTime.fromISO(cachedValue.expiry)) {
                logger_1.logger.trace({ namespace, key }, 'Returning cached value');
                // istanbul ignore if
                if (!cachedValue.compress) {
                    return cachedValue.value;
                }
                const res = await (0, compress_1.decompressFromBase64)(cachedValue.value);
                return JSON.parse(res);
            }
            await rm(namespace, key);
        }
    }
    catch (err) {
        logger_1.logger.trace({ namespace, key }, 'Cache miss');
    }
    return undefined;
}
async function set(namespace, key, value, ttlMinutes = 5) {
    if (!cacheFileName) {
        return;
    }
    logger_1.logger.trace({ namespace, key, ttlMinutes }, 'Saving cached value');
    await cacache_1.default.put(cacheFileName, getKey(namespace, key), JSON.stringify({
        compress: true,
        value: await (0, compress_1.compressToBase64)(JSON.stringify(value)),
        expiry: luxon_1.DateTime.local().plus({ minutes: ttlMinutes }),
    }));
}
function init(cacheDir) {
    cacheFileName = upath_1.default.join(cacheDir, '/renovate/renovate-cache-v1');
    logger_1.logger.debug('Initializing Renovate internal cache into ' + cacheFileName);
    return cacheFileName;
}
async function cleanup() {
    logger_1.logger.debug('Checking file package cache for expired items');
    try {
        let totalCount = 0;
        let deletedCount = 0;
        const startTime = Date.now();
        for await (const item of cacache_1.default.ls.stream(cacheFileName)) {
            totalCount += 1;
            const cachedItem = item;
            const res = await cacache_1.default.get(cacheFileName, cachedItem.key);
            let cachedValue;
            try {
                cachedValue = JSON.parse(res.data.toString());
            }
            catch (err) {
                logger_1.logger.debug('Error parsing cached value - deleting');
            }
            if (!cachedValue ||
                (cachedValue?.expiry &&
                    luxon_1.DateTime.local() > luxon_1.DateTime.fromISO(cachedValue.expiry))) {
                await cacache_1.default.rm.entry(cacheFileName, cachedItem.key);
                await cacache_1.default.rm.content(cacheFileName, cachedItem.integrity);
                deletedCount += 1;
            }
        }
        const durationMs = Math.round(Date.now() - startTime);
        logger_1.logger.debug(`Deleted ${deletedCount} of ${totalCount} file cached entries in ${durationMs}ms`);
    }
    catch (err) /* istanbul ignore next */ {
        logger_1.logger.warn({ err }, 'Error cleaning up expired file cache');
    }
}
//# sourceMappingURL=file.js.map