Files
overub/core/rate_limiter.py
2025-12-21 17:12:32 +01:00

24 lines
597 B
Python

import time
from dataclasses import dataclass
from typing import Dict, Tuple
@dataclass
class RateLimit:
limit: int
window: int
class RateLimiter:
def __init__(self) -> None:
self._hits: Dict[Tuple[str, int], list[float]] = {}
def check(self, key: str, user_id: int, limit: RateLimit) -> bool:
now = time.time()
bucket = self._hits.setdefault((key, user_id), [])
bucket[:] = [stamp for stamp in bucket if now - stamp < limit.window]
if len(bucket) >= limit.limit:
return False
bucket.append(now)
return True