UNPKG

@pixellot/pxlt-rabbit-handler

Version:

A generic class that handles RabbitMQ connection, consume and produce functionality.

67 lines (59 loc) 2.13 kB
/** * Exponential backoff timeout mechanism: exponentially decrease the rate of a process, until max interval is reached * @param {Number} retryCount: number of times a retry has been performed, used as the power of the base-2 exponent * @param {Number} factor: multiplication factor of the base-2 exponent * @param {Number} maxBackoffIntervalMs: the maximum interval duration between retries (in ms) * @returns {Number} - timeout in milliseconds */ function exponentialBackoff(retryCount, factor, maxBackoffIntervalMs) { const exponentialBackoffTime = factor * 2 ** retryCount; return (exponentialBackoffTime < maxBackoffIntervalMs && exponentialBackoffTime) || maxBackoffIntervalMs; } /** * Wrapper function that accepts a function and returns a function that is ensured to execute only once, an exception is thrown if same func is called more than once * @param {function} func - function to wrap * @param {Object} context - the context where the returned function is applied to * @return {function(): *} */ function runOnce(func, context) { let result = null; const funcName = func.name; return function run() { if (func) { result = func.apply(context || this, arguments); func = null; } else { throw `${funcName} already called`; } return result; }; } /** * Creates a promise that rejects in <ms> milliseconds * @param {number} ms - timeout value in ms * @param {Promise} promise * @return {Promise} */ function promiseTimeout(ms, promise) { const timeout = new Promise((resolve, reject) => { const id = setTimeout(() => { clearTimeout(id); reject(`Timed out in ${ms} ms.`); }, ms); }); // Returns a race between our timeout and the passed in promise return Promise.race([ promise, timeout ]); } function sleep(ms) { // eslint-disable-next-line no-promise-executor-return return new Promise((resolve) => setTimeout(resolve, ms)); } module.exports = { exponentialBackoff, runOnce, promiseTimeout, sleep };