Spaces:
Running
Running
add configurable api rate limiting
Browse files
api.py
CHANGED
|
@@ -16,7 +16,7 @@ from concurrent.futures import ThreadPoolExecutor
|
|
| 16 |
from datetime import datetime, timezone
|
| 17 |
from typing import Any, Literal
|
| 18 |
|
| 19 |
-
from fastapi import FastAPI, Header, HTTPException
|
| 20 |
from fastapi.middleware.cors import CORSMiddleware
|
| 21 |
from langgraph.types import Command
|
| 22 |
from pydantic import BaseModel, Field
|
|
@@ -33,6 +33,21 @@ app.add_middleware(CORSMiddleware, allow_origins=allowed_origins, allow_methods=
|
|
| 33 |
_jobs: dict[str, dict[str, Any]] = {}
|
| 34 |
_lock = threading.Lock()
|
| 35 |
_executor = ThreadPoolExecutor(max_workers=int(os.getenv("OCR_MAX_WORKERS", "2")))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
|
| 38 |
def _postgres_connect():
|
|
@@ -312,8 +327,9 @@ def health() -> dict[str, Any]:
|
|
| 312 |
|
| 313 |
|
| 314 |
@app.post("/api/reviews", status_code=202)
|
| 315 |
-
def create_review(request: ReviewRequest, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 316 |
_authorize(x_api_key)
|
|
|
|
| 317 |
job_id = str(uuid.uuid4())
|
| 318 |
job = {"id": job_id, "repo": request.repo, "pr_number": request.pr_number, "endpoint": request.endpoint, "status": "queued", "created_at": datetime.now(timezone.utc).isoformat()}
|
| 319 |
with _lock:
|
|
@@ -336,8 +352,9 @@ def get_review(job_id: str, x_api_key: str | None = Header(default=None)) -> dic
|
|
| 336 |
|
| 337 |
|
| 338 |
@app.post("/api/reviews/{job_id}/decision")
|
| 339 |
-
def decide_review(job_id: str, request: DecisionRequest, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 340 |
_authorize(x_api_key)
|
|
|
|
| 341 |
with _lock:
|
| 342 |
job = _jobs.get(job_id)
|
| 343 |
if not job:
|
|
|
|
| 16 |
from datetime import datetime, timezone
|
| 17 |
from typing import Any, Literal
|
| 18 |
|
| 19 |
+
from fastapi import FastAPI, Header, HTTPException, Request
|
| 20 |
from fastapi.middleware.cors import CORSMiddleware
|
| 21 |
from langgraph.types import Command
|
| 22 |
from pydantic import BaseModel, Field
|
|
|
|
| 33 |
_jobs: dict[str, dict[str, Any]] = {}
|
| 34 |
_lock = threading.Lock()
|
| 35 |
_executor = ThreadPoolExecutor(max_workers=int(os.getenv("OCR_MAX_WORKERS", "2")))
|
| 36 |
+
_rate_lock = threading.Lock()
|
| 37 |
+
_rate_windows: dict[str, list[float]] = {}
|
| 38 |
+
|
| 39 |
+
def _rate_limit(request: Request) -> None:
|
| 40 |
+
limit = int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0)
|
| 41 |
+
if limit <= 0:
|
| 42 |
+
return
|
| 43 |
+
now = datetime.now(timezone.utc).timestamp()
|
| 44 |
+
key = request.client.host if request.client else "unknown"
|
| 45 |
+
with _rate_lock:
|
| 46 |
+
window = [stamp for stamp in _rate_windows.get(key, []) if now - stamp < 60]
|
| 47 |
+
if len(window) >= limit:
|
| 48 |
+
raise HTTPException(status_code=429, detail="Rate limit exceeded")
|
| 49 |
+
window.append(now)
|
| 50 |
+
_rate_windows[key] = window
|
| 51 |
|
| 52 |
|
| 53 |
def _postgres_connect():
|
|
|
|
| 327 |
|
| 328 |
|
| 329 |
@app.post("/api/reviews", status_code=202)
|
| 330 |
+
def create_review(request: ReviewRequest, http_request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 331 |
_authorize(x_api_key)
|
| 332 |
+
_rate_limit(http_request)
|
| 333 |
job_id = str(uuid.uuid4())
|
| 334 |
job = {"id": job_id, "repo": request.repo, "pr_number": request.pr_number, "endpoint": request.endpoint, "status": "queued", "created_at": datetime.now(timezone.utc).isoformat()}
|
| 335 |
with _lock:
|
|
|
|
| 352 |
|
| 353 |
|
| 354 |
@app.post("/api/reviews/{job_id}/decision")
|
| 355 |
+
def decide_review(job_id: str, request: DecisionRequest, http_request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
|
| 356 |
_authorize(x_api_key)
|
| 357 |
+
_rate_limit(http_request)
|
| 358 |
with _lock:
|
| 359 |
job = _jobs.get(job_id)
|
| 360 |
if not job:
|