mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 01:58:41 +01:00
* fix(sync): cap play sessions on sync completion and require roms.user.write The completion endpoint fed an unbounded play_sessions list to the same ingest as POST /api/play-sessions, which allows 100 per batch and requires roms.user.write. Apply both rules before the session is completed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(config): reject empty platform binding and version values config.yml exits on load when a platforms or versions value is empty, so the API must not write one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(collections): require smart collection criteria to be a JSON object Any other JSON value was stored, then failed the response schema and broke the smart collection list for every user who could see the collection. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(stats): require roms.read on /api/stats Anonymous callers were served counts over the whole library, including platforms and ROMs hidden from users. The UI only calls it after login. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(permissions): apply ROM visibility to filters, saves, play sessions and collection removal /api/roms/filters aggregated facet values over the whole library, GET /api/saves/{id} and GET /api/play-sessions returned the caller's own rows on hidden ROMs, and removing ROMs from a collection could drop members hidden from its owner. The facet visibility clauses move onto RomVisibilityFilter so stats and filters share them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(webhooks): keep non-admin webhooks off the admin's internal metadata origins The SSRF exception for a self-hosted Playmatch or Hasheous applied to every request, so a user's webhook could reach any path on that private origin. Non-admin webhooks now validate and connect with an empty allowlist. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(saves): bound total decompressed size when hashing zip archives Zip content hashing capped each entry but not the archive, so many entries each under the cap could still decompress and hash far more than any real save or memory card holds. Budget the decompressed bytes across the whole archive and cap the entry count; callers keep treating an over-budget archive as an unknown hash. The chunked, budgeted entry reader is shared with the memory card archive check, and the RetroArch store path now hashes off the event loop like its siblings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(psp): clamp LZ4 literal and match copies to the ZISO block size The ZISO block decoder appended literals and copied matches for their full encoded length before checking the output size, and an LZ4 length can be extended without bound by 0xFF bytes. A small crafted block could therefore expand far past the block size before being truncated. Clamp each copy to the room left in the block, stop once it is full, end the block on a truncated match offset, and copy matches with slices instead of a per-byte loop (overlapping matches repeat their pattern). Output for valid blocks is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(auth): revoke OAuth tokens when a user's credentials change A password change, admin reset, reset-link reset or rename cleared the account's web sessions, but its OAuth access tokens kept working until they expired and its refresh tokens could still be exchanged at /api/token. Revoking a user's credentials now also records a per-username revocation time in Redis, kept for the longest token lifetime. Bearer validation and refresh consumption reject any token whose iat is at or before it. OAuth tokens now carry a sub-second iat, so a login right after the change still works; a token without iat counts as older than any revocation. The revocation is keyed by the token's sub, the same username sessions are keyed by, so a rename revokes tokens issued under the old name even if another account later takes it. Client (API) tokens are left alone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(api): reject local file URLs for user-supplied covers and manuals file:// and launchbox-file:// URLs are meant for covers and manuals that a scan records from gamelist.xml or LaunchBox metadata. The collection create/update endpoints and the ROM update endpoint passed a user-supplied url_cover (and url_manual) straight to the resource handler, which copied whatever library file it named into the entity's resources. That let any user with collections.write or roms.write pull files they cannot otherwise read, including those of hidden platforms and ROMs. These endpoints now answer 400 for a local file URL, unless it is the value already stored, which the edit forms echo back on every save. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(resources): bound cover downloads and decodes Remote covers, screenshots, manuals, badges and media files were streamed to disk with no size limit, and a gzip-encoded body was read whole and inflated in memory. Downloads now go through one helper that counts bytes against MAX_ASSET_UPLOAD_SIZE_BYTES, inflates gzip incrementally under the same cap, and aborts past it, so the partial file is removed and any earlier copy kept. Covers are also bounded once on disk: a still image whose header declares more than MAX_COVER_PIXELS is discarded before it is decoded (and an uploaded one is refused with a 400), and a DecompressionBombError while deriving the small cover now discards the download instead of failing the request and leaving the file behind. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: fix mypy errors in the new tests Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: address Greptile review on permission and input hardening - Date OAuth tokens to before the credential check, so a password change that lands during the check revokes the tokens it issues. - Apply ROM visibility to play sessions in SQL, before the page slice. - Reject truncated gzip bodies and inflate every gzip member. - Shorten the zip budget comment; stream real httpx2 responses in tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: apply code-review findings on permission hardening Revoke OAuth tokens and sessions on user deletion, apply ROM visibility to GET /states/{id}, validate update_collection rom_ids, run get_rom_filters off the event loop, and reuse the shared httpx client factory for webhooks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: apply simplify pass on permission hardening Read the OAuth revocation stamp through the async cache, share the play-session batch-size check, raise a plain OSError for oversized downloads, and drop a dead slice in the LZ4 decoder. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * style: apply review-polish pass on permission hardening Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: state that ROM visibility is enforced as access control Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(assets): hide saves, states, screenshots and memory cards on hidden ROMs Visibility is access control, so per-id save/state/screenshot routes now 404 when the save's ROM is hidden from the caller (hidden ROM, hidden platform or age limit), and the save/state lists and identifier lists leave those rows out in SQL. GET /api/saves/summary 404s on a hidden ROM. Memory cards on a hidden platform 404 on every per-id route, drop out of both lists, and can't be created against a hidden platform. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(saves): answer a hidden ROM's save summary like a missing one Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(permissions): enforce ROM visibility in sync, installs and feeds Hidden ROMs/platforms and age-limited ROMs are access control, so the paths that skipped the caller's visibility now apply it: - sync negotiate: saves on hidden ROMs are neither offered, paired nor reported as conflicts; a client save on one negotiates like an unknown ROM - push-pull SSH sync: resolves the device owner's visibility and skips saves on hidden ROMs in both directions - device installs: list and claim leave out requests whose ROM became hidden (they stay pending), and outcome notifications don't name it - recommendations: a hidden seed ROM is no longer named - music playlists: track_count counts only tracks on visible ROMs - audit events: firmware targets on hidden platforms are filtered - setup library: supported platforms honour the caller's visibility - feeds: a hidden platform found by slug reads as missing Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(visibility): hide ROMs from virtual collections, stats and scan events Virtual collections apply the caller's visibility in SQL: a collection with no visible member is left out (404 by id), member ids and covers skip hidden ROMs, and the limit counts only visible collections. Stats save, state and screenshot totals skip assets of hidden ROMs. Scan events no longer broadcast to every socket. Progress and end events go to a scan room that sockets of users holding platforms.write or tasks.run join on connect. scanning_rom and scanning_platform go to the user rooms of those followers who can see that ROM or platform, resolved once per scan and grouped by visibility. get_rom_audience now builds on a shared get_user_visibilities. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: apply code-review findings on ROM visibility enforcement Match virtual collection members by ROM id, build the cover visibility clauses once, filter feed platforms by visibility in SQL, resolve every id before a batch save or state delete, filter push-pull saves in the query, and narrow the hides query to the requested users. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: apply simplify pass on ROM visibility enforcement Require an explicit visibility filter on the saves, states and memory card queries, share one roms_facets visibility join and one owned-asset helper, filter virtual collection members by hidden ids, batch the scan audience's scope lookup, and move the empty-room emit guard into socket_handler. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: start the scan audience before emitting from scan_rom Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: apply humanizer pass on the visibility rule Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(streaming): don't mount a memory card on a hidden platform Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: address Greptile review on ROM visibility enforcement Refresh a running scan's audience after a permission change, fix the precedence of the scan-room join assertion, and narrow mock await_args before reading them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * revert: drop per-visibility scan event audience Scan events go back to every socket. Removes handler/scan/audience.py, the scan room join on connect, the permissions generation bump and the batched OAuth scope resolution that only the audience used. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1502 lines
50 KiB
Python
1502 lines
50 KiB
Python
"""
|
|
Unit tests for DBSavesHandler platform filtering functionality.
|
|
|
|
This module tests the platform filtering fixes for DBSavesHandler to ensure
|
|
it properly filters by platform_id through the Rom relationship.
|
|
"""
|
|
|
|
import ast
|
|
from collections.abc import Callable
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from datetime import UTC, datetime
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from typing import Any
|
|
from unittest import mock
|
|
|
|
import pytest
|
|
from sqlalchemy import Delete, event
|
|
from sqlalchemy.exc import NoResultFound
|
|
from tests.app_sources import app_sources
|
|
from tests.factories import make_save
|
|
|
|
import handler.database.saves_handler as saves_handler_module
|
|
from handler.auth.rom_visibility import UNRESTRICTED
|
|
from handler.database import db_deleted_asset_handler, db_save_handler
|
|
from handler.database.base_handler import sync_engine
|
|
from models.assets import Save, SaveLineage
|
|
from models.platform import Platform
|
|
from models.rom import Rom
|
|
from models.user import User
|
|
from utils.datetime import to_utc
|
|
|
|
|
|
class TestDBSavesHandlerPlatformFiltering:
|
|
"""Test suite for platform filtering in DBSavesHandler."""
|
|
|
|
def test_get_saves_without_platform_filter(self, admin_user: User, save: Save):
|
|
"""Test that get_saves returns all saves when no platform filter is applied."""
|
|
saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id, visibility=UNRESTRICTED
|
|
)
|
|
|
|
assert len(saves) >= 1
|
|
save_ids = [save.id for save in saves]
|
|
assert save.id in save_ids
|
|
|
|
def test_get_saves_with_platform_filter(
|
|
self, admin_user: User, platform: Platform, save: Save
|
|
):
|
|
"""Test that get_saves filters correctly by platform_id."""
|
|
saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id, platform_id=platform.id, visibility=UNRESTRICTED
|
|
)
|
|
|
|
assert len(saves) == 1
|
|
assert saves[0].id == save.id
|
|
assert saves[0].file_name == "test_save.sav"
|
|
|
|
def test_get_saves_with_rom_id_and_platform_filter(
|
|
self, admin_user: User, platform: Platform, rom: Rom, save: Save
|
|
):
|
|
"""Test that get_saves works with both rom_id and platform_id filters."""
|
|
saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id,
|
|
rom_ids=[rom.id],
|
|
platform_id=platform.id,
|
|
visibility=UNRESTRICTED,
|
|
)
|
|
|
|
assert len(saves) == 1
|
|
assert saves[0].id == save.id
|
|
|
|
def test_get_saves_with_nonexistent_platform(self, admin_user: User, save: Save):
|
|
"""Test that get_saves returns empty list for nonexistent platform."""
|
|
saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id, platform_id=999, visibility=UNRESTRICTED
|
|
)
|
|
|
|
assert len(saves) == 0
|
|
|
|
def test_platform_filtering_relationship_integrity(
|
|
self, admin_user: User, platform: Platform, rom: Rom, save: Save
|
|
):
|
|
"""Test that platform filtering correctly uses the Rom relationship."""
|
|
assert rom.platform_id == platform.id
|
|
|
|
saves_platform = db_save_handler.get_saves(
|
|
user_id=admin_user.id, platform_id=platform.id, visibility=UNRESTRICTED
|
|
)
|
|
|
|
assert len(saves_platform) == 1
|
|
|
|
def test_multiple_saves_same_platform(self, admin_user: User, rom: Rom):
|
|
"""Test filtering with multiple saves on the same platform."""
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"save1.sav",
|
|
emulator="emulator1",
|
|
file_path=f"{rom.platform_slug}/saves/emulator1",
|
|
file_size_bytes=100,
|
|
)
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"save2.sav",
|
|
emulator="emulator2",
|
|
file_path=f"{rom.platform_slug}/saves/emulator2",
|
|
file_size_bytes=200,
|
|
)
|
|
|
|
# Filter by platform should return both saves
|
|
saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id, platform_id=rom.platform_id, visibility=UNRESTRICTED
|
|
)
|
|
|
|
assert len(saves) == 2
|
|
save_names = [save.file_name for save in saves]
|
|
assert "save1.sav" in save_names
|
|
assert "save2.sav" in save_names
|
|
|
|
def test_get_save_by_filename_with_platform_filter(
|
|
self, admin_user: User, rom: Rom, save: Save
|
|
):
|
|
"""Test that get_save_by_filename works correctly with platform filtering."""
|
|
retrieved_save = db_save_handler.get_save_by_filename(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
file_name=save.file_name,
|
|
emulator=save.emulator,
|
|
slot=save.slot,
|
|
)
|
|
|
|
assert retrieved_save is not None
|
|
assert retrieved_save.id == save.id
|
|
assert retrieved_save.file_name == save.file_name
|
|
|
|
def test_get_save_by_filename_slotless_ignores_slotted_save(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
"""A slot-less lookup must not match a same-named save in a named slot."""
|
|
slotted = make_save(
|
|
rom,
|
|
admin_user,
|
|
"shared.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="Slot A",
|
|
)
|
|
|
|
# No null-slot save exists, so a slot-less lookup should find nothing.
|
|
assert (
|
|
db_save_handler.get_save_by_filename(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
file_name="shared.sav",
|
|
emulator="test_emu",
|
|
slot=None,
|
|
)
|
|
is None
|
|
)
|
|
|
|
# The named-slot lookup still resolves the slotted save.
|
|
found = db_save_handler.get_save_by_filename(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
file_name="shared.sav",
|
|
emulator="test_emu",
|
|
slot="Slot A",
|
|
)
|
|
assert found is not None
|
|
assert found.id == slotted.id
|
|
|
|
def test_get_save_by_filename_slotted_ignores_slotless_save(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
"""A named-slot lookup must not match a same-named null-slot save."""
|
|
slotless = make_save(
|
|
rom,
|
|
admin_user,
|
|
"shared.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot=None,
|
|
)
|
|
|
|
assert (
|
|
db_save_handler.get_save_by_filename(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
file_name="shared.sav",
|
|
emulator="test_emu",
|
|
slot="Slot A",
|
|
)
|
|
is None
|
|
)
|
|
|
|
found = db_save_handler.get_save_by_filename(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
file_name="shared.sav",
|
|
emulator="test_emu",
|
|
slot=None,
|
|
)
|
|
assert found is not None
|
|
assert found.id == slotless.id
|
|
|
|
def test_get_save_by_filename_ignores_another_emulators_save(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
mgba = make_save(
|
|
rom, admin_user, "shared.sav", emulator="mgba", file_size_bytes=100
|
|
)
|
|
|
|
assert (
|
|
db_save_handler.get_save_by_filename(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
file_name="shared.sav",
|
|
emulator="snes9x",
|
|
)
|
|
is None
|
|
)
|
|
|
|
found = db_save_handler.get_save_by_filename(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
file_name="shared.sav",
|
|
emulator="mgba",
|
|
)
|
|
assert found is not None
|
|
assert found.id == mgba.id
|
|
|
|
def test_get_save_by_filename_without_emulator_prefers_unfiled_save(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
mgba = make_save(
|
|
rom, admin_user, "shared.sav", emulator="mgba", file_size_bytes=100
|
|
)
|
|
|
|
def lookup() -> Save | None:
|
|
return db_save_handler.get_save_by_filename(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
file_name="shared.sav",
|
|
emulator=None,
|
|
)
|
|
|
|
found = lookup()
|
|
assert found is not None
|
|
assert found.id == mgba.id
|
|
|
|
unfiled = make_save(
|
|
rom, admin_user, "shared.sav", emulator=None, file_size_bytes=100
|
|
)
|
|
found = lookup()
|
|
assert found is not None
|
|
assert found.id == unfiled.id
|
|
|
|
def test_platform_filtering_with_different_emulators(
|
|
self, admin_user: User, platform: Platform, rom: Rom
|
|
):
|
|
"""Test platform filtering with saves from different emulators."""
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"save_emu1.sav",
|
|
emulator="emulator1",
|
|
file_path=f"{platform.slug}/saves/emulator1",
|
|
file_size_bytes=100,
|
|
)
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"save_emu2.sav",
|
|
emulator="emulator2",
|
|
file_path=f"{platform.slug}/saves/emulator2",
|
|
file_size_bytes=200,
|
|
)
|
|
|
|
# Filter by platform should return both saves regardless of emulator
|
|
saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id, platform_id=platform.id, visibility=UNRESTRICTED
|
|
)
|
|
|
|
assert len(saves) == 2
|
|
emulators = [save.emulator for save in saves]
|
|
assert "emulator1" in emulators
|
|
assert "emulator2" in emulators
|
|
|
|
def test_get_save_by_id_with_platform_context(
|
|
self, admin_user: User, platform: Platform, save: Save
|
|
):
|
|
"""Test that get_save works correctly and maintains platform context."""
|
|
retrieved_save = db_save_handler.get_save(user_id=admin_user.id, id=save.id)
|
|
|
|
assert retrieved_save is not None
|
|
assert retrieved_save.id == save.id
|
|
assert retrieved_save.file_name == "test_save.sav"
|
|
|
|
# Verify the save is associated with the correct platform through ROM
|
|
assert retrieved_save.rom.platform_id == platform.id
|
|
|
|
|
|
class TestDBSavesHandlerSlotFiltering:
|
|
def test_get_saves_with_slot_filter(self, admin_user: User, rom: Rom):
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"slot_test_1.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="Slot A",
|
|
)
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"slot_test_2.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="Slot A",
|
|
)
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"slot_test_3.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="Slot B",
|
|
)
|
|
|
|
slot_a_saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id,
|
|
rom_ids=[rom.id],
|
|
slot="Slot A",
|
|
visibility=UNRESTRICTED,
|
|
)
|
|
assert len(slot_a_saves) == 2
|
|
assert all(s.slot == "Slot A" for s in slot_a_saves)
|
|
|
|
slot_b_saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id,
|
|
rom_ids=[rom.id],
|
|
slot="Slot B",
|
|
visibility=UNRESTRICTED,
|
|
)
|
|
assert len(slot_b_saves) == 1
|
|
assert slot_b_saves[0].slot == "Slot B"
|
|
|
|
@pytest.mark.parametrize(
|
|
"slot,sibling",
|
|
[("autosave", "Autosave"), ("Cafe", "Café"), ("autosave", "autosave ")],
|
|
ids=["case", "accent", "trailing-space"],
|
|
)
|
|
def test_a_slot_is_matched_exactly(
|
|
self, admin_user: User, rom: Rom, slot: str, sibling: str
|
|
):
|
|
"""Sync pairs slots in Python, so the database must not fold them."""
|
|
for index, name in enumerate((slot, sibling)):
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
f"exact_{index}.sav",
|
|
file_size_bytes=100,
|
|
slot=name,
|
|
content_hash=f"exact_{index}",
|
|
)
|
|
|
|
[found] = db_save_handler.get_saves(
|
|
user_id=admin_user.id, rom_ids=[rom.id], slot=slot, visibility=UNRESTRICTED
|
|
)
|
|
assert found.slot == slot
|
|
|
|
db_save_handler.prune_slot(
|
|
user_id=admin_user.id, rom_id=rom.id, slot=slot, keep=0
|
|
)
|
|
[kept] = db_save_handler.get_saves(
|
|
user_id=admin_user.id, rom_ids=[rom.id], visibility=UNRESTRICTED
|
|
)
|
|
assert kept.slot == sibling
|
|
|
|
def _lineage_versions(self, admin_user: User, rom: Rom, **overrides: Any) -> None:
|
|
for index, (file_name, emulator) in enumerate(
|
|
[
|
|
("old.srm", "snes9x"),
|
|
("new.SRM", "snes9x"),
|
|
("clock.rtc", "snes9x"),
|
|
("other.srm", "bsnes"),
|
|
]
|
|
):
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
file_name,
|
|
emulator=emulator,
|
|
file_size_bytes=100,
|
|
slot="autosave",
|
|
content_hash=f"lineage_{index}",
|
|
**overrides,
|
|
)
|
|
|
|
def test_a_prune_can_be_scoped_to_a_lineage(self, admin_user: User, rom: Rom):
|
|
self._lineage_versions(admin_user, rom)
|
|
|
|
db_save_handler.prune_slot(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
slot="autosave",
|
|
keep=1,
|
|
lineage=SaveLineage("snes9x", "srm"),
|
|
)
|
|
|
|
kept = db_save_handler.get_saves(
|
|
user_id=admin_user.id, rom_ids=[rom.id], visibility=UNRESTRICTED
|
|
)
|
|
assert {save.file_name for save in kept} == {
|
|
"new.SRM",
|
|
"clock.rtc",
|
|
"other.srm",
|
|
}
|
|
|
|
def test_lineage_heads_are_the_newest_on_disk_version_per_emulator(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
self._lineage_versions(admin_user, rom)
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"gone.srm",
|
|
emulator="snes9x",
|
|
slot="autosave",
|
|
missing_from_fs=True,
|
|
)
|
|
make_save(rom, admin_user, "named.srm", emulator="snes9x", slot="speedrun")
|
|
|
|
heads = db_save_handler.get_lineage_heads(
|
|
user_id=admin_user.id, slot="autosave", file_extension="srm"
|
|
)
|
|
head = db_save_handler.get_lineage_head(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
slot="autosave",
|
|
lineages=[SaveLineage("snes9x", "srm")],
|
|
)
|
|
|
|
assert sorted(save.file_name for save in heads) == ["new.SRM", "other.srm"]
|
|
assert head is not None and head.file_name == "new.SRM"
|
|
|
|
def test_a_lineage_head_is_the_newest_across_lineages(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
self._lineage_versions(admin_user, rom)
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"unfiled.srm",
|
|
emulator=None,
|
|
slot="autosave",
|
|
updated_at=datetime(2030, 1, 1, tzinfo=UTC),
|
|
)
|
|
|
|
def head(*lineages: SaveLineage) -> str | None:
|
|
save = db_save_handler.get_lineage_head(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
slot="autosave",
|
|
lineages=lineages,
|
|
)
|
|
return save.file_name if save else None
|
|
|
|
assert head(SaveLineage("snes9x", "srm"), SaveLineage(None, "srm")) == (
|
|
"unfiled.srm"
|
|
)
|
|
assert (
|
|
head(SaveLineage("snes9x", "srm"), SaveLineage("bsnes", "srm"))
|
|
== "other.srm"
|
|
)
|
|
assert head(SaveLineage(None, "rtc")) is None
|
|
assert head() is None
|
|
|
|
def test_get_saves_filters_on_a_set_of_lineages(self, admin_user: User, rom: Rom):
|
|
self._lineage_versions(admin_user, rom)
|
|
make_save(rom, admin_user, "unfiled.srm", emulator=None, slot="autosave")
|
|
|
|
def names(*lineages: SaveLineage) -> set[str]:
|
|
saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id,
|
|
rom_ids=[rom.id],
|
|
lineages=lineages,
|
|
visibility=UNRESTRICTED,
|
|
)
|
|
return {save.file_name for save in saves}
|
|
|
|
assert names(SaveLineage("bsnes", "srm"), SaveLineage(None, "srm")) == {
|
|
"other.srm",
|
|
"unfiled.srm",
|
|
}
|
|
assert names(SaveLineage("snes9x", "rtc"), SaveLineage("bsnes", "srm")) == {
|
|
"clock.rtc",
|
|
"other.srm",
|
|
}
|
|
assert names(SaveLineage(None, "srm")) == {"unfiled.srm"}
|
|
assert names() == set()
|
|
|
|
def test_get_saves_at_paths_matches_any_listed_folder(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
for file_path in ("saves/snes9x", "saves/bsnes", "saves/other"):
|
|
make_save(rom, admin_user, "game.srm", file_path=file_path)
|
|
make_save(rom, admin_user, "else.srm", file_path="saves/snes9x")
|
|
|
|
saves = db_save_handler.get_saves_at_paths(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
file_paths=["saves/snes9x", "saves/bsnes"],
|
|
file_name="game.srm",
|
|
)
|
|
|
|
assert sorted(save.file_path for save in saves) == [
|
|
"saves/bsnes",
|
|
"saves/snes9x",
|
|
]
|
|
|
|
def test_get_saves_at_paths_ignores_case(self, admin_user: User, rom: Rom):
|
|
make_save(rom, admin_user, "Game (Disc 1).srm", file_path="saves/snes9x")
|
|
|
|
saves = db_save_handler.get_saves_at_paths(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
file_paths=["saves/snes9x"],
|
|
file_name="game (disc 1).srm",
|
|
)
|
|
|
|
assert [save.file_name for save in saves] == ["Game (Disc 1).srm"]
|
|
|
|
def test_get_saves_with_null_slot_filter(self, admin_user: User, rom: Rom):
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"with_slot.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="Main",
|
|
)
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"without_slot.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot=None,
|
|
)
|
|
|
|
all_saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id, rom_ids=[rom.id], visibility=UNRESTRICTED
|
|
)
|
|
assert len(all_saves) >= 2
|
|
|
|
def test_get_saves_with_unslotted_widens_the_slot_filter(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
make_save(rom, admin_user, "autosave.srm", slot="autosave")
|
|
make_save(rom, admin_user, "named.srm", slot="Main")
|
|
make_save(rom, admin_user, "unslotted.srm", slot=None)
|
|
|
|
saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id,
|
|
rom_ids=[rom.id],
|
|
slot="autosave",
|
|
with_unslotted=True,
|
|
visibility=UNRESTRICTED,
|
|
)
|
|
|
|
assert {save.file_name for save in saves} == {"autosave.srm", "unslotted.srm"}
|
|
|
|
def test_get_saves_order_by(self, admin_user: User, rom: Rom):
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
base_time = datetime.now(timezone.utc)
|
|
|
|
created1 = make_save(
|
|
rom,
|
|
admin_user,
|
|
"order_test_1.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="order_test",
|
|
)
|
|
created2 = make_save(
|
|
rom,
|
|
admin_user,
|
|
"order_test_2.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="order_test",
|
|
)
|
|
|
|
db_save_handler.update_save(
|
|
created1.id, {"updated_at": base_time - timedelta(hours=2)}
|
|
)
|
|
db_save_handler.update_save(
|
|
created2.id, {"updated_at": base_time - timedelta(hours=1)}
|
|
)
|
|
|
|
ordered_saves_desc = db_save_handler.get_saves(
|
|
user_id=admin_user.id,
|
|
rom_ids=[rom.id],
|
|
slot="order_test",
|
|
order_by="updated_at",
|
|
visibility=UNRESTRICTED,
|
|
)
|
|
|
|
assert len(ordered_saves_desc) == 2
|
|
assert ordered_saves_desc[0].id == created2.id
|
|
assert ordered_saves_desc[1].id == created1.id
|
|
|
|
ordered_saves_asc = db_save_handler.get_saves(
|
|
user_id=admin_user.id,
|
|
rom_ids=[rom.id],
|
|
slot="order_test",
|
|
order_by="updated_at",
|
|
order_dir="asc",
|
|
visibility=UNRESTRICTED,
|
|
)
|
|
|
|
assert len(ordered_saves_asc) == 2
|
|
assert ordered_saves_asc[0].id == created1.id
|
|
assert ordered_saves_asc[1].id == created2.id
|
|
|
|
|
|
class TestDBSavesHandlerPromoteToSlotHead:
|
|
def test_outranks_a_head_from_the_same_second(self, admin_user: User, rom: Rom):
|
|
same_second = datetime.now(UTC).replace(microsecond=0)
|
|
older = make_save(rom, admin_user, "older.sav", slot="slot1")
|
|
head = make_save(rom, admin_user, "head.sav", slot="slot1")
|
|
db_save_handler.update_save(older.id, {"updated_at": same_second})
|
|
db_save_handler.update_save(head.id, {"updated_at": same_second})
|
|
|
|
promoted = db_save_handler.promote_to_slot_head(older)
|
|
|
|
assert to_utc(promoted.updated_at) > same_second
|
|
assert db_save_handler.get_save_ids(
|
|
user_id=admin_user.id,
|
|
rom_ids=[rom.id],
|
|
slot="slot1",
|
|
order_by="updated_at",
|
|
visibility=UNRESTRICTED,
|
|
) == [older.id, head.id]
|
|
|
|
def test_leaves_the_head_as_is(self, admin_user: User, rom: Rom):
|
|
head = make_save(rom, admin_user, "head.sav", slot="slot1")
|
|
written_at = datetime(2024, 1, 1, tzinfo=UTC)
|
|
head = db_save_handler.update_save(head.id, {"updated_at": written_at})
|
|
|
|
promoted = db_save_handler.promote_to_slot_head(head)
|
|
|
|
assert to_utc(promoted.updated_at) == written_at
|
|
|
|
|
|
class TestDBSavesHandlerGetSaveByContentHash:
|
|
"""Pin the slot filter behavior of get_save_by_content_hash (commit
|
|
3d71ef3f6). Legacy callers still pass slot=None and expect cross-slot
|
|
lookup, while sync negotiation passes a concrete slot value and expects
|
|
a strict match.
|
|
"""
|
|
|
|
def test_returns_row_matching_slot_when_multiple_slots_share_hash(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
"""Two rows share (rom_id, user_id, content_hash) but differ in slot.
|
|
A call with a specific slot must return the row with that slot, not
|
|
the other."""
|
|
shared_hash = "abc123abc123abc123abc123abc12345"
|
|
|
|
slot_a = make_save(
|
|
rom,
|
|
admin_user,
|
|
"hash_match_a.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="Slot A",
|
|
content_hash=shared_hash,
|
|
)
|
|
slot_b = make_save(
|
|
rom,
|
|
admin_user,
|
|
"hash_match_b.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="Slot B",
|
|
content_hash=shared_hash,
|
|
)
|
|
|
|
result_a = db_save_handler.get_save_by_content_hash(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
content_hash=shared_hash,
|
|
slot="Slot A",
|
|
)
|
|
assert result_a is not None
|
|
assert result_a.id == slot_a.id
|
|
|
|
result_b = db_save_handler.get_save_by_content_hash(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
content_hash=shared_hash,
|
|
slot="Slot B",
|
|
)
|
|
assert result_b is not None
|
|
assert result_b.id == slot_b.id
|
|
|
|
def test_returns_none_when_slot_does_not_match(self, admin_user: User, rom: Rom):
|
|
"""A single row exists. Querying with a different slot value returns
|
|
None, even though the (rom_id, user_id, content_hash) tuple matches."""
|
|
target_hash = "ffffffffffffffffffffffffffffffff"
|
|
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"only_slot.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="autosave",
|
|
content_hash=target_hash,
|
|
)
|
|
|
|
result = db_save_handler.get_save_by_content_hash(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
content_hash=target_hash,
|
|
slot="manual",
|
|
)
|
|
assert result is None
|
|
|
|
def test_slot_none_finds_row_with_concrete_slot(self, admin_user: User, rom: Rom):
|
|
"""Legacy / cross-slot lookup: passing slot=None must not filter by
|
|
slot at all and must still return the row, regardless of the row's
|
|
own slot value."""
|
|
target_hash = "1234567890abcdef1234567890abcdef"
|
|
|
|
created = make_save(
|
|
rom,
|
|
admin_user,
|
|
"cross_slot.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="autosave",
|
|
content_hash=target_hash,
|
|
)
|
|
|
|
result = db_save_handler.get_save_by_content_hash(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
content_hash=target_hash,
|
|
slot=None,
|
|
)
|
|
assert result is not None
|
|
assert result.id == created.id
|
|
|
|
|
|
class TestDBSavesHandlerSlotNotNullFilter:
|
|
"""Pin the slot_not_null kwarg: when true, archival/null-slot saves are
|
|
excluded; when false (default), they are returned alongside slot-bound
|
|
rows. Sync callsites use slot_not_null=True so the database does the
|
|
filter instead of pulling the whole table into Python."""
|
|
|
|
def test_slot_not_null_false_returns_both(self, admin_user: User, rom: Rom):
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"slotted.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="autosave",
|
|
)
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"archival.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot=None,
|
|
)
|
|
|
|
saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id, rom_ids=[rom.id], visibility=UNRESTRICTED
|
|
)
|
|
|
|
names = {s.file_name for s in saves}
|
|
assert "slotted.sav" in names
|
|
assert "archival.sav" in names
|
|
|
|
def test_slot_not_null_true_excludes_null_slot(self, admin_user: User, rom: Rom):
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"slotted_only.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="autosave",
|
|
)
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"archival_only.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot=None,
|
|
)
|
|
|
|
saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id,
|
|
rom_ids=[rom.id],
|
|
slot_not_null=True,
|
|
visibility=UNRESTRICTED,
|
|
)
|
|
|
|
names = {s.file_name for s in saves}
|
|
assert "slotted_only.sav" in names
|
|
assert "archival_only.sav" not in names
|
|
assert all(s.slot is not None for s in saves)
|
|
|
|
def test_slot_not_null_true_composes_with_slot_value(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
"""slot_not_null and slot can both be set; the explicit slot filter
|
|
wins (and is implicitly not-null), so slot_not_null=True is a no-op
|
|
in that case. Pin that behavior so callers don't have to reason
|
|
about the interaction."""
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"compose_a.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="A",
|
|
)
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
"compose_b.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="B",
|
|
)
|
|
|
|
saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id,
|
|
rom_ids=[rom.id],
|
|
slot="A",
|
|
slot_not_null=True,
|
|
visibility=UNRESTRICTED,
|
|
)
|
|
|
|
assert len(saves) == 1
|
|
assert saves[0].slot == "A"
|
|
|
|
|
|
class TestDBSavesHandlerGetSavesAfterId:
|
|
"""Cover keyset pagination used by the recompute_save_content_hashes
|
|
maintenance task. Per-page bounded reads avoid materializing the full
|
|
saves table on instances with very large libraries."""
|
|
|
|
def test_paginates_in_order_and_terminates(self, admin_user: User, rom: Rom):
|
|
created_ids = []
|
|
for i in range(5):
|
|
created = make_save(
|
|
rom,
|
|
admin_user,
|
|
f"page_{i}.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot=f"slot_{i}",
|
|
)
|
|
created_ids.append(created.id)
|
|
|
|
seen: list[int] = []
|
|
last_id = 0
|
|
while True:
|
|
batch = db_save_handler.get_saves_after_id(after_id=last_id, limit=2)
|
|
if not batch:
|
|
break
|
|
for s in batch:
|
|
seen.append(s.id)
|
|
last_id = s.id
|
|
|
|
for cid in created_ids:
|
|
assert cid in seen
|
|
# IDs returned monotonically by primary key
|
|
assert seen == sorted(seen)
|
|
|
|
def test_after_id_excludes_anchor_row(self, admin_user: User, rom: Rom):
|
|
created = make_save(
|
|
rom,
|
|
admin_user,
|
|
"anchor.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="anchor_slot",
|
|
)
|
|
|
|
batch = db_save_handler.get_saves_after_id(after_id=created.id, limit=10)
|
|
|
|
assert all(s.id > created.id for s in batch)
|
|
|
|
|
|
class TestDBSavesHandlerSummary:
|
|
def test_get_saves_summary_basic(self, admin_user: User, rom: Rom):
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
base_time = datetime.now(timezone.utc)
|
|
|
|
configs = [
|
|
("summary_a_1.sav", "Slot A", -3),
|
|
("summary_a_2.sav", "Slot A", -1),
|
|
("summary_b_1.sav", "Slot B", -2),
|
|
("summary_none_1.sav", None, -4),
|
|
]
|
|
|
|
for filename, slot, hours_offset in configs:
|
|
created = make_save(
|
|
rom,
|
|
admin_user,
|
|
filename,
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot=slot,
|
|
)
|
|
db_save_handler.update_save(
|
|
created.id, {"updated_at": base_time + timedelta(hours=hours_offset)}
|
|
)
|
|
|
|
summary = db_save_handler.get_saves_summary(
|
|
user_id=admin_user.id, rom_id=rom.id
|
|
)
|
|
|
|
assert "total_count" in summary
|
|
assert "slots" in summary
|
|
assert summary["total_count"] == 4
|
|
assert len(summary["slots"]) == 3
|
|
|
|
def test_get_saves_summary_latest_per_slot(self, admin_user: User, rom: Rom):
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
base_time = datetime.now(timezone.utc)
|
|
|
|
old_created = make_save(
|
|
rom,
|
|
admin_user,
|
|
"latest_test_old.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="latest_test",
|
|
)
|
|
new_created = make_save(
|
|
rom,
|
|
admin_user,
|
|
"latest_test_new.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="latest_test",
|
|
)
|
|
|
|
db_save_handler.update_save(
|
|
old_created.id, {"updated_at": base_time - timedelta(hours=5)}
|
|
)
|
|
db_save_handler.update_save(
|
|
new_created.id, {"updated_at": base_time - timedelta(hours=1)}
|
|
)
|
|
|
|
summary = db_save_handler.get_saves_summary(
|
|
user_id=admin_user.id, rom_id=rom.id
|
|
)
|
|
|
|
latest_slot = next(
|
|
(s for s in summary["slots"] if s["slot"] == "latest_test"), None
|
|
)
|
|
assert latest_slot is not None
|
|
assert latest_slot["count"] == 2
|
|
assert latest_slot["latest"].file_name == "latest_test_new.sav"
|
|
|
|
def test_get_saves_summary_empty_rom(self, admin_user: User):
|
|
summary = db_save_handler.get_saves_summary(
|
|
user_id=admin_user.id, rom_id=999999
|
|
)
|
|
|
|
assert summary["total_count"] == 0
|
|
assert summary["slots"] == []
|
|
|
|
def test_get_saves_summary_count_accuracy(self, admin_user: User, rom: Rom):
|
|
for i in range(5):
|
|
make_save(
|
|
rom,
|
|
admin_user,
|
|
f"count_test_{i}.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
slot="count_test",
|
|
)
|
|
|
|
summary = db_save_handler.get_saves_summary(
|
|
user_id=admin_user.id, rom_id=rom.id
|
|
)
|
|
|
|
count_slot = next(
|
|
(s for s in summary["slots"] if s["slot"] == "count_test"), None
|
|
)
|
|
assert count_slot is not None
|
|
assert count_slot["count"] == 5
|
|
|
|
|
|
class TestDBSavesHandlerGetLatestSavesForRoms:
|
|
"""Cover the continue-playing rail's batch lookup of the newest save per
|
|
ROM."""
|
|
|
|
def test_returns_newest_save_per_rom(self, admin_user: User, rom: Rom):
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
base_time = datetime.now(timezone.utc)
|
|
|
|
older = make_save(
|
|
rom,
|
|
admin_user,
|
|
"latest_old.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
)
|
|
newer = make_save(
|
|
rom,
|
|
admin_user,
|
|
"latest_new.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
)
|
|
db_save_handler.update_save(
|
|
older.id, {"updated_at": base_time - timedelta(hours=2)}
|
|
)
|
|
db_save_handler.update_save(
|
|
newer.id, {"updated_at": base_time - timedelta(hours=1)}
|
|
)
|
|
|
|
latest = db_save_handler.get_latest_saves_for_roms(
|
|
user_id=admin_user.id, rom_ids=[rom.id]
|
|
)
|
|
|
|
assert set(latest.keys()) == {rom.id}
|
|
assert latest[rom.id].id == newer.id
|
|
|
|
def test_empty_rom_ids_returns_empty_dict(self, admin_user: User):
|
|
assert (
|
|
db_save_handler.get_latest_saves_for_roms(user_id=admin_user.id, rom_ids=[])
|
|
== {}
|
|
)
|
|
|
|
def test_excludes_other_users_saves(
|
|
self, admin_user: User, editor_user: User, rom: Rom
|
|
):
|
|
make_save(
|
|
rom,
|
|
editor_user,
|
|
"other_user.sav",
|
|
emulator="test_emu",
|
|
file_size_bytes=100,
|
|
)
|
|
|
|
latest = db_save_handler.get_latest_saves_for_roms(
|
|
user_id=admin_user.id, rom_ids=[rom.id]
|
|
)
|
|
|
|
assert latest == {}
|
|
|
|
|
|
class TestGetSavesRomIdsScope:
|
|
"""Test suite for the `rom_ids` scope on DBSavesHandler.get_saves."""
|
|
|
|
def test_scopes_to_listed_roms(
|
|
self, admin_user: User, rom: Rom, save: Save, second_save: Save
|
|
):
|
|
saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id, rom_ids=[rom.id], visibility=UNRESTRICTED
|
|
)
|
|
|
|
assert [s.id for s in saves] == [save.id]
|
|
|
|
def test_scopes_to_multiple_roms(
|
|
self,
|
|
admin_user: User,
|
|
rom: Rom,
|
|
second_rom: Rom,
|
|
save: Save,
|
|
second_save: Save,
|
|
):
|
|
saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id,
|
|
rom_ids=[rom.id, second_rom.id],
|
|
visibility=UNRESTRICTED,
|
|
)
|
|
|
|
assert {s.id for s in saves} == {save.id, second_save.id}
|
|
|
|
def test_empty_scope_returns_nothing(self, admin_user: User, save: Save):
|
|
assert (
|
|
db_save_handler.get_saves(
|
|
user_id=admin_user.id, rom_ids=[], visibility=UNRESTRICTED
|
|
)
|
|
== []
|
|
)
|
|
|
|
def test_omitted_scope_returns_everything(self, admin_user: User, save: Save):
|
|
saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id, rom_ids=None, visibility=UNRESTRICTED
|
|
)
|
|
|
|
assert save.id in [s.id for s in saves]
|
|
|
|
def test_combines_with_slot_filter(
|
|
self, admin_user: User, rom: Rom, save: Save, archival_save: Save
|
|
):
|
|
saves = db_save_handler.get_saves(
|
|
user_id=admin_user.id,
|
|
rom_ids=[rom.id],
|
|
slot_not_null=True,
|
|
visibility=UNRESTRICTED,
|
|
)
|
|
|
|
assert [s.id for s in saves] == [save.id]
|
|
|
|
|
|
class TestDBSavesHandlerRecordsLostVersions:
|
|
"""Every way a version leaves its slot is remembered for sync."""
|
|
|
|
@staticmethod
|
|
def _add(
|
|
user: User, rom: Rom, stem: str, slot: str | None, content_hash: str | None
|
|
) -> Save:
|
|
return make_save(
|
|
rom,
|
|
user,
|
|
f"{stem}.sav",
|
|
file_size_bytes=100,
|
|
slot=slot,
|
|
content_hash=content_hash,
|
|
)
|
|
|
|
@staticmethod
|
|
def _lost(user: User, rom: Rom) -> dict[str, list[str]]:
|
|
return {
|
|
record.slot: record.content_hashes
|
|
for record in db_deleted_asset_handler.get_deletions(
|
|
user_id=user.id, rom_ids=[rom.id]
|
|
)
|
|
}
|
|
|
|
def test_a_deleted_version_is_recorded(self, admin_user: User, rom: Rom):
|
|
save = self._add(admin_user, rom, "deleted", "autosave", "gone")
|
|
|
|
db_save_handler.delete_save(save.id)
|
|
|
|
assert self._lost(admin_user, rom) == {"autosave": ["gone"]}
|
|
|
|
def test_a_deleted_version_never_hashed_takes_the_callers_hash(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
save = self._add(admin_user, rom, "unhashed", "autosave", None)
|
|
|
|
db_save_handler.delete_save(save.id, content_hash="from_file")
|
|
|
|
assert self._lost(admin_user, rom) == {"autosave": ["from_file"]}
|
|
|
|
def test_a_save_outside_any_slot_is_not_recorded(self, admin_user: User, rom: Rom):
|
|
save = self._add(admin_user, rom, "archival", None, "archived")
|
|
|
|
db_save_handler.delete_save(save.id)
|
|
|
|
assert self._lost(admin_user, rom) == {}
|
|
|
|
def test_pruned_versions_are_recorded(self, admin_user: User, rom: Rom):
|
|
for index in range(3):
|
|
save = self._add(admin_user, rom, f"v{index}", "autosave", f"v{index}")
|
|
db_save_handler.update_save(
|
|
save.id, {"updated_at": datetime(2026, 1, 1 + index, tzinfo=UTC)}
|
|
)
|
|
|
|
db_save_handler.prune_slot(
|
|
user_id=admin_user.id, rom_id=rom.id, slot="autosave", keep=1
|
|
)
|
|
|
|
assert self._lost(admin_user, rom) == {"autosave": ["v0", "v1"]}
|
|
|
|
def test_a_prune_hands_back_versions_it_has_no_hash_for(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
for index, content_hash in enumerate([None, "hashed", None]):
|
|
save = self._add(admin_user, rom, f"v{index}", "autosave", content_hash)
|
|
db_save_handler.update_save(
|
|
save.id, {"updated_at": datetime(2026, 1, 1 + index, tzinfo=UTC)}
|
|
)
|
|
|
|
with pytest.raises(saves_handler_module.UnhashedVersions) as raised:
|
|
db_save_handler.prune_slot(
|
|
user_id=admin_user.id, rom_id=rom.id, slot="autosave", keep=1
|
|
)
|
|
[unhashed] = raised.value.versions
|
|
assert unhashed.file_name == "v0.sav"
|
|
assert (
|
|
len(
|
|
db_save_handler.get_saves(
|
|
user_id=admin_user.id, visibility=UNRESTRICTED
|
|
)
|
|
)
|
|
== 3
|
|
)
|
|
|
|
db_save_handler.prune_slot(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
slot="autosave",
|
|
keep=1,
|
|
fallback_hashes={unhashed.id: "from_file"},
|
|
)
|
|
|
|
assert self._lost(admin_user, rom) == {"autosave": ["from_file", "hashed"]}
|
|
|
|
def test_an_overwritten_version_never_hashed_takes_the_callers_hash(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
save = self._add(admin_user, rom, "unhashed", "autosave", None)
|
|
|
|
db_save_handler.update_save(
|
|
save.id, {"content_hash": "new"}, replaced_hash="from_file"
|
|
)
|
|
|
|
assert self._lost(admin_user, rom) == {"autosave": ["from_file"]}
|
|
|
|
def test_a_version_overwritten_since_it_was_read_is_recorded(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
"""Two overwrites racing: the second replaces what the first wrote."""
|
|
save = self._add(admin_user, rom, "raced", "autosave", "v0")
|
|
stale = db_save_handler._slot_version(save.id)
|
|
db_save_handler.update_save(save.id, {"content_hash": "v1"})
|
|
|
|
with mock.patch.object(db_save_handler, "_slot_version", return_value=stale):
|
|
db_save_handler.update_save(save.id, {"content_hash": "v2"})
|
|
|
|
assert self._lost(admin_user, rom) == {"autosave": ["v0", "v1"]}
|
|
|
|
def test_a_version_moved_since_it_was_read_is_retried_in_its_new_slot(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
save = self._add(admin_user, rom, "moved", "autosave", "v0")
|
|
moved_from = SimpleNamespace(
|
|
user_id=admin_user.id, rom_id=rom.id, slot="manual", content_hash="v0"
|
|
)
|
|
pre_reads = iter([moved_from])
|
|
read_current = db_save_handler._slot_version
|
|
|
|
with mock.patch.object(
|
|
db_save_handler,
|
|
"_slot_version",
|
|
side_effect=lambda id: next(pre_reads, None) or read_current(id),
|
|
) as pre_read:
|
|
db_save_handler.update_save(save.id, {"content_hash": "v1"})
|
|
|
|
assert pre_read.call_count == 2
|
|
current = db_save_handler.get_save(admin_user.id, save.id)
|
|
assert current is not None
|
|
assert current.content_hash == "v1"
|
|
assert self._lost(admin_user, rom)["autosave"] == ["v0"]
|
|
|
|
def test_a_version_that_keeps_moving_gives_up(self, admin_user: User, rom: Rom):
|
|
save = self._add(admin_user, rom, "moving", "autosave", "v0")
|
|
moved_from = SimpleNamespace(
|
|
user_id=admin_user.id, rom_id=rom.id, slot="manual", content_hash="v0"
|
|
)
|
|
|
|
with (
|
|
mock.patch.object(
|
|
db_save_handler, "_slot_version", return_value=moved_from
|
|
),
|
|
pytest.raises(saves_handler_module._SlotMoved),
|
|
):
|
|
db_save_handler.delete_save(save.id)
|
|
|
|
current = db_save_handler.get_save(admin_user.id, save.id)
|
|
assert current is not None
|
|
assert current.content_hash == "v0"
|
|
|
|
def test_a_prune_that_fails_records_nothing(self, admin_user: User, rom: Rom):
|
|
"""The record commits with the removal, so no negotiation sees one alone."""
|
|
self._add(admin_user, rom, "kept", "autosave", "kept")
|
|
|
|
# Raised before a cursor exists: failing inside one leaves the MariaDB
|
|
# driver's pooled connection unusable, and the next checkout crashes.
|
|
def fail_the_delete(_conn: Any, statement: Any, *_: Any) -> None:
|
|
if isinstance(statement, Delete) and statement.table.description == "saves":
|
|
raise RuntimeError("delete failed")
|
|
|
|
event.listen(sync_engine, "before_execute", fail_the_delete)
|
|
try:
|
|
with pytest.raises(RuntimeError):
|
|
db_save_handler.prune_slot(
|
|
user_id=admin_user.id, rom_id=rom.id, slot="autosave", keep=0
|
|
)
|
|
finally:
|
|
event.remove(sync_engine, "before_execute", fail_the_delete)
|
|
|
|
assert self._lost(admin_user, rom) == {"autosave": []}
|
|
assert db_save_handler.get_saves(
|
|
user_id=admin_user.id, rom_ids=[rom.id], visibility=UNRESTRICTED
|
|
)
|
|
|
|
def test_a_loss_the_first_read_missed_is_still_recorded(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
save = self._add(admin_user, rom, "missed", "autosave", "old")
|
|
looks_unchanged = SimpleNamespace(
|
|
user_id=admin_user.id, rom_id=rom.id, slot="autosave", content_hash="new"
|
|
)
|
|
|
|
with mock.patch.object(
|
|
db_save_handler, "_slot_version", return_value=looks_unchanged
|
|
):
|
|
db_save_handler.update_save(save.id, {"content_hash": "new"})
|
|
|
|
assert self._lost(admin_user, rom) == {"autosave": ["old"]}
|
|
|
|
def test_concurrent_removals_record_every_lost_version(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
"""One lock order, the slot's record before its rows, so none deadlock."""
|
|
# Five slots against four kinds of write, so every pair races on a slot.
|
|
saves = [
|
|
self._add(admin_user, rom, f"c{index}", f"slot{index % 5}", f"c{index}")
|
|
for index in range(120)
|
|
]
|
|
|
|
def remove(index: int) -> None:
|
|
save = saves[index]
|
|
try:
|
|
if index % 4 == 0:
|
|
db_save_handler.delete_save(save.id)
|
|
elif index % 4 == 1:
|
|
db_save_handler.update_save(save.id, {"content_hash": f"n{index}"})
|
|
elif index % 4 == 2:
|
|
db_save_handler.prune_slot(
|
|
user_id=admin_user.id,
|
|
rom_id=rom.id,
|
|
slot=f"slot{index % 5}",
|
|
keep=3,
|
|
)
|
|
else:
|
|
# Writes a row a prune may be deleting, without the slot's lock.
|
|
db_save_handler.update_save(
|
|
save.id, {"is_favorite": True}, touch=False
|
|
)
|
|
except NoResultFound:
|
|
pass # A prune removed the row first.
|
|
|
|
with ThreadPoolExecutor(max_workers=12) as pool:
|
|
list(pool.map(remove, range(120)))
|
|
|
|
remaining = {
|
|
save.content_hash
|
|
for save in db_save_handler.get_saves(
|
|
user_id=admin_user.id, rom_ids=[rom.id], visibility=UNRESTRICTED
|
|
)
|
|
}
|
|
lost = {h for hashes in self._lost(admin_user, rom).values() for h in hashes}
|
|
assert {save.content_hash for save in saves} - remaining <= lost
|
|
|
|
@pytest.mark.parametrize("path", ["delete", "prune", "overwrite"])
|
|
def test_recording_never_checks_out_a_second_connection(
|
|
self, admin_user: User, rom: Rom, path: str
|
|
):
|
|
"""A second checkout per removal would starve the pool under load."""
|
|
save = self._add(admin_user, rom, "pooled", "autosave", "pooled")
|
|
checked_out: dict[str, int] = {}
|
|
deleted_assets = saves_handler_module._deleted_assets
|
|
ensure, record = deleted_assets.ensure_record, deleted_assets.record_deletions
|
|
|
|
def spy(name: str, wrapped: Callable[..., Any]) -> Callable[..., Any]:
|
|
def call(*args: Any, **kwargs: Any) -> Any:
|
|
checked_out[name] = sync_engine.pool.checkedout() # type: ignore[attr-defined]
|
|
return wrapped(*args, **kwargs)
|
|
|
|
return call
|
|
|
|
with (
|
|
mock.patch.object(deleted_assets, "ensure_record", spy("ensure", ensure)),
|
|
mock.patch.object(
|
|
deleted_assets, "record_deletions", spy("record", record)
|
|
),
|
|
):
|
|
if path == "delete":
|
|
db_save_handler.delete_save(save.id)
|
|
elif path == "prune":
|
|
db_save_handler.prune_slot(
|
|
user_id=admin_user.id, rom_id=rom.id, slot="autosave", keep=0
|
|
)
|
|
else:
|
|
db_save_handler.update_save(save.id, {"content_hash": "new"})
|
|
|
|
# Ensuring runs before the removal holds one; recording joins it.
|
|
assert checked_out == {"ensure": 0, "record": 1}
|
|
|
|
def test_an_overwritten_version_is_recorded(self, admin_user: User, rom: Rom):
|
|
save = self._add(admin_user, rom, "overwritten", "autosave", "before")
|
|
|
|
db_save_handler.update_save(save.id, {"content_hash": "after"})
|
|
|
|
assert self._lost(admin_user, rom) == {"autosave": ["before"]}
|
|
|
|
def test_a_version_moved_to_another_slot_is_recorded_in_the_first(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
save = self._add(admin_user, rom, "moved", "autosave", "moved")
|
|
|
|
db_save_handler.update_save(save.id, {"slot": "main_quest"})
|
|
|
|
assert self._lost(admin_user, rom) == {"autosave": ["moved"]}
|
|
|
|
def test_a_recomputed_hash_of_the_same_bytes_records_nothing(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
save = self._add(admin_user, rom, "rehashed", "autosave", "raw_md5")
|
|
|
|
assert db_save_handler.rehash_save(save.id, "entries_md5", replacing="raw_md5")
|
|
assert self._lost(admin_user, rom) == {}
|
|
|
|
def test_a_recomputed_hash_keeps_the_saves_timestamp(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
"""Device sync reads `updated_at` as a write, and the bytes are unchanged."""
|
|
save = self._add(admin_user, rom, "rehashed", "autosave", "raw_md5")
|
|
written = datetime(2026, 1, 1, tzinfo=UTC)
|
|
db_save_handler.update_save(save.id, {"updated_at": written})
|
|
|
|
db_save_handler.rehash_save(save.id, "entries_md5", replacing="raw_md5")
|
|
|
|
[kept] = db_save_handler.get_saves(
|
|
user_id=admin_user.id, rom_ids=[rom.id], visibility=UNRESTRICTED
|
|
)
|
|
assert kept.content_hash == "entries_md5"
|
|
assert to_utc(kept.updated_at) == written
|
|
|
|
def test_a_recomputed_hash_never_replaces_a_newer_one(
|
|
self, admin_user: User, rom: Rom
|
|
):
|
|
save = self._add(admin_user, rom, "rewritten", "autosave", "newer")
|
|
|
|
assert not db_save_handler.rehash_save(
|
|
save.id, "entries_md5", replacing="read_before"
|
|
)
|
|
[kept] = db_save_handler.get_saves(
|
|
user_id=admin_user.id, rom_ids=[rom.id], visibility=UNRESTRICTED
|
|
)
|
|
assert kept.content_hash == "newer"
|
|
|
|
@pytest.mark.parametrize(
|
|
"data",
|
|
[{"content_hash": "same"}, {"is_favorite": True}],
|
|
ids=["same-bytes", "annotation"],
|
|
)
|
|
def test_an_update_that_keeps_the_version_records_nothing(
|
|
self, admin_user: User, rom: Rom, data: dict[str, Any]
|
|
):
|
|
save = self._add(admin_user, rom, "kept", "autosave", "same")
|
|
|
|
db_save_handler.update_save(save.id, data)
|
|
|
|
assert not any(self._lost(admin_user, rom).values())
|
|
|
|
|
|
SAVES_HANDLER = Path("handler", "database", "saves_handler.py")
|
|
|
|
|
|
def _writes_save_rows(node: ast.Call) -> bool:
|
|
"""Whether `node` is `delete(Save)`, `update(Save)` or `.query(Save)...delete()`."""
|
|
func = node.func
|
|
name = func.id if isinstance(func, ast.Name) else getattr(func, "attr", None)
|
|
if name not in {"delete", "update"}:
|
|
return False
|
|
if any(isinstance(arg, ast.Name) and arg.id == "Save" for arg in node.args):
|
|
return True
|
|
return isinstance(func, ast.Attribute) and "query(Save)" in ast.unparse(func.value)
|
|
|
|
|
|
def test_only_the_saves_handler_writes_save_rows():
|
|
"""The handler records every version leaving a slot, so nothing may go around it."""
|
|
offenders = []
|
|
for relative, tree in app_sources():
|
|
if relative == SAVES_HANDLER:
|
|
continue
|
|
offenders += [
|
|
f"{relative}:{node.lineno}"
|
|
for node in ast.walk(tree)
|
|
if isinstance(node, ast.Call) and _writes_save_rows(node)
|
|
]
|
|
|
|
assert offenders == []
|