fix(steam): bound each sync's achievement reads and tolerate malformed replies (pr-ready: code-review)

A first sync of a large library read every played game in one task and
could pass the task timeout, losing every read. Each sync now reads up to
100 games and stops after three failures in a row, so Steam outages don't
cost a full retry per game; the next sync carries on from what was stored.

Malformed unlock entries are dropped or coerced so the stored progression
always passes `UserSchema`, and a reply of the wrong shape counts as none.
Completed games are looked up with the library's existing Steam id query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NH5s4hBCkRF6nyKoFy6MXw
This commit is contained in:
Sam Dornan
2026-11-02 03:45:10 +00:00
committed by Claude
parent ffe28c0425
commit 4cddd8e7ee
5 changed files with 133 additions and 34 deletions

View File

@@ -366,4 +366,7 @@ class SteamWebApiService:
if exc.status == STEAM_NO_STATS_STATUS:
return []
raise
return response.get("playerstats", {}).get("achievements") or []
# A reply that strays from its TypedDict is handed back as sent.
stats = response.get("playerstats")
achievements = stats.get("achievements") if isinstance(stats, dict) else None
return achievements if isinstance(achievements, list) else []

View File

@@ -991,20 +991,6 @@ class DBRomsHandler(DBBaseHandler):
select(Rom.id, Rom.ra_id).where(Rom.ra_id.in_(ra_ids))
).all()
@begin_session
def get_roms_by_steam_ids(
self,
steam_ids: Sequence[int],
*,
session: Session = INJECTED_SESSION,
) -> Sequence[Row[int, int | None]]:
"""Get `(id, steam_id)` for every ROM matching any of `steam_ids`."""
if not steam_ids:
return []
return session.execute(
select(Rom.id, Rom.steam_id).where(Rom.steam_id.in_(steam_ids))
).all()
def get_files_for_roms(
self,
rom_ids: list[int],

View File

@@ -60,6 +60,13 @@ class SteamSyncResult:
unmatched_rom_ids: list[int] = field(default_factory=list)
# Reads per library sync, so a large first sync stays within the task timeout
# and the rest are read by the syncs after it.
STEAM_ACHIEVEMENT_READS_PER_SYNC: Final[int] = 100
# Failed reads in a row that mean Steam itself is struggling.
STEAM_ACHIEVEMENT_FAILURES_IN_A_ROW: Final[int] = 3
class SteamEarnedAchievement(TypedDict):
api_name: str
# Epoch seconds.
@@ -297,21 +304,39 @@ async def sync_steam_library(user: User) -> SteamSyncResult:
return result
def _last_played_epoch(entry: SteamLibraryEntry) -> int | None:
return int(entry.last_played_at.timestamp()) if entry.last_played_at else None
def _unlock_time(value: Any) -> int:
"""Steam's unlock time in epoch seconds, or 0, its own "unknown", if unreadable."""
try:
return int(value)
except (TypeError, ValueError, OverflowError):
return 0
def _game_progression(
entry: SteamLibraryEntry, achievements: list[SteamPlayerAchievement]
) -> SteamUserGameProgression:
earned = [
SteamEarnedAchievement(api_name=a["apiname"], unlock_time=a["unlocktime"])
# Steam's reply arrives even when it strays, and this must pass `UserSchema`.
named = [
a
for a in achievements
if a.get("achieved") and a.get("apiname")
if isinstance(a, dict) and isinstance(a.get("apiname"), str) and a["apiname"]
]
earned = [
SteamEarnedAchievement(
api_name=a["apiname"], unlock_time=_unlock_time(a.get("unlocktime"))
)
for a in named
if a.get("achieved") == 1
]
return SteamUserGameProgression(
rom_steam_id=entry.steam_app_id,
rtime_last_played=(
int(entry.last_played_at.timestamp()) if entry.last_played_at else None
),
rtime_last_played=_last_played_epoch(entry),
playtime_forever=entry.playtime_minutes,
num_achievements=len(achievements),
num_achievements=len(named),
num_unlocked=len(earned),
earned_achievements=earned,
)
@@ -322,10 +347,11 @@ async def get_steam_progression(
entries: Sequence[SteamLibraryEntry],
current: SteamUserProgression | None,
) -> SteamUserProgression:
"""Read the unlocks of each played game in `entries`.
"""Read the unlocks of the played games in `entries`, up to a budget per sync.
A game not played since `current` was read keeps its entry without a request,
and one whose read fails keeps whatever `current` has for it.
A game not played since `current` was read keeps its entry without a
request. Once the budget is spent, or Steam fails several reads in a row,
the remaining games keep what `current` has and wait for the next sync.
Raises:
SteamWebAPIError: Steam refused the player's achievements outright.
@@ -334,20 +360,27 @@ async def get_steam_progression(
current_by_app_id = {p["rom_steam_id"]: p for p in known_results}
api = steam_web_api()
results: list[SteamUserGameProgression] = []
reads = failures_in_a_row = 0
for entry in entries:
if not entry.playtime_minutes:
continue
game = _game_progression(entry, [])
known = current_by_app_id.get(entry.steam_app_id)
if (
unchanged = (
known
and known["rtime_last_played"] == game["rtime_last_played"]
and known["playtime_forever"] == game["playtime_forever"]
and known["rtime_last_played"] == _last_played_epoch(entry)
and known["playtime_forever"] == entry.playtime_minutes
)
if (
unchanged
or reads >= STEAM_ACHIEVEMENT_READS_PER_SYNC
or failures_in_a_row >= STEAM_ACHIEVEMENT_FAILURES_IN_A_ROW
):
results.append(known)
if known:
results.append(known)
continue
reads += 1
try:
achievements = await api.get_player_achievements(
steam_id, entry.steam_app_id
@@ -355,12 +388,14 @@ async def get_steam_progression(
except SteamWebAPIError as exc:
if exc.status == 403:
raise
failures_in_a_row += 1
log.warning(
f"Couldn't read achievements for Steam app {entry.steam_app_id}: {exc}"
)
if known:
results.append(known)
continue
failures_in_a_row = 0
results.append(_game_progression(entry, achievements))
return SteamUserProgression(total=len(results), results=results)
@@ -383,8 +418,8 @@ async def sync_steam_achievements(
for game in progression["results"]
if is_steam_game_completed(game)
]
statuses = {
rom.id: RomUserStatus.COMPLETED_100
for rom in db_rom_handler.get_roms_by_steam_ids(completed)
}
statuses = dict.fromkeys(
db_steam_library_handler.get_rom_ids_by_app_ids(completed),
RomUserStatus.COMPLETED_100,
)
db_rom_handler.set_rom_user_statuses(user.id, statuses)

View File

@@ -178,3 +178,14 @@ async def test_refused_player_achievements_are_an_error_with_their_status(sessio
await _service().get_player_achievements(STEAM_ID, 220)
assert exc_info.value.status == 403
@pytest.mark.parametrize(
"playerstats", [["not", "an", "object"], {"success": True, "achievements": "ACH"}]
)
async def test_a_malformed_player_achievements_reply_has_none(
session, lenient, playerstats
):
session.get.return_value = _response({"playerstats": playerstats})
assert await _service().get_player_achievements(STEAM_ID, 220) == []

View File

@@ -11,6 +11,7 @@ from adapters.services.steam_types import (
SteamPlayerAchievement,
SteamPlayerSummary,
)
from endpoints.responses.identity import UserSchema
from handler.database import (
db_collection_handler,
db_platform_handler,
@@ -441,6 +442,32 @@ async def test_a_failed_read_keeps_what_the_last_sync_stored(
assert (game["num_unlocked"], game["playtime_forever"]) == (1, 90)
async def test_malformed_unlocks_are_coerced_or_dropped(
steam_api: MagicMock, steam_user: User, win: Platform
):
steam_api.get_owned_games.return_value = [
_game(220, "Half-Life 2", playtime=90, last_played=1_700_000_000)
]
steam_api.get_player_achievements.return_value = [
{"apiname": "WIN", "achieved": 1, "unlocktime": "1700000000"},
{"apiname": "LATE", "achieved": 1, "unlocktime": None},
{"apiname": "LOCKED", "achieved": "0", "unlocktime": 0},
{"apiname": 5, "achieved": 1, "unlocktime": 1},
{"achieved": 1},
"NOT_AN_ACHIEVEMENT",
]
await sync_steam_library(steam_user)
UserSchema.model_validate(db_user_handler.get_user(steam_user.id))
[game] = _progression(steam_user)["results"]
assert game["earned_achievements"] == [
{"api_name": "WIN", "unlock_time": 1_700_000_000},
{"api_name": "LATE", "unlock_time": 0},
]
assert (game["num_achievements"], game["num_unlocked"]) == (3, 2)
async def test_refused_achievements_leave_the_library_sync_intact(
steam_api: MagicMock, steam_user: User, win: Platform
):
@@ -520,3 +547,40 @@ def test_a_game_is_completed_only_with_every_achievement(
"earned_achievements": [],
}
assert is_steam_game_completed(game) is expected
async def test_games_past_the_read_budget_wait_for_the_next_sync(
steam_api: MagicMock, steam_user: User, win: Platform
):
steam_api.get_owned_games.return_value = [
_game(220, "Half-Life 2", playtime=90, last_played=1_700_000_000),
_game(400, "Portal", playtime=30, last_played=1_700_000_500),
]
steam_api.get_player_achievements.return_value = _unlocks(True)
with patch("handler.steam_library_handler.STEAM_ACHIEVEMENT_READS_PER_SYNC", 1):
await sync_steam_library(steam_user)
assert len(_progression(steam_user)["results"]) == 1
user = db_user_handler.get_user(steam_user.id)
assert user is not None
await sync_steam_library(user)
assert {g["rom_steam_id"] for g in _progression(user)["results"]} == {220, 400}
assert steam_api.get_player_achievements.await_count == 2
async def test_reads_stop_after_several_failures_in_a_row(
steam_api: MagicMock, steam_user: User, win: Platform
):
steam_api.get_owned_games.return_value = [
_game(app_id, f"Game {app_id}", playtime=10, last_played=1_700_000_000)
for app_id in range(1, 6)
]
steam_api.get_player_achievements.side_effect = SteamWebAPIError(
"Steam did not answer in time"
)
await sync_steam_library(steam_user)
assert steam_api.get_player_achievements.await_count == 3