mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 10:01:00 +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>
394 lines
14 KiB
Python
394 lines
14 KiB
Python
from types import SimpleNamespace
|
|
from typing import Any
|
|
from unittest.mock import MagicMock
|
|
|
|
import pytest
|
|
from tests.factories import make_rom
|
|
|
|
from adapters.services.retroachievements_types import RAUserCompletionProgressKind
|
|
from handler.database import db_rom_handler, db_user_handler
|
|
from handler.database.roms_handler import DBRomsHandler
|
|
from handler.database.users_handler import DBUsersHandler
|
|
from handler.metadata.ra_handler import RAHandler
|
|
from handler.socket_handler import socket_handler
|
|
from models.rom import RomUserStatus
|
|
from models.user import User
|
|
from tasks.scheduled.sync_retroachievements_progress import (
|
|
RA_SYNCED_EVENT,
|
|
SyncRetroAchievementsProgressTask,
|
|
_get_rom_user_status_from_ra_award_kind,
|
|
_sync_and_report,
|
|
_sync_user_progress_by_id,
|
|
)
|
|
|
|
JOB_PATH = "tasks.scheduled.sync_retroachievements_progress"
|
|
|
|
|
|
@pytest.fixture
|
|
def task() -> SyncRetroAchievementsProgressTask:
|
|
"""Create a task instance for testing."""
|
|
return SyncRetroAchievementsProgressTask()
|
|
|
|
|
|
def _progression(*games: tuple[int, str | None]) -> dict[str, Any]:
|
|
return {
|
|
"total": len(games),
|
|
"results": [
|
|
{"rom_ra_id": ra_id, "highest_award_kind": award_kind}
|
|
for ra_id, award_kind in games
|
|
],
|
|
}
|
|
|
|
|
|
def _mock_sync(
|
|
mocker,
|
|
user: User,
|
|
progression: dict[str, Any],
|
|
roms: list[tuple[int, int]],
|
|
) -> tuple[MagicMock, MagicMock]:
|
|
"""Patch one user's RA feed and the sync's DB calls.
|
|
|
|
Returns:
|
|
The `get_roms_by_ra_ids` and `set_rom_user_statuses` mocks.
|
|
"""
|
|
mocker.patch.object(DBUsersHandler, "get_users", return_value=[user])
|
|
mocker.patch.object(DBUsersHandler, "set_ra_progression", return_value=True)
|
|
mocker.patch.object(RAHandler, "get_user_progression", return_value=progression)
|
|
return (
|
|
mocker.patch.object(
|
|
DBRomsHandler,
|
|
"get_roms_by_ra_ids",
|
|
return_value=[SimpleNamespace(id=i, ra_id=r) for i, r in roms],
|
|
),
|
|
mocker.patch.object(DBRomsHandler, "set_rom_user_statuses", return_value=0),
|
|
)
|
|
|
|
|
|
class TestGetRomUserStatusFromRaAwardKind:
|
|
"""Tests for the _get_rom_user_status_from_ra_award_kind helper."""
|
|
|
|
def test_mastered_returns_completed_100(self):
|
|
assert (
|
|
_get_rom_user_status_from_ra_award_kind(
|
|
RAUserCompletionProgressKind.MASTERED
|
|
)
|
|
== RomUserStatus.COMPLETED_100
|
|
)
|
|
|
|
def test_completed_returns_completed_100(self):
|
|
assert (
|
|
_get_rom_user_status_from_ra_award_kind(
|
|
RAUserCompletionProgressKind.COMPLETED
|
|
)
|
|
== RomUserStatus.COMPLETED_100
|
|
)
|
|
|
|
def test_beaten_hardcore_returns_finished(self):
|
|
assert (
|
|
_get_rom_user_status_from_ra_award_kind(
|
|
RAUserCompletionProgressKind.BEATEN_HARDCORE
|
|
)
|
|
== RomUserStatus.FINISHED
|
|
)
|
|
|
|
def test_beaten_softcore_returns_finished(self):
|
|
assert (
|
|
_get_rom_user_status_from_ra_award_kind(
|
|
RAUserCompletionProgressKind.BEATEN_SOFTCORE
|
|
)
|
|
== RomUserStatus.FINISHED
|
|
)
|
|
|
|
def test_none_returns_incomplete(self):
|
|
assert _get_rom_user_status_from_ra_award_kind(None) == RomUserStatus.INCOMPLETE
|
|
|
|
def test_unknown_value_returns_none(self):
|
|
assert _get_rom_user_status_from_ra_award_kind("unknown_award") is None
|
|
|
|
|
|
class TestSyncRetroAchievementsProgressTask:
|
|
"""Test suite for SyncRetroAchievementsProgressTask."""
|
|
|
|
def test_task_initialization(self, task):
|
|
"""Test task initialization with correct parameters."""
|
|
assert (
|
|
task.spec.description == "Updates RetroAchievements progress for all users"
|
|
)
|
|
|
|
async def test_run_when_retroachievements_api_disabled(self, task, mocker):
|
|
"""Test run method when RetroAchievements API is disabled."""
|
|
mocker.patch.object(RAHandler, "is_enabled", return_value=False)
|
|
mock_log = mocker.patch("tasks.scheduled.sync_retroachievements_progress.log")
|
|
|
|
await task.run()
|
|
|
|
mock_log.warning.assert_called_once_with(
|
|
"RetroAchievements API is not enabled, skipping progress sync"
|
|
)
|
|
|
|
async def test_run_when_no_users_set(self, task, mocker):
|
|
"""Test run method when no users have RetroAchievements usernames set"""
|
|
mock_get_users = mocker.patch.object(
|
|
DBUsersHandler, "get_users", return_value=[]
|
|
)
|
|
mock_get_user_progression = mocker.patch.object(
|
|
RAHandler, "get_user_progression"
|
|
)
|
|
|
|
await task.run()
|
|
|
|
mock_get_users.assert_called_once_with(has_ra_username=True)
|
|
mock_get_user_progression.assert_not_called()
|
|
|
|
async def test_run_saves_progress(self, task, viewer_user, mocker):
|
|
"""Test run method saves retrieved progress."""
|
|
mocker.patch.object(DBUsersHandler, "get_users", return_value=[viewer_user])
|
|
mock_set_progression = mocker.patch.object(
|
|
DBUsersHandler, "set_ra_progression", return_value=True
|
|
)
|
|
user_progression = {"total": 0, "results": []}
|
|
mocker.patch.object(
|
|
RAHandler, "get_user_progression", return_value=user_progression
|
|
)
|
|
|
|
await task.run()
|
|
|
|
mock_set_progression.assert_called_once_with(
|
|
viewer_user.id, viewer_user.ra_username, user_progression
|
|
)
|
|
|
|
async def test_run_is_resilient_to_errors(
|
|
self, task, viewer_user, editor_user, mocker
|
|
):
|
|
"""Test run method saves retrieved progress for a user even if another user fails."""
|
|
mocker.patch.object(
|
|
DBUsersHandler, "get_users", return_value=[viewer_user, editor_user]
|
|
)
|
|
user_progression = {"total": 0, "results": []}
|
|
mocker.patch.object(
|
|
RAHandler,
|
|
"get_user_progression",
|
|
side_effect=[
|
|
# Call for first user raises an exception.
|
|
Exception("API error"),
|
|
# Call for second user returns valid progression.
|
|
user_progression,
|
|
],
|
|
)
|
|
mock_set_progression = mocker.patch.object(
|
|
DBUsersHandler, "set_ra_progression", return_value=True
|
|
)
|
|
|
|
await task.run()
|
|
|
|
mock_set_progression.assert_called_once_with(
|
|
editor_user.id, editor_user.ra_username, user_progression
|
|
)
|
|
|
|
@pytest.mark.parametrize(
|
|
("award_kind", "expected_status"),
|
|
[
|
|
(RAUserCompletionProgressKind.MASTERED, RomUserStatus.COMPLETED_100),
|
|
(RAUserCompletionProgressKind.BEATEN_SOFTCORE, RomUserStatus.FINISHED),
|
|
(None, RomUserStatus.INCOMPLETE),
|
|
],
|
|
)
|
|
async def test_run_maps_award_to_rom_user_status(
|
|
self, task, viewer_user, mocker, award_kind, expected_status
|
|
):
|
|
_, mock_set_statuses = _mock_sync(
|
|
mocker,
|
|
viewer_user,
|
|
_progression((12345, award_kind)),
|
|
roms=[(1, 12345)],
|
|
)
|
|
|
|
await task.run()
|
|
|
|
mock_set_statuses.assert_called_once_with(viewer_user.id, {1: expected_status})
|
|
|
|
async def test_run_skips_status_update_when_rom_not_found(
|
|
self, task, viewer_user, mocker
|
|
):
|
|
"""Test that status update is skipped when the ROM is not in the database."""
|
|
_, mock_set_statuses = _mock_sync(
|
|
mocker,
|
|
viewer_user,
|
|
_progression((99999, RAUserCompletionProgressKind.MASTERED)),
|
|
roms=[],
|
|
)
|
|
|
|
await task.run()
|
|
|
|
mock_set_statuses.assert_called_once_with(viewer_user.id, {})
|
|
|
|
async def test_run_skips_unknown_award(self, task, viewer_user, mocker):
|
|
"""An unrecognised award kind is skipped without a write."""
|
|
mock_get_roms, mock_set_statuses = _mock_sync(
|
|
mocker,
|
|
viewer_user,
|
|
_progression((12345, "unknown_award")),
|
|
roms=[],
|
|
)
|
|
|
|
await task.run()
|
|
|
|
mock_get_roms.assert_called_once_with([])
|
|
mock_set_statuses.assert_called_once_with(viewer_user.id, {})
|
|
|
|
async def test_run_batches_one_read_and_one_write_per_user(
|
|
self, task, viewer_user, mocker
|
|
):
|
|
"""Regional ROMs sharing an ra_id all get that game's status."""
|
|
mock_get_roms, mock_set_statuses = _mock_sync(
|
|
mocker,
|
|
viewer_user,
|
|
_progression(
|
|
(12345, RAUserCompletionProgressKind.MASTERED),
|
|
(67890, None),
|
|
),
|
|
roms=[(1, 12345), (2, 12345), (3, 67890)],
|
|
)
|
|
|
|
await task.run()
|
|
|
|
mock_get_roms.assert_called_once_with([12345, 67890])
|
|
mock_set_statuses.assert_called_once_with(
|
|
viewer_user.id,
|
|
{
|
|
1: RomUserStatus.COMPLETED_100,
|
|
2: RomUserStatus.COMPLETED_100,
|
|
3: RomUserStatus.INCOMPLETE,
|
|
},
|
|
)
|
|
|
|
async def test_run_continues_after_status_sync_error(
|
|
self, task, viewer_user, editor_user, mocker
|
|
):
|
|
"""A status-sync failure for one user still syncs the next user."""
|
|
mock_get_roms, mock_set_statuses = _mock_sync(
|
|
mocker,
|
|
viewer_user,
|
|
_progression((12345, RAUserCompletionProgressKind.MASTERED)),
|
|
roms=[],
|
|
)
|
|
mocker.patch.object(
|
|
DBUsersHandler, "get_users", return_value=[viewer_user, editor_user]
|
|
)
|
|
mock_get_roms.side_effect = [
|
|
Exception("DB error"),
|
|
[SimpleNamespace(id=1, ra_id=12345)],
|
|
]
|
|
|
|
await task.run()
|
|
|
|
mock_set_statuses.assert_called_once_with(
|
|
editor_user.id, {1: RomUserStatus.COMPLETED_100}
|
|
)
|
|
|
|
async def test_run_syncs_real_rows(self, task, viewer_user, platform, mocker):
|
|
"""Unmocked getters: every regional ROM is synced and RETIRED is kept."""
|
|
usa_rom = make_rom(platform, "Game USA", ra_id=12345)
|
|
eur_rom = make_rom(platform, "Game Europe", ra_id=12345)
|
|
retired_rom = make_rom(platform, "Retired Game", ra_id=67890)
|
|
retired_rom_user = db_rom_handler.add_rom_user(retired_rom.id, viewer_user.id)
|
|
db_rom_handler.update_rom_user(
|
|
retired_rom_user.id, {"status": RomUserStatus.RETIRED}
|
|
)
|
|
mocker.patch.object(DBUsersHandler, "get_users", return_value=[viewer_user])
|
|
mocker.patch.object(DBUsersHandler, "set_ra_progression", return_value=True)
|
|
mocker.patch.object(
|
|
RAHandler,
|
|
"get_user_progression",
|
|
return_value=_progression(
|
|
(12345, RAUserCompletionProgressKind.MASTERED),
|
|
(67890, RAUserCompletionProgressKind.MASTERED),
|
|
),
|
|
)
|
|
|
|
await task.run()
|
|
|
|
for synced_rom in (usa_rom, eur_rom):
|
|
rom_user = db_rom_handler.get_rom_user(synced_rom.id, viewer_user.id)
|
|
assert rom_user is not None
|
|
assert rom_user.status == RomUserStatus.COMPLETED_100
|
|
rom_user = db_rom_handler.get_rom_user(retired_rom.id, viewer_user.id)
|
|
assert rom_user is not None
|
|
assert rom_user.status == RomUserStatus.RETIRED
|
|
|
|
|
|
class TestSyncUserProgressJob:
|
|
async def test_syncs_the_user(self, viewer_user, mocker):
|
|
db_user_handler.update_user(viewer_user.id, {"ra_username": "player"})
|
|
progression = {"total": 0, "results": []}
|
|
get_progression = mocker.patch.object(
|
|
RAHandler, "get_user_progression", return_value=progression
|
|
)
|
|
|
|
await _sync_user_progress_by_id(viewer_user.id)
|
|
|
|
get_progression.assert_awaited_once()
|
|
await_args = get_progression.await_args
|
|
assert await_args is not None
|
|
assert await_args.args == ("player",)
|
|
synced = db_user_handler.get_user(viewer_user.id)
|
|
assert synced and synced.ra_progression == progression
|
|
|
|
async def test_drops_progress_fetched_for_a_profile_unlinked_meanwhile(
|
|
self, viewer_user, mocker
|
|
):
|
|
db_user_handler.update_user(viewer_user.id, {"ra_username": "player"})
|
|
|
|
async def unlink_during_fetch(*_args, **_kwargs):
|
|
db_user_handler.update_user(
|
|
viewer_user.id, {"ra_username": None, "ra_progression": {}}
|
|
)
|
|
return _progression((12345, RAUserCompletionProgressKind.MASTERED))
|
|
|
|
mocker.patch.object(
|
|
RAHandler, "get_user_progression", side_effect=unlink_during_fetch
|
|
)
|
|
set_statuses = mocker.patch.object(DBRomsHandler, "set_rom_user_statuses")
|
|
|
|
await _sync_user_progress_by_id(viewer_user.id)
|
|
|
|
unlinked = db_user_handler.get_user(viewer_user.id)
|
|
assert unlinked and unlinked.ra_progression == {}
|
|
set_statuses.assert_not_called()
|
|
|
|
async def test_skips_a_user_without_an_ra_username(self, viewer_user, mocker):
|
|
get_progression = mocker.patch.object(RAHandler, "get_user_progression")
|
|
|
|
await _sync_user_progress_by_id(viewer_user.id)
|
|
|
|
get_progression.assert_not_called()
|
|
|
|
async def test_a_full_refresh_rereads_every_game(self, viewer_user, mocker):
|
|
stored = {"total": 1, "results": [{"rom_ra_id": 7}]}
|
|
db_user_handler.update_user(
|
|
viewer_user.id, {"ra_username": "player", "ra_progression": stored}
|
|
)
|
|
get_progression = mocker.patch.object(
|
|
RAHandler,
|
|
"get_user_progression",
|
|
return_value={"total": 0, "results": []},
|
|
)
|
|
|
|
await _sync_user_progress_by_id(viewer_user.id, refresh_all=True)
|
|
|
|
get_progression.assert_awaited_once_with(
|
|
"player", current_progression=stored, refresh_all=True
|
|
)
|
|
|
|
@pytest.mark.parametrize("fails", [False, True], ids=["synced", "sync_failed"])
|
|
async def test_the_outcome_reaches_the_users_tabs(self, mocker, fails: bool):
|
|
mocker.patch(
|
|
f"{JOB_PATH}._sync_user_progress_by_id",
|
|
side_effect=RuntimeError("RetroAchievements is down") if fails else None,
|
|
)
|
|
emit = mocker.patch.object(socket_handler, "emit_to_user")
|
|
|
|
await _sync_and_report(3, refresh_all=False)
|
|
|
|
emit.assert_awaited_once_with(3, RA_SYNCED_EVENT, {"ok": not fails})
|