From ccf43ed87ed49c652827926945c0026c6ddb7e4e Mon Sep 17 00:00:00 2001 From: nendo Date: Fri, 24 Jul 2026 02:54:20 +0900 Subject: [PATCH 01/40] Add binary title ID extraction via sigil during scans New SigilService adapter wraps the optional sigil cffi binding (guarded import, degrades to a no-op when absent) and extracts platform-native title/save IDs from ROM binaries during the scan's file pass, gated to nine platforms and independent of the hashable-platform gate. Switch resolves prod.keys from the platform's scanned firmware. Per-file title_id/save_id land on rom_files, rom-level title_id/save_id and a SaveUsage enum land on roms (base Switch ID derived arithmetically when only update/DLC files exist). Config flag filesystem.skip_title_id_extraction mirrors skip_hash_calculation. --- backend/adapters/services/sigil.py | 88 +++++ .../alembic/versions/0102_sigil_title_ids.py | 93 +++++ backend/config/config_manager.py | 5 + backend/endpoints/responses/rom.py | 14 +- backend/endpoints/sockets/scan.py | 36 +- backend/handler/filesystem/roms_handler.py | 148 ++++++-- backend/handler/scan_handler.py | 14 + backend/models/rom.py | 18 +- backend/tests/adapters/services/test_sigil.py | 151 ++++++++ .../handler/filesystem/test_roms_handler.py | 326 +++++++++++++++++- backend/tests/handler/test_fastapi.py | 111 +++++- 11 files changed, 973 insertions(+), 31 deletions(-) create mode 100644 backend/adapters/services/sigil.py create mode 100644 backend/alembic/versions/0102_sigil_title_ids.py create mode 100644 backend/tests/adapters/services/test_sigil.py diff --git a/backend/adapters/services/sigil.py b/backend/adapters/services/sigil.py new file mode 100644 index 000000000..11601f8d0 --- /dev/null +++ b/backend/adapters/services/sigil.py @@ -0,0 +1,88 @@ +import asyncio +from dataclasses import dataclass +from typing import Any, Final + +from handler.metadata.base_handler import UniversalPlatformSlug as UPS +from logger.logger import log + +try: + import sigil +except ImportError: + sigil = None # type: ignore[assignment] + +SWITCH_SIGIL_SLUG: Final = "switch" + +SIGIL_PLATFORM_SLUGS: Final[dict[UPS, str]] = { + UPS.PSP: "psp", + UPS.PSX: "psx", + UPS.PS2: "ps2", + UPS.PSVITA: "psvita", + UPS.SWITCH: SWITCH_SIGIL_SLUG, + UPS.SWITCH_2: SWITCH_SIGIL_SLUG, + UPS.N3DS: "3ds", + UPS.WII: "wii", + UPS.WIIU: "wiiu", + UPS.NGC: "gamecube", +} + +# Errors that are expected for arbitrary library files (no title id present, +# format sigil can't parse, missing decryption keys). Logged at debug level. +ROUTINE_SIGIL_ERROR_CODES: Final = frozenset( + {"NOT_FOUND", "UNSUPPORTED", "UNSUPPORTED_FORMAT", "NEEDS_KEY"} +) + +_missing_binding_logged = False + + +class SigilServiceError(Exception): ... + + +@dataclass(frozen=True) +class SigilExtractionResult: + title_id: str + save_id: str + usage: str + + +class SigilService: + """Service to extract platform-native title ids from ROM binaries via the + optional `sigil` cffi binding.""" + + async def extract_title_id( + self, + platform_slug: UPS | str, + file_path: str, + prod_keys_path: str | None = None, + ) -> SigilExtractionResult | None: + global _missing_binding_logged + + if sigil is None: + if not _missing_binding_logged: + log.debug("sigil binding not installed, skipping title id extraction") + _missing_binding_logged = True + return None + + sigil_slug = SIGIL_PLATFORM_SLUGS.get(platform_slug) # type: ignore[arg-type] + if sigil_slug is None: + return None + + kwargs: dict[str, Any] = {"platform": sigil_slug, "filename_fallback": False} + if sigil_slug == SWITCH_SIGIL_SLUG: + kwargs["prod_keys_path"] = prod_keys_path + + try: + result = await asyncio.to_thread(sigil.extract, file_path, **kwargs) + except Exception as exc: + code = getattr(exc, "code", None) + is_sigil_error = isinstance(exc, getattr(sigil, "SigilError", ())) + if is_sigil_error and code in ROUTINE_SIGIL_ERROR_CODES: + log.debug(f"Sigil found no title id for {file_path}: {code}") + else: + log.error(f"Sigil extraction failed for {file_path}: {exc}") + return None + + return SigilExtractionResult( + title_id=result.title_id, + save_id=result.save_id, + usage=result.usage, + ) diff --git a/backend/alembic/versions/0102_sigil_title_ids.py b/backend/alembic/versions/0102_sigil_title_ids.py new file mode 100644 index 000000000..8342ea282 --- /dev/null +++ b/backend/alembic/versions/0102_sigil_title_ids.py @@ -0,0 +1,93 @@ +"""Add sigil-extracted title id columns: per-file title_id/save_id on +rom_files, plus rom-level title_id/save_id/save_usage on roms. + +Revision ID: 0102_sigil_title_ids +Revises: 0101_virtual_collection_roms +Create Date: 2026-07-23 00:00:00.000000 + +""" + +import sqlalchemy as sa +from alembic import op +from sqlalchemy.dialects.postgresql import ENUM + +from utils.database import is_postgresql + +# revision identifiers, used by Alembic. +revision = "0102_sigil_title_ids" +down_revision = "0101_virtual_collection_roms" +branch_labels = None +depends_on = None + +SAVE_USAGE_VALUES = ("FOLDER_EXACT", "FOLDER_PREFIX", "FILE_EXACT", "FILE_PREFIX") + + +def _save_usage_enum(connection) -> sa.Enum: + if is_postgresql(connection): + enum = ENUM(*SAVE_USAGE_VALUES, name="saveusage", create_type=False) + enum.create(connection, checkfirst=True) + return enum + return sa.Enum(*SAVE_USAGE_VALUES, name="saveusage") + + +def upgrade() -> None: + connection = op.get_bind() + save_usage_enum = _save_usage_enum(connection) + + op.add_column( + "rom_files", + sa.Column("title_id", sa.String(length=100), nullable=True), + if_not_exists=True, + ) + op.add_column( + "rom_files", + sa.Column("save_id", sa.String(length=100), nullable=True), + if_not_exists=True, + ) + op.add_column( + "roms", + sa.Column("title_id", sa.String(length=100), nullable=True), + if_not_exists=True, + ) + op.add_column( + "roms", + sa.Column("save_id", sa.String(length=100), nullable=True), + if_not_exists=True, + ) + op.add_column( + "roms", + sa.Column("save_usage", save_usage_enum, nullable=True), + if_not_exists=True, + ) + + with op.batch_alter_table("rom_files", schema=None) as batch_op: + batch_op.create_index( + "idx_rom_files_title_id", + ["title_id"], + unique=False, + if_not_exists=True, + ) + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.create_index( + "idx_roms_title_id", + ["title_id"], + unique=False, + if_not_exists=True, + ) + + +def downgrade() -> None: + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.drop_index("idx_roms_title_id", if_exists=True) + with op.batch_alter_table("rom_files", schema=None) as batch_op: + batch_op.drop_index("idx_rom_files_title_id", if_exists=True) + + op.drop_column("roms", "save_usage", if_exists=True) + op.drop_column("roms", "save_id", if_exists=True) + op.drop_column("roms", "title_id", if_exists=True) + op.drop_column("rom_files", "save_id", if_exists=True) + op.drop_column("rom_files", "title_id", if_exists=True) + + connection = op.get_bind() + if is_postgresql(connection): + ENUM(name="saveusage").drop(connection, checkfirst=True) diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index 27705ce5e..0126ef44f 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -180,6 +180,7 @@ class Config: ROMS_FOLDER_NAME: str FIRMWARE_FOLDER_NAME: str SKIP_HASH_CALCULATION: bool + SKIP_TITLE_ID_EXTRACTION: bool EJS_DEBUG: bool EJS_CACHE_LIMIT: int | None EJS_DISABLE_AUTO_UNLOAD: bool @@ -431,6 +432,9 @@ class ConfigManager: SKIP_HASH_CALCULATION=pydash.get( self._raw_config, "filesystem.skip_hash_calculation", False ), + SKIP_TITLE_ID_EXTRACTION=pydash.get( + self._raw_config, "filesystem.skip_title_id_extraction", False + ), EJS_DEBUG=pydash.get(self._raw_config, "emulatorjs.debug", False), EJS_CACHE_LIMIT=pydash.get( self._raw_config, "emulatorjs.cache_limit", None @@ -851,6 +855,7 @@ class ConfigManager: "roms_folder": self.config.ROMS_FOLDER_NAME, "firmware_folder": self.config.FIRMWARE_FOLDER_NAME, "skip_hash_calculation": self.config.SKIP_HASH_CALCULATION, + "skip_title_id_extraction": self.config.SKIP_TITLE_ID_EXTRACTION, }, "system": { "platforms": self.config.PLATFORMS_BINDING, diff --git a/backend/endpoints/responses/rom.py b/backend/endpoints/responses/rom.py index 75094a90b..8cf766ee7 100644 --- a/backend/endpoints/responses/rom.py +++ b/backend/endpoints/responses/rom.py @@ -26,7 +26,14 @@ from handler.metadata.moby_handler import MobyMetadata from handler.metadata.ra_handler import RAMetadata from handler.metadata.ss_handler import SSMetadata from models.collection import Collection -from models.rom import Rom, RomArchiveMember, RomFile, RomFileCategory, RomUserStatus +from models.rom import ( + Rom, + RomArchiveMember, + RomFile, + RomFileCategory, + RomUserStatus, + SaveUsage, +) from .base import BaseModel, UTCDatetime @@ -191,6 +198,8 @@ class RomFileSchema(BaseModel): sha1_hash: str | None ra_hash: str | None chd_sha1_hash: str | None + title_id: str | None + save_id: str | None archive_members: list[RomArchiveMember] | None category: RomFileCategory | None track_meta: TrackMetaSchema | None = None @@ -331,6 +340,9 @@ class RomSchema(BaseModel): md5_hash: str | None sha1_hash: str | None ra_hash: str | None + title_id: str | None + save_id: str | None + save_usage: SaveUsage | None has_simple_single_file: bool has_nested_single_file: bool diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index dcc489852..9a3aadb83 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -12,7 +12,14 @@ from rq.job import Job from sqlalchemy.exc import IntegrityError from adapters.services.screenscraper import reset_daily_quota as reset_ss_daily_quota -from config import DEV_MODE, REDIS_URL, SCAN_TIMEOUT, SCAN_WORKERS, TASK_RESULT_TTL +from config import ( + DEV_MODE, + LIBRARY_BASE_PATH, + REDIS_URL, + SCAN_TIMEOUT, + SCAN_WORKERS, + TASK_RESULT_TTL, +) from config.config_manager import MetadataMediaType from config.config_manager import config_manager as cm from endpoints.responses import TaskType @@ -36,6 +43,7 @@ from handler.filesystem import ( ) from handler.filesystem.roms_handler import FSRom from handler.metadata import meta_gamelist_handler, meta_hltb_handler +from handler.metadata.base_handler import UniversalPlatformSlug as UPS from handler.metadata.ss_handler import add_ss_auth_to_url, get_preferred_media_types from handler.redis_handler import get_job_func_name, high_prio_queue, redis_client from handler.scan_handler import ( @@ -288,6 +296,17 @@ async def _identify_rom( } calculate_hashes = not cm.get_config().SKIP_HASH_CALCULATION + extract_title_ids = not cm.get_config().SKIP_TITLE_ID_EXTRACTION + + # Switch title id extraction needs the console's prod.keys to decrypt + # XCI/NSP headers; resolve it from the scanned firmware when present. + prod_keys_path: str | None = None + if extract_title_ids and platform.slug in (UPS.SWITCH, UPS.SWITCH_2): + prod_keys = db_firmware_handler.get_firmware_by_filename( + platform.id, "prod.keys" + ) + if prod_keys: + prod_keys_path = f"{LIBRARY_BASE_PATH}/{prod_keys.full_path}" newly_added: bool = rom is None reassociated: bool = False @@ -304,6 +323,8 @@ async def _identify_rom( platform=platform, ), calculate_hashes=calculate_hashes, + extract_title_ids=extract_title_ids, + prod_keys_path=prod_keys_path, ) fs_rom.update( { @@ -312,6 +333,9 @@ async def _identify_rom( "md5_hash": parsed_rom_files.md5_hash, "sha1_hash": parsed_rom_files.sha1_hash, "ra_hash": parsed_rom_files.ra_hash, + "title_id": parsed_rom_files.title_id, + "save_id": parsed_rom_files.save_id, + "save_usage": parsed_rom_files.save_usage, } ) files_built = True @@ -367,7 +391,10 @@ async def _identify_rom( log.debug(f"Calculating file hashes for {rom.fs_name}...") parsed_rom_files = await fs_rom_handler.get_rom_files( - rom, calculate_hashes=calculate_hashes + rom, + calculate_hashes=calculate_hashes, + extract_title_ids=extract_title_ids, + prod_keys_path=prod_keys_path, ) fs_rom.update( { @@ -376,6 +403,9 @@ async def _identify_rom( "md5_hash": parsed_rom_files.md5_hash, "sha1_hash": parsed_rom_files.sha1_hash, "ra_hash": parsed_rom_files.ra_hash, + "title_id": parsed_rom_files.title_id, + "save_id": parsed_rom_files.save_id, + "save_usage": parsed_rom_files.save_usage, } ) @@ -465,6 +495,8 @@ async def _identify_rom( sha1_hash=file.sha1_hash, ra_hash=file.ra_hash, chd_sha1_hash=file.chd_sha1_hash, + title_id=file.title_id, + save_id=file.save_id, ) for file in fs_rom["files"] ] diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 14517e45f..b44461f17 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -7,10 +7,15 @@ import re import zlib from dataclasses import dataclass from pathlib import Path -from typing import Any, TypedDict +from typing import Any, NotRequired, TypedDict from anyio import Path as AnyioPath +from adapters.services.sigil import ( + SIGIL_PLATFORM_SLUGS, + SigilExtractionResult, + SigilService, +) from config import LIBRARY_BASE_PATH from config.config_manager import ( DEFAULT_EXCLUDED_EXTENSIONS, @@ -23,7 +28,7 @@ from exceptions.fs_exceptions import ( ) from handler.metadata.base_handler import UniversalPlatformSlug as UPS from models.platform import Platform -from models.rom import Rom, RomFile, RomFileCategory, TrackMeta +from models.rom import Rom, RomFile, RomFileCategory, SaveUsage, TrackMeta from utils.archives import ( detect_mime_type, extract_chd_hash, @@ -95,6 +100,9 @@ class FSRom(TypedDict): md5_hash: str sha1_hash: str ra_hash: str + title_id: NotRequired[str | None] + save_id: NotRequired[str | None] + save_usage: NotRequired[SaveUsage | None] class FileHash(TypedDict): @@ -162,6 +170,67 @@ class ParsedRomFiles: md5_hash: str sha1_hash: str ra_hash: str + title_id: str | None = None + save_id: str | None = None + save_usage: SaveUsage | None = None + + +def _parse_save_usage(usage: str) -> SaveUsage | None: + try: + return SaveUsage(usage) + except ValueError: + return None + + +def _is_switch_base_title_id(title_id: str) -> bool: + """Base-game Switch title ids have their low 12 bits cleared and an even + program-index nibble; update/DLC ids differ only in those positions.""" + if len(title_id) < 4 or not title_id.endswith("000"): + return False + try: + return int(title_id[-4], 16) % 2 == 0 + except ValueError: + return False + + +def _derive_switch_base_title_id(title_id: str) -> str | None: + """Derive the base-game title id from an update/DLC id: clear the low 12 + bits and decrement the program-index nibble when it is odd.""" + if len(title_id) < 4: + return None + nibble_char = title_id[-4] + try: + nibble = int(nibble_char, 16) + except ValueError: + return None + if nibble % 2 == 1: + nibble -= 1 + formatted = format(nibble, "x" if nibble_char.islower() else "X") + return f"{title_id[:-4]}{formatted}000" + + +def _rom_level_title_values( + platform_slug: str, + extractions: list[SigilExtractionResult], +) -> tuple[str | None, str | None, SaveUsage | None]: + if not extractions: + return None, None, None + + if platform_slug in (UPS.SWITCH, UPS.SWITCH_2): + base = next( + (e for e in extractions if _is_switch_base_title_id(e.title_id)), None + ) + if base is not None: + return base.title_id, base.save_id, _parse_save_usage(base.usage) + + derived = _derive_switch_base_title_id(extractions[0].title_id) + if derived is None: + return None, None, None + # Switch saves are keyed by the base title id itself. + return derived, derived, SaveUsage.FOLDER_EXACT + + first = extractions[0] + return first.title_id, first.save_id, _parse_save_usage(first.usage) class FSRomsHandler(FSHandler): @@ -317,7 +386,11 @@ class FSRomsHandler(FSHandler): ) async def get_rom_files( - self, rom: Rom, calculate_hashes: bool = True + self, + rom: Rom, + calculate_hashes: bool = True, + extract_title_ids: bool = True, + prod_keys_path: str | None = None, ) -> ParsedRomFiles: from adapters.services.rahasher import RAHasherService from handler.metadata import meta_ra_handler @@ -333,6 +406,21 @@ class FSRomsHandler(FSHandler): rom.platform_slug not in NON_HASHABLE_PLATFORMS and calculate_hashes ) + # Title id extraction is independent of hashing support: it covers + # non-hashable platforms like Switch. + sigil_platform = extract_title_ids and rom.platform_slug in SIGIL_PLATFORM_SLUGS + sigil_extractions: list[SigilExtractionResult] = [] + + async def _extract_title_id(rom_file: RomFile, abs_file_path: Path) -> None: + extraction = await SigilService().extract_title_id( + rom.platform_slug, str(abs_file_path), prod_keys_path + ) + if extraction is None: + return + rom_file.title_id = extraction.title_id + rom_file.save_id = extraction.save_id + sigil_extractions.append(extraction) + cnfg = cm.get_config() excluded_file_names = cnfg.EXCLUDED_MULTI_PARTS_FILES excluded_file_exts = cnfg.EXCLUDED_MULTI_PARTS_EXT @@ -439,14 +527,15 @@ class FSRomsHandler(FSHandler): chd_sha1_hash="", ) - rom_files.append( - self._build_rom_file( - rom=rom, - rom_path=f_path.relative_to(self.base_path), - file_name=file_name, - file_hash=file_hash, - ) + rom_file = self._build_rom_file( + rom=rom, + rom_path=f_path.relative_to(self.base_path), + file_name=file_name, + file_hash=file_hash, ) + if sigil_platform and is_top_level: + await _extract_title_id(rom_file, Path(f_path, file_name)) + rom_files.append(rom_file) elif hashable_platform and rom_ext in ARCHIVE_READERS: # Multi-file archive: compute a composite hash across all # internal entries (in ASCII path order) for hash-database @@ -566,14 +655,15 @@ class FSRomsHandler(FSHandler): extract_chd_hash(rom_dir) if is_chd_file(rom_dir) else "" ), ) - rom_files.append( - self._build_rom_file( - rom=rom, - rom_path=Path(rel_roms_path), - file_name=rom.fs_name, - file_hash=file_hash, - ) + rom_file = self._build_rom_file( + rom=rom, + rom_path=Path(rel_roms_path), + file_name=rom.fs_name, + file_hash=file_hash, ) + if sigil_platform: + await _extract_title_id(rom_file, rom_dir) + rom_files.append(rom_file) else: file_hash = FileHash( crc_hash="", @@ -581,14 +671,21 @@ class FSRomsHandler(FSHandler): sha1_hash="", chd_sha1_hash="", ) - rom_files.append( - self._build_rom_file( - rom=rom, - rom_path=Path(rel_roms_path), - file_name=rom.fs_name, - file_hash=file_hash, - ) + rom_file = self._build_rom_file( + rom=rom, + rom_path=Path(rel_roms_path), + file_name=rom.fs_name, + file_hash=file_hash, ) + # Archives keep hashes only; sigil reads title ids from the ROM + # binary itself. + if sigil_platform and rom_ext not in ARCHIVE_READERS: + await _extract_title_id(rom_file, rom_dir) + rom_files.append(rom_file) + + rom_title_id, rom_save_id, rom_save_usage = _rom_level_title_values( + rom.platform_slug, sigil_extractions + ) return ParsedRomFiles( rom_files=rom_files, @@ -604,6 +701,9 @@ class FSRomsHandler(FSHandler): else "" ), ra_hash=rom_ra_h, + title_id=rom_title_id, + save_id=rom_save_id, + save_usage=rom_save_usage, ) def _calculate_rom_hashes( diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index cc7c41cd1..16dc4a8b1 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -346,6 +346,9 @@ async def scan_rom( "md5_hash": rom.md5_hash, "sha1_hash": rom.sha1_hash, "ra_hash": rom.ra_hash, + "title_id": rom.title_id, + "save_id": rom.save_id, + "save_usage": rom.save_usage, "fs_size_bytes": rom.fs_size_bytes, } @@ -362,6 +365,17 @@ async def scan_rom( } ) + # Only overwrite title id values when extraction produced them, so a + # hash-only or extraction-disabled rescan can't wipe existing ones. + if fs_rom.get("title_id"): + rom_attrs.update( + { + "title_id": fs_rom.get("title_id"), + "save_id": fs_rom.get("save_id"), + "save_usage": fs_rom.get("save_usage"), + } + ) + # Update properties from existing rom if not a complete rescan if not newly_added and scan_type != ScanType.COMPLETE: rom_attrs.update( diff --git a/backend/models/rom.py b/backend/models/rom.py index 957d01ad3..66a139e96 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -84,6 +84,13 @@ class RomFileCategory(enum.StrEnum): SCREENSHOT = "screenshot" +class SaveUsage(enum.StrEnum): + FOLDER_EXACT = "folder-exact" + FOLDER_PREFIX = "folder-prefix" + FILE_EXACT = "file-exact" + FILE_PREFIX = "file-prefix" + + class SiblingRom(BaseModel): __tablename__ = "sibling_roms" @@ -106,7 +113,10 @@ class RomArchiveMember(TypedDict): class RomFile(BaseModel): __tablename__ = "rom_files" - __table_args__ = (Index("idx_rom_files_rom_id", "rom_id"),) + __table_args__ = ( + Index("idx_rom_files_rom_id", "rom_id"), + Index("idx_rom_files_title_id", "title_id"), + ) id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) rom_id: Mapped[int] = mapped_column(ForeignKey("roms.id", ondelete="CASCADE")) @@ -119,6 +129,8 @@ 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(100)) + save_id: Mapped[str | None] = mapped_column(String(100)) archive_members: Mapped[list[RomArchiveMember] | None] = mapped_column( CustomJSON(), default=None, nullable=True ) @@ -321,6 +333,7 @@ class Rom(BaseModel): Index("idx_roms_hltb_id", "hltb_id"), Index("idx_roms_gamelist_id", "gamelist_id"), Index("idx_roms_libretro_id", "libretro_id"), + Index("idx_roms_title_id", "title_id"), ) fs_name: Mapped[str] = mapped_column(String(length=FILE_NAME_MAX_LENGTH)) @@ -393,6 +406,9 @@ class Rom(BaseModel): md5_hash: Mapped[str | None] = mapped_column(String(length=100)) sha1_hash: Mapped[str | None] = mapped_column(String(length=100)) ra_hash: Mapped[str | None] = mapped_column(String(length=100)) + title_id: Mapped[str | None] = mapped_column(String(length=100)) + save_id: Mapped[str | None] = mapped_column(String(length=100)) + save_usage: Mapped[SaveUsage | None] = mapped_column(Enum(SaveUsage), default=None) missing_from_fs: Mapped[bool] = mapped_column(default=False, nullable=False) diff --git a/backend/tests/adapters/services/test_sigil.py b/backend/tests/adapters/services/test_sigil.py new file mode 100644 index 000000000..ed38bd1cb --- /dev/null +++ b/backend/tests/adapters/services/test_sigil.py @@ -0,0 +1,151 @@ +import types +from unittest.mock import Mock + +import pytest + +import adapters.services.sigil as sigil_adapter +from adapters.services.sigil import ( + SIGIL_PLATFORM_SLUGS, + SigilExtractionResult, + SigilService, +) +from handler.metadata.base_handler import UniversalPlatformSlug as UPS + + +class FakeSigilError(Exception): + def __init__(self, code: str): + super().__init__(code) + self.code = code + + +def make_fake_sigil(extract: Mock) -> types.SimpleNamespace: + return types.SimpleNamespace(SigilError=FakeSigilError, extract=extract) + + +def make_result( + title_id: str = "0100ABCD12340000", + save_id: str = "0100ABCD12340000", + usage: str = "folder-exact", +) -> types.SimpleNamespace: + return types.SimpleNamespace( + title_id=title_id, + raw_serial="serial", + save_id=save_id, + platform="switch", + source="binary", + usage=usage, + experimental=False, + ) + + +class TestSigilService: + @pytest.fixture + def service(self): + return SigilService() + + @pytest.mark.asyncio + async def test_returns_none_when_binding_absent( + self, service: SigilService, monkeypatch + ): + monkeypatch.setattr(sigil_adapter, "sigil", None) + + result = await service.extract_title_id(UPS.SWITCH, "/roms/switch/game.nsp") + + assert result is None + + @pytest.mark.asyncio + async def test_returns_none_for_unsupported_platform( + self, service: SigilService, monkeypatch + ): + extract = Mock(return_value=make_result()) + monkeypatch.setattr(sigil_adapter, "sigil", make_fake_sigil(extract)) + + result = await service.extract_title_id(UPS.N64, "/roms/n64/game.z64") + + assert result is None + extract.assert_not_called() + + @pytest.mark.asyncio + async def test_successful_extraction_maps_fields( + self, service: SigilService, monkeypatch + ): + extract = Mock( + return_value=make_result( + title_id="0100ABCD12340000", + save_id="0100ABCD12340000", + usage="folder-exact", + ) + ) + monkeypatch.setattr(sigil_adapter, "sigil", make_fake_sigil(extract)) + + result = await service.extract_title_id(UPS.SWITCH, "/roms/switch/game.nsp") + + assert result == SigilExtractionResult( + title_id="0100ABCD12340000", + save_id="0100ABCD12340000", + usage="folder-exact", + ) + + @pytest.mark.asyncio + @pytest.mark.parametrize("code", ["NOT_FOUND", "UNSUPPORTED_FORMAT", "NEEDS_KEY"]) + async def test_routine_sigil_error_returns_none( + self, service: SigilService, monkeypatch, code: str + ): + extract = Mock(side_effect=FakeSigilError(code)) + monkeypatch.setattr(sigil_adapter, "sigil", make_fake_sigil(extract)) + + result = await service.extract_title_id(UPS.PSX, "/roms/psx/game.bin") + + assert result is None + + @pytest.mark.asyncio + async def test_unexpected_error_returns_none( + self, service: SigilService, monkeypatch + ): + extract = Mock(side_effect=OSError("native crash")) + monkeypatch.setattr(sigil_adapter, "sigil", make_fake_sigil(extract)) + + result = await service.extract_title_id(UPS.PS2, "/roms/ps2/game.iso") + + assert result is None + + @pytest.mark.asyncio + @pytest.mark.parametrize("platform_slug", [UPS.SWITCH, UPS.SWITCH_2]) + async def test_prod_keys_passed_for_switch_platforms( + self, service: SigilService, monkeypatch, platform_slug: UPS + ): + extract = Mock(return_value=make_result()) + monkeypatch.setattr(sigil_adapter, "sigil", make_fake_sigil(extract)) + + await service.extract_title_id( + platform_slug, "/roms/switch/game.xci", "/bios/switch/prod.keys" + ) + + extract.assert_called_once_with( + "/roms/switch/game.xci", + platform="switch", + filename_fallback=False, + prod_keys_path="/bios/switch/prod.keys", + ) + + @pytest.mark.asyncio + async def test_prod_keys_not_passed_for_non_switch_platforms( + self, service: SigilService, monkeypatch + ): + extract = Mock(return_value=make_result(usage="file-exact")) + monkeypatch.setattr(sigil_adapter, "sigil", make_fake_sigil(extract)) + + await service.extract_title_id( + UPS.PSP, "/roms/psp/game.iso", "/bios/switch/prod.keys" + ) + + extract.assert_called_once_with( + "/roms/psp/game.iso", + platform="psp", + filename_fallback=False, + ) + + def test_platform_slug_mapping(self): + assert SIGIL_PLATFORM_SLUGS[UPS.SWITCH_2] == "switch" + assert SIGIL_PLATFORM_SLUGS[UPS.N3DS] == "3ds" + assert SIGIL_PLATFORM_SLUGS[UPS.NGC] == "gamecube" diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index b58bd46b3..c1ef9e047 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -2,13 +2,14 @@ import os import shutil import tempfile from pathlib import Path -from unittest.mock import Mock, patch +from unittest.mock import AsyncMock, Mock, patch import pytest from hypothesis import assume, given from hypothesis import strategies as st from tests._zipfile_shim import reload_zipfile +from adapters.services.sigil import SigilExtractionResult from config.config_manager import LIBRARY_BASE_PATH, Config from handler.filesystem.base_handler import ( LANGUAGES_BY_SHORTCODE, @@ -19,7 +20,7 @@ from handler.filesystem.roms_handler import ( FSRomsHandler, ) from models.platform import Platform -from models.rom import Rom, RomFile, RomFileCategory +from models.rom import Rom, RomFile, RomFileCategory, SaveUsage from utils.archives import extract_chd_hash @@ -1212,6 +1213,327 @@ class TestFSRomsHandler: assert parsed.ra_hash == "" +class TestSigilTitleIdExtraction: + """Title id extraction via the sigil adapter during get_rom_files.""" + + SIGIL_PATCH_TARGET = "adapters.services.sigil.SigilService.extract_title_id" + + @pytest.fixture + def config(self): + cnfg = Config( + EXCLUDED_PLATFORMS=[], + EXCLUDED_SINGLE_EXT=[], + EXCLUDED_SINGLE_FILES=[], + EXCLUDED_MULTI_FILES=[], + EXCLUDED_MULTI_PARTS_EXT=[], + EXCLUDED_MULTI_PARTS_FILES=[], + PLATFORMS_BINDING={}, + PLATFORMS_VERSIONS={}, + ROMS_FOLDER_NAME="roms", + FIRMWARE_FOLDER_NAME="bios", + ) + cnfg.has_structure_path_b = True + return cnfg + + def _make_handler(self, tmp_path: Path) -> FSRomsHandler: + handler = FSRomsHandler() + handler.base_path = tmp_path + return handler + + def _make_single_file_rom( + self, tmp_path: Path, platform: Platform, fs_name: str + ) -> Rom: + roms_path = tmp_path / platform.fs_slug / "roms" + roms_path.mkdir(parents=True, exist_ok=True) + (roms_path / fs_name).write_bytes(b"rom-bytes") + return Rom( + id=1, + fs_name=fs_name, + fs_path=f"{platform.fs_slug}/roms", + platform=platform, + ) + + def _make_multi_part_rom( + self, tmp_path: Path, platform: Platform, fs_name: str, file_names: list[str] + ) -> Rom: + rom_dir = tmp_path / platform.fs_slug / "roms" / fs_name + rom_dir.mkdir(parents=True, exist_ok=True) + for file_name in file_names: + file_path = rom_dir / file_name + file_path.parent.mkdir(parents=True, exist_ok=True) + file_path.write_bytes(b"rom-bytes") + return Rom( + id=1, + fs_name=fs_name, + fs_extension="", + fs_path=f"{platform.fs_slug}/roms", + platform=platform, + ) + + @pytest.mark.asyncio + async def test_single_file_extraction_attaches_values( + self, tmp_path: Path, config: Config + ): + platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") + handler = self._make_handler(tmp_path) + rom = self._make_single_file_rom(tmp_path, platform, "Game.nsp") + + extraction = SigilExtractionResult( + title_id="0100ABCD12340000", + save_id="0100ABCD12340000", + usage="folder-exact", + ) + mock_extract = AsyncMock(return_value=extraction) + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with patch(self.SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files( + rom, prod_keys_path="/bios/switch/prod.keys" + ) + + assert len(parsed.rom_files) == 1 + assert parsed.rom_files[0].title_id == "0100ABCD12340000" + assert parsed.rom_files[0].save_id == "0100ABCD12340000" + assert parsed.title_id == "0100ABCD12340000" + assert parsed.save_id == "0100ABCD12340000" + assert parsed.save_usage == SaveUsage.FOLDER_EXACT + mock_extract.assert_awaited_once_with( + "switch", + str(tmp_path / "switch/roms/Game.nsp"), + "/bios/switch/prod.keys", + ) + + @pytest.mark.asyncio + async def test_multi_part_extraction_prefers_base_game( + self, tmp_path: Path, config: Config + ): + platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") + handler = self._make_handler(tmp_path) + rom = self._make_multi_part_rom( + tmp_path, + platform, + "Zelda", + ["Zelda [base].nsp", "Zelda [update].nsp", "extras/nested.nsp"], + ) + + async def fake_extract( + platform_slug: str, file_path: str, prod_keys_path: str | None = None + ) -> SigilExtractionResult: + if "update" in file_path: + return SigilExtractionResult( + title_id="0100ABCD12340800", + save_id="0100ABCD12340800", + usage="folder-exact", + ) + return SigilExtractionResult( + title_id="0100ABCD12340000", + save_id="0100ABCD12340000", + usage="folder-exact", + ) + + mock_extract = AsyncMock(side_effect=fake_extract) + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with patch(self.SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files(rom) + + by_name = {rf.file_name: rf for rf in parsed.rom_files} + assert by_name["Zelda [base].nsp"].title_id == "0100ABCD12340000" + assert by_name["Zelda [update].nsp"].title_id == "0100ABCD12340800" + # Nested files are not extracted + assert by_name["nested.nsp"].title_id is None + assert mock_extract.await_count == 2 + + assert parsed.title_id == "0100ABCD12340000" + assert parsed.save_id == "0100ABCD12340000" + assert parsed.save_usage == SaveUsage.FOLDER_EXACT + + @pytest.mark.asyncio + async def test_switch_base_derivation_from_update_only_folder( + self, tmp_path: Path, config: Config + ): + platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") + handler = self._make_handler(tmp_path) + rom = self._make_multi_part_rom( + tmp_path, platform, "Zelda", ["Zelda [update].nsp"] + ) + + mock_extract = AsyncMock( + return_value=SigilExtractionResult( + title_id="0100ABCD12340800", + save_id="0100ABCD12340800", + usage="folder-exact", + ) + ) + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with patch(self.SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files(rom) + + assert parsed.rom_files[0].title_id == "0100ABCD12340800" + assert parsed.title_id == "0100ABCD12340000" + assert parsed.save_id == "0100ABCD12340000" + assert parsed.save_usage == SaveUsage.FOLDER_EXACT + + @pytest.mark.asyncio + async def test_switch_base_derivation_from_dlc_odd_nibble( + self, tmp_path: Path, config: Config + ): + platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") + handler = self._make_handler(tmp_path) + rom = self._make_single_file_rom(tmp_path, platform, "Game [DLC].nsp") + + mock_extract = AsyncMock( + return_value=SigilExtractionResult( + title_id="0100ABCD12351064", + save_id="0100ABCD12351064", + usage="folder-exact", + ) + ) + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with patch(self.SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files(rom) + + assert parsed.title_id == "0100ABCD12350000" + assert parsed.save_id == "0100ABCD12350000" + assert parsed.save_usage == SaveUsage.FOLDER_EXACT + + @pytest.mark.asyncio + async def test_non_switch_platform_uses_first_extraction( + self, tmp_path: Path, config: Config + ): + platform = Platform(name="PlayStation Portable", slug="psp", fs_slug="psp") + handler = self._make_handler(tmp_path) + rom = self._make_single_file_rom(tmp_path, platform, "Game.iso") + + mock_extract = AsyncMock( + return_value=SigilExtractionResult( + title_id="ULUS-10041", + save_id="ULUS10041", + usage="folder-prefix", + ) + ) + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with ( + patch(self.SIGIL_PATCH_TARGET, mock_extract), + patch( + "adapters.services.rahasher.RAHasherService.calculate_hash", + new_callable=AsyncMock, + return_value="", + ), + ): + parsed = await handler.get_rom_files(rom) + + assert parsed.rom_files[0].title_id == "ULUS-10041" + assert parsed.rom_files[0].save_id == "ULUS10041" + assert parsed.title_id == "ULUS-10041" + assert parsed.save_id == "ULUS10041" + assert parsed.save_usage == SaveUsage.FOLDER_PREFIX + + @pytest.mark.asyncio + async def test_non_sigil_platform_skips_extraction( + self, tmp_path: Path, config: Config + ): + platform = Platform(name="Nintendo 64", slug="n64", fs_slug="n64") + handler = self._make_handler(tmp_path) + rom = self._make_single_file_rom(tmp_path, platform, "Game.z64") + + mock_extract = AsyncMock() + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with patch(self.SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files(rom, calculate_hashes=False) + + mock_extract.assert_not_awaited() + assert parsed.rom_files[0].title_id is None + assert parsed.title_id is None + assert parsed.save_usage is None + + @pytest.mark.asyncio + async def test_extraction_disabled_skips_extraction( + self, tmp_path: Path, config: Config + ): + platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") + handler = self._make_handler(tmp_path) + rom = self._make_single_file_rom(tmp_path, platform, "Game.nsp") + + mock_extract = AsyncMock() + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with patch(self.SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files(rom, extract_title_ids=False) + + mock_extract.assert_not_awaited() + assert parsed.title_id is None + + @pytest.mark.asyncio + async def test_archive_rom_skips_extraction(self, tmp_path: Path, config: Config): + import io + import zipfile + + reload_zipfile() + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as zf: + zf.writestr("game.bin", b"fake PSX disc content") + + platform = Platform(name="PlayStation", slug="psx", fs_slug="psx") + handler = self._make_handler(tmp_path) + roms_path = tmp_path / "psx" / "roms" + roms_path.mkdir(parents=True) + (roms_path / "game.zip").write_bytes(buf.getvalue()) + rom = Rom( + id=1, + fs_name="game.zip", + fs_path="psx/roms", + platform=platform, + ) + + mock_extract = AsyncMock() + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with ( + patch(self.SIGIL_PATCH_TARGET, mock_extract), + patch( + "adapters.services.rahasher.RAHasherService.calculate_hash", + new_callable=AsyncMock, + return_value="", + ), + ): + parsed = await handler.get_rom_files(rom) + + mock_extract.assert_not_awaited() + assert parsed.rom_files[0].title_id is None + assert parsed.title_id is None + + @pytest.mark.asyncio + async def test_non_hashable_archive_rom_skips_extraction( + self, tmp_path: Path, config: Config + ): + platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") + handler = self._make_handler(tmp_path) + rom = self._make_single_file_rom(tmp_path, platform, "game.zip") + + mock_extract = AsyncMock() + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with patch(self.SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files(rom) + + mock_extract.assert_not_awaited() + assert parsed.title_id is None + + class TestExtractCHDHash: """Test suite for extract_chd_hash function""" diff --git a/backend/tests/handler/test_fastapi.py b/backend/tests/handler/test_fastapi.py index e17896009..301dddc01 100644 --- a/backend/tests/handler/test_fastapi.py +++ b/backend/tests/handler/test_fastapi.py @@ -23,7 +23,7 @@ from handler.scan_handler import ( scan_rom, ) from models.platform import Platform -from models.rom import Rom, RomFile +from models.rom import Rom, RomFile, SaveUsage from utils.context import initialize_context @@ -192,6 +192,115 @@ async def test_scan_rom_complete_clears_unselected_metadata( assert result.hasheous_id == 999 +@patch.object(meta_playmatch_handler, "is_enabled", return_value=False) +async def test_scan_rom_folds_extracted_title_id_values(mock_playmatch_enabled): + """Extracted title id values on the parsed files must land on the Rom.""" + platform = Platform(id=1, slug="switch", fs_slug="switch", name="Nintendo Switch") + platform = db_platform_handler.add_platform(platform) + + rom = Rom( + platform_id=platform.id, + fs_name="Game.nsp", + fs_path="switch/roms", + name="Game", + fs_size_bytes=1024, + tags=[], + ) + rom = db_rom_handler.add_rom(rom) + + async with initialize_context(): + result = await scan_rom( + platform=platform, + scan_type=ScanType.QUICK, + rom=rom, + fs_rom={ + "fs_name": "Game.nsp", + "flat": True, + "nested": False, + "files": [ + RomFile( + rom=rom, + file_name="Game.nsp", + file_path="switch/roms", + file_size_bytes=1024, + last_modified=1620000000, + title_id="0100ABCD12340000", + save_id="0100ABCD12340000", + ) + ], + "crc_hash": "", + "md5_hash": "", + "sha1_hash": "", + "ra_hash": "", + "title_id": "0100ABCD12340000", + "save_id": "0100ABCD12340000", + "save_usage": SaveUsage.FOLDER_EXACT, + }, + metadata_sources=[], + newly_added=False, + ) + + assert result.title_id == "0100ABCD12340000" + assert result.save_id == "0100ABCD12340000" + assert result.save_usage == SaveUsage.FOLDER_EXACT + + +@patch.object(meta_playmatch_handler, "is_enabled", return_value=False) +async def test_scan_rom_preserves_title_id_when_extraction_yields_nothing( + mock_playmatch_enabled, +): + """A rescan without extracted values must not wipe existing title ids.""" + platform = Platform(id=1, slug="switch", fs_slug="switch", name="Nintendo Switch") + platform = db_platform_handler.add_platform(platform) + + rom = Rom( + platform_id=platform.id, + fs_name="Game.nsp", + fs_path="switch/roms", + name="Game", + fs_size_bytes=1024, + tags=[], + title_id="0100ABCD12340000", + save_id="0100ABCD12340000", + save_usage=SaveUsage.FOLDER_EXACT, + ) + rom = db_rom_handler.add_rom(rom) + + async with initialize_context(): + result = await scan_rom( + platform=platform, + scan_type=ScanType.QUICK, + rom=rom, + fs_rom={ + "fs_name": "Game.nsp", + "flat": True, + "nested": False, + "files": [ + RomFile( + rom=rom, + file_name="Game.nsp", + file_path="switch/roms", + file_size_bytes=1024, + last_modified=1620000000, + ) + ], + "crc_hash": "", + "md5_hash": "", + "sha1_hash": "", + "ra_hash": "", + "title_id": None, + "save_id": None, + "save_usage": None, + }, + metadata_sources=[], + newly_added=False, + ) + + assert result.title_id == "0100ABCD12340000" + assert result.save_id == "0100ABCD12340000" + assert result.save_usage == SaveUsage.FOLDER_EXACT + + @patch.object(meta_playmatch_handler, "is_enabled", return_value=False) @patch.object(meta_ra_handler, "get_rom_by_id", new_callable=AsyncMock) @patch.object(meta_ra_handler, "get_rom", new_callable=AsyncMock) From c7539979a3c1d4cd75a7315ddcd929da5b759528 Mon Sep 17 00:00:00 2001 From: nendo Date: Fri, 24 Jul 2026 02:54:29 +0900 Subject: [PATCH 02/40] Surface title and save IDs in the v2 game details Regenerated API types (title_id/save_id on RomFileSchema, plus save_usage and the SaveUsage enum on rom schemas), Title ID / Save ID rows on the metadata tab, a click-to-copy Title ID chip per file row, and the new rom.title-id / rom.save-id locale keys across all locales. --- frontend/src/__generated__/index.ts | 1 + frontend/src/__generated__/models/DetailedRomSchema.ts | 4 ++++ frontend/src/__generated__/models/RomFileSchema.ts | 2 ++ frontend/src/__generated__/models/SaveUsage.ts | 5 +++++ frontend/src/__generated__/models/SimpleRomSchema.ts | 4 ++++ frontend/src/locales/bg_BG/rom.json | 2 ++ frontend/src/locales/cs_CZ/rom.json | 2 ++ frontend/src/locales/de_DE/rom.json | 2 ++ frontend/src/locales/en_GB/rom.json | 2 ++ frontend/src/locales/en_US/rom.json | 2 ++ frontend/src/locales/es_ES/rom.json | 2 ++ frontend/src/locales/fr_FR/rom.json | 2 ++ frontend/src/locales/hu_HU/rom.json | 2 ++ frontend/src/locales/it_IT/rom.json | 2 ++ frontend/src/locales/ja_JP/rom.json | 2 ++ frontend/src/locales/ko_KR/rom.json | 2 ++ frontend/src/locales/pl_PL/rom.json | 2 ++ frontend/src/locales/pt_BR/rom.json | 2 ++ frontend/src/locales/ro_RO/rom.json | 2 ++ frontend/src/locales/ru_RU/rom.json | 2 ++ frontend/src/locales/tr_TR/rom.json | 2 ++ frontend/src/locales/zh_CN/rom.json | 2 ++ frontend/src/locales/zh_TW/rom.json | 2 ++ .../src/v2/components/GameDetails/FilesTab/FileRow.vue | 7 +++++++ frontend/src/v2/components/GameDetails/MetadataTab.vue | 2 ++ frontend/src/v2/components/GameDetails/RelatedGameCard.vue | 3 +++ frontend/src/v2/utils/romArtwork.test.ts | 2 ++ 27 files changed, 66 insertions(+) create mode 100644 frontend/src/__generated__/models/SaveUsage.ts diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts index 02838033a..f7a1d7685 100644 --- a/frontend/src/__generated__/index.ts +++ b/frontend/src/__generated__/index.ts @@ -154,6 +154,7 @@ export type { SaveAndExitRequest } from './models/SaveAndExitRequest'; export type { SaveSchema } from './models/SaveSchema'; export type { SaveStateRequest } from './models/SaveStateRequest'; export type { SaveSummarySchema } from './models/SaveSummarySchema'; +export type { SaveUsage } from './models/SaveUsage'; export type { ScanSettingsPayload } from './models/ScanSettingsPayload'; export type { ScanStats } from './models/ScanStats'; export type { ScanTaskMeta } from './models/ScanTaskMeta'; diff --git a/frontend/src/__generated__/models/DetailedRomSchema.ts b/frontend/src/__generated__/models/DetailedRomSchema.ts index b2c99c0bd..9929a7a3a 100644 --- a/frontend/src/__generated__/models/DetailedRomSchema.ts +++ b/frontend/src/__generated__/models/DetailedRomSchema.ts @@ -16,6 +16,7 @@ import type { RomRAMetadata } from './RomRAMetadata'; import type { RomSSMetadata } from './RomSSMetadata'; import type { RomUserSchema } from './RomUserSchema'; import type { SaveSchema } from './SaveSchema'; +import type { SaveUsage } from './SaveUsage'; import type { ScreenshotSchema } from './ScreenshotSchema'; import type { SiblingRomSchema } from './SiblingRomSchema'; import type { StateSchema } from './StateSchema'; @@ -84,6 +85,9 @@ export type DetailedRomSchema = { md5_hash: (string | null); sha1_hash: (string | null); ra_hash: (string | null); + title_id: (string | null); + save_id: (string | null); + save_usage: (SaveUsage | null); has_simple_single_file: boolean; has_nested_single_file: boolean; has_multiple_files: boolean; diff --git a/frontend/src/__generated__/models/RomFileSchema.ts b/frontend/src/__generated__/models/RomFileSchema.ts index 5d672771c..ff22fc54e 100644 --- a/frontend/src/__generated__/models/RomFileSchema.ts +++ b/frontend/src/__generated__/models/RomFileSchema.ts @@ -21,6 +21,8 @@ export type RomFileSchema = { sha1_hash: (string | null); ra_hash: (string | null); chd_sha1_hash: (string | null); + title_id: (string | null); + save_id: (string | null); archive_members: (Array | null); category: (RomFileCategory | null); track_meta?: (TrackMetaSchema | null); diff --git a/frontend/src/__generated__/models/SaveUsage.ts b/frontend/src/__generated__/models/SaveUsage.ts new file mode 100644 index 000000000..65f4d1a22 --- /dev/null +++ b/frontend/src/__generated__/models/SaveUsage.ts @@ -0,0 +1,5 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +export type SaveUsage = 'folder-exact' | 'folder-prefix' | 'file-exact' | 'file-prefix'; diff --git a/frontend/src/__generated__/models/SimpleRomSchema.ts b/frontend/src/__generated__/models/SimpleRomSchema.ts index ed03254ba..94c473a05 100644 --- a/frontend/src/__generated__/models/SimpleRomSchema.ts +++ b/frontend/src/__generated__/models/SimpleRomSchema.ts @@ -15,6 +15,7 @@ import type { RomMobyMetadata } from './RomMobyMetadata'; import type { RomRAMetadata } from './RomRAMetadata'; import type { RomSSMetadata } from './RomSSMetadata'; import type { RomUserSchema } from './RomUserSchema'; +import type { SaveUsage } from './SaveUsage'; import type { SiblingRomSchema } from './SiblingRomSchema'; export type SimpleRomSchema = { id: number; @@ -76,6 +77,9 @@ export type SimpleRomSchema = { md5_hash: (string | null); sha1_hash: (string | null); ra_hash: (string | null); + title_id: (string | null); + save_id: (string | null); + save_usage: (SaveUsage | null); has_simple_single_file: boolean; has_nested_single_file: boolean; has_multiple_files: boolean; diff --git a/frontend/src/locales/bg_BG/rom.json b/frontend/src/locales/bg_BG/rom.json index b8d8775f0..fb2fd97fa 100644 --- a/frontend/src/locales/bg_BG/rom.json +++ b/frontend/src/locales/bg_BG/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "ROM-ът е обновен успешно!", "save-data": "Данни от записи", "save-deleted": "Записът е изтрит.", + "save-id": "Save ID", "saves-empty": "Все още няма записи", "saves-empty-hint": "Записите, качени за този ROM, ще се появят тук.", "saves-section-community": "Community", @@ -423,6 +424,7 @@ "tab-notes": "Бележки", "tab-overview": "Преглед", "tags": "Тагове", + "title-id": "Title ID", "tracks-n": "{n} песен | {n} песни", "tracks-summary": "{count} песни · {duration}", "tracks-uploaded-n": "Качена е {n} песен. | Качени са {n} песни.", diff --git a/frontend/src/locales/cs_CZ/rom.json b/frontend/src/locales/cs_CZ/rom.json index 9c96f8615..3b013b3af 100644 --- a/frontend/src/locales/cs_CZ/rom.json +++ b/frontend/src/locales/cs_CZ/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "ROM úspěšně aktualizována!", "save-data": "Uložená data", "save-deleted": "Uložená pozice smazána.", + "save-id": "Save ID", "saves-empty": "Zatím žádné uložené pozice", "saves-empty-hint": "Uložené pozice nahrané pro tuto ROM se objeví zde.", "saves-section-community": "Community", @@ -423,6 +424,7 @@ "tab-notes": "Poznámky", "tab-overview": "Přehled", "tags": "Štítky", + "title-id": "Title ID", "tracks-n": "{n} skladeb | {n} skladba | {n} skladby | {n} skladeb", "tracks-summary": "{count} skladeb · {duration}", "tracks-uploaded-n": "Nahráno {n} skladeb. | Nahrána {n} skladba. | Nahrány {n} skladby. | Nahráno {n} skladeb.", diff --git a/frontend/src/locales/de_DE/rom.json b/frontend/src/locales/de_DE/rom.json index 48c6d6efa..5b9439dc8 100644 --- a/frontend/src/locales/de_DE/rom.json +++ b/frontend/src/locales/de_DE/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "ROM erfolgreich aktualisiert!", "save-data": "Speicherdaten", "save-deleted": "Spielstand gelöscht.", + "save-id": "Save ID", "saves-empty": "Noch keine Spielstände", "saves-empty-hint": "Für diese ROM hochgeladene Spielstände erscheinen hier.", "saves-section-community": "Community", @@ -423,6 +424,7 @@ "tab-notes": "Notizen", "tab-overview": "Übersicht", "tags": "Tags", + "title-id": "Title ID", "tracks-n": "{n} Track | {n} Tracks", "tracks-summary": "{count} Tracks · {duration}", "tracks-uploaded-n": "{n} Track hochgeladen. | {n} Tracks hochgeladen.", diff --git a/frontend/src/locales/en_GB/rom.json b/frontend/src/locales/en_GB/rom.json index 947156ea9..51e7ad038 100644 --- a/frontend/src/locales/en_GB/rom.json +++ b/frontend/src/locales/en_GB/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "Rom updated successfully!", "save-data": "Save data", "save-deleted": "Save deleted.", + "save-id": "Save ID", "saves-empty": "No saves yet", "saves-empty-hint": "Saves uploaded for this ROM will appear here.", "saves-section-community": "Community", @@ -423,6 +424,7 @@ "tab-notes": "Notes", "tab-overview": "Overview", "tags": "Tags", + "title-id": "Title ID", "tracks-n": "{n} track | {n} tracks", "tracks-summary": "{count} tracks · {duration}", "tracks-uploaded-n": "Uploaded {n} track. | Uploaded {n} tracks.", diff --git a/frontend/src/locales/en_US/rom.json b/frontend/src/locales/en_US/rom.json index 1f86d9e45..0ac9b09c1 100644 --- a/frontend/src/locales/en_US/rom.json +++ b/frontend/src/locales/en_US/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "Rom updated successfully!", "save-data": "Save data", "save-deleted": "Save deleted.", + "save-id": "Save ID", "saves-empty": "No saves yet", "saves-empty-hint": "Saves uploaded for this ROM will appear here.", "saves-section-community": "Community", @@ -423,6 +424,7 @@ "tab-notes": "Notes", "tab-overview": "Overview", "tags": "Tags", + "title-id": "Title ID", "tracks-n": "{n} track | {n} tracks", "tracks-summary": "{count} tracks · {duration}", "tracks-uploaded-n": "Uploaded {n} track. | Uploaded {n} tracks.", diff --git a/frontend/src/locales/es_ES/rom.json b/frontend/src/locales/es_ES/rom.json index 720a8f04a..3509b7754 100644 --- a/frontend/src/locales/es_ES/rom.json +++ b/frontend/src/locales/es_ES/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "ROM actualizada correctamente", "save-data": "Datos guardados", "save-deleted": "Partida eliminada", + "save-id": "Save ID", "saves-empty": "Aún no hay partidas", "saves-empty-hint": "Sube una partida para empezar.", "saves-section-community": "Comunidad", @@ -423,6 +424,7 @@ "tab-notes": "Notas", "tab-overview": "Resumen", "tags": "Etiquetas", + "title-id": "Title ID", "tracks-n": "{n} pista | {n} pistas", "tracks-summary": "{tracks}, {duration}", "tracks-uploaded-n": "{n} pista subida | {n} pistas subidas", diff --git a/frontend/src/locales/fr_FR/rom.json b/frontend/src/locales/fr_FR/rom.json index bb61b287d..57ba5f753 100644 --- a/frontend/src/locales/fr_FR/rom.json +++ b/frontend/src/locales/fr_FR/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "ROM mise à jour avec succès !", "save-data": "Sauvegardes", "save-deleted": "Sauvegarde supprimée.", + "save-id": "Save ID", "saves-empty": "Aucune sauvegarde pour le moment", "saves-empty-hint": "Les sauvegardes téléversées pour cette ROM apparaîtront ici.", "saves-section-community": "Community", @@ -423,6 +424,7 @@ "tab-notes": "Notes", "tab-overview": "Aperçu", "tags": "Tags", + "title-id": "Title ID", "tracks-n": "{n} piste | {n} pistes", "tracks-summary": "{count} pistes · {duration}", "tracks-uploaded-n": "{n} piste téléversée. | {n} pistes téléversées.", diff --git a/frontend/src/locales/hu_HU/rom.json b/frontend/src/locales/hu_HU/rom.json index 90e2ed4ce..0b67a8e43 100644 --- a/frontend/src/locales/hu_HU/rom.json +++ b/frontend/src/locales/hu_HU/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "A ROM frissítése sikeresen megtörtént!", "save-data": "Mentések", "save-deleted": "Mentés törölve.", + "save-id": "Save ID", "saves-empty": "Még nincsenek mentések", "saves-empty-hint": "A ROM-hoz feltöltött mentések itt jelennek meg.", "saves-section-community": "Community", @@ -423,6 +424,7 @@ "tab-notes": "Jegyzetek", "tab-overview": "Áttekintés", "tags": "Címkék", + "title-id": "Title ID", "tracks-n": "{n} szám | {n} szám", "tracks-summary": "{count} szám · {duration}", "tracks-uploaded-n": "{n} szám feltöltve. | {n} szám feltöltve.", diff --git a/frontend/src/locales/it_IT/rom.json b/frontend/src/locales/it_IT/rom.json index 77bb00c54..7882da154 100644 --- a/frontend/src/locales/it_IT/rom.json +++ b/frontend/src/locales/it_IT/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "ROM aggiornata con successo!", "save-data": "Dati di salvataggio", "save-deleted": "Salvataggio eliminato.", + "save-id": "Save ID", "saves-empty": "Nessun salvataggio ancora", "saves-empty-hint": "I salvataggi caricati per questa ROM appariranno qui.", "saves-section-community": "Community", @@ -423,6 +424,7 @@ "tab-notes": "Note", "tab-overview": "Panoramica", "tags": "Tag", + "title-id": "Title ID", "tracks-n": "{n} traccia | {n} tracce", "tracks-summary": "{count} tracce · {duration}", "tracks-uploaded-n": "Caricata {n} traccia. | Caricate {n} tracce.", diff --git a/frontend/src/locales/ja_JP/rom.json b/frontend/src/locales/ja_JP/rom.json index 45794e646..a936d8782 100644 --- a/frontend/src/locales/ja_JP/rom.json +++ b/frontend/src/locales/ja_JP/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "ROMを正常に更新しました!", "save-data": "セーブデータ", "save-deleted": "セーブを削除しました。", + "save-id": "Save ID", "saves-empty": "セーブはまだありません", "saves-empty-hint": "このROMにアップロードされたセーブはここに表示されます。", "saves-section-community": "Community", @@ -423,6 +424,7 @@ "tab-notes": "ノート", "tab-overview": "概要", "tags": "タグ", + "title-id": "Title ID", "tracks-n": "{n}件のトラック | {n}件のトラック", "tracks-summary": "{count}件のトラック · {duration}", "tracks-uploaded-n": "{n}件のトラックをアップロードしました。 | {n}件のトラックをアップロードしました。", diff --git a/frontend/src/locales/ko_KR/rom.json b/frontend/src/locales/ko_KR/rom.json index ba7bf8ff8..e8ac12d40 100644 --- a/frontend/src/locales/ko_KR/rom.json +++ b/frontend/src/locales/ko_KR/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "ROM이 성공적으로 업데이트되었습니다!", "save-data": "저장 데이터", "save-deleted": "세이브가 삭제되었습니다.", + "save-id": "Save ID", "saves-empty": "아직 세이브가 없습니다", "saves-empty-hint": "이 ROM에 대해 업로드된 세이브가 여기에 표시됩니다.", "saves-section-community": "Community", @@ -423,6 +424,7 @@ "tab-notes": "노트", "tab-overview": "개요", "tags": "태그", + "title-id": "Title ID", "tracks-n": "{n}개 트랙 | {n}개 트랙", "tracks-summary": "{count}개 트랙 · {duration}", "tracks-uploaded-n": "{n}개 트랙을 업로드했습니다. | {n}개 트랙을 업로드했습니다.", diff --git a/frontend/src/locales/pl_PL/rom.json b/frontend/src/locales/pl_PL/rom.json index 343d3731b..9b6bc1fb7 100644 --- a/frontend/src/locales/pl_PL/rom.json +++ b/frontend/src/locales/pl_PL/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "ROM zaktualizowany pomyślnie!", "save-data": "Dane zapisu", "save-deleted": "Zapis usunięty.", + "save-id": "Save ID", "saves-empty": "Brak zapisów", "saves-empty-hint": "Zapisy przesłane dla tego ROM-u pojawią się tutaj.", "saves-section-community": "Community", @@ -423,6 +424,7 @@ "tab-notes": "Notatki", "tab-overview": "Przegląd", "tags": "Tagi", + "title-id": "Title ID", "tracks-n": "{n} utwór | {n} utwory | {n} utworów", "tracks-summary": "{count} utworów · {duration}", "tracks-uploaded-n": "Przesłano {n} utwór. | Przesłano {n} utwory. | Przesłano {n} utworów.", diff --git a/frontend/src/locales/pt_BR/rom.json b/frontend/src/locales/pt_BR/rom.json index 263647944..eb9e4ae10 100644 --- a/frontend/src/locales/pt_BR/rom.json +++ b/frontend/src/locales/pt_BR/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "ROM atualizada com sucesso!", "save-data": "Dados salvos", "save-deleted": "Save excluído.", + "save-id": "Save ID", "saves-empty": "Nenhum save ainda", "saves-empty-hint": "Saves enviados para esta ROM aparecerão aqui.", "saves-section-community": "Community", @@ -423,6 +424,7 @@ "tab-notes": "Notas", "tab-overview": "Visão geral", "tags": "Tags", + "title-id": "Title ID", "tracks-n": "{n} faixa | {n} faixas", "tracks-summary": "{count} faixas · {duration}", "tracks-uploaded-n": "{n} faixa enviada. | {n} faixas enviadas.", diff --git a/frontend/src/locales/ro_RO/rom.json b/frontend/src/locales/ro_RO/rom.json index fdc4c864a..870fd2d4b 100644 --- a/frontend/src/locales/ro_RO/rom.json +++ b/frontend/src/locales/ro_RO/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "ROM actualizat cu succes!", "save-data": "Date salvate", "save-deleted": "Salvare ștearsă.", + "save-id": "Save ID", "saves-empty": "Nicio salvare încă", "saves-empty-hint": "Salvările încărcate pentru acest ROM vor apărea aici.", "saves-section-community": "Community", @@ -423,6 +424,7 @@ "tab-notes": "Notițe", "tab-overview": "Prezentare", "tags": "Etichete", + "title-id": "Title ID", "tracks-n": "{n} piesă | {n} piese", "tracks-summary": "{count} piese · {duration}", "tracks-uploaded-n": "S-a încărcat {n} piesă. | S-au încărcat {n} piese.", diff --git a/frontend/src/locales/ru_RU/rom.json b/frontend/src/locales/ru_RU/rom.json index f2740cb7b..26f758ab0 100644 --- a/frontend/src/locales/ru_RU/rom.json +++ b/frontend/src/locales/ru_RU/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "ROM успешно обновлён!", "save-data": "Сохранения", "save-deleted": "Сохранение удалено.", + "save-id": "Save ID", "saves-empty": "Сохранений пока нет", "saves-empty-hint": "Сохранения, загруженные для этого ROM, появятся здесь.", "saves-section-community": "Community", @@ -423,6 +424,7 @@ "tab-notes": "Заметки", "tab-overview": "Обзор", "tags": "Теги", + "title-id": "Title ID", "tracks-n": "{n} трек | {n} треков", "tracks-summary": "{count} треков · {duration}", "tracks-uploaded-n": "Загружен {n} трек. | Загружено {n} треков.", diff --git a/frontend/src/locales/tr_TR/rom.json b/frontend/src/locales/tr_TR/rom.json index e8c0b64b0..2a4a739d2 100644 --- a/frontend/src/locales/tr_TR/rom.json +++ b/frontend/src/locales/tr_TR/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "ROM başarıyla güncellendi!", "save-data": "Kayıt verisi", "save-deleted": "Kayıt silindi.", + "save-id": "Save ID", "saves-empty": "Henüz kayıt yok", "saves-empty-hint": "Bu ROM için yüklenen kayıtlar burada görünecek.", "saves-section-community": "Topluluk", @@ -423,6 +424,7 @@ "tab-notes": "Notlar", "tab-overview": "Genel Bakış", "tags": "Etiketler", + "title-id": "Title ID", "tracks-n": "{n} parça | {n} parça", "tracks-summary": "{count} parça · {duration}", "tracks-uploaded-n": "{n} parça yüklendi. | {n} parça yüklendi.", diff --git a/frontend/src/locales/zh_CN/rom.json b/frontend/src/locales/zh_CN/rom.json index 299338d37..a84396c95 100644 --- a/frontend/src/locales/zh_CN/rom.json +++ b/frontend/src/locales/zh_CN/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "ROM 更新成功!", "save-data": "存档数据", "save-deleted": "存档已删除。", + "save-id": "Save ID", "saves-empty": "暂无存档", "saves-empty-hint": "此 ROM 上传的存档将显示在此处。", "saves-section-community": "Community", @@ -423,6 +424,7 @@ "tab-notes": "笔记", "tab-overview": "概览", "tags": "标签", + "title-id": "Title ID", "tracks-n": "{n} 个曲目 | {n} 个曲目", "tracks-summary": "{count} 个曲目 · {duration}", "tracks-uploaded-n": "已上传 {n} 个曲目。 | 已上传 {n} 个曲目。", diff --git a/frontend/src/locales/zh_TW/rom.json b/frontend/src/locales/zh_TW/rom.json index 33f6e1a37..4d41662ed 100644 --- a/frontend/src/locales/zh_TW/rom.json +++ b/frontend/src/locales/zh_TW/rom.json @@ -320,6 +320,7 @@ "rom-updated-successfully": "ROM 更新成功!", "save-data": "存檔資料", "save-deleted": "存檔已刪除。", + "save-id": "Save ID", "saves-empty": "尚未有存檔", "saves-empty-hint": "為此 ROM 上傳的存檔將會顯示在此處。", "saves-section-community": "Community", @@ -423,6 +424,7 @@ "tab-notes": "筆記", "tab-overview": "概覽", "tags": "標籤", + "title-id": "Title ID", "tracks-n": "{n} 個音軌 | {n} 個音軌", "tracks-summary": "{count} 個音軌 · {duration}", "tracks-uploaded-n": "已上傳 {n} 個音軌。 | 已上傳 {n} 個音軌。", diff --git a/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue b/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue index a85763156..3038577a9 100644 --- a/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue +++ b/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue @@ -95,6 +95,7 @@ const audioDuration = computed(() => const hasAnyHash = computed( () => + Boolean(props.file.title_id) || Boolean(props.file.sha1_hash) || Boolean(props.file.chd_sha1_hash) || Boolean(props.file.md5_hash) || @@ -166,6 +167,12 @@ const hasAnyHash = computed(
+ (() => { return [ { label: t("rom.filename"), value: r.fs_name }, { label: t("common.size"), value: size }, + { label: t("rom.title-id"), value: r.title_id ?? "—" }, + { label: t("rom.save-id"), value: r.save_id ?? "—" }, ]; }); diff --git a/frontend/src/v2/components/GameDetails/RelatedGameCard.vue b/frontend/src/v2/components/GameDetails/RelatedGameCard.vue index 6a98289cc..75d3eddb8 100644 --- a/frontend/src/v2/components/GameDetails/RelatedGameCard.vue +++ b/frontend/src/v2/components/GameDetails/RelatedGameCard.vue @@ -142,6 +142,9 @@ const syntheticRom = computed(() => ({ md5_hash: null, sha1_hash: null, ra_hash: null, + title_id: null, + save_id: null, + save_usage: null, has_simple_single_file: false, has_nested_single_file: false, has_multiple_files: false, diff --git a/frontend/src/v2/utils/romArtwork.test.ts b/frontend/src/v2/utils/romArtwork.test.ts index 08b17e290..ee509ce37 100644 --- a/frontend/src/v2/utils/romArtwork.test.ts +++ b/frontend/src/v2/utils/romArtwork.test.ts @@ -20,6 +20,8 @@ function makeFile(overrides: Partial): RomFileSchema { sha1_hash: null, ra_hash: null, chd_sha1_hash: null, + title_id: null, + save_id: null, archive_members: null, category: "game", ...overrides, From 2f1d69f8342908f598f8fdb1281b754b43eca762 Mon Sep 17 00:00:00 2001 From: nendo Date: Fri, 24 Jul 2026 02:54:37 +0900 Subject: [PATCH 03/40] Build sigil into Docker images as an optional dependency docker/Dockerfile gains a sigil-build stage (python:3.13-alpine base so the cffi extension matches the venv's cp313/musl ABI) whose staged package is copied into the slim image's site-packages; the Ubuntu dev image builds it inline after uv sync. Pinned by commit ARG. The backend treats the package as optional, so images built without it simply skip extraction. DEVELOPER_SETUP documents the optional local build. --- DEVELOPER_SETUP.md | 14 ++++++++++++++ Dockerfile | 19 +++++++++++++++++++ docker/Dockerfile | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+) diff --git a/DEVELOPER_SETUP.md b/DEVELOPER_SETUP.md index f834506d1..32744aa93 100644 --- a/DEVELOPER_SETUP.md +++ b/DEVELOPER_SETUP.md @@ -100,6 +100,20 @@ source .venv/bin/activate uv sync --all-extras --dev ``` +#### - Build and install sigil (optional) + +```sh +# This is only required for title ID extraction; the feature no-ops without it +# Users on macOS can skip this step, like RAHasher +# Requires cmake, and RomM's Python 3.13 venv (created above) must be active +git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git ../argosy-sigil +cd ../argosy-sigil/bindings/python +uv pip install cffi setuptools +make build +uv pip install -e . +cd - +``` + #### - Spin up the database and other services ```sh diff --git a/Dockerfile b/Dockerfile index d4115ad7d..be0d0eb58 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,6 +10,7 @@ ENV DEBIAN_FRONTEND=noninteractive RUN apt-get update && apt-get install -y --no-install-recommends \ git \ make \ + cmake \ gcc \ g++ \ libmariadb3 \ @@ -76,6 +77,24 @@ RUN uv sync --all-extras ENV PATH="/app/.venv/bin:${PATH}" +# Build and install sigil (optional, for title ID extraction) +# Placed after `uv sync` because the extension is compiled with the venv's +# Python so the ABI matches. +ARG SIGIL_VERSION=44863fe614fd1c47e00c4bc28271e7a0d0e83a59 +RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git /tmp/argosy-sigil +WORKDIR /tmp/argosy-sigil +RUN git checkout "${SIGIL_VERSION}" \ + && git submodule update --init --recursive \ + && cmake -B ./build-python -S . -DSIGIL_BUILD_CLI=OFF -DSIGIL_BUILD_TESTS=OFF \ + && cmake --build ./build-python --target sigil +WORKDIR /tmp/argosy-sigil/bindings/python +RUN uv pip install --python /app/.venv/bin/python cffi setuptools \ + && /app/.venv/bin/python build_sigil.py \ + && mkdir -p /app/.venv/lib/python3.13/site-packages/sigil \ + && cp ./sigil/*.py ./sigil/_sigil.*.so /app/.venv/lib/python3.13/site-packages/sigil/ +WORKDIR /app +RUN rm -rf /tmp/argosy-sigil + # Copy entrypoint script COPY entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh diff --git a/docker/Dockerfile b/docker/Dockerfile index c80d9fb6b..e01573741 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -3,6 +3,7 @@ # - backend-build: Build backend environment # - backend-dev-build: Similar to `backend-build`, but also compiles and installs development dependencies # - rahasher-build: Build RAHasher +# - sigil-build: Build sigil Python bindings (title ID extraction) # - emulator-stage: Fetch and extract emulators # - nginx-build: Build nginx modules # - production-stage: Setup frontend and backend @@ -104,6 +105,32 @@ RUN git clone --recursive --branch "${RALIBRETRO_VERSION}" --depth 1 https://git make HAVE_CHD=1 -f ./Makefile.RAHasher +# SIGIL TITLE ID EXTRACTION LIBRARY +# Built from python-alias (not plain alpine) so the cffi extension matches the +# CPython ABI of the venv produced in backend-build. +FROM python-alias AS sigil-build +RUN apk add --no-cache \ + cmake \ + g++ \ + git \ + make \ + musl-dev + +ARG SIGIL_VERSION=44863fe614fd1c47e00c4bc28271e7a0d0e83a59 + +RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git && \ + cd ./argosy-sigil && \ + git checkout "${SIGIL_VERSION}" && \ + git submodule update --init --recursive && \ + cmake -B ./build-python -S . -DSIGIL_BUILD_CLI=OFF -DSIGIL_BUILD_TESTS=OFF && \ + cmake --build ./build-python --target sigil && \ + pip install --no-cache-dir cffi setuptools && \ + cd ./bindings/python && \ + python build_sigil.py && \ + mkdir /sigil-pkg && \ + cp ./sigil/*.py ./sigil/_sigil.*.so /sigil-pkg/ + + # FETCH EMULATORJS AND RUFFLE FROM alpine:${ALPINE_VERSION}@sha256:${ALPINE_SHA256} AS emulator-stage @@ -222,6 +249,11 @@ COPY --from=production-stage / / COPY --from=backend-build /src/.venv /src/.venv +# Optional sigil bindings for title ID extraction; the backend feature +# no-ops when the package is absent. +ARG PYTHON_VERSION +COPY --from=sigil-build /sigil-pkg /src/.venv/lib/python${PYTHON_VERSION}/site-packages/sigil + ENV PATH="/src/.venv/bin:${PATH}" # ScreenScraper developer (application) credentials, injected at build time from From 8fa9bc53e4ebd554c88b05c85cc9d9aa1b1ce430 Mon Sep 17 00:00:00 2001 From: nendo Date: Fri, 24 Jul 2026 03:45:00 +0900 Subject: [PATCH 04/40] Bump sigil pin for the Linux large-CHD fix --- Dockerfile | 2 +- docker/Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index be0d0eb58..ddcfd8ef1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -80,7 +80,7 @@ ENV PATH="/app/.venv/bin:${PATH}" # Build and install sigil (optional, for title ID extraction) # Placed after `uv sync` because the extension is compiled with the venv's # Python so the ABI matches. -ARG SIGIL_VERSION=44863fe614fd1c47e00c4bc28271e7a0d0e83a59 +ARG SIGIL_VERSION=542962a44ae6e385ef956b5d80d32e168dd88f44 RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git /tmp/argosy-sigil WORKDIR /tmp/argosy-sigil RUN git checkout "${SIGIL_VERSION}" \ diff --git a/docker/Dockerfile b/docker/Dockerfile index e01573741..9db83531a 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -116,7 +116,7 @@ RUN apk add --no-cache \ make \ musl-dev -ARG SIGIL_VERSION=44863fe614fd1c47e00c4bc28271e7a0d0e83a59 +ARG SIGIL_VERSION=542962a44ae6e385ef956b5d80d32e168dd88f44 RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git && \ cd ./argosy-sigil && \ From c90260500e49f3ef8020901ce47f5be32ce0eca3 Mon Sep 17 00:00:00 2001 From: nendo Date: Fri, 24 Jul 2026 04:23:41 +0900 Subject: [PATCH 05/40] Bump sigil pin for PS2 folder-prefix save_id --- Dockerfile | 2 +- docker/Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index ddcfd8ef1..0a4bf78d6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -80,7 +80,7 @@ ENV PATH="/app/.venv/bin:${PATH}" # Build and install sigil (optional, for title ID extraction) # Placed after `uv sync` because the extension is compiled with the venv's # Python so the ABI matches. -ARG SIGIL_VERSION=542962a44ae6e385ef956b5d80d32e168dd88f44 +ARG SIGIL_VERSION=d5752bcc435f5b30baca5c0f122aaaea6e63e93a RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git /tmp/argosy-sigil WORKDIR /tmp/argosy-sigil RUN git checkout "${SIGIL_VERSION}" \ diff --git a/docker/Dockerfile b/docker/Dockerfile index 9db83531a..f8a6bb911 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -116,7 +116,7 @@ RUN apk add --no-cache \ make \ musl-dev -ARG SIGIL_VERSION=542962a44ae6e385ef956b5d80d32e168dd88f44 +ARG SIGIL_VERSION=d5752bcc435f5b30baca5c0f122aaaea6e63e93a RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git && \ cd ./argosy-sigil && \ From fe0b4de169868d9bfaebaf99bafeb54cd88a5e8e Mon Sep 17 00:00:00 2001 From: nendo Date: Fri, 24 Jul 2026 05:20:09 +0900 Subject: [PATCH 06/40] Bump sigil pin for Switch CNMT content type and version --- Dockerfile | 2 +- docker/Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index 0a4bf78d6..e368cbd68 100644 --- a/Dockerfile +++ b/Dockerfile @@ -80,7 +80,7 @@ ENV PATH="/app/.venv/bin:${PATH}" # Build and install sigil (optional, for title ID extraction) # Placed after `uv sync` because the extension is compiled with the venv's # Python so the ABI matches. -ARG SIGIL_VERSION=d5752bcc435f5b30baca5c0f122aaaea6e63e93a +ARG SIGIL_VERSION=45fcd54c1e6e18b63f83a70b8d86a4f93fb53340 RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git /tmp/argosy-sigil WORKDIR /tmp/argosy-sigil RUN git checkout "${SIGIL_VERSION}" \ diff --git a/docker/Dockerfile b/docker/Dockerfile index f8a6bb911..1be2731e1 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -116,7 +116,7 @@ RUN apk add --no-cache \ make \ musl-dev -ARG SIGIL_VERSION=d5752bcc435f5b30baca5c0f122aaaea6e63e93a +ARG SIGIL_VERSION=45fcd54c1e6e18b63f83a70b8d86a4f93fb53340 RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git && \ cd ./argosy-sigil && \ From 4e696b389a2bff756f222fa469a9a0a29593cf1f Mon Sep 17 00:00:00 2001 From: nendo Date: Fri, 24 Jul 2026 06:04:07 +0900 Subject: [PATCH 07/40] Extract per-file Switch content type and version via CNMT Drop the top-level-only gate so update and DLC files in nested folders get extracted. Consume sigil's new content type and version: set the RomFile category from the binary content type (application/patch/addon -> GAME/UPDATE/DLC), authoritative over folder names for Switch when CNMT succeeds, and store the title version in a new BigInteger column. Updates now carry their own ...800 id and version instead of collapsing to the base. --- backend/adapters/services/sigil.py | 11 ++ .../versions/0103_sigil_title_version.py | 29 +++++ backend/endpoints/responses/rom.py | 1 + backend/handler/filesystem/roms_handler.py | 20 +++- backend/models/rom.py | 2 + backend/tests/adapters/services/test_sigil.py | 51 +++++++++ .../handler/filesystem/test_roms_handler.py | 104 ++++++++++++++++-- .../src/__generated__/models/RomFileSchema.ts | 1 + 8 files changed, 211 insertions(+), 8 deletions(-) create mode 100644 backend/alembic/versions/0103_sigil_title_version.py diff --git a/backend/adapters/services/sigil.py b/backend/adapters/services/sigil.py index 11601f8d0..27bba8a49 100644 --- a/backend/adapters/services/sigil.py +++ b/backend/adapters/services/sigil.py @@ -42,6 +42,8 @@ class SigilExtractionResult: title_id: str save_id: str usage: str + content_type: str | None = None + version: int | None = None class SigilService: @@ -81,8 +83,17 @@ class SigilService: log.error(f"Sigil extraction failed for {file_path}: {exc}") return None + raw_content_type = getattr(result, "switch_content_type", None) + content_type = ( + raw_content_type if raw_content_type not in (None, "", "unknown") else None + ) + return SigilExtractionResult( title_id=result.title_id, save_id=result.save_id, usage=result.usage, + content_type=content_type, + # Version 0 is a valid base-game version, so keep the int as-is; + # a missing field (non-Switch, older binding) maps to None. + version=getattr(result, "title_version", None), ) diff --git a/backend/alembic/versions/0103_sigil_title_version.py b/backend/alembic/versions/0103_sigil_title_version.py new file mode 100644 index 000000000..58a6a2ce5 --- /dev/null +++ b/backend/alembic/versions/0103_sigil_title_version.py @@ -0,0 +1,29 @@ +"""Add sigil-extracted title_version column to rom_files (Switch title +versions are u32, stored as BigInteger). + +Revision ID: 0103_sigil_title_version +Revises: 0102_sigil_title_ids +Create Date: 2026-07-24 00:00:00.000000 + +""" + +import sqlalchemy as sa +from alembic import op + +# revision identifiers, used by Alembic. +revision = "0103_sigil_title_version" +down_revision = "0102_sigil_title_ids" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.add_column( + "rom_files", + sa.Column("title_version", sa.BigInteger(), nullable=True), + if_not_exists=True, + ) + + +def downgrade() -> None: + op.drop_column("rom_files", "title_version", if_exists=True) diff --git a/backend/endpoints/responses/rom.py b/backend/endpoints/responses/rom.py index 8cf766ee7..0111d3e61 100644 --- a/backend/endpoints/responses/rom.py +++ b/backend/endpoints/responses/rom.py @@ -200,6 +200,7 @@ class RomFileSchema(BaseModel): chd_sha1_hash: str | None title_id: str | None save_id: str | None + title_version: int | None archive_members: list[RomArchiveMember] | None category: RomFileCategory | None track_meta: TrackMetaSchema | None = None diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index b44461f17..edd996f6e 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -175,6 +175,15 @@ class ParsedRomFiles: save_usage: SaveUsage | None = None +# Maps sigil's Switch CNMT content type to the RomFile category. Authoritative +# over folder-derived categories when the binary parse succeeds. +SWITCH_CONTENT_TYPE_CATEGORIES: dict[str, RomFileCategory] = { + "application": RomFileCategory.GAME, + "patch": RomFileCategory.UPDATE, + "addon": RomFileCategory.DLC, +} + + def _parse_save_usage(usage: str) -> SaveUsage | None: try: return SaveUsage(usage) @@ -419,6 +428,13 @@ class FSRomsHandler(FSHandler): return rom_file.title_id = extraction.title_id rom_file.save_id = extraction.save_id + rom_file.title_version = extraction.version + # For Switch, the binary CNMT content type is authoritative over the + # folder-derived category. Leave the folder category when absent. + if extraction.content_type is not None: + category = SWITCH_CONTENT_TYPE_CATEGORIES.get(extraction.content_type) + if category is not None: + rom_file.category = category sigil_extractions.append(extraction) cnfg = cm.get_config() @@ -533,7 +549,9 @@ class FSRomsHandler(FSHandler): file_name=file_name, file_hash=file_hash, ) - if sigil_platform and is_top_level: + # Extract from every file (base, updates, DLC in subfolders), not + # just the top-level one: sigil returns None for unparseable files. + if sigil_platform: await _extract_title_id(rom_file, Path(f_path, file_name)) rom_files.append(rom_file) elif hashable_platform and rom_ext in ARCHIVE_READERS: diff --git a/backend/models/rom.py b/backend/models/rom.py index 66a139e96..b141179bd 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -131,6 +131,8 @@ class RomFile(BaseModel): chd_sha1_hash: Mapped[str | None] = mapped_column(String(100)) title_id: Mapped[str | None] = mapped_column(String(100)) save_id: Mapped[str | None] = mapped_column(String(100)) + # BigInteger: Switch title versions are u32 and can exceed signed 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/tests/adapters/services/test_sigil.py b/backend/tests/adapters/services/test_sigil.py index ed38bd1cb..9826039d9 100644 --- a/backend/tests/adapters/services/test_sigil.py +++ b/backend/tests/adapters/services/test_sigil.py @@ -26,6 +26,8 @@ def make_result( title_id: str = "0100ABCD12340000", save_id: str = "0100ABCD12340000", usage: str = "folder-exact", + switch_content_type: str | None = None, + title_version: int | None = None, ) -> types.SimpleNamespace: return types.SimpleNamespace( title_id=title_id, @@ -35,6 +37,8 @@ def make_result( source="binary", usage=usage, experimental=False, + switch_content_type=switch_content_type, + title_version=title_version, ) @@ -86,6 +90,53 @@ class TestSigilService: usage="folder-exact", ) + @pytest.mark.asyncio + async def test_maps_switch_content_type_and_version( + self, service: SigilService, monkeypatch + ): + extract = Mock( + return_value=make_result( + switch_content_type="patch", + title_version=196608, + ) + ) + monkeypatch.setattr(sigil_adapter, "sigil", make_fake_sigil(extract)) + + result = await service.extract_title_id(UPS.SWITCH, "/roms/switch/game.nsp") + + assert result is not None + assert result.content_type == "patch" + assert result.version == 196608 + + @pytest.mark.asyncio + async def test_version_zero_is_preserved(self, service: SigilService, monkeypatch): + extract = Mock( + return_value=make_result( + switch_content_type="application", + title_version=0, + ) + ) + monkeypatch.setattr(sigil_adapter, "sigil", make_fake_sigil(extract)) + + result = await service.extract_title_id(UPS.SWITCH, "/roms/switch/game.xci") + + assert result is not None + assert result.content_type == "application" + assert result.version == 0 + + @pytest.mark.asyncio + @pytest.mark.parametrize("raw", ["unknown", "", None]) + async def test_absent_content_type_maps_to_none( + self, service: SigilService, monkeypatch, raw: str | None + ): + extract = Mock(return_value=make_result(switch_content_type=raw)) + monkeypatch.setattr(sigil_adapter, "sigil", make_fake_sigil(extract)) + + result = await service.extract_title_id(UPS.SWITCH, "/roms/switch/game.nsp") + + assert result is not None + assert result.content_type is None + @pytest.mark.asyncio @pytest.mark.parametrize("code", ["NOT_FOUND", "UNSUPPORTED_FORMAT", "NEEDS_KEY"]) async def test_routine_sigil_error_returns_none( diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index c1ef9e047..21e76a3b1 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -1305,7 +1305,7 @@ class TestSigilTitleIdExtraction: ) @pytest.mark.asyncio - async def test_multi_part_extraction_prefers_base_game( + async def test_multi_part_extraction_covers_nested_files( self, tmp_path: Path, config: Config ): platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") @@ -1314,7 +1314,11 @@ class TestSigilTitleIdExtraction: tmp_path, platform, "Zelda", - ["Zelda [base].nsp", "Zelda [update].nsp", "extras/nested.nsp"], + [ + "Zelda [base].nsp", + "updates/Zelda [update].nsp", + "dlc/Zelda [dlc].nsp", + ], ) async def fake_extract( @@ -1325,11 +1329,23 @@ class TestSigilTitleIdExtraction: title_id="0100ABCD12340800", save_id="0100ABCD12340800", usage="folder-exact", + content_type="patch", + version=196608, + ) + if "dlc" in file_path: + return SigilExtractionResult( + title_id="0100ABCD12341001", + save_id="0100ABCD12341001", + usage="folder-exact", + content_type="addon", + version=0, ) return SigilExtractionResult( title_id="0100ABCD12340000", save_id="0100ABCD12340000", usage="folder-exact", + content_type="application", + version=0, ) mock_extract = AsyncMock(side_effect=fake_extract) @@ -1340,16 +1356,90 @@ class TestSigilTitleIdExtraction: parsed = await handler.get_rom_files(rom) by_name = {rf.file_name: rf for rf in parsed.rom_files} - assert by_name["Zelda [base].nsp"].title_id == "0100ABCD12340000" - assert by_name["Zelda [update].nsp"].title_id == "0100ABCD12340800" - # Nested files are not extracted - assert by_name["nested.nsp"].title_id is None - assert mock_extract.await_count == 2 + base = by_name["Zelda [base].nsp"] + assert base.title_id == "0100ABCD12340000" + assert base.title_version == 0 + assert base.category == RomFileCategory.GAME + + update = by_name["Zelda [update].nsp"] + assert update.title_id == "0100ABCD12340800" + assert update.title_version == 196608 + assert update.category == RomFileCategory.UPDATE + + dlc = by_name["Zelda [dlc].nsp"] + assert dlc.title_id == "0100ABCD12341001" + assert dlc.title_version == 0 + assert dlc.category == RomFileCategory.DLC + + # All three files, including the nested update/DLC, are extracted. + assert mock_extract.await_count == 3 + + # The base game is still selected for the rom-level values. assert parsed.title_id == "0100ABCD12340000" assert parsed.save_id == "0100ABCD12340000" assert parsed.save_usage == SaveUsage.FOLDER_EXACT + @pytest.mark.asyncio + async def test_content_type_overrides_folder_category( + self, tmp_path: Path, config: Config + ): + platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") + handler = self._make_handler(tmp_path) + # Folder name "dlc" would otherwise derive category DLC, but the binary + # content type says this is the base application. + rom = self._make_multi_part_rom( + tmp_path, platform, "Zelda", ["dlc/Zelda [base].nsp"] + ) + + mock_extract = AsyncMock( + return_value=SigilExtractionResult( + title_id="0100ABCD12340000", + save_id="0100ABCD12340000", + usage="folder-exact", + content_type="application", + version=0, + ) + ) + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with patch(self.SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files(rom) + + assert parsed.rom_files[0].category == RomFileCategory.GAME + + @pytest.mark.asyncio + async def test_folder_category_preserved_when_content_type_absent( + self, tmp_path: Path, config: Config + ): + platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") + handler = self._make_handler(tmp_path) + rom = self._make_multi_part_rom( + tmp_path, platform, "Zelda", ["dlc/Zelda [addon].nsp"] + ) + + # CNMT miss: title id is present but content type is None. + mock_extract = AsyncMock( + return_value=SigilExtractionResult( + title_id="0100ABCD12341001", + save_id="0100ABCD12341001", + usage="folder-exact", + content_type=None, + version=None, + ) + ) + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with patch(self.SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files(rom) + + rom_file = parsed.rom_files[0] + # Folder-derived category survives, and title_version stays None. + assert rom_file.category == RomFileCategory.DLC + assert rom_file.title_version is None + @pytest.mark.asyncio async def test_switch_base_derivation_from_update_only_folder( self, tmp_path: Path, config: Config diff --git a/frontend/src/__generated__/models/RomFileSchema.ts b/frontend/src/__generated__/models/RomFileSchema.ts index ff22fc54e..68d9066a7 100644 --- a/frontend/src/__generated__/models/RomFileSchema.ts +++ b/frontend/src/__generated__/models/RomFileSchema.ts @@ -23,6 +23,7 @@ export type RomFileSchema = { chd_sha1_hash: (string | null); title_id: (string | null); save_id: (string | null); + title_version: (number | null); archive_members: (Array | null); category: (RomFileCategory | null); track_meta?: (TrackMetaSchema | null); From aba14c0d598603fdd07144d9b50f71d8451ab9ed Mon Sep 17 00:00:00 2001 From: nendo Date: Fri, 24 Jul 2026 06:14:41 +0900 Subject: [PATCH 08/40] Add opt-in Switch title ID filename embedding New config.yml flag filesystem.embed_switch_title_ids (default off) renames Switch/Switch 2 files during scan to embed their binary title id and version (Name [TITLEID][vN].ext), then reconciles the DB record. Idempotent (skips names already carrying a title-id bracket), collision-safe, and Switch-only. Single-file roms update Rom.fs_name; multi-part inner files update only their RomFile name. Driven by the CNMT-extracted per-file ids, this is the correct form of the filename embedding the original PR group attempted via filename heuristics. --- backend/config/config_manager.py | 5 + backend/endpoints/sockets/scan.py | 13 + backend/handler/filesystem/roms_handler.py | 84 ++++- backend/tests/endpoints/sockets/test_scan.py | 92 ++++++ .../handler/filesystem/test_roms_handler.py | 305 ++++++++++++++++++ 5 files changed, 496 insertions(+), 3 deletions(-) diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index 0126ef44f..2e3ca2a6d 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -181,6 +181,7 @@ class Config: FIRMWARE_FOLDER_NAME: str SKIP_HASH_CALCULATION: bool SKIP_TITLE_ID_EXTRACTION: bool + EMBED_SWITCH_TITLE_IDS: bool EJS_DEBUG: bool EJS_CACHE_LIMIT: int | None EJS_DISABLE_AUTO_UNLOAD: bool @@ -435,6 +436,9 @@ class ConfigManager: SKIP_TITLE_ID_EXTRACTION=pydash.get( self._raw_config, "filesystem.skip_title_id_extraction", False ), + EMBED_SWITCH_TITLE_IDS=pydash.get( + self._raw_config, "filesystem.embed_switch_title_ids", False + ), EJS_DEBUG=pydash.get(self._raw_config, "emulatorjs.debug", False), EJS_CACHE_LIMIT=pydash.get( self._raw_config, "emulatorjs.cache_limit", None @@ -856,6 +860,7 @@ class ConfigManager: "firmware_folder": self.config.FIRMWARE_FOLDER_NAME, "skip_hash_calculation": self.config.SKIP_HASH_CALCULATION, "skip_title_id_extraction": self.config.SKIP_TITLE_ID_EXTRACTION, + "embed_switch_title_ids": self.config.EMBED_SWITCH_TITLE_IDS, }, "system": { "platforms": self.config.PLATFORMS_BINDING, diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index 9a3aadb83..c6f194070 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -297,6 +297,7 @@ async def _identify_rom( calculate_hashes = not cm.get_config().SKIP_HASH_CALCULATION extract_title_ids = not cm.get_config().SKIP_TITLE_ID_EXTRACTION + embed_title_ids = cm.get_config().EMBED_SWITCH_TITLE_IDS # Switch title id extraction needs the console's prod.keys to decrypt # XCI/NSP headers; resolve it from the scanned firmware when present. @@ -325,6 +326,7 @@ async def _identify_rom( calculate_hashes=calculate_hashes, extract_title_ids=extract_title_ids, prod_keys_path=prod_keys_path, + embed_title_ids=embed_title_ids, ) fs_rom.update( { @@ -338,6 +340,11 @@ async def _identify_rom( "save_usage": parsed_rom_files.save_usage, } ) + # A single-file rom renamed on disk to embed its title id must carry the + # new name into both the new-entry insert and any hash reassociation. + if parsed_rom_files.renamed_rom_fs_name: + rom_attrs["fs_name"] = parsed_rom_files.renamed_rom_fs_name + fs_rom["fs_name"] = parsed_rom_files.renamed_rom_fs_name files_built = True missing_match = db_rom_handler.get_matching_missing_rom( @@ -395,6 +402,7 @@ async def _identify_rom( calculate_hashes=calculate_hashes, extract_title_ids=extract_title_ids, prod_keys_path=prod_keys_path, + embed_title_ids=embed_title_ids, ) fs_rom.update( { @@ -408,6 +416,11 @@ async def _identify_rom( "save_usage": parsed_rom_files.save_usage, } ) + # scan_rom persists Rom.fs_name from fs_rom["fs_name"]; keep the rom + # object in sync so its in-memory identity matches the renamed file. + if parsed_rom_files.renamed_rom_fs_name: + fs_rom["fs_name"] = parsed_rom_files.renamed_rom_fs_name + rom.fs_name = parsed_rom_files.renamed_rom_fs_name # For a COMPLETE rescan, wipe all downloaded resources before re-fetching so # stale files (e.g. a cover from the wrong region) can't be reused. The diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index edd996f6e..7b56c6ee0 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -27,6 +27,7 @@ from exceptions.fs_exceptions import ( RomsNotFoundException, ) from handler.metadata.base_handler import UniversalPlatformSlug as UPS +from logger.logger import log from models.platform import Platform from models.rom import Rom, RomFile, RomFileCategory, SaveUsage, TrackMeta from utils.archives import ( @@ -173,6 +174,10 @@ class ParsedRomFiles: title_id: str | None = None save_id: str | None = None save_usage: SaveUsage | None = None + # Set when a single-file rom's file was renamed on disk to embed its title + # id, so the caller can reconcile Rom.fs_name. None for multi-part roms + # (whose folder name is unchanged) or when no rename happened. + renamed_rom_fs_name: str | None = None # Maps sigil's Switch CNMT content type to the RomFile category. Authoritative @@ -183,6 +188,53 @@ SWITCH_CONTENT_TYPE_CATEGORIES: dict[str, RomFileCategory] = { "addon": RomFileCategory.DLC, } +# Platforms whose files may have their title id embedded in the filename. +EMBED_TITLE_ID_PLATFORM_SLUGS = frozenset((UPS.SWITCH, UPS.SWITCH_2)) + +# A 16-hex-digit title id in square brackets, e.g. [0100F4700B2E0000]. Used both +# to detect files that already carry an embedded id (idempotency) and to +# validate the id before embedding it. +SWITCH_TITLE_ID_BRACKET_REGEX = re.compile(r"\[[0-9A-Fa-f]{16}\]") +SWITCH_TITLE_ID_REGEX = re.compile(r"^[0-9A-Fa-f]{16}$") + + +def _embed_switch_title_id_in_name( + abs_file_path: Path, title_id: str, title_version: int | None +) -> Path | None: + """Rename a Switch ROM file to embed its title id and version as + ` [TITLEID][vVERSION]` before the extension, preserving existing tags. + + Returns the new absolute path, or None when the file was left untouched: + it already carries a 16-hex title-id bracket, the id is not a valid 16-hex + value, or the target name already exists on disk. The os.rename is the only + side effect. + """ + name = abs_file_path.name + + if SWITCH_TITLE_ID_BRACKET_REGEX.search(name): + log.debug(f"{name} already has an embedded title id, skipping rename") + return None + + if not SWITCH_TITLE_ID_REGEX.match(title_id): + log.debug(f"Title id {title_id!r} is not a 16-hex value, skipping rename") + return None + + version = title_version if title_version is not None else 0 + new_name = ( + f"{abs_file_path.stem} [{title_id.upper()}][v{version}]{abs_file_path.suffix}" + ) + new_path = abs_file_path.with_name(new_name) + + if new_path.exists(): + log.warning( + f"Cannot embed title id: target {new_name} already exists, skipping rename" + ) + return None + + os.rename(abs_file_path, new_path) + log.info(f"Embedded Switch title id: renamed {name} to {new_name}") + return new_path + def _parse_save_usage(usage: str) -> SaveUsage | None: try: @@ -400,6 +452,7 @@ class FSRomsHandler(FSHandler): calculate_hashes: bool = True, extract_title_ids: bool = True, prod_keys_path: str | None = None, + embed_title_ids: bool = False, ) -> ParsedRomFiles: from adapters.services.rahasher import RAHasherService from handler.metadata import meta_ra_handler @@ -420,7 +473,17 @@ class FSRomsHandler(FSHandler): sigil_platform = extract_title_ids and rom.platform_slug in SIGIL_PLATFORM_SLUGS sigil_extractions: list[SigilExtractionResult] = [] - async def _extract_title_id(rom_file: RomFile, abs_file_path: Path) -> None: + # Filename embedding is Switch-only, even though sigil covers more + # platforms; other platforms never have their files renamed. + embed_switch = ( + embed_title_ids and rom.platform_slug in EMBED_TITLE_ID_PLATFORM_SLUGS + ) + renamed_rom_fs_name: str | None = None + + async def _extract_title_id( + rom_file: RomFile, abs_file_path: Path, is_rom_level: bool = False + ) -> None: + nonlocal renamed_rom_fs_name extraction = await SigilService().extract_title_id( rom.platform_slug, str(abs_file_path), prod_keys_path ) @@ -437,6 +500,20 @@ class FSRomsHandler(FSHandler): rom_file.category = category sigil_extractions.append(extraction) + if embed_switch and extraction.title_id: + new_path = _embed_switch_title_id_in_name( + abs_file_path, extraction.title_id, extraction.version + ) + if new_path is not None: + # The file stays in the same directory, so only file_name + # changes; file_path is unaffected. + rom_file.file_name = new_path.name + # A single-file rom's file name IS the Rom.fs_name, so the + # caller must reconcile it. Multi-part inner files don't + # change the rom folder name. + if is_rom_level: + renamed_rom_fs_name = new_path.name + cnfg = cm.get_config() excluded_file_names = cnfg.EXCLUDED_MULTI_PARTS_FILES excluded_file_exts = cnfg.EXCLUDED_MULTI_PARTS_EXT @@ -680,7 +757,7 @@ class FSRomsHandler(FSHandler): file_hash=file_hash, ) if sigil_platform: - await _extract_title_id(rom_file, rom_dir) + await _extract_title_id(rom_file, rom_dir, is_rom_level=True) rom_files.append(rom_file) else: file_hash = FileHash( @@ -698,7 +775,7 @@ class FSRomsHandler(FSHandler): # Archives keep hashes only; sigil reads title ids from the ROM # binary itself. if sigil_platform and rom_ext not in ARCHIVE_READERS: - await _extract_title_id(rom_file, rom_dir) + await _extract_title_id(rom_file, rom_dir, is_rom_level=True) rom_files.append(rom_file) rom_title_id, rom_save_id, rom_save_usage = _rom_level_title_values( @@ -722,6 +799,7 @@ class FSRomsHandler(FSHandler): title_id=rom_title_id, save_id=rom_save_id, save_usage=rom_save_usage, + renamed_rom_fs_name=renamed_rom_fs_name, ) def _calculate_rom_hashes( diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index 6852860c4..5cb5782b0 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -553,6 +553,98 @@ class TestIdentifyRomReassociation: assert created.fs_name == "New Name.zip" +class TestIdentifyRomTitleIdEmbedRename: + """`_identify_rom` reconciles Rom.fs_name when a single-file Switch rom is + renamed on disk to embed its title id.""" + + NEW_NAME = "Game [0100ABCD12340000][v0].nsp" + + @pytest.fixture + def patched(self, mocker): + mocker.patch.object( + scan_module, "redis_client", Mock(get=Mock(return_value=None)) + ) + + fs = scan_module.fs_rom_handler + mocker.patch.object( + fs, + "parse_tags", + return_value=ParsedTags( + version="", revision="", regions=[], languages=[], other_tags=[] + ), + ) + mocker.patch.object(fs, "get_roms_fs_structure", return_value="switch/roms") + mocker.patch.object(fs, "get_file_name_with_no_tags", return_value="Game") + mocker.patch.object( + fs, + "get_rom_files", + AsyncMock( + return_value=ParsedRomFiles( + rom_files=[], + crc_hash="crc", + md5_hash="md5", + sha1_hash="sha1", + ra_hash="", + title_id="0100ABCD12340000", + renamed_rom_fs_name=self.NEW_NAME, + ) + ), + ) + + config = MagicMock() + config.SKIP_HASH_CALCULATION = False + config.SKIP_TITLE_ID_EXTRACTION = False + config.EMBED_SWITCH_TITLE_IDS = True + mocker.patch.object(scan_module.cm, "get_config", return_value=config) + + mocker.patch.object( + scan_module, + "scan_rom", + AsyncMock(return_value=MagicMock(is_identified=False)), + ) + + db = mocker.patch.object(scan_module, "db_rom_handler") + db.add_rom.return_value = MagicMock(is_identified=False, id=99) + db.get_matching_missing_rom.return_value = None + return db + + def _platform(self): + platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") + platform.id = 1 + return platform + + async def test_new_entry_carries_embedded_name(self, patched): + db = patched + fs_rom: FSRom = { + "fs_name": "Game.nsp", + "flat": True, + "nested": False, + "files": [], + "crc_hash": "", + "md5_hash": "", + "sha1_hash": "", + "ra_hash": "", + } + await _identify_rom( + platform=self._platform(), + fs_rom=fs_rom, + rom=None, + scan_type=ScanType.HASHES, + roms_ids=[], + metadata_sources=[], + launchbox_remote_enabled=False, + playmatch_enabled=False, + socket_manager=AsyncMock(), + scan_stats=AsyncMock(), + ) + + # The initial insert carries the renamed on-disk name, and the shared + # fs_rom dict is updated so scan_rom persists the same name. + created = db.add_rom.call_args_list[0].args[0] + assert created.fs_name == self.NEW_NAME + assert fs_rom["fs_name"] == self.NEW_NAME + + class TestIdentifyPlatformMarksMissingBeforeScan: """`_identify_platform` must flag missing entries before identifying files. diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index 21e76a3b1..1c0c87e7c 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -18,6 +18,7 @@ from handler.filesystem.base_handler import ( from handler.filesystem.roms_handler import ( FileHash, FSRomsHandler, + _embed_switch_title_id_in_name, ) from models.platform import Platform from models.rom import Rom, RomFile, RomFileCategory, SaveUsage @@ -1624,6 +1625,310 @@ class TestSigilTitleIdExtraction: assert parsed.title_id is None +class TestEmbedSwitchTitleIdInName: + """The pure rename helper that embeds a Switch title id into a filename.""" + + def test_embeds_id_and_version(self, tmp_path: Path): + src = tmp_path / "Moonlighter.xci" + src.write_bytes(b"rom") + + new_path = _embed_switch_title_id_in_name(src, "0100f4700b2e0000", 3) + + assert new_path is not None + assert new_path.name == "Moonlighter [0100F4700B2E0000][v3].xci" + assert new_path.exists() + assert not src.exists() + + def test_version_none_defaults_to_zero(self, tmp_path: Path): + src = tmp_path / "Game.nsp" + src.write_bytes(b"rom") + + new_path = _embed_switch_title_id_in_name(src, "0100ABCD12340000", None) + + assert new_path is not None + assert new_path.name == "Game [0100ABCD12340000][v0].nsp" + + def test_preserves_existing_tags(self, tmp_path: Path): + src = tmp_path / "Game (USA) (Rev 1).xci" + src.write_bytes(b"rom") + + new_path = _embed_switch_title_id_in_name(src, "0100ABCD12340000", 0) + + assert new_path is not None + assert new_path.name == "Game (USA) (Rev 1) [0100ABCD12340000][v0].xci" + + def test_idempotent_when_bracket_already_present(self, tmp_path: Path): + src = tmp_path / "Game [0100ABCD12340000][v0].nsp" + src.write_bytes(b"rom") + + assert _embed_switch_title_id_in_name(src, "0100ABCD12340000", 0) is None + assert src.exists() + + def test_invalid_title_id_skips(self, tmp_path: Path): + src = tmp_path / "Game.nsp" + src.write_bytes(b"rom") + + assert _embed_switch_title_id_in_name(src, "NOT-A-TITLE-ID", 0) is None + assert src.exists() + + def test_collision_skips_and_leaves_original(self, tmp_path: Path): + src = tmp_path / "Game.nsp" + src.write_bytes(b"original") + target = tmp_path / "Game [0100ABCD12340000][v0].nsp" + target.write_bytes(b"existing") + + assert _embed_switch_title_id_in_name(src, "0100ABCD12340000", 0) is None + assert src.read_bytes() == b"original" + assert target.read_bytes() == b"existing" + + +class TestSwitchTitleIdEmbedding: + """Config-gated on-disk renaming of Switch files during get_rom_files.""" + + SIGIL_PATCH_TARGET = "adapters.services.sigil.SigilService.extract_title_id" + + @pytest.fixture + def config(self): + cnfg = Config( + EXCLUDED_PLATFORMS=[], + EXCLUDED_SINGLE_EXT=[], + EXCLUDED_SINGLE_FILES=[], + EXCLUDED_MULTI_FILES=[], + EXCLUDED_MULTI_PARTS_EXT=[], + EXCLUDED_MULTI_PARTS_FILES=[], + PLATFORMS_BINDING={}, + PLATFORMS_VERSIONS={}, + ROMS_FOLDER_NAME="roms", + FIRMWARE_FOLDER_NAME="bios", + ) + cnfg.has_structure_path_b = True + return cnfg + + def _make_handler(self, tmp_path: Path) -> FSRomsHandler: + handler = FSRomsHandler() + handler.base_path = tmp_path + return handler + + def _make_single_file_rom( + self, tmp_path: Path, platform: Platform, fs_name: str + ) -> Rom: + roms_path = tmp_path / platform.fs_slug / "roms" + roms_path.mkdir(parents=True, exist_ok=True) + (roms_path / fs_name).write_bytes(b"rom-bytes") + return Rom( + id=1, + fs_name=fs_name, + fs_path=f"{platform.fs_slug}/roms", + platform=platform, + ) + + def _make_multi_part_rom( + self, tmp_path: Path, platform: Platform, fs_name: str, file_names: list[str] + ) -> Rom: + rom_dir = tmp_path / platform.fs_slug / "roms" / fs_name + rom_dir.mkdir(parents=True, exist_ok=True) + for file_name in file_names: + file_path = rom_dir / file_name + file_path.parent.mkdir(parents=True, exist_ok=True) + file_path.write_bytes(b"rom-bytes") + return Rom( + id=1, + fs_name=fs_name, + fs_extension="", + fs_path=f"{platform.fs_slug}/roms", + platform=platform, + ) + + @pytest.mark.asyncio + async def test_flag_off_leaves_file_unchanged(self, tmp_path: Path, config: Config): + platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") + handler = self._make_handler(tmp_path) + rom = self._make_single_file_rom(tmp_path, platform, "Game.nsp") + + extraction = SigilExtractionResult( + title_id="0100ABCD12340000", + save_id="0100ABCD12340000", + usage="folder-exact", + ) + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)): + parsed = await handler.get_rom_files(rom, embed_title_ids=False) + + assert parsed.rom_files[0].file_name == "Game.nsp" + assert parsed.renamed_rom_fs_name is None + assert (tmp_path / "switch/roms/Game.nsp").exists() + + @pytest.mark.asyncio + async def test_single_file_renamed_and_reconciled( + self, tmp_path: Path, config: Config + ): + platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") + handler = self._make_handler(tmp_path) + rom = self._make_single_file_rom(tmp_path, platform, "Moonlighter.xci") + + extraction = SigilExtractionResult( + title_id="0100F4700B2E0000", + save_id="0100F4700B2E0000", + usage="folder-exact", + version=0, + ) + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)): + parsed = await handler.get_rom_files(rom, embed_title_ids=True) + + new_name = "Moonlighter [0100F4700B2E0000][v0].xci" + assert parsed.rom_files[0].file_name == new_name + assert parsed.rom_files[0].file_path == "switch/roms" + assert parsed.renamed_rom_fs_name == new_name + assert (tmp_path / "switch/roms" / new_name).exists() + assert not (tmp_path / "switch/roms/Moonlighter.xci").exists() + + @pytest.mark.asyncio + async def test_already_embedded_file_skipped(self, tmp_path: Path, config: Config): + platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") + handler = self._make_handler(tmp_path) + fs_name = "Game [0100ABCD12340000][v0].nsp" + rom = self._make_single_file_rom(tmp_path, platform, fs_name) + + extraction = SigilExtractionResult( + title_id="0100ABCD12340000", + save_id="0100ABCD12340000", + usage="folder-exact", + ) + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)): + parsed = await handler.get_rom_files(rom, embed_title_ids=True) + + assert parsed.rom_files[0].file_name == fs_name + assert parsed.renamed_rom_fs_name is None + assert (tmp_path / "switch/roms" / fs_name).exists() + + @pytest.mark.asyncio + async def test_non_switch_platform_never_renamed( + self, tmp_path: Path, config: Config + ): + platform = Platform(name="PlayStation Portable", slug="psp", fs_slug="psp") + handler = self._make_handler(tmp_path) + rom = self._make_single_file_rom(tmp_path, platform, "Game.iso") + + extraction = SigilExtractionResult( + title_id="0100ABCD12340000", + save_id="0100ABCD12340000", + usage="folder-exact", + ) + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)): + parsed = await handler.get_rom_files(rom, embed_title_ids=True) + + assert parsed.rom_files[0].file_name == "Game.iso" + assert parsed.renamed_rom_fs_name is None + assert (tmp_path / "psp/roms/Game.iso").exists() + + @pytest.mark.asyncio + async def test_collision_target_exists_skips(self, tmp_path: Path, config: Config): + platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") + handler = self._make_handler(tmp_path) + rom = self._make_single_file_rom(tmp_path, platform, "Game.nsp") + target = tmp_path / "switch/roms/Game [0100ABCD12340000][v0].nsp" + target.write_bytes(b"existing") + + extraction = SigilExtractionResult( + title_id="0100ABCD12340000", + save_id="0100ABCD12340000", + usage="folder-exact", + ) + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)): + parsed = await handler.get_rom_files(rom, embed_title_ids=True) + + assert parsed.rom_files[0].file_name == "Game.nsp" + assert parsed.renamed_rom_fs_name is None + assert (tmp_path / "switch/roms/Game.nsp").read_bytes() == b"rom-bytes" + assert target.read_bytes() == b"existing" + + @pytest.mark.asyncio + async def test_no_title_id_not_renamed(self, tmp_path: Path, config: Config): + platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") + handler = self._make_handler(tmp_path) + rom = self._make_single_file_rom(tmp_path, platform, "Game.nsp") + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=None)): + parsed = await handler.get_rom_files(rom, embed_title_ids=True) + + assert parsed.rom_files[0].file_name == "Game.nsp" + assert parsed.renamed_rom_fs_name is None + assert (tmp_path / "switch/roms/Game.nsp").exists() + + @pytest.mark.asyncio + async def test_multi_part_nested_files_renamed( + self, tmp_path: Path, config: Config + ): + platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") + handler = self._make_handler(tmp_path) + rom = self._make_multi_part_rom( + tmp_path, + platform, + "Zelda", + ["Zelda base.nsp", "updates/Zelda update.nsp", "dlc/Zelda dlc.nsp"], + ) + + async def fake_extract( + platform_slug: str, file_path: str, prod_keys_path: str | None = None + ) -> SigilExtractionResult: + if "update" in file_path: + return SigilExtractionResult( + title_id="0100ABCD12340800", + save_id="0100ABCD12340800", + usage="folder-exact", + content_type="patch", + version=196608, + ) + if "dlc" in file_path: + return SigilExtractionResult( + title_id="0100ABCD12341001", + save_id="0100ABCD12341001", + usage="folder-exact", + content_type="addon", + version=0, + ) + return SigilExtractionResult( + title_id="0100ABCD12340000", + save_id="0100ABCD12340000", + usage="folder-exact", + content_type="application", + version=0, + ) + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with patch(self.SIGIL_PATCH_TARGET, AsyncMock(side_effect=fake_extract)): + parsed = await handler.get_rom_files(rom, embed_title_ids=True) + + names = {rf.file_name for rf in parsed.rom_files} + assert "Zelda base [0100ABCD12340000][v0].nsp" in names + assert "Zelda update [0100ABCD12340800][v196608].nsp" in names + assert "Zelda dlc [0100ABCD12341001][v0].nsp" in names + # A multi-part rom's folder name is not changed by inner-file renames. + assert parsed.renamed_rom_fs_name is None + rom_dir = tmp_path / "switch/roms/Zelda" + assert (rom_dir / "Zelda base [0100ABCD12340000][v0].nsp").exists() + assert ( + rom_dir / "updates/Zelda update [0100ABCD12340800][v196608].nsp" + ).exists() + + class TestExtractCHDHash: """Test suite for extract_chd_hash function""" From 4aaf6d6280570cce5db80e9308d4524014f89035 Mon Sep 17 00:00:00 2001 From: nendo Date: Fri, 24 Jul 2026 06:18:41 +0900 Subject: [PATCH 09/40] Show Switch title version in the file row Adds a compact version chip beside the per-file Title ID, shown only when the version is meaningful (hidden for the 0 that base games and DLC report), with the rom.version locale key across all locales. --- frontend/src/locales/bg_BG/rom.json | 1 + frontend/src/locales/cs_CZ/rom.json | 1 + frontend/src/locales/de_DE/rom.json | 1 + frontend/src/locales/en_GB/rom.json | 1 + frontend/src/locales/en_US/rom.json | 1 + frontend/src/locales/es_ES/rom.json | 1 + frontend/src/locales/fr_FR/rom.json | 1 + frontend/src/locales/hu_HU/rom.json | 1 + frontend/src/locales/it_IT/rom.json | 1 + frontend/src/locales/ja_JP/rom.json | 1 + frontend/src/locales/ko_KR/rom.json | 1 + frontend/src/locales/pl_PL/rom.json | 1 + frontend/src/locales/pt_BR/rom.json | 1 + frontend/src/locales/ro_RO/rom.json | 1 + frontend/src/locales/ru_RU/rom.json | 1 + frontend/src/locales/tr_TR/rom.json | 1 + frontend/src/locales/zh_CN/rom.json | 1 + frontend/src/locales/zh_TW/rom.json | 1 + .../src/v2/components/GameDetails/FilesTab/FileRow.vue | 7 +++++++ frontend/src/v2/utils/romArtwork.test.ts | 1 + 20 files changed, 26 insertions(+) diff --git a/frontend/src/locales/bg_BG/rom.json b/frontend/src/locales/bg_BG/rom.json index fb2fd97fa..1dc7cf049 100644 --- a/frontend/src/locales/bg_BG/rom.json +++ b/frontend/src/locales/bg_BG/rom.json @@ -451,6 +451,7 @@ "verification": "Потвърждение", "verified-rom": "Потвърден ROM", "verified-rom-hint": "Hash verified against ROM database", + "version": "Version", "versions-count": "{n} версии", "volume-mute": "Заглуши", "volume-unmute": "Включи звука", diff --git a/frontend/src/locales/cs_CZ/rom.json b/frontend/src/locales/cs_CZ/rom.json index 3b013b3af..5e547bca4 100644 --- a/frontend/src/locales/cs_CZ/rom.json +++ b/frontend/src/locales/cs_CZ/rom.json @@ -451,6 +451,7 @@ "verification": "Ověření", "verified-rom": "Ověřená ROM", "verified-rom-hint": "Hash verified against ROM database", + "version": "Version", "versions-count": "{n} verzí", "volume-mute": "Ztlumit", "volume-unmute": "Zrušit ztlumení", diff --git a/frontend/src/locales/de_DE/rom.json b/frontend/src/locales/de_DE/rom.json index 5b9439dc8..e0a1b586a 100644 --- a/frontend/src/locales/de_DE/rom.json +++ b/frontend/src/locales/de_DE/rom.json @@ -451,6 +451,7 @@ "verification": "Verifizierung", "verified-rom": "Verifizierte ROM", "verified-rom-hint": "Hash mit ROM-Datenbank abgeglichen", + "version": "Version", "versions-count": "{n} Versionen", "volume-mute": "Stummschalten", "volume-unmute": "Stummschaltung aufheben", diff --git a/frontend/src/locales/en_GB/rom.json b/frontend/src/locales/en_GB/rom.json index 51e7ad038..f3fb1a12e 100644 --- a/frontend/src/locales/en_GB/rom.json +++ b/frontend/src/locales/en_GB/rom.json @@ -451,6 +451,7 @@ "verification": "Verification", "verified-rom": "Verified ROM", "verified-rom-hint": "Hash verified against ROM database", + "version": "Version", "versions-count": "{n} versions", "volume-mute": "Mute", "volume-unmute": "Unmute", diff --git a/frontend/src/locales/en_US/rom.json b/frontend/src/locales/en_US/rom.json index 0ac9b09c1..db89680a5 100644 --- a/frontend/src/locales/en_US/rom.json +++ b/frontend/src/locales/en_US/rom.json @@ -451,6 +451,7 @@ "verification": "Verification", "verified-rom": "Verified ROM", "verified-rom-hint": "Hash verified against ROM database", + "version": "Version", "versions-count": "{n} versions", "volume-mute": "Mute", "volume-unmute": "Unmute", diff --git a/frontend/src/locales/es_ES/rom.json b/frontend/src/locales/es_ES/rom.json index 3509b7754..7895f8eb0 100644 --- a/frontend/src/locales/es_ES/rom.json +++ b/frontend/src/locales/es_ES/rom.json @@ -451,6 +451,7 @@ "verification": "Verificación", "verified-rom": "ROM verificada", "verified-rom-hint": "Hash verificado contra una base de datos de ROM", + "version": "Version", "versions-count": "{n} versiones", "volume-mute": "Silenciar", "volume-unmute": "Quitar silencio", diff --git a/frontend/src/locales/fr_FR/rom.json b/frontend/src/locales/fr_FR/rom.json index 57ba5f753..ae4f5cef3 100644 --- a/frontend/src/locales/fr_FR/rom.json +++ b/frontend/src/locales/fr_FR/rom.json @@ -451,6 +451,7 @@ "verification": "Vérification", "verified-rom": "ROM vérifiée", "verified-rom-hint": "Empreinte vérifiée dans une base de données de ROM", + "version": "Version", "versions-count": "{n} versions", "volume-mute": "Couper le son", "volume-unmute": "Activer le son", diff --git a/frontend/src/locales/hu_HU/rom.json b/frontend/src/locales/hu_HU/rom.json index 0b67a8e43..9d97d900a 100644 --- a/frontend/src/locales/hu_HU/rom.json +++ b/frontend/src/locales/hu_HU/rom.json @@ -451,6 +451,7 @@ "verification": "Ellenőrzés", "verified-rom": "Ellenőrzött ROM", "verified-rom-hint": "Hash verified against ROM database", + "version": "Version", "versions-count": "{n} verzió", "volume-mute": "Némítás", "volume-unmute": "Némítás feloldása", diff --git a/frontend/src/locales/it_IT/rom.json b/frontend/src/locales/it_IT/rom.json index 7882da154..74fceb9e6 100644 --- a/frontend/src/locales/it_IT/rom.json +++ b/frontend/src/locales/it_IT/rom.json @@ -451,6 +451,7 @@ "verification": "Verifica", "verified-rom": "ROM verificata", "verified-rom-hint": "Hash verificato su un database di ROM", + "version": "Version", "versions-count": "{n} versioni", "volume-mute": "Disattiva audio", "volume-unmute": "Riattiva audio", diff --git a/frontend/src/locales/ja_JP/rom.json b/frontend/src/locales/ja_JP/rom.json index a936d8782..cffaca864 100644 --- a/frontend/src/locales/ja_JP/rom.json +++ b/frontend/src/locales/ja_JP/rom.json @@ -451,6 +451,7 @@ "verification": "検証", "verified-rom": "確認済みROM", "verified-rom-hint": "Hash verified against ROM database", + "version": "Version", "versions-count": "{n}件のバージョン", "volume-mute": "ミュート", "volume-unmute": "ミュート解除", diff --git a/frontend/src/locales/ko_KR/rom.json b/frontend/src/locales/ko_KR/rom.json index e8ac12d40..42cc26cee 100644 --- a/frontend/src/locales/ko_KR/rom.json +++ b/frontend/src/locales/ko_KR/rom.json @@ -451,6 +451,7 @@ "verification": "검증", "verified-rom": "검증된 ROM", "verified-rom-hint": "Hash verified against ROM database", + "version": "Version", "versions-count": "{n}개 버전", "volume-mute": "음소거", "volume-unmute": "음소거 해제", diff --git a/frontend/src/locales/pl_PL/rom.json b/frontend/src/locales/pl_PL/rom.json index 9b6bc1fb7..705014c3e 100644 --- a/frontend/src/locales/pl_PL/rom.json +++ b/frontend/src/locales/pl_PL/rom.json @@ -451,6 +451,7 @@ "verification": "Weryfikacja", "verified-rom": "Zweryfikowany ROM", "verified-rom-hint": "Hash verified against ROM database", + "version": "Version", "versions-count": "{n} wersji", "volume-mute": "Wycisz", "volume-unmute": "Wyłącz wyciszenie", diff --git a/frontend/src/locales/pt_BR/rom.json b/frontend/src/locales/pt_BR/rom.json index eb9e4ae10..052482df8 100644 --- a/frontend/src/locales/pt_BR/rom.json +++ b/frontend/src/locales/pt_BR/rom.json @@ -451,6 +451,7 @@ "verification": "Verificação", "verified-rom": "ROM verificada", "verified-rom-hint": "Hash verificado em banco de dados de ROM", + "version": "Version", "versions-count": "{n} versões", "volume-mute": "Silenciar", "volume-unmute": "Reativar som", diff --git a/frontend/src/locales/ro_RO/rom.json b/frontend/src/locales/ro_RO/rom.json index 870fd2d4b..6bc8aafda 100644 --- a/frontend/src/locales/ro_RO/rom.json +++ b/frontend/src/locales/ro_RO/rom.json @@ -451,6 +451,7 @@ "verification": "Verificare", "verified-rom": "ROM verificat", "verified-rom-hint": "Hash verified against ROM database", + "version": "Version", "versions-count": "{n} versiuni", "volume-mute": "Mut", "volume-unmute": "Activează sunetul", diff --git a/frontend/src/locales/ru_RU/rom.json b/frontend/src/locales/ru_RU/rom.json index 26f758ab0..06e8bd818 100644 --- a/frontend/src/locales/ru_RU/rom.json +++ b/frontend/src/locales/ru_RU/rom.json @@ -451,6 +451,7 @@ "verification": "Проверка", "verified-rom": "Проверенный ROM", "verified-rom-hint": "Hash verified against ROM database", + "version": "Version", "versions-count": "{n} версий", "volume-mute": "Отключить звук", "volume-unmute": "Включить звук", diff --git a/frontend/src/locales/tr_TR/rom.json b/frontend/src/locales/tr_TR/rom.json index 2a4a739d2..16de21256 100644 --- a/frontend/src/locales/tr_TR/rom.json +++ b/frontend/src/locales/tr_TR/rom.json @@ -451,6 +451,7 @@ "verification": "Doğrulama", "verified-rom": "Doğrulanmış ROM", "verified-rom-hint": "Hash verified against ROM database", + "version": "Version", "versions-count": "{n} sürüm", "volume-mute": "Sesi kapat", "volume-unmute": "Sesi aç", diff --git a/frontend/src/locales/zh_CN/rom.json b/frontend/src/locales/zh_CN/rom.json index a84396c95..de98ec550 100644 --- a/frontend/src/locales/zh_CN/rom.json +++ b/frontend/src/locales/zh_CN/rom.json @@ -451,6 +451,7 @@ "verification": "验证", "verified-rom": "已验证 ROM", "verified-rom-hint": "Hash verified against ROM database", + "version": "Version", "versions-count": "{n} 个版本", "volume-mute": "静音", "volume-unmute": "取消静音", diff --git a/frontend/src/locales/zh_TW/rom.json b/frontend/src/locales/zh_TW/rom.json index 4d41662ed..983b9b0d0 100644 --- a/frontend/src/locales/zh_TW/rom.json +++ b/frontend/src/locales/zh_TW/rom.json @@ -451,6 +451,7 @@ "verification": "驗證", "verified-rom": "已驗證 ROM", "verified-rom-hint": "Hash verified against ROM database", + "version": "Version", "versions-count": "{n} 個版本", "volume-mute": "靜音", "volume-unmute": "取消靜音", diff --git a/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue b/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue index 3038577a9..f067a5cdf 100644 --- a/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue +++ b/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue @@ -96,6 +96,7 @@ const audioDuration = computed(() => const hasAnyHash = computed( () => Boolean(props.file.title_id) || + Boolean(props.file.title_version) || Boolean(props.file.sha1_hash) || Boolean(props.file.chd_sha1_hash) || Boolean(props.file.md5_hash) || @@ -173,6 +174,12 @@ const hasAnyHash = computed( :value="file.title_id" compact /> + ): RomFileSchema { chd_sha1_hash: null, title_id: null, save_id: null, + title_version: null, archive_members: null, category: "game", ...overrides, From dbab44c3d11f8d36b44bb067f81239c75ae4ff5b Mon Sep 17 00:00:00 2001 From: nendo Date: Fri, 24 Jul 2026 06:21:13 +0900 Subject: [PATCH 10/40] Persist title_version through the RomFile rebuild The purge-and-recreate list in _identify_rom copied title_id and save_id but not the new title_version column, so extracted Switch update versions were dropped to NULL on persist. Copy title_version too, and add a regression test that captures the rebuilt RomFile and fails if the version is lost. --- backend/endpoints/sockets/scan.py | 1 + backend/tests/endpoints/sockets/test_scan.py | 113 ++++++++++++++++++- 2 files changed, 113 insertions(+), 1 deletion(-) diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index c6f194070..1e82efb2b 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -510,6 +510,7 @@ async def _identify_rom( chd_sha1_hash=file.chd_sha1_hash, title_id=file.title_id, save_id=file.save_id, + title_version=file.title_version, ) for file in fs_rom["files"] ] diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index 5cb5782b0..fa9f6ac45 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -23,7 +23,7 @@ from handler.filesystem.roms_handler import ( from handler.metadata.base_handler import UniversalPlatformSlug as UPS from handler.scan_handler import ScanType from models.platform import Platform -from models.rom import Rom +from models.rom import Rom, RomFile, RomFileCategory def test_scan_stats(): @@ -645,6 +645,117 @@ class TestIdentifyRomTitleIdEmbedRename: assert fs_rom["fs_name"] == self.NEW_NAME +class TestIdentifyRomPersistsFileTitleVersion: + """`_identify_rom` must persist per-file `title_version` on the rebuilt files. + + A Switch update file carries a `title_version` extracted during scan. The + purge-and-recreate list in `_identify_rom` rebuilds each `RomFile` from + `fs_rom["files"]`; if it omits `title_version`, the version is silently + dropped to NULL on persist. A HASHES scan reaches the file-rebuild step and + returns right after it. + """ + + UPDATE_TITLE_ID = "0100F4700B2E0800" + UPDATE_TITLE_VERSION = 655360 + + @pytest.fixture + def patched(self, mocker): + mocker.patch.object( + scan_module, "redis_client", Mock(get=Mock(return_value=None)) + ) + + fs = scan_module.fs_rom_handler + mocker.patch.object( + fs, + "parse_tags", + return_value=ParsedTags( + version="", revision="", regions=[], languages=[], other_tags=[] + ), + ) + mocker.patch.object(fs, "get_roms_fs_structure", return_value="switch/roms") + mocker.patch.object(fs, "get_file_name_with_no_tags", return_value="Game") + + update_file = RomFile( + file_name="Game [UPD][v655360].nsp", + file_path="switch/roms", + file_size_bytes=1024, + category=RomFileCategory.UPDATE, + title_id=self.UPDATE_TITLE_ID, + title_version=self.UPDATE_TITLE_VERSION, + ) + mocker.patch.object( + fs, + "get_rom_files", + AsyncMock( + return_value=ParsedRomFiles( + rom_files=[update_file], + crc_hash="crc", + md5_hash="md5", + sha1_hash="sha1", + ra_hash="", + title_id=self.UPDATE_TITLE_ID, + ) + ), + ) + + config = MagicMock() + config.SKIP_HASH_CALCULATION = False + config.SKIP_TITLE_ID_EXTRACTION = False + config.EMBED_SWITCH_TITLE_IDS = False + mocker.patch.object(scan_module.cm, "get_config", return_value=config) + + mocker.patch.object( + scan_module, + "scan_rom", + AsyncMock(return_value=MagicMock(is_identified=False)), + ) + # The persist loop calls this per saved file; keep it inert. + mocker.patch.object(scan_module, "persist_soundtrack_cover") + + db = mocker.patch.object(scan_module, "db_rom_handler") + db.add_rom.return_value = MagicMock(is_identified=False, id=99) + db.get_matching_missing_rom.return_value = None + db.add_rom_file.side_effect = lambda rom_file: rom_file + return db + + def _platform(self): + platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") + platform.id = 1 + return platform + + async def test_rebuilt_file_keeps_title_version(self, patched): + db = patched + fs_rom: FSRom = { + "fs_name": "Game.nsp", + "flat": True, + "nested": False, + "files": [], + "crc_hash": "", + "md5_hash": "", + "sha1_hash": "", + "ra_hash": "", + } + await _identify_rom( + platform=self._platform(), + fs_rom=fs_rom, + rom=None, + scan_type=ScanType.HASHES, + roms_ids=[], + metadata_sources=[], + launchbox_remote_enabled=False, + playmatch_enabled=False, + socket_manager=AsyncMock(), + scan_stats=AsyncMock(), + ) + + db.purge_rom_files.assert_called_once_with(99) + db.add_rom_file.assert_called_once() + persisted = db.add_rom_file.call_args.args[0] + assert isinstance(persisted, RomFile) + assert persisted.title_id == self.UPDATE_TITLE_ID + assert persisted.title_version == self.UPDATE_TITLE_VERSION + + class TestIdentifyPlatformMarksMissingBeforeScan: """`_identify_platform` must flag missing entries before identifying files. From 0c88dfdfe097ed43e19adcfac1aebc52a0000de3 Mon Sep 17 00:00:00 2001 From: nendo Date: Wed, 29 Jul 2026 12:45:31 +0900 Subject: [PATCH 11/40] Extract 3DS save location via sigil folder-split usage The 3DS nests its save under two directory levels, so sigil reports it as a '/'-separated save_id (00040000/00033500) flagged with usage=folder-split rather than a flat id. Add SaveUsage.FOLDER_SPLIT, migrate the saveusage enum (0106), regenerate the frontend SaveUsage type, and bump the sigil pin to 98f3c62. --- Dockerfile | 2 +- .../versions/0106_sigil_folder_split.py | 59 +++++++++++++++++++ backend/models/rom.py | 1 + .../handler/filesystem/test_roms_handler.py | 33 +++++++++++ docker/Dockerfile | 2 +- .../src/__generated__/models/SaveUsage.ts | 2 +- 6 files changed, 96 insertions(+), 3 deletions(-) create mode 100644 backend/alembic/versions/0106_sigil_folder_split.py diff --git a/Dockerfile b/Dockerfile index 169ca7fe0..e6bb1c09e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -81,7 +81,7 @@ ENV PATH="/app/.venv/bin:${PATH}" # Build and install sigil (optional, for title ID extraction) # Placed after `uv sync` because the extension is compiled with the venv's # Python so the ABI matches. -ARG SIGIL_VERSION=45fcd54c1e6e18b63f83a70b8d86a4f93fb53340 +ARG SIGIL_VERSION=98f3c626eecac48aa99209414d88a15ebe9b70c4 RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git /tmp/argosy-sigil WORKDIR /tmp/argosy-sigil RUN git checkout "${SIGIL_VERSION}" \ diff --git a/backend/alembic/versions/0106_sigil_folder_split.py b/backend/alembic/versions/0106_sigil_folder_split.py new file mode 100644 index 000000000..7de15fbf2 --- /dev/null +++ b/backend/alembic/versions/0106_sigil_folder_split.py @@ -0,0 +1,59 @@ +"""Add FOLDER_SPLIT to the saveusage enum (3DS saves nest the id across +two directory levels). + +Revision ID: 0106_sigil_folder_split +Revises: 0105_sigil_title_version +Create Date: 2026-07-29 00:00:00.000000 + +""" + +import sqlalchemy as sa +from alembic import op + +from utils.database import is_postgresql + +# revision identifiers, used by Alembic. +revision = "0106_sigil_folder_split" +down_revision = "0105_sigil_title_version" +branch_labels = None +depends_on = None + +SAVE_USAGE_VALUES = ( + "FOLDER_EXACT", + "FOLDER_PREFIX", + "FILE_EXACT", + "FILE_PREFIX", + "FOLDER_SPLIT", +) + + +def upgrade() -> None: + connection = op.get_bind() + + if is_postgresql(connection): + # ALTER TYPE ... ADD VALUE must run outside alembic's transaction. + with op.get_context().autocommit_block(): + op.execute("ALTER TYPE saveusage ADD VALUE IF NOT EXISTS 'FOLDER_SPLIT'") + else: + save_usage_enum = sa.Enum(*SAVE_USAGE_VALUES, name="saveusage") + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.alter_column("save_usage", type_=save_usage_enum, nullable=True) + + +def downgrade() -> None: + # PostgreSQL cannot drop enum values; leave FOLDER_SPLIT in place. On + # MariaDB, narrow the enum back after clearing any rows that used it. + connection = op.get_bind() + if is_postgresql(connection): + return + + op.execute("UPDATE roms SET save_usage = NULL WHERE save_usage = 'FOLDER_SPLIT'") + reverted_enum = sa.Enum( + "FOLDER_EXACT", + "FOLDER_PREFIX", + "FILE_EXACT", + "FILE_PREFIX", + name="saveusage", + ) + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.alter_column("save_usage", type_=reverted_enum, nullable=True) diff --git a/backend/models/rom.py b/backend/models/rom.py index de822c54e..0b94b281e 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -89,6 +89,7 @@ class SaveUsage(enum.StrEnum): FOLDER_PREFIX = "folder-prefix" FILE_EXACT = "file-exact" FILE_PREFIX = "file-prefix" + FOLDER_SPLIT = "folder-split" class SiblingRom(BaseModel): diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index 1c0c87e7c..a190968d1 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -1528,6 +1528,39 @@ class TestSigilTitleIdExtraction: assert parsed.save_id == "ULUS10041" assert parsed.save_usage == SaveUsage.FOLDER_PREFIX + @pytest.mark.asyncio + async def test_3ds_extraction_maps_folder_split_usage( + self, tmp_path: Path, config: Config + ): + platform = Platform(name="Nintendo 3DS", slug="3ds", fs_slug="3ds") + handler = self._make_handler(tmp_path) + rom = self._make_single_file_rom(tmp_path, platform, "Game.3ds") + + mock_extract = AsyncMock( + return_value=SigilExtractionResult( + title_id="0004000000033500", + # save_id carries the on-disk split, not the flat id. + save_id="00040000/00033500", + usage="folder-split", + ) + ) + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with ( + patch(self.SIGIL_PATCH_TARGET, mock_extract), + patch( + "adapters.services.rahasher.RAHasherService.calculate_hash", + new_callable=AsyncMock, + return_value="", + ), + ): + parsed = await handler.get_rom_files(rom) + + assert parsed.rom_files[0].save_id == "00040000/00033500" + assert parsed.save_id == "00040000/00033500" + assert parsed.save_usage == SaveUsage.FOLDER_SPLIT + @pytest.mark.asyncio async def test_non_sigil_platform_skips_extraction( self, tmp_path: Path, config: Config diff --git a/docker/Dockerfile b/docker/Dockerfile index 2638fe99e..349c783d0 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -116,7 +116,7 @@ RUN apk add --no-cache \ make \ musl-dev -ARG SIGIL_VERSION=45fcd54c1e6e18b63f83a70b8d86a4f93fb53340 +ARG SIGIL_VERSION=98f3c626eecac48aa99209414d88a15ebe9b70c4 RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git && \ cd ./argosy-sigil && \ diff --git a/frontend/src/__generated__/models/SaveUsage.ts b/frontend/src/__generated__/models/SaveUsage.ts index 65f4d1a22..3286796e1 100644 --- a/frontend/src/__generated__/models/SaveUsage.ts +++ b/frontend/src/__generated__/models/SaveUsage.ts @@ -2,4 +2,4 @@ /* istanbul ignore file */ /* tslint:disable */ /* eslint-disable */ -export type SaveUsage = 'folder-exact' | 'folder-prefix' | 'file-exact' | 'file-prefix'; +export type SaveUsage = 'folder-exact' | 'folder-prefix' | 'file-exact' | 'file-prefix' | 'folder-split'; From 0cf06f2200f599c3348a03986c154a64d4b3785d Mon Sep 17 00:00:00 2001 From: nendo Date: Mon, 17 Aug 2026 03:21:41 +0900 Subject: [PATCH 12/40] Bump sigil pin for 3DS z3ds extraction fix --- Dockerfile | 2 +- docker/Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index e6bb1c09e..bbdff0bbe 100644 --- a/Dockerfile +++ b/Dockerfile @@ -81,7 +81,7 @@ ENV PATH="/app/.venv/bin:${PATH}" # Build and install sigil (optional, for title ID extraction) # Placed after `uv sync` because the extension is compiled with the venv's # Python so the ABI matches. -ARG SIGIL_VERSION=98f3c626eecac48aa99209414d88a15ebe9b70c4 +ARG SIGIL_VERSION=469dac19d9ec75ac848af5feb6de9e0564e30711 RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git /tmp/argosy-sigil WORKDIR /tmp/argosy-sigil RUN git checkout "${SIGIL_VERSION}" \ diff --git a/docker/Dockerfile b/docker/Dockerfile index 349c783d0..00c77ebd7 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -116,7 +116,7 @@ RUN apk add --no-cache \ make \ musl-dev -ARG SIGIL_VERSION=98f3c626eecac48aa99209414d88a15ebe9b70c4 +ARG SIGIL_VERSION=469dac19d9ec75ac848af5feb6de9e0564e30711 RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git && \ cd ./argosy-sigil && \ From b9261cdea649d2e648aad5c6a89b0be039ed2af2 Mon Sep 17 00:00:00 2001 From: nendo Date: Wed, 26 Aug 2026 19:27:15 +0900 Subject: [PATCH 13/40] fix(scan): store 3DS, Wii and Wii U save ids in the emulator's case save_id is the literal on-disk save location, and azahar, dolphin and cemu all build those directories with lowercase hex. On case-sensitive storage an uppercase id addressed a second directory beside the emulator's own, so a game's saves split across the two. Sigil now emits the path in the case the emulator writes; the pin moves with it, and 0111 recases the ids already stored so an existing library does not have to be rescanned. title_id keeps its canonical uppercase form. --- Dockerfile | 2 +- .../versions/0111_lowercase_save_ids.py | 72 +++++++++++++++++++ .../handler/filesystem/test_roms_handler.py | 13 ++-- docker/Dockerfile | 2 +- 4 files changed, 82 insertions(+), 7 deletions(-) create mode 100644 backend/alembic/versions/0111_lowercase_save_ids.py diff --git a/Dockerfile b/Dockerfile index bbdff0bbe..72b37ae6f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -81,7 +81,7 @@ ENV PATH="/app/.venv/bin:${PATH}" # Build and install sigil (optional, for title ID extraction) # Placed after `uv sync` because the extension is compiled with the venv's # Python so the ABI matches. -ARG SIGIL_VERSION=469dac19d9ec75ac848af5feb6de9e0564e30711 +ARG SIGIL_VERSION=a294ade6ef5043fd825ec5a866fe5aa3b6aeeb77 RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git /tmp/argosy-sigil WORKDIR /tmp/argosy-sigil RUN git checkout "${SIGIL_VERSION}" \ diff --git a/backend/alembic/versions/0111_lowercase_save_ids.py b/backend/alembic/versions/0111_lowercase_save_ids.py new file mode 100644 index 000000000..493121b88 --- /dev/null +++ b/backend/alembic/versions/0111_lowercase_save_ids.py @@ -0,0 +1,72 @@ +"""Lowercase the 3DS, Wii and Wii U save ids stored before sigil emitted them +in the case the emulators write. + +Revision ID: 0111_lowercase_save_ids +Revises: 0110_sigil_folder_split +Create Date: 2026-08-26 00:00:00.000000 + +""" + +from collections.abc import Callable + +import sqlalchemy as sa +from alembic import op + +# revision identifiers, used by Alembic. +revision = "0111_lowercase_save_ids" +down_revision = "0110_sigil_folder_split" +branch_labels = None +depends_on = None + +# Frozen at this revision: a migration describes the rows as they were, so it +# must not follow later edits to SIGIL_PLATFORM_SLUGS. +RECASED_PLATFORM_SLUGS = ("3ds", "wii", "wiiu") + +roms = sa.table( + "roms", + sa.column("id", sa.Integer), + sa.column("platform_id", sa.Integer), + sa.column("save_id", sa.String), +) +rom_files = sa.table( + "rom_files", + sa.column("rom_id", sa.Integer), + sa.column("save_id", sa.String), +) +platforms = sa.table( + "platforms", + sa.column("id", sa.Integer), + sa.column("slug", sa.String), +) + + +Recase = Callable[[sa.ColumnElement[str]], sa.ColumnElement[str]] + + +def _recase_save_ids(recase: Recase) -> None: + recased_platforms = sa.select(platforms.c.id).where( + platforms.c.slug.in_(RECASED_PLATFORM_SLUGS) + ) + recased_roms = sa.select(roms.c.id).where(roms.c.platform_id.in_(recased_platforms)) + + op.execute( + roms.update() + .where(roms.c.platform_id.in_(recased_platforms)) + .where(roms.c.save_id.is_not(None)) + .values(save_id=recase(roms.c.save_id)) + ) + op.execute( + rom_files.update() + .where(rom_files.c.rom_id.in_(recased_roms)) + .where(rom_files.c.save_id.is_not(None)) + .values(save_id=recase(rom_files.c.save_id)) + ) + + +def upgrade() -> None: + _recase_save_ids(sa.func.lower) + + +def downgrade() -> None: + # These ids are hex, so uppercasing is an exact inverse. + _recase_save_ids(sa.func.upper) diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index a805a799a..a967e2272 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -1635,9 +1635,10 @@ class TestSigilTitleIdExtraction: mock_extract = AsyncMock( return_value=SigilExtractionResult( - title_id="0004000000033500", - # save_id carries the on-disk split, not the flat id. - save_id="00040000/00033500", + title_id="0004000E0011C500", + # save_id carries the on-disk split, not the flat id, and is + # lowercase because that is the case the emulator writes. + save_id="0004000e/0011c500", usage="folder-split", ) ) @@ -1654,8 +1655,10 @@ class TestSigilTitleIdExtraction: ): parsed = await handler.get_rom_files(rom) - assert parsed.rom_files[0].save_id == "00040000/00033500" - assert parsed.save_id == "00040000/00033500" + assert parsed.rom_files[0].save_id == "0004000e/0011c500" + assert parsed.rom_files[0].title_id == "0004000E0011C500" + assert parsed.save_id == "0004000e/0011c500" + assert parsed.title_id == "0004000E0011C500" assert parsed.save_usage == SaveUsage.FOLDER_SPLIT @pytest.mark.asyncio diff --git a/docker/Dockerfile b/docker/Dockerfile index 00c77ebd7..dc7b1e926 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -116,7 +116,7 @@ RUN apk add --no-cache \ make \ musl-dev -ARG SIGIL_VERSION=469dac19d9ec75ac848af5feb6de9e0564e30711 +ARG SIGIL_VERSION=a294ade6ef5043fd825ec5a866fe5aa3b6aeeb77 RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git && \ cd ./argosy-sigil && \ From 9d9ce978580c79a2c3f6a4a06d6c5946a71ff9c7 Mon Sep 17 00:00:00 2001 From: nendo Date: Wed, 26 Aug 2026 19:27:30 +0900 Subject: [PATCH 14/40] feat(scan): extract Dreamcast title ids via sigil Sigil reads the IP.BIN product number off the boot header, which is the name flycast gives the per-game VMU file, so a Dreamcast ROM resolves the same way every other supported platform does. The extractor is flagged experimental upstream, having been validated against a small sample of real discs. --- backend/adapters/services/sigil.py | 1 + backend/tests/adapters/services/test_sigil.py | 1 + .../handler/filesystem/test_roms_handler.py | 33 +++++++++++++++++++ 3 files changed, 35 insertions(+) diff --git a/backend/adapters/services/sigil.py b/backend/adapters/services/sigil.py index 27bba8a49..61aa0ef03 100644 --- a/backend/adapters/services/sigil.py +++ b/backend/adapters/services/sigil.py @@ -23,6 +23,7 @@ SIGIL_PLATFORM_SLUGS: Final[dict[UPS, str]] = { UPS.WII: "wii", UPS.WIIU: "wiiu", UPS.NGC: "gamecube", + UPS.DC: "dreamcast", } # Errors that are expected for arbitrary library files (no title id present, diff --git a/backend/tests/adapters/services/test_sigil.py b/backend/tests/adapters/services/test_sigil.py index 9826039d9..ed21c3050 100644 --- a/backend/tests/adapters/services/test_sigil.py +++ b/backend/tests/adapters/services/test_sigil.py @@ -200,3 +200,4 @@ class TestSigilService: assert SIGIL_PLATFORM_SLUGS[UPS.SWITCH_2] == "switch" assert SIGIL_PLATFORM_SLUGS[UPS.N3DS] == "3ds" assert SIGIL_PLATFORM_SLUGS[UPS.NGC] == "gamecube" + assert SIGIL_PLATFORM_SLUGS[UPS.DC] == "dreamcast" diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index a967e2272..c636ba43d 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -1661,6 +1661,39 @@ class TestSigilTitleIdExtraction: assert parsed.title_id == "0004000E0011C500" assert parsed.save_usage == SaveUsage.FOLDER_SPLIT + @pytest.mark.asyncio + async def test_dreamcast_extraction_maps_file_prefix_usage( + self, tmp_path: Path, config: Config + ): + platform = Platform(name="Dreamcast", slug="dc", fs_slug="dc") + handler = self._make_handler(tmp_path) + rom = self._make_single_file_rom(tmp_path, platform, "Game.chd") + + mock_extract = AsyncMock( + return_value=SigilExtractionResult( + title_id="MK-51035", + save_id="MK-51035", + usage="file-prefix", + ) + ) + + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + with ( + patch(self.SIGIL_PATCH_TARGET, mock_extract), + patch( + "adapters.services.rahasher.RAHasherService.calculate_hash", + new_callable=AsyncMock, + return_value="", + ), + ): + parsed = await handler.get_rom_files(rom) + + assert parsed.rom_files[0].title_id == "MK-51035" + assert parsed.rom_files[0].save_id == "MK-51035" + assert parsed.save_id == "MK-51035" + assert parsed.save_usage == SaveUsage.FILE_PREFIX + @pytest.mark.asyncio async def test_non_sigil_platform_skips_extraction( self, tmp_path: Path, config: Config From 64779f82235612e3ec6d16d555d35ddba2d96d64 Mon Sep 17 00:00:00 2001 From: nendo Date: Thu, 27 Aug 2026 13:29:30 +0900 Subject: [PATCH 15/40] fix(scan): reassociate a renamed non-hashable ROM by its title id Reassociation matched a moved or renamed file to its existing entry by CRC, MD5 and SHA1, and deliberately refused a partial set. Switch and Switch 2 are never hashed, so nothing could ever match them: a renamed file created a duplicate and stranded the original entry, holding the user's collections and notes, as missing from the filesystem. That is the one platform title-id embedding renames. The binary title id is the identity those platforms do carry, so it serves when hashes cannot, under the same single-unambiguous-match rule. --- backend/endpoints/sockets/scan.py | 1 + backend/handler/database/roms_handler.py | 34 ++++++++++--- backend/tests/endpoints/sockets/test_scan.py | 36 ++++++++++++++ backend/tests/handler/test_db_handler.py | 51 +++++++++++++++++++- 4 files changed, 113 insertions(+), 9 deletions(-) diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index 34220ecba..a320f78f5 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -480,6 +480,7 @@ async def _identify_rom( crc_hash=parsed_rom_files.crc_hash, md5_hash=parsed_rom_files.md5_hash, sha1_hash=parsed_rom_files.sha1_hash, + title_id=parsed_rom_files.title_id, ) if missing_match is not None: # Move the existing entry onto the new file, clearing its missing state. diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index 0174db9d5..8a4a27dae 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -2894,17 +2894,37 @@ class DBRomsHandler(DBBaseHandler): crc_hash: str | None = None, md5_hash: str | None = None, sha1_hash: str | None = None, + title_id: str | None = None, session: Session = None, # type: ignore ) -> Rom | None: - """Find a ROM marked missing on a platform whose hashes match the file. + """Find a ROM marked missing on a platform that identifies the file. Used during scanning to reassociate a renamed or moved file with its existing entry (preserving collections, notes, and assets) instead of - creating a duplicate. Requires the CRC, MD5, and SHA1 hashes to all - match. Any missing hash yields no match, so non-hashable platforms and - pre-hash entries safely fall back to creating a new entry. + creating a duplicate. All three hashes must match; any missing hash + falls through to the binary title id, which is what non-hashable + platforms like Switch carry instead. With neither, a new entry is + created. + + Args: + platform_id: Platform whose missing entries are searched. + crc_hash: CRC hash of the scanned file, if hashed. + md5_hash: MD5 hash of the scanned file, if hashed. + sha1_hash: SHA1 hash of the scanned file, if hashed. + title_id: Binary title id of the scanned file, if extracted. + Returns: + The single matching ROM, or None when there is no unambiguous one. """ - if not (crc_hash and md5_hash and sha1_hash): + identity: tuple[ColumnElement[bool], ...] + if crc_hash and md5_hash and sha1_hash: + identity = ( + Rom.crc_hash == crc_hash, + Rom.md5_hash == md5_hash, + Rom.sha1_hash == sha1_hash, + ) + elif title_id: + identity = (Rom.title_id == title_id,) + else: return None matches = session.scalars( @@ -2913,9 +2933,7 @@ class DBRomsHandler(DBBaseHandler): and_( Rom.platform_id == platform_id, Rom.missing_from_fs.is_(True), - Rom.crc_hash == crc_hash, - Rom.md5_hash == md5_hash, - Rom.sha1_hash == sha1_hash, + *identity, ) ) .limit(2) diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index 3ebca93cd..e88938c45 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -822,6 +822,7 @@ class TestIdentifyRomReassociation: crc_hash="crc", md5_hash="md5", sha1_hash="sha1", + title_id=None, ) db.update_rom.assert_called_once() rom_id, data = db.update_rom.call_args.args @@ -831,6 +832,41 @@ class TestIdentifyRomReassociation: # No brand-new row is inserted; add_rom only persists the scan result. assert db.add_rom.call_count == 1 + async def test_title_id_is_offered_when_the_platform_is_not_hashed( + self, patched, mocker + ): + """Switch files carry no hashes, so the title id is the only identity. + + Without it a renamed Switch file lands as a duplicate and strands the + original entry, along with its collections and notes, as missing. + """ + db = patched + db.get_matching_missing_rom.return_value = None + mocker.patch.object( + scan_module.fs_rom_handler, + "get_rom_files", + AsyncMock( + return_value=ParsedRomFiles( + rom_files=[], + crc_hash="", + md5_hash="", + sha1_hash="", + ra_hash="", + title_id="0100ABCD12340000", + ) + ), + ) + + await self._run(db) + + db.get_matching_missing_rom.assert_called_once_with( + platform_id=1, + crc_hash="", + md5_hash="", + sha1_hash="", + title_id="0100ABCD12340000", + ) + async def test_files_are_reconciled_in_place(self, patched): db = patched db.get_matching_missing_rom.return_value = None diff --git a/backend/tests/handler/test_db_handler.py b/backend/tests/handler/test_db_handler.py index 99cada660..aaa24bc2f 100644 --- a/backend/tests/handler/test_db_handler.py +++ b/backend/tests/handler/test_db_handler.py @@ -1049,7 +1049,7 @@ def test_get_matching_missing_rom_ambiguous_match_returns_none(platform: Platfor def test_get_matching_missing_rom_requires_all_three_hashes(platform: Platform): - """A match needs all three hashes; omitting one yields no match.""" + """A partial hash set yields no match when there is no title id either.""" _add_missing_rom( platform, "renamed", crc_hash="aabbccdd", md5_hash="md5val", sha1_hash="sha1val" ) @@ -1060,6 +1060,55 @@ def test_get_matching_missing_rom_requires_all_three_hashes(platform: Platform): assert match is None +def test_get_matching_missing_rom_matches_title_id_without_hashes(platform: Platform): + """A non-hashable platform reassociates on the binary title id. + + Switch ROMs are never hashed, so a renamed file would otherwise be + unrecoverable and land as a duplicate entry. + """ + missing = _add_missing_rom(platform, "renamed", title_id="0100ABCD12340000") + + match = db_rom_handler.get_matching_missing_rom( + platform_id=platform.id, title_id="0100ABCD12340000" + ) + assert match is not None + assert match.id == missing.id + + +def test_get_matching_missing_rom_hashes_take_precedence_over_title_id( + platform: Platform, +): + """A hashed file is matched on its hashes, not on a shared title id.""" + _add_missing_rom( + platform, + "other", + crc_hash="aabbccdd", + md5_hash="md5val", + sha1_hash="sha1val", + title_id="0100ABCD12340000", + ) + + match = db_rom_handler.get_matching_missing_rom( + platform_id=platform.id, + crc_hash="different", + md5_hash="different", + sha1_hash="different", + title_id="0100ABCD12340000", + ) + assert match is None + + +def test_get_matching_missing_rom_ambiguous_title_id_returns_none(platform: Platform): + """Two missing entries sharing a title id leave the choice to a new entry.""" + _add_missing_rom(platform, "dup_a", title_id="0100ABCD12340000") + _add_missing_rom(platform, "dup_b", title_id="0100ABCD12340000") + + match = db_rom_handler.get_matching_missing_rom( + platform_id=platform.id, title_id="0100ABCD12340000" + ) + assert match is None + + def test_get_matching_missing_rom_ignores_present_roms(platform: Platform): """Only ROMs marked missing are eligible for reassociation.""" db_rom_handler.add_rom( From 7609be057051ccd38bc264819e5f6f5ec443359b Mon Sep 17 00:00:00 2001 From: nendo Date: Thu, 27 Aug 2026 13:29:37 +0900 Subject: [PATCH 16/40] fix(gallery): show the version chip for a base game at version 0 A Switch base game is version 0, which is a real version and not a missing one, so the truthiness check hid the chip for every base game while filename embedding wrote [v0] into the name of the same file. --- frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue b/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue index cd9fc44ea..4249883a7 100644 --- a/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue +++ b/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue @@ -100,7 +100,7 @@ const audioDuration = computed(() => const hasAnyHash = computed( () => Boolean(props.file.title_id) || - Boolean(props.file.title_version) || + props.file.title_version != null || Boolean(props.file.sha1_hash) || Boolean(props.file.chd_sha1_hash) || Boolean(props.file.md5_hash) || @@ -179,7 +179,7 @@ const hasAnyHash = computed( compact /> Date: Fri, 28 Aug 2026 10:54:58 +0900 Subject: [PATCH 17/40] feat(scan): extract PS3, Xbox and Xbox 360 title ids via sigil sigil gained an Xbox extractor and learned to read PS3, PS Vita, Xbox 360 and Wii U out of their containers, so the three platforms it could already name are now reachable from a scan. All three are non-hashable or partly so, which is where a binary id earns the most: it is the only identity those libraries carry. The extractors are flagged experimental upstream. --- Dockerfile | 2 +- backend/adapters/services/sigil.py | 3 +++ backend/tests/adapters/services/test_sigil.py | 3 +++ docker/Dockerfile | 2 +- 4 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index 72b37ae6f..74c0b26f4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -81,7 +81,7 @@ ENV PATH="/app/.venv/bin:${PATH}" # Build and install sigil (optional, for title ID extraction) # Placed after `uv sync` because the extension is compiled with the venv's # Python so the ABI matches. -ARG SIGIL_VERSION=a294ade6ef5043fd825ec5a866fe5aa3b6aeeb77 +ARG SIGIL_VERSION=9665f03c04d0f547ed38dd5e5e31916c1da5f2e9 RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git /tmp/argosy-sigil WORKDIR /tmp/argosy-sigil RUN git checkout "${SIGIL_VERSION}" \ diff --git a/backend/adapters/services/sigil.py b/backend/adapters/services/sigil.py index 61aa0ef03..55a5c9b9a 100644 --- a/backend/adapters/services/sigil.py +++ b/backend/adapters/services/sigil.py @@ -24,6 +24,9 @@ SIGIL_PLATFORM_SLUGS: Final[dict[UPS, str]] = { UPS.WIIU: "wiiu", UPS.NGC: "gamecube", UPS.DC: "dreamcast", + UPS.PS3: "ps3", + UPS.XBOX: "xbox", + UPS.XBOX360: "xbox360", } # Errors that are expected for arbitrary library files (no title id present, diff --git a/backend/tests/adapters/services/test_sigil.py b/backend/tests/adapters/services/test_sigil.py index ed21c3050..6f5f0f715 100644 --- a/backend/tests/adapters/services/test_sigil.py +++ b/backend/tests/adapters/services/test_sigil.py @@ -201,3 +201,6 @@ class TestSigilService: assert SIGIL_PLATFORM_SLUGS[UPS.N3DS] == "3ds" assert SIGIL_PLATFORM_SLUGS[UPS.NGC] == "gamecube" assert SIGIL_PLATFORM_SLUGS[UPS.DC] == "dreamcast" + assert SIGIL_PLATFORM_SLUGS[UPS.PS3] == "ps3" + assert SIGIL_PLATFORM_SLUGS[UPS.XBOX] == "xbox" + assert SIGIL_PLATFORM_SLUGS[UPS.XBOX360] == "xbox360" diff --git a/docker/Dockerfile b/docker/Dockerfile index 4a550272f..215243db4 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -116,7 +116,7 @@ RUN apk add --no-cache \ make \ musl-dev -ARG SIGIL_VERSION=a294ade6ef5043fd825ec5a866fe5aa3b6aeeb77 +ARG SIGIL_VERSION=9665f03c04d0f547ed38dd5e5e31916c1da5f2e9 RUN git clone --recurse-submodules https://github.com/rommforge/argosy-sigil.git && \ cd ./argosy-sigil && \ From 228197b4ec8df9bb845475f8f167c49f5b852452 Mon Sep 17 00:00:00 2001 From: nendo Date: Fri, 28 Aug 2026 11:02:39 +0900 Subject: [PATCH 18/40] Merge upstream master into feature/sigil-title-ids Upstream took 0111 and 0112, so the four sigil migrations rechain onto 0112_publisher_developer_split as 0113 through 0116. --- .../{0111_sigil_title_ids.py => 0113_sigil_title_ids.py} | 8 ++++---- ...sigil_title_version.py => 0114_sigil_title_version.py} | 8 ++++---- ...3_sigil_folder_split.py => 0115_sigil_folder_split.py} | 8 ++++---- ...4_lowercase_save_ids.py => 0116_lowercase_save_ids.py} | 8 ++++---- 4 files changed, 16 insertions(+), 16 deletions(-) rename backend/alembic/versions/{0111_sigil_title_ids.py => 0113_sigil_title_ids.py} (94%) rename backend/alembic/versions/{0112_sigil_title_version.py => 0114_sigil_title_version.py} (79%) rename backend/alembic/versions/{0113_sigil_folder_split.py => 0115_sigil_folder_split.py} (91%) rename backend/alembic/versions/{0114_lowercase_save_ids.py => 0116_lowercase_save_ids.py} (92%) diff --git a/backend/alembic/versions/0111_sigil_title_ids.py b/backend/alembic/versions/0113_sigil_title_ids.py similarity index 94% rename from backend/alembic/versions/0111_sigil_title_ids.py rename to backend/alembic/versions/0113_sigil_title_ids.py index 341208c36..833df86a2 100644 --- a/backend/alembic/versions/0111_sigil_title_ids.py +++ b/backend/alembic/versions/0113_sigil_title_ids.py @@ -1,8 +1,8 @@ """Add sigil-extracted title id columns: per-file title_id/save_id on rom_files, plus rom-level title_id/save_id/save_usage on roms. -Revision ID: 0111_sigil_title_ids -Revises: 0110_walkthrough_docs +Revision ID: 0113_sigil_title_ids +Revises: 0112_publisher_developer_split Create Date: 2026-07-23 00:00:00.000000 """ @@ -14,8 +14,8 @@ from sqlalchemy.dialects.postgresql import ENUM from utils.database import is_postgresql # revision identifiers, used by Alembic. -revision = "0111_sigil_title_ids" -down_revision = "0110_walkthrough_docs" +revision = "0113_sigil_title_ids" +down_revision = "0112_publisher_developer_split" branch_labels = None depends_on = None diff --git a/backend/alembic/versions/0112_sigil_title_version.py b/backend/alembic/versions/0114_sigil_title_version.py similarity index 79% rename from backend/alembic/versions/0112_sigil_title_version.py rename to backend/alembic/versions/0114_sigil_title_version.py index 3eff91523..12f1a16bb 100644 --- a/backend/alembic/versions/0112_sigil_title_version.py +++ b/backend/alembic/versions/0114_sigil_title_version.py @@ -1,8 +1,8 @@ """Add sigil-extracted title_version column to rom_files (Switch title versions are u32, stored as BigInteger). -Revision ID: 0112_sigil_title_version -Revises: 0111_sigil_title_ids +Revision ID: 0114_sigil_title_version +Revises: 0113_sigil_title_ids Create Date: 2026-07-24 00:00:00.000000 """ @@ -11,8 +11,8 @@ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. -revision = "0112_sigil_title_version" -down_revision = "0111_sigil_title_ids" +revision = "0114_sigil_title_version" +down_revision = "0113_sigil_title_ids" branch_labels = None depends_on = None diff --git a/backend/alembic/versions/0113_sigil_folder_split.py b/backend/alembic/versions/0115_sigil_folder_split.py similarity index 91% rename from backend/alembic/versions/0113_sigil_folder_split.py rename to backend/alembic/versions/0115_sigil_folder_split.py index 8f6b4354c..3d2407836 100644 --- a/backend/alembic/versions/0113_sigil_folder_split.py +++ b/backend/alembic/versions/0115_sigil_folder_split.py @@ -1,8 +1,8 @@ """Add FOLDER_SPLIT to the saveusage enum (3DS saves nest the id across two directory levels). -Revision ID: 0113_sigil_folder_split -Revises: 0112_sigil_title_version +Revision ID: 0115_sigil_folder_split +Revises: 0114_sigil_title_version Create Date: 2026-07-29 00:00:00.000000 """ @@ -13,8 +13,8 @@ from alembic import op from utils.database import is_postgresql # revision identifiers, used by Alembic. -revision = "0113_sigil_folder_split" -down_revision = "0112_sigil_title_version" +revision = "0115_sigil_folder_split" +down_revision = "0114_sigil_title_version" branch_labels = None depends_on = None diff --git a/backend/alembic/versions/0114_lowercase_save_ids.py b/backend/alembic/versions/0116_lowercase_save_ids.py similarity index 92% rename from backend/alembic/versions/0114_lowercase_save_ids.py rename to backend/alembic/versions/0116_lowercase_save_ids.py index e9e6d1e66..1a3f51639 100644 --- a/backend/alembic/versions/0114_lowercase_save_ids.py +++ b/backend/alembic/versions/0116_lowercase_save_ids.py @@ -1,8 +1,8 @@ """Lowercase the 3DS, Wii and Wii U save ids stored before sigil emitted them in the case the emulators write. -Revision ID: 0114_lowercase_save_ids -Revises: 0113_sigil_folder_split +Revision ID: 0116_lowercase_save_ids +Revises: 0115_sigil_folder_split Create Date: 2026-08-26 00:00:00.000000 """ @@ -13,8 +13,8 @@ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. -revision = "0114_lowercase_save_ids" -down_revision = "0113_sigil_folder_split" +revision = "0116_lowercase_save_ids" +down_revision = "0115_sigil_folder_split" branch_labels = None depends_on = None From e7c4cb2ab6b3d437c7b06d82de162c8b6490e855 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Fri, 28 Aug 2026 18:18:47 -0400 Subject: [PATCH 19/40] refactor(scan): tighten the sigil title id extraction paths Quality pass over the title id feature, no behaviour change. Give the Switch platform family one home by deriving it from the sigil slug map, and drop the two inline tuples and the local frozenset that restated it. Express the base-title-id rule once: a base id is its own derived base. Compose the bracket regex from the 16-hex pattern instead of repeating it. Return the embedded name from the extraction closure rather than writing it through nonlocal, which removes the is_rom_level flag and the repeated sigil_platform guards, and factor the twice-duplicated rom-level file tail into one helper. Cut two per-ROM costs in _identify_rom: config.yml was re-read and re-parsed three times per ROM, and the prod.keys firmware lookup ran one DB query per Switch ROM despite depending only on the platform. Both are now resolved once, the latter in the per-platform callers. Also document skip_title_id_extraction and embed_switch_title_ids, drop the always-dashed title/save id rows from the metadata tab, and render the file row's chips from one list. Co-Authored-By: Claude Opus 5 (1M context) --- backend/adapters/services/sigil.py | 22 +- backend/endpoints/sockets/scan.py | 86 ++-- backend/handler/filesystem/roms_handler.py | 152 +++--- backend/tests/endpoints/sockets/test_scan.py | 253 ++++------ .../handler/filesystem/test_roms_handler.py | 476 +++++++----------- docs/BACKEND_ARCHITECTURE.md | 7 + examples/config.example.yml | 4 + .../GameDetails/FilesTab/FileRow.vue | 74 +-- .../v2/components/GameDetails/MetadataTab.vue | 7 +- 9 files changed, 461 insertions(+), 620 deletions(-) diff --git a/backend/adapters/services/sigil.py b/backend/adapters/services/sigil.py index 55a5c9b9a..569dcd121 100644 --- a/backend/adapters/services/sigil.py +++ b/backend/adapters/services/sigil.py @@ -9,6 +9,7 @@ try: import sigil except ImportError: sigil = None # type: ignore[assignment] + log.debug("sigil binding not installed, title id extraction disabled") SWITCH_SIGIL_SLUG: Final = "switch" @@ -29,17 +30,20 @@ SIGIL_PLATFORM_SLUGS: Final[dict[UPS, str]] = { UPS.XBOX360: "xbox360", } +# The Switch family needs prod.keys to decrypt headers, and is the only family +# whose files may have their title id embedded in the filename. +SWITCH_PLATFORM_SLUGS: Final = frozenset( + slug + for slug, sigil_slug in SIGIL_PLATFORM_SLUGS.items() + if sigil_slug == SWITCH_SIGIL_SLUG +) + # Errors that are expected for arbitrary library files (no title id present, # format sigil can't parse, missing decryption keys). Logged at debug level. ROUTINE_SIGIL_ERROR_CODES: Final = frozenset( {"NOT_FOUND", "UNSUPPORTED", "UNSUPPORTED_FORMAT", "NEEDS_KEY"} ) -_missing_binding_logged = False - - -class SigilServiceError(Exception): ... - @dataclass(frozen=True) class SigilExtractionResult: @@ -60,12 +64,7 @@ class SigilService: file_path: str, prod_keys_path: str | None = None, ) -> SigilExtractionResult | None: - global _missing_binding_logged - if sigil is None: - if not _missing_binding_logged: - log.debug("sigil binding not installed, skipping title id extraction") - _missing_binding_logged = True return None sigil_slug = SIGIL_PLATFORM_SLUGS.get(platform_slug) # type: ignore[arg-type] @@ -80,8 +79,7 @@ class SigilService: result = await asyncio.to_thread(sigil.extract, file_path, **kwargs) except Exception as exc: code = getattr(exc, "code", None) - is_sigil_error = isinstance(exc, getattr(sigil, "SigilError", ())) - if is_sigil_error and code in ROUTINE_SIGIL_ERROR_CODES: + if code in ROUTINE_SIGIL_ERROR_CODES: log.debug(f"Sigil found no title id for {file_path}: {code}") else: log.error(f"Sigil extraction failed for {file_path}: {exc}") diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index 824711a8f..e87285cd1 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -10,6 +10,7 @@ from rq import Worker, get_current_job from rq.job import Job, JobStatus from sqlalchemy.exc import IntegrityError +from adapters.services.sigil import SWITCH_PLATFORM_SLUGS from config import ( DEV_MODE, LIBRARY_BASE_PATH, @@ -44,13 +45,12 @@ from handler.filesystem import ( fs_resource_handler, fs_rom_handler, ) -from handler.filesystem.roms_handler import FSRom +from handler.filesystem.roms_handler import FSRom, ParsedRomFiles from handler.metadata import ( meta_gamelist_handler, meta_hltb_handler, meta_launchbox_handler, ) -from handler.metadata.base_handler import UniversalPlatformSlug as UPS from handler.metadata.launchbox_handler.types import LAUNCHBOX_PLATFORMS_DIR from handler.metadata.ss_handler import begin_scan as begin_ss_scan from handler.metadata.ss_handler import log_quota as log_ss_quota @@ -381,6 +381,29 @@ def _should_hash_firmware( ) +def _resolve_prod_keys_path(platform: Platform) -> str | None: + """Locate the console's prod.keys, which sigil needs to decrypt Switch + XCI/NSP headers, among the platform's scanned firmware.""" + if platform.slug not in SWITCH_PLATFORM_SLUGS: + return None + + prod_keys = db_firmware_handler.get_firmware_by_filename(platform.id, "prod.keys") + return f"{LIBRARY_BASE_PATH}/{prod_keys.full_path}" if prod_keys else None + + +def _apply_scanned_values(fs_rom: FSRom, parsed: ParsedRomFiles) -> None: + fs_rom["files"] = parsed.rom_files + fs_rom["crc_hash"] = parsed.crc_hash + fs_rom["md5_hash"] = parsed.md5_hash + fs_rom["sha1_hash"] = parsed.sha1_hash + fs_rom["ra_hash"] = parsed.ra_hash + fs_rom["title_id"] = parsed.title_id + fs_rom["save_id"] = parsed.save_id + fs_rom["save_usage"] = parsed.save_usage + if parsed.renamed_rom_fs_name: + fs_rom["fs_name"] = parsed.renamed_rom_fs_name + + # There's an order of operations here that is important: # 1. Read the list of roms from the filesystem # 2. Check if ROM should be scanned based on the scan type @@ -398,6 +421,7 @@ async def _identify_rom( playmatch_enabled: bool, socket_manager: socketio.AsyncRedisManager, scan_stats: ScanStats, + prod_keys_path: str | None = None, ) -> None: # Break early if the flag is set if redis_client.get(STOP_SCAN_FLAG): @@ -422,19 +446,10 @@ async def _identify_rom( "url_screenshots": [], } - calculate_hashes = not cm.get_config().SKIP_HASH_CALCULATION - extract_title_ids = not cm.get_config().SKIP_TITLE_ID_EXTRACTION - embed_title_ids = cm.get_config().EMBED_SWITCH_TITLE_IDS - - # Switch title id extraction needs the console's prod.keys to decrypt - # XCI/NSP headers; resolve it from the scanned firmware when present. - prod_keys_path: str | None = None - if extract_title_ids and platform.slug in (UPS.SWITCH, UPS.SWITCH_2): - prod_keys = db_firmware_handler.get_firmware_by_filename( - platform.id, "prod.keys" - ) - if prod_keys: - prod_keys_path = f"{LIBRARY_BASE_PATH}/{prod_keys.full_path}" + cnfg = cm.get_config() + calculate_hashes = not cnfg.SKIP_HASH_CALCULATION + extract_title_ids = not cnfg.SKIP_TITLE_ID_EXTRACTION + embed_title_ids = cnfg.EMBED_SWITCH_TITLE_IDS newly_added: bool = rom is None reassociated: bool = False @@ -455,23 +470,10 @@ async def _identify_rom( prod_keys_path=prod_keys_path, embed_title_ids=embed_title_ids, ) - fs_rom.update( - { - "files": parsed_rom_files.rom_files, - "crc_hash": parsed_rom_files.crc_hash, - "md5_hash": parsed_rom_files.md5_hash, - "sha1_hash": parsed_rom_files.sha1_hash, - "ra_hash": parsed_rom_files.ra_hash, - "title_id": parsed_rom_files.title_id, - "save_id": parsed_rom_files.save_id, - "save_usage": parsed_rom_files.save_usage, - } - ) - # A single-file rom renamed on disk to embed its title id must carry the - # new name into both the new-entry insert and any hash reassociation. + _apply_scanned_values(fs_rom, parsed_rom_files) + # The new-entry insert reads its name from rom_attrs, not fs_rom. if parsed_rom_files.renamed_rom_fs_name: rom_attrs["fs_name"] = parsed_rom_files.renamed_rom_fs_name - fs_rom["fs_name"] = parsed_rom_files.renamed_rom_fs_name files_built = True missing_match = db_rom_handler.get_matching_missing_rom( @@ -543,22 +545,9 @@ async def _identify_rom( prod_keys_path=prod_keys_path, embed_title_ids=embed_title_ids, ) - fs_rom.update( - { - "files": parsed_rom_files.rom_files, - "crc_hash": parsed_rom_files.crc_hash, - "md5_hash": parsed_rom_files.md5_hash, - "sha1_hash": parsed_rom_files.sha1_hash, - "ra_hash": parsed_rom_files.ra_hash, - "title_id": parsed_rom_files.title_id, - "save_id": parsed_rom_files.save_id, - "save_usage": parsed_rom_files.save_usage, - } - ) - # scan_rom persists Rom.fs_name from fs_rom["fs_name"]; keep the rom - # object in sync so its in-memory identity matches the renamed file. + _apply_scanned_values(fs_rom, parsed_rom_files) + # Keep the in-memory rom's identity matching the renamed file. if parsed_rom_files.renamed_rom_fs_name: - fs_rom["fs_name"] = parsed_rom_files.renamed_rom_fs_name rom.fs_name = parsed_rom_files.renamed_rom_fs_name # For a COMPLETE rescan, wipe all downloaded resources before re-fetching so @@ -631,8 +620,7 @@ async def _identify_rom( if should_update_files: # Reconcile against the existing rows instead of replacing them, so file # ids survive a rescan and anything keyed on them (track metadata, - # persisted soundtrack covers) stays valid. title_id/save_id/title_version - # ride along via ROM_FILE_SCANNED_COLUMNS in sync_rom_files. + # persisted soundtrack covers) stays valid. synced = db_rom_handler.sync_rom_files(_added_rom.id, fs_rom["files"]) for cover_path in synced.orphaned_cover_paths: remove_persisted_cover(cover_path) @@ -699,6 +687,7 @@ async def _scan_selected_roms( ) scan_semaphore = asyncio.Semaphore(SCAN_WORKERS) + prod_keys_path = _resolve_prod_keys_path(platform) async def scan_rom_with_semaphore(rom: Rom) -> None: async with scan_semaphore: @@ -730,6 +719,7 @@ async def _scan_selected_roms( playmatch_enabled=playmatch_enabled, socket_manager=socket_manager, scan_stats=scan_stats, + prod_keys_path=prod_keys_path, ) results = await asyncio.gather( @@ -859,6 +849,7 @@ async def _identify_platform( # Create semaphore to limit concurrent ROM scanning scan_semaphore = asyncio.Semaphore(SCAN_WORKERS) + prod_keys_path = _resolve_prod_keys_path(platform) async def scan_rom_with_semaphore(fs_rom: FSRom, rom: Rom | None) -> None: """Scan a single ROM with semaphore limiting""" @@ -874,6 +865,7 @@ async def _identify_platform( playmatch_enabled=playmatch_enabled, socket_manager=socket_manager, scan_stats=scan_stats, + prod_keys_path=prod_keys_path, ) for fs_roms_batch in batched(fs_roms, 200, strict=False): diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 8f704c5ca..310e2801b 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -13,6 +13,7 @@ from anyio import Path as AnyioPath from adapters.services.sigil import ( SIGIL_PLATFORM_SLUGS, + SWITCH_PLATFORM_SLUGS, SigilExtractionResult, SigilService, ) @@ -181,8 +182,7 @@ class ParsedRomFiles: save_id: str | None = None save_usage: SaveUsage | None = None # Set when a single-file rom's file was renamed on disk to embed its title - # id, so the caller can reconcile Rom.fs_name. None for multi-part roms - # (whose folder name is unchanged) or when no rename happened. + # id, so the caller can reconcile Rom.fs_name. renamed_rom_fs_name: str | None = None @@ -194,26 +194,19 @@ SWITCH_CONTENT_TYPE_CATEGORIES: dict[str, RomFileCategory] = { "addon": RomFileCategory.DLC, } -# Platforms whose files may have their title id embedded in the filename. -EMBED_TITLE_ID_PLATFORM_SLUGS = frozenset((UPS.SWITCH, UPS.SWITCH_2)) - -# A 16-hex-digit title id in square brackets, e.g. [0100F4700B2E0000]. Used both -# to detect files that already carry an embedded id (idempotency) and to -# validate the id before embedding it. -SWITCH_TITLE_ID_BRACKET_REGEX = re.compile(r"\[[0-9A-Fa-f]{16}\]") -SWITCH_TITLE_ID_REGEX = re.compile(r"^[0-9A-Fa-f]{16}$") +SWITCH_TITLE_ID_REGEX = re.compile(r"[0-9A-Fa-f]{16}") +# An already-embedded id, e.g. [0100F4700B2E0000]. +SWITCH_TITLE_ID_BRACKET_REGEX = re.compile(rf"\[{SWITCH_TITLE_ID_REGEX.pattern}\]") def _embed_switch_title_id_in_name( abs_file_path: Path, title_id: str, title_version: int | None ) -> Path | None: - """Rename a Switch ROM file to embed its title id and version as - ` [TITLEID][vVERSION]` before the extension, preserving existing tags. + """Rename a Switch ROM file to embed ` [TITLEID][vVERSION]` before the + extension. - Returns the new absolute path, or None when the file was left untouched: - it already carries a 16-hex title-id bracket, the id is not a valid 16-hex - value, or the target name already exists on disk. The os.rename is the only - side effect. + Returns: + The new absolute path, or None when the file was left untouched. """ name = abs_file_path.name @@ -221,7 +214,7 @@ def _embed_switch_title_id_in_name( log.debug(f"{name} already has an embedded title id, skipping rename") return None - if not SWITCH_TITLE_ID_REGEX.match(title_id): + if not SWITCH_TITLE_ID_REGEX.fullmatch(title_id): log.debug(f"Title id {title_id!r} is not a 16-hex value, skipping rename") return None @@ -249,17 +242,6 @@ def _parse_save_usage(usage: str) -> SaveUsage | None: return None -def _is_switch_base_title_id(title_id: str) -> bool: - """Base-game Switch title ids have their low 12 bits cleared and an even - program-index nibble; update/DLC ids differ only in those positions.""" - if len(title_id) < 4 or not title_id.endswith("000"): - return False - try: - return int(title_id[-4], 16) % 2 == 0 - except ValueError: - return False - - def _derive_switch_base_title_id(title_id: str) -> str | None: """Derive the base-game title id from an update/DLC id: clear the low 12 bits and decrement the program-index nibble when it is odd.""" @@ -276,6 +258,11 @@ def _derive_switch_base_title_id(title_id: str) -> str | None: return f"{title_id[:-4]}{formatted}000" +def _is_switch_base_title_id(title_id: str) -> bool: + """A base-game id is its own derived base.""" + return _derive_switch_base_title_id(title_id) == title_id + + def _rom_level_title_values( platform_slug: str, extractions: list[SigilExtractionResult], @@ -283,7 +270,7 @@ def _rom_level_title_values( if not extractions: return None, None, None - if platform_slug in (UPS.SWITCH, UPS.SWITCH_2): + if platform_slug in SWITCH_PLATFORM_SLUGS: base = next( (e for e in extractions if _is_switch_base_title_id(e.title_id)), None ) @@ -488,47 +475,61 @@ class FSRomsHandler(FSHandler): # non-hashable platforms like Switch. sigil_platform = extract_title_ids and rom.platform_slug in SIGIL_PLATFORM_SLUGS sigil_extractions: list[SigilExtractionResult] = [] + sigil_service = SigilService() # Filename embedding is Switch-only, even though sigil covers more # platforms; other platforms never have their files renamed. - embed_switch = ( - embed_title_ids and rom.platform_slug in EMBED_TITLE_ID_PLATFORM_SLUGS - ) + embed_switch = embed_title_ids and rom.platform_slug in SWITCH_PLATFORM_SLUGS renamed_rom_fs_name: str | None = None async def _extract_title_id( - rom_file: RomFile, abs_file_path: Path, is_rom_level: bool = False - ) -> None: - nonlocal renamed_rom_fs_name - extraction = await SigilService().extract_title_id( + rom_file: RomFile, abs_file_path: Path + ) -> str | None: + """Populate the file's title id fields, returning its new name if + embedding renamed it on disk.""" + if not sigil_platform: + return None + + extraction = await sigil_service.extract_title_id( rom.platform_slug, str(abs_file_path), prod_keys_path ) if extraction is None: - return + return None rom_file.title_id = extraction.title_id rom_file.save_id = extraction.save_id rom_file.title_version = extraction.version - # For Switch, the binary CNMT content type is authoritative over the - # folder-derived category. Leave the folder category when absent. if extraction.content_type is not None: category = SWITCH_CONTENT_TYPE_CATEGORIES.get(extraction.content_type) if category is not None: rom_file.category = category sigil_extractions.append(extraction) - if embed_switch and extraction.title_id: - new_path = _embed_switch_title_id_in_name( - abs_file_path, extraction.title_id, extraction.version - ) - if new_path is not None: - # The file stays in the same directory, so only file_name - # changes; file_path is unaffected. - rom_file.file_name = new_path.name - # A single-file rom's file name IS the Rom.fs_name, so the - # caller must reconcile it. Multi-part inner files don't - # change the rom folder name. - if is_rom_level: - renamed_rom_fs_name = new_path.name + if not (embed_switch and extraction.title_id): + return None + + new_path = _embed_switch_title_id_in_name( + abs_file_path, extraction.title_id, extraction.version + ) + if new_path is None: + return None + rom_file.file_name = new_path.name + return new_path.name + + async def _append_rom_level_file(file_hash: FileHash) -> str | None: + """Emit the single RomFile that stands for the whole rom, returning + its new name if embedding renamed it on disk.""" + rom_file = self._build_rom_file( + rom=rom, + rom_path=Path(rel_roms_path), + file_name=rom.fs_name, + file_hash=file_hash, + ) + rom_files.append(rom_file) + # Archives keep hashes only; sigil reads title ids from the ROM + # binary itself. + if rom_ext in ARCHIVE_READERS: + return None + return await _extract_title_id(rom_file, rom_dir) cnfg = cm.get_config() excluded_file_names = cnfg.EXCLUDED_MULTI_PARTS_FILES @@ -638,8 +639,7 @@ class FSRomsHandler(FSHandler): ) # Extract from every file (base, updates, DLC in subfolders), not # just the top-level one: sigil returns None for unparseable files. - if sigil_platform: - await _extract_title_id(rom_file, Path(f_path, file_name)) + await _extract_title_id(rom_file, abs_file_path) rom_files.append(rom_file) elif hashable_platform and rom_ext in ARCHIVE_READERS: # Multi-file archive: compute a composite hash across all @@ -762,39 +762,23 @@ class FSRomsHandler(FSHandler): f"{abs_fs_path}/{rom.fs_name}", ) - file_hash = _make_file_hash( - crc_c, - md5_h, - sha1_h, - chd_sha1_hash=_chd_sha1_hash(rom_dir), + renamed_rom_fs_name = await _append_rom_level_file( + _make_file_hash( + crc_c, + md5_h, + sha1_h, + chd_sha1_hash=_chd_sha1_hash(rom_dir), + ) ) - rom_file = self._build_rom_file( - rom=rom, - rom_path=Path(rel_roms_path), - file_name=rom.fs_name, - file_hash=file_hash, - ) - if sigil_platform: - await _extract_title_id(rom_file, rom_dir, is_rom_level=True) - rom_files.append(rom_file) else: - file_hash = FileHash( - crc_hash="", - md5_hash="", - sha1_hash="", - chd_sha1_hash="", + renamed_rom_fs_name = await _append_rom_level_file( + FileHash( + crc_hash="", + md5_hash="", + sha1_hash="", + chd_sha1_hash="", + ) ) - rom_file = self._build_rom_file( - rom=rom, - rom_path=Path(rel_roms_path), - file_name=rom.fs_name, - file_hash=file_hash, - ) - # Archives keep hashes only; sigil reads title ids from the ROM - # binary itself. - if sigil_platform and rom_ext not in ARCHIVE_READERS: - await _extract_title_id(rom_file, rom_dir, is_rom_level=True) - rom_files.append(rom_file) rom_title_id, rom_save_id, rom_save_usage = _rom_level_title_values( rom.platform_slug, sigil_extractions diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index 4f41daaa1..74906ee2e 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -723,6 +723,79 @@ class TestScanAuthorization: get_jobs.assert_not_called() +def patch_identify_rom( + mocker, + *, + parsed: ParsedRomFiles, + roms_fs_structure: str, + name_with_no_tags: str, + platform_slug: str, + **config_flags: bool, +) -> tuple[Mock, Platform]: + """Stub out everything `_identify_rom` reaches so only the wiring under test + is exercised, returning the patched db handler and the platform to scan.""" + mocker.patch.object(scan_module, "redis_client", Mock(get=Mock(return_value=None))) + + fs = scan_module.fs_rom_handler + mocker.patch.object( + fs, + "parse_tags", + return_value=ParsedTags( + version="", revision="", regions=[], languages=[], other_tags=[] + ), + ) + mocker.patch.object(fs, "get_roms_fs_structure", return_value=roms_fs_structure) + mocker.patch.object( + fs, "get_file_name_with_no_tags", return_value=name_with_no_tags + ) + mocker.patch.object(fs, "get_rom_files", AsyncMock(return_value=parsed)) + + config = MagicMock() + config.SKIP_HASH_CALCULATION = False + for flag, value in config_flags.items(): + setattr(config, flag, value) + mocker.patch.object(scan_module.cm, "get_config", return_value=config) + + mocker.patch.object( + scan_module, "scan_rom", AsyncMock(return_value=MagicMock(is_identified=False)) + ) + + db = mocker.patch.object(scan_module, "db_rom_handler") + db.add_rom.return_value = MagicMock(is_identified=False, id=99) + + platform = Platform(name=platform_slug, slug=platform_slug, fs_slug=platform_slug) + platform.id = 1 + return db, platform + + +async def run_identify_rom(platform: Platform, fs_rom: FSRom) -> None: + await _identify_rom( + platform=platform, + fs_rom=fs_rom, + rom=None, + scan_type=ScanType.HASHES, + roms_ids=[], + metadata_sources=[], + launchbox_remote_enabled=False, + playmatch_enabled=False, + socket_manager=AsyncMock(), + scan_stats=AsyncMock(), + ) + + +def make_fs_rom(fs_name: str) -> FSRom: + return { + "fs_name": fs_name, + "flat": True, + "nested": False, + "files": [], + "crc_hash": "", + "md5_hash": "", + "sha1_hash": "", + "ra_hash": "", + } + + class TestIdentifyRomReassociation: """`_identify_rom` reassociates a renamed/moved file with its missing entry. @@ -909,82 +982,31 @@ class TestIdentifyRomTitleIdEmbedRename: @pytest.fixture def patched(self, mocker): - mocker.patch.object( - scan_module, "redis_client", Mock(get=Mock(return_value=None)) - ) - - fs = scan_module.fs_rom_handler - mocker.patch.object( - fs, - "parse_tags", - return_value=ParsedTags( - version="", revision="", regions=[], languages=[], other_tags=[] + db, platform = patch_identify_rom( + mocker, + parsed=ParsedRomFiles( + rom_files=[], + crc_hash="crc", + md5_hash="md5", + sha1_hash="sha1", + ra_hash="", + title_id="0100ABCD12340000", + renamed_rom_fs_name=self.NEW_NAME, ), + roms_fs_structure="switch/roms", + name_with_no_tags="Game", + platform_slug="switch", + SKIP_TITLE_ID_EXTRACTION=False, + EMBED_SWITCH_TITLE_IDS=True, ) - mocker.patch.object(fs, "get_roms_fs_structure", return_value="switch/roms") - mocker.patch.object(fs, "get_file_name_with_no_tags", return_value="Game") - mocker.patch.object( - fs, - "get_rom_files", - AsyncMock( - return_value=ParsedRomFiles( - rom_files=[], - crc_hash="crc", - md5_hash="md5", - sha1_hash="sha1", - ra_hash="", - title_id="0100ABCD12340000", - renamed_rom_fs_name=self.NEW_NAME, - ) - ), - ) - - config = MagicMock() - config.SKIP_HASH_CALCULATION = False - config.SKIP_TITLE_ID_EXTRACTION = False - config.EMBED_SWITCH_TITLE_IDS = True - mocker.patch.object(scan_module.cm, "get_config", return_value=config) - - mocker.patch.object( - scan_module, - "scan_rom", - AsyncMock(return_value=MagicMock(is_identified=False)), - ) - - db = mocker.patch.object(scan_module, "db_rom_handler") - db.add_rom.return_value = MagicMock(is_identified=False, id=99) db.get_matching_missing_rom.return_value = None - return db - - def _platform(self): - platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") - platform.id = 1 - return platform + return db, platform async def test_new_entry_carries_embedded_name(self, patched): - db = patched - fs_rom: FSRom = { - "fs_name": "Game.nsp", - "flat": True, - "nested": False, - "files": [], - "crc_hash": "", - "md5_hash": "", - "sha1_hash": "", - "ra_hash": "", - } - await _identify_rom( - platform=self._platform(), - fs_rom=fs_rom, - rom=None, - scan_type=ScanType.HASHES, - roms_ids=[], - metadata_sources=[], - launchbox_remote_enabled=False, - playmatch_enabled=False, - socket_manager=AsyncMock(), - scan_stats=AsyncMock(), - ) + db, platform = patched + fs_rom = make_fs_rom("Game.nsp") + + await run_identify_rom(platform, fs_rom) # The initial insert carries the renamed on-disk name, and the shared # fs_rom dict is updated so scan_rom persists the same name. @@ -1020,21 +1042,6 @@ class TestIdentifyRomPersistsFileTitleVersion: @pytest.fixture def patched(self, mocker): - mocker.patch.object( - scan_module, "redis_client", Mock(get=Mock(return_value=None)) - ) - - fs = scan_module.fs_rom_handler - mocker.patch.object( - fs, - "parse_tags", - return_value=ParsedTags( - version="", revision="", regions=[], languages=[], other_tags=[] - ), - ) - mocker.patch.object(fs, "get_roms_fs_structure", return_value="switch/roms") - mocker.patch.object(fs, "get_file_name_with_no_tags", return_value="Game") - update_file = RomFile( file_name="Game [UPD][v655360].nsp", file_path="switch/roms", @@ -1043,72 +1050,34 @@ class TestIdentifyRomPersistsFileTitleVersion: title_id=self.UPDATE_TITLE_ID, title_version=self.UPDATE_TITLE_VERSION, ) - mocker.patch.object( - fs, - "get_rom_files", - AsyncMock( - return_value=ParsedRomFiles( - rom_files=[update_file], - crc_hash="crc", - md5_hash="md5", - sha1_hash="sha1", - ra_hash="", - title_id=self.UPDATE_TITLE_ID, - ) + db, platform = patch_identify_rom( + mocker, + parsed=ParsedRomFiles( + rom_files=[update_file], + crc_hash="crc", + md5_hash="md5", + sha1_hash="sha1", + ra_hash="", + title_id=self.UPDATE_TITLE_ID, ), - ) - - config = MagicMock() - config.SKIP_HASH_CALCULATION = False - config.SKIP_TITLE_ID_EXTRACTION = False - config.EMBED_SWITCH_TITLE_IDS = False - mocker.patch.object(scan_module.cm, "get_config", return_value=config) - - mocker.patch.object( - scan_module, - "scan_rom", - AsyncMock(return_value=MagicMock(is_identified=False)), + roms_fs_structure="switch/roms", + name_with_no_tags="Game", + platform_slug="switch", + SKIP_TITLE_ID_EXTRACTION=False, + EMBED_SWITCH_TITLE_IDS=False, ) # The persist loop calls this per saved file; keep it inert. mocker.patch.object(scan_module, "persist_soundtrack_cover") - - db = mocker.patch.object(scan_module, "db_rom_handler") - db.add_rom.return_value = MagicMock(is_identified=False, id=99) db.get_matching_missing_rom.return_value = None db.sync_rom_files.side_effect = lambda rom_id, files: SyncedRomFiles( files=list(files), orphaned_cover_paths=[] ) - return db - - def _platform(self): - platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") - platform.id = 1 - return platform + return db, platform async def test_rebuilt_file_keeps_title_version(self, patched): - db = patched - fs_rom: FSRom = { - "fs_name": "Game.nsp", - "flat": True, - "nested": False, - "files": [], - "crc_hash": "", - "md5_hash": "", - "sha1_hash": "", - "ra_hash": "", - } - await _identify_rom( - platform=self._platform(), - fs_rom=fs_rom, - rom=None, - scan_type=ScanType.HASHES, - roms_ids=[], - metadata_sources=[], - launchbox_remote_enabled=False, - playmatch_enabled=False, - socket_manager=AsyncMock(), - scan_stats=AsyncMock(), - ) + db, platform = patched + + await run_identify_rom(platform, make_fs_rom("Game.nsp")) db.sync_rom_files.assert_called_once() rom_id, synced_files = db.sync_rom_files.call_args.args diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index ce0b4a3d3..0a19e098c 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -1373,70 +1373,74 @@ class TestFSRomsHandler: assert parsed.ra_hash == "" +SIGIL_PATCH_TARGET = "adapters.services.sigil.SigilService.extract_title_id" + + +@pytest.fixture +def sigil_config(monkeypatch): + cnfg = Config( + EXCLUDED_PLATFORMS=[], + EXCLUDED_SINGLE_EXT=[], + EXCLUDED_SINGLE_FILES=[], + EXCLUDED_MULTI_FILES=[], + EXCLUDED_MULTI_PARTS_EXT=[], + EXCLUDED_MULTI_PARTS_FILES=[], + PLATFORMS_BINDING={}, + PLATFORMS_VERSIONS={}, + ROMS_FOLDER_NAME="roms", + FIRMWARE_FOLDER_NAME="bios", + ) + cnfg.has_structure_path_b = True + monkeypatch.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: cnfg) + return cnfg + + +def make_sigil_handler(tmp_path: Path) -> FSRomsHandler: + handler = FSRomsHandler() + handler.base_path = tmp_path + return handler + + +def make_single_file_rom(tmp_path: Path, platform: Platform, fs_name: str) -> Rom: + roms_path = tmp_path / platform.fs_slug / "roms" + roms_path.mkdir(parents=True, exist_ok=True) + (roms_path / fs_name).write_bytes(b"rom-bytes") + return Rom( + id=1, + fs_name=fs_name, + fs_path=f"{platform.fs_slug}/roms", + platform=platform, + ) + + +def make_multi_part_rom( + tmp_path: Path, platform: Platform, fs_name: str, file_names: list[str] +) -> Rom: + rom_dir = tmp_path / platform.fs_slug / "roms" / fs_name + rom_dir.mkdir(parents=True, exist_ok=True) + for file_name in file_names: + file_path = rom_dir / file_name + file_path.parent.mkdir(parents=True, exist_ok=True) + file_path.write_bytes(b"rom-bytes") + return Rom( + id=1, + fs_name=fs_name, + fs_extension="", + fs_path=f"{platform.fs_slug}/roms", + platform=platform, + ) + + class TestSigilTitleIdExtraction: """Title id extraction via the sigil adapter during get_rom_files.""" - SIGIL_PATCH_TARGET = "adapters.services.sigil.SigilService.extract_title_id" - - @pytest.fixture - def config(self): - cnfg = Config( - EXCLUDED_PLATFORMS=[], - EXCLUDED_SINGLE_EXT=[], - EXCLUDED_SINGLE_FILES=[], - EXCLUDED_MULTI_FILES=[], - EXCLUDED_MULTI_PARTS_EXT=[], - EXCLUDED_MULTI_PARTS_FILES=[], - PLATFORMS_BINDING={}, - PLATFORMS_VERSIONS={}, - ROMS_FOLDER_NAME="roms", - FIRMWARE_FOLDER_NAME="bios", - ) - cnfg.has_structure_path_b = True - return cnfg - - def _make_handler(self, tmp_path: Path) -> FSRomsHandler: - handler = FSRomsHandler() - handler.base_path = tmp_path - return handler - - def _make_single_file_rom( - self, tmp_path: Path, platform: Platform, fs_name: str - ) -> Rom: - roms_path = tmp_path / platform.fs_slug / "roms" - roms_path.mkdir(parents=True, exist_ok=True) - (roms_path / fs_name).write_bytes(b"rom-bytes") - return Rom( - id=1, - fs_name=fs_name, - fs_path=f"{platform.fs_slug}/roms", - platform=platform, - ) - - def _make_multi_part_rom( - self, tmp_path: Path, platform: Platform, fs_name: str, file_names: list[str] - ) -> Rom: - rom_dir = tmp_path / platform.fs_slug / "roms" / fs_name - rom_dir.mkdir(parents=True, exist_ok=True) - for file_name in file_names: - file_path = rom_dir / file_name - file_path.parent.mkdir(parents=True, exist_ok=True) - file_path.write_bytes(b"rom-bytes") - return Rom( - id=1, - fs_name=fs_name, - fs_extension="", - fs_path=f"{platform.fs_slug}/roms", - platform=platform, - ) - @pytest.mark.asyncio async def test_single_file_extraction_attaches_values( - self, tmp_path: Path, config: Config + self, tmp_path: Path, sigil_config: Config ): platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") - handler = self._make_handler(tmp_path) - rom = self._make_single_file_rom(tmp_path, platform, "Game.nsp") + handler = make_sigil_handler(tmp_path) + rom = make_single_file_rom(tmp_path, platform, "Game.nsp") extraction = SigilExtractionResult( title_id="0100ABCD12340000", @@ -1445,12 +1449,10 @@ class TestSigilTitleIdExtraction: ) mock_extract = AsyncMock(return_value=extraction) - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with patch(self.SIGIL_PATCH_TARGET, mock_extract): - parsed = await handler.get_rom_files( - rom, prod_keys_path="/bios/switch/prod.keys" - ) + with patch(SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files( + rom, prod_keys_path="/bios/switch/prod.keys" + ) assert len(parsed.rom_files) == 1 assert parsed.rom_files[0].title_id == "0100ABCD12340000" @@ -1466,11 +1468,11 @@ class TestSigilTitleIdExtraction: @pytest.mark.asyncio async def test_multi_part_extraction_covers_nested_files( - self, tmp_path: Path, config: Config + self, tmp_path: Path, sigil_config: Config ): platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") - handler = self._make_handler(tmp_path) - rom = self._make_multi_part_rom( + handler = make_sigil_handler(tmp_path) + rom = make_multi_part_rom( tmp_path, platform, "Zelda", @@ -1510,10 +1512,8 @@ class TestSigilTitleIdExtraction: mock_extract = AsyncMock(side_effect=fake_extract) - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with patch(self.SIGIL_PATCH_TARGET, mock_extract): - parsed = await handler.get_rom_files(rom) + with patch(SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files(rom) by_name = {rf.file_name: rf for rf in parsed.rom_files} @@ -1542,15 +1542,13 @@ class TestSigilTitleIdExtraction: @pytest.mark.asyncio async def test_content_type_overrides_folder_category( - self, tmp_path: Path, config: Config + self, tmp_path: Path, sigil_config: Config ): platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") - handler = self._make_handler(tmp_path) + handler = make_sigil_handler(tmp_path) # Folder name "dlc" would otherwise derive category DLC, but the binary # content type says this is the base application. - rom = self._make_multi_part_rom( - tmp_path, platform, "Zelda", ["dlc/Zelda [base].nsp"] - ) + rom = make_multi_part_rom(tmp_path, platform, "Zelda", ["dlc/Zelda [base].nsp"]) mock_extract = AsyncMock( return_value=SigilExtractionResult( @@ -1562,20 +1560,18 @@ class TestSigilTitleIdExtraction: ) ) - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with patch(self.SIGIL_PATCH_TARGET, mock_extract): - parsed = await handler.get_rom_files(rom) + with patch(SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files(rom) assert parsed.rom_files[0].category == RomFileCategory.GAME @pytest.mark.asyncio async def test_folder_category_preserved_when_content_type_absent( - self, tmp_path: Path, config: Config + self, tmp_path: Path, sigil_config: Config ): platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") - handler = self._make_handler(tmp_path) - rom = self._make_multi_part_rom( + handler = make_sigil_handler(tmp_path) + rom = make_multi_part_rom( tmp_path, platform, "Zelda", ["dlc/Zelda [addon].nsp"] ) @@ -1590,10 +1586,8 @@ class TestSigilTitleIdExtraction: ) ) - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with patch(self.SIGIL_PATCH_TARGET, mock_extract): - parsed = await handler.get_rom_files(rom) + with patch(SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files(rom) rom_file = parsed.rom_files[0] # Folder-derived category survives, and title_version stays None. @@ -1602,13 +1596,11 @@ class TestSigilTitleIdExtraction: @pytest.mark.asyncio async def test_switch_base_derivation_from_update_only_folder( - self, tmp_path: Path, config: Config + self, tmp_path: Path, sigil_config: Config ): platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") - handler = self._make_handler(tmp_path) - rom = self._make_multi_part_rom( - tmp_path, platform, "Zelda", ["Zelda [update].nsp"] - ) + handler = make_sigil_handler(tmp_path) + rom = make_multi_part_rom(tmp_path, platform, "Zelda", ["Zelda [update].nsp"]) mock_extract = AsyncMock( return_value=SigilExtractionResult( @@ -1618,10 +1610,8 @@ class TestSigilTitleIdExtraction: ) ) - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with patch(self.SIGIL_PATCH_TARGET, mock_extract): - parsed = await handler.get_rom_files(rom) + with patch(SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files(rom) assert parsed.rom_files[0].title_id == "0100ABCD12340800" assert parsed.title_id == "0100ABCD12340000" @@ -1630,11 +1620,11 @@ class TestSigilTitleIdExtraction: @pytest.mark.asyncio async def test_switch_base_derivation_from_dlc_odd_nibble( - self, tmp_path: Path, config: Config + self, tmp_path: Path, sigil_config: Config ): platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") - handler = self._make_handler(tmp_path) - rom = self._make_single_file_rom(tmp_path, platform, "Game [DLC].nsp") + handler = make_sigil_handler(tmp_path) + rom = make_single_file_rom(tmp_path, platform, "Game [DLC].nsp") mock_extract = AsyncMock( return_value=SigilExtractionResult( @@ -1644,10 +1634,8 @@ class TestSigilTitleIdExtraction: ) ) - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with patch(self.SIGIL_PATCH_TARGET, mock_extract): - parsed = await handler.get_rom_files(rom) + with patch(SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files(rom) assert parsed.title_id == "0100ABCD12350000" assert parsed.save_id == "0100ABCD12350000" @@ -1655,11 +1643,11 @@ class TestSigilTitleIdExtraction: @pytest.mark.asyncio async def test_non_switch_platform_uses_first_extraction( - self, tmp_path: Path, config: Config + self, tmp_path: Path, sigil_config: Config ): platform = Platform(name="PlayStation Portable", slug="psp", fs_slug="psp") - handler = self._make_handler(tmp_path) - rom = self._make_single_file_rom(tmp_path, platform, "Game.iso") + handler = make_sigil_handler(tmp_path) + rom = make_single_file_rom(tmp_path, platform, "Game.iso") mock_extract = AsyncMock( return_value=SigilExtractionResult( @@ -1669,17 +1657,15 @@ class TestSigilTitleIdExtraction: ) ) - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with ( - patch(self.SIGIL_PATCH_TARGET, mock_extract), - patch( - "adapters.services.rahasher.RAHasherService.calculate_hash", - new_callable=AsyncMock, - return_value="", - ), - ): - parsed = await handler.get_rom_files(rom) + with ( + patch(SIGIL_PATCH_TARGET, mock_extract), + patch( + "adapters.services.rahasher.RAHasherService.calculate_hash", + new_callable=AsyncMock, + return_value="", + ), + ): + parsed = await handler.get_rom_files(rom) assert parsed.rom_files[0].title_id == "ULUS-10041" assert parsed.rom_files[0].save_id == "ULUS10041" @@ -1689,11 +1675,11 @@ class TestSigilTitleIdExtraction: @pytest.mark.asyncio async def test_3ds_extraction_maps_folder_split_usage( - self, tmp_path: Path, config: Config + self, tmp_path: Path, sigil_config: Config ): platform = Platform(name="Nintendo 3DS", slug="3ds", fs_slug="3ds") - handler = self._make_handler(tmp_path) - rom = self._make_single_file_rom(tmp_path, platform, "Game.3ds") + handler = make_sigil_handler(tmp_path) + rom = make_single_file_rom(tmp_path, platform, "Game.3ds") mock_extract = AsyncMock( return_value=SigilExtractionResult( @@ -1705,17 +1691,15 @@ class TestSigilTitleIdExtraction: ) ) - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with ( - patch(self.SIGIL_PATCH_TARGET, mock_extract), - patch( - "adapters.services.rahasher.RAHasherService.calculate_hash", - new_callable=AsyncMock, - return_value="", - ), - ): - parsed = await handler.get_rom_files(rom) + with ( + patch(SIGIL_PATCH_TARGET, mock_extract), + patch( + "adapters.services.rahasher.RAHasherService.calculate_hash", + new_callable=AsyncMock, + return_value="", + ), + ): + parsed = await handler.get_rom_files(rom) assert parsed.rom_files[0].save_id == "0004000e/0011c500" assert parsed.rom_files[0].title_id == "0004000E0011C500" @@ -1725,11 +1709,11 @@ class TestSigilTitleIdExtraction: @pytest.mark.asyncio async def test_dreamcast_extraction_maps_file_prefix_usage( - self, tmp_path: Path, config: Config + self, tmp_path: Path, sigil_config: Config ): platform = Platform(name="Dreamcast", slug="dc", fs_slug="dc") - handler = self._make_handler(tmp_path) - rom = self._make_single_file_rom(tmp_path, platform, "Game.chd") + handler = make_sigil_handler(tmp_path) + rom = make_single_file_rom(tmp_path, platform, "Game.chd") mock_extract = AsyncMock( return_value=SigilExtractionResult( @@ -1739,17 +1723,15 @@ class TestSigilTitleIdExtraction: ) ) - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with ( - patch(self.SIGIL_PATCH_TARGET, mock_extract), - patch( - "adapters.services.rahasher.RAHasherService.calculate_hash", - new_callable=AsyncMock, - return_value="", - ), - ): - parsed = await handler.get_rom_files(rom) + with ( + patch(SIGIL_PATCH_TARGET, mock_extract), + patch( + "adapters.services.rahasher.RAHasherService.calculate_hash", + new_callable=AsyncMock, + return_value="", + ), + ): + parsed = await handler.get_rom_files(rom) assert parsed.rom_files[0].title_id == "MK-51035" assert parsed.rom_files[0].save_id == "MK-51035" @@ -1758,18 +1740,16 @@ class TestSigilTitleIdExtraction: @pytest.mark.asyncio async def test_non_sigil_platform_skips_extraction( - self, tmp_path: Path, config: Config + self, tmp_path: Path, sigil_config: Config ): platform = Platform(name="Nintendo 64", slug="n64", fs_slug="n64") - handler = self._make_handler(tmp_path) - rom = self._make_single_file_rom(tmp_path, platform, "Game.z64") + handler = make_sigil_handler(tmp_path) + rom = make_single_file_rom(tmp_path, platform, "Game.z64") mock_extract = AsyncMock() - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with patch(self.SIGIL_PATCH_TARGET, mock_extract): - parsed = await handler.get_rom_files(rom, calculate_hashes=False) + with patch(SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files(rom, calculate_hashes=False) mock_extract.assert_not_awaited() assert parsed.rom_files[0].title_id is None @@ -1778,24 +1758,24 @@ class TestSigilTitleIdExtraction: @pytest.mark.asyncio async def test_extraction_disabled_skips_extraction( - self, tmp_path: Path, config: Config + self, tmp_path: Path, sigil_config: Config ): platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") - handler = self._make_handler(tmp_path) - rom = self._make_single_file_rom(tmp_path, platform, "Game.nsp") + handler = make_sigil_handler(tmp_path) + rom = make_single_file_rom(tmp_path, platform, "Game.nsp") mock_extract = AsyncMock() - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with patch(self.SIGIL_PATCH_TARGET, mock_extract): - parsed = await handler.get_rom_files(rom, extract_title_ids=False) + with patch(SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files(rom, extract_title_ids=False) mock_extract.assert_not_awaited() assert parsed.title_id is None @pytest.mark.asyncio - async def test_archive_rom_skips_extraction(self, tmp_path: Path, config: Config): + async def test_archive_rom_skips_extraction( + self, tmp_path: Path, sigil_config: Config + ): import io import zipfile @@ -1805,7 +1785,7 @@ class TestSigilTitleIdExtraction: zf.writestr("game.bin", b"fake PSX disc content") platform = Platform(name="PlayStation", slug="psx", fs_slug="psx") - handler = self._make_handler(tmp_path) + handler = make_sigil_handler(tmp_path) roms_path = tmp_path / "psx" / "roms" roms_path.mkdir(parents=True) (roms_path / "game.zip").write_bytes(buf.getvalue()) @@ -1818,17 +1798,15 @@ class TestSigilTitleIdExtraction: mock_extract = AsyncMock() - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with ( - patch(self.SIGIL_PATCH_TARGET, mock_extract), - patch( - "adapters.services.rahasher.RAHasherService.calculate_hash", - new_callable=AsyncMock, - return_value="", - ), - ): - parsed = await handler.get_rom_files(rom) + with ( + patch(SIGIL_PATCH_TARGET, mock_extract), + patch( + "adapters.services.rahasher.RAHasherService.calculate_hash", + new_callable=AsyncMock, + return_value="", + ), + ): + parsed = await handler.get_rom_files(rom) mock_extract.assert_not_awaited() assert parsed.rom_files[0].title_id is None @@ -1836,18 +1814,16 @@ class TestSigilTitleIdExtraction: @pytest.mark.asyncio async def test_non_hashable_archive_rom_skips_extraction( - self, tmp_path: Path, config: Config + self, tmp_path: Path, sigil_config: Config ): platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") - handler = self._make_handler(tmp_path) - rom = self._make_single_file_rom(tmp_path, platform, "game.zip") + handler = make_sigil_handler(tmp_path) + rom = make_single_file_rom(tmp_path, platform, "game.zip") mock_extract = AsyncMock() - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with patch(self.SIGIL_PATCH_TARGET, mock_extract): - parsed = await handler.get_rom_files(rom) + with patch(SIGIL_PATCH_TARGET, mock_extract): + parsed = await handler.get_rom_files(rom) mock_extract.assert_not_awaited() assert parsed.title_id is None @@ -1913,65 +1889,13 @@ class TestEmbedSwitchTitleIdInName: class TestSwitchTitleIdEmbedding: """Config-gated on-disk renaming of Switch files during get_rom_files.""" - SIGIL_PATCH_TARGET = "adapters.services.sigil.SigilService.extract_title_id" - - @pytest.fixture - def config(self): - cnfg = Config( - EXCLUDED_PLATFORMS=[], - EXCLUDED_SINGLE_EXT=[], - EXCLUDED_SINGLE_FILES=[], - EXCLUDED_MULTI_FILES=[], - EXCLUDED_MULTI_PARTS_EXT=[], - EXCLUDED_MULTI_PARTS_FILES=[], - PLATFORMS_BINDING={}, - PLATFORMS_VERSIONS={}, - ROMS_FOLDER_NAME="roms", - FIRMWARE_FOLDER_NAME="bios", - ) - cnfg.has_structure_path_b = True - return cnfg - - def _make_handler(self, tmp_path: Path) -> FSRomsHandler: - handler = FSRomsHandler() - handler.base_path = tmp_path - return handler - - def _make_single_file_rom( - self, tmp_path: Path, platform: Platform, fs_name: str - ) -> Rom: - roms_path = tmp_path / platform.fs_slug / "roms" - roms_path.mkdir(parents=True, exist_ok=True) - (roms_path / fs_name).write_bytes(b"rom-bytes") - return Rom( - id=1, - fs_name=fs_name, - fs_path=f"{platform.fs_slug}/roms", - platform=platform, - ) - - def _make_multi_part_rom( - self, tmp_path: Path, platform: Platform, fs_name: str, file_names: list[str] - ) -> Rom: - rom_dir = tmp_path / platform.fs_slug / "roms" / fs_name - rom_dir.mkdir(parents=True, exist_ok=True) - for file_name in file_names: - file_path = rom_dir / file_name - file_path.parent.mkdir(parents=True, exist_ok=True) - file_path.write_bytes(b"rom-bytes") - return Rom( - id=1, - fs_name=fs_name, - fs_extension="", - fs_path=f"{platform.fs_slug}/roms", - platform=platform, - ) - @pytest.mark.asyncio - async def test_flag_off_leaves_file_unchanged(self, tmp_path: Path, config: Config): + async def test_flag_off_leaves_file_unchanged( + self, tmp_path: Path, sigil_config: Config + ): platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") - handler = self._make_handler(tmp_path) - rom = self._make_single_file_rom(tmp_path, platform, "Game.nsp") + handler = make_sigil_handler(tmp_path) + rom = make_single_file_rom(tmp_path, platform, "Game.nsp") extraction = SigilExtractionResult( title_id="0100ABCD12340000", @@ -1979,10 +1903,8 @@ class TestSwitchTitleIdEmbedding: usage="folder-exact", ) - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)): - parsed = await handler.get_rom_files(rom, embed_title_ids=False) + with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)): + parsed = await handler.get_rom_files(rom, embed_title_ids=False) assert parsed.rom_files[0].file_name == "Game.nsp" assert parsed.renamed_rom_fs_name is None @@ -1990,11 +1912,11 @@ class TestSwitchTitleIdEmbedding: @pytest.mark.asyncio async def test_single_file_renamed_and_reconciled( - self, tmp_path: Path, config: Config + self, tmp_path: Path, sigil_config: Config ): platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") - handler = self._make_handler(tmp_path) - rom = self._make_single_file_rom(tmp_path, platform, "Moonlighter.xci") + handler = make_sigil_handler(tmp_path) + rom = make_single_file_rom(tmp_path, platform, "Moonlighter.xci") extraction = SigilExtractionResult( title_id="0100F4700B2E0000", @@ -2003,10 +1925,8 @@ class TestSwitchTitleIdEmbedding: version=0, ) - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)): - parsed = await handler.get_rom_files(rom, embed_title_ids=True) + with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)): + parsed = await handler.get_rom_files(rom, embed_title_ids=True) new_name = "Moonlighter [0100F4700B2E0000][v0].xci" assert parsed.rom_files[0].file_name == new_name @@ -2016,11 +1936,13 @@ class TestSwitchTitleIdEmbedding: assert not (tmp_path / "switch/roms/Moonlighter.xci").exists() @pytest.mark.asyncio - async def test_already_embedded_file_skipped(self, tmp_path: Path, config: Config): + async def test_already_embedded_file_skipped( + self, tmp_path: Path, sigil_config: Config + ): platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") - handler = self._make_handler(tmp_path) + handler = make_sigil_handler(tmp_path) fs_name = "Game [0100ABCD12340000][v0].nsp" - rom = self._make_single_file_rom(tmp_path, platform, fs_name) + rom = make_single_file_rom(tmp_path, platform, fs_name) extraction = SigilExtractionResult( title_id="0100ABCD12340000", @@ -2028,10 +1950,8 @@ class TestSwitchTitleIdEmbedding: usage="folder-exact", ) - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)): - parsed = await handler.get_rom_files(rom, embed_title_ids=True) + with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)): + parsed = await handler.get_rom_files(rom, embed_title_ids=True) assert parsed.rom_files[0].file_name == fs_name assert parsed.renamed_rom_fs_name is None @@ -2039,11 +1959,11 @@ class TestSwitchTitleIdEmbedding: @pytest.mark.asyncio async def test_non_switch_platform_never_renamed( - self, tmp_path: Path, config: Config + self, tmp_path: Path, sigil_config: Config ): platform = Platform(name="PlayStation Portable", slug="psp", fs_slug="psp") - handler = self._make_handler(tmp_path) - rom = self._make_single_file_rom(tmp_path, platform, "Game.iso") + handler = make_sigil_handler(tmp_path) + rom = make_single_file_rom(tmp_path, platform, "Game.iso") extraction = SigilExtractionResult( title_id="0100ABCD12340000", @@ -2051,20 +1971,20 @@ class TestSwitchTitleIdEmbedding: usage="folder-exact", ) - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)): - parsed = await handler.get_rom_files(rom, embed_title_ids=True) + with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)): + parsed = await handler.get_rom_files(rom, embed_title_ids=True) assert parsed.rom_files[0].file_name == "Game.iso" assert parsed.renamed_rom_fs_name is None assert (tmp_path / "psp/roms/Game.iso").exists() @pytest.mark.asyncio - async def test_collision_target_exists_skips(self, tmp_path: Path, config: Config): + async def test_collision_target_exists_skips( + self, tmp_path: Path, sigil_config: Config + ): platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") - handler = self._make_handler(tmp_path) - rom = self._make_single_file_rom(tmp_path, platform, "Game.nsp") + handler = make_sigil_handler(tmp_path) + rom = make_single_file_rom(tmp_path, platform, "Game.nsp") target = tmp_path / "switch/roms/Game [0100ABCD12340000][v0].nsp" target.write_bytes(b"existing") @@ -2074,10 +1994,8 @@ class TestSwitchTitleIdEmbedding: usage="folder-exact", ) - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)): - parsed = await handler.get_rom_files(rom, embed_title_ids=True) + with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)): + parsed = await handler.get_rom_files(rom, embed_title_ids=True) assert parsed.rom_files[0].file_name == "Game.nsp" assert parsed.renamed_rom_fs_name is None @@ -2085,15 +2003,13 @@ class TestSwitchTitleIdEmbedding: assert target.read_bytes() == b"existing" @pytest.mark.asyncio - async def test_no_title_id_not_renamed(self, tmp_path: Path, config: Config): + async def test_no_title_id_not_renamed(self, tmp_path: Path, sigil_config: Config): platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") - handler = self._make_handler(tmp_path) - rom = self._make_single_file_rom(tmp_path, platform, "Game.nsp") + handler = make_sigil_handler(tmp_path) + rom = make_single_file_rom(tmp_path, platform, "Game.nsp") - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with patch(self.SIGIL_PATCH_TARGET, AsyncMock(return_value=None)): - parsed = await handler.get_rom_files(rom, embed_title_ids=True) + with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=None)): + parsed = await handler.get_rom_files(rom, embed_title_ids=True) assert parsed.rom_files[0].file_name == "Game.nsp" assert parsed.renamed_rom_fs_name is None @@ -2101,11 +2017,11 @@ class TestSwitchTitleIdEmbedding: @pytest.mark.asyncio async def test_multi_part_nested_files_renamed( - self, tmp_path: Path, config: Config + self, tmp_path: Path, sigil_config: Config ): platform = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") - handler = self._make_handler(tmp_path) - rom = self._make_multi_part_rom( + handler = make_sigil_handler(tmp_path) + rom = make_multi_part_rom( tmp_path, platform, "Zelda", @@ -2139,10 +2055,8 @@ class TestSwitchTitleIdEmbedding: version=0, ) - with pytest.MonkeyPatch.context() as m: - m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) - with patch(self.SIGIL_PATCH_TARGET, AsyncMock(side_effect=fake_extract)): - parsed = await handler.get_rom_files(rom, embed_title_ids=True) + with patch(SIGIL_PATCH_TARGET, AsyncMock(side_effect=fake_extract)): + parsed = await handler.get_rom_files(rom, embed_title_ids=True) names = {rf.file_name for rf in parsed.rom_files} assert "Zelda base [0100ABCD12340000][v0].nsp" in names diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md index 854b907ef..e2353940c 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/BACKEND_ARCHITECTURE.md @@ -1475,6 +1475,11 @@ Nginx receives an internal redirect header and efficiently serves the file from Hashing can be disabled per-installation via `skip_hash_calculation` in config.yml. +Alongside hashing, scans extract platform-native title IDs from ROM binaries via +the optional `sigil` binding (Switch, PlayStation, Nintendo, Xbox and Dreamcast +families). The feature no-ops when the binding is absent, and can be turned off +with `skip_title_id_extraction`. + --- ## 13. Caching (Redis) @@ -1644,6 +1649,8 @@ filesystem: roms_folder: "roms" # Subfolder name for ROMs firmware_folder: "bios" # Subfolder name for BIOS skip_hash_calculation: false + skip_title_id_extraction: false # Skip sigil title ID extraction + embed_switch_title_ids: false # Rename Switch ROMs to embed their title ID system: platforms: diff --git a/examples/config.example.yml b/examples/config.example.yml index d6baa570a..bc9a61f90 100644 --- a/examples/config.example.yml +++ b/examples/config.example.yml @@ -76,6 +76,10 @@ # roms_folder: 'roms' # # Skip file hash calculations on low power devices (eg. Raspberry PI) # skip_hash_calculation: false +# # Skip reading platform-native title IDs out of ROM binaries during scans +# skip_title_id_extraction: false +# # Rename Switch ROMs to embed ` [TITLEID][vVERSION]` in their filename +# embed_switch_title_ids: false # scan: # # Metadata priority during scans diff --git a/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue b/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue index 4249883a7..9ed8a9439 100644 --- a/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue +++ b/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue @@ -97,16 +97,23 @@ const audioDuration = computed(() => formatDuration(props.file.track_meta?.duration_seconds), ); -const hasAnyHash = computed( - () => - Boolean(props.file.title_id) || - props.file.title_version != null || - Boolean(props.file.sha1_hash) || - Boolean(props.file.chd_sha1_hash) || - Boolean(props.file.md5_hash) || - Boolean(props.file.crc_hash) || - Boolean(props.file.ra_hash), -); +// Title ids get the same click-to-copy treatment as the digests. +const identifierChips = computed(() => { + const f = props.file; + const chips: { label: string; value: string | null }[] = [ + { label: t("rom.title-id"), value: f.title_id }, + { + label: t("rom.version"), + value: f.title_version != null ? String(f.title_version) : null, + }, + { label: "SHA-1", value: f.sha1_hash }, + { label: "CHD SHA-1", value: f.chd_sha1_hash }, + { label: "MD5", value: f.md5_hash }, + { label: "CRC", value: f.crc_hash }, + { label: "RA", value: f.ra_hash }, + ]; + return chips.filter((chip) => Boolean(chip.value)); +});
-
+
- - - - - -
@@ -336,7 +308,7 @@ const hasAnyHash = computed( opacity: 0.5; } -.r-v2-file-row__hashes { +.r-v2-file-row__identifiers { display: flex; flex-wrap: wrap; gap: 4px; diff --git a/frontend/src/v2/components/GameDetails/MetadataTab.vue b/frontend/src/v2/components/GameDetails/MetadataTab.vue index 1ea522d3d..865626621 100644 --- a/frontend/src/v2/components/GameDetails/MetadataTab.vue +++ b/frontend/src/v2/components/GameDetails/MetadataTab.vue @@ -1,6 +1,6 @@ @@ -172,12 +171,12 @@ const identifierChips = computed(() => {
-
+
@@ -302,7 +301,7 @@ const identifierChips = computed(() => { opacity: 0.5; } -.r-v2-file-row__identifiers { +.r-v2-file-row__hashes { display: flex; flex-wrap: wrap; gap: 4px; diff --git a/frontend/src/v2/components/GameDetails/MetadataTab.vue b/frontend/src/v2/components/GameDetails/MetadataTab.vue index 8b14ef6ab..a0d6f01c2 100644 --- a/frontend/src/v2/components/GameDetails/MetadataTab.vue +++ b/frontend/src/v2/components/GameDetails/MetadataTab.vue @@ -30,15 +30,16 @@ type Row = { label: string; value: string }; const fileRows = computed(() => { const r = props.rom; const size = r.fs_size_bytes != null ? formatBytes(r.fs_size_bytes) : "—"; - return [ + const rows: Row[] = [ { label: t("rom.filename"), value: r.fs_name }, { label: t("common.size"), value: size }, - // Only the sigil platforms carry these, so skip rather than dash them. - ...(r.title_id ? [{ label: t("rom.title-id"), value: r.title_id }] : []), - ...(r.save_target - ? [{ label: t("rom.save-target"), value: r.save_target }] - : []), ]; + // Present only for platforms with a readable binary id, so skip rather + // than dash them. + if (r.title_id) rows.push({ label: t("rom.title-id"), value: r.title_id }); + if (r.save_target) + rows.push({ label: t("rom.save-target"), value: r.save_target }); + return rows; }); // Hash rows accept `value: string | null` because HashChip's click-to- From adc4dbfe25bcc9184546388dd62be4baf24e6a29 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 2 Sep 2026 16:38:09 -0400 Subject: [PATCH 34/40] db: renumber the sigil migration behind master's new revisions Master landed 0114 and 0115, so the sigil columns move to 0116 and revise 0115_add_steam_metadata, leaving a single alembic head. Co-Authored-By: Claude Opus 5 (1M context) --- .../{0114_sigil_title_ids.py => 0116_sigil_title_ids.py} | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) rename backend/alembic/versions/{0114_sigil_title_ids.py => 0116_sigil_title_ids.py} (93%) diff --git a/backend/alembic/versions/0114_sigil_title_ids.py b/backend/alembic/versions/0116_sigil_title_ids.py similarity index 93% rename from backend/alembic/versions/0114_sigil_title_ids.py rename to backend/alembic/versions/0116_sigil_title_ids.py index afbdeb2ff..fdcc056f6 100644 --- a/backend/alembic/versions/0114_sigil_title_ids.py +++ b/backend/alembic/versions/0116_sigil_title_ids.py @@ -1,8 +1,8 @@ """Add the binary identity columns on roms: title_id, save_target and save_target_layout. -Revision ID: 0114_sigil_title_ids -Revises: 0113_roms_locked_fields +Revision ID: 0116_sigil_title_ids +Revises: 0115_add_steam_metadata Create Date: 2026-07-23 00:00:00.000000 """ @@ -14,8 +14,8 @@ from sqlalchemy.dialects.postgresql import ENUM from utils.database import is_postgresql # revision identifiers, used by Alembic. -revision = "0114_sigil_title_ids" -down_revision = "0113_roms_locked_fields" +revision = "0116_sigil_title_ids" +down_revision = "0115_add_steam_metadata" branch_labels = None depends_on = None From 97a16e2c79c60a2ebea5793db937db40d482ca13 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 2 Sep 2026 17:13:20 -0400 Subject: [PATCH 35/40] refactor: tighten comments and tests on the sigil branch Reverts the FileRow hash-chip loop. It was left over from the per-file version chip that no longer exists, so it is unrelated to title ids. Cuts the comments that restate the code or defend an obvious choice, and the `Args:` block on `get_matching_missing_rom` that repeated its own parameter names. The CNMT content-type rationale now lives only on `CONTENT_TYPE_CATEGORIES`. Tests exercise the production path: the title id regex is checked with `fullmatch`, the way the caller uses it, and `test_identity` builds its auth header the way every other endpoint test does. Co-Authored-By: Claude Opus 5 (1M context) --- Dockerfile | 3 +- backend/handler/database/roms_handler.py | 11 +--- backend/handler/filesystem/roms_handler.py | 10 ++-- backend/tests/endpoints/roms/test_identity.py | 18 +++---- backend/tests/utils/test_switch.py | 9 ++-- .../GameDetails/FilesTab/FileRow.vue | 51 +++++++++++++------ .../v2/components/GameDetails/MetadataTab.vue | 2 - 7 files changed, 54 insertions(+), 50 deletions(-) diff --git a/Dockerfile b/Dockerfile index 676ca92b3..a228704e7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -83,8 +83,7 @@ ENV PATH="/app/.venv/bin:${PATH}" # Python so the ABI matches. Keep the pin in sync with docker/Dockerfile. ARG SIGIL_VERSION=9665f03c04d0f547ed38dd5e5e31916c1da5f2e9 ARG PYTHON_VERSION=3.13 -# One layer so the clone and the cmake tree never reach the image, which rules -# out WORKDIR between the steps. +# One layer, so the clone and the cmake tree never reach the image. # trunk-ignore(hadolint/DL3003) RUN git clone --filter=blob:none https://github.com/rommforge/argosy-sigil.git /tmp/argosy-sigil \ && cd /tmp/argosy-sigil \ diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index 0ddfce6be..c128ff666 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -3267,16 +3267,9 @@ class DBRomsHandler(DBBaseHandler): Used during scanning to reassociate a renamed or moved file with its existing entry (preserving collections, notes, and assets) instead of creating a duplicate. All three hashes must match; any missing hash - falls through to the binary title id, which is what non-hashable - platforms like Switch carry instead. With neither, a new entry is - created. + falls through to the binary title id, which non-hashable platforms + like Switch carry instead. - Args: - platform_id: Platform whose missing entries are searched. - crc_hash: CRC hash of the scanned file, if hashed. - md5_hash: MD5 hash of the scanned file, if hashed. - sha1_hash: SHA1 hash of the scanned file, if hashed. - title_id: Binary title id of the scanned file, if extracted. Returns: The single matching ROM, or None when there is no unambiguous one. """ diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index cfce9892a..0034fd112 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -431,8 +431,8 @@ class FSRomsHandler(FSHandler): async def _extract_title_id(rom_file: RomFile) -> str | None: """Populate the file's title id fields, returning its new name if embedding renamed it on disk.""" - # Only Switch reads a per-file content type, so elsewhere every - # extraction past the first is parsed and then discarded. + # Only Switch needs a per-file content type; one extraction is + # enough elsewhere. if not sigil_platform or (sigil_extractions and not is_switch): return None @@ -442,8 +442,6 @@ class FSRomsHandler(FSHandler): ) if extraction is None: return None - # For Switch, the binary CNMT content type is authoritative over the - # folder-derived category. Leave the folder category when absent. if extraction.content_type is not None: category = switch.CONTENT_TYPE_CATEGORIES.get(extraction.content_type) if category is not None: @@ -915,9 +913,7 @@ class FSRomsHandler(FSHandler): ) try: - await self.rename_fs_rom( - name, new_name, str(rel_file_path.parent.as_posix()) - ) + await self.rename_fs_rom(name, new_name, rel_file_path.parent.as_posix()) except RomAlreadyExistsException: log.warning( f"Cannot embed title id: target {new_name} already exists, skipping rename" diff --git a/backend/tests/endpoints/roms/test_identity.py b/backend/tests/endpoints/roms/test_identity.py index 9228e1d94..acab59892 100644 --- a/backend/tests/endpoints/roms/test_identity.py +++ b/backend/tests/endpoints/roms/test_identity.py @@ -2,19 +2,13 @@ import pytest from fastapi import status from fastapi.testclient import TestClient -from handler.database import db_rom_handler +from handler.database import db_platform_handler, db_rom_handler from models.platform import Platform from models.rom import Rom, SaveTargetLayout -def _auth(token: str) -> dict[str, str]: - return {"Authorization": f"Bearer {token}"} - - @pytest.fixture def switch_platform() -> Platform: - from handler.database import db_platform_handler - return db_platform_handler.add_platform( Platform(name="Nintendo Switch", slug="switch", fs_slug="switch") ) @@ -42,7 +36,7 @@ def test_stores_the_identity_a_client_extracted( ): response = client.put( f"/api/roms/{switch_rom.id}/identity", - headers=_auth(access_token), + headers={"Authorization": f"Bearer {access_token}"}, json={ "title_id": "0100ABCD12340000", "save_target": "0100ABCD12340000", @@ -67,7 +61,7 @@ def test_a_switch_update_or_dlc_id_resolves_to_its_base( """Reassociation matches on this id, so an update id here strands the entry.""" response = client.put( f"/api/roms/{switch_rom.id}/identity", - headers=_auth(access_token), + headers={"Authorization": f"Bearer {access_token}"}, json={"title_id": submitted}, ) assert response.status_code == status.HTTP_200_OK @@ -82,7 +76,7 @@ def test_a_non_switch_serial_is_stored_verbatim( ): response = client.put( f"/api/roms/{rom.id}/identity", - headers=_auth(access_token), + headers={"Authorization": f"Bearer {access_token}"}, json={"title_id": "SLUS-20152", "save_target": "BASLUS-20152"}, ) assert response.status_code == status.HTTP_200_OK @@ -103,7 +97,7 @@ def test_omitted_fields_are_left_alone( response = client.put( f"/api/roms/{switch_rom.id}/identity", - headers=_auth(access_token), + headers={"Authorization": f"Bearer {access_token}"}, json={"save_target_layout": "folder-exact"}, ) assert response.status_code == status.HTTP_200_OK @@ -117,7 +111,7 @@ def test_omitted_fields_are_left_alone( def test_an_unknown_rom_is_not_found(client: TestClient, access_token: str): response = client.put( "/api/roms/99999/identity", - headers=_auth(access_token), + headers={"Authorization": f"Bearer {access_token}"}, json={"title_id": "0100ABCD12340000"}, ) assert response.status_code == status.HTTP_404_NOT_FOUND diff --git a/backend/tests/utils/test_switch.py b/backend/tests/utils/test_switch.py index c64fc7051..b057ff6b7 100644 --- a/backend/tests/utils/test_switch.py +++ b/backend/tests/utils/test_switch.py @@ -46,11 +46,14 @@ class TestDeriveBaseTitleId: class TestTitleIdRegexes: def test_a_bare_id_matches_the_plain_regex(self): - assert switch.TITLE_ID_REGEX.match("0100ABCD12340000") + assert switch.TITLE_ID_REGEX.fullmatch("0100ABCD12340000") - @pytest.mark.parametrize("value", ["0100ABCD1234000", "[0100ABCD12340000]", "xyz"]) + @pytest.mark.parametrize( + "value", + ["0100ABCD1234000", "0100ABCD123400001", "[0100ABCD12340000]", "xyz"], + ) def test_anything_else_does_not(self, value: str): - assert not switch.TITLE_ID_REGEX.match(value) + assert not switch.TITLE_ID_REGEX.fullmatch(value) def test_an_embedded_id_is_found_anywhere_in_a_name(self): assert switch.TITLE_ID_BRACKET_REGEX.search("Game [0100ABCD12340000][v0].nsp") diff --git a/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue b/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue index 926f2e244..a7e70a380 100644 --- a/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue +++ b/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue @@ -97,16 +97,14 @@ const audioDuration = computed(() => formatDuration(props.file.track_meta?.duration_seconds), ); -const hashChips = computed(() => { - const f = props.file; - return [ - { label: "SHA-1", value: f.sha1_hash }, - { label: "CHD SHA-1", value: f.chd_sha1_hash }, - { label: "MD5", value: f.md5_hash }, - { label: "CRC", value: f.crc_hash }, - { label: "RA", value: f.ra_hash }, - ].flatMap((chip) => (chip.value ? [{ ...chip, value: chip.value }] : [])); -}); +const hasAnyHash = computed( + () => + Boolean(props.file.sha1_hash) || + Boolean(props.file.chd_sha1_hash) || + Boolean(props.file.md5_hash) || + Boolean(props.file.crc_hash) || + Boolean(props.file.ra_hash), +);
-
+
+ + + +
diff --git a/frontend/src/v2/components/GameDetails/MetadataTab.vue b/frontend/src/v2/components/GameDetails/MetadataTab.vue index dbba9075a..4b8007634 100644 --- a/frontend/src/v2/components/GameDetails/MetadataTab.vue +++ b/frontend/src/v2/components/GameDetails/MetadataTab.vue @@ -34,8 +34,6 @@ const fileRows = computed(() => { { label: t("rom.filename"), value: r.fs_name }, { label: t("common.size"), value: size }, ]; - // Present only for platforms with a readable binary id, so skip rather - // than dash them. if (r.title_id) rows.push({ label: t("rom.title-id"), value: r.title_id }); if (r.save_target) rows.push({ label: t("rom.save-target"), value: r.save_target }); From b13a2373fbb124769327f6e75a9f9b77264e3842 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Wed, 2 Sep 2026 18:41:22 -0500 Subject: [PATCH 36/40] chore: drop the vcrpy exclude-newer override The override let vcrpy 8.2.1 past the rolling 7-day exclude-newer window on the day after its release. The window has since caught up, and the fixed 2026-06-17 cutoff was now holding vcrpy back from 8.3.0. The aiohttp 3.14 compatibility fix the comment referred to landed in 8.2.0 and is present in every later release, so nothing needs the override. Upgrade vcrpy to 8.3.0 in the lock so the change exercises what the removal permits; all cassette-backed tests pass on it. Co-Authored-By: Claude Fable 5.1 --- pyproject.toml | 3 --- uv.lock | 9 +++------ 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index c50fb843d..2506484ce 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -144,9 +144,6 @@ DEP002 = [ # DEP002 rule: Project should not contain unused dependencies [tool.uv] package = false exclude-newer = "7 days" -# vcrpy >= 8.2.0 is required for aiohttp 3.14 compatibility (the removal of -# `AsyncStreamReaderMixin`); allow it past the rolling 7-day window. -exclude-newer-package = { vcrpy = "2026-06-17" } [tool.ty.environment] root = ["./backend"] diff --git a/uv.lock b/uv.lock index f89c4c28b..cc438e352 100644 --- a/uv.lock +++ b/uv.lock @@ -10,9 +10,6 @@ resolution-markers = [ exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values. exclude-newer-span = "P7D" -[options.exclude-newer-package] -vcrpy = "2026-06-18T00:00:00Z" - [[package]] name = "aiohappyeyeballs" version = "2.6.2" @@ -2797,15 +2794,15 @@ wheels = [ [[package]] name = "vcrpy" -version = "8.2.1" +version = "8.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pyyaml" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/08/db/08183b845b0040bb877dad2bd7e4e0976fc232bb3476d7ee369c6c4f8b5a/vcrpy-8.2.1.tar.gz", hash = "sha256:d73a6e4eb6dae8148e659764b7a00e68cc51ba29ba9e6a85e1f0790ad96b97df", size = 90511, upload-time = "2026-06-16T13:20:52.906Z" } +sdist = { url = "https://files.pythonhosted.org/packages/39/d5/8a1f8eb603e2d35fbb0ecd1e309d0c5c18a0ecfc8c0a8f04088bbc8f833b/vcrpy-8.3.0.tar.gz", hash = "sha256:46d64e77e8d95e5c76c7d9a94ff05d8b38b2ae4e1d4869eb0235024b6fcb5212", size = 96117, upload-time = "2026-07-04T14:27:01.608Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f8/7c/0e812ab83f5289404c674f3461ba783250b967d34b5ab034d361236ec042/vcrpy-8.2.1-py3-none-any.whl", hash = "sha256:7ce58c9e2792b246f79d6f4b3e9660676cc6f853be17e1547305b4437ab1ff85", size = 44925, upload-time = "2026-06-16T13:20:51.734Z" }, + { url = "https://files.pythonhosted.org/packages/34/77/cb4219be91508399cbcb6143bad89462cfb16f6c638458f454a5d46ac95a/vcrpy-8.3.0-py3-none-any.whl", hash = "sha256:bd66e6143746778157f00e2a922527a8d96b2fdc350be8988a45a29c843815b9", size = 46530, upload-time = "2026-07-04T14:27:00.546Z" }, ] [[package]] From 787bbba2b48fbf5d57a63c09ae86c9ee54c4b812 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 2 Sep 2026 21:03:18 -0400 Subject: [PATCH 37/40] refactor(tasks): give every enqueue one home Scheduling moved onto RQ, which left the task catalog with two identity schemes: the registry key a job payload now carries, and the dotted func path each PeriodicTask still declared. Nothing read the latter, so it is gone, along with the test that guarded paths no payload names. Four sites built the same enqueue by hand and had already drifted: the startup backfills passed the global timeout and no result_ttl, so an auto-enqueued conversion fell out of the task list after RQ's default 500s while the same task triggered by an admin lived for TASK_RESULT_TTL. They now go through enqueue_task, which derives timeout, ttl and meta from the task itself. Scan discovery paid a Redis round trip per queued job to re-read a status the fetch already carried, and the stale sweep read every delayed job to find the few past due. Both now ask Redis once. Co-Authored-By: Claude Opus 5 (1M context) --- backend/endpoints/sockets/scan.py | 62 ++++---- backend/endpoints/tasks.py | 79 ++++------ backend/exceptions/task_exceptions.py | 11 +- backend/handler/redis_handler.py | 28 +++- backend/startup.py | 125 +++++---------- backend/tasks/cron_config.py | 10 +- backend/tasks/registry.py | 43 +++++- backend/tasks/scheduled/cleanup_netplay.py | 1 - .../scheduled/cleanup_orphaned_resources.py | 1 - backend/tasks/scheduled/cleanup_upload_tmp.py | 1 - backend/tasks/scheduled/cleanup_zip_cache.py | 1 - .../tasks/scheduled/convert_images_to_webp.py | 1 - backend/tasks/scheduled/scan_library.py | 1 - .../sync_retroachievements_progress.py | 1 - .../scheduled/update_launchbox_metadata.py | 1 - .../tasks/scheduled/update_switch_titledb.py | 1 - backend/tasks/sync_push_pull_task.py | 1 - backend/tasks/tasks.py | 9 +- backend/tests/endpoints/sockets/test_scan.py | 43 ++++-- backend/tests/endpoints/test_tasks.py | 66 ++++---- backend/tests/handler/test_redis_handler.py | 31 +++- .../tasks/test_cleanup_orphaned_resources.py | 6 - .../tests/tasks/test_cleanup_upload_tmp.py | 4 - backend/tests/tasks/test_cleanup_zip_cache.py | 1 - backend/tests/tasks/test_registry.py | 47 +++++- backend/tests/tasks/test_scan_library.py | 5 - backend/tests/tasks/test_sync_push_pull.py | 1 - .../test_sync_retroachievements_progress.py | 4 - backend/tests/tasks/test_task_func_paths.py | 27 ++-- backend/tests/tasks/test_tasks.py | 6 - .../tasks/test_update_launchbox_metadata.py | 4 - .../tests/tasks/test_update_switch_titledb.py | 4 - backend/tests/test_startup.py | 146 ++++++------------ backend/watcher.py | 34 ++-- docker/init_scripts/init | 30 ++-- entrypoint.sh | 18 +-- 36 files changed, 398 insertions(+), 456 deletions(-) diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index d062ee384..c23f6ece7 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -8,7 +8,6 @@ from typing import Any, Final import socketio # type: ignore from rq import Worker, get_current_job -from rq.exceptions import NoSuchJobError from rq.job import Job, JobStatus from rq.registry import ScheduledJobRegistry from sqlalchemy.exc import IntegrityError @@ -53,6 +52,7 @@ from handler.metadata.ss_handler import log_scan_summary as log_ss_scan_summary from handler.redis_handler import ( get_job_func_name, get_job_status, + get_worker_current_job, high_prio_queue, low_prio_queue, redis_client, @@ -117,13 +117,7 @@ def _get_running_scan_job() -> Job | None: the workers what they are holding. """ for worker in Worker.all(connection=redis_client): - # A worker killed mid-scan keeps pointing at its job until its own - # registration expires, and the job can be gone by then. - try: - job = worker.get_current_job() - except NoSuchJobError: - continue - + job = get_worker_current_job(worker) if job is not None and _is_scan_job(job): return job @@ -136,17 +130,17 @@ def _get_queued_scan_jobs() -> list[Job]: Socket scans go to the high priority queue and watcher scans to the low priority one, once their delay is up. """ - jobs: dict[str, Job] = {} + job_ids = chain(high_prio_queue.get_job_ids(), low_prio_queue.get_job_ids()) + jobs = Job.fetch_many(job_ids, connection=redis_client) - for job in chain(high_prio_queue.get_jobs(), low_prio_queue.get_jobs()): - if ( - isinstance(job, Job) - and _is_scan_job(job) - and get_job_status(job) == JobStatus.QUEUED - ): - jobs[job.id] = job - - return list(jobs.values()) + return [ + job + for job in jobs + if job is not None and _is_scan_job(job) + # The fetch above already carries the status, so re-reading it would be + # a round trip per queued job. + and get_job_status(job, refresh=False) == JobStatus.QUEUED + ] def _scheduled_scan_registry() -> ScheduledJobRegistry: @@ -186,24 +180,32 @@ def drop_stale_scheduled_scans() -> int: """ registry = _scheduled_scan_registry() cutoff = datetime.now(timezone.utc) - STALE_SCHEDULED_SCAN_AGE + + # The registry is scored by due time, so it can hand back only what is past + # due rather than every delayed job. + stale_ids = registry.get_jobs_to_schedule(int(cutoff.timestamp())) + jobs = Job.fetch_many(stale_ids, connection=redis_client) dropped = 0 - for job in _get_scheduled_scan_jobs(): - try: - scheduled_at = registry.get_scheduled_time(job) - except NoSuchJobError: - continue - - if scheduled_at > cutoff: + for job in jobs: + if job is None or not _is_scan_job(job): continue job.cancel() dropped += 1 - log.warning(f"Dropped scan scheduled for {scheduled_at}, too long past due") + log.warning(f"Dropped scan {job.id}, due over {STALE_SCHEDULED_SCAN_AGE} ago") return dropped +def scan_job_meta(scan_type: ScanType) -> dict[str, Any]: + """What a scan job carries so a client can tell which scan is running.""" + return { + "task_name": f"{scan_type.value.capitalize()} Scan", + "task_type": TaskType.SCAN, + } + + def _scan_job_label(job: Job) -> str: """How to refer to a scan job when reporting it to a client.""" return str(job.meta.get("task_name") or "A scan") @@ -214,7 +216,8 @@ def _scan_in_flight_message(running: Job | None, queued: list[Job]) -> str: if running is None: return f"{_scan_job_label(queued[0])} is already queued" - if get_job_status(running) in (JobStatus.CANCELED, JobStatus.STOPPED): + stopping = (JobStatus.CANCELED, JobStatus.STOPPED) + if get_job_status(running, refresh=False) in stopping: return f"{_scan_job_label(running)} is still stopping, try again in a moment" return f"{_scan_job_label(running)} is already running" @@ -1373,10 +1376,7 @@ async def scan_handler(sid: str, options: dict[str, Any]): platform_fs_slugs=platform_fs_slugs, job_timeout=SCAN_TIMEOUT, # Timeout (default of 4 hours) result_ttl=TASK_RESULT_TTL, - meta={ - "task_name": f"{scan_type.value.capitalize()} Scan", - "task_type": TaskType.SCAN, - }, + meta=scan_job_meta(scan_type), ) diff --git a/backend/endpoints/tasks.py b/backend/endpoints/tasks.py index e27a4ec9f..0fc44e26a 100644 --- a/backend/endpoints/tasks.py +++ b/backend/endpoints/tasks.py @@ -7,11 +7,7 @@ from rq.exceptions import NoSuchJobError from rq.job import Job, JobStatus from rq.registry import FailedJobRegistry, FinishedJobRegistry -from config import ( - ENABLE_RESCAN_ON_FILESYSTEM_CHANGE, - RESCAN_ON_FILESYSTEM_CHANGE_DELAY, - TASK_RESULT_TTL, -) +from config import ENABLE_RESCAN_ON_FILESYSTEM_CHANGE, RESCAN_ON_FILESYSTEM_CHANGE_DELAY from decorators.auth import protected_route from endpoints.responses import ( CleanupTaskStatusResponse, @@ -29,12 +25,13 @@ from handler.auth.constants import Scope from handler.redis_handler import ( default_queue, get_job_func_name, + get_worker_current_job, high_prio_queue, low_prio_queue, redis_client, ) -from tasks.registry import MANUAL_TASKS, SCHEDULED_TASKS -from tasks.tasks import Task, TaskType, run_task_by_name +from tasks.registry import MANUAL_TASKS, SCHEDULED_TASKS, enqueue_task +from tasks.tasks import Task, TaskType from utils.router import APIRouter router = APIRouter( @@ -44,15 +41,21 @@ router = APIRouter( # Scheduled tasks an admin can see and trigger. The rest of the catalog runs on -# its schedule without being surfaced. -VISIBLE_SCHEDULED_TASKS: Final = ( - "scan_library", - "update_launchbox_metadata", - "update_switch_titledb", - "convert_images_to_webp", - "cleanup_zip_cache", - "cleanup_orphaned_resources", -) +# its schedule without being surfaced. Resolved here so a registry rename fails +# at import rather than on a request. +VISIBLE_SCHEDULED_TASKS: Final[dict[str, Task]] = { + name: SCHEDULED_TASKS[name] + for name in ( + "scan_library", + "update_launchbox_metadata", + "update_switch_titledb", + "convert_images_to_webp", + "cleanup_zip_cache", + "cleanup_orphaned_resources", + ) +} + +RUNNABLE_TASKS: Final[dict[str, Task]] = {**MANUAL_TASKS, **VISIBLE_SCHEDULED_TASKS} def _build_task_info(name: str, task: Task) -> TaskInfo: @@ -164,8 +167,8 @@ async def list_tasks(request: Request) -> GroupedTasksDict: for name, task in MANUAL_TASKS.items(): grouped_tasks["manual"].append(_build_task_info(name, task)) - for name in VISIBLE_SCHEDULED_TASKS: - grouped_tasks["scheduled"].append(_build_task_info(name, SCHEDULED_TASKS[name])) + for name, task in VISIBLE_SCHEDULED_TASKS.items(): + grouped_tasks["scheduled"].append(_build_task_info(name, task)) # Add the adhoc watcher task grouped_tasks["watcher"].append( @@ -195,15 +198,8 @@ async def get_tasks_status(request: Request) -> list[TaskStatusResponse]: all_tasks: list[TaskStatusResponse] = [] # Get currently running jobs from workers - workers = Worker.all(connection=redis_client) - for worker in workers: - # A worker killed mid-job keeps pointing at it until its own - # registration expires, and the job can be gone by then. - try: - current_job = worker.get_current_job() - except NoSuchJobError: - continue - + for worker in Worker.all(connection=redis_client): + current_job = get_worker_current_job(worker) if current_job: all_tasks.append(_build_task_status_response(current_job)) @@ -299,39 +295,22 @@ async def run_single_task( Returns: TaskExecutionResponse: Task execution response with details """ - all_tasks: dict[str, Task] = { - **MANUAL_TASKS, - **{name: SCHEDULED_TASKS[name] for name in VISIBLE_SCHEDULED_TASKS}, - } - - if task_name not in all_tasks: - available_tasks = list(all_tasks.keys()) + task_instance = RUNNABLE_TASKS.get(task_name) + if task_instance is None: raise HTTPException( status_code=404, - detail=f"Task '{task_name}' not found, available tasks are {', '.join(available_tasks)}", + detail=f"Task '{task_name}' not found, available tasks are {', '.join(RUNNABLE_TASKS)}", ) - task_instance = all_tasks[task_name] if not task_instance.can_run_manually: raise HTTPException( status_code=400, detail=f"Task '{task_name}' cannot be run", ) - # Enqueued by name, like the scheduled runs, so the payload carries no - # pickled task and the job is readable by whatever version picks it up. The - # caller's arguments are nested rather than spread, so a body cannot name a - # different task than the one this route just authorized. - job = low_prio_queue.enqueue( - run_task_by_name, - kwargs={"name": task_name, "task_kwargs": task_kwargs or {}}, - job_timeout=task_instance.timeout, - result_ttl=TASK_RESULT_TTL, - meta={ - "task_name": task_instance.title, - "task_type": task_instance.task_type.value, - }, - ) + # The caller's arguments are nested rather than spread, so a body cannot + # name a different task than the one this route just authorized. + job = enqueue_task(task_name, task_kwargs=task_kwargs or {}) return { "task_name": task_instance.title, diff --git a/backend/exceptions/task_exceptions.py b/backend/exceptions/task_exceptions.py index 0ed51fd1d..85b9b7f41 100644 --- a/backend/exceptions/task_exceptions.py +++ b/backend/exceptions/task_exceptions.py @@ -1,12 +1,7 @@ -class SchedulerException(Exception): - def __init__(self, message: str): - self.message = message +class TaskNotFoundException(Exception): + def __init__(self, name: str): + self.message = f"No task is registered under the name '{name}'" super().__init__(self.message) def __repr__(self): return self.message - - -class TaskNotFoundException(SchedulerException): - def __init__(self, name: str): - super().__init__(f"No task is registered under the name '{name}'") diff --git a/backend/handler/redis_handler.py b/backend/handler/redis_handler.py index fa2761bed..cb6e3d32b 100644 --- a/backend/handler/redis_handler.py +++ b/backend/handler/redis_handler.py @@ -5,8 +5,8 @@ from typing import Any from redis import Redis from redis.asyncio import Redis as AsyncRedis -from rq import Queue -from rq.exceptions import DeserializationError, InvalidJobOperation +from rq import Queue, Worker +from rq.exceptions import DeserializationError, InvalidJobOperation, NoSuchJobError from rq.job import Job, JobStatus from config import IS_PYTEST_RUN, REDIS_URL @@ -77,17 +77,19 @@ def get_job_func_name(job: Job, fallback: str = "") -> str: return fallback -def get_job_status(job: Job) -> JobStatus | None: +def get_job_status(job: Job, refresh: bool = True) -> JobStatus | None: """Safely get the status of an RQ job, which is gone once its hash expires. Args: job: The RQ Job object to get the status of + refresh: Whether to re-read the status, rather than trust the one the + job was fetched with Returns: The job status, or None if the job no longer has one """ try: - return job.get_status() + return job.get_status(refresh=refresh) except InvalidJobOperation: return None @@ -105,3 +107,21 @@ def get_job_kwargs(job: Job) -> dict[str, Any] | None: return job.kwargs except DeserializationError: return None + + +def get_worker_current_job(worker: Worker) -> Job | None: + """Safely get the job a worker is holding. + + A worker killed mid-job keeps pointing at it until its own registration + expires, by which time the job can be gone. + + Args: + worker: The RQ Worker to read + + Returns: + The job the worker is running, or None if it has none or it is gone + """ + try: + return worker.get_current_job() + except NoSuchJobError: + return None diff --git a/backend/startup.py b/backend/startup.py index 46daecd94..afa5fa86d 100644 --- a/backend/startup.py +++ b/backend/startup.py @@ -5,12 +5,9 @@ import asyncio import sentry_sdk from opentelemetry import trace from rq.exceptions import DuplicateJobError +from rq.job import Job -from config import ( - ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP, - SENTRY_DSN, - TASK_TIMEOUT, -) +from config import ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP, SENTRY_DSN from endpoints.sockets.scan import drop_stale_scheduled_scans from handler.database import db_save_handler from handler.metadata.base_handler import ( @@ -31,11 +28,7 @@ from handler.redis_handler import ( ) from logger.logger import log from models.firmware import FIRMWARE_FIXTURES_DIR, KNOWN_BIOS_KEY -from tasks.manual.recompute_save_content_hashes import ( - recompute_save_content_hashes_task, -) -from tasks.scheduled.convert_images_to_webp import convert_images_to_webp_task -from tasks.tasks import run_task_by_name +from tasks.registry import enqueue_task from utils import get_version from utils.cache import conditionally_set_cache from utils.context import initialize_context @@ -45,25 +38,37 @@ tracer = trace.get_tracer(__name__) RECOMPUTE_SAVE_HASHES_JOB_ID = "recompute_save_content_hashes_bootstrap" CONVERT_IMAGES_TO_WEBP_JOB_ID = "convert_images_to_webp_bootstrap" -# The names these backfills are registered under, which is what the payload -# carries rather than the task itself. -RECOMPUTE_SAVE_HASHES_TASK = "recompute_save_content_hashes" -CONVERT_IMAGES_TO_WEBP_TASK = "convert_images_to_webp" + +def _enqueue_backfill(task_name: str, job_id: str) -> None: + """Hand a backfill to the low-priority worker and move on. + + A fixed id with unique=True settles it in one round trip, so two instances + starting together cannot both get past the check. + """ + try: + enqueue_task(task_name, job_id=job_id, unique=True) + log.info(f"Enqueued {task_name} on the low-priority worker") + except DuplicateJobError: + log.info( + f"{task_name} already queued or running from a previous restart; " + "skipping enqueue" + ) + except Exception: + log.exception(f"Failed to enqueue {task_name}; admins can run it manually") def _enqueue_recompute_save_hashes_if_needed() -> None: - """Backfill content_hash for saves uploaded before the path-resolution - fix. Non-blocking: a single COUNT query, then -- only if any Save rows - still have NULL content_hash -- enqueue the manual recompute task on - the low-priority RQ queue. The worker process picks it up; this - process moves on. Once the run completes, future restarts see 0 NULL - hashes and skip. Admins can still trigger the manual task explicitly.""" + """Backfill content_hash for saves uploaded before the path-resolution fix. + + A single COUNT query gates it, so a run that already completed costs nothing + on later restarts. + """ try: missing = db_save_handler.count_saves_missing_content_hash() except Exception: log.exception( - "Failed to count saves with NULL content_hash; " - "skipping auto-enqueue of recompute_save_content_hashes (admins can run it manually)" + "Failed to count saves with NULL content_hash; skipping auto-enqueue " + "of recompute_save_content_hashes (admins can run it manually)" ) return @@ -71,70 +76,22 @@ def _enqueue_recompute_save_hashes_if_needed() -> None: log.debug("All saves have content_hash; skipping recompute auto-enqueue") return - try: - # A fixed id with unique=True settles it in one round trip, so two - # instances starting together cannot both get past the check. - low_prio_queue.enqueue( - run_task_by_name, - kwargs={"name": RECOMPUTE_SAVE_HASHES_TASK}, - job_id=RECOMPUTE_SAVE_HASHES_JOB_ID, - unique=True, - job_timeout=TASK_TIMEOUT, - meta={ - "task_name": recompute_save_content_hashes_task.title, - "task_type": recompute_save_content_hashes_task.task_type.value, - }, - ) - log.info( - f"Enqueued recompute_save_content_hashes ({missing} saves with NULL content_hash); " - "running on low-priority worker" - ) - except DuplicateJobError: - log.info( - "recompute_save_content_hashes already queued or running from a " - "previous restart; skipping enqueue" - ) - except Exception: - log.exception( - "Failed to enqueue recompute_save_content_hashes; admins can run it manually" - ) + log.info(f"{missing} save(s) still have a NULL content_hash") + _enqueue_backfill("recompute_save_content_hashes", RECOMPUTE_SAVE_HASHES_JOB_ID) def _enqueue_convert_images_to_webp() -> None: """Backfill .webp covers when WebP conversion is enabled. - The frontend rewrites cover URLs to .webp as soon as the feature flag is - on, but the scheduled task only runs at its next cron time and the inline + The frontend rewrites cover URLs to .webp as soon as the feature flag is on, + but the scheduled task only runs at its next cron time and the inline conversion in the resources handler only fires for covers fetched after - enabling. Without a backfill, existing covers have no .webp sibling and - every request 404s until the cron eventually runs.""" - try: - low_prio_queue.enqueue( - run_task_by_name, - kwargs={"name": CONVERT_IMAGES_TO_WEBP_TASK}, - job_id=CONVERT_IMAGES_TO_WEBP_JOB_ID, - unique=True, - job_timeout=TASK_TIMEOUT, - meta={ - "task_name": convert_images_to_webp_task.title, - "task_type": convert_images_to_webp_task.task_type.value, - }, - ) - log.info("Enqueued convert_images_to_webp backfill on low-priority worker") - except DuplicateJobError: - log.info( - "convert_images_to_webp already queued or running from a previous " - "restart; skipping enqueue" - ) - except Exception: - log.exception( - "Failed to enqueue convert_images_to_webp; admins can run it manually" - ) + enabling, so without this every existing cover 404s until then. + """ + _enqueue_backfill("convert_images_to_webp", CONVERT_IMAGES_TO_WEBP_JOB_ID) -# Keys the rq-scheduler process used before scheduling moved onto RQ itself. -# Everything it held is either obsolete or now owned by the cron config, so it -# only has to be cleared once, and this can go a release or two from now. +# Keys the rq-scheduler process left behind, now owned by the cron config. LEGACY_SCHEDULED_JOBS_KEY = "rq:scheduler:scheduled_jobs" LEGACY_SCHEDULER_KEYS = ( LEGACY_SCHEDULED_JOBS_KEY, @@ -160,7 +117,7 @@ def _drop_legacy_scheduler_state() -> None: orphans = legacy_job_ids - queued if orphans: - redis_client.delete(*(f"rq:job:{job_id}" for job_id in orphans)) + redis_client.delete(*(Job.key_for(job_id) for job_id in orphans)) log.info( f"Cleared {len(legacy_job_ids)} job(s) left behind by the old scheduler" @@ -168,9 +125,10 @@ def _drop_legacy_scheduler_state() -> None: # The registry, the lock and the scheduler's own keys go regardless: an # old scheduler that never held a job still registered itself. - redis_client.delete(*LEGACY_SCHEDULER_KEYS) - for key in redis_client.scan_iter("rq:scheduler_instance:*"): - redis_client.delete(key) + instance_keys = list( + redis_client.scan_iter("rq:scheduler_instance:*", count=1000) + ) + redis_client.delete(*LEGACY_SCHEDULER_KEYS, *instance_keys) except Exception: log.exception("Failed to clear the old scheduler's leftovers") @@ -182,9 +140,6 @@ async def main() -> None: async with initialize_context(): log.info("Running startup tasks") - # An instance that was down for a while comes back with every rescan - # its watcher queued still waiting, and releasing them all would run the - # same library scan over and over. try: drop_stale_scheduled_scans() except Exception: diff --git a/backend/tasks/cron_config.py b/backend/tasks/cron_config.py index ea9f47236..780dcf78c 100644 --- a/backend/tasks/cron_config.py +++ b/backend/tasks/cron_config.py @@ -1,8 +1,7 @@ """The schedule `rq cron` runs, registered when that process starts. -A task is registered only when it is enabled and has a cron string, so nothing -in Redis has to be unscheduled when a deployment turns one off: the next start -simply leaves it out. +A task is registered only when it is enabled and has a cron string, so turning +one off is a restart rather than an unschedule. """ from rq import cron @@ -22,9 +21,6 @@ for name, task in SCHEDULED_TASKS.items(): kwargs={"name": name}, cron=task.cron_string, job_timeout=task.timeout, - meta={ - "task_name": task.title, - "task_type": task.task_type.value, - }, + meta=task.job_meta, ) log.info(f"Scheduled '{name}' at '{task.cron_string}'") diff --git a/backend/tasks/registry.py b/backend/tasks/registry.py index 2c2fd0aed..3483c39ce 100644 --- a/backend/tasks/registry.py +++ b/backend/tasks/registry.py @@ -1,7 +1,13 @@ """The catalog of tasks an admin can see, run, or have run on a schedule.""" -from typing import Final +from typing import Any, Final +from rq.job import Job +from rq.queue import Queue + +from config import TASK_RESULT_TTL +from exceptions.task_exceptions import TaskNotFoundException +from handler.redis_handler import low_prio_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.recompute_save_content_hashes import ( @@ -20,7 +26,7 @@ from tasks.scheduled.sync_retroachievements_progress import ( from tasks.scheduled.update_launchbox_metadata import update_launchbox_metadata_task from tasks.scheduled.update_switch_titledb import update_switch_titledb_task from tasks.sync_push_pull_task import sync_push_pull_task -from tasks.tasks import PeriodicTask, Task +from tasks.tasks import PeriodicTask, Task, run_task_by_name # The keys are the names the API and the cron schedule address a task by, and # they end up in the job payload, so they outlive any given release. Every task @@ -50,3 +56,36 @@ MANUAL_TASKS: Final[dict[str, Task]] = { def get_task(name: str) -> Task | None: """Look up a task by the name it is addressed by.""" return SCHEDULED_TASKS.get(name) or MANUAL_TASKS.get(name) + + +def enqueue_task( + name: str, + *, + queue: Queue = low_prio_queue, + task_kwargs: dict[str, Any] | None = None, + **job_options: Any, +) -> Job: + """Enqueue a registered task by name, on the queue a worker picks it up from. + + Args: + name: The key the task is registered under. + queue: Which queue to enqueue on. + task_kwargs: Forwarded to the task's ``run``, nested so that they cannot + collide with the name of the task to run. + job_options: Passed through to RQ, for a fixed job id and the like. + + Returns: + The enqueued job. + """ + task = get_task(name) + if task is None: + raise TaskNotFoundException(name) + + return queue.enqueue( + run_task_by_name, + kwargs={"name": name, "task_kwargs": task_kwargs or {}}, + job_timeout=task.timeout, + result_ttl=TASK_RESULT_TTL, + meta=task.job_meta, + **job_options, + ) diff --git a/backend/tasks/scheduled/cleanup_netplay.py b/backend/tasks/scheduled/cleanup_netplay.py index 635ae0783..cb1282e4e 100644 --- a/backend/tasks/scheduled/cleanup_netplay.py +++ b/backend/tasks/scheduled/cleanup_netplay.py @@ -12,7 +12,6 @@ class CleanupNetplayTask(PeriodicTask): enabled=True, manual_run=False, cron_string="*/30 * * * *", # Every 30 minutes - func="tasks.scheduled.cleanup_netplay.cleanup_netplay_task.run", ) async def run(self) -> None: diff --git a/backend/tasks/scheduled/cleanup_orphaned_resources.py b/backend/tasks/scheduled/cleanup_orphaned_resources.py index 3c25f99d3..b86c21652 100644 --- a/backend/tasks/scheduled/cleanup_orphaned_resources.py +++ b/backend/tasks/scheduled/cleanup_orphaned_resources.py @@ -82,7 +82,6 @@ class CleanupOrphanedResourcesTask(PeriodicTask): enabled=ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES, manual_run=True, cron_string=SCHEDULED_CLEANUP_ORPHANED_RESOURCES_CRON, - func="tasks.scheduled.cleanup_orphaned_resources.cleanup_orphaned_resources_task.run", ) @initialize_context() diff --git a/backend/tasks/scheduled/cleanup_upload_tmp.py b/backend/tasks/scheduled/cleanup_upload_tmp.py index 925329988..b6e5d8c1f 100644 --- a/backend/tasks/scheduled/cleanup_upload_tmp.py +++ b/backend/tasks/scheduled/cleanup_upload_tmp.py @@ -15,7 +15,6 @@ class CleanupUploadTmpTask(PeriodicTask): enabled=True, manual_run=False, cron_string="0 * * * *", # Every hour - func="tasks.scheduled.cleanup_upload_tmp.cleanup_upload_tmp_task.run", ) async def run(self) -> None: diff --git a/backend/tasks/scheduled/cleanup_zip_cache.py b/backend/tasks/scheduled/cleanup_zip_cache.py index f69a5d3b4..9636392b0 100644 --- a/backend/tasks/scheduled/cleanup_zip_cache.py +++ b/backend/tasks/scheduled/cleanup_zip_cache.py @@ -12,7 +12,6 @@ class CleanupZipCacheTask(PeriodicTask): enabled=True, manual_run=False, cron_string="0 4 * * *", - func="tasks.scheduled.cleanup_zip_cache.cleanup_zip_cache_task.run", ) async def run(self) -> None: diff --git a/backend/tasks/scheduled/convert_images_to_webp.py b/backend/tasks/scheduled/convert_images_to_webp.py index 9cc90345c..da44849bc 100644 --- a/backend/tasks/scheduled/convert_images_to_webp.py +++ b/backend/tasks/scheduled/convert_images_to_webp.py @@ -119,7 +119,6 @@ class ConvertImagesToWebPTask(PeriodicTask): enabled=ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP, manual_run=True, cron_string=SCHEDULED_CONVERT_IMAGES_TO_WEBP_CRON, - func="tasks.scheduled.convert_images_to_webp.convert_images_to_webp_task.run", ) self.resources_path = Path(RESOURCES_BASE_PATH) self.converter = ImageConverter() diff --git a/backend/tasks/scheduled/scan_library.py b/backend/tasks/scheduled/scan_library.py index b851d85a3..81e7add1c 100644 --- a/backend/tasks/scheduled/scan_library.py +++ b/backend/tasks/scheduled/scan_library.py @@ -35,7 +35,6 @@ class ScanLibraryTask(PeriodicTask): enabled=ENABLE_SCHEDULED_RESCAN, manual_run=False, cron_string=SCHEDULED_RESCAN_CRON, - func="tasks.scheduled.scan_library.scan_library_task.run", ) async def run(self) -> dict[str, str]: diff --git a/backend/tasks/scheduled/sync_retroachievements_progress.py b/backend/tasks/scheduled/sync_retroachievements_progress.py index a3fc3afc3..269ecf362 100644 --- a/backend/tasks/scheduled/sync_retroachievements_progress.py +++ b/backend/tasks/scheduled/sync_retroachievements_progress.py @@ -94,7 +94,6 @@ class SyncRetroAchievementsProgressTask(PeriodicTask): enabled=ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC, cron_string=SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON, manual_run=False, - func="tasks.scheduled.sync_retroachievements_progress.sync_retroachievements_progress_task.run", ) @initialize_context() diff --git a/backend/tasks/scheduled/update_launchbox_metadata.py b/backend/tasks/scheduled/update_launchbox_metadata.py index cbf957fb9..a1314a168 100644 --- a/backend/tasks/scheduled/update_launchbox_metadata.py +++ b/backend/tasks/scheduled/update_launchbox_metadata.py @@ -102,7 +102,6 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): enabled=ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA, cron_string=SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON, manual_run=True, - func="tasks.scheduled.update_launchbox_metadata.update_launchbox_metadata_task.run", url="https://gamesdb.launchbox-app.com/Metadata.zip", timeout=LAUNCHBOX_TASK_TIMEOUT, ) diff --git a/backend/tasks/scheduled/update_switch_titledb.py b/backend/tasks/scheduled/update_switch_titledb.py index bf48adb9e..48142f697 100644 --- a/backend/tasks/scheduled/update_switch_titledb.py +++ b/backend/tasks/scheduled/update_switch_titledb.py @@ -26,7 +26,6 @@ class UpdateSwitchTitleDBTask(RemoteFilePullTask): enabled=ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB, cron_string=SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON, manual_run=True, - func="tasks.scheduled.update_switch_titledb.update_switch_titledb_task.run", url="https://raw.githubusercontent.com/blawar/titledb/master/US.en.json", ) diff --git a/backend/tasks/sync_push_pull_task.py b/backend/tasks/sync_push_pull_task.py index 1600f9c96..1d43f860e 100644 --- a/backend/tasks/sync_push_pull_task.py +++ b/backend/tasks/sync_push_pull_task.py @@ -425,7 +425,6 @@ class SyncPushPullTask(PeriodicTask): task_type=TaskType.SYNC, enabled=ENABLE_SYNC_PUSH_PULL, cron_string=SYNC_PUSH_PULL_CRON, - func="tasks.sync_push_pull_task.run_push_pull_sync", ) async def run(self, *args: Any, **kwargs: Any) -> Any: diff --git a/backend/tasks/tasks.py b/backend/tasks/tasks.py index 0410e2889..05c5ccf2b 100644 --- a/backend/tasks/tasks.py +++ b/backend/tasks/tasks.py @@ -95,6 +95,11 @@ class Task(ABC): """Whether an admin can trigger this task on demand.""" return self.manual_run and self.enabled + @property + def job_meta(self) -> dict[str, Any]: + """What a job of this task carries so the API can describe it.""" + return {"task_name": self.title, "task_type": self.task_type.value} + @abstractmethod async def run(self, *args: Any, **kwargs: Any) -> Any: ... @@ -102,10 +107,6 @@ class Task(ABC): class PeriodicTask(Task, ABC): """Base class for tasks the cron scheduler runs on a schedule.""" - def __init__(self, *args: Any, func: str, **kwargs: Any): - super().__init__(*args, **kwargs) - self.func = func - class RemoteFilePullTask(PeriodicTask, ABC): """Base class for tasks that pull files from a remote URL.""" diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index 4ff1164bb..ec03c021b 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -1729,18 +1729,33 @@ def patch_scan_jobs( else: worker.get_current_job.return_value = running mocker.patch.object(scan_module.Worker, "all", return_value=[worker]) + + queued_jobs = list(high_queued) + list(low_queued) + scheduled_jobs = list(scheduled) mocker.patch.object( - scan_module.high_prio_queue, "get_jobs", return_value=list(high_queued) + scan_module.high_prio_queue, + "get_job_ids", + return_value=[job.id for job in high_queued], ) mocker.patch.object( - scan_module.low_prio_queue, "get_jobs", return_value=list(low_queued) + scan_module.low_prio_queue, + "get_job_ids", + return_value=[job.id for job in low_queued], ) - scheduled_jobs = list(scheduled) registry = MagicMock() registry.get_job_ids.return_value = [job.id for job in scheduled_jobs] + registry.get_jobs_to_schedule.return_value = [] mocker.patch.object(scan_module, "_scheduled_scan_registry", return_value=registry) - mocker.patch.object(scan_module.Job, "fetch_many", return_value=scheduled_jobs) + + # Both the queue and the registry lookups fetch by id, so the stub has to + # answer for whichever ids it is handed. + by_id = {job.id: job for job in queued_jobs + scheduled_jobs} + mocker.patch.object( + scan_module.Job, + "fetch_many", + side_effect=lambda job_ids, **kwargs: [by_id.get(i) for i in job_ids], + ) return registry @@ -2056,23 +2071,31 @@ class TestDropStaleScheduledScans: def test_drops_a_scan_long_past_due(self, mocker): job = make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.SCHEDULED) registry = patch_scan_jobs(mocker, scheduled=[job]) - registry.get_scheduled_time.return_value = self._due(2) + registry.get_jobs_to_schedule.return_value = [job.id] assert scan_module.drop_stale_scheduled_scans() == 1 job.cancel.assert_called_once() + def test_asks_the_registry_only_for_what_is_past_due(self, mocker): + registry = patch_scan_jobs(mocker) + + scan_module.drop_stale_scheduled_scans() + + cutoff = registry.get_jobs_to_schedule.call_args.args[0] + expected = datetime.now(timezone.utc) - scan_module.STALE_SCHEDULED_SCAN_AGE + assert abs(cutoff - expected.timestamp()) < 5 + def test_keeps_a_scan_still_waiting_out_its_delay(self, mocker): job = make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.SCHEDULED) - registry = patch_scan_jobs(mocker, scheduled=[job]) - registry.get_scheduled_time.return_value = self._due(-1) + patch_scan_jobs(mocker, scheduled=[job]) assert scan_module.drop_stale_scheduled_scans() == 0 job.cancel.assert_not_called() def test_ignores_a_scan_that_left_the_registry(self, mocker): job = make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.SCHEDULED) - registry = patch_scan_jobs(mocker, scheduled=[job]) - registry.get_scheduled_time.side_effect = NoSuchJobError + registry = patch_scan_jobs(mocker) + registry.get_jobs_to_schedule.return_value = [job.id] assert scan_module.drop_stale_scheduled_scans() == 0 job.cancel.assert_not_called() @@ -2080,7 +2103,7 @@ class TestDropStaleScheduledScans: def test_leaves_jobs_that_are_not_scans_alone(self, mocker): job = make_job(CLEANUP_FUNC, status=JobStatus.SCHEDULED) registry = patch_scan_jobs(mocker, scheduled=[job]) - registry.get_scheduled_time.return_value = self._due(2) + registry.get_jobs_to_schedule.return_value = [job.id] assert scan_module.drop_stale_scheduled_scans() == 0 job.cancel.assert_not_called() diff --git a/backend/tests/endpoints/test_tasks.py b/backend/tests/endpoints/test_tasks.py index 03097dde7..5776a2654 100644 --- a/backend/tests/endpoints/test_tasks.py +++ b/backend/tests/endpoints/test_tasks.py @@ -96,9 +96,8 @@ class TestListTasks: ), }, ) - @patch("endpoints.tasks.VISIBLE_SCHEDULED_TASKS", ("test_scheduled",)) @patch( - "endpoints.tasks.SCHEDULED_TASKS", + "endpoints.tasks.VISIBLE_SCHEDULED_TASKS", { "test_scheduled": Mock( spec=Task, @@ -160,7 +159,7 @@ class TestListTasks: @patch("endpoints.tasks.ENABLE_RESCAN_ON_FILESYSTEM_CHANGE", False) @patch("endpoints.tasks.RESCAN_ON_FILESYSTEM_CHANGE_DELAY", 10) @patch("endpoints.tasks.MANUAL_TASKS", {}) - @patch("endpoints.tasks.VISIBLE_SCHEDULED_TASKS", ()) + @patch("endpoints.tasks.VISIBLE_SCHEDULED_TASKS", {}) def test_list_tasks_empty(self, client, access_token): """Test listing tasks when no tasks are available""" response = client.get( @@ -220,9 +219,9 @@ class TestListTasks: class TestRunSingleTask: """Test suite for the run_single_task endpoint""" - @patch("endpoints.tasks.low_prio_queue.enqueue", return_value=create_mock_job()) + @patch("endpoints.tasks.enqueue_task", return_value=create_mock_job()) @patch( - "endpoints.tasks.MANUAL_TASKS", + "endpoints.tasks.RUNNABLE_TASKS", { "test_task": Mock( spec=Task, @@ -237,8 +236,7 @@ class TestRunSingleTask: ), }, ) - @patch("endpoints.tasks.VISIBLE_SCHEDULED_TASKS", ()) - def test_run_single_task_success(self, mock_queue, client, access_token): + def test_run_single_task_success(self, mock_enqueue, client, access_token): """Test successful running of a single task""" response = client.post( "/api/tasks/run/test_task", @@ -254,10 +252,9 @@ class TestRunSingleTask: assert "created_at" in data assert "enqueued_at" in data - mock_queue.assert_called_once() + mock_enqueue.assert_called_once() - @patch("endpoints.tasks.MANUAL_TASKS", {}) - @patch("endpoints.tasks.VISIBLE_SCHEDULED_TASKS", ()) + @patch("endpoints.tasks.RUNNABLE_TASKS", {}) def test_run_single_task_not_found(self, client, access_token): """Test running a non-existent task""" response = client.post( @@ -269,9 +266,9 @@ class TestRunSingleTask: data = response.json() assert "not found" in data["detail"].lower() - @patch("endpoints.tasks.low_prio_queue") + @patch("endpoints.tasks.enqueue_task") @patch( - "endpoints.tasks.MANUAL_TASKS", + "endpoints.tasks.RUNNABLE_TASKS", { "disabled_task": Mock( spec=Task, @@ -286,8 +283,7 @@ class TestRunSingleTask: ), }, ) - @patch("endpoints.tasks.VISIBLE_SCHEDULED_TASKS", ()) - def test_run_single_task_disabled(self, mock_queue, client, access_token): + def test_run_single_task_disabled(self, mock_enqueue, client, access_token): """Test running a disabled task""" response = client.post( "/api/tasks/run/disabled_task", @@ -298,9 +294,9 @@ class TestRunSingleTask: data = response.json() assert "cannot be run" in data["detail"].lower() - @patch("endpoints.tasks.low_prio_queue") + @patch("endpoints.tasks.enqueue_task") @patch( - "endpoints.tasks.MANUAL_TASKS", + "endpoints.tasks.RUNNABLE_TASKS", { "non_manual_task": Mock( spec=Task, @@ -315,8 +311,7 @@ class TestRunSingleTask: ), }, ) - @patch("endpoints.tasks.VISIBLE_SCHEDULED_TASKS", ()) - def test_run_single_task_non_manual(self, mock_queue, client, access_token): + def test_run_single_task_non_manual(self, mock_enqueue, client, access_token): """Test running a task that cannot be run manually""" response = client.post( "/api/tasks/run/non_manual_task", @@ -523,7 +518,7 @@ class TestTaskInfoBuilding: ), }, ): - with patch("endpoints.tasks.VISIBLE_SCHEDULED_TASKS", ()): + with patch("endpoints.tasks.VISIBLE_SCHEDULED_TASKS", {}): response = client.get( "/api/tasks", headers={"Authorization": f"Bearer {access_token}"} ) @@ -537,11 +532,8 @@ class TestIntegration: @patch("endpoints.tasks.ENABLE_RESCAN_ON_FILESYSTEM_CHANGE", True) @patch("endpoints.tasks.RESCAN_ON_FILESYSTEM_CHANGE_DELAY", 5) - @patch( - "endpoints.tasks.low_prio_queue.enqueue", - return_value=create_mock_job(), - ) - def test_full_workflow(self, mock_queue, client, access_token): + @patch("endpoints.tasks.enqueue_task", return_value=create_mock_job()) + def test_full_workflow(self, mock_enqueue, client, access_token): """Test a complete workflow: list tasks, then run a specific task""" # First, list all tasks list_response = client.get( @@ -551,7 +543,7 @@ class TestIntegration: # Then run a specific task (if any exist) with patch( - "endpoints.tasks.MANUAL_TASKS", + "endpoints.tasks.RUNNABLE_TASKS", { "workflow_task": Mock( spec=Task, @@ -566,13 +558,12 @@ class TestIntegration: ), }, ): - with patch("endpoints.tasks.VISIBLE_SCHEDULED_TASKS", ()): - run_response = client.post( - "/api/tasks/run/workflow_task", - headers={"Authorization": f"Bearer {access_token}"}, - ) - assert run_response.status_code == status.HTTP_200_OK - assert mock_queue.called + run_response = client.post( + "/api/tasks/run/workflow_task", + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert run_response.status_code == status.HTTP_200_OK + assert mock_enqueue.called def test_error_handling(self, client, access_token): """Test error handling for various scenarios""" @@ -587,9 +578,9 @@ class TestIntegration: class TestRunSingleTaskArgumentHandling: """A request body must not be able to choose which task runs.""" - @patch("endpoints.tasks.low_prio_queue.enqueue", return_value=create_mock_job()) + @patch("endpoints.tasks.enqueue_task", return_value=create_mock_job()) @patch( - "endpoints.tasks.MANUAL_TASKS", + "endpoints.tasks.RUNNABLE_TASKS", { "allowed_task": Mock( spec=Task, @@ -603,7 +594,6 @@ class TestRunSingleTaskArgumentHandling: ), }, ) - @patch("endpoints.tasks.VISIBLE_SCHEDULED_TASKS", ()) def test_body_cannot_override_the_task_name( self, mock_enqueue, client, access_token ): @@ -614,7 +604,7 @@ class TestRunSingleTaskArgumentHandling: ) assert response.status_code == status.HTTP_200_OK - assert mock_enqueue.call_args.kwargs["kwargs"] == { - "name": "allowed_task", - "task_kwargs": {"name": "sync_push_pull"}, + assert mock_enqueue.call_args.args == ("allowed_task",) + assert mock_enqueue.call_args.kwargs["task_kwargs"] == { + "name": "sync_push_pull" } diff --git a/backend/tests/handler/test_redis_handler.py b/backend/tests/handler/test_redis_handler.py index 2a55b38cc..6d9c3147e 100644 --- a/backend/tests/handler/test_redis_handler.py +++ b/backend/tests/handler/test_redis_handler.py @@ -1,9 +1,15 @@ from unittest.mock import MagicMock, PropertyMock -from rq.exceptions import DeserializationError, InvalidJobOperation +from rq import Worker +from rq.exceptions import DeserializationError, InvalidJobOperation, NoSuchJobError from rq.job import Job, JobStatus -from handler.redis_handler import get_job_func_name, get_job_kwargs, get_job_status +from handler.redis_handler import ( + get_job_func_name, + get_job_kwargs, + get_job_status, + get_worker_current_job, +) def make_job() -> MagicMock: @@ -69,3 +75,24 @@ class TestGetJobStatus: job.get_status.side_effect = InvalidJobOperation assert get_job_status(job) is None + + +class TestGetWorkerCurrentJob: + @staticmethod + def _worker(**kwargs) -> MagicMock: + worker = MagicMock(spec=Worker) + worker.get_current_job.configure_mock(**kwargs) + return worker + + def test_returns_the_job_the_worker_is_holding(self): + job = make_job() + + assert get_worker_current_job(self._worker(return_value=job)) is job + + def test_returns_none_when_the_worker_is_idle(self): + assert get_worker_current_job(self._worker(return_value=None)) is None + + def test_returns_none_when_the_job_outlived_by_its_worker_is_gone(self): + worker = self._worker(side_effect=NoSuchJobError) + + assert get_worker_current_job(worker) is None diff --git a/backend/tests/tasks/test_cleanup_orphaned_resources.py b/backend/tests/tasks/test_cleanup_orphaned_resources.py index bbab91496..adf194110 100644 --- a/backend/tests/tasks/test_cleanup_orphaned_resources.py +++ b/backend/tests/tasks/test_cleanup_orphaned_resources.py @@ -13,12 +13,6 @@ class TestCleanupOrphanedResourcesTask: def task(self): return CleanupOrphanedResourcesTask() - def test_func_points_at_scheduled_module(self, task): - assert ( - task.func - == "tasks.scheduled.cleanup_orphaned_resources.cleanup_orphaned_resources_task.run" - ) - def test_disabled_by_default(self, task): # The run-task endpoint rejects a task unless both flags are set, so a # disabled schedule also means no manual runs. diff --git a/backend/tests/tasks/test_cleanup_upload_tmp.py b/backend/tests/tasks/test_cleanup_upload_tmp.py index 2a833fd31..2992ca7d4 100644 --- a/backend/tests/tasks/test_cleanup_upload_tmp.py +++ b/backend/tests/tasks/test_cleanup_upload_tmp.py @@ -12,10 +12,6 @@ class TestCleanupUploadTmpTask: def test_init(self, task): """Test task initialization""" - assert ( - task.func - == "tasks.scheduled.cleanup_upload_tmp.cleanup_upload_tmp_task.run" - ) assert task.enabled is True assert task.cron_string == "0 * * * *" diff --git a/backend/tests/tasks/test_cleanup_zip_cache.py b/backend/tests/tasks/test_cleanup_zip_cache.py index c5cdf637e..463bb6713 100644 --- a/backend/tests/tasks/test_cleanup_zip_cache.py +++ b/backend/tests/tasks/test_cleanup_zip_cache.py @@ -6,7 +6,6 @@ class TestCleanupZipCacheTask: task = CleanupZipCacheTask() assert task.enabled is True assert task.cron_string == "0 4 * * *" - assert "cleanup_zip_cache" in task.func async def test_run_calls_cleanup(self, mocker): task = CleanupZipCacheTask() diff --git a/backend/tests/tasks/test_registry.py b/backend/tests/tasks/test_registry.py index 4a3f98b6e..0faf9287a 100644 --- a/backend/tests/tasks/test_registry.py +++ b/backend/tests/tasks/test_registry.py @@ -1,7 +1,9 @@ import pytest -from tasks.registry import MANUAL_TASKS, SCHEDULED_TASKS, get_task -from tasks.tasks import PeriodicTask +from config import TASK_RESULT_TTL +from exceptions.task_exceptions import TaskNotFoundException +from tasks.registry import MANUAL_TASKS, SCHEDULED_TASKS, enqueue_task, get_task +from tasks.tasks import PeriodicTask, run_task_by_name class TestRegistry: @@ -20,3 +22,44 @@ class TestRegistry: def test_an_unknown_name_resolves_to_nothing(self): assert get_task("no_such_task") is None + + +class TestEnqueueTask: + """Every enqueue goes through here, so the payload is built in one place.""" + + @pytest.fixture + def queue(self, mocker): + return mocker.MagicMock() + + def test_the_payload_carries_the_name_and_the_task_metadata(self, queue): + enqueue_task("cleanup_zip_cache", queue=queue) + + args, kwargs = queue.enqueue.call_args + task = SCHEDULED_TASKS["cleanup_zip_cache"] + assert args[0] is run_task_by_name + assert kwargs["kwargs"] == {"name": "cleanup_zip_cache", "task_kwargs": {}} + assert kwargs["job_timeout"] == task.timeout + assert kwargs["result_ttl"] == TASK_RESULT_TTL + assert kwargs["meta"] == task.job_meta + + def test_caller_arguments_are_nested_under_the_name(self, queue): + enqueue_task("cleanup_missing_roms", queue=queue, task_kwargs={"dry_run": True}) + + kwargs = queue.enqueue.call_args.kwargs["kwargs"] + assert kwargs == { + "name": "cleanup_missing_roms", + "task_kwargs": {"dry_run": True}, + } + + def test_job_options_reach_rq(self, queue): + enqueue_task("cleanup_zip_cache", queue=queue, job_id="fixed", unique=True) + + kwargs = queue.enqueue.call_args.kwargs + assert kwargs["job_id"] == "fixed" + assert kwargs["unique"] is True + + def test_an_unknown_name_is_refused_before_it_reaches_redis(self, queue): + with pytest.raises(TaskNotFoundException): + enqueue_task("no_such_task", queue=queue) + + queue.enqueue.assert_not_called() diff --git a/backend/tests/tasks/test_scan_library.py b/backend/tests/tasks/test_scan_library.py index aefa637a4..deac631b4 100644 --- a/backend/tests/tasks/test_scan_library.py +++ b/backend/tests/tasks/test_scan_library.py @@ -28,7 +28,6 @@ class TestScanLibraryTask: def test_init(self, task): """Test task initialization""" - assert task.func == "tasks.scheduled.scan_library.scan_library_task.run" assert task.description == "Rescans the entire library" async def test_run_enabled(self, task, mocker): @@ -85,7 +84,3 @@ class TestScanLibraryTask: def test_task_instance(self): """Test that the module-level task instance is created correctly""" assert isinstance(scan_library_task, ScanLibraryTask) - assert ( - scan_library_task.func - == "tasks.scheduled.scan_library.scan_library_task.run" - ) diff --git a/backend/tests/tasks/test_sync_push_pull.py b/backend/tests/tasks/test_sync_push_pull.py index 1cd5e7cee..837c33de1 100644 --- a/backend/tests/tasks/test_sync_push_pull.py +++ b/backend/tests/tasks/test_sync_push_pull.py @@ -30,7 +30,6 @@ class TestSyncPushPullTaskInit: assert task.title == "Push-Pull Sync" assert task.description == "Sync saves with devices via SSH/SFTP" assert task.task_type == TaskType.SYNC - assert task.func == "tasks.sync_push_pull_task.run_push_pull_sync" def test_is_periodic_task(self, task: SyncPushPullTask): assert isinstance(task, PeriodicTask) diff --git a/backend/tests/tasks/test_sync_retroachievements_progress.py b/backend/tests/tasks/test_sync_retroachievements_progress.py index 217366dab..5a381705f 100644 --- a/backend/tests/tasks/test_sync_retroachievements_progress.py +++ b/backend/tests/tasks/test_sync_retroachievements_progress.py @@ -66,10 +66,6 @@ class TestSyncRetroAchievementsProgressTask: def test_task_initialization(self, task): """Test task initialization with correct parameters.""" - assert ( - task.func - == "tasks.scheduled.sync_retroachievements_progress.sync_retroachievements_progress_task.run" - ) assert task.description == "Updates RetroAchievements progress for all users" async def test_run_when_retroachievements_api_disabled(self, task, mocker): diff --git a/backend/tests/tasks/test_task_func_paths.py b/backend/tests/tasks/test_task_func_paths.py index 3c1bdfcd3..e532eb76a 100644 --- a/backend/tests/tasks/test_task_func_paths.py +++ b/backend/tests/tasks/test_task_func_paths.py @@ -1,34 +1,25 @@ import os -import pkgutil import subprocess import sys -from importlib import import_module from pathlib import Path import pytest -import tasks -from tasks.tasks import PeriodicTask - BACKEND_ROOT = Path(__file__).resolve().parents[2] - -def _periodic_task_funcs() -> list[str]: - funcs = set() - for module_info in pkgutil.walk_packages(tasks.__path__, prefix="tasks."): - module = import_module(module_info.name) - for value in vars(module).values(): - if isinstance(value, PeriodicTask): - funcs.add(value.func) - return sorted(funcs) +# The only two callables a job payload names. Everything else runs through +# run_task_by_name, which resolves it from the registry. +JOB_FUNC_PATHS = ( + "tasks.tasks.run_task_by_name", + "endpoints.sockets.scan.scan_platforms", +) -@pytest.mark.parametrize("func", _periodic_task_funcs()) +@pytest.mark.parametrize("func", JOB_FUNC_PATHS) def test_task_func_resolves_in_a_fresh_interpreter(func): """The RQ worker resolves a job by importing its func path into a process - where the task module is the first application module imported. An import - cycle that stays hidden in the web process breaks the job there, so resolve - each func the way the worker does, in a clean interpreter.""" + where that module is the first application module imported. An import cycle + that stays hidden in the web process breaks the job there.""" result = subprocess.run( [ sys.executable, diff --git a/backend/tests/tasks/test_tasks.py b/backend/tests/tasks/test_tasks.py index f66c09ded..181fde526 100644 --- a/backend/tests/tasks/test_tasks.py +++ b/backend/tests/tasks/test_tasks.py @@ -18,7 +18,6 @@ class TestPeriodicTask: @pytest.fixture def task(self): return ConcretePeriodicTask( - func="test.function", title="Test Task", description="test task", task_type=TaskType.GENERIC, @@ -29,7 +28,6 @@ class TestPeriodicTask: @pytest.fixture def disabled_task(self): return ConcretePeriodicTask( - func="test.disabled.function", title="Disabled Task", description="disabled task", task_type=TaskType.GENERIC, @@ -39,7 +37,6 @@ class TestPeriodicTask: def test_init(self, task): """Test task initialization""" - assert task.func == "test.function" assert task.title == "Test Task" assert task.description == "test task" assert task.enabled is True @@ -55,7 +52,6 @@ class TestRemoteFilePullTask: @pytest.fixture def task(self): return RemoteFilePullTask( - func="test.remote.function", title="Remote Test Task", task_type=TaskType.UPDATE, description="remote test task", @@ -67,7 +63,6 @@ class TestRemoteFilePullTask: @pytest.fixture def disabled_task(self): return RemoteFilePullTask( - func="test.remote.disabled.function", title="Disabled Remote Task", task_type=TaskType.UPDATE, description="disabled remote task", @@ -77,7 +72,6 @@ class TestRemoteFilePullTask: def test_init(self, task): """Test RemoteFilePullTask initialization""" - assert task.func == "test.remote.function" assert task.task_type == TaskType.UPDATE assert task.description == "remote test task" assert task.enabled is True diff --git a/backend/tests/tasks/test_update_launchbox_metadata.py b/backend/tests/tasks/test_update_launchbox_metadata.py index 1d3d177e5..190aadcd6 100644 --- a/backend/tests/tasks/test_update_launchbox_metadata.py +++ b/backend/tests/tasks/test_update_launchbox_metadata.py @@ -52,10 +52,6 @@ class TestUpdateLaunchboxMetadataTask: def test_task_initialization(self, task): """Test task initialization with correct parameters""" - assert ( - task.func - == "tasks.scheduled.update_launchbox_metadata.update_launchbox_metadata_task.run" - ) assert task.description == "Updates the LaunchBox metadata store" assert task.url == "https://gamesdb.launchbox-app.com/Metadata.zip" diff --git a/backend/tests/tasks/test_update_switch_titledb.py b/backend/tests/tasks/test_update_switch_titledb.py index 868571c3d..8f5283f7b 100644 --- a/backend/tests/tasks/test_update_switch_titledb.py +++ b/backend/tests/tasks/test_update_switch_titledb.py @@ -54,10 +54,6 @@ class TestUpdateSwitchTitleDBTask: def test_init(self, task): """Test task initialization""" - assert ( - task.func - == "tasks.scheduled.update_switch_titledb.update_switch_titledb_task.run" - ) assert task.description == "Updates the Nintendo Switch TitleDB file" assert ( task.url diff --git a/backend/tests/test_startup.py b/backend/tests/test_startup.py index a4dcacea0..6d049207a 100644 --- a/backend/tests/test_startup.py +++ b/backend/tests/test_startup.py @@ -8,143 +8,91 @@ from rq.job import JOB_ID_PATTERN from tasks.registry import get_task -def test_enqueue_recompute_skips_when_no_missing_hashes(mocker): +@pytest.fixture +def enqueue_task(mocker): + return mocker.patch.object(startup, "enqueue_task") + + +def test_enqueue_recompute_skips_when_no_missing_hashes(mocker, enqueue_task): """Saves all have content_hash -> no enqueue.""" mocker.patch.object( startup.db_save_handler, "count_saves_missing_content_hash", return_value=0 ) - enqueue = mocker.patch.object(startup.low_prio_queue, "enqueue") startup._enqueue_recompute_save_hashes_if_needed() - enqueue.assert_not_called() + enqueue_task.assert_not_called() -def test_enqueue_recompute_fires_when_missing_hashes_present(mocker): +def test_enqueue_recompute_fires_when_missing_hashes_present(mocker, enqueue_task): """At least one Save row has NULL content_hash -> enqueue exactly once.""" mocker.patch.object( startup.db_save_handler, "count_saves_missing_content_hash", return_value=42 ) - enqueue = mocker.patch.object(startup.low_prio_queue, "enqueue") startup._enqueue_recompute_save_hashes_if_needed() - enqueue.assert_called_once() - args, kwargs = enqueue.call_args - # Enqueued by name, so the payload survives the code moving underneath it - assert args[0] is startup.run_task_by_name - assert kwargs["kwargs"] == {"name": startup.RECOMPUTE_SAVE_HASHES_TASK} - # RQ settles the duplicate check and the enqueue in one round trip - assert kwargs["unique"] is True - # Sanity-check the meta payload routes correctly in the task list UI - assert kwargs["meta"]["task_name"] == ( - startup.recompute_save_content_hashes_task.title + enqueue_task.assert_called_once_with( + "recompute_save_content_hashes", + job_id=startup.RECOMPUTE_SAVE_HASHES_JOB_ID, + # RQ settles the duplicate check and the enqueue in one round trip + unique=True, ) - assert kwargs["meta"]["task_type"] == ( - startup.recompute_save_content_hashes_task.task_type.value - ) - # Job timeout must be passed; otherwise long-running recomputes get killed - # by RQ's default short timeout on very large libraries. - assert kwargs["job_timeout"] == startup.TASK_TIMEOUT - assert kwargs["job_id"] == startup.RECOMPUTE_SAVE_HASHES_JOB_ID -def test_recompute_job_id_is_valid_rq_id(): +def test_enqueue_convert_webp_fires_when_not_queued(enqueue_task): + """No in-flight bootstrap job -> enqueue the backfill exactly once.""" + startup._enqueue_convert_images_to_webp() + + enqueue_task.assert_called_once_with( + "convert_images_to_webp", + job_id=startup.CONVERT_IMAGES_TO_WEBP_JOB_ID, + unique=True, + ) + + +@pytest.mark.parametrize( + "job_id", + (startup.RECOMPUTE_SAVE_HASHES_JOB_ID, startup.CONVERT_IMAGES_TO_WEBP_JOB_ID), +) +def test_backfill_job_ids_are_valid_rq_ids(job_id): """RQ rejects any job_id not matching [A-Za-z0-9_-]+ (ValueError in set_id), - which the broad except here would swallow -> backfill silently never enqueues. - A colon was the original culprit; assert the full contract, not just that.""" - assert JOB_ID_PATTERN.fullmatch(startup.RECOMPUTE_SAVE_HASHES_JOB_ID) + which the broad except here would swallow -> backfill silently never + enqueues. A colon was the original culprit.""" + assert JOB_ID_PATTERN.fullmatch(job_id) -def test_enqueue_recompute_tolerates_an_in_flight_job(mocker): - """An in-flight job from a previous restart -> RQ refuses, startup carries on.""" +def test_both_backfills_name_a_registered_task(): + """The name in the payload is all the runner gets, so it has to resolve.""" + assert get_task("recompute_save_content_hashes") is not None + assert get_task("convert_images_to_webp") is not None + + +@pytest.mark.parametrize( + "error", (DuplicateJobError("exists"), RuntimeError("redis gone")) +) +def test_a_failed_backfill_enqueue_does_not_crash_startup(mocker, error): + """An in-flight job from a previous restart, or a Redis outage, is survivable.""" mocker.patch.object( startup.db_save_handler, "count_saves_missing_content_hash", return_value=10 ) - mocker.patch.object( - startup.low_prio_queue, "enqueue", side_effect=DuplicateJobError("exists") - ) + mocker.patch.object(startup, "enqueue_task", side_effect=error) startup._enqueue_recompute_save_hashes_if_needed() + startup._enqueue_convert_images_to_webp() -def test_both_backfills_name_a_registered_task(mocker): - """The name in the payload is all the runner gets, so it has to resolve.""" - assert get_task(startup.RECOMPUTE_SAVE_HASHES_TASK) is ( - startup.recompute_save_content_hashes_task - ) - assert get_task(startup.CONVERT_IMAGES_TO_WEBP_TASK) is ( - startup.convert_images_to_webp_task - ) - - -def test_enqueue_recompute_swallows_count_error(mocker): +def test_enqueue_recompute_swallows_count_error(mocker, enqueue_task): """A failed COUNT query must not crash startup.""" mocker.patch.object( startup.db_save_handler, "count_saves_missing_content_hash", side_effect=RuntimeError("db gone"), ) - enqueue = mocker.patch.object(startup.low_prio_queue, "enqueue") startup._enqueue_recompute_save_hashes_if_needed() - enqueue.assert_not_called() - - -def test_enqueue_recompute_swallows_enqueue_error(mocker): - """A failed enqueue must not crash startup.""" - mocker.patch.object( - startup.db_save_handler, "count_saves_missing_content_hash", return_value=5 - ) - mocker.patch.object( - startup.low_prio_queue, "enqueue", side_effect=RuntimeError("redis gone") - ) - - startup._enqueue_recompute_save_hashes_if_needed() - - -def test_enqueue_convert_webp_fires_when_not_queued(mocker): - """No in-flight bootstrap job -> enqueue the backfill exactly once.""" - enqueue = mocker.patch.object(startup.low_prio_queue, "enqueue") - - startup._enqueue_convert_images_to_webp() - - enqueue.assert_called_once() - args, kwargs = enqueue.call_args - assert args[0] is startup.run_task_by_name - assert kwargs["kwargs"] == {"name": startup.CONVERT_IMAGES_TO_WEBP_TASK} - assert kwargs["unique"] is True - assert kwargs["meta"]["task_name"] == startup.convert_images_to_webp_task.title - assert kwargs["meta"]["task_type"] == ( - startup.convert_images_to_webp_task.task_type.value - ) - assert kwargs["job_timeout"] == startup.TASK_TIMEOUT - assert kwargs["job_id"] == startup.CONVERT_IMAGES_TO_WEBP_JOB_ID - - -def test_convert_webp_job_id_is_valid_rq_id(): - """An invalid job_id raises in set_id, which the broad except swallows -> - backfill silently never enqueues. Assert the id matches RQ's contract.""" - assert JOB_ID_PATTERN.fullmatch(startup.CONVERT_IMAGES_TO_WEBP_JOB_ID) - - -def test_enqueue_convert_webp_tolerates_an_in_flight_job(mocker): - """An in-flight job from a previous restart -> RQ refuses, startup carries on.""" - mocker.patch.object( - startup.low_prio_queue, "enqueue", side_effect=DuplicateJobError("exists") - ) - - startup._enqueue_convert_images_to_webp() - - -def test_enqueue_convert_webp_swallows_enqueue_error(mocker): - """A failed enqueue must not crash startup.""" - mocker.patch.object( - startup.low_prio_queue, "enqueue", side_effect=RuntimeError("redis gone") - ) - - startup._enqueue_convert_images_to_webp() + enqueue_task.assert_not_called() class TestDropLegacySchedulerState: diff --git a/backend/watcher.py b/backend/watcher.py index fa442f232..c1861aa00 100644 --- a/backend/watcher.py +++ b/backend/watcher.py @@ -21,6 +21,7 @@ from config import ( from config.config_manager import config_manager as cm from endpoints.sockets.scan import ( get_pending_scan_jobs, + scan_job_meta, scan_platforms, ) from handler.database import db_platform_handler @@ -47,7 +48,6 @@ from handler.scan_handler import MetadataSource, ScanType from logger.formatter import CYAN from logger.formatter import highlight as hl from logger.logger import log -from tasks.tasks import TaskType from utils import get_version sentry_sdk.init( @@ -213,22 +213,22 @@ def process_changes(changes: Sequence[Change]) -> None: time_delta = timedelta(minutes=RESCAN_ON_FILESYSTEM_CHANGE_DELAY) rescan_in_msg = f"rescanning in {hl(str(RESCAN_ON_FILESYSTEM_CHANGE_DELAY), color=CYAN)} minutes." - # Any change to a platform directory should trigger a full rescan - if changes_platform_directory: - log.info(f"Platform directory changed, {rescan_in_msg}") + def schedule_rescan(platform_ids: list[int], scan_type: ScanType) -> None: low_prio_queue.enqueue_in( time_delta, scan_platforms, - platform_ids=[], + platform_ids=platform_ids, metadata_sources=metadata_sources, - scan_type=ScanType.UPDATE, + scan_type=scan_type, job_timeout=SCAN_TIMEOUT, result_ttl=TASK_RESULT_TTL, - meta={ - "task_name": "Update Scan", - "task_type": TaskType.SCAN, - }, + meta=scan_job_meta(scan_type), ) + + # Any change to a platform directory should trigger a full rescan + if changes_platform_directory: + log.info(f"Platform directory changed, {rescan_in_msg}") + schedule_rescan([], ScanType.UPDATE) return # Otherwise, process each platform slug @@ -246,19 +246,7 @@ def process_changes(changes: Sequence[Change]) -> None: continue log.info(f"Change detected in {hl(fs_slug)} folder, {rescan_in_msg}") - low_prio_queue.enqueue_in( - time_delta, - scan_platforms, - platform_ids=[db_platform.id], - metadata_sources=metadata_sources, - scan_type=ScanType.QUICK, - job_timeout=SCAN_TIMEOUT, - result_ttl=TASK_RESULT_TTL, - meta={ - "task_name": "Quick Scan", - "task_type": TaskType.SCAN, - }, - ) + schedule_rescan([db_platform.id], ScanType.QUICK) if __name__ == "__main__": diff --git a/docker/init_scripts/init b/docker/init_scripts/init index af22f0c07..0f3bbfab3 100755 --- a/docker/init_scripts/init +++ b/docker/init_scripts/init @@ -221,30 +221,24 @@ start_bin_valkey-server() { error_log "Internal valkey did not become ready after $((max_retries * 500))ms" } -# The app reads REDIS_SSL as a boolean, so "false" and "0" mean plaintext. -# Testing the variable for non-emptiness would make every documented value TLS. -redis_scheme() { - local ssl - ssl="$(printf '%s' "${REDIS_SSL-}" | tr '[:upper:]' '[:lower:]')" - case "${ssl}" in - 1 | true | yes | on) echo "rediss" ;; - *) echo "redis" ;; - esac -} - # The URL carries the password, so it goes through RQ_REDIS_URL rather than -# --url, which would put it on a world-readable command line. +# --url, which would put it on a world-readable command line. REDIS_SSL is a +# boolean to the app, so "false" and "0" mean plaintext. build_redis_url() { - local scheme - scheme="$(redis_scheme)" + local scheme userinfo="" ssl="${REDIS_SSL-}" + + case "${ssl,,}" in + 1 | true | yes | on) scheme="rediss" ;; + *) scheme="redis" ;; + esac if [[ -n ${REDIS_PASSWORD-} ]]; then - echo "${scheme}://${REDIS_USERNAME-}:${REDIS_PASSWORD}@${REDIS_HOST:-127.0.0.1}:${REDIS_PORT:-6379}/${REDIS_DB:-0}" + userinfo="${REDIS_USERNAME-}:${REDIS_PASSWORD}@" elif [[ -n ${REDIS_USERNAME-} ]]; then - echo "${scheme}://${REDIS_USERNAME}@${REDIS_HOST:-127.0.0.1}:${REDIS_PORT:-6379}/${REDIS_DB:-0}" - else - echo "${scheme}://${REDIS_HOST:-127.0.0.1}:${REDIS_PORT:-6379}/${REDIS_DB:-0}" + userinfo="${REDIS_USERNAME}@" fi + + echo "${scheme}://${userinfo}${REDIS_HOST:-127.0.0.1}:${REDIS_PORT:-6379}/${REDIS_DB:-0}" } # Commands to start the RQ cron scheduler, which runs the periodic tasks listed diff --git a/entrypoint.sh b/entrypoint.sh index 7bfd17d41..e606234ff 100644 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -47,21 +47,19 @@ else uv run python main.py & fi -# Build Redis URL properly. The app reads REDIS_SSL as a boolean, so "false" -# and "0" mean plaintext; testing it for non-emptiness would make every -# documented value TLS. -REDIS_SCHEME="redis" -case "$(printf '%s' "${REDIS_SSL-}" | tr '[:upper:]' '[:lower:]')" in +# REDIS_SSL is a boolean to the app, so "false" and "0" mean plaintext. +REDIS_USERINFO="" +REDIS_SSL_VALUE="${REDIS_SSL-}" +case "${REDIS_SSL_VALUE,,}" in 1 | true | yes | on) REDIS_SCHEME="rediss" ;; -*) ;; +*) REDIS_SCHEME="redis" ;; esac if [[ -n ${REDIS_PASSWORD-} ]]; then - REDIS_URL="${REDIS_SCHEME}://${REDIS_USERNAME-}:${REDIS_PASSWORD}@${REDIS_HOST:-127.0.0.1}:${REDIS_PORT:-6379}/${REDIS_DB:-0}" + REDIS_USERINFO="${REDIS_USERNAME-}:${REDIS_PASSWORD}@" elif [[ -n ${REDIS_USERNAME-} ]]; then - REDIS_URL="${REDIS_SCHEME}://${REDIS_USERNAME}@${REDIS_HOST:-127.0.0.1}:${REDIS_PORT:-6379}/${REDIS_DB:-0}" -else - REDIS_URL="${REDIS_SCHEME}://${REDIS_HOST:-127.0.0.1}:${REDIS_PORT:-6379}/${REDIS_DB:-0}" + REDIS_USERINFO="${REDIS_USERNAME}@" fi +REDIS_URL="${REDIS_SCHEME}://${REDIS_USERINFO}${REDIS_HOST:-127.0.0.1}:${REDIS_PORT:-6379}/${REDIS_DB:-0}" echo "Starting RQ cron scheduler..." # The URL carries the password, so it goes through RQ_REDIS_URL rather than From 24cf0a47c35eca83affb4d310ae1f1c94e9bc131 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 2 Sep 2026 21:08:38 -0400 Subject: [PATCH 38/40] refactor(scan): move scan job bookkeeping out of the socket endpoint Finding a scan in flight and pruning ones left behind is RQ bookkeeping, not socket work, and the watcher and the startup script both ask for it. It now lives in a handler that depends on nothing heavier than the queue, with its own tests; the socket module keeps only what it says to a client. The func name a directly enqueued scan carries is spelled out rather than read off the function, which lives in the module that imports this one. A test holds the two together. Co-Authored-By: Claude Opus 5 (1M context) --- backend/endpoints/sockets/scan.py | 146 ++----------------- backend/handler/scan_jobs.py | 134 +++++++++++++++++ backend/startup.py | 2 +- backend/tests/endpoints/sockets/test_scan.py | 143 ++---------------- backend/tests/handler/test_scan_jobs.py | 121 +++++++++++++++ backend/tests/scan_job_stubs.py | 92 ++++++++++++ backend/watcher.py | 7 +- docs/BACKEND_ARCHITECTURE.md | 1 + 8 files changed, 374 insertions(+), 272 deletions(-) create mode 100644 backend/handler/scan_jobs.py create mode 100644 backend/tests/handler/test_scan_jobs.py create mode 100644 backend/tests/scan_job_stubs.py diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index c23f6ece7..28e50d59b 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -2,14 +2,12 @@ from __future__ import annotations import asyncio from dataclasses import dataclass -from datetime import datetime, timedelta, timezone -from itertools import batched, chain +from itertools import batched from typing import Any, Final import socketio # type: ignore -from rq import Worker, get_current_job +from rq import get_current_job from rq.job import Job, JobStatus -from rq.registry import ScheduledJobRegistry from sqlalchemy.exc import IntegrityError from config import DEV_MODE, REDIS_URL, SCAN_TIMEOUT, SCAN_WORKERS, TASK_RESULT_TTL @@ -49,14 +47,7 @@ from handler.metadata.launchbox_handler.types import LAUNCHBOX_PLATFORMS_DIR from handler.metadata.ss_handler import begin_scan as begin_ss_scan from handler.metadata.ss_handler import log_quota as log_ss_quota from handler.metadata.ss_handler import log_scan_summary as log_ss_scan_summary -from handler.redis_handler import ( - get_job_func_name, - get_job_status, - get_worker_current_job, - high_prio_queue, - low_prio_queue, - redis_client, -) +from handler.redis_handler import get_job_status, high_prio_queue, redis_client from handler.scan_handler import ( MetadataSource, ScanType, @@ -67,6 +58,11 @@ from handler.scan_handler import ( scan_platform, scan_rom, ) +from handler.scan_jobs import ( + get_queued_scan_jobs, + get_running_scan_job, + get_scheduled_scan_jobs, +) from handler.socket_handler import socket_handler from logger.formatter import BLUE, LIGHTYELLOW from logger.formatter import highlight as hl @@ -83,120 +79,6 @@ from utils.pegasus_exporter import PegasusExporter STOP_SCAN_FLAG: Final = "scan:stop" -# A delayed watcher scan this far past due was left behind by an instance that -# was not running, and the change it reacted to has long since settled. -STALE_SCHEDULED_SCAN_AGE: Final = timedelta(hours=1) - - -def _scan_platforms_func_name() -> str: - """Fully qualified name RQ records for a directly enqueued scan. - - Derived from the function itself so it cannot drift out of sync with the - name RQ stores when the job is enqueued. - """ - return f"{scan_platforms.__module__}.{scan_platforms.__name__}" - - -def _is_scan_job(job: Job) -> bool: - """Whether this job runs a scan. - - Socket and watcher scans enqueue scan_platforms itself. Task-driven scans go - through the task runner, which every task shares, so they are recognised by - the type their job carries instead. - """ - if get_job_func_name(job) == _scan_platforms_func_name(): - return True - - return job.meta.get("task_type") == TaskType.SCAN - - -def _get_running_scan_job() -> Job | None: - """The scan currently executing on a worker, if any. - - A started job is no longer in the queue, so it can only be found by asking - the workers what they are holding. - """ - for worker in Worker.all(connection=redis_client): - job = get_worker_current_job(worker) - if job is not None and _is_scan_job(job): - return job - - return None - - -def _get_queued_scan_jobs() -> list[Job]: - """Scans sitting on a worker queue, waiting to be picked up. - - Socket scans go to the high priority queue and watcher scans to the low - priority one, once their delay is up. - """ - job_ids = chain(high_prio_queue.get_job_ids(), low_prio_queue.get_job_ids()) - jobs = Job.fetch_many(job_ids, connection=redis_client) - - return [ - job - for job in jobs - if job is not None and _is_scan_job(job) - # The fetch above already carries the status, so re-reading it would be - # a round trip per queued job. - and get_job_status(job, refresh=False) == JobStatus.QUEUED - ] - - -def _scheduled_scan_registry() -> ScheduledJobRegistry: - """Where delayed scans wait, which is only ever the watcher's queue.""" - return ScheduledJobRegistry(queue=low_prio_queue) - - -def _get_scheduled_scan_jobs() -> list[Job]: - """Scans waiting out a delay, which only the watcher sets. - - These never stand in for a scan in flight: a worker has to be running to - release them, so counting them would refuse scans on an idle instance. - """ - registry = _scheduled_scan_registry() - jobs = Job.fetch_many(registry.get_job_ids(), connection=redis_client) - - return [job for job in jobs if job is not None and _is_scan_job(job)] - - -def get_pending_scan_jobs() -> list[Job]: - """Scans that have not started yet: queued, or waiting out a delay. - - A scan already running is deliberately not one of these. It may have walked - past the folder that just changed, so a fresh scan is still warranted. - """ - return _get_queued_scan_jobs() + _get_scheduled_scan_jobs() - - -def drop_stale_scheduled_scans() -> int: - """Drop delayed watcher scans that are long past due. - - Releasing a backlog of them at once, which is what an instance that was down - for a while does on start, would run the same library scan over and over. - - Returns: - int: How many scans were dropped. - """ - registry = _scheduled_scan_registry() - cutoff = datetime.now(timezone.utc) - STALE_SCHEDULED_SCAN_AGE - - # The registry is scored by due time, so it can hand back only what is past - # due rather than every delayed job. - stale_ids = registry.get_jobs_to_schedule(int(cutoff.timestamp())) - jobs = Job.fetch_many(stale_ids, connection=redis_client) - dropped = 0 - - for job in jobs: - if job is None or not _is_scan_job(job): - continue - - job.cancel() - dropped += 1 - log.warning(f"Dropped scan {job.id}, due over {STALE_SCHEDULED_SCAN_AGE} ago") - - return dropped - def scan_job_meta(scan_type: ScanType) -> dict[str, Any]: """What a scan job carries so a client can tell which scan is running.""" @@ -1028,7 +910,7 @@ async def scan_platforms( # scan that ended first would otherwise stop this one before it began. A # scan still on a worker owns the flag though, and clearing it there would # let a stopped scan carry on. - running_job = _get_running_scan_job() + running_job = get_running_scan_job() current_job = get_current_job() if running_job is None or ( current_job is not None and running_job.id == current_job.id @@ -1332,8 +1214,8 @@ async def scan_handler(sid: str, options: dict[str, Any]): # Without this, every request enqueues another full scan behind the running # one, and a client that lost the progress socket has no way to tell. if not DEV_MODE: - running_job = _get_running_scan_job() - queued_jobs = _get_queued_scan_jobs() + running_job = get_running_scan_job() + queued_jobs = get_queued_scan_jobs() if running_job is not None or queued_jobs: message = _scan_in_flight_message(running_job, queued_jobs) log.info(f"{emoji.EMOJI_STOP_SIGN} {message}, ignoring request") @@ -1391,14 +1273,14 @@ async def stop_scan_handler(sid: str): # Queued scans have not started, so cancelling them is enough. They have to # go too: stopping only the running scan would hand the worker the next one. - queued_jobs = _get_queued_scan_jobs() - scheduled_jobs = _get_scheduled_scan_jobs() + queued_jobs = get_queued_scan_jobs() + scheduled_jobs = get_scheduled_scan_jobs() for job in queued_jobs + scheduled_jobs: job.cancel() # A running scan cannot be interrupted from here, it polls the stop flag # between platforms and ROMs and unwinds itself. - running_job = _get_running_scan_job() + running_job = get_running_scan_job() if running_job is not None: running_job.cancel() redis_client.set(STOP_SCAN_FLAG, 1) diff --git a/backend/handler/scan_jobs.py b/backend/handler/scan_jobs.py new file mode 100644 index 000000000..1210b8b51 --- /dev/null +++ b/backend/handler/scan_jobs.py @@ -0,0 +1,134 @@ +"""Finding and pruning the RQ jobs that run a library scan. + +Kept out of the socket endpoint so the watcher and the startup script can ask +about scans without importing the scan implementation and everything under it. +""" + +from datetime import datetime, timedelta, timezone +from itertools import chain +from typing import Final + +from rq import Worker +from rq.job import Job, JobStatus +from rq.registry import ScheduledJobRegistry + +from handler.redis_handler import ( + get_job_func_name, + get_job_status, + get_worker_current_job, + high_prio_queue, + low_prio_queue, + redis_client, +) +from logger.logger import log +from tasks.tasks import TaskType + +# The name RQ records for a directly enqueued scan. Spelled out rather than +# derived from the function, which lives in the module that imports this one; +# a test holds the two together. +SCAN_PLATFORMS_FUNC: Final = "endpoints.sockets.scan.scan_platforms" + +# A delayed watcher scan this far past due was left behind by an instance that +# was not running, and the change it reacted to has long since settled. +STALE_SCHEDULED_SCAN_AGE: Final = timedelta(hours=1) + + +def is_scan_job(job: Job) -> bool: + """Whether this job runs a scan. + + Socket and watcher scans enqueue scan_platforms itself. Task-driven scans go + through the task runner, which every task shares, so they are recognised by + the type their job carries instead. + """ + if get_job_func_name(job) == SCAN_PLATFORMS_FUNC: + return True + + return job.meta.get("task_type") == TaskType.SCAN + + +def get_running_scan_job() -> Job | None: + """The scan currently executing on a worker, if any. + + A started job is no longer in the queue, so it can only be found by asking + the workers what they are holding. + """ + for worker in Worker.all(connection=redis_client): + job = get_worker_current_job(worker) + if job is not None and is_scan_job(job): + return job + + return None + + +def get_queued_scan_jobs() -> list[Job]: + """Scans sitting on a worker queue, waiting to be picked up. + + Socket scans go to the high priority queue and watcher scans to the low + priority one, once their delay is up. + """ + job_ids = chain(high_prio_queue.get_job_ids(), low_prio_queue.get_job_ids()) + jobs = Job.fetch_many(job_ids, connection=redis_client) + + return [ + job + for job in jobs + if job is not None and is_scan_job(job) + # The fetch above already carries the status, so re-reading it would be + # a round trip per queued job. + and get_job_status(job, refresh=False) == JobStatus.QUEUED + ] + + +def _scheduled_scan_registry() -> ScheduledJobRegistry: + """Where delayed scans wait, which is only ever the watcher's queue.""" + return ScheduledJobRegistry(queue=low_prio_queue) + + +def get_scheduled_scan_jobs() -> list[Job]: + """Scans waiting out a delay, which only the watcher sets. + + These never stand in for a scan in flight: a worker has to be running to + release them, so counting them would refuse scans on an idle instance. + """ + registry = _scheduled_scan_registry() + jobs = Job.fetch_many(registry.get_job_ids(), connection=redis_client) + + return [job for job in jobs if job is not None and is_scan_job(job)] + + +def get_pending_scan_jobs() -> list[Job]: + """Scans that have not started yet: queued, or waiting out a delay. + + A scan already running is deliberately not one of these. It may have walked + past the folder that just changed, so a fresh scan is still warranted. + """ + return get_queued_scan_jobs() + get_scheduled_scan_jobs() + + +def drop_stale_scheduled_scans() -> int: + """Drop delayed watcher scans that are long past due. + + Releasing a backlog of them at once, which is what an instance that was down + for a while does on start, would run the same library scan over and over. + + Returns: + int: How many scans were dropped. + """ + registry = _scheduled_scan_registry() + cutoff = datetime.now(timezone.utc) - STALE_SCHEDULED_SCAN_AGE + + # The registry is scored by due time, so it can hand back only what is past + # due rather than every delayed job. + stale_ids = registry.get_jobs_to_schedule(int(cutoff.timestamp())) + jobs = Job.fetch_many(stale_ids, connection=redis_client) + dropped = 0 + + for job in jobs: + if job is None or not is_scan_job(job): + continue + + job.cancel() + dropped += 1 + log.warning(f"Dropped scan {job.id}, due over {STALE_SCHEDULED_SCAN_AGE} ago") + + return dropped diff --git a/backend/startup.py b/backend/startup.py index afa5fa86d..bc04cae98 100644 --- a/backend/startup.py +++ b/backend/startup.py @@ -8,7 +8,6 @@ from rq.exceptions import DuplicateJobError from rq.job import Job from config import ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP, SENTRY_DSN -from endpoints.sockets.scan import drop_stale_scheduled_scans from handler.database import db_save_handler from handler.metadata.base_handler import ( MAME_XML_KEY, @@ -26,6 +25,7 @@ from handler.redis_handler import ( low_prio_queue, redis_client, ) +from handler.scan_jobs import drop_stale_scheduled_scans from logger.logger import log from models.firmware import FIRMWARE_FIXTURES_DIR, KNOWN_BIOS_KEY from tasks.registry import enqueue_task diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index ec03c021b..b8618ac8c 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -1,12 +1,17 @@ -from datetime import datetime, timedelta, timezone -from itertools import count from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock, Mock import pytest import socketio -from rq.exceptions import InvalidJobOperation, NoSuchJobError -from rq.job import Job, JobStatus +from rq.exceptions import InvalidJobOperation +from rq.job import JobStatus +from tests.scan_job_stubs import ( + CLEANUP_FUNC, + SCAN_PLATFORMS_FUNC, + make_job, + make_task_job, + patch_scan_jobs, +) from endpoints.sockets import scan as scan_module from endpoints.sockets.scan import ( @@ -35,7 +40,6 @@ from handler.scan_handler import MetadataSource, ScanType from models.firmware import Firmware from models.platform import Platform from models.rom import Rom -from tasks.tasks import TaskType def test_scan_stats(): @@ -1678,87 +1682,6 @@ class TestGetPico8CoverUrl: assert fs_name in url -SCAN_PLATFORMS_FUNC = "endpoints.sockets.scan.scan_platforms" -TASK_RUNNER_FUNC = "tasks.tasks.run_task_by_name" -CLEANUP_FUNC = "tasks.scheduled.cleanup_zip_cache.cleanup_zip_cache_task.run" - -_job_ids = count() - - -def make_job( - func_name: str, - *, - status=JobStatus.QUEUED, - task_name: str | None = None, - task_type: TaskType | None = None, -): - """An RQ job stub that scan job discovery will accept.""" - job = MagicMock(spec=Job) - job.id = f"job-{next(_job_ids)}" - job.func_name = func_name - job.get_status.return_value = status - job.meta = {} - if task_name: - job.meta["task_name"] = task_name - if task_type: - job.meta["task_type"] = task_type - return job - - -def make_task_job(**kwargs): - """A scan that runs through the task runner, as the scheduled rescan does.""" - return make_job(TASK_RUNNER_FUNC, task_type=TaskType.SCAN, **kwargs) - - -def patch_scan_jobs( - mocker, - *, - running=None, - high_queued=(), - low_queued=(), - scheduled=(), - worker_lost=False, -) -> MagicMock: - """Point every place scan discovery looks at a fixed set of jobs. - - Returns the patched scheduled-scan registry. - """ - worker = MagicMock() - if worker_lost: - worker.get_current_job.side_effect = NoSuchJobError - else: - worker.get_current_job.return_value = running - mocker.patch.object(scan_module.Worker, "all", return_value=[worker]) - - queued_jobs = list(high_queued) + list(low_queued) - scheduled_jobs = list(scheduled) - mocker.patch.object( - scan_module.high_prio_queue, - "get_job_ids", - return_value=[job.id for job in high_queued], - ) - mocker.patch.object( - scan_module.low_prio_queue, - "get_job_ids", - return_value=[job.id for job in low_queued], - ) - - registry = MagicMock() - registry.get_job_ids.return_value = [job.id for job in scheduled_jobs] - registry.get_jobs_to_schedule.return_value = [] - mocker.patch.object(scan_module, "_scheduled_scan_registry", return_value=registry) - - # Both the queue and the registry lookups fetch by id, so the stub has to - # answer for whichever ids it is handed. - by_id = {job.id: job for job in queued_jobs + scheduled_jobs} - mocker.patch.object( - scan_module.Job, - "fetch_many", - side_effect=lambda job_ids, **kwargs: [by_id.get(i) for i in job_ids], - ) - return registry - - class TestScanConcurrency: """A scan already in flight must block another from being enqueued.""" @@ -2059,51 +1982,3 @@ class TestStopScan: await stop_scan_handler("sid") redis.set.assert_not_called() - - -class TestDropStaleScheduledScans: - """A worker that starts after downtime must not release a backlog.""" - - @staticmethod - def _due(hours_late: float): - return datetime.now(timezone.utc) - timedelta(hours=hours_late) - - def test_drops_a_scan_long_past_due(self, mocker): - job = make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.SCHEDULED) - registry = patch_scan_jobs(mocker, scheduled=[job]) - registry.get_jobs_to_schedule.return_value = [job.id] - - assert scan_module.drop_stale_scheduled_scans() == 1 - job.cancel.assert_called_once() - - def test_asks_the_registry_only_for_what_is_past_due(self, mocker): - registry = patch_scan_jobs(mocker) - - scan_module.drop_stale_scheduled_scans() - - cutoff = registry.get_jobs_to_schedule.call_args.args[0] - expected = datetime.now(timezone.utc) - scan_module.STALE_SCHEDULED_SCAN_AGE - assert abs(cutoff - expected.timestamp()) < 5 - - def test_keeps_a_scan_still_waiting_out_its_delay(self, mocker): - job = make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.SCHEDULED) - patch_scan_jobs(mocker, scheduled=[job]) - - assert scan_module.drop_stale_scheduled_scans() == 0 - job.cancel.assert_not_called() - - def test_ignores_a_scan_that_left_the_registry(self, mocker): - job = make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.SCHEDULED) - registry = patch_scan_jobs(mocker) - registry.get_jobs_to_schedule.return_value = [job.id] - - assert scan_module.drop_stale_scheduled_scans() == 0 - job.cancel.assert_not_called() - - def test_leaves_jobs_that_are_not_scans_alone(self, mocker): - job = make_job(CLEANUP_FUNC, status=JobStatus.SCHEDULED) - registry = patch_scan_jobs(mocker, scheduled=[job]) - registry.get_jobs_to_schedule.return_value = [job.id] - - assert scan_module.drop_stale_scheduled_scans() == 0 - job.cancel.assert_not_called() diff --git a/backend/tests/handler/test_scan_jobs.py b/backend/tests/handler/test_scan_jobs.py new file mode 100644 index 000000000..11ba8ad5d --- /dev/null +++ b/backend/tests/handler/test_scan_jobs.py @@ -0,0 +1,121 @@ +from datetime import datetime, timezone + +from rq.job import JobStatus +from tests.scan_job_stubs import ( + CLEANUP_FUNC, + SCAN_PLATFORMS_FUNC, + make_job, + make_task_job, + patch_scan_jobs, +) + +import handler.scan_jobs as scan_jobs +from endpoints.sockets.scan import scan_platforms + + +def test_the_scan_func_name_matches_the_function(): + """The constant stands in for an import the other direction, so it has to + keep naming the function RQ actually records.""" + assert scan_jobs.SCAN_PLATFORMS_FUNC == ( + f"{scan_platforms.__module__}.{scan_platforms.__name__}" + ) + + +class TestIsScanJob: + def test_recognises_a_directly_enqueued_scan(self): + assert scan_jobs.is_scan_job(make_job(SCAN_PLATFORMS_FUNC)) + + def test_recognises_a_scan_that_runs_through_the_task_runner(self): + assert scan_jobs.is_scan_job(make_task_job()) + + def test_ignores_another_task(self): + assert not scan_jobs.is_scan_job(make_job(CLEANUP_FUNC)) + + +class TestGetQueuedScanJobs: + def test_collects_scans_from_both_queues(self, mocker): + high = make_job(SCAN_PLATFORMS_FUNC) + low = make_task_job() + patch_scan_jobs(mocker, high_queued=[high], low_queued=[low]) + + assert scan_jobs.get_queued_scan_jobs() == [high, low] + + def test_leaves_out_jobs_that_are_not_scans(self, mocker): + patch_scan_jobs(mocker, high_queued=[make_job(CLEANUP_FUNC)]) + + assert scan_jobs.get_queued_scan_jobs() == [] + + def test_leaves_out_a_scan_that_is_no_longer_queued(self, mocker): + job = make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.STARTED) + patch_scan_jobs(mocker, high_queued=[job]) + + assert scan_jobs.get_queued_scan_jobs() == [] + + +class TestGetRunningScanJob: + def test_returns_the_scan_a_worker_is_holding(self, mocker): + job = make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.STARTED) + patch_scan_jobs(mocker, running=job) + + assert scan_jobs.get_running_scan_job() is job + + def test_returns_none_when_a_worker_outlived_its_job(self, mocker): + patch_scan_jobs(mocker, worker_lost=True) + + assert scan_jobs.get_running_scan_job() is None + + +class TestGetPendingScanJobs: + def test_counts_queued_and_delayed_scans_but_not_running_ones(self, mocker): + queued = make_job(SCAN_PLATFORMS_FUNC) + delayed = make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.SCHEDULED) + running = make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.STARTED) + patch_scan_jobs( + mocker, running=running, high_queued=[queued], scheduled=[delayed] + ) + + assert scan_jobs.get_pending_scan_jobs() == [queued, delayed] + + +class TestDropStaleScheduledScans: + """A worker that starts after downtime must not release a backlog.""" + + def test_drops_a_scan_long_past_due(self, mocker): + job = make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.SCHEDULED) + registry = patch_scan_jobs(mocker, scheduled=[job]) + registry.get_jobs_to_schedule.return_value = [job.id] + + assert scan_jobs.drop_stale_scheduled_scans() == 1 + job.cancel.assert_called_once() + + def test_asks_the_registry_only_for_what_is_past_due(self, mocker): + registry = patch_scan_jobs(mocker) + + scan_jobs.drop_stale_scheduled_scans() + + cutoff = registry.get_jobs_to_schedule.call_args.args[0] + expected = datetime.now(timezone.utc) - scan_jobs.STALE_SCHEDULED_SCAN_AGE + assert abs(cutoff - expected.timestamp()) < 5 + + def test_keeps_a_scan_still_waiting_out_its_delay(self, mocker): + job = make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.SCHEDULED) + patch_scan_jobs(mocker, scheduled=[job]) + + assert scan_jobs.drop_stale_scheduled_scans() == 0 + job.cancel.assert_not_called() + + def test_ignores_a_scan_that_left_the_registry(self, mocker): + job = make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.SCHEDULED) + registry = patch_scan_jobs(mocker) + registry.get_jobs_to_schedule.return_value = [job.id] + + assert scan_jobs.drop_stale_scheduled_scans() == 0 + job.cancel.assert_not_called() + + def test_leaves_jobs_that_are_not_scans_alone(self, mocker): + job = make_job(CLEANUP_FUNC, status=JobStatus.SCHEDULED) + registry = patch_scan_jobs(mocker, scheduled=[job]) + registry.get_jobs_to_schedule.return_value = [job.id] + + assert scan_jobs.drop_stale_scheduled_scans() == 0 + job.cancel.assert_not_called() diff --git a/backend/tests/scan_job_stubs.py b/backend/tests/scan_job_stubs.py new file mode 100644 index 000000000..e44f87825 --- /dev/null +++ b/backend/tests/scan_job_stubs.py @@ -0,0 +1,92 @@ +"""Job stubs and Redis patching shared by the scan job discovery tests.""" + +from itertools import count +from unittest.mock import MagicMock + +from rq.exceptions import NoSuchJobError +from rq.job import Job, JobStatus + +import handler.scan_jobs as scan_jobs_module +from tasks.tasks import TaskType + +SCAN_PLATFORMS_FUNC = "endpoints.sockets.scan.scan_platforms" +TASK_RUNNER_FUNC = "tasks.tasks.run_task_by_name" +CLEANUP_FUNC = "tasks.scheduled.cleanup_zip_cache.cleanup_zip_cache_task.run" + +_job_ids = count() + + +def make_job( + func_name: str, + *, + status=JobStatus.QUEUED, + task_name: str | None = None, + task_type: TaskType | None = None, +): + """An RQ job stub that scan job discovery will accept.""" + job = MagicMock(spec=Job) + job.id = f"job-{next(_job_ids)}" + job.func_name = func_name + job.get_status.return_value = status + job.meta = {} + if task_name: + job.meta["task_name"] = task_name + if task_type: + job.meta["task_type"] = task_type + return job + + +def make_task_job(**kwargs): + """A scan that runs through the task runner, as the scheduled rescan does.""" + return make_job(TASK_RUNNER_FUNC, task_type=TaskType.SCAN, **kwargs) + + +def patch_scan_jobs( + mocker, + *, + running=None, + high_queued=(), + low_queued=(), + scheduled=(), + worker_lost=False, +) -> MagicMock: + """Point every place scan discovery looks at a fixed set of jobs. + + Returns the patched scheduled-scan registry. + """ + worker = MagicMock() + if worker_lost: + worker.get_current_job.side_effect = NoSuchJobError + else: + worker.get_current_job.return_value = running + mocker.patch.object(scan_jobs_module.Worker, "all", return_value=[worker]) + + queued_jobs = list(high_queued) + list(low_queued) + scheduled_jobs = list(scheduled) + mocker.patch.object( + scan_jobs_module.high_prio_queue, + "get_job_ids", + return_value=[job.id for job in high_queued], + ) + mocker.patch.object( + scan_jobs_module.low_prio_queue, + "get_job_ids", + return_value=[job.id for job in low_queued], + ) + + registry = MagicMock() + registry.get_job_ids.return_value = [job.id for job in scheduled_jobs] + registry.get_jobs_to_schedule.return_value = [] + mocker.patch.object( + scan_jobs_module, "_scheduled_scan_registry", return_value=registry + ) + + # Both the queue and the registry lookups fetch by id, so the stub has to + # answer for whichever ids it is handed. + by_id = {job.id: job for job in queued_jobs + scheduled_jobs} + mocker.patch.object( + scan_jobs_module.Job, + "fetch_many", + side_effect=lambda job_ids, **kwargs: [by_id.get(i) for i in job_ids], + ) + return registry diff --git a/backend/watcher.py b/backend/watcher.py index c1861aa00..40115ebdb 100644 --- a/backend/watcher.py +++ b/backend/watcher.py @@ -19,11 +19,7 @@ from config import ( TASK_RESULT_TTL, ) from config.config_manager import config_manager as cm -from endpoints.sockets.scan import ( - get_pending_scan_jobs, - scan_job_meta, - scan_platforms, -) +from endpoints.sockets.scan import scan_job_meta, scan_platforms from handler.database import db_platform_handler from handler.metadata import ( meta_csdb_handler, @@ -45,6 +41,7 @@ from handler.metadata import ( ) from handler.redis_handler import get_job_kwargs, low_prio_queue from handler.scan_handler import MetadataSource, ScanType +from handler.scan_jobs import get_pending_scan_jobs from logger.formatter import CYAN from logger.formatter import highlight as hl from logger.logger import log diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md index fc88db9d4..f585a4f64 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/BACKEND_ARCHITECTURE.md @@ -226,6 +226,7 @@ backend/ │ ├── socket_handler.py # Socket.IO server management │ ├── netplay_handler.py # Netplay room state │ ├── redis_handler.py # Redis clients & queues +│ ├── scan_jobs.py # Finding & pruning in-flight scan jobs │ ├── auth/ # Authentication subsystem │ │ ├── base_handler.py # Auth, OAuth, OIDC handlers │ │ ├── hybrid_auth.py # Multi-method auth backend From 12b67f1c2c266db7ebb3f3071d36282b20cef9b2 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 3 Sep 2026 07:36:51 -0400 Subject: [PATCH 39/40] chore(tasks): trim the comments down to what the code cannot say Also stops the scan job test stubs keeping their own copy of the func name the handler already declares. Co-Authored-By: Claude Opus 5 (1M context) --- backend/endpoints/tasks.py | 3 +-- backend/handler/redis_handler.py | 6 ++--- backend/handler/scan_jobs.py | 23 ++++++++------------ backend/startup.py | 12 +++------- backend/tasks/registry.py | 2 +- backend/tests/endpoints/sockets/test_scan.py | 12 +++++----- backend/tests/handler/test_scan_jobs.py | 10 ++++----- backend/tests/scan_job_stubs.py | 7 +++--- 8 files changed, 30 insertions(+), 45 deletions(-) diff --git a/backend/endpoints/tasks.py b/backend/endpoints/tasks.py index 0fc44e26a..3a508a0be 100644 --- a/backend/endpoints/tasks.py +++ b/backend/endpoints/tasks.py @@ -41,8 +41,7 @@ router = APIRouter( # Scheduled tasks an admin can see and trigger. The rest of the catalog runs on -# its schedule without being surfaced. Resolved here so a registry rename fails -# at import rather than on a request. +# its schedule without being surfaced. VISIBLE_SCHEDULED_TASKS: Final[dict[str, Task]] = { name: SCHEDULED_TASKS[name] for name in ( diff --git a/backend/handler/redis_handler.py b/backend/handler/redis_handler.py index cb6e3d32b..668a2ac81 100644 --- a/backend/handler/redis_handler.py +++ b/backend/handler/redis_handler.py @@ -110,10 +110,8 @@ def get_job_kwargs(job: Job) -> dict[str, Any] | None: def get_worker_current_job(worker: Worker) -> Job | None: - """Safely get the job a worker is holding. - - A worker killed mid-job keeps pointing at it until its own registration - expires, by which time the job can be gone. + """Safely get the job a worker is holding, which can be gone before the + worker's own registration expires. Args: worker: The RQ Worker to read diff --git a/backend/handler/scan_jobs.py b/backend/handler/scan_jobs.py index 1210b8b51..84f0b7ccc 100644 --- a/backend/handler/scan_jobs.py +++ b/backend/handler/scan_jobs.py @@ -1,8 +1,4 @@ -"""Finding and pruning the RQ jobs that run a library scan. - -Kept out of the socket endpoint so the watcher and the startup script can ask -about scans without importing the scan implementation and everything under it. -""" +"""Finding and pruning the RQ jobs that run a library scan.""" from datetime import datetime, timedelta, timezone from itertools import chain @@ -23,9 +19,8 @@ from handler.redis_handler import ( from logger.logger import log from tasks.tasks import TaskType -# The name RQ records for a directly enqueued scan. Spelled out rather than -# derived from the function, which lives in the module that imports this one; -# a test holds the two together. +# The name RQ records for a directly enqueued scan, kept in step with the +# function by a test rather than an import, which would be a cycle. SCAN_PLATFORMS_FUNC: Final = "endpoints.sockets.scan.scan_platforms" # A delayed watcher scan this far past due was left behind by an instance that @@ -36,9 +31,8 @@ STALE_SCHEDULED_SCAN_AGE: Final = timedelta(hours=1) def is_scan_job(job: Job) -> bool: """Whether this job runs a scan. - Socket and watcher scans enqueue scan_platforms itself. Task-driven scans go - through the task runner, which every task shares, so they are recognised by - the type their job carries instead. + Task-driven scans carry the task runner's func name, which every task + shares, so those are recognised by the type in their meta instead. """ if get_job_func_name(job) == SCAN_PLATFORMS_FUNC: return True @@ -117,8 +111,7 @@ def drop_stale_scheduled_scans() -> int: registry = _scheduled_scan_registry() cutoff = datetime.now(timezone.utc) - STALE_SCHEDULED_SCAN_AGE - # The registry is scored by due time, so it can hand back only what is past - # due rather than every delayed job. + # The registry is scored by due time, so it can hand back only what is due. stale_ids = registry.get_jobs_to_schedule(int(cutoff.timestamp())) jobs = Job.fetch_many(stale_ids, connection=redis_client) dropped = 0 @@ -129,6 +122,8 @@ def drop_stale_scheduled_scans() -> int: job.cancel() dropped += 1 - log.warning(f"Dropped scan {job.id}, due over {STALE_SCHEDULED_SCAN_AGE} ago") + log.warning( + f"Dropped scan {job.id}, overdue by more than {STALE_SCHEDULED_SCAN_AGE}" + ) return dropped diff --git a/backend/startup.py b/backend/startup.py index bc04cae98..716342945 100644 --- a/backend/startup.py +++ b/backend/startup.py @@ -58,11 +58,7 @@ def _enqueue_backfill(task_name: str, job_id: str) -> None: def _enqueue_recompute_save_hashes_if_needed() -> None: - """Backfill content_hash for saves uploaded before the path-resolution fix. - - A single COUNT query gates it, so a run that already completed costs nothing - on later restarts. - """ + """Backfill content_hash for saves uploaded before the path-resolution fix.""" try: missing = db_save_handler.count_saves_missing_content_hash() except Exception: @@ -83,10 +79,8 @@ def _enqueue_recompute_save_hashes_if_needed() -> None: def _enqueue_convert_images_to_webp() -> None: """Backfill .webp covers when WebP conversion is enabled. - The frontend rewrites cover URLs to .webp as soon as the feature flag is on, - but the scheduled task only runs at its next cron time and the inline - conversion in the resources handler only fires for covers fetched after - enabling, so without this every existing cover 404s until then. + The frontend rewrites cover URLs to .webp as soon as the flag is on, so + without this every cover fetched before it 404s until the next cron run. """ _enqueue_backfill("convert_images_to_webp", CONVERT_IMAGES_TO_WEBP_JOB_ID) diff --git a/backend/tasks/registry.py b/backend/tasks/registry.py index 3483c39ce..3596f208e 100644 --- a/backend/tasks/registry.py +++ b/backend/tasks/registry.py @@ -65,7 +65,7 @@ def enqueue_task( task_kwargs: dict[str, Any] | None = None, **job_options: Any, ) -> Job: - """Enqueue a registered task by name, on the queue a worker picks it up from. + """Enqueue a registered task by name. Args: name: The key the task is registered under. diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index b8618ac8c..21396bbf4 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -6,8 +6,7 @@ import socketio from rq.exceptions import InvalidJobOperation from rq.job import JobStatus from tests.scan_job_stubs import ( - CLEANUP_FUNC, - SCAN_PLATFORMS_FUNC, + NON_SCAN_FUNC, make_job, make_task_job, patch_scan_jobs, @@ -37,6 +36,7 @@ from handler.filesystem.roms_handler import ( ) from handler.metadata.base_handler import UniversalPlatformSlug as UPS from handler.scan_handler import MetadataSource, ScanType +from handler.scan_jobs import SCAN_PLATFORMS_FUNC from models.firmware import Firmware from models.platform import Platform from models.rom import Rom @@ -1834,10 +1834,10 @@ class TestScanConcurrency: # Only scans block scans; a cleanup or metadata task must not. patch_scan_jobs( mocker, - running=make_job(CLEANUP_FUNC), - high_queued=[make_job(CLEANUP_FUNC)], - low_queued=[make_job(CLEANUP_FUNC)], - scheduled=[make_job(CLEANUP_FUNC, status=JobStatus.SCHEDULED)], + running=make_job(NON_SCAN_FUNC), + high_queued=[make_job(NON_SCAN_FUNC)], + low_queued=[make_job(NON_SCAN_FUNC)], + scheduled=[make_job(NON_SCAN_FUNC, status=JobStatus.SCHEDULED)], ) enqueue = mocker.patch.object(scan_module.high_prio_queue, "enqueue") diff --git a/backend/tests/handler/test_scan_jobs.py b/backend/tests/handler/test_scan_jobs.py index 11ba8ad5d..9c2427bbf 100644 --- a/backend/tests/handler/test_scan_jobs.py +++ b/backend/tests/handler/test_scan_jobs.py @@ -2,8 +2,7 @@ from datetime import datetime, timezone from rq.job import JobStatus from tests.scan_job_stubs import ( - CLEANUP_FUNC, - SCAN_PLATFORMS_FUNC, + NON_SCAN_FUNC, make_job, make_task_job, patch_scan_jobs, @@ -11,6 +10,7 @@ from tests.scan_job_stubs import ( import handler.scan_jobs as scan_jobs from endpoints.sockets.scan import scan_platforms +from handler.scan_jobs import SCAN_PLATFORMS_FUNC def test_the_scan_func_name_matches_the_function(): @@ -29,7 +29,7 @@ class TestIsScanJob: assert scan_jobs.is_scan_job(make_task_job()) def test_ignores_another_task(self): - assert not scan_jobs.is_scan_job(make_job(CLEANUP_FUNC)) + assert not scan_jobs.is_scan_job(make_job(NON_SCAN_FUNC)) class TestGetQueuedScanJobs: @@ -41,7 +41,7 @@ class TestGetQueuedScanJobs: assert scan_jobs.get_queued_scan_jobs() == [high, low] def test_leaves_out_jobs_that_are_not_scans(self, mocker): - patch_scan_jobs(mocker, high_queued=[make_job(CLEANUP_FUNC)]) + patch_scan_jobs(mocker, high_queued=[make_job(NON_SCAN_FUNC)]) assert scan_jobs.get_queued_scan_jobs() == [] @@ -113,7 +113,7 @@ class TestDropStaleScheduledScans: job.cancel.assert_not_called() def test_leaves_jobs_that_are_not_scans_alone(self, mocker): - job = make_job(CLEANUP_FUNC, status=JobStatus.SCHEDULED) + job = make_job(NON_SCAN_FUNC, status=JobStatus.SCHEDULED) registry = patch_scan_jobs(mocker, scheduled=[job]) registry.get_jobs_to_schedule.return_value = [job.id] diff --git a/backend/tests/scan_job_stubs.py b/backend/tests/scan_job_stubs.py index e44f87825..f800f06c3 100644 --- a/backend/tests/scan_job_stubs.py +++ b/backend/tests/scan_job_stubs.py @@ -7,11 +7,10 @@ from rq.exceptions import NoSuchJobError from rq.job import Job, JobStatus import handler.scan_jobs as scan_jobs_module -from tasks.tasks import TaskType +from tasks.tasks import TaskType, run_task_by_name -SCAN_PLATFORMS_FUNC = "endpoints.sockets.scan.scan_platforms" -TASK_RUNNER_FUNC = "tasks.tasks.run_task_by_name" -CLEANUP_FUNC = "tasks.scheduled.cleanup_zip_cache.cleanup_zip_cache_task.run" +TASK_RUNNER_FUNC = f"{run_task_by_name.__module__}.{run_task_by_name.__name__}" +NON_SCAN_FUNC = "tasks.tasks.not_a_scan" _job_ids = count() From 92c25d8db38c933389cfca96508719ce564d788c Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 3 Sep 2026 08:11:02 -0400 Subject: [PATCH 40/40] fix(tasks): give each cron entry its own identity and result ttl rq.cron names an entry after its function unless told otherwise, and every entry here runs the task runner, so all of them shared one cron identity and one job history zset. It also always passes a result_ttl, so leaving it out meant its 500s default rather than the worker's setting: a scheduled run vanished from the task list eight minutes after finishing while a manual run of the same task was kept for a day. Stopping a scan twice raised out of the socket handler. The first Stop marks the job cancelled but the worker holds it until it unwinds, so the second reaches it again and RQ refuses to cancel a cancelled job. Co-Authored-By: Claude Opus 5 (1M context) --- backend/endpoints/sockets/scan.py | 13 +++++++++---- backend/handler/redis_handler.py | 17 +++++++++++++++++ backend/handler/scan_jobs.py | 5 ++++- backend/startup.py | 7 +++---- backend/tasks/cron_config.py | 5 +++++ backend/tests/endpoints/sockets/test_scan.py | 13 +++++++++++++ backend/tests/handler/test_redis_handler.py | 16 ++++++++++++++++ backend/tests/tasks/test_cron_config.py | 18 ++++++++++++++++++ 8 files changed, 85 insertions(+), 9 deletions(-) diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index 28e50d59b..a6658f85d 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -47,7 +47,12 @@ from handler.metadata.launchbox_handler.types import LAUNCHBOX_PLATFORMS_DIR from handler.metadata.ss_handler import begin_scan as begin_ss_scan from handler.metadata.ss_handler import log_quota as log_ss_quota from handler.metadata.ss_handler import log_scan_summary as log_ss_scan_summary -from handler.redis_handler import get_job_status, high_prio_queue, redis_client +from handler.redis_handler import ( + cancel_job, + get_job_status, + high_prio_queue, + redis_client, +) from handler.scan_handler import ( MetadataSource, ScanType, @@ -84,7 +89,7 @@ def scan_job_meta(scan_type: ScanType) -> dict[str, Any]: """What a scan job carries so a client can tell which scan is running.""" return { "task_name": f"{scan_type.value.capitalize()} Scan", - "task_type": TaskType.SCAN, + "task_type": TaskType.SCAN.value, } @@ -1276,13 +1281,13 @@ async def stop_scan_handler(sid: str): queued_jobs = get_queued_scan_jobs() scheduled_jobs = get_scheduled_scan_jobs() for job in queued_jobs + scheduled_jobs: - job.cancel() + cancel_job(job) # A running scan cannot be interrupted from here, it polls the stop flag # between platforms and ROMs and unwinds itself. running_job = get_running_scan_job() if running_job is not None: - running_job.cancel() + cancel_job(running_job) redis_client.set(STOP_SCAN_FLAG, 1) if running_job is None and not queued_jobs and not scheduled_jobs: diff --git a/backend/handler/redis_handler.py b/backend/handler/redis_handler.py index 668a2ac81..b82ec61dd 100644 --- a/backend/handler/redis_handler.py +++ b/backend/handler/redis_handler.py @@ -109,6 +109,23 @@ def get_job_kwargs(job: Job) -> dict[str, Any] | None: return None +def cancel_job(job: Job) -> bool: + """Cancel an RQ job, tolerating one that is already cancelled. + + Args: + job: The RQ Job object to cancel + + Returns: + Whether this call was the one that cancelled it + """ + try: + job.cancel() + except InvalidJobOperation: + return False + + return True + + def get_worker_current_job(worker: Worker) -> Job | None: """Safely get the job a worker is holding, which can be gone before the worker's own registration expires. diff --git a/backend/handler/scan_jobs.py b/backend/handler/scan_jobs.py index 84f0b7ccc..61a8f7d26 100644 --- a/backend/handler/scan_jobs.py +++ b/backend/handler/scan_jobs.py @@ -9,6 +9,7 @@ from rq.job import Job, JobStatus from rq.registry import ScheduledJobRegistry from handler.redis_handler import ( + cancel_job, get_job_func_name, get_job_status, get_worker_current_job, @@ -120,7 +121,9 @@ def drop_stale_scheduled_scans() -> int: if job is None or not is_scan_job(job): continue - job.cancel() + if not cancel_job(job): + continue + dropped += 1 log.warning( f"Dropped scan {job.id}, overdue by more than {STALE_SCHEDULED_SCAN_AGE}" diff --git a/backend/startup.py b/backend/startup.py index 716342945..1579043dd 100644 --- a/backend/startup.py +++ b/backend/startup.py @@ -6,6 +6,7 @@ import sentry_sdk from opentelemetry import trace from rq.exceptions import DuplicateJobError from rq.job import Job +from rq.utils import as_text from config import ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP, SENTRY_DSN from handler.database import db_save_handler @@ -98,7 +99,7 @@ def _drop_legacy_scheduler_state() -> None: """Clear what the old scheduler left in Redis, jobs included.""" try: legacy_job_ids = { - job_id.decode() + as_text(job_id) for job_id in redis_client.zrange(LEGACY_SCHEDULED_JOBS_KEY, 0, -1) } @@ -113,9 +114,7 @@ def _drop_legacy_scheduler_state() -> None: if orphans: redis_client.delete(*(Job.key_for(job_id) for job_id in orphans)) - log.info( - f"Cleared {len(legacy_job_ids)} job(s) left behind by the old scheduler" - ) + log.info(f"Cleared {len(orphans)} job(s) left behind by the old scheduler") # The registry, the lock and the scheduler's own keys go regardless: an # old scheduler that never held a job still registered itself. diff --git a/backend/tasks/cron_config.py b/backend/tasks/cron_config.py index 780dcf78c..a04e876f2 100644 --- a/backend/tasks/cron_config.py +++ b/backend/tasks/cron_config.py @@ -6,6 +6,7 @@ one off is a restart rather than an unschedule. from rq import cron +from config import TASK_RESULT_TTL from handler.redis_handler import QueuePrio from logger.logger import log from tasks.registry import SCHEDULED_TASKS @@ -15,12 +16,16 @@ for name, task in SCHEDULED_TASKS.items(): if not task.enabled or not task.cron_string: continue + # Every entry runs the same function, so without an explicit name they all + # share one cron identity and one job history. cron.register( run_task_by_name, QueuePrio.LOW.value, + name=name, kwargs={"name": name}, cron=task.cron_string, job_timeout=task.timeout, + result_ttl=TASK_RESULT_TTL, meta=task.job_meta, ) log.info(f"Scheduled '{name}' at '{task.cron_string}'") diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index 21396bbf4..78d77ecb6 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -1951,6 +1951,19 @@ class TestStopScan: for job in queued: job.cancel.assert_called_once() + async def test_a_second_stop_on_an_unwinding_scan_is_not_an_error( + self, mocker, emit, redis + ): + # The first Stop marks the job cancelled, but the worker still holds it + # while it unwinds, so the second Stop reaches it again. + running = make_job(SCAN_PLATFORMS_FUNC, status=JobStatus.CANCELED) + running.cancel.side_effect = InvalidJobOperation + patch_scan_jobs(mocker, running=running) + + await stop_scan_handler("sid") + + redis.set.assert_called_once_with(scan_module.STOP_SCAN_FLAG, 1) + async def test_cancels_watcher_scans(self, mocker, emit, redis): # Cancelling only the high priority queue would hand the worker the # watcher's scan the moment the running one unwinds. diff --git a/backend/tests/handler/test_redis_handler.py b/backend/tests/handler/test_redis_handler.py index 6d9c3147e..8ccecde33 100644 --- a/backend/tests/handler/test_redis_handler.py +++ b/backend/tests/handler/test_redis_handler.py @@ -5,6 +5,7 @@ from rq.exceptions import DeserializationError, InvalidJobOperation, NoSuchJobEr from rq.job import Job, JobStatus from handler.redis_handler import ( + cancel_job, get_job_func_name, get_job_kwargs, get_job_status, @@ -77,6 +78,21 @@ class TestGetJobStatus: assert get_job_status(job) is None +class TestCancelJob: + def test_cancels_a_live_job(self): + job = make_job() + + assert cancel_job(job) is True + job.cancel.assert_called_once() + + def test_tolerates_a_job_cancelled_by_an_earlier_call(self): + # Stopping a scan twice reaches the running job again while it unwinds. + job = make_job() + job.cancel.side_effect = InvalidJobOperation + + assert cancel_job(job) is False + + class TestGetWorkerCurrentJob: @staticmethod def _worker(**kwargs) -> MagicMock: diff --git a/backend/tests/tasks/test_cron_config.py b/backend/tests/tasks/test_cron_config.py index 54df7d361..b306a4386 100644 --- a/backend/tests/tasks/test_cron_config.py +++ b/backend/tests/tasks/test_cron_config.py @@ -2,6 +2,7 @@ import importlib import pytest +from config import TASK_RESULT_TTL from tasks import cron_config from tasks.registry import SCHEDULED_TASKS from tasks.tasks import run_task_by_name @@ -43,6 +44,23 @@ class TestCronConfig: assert kwargs["kwargs"] == {"name": "test_task"} assert kwargs["cron"] == "0 4 * * *" + def test_each_entry_gets_its_own_cron_identity(self, mocker, registered): + # Every entry runs the same function, so an unnamed one would inherit + # that func name and share one job history with all the others. + register = registered( + {"first": _task(mocker), "second": _task(mocker)}, + ) + + names = [call.kwargs["name"] for call in register.call_args_list] + assert names == ["first", "second"] + + def test_a_finished_run_is_kept_as_long_as_a_manual_one(self, mocker, registered): + # rq.cron always passes a result_ttl, so leaving it out means its 500s + # default rather than the worker's setting. + register = registered({"test_task": _task(mocker)}) + + assert register.call_args.kwargs["result_ttl"] == TASK_RESULT_TTL + def test_skips_a_disabled_task(self, mocker, registered): assert registered({"off": _task(mocker, enabled=False)}).call_count == 0