"""A small in-memory rate limit for the public endpoints (CL-4, plan phase 3S S.4). hit(bucket, key, limit, per_seconds) -> bool True = allowed (and counted) client_ip(request) the caller's address behind the proxy Per process (the cloud runs one); a restart forgets. Enough to stop a script hammering the order endpoint; not a defence against a distributed attack (that's the proxy's job). """ from __future__ import annotations import threading import time from collections import deque _lock = threading.Lock() _hits: dict[tuple[str, str], deque] = {} _MAX_KEYS = 50_000 def hit(bucket: str, key: str, limit: int, per_seconds: float, now: float | None = None) -> bool: now = time.monotonic() if now is None else now with _lock: if len(_hits) > _MAX_KEYS: # never grow without bound _hits.clear() q = _hits.setdefault((bucket, key), deque()) while q and now - q[0] >= per_seconds: q.popleft() if len(q) >= limit: return False q.append(now) return True def reset() -> None: with _lock: _hits.clear() def client_ip(request) -> str: """The first X-Forwarded-For address (the VPS proxy sets it), else the socket's.""" fwd = request.headers.get("x-forwarded-for", "") if fwd: return fwd.split(",")[0].strip() or "?" return getattr(request.client, "host", None) or "?"