diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index 899ea838a..7dd9b891b 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -197,6 +197,7 @@ def _get_socket_manager() -> socketio.AsyncRedisManager: async def _identify_firmware( platform: Platform, fs_fw: str, + scan_type: ScanType, ) -> int: # Break early if the flag is set if redis_client.get(STOP_SCAN_FLAG): @@ -204,6 +205,19 @@ async def _identify_firmware( firmware = db_firmware_handler.get_firmware_by_filename(platform.id, fs_fw) + # The row is consulted before the filesystem, so an entry that could never + # be skipped costs no stat. + if firmware and not _should_hash_firmware(scan_type, firmware): + file_size = await fs_firmware_handler.get_file_size(firmware.full_path) + if file_size == firmware.file_size_bytes: + # Only written when it actually flips, keeping `updated_at` usable + # as an incremental signal. + if firmware.missing_from_fs: + db_firmware_handler.update_firmware( + firmware.id, {"missing_from_fs": False} + ) + return 0 + scanned_firmware = await scan_firmware( platform=platform, file_name=fs_fw, @@ -303,6 +317,29 @@ def _should_get_rom_files( ) +def _should_hash_firmware( + scan_type: ScanType, + firmware: Firmware | None, +) -> bool: + """Decide if a firmware file's hashes should be recalculated or not + + The firmware counterpart of `_should_get_rom_files`: bytes are only re-read + for a new entry or a scan that asked for hashes. An entry with no stored + hash is treated as new. + + Args: + scan_type (ScanType): Type of scan to be performed. + firmware (Firmware | None): The firmware entry already in the database. + """ + + return bool( + firmware is None + or not firmware.md5_hash + or (scan_type == ScanType.COMPLETE) + or (scan_type == ScanType.HASHES) + ) + + # 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 @@ -665,6 +702,7 @@ async def _identify_platform( new_firmware += await _identify_firmware( platform=platform, fs_fw=fs_fw, + scan_type=scan_type, ) # `new_firmware_count` is scoped to this scan: the client reports what the diff --git a/backend/tests/endpoints/sockets/test_scan.py b/backend/tests/endpoints/sockets/test_scan.py index f52430f61..6780655a8 100644 --- a/backend/tests/endpoints/sockets/test_scan.py +++ b/backend/tests/endpoints/sockets/test_scan.py @@ -1,4 +1,5 @@ from itertools import count +from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock, Mock import pytest @@ -965,6 +966,150 @@ class TestIdentifyPlatformFirmwareReporting: assert payload["new_firmware_count"] == 0 +class TestShouldHashFirmware: + """The firmware counterpart of `_should_get_rom_files`.""" + + def _stored(self, md5: str = "d41d8cd9") -> Firmware: + firmware = Firmware(file_name="bios.bin", platform_id=1) + firmware.md5_hash = md5 + return firmware + + @pytest.mark.parametrize("scan_type", [ScanType.COMPLETE, ScanType.HASHES]) + def test_hashes_when_the_scan_asked_for_hashes(self, scan_type): + assert scan_module._should_hash_firmware(scan_type, self._stored()) is True + + @pytest.mark.parametrize( + "scan_type", + [ + ScanType.QUICK, + ScanType.NEW_PLATFORMS, + ScanType.UPDATE, + ScanType.UNMATCHED, + ], + ) + def test_skips_a_known_entry_on_every_other_scan(self, scan_type): + assert scan_module._should_hash_firmware(scan_type, self._stored()) is False + + def test_hashes_an_entry_missing_from_the_database(self): + assert scan_module._should_hash_firmware(ScanType.QUICK, None) is True + + def test_hashes_an_entry_with_no_stored_hash(self): + assert ( + scan_module._should_hash_firmware(ScanType.QUICK, self._stored(md5="")) + is True + ) + + +class TestIdentifyFirmwareRehashing: + """Firmware follows the same re-read rule as ROM files. + + `_should_get_rom_files` only re-reads a file's bytes for a new entry or a + COMPLETE/HASHES scan. Firmware had no such gate, so a scan of any type + re-hashed every BIOS file on the platform. + """ + + @pytest.fixture + def patched(self, mocker): + mocker.patch.object( + scan_module, "redis_client", Mock(get=Mock(return_value=None)) + ) + mocker.patch.object( + scan_module.Firmware, "verify_file_hashes", return_value=True + ) + + patches = SimpleNamespace( + scan_firmware=mocker.patch.object( + scan_module, + "scan_firmware", + AsyncMock(return_value=Firmware(file_name="bios.bin", platform_id=1)), + ), + get_file_size=mocker.patch.object( + scan_module.fs_firmware_handler, + "get_file_size", + AsyncMock(return_value=1024), + ), + db_firmware=mocker.patch.object(scan_module, "db_firmware_handler"), + ) + patches.db_firmware.get_firmware_by_filename.return_value = self._stored() + return patches + + def _stored(self, *, size: int = 1024, md5: str = "d41d8cd9", missing=False): + firmware = Firmware(file_name="bios.bin", file_path="bios/test", platform_id=1) + firmware.id = 7 + firmware.md5_hash = md5 + firmware.file_size_bytes = size + firmware.missing_from_fs = missing + return firmware + + async def _run(self, scan_type: ScanType = ScanType.QUICK) -> int: + platform = Platform(name="Test", slug="test", fs_slug="test") + platform.id = 1 + return await scan_module._identify_firmware( + platform=platform, fs_fw="bios.bin", scan_type=scan_type + ) + + @pytest.mark.parametrize( + "scan_type", + [ + ScanType.QUICK, + ScanType.NEW_PLATFORMS, + ScanType.UPDATE, + ScanType.UNMATCHED, + ], + ) + async def test_skips_rehashing_an_unchanged_file(self, patched, scan_type): + assert await self._run(scan_type) == 0 + + patched.scan_firmware.assert_not_called() + patched.db_firmware.add_firmware.assert_not_called() + + @pytest.mark.parametrize("scan_type", [ScanType.COMPLETE, ScanType.HASHES]) + async def test_rehashes_when_the_scan_asked_for_hashes(self, patched, scan_type): + await self._run(scan_type) + + patched.scan_firmware.assert_called_once() + + async def test_rehashes_when_the_file_size_changed(self, patched): + patched.get_file_size.return_value = 2048 + + await self._run() + + patched.scan_firmware.assert_called_once() + + async def test_rehashes_an_entry_with_no_stored_hash(self, patched): + patched.db_firmware.get_firmware_by_filename.return_value = self._stored(md5="") + + await self._run() + + patched.scan_firmware.assert_called_once() + # The database row already rules out a skip, so the file is never stat'd. + patched.get_file_size.assert_not_called() + + async def test_hashes_firmware_missing_from_the_database(self, patched): + patched.db_firmware.get_firmware_by_filename.return_value = None + + assert await self._run() == 1 + + patched.scan_firmware.assert_called_once() + + async def test_clears_the_missing_flag_without_rehashing(self, patched): + patched.db_firmware.get_firmware_by_filename.return_value = self._stored( + missing=True + ) + + await self._run() + + patched.scan_firmware.assert_not_called() + patched.db_firmware.update_firmware.assert_called_once_with( + 7, {"missing_from_fs": False} + ) + + async def test_leaves_an_unchanged_row_untouched(self, patched): + await self._run() + + patched.db_firmware.update_firmware.assert_not_called() + + class TestGetPico8CoverUrl: """Tests for the PICO-8 cover art URL helper on FSRomsHandler."""