mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 10:33:22 +01:00
Merge remote-tracking branch 'origin/master' into claude/tender-hopper-m4x9hm
# Conflicts: # docker/Dockerfile
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
---
|
||||
name: backend-development
|
||||
description: Working on the RomM Python backend (backend/), a FastAPI app with SQLAlchemy 2.0, Alembic, RQ/Redis, and Socket.IO. Use when adding or changing API endpoints, handlers, ORM models, response schemas, metadata-provider adapters, background tasks, database migrations, or backend tests. Covers the layered architecture, conventions, auth/scopes, the OpenAPI→frontend type pipeline, and the uv/pytest/alembic/trunk workflow. Trigger on any work under backend/.
|
||||
description: Working on the RomM Python backend (backend/), a FastAPI app with SQLAlchemy 2.1, Alembic, RQ/Redis, and Socket.IO. Use when adding or changing API endpoints, handlers, ORM models, response schemas, metadata-provider adapters, background tasks, database migrations, or backend tests. Covers the layered architecture, conventions, auth/scopes, the OpenAPI→frontend type pipeline, and the uv/pytest/alembic/trunk workflow. Trigger on any work under backend/.
|
||||
---
|
||||
|
||||
# RomM Backend: FastAPI / SQLAlchemy
|
||||
|
||||
Python 3.14+, FastAPI, SQLAlchemy 2.0 (MariaDB default; MySQL/PostgreSQL supported), Alembic, Redis + RQ for jobs/cache/sessions, Socket.IO for real-time. Managed with **uv**.
|
||||
Python 3.14+, FastAPI, SQLAlchemy 2.1 (MariaDB default; MySQL/PostgreSQL supported), Alembic, Redis + RQ for jobs/cache/sessions, Socket.IO for real-time. Managed with **uv**.
|
||||
|
||||
Full reference: **`docs/BACKEND_ARCHITECTURE.md`** (directory map, ER diagram, every endpoint, auth flows). Read it before non-trivial changes.
|
||||
|
||||
@@ -42,6 +42,7 @@ alembic/ Migrations (env.py + versions/)
|
||||
- **Imports:** stdlib → third-party → local; explicit (no wildcards); `TYPE_CHECKING` blocks to break circular imports.
|
||||
- **Errors:** raise the custom exceptions in `exceptions/` (e.g. `RomNotFoundInDatabaseException`), not bare `HTTPException`, where a typed one exists.
|
||||
- **Validation/SSRF:** sanitize filenames/paths before filesystem use (`utils/`); paths are rooted at `LIBRARY_BASE_PATH`/`RESOURCES_BASE_PATH`/`ASSETS_BASE_PATH` from config.
|
||||
- **Statement types:** type a statement by its columns, as SQLAlchemy 2.1 does: `Select[Rom]`, `Row[int, str]`, not 2.0's `Select[tuple[Rom]]`. A helper that takes a select of any shape uses `Select[*tuple[Any, ...]]`; `Select[Any]` means one column.
|
||||
- **Engine-specific query SQL:** reach for a portable SQLAlchemy expression first. If the engines need different SQL, build both with `DialectCase(postgresql=..., mysql=...)` from `utils/sql_dialect.py` (or add a helper or `@compiles` construct there) rather than branching on `ROMM_DB_DRIVER` in a handler. `@compiles(..., "mysql")` alone misses MariaDB; use `_compiles_on_mysql_family`. Pin each spelling in tests by compiling for `MARIADB_DIALECT`/`POSTGRESQL_DIALECT` from `tests/sql_dialects.py`.
|
||||
|
||||
## Auth & scopes
|
||||
|
||||
16
Dockerfile
16
Dockerfile
@@ -126,6 +126,22 @@ RUN make HAVE_CHD=1 -f ./Makefile.RAHasher \
|
||||
&& cp ./bin64/RAHasher /usr/bin/RAHasher
|
||||
RUN rm -rf /tmp/RALibretro
|
||||
|
||||
# Install rom-converto (optional); its static musl build runs on this glibc image.
|
||||
# Keep the version and both sums in sync with docker/Dockerfile.
|
||||
ARG TARGETARCH
|
||||
RUN ROM_CONVERTO_VERSION=v0.23.0 \
|
||||
&& arch="${TARGETARCH:-$(dpkg --print-architecture)}" \
|
||||
&& case "${arch}" in \
|
||||
amd64) rc="linux-x64-musl"; sum="37d03a67ad97fc02768890e763b4c80072fdfd15f2c5b97e44f9a2b50fc40876" ;; \
|
||||
arm64) rc="linux-arm64-musl"; sum="8abe37ca2d1a0e3d719fb8e795e011c672e3f1c088521cf0bb1e467dc658dc3c" ;; \
|
||||
*) echo "unsupported architecture: ${arch}" && exit 1 ;; \
|
||||
esac \
|
||||
&& curl -fsSL -o "/tmp/rom-converto-cli-${rc}" \
|
||||
"https://github.com/DevYukine/rom-converto/releases/download/${ROM_CONVERTO_VERSION}/rom-converto-cli-${rc}" \
|
||||
&& echo "${sum} /tmp/rom-converto-cli-${rc}" | sha256sum -c --status \
|
||||
&& install -m 0755 "/tmp/rom-converto-cli-${rc}" /usr/bin/rom-converto \
|
||||
&& rm -f "/tmp/rom-converto-cli-${rc}"
|
||||
|
||||
# Install frontend dependencies
|
||||
COPY frontend/package.json /app/frontend/
|
||||
WORKDIR /app/frontend
|
||||
|
||||
341
backend/adapters/services/rom_converto.py
Normal file
341
backend/adapters/services/rom_converto.py
Normal file
@@ -0,0 +1,341 @@
|
||||
import asyncio
|
||||
import contextlib
|
||||
import json
|
||||
import shutil
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
from config import ROM_CONVERTO_ENABLED, ROM_CONVERTO_TIMEOUT
|
||||
from logger.formatter import LIGHTMAGENTA
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from utils.filesystem import SERVED_FILE_MODE
|
||||
from utils.platform_slugs import UniversalPlatformSlug as UPS
|
||||
|
||||
# The capabilities probe must never hang download paths; a real
|
||||
# manifest print is instant.
|
||||
_PROBE_TIMEOUT_SECONDS = 30
|
||||
|
||||
_STDERR_TAIL_BYTES = 400
|
||||
|
||||
_BINARY: Final = "rom-converto"
|
||||
|
||||
|
||||
class RomConvertoError(Exception): ...
|
||||
|
||||
|
||||
class RomConvertoBinaryNotFoundError(RomConvertoError): ...
|
||||
|
||||
|
||||
class RomConvertoTimeoutError(RomConvertoError): ...
|
||||
|
||||
|
||||
class RomConvertoOperationError(RomConvertoError):
|
||||
"""A conversion command exited nonzero."""
|
||||
|
||||
|
||||
# `xbox convert` keeps only a dump's game partition, so a library never stores its output.
|
||||
_LOSSY_ARGV: Final[frozenset[tuple[str, ...]]] = frozenset({("xbox", "convert")})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Operation:
|
||||
"""A subcommand bringing `input_exts` files to `target`; source and output are appended to `argv`."""
|
||||
|
||||
target: str
|
||||
platforms: frozenset[str]
|
||||
argv: tuple[str, ...]
|
||||
input_exts: frozenset[str]
|
||||
output_ext: str
|
||||
|
||||
@property
|
||||
def lossless(self) -> bool:
|
||||
return self.argv not in _LOSSY_ARGV
|
||||
|
||||
def output_name(self, src: Path, input_ext: str) -> str:
|
||||
"""`src` renamed from the matched lowercase `input_ext` to the output extension."""
|
||||
return f"{src.name[: len(src.name) - len(input_ext)]}{self.output_ext}"
|
||||
|
||||
|
||||
def _op(
|
||||
target: str,
|
||||
platforms: set[UPS],
|
||||
argv: str,
|
||||
input_exts: str,
|
||||
output_ext: str,
|
||||
) -> Operation:
|
||||
return Operation(
|
||||
target=target,
|
||||
platforms=frozenset(platforms),
|
||||
argv=tuple(argv.split()),
|
||||
input_exts=frozenset(input_exts.split()),
|
||||
output_ext=output_ext,
|
||||
)
|
||||
|
||||
|
||||
_DVD_PLATFORMS = {UPS.PSP, UPS.PS2}
|
||||
_CD_PLATFORMS = {UPS.PSX, UPS.SATURN, UPS.SEGACD, UPS.DC}
|
||||
|
||||
# The CLI's single-file format conversions. Decrypt/encrypt and directory-shaped
|
||||
# operations (Wii U packs, Switch merge/split, `extract`, Xbox 360 GoD) are left out.
|
||||
OPERATIONS: Final[tuple[Operation, ...]] = (
|
||||
# 3DS
|
||||
_op("z3ds", {UPS.N3DS}, "ctr compress", ".cia", ".zcia"),
|
||||
_op("z3ds", {UPS.N3DS}, "ctr compress", ".cci .3ds", ".zcci"),
|
||||
_op("z3ds", {UPS.N3DS}, "ctr compress", ".cxi", ".zcxi"),
|
||||
_op("cia", {UPS.N3DS}, "ctr decompress", ".zcia", ".cia"),
|
||||
_op("cia", {UPS.N3DS}, "ctr convert", ".3ds .cci", ".cia"),
|
||||
_op("cci", {UPS.N3DS}, "ctr decompress", ".zcci", ".cci"),
|
||||
_op("cci", {UPS.N3DS}, "ctr convert", ".cia", ".cci"),
|
||||
# Sony discs
|
||||
_op("iso", _DVD_PLATFORMS, "cso decompress", ".cso .zso .dax", ".iso"),
|
||||
# CD-mode CHDs extract to .bin/.cue, so only DVD platforms get this.
|
||||
_op("iso", _DVD_PLATFORMS, "chd extract", ".chd", ".iso"),
|
||||
_op("iso", _DVD_PLATFORMS, "cue to-iso", ".cue", ".iso"),
|
||||
_op("iso", {UPS.PSP}, "psp to-iso", ".pbp", ".iso"),
|
||||
_op("cso", _DVD_PLATFORMS, "cso compress --format cso", ".iso", ".cso"),
|
||||
_op("cso", _DVD_PLATFORMS, "chd to-cso --format cso", ".chd", ".cso"),
|
||||
_op("zso", _DVD_PLATFORMS, "cso compress --format zso", ".iso", ".zso"),
|
||||
_op("zso", _DVD_PLATFORMS, "chd to-cso --format zso", ".chd", ".zso"),
|
||||
_op("chd", _DVD_PLATFORMS | _CD_PLATFORMS, "chd compress", ".cue .iso", ".chd"),
|
||||
_op("chd", _DVD_PLATFORMS, "cso to-chd", ".cso .zso .dax", ".chd"),
|
||||
# GameCube / Wii
|
||||
_op("rvz", {UPS.NGC}, "dol compress", ".iso .gcm", ".rvz"),
|
||||
_op("rvz", {UPS.NGC}, "dol migrate", ".gcz .nkit.iso .nkit.gcz", ".rvz"),
|
||||
_op("iso", {UPS.NGC}, "dol decompress", ".rvz", ".iso"),
|
||||
_op("rvz", {UPS.WII}, "rvl compress", ".iso .wbfs", ".rvz"),
|
||||
_op("rvz", {UPS.WII}, "rvl migrate", ".wia .gcz .nkit.iso .nkit.gcz", ".rvz"),
|
||||
_op("iso", {UPS.WII}, "rvl decompress", ".rvz", ".iso"),
|
||||
_op("wbfs", {UPS.WII}, "rvl decompress", ".rvz", ".wbfs"),
|
||||
# Switch (prod.keys resolved by the CLI itself)
|
||||
_op("nsz", {UPS.SWITCH, UPS.SWITCH_2}, "nx compress", ".nsp", ".nsz"),
|
||||
_op("xcz", {UPS.SWITCH, UPS.SWITCH_2}, "nx compress", ".xci", ".xcz"),
|
||||
_op("nsp", {UPS.SWITCH, UPS.SWITCH_2}, "nx decompress", ".nsz", ".nsp"),
|
||||
_op("xci", {UPS.SWITCH, UPS.SWITCH_2}, "nx decompress", ".xcz", ".xci"),
|
||||
# Xbox
|
||||
_op("xiso", {UPS.XBOX}, "xbox convert", ".iso", ".xiso"),
|
||||
_op("zar", {UPS.XBOX360}, "xenon compress", ".iso", ".zar"),
|
||||
)
|
||||
|
||||
# Targets that store the image as-is, so converting to one can grow the file.
|
||||
UNCOMPRESSED_TARGETS: Final[frozenset[str]] = frozenset(
|
||||
{"cci", "cia", "iso", "nsp", "wbfs", "xci", "xiso"}
|
||||
)
|
||||
|
||||
|
||||
# Platform slug -> the targets a library can be stored in.
|
||||
LIBRARY_TARGETS_BY_PLATFORM: Final[dict[str, frozenset[str]]] = {
|
||||
slug: frozenset(
|
||||
op.target for op in OPERATIONS if slug in op.platforms and op.lossless
|
||||
)
|
||||
for slug in sorted(
|
||||
{slug for op in OPERATIONS if op.lossless for slug in op.platforms}
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def _download_formats() -> dict[str, dict[str, list[str]]]:
|
||||
table: dict[str, dict[str, set[str]]] = {}
|
||||
for op in OPERATIONS:
|
||||
for slug in op.platforms:
|
||||
for ext in op.input_exts:
|
||||
table.setdefault(slug, {}).setdefault(ext, set()).add(op.target)
|
||||
return {
|
||||
slug: {ext: sorted(targets) for ext, targets in sorted(exts.items())}
|
||||
for slug, exts in sorted(table.items())
|
||||
}
|
||||
|
||||
|
||||
# Platform slug -> input extension -> the targets a download of it can be converted to.
|
||||
DOWNLOAD_FORMATS: Final[dict[str, dict[str, list[str]]]] = _download_formats()
|
||||
|
||||
|
||||
# Extensions whose format goes by another name than the extension itself.
|
||||
_FORMAT_ALIASES: Final[dict[str, str]] = {
|
||||
".3ds": "cci",
|
||||
".gcm": "iso",
|
||||
".zcci": "z3ds",
|
||||
".zcia": "z3ds",
|
||||
".zcxi": "z3ds",
|
||||
}
|
||||
_KNOWN_EXTS: Final[frozenset[str]] = frozenset(
|
||||
{ext for op in OPERATIONS for ext in (*op.input_exts, op.output_ext)}
|
||||
| _FORMAT_ALIASES.keys()
|
||||
)
|
||||
|
||||
|
||||
def file_format(file_name: str) -> str:
|
||||
"""The format `file_name` is in, as a target name or its extension (`nkit-iso`)."""
|
||||
name = file_name.lower()
|
||||
ext = max((e for e in _KNOWN_EXTS if name.endswith(e)), key=len, default=None)
|
||||
if ext is None:
|
||||
return Path(name).suffix.lstrip(".")
|
||||
return _FORMAT_ALIASES.get(ext, ext.lstrip(".").replace(".", "-"))
|
||||
|
||||
|
||||
def canonical_format(name: str) -> str:
|
||||
"""The target name a client means by `name`, so `3ds` reads as `cci`."""
|
||||
return _FORMAT_ALIASES.get(f".{name}", name)
|
||||
|
||||
|
||||
def normalize_platform_formats(raw: dict[str, str]) -> dict[str, str]:
|
||||
"""`raw` with slugs and library targets trimmed and lowercased.
|
||||
|
||||
Raises:
|
||||
ValueError: A platform has no library targets, or a target isn't one of them.
|
||||
"""
|
||||
cleaned = {
|
||||
str(slug).strip().lower(): str(target).strip().lower()
|
||||
for slug, target in raw.items()
|
||||
}
|
||||
for slug, target in cleaned.items():
|
||||
targets = LIBRARY_TARGETS_BY_PLATFORM.get(slug)
|
||||
if targets is None:
|
||||
raise ValueError(
|
||||
f"rom-converto has no library formats for {slug!r}. "
|
||||
f"Supported: {sorted(LIBRARY_TARGETS_BY_PLATFORM)}."
|
||||
)
|
||||
if target not in targets:
|
||||
raise ValueError(
|
||||
f"{target!r} is not a conversion target for {slug}. "
|
||||
f"Valid options: {sorted(targets)}."
|
||||
)
|
||||
return cleaned
|
||||
|
||||
|
||||
def resolve_operation(
|
||||
platform_slug: str, target: str, file_name: str, *, lossless: bool = False
|
||||
) -> tuple[Operation, str] | None:
|
||||
"""The operation and matched extension bringing `file_name` to `target`, or None if none applies."""
|
||||
name = file_name.lower()
|
||||
best: tuple[Operation, str] | None = None
|
||||
for op in OPERATIONS:
|
||||
if op.target != target or platform_slug not in op.platforms:
|
||||
continue
|
||||
if lossless and not op.lossless:
|
||||
continue
|
||||
for ext in op.input_exts:
|
||||
# Prefer the longer extension so `.nkit.iso` is not read as `.iso`.
|
||||
if name.endswith(ext) and (best is None or len(ext) > len(best[1])):
|
||||
best = (op, ext)
|
||||
return best
|
||||
|
||||
|
||||
def _tail(text: str) -> str:
|
||||
return text.strip()[-_STDERR_TAIL_BYTES:]
|
||||
|
||||
|
||||
async def _run(argv: list[str], timeout_seconds: float) -> tuple[int, str, str]:
|
||||
"""Run a rom-converto subcommand and return (returncode, stdout, stderr)."""
|
||||
binary = await asyncio.to_thread(shutil.which, _BINARY)
|
||||
if binary is None:
|
||||
raise RomConvertoBinaryNotFoundError(f"{_BINARY} binary not found on PATH")
|
||||
# The CLI otherwise asks api.github.com for a newer release on every run.
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
binary,
|
||||
"--no-update-check",
|
||||
*argv,
|
||||
stdin=asyncio.subprocess.DEVNULL,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
try:
|
||||
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout_seconds)
|
||||
except TimeoutError as err:
|
||||
_kill(proc)
|
||||
# Drain the pipes so the transport closes instead of leaking its fds.
|
||||
await proc.communicate()
|
||||
raise RomConvertoTimeoutError(
|
||||
f"rom-converto {' '.join(argv[:2])} timed out after {timeout_seconds}s"
|
||||
) from err
|
||||
except BaseException:
|
||||
# A cancelled caller must not leave a conversion running unowned.
|
||||
_kill(proc)
|
||||
raise
|
||||
|
||||
return (
|
||||
proc.returncode or 0,
|
||||
stdout.decode("utf-8", errors="replace"),
|
||||
stderr.decode("utf-8", errors="replace"),
|
||||
)
|
||||
|
||||
|
||||
def _settle_output(operation: Operation, out: Path) -> None:
|
||||
"""Check `out` is all the command wrote beside it, and make it servable."""
|
||||
if [p.name for p in out.parent.iterdir()] != [out.name]:
|
||||
raise RomConvertoOperationError(
|
||||
f"rom-converto {' '.join(operation.argv)} did not write exactly {out.name}"
|
||||
)
|
||||
# rom-converto may write an owner-only file, which nginx can't serve.
|
||||
out.chmod(SERVED_FILE_MODE)
|
||||
|
||||
|
||||
def _kill(proc: asyncio.subprocess.Process) -> None:
|
||||
with contextlib.suppress(ProcessLookupError):
|
||||
proc.kill()
|
||||
|
||||
|
||||
class RomConvertoService:
|
||||
"""Service to convert ROMs using the rom-converto CLI."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._available: bool | None = None
|
||||
self._probe_lock = asyncio.Lock()
|
||||
|
||||
async def is_enabled(self) -> bool:
|
||||
if not ROM_CONVERTO_ENABLED:
|
||||
return False
|
||||
if self._available is not None:
|
||||
return self._available
|
||||
async with self._probe_lock:
|
||||
if self._available is not None:
|
||||
return self._available
|
||||
# A corrupt or wrong-arch binary passes which(); a missing one
|
||||
# stays uncached so installing it needs no restart.
|
||||
failure: str | None
|
||||
try:
|
||||
code, stdout, _ = await _run(["capabilities"], _PROBE_TIMEOUT_SECONDS)
|
||||
except RomConvertoBinaryNotFoundError:
|
||||
return False
|
||||
except (RomConvertoTimeoutError, OSError) as exc:
|
||||
failure = str(exc)
|
||||
else:
|
||||
failure = f"code {code}" if code != 0 else None
|
||||
if failure is not None:
|
||||
log.warning(
|
||||
f"{hl(_BINARY)} failed its capability "
|
||||
f"probe ({failure}); disabling integration until restart"
|
||||
)
|
||||
self._available = False
|
||||
return False
|
||||
try:
|
||||
manifest = json.loads(stdout)
|
||||
except json.JSONDecodeError:
|
||||
manifest = None
|
||||
version = (
|
||||
manifest.get("version") if isinstance(manifest, dict) else None
|
||||
) or "unknown version"
|
||||
log.info(
|
||||
f"Detected {hl('rom-converto', color=LIGHTMAGENTA)} {hl(str(version))}"
|
||||
)
|
||||
self._available = True
|
||||
return True
|
||||
|
||||
async def convert(self, operation: Operation, src: Path, out: Path) -> None:
|
||||
"""Run `operation` on `src`, writing `out`, which must be alone in its directory.
|
||||
|
||||
Raises:
|
||||
RomConvertoOperationError: The command failed or wrote more than `out`.
|
||||
"""
|
||||
argv = [*operation.argv, str(src), str(out)]
|
||||
code, stdout, stderr = await _run(argv, ROM_CONVERTO_TIMEOUT)
|
||||
if code != 0:
|
||||
diagnostic = _tail(stderr) or _tail(stdout)
|
||||
raise RomConvertoOperationError(
|
||||
f"rom-converto {' '.join(operation.argv)} failed with code {code}: {diagnostic}"
|
||||
)
|
||||
await asyncio.to_thread(_settle_output, operation, out)
|
||||
|
||||
|
||||
rom_converto_service = RomConvertoService()
|
||||
@@ -65,6 +65,19 @@ ROM_PATCHER_MAX_CONCURRENCY: Final[int] = max(
|
||||
1, safe_int(_get_env("ROM_PATCHER_MAX_CONCURRENCY"), 2)
|
||||
)
|
||||
|
||||
# ROM CONVERTO
|
||||
ROM_CONVERTO_ENABLED: Final[bool] = safe_str_to_bool(_get_env("ROM_CONVERTO_ENABLED"))
|
||||
# Seconds per rom-converto CLI operation.
|
||||
ROM_CONVERTO_TIMEOUT: Final[int] = max(
|
||||
1, safe_int(_get_env("ROM_CONVERTO_TIMEOUT"), 600)
|
||||
)
|
||||
# Concurrent conversion subprocesses per process (each web and RQ worker).
|
||||
ROM_CONVERTO_MAX_CONCURRENCY: Final[int] = max(
|
||||
1, safe_int(_get_env("ROM_CONVERTO_MAX_CONCURRENCY"), 2)
|
||||
)
|
||||
# Disk cache for converted downloads, under the tree nginx serves at /cache/.
|
||||
ROM_CONVERTO_CACHE_PATH: Final[str] = f"{ROMM_BASE_PATH}/cache/converts"
|
||||
|
||||
# DATABASE
|
||||
DB_HOST: Final[str | None] = _get_env("DB_HOST")
|
||||
DB_PORT: Final[int] = safe_int(_get_env("DB_PORT"), 3306)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import dataclasses
|
||||
import enum
|
||||
import functools
|
||||
import glob
|
||||
@@ -14,6 +15,7 @@ import yaml
|
||||
from sqlalchemy import URL
|
||||
from yaml.loader import SafeLoader
|
||||
|
||||
from adapters.services.rom_converto import normalize_platform_formats
|
||||
from config import (
|
||||
DB_HOST,
|
||||
DB_NAME,
|
||||
@@ -401,6 +403,22 @@ VALID_SCAN_PRIORITY_SOURCES = frozenset(
|
||||
VALID_SCAN_REGION_MODES = frozenset({"prefer_rom_tags", "prefer_config"})
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class ConvertoConfig:
|
||||
download_conversion_enabled: bool = False
|
||||
cache_ttl_hours: int = 24
|
||||
# 0 leaves the cache unbounded.
|
||||
cache_max_size_gb: int = 20
|
||||
platform_formats: dict[str, str] = dataclasses.field(default_factory=dict)
|
||||
|
||||
|
||||
# The smallest value each integer converto.* setting accepts.
|
||||
CONVERTO_INT_MINIMUMS: Final[dict[str, int]] = {
|
||||
"cache_ttl_hours": 1,
|
||||
"cache_max_size_gb": 0,
|
||||
}
|
||||
|
||||
|
||||
class EjsControls(TypedDict):
|
||||
_0: dict[int, EjsControlsButton] # button_number -> EjsControlsButton
|
||||
_1: dict[int, EjsControlsButton]
|
||||
@@ -506,6 +524,7 @@ class Config:
|
||||
GAMELIST_MEDIA_IMAGE: MetadataMediaType
|
||||
STREAMING_ENABLED: bool
|
||||
STREAMING_CONTAINERS: list[StreamingContainer]
|
||||
CONVERTO: ConvertoConfig
|
||||
|
||||
def __init__(self, **entries: Any) -> None:
|
||||
self.__dict__.update(entries)
|
||||
@@ -879,6 +898,12 @@ class ConfigManager:
|
||||
STREAMING_CONTAINERS=pydash.get(
|
||||
self._raw_config, "streaming.containers", []
|
||||
),
|
||||
CONVERTO=ConvertoConfig(
|
||||
**{
|
||||
key: pydash.get(self._raw_config, f"converto.{key}", default)
|
||||
for key, default in dataclasses.asdict(ConvertoConfig()).items()
|
||||
}
|
||||
),
|
||||
STRUCTURE_TEMPLATES=pydash.get(
|
||||
self._raw_config, "filesystem.structure", {}
|
||||
),
|
||||
@@ -1281,6 +1306,31 @@ class ConfigManager:
|
||||
len(legacy_containers),
|
||||
)
|
||||
|
||||
if not isinstance(self.config.CONVERTO.download_conversion_enabled, bool):
|
||||
log.critical(
|
||||
"Invalid config.yml: converto.download_conversion_enabled must be a boolean"
|
||||
)
|
||||
sys.exit(3)
|
||||
|
||||
for key, minimum in CONVERTO_INT_MINIMUMS.items():
|
||||
value = getattr(self.config.CONVERTO, key)
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value < minimum:
|
||||
log.critical(
|
||||
f"Invalid config.yml: converto.{key} must be an integer >= {minimum}"
|
||||
)
|
||||
sys.exit(3)
|
||||
|
||||
try:
|
||||
self.config.CONVERTO.platform_formats = normalize_platform_formats(
|
||||
self._validated_platform_map(
|
||||
self.config.CONVERTO.platform_formats or {},
|
||||
"converto.platform_formats",
|
||||
)
|
||||
)
|
||||
except ValueError as exc:
|
||||
log.critical(f"Invalid config.yml: converto.platform_formats: {exc}")
|
||||
sys.exit(3)
|
||||
|
||||
def get_config(self) -> Config:
|
||||
try:
|
||||
with open(self.config_file, "r") as config_file:
|
||||
@@ -1366,6 +1416,7 @@ class ConfigManager:
|
||||
"export": self.config.PEGASUS_AUTO_EXPORT_ON_SCAN,
|
||||
},
|
||||
},
|
||||
"converto": dataclasses.asdict(self.config.CONVERTO),
|
||||
}
|
||||
|
||||
# The streaming section isn't editable at runtime, but it must survive
|
||||
@@ -1500,5 +1551,10 @@ class ConfigManager:
|
||||
self.config.PEGASUS_AUTO_EXPORT_ON_SCAN = pegasus_export
|
||||
self._update_config_file()
|
||||
|
||||
def update_converto_settings(self, converto: ConvertoConfig) -> None:
|
||||
"""Replace the whole converto.* section and persist it to config.yml."""
|
||||
self.config.CONVERTO = converto
|
||||
self._update_config_file()
|
||||
|
||||
|
||||
config_manager = ConfigManager()
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
from fastapi import HTTPException, Request, status
|
||||
from pydantic import BaseModel, field_validator
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from adapters.services.rom_converto import (
|
||||
DOWNLOAD_FORMATS,
|
||||
LIBRARY_TARGETS_BY_PLATFORM,
|
||||
normalize_platform_formats,
|
||||
)
|
||||
from config.config_manager import (
|
||||
CONVERTO_INT_MINIMUMS,
|
||||
DEFAULT_EXCLUDED_EXTENSIONS,
|
||||
DEFAULT_EXCLUDED_FILES,
|
||||
DEFAULT_EXCLUDED_MULTI_FILE_DIRS,
|
||||
@@ -9,6 +15,7 @@ from config.config_manager import (
|
||||
VALID_GAMELIST_IMAGE_TYPES,
|
||||
VALID_GAMELIST_THUMBNAIL_TYPES,
|
||||
VALID_SCAN_PRIORITY_SOURCES,
|
||||
ConvertoConfig,
|
||||
ExclusionType,
|
||||
MetadataMediaType,
|
||||
)
|
||||
@@ -117,6 +124,19 @@ class ScanSettingsPayload(BaseModel):
|
||||
return value
|
||||
|
||||
|
||||
class ConvertoSettingsPayload(BaseModel):
|
||||
"""The converto.* settings editable at runtime; `cache_ttl_hours` stays config.yml-only."""
|
||||
|
||||
download_conversion_enabled: bool
|
||||
cache_max_size_gb: int = Field(ge=CONVERTO_INT_MINIMUMS["cache_max_size_gb"])
|
||||
platform_formats: dict[str, str]
|
||||
|
||||
@field_validator("platform_formats")
|
||||
@classmethod
|
||||
def validate_platform_formats(cls, value: dict[str, str]) -> dict[str, str]:
|
||||
return normalize_platform_formats(value)
|
||||
|
||||
|
||||
@router.get("")
|
||||
def get_config(request: Request) -> ConfigResponse:
|
||||
"""Get config endpoint
|
||||
@@ -169,6 +189,12 @@ def get_config(request: Request) -> ConfigResponse:
|
||||
GAMELIST_MEDIA_THUMBNAIL=cfg.GAMELIST_MEDIA_THUMBNAIL,
|
||||
GAMELIST_MEDIA_IMAGE=cfg.GAMELIST_MEDIA_IMAGE,
|
||||
PEGASUS_AUTO_EXPORT_ON_SCAN=cfg.PEGASUS_AUTO_EXPORT_ON_SCAN,
|
||||
CONVERTO=cfg.CONVERTO,
|
||||
CONVERTO_LIBRARY_TARGETS={
|
||||
slug: sorted(targets)
|
||||
for slug, targets in LIBRARY_TARGETS_BY_PLATFORM.items()
|
||||
},
|
||||
CONVERTO_DOWNLOAD_FORMATS=DOWNLOAD_FORMATS,
|
||||
)
|
||||
|
||||
|
||||
@@ -338,3 +364,24 @@ async def update_scan_settings(request: Request, payload: ScanSettingsPayload) -
|
||||
# cached gallery sidecar is stale the moment the order changes.
|
||||
if region_priority_changed:
|
||||
db_rom_handler.invalidate_filter_values_cache()
|
||||
|
||||
|
||||
@protected_route(router.put, "/converto_settings", [Scope.PLATFORMS_WRITE])
|
||||
async def update_converto_settings(
|
||||
request: Request, payload: ConvertoSettingsPayload
|
||||
) -> None:
|
||||
"""Update the runtime-editable converto.* settings"""
|
||||
|
||||
current = cm.get_config().CONVERTO
|
||||
try:
|
||||
cm.update_converto_settings(
|
||||
ConvertoConfig(
|
||||
**payload.model_dump(), cache_ttl_hours=current.cache_ttl_hours
|
||||
)
|
||||
)
|
||||
except ConfigNotWritableException as exc:
|
||||
log.critical(exc.message)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
|
||||
) from exc
|
||||
_record_config(request, "converto_settings", "update")
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
from typing import TypedDict
|
||||
|
||||
from config.config_manager import EjsControls, MetadataMediaType, NetplayICEServer
|
||||
from config.config_manager import (
|
||||
ConvertoConfig,
|
||||
EjsControls,
|
||||
MetadataMediaType,
|
||||
NetplayICEServer,
|
||||
)
|
||||
|
||||
|
||||
class ConfigResponse(TypedDict):
|
||||
@@ -40,3 +45,8 @@ class ConfigResponse(TypedDict):
|
||||
GAMELIST_MEDIA_THUMBNAIL: MetadataMediaType
|
||||
GAMELIST_MEDIA_IMAGE: MetadataMediaType
|
||||
PEGASUS_AUTO_EXPORT_ON_SCAN: bool
|
||||
CONVERTO: ConvertoConfig
|
||||
# Platform slug -> the formats its library can be stored in.
|
||||
CONVERTO_LIBRARY_TARGETS: dict[str, list[str]]
|
||||
# Platform slug -> input extension -> the formats a download can be converted to.
|
||||
CONVERTO_DOWNLOAD_FORMATS: dict[str, dict[str, list[str]]]
|
||||
|
||||
@@ -122,6 +122,7 @@ from models.rom import (
|
||||
PINNED_MEDIA_MAX_ITEMS,
|
||||
TITLE_ID_MAX_LENGTH,
|
||||
Rom,
|
||||
RomFile,
|
||||
RomIdentity,
|
||||
RomUserStatus,
|
||||
SaveTargetLayout,
|
||||
@@ -130,6 +131,13 @@ from models.rom import (
|
||||
)
|
||||
from utils import switch
|
||||
from utils.background_tasks import fire_and_forget
|
||||
from utils.conversion_cache import (
|
||||
RETRY_AFTER_SECONDS,
|
||||
FormatOutcome,
|
||||
get_redirect_path,
|
||||
parse_formats,
|
||||
resolve_format_download,
|
||||
)
|
||||
from utils.database import safe_int, safe_str_to_bool
|
||||
from utils.filesystem import check_filename_length, sanitize_filename
|
||||
from utils.hashing import crc32_to_hex
|
||||
@@ -1312,11 +1320,86 @@ def get_rom(
|
||||
return DetailedRomSchema.from_orm_with_request(rom, request)
|
||||
|
||||
|
||||
CONTENT_RESPONSES: Final[dict[int | str, dict[str, Any]]] = {
|
||||
status.HTTP_202_ACCEPTED: {
|
||||
"description": "The requested format is converting; retry after Retry-After."
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {},
|
||||
status.HTTP_406_NOT_ACCEPTABLE: {
|
||||
"description": "No requested format can be served for this download."
|
||||
},
|
||||
}
|
||||
|
||||
FormatQuery = Annotated[
|
||||
str | None,
|
||||
Query(
|
||||
alias="format",
|
||||
description="Comma-separated formats the client can read, such as "
|
||||
"`zso,iso`. The stored file is served when its format is listed, else "
|
||||
"a converted copy: 202 with Retry-After while it converts, 406 when no "
|
||||
"listed format can be produced. Single-file downloads only.",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
async def _negotiate_format(
|
||||
request: Request,
|
||||
rom: Rom,
|
||||
files: list[RomFile],
|
||||
raw_formats: str | None,
|
||||
*,
|
||||
start: bool,
|
||||
) -> Response | None:
|
||||
"""The response a `?format=` download gets, or None to serve the stored file."""
|
||||
formats = parse_formats(raw_formats or "")
|
||||
if not formats:
|
||||
return None
|
||||
if len(files) != 1:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_406_NOT_ACCEPTABLE,
|
||||
detail="A format can only be requested for a single file",
|
||||
)
|
||||
|
||||
file = files[0]
|
||||
# DISABLE_DOWNLOAD_ENDPOINT_AUTH and KIOSK_MODE open this route to visitors,
|
||||
# and a conversion is minutes of CPU.
|
||||
allowed = request.user.is_authenticated and not request.user.is_kiosk_guest
|
||||
resolution = await resolve_format_download(
|
||||
rom, file, formats, allowed=allowed, start=start, touch=start
|
||||
)
|
||||
if resolution.outcome == FormatOutcome.ORIGINAL:
|
||||
return None
|
||||
if resolution.outcome == FormatOutcome.PENDING:
|
||||
return Response(
|
||||
status_code=status.HTTP_202_ACCEPTED,
|
||||
headers={"Retry-After": str(RETRY_AFTER_SECONDS)},
|
||||
)
|
||||
if resolution.outcome == FormatOutcome.UNAVAILABLE or resolution.path is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_406_NOT_ACCEPTABLE,
|
||||
detail=f"{file.file_name} can't be served as {', '.join(formats)}",
|
||||
)
|
||||
|
||||
converted = resolution.path
|
||||
if DEV_MODE:
|
||||
return FileResponse(
|
||||
path=converted,
|
||||
filename=converted.name,
|
||||
headers={
|
||||
"Content-Disposition": content_disposition(converted.name),
|
||||
"Content-Type": "application/octet-stream",
|
||||
},
|
||||
)
|
||||
return FileRedirectResponse(
|
||||
download_path=get_redirect_path(converted), filename=converted.name
|
||||
)
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.head,
|
||||
"/{id}/content/{file_name}",
|
||||
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
|
||||
responses={status.HTTP_404_NOT_FOUND: {}},
|
||||
responses=CONTENT_RESPONSES,
|
||||
)
|
||||
async def head_rom_content(
|
||||
request: Request,
|
||||
@@ -1328,6 +1411,7 @@ async def head_rom_content(
|
||||
description="Comma-separated list of file ids to download for multi-part roms."
|
||||
),
|
||||
] = None,
|
||||
formats: FormatQuery = None,
|
||||
) -> Response:
|
||||
"""Retrieve head information for a rom file download."""
|
||||
|
||||
@@ -1350,6 +1434,10 @@ async def head_rom_content(
|
||||
detail=f"No files found for ROM {id}",
|
||||
)
|
||||
|
||||
# Report what a GET would serve, but never start a conversion.
|
||||
if negotiated := await _negotiate_format(request, rom, files, formats, start=False):
|
||||
return negotiated
|
||||
|
||||
# Serve the file directly in development mode for emulatorjs
|
||||
if DEV_MODE:
|
||||
if len(files) == 1:
|
||||
@@ -1410,7 +1498,7 @@ async def head_rom_content(
|
||||
router.get,
|
||||
"/{id}/content/{file_name}",
|
||||
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
|
||||
responses={status.HTTP_404_NOT_FOUND: {}},
|
||||
responses=CONTENT_RESPONSES,
|
||||
)
|
||||
async def get_rom_content(
|
||||
request: Request,
|
||||
@@ -1429,6 +1517,7 @@ async def get_rom_content(
|
||||
"recorded as a player load rather than a download."
|
||||
),
|
||||
] = "download",
|
||||
formats: FormatQuery = None,
|
||||
) -> Response:
|
||||
"""Download a rom.
|
||||
|
||||
@@ -1494,6 +1583,13 @@ async def get_rom_content(
|
||||
)
|
||||
return response
|
||||
|
||||
if negotiated := await _negotiate_format(request, rom, files, formats, start=True):
|
||||
return (
|
||||
served(negotiated)
|
||||
if negotiated.status_code == status.HTTP_200_OK
|
||||
else negotiated
|
||||
)
|
||||
|
||||
m3u_files = playlist_files(files)
|
||||
|
||||
# Serve the file directly in development mode for emulatorjs
|
||||
|
||||
@@ -56,6 +56,7 @@ VISIBLE_SCHEDULED_TASKS: Final[dict[str, TaskSpec]] = {
|
||||
"build_recommendations",
|
||||
"convert_images_to_webp",
|
||||
"cleanup_zip_cache",
|
||||
"cleanup_conversion_cache",
|
||||
"cleanup_orphaned_resources",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ class AuditEventFilters:
|
||||
|
||||
|
||||
def _not_targeting(
|
||||
target_type: str, ids: Collection[int] | Select[tuple[str]]
|
||||
target_type: str, ids: Collection[int] | Select[str]
|
||||
) -> ColumnElement[bool]:
|
||||
"""Events other than those on the given targets of one type."""
|
||||
excluded = ids if isinstance(ids, Select) else [str(i) for i in ids]
|
||||
|
||||
@@ -56,10 +56,10 @@ if DEV_SQL_ECHO:
|
||||
class DBBaseHandler: ...
|
||||
|
||||
|
||||
def affected_rows(result: Result[Any]) -> int:
|
||||
def affected_rows(result: Result[*tuple[Any, ...]]) -> int:
|
||||
"""How many rows an UPDATE or DELETE run through `Session.execute` matched."""
|
||||
# Session.execute is typed to return Result, but DML gets a CursorResult.
|
||||
return cast(CursorResult[Any], result).rowcount
|
||||
return cast(CursorResult[*tuple[Any, ...]], result).rowcount
|
||||
|
||||
|
||||
# A process may load one model, whose relationships name others by string, and
|
||||
|
||||
@@ -59,7 +59,7 @@ def _roms_load_options() -> list[Any]:
|
||||
|
||||
|
||||
# Default for a `query` parameter that with_roms fills before the body runs.
|
||||
INJECTED_COLLECTION_QUERY = cast(Select[tuple[Collection]], None)
|
||||
INJECTED_COLLECTION_QUERY = cast(Select[Collection], None)
|
||||
|
||||
|
||||
def with_roms[**P, R](func: Callable[P, R]) -> Callable[P, R]:
|
||||
@@ -77,7 +77,7 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
def add_collection(
|
||||
self,
|
||||
collection: Collection,
|
||||
query: Select[tuple[Collection]] = INJECTED_COLLECTION_QUERY,
|
||||
query: Select[Collection] = INJECTED_COLLECTION_QUERY,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> Collection:
|
||||
collection = session.merge(collection)
|
||||
@@ -90,7 +90,7 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
def get_collection(
|
||||
self,
|
||||
id: int,
|
||||
query: Select[tuple[Collection]] = INJECTED_COLLECTION_QUERY,
|
||||
query: Select[Collection] = INJECTED_COLLECTION_QUERY,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> Collection | None:
|
||||
return session.scalar(query.filter_by(id=id).limit(1))
|
||||
@@ -101,7 +101,7 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
self,
|
||||
name: str,
|
||||
user_id: int,
|
||||
query: Select[tuple[Collection]] = INJECTED_COLLECTION_QUERY,
|
||||
query: Select[Collection] = INJECTED_COLLECTION_QUERY,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> Collection | None:
|
||||
return session.scalar(query.filter_by(name=name, user_id=user_id).limit(1))
|
||||
@@ -111,7 +111,7 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
def get_favorite_collection(
|
||||
self,
|
||||
user_id: int,
|
||||
query: Select[tuple[Collection]] = INJECTED_COLLECTION_QUERY,
|
||||
query: Select[Collection] = INJECTED_COLLECTION_QUERY,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> Collection | None:
|
||||
return session.scalar(
|
||||
@@ -121,7 +121,7 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
def _collections_query(
|
||||
self,
|
||||
updated_after: datetime | None = None,
|
||||
) -> Select[tuple[Collection]]:
|
||||
) -> Select[Collection]:
|
||||
query = select(Collection)
|
||||
|
||||
if updated_after:
|
||||
@@ -143,7 +143,7 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
self,
|
||||
updated_after: datetime | None = None,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> list[Row[tuple[int, int, bool]]]:
|
||||
) -> list[Row[int, int, bool]]:
|
||||
"""Id, owner and visibility only, so neither eager load fires."""
|
||||
query = self._collections_query(updated_after=updated_after)
|
||||
return list(
|
||||
@@ -161,7 +161,7 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
id: int,
|
||||
data: dict[str, Any],
|
||||
rom_ids: list[int] | None = None,
|
||||
query: Select[tuple[Collection]] = INJECTED_COLLECTION_QUERY,
|
||||
query: Select[Collection] = INJECTED_COLLECTION_QUERY,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> Collection:
|
||||
session.execute(
|
||||
@@ -200,7 +200,7 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
self,
|
||||
id: int,
|
||||
rom_ids: list[int],
|
||||
query: Select[tuple[Collection]] = INJECTED_COLLECTION_QUERY,
|
||||
query: Select[Collection] = INJECTED_COLLECTION_QUERY,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> Collection:
|
||||
if rom_ids:
|
||||
@@ -243,7 +243,7 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
self,
|
||||
id: int,
|
||||
rom_ids: list[int],
|
||||
query: Select[tuple[Collection]] = INJECTED_COLLECTION_QUERY,
|
||||
query: Select[Collection] = INJECTED_COLLECTION_QUERY,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> Collection:
|
||||
if rom_ids:
|
||||
@@ -294,7 +294,7 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
if not collections:
|
||||
return
|
||||
|
||||
def covers_select(collection: VirtualCollection) -> Select[Any]:
|
||||
def covers_select(collection: VirtualCollection) -> Select[*tuple[Any, ...]]:
|
||||
return (
|
||||
select(
|
||||
VirtualCollectionRom.type,
|
||||
@@ -372,7 +372,7 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
|
||||
return collections
|
||||
|
||||
def get_virtual_collection_rom_ids(self, id: str) -> Select[tuple[int]]:
|
||||
def get_virtual_collection_rom_ids(self, id: str) -> Select[int]:
|
||||
"""Select the rom ids of a virtual collection, as an indexed subquery."""
|
||||
name, type = VirtualCollection.from_id(id)
|
||||
return select(VirtualCollectionRom.rom_id).where(
|
||||
@@ -416,7 +416,7 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
self,
|
||||
user_id: int | None = None,
|
||||
updated_after: datetime | None = None,
|
||||
) -> Select[tuple[SmartCollection]]:
|
||||
) -> Select[SmartCollection]:
|
||||
query = select(SmartCollection).order_by(SmartCollection.name.asc())
|
||||
|
||||
if user_id is not None:
|
||||
@@ -516,7 +516,7 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
def build_smart_collection_query[S: Select[Any]](
|
||||
def build_smart_collection_query[S: Select[*tuple[Any, ...]]](
|
||||
self,
|
||||
*,
|
||||
query: S,
|
||||
@@ -556,7 +556,7 @@ class DBCollectionsHandler(DBBaseHandler):
|
||||
smart_collection: SmartCollection,
|
||||
user_id: int | None = None,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> Sequence[Row[tuple[int, str | None, str | None]]]:
|
||||
) -> Sequence[Row[int, str | None, str | None]]:
|
||||
"""Every member's id and cover paths, in the collection's own order.
|
||||
|
||||
Only the columns the cached membership needs, so refreshing never
|
||||
|
||||
@@ -34,7 +34,7 @@ class DBFirmwareHandler(DBBaseHandler):
|
||||
platform_ids: Sequence[int] | None = None,
|
||||
missing: bool | None = None,
|
||||
hidden_platform_ids: Collection[int] | None = None,
|
||||
) -> Select[tuple[Firmware]]:
|
||||
) -> Select[Firmware]:
|
||||
query = select(Firmware).order_by(Firmware.file_name.asc())
|
||||
|
||||
if platform_ids:
|
||||
|
||||
@@ -13,7 +13,7 @@ from models.rom import Rom
|
||||
from .base_handler import DBBaseHandler
|
||||
|
||||
# Default for a `query` parameter that with_firmware fills before the body runs.
|
||||
INJECTED_PLATFORM_QUERY = cast(Select[tuple[Platform]], None)
|
||||
INJECTED_PLATFORM_QUERY = cast(Select[Platform], None)
|
||||
|
||||
|
||||
def with_firmware[**P, R](func: Callable[P, R]) -> Callable[P, R]:
|
||||
@@ -33,7 +33,7 @@ class DBPlatformsHandler(DBBaseHandler):
|
||||
def add_platform(
|
||||
self,
|
||||
platform: Platform,
|
||||
query: Select[tuple[Platform]] = INJECTED_PLATFORM_QUERY,
|
||||
query: Select[Platform] = INJECTED_PLATFORM_QUERY,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> Platform:
|
||||
platform = session.merge(platform)
|
||||
@@ -61,7 +61,7 @@ class DBPlatformsHandler(DBBaseHandler):
|
||||
def get_platform(
|
||||
self,
|
||||
id: int,
|
||||
query: Select[tuple[Platform]] = INJECTED_PLATFORM_QUERY,
|
||||
query: Select[Platform] = INJECTED_PLATFORM_QUERY,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> Platform | None:
|
||||
return session.scalar(query.filter_by(id=id).limit(1))
|
||||
@@ -72,7 +72,7 @@ class DBPlatformsHandler(DBBaseHandler):
|
||||
self,
|
||||
updated_after: datetime | None = None,
|
||||
hidden_platform_ids: Collection[int] | None = None,
|
||||
query: Select[tuple[Platform]] = INJECTED_PLATFORM_QUERY,
|
||||
query: Select[Platform] = INJECTED_PLATFORM_QUERY,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> Sequence[Platform]:
|
||||
if updated_after:
|
||||
@@ -104,7 +104,7 @@ class DBPlatformsHandler(DBBaseHandler):
|
||||
def get_platform_by_fs_slug(
|
||||
self,
|
||||
fs_slug: str,
|
||||
query: Select[tuple[Platform]] = INJECTED_PLATFORM_QUERY,
|
||||
query: Select[Platform] = INJECTED_PLATFORM_QUERY,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> Platform | None:
|
||||
platform = session.scalar(query.filter_by(fs_slug=fs_slug).limit(1))
|
||||
@@ -122,7 +122,7 @@ class DBPlatformsHandler(DBBaseHandler):
|
||||
def get_platform_by_slug(
|
||||
self,
|
||||
slug: str,
|
||||
query: Select[tuple[Platform]] = INJECTED_PLATFORM_QUERY,
|
||||
query: Select[Platform] = INJECTED_PLATFORM_QUERY,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> Platform | None:
|
||||
return session.scalar(query.filter_by(slug=slug).limit(1))
|
||||
|
||||
@@ -108,7 +108,7 @@ class DBRecommendationsHandler(DBBaseHandler):
|
||||
.where(Rom.missing_from_fs.is_(False))
|
||||
)
|
||||
|
||||
return [RomFeatureRow(*row) for row in session.execute(stmt).all()]
|
||||
return [RomFeatureRow._make(row) for row in session.execute(stmt).all()]
|
||||
|
||||
@begin_session
|
||||
def get_rom_igdb_ids(self, session: Session = INJECTED_SESSION) -> dict[int, int]:
|
||||
@@ -116,7 +116,11 @@ class DBRecommendationsHandler(DBBaseHandler):
|
||||
stmt = select(RomFacets.rom_id, RomFacets.igdb_id).where(
|
||||
RomFacets.igdb_id.is_not(None)
|
||||
)
|
||||
return {rom_id: igdb_id for rom_id, igdb_id in session.execute(stmt).all()}
|
||||
return {
|
||||
rom_id: igdb_id
|
||||
for rom_id, igdb_id in session.execute(stmt).all()
|
||||
if igdb_id is not None
|
||||
}
|
||||
|
||||
@begin_session
|
||||
def get_rom_identity_ids(
|
||||
|
||||
@@ -117,7 +117,7 @@ from utils.sql_dialect import (
|
||||
|
||||
from .base_handler import DBBaseHandler, affected_rows, sync_engine
|
||||
|
||||
type RomSelect = Select[tuple[Rom]]
|
||||
type RomSelect = Select[Rom]
|
||||
|
||||
EJS_SUPPORTED_PLATFORMS = [
|
||||
UPS._3DO,
|
||||
@@ -1136,12 +1136,12 @@ class DBRomsHandler(DBBaseHandler):
|
||||
def filter_by_platform_id(self, query: RomSelect, platform_id: int) -> RomSelect:
|
||||
return query.filter(Rom.platform_id == platform_id)
|
||||
|
||||
def _filter_by_platform_ids[S: Select[Any]](
|
||||
def _filter_by_platform_ids[S: Select[*tuple[Any, ...]]](
|
||||
self, query: S, platform_ids: Sequence[int]
|
||||
) -> S:
|
||||
return query.filter(Rom.platform_id.in_(platform_ids))
|
||||
|
||||
def _filter_by_collection_id[S: Select[Any]](
|
||||
def _filter_by_collection_id[S: Select[*tuple[Any, ...]]](
|
||||
self, query: S, collection_id: int
|
||||
) -> S:
|
||||
# `collections_roms` is keyed on (collection_id, rom_id), so membership
|
||||
@@ -1154,7 +1154,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
)
|
||||
)
|
||||
|
||||
def _filter_by_virtual_collection_id[S: Select[Any]](
|
||||
def _filter_by_virtual_collection_id[S: Select[*tuple[Any, ...]]](
|
||||
self, query: S, virtual_collection_id: str
|
||||
) -> S:
|
||||
from . import db_collection_handler
|
||||
@@ -1167,7 +1167,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
)
|
||||
)
|
||||
|
||||
def _filter_by_smart_collection_id[S: Select[Any]](
|
||||
def _filter_by_smart_collection_id[S: Select[*tuple[Any, ...]]](
|
||||
self,
|
||||
query: S,
|
||||
session: Session,
|
||||
@@ -1194,7 +1194,9 @@ class DBRomsHandler(DBBaseHandler):
|
||||
)
|
||||
)
|
||||
|
||||
def _join_rom_user[S: Select[Any]](self, query: S, user_id: int | None) -> S:
|
||||
def _join_rom_user[S: Select[*tuple[Any, ...]]](
|
||||
self, query: S, user_id: int | None
|
||||
) -> S:
|
||||
if not user_id:
|
||||
return query
|
||||
|
||||
@@ -1265,7 +1267,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
)
|
||||
return conditions
|
||||
|
||||
def _build_hash_selects(self, terms: Iterable[str]) -> list[Select[tuple[int]]]:
|
||||
def _build_hash_selects(self, terms: Iterable[str]) -> list[Select[int]]:
|
||||
"""Id-yielding selects for terms shaped like a hash digest.
|
||||
|
||||
A ROM's own hashes and its files' are queried separately so each side
|
||||
@@ -1294,7 +1296,9 @@ class DBRomsHandler(DBBaseHandler):
|
||||
select(RomFile.rom_id.label("id")).where(or_(*file_predicates)),
|
||||
]
|
||||
|
||||
def _filter_by_search_term[S: Select[Any]](self, query: S, search_term: str) -> S:
|
||||
def _filter_by_search_term[S: Select[*tuple[Any, ...]]](
|
||||
self, query: S, search_term: str
|
||||
) -> S:
|
||||
terms = _search_terms(search_term)
|
||||
if not terms:
|
||||
return query
|
||||
@@ -1313,7 +1317,9 @@ class DBRomsHandler(DBBaseHandler):
|
||||
).subquery()
|
||||
return query.filter(Rom.id.in_(select(matches.c.id)))
|
||||
|
||||
def _filter_by_matched[S: Select[Any]](self, query: S, value: bool) -> S:
|
||||
def _filter_by_matched[S: Select[*tuple[Any, ...]]](
|
||||
self, query: S, value: bool
|
||||
) -> S:
|
||||
"""Filter based on whether the rom is matched to a metadata provider.
|
||||
|
||||
Args:
|
||||
@@ -1321,7 +1327,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
"""
|
||||
return query.filter(ROM_IS_IDENTIFIED if value else not_(ROM_IS_IDENTIFIED))
|
||||
|
||||
def _filter_by_favorite[S: Select[Any]](
|
||||
def _filter_by_favorite[S: Select[*tuple[Any, ...]]](
|
||||
self, query: S, value: bool, user_id: int | None
|
||||
) -> S:
|
||||
"""Filter based on whether the rom is in the user's favorites collection."""
|
||||
@@ -1340,14 +1346,18 @@ class DBRomsHandler(DBBaseHandler):
|
||||
predicate = not_(predicate)
|
||||
return query.filter(predicate)
|
||||
|
||||
def _filter_by_duplicate[S: Select[Any]](self, query: S, value: bool) -> S:
|
||||
def _filter_by_duplicate[S: Select[*tuple[Any, ...]]](
|
||||
self, query: S, value: bool
|
||||
) -> S:
|
||||
"""Filter based on whether the rom has duplicates."""
|
||||
predicate = Rom.sibling_roms.any()
|
||||
if not value:
|
||||
predicate = not_(predicate)
|
||||
return query.filter(predicate)
|
||||
|
||||
def _filter_by_playable[S: Select[Any]](self, query: S, value: bool) -> S:
|
||||
def _filter_by_playable[S: Select[*tuple[Any, ...]]](
|
||||
self, query: S, value: bool
|
||||
) -> S:
|
||||
"""Filter based on whether the rom is playable on supported platforms."""
|
||||
predicate = or_(
|
||||
Platform.slug.in_(EJS_SUPPORTED_PLATFORMS),
|
||||
@@ -1357,7 +1367,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
predicate = not_(predicate)
|
||||
return query.join(Platform).filter(predicate)
|
||||
|
||||
def _filter_by_last_played[S: Select[Any]](
|
||||
def _filter_by_last_played[S: Select[*tuple[Any, ...]]](
|
||||
self, query: S, value: bool, user_id: int | None = None
|
||||
) -> S:
|
||||
"""Filter based on whether the rom has a last played value for the user."""
|
||||
@@ -1371,13 +1381,15 @@ class DBRomsHandler(DBBaseHandler):
|
||||
)
|
||||
return query.filter(has_last_played)
|
||||
|
||||
def _filter_by_has_ra[S: Select[Any]](self, query: S, value: bool) -> S:
|
||||
def _filter_by_has_ra[S: Select[*tuple[Any, ...]]](
|
||||
self, query: S, value: bool
|
||||
) -> S:
|
||||
predicate = Rom.ra_id.isnot(None)
|
||||
if not value:
|
||||
predicate = not_(predicate)
|
||||
return query.filter(predicate)
|
||||
|
||||
def _filter_by_has_saves[S: Select[Any]](
|
||||
def _filter_by_has_saves[S: Select[*tuple[Any, ...]]](
|
||||
self, query: S, value: bool, user_id: int | None = None
|
||||
) -> S:
|
||||
"""Filter based on whether the rom has saves visible to the current
|
||||
@@ -1389,7 +1401,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
predicate = not_(predicate)
|
||||
return query.filter(predicate)
|
||||
|
||||
def _filter_by_has_states[S: Select[Any]](
|
||||
def _filter_by_has_states[S: Select[*tuple[Any, ...]]](
|
||||
self, query: S, value: bool, user_id: int | None = None
|
||||
) -> S:
|
||||
"""Filter based on whether the rom has save states visible to the
|
||||
@@ -1401,7 +1413,9 @@ class DBRomsHandler(DBBaseHandler):
|
||||
predicate = not_(predicate)
|
||||
return query.filter(predicate)
|
||||
|
||||
def _filter_by_missing_from_fs[S: Select[Any]](self, query: S, value: bool) -> S:
|
||||
def _filter_by_missing_from_fs[S: Select[*tuple[Any, ...]]](
|
||||
self, query: S, value: bool
|
||||
) -> S:
|
||||
# The column is NOT NULL, so equality matches the same rows as the
|
||||
# `IS [NOT] FALSE` form. MariaDB only treats the equality as indexable
|
||||
# though, and this filter backs the Missing tab's whole-library scan.
|
||||
@@ -1413,7 +1427,9 @@ class DBRomsHandler(DBBaseHandler):
|
||||
and_(Rom.missing_from_fs == true(), Rom.is_physical.is_(False))
|
||||
)
|
||||
|
||||
def _filter_by_verified[S: Select[Any]](self, query: S, value: bool) -> S:
|
||||
def _filter_by_verified[S: Select[*tuple[Any, ...]]](
|
||||
self, query: S, value: bool
|
||||
) -> S:
|
||||
keys_to_check = [
|
||||
"tosec_match",
|
||||
"mame_arcade_match",
|
||||
@@ -1468,7 +1484,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
|
||||
return and_(condition, _rom_user_not_hidden())
|
||||
|
||||
def _apply_filter_spec[S: Select[Any]](
|
||||
def _apply_filter_spec[S: Select[*tuple[Any, ...]]](
|
||||
self,
|
||||
query: S,
|
||||
spec: RomFilterSpec,
|
||||
@@ -1499,7 +1515,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
|
||||
return query.filter(~condition) if match_none else query.filter(condition)
|
||||
|
||||
def _filter_by_metadata_providers[S: Select[Any]](
|
||||
def _filter_by_metadata_providers[S: Select[*tuple[Any, ...]]](
|
||||
self,
|
||||
query: S,
|
||||
*,
|
||||
@@ -1532,7 +1548,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
return query.filter(or_(*predicates))
|
||||
|
||||
@begin_session
|
||||
def filter_roms[S: Select[Any]](
|
||||
def filter_roms[S: Select[*tuple[Any, ...]]](
|
||||
self,
|
||||
query: S,
|
||||
filters: RomFilterParams | None = None,
|
||||
@@ -3285,7 +3301,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
).all()
|
||||
return rows, total
|
||||
|
||||
def _music_facet_joins[S: Select[Any]](self, statement: S) -> S:
|
||||
def _music_facet_joins[S: Select[*tuple[Any, ...]]](self, statement: S) -> S:
|
||||
return (
|
||||
statement.select_from(TrackMeta)
|
||||
.join(RomFile, TrackMeta.rom_file_id == RomFile.id)
|
||||
@@ -3569,7 +3585,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
public_only: bool = False,
|
||||
search: str | None = "",
|
||||
tags: list[str] | None = None,
|
||||
) -> Select[tuple[RomNote]]:
|
||||
) -> Select[RomNote]:
|
||||
query = select(RomNote).filter(RomNote.rom_id == rom_id)
|
||||
|
||||
if public_only:
|
||||
@@ -3870,7 +3886,7 @@ class DBRomsHandler(DBBaseHandler):
|
||||
def _collect_filter_values(
|
||||
self,
|
||||
session: Session,
|
||||
statement: RomSelect,
|
||||
statement: Select[*tuple[Any, ...]],
|
||||
) -> RomFiltersDict:
|
||||
genres = set()
|
||||
franchises = set()
|
||||
|
||||
@@ -28,7 +28,7 @@ class _SlotMoved(Exception):
|
||||
class UnhashedVersions(Exception):
|
||||
"""Versions a prune would drop without a hash to record them by."""
|
||||
|
||||
def __init__(self, versions: Sequence[Row[Any]]):
|
||||
def __init__(self, versions: Sequence[Row[*tuple[Any, ...]]]):
|
||||
super().__init__(f"{len(versions)} versions to prune were never hashed")
|
||||
self.versions = versions
|
||||
|
||||
@@ -130,7 +130,7 @@ class DBSavesHandler(DBBaseHandler):
|
||||
file_name_prefix: str | None = None,
|
||||
order_by: Literal["updated_at", "created_at"] | None = None,
|
||||
order_dir: Literal["asc", "desc"] = "desc",
|
||||
) -> Select[tuple[Save]]:
|
||||
) -> Select[Save]:
|
||||
query = select(Save).filter_by(user_id=user_id)
|
||||
|
||||
# An empty collection is an explicit empty scope, not an absent filter.
|
||||
@@ -279,10 +279,12 @@ class DBSavesHandler(DBBaseHandler):
|
||||
self,
|
||||
id: int,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> Row[Any] | None:
|
||||
) -> Row[*tuple[Any, ...]] | None:
|
||||
return session.execute(_version_query(id)).one_or_none()
|
||||
|
||||
def _lock_for_removal(self, id: int, session: Session) -> Row[Any] | None:
|
||||
def _lock_for_removal(
|
||||
self, id: int, session: Session
|
||||
) -> Row[*tuple[Any, ...]] | None:
|
||||
"""Lock the save's slot record, then the save, returning its current version."""
|
||||
# Before this session holds a connection, since ensuring takes its own.
|
||||
before = self._slot_version(id)
|
||||
@@ -367,7 +369,7 @@ class DBSavesHandler(DBBaseHandler):
|
||||
keep: int,
|
||||
fallback_hashes: Mapping[int, str | None] | None = None,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> Sequence[Row[Any]]:
|
||||
) -> Sequence[Row[*tuple[Any, ...]]]:
|
||||
"""Delete every version of a slot past the ``keep`` newest.
|
||||
|
||||
The slot's record is locked while its versions are listed and deleted,
|
||||
@@ -438,7 +440,7 @@ class DBSavesHandler(DBBaseHandler):
|
||||
@begin_session
|
||||
def _any(
|
||||
self,
|
||||
query: Select[Any],
|
||||
query: Select[*tuple[Any, ...]],
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> bool:
|
||||
return session.execute(query.limit(1)).first() is not None
|
||||
@@ -522,11 +524,11 @@ class DBSavesHandler(DBBaseHandler):
|
||||
).all()
|
||||
|
||||
|
||||
def _version_query(id: int) -> Select[Any]:
|
||||
def _version_query(id: int) -> Select[*tuple[Any, ...]]:
|
||||
return select(*_VERSION_COLUMNS).where(Save.id == id)
|
||||
|
||||
|
||||
def _loses_version(version: Row[Any], data: dict[str, Any]) -> bool:
|
||||
def _loses_version(version: Row[*tuple[Any, ...]], data: dict[str, Any]) -> bool:
|
||||
"""Whether writing `data` takes this version out of its slot."""
|
||||
return bool(
|
||||
data.get("slot", version.slot) != version.slot
|
||||
@@ -542,7 +544,7 @@ def _lock_slot(user_id: int, rom_id: int, slot: str, session: Session) -> None:
|
||||
|
||||
|
||||
def _record_loss(
|
||||
version: Row[Any], session: Session, content_hash: str | None = None
|
||||
version: Row[*tuple[Any, ...]], session: Session, content_hash: str | None = None
|
||||
) -> None:
|
||||
"""Remember a version leaving its slot, in the transaction that removes it."""
|
||||
content_hash = version.content_hash or content_hash
|
||||
|
||||
@@ -14,7 +14,7 @@ from .base_handler import DBBaseHandler
|
||||
|
||||
|
||||
class DBScreenshotsHandler(DBBaseHandler):
|
||||
def filter[QueryT: (Select[tuple[Screenshot]], Update, Delete)](
|
||||
def filter[QueryT: (Select[Screenshot], Update, Delete)](
|
||||
self,
|
||||
query: QueryT,
|
||||
*,
|
||||
|
||||
@@ -49,7 +49,7 @@ class DBStatesHandler(DBBaseHandler):
|
||||
user_id: int,
|
||||
rom_ids: Collection[int] | None = None,
|
||||
platform_id: int | None = None,
|
||||
) -> Select[tuple[State]]:
|
||||
) -> Select[State]:
|
||||
query = select(State).filter_by(user_id=user_id)
|
||||
|
||||
# An empty collection is an explicit empty scope, not an absent filter.
|
||||
|
||||
@@ -21,7 +21,7 @@ from utils.database import is_non_blank
|
||||
from .base_handler import DBBaseHandler
|
||||
|
||||
|
||||
def _exclude_hidden[S: Select[Any]](
|
||||
def _exclude_hidden[S: Select[*tuple[Any, ...]]](
|
||||
query: S,
|
||||
hidden_platform_ids: Collection[int] | None,
|
||||
hidden_rom_ids: Collection[int] | None,
|
||||
|
||||
@@ -12,7 +12,7 @@ from .base_handler import DBBaseHandler
|
||||
|
||||
|
||||
class DBUsersHandler(DBBaseHandler):
|
||||
def filter[QueryT: (Select[tuple[User]], Update, Delete)](
|
||||
def filter[QueryT: (Select[User], Update, Delete)](
|
||||
self,
|
||||
query: QueryT,
|
||||
*,
|
||||
@@ -127,7 +127,7 @@ class DBUsersHandler(DBBaseHandler):
|
||||
self,
|
||||
id: int,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> Result[Any]:
|
||||
) -> Result[*tuple[Any, ...]]:
|
||||
return session.execute(
|
||||
delete(User)
|
||||
.where(User.id == id)
|
||||
|
||||
@@ -7,7 +7,8 @@ from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.rom import Rom
|
||||
|
||||
_STAGE_PREFIX = ".romm_tmp_"
|
||||
# Scans and the watcher skip dot-prefixed entries, so staged files stay unseen.
|
||||
STAGE_PREFIX = ".romm_tmp_"
|
||||
|
||||
# Parallel uploads each promote the ROM, maybe on different gunicorn workers.
|
||||
# Keyed by the target folder, since lone files sharing a stem promote into one.
|
||||
@@ -39,7 +40,7 @@ async def _promote(rom: Rom) -> Rom:
|
||||
origin = f"{fs_path}/{fs_name}"
|
||||
dest_dir = f"{fs_path}/{folder}"
|
||||
final = f"{dest_dir}/{fs_name}"
|
||||
staged = f"{fs_path}/{_STAGE_PREFIX}{fs_name}"
|
||||
staged = f"{fs_path}/{STAGE_PREFIX}{fs_name}"
|
||||
extensionless = folder == fs_name
|
||||
|
||||
# Extensionless dest_dir is the file's own path; only a directory collides.
|
||||
|
||||
@@ -5,7 +5,7 @@ import enum
|
||||
import hashlib
|
||||
import re
|
||||
import sys
|
||||
from collections.abc import Mapping, Sequence
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from functools import cached_property
|
||||
@@ -302,8 +302,8 @@ class SiblingRom(BaseModel):
|
||||
|
||||
A database view, not a table, over `RomIdentityKey` self-joined on its
|
||||
(provider, platform, provider id). A pair matched by several providers
|
||||
appears once per provider, which `get_siblings_for_roms` and the relationship
|
||||
loaders both collapse.
|
||||
appears once per provider, which `get_siblings_for_roms` and
|
||||
`UniqueSiblingList` both collapse.
|
||||
"""
|
||||
|
||||
__tablename__ = "sibling_roms"
|
||||
@@ -312,6 +312,23 @@ class SiblingRom(BaseModel):
|
||||
sibling_rom_id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
|
||||
|
||||
class UniqueSiblingList(list["Rom"]):
|
||||
"""`Rom.sibling_roms`, holding each sibling once though the view repeats it."""
|
||||
|
||||
def __init__(self, roms: Iterable[Rom] = ()) -> None:
|
||||
super().__init__(roms)
|
||||
self._held = {id(rom) for rom in self}
|
||||
|
||||
# selectinload hands the collection every view row, duplicates included.
|
||||
def append(self, rom: Rom, /) -> None:
|
||||
# A list method other than this one changed the contents.
|
||||
if len(self._held) != len(self):
|
||||
self._held = {id(held) for held in self}
|
||||
if id(rom) not in self._held:
|
||||
self._held.add(id(rom))
|
||||
super().append(rom)
|
||||
|
||||
|
||||
class RomArchiveMember(TypedDict):
|
||||
name: str
|
||||
size: int
|
||||
@@ -1019,6 +1036,7 @@ class Rom(BaseModel):
|
||||
secondary="sibling_roms",
|
||||
primaryjoin="Rom.id == SiblingRom.rom_id",
|
||||
secondaryjoin="Rom.id == SiblingRom.sibling_rom_id",
|
||||
collection_class=UniqueSiblingList,
|
||||
lazy="raise",
|
||||
)
|
||||
files: Mapped[list[RomFile]] = relationship(lazy="raise", back_populates="rom")
|
||||
|
||||
315
backend/tasks/manual/convert_library.py
Normal file
315
backend/tasks/manual/convert_library.py
Normal file
@@ -0,0 +1,315 @@
|
||||
"""Convert each matched ROM to its platform's library format, in place."""
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
from dataclasses import asdict, dataclass
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from adapters.services.rom_converto import (
|
||||
Operation,
|
||||
RomConvertoError,
|
||||
file_format,
|
||||
resolve_operation,
|
||||
rom_converto_service,
|
||||
)
|
||||
from config.config_manager import config_manager as cm
|
||||
from handler.database import db_platform_handler, db_rom_handler
|
||||
from handler.filesystem import fs_rom_handler
|
||||
from handler.rom_conversion import STAGE_PREFIX
|
||||
from handler.rom_files import refresh_rom_files
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.rom import Rom, RomFile, RomFileCategory
|
||||
from tasks.registry import CONVERT_LIBRARY_SPEC
|
||||
from tasks.scheduled.convert_images_to_webp import ConversionStats
|
||||
from tasks.tasks import Task
|
||||
from utils.context import initialize_context
|
||||
from utils.filesystem import LINK_FALLBACK_ERRNOS
|
||||
|
||||
_CUE_FILE_LINE: Final = re.compile(r'^\s*FILE\s+(?:"([^"]+)"|(\S+))', re.IGNORECASE)
|
||||
_CUE_EXT: Final = ".cue"
|
||||
_PLAYLIST_EXT: Final = ".m3u"
|
||||
_CONVERT_STAGE_PREFIX: Final = f"{STAGE_PREFIX}convert_"
|
||||
|
||||
|
||||
@dataclass
|
||||
class ConvertLibraryStats:
|
||||
converted: int = 0
|
||||
already_converted: int = 0
|
||||
# Converted files no longer hash-match a DAT, so only matched roms convert.
|
||||
unmatched: int = 0
|
||||
unsupported: int = 0
|
||||
failed: int = 0
|
||||
bytes_saved: int = 0
|
||||
|
||||
|
||||
def _cue_tracks(cue: Path) -> list[Path]:
|
||||
"""The track files a cue sheet references, all beside it."""
|
||||
tracks: list[Path] = []
|
||||
for line in cue.read_text(encoding="utf-8-sig", errors="replace").splitlines():
|
||||
match = _CUE_FILE_LINE.match(line)
|
||||
if match is None:
|
||||
continue
|
||||
name = match.group(1) or match.group(2)
|
||||
# A track outside the cue's folder isn't this rom's to delete.
|
||||
if Path(name).name != name:
|
||||
raise ValueError(f"{cue.name} references a track outside its folder")
|
||||
tracks.append(cue.with_name(name))
|
||||
return tracks
|
||||
|
||||
|
||||
def _shared_tracks(cue: Path, tracks: list[Path]) -> set[Path]:
|
||||
"""The tracks of `cue` that another cue beside it also references."""
|
||||
others: set[Path] = set()
|
||||
for other in cue.parent.iterdir():
|
||||
if other == cue or other.suffix.lower() != _CUE_EXT or not other.is_file():
|
||||
continue
|
||||
with contextlib.suppress(OSError, ValueError):
|
||||
others.update(_cue_tracks(other))
|
||||
return set(tracks) & others
|
||||
|
||||
|
||||
def _renamed_entry(line: str, renames: dict[str, str]) -> str:
|
||||
entry = line.strip()
|
||||
return renames.get(os.path.normpath(entry), line) if entry else line
|
||||
|
||||
|
||||
def _rewritten_playlists(folder: Path, renames: dict[str, str]) -> dict[Path, str]:
|
||||
"""The playlists in `folder` that name a renamed file, with their new text."""
|
||||
rewrites: dict[Path, str] = {}
|
||||
for playlist in folder.iterdir():
|
||||
if playlist.suffix.lower() != _PLAYLIST_EXT or not playlist.is_file():
|
||||
continue
|
||||
lines = playlist.read_text(encoding="utf-8-sig", errors="replace").splitlines()
|
||||
rewritten = [_renamed_entry(line, renames) for line in lines]
|
||||
if rewritten != lines:
|
||||
rewrites[playlist] = "\n".join(rewritten) + "\n"
|
||||
return rewrites
|
||||
|
||||
|
||||
async def _rewrite_playlists(folder: Path, renames: dict[str, str]) -> None:
|
||||
"""Point each playlist entry for a converted file at its new name."""
|
||||
rewrites = await asyncio.to_thread(_rewritten_playlists, folder, renames)
|
||||
for playlist, text in rewrites.items():
|
||||
async with fs_rom_handler._atomic_write(playlist) as staged:
|
||||
await asyncio.to_thread(staged.write_text, text)
|
||||
|
||||
|
||||
def _sources(src: Path, final: Path, input_ext: str) -> list[Path]:
|
||||
"""The files a conversion of `src` replaces, refusing one that would overwrite."""
|
||||
if final.exists():
|
||||
raise FileExistsError(f"{final.name} already exists")
|
||||
if input_ext != _CUE_EXT:
|
||||
return [src]
|
||||
tracks = _cue_tracks(src)
|
||||
if shared := _shared_tracks(src, tracks):
|
||||
raise ValueError(
|
||||
f"{src.name} shares {sorted(p.name for p in shared)} with another cue"
|
||||
)
|
||||
return [src, *tracks]
|
||||
|
||||
|
||||
def _drop_stale_stages(folder: Path) -> None:
|
||||
"""Remove stage dirs a killed conversion left, none recent enough to be live."""
|
||||
cutoff = time.time() - CONVERT_LIBRARY_SPEC.timeout
|
||||
for stage in folder.glob(f"{_CONVERT_STAGE_PREFIX}*"):
|
||||
with contextlib.suppress(OSError):
|
||||
if stage.is_dir() and stage.stat().st_mtime < cutoff:
|
||||
shutil.rmtree(stage, ignore_errors=True)
|
||||
|
||||
|
||||
def _publish(stage_dir: Path, final: Path) -> None:
|
||||
"""Move the staged output to `final`, never replacing a file that appeared there."""
|
||||
staged = stage_dir / final.name
|
||||
try:
|
||||
os.link(staged, final)
|
||||
except OSError as exc:
|
||||
if exc.errno not in LINK_FALLBACK_ERRNOS:
|
||||
raise
|
||||
if final.exists():
|
||||
raise FileExistsError(f"{final.name} already exists") from None
|
||||
os.replace(staged, final)
|
||||
|
||||
|
||||
def _replace_sources(sources: list[Path], final: Path) -> int:
|
||||
"""Delete the converted files and return the bytes the conversion saved."""
|
||||
saved = sum(p.stat().st_size for p in sources if p.exists()) - final.stat().st_size
|
||||
for path in sources:
|
||||
try:
|
||||
path.unlink(missing_ok=True)
|
||||
except OSError as exc:
|
||||
log.warning(
|
||||
f"Converted to {hl(final.name)} but could not delete {path}: {exc}"
|
||||
)
|
||||
return saved
|
||||
|
||||
|
||||
async def _convert_beside(
|
||||
src: Path, final: Path, operation: Operation, stage_parent: Path
|
||||
) -> None:
|
||||
"""Convert `src` to `final` beside it, staging in `stage_parent` and leaving `src` in place."""
|
||||
stage_dir = Path(
|
||||
await asyncio.to_thread(
|
||||
tempfile.mkdtemp, prefix=_CONVERT_STAGE_PREFIX, dir=stage_parent
|
||||
)
|
||||
)
|
||||
try:
|
||||
await rom_converto_service.convert(
|
||||
operation, src=src, out=stage_dir / final.name
|
||||
)
|
||||
await asyncio.to_thread(_publish, stage_dir, final)
|
||||
finally:
|
||||
await asyncio.to_thread(shutil.rmtree, stage_dir, True)
|
||||
|
||||
|
||||
def _names_taken(rom: Rom, names: list[str]) -> list[str]:
|
||||
"""The `names` another rom row beside `rom` already holds."""
|
||||
if not names:
|
||||
return []
|
||||
owned = db_rom_handler.get_roms_by_fs_name(rom.platform_id, names)
|
||||
return sorted(n for n in names if f"{rom.fs_path}/{n}" in owned)
|
||||
|
||||
|
||||
def _game_files(rom: Rom) -> list[RomFile]:
|
||||
return [
|
||||
f
|
||||
for f in rom.files
|
||||
if f.is_top_level
|
||||
and not f.missing_from_fs
|
||||
and f.category in (None, RomFileCategory.GAME)
|
||||
]
|
||||
|
||||
|
||||
class ConvertLibraryTask(Task):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(CONVERT_LIBRARY_SPEC)
|
||||
|
||||
async def _convert_rom(
|
||||
self, rom: Rom, target: str, stats: ConvertLibraryStats
|
||||
) -> None:
|
||||
single_file = rom.has_simple_single_file
|
||||
planned: list[tuple[RomFile, Operation, str]] = []
|
||||
for rom_file in _game_files(rom):
|
||||
if file_format(rom_file.file_name) == target:
|
||||
stats.already_converted += 1
|
||||
continue
|
||||
resolved = resolve_operation(
|
||||
rom.platform_slug, target, rom_file.file_name, lossless=True
|
||||
)
|
||||
if resolved is None:
|
||||
stats.unsupported += 1
|
||||
continue
|
||||
name = resolved[0].output_name(Path(rom.fs_name), resolved[1])
|
||||
if single_file and _names_taken(rom, [name]):
|
||||
log.warning(
|
||||
f"Not converting {hl(rom.fs_name)}: a rom named {name} exists"
|
||||
)
|
||||
stats.failed += 1
|
||||
continue
|
||||
planned.append((rom_file, *resolved))
|
||||
if not planned:
|
||||
return
|
||||
if not rom.is_identified:
|
||||
stats.unmatched += 1
|
||||
return
|
||||
|
||||
# A rom folder lists dot-prefixed subfolders as its files, so stage beside it.
|
||||
stage_parent = fs_rom_handler.validate_path(rom.fs_path)
|
||||
await asyncio.to_thread(_drop_stale_stages, stage_parent)
|
||||
# Originals go only once the rom and its playlists point at the new files.
|
||||
published: list[tuple[Path, Path, list[Path]]] = []
|
||||
for rom_file, operation, input_ext in planned:
|
||||
src = fs_rom_handler.validate_path(rom_file.full_path)
|
||||
final = src.with_name(operation.output_name(src, input_ext))
|
||||
try:
|
||||
sources = await asyncio.to_thread(_sources, src, final, input_ext)
|
||||
if single_file and (
|
||||
taken := _names_taken(rom, [t.name for t in sources[1:]])
|
||||
):
|
||||
raise ValueError(f"{taken} belong to other roms")
|
||||
await _convert_beside(src, final, operation, stage_parent)
|
||||
except (RomConvertoError, OSError, ValueError) as exc:
|
||||
log.warning(f"Could not convert {hl(rom_file.file_name)}: {exc}")
|
||||
stats.failed += 1
|
||||
continue
|
||||
published.append((src, final, sources))
|
||||
|
||||
if not published:
|
||||
return
|
||||
renames = {src.name: final.name for src, final, _ in published}
|
||||
try:
|
||||
if single_file:
|
||||
db_rom_handler.update_rom(rom.id, {"fs_name": renames[rom.fs_name]})
|
||||
else:
|
||||
await _rewrite_playlists(
|
||||
fs_rom_handler.validate_path(rom.full_path), renames
|
||||
)
|
||||
except (OSError, SQLAlchemyError) as exc:
|
||||
log.warning(f"Kept the originals of {hl(rom.fs_name)}: {exc}")
|
||||
stats.failed += len(published)
|
||||
if single_file:
|
||||
for _, final, _ in published:
|
||||
final.unlink(missing_ok=True)
|
||||
return
|
||||
|
||||
for src, final, sources in published:
|
||||
stats.bytes_saved += await asyncio.to_thread(
|
||||
_replace_sources, sources, final
|
||||
)
|
||||
stats.converted += 1
|
||||
log.info(f"Converted {hl(src.name)} to {hl(final.name)}")
|
||||
refreshed = db_rom_handler.get_rom(rom.id)
|
||||
if refreshed is not None:
|
||||
await refresh_rom_files(refreshed)
|
||||
|
||||
@initialize_context()
|
||||
async def run(self, platform_id: int | None = None) -> dict[str, int]:
|
||||
"""Convert every matched ROM on platforms that have a library format."""
|
||||
log.info(f"Starting {self.spec.title} task...")
|
||||
stats = ConvertLibraryStats()
|
||||
if not await rom_converto_service.is_enabled():
|
||||
log.warning(
|
||||
f"{self.spec.title} needs rom-converto; set ROM_CONVERTO_ENABLED"
|
||||
)
|
||||
return asdict(stats)
|
||||
|
||||
formats = cm.get_config().CONVERTO.platform_formats
|
||||
rom_ids: list[tuple[int, str]] = []
|
||||
for platform in db_platform_handler.get_platforms():
|
||||
if platform_id is not None and platform.id != platform_id:
|
||||
continue
|
||||
target = formats.get(platform.slug)
|
||||
if target:
|
||||
rom_ids.extend(
|
||||
(rom_id, target)
|
||||
for rom_id in db_rom_handler.get_rom_ids(platform_ids=[platform.id])
|
||||
)
|
||||
|
||||
progress = ConversionStats()
|
||||
progress.update(total=len(rom_ids))
|
||||
for index, (rom_id, target) in enumerate(rom_ids):
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
if rom is not None:
|
||||
try:
|
||||
await self._convert_rom(rom, target, stats)
|
||||
except Exception as exc:
|
||||
log.exception(f"Could not convert {hl(rom.fs_name)}: {exc}")
|
||||
stats.failed += 1
|
||||
progress.update(processed=index + 1, errors=stats.failed)
|
||||
|
||||
log.info(
|
||||
f"{self.spec.title} completed: {stats.converted} converted, "
|
||||
f"{stats.failed} failed, {stats.bytes_saved} bytes saved"
|
||||
)
|
||||
return asdict(stats)
|
||||
|
||||
|
||||
convert_library_task = ConvertLibraryTask()
|
||||
@@ -113,6 +113,15 @@ CLEANUP_ZIP_CACHE_SPEC: Final = TaskSpec(
|
||||
cron_string=SCHEDULED_CLEANUP_ZIP_CACHE_CRON,
|
||||
)
|
||||
|
||||
CLEANUP_CONVERSION_CACHE_SPEC: Final = TaskSpec(
|
||||
implementation="tasks.scheduled.cleanup_conversion_cache.cleanup_conversion_cache_task",
|
||||
title="Scheduled conversion cache cleanup",
|
||||
description="Removes stale converted download files based on TTL",
|
||||
task_type=TaskType.CLEANUP,
|
||||
enabled=True,
|
||||
cron_string="0 4 * * *",
|
||||
)
|
||||
|
||||
CLEANUP_ORPHANED_RESOURCES_SPEC: Final = TaskSpec(
|
||||
implementation="tasks.scheduled.cleanup_orphaned_resources.cleanup_orphaned_resources_task",
|
||||
title="Cleanup orphaned resources",
|
||||
@@ -232,6 +241,20 @@ RECOMPUTE_SAVE_CONTENT_HASHES_SPEC: Final = TaskSpec(
|
||||
manual_run=True,
|
||||
)
|
||||
|
||||
CONVERT_LIBRARY_SPEC: Final = TaskSpec(
|
||||
implementation="tasks.manual.convert_library.convert_library_task",
|
||||
title="Convert library",
|
||||
description=(
|
||||
"Convert each matched ROM to its platform's library format, "
|
||||
"replacing the original files"
|
||||
),
|
||||
task_type=TaskType.CONVERSION,
|
||||
enabled=True,
|
||||
manual_run=True,
|
||||
# One conversion after another, each up to ROM_CONVERTO_TIMEOUT.
|
||||
timeout=SCAN_TIMEOUT,
|
||||
)
|
||||
|
||||
# The keys are the names the API and the cron schedule address a task by, and
|
||||
# they end up in the job payload, so they outlive any given release. Every task
|
||||
# that runs on a schedule belongs here; which of them the API surfaces is the
|
||||
@@ -243,6 +266,7 @@ SCHEDULED_TASKS: Final[dict[str, TaskSpec]] = {
|
||||
"build_recommendations": BUILD_RECOMMENDATIONS_SPEC,
|
||||
"convert_images_to_webp": CONVERT_IMAGES_TO_WEBP_SPEC,
|
||||
"cleanup_zip_cache": CLEANUP_ZIP_CACHE_SPEC,
|
||||
"cleanup_conversion_cache": CLEANUP_CONVERSION_CACHE_SPEC,
|
||||
"cleanup_orphaned_resources": CLEANUP_ORPHANED_RESOURCES_SPEC,
|
||||
"cleanup_netplay": CLEANUP_NETPLAY_SPEC,
|
||||
"cleanup_upload_tmp": CLEANUP_UPLOAD_TMP_SPEC,
|
||||
@@ -258,6 +282,7 @@ MANUAL_TASKS: Final[dict[str, TaskSpec]] = {
|
||||
"cleanup_missing_firmware": CLEANUP_MISSING_FIRMWARE_SPEC,
|
||||
"sync_folder_scan": SYNC_FOLDER_SCAN_SPEC,
|
||||
"recompute_save_content_hashes": RECOMPUTE_SAVE_CONTENT_HASHES_SPEC,
|
||||
"convert_library": CONVERT_LIBRARY_SPEC,
|
||||
}
|
||||
|
||||
|
||||
|
||||
20
backend/tasks/scheduled/cleanup_conversion_cache.py
Normal file
20
backend/tasks/scheduled/cleanup_conversion_cache.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from logger.logger import log
|
||||
from tasks.registry import CLEANUP_CONVERSION_CACHE_SPEC
|
||||
from tasks.tasks import PeriodicTask
|
||||
from utils.conversion_cache import cleanup_stale_conversions
|
||||
|
||||
|
||||
class CleanupConversionCacheTask(PeriodicTask):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(CLEANUP_CONVERSION_CACHE_SPEC)
|
||||
|
||||
async def run(self) -> None:
|
||||
if not self.spec.enabled:
|
||||
return
|
||||
|
||||
deleted = cleanup_stale_conversions()
|
||||
if deleted:
|
||||
log.info(f"Cleaned up {deleted} stale converted download caches")
|
||||
|
||||
|
||||
cleanup_conversion_cache_task = CleanupConversionCacheTask()
|
||||
392
backend/tests/adapters/services/test_rom_converto.py
Normal file
392
backend/tests/adapters/services/test_rom_converto.py
Normal file
@@ -0,0 +1,392 @@
|
||||
import asyncio
|
||||
import stat
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from adapters.services import rom_converto
|
||||
from adapters.services.rom_converto import (
|
||||
DOWNLOAD_FORMATS,
|
||||
LIBRARY_TARGETS_BY_PLATFORM,
|
||||
Operation,
|
||||
RomConvertoBinaryNotFoundError,
|
||||
RomConvertoOperationError,
|
||||
RomConvertoService,
|
||||
RomConvertoTimeoutError,
|
||||
canonical_format,
|
||||
file_format,
|
||||
resolve_operation,
|
||||
)
|
||||
from utils.filesystem import SERVED_FILE_MODE
|
||||
|
||||
|
||||
class FakeProc:
|
||||
def __init__(
|
||||
self,
|
||||
returncode: int = 0,
|
||||
stdout: bytes = b"",
|
||||
stderr: bytes = b"",
|
||||
delay: float = 0.0,
|
||||
):
|
||||
self._stdout = stdout
|
||||
self._stderr = stderr
|
||||
self._delay = delay
|
||||
self.killed = False
|
||||
self.returncode = returncode
|
||||
|
||||
async def communicate(self) -> tuple[bytes, bytes]:
|
||||
if self._delay and not self.killed:
|
||||
await asyncio.sleep(self._delay)
|
||||
return self._stdout, self._stderr
|
||||
|
||||
def kill(self) -> None:
|
||||
self.killed = True
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def service() -> RomConvertoService:
|
||||
return RomConvertoService()
|
||||
|
||||
|
||||
class TestRun:
|
||||
async def test_binary_missing_raises(self) -> None:
|
||||
with (
|
||||
patch("shutil.which", return_value=None),
|
||||
pytest.raises(RomConvertoBinaryNotFoundError),
|
||||
):
|
||||
await rom_converto._run(["info", "--json", "x"], timeout_seconds=1)
|
||||
|
||||
async def test_timeout_kills_process(self) -> None:
|
||||
proc = FakeProc(delay=5.0)
|
||||
with (
|
||||
patch("shutil.which", return_value="/usr/bin/rom-converto"),
|
||||
patch("asyncio.create_subprocess_exec", return_value=proc),
|
||||
pytest.raises(RomConvertoTimeoutError),
|
||||
):
|
||||
await rom_converto._run(["info", "--json", "x"], timeout_seconds=0.01)
|
||||
assert proc.killed is True
|
||||
|
||||
async def test_cancellation_kills_process(self) -> None:
|
||||
proc = FakeProc(delay=5.0)
|
||||
with (
|
||||
patch("shutil.which", return_value="/usr/bin/rom-converto"),
|
||||
patch("asyncio.create_subprocess_exec", return_value=proc),
|
||||
):
|
||||
run = asyncio.create_task(
|
||||
rom_converto._run(["info", "--json", "x"], timeout_seconds=10)
|
||||
)
|
||||
await asyncio.sleep(0.01)
|
||||
run.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await run
|
||||
assert proc.killed is True
|
||||
|
||||
|
||||
class TestIsEnabled:
|
||||
async def test_disabled_when_config_disabled(self, service: RomConvertoService):
|
||||
with (
|
||||
patch.object(rom_converto, "ROM_CONVERTO_ENABLED", False),
|
||||
patch("shutil.which", return_value="/usr/bin/rom-converto"),
|
||||
):
|
||||
assert await service.is_enabled() is False
|
||||
|
||||
async def test_probe_fail_cached_false(self, service: RomConvertoService):
|
||||
proc = FakeProc(returncode=1)
|
||||
spawn_count = 0
|
||||
|
||||
async def spawn(*args, **kwargs):
|
||||
nonlocal spawn_count
|
||||
spawn_count += 1
|
||||
return proc
|
||||
|
||||
with (
|
||||
patch.object(rom_converto, "ROM_CONVERTO_ENABLED", True),
|
||||
patch("shutil.which", return_value="/usr/bin/rom-converto"),
|
||||
patch("asyncio.create_subprocess_exec", spawn),
|
||||
):
|
||||
assert await service.is_enabled() is False
|
||||
assert await service.is_enabled() is False
|
||||
assert spawn_count == 1
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error",
|
||||
[OSError(8, "Exec format error"), RomConvertoTimeoutError("timed out")],
|
||||
)
|
||||
async def test_probe_that_cannot_run_is_cached_false(
|
||||
self, service: RomConvertoService, error: Exception
|
||||
):
|
||||
spawn_count = 0
|
||||
|
||||
async def spawn(*args, **kwargs):
|
||||
nonlocal spawn_count
|
||||
spawn_count += 1
|
||||
raise error
|
||||
|
||||
with (
|
||||
patch.object(rom_converto, "ROM_CONVERTO_ENABLED", True),
|
||||
patch("shutil.which", return_value="/usr/bin/rom-converto"),
|
||||
patch("asyncio.create_subprocess_exec", spawn),
|
||||
):
|
||||
assert await service.is_enabled() is False
|
||||
assert await service.is_enabled() is False
|
||||
assert spawn_count == 1
|
||||
|
||||
async def test_probe_ok_logs_version(self, service: RomConvertoService, mocker):
|
||||
log_info = mocker.patch("adapters.services.rom_converto.log.info")
|
||||
proc = FakeProc(stdout=b'{"version": "0.21.0"}')
|
||||
with (
|
||||
patch.object(rom_converto, "ROM_CONVERTO_ENABLED", True),
|
||||
patch("shutil.which", return_value="/usr/bin/rom-converto"),
|
||||
patch("asyncio.create_subprocess_exec", return_value=proc),
|
||||
):
|
||||
assert await service.is_enabled() is True
|
||||
assert log_info.call_count == 1
|
||||
|
||||
async def test_missing_binary_not_cached(self, service: RomConvertoService):
|
||||
with (
|
||||
patch.object(rom_converto, "ROM_CONVERTO_ENABLED", True),
|
||||
patch("shutil.which", return_value=None),
|
||||
):
|
||||
assert await service.is_enabled() is False
|
||||
|
||||
proc = FakeProc(stdout=b'{"version": "0.21.0"}')
|
||||
with (
|
||||
patch.object(rom_converto, "ROM_CONVERTO_ENABLED", True),
|
||||
patch("shutil.which", return_value="/usr/bin/rom-converto"),
|
||||
patch("asyncio.create_subprocess_exec", return_value=proc),
|
||||
):
|
||||
assert await service.is_enabled() is True
|
||||
|
||||
|
||||
def _capture_spawn(proc: FakeProc, calls: list[tuple[str, ...]]):
|
||||
async def spawn(*args, **kwargs):
|
||||
calls.append(args)
|
||||
return proc
|
||||
|
||||
return spawn
|
||||
|
||||
|
||||
class TestUpdateCheck:
|
||||
async def test_every_run_disables_the_update_check(self):
|
||||
calls: list[tuple[str, ...]] = []
|
||||
with (
|
||||
patch("shutil.which", return_value="/usr/bin/rom-converto"),
|
||||
patch("asyncio.create_subprocess_exec", _capture_spawn(FakeProc(), calls)),
|
||||
):
|
||||
await rom_converto._run(["capabilities"], timeout_seconds=1)
|
||||
|
||||
assert calls[0][:3] == (
|
||||
"/usr/bin/rom-converto",
|
||||
"--no-update-check",
|
||||
"capabilities",
|
||||
)
|
||||
|
||||
|
||||
class TestConvert:
|
||||
def _op(self) -> Operation:
|
||||
return Operation(
|
||||
target="chd",
|
||||
platforms=frozenset({"psp"}),
|
||||
argv=("chd", "compress"),
|
||||
input_exts=frozenset({".iso"}),
|
||||
output_ext=".chd",
|
||||
)
|
||||
|
||||
async def test_argv_is_operation_argv_plus_src_and_out(
|
||||
self, service: RomConvertoService, tmp_path: Path
|
||||
):
|
||||
recorded: list[list[str]] = []
|
||||
|
||||
src = tmp_path / "game.iso"
|
||||
out = tmp_path / "stage" / "game.chd"
|
||||
out.parent.mkdir()
|
||||
|
||||
async def fake_run(argv: list[str], timeout_seconds: float):
|
||||
recorded.append(argv)
|
||||
out.write_bytes(b"converted")
|
||||
return 0, "", ""
|
||||
|
||||
with patch.object(rom_converto, "_run", fake_run):
|
||||
await service.convert(self._op(), src, out)
|
||||
|
||||
assert recorded == [["chd", "compress", str(src), str(out)]]
|
||||
|
||||
async def test_an_owner_only_output_is_made_readable_for_nginx(
|
||||
self, service: RomConvertoService, tmp_path: Path
|
||||
):
|
||||
out = tmp_path / "game.chd"
|
||||
|
||||
async def fake_run(argv: list[str], timeout_seconds: float):
|
||||
out.write_bytes(b"converted")
|
||||
out.chmod(0o600)
|
||||
return 0, "", ""
|
||||
|
||||
with patch.object(rom_converto, "_run", fake_run):
|
||||
await service.convert(self._op(), tmp_path / "src" / "game.iso", out)
|
||||
|
||||
assert stat.S_IMODE(out.stat().st_mode) == SERVED_FILE_MODE
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"written",
|
||||
[
|
||||
pytest.param(["game.chd", "game.bin"], id="split"),
|
||||
pytest.param([], id="nothing"),
|
||||
],
|
||||
)
|
||||
async def test_output_other_than_out_raises_operation_error(
|
||||
self, service: RomConvertoService, tmp_path: Path, written: list[str]
|
||||
):
|
||||
async def fake_run(argv: list[str], timeout_seconds: float):
|
||||
for name in written:
|
||||
(tmp_path / name).write_bytes(b"x")
|
||||
return 0, "", ""
|
||||
|
||||
with (
|
||||
patch.object(rom_converto, "_run", fake_run),
|
||||
pytest.raises(RomConvertoOperationError, match="did not write exactly"),
|
||||
):
|
||||
await service.convert(self._op(), tmp_path / "x.iso", tmp_path / "game.chd")
|
||||
|
||||
async def test_nonzero_raises_operation_error_with_diagnostic(
|
||||
self, service: RomConvertoService, tmp_path: Path
|
||||
):
|
||||
async def fake_run(argv: list[str], timeout_seconds: float):
|
||||
return 1, "", "error: bad disc key"
|
||||
|
||||
src = tmp_path / "game.iso"
|
||||
out = tmp_path / "game.chd"
|
||||
with (
|
||||
patch.object(rom_converto, "_run", fake_run),
|
||||
pytest.raises(RomConvertoOperationError) as exc_info,
|
||||
):
|
||||
await service.convert(self._op(), src, out)
|
||||
|
||||
assert "bad disc key" in str(exc_info.value)
|
||||
|
||||
|
||||
class TestFileFormat:
|
||||
@pytest.mark.parametrize(
|
||||
("file_name", "expected"),
|
||||
[
|
||||
pytest.param("Game.ISO", "iso", id="target-extension"),
|
||||
pytest.param("game.zcia", "z3ds", id="compressed-3ds"),
|
||||
pytest.param("game.3ds", "cci", id="alias"),
|
||||
pytest.param("game.nkit.iso", "nkit-iso", id="compound-extension"),
|
||||
pytest.param("game.pbp", "pbp", id="input-only-extension"),
|
||||
pytest.param("game.zip", "zip", id="unknown-extension"),
|
||||
pytest.param("README", "", id="no-extension"),
|
||||
],
|
||||
)
|
||||
def test_names_the_format(self, file_name: str, expected: str):
|
||||
assert file_format(file_name) == expected
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("name", "expected"),
|
||||
[
|
||||
pytest.param("iso", "iso", id="plain"),
|
||||
pytest.param("3ds", "cci", id="alias"),
|
||||
pytest.param("zcia", "z3ds", id="compressed-alias"),
|
||||
pytest.param("nkit-iso", "nkit-iso", id="compound-not-iso"),
|
||||
],
|
||||
)
|
||||
def test_canonical_format_reads_aliases(self, name: str, expected: str):
|
||||
assert canonical_format(name) == expected
|
||||
|
||||
|
||||
class TestResolveOperation:
|
||||
@pytest.mark.parametrize(
|
||||
("platform", "target", "file_name", "argv", "input_ext", "output_name"),
|
||||
[
|
||||
(
|
||||
"ngc",
|
||||
"rvz",
|
||||
"Game.nkit.iso",
|
||||
("dol", "migrate"),
|
||||
".nkit.iso",
|
||||
"Game.rvz",
|
||||
),
|
||||
("ngc", "rvz", "Game.iso", ("dol", "compress"), ".iso", "Game.rvz"),
|
||||
("wii", "wbfs", "Game.rvz", ("rvl", "decompress"), ".rvz", "Game.wbfs"),
|
||||
("3ds", "z3ds", "Game.3ds", ("ctr", "compress"), ".3ds", "Game.zcci"),
|
||||
("3ds", "cci", "My Game.CIA", ("ctr", "convert"), ".cia", "My Game.cci"),
|
||||
("psp", "chd", "Game.ISO", ("chd", "compress"), ".iso", "Game.chd"),
|
||||
],
|
||||
)
|
||||
def test_resolves_operation_and_output_name(
|
||||
self,
|
||||
platform: str,
|
||||
target: str,
|
||||
file_name: str,
|
||||
argv: tuple[str, ...],
|
||||
input_ext: str,
|
||||
output_name: str,
|
||||
):
|
||||
resolved = resolve_operation(platform, target, file_name)
|
||||
|
||||
assert resolved is not None
|
||||
op, ext = resolved
|
||||
assert (op.argv, ext) == (argv, input_ext)
|
||||
assert op.output_name(Path(file_name), ext) == output_name
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("platform", "target", "file_name"),
|
||||
[
|
||||
pytest.param("psp", "iso", "Game.iso", id="already-in-target-format"),
|
||||
pytest.param("psx", "iso", "Game.chd", id="cd-chd-has-no-extract"),
|
||||
pytest.param("psx", "iso", "Game.cue", id="psx-cue-can-have-audio"),
|
||||
pytest.param("saturn", "iso", "Game.cue", id="saturn-cue-can-have-audio"),
|
||||
pytest.param("segacd", "iso", "Game.cue", id="segacd-cue-can-have-audio"),
|
||||
pytest.param("dc", "iso", "Game.cue", id="dc-cue-can-have-audio"),
|
||||
],
|
||||
)
|
||||
def test_returns_none_when_nothing_applies(
|
||||
self, platform: str, target: str, file_name: str
|
||||
):
|
||||
assert resolve_operation(platform, target, file_name) is None
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"platform",
|
||||
[
|
||||
pytest.param("psp", id="psp"),
|
||||
pytest.param("ps2", id="ps2"),
|
||||
],
|
||||
)
|
||||
def test_dvd_cue_still_converts_to_iso(self, platform: str):
|
||||
resolved = resolve_operation(platform, "iso", "Game.cue")
|
||||
|
||||
assert resolved is not None
|
||||
op, ext = resolved
|
||||
assert op.argv == ("cue", "to-iso")
|
||||
assert op.output_name(Path("Game.cue"), ext) == "Game.iso"
|
||||
|
||||
|
||||
class TestLibraryTargetsByPlatform:
|
||||
def test_psp_targets(self):
|
||||
assert LIBRARY_TARGETS_BY_PLATFORM["psp"] == {"chd", "cso", "iso", "zso"}
|
||||
|
||||
def test_platforms_without_format_conversions(self):
|
||||
for slug in ("wiiu", "psvita", "nds", "ps3"):
|
||||
assert slug not in LIBRARY_TARGETS_BY_PLATFORM
|
||||
|
||||
def test_a_lossy_conversion_is_no_library_target(self):
|
||||
assert "xbox" not in LIBRARY_TARGETS_BY_PLATFORM
|
||||
assert resolve_operation("xbox", "xiso", "game.iso") is not None
|
||||
assert resolve_operation("xbox", "xiso", "game.iso", lossless=True) is None
|
||||
|
||||
|
||||
class TestDownloadFormats:
|
||||
def test_maps_each_input_extension_to_its_targets(self):
|
||||
formats = DOWNLOAD_FORMATS
|
||||
|
||||
assert formats["psp"][".chd"] == ["cso", "iso", "zso"]
|
||||
assert formats["xbox"][".iso"] == ["xiso"]
|
||||
|
||||
def test_no_decrypt_or_encrypt_targets(self):
|
||||
targets = {
|
||||
target
|
||||
for exts in DOWNLOAD_FORMATS.values()
|
||||
for ext_targets in exts.values()
|
||||
for target in ext_targets
|
||||
}
|
||||
assert not targets & {"decrypted", "encrypted"}
|
||||
@@ -11,6 +11,7 @@ from config.config_manager import (
|
||||
DEFAULT_EXCLUDED_MULTI_FILE_DIRS,
|
||||
DEFAULT_EXCLUDED_PLATFORM_DIRS,
|
||||
ConfigManager,
|
||||
ConvertoConfig,
|
||||
parse_firmware_template,
|
||||
parse_platform_templates,
|
||||
parse_structure_template,
|
||||
@@ -188,6 +189,9 @@ def test_empty_config_loader():
|
||||
assert loader.config.SCAN_REGION_MODE == "prefer_rom_tags"
|
||||
assert loader.config.GAMELIST_MEDIA_THUMBNAIL == "box2d"
|
||||
assert loader.config.GAMELIST_MEDIA_IMAGE == "screenshot"
|
||||
assert not loader.config.CONVERTO.download_conversion_enabled
|
||||
assert loader.config.CONVERTO.cache_ttl_hours == 24
|
||||
assert loader.config.CONVERTO.platform_formats == {}
|
||||
assert loader.config.STRUCTURE_TEMPLATES == {}
|
||||
|
||||
|
||||
@@ -677,6 +681,72 @@ def test_reparenting_a_folder_replaces_the_existing_version(tmp_path):
|
||||
assert reloaded.config.PLATFORMS_VERSIONS == {"naomi": "dc"}
|
||||
|
||||
|
||||
def test_converto_config_from_yaml(tmp_path):
|
||||
config_file = tmp_path / "config.yml"
|
||||
config_file.write_text(
|
||||
"converto:\n"
|
||||
" download_conversion_enabled: true\n"
|
||||
" cache_ttl_hours: 48\n"
|
||||
" cache_max_size_gb: 0\n"
|
||||
" platform_formats:\n"
|
||||
" PSP: iso\n"
|
||||
" ngc: rvz\n"
|
||||
)
|
||||
loader = ConfigManager(str(config_file))
|
||||
|
||||
# Slugs and targets are normalized to lowercase.
|
||||
assert loader.config.CONVERTO == ConvertoConfig(
|
||||
download_conversion_enabled=True,
|
||||
cache_ttl_hours=48,
|
||||
cache_max_size_gb=0,
|
||||
platform_formats={"psp": "iso", "ngc": "rvz"},
|
||||
)
|
||||
|
||||
|
||||
def test_null_converto_platform_formats_means_empty(tmp_path):
|
||||
config_file = tmp_path / "config.yml"
|
||||
config_file.write_text("converto:\n platform_formats:\n")
|
||||
|
||||
assert ConfigManager(str(config_file)).config.CONVERTO.platform_formats == {}
|
||||
|
||||
|
||||
def test_update_converto_settings_round_trip(tmp_path):
|
||||
config_file = tmp_path / "config.yml"
|
||||
config_file.write_text("converto:\n cache_ttl_hours: 12\n")
|
||||
loader = ConfigManager(str(config_file))
|
||||
converto = ConvertoConfig(
|
||||
download_conversion_enabled=True,
|
||||
cache_ttl_hours=72,
|
||||
cache_max_size_gb=50,
|
||||
platform_formats={"psp": "iso", "ngc": "rvz"},
|
||||
)
|
||||
|
||||
loader.update_converto_settings(converto)
|
||||
|
||||
assert ConfigManager(str(config_file)).config.CONVERTO == converto
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"block",
|
||||
[
|
||||
" platform_formats:\n psvita: iso\n",
|
||||
" platform_formats:\n psp: rvz\n",
|
||||
" platform_formats:\n xbox: xiso\n",
|
||||
" cache_ttl_hours: 0\n",
|
||||
" cache_max_size_gb: -1\n",
|
||||
" cache_max_size_gb: true\n",
|
||||
],
|
||||
)
|
||||
def test_invalid_converto_setting_exits(tmp_path, block):
|
||||
config_file = tmp_path / "config.yml"
|
||||
config_file.write_text(f"converto:\n{block}")
|
||||
|
||||
with pytest.raises(SystemExit) as excinfo:
|
||||
ConfigManager(str(config_file))
|
||||
|
||||
assert excinfo.value.code == 3
|
||||
|
||||
|
||||
def _write_emulatorjs_config(tmp_path: Path, emulatorjs_block: str) -> ConfigManager:
|
||||
config_file = tmp_path / "config.yml"
|
||||
config_file.write_text(f"emulatorjs:\n{emulatorjs_block}")
|
||||
|
||||
311
backend/tests/endpoints/roms/test_converted_download.py
Normal file
311
backend/tests/endpoints/roms/test_converted_download.py
Normal file
@@ -0,0 +1,311 @@
|
||||
import asyncio
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
from urllib.parse import unquote
|
||||
|
||||
import pytest
|
||||
from fastapi import status
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from adapters.services.rom_converto import resolve_operation
|
||||
from config.config_manager import ConvertoConfig
|
||||
from models.rom import Rom
|
||||
from utils import conversion_cache
|
||||
from utils.conversion_cache import FAILED_FILE, RETRY_AFTER_SECONDS
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def conversion(tmp_path: Path, mocker):
|
||||
"""Enable download conversion with every rom-converto step mocked.
|
||||
|
||||
Any listed target resolves to a CHD under a temporary cache, and a
|
||||
conversion writes it there.
|
||||
"""
|
||||
converto = ConvertoConfig(download_conversion_enabled=True)
|
||||
mocker.patch(
|
||||
"utils.conversion_cache.cm.get_config",
|
||||
return_value=SimpleNamespace(CONVERTO=converto),
|
||||
)
|
||||
mocker.patch(
|
||||
"utils.conversion_cache.rom_converto_service.is_enabled",
|
||||
AsyncMock(return_value=True),
|
||||
)
|
||||
final = tmp_path / "cache/converts/1-abc/test_rom.chd"
|
||||
final.parent.mkdir(parents=True)
|
||||
resolved = resolve_operation("psp", "chd", "test_rom.iso")
|
||||
assert resolved is not None
|
||||
lookup = mocker.patch.object(
|
||||
conversion_cache, "_lookup", return_value=(resolved[0], final)
|
||||
)
|
||||
mocker.patch.object(conversion_cache, "ROMM_BASE_PATH", str(tmp_path))
|
||||
mocker.patch.object(
|
||||
conversion_cache, "ROM_CONVERTO_CACHE_PATH", str(final.parent.parent)
|
||||
)
|
||||
|
||||
async def convert(*args, **kwargs) -> Path:
|
||||
final.write_bytes(b"x" * 120)
|
||||
return final
|
||||
|
||||
return SimpleNamespace(
|
||||
converto=converto,
|
||||
final=final,
|
||||
lookup=lookup,
|
||||
convert=mocker.patch.object(
|
||||
conversion_cache, "get_or_convert", AsyncMock(side_effect=convert)
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cached_copy(conversion) -> Path:
|
||||
final: Path = conversion.final
|
||||
final.write_bytes(b"x" * 120)
|
||||
served = time.time() - 3600
|
||||
os.utime(final, (served, served))
|
||||
return final
|
||||
|
||||
|
||||
def _redirect(response) -> str:
|
||||
return unquote(response.headers["X-Accel-Redirect"])
|
||||
|
||||
|
||||
def _download(client: TestClient, rom: Rom, *, token: str | None, **params):
|
||||
return client.get(
|
||||
f"/api/roms/{rom.id}/content/test_rom.zip",
|
||||
headers={"Authorization": f"Bearer {token}"} if token else {},
|
||||
params=params,
|
||||
follow_redirects=False,
|
||||
)
|
||||
|
||||
|
||||
def _as_kiosk(mocker) -> None:
|
||||
mocker.patch("handler.auth.hybrid_auth.KIOSK_MODE", True)
|
||||
mocker.patch("handler.auth.permissions.KIOSK_MODE", True)
|
||||
|
||||
|
||||
def test_download_is_untouched_without_a_format(
|
||||
client: TestClient, access_token: str, rom: Rom, rom_file, conversion
|
||||
):
|
||||
response = _download(client, rom, token=access_token)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert _redirect(response) == f"/library/{rom_file.full_path}"
|
||||
conversion.lookup.assert_not_called()
|
||||
conversion.convert.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("formats", ["zip", "chd,zip", " ZIP "])
|
||||
def test_a_listed_stored_format_serves_the_stored_file(
|
||||
client: TestClient, access_token: str, rom: Rom, rom_file, conversion, formats
|
||||
):
|
||||
response = _download(client, rom, token=access_token, format=formats)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert _redirect(response) == f"/library/{rom_file.full_path}"
|
||||
conversion.convert.assert_not_called()
|
||||
|
||||
|
||||
def test_a_listed_stored_format_is_served_with_conversion_disabled(
|
||||
client: TestClient, access_token: str, rom: Rom, rom_file, conversion
|
||||
):
|
||||
conversion.converto.download_conversion_enabled = False
|
||||
|
||||
response = _download(client, rom, token=access_token, format="zip")
|
||||
|
||||
assert _redirect(response) == f"/library/{rom_file.full_path}"
|
||||
|
||||
|
||||
def test_a_cached_copy_is_served_without_converting(
|
||||
client: TestClient, access_token: str, rom: Rom, rom_file, cached_copy, conversion
|
||||
):
|
||||
response = _download(client, rom, token=access_token, format="chd")
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert _redirect(response) == "/cache/converts/1-abc/test_rom.chd"
|
||||
assert "test_rom.chd" in response.headers["Content-Disposition"]
|
||||
conversion.convert.assert_not_called()
|
||||
|
||||
|
||||
def test_a_quick_conversion_is_served_by_the_same_request(
|
||||
client: TestClient, access_token: str, rom: Rom, rom_file, conversion
|
||||
):
|
||||
response = _download(client, rom, token=access_token, format="chd")
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert _redirect(response) == "/cache/converts/1-abc/test_rom.chd"
|
||||
conversion.convert.assert_awaited_once()
|
||||
|
||||
|
||||
def test_a_slow_conversion_answers_202_and_keeps_running(
|
||||
client: TestClient, access_token: str, rom: Rom, rom_file, conversion, mocker
|
||||
):
|
||||
mocker.patch.object(conversion_cache, "CONVERSION_WAIT_SECONDS", 0.01)
|
||||
|
||||
final: Path = conversion.final
|
||||
|
||||
async def slow_convert(*args, **kwargs) -> Path:
|
||||
await asyncio.sleep(0.2)
|
||||
return final
|
||||
|
||||
conversion.convert.side_effect = slow_convert
|
||||
|
||||
response = _download(client, rom, token=access_token, format="chd")
|
||||
|
||||
assert response.status_code == status.HTTP_202_ACCEPTED
|
||||
assert response.headers["Retry-After"] == str(RETRY_AFTER_SECONDS)
|
||||
assert "X-Accel-Redirect" not in response.headers
|
||||
conversion.convert.assert_called_once()
|
||||
|
||||
|
||||
def test_a_running_conversion_answers_202_without_starting_another(
|
||||
client: TestClient, access_token: str, rom: Rom, rom_file, conversion, mocker
|
||||
):
|
||||
mocker.patch.object(conversion_cache, "_is_converting", return_value=True)
|
||||
|
||||
response = _download(client, rom, token=access_token, format="chd")
|
||||
|
||||
assert response.status_code == status.HTTP_202_ACCEPTED
|
||||
conversion.convert.assert_not_called()
|
||||
|
||||
|
||||
def test_head_reports_202_or_the_cached_copy_but_never_converts(
|
||||
client: TestClient, access_token: str, rom: Rom, rom_file, conversion
|
||||
):
|
||||
headers = {"Authorization": f"Bearer {access_token}"}
|
||||
url = f"/api/roms/{rom.id}/content/test_rom.zip"
|
||||
|
||||
uncached = client.head(url, headers=headers, params={"format": "chd"})
|
||||
conversion.final.write_bytes(b"x")
|
||||
cached = client.head(url, headers=headers, params={"format": "chd"})
|
||||
|
||||
assert uncached.status_code == status.HTTP_202_ACCEPTED
|
||||
assert _redirect(cached) == "/cache/converts/1-abc/test_rom.chd"
|
||||
conversion.convert.assert_not_called()
|
||||
|
||||
|
||||
def test_a_kiosk_visitor_never_starts_a_conversion(
|
||||
client: TestClient, rom: Rom, rom_file, conversion, mocker
|
||||
):
|
||||
_as_kiosk(mocker)
|
||||
|
||||
response = _download(client, rom, token=None, format="chd")
|
||||
|
||||
assert response.status_code == status.HTTP_406_NOT_ACCEPTABLE
|
||||
conversion.convert.assert_not_called()
|
||||
|
||||
|
||||
def test_a_kiosk_visitor_still_gets_a_cached_copy(
|
||||
client: TestClient, rom: Rom, rom_file, cached_copy, conversion, mocker
|
||||
):
|
||||
_as_kiosk(mocker)
|
||||
|
||||
response = _download(client, rom, token=None, format="chd")
|
||||
|
||||
assert _redirect(response) == "/cache/converts/1-abc/test_rom.chd"
|
||||
|
||||
|
||||
def test_no_producible_format_answers_406(
|
||||
client: TestClient, access_token: str, rom: Rom, rom_file, conversion
|
||||
):
|
||||
conversion.lookup.return_value = None
|
||||
|
||||
response = _download(client, rom, token=access_token, format="rvz,wbfs")
|
||||
|
||||
assert response.status_code == status.HTTP_406_NOT_ACCEPTABLE
|
||||
assert "rvz, wbfs" in response.json()["detail"]
|
||||
conversion.convert.assert_not_called()
|
||||
|
||||
|
||||
def test_disabled_conversion_answers_406_for_another_format(
|
||||
client: TestClient, access_token: str, rom: Rom, rom_file, conversion
|
||||
):
|
||||
conversion.converto.download_conversion_enabled = False
|
||||
|
||||
response = _download(client, rom, token=access_token, format="chd")
|
||||
|
||||
assert response.status_code == status.HTTP_406_NOT_ACCEPTABLE
|
||||
conversion.lookup.assert_not_called()
|
||||
|
||||
|
||||
def test_a_failed_conversion_is_not_retried(
|
||||
client: TestClient, access_token: str, rom: Rom, rom_file, conversion
|
||||
):
|
||||
(conversion.final.parent / FAILED_FILE).touch()
|
||||
|
||||
response = _download(client, rom, token=access_token, format="chd")
|
||||
|
||||
assert response.status_code == status.HTTP_406_NOT_ACCEPTABLE
|
||||
conversion.convert.assert_not_called()
|
||||
|
||||
|
||||
def test_a_conversion_that_fails_answers_406(
|
||||
client: TestClient, access_token: str, rom: Rom, rom_file, conversion
|
||||
):
|
||||
conversion.convert.side_effect = None
|
||||
conversion.convert.return_value = None
|
||||
|
||||
response = _download(client, rom, token=access_token, format="chd")
|
||||
|
||||
assert response.status_code == status.HTTP_406_NOT_ACCEPTABLE
|
||||
|
||||
|
||||
def test_a_format_needs_a_single_file(
|
||||
client: TestClient, access_token: str, multi_file_rom: Rom, conversion
|
||||
):
|
||||
response = client.head(
|
||||
f"/api/roms/{multi_file_rom.id}/content/test_multi_file_rom.zip",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
params={"format": "chd"},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_406_NOT_ACCEPTABLE
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "visitor"),
|
||||
[
|
||||
pytest.param("get", "authenticated", id="authenticated-download"),
|
||||
pytest.param("get", "kiosk", id="kiosk-download"),
|
||||
pytest.param("get", "public", id="download-auth-disabled"),
|
||||
pytest.param("head", "authenticated", id="metadata"),
|
||||
],
|
||||
)
|
||||
def test_get_refreshes_a_cached_copy_but_head_does_not(
|
||||
client: TestClient,
|
||||
access_token: str,
|
||||
rom: Rom,
|
||||
rom_file,
|
||||
conversion,
|
||||
cached_copy: Path,
|
||||
mocker,
|
||||
method,
|
||||
visitor,
|
||||
):
|
||||
headers = {"Authorization": f"Bearer {access_token}"}
|
||||
if visitor == "kiosk":
|
||||
_as_kiosk(mocker)
|
||||
headers = {}
|
||||
elif visitor == "public":
|
||||
# Download scopes are fixed when the route decorators are evaluated.
|
||||
mocker.patch("decorators.auth.has_required_scope", return_value=True)
|
||||
headers = {}
|
||||
conversion.converto.cache_max_size_gb = 1
|
||||
mocker.patch.object(conversion_cache, "BYTES_PER_GB", 100)
|
||||
|
||||
response = client.request(
|
||||
method,
|
||||
f"/api/roms/{rom.id}/content/test_rom.zip",
|
||||
headers=headers,
|
||||
params={"format": "chd"},
|
||||
follow_redirects=False,
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert _redirect(response) == "/cache/converts/1-abc/test_rom.chd"
|
||||
assert (cached_copy.stat().st_mtime > time.time() - 60) is (method == "get")
|
||||
assert conversion_cache.cleanup_stale_conversions() == (0 if method == "get" else 1)
|
||||
assert cached_copy.exists() is (method == "get")
|
||||
conversion.convert.assert_not_called()
|
||||
@@ -1,5 +1,7 @@
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import status
|
||||
|
||||
from config.config_manager import (
|
||||
@@ -7,6 +9,7 @@ from config.config_manager import (
|
||||
DEFAULT_EXCLUDED_FILES,
|
||||
DEFAULT_EXCLUDED_MULTI_FILE_DIRS,
|
||||
DEFAULT_EXCLUDED_PLATFORM_DIRS,
|
||||
ConvertoConfig,
|
||||
ExclusionType,
|
||||
)
|
||||
from config.config_manager import config_manager as cm
|
||||
@@ -261,3 +264,66 @@ def test_update_scan_settings_normalizes_codes(client, access_token: str):
|
||||
_, kwargs = update_scan_settings.call_args
|
||||
assert kwargs["region_priority"] == ["us", "eu"]
|
||||
assert kwargs["language_priority"] == ["en"]
|
||||
|
||||
|
||||
def _converto_payload(**overrides):
|
||||
payload = {
|
||||
"download_conversion_enabled": True,
|
||||
"cache_max_size_gb": 20,
|
||||
"platform_formats": {"psp": "cso"},
|
||||
}
|
||||
payload.update(overrides)
|
||||
return payload
|
||||
|
||||
|
||||
def test_update_converto_settings_normalizes_formats_and_keeps_the_ttl(
|
||||
client, access_token: str
|
||||
):
|
||||
current = SimpleNamespace(CONVERTO=ConvertoConfig(cache_ttl_hours=72))
|
||||
with (
|
||||
patch.object(cm, "get_config", return_value=current),
|
||||
patch.object(cm, "update_converto_settings") as update_converto_settings,
|
||||
):
|
||||
response = client.put(
|
||||
"/api/config/converto_settings",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
json=_converto_payload(platform_formats={" PSP ": "CSO"}),
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
update_converto_settings.assert_called_once_with(
|
||||
ConvertoConfig(
|
||||
download_conversion_enabled=True,
|
||||
cache_ttl_hours=72,
|
||||
cache_max_size_gb=20,
|
||||
platform_formats={"psp": "cso"},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_update_converto_settings_requires_auth(client):
|
||||
response = client.put("/api/config/converto_settings", json=_converto_payload())
|
||||
assert response.status_code == status.HTTP_401_UNAUTHORIZED
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"overrides",
|
||||
[
|
||||
{"platform_formats": {"psp": "rvz"}},
|
||||
{"platform_formats": {"psvita": "iso"}},
|
||||
{"platform_formats": {"xbox": "xiso"}},
|
||||
{"cache_max_size_gb": -1},
|
||||
],
|
||||
)
|
||||
def test_update_converto_settings_rejects_invalid_values(
|
||||
client, access_token: str, overrides
|
||||
):
|
||||
with patch.object(cm, "update_converto_settings") as update_converto_settings:
|
||||
response = client.put(
|
||||
"/api/config/converto_settings",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
json=_converto_payload(**overrides),
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
|
||||
update_converto_settings.assert_not_called()
|
||||
|
||||
@@ -43,8 +43,8 @@ def _keys(rom_id: int) -> set[tuple[int, int, str]]:
|
||||
"""
|
||||
with sync_session.begin() as session:
|
||||
return {
|
||||
tuple(row)
|
||||
for row in session.execute(
|
||||
(provider, platform_id, provider_id)
|
||||
for provider, platform_id, provider_id in session.execute(
|
||||
select(
|
||||
RomIdentityKey.provider,
|
||||
RomIdentityKey.platform_id,
|
||||
|
||||
@@ -69,7 +69,7 @@ def _grouped_query(order_by: str = "", user_id: int | None = None):
|
||||
|
||||
def _dedup_window_subquery(
|
||||
order_by: str = "", user_id: int | None = None
|
||||
) -> Select[Any]:
|
||||
) -> Select[*tuple[Any, ...]]:
|
||||
"""The narrow `roms` subquery the grouped query materializes for its window."""
|
||||
for subquery in _subqueries(_grouped_query(order_by, user_id)):
|
||||
if not isinstance(subquery.element, Select):
|
||||
@@ -83,7 +83,9 @@ def _dedup_window_subquery(
|
||||
raise AssertionError("the grouped query no longer materializes a roms subquery")
|
||||
|
||||
|
||||
def _dedup_window_select(order_by: str = "", user_id: int | None = None) -> Select[Any]:
|
||||
def _dedup_window_select(
|
||||
order_by: str = "", user_id: int | None = None
|
||||
) -> Select[*tuple[Any, ...]]:
|
||||
"""The SELECT that computes `row_num` (and any group aggregate)."""
|
||||
for subquery in _subqueries(_grouped_query(order_by, user_id)):
|
||||
if not isinstance(subquery.element, Select):
|
||||
|
||||
28
backend/tests/tasks/test_cleanup_conversion_cache.py
Normal file
28
backend/tests/tasks/test_cleanup_conversion_cache.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from dataclasses import replace
|
||||
|
||||
from tasks.registry import CLEANUP_CONVERSION_CACHE_SPEC
|
||||
from tasks.scheduled.cleanup_conversion_cache import CleanupConversionCacheTask
|
||||
|
||||
|
||||
class TestCleanupConversionCacheTask:
|
||||
def test_configuration(self):
|
||||
assert CLEANUP_CONVERSION_CACHE_SPEC.enabled is True
|
||||
assert CLEANUP_CONVERSION_CACHE_SPEC.cron_string == "0 4 * * *"
|
||||
|
||||
async def test_run_calls_cleanup(self, mocker):
|
||||
task = CleanupConversionCacheTask()
|
||||
mock_cleanup = mocker.patch(
|
||||
"tasks.scheduled.cleanup_conversion_cache.cleanup_stale_conversions",
|
||||
return_value=2,
|
||||
)
|
||||
await task.run()
|
||||
mock_cleanup.assert_called_once_with()
|
||||
|
||||
async def test_run_disabled_skips_the_cleanup(self, mocker):
|
||||
task = CleanupConversionCacheTask()
|
||||
task.spec = replace(task.spec, enabled=False)
|
||||
mock_cleanup = mocker.patch(
|
||||
"tasks.scheduled.cleanup_conversion_cache.cleanup_stale_conversions",
|
||||
)
|
||||
await task.run()
|
||||
mock_cleanup.assert_not_called()
|
||||
400
backend/tests/tasks/test_convert_library.py
Normal file
400
backend/tests/tasks/test_convert_library.py
Normal file
@@ -0,0 +1,400 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from tests.factories import make_rom
|
||||
|
||||
from adapters.services.rom_converto import (
|
||||
RomConvertoOperationError,
|
||||
rom_converto_service,
|
||||
)
|
||||
from config.config_manager import ConvertoConfig
|
||||
from config.config_manager import config_manager as cm
|
||||
from handler.database import db_platform_handler, db_rom_handler
|
||||
from handler.filesystem import fs_rom_handler
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom, RomFile, RomFileCategory
|
||||
from models.user import User
|
||||
from tasks.manual.convert_library import ConvertLibraryTask
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def library(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
lib = tmp_path / "library"
|
||||
lib.mkdir()
|
||||
monkeypatch.setattr(fs_rom_handler, "base_path", lib.resolve())
|
||||
return lib
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def converto(mocker) -> ConvertoConfig:
|
||||
config = ConvertoConfig(platform_formats={"psp": "chd", "psx": "chd"})
|
||||
# The file refresh after a conversion reads the rest of the same config.
|
||||
real = cm.get_config()
|
||||
mocker.patch.object(real, "CONVERTO", config)
|
||||
mocker.patch.object(cm, "get_config", return_value=real)
|
||||
return config
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def converted(mocker) -> list[tuple[str, Path]]:
|
||||
"""Fake rom-converto: each conversion writes a small output and is recorded."""
|
||||
calls: list[tuple[str, Path]] = []
|
||||
|
||||
def convert(operation, src: Path, out: Path) -> None:
|
||||
calls.append((src.name, out))
|
||||
out.write_bytes(b"c")
|
||||
|
||||
mocker.patch.object(
|
||||
rom_converto_service, "is_enabled", AsyncMock(return_value=True)
|
||||
)
|
||||
mocker.patch.object(rom_converto_service, "convert", AsyncMock(side_effect=convert))
|
||||
return calls
|
||||
|
||||
|
||||
def _platform(slug: str) -> Platform:
|
||||
return db_platform_handler.add_platform(
|
||||
Platform(name=slug, slug=slug, fs_slug=slug)
|
||||
)
|
||||
|
||||
|
||||
def _rom(
|
||||
library: Path,
|
||||
admin_user: User,
|
||||
platform: Platform,
|
||||
files: dict[str, bytes],
|
||||
*,
|
||||
folder: bool = False,
|
||||
matched: bool = True,
|
||||
) -> Rom:
|
||||
"""A rom with `files` on disk: a single file, or a folder holding them all."""
|
||||
name = "game"
|
||||
rom = make_rom(
|
||||
platform,
|
||||
name,
|
||||
fs_extension="" if folder else Path(next(iter(files))).suffix.lstrip("."),
|
||||
igdb_id=1 if matched else None,
|
||||
)
|
||||
db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id)
|
||||
file_path = f"{rom.fs_path}/{rom.fs_name}" if folder else rom.fs_path
|
||||
for file_name, data in files.items():
|
||||
disk = library / file_path / file_name
|
||||
disk.parent.mkdir(parents=True, exist_ok=True)
|
||||
disk.write_bytes(data)
|
||||
db_rom_handler.add_rom_file(
|
||||
RomFile(
|
||||
rom_id=rom.id,
|
||||
file_name=file_name,
|
||||
file_path=file_path,
|
||||
file_size_bytes=len(data),
|
||||
last_modified=disk.stat().st_mtime,
|
||||
category=RomFileCategory.GAME,
|
||||
)
|
||||
)
|
||||
refreshed = db_rom_handler.get_rom(rom.id)
|
||||
assert refreshed is not None
|
||||
return refreshed
|
||||
|
||||
|
||||
def _reload(rom: Rom) -> Rom:
|
||||
refreshed = db_rom_handler.get_rom(rom.id)
|
||||
assert refreshed is not None
|
||||
return refreshed
|
||||
|
||||
|
||||
async def _run(platform: Platform | None = None) -> dict[str, int]:
|
||||
return await ConvertLibraryTask().run(platform.id if platform else None)
|
||||
|
||||
|
||||
async def test_a_single_file_rom_is_replaced_and_keeps_its_id(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
psp = _platform("psp")
|
||||
rom = _rom(library, admin_user, psp, {"game.iso": b"x" * 100})
|
||||
folder = library / rom.fs_path
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["converted"] == 1
|
||||
assert stats["bytes_saved"] == 99
|
||||
assert sorted(p.name for p in folder.iterdir()) == ["game.chd"]
|
||||
after = _reload(rom)
|
||||
assert after.fs_name == "game.chd"
|
||||
assert after.fs_extension == "chd"
|
||||
assert [f.file_name for f in after.files] == ["game.chd"]
|
||||
|
||||
|
||||
async def test_a_cue_folder_becomes_one_chd_and_its_playlist_follows(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
psx = _platform("psx")
|
||||
cue = 'FILE "game (Track 1).bin" BINARY\nFILE "game (Track 2).bin" BINARY\n'
|
||||
rom = _rom(
|
||||
library,
|
||||
admin_user,
|
||||
psx,
|
||||
{
|
||||
"game.cue": cue.encode(),
|
||||
"game (Track 1).bin": b"x" * 50,
|
||||
"game (Track 2).bin": b"x" * 50,
|
||||
"game.m3u": b"game.cue\n",
|
||||
},
|
||||
folder=True,
|
||||
)
|
||||
folder = library / rom.full_path
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["converted"] == 1
|
||||
assert sorted(p.name for p in folder.iterdir()) == ["game.chd", "game.m3u"]
|
||||
assert (folder / "game.m3u").read_text() == "game.chd\n"
|
||||
after = _reload(rom)
|
||||
assert after.fs_name == rom.fs_name
|
||||
assert sorted(f.file_name for f in after.files) == ["game.chd", "game.m3u"]
|
||||
|
||||
|
||||
async def test_a_bom_cue_and_playlist_still_follow_the_conversion(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
bom = "\ufeff".encode()
|
||||
rom = _rom(
|
||||
library,
|
||||
admin_user,
|
||||
_platform("psx"),
|
||||
{
|
||||
"game.cue": bom + b'FILE "game.bin" BINARY\n',
|
||||
"game.bin": b"x" * 50,
|
||||
"game.m3u": bom + b"./game.cue\n",
|
||||
},
|
||||
folder=True,
|
||||
)
|
||||
folder = library / rom.full_path
|
||||
|
||||
await _run()
|
||||
|
||||
assert sorted(p.name for p in folder.iterdir()) == ["game.chd", "game.m3u"]
|
||||
assert (folder / "game.m3u").read_text() == "game.chd\n"
|
||||
# Staged beside the rom folder, whose dot-prefixed subfolders count as its files.
|
||||
assert converted[0][1].parent.parent == library / rom.fs_path
|
||||
|
||||
|
||||
async def test_one_roms_failure_does_not_stop_the_run(
|
||||
library: Path, admin_user: User, converto, converted, mocker
|
||||
):
|
||||
_rom(library, admin_user, _platform("psp"), {"game.iso": b"x"})
|
||||
_rom(library, admin_user, _platform("psx"), {"game.cue": b""}, folder=True)
|
||||
mocker.patch(
|
||||
"tasks.manual.convert_library.refresh_rom_files",
|
||||
AsyncMock(side_effect=[RuntimeError("lock timeout"), None]),
|
||||
)
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["failed"] == 1
|
||||
assert sorted(src for src, _ in converted) == ["game.cue", "game.iso"]
|
||||
|
||||
|
||||
async def test_a_file_already_in_the_library_format_is_left_alone(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
_rom(library, admin_user, _platform("psp"), {"game.chd": b"x"})
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["already_converted"] == 1
|
||||
assert converted == []
|
||||
|
||||
|
||||
async def test_an_unmatched_rom_is_not_converted(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
rom = _rom(library, admin_user, _platform("psp"), {"game.iso": b"x"}, matched=False)
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["unmatched"] == 1
|
||||
assert converted == []
|
||||
assert (library / rom.full_path).exists()
|
||||
|
||||
|
||||
async def test_a_platform_without_a_library_format_is_skipped(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
converto.platform_formats = {}
|
||||
_rom(library, admin_user, _platform("psp"), {"game.iso": b"x"})
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["converted"] == 0
|
||||
assert converted == []
|
||||
|
||||
|
||||
async def test_only_the_requested_platform_is_converted(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
psp = _platform("psp")
|
||||
_rom(library, admin_user, psp, {"game.iso": b"x" * 10})
|
||||
_rom(library, admin_user, _platform("psx"), {"game.cue": b""}, folder=True)
|
||||
|
||||
await _run(psp)
|
||||
|
||||
assert [src for src, _ in converted] == ["game.iso"]
|
||||
|
||||
|
||||
async def test_a_failed_conversion_leaves_the_original_and_no_staged_output(
|
||||
library: Path, admin_user: User, converto, converted, mocker
|
||||
):
|
||||
rom = _rom(library, admin_user, _platform("psp"), {"game.iso": b"x"})
|
||||
mocker.patch.object(
|
||||
rom_converto_service,
|
||||
"convert",
|
||||
AsyncMock(side_effect=RomConvertoOperationError("boom")),
|
||||
)
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["failed"] == 1
|
||||
assert sorted(p.name for p in (library / rom.fs_path).iterdir()) == ["game.iso"]
|
||||
assert _reload(rom).fs_name == "game.iso"
|
||||
|
||||
|
||||
async def test_an_existing_output_is_never_overwritten(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
rom = _rom(library, admin_user, _platform("psp"), {"game.iso": b"x"})
|
||||
(library / rom.fs_path / "game.chd").write_bytes(b"theirs")
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["failed"] == 1
|
||||
assert converted == []
|
||||
assert (library / rom.fs_path / "game.chd").read_bytes() == b"theirs"
|
||||
assert (library / rom.full_path).exists()
|
||||
|
||||
|
||||
async def test_an_output_appearing_during_conversion_is_never_overwritten(
|
||||
library: Path, admin_user: User, converto, converted, mocker
|
||||
):
|
||||
rom = _rom(library, admin_user, _platform("psp"), {"game.iso": b"x"})
|
||||
theirs = library / rom.fs_path / "game.chd"
|
||||
|
||||
def convert(operation, src: Path, out: Path) -> None:
|
||||
theirs.write_bytes(b"theirs")
|
||||
out.write_bytes(b"c")
|
||||
|
||||
mocker.patch.object(rom_converto_service, "convert", AsyncMock(side_effect=convert))
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["failed"] == 1
|
||||
assert theirs.read_bytes() == b"theirs"
|
||||
assert (library / rom.full_path).exists()
|
||||
|
||||
|
||||
async def test_a_failed_rom_update_keeps_the_original(
|
||||
library: Path, admin_user: User, converto, converted, mocker
|
||||
):
|
||||
rom = _rom(library, admin_user, _platform("psp"), {"game.iso": b"x"})
|
||||
mocker.patch.object(
|
||||
db_rom_handler, "update_rom", side_effect=SQLAlchemyError("conflict")
|
||||
)
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["failed"] == 1
|
||||
assert sorted(p.name for p in (library / rom.fs_path).iterdir()) == ["game.iso"]
|
||||
|
||||
|
||||
async def test_a_cue_track_held_by_another_rom_is_not_deleted(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
psx = _platform("psx")
|
||||
rom = _rom(library, admin_user, psx, {"game.cue": b'FILE "game.bin" BINARY\n'})
|
||||
(library / rom.fs_path / "game.bin").write_bytes(b"x")
|
||||
make_rom(psx, "track", fs_stem="game", fs_extension="bin")
|
||||
|
||||
stats = await _run(psx)
|
||||
|
||||
assert stats["failed"] == 1
|
||||
assert converted == []
|
||||
assert (library / rom.fs_path / "game.bin").exists()
|
||||
|
||||
|
||||
async def test_a_track_another_cue_shares_is_refused(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
track = b'FILE "game.bin" BINARY\n'
|
||||
rom = _rom(
|
||||
library,
|
||||
admin_user,
|
||||
_platform("psx"),
|
||||
{"disc 1.cue": track, "disc 2.cue": track, "game.bin": b"x"},
|
||||
folder=True,
|
||||
)
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["failed"] == 2
|
||||
assert converted == []
|
||||
assert (library / rom.full_path / "game.bin").exists()
|
||||
|
||||
|
||||
async def test_a_stage_left_by_a_killed_conversion_is_removed(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
rom = _rom(library, admin_user, _platform("psp"), {"game.iso": b"x"})
|
||||
stale = library / rom.fs_path / ".romm_tmp_convert_old"
|
||||
stale.mkdir()
|
||||
os.utime(stale, (0, 0))
|
||||
|
||||
await _run()
|
||||
|
||||
assert not stale.exists()
|
||||
|
||||
|
||||
async def test_a_rom_row_already_holding_the_output_name_is_left_alone(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
psp = _platform("psp")
|
||||
rom = _rom(library, admin_user, psp, {"game.iso": b"x"})
|
||||
make_rom(psp, "other", fs_stem="game", fs_extension="chd")
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["failed"] == 1
|
||||
assert converted == []
|
||||
assert (library / rom.full_path).exists()
|
||||
|
||||
|
||||
async def test_a_cue_pointing_outside_its_folder_is_refused(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
rom = _rom(
|
||||
library,
|
||||
admin_user,
|
||||
_platform("psx"),
|
||||
{"game.cue": b'FILE "../other.bin" BINARY\n'},
|
||||
folder=True,
|
||||
)
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["failed"] == 1
|
||||
assert converted == []
|
||||
assert (library / rom.full_path / "game.cue").exists()
|
||||
|
||||
|
||||
async def test_nothing_runs_without_rom_converto(
|
||||
library: Path, admin_user: User, converto, converted, mocker
|
||||
):
|
||||
mocker.patch.object(
|
||||
rom_converto_service, "is_enabled", AsyncMock(return_value=False)
|
||||
)
|
||||
_rom(library, admin_user, _platform("psp"), {"game.iso": b"x"})
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["converted"] == 0
|
||||
assert converted == []
|
||||
@@ -195,7 +195,7 @@ def test_the_migrated_full_path_digest_matches_the_models(
|
||||
A mismatch would make every pre-existing rom look new to the unique index.
|
||||
"""
|
||||
with sync_engine.connect() as connection:
|
||||
digest = connection.execute(
|
||||
digest: str = connection.execute(
|
||||
sa.text(
|
||||
f"SELECT {full_path_digest_sql(connection)} FROM "
|
||||
"(SELECT :fs_path AS fs_path, :fs_name AS fs_name) AS one_rom"
|
||||
@@ -375,7 +375,7 @@ def test_the_derivable_columns_revision_reverses_and_replays(admin_user: User):
|
||||
}
|
||||
assert not columns[("rom_file_doc_meta", "rom_id")]["nullable"]
|
||||
assert columns[("smart_collections", "rom_count")]["default"] is None
|
||||
rom_count = connection.execute(
|
||||
rom_count: int = connection.execute(
|
||||
sa.text("SELECT rom_count FROM smart_collections WHERE id = :id"),
|
||||
{"id": smart.id},
|
||||
).scalar_one()
|
||||
@@ -673,7 +673,7 @@ def test_the_full_path_hash_migration_resumes_an_interrupted_run(rom: Rom):
|
||||
migration.upgrade()
|
||||
|
||||
columns, indexes = _schema_of(connection, "roms")
|
||||
digest = connection.execute(
|
||||
digest: str = connection.execute(
|
||||
sa.text(
|
||||
f"SELECT {migration.COLUMN_NAME} FROM roms WHERE id = :rom_id"
|
||||
), # nosec B608
|
||||
@@ -940,7 +940,7 @@ def test_the_roms_columns_helper_fills_the_full_path_digest_where_it_can(rom: Ro
|
||||
assert columns[FULL_PATH_HASH_COLUMN] is not is_mariadb(connection)
|
||||
assert not has_server_default(connection, FULL_PATH_HASH_COLUMN)
|
||||
if is_mariadb(connection):
|
||||
digest = connection.execute(
|
||||
digest: str = connection.execute(
|
||||
sa.text(
|
||||
f"SELECT {FULL_PATH_HASH_COLUMN} FROM roms WHERE id = :rom_id" # nosec B608
|
||||
),
|
||||
|
||||
986
backend/tests/utils/test_conversion_cache.py
Normal file
986
backend/tests/utils/test_conversion_cache.py
Normal file
@@ -0,0 +1,986 @@
|
||||
import asyncio
|
||||
import fcntl
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from contextlib import ExitStack, contextmanager, nullcontext
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, cast
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
from adapters.services.rom_converto import (
|
||||
RomConvertoBinaryNotFoundError,
|
||||
RomConvertoOperationError,
|
||||
RomConvertoTimeoutError,
|
||||
resolve_operation,
|
||||
)
|
||||
from config import ROMM_BASE_PATH
|
||||
from config.config_manager import ConvertoConfig
|
||||
from models.rom import Rom, RomFile
|
||||
from utils import conversion_cache
|
||||
from utils.conversion_cache import (
|
||||
FAILED_FILE,
|
||||
PARTIAL_DIR,
|
||||
SERVE_GRACE_SECONDS,
|
||||
FormatOutcome,
|
||||
FormatResolution,
|
||||
converted_file_path,
|
||||
get_cached_converted,
|
||||
get_or_convert,
|
||||
get_redirect_path,
|
||||
parse_formats,
|
||||
resolve_format_download,
|
||||
)
|
||||
|
||||
|
||||
def _rom_file(**overrides: Any) -> RomFile:
|
||||
defaults: dict[str, Any] = {
|
||||
"rom_id": 1,
|
||||
"file_name": "game.iso",
|
||||
"file_path": "psp/roms",
|
||||
"file_size_bytes": 1000,
|
||||
"last_modified": 1700000000.0,
|
||||
}
|
||||
defaults.update(overrides)
|
||||
return RomFile(**defaults)
|
||||
|
||||
|
||||
def _final_path(rom_file: RomFile) -> Path:
|
||||
resolved = resolve_operation("psp", "chd", rom_file.file_name)
|
||||
assert resolved is not None
|
||||
return converted_file_path(1, rom_file, *resolved)
|
||||
|
||||
|
||||
def _partial_path(final: Path) -> Path:
|
||||
return final.parent / PARTIAL_DIR / final.name
|
||||
|
||||
|
||||
def _seed_cached(rom_file: RomFile, *, age_seconds: float = 0) -> Path:
|
||||
"""Write a converted copy for `rom_file`, last served `age_seconds` ago."""
|
||||
final = _final_path(rom_file)
|
||||
final.parent.mkdir(parents=True, exist_ok=True)
|
||||
final.write_bytes(b"cached")
|
||||
served = time.time() - age_seconds
|
||||
os.utime(final, (served, served))
|
||||
return final
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _held_lock(key_dir: Path, *, shared: bool = False) -> Iterator[None]:
|
||||
"""Hold a key dir lock while a request or worker uses it."""
|
||||
fd = os.open(key_dir, os.O_RDONLY)
|
||||
fcntl.flock(fd, fcntl.LOCK_SH if shared else fcntl.LOCK_EX)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def converto(mocker) -> ConvertoConfig:
|
||||
"""The converto.* settings every cache function reads, editable per test."""
|
||||
config = ConvertoConfig()
|
||||
mocker.patch(
|
||||
"utils.conversion_cache.cm.get_config",
|
||||
return_value=SimpleNamespace(CONVERTO=config),
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cache_root(tmp_path, mocker):
|
||||
mocker.patch.object(conversion_cache, "ROM_CONVERTO_CACHE_PATH", str(tmp_path))
|
||||
return tmp_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def convert_outputs(mocker) -> list[Path]:
|
||||
"""Fake the adapter: write each requested output and record its path."""
|
||||
outputs: list[Path] = []
|
||||
|
||||
async def convert(operation, src, out) -> None:
|
||||
outputs.append(out)
|
||||
out.write_bytes(b"converted")
|
||||
|
||||
mocker.patch(
|
||||
"utils.conversion_cache.rom_converto_service.convert", side_effect=convert
|
||||
)
|
||||
return outputs
|
||||
|
||||
|
||||
class TestGetOrConvert:
|
||||
async def test_unresolvable_returns_none_without_touching_disk(
|
||||
self, cache_root, convert_outputs
|
||||
):
|
||||
f = _rom_file(file_name="game.zip")
|
||||
|
||||
assert await get_or_convert(1, f, "psp", "chd") is None
|
||||
assert convert_outputs == []
|
||||
assert not any(cache_root.iterdir())
|
||||
|
||||
async def test_cache_hit_returns_path_and_refreshes_mtime(
|
||||
self, cache_root, convert_outputs
|
||||
):
|
||||
f = _rom_file()
|
||||
final = _seed_cached(f, age_seconds=3600)
|
||||
|
||||
assert await get_or_convert(1, f, "psp", "chd") == final
|
||||
assert final.stat().st_mtime > time.time() - 60
|
||||
assert convert_outputs == []
|
||||
|
||||
async def test_oversized_conversion_returns_none_without_converting(
|
||||
self, cache_root, converto, convert_outputs, mocker
|
||||
):
|
||||
converto.cache_max_size_gb = 1
|
||||
mocker.patch.object(conversion_cache, "BYTES_PER_GB", 100)
|
||||
|
||||
assert (
|
||||
await get_or_convert(1, _rom_file(file_size_bytes=101), "psp", "chd")
|
||||
is None
|
||||
)
|
||||
assert convert_outputs == []
|
||||
|
||||
async def test_admission_reserves_room_for_a_decompression(
|
||||
self, cache_root, converto, convert_outputs, mocker
|
||||
):
|
||||
converto.cache_max_size_gb = 1
|
||||
mocker.patch.object(conversion_cache, "BYTES_PER_GB", 100)
|
||||
f = _rom_file(file_name="game.chd", file_size_bytes=30)
|
||||
|
||||
assert await get_or_convert(1, f, "psp", "iso") is None
|
||||
assert convert_outputs == []
|
||||
|
||||
async def test_admission_evicts_an_older_copy_to_make_room(
|
||||
self, cache_root, converto, convert_outputs, mocker
|
||||
):
|
||||
converto.cache_max_size_gb = 1
|
||||
mocker.patch.object(conversion_cache, "BYTES_PER_GB", 100)
|
||||
older = _seed_cached(_rom_file(file_name="older.iso"))
|
||||
older.write_bytes(b"x" * 40)
|
||||
served = time.time() - 300
|
||||
os.utime(older, (served, served))
|
||||
f = _rom_file(file_size_bytes=70)
|
||||
|
||||
assert await get_or_convert(1, f, "psp", "chd") == _final_path(f)
|
||||
assert not older.parent.exists()
|
||||
assert _final_path(f).read_bytes() == b"converted"
|
||||
|
||||
async def test_admission_does_not_evict_a_recently_served_copy(
|
||||
self, cache_root, converto, convert_outputs, mocker
|
||||
):
|
||||
converto.cache_max_size_gb = 1
|
||||
mocker.patch.object(conversion_cache, "BYTES_PER_GB", 100)
|
||||
recent = _seed_cached(_rom_file(file_name="recent.iso"))
|
||||
recent.write_bytes(b"x" * 80)
|
||||
f = _rom_file(file_size_bytes=50)
|
||||
|
||||
assert await get_or_convert(1, f, "psp", "chd") is None
|
||||
assert recent.read_bytes() == b"x" * 80
|
||||
assert convert_outputs == []
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("size_bytes", "blocked"),
|
||||
[
|
||||
pytest.param(101, "none", id="larger-than-cap"),
|
||||
pytest.param(70, "grace", id="insufficient-outside-grace"),
|
||||
pytest.param(70, "exclusive", id="conversion-locked"),
|
||||
pytest.param(70, "shared", id="download-locked"),
|
||||
],
|
||||
)
|
||||
async def test_impossible_admission_preserves_other_copies(
|
||||
self, cache_root, converto, convert_outputs, mocker, size_bytes, blocked
|
||||
):
|
||||
converto.cache_max_size_gb = 1
|
||||
mocker.patch.object(conversion_cache, "BYTES_PER_GB", 100)
|
||||
older = _seed_cached(_rom_file(file_name="older.iso"))
|
||||
protected = _seed_cached(_rom_file(file_name="protected.iso"))
|
||||
older.write_bytes(b"x" * 40)
|
||||
protected.write_bytes(b"x" * 50)
|
||||
now = time.time()
|
||||
os.utime(older, (now - 300, now - 300))
|
||||
protected_age = 0 if blocked == "grace" else SERVE_GRACE_SECONDS * 2
|
||||
os.utime(protected, (now - protected_age, now - protected_age))
|
||||
holder = (
|
||||
_held_lock(protected.parent, shared=blocked == "shared")
|
||||
if blocked in ("exclusive", "shared")
|
||||
else nullcontext()
|
||||
)
|
||||
|
||||
with holder:
|
||||
assert (
|
||||
await get_or_convert(
|
||||
1, _rom_file(file_size_bytes=size_bytes), "psp", "chd"
|
||||
)
|
||||
is None
|
||||
)
|
||||
|
||||
assert older.read_bytes() == b"x" * 40
|
||||
assert protected.read_bytes() == b"x" * 50
|
||||
assert convert_outputs == []
|
||||
|
||||
async def test_conversion_evicts_the_least_recently_served_other_copy(
|
||||
self, cache_root, converto, mocker
|
||||
):
|
||||
converto.cache_max_size_gb = 1
|
||||
mocker.patch.object(conversion_cache, "BYTES_PER_GB", 100)
|
||||
oldest = _seed_cached(_rom_file(file_name="old.iso"), age_seconds=300)
|
||||
newer = _seed_cached(_rom_file(file_name="newer.iso"), age_seconds=200)
|
||||
oldest.write_bytes(b"x" * 40)
|
||||
newer.write_bytes(b"x" * 40)
|
||||
now = time.time()
|
||||
os.utime(oldest, (now - 300, now - 300))
|
||||
os.utime(newer, (now - 200, now - 200))
|
||||
f = _rom_file(file_size_bytes=10)
|
||||
|
||||
async def convert(op, src, out) -> None:
|
||||
out.write_bytes(b"converted" * 6)
|
||||
|
||||
mocker.patch(
|
||||
"utils.conversion_cache.rom_converto_service.convert", side_effect=convert
|
||||
)
|
||||
|
||||
final = await get_or_convert(1, f, "psp", "chd")
|
||||
|
||||
assert final == _final_path(f)
|
||||
assert final is not None
|
||||
assert final.read_bytes() == b"converted" * 6
|
||||
assert not oldest.parent.exists()
|
||||
assert newer.exists()
|
||||
assert conversion_cache.cache_size_bytes() <= 100
|
||||
|
||||
async def test_post_conversion_cleanup_failure_still_serves_the_copy(
|
||||
self, cache_root, convert_outputs, mocker
|
||||
):
|
||||
f = _rom_file()
|
||||
final = _final_path(f)
|
||||
cleanup = conversion_cache.cleanup_stale_conversions
|
||||
|
||||
def fail_after_publication(*args, **kwargs):
|
||||
if final.exists():
|
||||
raise RuntimeError("cleanup failed")
|
||||
return cleanup(*args, **kwargs)
|
||||
|
||||
mocker.patch.object(
|
||||
conversion_cache,
|
||||
"cleanup_stale_conversions",
|
||||
side_effect=fail_after_publication,
|
||||
)
|
||||
|
||||
assert await get_or_convert(1, f, "psp", "chd") == final
|
||||
assert final.read_bytes() == b"converted"
|
||||
|
||||
async def test_locked_key_dir_returns_none(self, cache_root, convert_outputs):
|
||||
f = _rom_file()
|
||||
key_dir = _final_path(f).parent
|
||||
key_dir.mkdir(parents=True)
|
||||
|
||||
with _held_lock(key_dir):
|
||||
assert await get_or_convert(1, f, "psp", "chd") is None
|
||||
assert convert_outputs == []
|
||||
|
||||
async def test_concurrent_request_returns_none_while_one_converts(
|
||||
self, cache_root, mocker
|
||||
):
|
||||
f = _rom_file()
|
||||
started = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
|
||||
async def convert(op, src, out) -> None:
|
||||
started.set()
|
||||
await release.wait()
|
||||
out.write_bytes(b"converted")
|
||||
|
||||
mocker.patch(
|
||||
"utils.conversion_cache.rom_converto_service.convert", side_effect=convert
|
||||
)
|
||||
|
||||
first = asyncio.create_task(get_or_convert(1, f, "psp", "chd"))
|
||||
await started.wait()
|
||||
assert await get_or_convert(1, f, "psp", "chd") is None
|
||||
release.set()
|
||||
assert await first == _final_path(f)
|
||||
|
||||
async def test_queued_conversion_checks_budget_after_a_slot_opens(
|
||||
self, cache_root, converto, mocker
|
||||
):
|
||||
converto.cache_max_size_gb = 1
|
||||
mocker.patch.object(conversion_cache, "BYTES_PER_GB", 100)
|
||||
mocker.patch.object(
|
||||
conversion_cache, "_convert_semaphore", asyncio.Semaphore(1)
|
||||
)
|
||||
first_file = _rom_file(file_size_bytes=10)
|
||||
second_file = _rom_file(file_name="second.iso", file_size_bytes=10)
|
||||
second_dir = _final_path(second_file).parent
|
||||
started = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
|
||||
async def convert(op, src, out) -> None:
|
||||
started.set()
|
||||
await release.wait()
|
||||
out.write_bytes(b"x" * 100)
|
||||
|
||||
mocker.patch(
|
||||
"utils.conversion_cache.rom_converto_service.convert", side_effect=convert
|
||||
)
|
||||
|
||||
first = asyncio.create_task(get_or_convert(1, first_file, "psp", "chd"))
|
||||
await started.wait()
|
||||
second = asyncio.create_task(get_or_convert(1, second_file, "psp", "chd"))
|
||||
try:
|
||||
while not second.done():
|
||||
if second_dir.exists():
|
||||
with conversion_cache._try_lock(second_dir) as locked:
|
||||
if not locked:
|
||||
break
|
||||
await asyncio.sleep(0)
|
||||
queued = not second.done()
|
||||
finally:
|
||||
release.set()
|
||||
results = await asyncio.gather(first, second)
|
||||
|
||||
assert queued
|
||||
assert list(results) == [_final_path(first_file), None]
|
||||
assert _final_path(first_file).read_bytes() == b"x" * 100
|
||||
assert not _final_path(second_file).exists()
|
||||
|
||||
async def test_writes_in_partial_dir_then_renames_into_place(
|
||||
self, cache_root, convert_outputs
|
||||
):
|
||||
f = _rom_file()
|
||||
final = _final_path(f)
|
||||
|
||||
assert await get_or_convert(1, f, "psp", "chd") == final
|
||||
assert convert_outputs == [_partial_path(final)]
|
||||
assert final.read_bytes() == b"converted"
|
||||
assert [p.name for p in final.parent.iterdir()] == [final.name]
|
||||
|
||||
async def test_leading_dot_copy_survives_cleanup(self, cache_root, convert_outputs):
|
||||
f = _rom_file(file_name=".hack - Infection (USA).iso")
|
||||
final = _final_path(f)
|
||||
|
||||
assert await get_or_convert(1, f, "psp", "chd") == final
|
||||
assert final.name == ".hack - Infection (USA).chd"
|
||||
assert conversion_cache.cleanup_stale_conversions() == 0
|
||||
assert final.read_bytes() == b"converted"
|
||||
assert get_cached_converted(1, f, "psp", "chd") == final
|
||||
|
||||
async def test_removes_all_a_crashed_runs_partial_outputs(
|
||||
self, cache_root, convert_outputs
|
||||
):
|
||||
f = _rom_file()
|
||||
final = _final_path(f)
|
||||
final.parent.mkdir(parents=True)
|
||||
partial = _partial_path(final)
|
||||
partial.parent.mkdir()
|
||||
for path in (
|
||||
partial,
|
||||
partial.with_name(f".{partial.name}.ABCDEF.tmp"),
|
||||
partial.with_suffix(".bin"),
|
||||
):
|
||||
path.write_bytes(b"leftover")
|
||||
|
||||
assert await get_or_convert(1, f, "psp", "chd") == final
|
||||
assert final.read_bytes() == b"converted"
|
||||
assert list(final.parent.iterdir()) == [final]
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("error", "writes_partial"),
|
||||
[
|
||||
pytest.param(RomConvertoOperationError, False, id="nonzero-exit-no-output"),
|
||||
pytest.param(RomConvertoOperationError, True, id="nonzero-exit-partials"),
|
||||
pytest.param(RomConvertoTimeoutError, True, id="timeout-partials"),
|
||||
],
|
||||
)
|
||||
async def test_failed_conversion_retries_only_after_marker_expires(
|
||||
self, cache_root, converto, mocker, error, writes_partial
|
||||
):
|
||||
f = _rom_file()
|
||||
final = _final_path(f)
|
||||
marker = final.parent / FAILED_FILE
|
||||
|
||||
async def convert(op, src, out) -> None:
|
||||
if writes_partial:
|
||||
out.write_bytes(b"partial")
|
||||
out.with_name(f".{out.name}.ABCDEF.tmp").write_bytes(b"scratch")
|
||||
out.with_suffix(".bin").write_bytes(b"data")
|
||||
raise error("boom")
|
||||
|
||||
convert_mock = mocker.patch(
|
||||
"utils.conversion_cache.rom_converto_service.convert", side_effect=convert
|
||||
)
|
||||
|
||||
assert await get_or_convert(1, f, "psp", "chd") is None
|
||||
assert list(final.parent.iterdir()) == [marker]
|
||||
assert await get_or_convert(1, f, "psp", "chd") is None
|
||||
convert_mock.assert_awaited_once()
|
||||
expired = time.time() - converto.cache_ttl_hours * 3600 - 1
|
||||
os.utime(marker, (expired, expired))
|
||||
assert conversion_cache.cleanup_stale_conversions() == 1
|
||||
|
||||
async def succeed(op, src, out) -> None:
|
||||
out.write_bytes(b"converted")
|
||||
|
||||
convert_mock.side_effect = succeed
|
||||
assert await get_or_convert(1, f, "psp", "chd") == final
|
||||
assert final.read_bytes() == b"converted"
|
||||
assert not marker.exists()
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"stage",
|
||||
[
|
||||
pytest.param("mkdir", id="partial-dir-error"),
|
||||
pytest.param("replace", id="publication-error"),
|
||||
pytest.param("convert-os-error", id="subprocess-os-error"),
|
||||
pytest.param("missing-binary", id="binary-not-found"),
|
||||
],
|
||||
)
|
||||
async def test_transient_failure_retries_the_next_download(
|
||||
self, cache_root, mocker, stage
|
||||
):
|
||||
f = _rom_file()
|
||||
final = _final_path(f)
|
||||
failed = False
|
||||
|
||||
async def convert(op, src, out) -> None:
|
||||
nonlocal failed
|
||||
if not failed and stage in ("convert-os-error", "missing-binary"):
|
||||
failed = True
|
||||
error = (
|
||||
RomConvertoBinaryNotFoundError
|
||||
if stage == "missing-binary"
|
||||
else OSError
|
||||
)
|
||||
raise error("temporary failure")
|
||||
out.write_bytes(b"converted")
|
||||
|
||||
mocker.patch(
|
||||
"utils.conversion_cache.rom_converto_service.convert", side_effect=convert
|
||||
)
|
||||
if stage in ("mkdir", "replace"):
|
||||
write = Path.mkdir if stage == "mkdir" else os.replace
|
||||
|
||||
def fail_write_once(*args, **kwargs):
|
||||
nonlocal failed
|
||||
if not failed and (stage == "replace" or args[0].name == PARTIAL_DIR):
|
||||
failed = True
|
||||
raise OSError("temporary filesystem failure")
|
||||
return write(*args, **kwargs)
|
||||
|
||||
mocker.patch(
|
||||
"pathlib.Path.mkdir" if stage == "mkdir" else "os.replace",
|
||||
side_effect=fail_write_once,
|
||||
autospec=True,
|
||||
)
|
||||
|
||||
assert await get_or_convert(1, f, "psp", "chd") is None
|
||||
assert not (final.parent / FAILED_FILE).exists()
|
||||
assert not (final.parent / PARTIAL_DIR).exists()
|
||||
assert await get_or_convert(1, f, "psp", "chd") == final
|
||||
assert final.read_bytes() == b"converted"
|
||||
|
||||
async def test_cancellation_removes_every_partial_output(self, cache_root, mocker):
|
||||
f = _rom_file()
|
||||
final = _final_path(f)
|
||||
started = asyncio.Event()
|
||||
|
||||
async def convert(op, src, out) -> None:
|
||||
out.write_bytes(b"partial")
|
||||
out.with_name(f".{out.name}.ABCDEF.tmp").write_bytes(b"scratch")
|
||||
out.with_suffix(".bin").write_bytes(b"data")
|
||||
started.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
mocker.patch(
|
||||
"utils.conversion_cache.rom_converto_service.convert", side_effect=convert
|
||||
)
|
||||
|
||||
conversion = asyncio.create_task(get_or_convert(1, f, "psp", "chd"))
|
||||
await started.wait()
|
||||
conversion.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await conversion
|
||||
|
||||
assert not final.exists()
|
||||
assert list(final.parent.iterdir()) == []
|
||||
|
||||
|
||||
class TestGetCachedConverted:
|
||||
@pytest.mark.parametrize("file_name", ["game.zip", "game.iso"])
|
||||
def test_returns_none_when_unresolvable_or_not_cached(self, cache_root, file_name):
|
||||
f = _rom_file(file_name=file_name)
|
||||
|
||||
assert get_cached_converted(1, f, "psp", "chd") is None
|
||||
|
||||
@pytest.mark.parametrize("touch", [False, True])
|
||||
def test_returns_the_copy_refreshing_mtime_only_when_asked(self, cache_root, touch):
|
||||
f = _rom_file()
|
||||
final = _seed_cached(f, age_seconds=3600)
|
||||
|
||||
assert get_cached_converted(1, f, "psp", "chd", touch=touch) == final
|
||||
assert (final.stat().st_mtime > time.time() - 60) is touch
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"touch",
|
||||
[
|
||||
pytest.param(False, id="lookup"),
|
||||
pytest.param(True, id="download"),
|
||||
],
|
||||
)
|
||||
def test_returns_none_while_key_dir_is_locked(self, cache_root, touch):
|
||||
f = _rom_file()
|
||||
final = _seed_cached(f)
|
||||
|
||||
with _held_lock(final.parent):
|
||||
assert get_cached_converted(1, f, "psp", "chd", touch=touch) is None
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error",
|
||||
[
|
||||
pytest.param(FileNotFoundError, id="touch-not-found"),
|
||||
pytest.param(PermissionError, id="permission-denied"),
|
||||
],
|
||||
)
|
||||
def test_touch_failure_still_serves_the_copy(self, cache_root, mocker, error):
|
||||
f = _rom_file()
|
||||
final = _seed_cached(f)
|
||||
mocker.patch("os.utime", side_effect=error)
|
||||
|
||||
assert get_cached_converted(1, f, "psp", "chd", touch=True) == final
|
||||
assert final.read_bytes() == b"cached"
|
||||
|
||||
def test_lock_open_failure_returns_none(self, cache_root, mocker):
|
||||
f = _rom_file()
|
||||
_seed_cached(f)
|
||||
mocker.patch("os.open", side_effect=PermissionError)
|
||||
|
||||
assert get_cached_converted(1, f, "psp", "chd") is None
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"recreate",
|
||||
[
|
||||
pytest.param(False, id="removed"),
|
||||
pytest.param(True, id="recreated"),
|
||||
],
|
||||
)
|
||||
def test_does_not_serve_a_replaced_key_dir(self, cache_root, mocker, recreate):
|
||||
f = _rom_file()
|
||||
final = _seed_cached(f)
|
||||
flock = fcntl.flock
|
||||
|
||||
def replace_dir(fd, mode):
|
||||
flock(fd, mode)
|
||||
shutil.rmtree(final.parent)
|
||||
if recreate:
|
||||
final.parent.mkdir()
|
||||
final.write_bytes(b"replacement")
|
||||
|
||||
mocker.patch("fcntl.flock", side_effect=replace_dir)
|
||||
|
||||
assert get_cached_converted(1, f, "psp", "chd") is None
|
||||
|
||||
|
||||
class TestHasRoomFor:
|
||||
def test_unbounded_when_cap_is_zero(self, cache_root, converto):
|
||||
converto.cache_max_size_gb = 0
|
||||
|
||||
assert conversion_cache.has_room_for(10 * conversion_cache.BYTES_PER_GB)
|
||||
|
||||
def test_counts_partial_output_against_the_cap(self, cache_root, converto, mocker):
|
||||
converto.cache_max_size_gb = 1
|
||||
mocker.patch.object(conversion_cache, "BYTES_PER_GB", 100)
|
||||
key_dir = cache_root / "1-a"
|
||||
key_dir.mkdir()
|
||||
(key_dir / "game.chd").write_bytes(b"x" * 40)
|
||||
partial_dir = key_dir / PARTIAL_DIR
|
||||
partial_dir.mkdir()
|
||||
(partial_dir / "other.chd").write_bytes(b"x" * 20)
|
||||
|
||||
assert conversion_cache.has_room_for(40)
|
||||
assert not conversion_cache.has_room_for(41)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"vanishes",
|
||||
[
|
||||
pytest.param("file", id="vanishing-file"),
|
||||
pytest.param("dir", id="vanishing-dir"),
|
||||
],
|
||||
)
|
||||
def test_size_walk_tolerates_vanishing_entries(self, cache_root, mocker, vanishes):
|
||||
vanished = _seed_cached(_rom_file(file_name="vanished.iso"))
|
||||
survivor = _seed_cached(_rom_file(file_name="survivor.iso"))
|
||||
stat = os.stat
|
||||
scandir = os.scandir
|
||||
|
||||
if vanishes == "file":
|
||||
|
||||
def stat_after_removal(path, *args, **kwargs):
|
||||
if path == str(vanished):
|
||||
vanished.unlink(missing_ok=True)
|
||||
return stat(path, *args, **kwargs)
|
||||
|
||||
mocker.patch("os.stat", side_effect=stat_after_removal)
|
||||
else:
|
||||
|
||||
def scan_after_removal(path):
|
||||
if path == str(vanished.parent):
|
||||
shutil.rmtree(vanished.parent)
|
||||
return scandir(path)
|
||||
|
||||
mocker.patch("os.scandir", side_effect=scan_after_removal)
|
||||
|
||||
assert conversion_cache.cache_size_bytes() == len(b"cached")
|
||||
assert survivor.read_bytes() == b"cached"
|
||||
|
||||
|
||||
class TestGetRedirectPath:
|
||||
def test_relative_to_romm_base_path(self):
|
||||
converted_path = Path(ROMM_BASE_PATH) / "cache/converts/1-abc/Game.chd"
|
||||
assert get_redirect_path(converted_path) == Path(
|
||||
"/cache/converts/1-abc/Game.chd"
|
||||
)
|
||||
|
||||
|
||||
class TestCleanupStaleConversions:
|
||||
def test_missing_root_is_noop(self, tmp_path, mocker):
|
||||
mocker.patch.object(
|
||||
conversion_cache, "ROM_CONVERTO_CACHE_PATH", str(tmp_path / "nope")
|
||||
)
|
||||
assert conversion_cache.cleanup_stale_conversions() == 0
|
||||
|
||||
def test_deletes_expired_and_keeps_fresh(self, cache_root):
|
||||
expired = _seed_cached(_rom_file(file_name="old.iso"), age_seconds=25 * 3600)
|
||||
fresh = _seed_cached(_rom_file(file_name="new.iso"))
|
||||
|
||||
assert conversion_cache.cleanup_stale_conversions() == 1
|
||||
assert not expired.parent.exists()
|
||||
assert fresh.exists()
|
||||
|
||||
def test_removes_partial_outputs_from_a_kept_dir(self, cache_root):
|
||||
final = _seed_cached(_rom_file())
|
||||
partial = _partial_path(final)
|
||||
partial.parent.mkdir()
|
||||
for path in (
|
||||
partial,
|
||||
partial.with_name(f".{partial.name}.ABCDEF.tmp"),
|
||||
partial.with_suffix(".bin"),
|
||||
):
|
||||
path.write_bytes(b"leftover")
|
||||
|
||||
assert conversion_cache.cleanup_stale_conversions() == 0
|
||||
assert final.read_bytes() == b"cached"
|
||||
assert list(final.parent.iterdir()) == [final]
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"leftover",
|
||||
[
|
||||
pytest.param(False, id="empty"),
|
||||
pytest.param(True, id="partial"),
|
||||
],
|
||||
)
|
||||
def test_deletes_dirs_without_a_served_copy(self, cache_root, leftover):
|
||||
key_dir = cache_root / "1-e"
|
||||
key_dir.mkdir()
|
||||
if leftover:
|
||||
partial_dir = key_dir / PARTIAL_DIR
|
||||
partial_dir.mkdir()
|
||||
(partial_dir / "game.chd").write_bytes(b"partial")
|
||||
|
||||
assert conversion_cache.cleanup_stale_conversions() == 1
|
||||
assert not key_dir.exists()
|
||||
|
||||
def test_skips_a_dir_whose_conversion_is_running(self, cache_root):
|
||||
key_dir = cache_root / "1-busy"
|
||||
key_dir.mkdir()
|
||||
partial_dir = key_dir / PARTIAL_DIR
|
||||
partial_dir.mkdir()
|
||||
(partial_dir / "game.chd").write_bytes(b"partial")
|
||||
|
||||
with _held_lock(key_dir):
|
||||
assert conversion_cache.cleanup_stale_conversions() == 0
|
||||
assert key_dir.exists()
|
||||
|
||||
def test_kept_copy_remains_available_during_cleanup(self, cache_root, mocker):
|
||||
f = _rom_file()
|
||||
final = _seed_cached(f)
|
||||
files = conversion_cache._files
|
||||
|
||||
def serve_during_listing(key_dir):
|
||||
listed = files(key_dir)
|
||||
assert get_cached_converted(1, f, "psp", "chd") == final
|
||||
return listed
|
||||
|
||||
mocker.patch.object(
|
||||
conversion_cache, "_files", side_effect=serve_during_listing
|
||||
)
|
||||
|
||||
assert conversion_cache.cleanup_stale_conversions() == 0
|
||||
assert final.read_bytes() == b"cached"
|
||||
|
||||
def test_evicts_least_recently_served_over_the_cap(
|
||||
self, cache_root, converto, mocker
|
||||
):
|
||||
converto.cache_max_size_gb = 1
|
||||
mocker.patch.object(conversion_cache, "BYTES_PER_GB", 100)
|
||||
dirs = {}
|
||||
for name, age in (("old", 300), ("mid", 200), ("new", 100)):
|
||||
final = _seed_cached(_rom_file(file_name=f"{name}.iso"))
|
||||
final.write_bytes(b"x" * 40)
|
||||
os.utime(final, (time.time() - age, time.time() - age))
|
||||
dirs[name] = final.parent
|
||||
|
||||
assert conversion_cache.cleanup_stale_conversions() == 1
|
||||
assert not dirs["old"].exists()
|
||||
assert dirs["mid"].exists()
|
||||
assert dirs["new"].exists()
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"reserve_bytes",
|
||||
[
|
||||
pytest.param(0, id="post-conversion"),
|
||||
pytest.param(70, id="admission"),
|
||||
],
|
||||
)
|
||||
def test_size_eviction_preserves_failure_markers(
|
||||
self, cache_root, converto, mocker, reserve_bytes
|
||||
):
|
||||
converto.cache_max_size_gb = 1
|
||||
mocker.patch.object(conversion_cache, "BYTES_PER_GB", 100)
|
||||
marker_dir = cache_root / "1-failed"
|
||||
marker_dir.mkdir()
|
||||
marker = marker_dir / FAILED_FILE
|
||||
marker.touch()
|
||||
served = time.time() - 3600
|
||||
os.utime(marker, (served, served))
|
||||
recent = _seed_cached(_rom_file())
|
||||
recent.write_bytes(b"x" * 120)
|
||||
|
||||
assert conversion_cache.cleanup_stale_conversions(reserve_bytes) == 0
|
||||
assert marker.exists()
|
||||
assert recent.read_bytes() == b"x" * 120
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("age_seconds", "kept"),
|
||||
[
|
||||
pytest.param(SERVE_GRACE_SECONDS // 2, True, id="within-grace"),
|
||||
pytest.param(SERVE_GRACE_SECONDS * 2, False, id="after-grace"),
|
||||
],
|
||||
)
|
||||
def test_size_eviction_respects_serve_grace(
|
||||
self, cache_root, converto, mocker, age_seconds, kept
|
||||
):
|
||||
converto.cache_max_size_gb = 1
|
||||
mocker.patch.object(conversion_cache, "BYTES_PER_GB", 100)
|
||||
final = _seed_cached(_rom_file())
|
||||
final.write_bytes(b"x" * 120)
|
||||
served = time.time() - age_seconds
|
||||
os.utime(final, (served, served))
|
||||
|
||||
assert conversion_cache.cleanup_stale_conversions() == (0 if kept else 1)
|
||||
assert final.exists() is kept
|
||||
|
||||
def test_size_eviction_rechecks_a_copy_served_after_the_ttl_pass(
|
||||
self, cache_root, converto, mocker
|
||||
):
|
||||
converto.cache_max_size_gb = 1
|
||||
mocker.patch.object(conversion_cache, "BYTES_PER_GB", 100)
|
||||
f = _rom_file()
|
||||
final = _seed_cached(f)
|
||||
final.write_bytes(b"x" * 120)
|
||||
served = time.time() - 120
|
||||
os.utime(final, (served, served))
|
||||
iterdir = Path.iterdir
|
||||
|
||||
def serve_after_listing(path):
|
||||
yield from iterdir(path)
|
||||
if path == cache_root:
|
||||
assert get_cached_converted(1, f, "psp", "chd", touch=True) == final
|
||||
|
||||
mocker.patch.object(
|
||||
Path, "iterdir", side_effect=serve_after_listing, autospec=True
|
||||
)
|
||||
|
||||
assert conversion_cache.cleanup_stale_conversions() == 0
|
||||
assert final.read_bytes() == b"x" * 120
|
||||
|
||||
|
||||
class TestParseFormats:
|
||||
@pytest.mark.parametrize(
|
||||
("raw", "expected"),
|
||||
[
|
||||
pytest.param("zso,iso", ("zso", "iso"), id="in-order"),
|
||||
pytest.param(" ZSO , iso,zso ", ("zso", "iso"), id="trimmed-deduplicated"),
|
||||
pytest.param(",,", (), id="empty"),
|
||||
pytest.param("3ds,GCM", ("cci", "iso"), id="aliases"),
|
||||
],
|
||||
)
|
||||
def test_parses_the_list(self, raw: str, expected: tuple[str, ...]):
|
||||
assert parse_formats(raw) == expected
|
||||
|
||||
|
||||
class TestResolveFormatDownload:
|
||||
@pytest.fixture(autouse=True)
|
||||
def enabled(self, converto, mocker):
|
||||
converto.download_conversion_enabled = True
|
||||
mocker.patch(
|
||||
"utils.conversion_cache.rom_converto_service.is_enabled",
|
||||
AsyncMock(return_value=True),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _rom() -> Rom:
|
||||
return cast(Rom, SimpleNamespace(id=1, platform_slug="psp"))
|
||||
|
||||
async def test_a_listed_stored_format_wins_over_a_cached_copy(self, cache_root):
|
||||
f = _rom_file()
|
||||
_seed_cached(f)
|
||||
|
||||
resolution = await resolve_format_download(
|
||||
self._rom(), f, ("chd", "iso"), allowed=True, start=True, touch=True
|
||||
)
|
||||
|
||||
assert resolution == FormatResolution(FormatOutcome.ORIGINAL)
|
||||
|
||||
async def test_an_aliased_files_own_extension_serves_the_original(
|
||||
self, cache_root, convert_outputs
|
||||
):
|
||||
rom = cast(Rom, SimpleNamespace(id=1, platform_slug="3ds"))
|
||||
|
||||
resolution = await resolve_format_download(
|
||||
rom,
|
||||
_rom_file(file_name="game.3ds"),
|
||||
parse_formats("3ds,cia"),
|
||||
allowed=True,
|
||||
start=True,
|
||||
touch=True,
|
||||
)
|
||||
|
||||
assert resolution == FormatResolution(FormatOutcome.ORIGINAL)
|
||||
assert convert_outputs == []
|
||||
|
||||
async def test_a_cached_copy_wins_over_an_earlier_uncached_format(
|
||||
self, cache_root, convert_outputs
|
||||
):
|
||||
f = _rom_file()
|
||||
final = _seed_cached(f)
|
||||
|
||||
resolution = await resolve_format_download(
|
||||
self._rom(), f, ("cso", "chd"), allowed=True, start=True, touch=True
|
||||
)
|
||||
|
||||
assert resolution == FormatResolution(FormatOutcome.CONVERTED, final)
|
||||
assert convert_outputs == []
|
||||
|
||||
async def test_converts_to_the_first_listed_format_it_can_produce(
|
||||
self, cache_root, convert_outputs
|
||||
):
|
||||
f = _rom_file()
|
||||
|
||||
resolution = await resolve_format_download(
|
||||
self._rom(), f, ("rvz", "cso", "chd"), allowed=True, start=True, touch=True
|
||||
)
|
||||
|
||||
assert resolution.outcome == FormatOutcome.CONVERTED
|
||||
assert resolution.path is not None and resolution.path.suffix == ".cso"
|
||||
assert [out.suffix for out in convert_outputs] == [".cso"]
|
||||
|
||||
async def test_skips_a_format_whose_conversion_failed(
|
||||
self, cache_root, convert_outputs
|
||||
):
|
||||
f = _rom_file()
|
||||
failed = _final_path(f).parent
|
||||
failed.mkdir(parents=True)
|
||||
(failed / FAILED_FILE).touch()
|
||||
|
||||
resolution = await resolve_format_download(
|
||||
self._rom(), f, ("chd", "cso"), allowed=True, start=True, touch=True
|
||||
)
|
||||
|
||||
assert resolution.path is not None and resolution.path.suffix == ".cso"
|
||||
|
||||
async def test_reports_pending_without_starting(self, cache_root, convert_outputs):
|
||||
resolution = await resolve_format_download(
|
||||
self._rom(), _rom_file(), ("chd",), allowed=True, start=False, touch=False
|
||||
)
|
||||
|
||||
assert resolution.outcome == FormatOutcome.PENDING
|
||||
assert convert_outputs == []
|
||||
|
||||
async def test_falls_back_to_a_later_format_when_a_conversion_fails(
|
||||
self, cache_root, mocker
|
||||
):
|
||||
async def convert(operation, src, out) -> None:
|
||||
if out.suffix == ".cso":
|
||||
raise RomConvertoOperationError("bad image")
|
||||
out.write_bytes(b"converted")
|
||||
|
||||
mocker.patch(
|
||||
"utils.conversion_cache.rom_converto_service.convert", side_effect=convert
|
||||
)
|
||||
|
||||
resolution = await resolve_format_download(
|
||||
self._rom(),
|
||||
_rom_file(),
|
||||
("cso", "chd"),
|
||||
allowed=True,
|
||||
start=True,
|
||||
touch=True,
|
||||
)
|
||||
|
||||
assert resolution.path is not None and resolution.path.suffix == ".chd"
|
||||
|
||||
async def test_a_locked_key_dir_without_partial_output_is_pending(
|
||||
self, cache_root, convert_outputs
|
||||
):
|
||||
key_dir = _final_path(_rom_file()).parent
|
||||
key_dir.mkdir(parents=True)
|
||||
|
||||
with _held_lock(key_dir):
|
||||
resolution = await resolve_format_download(
|
||||
self._rom(), _rom_file(), ("chd",), allowed=True, start=True, touch=True
|
||||
)
|
||||
|
||||
assert resolution.outcome == FormatOutcome.PENDING
|
||||
assert convert_outputs == []
|
||||
|
||||
async def test_a_finished_conversion_is_served_while_a_download_holds_its_dir(
|
||||
self, cache_root, mocker
|
||||
):
|
||||
f = _rom_file()
|
||||
final = _final_path(f)
|
||||
|
||||
async def convert(operation, src, out) -> None:
|
||||
out.write_bytes(b"converted")
|
||||
|
||||
async def convert_then_serve(*args) -> Path | None:
|
||||
converted = await get_or_convert(*args)
|
||||
stack.enter_context(_held_lock(final.parent, shared=True))
|
||||
return converted
|
||||
|
||||
mocker.patch(
|
||||
"utils.conversion_cache.rom_converto_service.convert", side_effect=convert
|
||||
)
|
||||
mocker.patch.object(
|
||||
conversion_cache, "get_or_convert", side_effect=convert_then_serve
|
||||
)
|
||||
with ExitStack() as stack:
|
||||
resolution = await resolve_format_download(
|
||||
self._rom(), f, ("chd",), allowed=True, start=True, touch=True
|
||||
)
|
||||
|
||||
assert resolution == FormatResolution(FormatOutcome.CONVERTED, final)
|
||||
|
||||
async def test_is_pending_without_starting_once_too_many_conversions_run(
|
||||
self, cache_root, convert_outputs, mocker
|
||||
):
|
||||
mocker.patch.object(conversion_cache, "MAX_STARTED_CONVERSIONS", 0)
|
||||
|
||||
resolution = await resolve_format_download(
|
||||
self._rom(), _rom_file(), ("chd",), allowed=True, start=True, touch=True
|
||||
)
|
||||
|
||||
assert resolution.outcome == FormatOutcome.PENDING
|
||||
assert convert_outputs == []
|
||||
@@ -55,7 +55,7 @@ def _engine_connecting(conn: MagicMock) -> MagicMock:
|
||||
@pytest.mark.skipif(not IS_FULLTEXT_ENGINE, reason="InnoDB full-text only")
|
||||
def test_reads_the_servers_settings():
|
||||
with sync_engine.connect() as conn:
|
||||
min_token_size = conn.execute(
|
||||
min_token_size: int = conn.execute(
|
||||
text("SELECT @@innodb_ft_min_token_size")
|
||||
).scalar_one()
|
||||
settings = read_fulltext_settings(conn)
|
||||
|
||||
@@ -71,7 +71,8 @@ def load_igdb_ids(limit: int | None) -> dict[int, list[int]]:
|
||||
grouped: dict[int, list[int]] = {}
|
||||
with sync_session.begin() as session:
|
||||
for igdb_id, rom_id in session.execute(stmt).all():
|
||||
grouped.setdefault(igdb_id, []).append(rom_id)
|
||||
if igdb_id is not None:
|
||||
grouped.setdefault(igdb_id, []).append(rom_id)
|
||||
|
||||
return grouped
|
||||
|
||||
|
||||
415
backend/utils/conversion_cache.py
Normal file
415
backend/utils/conversion_cache.py
Normal file
@@ -0,0 +1,415 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import enum
|
||||
import fcntl
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
from collections.abc import Generator, Sequence
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Final
|
||||
|
||||
from adapters.services.rom_converto import (
|
||||
UNCOMPRESSED_TARGETS,
|
||||
Operation,
|
||||
RomConvertoOperationError,
|
||||
RomConvertoTimeoutError,
|
||||
canonical_format,
|
||||
file_format,
|
||||
resolve_operation,
|
||||
rom_converto_service,
|
||||
)
|
||||
from config import (
|
||||
LIBRARY_BASE_PATH,
|
||||
ROM_CONVERTO_CACHE_PATH,
|
||||
ROM_CONVERTO_MAX_CONCURRENCY,
|
||||
ROMM_BASE_PATH,
|
||||
)
|
||||
from config.config_manager import config_manager as cm
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from utils.background_tasks import fire_and_forget
|
||||
from utils.zip_cache import CACHE_KEY_LENGTH, SECONDS_PER_HOUR
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from models.rom import Rom, RomFile
|
||||
|
||||
BYTES_PER_GB = 1024**3
|
||||
# How long a download waits on a conversion it started before answering 202.
|
||||
CONVERSION_WAIT_SECONDS: Final = 15
|
||||
RETRY_AFTER_SECONDS: Final = 30
|
||||
PARTIAL_DIR: Final = ".partial"
|
||||
FAILED_FILE: Final = ".failed"
|
||||
# Give nginx time to open a copy after the X-Accel-Redirect response.
|
||||
SERVE_GRACE_SECONDS: Final = 60
|
||||
# Room a conversion to an uncompressed target reserves per input byte; the
|
||||
# cleanup pass after it evicts any overshoot.
|
||||
EXPANSION_RESERVE_FACTOR: Final = 4
|
||||
# Downloads may start conversions until this many wait for or hold the semaphore.
|
||||
MAX_STARTED_CONVERSIONS: Final = ROM_CONVERTO_MAX_CONCURRENCY * 4
|
||||
|
||||
# Each conversion reads and writes whole disc images.
|
||||
_convert_semaphore = asyncio.Semaphore(ROM_CONVERTO_MAX_CONCURRENCY)
|
||||
_started_conversions: set[asyncio.Task[Path | None]] = set()
|
||||
|
||||
|
||||
def converted_file_path(
|
||||
rom_id: int, rom_file: RomFile, operation: Operation, input_ext: str
|
||||
) -> Path:
|
||||
"""Deterministic cache path for a converted ROM file."""
|
||||
key = hashlib.sha1(
|
||||
f"{rom_file.file_path}/{rom_file.file_name}|{rom_file.last_modified}|{rom_file.file_size_bytes}|{operation.target}".encode(),
|
||||
usedforsecurity=False,
|
||||
).hexdigest()[:CACHE_KEY_LENGTH]
|
||||
key_dir = Path(ROM_CONVERTO_CACHE_PATH) / f"{rom_id}-{key}"
|
||||
return key_dir / operation.output_name(Path(rom_file.file_name), input_ext)
|
||||
|
||||
|
||||
def get_redirect_path(converted_path: Path) -> Path:
|
||||
"""The nginx-internal path for a converted file (`/cache/` aliases `${ROMM_BASE_PATH}/cache/`)."""
|
||||
return Path("/") / converted_path.relative_to(ROMM_BASE_PATH)
|
||||
|
||||
|
||||
def _dir_size(path: Path) -> int:
|
||||
total = 0
|
||||
for root, _, files in os.walk(path):
|
||||
for name in files:
|
||||
with contextlib.suppress(OSError):
|
||||
total += os.stat(os.path.join(root, name)).st_size
|
||||
return total
|
||||
|
||||
|
||||
def _files(key_dir: Path) -> list[Path]:
|
||||
return [p for p in key_dir.iterdir() if p.is_file()]
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _try_lock(key_dir: Path, *, shared: bool = False) -> Generator[bool]:
|
||||
"""Lock the key dir without blocking, yielding False if it is busy, removed or replaced."""
|
||||
fd = os.open(key_dir, os.O_RDONLY)
|
||||
try:
|
||||
try:
|
||||
mode = fcntl.LOCK_SH if shared else fcntl.LOCK_EX
|
||||
fcntl.flock(fd, mode | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
yield False
|
||||
return
|
||||
try:
|
||||
current_dir = os.path.samestat(os.fstat(fd), os.stat(key_dir))
|
||||
except FileNotFoundError:
|
||||
current_dir = False
|
||||
yield current_dir
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def _stat_files(key_dir: Path) -> tuple[dict[str, os.stat_result], float]:
|
||||
"""The stats of `key_dir`'s files and the newest mtime among them."""
|
||||
stats = {p.name: p.stat() for p in _files(key_dir)}
|
||||
return stats, max((st.st_mtime for st in stats.values()), default=0.0)
|
||||
|
||||
|
||||
def cache_size_bytes() -> int:
|
||||
"""Bytes every key dir holds on disk, partial output included."""
|
||||
return _dir_size(Path(ROM_CONVERTO_CACHE_PATH))
|
||||
|
||||
|
||||
def has_room_for(size_bytes: int) -> bool:
|
||||
"""Whether adding `size_bytes` keeps the cache under `converto.cache_max_size_gb`."""
|
||||
max_bytes = cm.get_config().CONVERTO.cache_max_size_gb * BYTES_PER_GB
|
||||
return not max_bytes or cache_size_bytes() + size_bytes <= max_bytes
|
||||
|
||||
|
||||
def _lookup(
|
||||
rom_id: int, rom_file: RomFile, platform_slug: str, target: str
|
||||
) -> tuple[Operation, Path] | None:
|
||||
"""The operation bringing `rom_file` to `target` and its cache path."""
|
||||
resolved = resolve_operation(platform_slug, target, rom_file.file_name)
|
||||
if resolved is None:
|
||||
return None
|
||||
operation, input_ext = resolved
|
||||
return operation, converted_file_path(rom_id, rom_file, operation, input_ext)
|
||||
|
||||
|
||||
def _serve_cached(final_path: Path, *, touch: bool) -> Path | None:
|
||||
"""`final_path` if it is cached, or None while cleanup or a conversion holds its dir."""
|
||||
with (
|
||||
contextlib.suppress(OSError),
|
||||
_try_lock(final_path.parent, shared=True) as locked,
|
||||
):
|
||||
if locked and final_path.exists():
|
||||
if touch:
|
||||
# Keep a served file fresh so TTL cleanup measures demand.
|
||||
with contextlib.suppress(OSError):
|
||||
os.utime(final_path)
|
||||
return final_path
|
||||
return None
|
||||
|
||||
|
||||
def get_cached_converted(
|
||||
rom_id: int,
|
||||
rom_file: RomFile,
|
||||
platform_slug: str,
|
||||
target: str,
|
||||
*,
|
||||
touch: bool = False,
|
||||
) -> Path | None:
|
||||
"""The converted file if it is already cached, without converting.
|
||||
|
||||
Args:
|
||||
touch: Refresh its mtime so TTL cleanup measures demand.
|
||||
"""
|
||||
found = _lookup(rom_id, rom_file, platform_slug, target)
|
||||
return _serve_cached(found[1], touch=touch) if found else None
|
||||
|
||||
|
||||
class FormatOutcome(enum.StrEnum):
|
||||
ORIGINAL = "original"
|
||||
CONVERTED = "converted"
|
||||
PENDING = "pending"
|
||||
UNAVAILABLE = "unavailable"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FormatResolution:
|
||||
outcome: FormatOutcome
|
||||
# The cached copy to serve when `outcome` is CONVERTED.
|
||||
path: Path | None = None
|
||||
|
||||
|
||||
_PENDING: Final = FormatResolution(FormatOutcome.PENDING)
|
||||
_UNAVAILABLE: Final = FormatResolution(FormatOutcome.UNAVAILABLE)
|
||||
|
||||
|
||||
def parse_formats(raw: str) -> tuple[str, ...]:
|
||||
"""The comma-separated `?format=` list, canonical, lowercased and deduplicated in order."""
|
||||
formats = (canonical_format(f.strip().lower()) for f in raw.split(","))
|
||||
return tuple(dict.fromkeys(f for f in formats if f))
|
||||
|
||||
|
||||
def _is_converting(final_path: Path) -> bool:
|
||||
"""Whether a worker holds `final_path`'s key dir, which it locks before converting."""
|
||||
# A shared probe leaves downloads serving a cached copy undisturbed.
|
||||
with (
|
||||
contextlib.suppress(OSError),
|
||||
_try_lock(final_path.parent, shared=True) as locked,
|
||||
):
|
||||
return not locked
|
||||
return False
|
||||
|
||||
|
||||
async def resolve_format_download(
|
||||
rom: Rom,
|
||||
file: RomFile,
|
||||
formats: Sequence[str],
|
||||
*,
|
||||
allowed: bool,
|
||||
start: bool,
|
||||
touch: bool,
|
||||
) -> FormatResolution:
|
||||
"""What a `?format=` download serves: the stored file if listed, else the first cached, then the first convertible format.
|
||||
|
||||
Args:
|
||||
allowed: The caller may start a conversion.
|
||||
start: Start it now, rather than only report that one would run.
|
||||
touch: Refresh a served copy's mtime so TTL cleanup measures demand.
|
||||
"""
|
||||
if file_format(file.file_name) in formats:
|
||||
return FormatResolution(FormatOutcome.ORIGINAL)
|
||||
|
||||
converto = cm.get_config().CONVERTO
|
||||
if (
|
||||
not converto.download_conversion_enabled
|
||||
or not await rom_converto_service.is_enabled()
|
||||
):
|
||||
return _UNAVAILABLE
|
||||
|
||||
candidates = [
|
||||
(target, found[1])
|
||||
for target in formats
|
||||
if (found := _lookup(rom.id, file, rom.platform_slug, target))
|
||||
]
|
||||
for _, final_path in candidates:
|
||||
if cached := _serve_cached(final_path, touch=touch):
|
||||
return FormatResolution(FormatOutcome.CONVERTED, cached)
|
||||
if not allowed:
|
||||
return _UNAVAILABLE
|
||||
|
||||
for target, final_path in candidates:
|
||||
if (final_path.parent / FAILED_FILE).exists():
|
||||
continue
|
||||
if (
|
||||
not start
|
||||
or _is_converting(final_path)
|
||||
or len(_started_conversions) >= MAX_STARTED_CONVERSIONS
|
||||
):
|
||||
return _PENDING
|
||||
# The conversion finishes into the cache even when this request stops waiting.
|
||||
conversion = fire_and_forget(
|
||||
get_or_convert(rom.id, file, rom.platform_slug, target)
|
||||
)
|
||||
_started_conversions.add(conversion)
|
||||
conversion.add_done_callback(_started_conversions.discard)
|
||||
done, _ = await asyncio.wait({conversion}, timeout=CONVERSION_WAIT_SECONDS)
|
||||
if done and (converted := conversion.result()):
|
||||
return FormatResolution(FormatOutcome.CONVERTED, converted)
|
||||
if not done or _is_converting(final_path):
|
||||
return _PENDING
|
||||
return _UNAVAILABLE
|
||||
|
||||
|
||||
async def get_or_convert(
|
||||
rom_id: int,
|
||||
rom_file: RomFile,
|
||||
platform_slug: str,
|
||||
target: str,
|
||||
) -> Path | None:
|
||||
"""The converted file, converting it under a lock on its key dir, or None when it can't be."""
|
||||
found = _lookup(rom_id, rom_file, platform_slug, target)
|
||||
if found is None:
|
||||
return None
|
||||
operation, final_path = found
|
||||
|
||||
try:
|
||||
if cached := _serve_cached(final_path, touch=True):
|
||||
return cached
|
||||
|
||||
final_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with _try_lock(final_path.parent) as locked:
|
||||
if not locked:
|
||||
# Another worker is converting it.
|
||||
return None
|
||||
# A conversion may have finished between the check above and the lock.
|
||||
if final_path.exists():
|
||||
with contextlib.suppress(OSError):
|
||||
os.utime(final_path)
|
||||
return final_path
|
||||
if (final_path.parent / FAILED_FILE).exists():
|
||||
return None
|
||||
async with _convert_semaphore:
|
||||
await asyncio.to_thread(
|
||||
shutil.rmtree, final_path.parent / PARTIAL_DIR, True
|
||||
)
|
||||
size_bytes = (rom_file.file_size_bytes or 0) * (
|
||||
EXPANSION_RESERVE_FACTOR
|
||||
if operation.target in UNCOMPRESSED_TARGETS
|
||||
else 1
|
||||
)
|
||||
await asyncio.to_thread(cleanup_stale_conversions, size_bytes)
|
||||
if not await asyncio.to_thread(has_room_for, size_bytes):
|
||||
log.info(
|
||||
f"Conversion cache is full, not converting ROM {rom_id} (target {hl(target)})"
|
||||
)
|
||||
return None
|
||||
converted = await _convert(
|
||||
rom_id, rom_file, target, operation, final_path
|
||||
)
|
||||
if converted:
|
||||
try:
|
||||
await asyncio.to_thread(cleanup_stale_conversions)
|
||||
except Exception as e:
|
||||
log.warning(
|
||||
f"Conversion cache cleanup failed for ROM {rom_id}: {e}; serving converted copy"
|
||||
)
|
||||
return converted
|
||||
except Exception as e:
|
||||
log.warning(
|
||||
f"Conversion cache unavailable for ROM {rom_id} (target {hl(target)}): {e}"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
async def _convert(
|
||||
rom_id: int, rom_file: RomFile, target: str, operation: Operation, final_path: Path
|
||||
) -> Path | None:
|
||||
"""Convert into a partial file and rename it into place; the caller holds the key dir lock."""
|
||||
partial_dir = final_path.parent / PARTIAL_DIR
|
||||
produced = partial_dir / final_path.name
|
||||
try:
|
||||
partial_dir.mkdir()
|
||||
await rom_converto_service.convert(
|
||||
operation, src=Path(LIBRARY_BASE_PATH) / rom_file.full_path, out=produced
|
||||
)
|
||||
os.replace(produced, final_path)
|
||||
except Exception as e:
|
||||
log.warning(f"Conversion failed for ROM {rom_id} (target {hl(target)}): {e}")
|
||||
if isinstance(e, (RomConvertoOperationError, RomConvertoTimeoutError)):
|
||||
(final_path.parent / FAILED_FILE).touch()
|
||||
return None
|
||||
finally:
|
||||
await asyncio.to_thread(shutil.rmtree, partial_dir, True)
|
||||
return final_path
|
||||
|
||||
|
||||
def cleanup_stale_conversions(reserve_bytes: int = 0) -> int:
|
||||
"""Remove expired or leaked key dirs, then evict least recently served copies to make room."""
|
||||
cache_root = Path(ROM_CONVERTO_CACHE_PATH)
|
||||
if not cache_root.exists():
|
||||
return 0
|
||||
|
||||
converto = cm.get_config().CONVERTO
|
||||
now = time.time()
|
||||
expired_before = now - converto.cache_ttl_hours * SECONDS_PER_HOUR
|
||||
deleted = 0
|
||||
# (last served, size) of the final copies in each dir that survives the TTL pass.
|
||||
kept: list[tuple[float, int, Path]] = []
|
||||
|
||||
for key_dir in cache_root.iterdir():
|
||||
if not key_dir.is_dir():
|
||||
continue
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
stats, last_served = _stat_files(key_dir)
|
||||
partial_dir = key_dir / PARTIAL_DIR
|
||||
if last_served < expired_before or partial_dir.exists():
|
||||
with _try_lock(key_dir) as locked:
|
||||
if locked:
|
||||
stats, last_served = _stat_files(key_dir)
|
||||
if last_served < expired_before:
|
||||
shutil.rmtree(key_dir, ignore_errors=True)
|
||||
deleted += 1
|
||||
continue
|
||||
shutil.rmtree(partial_dir, ignore_errors=True)
|
||||
# A failure marker frees nothing, and evicting it would retry the conversion.
|
||||
stats.pop(FAILED_FILE, None)
|
||||
if stats:
|
||||
kept.append(
|
||||
(
|
||||
max(st.st_mtime for st in stats.values()),
|
||||
sum(st.st_size for st in stats.values()),
|
||||
key_dir,
|
||||
)
|
||||
)
|
||||
|
||||
max_bytes = converto.cache_max_size_gb * BYTES_PER_GB
|
||||
if not max_bytes:
|
||||
return deleted
|
||||
used = cache_size_bytes()
|
||||
candidates = sorted(c for c in kept if c[0] < now - SERVE_GRACE_SECONDS)
|
||||
if reserve_bytes and used + reserve_bytes > max_bytes:
|
||||
evictable = 0
|
||||
for _, size, key_dir in candidates:
|
||||
# A dir a download or conversion holds right now can't be evicted.
|
||||
with contextlib.suppress(FileNotFoundError), _try_lock(key_dir) as locked:
|
||||
evictable += size if locked else 0
|
||||
if used + reserve_bytes - evictable > max_bytes:
|
||||
# Evicting every candidate would still not make room, so keep them.
|
||||
return deleted
|
||||
for _, _, key_dir in candidates:
|
||||
if used + reserve_bytes <= max_bytes:
|
||||
break
|
||||
with contextlib.suppress(FileNotFoundError), _try_lock(key_dir) as locked:
|
||||
# A download may have touched the copy since the pass above.
|
||||
if not locked or any(
|
||||
p.stat().st_mtime >= now - SERVE_GRACE_SECONDS for p in _files(key_dir)
|
||||
):
|
||||
continue
|
||||
size = _dir_size(key_dir)
|
||||
shutil.rmtree(key_dir, ignore_errors=True)
|
||||
used -= size
|
||||
deleted += 1
|
||||
|
||||
return deleted
|
||||
@@ -548,7 +548,7 @@ def drop_save_target_layout_type(conn: sa.Connection) -> None:
|
||||
|
||||
|
||||
# The stored columns in the catalog, minus `full_path_hash`.
|
||||
PLAIN_COLUMNS = [
|
||||
PLAIN_COLUMNS: list[sa.Column[Any]] = [
|
||||
sa.Column("is_physical", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column("upc", sa.String(length=64)),
|
||||
sa.Column("locked_fields", CustomJSON()),
|
||||
|
||||
@@ -100,7 +100,7 @@ def nulls_last[T](sort_key: SQLColumnExpression[T], descending: bool) -> Dialect
|
||||
)
|
||||
|
||||
|
||||
def force_index_on_mysql[S: Select[Any]](
|
||||
def force_index_on_mysql[S: Select[*tuple[Any, ...]]](
|
||||
statement: S, table: FromClause | type[Any], index_name: str
|
||||
) -> S:
|
||||
"""Make MySQL and MariaDB read `table` through `index_name`; PostgreSQL plans freely."""
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
# - sigil-build: Build sigil Python bindings (title ID extraction)
|
||||
# - gme-build: Build libgme to WebAssembly (chiptune soundtracks)
|
||||
# - gme-native-build: Build libgme for the backend, which lists chiptune songs
|
||||
# - rom-converto-fetch: Fetch the rom-converto CLI (ROM conversion and metadata)
|
||||
# - emulator-stage: Fetch and extract emulators
|
||||
# - nginx-build: Build nginx modules
|
||||
# - production-stage: Setup frontend and backend
|
||||
@@ -200,6 +201,22 @@ RUN cmake -S /libgme -B /build \
|
||||
cmake --install /build --prefix /gme-native
|
||||
|
||||
|
||||
# ROM-CONVERTO CLI
|
||||
# Keep the version and both sums in sync with the dev image's copy in ../Dockerfile.
|
||||
FROM alpine:${ALPINE_VERSION}@sha256:${ALPINE_SHA256} AS rom-converto-fetch
|
||||
ARG TARGETARCH
|
||||
ARG ROM_CONVERTO_VERSION=v0.23.0
|
||||
RUN case "${TARGETARCH}" in \
|
||||
amd64) rc="linux-x64-musl"; sum="37d03a67ad97fc02768890e763b4c80072fdfd15f2c5b97e44f9a2b50fc40876" ;; \
|
||||
arm64) rc="linux-arm64-musl"; sum="8abe37ca2d1a0e3d719fb8e795e011c672e3f1c088521cf0bb1e467dc658dc3c" ;; \
|
||||
*) echo "unsupported TARGETARCH: ${TARGETARCH}" && exit 1 ;; \
|
||||
esac && \
|
||||
wget -qO /rom-converto \
|
||||
"https://github.com/DevYukine/rom-converto/releases/download/${ROM_CONVERTO_VERSION}/rom-converto-cli-${rc}" && \
|
||||
echo "${sum} /rom-converto" | sha256sum -c - && \
|
||||
chmod 0755 /rom-converto
|
||||
|
||||
|
||||
# FETCH EMULATORJS, RUFFLE, JS-DOS AND FAKE-08
|
||||
# Keep the pins below in sync with the dev image's copies in ../Dockerfile.
|
||||
# checkov:skip=CKV_DOCKER_4:every ADD below is a remote URL pinned by --checksum
|
||||
@@ -320,6 +337,7 @@ COPY --from=rahasher-build /RALibretro/bin64/RAHasher /usr/bin/RAHasher
|
||||
COPY --from=gme-native-build /gme-native/lib/libgme.so.0 /usr/local/lib/
|
||||
# Fails the build if the library is missing one of its runtime dependencies.
|
||||
RUN python3 -c "import ctypes; ctypes.CDLL('libgme.so.0')"
|
||||
COPY --from=rom-converto-fetch /rom-converto /usr/bin/rom-converto
|
||||
COPY --from=nginx-build ./nginx/objs/ngx_http_zip_module.so /usr/lib/nginx/modules/
|
||||
COPY --from=frontend-build /front/dist ${WEBSERVER_FOLDER}
|
||||
COPY --from=backend-node-build /backend-node/rom_patcher/node_modules/rom-patcher/rom-patcher-js /backend/utils/rom_patcher/rom-patcher-js
|
||||
|
||||
@@ -32,7 +32,7 @@ Comprehensive documentation of the RomM backend: a FastAPI-based server powering
|
||||
| ------------------ | -------------------------------- |
|
||||
| **Framework** | FastAPI 0.121.1 |
|
||||
| **Language** | Python 3.14+ |
|
||||
| **ORM** | SQLAlchemy 2.0 |
|
||||
| **ORM** | SQLAlchemy 2.1 |
|
||||
| **Migrations** | Alembic |
|
||||
| **Databases** | MariaDB, MySQL, PostgreSQL |
|
||||
| **Cache/Queue** | Redis (via RQ) |
|
||||
@@ -321,6 +321,7 @@ backend/
|
||||
│ │ └── reap_streaming_sessions.py # Stop abandoned streaming sessions
|
||||
│ └── manual/ # On-demand tasks
|
||||
│ ├── cleanup_missing_roms.py # Drop DB entries for missing files
|
||||
│ ├── convert_library.py # Store matched ROMs in each platform's library format
|
||||
│ ├── cleanup_orphaned_resources.py # Remove unreferenced artwork
|
||||
│ └── sync_folder_scan.py # Scan sync folder for new saves
|
||||
│
|
||||
@@ -908,8 +909,11 @@ A reset link is emailed when SMTP is set up, the user has an address and `ROMM_B
|
||||
| DELETE | `/{id}` | ROMS_WRITE | Delete ROM |
|
||||
| POST | `/delete` | ROMS_WRITE | Bulk delete |
|
||||
| POST | `/download/{id}/{file_name}` | ROMS_READ | Download ROM |
|
||||
| GET | `/{id}/content/{file_name}` | ROMS_READ | Download ROM, in a listed `?format=` when asked |
|
||||
| POST | `/unidentified` | ROMS_READ | Get unidentified ROMs |
|
||||
|
||||
With rom-converto enabled (`ROM_CONVERTO_ENABLED`, `converto.download_conversion_enabled`), `?format=zso,iso` lists the formats a client can read. A single-file download whose stored format is listed is served as-is. Otherwise the first listed format with a copy cached under `/romm/cache/converts` is served, then the first one rom-converto can produce: answered by the same request if it converts within a few seconds, else `202` with `Retry-After` while it finishes. `406` means no listed format can be served, and `HEAD` reports the same without starting a conversion. Only signed-in, non-kiosk users start conversions. `CONVERTO_DOWNLOAD_FORMATS` in `/api/config` lists the formats each input extension converts to.
|
||||
|
||||
#### ROM Upload (Chunked)
|
||||
|
||||
| Method | Path | Scope | Description |
|
||||
@@ -1679,29 +1683,33 @@ failure callback and a scan needs one to report a worker that died mid-scan.
|
||||
|
||||
Toggled via environment variables:
|
||||
|
||||
| Task | Env Toggle | Default Cron | Description |
|
||||
| --------------------------------- | ----------------------------------------------------- | ------------------ | ---------------------- |
|
||||
| `scan_library` | `ENABLE_SCHEDULED_RESCAN` | `0 3 * * *` (3 AM) | Full library rescan |
|
||||
| `update_switch_titledb` | `ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB` | `0 4 * * *` | Update Switch game DB |
|
||||
| `update_launchbox_metadata` | `ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA` | `0 4 * * *` | Refresh LaunchBox data |
|
||||
| `convert_images_to_webp` | `ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP` | `0 4 * * *` | Image optimization |
|
||||
| `sync_retroachievements_progress` | `ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC` | `0 4 * * *` | Sync RA user progress |
|
||||
| `cleanup_orphaned_resources` | `ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES` | `0 5 * * *` | Remove unused artwork |
|
||||
| `cleanup_netplay` | `ENABLE_SCHEDULED_CLEANUP_NETPLAY` (default on) | `*/30 * * * *` | Clean empty rooms |
|
||||
| `cleanup_upload_tmp` | `ENABLE_SCHEDULED_CLEANUP_UPLOAD_TMP` (default on) | `0 * * * *` | Drop stale uploads |
|
||||
| `cleanup_zip_cache` | `ENABLE_SCHEDULED_CLEANUP_ZIP_CACHE` (default on) | `0 4 * * *` | Drop stale cached ZIPs |
|
||||
| `cleanup_sync_sessions` | `ENABLE_SCHEDULED_CLEANUP_SYNC_SESSIONS` (default on) | `23 * * * *` | Fail abandoned syncs |
|
||||
| `reap_streaming_sessions` | `streaming.enabled` in config, read at startup | `* * * * *` | Stop abandoned streams |
|
||||
| `cleanup_audit_log` | `AUDIT_LOG_RETENTION_DAYS` above 0 (default 90) | `30 4 * * *` | Prune old audit events |
|
||||
| Task | Env Toggle | Default Cron | Description |
|
||||
| --------------------------------- | ----------------------------------------------------- | ------------------ | ------------------------------ |
|
||||
| `scan_library` | `ENABLE_SCHEDULED_RESCAN` | `0 3 * * *` (3 AM) | Full library rescan |
|
||||
| `update_switch_titledb` | `ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB` | `0 4 * * *` | Update Switch game DB |
|
||||
| `update_launchbox_metadata` | `ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA` | `0 4 * * *` | Refresh LaunchBox data |
|
||||
| `convert_images_to_webp` | `ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP` | `0 4 * * *` | Image optimization |
|
||||
| `sync_retroachievements_progress` | `ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC` | `0 4 * * *` | Sync RA user progress |
|
||||
| `cleanup_orphaned_resources` | `ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES` | `0 5 * * *` | Remove unused artwork |
|
||||
| `cleanup_netplay` | `ENABLE_SCHEDULED_CLEANUP_NETPLAY` (default on) | `*/30 * * * *` | Clean empty rooms |
|
||||
| `cleanup_upload_tmp` | `ENABLE_SCHEDULED_CLEANUP_UPLOAD_TMP` (default on) | `0 * * * *` | Drop stale uploads |
|
||||
| `cleanup_zip_cache` | `ENABLE_SCHEDULED_CLEANUP_ZIP_CACHE` (default on) | `0 4 * * *` | Drop stale cached ZIPs |
|
||||
| `cleanup_conversion_cache` | Always on | `0 4 * * *` | Drop stale converted downloads |
|
||||
| `cleanup_sync_sessions` | `ENABLE_SCHEDULED_CLEANUP_SYNC_SESSIONS` (default on) | `23 * * * *` | Fail abandoned syncs |
|
||||
| `reap_streaming_sessions` | `streaming.enabled` in config, read at startup | `* * * * *` | Stop abandoned streams |
|
||||
| `cleanup_audit_log` | `AUDIT_LOG_RETENTION_DAYS` above 0 (default 90) | `30 4 * * *` | Prune old audit events |
|
||||
|
||||
### Manual Tasks
|
||||
|
||||
Triggered via `POST /api/tasks/run/{task_name}`, which enqueues on `low_prio_queue` and answers 503 when no live worker is listening on it:
|
||||
|
||||
| Task | Description |
|
||||
| ---------------------- | --------------------------------------------- |
|
||||
| `cleanup_missing_roms` | Remove DB entries for files no longer on disk |
|
||||
| `sync_folder_scan` | Scan sync folder for new device saves |
|
||||
| Task | Description |
|
||||
| ---------------------- | ------------------------------------------------------------------------------------- |
|
||||
| `cleanup_missing_roms` | Remove DB entries for files no longer on disk |
|
||||
| `sync_folder_scan` | Scan sync folder for new device saves |
|
||||
| `convert_library` | Convert matched ROMs to `converto.platform_formats` in place, replacing the originals |
|
||||
|
||||
`convert_library` only converts losslessly (no xiso) and only identified ROMs, since a converted file no longer hash-matches a DAT. It stages each output under a `.romm_tmp_` directory beside the ROM, deletes the originals (and a cue's tracks) once the output is in place, rewrites `.m3u` entries in folder ROMs, and refreshes the ROM's files, so the ROM keeps its id, saves and collections.
|
||||
|
||||
`cleanup_orphaned_resources` is also runnable this way; it is listed under
|
||||
Scheduled Tasks because it additionally supports an opt-in cron schedule. It
|
||||
|
||||
@@ -150,6 +150,11 @@ DISABLE_RUFFLE_RS=false # Disable in-browser Flash playback via RuffleRS
|
||||
DISABLE_JSDOS=false # Disable in-browser Win3.x and Win9.x playback via js-dos
|
||||
DISABLE_PICO8=false # Disable in-browser PICO-8 playback via FAKE-08
|
||||
|
||||
# ROM conversion
|
||||
ROM_CONVERTO_ENABLED=false # Enable rom-converto for the "Convert library" task and ?format= download conversions
|
||||
ROM_CONVERTO_TIMEOUT=600 # Timeout for each rom-converto operation in seconds
|
||||
ROM_CONVERTO_MAX_CONCURRENCY=2 # Concurrent conversions per web or task worker
|
||||
|
||||
# Integrations
|
||||
YOUTUBE_BASE_URL=https://www.youtube.com # Base URL for alternate YouTube frontends (Piped, Invidious, etc.)
|
||||
TINFOIL_WELCOME_MESSAGE="RomM Switch Library" # Welcome message shown in Tinfoil Switch clients
|
||||
|
||||
@@ -253,3 +253,24 @@
|
||||
# core: parallel_n64
|
||||
# # Lets a core listed as broken by the broker run anyway.
|
||||
# # experimental_cores: true
|
||||
|
||||
# converto:
|
||||
# # Convert a single-file download into a format the client lists with
|
||||
# # ?format=, e.g. ?format=zso,iso (needs ROM_CONVERTO_ENABLED)
|
||||
# download_conversion_enabled: false
|
||||
# # Hours a converted download stays cached after it was last downloaded
|
||||
# cache_ttl_hours: 24
|
||||
# # Cache size before the least recently downloaded copies are evicted (0: unbounded)
|
||||
# cache_max_size_gb: 20
|
||||
# # Platform slug -> the format the "Convert library" task stores its matched
|
||||
# # roms in, replacing the original files. Formats per platform:
|
||||
# # 3ds: cci, cia, z3ds
|
||||
# # psp, ps2: chd, cso, iso, zso
|
||||
# # psx, saturn, segacd, dc: chd
|
||||
# # ngc: iso, rvz
|
||||
# # wii: iso, rvz, wbfs
|
||||
# # switch, switch-2: nsp, nsz, xci, xcz
|
||||
# # xbox360: zar
|
||||
# platform_formats:
|
||||
# psx: chd
|
||||
# ngc: rvz
|
||||
|
||||
2
frontend/src/__generated__/index.ts
generated
2
frontend/src/__generated__/index.ts
generated
@@ -82,6 +82,8 @@ export type { ContainerSessionSchema } from './models/ContainerSessionSchema';
|
||||
export type { ConversionStats } from './models/ConversionStats';
|
||||
export type { ConversionTaskMeta } from './models/ConversionTaskMeta';
|
||||
export type { ConversionTaskStatusResponse } from './models/ConversionTaskStatusResponse';
|
||||
export type { ConvertoConfig } from './models/ConvertoConfig';
|
||||
export type { ConvertoSettingsPayload } from './models/ConvertoSettingsPayload';
|
||||
export type { CoverResource } from './models/CoverResource';
|
||||
export type { CsdbCredit } from './models/CsdbCredit';
|
||||
export type { CustomLimitOffsetPage_SimpleRomSchema_ } from './models/CustomLimitOffsetPage_SimpleRomSchema_';
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
import type { ConvertoConfig } from './ConvertoConfig';
|
||||
import type { EjsControls } from './EjsControls';
|
||||
import type { MetadataMediaType } from './MetadataMediaType';
|
||||
import type { NetplayICEServer } from './NetplayICEServer';
|
||||
@@ -42,5 +43,8 @@ export type ConfigResponse = {
|
||||
GAMELIST_MEDIA_THUMBNAIL: MetadataMediaType;
|
||||
GAMELIST_MEDIA_IMAGE: MetadataMediaType;
|
||||
PEGASUS_AUTO_EXPORT_ON_SCAN: boolean;
|
||||
CONVERTO: ConvertoConfig;
|
||||
CONVERTO_LIBRARY_TARGETS: Record<string, Array<string>>;
|
||||
CONVERTO_DOWNLOAD_FORMATS: Record<string, Record<string, Array<string>>>;
|
||||
};
|
||||
|
||||
|
||||
11
frontend/src/__generated__/models/ConvertoConfig.ts
generated
Normal file
11
frontend/src/__generated__/models/ConvertoConfig.ts
generated
Normal file
@@ -0,0 +1,11 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export type ConvertoConfig = {
|
||||
download_conversion_enabled?: boolean;
|
||||
cache_ttl_hours?: number;
|
||||
cache_max_size_gb?: number;
|
||||
platform_formats?: Record<string, string>;
|
||||
};
|
||||
|
||||
13
frontend/src/__generated__/models/ConvertoSettingsPayload.ts
generated
Normal file
13
frontend/src/__generated__/models/ConvertoSettingsPayload.ts
generated
Normal file
@@ -0,0 +1,13 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* The converto.* settings editable at runtime; `cache_ttl_hours` stays config.yml-only.
|
||||
*/
|
||||
export type ConvertoSettingsPayload = {
|
||||
download_conversion_enabled: boolean;
|
||||
cache_max_size_gb: number;
|
||||
platform_formats: Record<string, string>;
|
||||
};
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
"playing-on": "Sta giocando su {device}",
|
||||
"playing-since": "Sta giocando da {time}",
|
||||
"release-failed": "Impossibile liberare la sessione",
|
||||
"release-reason": "Reason (optional)",
|
||||
"release-reason-placeholder": "Shown to the player whose session ends",
|
||||
"release-reason": "Motivo (opzionale)",
|
||||
"release-reason-placeholder": "Mostrato al giocatore quando la sessione finisce",
|
||||
"release-session": "Libera",
|
||||
"release-session-body": "Questo fermerà immediatamente {game} e disconnetterà {user}. I progressi non salvati andranno persi.",
|
||||
"release-session-title": "Liberare la sessione di streaming?",
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"emulator-failed": "Impossibile caricare l'emulatore",
|
||||
"emulator-loading": "Caricamento emulatore...",
|
||||
"enabled": "Abilitato",
|
||||
"exit-console-mode": "Esci dalla modalit'a console",
|
||||
"exit-console-mode": "Esci dalla modalità console",
|
||||
"exit-game": "Premi Start + Select (o Backspace) per uscire",
|
||||
"fullscreen": "Schermo intero",
|
||||
"game-detail": "Dettagli",
|
||||
@@ -22,7 +22,7 @@
|
||||
"game-exit-save": "Salva ed esci",
|
||||
"game-exit-save-desc": "Salva lo stato corrente, quindi esci",
|
||||
"game-play": "Gioca",
|
||||
"game-saving": "RISPARMIO…",
|
||||
"game-saving": "SALVATAGGIO…",
|
||||
"games-n": "{n} gioco | {n} giochi",
|
||||
"loading-platforms": "Caricamento piattaforme...",
|
||||
"nav-back": "Indietro",
|
||||
@@ -33,7 +33,7 @@
|
||||
"nav-select": "Seleziona",
|
||||
"platforms": "Piattaforme",
|
||||
"recently-played": "Giocati di recente",
|
||||
"save-states": "SALVATAGGI",
|
||||
"save-states": "Salvataggi",
|
||||
"screenshots": "Screenshot",
|
||||
"settings": "Impostazioni",
|
||||
"smart-collections": "Collezioni intelligenti",
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
{
|
||||
"clear": "Clear",
|
||||
"click-to-copy": "Click to copy to clipboard",
|
||||
"copied": "Logs copied to clipboard",
|
||||
"copy": "Copy to clipboard",
|
||||
"download": "Download",
|
||||
"empty": "No logs yet",
|
||||
"jump-to-latest": "Jump to latest",
|
||||
"level-all": "All levels",
|
||||
"level-filter": "Filter by level",
|
||||
"line-copied": "Line copied to clipboard",
|
||||
"load-error": "Failed to load logs",
|
||||
"module-all": "All modules",
|
||||
"module-filter": "Filter by module",
|
||||
"no-matches": "No logs match your filters",
|
||||
"pause": "Pause",
|
||||
"resume": "Resume",
|
||||
"search-placeholder": "Search logs"
|
||||
"clear": "Pulisci",
|
||||
"click-to-copy": "Clicca per copiare negli appunti",
|
||||
"copied": "Log copiati negli appunti",
|
||||
"copy": "Copia negli appunti",
|
||||
"download": "Scarica",
|
||||
"empty": "Nessun log presente",
|
||||
"jump-to-latest": "Salta all'ultimo",
|
||||
"level-all": "Tutti i livelli",
|
||||
"level-filter": "Filtra per livello",
|
||||
"line-copied": "Riga copiata negli appunti",
|
||||
"load-error": "Caricamento log fallito",
|
||||
"module-all": "Tutti i moduli",
|
||||
"module-filter": "Filtra per modulo",
|
||||
"no-matches": "Nessun log corrisponde ai tuoi filtri",
|
||||
"pause": "Pausa",
|
||||
"resume": "Riprendi",
|
||||
"search-placeholder": "Cerca log"
|
||||
}
|
||||
|
||||
@@ -40,5 +40,5 @@
|
||||
"upload-errors": " (con alcuni errori)",
|
||||
"upload-success": "ROM patchata caricata con successo{errors}. Avvio scansione...",
|
||||
"upload-to-romm": "Carica su RomM",
|
||||
"validation-warning": "Patch source checksum did not match the ROM; the patched file may be incorrect."
|
||||
"validation-warning": "Il checksum sorgente della patch non corrisponde alla ROM; il file patchato potrebbe non essere corretto."
|
||||
}
|
||||
|
||||
@@ -28,18 +28,18 @@
|
||||
"delete-memory-card-body": "Questa operazione elimina definitivamente \"{name}\" e tutte le sue versioni salvate. L'azione non può essere annullata.",
|
||||
"deselect-save": "Deseleziona Salvataggio",
|
||||
"deselect-state": "Deseleziona Stato",
|
||||
"desktop-back": "Back to administration",
|
||||
"desktop-error-no-container": "That streaming container is not configured.",
|
||||
"desktop-error-occupied": "This container is already in use. End the session holding it first.",
|
||||
"desktop-back": "Ritorna al pannello amministratore",
|
||||
"desktop-error-no-container": "Questo container streaming non è configurato.",
|
||||
"desktop-error-occupied": "Questo container è già in uso. Termina prima la sessione che lo sta occupando.",
|
||||
"desktop-error-occupied-by": "{rom} è in esecuzione su questo container. Termina prima quella sessione.",
|
||||
"desktop-error-release": "The desktop session could not be released. The container may still be in use.",
|
||||
"desktop-error-server": "The desktop session could not be opened.",
|
||||
"desktop-exit": "End desktop session",
|
||||
"desktop-exit-body": "The container will be released and anything still open on the desktop will be closed. Emulator settings you saved are kept.",
|
||||
"desktop-exit-confirm": "End session",
|
||||
"desktop-exit-title": "End this desktop session?",
|
||||
"desktop-error-release": "Non è stato possibile liberare la sessione desktop. Il container potrebbe essere ancora in uso.",
|
||||
"desktop-error-server": "Non è stato possibile aprire la sessione desktop.",
|
||||
"desktop-exit": "Chiudi sessione desktop",
|
||||
"desktop-exit-body": "Il container verrà liberato e qualunque programma aperto sul desktop verrà terminato. Le impostazioni dell'emulatore che hai salvato saranno conservate.",
|
||||
"desktop-exit-confirm": "Chiudi sessione",
|
||||
"desktop-exit-title": "Vuoi chiudere questa sessione desktop?",
|
||||
"desktop-frame-title": "Container desktop",
|
||||
"desktop-subtitle": "Desktop session",
|
||||
"desktop-subtitle": "Sessione desktop",
|
||||
"desktop-title": "Container desktop",
|
||||
"discs": "Dischi",
|
||||
"download-memory-card": "Scarica card",
|
||||
@@ -195,10 +195,10 @@
|
||||
"select-background-color": "Seleziona colore di sfondo",
|
||||
"select-save": "Seleziona Salvataggio",
|
||||
"select-state": "Seleziona Stato",
|
||||
"session-ended": "Your streaming session has ended.",
|
||||
"session-ended-by": "An administrator ({user}) ended your streaming session.",
|
||||
"session-ended-reason-label": "Reason given",
|
||||
"session-ended-title": "Session ended",
|
||||
"session-ended": "La tua sessione di streaming è stata terminata.",
|
||||
"session-ended-by": "Un amministratore ({user}) ha terminato la tua sessione di streaming.",
|
||||
"session-ended-reason-label": "Motivazione fornita",
|
||||
"session-ended-title": "Sessione terminata",
|
||||
"show-bezel": "Mostra cornice",
|
||||
"show-older-versions": "Mostra {count} versione precedente | Mostra {count} versioni precedenti",
|
||||
"slot": "Slot",
|
||||
@@ -214,10 +214,10 @@
|
||||
"state-not-synced": "Il tuo ultimo stato non è ancora arrivato al server. Viene conservato in questo browser e RomM continua a riprovare in background.",
|
||||
"state-sync-refused": "Il server ha rifiutato lo stato conservato per {game}: {reason}. Non è più conservato in questo browser.",
|
||||
"state-synced": "Stato sincronizzato con il server",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
"states-view-strip": "Row",
|
||||
"states-view": "Vista stato",
|
||||
"states-view-grid": "Griglia",
|
||||
"states-view-list": "Lista",
|
||||
"states-view-strip": "Riga",
|
||||
"stream-error-generic": "Si è verificato un errore imprevisto.",
|
||||
"stream-error-import-refused": "Il salvataggio o lo stato selezionato non è stato utilizzabile.",
|
||||
"stream-error-load-rom": "Impossibile caricare i dettagli della ROM.",
|
||||
@@ -227,16 +227,16 @@
|
||||
"stream-frame-title": "Stream del gioco",
|
||||
"stream-fullscreen": "Schermo intero",
|
||||
"stream-load-state": "Carica stato",
|
||||
"stream-load-state-failed": "The state could not be loaded.",
|
||||
"stream-load-state-failed": "Non è stato possibile caricare lo stato.",
|
||||
"stream-mute": "Disattiva audio",
|
||||
"stream-occupied-body": "{rom} è in gioco da {time}.",
|
||||
"stream-occupied-draining": "La sessione precedente è ancora in chiusura. Riprova tra un momento.",
|
||||
"stream-occupied-fallback": "Qualcun altro sta giocando in questo momento. Riprova più tardi.",
|
||||
"stream-occupied-title": "Sessione in uso",
|
||||
"stream-release-failed": "The session could not be released. The container may still be in use.",
|
||||
"stream-release-failed": "Non è stato possibile liberare questa sessione. Il container potrebbe essere ancora in uso.",
|
||||
"stream-save-and-exit": "Salva ed esci",
|
||||
"stream-save-state": "Salva stato",
|
||||
"stream-save-state-failed": "The state could not be saved.",
|
||||
"stream-save-state-failed": "Non è stato possibile salvare lo stato.",
|
||||
"stream-save-unconfirmed": "L'emulatore non ha confermato il salvataggio. I progressi recenti potrebbero andare persi.",
|
||||
"stream-stop": "Ferma",
|
||||
"stream-subtitle": "Streaming",
|
||||
|
||||
@@ -81,8 +81,8 @@
|
||||
"confirm-join-title-of": "Partecipare alla sessione di {user}?",
|
||||
"confirm-launch-protected-body": "Hai contrassegnato «{name}» come {status}. Vuoi comunque giocarci?",
|
||||
"confirm-launch-protected-title": "Avviare questo gioco?",
|
||||
"convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.",
|
||||
"convert-to-folder-title": "Convert to folder ROM?",
|
||||
"convert-to-folder-body": "Questa azione convertirà la ROM in una ROM multi-file. Questa azione è irreversibile.",
|
||||
"convert-to-folder-title": "Converti in cartella ROM?",
|
||||
"copy-download-link-title": "Copia link per il download",
|
||||
"copy-link": "Copia link per il download",
|
||||
"copy-link-action": "Copia link",
|
||||
@@ -140,7 +140,7 @@
|
||||
"details": "Dettagli",
|
||||
"developers": "Sviluppatori",
|
||||
"difficulty": "Difficoltà",
|
||||
"disc": "Disc",
|
||||
"disc": "Disco",
|
||||
"download": "Scarica",
|
||||
"download-all": "Scarica tutto",
|
||||
"download-file": "Scarica file",
|
||||
@@ -156,7 +156,7 @@
|
||||
"favorite": "Preferito",
|
||||
"favorites-updated-n": "{n} elemento aggiornato | {n} elementi aggiornati",
|
||||
"file": "File",
|
||||
"file-delete-failed": "Failed to delete file: {error}",
|
||||
"file-delete-failed": "Rimozione file fallita: {error}",
|
||||
"file-info": "Info file",
|
||||
"file-name-taken": "Un altro file usa già questo nome",
|
||||
"filename": "Name file",
|
||||
@@ -210,22 +210,22 @@
|
||||
"manage-collections": "Gestisci collezioni",
|
||||
"manual": "Manuale",
|
||||
"manual-empty": "Nessun manuale ancora disponibile",
|
||||
"manual-file-remove-failed": "Failed to remove manual file: {error}",
|
||||
"manual-file-removed": "Manual file removed successfully",
|
||||
"manual-files-upload-failed": "Unable to upload manual files: {error}",
|
||||
"manual-files-upload-skipped": "All manual files skipped, nothing to upload.",
|
||||
"manual-files-upload-success": "{count} manual file uploaded successfully ({failed} skipped/failed). | {count} manual files uploaded successfully ({failed} skipped/failed).",
|
||||
"manual-load-failed": "Unable to load manual",
|
||||
"manual-file-remove-failed": "Rimozione file di manuale fallita: {error}",
|
||||
"manual-file-removed": "File di manuale rimosso con successo",
|
||||
"manual-files-upload-failed": "Impossibile caricare i file di manuale: {error}",
|
||||
"manual-files-upload-skipped": "Tutti i file manuale saltati, niente da caricare.",
|
||||
"manual-files-upload-success": "{count} file di manuale caricato con successo ({failed} saltato/fallito). | {count} files di manuale caricati con successo ({failed} saltati/falliti).",
|
||||
"manual-load-failed": "Impossibile caricare manuale",
|
||||
"manual-match": "Associazione manuale",
|
||||
"manual-redownload-failed": "Failed to re-download manual: {error}",
|
||||
"manual-redownloaded": "Manual re-downloaded successfully",
|
||||
"manual-redownload-failed": "Riscaricamento manuale fallito: {error}",
|
||||
"manual-redownloaded": "Riscaricamento manuale effettuato con successo",
|
||||
"manual-remove-failed": "Errore durante la rimozione del manuale: {error}",
|
||||
"manual-removed": "Manuale rimosso con successo",
|
||||
"manual-upload-target-folder-desc": "Saved inside the game's manual/ subfolder alongside other game files.",
|
||||
"manual-upload-target-folder-title": "Add to ROM folder",
|
||||
"manual-upload-target-resources-desc": "Stored in the resources folder. Overwrites the existing scraped/uploaded PDF.",
|
||||
"manual-upload-target-resources-title": "Replace scraped manual",
|
||||
"manual-upload-target-title": "Where should the manual go?",
|
||||
"manual-upload-target-folder-desc": "Salvato nella sottocartella manual/ del gioco insieme agli altri file di gioco.",
|
||||
"manual-upload-target-folder-title": "Aggiungi alla cartella della ROM",
|
||||
"manual-upload-target-resources-desc": "Salvato nella cartella delle resources. Sovrascrive il PDF già esistente caricato/scraped.",
|
||||
"manual-upload-target-resources-title": "Sostituisci manuale scraped",
|
||||
"manual-upload-target-title": "Dove dovrebbe andare il manuale?",
|
||||
"manual-upload-title": "Carica",
|
||||
"manuals-upload-failed": "Impossibile caricare i manuali: {error}",
|
||||
"manuals-upload-skipped": "Tutti i manuali saltati, niente da caricare.",
|
||||
@@ -265,12 +265,12 @@
|
||||
"media-video-normalized": "Video (standardizzato)",
|
||||
"metadata": "Metadati",
|
||||
"metadata-ids": "ID metadati",
|
||||
"metadata-providers": "Provider di metadati",
|
||||
"metadata-providers": "Provider dei metadati",
|
||||
"metadata-sources-label": "Fonti metadati",
|
||||
"metric-completion": "Completamento",
|
||||
"metric-difficulty": "Difficoltà",
|
||||
"metric-rating": "Valutazione",
|
||||
"missing-from-fs-path": "Missing from filesystem: {path}",
|
||||
"missing-from-fs-path": "Mancante dal filesystem: {path}",
|
||||
"missing-platform": "Piattaforma mancante dal filesystem",
|
||||
"more-actions": "Altre azioni",
|
||||
"my-notes": "Mie note",
|
||||
@@ -283,14 +283,14 @@
|
||||
"no-games-match": "Nessun gioco corrisponde alla tua ricerca.",
|
||||
"no-games-match-filters": "Nessun gioco corrisponde ai filtri selezionati.",
|
||||
"no-games-match-query": "Nessun gioco corrisponde a \"{query}\".",
|
||||
"no-manual": "No manual available for this game.",
|
||||
"no-manual": "Nessun manuale disponibile per questo gioco.",
|
||||
"no-metadata-source": "Nessuna fonte di metadati abilitata",
|
||||
"no-notes": "Nessuna nota trovata",
|
||||
"no-notes-desc": "Clicca sul pulsante Aggiungi Nota per creare la tua prima nota",
|
||||
"no-saves-found": "Nessun salvataggio trovato",
|
||||
"no-saves-uploaded": "Nessun salvataggio caricato.",
|
||||
"no-screenshots-uploaded": "Nessuno screenshot caricato.",
|
||||
"no-soundtrack": "No soundtrack available for this game.",
|
||||
"no-soundtrack": "Nessuna soundtrack disponibile per questo gioco.",
|
||||
"no-states-found": "Nessun stato trovato",
|
||||
"no-states-uploaded": "Nessuno stato caricato.",
|
||||
"note-content": "Contenuto della Nota",
|
||||
@@ -358,7 +358,7 @@
|
||||
"ratings-label": "Valutazioni",
|
||||
"reading-progress": "Avanzamento lettura",
|
||||
"redownload": "Riscarica",
|
||||
"redownload-manual": "Re-download scraped manual",
|
||||
"redownload-manual": "Riscarica manuale scraped",
|
||||
"refresh-complete-desc": "Sovrascrivi i metadati da tutti i provider selezionati",
|
||||
"refresh-files": "Aggiorna file",
|
||||
"refresh-files-desc": "Rileva i file aggiunti alla cartella di questo gioco senza recuperare di nuovo i metadati",
|
||||
@@ -400,7 +400,7 @@
|
||||
"saves-empty": "Nessun salvataggio ancora",
|
||||
"saves-empty-hint": "I salvataggi caricati per questa ROM appariranno qui.",
|
||||
"saves-section-community": "Community",
|
||||
"saves-section-mine": "My saves",
|
||||
"saves-section-mine": "I miei salvataggi",
|
||||
"saves-tab": "Salvataggi",
|
||||
"saves-uploaded-n": "Caricato {n} salvataggio. | Caricati {n} salvataggi.",
|
||||
"saves-uploaded-with-failed": "Caricato {n} salvataggio, {failed} falliti. | Caricati {n} salvataggi, {failed} falliti.",
|
||||
@@ -443,7 +443,7 @@
|
||||
"share-qr": "Condividi (codice QR)",
|
||||
"show-earned-only": "Mostra solo guadagnati",
|
||||
"single-player": "Giocatore singolo",
|
||||
"size": "Dimenzioni",
|
||||
"size": "Dimensioni",
|
||||
"snackbar-download-link-copied": "Link per il download copiato negli appunti",
|
||||
"snackbar-link-copied": "Link copiato negli appunti",
|
||||
"snackbar-remove-from-playing-failed": "Impossibile rimuovere da Stai giocando",
|
||||
@@ -455,11 +455,11 @@
|
||||
"soundtrack-close-player": "Chiudi player",
|
||||
"soundtrack-delete-track": "Elimina traccia",
|
||||
"soundtrack-empty": "Nessuna colonna sonora ancora disponibile",
|
||||
"soundtrack-folder-only": "Available for folder-based ROMs only",
|
||||
"soundtrack-folder-only": "Disponibile solo per ROM folder-based",
|
||||
"soundtrack-metadata-error": "Impossibile caricare i metadati della colonna sonora",
|
||||
"soundtrack-mini-player": "Player colonna sonora",
|
||||
"soundtrack-next": "Traccia successiva",
|
||||
"soundtrack-open-rom": "Open ROM details",
|
||||
"soundtrack-open-rom": "Apri dettagli ROM",
|
||||
"soundtrack-open-rom-tooltip": "Apri ROM",
|
||||
"soundtrack-pause": "Pausa",
|
||||
"soundtrack-play": "Riproduci",
|
||||
@@ -471,16 +471,16 @@
|
||||
"soundtrack-seek": "Cerca",
|
||||
"soundtrack-upload-title": "Carica",
|
||||
"soundtrack-volume": "Volume",
|
||||
"soundtracks-upload-failed": "Unable to upload soundtracks: {error}",
|
||||
"soundtracks-upload-skipped": "All soundtracks skipped, nothing to upload.",
|
||||
"soundtracks-upload-success": "{count} soundtrack uploaded successfully ({failed} skipped/failed). | {count} soundtracks uploaded successfully ({failed} skipped/failed).",
|
||||
"soundtracks-upload-failed": "Impossibile caricare le soundtracks: {error}",
|
||||
"soundtracks-upload-skipped": "Tutte le soundtracks saltate, nulla da caricare.",
|
||||
"soundtracks-upload-success": "{count} soundtrack caricata con successo ({failed} saltato/fallito). | {count} soundtracks caricate con successo ({failed} saltato/fallito).",
|
||||
"state-deleted": "Stato eliminato.",
|
||||
"state-updated": "Stato aggiornato.",
|
||||
"states-deleted-n": "{n} stato eliminato | {n} stati eliminati",
|
||||
"states-empty": "Nessuno stato ancora",
|
||||
"states-empty-hint": "Gli stati di salvataggio caricati per questa ROM appariranno qui.",
|
||||
"states-section-community": "Community",
|
||||
"states-section-mine": "My states",
|
||||
"states-section-mine": "I miei stati",
|
||||
"states-tab": "Stati",
|
||||
"states-uploaded-n": "Caricato {n} stato. | Caricati {n} stati.",
|
||||
"states-uploaded-with-failed": "Caricato {n} stato, {failed} falliti. | Caricati {n} stati, {failed} falliti.",
|
||||
@@ -492,7 +492,7 @@
|
||||
"status-finished": "Finito",
|
||||
"status-hidden": "Nascosto",
|
||||
"status-incomplete": "Incompleto",
|
||||
"status-never-playing": "Mai giocare",
|
||||
"status-never-playing": "Mai giocato",
|
||||
"status-now-playing": "In gioco",
|
||||
"status-retired": "Abbandonato",
|
||||
"stream": "Trasmetti",
|
||||
@@ -531,11 +531,11 @@
|
||||
"upload-saves": "Carica salvataggi",
|
||||
"upload-screenshots": "Carica screenshot",
|
||||
"upload-slot-hint": "I salvataggi in uno slot entrano nella sincronizzazione dei dispositivi; senza slot il file resta un archivio manuale.",
|
||||
"upload-soundtrack": "Upload soundtrack",
|
||||
"upload-soundtrack": "Carica soundtrack",
|
||||
"upload-states": "Carica stati",
|
||||
"upload-to-folder": "Carica in cartella",
|
||||
"upload-tracks": "Add tracks",
|
||||
"upload-walkthrough": "Upload walkthrough",
|
||||
"upload-tracks": "Aggiungi tracce",
|
||||
"upload-walkthrough": "Carica walkthrough",
|
||||
"verification": "Verifica",
|
||||
"verified-rom": "ROM verificata",
|
||||
"verified-rom-hint": "Hash verificato su un database di ROM",
|
||||
@@ -543,13 +543,13 @@
|
||||
"volume-mute": "Disattiva audio",
|
||||
"volume-unmute": "Riattiva audio",
|
||||
"walkthrough": "Walkthrough",
|
||||
"walkthrough-add-failed": "Could not add walkthrough: {error}",
|
||||
"walkthrough-added": "Walkthrough added",
|
||||
"walkthrough-empty": "No walkthroughs yet",
|
||||
"walkthrough-remove-failed": "Failed to remove walkthrough: {error}",
|
||||
"walkthrough-removed": "Walkthrough removed",
|
||||
"walkthrough-url-label": "GameFAQs guide URL",
|
||||
"walkthrough-add-failed": "Non è stato possibile aggiungere walkthrough: {error}",
|
||||
"walkthrough-added": "Walkthrough aggiunto",
|
||||
"walkthrough-empty": "Nessun walkthrough presente",
|
||||
"walkthrough-remove-failed": "Non è stato possibile rimuovere walkthrough: {error}",
|
||||
"walkthrough-removed": "Walkthrough rimosso",
|
||||
"walkthrough-url-label": "URL guida GameFAQs",
|
||||
"walkthroughs": "Walkthroughs",
|
||||
"your-progress": "Your progress",
|
||||
"your-progress": "Tuo progresso",
|
||||
"youtube-video-id": "ID video YouTube"
|
||||
}
|
||||
|
||||
@@ -7,9 +7,9 @@
|
||||
"add-mapping-type": "Seleziona tipo di mapping:",
|
||||
"add-platform-variant": "Aggiungi variante piattaforma",
|
||||
"added-header": "Aggiunto",
|
||||
"administrator": "Administrator",
|
||||
"administrator-hint": "Full access to everything. Groups and hidden platforms don't apply.",
|
||||
"advanced-permissions": "Advanced permissions",
|
||||
"administrator": "Amministratore",
|
||||
"administrator-hint": "Accesso completo. Non si applica a gruppi e piattaforme nascoste.",
|
||||
"advanced-permissions": "Permessi avanzati",
|
||||
"auto-detected": "Rilevato automaticamente",
|
||||
"backlogged": "In sospeso",
|
||||
"boxart-advanced": "Stili copertina avanzati",
|
||||
@@ -24,39 +24,39 @@
|
||||
"boxart-style-details": "Stile della pagina dei dettagli",
|
||||
"boxart-style-player": "Stile della pagina di gioco",
|
||||
"canceled": "Annullato",
|
||||
"cannot-change-own-role": "You can't change your own access level.",
|
||||
"cannot-change-own-role": "Non puoi cambiare il tuo stesso livello di accesso.",
|
||||
"change-avatar": "Cambia avatar",
|
||||
"change-password": "Cambia password",
|
||||
"cleanup": "Pulizia",
|
||||
"cleanup-all": "Pulisci tutto",
|
||||
"cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.",
|
||||
"cleanup-all-confirm": "Questo cancellerà definitivamente dal database tutte le ROM{platform} i cui file mancano dal filesystem e le loro cartelle di risorse. Questa azione è irreversibile.",
|
||||
"cleanup-firmware-confirm": "Questa azione eliminerà definitivamente dal database ogni voce di firmware{platform} il cui file manca dal filesystem. Nulla viene rimosso dal disco.",
|
||||
"cleanup-firmware-queued": "Attività di pulizia accodata, il firmware mancante verrà eliminato a breve",
|
||||
"cleanup-queued": "Attività di pulizia accodata, le ROM mancanti verranno eliminate a breve",
|
||||
"client-api-tokens": "Client API Tokens",
|
||||
"client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.",
|
||||
"client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.",
|
||||
"client-token-copied": "Token copied to clipboard",
|
||||
"client-token-created": "Token created successfully",
|
||||
"client-token-deleted": "Token revoked successfully",
|
||||
"client-token-delivery-hint": "This token will not be shown again.",
|
||||
"client-token-expiry-1y": "1 year",
|
||||
"client-token-expiry-30d": "30 days",
|
||||
"client-token-expiry-90d": "90 days",
|
||||
"client-token-expiry-never": "Never",
|
||||
"client-token-name": "Token name",
|
||||
"client-token-pair-claimed": "Device paired successfully!",
|
||||
"client-token-pair-expired": "Pairing code expired",
|
||||
"client-token-regenerated": "Token regenerated successfully",
|
||||
"client-token-scopes": "Permissions",
|
||||
"client-token-select-expiry": "Expiration",
|
||||
"client-api-tokens": "Token Client API",
|
||||
"client-token-confirm-delete": "Sei sicuro di revocare questo token? Tutti i dispositivi che lo utilizzano perderanno l'accesso.",
|
||||
"client-token-confirm-regenerate": "Questo invaliderà le credenziali correnti. Tutti i dispositivi che usano il vecchio token dovranno essere ri-associati.",
|
||||
"client-token-copied": "Token copiato negli appunti",
|
||||
"client-token-created": "Token creato con successo",
|
||||
"client-token-deleted": "Token revocato con successo",
|
||||
"client-token-delivery-hint": "Questo token non sarà mostrato di nuovo.",
|
||||
"client-token-expiry-1y": "1 anno",
|
||||
"client-token-expiry-30d": "30 giorni",
|
||||
"client-token-expiry-90d": "90 giorni",
|
||||
"client-token-expiry-never": "Mai",
|
||||
"client-token-name": "Nome del token",
|
||||
"client-token-pair-claimed": "Dispositivo associato con successo!",
|
||||
"client-token-pair-expired": "Codice di associazione scaduto",
|
||||
"client-token-regenerated": "Token rigenerato con successo",
|
||||
"client-token-scopes": "Permessi",
|
||||
"client-token-select-expiry": "Scadenza",
|
||||
"completed": "Completato",
|
||||
"config-file-not-mounted-desc": "Il file config.yml non è stato montato. Qualsiasi modifica apportata alla configurazione non persisterà dopo il riavvio dell'applicazione.",
|
||||
"config-file-not-mounted-title": "File di configurazione non montato!",
|
||||
"config-file-not-writable-desc": "Il file config.yml non è scrivibile. Qualsiasi modifica apportata alla configurazione non persisterà dopo il riavvio dell'applicazione.",
|
||||
"config-file-not-writable-title": "File di configurazione non scrivibile!",
|
||||
"config-file-parse-error-desc": "The config.yml file has a syntax error, so RomM is running with default settings and ignoring your configuration. Fix the error and restart RomM to apply your settings. Details: {error}",
|
||||
"config-file-parse-error-title": "Configuration file could not be parsed!",
|
||||
"config-file-parse-error-desc": "Il file config.yml ha un errore di sintassi, quindi RomM sta ignorando la tua configurazione e sta usando le impostazioni di default. Sistema l'errore e riavvia RomM per applicare le tue impostazioni. Dettagli: {error}",
|
||||
"config-file-parse-error-title": "Non è stato possibile parsare il file di configurazione!",
|
||||
"config-tab": "Configurazione",
|
||||
"confirm-delete-mapping": "Confermi?",
|
||||
"confirm-protected-launch": "Conferma l'avvio dei giochi accantonati",
|
||||
@@ -75,7 +75,7 @@
|
||||
"controller-debug-no-gamepad": "Nessun gamepad rilevato",
|
||||
"controller-debug-right-stick": "Stick destro",
|
||||
"controller-debug-slot": "Slot {n}",
|
||||
"controller-debug-test-hint": "Button actions are paused here so you can test every button. Hold B / Back to exit.",
|
||||
"controller-debug-test-hint": "Le azioni dei pulsanti sono state messe in pausa qui per permettere di testare ogni pulsante. Tieni premuto B / Back per uscire.",
|
||||
"controller-debug-wake-hint": "Premi un pulsante qualsiasi del controller per attivarlo.",
|
||||
"conversion": "Conversione",
|
||||
"copy-link": "Copia link",
|
||||
@@ -86,10 +86,10 @@
|
||||
"couldnt-queue-cleanup": "Impossibile accodare l'attività di pulizia: {error}",
|
||||
"create-new-api-token": "Crea nuovo token API",
|
||||
"create-user": "Crea utente",
|
||||
"crt-mode-desc": "Give the interface a retro cathode-ray-tube look with scanlines, glow and flicker",
|
||||
"crt-mode-desc": "Dà all'interfaccia un look retrò in stile tubo catodico con linee di scansione, luce e sfarfallio",
|
||||
"current-password": "Password attuale",
|
||||
"debug-overlay": "Debug overlay",
|
||||
"debug-overlay-desc": "Show a developer overlay (bottom-right) with live breakpoint, viewport, input modality, theme, route, gamepad and performance info.",
|
||||
"debug-overlay-desc": "Mostra overlay sviluppatore (in basso a destra) con breakpoint live, viewport, modalità input, tema, route, gamepad e informazioni sulle performance.",
|
||||
"deferred": "Rimandato",
|
||||
"delete-user-confirm": "Eliminare l'utente \"{username}\"? L'operazione non può essere annullata.",
|
||||
"deleting-mapping": "Eliminazione",
|
||||
@@ -99,32 +99,32 @@
|
||||
"description": "Description",
|
||||
"desktop-shell": "Applicazione desktop",
|
||||
"desktop-shell-desc": "I percorsi degli emulatori, la cache delle ROM e la posizione della libreria sono impostati nella configurazione dell'applicazione, su questa macchina. Versione {version}.",
|
||||
"developer": "Developer",
|
||||
"device-auth-approve": "Approve",
|
||||
"device-auth-approve-failed": "Failed to approve device.",
|
||||
"device-auth-approved-body": "You can close this tab. Your device will connect automatically.",
|
||||
"device-auth-approved-title": "Device authorized",
|
||||
"device-auth-auto-close": "Closing in {seconds}s...",
|
||||
"device-auth-code-already-handled": "This pairing request was already handled.",
|
||||
"device-auth-code-expired": "This pairing code has expired or was not found.",
|
||||
"device-auth-denied-body": "The device's request was denied.",
|
||||
"device-auth-denied-title": "Request denied",
|
||||
"device-auth-deny": "Deny",
|
||||
"device-auth-deny-failed": "Failed to deny device.",
|
||||
"device-auth-device-name": "Device name",
|
||||
"device-auth-disallowed-label": "Your account doesn't have permission for:",
|
||||
"device-auth-expires-in": "Token expires in",
|
||||
"device-auth-fetch-failed": "Failed to load pairing request.",
|
||||
"device-auth-heading": "Authorize device",
|
||||
"device-auth-loading": "Loading pairing request...",
|
||||
"device-auth-no-code": "No pairing code provided.",
|
||||
"device-auth-scopes-label": "This device is requesting:",
|
||||
"device-auth-subheading": "A device is requesting access to your RomM library.",
|
||||
"developer": "Sviluppatore",
|
||||
"device-auth-approve": "Approva",
|
||||
"device-auth-approve-failed": "Approvazione dispositivo fallita.",
|
||||
"device-auth-approved-body": "Puoi chiudere questa scheda. Il tuo dispositivo si connetterà automaticamente.",
|
||||
"device-auth-approved-title": "Dispositivo autorizzato",
|
||||
"device-auth-auto-close": "Si chiuderà tra {seconds}s...",
|
||||
"device-auth-code-already-handled": "Questa richiesta di accoppiamento è stata già gestita.",
|
||||
"device-auth-code-expired": "Questo codice di accoppiamento è scaduto o non è stato trovato.",
|
||||
"device-auth-denied-body": "Questa richiesta del dispositivo è stata negata.",
|
||||
"device-auth-denied-title": "Richiesta negata",
|
||||
"device-auth-deny": "Rifiuta",
|
||||
"device-auth-deny-failed": "Impossibile rifiutare dispositivo.",
|
||||
"device-auth-device-name": "Nome del dispositivo",
|
||||
"device-auth-disallowed-label": "Il tuo account non ha i permessi per:",
|
||||
"device-auth-expires-in": "Token scade tra",
|
||||
"device-auth-fetch-failed": "Impossibile caricare la richiesta di associazione.",
|
||||
"device-auth-heading": "Autorizza dispositivo",
|
||||
"device-auth-loading": "Caricamento richiesta di associazione...",
|
||||
"device-auth-no-code": "Non è stato fornito alcun codice di associazione.",
|
||||
"device-auth-scopes-label": "Questo dispositivo sta richiedendo:",
|
||||
"device-auth-subheading": "Un dispositivo sta richiedendo l'accesso alla tua libreria RomM.",
|
||||
"disable-animations": "Disabilita animazioni",
|
||||
"disable-animations-desc": "Disabilita tutte le animazioni nella galleria (rotazione CD, caricamento cartucce, video al passaggio del mouse)",
|
||||
"disable-user": "Disabilita {username}",
|
||||
"discard": "Scarta",
|
||||
"edit-group": "Edit group",
|
||||
"edit-group": "Modifica gruppo",
|
||||
"edit-user": "Modifica utente",
|
||||
"email": "Email",
|
||||
"enable-3d-effect": "Abilita effetto 3D",
|
||||
@@ -176,35 +176,35 @@
|
||||
"gallery": "Galleria",
|
||||
"gameplay": "Gameplay",
|
||||
"games-label": "Giochi",
|
||||
"grant-full": "Full access",
|
||||
"grant-none": "Not granted",
|
||||
"grant-own": "Own items only",
|
||||
"grant-full": "Accesso completo",
|
||||
"grant-none": "Non concesso",
|
||||
"grant-own": "Solo elementi propri",
|
||||
"group-account": "Account",
|
||||
"group-color": "Color",
|
||||
"group-default-option": "Default group",
|
||||
"group-color": "Colore",
|
||||
"group-default-option": "Gruppo default",
|
||||
"group-default-tag": "Default",
|
||||
"group-delete-confirm": "Delete the \"{name}\" group? Its members fall back to the default group.",
|
||||
"group-delete-failed": "Could not delete group: {detail}",
|
||||
"group-grants": "Permissions",
|
||||
"group-is-default": "Default group for new users",
|
||||
"group-is-default-hint": "New users are assigned to this group automatically.",
|
||||
"group-delete-confirm": "Vuoi cancellare il gruppo \"{name}\"? I suoi membri ripiegheranno sul gruppo default.",
|
||||
"group-delete-failed": "Non è stato possibile cancellare il gruppo: {detail}",
|
||||
"group-grants": "Permessi",
|
||||
"group-is-default": "Gruppo default per nuovi utenti",
|
||||
"group-is-default-hint": "I nuovi utenti vengono assegnati a questo gruppo automaticamente.",
|
||||
"group-library": "Libreria",
|
||||
"group-members": "Members",
|
||||
"group-removed": "Group \"{name}\" removed",
|
||||
"group-roms": "Raggruppa rom",
|
||||
"group-members": "Membri",
|
||||
"group-removed": "Gruppo \"{name}\" rimosso",
|
||||
"group-roms": "Raggruppa ROM",
|
||||
"group-roms-desc": "Raggruppa le diverse versioni della stessa ROM nella galleria",
|
||||
"group-save-failed": "Could not save group: {detail}",
|
||||
"group-saved": "Group \"{name}\" saved",
|
||||
"group-save-failed": "Non è stato possibile salvare il gruppo: {detail}",
|
||||
"group-saved": "Gruppo \"{name}\" salvato",
|
||||
"group-system": "Sistema",
|
||||
"group-system-tag": "System",
|
||||
"group-system-warning": "This is a built-in group. Editing it changes what its members can do.",
|
||||
"group-system-tag": "Sistema",
|
||||
"group-system-warning": "Questo è un gruppo integrato. Modificandolo, controlli cosa possono fare i suoi membri.",
|
||||
"group-tools": "Strumenti",
|
||||
"groups-empty": "No permission groups yet",
|
||||
"hidden-games": "Hidden games",
|
||||
"hidden-games-search": "Search games to hide",
|
||||
"hidden-platforms": "Hidden platforms",
|
||||
"hidden-platforms-hint": "These platforms and their games are hidden from this user.",
|
||||
"hidden-platforms-placeholder": "Select platforms to hide",
|
||||
"groups-empty": "Nessun gruppo di permessi",
|
||||
"hidden-games": "Giochi nascosti",
|
||||
"hidden-games-search": "Cerca giochi da nascondere",
|
||||
"hidden-platforms": "Piattaforme nascoste",
|
||||
"hidden-platforms-hint": "Queste piattaforme e i loro giochi sono nascosti a questo utente.",
|
||||
"hidden-platforms-placeholder": "Seleziona piattaforme da nascondere",
|
||||
"home": "Home",
|
||||
"home-sections": "Sezioni",
|
||||
"home-widgets": "Widget",
|
||||
@@ -249,11 +249,11 @@
|
||||
"missing-firmware-none": "Nessun firmware mancante trovato",
|
||||
"missing-firmware-tab": "Firmware mancante",
|
||||
"missing-games-actions": "Azioni per giochi mancanti",
|
||||
"missing-games-delete-all": "Delete all missing games",
|
||||
"missing-games-delete-all": "Cancella tutti i giochi mancanti",
|
||||
"missing-games-none": "Nessuna ROM mancante trovata",
|
||||
"missing-games-tab": "Giochi mancanti",
|
||||
"missing-platform-from-fs": "Piattaforma mancante dal filesystem",
|
||||
"new-group": "New group",
|
||||
"new-group": "Nuovo gruppo",
|
||||
"new-password": "Nuova password",
|
||||
"no-matching-platforms": "Nessuna piattaforma corrispondente.",
|
||||
"no-missing-roms-to-delete": "Nessuna ROM mancante da eliminare",
|
||||
@@ -263,10 +263,10 @@
|
||||
"open-shell-settings": "Apri le impostazioni dell'applicazione",
|
||||
"open-shell-settings-failed": "Non è stato possibile aprire le impostazioni dell'app desktop",
|
||||
"order-platforms-by": "Ordina piattaforme per",
|
||||
"override-grant": "Granted",
|
||||
"override-grant-own": "Granted (own items only)",
|
||||
"override-inherit": "Inherit from group",
|
||||
"override-revoke": "Revoked",
|
||||
"override-grant": "Concesso",
|
||||
"override-grant-own": "Concesso (solo i propri elementi)",
|
||||
"override-inherit": "Eredita dal gruppo",
|
||||
"override-revoke": "Revocato",
|
||||
"pair-device": "Associa dispositivo",
|
||||
"pair-enter-code-prompt": "Inserisci questo codice sul tuo dispositivo per completare l'associazione:",
|
||||
"pair-exchange-failed": "Impossibile scambiare il codice di associazione.",
|
||||
@@ -280,30 +280,30 @@
|
||||
"password-updated": "Password aggiornata",
|
||||
"passwords-must-match": "Le password devono corrispondere",
|
||||
"perm-action": {
|
||||
"delete": "Delete",
|
||||
"read": "Read",
|
||||
"write": "Write"
|
||||
"delete": "Eliminazione",
|
||||
"read": "Lettura",
|
||||
"write": "Scrittura"
|
||||
},
|
||||
"perm-entity": {
|
||||
"assets": "Saves & states",
|
||||
"collections": "Collections",
|
||||
"devices": "Devices",
|
||||
"assets": "Salvataggi & stati",
|
||||
"collections": "Collezioni",
|
||||
"devices": "Dispositivi",
|
||||
"firmware": "Firmware",
|
||||
"logs": "Logs",
|
||||
"platforms": "Platforms",
|
||||
"playlists": "Playlists",
|
||||
"roms": "Games",
|
||||
"tasks": "Tasks",
|
||||
"users": "Users"
|
||||
"platforms": "Piattaforme",
|
||||
"playlists": "Playlist",
|
||||
"roms": "Giochi",
|
||||
"tasks": "Attività",
|
||||
"users": "Utenti"
|
||||
},
|
||||
"perm-entity-label": "Entity",
|
||||
"perm-own-only": "own",
|
||||
"perm-own-only-hint": "Limited to the user's own items",
|
||||
"permission-group": "Permission group",
|
||||
"permission-group-hint": "Sets which actions this user can perform across the library.",
|
||||
"permission-groups": "Permission Groups",
|
||||
"permission-overrides": "Permission overrides",
|
||||
"permission-overrides-hint": "Grant or revoke specific actions for this user, on top of their group.",
|
||||
"perm-entity-label": "Entità",
|
||||
"perm-own-only": "proprio",
|
||||
"perm-own-only-hint": "Limitato agli oggetti dell'utente",
|
||||
"permission-group": "Gruppo di permessi",
|
||||
"permission-group-hint": "Imposta quali azioni può compiere questo utente all'interno della libreria.",
|
||||
"permission-groups": "Gruppi di Permessi",
|
||||
"permission-overrides": "Override permessi",
|
||||
"permission-overrides-hint": "Concedi o revoca azioni specifiche per questo utente, oltre a quelle del suo gruppo.",
|
||||
"platform-count-games": "{count} gioco | {count} giochi",
|
||||
"platform-mapping-created": "Mappatura della piattaforma creata",
|
||||
"platform-mapping-deleted": "Mappatura della piattaforma eliminata",
|
||||
@@ -394,8 +394,8 @@
|
||||
"scan-region-priority": "Priorità regioni",
|
||||
"scan-region-priority-desc": "Ordine dei codici regione usati per le varianti regionali, sia per la versione predefinita mostrata di un gioco sia per gli artwork da IGDB e ScreenScraper. Vince la prima regione disponibile.",
|
||||
"scan-settings": "Impostazioni di scansione",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
"scan-settings-load-error-desc": "Non è stato possibile caricare le impostazioni di scansione dal server. La modifica è disabilitata per evitare sovrascrittura della tua configurazione già esistente.",
|
||||
"scan-settings-load-error-title": "Impossibile caricare le impostazioni di scansione",
|
||||
"scan-settings-save-error": "Impossibile salvare le impostazioni di scansione: {detail}",
|
||||
"scan-settings-saved": "Impostazioni di scansione salvate",
|
||||
"scan-unsaved-changes": "Hai modifiche non salvate",
|
||||
@@ -410,7 +410,7 @@
|
||||
"screenshots": "Screenshot",
|
||||
"search-exclusions": "Cerca esclusioni",
|
||||
"search-folder-mappings": "Cerca mapping cartelle",
|
||||
"search-groups": "Search groups",
|
||||
"search-groups": "Cerca gruppi",
|
||||
"search-platforms": "Cerca piattaforme",
|
||||
"search-tokens": "Cerca token",
|
||||
"search-users": "Cerca utenti",
|
||||
@@ -462,24 +462,24 @@
|
||||
"stopped": "Fermato",
|
||||
"streaming": "Streaming",
|
||||
"streaming-by": "({user})",
|
||||
"streaming-desktop-session": "Desktop session",
|
||||
"streaming-disabled": "Emulator streaming is disabled on this server.",
|
||||
"streaming-desktop-session": "Sessione desktop",
|
||||
"streaming-disabled": "Lo streaming dell'emulatore è disattivato su questo server.",
|
||||
"streaming-draining": "Chiusura della sessione precedente",
|
||||
"streaming-idle": "Idle",
|
||||
"streaming-load-failed": "Could not load the streaming containers.",
|
||||
"streaming-none": "No streaming containers are configured.",
|
||||
"streaming-open-desktop": "Open desktop",
|
||||
"streaming-refresh": "Refresh",
|
||||
"streaming-release": "End session",
|
||||
"streaming-release-body": "This stops whatever is running on {container} and disconnects the player holding it.",
|
||||
"streaming-release-confirm": "End session",
|
||||
"streaming-release-failed": "Could not end the session.",
|
||||
"streaming-release-reason": "Ended by an administrator",
|
||||
"streaming-release-title": "End this session?",
|
||||
"streaming-released": "Session ended.",
|
||||
"streaming-since": "since {time}",
|
||||
"streaming-unknown-game": "Unknown game",
|
||||
"streaming-unusable": "This container's host has no scheme, so it can never be claimed.",
|
||||
"streaming-idle": "Inattivo",
|
||||
"streaming-load-failed": "Non è stato possibile caricare i container di streaming.",
|
||||
"streaming-none": "Nessun container di streaming è configurato.",
|
||||
"streaming-open-desktop": "Apri desktop",
|
||||
"streaming-refresh": "Aggiorna",
|
||||
"streaming-release": "Termina sessione",
|
||||
"streaming-release-body": "Questo arresta qualunque cosa sia in esecuzione su {container} e disconnette il giocatore che lo sta eseguendo.",
|
||||
"streaming-release-confirm": "Termina sessione",
|
||||
"streaming-release-failed": "Non è stato possibile terminare la sessione.",
|
||||
"streaming-release-reason": "Terminata dall'amministratore",
|
||||
"streaming-release-title": "Terminare questa sessione?",
|
||||
"streaming-released": "Sessione terminata.",
|
||||
"streaming-since": "da {time}",
|
||||
"streaming-unknown-game": "Gioco sconosciuto",
|
||||
"streaming-unusable": "L'host di questo container non ha uno schema, quindi non può essere reclamato.",
|
||||
"summary": "Riepilogo",
|
||||
"task-failed": "Attività non riuscita",
|
||||
"task-history": "Cronologia attività",
|
||||
|
||||
@@ -51,6 +51,14 @@ const defaultConfig = {
|
||||
GAMELIST_MEDIA_THUMBNAIL: "box2d",
|
||||
GAMELIST_MEDIA_IMAGE: "screenshot",
|
||||
PEGASUS_AUTO_EXPORT_ON_SCAN: false,
|
||||
CONVERTO: {
|
||||
download_conversion_enabled: false,
|
||||
cache_ttl_hours: 24,
|
||||
cache_max_size_gb: 20,
|
||||
platform_formats: {},
|
||||
},
|
||||
CONVERTO_LIBRARY_TARGETS: {},
|
||||
CONVERTO_DOWNLOAD_FORMATS: {},
|
||||
} as ConfigResponse;
|
||||
|
||||
export default defineStore("config", {
|
||||
|
||||
@@ -12,7 +12,7 @@ readme = "README.md"
|
||||
license = "AGPL-3.0-only"
|
||||
dependencies = [
|
||||
"PyYAML ~= 6.0",
|
||||
"SQLAlchemy[mariadb-connector,mysql-connector,postgresql-psycopg] ~= 2.0",
|
||||
"SQLAlchemy[mariadb-connector,mysql-connector,postgresql-psycopg] ~= 2.1",
|
||||
"Unidecode ~= 1.3",
|
||||
"aiohttp ~= 3.14",
|
||||
"asyncssh ~= 2.24",
|
||||
|
||||
96
uv.lock
generated
96
uv.lock
generated
@@ -754,45 +754,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/86/f1/62a193f0227cf15a920390abe675f386dec35f7ae3ffe6da582d3ade42c7/googleapis_common_protos-1.70.0-py3-none-any.whl", hash = "sha256:b8bfcca8c25a2bb253e0e0b0adaf8c00773e5e6af6fd92397576680b807e0fd8", size = 294530, upload-time = "2025-04-14T10:17:01.271Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "greenlet"
|
||||
version = "3.5.5"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0b/d8/7cc97c142388aef03f622e001c572c4f84e9252a439549d483f555771970/greenlet-3.5.5.tar.gz", hash = "sha256:adb4bae02e91a8e863e48b177e4014bdcac8a6b5e047ea1df687a61534b85e6c", size = 207585, upload-time = "2026-08-10T15:09:36.136Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/7f/8c/080e881fa2be95ff1ddbd6994b2bab3b1a78df3b3fcab39306011764fcc7/greenlet-3.5.5-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:d4a389a852e392a6366058651a20fa5ba40d979865aa81bea2ccbdc44805070d", size = 295309, upload-time = "2026-08-10T13:26:03.032Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/25/cc/0ac614e6586c0e42d4cc281a5819150f4f43685744a4c5ff77139286409d/greenlet-3.5.5-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:70b157cd319873e8b544ddc2de158f55bbd0a9b0218c8ce9332039801518e328", size = 661185, upload-time = "2026-08-10T14:14:37.867Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5e/b9/6808725354be8ad305dfe5172377664fc9642d4fc043be246b3314cf4482/greenlet-3.5.5-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8bdfd1424abcf26832961e766570cae79efdb9599d709088c9cb6ef82b194926", size = 673419, upload-time = "2026-08-10T14:27:28.652Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/42/2e/40c509967da7f254680826a2fa0dd22138ec79946c70b97542d74cde8b43/greenlet-3.5.5-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:182de51c6b572a705f2fafaab2e783bcf7d2760940229dfe73086cbae037af3e", size = 670822, upload-time = "2026-08-10T13:40:51.833Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2d/22/c3c2eee4a8fe191d6d1d183086c56133d646024e3d70bfd414829f64560b/greenlet-3.5.5-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8fec3f165dfe332e490c3247c0f6c23b0bfc45f06496ad7f00ddb00e3d35e4dc", size = 1628469, upload-time = "2026-08-10T14:15:08.11Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f7/87/25babd09b94cb1f03e71db815fde463f0262e40cfbd953d58a8d77311351/greenlet-3.5.5-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:c6ce25fee6cabc8bf22cb8b52e642cbb821be5b9aec8094d07ff03378141b8e9", size = 1691952, upload-time = "2026-08-10T13:40:33.502Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2e/3d/5cc9701117ea4dc0eb7bf1f4f9b7888a6e2e5277ddfae095805ace50f2b6/greenlet-3.5.5-cp314-cp314-win_amd64.whl", hash = "sha256:7dffc5c859fe6059974df1e37d7923d654a83e2ae18fdd616994270e001115e1", size = 327458, upload-time = "2026-08-10T13:27:02.868Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a7/6b/594fa2de7fae7629168a404a4305d7d7e31a5742c50a801b1839543cb93d/greenlet-3.5.5-cp314-cp314-win_arm64.whl", hash = "sha256:5e2afcfc4d4305dd715809b03da5cbe437c8984f61d8917751eb5fe4aefa3e07", size = 311146, upload-time = "2026-08-10T13:27:25.046Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/24/e0/50cd600b469e5734c72709b6b1838b6bc63f307b573c772c3132d6ecfe92/greenlet-3.5.5-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:0e5a7de979d764aea1f5b6e95cf92b5b37741b9823702041f34b126e7f690277", size = 305471, upload-time = "2026-08-10T13:26:20.568Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/75/a3/77acd66dfc6387b5219b2080806c0cabb73c10eb1bb44b413c40a62015ba/greenlet-3.5.5-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fef01bd457f11fc158b130ca0027a3c365693280e8e231b65bdaf57999f39f5b", size = 672470, upload-time = "2026-08-10T14:14:39.058Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b9/71/0d178142dca3ec19f46fb2212ae73d30ad53b9d548dc64804086033a7089/greenlet-3.5.5-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5173a72310725a74afc82c164f0e52cb8ad0de62f2bb623f24f6c0cc07d80272", size = 679973, upload-time = "2026-08-10T14:27:30.072Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6e/31/46eb8567302eaf787abf88d09df014e14ae3baf460af1b8b0efdbd3efcd5/greenlet-3.5.5-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:44f08341873200ba8a60a8bc14ace3d91f1754f7fa7bc66157714a8cd420a476", size = 676634, upload-time = "2026-08-10T13:40:53.004Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a3/e9/b88bbf5b29970cb84172dc2c32aa3e5e579ceb94c808e81c826454138850/greenlet-3.5.5-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d246c0db9a2513cd45f019ba178ea4d4d4705bd210ee465e2c15d76a1ab13874", size = 1637320, upload-time = "2026-08-10T14:15:09.317Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6d/8c/7631ed29cc6f0392f11830076e172ce4885e70b0bc2c1bce1731176d4b4e/greenlet-3.5.5-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:72507285b5caa1d17904a3f7c322ca780823a54170a0e04ec3f37bcc60d4db71", size = 1697412, upload-time = "2026-08-10T13:40:34.924Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/da/0f/f7dd935f9c4cb1be49098770587f54d8a78518e55c89bce86c4fb4109057/greenlet-3.5.5-cp314-cp314t-win_amd64.whl", hash = "sha256:7805655781fb8f28a55d05fe57ed61f5f10f1892fb587673e3bb5264f28041f0", size = 331514, upload-time = "2026-08-10T13:29:20.611Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b7/e5/681b01f8fbc1b55232822f99e8f8afeb78a55a7c76a7bf9dbdc7ccb03a6d/greenlet-3.5.5-cp315-cp315-macosx_11_0_universal2.whl", hash = "sha256:c0db80fcd5b8aece93f66c64f78a786bbb6b96c5fe63ef5a5a4581ecf8bab206", size = 295975, upload-time = "2026-08-10T13:28:45.985Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/11/f2/69b488cd9e7267bf4b0fe8cdebf25d8d6df680d21bdf41150d23e23d6652/greenlet-3.5.5-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6b241c32f912ada659808d68e308c568baf577eebf757d15471472de0c18cfad", size = 666823, upload-time = "2026-08-10T14:14:40.222Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/84/d4/d5bc2fdebbdda0c94555925ba79948b8395d75a7f6a36cc85dce5bab9f11/greenlet-3.5.5-cp315-cp315-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ef6a08349401d8eaf3cb12688ac8557de95788556b8631ef17555a4a173022c0", size = 677613, upload-time = "2026-08-10T14:27:31.543Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bd/93/542d8a3a90f3b35c6ad8bf7e56a03010287f2cafa289a5b7985b5207db39/greenlet-3.5.5-cp315-cp315-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f2e3d061b8e13aec2f0441689b3c71b244a20e5d274a52cb0f7e31bd1d139552", size = 675930, upload-time = "2026-08-10T13:40:54.205Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/52/b5/89c9f2e8460d71101037d47a1feed11928615a5edd42370be290e0657eeb/greenlet-3.5.5-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:9ab5f5b93655e77fe0d6c2dfd22b5eac751bb1f876d8ec21761b7c1fb9266007", size = 1633878, upload-time = "2026-08-10T14:15:10.693Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b8/60/297de93f3b02ac78a5e04d32bb8bbe3080f4a73d8ed95016561463b70618/greenlet-3.5.5-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:f0e5a21bd4452a88cf032fc43c4a5b307ab1380eacb63b5988f9c0317885e773", size = 1696597, upload-time = "2026-08-10T13:40:36.252Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/18/25/54c6eaff4f337fb670215e89eb2d00d9499487b658e709d4b477be4a342e/greenlet-3.5.5-cp315-cp315-win_amd64.whl", hash = "sha256:469dbb0a78625642f4a626cfd0c6e8bccc0385b5e49189b6308bbe849ec88a8e", size = 327700, upload-time = "2026-08-10T13:28:06.752Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/67/67/857e88a36301caa0e029870132c2478bd55d896630321432afab03a3115f/greenlet-3.5.5-cp315-cp315-win_arm64.whl", hash = "sha256:2d57406c3efd32d7a81e17a674314e8bd00792cdab49ea3228a49aa1bfb2e769", size = 311750, upload-time = "2026-08-10T13:34:08.815Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/10/e2/3144c0a116067ac1e30457b0139a94d60d1d36a86e015de68e9ac87cb3bc/greenlet-3.5.5-cp315-cp315t-macosx_11_0_universal2.whl", hash = "sha256:68184dfcf50ccaa8e864770fe0633a7e27250ea9329f8192ef47ee9ecfd78e1c", size = 306387, upload-time = "2026-08-10T13:27:00.897Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5c/a1/cb4223a7e9b9f43b8807e8eb212358bfe2dfaa174a9ea2889eb1714dcba2/greenlet-3.5.5-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9ec0dc0e59dc9c61af5c47348365ccbbd7addfafe0a93b00336ff3da2907bdc6", size = 676472, upload-time = "2026-08-10T14:14:41.417Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9e/cd/a154b4498e5d8f12ada291cfb3b8d596eadde2177f5bf09a9be699d2a446/greenlet-3.5.5-cp315-cp315t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e604f58e35833fc46ef20302bcb314dddbfd3fcf33a4f936216d51dd678d63ae", size = 684238, upload-time = "2026-08-10T14:27:32.946Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bf/bb/b0031d260c2968a3c87deebc51d80c64e499377f993aafe06ee3b7488cc2/greenlet-3.5.5-cp315-cp315t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:40239b5384f96da3963585cc6d7eaa9b56f8ae67e8d92cc82dd9e202fc847de3", size = 681246, upload-time = "2026-08-10T13:40:55.402Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9a/07/da554b71ab88e649da146e1065d86a48a5c5d92e50ab74ef41b504aa7f56/greenlet-3.5.5-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:a1eaccf5c3a1d3e46dead602c72e6836731e8e245c9de6a27764567b6b62d4c0", size = 1642735, upload-time = "2026-08-10T14:15:11.92Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/78/76/26a3782a051677668af9d92beaa47cd87ba9dd5072f762961144a03dd4c6/greenlet-3.5.5-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:19e4e026fe20691f333b8eb1a3bc9625eceba8c3f9d62ec5a6f8581afbc6b5a5", size = 1700925, upload-time = "2026-08-10T13:40:37.656Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/28/d9/fe7baf4190c2ae71f267efb9de21b3172bb35bc0ed1ef53dd6027d658e33/greenlet-3.5.5-cp315-cp315t-win_amd64.whl", hash = "sha256:712aee154f648bde84634654bb38bb78c69ac640c37a45c9effed800735049d8", size = 331829, upload-time = "2026-08-10T13:26:48.851Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/df/af/419a4e383bd600858a9b67e9b280a60fdc383ee3f2fe5b6c0c1ef04e74d1/greenlet-3.5.5-cp315-cp315t-win_arm64.whl", hash = "sha256:7f049911ee81a16a03c33d5450d8d5867d27f596ca5fb201b86f4524e874468b", size = 315093, upload-time = "2026-08-10T13:29:34.949Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "grpcio"
|
||||
version = "1.83.1"
|
||||
@@ -2578,7 +2539,7 @@ requires-dist = [
|
||||
{ name = "redis", specifier = "~=8.1" },
|
||||
{ name = "rq", specifier = "~=2.12" },
|
||||
{ name = "sentry-sdk", specifier = "~=2.32" },
|
||||
{ name = "sqlalchemy", extras = ["mariadb-connector", "mysql-connector", "postgresql-psycopg"], specifier = "~=2.0" },
|
||||
{ name = "sqlalchemy", extras = ["mariadb-connector", "mysql-connector", "postgresql-psycopg"], specifier = "~=2.1" },
|
||||
{ name = "starlette", specifier = "~=1.7.0" },
|
||||
{ name = "streaming-form-data", specifier = "~=2.1" },
|
||||
{ name = "strsimpy", specifier = "~=0.2" },
|
||||
@@ -2677,29 +2638,48 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "sqlalchemy"
|
||||
version = "2.0.54"
|
||||
version = "2.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "greenlet", marker = "platform_machine == 'AMD64' or platform_machine == 'WIN32' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'ppc64le' or platform_machine == 'win32' or platform_machine == 'x86_64'" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/29/9c/271aa905cf2964f841371a97f3e63ab692bf51b4423d0491e67bc7f64037/sqlalchemy-2.0.54.tar.gz", hash = "sha256:baa8521e8ee9f24e75dfc7aaabc08020e551ef0d48d7c3e3536f5cddf277586b", size = 9969559, upload-time = "2026-09-15T21:06:57.337Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/ba/29/8de56a7f78fb0d71fe4f91ee43401a24ba8777e6d4f72683f268c9e0c72e/sqlalchemy-2.1.0.tar.gz", hash = "sha256:37600e4641c435a7e4549f4e6df79d9dfc096bb9712a10dba8925921bc87bc3c", size = 10502427, upload-time = "2026-09-24T20:12:49.737Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ab/c0/4a6503c9d22d6d00a5631082ab1484222ecf7d573db791e0f53161bf7745/sqlalchemy-2.0.54-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:abd6b21bc58e91c1932eb5d6d7f1bd44a551dfec7b6a7f517c3638ccd67233a0", size = 2185899, upload-time = "2026-09-15T22:29:00.581Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/12/28/f4424f618bd1f373761a32a821d53ce2c257350e9894bae9b968cb03d8fd/sqlalchemy-2.0.54-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5417322b3c025dd82918725d3bf09ec105fac95efc195722b8b06e1d9c381139", size = 3394763, upload-time = "2026-09-15T22:29:38.131Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/59/d2/7f0c77f8e042cb5f28275fea29c3080b4ac6fd4b3fdd7f59ff1ef3e28c11/sqlalchemy-2.0.54-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6f84099e4b04a5c2d44500a2a8302eee5af4bc6fee63e8c6e9cf6786e747280e", size = 3402800, upload-time = "2026-09-15T22:40:36.509Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/af/32/3eaa930bcf71d17a72587081d2706a5fb97ab3f11a7e0fb838f581f7cff1/sqlalchemy-2.0.54-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a0956dc754d3884da7fe60097110ec7a8a105d26afa2f0844468f4b1598c6912", size = 3341469, upload-time = "2026-09-15T22:29:39.682Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/eb/cc/cddb6cbd4408e5c55b3bf722be26b9d3b54d42509f901b7ecc15debd3d1f/sqlalchemy-2.0.54-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:87ba8834318b0d8dc94fc6f405d071b5c08be32a6c3fd68107fd6952ee949615", size = 3373232, upload-time = "2026-09-15T22:40:39.181Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/34/2f/9c2aa5efc642b7f3b985d13565cd1a5e78856e079ef3022796fea5180498/sqlalchemy-2.0.54-cp314-cp314-win32.whl", hash = "sha256:842540e4382472f23c79589995752648d14696a8200d0807ed8c5c59c92ade44", size = 2142018, upload-time = "2026-09-15T22:42:55.118Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e2/0b/3594f1f51769feb3022d686135dc5d8682a12345ed15ae61d0c0ca42cbee/sqlalchemy-2.0.54-cp314-cp314-win_amd64.whl", hash = "sha256:f4e8f955d13af83fb4e35c3472e5377ee22d3445eada1e5e48199588edb69835", size = 2169220, upload-time = "2026-09-15T22:42:56.727Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c3/a5/c211a9a7af83222509519407e16a4db760c6df3d03be69ebc5414d465321/sqlalchemy-2.0.54-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ca05f4e7852cf48083b0cf157e4f9504b7068780422a50fa82f45353b8c5e14a", size = 2208458, upload-time = "2026-09-15T22:30:05.718Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/cb/2e/490ad7b3731116cb48ba170f7722eaa99a89707193e54389ca84b7ad55af/sqlalchemy-2.0.54-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:18a8b6417cbb7b735cf91c2b59453c2a554cefa0a8d7bd15aa35740739410d77", size = 3660585, upload-time = "2026-09-15T22:36:06.649Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/eb/25/15dfe6814847eeda773bd58ab6cf42a94b0176e5cf25a578fc1165777160/sqlalchemy-2.0.54-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4e55a0b96a1577a1e108c91ccdeeb9cd92768f28ce206597311c3bf6d6423abd", size = 3624442, upload-time = "2026-09-15T22:36:38.377Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/aa/19/724d0a6a2fb2a86ff2d6008e581c258f722d9b7d8e52adc7b79085febdd4/sqlalchemy-2.0.54-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:69cab115c40fd02c5a22c68e4ee630fa6ef9a1650f1de944419aab1f7096fc4f", size = 3562972, upload-time = "2026-09-15T22:36:08.581Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/49/bb/9df1bd81c2f2d000cf5e7a1b1a9b331468a3aab939ad983355e701fa42b2/sqlalchemy-2.0.54-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:e08397c6c42f53b2488acde9108b8bfefd52d7afd1bf2f03d2ffcab7a204aceb", size = 3576479, upload-time = "2026-09-15T22:36:40.272Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/df/c0/b5775465d3b89061d7c46057c31c56ff8fb6c509550b2b0c6570ffc248b3/sqlalchemy-2.0.54-cp314-cp314t-win32.whl", hash = "sha256:b9086b8ad48280ef6a7ba68262d5e44f7db1c4cb1973e8cdae8a9f467ae66f51", size = 2174794, upload-time = "2026-09-15T22:31:45.925Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/77/f8/296c2e46b4ccd3f29b00b954ef2f195dde32f98e352ed21de1d292cedc0d/sqlalchemy-2.0.54-cp314-cp314t-win_amd64.whl", hash = "sha256:b67c1744e453af833667fc1b84de07adb4a64f3536ef52a8ec5ac2b941d43970", size = 2211942, upload-time = "2026-09-15T22:31:47.368Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/24/a1/bd5e3e99bc9c8863b51ac5b9b03008a7f2da8c6b59695992f5c654e1265b/sqlalchemy-2.0.54-py3-none-any.whl", hash = "sha256:7e33a631ab1474f8fe6b910bd1a07b7b8009c4c78cdd3fb18001b03e3bc2e1d2", size = 1958015, upload-time = "2026-09-15T22:24:22.95Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1f/3c/ddb9b34ff200bc1eabc713ec08b47ef250335eb50f67596d149821e4b526/sqlalchemy-2.1.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:2932efe3759b61227e8e7129d6a88261872104bfdf8a27a28bf337f26ee8a800", size = 2455656, upload-time = "2026-09-24T20:29:11.556Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5b/12/9bec32d176d3a73e1b57605f6ecef40792f5debaa9c9ebd33527661e9955/sqlalchemy-2.1.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b3dbb9eb73e16b30f40fb6f715b390fa211e402b054e2c411c58bcbeb0a9f24b", size = 4571656, upload-time = "2026-09-24T20:38:38.822Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/49/5e/26b1e3c5862aec10a69dda0b045b08b829e7168fc95a65f2a88fe35ae732/sqlalchemy-2.1.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a251e65f473e382689c8eb8d0e929b3ad4d4a831faf6e15fe28a771efb071bad", size = 4601917, upload-time = "2026-09-24T20:38:06.363Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b6/32/b36848b97b52d07680603bdd795d2fdd91db385fbbc8b9501062b5de356a/sqlalchemy-2.1.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:26b66db869257a32ecfebadac230e8008e2bf402f2bc16f9c8f2dc643fd4c9ef", size = 4501799, upload-time = "2026-09-24T20:38:40.74Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/49/3f/c33bf58d6ed24e7b297fbdbc9ea489cb990affb85e82da5bfcbae37b8009/sqlalchemy-2.1.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:3e4bf2ddee8256be3577a5e82de469c2e918b17dd6aa72270056f1de56cc18bd", size = 4561000, upload-time = "2026-09-24T20:38:08.569Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b6/47/5f09db0dd2261c8c6e86ea836fb237a1435f5003856b82ff847d2b6574a2/sqlalchemy-2.1.0-cp314-cp314-win32.whl", hash = "sha256:cbc05572d4e15a2391ea632797ac972693827efbf14218e310cf979a3d9899ce", size = 2373392, upload-time = "2026-09-24T20:36:55.563Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d5/e9/69a17bc68924490ceeff5f92b4f7c02f93c6a3e54f18bb64d8f26074014f/sqlalchemy-2.1.0-cp314-cp314-win_amd64.whl", hash = "sha256:be634518ab04942ac0af4973ab633b4e2abcf307ad3b8e064f5822fad0b44c34", size = 2423825, upload-time = "2026-09-24T20:36:57.396Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/03/cd/8edfa2c19086a2d12a985a23825bb1a90b37435d650d476655bc877ebebd/sqlalchemy-2.1.0-cp314-cp314-win_arm64.whl", hash = "sha256:12454ca5f8cfb48698f45d7bd65fc8e3ae8a1f176f2a5869d58e6bdb0dada467", size = 2388600, upload-time = "2026-09-24T20:27:56.542Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0a/4d/8986912d5220f63d5f02d9db3efd4f6ca2c9790081b7cf049f62d72e33b0/sqlalchemy-2.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:71a03ce32b84fa58efabeafee57888775dc454ca574c78461e71c68f63a327e1", size = 2495109, upload-time = "2026-09-24T20:32:10.933Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f2/92/e3471ea4ad26e2fab85a7a633211f678a96db3304e04fb0fcd55fa37c428/sqlalchemy-2.1.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0cd723c8b43c1cb81e81196f4d8dc681161fb116c3615d2896da4a8573f78985", size = 4899821, upload-time = "2026-09-24T20:30:23.073Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/85/b8/5db6a658721086d32409fc363614148c4d93104126c51beef9b7dc173b06/sqlalchemy-2.1.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f362bbd77c35e81db267c147fff927f960e7f712bdd9ac14abf61a358181d29b", size = 4810220, upload-time = "2026-09-24T20:58:29.381Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1a/0b/8f0bbb602dd4e5db3a76c81b2ea13a2b4c6907ce000098167c01785dde9d/sqlalchemy-2.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:3459ac26998cb40a2c0cc1a02630fd5f4989ce0a65b010968d485cf8ce520bc1", size = 4757967, upload-time = "2026-09-24T20:30:25.142Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/69/b8/578f67663c2377e8bd49f68000cec71ff2331884b7f721137e11e127a866/sqlalchemy-2.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:624dfe777c32f31825efe1ca7c1a56f1b4fefd4cd7b2a6b55395928ebdebeb29", size = 4748381, upload-time = "2026-09-24T20:58:32.02Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/97/ff/7fc4bdd510bb83912ac7f6eb72b02ff13c7e1064942d7f6e1667fa2ffee2/sqlalchemy-2.1.0-cp314-cp314t-win32.whl", hash = "sha256:662488315042d7ce02189c0d74f16b84437d0aedb0aa0f13d82a9d86cd4db083", size = 2431769, upload-time = "2026-09-24T20:43:50.969Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ac/b7/3ab5594f90612ae0c310e425501a804bc59a72a5c1aadfc891c19eda7f35/sqlalchemy-2.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:725686589143c64a9880d42d2df00edec7eb07b6a4ab8611adc4a9aa97c40206", size = 2499221, upload-time = "2026-09-24T20:43:52.978Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6b/a1/ed96402b6ea327cf7b13207bbbd2c21b3ba632ad931a3fd8ac82b9de41d8/sqlalchemy-2.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:c9a853fc8fd3baf5edc3efb5f5c391eb4e043020023961b29fea2181be22177b", size = 2417272, upload-time = "2026-09-24T20:28:23.619Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c4/cc/7693884478e6cdbf0145129f8933c17b8413ecaa58f6e3562c5a28ac5d6e/sqlalchemy-2.1.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:4fa46ff8493d7b43cef1a0cb37787ceca29b9acce3d869259ec5ef364088757d", size = 2455611, upload-time = "2026-09-24T20:22:44.205Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/97/de/c7e84993c6fd4030ac8dfeaafed4bdfd5e13b94b53529ed74e5f8f16edfa/sqlalchemy-2.1.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:82892cf6ecbe3cf9dcfc0a68c41363a9b805fdf6b851b85e76916ef8c6114782", size = 4575286, upload-time = "2026-09-24T20:32:08.739Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/32/05/39f9eafe8130c14040eed117c9f1f12de20bdc7bb7f9d700cb096253fde8/sqlalchemy-2.1.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1570ddca36009d2d6fb2a73d549bda0f1c187658f2f7f99ea190d30b9c73370d", size = 4610991, upload-time = "2026-09-24T20:35:33.741Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/68/4d/dd19363dddd9c5ca6cdd5634c775ed3997b02e0e193d299b15ca045d85af/sqlalchemy-2.1.0-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0a5964ef9edd33c78fd7a7064b4a866ff921dd3bdee9ee03ba36ca6d63c68c84", size = 4312176, upload-time = "2026-09-24T20:43:23.156Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d8/27/81bdf0c40e835635d97321ec5dd6aefdff0f435d7b8549a33c5df01d5194/sqlalchemy-2.1.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:9da59daf43ad6fd7a5e8412ee5d822b5ec9ed18604714d20d3974e9a0ffb48ff", size = 4505239, upload-time = "2026-09-24T20:32:10.538Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/40/72/13d869f20c60ed69d955f947bf3a04d44517a063b814e91ae5c40c9b42a9/sqlalchemy-2.1.0-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:6c524e706836aff3012e3c00cbe383ecac0ca57517677576d81ef0543c66008f", size = 4312130, upload-time = "2026-09-24T20:43:25.682Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ef/57/529a32d2771c7b9ae54c4f231fa914d777cd9f108662739505c8a1710773/sqlalchemy-2.1.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:a654cf556ba18c3aa72fa10cf857e5d7841ecc265cdd37219b40f65fe8798fca", size = 4572106, upload-time = "2026-09-24T20:35:36.017Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3e/e1/65cd4f6fe6c412b5fdb030690f5a9c7df6569541c9aaf2117bf09b31b3ad/sqlalchemy-2.1.0-cp315-cp315-win32.whl", hash = "sha256:3151754a864ed542e084a29c0ac9572547d21dae9822f0b87d6eb05746dfe456", size = 2373111, upload-time = "2026-09-24T20:27:44.814Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f3/9a/f3a6b56e03c55892c08ce0902fb661eaaddb8bca34f44419ad7b3ae6aa3e/sqlalchemy-2.1.0-cp315-cp315-win_amd64.whl", hash = "sha256:2ae5be5d075a8098e63e35d4a318576f203374406b4606685227ea51affe139a", size = 2423868, upload-time = "2026-09-24T20:27:46.268Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9c/3f/a05c420092ff112c53634be52b691ebc2760c194e831447339605e24485d/sqlalchemy-2.1.0-cp315-cp315-win_arm64.whl", hash = "sha256:548c1ed23c5b6f9a8268731d1a22fa4997c174231ded17a6feec72967e43128d", size = 2388298, upload-time = "2026-09-24T20:28:50.05Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2a/3c/2acbd3e6df0a97751bbbce69174e18a5fbd07e21f90d25761cdc9c07ea4f/sqlalchemy-2.1.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:db2179ee846697aa1a5a10ec49774b65e6f65a6222c2bcf8938b6afe06cf28b2", size = 2491296, upload-time = "2026-09-24T20:32:13.658Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/00/15/f814e5fb6039a0b12fd3b65e9ba6b21bbc35ee5cd958fc1ae87bf58426dc/sqlalchemy-2.1.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d2fdfd28b94bad614e18a00e150116c7641f6bf1b430933bf0e6b7f003576529", size = 4875881, upload-time = "2026-09-24T20:30:27.472Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6a/9a/592fa43f17349f9525bcd7229669e3daa4ad33a9c22328fa76fac1d2d651/sqlalchemy-2.1.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0a1176457cd4f002c805170c5b9881124d4b7102b521120ff04178eaeb3b5bd8", size = 4826133, upload-time = "2026-09-24T20:58:34.003Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/48/43/fa4ded1c1994fc919dea1620b4a57aa6ce9d9681910b4a4adf4a2777f8f7/sqlalchemy-2.1.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:a4ad18072fc8be8f3d8f7fda661718f98a9fedd8db0250ad67445ab78fd3d544", size = 4733475, upload-time = "2026-09-24T20:30:29.859Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8d/e3/e8a6e3f80fa37e3f22b1a62a3b3593ae9f3086bcd9a0acf93a7325e1b931/sqlalchemy-2.1.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:db734efaca2f473782afc6887fd07f00fea28b6c27e125a20031085a8016fbd2", size = 4753043, upload-time = "2026-09-24T20:58:35.995Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e5/c7/8cb7dbf86730c5eadcfca84ed1ece380bf8779929fec91f830090ad5833b/sqlalchemy-2.1.0-cp315-cp315t-win32.whl", hash = "sha256:41f8e7ffb0533dd494f2e20cdfa13b33e7655ec06810e7630fcf12cd9e14bb48", size = 2428549, upload-time = "2026-09-24T20:43:55.676Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6d/8e/b74b58ca5c9e46605707b67093b07fe5dfe1177c3992f86fb5282d5f10b7/sqlalchemy-2.1.0-cp315-cp315t-win_amd64.whl", hash = "sha256:3a7154222e0c31434bd125145415a748d09a132360be7124b529a23ebed7fa31", size = 2494250, upload-time = "2026-09-24T20:43:57.585Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b3/03/188a5fb7786e9bd8922a452af5e22ea5df7bb438da28a0306981dc7e1d8c/sqlalchemy-2.1.0-cp315-cp315t-win_arm64.whl", hash = "sha256:aa60028a966361ac285bfd7e10fb3389b679218dd39c8e5ea54eba28ab763e48", size = 2413092, upload-time = "2026-09-24T20:28:25.185Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/25/8a/9178cd9411c57f16a1e73b0a75bca9270cd471aafdccae2dd8b0b491c9bd/sqlalchemy-2.1.0-py3-none-any.whl", hash = "sha256:8728cbc7544d05c5cab9bf50749636f128e4db4828a20ce5952355c4f33d6e2e", size = 2047583, upload-time = "2026-09-24T20:36:44.055Z" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
|
||||
Reference in New Issue
Block a user