"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.tryInSequence = exports.withThrottling = exports.pOnce = exports.pOne = exports.pLimitFn = exports.pOrderedResolve = void 0;
const utils_1 = require("@streamr/utils");
const p_limit_1 = __importDefault(require("p-limit"));
const p_throttle_1 = __importDefault(require("p-throttle"));
/**
 * Execute functions in parallel, but ensure they resolve in the order they were executed
 */
function pOrderedResolve(fn) {
    const queue = (0, p_limit_1.default)(1);
    return Object.assign(async (...args) => {
        const d = new utils_1.Defer();
        const done = queue(() => d);
        await Promise.resolve(fn(...args)).then(d.resolve.bind(d), d.reject.bind(d));
        return done;
    }, {
        clear() {
            queue.clearQueue();
        },
    });
}
exports.pOrderedResolve = pOrderedResolve;
/**
 * Returns a function that executes with limited concurrency.
 */
function pLimitFn(fn, limit = 1) {
    const queue = (0, p_limit_1.default)(limit);
    return Object.assign((...args) => queue(() => fn(...args)), {
        clear() {
            queue.clearQueue();
        },
    });
}
exports.pLimitFn = pLimitFn;
/**
 * Only allows one outstanding call.
 * Returns same promise while task is executing.
 */
function pOne(fn) {
    const once = pOnce(fn);
    return async (...args) => {
        try {
            return await once(...args);
        }
        finally {
            once.reset();
        }
    };
}
exports.pOne = pOne;
/**
 * Only allows calling `fn` once.
 * Returns same promise while task is executing.
 */
function pOnce(fn) {
    let currentCall = { status: 'init' };
    return Object.assign(async function pOnceWrap(...args) {
        // eslint-disable-line prefer-arrow-callback
        // capture currentCall so can assign to it, even after reset
        const thisCall = currentCall;
        if (thisCall.status === 'pending') {
            return thisCall.promise;
        }
        if (thisCall.status === 'fulfilled') {
            return thisCall.value;
        }
        if (thisCall.status === 'rejected') {
            throw thisCall.reason;
        }
        // status === 'init'
        currentCall = thisCall;
        const promise = (async () => {
            // capture value/error
            try {
                const value = await fn(...args);
                Object.assign(thisCall, {
                    promise: undefined, // release promise
                    status: 'fulfilled',
                    value,
                });
                return value;
            }
            catch (reason) {
                Object.assign(thisCall, {
                    promise: undefined, // release promise
                    status: 'rejected',
                    reason,
                });
                throw reason;
            }
        })();
        promise.catch(() => { }); // prevent unhandled
        Object.assign(thisCall, {
            status: 'pending',
            promise,
        });
        return promise;
    }, {
        isStarted() {
            return currentCall.status !== 'init';
        },
        reset() {
            currentCall = { status: 'init' };
        },
    });
}
exports.pOnce = pOnce;
const withThrottling = (fn, maxInvocationsPerSecond) => {
    const throttler = (0, p_throttle_1.default)({
        limit: maxInvocationsPerSecond,
        interval: 1000,
    });
    return throttler(fn);
};
exports.withThrottling = withThrottling;
const tryInSequence = async (fns) => {
    if (fns.length === 0) {
        throw new Error('no tasks');
    }
    let firstError;
    for (const fn of fns) {
        try {
            const promise = fn();
            return await promise;
        }
        catch (e) {
            if (firstError === undefined) {
                firstError = e;
            }
        }
    }
    throw firstError;
};
exports.tryInSequence = tryInSequence;
//# sourceMappingURL=promises.js.map