"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 stats_1 = require("../../stats");
const memCache = tslib_1.__importStar(require("../memory"));
const fileCache = tslib_1.__importStar(require("./file"));
const redisCache = tslib_1.__importStar(require("./redis"));
const sqlite_1 = require("./sqlite");
let cacheProxy;
function getGlobalKey(namespace, key) {
    return `global%%${namespace}%%${key}`;
}
async function get(namespace, key) {
    if (!cacheProxy) {
        return undefined;
    }
    const globalKey = getGlobalKey(namespace, key);
    let p = memCache.get(globalKey);
    if (!p) {
        p = stats_1.PackageCacheStats.wrapGet(() => cacheProxy.get(namespace, key));
        memCache.set(globalKey, p);
    }
    const result = await p;
    return result;
}
async function set(namespace, key, value, minutes) {
    if (!cacheProxy) {
        return;
    }
    await stats_1.PackageCacheStats.wrapSet(() => cacheProxy.set(namespace, key, value, minutes));
    const globalKey = getGlobalKey(namespace, key);
    const p = Promise.resolve(value);
    memCache.set(globalKey, p);
}
async function init(config) {
    if (config.redisUrl) {
        await redisCache.init(config.redisUrl, config.redisPrefix);
        cacheProxy = {
            get: redisCache.get,
            set: redisCache.set,
        };
        return;
    }
    if (process.env.RENOVATE_X_SQLITE_PACKAGE_CACHE) {
        cacheProxy = await sqlite_1.SqlitePackageCache.init(config.cacheDir);
        return;
    }
    if (config.cacheDir) {
        fileCache.init(config.cacheDir);
        cacheProxy = {
            get: fileCache.get,
            set: fileCache.set,
            cleanup: fileCache.cleanup,
        };
        return;
    }
}
async function cleanup(config) {
    if (config?.redisUrl) {
        await redisCache.end();
    }
    if (cacheProxy?.cleanup) {
        await cacheProxy.cleanup();
    }
}
//# sourceMappingURL=index.js.map