From fc8cfbc6f177acbeeff485409fb79c09d3f77c75 Mon Sep 17 00:00:00 2001 From: zurdi Date: Mon, 24 Aug 2026 21:01:13 +0200 Subject: [PATCH] feat(scan): add a files scan that reconciles rom folders incrementally Files added to an already-scanned folder ROM could only be picked up by a complete or hashes rescan, which rehash every known file. The new `files` scan type scans new games like quick and re-lists the files of existing folder ROMs, hashing only new or changed files and recomputing the ROM-level hashes only when a top-level file changed. Per-rom update and unmatched scans reuse the same incremental mode, and the filesystem watcher enqueues it instead of quick. Also stores rom_files.last_modified as Double (MariaDB FLOAT rounds a current mtime to about 128 seconds), adds the CHEAT value missing from the PostgreSQL category enum, maps `patches/` to the patch category and excludes upload temp files from scans. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_017WbesTQXohyAWWcLV5iiEN --- .../versions/0117_rom_files_mtime_double.py | 41 +++ .../versions/0118_rom_category_cheat_pg.py | 37 +++ backend/config/config_manager.py | 1 + backend/endpoints/responses/__init__.py | 2 + backend/endpoints/sockets/scan.py | 130 +++++--- backend/handler/database/roms_handler.py | 24 +- backend/handler/filesystem/roms_handler.py | 186 +++++++++-- backend/handler/rom_files.py | 114 +++++++ backend/handler/scan_handler.py | 1 + backend/tests/endpoints/sockets/test_scan.py | 310 ++++++++++++++++++ .../handler/database/test_roms_handler.py | 42 +++ .../handler/filesystem/test_roms_handler.py | 286 +++++++++++++++- backend/tests/handler/test_rom_files.py | 188 +++++++++++ backend/tests/test_watcher.py | 13 +- backend/watcher.py | 2 +- docs/BACKEND_ARCHITECTURE.md | 17 +- 16 files changed, 1308 insertions(+), 86 deletions(-) create mode 100644 backend/alembic/versions/0117_rom_files_mtime_double.py create mode 100644 backend/alembic/versions/0118_rom_category_cheat_pg.py create mode 100644 backend/handler/rom_files.py create mode 100644 backend/tests/handler/test_rom_files.py diff --git a/backend/alembic/versions/0117_rom_files_mtime_double.py b/backend/alembic/versions/0117_rom_files_mtime_double.py new file mode 100644 index 000000000..34425717b --- /dev/null +++ b/backend/alembic/versions/0117_rom_files_mtime_double.py @@ -0,0 +1,41 @@ +"""Store rom_files.last_modified with full precision + +`last_modified` was created as a single-precision float, which on MariaDB and +MySQL rounds a current mtime to the nearest 128 seconds. Incremental file +scans compare it with the mtime on disk, so it needs the double precision the +rest of the stack already uses. + +Revision ID: 0117_rom_files_mtime_double +Revises: 0116_sigil_title_ids +Create Date: 2026-08-24 00:00:00.000000 + +""" + +import sqlalchemy as sa +from alembic import op + +# revision identifiers, used by Alembic. +revision = "0117_rom_files_mtime_double" +down_revision = "0116_sigil_title_ids" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table("rom_files", schema=None) as batch_op: + batch_op.alter_column( + "last_modified", + existing_type=sa.Float(), + type_=sa.Double(), + existing_nullable=True, + ) + + +def downgrade() -> None: + with op.batch_alter_table("rom_files", schema=None) as batch_op: + batch_op.alter_column( + "last_modified", + existing_type=sa.Double(), + type_=sa.Float(), + existing_nullable=True, + ) diff --git a/backend/alembic/versions/0118_rom_category_cheat_pg.py b/backend/alembic/versions/0118_rom_category_cheat_pg.py new file mode 100644 index 000000000..887da1410 --- /dev/null +++ b/backend/alembic/versions/0118_rom_category_cheat_pg.py @@ -0,0 +1,37 @@ +"""Add the CHEAT rom_files category to the PostgreSQL enum + +Migration 0067 created the value with `ENUM.create(checkfirst=True)`, which +is a no-op once the type exists, so PostgreSQL databases never received it +and every cheat file failed to insert during scans. MariaDB and MySQL got it +through the column rewrite and need nothing here. + +Revision ID: 0118_rom_category_cheat_pg +Revises: 0117_rom_files_mtime_double +Create Date: 2026-08-24 00:00:00.000000 + +""" + +from alembic import op + +from utils.database import is_postgresql + +# revision identifiers, used by Alembic. +revision = "0118_rom_category_cheat_pg" +down_revision = "0117_rom_files_mtime_double" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + if not is_postgresql(op.get_bind()): + return + + # `ALTER TYPE ... ADD VALUE` must run outside a transaction in PostgreSQL. + with op.get_context().autocommit_block(): + op.execute("ALTER TYPE romfilecategory ADD VALUE IF NOT EXISTS 'CHEAT'") + + +def downgrade() -> None: + # PostgreSQL cannot remove enum values, and the other backends are + # untouched by the upgrade. + pass diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index 3a49bad22..ec5f14c25 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -39,6 +39,7 @@ DEFAULT_EXCLUDED_EXTENSIONS: Final = [ "log", "cache", "crdownload", + "assembling", ] DEFAULT_EXCLUDED_FILES: Final = [ ".DS_Store", diff --git a/backend/endpoints/responses/__init__.py b/backend/endpoints/responses/__init__.py index b8a7647e8..783007f0b 100644 --- a/backend/endpoints/responses/__init__.py +++ b/backend/endpoints/responses/__init__.py @@ -16,6 +16,8 @@ class ScanStats(TypedDict): identified_roms: int scanned_firmware: int new_firmware: int + updated_roms: int + new_files: int class ScanTaskMeta(TypedDict): diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index 540d35c94..fb6dc1b32 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -55,6 +55,7 @@ from handler.redis_handler import ( redis_client, scan_queue, ) +from handler.rom_files import HashPolicy, loaded_rom_files, refresh_rom_files from handler.scan_handler import ( MetadataSource, ScanType, @@ -91,7 +92,7 @@ STOP_SCAN_FLAG: Final = "scan:stop" 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_name": f"{scan_type.value.replace('_', ' ').title()} Scan", "task_type": TaskType.SCAN.value, } @@ -151,6 +152,8 @@ class ScanStats: identified_roms: int = 0 scanned_firmware: int = 0 new_firmware: int = 0 + updated_roms: int = 0 + new_files: int = 0 def __post_init__(self): # Lock for thread-safe updates @@ -187,6 +190,8 @@ class ScanStats: "identified_roms": self.identified_roms, "scanned_firmware": self.scanned_firmware, "new_firmware": self.new_firmware, + "updated_roms": self.updated_roms, + "new_files": self.new_files, } @@ -248,6 +253,28 @@ async def _identify_firmware( return 1 if not firmware else 0 +# `files` is left out so a scan does not ship every file row of every rom. +SCANNING_ROM_EXCLUDE: Final = { + "created_at", + "updated_at", + "rom_user", + "last_modified", + "files", + "sibling_roms", +} + + +async def _emit_scanning_rom( + socket_manager: socketio.AsyncRedisManager, rom: Rom +) -> None: + await socket_manager.emit( + "scan:scanning_rom", + SimpleRomSchema.from_orm_with_factory(rom).model_dump( + exclude=SCANNING_ROM_EXCLUDE + ), + ) + + def should_scan_rom( scan_type: ScanType, rom: Rom | None, @@ -270,11 +297,16 @@ def should_scan_rom( # This logic is tricky so only touch it if you know what you're doing""" should_scan = bool( # Any new roms should be scanned - (scan_type in {ScanType.NEW_PLATFORMS, ScanType.QUICK} and not rom) + ( + scan_type in {ScanType.NEW_PLATFORMS, ScanType.QUICK, ScanType.FILES} + and not rom + ) # Complete rescan should scan all roms or (scan_type == ScanType.COMPLETE) # Hashes rescan should scan all roms to update the hashes or (scan_type == ScanType.HASHES) + # Files rescan reconciles every existing rom's files with disk + or (scan_type == ScanType.FILES) or ( rom and ( @@ -347,6 +379,31 @@ def _should_reparse_tags( return bool(scan_type == ScanType.COMPLETE or (rom and rom.id in roms_ids)) +def _should_hash_incrementally( + scan_type: ScanType, + rom: Rom | None, + roms_ids: list[int], +) -> bool: + """Decide if an existing rom's unchanged files may keep their stored hashes + + Only COMPLETE and HASHES promise to re-read every byte. + + Args: + scan_type (ScanType): Type of scan to be performed. + rom (Rom | None): The rom whose files are rebuilt. + roms_ids (list[int]): List of selected roms to be scanned. + """ + + return bool( + scan_type == ScanType.FILES + or ( + scan_type in (ScanType.UPDATE, ScanType.UNMATCHED) + and rom + and rom.id in roms_ids + ) + ) + + def _should_hash_firmware( scan_type: ScanType, firmware: Firmware | None, @@ -495,6 +552,27 @@ async def _identify_rom( ) return + # A files scan only reconciles an existing entry's files with disk; the + # metadata pipeline below is for new entries and the other scan types. + if not newly_added and not reassociated and scan_type == ScanType.FILES: + refreshed = await refresh_rom_files(rom, hash_policy=HashPolicy.INCREMENTAL) + await scan_stats.increment( + socket_manager=socket_manager, + scanned_roms=1, + updated_roms=1 if refreshed.changed else 0, + new_files=refreshed.new_files, + ) + if refreshed.changed: + log.info( + f"Files of {hl(rom.name or rom.fs_name, color=BLUE)} refreshed: " + f"{refreshed.new_files} new, {refreshed.updated_files} updated, " + f"{refreshed.removed_files} removed" + ) + hydrated_rom = db_rom_handler.get_rom(rom.id) + if hydrated_rom is not None: + await _emit_scanning_rom(socket_manager, hydrated_rom) + return + # Re-read the filename tags onto an existing entry. Written onto the instance # rather than through update_rom because scan_rom carries these columns # forward from the rom it is handed, and merging its result is what persists @@ -524,6 +602,11 @@ async def _identify_rom( calculate_hashes=calculate_hashes, extract_title_ids=extract_title_ids, embed_title_ids=embed_title_ids, + existing_files=( + loaded_rom_files(rom) + if _should_hash_incrementally(scan_type, rom, roms_ids) + else None + ), ) _apply_scanned_values(fs_rom, parsed_rom_files) # Keep the in-memory rom's identity matching the renamed file. @@ -583,19 +666,7 @@ async def _identify_rom( _added_rom = db_rom_handler.add_rom(scanned_rom) if _added_rom.is_identified: - await socket_manager.emit( - "scan:scanning_rom", - SimpleRomSchema.from_orm_with_factory(_added_rom).model_dump( - exclude={ - "created_at", - "updated_at", - "rom_user", - "last_modified", - "files", - "sibling_roms", - } - ), - ) + await _emit_scanning_rom(socket_manager, _added_rom) if should_update_files: # Reconcile against the existing rows instead of replacing them, so file @@ -619,19 +690,7 @@ async def _identify_rom( metadata_sources=metadata_sources, ) - await socket_manager.emit( - "scan:scanning_rom", - SimpleRomSchema.from_orm_with_factory(_added_rom).model_dump( - exclude={ - "created_at", - "updated_at", - "rom_user", - "last_modified", - "files", - "sibling_roms", - } - ), - ) + await _emit_scanning_rom(socket_manager, _added_rom) async def _scan_selected_roms( @@ -848,6 +907,7 @@ async def _identify_platform( roms_by_fs_name = db_rom_handler.get_roms_by_fs_name( platform_id=platform.id, fs_names={fs_rom["fs_name"] for fs_rom in fs_roms_batch}, + with_files=scan_type == ScanType.FILES, ) # Separate skipped ROMs from those that need scanning @@ -889,19 +949,7 @@ async def _identify_platform( if hydrated_rom is None: continue - await socket_manager.emit( - "scan:scanning_rom", - SimpleRomSchema.from_orm_with_factory(hydrated_rom).model_dump( - exclude={ - "created_at", - "updated_at", - "rom_user", - "last_modified", - "files", - "sibling_roms", - } - ), - ) + await _emit_scanning_rom(socket_manager, hydrated_rom) # Process only ROMs that actually need scanning scan_tasks = [ diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index c128ff666..9c55c239b 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -1876,6 +1876,7 @@ class DBRomsHandler(DBBaseHandler): self, platform_id: int, fs_names: Iterable[str], + with_files: bool = False, session: Session = None, # type: ignore ) -> dict[str, Rom]: """Retrieve a dictionary of roms by their filesystem names. @@ -1883,15 +1884,21 @@ class DBRomsHandler(DBBaseHandler): Eager-loads only `platform` (used downstream by the scan loop via `rom.platform_slug` / `rom.platform.fs_slug`). This deliberately avoids `with_details`, whose full relationship eager-load is - wasted work for the scan-skip decision on large platforms. + wasted work for the scan-skip decision on large platforms. Scans that + reconcile files opt into `with_files` to load them once per batch + instead of once per rom. """ + query = select(Rom).options(selectinload(Rom.platform)) + if with_files: + query = query.options( + selectinload(Rom.files).options( + joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name), + selectinload(RomFile.track_meta), + ) + ) roms = ( session.scalars( - select(Rom) - .options( - selectinload(Rom.platform), - ) - .where( + query.where( and_( Rom.platform_id == platform_id, Rom.fs_name.in_(fs_names), @@ -2367,7 +2374,10 @@ class DBRomsHandler(DBBaseHandler): session.scalars( select(RomFile) .filter_by(rom_id=rom_id) - .options(joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name)) + .options( + joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name), + selectinload(RomFile.track_meta), + ) ) .unique() .all() diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 0034fd112..f2c0689b5 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -4,7 +4,9 @@ import fnmatch import hashlib import os import re +import struct import zlib +from collections.abc import Mapping, Sequence from dataclasses import dataclass from pathlib import Path from typing import Any, Final, NotRequired, TypedDict @@ -21,6 +23,7 @@ from config import LIBRARY_BASE_PATH from config.config_manager import ( DEFAULT_EXCLUDED_EXTENSIONS, DEFAULT_EXCLUDED_FILES, + Config, ) from config.config_manager import config_manager as cm from exceptions.fs_exceptions import ( @@ -124,8 +127,10 @@ class FileHash(TypedDict): chd_sha1_hash: str -def category_matches(category: str, path_parts: list[str]): - return category in path_parts or f"{category}s" in path_parts +def category_matches(category: str, path_parts: list[str]) -> bool: + return any( + form in path_parts for form in (category, f"{category}s", f"{category}es") + ) DEFAULT_CRC_C = 0 @@ -187,6 +192,9 @@ class ParsedRomFiles: md5_hash: str sha1_hash: str ra_hash: str + # False when an incremental listing found the top-level files untouched, in + # which case the hashes above are the stored ones rather than recomputed. + top_level_changed: bool = True title_id: str | None = None save_target: str | None = None save_target_layout: SaveTargetLayout | None = None @@ -195,6 +203,67 @@ class ParsedRomFiles: renamed_rom_fs_name: str | None = None +RomFileKey = tuple[str, str] +DirEntry = tuple[Path, str, os.stat_result] + + +def rom_file_key(rom_file: RomFile) -> RomFileKey: + return (rom_file.file_path, rom_file.file_name) + + +def mtime_matches(stored: float | None, actual: float) -> bool: + """Compare a stored mtime with the one on disk, also accepting rows written + through the former single-precision column.""" + if stored is None: + return False + return stored == actual or stored == struct.unpack("f", struct.pack("f", actual))[0] + + +def rom_file_unchanged( + row: RomFile, *, size: int, mtime: float, hashable: bool +) -> bool: + """Whether a stored row still describes the file on disk, so its hashes can + be reused instead of re-reading the bytes.""" + return ( + row.file_size_bytes == size + and mtime_matches(row.last_modified, mtime) + and (not hashable or bool(row.md5_hash)) + ) + + +def _flat_file_unchanged(row: RomFile, file_path: Path, hashable: bool) -> bool: + try: + st = os.stat(file_path) + except OSError: + return False + return rom_file_unchanged( + row, size=st.st_size, mtime=st.st_mtime, hashable=hashable + ) + + +def _top_level_changed( + entries: list[DirEntry], + rom_dir: Path, + rel_rom_dir: str, + existing_by_key: Mapping[RomFileKey, RomFile], + hashable: bool, +) -> bool: + """Whether a top-level file was added, changed or removed since the rows + were written, which forces re-reading that whole level for the ROM hash.""" + seen: set[RomFileKey] = set() + for f_path, file_name, st in entries: + if f_path != rom_dir: + continue + key = (rel_rom_dir, file_name) + seen.add(key) + row = existing_by_key.get(key) + if row is None or not rom_file_unchanged( + row, size=st.st_size, mtime=st.st_mtime, hashable=hashable + ): + return True + return any(key[0] == rel_rom_dir and key not in seen for key in existing_by_key) + + # File categories that never hold a ROM binary, so sigil has nothing to read. NON_BINARY_FILE_CATEGORIES: Final = DOCUMENT_CATEGORIES | { RomFileCategory.SOUNDTRACK, @@ -396,13 +465,50 @@ class FSRomsHandler(FSHandler): archive_members=archive_members, ) + def is_excluded_multi_part( + self, file_name: str, cnfg: Config | None = None + ) -> bool: + """Whether the scanner ignores a file with this name inside a ROM folder.""" + cnfg = cnfg or cm.get_config() + file_name_lower = file_name.lower() + if any( + file_name_lower.endswith(f".{ext}") for ext in cnfg.EXCLUDED_MULTI_PARTS_EXT + ): + return True + return any( + file_name == exc_name or fnmatch.fnmatch(file_name, exc_name) + for exc_name in cnfg.EXCLUDED_MULTI_PARTS_FILES + ) + + def _list_rom_dir(self, rom_dir: Path, cnfg: Config) -> list[DirEntry]: + """Every file under a ROM folder, at any depth, with its stat.""" + entries: list[DirEntry] = [] + for f_path, file_name in iter_files(str(rom_dir), recursive=True): + if self.is_excluded_multi_part(file_name, cnfg): + continue + try: + entries.append((f_path, file_name, os.stat(Path(f_path, file_name)))) + except OSError as exc: + log.warning(f"Skipping unreadable file {f_path / file_name}: {exc}") + return entries + async def get_rom_files( self, rom: Rom, calculate_hashes: bool = True, extract_title_ids: bool = True, embed_title_ids: bool = False, + *, + existing_files: Sequence[RomFile] | None = None, ) -> ParsedRomFiles: + """Build the ROM's file rows from disk. + + Args: + existing_files: The rows currently stored for the ROM. When given, + files whose size and mtime still match are returned as those + very rows with their hashes untouched, and the ROM-level hashes + are only recomputed when a top-level file changed. + """ from adapters.services.rahasher import RAHasherService from handler.metadata import meta_ra_handler @@ -459,21 +565,32 @@ class FSRomsHandler(FSHandler): return new_name cnfg = cm.get_config() - excluded_file_names = cnfg.EXCLUDED_MULTI_PARTS_FILES - excluded_file_exts = cnfg.EXCLUDED_MULTI_PARTS_EXT + existing_by_key: Mapping[RomFileKey, RomFile] | None = ( + {rom_file_key(f): f for f in existing_files} + if existing_files is not None + else None + ) rom_crc_c = 0 rom_md5_h = hashlib.md5(usedforsecurity=False) if calculate_hashes else None rom_sha1_h = hashlib.sha1(usedforsecurity=False) if calculate_hashes else None rom_ra_h = "" + top_level_changed = True rom_dir = Path(abs_fs_path, rom.fs_name) rom_ext = f".{rom.fs_extension.lower()}" if rom.fs_extension else "" # Check if rom is a multi-part rom if await AnyioPath(f"{abs_fs_path}/{rom.fs_name}").is_dir(): + rel_rom_dir = str(rom_dir.relative_to(self.base_path)) + entries = await asyncio.to_thread(self._list_rom_dir, rom_dir, cnfg) + if existing_by_key is not None: + top_level_changed = _top_level_changed( + entries, rom_dir, rel_rom_dir, existing_by_key, hashable_platform + ) + # Calculate the RA hash if the platform has a slug that matches a known RA slug - if calculate_hashes: + if calculate_hashes and top_level_changed: ra_platform = meta_ra_handler.get_platform(rom.platform_slug) if ra_platform and ra_platform["ra_id"]: # RAHasher can't process CHD files via the /* wildcard and instead expects @@ -498,26 +615,29 @@ class FSRomsHandler(FSHandler): ra_path, ) - for f_path, file_name in iter_files( - f"{abs_fs_path}/{rom.fs_name}", recursive=True - ): - # Check if file is excluded by extension. - file_name_lower = file_name.lower() - if any( - file_name_lower.endswith("." + ext) for ext in excluded_file_exts + for f_path, file_name, st in entries: + is_top_level = f_path == rom_dir + rel_dir = f_path.relative_to(self.base_path) + row = ( + existing_by_key.get((str(rel_dir), file_name)) + if existing_by_key is not None + else None + ) + # An unchanged top-level file is still re-read when its level + # changed, since the ROM-level hash spans every file in it. + if ( + row is not None + and not (is_top_level and top_level_changed) + and rom_file_unchanged( + row, + size=st.st_size, + mtime=st.st_mtime, + hashable=hashable_platform, + ) ): + rom_files.append(row) continue - # Check if the file name matches a pattern in the excluded list. - if any( - file_name == exc_name or fnmatch.fnmatch(file_name, exc_name) - for exc_name in excluded_file_names - ): - continue - - # Check if this is a top-level file (not in a subdirectory) - is_top_level = f_path.samefile(Path(abs_fs_path, rom.fs_name)) - abs_file_path = Path(f_path, file_name) if hashable_platform: @@ -560,9 +680,11 @@ class FSRomsHandler(FSHandler): rom_file = self._build_rom_file( rom=rom, - rom_path=f_path.relative_to(self.base_path), + rom_path=rel_dir, file_name=file_name, file_hash=file_hash, + file_size_bytes=st.st_size, + last_modified=st.st_mtime, ) # Extract from every ROM file (base, updates and DLC in # subfolders), not just the top-level one. @@ -572,6 +694,14 @@ class FSRomsHandler(FSHandler): ): await _extract_title_id(rom_file) rom_files.append(rom_file) + elif ( + existing_by_key is not None + and (flat_row := existing_by_key.get((rel_roms_path, rom.fs_name))) + is not None + and _flat_file_unchanged(flat_row, rom_dir, hashable_platform) + ): + rom_files.append(flat_row) + top_level_changed = False 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 @@ -724,6 +854,16 @@ class FSRomsHandler(FSHandler): rom.platform_slug, sigil_extractions ) + if not top_level_changed: + return ParsedRomFiles( + rom_files=rom_files, + crc_hash=rom.crc_hash or "", + md5_hash=rom.md5_hash or "", + sha1_hash=rom.sha1_hash or "", + ra_hash=rom.ra_hash or "", + top_level_changed=False, + ) + return ParsedRomFiles( rom_files=rom_files, crc_hash=crc32_to_hex(rom_crc_c) if rom_crc_c != DEFAULT_CRC_C else "", diff --git a/backend/handler/rom_files.py b/backend/handler/rom_files.py new file mode 100644 index 000000000..bfe0b556f --- /dev/null +++ b/backend/handler/rom_files.py @@ -0,0 +1,114 @@ +import enum +from dataclasses import dataclass +from typing import Any + +from sqlalchemy import inspect as sa_inspect + +from config.config_manager import config_manager as cm +from handler.database import db_rom_handler +from handler.filesystem import fs_rom_handler +from handler.filesystem.roms_handler import RomFileKey, rom_file_key +from handler.scan_handler import persist_soundtrack_cover +from logger.formatter import highlight as hl +from logger.logger import log +from models.rom import Rom, RomFile +from utils.audio_tags import remove_persisted_cover + +ROM_LEVEL_HASH_COLUMNS = ("crc_hash", "md5_hash", "sha1_hash", "ra_hash") + + +class HashPolicy(enum.StrEnum): + FULL = "full" + INCREMENTAL = "incremental" + + +@dataclass(frozen=True) +class RomFilesRefresh: + files: list[RomFile] + new_files: int + updated_files: int + removed_files: int + top_level_changed: bool + rom_updates: dict[str, Any] + + @property + def changed(self) -> bool: + return bool(self.new_files or self.updated_files or self.removed_files) + + +def loaded_rom_files(rom: Rom) -> list[RomFile]: + """The ROM's file rows, fetched on demand when the relationship is unloaded.""" + if "files" not in sa_inspect(rom).unloaded: + return list(rom.files) + return db_rom_handler.rom_files_for_rom_id(rom.id) + + +async def refresh_rom_files( + rom: Rom, *, hash_policy: HashPolicy = HashPolicy.INCREMENTAL +) -> RomFilesRefresh: + """Reconcile a ROM's file rows with what is on disk. + + Args: + rom: A persisted ROM whose folder or file exists on disk. + hash_policy: INCREMENTAL keeps the stored hashes of unchanged files, + FULL re-reads every file. + Returns: + The persisted rows and what changed, so callers can report it. + """ + existing = loaded_rom_files(rom) + parsed = await fs_rom_handler.get_rom_files( + rom, + calculate_hashes=not cm.get_config().SKIP_HASH_CALCULATION, + existing_files=existing if hash_policy == HashPolicy.INCREMENTAL else None, + ) + if existing and not parsed.rom_files: + # A mount that dropped out would otherwise read as every file deleted. + log.warning( + f"{hl(rom.fs_name)} lists no files on disk, keeping its " + f"{len(existing)} recorded files" + ) + return RomFilesRefresh([], 0, 0, 0, False, {}) + + existing_keys = {rom_file_key(f) for f in existing} + reused_ids = {id(f) for f in existing} + new_keys: set[RomFileKey] = set() + updated_keys: set[RomFileKey] = set() + for scanned in parsed.rom_files: + if id(scanned) in reused_ids: + continue + key = rom_file_key(scanned) + (updated_keys if key in existing_keys else new_keys).add(key) + removed_keys = existing_keys - {rom_file_key(f) for f in parsed.rom_files} + + files = list(parsed.rom_files) + if new_keys or updated_keys or removed_keys: + synced = db_rom_handler.sync_rom_files(rom.id, parsed.rom_files) + for cover_path in synced.orphaned_cover_paths: + remove_persisted_cover(cover_path) + for saved in synced.files: + if rom_file_key(saved) in new_keys or rom_file_key(saved) in updated_keys: + persist_soundtrack_cover(saved, rom) + files = synced.files + + rom_updates: dict[str, Any] = {} + fs_size_bytes = sum(f.file_size_bytes for f in parsed.rom_files) + if fs_size_bytes != rom.fs_size_bytes: + rom_updates["fs_size_bytes"] = fs_size_bytes + if parsed.top_level_changed: + for column in ROM_LEVEL_HASH_COLUMNS: + value = getattr(parsed, column) + if value != (getattr(rom, column) or ""): + rom_updates[column] = value + if rom.missing_from_fs: + rom_updates["missing_from_fs"] = False + if rom_updates: + db_rom_handler.update_rom(rom.id, rom_updates) + + return RomFilesRefresh( + files=files, + new_files=len(new_keys), + updated_files=len(updated_keys), + removed_files=len(removed_keys), + top_level_changed=parsed.top_level_changed, + rom_updates=rom_updates, + ) diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index a2f79ee8a..c2e1e23f5 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -91,6 +91,7 @@ class ScanType(enum.StrEnum): UNMATCHED = "unmatched" COMPLETE = "complete" HASHES = "hashes" + FILES = "files" @enum.unique diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index f561c0a0b..454224e7b 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -18,6 +18,7 @@ from endpoints.sockets.scan import ( ScanStats, _identify_rom, _scan_selected_roms, + _should_hash_incrementally, _should_reparse_tags, reject_unauthorized_scan, scan_handler, @@ -36,6 +37,7 @@ from handler.filesystem.roms_handler import ( ParsedTags, ) from handler.metadata.base_handler import UniversalPlatformSlug as UPS +from handler.rom_files import HashPolicy, RomFilesRefresh from handler.scan_handler import MetadataSource, ScanType from handler.scan_jobs import SCAN_PLATFORMS_FUNC from models.firmware import Firmware @@ -2232,3 +2234,311 @@ class TestReportScanFailure: ) emit.assert_called_once() + + +def test_scan_stats_reports_file_counters(): + stats = ScanStats(updated_roms=2, new_files=5) + + assert stats.to_dict()["updated_roms"] == 2 + assert stats.to_dict()["new_files"] == 5 + + +class TestShouldScanRomFiles: + def test_files_scan_covers_new_and_existing_roms(self, rom: Rom): + assert should_scan_rom(ScanType.FILES, None, [], []) is True + assert should_scan_rom(ScanType.FILES, rom, [], []) is True + + def test_scoped_files_scan_respects_roms_ids(self, rom: Rom): + assert should_scan_rom(ScanType.FILES, None, [rom.id], []) is False + assert should_scan_rom(ScanType.FILES, rom, [rom.id + 99], []) is False + assert should_scan_rom(ScanType.FILES, rom, [rom.id], []) is True + + +class TestShouldHashIncrementally: + def test_files_scan_is_incremental(self, rom: Rom): + assert _should_hash_incrementally(ScanType.FILES, rom, []) is True + + def test_selected_metadata_scans_are_incremental(self, rom: Rom): + assert _should_hash_incrementally(ScanType.UPDATE, rom, [rom.id]) is True + assert _should_hash_incrementally(ScanType.UNMATCHED, rom, [rom.id]) is True + assert _should_hash_incrementally(ScanType.UPDATE, rom, []) is False + assert _should_hash_incrementally(ScanType.UPDATE, rom, [rom.id + 1]) is False + + @pytest.mark.parametrize("scan_type", [ScanType.COMPLETE, ScanType.HASHES]) + def test_full_rescans_read_every_file(self, rom: Rom, scan_type: ScanType): + assert _should_hash_incrementally(scan_type, rom, [rom.id]) is False + + +@pytest.fixture +def identify_harness(mocker): + """`_identify_rom` with every collaborator stubbed, so a scan type's + control flow can be asserted without a database or a filesystem.""" + 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="test/roms") + mocker.patch.object(fs, "get_file_name_with_no_tags", return_value="Game") + get_rom_files = mocker.patch.object( + fs, + "get_rom_files", + AsyncMock( + return_value=ParsedRomFiles( + rom_files=[], crc_hash="", md5_hash="", sha1_hash="", ra_hash="" + ) + ), + ) + + 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) + + scan_rom = mocker.patch.object( + scan_module, "scan_rom", AsyncMock(return_value=MagicMock(is_identified=False)) + ) + + mocker.patch.object(scan_module, "fs_resource_handler", new=AsyncMock()) + mocker.patch.object(scan_module, "download_rom_resources", new=AsyncMock()) + mocker.patch.object(scan_module, "SimpleRomSchema", MagicMock()) + + db = mocker.patch.object(scan_module, "db_rom_handler") + db.add_rom.return_value = MagicMock( + is_identified=False, id=1, url_cover="", url_manual="", url_screenshots=[] + ) + db.get_matching_missing_rom.return_value = None + db.sync_rom_files.return_value = SyncedRomFiles(files=[], orphaned_cover_paths=[]) + + loaded_rom_files = mocker.patch.object( + scan_module, "loaded_rom_files", return_value=["stored-row"] + ) + refresh = mocker.patch.object( + scan_module, + "refresh_rom_files", + AsyncMock( + return_value=RomFilesRefresh( + files=[], + new_files=2, + updated_files=0, + removed_files=1, + top_level_changed=False, + rom_updates={}, + ) + ), + ) + + def existing_rom() -> Rom: + rom = Rom(platform_id=1, fs_name="Game", fs_path="test/roms") + rom.id = 1 + return rom + + async def run( + rom: Rom | None, + scan_type: ScanType, + roms_ids: list[int], + socket_manager: AsyncMock | None = None, + scan_stats: AsyncMock | None = None, + ) -> None: + fs_rom: FSRom = { + "fs_name": "Game", + "flat": False, + "nested": True, + "files": [], + "crc_hash": "", + "md5_hash": "", + "sha1_hash": "", + "ra_hash": "", + } + platform = Platform(name="Test", slug="test", fs_slug="test") + platform.id = 1 + await _identify_rom( + platform=platform, + fs_rom=fs_rom, + rom=rom, + scan_type=scan_type, + roms_ids=roms_ids, + metadata_sources=[], + launchbox_remote_enabled=False, + playmatch_enabled=False, + socket_manager=socket_manager or AsyncMock(), + scan_stats=scan_stats or AsyncMock(), + ) + + return SimpleNamespace( + db=db, + scan_rom=scan_rom, + get_rom_files=get_rom_files, + loaded_rom_files=loaded_rom_files, + refresh=refresh, + existing_rom=existing_rom, + run=run, + ) + + +class TestIdentifyRomFiles: + """A files scan hands an existing rom to `refresh_rom_files` and skips the + metadata pipeline; a rom not yet in the database goes the regular way.""" + + async def test_existing_rom_only_refreshes_its_files(self, identify_harness): + rom = identify_harness.existing_rom() + socket_manager = AsyncMock() + scan_stats = AsyncMock() + + await identify_harness.run( + rom, + ScanType.FILES, + [], + socket_manager=socket_manager, + scan_stats=scan_stats, + ) + + identify_harness.refresh.assert_awaited_once_with( + rom, hash_policy=HashPolicy.INCREMENTAL + ) + identify_harness.scan_rom.assert_not_called() + identify_harness.db.add_rom.assert_not_called() + scan_stats.increment.assert_awaited_once_with( + socket_manager=socket_manager, scanned_roms=1, updated_roms=1, new_files=2 + ) + identify_harness.db.get_rom.assert_called_once_with(rom.id) + socket_manager.emit.assert_awaited_once() + assert socket_manager.emit.await_args.args[0] == "scan:scanning_rom" + + async def test_unchanged_rom_emits_nothing(self, identify_harness): + identify_harness.refresh.return_value = RomFilesRefresh( + files=[], + new_files=0, + updated_files=0, + removed_files=0, + top_level_changed=False, + rom_updates={}, + ) + socket_manager = AsyncMock() + scan_stats = AsyncMock() + + await identify_harness.run( + identify_harness.existing_rom(), + ScanType.FILES, + [], + socket_manager=socket_manager, + scan_stats=scan_stats, + ) + + scan_stats.increment.assert_awaited_once_with( + socket_manager=socket_manager, scanned_roms=1, updated_roms=0, new_files=0 + ) + identify_harness.db.get_rom.assert_not_called() + socket_manager.emit.assert_not_awaited() + + async def test_new_rom_takes_the_regular_path(self, identify_harness): + await identify_harness.run(None, ScanType.FILES, []) + + identify_harness.refresh.assert_not_called() + identify_harness.scan_rom.assert_awaited_once() + identify_harness.db.add_rom.assert_called() + + +class TestIdentifyRomIncrementalHashing: + """Selected-rom metadata scans hand the stored rows to the file rebuild so + unchanged files keep their hashes; full rescans read every file.""" + + async def test_selected_update_scan_passes_existing_files(self, identify_harness): + rom = identify_harness.existing_rom() + + await identify_harness.run(rom, ScanType.UPDATE, [rom.id]) + + identify_harness.loaded_rom_files.assert_called_once_with(rom) + kwargs = identify_harness.get_rom_files.await_args.kwargs + assert kwargs["existing_files"] == ["stored-row"] + + @pytest.mark.parametrize("scan_type", [ScanType.HASHES, ScanType.COMPLETE]) + async def test_full_rescans_rehash_everything(self, identify_harness, scan_type): + rom = identify_harness.existing_rom() + + await identify_harness.run(rom, scan_type, [rom.id]) + + kwargs = identify_harness.get_rom_files.await_args.kwargs + assert kwargs["existing_files"] is None + + +class TestIdentifyPlatformLoadsFilesForFilesScan: + """A files scan reconciles every existing rom's files, so their rows are + loaded with the batch lookup instead of one query per rom.""" + + @pytest.fixture + def patched(self, mocker): + mocker.patch.object( + scan_module, "redis_client", Mock(get=Mock(return_value=None)) + ) + + platform = Platform(name="Test", slug="test", fs_slug="test") + platform.id = 1 + platform.missing_from_fs = False + db_platform = mocker.patch.object(scan_module, "db_platform_handler") + db_platform.get_platform_by_fs_slug.return_value = platform + db_platform.add_platform.return_value = platform + + mocker.patch.object( + scan_module, "scan_platform", AsyncMock(return_value=platform) + ) + mocker.patch.object( + scan_module.PlatformSchema, + "model_validate", + return_value=Mock(model_dump=Mock(return_value={})), + ) + mocker.patch.object( + scan_module.fs_firmware_handler, + "get_firmware", + AsyncMock(return_value=[]), + ) + fs_rom: FSRom = { + "fs_name": "Game", + "flat": False, + "nested": True, + "files": [], + "crc_hash": "", + "md5_hash": "", + "sha1_hash": "", + "ra_hash": "", + } + mocker.patch.object( + scan_module.fs_rom_handler, "get_roms", AsyncMock(return_value=[fs_rom]) + ) + mocker.patch.object(scan_module, "_identify_rom", AsyncMock()) + + rom = Rom(fs_name="Game", platform_id=platform.id) + rom.id = 42 + db_rom = mocker.patch.object(scan_module, "db_rom_handler") + db_rom.get_roms_by_fs_name.return_value = {"Game": rom} + db_rom.get_missing_rom_ids.return_value = set() + db_rom.mark_missing_roms.return_value = [] + db_firmware = mocker.patch.object(scan_module, "db_firmware_handler") + db_firmware.mark_missing_firmware.return_value = [] + return db_rom + + @pytest.mark.parametrize( + "scan_type,with_files", [(ScanType.FILES, True), (ScanType.QUICK, False)] + ) + async def test_rows_are_loaded_only_for_files_scans( + self, patched, scan_type, with_files + ): + await scan_module._identify_platform( + platform_slug="test", + scan_type=scan_type, + fs_platforms=["test"], + roms_ids=[], + metadata_sources=[], + launchbox_remote_enabled=False, + playmatch_enabled=False, + socket_manager=AsyncMock(), + scan_stats=AsyncMock(), + ) + + assert patched.get_roms_by_fs_name.call_args.kwargs["with_files"] is with_files diff --git a/backend/tests/handler/database/test_roms_handler.py b/backend/tests/handler/database/test_roms_handler.py index 1e56525fc..8d152c676 100644 --- a/backend/tests/handler/database/test_roms_handler.py +++ b/backend/tests/handler/database/test_roms_handler.py @@ -5,6 +5,7 @@ the columns derived from `name` / `fs_name` in sync explicitly. """ import pytest +from sqlalchemy import inspect as sa_inspect from sqlalchemy.exc import IntegrityError from handler.database import ( @@ -460,3 +461,44 @@ class TestSyncRomFiles: assert synced.files == [] assert synced.orphaned_cover_paths == ["covers/track01.png"] + + +class TestScanFileLoaders: + """The scan loop reads rows off detached roms, so every relationship it + touches has to be eager-loaded by the lookup.""" + + def test_get_roms_by_fs_name_with_files_loads_rows_and_backref( + self, multi_file_rom: Rom, platform: Platform + ): + rom = db_rom_handler.get_roms_by_fs_name( + platform_id=platform.id, fs_names={multi_file_rom.fs_name}, with_files=True + )[multi_file_rom.fs_name] + + assert {f.file_name for f in rom.files} == {"disc1.bin", "disc2.bin"} + assert all(f.track_meta is None for f in rom.files) + assert all(f.rom.fs_name == rom.fs_name for f in rom.files) + + def test_get_roms_by_fs_name_leaves_files_unloaded_by_default( + self, multi_file_rom: Rom, platform: Platform + ): + rom = db_rom_handler.get_roms_by_fs_name( + platform_id=platform.id, fs_names={multi_file_rom.fs_name} + )[multi_file_rom.fs_name] + + assert "files" in sa_inspect(rom).unloaded + + def test_rom_files_for_rom_id_loads_track_meta(self, multi_file_rom: Rom): + files = db_rom_handler.rom_files_for_rom_id(multi_file_rom.id) + + assert len(files) == 2 + assert all("track_meta" not in sa_inspect(f).unloaded for f in files) + + +class TestSyncRomFilesWithReusedRows: + def test_rows_handed_back_are_a_noop(self, rom: Rom): + first = _sync(rom, [_scanned_file(rom, "a.bin")]) + + second = db_rom_handler.sync_rom_files(rom.id, first).files + + assert [f.id for f in second] == [f.id for f in first] + assert second[0].md5_hash == "md5" diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index 68541185c..d3f63e704 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -1,8 +1,10 @@ import hashlib import os import shutil +import struct import tempfile from pathlib import Path +from types import SimpleNamespace from unittest.mock import AsyncMock, Mock, patch import pytest @@ -11,12 +13,21 @@ 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 config.config_manager import ( + DEFAULT_EXCLUDED_EXTENSIONS, + LIBRARY_BASE_PATH, + Config, +) from handler.filesystem.base_handler import ( LANGUAGES_BY_SHORTCODE, REGIONS_BY_SHORTCODE, ) -from handler.filesystem.roms_handler import FileHash, FSRomsHandler +from handler.filesystem.roms_handler import ( + FileHash, + FSRomsHandler, + category_matches, + mtime_matches, +) from models.platform import Platform from models.rom import Rom, RomFile, RomFileCategory, SaveTargetLayout from utils.archives import extract_chd_hash @@ -2468,3 +2479,274 @@ class TestExtractCHDHashProperties: @given(data=st.binary()) def test_never_raises_on_arbitrary_bytes(self, data: bytes): _run_extract(data) + + +class TestIncrementalRomFiles: + """`existing_files` lets a rescan keep the hashes of files whose size and + mtime are unchanged, and only recompute the ROM-level hashes when a + top-level file changed.""" + + ROM_DIR = "n64/roms/Sonic" + + @pytest.fixture + def platform(self): + return Platform(name="Nintendo 64", slug="n64", fs_slug="n64") + + @pytest.fixture + def handler(self, tmp_path: Path): + handler = FSRomsHandler() + handler.base_path = tmp_path + return handler + + @pytest.fixture(autouse=True) + def patched(self, mocker): + config = Config( + EXCLUDED_PLATFORMS=[], + EXCLUDED_SINGLE_EXT=[], + EXCLUDED_SINGLE_FILES=[], + EXCLUDED_MULTI_FILES=[], + EXCLUDED_MULTI_PARTS_EXT=["tmp"], + EXCLUDED_MULTI_PARTS_FILES=[], + PLATFORMS_BINDING={}, + PLATFORMS_VERSIONS={}, + ROMS_FOLDER_NAME="roms", + FIRMWARE_FOLDER_NAME="bios", + ) + mocker.patch( + "handler.filesystem.roms_handler.cm.get_config", return_value=config + ) + ra = mocker.patch( + "adapters.services.rahasher.RAHasherService.calculate_hash", + AsyncMock(return_value="ra-hash"), + ) + return SimpleNamespace(ra=ra) + + def _rom(self, platform: Platform, fs_name: str = "Sonic", ext: str = "") -> Rom: + return Rom( + id=7, + fs_name=fs_name, + fs_path="n64/roms", + fs_extension=ext, + platform=platform, + crc_hash="stored-crc", + md5_hash="stored-md5", + sha1_hash="stored-sha1", + ra_hash="stored-ra", + ) + + def _write(self, handler: FSRomsHandler, rel: str, data: bytes) -> os.stat_result: + path = handler.base_path / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + return path.stat() + + def _row( + self, rom: Rom, rel_dir: str, name: str, st: os.stat_result, hashed: bool = True + ) -> RomFile: + return RomFile( + rom_id=rom.id, + file_name=name, + file_path=rel_dir, + file_size_bytes=st.st_size, + last_modified=st.st_mtime, + crc_hash="row-crc" if hashed else "", + md5_hash="row-md5" if hashed else "", + sha1_hash="row-sha1" if hashed else "", + ) + + def _folder_rom(self, handler: FSRomsHandler, platform: Platform): + rom = self._rom(platform) + game = self._write(handler, f"{self.ROM_DIR}/game.n64", b"game bytes") + hack = self._write(handler, f"{self.ROM_DIR}/hack/patched.n64", b"hack bytes") + rows = [ + self._row(rom, self.ROM_DIR, "game.n64", game), + self._row(rom, f"{self.ROM_DIR}/hack", "patched.n64", hack), + ] + return rom, rows + + async def test_unchanged_rows_are_reused_without_hashing( + self, handler, platform, patched, mocker + ): + rom, rows = self._folder_rom(handler, platform) + hasher = mocker.spy(handler, "_calculate_rom_hashes") + + parsed = await handler.get_rom_files(rom, existing_files=rows) + + assert {id(f) for f in parsed.rom_files} == {id(r) for r in rows} + assert parsed.top_level_changed is False + assert (parsed.crc_hash, parsed.md5_hash, parsed.sha1_hash, parsed.ra_hash) == ( + "stored-crc", + "stored-md5", + "stored-sha1", + "stored-ra", + ) + hasher.assert_not_called() + patched.ra.assert_not_called() + + async def test_new_nested_file_is_hashed_alone( + self, handler, platform, patched, mocker + ): + rom, rows = self._folder_rom(handler, platform) + self._write(handler, f"{self.ROM_DIR}/hack/v2/new.ips", b"new patch") + hasher = mocker.spy(handler, "_calculate_rom_hashes") + + parsed = await handler.get_rom_files(rom, existing_files=rows) + + new = next(f for f in parsed.rom_files if f.file_name == "new.ips") + assert new.file_path == f"{self.ROM_DIR}/hack/v2" + assert new.category == RomFileCategory.HACK + assert new.md5_hash == hashlib.md5(b"new patch").hexdigest() + assert all(any(f is row for f in parsed.rom_files) for row in rows) + assert parsed.top_level_changed is False + assert parsed.md5_hash == "stored-md5" + assert hasher.call_count == 1 + patched.ra.assert_not_called() + + async def test_top_level_addition_recomputes_rom_hashes( + self, handler, platform, patched, mocker + ): + rom, rows = self._folder_rom(handler, platform) + self._write(handler, f"{self.ROM_DIR}/extra.n64", b"extra bytes") + hasher = mocker.spy(handler, "_calculate_rom_hashes") + + parsed = await handler.get_rom_files(rom, existing_files=rows) + + top_level = [f for f in parsed.rom_files if f.file_path == self.ROM_DIR] + assert {f.file_name for f in top_level} == {"game.n64", "extra.n64"} + expected_md5 = hashlib.md5(usedforsecurity=False) + for rom_file in top_level: + expected_md5.update( + ( + handler.base_path / rom_file.file_path / rom_file.file_name + ).read_bytes() + ) + assert parsed.top_level_changed is True + assert parsed.md5_hash == expected_md5.hexdigest() + assert parsed.ra_hash == "ra-hash" + patched.ra.assert_awaited_once() + # The nested file is untouched, so its row is still reused. + assert any(f is rows[1] for f in parsed.rom_files) + assert hasher.call_count == 2 + + async def test_removed_top_level_file_recomputes_rom_hashes( + self, handler, platform, patched + ): + rom, rows = self._folder_rom(handler, platform) + gone = self._write(handler, f"{self.ROM_DIR}/gone.n64", b"gone") + rows.append(self._row(rom, self.ROM_DIR, "gone.n64", gone)) + (handler.base_path / self.ROM_DIR / "gone.n64").unlink() + + parsed = await handler.get_rom_files(rom, existing_files=rows) + + assert parsed.top_level_changed is True + assert {f.file_name for f in parsed.rom_files} == {"game.n64", "patched.n64"} + assert parsed.md5_hash == hashlib.md5(b"game bytes").hexdigest() + + @pytest.mark.parametrize("column", ["file_size_bytes", "last_modified"]) + async def test_changed_file_is_rehashed(self, handler, platform, column): + rom, rows = self._folder_rom(handler, platform) + setattr(rows[1], column, getattr(rows[1], column) + 1) + + parsed = await handler.get_rom_files(rom, existing_files=rows) + + hack = next(f for f in parsed.rom_files if f.file_name == "patched.n64") + assert hack is not rows[1] + assert hack.md5_hash == hashlib.md5(b"hack bytes").hexdigest() + assert parsed.top_level_changed is False + + async def test_row_without_hashes_is_rehashed(self, handler, platform): + rom, rows = self._folder_rom(handler, platform) + rows[1] = self._row( + rom, + f"{self.ROM_DIR}/hack", + "patched.n64", + (handler.base_path / self.ROM_DIR / "hack/patched.n64").stat(), + hashed=False, + ) + + parsed = await handler.get_rom_files(rom, existing_files=rows) + + hack = next(f for f in parsed.rom_files if f.file_name == "patched.n64") + assert hack is not rows[1] + assert hack.md5_hash == hashlib.md5(b"hack bytes").hexdigest() + + async def test_row_without_hashes_is_reused_when_hashing_is_disabled( + self, handler, platform, mocker + ): + rom, rows = self._folder_rom(handler, platform) + rows = [ + self._row( + rom, + row.file_path, + row.file_name, + os.stat(handler.base_path / row.file_path / row.file_name), + hashed=False, + ) + for row in rows + ] + hasher = mocker.spy(handler, "_calculate_rom_hashes") + + parsed = await handler.get_rom_files( + rom, calculate_hashes=False, existing_files=rows + ) + + assert {id(f) for f in parsed.rom_files} == {id(r) for r in rows} + hasher.assert_not_called() + + async def test_flat_rom_reuses_its_row(self, handler, platform, patched, mocker): + rom = self._rom(platform, fs_name="Paper Mario (USA).z64", ext="z64") + st = self._write(handler, "n64/roms/Paper Mario (USA).z64", b"paper mario") + row = self._row(rom, "n64/roms", "Paper Mario (USA).z64", st) + hasher = mocker.spy(handler, "_calculate_rom_hashes") + + parsed = await handler.get_rom_files(rom, existing_files=[row]) + + assert parsed.rom_files[0] is row + assert parsed.top_level_changed is False + assert parsed.md5_hash == "stored-md5" + hasher.assert_not_called() + patched.ra.assert_not_called() + + async def test_replaced_flat_rom_is_rehashed(self, handler, platform): + rom = self._rom(platform, fs_name="Paper Mario (USA).z64", ext="z64") + st = self._write(handler, "n64/roms/Paper Mario (USA).z64", b"paper mario") + row = self._row(rom, "n64/roms", "Paper Mario (USA).z64", st) + row.file_size_bytes += 1 + + parsed = await handler.get_rom_files(rom, existing_files=[row]) + + assert parsed.rom_files[0] is not row + assert parsed.top_level_changed is True + assert parsed.md5_hash == hashlib.md5(b"paper mario").hexdigest() + + async def test_nested_folders_map_to_categories(self, handler, platform): + rom = self._rom(platform) + self._write(handler, f"{self.ROM_DIR}/game.n64", b"game") + self._write(handler, f"{self.ROM_DIR}/hack/part1 (Hack).bin", b"hack") + self._write(handler, f"{self.ROM_DIR}/patches/v2/fix.ips", b"patch") + + parsed = await handler.get_rom_files(rom) + + by_name = {f.file_name: f for f in parsed.rom_files} + assert by_name["game.n64"].category is None + assert by_name["part1 (Hack).bin"].category == RomFileCategory.HACK + assert by_name["fix.ips"].category == RomFileCategory.PATCH + + def test_category_matches_plural_forms(self): + assert category_matches("patch", ["patches"]) + assert category_matches("hack", ["hacks"]) + assert category_matches("cheat", ["n64", "roms", "game", "cheats"]) + assert not category_matches("patch", ["patched"]) + + def test_mtime_matches_accepts_single_precision_rounding(self): + actual = 1724500000.123456 + rounded = struct.unpack("f", struct.pack("f", actual))[0] + + assert rounded != actual + assert mtime_matches(actual, actual) + assert mtime_matches(rounded, actual) + assert not mtime_matches(actual + 1, actual) + assert not mtime_matches(None, actual) + + def test_upload_temp_files_are_excluded_by_default(self): + assert "assembling" in DEFAULT_EXCLUDED_EXTENSIONS diff --git a/backend/tests/handler/test_rom_files.py b/backend/tests/handler/test_rom_files.py new file mode 100644 index 000000000..621ffb6a4 --- /dev/null +++ b/backend/tests/handler/test_rom_files.py @@ -0,0 +1,188 @@ +import hashlib +import os +from pathlib import Path + +import pytest + +from handler.database import db_rom_handler +from handler.filesystem import fs_rom_handler +from handler.rom_files import HashPolicy, refresh_rom_files +from models.platform import Platform +from models.rom import Rom, RomFile, RomFileCategory +from models.user import User + +FOLDER = "Multi" + + +@pytest.fixture +def library(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + lib = tmp_path / "library" + lib.mkdir() + monkeypatch.setattr(fs_rom_handler, "base_path", lib.resolve()) + return lib + + +def _write(lib: Path, rel: str, data: bytes) -> os.stat_result: + path = lib / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + return path.stat() + + +def _folder_rom( + platform: Platform, admin_user: User, lib: Path, files: dict[str, bytes] +) -> Rom: + """A folder ROM whose rows describe the files on disk, with stored hashes.""" + rom = Rom( + platform_id=platform.id, + name=FOLDER, + slug=f"{FOLDER}_slug", + fs_name=FOLDER, + fs_name_no_tags=FOLDER, + fs_name_no_ext=FOLDER, + fs_extension="", + fs_path=f"{platform.fs_slug}/roms", + fs_size_bytes=sum(len(data) for data in files.values()), + crc_hash="stored-crc", + md5_hash="stored-md5", + sha1_hash="stored-sha1", + ) + rom = db_rom_handler.add_rom(rom) + db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id) + for rel, data in files.items(): + st = _write(lib, f"{rom.fs_path}/{FOLDER}/{rel}", data) + db_rom_handler.add_rom_file( + RomFile( + rom_id=rom.id, + file_name=Path(rel).name, + file_path=str(Path(rom.fs_path, FOLDER, rel).parent), + file_size_bytes=st.st_size, + last_modified=st.st_mtime, + crc_hash="row-crc", + md5_hash="row-md5", + sha1_hash="row-sha1", + ) + ) + return db_rom_handler.get_rom(rom.id) + + +def _files_by_name(rom_id: int) -> dict[str, RomFile]: + return {f.file_name: f for f in db_rom_handler.get_rom(rom_id).files} + + +async def test_registers_new_nested_file(platform, admin_user, library): + rom = _folder_rom( + platform, admin_user, library, {"game.bin": b"game", "readme.txt": b"readme"} + ) + _write(library, f"{rom.fs_path}/{FOLDER}/patches/v2/fix.ips", b"patch bytes") + + result = await refresh_rom_files(rom) + + assert (result.new_files, result.updated_files, result.removed_files) == (1, 0, 0) + assert result.top_level_changed is False + new = _files_by_name(rom.id)["fix.ips"] + assert new.category == RomFileCategory.PATCH + assert new.md5_hash == hashlib.md5(b"patch bytes").hexdigest() + after = db_rom_handler.get_rom(rom.id) + assert after.fs_size_bytes == len(b"game") + len(b"readme") + len(b"patch bytes") + assert after.md5_hash == "stored-md5" + + +async def test_top_level_addition_updates_rom_hashes_and_size( + platform, admin_user, library +): + rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"}) + _write(library, f"{rom.fs_path}/{FOLDER}/extra.bin", b"extra") + + result = await refresh_rom_files(rom) + + assert result.top_level_changed is True + assert result.new_files == 1 + expected = hashlib.md5(usedforsecurity=False) + for rom_file in result.files: + expected.update( + (library / rom_file.file_path / rom_file.file_name).read_bytes() + ) + after = db_rom_handler.get_rom(rom.id) + assert after.md5_hash == expected.hexdigest() + assert after.fs_size_bytes == len(b"game") + len(b"extra") + assert ( + _files_by_name(rom.id)["game.bin"].md5_hash == hashlib.md5(b"game").hexdigest() + ) + + +async def test_unchanged_rom_writes_nothing(platform, admin_user, library, mocker): + rom = _folder_rom( + platform, admin_user, library, {"game.bin": b"game", "hack/x.bin": b"hack"} + ) + sync = mocker.spy(db_rom_handler, "sync_rom_files") + update = mocker.spy(db_rom_handler, "update_rom") + + result = await refresh_rom_files(rom) + + assert not result.changed + assert result.rom_updates == {} + sync.assert_not_called() + update.assert_not_called() + + +async def test_removes_rows_for_vanished_files(platform, admin_user, library): + rom = _folder_rom( + platform, admin_user, library, {"game.bin": b"game", "hack/old.bin": b"old"} + ) + (library / rom.fs_path / FOLDER / "hack/old.bin").unlink() + + result = await refresh_rom_files(rom) + + assert result.removed_files == 1 + assert result.top_level_changed is False + assert set(_files_by_name(rom.id)) == {"game.bin"} + + +async def test_clears_missing_flag(platform, admin_user, library): + rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"}) + db_rom_handler.update_rom(rom.id, {"missing_from_fs": True}) + rom = db_rom_handler.get_rom(rom.id) + + result = await refresh_rom_files(rom) + + assert result.rom_updates == {"missing_from_fs": False} + assert db_rom_handler.get_rom(rom.id).missing_from_fs is False + + +async def test_empty_folder_keeps_recorded_rows(platform, admin_user, library): + rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"}) + (library / rom.fs_path / FOLDER / "game.bin").unlink() + + result = await refresh_rom_files(rom) + + assert not result.changed + assert result.files == [] + assert set(_files_by_name(rom.id)) == {"game.bin"} + + +async def test_full_policy_rehashes_every_file_in_place(platform, admin_user, library): + rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"}) + row_id = rom.files[0].id + + result = await refresh_rom_files(rom, hash_policy=HashPolicy.FULL) + + assert result.updated_files == 1 + assert result.top_level_changed is True + after = db_rom_handler.get_rom(rom.id) + assert after.files[0].id == row_id + assert after.files[0].md5_hash == hashlib.md5(b"game").hexdigest() + assert after.md5_hash == hashlib.md5(b"game").hexdigest() + + +async def test_loads_files_when_relationship_is_unloaded(platform, admin_user, library): + rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"}) + lean = db_rom_handler.get_roms_by_fs_name( + platform_id=platform.id, fs_names={FOLDER} + )[FOLDER] + _write(library, f"{rom.fs_path}/{FOLDER}/cheats/codes.cht", b"cheats") + + result = await refresh_rom_files(lean) + + assert result.new_files == 1 + assert _files_by_name(rom.id)["codes.cht"].category == RomFileCategory.CHEAT diff --git a/backend/tests/test_watcher.py b/backend/tests/test_watcher.py index cf0d4cf91..58292bdf5 100644 --- a/backend/tests/test_watcher.py +++ b/backend/tests/test_watcher.py @@ -27,7 +27,7 @@ def watcher_full_rescan_job() -> MagicMock: def watcher_platform_job(platform_id: int) -> MagicMock: - return make_job(platform_ids=[platform_id], scan_type=ScanType.QUICK) + return make_job(platform_ids=[platform_id], scan_type=ScanType.FILES) def scheduled_rescan_job() -> MagicMock: @@ -160,7 +160,7 @@ class TestProcessChanges: def platform_dir_change(self, fs_slug: str = "gba"): return (EventType.ADDED, f"{LIBRARY_BASE_PATH}/roms/{fs_slug}") - def test_schedules_a_scan_for_the_changed_platform( + def test_schedules_a_files_scan_for_the_changed_platform( self, mocker, platform, enqueue_in ): patch_pending_jobs(mocker) @@ -168,7 +168,10 @@ class TestProcessChanges: process_changes([self.rom_change()]) enqueue_in.assert_called_once() - assert enqueue_in.call_args.kwargs["platform_ids"] == [platform.id] + kwargs = enqueue_in.call_args.kwargs + assert kwargs["platform_ids"] == [platform.id] + assert kwargs["scan_type"] == ScanType.FILES + assert kwargs["meta"]["task_name"] == "Files Scan" def test_a_platform_directory_change_schedules_a_full_rescan( self, mocker, platform, enqueue_in @@ -178,7 +181,9 @@ class TestProcessChanges: process_changes([self.platform_dir_change()]) enqueue_in.assert_called_once() - assert enqueue_in.call_args.kwargs["platform_ids"] == [] + kwargs = enqueue_in.call_args.kwargs + assert kwargs["platform_ids"] == [] + assert kwargs["scan_type"] == ScanType.UPDATE def test_a_pending_full_rescan_absorbs_every_change( self, mocker, platform, enqueue_in diff --git a/backend/watcher.py b/backend/watcher.py index 88e91619a..74a612e61 100644 --- a/backend/watcher.py +++ b/backend/watcher.py @@ -250,7 +250,7 @@ def process_changes(changes: Sequence[Change]) -> None: continue log.info(f"Change detected in {hl(fs_slug)} folder, {rescan_in_msg}") - schedule_rescan([db_platform.id], ScanType.QUICK) + schedule_rescan([db_platform.id], ScanType.FILES) if __name__ == "__main__": diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md index 95480776c..5480217a7 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/BACKEND_ARCHITECTURE.md @@ -1105,14 +1105,15 @@ The core of RomM. Orchestrates library scanning and metadata enrichment. **Scan Types:** -| Type | Behavior | -| --------------- | -------------------------------- | -| `NEW_PLATFORMS` | Detect new platform folders only | -| `QUICK` | Scan new/unscanned ROMs | -| `UPDATE` | Rescan already-identified ROMs | -| `UNMATCHED` | Rescan ROMs without metadata | -| `COMPLETE` | Full rescan of everything | -| `HASHES` | Recalculate all file hashes | +| Type | Behavior | +| --------------- | ----------------------------------------------------------------------------------------- | +| `NEW_PLATFORMS` | Detect new platform folders only | +| `QUICK` | Scan new/unscanned ROMs | +| `FILES` | Scan new ROMs and reconcile the files of existing ones, hashing only new or changed files | +| `UPDATE` | Rescan already-identified ROMs | +| `UNMATCHED` | Rescan ROMs without metadata | +| `COMPLETE` | Full rescan of everything | +| `HASHES` | Recalculate all file hashes | **Scan Flow:**