12 Commits

Author SHA1 Message Date
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
Sam Dornan
d05f5cc5e1 feat(ra): sync a player's achievements after they play an RA game (#5425)
* feat(ra): sync a player's achievements after they play an RA game

RetroAchievements progress only synced nightly (and only when the
scheduled task is enabled) or by hand from Settings, so achievements
earned in a session didn't show in RomM until much later.

When a play session is recorded for a ROM matched to RetroAchievements,
queue an incremental progress sync for that user on the low-priority
queue. Every play path (web player, streaming, device sync) records its
sessions through ingest_play_sessions, so all of them trigger it. A fixed
job id keeps one sync per user queued at a time.

The per-user sync body moves out of the scheduled task so both share it.

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

* fix(ra): queue the after-play sync under a valid id that a failure can't hold

The job id used a colon, which RQ rejects, so every enqueue raised and was
logged instead of queued. Use an underscore.

With unique=True, RQ refuses any job whose id still exists, and a failed
job is kept for failure_ttl (a year by default). One failed sync would
have blocked that user's after-play syncs. The job now logs its own
errors instead of failing, and failure_ttl is capped for a worker that
dies mid-run.

Add tests against the real queue: one job per user, and the id is free
again after a sync succeeds or fails. Also drop the docstring's Raises
block and narrow await_args before reading it.

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

* fix(ra): give the after-play sync the RetroAchievements task's timeout

It used RQ's 180s default, which a first sync of a large account can
exceed. Use the scheduled sync's configured timeout (TASK_TIMEOUT).

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:10:25 -05:00
Sam Dornan
b3ad84c296 Route ROM visibility through a single RomVisibilityFilter (#5064)
Replace the hidden_platform_ids/hidden_rom_ids parameter pairs with one
RomVisibilityFilter that builds the WHERE clauses and checks loaded ROMs,
so a new visibility rule (the age-rating cap for #2013) lands in one place.
No behaviour change; the visibility-filtered queries send the same SQL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Wc3NzFkv97CXavLyZg5kJE
2026-10-03 10:46:47 -04:00
Sam Dornan
5a6c895d33 chore(mypy): give every generic its type arguments (#4818)
* chore(mypy): switch to strict mode with listed exceptions

Replace the hand-picked flags with `strict = True`, turning off only the
four flags that aren't clean yet (disallow_any_generics,
warn_return_any, disallow_untyped_calls, disallow_untyped_decorators).
Any other strict flag, including those future mypy releases add to the
preset, is on by default.

That turns on no_implicit_reexport, strict_equality and extra_checks:
- Import each name from the module that defines it. About 240 test
  sites patched a dependency through the module that imported it
  (`scan_module.fs_rom_handler`); they now import the same object from
  its source, so every patch targets what it did before. Tests that
  replace a module attribute are unchanged.
- handler.streaming.memory_cards re-exports store_memory_card_version
  explicitly, since endpoints call it there and tests patch it there.
- mutagen gets implicit_reexport, as it re-exports without __all__.
- Test comparisons build typed values (CoverResult, a typed expected
  dict, enum .value) and the CORS lookup casts for its identity check.
- One ss_handler ** spread keeps a coded ignore: extra_checks wants its
  NotRequired dump_* keys spelled out, and the media dict never has them.

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

* chore(mypy): give every generic its type arguments

Drop disallow_any_generics from the strict-mode exceptions and fix the
347 bare generics it reports, 230 of them in app code.

- Bare `dict` becomes `dict[str, Any]`: update payloads, raw provider
  JSON and endpoint bodies map string keys to mixed values, so the Any is
  real and now written down. The OpenAPI document is unchanged.
- Rom query filters take and return RomSelect; _music_facet_joins and
  _exclude_hidden are generic over the Select they're given, and
  _build_hash_selects returns id-only selects.
- Redis clients are typed by what they return: the decoding caches are
  Redis[str], the RQ connection and binary cache Redis[bytes].
- The rest get explicit parameters: Row, Pattern, ColumnElement,
  QueryableAttribute, SpooledTemporaryFile, Task, Future and friends.

Precise types reached callers that had been getting Any, which surfaced:
- The LaunchBox cache writer is fed binary-cache pipelines.
- The flashpoint and IGDB request helpers return raw JSON of varying
  shape, not always a dict.
- The rom search endpoint returned dicts under a list[SearchRomSchema]
  annotation; it now validates them into that schema.
- The audit filter's id subquery selects strings.
- In tests the binary cache is the non-decoding fake shared with
  async_cache, so it is cast to Redis[bytes] rather than changed.

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

* test(upload): assert cleanup against the patched upload directory

The 409 test checked config's ROM_UPLOAD_TMP_BASE while the fixture patches
the endpoint's copy to tmp_path/uploads, so it passed even if cleanup failed.

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

* chore(mypy): keep the row type through the ROM filter helpers

filter_roms and its helpers also receive select(Rom.id) membership queries,
so they now take and return the caller's Select type instead of narrowing to
RomSelect. merged_ra_metadata mixes scalar and list values.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 16:32:29 -05:00
Sam Dornan
7dd35aa139 fix(sync): give a sync session the life of one launch, and drop the dead play-session link (#4670) 2026-09-25 10:14:09 -04:00
zurdi
a779fa41f7 fix(audit): apply the second pr-ready code review
- Re-measure the phone event rows whenever a web font finishes loading,
  and when a scrollbar narrows the rows, not only at mount.
- Log only the kind of an audit claim key when Redis fails, since a
  failed sign-in's key holds the text typed as the username.
- Make play-session ingest take the caller's permissions explicitly, so
  no caller skips the hidden-rom check by leaving them out.
- Read an empty collection cover URL as no cover, as the other fields do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 10:18:57 +02:00
zurdi
5cccceea60 fix(audit): close the gaps left open by the pr-ready review
- A failed login keeps the attempted username only when it names an
  account, so a password typed into the username box is never stored.
- Gunicorn trusts X-Forwarded-For only from loopback and private ranges
  (FORWARDED_ALLOW_IPS, documented in env.template), so a client can no
  longer choose the address the audit log and rate limits see.
- A player's fetch (purpose=play) is recorded as rom.player_load instead
  of being skipped, so the marker can't hide a download.
- Play-session ingest treats a rom hidden from the caller as unknown, so
  its session and rom.play event don't name it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 08:08:53 +02:00
zurdi
283c92c278 feat(audit): record downloads and plays
A ROM, file or bulk download is recorded once per caller within ten
minutes, and only when a transfer starts from the first byte, so range
requests and retries don't multiply it. In-browser players mark their
fetch with purpose=play, and the session they report becomes a rom.play
event instead. Feeds and QR links still count as downloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 01:14:34 +02:00
Georges-Antoine Assi
58ec1c4aa8 feat(v2): drive rom_user status from play sessions, not launch write
Move the per-play status update (last_played, now_playing, and the
finished/empty -> incomplete rewind) off the optimistic launch-time write
and onto play-session ingest, so it reflects real play and is recorded once.

Backend: ingest now updates rom_user status when a session is the newest
play, leaving deliberate statuses (completed_100 / retired / never_playing)
untouched and skipping backfilled older sessions so they can't resurrect
now_playing.

Frontend: new usePlaySession composable records a session and ingests it on
exit; wired into Ruffle and Stream. EmulatorJS already ingests via the
embedded v1 Player, so its launch-time recordLaunch is dropped. The dead
recordLaunch / applyLaunchStatus helpers are removed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 15:56:28 -04:00
Georges-Antoine Assi
4e5ee69343 more simplify 2026-04-06 22:29:55 -04:00
Georges-Antoine Assi
b2e1e094f7 some simplification 2026-04-06 21:53:49 -04:00
Georges-Antoine Assi
ae03b0b322 ingest playtime with sync sessions 2026-04-06 21:32:13 -04:00