"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.clearDnsCache = exports.printDnsStats = exports.dnsLookup = void 0;
const tslib_1 = require("tslib");
const dns_1 = require("dns");
const quick_lru_1 = tslib_1.__importDefault(require("quick-lru"));
const logger_1 = require("../../logger");
const cache = new quick_lru_1.default({ maxSize: 1000 });
function lookup(...[host, options, callback]) {
    let opts;
    // TODO: strict null incompatible types (#7154)
    let cb;
    if (typeof options === 'function') {
        opts = {};
        cb = options;
    }
    else if (typeof options === 'number') {
        opts = { family: options };
        cb = callback;
    }
    else {
        opts = options;
        cb = callback;
    }
    // istanbul ignore if: not used
    if (opts.all) {
        const key = `${host}_all`;
        if (cache.has(key)) {
            logger_1.logger.trace({ host }, 'dns lookup cache hit');
            cb(null, cache.get(key));
            return;
        }
        (0, dns_1.lookup)(host, opts, (err, res) => {
            if (err) {
                logger_1.logger.debug({ host, err }, 'dns lookup error');
                cb(err, null, null);
                return;
            }
            logger_1.logger.trace({ host, opts, res }, 'dns lookup');
            cache.set(key, res);
            cb(null, res, null);
        });
    }
    else {
        if (cache.has(host)) {
            logger_1.logger.trace({ host }, 'dns lookup cache hit');
            cb(null, ...cache.get(host));
            return;
        }
        (0, dns_1.lookup)(host, opts, (err, ...res) => {
            if (err) {
                logger_1.logger.debug({ host, err }, 'dns lookup error');
                cb(err);
                return;
            }
            logger_1.logger.trace({ host, opts, res }, 'dns lookup');
            cache.set(host, res);
            cb(null, ...res);
        });
    }
}
exports.dnsLookup = lookup;
function printDnsStats() {
    logger_1.logger.debug({ hosts: Array.from(cache.keys()) }, 'dns cache');
}
exports.printDnsStats = printDnsStats;
function clearDnsCache() {
    cache.clear();
}
exports.clearDnsCache = clearDnsCache;
//# sourceMappingURL=dns.js.map