Files
romm/backend/handler/metadata/base_handler.py
Sam Dornan 130ea73c23 perf(metadata): compress the cache-only metadata dump records (#4426)
* perf(metadata): compress the cache-only metadata dump records

The LaunchBox and Switch TitleDB stores are read by exact key and never
scanned, so each value can be compressed on its own. On a full import of
both real dumps into the bundled valkey, `used_memory` drops from 539.1MB
to 335.9MB and RSS from 553.3MB to 350.2MB, a 38% saving.

Values are zstd level 3, which costs 3-6us per record read, less than the
`json.loads` that follows it. A payload under 256 bytes is stored as plain
JSON: below that a frame header and a poor ratio on a short payload cost
more than they save, which is what leaves the id-valued title and product
id indexes untouched. `tools/measure_dump_cache.py --sweep` finds the real
records flat between 64 and 256 bytes.

Reads detect the zstd frame rather than trusting the key, so a store
written by an earlier import keeps answering until the next update
rewrites it. No re-import is required to upgrade.

A zstd frame is not UTF-8, so the dump keys move to a cache client that
leaves values as bytes. `async_cache` still serves everything else,
including the existence checks on these keys.

The new tool measures per-store size with `MEMORY USAGE ... SAMPLES 0`,
which walks every field. The default of five samples extrapolates, and on
a hash of this size it is wrong by enough that per-key figures stop
adding up to `used_memory`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* test(metadata): assert the writer stores through the dump codec

`test_values_are_json_encoded` pinned the exact string `json.dumps`
produced with default separators. The writer now hands the pipeline
compact bytes from `encode`, so the test asserts the contract that
matters instead: the value is bytes, and it decodes back to the record.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* fix(tools): stop the dump measurement wiping the whole cache server

`flushall` between passes would erase every database on whatever
`--redis-url` names, and RomM's sessions and RQ queues share that
database with the dump stores, so pointing the tool at a live instance
cost far more than the stores it meant to reset.

It now deletes only the ten keys it writes, and refuses a server holding
anything else unless forced, since a running RomM would have to
re-import what it drops. Each pass records what the server uses without
those stores and reports figures net of it, so a non-empty server still
measures what the dumps themselves cost.

Reported by Greptile on #4426.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* fix(tools): report field counts and bytes off the stores, not the writes

Two accounting errors in the measurement tool, both reported by Copilot
on #4426.

Field counts and byte totals were tallied while writing, so they counted
write attempts. `HSET` overwrites, and the dump repeats a title on one
platform and an alternate name across platforms, so 8,997 of the writes
landed on a field another record already held: the alternate name store
reported 70,297 fields against 62,384 actually stored. Both figures now
come from `HLEN` and a scan of each hash, which cannot drift from what
the store holds.

`used_memory_rss` was offset by a `used_memory` baseline, mixing two
metrics. Netting RSS turns out to be wrong however the baseline is
captured, because the pages a delete frees stay resident, which made the
encoded pass report -56.1MB. RSS is now reported absolute, and `--only`
loads a single encoding so it can be read off a server started fresh for
that pass: 555.8MB plain against 348.9MB encoded, measured that way.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* style(tools): cut the measurement tool's docstrings to the repo's limit

CLAUDE.md allows a docstring one sentence plus `Args:`/`Returns:`, and the
module docstring ran to four paragraphs. The non-obvious reasons move to
one-line comments at the code they explain, which is where a reader needs
them, and the operational detail was already carried by `--force` and
`--only`'s help text and by the refusal message itself.

Reported by Copilot on #4426.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* fix(tools): fold titles the way production does, and stop echoing the URL

Four more Copilot findings on #4426, three of them in the measurement tool
and one in the codec module.

The folded-title stand-in kept only ASCII alphanumerics, the exact thing
`fold_title`'s docstring warns against: it reduced `Astérix` to `astrix`
and `三國立志傳2` to `2`, and dropped titles that fold to nothing, so the
folded index measured smaller than it is. The tool now mirrors
`fold_title` character for character, verified against the real function
extracted from its module over 40,000 dump titles with no mismatch. The
store grows by 244 fields and 0.1MB, so the totals barely move.

The refusal path printed the target URL, which RomM builds with the
password inline, so it could have carried a credential into a CI log. It
now names the server generically and keeps the key count and the remedy.

`dump_cache`'s module docstring and its threshold comment both ran past
the one-to-two-line limit in CLAUDE.md. The benchmark numbers behind the
threshold live in the PR description, not the source.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* refactor(cache): give the dump store keys one home

The measurement tool carried its own copies of the ten store key strings,
against the single-source rule in CLAUDE.md. That matters more now the
tool deletes those keys: a production rename would have left it deleting
stale hashes, missing the new ones, and counting the real stores as
foreign data in its own safety guard.

The keys move to `handler/dump_cache.py`, which already holds the codec
that reads and writes them and depends on nothing but the cache client,
so the importers, the lookups and the tool all take them from there.
`DUMP_STORE_KEYS` is the list the tool measures and clears.

`base_handler` was reaching into `tasks/scheduled/update_switch_titledb`
for two constants, so a handler depended on a task module; that import is
gone. `launchbox_handler/types.py` keeps the initial-import flag, which
marks an import in progress rather than naming a store.

Measurement is unchanged: 538.0MB to 334.8MB, per-store figures identical.

Reported by Copilot on #4426.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* fix(tests): import the store keys from where the merge left them

Two test modules still took the keys from `handler.dump_cache`, which the
merge emptied of them, so collection failed with an ImportError on both
databases and mypy flagged nine missing attributes. They read them from
`launchbox_handler/types.py` and the TitleDB task now, as the code does.

Also reverts formatting the merge dragged into four files this change has
no business touching: running isort over everything the merge listed
reclassified `tests.*` and `startup` out of the block master keeps them
in, and black rewrote two `except (A, B)` clauses into the unparenthesized
form. Those files go back to master's copy.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* style(tests): restore both metadata test files to master's formatting

Running the formatters over everything the merge touched had reordered
imports trunk keeps in another block. Both files go back to master's copy,
with the compressed-store read test re-added by hand and its import placed
in the first-party block where the other `handler.*` imports sit.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* fix(tools): report bad input rather than dividing by zero

A zip with none of the four XML files loads no records, and every ratio
the report prints then divides by a zero total.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* refactor(tools): match the yields to their siblings, type the serializer

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

* style: trim the comments and tighten the names review-polish flags

Cut the version notes to what version 2 is, drop the two comments that
repeated a neighbour, rename the tool's `measure` to `store_memory` beside
`store_stats`, and annotate the codec tests' parametrized arguments.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQNNQHk7uyS3eoB9yAxoM9

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-10 16:09:32 -05:00

379 lines
13 KiB
Python

import abc
import json
import re
import unicodedata
from functools import lru_cache
from pathlib import Path
from typing import TYPE_CHECKING, Final, Mapping, NotRequired, TypedDict
from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
from fastapi import HTTPException, status
from strsimpy.jaro_winkler import JaroWinkler
from handler.dump_cache import hget_json
from handler.redis_handler import async_cache
from logger.logger import log
from tasks.scheduled.update_switch_titledb import (
SWITCH_PRODUCT_ID_KEY,
SWITCH_TITLEDB_INDEX_KEY,
SWITCH_TITLEDB_STORE,
)
from utils.cache import is_cache_store_ready
from utils.context import ctx_httpx_client
from utils.switch import derive_base_title_id
if TYPE_CHECKING:
from models.rom import Rom
jarowinkler = JaroWinkler()
METADATA_FIXTURES_DIR: Final = Path(__file__).parent / "fixtures"
# Providers are third parties; a response is read only this far before it is dropped.
MAX_RESPONSE_BYTES: Final[int] = 1_000_000
REQUEST_TIMEOUT: Final[int] = 25
# These are loaded in cache in update_switch_titledb_task
SWITCH_TITLEDB_REGEX: Final = re.compile(r"(70[0-9]{12})")
SWITCH_PRODUCT_ID_REGEX: Final = re.compile(r"(0100[0-9A-F]{12})")
# No regex needed for MAME
MAME_XML_KEY: Final = "romm:mame_xml"
# ScummVM
SCUMMVM_INDEX_KEY: Final = "romm:scummvm_index"
# PS2 OPL
PS2_OPL_REGEX: Final = re.compile(r"^([A-Z]{4}_\d{3}\.\d{2})\..*$")
PS2_OPL_KEY: Final = "romm:ps2_opl_index"
# Sony serial codes for PS1, PS2, PS3 and PSP
SONY_SERIAL_REGEX: Final = re.compile(r".*([a-zA-Z]{4}-\d{5}).*$")
PS1_SERIAL_INDEX_KEY: Final = "romm:ps1_serial_index"
PS2_SERIAL_INDEX_KEY: Final = "romm:ps2_serial_index"
PSP_SERIAL_INDEX_KEY: Final = "romm:psp_serial_index"
LEADING_ARTICLE_PATTERN = re.compile(r"^(a|an|the)\b", re.IGNORECASE)
COMMA_ARTICLE_PATTERN = re.compile(r",\s(a|an|the)\b(?=\s*[^\w\s]|$)", re.IGNORECASE)
NON_WORD_SPACE_PATTERN = re.compile(r"[^\w\s]")
MULTIPLE_SPACE_PATTERN = re.compile(r"\s+")
def unavailable(provider: str) -> HTTPException:
"""The error a provider raises when it can't be reached."""
return HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail=f"Can't connect to {provider}, check your internet connection",
)
class BaseRom(TypedDict):
name: NotRequired[str]
name_sort_key: NotRequired[str | None]
summary: NotRequired[str]
url_cover: NotRequired[str]
url_screenshots: NotRequired[list[str]]
url_manual: NotRequired[str]
SENSITIVE_KEYS = {
"Authorization",
"Client-ID",
"Client-Secret",
"client_id",
"client_secret",
"api_key",
"ssid",
"sspassword",
"devid",
"devpassword",
"y",
}
SENSITIVE_KEYS_REGEX = re.compile(
rf"({'|'.join(re.escape(k) for k in SENSITIVE_KEYS)})=[^&\s\"]*",
re.IGNORECASE,
)
# This caches results to avoid repeated normalization of the same search term
@lru_cache(maxsize=1024)
def _normalize_search_term(
name: str, remove_articles: bool = True, remove_punctuation: bool = True
) -> str:
# Lower and replace underscores with spaces
name = name.lower().replace("_", " ")
# Remove articles (combined if possible)
if remove_articles:
name = LEADING_ARTICLE_PATTERN.sub("", name)
name = COMMA_ARTICLE_PATTERN.sub("", name)
# Remove punctuation and normalize spaces in one step
if remove_punctuation:
name = NON_WORD_SPACE_PATTERN.sub(" ", name)
name = MULTIPLE_SPACE_PATTERN.sub(" ", name)
# Unicode normalization and accent removal
if any(ord(c) > 127 for c in name): # Only if non-ASCII chars present
normalized = unicodedata.normalize("NFD", name)
name = "".join(c for c in normalized if not unicodedata.combining(c))
return name.strip()
def strip_sensitive_query_params(
url: str, sensitive_keys: set[str] = SENSITIVE_KEYS
) -> str:
"""Remove sensitive query parameters from a URL."""
parsed = urlparse(url)
qsl = parse_qsl(parsed.query, keep_blank_values=True)
keys_lower = {k.lower() for k in sensitive_keys}
keep = [(k, v) for k, v in qsl if k.lower() not in keys_lower]
new_query = urlencode(keep, doseq=True)
return urlunparse(parsed._replace(query=new_query))
def restore_sensitive_query_params(url: str, params: dict[str, str]) -> str:
"""Add back key/value pairs previously stripped by strip_sensitive_query_params."""
parsed = urlparse(url)
qsl = parse_qsl(parsed.query, keep_blank_values=True)
existing = {k.lower() for k in params}
filtered = [(k, v) for k, v in qsl if k.lower() not in existing]
new_query = urlencode(filtered + list(params.items()))
return urlunparse(parsed._replace(query=new_query))
class MetadataHandler(abc.ABC):
SEARCH_TERM_SPLIT_PATTERN = re.compile(r"[\:\-\/]")
SEARCH_TERM_NORMALIZER = re.compile(r"\s*[:-]\s+")
@classmethod
@abc.abstractmethod
def is_enabled(cls) -> bool:
"""Return whether this metadata handler is enabled."""
async def _fetch_capped(
self, url: str, *, headers: Mapping[str, str]
) -> bytes | None:
"""Stream a body, returning None rather than reading past the cap."""
httpx_client = ctx_httpx_client.get()
body = bytearray()
async with httpx_client.stream(
"GET", url, headers=dict(headers), timeout=REQUEST_TIMEOUT
) as res:
res.raise_for_status()
async for chunk in res.aiter_bytes():
body += chunk
if len(body) > MAX_RESPONSE_BYTES:
log.warning(
"Response from %s exceeds %s bytes", url, MAX_RESPONSE_BYTES
)
return None
return bytes(body)
def normalize_cover_url(self, url: str) -> str:
return url if not url else f"https:{url.replace('https:', '')}"
def normalize_search_term(
self, name: str, remove_articles: bool = True, remove_punctuation: bool = True
) -> str:
return _normalize_search_term(name, remove_articles, remove_punctuation)
def find_best_match(
self,
search_term: str,
game_names: list[str],
min_similarity_score: float = 0.75,
split_game_name: bool = False,
) -> tuple[str | None, float]:
"""
Find the best matching game name from a list of candidates.
Args:
search_term: The search term to match
game_names: List of game names to check against
min_similarity_score: Minimum similarity score to consider a match
Returns:
Tuple of (best_match_name, similarity_score) or (None, 0.0) if no good match
"""
if not game_names:
return None, 0.0
best_match = None
best_score = 0.0
search_term_normalized = self.normalize_search_term(search_term)
for game_name in game_names:
game_name_normalized = self.normalize_search_term(game_name)
# If the game name is split, normalize the last term
if split_game_name and re.search(self.SEARCH_TERM_SPLIT_PATTERN, game_name):
game_name_normalized = self.normalize_search_term(
re.split(self.SEARCH_TERM_SPLIT_PATTERN, game_name)[-1]
)
score = jarowinkler.similarity(search_term_normalized, game_name_normalized)
if score > best_score:
best_score = score
best_match = game_name
# Early exit for perfect match
if score == 1.0:
break
if best_score >= min_similarity_score:
return best_match, best_score
return None, 0.0
async def _ps2_opl_format(self, match: re.Match[str], search_term: str) -> str:
serial_code = match.group(1)
index_entry = await async_cache.hget(PS2_OPL_KEY, serial_code)
if index_entry:
index_entry = json.loads(index_entry)
search_term = index_entry["Name"] # type: ignore
return search_term
async def _sony_serial_format(self, index_key: str, serial_code: str) -> str | None:
index_entry = await async_cache.hget(index_key, serial_code.upper())
if index_entry:
index_entry = json.loads(index_entry)
return index_entry["title"]
return None
async def _ps1_serial_format(self, match: re.Match[str], search_term: str) -> str:
serial_code = match.group(1)
return (
await self._sony_serial_format(PS1_SERIAL_INDEX_KEY, serial_code)
or search_term
)
async def _ps2_serial_format(self, match: re.Match[str], search_term: str) -> str:
serial_code = match.group(1)
return (
await self._sony_serial_format(PS2_SERIAL_INDEX_KEY, serial_code)
or search_term
)
async def _psp_serial_format(self, match: re.Match[str], search_term: str) -> str:
serial_code = match.group(1)
return (
await self._sony_serial_format(PSP_SERIAL_INDEX_KEY, serial_code)
or search_term
)
async def _switch_titledb_format(
self, match: re.Match[str], search_term: str
) -> tuple[str, dict | None]:
title_id = match.group(1)
if not await self._is_switch_titledb_current():
log.error("Could not find a current Switch titleID index in cache")
return search_term, None
index_entry = await self._switch_titledb_entry(title_id)
if index_entry:
return index_entry["name"], index_entry
return search_term, None
async def _switch_productid_format(
self, rom: "Rom", fs_name: str, search_term: str
) -> tuple[str, dict | None]:
"""Match by Switch product id, preferring the one the scan read out of
the binary over one scraped from the filename."""
if rom.title_id and SWITCH_PRODUCT_ID_REGEX.fullmatch(rom.title_id.upper()):
product_id = rom.title_id.upper()
else:
match = SWITCH_PRODUCT_ID_REGEX.search(fs_name)
if not match:
return search_term, None
product_id = match.group(1)
# Updates and DLC share the base application's product ID, off by the
# low 12 bits, and only the base has a titledb entry.
product_id = derive_base_title_id(product_id) or product_id
if not await self._is_switch_titledb_current():
log.error("Could not find a current Switch productID index in cache")
return search_term, None
index_entry = await self._switch_product_id_entry(product_id)
if index_entry:
return index_entry["name"], index_entry
return search_term, None
@staticmethod
async def _is_switch_titledb_current() -> bool:
"""Whether the titleID index was written by the current import."""
return await is_cache_store_ready(
async_cache, SWITCH_TITLEDB_STORE, SWITCH_TITLEDB_INDEX_KEY
)
@staticmethod
async def _switch_titledb_entry(title_id: str) -> dict | None:
return await hget_json(SWITCH_TITLEDB_INDEX_KEY, title_id)
@classmethod
async def _switch_product_id_entry(cls, product_id: str) -> dict | None:
"""Resolve a Switch product id to the titleID entry its index points at."""
title_id = await hget_json(SWITCH_PRODUCT_ID_KEY, product_id)
if not title_id:
return None
return await cls._switch_titledb_entry(title_id)
async def _mame_format(self, search_term: str) -> str:
from handler.filesystem import fs_rom_handler
index_entry = await async_cache.hget(MAME_XML_KEY, search_term)
if index_entry:
index_entry = json.loads(index_entry)
search_term = fs_rom_handler.get_file_name_with_no_tags(
index_entry.get("description", search_term)
)
return search_term
async def _scummvm_format(self, search_term: str) -> str:
from handler.filesystem import fs_rom_handler
search_term = fs_rom_handler.get_file_name_with_no_extension(search_term)
index_entry = await async_cache.hget(SCUMMVM_INDEX_KEY, search_term)
if index_entry:
index_entry = json.loads(index_entry)
search_term = index_entry["name"]
return search_term
def _mask_sensitive_values(
self, values: Mapping[str, str | None]
) -> dict[str, str]:
"""
Mask sensitive values (headers or params), leaving only the first 2 and last 2 characters of the token.
"""
masked_keys: dict[str, str] = {}
for key, val in values.items():
if val is None:
masked_keys[key] = ""
continue
if key == "Authorization" and val.startswith("Bearer "):
token = val.split(" ", 1)[1]
masked_keys[key] = f"Bearer {token[:2]}***{token[-2:]}"
elif key in SENSITIVE_KEYS:
masked_keys[key] = f"{val[:2]}***{val[-2:]}"
else:
masked_keys[key] = val
return masked_keys