From c33a3e65df0601efd458f47cdb31a4ec2838703e Mon Sep 17 00:00:00 2001 From: nendo Date: Mon, 31 Aug 2026 14:23:14 +0900 Subject: [PATCH] fix(roms): keep a failed promotion from destroying another's folder The lock only covers one worker, so a deployment running several can still race. A rollback now moves the ROM back only if this call moved it, and drops the destination only while it is empty: removal is recursive, and a folder with anything left in it belongs to the promotion that won. --- backend/handler/rom_conversion.py | 33 +++++++---- .../endpoints/roms/test_convert_to_folder.py | 57 ++++++++++++++++++- 2 files changed, 77 insertions(+), 13 deletions(-) diff --git a/backend/handler/rom_conversion.py b/backend/handler/rom_conversion.py index ab854d990..0f1dda86c 100644 --- a/backend/handler/rom_conversion.py +++ b/backend/handler/rom_conversion.py @@ -1,5 +1,4 @@ import asyncio -from collections import defaultdict from exceptions.fs_exceptions import RomAlreadyExistsException from handler.database import db_rom_handler @@ -12,7 +11,7 @@ from models.rom import Rom _STAGE_PREFIX = ".romm_tmp_" # Uploading several files fires a request per file, each promoting the same ROM. -_promotion_locks: defaultdict[int, asyncio.Lock] = defaultdict(asyncio.Lock) +_promotion_lock = asyncio.Lock() async def promote_single_file_to_folder(rom: Rom) -> Rom: @@ -20,7 +19,7 @@ async def promote_single_file_to_folder(rom: Rom) -> Rom: and every relation. Idempotent; raises RomAlreadyExistsException on a folder-name collision. """ - async with _promotion_locks[rom.id]: + async with _promotion_lock: return await _promote(db_rom_handler.get_rom(rom.id) or rom) @@ -43,33 +42,47 @@ async def _promote(rom: Rom) -> Rom: if collision: raise RomAlreadyExistsException(folder) + # A promotion racing this one from another worker can win the move and own + # the folder, so undo only what this call did. Removal is recursive, and a + # folder with anything left in it holds someone else's ROM. + moved = False + + async def _drop_dir() -> None: + path = fs_rom_handler.validate_path(dest_dir) + if path.is_dir() and not any(path.iterdir()): + await fs_rom_handler.remove_directory(dest_dir) + async def _restore() -> None: """Return the lone file to its original path and drop the new folder.""" src = next( - (p for p in (final, staged) if fs_rom_handler.validate_path(p).exists()), + ( + p + for p in (final, staged) + if moved and fs_rom_handler.validate_path(p).exists() + ), None, ) if src is not None and extensionless: if src != staged: await fs_rom_handler.move_file_or_folder(src, staged) - if fs_rom_handler.validate_path(dest_dir).is_dir(): - await fs_rom_handler.remove_directory(dest_dir) + await _drop_dir() await fs_rom_handler.move_file_or_folder(staged, origin) elif src is not None: await fs_rom_handler.move_file_or_folder(src, origin) - if fs_rom_handler.validate_path(dest_dir).is_dir(): - await fs_rom_handler.remove_directory(dest_dir) - elif fs_rom_handler.validate_path(dest_dir).is_dir(): - await fs_rom_handler.remove_directory(dest_dir) + await _drop_dir() + else: + await _drop_dir() try: if extensionless: await fs_rom_handler.move_file_or_folder(origin, staged) + moved = True await fs_rom_handler.make_directory(dest_dir) await fs_rom_handler.move_file_or_folder(staged, final) else: await fs_rom_handler.make_directory(dest_dir) await fs_rom_handler.move_file_or_folder(origin, final) + moved = True db_rom_handler.convert_rom_to_folder(rom.id, folder, dest_dir) except Exception: try: diff --git a/backend/tests/endpoints/roms/test_convert_to_folder.py b/backend/tests/endpoints/roms/test_convert_to_folder.py index d9699254d..5f4b80450 100644 --- a/backend/tests/endpoints/roms/test_convert_to_folder.py +++ b/backend/tests/endpoints/roms/test_convert_to_folder.py @@ -5,6 +5,7 @@ import pytest from fastapi import status from fastapi.testclient import TestClient +from handler import rom_conversion from handler.database import db_rom_handler from handler.filesystem import fs_rom_handler from handler.rom_conversion import promote_single_file_to_folder @@ -374,6 +375,57 @@ async def test_second_upload_racing_a_promotion_keeps_the_rom_in_its_folder( monkeypatch.setattr(fs_rom_handler, "make_directory", gated_make_directory) + results = await asyncio.gather( + promote_single_file_to_folder(rom), + promote_single_file_to_folder(second), + return_exceptions=True, + ) + + assert not [r for r in results if isinstance(r, BaseException)] + inside = real_library / f"{platform.slug}/roms/sf2ce/sf2ce.zip" + beside = real_library / f"{platform.slug}/roms/sf2ce.zip" + assert inside.exists(), "the loser dragged the ROM back out of its folder" + assert not beside.exists() + + +async def test_promotion_racing_across_workers_does_not_destroy_the_folder( + platform: Platform, + admin_user: User, + real_library: Path, + monkeypatch: pytest.MonkeyPatch, +): + rom = _single_file_rom( + platform, + admin_user, + real_library, + fs_name="sf2ce.zip", + fs_name_no_ext="sf2ce", + fs_extension="zip", + ) + second = db_rom_handler.get_rom(rom.id) + + class _NoLock: + async def __aenter__(self) -> None: + return None + + async def __aexit__(self, *_: object) -> None: + return None + + # Separate workers hold separate locks, so neither serializes the other. + monkeypatch.setattr(rom_conversion, "_promotion_lock", _NoLock()) + + make_directory = fs_rom_handler.make_directory + barrier = asyncio.Barrier(2) + + async def gated_make_directory(path: str) -> None: + try: + await asyncio.wait_for(barrier.wait(), 0.5) + except (TimeoutError, asyncio.BrokenBarrierError): + pass + await make_directory(path) + + monkeypatch.setattr(fs_rom_handler, "make_directory", gated_make_directory) + await asyncio.gather( promote_single_file_to_folder(rom), promote_single_file_to_folder(second), @@ -381,6 +433,5 @@ async def test_second_upload_racing_a_promotion_keeps_the_rom_in_its_folder( ) inside = real_library / f"{platform.slug}/roms/sf2ce/sf2ce.zip" - beside = real_library / f"{platform.slug}/roms/sf2ce.zip" - assert inside.exists(), "the loser dragged the ROM back out of its folder" - assert not beside.exists() + assert inside.exists(), "the loser destroyed the winner's folder" + assert inside.read_bytes() == b"romdata"