Files
romm/backend/tasks/scheduled/sync_retroachievements_progress.py
Sam Dornan 4542998510 fix(backend): make type ignores honest and replace mypy trunk-ignores with fixes (#4711)
* fix(backend): make type ignores match what mypy reports

Third in the staged series clearing the errors #4655 made visible.
Whole-project mypy: 91 errors in 26 files -> 64 in 23.

Twenty `# type: ignore[assignment]` comments in
endpoints/responses/rom.py never suppressed anything. The request-scoped
values `from_orm_with_request` attaches to a Rom (rom_user, has_notes,
user_saves and the rest) are not declared on the model, so mypy reports
`attr-defined`; it does so under 1.19 as well as 2.3, so the code was
wrong when the comments were written rather than drifting since. They
now name the error they were meant to silence.

Seventy-nine ignores across 24 files suppressed nothing at all under
`--warn-unused-ignores`, and are removed. One of them,
`utils/zip_cache.py`, keeps its `attr-defined` code for the private
`zipfile._get_compressor` and drops only `assignment`. The unused set is
identical under mypy 2.3.0 and 2.3.1, and removing them leaves the error
count unchanged under both, so none was quietly needed.

The two `filter` helpers typed as `[QueryT: Select | Update | Delete]`
bound the TypeVar to the union, so `query.filter(...)` returned the union
and could not be assigned back to `QueryT`. Constraining it to the three
types lets mypy check each one separately, and the callers are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp

* fix(backend): replace mypy and ASYNC240 trunk-ignores with real fixes

A `trunk-ignore` only suppresses when Trunk runs the linter. Plain mypy
does not read them, so the 13 on mypy findings were all still errors to
`mypy .` and would fail a whole-project check. Each now has a fix.

endpoints/tasks.py: `common_data` was a plain dict literal unpacked into
eight TypedDict constructors, so mypy saw `dict[str, Any]` and could not
match its keys. It holds exactly the fields of BaseTaskStatusResponse and
is now annotated as one, so the unpacking is checked.

handler/metadata/gamelist_handler.py: both media maps were inferred as
`dict[str, str]`, so indexing the TypedDict with their keys was
unprovable. Their keys are now typed `GamelistMediaKey`, the Literal of
the TypedDict's fields. A misspelt map key is now an error at the entry;
before, only the index site could have noticed, and it was suppressed.

handler/metadata/playmatch_handler.py: `attr` was a bare `str`. A TypeIs
guard narrows it to the five lookup attributes, and the frozenset is
derived from that Literal so the names live in one place. mypy now checks
that each name is a real PlaymatchRomMatch key. It does not check that
each takes an int, since mypy is lenient about value types on a union key;
that still rests on which five names are listed.

endpoints/search.py: the per-source tuples mixed ROM-list and handler
types, which mypy joined to `object`. The dict is now annotated with what
the loop uses: Mapping rows and the MetadataHandler base.

tests/handler/metadata/test_launchbox_handler.py: `Path.stat()` inside an
async test (ASYNC240) now goes through `anyio.Path`, as the rest of the
codebase already does.

Whole-project mypy: 64 errors in 23 files -> 51 in 20, identical under
2.3.0 and 2.3.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp

* fix(backend): keep gamelist media keys in one place

Review pointed out that `GamelistMediaKey` repeated all fourteen fields
of GamelistMetadataMedia. Python has no `keyof`, so any Literal of a
TypedDict's keys is a second declaration of them, and a field added to
the TypedDict would be left out of it without any error.

The three index sites go back to suppressing `literal-required`, now as
`# type: ignore[literal-required]` so plain mypy reads it as well as
Trunk. The TypedDict stays the only declaration of the key set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-22 16:02:39 -05:00

149 lines
5.0 KiB
Python

from typing import Any, cast
from adapters.services.retroachievements_types import RAUserCompletionProgressKind
from config import (
ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC,
SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON,
)
from handler.database import db_rom_handler, db_user_handler
from handler.metadata import meta_ra_handler
from handler.metadata.ra_handler import RAUserProgression
from logger.logger import log
from models.rom import RomUserStatus
from models.user import User
from tasks.tasks import PeriodicTask, TaskType
from utils.context import initialize_context
from . import UpdateStats
def _get_rom_user_status_from_ra_award_kind(
highest_award_kind: str | None,
) -> RomUserStatus | None:
"""Map a RetroAchievements award kind to a RomUser status.
Returns:
- COMPLETED_100 if the user has mastered or completed the game
- FINISHED if the user has beaten the game (softcore or hardcore)
- INCOMPLETE if the user has started but not yet beaten the game
- None if the award kind is unrecognised
"""
if highest_award_kind in (
RAUserCompletionProgressKind.MASTERED,
RAUserCompletionProgressKind.COMPLETED,
):
return RomUserStatus.COMPLETED_100
if highest_award_kind in (
RAUserCompletionProgressKind.BEATEN_HARDCORE,
RAUserCompletionProgressKind.BEATEN_SOFTCORE,
):
return RomUserStatus.FINISHED
if highest_award_kind is None:
return RomUserStatus.INCOMPLETE
return None
def _sync_rom_user_statuses(user: User, user_progression: RAUserProgression) -> None:
"""Update rom_user.status for each game in the user's RA progression.
The status is always kept in sync with the user's latest RA award so that
changes (e.g. beating a previously-incomplete game) are reflected on every
sync run.
"""
for game_progression in user_progression.get("results", []):
rom_ra_id = game_progression.get("rom_ra_id")
if not rom_ra_id:
continue
new_status = _get_rom_user_status_from_ra_award_kind(
game_progression.get("highest_award_kind")
)
if new_status is None:
continue
rom = db_rom_handler.get_rom_by_metadata_id(ra_id=rom_ra_id)
if not rom:
continue
rom_user = db_rom_handler.get_rom_user(rom.id, user.id)
if rom_user is None:
rom_user = db_rom_handler.add_rom_user(rom.id, user.id)
if rom_user.status == new_status:
continue
if rom_user.status in {RomUserStatus.RETIRED, RomUserStatus.NEVER_PLAYING}:
continue
db_rom_handler.update_rom_user(rom_user.id, {"status": new_status})
log.debug(
f"Set rom_user status to '{new_status}' for user '{user.username}' "
f"and ROM with RA ID {rom_ra_id}"
)
class SyncRetroAchievementsProgressTask(PeriodicTask):
def __init__(self):
super().__init__(
title="Scheduled RetroAchievements progress sync",
task_type=TaskType.UPDATE,
description="Updates RetroAchievements progress for all users",
enabled=ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC,
cron_string=SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON,
manual_run=False,
)
@initialize_context()
async def run(self) -> dict[str, Any]:
update_stats = UpdateStats()
if not meta_ra_handler.is_enabled():
log.warning("RetroAchievements API is not enabled, skipping progress sync")
return update_stats.to_dict()
log.info("Scheduled RetroAchievements progress sync started...")
users = db_user_handler.get_users(has_ra_username=True)
total_users = len(users)
processed_users = 0
# Update initial progress
update_stats.update(processed=processed_users, total=total_users)
for user in users:
try:
user_progression = await meta_ra_handler.get_user_progression(
user.ra_username,
current_progression=cast(
RAUserProgression | None, user.ra_progression
),
)
db_user_handler.update_user(
user.id,
{"ra_progression": user_progression},
)
except Exception as e:
log.error(
f"Failed to update RetroAchievements progress for user: {user.username}, error: {e}"
)
else:
log.debug(
f"Updated RetroAchievements progress for user: {user.username}"
)
_sync_rom_user_statuses(user, user_progression)
processed_users += 1
update_stats.update(processed=processed_users)
log.info(
f"Scheduled RetroAchievements progress sync done. Updated users: {len(users)}"
)
return update_stats.to_dict()
sync_retroachievements_progress_task = SyncRetroAchievementsProgressTask()