Files
romm/backend/utils/rate_limit.py
zurdi d9d65d8b56 refactor(audit): apply the pr-ready simplify pass
- record() takes the request as its actor, and a target can be a
  function: the lookups that name it now run inside the recorder's error
  handling, and for downloads only once the dedupe lets them record.
  That also restores the minimal visibility query on the file route.
- One changed_fields/change pair for rom, user, collection and platform
  edits, one collection helper, AuditActor.anonymous, a shared
  count_in_window and current_device_id, one test helper for recorded
  events and one fixture for audit events.
- The describers share simple/counted/visibility builders and the
  eventData readers with notifications, join lists per locale, and treat
  any *.delete as unlinked.
- EventLog builds one item list with the phase folded in, keeps each
  event's sentence across pages, formats days once, and loads users
  through the users store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 02:45:12 +02:00

40 lines
1.3 KiB
Python

"""Fixed-window, Redis-backed request rate limiting."""
from fastapi import HTTPException, Request, status
from handler.redis_handler import sync_cache
def get_client_ip(request: Request) -> str:
return request.client.host if request.client else "unknown"
def count_in_window(key: str, window_seconds: int) -> int:
"""Count one call against a fixed window and return the window's count so far."""
pipe = sync_cache.pipeline()
pipe.incr(key)
# NX in the same transaction as the INCR: only the call that starts a window
# sets its TTL, and no counter can be left without one.
pipe.expire(key, window_seconds, nx=True)
count, _ = pipe.execute()
return int(count)
def enforce_rate_limit(
key: str, *, max_requests: int, window_seconds: int, detail: str
) -> None:
"""Count one call against a fixed window, raising 429 once the cap is passed.
Args:
key: Redis key the window is counted under, already scoped to whatever
identifies the caller (usually their IP).
max_requests: Calls allowed per window.
window_seconds: Window length.
detail: Message returned with the 429.
"""
if count_in_window(key, window_seconds) > max_requests:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail=detail,
)