|
| 1 | +/** |
| 2 | + * Rate Limiter Implementation |
| 3 | + * |
| 4 | + * Implements a sliding window rate limiter to control request rates |
| 5 | + */ |
| 6 | + |
| 7 | +export interface RateLimiterOptions { |
| 8 | + /** Maximum number of requests allowed in the time window */ |
| 9 | + maxRequests: number |
| 10 | + /** Time window in milliseconds */ |
| 11 | + windowMs: number |
| 12 | + /** Optional key generator function for identifying clients */ |
| 13 | + keyGenerator?: (identifier: string) => string |
| 14 | +} |
| 15 | + |
| 16 | +interface RateLimitRecord { |
| 17 | + timestamps: number[] |
| 18 | +} |
| 19 | + |
| 20 | +export class RateLimiter { |
| 21 | + private records: Map<string, RateLimitRecord> = new Map() |
| 22 | + private options: Required<RateLimiterOptions> |
| 23 | + private cleanupInterval: NodeJS.Timeout | null = null |
| 24 | + |
| 25 | + constructor (options: RateLimiterOptions) { |
| 26 | + this.options = { |
| 27 | + maxRequests: options.maxRequests, |
| 28 | + windowMs: options.windowMs, |
| 29 | + keyGenerator: options.keyGenerator ?? ((id: string) => id), |
| 30 | + } |
| 31 | + |
| 32 | + // Clean up old records every minute to prevent memory leaks |
| 33 | + this.cleanupInterval = setInterval(() => { |
| 34 | + this.cleanup() |
| 35 | + }, 60_000) |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Check if a request should be allowed |
| 40 | + * @param identifier - Client identifier (e.g., IP address, session ID) |
| 41 | + * @returns Object with allowed status and retry information |
| 42 | + */ |
| 43 | + check (identifier: string): { |
| 44 | + allowed: boolean |
| 45 | + remaining: number |
| 46 | + resetTime: number |
| 47 | + retryAfter?: number |
| 48 | + } { |
| 49 | + const key = this.options.keyGenerator(identifier) |
| 50 | + const now = Date.now() |
| 51 | + const windowStart = now - this.options.windowMs |
| 52 | + |
| 53 | + let record = this.records.get(key) |
| 54 | + if (!record) { |
| 55 | + record = { timestamps: [] } |
| 56 | + this.records.set(key, record) |
| 57 | + } |
| 58 | + |
| 59 | + // Remove timestamps outside the current window |
| 60 | + record.timestamps = record.timestamps.filter(ts => ts > windowStart) |
| 61 | + |
| 62 | + // Check if limit is exceeded |
| 63 | + const allowed = record.timestamps.length < this.options.maxRequests |
| 64 | + const remaining = Math.max(0, this.options.maxRequests - record.timestamps.length) |
| 65 | + |
| 66 | + // Calculate reset time (when the oldest request will fall outside the window) |
| 67 | + const resetTime = record.timestamps.length > 0 |
| 68 | + ? record.timestamps[0] + this.options.windowMs |
| 69 | + : now + this.options.windowMs |
| 70 | + |
| 71 | + let retryAfter: number | undefined |
| 72 | + if (!allowed && record.timestamps.length > 0) { |
| 73 | + // Calculate how long to wait until the oldest request expires |
| 74 | + retryAfter = Math.ceil((record.timestamps[0] + this.options.windowMs - now) / 1000) |
| 75 | + } |
| 76 | + |
| 77 | + // If allowed, record this request |
| 78 | + if (allowed) { |
| 79 | + record.timestamps.push(now) |
| 80 | + } |
| 81 | + |
| 82 | + return { |
| 83 | + allowed, |
| 84 | + remaining: allowed ? remaining - 1 : remaining, |
| 85 | + resetTime, |
| 86 | + retryAfter, |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + /** |
| 91 | + * Reset rate limit for a specific identifier |
| 92 | + */ |
| 93 | + reset (identifier: string): void { |
| 94 | + const key = this.options.keyGenerator(identifier) |
| 95 | + this.records.delete(key) |
| 96 | + } |
| 97 | + |
| 98 | + /** |
| 99 | + * Clear all rate limit records |
| 100 | + */ |
| 101 | + clear (): void { |
| 102 | + this.records.clear() |
| 103 | + } |
| 104 | + |
| 105 | + destroy (): void { |
| 106 | + if (this.cleanupInterval) { |
| 107 | + clearInterval(this.cleanupInterval) |
| 108 | + this.cleanupInterval = null |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + /** |
| 113 | + * Clean up expired records |
| 114 | + */ |
| 115 | + private cleanup (): void { |
| 116 | + const now = Date.now() |
| 117 | + const windowStart = now - this.options.windowMs |
| 118 | + |
| 119 | + for (const [key, record] of this.records.entries()) { |
| 120 | + // Remove timestamps outside the current window |
| 121 | + record.timestamps = record.timestamps.filter(ts => ts > windowStart) |
| 122 | + |
| 123 | + // Remove the record entirely if it has no timestamps |
| 124 | + if (record.timestamps.length === 0) { |
| 125 | + this.records.delete(key) |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | +} |
0 commit comments