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

241 lines
8.2 KiB
Python

from datetime import datetime, timedelta, timezone
from typing import Any, Literal, NotRequired, TypedDict
from pydash import compact
from rq.exceptions import DuplicateJobError
from handler.audit_handler import AuditActor, AuditDraft, AuditTarget, record_many
from handler.auth.permissions import ResolvedPermissions
from handler.database import db_device_handler, db_play_session_handler, db_rom_handler
from handler.metadata import meta_ra_handler
from handler.redis_handler import low_prio_queue
from logger.logger import log
from models.audit_event import AuditAction, AuditActorKind
from models.play_session import PlaySession
from models.rom import RomUserStatus
from tasks.registry import SYNC_RETROACHIEVEMENTS_PROGRESS_SPEC
from utils.datetime import to_utc
class PlaySessionIngestResult(TypedDict):
index: int
status: Literal["created", "duplicate", "error"]
id: NotRequired[int | None]
detail: NotRequired[str | None]
class PlaySessionIngestSummary(TypedDict):
results: list[PlaySessionIngestResult]
created_count: int
skipped_count: int
class PlaySessionEntry(TypedDict):
rom_id: int | None
save_slot: str | None
start_time: datetime
end_time: datetime
duration_ms: int
def _resolve_device(device_id: str | None, user_id: int) -> str | None:
if device_id is None:
return None
device = db_device_handler.get_device(device_id=device_id, user_id=user_id)
return device_id if device is not None else None
def _apply_play_to_rom_user(
rom_user_updates: dict[int, datetime], user_id: int
) -> None:
for rom_id, latest_end_time in rom_user_updates.items():
rom_user = db_rom_handler.get_rom_user(rom_id=rom_id, user_id=user_id)
if not rom_user:
rom_user = db_rom_handler.add_rom_user(rom_id=rom_id, user_id=user_id)
current = to_utc(rom_user.last_played) if rom_user.last_played else None
# Only the newest play advances state. A backfilled or device-synced
# older session must not resurrect "now playing" or rewind the status.
if current is not None and latest_end_time <= current:
continue
updates: dict[str, Any] = {"last_played": latest_end_time, "now_playing": True}
# Playing again counts as active: rewind an empty or "finished" status
# to "incomplete", but leave statuses the user set on purpose
# (completed_100 / retired / never_playing) untouched.
if rom_user.status in (None, RomUserStatus.FINISHED):
updates["status"] = RomUserStatus.INCOMPLETE
db_rom_handler.update_rom_user(rom_user.id, updates)
RA_PROGRESS_SYNC_FAILURE_TTL_SECONDS = 300
def queue_ra_progress_sync(user_id: int, *, refresh_all: bool = False) -> bool:
"""Refresh the user's RetroAchievements progress, at most one job at a time.
Returns:
Whether a sync is queued, including one queued before this call.
"""
try:
low_prio_queue.enqueue(
"tasks.scheduled.sync_retroachievements_progress.sync_user_progress_job",
kwargs={"user_id": user_id, "refresh_all": refresh_all},
job_id=f"ra_progress_sync_{user_id}",
unique=True,
job_timeout=SYNC_RETROACHIEVEMENTS_PROGRESS_SPEC.timeout,
result_ttl=0,
# A worker killed mid-run fails the job, which must not hold the id long.
# Not 0: RQ reads a stored 0 back as unset, which means a year.
failure_ttl=RA_PROGRESS_SYNC_FAILURE_TTL_SECONDS,
meta={"task_name": "RetroAchievements progress sync"},
)
except DuplicateJobError:
pass
except Exception: # noqa: BLE001 - the nightly sync catches up
log.exception("Failed to queue a RetroAchievements progress sync")
return False
return True
def ingest_play_sessions(
*,
user_id: int,
username: str,
entries: list[PlaySessionEntry],
device_id: str | None = None,
max_future_minutes: int = 5,
perms: ResolvedPermissions | None,
) -> PlaySessionIngestSummary:
"""Core play session ingestion logic shared by the standalone endpoint and sync complete.
Args:
perms: The caller's permissions, a rom hidden from them counting as
unknown; None when its roms were already checked.
"""
max_future = datetime.now(timezone.utc) + timedelta(minutes=max_future_minutes)
resolved_device_id = _resolve_device(device_id, user_id)
# Bulk-resolve all referenced rom IDs in one query
candidate_rom_ids = {e["rom_id"] for e in entries}
found_roms = (
{
r.id: r
for r in db_rom_handler.get_roms_by_ids(compact(candidate_rom_ids))
if perms is None or perms.can_see_rom(r)
}
if candidate_rom_ids
else {}
)
valid_rom_ids = set(found_roms)
# Phase 1: Validate and resolve each entry
results: list[PlaySessionIngestResult] = []
valid: list[tuple[int, int | None, PlaySessionEntry]] = []
for idx, item in enumerate(entries):
if item["end_time"] > max_future:
results.append(
{
"index": idx,
"status": "error",
"detail": "end_time is too far in the future",
}
)
continue
rom_id = item.get("rom_id")
resolved_rom_id = rom_id if rom_id in valid_rom_ids else None
valid.append((idx, resolved_rom_id, item))
# Phase 2: Batch dedup check
rom_start_pairs = [
(rom_id, to_utc(item["start_time"])) for _, rom_id, item in valid
]
existing = db_play_session_handler.find_existing(
user_id=user_id, device_id=resolved_device_id, rom_start_pairs=rom_start_pairs
)
seen: set[tuple[int | None, datetime]] = set()
to_insert: list[tuple[int, int | None, PlaySession]] = []
for (idx, resolved_rom_id, item), key in zip(valid, rom_start_pairs, strict=True):
if key in seen or key in existing:
results.append({"index": idx, "status": "duplicate"})
continue
seen.add(key)
to_insert.append(
(
idx,
resolved_rom_id,
PlaySession(
user_id=user_id,
device_id=resolved_device_id,
rom_id=resolved_rom_id,
save_slot=item.get("save_slot"),
start_time=item["start_time"],
end_time=item["end_time"],
duration_ms=item["duration_ms"],
),
)
)
# Phase 3: Bulk insert
if to_insert:
db_play_session_handler.add_sessions([ps for _, _, ps in to_insert])
rom_user_updates: dict[int, datetime] = {}
for idx, resolved_rom_id, ps in to_insert:
results.append({"index": idx, "status": "created", "id": ps.id})
if resolved_rom_id is not None:
prev = rom_user_updates.get(resolved_rom_id)
if prev is None or ps.end_time > prev:
rom_user_updates[resolved_rom_id] = ps.end_time
# Phase 4: Side effects
_apply_play_to_rom_user(rom_user_updates, user_id)
if meta_ra_handler.is_enabled() and any(
found_roms[rom_id].ra_id for rom_id in rom_user_updates
):
queue_ra_progress_sync(user_id)
actor = AuditActor(
AuditActorKind.USER,
user_id=user_id,
name=username,
device_id=resolved_device_id,
)
record_many(
[
AuditDraft(
AuditAction.ROM_PLAY,
actor,
AuditTarget.of_rom(found_roms[ps.rom_id]),
{"duration_ms": ps.duration_ms, "save_slot": ps.save_slot},
occurred_at=to_utc(ps.start_time),
)
for _, _, ps in to_insert
if ps.rom_id is not None
]
)
if resolved_device_id is not None:
db_device_handler.update_last_seen(
device_id=resolved_device_id, user_id=user_id
)
created_count = len(to_insert)
skipped_count = len(entries) - created_count
log.info(
f"Ingested {created_count} play sessions for user {username}"
f" ({skipped_count} skipped)"
)
return {
"results": results,
"created_count": created_count,
"skipped_count": skipped_count,
}