From e075908a15b28ba0b74a39beba795b69d65c8cfe Mon Sep 17 00:00:00 2001 From: johndoe6345789 Date: Sun, 18 Jan 2026 18:15:25 +0000 Subject: [PATCH] Refactor rate limiter retry loop --- src/lib/rate-limiter.ts | 43 +++++++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/src/lib/rate-limiter.ts b/src/lib/rate-limiter.ts index cd54531..3f17ebe 100644 --- a/src/lib/rate-limiter.ts +++ b/src/lib/rate-limiter.ts @@ -26,30 +26,39 @@ class RateLimiter { fn: () => Promise, priority: 'low' | 'medium' | 'high' = 'medium' ): Promise { - const now = Date.now() - const record = this.requests.get(key) + const maxHighPriorityRetries = 5 + let retryCount = 0 + let record: RequestRecord | undefined - if (record) { - const timeElapsed = now - record.timestamp + while (true) { + const now = Date.now() + record = this.requests.get(key) - if (timeElapsed < this.config.windowMs) { - if (record.count >= this.config.maxRequests) { - console.warn(`Rate limit exceeded for ${key}. Try again in ${Math.ceil((this.config.windowMs - timeElapsed) / 1000)}s`) - - if (priority === 'high') { - await new Promise(resolve => setTimeout(resolve, this.config.retryDelay)) - return this.throttle(key, fn, priority) + if (record) { + const timeElapsed = now - record.timestamp + + if (timeElapsed < this.config.windowMs) { + if (record.count >= this.config.maxRequests) { + console.warn(`Rate limit exceeded for ${key}. Try again in ${Math.ceil((this.config.windowMs - timeElapsed) / 1000)}s`) + + if (priority === 'high' && retryCount < maxHighPriorityRetries) { + retryCount++ + await new Promise(resolve => setTimeout(resolve, this.config.retryDelay)) + continue + } + + return null } - - return null + + record.count++ + } else { + this.requests.set(key, { timestamp: now, count: 1 }) } - - record.count++ } else { this.requests.set(key, { timestamp: now, count: 1 }) } - } else { - this.requests.set(key, { timestamp: now, count: 1 }) + + break } this.cleanup()