diff --git a/Dockerfile b/Dockerfile
index 69ff807b8..a228704e7 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 \
@@ -77,6 +78,27 @@ 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. 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.
+# trunk-ignore(hadolint/DL3003)
+RUN git clone --filter=blob:none https://github.com/rommforge/argosy-sigil.git /tmp/argosy-sigil \
+ && cd /tmp/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 \
+ && uv pip install --python /app/.venv/bin/python cffi setuptools \
+ && cd ./bindings/python \
+ && /app/.venv/bin/python build_sigil.py \
+ && mkdir -p "/app/.venv/lib/python${PYTHON_VERSION}/site-packages/sigil" \
+ && cp ./sigil/*.py ./sigil/_sigil.*.so "/app/.venv/lib/python${PYTHON_VERSION}/site-packages/sigil/" \
+ && rm -rf /tmp/argosy-sigil
+WORKDIR /app
+
# Copy entrypoint script
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
diff --git a/backend/adapters/services/sigil.py b/backend/adapters/services/sigil.py
new file mode 100644
index 000000000..b7d5bbc29
--- /dev/null
+++ b/backend/adapters/services/sigil.py
@@ -0,0 +1,93 @@
+import asyncio
+from dataclasses import dataclass
+from typing import 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]
+ log.debug("sigil binding not installed, title id extraction disabled")
+
+# 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({UPS.SWITCH, UPS.SWITCH_2})
+
+SIGIL_PLATFORM_SLUGS: Final[dict[str, str]] = {
+ UPS.PSP: "psp",
+ UPS.PSX: "psx",
+ UPS.PS2: "ps2",
+ UPS.PSVITA: "psvita",
+ UPS.SWITCH: "switch",
+ UPS.SWITCH_2: "switch",
+ UPS.N3DS: "3ds",
+ UPS.WII: "wii",
+ 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,
+# 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"}
+)
+
+
+@dataclass(frozen=True)
+class SigilExtractionResult:
+ title_id: str
+ save_target: str
+ usage: str
+ content_type: str | None = None
+ version: int | None = None
+
+
+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: str,
+ file_path: str,
+ ) -> SigilExtractionResult | None:
+ if sigil is None:
+ return None
+
+ sigil_slug = SIGIL_PLATFORM_SLUGS.get(platform_slug)
+ if sigil_slug is None:
+ return None
+
+ try:
+ result = await asyncio.to_thread(
+ sigil.extract, file_path, platform=sigil_slug, filename_fallback=False
+ )
+ except Exception as exc:
+ code = getattr(exc, "code", None)
+ 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}")
+ 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,
+ # sigil calls this save_id; RomM's name for it is save_target.
+ save_target=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/0116_sigil_title_ids.py b/backend/alembic/versions/0116_sigil_title_ids.py
new file mode 100644
index 000000000..fdcc056f6
--- /dev/null
+++ b/backend/alembic/versions/0116_sigil_title_ids.py
@@ -0,0 +1,75 @@
+"""Add the binary identity columns on roms: title_id, save_target and
+save_target_layout.
+
+Revision ID: 0116_sigil_title_ids
+Revises: 0115_add_steam_metadata
+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 = "0116_sigil_title_ids"
+down_revision = "0115_add_steam_metadata"
+branch_labels = None
+depends_on = None
+
+SAVE_TARGET_LAYOUT_VALUES = (
+ "FOLDER_EXACT",
+ "FOLDER_PREFIX",
+ "FILE_EXACT",
+ "FILE_PREFIX",
+ "FOLDER_SPLIT",
+)
+
+
+def _save_target_layout_enum(connection) -> sa.Enum:
+ if is_postgresql(connection):
+ enum = ENUM(
+ *SAVE_TARGET_LAYOUT_VALUES, name="savetargetlayout", create_type=False
+ )
+ enum.create(connection, checkfirst=True)
+ return enum
+ return sa.Enum(*SAVE_TARGET_LAYOUT_VALUES, name="savetargetlayout")
+
+
+def upgrade() -> None:
+ connection = op.get_bind()
+ save_target_layout_enum = _save_target_layout_enum(connection)
+
+ with op.batch_alter_table("roms", schema=None) as batch_op:
+ batch_op.add_column(
+ sa.Column("title_id", sa.String(length=100), nullable=True),
+ if_not_exists=True,
+ )
+ batch_op.add_column(
+ sa.Column("save_target", sa.String(length=100), nullable=True),
+ if_not_exists=True,
+ )
+ batch_op.add_column(
+ sa.Column("save_target_layout", save_target_layout_enum, nullable=True),
+ if_not_exists=True,
+ )
+ 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)
+ batch_op.drop_column("save_target_layout", if_exists=True)
+ batch_op.drop_column("save_target", if_exists=True)
+ batch_op.drop_column("title_id", if_exists=True)
+
+ connection = op.get_bind()
+ if is_postgresql(connection):
+ ENUM(name="savetargetlayout").drop(connection, checkfirst=True)
diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py
index 523421de9..3a49bad22 100644
--- a/backend/config/config_manager.py
+++ b/backend/config/config_manager.py
@@ -190,6 +190,8 @@ class Config:
ROMS_FOLDER_NAME: str
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
@@ -442,6 +444,12 @@ 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
+ ),
+ 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
@@ -886,6 +894,8 @@ 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,
+ "embed_switch_title_ids": self.config.EMBED_SWITCH_TITLE_IDS,
},
"system": {
"platforms": self.config.PLATFORMS_BINDING,
diff --git a/backend/endpoints/responses/rom.py b/backend/endpoints/responses/rom.py
index c37313e1d..7b197457d 100644
--- a/backend/endpoints/responses/rom.py
+++ b/backend/endpoints/responses/rom.py
@@ -37,6 +37,7 @@ from models.rom import (
RomFile,
RomFileCategory,
RomUserStatus,
+ SaveTargetLayout,
)
from .base import BaseModel, UTCDatetime
@@ -403,6 +404,9 @@ class RomSchema(BaseModel):
md5_hash: str | None
sha1_hash: str | None
ra_hash: str | None
+ title_id: str | None
+ save_target: str | None
+ save_target_layout: SaveTargetLayout | None
has_simple_single_file: bool
has_nested_single_file: bool
diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py
index 4e4534aa7..b5238c35b 100644
--- a/backend/endpoints/roms/__init__.py
+++ b/backend/endpoints/roms/__init__.py
@@ -32,6 +32,7 @@ from pydantic import BaseModel, Field
from sqlalchemy.exc import IntegrityError
from starlette.responses import FileResponse
+from adapters.services.sigil import SWITCH_PLATFORM_SLUGS
from config import (
DEV_MODE,
DISABLE_DOWNLOAD_ENDPOINT_AUTH,
@@ -97,11 +98,14 @@ from logger.logger import log
from models.permission import PermAction, PermEntity
from models.rom import (
HAS_FILE_ON_DISK_FILTERS,
+ TITLE_ID_MAX_LENGTH,
Rom,
RomUserStatus,
+ SaveTargetLayout,
apply_file_stats,
compute_name_sort_key,
)
+from utils import switch
from utils.background_tasks import fire_and_forget
from utils.database import safe_int, safe_str_to_bool
from utils.filesystem import sanitize_filename
@@ -2551,3 +2555,59 @@ async def update_rom_user(
refresh_affected_smart_collections([id], membership_only=True)
return RomUserSchema.model_validate(rom_user)
+
+
+class RomIdentityData(BaseModel):
+ """Binary identity a client extracted for a ROM that RomM cannot read itself."""
+
+ title_id: str | None = Field(
+ default=None,
+ description="Platform-native identity, e.g. 0100ABCD12340000 or SLUS-20152.",
+ max_length=TITLE_ID_MAX_LENGTH,
+ )
+ save_target: str | None = Field(
+ default=None,
+ description="On-disk name the emulator gives this game's saves.",
+ max_length=TITLE_ID_MAX_LENGTH,
+ )
+ save_target_layout: SaveTargetLayout | None = Field(
+ default=None,
+ description="How to apply save_target when locating saves on disk.",
+ )
+
+
+@protected_route(
+ router.put,
+ "/{id}/identity",
+ [Scope.ROMS_WRITE],
+ responses={status.HTTP_404_NOT_FOUND: {}},
+)
+async def update_rom_identity(
+ request: Request,
+ id: Annotated[int, PathVar(description="Rom internal id.", ge=1)],
+ data: Annotated[RomIdentityData, Body()],
+) -> DetailedRomSchema:
+ """Store binary identity a client extracted from a ROM the scan cannot read."""
+ rom = db_rom_handler.get_rom(id)
+
+ if not rom:
+ raise RomNotFoundInDatabaseException(id)
+
+ assert_rom_visible(request, rom)
+
+ cleaned_data = data.model_dump(exclude_unset=True)
+
+ # Reassociating a renamed non-hashable ROM matches on this id, which only
+ # works while it is the base game's.
+ title_id = cleaned_data.get("title_id")
+ if title_id and rom.platform_slug in SWITCH_PLATFORM_SLUGS:
+ cleaned_data["title_id"] = switch.derive_base_title_id(title_id) or title_id
+
+ db_rom_handler.update_rom(id, cleaned_data)
+
+ # The update returns a bare row; the schema reads relationships off it.
+ updated_rom = db_rom_handler.get_rom(id)
+ if not updated_rom:
+ raise RomNotFoundInDatabaseException(id)
+
+ return DetailedRomSchema.from_orm_with_request(updated_rom, request)
diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py
index d89fc799d..baa776303 100644
--- a/backend/endpoints/sockets/scan.py
+++ b/backend/endpoints/sockets/scan.py
@@ -1,18 +1,15 @@
from __future__ import annotations
import asyncio
-from collections.abc import Iterator
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 redis import Redis
-from rq import Worker, get_current_job
-from rq.exceptions import AbandonedJobError, NoSuchJobError
+from rq import get_current_job
+from rq.exceptions import AbandonedJobError
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
@@ -42,7 +39,7 @@ 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,
@@ -53,11 +50,8 @@ 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_kwargs,
+ cancel_job,
get_job_status,
- high_prio_queue,
- low_prio_queue,
redis_client,
scan_queue,
)
@@ -71,6 +65,12 @@ 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,
+ is_scoped_scan_job,
+)
from handler.socket_handler import socket_handler
from logger.formatter import BLUE, LIGHTYELLOW
from logger.formatter import highlight as hl
@@ -87,148 +87,13 @@ 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 _is_scoped_scan_job(job: Job) -> bool:
- """Whether this scan covers named roms rather than the library.
-
- A scan that cannot be read is treated as a library scan: the worker will
- fail it on the next dequeue, so it stops standing in the way by itself.
- """
- kwargs = get_job_kwargs(job)
- return bool(kwargs and kwargs.get("roms_ids"))
-
-
-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):
- # 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
-
- 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.
-
- The other queues are still read because a scan enqueued before scans had
- their own queue is on one of them, and it will still run.
- """
- jobs: dict[str, Job] = {}
-
- for job in chain(
- scan_queue.get_jobs(), 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())
-
-
-def _scheduled_scan_registries() -> list[ScheduledJobRegistry]:
- """Where delayed scans wait until a worker releases them.
-
- The low priority queue is still read because a scan delayed before scans had
- their own queue waits in its registry, and a worker will still release it.
- """
- return [
- ScheduledJobRegistry(queue=scan_queue),
- ScheduledJobRegistry(queue=low_prio_queue),
- ]
-
-
-def _iter_scheduled_scans() -> Iterator[tuple[ScheduledJobRegistry, Job]]:
- """Every delayed scan, with the registry that holds its due time."""
- for registry in _scheduled_scan_registries():
- for job in Job.fetch_many(registry.get_job_ids(), connection=redis_client):
- if job is not None and _is_scan_job(job):
- yield registry, job
-
-
-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.
- """
- return list({job.id: job for _, job in _iter_scheduled_scans()}.values())
-
-
-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.
- """
- cutoff = datetime.now(timezone.utc) - STALE_SCHEDULED_SCAN_AGE
- dropped = 0
-
- for registry, job in _iter_scheduled_scans():
- try:
- scheduled_at = registry.get_scheduled_time(job)
- except NoSuchJobError:
- continue
-
- if scheduled_at > cutoff:
- continue
-
- job.cancel()
- dropped += 1
- log.warning(f"Dropped scan scheduled for {scheduled_at}, too long past due")
-
- 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.value,
+ }
def report_scan_failure(
@@ -264,7 +129,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"
@@ -501,6 +367,23 @@ def _should_hash_firmware(
)
+def _apply_scanned_values(fs_rom: FSRom, parsed: ParsedRomFiles) -> None:
+ fs_rom.update(
+ {
+ "files": parsed.rom_files,
+ "crc_hash": parsed.crc_hash,
+ "md5_hash": parsed.md5_hash,
+ "sha1_hash": parsed.sha1_hash,
+ "ra_hash": parsed.ra_hash,
+ "title_id": parsed.title_id,
+ "save_target": parsed.save_target,
+ "save_target_layout": parsed.save_target_layout,
+ }
+ )
+ 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
@@ -542,7 +425,10 @@ async def _identify_rom(
"url_screenshots": [],
}
- calculate_hashes = not cm.get_config().SKIP_HASH_CALCULATION
+ 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
@@ -559,16 +445,13 @@ async def _identify_rom(
platform=platform,
),
calculate_hashes=calculate_hashes,
+ extract_title_ids=extract_title_ids,
+ 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,
- }
- )
+ _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
files_built = True
missing_match = db_rom_handler.get_matching_missing_rom(
@@ -576,6 +459,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.
@@ -633,17 +517,15 @@ 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
- )
- 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,
- }
+ rom,
+ calculate_hashes=calculate_hashes,
+ extract_title_ids=extract_title_ids,
+ embed_title_ids=embed_title_ids,
)
+ _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:
+ 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
@@ -1075,7 +957,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
@@ -1387,12 +1269,12 @@ async def scan_handler(sid: str, options: dict[str, Any]):
# roms is not that, and refusing it loses a click the user has to remember
# to repeat, so it is allowed to queue instead.
if not DEV_MODE and not roms_ids:
- running_job = _get_running_scan_job()
- if running_job is not None and _is_scoped_scan_job(running_job):
+ running_job = get_running_scan_job()
+ if running_job is not None and is_scoped_scan_job(running_job):
running_job = None
queued_jobs = [
- job for job in _get_queued_scan_jobs() if not _is_scoped_scan_job(job)
+ job for job in get_queued_scan_jobs() if not is_scoped_scan_job(job)
]
if running_job is not None or queued_jobs:
@@ -1437,10 +1319,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),
)
@@ -1455,16 +1334,16 @@ 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()
+ 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()
+ 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/endpoints/tasks.py b/backend/endpoints/tasks.py
index aa9118b74..4c61c8f9b 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,13 +25,14 @@ 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,
scan_queue,
)
-from tasks.registry import MANUAL_TASKS, SCHEDULED_TASKS
-from tasks.tasks import SCAN_DISPATCH_META_KEY, Task, TaskType, run_task_by_name
+from tasks.registry import MANUAL_TASKS, SCHEDULED_TASKS, enqueue_task
+from tasks.tasks import SCAN_DISPATCH_META_KEY, Task, TaskType
from utils.router import APIRouter
router = APIRouter(
@@ -49,14 +46,19 @@ ALL_QUEUES: Final = (scan_queue, high_prio_queue, default_queue, low_prio_queue)
# 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",
-)
+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:
@@ -180,8 +182,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(
@@ -211,15 +213,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 and not _is_spent_scan_dispatch(current_job):
all_tasks.append(_build_task_status_response(current_job))
@@ -302,39 +297,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/database/roms_handler.py b/backend/handler/database/roms_handler.py
index 8a3092c3e..c128ff666 100644
--- a/backend/handler/database/roms_handler.py
+++ b/backend/handler/database/roms_handler.py
@@ -3259,17 +3259,30 @@ 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 non-hashable platforms
+ like Switch carry instead.
+
+ 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(
@@ -3278,9 +3291,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/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py
index bf01afdeb..0034fd112 100644
--- a/backend/handler/filesystem/roms_handler.py
+++ b/backend/handler/filesystem/roms_handler.py
@@ -7,10 +7,16 @@ import re
import zlib
from dataclasses import dataclass
from pathlib import Path
-from typing import Any, TypedDict
+from typing import Any, Final, NotRequired, TypedDict
from anyio import Path as AnyioPath
+from adapters.services.sigil import (
+ SIGIL_PLATFORM_SLUGS,
+ SWITCH_PLATFORM_SLUGS,
+ SigilExtractionResult,
+ SigilService,
+)
from config import LIBRARY_BASE_PATH
from config.config_manager import (
DEFAULT_EXCLUDED_EXTENSIONS,
@@ -23,8 +29,17 @@ from exceptions.fs_exceptions import (
)
from handler.metadata.base_handler import UniversalPlatformSlug as UPS
from logger.logger import log
+from models.base import compute_file_extension, compute_file_name_no_ext
from models.platform import Platform
-from models.rom import Rom, RomFile, RomFileCategory, TrackMeta
+from models.rom import (
+ DOCUMENT_CATEGORIES,
+ Rom,
+ RomFile,
+ RomFileCategory,
+ SaveTargetLayout,
+ TrackMeta,
+)
+from utils import switch
from utils.archives import (
ArchiveReadError,
detect_mime_type,
@@ -97,6 +112,9 @@ class FSRom(TypedDict):
md5_hash: str
sha1_hash: str
ra_hash: str
+ title_id: NotRequired[str | None]
+ save_target: NotRequired[str | None]
+ save_target_layout: NotRequired[SaveTargetLayout | None]
class FileHash(TypedDict):
@@ -169,6 +187,51 @@ class ParsedRomFiles:
md5_hash: str
sha1_hash: str
ra_hash: str
+ title_id: str | None = None
+ save_target: str | None = None
+ save_target_layout: SaveTargetLayout | 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.
+ renamed_rom_fs_name: str | None = None
+
+
+# File categories that never hold a ROM binary, so sigil has nothing to read.
+NON_BINARY_FILE_CATEGORIES: Final = DOCUMENT_CATEGORIES | {
+ RomFileCategory.SOUNDTRACK,
+ RomFileCategory.SCREENSHOT,
+ RomFileCategory.CHEAT,
+}
+
+
+def _parse_save_target_layout(usage: str) -> SaveTargetLayout | None:
+ try:
+ return SaveTargetLayout(usage)
+ except ValueError:
+ log.warning(f"Unrecognized sigil save target layout {usage!r}")
+ return None
+
+
+def _rom_level_title_values(
+ platform_slug: str,
+ extractions: list[SigilExtractionResult],
+) -> tuple[str | None, str | None, SaveTargetLayout | None]:
+ if not extractions:
+ return None, None, None
+
+ if platform_slug in SWITCH_PLATFORM_SLUGS:
+ chosen = next(
+ (e for e in extractions if switch.is_base_title_id(e.title_id)), None
+ )
+ if chosen is None:
+ derived = switch.derive_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, SaveTargetLayout.FOLDER_EXACT
+ else:
+ chosen = extractions[0]
+
+ return chosen.title_id, chosen.save_target, _parse_save_target_layout(chosen.usage)
class FSRomsHandler(FSHandler):
@@ -334,7 +397,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,
+ embed_title_ids: bool = False,
) -> ParsedRomFiles:
from adapters.services.rahasher import RAHasherService
from handler.metadata import meta_ra_handler
@@ -350,6 +417,47 @@ 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
+ is_switch = rom.platform_slug in SWITCH_PLATFORM_SLUGS
+ sigil_extractions: list[SigilExtractionResult] = []
+ sigil_service = SigilService()
+
+ # Embedding is Switch-only even though sigil covers more platforms.
+ embed_switch = embed_title_ids and is_switch
+ renamed_rom_fs_name: str | None = None
+
+ 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 needs a per-file content type; one extraction is
+ # enough elsewhere.
+ if not sigil_platform or (sigil_extractions and not is_switch):
+ return None
+
+ rel_file_path = Path(rom_file.file_path, rom_file.file_name)
+ extraction = await sigil_service.extract_title_id(
+ rom.platform_slug, str(Path(self.base_path, rel_file_path))
+ )
+ if extraction is None:
+ return None
+ 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 not (embed_switch and extraction.title_id):
+ return None
+
+ new_name = await self._embed_switch_title_id_in_name(
+ rel_file_path, extraction.title_id, extraction.version
+ )
+ if new_name is not None:
+ rom_file.file_name = new_name
+ return new_name
+
cnfg = cm.get_config()
excluded_file_names = cnfg.EXCLUDED_MULTI_PARTS_FILES
excluded_file_exts = cnfg.EXCLUDED_MULTI_PARTS_EXT
@@ -450,14 +558,20 @@ 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,
)
+ # Extract from every ROM file (base, updates and DLC in
+ # subfolders), not just the top-level one.
+ if (
+ abs_file_path.suffix.lower() not in ARCHIVE_READERS
+ and rom_file.category not in NON_BINARY_FILE_CATEGORIES
+ ):
+ await _extract_title_id(rom_file)
+ 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
@@ -555,59 +669,60 @@ class FSRomsHandler(FSHandler):
file_hash=_make_file_hash(rom_crc_c, rom_md5_h, rom_sha1_h),
)
)
- elif hashable_platform:
- try:
- crc_c, _, md5_h, _, sha1_h, _ = await asyncio.to_thread(
- self._calculate_rom_hashes,
- Path(abs_fs_path, rom.fs_name),
- )
- except zlib.error:
- crc_c = 0
- md5_h = hashlib.md5(usedforsecurity=False)
- sha1_h = hashlib.sha1(usedforsecurity=False)
-
- # A single-file ROM spans exactly one file, so its ROM-level hashes
- # are that file's hashes.
- rom_crc_c, rom_md5_h, rom_sha1_h = crc_c, md5_h, sha1_h
-
- # Calculate the RA hash if the platform has a slug that matches a known RA slug
- if calculate_hashes:
- ra_platform = meta_ra_handler.get_platform(rom.platform_slug)
- if ra_platform and ra_platform["ra_id"]:
- rom_ra_h = await RAHasherService().calculate_hash(
- ra_platform,
- 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),
- )
- rom_files.append(
- self._build_rom_file(
- rom=rom,
- rom_path=Path(rel_roms_path),
- file_name=rom.fs_name,
- file_hash=file_hash,
- )
- )
else:
- file_hash = FileHash(
- crc_hash="",
- md5_hash="",
- 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,
+ if hashable_platform:
+ try:
+ crc_c, _, md5_h, _, sha1_h, _ = await asyncio.to_thread(
+ self._calculate_rom_hashes,
+ Path(abs_fs_path, rom.fs_name),
+ )
+ except zlib.error:
+ crc_c = 0
+ md5_h = hashlib.md5(usedforsecurity=False)
+ sha1_h = hashlib.sha1(usedforsecurity=False)
+
+ # A single-file ROM spans exactly one file, so its ROM-level
+ # hashes are that file's hashes.
+ rom_crc_c, rom_md5_h, rom_sha1_h = crc_c, md5_h, sha1_h
+
+ # Calculate the RA hash if the platform has a slug that matches a known RA slug
+ if calculate_hashes:
+ ra_platform = meta_ra_handler.get_platform(rom.platform_slug)
+ if ra_platform and ra_platform["ra_id"]:
+ rom_ra_h = await RAHasherService().calculate_hash(
+ ra_platform,
+ 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),
)
+ else:
+ file_hash = 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,
)
+ rom_files.append(rom_file)
+ # Archives keep hashes only; sigil reads title ids from the ROM
+ # binary itself.
+ if rom_ext not in ARCHIVE_READERS:
+ renamed_rom_fs_name = await _extract_title_id(rom_file)
+
+ rom_title_id, rom_save_target, rom_save_target_layout = _rom_level_title_values(
+ rom.platform_slug, sigil_extractions
+ )
return ParsedRomFiles(
rom_files=rom_files,
@@ -623,6 +738,10 @@ class FSRomsHandler(FSHandler):
else ""
),
ra_hash=rom_ra_h,
+ title_id=rom_title_id,
+ save_target=rom_save_target,
+ save_target_layout=rom_save_target_layout,
+ renamed_rom_fs_name=renamed_rom_fs_name,
)
def _calculate_rom_hashes(
@@ -765,6 +884,45 @@ class FSRomsHandler(FSHandler):
f"{fs_path}/{old_name}", f"{fs_path}/{new_name}"
)
+ async def _embed_switch_title_id_in_name(
+ self, rel_file_path: Path, title_id: str, title_version: int | None
+ ) -> str | None:
+ """Rename a Switch ROM file to embed ` [TITLEID][vVERSION]` before the
+ extension.
+
+ Args:
+ rel_file_path: The file's path relative to the library root.
+ Returns:
+ The new file name, or None when the file was left untouched.
+ """
+ name = rel_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.fullmatch(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
+ extension = compute_file_extension(name)
+ new_name = (
+ f"{compute_file_name_no_ext(name)} [{title_id.upper()}][v{version}]"
+ f"{'.' + extension if extension else ''}"
+ )
+
+ try:
+ 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"
+ )
+ return None
+
+ log.info(f"Embedded Switch title id: renamed {name} to {new_name}")
+ return new_name
+
def get_pico8_cover_url(
self, platform_slug: str, fs_name: str, fs_path: str
) -> str | None:
diff --git a/backend/handler/redis_handler.py b/backend/handler/redis_handler.py
index 135732c1a..ee6fa632a 100644
--- a/backend/handler/redis_handler.py
+++ b/backend/handler/redis_handler.py
@@ -5,8 +5,8 @@ from typing import Any, Final
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
@@ -84,17 +84,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
@@ -112,3 +114,36 @@ def get_job_kwargs(job: Job) -> dict[str, Any] | None:
return job.kwargs
except DeserializationError:
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.
+
+ 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/handler/scan_handler.py b/backend/handler/scan_handler.py
index 564517b81..a2f79ee8a 100644
--- a/backend/handler/scan_handler.py
+++ b/backend/handler/scan_handler.py
@@ -519,6 +519,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_target": rom.save_target,
+ "save_target_layout": rom.save_target_layout,
"fs_size_bytes": rom.fs_size_bytes,
"is_physical": rom.is_physical,
"upc": rom.upc,
@@ -537,6 +540,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_target": fs_rom.get("save_target"),
+ "save_target_layout": fs_rom.get("save_target_layout"),
+ }
+ )
+
# 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/handler/scan_jobs.py b/backend/handler/scan_jobs.py
new file mode 100644
index 000000000..ed07112fa
--- /dev/null
+++ b/backend/handler/scan_jobs.py
@@ -0,0 +1,159 @@
+"""Finding and pruning the RQ jobs that run a library scan."""
+
+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 (
+ cancel_job,
+ get_job_func_name,
+ get_job_kwargs,
+ get_job_status,
+ get_worker_current_job,
+ high_prio_queue,
+ low_prio_queue,
+ redis_client,
+ scan_queue,
+)
+from logger.logger import log
+from tasks.tasks import TaskType
+
+# 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
+# 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.
+
+ 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
+
+ return job.meta.get("task_type") == TaskType.SCAN
+
+
+def is_scoped_scan_job(job: Job) -> bool:
+ """Whether this scan covers named roms rather than the library.
+
+ A scan that cannot be read is treated as a library scan: the worker will
+ fail it on the next dequeue, so it stops standing in the way by itself.
+ """
+ kwargs = get_job_kwargs(job)
+ return bool(kwargs and kwargs.get("roms_ids"))
+
+
+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.
+
+ The other queues are still read because a scan enqueued before scans had
+ their own queue is on one of them, and it will still run.
+ """
+ job_ids = chain(
+ scan_queue.get_job_ids(),
+ 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_registries() -> list[ScheduledJobRegistry]:
+ """Where delayed scans wait until a worker releases them.
+
+ The low priority queue is still read because a scan delayed before scans had
+ their own queue waits in its registry, and a worker will still release it.
+ """
+ return [
+ ScheduledJobRegistry(queue=scan_queue),
+ 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.
+ """
+ job_ids = chain.from_iterable(
+ registry.get_job_ids() for registry in _scheduled_scan_registries()
+ )
+ 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)]
+
+
+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.
+ """
+ cutoff = datetime.now(timezone.utc) - STALE_SCHEDULED_SCAN_AGE
+
+ # A registry is scored by due time, so it can hand back only what is due.
+ stale_ids = chain.from_iterable(
+ registry.get_jobs_to_schedule(int(cutoff.timestamp()))
+ for registry in _scheduled_scan_registries()
+ )
+ 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
+
+ if not cancel_job(job):
+ continue
+
+ dropped += 1
+ log.warning(
+ f"Dropped scan {job.id}, overdue by more than {STALE_SCHEDULED_SCAN_AGE}"
+ )
+
+ return dropped
diff --git a/backend/models/rom.py b/backend/models/rom.py
index 63c3a70c2..a6506425d 100644
--- a/backend/models/rom.py
+++ b/backend/models/rom.py
@@ -52,6 +52,8 @@ from utils.database import CustomJSON
NAME_SORT_KEY_MAX_LENGTH = 500
# Max length for free-text audio tag columns (title/artist/album).
AUDIO_TAG_MAX_LENGTH = 512
+# Max length for the binary identity columns (title id and save target).
+TITLE_ID_MAX_LENGTH = 100
# Articles ignored when sorting or bucketing a title, across the languages
# No-Intro and LaunchBox name games in. Both patterns built from this are
# anchored on the right, so "la" preceding "las" costs nothing.
@@ -109,6 +111,14 @@ class RomFileCategory(enum.StrEnum):
SCREENSHOT = "screenshot"
+class SaveTargetLayout(enum.StrEnum):
+ FOLDER_EXACT = "folder-exact"
+ FOLDER_PREFIX = "folder-prefix"
+ FILE_EXACT = "file-exact"
+ FILE_PREFIX = "file-prefix"
+ FOLDER_SPLIT = "folder-split"
+
+
# Document-category files (manuals, walkthroughs) share one substrate: a
# RomFile plus an optional RomFileDocMeta sidecar for provenance.
DOCUMENT_CATEGORIES = frozenset({RomFileCategory.MANUAL, RomFileCategory.WALKTHROUGH})
@@ -525,6 +535,7 @@ class Rom(BaseModel):
Index("idx_roms_steam_id", "steam_id"),
Index("idx_roms_gamelist_id", "gamelist_id"),
Index("idx_roms_libretro_id", "libretro_id"),
+ Index("idx_roms_title_id", "title_id"),
# Searching the gallery by a hash digest
Index("idx_roms_crc_hash", "crc_hash"),
Index("idx_roms_md5_hash", "md5_hash"),
@@ -641,6 +652,19 @@ 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=TITLE_ID_MAX_LENGTH),
+ doc="Platform-native identity read from the ROM binary, normalized (0100ABCD12340000, SLUS-20152)",
+ )
+ save_target: Mapped[str | None] = mapped_column(
+ String(length=TITLE_ID_MAX_LENGTH),
+ doc="On-disk name an emulator gives this game's saves; a file stem, a folder, or a nested path",
+ )
+ save_target_layout: Mapped[SaveTargetLayout | None] = mapped_column(
+ Enum(SaveTargetLayout),
+ default=None,
+ doc="How to apply save_target: one folder, a folder prefix, a file prefix, or a nested path",
+ )
missing_from_fs: Mapped[bool] = mapped_column(default=False, nullable=False)
diff --git a/backend/startup.py b/backend/startup.py
index 46daecd94..1579043dd 100644
--- a/backend/startup.py
+++ b/backend/startup.py
@@ -5,13 +5,10 @@ import asyncio
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,
- TASK_TIMEOUT,
-)
-from endpoints.sockets.scan import drop_stale_scheduled_scans
+from config import ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP, SENTRY_DSN
from handler.database import db_save_handler
from handler.metadata.base_handler import (
MAME_XML_KEY,
@@ -29,13 +26,10 @@ 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.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 +39,33 @@ 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."""
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 +73,20 @@ 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
- 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"
- )
+ 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)
-# 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,
@@ -147,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)
}
@@ -160,17 +112,16 @@ 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"
- )
+ 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.
- 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 +133,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 be8fe9529..9fce0e4d3 100644
--- a/backend/tasks/cron_config.py
+++ b/backend/tasks/cron_config.py
@@ -1,24 +1,16 @@
"""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 typing import Any
-
from rq import cron
from config import TASK_RESULT_TTL, TASK_TIMEOUT
-from endpoints.responses import TaskType
from handler.redis_handler import QueuePrio
from logger.logger import log
-from tasks.registry import SCHEDULED_TASKS
-from tasks.tasks import (
- SCAN_DISPATCH_META_KEY,
- enqueue_scheduled_scan,
- run_task_by_name,
-)
+from tasks.registry import SCHEDULED_TASKS, enqueue_scheduled_scan
+from tasks.tasks import SCAN_DISPATCH_META_KEY, TaskType, run_task_by_name
for name, task in SCHEDULED_TASKS.items():
if not task.enabled or not task.cron_string:
@@ -30,23 +22,17 @@ for name, task in SCHEDULED_TASKS.items():
# of waiting behind a scan, and only enqueues, so the scan timeout belongs
# to the scan rather than to this.
is_scan = task.task_type is TaskType.SCAN
+ meta = {**task.job_meta, SCAN_DISPATCH_META_KEY: True} if is_scan else task.job_meta
- meta: dict[str, Any] = {
- "task_name": task.title,
- "task_type": task.task_type.value,
- }
- if is_scan:
- meta[SCAN_DISPATCH_META_KEY] = True
-
+ # Every entry runs the same function, so without an explicit name they all
+ # share one cron identity and one job history.
cron.register(
enqueue_scheduled_scan if is_scan else run_task_by_name,
QueuePrio.LOW.value,
+ name=name,
kwargs={"name": name},
cron=task.cron_string,
job_timeout=TASK_TIMEOUT if is_scan else task.timeout,
- # `register()` defaults this to RQ's 500 seconds and always writes it
- # onto the job, so the worker's own result TTL can never apply and the
- # task history would empty minutes after each run.
result_ttl=TASK_RESULT_TTL,
meta=meta,
)
diff --git a/backend/tasks/registry.py b/backend/tasks/registry.py
index 2c2fd0aed..f80e70bf2 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, scan_queue
from tasks.manual.cleanup_missing_firmware import cleanup_missing_firmware_task
from tasks.manual.cleanup_missing_roms import cleanup_missing_roms_task
from tasks.manual.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,55 @@ 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.
+
+ 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,
+ )
+
+
+def enqueue_scheduled_scan(name: str) -> str:
+ """Put a scheduled scan on the scan queue with the abandoned-job callback.
+
+ Cron can attach no `on_failure`, so a scan it enqueues itself is the one
+ scan whose worker can die without anything telling the clients.
+
+ Args:
+ name: The key the scan task is registered under.
+
+ Returns:
+ The id of the enqueued scan job.
+ """
+ # Imported here because the scan module imports the task modules this one
+ # pulls in.
+ from endpoints.sockets.scan import report_scan_failure
+
+ return enqueue_task(name, queue=scan_queue, on_failure=report_scan_failure).id
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 cdee05498..8d163e82e 100644
--- a/backend/tasks/scheduled/scan_library.py
+++ b/backend/tasks/scheduled/scan_library.py
@@ -38,7 +38,6 @@ class ScanLibraryTask(PeriodicTask):
cron_string=SCHEDULED_RESCAN_CRON,
# A library scan is not a five-minute task like the rest.
timeout=SCAN_TIMEOUT,
- 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 952068a62..a66255881 100644
--- a/backend/tasks/tasks.py
+++ b/backend/tasks/tasks.py
@@ -5,7 +5,7 @@ from typing import Any
import httpx
from rq import get_current_job
-from config import TASK_RESULT_TTL, TASK_TIMEOUT
+from config import TASK_TIMEOUT
from exceptions.task_exceptions import TaskNotFoundException
from logger.logger import log
from utils.context import ctx_httpx_client
@@ -41,42 +41,6 @@ async def run_task_by_name(name: str, task_kwargs: dict[str, Any] | None = None)
return await task.run(**(task_kwargs or {}))
-def enqueue_scheduled_scan(name: str) -> str:
- """Put a scheduled scan on the scan queue with the abandoned-job callback.
-
- Cron can attach no `on_failure`, so a scan it enqueues itself is the one
- scan whose worker can die without anything telling the clients.
-
- Args:
- name: The key the scan task is registered under.
-
- Returns:
- The id of the enqueued scan job.
- """
- # Imported here for the same reason as in run_task_by_name: the registry
- # imports every task module, and the scan module imports this one.
- from endpoints.sockets.scan import report_scan_failure
- from handler.redis_handler import scan_queue
- from tasks.registry import get_task
-
- task = get_task(name)
- if task is None:
- raise TaskNotFoundException(name)
-
- job = scan_queue.enqueue(
- run_task_by_name,
- kwargs={"name": name},
- on_failure=report_scan_failure,
- job_timeout=task.timeout,
- result_ttl=TASK_RESULT_TTL,
- meta={
- "task_name": task.title,
- "task_type": task.task_type.value,
- },
- )
- return job.id
-
-
def update_job_meta(metadata: dict[str, Any]) -> None:
"""Update the current RQ job's meta data with update stats information"""
try:
@@ -135,6 +99,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: ...
@@ -142,10 +111,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/adapters/services/test_sigil.py b/backend/tests/adapters/services/test_sigil.py
new file mode 100644
index 000000000..14fc3570b
--- /dev/null
+++ b/backend/tests/adapters/services/test_sigil.py
@@ -0,0 +1,162 @@
+import types
+from unittest.mock import Mock
+
+import pytest
+
+import adapters.services.sigil as sigil_adapter
+from adapters.services.sigil import 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(extract=extract)
+
+
+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,
+ save_id=save_id,
+ usage=usage,
+ switch_content_type=switch_content_type,
+ title_version=title_version,
+ )
+
+
+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_target="0100ABCD12340000",
+ usage="folder-exact",
+ )
+
+ @pytest.mark.asyncio
+ # Version 0 is a real base-game version, not a missing one.
+ @pytest.mark.parametrize(
+ ("content_type", "version"), [("patch", 196608), ("application", 0)]
+ )
+ async def test_maps_switch_content_type_and_version(
+ self,
+ service: SigilService,
+ monkeypatch,
+ content_type: str,
+ version: int,
+ ):
+ extract = Mock(
+ return_value=make_result(
+ switch_content_type=content_type,
+ title_version=version,
+ )
+ )
+ 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 == content_type
+ assert result.version == version
+
+ @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(
+ 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_no_decryption_keys_are_passed(
+ self, service: SigilService, monkeypatch, platform_slug: UPS
+ ):
+ """RomM never handles a user's console keys, so no key path is passed."""
+ 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")
+
+ extract.assert_called_once_with(
+ "/roms/switch/game.xci",
+ platform="switch",
+ filename_fallback=False,
+ )
diff --git a/backend/tests/endpoints/roms/test_identity.py b/backend/tests/endpoints/roms/test_identity.py
new file mode 100644
index 000000000..acab59892
--- /dev/null
+++ b/backend/tests/endpoints/roms/test_identity.py
@@ -0,0 +1,125 @@
+import pytest
+from fastapi import status
+from fastapi.testclient import TestClient
+
+from handler.database import db_platform_handler, db_rom_handler
+from models.platform import Platform
+from models.rom import Rom, SaveTargetLayout
+
+
+@pytest.fixture
+def switch_platform() -> Platform:
+ return db_platform_handler.add_platform(
+ Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
+ )
+
+
+@pytest.fixture
+def switch_rom(switch_platform: Platform) -> Rom:
+ return db_rom_handler.add_rom(
+ Rom(
+ platform_id=switch_platform.id,
+ name="Game",
+ slug="game",
+ fs_name="Game.nsp",
+ fs_name_no_tags="Game",
+ fs_name_no_ext="Game",
+ fs_extension="nsp",
+ fs_path="switch/roms",
+ fs_size_bytes=0,
+ )
+ )
+
+
+def test_stores_the_identity_a_client_extracted(
+ client: TestClient, access_token: str, switch_rom: Rom
+):
+ response = client.put(
+ f"/api/roms/{switch_rom.id}/identity",
+ headers={"Authorization": f"Bearer {access_token}"},
+ json={
+ "title_id": "0100ABCD12340000",
+ "save_target": "0100ABCD12340000",
+ "save_target_layout": "folder-exact",
+ },
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ stored = db_rom_handler.get_rom(switch_rom.id)
+ assert stored is not None
+ assert stored.title_id == "0100ABCD12340000"
+ assert stored.save_target == "0100ABCD12340000"
+ assert stored.save_target_layout == SaveTargetLayout.FOLDER_EXACT
+
+
+@pytest.mark.parametrize(
+ "submitted", ["0100ABCD12340800", "0100ABCD12341001"] # update, DLC
+)
+def test_a_switch_update_or_dlc_id_resolves_to_its_base(
+ client: TestClient, access_token: str, switch_rom: Rom, submitted: str
+):
+ """Reassociation matches on this id, so an update id here strands the entry."""
+ response = client.put(
+ f"/api/roms/{switch_rom.id}/identity",
+ headers={"Authorization": f"Bearer {access_token}"},
+ json={"title_id": submitted},
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ stored = db_rom_handler.get_rom(switch_rom.id)
+ assert stored is not None
+ assert stored.title_id == "0100ABCD12340000"
+
+
+def test_a_non_switch_serial_is_stored_verbatim(
+ client: TestClient, access_token: str, rom: Rom
+):
+ response = client.put(
+ f"/api/roms/{rom.id}/identity",
+ headers={"Authorization": f"Bearer {access_token}"},
+ json={"title_id": "SLUS-20152", "save_target": "BASLUS-20152"},
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ stored = db_rom_handler.get_rom(rom.id)
+ assert stored is not None
+ assert stored.title_id == "SLUS-20152"
+ assert stored.save_target == "BASLUS-20152"
+
+
+def test_omitted_fields_are_left_alone(
+ client: TestClient, access_token: str, switch_rom: Rom
+):
+ db_rom_handler.update_rom(
+ switch_rom.id,
+ {"title_id": "0100ABCD12340000", "save_target": "0100ABCD12340000"},
+ )
+
+ response = client.put(
+ f"/api/roms/{switch_rom.id}/identity",
+ headers={"Authorization": f"Bearer {access_token}"},
+ json={"save_target_layout": "folder-exact"},
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ stored = db_rom_handler.get_rom(switch_rom.id)
+ assert stored is not None
+ assert stored.title_id == "0100ABCD12340000"
+ assert stored.save_target == "0100ABCD12340000"
+
+
+def test_an_unknown_rom_is_not_found(client: TestClient, access_token: str):
+ response = client.put(
+ "/api/roms/99999/identity",
+ headers={"Authorization": f"Bearer {access_token}"},
+ json={"title_id": "0100ABCD12340000"},
+ )
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+
+def test_an_unauthenticated_write_is_rejected(client: TestClient, switch_rom: Rom):
+ response = client.put(
+ f"/api/roms/{switch_rom.id}/identity",
+ json={"title_id": "0100ABCD12340000"},
+ )
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py
index 363e89e3f..f178b6654 100644
--- a/backend/tests/endpoints/sockets/test_scan.py
+++ b/backend/tests/endpoints/sockets/test_scan.py
@@ -1,16 +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 (
- AbandonedJobError,
- InvalidJobOperation,
- NoSuchJobError,
+from rq.exceptions import AbandonedJobError, InvalidJobOperation
+from rq.job import JobStatus
+from tests.scan_job_stubs import (
+ NON_SCAN_FUNC,
+ make_job,
+ make_scoped_job,
+ make_task_job,
+ patch_scan_jobs,
)
-from rq.job import Job, JobStatus
from endpoints.sockets import scan as scan_module
from endpoints.sockets.scan import (
@@ -36,10 +37,10 @@ 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
-from tasks.tasks import TaskType
+from models.rom import Rom, RomFile, RomFileCategory
def test_scan_stats():
@@ -723,11 +724,84 @@ class TestScanAuthorization:
mocker.patch.object(
scan_module, "get_authenticated_user", AsyncMock(return_value=None)
)
- get_jobs = mocker.patch.object(scan_module.high_prio_queue, "get_jobs")
+ queued_jobs = mocker.patch.object(scan_module, "get_queued_scan_jobs")
await stop_scan_handler("sid")
- get_jobs.assert_not_called()
+ queued_jobs.assert_not_called()
+
+
+def patch_identify_rom(
+ mocker,
+ *,
+ parsed: ParsedRomFiles,
+ roms_fs_structure: str,
+ name_with_no_tags: str,
+ platform_slug: str,
+ embed_switch_title_ids: bool = False,
+) -> 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
+ config.SKIP_TITLE_ID_EXTRACTION = False
+ config.EMBED_SWITCH_TITLE_IDS = embed_switch_title_ids
+ 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:
@@ -739,90 +813,37 @@ class TestIdentifyRomReassociation:
@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="test/roms")
- mocker.patch.object(fs, "get_file_name_with_no_tags", return_value="New Name")
- mocker.patch.object(
- fs,
- "get_rom_files",
- AsyncMock(
- return_value=ParsedRomFiles(
- rom_files=[],
- crc_hash="crc",
- md5_hash="md5",
- sha1_hash="sha1",
- ra_hash="",
- )
+ return patch_identify_rom(
+ mocker,
+ parsed=ParsedRomFiles(
+ rom_files=[],
+ crc_hash="crc",
+ md5_hash="md5",
+ sha1_hash="sha1",
+ ra_hash="",
),
+ roms_fs_structure="test/roms",
+ name_with_no_tags="New Name",
+ platform_slug="test",
)
- config = MagicMock()
- config.SKIP_HASH_CALCULATION = 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)),
- )
-
- db = mocker.patch.object(scan_module, "db_rom_handler")
- db.add_rom.return_value = MagicMock(is_identified=False, id=99)
- return db
-
- def _platform(self):
- platform = Platform(name="Test", slug="test", fs_slug="test")
- platform.id = 1
- return platform
-
- async def _run(self, db):
- fs_rom: FSRom = {
- "fs_name": "New Name.zip",
- "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(),
- )
+ async def _run(self, platform: Platform) -> None:
+ await run_identify_rom(platform, make_fs_rom("New Name.zip"))
async def test_reassociates_with_missing_entry(self, patched):
- db = patched
+ db, platform = patched
missing = MagicMock(id=42, name="Old Game", fs_name="old.zip")
db.get_matching_missing_rom.return_value = missing
db.update_rom.return_value = missing
- await self._run(db)
+ await self._run(platform)
db.get_matching_missing_rom.assert_called_once_with(
platform_id=1,
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
@@ -832,35 +853,70 @@ 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, platform = 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(platform)
+
+ 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, platform = patched
db.get_matching_missing_rom.return_value = None
db.sync_rom_files.return_value = SyncedRomFiles(
files=[], orphaned_cover_paths=[]
)
- await self._run(db)
+ await self._run(platform)
# Rows are reconciled against the scan, so file ids survive the rescan.
db.sync_rom_files.assert_called_once_with(99, [])
async def test_orphaned_soundtrack_covers_are_unlinked(self, patched, mocker):
- db = patched
+ db, platform = patched
db.get_matching_missing_rom.return_value = None
db.sync_rom_files.return_value = SyncedRomFiles(
files=[], orphaned_cover_paths=["covers/track01.png"]
)
remove = mocker.patch.object(scan_module, "remove_persisted_cover")
- await self._run(db)
+ await self._run(platform)
remove.assert_called_once_with("covers/track01.png")
async def test_creates_new_entry_when_no_match(self, patched):
- db = patched
+ db, platform = patched
db.get_matching_missing_rom.return_value = None
- await self._run(db)
+ await self._run(platform)
db.get_matching_missing_rom.assert_called_once()
# No reassociation update happens on the create path.
@@ -872,6 +928,96 @@ 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):
+ 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",
+ embed_switch_title_ids=True,
+ )
+ db.get_matching_missing_rom.return_value = None
+ return db, platform
+
+ async def test_new_entry_carries_embedded_name(self, patched):
+ 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.
+ 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 TestIdentifyRomPersistsFileCategory:
+ """A file losing its category before `sync_rom_files` persists an update as
+ a plain game."""
+
+ UPDATE_TITLE_ID = "0100F4700B2E0800"
+
+ @pytest.fixture
+ def patched(self, mocker):
+ update_file = RomFile(
+ file_name="Game [UPD][v655360].nsp",
+ file_path="switch/roms",
+ file_size_bytes=1024,
+ category=RomFileCategory.UPDATE,
+ )
+ 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,
+ ),
+ roms_fs_structure="switch/roms",
+ name_with_no_tags="Game",
+ platform_slug="switch",
+ )
+ # The persist loop calls this per saved file; keep it inert.
+ mocker.patch.object(scan_module, "persist_soundtrack_cover")
+ 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, platform
+
+ async def test_rebuilt_file_keeps_category(self, patched):
+ 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
+ assert rom_id == 99
+ assert len(synced_files) == 1
+ persisted = synced_files[0]
+ assert isinstance(persisted, RomFile)
+ assert persisted.category == RomFileCategory.UPDATE
+
+
class TestIdentifyPlatformMarksMissingBeforeScan:
"""`_identify_platform` must flag missing entries before identifying files.
@@ -1682,83 +1828,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.kwargs = {}
- 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 make_scoped_job(**kwargs):
- """A scan of named roms, which the metadata refresh dialog asks for."""
- job = make_job(SCAN_PLATFORMS_FUNC, **kwargs)
- job.kwargs = {"platform_ids": [1], "roms_ids": [7]}
- return job
-
-
-def patch_scan_jobs(
- mocker,
- *,
- running=None,
- scan_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])
- mocker.patch.object(
- scan_module.scan_queue, "get_jobs", return_value=list(scan_queued)
- )
- mocker.patch.object(scan_module.high_prio_queue, "get_jobs", return_value=[])
- mocker.patch.object(
- scan_module.low_prio_queue, "get_jobs", return_value=list(low_queued)
- )
-
- scheduled_jobs = list(scheduled)
- registry = MagicMock()
- registry.get_job_ids.return_value = [job.id for job in scheduled_jobs]
- mocker.patch.object(
- scan_module, "_scheduled_scan_registries", return_value=[registry]
- )
- mocker.patch.object(scan_module.Job, "fetch_many", return_value=scheduled_jobs)
- return registry
-
-
class TestScanConcurrency:
"""A scan already in flight must block another from being enqueued."""
@@ -1830,12 +1899,7 @@ class TestScanConcurrency:
async def test_a_scan_left_on_an_older_queue_still_blocks(self, mocker, emit):
# A scan enqueued before scans had their own queue is on the high or low
# queue, and a worker will still run it.
- patch_scan_jobs(mocker)
- mocker.patch.object(
- scan_module.high_prio_queue,
- "get_jobs",
- return_value=[make_job(SCAN_PLATFORMS_FUNC)],
- )
+ patch_scan_jobs(mocker, high_queued=[make_job(SCAN_PLATFORMS_FUNC)])
enqueue = mocker.patch.object(scan_module.scan_queue, "enqueue")
await scan_handler("sid", {"type": "quick"})
@@ -1982,10 +2046,10 @@ class TestScanConcurrency:
# Only scans block scans; a cleanup or metadata task must not.
patch_scan_jobs(
mocker,
- running=make_job(CLEANUP_FUNC),
- scan_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),
+ scan_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.scan_queue, "enqueue")
@@ -2099,6 +2163,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.
@@ -2132,46 +2209,6 @@ class TestStopScan:
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_scheduled_time.return_value = self._due(2)
-
- assert scan_module.drop_stale_scheduled_scans() == 1
- job.cancel.assert_called_once()
-
- 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)
-
- 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
-
- 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_scheduled_time.return_value = self._due(2)
-
- assert scan_module.drop_stale_scheduled_scans() == 0
- job.cancel.assert_not_called()
-
-
class TestReportScanFailure:
"""A scan whose worker died cannot report itself, so RQ reports for it."""
@@ -2204,15 +2241,3 @@ class TestReportScanFailure:
)
emit.assert_not_awaited()
-
-
-class TestScheduledScanRegistries:
- """A scan delayed before scans had their own queue is still in the old one."""
-
- def test_reads_the_scan_queue_and_the_low_queue(self):
- names = [registry.name for registry in scan_module._scheduled_scan_registries()]
-
- assert names == [
- scan_module.scan_queue.name,
- scan_module.low_prio_queue.name,
- ]
diff --git a/backend/tests/endpoints/test_tasks.py b/backend/tests/endpoints/test_tasks.py
index a9f64fee1..409d11131 100644
--- a/backend/tests/endpoints/test_tasks.py
+++ b/backend/tests/endpoints/test_tasks.py
@@ -132,9 +132,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,
@@ -196,7 +195,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(
@@ -256,9 +255,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,
@@ -273,8 +272,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",
@@ -290,10 +288,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(
@@ -305,9 +302,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,
@@ -322,8 +319,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",
@@ -334,9 +330,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,
@@ -351,8 +347,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",
@@ -592,7 +587,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}"}
)
@@ -606,11 +601,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(
@@ -620,7 +612,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,
@@ -635,13 +627,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"""
@@ -656,9 +647,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,
@@ -672,7 +663,6 @@ class TestRunSingleTaskArgumentHandling:
),
},
)
- @patch("endpoints.tasks.VISIBLE_SCHEDULED_TASKS", ())
def test_body_cannot_override_the_task_name(
self, mock_enqueue, client, access_token
):
@@ -683,7 +673,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/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py
index 27101330b..68541185c 100644
--- a/backend/tests/handler/filesystem/test_roms_handler.py
+++ b/backend/tests/handler/filesystem/test_roms_handler.py
@@ -3,24 +3,22 @@ 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,
REGIONS_BY_SHORTCODE,
)
-from handler.filesystem.roms_handler import (
- FileHash,
- FSRomsHandler,
-)
+from handler.filesystem.roms_handler import FileHash, FSRomsHandler
from models.platform import Platform
-from models.rom import Rom, RomFile, RomFileCategory
+from models.rom import Rom, RomFile, RomFileCategory, SaveTargetLayout
from utils.archives import extract_chd_hash
@@ -1371,6 +1369,610 @@ class TestFSRomsHandler:
assert parsed.ra_hash == ""
+SIGIL_PATCH_TARGET = "adapters.services.sigil.SigilService.extract_title_id"
+
+SWITCH_PLATFORM = Platform(name="Nintendo Switch", slug="switch", fs_slug="switch")
+
+
+@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
+
+
+@pytest.fixture
+def stub_ra_hasher(monkeypatch):
+ """Keep the hashable-platform cases off the real RAHasher binary."""
+ monkeypatch.setattr(
+ "adapters.services.rahasher.RAHasherService.calculate_hash",
+ AsyncMock(return_value=""),
+ )
+
+
+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,
+ )
+
+
+async def switch_family_extract(
+ platform_slug: str, file_path: str
+) -> SigilExtractionResult:
+ """Stand in for sigil over a base/update/DLC folder, keyed by file name."""
+ if "update" in file_path:
+ return SigilExtractionResult(
+ title_id="0100ABCD12340800",
+ save_target="0100ABCD12340800",
+ usage="folder-exact",
+ content_type="patch",
+ version=196608,
+ )
+ if "dlc" in file_path:
+ return SigilExtractionResult(
+ title_id="0100ABCD12341001",
+ save_target="0100ABCD12341001",
+ usage="folder-exact",
+ content_type="addon",
+ version=0,
+ )
+ return SigilExtractionResult(
+ title_id="0100ABCD12340000",
+ save_target="0100ABCD12340000",
+ usage="folder-exact",
+ content_type="application",
+ version=0,
+ )
+
+
+class TestSigilTitleIdExtraction:
+ """Title id extraction via the sigil adapter during get_rom_files."""
+
+ @pytest.mark.asyncio
+ async def test_single_file_extraction_attaches_values(
+ self, tmp_path: Path, sigil_config: Config
+ ):
+ handler = make_sigil_handler(tmp_path)
+ rom = make_single_file_rom(tmp_path, SWITCH_PLATFORM, "Game.nsp")
+
+ extraction = SigilExtractionResult(
+ title_id="0100ABCD12340000",
+ save_target="0100ABCD12340000",
+ usage="folder-exact",
+ )
+ mock_extract = AsyncMock(return_value=extraction)
+
+ with patch(SIGIL_PATCH_TARGET, mock_extract):
+ parsed = await handler.get_rom_files(rom)
+
+ assert len(parsed.rom_files) == 1
+ assert parsed.title_id == "0100ABCD12340000"
+ assert parsed.save_target == "0100ABCD12340000"
+ assert parsed.save_target_layout == SaveTargetLayout.FOLDER_EXACT
+ mock_extract.assert_awaited_once_with(
+ "switch",
+ str(tmp_path / "switch/roms/Game.nsp"),
+ )
+
+ @pytest.mark.asyncio
+ async def test_multi_part_extraction_covers_nested_files(
+ self, tmp_path: Path, sigil_config: Config
+ ):
+ handler = make_sigil_handler(tmp_path)
+ rom = make_multi_part_rom(
+ tmp_path,
+ SWITCH_PLATFORM,
+ "Zelda",
+ [
+ "Zelda [base].nsp",
+ "updates/Zelda [update].nsp",
+ "dlc/Zelda [dlc].nsp",
+ ],
+ )
+
+ mock_extract = AsyncMock(side_effect=switch_family_extract)
+
+ 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}
+
+ assert by_name["Zelda [base].nsp"].category == RomFileCategory.GAME
+ assert by_name["Zelda [update].nsp"].category == RomFileCategory.UPDATE
+ assert by_name["Zelda [dlc].nsp"].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_target == "0100ABCD12340000"
+ assert parsed.save_target_layout == SaveTargetLayout.FOLDER_EXACT
+
+ @pytest.mark.asyncio
+ async def test_content_type_overrides_folder_category(
+ self, tmp_path: Path, sigil_config: Config
+ ):
+ 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 = make_multi_part_rom(
+ tmp_path, SWITCH_PLATFORM, "Zelda", ["dlc/Zelda [base].nsp"]
+ )
+
+ mock_extract = AsyncMock(
+ return_value=SigilExtractionResult(
+ title_id="0100ABCD12340000",
+ save_target="0100ABCD12340000",
+ usage="folder-exact",
+ content_type="application",
+ version=0,
+ )
+ )
+
+ 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, sigil_config: Config
+ ):
+ handler = make_sigil_handler(tmp_path)
+ rom = make_multi_part_rom(
+ tmp_path, SWITCH_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_target="0100ABCD12341001",
+ usage="folder-exact",
+ content_type=None,
+ version=None,
+ )
+ )
+
+ with patch(SIGIL_PATCH_TARGET, mock_extract):
+ parsed = await handler.get_rom_files(rom)
+
+ # The folder-derived category survives when the binary offers none.
+ assert parsed.rom_files[0].category == RomFileCategory.DLC
+
+ @pytest.mark.asyncio
+ async def test_non_rom_files_are_not_read(
+ self, tmp_path: Path, sigil_config: Config
+ ):
+ handler = make_sigil_handler(tmp_path)
+ rom = make_multi_part_rom(
+ tmp_path,
+ SWITCH_PLATFORM,
+ "Zelda",
+ [
+ "Zelda [base].nsp",
+ "manuals/Zelda.pdf",
+ "soundtracks/Zelda.mp3",
+ "screenshots/Zelda.png",
+ ],
+ )
+
+ mock_extract = AsyncMock(side_effect=switch_family_extract)
+
+ with patch(SIGIL_PATCH_TARGET, mock_extract):
+ await handler.get_rom_files(rom)
+
+ # Only the ROM file itself is worth a native parse.
+ assert mock_extract.await_count == 1
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("fs_name", "title_id", "expected"),
+ [
+ # A patch id carries bitmask 0x800.
+ ("Zelda [update].nsp", "0100ABCD12340800", "0100ABCD12340000"),
+ # A DLC id carries an odd program-index nibble.
+ ("Game [DLC].nsp", "0100ABCD12351064", "0100ABCD12350000"),
+ ],
+ )
+ async def test_switch_base_id_is_derived_when_no_base_file_is_present(
+ self,
+ tmp_path: Path,
+ sigil_config: Config,
+ fs_name: str,
+ title_id: str,
+ expected: str,
+ ):
+ handler = make_sigil_handler(tmp_path)
+ rom = make_single_file_rom(tmp_path, SWITCH_PLATFORM, fs_name)
+
+ mock_extract = AsyncMock(
+ return_value=SigilExtractionResult(
+ title_id=title_id,
+ save_target=title_id,
+ usage="folder-exact",
+ )
+ )
+
+ with patch(SIGIL_PATCH_TARGET, mock_extract):
+ parsed = await handler.get_rom_files(rom)
+
+ # Switch saves are keyed by the base title id itself.
+ assert parsed.title_id == expected
+ assert parsed.save_target == expected
+ assert parsed.save_target_layout == SaveTargetLayout.FOLDER_EXACT
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("platform", "fs_name", "extraction", "expected_layout"),
+ [
+ (
+ Platform(name="PlayStation Portable", slug="psp", fs_slug="psp"),
+ "Game.iso",
+ SigilExtractionResult(
+ title_id="ULUS-10041",
+ save_target="ULUS10041",
+ usage="folder-prefix",
+ ),
+ SaveTargetLayout.FOLDER_PREFIX,
+ ),
+ (
+ Platform(name="Nintendo 3DS", slug="3ds", fs_slug="3ds"),
+ "Game.3ds",
+ SigilExtractionResult(
+ title_id="0004000E0011C500",
+ # The split path in the emulator's case, not the flat id.
+ save_target="0004000e/0011c500",
+ usage="folder-split",
+ ),
+ SaveTargetLayout.FOLDER_SPLIT,
+ ),
+ (
+ Platform(name="Dreamcast", slug="dc", fs_slug="dc"),
+ "Game.chd",
+ SigilExtractionResult(
+ title_id="MK-51035",
+ save_target="MK-51035",
+ usage="file-prefix",
+ ),
+ SaveTargetLayout.FILE_PREFIX,
+ ),
+ ],
+ )
+ async def test_non_switch_platform_uses_first_extraction_verbatim(
+ self,
+ tmp_path: Path,
+ sigil_config: Config,
+ stub_ra_hasher: None,
+ platform: Platform,
+ fs_name: str,
+ extraction: SigilExtractionResult,
+ expected_layout: SaveTargetLayout,
+ ):
+ handler = make_sigil_handler(tmp_path)
+ rom = make_single_file_rom(tmp_path, platform, fs_name)
+
+ with patch(SIGIL_PATCH_TARGET, AsyncMock(return_value=extraction)):
+ parsed = await handler.get_rom_files(rom)
+
+ assert parsed.title_id == extraction.title_id
+ assert parsed.save_target == extraction.save_target
+ assert parsed.save_target_layout == expected_layout
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("platform", "fs_name", "kwargs"),
+ [
+ # Not a platform sigil covers.
+ (
+ Platform(name="Nintendo 64", slug="n64", fs_slug="n64"),
+ "Game.z64",
+ {"calculate_hashes": False},
+ ),
+ # Turned off by config.
+ (SWITCH_PLATFORM, "Game.nsp", {"extract_title_ids": False}),
+ # An archive holds no ROM binary sigil can read.
+ (SWITCH_PLATFORM, "game.zip", {}),
+ ],
+ )
+ async def test_extraction_is_skipped(
+ self,
+ tmp_path: Path,
+ sigil_config: Config,
+ platform: Platform,
+ fs_name: str,
+ kwargs: dict[str, bool],
+ ):
+ handler = make_sigil_handler(tmp_path)
+ rom = make_single_file_rom(tmp_path, platform, fs_name)
+
+ mock_extract = AsyncMock()
+
+ with patch(SIGIL_PATCH_TARGET, mock_extract):
+ parsed = await handler.get_rom_files(rom, **kwargs)
+
+ mock_extract.assert_not_awaited()
+ assert parsed.title_id is None
+ assert parsed.save_target_layout is None
+
+ @pytest.mark.asyncio
+ async def test_hashable_archive_rom_skips_extraction(
+ self, tmp_path: Path, sigil_config: Config, stub_ra_hasher: None
+ ):
+ 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 = make_sigil_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 patch(SIGIL_PATCH_TARGET, mock_extract):
+ parsed = await handler.get_rom_files(rom)
+
+ mock_extract.assert_not_awaited()
+ assert parsed.title_id is None
+
+
+class TestEmbedSwitchTitleIdInName:
+ """The rename helper that embeds a Switch title id into a filename."""
+
+ @pytest.fixture
+ def handler(self, tmp_path: Path) -> FSRomsHandler:
+ (tmp_path / "switch/roms").mkdir(parents=True)
+ return make_sigil_handler(tmp_path)
+
+ @staticmethod
+ def _write(handler: FSRomsHandler, name: str, content: bytes = b"rom") -> Path:
+ path = handler.base_path / "switch/roms" / name
+ path.write_bytes(content)
+ return path
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("name", "title_id", "version", "expected"),
+ [
+ (
+ "Moonlighter.xci",
+ "0100f4700b2e0000",
+ 3,
+ "Moonlighter [0100F4700B2E0000][v3].xci",
+ ),
+ # A missing version is a base game's version 0.
+ (
+ "Game.nsp",
+ "0100ABCD12340000",
+ None,
+ "Game [0100ABCD12340000][v0].nsp",
+ ),
+ (
+ "Game (USA) (Rev 1).xci",
+ "0100ABCD12340000",
+ 0,
+ "Game (USA) (Rev 1) [0100ABCD12340000][v0].xci",
+ ),
+ ],
+ )
+ async def test_embeds_id_and_version(
+ self,
+ handler: FSRomsHandler,
+ name: str,
+ title_id: str,
+ version: int | None,
+ expected: str,
+ ):
+ src = self._write(handler, name)
+
+ new_name = await handler._embed_switch_title_id_in_name(
+ Path("switch/roms", name), title_id, version
+ )
+
+ assert new_name == expected
+ assert (handler.base_path / "switch/roms" / expected).exists()
+ assert not src.exists()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("name", "title_id"),
+ [
+ # Already embedded, so renaming again would stack the tags.
+ ("Game [0100ABCD12340000][v0].nsp", "0100ABCD12340000"),
+ ("Game.nsp", "NOT-A-TITLE-ID"),
+ ],
+ )
+ async def test_file_is_left_alone(
+ self, handler: FSRomsHandler, name: str, title_id: str
+ ):
+ src = self._write(handler, name)
+
+ assert (
+ await handler._embed_switch_title_id_in_name(
+ Path("switch/roms", name), title_id, 0
+ )
+ is None
+ )
+ assert src.exists()
+
+ @pytest.mark.asyncio
+ async def test_collision_skips_and_leaves_both_files(self, handler: FSRomsHandler):
+ src = self._write(handler, "Game.nsp", b"original")
+ target = self._write(handler, "Game [0100ABCD12340000][v0].nsp", b"existing")
+
+ assert (
+ await handler._embed_switch_title_id_in_name(
+ Path("switch/roms/Game.nsp"), "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."""
+
+ @pytest.mark.asyncio
+ async def test_flag_off_leaves_file_unchanged(
+ self, tmp_path: Path, sigil_config: Config
+ ):
+ handler = make_sigil_handler(tmp_path)
+ rom = make_single_file_rom(tmp_path, SWITCH_PLATFORM, "Game.nsp")
+
+ extraction = SigilExtractionResult(
+ title_id="0100ABCD12340000",
+ save_target="0100ABCD12340000",
+ usage="folder-exact",
+ )
+
+ 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
+ assert (tmp_path / "switch/roms/Game.nsp").exists()
+
+ @pytest.mark.asyncio
+ async def test_single_file_renamed_and_reconciled(
+ self, tmp_path: Path, sigil_config: Config
+ ):
+ handler = make_sigil_handler(tmp_path)
+ rom = make_single_file_rom(tmp_path, SWITCH_PLATFORM, "Moonlighter.xci")
+
+ extraction = SigilExtractionResult(
+ title_id="0100F4700B2E0000",
+ save_target="0100F4700B2E0000",
+ usage="folder-exact",
+ version=0,
+ )
+
+ 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
+ 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_non_switch_platform_never_renamed(
+ self, tmp_path: Path, sigil_config: Config, stub_ra_hasher: None
+ ):
+ platform = Platform(name="PlayStation Portable", slug="psp", fs_slug="psp")
+ handler = make_sigil_handler(tmp_path)
+ rom = make_single_file_rom(tmp_path, platform, "Game.iso")
+
+ extraction = SigilExtractionResult(
+ title_id="0100ABCD12340000",
+ save_target="0100ABCD12340000",
+ usage="folder-exact",
+ )
+
+ 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_no_title_id_not_renamed(self, tmp_path: Path, sigil_config: Config):
+ handler = make_sigil_handler(tmp_path)
+ rom = make_single_file_rom(tmp_path, SWITCH_PLATFORM, "Game.nsp")
+
+ 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
+ assert (tmp_path / "switch/roms/Game.nsp").exists()
+
+ @pytest.mark.asyncio
+ async def test_multi_part_nested_files_renamed(
+ self, tmp_path: Path, sigil_config: Config
+ ):
+ handler = make_sigil_handler(tmp_path)
+ rom = make_multi_part_rom(
+ tmp_path,
+ SWITCH_PLATFORM,
+ "Zelda",
+ ["Zelda base.nsp", "updates/Zelda update.nsp", "dlc/Zelda dlc.nsp"],
+ )
+
+ with patch(SIGIL_PATCH_TARGET, AsyncMock(side_effect=switch_family_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"""
diff --git a/backend/tests/handler/test_db_handler.py b/backend/tests/handler/test_db_handler.py
index c7b71e01a..6a867fb2a 100644
--- a/backend/tests/handler/test_db_handler.py
+++ b/backend/tests/handler/test_db_handler.py
@@ -1101,7 +1101,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"
)
@@ -1112,6 +1112,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(
diff --git a/backend/tests/handler/test_fastapi.py b/backend/tests/handler/test_fastapi.py
index 417b2cc5b..0fee47256 100644
--- a/backend/tests/handler/test_fastapi.py
+++ b/backend/tests/handler/test_fastapi.py
@@ -32,7 +32,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, SaveTargetLayout
from utils.context import initialize_context
@@ -201,6 +201,74 @@ async def test_scan_rom_complete_clears_unselected_metadata(
assert result.hasheous_id == 999
+@pytest.mark.parametrize(
+ ("stored_title_id", "extracted_title_id"),
+ [
+ # A first extraction lands on a rom that has no identity yet.
+ (None, "0100ABCD12340000"),
+ # A hash-only or extraction-disabled rescan must not wipe what is there.
+ ("0100ABCD12340000", None),
+ ],
+)
+@patch.object(meta_playmatch_handler, "is_enabled", return_value=False)
+async def test_scan_rom_folds_extracted_title_id_values(
+ mock_playmatch_enabled,
+ stored_title_id: str | None,
+ extracted_title_id: str | None,
+):
+ 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=stored_title_id,
+ save_target=stored_title_id,
+ save_target_layout=(SaveTargetLayout.FOLDER_EXACT if stored_title_id else None),
+ )
+ 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": extracted_title_id,
+ "save_target": extracted_title_id,
+ "save_target_layout": (
+ SaveTargetLayout.FOLDER_EXACT if extracted_title_id else None
+ ),
+ },
+ metadata_sources=[],
+ newly_added=False,
+ )
+
+ assert result.title_id == "0100ABCD12340000"
+ assert result.save_target == "0100ABCD12340000"
+ assert result.save_target_layout == SaveTargetLayout.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)
diff --git a/backend/tests/handler/test_redis_handler.py b/backend/tests/handler/test_redis_handler.py
index 2a55b38cc..8ccecde33 100644
--- a/backend/tests/handler/test_redis_handler.py
+++ b/backend/tests/handler/test_redis_handler.py
@@ -1,9 +1,16 @@
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 (
+ cancel_job,
+ get_job_func_name,
+ get_job_kwargs,
+ get_job_status,
+ get_worker_current_job,
+)
def make_job() -> MagicMock:
@@ -69,3 +76,39 @@ class TestGetJobStatus:
job.get_status.side_effect = InvalidJobOperation
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:
+ 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/handler/test_scan_jobs.py b/backend/tests/handler/test_scan_jobs.py
new file mode 100644
index 000000000..ec49e2482
--- /dev/null
+++ b/backend/tests/handler/test_scan_jobs.py
@@ -0,0 +1,151 @@
+from datetime import datetime, timezone
+
+from rq.job import JobStatus
+from tests.scan_job_stubs import (
+ NON_SCAN_FUNC,
+ make_job,
+ make_scoped_job,
+ make_task_job,
+ patch_scan_jobs,
+)
+
+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():
+ """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(NON_SCAN_FUNC))
+
+
+class TestIsScopedScanJob:
+ def test_recognises_a_scan_of_named_roms(self):
+ assert scan_jobs.is_scoped_scan_job(make_scoped_job())
+
+ def test_treats_a_library_scan_as_unscoped(self):
+ assert not scan_jobs.is_scoped_scan_job(make_job(SCAN_PLATFORMS_FUNC))
+
+ def test_treats_a_scan_it_cannot_read_as_unscoped(self, mocker):
+ # A payload that will not deserialize fails on the next dequeue, so it
+ # stops standing in the way by itself.
+ mocker.patch.object(scan_jobs, "get_job_kwargs", return_value=None)
+
+ assert not scan_jobs.is_scoped_scan_job(make_scoped_job())
+
+
+class TestGetQueuedScanJobs:
+ def test_collects_scans_from_every_queue(self, mocker):
+ # A scan enqueued before scans had their own queue is on one of the
+ # others, and a worker will still run it.
+ scan = make_job(SCAN_PLATFORMS_FUNC)
+ high = make_job(SCAN_PLATFORMS_FUNC)
+ low = make_task_job()
+ patch_scan_jobs(
+ mocker, scan_queued=[scan], high_queued=[high], low_queued=[low]
+ )
+
+ assert scan_jobs.get_queued_scan_jobs() == [scan, high, low]
+
+ def test_leaves_out_jobs_that_are_not_scans(self, mocker):
+ patch_scan_jobs(mocker, high_queued=[make_job(NON_SCAN_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(NON_SCAN_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()
+
+
+class TestScheduledScanRegistries:
+ """A scan delayed before scans had their own queue is still in the old one."""
+
+ def test_reads_the_scan_queue_and_the_low_queue(self):
+ names = [registry.name for registry in scan_jobs._scheduled_scan_registries()]
+
+ assert names == [scan_jobs.scan_queue.name, scan_jobs.low_prio_queue.name]
diff --git a/backend/tests/scan_job_stubs.py b/backend/tests/scan_job_stubs.py
new file mode 100644
index 000000000..be52a575f
--- /dev/null
+++ b/backend/tests/scan_job_stubs.py
@@ -0,0 +1,105 @@
+"""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, run_task_by_name
+
+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()
+
+
+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.kwargs = {}
+ 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 make_scoped_job(**kwargs):
+ """A scan of named roms, which the metadata refresh dialog asks for."""
+ job = make_job(scan_jobs_module.SCAN_PLATFORMS_FUNC, **kwargs)
+ job.kwargs = {"platform_ids": [1], "roms_ids": [7]}
+ return job
+
+
+def patch_scan_jobs(
+ mocker,
+ *,
+ running=None,
+ scan_queued=(),
+ 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(scan_queued) + list(high_queued) + list(low_queued)
+ scheduled_jobs = list(scheduled)
+ mocker.patch.object(
+ scan_jobs_module.scan_queue,
+ "get_job_ids",
+ return_value=[job.id for job in scan_queued],
+ )
+ 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_registries", 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/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_cron_config.py b/backend/tests/tasks/test_cron_config.py
index 775a1942c..77e1540db 100644
--- a/backend/tests/tasks/test_cron_config.py
+++ b/backend/tests/tasks/test_cron_config.py
@@ -3,15 +3,10 @@ import importlib
import pytest
from config import TASK_RESULT_TTL, TASK_TIMEOUT
-from endpoints.responses import TaskType
from handler.redis_handler import QueuePrio
from tasks import cron_config
-from tasks.registry import SCHEDULED_TASKS
-from tasks.tasks import (
- SCAN_DISPATCH_META_KEY,
- enqueue_scheduled_scan,
- run_task_by_name,
-)
+from tasks.registry import SCHEDULED_TASKS, enqueue_scheduled_scan
+from tasks.tasks import SCAN_DISPATCH_META_KEY, TaskType, run_task_by_name
@pytest.fixture
@@ -35,12 +30,14 @@ def _task(mocker, *, enabled=True, cron_string="0 4 * * *"):
title="Test Task",
description="test task",
task_type=TaskType.CLEANUP,
+ job_meta={"task_name": "Test Task", "task_type": TaskType.CLEANUP.value},
)
def _scan_task(mocker, **kwargs):
task = _task(mocker, **kwargs)
task.task_type = TaskType.SCAN
+ task.job_meta = {"task_name": "Test Task", "task_type": TaskType.SCAN.value}
return task
@@ -65,7 +62,11 @@ class TestCronConfig:
kwargs = register.call_args.kwargs
assert register.call_args.args[0] is enqueue_scheduled_scan
assert kwargs["job_timeout"] == TASK_TIMEOUT
- assert kwargs["meta"][SCAN_DISPATCH_META_KEY] is True
+ assert kwargs["meta"] == {
+ "task_name": "Test Task",
+ "task_type": TaskType.SCAN.value,
+ SCAN_DISPATCH_META_KEY: True,
+ }
def test_everything_runs_on_the_low_queue(self, mocker, registered):
for tasks in ({"cleanup": _task(mocker)}, {"scan": _scan_task(mocker)}):
@@ -79,6 +80,16 @@ class TestCronConfig:
assert register.call_args.kwargs["result_ttl"] == TASK_RESULT_TTL
+ 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_skips_a_disabled_task(self, mocker, registered):
assert registered({"off": _task(mocker, enabled=False)}).call_count == 0
diff --git a/backend/tests/tasks/test_registry.py b/backend/tests/tasks/test_registry.py
index 4a3f98b6e..eef0b7c3c 100644
--- a/backend/tests/tasks/test_registry.py
+++ b/backend/tests/tasks/test_registry.py
@@ -1,7 +1,16 @@
import pytest
-from tasks.registry import MANUAL_TASKS, SCHEDULED_TASKS, get_task
-from tasks.tasks import PeriodicTask
+from config import SCAN_TIMEOUT, TASK_RESULT_TTL
+from endpoints.sockets.scan import report_scan_failure
+from exceptions.task_exceptions import TaskNotFoundException
+from tasks.registry import (
+ MANUAL_TASKS,
+ SCHEDULED_TASKS,
+ enqueue_scheduled_scan,
+ enqueue_task,
+ get_task,
+)
+from tasks.tasks import PeriodicTask, run_task_by_name
class TestRegistry:
@@ -20,3 +29,69 @@ 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()
+
+
+class TestEnqueueScheduledScan:
+ """Cron cannot attach a failure callback, so a dispatch job does it."""
+
+ @pytest.fixture
+ def scan_queue(self, mocker):
+ queue = mocker.patch("tasks.registry.scan_queue")
+ queue.enqueue.return_value = mocker.MagicMock(id="job-1")
+ return queue
+
+ def test_enqueues_the_scan_with_the_abandoned_job_callback(self, scan_queue):
+ assert enqueue_scheduled_scan("scan_library") == "job-1"
+
+ args, kwargs = scan_queue.enqueue.call_args
+ assert args[0] is run_task_by_name
+ assert kwargs["kwargs"]["name"] == "scan_library"
+ assert kwargs["on_failure"] is report_scan_failure
+
+ def test_the_scan_carries_the_scan_timeout(self, scan_queue):
+ # The dispatch itself runs on the ordinary task timeout, so the scan
+ # timeout has to reach the scan it creates.
+ enqueue_scheduled_scan("scan_library")
+
+ assert scan_queue.enqueue.call_args.kwargs["job_timeout"] == SCAN_TIMEOUT
diff --git a/backend/tests/tasks/test_scan_library.py b/backend/tests/tasks/test_scan_library.py
index fd6ab9832..29540f728 100644
--- a/backend/tests/tasks/test_scan_library.py
+++ b/backend/tests/tasks/test_scan_library.py
@@ -29,7 +29,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):
@@ -86,10 +85,6 @@ 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"
- )
def test_scheduled_rescan_gets_the_scan_timeout():
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..14cc126cb 100644
--- a/backend/tests/tasks/test_task_func_paths.py
+++ b/backend/tests/tasks/test_task_func_paths.py
@@ -1,34 +1,26 @@
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 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",
+ "tasks.registry.enqueue_scheduled_scan",
+)
-@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 d0e74b6e3..181fde526 100644
--- a/backend/tests/tasks/test_tasks.py
+++ b/backend/tests/tasks/test_tasks.py
@@ -3,15 +3,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
import httpx
import pytest
-from config import TASK_RESULT_TTL
from exceptions.task_exceptions import TaskNotFoundException
-from tasks.tasks import (
- PeriodicTask,
- RemoteFilePullTask,
- TaskType,
- enqueue_scheduled_scan,
- run_task_by_name,
-)
+from tasks.tasks import PeriodicTask, RemoteFilePullTask, TaskType, run_task_by_name
class ConcretePeriodicTask(PeriodicTask):
@@ -25,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,
@@ -36,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,
@@ -46,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
@@ -62,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",
@@ -74,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",
@@ -84,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
@@ -207,58 +194,3 @@ class TestRunTaskByName:
with pytest.raises(TaskNotFoundException, match="some_task"):
await run_task_by_name("some_task")
-
-
-class TestEnqueueScheduledScan:
- """Cron cannot attach a failure callback, so a dispatch job does it."""
-
- @pytest.fixture
- def scan_queue(self, mocker):
- queue = mocker.patch("handler.redis_handler.scan_queue")
- queue.enqueue.return_value = MagicMock(id="job-1")
- return queue
-
- @pytest.fixture
- def task(self, mocker):
- task = MagicMock(title="Scan Library", task_type=TaskType.SCAN, timeout=14400)
- mocker.patch("tasks.registry.get_task", return_value=task)
- return task
-
- def test_enqueues_the_scan_with_the_abandoned_job_callback(
- self, scan_queue, task
- ) -> None:
- from endpoints.sockets.scan import report_scan_failure
-
- assert enqueue_scheduled_scan("scan_library") == "job-1"
-
- kwargs = scan_queue.enqueue.call_args.kwargs
- assert scan_queue.enqueue.call_args.args[0] is run_task_by_name
- assert kwargs["kwargs"] == {"name": "scan_library"}
- assert kwargs["on_failure"] is report_scan_failure
-
- def test_the_scan_carries_its_own_timeout_and_result_ttl(
- self, scan_queue, task
- ) -> None:
- # The dispatch runs on the ordinary task timeout; the scan timeout
- # belongs to the scan the dispatch creates.
- enqueue_scheduled_scan("scan_library")
-
- kwargs = scan_queue.enqueue.call_args.kwargs
- assert kwargs["job_timeout"] == task.timeout
- assert kwargs["result_ttl"] == TASK_RESULT_TTL
-
- def test_the_scan_is_labelled_for_the_task_history(self, scan_queue, task) -> None:
- enqueue_scheduled_scan("scan_library")
-
- assert scan_queue.enqueue.call_args.kwargs["meta"] == {
- "task_name": "Scan Library",
- "task_type": TaskType.SCAN.value,
- }
-
- def test_raises_for_a_name_that_is_not_registered(self, mocker, scan_queue) -> None:
- mocker.patch("tasks.registry.get_task", return_value=None)
-
- with pytest.raises(TaskNotFoundException, match="nope"):
- enqueue_scheduled_scan("nope")
-
- scan_queue.enqueue.assert_not_called()
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/tests/utils/test_switch.py b/backend/tests/utils/test_switch.py
new file mode 100644
index 000000000..b057ff6b7
--- /dev/null
+++ b/backend/tests/utils/test_switch.py
@@ -0,0 +1,62 @@
+import pytest
+
+from utils import switch
+
+
+class TestIsBaseTitleId:
+ @pytest.mark.parametrize(
+ "title_id",
+ ["0100ABCD12340000", "0100F4700B2E0000", "0100abcd12340000"],
+ )
+ def test_base_ids_are_recognized(self, title_id: str):
+ assert switch.is_base_title_id(title_id)
+
+ @pytest.mark.parametrize(
+ "title_id",
+ [
+ "0100ABCD12340800", # update: odd program-index nibble
+ "0100ABCD12341001", # DLC: low bits set
+ "",
+ "000",
+ "0100ABCD1234ZZZ0", # non-hex nibble
+ ],
+ )
+ def test_non_base_ids_are_rejected(self, title_id: str):
+ assert not switch.is_base_title_id(title_id)
+
+
+class TestDeriveBaseTitleId:
+ def test_update_resolves_to_its_base(self):
+ assert switch.derive_base_title_id("0100ABCD12340800") == "0100ABCD12340000"
+
+ def test_dlc_resolves_to_its_base(self):
+ assert switch.derive_base_title_id("0100ABCD12341001") == "0100ABCD12340000"
+
+ def test_a_base_id_is_left_alone(self):
+ assert switch.derive_base_title_id("0100ABCD12340000") == "0100ABCD12340000"
+
+ def test_case_of_the_program_index_nibble_is_preserved(self):
+ assert switch.derive_base_title_id("0100abcd1234e000") == "0100abcd1234e000"
+ assert switch.derive_base_title_id("0100ABCD1234E000") == "0100ABCD1234E000"
+
+ @pytest.mark.parametrize("title_id", ["", "000", "0100ABCD1234ZZZ0"])
+ def test_unparseable_ids_yield_nothing(self, title_id: str):
+ assert switch.derive_base_title_id(title_id) is None
+
+
+class TestTitleIdRegexes:
+ def test_a_bare_id_matches_the_plain_regex(self):
+ assert switch.TITLE_ID_REGEX.fullmatch("0100ABCD12340000")
+
+ @pytest.mark.parametrize(
+ "value",
+ ["0100ABCD1234000", "0100ABCD123400001", "[0100ABCD12340000]", "xyz"],
+ )
+ def test_anything_else_does_not(self, value: str):
+ 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")
+
+ def test_a_name_without_one_is_not_matched(self):
+ assert not switch.TITLE_ID_BRACKET_REGEX.search("Game [USA][v0].nsp")
diff --git a/backend/utils/switch.py b/backend/utils/switch.py
new file mode 100644
index 000000000..132c56d3a
--- /dev/null
+++ b/backend/utils/switch.py
@@ -0,0 +1,40 @@
+"""Switch title-id knowledge: recognising a base-game id, recovering one from an
+update or DLC id, and mapping a content type to a file category."""
+
+import re
+from typing import Final
+
+from models.rom import RomFileCategory
+
+# Maps sigil's Switch CNMT content type to the RomFile category. Authoritative
+# over folder-derived categories when the binary parse succeeds.
+CONTENT_TYPE_CATEGORIES: Final[dict[str, RomFileCategory]] = {
+ "application": RomFileCategory.GAME,
+ "patch": RomFileCategory.UPDATE,
+ "addon": RomFileCategory.DLC,
+}
+
+TITLE_ID_REGEX: Final = re.compile(r"[0-9A-Fa-f]{16}")
+# An already-embedded id, e.g. [0100F4700B2E0000].
+TITLE_ID_BRACKET_REGEX: Final = re.compile(rf"\[{TITLE_ID_REGEX.pattern}\]")
+
+
+def derive_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 is_base_title_id(title_id: str) -> bool:
+ """A base-game id is its own derived base."""
+ return derive_base_title_id(title_id) == title_id
diff --git a/backend/watcher.py b/backend/watcher.py
index 0e04f874d..ec55e2118 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,
- report_scan_failure,
- scan_platforms,
-)
+from endpoints.sockets.scan import report_scan_failure, scan_job_meta, scan_platforms
from handler.database import db_platform_handler
from handler.metadata import (
meta_csdb_handler,
@@ -45,10 +41,10 @@ from handler.metadata import (
)
from handler.redis_handler import get_job_kwargs, scan_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
-from tasks.tasks import TaskType
from utils import get_version
sentry_sdk.init(
@@ -214,23 +210,23 @@ 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:
scan_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,
on_failure=report_scan_failure,
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
@@ -248,20 +244,7 @@ def process_changes(changes: Sequence[Change]) -> None:
continue
log.info(f"Change detected in {hl(fs_slug)} folder, {rescan_in_msg}")
- scan_queue.enqueue_in(
- time_delta,
- scan_platforms,
- platform_ids=[db_platform.id],
- metadata_sources=metadata_sources,
- scan_type=ScanType.QUICK,
- on_failure=report_scan_failure,
- 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/Dockerfile b/docker/Dockerfile
index 37702b4a6..55ec7b2c6 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,33 @@ 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
+
+# Keep this pin in sync with the dev image's SIGIL_VERSION in ../Dockerfile.
+ARG SIGIL_VERSION=9665f03c04d0f547ed38dd5e5e31916c1da5f2e9
+
+RUN git clone --filter=blob:none 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, RUFFLE AND JS-DOS
FROM alpine:${ALPINE_VERSION}@sha256:${ALPINE_SHA256} AS emulator-stage
@@ -236,6 +264,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
diff --git a/docker/init_scripts/init b/docker/init_scripts/init
index 1bbcdacb9..c45c265aa 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/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md
index 1bfd08609..95480776c 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
@@ -1486,6 +1487,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)
@@ -1657,6 +1663,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/entrypoint.sh b/entrypoint.sh
index d00a89188..cea3b740d 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
diff --git a/examples/config.example.yml b/examples/config.example.yml
index 2c953b434..5ea43bb58 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/index.html b/frontend/index.html
index 2c4572348..2e8f95f89 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -5,7 +5,7 @@
-
+
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 16a1ab040..0ecae0c94 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -2716,29 +2716,43 @@
}
},
"node_modules/@humanfs/core": {
- "version": "0.19.1",
- "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz",
- "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==",
+ "version": "0.19.2",
+ "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",
+ "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==",
"dev": true,
"license": "Apache-2.0",
+ "dependencies": {
+ "@humanfs/types": "^0.15.0"
+ },
"engines": {
"node": ">=18.18.0"
}
},
"node_modules/@humanfs/node": {
- "version": "0.16.7",
- "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz",
- "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==",
+ "version": "0.16.8",
+ "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz",
+ "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
- "@humanfs/core": "^0.19.1",
+ "@humanfs/core": "^0.19.2",
+ "@humanfs/types": "^0.15.0",
"@humanwhocodes/retry": "^0.4.0"
},
"engines": {
"node": ">=18.18.0"
}
},
+ "node_modules/@humanfs/types": {
+ "version": "0.15.0",
+ "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz",
+ "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=18.18.0"
+ }
+ },
"node_modules/@humanwhocodes/module-importer": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",
@@ -7617,9 +7631,9 @@
"license": "MIT"
},
"node_modules/fast-uri": {
- "version": "3.1.5",
- "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz",
- "integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==",
+ "version": "3.1.7",
+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz",
+ "integrity": "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==",
"dev": true,
"funding": [
{
diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts
index 4231b54a8..25cf80c4b 100644
--- a/frontend/src/__generated__/index.ts
+++ b/frontend/src/__generated__/index.ts
@@ -158,6 +158,7 @@ export type { RomFlashpointMetadata } from './models/RomFlashpointMetadata';
export type { RomGamelistMetadata } from './models/RomGamelistMetadata';
export type { RomHasheousMetadata } from './models/RomHasheousMetadata';
export type { RomHLTBMetadata } from './models/RomHLTBMetadata';
+export type { RomIdentityData } from './models/RomIdentityData';
export type { RomIGDBMetadata } from './models/RomIGDBMetadata';
export type { RomLaunchboxMetadata } from './models/RomLaunchboxMetadata';
export type { RomMetadataSchema } from './models/RomMetadataSchema';
@@ -174,6 +175,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 { SaveTargetLayout } from './models/SaveTargetLayout';
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 e2844da6c..20c2047d9 100644
--- a/frontend/src/__generated__/models/DetailedRomSchema.ts
+++ b/frontend/src/__generated__/models/DetailedRomSchema.ts
@@ -20,6 +20,7 @@ import type { RomSSMetadata } from './RomSSMetadata';
import type { RomSteamMetadata } from './RomSteamMetadata';
import type { RomUserSchema } from './RomUserSchema';
import type { SaveSchema } from './SaveSchema';
+import type { SaveTargetLayout } from './SaveTargetLayout';
import type { ScreenshotSchema } from './ScreenshotSchema';
import type { SiblingRomSchema } from './SiblingRomSchema';
import type { StateSchema } from './StateSchema';
@@ -96,6 +97,9 @@ export type DetailedRomSchema = {
md5_hash: (string | null);
sha1_hash: (string | null);
ra_hash: (string | null);
+ title_id: (string | null);
+ save_target: (string | null);
+ save_target_layout: (SaveTargetLayout | null);
has_simple_single_file: boolean;
has_nested_single_file: boolean;
has_multiple_files: boolean;
diff --git a/frontend/src/__generated__/models/RomIdentityData.ts b/frontend/src/__generated__/models/RomIdentityData.ts
new file mode 100644
index 000000000..f047bbbd6
--- /dev/null
+++ b/frontend/src/__generated__/models/RomIdentityData.ts
@@ -0,0 +1,23 @@
+/* generated using openapi-typescript-codegen -- do not edit */
+/* istanbul ignore file */
+/* tslint:disable */
+/* eslint-disable */
+import type { SaveTargetLayout } from './SaveTargetLayout';
+/**
+ * Binary identity a client extracted for a ROM that RomM cannot read itself.
+ */
+export type RomIdentityData = {
+ /**
+ * Platform-native identity, e.g. 0100ABCD12340000 or SLUS-20152.
+ */
+ title_id?: (string | null);
+ /**
+ * On-disk name the emulator gives this game's saves.
+ */
+ save_target?: (string | null);
+ /**
+ * How to apply save_target when locating saves on disk.
+ */
+ save_target_layout?: (SaveTargetLayout | null);
+};
+
diff --git a/frontend/src/__generated__/models/SaveTargetLayout.ts b/frontend/src/__generated__/models/SaveTargetLayout.ts
new file mode 100644
index 000000000..e1a96b1f7
--- /dev/null
+++ b/frontend/src/__generated__/models/SaveTargetLayout.ts
@@ -0,0 +1,5 @@
+/* generated using openapi-typescript-codegen -- do not edit */
+/* istanbul ignore file */
+/* tslint:disable */
+/* eslint-disable */
+export type SaveTargetLayout = 'folder-exact' | 'folder-prefix' | 'file-exact' | 'file-prefix' | 'folder-split';
diff --git a/frontend/src/__generated__/models/SimpleRomSchema.ts b/frontend/src/__generated__/models/SimpleRomSchema.ts
index 76f4e2c46..0eef0a6d5 100644
--- a/frontend/src/__generated__/models/SimpleRomSchema.ts
+++ b/frontend/src/__generated__/models/SimpleRomSchema.ts
@@ -19,6 +19,7 @@ import type { RomRAMetadata } from './RomRAMetadata';
import type { RomSSMetadata } from './RomSSMetadata';
import type { RomSteamMetadata } from './RomSteamMetadata';
import type { RomUserSchema } from './RomUserSchema';
+import type { SaveTargetLayout } from './SaveTargetLayout';
import type { SiblingRomSchema } from './SiblingRomSchema';
export type SimpleRomSchema = {
id: number;
@@ -88,6 +89,9 @@ export type SimpleRomSchema = {
md5_hash: (string | null);
sha1_hash: (string | null);
ra_hash: (string | null);
+ title_id: (string | null);
+ save_target: (string | null);
+ save_target_layout: (SaveTargetLayout | 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 46c91b932..daee7d887 100644
--- a/frontend/src/locales/bg_BG/rom.json
+++ b/frontend/src/locales/bg_BG/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "ROM-ът е обновен успешно!",
"save-data": "Данни от записи",
"save-deleted": "Записът е изтрит.",
+ "save-target": "Save File/Folder Target",
"saves-empty": "Все още няма записи",
"saves-empty-hint": "Записите, качени за този ROM, ще се появят тук.",
"saves-section-community": "Community",
@@ -453,6 +454,7 @@
"tab-notes": "Бележки",
"tab-overview": "Преглед",
"tags": "Тагове",
+ "title-id": "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 f60cde412..bfe6ebef8 100644
--- a/frontend/src/locales/cs_CZ/rom.json
+++ b/frontend/src/locales/cs_CZ/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "ROM úspěšně aktualizována!",
"save-data": "Uložená data",
"save-deleted": "Uložená pozice smazána.",
+ "save-target": "Save File/Folder Target",
"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",
@@ -453,6 +454,7 @@
"tab-notes": "Poznámky",
"tab-overview": "Přehled",
"tags": "Štítky",
+ "title-id": "ID titulu",
"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 6b1c32cf3..9ecde8d49 100644
--- a/frontend/src/locales/de_DE/rom.json
+++ b/frontend/src/locales/de_DE/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "ROM erfolgreich aktualisiert!",
"save-data": "Speicherdaten",
"save-deleted": "Spielstand gelöscht.",
+ "save-target": "Save File/Folder Target",
"saves-empty": "Noch keine Spielstände",
"saves-empty-hint": "Für diese ROM hochgeladene Spielstände erscheinen hier.",
"saves-section-community": "Community",
@@ -453,6 +454,7 @@
"tab-notes": "Notizen",
"tab-overview": "Übersicht",
"tags": "Tags",
+ "title-id": "Titel-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 cb88a0825..9454c9abf 100644
--- a/frontend/src/locales/en_GB/rom.json
+++ b/frontend/src/locales/en_GB/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "Rom updated successfully!",
"save-data": "Save data",
"save-deleted": "Save deleted.",
+ "save-target": "Save File/Folder Target",
"saves-empty": "No saves yet",
"saves-empty-hint": "Saves uploaded for this ROM will appear here.",
"saves-section-community": "Community",
@@ -453,6 +454,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 e55499e16..9503b8a05 100644
--- a/frontend/src/locales/en_US/rom.json
+++ b/frontend/src/locales/en_US/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "Rom updated successfully!",
"save-data": "Save data",
"save-deleted": "Save deleted.",
+ "save-target": "Save File/Folder Target",
"saves-empty": "No saves yet",
"saves-empty-hint": "Saves uploaded for this ROM will appear here.",
"saves-section-community": "Community",
@@ -453,6 +454,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 4043ffee3..51e506ec7 100644
--- a/frontend/src/locales/es_ES/rom.json
+++ b/frontend/src/locales/es_ES/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "ROM actualizada correctamente",
"save-data": "Datos guardados",
"save-deleted": "Partida eliminada",
+ "save-target": "Save File/Folder Target",
"saves-empty": "Aún no hay partidas",
"saves-empty-hint": "Sube una partida para empezar.",
"saves-section-community": "Comunidad",
@@ -453,6 +454,7 @@
"tab-notes": "Notas",
"tab-overview": "Resumen",
"tags": "Etiquetas",
+ "title-id": "ID del título",
"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 daf6ae44a..b917fb899 100644
--- a/frontend/src/locales/fr_FR/rom.json
+++ b/frontend/src/locales/fr_FR/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "ROM mise à jour avec succès !",
"save-data": "Sauvegardes",
"save-deleted": "Sauvegarde supprimée.",
+ "save-target": "Save File/Folder Target",
"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",
@@ -453,6 +454,7 @@
"tab-notes": "Notes",
"tab-overview": "Aperçu",
"tags": "Tags",
+ "title-id": "ID du titre",
"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 d79ff1746..b4822905d 100644
--- a/frontend/src/locales/hu_HU/rom.json
+++ b/frontend/src/locales/hu_HU/rom.json
@@ -350,6 +350,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-target": "Save File/Folder Target",
"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",
@@ -453,6 +454,7 @@
"tab-notes": "Jegyzetek",
"tab-overview": "Áttekintés",
"tags": "Címkék",
+ "title-id": "Cím 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 2719bf6e5..3495c738f 100644
--- a/frontend/src/locales/it_IT/rom.json
+++ b/frontend/src/locales/it_IT/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "ROM aggiornata con successo!",
"save-data": "Dati di salvataggio",
"save-deleted": "Salvataggio eliminato.",
+ "save-target": "Save File/Folder Target",
"saves-empty": "Nessun salvataggio ancora",
"saves-empty-hint": "I salvataggi caricati per questa ROM appariranno qui.",
"saves-section-community": "Community",
@@ -453,6 +454,7 @@
"tab-notes": "Note",
"tab-overview": "Panoramica",
"tags": "Tag",
+ "title-id": "ID titolo",
"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 04afd8e72..c53274f9b 100644
--- a/frontend/src/locales/ja_JP/rom.json
+++ b/frontend/src/locales/ja_JP/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "ROMを正常に更新しました!",
"save-data": "セーブデータ",
"save-deleted": "セーブを削除しました。",
+ "save-target": "Save File/Folder Target",
"saves-empty": "セーブはまだありません",
"saves-empty-hint": "このROMにアップロードされたセーブはここに表示されます。",
"saves-section-community": "Community",
@@ -453,6 +454,7 @@
"tab-notes": "ノート",
"tab-overview": "概要",
"tags": "タグ",
+ "title-id": "タイトル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 846f36d4a..39f3201ec 100644
--- a/frontend/src/locales/ko_KR/rom.json
+++ b/frontend/src/locales/ko_KR/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "ROM이 성공적으로 업데이트되었습니다!",
"save-data": "저장 데이터",
"save-deleted": "세이브가 삭제되었습니다.",
+ "save-target": "Save File/Folder Target",
"saves-empty": "아직 세이브가 없습니다",
"saves-empty-hint": "이 ROM에 대해 업로드된 세이브가 여기에 표시됩니다.",
"saves-section-community": "Community",
@@ -453,6 +454,7 @@
"tab-notes": "노트",
"tab-overview": "개요",
"tags": "태그",
+ "title-id": "타이틀 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 c65b786e7..b21baebde 100644
--- a/frontend/src/locales/pl_PL/rom.json
+++ b/frontend/src/locales/pl_PL/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "ROM zaktualizowany pomyślnie!",
"save-data": "Dane zapisu",
"save-deleted": "Zapis usunięty.",
+ "save-target": "Save File/Folder Target",
"saves-empty": "Brak zapisów",
"saves-empty-hint": "Zapisy przesłane dla tego ROM-u pojawią się tutaj.",
"saves-section-community": "Community",
@@ -453,6 +454,7 @@
"tab-notes": "Notatki",
"tab-overview": "Przegląd",
"tags": "Tagi",
+ "title-id": "ID tytułu",
"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 9632c4ea1..49c953662 100644
--- a/frontend/src/locales/pt_BR/rom.json
+++ b/frontend/src/locales/pt_BR/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "ROM atualizada com sucesso!",
"save-data": "Dados salvos",
"save-deleted": "Save excluído.",
+ "save-target": "Save File/Folder Target",
"saves-empty": "Nenhum save ainda",
"saves-empty-hint": "Saves enviados para esta ROM aparecerão aqui.",
"saves-section-community": "Comunidade",
@@ -453,6 +454,7 @@
"tab-notes": "Notas",
"tab-overview": "Visão geral",
"tags": "Tags",
+ "title-id": "ID do título",
"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 c8b5d0933..3bc4dbae2 100644
--- a/frontend/src/locales/ro_RO/rom.json
+++ b/frontend/src/locales/ro_RO/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "ROM actualizat cu succes!",
"save-data": "Date salvate",
"save-deleted": "Salvare ștearsă.",
+ "save-target": "Save File/Folder Target",
"saves-empty": "Nicio salvare încă",
"saves-empty-hint": "Salvările încărcate pentru acest ROM vor apărea aici.",
"saves-section-community": "Community",
@@ -453,6 +454,7 @@
"tab-notes": "Notițe",
"tab-overview": "Prezentare",
"tags": "Etichete",
+ "title-id": "ID titlu",
"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 be7906a70..7af139866 100644
--- a/frontend/src/locales/ru_RU/rom.json
+++ b/frontend/src/locales/ru_RU/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "ROM успешно обновлён!",
"save-data": "Сохранения",
"save-deleted": "Сохранение удалено.",
+ "save-target": "Save File/Folder Target",
"saves-empty": "Сохранений пока нет",
"saves-empty-hint": "Сохранения, загруженные для этого ROM, появятся здесь.",
"saves-section-community": "Community",
@@ -453,6 +454,7 @@
"tab-notes": "Заметки",
"tab-overview": "Обзор",
"tags": "Теги",
+ "title-id": "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 79cd6ac5a..8da94ea9d 100644
--- a/frontend/src/locales/tr_TR/rom.json
+++ b/frontend/src/locales/tr_TR/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "ROM başarıyla güncellendi!",
"save-data": "Kayıt verisi",
"save-deleted": "Kayıt silindi.",
+ "save-target": "Save File/Folder Target",
"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",
@@ -453,6 +454,7 @@
"tab-notes": "Notlar",
"tab-overview": "Genel Bakış",
"tags": "Etiketler",
+ "title-id": "Başlık 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 d3668b111..2b4db14b8 100644
--- a/frontend/src/locales/zh_CN/rom.json
+++ b/frontend/src/locales/zh_CN/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "ROM 更新成功!",
"save-data": "存档数据",
"save-deleted": "存档已删除。",
+ "save-target": "Save File/Folder Target",
"saves-empty": "暂无存档",
"saves-empty-hint": "此 ROM 上传的存档将显示在此处。",
"saves-section-community": "Community",
@@ -453,6 +454,7 @@
"tab-notes": "笔记",
"tab-overview": "概览",
"tags": "标签",
+ "title-id": "标题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 4a5337f18..66838bc61 100644
--- a/frontend/src/locales/zh_TW/rom.json
+++ b/frontend/src/locales/zh_TW/rom.json
@@ -350,6 +350,7 @@
"rom-updated-successfully": "ROM 更新成功!",
"save-data": "存檔資料",
"save-deleted": "存檔已刪除。",
+ "save-target": "Save File/Folder Target",
"saves-empty": "尚未有存檔",
"saves-empty-hint": "為此 ROM 上傳的存檔將會顯示在此處。",
"saves-section-community": "Community",
@@ -453,6 +454,7 @@
"tab-notes": "筆記",
"tab-overview": "概覽",
"tags": "標籤",
+ "title-id": "標題ID",
"tracks-n": "{n} 個音軌 | {n} 個音軌",
"tracks-summary": "{count} 個音軌 · {duration}",
"tracks-uploaded-n": "已上傳 {n} 個音軌。 | 已上傳 {n} 個音軌。",
diff --git a/frontend/src/v2/components/GameDetails/MetadataTab.vue b/frontend/src/v2/components/GameDetails/MetadataTab.vue
index bdfa9358c..4b8007634 100644
--- a/frontend/src/v2/components/GameDetails/MetadataTab.vue
+++ b/frontend/src/v2/components/GameDetails/MetadataTab.vue
@@ -1,6 +1,6 @@