Files
romm/backend/utils/rom_patcher/patcher.py
Georges-Antoine Assi c8055ac973 Address self-review on patcher PR
- patcher.js resolves rom-patcher-js from both the relocated sibling
  layout (docker/Dockerfile) and the plain node_modules layout (root
  Dockerfile), so both build flows work without a manual copy
- apply_patch wraps the node subprocess in asyncio.wait_for with a
  timeout and kills it on expiry; a semaphore bounds concurrency, and the
  endpoint rejects oversized ROM/patch files to avoid OOM
- report the patch source-checksum validation result via an
  X-Patch-Validated header; the patcher UI warns on a mismatch
- return a generic "Patching failed" detail to clients and log the real
  error server-side, so node/RomPatcher.js paths don't leak

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 21:07:27 -04:00

79 lines
2.6 KiB
Python

"""Server-side ROM patching helpers.
Shells out to the sibling ``patcher.js`` (Node.js + RomPatcher.js) to apply
a patch file to a ROM file.
"""
import asyncio
import json
from pathlib import Path
from anyio import Path as AnyioPath
from config import ROM_PATCHER_MAX_CONCURRENCY, ROM_PATCHER_TIMEOUT
PATCHER_SCRIPT = Path(__file__).parent / "patcher.js"
SUPPORTED_PATCH_EXTENSIONS = frozenset(
(".ips", ".ups", ".bps", ".ppf", ".rup", ".aps", ".bdf", ".pmsr", ".vcdiff")
)
# Bound concurrent node subprocesses, each of which loads a full ROM into memory.
_patch_semaphore = asyncio.Semaphore(ROM_PATCHER_MAX_CONCURRENCY)
class PatcherError(Exception):
"""Raised when the Node.js patcher script fails or produces no output."""
async def apply_patch(rom_path: Path, patch_path: Path, output_path: Path) -> bool:
"""Apply ``patch_path`` to ``rom_path`` and write the result to ``output_path``.
Returns whether the patch's embedded source checksum matched the ROM (always
``True`` for formats that carry no source checksum). The patch is applied
regardless; the result lets callers warn on a likely ROM/patch mismatch.
Raises :class:`PatcherError` if the subprocess fails, times out, or the
output file is missing.
"""
async with _patch_semaphore:
proc = await asyncio.create_subprocess_exec(
"node",
str(PATCHER_SCRIPT),
str(rom_path),
str(patch_path),
str(output_path),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
try:
stdout, stderr = await asyncio.wait_for(
proc.communicate(), timeout=ROM_PATCHER_TIMEOUT
)
except (asyncio.TimeoutError, TimeoutError) as e:
proc.kill()
await proc.wait()
raise PatcherError(
f"Patching timed out after {ROM_PATCHER_TIMEOUT}s"
) from e
if proc.returncode != 0:
message = "Patching failed"
try:
err_data = json.loads(stderr.decode())
message = err_data.get("error", message)
except (json.JSONDecodeError, UnicodeDecodeError):
if stderr:
message = stderr.decode(errors="replace").strip()
raise PatcherError(message)
if not await AnyioPath(output_path).exists():
raise PatcherError("Patcher did not produce an output file")
# The script reports source-checksum validation in its JSON stdout.
try:
result = json.loads(stdout.decode())
return bool(result.get("validated", True))
except (json.JSONDecodeError, UnicodeDecodeError):
return True