File size: 1,387 Bytes
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)