UNPKG

@barchart/common-js

Version:
147 lines (141 loc) 5.19 kB
var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var RateLimiter_exports = {}; __export(RateLimiter_exports, { default: () => RateLimiter }); module.exports = __toCommonJS(RateLimiter_exports); var assert = __toESM(require("./../lang/assert.js")); var is = __toESM(require("./../lang/is.js")); var promise = __toESM(require("./../lang/promise.js")); var import_Disposable = __toESM(require("./../lang/Disposable.js")); var import_Queue = __toESM(require("./../collections/Queue.js")); var import_Scheduler = __toESM(require("./Scheduler.js")); class RateLimiter extends import_Disposable.default { #windowMaximumCount; #windowDurationMilliseconds; #scheduler; #workQueue; #windowStart; #windowCounter; /** * @param {number} windowMaximumCount - The maximum number of items which can be processed during a timeframe (positive integer). * @param {number} windowDurationMilliseconds - The number of milliseconds in the timeframe (positive integer). */ constructor(windowMaximumCount, windowDurationMilliseconds) { super(); assert.argumentIsValid(windowMaximumCount, "windowMaximumCount", (x) => is.integer(x) && is.positive(x)); assert.argumentIsValid(windowDurationMilliseconds, "windowDurationMilliseconds", (x) => is.integer(x) && is.positive(x)); this.#windowMaximumCount = windowMaximumCount; this.#windowDurationMilliseconds = windowDurationMilliseconds; this.#scheduler = new import_Scheduler.default(); this.#workQueue = new import_Queue.default(); this.#windowStart = null; this.#windowCounter = 0; } /** * Adds an item to the work queue and returns a promise that will * resolve after the item completes execution. * * @public * @param {Function} actionToEnqueue - The action to execute. * @returns {Promise} */ enqueue(actionToEnqueue) { return promise.build((resolveCallback, rejectCallback) => { assert.argumentIsRequired(actionToEnqueue, "actionToEnqueue", Function); if (this.disposed) { throw new Error("Unable to enqueue action, the rate limiter has been disposed."); } this.#workQueue.enqueue(async () => { try { const result = await actionToEnqueue(); resolveCallback(result); } catch (error) { rejectCallback(error); } finally { this.#checkStart(); } }); this.#checkStart(); }); } /** * @protected * @override */ _onDispose() { this.#scheduler.dispose(); this.#workQueue = null; } /** * Returns a string representation. * * @public * @returns {string} */ toString() { return "[RateLimiter]"; } #checkStart() { if (this.disposed) { return; } if (this.#workQueue.empty()) { return; } if (this.#windowStart === null) { const timestamp = /* @__PURE__ */ new Date(); this.#windowStart = timestamp.getTime(); this.#windowCounter = 0; const resetWindow = () => { this.#windowStart = null; this.#windowCounter = 0; this.#checkStart(); }; this.#scheduler.schedule(resetWindow, this.#windowDurationMilliseconds, "Rate Limiter Window Reset"); } if (this.#windowCounter < this.#windowMaximumCount) { this.#windowCounter = this.#windowCounter + 1; const actionToExecute = this.#workQueue.dequeue(); actionToExecute(); } } } { const cjsExports = module.exports; const cjsDefaultExport = cjsExports && cjsExports.__esModule ? cjsExports.default : cjsExports; if (cjsDefaultExport && (typeof cjsDefaultExport === 'function' || typeof cjsDefaultExport === 'object')) { Object.keys(cjsExports).forEach((key) => { if (key !== 'default' && key !== '__esModule') { cjsDefaultExport[key] = cjsExports[key]; } }); } module.exports = cjsDefaultExport; }