mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
* feat(config): warn about platform bindings to unknown slugs A config.yml binding whose value is neither a platform slug nor a folder alias (a typo such as `snes-test: snse`) silently made a custom platform with no metadata. Nothing pointed at the binding: the scan only logged "Platform snse not identified", like any unknown folder. Startup and the platform scan now log a warning that names the system.platforms or system.versions key, the bound value and the closest known slugs. Unbound folders are not checked, so custom platforms stay quiet. Closes #5464 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(config): treat IGDB version slugs as known bindings (pr-ready: code-review) Bindings to IGDB platform-version slugs such as amiga-a-1200 are identified by the scan, so they no longer warn. Startup reuses the config that migrate_retired_filesystem_keys just loaded. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(config): share the binding lookup with resolve_platform_slug (pr-ready: simplify) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(config): tighten binding warning docstrings and test typing (pr-ready: review-polish) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
288 lines
9.6 KiB
Python
288 lines
9.6 KiB
Python
"""Startup script to run tasks before the main application is started."""
|
|
|
|
import asyncio
|
|
from typing import cast
|
|
|
|
from opentelemetry import trace
|
|
from rq.exceptions import DuplicateJobError, NoSuchJobError
|
|
from rq.job import Job, JobStatus
|
|
from rq.utils import as_text
|
|
|
|
from config import (
|
|
ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP,
|
|
LAUNCHBOX_API_ENABLED,
|
|
SMTP_HOST,
|
|
SMTP_SECURITY,
|
|
SMTP_SECURITY_MODES,
|
|
)
|
|
from config.config_manager import config_manager as cm
|
|
from handler.database import db_save_handler
|
|
from handler.metadata.base_handler import (
|
|
MAME_XML_KEY,
|
|
METADATA_FIXTURES_DIR,
|
|
PS1_SERIAL_INDEX_KEY,
|
|
PS2_OPL_KEY,
|
|
PS2_SERIAL_INDEX_KEY,
|
|
PSP_SERIAL_INDEX_KEY,
|
|
SCUMMVM_INDEX_KEY,
|
|
)
|
|
from handler.metadata.launchbox_handler.types import LAUNCHBOX_METADATA_STORE
|
|
from handler.redis_handler import (
|
|
async_cache,
|
|
default_queue,
|
|
high_prio_queue,
|
|
low_prio_queue,
|
|
redis_client,
|
|
)
|
|
from handler.scan_jobs import drop_stale_scheduled_scans
|
|
from logger.logger import log
|
|
from models.firmware import KNOWN_BIOS_FILE, KNOWN_BIOS_KEY
|
|
from models.rom import sort_articles
|
|
from tasks.manual.recompute_name_sort_keys import (
|
|
applied_sort_articles,
|
|
articles_digest,
|
|
)
|
|
from tasks.registry import enqueue_task
|
|
from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_STORE
|
|
from utils.cache import conditionally_set_cache, drop_stale_cache_store
|
|
from utils.context import initialize_context
|
|
from utils.platform_aliases import unknown_binding_warnings
|
|
from utils.sentry import init_sentry
|
|
|
|
tracer = trace.get_tracer(__name__)
|
|
|
|
RECOMPUTE_SAVE_HASHES_JOB_ID = "recompute_save_content_hashes_bootstrap"
|
|
RECOMPUTE_NAME_SORT_KEYS_JOB_ID = "recompute_name_sort_keys_bootstrap"
|
|
CONVERT_IMAGES_TO_WEBP_JOB_ID = "convert_images_to_webp_bootstrap"
|
|
UPDATE_LAUNCHBOX_METADATA_JOB_ID = "update_launchbox_metadata_bootstrap"
|
|
UPDATE_SWITCH_TITLEDB_JOB_ID = "update_switch_titledb_bootstrap"
|
|
|
|
|
|
def _enqueue_backfill(task_name: str, job_id: str) -> None:
|
|
"""Hand a backfill to the low-priority worker and move on.
|
|
|
|
A fixed id with unique=True settles it in one round trip, so two instances
|
|
starting together cannot both get past the check.
|
|
"""
|
|
try:
|
|
enqueue_task(task_name, job_id=job_id, unique=True)
|
|
log.info(f"Enqueued {task_name} on the low-priority worker")
|
|
except DuplicateJobError:
|
|
log.info(
|
|
f"{task_name} already queued or running from a previous restart; "
|
|
"skipping enqueue"
|
|
)
|
|
except Exception:
|
|
log.exception(f"Failed to enqueue {task_name}; admins can run it manually")
|
|
|
|
|
|
def _enqueue_recompute_save_hashes_if_needed() -> None:
|
|
"""Backfill content_hash for saves uploaded before the path-resolution fix."""
|
|
try:
|
|
missing = db_save_handler.count_saves_missing_content_hash()
|
|
except Exception:
|
|
log.exception(
|
|
"Failed to count saves with NULL content_hash; skipping auto-enqueue "
|
|
"of recompute_save_content_hashes (admins can run it manually)"
|
|
)
|
|
return
|
|
|
|
if missing == 0:
|
|
log.debug("All saves have content_hash; skipping recompute auto-enqueue")
|
|
return
|
|
|
|
log.info(f"{missing} save(s) still have a NULL content_hash")
|
|
_enqueue_backfill("recompute_save_content_hashes", RECOMPUTE_SAVE_HASHES_JOB_ID)
|
|
|
|
|
|
TERMINAL_JOB_STATUSES = frozenset(
|
|
{JobStatus.FINISHED, JobStatus.FAILED, JobStatus.STOPPED, JobStatus.CANCELED}
|
|
)
|
|
|
|
|
|
def _free_finished_job_id(job_id: str) -> None:
|
|
"""Delete a job that has stopped running, so its id can be enqueued again."""
|
|
try:
|
|
job = Job.fetch(job_id, connection=redis_client)
|
|
except NoSuchJobError:
|
|
return
|
|
if job.get_status() in TERMINAL_JOB_STATUSES:
|
|
job.delete()
|
|
|
|
|
|
def _enqueue_recompute_name_sort_keys_if_needed() -> None:
|
|
"""Re-derive sort keys when `sorting.articles` differs from the stored keys'."""
|
|
try:
|
|
articles = sort_articles()
|
|
outdated = applied_sort_articles() != articles
|
|
except Exception:
|
|
log.exception("Failed to compare the sort articles; skipping the recompute")
|
|
return
|
|
|
|
if outdated:
|
|
# Keyed by the list; a queued or running job for it still blocks a duplicate.
|
|
job_id = f"{RECOMPUTE_NAME_SORT_KEYS_JOB_ID}_{articles_digest(articles)}"
|
|
try:
|
|
_free_finished_job_id(job_id)
|
|
except Exception:
|
|
log.exception(f"Failed to check {job_id}; enqueueing anyway")
|
|
_enqueue_backfill("recompute_name_sort_keys", job_id)
|
|
|
|
|
|
def _enqueue_convert_images_to_webp() -> None:
|
|
"""Backfill .webp covers when WebP conversion is enabled.
|
|
|
|
The frontend rewrites cover URLs to .webp as soon as the flag is on, so
|
|
without this every cover fetched before it 404s until the next cron run.
|
|
"""
|
|
_enqueue_backfill("convert_images_to_webp", CONVERT_IMAGES_TO_WEBP_JOB_ID)
|
|
|
|
|
|
# A provider that is off reclaims its store's memory without queueing a
|
|
# download nothing would read.
|
|
VERSIONED_METADATA_STORES = (
|
|
(
|
|
LAUNCHBOX_METADATA_STORE,
|
|
"update_launchbox_metadata",
|
|
UPDATE_LAUNCHBOX_METADATA_JOB_ID,
|
|
LAUNCHBOX_API_ENABLED,
|
|
),
|
|
(
|
|
SWITCH_TITLEDB_STORE,
|
|
"update_switch_titledb",
|
|
UPDATE_SWITCH_TITLEDB_JOB_ID,
|
|
True,
|
|
),
|
|
)
|
|
|
|
|
|
async def _rebuild_outdated_metadata_stores() -> None:
|
|
"""Drop the metadata stores an older release wrote and queue their rebuild."""
|
|
for store, task_name, job_id, rebuild in VERSIONED_METADATA_STORES:
|
|
if not await drop_stale_cache_store(async_cache, store):
|
|
continue
|
|
|
|
log.info(f"Dropped the {task_name} store left by an older release")
|
|
if rebuild:
|
|
_enqueue_backfill(task_name, job_id)
|
|
|
|
|
|
# Keys the rq-scheduler process left behind, now owned by the cron config.
|
|
LEGACY_SCHEDULED_JOBS_KEY = "rq:scheduler:scheduled_jobs"
|
|
LEGACY_SCHEDULER_KEYS = (
|
|
LEGACY_SCHEDULED_JOBS_KEY,
|
|
"rq:scheduler_lock",
|
|
"rq:scheduler",
|
|
)
|
|
|
|
|
|
def _drop_legacy_scheduler_state() -> None:
|
|
"""Clear what the old scheduler left in Redis, jobs included."""
|
|
try:
|
|
legacy_job_ids = {
|
|
as_text(job_id)
|
|
for job_id in cast(
|
|
list[bytes], redis_client.zrange(LEGACY_SCHEDULED_JOBS_KEY, 0, -1)
|
|
)
|
|
}
|
|
|
|
if legacy_job_ids:
|
|
# A cron job the old scheduler had already queued lives in both
|
|
# places, and it still has to run, so only the orphans are deleted.
|
|
queued: set[str] = set()
|
|
for queue in (high_prio_queue, default_queue, low_prio_queue):
|
|
queued.update(queue.get_job_ids())
|
|
|
|
orphans = legacy_job_ids - queued
|
|
if orphans:
|
|
redis_client.delete(*(Job.key_for(job_id) for job_id in orphans))
|
|
|
|
log.info(f"Cleared {len(orphans)} job(s) left behind by the old scheduler")
|
|
|
|
# The registry, the lock and the scheduler's own keys go regardless: an
|
|
# old scheduler that never held a job still registered itself.
|
|
instance_keys = list(
|
|
redis_client.scan_iter("rq:scheduler_instance:*", count=1000)
|
|
)
|
|
redis_client.delete(*LEGACY_SCHEDULER_KEYS, *instance_keys)
|
|
except Exception:
|
|
log.exception("Failed to clear the old scheduler's leftovers")
|
|
|
|
|
|
def _warn_about_unknown_platform_bindings() -> None:
|
|
for warning in unknown_binding_warnings(cm.config):
|
|
log.warning(warning)
|
|
|
|
|
|
@tracer.start_as_current_span("main")
|
|
async def main() -> None:
|
|
"""Run startup tasks."""
|
|
|
|
async with initialize_context():
|
|
log.info("Running startup tasks")
|
|
|
|
cm.migrate_retired_filesystem_keys()
|
|
cm.check_library_layout()
|
|
_warn_about_unknown_platform_bindings()
|
|
|
|
if SMTP_HOST and SMTP_SECURITY not in SMTP_SECURITY_MODES:
|
|
log.warning(
|
|
f"Email is off: SMTP_SECURITY is {SMTP_SECURITY!r}, not one of "
|
|
+ ", ".join(SMTP_SECURITY_MODES)
|
|
)
|
|
|
|
try:
|
|
drop_stale_scheduled_scans()
|
|
except Exception:
|
|
log.exception("Failed to check for stale scheduled scans")
|
|
|
|
_drop_legacy_scheduler_state()
|
|
|
|
if ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP:
|
|
_enqueue_convert_images_to_webp()
|
|
|
|
_enqueue_recompute_save_hashes_if_needed()
|
|
_enqueue_recompute_name_sort_keys_if_needed()
|
|
|
|
try:
|
|
await _rebuild_outdated_metadata_stores()
|
|
except Exception:
|
|
log.exception("Failed to check the metadata stores for an older shape")
|
|
|
|
log.info("Initializing cache with fixtures data")
|
|
await conditionally_set_cache(
|
|
async_cache, MAME_XML_KEY, METADATA_FIXTURES_DIR / "mame_index.json"
|
|
)
|
|
await conditionally_set_cache(
|
|
async_cache,
|
|
SCUMMVM_INDEX_KEY,
|
|
METADATA_FIXTURES_DIR / "scummvm_index.json",
|
|
)
|
|
await conditionally_set_cache(
|
|
async_cache, PS2_OPL_KEY, METADATA_FIXTURES_DIR / "ps2_opl_index.json"
|
|
)
|
|
await conditionally_set_cache(
|
|
async_cache,
|
|
PS1_SERIAL_INDEX_KEY,
|
|
METADATA_FIXTURES_DIR / "ps1_serial_index.json",
|
|
)
|
|
await conditionally_set_cache(
|
|
async_cache,
|
|
PS2_SERIAL_INDEX_KEY,
|
|
METADATA_FIXTURES_DIR / "ps2_serial_index.json",
|
|
)
|
|
await conditionally_set_cache(
|
|
async_cache,
|
|
PSP_SERIAL_INDEX_KEY,
|
|
METADATA_FIXTURES_DIR / "psp_serial_index.json",
|
|
)
|
|
await conditionally_set_cache(async_cache, KNOWN_BIOS_KEY, KNOWN_BIOS_FILE)
|
|
|
|
log.info("Startup tasks completed")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
init_sentry()
|
|
|
|
asyncio.run(main())
|