Files
romm/backend/endpoints/roms/upload.py
Georges-Antoine Assi f105622513 fix: address code review on the library structure unique index and relocation
Key the unique roms index on a sha256 digest of the full path. Indexing
(platform_id, fs_path, fs_name) directly is 5804 bytes of utf8mb4, which MySQL
rejects with ER_TOO_LONG_KEY and MariaDB silently demotes to a hash index; the
digest column keeps it a 260-byte BTREE on every supported driver. It is derived
by the same @validates hook that maintains the other fs_name columns, and
resynced explicitly in update_rom and convert_rom_to_folder.

Migration 0126 backfills the digest in one dialect-branched UPDATE. A Python
executemany right after the ADD COLUMN silently applies only its first parameter
set on mariadb-connector, leaving the rest NULL. test_migrations pins the SQL
expression to compute_full_path_hash so the two cannot drift.

Drop the relocation pre-pass. mark_missing_roms already runs before the identify
loop, so a moved file reaches get_matching_missing_rom, which requires all three
hashes to agree (or a title_id, covering non-hashable platforms), refuses
ambiguous matches, re-parses filename tags and emits over the socket. The
pre-pass duplicated it with a weaker CRC-only check, hashed every candidate
twice, compared folder sizes against a total that excludes filtered files, and
ran on QUICK scans.

Send uploads to a folder the platform's structure will actually discover, so the
next scan does not flag a fresh upload as missing, and refuse with a 400 when
only the user can pick the folder.

Make 0126's downgrade refuse when duplicate file names exist instead of deleting
the roms (and their saves, notes and collection membership) that carry them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:14:58 -04:00

561 lines
18 KiB
Python

import json
import os
import shutil
from pathlib import Path
from typing import Annotated
from uuid import UUID, uuid4
from anyio import open_file
from fastapi import Header, HTTPException, Request, status
from pydantic import BaseModel, Field
from starlette.responses import Response
from config import (
ROM_UPLOAD_ASSEMBLING_EXT,
ROM_UPLOAD_TMP_BASE,
ROM_UPLOAD_TTL,
)
from decorators.auth import protected_route
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
from exceptions.fs_exceptions import RomAlreadyExistsException
from handler.auth.constants import Scope
from handler.auth.dependencies import assert_rom_visible
from handler.database import db_platform_handler, db_rom_handler
from handler.filesystem import fs_rom_handler
from handler.redis_handler import async_cache
from handler.rom_conversion import promote_single_file_to_folder
from handler.rom_files import refresh_rom_files
from logger.logger import log
from models.rom import Rom
from utils.router import APIRouter
router = APIRouter(
prefix="/upload",
tags=["upload"],
)
ROM_ASSEMBLY_CHUNK_SIZE = 8192 # 8KB read buffer during assembly
ROM_UPLOAD_MAX_CHUNK_SIZE = 64 * 1024 * 1024 # 64MB hard cap per chunk
def _session_key(upload_id: str) -> str:
return f"chunked_upload:{upload_id}"
def _chunks_key(upload_id: str) -> str:
return f"chunked_upload:{upload_id}:chunks"
def _expected_chunk_size(total_size: int, total_chunks: int, chunk_index: int) -> int:
"""Return expected chunk size using fixed-size chunks with a shorter final chunk."""
chunk_size = (total_size + total_chunks - 1) // total_chunks
if chunk_index < total_chunks - 1:
return chunk_size
return total_size - (chunk_size * (total_chunks - 1))
async def _get_session(upload_id: str) -> dict:
raw = await async_cache.get(_session_key(upload_id))
if not raw:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Upload session not found or expired",
)
return json.loads(raw)
async def _save_session(upload_id: str, session: dict) -> None:
await async_cache.set(
_session_key(upload_id), json.dumps(session), ex=ROM_UPLOAD_TTL
)
def _cleanup_tmp(upload_id: str) -> None:
tmp_dir = ROM_UPLOAD_TMP_BASE / upload_id
if tmp_dir.exists():
shutil.rmtree(tmp_dir, ignore_errors=True)
def _validate_upload_id(upload_id: str) -> None:
try:
UUID(upload_id)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid upload ID",
) from exc
def _validate_session_owner(session: dict, user_id: int) -> None:
if session["user_id"] != user_id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Forbidden",
)
async def _cleanup_upload_state(upload_id: str) -> None:
_cleanup_tmp(upload_id)
await async_cache.delete(_chunks_key(upload_id))
def _sanitized_filename(filename: str) -> str:
try:
safe_filename = fs_rom_handler._sanitize_filename(filename)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Invalid upload filename: {exc}",
) from exc
if safe_filename != filename:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Upload filename must be a plain file name, not a path",
)
return safe_filename
def _parse_upload_folder(folder: str) -> str:
"""Normalize the target subfolder to a relative path made of plain names."""
raw = folder.strip()
if raw.startswith("/") or "\\" in raw:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Upload folder must be a relative, forward-slashed path",
)
raw = raw.rstrip("/")
if not raw:
return ""
segments = raw.split("/")
for segment in segments:
try:
safe_segment = fs_rom_handler._sanitize_filename(segment)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Invalid upload folder: {exc}",
) from exc
if safe_segment != segment:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Upload folder must be a relative path inside the game folder",
)
return "/".join(segments)
def _get_upload_rom(request: Request, rom_id: int, platform_id: int) -> Rom:
rom = db_rom_handler.get_rom_simple(rom_id)
if not rom:
raise RomNotFoundInDatabaseException(rom_id)
assert_rom_visible(request, rom)
if rom.platform_id != platform_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Upload platform does not match the game's platform",
)
return rom
def _free_rom_destination(rom: Rom, folder: str, filename: str) -> tuple[str, Path]:
"""The library-relative directory and absolute file path of an upload into a
ROM, kept inside the folder a lone file gets promoted into and refused when
a file of that name is already there (or will be, once promoted)."""
root = (
f"{rom.fs_path}/{rom.fs_name_no_ext}"
if rom.has_simple_single_file
else rom.full_path
)
rel_dir = f"{root}/{folder}" if folder else root
try:
root_location = fs_rom_handler.validate_path(root)
location = fs_rom_handler.validate_path(f"{rel_dir}/{filename}")
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
) from exc
if not location.is_relative_to(root_location):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Upload destination must be inside the game folder",
)
promoted_over_itself = (
rom.has_simple_single_file and not folder and filename == rom.fs_name
)
if location.exists() or promoted_over_itself:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"File {filename} already exists in the game folder",
)
return rel_dir, location
def _claim_destination(location: Path) -> None:
"""Create the final path exclusively, so two completions racing for the
same name cannot overwrite each other's bytes."""
try:
os.close(os.open(location, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644))
except FileExistsError as exc:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"File {location.name} already exists",
) from exc
async def _resolve_destination(
request: Request, session: dict
) -> tuple[str, Path, Rom | None]:
"""Where a completed upload lands: the directory to create, the file path,
and the ROM it belongs to when it targets one."""
filename = session["filename"]
rom_id = session.get("rom_id")
if rom_id is None:
try:
roms_path = fs_rom_handler.get_roms_upload_path(session["platform_fs_slug"])
return (
roms_path,
fs_rom_handler.validate_path(f"{roms_path}/{filename}"),
None,
)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
) from exc
rom = _get_upload_rom(request, rom_id, session["platform_id"])
folder = session["folder"]
rel_dir, location = _free_rom_destination(rom, folder, filename)
if rom.has_simple_single_file:
try:
rom = await promote_single_file_to_folder(rom)
except RomAlreadyExistsException as exc:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT, detail=str(exc)
) from exc
return rel_dir, location, rom
class UploadTargetPayload(BaseModel):
"""Optional body of `/start`: upload into a ROM's folder instead of the
platform folder."""
rom_id: int = Field(ge=1)
folder: str = Field(
default="",
description="Subfolder inside the ROM's folder, relative and forward-slashed. Empty for the root.",
)
@protected_route(
router.post,
"/start",
[Scope.ROMS_WRITE],
status_code=status.HTTP_201_CREATED,
)
async def start_chunked_upload(
request: Request,
platform_id: Annotated[
int,
Header(alias="x-upload-platform", ge=1),
],
filename: Annotated[
str,
Header(alias="x-upload-filename"),
],
total_size: Annotated[
int,
Header(alias="x-upload-total-size", ge=1),
],
total_chunks: Annotated[
int,
Header(alias="x-upload-total-chunks", ge=1),
],
target: UploadTargetPayload | None = None,
) -> dict:
"""Initiate a chunked ROM upload session."""
db_platform = db_platform_handler.get_platform(platform_id)
if not db_platform:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Platform not found",
)
platform_fs_slug = db_platform.fs_slug
safe_filename = _sanitized_filename(filename)
rel_folder = ""
if target is None:
try:
roms_path = fs_rom_handler.get_roms_upload_path(platform_fs_slug)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
) from exc
if await fs_rom_handler.file_exists(f"{roms_path}/{safe_filename}"):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"File {filename} already exists",
)
else:
rom = _get_upload_rom(request, target.rom_id, platform_id)
rel_folder = _parse_upload_folder(target.folder)
if fs_rom_handler.is_excluded_multi_part(safe_filename):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"File {filename} would be ignored by the scanner",
)
_free_rom_destination(rom, rel_folder, safe_filename)
upload_id = str(uuid4())
tmp_dir = ROM_UPLOAD_TMP_BASE / upload_id
tmp_dir.mkdir(parents=True, exist_ok=True)
session = {
"upload_id": upload_id,
"platform_id": platform_id,
"platform_fs_slug": platform_fs_slug,
"filename": safe_filename,
"total_chunks": total_chunks,
"total_size": total_size,
"user_id": request.user.id,
"rom_id": target.rom_id if target else None,
"folder": rel_folder,
}
await _save_session(upload_id, session)
log.info(
f"Started chunked upload session {upload_id} for {filename} "
f"({total_chunks} chunks, {total_size} bytes)"
)
return {"upload_id": upload_id}
@protected_route(
router.put,
"/{upload_id}",
[Scope.ROMS_WRITE],
)
async def upload_chunk(
request: Request,
upload_id: str,
chunk_index: Annotated[
int,
Header(alias="x-chunk-index", ge=0),
],
) -> dict:
"""Upload a single chunk of a ROM file."""
_validate_upload_id(upload_id)
session = await _get_session(upload_id)
_validate_session_owner(session, request.user.id)
if chunk_index >= session["total_chunks"]:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Chunk index {chunk_index} out of range (total: {session['total_chunks']})",
)
expected_chunk_size = _expected_chunk_size(
session["total_size"], session["total_chunks"], chunk_index
)
if expected_chunk_size > ROM_UPLOAD_MAX_CHUNK_SIZE:
raise HTTPException(
status_code=status.HTTP_413_CONTENT_TOO_LARGE,
detail="Chunk size exceeds server maximum",
)
if content_length := request.headers.get("content-length"):
try:
content_length_bytes = int(content_length)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid Content-Length header",
) from exc
if content_length_bytes > ROM_UPLOAD_MAX_CHUNK_SIZE:
raise HTTPException(
status_code=status.HTTP_413_CONTENT_TOO_LARGE,
detail="Chunk exceeds maximum allowed size",
)
chunk_path = ROM_UPLOAD_TMP_BASE / upload_id / f"{chunk_index:05d}"
chunk_bytes_written = 0
try:
async with await open_file(chunk_path, "wb") as f:
async for body_chunk in request.stream():
chunk_bytes_written += len(body_chunk)
if chunk_bytes_written > ROM_UPLOAD_MAX_CHUNK_SIZE:
raise HTTPException(
status_code=status.HTTP_413_CONTENT_TOO_LARGE,
detail="Chunk exceeds maximum allowed size",
)
await f.write(body_chunk)
except Exception as exc:
if chunk_path.exists():
chunk_path.unlink()
if isinstance(exc, HTTPException):
raise
log.error(
f"Error writing chunk {chunk_index} for upload {upload_id}", exc_info=exc
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Error writing chunk to disk",
) from exc
# Atomically add chunk to set and update TTL
await async_cache.sadd(_chunks_key(upload_id), chunk_index)
await async_cache.expire(_chunks_key(upload_id), ROM_UPLOAD_TTL)
# Get current chunk count
received_count = await async_cache.scard(_chunks_key(upload_id))
return {"received": received_count, "total": session["total_chunks"]}
@protected_route(
router.post,
"/{upload_id}/complete",
[Scope.ROMS_WRITE],
status_code=status.HTTP_201_CREATED,
)
async def complete_chunked_upload(
request: Request,
upload_id: str,
) -> Response:
"""Assemble all chunks into the final ROM file."""
_validate_upload_id(upload_id)
session = await _get_session(upload_id)
_validate_session_owner(session, request.user.id)
total_chunks = session["total_chunks"]
# Atomically get received chunk count and members from Redis set
received_count = await async_cache.scard(_chunks_key(upload_id))
if received_count != total_chunks:
received_chunks_bytes = await async_cache.smembers(_chunks_key(upload_id))
received_chunks = {int(chunk) for chunk in received_chunks_bytes}
missing = sorted(set(range(total_chunks)) - received_chunks)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Missing chunks: {missing}",
)
# Atomically claim this upload session so only one /complete can proceed.
deleted = await async_cache.delete(_session_key(upload_id))
if not deleted:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Upload is already being assembled or has already completed",
)
try:
target_dir, file_location, rom = await _resolve_destination(request, session)
except Exception:
await _cleanup_upload_state(upload_id)
raise
await fs_rom_handler.make_directory(target_dir)
log.info(f"Assembling {total_chunks} chunks into {file_location}")
# Assemble chunks in order into final file with a temporary filename
# then atomically rename to final location
temp_location = file_location.with_name(
f".{file_location.name}.{uuid4().hex}.{ROM_UPLOAD_ASSEMBLING_EXT}"
)
assembled_bytes = 0
claimed = False
try:
async with await open_file(temp_location, "wb") as dest:
for i in range(total_chunks):
chunk_path = ROM_UPLOAD_TMP_BASE / upload_id / f"{i:05d}"
async with await open_file(chunk_path, "rb") as src:
while True:
buf = await src.read(ROM_ASSEMBLY_CHUNK_SIZE)
if not buf:
break
assembled_bytes += len(buf)
await dest.write(buf)
if assembled_bytes != session["total_size"]:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=(
"Assembled file size mismatch: "
f"expected {session['total_size']}, got {assembled_bytes}"
),
)
_claim_destination(file_location)
claimed = True
temp_location.replace(file_location)
except Exception as exc:
if temp_location.exists():
temp_location.unlink()
if claimed:
# The claim is an empty placeholder the rename never replaced;
# left behind, a scan would ingest it as a zero-byte ROM.
file_location.unlink(missing_ok=True)
await _cleanup_upload_state(upload_id)
if isinstance(exc, HTTPException):
raise
log.error(f"Error assembling upload {upload_id}", exc_info=exc)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Error assembling file chunks",
) from exc
await _cleanup_upload_state(upload_id)
log.info(f"Chunked upload complete: {file_location}")
if rom is not None:
try:
await refresh_rom_files(rom)
except Exception as exc:
log.error(f"Error registering uploaded file for ROM {rom.id}", exc_info=exc)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="File uploaded but not registered yet, run a quick scan",
) from exc
return Response(status_code=status.HTTP_201_CREATED)
@protected_route(
router.post,
"/{upload_id}/cancel",
[Scope.ROMS_WRITE],
status_code=status.HTTP_204_NO_CONTENT,
)
async def cancel_chunked_upload(
request: Request,
upload_id: str,
) -> Response:
"""Cancel a chunked upload session and clean up temp files."""
_validate_upload_id(upload_id)
# Best-effort: session may already be gone because /complete claimed it.
raw = await async_cache.get(_session_key(upload_id))
if not raw:
return Response(status_code=status.HTTP_204_NO_CONTENT)
session = json.loads(raw)
_validate_session_owner(session, request.user.id)
await async_cache.delete(_session_key(upload_id))
await _cleanup_upload_state(upload_id)
return Response(status_code=status.HTTP_204_NO_CONTENT)