Files
romm/backend/startup.py
Georges-Antoine Assi ec1684d2af perf(metadata): serve the metadata dumps and fixtures from SQLite files (#5844)
* perf(metadata): serve the metadata dumps and fixtures from SQLite files

The LaunchBox and Switch TitleDB stores sat in valkey, which keeps every
byte resident: about 300MB on an instance with both imported, against
roughly 1MB for an empty server. Every read is an exact-key lookup and
nothing writes between imports, so they now live in read-only SQLite
files under RESOURCES_BASE_PATH/metadata, where the OS page cache holds
only the pages lookups touch.

A build writes a temporary file and renames it over the previous one,
so readers see the old store or the new one and never a partial import.
That replaces the initial-import flag and the schema stamp: the store
revision is part of the file name. A failed import keeps serving the
previous file.

The startup fixture indexes (MAME, ScummVM, Sony serials, known BIOS)
no longer get copied into valkey on every boot. They build on first use
into a file under the cache path, named after a hash of the JSON.

Startup deletes the old valkey keys and any file of an older revision,
and queues a rebuild when a store had data, so an upgrade refills
LaunchBox and TitleDB on its own. nginx returns 404 for the metadata
folder, since /assets/romm/resources is otherwise served without auth.

Measured against the real dumps: LaunchBox builds in 22s into 263MB on
disk, TitleDB in 1.2s into 54MB, the fixtures in 0.2s into 8MB. A hit
costs 10-23us including decompression, a miss about 7us.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: code-review

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: simplify

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: review-polish

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: prose

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: prose (code-review fixes)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep the previous metadata store when a dump comes out empty

A LaunchBox or TitleDB build that writes no rows to its main table now
fails with EmptyDumpError instead of swapping an empty store over a
populated one.

Each store keeps one connection per process behind a lock instead of one
per thread. A build closes it once it swaps the file in, and any other
process closes its own on its next lookup, so a replaced file's disk
space is released instead of held by idle threads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Address Greptile review: trim DumpStore comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Restore valkey's own snapshot policy by default

The hourly default (48259b3a9, #3980) kept valkey from rewriting the
hundreds of MB of LaunchBox and TitleDB data it held. With those moved to
SQLite files, a snapshot holds only sessions, queues and query caches, so
an unset REDIS_SAVE_POLICY now leaves valkey's stock policy in place and
loses less on a crash. An empty value still disables snapshots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 08:49:15 -05:00

302 lines
9.8 KiB
Python

"""Startup script to run tasks before the main application is started."""
import asyncio
from typing import Final, NamedTuple, 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.dump_store import DumpStore
from handler.fixture_store import fixture_store
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.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.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)
# Cache keys earlier releases kept the metadata stores under.
LEGACY_LAUNCHBOX_CACHE_KEYS: Final = (
"romm:launchbox_platforms",
"romm:launchbox_metadata_database_id",
"romm:launchbox_metadata_name",
"romm:launchbox_metadata_alternate_name",
"romm:launchbox_metadata_folded_name",
"romm:launchbox_metadata_image",
"romm:launchbox_mame",
"romm:launchbox_files",
"romm:launchbox_metadata_schema",
"romm:launchbox_metadata_initial_import",
)
LEGACY_SWITCH_TITLEDB_CACHE_KEYS: Final = (
"romm:switch_titledb",
"romm:switch_product_id",
"romm:switch_titledb_schema",
)
LEGACY_FIXTURE_CACHE_KEYS: Final = tuple(
f"romm:{name}{suffix}"
for name in (
"mame_xml",
"scummvm_index",
"ps2_opl_index",
"ps1_serial_index",
"ps2_serial_index",
"psp_serial_index",
"known_bios_files",
)
for suffix in ("", ":file_hash")
)
class MetadataDumpStore(NamedTuple):
store: DumpStore
legacy_keys: tuple[str, ...]
task_name: str
job_id: str
# A provider that is off reclaims its store without queueing a download
# nothing would read.
rebuild: bool
METADATA_DUMP_STORES: Final[tuple[MetadataDumpStore, ...]] = (
MetadataDumpStore(
LAUNCHBOX_METADATA_STORE,
LEGACY_LAUNCHBOX_CACHE_KEYS,
"update_launchbox_metadata",
UPDATE_LAUNCHBOX_METADATA_JOB_ID,
LAUNCHBOX_API_ENABLED,
),
MetadataDumpStore(
SWITCH_TITLEDB_STORE,
LEGACY_SWITCH_TITLEDB_CACHE_KEYS,
"update_switch_titledb",
UPDATE_SWITCH_TITLEDB_JOB_ID,
True,
),
)
async def _rebuild_outdated_metadata_stores() -> None:
"""Drop what an older release left of the metadata stores and queue a rebuild."""
await async_cache.unlink(*LEGACY_FIXTURE_CACHE_KEYS)
for store, legacy_keys, task_name, job_id, rebuild in METADATA_DUMP_STORES:
dropped_legacy = bool(await async_cache.unlink(*legacy_keys))
dropped_files = store.drop_other_revisions()
if not (dropped_legacy or dropped_files):
continue
log.info(f"Dropped the {task_name} store left by an older release")
if rebuild and not store.exists():
_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")
try:
fixture_store()
except Exception:
log.exception("Failed to build the fixture store")
log.info("Startup tasks completed")
if __name__ == "__main__":
init_sentry()
asyncio.run(main())