15 Commits

Author SHA1 Message Date
Georges-Antoine Assi
38d0a671df fix(archives): fix zipfile writes where zipfile_inflate64 is imported (#5678)
zipfile_inflate64 replaces zipfile._get_compressor with a one-argument
wrapper, while CPython 3.13+ passes compresslevel too, so every zip write
raises TypeError once it is imported. Each writer had to call
ensure_zipfile_writable() first, and a new writer that forgot it broke.

Wrap the patched function right after the import in utils/archives.py,
the only module that imports zipfile_inflate64, and drop the per-site
calls and the helper.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 07:03:48 -05:00
Sam Dornan
3750d6ff70 chore(mypy): require full annotations outside tests, type the setup responses (#4795) 2026-09-26 15:31:00 -04:00
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
Georges-Antoine Assi
2d89f12b1f refactor(download): tighten the zip cache comments and test typing
Cut the docstring paragraphs down to the one fact each reader cannot get
from the code, name the readability test after the helper it exercises, and
give the flock stand-in and the zip factory real signatures.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 09:58:30 -04:00
Georges-Antoine Assi
0a0ed62a4c refactor(download): return the stat alongside the cached ZIP path
get_cached_zip already stats the archive to decide whether it exists, so
hand that stat back instead of making head_rom_content take another one for
Content-Length. A HEAD on a cached multi-file ROM now costs one stat.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 09:49:50 -04:00
Georges-Antoine Assi
352473d28c refactor(download): share the served-file mode and slim the zip cache
Give 0o644 a single home in utils/filesystem as SERVED_FILE_MODE, used by
both the ZIP cache and FSHandler._atomic_write. Collapse the mode repair to
one call site behind a single stat per cache hit, close the temp descriptor
unconditionally, and log the build where the namespace is already in scope.

Deduplicate the test fixtures and drive the concurrency test with a barrier
on flock instead of a sleep, so the race is guaranteed rather than timed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 09:48:03 -04:00
nendo
96bbc05ff6 fix(download): close the temp descriptor when chmod fails 2026-09-03 03:54:27 +09:00
nendo
cb562ec1b8 fix(download): make cached zips readable by nginx and serialize their builds 2026-09-02 20:37:30 +09:00
Georges-Antoine Assi
144e3adda3 fix(download): restore the zip writer for dev-mode multi-file downloads
The dev-mode in-memory ZIP branch of `get_rom_content` never called the
`zipfile._get_compressor` shim, so `zipfile-inflate64`'s one-arg override
raised a `TypeError` inside `_ZipWriteFile.__init__`. That leaves
`ZipFile._writing` stuck `True`, and `__exit__` masks the real error with
"Can't close the ZIP file while there is an open writing handle on it",
returning a 500 for any multi-file ROM.

The shim is now shared with the endpoint, so it drops its underscore.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-29 09:24:37 -04:00
Georges-Antoine Assi
fe32918b46 refactor: simplify ZIP cache range-request support
- Centralize the cache-hit-or-build-then-fallback flow into
  resolve_cached_zip(), collapsing three near-identical endpoint
  blocks; add ZipFileEntry.from_rom_file() factory.
- Use get_ttl_hours() (now size-based) in cleanup_stale_zips instead
  of inlining the tier decision.
- Drop on-demand LRU eviction and the 2x space guard; a full disk now
  falls back to mod_zip streaming via the existing build try/except.
- Replace the per-request importlib.reload(zipfile) with a one-time,
  thread-safe shim that fixes zipfile_inflate64's _get_compressor
  signature without a global module reload.
- Simplify get_cache_key by folding the empty-entries case into the
  normal path (non-empty keys unchanged).

Generated-By: PostHog Code
Task-Id: e68b880f-34d8-4bf6-8cd0-886ef2caecb4
2026-07-16 21:55:28 -04:00
nendo
6ffb8ac891 Address Copilot review feedback
- Use zipfile.ZipFile after reload instead of stale direct import
- Use ZipFile.write() for streaming (reload fixes CPython 3.13 bug)
- Wrap cache build in try/except, fall back to mod_zip on failure
- Guard empty entries list in get_cache_key
- Hash bulk namespace to avoid ENAMETOOLONG with 100 ROM IDs
- Use MagicMock for sync unschedule method in tests
- Mock _get_available_space in eviction tests to force eviction path
- Use sparse file (truncate) for large file TTL test
- Add tests for get_bulk_namespace and empty entries
2026-03-24 08:11:55 +09:00
nendo
3f47af1110 Work around zipfile monkey-patch breaking writestr on CPython 3.13
A third-party library in the import chain replaces
zipfile._get_compressor with an incompatible signature. Reload
the zipfile module before building cached ZIPs to restore it.
2026-03-24 07:00:13 +09:00
nendo
18864a54f9 Add bulk download caching, LRU eviction, tiered TTL
- Bulk /download endpoint now caches ZIPs for Range requests (max 100 ROMs)
- LRU eviction frees space by removing oldest cached ZIPs (>1h old)
- Tiered TTL: 48h default, 12h for ZIPs over 8GB
- Generalize cache paths from rom_id to namespace (supports bulk-{ids})
2026-03-24 06:34:26 +09:00
nendo
476f3ef6d6 Add tests, fix streaming write and code standards
- Use ZipFile.write() instead of reading entire files into memory
- Extract magic numbers to module constants
- Use hl() for log message highlighting
- Tests for zip_cache, m3u, and cleanup task using mocker fixture
2026-03-24 06:13:45 +09:00
nendo
0273d5832c Support Range requests for multi-file ROM downloads
Cache ZIPs to disk on Range requests so nginx can serve 206 natively.
Non-Range requests still stream via mod_zip as before.

Refs: rommapp/romm#3160
2026-03-24 05:56:15 +09:00