"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MetadataCache = void 0;
const tslib_1 = require("tslib");
const packageCache = tslib_1.__importStar(require("../../../util/cache/package"));
const hash_1 = require("../../../util/hash");
const result_1 = require("../../../util/result");
const url_1 = require("../../../util/url");
const common_1 = require("./common");
class MetadataCache {
    http;
    constructor(http) {
        this.http = http;
    }
    async getRelease(registryUrl, packageName, versions) {
        const cacheNs = `datasource-rubygems`;
        const cacheKey = `metadata-cache:${registryUrl}:${packageName}`;
        const hash = (0, hash_1.toSha256)(versions.join(''));
        const loadCache = () => result_1.Result.wrapNullable(packageCache.get(cacheNs, cacheKey), 'cache-not-found').transform((cache) => {
            return hash === cache.hash
                ? result_1.Result.ok(cache.data)
                : result_1.Result.err('cache-outdated');
        });
        const saveCache = async (data) => {
            const registryHostname = (0, url_1.parseUrl)(registryUrl)?.hostname;
            if (registryHostname === 'rubygems.org') {
                const newCache = { hash, data };
                const ttlMinutes = 100 * 24 * 60;
                const ttlRandomDelta = Math.floor(Math.random() * 10 * 24 * 60);
                await packageCache.set(cacheNs, cacheKey, newCache, ttlMinutes + ttlRandomDelta);
            }
            return data;
        };
        return await loadCache()
            .catch(() => (0, common_1.getV1Releases)(this.http, registryUrl, packageName).transform(saveCache))
            .catch(() => result_1.Result.ok({
            releases: versions.map((version) => ({ version })),
        }))
            .unwrapOrThrow();
    }
}
exports.MetadataCache = MetadataCache;
//# sourceMappingURL=metadata-cache.js.map