"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.ResponseCache = void 0;
const util_1 = require("../util");
const censor_list_1 = __importDefault(require("../util/censor/censor-list"));
const utils_1 = require("../validation/utils");
const _1 = require("./");
const cacheMetrics = __importStar(require("./metrics"));
const logger = (0, util_1.makeLogger)('ResponseCache');
/**
 * Special type of cache to store responses for this adapter.
 */
class ResponseCache {
    constructor({ inputParameters, adapterName, endpointName, adapterSettings, dependencies, }) {
        this.cache = dependencies.cache;
        this.inputParameters = inputParameters;
        this.adapterName = adapterName;
        this.endpointName = endpointName;
        this.adapterSettings = adapterSettings;
    }
    /**
     * Sets responses in the adapter cache (adding necessary metadata and defaults)
     *
     * @param results - the entries to write to the cache
     */
    async write(transportName, results) {
        const censorList = censor_list_1.default.getAll();
        const entries = results.map((r) => {
            const { data, result, errorMessage } = r.response;
            if (!errorMessage && data === undefined) {
                logger.warn('The "data" property of the response is undefined.');
            }
            else if (!errorMessage && result === undefined) {
                logger.warn('The "result" property of the response is undefined.');
            }
            let censoredResponse;
            if (!censorList.length) {
                censoredResponse = r.response;
            }
            else {
                try {
                    censoredResponse = (0, util_1.censor)(r.response, censorList, true);
                }
                catch (error) {
                    (0, util_1.censorLogs)(() => logger.error(`Error censoring response: ${error}`));
                    censoredResponse = {
                        statusCode: 502,
                        errorMessage: 'Response could not be censored due to an error',
                        timestamps: r.response.timestamps,
                    };
                }
            }
            const response = {
                ...censoredResponse,
                statusCode: censoredResponse.statusCode || 200,
            };
            if (this.adapterSettings.METRICS_ENABLED &&
                this.adapterSettings.EXPERIMENTAL_METRICS_ENABLED) {
                response.meta = {
                    adapterName: (0, _1.calculateAdapterName)(this.adapterName, r.params),
                    metrics: {
                        feedId: (0, _1.calculateFeedId)({
                            adapterSettings: this.adapterSettings,
                        }, r.params),
                    },
                };
            }
            if (response.timestamps?.providerIndicatedTimeUnixMs !== undefined) {
                const timestampValidator = utils_1.validator.responseTimestamp();
                const error = timestampValidator.fn(response.timestamps?.providerIndicatedTimeUnixMs);
                if (error) {
                    (0, util_1.censorLogs)(() => logger.warn(`Provider indicated time is invalid: ${error}`));
                }
            }
            return {
                key: (0, _1.calculateCacheKey)({
                    transportName,
                    data: r.params,
                    adapterName: this.adapterName,
                    endpointName: this.endpointName,
                    adapterSettings: this.adapterSettings,
                }),
                value: response,
            };
        });
        const ttl = this.adapterSettings.CACHE_MAX_AGE;
        await this.cache.setMany(entries, ttl);
        const now = Date.now();
        for (const { key, value } of entries) {
            // Only record metrics if feed Id is present, otherwise assuming value is not adapter response to record
            const response = value;
            const feedId = response.meta?.metrics?.feedId;
            if (feedId) {
                const providerTime = response.timestamps?.providerIndicatedTimeUnixMs;
                const timeDelta = providerTime ? now - providerTime : undefined;
                // Record cache set count, max age, and staleness (set to 0 for cache set)
                const label = cacheMetrics.cacheMetricsLabel(key, feedId, this.cache.type);
                cacheMetrics.cacheSet(label, ttl, timeDelta);
            }
        }
        return;
    }
    /**
     * Sets a new TTL value for already cached responses in the adapter cache
     *
     * @param transportName - transport name
     * @param params - set of parameters that uniquely relate to the response
     * @param ttl - a new time in milliseconds until the response expires
     */
    async writeTTL(transportName, params, ttl) {
        for (const param of params) {
            const key = (0, _1.calculateCacheKey)({
                transportName: transportName,
                data: param,
                adapterName: this.adapterName,
                endpointName: this.endpointName,
                adapterSettings: this.adapterSettings,
            });
            this.cache.setTTL(key, ttl);
        }
    }
}
exports.ResponseCache = ResponseCache;
//# sourceMappingURL=response.js.map