All files / src/resilience rate-limiter.ts

0% Statements 0/420
0% Branches 0/1
0% Functions 0/1
0% Lines 0/420

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
/**
 * Rate Limiter
 *
 * Production-ready rate limiting implementations.
 *
 * @module v3/shared/resilience/rate-limiter
 */

/**
 * Rate limiter options
 */
export interface RateLimiterOptions {
  /** Maximum requests allowed in the window */
  maxRequests: number;

  /** Time window in milliseconds */
  windowMs: number;

  /** Enable sliding window (vs fixed window) */
  slidingWindow?: boolean;

  /** Key generator for per-key limiting */
  keyGenerator?: (context: unknown) => string;

  /** Skip limiter for certain requests */
  skip?: (context: unknown) => boolean;

  /** Handler when rate limit is exceeded */
  onRateLimited?: (key: string, remaining: number, resetAt: Date) => void;
}

/**
 * Rate limit result
 */
export interface RateLimitResult {
  allowed: boolean;
  remaining: number;
  resetAt: Date;
  retryAfter: number; // ms until reset
  total: number;
  used: number;
}

/**
 * Base Rate Limiter interface
 */
export interface RateLimiter {
  /** Check if request is allowed */
  check(key?: string): RateLimitResult;

  /** Consume a request token */
  consume(key?: string): RateLimitResult;

  /** Reset a specific key or all keys */
  reset(key?: string): void;

  /** Get current status */
  status(key?: string): RateLimitResult;
}

/**
 * Request entry for tracking
 */
interface RequestEntry {
  timestamp: number;
  key: string;
}

/**
 * Sliding Window Rate Limiter
 *
 * Uses sliding window algorithm for smooth rate limiting.
 *
 * @example
 * const limiter = new SlidingWindowRateLimiter({
 *   maxRequests: 100,
 *   windowMs: 60000, // 100 requests per minute
 * });
 *
 * const result = limiter.consume('user-123');
 * if (!result.allowed) {
 *   throw new Error(`Rate limited. Retry in ${result.retryAfter}ms`);
 * }
 */
export class SlidingWindowRateLimiter implements RateLimiter {
  private readonly options: RateLimiterOptions;
  private readonly requests: Map<string, RequestEntry[]> = new Map();
  private cleanupInterval?: ReturnType<typeof setInterval>;

  constructor(options: RateLimiterOptions) {
    this.options = {
      slidingWindow: true,
      ...options,
    };

    // Periodic cleanup of old entries
    this.cleanupInterval = setInterval(() => {
      this.cleanup();
    }, this.options.windowMs);
  }

  /**
   * Check if a request would be allowed without consuming
   */
  check(key: string = 'default'): RateLimitResult {
    this.cleanupKey(key);
    const entries = this.requests.get(key) || [];

    return {
      allowed: entries.length < this.options.maxRequests,
      remaining: Math.max(0, this.options.maxRequests - entries.length),
      resetAt: this.getResetTime(entries),
      retryAfter: this.getRetryAfter(entries),
      total: this.options.maxRequests,
      used: entries.length,
    };
  }

  /**
   * Consume a request token
   */
  consume(key: string = 'default'): RateLimitResult {
    // Clean old entries first
    this.cleanupKey(key);

    let entries = this.requests.get(key);
    if (!entries) {
      entries = [];
      this.requests.set(key, entries);
    }

    // Check if allowed
    if (entries.length >= this.options.maxRequests) {
      const result: RateLimitResult = {
        allowed: false,
        remaining: 0,
        resetAt: this.getResetTime(entries),
        retryAfter: this.getRetryAfter(entries),
        total: this.options.maxRequests,
        used: entries.length,
      };

      this.options.onRateLimited?.(key, 0, result.resetAt);
      return result;
    }

    // Add new entry
    entries.push({ timestamp: Date.now(), key });

    return {
      allowed: true,
      remaining: this.options.maxRequests - entries.length,
      resetAt: this.getResetTime(entries),
      retryAfter: 0,
      total: this.options.maxRequests,
      used: entries.length,
    };
  }

  /**
   * Reset rate limit for a key
   */
  reset(key?: string): void {
    if (key) {
      this.requests.delete(key);
    } else {
      this.requests.clear();
    }
  }

  /**
   * Get current status
   */
  status(key: string = 'default'): RateLimitResult {
    return this.check(key);
  }

  /**
   * Cleanup resources
   */
  destroy(): void {
    if (this.cleanupInterval) {
      clearInterval(this.cleanupInterval);
      this.cleanupInterval = undefined;
    }
    this.requests.clear();
  }

  /**
   * Clean old entries for a specific key
   */
  private cleanupKey(key: string): void {
    const entries = this.requests.get(key);
    if (!entries) return;

    const cutoff = Date.now() - this.options.windowMs;
    const filtered = entries.filter((e) => e.timestamp >= cutoff);

    if (filtered.length === 0) {
      this.requests.delete(key);
    } else if (filtered.length !== entries.length) {
      this.requests.set(key, filtered);
    }
  }

  /**
   * Clean all old entries
   */
  private cleanup(): void {
    for (const key of this.requests.keys()) {
      this.cleanupKey(key);
    }
  }

  /**
   * Get reset time based on oldest entry
   */
  private getResetTime(entries: RequestEntry[]): Date {
    if (entries.length === 0) {
      return new Date(Date.now() + this.options.windowMs);
    }

    const oldest = entries[0]!;
    return new Date(oldest.timestamp + this.options.windowMs);
  }

  /**
   * Get retry after time in ms
   */
  private getRetryAfter(entries: RequestEntry[]): number {
    if (entries.length < this.options.maxRequests) {
      return 0;
    }

    const oldest = entries[0]!;
    const resetAt = oldest.timestamp + this.options.windowMs;
    return Math.max(0, resetAt - Date.now());
  }
}

/**
 * Token Bucket Rate Limiter
 *
 * Uses token bucket algorithm for burst-friendly rate limiting.
 *
 * @example
 * const limiter = new TokenBucketRateLimiter({
 *   maxRequests: 10, // bucket size
 *   windowMs: 1000,  // refill interval
 * });
 */
export class TokenBucketRateLimiter implements RateLimiter {
  private readonly options: RateLimiterOptions;
  private readonly buckets: Map<string, { tokens: number; lastRefill: number }> = new Map();
  private cleanupInterval?: ReturnType<typeof setInterval>;

  constructor(options: RateLimiterOptions) {
    this.options = options;

    // Periodic cleanup
    this.cleanupInterval = setInterval(() => {
      this.cleanup();
    }, this.options.windowMs * 10);
  }

  /**
   * Check if a request would be allowed
   */
  check(key: string = 'default'): RateLimitResult {
    this.refill(key);
    const bucket = this.getBucket(key);

    return {
      allowed: bucket.tokens >= 1,
      remaining: Math.floor(bucket.tokens),
      resetAt: new Date(bucket.lastRefill + this.options.windowMs),
      retryAfter: bucket.tokens >= 1 ? 0 : this.options.windowMs,
      total: this.options.maxRequests,
      used: this.options.maxRequests - Math.floor(bucket.tokens),
    };
  }

  /**
   * Consume a token
   */
  consume(key: string = 'default'): RateLimitResult {
    this.refill(key);
    const bucket = this.getBucket(key);

    if (bucket.tokens < 1) {
      const result: RateLimitResult = {
        allowed: false,
        remaining: 0,
        resetAt: new Date(bucket.lastRefill + this.options.windowMs),
        retryAfter: this.options.windowMs,
        total: this.options.maxRequests,
        used: this.options.maxRequests,
      };

      this.options.onRateLimited?.(key, 0, result.resetAt);
      return result;
    }

    bucket.tokens -= 1;

    return {
      allowed: true,
      remaining: Math.floor(bucket.tokens),
      resetAt: new Date(bucket.lastRefill + this.options.windowMs),
      retryAfter: 0,
      total: this.options.maxRequests,
      used: this.options.maxRequests - Math.floor(bucket.tokens),
    };
  }

  /**
   * Reset bucket for a key
   */
  reset(key?: string): void {
    if (key) {
      this.buckets.delete(key);
    } else {
      this.buckets.clear();
    }
  }

  /**
   * Get current status
   */
  status(key: string = 'default'): RateLimitResult {
    return this.check(key);
  }

  /**
   * Cleanup resources
   */
  destroy(): void {
    if (this.cleanupInterval) {
      clearInterval(this.cleanupInterval);
      this.cleanupInterval = undefined;
    }
    this.buckets.clear();
  }

  /**
   * Get or create bucket for key
   */
  private getBucket(key: string): { tokens: number; lastRefill: number } {
    let bucket = this.buckets.get(key);
    if (!bucket) {
      bucket = { tokens: this.options.maxRequests, lastRefill: Date.now() };
      this.buckets.set(key, bucket);
    }
    return bucket;
  }

  /**
   * Refill tokens based on elapsed time
   */
  private refill(key: string): void {
    const bucket = this.getBucket(key);
    const now = Date.now();
    const elapsed = now - bucket.lastRefill;

    if (elapsed >= this.options.windowMs) {
      // Full refill after window
      const intervals = Math.floor(elapsed / this.options.windowMs);
      bucket.tokens = Math.min(
        this.options.maxRequests,
        bucket.tokens + intervals * this.options.maxRequests
      );
      bucket.lastRefill = now;
    }
  }

  /**
   * Clean inactive buckets
   */
  private cleanup(): void {
    const cutoff = Date.now() - this.options.windowMs * 10;

    for (const [key, bucket] of this.buckets) {
      if (bucket.lastRefill < cutoff && bucket.tokens >= this.options.maxRequests) {
        this.buckets.delete(key);
      }
    }
  }
}

/**
 * Rate limiter middleware for Express-like frameworks
 */
export function createRateLimiterMiddleware(limiter: RateLimiter) {
  return (req: { ip?: string; headers?: Record<string, string> }, res: {
    status: (code: number) => { json: (body: unknown) => void };
    setHeader: (name: string, value: string) => void;
  }, next: () => void): void => {
    // Get key from IP or header
    const key = req.ip || req.headers?.['x-forwarded-for'] || 'anonymous';

    const result = limiter.consume(key);

    // Set rate limit headers
    res.setHeader('X-RateLimit-Limit', String(result.total));
    res.setHeader('X-RateLimit-Remaining', String(result.remaining));
    res.setHeader('X-RateLimit-Reset', String(Math.ceil(result.resetAt.getTime() / 1000)));

    if (!result.allowed) {
      res.setHeader('Retry-After', String(Math.ceil(result.retryAfter / 1000)));
      res.status(429).json({
        error: 'Too Many Requests',
        retryAfter: result.retryAfter,
        resetAt: result.resetAt.toISOString(),
      });
      return;
    }

    next();
  };
}