mirror of
https://github.com/rommapp/romm.git
synced 2026-12-04 12:52:19 +01:00
* refactor(adapters): send provider requests through httpx2 The metadata provider adapters (IGDB, ScreenScraper, MobyGames, RetroAchievements, Steam, SteamGridDB, libretro thumbnails) used aiohttp while the rest of the backend used httpx2. They now share the request's httpx2 client through `send_request` in provider_http.py, which bounds the whole exchange with one timeout and follows redirects, as aiohttp did. Each provider's auth middleware becomes an httpx2.Auth flow. aiohttp was adopted because httpx logged request URLs carrying API keys at INFO. The log formatter now masks every credential parameter those URLs carry, so that reason no longer holds. Behavior changes: - Provider requests go through the SSRF-guarded client. Only tests ever pointed a provider at a custom base URL. - A dropped connection is no longer resent once by the client; it surfaces as the existing 503. - SteamGridDB's default base URL is www.steamgriddb.com. The bare domain answers with a cross-host 301, and httpx2 drops the Authorization header on that hop. aiohttp, its OpenTelemetry instrumentation, and the packages only aiohttp needed (aiohappyeyeballs, aiosignal, attrs, frozenlist) leave the lockfile. The scripted test server becomes an httpx2.MockTransport, and the aiohttp-recorded cassettes are adapted to what httpx2 sends: masked credentials in the query, empty bodies as "", and no stale gzip Content-Encoding headers on already-decompressed bodies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(logging): keep provider API keys out of Sentry The log formatter masks credential query parameters on stdout, but Sentry's logging integration reads the raw record before any handler formats it. Two paths sent provider keys to Sentry when SENTRY_DSN is set: - httpx2's INFO request line, which carries the authenticated URL, as a breadcrumb in the web process. - An adapter's `log.error(exc)` on an error status, since an HTTPStatusError's message carries the same URL, as an event in the web and worker processes. The `romm` logger now masks the record itself in a filter, which runs before handlers and Sentry's hook. httpx2's request lines are no longer emitted. Sentry's before_send and before_breadcrumb mask every string in a payload, which covers exceptions captured directly, including their messages and stack locals. The masking regex also stops at a single quote, so httpx2's quoted URLs keep their closing quote. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: code-review Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: simplify Set the RomM user agent and convert httpx2 timeouts to TimeoutError in send_request, so adapters drop their copies and send_with_retries catches a single timeout type. Read the ScreenScraper status code once in _handle_client_error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: review-polish Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: prose Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: prose (code-review follow-up) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(logging): keep the log template when redacting a record RedactFilter replaced msg with the formatted text and dropped args, so Sentry grouped each redacted URL or game id as its own issue. It now redacts the template and each argument in place, and falls back to the flat text only when a secret spans the template and an argument. pprint records keep their structured msg. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(screenscraper): pin dev credentials for the cassette tests The cassettes now record devid and devpassword, since httpx2's auth flow runs before VCR sees the request. CI has no developer credentials, so the requests carried a blank devid= that VCR drops when matching, and all seven integration tests failed to find their recording. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
146 lines
5.4 KiB
Python
146 lines
5.4 KiB
Python
import json
|
|
from html.parser import HTMLParser
|
|
from typing import cast
|
|
from urllib.parse import quote, unquote
|
|
|
|
import httpx2
|
|
import yarl
|
|
|
|
from adapters.services.libretro_thumbnails_types import LibretroArtType
|
|
from adapters.services.provider_http import send_request
|
|
from handler.redis_handler import async_cache
|
|
from logger.logger import log
|
|
|
|
LIBRETRO_THUMBNAIL_ROOT = "https://thumbnails.libretro.com"
|
|
LIBRETRO_LISTING_CACHE_KEY = "romm:libretro:listing"
|
|
LIBRETRO_LISTING_CACHE_TTL = 60 * 60 * 24 # 24 hours
|
|
# Not every system has every art type, so misses are cached too, on a shorter
|
|
# TTL in case the directory is added upstream later.
|
|
LIBRETRO_MISSING_LISTING_CACHE_TTL = 60 * 60 # 1 hour
|
|
# Statuses that mean the directory isn't there, as opposed to a request that
|
|
# could succeed on a retry (429, 408, 403, 5xx).
|
|
LIBRETRO_MISSING_LISTING_STATUSES = frozenset({404, 410})
|
|
LIBRETRO_LISTING_TIMEOUT = 60 # seconds
|
|
LIBRETRO_HEAD_TIMEOUT = 10 # seconds
|
|
|
|
|
|
class _AnchorHrefParser(HTMLParser):
|
|
"""Collects filenames from href attributes of <a> tags in an Apache autoindex page."""
|
|
|
|
def __init__(self) -> None:
|
|
super().__init__()
|
|
self.filenames: list[str] = []
|
|
|
|
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
if tag != "a":
|
|
return
|
|
for name, value in attrs:
|
|
if name != "href" or not value:
|
|
continue
|
|
# Skip sort/parent/query links exposed by Apache autoindex.
|
|
if value.startswith(("?", "/", "#")) or ".." in value:
|
|
return
|
|
# Only keep image files, since libretro stores PNGs.
|
|
decoded = unquote(value)
|
|
if decoded.lower().endswith((".png", ".jpg", ".jpeg", ".webp")):
|
|
self.filenames.append(decoded)
|
|
return
|
|
|
|
|
|
class LibretroThumbnailsService:
|
|
"""Service to interact with the libretro thumbnail server.
|
|
|
|
The server hosts Apache-style directory listings of per-system PNG art at
|
|
https://thumbnails.libretro.com/{System}/{Named_Boxarts|Named_Titles|Named_Logos|Named_Snaps}/
|
|
"""
|
|
|
|
def __init__(self, base_url: str | None = None) -> None:
|
|
self.url = yarl.URL(base_url or LIBRETRO_THUMBNAIL_ROOT)
|
|
|
|
@staticmethod
|
|
def _cache_key(system_name: str, art_type: LibretroArtType) -> str:
|
|
return f"{LIBRETRO_LISTING_CACHE_KEY}:{system_name}:{art_type.value}"
|
|
|
|
@staticmethod
|
|
def build_art_url(
|
|
system_name: str, art_type: LibretroArtType, filename: str
|
|
) -> str:
|
|
subdir = f"{system_name}/{art_type.value}"
|
|
return (
|
|
f"{LIBRETRO_THUMBNAIL_ROOT}/{quote(subdir, safe='/')}"
|
|
f"/{quote(filename, safe='')}"
|
|
)
|
|
|
|
async def fetch_listing(
|
|
self, system_name: str, art_type: LibretroArtType
|
|
) -> list[str]:
|
|
"""Return the list of art filenames for a given system + art type.
|
|
|
|
Cached in Redis with a 24h TTL to avoid hammering the libretro server.
|
|
"""
|
|
cache_key = self._cache_key(system_name, art_type)
|
|
|
|
cached = await async_cache.get(cache_key)
|
|
if cached:
|
|
try:
|
|
return cast(list[str], json.loads(cached))
|
|
except json.JSONDecodeError:
|
|
log.warning("Invalid cached libretro listing for %s", cache_key)
|
|
|
|
subdir = f"{system_name}/{art_type.value}"
|
|
url = f"{self.url}/{quote(subdir, safe='/')}/?F=2"
|
|
|
|
try:
|
|
res = await send_request(
|
|
"GET",
|
|
url,
|
|
request_timeout=LIBRETRO_LISTING_TIMEOUT,
|
|
)
|
|
res.raise_for_status()
|
|
body = res.text
|
|
except httpx2.HTTPStatusError as exc:
|
|
status = exc.response.status_code
|
|
log.warning(
|
|
"Libretro listing request failed with status %s for URL: %s",
|
|
status,
|
|
url,
|
|
)
|
|
# An absent directory won't reappear between ROMs of the same
|
|
# platform, so remember it. Anything retryable stays uncached.
|
|
if status in LIBRETRO_MISSING_LISTING_STATUSES:
|
|
await self._cache_listing(
|
|
cache_key, [], ttl=LIBRETRO_MISSING_LISTING_CACHE_TTL
|
|
)
|
|
return []
|
|
# send_request raises every timeout as a bare TimeoutError, not an HTTPError.
|
|
except (httpx2.HTTPError, TimeoutError) as exc:
|
|
log.warning("Libretro listing request failed for URL %s: %s", url, exc)
|
|
return []
|
|
|
|
parser = _AnchorHrefParser()
|
|
parser.feed(body)
|
|
filenames = parser.filenames
|
|
|
|
await self._cache_listing(cache_key, filenames, ttl=LIBRETRO_LISTING_CACHE_TTL)
|
|
|
|
return filenames
|
|
|
|
@staticmethod
|
|
async def _cache_listing(cache_key: str, filenames: list[str], *, ttl: int) -> None:
|
|
try:
|
|
await async_cache.set(cache_key, json.dumps(filenames), ex=ttl)
|
|
except Exception as exc: # pragma: no cover - cache is best-effort
|
|
log.warning("Failed to cache libretro listing %s: %s", cache_key, exc)
|
|
|
|
async def head(self) -> bool:
|
|
"""Lightweight connectivity check against the thumbnail server root."""
|
|
try:
|
|
res = await send_request(
|
|
"HEAD",
|
|
str(self.url),
|
|
request_timeout=LIBRETRO_HEAD_TIMEOUT,
|
|
)
|
|
return res.status_code < 500
|
|
except (httpx2.HTTPError, TimeoutError):
|
|
return False
|