mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 10:01:00 +01:00
Merge pull request #4807 from rommapp/claude/sync-deleted-saves-followup
fix(sync): follow-ups to deleted-save tracking
This commit is contained in:
@@ -24,6 +24,24 @@ SLOT_COLUMNS = (("saves", True), ("deleted_assets", False))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column(
|
||||
"deleted_assets",
|
||||
sa.Column("removed_at", CustomJSON(), nullable=True),
|
||||
if_not_exists=True,
|
||||
)
|
||||
collation = exact_collation(op.get_bind())
|
||||
if collation is not None:
|
||||
for table, nullable in SLOT_COLUMNS:
|
||||
# Skipped once done, so a run that died partway resumes without a rebuild.
|
||||
if _slot_collation(table) != collation:
|
||||
op.alter_column(
|
||||
table,
|
||||
"slot",
|
||||
existing_type=sa.String(length=SAVE_SLOT_MAX_LENGTH),
|
||||
type_=sa.String(length=SAVE_SLOT_MAX_LENGTH, collation=collation),
|
||||
existing_nullable=nullable,
|
||||
)
|
||||
# After the collation change, which would otherwise rebuild it.
|
||||
op.create_index(
|
||||
SAVE_SLOT_VERSIONS_INDEX,
|
||||
"saves",
|
||||
@@ -32,24 +50,6 @@ def upgrade() -> None:
|
||||
["rom_id", "user_id", "slot", "updated_at"],
|
||||
if_not_exists=True,
|
||||
)
|
||||
op.add_column(
|
||||
"deleted_assets",
|
||||
sa.Column("removed_at", CustomJSON(), nullable=True),
|
||||
if_not_exists=True,
|
||||
)
|
||||
collation = exact_collation(op.get_bind())
|
||||
if collation is None:
|
||||
return
|
||||
for table, nullable in SLOT_COLUMNS:
|
||||
# Skipped once done, so a run that died partway resumes without a rebuild.
|
||||
if _slot_collation(table) != collation:
|
||||
op.alter_column(
|
||||
table,
|
||||
"slot",
|
||||
existing_type=sa.String(length=SAVE_SLOT_MAX_LENGTH),
|
||||
type_=sa.String(length=SAVE_SLOT_MAX_LENGTH, collation=collation),
|
||||
existing_nullable=nullable,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
|
||||
@@ -17,7 +17,6 @@ from handler.asset_store import (
|
||||
prune_save_slot,
|
||||
remove_save,
|
||||
rename_asset,
|
||||
unrecorded_hash,
|
||||
)
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import assert_rom_visible
|
||||
@@ -288,7 +287,9 @@ async def add_save(
|
||||
)
|
||||
)
|
||||
replaced = db_save or colliding_save
|
||||
replaced_hash = await unrecorded_hash(replaced) if replaced else None
|
||||
replaced_hash = (
|
||||
await fs_asset_handler.unrecorded_hash(replaced) if replaced else None
|
||||
)
|
||||
await fs_asset_handler.write_file(
|
||||
file=saveFile, path=saves_path, filename=actual_filename
|
||||
)
|
||||
@@ -622,6 +623,7 @@ async def update_save(
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
if saveFile:
|
||||
replaced_hash = await fs_asset_handler.unrecorded_hash(db_save)
|
||||
await fs_asset_handler.write_file(
|
||||
file=saveFile, path=db_save.file_path, filename=db_save.file_name
|
||||
)
|
||||
@@ -638,6 +640,7 @@ async def update_save(
|
||||
"file_size_bytes": scanned_save.file_size_bytes,
|
||||
"content_hash": scanned_save.content_hash,
|
||||
},
|
||||
replaced_hash=replaced_hash,
|
||||
)
|
||||
|
||||
if screenshotFile and screenshotFile.filename:
|
||||
|
||||
@@ -10,7 +10,6 @@ from urllib.parse import quote
|
||||
from fastapi import APIRouter, Request, Response, UploadFile, status
|
||||
from fastapi.responses import JSONResponse, RedirectResponse
|
||||
|
||||
from handler.asset_store import unrecorded_hash
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import get_permissions
|
||||
from handler.auth.permissions import ResolvedPermissions
|
||||
@@ -570,7 +569,9 @@ async def retroarch_sync_put(request: Request, file_path: str) -> Response:
|
||||
existing = _get_asset(request.user, rom, parsed)
|
||||
write_file_name = existing.file_name if existing else file_name
|
||||
replaced_hash = (
|
||||
await unrecorded_hash(existing) if isinstance(existing, Save) else None
|
||||
await fs_asset_handler.unrecorded_hash(existing)
|
||||
if isinstance(existing, Save)
|
||||
else None
|
||||
)
|
||||
|
||||
async with _request_body(request) as body:
|
||||
@@ -664,7 +665,9 @@ async def retroarch_sync_delete(request: Request, file_path: str) -> Response:
|
||||
if isinstance(asset, Screenshot):
|
||||
db_screenshot_handler.delete_screenshot(asset.id)
|
||||
elif isinstance(asset, Save):
|
||||
db_save_handler.delete_save(asset.id, content_hash=await unrecorded_hash(asset))
|
||||
db_save_handler.delete_save(
|
||||
asset.id, content_hash=await fs_asset_handler.unrecorded_hash(asset)
|
||||
)
|
||||
else:
|
||||
db_state_handler.delete_state(asset.id)
|
||||
|
||||
|
||||
@@ -154,16 +154,11 @@ async def release_thumbnail(screenshot: Screenshot | None) -> None:
|
||||
await remove_asset_file(path, "Screenshot file")
|
||||
|
||||
|
||||
async def unrecorded_hash(save: Save) -> str | None:
|
||||
"""The file's hash for a slotted save never hashed, so its removal is still recorded."""
|
||||
if save.slot and not save.content_hash:
|
||||
return await fs_asset_handler.compute_content_hash(save.full_path)
|
||||
return None
|
||||
|
||||
|
||||
async def remove_save(save: Save) -> None:
|
||||
"""Drop a save row with its file and screenshot."""
|
||||
db_save_handler.delete_save(save.id, content_hash=await unrecorded_hash(save))
|
||||
db_save_handler.delete_save(
|
||||
save.id, content_hash=await fs_asset_handler.unrecorded_hash(save)
|
||||
)
|
||||
await remove_asset_file(save.full_path, "Save file")
|
||||
await release_thumbnail(save.screenshot)
|
||||
|
||||
|
||||
@@ -99,17 +99,16 @@ class DBDeletedAssetsHandler(DBBaseHandler):
|
||||
record = self.lock_record(user_id, rom_id, slot, session)
|
||||
if record is None:
|
||||
raise
|
||||
# Read before the flush bumps `updated_at`, which unstamped versions fall back to.
|
||||
previous = record.removal_times()
|
||||
# A version lost again moves to the end, so trimming keeps it.
|
||||
lost = dict.fromkeys(content_hashes)
|
||||
hashes = [h for h in record.content_hashes if h not in lost] + list(lost)
|
||||
hashes = hashes[-MAX_REMEMBERED_HASHES:]
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
stamped = record.removed_at or {}
|
||||
record.content_hashes = hashes
|
||||
record.removed_at = {
|
||||
h: now if h in lost else stamped[h]
|
||||
for h in hashes
|
||||
if h in lost or h in stamped
|
||||
h: now if h in lost else previous[h].isoformat() for h in hashes
|
||||
}
|
||||
session.flush()
|
||||
return record
|
||||
|
||||
@@ -337,10 +337,11 @@ class DBSavesHandler(DBBaseHandler):
|
||||
Returns:
|
||||
Whether the row still held ``replacing`` and took the new hash.
|
||||
"""
|
||||
# Keeps `updated_at`, as `touch=False` does: device sync reads it as a write.
|
||||
result = session.execute(
|
||||
update(Save)
|
||||
.where(Save.id == id, Save.content_hash.is_not_distinct_from(replacing))
|
||||
.values(content_hash=content_hash)
|
||||
.values(content_hash=content_hash, updated_at=Save.updated_at)
|
||||
.execution_options(synchronize_session=False)
|
||||
)
|
||||
return affected_rows(result) == 1
|
||||
@@ -425,6 +426,7 @@ class DBSavesHandler(DBBaseHandler):
|
||||
_deleted_assets.record_deletions(
|
||||
user_id, rom_id, slot, lost, session=session
|
||||
)
|
||||
# One row at a time: MariaDB's `id IN (...)` plan deadlocks concurrent prunes.
|
||||
for row in rows:
|
||||
session.execute(
|
||||
delete(Save)
|
||||
|
||||
@@ -4,6 +4,7 @@ import threading
|
||||
import zipfile
|
||||
from mimetypes import guess_type
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import magic
|
||||
from fastapi import HTTPException, UploadFile, status
|
||||
@@ -16,6 +17,9 @@ from utils.media_types import IMAGE_EXT_BY_MIME_TYPE
|
||||
|
||||
from .base_handler import FSHandler
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from models.assets import Save
|
||||
|
||||
# libmagic loads its database on construction (~few MB read from disk), so we
|
||||
# share a single Magic instance across requests. The underlying magic_t handle
|
||||
# is not thread-safe, so guard from_buffer with a lock. Endpoints that call
|
||||
@@ -201,3 +205,9 @@ class FSAssetsHandler(FSHandler):
|
||||
except Exception as e:
|
||||
log.debug(f"Failed to compute content hash for {file_path}: {e}")
|
||||
return None
|
||||
|
||||
async def unrecorded_hash(self, save: "Save") -> str | None:
|
||||
"""The file's hash for a slotted save never hashed, so its removal is still recorded."""
|
||||
if save.slot and not save.content_hash:
|
||||
return await self.compute_content_hash(save.full_path)
|
||||
return None
|
||||
|
||||
@@ -23,7 +23,6 @@ from typing import Literal
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from config import SYNC_RETROARCH_PSP_PENDING_PATH, SYNC_RETROARCH_PSP_SERIAL_MAP
|
||||
from handler.asset_store import unrecorded_hash
|
||||
from handler.database import db_platform_handler, db_rom_handler, db_save_handler
|
||||
from handler.filesystem import fs_asset_handler
|
||||
from handler.filesystem.base_handler import FSHandler
|
||||
@@ -447,7 +446,6 @@ async def put_psp_file(
|
||||
async def _rewrite_bundle(bundle: Save, entries: dict[str, bytes]) -> None:
|
||||
"""Write `entries` over the bundle's own file and refresh its row."""
|
||||
zip_bytes = await asyncio.to_thread(_write_bundle, entries)
|
||||
replaced_hash = await unrecorded_hash(bundle)
|
||||
await fs_asset_handler.write_file(
|
||||
file=zip_bytes, path=bundle.file_path, filename=bundle.file_name
|
||||
)
|
||||
@@ -458,7 +456,6 @@ async def _rewrite_bundle(bundle: Save, entries: dict[str, bytes]) -> None:
|
||||
"content_hash": content_hash_of_bytes(zip_bytes),
|
||||
"missing_from_fs": False,
|
||||
},
|
||||
replaced_hash=replaced_hash,
|
||||
)
|
||||
await _cache_member_md5s(updated, entries)
|
||||
|
||||
|
||||
@@ -20,7 +20,6 @@ from typing import cast
|
||||
import sentry_sdk
|
||||
|
||||
from config import ENABLE_SYNC_FOLDER_WATCHER, SENTRY_DSN
|
||||
from handler.asset_store import unrecorded_hash
|
||||
from handler.database import (
|
||||
db_deleted_asset_handler,
|
||||
db_device_handler,
|
||||
@@ -251,8 +250,13 @@ def _process_incoming_file(
|
||||
server_hash=matched_save.content_hash,
|
||||
server_updated_at=matched_save.updated_at,
|
||||
device_last_synced_at=device_sync.last_synced_at if device_sync else None,
|
||||
removed_at=db_deleted_asset_handler.removal_times(
|
||||
device.user_id, matched_save.rom_id, matched_save.slot
|
||||
# Identical content is a no_op, which never reads removals.
|
||||
removed_at=(
|
||||
db_deleted_asset_handler.removal_times(
|
||||
device.user_id, matched_save.rom_id, matched_save.slot
|
||||
)
|
||||
if file_hash != matched_save.content_hash
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
@@ -268,7 +272,7 @@ def _process_incoming_file(
|
||||
)
|
||||
with open(full_path, "rb") as f:
|
||||
file_data = f.read()
|
||||
replaced_hash = asyncio.run(unrecorded_hash(matched_save))
|
||||
replaced_hash = asyncio.run(fs_asset_handler.unrecorded_hash(matched_save))
|
||||
asyncio.run(
|
||||
fs_asset_handler.write_file(
|
||||
file=file_data,
|
||||
|
||||
@@ -12,7 +12,6 @@ from anyio import Path as AnyioPath
|
||||
from anyio import open_file
|
||||
|
||||
from config import ENABLE_SYNC_PUSH_PULL, SYNC_PUSH_PULL_CRON
|
||||
from handler.asset_store import unrecorded_hash
|
||||
from handler.database import (
|
||||
db_deleted_asset_handler,
|
||||
db_device_handler,
|
||||
@@ -268,8 +267,13 @@ async def _process_remote_save(
|
||||
server_hash=matched_save.content_hash,
|
||||
server_updated_at=matched_save.updated_at,
|
||||
device_last_synced_at=device_sync.last_synced_at if device_sync else None,
|
||||
removed_at=db_deleted_asset_handler.removal_times(
|
||||
device.user_id, matched_save.rom_id, matched_save.slot
|
||||
# Identical content is a no_op, which never reads removals.
|
||||
removed_at=(
|
||||
db_deleted_asset_handler.removal_times(
|
||||
device.user_id, matched_save.rom_id, matched_save.slot
|
||||
)
|
||||
if remote_hash != matched_save.content_hash
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
@@ -289,7 +293,7 @@ async def _process_remote_save(
|
||||
)
|
||||
async with await open_file(local_path, "rb") as f:
|
||||
file_data = await f.read()
|
||||
replaced_hash = await unrecorded_hash(matched_save)
|
||||
replaced_hash = await fs_asset_handler.unrecorded_hash(matched_save)
|
||||
await fs_asset_handler.write_file(
|
||||
file=file_data,
|
||||
path=matched_save.file_path,
|
||||
|
||||
@@ -3652,6 +3652,45 @@ class TestSlotScopedDedupeMatrix:
|
||||
[slotted.json()["content_hash"]],
|
||||
)
|
||||
|
||||
def test_updating_a_save_never_hashed_records_its_bytes(
|
||||
self,
|
||||
client,
|
||||
access_token: str,
|
||||
rom: Rom,
|
||||
admin_user: User,
|
||||
_isolated_assets_dir,
|
||||
):
|
||||
slotted = self._upload(
|
||||
client, access_token, rom, _build_fixture_a_zip(), slot="slot1"
|
||||
)
|
||||
with sync_session.begin() as session:
|
||||
session.execute(
|
||||
update(Save)
|
||||
.where(Save.id == slotted.json()["id"])
|
||||
.values(content_hash=None)
|
||||
)
|
||||
|
||||
response = client.put(
|
||||
f"/api/saves/{slotted.json()['id']}",
|
||||
files={
|
||||
"saveFile": (
|
||||
slotted.json()["file_name"],
|
||||
BytesIO(_build_fixture_b_zip()),
|
||||
"application/octet-stream",
|
||||
)
|
||||
},
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
[record] = db_deleted_asset_handler.get_deletions(
|
||||
user_id=admin_user.id, rom_ids=[rom.id]
|
||||
)
|
||||
assert (record.slot, record.content_hashes) == (
|
||||
"slot1",
|
||||
[slotted.json()["content_hash"]],
|
||||
)
|
||||
|
||||
def test_different_bytes_same_slot_creates_distinct_records(
|
||||
self,
|
||||
client,
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import update
|
||||
|
||||
from handler.database import db_deleted_asset_handler
|
||||
from handler.database.base_handler import sync_session
|
||||
from models.deleted_asset import MAX_REMEMBERED_HASHES, DeletedAsset
|
||||
from models.rom import Rom
|
||||
from models.user import User
|
||||
@@ -100,6 +103,24 @@ class TestRemovalTimes:
|
||||
"stamped": to_utc(record.updated_at),
|
||||
}
|
||||
|
||||
def test_an_unstamped_version_keeps_its_time_when_another_is_lost(
|
||||
self, rom: Rom, admin_user: User
|
||||
):
|
||||
"""Recording bumps the record's own time, which must not move older losses."""
|
||||
legacy = _record(admin_user, rom, "autosave", "legacy")
|
||||
recorded = datetime(2026, 1, 1, tzinfo=timezone.utc)
|
||||
with sync_session.begin() as session:
|
||||
session.execute(
|
||||
update(DeletedAsset)
|
||||
.where(DeletedAsset.id == legacy.id)
|
||||
.values(removed_at=None, updated_at=recorded)
|
||||
)
|
||||
|
||||
times = _record(admin_user, rom, "autosave", "later").removal_times()
|
||||
|
||||
assert times["legacy"] == recorded
|
||||
assert times["later"] > recorded
|
||||
|
||||
def test_trimmed_versions_lose_their_stamps(self, rom: Rom, admin_user: User):
|
||||
for index in range(MAX_REMEMBERED_HASHES + 1):
|
||||
record = _record(admin_user, rom, "autosave", f"v{index}")
|
||||
|
||||
@@ -25,6 +25,7 @@ from models.assets import Save
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom
|
||||
from models.user import User
|
||||
from utils.datetime import to_utc
|
||||
|
||||
|
||||
class TestDBSavesHandlerPlatformFiltering:
|
||||
@@ -1295,6 +1296,20 @@ class TestDBSavesHandlerRecordsLostVersions:
|
||||
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])
|
||||
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
|
||||
):
|
||||
|
||||
Reference in New Issue
Block a user