refactor(scan): let the terminal event own the progress flush

`scan_platforms` ends in four places, and three of them had to remember to
flush the counters a coalesced increment held back. The fourth, the early
return on a folder structure it cannot read, did not, and was correct only
because it sits above the first report. `finish` pairs the flush with the
emit so every exit gets both, including that one.

The failure path's guard around the flush goes with it. It was protecting
against an emit that fails, one line above an emit that would fail the same
way and is not protected, and `update_job_meta` already swallows its own
errors, so it bought nothing.

Also: `refetchCurrentRom` wrote `currentRom` twice, once directly and again
through `syncCachedRom`, which owns that write and applies the same identity
guard. `useRomScanRefresh` kept an `alive` check that `useSocketEvent`'s
unsubscribe already covers; its test was passing on the check rather than the
unsubscribe, so the socket mock now actually unsubscribes. DeleteManualDialog
was the tenth surface still spelling out the refetch by hand, and seven
components kept a rom store binding nothing reads any more.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-09-04 15:42:20 -04:00
parent 534033773e
commit ccc950f72e
14 changed files with 71 additions and 141 deletions

View File

@@ -143,9 +143,9 @@ def _scan_in_flight_message(running: Job | None, queued: list[Job]) -> str:
return f"{_scan_job_label(running)} is already running"
# A scan reports progress after every rom, and each report is a synchronous
# redis write plus a publish. Coalescing them keeps a large library from
# spending longer announcing progress than making it.
# Each report is a synchronous redis write plus a publish, and a scan makes one
# per rom. Coalescing keeps a large library from spending longer announcing
# progress than making it.
SCAN_STATS_PUBLISH_INTERVAL = 0.25
@@ -1096,6 +1096,11 @@ async def scan_platforms(
socket_manager = _get_socket_manager()
scan_stats = ScanStats()
async def finish(event: str, payload: Any) -> None:
"""End the scan, reporting whatever a coalesced increment held back."""
await scan_stats.flush(socket_manager)
await socket_manager.emit(event, payload)
# A ROM-id-scoped scan resolves its work from the database, so it neither
# needs nor can afford the filesystem walk a library scan starts with.
scoped_roms_by_platform: dict[int, list[Rom]] = {}
@@ -1115,7 +1120,7 @@ async def scan_platforms(
fs_platforms = await fs_platform_handler.get_platforms()
except FolderStructureNotMatchException as e:
log.error(e)
await socket_manager.emit("scan:done_ko", e.message)
await finish("scan:done_ko", e.message)
return scan_stats
# Clear the gamelist cache to ensure we're using fresh gamelist.xml data
@@ -1221,8 +1226,7 @@ async def scan_platforms(
async def stop_scan():
log.info(f"{emoji.EMOJI_STOP_SIGN} Scan stopped manually")
await scan_stats.flush(socket_manager)
await socket_manager.emit("scan:done", scan_stats.to_dict())
await finish("scan:done", scan_stats.to_dict())
redis_client.delete(STOP_SCAN_FLAG)
try:
@@ -1338,20 +1342,13 @@ async def scan_platforms(
)
log.info("Pegasus metadata auto-export completed.")
await scan_stats.flush(socket_manager)
await socket_manager.emit("scan:done", scan_stats.to_dict())
await finish("scan:done", scan_stats.to_dict())
except ScanStoppedException:
await stop_scan()
except Exception as e:
log.error(f"Error in scan_platform: {e}")
# What the scan did get through still counts, so report it before saying
# it failed; a failure to do so must not replace the error being raised.
try:
await scan_stats.flush(socket_manager)
except Exception:
log.error("Could not report the stats of a failed scan", exc_info=True)
# Catch all exceptions and emit error to the client
await socket_manager.emit("scan:done_ko", str(e))
await finish("scan:done_ko", str(e))
# Re-raise the exception to be caught by the error handler
raise e

View File

@@ -47,67 +47,76 @@ from models.rom import Rom, RomFile, RomFileCategory, RomIdentity
from utils.platform_slugs import UniversalPlatformSlug as UPS
@pytest.fixture
def hold_everything_back(mocker):
"""An interval no test can outrun, so coalescing is what decides."""
mocker.patch.object(scan_module, "SCAN_STATS_PUBLISH_INTERVAL", 3600)
class TestScanStatsPublishing:
"""Counters are exact on every increment; only the reporting is coalesced."""
@pytest.fixture
def emit(self, mocker):
def socket_manager(self, mocker):
mocker.patch.object(scan_module, "update_job_meta")
return AsyncMock()
async def test_reports_once_for_a_burst_of_increments(self, mocker, emit):
mocker.patch.object(scan_module, "SCAN_STATS_PUBLISH_INTERVAL", 3600)
async def test_reports_once_for_a_burst_of_increments(
self, hold_everything_back, socket_manager
):
stats = ScanStats()
for _ in range(50):
await stats.increment(socket_manager=emit, scanned_roms=1)
await stats.increment(socket_manager=socket_manager, scanned_roms=1)
# The first increment reports, the rest ride along with it.
emit.emit.assert_awaited_once()
socket_manager.emit.assert_awaited_once()
assert stats.scanned_roms == 50
async def test_flush_reports_what_a_burst_held_back(self, mocker, emit):
mocker.patch.object(scan_module, "SCAN_STATS_PUBLISH_INTERVAL", 3600)
async def test_flush_reports_what_a_burst_held_back(
self, hold_everything_back, socket_manager
):
stats = ScanStats()
for _ in range(5):
await stats.increment(socket_manager=emit, scanned_roms=1)
emit.emit.reset_mock()
await stats.increment(socket_manager=socket_manager, scanned_roms=1)
socket_manager.emit.reset_mock()
await stats.flush(emit)
await stats.flush(socket_manager)
assert emit.emit.await_args.args[1]["scanned_roms"] == 5
assert socket_manager.emit.await_args.args[1]["scanned_roms"] == 5
async def test_flush_is_quiet_with_nothing_held_back(self, mocker, emit):
async def test_flush_is_quiet_with_nothing_held_back(self, mocker, socket_manager):
mocker.patch.object(scan_module, "SCAN_STATS_PUBLISH_INTERVAL", 0)
stats = ScanStats()
await stats.increment(socket_manager=emit, scanned_roms=1)
emit.emit.reset_mock()
await stats.increment(socket_manager=socket_manager, scanned_roms=1)
socket_manager.emit.reset_mock()
await stats.flush(emit)
await stats.flush(socket_manager)
emit.emit.assert_not_awaited()
socket_manager.emit.assert_not_awaited()
async def test_a_phase_boundary_reports_immediately(self, mocker, emit):
mocker.patch.object(scan_module, "SCAN_STATS_PUBLISH_INTERVAL", 3600)
async def test_a_phase_boundary_reports_immediately(
self, hold_everything_back, socket_manager
):
stats = ScanStats()
await stats.increment(socket_manager=emit, scanned_roms=1)
emit.emit.reset_mock()
await stats.increment(socket_manager=socket_manager, scanned_roms=1)
socket_manager.emit.reset_mock()
await stats.update(socket_manager=emit, total_roms=12)
await stats.update(socket_manager=socket_manager, total_roms=12)
assert emit.emit.await_args.args[1]["total_roms"] == 12
assert socket_manager.emit.await_args.args[1]["total_roms"] == 12
async def test_the_first_report_survives_a_clock_reading_near_zero(
self, mocker, emit
self, mocker, socket_manager
):
# A monotonic clock counting from boot can read below the interval, and
# the first report must not be coalesced against a scan that never ran.
mocker.patch.object(scan_module.time, "monotonic", return_value=0.01)
stats = ScanStats()
await stats.increment(socket_manager=emit, scanned_roms=1)
await stats.increment(socket_manager=socket_manager, scanned_roms=1)
emit.emit.assert_awaited_once()
socket_manager.emit.assert_awaited_once()
def test_scan_stats():
@@ -217,9 +226,8 @@ class TestScanFailureReporting:
"""A failed scan still reports the progress it made before saying it failed."""
async def test_a_failure_publishes_what_an_increment_held_back(
self, patched, mocker
self, patched, hold_everything_back, mocker
):
mocker.patch.object(scan_module, "SCAN_STATS_PUBLISH_INTERVAL", 3600)
update_job_meta = mocker.patch.object(scan_module, "update_job_meta")
async def scan_then_fail(**kwargs):
@@ -238,25 +246,6 @@ class TestScanFailureReporting:
assert update_job_meta.call_args.args[0]["scan_stats"]["scanned_roms"] == 7
assert patched.emit.await_args.args[0] == "scan:done_ko"
async def test_a_failure_to_report_does_not_replace_the_error(
self, patched, mocker
):
mocker.patch.object(
scan_module.ScanStats,
"flush",
AsyncMock(side_effect=OSError("redis is gone")),
)
async def scan_then_fail(**_kwargs):
raise RuntimeError("boom")
mocker.patch.object(
scan_module, "_identify_platform", side_effect=scan_then_fail
)
with pytest.raises(RuntimeError, match="boom"):
await scan_platforms(platform_ids=[], metadata_sources=[])
class TestScanTotals:
"""The scan tracker totals must reflect the platforms/roms actually scanned."""
@@ -309,11 +298,8 @@ class TestScreenScraperScanReporting:
when the scan actually uses ScreenScraper."""
@pytest.fixture
def patched(self, mocker):
socket_manager = AsyncMock()
mocker.patch.object(
scan_module, "_get_socket_manager", return_value=socket_manager
)
def patched(self, patched, mocker):
"""The shared harness, narrowed to a single platform with no roms."""
mocker.patch.object(
scan_module.fs_platform_handler,
"get_platforms",
@@ -322,28 +308,10 @@ class TestScreenScraperScanReporting:
mocker.patch.object(
scan_module.fs_rom_handler, "count_roms", AsyncMock(return_value=0)
)
mocker.patch.object(scan_module.meta_gamelist_handler, "clear_cache")
mocker.patch.object(
scan_module.db_platform_handler, "mark_missing_platforms", return_value=[]
)
mocker.patch.object(
scan_module.db_platform_handler, "get_platforms", return_value=[]
)
mocker.patch.object(
scan_module.db_rom_handler, "invalidate_filter_values_cache"
)
config = MagicMock()
config.GAMELIST_AUTO_EXPORT_ON_SCAN = False
config.PEGASUS_AUTO_EXPORT_ON_SCAN = False
mocker.patch.object(scan_module.cm, "get_config", return_value=config)
async def fake_identify(**kwargs):
return kwargs["scan_stats"]
mocker.patch.object(
scan_module, "_identify_platform", side_effect=fake_identify
)
return socket_manager
return patched
async def test_begins_a_screenscraper_scan(self, patched, mocker):
begin = mocker.patch.object(

View File

@@ -7,7 +7,7 @@ import type { Emitter } from "mitt";
import { inject, onBeforeUnmount, ref } from "vue";
import { useI18n } from "vue-i18n";
import romApi from "@/services/api/rom";
import storeRoms, { type DetailedRom } from "@/stores/roms";
import { type DetailedRom } from "@/stores/roms";
import type { Events } from "@/types/emitter";
import { useRomSync } from "@/v2/composables/useRomSync";
import { useSnackbar } from "@/v2/composables/useSnackbar";
@@ -18,8 +18,7 @@ defineOptions({ inheritAttrs: false });
const { t } = useI18n();
const emitter = inject<Emitter<Events>>("emitter");
const snackbar = useSnackbar();
const romsStore = storeRoms();
const { syncCachedRom } = useRomSync();
const { refetchCurrentRom } = useRomSync();
const show = ref(false);
const rom = ref<DetailedRom | null>(null);
@@ -36,17 +35,6 @@ const handleShow = (payload: Events["showDeleteManualDialog"]) => {
emitter?.on("showDeleteManualDialog", handleShow);
onBeforeUnmount(() => emitter?.off("showDeleteManualDialog", handleShow));
async function refreshRom() {
if (!rom.value) return;
try {
const { data } = await romApi.getRom({ romId: rom.value.id });
romsStore.currentRom = data;
syncCachedRom(data);
} catch (error) {
console.error(error);
}
}
async function deleteManual() {
if (!rom.value || deleting.value) return;
deleting.value = true;
@@ -58,7 +46,7 @@ async function deleteManual() {
} else if (fileId.value !== undefined) {
await romApi.deleteManualFile({ romId, fileId: fileId.value });
}
await refreshRom();
await refetchCurrentRom(romId);
snackbar.success(
t(primary ? "rom.manual-removed" : "rom.manual-file-removed"),
{ icon: "mdi-check-bold" },

View File

@@ -7,7 +7,7 @@ import type { Emitter } from "mitt";
import { inject, onBeforeUnmount, ref } from "vue";
import { useI18n } from "vue-i18n";
import romApi from "@/services/api/rom";
import storeRoms, { type DetailedRom } from "@/stores/roms";
import type { DetailedRom } from "@/stores/roms";
import storeUpload from "@/stores/upload";
import type { Events } from "@/types/emitter";
import { useRomSync } from "@/v2/composables/useRomSync";
@@ -18,7 +18,6 @@ defineOptions({ inheritAttrs: false });
const { t } = useI18n();
const emitter = inject<Emitter<Events>>("emitter");
const snackbar = useSnackbar();
const romsStore = storeRoms();
const { refetchCurrentRom } = useRomSync();
const uploadStore = storeUpload();
@@ -58,10 +57,6 @@ const handleShow = (payload: Events["showManualUploadTargetDialog"]) => {
emitter?.on("showManualUploadTargetDialog", handleShow);
onBeforeUnmount(() => emitter?.off("showManualUploadTargetDialog", handleShow));
async function refreshRom(target: DetailedRom) {
await refetchCurrentRom(target.id);
}
async function handleUploadResult(
responses: PromiseSettledResult<unknown>[],
successKey: string,
@@ -78,7 +73,7 @@ async function handleUploadResult(
icon: "mdi-check-bold",
timeout: 3000,
});
await refreshRom(target);
await refetchCurrentRom(target.id);
} else {
snackbar.warning(t(skippedKey), {
icon: "mdi-close-circle",

View File

@@ -6,7 +6,6 @@ import FilesTab from "./FilesTab.vue";
const {
uploadRoms,
getRom,
refetchCurrentRom,
confirmFn,
snackbar,
@@ -14,7 +13,6 @@ const {
grants,
} = vi.hoisted(() => ({
uploadRoms: vi.fn(),
getRom: vi.fn(),
refetchCurrentRom: vi.fn(),
confirmFn: vi.fn(),
snackbar: {
@@ -36,7 +34,7 @@ vi.mock("vue-router", async (importOriginal) => ({
useRouter: () => ({ replace: vi.fn(), push: vi.fn() }),
}));
vi.mock("@/services/api/rom", () => ({
default: { uploadRoms, getRom, deleteRomFile: vi.fn() },
default: { uploadRoms, deleteRomFile: vi.fn() },
}));
vi.mock("@/v2/composables/useCan", async () => {
const { computed } = await import("vue");

View File

@@ -12,7 +12,7 @@ import type { Emitter } from "mitt";
import { computed, defineAsyncComponent, inject, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import romApi from "@/services/api/rom";
import storeRoms, { type DetailedRom } from "@/stores/roms";
import type { DetailedRom } from "@/stores/roms";
import type { Events } from "@/types/emitter";
import { FRONTEND_RESOURCES_PATH } from "@/utils";
import { useCan } from "@/v2/composables/useCan";
@@ -33,7 +33,6 @@ const TextViewer = defineAsyncComponent(
const props = defineProps<{ rom: DetailedRom }>();
const emitter = inject<Emitter<Events>>("emitter");
const snackbar = useSnackbar();
const romsStore = storeRoms();
const { refetchCurrentRom } = useRomSync();
const { t } = useI18n();
@@ -123,10 +122,6 @@ const manualItems = computed(() =>
const manualDz = ref<InstanceType<typeof RDropzone> | null>(null);
const redownloadingManual = ref(false);
async function refreshRom() {
await refetchCurrentRom(props.rom.id);
}
function handleManualFiles(files: File[]) {
if (files.length === 0) return;
emitter?.emit("showManualUploadTargetDialog", { rom: props.rom, files });
@@ -137,7 +132,7 @@ async function redownloadManual() {
redownloadingManual.value = true;
try {
await romApi.redownloadManual({ romId: props.rom.id });
await refreshRom();
await refetchCurrentRom(props.rom.id);
snackbar.success(t("rom.manual-redownloaded"), {
icon: "mdi-check-bold",
});

View File

@@ -16,7 +16,7 @@ import { computed, defineAsyncComponent, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import romApi from "@/services/api/rom";
import storeRoms, { type DetailedRom } from "@/stores/roms";
import type { DetailedRom } from "@/stores/roms";
import storeUpload from "@/stores/upload";
import { useCan } from "@/v2/composables/useCan";
import { useConfirm } from "@/v2/composables/useConfirm";
@@ -50,7 +50,6 @@ const {
loading: soundtrackLoading,
fallbackArtUrl: soundtrackArtUrl,
} = useRomSoundtrack(() => props.rom);
const romsStore = storeRoms();
const { refetchCurrentRom } = useRomSync();
const uploadStore = storeUpload();
const { t } = useI18n();

View File

@@ -23,7 +23,6 @@ import type { UserNoteSchema } from "@/__generated__";
import romApi from "@/services/api/rom";
import storeAuth from "@/stores/auth";
import type { DetailedRom } from "@/stores/roms";
import storeRoms from "@/stores/roms";
import { useConfirm } from "@/v2/composables/useConfirm";
import { useRomSync } from "@/v2/composables/useRomSync";
import { useSnackbar } from "@/v2/composables/useSnackbar";
@@ -38,7 +37,6 @@ const { t } = useI18n();
const snackbar = useSnackbar();
const confirm = useConfirm();
const authStore = storeAuth();
const romsStore = storeRoms();
const { refetchCurrentRom } = useRomSync();
const route = useRoute();
const router = useRouter();

View File

@@ -27,11 +27,9 @@ import type {
UserSaveSchema,
UserStateSchema,
} from "@/__generated__";
import romApi from "@/services/api/rom";
import saveApi from "@/services/api/save";
import stateApi from "@/services/api/state";
import storeAuth from "@/stores/auth";
import storeRoms from "@/stores/roms";
import AssetList from "@/v2/components/shared/AssetList.vue";
import AssetStrip from "@/v2/components/shared/AssetStrip.vue";
import { useConfirm } from "@/v2/composables/useConfirm";
@@ -138,7 +136,6 @@ const uploadingStates = ref(false);
const snackbar = useSnackbar();
const confirm = useConfirm();
const romsStore = storeRoms();
const { refetchCurrentRom } = useRomSync();
async function refreshRom() {

View File

@@ -19,7 +19,7 @@ import { useI18n } from "vue-i18n";
import romApi from "@/services/api/rom";
import screenshotApi from "@/services/api/screenshot";
import storeAuth from "@/stores/auth";
import storeRoms, { type DetailedRom } from "@/stores/roms";
import type { DetailedRom } from "@/stores/roms";
import storeUpload from "@/stores/upload";
import type { ScreenshotItem } from "@/v2/components/GameDetails/ScreenshotsTab.vue";
import { useCan } from "@/v2/composables/useCan";
@@ -49,7 +49,6 @@ const props = defineProps<{ rom: DetailedRom }>();
const { t } = useI18n();
const snackbar = useSnackbar();
const confirm = useConfirm();
const romsStore = storeRoms();
const { refetchCurrentRom } = useRomSync();
const uploadStore = storeUpload();
const authStore = storeAuth();

View File

@@ -8,7 +8,7 @@ import axios from "axios";
import { computed, defineAsyncComponent, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import romApi from "@/services/api/rom";
import storeRoms, { type DetailedRom } from "@/stores/roms";
import type { DetailedRom } from "@/stores/roms";
import { useCan } from "@/v2/composables/useCan";
import { useConfirm } from "@/v2/composables/useConfirm";
import { useRomSync } from "@/v2/composables/useRomSync";
@@ -45,7 +45,6 @@ type WalkthroughEntry = {
const props = defineProps<{ rom: DetailedRom }>();
const snackbar = useSnackbar();
const confirm = useConfirm();
const romsStore = storeRoms();
const { refetchCurrentRom } = useRomSync();
const { t } = useI18n();

View File

@@ -14,7 +14,9 @@ vi.mock("@/services/socket", () => ({
on: (event: string, handler: (payload: unknown) => void) => {
handlers.set(event, handler);
},
off: vi.fn(),
off: (event: string) => {
handlers.delete(event);
},
},
}));

View File

@@ -2,21 +2,18 @@
// events carry no file rows and the Files tab would keep the stale listing.
import type { ScanStats } from "@/__generated__";
import storeRoms from "@/stores/roms";
import { useIsAlive } from "@/v2/composables/useIsAlive";
import { useRomSync } from "@/v2/composables/useRomSync";
import { useSocketEvent } from "@/v2/composables/useSocketEvent";
export function useRomScanRefresh() {
const romsStore = storeRoms();
const { refetchCurrentRom } = useRomSync();
const alive = useIsAlive();
useSocketEvent<ScanStats>(
"scan:done",
async () => {
const romId = romsStore.currentRom?.id;
if (romId === undefined || !alive.value) return;
await refetchCurrentRom(romId);
if (romId !== undefined) await refetchCurrentRom(romId);
},
{ connect: false },
);

View File

@@ -60,18 +60,16 @@ export function useRomSync() {
}
}
/** Re-read a ROM from the API and apply it everywhere it is cached.
/** Re-read a ROM from the API and apply it everywhere it is cached, for the
* surfaces that write a ROM's assets and need the detailed record back
* rather than the row the write returned.
*
* For the surfaces that write a ROM's assets (saves, screenshots, manuals,
* notes, files) and need the detailed record back rather than the row the
* write returned. `currentRom` is only replaced when it is still this ROM:
* the user can open another game while the request is in flight.
*
* Returns the fresh ROM, or null when the request failed or landed late. */
* `syncCachedRom` owns the `currentRom` write, so a response that lands
* after the user opened another game updates the caches and leaves the
* open ROM alone. Returns null when the request failed. */
async function refetchCurrentRom(romId: number): Promise<DetailedRom | null> {
try {
const { data } = await romApi.getRom({ romId });
if (romsStore.currentRom?.id === romId) romsStore.setCurrentRom(data);
syncCachedRom(data);
return data;
} catch (error) {