"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const pool_1 = __importDefault(require("@cocalc/database/pool"));
const logger_1 = require("@cocalc/backend/logger");
const lru_cache_1 = __importDefault(require("lru-cache"));
const logger = (0, logger_1.getLogger)("get-vhost-info");
// This could get called a LOT on the same host that is not special
// for the server, and also the list of public projects that have
// vhost info is very small (e.g., like 10 of them) and at least
// right now only something that is manually changed!  We thus cache
// the answer for 1 minute.  If we change our use of vhosts, we can
// revisit this parameter.
const cache = new lru_cache_1.default({
    maxAge: 1000 * 60,
});
async function getVirtualHostInfo(vhost) {
    if (cache.has(vhost)) {
        //logger.debug("using cache");
        return cache.get(vhost);
    }
    // long: once a vhost is set, it's unlikely to change for a while, since it literally
    // requires updating DNS entries to have any impact.
    const pool = (0, pool_1.default)("long");
    // Get the database entry that describes the public path with given vhost.
    // NOTE: we are assuming there is at most one with a given vhost.  If there
    // are more, behavior is not defined, but that will get logged.
    // As an optimization, we also check if vhost is null, to quickly remove the majority of entries (gives a 1000x speedup in prod).
    const query = `SELECT project_id, path, auth, cross_origin_isolation
    FROM public_paths
    WHERE disabled IS NOT TRUE
      AND vhost IS NOT NULL
      AND $1::TEXT=ANY(string_to_array(vhost,','))`;
    // logger.debug('query = ', query);
    try {
        const { rows } = await pool.query(query, [vhost]);
        if (rows.length == 0 ||
            rows[0].project_id == null ||
            rows[0].path == null) {
            // logger.debug("no valid virtual vhost=%s", vhost);
            cache.set(vhost, null);
            return null;
        }
        if (rows.length > 1) {
            logger.warn("WARNING: multiple virtual host entries for vhost=%s", vhost);
        }
        const { project_id, path, auth, cross_origin_isolation } = rows[0]; // is a weird data type, which is why we don't just return it.
        const r = { project_id, path, auth, cross_origin_isolation };
        cache.set(vhost, r);
        return r;
    }
    catch (err) {
        logger.error(`error querying for vhost ${vhost}`, err);
        return null;
    }
}
exports.default = getVirtualHostInfo;
//# sourceMappingURL=get-vhost-info.js.map