22 lines
553 B
Python
Raw Normal View History

from __future__ import annotations
import time
from . import settings
2026-01-02 01:34:18 -03:00
_RATE_BUCKETS: dict[str, dict[str, list[float]]] = {}
2026-01-02 01:34:18 -03:00
def rate_limit_allow(ip: str, *, key: str, limit: int, window_sec: int) -> bool:
if limit <= 0:
return True
now = time.time()
2026-01-02 01:34:18 -03:00
window_start = now - window_sec
buckets_by_ip = _RATE_BUCKETS.setdefault(key, {})
bucket = buckets_by_ip.setdefault(ip, [])
bucket[:] = [t for t in bucket if t >= window_start]
2026-01-02 01:34:18 -03:00
if len(bucket) >= limit:
return False
bucket.append(now)
return True