diff --git a/Dockerfile b/Dockerfile index a228704e7..dc8282eba 100644 --- a/Dockerfile +++ b/Dockerfile @@ -51,6 +51,23 @@ RUN make HAVE_CHD=1 -f ./Makefile.RAHasher \ && cp ./bin64/RAHasher /usr/bin/RAHasher RUN rm -rf /tmp/RALibretro +# Install rom-converto (optional ROM conversion/decryption/metadata tool). +# Pinned release; checksums are the upstream-published sha256 of the musl +# builds, which are fully static so they run on this glibc image. Bump the +# version and both sums together. +ARG TARGETARCH +RUN ROM_CONVERTO_VERSION=v0.21.0 \ + && case "${TARGETARCH}" in \ + amd64) rc="linux-x64-musl"; sum="d6446fac50ca2dae2a3702351bc2c409a19f8a4f7a91ae838283ebf5f151e578" ;; \ + arm64) rc="linux-arm64-musl"; sum="3ef3414ad425fb222f647ef0f3e74122077721a046eb07256c6d870b007b3c2e" ;; \ + *) echo "unsupported TARGETARCH: ${TARGETARCH}" && exit 1 ;; \ + esac \ + && curl -fsSL -o "/tmp/rom-converto-cli-${rc}" \ + "https://github.com/DevYukine/rom-converto/releases/download/${ROM_CONVERTO_VERSION}/rom-converto-cli-${rc}" \ + && echo "${sum} /tmp/rom-converto-cli-${rc}" | sha256sum -c --status \ + && install -m 0755 "/tmp/rom-converto-cli-${rc}" /usr/bin/rom-converto \ + && rm -f "/tmp/rom-converto-cli-${rc}" + # Install frontend dependencies COPY frontend/package.json /app/frontend/ WORKDIR /app/frontend diff --git a/backend/adapters/services/rom_converto.py b/backend/adapters/services/rom_converto.py new file mode 100644 index 000000000..f161d06e8 --- /dev/null +++ b/backend/adapters/services/rom_converto.py @@ -0,0 +1,342 @@ +import asyncio +import json +import shutil +from dataclasses import dataclass +from pathlib import Path +from typing import Final + +from config import ( + ROM_CONVERTO_ENABLED, + ROM_CONVERTO_MAX_CONCURRENCY, + ROM_CONVERTO_PATH, + ROM_CONVERTO_TIMEOUT, +) +from logger.formatter import LIGHTMAGENTA +from logger.formatter import highlight as hl +from logger.logger import log +from utils.platform_slugs import UniversalPlatformSlug as UPS + +# Platform slugs whose files rom-converto's `info` can identify with a +# title id or serial. Wider than the conversion targets on purpose: +# extraction only reads headers, so every inspector counts. +CONVERTO_PLATFORM_SLUGS: Final[frozenset[str]] = frozenset( + { + UPS.N3DS, + UPS.NDS, + UPS.PSP, + UPS.PSVITA, + UPS.PSX, + UPS.PS2, + UPS.PS3, + UPS.NGC, + UPS.WII, + UPS.WIIU, + UPS.SWITCH, + UPS.SWITCH_2, + UPS.XBOX, + UPS.XBOX360, + } +) + +# The capabilities probe must never hang scan/download paths; a real +# manifest print is instant. +_PROBE_TIMEOUT_SECONDS = 30 + +_STDERR_TAIL_BYTES = 400 + + +class RomConvertoError(Exception): ... + + +class RomConvertoBinaryNotFoundError(RomConvertoError): ... + + +class RomConvertoTimeoutError(RomConvertoError): ... + + +class RomConvertoOperationError(RomConvertoError): + """A conversion command exited nonzero; carries the CLI's diagnostic.""" + + def __init__(self, message: str, returncode: int, stderr: str): + super().__init__(message) + self.returncode = returncode + self.stderr = stderr + + +@dataclass(frozen=True) +class RomConvertoInfo: + kind: str + # Rendered the way sigil renders the same platform's id, so either + # extractor can fill `Rom.title_id` interchangeably. + title_id: str | None + title_version: int | None + + +@dataclass(frozen=True) +class Operation: + """One rom-converto subcommand that turns a file of `input_exts` into + the `target` format. `argv` is the subcommand plus fixed flags; the + source and output paths are appended positionally.""" + + target: str + platforms: frozenset[str] + argv: tuple[str, ...] + input_exts: frozenset[str] + # None keeps the input's extension (decrypt/encrypt rewrite in place). + output_ext: str | None + + def output_name(self, src: Path, input_ext: str) -> str: + """`src` renamed to the output extension; `input_ext` is the + lowercased extension `resolve_operation` matched.""" + cut = len(src.name) - len(input_ext) + return f"{src.name[:cut]}{self.output_ext or src.name[cut:]}" + + +def _op( + target: str, + platforms: set[str], + argv: str, + input_exts: str, + output_ext: str | None, +) -> Operation: + return Operation( + target=target, + platforms=frozenset(platforms), + argv=tuple(argv.split()), + input_exts=frozenset(input_exts.split()), + output_ext=output_ext, + ) + + +_DVD_PLATFORMS = {UPS.PSP, UPS.PS2} +_CD_PLATFORMS = {UPS.PSX, UPS.SATURN, UPS.SEGACD, UPS.DC} + +# Every single-file operation the CLI offers, keyed by the target a platform +# can be configured with. Directory-shaped operations (Wii U packs, Switch +# merge/split, the `extract` family, Xbox 360 GoD) have no single output +# file to serve, so they are not here. +OPERATIONS: Final[tuple[Operation, ...]] = ( + # 3DS + _op("decrypted", {UPS.N3DS}, "ctr decrypt", ".cia .3ds .cci .cxi", None), + _op("encrypted", {UPS.N3DS}, "ctr encrypt", ".cia .3ds .cci .cxi", None), + _op("z3ds", {UPS.N3DS}, "ctr compress", ".cia", ".zcia"), + _op("z3ds", {UPS.N3DS}, "ctr compress", ".cci .3ds", ".zcci"), + _op("z3ds", {UPS.N3DS}, "ctr compress", ".cxi", ".zcxi"), + _op("cia", {UPS.N3DS}, "ctr decompress", ".zcia", ".cia"), + _op("cia", {UPS.N3DS}, "ctr convert", ".3ds .cci", ".cia"), + _op("cci", {UPS.N3DS}, "ctr decompress", ".zcci", ".cci"), + _op("cci", {UPS.N3DS}, "ctr convert", ".cia", ".cci"), + # NDS + _op("decrypted", {UPS.NDS}, "nds decrypt", ".nds", None), + _op("encrypted", {UPS.NDS}, "nds encrypt", ".nds", None), + # Sony discs + _op("iso", _DVD_PLATFORMS, "cso decompress", ".cso .zso .dax", ".iso"), + # CD-mode CHDs extract to .bin/.cue, so only DVD platforms get this. + _op("iso", _DVD_PLATFORMS, "chd extract", ".chd", ".iso"), + _op("iso", _DVD_PLATFORMS | _CD_PLATFORMS, "cue to-iso", ".cue", ".iso"), + _op("iso", {UPS.PSP}, "psp to-iso", ".pbp", ".iso"), + _op("cso", _DVD_PLATFORMS, "cso compress --format cso", ".iso", ".cso"), + _op("cso", _DVD_PLATFORMS, "chd to-cso --format cso", ".chd", ".cso"), + _op("zso", _DVD_PLATFORMS, "cso compress --format zso", ".iso", ".zso"), + _op("zso", _DVD_PLATFORMS, "chd to-cso --format zso", ".chd", ".zso"), + _op("chd", _DVD_PLATFORMS | _CD_PLATFORMS, "chd compress", ".cue .iso", ".chd"), + _op("chd", _DVD_PLATFORMS, "cso to-chd", ".cso .zso .dax", ".chd"), + _op("decrypted", {UPS.PS3}, "ps3 decrypt", ".iso", None), + # GameCube / Wii + _op("rvz", {UPS.NGC}, "dol compress", ".iso .gcm", ".rvz"), + _op("rvz", {UPS.NGC}, "dol migrate", ".gcz .nkit.iso .nkit.gcz", ".rvz"), + _op("iso", {UPS.NGC}, "dol decompress", ".rvz", ".iso"), + _op("rvz", {UPS.WII}, "rvl compress", ".iso .wbfs", ".rvz"), + _op("rvz", {UPS.WII}, "rvl migrate", ".wia .gcz .nkit.iso .nkit.gcz", ".rvz"), + _op("iso", {UPS.WII}, "rvl decompress", ".rvz", ".iso"), + _op("wbfs", {UPS.WII}, "rvl decompress", ".rvz", ".wbfs"), + # Switch (prod.keys resolved by the CLI itself) + _op("nsz", {UPS.SWITCH, UPS.SWITCH_2}, "nx compress", ".nsp", ".nsz"), + _op("xcz", {UPS.SWITCH, UPS.SWITCH_2}, "nx compress", ".xci", ".xcz"), + _op("nsp", {UPS.SWITCH, UPS.SWITCH_2}, "nx decompress", ".nsz", ".nsp"), + _op("xci", {UPS.SWITCH, UPS.SWITCH_2}, "nx decompress", ".xcz", ".xci"), + # Xbox + _op("xiso", {UPS.XBOX}, "xbox convert", ".iso", ".xiso"), + _op("zar", {UPS.XBOX360}, "xenon compress", ".iso", ".zar"), +) + +# Platform slug -> the targets it can be configured with. +TARGETS_BY_PLATFORM: Final[dict[str, frozenset[str]]] = { + slug: frozenset(op.target for op in OPERATIONS if slug in op.platforms) + for slug in sorted({slug for op in OPERATIONS for slug in op.platforms}) +} + + +def resolve_operation( + platform_slug: str, target: str, file_name: str +) -> tuple[Operation, str] | None: + """The operation that brings `file_name` to `target` on this platform, + with the input extension it matched, or None when the file is already + there or no subcommand accepts it.""" + name = file_name.lower() + best: tuple[Operation, str] | None = None + for op in OPERATIONS: + if op.target != target or platform_slug not in op.platforms: + continue + for ext in op.input_exts: + # Prefer the longer extension so `.nkit.iso` is not read as `.iso`. + if name.endswith(ext) and (best is None or len(ext) > len(best[1])): + best = (op, ext) + return best + + +def _tail(text: str) -> str: + return text.strip()[-_STDERR_TAIL_BYTES:] + + +async def _run(argv: list[str], timeout_seconds: float) -> tuple[int, str, str]: + """Run a rom-converto subcommand and return (returncode, stdout, stderr).""" + binary = await asyncio.to_thread(shutil.which, ROM_CONVERTO_PATH) + if binary is None: + raise RomConvertoBinaryNotFoundError( + f"rom-converto binary not found at {ROM_CONVERTO_PATH}" + ) + proc = await asyncio.create_subprocess_exec( + binary, + *argv, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + try: + stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout_seconds) + except TimeoutError as err: + proc.kill() + # Drain the pipes so the transport closes instead of leaking its fds. + await proc.communicate() + raise RomConvertoTimeoutError( + f"rom-converto {' '.join(argv[:2])} timed out after {timeout_seconds}s" + ) from err + + return ( + proc.returncode or 0, + stdout.decode("utf-8", errors="replace"), + stderr.decode("utf-8", errors="replace"), + ) + + +def _first_str(data: dict, *keys: str) -> str | None: + for key in keys: + value = data.get(key) + if isinstance(value, str) and value: + return value + return None + + +def _title_id(kind: str, flat: dict) -> str | None: + if kind in ("dol", "rvl"): + # Sigil keys GameCube and Wii by the hex-encoded 4-char game id. + game_id = flat.get("game_id") + if isinstance(game_id, str) and len(game_id) >= 4: + return game_id[:4].encode("ascii", "replace").hex().upper() + return None + if kind == "wup": + title_id_hex = flat.get("title_id_hex") + return title_id_hex[-8:] if isinstance(title_id_hex, str) else None + if kind == "xbox": + return _first_str(flat, "title_id_code") + if kind == "xenon": + return _first_str(flat, "title_id_hex") + return _first_str(flat, "application_title_id_hex", "title_id", "game_code") + + +def _parse_info(payload: dict) -> RomConvertoInfo: + # `kind` is the serde tag of InfoResult. Consoles nest their header + # (Xbox `xbe`, 360 `xex`, Switch `full`, CHD/CSO inner disc `content`); + # top-level keys win on conflict. + flat = dict(payload) + for key in ("xbe", "xex", "full", "content"): + nested = payload.get(key) + if isinstance(nested, dict): + flat = {**nested, **flat} + kind = str(flat.get("kind") or "") + title_version = flat.get("title_version") + return RomConvertoInfo( + kind=kind, + title_id=_title_id(kind, flat), + title_version=title_version if isinstance(title_version, int) else None, + ) + + +class RomConvertoService: + """Service to inspect and convert ROMs using the rom-converto CLI.""" + + def __init__(self) -> None: + self._available: bool | None = None + self._probe_lock = asyncio.Lock() + # Each conversion reads and writes whole disc images. + self._convert_semaphore = asyncio.Semaphore(ROM_CONVERTO_MAX_CONCURRENCY) + + async def is_enabled(self) -> bool: + if not ROM_CONVERTO_ENABLED: + return False + async with self._probe_lock: + if self._available is not None: + return self._available + # A stale, corrupt, or wrong-arch binary passes which(); prove it + # runs once with the cheap capabilities manifest. A missing binary + # stays uncached so the integration picks it up without a restart. + try: + code, stdout, _ = await _run(["capabilities"], _PROBE_TIMEOUT_SECONDS) + except RomConvertoBinaryNotFoundError: + return False + if code != 0: + log.warning( + f"rom-converto at {hl(ROM_CONVERTO_PATH)} failed its capability " + f"probe (code {code}); disabling integration until restart" + ) + self._available = False + return False + try: + version = json.loads(stdout)["version"] + except (json.JSONDecodeError, KeyError, TypeError): + version = "unknown version" + log.info( + f"Detected {hl('rom-converto', color=LIGHTMAGENTA)} {hl(str(version))}" + ) + self._available = True + return True + + async def read_info(self, path: Path) -> RomConvertoInfo | None: + """Inspect a ROM with `rom-converto info --json`, or None when the + tool does not recognize the file.""" + log.debug( + f"Executing {hl('rom-converto', color=LIGHTMAGENTA)} info on {hl(str(path))}" + ) + code, stdout, stderr = await _run( + ["info", "--json", str(path)], ROM_CONVERTO_TIMEOUT + ) + if code != 0: + log.debug( + f"rom-converto info did not recognize {path} (code {code}): {_tail(stderr)}" + ) + return None + try: + payload = json.loads(stdout) + except json.JSONDecodeError: + log.debug(f"rom-converto info returned non-JSON output for {path}") + return None + if not isinstance(payload, dict): + return None + return _parse_info(payload) + + async def convert(self, operation: Operation, src: Path, out: Path) -> None: + """Run `operation` on `src`, writing `out`. Bounded by the service + semaphore and ROM_CONVERTO_TIMEOUT.""" + argv = [*operation.argv, str(src), str(out)] + async with self._convert_semaphore: + code, stdout, stderr = await _run(argv, ROM_CONVERTO_TIMEOUT) + if code != 0: + diagnostic = _tail(stderr) or _tail(stdout) + raise RomConvertoOperationError( + f"rom-converto {' '.join(operation.argv)} failed with code {code}: {diagnostic}", + returncode=code, + stderr=stderr, + ) + + +rom_converto_service = RomConvertoService() diff --git a/backend/alembic/versions/0122_add_rom_file_title_ids.py b/backend/alembic/versions/0122_add_rom_file_title_ids.py new file mode 100644 index 000000000..d57c61148 --- /dev/null +++ b/backend/alembic/versions/0122_add_rom_file_title_ids.py @@ -0,0 +1,38 @@ +"""Add the per-file title id columns on rom_files: title_id and title_version. + +Rom-level title_id landed in 0116_sigil_title_ids; these columns hold the +identity of every file in a multi-part rom, extracted by rom-converto. + +Revision ID: 0122_add_rom_file_title_ids +Revises: 0121_state_disc_file +Create Date: 2026-09-03 00:00:00.000000 + +""" + +import sqlalchemy as sa +from alembic import op # type: ignore[attr-defined] + +# revision identifiers, used by Alembic. +revision = "0122_add_rom_file_title_ids" +down_revision = "0121_state_disc_file" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.add_column( + "rom_files", + sa.Column("title_id", sa.String(length=100), nullable=True), + ) + # BigInteger: Switch title versions are u32 and can exceed signed int32. + op.add_column( + "rom_files", + sa.Column("title_version", sa.BigInteger(), nullable=True), + ) + op.create_index("idx_rom_files_title_id", "rom_files", ["title_id"], unique=False) + + +def downgrade() -> None: + op.drop_index("idx_rom_files_title_id", table_name="rom_files") + op.drop_column("rom_files", "title_version") + op.drop_column("rom_files", "title_id") diff --git a/backend/config/__init__.py b/backend/config/__init__.py index d4492555e..96ee317d4 100644 --- a/backend/config/__init__.py +++ b/backend/config/__init__.py @@ -64,6 +64,23 @@ ROM_PATCHER_MAX_CONCURRENCY: Final[int] = max( 1, safe_int(_get_env("ROM_PATCHER_MAX_CONCURRENCY"), 2) ) +# ROM CONVERTO +ROM_CONVERTO_ENABLED: Final[bool] = safe_str_to_bool(_get_env("ROM_CONVERTO_ENABLED")) +ROM_CONVERTO_PATH: Final[str] = _get_env("ROM_CONVERTO_PATH", "/usr/bin/rom-converto") +# Seconds per rom-converto CLI operation. +ROM_CONVERTO_TIMEOUT: Final[int] = safe_int(_get_env("ROM_CONVERTO_TIMEOUT"), 600) +# Limit concurrent conversion subprocesses to bound total memory use. +ROM_CONVERTO_MAX_CONCURRENCY: Final[int] = max( + 1, safe_int(_get_env("ROM_CONVERTO_MAX_CONCURRENCY"), 2) +) +# Disk cache for converted downloads, under the tree nginx serves at /cache/. +ROM_CONVERTO_CACHE_PATH: Final[str] = f"{ROMM_BASE_PATH}/cache/converts" +# Max source file size (MB) converted in-request on download; 0 disables +# in-request conversion entirely and serves the original file. +ROM_CONVERTO_MAX_SYNC_SIZE_MB: Final[int] = safe_int( + _get_env("ROM_CONVERTO_MAX_SYNC_SIZE_MB"), 512 +) + # DATABASE DB_HOST: Final[str | None] = _get_env("DB_HOST") DB_PORT: Final[int] = safe_int(_get_env("DB_PORT"), 3306) diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index 3d51c2920..6545cccdf 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -1,3 +1,4 @@ +import dataclasses import enum import functools import glob @@ -12,6 +13,7 @@ import yaml from sqlalchemy import URL from yaml.loader import SafeLoader +from adapters.services.rom_converto import TARGETS_BY_PLATFORM from config import ( DB_HOST, DB_NAME, @@ -177,6 +179,14 @@ VALID_SCAN_PRIORITY_SOURCES = frozenset( VALID_SCAN_REGION_MODES = frozenset({"prefer_rom_tags", "prefer_config"}) +@dataclasses.dataclass +class ConvertoConfig: + download_conversion_enabled: bool = False + scan_metadata: bool = True + cache_ttl_hours: int = 24 + platform_formats: dict[str, str] = dataclasses.field(default_factory=dict) + + class EjsControls(TypedDict): _0: dict[int, EjsControlsButton] # button_number -> EjsControlsButton _1: dict[int, EjsControlsButton] @@ -266,6 +276,7 @@ class Config: GAMELIST_MEDIA_IMAGE: MetadataMediaType STREAMING_ENABLED: bool STREAMING_CONTAINERS: list[StreamingContainer] + CONVERTO: ConvertoConfig def __init__(self, **entries): self.__dict__.update(entries) @@ -617,6 +628,20 @@ class ConfigManager: STREAMING_CONTAINERS=pydash.get( self._raw_config, "streaming.containers", [] ), + CONVERTO=ConvertoConfig( + download_conversion_enabled=pydash.get( + self._raw_config, "converto.download_conversion_enabled", False + ), + scan_metadata=pydash.get( + self._raw_config, "converto.scan_metadata", True + ), + cache_ttl_hours=pydash.get( + self._raw_config, "converto.cache_ttl_hours", 24 + ), + platform_formats=pydash.get( + self._raw_config, "converto.platform_formats", {} + ), + ), ) def _get_ejs_controls(self) -> dict[str, EjsControls]: @@ -932,6 +957,51 @@ class ConfigManager: len(legacy_containers), ) + if not isinstance(self.config.CONVERTO.download_conversion_enabled, bool): + log.critical( + "Invalid config.yml: converto.download_conversion_enabled must be a boolean" + ) + sys.exit(3) + + if not isinstance(self.config.CONVERTO.scan_metadata, bool): + log.critical("Invalid config.yml: converto.scan_metadata must be a boolean") + sys.exit(3) + + if ( + not isinstance(self.config.CONVERTO.cache_ttl_hours, int) + or self.config.CONVERTO.cache_ttl_hours < 1 + ): + log.critical( + "Invalid config.yml: converto.cache_ttl_hours must be an integer >= 1" + ) + sys.exit(3) + + if not isinstance(self.config.CONVERTO.platform_formats, dict): + log.critical( + "Invalid config.yml: converto.platform_formats must be a dictionary" + ) + sys.exit(3) + + self.config.CONVERTO.platform_formats = { + str(slug).lower(): str(target).lower() + for slug, target in self.config.CONVERTO.platform_formats.items() + } + for slug, target in self.config.CONVERTO.platform_formats.items(): + targets = TARGETS_BY_PLATFORM.get(slug) + if targets is None: + log.critical( + f"Invalid config.yml: converto.platform_formats.{slug}: " + f"rom-converto has no conversions for this platform. " + f"Supported: {sorted(TARGETS_BY_PLATFORM)}." + ) + sys.exit(3) + if target not in targets: + log.critical( + f"Invalid config.yml: converto.platform_formats.{slug} has an " + f"invalid target {target!r}. Valid options: {sorted(targets)}." + ) + sys.exit(3) + def get_config(self) -> Config: try: with open(self.config_file, "r") as config_file: @@ -1016,6 +1086,12 @@ class ConfigManager: "export": self.config.PEGASUS_AUTO_EXPORT_ON_SCAN, }, }, + "converto": { + "download_conversion_enabled": self.config.CONVERTO.download_conversion_enabled, + "scan_metadata": self.config.CONVERTO.scan_metadata, + "cache_ttl_hours": self.config.CONVERTO.cache_ttl_hours, + "platform_formats": self.config.CONVERTO.platform_formats, + }, } # The streaming section isn't editable at runtime, but it must survive @@ -1142,5 +1218,22 @@ class ConfigManager: self.config.PEGASUS_AUTO_EXPORT_ON_SCAN = pegasus_export self._update_config_file() + def update_converto_settings( + self, + *, + download_conversion_enabled: bool, + scan_metadata: bool, + cache_ttl_hours: int, + platform_formats: dict[str, str], + ) -> None: + """Replace the whole converto.* section and persist it to config.yml.""" + self.config.CONVERTO = ConvertoConfig( + download_conversion_enabled=download_conversion_enabled, + scan_metadata=scan_metadata, + cache_ttl_hours=cache_ttl_hours, + platform_formats=platform_formats, + ) + self._update_config_file() + config_manager = ConfigManager() diff --git a/backend/endpoints/configs.py b/backend/endpoints/configs.py index 970f68b63..c6862b298 100644 --- a/backend/endpoints/configs.py +++ b/backend/endpoints/configs.py @@ -1,6 +1,7 @@ from fastapi import HTTPException, Request, status from pydantic import BaseModel, field_validator +from adapters.services.rom_converto import TARGETS_BY_PLATFORM from config.config_manager import ( DEFAULT_EXCLUDED_EXTENSIONS, DEFAULT_EXCLUDED_FILES, @@ -103,6 +104,34 @@ class ScanSettingsPayload(BaseModel): return value +class ConvertoSettingsPayload(BaseModel): + """Full replacement of the converto.* config section.""" + + download_conversion_enabled: bool + scan_metadata: bool + cache_ttl_hours: int + platform_formats: dict[str, str] + + @field_validator("cache_ttl_hours") + @classmethod + def validate_cache_ttl(cls, value: int) -> int: + if value < 1: + raise ValueError("cache_ttl_hours must be an integer >= 1") + return value + + @field_validator("platform_formats") + @classmethod + def validate_platform_formats(cls, value: dict[str, str]) -> dict[str, str]: + cleaned = { + slug.strip().lower(): target.strip().lower() + for slug, target in value.items() + } + for slug, target in cleaned.items(): + if target not in TARGETS_BY_PLATFORM.get(slug, ()): + raise ValueError(f"{target!r} is not a conversion target for {slug}") + return cleaned + + @router.get("") def get_config(request: Request) -> ConfigResponse: """Get config endpoint @@ -153,6 +182,10 @@ def get_config(request: Request) -> ConfigResponse: GAMELIST_MEDIA_THUMBNAIL=cfg.GAMELIST_MEDIA_THUMBNAIL, GAMELIST_MEDIA_IMAGE=cfg.GAMELIST_MEDIA_IMAGE, PEGASUS_AUTO_EXPORT_ON_SCAN=cfg.PEGASUS_AUTO_EXPORT_ON_SCAN, + CONVERTO=cfg.CONVERTO, + CONVERTO_TARGETS={ + slug: sorted(targets) for slug, targets in TARGETS_BY_PLATFORM.items() + }, ) @@ -287,3 +320,23 @@ async def update_scan_settings(request: Request, payload: ScanSettingsPayload) - # cached gallery sidecar is stale the moment the order changes. if region_priority_changed: db_rom_handler.invalidate_filter_values_cache() + + +@protected_route(router.put, "/converto_settings", [Scope.PLATFORMS_WRITE]) +async def update_converto_settings( + request: Request, payload: ConvertoSettingsPayload +) -> None: + """Replace the converto.* section of the configuration""" + + try: + cm.update_converto_settings( + download_conversion_enabled=payload.download_conversion_enabled, + scan_metadata=payload.scan_metadata, + cache_ttl_hours=payload.cache_ttl_hours, + platform_formats=payload.platform_formats, + ) + except ConfigNotWritableException as exc: + log.critical(exc.message) + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message + ) from exc diff --git a/backend/endpoints/responses/config.py b/backend/endpoints/responses/config.py index 0aa6789ac..429e7af52 100644 --- a/backend/endpoints/responses/config.py +++ b/backend/endpoints/responses/config.py @@ -1,6 +1,11 @@ from typing import TypedDict -from config.config_manager import EjsControls, MetadataMediaType, NetplayICEServer +from config.config_manager import ( + ConvertoConfig, + EjsControls, + MetadataMediaType, + NetplayICEServer, +) class ConfigResponse(TypedDict): @@ -38,3 +43,6 @@ class ConfigResponse(TypedDict): GAMELIST_MEDIA_THUMBNAIL: MetadataMediaType GAMELIST_MEDIA_IMAGE: MetadataMediaType PEGASUS_AUTO_EXPORT_ON_SCAN: bool + CONVERTO: ConvertoConfig + # Platform slug -> the targets rom-converto can convert it to. + CONVERTO_TARGETS: dict[str, list[str]] diff --git a/backend/endpoints/responses/rom.py b/backend/endpoints/responses/rom.py index 7b197457d..27c558665 100644 --- a/backend/endpoints/responses/rom.py +++ b/backend/endpoints/responses/rom.py @@ -245,6 +245,8 @@ class RomFileSchema(BaseModel): sha1_hash: str | None ra_hash: str | None chd_sha1_hash: str | None + title_id: str | None + title_version: int | None archive_members: list[RomArchiveMember] | None category: RomFileCategory | None track_meta: TrackMetaSchema | None = None diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 6bf9730c1..9a67a2c60 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -1,5 +1,6 @@ import binascii import json +import pathlib from base64 import b64encode from dataclasses import replace from datetime import datetime, timezone @@ -11,20 +12,9 @@ from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile, ZipInfo import pydash from anyio import Path, open_file -from fastapi import ( - Body, - Depends, - File, - Form, - HTTPException, -) +from fastapi import Body, Depends, File, Form, HTTPException from fastapi import Path as PathVar -from fastapi import ( - Query, - Request, - UploadFile, - status, -) +from fastapi import Query, Request, UploadFile, status from fastapi.responses import Response from fastapi_pagination import resolve_params from fastapi_pagination.limit_offset import LimitOffsetPage, LimitOffsetParams @@ -33,12 +23,15 @@ from pydantic import BaseModel, Field from sqlalchemy.exc import IntegrityError from starlette.responses import FileResponse +from adapters.services.rom_converto import rom_converto_service from adapters.services.sigil import SWITCH_PLATFORM_SLUGS from config import ( DEV_MODE, DISABLE_DOWNLOAD_ENDPOINT_AUTH, LIBRARY_BASE_PATH, + ROM_CONVERTO_MAX_SYNC_SIZE_MB, ) +from config.config_manager import config_manager as cm from decorators.auth import protected_route from endpoints.responses import BulkOperationResponse from endpoints.responses.rom import ( @@ -101,6 +94,7 @@ from models.rom import ( HAS_FILE_ON_DISK_FILTERS, TITLE_ID_MAX_LENGTH, Rom, + RomFile, RomIdentity, RomUserStatus, SaveTargetLayout, @@ -109,6 +103,11 @@ from models.rom import ( ) from utils import switch from utils.background_tasks import fire_and_forget +from utils.conversion_cache import ( + get_cached_converted, + get_or_convert, + get_redirect_path, +) from utils.database import safe_int, safe_str_to_bool from utils.filesystem import sanitize_filename from utils.hashing import crc32_to_hex @@ -1486,6 +1485,14 @@ async def head_rom_content( # Otherwise proxy through nginx if len(files) == 1: + # Report a cached conversion, but never start one: HEAD may be + # unauthenticated and a conversion is minutes of CPU. + converted_path = await _maybe_converted_download(rom, files[0], convert=False) + if converted_path: + return FileRedirectResponse( + download_path=get_redirect_path(converted_path), + filename=converted_path.name, + ) return FileRedirectResponse( download_path=Path(f"/library/{files[0].full_path}"), ) @@ -1513,6 +1520,28 @@ async def head_rom_content( ) +async def _maybe_converted_download( + rom: Rom, file: RomFile, *, convert: bool = True +) -> pathlib.Path | None: + """The converted file's disk path for a single-file download, or None + to serve the original. Every failure path falls back to the original.""" + converto = cm.get_config().CONVERTO + target = converto.platform_formats.get(rom.platform_slug) + if ( + not converto.download_conversion_enabled + or not target + or ROM_CONVERTO_MAX_SYNC_SIZE_MB <= 0 + or (file.file_size_bytes or rom.fs_size_bytes) + > ROM_CONVERTO_MAX_SYNC_SIZE_MB * 1024 * 1024 + or not await rom_converto_service.is_enabled() + ): + return None + + if not convert: + return get_cached_converted(rom.id, file, rom.platform_slug, target) + return await get_or_convert(rom.id, file, rom.platform_slug, target) + + @protected_route( router.get, "/{id}/content/{file_name}", @@ -1656,8 +1685,15 @@ async def get_rom_content( # Otherwise proxy through nginx if len(files) == 1: + file = files[0] + converted_path = await _maybe_converted_download(rom, file) + if converted_path: + return FileRedirectResponse( + download_path=get_redirect_path(converted_path), + filename=converted_path.name, + ) return FileRedirectResponse( - download_path=Path(f"/library/{files[0].full_path}"), + download_path=Path(f"/library/{file.full_path}"), ) # Multi-file path: serve cached ZIP for Range requests (resumable), diff --git a/backend/endpoints/tasks.py b/backend/endpoints/tasks.py index 9b658256a..8f4b00d99 100644 --- a/backend/endpoints/tasks.py +++ b/backend/endpoints/tasks.py @@ -47,6 +47,7 @@ VISIBLE_SCHEDULED_TASKS: Final[dict[str, Task]] = { "update_switch_titledb", "convert_images_to_webp", "cleanup_zip_cache", + "cleanup_conversion_cache", "cleanup_orphaned_resources", ) } diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index af1bf23c9..b136da3a1 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -212,6 +212,8 @@ ROM_FILE_SCANNED_COLUMNS = ( "sha1_hash", "ra_hash", "chd_sha1_hash", + "title_id", + "title_version", "archive_members", "category", ) diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 4eb246860..a508dfcd9 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -1,5 +1,6 @@ import asyncio import binascii +import dataclasses import fnmatch import hashlib import os @@ -13,6 +14,7 @@ from typing import Any, Final, NotRequired, TypedDict from anyio import Path as AnyioPath +from adapters.services.rom_converto import CONVERTO_PLATFORM_SLUGS, rom_converto_service from adapters.services.sigil import ( SIGIL_PLATFORM_SLUGS, SWITCH_PLATFORM_SLUGS, @@ -26,10 +28,7 @@ from config.config_manager import ( Config, ) from config.config_manager import config_manager as cm -from exceptions.fs_exceptions import ( - RomAlreadyExistsException, - RomsNotFoundException, -) +from exceptions.fs_exceptions import RomAlreadyExistsException, RomsNotFoundException from logger.logger import log from models.base import compute_file_extension, compute_file_name_no_ext from models.platform import Platform @@ -293,22 +292,37 @@ def _parse_save_target_layout(usage: str) -> SaveTargetLayout | None: def _rom_level_identity( platform_slug: str, extractions: list[SigilExtractionResult], + rom_files: list[RomFile], ) -> RomIdentity: - """The rom's identity, from the base game's file where the family has one.""" - if not extractions: - return RomIdentity() + """The rom's identity, from the base game's file where the family has one. - chosen = next( - (e for e in extractions if switch.is_base_title_id(e.title_id)), extractions[0] - ) - return switch.normalize_identity( - platform_slug in SWITCH_PLATFORM_SLUGS, - RomIdentity( + A sigil extraction wins because it carries the save target; otherwise a + file rom-converto identified contributes its bare title id. + """ + is_switch = platform_slug in SWITCH_PLATFORM_SLUGS + if extractions: + chosen = next( + ( + e + for e in extractions + if is_switch and switch.is_base_title_id(e.title_id) + ), + extractions[0], + ) + identity = RomIdentity( title_id=chosen.title_id, save_target=chosen.save_target, save_target_layout=_parse_save_target_layout(chosen.usage), - ), - ) + ) + else: + title_ids = [f.title_id for f in rom_files if f.title_id] + identity = RomIdentity( + title_id=next( + (t for t in title_ids if is_switch and switch.is_base_title_id(t)), + title_ids[0] if title_ids else None, + ) + ) + return switch.normalize_identity(is_switch, identity) class FSRomsHandler(FSHandler): @@ -503,6 +517,36 @@ class FSRomsHandler(FSHandler): log.warning(f"Skipping unreadable file {f_path / file_name}: {exc}") return entries + async def _converto_active(self, rom: Rom) -> bool: + """Whether rom-converto should inspect this rom's files during scan.""" + return ( + rom.platform_slug in CONVERTO_PLATFORM_SLUGS + and cm.get_config().CONVERTO.scan_metadata + and await rom_converto_service.is_enabled() + ) + + async def _read_converto_title_id(self, rom_file: RomFile) -> None: + """Write rom-converto's title id onto one scanned file. + + Best-effort: an unrecognized file leaves the columns unset and any + failure is logged, never raised into the scan. + """ + try: + info = await rom_converto_service.read_info( + self.validate_path(rom_file.full_path) + ) + except Exception as exc: # noqa: BLE001 + log.warning( + f"rom-converto title id extraction failed for " + f"{rom_file.full_path}: {exc}" + ) + return + if info is None: + log.debug(f"rom-converto did not recognize {rom_file.full_path}") + return + rom_file.title_id = info.title_id + rom_file.title_version = info.title_version + async def get_rom_files( self, rom: Rom, @@ -537,6 +581,11 @@ class FSRomsHandler(FSHandler): # non-hashable platforms like Switch. sigil_platform = extract_title_ids and rom.platform_slug in SIGIL_PLATFORM_SLUGS is_switch = rom.platform_slug in SWITCH_PLATFORM_SLUGS + # rom-converto runs before sigil and writes the per-file title ids; + # sigil then trusts those and only fills what it left unset. Unlike + # sigil it also reads archives, and it has no save-target guidance, + # which stays sigil's job. + converto_active = extract_title_ids and await self._converto_active(rom) sigil_extractions: list[SigilExtractionResult] = [] embed_candidates: list[TitleIdEmbedCandidate] = [] sigil_service = SigilService() @@ -554,6 +603,18 @@ class FSRomsHandler(FSHandler): ) if extraction is None: return + # rom-converto already identified this file; sigil keeps its + # save-target knowledge but takes that id. + if rom_file.title_id: + extraction = dataclasses.replace( + extraction, + title_id=rom_file.title_id, + version=( + rom_file.title_version + if rom_file.title_version is not None + else extraction.version + ), + ) if extraction.content_type is not None: category = switch.CONTENT_TYPE_CATEGORIES.get(extraction.content_type) if category is not None: @@ -690,7 +751,13 @@ class FSRomsHandler(FSHandler): last_modified=st.st_mtime, ) # Extract from every ROM file (base, updates and DLC in - # subfolders), not just the top-level one. + # subfolders), not just the top-level one. rom-converto goes + # first and also covers archive files sigil cannot read. + if ( + converto_active + and rom_file.category not in NON_BINARY_FILE_CATEGORIES + ): + await self._read_converto_title_id(rom_file) if ( abs_file_path.suffix.lower() not in ARCHIVE_READERS and rom_file.category not in NON_BINARY_FILE_CATEGORIES @@ -778,6 +845,8 @@ class FSRomsHandler(FSHandler): archive_members=members, ) ) + if converto_active: + await self._read_converto_title_id(rom_files[-1]) else: # Empty, malformed, unreadable, or all-excluded archive: hash the archive # file's raw bytes. We avoid `_calculate_rom_hashes` here because @@ -802,6 +871,8 @@ class FSRomsHandler(FSHandler): file_hash=_make_file_hash(rom_crc_c, rom_md5_h, rom_sha1_h), ) ) + if converto_active: + await self._read_converto_title_id(rom_files[-1]) else: if hashable_platform: try: @@ -848,8 +919,10 @@ class FSRomsHandler(FSHandler): file_hash=file_hash, ) rom_files.append(rom_file) - # Archives keep hashes only; sigil reads title ids from the ROM - # binary itself. + # rom-converto inspects every single-file rom, archives included; + # sigil then reads what it can, trusting converto's ids. + if converto_active: + await self._read_converto_title_id(rom_file) if rom_ext not in ARCHIVE_READERS: await _extract_title_id(rom_file, is_rom_level=True) @@ -880,7 +953,9 @@ class FSRomsHandler(FSHandler): sha1_hash=sha1_hash, ra_hash=ra_hash, top_level_changed=top_level_changed, - identity=_rom_level_identity(rom.platform_slug, sigil_extractions), + identity=_rom_level_identity( + rom.platform_slug, sigil_extractions, rom_files + ), embed_candidates=embed_candidates, ) diff --git a/backend/models/rom.py b/backend/models/rom.py index e13acc111..182f6118e 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -202,6 +202,7 @@ class RomFile(BaseModel): Index("idx_rom_files_sha1_hash", "sha1_hash"), Index("idx_rom_files_ra_hash", "ra_hash"), Index("idx_rom_files_chd_sha1_hash", "chd_sha1_hash"), + Index("idx_rom_files_title_id", "title_id"), ) id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) @@ -215,6 +216,9 @@ class RomFile(BaseModel): sha1_hash: Mapped[str | None] = mapped_column(String(100)) ra_hash: Mapped[str | None] = mapped_column(String(100)) chd_sha1_hash: Mapped[str | None] = mapped_column(String(100)) + title_id: Mapped[str | None] = mapped_column(String(length=100)) + # BigInteger because Switch title versions exceed int32 + title_version: Mapped[int | None] = mapped_column(BigInteger, default=None) archive_members: Mapped[list[RomArchiveMember] | None] = mapped_column( CustomJSON(), default=None, nullable=True ) diff --git a/backend/tasks/manual/convert_library.py b/backend/tasks/manual/convert_library.py new file mode 100644 index 000000000..58cb94da9 --- /dev/null +++ b/backend/tasks/manual/convert_library.py @@ -0,0 +1,98 @@ +from dataclasses import asdict, dataclass + +from adapters.services.rom_converto import resolve_operation, rom_converto_service +from config.config_manager import config_manager as cm +from handler.database import db_platform_handler, db_rom_handler +from handler.database.base_handler import sync_session +from logger.logger import log +from tasks.tasks import Task, TaskType, update_job_meta +from utils.context import initialize_context +from utils.conversion_cache import get_or_convert + + +@dataclass +class ConvertLibraryStats: + platform_id: int | None = None + converted: int = 0 + skipped: int = 0 + failed: int = 0 + + +class ConvertLibraryTask(Task): + def __init__(self): + super().__init__( + title="Convert library to target formats", + description="Pre-warm the conversion cache for ROMs covered by the per-platform format policy", + task_type=TaskType.CONVERSION, + enabled=True, + manual_run=True, + cron_string=None, + ) + + @initialize_context() + async def run(self, platform_id: int | None = None) -> dict: + """Pre-warm the conversion cache for every eligible single-file ROM.""" + log.info(f"Starting {self.title} task...") + + stats = ConvertLibraryStats(platform_id=platform_id) + converto = cm.get_config().CONVERTO + if ( + not converto.download_conversion_enabled + or not converto.platform_formats + or not await rom_converto_service.is_enabled() + ): + log.info( + "Download conversion is not enabled or no platform formats " + "configured, skipping" + ) + return asdict(stats) + + platforms = db_platform_handler.get_platforms() + for platform in platforms: + if platform_id is not None and platform.id != platform_id: + continue + target = converto.platform_formats.get(platform.slug) + if not target: + continue + + with sync_session.begin() as session: + roms = db_rom_handler.get_roms_scalar( + platform_ids=[platform.id], session=session + ) + files_by_rom = db_rom_handler.get_files_for_roms( + [rom.id for rom in roms], session=session + ) + candidates = [] + for rom in roms: + files = files_by_rom.get(rom.id, []) + # Equivalent of `has_simple_single_file` (exactly one file + # at the ROM root) without its deferred-column N+1. + if ( + len(files) != 1 + or files[0].file_path != rom.fs_path + or resolve_operation(platform.slug, target, files[0].file_name) + is None + ): + stats.skipped += 1 + continue + candidates.append((rom, files[0])) + + for rom, rom_file in candidates: + log.info( + f"Pre-warming conversion of '{rom.fs_name}' [ID: {rom.id}] to {target}" + ) + result = await get_or_convert(rom.id, rom_file, platform.slug, target) + if result is None: + stats.failed += 1 + else: + stats.converted += 1 + update_job_meta({"conversion_stats": asdict(stats)}) + + log.info( + f"{self.title} completed: {stats.converted} converted, " + f"{stats.skipped} skipped, {stats.failed} failed" + ) + return asdict(stats) + + +convert_library_task = ConvertLibraryTask() diff --git a/backend/tasks/registry.py b/backend/tasks/registry.py index f80e70bf2..41ea326d2 100644 --- a/backend/tasks/registry.py +++ b/backend/tasks/registry.py @@ -10,10 +10,12 @@ from exceptions.task_exceptions import TaskNotFoundException from handler.redis_handler import low_prio_queue, scan_queue from tasks.manual.cleanup_missing_firmware import cleanup_missing_firmware_task from tasks.manual.cleanup_missing_roms import cleanup_missing_roms_task +from tasks.manual.convert_library import convert_library_task from tasks.manual.recompute_save_content_hashes import ( recompute_save_content_hashes_task, ) from tasks.manual.sync_folder_scan import sync_folder_scan_task +from tasks.scheduled.cleanup_conversion_cache import cleanup_conversion_cache_task from tasks.scheduled.cleanup_netplay import cleanup_netplay_task from tasks.scheduled.cleanup_orphaned_resources import cleanup_orphaned_resources_task from tasks.scheduled.cleanup_upload_tmp import cleanup_upload_tmp_task @@ -39,6 +41,7 @@ SCHEDULED_TASKS: Final[dict[str, PeriodicTask]] = { "convert_images_to_webp": convert_images_to_webp_task, "cleanup_zip_cache": cleanup_zip_cache_task, "cleanup_orphaned_resources": cleanup_orphaned_resources_task, + "cleanup_conversion_cache": cleanup_conversion_cache_task, "cleanup_netplay": cleanup_netplay_task, "cleanup_upload_tmp": cleanup_upload_tmp_task, "sync_retroachievements_progress": sync_retroachievements_progress_task, @@ -50,6 +53,7 @@ MANUAL_TASKS: Final[dict[str, Task]] = { "cleanup_missing_firmware": cleanup_missing_firmware_task, "sync_folder_scan": sync_folder_scan_task, "recompute_save_content_hashes": recompute_save_content_hashes_task, + "convert_library": convert_library_task, } diff --git a/backend/tasks/scheduled/cleanup_conversion_cache.py b/backend/tasks/scheduled/cleanup_conversion_cache.py new file mode 100644 index 000000000..0f410ca4d --- /dev/null +++ b/backend/tasks/scheduled/cleanup_conversion_cache.py @@ -0,0 +1,26 @@ +from logger.logger import log +from tasks.tasks import PeriodicTask, TaskType +from utils.conversion_cache import cleanup_stale_conversions + + +class CleanupConversionCacheTask(PeriodicTask): + def __init__(self): + super().__init__( + title="Scheduled conversion cache cleanup", + description="Removes stale converted download files based on TTL", + task_type=TaskType.CLEANUP, + enabled=True, + manual_run=False, + cron_string="0 4 * * *", + ) + + async def run(self) -> None: + if not self.enabled: + return + + deleted = cleanup_stale_conversions() + if deleted: + log.info(f"Cleaned up {deleted} stale converted download caches") + + +cleanup_conversion_cache_task = CleanupConversionCacheTask() diff --git a/backend/tests/adapters/services/test_rom_converto.py b/backend/tests/adapters/services/test_rom_converto.py new file mode 100644 index 000000000..08deb60a2 --- /dev/null +++ b/backend/tests/adapters/services/test_rom_converto.py @@ -0,0 +1,348 @@ +import asyncio +import json +from pathlib import Path +from unittest.mock import patch + +import pytest + +from adapters.services import rom_converto +from adapters.services.rom_converto import ( + TARGETS_BY_PLATFORM, + Operation, + RomConvertoBinaryNotFoundError, + RomConvertoInfo, + RomConvertoOperationError, + RomConvertoService, + RomConvertoTimeoutError, + resolve_operation, +) + + +class FakeProc: + def __init__( + self, + returncode: int = 0, + stdout: bytes = b"", + stderr: bytes = b"", + delay: float = 0.0, + ): + self._stdout = stdout + self._stderr = stderr + self._delay = delay + self.killed = False + self.returncode = returncode + + async def communicate(self) -> tuple[bytes, bytes]: + if self._delay and not self.killed: + await asyncio.sleep(self._delay) + return self._stdout, self._stderr + + def kill(self) -> None: + self.killed = True + + +@pytest.fixture +def service() -> RomConvertoService: + return RomConvertoService() + + +class TestRun: + async def test_binary_missing_raises(self) -> None: + with ( + patch("shutil.which", return_value=None), + pytest.raises(RomConvertoBinaryNotFoundError), + ): + await rom_converto._run(["info", "--json", "x"], timeout_seconds=1) + + async def test_timeout_kills_process(self) -> None: + proc = FakeProc(delay=5.0) + with ( + patch("shutil.which", return_value="/usr/bin/rom-converto"), + patch("asyncio.create_subprocess_exec", return_value=proc), + pytest.raises(RomConvertoTimeoutError), + ): + await rom_converto._run(["info", "--json", "x"], timeout_seconds=0.01) + assert proc.killed is True + + +class TestIsEnabled: + async def test_disabled_when_config_disabled(self, service: RomConvertoService): + with ( + patch.object(rom_converto, "ROM_CONVERTO_ENABLED", False), + patch("shutil.which", return_value="/usr/bin/rom-converto"), + ): + assert await service.is_enabled() is False + + async def test_probe_fail_cached_false(self, service: RomConvertoService): + proc = FakeProc(returncode=1) + spawn_count = 0 + + async def spawn(*args, **kwargs): + nonlocal spawn_count + spawn_count += 1 + return proc + + with ( + patch.object(rom_converto, "ROM_CONVERTO_ENABLED", True), + patch("shutil.which", return_value="/usr/bin/rom-converto"), + patch("asyncio.create_subprocess_exec", spawn), + ): + assert await service.is_enabled() is False + assert await service.is_enabled() is False + assert spawn_count == 1 + + async def test_probe_ok_logs_version(self, service: RomConvertoService, mocker): + log_info = mocker.patch.object(rom_converto.log, "info") + proc = FakeProc(stdout=b'{"version": "0.21.0"}') + with ( + patch.object(rom_converto, "ROM_CONVERTO_ENABLED", True), + patch("shutil.which", return_value="/usr/bin/rom-converto"), + patch("asyncio.create_subprocess_exec", return_value=proc), + ): + assert await service.is_enabled() is True + assert log_info.call_count == 1 + + async def test_missing_binary_not_cached(self, service: RomConvertoService): + with ( + patch.object(rom_converto, "ROM_CONVERTO_ENABLED", True), + patch("shutil.which", return_value=None), + ): + assert await service.is_enabled() is False + + proc = FakeProc(stdout=b'{"version": "0.21.0"}') + with ( + patch.object(rom_converto, "ROM_CONVERTO_ENABLED", True), + patch("shutil.which", return_value="/usr/bin/rom-converto"), + patch("asyncio.create_subprocess_exec", return_value=proc), + ): + assert await service.is_enabled() is True + + +class TestReadInfo: + async def test_nonzero_returns_none(self, service: RomConvertoService): + proc = FakeProc( + returncode=1, + stderr=b"error: could not detect console for path: /roms/junk.bin", + ) + with ( + patch("shutil.which", return_value="rc"), + patch("asyncio.create_subprocess_exec", return_value=proc), + ): + assert await service.read_info(Path("/roms/junk.bin")) is None + + async def test_non_json_output_returns_none(self, service: RomConvertoService): + proc = FakeProc(returncode=0, stdout=b"not json at all") + with ( + patch("shutil.which", return_value="rc"), + patch("asyncio.create_subprocess_exec", return_value=proc), + ): + assert await service.read_info(Path("/roms/game.iso")) is None + + async def test_parses_nx_payload(self, service: RomConvertoService): + payload = json.dumps( + { + "kind": "nx", + "container_kind": "nsp", + "full": { + "application_title_id_hex": "0100ABCD12345000", + "title_version": 65536, + }, + } + ) + proc = FakeProc(stdout=payload.encode()) + with ( + patch("shutil.which", return_value="rc"), + patch("asyncio.create_subprocess_exec", return_value=proc), + ): + info = await service.read_info(Path("/roms/game.nsp")) + + assert info == RomConvertoInfo( + kind="nx", title_id="0100ABCD12345000", title_version=65536 + ) + + +class TestParseInfo: + def test_nx_without_prod_keys_has_no_title_id(self): + payload = {"kind": "nx", "container_kind": "nsp"} + + info = rom_converto._parse_info(payload) + + assert info == RomConvertoInfo(kind="nx", title_id=None, title_version=None) + + def test_chd_inner_disc_flattens_content(self): + payload = {"kind": "chd", "content": {"kind": "psx", "title_id": "SLUS-00594"}} + + info = rom_converto._parse_info(payload) + + assert info == RomConvertoInfo( + kind="chd", title_id="SLUS-00594", title_version=None + ) + + def test_dol_hex_encodes_game_id(self): + payload = {"kind": "dol", "game_id": "GZLE01"} + + info = rom_converto._parse_info(payload) + + assert info.title_id == "475A4C45" + + def test_rvl_hex_encodes_game_id(self): + payload = {"kind": "rvl", "game_id": "RZTE01"} + + info = rom_converto._parse_info(payload) + + assert info.title_id == "525A5445" + + def test_wup_takes_last_8_of_title_id_hex(self): + payload = { + "kind": "wup", + "title_id_hex": "0005000010143500", + "title_version": 16, + } + + info = rom_converto._parse_info(payload) + + assert info.title_id == "10143500" + assert info.title_version == 16 + + def test_xbox_uses_nested_xbe_title_id_code(self): + payload = { + "kind": "xbox", + "xbe": {"title_id_code": "TT-027", "title_id_hex": "5454001B"}, + } + + info = rom_converto._parse_info(payload) + + assert info.title_id == "TT-027" + + def test_xenon_uses_nested_xex_title_id_hex(self): + payload = {"kind": "xenon", "xex": {"title_id_hex": "4D5307DC"}} + + info = rom_converto._parse_info(payload) + + assert info.title_id == "4D5307DC" + + def test_ctr_title_id_ignores_product_code(self): + payload = { + "kind": "ctr", + "title_id": "0004000000123456", + "product_code": "CTR-P-AXXE", + } + + info = rom_converto._parse_info(payload) + + assert info.title_id == "0004000000123456" + + def test_nds_falls_back_to_game_code(self): + payload = {"kind": "nds", "game_code": "AXXE"} + + info = rom_converto._parse_info(payload) + + assert info.title_id == "AXXE" + + def test_ps3_string_version_is_none(self): + payload = {"kind": "ps3", "title_id": "BLUS31426", "version": "01.00"} + + info = rom_converto._parse_info(payload) + + assert info.title_id == "BLUS31426" + assert info.title_version is None + + +class TestConvert: + def _op(self) -> Operation: + return Operation( + target="chd", + platforms=frozenset({"psp"}), + argv=("chd", "compress"), + input_exts=frozenset({".iso"}), + output_ext=".chd", + ) + + async def test_argv_is_operation_argv_plus_src_and_out( + self, service: RomConvertoService, tmp_path: Path + ): + recorded: list[list[str]] = [] + + async def fake_run(argv: list[str], timeout_seconds: float): + recorded.append(argv) + return 0, "", "" + + src = tmp_path / "game.iso" + out = tmp_path / "game.chd" + with patch.object(rom_converto, "_run", fake_run): + await service.convert(self._op(), src, out) + + assert recorded == [["chd", "compress", str(src), str(out)]] + + async def test_nonzero_raises_operation_error_with_stderr( + self, service: RomConvertoService, tmp_path: Path + ): + async def fake_run(argv: list[str], timeout_seconds: float): + return 1, "", "error: bad disc key" + + src = tmp_path / "game.iso" + out = tmp_path / "game.chd" + with ( + patch.object(rom_converto, "_run", fake_run), + pytest.raises(RomConvertoOperationError) as exc_info, + ): + await service.convert(self._op(), src, out) + + assert exc_info.value.returncode == 1 + assert exc_info.value.stderr == "error: bad disc key" + assert "bad disc key" in str(exc_info.value) + + +class TestResolveOperation: + def test_ngc_rvz_nkit_iso_picks_dol_migrate(self): + resolved = resolve_operation("ngc", "rvz", "Game.nkit.iso") + assert resolved is not None + op, ext = resolved + assert op.argv == ("dol", "migrate") + assert ext == ".nkit.iso" + + def test_ngc_rvz_plain_iso_picks_dol_compress(self): + resolved = resolve_operation("ngc", "rvz", "Game.iso") + assert resolved is not None + op, ext = resolved + assert op.argv == ("dol", "compress") + assert ext == ".iso" + + def test_psp_iso_already_target_returns_none(self): + assert resolve_operation("psp", "iso", "Game.iso") is None + + def test_psx_chd_has_no_extract_operation(self): + assert resolve_operation("psx", "iso", "Game.chd") is None + + def test_wii_wbfs_output_name(self): + resolved = resolve_operation("wii", "wbfs", "Game.rvz") + assert resolved is not None + op, ext = resolved + assert op.output_name(Path("Game.rvz"), ext) == "Game.wbfs" + + def test_3ds_decrypted_output_name_keeps_source_ext_casing(self): + resolved = resolve_operation("3ds", "decrypted", "Game.CIA") + assert resolved is not None + op, ext = resolved + assert op.output_name(Path("Game.CIA"), ext) == "Game.CIA" + + def test_3ds_z3ds_output_name(self): + resolved = resolve_operation("3ds", "z3ds", "Game.3ds") + assert resolved is not None + op, ext = resolved + assert op.output_name(Path("Game.3ds"), ext) == "Game.zcci" + + def test_case_insensitive_ext_match(self): + resolved = resolve_operation("psp", "chd", "Game.ISO") + assert resolved is not None + _, ext = resolved + assert ext == ".iso" + + +class TestTargetsByPlatform: + def test_psp_targets(self): + assert TARGETS_BY_PLATFORM["psp"] == {"chd", "cso", "iso", "zso"} + + def test_wiiu_and_psvita_have_no_conversions(self): + assert "wiiu" not in TARGETS_BY_PLATFORM + assert "psvita" not in TARGETS_BY_PLATFORM diff --git a/backend/tests/config/test_config_loader.py b/backend/tests/config/test_config_loader.py index 26406bfd0..7c5cb1e67 100644 --- a/backend/tests/config/test_config_loader.py +++ b/backend/tests/config/test_config_loader.py @@ -139,6 +139,10 @@ def test_empty_config_loader(): assert loader.config.SCAN_REGION_MODE == "prefer_rom_tags" assert loader.config.GAMELIST_MEDIA_THUMBNAIL == "box2d" assert loader.config.GAMELIST_MEDIA_IMAGE == "screenshot" + assert not loader.config.CONVERTO.download_conversion_enabled + assert loader.config.CONVERTO.scan_metadata + assert loader.config.CONVERTO.cache_ttl_hours == 24 + assert loader.config.CONVERTO.platform_formats == {} def test_missing_config_file_is_created(tmp_path): @@ -478,3 +482,58 @@ def test_platform_binding_lookup_ignores_case(tmp_path): loader.remove_platform_binding("GAMECUBE") assert loader.config.PLATFORMS_BINDING == {} + + +def test_converto_config_from_yaml(tmp_path): + config_file = tmp_path / "config.yml" + config_file.write_text( + "converto:\n" + " download_conversion_enabled: true\n" + " scan_metadata: false\n" + " cache_ttl_hours: 48\n" + " platform_formats:\n" + " PSP: iso\n" + " ngc: rvz\n" + ) + loader = ConfigManager(str(config_file)) + + # Slugs and targets are normalized to lowercase. + assert loader.config.CONVERTO.download_conversion_enabled is True + assert loader.config.CONVERTO.scan_metadata is False + assert loader.config.CONVERTO.cache_ttl_hours == 48 + assert loader.config.CONVERTO.platform_formats == {"psp": "iso", "ngc": "rvz"} + + +def test_update_converto_settings_round_trip(tmp_path): + config_file = tmp_path / "config.yml" + config_file.write_text("converto:\n cache_ttl_hours: 12\n") + loader = ConfigManager(str(config_file)) + + loader.update_converto_settings( + download_conversion_enabled=True, + scan_metadata=True, + cache_ttl_hours=72, + platform_formats={"psp": "iso", "ngc": "rvz"}, + ) + + reloaded = ConfigManager(str(config_file)) + assert reloaded.config.CONVERTO.download_conversion_enabled is True + assert reloaded.config.CONVERTO.scan_metadata is True + assert reloaded.config.CONVERTO.cache_ttl_hours == 72 + assert reloaded.config.CONVERTO.platform_formats == {"psp": "iso", "ngc": "rvz"} + + +def test_converto_invalid_platform_slug_exits(tmp_path): + config_file = tmp_path / "config.yml" + config_file.write_text("converto:\n platform_formats:\n psvita: iso\n") + + with pytest.raises(SystemExit): + ConfigManager(str(config_file)) + + +def test_converto_invalid_target_format_exits(tmp_path): + config_file = tmp_path / "config.yml" + config_file.write_text("converto:\n platform_formats:\n psp: rvz\n") + + with pytest.raises(SystemExit): + ConfigManager(str(config_file)) diff --git a/backend/tests/handler/filesystem/test_roms_title_ids.py b/backend/tests/handler/filesystem/test_roms_title_ids.py new file mode 100644 index 000000000..db7ad0e98 --- /dev/null +++ b/backend/tests/handler/filesystem/test_roms_title_ids.py @@ -0,0 +1,338 @@ +"""Tests for rom-converto title id extraction during scan.""" + +from types import SimpleNamespace + +import pytest + +from adapters.services.rom_converto import ( + RomConvertoError, + RomConvertoInfo, + rom_converto_service, +) +from adapters.services.sigil import SigilExtractionResult +from handler import scan_handler as scan_handler_module +from handler.filesystem.roms_handler import FSRomsHandler, _rom_level_identity +from handler.scan_handler import ScanType, scan_rom +from models.platform import Platform +from models.rom import Rom, RomFile, RomIdentity, SaveTargetLayout +from utils import switch + + +def _info(**overrides) -> RomConvertoInfo: + defaults = { + "kind": "psx", + "title_id": "SCUS-94163", + "title_version": None, + } + defaults.update(overrides) + return RomConvertoInfo(**defaults) + + +@pytest.fixture +def handler() -> FSRomsHandler: + return FSRomsHandler() + + +@pytest.fixture +def psx_rom() -> Rom: + return Rom( + id=1, + fs_name="PaRappa the Rapper (USA).chd", + fs_path="psx/roms", + fs_extension="chd", + platform=Platform(name="PlayStation", slug="psx", fs_slug="psx"), + ) + + +def _patch_service(mocker, read_info=None, enabled: bool = True, scan_metadata=True): + mocker.patch.object( + rom_converto_service, "is_enabled", mocker.AsyncMock(return_value=enabled) + ) + if read_info is not None: + mocker.patch.object(rom_converto_service, "read_info", read_info) + mocker.patch( + "handler.filesystem.roms_handler.cm.get_config", + lambda: SimpleNamespace(CONVERTO=SimpleNamespace(scan_metadata=scan_metadata)), + ) + + +class TestReadConvertoTitleId: + @pytest.mark.asyncio + async def test_sets_title_id_and_version(self, handler, psx_rom, mocker): + rom_file = RomFile(file_name="game.chd", file_path="psx/roms") + + async def read_info(path): + return _info(title_version=65536) + + _patch_service(mocker, read_info) + + await handler._read_converto_title_id(rom_file) + + assert rom_file.title_id == "SCUS-94163" + assert rom_file.title_version == 65536 + + @pytest.mark.asyncio + async def test_no_title_id_leaves_column_none(self, handler, psx_rom, mocker): + rom_file = RomFile(file_name="game.chd", file_path="psx/roms") + + async def read_info(path): + return _info(title_id=None) + + _patch_service(mocker, read_info) + + await handler._read_converto_title_id(rom_file) + + assert rom_file.title_id is None + assert rom_file.title_version is None + + @pytest.mark.asyncio + async def test_unrecognized_file_is_skipped(self, handler, psx_rom, mocker): + rom_file = RomFile(file_name="game.chd", file_path="psx/roms") + + async def read_info(path): + return None + + _patch_service(mocker, read_info) + + await handler._read_converto_title_id(rom_file) + + assert rom_file.title_id is None + assert rom_file.title_version is None + + @pytest.mark.asyncio + async def test_error_does_not_fail_scan(self, handler, psx_rom, mocker): + rom_files = [ + RomFile(file_name="game.chd", file_path="psx/roms"), + RomFile(file_name="game2.chd", file_path="psx/roms"), + ] + + async def read_info(path): + if "game.chd" in str(path): + raise RomConvertoError("boom") + return _info(title_id="TITLE-2") + + _patch_service(mocker, read_info) + + for rom_file in rom_files: + await handler._read_converto_title_id(rom_file) + + assert rom_files[0].title_id is None + assert rom_files[0].title_version is None + assert rom_files[1].title_id == "TITLE-2" + + @pytest.mark.asyncio + async def test_unexpected_error_does_not_fail_scan(self, handler, psx_rom, mocker): + rom_file = RomFile(file_name="game.chd", file_path="psx/roms") + + async def read_info(path): + raise RuntimeError("boom") + + _patch_service(mocker, read_info) + + await handler._read_converto_title_id(rom_file) + + assert rom_file.title_id is None + assert rom_file.title_version is None + + +async def test_converto_active_for_supported_platform(handler, psx_rom, mocker): + _patch_service(mocker) + + assert await handler._converto_active(psx_rom) is True + + +async def test_converto_active_false_when_service_disabled(handler, psx_rom, mocker): + _patch_service(mocker, enabled=False) + + assert await handler._converto_active(psx_rom) is False + + +async def test_converto_active_false_when_scan_metadata_disabled( + handler, psx_rom, mocker +): + _patch_service(mocker, scan_metadata=False) + + assert await handler._converto_active(psx_rom) is False + + +async def test_converto_active_false_for_unsupported_platform(handler, mocker): + rom = Rom( + id=1, + fs_name="Paper Mario (USA).z64", + fs_path="n64/roms", + fs_extension="z64", + platform=Platform(name="Nintendo 64", slug="n64", fs_slug="n64"), + ) + _patch_service(mocker) + + assert await handler._converto_active(rom) is False + + +def _fs_rom( + files: list[RomFile], sha1_hash: str, identity: RomIdentity | None = None +) -> dict: + fs_rom = { + "fs_name": "PaRappa the Rapper (USA).chd", + "flat": True, + "nested": False, + "files": files, + "crc_hash": "", + "md5_hash": "", + "sha1_hash": sha1_hash, + "ra_hash": "", + } + if identity is not None: + fs_rom["identity"] = identity + return fs_rom + + +def _rom_file(name: str, **kwargs) -> RomFile: + return RomFile(file_name=name, file_path="psx/roms", file_size_bytes=1, **kwargs) + + +@pytest.fixture +def patched_scan_env(mocker): + mocker.patch.object( + scan_handler_module.db_rom_handler, "add_rom", side_effect=lambda rom: rom + ) + mocker.patch.object( + scan_handler_module.cm, + "get_config", + return_value=SimpleNamespace( + SCAN_METADATA_PRIORITY=[], + SCAN_ARTWORK_PRIORITY=[], + SCAN_ARTWORK_PRIORITY_OVERRIDES={}, + ), + ) + + +class TestScanRomTitleId: + @pytest.mark.asyncio + async def test_title_id_flows_from_identity(self, patched_scan_env, psx_rom): + # get_rom_files resolves the rom-level identity from converto/sigil; + # scan_rom trusts what fs_rom carries. + scanned = await scan_rom( + scan_type=ScanType.QUICK, + platform=psx_rom.platform, + rom=psx_rom, + fs_rom=_fs_rom( + [_rom_file("game.chd", sha1_hash="abc123")], + sha1_hash="abc123", + identity=RomIdentity(title_id="SCUS-94163"), + ), + metadata_sources=[], + newly_added=True, + ) + + assert scanned.title_id == "SCUS-94163" + + @pytest.mark.asyncio + async def test_title_id_carried_forward_without_files( + self, patched_scan_env, psx_rom + ): + psx_rom.title_id = "SCUS-94163" + scanned = await scan_rom( + scan_type=ScanType.QUICK, + platform=psx_rom.platform, + rom=psx_rom, + fs_rom=_fs_rom([], sha1_hash=""), + metadata_sources=[], + newly_added=True, + ) + + assert scanned.title_id == "SCUS-94163" + + @pytest.mark.asyncio + async def test_title_id_preserved_when_files_yield_none( + self, patched_scan_env, psx_rom + ): + # Files are present but extraction finds no title id on any of them; + # the re-scan must keep the value already stored on the rom. + psx_rom.title_id = "SCUS-94163" + scanned = await scan_rom( + scan_type=ScanType.QUICK, + platform=psx_rom.platform, + rom=psx_rom, + fs_rom=_fs_rom( + [_rom_file("game.chd", sha1_hash="abc123")], sha1_hash="abc123" + ), + metadata_sources=[], + newly_added=True, + ) + + assert scanned.title_id == "SCUS-94163" + + @pytest.mark.asyncio + async def test_title_id_updated_with_new_value(self, patched_scan_env, psx_rom): + # A new truthy title id from the re-scan must overwrite the stored one. + psx_rom.title_id = "OLD-ID" + scanned = await scan_rom( + scan_type=ScanType.QUICK, + platform=psx_rom.platform, + rom=psx_rom, + fs_rom=_fs_rom( + [_rom_file("game.chd", sha1_hash="abc123")], + sha1_hash="abc123", + identity=RomIdentity(title_id="SCUS-94163"), + ), + metadata_sources=[], + newly_added=True, + ) + + assert scanned.title_id == "SCUS-94163" + + +class TestRomLevelIdentity: + """Sigil wins when it ran; otherwise a converto-tagged file's bare id is used.""" + + def test_no_files_returns_empty_identity(self): + assert _rom_level_identity("psx", [], []) == RomIdentity() + + def test_converto_only_ids_use_first_found(self): + files = [ + _rom_file("disc1.chd", title_id=None), + _rom_file("disc2.chd", title_id="SCUS-94163"), + _rom_file("disc3.chd", title_id="OTHER-ID"), + ] + identity = _rom_level_identity("psx", [], files) + assert identity.title_id == "SCUS-94163" + assert identity.save_target is None + + def test_non_switch_first_file_id_wins_even_if_later_looks_like_base_id(self): + # These ids are shaped like Switch update/base ids, but the platform + # is not Switch, so the base-id preference must not kick in. + files = [ + _rom_file("update.bin", title_id="0100ABCD12340800"), + _rom_file("base.bin", title_id="0100ABCD12340000"), + ] + identity = _rom_level_identity("psx", [], files) + assert identity.title_id == "0100ABCD12340800" + + def test_switch_picks_base_id_when_present_among_converto_ids(self): + files = [ + _rom_file("update.nsp", title_id="0100ABCD12340800"), + _rom_file("base.nsp", title_id="0100ABCD12340000"), + ] + identity = _rom_level_identity("switch", [], files) + assert identity.title_id == "0100ABCD12340000" + assert switch.is_base_title_id(identity.title_id) + + def test_switch_derives_base_id_when_only_update_id_present(self): + files = [_rom_file("update.nsp", title_id="0100ABCD12340800")] + identity = _rom_level_identity("switch", [], files) + + assert identity.title_id == "0100ABCD12340000" + assert identity.save_target == "0100ABCD12340000" + assert identity.save_target_layout == SaveTargetLayout.FOLDER_EXACT + + def test_sigil_extraction_wins_over_converto_ids(self): + files = [_rom_file("game.chd", title_id="CONVERTO-ID")] + extraction = SigilExtractionResult( + title_id="SIGIL-ID", save_target="SIGIL-TARGET", usage="file-prefix" + ) + + identity = _rom_level_identity("psx", [extraction], files) + + assert identity.title_id == "SIGIL-ID" + assert identity.save_target == "SIGIL-TARGET" + assert identity.save_target_layout == SaveTargetLayout.FILE_PREFIX diff --git a/backend/tests/tasks/test_cleanup_conversion_cache.py b/backend/tests/tasks/test_cleanup_conversion_cache.py new file mode 100644 index 000000000..21ccc8a83 --- /dev/null +++ b/backend/tests/tasks/test_cleanup_conversion_cache.py @@ -0,0 +1,26 @@ +from tasks.scheduled.cleanup_conversion_cache import CleanupConversionCacheTask + + +class TestCleanupConversionCacheTask: + def test_configuration(self): + task = CleanupConversionCacheTask() + assert task.enabled is True + assert task.cron_string == "0 4 * * *" + + async def test_run_calls_cleanup(self, mocker): + task = CleanupConversionCacheTask() + mock_cleanup = mocker.patch( + "tasks.scheduled.cleanup_conversion_cache.cleanup_stale_conversions", + return_value=2, + ) + await task.run() + mock_cleanup.assert_called_once_with() + + async def test_run_disabled_skips_the_cleanup(self, mocker): + task = CleanupConversionCacheTask() + task.enabled = False + mock_cleanup = mocker.patch( + "tasks.scheduled.cleanup_conversion_cache.cleanup_stale_conversions", + ) + await task.run() + mock_cleanup.assert_not_called() diff --git a/backend/tests/tasks/test_convert_library.py b/backend/tests/tasks/test_convert_library.py new file mode 100644 index 000000000..a95ae8aa4 --- /dev/null +++ b/backend/tests/tasks/test_convert_library.py @@ -0,0 +1,230 @@ +"""Tests for ConvertLibraryTask (conversion cache pre-warming).""" + +from pathlib import Path + +import pytest + +from handler.database import db_platform_handler, db_rom_handler +from models.platform import Platform +from models.rom import Rom, RomFile +from tasks.manual.convert_library import ConvertLibraryTask + + +@pytest.fixture +def converto_config(mocker): + """Point the task's config at a policy covering both test platforms.""" + formats = {"test_platform_slug": "chd", "psp": "chd"} + mocker.patch( + "tasks.manual.convert_library.cm", + mocker.Mock( + **{ + "get_config.return_value.CONVERTO.platform_formats": formats, + "get_config.return_value.CONVERTO.download_conversion_enabled": True, + } + ), + ) + + +@pytest.fixture +def conversion_enabled(mocker): + mocker.patch( + "tasks.manual.convert_library.rom_converto_service.is_enabled", + new_callable=mocker.AsyncMock, + return_value=True, + ) + + +@pytest.fixture +def fake_convert(mocker): + """Fake get_or_convert; returns a cache path per rom.""" + return mocker.patch( + "tasks.manual.convert_library.get_or_convert", + side_effect=lambda rom_id, rom_file, platform_slug, target: Path( + f"/cache/{rom_id}" + ), + ) + + +@pytest.fixture +def psp_platform() -> Platform: + return db_platform_handler.add_platform( + Platform(name="psp", slug="psp", fs_slug="psp") + ) + + +@pytest.fixture +def psp_rom(admin_user, psp_platform: Platform) -> Rom: + rom = Rom( + platform_id=psp_platform.id, + name="psp_rom", + slug="psp_rom_slug", + fs_name="game.iso", + fs_name_no_tags="game", + fs_name_no_ext="game", + fs_extension="iso", + fs_path=f"{psp_platform.slug}/roms", + ) + rom = db_rom_handler.add_rom(rom) + db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id) + return rom + + +@pytest.fixture +def psp_rom_file(psp_rom: Rom) -> RomFile: + rom_file = RomFile( + rom_id=psp_rom.id, + file_name="game.iso", + file_path=psp_rom.fs_path, + file_size_bytes=1000, + ) + return db_rom_handler.add_rom_file(rom_file) + + +class TestConvertLibraryTask: + @pytest.fixture + def task(self) -> ConvertLibraryTask: + return ConvertLibraryTask() + + def test_configuration(self, task: ConvertLibraryTask): + assert task.title == "Convert library to target formats" + assert task.task_type.value == "conversion" + assert task.enabled is True + assert task.manual_run is True + assert task.can_run_manually is True + assert task.cron_string is None + + async def test_gating_noop_when_conversion_disabled( + self, task, mocker, converto_config, fake_convert, rom, rom_file + ): + mocker.patch( + "tasks.manual.convert_library.rom_converto_service.is_enabled", + new_callable=mocker.AsyncMock, + return_value=False, + ) + + stats = await task.run() + + assert stats["converted"] == 0 + fake_convert.assert_not_called() + + async def test_gating_noop_when_no_platform_formats( + self, task, mocker, conversion_enabled, fake_convert, rom, rom_file + ): + mocker.patch( + "tasks.manual.convert_library.cm", + mocker.Mock(**{"get_config.return_value.CONVERTO.platform_formats": {}}), + ) + + stats = await task.run() + + assert stats["converted"] == 0 + fake_convert.assert_not_called() + + async def test_gating_noop_when_download_conversion_disabled( + self, task, mocker, conversion_enabled, fake_convert, rom, rom_file + ): + mocker.patch( + "tasks.manual.convert_library.cm", + mocker.Mock( + **{ + "get_config.return_value.CONVERTO.platform_formats": { + "test_platform_slug": "chd" + }, + "get_config.return_value.CONVERTO.download_conversion_enabled": False, + } + ), + ) + + stats = await task.run() + + assert stats["converted"] == 0 + fake_convert.assert_not_called() + + async def test_skips_unresolvable_files( + self, task, converto_config, conversion_enabled, fake_convert, rom, rom_file + ): + # `rom`/`rom_file` live on "test_platform_slug", which rom-converto has + # no operations for, so resolve_operation always misses. + stats = await task.run() + + assert stats["converted"] == 0 + assert stats["skipped"] == 1 + assert stats["failed"] == 0 + fake_convert.assert_not_called() + + async def test_skips_multi_file_roms( + self, + task, + converto_config, + conversion_enabled, + fake_convert, + multi_file_rom, + ): + stats = await task.run() + + assert stats["converted"] == 0 + assert stats["skipped"] == 1 + fake_convert.assert_not_called() + + async def test_converts_matching_single_file_roms( + self, + task, + converto_config, + conversion_enabled, + fake_convert, + psp_rom, + psp_rom_file, + ): + stats = await task.run() + + assert stats["converted"] == 1 + assert stats["skipped"] == 0 + assert stats["failed"] == 0 + # The task re-queries roms/files in its own session, so the RomFile + # passed to get_or_convert is a different ORM instance; compare by id. + fake_convert.assert_called_once() + rom_id, rom_file, platform_slug, target = fake_convert.call_args.args + assert (rom_id, rom_file.id, platform_slug, target) == ( + psp_rom.id, + psp_rom_file.id, + "psp", + "chd", + ) + + async def test_counts_failed_conversions( + self, task, converto_config, conversion_enabled, mocker, psp_rom, psp_rom_file + ): + fake_convert = mocker.patch( + "tasks.manual.convert_library.get_or_convert", return_value=None + ) + + stats = await task.run() + + assert stats["converted"] == 0 + assert stats["failed"] == 1 + fake_convert.assert_called_once() + rom_id, rom_file, platform_slug, target = fake_convert.call_args.args + assert (rom_id, rom_file.id, platform_slug, target) == ( + psp_rom.id, + psp_rom_file.id, + "psp", + "chd", + ) + + async def test_platform_id_restricts_scope( + self, + task, + converto_config, + conversion_enabled, + fake_convert, + psp_rom, + psp_rom_file, + rom, + rom_file, + ): + """Roms on other platforms are untouched when scoped by platform_id.""" + stats = await task.run(platform_id=psp_rom.platform_id) + + assert stats["platform_id"] == psp_rom.platform_id + assert stats["converted"] == 1 + assert all(call.args[0] == psp_rom.id for call in fake_convert.call_args_list) diff --git a/backend/tests/utils/test_conversion_cache.py b/backend/tests/utils/test_conversion_cache.py new file mode 100644 index 000000000..d30749a95 --- /dev/null +++ b/backend/tests/utils/test_conversion_cache.py @@ -0,0 +1,264 @@ +import os +import time +from pathlib import Path + +import pytest + +from adapters.services.rom_converto import RomConvertoOperationError, resolve_operation +from config import ROMM_BASE_PATH +from models.rom import RomFile +from utils import conversion_cache +from utils.conversion_cache import ( + SENTINEL_NAME, + converted_file_path, + get_cached_converted, + get_or_convert, + get_redirect_path, +) + + +def _rom_file(**overrides) -> RomFile: + defaults = { + "rom_id": 1, + "file_name": "game.iso", + "file_path": "psp/roms", + "file_size_bytes": 1000, + "last_modified": 1700000000.0, + } + defaults.update(overrides) + return RomFile(**defaults) + + +@pytest.fixture +def cache_root(tmp_path, mocker): + mocker.patch.object(conversion_cache, "ROM_CONVERTO_CACHE_PATH", str(tmp_path)) + return tmp_path + + +@pytest.fixture +def fake_convert(mocker): + """Materialize the `.tmp` output file, like the real adapter does.""" + + async def convert(operation, src, out) -> None: + out.write_bytes(b"converted") + + return mocker.patch.object( + conversion_cache.rom_converto_service, "convert", side_effect=convert + ) + + +class TestGetOrConvert: + async def test_unresolvable_returns_none_without_touching_disk( + self, cache_root, fake_convert + ): + f = _rom_file(file_name="game.zip") + + assert await get_or_convert(1, f, "psp", "chd") is None + fake_convert.assert_not_called() + assert not any(cache_root.iterdir()) + + async def test_cache_hit_returns_path_and_refreshes_mtime( + self, cache_root, fake_convert + ): + f = _rom_file() + operation, input_ext = resolve_operation("psp", "chd", f.file_name) + final = converted_file_path(1, f, operation, input_ext) + final.parent.mkdir(parents=True) + final.write_bytes(b"cached") + old = time.time() - 3600 + os.utime(final, (old, old)) + + result = await get_or_convert(1, f, "psp", "chd") + + assert result == final + assert os.stat(final).st_mtime > old + fake_convert.assert_not_called() + + async def test_fresh_sentinel_returns_none(self, cache_root, fake_convert): + f = _rom_file() + operation, input_ext = resolve_operation("psp", "chd", f.file_name) + key_dir = converted_file_path(1, f, operation, input_ext).parent + key_dir.mkdir(parents=True) + (key_dir / SENTINEL_NAME).touch() + + assert await get_or_convert(1, f, "psp", "chd") is None + fake_convert.assert_not_called() + + async def test_stale_sentinel_is_reclaimed(self, cache_root, fake_convert): + f = _rom_file() + operation, input_ext = resolve_operation("psp", "chd", f.file_name) + final = converted_file_path(1, f, operation, input_ext) + key_dir = final.parent + key_dir.mkdir(parents=True) + sentinel = key_dir / SENTINEL_NAME + sentinel.touch() + stale = time.time() - 7 * 3600 + os.utime(sentinel, (stale, stale)) + + result = await get_or_convert(1, f, "psp", "chd") + + assert result == final + assert final.read_bytes() == b"converted" + assert not sentinel.exists() + + async def test_success_writes_via_tmp_then_final(self, cache_root, mocker): + f = _rom_file() + operation, input_ext = resolve_operation("psp", "chd", f.file_name) + final = converted_file_path(1, f, operation, input_ext) + seen_out: list[Path] = [] + + async def convert(op, src, out) -> None: + seen_out.append(out) + out.write_bytes(b"converted") + + mocker.patch.object( + conversion_cache.rom_converto_service, "convert", side_effect=convert + ) + + result = await get_or_convert(1, f, "psp", "chd") + + assert result == final + assert seen_out == [ + final.with_name(f"{final.stem}.tmp{os.getpid()}{final.suffix}") + ] + assert final.exists() + assert not (final.parent / SENTINEL_NAME).exists() + + async def test_stale_tmp_from_this_pid_is_removed_before_convert( + self, cache_root, fake_convert + ): + f = _rom_file() + operation, input_ext = resolve_operation("psp", "chd", f.file_name) + final = converted_file_path(1, f, operation, input_ext) + final.parent.mkdir(parents=True) + tmp = final.with_name(f"{final.stem}.tmp{os.getpid()}{final.suffix}") + tmp.write_bytes(b"leftover") + + result = await get_or_convert(1, f, "psp", "chd") + + assert result == final + assert final.read_bytes() == b"converted" + + async def test_conversion_failure_returns_none_and_empties_key_dir( + self, cache_root, mocker + ): + f = _rom_file() + operation, input_ext = resolve_operation("psp", "chd", f.file_name) + key_dir = converted_file_path(1, f, operation, input_ext).parent + + async def convert(op, src, out) -> None: + raise RomConvertoOperationError("boom", returncode=1, stderr="boom") + + mocker.patch.object( + conversion_cache.rom_converto_service, "convert", side_effect=convert + ) + + assert await get_or_convert(1, f, "psp", "chd") is None + assert list(key_dir.iterdir()) == [] + + async def test_conversion_failure_leaves_no_partial_tmp(self, cache_root, mocker): + f = _rom_file() + operation, input_ext = resolve_operation("psp", "chd", f.file_name) + key_dir = converted_file_path(1, f, operation, input_ext).parent + + async def convert(op, src, out) -> None: + out.write_bytes(b"partial") + raise RomConvertoOperationError("boom", returncode=1, stderr="boom") + + mocker.patch.object( + conversion_cache.rom_converto_service, "convert", side_effect=convert + ) + + assert await get_or_convert(1, f, "psp", "chd") is None + assert list(key_dir.iterdir()) == [] + + +class TestGetCachedConverted: + def test_returns_none_when_unresolvable(self, cache_root): + f = _rom_file(file_name="game.zip") + + assert get_cached_converted(1, f, "psp", "chd") is None + + def test_returns_none_when_not_cached(self, cache_root): + f = _rom_file() + + assert get_cached_converted(1, f, "psp", "chd") is None + + def test_returns_final_path_when_cached(self, cache_root): + f = _rom_file() + operation, input_ext = resolve_operation("psp", "chd", f.file_name) + final = converted_file_path(1, f, operation, input_ext) + final.parent.mkdir(parents=True) + final.write_bytes(b"cached") + + assert get_cached_converted(1, f, "psp", "chd") == final + + +class TestGetRedirectPath: + def test_relative_to_romm_base_path(self): + converted_path = Path(ROMM_BASE_PATH) / "cache/converts/1-abc/Game.chd" + assert get_redirect_path(converted_path) == Path( + "/cache/converts/1-abc/Game.chd" + ) + + +class TestCleanupStaleConversions: + @pytest.fixture + def cleanup_cache_root(self, tmp_path, mocker): + mocker.patch.object(conversion_cache, "ROM_CONVERTO_CACHE_PATH", str(tmp_path)) + mocker.patch.object( + conversion_cache.cm, + "get_config", + return_value=mocker.Mock(**{"CONVERTO.cache_ttl_hours": 24}), + ) + return tmp_path + + def test_missing_root_is_noop(self, tmp_path, mocker): + mocker.patch.object( + conversion_cache, "ROM_CONVERTO_CACHE_PATH", str(tmp_path / "nope") + ) + assert conversion_cache.cleanup_stale_conversions() == 0 + + def test_deletes_expired_and_keeps_fresh(self, cleanup_cache_root): + expired = cleanup_cache_root / "1-a" + expired.mkdir() + (expired / "game.chd").write_bytes(b"x") + old = time.time() - 25 * 3600 + os.utime(expired / "game.chd", (old, old)) + + fresh = cleanup_cache_root / "1-b" + fresh.mkdir() + (fresh / "game.chd").write_bytes(b"x") + + deleted = conversion_cache.cleanup_stale_conversions() + + assert deleted == 1 + assert not expired.exists() + assert fresh.exists() + + def test_deletes_stale_sentinel_only_dirs(self, cleanup_cache_root): + stale = cleanup_cache_root / "1-c" + stale.mkdir() + sentinel = stale / SENTINEL_NAME + sentinel.touch() + old = time.time() - 7 * 3600 + os.utime(sentinel, (old, old)) + + fresh = cleanup_cache_root / "1-d" + fresh.mkdir() + (fresh / SENTINEL_NAME).touch() + + deleted = conversion_cache.cleanup_stale_conversions() + + assert deleted == 1 + assert not stale.exists() + assert fresh.exists() + + def test_deletes_empty_leaked_dirs(self, cleanup_cache_root): + leaked = cleanup_cache_root / "1-e" + leaked.mkdir() + + deleted = conversion_cache.cleanup_stale_conversions() + + assert deleted == 1 + assert not leaked.exists() diff --git a/backend/utils/conversion_cache.py b/backend/utils/conversion_cache.py new file mode 100644 index 000000000..369eae5cd --- /dev/null +++ b/backend/utils/conversion_cache.py @@ -0,0 +1,178 @@ +from __future__ import annotations + +import contextlib +import hashlib +import os +import shutil +import time +from pathlib import Path +from typing import TYPE_CHECKING + +from adapters.services.rom_converto import ( + Operation, + resolve_operation, + rom_converto_service, +) +from config import LIBRARY_BASE_PATH, ROM_CONVERTO_CACHE_PATH, ROMM_BASE_PATH +from config.config_manager import config_manager as cm +from logger.formatter import highlight as hl +from logger.logger import log + +if TYPE_CHECKING: + from models.rom import RomFile + +CACHE_KEY_LENGTH = 16 +SECONDS_PER_HOUR = 3600 +# A fresher sentinel means another worker is actively converting. +PARTIAL_STALE_SECONDS = 6 * SECONDS_PER_HOUR +SENTINEL_NAME = ".partial" + + +def converted_file_path( + rom_id: int, rom_file: RomFile, operation: Operation, input_ext: str +) -> Path: + """Deterministic cache path for a converted ROM file.""" + key = hashlib.sha1( + f"{rom_file.file_path}/{rom_file.file_name}|{rom_file.last_modified}|{rom_file.file_size_bytes}|{operation.target}".encode(), + usedforsecurity=False, + ).hexdigest()[:CACHE_KEY_LENGTH] + key_dir = Path(ROM_CONVERTO_CACHE_PATH) / f"{rom_id}-{key}" + return key_dir / operation.output_name(Path(rom_file.file_name), input_ext) + + +def get_redirect_path(converted_path: Path) -> Path: + """The nginx-internal path for a converted file (`/cache/` aliases + `${ROMM_BASE_PATH}/cache/`).""" + return Path("/") / converted_path.relative_to(ROMM_BASE_PATH) + + +def get_cached_converted( + rom_id: int, rom_file: RomFile, platform_slug: str, target: str +) -> Path | None: + """The converted file if it is already cached, without converting.""" + resolved = resolve_operation(platform_slug, target, rom_file.file_name) + if resolved is None: + return None + final_path = converted_file_path(rom_id, rom_file, *resolved) + return final_path if final_path.exists() else None + + +async def get_or_convert( + rom_id: int, rom_file: RomFile, platform_slug: str, target: str +) -> Path | None: + """Return the converted file's path, converting it on demand. + + Single-flight via a `.partial` sentinel. Never raises; returns None + whenever the file cannot be served converted (already in the target + format, no subcommand accepts it, another worker is converting it, or + the conversion failed) so the caller serves the original. + """ + resolved = resolve_operation(platform_slug, target, rom_file.file_name) + if resolved is None: + return None + operation, input_ext = resolved + final_path = converted_file_path(rom_id, rom_file, operation, input_ext) + key_dir = final_path.parent + sentinel = key_dir / SENTINEL_NAME + + try: + if final_path.exists(): + # Keep a served file fresh so TTL cleanup measures demand. + os.utime(final_path) + return final_path + + key_dir.mkdir(parents=True, exist_ok=True) + stale_sentinel = None + try: + fd = os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY) + except FileExistsError: + if sentinel.stat().st_mtime >= time.time() - PARTIAL_STALE_SECONDS: + # Another worker is converting; serve the original meanwhile. + return None + # Stale sentinel from a crashed run: rename it aside atomically + # (rmtree-then-recreate would leave a window with no key dir for + # a concurrent worker that lost the race) and clean it up below. + stale_sentinel = sentinel.with_name( + f"{SENTINEL_NAME}.stale-{os.getpid()}-{time.time_ns()}" + ) + os.replace(sentinel, stale_sentinel) + fd = os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY) + os.close(fd) + if stale_sentinel is not None: + with contextlib.suppress(OSError): + stale_sentinel.unlink() + except Exception as e: + log.warning( + f"Conversion cache unavailable for ROM {rom_id} (target {hl(target)}): {e}; serving original" + ) + return None + + # Written under a per-process temporary name so a reader never sees a + # partial file and a worker that took over a stale sentinel never + # collides with the one it displaced. + produced = final_path.with_name( + f"{final_path.stem}.tmp{os.getpid()}{final_path.suffix}" + ) + try: + produced.unlink(missing_ok=True) + await rom_converto_service.convert( + operation, src=Path(LIBRARY_BASE_PATH) / rom_file.full_path, out=produced + ) + try: + os.replace(produced, final_path) + except PermissionError: + # Windows: a concurrent request may still stream the old final + # file; if a final file is in place, serving it is success. + if not final_path.exists(): + raise + except Exception as e: + log.warning( + f"Conversion failed for ROM {rom_id} (target {hl(target)}): {e}; serving original" + ) + return None + finally: + with contextlib.suppress(OSError): + produced.unlink(missing_ok=True) + sentinel.unlink() + + # The file can vanish (e.g. TTL cleanup) between the replace and here; + # only return a path that actually exists right now. + return final_path if final_path.exists() else None + + +def cleanup_stale_conversions() -> int: + """Remove key dirs whose final file exceeded the configured TTL, and + sentinel-only dirs whose last conversion attempt is older than 6 hours.""" + cache_root = Path(ROM_CONVERTO_CACHE_PATH) + if not cache_root.exists(): + return 0 + + ttl_seconds = cm.get_config().CONVERTO.cache_ttl_hours * SECONDS_PER_HOUR + now = time.time() + deleted = 0 + + for key_dir in cache_root.iterdir(): + if not key_dir.is_dir(): + continue + files = [ + p + for p in key_dir.iterdir() + if p.is_file() and not p.name.startswith(SENTINEL_NAME) + ] + stale_cutoff = now - (PARTIAL_STALE_SECONDS if not files else ttl_seconds) + if not files: + sentinel = key_dir / SENTINEL_NAME + if not sentinel.exists(): + # Neither a final file nor an in-flight sentinel: an empty + # leaked dir. Only sentinels and final files are meaningful. + shutil.rmtree(key_dir, ignore_errors=True) + deleted += 1 + continue + if sentinel.stat().st_mtime >= stale_cutoff: + continue + elif any(p.stat().st_mtime >= stale_cutoff for p in files): + continue + shutil.rmtree(key_dir, ignore_errors=True) + deleted += 1 + + return deleted diff --git a/examples/config.example.yml b/examples/config.example.yml index 140c285f4..f57da4f64 100644 --- a/examples/config.example.yml +++ b/examples/config.example.yml @@ -217,3 +217,25 @@ # ps2: # ...or a block overriding container keys # emulator: pcsx2 # memory_card_sync: true + +# converto: +# # Serve single-file downloads converted by rom-converto (needs ROM_CONVERTO_ENABLED) +# download_conversion_enabled: false +# # Read title ids and serials with rom-converto during scans +# scan_metadata: true +# # Hours a converted download stays cached +# cache_ttl_hours: 24 +# # Platform slug -> target format. Targets per platform: +# # 3ds: cci, cia, decrypted, encrypted, z3ds +# # nds: decrypted, encrypted +# # ps3: decrypted +# # psp, ps2: chd, cso, iso, zso +# # psx, saturn, segacd, dc: chd, iso +# # ngc: iso, rvz +# # wii: iso, rvz, wbfs +# # switch, switch-2: nsp, nsz, xci, xcz +# # xbox: xiso +# # xbox360: zar +# platform_formats: +# psp: cso +# ngc: rvz