Files
romm/backend/utils/database.py
Georges-Antoine Assi 3b8eabdb77 feat(sync): sync RetroArch Cloud Sync saves through save slots (#5170)
* feat(sync): sync RetroArch Cloud Sync saves through save slots

RetroArch saves were unslotted and overwritten in place, so they never
reached the slot-based sync the native clients use, and a bad upload
replaced the only copy.

A save path now serves the newest slotted version for its ROM, core and
extension, from any slot, under RetroArch's own file name. An upload adds
a version to that slot (or autosave), skips unchanged bytes, and prunes to
MAX_SAVES_PER_SLOT. A delete removes every save the path covers, so none
resurfaces on the next sync. Unslotted saves keep serving until the first
slotted upload; PSP bundles and states are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): lock RetroArch save uploads and prune per core and extension

Addresses Greptile's review on #5170:
- Move the RetroArch save upload into sync_handler.store_save_version,
  leaving the endpoint to validate and map the result to a status.
- Hold a Redis lock per (user, rom, core, extension) across the lookup,
  write, scan and row update, so concurrent same-second uploads never file
  two rows over one tagged file. A lock timeout answers 503.
- Prune only the uploaded path's core and extension in the slot, so
  another core's or a .rtc's current save is never dropped.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): pr-ready code-review fixes for RetroArch save slots

- Scope an extensionless prune to dotless file names, since every name
  ends in an empty extension.
- Treat only NULL slots as unslotted in the manifest, matching the query
  it replaced and the PSP bundle lookup.
- Share one helper for the slot versions a RetroArch path covers.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(sync): pr-ready simplify pass for RetroArch save slots

- Scope a slot prune by save ids, so the versions a RetroArch path covers
  are decided once in Python instead of again in SQL.
- One newest-per-key helper for states and save versions, and
  resolve_save_by_slot reuses it.
- A canonical_save_file_name helper next to the state one.
- The upload builds its tagged name once, checks its length in the
  handler, and finds a same-second version in the list it already loaded.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(sync): pr-ready review-polish pass

Drop a comment the canonical_save_file_name helper now says.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): map RetroArch saves onto autosave lineages with unique version names

- Only RetroArch's .srm goes through slots, as the autosave versions of
  its ROM and core. Companion files such as .rtc stay single unslotted
  saves, so a slot never offers a clock file as the save.
- RetroArch reads, writes and deletes in autosave only, leaving named
  slots alone.
- Every slot prune, web uploads included, is scoped to the uploaded save's
  lineage (emulator and extension), so one core's uploads never drop
  another's only save.
- The manifest lists the newest version under the client's spelling of
  the game when it still names the ROM.
- reserve_version_name moves a taken tag on a second and claims it in
  Redis, so same-second, concurrent or repeated-hour uploads from either
  endpoint never share a file. The RetroArch lock and its 503 go.
- The manifest reads only the newest version per lineage, through one
  window query.
- An upload is hashed before it is written, so an unchanged re-send
  writes nothing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(sync): seed the client-spelled save instead of uploading it

Uploading TEST_ROM.srm only resolves to the test_rom ROM under MariaDB's
case-insensitive collation, so the test 409'd on PostgreSQL. Seeding the
version directly still checks that the manifest keeps the client's
spelling of the game.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): resolve RetroArch saves to ROMs case-insensitively on PostgreSQL

Cloud Sync matches a save's game name to a ROM's fs_name_no_ext. MariaDB's
collation ignores case, but PostgreSQL compared exactly, so TEST_ROM.srm
never reached the test_rom ROM. PostgreSQL now compares lowercased names,
served by a new expression index (0150), and the endpoint test uploads the
differently-cased name again.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): address Greptile review on RetroArch save slots

- add_save derives the prune lineage from the tagged name it stores, so a
  dotted upload such as game.rev.srm is counted against its own versions.
- Deleting a RetroArch .srm path also removes unslotted saves in that
  lineage spelled in another case, which the manifest hid behind the
  autosave head and PostgreSQL's exact match left behind.
- reserve_version_name looks up existing versions off the event loop.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 18:30:57 -04:00

356 lines
13 KiB
Python

from datetime import date
from functools import reduce
from operator import getitem
from typing import Any, Sequence
from uuid import uuid4
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql as sa_pg
from sqlalchemy.orm import InstrumentedAttribute
from sqlalchemy.sql import ColumnElement
# These helpers only read `.engine`, which an Engine answers with itself.
type DatabaseBind = sa.Engine | sa.Connection
# Single-column foreign keys that MariaDB/MySQL index implicitly but PostgreSQL
# does not, so 0124 creates them there only and no model declares them.
POSTGRESQL_FK_INDEXES: tuple[tuple[str, str, str], ...] = (
("collections", "ix_collections_user_id", "user_id"),
("smart_collections", "ix_smart_collections_user_id", "user_id"),
("rom_notes", "ix_rom_notes_user_id", "user_id"),
("firmware", "ix_firmware_platform_id", "platform_id"),
("collections_roms", "ix_collections_roms_rom_id", "rom_id"),
("music_playlist_tracks", "ix_music_playlist_tracks_rom_file_id", "rom_file_id"),
("music_favorite_tracks", "ix_music_favorite_tracks_rom_file_id", "rom_file_id"),
("play_sessions", "ix_play_sessions_rom_id", "rom_id"),
("play_sessions", "ix_play_sessions_device_id", "device_id"),
("saves", "ix_saves_user_id", "user_id"),
("states", "ix_states_user_id", "user_id"),
("screenshots", "ix_screenshots_user_id", "user_id"),
("rom_file_user", "ix_rom_file_user_user_id", "user_id"),
("memory_cards", "ix_memory_cards_platform_id", "platform_id"),
(
"streaming_container_adoptions",
"ix_streaming_container_adoptions_decided_by_user_id",
"decided_by_user_id",
),
)
HLTB_MAIN_STORY_COLUMN = "generated_hltb_main_story"
SEARCH_TITLES_COLUMN = "search_titles"
MIN_AGE_COLUMN = "min_age"
# The nullable `roms` columns the gallery sorts on. MariaDB and MySQL have no
# NULLS LAST and cannot index the `IS NULL` term emulating it, so each column
# gets a materialized `_unset` flag the ascending sort leads with instead.
# Named here rather than in `utils.roms_columns`, which imports this module.
SORTABLE_NULLABLE_ROM_COLUMNS = (
"generated_first_release_date",
"generated_average_rating",
HLTB_MAIN_STORY_COLUMN,
)
def rom_unset_flag_column(column: str) -> str:
"""The generated flag column recording whether `column` is unset."""
return f"{column}_unset"
def rom_sort_index_name(column: str) -> str:
"""The composite index the ascending gallery sort on `column` walks."""
return f"idx_roms_{column}_sort"
def rom_desc_index_name(column: str) -> str:
"""The PostgreSQL-only index the descending gallery sort on `column` walks."""
return f"idx_roms_{column}_desc"
# The gallery search's FULLTEXT index on MySQL/MariaDB, whose columns a MATCH
# must list exactly, and PostgreSQL's pg_trgm index over the titles.
ROMS_SEARCH_FULLTEXT_INDEX = "idx_roms_search_fulltext"
ROMS_SEARCH_FULLTEXT_COLUMNS = ("name", "fs_name", SEARCH_TITLES_COLUMN)
ROMS_SEARCH_TITLES_TRGM_INDEX = "idx_roms_search_titles_trgm"
# PostgreSQL-only, for RetroArch Cloud Sync's case-insensitive ROM lookup.
ROMS_FS_NAME_NO_EXT_LOWER_INDEX = "idx_roms_fs_name_no_ext_lower"
# Indexes that exist in some databases but cannot be declared on a model.
AUTOGENERATE_EXEMPT_INDEX_NAMES = (
frozenset(
# Search indexes built per dialect: FULLTEXT on MySQL/MariaDB, pg_trgm
# GIN on PostgreSQL. No portable model declaration exists.
{
ROMS_SEARCH_FULLTEXT_INDEX,
ROMS_SEARCH_TITLES_TRGM_INDEX,
"idx_roms_name_trgm",
"idx_roms_fs_name_trgm",
}
)
| frozenset(name for _, name, _ in POSTGRESQL_FK_INDEXES)
# `DESC NULLS LAST` is the only spelling that matches what the descending
# gallery sort asks for, and no other engine parses it.
| frozenset(rom_desc_index_name(c) for c in SORTABLE_NULLABLE_ROM_COLUMNS)
# An expression index, which MariaDB has no use for: its collation ignores case.
| {ROMS_FS_NAME_NO_EXT_LOWER_INDEX}
)
def CustomJSON(**kwargs: Any) -> sa.JSON:
"""Custom SQLAlchemy JSON type that uses JSONB on PostgreSQL."""
return sa.JSON(**kwargs).with_variant(sa_pg.JSONB(**kwargs), "postgresql")
# Byte for byte and NO PAD, so case, accents and trailing spaces all count.
MARIADB_EXACT_COLLATION = "utf8mb4_nopad_bin"
MYSQL_EXACT_COLLATION = "utf8mb4_0900_bin"
class ExactString(sa.types.TypeDecorator[str]):
"""A VARCHAR that MariaDB and MySQL compare exactly, as PostgreSQL and Python do."""
impl = sa.String
cache_ok = True
def load_dialect_impl(self, dialect: sa.Dialect) -> sa.types.TypeEngine[Any]:
return dialect.type_descriptor(
sa.String(self.length, collation=_exact_collation(dialect))
)
def exact_collation(conn: DatabaseBind) -> str | None:
"""The collation `ExactString` needs on this server, None on PostgreSQL."""
return _exact_collation(conn.engine.dialect)
def _exact_collation(dialect: sa.Dialect) -> str | None:
if dialect.name == "postgresql":
return None
# The dialect is named `mysql` when the MySQL driver reaches a MariaDB server.
if getattr(dialect, "is_mariadb", False):
return MARIADB_EXACT_COLLATION
return MYSQL_EXACT_COLLATION
def is_postgresql(conn: DatabaseBind) -> bool:
return conn.engine.name == "postgresql"
def is_mysql(conn: DatabaseBind) -> bool:
return conn.engine.name == "mysql"
def is_mariadb(conn: DatabaseBind) -> bool:
return conn.engine.name == "mariadb"
# Queries use JSON_OVERLAPS (MariaDB 10.9, MySQL 8.0.17); 10.11 is the oldest
# MariaDB LTS still receiving fixes.
MIN_MARIADB_VERSION = (10, 11)
MIN_MYSQL_VERSION = (8, 0, 17)
def unsupported_server_version(dialect: sa.Dialect) -> str | None:
"""Why the connected server is too old for RomM, or None when it is supported."""
if dialect.name not in ("mysql", "mariadb") or not dialect.server_version_info:
return None
# A MariaDB server reached through the mysql driver still reports as MariaDB.
engine, minimum = (
("MariaDB", MIN_MARIADB_VERSION)
if getattr(dialect, "is_mariadb", False)
else ("MySQL", MIN_MYSQL_VERSION)
)
version = tuple(p for p in dialect.server_version_info if isinstance(p, int))
if version >= minimum:
return None
return (
f"RomM needs {engine} {'.'.join(map(str, minimum))} or newer, but the "
f"database server runs {'.'.join(map(str, version))}. Upgrade the server, "
"then start RomM again. See https://docs.romm.app/latest/install/databases/"
)
# Error 1419, which MariaDB and MySQL raise for every trigger statement while
# binary logging is on and the user lacks SUPER (issue #3932).
BINLOG_TRIGGER_DDL_ERRNO = 1419
def alembic_command_runs_revisions(command: str, *, pending: bool) -> bool:
"""Whether this alembic command reaches revision code, trigger DDL included.
`command` is the `fn` name alembic hands its environment, not the CLI word.
"""
return command == "downgrade" or (command == "upgrade" and pending)
def is_binlog_trigger_privilege_error(exc: BaseException) -> bool:
"""Whether `exc` is the server refusing trigger DDL under binary logging."""
orig = getattr(exc, "orig", exc)
errno = getattr(orig, "errno", None)
if errno is None:
args = getattr(orig, "args", ())
errno = args[0] if args else None
return errno == BINLOG_TRIGGER_DDL_ERRNO
def probe_trigger_name() -> str:
"""A trigger name no schema can already hold, for the privilege probe.
Trigger names are schema-wide, so a fixed one could name an operator's own
trigger and the probe would really drop it.
"""
return f"romm_trigger_ddl_probe_{uuid4().hex}"
def trigger_ddl_is_blocked(conn: sa.Connection) -> bool:
"""Whether the server refuses the trigger DDL the migrations need.
Dropping a trigger that cannot exist is the cheapest statement that still
goes through the privilege check, and the only error it can raise is the
refusal itself. Rolls `conn` back on one.
"""
if not (is_mysql(conn) or is_mariadb(conn)):
return False
try:
conn.exec_driver_sql(f"DROP TRIGGER IF EXISTS {probe_trigger_name()}")
except sa.exc.DBAPIError as exc:
conn.rollback()
return is_binlog_trigger_privilege_error(exc)
return False
def column_names(conn: sa.Connection, table: str) -> set[str]:
"""The columns `table` currently carries, for guards over a set of them.
One reflection answers the whole set; `has_column` per candidate costs one
round-trip each.
"""
return {column["name"] for column in sa.inspect(conn).get_columns(table)}
def has_column(conn: sa.Connection, table: str, column: str) -> bool:
"""Whether `table` already carries `column`, which `Inspector` cannot answer."""
return column in column_names(conn, table)
def full_path_digest_sql(conn: sa.Connection) -> str:
"""`models.rom.compute_full_path_hash` spelled in SQL, for 0126's backfill.
`test_migrations` pins this to the Python function it mirrors.
"""
# COALESCE because the Python side reads a NULL as "", while both dialects
# would fold the whole concatenation to NULL and fail 0126's NOT NULL step.
if is_postgresql(conn):
return (
"encode(sha256(convert_to(COALESCE(fs_path, '') || '/' || "
"COALESCE(fs_name, ''), 'UTF8')), 'hex')"
)
return "SHA2(CONCAT(COALESCE(fs_path, ''), '/', COALESCE(fs_name, '')), 256)"
MS_PER_DAY = 86_400_000
# Tennis for Two (1958) predates the epoch, so the oldest ranges are negative.
EARLIEST_RELEASE_YEAR = 1958
# The range union has to be finite, so "any year" stops here.
LATEST_RELEASE_YEAR = 2100
_EPOCH = date(1970, 1, 1)
def day_of_year_ranges(
month: int, day: int, *, before_year: int
) -> list[tuple[int, int]]:
"""Half-open epoch-millisecond ranges covering (month, day) in each earlier year.
Ranges rather than `MONTH()/DAY()` on the value, because they are sargable
and emit no SQL date function, so every dialect plans them the same way.
Args:
month: Calendar month, 1-12.
day: Day of the month, 1-31.
before_year: Exclusive upper bound on the years covered.
Returns:
Ascending (start, end) pairs, skipping years the date does not exist in,
so an impossible date yields none at all.
"""
ranges: list[tuple[int, int]] = []
for year in range(EARLIEST_RELEASE_YEAR, before_year):
try:
start = (date(year, month, day) - _EPOCH).days * MS_PER_DAY
except ValueError:
continue
ranges.append((start, start + MS_PER_DAY))
return ranges
def release_day_ranges(
days: Sequence[tuple[int, int]], *, before_year: int | None = None
) -> list[tuple[int, int]]:
"""Epoch-millisecond ranges covering every day in `days`, in every year.
Args:
days: (month, day) pairs to match.
before_year: Exclusive upper bound on the years covered, defaulting to
`LATEST_RELEASE_YEAR`.
Returns:
(start, end) pairs, skipping years a date does not exist in.
"""
bound = LATEST_RELEASE_YEAR if before_year is None else before_year
return [
day_range
for month, day in days
for day_range in day_of_year_ranges(month, day, before_year=bound)
]
def epoch_ms_in_ranges(
column: sa.Column[Any] | Any, ranges: Sequence[tuple[int, int]]
) -> ColumnElement[Any]:
"""Match an epoch-millisecond column against any of the given half-open ranges."""
if not ranges:
return sa.false()
return sa.or_(
*[sa.and_(column >= start, column < end) for start, end in sorted(ranges)]
)
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:
return default
def get_nested(obj: Any, path: str, default: Any = None) -> Any:
"""Read a dot-separated key path from nested dicts, returning default if any step is missing."""
try:
return reduce(getitem, path.split("."), obj)
except KeyError, TypeError:
return default
def is_non_blank(column: InstrumentedAttribute[Any]) -> ColumnElement[bool]:
"""Whether `column` holds a value other than NULL or its type's blank (0 or "")."""
blank: int | str = "" if isinstance(column.type, sa.String) else 0
return sa.and_(column.isnot(None), column != blank)