Skip to content
Shell
4.9 KB
Raw Blame
/**
 * Rate Limiter
 * Prevents hitting Reddit's rate limits (60 requests per minute)
 */

export interface RateLimiterConfig {
  maxRequests: number;
  windowMs: number;
  retryAfterMs?: number;
}

/**
 * Token bucket rate limiter
 */
export class RateLimiter {
  private tokens: number;
  private maxTokens: number;
  private refillRate: number; // tokens per ms
  private lastRefill: number;
  private retryAfterMs: number;

  constructor(config: RateLimiterConfig) {
    this.maxTokens = config.maxRequests;
    this.tokens = config.maxRequests;
    this.refillRate = config.maxRequests / config.windowMs;
    this.lastRefill = Date.now();
    this.retryAfterMs = config.retryAfterMs || 1000;
  }

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

    this.tokens = Math.min(this.maxTokens, this.tokens + tokensToAdd);
    this.lastRefill = now;
  }

  /**
   * Wait for a token to become available
   */
  async acquire(): Promise<void> {
    this.refill();

    if (this.tokens >= 1) {
      this.tokens -= 1;
      return;
    }

    // Calculate wait time
    const tokensNeeded = 1 - this.tokens;
    const waitMs = Math.ceil(tokensNeeded / this.refillRate);

    await new Promise(resolve => setTimeout(resolve, Math.max(waitMs, this.retryAfterMs)));

    // Try again
    return this.acquire();
  }

  /**
   * Try to acquire without waiting
   */
  tryAcquire(): boolean {
    this.refill();

    if (this.tokens >= 1) {
      this.tokens -= 1;
      return true;
    }

    return false;
  }

  /**
   * Get current token count
   */
  getAvailableTokens(): number {
    this.refill();
    return Math.floor(this.tokens);
  }

  /**
   * Get time until next token is available
   */
  getWaitTime(): number {
    this.refill();

    if (this.tokens >= 1) {
      return 0;
    }

    const tokensNeeded = 1 - this.tokens;
    return Math.ceil(tokensNeeded / this.refillRate);
  }
}

/**
 * Reddit-specific rate limiter
 * 60 requests per minute with burst allowance
 */
export class RedditRateLimiter extends RateLimiter {
  private consecutiveErrors: number = 0;
  private backoffUntil: number = 0;

  constructor() {
    super({
      maxRequests: 60,
      windowMs: 60000, // 1 minute
      retryAfterMs: 1000
    });
  }

  /**
   * Acquire with exponential backoff on errors
   */
  async acquireWithBackoff(): Promise<void> {
    // Check if we're in backoff period
    const now = Date.now();
    if (now < this.backoffUntil) {
      const waitMs = this.backoffUntil - now;
      await new Promise(resolve => setTimeout(resolve, waitMs));
    }

    await this.acquire();
  }

  /**
   * Report a successful request
   */
  reportSuccess(): void {
    this.consecutiveErrors = 0;
  }

  /**
   * Report a rate limit error (429)
   */
  reportRateLimit(): void {
    this.consecutiveErrors++;
    // Exponential backoff: 2^n seconds, max 5 minutes
    const backoffSeconds = Math.min(Math.pow(2, this.consecutiveErrors), 300);
    this.backoffUntil = Date.now() + backoffSeconds * 1000;

    console.warn(`Rate limited. Backing off for ${backoffSeconds}s`);
  }

  /**
   * Report a general error
   */
  reportError(): void {
    this.consecutiveErrors++;
    // Linear backoff for non-rate-limit errors
    const backoffSeconds = Math.min(this.consecutiveErrors * 2, 30);
    this.backoffUntil = Date.now() + backoffSeconds * 1000;
  }

  /**
   * Reset error state
   */
  reset(): void {
    this.consecutiveErrors = 0;
    this.backoffUntil = 0;
  }
}

// Global Reddit rate limiter instance
let redditLimiter: RedditRateLimiter | null = null;

/**
 * Get the global Reddit rate limiter
 */
export function getRedditRateLimiter(): RedditRateLimiter {
  if (!redditLimiter) {
    redditLimiter = new RedditRateLimiter();
  }
  return redditLimiter;
}

/**
 * Throttle function calls
 */
export function throttle<T extends (...args: any[]) => Promise<any>>(
  fn: T,
  limiter: RateLimiter
): T {
  return (async (...args: Parameters<T>) => {
    await limiter.acquire();
    return fn(...args);
  }) as T;
}

/**
 * Retry with exponential backoff
 */
export async function retryWithBackoff<T>(
  fn: () => Promise<T>,
  options: {
    maxRetries?: number;
    initialDelayMs?: number;
    maxDelayMs?: number;
    onRetry?: (error: Error, attempt: number) => void;
  } = {}
): Promise<T> {
  const {
    maxRetries = 3,
    initialDelayMs = 1000,
    maxDelayMs = 30000,
    onRetry
  } = options;

  let lastError: Error;

  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      lastError = error as Error;

      if (attempt < maxRetries) {
        const delay = Math.min(initialDelayMs * Math.pow(2, attempt), maxDelayMs);
        onRetry?.(lastError, attempt + 1);
        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }
  }

  throw lastError!;
}