import threading import time from collections import defaultdict from fastapi import HTTPException, Request # Burst rate limiter: max 5 requests per 60 seconds per IP on shared server key _rate_limit_lock = threading.Lock() _request_history = defaultdict(list) def check_burst_rate_limit(request: Request, custom_api_key: str | None = None): """ Ensures users on the shared server key cannot burst more than 5 requests per minute. Users with custom API keys are completely exempt from rate limiting. """ if custom_api_key and custom_api_key.strip(): return client_ip = request.client.host if request.client else "unknown_client" forwarded = request.headers.get("x-forwarded-for") if forwarded: client_ip = forwarded.split(",")[0].strip() now = time.time() window = 60.0 # 1 minute max_requests = 5 with _rate_limit_lock: _request_history[client_ip] = [ ts for ts in _request_history[client_ip] if now - ts < window ] if len(_request_history[client_ip]) >= max_requests: raise HTTPException( status_code=429, detail="Too many AI requests. Please wait a moment (max 5 requests/minute on free server tier), or enter your own free API key in Settings for unlimited requests.", ) _request_history[client_ip].append(now)