Files
romm/backend/tests/handler/test_play_session_handler.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

74 lines
2.5 KiB
Python

import uuid
from collections.abc import Iterator
import pytest
from rq import Queue, SimpleWorker
from handler import play_session_handler
from handler.play_session_handler import queue_ra_progress_sync
from handler.redis_handler import redis_client
from tasks.registry import SYNC_RETROACHIEVEMENTS_PROGRESS_SPEC
JOB_PATH = "tasks.scheduled.sync_retroachievements_progress"
@pytest.fixture
def queue(mocker) -> Iterator[Queue]:
queue = Queue(name=f"test-ra-sync-{uuid.uuid4().hex}", connection=redis_client)
mocker.patch.object(play_session_handler, "low_prio_queue", queue)
yield queue
for job in queue.jobs:
job.delete()
@pytest.fixture
def user_ids() -> tuple[int, int]:
"""Ids no other test queues a sync for, as the job ids live in a shared Redis."""
first = uuid.uuid4().int % 10**9
return first, first + 1
def run_queued_jobs(queue: Queue) -> None:
SimpleWorker([queue], connection=redis_client).work(burst=True)
class TestQueueRAProgressSync:
def test_one_sync_per_user_is_queued_at_a_time(
self, queue: Queue, user_ids: tuple[int, int]
):
first, second = user_ids
assert queue_ra_progress_sync(first, refresh_all=True)
assert queue_ra_progress_sync(first)
assert queue_ra_progress_sync(second)
assert sorted(
(job.kwargs["user_id"], job.kwargs["refresh_all"]) for job in queue.jobs
) == [(first, True), (second, False)]
assert {job.timeout for job in queue.jobs} == {
SYNC_RETROACHIEVEMENTS_PROGRESS_SPEC.timeout
}
@pytest.mark.parametrize("fails", [False, True], ids=["synced", "sync_failed"])
def test_a_finished_sync_lets_the_next_play_queue_another(
self, queue: Queue, mocker, fails: bool, user_ids: tuple[int, int]
):
user_id, _ = user_ids
sync = mocker.patch(
f"{JOB_PATH}._sync_user_progress_by_id",
side_effect=RuntimeError("RetroAchievements is down") if fails else None,
)
queue_ra_progress_sync(user_id)
run_queued_jobs(queue)
queue_ra_progress_sync(user_id)
sync.assert_called_once_with(user_id, refresh_all=False)
assert [job.kwargs["user_id"] for job in queue.jobs] == [user_id]
def test_a_sync_that_cannot_be_queued_is_reported(self, queue: Queue, mocker):
mocker.patch.object(
queue, "enqueue", side_effect=ConnectionError("Redis is down")
)
assert not queue_ra_progress_sync(1)