Files
romm/backend/utils/rate_limiter.py
Georges-Antoine Assi 0183cae8ad fix(retroachievements): ride out rate limits during the progress sync (#5532)
* fix(retroachievements): ride out rate limits during the progress sync

The progress sync asks RetroAchievements for each changed game's
achievements, one request per game. A single 429 that outlasted the one
2s retry became a 503 that aborted the whole sync and discarded every
game already read, so a large first sync never completed.

- send_with_retries honours Retry-After (capped at 60s) and doubles its
  backoff on each 429; rate limits can get their own attempt budget so
  timeouts are not retried more often.
- RetroAchievements gets five attempts against a 429.
- get_user_progression stops asking for game details once RA refuses
  one, keeps the stored entry for the remaining changed games, and
  returns what it read so it is saved and the next sync resumes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(retroachievements): keep stored progress on full refreshes and read pages first

Addresses Greptile review on #5532:
- a full refresh now passes the stored progression with refresh_all, so
  a refusal keeps the games it could not read instead of dropping them
- every completion page is read before any detail request, so a
  throttled later page fails before details are fetched and discarded
- docstrings trimmed to the comment rules

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(retroachievements): apply code-review fixes

pr-ready step 2 (code-review xhigh --fix): drop the synced progression
when the RA username changes, keep the award kind current on refused
games, read HTTP-date Retry-After values, and honour an explicit zero
rate_limit_attempts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(retroachievements): apply simplify cleanups

pr-ready step 3 (simplify): reuse to_utc for HTTP-date Retry-After,
fold the None checks into _retry_after_seconds, drop the result=None
seed and the award-kind compare in get_user_progression, and share the
refusal setup and call() asserts across the new tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(retroachievements): review-polish comment trim

pr-ready step 4 (review-polish): drop a comment that restated the code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(retroachievements): run the sync as a job and tell rejects from outages

- A non-429 error status or unreadable reply for one game keeps that
  game's stored progress and the sync moves on; only a throttle or an
  outage defers the remaining games.
- The five-attempt 429 budget applies to the progress sync's two
  requests, not every RetroAchievements call.
- A 429 holds the shared RA rate limiter through its wait and halves its
  pace, which steps back up as requests go through.
- Timeouts and 429s each count against their own attempt budget, and
  the 429 backoff doubles per 429.
- /ra/refresh queues the sync as a background job and answers 202; the
  job reports its outcome over the ra:synced socket event, which the
  settings section uses to reload the user or show the failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 07:56:45 -05:00

126 lines
4.4 KiB
Python

import asyncio
from collections import deque
class RateLimiter:
"""Pre-emptive async rate limiter.
Spaces grants so callers stay at or below ``requests_per_second``. Concurrent
callers each reserve the next slot before awaiting, so they are evenly spaced
instead of being released in a burst.
"""
def __init__(self, requests_per_second: float) -> None:
if requests_per_second <= 0:
raise ValueError("requests_per_second must be positive")
self._min_interval = 1.0 / requests_per_second
self._next_slot = 0.0
@property
def requests_per_second(self) -> float:
return 1.0 / self._min_interval
def set_requests_per_second(self, requests_per_second: float) -> None:
"""Re-pace the limiter, for APIs that report their own per-account rate.
Slots already reserved keep their time; only later ones use the new
spacing.
"""
if requests_per_second <= 0:
raise ValueError("requests_per_second must be positive")
self._min_interval = 1.0 / requests_per_second
def hold(self, seconds: float) -> None:
"""Grant no new slot for `seconds`; slots already reserved keep their time."""
resume = asyncio.get_running_loop().time() + seconds
self._next_slot = max(self._next_slot, resume)
async def acquire(self) -> None:
# Reserving the slot is a read-then-write on _next_slot with no await
# between, so it is atomic on the single-threaded loop and needs no lock.
loop = asyncio.get_running_loop()
now = loop.time()
slot = max(now, self._next_slot)
self._next_slot = slot + self._min_interval
delay = slot - now
if delay > 0:
await asyncio.sleep(delay)
class ConcurrencyLimiter:
"""Caps the number of in-flight operations, with a runtime-adjustable capacity.
It suits APIs that enforce a per-account thread/connection cap (e.g. ScreenScraper)
rather than a call rate. Because a slot is held for the whole request, slow
responses can never cause overlapping requests to exceed the cap.
Use it as an async context manager so the slot is always released, even if the
wrapped request raises:
async with limiter:
await do_request()
"""
def __init__(self, max_concurrency: int) -> None:
if max_concurrency < 1:
raise ValueError("max_concurrency must be at least 1")
self._max_concurrency = max_concurrency
self._in_flight = 0
self._waiters: deque[asyncio.Future[None]] = deque()
@property
def max_concurrency(self) -> int:
return self._max_concurrency
@property
def in_flight(self) -> int:
return self._in_flight
def set_max_concurrency(self, max_concurrency: int) -> None:
if max_concurrency < 1:
raise ValueError("max_concurrency must be at least 1")
previous = self._max_concurrency
self._max_concurrency = max_concurrency
# Wake one waiter per newly opened slot; each re-checks capacity itself.
for _ in range(max(0, max_concurrency - previous)):
self._wake_next()
async def acquire(self) -> None:
# Re-check on every wake-up, as another coroutine may have taken the slot,
# or the capacity may have been lowered while we waited.
while self._in_flight >= self._max_concurrency:
loop = asyncio.get_running_loop()
waiter = loop.create_future()
self._waiters.append(waiter)
try:
try:
await waiter
finally:
self._waiters.remove(waiter)
except asyncio.CancelledError:
# We were granted a slot but cancelled before using it, so pass the
# grant on so a waiting peer is not stranded.
if not waiter.cancelled():
self._wake_next()
raise
self._in_flight += 1
def release(self) -> None:
if self._in_flight > 0:
self._in_flight -= 1
self._wake_next()
def _wake_next(self) -> None:
for waiter in self._waiters:
if not waiter.done():
waiter.set_result(None)
return
async def __aenter__(self) -> "ConcurrencyLimiter":
await self.acquire()
return self
async def __aexit__(self, *exc_info: object) -> None:
self.release()