fix(scan): emit a client update for ROMs that are no longer missing

A platform scan already clears `missing_from_fs` for an entry whose file
came back under the same name, but the ROM is skipped by `should_scan_rom`
so nothing emits `scan:scanning_rom` for it. An open gallery keeps showing
the stale "missing" badge until a refetch, which reads as the platform scan
ignoring missing games (a single-game scan does emit, and looks fixed).

Snapshot the flagged ids before the pre-loop sync clears them, then emit for
the restored entries after `bulk_mark_present`.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-07-23 09:40:17 -04:00
parent 5edf6bc4f7
commit 71c04f186b
4 changed files with 183 additions and 0 deletions

View File

@@ -666,6 +666,10 @@ async def _identify_platform(
else:
log.info(f"{hl(str(len(fs_roms)))} roms found in the file system")
# Snapshot the missing entries before the sync below clears the flag for any
# whose file is back, so the skip path can still tell the client about them.
previously_missing_rom_ids = db_rom_handler.get_missing_rom_ids(platform.id)
# Flag entries whose file is gone before identifying files, so a renamed or
# moved ROM (a new file with no fs_name match) can be reassociated by hash
# with its now-missing entry instead of spawning a duplicate. The end-of-scan
@@ -699,6 +703,7 @@ async def _identify_platform(
# Separate skipped ROMs from those that need scanning
skipped_rom_ids: list[int] = []
restored_roms: list[Rom] = []
roms_to_scan: list[tuple[FSRom, Rom | None]] = []
for fs_rom in fs_roms_batch:
@@ -712,6 +717,8 @@ async def _identify_platform(
roms_to_scan.append((fs_rom, rom))
elif rom:
skipped_rom_ids.append(rom.id)
if rom.id in previously_missing_rom_ids:
restored_roms.append(rom)
# Bulk update all skipped ROMs in one query instead of per-ROM updates
if skipped_rom_ids:
@@ -721,6 +728,32 @@ async def _identify_platform(
scanned_roms=len(skipped_rom_ids),
)
# Skipped ROMs emit nothing, so a ROM whose file came back would keep its
# stale "missing" badge in an open gallery until a refetch. Reload with
# details since the scan-loop lookup only eager-loads the platform.
for restored_rom in restored_roms:
log.info(
f"{hl(restored_rom.fs_name)} is back in the filesystem, "
f"no longer {hl('missing', color=LIGHTYELLOW)}"
)
hydrated_rom = db_rom_handler.get_rom(restored_rom.id)
if hydrated_rom is None:
continue
await socket_manager.emit(
"scan:scanning_rom",
SimpleRomSchema.from_orm_with_factory(hydrated_rom).model_dump(
exclude={
"created_at",
"updated_at",
"rom_user",
"last_modified",
"files",
"sibling_roms",
}
),
)
# Process only ROMs that actually need scanning
scan_tasks = [
scan_rom_with_semaphore(fs_rom=fs_rom, rom=rom)

View File

@@ -1544,6 +1544,24 @@ class DBRomsHandler(DBBaseHandler):
.execution_options(synchronize_session="evaluate")
)
@begin_session
def get_missing_rom_ids(
self,
platform_id: int,
session: Session = None, # type: ignore
) -> set[int]:
"""Return the ids of a platform's ROMs currently flagged missing."""
return set(
session.scalars(
select(Rom.id).where(
and_(
Rom.platform_id == platform_id,
Rom.missing_from_fs.is_(True),
)
)
).all()
)
@begin_session
def bulk_mark_present(
self,

View File

@@ -635,6 +635,113 @@ class TestIdentifyPlatformMarksMissingBeforeScan:
assert calls.index("mark_missing") < calls.index("identify")
class TestIdentifyPlatformEmitsRestoredRoms:
"""A quick platform scan tells the client about ROMs that came back.
Existing entries are skipped by `should_scan_rom`, so nothing else in the
loop emits for them and an open gallery would keep showing a stale
"missing" badge until a refetch.
"""
@pytest.fixture
def patched(self, mocker):
mocker.patch.object(
scan_module, "redis_client", Mock(get=Mock(return_value=None))
)
platform = Platform(name="Test", slug="test", fs_slug="test")
platform.id = 1
platform.missing_from_fs = False
db_platform = mocker.patch.object(scan_module, "db_platform_handler")
db_platform.get_platform_by_fs_slug.return_value = platform
db_platform.add_platform.return_value = platform
mocker.patch.object(
scan_module, "scan_platform", AsyncMock(return_value=platform)
)
mocker.patch.object(
scan_module.PlatformSchema,
"model_validate",
return_value=Mock(model_dump=Mock(return_value={})),
)
mocker.patch.object(
scan_module.fs_firmware_handler,
"get_firmware",
AsyncMock(return_value=[]),
)
fs_rom: FSRom = {
"fs_name": "Game.zip",
"flat": True,
"nested": False,
"files": [],
"crc_hash": "",
"md5_hash": "",
"sha1_hash": "",
"ra_hash": "",
}
mocker.patch.object(
scan_module.fs_rom_handler, "get_roms", AsyncMock(return_value=[fs_rom])
)
rom = Rom(fs_name="Game.zip", platform_id=platform.id)
rom.id = 42
db_rom = mocker.patch.object(scan_module, "db_rom_handler")
db_rom.get_roms_by_fs_name.return_value = {"Game.zip": rom}
db_rom.mark_missing_roms.return_value = []
db_rom.get_rom.return_value = rom
db_firmware = mocker.patch.object(scan_module, "db_firmware_handler")
db_firmware.mark_missing_firmware.return_value = []
mocker.patch.object(
scan_module.SimpleRomSchema,
"from_orm_with_factory",
return_value=Mock(model_dump=Mock(return_value={"id": rom.id})),
)
return db_rom
async def _run(self, socket_manager):
await scan_module._identify_platform(
platform_slug="test",
scan_type=ScanType.QUICK,
fs_platforms=["test"],
roms_ids=[],
metadata_sources=[],
launchbox_remote_enabled=False,
playmatch_enabled=False,
socket_manager=socket_manager,
scan_stats=AsyncMock(),
)
async def test_emits_for_rom_that_is_no_longer_missing(self, patched):
patched.get_missing_rom_ids.return_value = {42}
socket_manager = AsyncMock()
await self._run(socket_manager)
patched.bulk_mark_present.assert_called_once_with(1, [42])
patched.get_rom.assert_called_once_with(42)
assert any(
call.args[0] == "scan:scanning_rom"
for call in socket_manager.emit.call_args_list
)
async def test_no_emit_for_rom_that_was_already_present(self, patched):
patched.get_missing_rom_ids.return_value = set()
socket_manager = AsyncMock()
await self._run(socket_manager)
patched.get_rom.assert_not_called()
assert not any(
call.args[0] == "scan:scanning_rom"
for call in socket_manager.emit.call_args_list
)
class TestGetPico8CoverUrl:
"""Tests for the PICO-8 cover art URL helper on FSRomsHandler."""

View File

@@ -459,6 +459,31 @@ def test_custom_name_sort_key_overrides_name_sort_order(platform: Platform):
assert [r.name for r in roms] == ["Display Z", "Display M", "Display A"]
def test_get_missing_rom_ids(platform: Platform):
"""get_missing_rom_ids returns only the platform's flagged ROMs."""
roms = []
for i in range(4):
rom = db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
name=f"missing_rom_{i}",
slug=f"missing-rom-{i}",
fs_name=f"missing_rom_{i}.zip",
fs_name_no_tags=f"missing_rom_{i}",
fs_name_no_ext=f"missing_rom_{i}",
fs_extension="zip",
fs_path=f"{platform.slug}/roms",
missing_from_fs=i < 2,
)
)
roms.append(rom)
assert db_rom_handler.get_missing_rom_ids(platform.id) == {
roms[0].id,
roms[1].id,
}
def test_bulk_mark_present(platform: Platform):
"""bulk_mark_present sets missing_from_fs=False for the given ROM IDs."""
roms = []