refactor(firmware): reuse shared helpers in the missing firmware code

Swap the hand-rolled platform picker in MissingFirmwareSection for the
shared PlatformSelect, and fold the triplicated firmware builder in the
tests into an add_firmware factory fixture.

Keep Platform out of list_firmware: the relationship is lazy="joined",
so every row also ran Platform's rom_count and fs_size_bytes aggregate
subqueries over roms, for data no caller reads.

In useTaskCompletion, the resolver already identifies the live wait, so
drop the parallel generation counter and the unused cancel export.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-08-29 15:42:22 -04:00
parent c45587fe7c
commit e32c8c68cd
9 changed files with 105 additions and 225 deletions

View File

@@ -1,7 +1,7 @@
from collections.abc import Sequence
from sqlalchemy import and_, delete, select, update
from sqlalchemy.orm import QueryableAttribute, Session, load_only
from sqlalchemy.orm import QueryableAttribute, Session, load_only, noload
from decorators.database import begin_session
from models.firmware import Firmware
@@ -37,7 +37,14 @@ class DBFirmwareHandler(DBBaseHandler):
hidden_platform_ids: Sequence[int] | None = None,
session: Session = None, # type: ignore
) -> Sequence[Firmware]:
query = select(Firmware).order_by(Firmware.file_name.asc())
# `Firmware.platform` is `lazy="joined"`, which drags in Platform's
# rom_count / fs_size_bytes aggregate subqueries over `roms`. No
# caller here reads the relationship, so keep it out of the query.
query = (
select(Firmware)
.options(noload(Firmware.platform))
.order_by(Firmware.file_name.asc())
)
if platform_id:
query = query.filter_by(platform_id=platform_id)

View File

@@ -127,33 +127,43 @@ def platform():
return db_platform_handler.add_platform(platform)
def _build_firmware(platform: Platform, file_name: str, missing: bool) -> Firmware:
return Firmware(
platform_id=platform.id,
file_name=file_name,
file_path=f"{platform.fs_slug}/bios",
file_size_bytes=1024,
crc_hash="crc",
md5_hash="md5",
sha1_hash="sha1",
missing_from_fs=missing,
)
@pytest.fixture
def other_platform():
platform = Platform(name="other", slug="other_slug", fs_slug="other_slug")
return db_platform_handler.add_platform(platform)
@pytest.fixture
def firmware(platform: Platform):
def add_firmware():
"""Factory for firmware rows, defaulting to a file still on disk."""
def _add(platform: Platform, file_name: str, missing: bool = False) -> Firmware:
return db_firmware_handler.add_firmware(
Firmware(
platform_id=platform.id,
file_name=file_name,
file_path=f"{platform.fs_slug}/bios",
file_size_bytes=1024,
crc_hash="crc",
md5_hash="md5",
sha1_hash="sha1",
missing_from_fs=missing,
)
)
return _add
@pytest.fixture
def firmware(platform: Platform, add_firmware):
"""Firmware whose file is still on disk."""
return db_firmware_handler.add_firmware(
_build_firmware(platform, "present.bin", missing=False)
)
return add_firmware(platform, "present.bin")
@pytest.fixture
def missing_firmware(platform: Platform):
def missing_firmware(platform: Platform, add_firmware):
"""Firmware flagged by a scan as gone from the filesystem."""
return db_firmware_handler.add_firmware(
_build_firmware(platform, "gone.bin", missing=True)
)
return add_firmware(platform, "gone.bin", missing=True)
@pytest.fixture

View File

@@ -1,10 +1,4 @@
"""Tests for `GET /api/firmware`.
Issue #4075: the endpoint returned every row with no way to select on
`missing_from_fs`, so the player's BIOS list offered (and auto-selected)
firmware whose file was gone, and nothing could list missing firmware
library-wide.
"""
"""Tests for `GET /api/firmware`."""
from fastapi import status

View File

@@ -1,74 +1,48 @@
"""Tests for the firmware list filters.
"""Tests for the firmware list filters."""
A scan flags firmware whose file vanished with `missing_from_fs`, but until
issue #4075 nothing could select on that flag, so every consumer (the player's
BIOS list, the platform firmware count) had to take the whole set.
"""
from handler.database import db_firmware_handler, db_platform_handler
from models.firmware import Firmware
from models.platform import Platform
def _add(platform: Platform, file_name: str, missing: bool) -> Firmware:
return db_firmware_handler.add_firmware(
Firmware(
platform_id=platform.id,
file_name=file_name,
file_path=f"{platform.fs_slug}/bios",
file_size_bytes=1,
crc_hash="crc",
md5_hash="md5",
sha1_hash="sha1",
missing_from_fs=missing,
)
)
def _other_platform() -> Platform:
return db_platform_handler.add_platform(
Platform(name="other", slug="other_slug", fs_slug="other_slug")
)
from handler.database import db_firmware_handler
class TestListFirmwareMissingFilter:
def test_lists_everything_without_the_filter(self, platform):
_add(platform, "present.bin", missing=False)
_add(platform, "gone.bin", missing=True)
def test_lists_everything_without_the_filter(self, platform, add_firmware):
add_firmware(platform, "present.bin")
add_firmware(platform, "gone.bin", missing=True)
names = [f.file_name for f in db_firmware_handler.list_firmware()]
assert names == ["gone.bin", "present.bin"]
def test_missing_true_returns_only_flagged_firmware(self, platform):
_add(platform, "present.bin", missing=False)
_add(platform, "gone.bin", missing=True)
def test_missing_true_returns_only_flagged_firmware(self, platform, add_firmware):
add_firmware(platform, "present.bin")
add_firmware(platform, "gone.bin", missing=True)
firmware = db_firmware_handler.list_firmware(missing=True)
assert [f.file_name for f in firmware] == ["gone.bin"]
def test_missing_false_excludes_flagged_firmware(self, platform):
_add(platform, "present.bin", missing=False)
_add(platform, "gone.bin", missing=True)
def test_missing_false_excludes_flagged_firmware(self, platform, add_firmware):
add_firmware(platform, "present.bin")
add_firmware(platform, "gone.bin", missing=True)
firmware = db_firmware_handler.list_firmware(missing=False)
assert [f.file_name for f in firmware] == ["present.bin"]
def test_combines_with_the_platform_filter(self, platform):
other = _other_platform()
_add(platform, "gone.bin", missing=True)
_add(other, "other-gone.bin", missing=True)
def test_combines_with_the_platform_filter(
self, platform, other_platform, add_firmware
):
add_firmware(platform, "gone.bin", missing=True)
add_firmware(other_platform, "other-gone.bin", missing=True)
firmware = db_firmware_handler.list_firmware(
platform_id=platform.id, missing=True
)
assert [f.file_name for f in firmware] == ["gone.bin"]
def test_combines_with_the_hidden_platform_filter(self, platform):
other = _other_platform()
_add(platform, "gone.bin", missing=True)
_add(other, "other-gone.bin", missing=True)
def test_combines_with_the_hidden_platform_filter(
self, platform, other_platform, add_firmware
):
add_firmware(platform, "gone.bin", missing=True)
add_firmware(other_platform, "other-gone.bin", missing=True)
firmware = db_firmware_handler.list_firmware(
missing=True, hidden_platform_ids=[other.id]
missing=True, hidden_platform_ids=[other_platform.id]
)
assert [f.file_name for f in firmware] == ["gone.bin"]

View File

@@ -1,43 +1,14 @@
"""Tests for CleanupMissingFirmwareTask.
The ROM side has had a bulk cleanup for missing rows since forever; firmware
flagged by `mark_missing_firmware` had no counterpart, so stale BIOS entries
could only be removed one platform tab at a time (issue #4075).
"""
"""Tests for CleanupMissingFirmwareTask."""
import pytest
from handler.database import db_firmware_handler, db_platform_handler
from models.firmware import Firmware
from models.platform import Platform
from handler.database import db_firmware_handler
from tasks.manual.cleanup_missing_firmware import (
CleanupMissingFirmwareTask,
cleanup_missing_firmware_task,
)
def _add(platform: Platform, file_name: str, missing: bool) -> Firmware:
return db_firmware_handler.add_firmware(
Firmware(
platform_id=platform.id,
file_name=file_name,
file_path=f"{platform.fs_slug}/bios",
file_size_bytes=1,
crc_hash="crc",
md5_hash="md5",
sha1_hash="sha1",
missing_from_fs=missing,
)
)
@pytest.fixture
def other_platform() -> Platform:
return db_platform_handler.add_platform(
Platform(name="other", slug="other_slug", fs_slug="other_slug")
)
class TestCleanupMissingFirmwareTask:
@pytest.fixture
def task(self) -> CleanupMissingFirmwareTask:
@@ -52,9 +23,9 @@ class TestCleanupMissingFirmwareTask:
assert task.can_run_manually is True
assert task.cron_string is None
async def test_deletes_only_missing_firmware(self, task, platform):
present = _add(platform, "present.bin", missing=False)
gone = _add(platform, "gone.bin", missing=True)
async def test_deletes_only_missing_firmware(self, task, platform, add_firmware):
present = add_firmware(platform, "present.bin")
gone = add_firmware(platform, "gone.bin", missing=True)
stats = await task.run()
@@ -64,9 +35,11 @@ class TestCleanupMissingFirmwareTask:
assert db_firmware_handler.get_firmware(gone.id) is None
assert db_firmware_handler.get_firmware(present.id) is not None
async def test_scopes_to_a_single_platform(self, task, platform, other_platform):
mine = _add(platform, "gone.bin", missing=True)
theirs = _add(other_platform, "other-gone.bin", missing=True)
async def test_scopes_to_a_single_platform(
self, task, platform, other_platform, add_firmware
):
mine = add_firmware(platform, "gone.bin", missing=True)
theirs = add_firmware(other_platform, "other-gone.bin", missing=True)
stats = await task.run(platform_id=platform.id)
@@ -75,9 +48,9 @@ class TestCleanupMissingFirmwareTask:
assert db_firmware_handler.get_firmware(mine.id) is None
assert db_firmware_handler.get_firmware(theirs.id) is not None
async def test_counts_delete_failures(self, task, platform, mocker):
_add(platform, "gone-a.bin", missing=True)
_add(platform, "gone-b.bin", missing=True)
async def test_counts_delete_failures(self, task, platform, mocker, add_firmware):
add_firmware(platform, "gone-a.bin", missing=True)
add_firmware(platform, "gone-b.bin", missing=True)
mocker.patch(
"tasks.manual.cleanup_missing_firmware.db_firmware_handler.delete_firmware",
side_effect=RuntimeError("boom"),
@@ -89,8 +62,8 @@ class TestCleanupMissingFirmwareTask:
assert stats["firmware_deleted"] == 0
assert stats["errors"] == 2
async def test_no_missing_firmware_is_a_no_op(self, task, platform):
_add(platform, "present.bin", missing=False)
async def test_no_missing_firmware_is_a_no_op(self, task, platform, add_firmware):
add_firmware(platform, "present.bin")
stats = await task.run()

View File

@@ -1,42 +1,22 @@
<script setup lang="ts">
// MissingFirmwareSection — Settings tab listing every firmware (BIOS) file
// flagged as gone from disk, across the whole library, with a bulk cleanup.
// Before this, a stale entry could only be found by opening each platform's
// Firmware tab one at a time (issue #4075).
//
// Structured after MissingGamesSection: a platform multi-select on the left,
// a count chip plus a kebab holding cleanup-all on the right, and a bordered
// list below. It differs in how it loads: firmware sets are small (dozens per
// library, not tens of thousands), so the whole missing set is fetched once
// and the platform filter narrows it in memory rather than refetching.
import {
RBtn,
REmptyState,
RIcon,
RMenu,
RMenuItem,
RSelect,
RTag,
} from "@v2/lib";
// Firmware sets are small (dozens per library, not tens of thousands), so the
// whole missing set is fetched once and the platform filter narrows it in
// memory rather than refetching.
import { RBtn, REmptyState, RIcon, RMenu, RMenuItem, RTag } from "@v2/lib";
import { storeToRefs } from "pinia";
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import type { FirmwareSchema } from "@/__generated__";
import firmwareApi from "@/services/api/firmware";
import taskApi from "@/services/api/task";
import storePlatforms from "@/stores/platforms";
import storePlatforms, { type Platform } from "@/stores/platforms";
import { formatBytes } from "@/utils";
import CachedPlatformIcon from "@/v2/components/shared/CachedPlatformIcon.vue";
import PlatformSelect from "@/v2/components/shared/PlatformSelect.vue";
import { useConfirm } from "@/v2/composables/useConfirm";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import { useTaskCompletion } from "@/v2/composables/useTaskCompletion";
interface PlatformItem {
id: number;
slug: string;
name: string;
}
defineOptions({ inheritAttrs: false });
const { t } = useI18n();
@@ -51,16 +31,14 @@ const missingFirmware = ref<FirmwareSchema[]>([]);
const loading = ref(true);
const cleaningUp = ref(false);
const selectedPlatformIds = ref<number[]>([]);
const platformSearch = ref("");
// Only platforms that actually have something to clean up: the rest would
// filter the list down to nothing.
const platformItems = computed<PlatformItem[]>(() => {
const platformItems = computed<Platform[]>(() => {
const affected = new Set(missingFirmware.value.map((f) => f.platform_id));
return allPlatforms.value
.filter((p) => affected.has(p.id))
.map((p) => ({ id: p.id, slug: p.slug, name: p.display_name }))
.sort((a, b) => a.name.localeCompare(b.name));
.sort((a, b) => a.display_name.localeCompare(b.display_name));
});
const platformById = computed(
@@ -81,7 +59,7 @@ const showEmpty = computed(() => !loading.value && rows.value.length === 0);
const selectedPlatformsLabel = computed(() =>
selectedPlatformIds.value
.map((id) => platformById.value.get(id)?.name)
.map((id) => platformById.value.get(id)?.display_name)
.filter(Boolean)
.join(", "),
);
@@ -129,8 +107,6 @@ async function cleanupAll() {
: {};
const { data } = await taskApi.runTask("cleanup_missing_firmware", body);
snackbar.success(t("settings.cleanup-firmware-queued"));
// The run endpoint returns once the job is queued, so wait for the worker
// to finish before showing what's left.
if (await awaitTask(data.task_id)) await fetchMissingFirmware();
} catch (err) {
snackbar.error(t("settings.couldnt-queue-cleanup", { error: String(err) }));
@@ -147,18 +123,13 @@ onMounted(() => {
<template>
<div class="r-v2-missing-fw">
<div class="r-v2-missing-fw__toolbar">
<RSelect
<PlatformSelect
v-model="selectedPlatformIds"
v-model:search="platformSearch"
:items="platformItems"
item-title="name"
item-value="id"
prefix-label="inline"
multiple
chips
closable-chips
clearable
searchable
prefix-label="inline"
:search-placeholder="t('common.search')"
:placeholder="t('common.all')"
hide-details
@@ -168,29 +139,7 @@ onMounted(() => {
<RIcon icon="mdi-controller" size="14" />
{{ t("common.platform") }}
</template>
<template #selection="{ item }">
<span class="r-v2-missing-fw__platform-chip">
<CachedPlatformIcon
:slug="(item.raw as PlatformItem).slug"
:name="(item.raw as PlatformItem).name"
:size="14"
/>
<span>{{ (item.raw as PlatformItem).name }}</span>
</span>
</template>
<template #item="{ props: itemProps, item }">
<li v-bind="itemProps">
<CachedPlatformIcon
:slug="(item.raw as PlatformItem).slug"
:name="(item.raw as PlatformItem).name"
:size="20"
/>
<span class="r-select__item-title">
{{ (item.raw as PlatformItem).name }}
</span>
</li>
</template>
</RSelect>
</PlatformSelect>
<div class="r-v2-missing-fw__actions">
<RTag
v-if="!loading"
@@ -252,10 +201,10 @@ onMounted(() => {
<span v-if="platform" class="r-v2-missing-fw__row-platform">
<CachedPlatformIcon
:slug="platform.slug"
:name="platform.name"
:name="platform.display_name"
:size="16"
/>
{{ platform.name }}
{{ platform.display_name }}
</span>
<span class="r-v2-missing-fw__row-size">
{{ formatBytes(firmware.file_size_bytes) }}
@@ -285,12 +234,6 @@ onMounted(() => {
max-width: 480px;
}
.r-v2-missing-fw__platform-chip {
display: inline-flex;
align-items: center;
gap: 6px;
}
.r-v2-missing-fw__actions {
display: flex;
align-items: center;

View File

@@ -255,8 +255,6 @@ async function cleanupAll() {
: {};
const { data } = await taskApi.runTask("cleanup_missing_roms", body);
snackbar.success(t("settings.cleanup-queued"));
// The run endpoint returns once the job is queued, so wait for the worker
// to finish before reloading the table.
if (await awaitTask(data.task_id)) {
galleryRoms.invalidateWindows();
await galleryRoms.fetchInitialMetadata(NO_SIDECARS);

View File

@@ -1,18 +1,6 @@
// useTaskCompletion — wait for a queued RQ job to finish before reacting to it.
//
// `POST /tasks/run/{name}` returns as soon as the job is enqueued, so anything
// that wants to show the job's effect has to wait for the worker. Guessing at
// a fixed delay loses the race whenever the worker is busy or the job is slow,
// which leaves the caller showing stale data behind a success toast. Polling
// the job's own status instead means the wait is as long as the job actually
// takes. There is no socket event for task completion, and `TasksSection`
// already polls task status, so this follows the same mechanism scoped to one
// job.
//
// Usage:
// const { awaitTask } = useTaskCompletion();
// const { data } = await taskApi.runTask("cleanup_missing_roms", body);
// if (await awaitTask(data.task_id)) await refresh();
// `POST /tasks/run/{name}` returns as soon as the job is enqueued, so a caller
// that wants to show the job's effect has to wait for the worker. There is no
// socket event for task completion, so poll the job's own status.
import axios from "axios";
import { onScopeDispose } from "vue";
import type { JobStatus } from "@/__generated__";
@@ -42,20 +30,17 @@ export interface UseTaskCompletion {
* refresh still happens on a best-effort basis.
*/
awaitTask: (taskId: string) => Promise<boolean>;
/** Abandons an in-flight wait. Called automatically on scope dispose. */
cancel: () => void;
}
export function useTaskCompletion(): UseTaskCompletion {
let timer: ReturnType<typeof setTimeout> | null = null;
// Bumped on cancel so a poll already in flight knows it was superseded.
let generation = 0;
// Cancelling clears the pending timer, so it has to settle the outstanding
// promise itself or the caller waits on it forever.
// The live wait's resolver, which doubles as its identity: a poll still in
// flight compares against it to know whether it was superseded. Cancelling
// clears the pending timer, so it has to settle the outstanding promise
// itself or the caller waits on it forever.
let settle: ((observed: boolean) => void) | null = null;
function cancel() {
generation += 1;
if (timer) clearTimeout(timer);
timer = null;
settle?.(false);
@@ -64,7 +49,6 @@ export function useTaskCompletion(): UseTaskCompletion {
function awaitTask(taskId: string): Promise<boolean> {
cancel();
const mine = generation;
const deadline = Date.now() + POLL_TIMEOUT_MS;
let delay = FIRST_POLL_DELAY_MS;
@@ -72,20 +56,20 @@ export function useTaskCompletion(): UseTaskCompletion {
settle = resolve;
const finish = (observed: boolean) => {
if (mine !== generation) return;
if (settle !== resolve) return;
settle = null;
resolve(observed);
};
const poll = async () => {
if (mine !== generation) return;
if (settle !== resolve) return;
try {
const { data } = await taskApi.getTaskById(taskId);
if (mine !== generation) return;
if (settle !== resolve) return;
if (TERMINAL_STATUSES.includes(data.status)) return finish(true);
} catch (err) {
if (mine !== generation) return;
if (settle !== resolve) return;
// A job past its result TTL 404s, which means it ran and is gone.
// Anything else (a timeout, a 5xx) says nothing about the job, so
// keep polling rather than refreshing over a cleanup still in
@@ -107,5 +91,5 @@ export function useTaskCompletion(): UseTaskCompletion {
onScopeDispose(cancel);
return { awaitTask, cancel };
return { awaitTask };
}

View File

@@ -1,11 +1,8 @@
// Choosing which firmware (BIOS) the EmulatorJS player boots with.
//
// A scan flags firmware whose file vanished with `missing_from_fs`, but the
// player used to offer every entry for the platform, and auto-selected the sole
// entry when there was only one. A stale sole entry then made the game fail to
// load with nothing pointing at the BIOS (issue #4075). Missing entries are
// never selectable here, so a platform whose only BIOS is gone boots with none
// rather than with a file the server can't serve.
// A platform whose only BIOS is gone boots with none rather than with a file
// the server can't serve. The caller already fetches with `missing: false`;
// re-filtering keeps that rule true for any other caller.
// Only these fields are read, so both `FirmwareSchema` and lighter shapes fit.
interface FirmwareLike {