mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 01:58:41 +01:00
* 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>
186 lines
6.0 KiB
Python
186 lines
6.0 KiB
Python
import asyncio
|
|
|
|
import pytest
|
|
|
|
from utils.rate_limiter import ConcurrencyLimiter, RateLimiter
|
|
|
|
|
|
def _record_sleeps(monkeypatch) -> list[float]:
|
|
"""Replace asyncio.sleep with a no-op that records requested delays."""
|
|
sleeps: list[float] = []
|
|
|
|
async def fake_sleep(delay: float) -> None:
|
|
sleeps.append(delay)
|
|
|
|
monkeypatch.setattr(asyncio, "sleep", fake_sleep)
|
|
return sleeps
|
|
|
|
|
|
class TestRateLimiter:
|
|
async def test_first_acquire_does_not_sleep(self, monkeypatch):
|
|
sleeps = _record_sleeps(monkeypatch)
|
|
limiter = RateLimiter(requests_per_second=4)
|
|
|
|
await limiter.acquire()
|
|
|
|
assert sleeps == []
|
|
|
|
async def test_slots_advance_by_interval(self, monkeypatch):
|
|
sleeps = _record_sleeps(monkeypatch)
|
|
limiter = RateLimiter(requests_per_second=4)
|
|
|
|
for _ in range(5):
|
|
await limiter.acquire()
|
|
|
|
# First grant is immediate; the next four are spaced one interval apart.
|
|
assert len(sleeps) == 4
|
|
for index, delay in enumerate(sleeps, start=1):
|
|
assert delay == pytest.approx(index * 0.25, abs=0.05)
|
|
|
|
async def test_concurrent_callers_are_spaced(self):
|
|
rate = 50
|
|
interval = 1 / rate
|
|
count = 5
|
|
limiter = RateLimiter(requests_per_second=rate)
|
|
|
|
loop = asyncio.get_running_loop()
|
|
start = loop.time()
|
|
await asyncio.gather(*(limiter.acquire() for _ in range(count)))
|
|
elapsed = loop.time() - start
|
|
|
|
assert elapsed >= (count - 1) * interval
|
|
assert elapsed < (count - 1) * interval + 0.5
|
|
|
|
@pytest.mark.parametrize("rate", [0, -1, -0.5])
|
|
def test_non_positive_rate_raises(self, rate):
|
|
with pytest.raises(ValueError):
|
|
RateLimiter(requests_per_second=rate)
|
|
|
|
async def test_raising_the_rate_shortens_the_interval(self, monkeypatch):
|
|
sleeps = _record_sleeps(monkeypatch)
|
|
limiter = RateLimiter(requests_per_second=1)
|
|
|
|
limiter.set_requests_per_second(4)
|
|
await limiter.acquire()
|
|
await limiter.acquire()
|
|
|
|
assert limiter.requests_per_second == pytest.approx(4)
|
|
assert sleeps == [pytest.approx(0.25, abs=0.05)]
|
|
|
|
async def test_lowering_the_rate_widens_the_interval(self, monkeypatch):
|
|
sleeps = _record_sleeps(monkeypatch)
|
|
limiter = RateLimiter(requests_per_second=4)
|
|
|
|
limiter.set_requests_per_second(1)
|
|
await limiter.acquire()
|
|
await limiter.acquire()
|
|
|
|
assert sleeps == [pytest.approx(1.0, abs=0.05)]
|
|
|
|
async def test_a_hold_delays_the_next_grant(self, monkeypatch):
|
|
sleeps = _record_sleeps(monkeypatch)
|
|
limiter = RateLimiter(requests_per_second=4)
|
|
|
|
limiter.hold(3)
|
|
await limiter.acquire()
|
|
await limiter.acquire()
|
|
|
|
assert sleeps == [
|
|
pytest.approx(3.0, abs=0.05),
|
|
pytest.approx(3.25, abs=0.05),
|
|
]
|
|
|
|
async def test_a_hold_shorter_than_the_queue_changes_nothing(self, monkeypatch):
|
|
sleeps = _record_sleeps(monkeypatch)
|
|
limiter = RateLimiter(requests_per_second=1)
|
|
|
|
await limiter.acquire()
|
|
limiter.hold(0.5)
|
|
await limiter.acquire()
|
|
|
|
assert sleeps == [pytest.approx(1.0, abs=0.05)]
|
|
|
|
@pytest.mark.parametrize("rate", [0, -1, -0.5])
|
|
def test_setting_non_positive_rate_raises(self, rate):
|
|
limiter = RateLimiter(requests_per_second=4)
|
|
with pytest.raises(ValueError):
|
|
limiter.set_requests_per_second(rate)
|
|
|
|
|
|
class TestConcurrencyLimiter:
|
|
@pytest.mark.parametrize("value", [0, -1])
|
|
def test_non_positive_capacity_raises(self, value):
|
|
with pytest.raises(ValueError):
|
|
ConcurrencyLimiter(max_concurrency=value)
|
|
|
|
async def test_acquire_release_tracks_in_flight(self):
|
|
limiter = ConcurrencyLimiter(max_concurrency=2)
|
|
|
|
await limiter.acquire()
|
|
await limiter.acquire()
|
|
assert limiter.in_flight == 2
|
|
|
|
limiter.release()
|
|
assert limiter.in_flight == 1
|
|
|
|
async def test_context_manager_releases(self):
|
|
limiter = ConcurrencyLimiter(max_concurrency=1)
|
|
|
|
async with limiter:
|
|
assert limiter.in_flight == 1
|
|
assert limiter.in_flight == 0
|
|
|
|
async def test_context_manager_releases_on_error(self):
|
|
limiter = ConcurrencyLimiter(max_concurrency=1)
|
|
|
|
with pytest.raises(RuntimeError):
|
|
async with limiter:
|
|
raise RuntimeError("boom")
|
|
|
|
assert limiter.in_flight == 0
|
|
|
|
async def test_acquire_blocks_until_slot_freed(self):
|
|
limiter = ConcurrencyLimiter(max_concurrency=1)
|
|
await limiter.acquire()
|
|
|
|
waiter = asyncio.ensure_future(limiter.acquire())
|
|
await asyncio.sleep(0) # Let the waiter run and block.
|
|
assert not waiter.done()
|
|
|
|
limiter.release()
|
|
await asyncio.wait_for(waiter, timeout=1)
|
|
assert limiter.in_flight == 1
|
|
|
|
async def test_set_max_concurrency_wakes_waiters(self):
|
|
limiter = ConcurrencyLimiter(max_concurrency=1)
|
|
await limiter.acquire()
|
|
|
|
waiter = asyncio.ensure_future(limiter.acquire())
|
|
await asyncio.sleep(0)
|
|
assert not waiter.done()
|
|
|
|
# Opening a second slot should release the blocked acquirer.
|
|
limiter.set_max_concurrency(2)
|
|
await asyncio.wait_for(waiter, timeout=1)
|
|
assert limiter.in_flight == 2
|
|
|
|
async def test_lowering_capacity_blocks_new_acquirers(self):
|
|
limiter = ConcurrencyLimiter(max_concurrency=2)
|
|
await limiter.acquire()
|
|
limiter.set_max_concurrency(1)
|
|
|
|
waiter = asyncio.ensure_future(limiter.acquire())
|
|
await asyncio.sleep(0)
|
|
# Already at the new cap, so the next acquirer must wait.
|
|
assert not waiter.done()
|
|
|
|
limiter.release()
|
|
await asyncio.wait_for(waiter, timeout=1)
|
|
assert limiter.in_flight == 1
|
|
|
|
@pytest.mark.parametrize("value", [0, -1])
|
|
def test_set_non_positive_capacity_raises(self, value):
|
|
limiter = ConcurrencyLimiter(max_concurrency=1)
|
|
with pytest.raises(ValueError):
|
|
limiter.set_max_concurrency(value)
|