Files
romm/backend/handler/rom_files.py
MMagTech c925728cab fix(converto): move save channels to the converted files (#5681)
* fix(converto): move save channels to the converted files

Convert library pointed the game at its new file and refreshed its files,
but a channel names its file by SHA-1, name and size, and those still named
the original. Afterwards GET /api/channels?rom_file_id=<new file> found
nothing and a push into the channel with the new file was refused 422
("the ROM file does not match the channel's").

After the refresh, every user's channels on the game move: one on a
replaced file (an iso, a cue, its tracks, a rewritten m3u) to the file that
replaced it, and one on the game's sync file (channel_file_id) to its new
sync file, since name order picks that once no cue is left. The move keeps
updated_at, which orders a user's channels.

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: prose

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(converto): move channels before deleting the originals

Convert library now refreshes a ROM's files while the originals are still
on disk, moves what keys to them onto the outputs in one transaction, and
only then deletes the originals. A failure before the deletion removes the
outputs, puts rewritten playlists back and keeps the channels on the
originals, so no failure leaves a channel on a file that is gone.

The sync-file redirect follows only to a file this run wrote, so a disc
that failed to convert no longer takes a converted disc's channels, and it
yields to the channel's own replacement when the user already has a channel
of that label on the new sync file.

The same transaction moves the ROM's snapshot hashes, so archival snapshots
still reattach after a rescan, and its states' capture disc, so a resume
mounts the right disc.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(converto): skip the ROM-level hash in the early file refresh

The refresh that runs while a folder ROM's originals and outputs are both
on disk rereads every top-level file for the ROM-level hashes and RAHasher,
and the refresh after the originals go does it again. A new rom_hashes flag
on refresh_rom_files keeps the stored ROM-level hashes in the early
refresh, which then reads only the new and changed files, so the originals
are never reread and the ROM-level hashes are computed once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-11-21 08:38:19 -05:00

158 lines
6.0 KiB
Python

from dataclasses import dataclass
from typing import Any
from sqlalchemy import inspect as sa_inspect
from config.config_manager import Config
from config.config_manager import config_manager as cm
from handler.database import db_rom_handler
from handler.filesystem import fs_rom_handler
from handler.filesystem.roms_handler import RomFileKey, rom_file_key
from handler.redis_handler import redis_lock
from handler.scan_handler import persist_soundtrack_cover
from logger.formatter import highlight as hl
from logger.logger import log
from models.rom import Rom, RomFile, RomIdentity
from utils.audio_tags import remove_persisted_cover
ROM_LEVEL_HASH_COLUMNS = ("crc_hash", "md5_hash", "sha1_hash", "ra_hash")
# A refresh lists the folder and then deletes every row the listing missed, so
# two of them running for the same rom (parallel uploads into one folder) would
# let the slower listing drop what the faster one just registered. The lock
# lives in Redis because the uploads may land on different gunicorn workers.
REFRESH_LOCK_TIMEOUT_SECONDS = 600
@dataclass(frozen=True)
class RomFilesRefresh:
new_files: int
updated_files: int
removed_files: int
identity_changed: bool = False
@property
def changed(self) -> bool:
return bool(
self.new_files
or self.updated_files
or self.removed_files
or self.identity_changed
)
def _extracted_state(rom_file: RomFile) -> tuple[Any, ...]:
"""The columns title id extraction and rom-converto write onto a reused row."""
return (
rom_file.category,
rom_file.title_id,
rom_file.title_version,
rom_file.converto_read_at,
rom_file.raw_serial,
rom_file.sigil_features,
rom_file.n64_header,
rom_file.n64_md5,
rom_file.n64_md5_n64,
rom_file.playlist_title_ids,
)
def loaded_rom_files(rom: Rom) -> list[RomFile]:
"""The ROM's file rows, fetched on demand when the relationship is unloaded."""
if "files" not in sa_inspect(rom).unloaded:
return list(rom.files)
return db_rom_handler.rom_files_for_rom_id(rom.id)
async def refresh_rom_files(
rom: Rom, cnfg: Config | None = None, *, rom_hashes: bool = True
) -> RomFilesRefresh:
"""Reconcile a ROM's file rows with what is on disk, keeping the stored
hashes of files whose size and mtime are unchanged.
Args:
rom: A persisted ROM whose folder or file exists on disk.
cnfg: The config to read, so a scan can load it once.
rom_hashes: False keeps a folder ROM's stored ROM-level hashes, for a
caller that refreshes again once the files settle.
Returns:
What changed, so callers can report it.
"""
async with redis_lock(
f"rom_files_refresh:{rom.id}", timeout_seconds=REFRESH_LOCK_TIMEOUT_SECONDS
):
return await _refresh(rom, cnfg or cm.get_config(), rom_hashes)
async def _refresh(rom: Rom, cnfg: Config, rom_hashes: bool) -> RomFilesRefresh:
existing = loaded_rom_files(rom)
# Extraction can settle a reused row's category, title id and read time in
# place, so that row is compared against the values it was loaded with.
reused_state = {id(f): _extracted_state(f) for f in existing}
calculate_hashes = not cnfg.SKIP_HASH_CALCULATION
parsed = await fs_rom_handler.get_rom_files(
rom,
calculate_hashes=calculate_hashes,
extract_title_ids=not cnfg.SKIP_TITLE_ID_EXTRACTION,
existing_files=existing,
reuse_title_ids=True,
rom_hashes=rom_hashes,
cnfg=cnfg,
)
if existing and not parsed.rom_files:
# A mount that dropped out would otherwise read as every file deleted.
log.warning(
f"{hl(rom.fs_name)} lists no files on disk, keeping its "
f"{len(existing)} recorded files"
)
return RomFilesRefresh(0, 0, 0)
existing_keys = {rom_file_key(f) for f in existing}
new_keys: set[RomFileKey] = set()
updated_keys: set[RomFileKey] = set()
for scanned in parsed.rom_files:
if reused_state.get(id(scanned)) == _extracted_state(scanned):
continue
key = rom_file_key(scanned)
(updated_keys if key in existing_keys else new_keys).add(key)
removed_keys = existing_keys - {rom_file_key(f) for f in parsed.rom_files}
if new_keys or updated_keys or removed_keys:
synced = db_rom_handler.sync_rom_files(rom.id, parsed.rom_files)
for cover_path in synced.orphaned_cover_paths:
remove_persisted_cover(cover_path)
for saved in synced.files:
if rom_file_key(saved) in new_keys or rom_file_key(saved) in updated_keys:
persist_soundtrack_cover(saved, rom)
rom_updates: dict[str, Any] = {}
fs_size_bytes = sum(f.file_size_bytes for f in parsed.rom_files)
if fs_size_bytes != rom.fs_size_bytes:
rom_updates["fs_size_bytes"] = fs_size_bytes
# With hashing disabled the listing carries no digests, so the stored
# hashes outlive it rather than being blanked.
if parsed.top_level_changed and calculate_hashes:
for column in ROM_LEVEL_HASH_COLUMNS:
value = getattr(parsed, column)
if value != (getattr(rom, column) or ""):
rom_updates[column] = value
# Only written when the parse actually read an id, so a refresh that read
# none (extraction disabled, or no readable file) leaves the stored triple
# alone rather than blanking it.
identity_changed = bool(
parsed.identity.title_id and parsed.identity != RomIdentity.from_rom(rom)
)
if identity_changed:
rom_updates.update(parsed.identity.as_rom_attrs())
if rom.missing_from_fs:
rom_updates["missing_from_fs"] = False
if rom_updates:
db_rom_handler.update_rom(rom.id, rom_updates)
return RomFilesRefresh(
new_files=len(new_keys),
updated_files=len(updated_keys),
removed_files=len(removed_keys),
identity_changed=identity_changed,
)