mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 18:42:34 +01:00
* feat(converto): read per-file title ids with rom-converto during scans The title-id half of #5002: rom-converto's info runs fill rom_files.title_id and title_version, sigil fills what rom-converto can't read and keeps owning save targets, and roms in a scan batch share info runs of up to 64 files. A converto_read_at marker lets quick scans backfill files rom-converto has not read yet. converto.scan_metadata (config.yml only) turns it off. The other per-file fields and embedded images stay out until a UI reads them. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(converto): name the same-content check that keeps unread title ids Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(converto): queue unread files in one pass over the built rows Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(converto): address Greptile review on #5031 - A file refresh now persists converto_read_at when rom-converto's read confirms a reused row's stored title id, so the file isn't re-read on every refresh. - RomConvertoService.read_infos splits its paths into info runs of at most INFO_BATCH_SIZE, so a rom with many files can't send them all through one run. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(converto): apply code-review fixes - A stored file title id counts as rom-converto's only once rom-converto has read the row, so a stale sigil id can't override a fresh extraction. - Fresh hashes decide whether unread title ids still describe a file, ahead of a size and mtime a copy can preserve. - One rom's failed candidate listing no longer aborts its scan batch. - The info paths file's cleanup can't raise out of read_infos. - _rom_file_order sorts by Path like _TitleIdSource.order. - Restored the in-place reconcile test for _identify_rom. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(converto): apply simplify pass - sync_rom_files reads 'rom-converto read this pass' off converto_read_at instead of an inspected set threaded through ParsedRomFiles, FSRom, the scan socket and the refresh. - One _converto_may_read check serves the scan and the batch candidates. - converto_candidates reuses _list_rom_dir, validates paths off the event loop and is best-effort itself, so the scan socket gathers it plainly. - get_rom_files builds rom-converto paths from the validated rom dir instead of validating each file again. - _rom_level_identity returns early on sigil's extraction. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * chore(converto): apply review-polish pass Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(converto): drop the shared info batch Sharing rom-converto info runs across a scan batch saved about 2 ms per rom (one process start) in exchange for a second directory walk per rebuilt rom, the RomConvertoInfoBatch bookkeeping and the scan socket wiring. Each rom now reads its own files; read_infos still caps a run at INFO_RUN_MAX_FILES. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(converto): name the rom-converto columns inline Drops ROM_FILE_CONVERTO_COLUMNS and ROM_FILE_CONVERTO_KEPT_COLUMNS, so _copy_scanned_columns keeps master's frozenset keep_when_unset. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
144 lines
5.4 KiB
Python
144 lines
5.4 KiB
Python
from dataclasses import dataclass
|
|
from typing import Any
|
|
|
|
from sqlalchemy import inspect as sa_inspect
|
|
|
|
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,
|
|
)
|
|
|
|
|
|
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) -> 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.
|
|
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)
|
|
|
|
|
|
async def _refresh(rom: Rom) -> 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}
|
|
cnfg = cm.get_config()
|
|
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,
|
|
)
|
|
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,
|
|
)
|