Files
romm/backend/handler/dump_store.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

265 lines
8.6 KiB
Python

"""Read-only SQLite files of key-value tables, for lookups an import rebuilds whole.
A build renames a finished file over the old one, so readers never see a partial store.
"""
import json
import os
import sqlite3
import threading
import time
import uuid
import weakref
from collections.abc import Iterator
from compression import zstd
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Final
from logger.logger import log
# Level 3 costs less per read than the `json.loads` that follows it.
COMPRESSION_LEVEL: Final[int] = 3
# Below this size, a frame header and a poor ratio cost more than they save, so
# the title and product id indexes, which hold only ids, stay plain JSON.
COMPRESS_MIN_BYTES: Final[int] = 256
# Zstandard frame magic, from RFC 8878 section 3.1.1.
_ZSTD_MAGIC: Final[bytes] = b"\x28\xb5\x2f\xfd"
WRITE_BATCH_SIZE: Final[int] = 2000
# A build writes constantly, so a temporary file idle this long is one a killed
# process left behind.
STALE_BUILD_SECONDS: Final[int] = 3600
_compressor = zstd.ZstdCompressor(level=COMPRESSION_LEVEL)
_stores: "weakref.WeakSet[DumpStore]" = weakref.WeakSet()
def _reset_stores_after_fork() -> None:
# A forked child must not use the parent's connection, nor a lock another
# thread held at the moment of the fork.
for store in _stores:
store._lock = threading.Lock()
store._conn = None
os.register_at_fork(after_in_child=_reset_stores_after_fork)
class EmptyDumpError(RuntimeError):
"""A build finished without a single row in the store's required table."""
def encode(value: Any) -> bytes:
"""Serialize a dump record, compressing it when it is large enough to pay off.
Args:
value: The record to store, as JSON-serializable data.
Returns:
The bytes to write into the store.
"""
payload = json.dumps(value, separators=(",", ":")).encode()
if len(payload) < COMPRESS_MIN_BYTES:
return payload
return _compressor.compress(payload, zstd.ZstdCompressor.FLUSH_FRAME)
def decode(raw: bytes | None) -> Any:
"""Deserialize a dump record, whether or not it was stored compressed.
Args:
raw: The stored value, or None when the key is absent.
Returns:
The record, or None when there was nothing stored.
"""
if not raw:
return None
if raw.startswith(_ZSTD_MAGIC):
raw = zstd.decompress(raw)
return json.loads(raw)
class DumpWriter:
"""Batches the rows of a store being built."""
def __init__(self, conn: sqlite3.Connection, tables: tuple[str, ...]) -> None:
self._conn = conn
self._pending: dict[str, list[tuple[str, bytes]]] = {t: [] for t in tables}
self._queued = 0
def put(self, table: str, key: str, value: Any) -> None:
"""Queue a record, replacing any earlier one under the same key."""
self._pending[table].append((key, encode(value)))
self._queued += 1
if self._queued >= WRITE_BATCH_SIZE:
self.flush()
def flush(self) -> None:
for table, rows in self._pending.items():
if rows:
self._conn.executemany(
f"INSERT OR REPLACE INTO {table} (key, value) VALUES (?, ?)", # nosec B608
rows,
)
rows.clear()
self._queued = 0
class DumpStore:
"""One read-only SQLite file of key-value tables, swapped in whole by a build.
Args:
revision: Part of the file name; bump it when a build changes what a table holds.
required_table: A build that leaves it empty fails and keeps the previous file.
"""
def __init__(
self,
directory: Path,
name: str,
revision: str,
tables: tuple[str, ...],
required_table: str | None = None,
) -> None:
if required_table is not None and required_table not in tables:
raise ValueError(f"{name} has no table {required_table!r}")
self.directory = directory
self.name = name
self.revision = revision
self.tables = tables
self.required_table = required_table
# One connection per process, so a rebuild leaves at most one stale file open.
self._lock = threading.Lock()
self._conn: tuple[tuple[int, int], sqlite3.Connection] | None = None
_stores.add(self)
@property
def path(self) -> Path:
return self.directory / f"{self.name}.{self.revision}.sqlite"
def exists(self) -> bool:
return self.path.is_file()
def get(self, table: str, key: str) -> Any:
"""Read one record, or None when the key or the whole store is absent."""
if table not in self.tables:
raise ValueError(f"{self.name} has no table {table!r}")
with self._lock:
try:
conn = self._connection()
if conn is None:
return None
row = conn.execute(
f"SELECT value FROM {table} WHERE key = ?", (key,) # nosec B608
).fetchone()
except sqlite3.DatabaseError as exc:
log.error(f"Could not read {self.path}: {exc}")
self._close()
return None
return decode(row[0]) if row else None
def _connection(self) -> sqlite3.Connection | None:
"""The connection to the current file, reopened once a build swaps it.
The caller holds `_lock`.
"""
try:
stat = os.stat(self.path)
except FileNotFoundError:
self._close()
return None
identity = (stat.st_dev, stat.st_ino)
if self._conn is not None and self._conn[0] == identity:
return self._conn[1]
self._close()
# The file is never written in place, so SQLite can skip locking it.
uri = f"{self.path.resolve().as_uri()}?mode=ro&immutable=1"
conn = sqlite3.connect(uri, uri=True, check_same_thread=False)
self._conn = (identity, conn)
return conn
def _close(self) -> None:
"""Close the open connection, releasing a replaced file. The caller holds `_lock`."""
if self._conn is not None:
self._conn[1].close()
self._conn = None
@contextmanager
def build(self) -> Iterator[DumpWriter]:
"""Write a new file and swap it in once the block finishes without error."""
self.directory.mkdir(parents=True, exist_ok=True)
self._drop_abandoned_builds()
tmp_path = self.directory / f".{self.path.name}.{uuid.uuid4().hex}.tmp"
# Nothing else opens the file, and locks can fail on a network share.
conn = sqlite3.connect(f"{tmp_path.resolve().as_uri()}?nolock=1", uri=True)
try:
# A failed build throws its file away, so it needs no journal.
conn.execute("PRAGMA journal_mode = OFF")
conn.execute("PRAGMA synchronous = OFF")
# Rowid tables, since they pack large values densely in any key order.
for table in self.tables:
conn.execute(
f"CREATE TABLE {table} (key TEXT PRIMARY KEY, value BLOB NOT NULL)"
)
writer = DumpWriter(conn, self.tables)
yield writer
writer.flush()
if (
self.required_table is not None
and not conn.execute(
f"SELECT 1 FROM {self.required_table} LIMIT 1" # nosec B608
).fetchone()
):
raise EmptyDumpError(
f"{self.name} build wrote no {self.required_table} rows"
)
conn.commit()
conn.close()
with open(tmp_path, "rb") as f:
os.fsync(f.fileno())
os.replace(tmp_path, self.path)
except BaseException:
conn.close()
tmp_path.unlink(missing_ok=True)
raise
with self._lock:
self._close()
self.drop_other_revisions()
def drop_other_revisions(self) -> list[Path]:
"""Delete the files that earlier revisions of this store left, and return their paths."""
dropped = []
for path in self.directory.glob(f"{self.name}.*.sqlite"):
if path != self.path:
path.unlink(missing_ok=True)
dropped.append(path)
return dropped
def _drop_abandoned_builds(self) -> None:
cutoff = time.time() - STALE_BUILD_SECONDS
for path in self.directory.glob(f".{self.name}.*.tmp"):
try:
if path.stat().st_mtime < cutoff:
path.unlink()
except FileNotFoundError:
continue