diff --git a/backend/tasks/scheduled/cleanup_orphaned_resources.py b/backend/tasks/scheduled/cleanup_orphaned_resources.py index 170e90f89..2f30d43c6 100644 --- a/backend/tasks/scheduled/cleanup_orphaned_resources.py +++ b/backend/tasks/scheduled/cleanup_orphaned_resources.py @@ -1,3 +1,4 @@ +import asyncio import os import shutil from dataclasses import dataclass @@ -16,6 +17,34 @@ from tasks.tasks import PeriodicTask, TaskType, update_job_meta from utils.context import initialize_context +def _numeric_subdirs(path: str) -> set[int]: + """Numeric-named subdirectories of `path`, as ints.""" + try: + with os.scandir(path) as entries: + return { + int(entry.name) + for entry in entries + if entry.name.isdigit() and entry.is_dir() + } + except OSError as exc: + log.error(f"Unable to list resource directory {path}: {str(exc)}") + return set() + + +def _scan_resource_dirs(roms_resources_path: str) -> dict[int, set[int]]: + """Map each platform id on disk to the ROM ids that have a resource directory. + + `os.scandir` reports the entry type from the directory read itself, so this + walks tens of thousands of entries without a stat call per entry. + """ + return { + platform_id: _numeric_subdirs( + os.path.join(roms_resources_path, str(platform_id)) + ) + for platform_id in _numeric_subdirs(roms_resources_path) + } + + @dataclass class CleanupStats: """Statistics for cleanup operations.""" @@ -107,11 +136,10 @@ class CleanupOrphanedResourcesTask(PeriodicTask): ) # Count total platforms and ROMs for progress tracking - platform_dirs: set[int] = { - int(entry.name) - async for entry in roms_resources_dir.iterdir() - if entry.name.isdigit() and await entry.is_dir() - } + rom_dirs_by_platform: dict[int, set[int]] = await asyncio.to_thread( + _scan_resource_dirs, roms_resources_path + ) + platform_dirs = set(rom_dirs_by_platform) # An empty library alongside artwork on disk is far more likely to be a # database that is unavailable or mid-migration than one that was really @@ -125,16 +153,6 @@ class CleanupOrphanedResourcesTask(PeriodicTask): ) return cleanup_stats.to_dict() - rom_dirs_by_platform: dict[int, set[int]] = {} - for platform_dir in platform_dirs: - platform_path = os.path.join(roms_resources_path, str(platform_dir)) - platform_dir_path = AnyioPath(platform_path) - rom_dirs_by_platform[platform_dir] = { - int(entry.name) - async for entry in platform_dir_path.iterdir() - if entry.name.isdigit() and await entry.is_dir() - } - cleanup_stats.update( platforms_in_fs=len(platform_dirs), roms_in_fs=sum(len(rom_dirs) for rom_dirs in rom_dirs_by_platform.values()), diff --git a/backend/tests/tasks/test_cleanup_orphaned_resources.py b/backend/tests/tasks/test_cleanup_orphaned_resources.py index 12af2c1af..9f630e796 100644 --- a/backend/tests/tasks/test_cleanup_orphaned_resources.py +++ b/backend/tests/tasks/test_cleanup_orphaned_resources.py @@ -1,3 +1,4 @@ +import os from types import SimpleNamespace from unittest.mock import patch @@ -126,3 +127,55 @@ class TestCleanupOrphanedResourcesRun: assert stats["platforms_in_fs"] == 0 assert stats["removed_fs_platforms"] == 0 + + +class TestScanResourceDirs: + """The resource tree walk backing the cleanup task.""" + + @staticmethod + def _make_tree(root, layout: dict[int, list[int]]) -> None: + for platform_id, rom_ids in layout.items(): + for rom_id in rom_ids: + (root / str(platform_id) / str(rom_id)).mkdir(parents=True) + + def test_maps_platforms_to_rom_dirs(self, tmp_path): + self._make_tree(tmp_path, {1: [10, 11], 2: [20]}) + + assert mod._scan_resource_dirs(str(tmp_path)) == {1: {10, 11}, 2: {20}} + + def test_ignores_non_numeric_names(self, tmp_path): + self._make_tree(tmp_path, {1: [10]}) + (tmp_path / "not-a-platform").mkdir() + (tmp_path / "1" / "not-a-rom").mkdir() + + assert mod._scan_resource_dirs(str(tmp_path)) == {1: {10}} + + def test_ignores_files(self, tmp_path): + self._make_tree(tmp_path, {1: [10]}) + (tmp_path / "2").write_text("stray file named like a platform") + (tmp_path / "1" / "20").write_text("stray file named like a rom") + + assert mod._scan_resource_dirs(str(tmp_path)) == {1: {10}} + + def test_empty_tree(self, tmp_path): + assert mod._scan_resource_dirs(str(tmp_path)) == {} + + def test_platform_with_no_rom_dirs(self, tmp_path): + (tmp_path / "1").mkdir() + + assert mod._scan_resource_dirs(str(tmp_path)) == {1: set()} + + def test_unreadable_directory_yields_empty_set(self, tmp_path): + # A directory that disappears or denies access must not abort the walk, + # otherwise one bad platform would strand every other platform's orphans. + self._make_tree(tmp_path, {1: [10]}) + + real_scandir = os.scandir + + def flaky_scandir(path): + if path.endswith(os.sep + "1"): + raise PermissionError(13, "Permission denied") + return real_scandir(path) + + with patch.object(mod.os, "scandir", side_effect=flaky_scandir): + assert mod._scan_resource_dirs(str(tmp_path)) == {1: set()}