The rationale for the locking scheme lives in the migration docstring and the
PR; the code only needs the part a reader cannot recover from it.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Review of the artwork-provenance work turned up two gaps behind the cleanup.
The new skip gate compared files on disk against the number of urls, so a
permanently dead url held the count below the target forever and every scan
refetched the entire set. Going index by index refetches only what is absent,
and lets `_store_screenshot` report success instead of the caller stating the
file back off the disk it just wrote.
The SGDB block still read `path_cover_s` to decide whether a cover was hand
supplied, the inferred marker `locked_fields` exists to replace. That also
shielded scraped covers from a better ranked source, which is the behaviour
this branch set out to fix, so it now asks the lock like the block above it.
The rest is cleanup: drop the dead `screenshots_exist`, give the column one
normal form across its writers, hoist the duplicated clear-out dict in
`delete_rom_manuals`, and drop the blanket backfill UPDATE, since a NULL
already reads as "no locks" everywhere.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Unify manuals and walkthroughs on one document model instead of a
separate walkthrough subsystem. Walkthroughs are RomFiles under a new
WALKTHROUGH category with an optional RomFileDocMeta provenance sidecar,
and reading progress is a per-user RomFileUser row keyed on rom_file_id
so the same mechanism covers manuals and walkthroughs.
Backend:
- models: RomFileCategory.WALKTHROUGH, DocSource, RomFileDocMeta,
RomFileUser; migration 0110 (enum value + two tables, cross-DB)
- serve .txt/.html documents inline (HTML under a sandboxing CSP);
add .txt to allowed manual files
- endpoints: walkthrough upload / GameFAQs fetch / delete, and per-user
reading-progress GET (ROMS_READ) / PUT (ROMS_USER_WRITE, like notes, so a
kiosk guest capped to the read scopes cannot write)
- last_page is range-checked, so an out-of-range value is a 400 rather than
an integer column overflow
- the guide body is read under the size cap instead of being buffered in
full and truncated afterwards
- GameFAQs import extracts text only (stored as .txt); no remote HTML is
persisted or served. Host-allowlisted on top of the SSRF-safe client
- a Cloudflare bot challenge is detected and reported as "open it in your
browser and upload the text" instead of an opaque 403
- reading-progress upsert retries as an update on a unique-constraint
race, so concurrent saves for one user/file can't 500
- a GameFAQs guide is removed from disk again if indexing it fails,
rather than being left unreferenced
- tests for CRUD, progress, the GameFAQs parser/URL validation, and
hidden-rom masking on every walkthrough route
Frontend (v2):
- TextViewer (.txt/.html), useReadingProgress composable, WalkthroughSubtab
(upload + add-from-GameFAQs-URL + delete + progress), wired into MediaTab
- ManualSubtab renders .txt manuals; walkthrough category surfaced in
FilesTab; regenerated types; i18n keys across all locales
- a pending scroll position is committed before the viewer follows a new
document, so switching files mid-debounce no longer drops it
- WalkthroughSubtab gates upload, the GameFAQs URL field, and delete on
useCan("rom.edit"), as ManualSubtab already does
AI assistance: implemented with Claude Code (Opus 4.8). The data-model
design, backend, migration, tests, and v2 UI were AI-authored under human
direction. Alternative approach to #2892.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The name claimed a locked cover surviving an unmatch, but the test sets
no lock and performs no unmatch. It cannot: get_cover takes url_cover as
an argument and never reads locked_fields, so an empty url is how a lock
reaches this layer. Setting one on the mock would imply a coupling that
does not exist.
Renamed to describe the behaviour it does cover, and the comment now
points at the test carrying the other half of the chain.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
From review. get_rom_screenshots recorded a path for every url whether or
not the download landed, pointing the database at files that were never
written. Only record paths that made it to disk, and decide the early
return by counting files on disk rather than trusting the recorded list,
so a set left short by a failed run is retried instead of being frozen by
an unchanged url set.
The existing with-urls test asserted the old behaviour with a stand-in
that wrote nothing, so it now writes the files it claims to store.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
_atomic_write cleaned up in `except Exception`, which does not catch
CancelledError. Stopping a scan mid-download therefore stranded a
`.romm_tmp_*` file per cancelled transfer. Catch BaseException instead.
This also covers uploads, which have always gone through this path.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YKbk4cDmdKKMcBxGmsRVT5
Streamed downloads opened the destination directly, so an interrupted
transfer truncated the file in place. A truncated file is worse than a
missing one: it still satisfies the *_exists checks, so later scans skip
it and never refetch. The error paths cleaned it up, but only when the
process survived to run them, which a SIGKILL or host reboot does not.
write_file_streamed now writes to a temp file in the destination
directory and renames it over the target once the caller's block
completes, reusing the _atomic_write helper uploads already use. The
handle closes before the rename, so the target never sees a partial
flush.
The _discard_partial_file calls that followed a streamed write are gone.
There is no longer a partial file to remove, and the target now holds
either nothing or the previous good copy, which those calls would
delete. Refreshing a cover no longer costs the existing one when the
transfer dies.
The two disk-full tests patched write_file_streamed itself, so they were
asserting against the non-atomicity this removes. They now fail the
write from the response stream and exercise the real path.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
(cherry picked from commit 9b81fef29564d053c0ba4bb21f2192e0b9dc1f50)
get_cover() called _store_cover() once for CoverSize.SMALL and once for
CoverSize.BIG with the same URL, and each call performed a complete fetch.
The small cover has no distinct source: it is the large image downloaded in
full and then resized in place, so the second request only re-retrieved bytes
already on disk. Every cover cost twice the bandwidth, doubled the load on
every provider, and on ScreenScraper spent a second request from the
account's quota, since media is served from the same authenticated api2
endpoints as metadata lookups.
_store_cover() now takes no size: it fetches once into big.png and derives
small.png from it, the way store_artwork() already did.
A missing small cover no longer triggers a fetch at all. get_cover()
downloads only when overwriting or when the large cover is absent, and
otherwise rebuilds the small one from the large one already on disk via
_derive_small_cover(). That drops the half-written pair case from one request
to none, and keeps a good large cover out of the blast radius of a download
that might fail. The derive path resolves its source through _get_cover_path,
so an uploaded big.jpg or a converted big.webp yields a matching small file
rather than assuming a .png extension.
Failure paths now clean up both destinations. Undecodable bytes are
discarded rather than left on disk, where they satisfy cover_exists() and
stop any later scan from refetching a working cover, and a discarded
chroma-key placeholder also clears a small cover left by an earlier scan.
_derive_small_cover() is the exception: it did not write those bytes, so a
large cover it cannot decode is left in place and only the partial small one
is dropped.
Fixes#4102
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A *_path with no matching *_url can never be fetched, so it must not
survive when the file it names is missing. No provider produces that
state today (each gates the path on the URL), but store_metadata_media
now guarantees every path it leaves behind points at a real file.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Metadata providers record where each media file should live at match time,
and the path was persisted whether or not the download produced a file. A
non-200 response, an unexpected content type, a transport error, or a
discarded ScreenScraper chroma-key placeholder all leave nothing on disk,
so the ROM kept pointing at a file that was never there.
Local gamelist/Pegasus exports then warned once per ROM per phantom asset
and left an empty assets/<subdir>/ behind, and the frontend built box-face
URLs that 404.
store_media_file now reports whether the file is on disk afterwards, and
store_metadata_media clears the *_path entry for anything that didn't land
while keeping the *_url so a later scan can retry. Both exporters skip a
missing source quietly instead of warning, and no longer create the
destination directory before knowing the source exists.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The last platform's quota readout and the end-of-scan summary both call
_log_ss_quota, so a completed scan printed the same numbers twice in a row.
Skip a line identical to the previous one, resetting at the start of each scan
so a new run always reports.
ScreenScraper returns the account's allowances on every response, but only
maxthreads was read. Use the rest:
- Pace requests against the reported maxrequestspermin (falling back to the
documented threads x 50), so fast lookups can no longer overrun the
per-minute budget without ever exceeding the thread cap.
- Report the remaining daily and unrecognized-ROM quotas after each platform
and at the end of a scan, and warn once when either drops below 10%.
- Hint once per scan when SCAN_WORKERS is below the thread allowance (scans
slower than the account allows) or above it (extra workers just queue).
- Raise a distinct error when a request is refused twice for exceeding the
rate, so the ROM is reported as skipped in the scan summary instead of being
saved with no ScreenScraper data.
- Route ScreenScraper media downloads (covers, screenshots, manuals, mixed
media) through the same limiters, since they are api2 endpoints that count
against the same allowances, and derive their timeout from the account's
advertised download speed.
Fixes#3978
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The streamed resource downloads wrapped their writes in `except
httpx.TransportError`, which does not cover the `OSError` raised by
`f.write()` when the filesystem is out of space. The error escaped the
handler and the partially written file stayed on disk.
A truncated file is worse than a missing one: it satisfies the
`cover_exists` / `screenshots_exist` checks and the `file_exists` guards
in `store_ra_badge` and `store_media_file`, so later scans skip it and
never refetch it. The artwork stays permanently corrupt.
Catch `OSError` on every resource write path (covers, screenshots,
manuals, RA badges, media files and uploaded artwork) and remove the
partial file so the next scan refetches it. A stream that drops
mid-transfer leaves the same truncated file, so the transport-error
branches now discard it too. The cleanup helper swallows its own
`OSError` so it can never mask the original failure.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
ScreenScraper serves a solid chroma-key green (#00FF00) square when a
requested image (box-2D front/back/side) doesn't exist. RomM stored it as
real artwork, so the v2 3D box painted a bright green face and the flat
cover showed green in the gallery.
Detect the placeholder at download time and drop it: covers fall back to
the procedural placeholder, and a discarded box-2D face falls back to the
dark cover placeholder the box already paints (rather than bright green).
- Add _is_chroma_key_placeholder + _discard_if_chroma_key in the resources
handler; wire into _store_cover and store_media_file.
- store_media_file also cleans up pre-existing green files on rescan.
Generated-By: PostHog Code
Task-Id: 5534668f-a2b6-4575-b6c1-73dcd965062c
Discover manuals only for the allowed extensions (.pdf, .md) instead of
globbing {rom.id}.*, so stray files (e.g. {rom.id}.part) are never treated
as a manual. Select deterministically by newest mtime when multiple allowed
manuals coexist. Drop the redundant .md token from the frontend accept lists.
Generated-By: PostHog Code
Task-Id: 1d785bcc-ea5c-4b99-b619-73625a9e218c