refactor: drop file-less roms in the query, not after loading

Every surface that enumerates roms to point at their files was fetching the
whole platform and discarding the file-less ones in Python. Give filter_roms a
`physical` filter to sit alongside `missing`, and pair the two in
HAS_FILE_ON_DISK_FILTERS, the query-side twin of Rom.has_file_on_disk.

- The device feeds lose _servable_roms(); the three get_roms_scalar calls spread
  the filters instead, so the dropped roms no longer get their RomFile rows
  selectin-loaded just to be thrown away.
- Both exporters filter in SQL. Pegasus was collecting and copying assets for
  roms it went on to skip, and the ES-DE guard's `not rom` arm was dead.
- The bulk zip download applies them to its platform/collection selector. A
  physical game contributes no files, so it only inflated the rom count in the
  log line, the generated "N ROMs (crc).zip" filename, and the bulk cache
  namespace. Roms named by explicit id still bypass this.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-08-26 21:42:01 -04:00
parent c2547ec68c
commit a5f37d32e3
9 changed files with 136 additions and 41 deletions

View File

@@ -50,7 +50,12 @@ from handler.metadata.base_handler import (
SWITCH_TITLEDB_REGEX,
)
from handler.metadata.base_handler import UniversalPlatformSlug as UPS
from models.rom import Rom, RomFile, RomFileCategory
from models.rom import (
HAS_FILE_ON_DISK_FILTERS,
Rom,
RomFile,
RomFileCategory,
)
from utils.archives import is_compressed_file
from utils.router import APIRouter
@@ -93,24 +98,19 @@ def _hidden_ids(request: Request) -> tuple[list[int], list[int]]:
return list(perms.hidden_platform_ids), list(perms.hidden_rom_ids)
def _servable_roms(roms: Sequence[Rom]) -> list[Rom]:
"""Every feed entry carries a download URL, so a rom with no file has none."""
return [rom for rom in roms if rom.has_file_on_disk]
def _platform_roms(
request: Request, platform_id: int, *, include_files: bool = False
) -> list[Rom]:
"""Roms of a platform, excluding any hidden from the caller (cascade included)."""
) -> Sequence[Rom]:
"""Roms of a platform a feed can serve: nothing hidden from the caller, and
nothing file-less (every feed entry carries a download URL)."""
hidden_platforms, hidden_roms = _hidden_ids(request)
if platform_id in hidden_platforms:
return []
return _servable_roms(
db_rom_handler.get_roms_scalar(
platform_ids=[platform_id],
include_files=include_files,
hidden_rom_ids=hidden_roms,
)
return db_rom_handler.get_roms_scalar(
platform_ids=[platform_id],
include_files=include_files,
hidden_rom_ids=hidden_roms,
**HAS_FILE_ON_DISK_FILTERS,
)
@@ -139,12 +139,11 @@ def platforms_webrcade_feed(request: Request) -> WebrcadeFeedSchema:
continue
category_items = []
roms = _servable_roms(
db_rom_handler.get_roms_scalar(
platform_ids=[p.id],
hidden_platform_ids=hidden_platforms,
hidden_rom_ids=hidden_roms,
)
roms = db_rom_handler.get_roms_scalar(
platform_ids=[p.id],
hidden_platform_ids=hidden_platforms,
hidden_rom_ids=hidden_roms,
**HAS_FILE_ON_DISK_FILTERS,
)
for rom in roms:
download_url = generate_rom_download_url(request, rom)
@@ -257,13 +256,12 @@ async def tinfoil_index_feed(
return titledb
hidden_platforms, hidden_roms = _hidden_ids(request)
roms = _servable_roms(
db_rom_handler.get_roms_scalar(
platform_ids=[switch.id],
include_files=True,
hidden_platform_ids=hidden_platforms,
hidden_rom_ids=hidden_roms,
)
roms = db_rom_handler.get_roms_scalar(
platform_ids=[switch.id],
include_files=True,
hidden_platform_ids=hidden_platforms,
hidden_rom_ids=hidden_roms,
**HAS_FILE_ON_DISK_FILTERS,
)
return TinfoilFeedSchema(

View File

@@ -90,6 +90,7 @@ from logger.formatter import highlight as hl
from logger.logger import log
from models.permission import PermAction, PermEntity
from models.rom import (
HAS_FILE_ON_DISK_FILTERS,
Rom,
RomUserStatus,
apply_file_stats,
@@ -1056,6 +1057,7 @@ async def download_roms(
smart_collection_id=smart_collection_id,
hidden_platform_ids=list(perms.hidden_platform_ids),
hidden_rom_ids=list(perms.hidden_rom_ids),
**HAS_FILE_ON_DISK_FILTERS,
)
rom_id_list = list(dict.fromkeys(rom.id for rom in rom_rows))
elif rom_ids:

View File

@@ -1186,6 +1186,7 @@ class DBRomsHandler(DBBaseHandler):
has_saves: bool | None = None,
has_states: bool | None = None,
missing: bool | None = None,
physical: bool | None = None,
verified: bool | None = None,
has_soundtrack: bool | None = None,
group_by_meta_id: bool = False,
@@ -1327,6 +1328,9 @@ class DBRomsHandler(DBBaseHandler):
if missing is not None:
query = self._filter_by_missing_from_fs(query, value=missing)
if physical is not None:
query = query.filter(Rom.is_physical.is_(physical))
if verified is not None:
query = self._filter_by_verified(query, value=verified)
@@ -1614,6 +1618,7 @@ class DBRomsHandler(DBBaseHandler):
has_states=kwargs.get("has_states", None),
has_soundtrack=kwargs.get("has_soundtrack", None),
missing=kwargs.get("missing", None),
physical=kwargs.get("physical", None),
verified=kwargs.get("verified", None),
genres=kwargs.get("genres", None),
franchises=kwargs.get("franchises", None),

View File

@@ -912,6 +912,11 @@ def apply_file_stats(rom: Rom, files: Sequence[RomFile]) -> None:
)
# Query-side twin of `Rom.has_file_on_disk`, for callers that enumerate roms and
# want the file-less ones dropped by the database rather than after loading.
HAS_FILE_ON_DISK_FILTERS = {"physical": False, "missing": False}
# Maps a metadata-source slug (matching the MetadataSource enum) to the Rom
# column holding that source's match id. A populated column means the ROM
# matched that source. Shared by the stats coverage breakdown and the gallery

View File

@@ -43,6 +43,45 @@ def test_webrcade_feed(
assert len(body["categories"][0]["items"]) == 1
def test_webrcade_feed_skips_roms_without_a_file(
client: TestClient, access_token: str, platform: Platform, rom: Rom
):
platform = db_platform_handler.update_platform(
platform.id,
{"name": "Nintendo Entertainment System", "slug": UPS.NES, "fs_slug": UPS.NES},
)
db_rom_handler.update_rom(rom.id, {"platform_id": platform.id})
db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
name="Physical Game",
fs_name="Physical Game",
fs_path=f"{platform.slug}/roms/.physical",
fs_size_bytes=0,
is_physical=True,
)
)
db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
name="Gone Game",
fs_name="Gone Game.zip",
fs_path=f"{platform.slug}/roms",
fs_size_bytes=123,
missing_from_fs=True,
)
)
response = client.get(
"/api/feeds/webrcade",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
items = response.json()["categories"][0]["items"]
assert [item["title"] for item in items] == [rom.name]
def test_tinfoil_feed(client: TestClient, platform: Platform, rom: Rom):
platform = db_platform_handler.update_platform(
platform.id,

View File

@@ -1,5 +1,6 @@
import json
from unittest.mock import AsyncMock, patch
from urllib.parse import unquote
from fastapi import status
from fastapi.testclient import TestClient
@@ -226,6 +227,35 @@ def test_download_roms_by_platform(
assert rom_file.file_name in response.text
def test_download_roms_by_platform_skips_roms_without_a_file(
client: TestClient,
access_token: str,
platform: Platform,
rom_file: RomFile,
):
"""A physical game has no files to zip, so it must not swell the archive's
ROM count (and therefore its generated name)."""
db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
name="Physical Game",
fs_name="Physical Game",
fs_path=f"{platform.slug}/roms/.physical",
fs_size_bytes=0,
is_physical=True,
)
)
response = client.get(
f"/api/roms/download?platform_id={platform.id}",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert "1 ROMs" in unquote(response.headers["Content-Disposition"])
assert rom_file.file_name in response.text
def test_download_roms_by_collection(
client: TestClient,
access_token: str,

View File

@@ -77,6 +77,20 @@ def test_get_roms_scalar_missing_excludes_physical(platform: Platform):
assert physical.id not in {r.id for r in missing}
def test_get_roms_scalar_physical_filter(rom: Rom, platform: Platform):
physical = _add_physical_rom(platform)
only_physical = db_rom_handler.get_roms_scalar(
platform_ids=[platform.id], physical=True
)
assert {r.id for r in only_physical} == {physical.id}
no_physical = db_rom_handler.get_roms_scalar(
platform_ids=[platform.id], physical=False
)
assert {r.id for r in no_physical} == {rom.id}
def test_roms(rom: Rom, platform: Platform):
db_rom_handler.add_rom(
Rom(

View File

@@ -15,7 +15,7 @@ from config.config_manager import config_manager as cm
from handler.database import db_platform_handler, db_rom_handler
from handler.filesystem import fs_platform_handler, fs_resource_handler
from logger.logger import log
from models.rom import Rom
from models.rom import HAS_FILE_ON_DISK_FILTERS, Rom
from utils.filesystem import link_or_copy_file
# Map gamelist asset keys to subdirectory names inside assets/
@@ -301,14 +301,16 @@ class GamelistExporter:
if not platform:
raise ValueError(f"Platform with ID {platform_id} not found")
roms = db_rom_handler.get_roms_scalar(platform_ids=[platform_id])
roms = db_rom_handler.get_roms_scalar(
platform_ids=[platform_id], **HAS_FILE_ON_DISK_FILTERS
)
root = Element("gameList")
media_image, media_thumbnail = get_media_options_for_export()
count = 0
for rom in roms:
if not rom or not rom.has_file_on_disk or rom.fs_name == "gamelist.xml":
if rom.fs_name == "gamelist.xml":
continue
assets = self._collect_assets(rom)

View File

@@ -8,7 +8,7 @@ from handler.filesystem import fs_platform_handler, fs_resource_handler
from handler.metadata.base_handler import UniversalPlatformSlug as UPS
from logger.logger import log
from models.platform import Platform
from models.rom import Rom
from models.rom import HAS_FILE_ON_DISK_FILTERS, Rom
from utils.filesystem import link_or_copy_file
# Map RomM platform slugs to canonical Pegasus (collection name, shortname) pairs.
@@ -326,7 +326,9 @@ class PegasusExporter:
if not platform:
raise ValueError(f"Platform with ID {platform_id} not found")
roms = db_rom_handler.get_roms_scalar(platform_ids=[platform_id])
roms = db_rom_handler.get_roms_scalar(
platform_ids=[platform_id], **HAS_FILE_ON_DISK_FILTERS
)
lines: list[str] = []
@@ -339,11 +341,10 @@ class PegasusExporter:
# Game entries
game_count = 0
for rom in roms:
if rom.has_file_on_disk:
if game_count > 0:
lines.append("")
lines.append(self._create_game_entry(rom, request=request))
game_count += 1
if game_count > 0:
lines.append("")
lines.append(self._create_game_entry(rom, request=request))
game_count += 1
log.info(f"Exported {game_count} ROMs for platform {platform.name}")
return "\n".join(lines) + "\n"
@@ -374,7 +375,9 @@ class PegasusExporter:
)
platform_dir = fs_platform_handler.base_path / platform_fs_structure
roms = db_rom_handler.get_roms_scalar(platform_ids=[platform_id])
roms = db_rom_handler.get_roms_scalar(
platform_ids=[platform_id], **HAS_FILE_ON_DISK_FILTERS
)
lines: list[str] = []
@@ -386,9 +389,6 @@ class PegasusExporter:
game_count = 0
for rom in roms:
if not rom.has_file_on_disk:
continue
exported_assets: dict[str, str] = {}
if self.local_export: