UNPKG

@hisorange/resistor

Version:

Versatily resource load throttler with extensible strategies, configuration and virtual thread management.

42 lines 1.61 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RateLimiterStrategy = void 0; /** * Restricts the executions count in the given interval to respect a rate limiter. */ class RateLimiterStrategy { constructor(config) { this.threadActivity = new Map(); this.config = { interval: 1000, occurrence: 1, }; this.config = { ...this.config, ...config }; } async handleWaitPass(threadId, waitPass) { var _a; const now = Date.now(); const activity = (_a = this.threadActivity.get(threadId)) !== null && _a !== void 0 ? _a : []; const inInterval = activity.filter(activityAt => now - activityAt < this.config.interval); if (inInterval.length >= this.config.occurrence) { await new Promise(wait => { var _a; return setTimeout(wait, this.config.interval - (now - ((_a = inInterval.shift()) !== null && _a !== void 0 ? _a : 0))); }); } // Use the filtered activities to reduce the activity tracker. this.threadActivity.set(threadId, inInterval); waitPass(); } threadFinished(threadId, activityAt) { var _a; if (!this.threadActivity.has(threadId)) { this.threadActivity.set(threadId, [activityAt]); } else { (_a = this.threadActivity.get(threadId)) === null || _a === void 0 ? void 0 : _a.push(activityAt); } } } exports.RateLimiterStrategy = RateLimiterStrategy; //# sourceMappingURL=rate-limiter.strategy.js.map