"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getStatWorker = getStatWorker;
const node_worker_threads_1 = require("node:worker_threads");
const node_fs_1 = require("node:fs");
const cross_1 = require("./cross");
const first_1 = require("./first");
// all stat requests for the same worker are serialized, potentially introducing extra latency
const pool = new Map();
function getStatWorker(key) {
    if (first_1.quitting)
        return () => Promise.reject('quitting');
    const existing = pool.get(key);
    if (existing)
        return existing;
    const worker = new node_worker_threads_1.Worker(__dirname + '/statWorker.js');
    worker.unref();
    const requests = new Map();
    worker.on('message', (msg) => {
        const k = msg.path;
        requests.get(k)?.resolve(msg.error ? Promise.reject(Error(msg.error))
            : Object.setPrototypeOf(msg.result, node_fs_1.Stats.prototype));
        requests.delete(k);
    });
    worker.on('error', (err) => {
        for (const p of requests.values())
            p.reject(err);
        requests.clear();
        worker.terminate().catch(() => { });
        pool.delete(key);
    });
    pool.set(key, query);
    return query;
    function query(path) {
        const was = requests.get(path);
        if (was)
            return was;
        const ret = (0, cross_1.pendingPromise)();
        requests.set(path, ret);
        worker.postMessage(path);
        return ret;
    }
}
