-
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
"""Minimal in-memory sliding-window rate limiter.
|
||||
|
||||
Good enough for a single-process development server. A multi-process deployment
|
||||
would need a shared store (e.g. Redis) instead.
|
||||
"""
|
||||
|
||||
import time
|
||||
from collections import defaultdict, deque
|
||||
|
||||
from fastapi import HTTPException, Request, status
|
||||
|
||||
_registry: list["RateLimiter"] = []
|
||||
|
||||
|
||||
class RateLimiter:
|
||||
def __init__(self, name: str, limit_per_minute: int, window_seconds: float = 60.0):
|
||||
self.name = name
|
||||
self.limit = limit_per_minute
|
||||
self.window = window_seconds
|
||||
self._hits: dict[str, deque[float]] = defaultdict(deque)
|
||||
_registry.append(self)
|
||||
|
||||
async def __call__(self, request: Request) -> None:
|
||||
if self.limit <= 0:
|
||||
return
|
||||
key = request.client.host if request.client else "unknown"
|
||||
now = time.monotonic()
|
||||
hits = self._hits[key]
|
||||
while hits and now - hits[0] > self.window:
|
||||
hits.popleft()
|
||||
if len(hits) >= self.limit:
|
||||
retry_after = max(1, int(self.window - (now - hits[0])))
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="Too many requests. Please try again shortly.",
|
||||
headers={"Retry-After": str(retry_after)},
|
||||
)
|
||||
hits.append(now)
|
||||
|
||||
def reset(self) -> None:
|
||||
self._hits.clear()
|
||||
|
||||
|
||||
def reset_all_limiters() -> None:
|
||||
for limiter in _registry:
|
||||
limiter.reset()
|
||||
Reference in New Issue
Block a user