Commit ·
7c4bccf
1
Parent(s): fea83e5
chore: remove rate limit middleware
Browse files- api/main.py +0 -37
api/main.py
CHANGED
|
@@ -114,43 +114,6 @@ app.add_middleware(
|
|
| 114 |
allow_headers=["*"],
|
| 115 |
)
|
| 116 |
|
| 117 |
-
# ── Lightweight in-process rate limiting (per client IP, /api/* only) ──
|
| 118 |
-
# Baseline abuse protection. For multi-instance deploys move this to Redis.
|
| 119 |
-
# Tune with RATE_LIMIT_PER_MIN (default 120 req/min/IP).
|
| 120 |
-
import time as _time
|
| 121 |
-
from collections import defaultdict, deque
|
| 122 |
-
from fastapi import Request
|
| 123 |
-
from fastapi.responses import JSONResponse
|
| 124 |
-
|
| 125 |
-
_RATE_LIMIT = int(os.environ.get("RATE_LIMIT_PER_MIN", "120"))
|
| 126 |
-
_RATE_WINDOW = 60.0
|
| 127 |
-
_rate_hits = defaultdict(deque)
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
def _client_ip(request: Request) -> str:
|
| 131 |
-
# Behind Cloudflare/Render the socket peer is the proxy, so the real client
|
| 132 |
-
# IP is in these headers. Without this, every user shares one rate-limit
|
| 133 |
-
# bucket (collective throttling) and the limit is effectively useless.
|
| 134 |
-
fwd = request.headers.get("cf-connecting-ip") or request.headers.get("x-forwarded-for")
|
| 135 |
-
if fwd:
|
| 136 |
-
return fwd.split(",")[0].strip()
|
| 137 |
-
return request.client.host if request.client else "unknown"
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
@app.middleware("http")
|
| 141 |
-
async def _rate_limit(request: Request, call_next):
|
| 142 |
-
path = request.url.path
|
| 143 |
-
if path == "/api/health" or not path.startswith("/api/"):
|
| 144 |
-
return await call_next(request)
|
| 145 |
-
ip = _client_ip(request)
|
| 146 |
-
now = _time.time()
|
| 147 |
-
dq = _rate_hits[ip]
|
| 148 |
-
while dq and dq[0] < now - _RATE_WINDOW:
|
| 149 |
-
dq.popleft()
|
| 150 |
-
if len(dq) >= _RATE_LIMIT:
|
| 151 |
-
return JSONResponse(status_code=429, content={"detail": "Too many requests. Please slow down."})
|
| 152 |
-
dq.append(now)
|
| 153 |
-
return await call_next(request)
|
| 154 |
|
| 155 |
|
| 156 |
# Include API Routers
|
|
|
|
| 114 |
allow_headers=["*"],
|
| 115 |
)
|
| 116 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
|
| 119 |
# Include API Routers
|