mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 10:33:22 +01:00
* feat(converto): integrate rom-converto for title id extraction and download conversion * feat(converto): add conversion settings UI with per-platform format policies * fix(converto): read conversion targets from the backend and translate the settings page * fix(docker): ship rom-converto in the production image Only the dev Dockerfile installed the binary, so the integration could never enable on a released image. Fetch the same pinned, checksummed musl build in a dedicated stage and copy it next to RAHasher. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(converto): skip the update check and batch info calls The CLI asks api.github.com for a newer release on every run unless told not to, so pass --no-update-check on each invocation. Inspect a rom's files in one `info --paths-file` run instead of one subprocess per file, and read the inspectable extensions from the capabilities manifest so scans skip files info cannot recognize. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(scan): keep sigil authoritative for title ids rom-converto ran first and overrode the ids sigil read. Sigil now runs first and records its per-file ids; rom-converto only fills files sigil left unset, on new or changed files, in one batch. Restore the base-id selection for sigil extractions on every platform, as on master. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(downloads): make conversion opt-in and bound the cache The download endpoint returned a converted file to every client once a platform had a target, including the browser player and apps that check hashes against RomFile. Conversion now needs ?converted=true. A pre-warmed copy is served whatever its size; the in-request size cap only gates starting a conversion. ROM_CONVERTO_CACHE_MAX_SIZE_GB (default 20, 0 unbounded) caps the cache: conversions and the pre-warm task stop when it is full, and cleanup evicts the least recently served copies. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * chore(types): regenerate frontend types for the converto schema Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(converto): address code-review findings (pr-ready step 2) - Fall back to rom-converto's stored ids only when it ran this pass, in disc order, so a rescan that skipped extraction keeps sigil's save target - Persist per-file title ids that extraction writes onto reused rows - Only authenticated callers may start an in-request conversion; past a 240s deadline serve the original and let the conversion finish into the cache instead of nginx returning 504 - Treat a probe OSError or timeout as a failed probe; kill the subprocess when the caller is cancelled - Give the pre-warm task the scan timeout and report progress in the ConversionStats shape the task UI reads - Reuse zip_cache constants, walk the cache off the event loop, tolerate files vanishing mid-cleanup, and trim long comments Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(converto): simplify conversion code (pr-ready step 3) - Move the converted-download policy (target lookup, cached-first, sync size cap, deadline) from the endpoint into utils/conversion_cache and share conversion_target with the pre-warm task - Share one path lookup between get_cached_converted and get_or_convert; the pre-warm walks the cache once and tracks a running byte budget instead of walking it twice per rom - One normalize_platform_formats beside TARGETS_BY_PLATFORM for the config loader (via _validated_platform_map) and the settings endpoint; update_converto_settings takes a ConvertoConfig and is written back with dataclasses.asdict - read_infos owns its never-raise contract, so the scan drops its blanket except; drop the unused RomConvertoInfo.kind and error attributes - Sort files for the rom-converto identity only when it is used; stat each cached file once during cleanup Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * chore(converto): trim comments (pr-ready step 4) Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(converto): convert on first download instead of pre-warming A library pre-warm fought the TTL: cleanup dropped every copy nobody downloaded within a day. Remove the Convert library task and convert on demand only. Files over ROM_CONVERTO_MAX_SYNC_SIZE_MB now start their conversion in the background while the original is served, so the next download within the TTL gets the converted copy at any size. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(converto): drop decrypt and encrypt download targets Downloads now only change a rom's container or compression (CHD, RVZ, CSO, NSZ, ...); serving decrypted files is left for a separate decision. NDS and PS3 have no remaining targets. Also note that the conversion concurrency limit applies per process. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(converto): move the cache limits into converto.* cache_max_size_gb and max_sync_size_mb join cache_ttl_hours in config.yml and PUT /api/config/converto_settings, replacing the ROM_CONVERTO_CACHE_MAX_SIZE_GB and ROM_CONVERTO_MAX_SYNC_SIZE_MB env vars, so every eviction knob is edited in one place at runtime. The loader takes its defaults from ConvertoConfig and one table holds each integer's minimum for both the loader and the payload. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(converto): lock conversions with flock instead of a sentinel A conversion now holds a non-blocking flock on its key dir, which the kernel releases if the worker dies. That replaces the .partial sentinel, its 6-hour staleness guess (which a long ROM_CONVERTO_TIMEOUT could outlive), and the rename-aside takeover. Cleanup skips locked dirs, and partial output gets a hidden name so it never counts as a served copy. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * test(converto): parametrize repeated test cases Collapse the per-platform info parsing, operation resolution and converto_active cases into parametrized tests, so a new platform or target is one row. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(scan): run rom-converto first with sigil as the fallback rom-converto reads each rom's new or changed files first, in one batch, and its title ids win. sigil still reads what it can, since it alone provides save targets and Switch content types, and fills the ids rom-converto left unset. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(converto): edit the cache size limits on the settings page * feat(converto): store per-file metadata read by rom-converto during scans * fix(converto): show the labels of the cache settings fields * fix(scan): keep the stored save target when sigil reads nothing * fix(converto): read Xbox 360 disc ids and Wii title versions, store content type as text * feat(converto): save file icons, banners and backgrounds read by rom-converto * chore(converto): bump rom-converto to v0.23.0 * fix(converto): address review findings in the conversion cache, scan metadata and settings * refactor(converto): move per-file metadata out of the conversion PR Scan-time metadata (title ids, the 17 rom_files columns, artwork and converto.scan_metadata) moves to its own PR so its columns land with the UI that reads them. This PR keeps conversion only. The conversion cache no longer has uncompressed_size_bytes to budget with, so a conversion to an uncompressed target reserves a fixed multiple of its input and the cleanup pass after it evicts any overshoot. Co-Authored-By: DevYukine <20647088+DevYukine@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017BuuZVVtVPNLRaCjTN9bgQ * feat(converto): let the client pick the download format with ?format= `?format=zso,iso` lists the formats a client can read. The stored file is served whenever its format is listed, even with conversion off, so most emulator clients never trigger a conversion. Otherwise the first listed format with a cached copy is served, then the first one rom-converto can produce. A conversion that outlasts a short wait answers 202 with Retry-After instead of falling back to the original, so a URL never serves two different files and a client never gets bytes it can't read. 406 means no listed format can be served. HEAD reports the same without starting a conversion. This replaces `?converted=true`, the per-platform download target and `max_sync_size_mb`; `cache_ttl_hours` stays config.yml-only. Co-Authored-By: DevYukine <20647088+DevYukine@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017BuuZVVtVPNLRaCjTN9bgQ * feat(converto): convert the library in place with a manual task `converto.platform_formats` now names the format a platform's library is stored in, and the new "Convert library" task brings every matched rom to it. Each output is staged in a `.romm_tmp_` directory beside the original, moved into place, and only then are the originals (and a cue's tracks) deleted. Single-file roms take the new name, folder roms keep theirs and get their .m3u entries rewritten, and the file rows refresh, so a rom keeps its id, saves and collections. Only lossless conversions qualify, so xbox (xiso trims the dump) has no library format. Unmatched roms are skipped because a converted file no longer hash-matches a DAT. `/api/config` now carries the library targets and, per input extension, the formats a download can be converted to. Co-Authored-By: DevYukine <20647088+DevYukine@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017BuuZVVtVPNLRaCjTN9bgQ * feat(converto): library format settings and "Download as" on the game page The settings page follows the reworked backend: per-platform formats are now the library format the "Convert library" task stores matched games in ("Leave as is" keeps a platform untouched), the scan metadata, cache TTL and max-sync fields are gone, and a "Convert library now" button starts the task behind a typed confirmation, since it deletes the originals. The game's More menu offers "Download as <format>" for a single-file rom when download conversion is on, from the per-extension table `/api/config` exposes. A one-byte ranged GET asks for the format, the UI polls through 202s while it converts, then downloads it; a 406 shows an error. Co-Authored-By: DevYukine <20647088+DevYukine@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017BuuZVVtVPNLRaCjTN9bgQ * fix(converto): address code-review findings (pr-ready step 2) Guard the conversion settings route, add it to the user menu, ignore a non-positive Retry-After, drop duplicate Download as clicks, name the game in the persisted error, and tidy the settings page (display-name sort, useUnloadGuard, decimal cache sizes, save snapshot). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(settings): share the config alerts and save bar (pr-ready step 3) Extract ConfigFileAlerts and SettingsSaveBar from the three settings views that copied them, move ScanSettings onto useUnloadGuard, align the retry slot, and flatten downloadFormats, getDownloadFormats and the format poll loop. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * chore(converto): trim comments (pr-ready step 4) Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat(converto): guard destructive tasks and serve download formats per rom - TaskSpec gains destructive and single_instance. The Tasks list asks for a typed confirmation before a destructive task, and POST /tasks/run answers 409 while a single-instance task is queued or running. - convert_library is both, and only runnable with ROM_CONVERTO_ENABLED. - The heartbeat reports CONVERTO.ENABLED, which hides Conversion settings from the sidebar and user menu and warns on the page. - DetailedRomSchema.download_formats lists what the caller can convert the rom's single file to, resolved by the backend's own operation table and empty for visitors who can't start a conversion. It replaces CONVERTO_DOWNLOAD_FORMATS in /api/config and the frontend's copy of the extension matching. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Yukine <devyukine@gmx.de> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: DevYukine <20647088+DevYukine@users.noreply.github.com>
381 lines
14 KiB
Python
381 lines
14 KiB
Python
"""The catalog of tasks, kept free of task code so scheduling or listing them imports none."""
|
|
|
|
from typing import Any, Final, cast
|
|
|
|
from rq.job import Callback, Job
|
|
from rq.queue import Queue
|
|
from rq.utils import import_attribute
|
|
from rq.worker import Worker
|
|
|
|
from config import (
|
|
AUDIT_LOG_RETENTION_DAYS,
|
|
ENABLE_SCHEDULED_BUILD_RECOMMENDATIONS,
|
|
ENABLE_SCHEDULED_CLEANUP_NETPLAY,
|
|
ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES,
|
|
ENABLE_SCHEDULED_CLEANUP_SYNC_SESSIONS,
|
|
ENABLE_SCHEDULED_CLEANUP_UPLOAD_TMP,
|
|
ENABLE_SCHEDULED_CLEANUP_ZIP_CACHE,
|
|
ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP,
|
|
ENABLE_SCHEDULED_RESCAN,
|
|
ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC,
|
|
ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA,
|
|
ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB,
|
|
ENABLE_SYNC_FOLDER_WATCHER,
|
|
ENABLE_SYNC_PUSH_PULL,
|
|
LAUNCHBOX_API_ENABLED,
|
|
ROM_CONVERTO_ENABLED,
|
|
SCAN_TIMEOUT,
|
|
SCHEDULED_BUILD_RECOMMENDATIONS_CRON,
|
|
SCHEDULED_CLEANUP_NETPLAY_CRON,
|
|
SCHEDULED_CLEANUP_ORPHANED_RESOURCES_CRON,
|
|
SCHEDULED_CLEANUP_SYNC_SESSIONS_CRON,
|
|
SCHEDULED_CLEANUP_UPLOAD_TMP_CRON,
|
|
SCHEDULED_CLEANUP_ZIP_CACHE_CRON,
|
|
SCHEDULED_CONVERT_IMAGES_TO_WEBP_CRON,
|
|
SCHEDULED_RESCAN_CRON,
|
|
SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON,
|
|
SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON,
|
|
SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON,
|
|
SYNC_PUSH_PULL_CRON,
|
|
TASK_TIMEOUT,
|
|
)
|
|
from exceptions.task_exceptions import TaskNotFoundException
|
|
from handler.redis_handler import (
|
|
ALL_QUEUES,
|
|
QUEUES_BY_NAME,
|
|
STREAMING_QUEUE_NAME,
|
|
get_worker_current_job,
|
|
redis_client,
|
|
scan_queue,
|
|
)
|
|
from handler.streaming.config import HOLD_CEILING_SECONDS, streaming_enabled
|
|
from tasks.tasks import Task, TaskSpec, TaskType, run_task_by_name
|
|
|
|
SCAN_LIBRARY_SPEC: Final = TaskSpec(
|
|
implementation="tasks.scheduled.scan_library.scan_library_task",
|
|
title="Scheduled rescan",
|
|
description="Rescans the entire library",
|
|
task_type=TaskType.SCAN,
|
|
enabled=ENABLE_SCHEDULED_RESCAN,
|
|
cron_string=SCHEDULED_RESCAN_CRON,
|
|
# A library scan is not a five-minute task like the rest.
|
|
timeout=SCAN_TIMEOUT,
|
|
)
|
|
|
|
UPDATE_LAUNCHBOX_METADATA_SPEC: Final = TaskSpec(
|
|
implementation="tasks.scheduled.update_launchbox_metadata.update_launchbox_metadata_task",
|
|
title="Scheduled LaunchBox metadata update",
|
|
description="Updates the LaunchBox metadata store",
|
|
task_type=TaskType.UPDATE,
|
|
enabled=ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA,
|
|
cron_string=SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON,
|
|
manual_run=True,
|
|
# The store lives only in the cache, so with LaunchBox on admins must be
|
|
# able to fill it even while the scheduled update is off.
|
|
manual_run_when_disabled=LAUNCHBOX_API_ENABLED,
|
|
# Downloading ~100MB and parsing it takes far longer than an ordinary task.
|
|
timeout=max(TASK_TIMEOUT, 30 * 60),
|
|
)
|
|
|
|
UPDATE_SWITCH_TITLEDB_SPEC: Final = TaskSpec(
|
|
implementation="tasks.scheduled.update_switch_titledb.update_switch_titledb_task",
|
|
title="Scheduled Switch TitleDB update",
|
|
description="Updates the Nintendo Switch TitleDB file",
|
|
task_type=TaskType.UPDATE,
|
|
enabled=ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB,
|
|
cron_string=SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON,
|
|
manual_run=True,
|
|
# The store lives only in the cache, and a rebuild that fails is not queued
|
|
# again, so admins need a way to fill it with the cron off.
|
|
manual_run_when_disabled=True,
|
|
)
|
|
|
|
BUILD_RECOMMENDATIONS_SPEC: Final = TaskSpec(
|
|
implementation="tasks.scheduled.build_recommendations.build_recommendations_task",
|
|
title="Build recommendations index",
|
|
description=(
|
|
"Rebuilds the similar-games index from library metadata, "
|
|
"play history and collections"
|
|
),
|
|
task_type=TaskType.UPDATE,
|
|
enabled=ENABLE_SCHEDULED_BUILD_RECOMMENDATIONS,
|
|
manual_run=True,
|
|
cron_string=SCHEDULED_BUILD_RECOMMENDATIONS_CRON,
|
|
)
|
|
|
|
CONVERT_IMAGES_TO_WEBP_SPEC: Final = TaskSpec(
|
|
implementation="tasks.scheduled.convert_images_to_webp.convert_images_to_webp_task",
|
|
title="Convert images to WebP",
|
|
description="Convert existing image files (PNG, JPG, BMP, TIFF, GIF) to WebP format for better performance",
|
|
task_type=TaskType.CONVERSION,
|
|
enabled=ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP,
|
|
manual_run=True,
|
|
cron_string=SCHEDULED_CONVERT_IMAGES_TO_WEBP_CRON,
|
|
)
|
|
|
|
CLEANUP_ZIP_CACHE_SPEC: Final = TaskSpec(
|
|
implementation="tasks.scheduled.cleanup_zip_cache.cleanup_zip_cache_task",
|
|
title="Scheduled ZIP cache cleanup",
|
|
description="Removes stale cached ZIP files based on tiered TTL",
|
|
task_type=TaskType.CLEANUP,
|
|
enabled=ENABLE_SCHEDULED_CLEANUP_ZIP_CACHE,
|
|
cron_string=SCHEDULED_CLEANUP_ZIP_CACHE_CRON,
|
|
)
|
|
|
|
CLEANUP_CONVERSION_CACHE_SPEC: Final = TaskSpec(
|
|
implementation="tasks.scheduled.cleanup_conversion_cache.cleanup_conversion_cache_task",
|
|
title="Scheduled conversion cache cleanup",
|
|
description="Removes stale converted download files based on TTL",
|
|
task_type=TaskType.CLEANUP,
|
|
enabled=True,
|
|
cron_string="0 4 * * *",
|
|
)
|
|
|
|
CLEANUP_ORPHANED_RESOURCES_SPEC: Final = TaskSpec(
|
|
implementation="tasks.scheduled.cleanup_orphaned_resources.cleanup_orphaned_resources_task",
|
|
title="Cleanup orphaned resources",
|
|
description="Clean up orphaned resources in the ROMs directory",
|
|
task_type=TaskType.CLEANUP,
|
|
enabled=ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES,
|
|
manual_run=True,
|
|
cron_string=SCHEDULED_CLEANUP_ORPHANED_RESOURCES_CRON,
|
|
)
|
|
|
|
CLEANUP_NETPLAY_SPEC: Final = TaskSpec(
|
|
implementation="tasks.scheduled.cleanup_netplay.cleanup_netplay_task",
|
|
title="Scheduled netplay cleanup",
|
|
description="Cleans up empty netplay rooms",
|
|
task_type=TaskType.CLEANUP,
|
|
enabled=ENABLE_SCHEDULED_CLEANUP_NETPLAY,
|
|
cron_string=SCHEDULED_CLEANUP_NETPLAY_CRON,
|
|
)
|
|
|
|
CLEANUP_UPLOAD_TMP_SPEC: Final = TaskSpec(
|
|
implementation="tasks.scheduled.cleanup_upload_tmp.cleanup_upload_tmp_task",
|
|
title="Scheduled upload tmp cleanup",
|
|
description="Cleans up orphaned chunked-upload temp directories",
|
|
task_type=TaskType.CLEANUP,
|
|
enabled=ENABLE_SCHEDULED_CLEANUP_UPLOAD_TMP,
|
|
cron_string=SCHEDULED_CLEANUP_UPLOAD_TMP_CRON,
|
|
)
|
|
|
|
REAP_STREAMING_SESSIONS_SPEC: Final = TaskSpec(
|
|
implementation="tasks.scheduled.reap_streaming_sessions.reap_streaming_sessions_task",
|
|
title="Scheduled streaming session reaper",
|
|
description="Stops streaming sessions whose player stopped sending heartbeats",
|
|
task_type=TaskType.CLEANUP,
|
|
# Read once, as cron registers only enabled tasks when it starts.
|
|
enabled=streaming_enabled(),
|
|
cron_string="* * * * *", # Every minute
|
|
# RQ kills a job at its timeout, so it has to cover a teardown holding its
|
|
# marker to the ceiling.
|
|
timeout=HOLD_CEILING_SECONDS,
|
|
result_ttl=0,
|
|
queue_name=STREAMING_QUEUE_NAME,
|
|
)
|
|
|
|
CLEANUP_SYNC_SESSIONS_SPEC: Final = TaskSpec(
|
|
implementation="tasks.scheduled.cleanup_sync_sessions.cleanup_sync_sessions_task",
|
|
title="Scheduled sync session cleanup",
|
|
description="Fails sync sessions no client ever completed",
|
|
task_type=TaskType.CLEANUP,
|
|
enabled=ENABLE_SCHEDULED_CLEANUP_SYNC_SESSIONS,
|
|
cron_string=SCHEDULED_CLEANUP_SYNC_SESSIONS_CRON,
|
|
)
|
|
|
|
CLEANUP_AUDIT_LOG_SPEC: Final = TaskSpec(
|
|
implementation="tasks.scheduled.cleanup_audit_log.cleanup_audit_log_task",
|
|
title="Scheduled audit log cleanup",
|
|
description=f"Removes audit log events older than {AUDIT_LOG_RETENTION_DAYS} days",
|
|
task_type=TaskType.CLEANUP,
|
|
enabled=AUDIT_LOG_RETENTION_DAYS > 0,
|
|
cron_string="30 4 * * *",
|
|
)
|
|
|
|
SYNC_RETROACHIEVEMENTS_PROGRESS_SPEC: Final = TaskSpec(
|
|
implementation="tasks.scheduled.sync_retroachievements_progress.sync_retroachievements_progress_task",
|
|
title="Scheduled RetroAchievements progress sync",
|
|
description="Updates RetroAchievements progress for all users",
|
|
task_type=TaskType.UPDATE,
|
|
enabled=ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC,
|
|
cron_string=SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON,
|
|
)
|
|
|
|
SYNC_PUSH_PULL_SPEC: Final = TaskSpec(
|
|
implementation="tasks.sync_push_pull_task.sync_push_pull_task",
|
|
title="Push-Pull Sync",
|
|
description="Sync saves with devices via SSH/SFTP",
|
|
task_type=TaskType.SYNC,
|
|
enabled=ENABLE_SYNC_PUSH_PULL,
|
|
cron_string=SYNC_PUSH_PULL_CRON,
|
|
)
|
|
|
|
CLEANUP_MISSING_ROMS_SPEC: Final = TaskSpec(
|
|
implementation="tasks.manual.cleanup_missing_roms.cleanup_missing_roms_task",
|
|
title="Cleanup missing ROMs",
|
|
description="Delete all ROMs flagged as missing from the filesystem from the database",
|
|
task_type=TaskType.CLEANUP,
|
|
enabled=True,
|
|
manual_run=True,
|
|
)
|
|
|
|
CLEANUP_MISSING_FIRMWARE_SPEC: Final = TaskSpec(
|
|
implementation="tasks.manual.cleanup_missing_firmware.cleanup_missing_firmware_task",
|
|
title="Cleanup missing firmware",
|
|
description="Delete all firmware flagged as missing from the filesystem from the database",
|
|
task_type=TaskType.CLEANUP,
|
|
enabled=True,
|
|
manual_run=True,
|
|
)
|
|
|
|
SYNC_FOLDER_SCAN_SPEC: Final = TaskSpec(
|
|
implementation="tasks.manual.sync_folder_scan.sync_folder_scan_task",
|
|
title="Sync Folder Scan",
|
|
description="Scan device sync folders for new save files",
|
|
task_type=TaskType.SYNC,
|
|
enabled=ENABLE_SYNC_FOLDER_WATCHER,
|
|
manual_run=True,
|
|
)
|
|
|
|
RECOMPUTE_SAVE_CONTENT_HASHES_SPEC: Final = TaskSpec(
|
|
implementation="tasks.manual.recompute_save_content_hashes.recompute_save_content_hashes_task",
|
|
title="Recompute save content hashes",
|
|
description=(
|
|
"Re-scan every save row and rewrite content_hash with the "
|
|
"current compute_content_hash algorithm. One-time recovery "
|
|
"after the zip-hash dispatch fix."
|
|
),
|
|
task_type=TaskType.CLEANUP,
|
|
enabled=True,
|
|
manual_run=True,
|
|
)
|
|
|
|
CONVERT_LIBRARY_SPEC: Final = TaskSpec(
|
|
implementation="tasks.manual.convert_library.convert_library_task",
|
|
title="Convert library",
|
|
description=(
|
|
"Convert each matched ROM to its platform's library format, "
|
|
"replacing the original files"
|
|
),
|
|
task_type=TaskType.CONVERSION,
|
|
enabled=ROM_CONVERTO_ENABLED,
|
|
manual_run=True,
|
|
destructive=True,
|
|
single_instance=True,
|
|
# One conversion after another, each up to ROM_CONVERTO_TIMEOUT.
|
|
timeout=SCAN_TIMEOUT,
|
|
)
|
|
|
|
# The keys are the names the API and the cron schedule address a task by, and
|
|
# they end up in the job payload, so they outlive any given release. Every task
|
|
# that runs on a schedule belongs here; which of them the API surfaces is the
|
|
# endpoint's business.
|
|
SCHEDULED_TASKS: Final[dict[str, TaskSpec]] = {
|
|
"scan_library": SCAN_LIBRARY_SPEC,
|
|
"update_launchbox_metadata": UPDATE_LAUNCHBOX_METADATA_SPEC,
|
|
"update_switch_titledb": UPDATE_SWITCH_TITLEDB_SPEC,
|
|
"build_recommendations": BUILD_RECOMMENDATIONS_SPEC,
|
|
"convert_images_to_webp": CONVERT_IMAGES_TO_WEBP_SPEC,
|
|
"cleanup_zip_cache": CLEANUP_ZIP_CACHE_SPEC,
|
|
"cleanup_conversion_cache": CLEANUP_CONVERSION_CACHE_SPEC,
|
|
"cleanup_orphaned_resources": CLEANUP_ORPHANED_RESOURCES_SPEC,
|
|
"cleanup_netplay": CLEANUP_NETPLAY_SPEC,
|
|
"cleanup_upload_tmp": CLEANUP_UPLOAD_TMP_SPEC,
|
|
"reap_streaming_sessions": REAP_STREAMING_SESSIONS_SPEC,
|
|
"cleanup_sync_sessions": CLEANUP_SYNC_SESSIONS_SPEC,
|
|
"cleanup_audit_log": CLEANUP_AUDIT_LOG_SPEC,
|
|
"sync_retroachievements_progress": SYNC_RETROACHIEVEMENTS_PROGRESS_SPEC,
|
|
"sync_push_pull": SYNC_PUSH_PULL_SPEC,
|
|
}
|
|
|
|
MANUAL_TASKS: Final[dict[str, TaskSpec]] = {
|
|
"cleanup_missing_roms": CLEANUP_MISSING_ROMS_SPEC,
|
|
"cleanup_missing_firmware": CLEANUP_MISSING_FIRMWARE_SPEC,
|
|
"sync_folder_scan": SYNC_FOLDER_SCAN_SPEC,
|
|
"recompute_save_content_hashes": RECOMPUTE_SAVE_CONTENT_HASHES_SPEC,
|
|
"convert_library": CONVERT_LIBRARY_SPEC,
|
|
}
|
|
|
|
|
|
def get_task_spec(name: str) -> TaskSpec | None:
|
|
"""Look up what is known of a task by the name it is addressed by."""
|
|
return SCHEDULED_TASKS.get(name) or MANUAL_TASKS.get(name)
|
|
|
|
|
|
def get_task(name: str) -> Task | None:
|
|
"""Import the task registered under ``name``, the first call loading its module."""
|
|
spec = get_task_spec(name)
|
|
if spec is None:
|
|
return None
|
|
return cast(Task, import_attribute(spec.implementation))
|
|
|
|
|
|
def enqueue_task(
|
|
name: str,
|
|
*,
|
|
queue: Queue | None = None,
|
|
task_kwargs: dict[str, Any] | None = None,
|
|
run_by_user_id: int | None = None,
|
|
**job_options: Any,
|
|
) -> Job:
|
|
"""Enqueue a registered task by name.
|
|
|
|
Args:
|
|
name: The key the task is registered under.
|
|
queue: Which queue to enqueue on, the one the spec names by default.
|
|
task_kwargs: Forwarded to the task's ``run``, nested so that they cannot
|
|
collide with the name of the task to run.
|
|
run_by_user_id: Who ran it by hand, notified when it ends.
|
|
job_options: Passed through to RQ, for a fixed job id and the like.
|
|
|
|
Returns:
|
|
The enqueued job.
|
|
"""
|
|
spec = get_task_spec(name)
|
|
if spec is None:
|
|
raise TaskNotFoundException(name)
|
|
|
|
queue = queue or QUEUES_BY_NAME[spec.queue_name]
|
|
return queue.enqueue(
|
|
run_task_by_name,
|
|
kwargs={
|
|
"name": name,
|
|
"task_kwargs": task_kwargs or {},
|
|
"run_by_user_id": run_by_user_id,
|
|
},
|
|
job_timeout=spec.timeout,
|
|
result_ttl=spec.result_ttl,
|
|
meta=spec.job_meta(name),
|
|
**job_options,
|
|
)
|
|
|
|
|
|
def get_active_task_job(name: str) -> Job | None:
|
|
"""A job of the task registered as `name` that a worker holds or a queue waits on."""
|
|
for worker in Worker.all(connection=redis_client):
|
|
job = get_worker_current_job(worker)
|
|
if job is not None and job.meta.get("task_key") == name:
|
|
return job
|
|
for queue in ALL_QUEUES:
|
|
for job in queue.get_jobs():
|
|
if job.meta.get("task_key") == name:
|
|
return job
|
|
return None
|
|
|
|
|
|
def enqueue_scheduled_scan(name: str) -> str:
|
|
"""Put a scheduled scan on the scan queue with the abandoned-job callback.
|
|
|
|
Cron can attach no `on_failure`, so a scan it enqueues itself is the one
|
|
scan whose worker can die without anything telling the clients.
|
|
|
|
Args:
|
|
name: The key the scan task is registered under.
|
|
|
|
Returns:
|
|
The id of the enqueued scan job.
|
|
"""
|
|
# By path, so the dispatch job doesn't load the scan stack to reference it.
|
|
on_failure = Callback("endpoints.sockets.scan.report_scan_failure")
|
|
return enqueue_task(name, queue=scan_queue, on_failure=on_failure).id
|