Files
romm/backend/utils/__init__.py
Stu Anderson 355ce188a4 perf(rq): Save 70MB+ RAM; keep SQLAlchemy out of RQ workers, cron processes (#5736)
* perf(rq): keep SQLAlchemy out of the RQ worker and cron processes

The RQ worker parents and rq cron imported SQLAlchemy and the ORM models at
start-up, through config/__init__.py (safe_* helpers in utils.database) and
config_manager (sqlalchemy.URL and the rom-converto adapter). None of them
query the database themselves; each job's work horse loads what it needs.

- Move safe_int, safe_str_to_bool and get_nested from utils.database to utils.
- Import sqlalchemy.URL inside get_db_engine.
- Import the rom-converto normalizer only when converto.platform_formats is set.
- Add a test that tasks.cron_config and handler.rq_worker start without
  loading SQLAlchemy.
- Run a killed work horse's failure callback and exception handlers in a
  short-lived child, so the job code they import never stays in the parent.

Measured on the production image: idle PSS of rq_worker, rq_scan_worker and
rq_cron fell by 98 MB in total.

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

* perf(rq): move to constants file, tests prevent huge imports

* perf(rq) revert forked failure report.

* 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: plain-prose

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

* refactor(db): build the database URL in utils.database

ConfigManager.get_db_engine becomes utils.database.get_db_url, so
config_manager no longer needs SQLAlchemy at all and the function-local
import goes away. Every caller already loads SQLAlchemy.

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

* fix(roms): clear a match id that is not a number instead of storing 0

safe_int_or_none fell back to safe_int's default of 0, so sgdb_id,
hasheous_id and tgdb_id (which have no refetch to reset them) were saved
as 0. Use utils.int_or_none instead.

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

* docs(models): describe where each shared column limit is used

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>
2026-11-28 12:08:54 -05:00

93 lines
2.8 KiB
Python

import re
import subprocess # trunk-ignore(bandit/B404): only used by get_git_branch, argv is hardcoded
import uuid
from functools import lru_cache
from pathlib import Path
from typing import Any, Final
from __version__ import __version__
# Embedded straight into a YouTube URL, so anything outside this must be dropped.
YOUTUBE_ID_RE: Final = re.compile(r"[A-Za-z0-9_-]{11}")
_REPO_ROOT: Final = Path(__file__).resolve().parent.parent.parent
def get_version() -> str:
"""Returns current version tag"""
if __version__ != "<version>":
return __version__
return "development"
@lru_cache(maxsize=1)
def get_git_branch() -> str | None:
"""Current git branch for a dev build's display, or None outside a checkout (cached for the process's life)."""
try:
# The Docker dev image's bind-mounted .git is host-owned while the
# container runs as root, which git 2.35.2+ refuses as "dubious ownership".
# trunk-ignore(bandit/B607): git is resolved from PATH by design
result = subprocess.run(
[
"git",
"-c",
f"safe.directory={_REPO_ROOT}",
"rev-parse",
"--abbrev-ref",
"HEAD",
],
cwd=_REPO_ROOT,
capture_output=True,
text=True,
check=True,
timeout=2,
shell=False, # trunk-ignore(bandit/B603): args are hardcoded
)
except OSError, subprocess.SubprocessError:
return None
branch = result.stdout.strip()
return branch if branch and branch != "HEAD" else None
def is_valid_uuid(uuid_str: str) -> bool:
"""Check if a string is a valid UUID."""
try:
uuid.UUID(uuid_str, version=4)
return True
except ValueError:
return False
def safe_str_to_bool(value: Any, default: bool = False) -> bool:
"""Safely convert a value to bool, returning default if conversion fails."""
try:
return value.strip().lower() in ("1", "true", "yes", "on")
except ValueError, TypeError, AttributeError:
return default
def safe_int(value: Any, default: int = 0) -> int:
"""Safely convert a value to int, returning default if conversion fails."""
try:
return int(value)
except ValueError, TypeError, OverflowError:
return default
def int_or_none(value: Any) -> int | None:
"""An int, or None when it is not one (``int()`` raises past 4300 digits)."""
if value is None or value == "":
return None
try:
return int(value)
except TypeError, ValueError:
return None
def valid_youtube_id(value: Any) -> str | None:
"""A video id, or None when it is not one."""
text = str(value or "")
return text if YOUTUBE_ID_RE.fullmatch(text) else None