diff --git a/DEVELOPER_SETUP.md b/DEVELOPER_SETUP.md index fcc3d916f..6b0518c13 100644 --- a/DEVELOPER_SETUP.md +++ b/DEVELOPER_SETUP.md @@ -126,6 +126,27 @@ cd backend uv run python3 main.py ``` +#### - Run the task workers + +Manual tasks (the missing ROMs and firmware cleanups, folder sync) and every scheduled job run on RQ workers, and scans on a worker of their own. Without them a task stays queued. Each command is a foreground process, so run them in separate terminals. The Redis URL below matches the `REDIS_*` defaults in `.env`; adjust it if you changed them. + +```sh +cd backend +uv run rq worker --url redis://127.0.0.1:6379/0 --worker-class handler.rq_worker.RomMWorker --with-scheduler high default low +``` + +```sh +cd backend +uv run rq worker --url redis://127.0.0.1:6379/0 --worker-class handler.rq_worker.RomMWorker scans +``` + +`--with-scheduler` only releases delayed jobs. The recurring schedule itself is registered by the RQ cron process, which the workers then execute: + +```sh +cd backend +RQ_REDIS_URL=redis://127.0.0.1:6379/0 uv run rq cron tasks.cron_config +``` + ### Setting up the frontend #### - Install node.js dependencies diff --git a/backend/endpoints/responses/__init__.py b/backend/endpoints/responses/__init__.py index b225d6f89..6f1fa89c2 100644 --- a/backend/endpoints/responses/__init__.py +++ b/backend/endpoints/responses/__init__.py @@ -53,13 +53,24 @@ class OrphanedResourcesCleanupStats(TypedDict): class MissingRomsCleanupStats(TypedDict): - platform_id: int | None + platform_ids: list[int] | None roms_found: int roms_deleted: int errors: int -CleanupStats = Union[OrphanedResourcesCleanupStats, MissingRomsCleanupStats] +class MissingFirmwareCleanupStats(TypedDict): + platform_ids: list[int] | None + firmware_found: int + firmware_deleted: int + errors: int + + +CleanupStats = Union[ + OrphanedResourcesCleanupStats, + MissingRomsCleanupStats, + MissingFirmwareCleanupStats, +] class CleanupTaskMeta(TypedDict): diff --git a/backend/endpoints/tasks.py b/backend/endpoints/tasks.py index 781be1b6e..119957b14 100644 --- a/backend/endpoints/tasks.py +++ b/backend/endpoints/tasks.py @@ -1,11 +1,12 @@ from datetime import datetime, timezone from typing import Any, Final, Mapping, cast -from fastapi import Body, HTTPException, Request -from rq import Worker +from fastapi import Body, HTTPException, Request, status +from rq import Queue, Worker from rq.exceptions import NoSuchJobError from rq.job import Job, JobStatus from rq.registry import FailedJobRegistry, FinishedJobRegistry +from rq.worker import WorkerStatus from config import ENABLE_RESCAN_ON_FILESYSTEM_CHANGE, RESCAN_ON_FILESYSTEM_CHANGE_DELAY from decorators.auth import protected_route @@ -27,6 +28,7 @@ from handler.redis_handler import ( ALL_QUEUES, get_job_func_name, get_worker_current_job, + low_prio_queue, redis_client, ) from tasks.registry import MANUAL_TASKS, SCHEDULED_TASKS, enqueue_task @@ -273,6 +275,19 @@ async def get_task_by_id(request: Request, task_id: str) -> TaskStatusResponse: TASK_KWARGS = Body(default=None) +def _listening_workers(queue: Queue) -> list[Worker]: + """Registered workers of ``queue`` that are alive and not suspended. + + A crashed worker stays registered until its TTL expires, which RQ's own + maintenance sweep bounds; this filters the ones that told us they left. + """ + return [ + worker + for worker in Worker.all(queue=queue, connection=redis_client) + if worker.death_date is None and worker.get_state() != WorkerStatus.SUSPENDED + ] + + @protected_route(router.post, "/run/{task_name}", [Scope.TASKS_RUN]) async def run_single_task( request: Request, @@ -301,6 +316,13 @@ async def run_single_task( detail=f"Task '{task_name}' cannot be run", ) + # Without a worker the job would sit queued while the UI waits on it. + if not _listening_workers(low_prio_queue): + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="No task worker is running, so the task cannot be queued", + ) + # The caller's arguments are nested rather than spread, so a body cannot # name a different task than the one this route just authorized. job = enqueue_task(task_name, task_kwargs=task_kwargs or {}) diff --git a/backend/tests/endpoints/test_tasks.py b/backend/tests/endpoints/test_tasks.py index bc5045bc1..dd73d6f0f 100644 --- a/backend/tests/endpoints/test_tasks.py +++ b/backend/tests/endpoints/test_tasks.py @@ -5,10 +5,31 @@ import pytest from fastapi import status from rq.exceptions import NoSuchJobError -from handler.redis_handler import redis_client +from handler.redis_handler import low_prio_queue, redis_client, scan_queue +from tasks.manual.cleanup_missing_firmware import CleanupMissingFirmwareStats +from tasks.manual.cleanup_missing_roms import CleanupMissingRomsStats from tasks.tasks import Task, TaskType +def _live_worker() -> Mock: + worker = Mock(death_date=None) + worker.get_state.return_value = "idle" + return worker + + +@pytest.fixture(autouse=True) +def task_queue_worker(): + """A live worker on the task queue, so a run is accepted unless a test + takes it away.""" + worker = _live_worker() + + def workers_for(connection=None, queue=None, **_kwargs): + return [worker] if queue is low_prio_queue else [] + + with patch("endpoints.tasks.Worker.all", side_effect=workers_for) as mocked: + yield mocked + + def _job_with_meta(meta: dict[str, Any]) -> Mock: """A finished job carrying `meta`, for asserting on what the response reports.""" job = Mock() @@ -271,6 +292,76 @@ class TestRunSingleTask: mock_enqueue.assert_called_once() + @patch("endpoints.tasks.enqueue_task") + @patch( + "endpoints.tasks.RUNNABLE_TASKS", + { + "test_task": Mock( + spec=Task, + task_type=TaskType.CLEANUP, + title="Test Task", + enabled=True, + manual_run=True, + can_run_manually=True, + run=Mock(), + ), + }, + ) + def test_run_single_task_without_a_worker_is_refused( + self, mock_enqueue, client, access_token + ): + with patch("endpoints.tasks.Worker.all", return_value=[]): + response = client.post( + "/api/tasks/run/test_task", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE + assert "worker" in response.json()["detail"] + mock_enqueue.assert_not_called() + + @pytest.mark.parametrize( + "workers_for", + [ + # A scan worker does not serve the task queue. + lambda connection=None, queue=None, **_: ( + [_live_worker()] if queue is scan_queue else [] + ), + # One that announced its death or was suspended does not count. + lambda connection=None, queue=None, **_: [Mock(death_date="gone")], + lambda connection=None, queue=None, **_: [ + Mock(death_date=None, **{"get_state.return_value": "suspended"}) + ], + ], + ids=["scan-worker-only", "dead-worker", "suspended-worker"], + ) + @patch("endpoints.tasks.enqueue_task") + @patch( + "endpoints.tasks.RUNNABLE_TASKS", + { + "test_task": Mock( + spec=Task, + task_type=TaskType.CLEANUP, + title="Test Task", + enabled=True, + manual_run=True, + can_run_manually=True, + run=Mock(), + ), + }, + ) + def test_only_a_live_worker_on_the_task_queue_counts( + self, mock_enqueue, client, access_token, workers_for + ): + with patch("endpoints.tasks.Worker.all", side_effect=workers_for): + response = client.post( + "/api/tasks/run/test_task", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE + mock_enqueue.assert_not_called() + @patch("endpoints.tasks.RUNNABLE_TASKS", {}) def test_run_single_task_not_found(self, client, access_token): """Test running a non-existent task""" @@ -382,6 +473,41 @@ class TestGetTasksStatus: class TestGetTaskById: """Test suite for the get_task_by_id endpoint""" + @pytest.mark.parametrize( + "stats", + [ + CleanupMissingRomsStats(platform_ids=[3], roms_found=2, roms_deleted=2), + CleanupMissingFirmwareStats(firmware_found=1, firmware_deleted=1), + ], + ) + @patch("endpoints.tasks.Job.fetch") + def test_a_finished_cleanup_reports_its_stats( + self, mock_job_fetch, client, access_token, stats + ): + mock_job = Mock() + for field in ("enqueued_at", "created_at", "started_at", "ended_at"): + setattr(mock_job, field, Mock()) + getattr(mock_job, field).isoformat.return_value = "2023-01-01T00:00:00" + mock_job.get_meta.return_value = { + "task_key": "cleanup_missing_roms", + "task_type": TaskType.CLEANUP, + "cleanup_stats": stats.to_dict(), + } + mock_job.func_name = "tasks.tasks.run_task_by_name" + mock_job.kwargs = {"name": "cleanup_missing_roms"} + mock_job.get_status.return_value = "finished" + mock_job.id = "cleanup-job" + mock_job.result = stats.to_dict() + mock_job_fetch.return_value = mock_job + + response = client.get( + "/api/tasks/cleanup-job", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + assert response.json()["meta"]["cleanup_stats"] == stats.to_dict() + @patch("endpoints.tasks.Job.fetch") def test_get_task_by_id_success(self, mock_job_fetch, client, access_token): """Test successful retrieval of a task by job ID""" diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts index 95ca60ceb..7ef424937 100644 --- a/frontend/src/__generated__/index.ts +++ b/frontend/src/__generated__/index.ts @@ -130,6 +130,7 @@ export type { MemoryCardVersionSchema } from './models/MemoryCardVersionSchema'; export type { MetadataCoverageItem } from './models/MetadataCoverageItem'; export type { MetadataMediaType } from './models/MetadataMediaType'; export type { MetadataSourcesDict } from './models/MetadataSourcesDict'; +export type { MissingFirmwareCleanupStats } from './models/MissingFirmwareCleanupStats'; export type { MissingRomsCleanupStats } from './models/MissingRomsCleanupStats'; export type { MobyMetadataPlatform } from './models/MobyMetadataPlatform'; export type { MusicGameFacetSchema } from './models/MusicGameFacetSchema'; diff --git a/frontend/src/__generated__/models/CleanupTaskMeta.ts b/frontend/src/__generated__/models/CleanupTaskMeta.ts index ad55db405..1e0897265 100644 --- a/frontend/src/__generated__/models/CleanupTaskMeta.ts +++ b/frontend/src/__generated__/models/CleanupTaskMeta.ts @@ -2,9 +2,10 @@ /* istanbul ignore file */ /* tslint:disable */ /* eslint-disable */ +import type { MissingFirmwareCleanupStats } from './MissingFirmwareCleanupStats'; import type { MissingRomsCleanupStats } from './MissingRomsCleanupStats'; import type { OrphanedResourcesCleanupStats } from './OrphanedResourcesCleanupStats'; export type CleanupTaskMeta = { - cleanup_stats: (OrphanedResourcesCleanupStats | MissingRomsCleanupStats | null); + cleanup_stats: (OrphanedResourcesCleanupStats | MissingRomsCleanupStats | MissingFirmwareCleanupStats | null); }; diff --git a/frontend/src/__generated__/models/MissingFirmwareCleanupStats.ts b/frontend/src/__generated__/models/MissingFirmwareCleanupStats.ts new file mode 100644 index 000000000..ed5c09be1 --- /dev/null +++ b/frontend/src/__generated__/models/MissingFirmwareCleanupStats.ts @@ -0,0 +1,11 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +export type MissingFirmwareCleanupStats = { + platform_ids: (Array | null); + firmware_found: number; + firmware_deleted: number; + errors: number; +}; + diff --git a/frontend/src/__generated__/models/MissingRomsCleanupStats.ts b/frontend/src/__generated__/models/MissingRomsCleanupStats.ts index ced1b85cb..59d8bffc4 100644 --- a/frontend/src/__generated__/models/MissingRomsCleanupStats.ts +++ b/frontend/src/__generated__/models/MissingRomsCleanupStats.ts @@ -3,7 +3,7 @@ /* tslint:disable */ /* eslint-disable */ export type MissingRomsCleanupStats = { - platform_id: (number | null); + platform_ids: (Array | null); roms_found: number; roms_deleted: number; errors: number; diff --git a/frontend/src/locales/bg_BG/settings.json b/frontend/src/locales/bg_BG/settings.json index 1438be469..5383b7dc1 100644 --- a/frontend/src/locales/bg_BG/settings.json +++ b/frontend/src/locales/bg_BG/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "Това ще изтрие окончателно всички липсващи ROM-ове{platform} от базата данни и техните директории. Това действие е необратимо.", "cleanup-firmware-confirm": "Това ще изтрие окончателно всеки запис за фърмуер{platform}, чийто файл липсва от файловата система. Нищо няма да бъде премахнато от диска.", "cleanup-firmware-queued": "Задачата за почистване е на опашка, липсващият фърмуер ще бъде изтрит скоро", - "cleanup-queued": "Задачата за почистване е на опашка — липсващите ROM-ове ще бъдат изтрити скоро", + "cleanup-queued": "Задачата за почистване е на опашка, липсващите ROM-ове ще бъдат изтрити скоро", "client-api-tokens": "API токени", "client-token-confirm-delete": "Сигурен ли си, че искаш да отмениш този токен? Всички устройства които го използват ще загубят достъп.", "client-token-confirm-regenerate": "Това ще анулира текущия токен. Всички устройства използващи стария токен ще трябва да се сдвоят отново.", diff --git a/frontend/src/locales/cs_CZ/settings.json b/frontend/src/locales/cs_CZ/settings.json index 8dc1bf679..c4166b911 100644 --- a/frontend/src/locales/cs_CZ/settings.json +++ b/frontend/src/locales/cs_CZ/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Tímto se z databáze trvale odstraní každý záznam firmwaru{platform}, jehož soubor v souborovém systému chybí. Na disku se nic nesmaže.", "cleanup-firmware-queued": "Úloha vyčištění zařazena do fronty, chybějící firmware bude brzy smazán", - "cleanup-queued": "Úloha vyčištění zařazena do fronty — chybějící ROMy budou brzy smazány", + "cleanup-queued": "Úloha vyčištění zařazena do fronty, chybějící ROMy budou brzy smazány", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/de_DE/settings.json b/frontend/src/locales/de_DE/settings.json index ffca1a99c..00105af77 100644 --- a/frontend/src/locales/de_DE/settings.json +++ b/frontend/src/locales/de_DE/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Dadurch wird jeder Firmware-Eintrag{platform}, dessen Datei im Dateisystem fehlt, dauerhaft aus der Datenbank gelöscht. Auf der Festplatte wird nichts entfernt.", "cleanup-firmware-queued": "Bereinigungsaufgabe in Warteschlange, fehlende Firmware wird in Kürze gelöscht", - "cleanup-queued": "Bereinigungsaufgabe in Warteschlange — fehlende ROMs werden in Kürze gelöscht", + "cleanup-queued": "Bereinigungsaufgabe in Warteschlange, fehlende ROMs werden in Kürze gelöscht", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/en_GB/settings.json b/frontend/src/locales/en_GB/settings.json index f7817aa26..aa03d137f 100644 --- a/frontend/src/locales/en_GB/settings.json +++ b/frontend/src/locales/en_GB/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "This will permanently delete every firmware entry{platform} whose file is missing from the filesystem. Nothing is removed from disk.", "cleanup-firmware-queued": "Cleanup task queued, missing firmware will be deleted shortly", - "cleanup-queued": "Cleanup task queued — missing ROMs will be deleted shortly", + "cleanup-queued": "Cleanup task queued, missing ROMs will be deleted shortly", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/en_US/settings.json b/frontend/src/locales/en_US/settings.json index 4c4387247..c7b8dc7cb 100644 --- a/frontend/src/locales/en_US/settings.json +++ b/frontend/src/locales/en_US/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "This will permanently delete every firmware entry{platform} whose file is missing from the filesystem. Nothing is removed from disk.", "cleanup-firmware-queued": "Cleanup task queued, missing firmware will be deleted shortly", - "cleanup-queued": "Cleanup task queued — missing ROMs will be deleted shortly", + "cleanup-queued": "Cleanup task queued, missing ROMs will be deleted shortly", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/es_ES/settings.json b/frontend/src/locales/es_ES/settings.json index f7d2de8ea..d0569c26e 100644 --- a/frontend/src/locales/es_ES/settings.json +++ b/frontend/src/locales/es_ES/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Esto eliminará permanentemente de la base de datos cada entrada de firmware{platform} cuyo archivo falte en el sistema de archivos. No se elimina nada del disco.", "cleanup-firmware-queued": "Tarea de limpieza en cola, el firmware ausente se eliminará en breve", - "cleanup-queued": "Tarea de limpieza en cola — las ROMs ausentes se eliminarán en breve", + "cleanup-queued": "Tarea de limpieza en cola, las ROMs ausentes se eliminarán en breve", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/fr_FR/settings.json b/frontend/src/locales/fr_FR/settings.json index b40745ca7..44a925f2d 100644 --- a/frontend/src/locales/fr_FR/settings.json +++ b/frontend/src/locales/fr_FR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Cette action supprimera définitivement de la base de données chaque entrée de firmware{platform} dont le fichier est absent du système de fichiers. Rien n'est supprimé du disque.", "cleanup-firmware-queued": "Tâche de nettoyage mise en file d'attente, les firmwares manquants seront supprimés sous peu", - "cleanup-queued": "Tâche de nettoyage mise en file d'attente — les ROMs manquantes seront supprimées sous peu", + "cleanup-queued": "Tâche de nettoyage mise en file d'attente, les ROMs manquantes seront supprimées sous peu", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/hu_HU/settings.json b/frontend/src/locales/hu_HU/settings.json index 61248d518..f9ed2f981 100644 --- a/frontend/src/locales/hu_HU/settings.json +++ b/frontend/src/locales/hu_HU/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Ez véglegesen törli az adatbázisból minden olyan firmware-bejegyzést{platform}, amelynek a fájlja hiányzik a fájlrendszerből. A lemezről semmi sem törlődik.", "cleanup-firmware-queued": "Takarítási feladat sorba állítva, a hiányzó firmware hamarosan törlődik", - "cleanup-queued": "Takarítási feladat sorba állítva — a hiányzó ROM-ok hamarosan törlődnek", + "cleanup-queued": "Takarítási feladat sorba állítva, a hiányzó ROM-ok hamarosan törlődnek", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/it_IT/settings.json b/frontend/src/locales/it_IT/settings.json index e0d1ad6b2..36cdbe4c1 100644 --- a/frontend/src/locales/it_IT/settings.json +++ b/frontend/src/locales/it_IT/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Questa azione eliminerà definitivamente dal database ogni voce di firmware{platform} il cui file manca dal filesystem. Nulla viene rimosso dal disco.", "cleanup-firmware-queued": "Attività di pulizia accodata, il firmware mancante verrà eliminato a breve", - "cleanup-queued": "Attività di pulizia accodata — le ROM mancanti verranno eliminate a breve", + "cleanup-queued": "Attività di pulizia accodata, le ROM mancanti verranno eliminate a breve", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ja_JP/settings.json b/frontend/src/locales/ja_JP/settings.json index 38a2e353b..f11071644 100644 --- a/frontend/src/locales/ja_JP/settings.json +++ b/frontend/src/locales/ja_JP/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "ファイルシステムにファイルが存在しないファームウェアの登録{platform}をデータベースから完全に削除します。ディスク上のファイルは削除されません。", "cleanup-firmware-queued": "クリーンアップタスクをキューに追加しました。不足しているファームウェアはまもなく削除されます", - "cleanup-queued": "クリーンアップタスクをキューに追加しました — 不足しているROMはまもなく削除されます", + "cleanup-queued": "クリーンアップタスクをキューに追加しました。不足しているROMはまもなく削除されます", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ko_KR/settings.json b/frontend/src/locales/ko_KR/settings.json index 194e70318..5bf1a67fc 100644 --- a/frontend/src/locales/ko_KR/settings.json +++ b/frontend/src/locales/ko_KR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "파일 시스템에서 파일이 사라진 모든 펌웨어 항목{platform}을 데이터베이스에서 영구적으로 삭제합니다. 디스크에서는 아무것도 삭제되지 않습니다.", "cleanup-firmware-queued": "정리 작업이 대기열에 추가되었습니다. 누락된 펌웨어는 곧 삭제됩니다", - "cleanup-queued": "정리 작업이 대기열에 추가되었습니다 — 누락된 ROM은 곧 삭제됩니다", + "cleanup-queued": "정리 작업이 대기열에 추가되었습니다. 누락된 ROM은 곧 삭제됩니다", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/pl_PL/settings.json b/frontend/src/locales/pl_PL/settings.json index 30f83fabd..57b74a7e8 100644 --- a/frontend/src/locales/pl_PL/settings.json +++ b/frontend/src/locales/pl_PL/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Spowoduje to trwałe usunięcie z bazy danych każdego wpisu oprogramowania{platform}, którego plik nie istnieje w systemie plików. Nic nie zostanie usunięte z dysku.", "cleanup-firmware-queued": "Zadanie czyszczenia w kolejce, brakujące oprogramowanie zostanie wkrótce usunięte", - "cleanup-queued": "Zadanie czyszczenia w kolejce — brakujące ROM-y zostaną wkrótce usunięte", + "cleanup-queued": "Zadanie czyszczenia w kolejce, brakujące ROM-y zostaną wkrótce usunięte", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/pt_BR/settings.json b/frontend/src/locales/pt_BR/settings.json index 2a32496e9..591148603 100644 --- a/frontend/src/locales/pt_BR/settings.json +++ b/frontend/src/locales/pt_BR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "Isso excluirá permanentemente do banco de dados todas as ROMs ausentes{platform} e seus diretórios de recursos. Esta ação não pode ser desfeita.", "cleanup-firmware-confirm": "Isso excluirá permanentemente do banco de dados cada entrada de firmware{platform} cujo arquivo esteja ausente no sistema de arquivos. Nada é removido do disco.", "cleanup-firmware-queued": "Tarefa de limpeza na fila, o firmware ausente será excluído em breve", - "cleanup-queued": "Tarefa de limpeza na fila — as ROMs ausentes serão excluídas em breve", + "cleanup-queued": "Tarefa de limpeza na fila, as ROMs ausentes serão excluídas em breve", "client-api-tokens": "Tokens de API de cliente", "client-token-confirm-delete": "Tem certeza de que deseja revogar este token? Qualquer dispositivo que o utilize perderá o acesso.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ro_RO/settings.json b/frontend/src/locales/ro_RO/settings.json index 4ac3d4e8c..ed1fcbb02 100644 --- a/frontend/src/locales/ro_RO/settings.json +++ b/frontend/src/locales/ro_RO/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Aceasta va șterge definitiv din baza de date fiecare intrare de firmware{platform} al cărei fișier lipsește din sistemul de fișiere. Nu se șterge nimic de pe disc.", "cleanup-firmware-queued": "Sarcina de curățare a fost pusă în coadă, firmware-ul lipsă va fi șters în scurt timp", - "cleanup-queued": "Sarcina de curățare a fost pusă în coadă — ROM-urile lipsă vor fi șterse în scurt timp", + "cleanup-queued": "Sarcina de curățare a fost pusă în coadă, ROM-urile lipsă vor fi șterse în scurt timp", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ru_RU/settings.json b/frontend/src/locales/ru_RU/settings.json index 56e5865b1..b0dc66c8c 100644 --- a/frontend/src/locales/ru_RU/settings.json +++ b/frontend/src/locales/ru_RU/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Это навсегда удалит из базы данных каждую запись прошивки{platform}, файл которой отсутствует в файловой системе. С диска ничего не удаляется.", "cleanup-firmware-queued": "Задача очистки поставлена в очередь, отсутствующие прошивки скоро будут удалены", - "cleanup-queued": "Задача очистки поставлена в очередь — отсутствующие ROM-ы скоро будут удалены", + "cleanup-queued": "Задача очистки поставлена в очередь, отсутствующие ROM-ы скоро будут удалены", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/tr_TR/settings.json b/frontend/src/locales/tr_TR/settings.json index e047f54b8..cb2f8171a 100644 --- a/frontend/src/locales/tr_TR/settings.json +++ b/frontend/src/locales/tr_TR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "Bu işlem, veritabanından tüm eksik ROM'ları{platform} ve kaynak dizinlerini kalıcı olarak siler. Bu işlem geri alınamaz.", "cleanup-firmware-confirm": "Bu işlem, dosyası dosya sisteminde bulunmayan her firmware kaydını{platform} veritabanından kalıcı olarak siler. Diskten hiçbir şey silinmez.", "cleanup-firmware-queued": "Temizlik görevi sıraya alındı, eksik firmware kısa süre içinde silinecek", - "cleanup-queued": "Temizlik görevi sıraya alındı — eksik ROM'lar kısa süre içinde silinecek", + "cleanup-queued": "Temizlik görevi sıraya alındı, eksik ROM'lar kısa süre içinde silinecek", "client-api-tokens": "İstemci API Tokenları", "client-token-confirm-delete": "Bu tokenı iptal etmek istediğinizden emin misiniz? Kullanan tüm cihazlar erişimini kaybedecek.", "client-token-confirm-regenerate": "Bu işlem mevcut kimlik bilgisini geçersiz kılacak. Eski tokenı kullanan cihazların yeniden eşleştirilmesi gerekecek.", diff --git a/frontend/src/locales/zh_CN/settings.json b/frontend/src/locales/zh_CN/settings.json index 01d4a57b9..d0d2de8ee 100644 --- a/frontend/src/locales/zh_CN/settings.json +++ b/frontend/src/locales/zh_CN/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "这会从数据库中永久删除所有缺失的 ROM{platform} 及其资源目录。此操作无法撤销。", "cleanup-firmware-confirm": "这将从数据库中永久删除文件已从文件系统中缺失的所有固件条目{platform}。磁盘上的文件不会被删除。", "cleanup-firmware-queued": "清理任务已排队,缺失的固件将很快被删除", - "cleanup-queued": "清理任务已排队 — 缺失的 ROM 将很快被删除", + "cleanup-queued": "清理任务已排队,缺失的 ROM 将很快被删除", "client-api-tokens": "客户端 API 令牌", "client-token-confirm-delete": "确定要吊销此令牌吗?任何使用它的设备都将失去访问权限。", "client-token-confirm-regenerate": "这会使当前凭据失效。任何使用旧令牌的设备都需要重新配对。", diff --git a/frontend/src/locales/zh_TW/settings.json b/frontend/src/locales/zh_TW/settings.json index 6e41e976f..96771d79b 100644 --- a/frontend/src/locales/zh_TW/settings.json +++ b/frontend/src/locales/zh_TW/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "這將從資料庫中永久刪除檔案已從檔案系統中缺失的所有韌體項目{platform}。磁碟上的檔案不會被刪除。", "cleanup-firmware-queued": "清理任務已排程,缺失的韌體將在稍後被刪除", - "cleanup-queued": "清理任務已排程 — 缺失的 ROM 將在稍後被刪除", + "cleanup-queued": "清理任務已排程,缺失的 ROM 將在稍後被刪除", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/v2/components/Dialogs/DeleteRomDialog.vue b/frontend/src/v2/components/Dialogs/DeleteRomDialog.vue index 5fde135cb..c17f84c37 100644 --- a/frontend/src/v2/components/Dialogs/DeleteRomDialog.vue +++ b/frontend/src/v2/components/Dialogs/DeleteRomDialog.vue @@ -423,7 +423,7 @@ function closeDialog() { } .r-v2-del-rom__append { - padding: 10px 14px 0; + padding: 10px 14px 12px; display: flex; flex-direction: column; gap: 8px; diff --git a/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts b/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts index fc380aee4..c20a8a93a 100644 --- a/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts +++ b/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts @@ -1,30 +1,55 @@ import { flushPromises, mount } from "@vue/test-utils"; +import { AxiosError } from "axios"; import { createPinia, setActivePinia } from "pinia"; import { beforeEach, describe, expect, it, vi } from "vitest"; import storePlatforms from "@/stores/platforms"; import MissingFirmwareSection from "./MissingFirmwareSection.vue"; -const { getFirmware, runTask, getTaskById, confirm } = vi.hoisted(() => ({ - getFirmware: vi.fn(), - runTask: vi.fn(), - getTaskById: vi.fn(), - confirm: vi.fn(), -})); +const { getFirmware, runTask, getTaskById, confirm, snackbarError } = + vi.hoisted(() => ({ + getFirmware: vi.fn(), + runTask: vi.fn(), + getTaskById: vi.fn(), + confirm: vi.fn(), + snackbarError: vi.fn(), + })); vi.mock("@/services/api/firmware", () => ({ default: { getFirmware } })); vi.mock("@/services/api/task", () => ({ default: { runTask, getTaskById } })); +// Error messages keep their `error` parameter so the tests can see what +// reached the snackbar. vi.mock("vue-i18n", () => ({ - useI18n: () => ({ t: (key: string) => key }), + useI18n: () => ({ + t: (key: string, params?: { error?: string }) => + params?.error ? `${key}: ${params.error}` : key, + }), })); vi.mock("@/v2/composables/useConfirm", () => ({ useConfirm: () => confirm, })); vi.mock("@/v2/composables/useSnackbar", () => ({ - useSnackbar: () => ({ success: vi.fn(), error: vi.fn() }), + useSnackbar: () => ({ success: vi.fn(), error: snackbarError }), })); +// The server's reason for a refused request, as axios delivers it. +function serverError(detail: string) { + return new AxiosError( + "Request failed with status code 503", + "ERR_BAD_RESPONSE", + undefined, + undefined, + { + status: 503, + statusText: "Service Unavailable", + data: { detail }, + headers: {}, + config: {} as never, + }, + ); +} + const PS1 = { id: 1, slug: "ps", @@ -96,6 +121,7 @@ describe("MissingFirmwareSection", () => { getTaskById.mockResolvedValue({ data: { status: "finished" } }); confirm.mockReset(); confirm.mockResolvedValue(true); + snackbarError.mockReset(); getFirmware.mockReset(); getFirmware.mockResolvedValue({ data: [firmware(10, PS1.id, "scph5501.bin")], @@ -238,4 +264,27 @@ describe("MissingFirmwareSection", () => { 0, ); }); + + it("tells why the server refused the cleanup", async () => { + runTask.mockRejectedValue(serverError("No task worker is running")); + const wrapper = mountSection(); + await flushPromises(); + + wrapper.findComponent({ name: "RMenuItem" }).vm.$emit("click"); + await flushPromises(); + + expect(snackbarError).toHaveBeenCalledWith( + "settings.couldnt-queue-cleanup: No task worker is running", + ); + }); + + it("tells why the list could not be fetched", async () => { + getFirmware.mockRejectedValue(serverError("Database unavailable")); + mountSection(); + await flushPromises(); + + expect(snackbarError).toHaveBeenCalledWith( + "settings.couldnt-fetch-missing-firmware: Database unavailable", + ); + }); }); diff --git a/frontend/src/v2/components/Settings/MissingFirmwareSection.vue b/frontend/src/v2/components/Settings/MissingFirmwareSection.vue index bf6a2eb5d..3190f452c 100644 --- a/frontend/src/v2/components/Settings/MissingFirmwareSection.vue +++ b/frontend/src/v2/components/Settings/MissingFirmwareSection.vue @@ -15,6 +15,7 @@ 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"; +import { errorMessage } from "@/v2/utils/errorMessage"; defineOptions({ inheritAttrs: false }); @@ -74,7 +75,9 @@ async function fetchMissingFirmware() { ); } catch (err) { snackbar.error( - t("settings.couldnt-fetch-missing-firmware", { error: String(err) }), + t("settings.couldnt-fetch-missing-firmware", { + error: errorMessage(err), + }), ); } finally { loading.value = false; @@ -103,7 +106,9 @@ async function cleanupAll() { snackbar.success(t("settings.cleanup-firmware-queued")); if (await awaitTask(data.task_id)) await fetchMissingFirmware(); } catch (err) { - snackbar.error(t("settings.couldnt-queue-cleanup", { error: String(err) })); + snackbar.error( + t("settings.couldnt-queue-cleanup", { error: errorMessage(err) }), + ); } finally { cleaningUp.value = false; } diff --git a/frontend/src/v2/components/Settings/MissingGamesSection.test.ts b/frontend/src/v2/components/Settings/MissingGamesSection.test.ts index bffb190df..44a7c5c0a 100644 --- a/frontend/src/v2/components/Settings/MissingGamesSection.test.ts +++ b/frontend/src/v2/components/Settings/MissingGamesSection.test.ts @@ -1,4 +1,5 @@ import { flushPromises, mount } from "@vue/test-utils"; +import { AxiosError } from "axios"; import { createPinia, setActivePinia } from "pinia"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { nextTick } from "vue"; @@ -6,26 +7,43 @@ import type { SimpleRom } from "@/stores/roms"; import storeGallerySelection from "@/v2/stores/gallerySelection"; import MissingGamesSection from "./MissingGamesSection.vue"; -const { getRoms } = vi.hoisted(() => ({ getRoms: vi.fn() })); +const { getRoms, runTask, getTaskById, confirm, snackbarError } = vi.hoisted( + () => ({ + getRoms: vi.fn(), + runTask: vi.fn(), + getTaskById: vi.fn(), + confirm: vi.fn(), + snackbarError: vi.fn(), + }), +); vi.mock("@/services/api/rom", () => ({ default: { getRoms } })); vi.mock("@/services/api/task", () => ({ - default: { - runTask: vi.fn().mockResolvedValue({ data: { task_id: "job-1" } }), - getTaskById: vi.fn().mockResolvedValue({ data: { status: "finished" } }), - }, + default: { runTask, getTaskById }, })); +// Error messages keep their `error` parameter so the tests can see what +// reached the snackbar. vi.mock("vue-i18n", () => ({ - useI18n: () => ({ t: (key: string) => key }), + useI18n: () => ({ + t: (key: string, params?: { error?: string }) => + params?.error ? `${key}: ${params.error}` : key, + }), })); vi.mock("@/v2/composables/useConfirm", () => ({ - useConfirm: () => vi.fn().mockResolvedValue(false), + useConfirm: () => confirm, })); vi.mock("@/v2/composables/useSnackbar", () => ({ - useSnackbar: () => ({ success: vi.fn(), error: vi.fn() }), + useSnackbar: () => ({ success: vi.fn(), error: snackbarError }), })); + +// The kebab's items live in RMenu's default slot; the auto-stub drops slot +// content, so render it to reach the cleanup action. +const RMenuStub = { + name: "RMenu", + template: '
', +}; vi.mock("@/v2/composables/useWebpSupport", () => ({ useWebpSupport: () => ({ supportsWebp: { value: true } }), })); @@ -40,7 +58,7 @@ function mountSection() { GameListSkeletonRow: true, RBtn: true, RIcon: true, - RMenu: true, + RMenu: RMenuStub, RMenuItem: true, RSelect: true, RTag: true, @@ -57,6 +75,13 @@ describe("MissingGamesSection", () => { getRoms.mockResolvedValue({ data: { total: 0, items: [], char_index: {}, rom_id_index: [] }, }); + runTask.mockReset(); + runTask.mockResolvedValue({ data: { task_id: "job-1" } }); + getTaskById.mockReset(); + getTaskById.mockResolvedValue({ data: { status: "finished" } }); + confirm.mockReset(); + confirm.mockResolvedValue(false); + snackbarError.mockReset(); }); // The tab renders no filter drawer, no A-Z strip and drives its scroller @@ -91,6 +116,34 @@ describe("MissingGamesSection", () => { expect(params.withRomIdIndex).toBe(false); }); + it("tells why the server refused the cleanup", async () => { + confirm.mockResolvedValue(true); + runTask.mockRejectedValue( + new AxiosError( + "Request failed with status code 503", + "ERR_BAD_RESPONSE", + undefined, + undefined, + { + status: 503, + statusText: "Service Unavailable", + data: { detail: "No task worker is running" }, + headers: {}, + config: {} as never, + }, + ), + ); + const wrapper = mountSection(); + await flushPromises(); + + wrapper.findComponent({ name: "RMenuItem" }).vm.$emit("click"); + await flushPromises(); + + expect(snackbarError).toHaveBeenCalledWith( + "settings.couldnt-queue-cleanup: No task worker is running", + ); + }); + // Rows are selectable here, so the selection needs the same bulk actions // it gets in the gallery rather than none at all (issue #4036). it("raises the gallery's bulk actions once a row is selected", async () => { diff --git a/frontend/src/v2/components/Settings/MissingGamesSection.vue b/frontend/src/v2/components/Settings/MissingGamesSection.vue index 13c24bd37..cc04b90ed 100644 --- a/frontend/src/v2/components/Settings/MissingGamesSection.vue +++ b/frontend/src/v2/components/Settings/MissingGamesSection.vue @@ -48,6 +48,7 @@ import { useTaskCompletion } from "@/v2/composables/useTaskCompletion"; import { useWebpSupport } from "@/v2/composables/useWebpSupport"; import storeGalleryRoms, { NO_SIDECARS } from "@/v2/stores/galleryRoms"; import storeGallerySelection from "@/v2/stores/gallerySelection"; +import { errorMessage } from "@/v2/utils/errorMessage"; interface PlatformItem { id: number; @@ -241,7 +242,9 @@ async function cleanupAll() { await galleryRoms.fetchInitialMetadata(NO_SIDECARS); } } catch (err) { - snackbar.error(t("settings.couldnt-queue-cleanup", { error: String(err) })); + snackbar.error( + t("settings.couldnt-queue-cleanup", { error: errorMessage(err) }), + ); } finally { cleaningUp.value = false; }