Files
romm/backend/utils/zip_cache.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

283 lines
8.6 KiB
Python

from __future__ import annotations
import contextlib
import dataclasses
import fcntl
import functools
import hashlib
import os
import stat
import tempfile
import time
import zipfile
from collections.abc import Generator
from pathlib import Path
from typing import TYPE_CHECKING, NamedTuple
import anyio
from config import LIBRARY_BASE_PATH, ZIP_CACHE_PATH
from logger.formatter import highlight as hl
from logger.logger import log
from utils.filesystem import SERVED_FILE_MODE
if TYPE_CHECKING:
from models.rom import RomFile
CACHE_KEY_LENGTH = 16
SECONDS_PER_HOUR = 3600
LARGE_ZIP_THRESHOLD_BYTES = 8 * 1024 * 1024 * 1024 # 8 GB
DEFAULT_TTL_HOURS = 48
LARGE_ZIP_TTL_HOURS = 12
BULK_CACHE_MAX_ROMS = 100
BULK_NAMESPACE_PREFIX = "bulk"
@dataclasses.dataclass(frozen=True)
class ZipFileEntry:
"""Thread-safe snapshot of a RomFile's download-relevant data."""
download_name: str
full_path: str
file_size_bytes: int
updated_at_epoch: float
@classmethod
def from_rom_file(cls, file: RomFile, hidden_folder: bool) -> ZipFileEntry:
return cls(
download_name=file.file_name_for_download(hidden_folder),
full_path=file.full_path,
file_size_bytes=file.file_size_bytes,
updated_at_epoch=file.updated_at.timestamp(),
)
def get_cache_key(
namespace: str,
entries: list[ZipFileEntry],
hidden_folder: bool = False,
) -> str:
"""Deterministic cache key derived from content state."""
parts = [
namespace,
str(hidden_folder),
str(max((e.updated_at_epoch for e in entries), default=0.0)),
]
for e in sorted(entries, key=lambda x: x.download_name):
parts.append(f"{e.download_name}:{e.file_size_bytes}")
return hashlib.sha256("|".join(parts).encode()).hexdigest()[:CACHE_KEY_LENGTH]
def get_bulk_namespace(rom_ids: list[int]) -> str:
"""Deterministic namespace for bulk downloads, hashed to avoid ENAMETOOLONG."""
id_str = "-".join(str(i) for i in sorted(rom_ids))
id_hash = hashlib.sha256(id_str.encode()).hexdigest()[:CACHE_KEY_LENGTH]
return f"{BULK_NAMESPACE_PREFIX}-{id_hash}"
def _cache_dir(namespace: str) -> Path:
return Path(ZIP_CACHE_PATH) / namespace
def _cache_file(namespace: str, cache_key: str) -> Path:
return _cache_dir(namespace) / f"{cache_key}.zip"
class CachedZip(NamedTuple):
path: Path
stat: os.stat_result
def get_cached_zip(namespace: str, cache_key: str) -> CachedZip | None:
"""Return the cached ZIP and the stat that found it, or None if it is missing."""
path = _cache_file(namespace, cache_key)
try:
file_stat = os.stat(path)
except OSError:
return None
_ensure_nginx_readable(path, stat.S_IMODE(file_stat.st_mode))
return CachedZip(path, file_stat)
def _ensure_nginx_readable(path: Path, mode: int) -> None:
"""Widen a legacy owner-only archive so nginx can read it."""
if mode & SERVED_FILE_MODE == SERVED_FILE_MODE:
return
try:
path.chmod(mode | SERVED_FILE_MODE)
except OSError as e:
log.warning(f"Cached ZIP {hl(path.name)} may be unreadable by nginx: {e}")
@contextlib.contextmanager
def _namespace_build_lock(namespace_dir: Path) -> Generator[None]:
"""Serialize builds within a namespace across threads and worker processes."""
fd = os.open(namespace_dir, os.O_RDONLY)
try:
fcntl.flock(fd, fcntl.LOCK_EX)
yield
finally:
os.close(fd)
def ensure_zipfile_writable() -> None:
"""Restore ``zipfile._get_compressor`` to a writable signature.
``zipfile_inflate64`` (imported in ``handler/filesystem/roms_handler.py``
to support Enhanced Deflate) replaces ``zipfile._get_compressor`` with a
wrapper that only accepts ``compress_type``. CPython 3.13 calls it with
``(compress_type, compresslevel)``, so ``ZipFile.write()``/``writestr()``
raise ``TypeError``. Wrap it once with a signature-compatible shim that
drops the extra arg, matching inflate64's own behavior (it already ignores
``compresslevel``). Idempotent and safe to call from any thread.
"""
current = zipfile._get_compressor # type: ignore[attr-defined]
if getattr(current, "_romm_compresslevel_safe", False):
return
# Probe with two args: the stdlib accepts them, inflate64's wrapper does not.
try:
current(zipfile.ZIP_STORED, None)
return
except TypeError:
pass
@functools.wraps(current)
def _get_compressor(compress_type, compresslevel=None):
return current(compress_type)
_get_compressor._romm_compresslevel_safe = True # type: ignore[attr-defined]
zipfile._get_compressor = _get_compressor # type: ignore[attr-defined]
def build_cached_zip(
namespace: str,
entries: list[ZipFileEntry],
m3u_content: bytes | None,
m3u_filename: str | None,
cache_key: str,
) -> Path:
"""Build a ZIP_STORED archive on disk and return its path.
Written to a temp file in the same directory and renamed, so a partial
file is never served.
"""
target = _cache_file(namespace, cache_key)
target.parent.mkdir(parents=True, exist_ok=True)
with _namespace_build_lock(target.parent):
if cached := get_cached_zip(namespace, cache_key):
return cached.path
_write_cached_zip(target, entries, m3u_content, m3u_filename)
log.info(f"Built cached ZIP in {hl(namespace)}: {hl(target.name)}")
return target
def _write_cached_zip(
target: Path,
entries: list[ZipFileEntry],
m3u_content: bytes | None,
m3u_filename: str | None,
) -> None:
fd, tmp_path = tempfile.mkstemp(dir=target.parent, suffix=".tmp")
os.close(fd)
try:
os.chmod(tmp_path, SERVED_FILE_MODE)
ensure_zipfile_writable()
with zipfile.ZipFile(tmp_path, "w") as zf:
for entry in entries:
src = Path(LIBRARY_BASE_PATH) / entry.full_path
zf.write(src, arcname=entry.download_name)
if m3u_content is not None and m3u_filename is not None:
zf.writestr(m3u_filename, m3u_content)
os.rename(tmp_path, target)
except BaseException:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
raise
def get_zip_redirect_path(namespace: str, cache_key: str) -> Path:
"""Return the nginx-internal URL path for the cached ZIP."""
return Path(f"/cache/zips/{namespace}/{cache_key}.zip")
async def resolve_cached_zip(
namespace: str,
entries: list[ZipFileEntry],
*,
hidden_folder: bool = False,
m3u_content: bytes | None = None,
m3u_filename: str | None = None,
log_label: str,
) -> Path | None:
"""Return the nginx redirect path for a cached ZIP, building it on demand.
Returns ``None`` when there is nothing to cache or the build fails, letting
the caller fall back to mod_zip streaming. A full disk simply surfaces as a
build failure here, so no separate space check is needed.
"""
if not entries:
return None
cache_key = get_cache_key(namespace, entries, hidden_folder)
if get_cached_zip(namespace, cache_key):
return get_zip_redirect_path(namespace, cache_key)
try:
await anyio.to_thread.run_sync(
functools.partial(
build_cached_zip,
namespace=namespace,
entries=entries,
m3u_content=m3u_content,
m3u_filename=m3u_filename,
cache_key=cache_key,
)
)
except Exception as e:
log.warning(
f"Failed to build cached ZIP for {log_label}, falling back to streaming: {e}"
)
return None
return get_zip_redirect_path(namespace, cache_key)
def get_ttl_hours(size_bytes: int) -> int:
"""Return the appropriate TTL based on ZIP size."""
if size_bytes > LARGE_ZIP_THRESHOLD_BYTES:
return LARGE_ZIP_TTL_HOURS
return DEFAULT_TTL_HOURS
def cleanup_stale_zips() -> int:
"""Remove cached ZIPs that have exceeded their TTL.
Files larger than LARGE_ZIP_THRESHOLD_BYTES use LARGE_ZIP_TTL_HOURS,
all others use DEFAULT_TTL_HOURS.
"""
cache_root = Path(ZIP_CACHE_PATH)
if not cache_root.exists():
return 0
now = time.time()
deleted = 0
for ns_dir in cache_root.iterdir():
if not ns_dir.is_dir():
continue
for zip_file in ns_dir.glob("*.zip"):
file_stat = zip_file.stat()
cutoff = now - (get_ttl_hours(file_stat.st_size) * SECONDS_PER_HOUR)
if file_stat.st_mtime < cutoff:
zip_file.unlink()
deleted += 1
if ns_dir.exists() and not any(ns_dir.iterdir()):
ns_dir.rmdir()
return deleted