"""Rate-limit in-proces cu fereastra glisanta. US-009 PRD 3.3 C5. Fara dependinta externa. Folosit de POST /signup (US-003) cu cheia = IP client. Configurabil prin AUTOPASS_signup_rate_max / AUTOPASS_signup_rate_window_s (config.py). """ from __future__ import annotations import time from collections import defaultdict # ip/key -> lista de timestamps (time.monotonic) ale cererilor din fereastra activa _hits: dict[str, list[float]] = defaultdict(list) def check_rate_limit(key: str, max_hits: int, window_s: int) -> bool: """Fereastra glisanta: returneaza True daca cererea e permisa, False la depasire. Curata timestamp-urile expirate la fiecare apel (O(n) per cheie, acceptabil pentru trafic de signup). Thread-safety: GIL Python protejeaza list ops simple; suficient pentru un singur proces uvicorn. """ now = time.monotonic() cutoff = now - window_s timestamps = _hits[key] # Sterge intrari expirate _hits[key] = [t for t in timestamps if t > cutoff] if len(_hits[key]) >= max_hits: return False _hits[key].append(now) return True