refactor(screenscraper): report a short-circuited lookup per rom

A tripped breaker answers in ScreenScraper's place, so the empty match it
produces is not a miss and must not clear the rom's stored ss_id. The scan
learned that by sampling the module-wide is_breaker_tripped() at three points,
which reads another rom's trip as this rom's evidence.

SSHandler now raises ScreenScraperExhaustedError instead of swallowing the
breaker's error, carrying the match it would have returned so the name the
filename lookup derives locally (Switch title database, MAME, PS2 OPL) still
reaches the scan. fetch_ss_rom catches it the way it already catches
ScreenScraperRateLimitError, and drops ScreenScraper from attempted_sources
from a plain local, so the signal is exactly this rom's own lookups.

Also folds in a cleanup pass over the branch: the dead default_factory arm in
_ScanState.reset(), one home for the ssuserInfos.php path, asyncio.wait_for
around the quota probe so it cannot block behind a media download holding the
concurrency slot, and shared fixtures for the ScreenScraper tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-09-06 21:35:25 -04:00
parent 63d58ab65e
commit 6161f8057d
7 changed files with 382 additions and 492 deletions

View File

@@ -6,7 +6,7 @@ import re
import time
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import MISSING, dataclass, fields
from dataclasses import dataclass, fields
from math import isclose
from typing import Final, cast
from urllib.parse import urlparse
@@ -75,9 +75,12 @@ SS_LOW_QUOTA_FRACTION: Final[float] = 0.1
# scrape allowance is refused this many times before the provider is taken out.
SS_QUOTA_TRIP_THRESHOLD: Final[int] = 2
# The account endpoint costs no quota, so an armed breaker can afford to re-check
# it this often. The check is opportunistic, hence the short timeout.
SS_QUOTA_RECHECK_SECONDS: Final[float] = 60
# Free of the daily quota, which is what lets an armed breaker use it as a probe.
SS_ACCOUNT_ENDPOINT: Final[str] = "ssuserInfos.php"
# How often an armed breaker re-checks the account. The check is opportunistic,
# hence the short timeout.
SS_QUOTA_RECHECK_SECONDS: Final[int] = 60
SS_QUOTA_RECHECK_TIMEOUT: Final[int] = 30
# Whose allowance was spent is left open on purpose: a refused password gets the
@@ -232,8 +235,7 @@ class _ScanState:
def reset(self) -> None:
for f in fields(self):
factory = f.default_factory
setattr(self, f.name, f.default if factory is MISSING else factory())
setattr(self, f.name, f.default)
_state = _ScanState()
@@ -324,7 +326,7 @@ def _credential_set(url: str, message: str) -> SSCredentialSet:
if "développeur" in message.lower():
return SSCredentialSet.DEVELOPER
if "ssuserInfos.php" in url:
if SS_ACCOUNT_ENDPOINT in url:
return SSCredentialSet.USER
return SSCredentialSet.DEVELOPER
@@ -507,8 +509,8 @@ def _is_low(remaining: int | None, allowance: int | None) -> bool:
def _warn_on_low_quota(limits: SSAccountLimits) -> None:
"""Flag a daily allowance running out, rather than waiting for the refusal.
The two get their own one-shot: the submission allowance is an order of
magnitude smaller, so it would otherwise consume the scrape quota's advisory.
Each allowance gets its own one-shot, so the much smaller submission quota
does not consume the scrape quota's advisory.
"""
if not _state.logged_low_quota_warning and _is_low(
limits.remaining_requests, limits.max_requests_per_day
@@ -722,9 +724,6 @@ class ScreenScraperService:
async def _recheck_daily_quota(self) -> bool:
"""Ask the free account endpoint whether the scrape allowance is back.
Goes through ``_attempt_request`` rather than ``_request`` so it bypasses
the very breaker it is checking.
Returns:
True when the breaker was cleared and the caller may proceed.
"""
@@ -736,28 +735,31 @@ class ScreenScraperService:
# from probing at once: read-then-write with no await is atomic here.
_state.quota_recheck_at = now + SS_QUOTA_RECHECK_SECONDS
url = str(self.url.joinpath("ssuserInfos.php"))
url = str(self.url.joinpath(SS_ACCOUNT_ENDPOINT))
credentials_before = _state.credentials_rejected
limits_before = _state.account_limits
try:
await self._attempt_request(url, SS_QUOTA_RECHECK_TIMEOUT)
# _attempt_request rather than _request, to bypass the breaker being
# checked. wait_for bounds the wait for a concurrency slot too, which
# a media download can hold for minutes.
await asyncio.wait_for(
self._attempt_request(url, SS_QUOTA_RECHECK_TIMEOUT),
SS_QUOTA_RECHECK_TIMEOUT,
)
except (
HTTPException,
TimeoutError,
aiohttp.ClientError,
json.JSONDecodeError,
) as exc:
# The re-check reports, but it never arms a breaker of its own: a 403
# here would take the provider out for good, since nothing outside a
# scan clears the credentials breaker.
# Restored because nothing outside a scan clears the credentials
# breaker, so a 403 here would take the provider out for good.
_state.credentials_rejected = credentials_before
log.debug("ScreenScraper: could not re-check the daily quota (%s)", exc)
return False
# Only a readable reading this probe brought back is evidence. A body
# with no ssuser block leaves the module's limits at their pre-wall
# value, which still shows the headroom the account had before it ran
# out; one whose counters are missing or unparseable reports nothing.
# Only a reading this probe brought back is evidence: the pre-wall limits
# still show the headroom the account had before it ran out.
limits = _state.account_limits
remaining = limits.remaining_requests if limits is not None else None
if limits is limits_before or not remaining:
@@ -828,7 +830,7 @@ class ScreenScraperService:
Reference: https://api.screenscraper.fr/webapi2.php#ssuserInfos
"""
url = self.url.joinpath("ssuserInfos.php")
url = self.url.joinpath(SS_ACCOUNT_ENDPOINT)
return await self._request(str(url))
async def get_infra_info(self) -> dict:

View File

@@ -82,7 +82,11 @@ from handler.metadata import (
scene_id_or_none,
)
from handler.metadata.launchbox_handler.media import populate_rom_specific_paths
from handler.metadata.ss_handler import add_ss_auth_to_url, get_preferred_media_types
from handler.metadata.ss_handler import (
ScreenScraperExhaustedError,
add_ss_auth_to_url,
get_preferred_media_types,
)
from handler.rom_conversion import promote_single_file_to_folder
from handler.scan_handler import (
MetadataSource,
@@ -2073,7 +2077,10 @@ async def update_rom(
cleaned_data.update({"moby_id": None, "moby_metadata": {}})
if cleaned_data["ss_id"] and int(cleaned_data["ss_id"]) != rom.ss_id:
ss_rom = await meta_ss_handler.get_rom_by_id(rom, cleaned_data["ss_id"])
try:
ss_rom = await meta_ss_handler.get_rom_by_id(rom, cleaned_data["ss_id"])
except ScreenScraperExhaustedError as exc:
ss_rom = exc.fallback
if ss_rom.get("ss_id"):
cleaned_data.update(ss_rom)
elif rom.ss_id and not cleaned_data["ss_id"]:

View File

@@ -254,12 +254,10 @@ def _is_daily_quota_error(exc: HTTPException) -> bool:
def _is_provider_exhausted(exc: HTTPException) -> bool:
"""True for the errors that take ScreenScraper out for the rest of the scan.
"""True for the errors a breaker raises in ScreenScraper's place.
Both an exhausted daily quota and a refused credential set trip a breaker in
the service, so the remaining ROMs short-circuit. The scan carries on with
the other providers rather than failing over a provider that has already said
everything it is going to say.
the service, so the request never went out and the answer is not ScreenScraper's.
"""
return _is_daily_quota_error(exc) or isinstance(exc, ScreenScraperCredentialsError)
@@ -340,6 +338,19 @@ class SSRom(BaseRom):
ss_metadata: NotRequired[SSMetadata]
class ScreenScraperExhaustedError(Exception):
"""A breaker answered this lookup, so ScreenScraper itself never saw it.
Carries the match the lookup would otherwise have returned, which still holds
whatever the handler derived locally (a name from the Switch title database,
a MAME index, a PS2 OPL tag).
"""
def __init__(self, fallback: SSRom):
super().__init__("ScreenScraper short-circuited the lookup")
self.fallback = fallback
def _get_rom_type(file: RomFile) -> str:
if not file.is_top_level:
return "dossier"
@@ -873,11 +884,9 @@ class SSHandler(MetadataHandler):
rom_type=_get_rom_type(first_file),
)
except HTTPException as exc:
# Quota exhausted or credentials refused: skip ScreenScraper for this
# ROM so the scan falls back to the other providers.
if not _is_provider_exhausted(exc):
raise
return SSRom(ss_id=None), False
raise ScreenScraperExhaustedError(SSRom(ss_id=None)) from exc
if not res:
return SSRom(ss_id=None), False
@@ -996,11 +1005,9 @@ class SSHandler(MetadataHandler):
terms[-1], platform_ss_id, split_game_name=True
)
except HTTPException as exc:
# Quota exhausted or credentials refused: fall back to the name-only
# match (if any).
if not _is_provider_exhausted(exc):
raise
return fallback_rom
raise ScreenScraperExhaustedError(fallback_rom) from exc
if not res or not res.get("id"):
return fallback_rom
@@ -1014,11 +1021,9 @@ class SSHandler(MetadataHandler):
try:
res = await self.ss_service.get_game_info(game_id=ss_id)
except HTTPException as exc:
# Quota exhausted or credentials refused: return an empty match rather
# than failing.
if not _is_provider_exhausted(exc):
raise
return SSRom(ss_id=None)
raise ScreenScraperExhaustedError(SSRom(ss_id=None)) from exc
if not res:
return SSRom(ss_id=None)
@@ -1028,7 +1033,12 @@ class SSHandler(MetadataHandler):
if not self.is_enabled():
return None
game_rom = await self.get_rom_by_id(rom, ss_id)
try:
game_rom = await self.get_rom_by_id(rom, ss_id)
except ScreenScraperExhaustedError:
# A manual match wants the providers that can still answer, not this.
return None
return game_rom if game_rom.get("ss_id", "") else None
async def get_matched_roms_by_name(
@@ -1046,8 +1056,8 @@ class SSHandler(MetadataHandler):
system_id=platform_ss_id,
)
except HTTPException as exc:
# The caller gathers every provider without return_exceptions, so
# raising here would lose the other providers' matches too.
# A provider that has said everything it is going to say contributes
# no matches; it is not a failed search.
if not _is_provider_exhausted(exc):
raise
return []

View File

@@ -6,10 +6,7 @@ from typing import Any
import pydash
import socketio # type: ignore
from adapters.services.screenscraper import (
ScreenScraperRateLimitError,
is_breaker_tripped,
)
from adapters.services.screenscraper import ScreenScraperRateLimitError
from config.config_manager import config_manager as cm
from endpoints.responses.rom import SimpleRomSchema
from handler.database import db_platform_handler, db_rom_handler
@@ -65,6 +62,7 @@ from handler.metadata.ra_handler import RA_PLATFORM_LIST, RAGameRom
from handler.metadata.sgdb_handler import SGDBRom
from handler.metadata.ss_handler import (
SCREENSAVER_PLATFORM_LIST,
ScreenScraperExhaustedError,
SSRom,
add_ss_auth_to_url,
get_preferred_media_types,
@@ -592,11 +590,6 @@ async def scan_rom(
# no id for it never enters the set, so a rescan can't clear what it can't redo.
attempted_sources: set[MetadataSource] = set()
# Sampled where ScreenScraper is consulted, because its breaker re-checks the
# account and can clear itself while this rom is still gathering the other
# providers.
ss_breaker_tripped = False
def resolve_fetch(source: MetadataSource, result: Any, fallback: Any) -> Any:
"""Unwrap a gathered lookup, falling back to an empty match when it failed."""
if not isinstance(result, BaseException):
@@ -952,8 +945,6 @@ async def scan_rom(
return MobyGamesRom(moby_id=None)
async def fetch_ss_rom(playmatch_rom: PlaymatchRomMatch) -> SSRom:
nonlocal ss_breaker_tripped
if (
MetadataSource.SS in metadata_sources
and platform.ss_id
@@ -969,10 +960,9 @@ async def scan_rom(
)
):
attempted_sources.add(MetadataSource.SS)
ss_breaker_tripped = ss_breaker_tripped or is_breaker_tripped()
# One refusal means the per-minute budget is already spent, so give
# up on this ROM rather than spending another retried request (and
# its backoff) on the fallback lookups.
# A breaker answering in ScreenScraper's place rules nothing out for
# this rom, whichever of the lookups below it short-circuits.
short_circuited = False
try:
# Use the ID to refetch metadata
if scan_type == ScanType.UPDATE and rom.ss_id:
@@ -990,22 +980,35 @@ async def scan_rom(
)
# Use the file hashes for lookup
game_by_hash, is_not_game = await meta_ss_handler.lookup_rom(
rom, platform.ss_id, get_match_files()
)
if game_by_hash.get("ss_id") or is_not_game:
return game_by_hash
try:
game_by_hash, is_not_game = await meta_ss_handler.lookup_rom(
rom, platform.ss_id, get_match_files()
)
except ScreenScraperExhaustedError:
# The filename lookup below still derives a name for some
# platforms, and the breaker can clear before it runs.
short_circuited = True
else:
if game_by_hash.get("ss_id") or is_not_game:
return game_by_hash
# Fallback to the filename
return await meta_ss_handler.get_rom(
rom, rom_attrs["fs_name"], platform_ss_id=platform.ss_id
)
except ScreenScraperExhaustedError as exc:
short_circuited = True
return exc.fallback
except ScreenScraperRateLimitError:
# One refusal means the per-minute budget is already spent, so
# give up on this ROM rather than spending another retried
# request (and its backoff) on the fallback lookups.
note_rate_limited_rom(rom_attrs["fs_name"])
attempted_sources.discard(MetadataSource.SS)
short_circuited = True
return SSRom(ss_id=None)
finally:
ss_breaker_tripped = ss_breaker_tripped or is_breaker_tripped()
if short_circuited:
attempted_sources.discard(MetadataSource.SS)
return SSRom(ss_id=None)
@@ -1162,11 +1165,6 @@ async def scan_rom(
)
]
# Once a ScreenScraper breaker trips, the remaining lookups answer empty
# without asking, so it has ruled nothing out for this rom either.
if ss_breaker_tripped or is_breaker_tripped():
attempted_sources.discard(MetadataSource.SS)
(
igdb_handler_rom,
moby_handler_rom,

View File

@@ -12,6 +12,7 @@ from fastapi import HTTPException, status
import adapters.services.screenscraper as ss_module
from adapters.services.screenscraper import (
LOGIN_ERROR_CHECK,
SS_ACCOUNT_ENDPOINT,
SS_DEFAULT_MAX_THREADS,
SS_DEFAULT_MEDIA_TIMEOUT,
SS_MAX_MEDIA_TIMEOUT,
@@ -46,6 +47,75 @@ UNTHROTTLED_RATE = 10_000
SS_LOGIN_ERROR_BODY = "Erreur de login : Vérifier les identifiants utilisateurs !"
SS_DEV_ERROR_BODY = "Erreur de login : Vérifier vos identifiants développeur !"
ACCOUNT_URL = "https://api.screenscraper.fr/api2/ssuserInfos.php"
GAME_URL = "https://api.screenscraper.fr/api2/jeuInfos.php"
@pytest.fixture
def service():
return ScreenScraperService()
@pytest.fixture
def mock_log(monkeypatch):
"""Capture what the module logs, so one-shot advisories can be counted."""
log = MagicMock()
monkeypatch.setattr(ss_module, "log", log)
return log
def _session(*responses) -> tuple[AsyncMock, MagicMock]:
"""A patched aiohttp session answering the given responses in order.
A lone response is repeatable; an exception is always raised rather than
returned, and a lone one is not repeated.
"""
session = AsyncMock()
if len(responses) == 1 and not isinstance(responses[0], BaseException):
session.get.return_value = responses[0]
else:
session.get.side_effect = list(responses)
context = MagicMock()
context.get.return_value = session
return session, context
def _ok_response(payload: dict) -> MagicMock:
"""A 200 carrying the given JSON body."""
response = MagicMock()
response.text = AsyncMock(return_value=json.dumps(payload))
response.json = AsyncMock(return_value=payload)
response.raise_for_status.return_value = None
return response
def _forbidden_response(body: str = SS_LOGIN_ERROR_BODY) -> MagicMock:
"""A response whose body carries the login error, as a 403 does."""
response = MagicMock()
response.text = AsyncMock(return_value=body)
response.json = AsyncMock(return_value={})
response.raise_for_status.side_effect = aiohttp.ClientResponseError(
request_info=MagicMock(),
history=(),
status=http.HTTPStatus.FORBIDDEN,
message="Forbidden",
)
return response
def _ssuser_response(**fields: str) -> dict:
return {"response": {"ssuser": dict(fields)}}
def _account(**fields: str) -> MagicMock:
"""A 200 from the account endpoint, carrying the given quota counters."""
return _ok_response(_ssuser_response(**fields))
def _client_error(status_code: int) -> aiohttp.ClientResponseError:
return aiohttp.ClientResponseError(
request_info=MagicMock(), history=(), status=status_code
)
def _rendered(mock_call) -> str:
@@ -1251,37 +1321,9 @@ class TestCredentialErrors:
scraping endpoint is always about RomM's own credentials, whatever the body
happens to say."""
@pytest.fixture
def service(self):
return ScreenScraperService()
def _forbidden_response(self, body: str = SS_LOGIN_ERROR_BODY) -> MagicMock:
"""A response whose body carries the login error, as a 403 does."""
response = MagicMock()
response.text = AsyncMock(return_value=body)
response.json = AsyncMock(return_value={})
response.raise_for_status.side_effect = aiohttp.ClientResponseError(
request_info=MagicMock(),
history=(),
status=http.HTTPStatus.FORBIDDEN,
message="Forbidden",
)
return response
def _session(self, *responses) -> tuple[AsyncMock, MagicMock]:
session = AsyncMock()
if len(responses) == 1:
session.get.return_value = responses[0]
else:
session.get.side_effect = list(responses)
context = MagicMock()
context.get.return_value = session
return session, context
@pytest.mark.asyncio
async def test_the_account_endpoint_reports_the_account_sign_in(self, service):
_, context = self._session(self._forbidden_response())
_, context = _session(_forbidden_response())
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(ScreenScraperCredentialsError) as exc_info:
@@ -1294,7 +1336,7 @@ class TestCredentialErrors:
@pytest.mark.asyncio
async def test_a_scraping_endpoint_reports_romms_own_credentials(self, service):
_, context = self._session(self._forbidden_response(SS_DEV_ERROR_BODY))
_, context = _session(_forbidden_response(SS_DEV_ERROR_BODY))
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(ScreenScraperCredentialsError) as exc_info:
@@ -1307,7 +1349,7 @@ class TestCredentialErrors:
async def test_the_developer_credentials_are_never_named(self, service):
"""Their values are only semi-protected, so nothing sends an end user
looking for them."""
_, context = self._session(self._forbidden_response(SS_DEV_ERROR_BODY))
_, context = _session(_forbidden_response(SS_DEV_ERROR_BODY))
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(ScreenScraperCredentialsError) as exc_info:
@@ -1320,7 +1362,7 @@ class TestCredentialErrors:
async def test_a_scraping_refusal_is_not_blamed_on_the_account(self, service):
"""ScreenScraper says "utilisateurs" from endpoints that never check the
account password, so the endpoint settles it rather than the wording."""
_, context = self._session(self._forbidden_response())
_, context = _session(_forbidden_response())
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(ScreenScraperCredentialsError) as exc_info:
@@ -1332,8 +1374,8 @@ class TestCredentialErrors:
async def test_the_body_is_read_before_the_status_is_raised(self, service):
"""The regression: the login-error check sat after raise_for_status(), so
it could never match the 403 it was written for."""
response = self._forbidden_response()
_, context = self._session(response)
response = _forbidden_response()
_, context = _session(response)
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(ScreenScraperCredentialsError) as exc_info:
@@ -1347,8 +1389,8 @@ class TestCredentialErrors:
async def test_credentials_are_masked_in_the_reported_message(self, service):
"""The message reaches the caller, and the credentials ride in the query
string ScreenScraper is free to quote back."""
_, context = self._session(
self._forbidden_response(
_, context = _session(
_forbidden_response(
"Erreur de login : ssid=user1&sspassword=hunter2&devpassword=s3cret"
)
)
@@ -1362,7 +1404,7 @@ class TestCredentialErrors:
@pytest.mark.asyncio
async def test_forbidden_without_a_body_still_names_a_set(self, service):
_, context = self._session(self._forbidden_response(""))
_, context = _session(_forbidden_response(""))
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(ScreenScraperCredentialsError) as exc_info:
@@ -1373,7 +1415,7 @@ class TestCredentialErrors:
@pytest.mark.asyncio
async def test_rejected_credentials_are_not_retried(self, service):
"""Nothing about a wrong password clears on a second attempt."""
session, context = self._session(self._forbidden_response())
session, context = _session(_forbidden_response())
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(ScreenScraperCredentialsError):
@@ -1383,8 +1425,8 @@ class TestCredentialErrors:
@pytest.mark.asyncio
async def test_forbidden_on_the_retry_attempt_is_reported(self, service):
session, context = self._session(
aiohttp.ServerTimeoutError("Timeout"), self._forbidden_response()
session, context = _session(
aiohttp.ServerTimeoutError("Timeout"), _forbidden_response()
)
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
@@ -1396,7 +1438,7 @@ class TestCredentialErrors:
@pytest.mark.asyncio
async def test_later_requests_short_circuit(self, service):
"""Every remaining ROM would be refused the same way, so stop asking."""
session, context = self._session(self._forbidden_response())
session, context = _session(_forbidden_response())
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(ScreenScraperCredentialsError):
@@ -1410,7 +1452,7 @@ class TestCredentialErrors:
async def test_the_failure_is_logged_once(self, service, monkeypatch):
mock_log = MagicMock()
monkeypatch.setattr(ss_module, "log", mock_log)
_, context = self._session(self._forbidden_response())
_, context = _session(_forbidden_response())
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
for _ in range(2):
@@ -1425,7 +1467,7 @@ class TestCredentialErrors:
@pytest.mark.asyncio
async def test_a_new_scan_asks_again(self, service):
"""Credentials are read at startup, so a restart is what clears this."""
_, context = self._session(self._forbidden_response())
_, context = _session(_forbidden_response())
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(ScreenScraperCredentialsError):
@@ -1437,7 +1479,7 @@ class TestCredentialErrors:
ok_response.text = AsyncMock(return_value="{}")
ok_response.json = AsyncMock(return_value={"response": {}})
ok_response.raise_for_status.return_value = None
session, context = self._session(ok_response)
session, context = _session(ok_response)
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
assert await service._request(
@@ -1449,66 +1491,40 @@ class TestCredentialErrors:
class TestSubmissionLimit:
"""HTTP 431 is two things at once: this ROM did not match, and the account has
proposed its daily maximum of unknown ROMs to ScreenScraper's moderation
queue. Only the first affects the scan, so it is a not-found that costs a
contribution, never a reason to stop scraping."""
proposed its daily maximum of unknown ROMs for review. Only the first affects
the scan, so it is a not-found that costs a contribution."""
@pytest.fixture
def service(self):
return ScreenScraperService()
@staticmethod
def _refused() -> aiohttp.ClientResponseError:
return _client_error(431)
def _session(self, *responses) -> tuple[AsyncMock, MagicMock]:
session = AsyncMock()
session.get.side_effect = list(responses)
context = MagicMock()
context.get.return_value = session
return session, context
def _refused(self) -> aiohttp.ClientResponseError:
return aiohttp.ClientResponseError(
request_info=MagicMock(), history=(), status=431
)
def _matched(self) -> MagicMock:
response = MagicMock()
response.text = AsyncMock(return_value='{"response": {"jeu": {"id": "1"}}}')
response.json = AsyncMock(return_value={"response": {"jeu": {"id": "1"}}})
response.raise_for_status.return_value = None
return response
@staticmethod
def _matched() -> MagicMock:
return _ok_response({"response": {"jeu": {"id": "1"}}})
@pytest.mark.asyncio
async def test_the_next_rom_still_scrapes(self, service):
"""The whole defect in one test: an unmatched ROM must not cost the scan
every ROM that would have matched."""
session, context = self._session(self._refused(), self._matched())
session, context = _session(self._refused(), self._matched())
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
assert (
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
== {}
)
assert await service._request(
"https://api.screenscraper.fr/api2/jeuInfos.php"
) == {"response": {"jeu": {"id": "1"}}}
assert await service._request(GAME_URL) == {}
assert await service._request(GAME_URL) == {
"response": {"jeu": {"id": "1"}}
}
assert session.get.call_count == 2
assert ss_module.is_breaker_tripped() is False
@pytest.mark.asyncio
async def test_the_lost_contribution_is_reported_once(self, service, monkeypatch):
async def test_the_lost_contribution_is_reported_once(self, service, mock_log):
"""Every unmatched ROM in a scan gets the same 431, so say it once."""
mock_log = MagicMock()
monkeypatch.setattr(ss_module, "log", mock_log)
session, context = self._session(*(self._refused() for _ in range(4)))
session, context = _session(*(self._refused() for _ in range(4)))
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
for _ in range(4):
assert (
await service._request(
"https://api.screenscraper.fr/api2/jeuInfos.php"
)
== {}
)
assert await service._request(GAME_URL) == {}
assert session.get.call_count == 4
assert mock_log.warning.call_count == 0
@@ -1516,26 +1532,24 @@ class TestSubmissionLimit:
assert "submitting unknown ROMs" in _rendered(mock_log.info.call_args)
@pytest.mark.asyncio
async def test_a_new_scan_reports_it_again(self, service, monkeypatch):
mock_log = MagicMock()
monkeypatch.setattr(ss_module, "log", mock_log)
_, context = self._session(self._refused(), self._refused())
async def test_a_new_scan_reports_it_again(self, service, mock_log):
_, context = _session(self._refused(), self._refused())
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
reset_scan_state()
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
assert mock_log.info.call_count == 2
@pytest.mark.asyncio
async def test_the_submission_limit_never_counts_toward_the_breaker(self, service):
"""A library of unmatched ROMs would otherwise arm the scrape breaker."""
_, context = self._session(*(self._refused() for _ in range(5)))
_, context = _session(*(self._refused() for _ in range(5)))
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
for _ in range(5):
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
assert ss_module._state.daily_quota_errors == 0
assert is_daily_quota_exhausted() is False
@@ -1547,78 +1561,53 @@ class TestDailyQuotaBreaker:
trip to be told the same thing. It has to be recoverable, though, because the
web process never starts a scan and so never resets it."""
@pytest.fixture
def service(self):
return ScreenScraperService()
@staticmethod
def _refused() -> aiohttp.ClientResponseError:
return _client_error(430)
def _session(self, *responses) -> tuple[AsyncMock, MagicMock]:
session = AsyncMock()
session.get.side_effect = list(responses)
context = MagicMock()
context.get.return_value = session
return session, context
def _refused(self) -> aiohttp.ClientResponseError:
return aiohttp.ClientResponseError(
request_info=MagicMock(), history=(), status=430
)
def _account(self, **fields: str) -> MagicMock:
payload = _ssuser_response(**fields)
response = MagicMock()
response.text = AsyncMock(return_value=json.dumps(payload))
response.json = AsyncMock(return_value=payload)
response.raise_for_status.return_value = None
return response
def _forbidden(self) -> MagicMock:
"""A refused credential set, the way the account endpoint answers one."""
response = MagicMock()
response.text = AsyncMock(return_value=SS_LOGIN_ERROR_BODY)
response.json = AsyncMock(return_value={})
response.raise_for_status.side_effect = aiohttp.ClientResponseError(
request_info=MagicMock(),
history=(),
status=http.HTTPStatus.FORBIDDEN,
message="Forbidden",
)
return response
def _due_for_a_recheck(self) -> None:
@staticmethod
def _due_for_a_recheck() -> None:
ss_module._state.quota_recheck_at = time.monotonic() - 1
async def _arm(self, service, context) -> None:
for _ in range(SS_QUOTA_TRIP_THRESHOLD):
with pytest.raises(HTTPException):
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
async def _arm(self, service) -> None:
"""Spend the threshold on refusals, leaving the breaker armed."""
_, context = _session(
*(self._refused() for _ in range(SS_QUOTA_TRIP_THRESHOLD))
)
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
for _ in range(SS_QUOTA_TRIP_THRESHOLD):
with pytest.raises(HTTPException):
await service._request(GAME_URL)
assert is_daily_quota_exhausted() is True
@pytest.mark.asyncio
async def test_one_refusal_is_not_enough(self, service):
"""ScreenScraper answers 430 for reasons that do not survive a retry, and
one of them must not cost the scan the provider."""
session, context = self._session(self._refused(), self._account())
session, context = _session(self._refused(), _account())
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(HTTPException):
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
assert is_daily_quota_exhausted() is False
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
assert session.get.call_count == 2
@pytest.mark.asyncio
async def test_a_response_in_between_clears_the_count(self, service):
_, context = self._session(self._refused(), self._account(), self._refused())
_, context = _session(self._refused(), _account(), self._refused())
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(HTTPException):
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
await service._request(GAME_URL)
with pytest.raises(HTTPException):
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
assert is_daily_quota_exhausted() is False
@@ -1626,24 +1615,21 @@ class TestDailyQuotaBreaker:
async def test_the_submission_limit_does_not_count(self, service):
"""A scan interleaves unmatched ROMs with refused ones; only the refusals
of the scrape allowance may arm the breaker."""
unmatched = aiohttp.ClientResponseError(
request_info=MagicMock(), history=(), status=431
)
_, context = self._session(self._refused(), unmatched, self._refused())
_, context = _session(self._refused(), _client_error(431), self._refused())
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(HTTPException):
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
await service._request(GAME_URL)
with pytest.raises(HTTPException):
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
assert is_daily_quota_exhausted() is True
@pytest.mark.asyncio
async def test_a_refusal_on_the_retry_leg_counts(self, service):
"""The first attempt can time out, and the retry is where the wall shows."""
_, context = self._session(
_, context = _session(
aiohttp.ServerTimeoutError("Timeout"),
self._refused(),
aiohttp.ServerTimeoutError("Timeout"),
@@ -1653,17 +1639,14 @@ class TestDailyQuotaBreaker:
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
for _ in range(SS_QUOTA_TRIP_THRESHOLD):
with pytest.raises(HTTPException):
await service._request(
"https://api.screenscraper.fr/api2/jeuInfos.php"
)
await service._request(GAME_URL)
assert is_daily_quota_exhausted() is True
@pytest.mark.asyncio
async def test_simultaneous_refusals_are_one_wall(self, service, monkeypatch):
"""An account with a thread allowance has that many requests in flight
when the quota runs out. They all come back 430, but they are the same
refusal seen N times, so a threshold above one has to survive them."""
"""An account with a thread allowance has that many requests in flight when
the quota runs out: the same refusal seen N times, not N walls."""
in_flight = SS_QUOTA_TRIP_THRESHOLD + 2
monkeypatch.setattr(
ss_module, "_concurrency_limiter", ConcurrencyLimiter(in_flight)
@@ -1689,10 +1672,7 @@ class TestDailyQuotaBreaker:
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
results = await asyncio.gather(
*(
service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
for _ in range(in_flight)
),
*(service._request(GAME_URL) for _ in range(in_flight)),
return_exceptions=True,
)
@@ -1701,15 +1681,13 @@ class TestDailyQuotaBreaker:
assert is_daily_quota_exhausted() is False
@pytest.mark.asyncio
async def test_it_is_reported_once(self, service, monkeypatch):
mock_log = MagicMock()
monkeypatch.setattr(ss_module, "log", mock_log)
_, context = self._session(*(self._refused() for _ in range(4)))
async def test_it_is_reported_once(self, service, mock_log):
await self._arm(service)
_, context = _session()
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
await self._arm(service, context)
with pytest.raises(HTTPException):
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
messages = [_rendered(call) for call in mock_log.warning.call_args_list]
assert sum("pausing ScreenScraper" in message for message in messages) == 1
@@ -1717,52 +1695,39 @@ class TestDailyQuotaBreaker:
@pytest.mark.asyncio
async def test_it_recovers_once_the_account_has_room_again(self, service):
"""The web process never starts a scan, so nothing else will ever clear
this. The account endpoint costs no quota, which is what makes the
re-check affordable."""
_, context = self._session(
*(self._refused() for _ in range(SS_QUOTA_TRIP_THRESHOLD))
)
this. The account endpoint costs no quota, which makes the probe affordable."""
await self._arm(service)
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
await self._arm(service, context)
session, context = self._session(
self._account(maxrequestsperday="20000", requeststoday="10"),
self._account(maxrequestsperday="20000", requeststoday="11"),
session, context = _session(
_account(maxrequestsperday="20000", requeststoday="10"),
_account(maxrequestsperday="20000", requeststoday="11"),
)
self._due_for_a_recheck()
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
assert await service._request(
"https://api.screenscraper.fr/api2/jeuInfos.php"
) == _ssuser_response(maxrequestsperday="20000", requeststoday="11")
assert await service._request(GAME_URL) == _ssuser_response(
maxrequestsperday="20000", requeststoday="11"
)
assert is_daily_quota_exhausted() is False
# The re-check itself, then the request that was asking.
assert session.get.call_count == 2
assert session.get.call_args_list[0][0][0].endswith("ssuserInfos.php")
assert session.get.call_args_list[0][0][0].endswith(SS_ACCOUNT_ENDPOINT)
@pytest.mark.asyncio
async def test_it_stays_armed_while_the_allowance_is_still_spent(
self, service, monkeypatch
self, service, mock_log
):
mock_log = MagicMock()
monkeypatch.setattr(ss_module, "log", mock_log)
_, context = self._session(
*(self._refused() for _ in range(SS_QUOTA_TRIP_THRESHOLD))
)
await self._arm(service)
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
await self._arm(service, context)
session, context = self._session(
self._account(maxrequestsperday="20000", requeststoday="20000")
session, context = _session(
_account(maxrequestsperday="20000", requeststoday="20000")
)
self._due_for_a_recheck()
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(HTTPException):
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
assert is_daily_quota_exhausted() is True
assert session.get.call_count == 1
@@ -1772,24 +1737,16 @@ class TestDailyQuotaBreaker:
@pytest.mark.asyncio
async def test_a_re_check_is_claimed_before_it_is_made(self, service):
"""Concurrent short-circuiting requests must not all probe at once."""
_, context = self._session(
*(self._refused() for _ in range(SS_QUOTA_TRIP_THRESHOLD))
)
await self._arm(service)
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
await self._arm(service, context)
session, context = self._session(
self._account(maxrequestsperday="20000", requeststoday="20000")
session, context = _session(
_account(maxrequestsperday="20000", requeststoday="20000")
)
self._due_for_a_recheck()
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
results = await asyncio.gather(
*(
service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
for _ in range(4)
),
*(service._request(GAME_URL) for _ in range(4)),
return_exceptions=True,
)
@@ -1797,118 +1754,74 @@ class TestDailyQuotaBreaker:
assert session.get.call_count == 1
@pytest.mark.asyncio
async def test_a_failed_re_check_never_reaches_the_caller(self, service):
"""A re-check that times out must not turn a short-circuit into a crash,
@pytest.mark.parametrize(
"failure",
(aiohttp.ServerTimeoutError("Timeout"), aiohttp.ClientConnectionError("nope")),
ids=("timeout", "connection-error"),
)
async def test_a_failed_re_check_never_reaches_the_caller(self, service, failure):
"""A probe that cannot complete must not turn a short-circuit into a crash,
and must not wedge the breaker either."""
_, context = self._session(
*(self._refused() for _ in range(SS_QUOTA_TRIP_THRESHOLD))
)
await self._arm(service)
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
await self._arm(service, context)
_, context = self._session(aiohttp.ServerTimeoutError("Timeout"))
_, context = _session(failure)
self._due_for_a_recheck()
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(HTTPException) as exc_info:
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
assert exc_info.value.status_code == status.HTTP_429_TOO_MANY_REQUESTS
assert is_daily_quota_exhausted() is True
assert ss_module._state.quota_recheck_at is not None
@pytest.mark.asyncio
async def test_a_connection_error_on_the_re_check_is_survivable(self, service):
_, context = self._session(
*(self._refused() for _ in range(SS_QUOTA_TRIP_THRESHOLD))
)
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
await self._arm(service, context)
_, context = self._session(aiohttp.ClientConnectionError("nope"))
self._due_for_a_recheck()
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(HTTPException):
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
assert is_daily_quota_exhausted() is True
@pytest.mark.asyncio
async def test_a_re_check_without_a_reading_stays_armed(self, service):
"""ScreenScraper answers 200 with a body it could not fill. The limits it
leaves behind are the ones from before the wall, so they still show
headroom: resuming on them would claim a recovery that never happened."""
_, context = self._session(
self._account(maxrequestsperday="20000", requeststoday="10"),
@pytest.mark.parametrize(
"probe",
(lambda: _ok_response({"response": {}}), lambda: _account()),
ids=("no-ssuser-block", "no-usable-counters"),
)
async def test_a_re_check_without_a_reading_stays_armed(self, service, probe):
"""The limits left behind are the ones from before the wall, so they still
show headroom: resuming on them would claim a recovery that never happened."""
_, context = _session(
_account(maxrequestsperday="20000", requeststoday="10"),
*(self._refused() for _ in range(SS_QUOTA_TRIP_THRESHOLD)),
)
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await self._arm(service, context)
await service._request(GAME_URL)
for _ in range(SS_QUOTA_TRIP_THRESHOLD):
with pytest.raises(HTTPException):
await service._request(GAME_URL)
empty = MagicMock()
empty.text = AsyncMock(return_value='{"response": {}}')
empty.json = AsyncMock(return_value={"response": {}})
empty.raise_for_status.return_value = None
session, context = self._session(empty)
session, context = _session(probe())
self._due_for_a_recheck()
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(HTTPException):
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
assert is_daily_quota_exhausted() is True
# The probe went out, but the caller's request did not follow it.
assert session.get.call_count == 1
@pytest.mark.asyncio
async def test_a_re_check_with_no_usable_counters_stays_armed(self, service):
"""An ssuser block with nothing readable in it is a reading in name only:
it replaces the limits, so an identity check calls it fresh evidence,
while it says nothing about whether the allowance came back."""
_, context = self._session(
self._account(maxrequestsperday="20000", requeststoday="10"),
*(self._refused() for _ in range(SS_QUOTA_TRIP_THRESHOLD)),
)
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await self._arm(service, context)
session, context = self._session(self._account())
self._due_for_a_recheck()
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(HTTPException):
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
assert is_daily_quota_exhausted() is True
assert session.get.call_count == 1
@pytest.mark.asyncio
async def test_a_refusal_that_keeps_not_sticking_is_reported_once(
self, service, monkeypatch
self, service, mock_log
):
"""A response clears the count, so a 430 that never survives a retry would
otherwise warn on every ROM in the library."""
mock_log = MagicMock()
monkeypatch.setattr(ss_module, "log", mock_log)
responses = []
for _ in range(6):
responses += [self._refused(), self._account()]
_, context = self._session(*responses)
responses += [self._refused(), _account()]
_, context = _session(*responses)
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
for _ in range(6):
with pytest.raises(HTTPException):
await service._request(
"https://api.screenscraper.fr/api2/jeuInfos.php"
)
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
await service._request(GAME_URL)
assert is_daily_quota_exhausted() is False
messages = [_rendered(call) for call in mock_log.warning.call_args_list]
@@ -1916,36 +1829,30 @@ class TestDailyQuotaBreaker:
@pytest.mark.asyncio
async def test_a_refused_re_check_never_arms_the_credentials_breaker(self, service):
"""ScreenScraper refuses a developer id it accepted a minute earlier, and
nothing outside a scan clears the credentials breaker. A probe that armed
it would wedge the provider harder than the quota breaker it is checking."""
_, context = self._session(
*(self._refused() for _ in range(SS_QUOTA_TRIP_THRESHOLD))
)
"""Nothing outside a scan clears the credentials breaker, so a probe that
armed it would wedge the provider harder than the quota breaker it checks."""
await self._arm(service)
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
await self._arm(service, context)
_, context = self._session(self._forbidden())
_, context = _session(_forbidden_response())
self._due_for_a_recheck()
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
with pytest.raises(HTTPException) as exc_info:
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
# The caller hears about the quota, not the probe's refusal.
assert exc_info.value.status_code == status.HTTP_429_TOO_MANY_REQUESTS
assert ss_module._state.credentials_rejected is None
# And once the allowance comes back, ScreenScraper is usable again.
session, context = self._session(
self._account(maxrequestsperday="20000", requeststoday="10"),
self._account(maxrequestsperday="20000", requeststoday="11"),
session, context = _session(
_account(maxrequestsperday="20000", requeststoday="10"),
_account(maxrequestsperday="20000", requeststoday="11"),
)
self._due_for_a_recheck()
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
assert is_daily_quota_exhausted() is False
assert session.get.call_count == 2
@@ -1954,21 +1861,16 @@ class TestDailyQuotaBreaker:
async def test_a_re_check_leaves_a_refused_credential_set_refused(self, service):
"""Restoring what the probe found must not hand an already-refused set a
second chance either."""
_, context = self._session(
*(self._refused() for _ in range(SS_QUOTA_TRIP_THRESHOLD))
)
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
await self._arm(service, context)
await self._arm(service)
ss_module._state.credentials_rejected = SSCredentialSet.DEVELOPER
_, context = self._session(self._forbidden())
_, context = _session(_forbidden_response())
self._due_for_a_recheck()
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
# The quota guard runs first, so that is the refusal the caller sees.
with pytest.raises(HTTPException) as exc_info:
await service._request("https://api.screenscraper.fr/api2/jeuInfos.php")
await service._request(GAME_URL)
assert exc_info.value.status_code == status.HTTP_429_TOO_MANY_REQUESTS
assert ss_module._state.credentials_rejected is SSCredentialSet.DEVELOPER
@@ -1977,12 +1879,7 @@ class TestDailyQuotaBreaker:
async def test_the_credentials_breaker_still_stands_on_its_own(self, service):
"""Clearing the quota breaker must not hand a refused credential set a
second chance: nothing but a restart fixes that one."""
_, context = self._session(
*(self._refused() for _ in range(SS_QUOTA_TRIP_THRESHOLD))
)
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
await self._arm(service, context)
await self._arm(service)
ss_module._state.credentials_rejected = SSCredentialSet.DEVELOPER
reset_daily_quota()
@@ -2067,10 +1964,6 @@ class TestLoadsLenient:
}
def _ssuser_response(**fields: str) -> dict:
return {"response": {"ssuser": dict(fields)}}
class TestAccountLimits:
"""ScreenScraper reports the account's allowances on every response; they
drive pacing, the quota readout and the configuration advisories."""

View File

@@ -21,6 +21,7 @@ from handler.metadata.base_handler import PS1_SERIAL_INDEX_KEY
from handler.metadata.ss_handler import (
PS1_SS_ID,
SWITCH_SS_ID,
ScreenScraperExhaustedError,
SSHandler,
_get_rom_type,
_is_daily_quota_error,
@@ -1332,9 +1333,9 @@ class TestLookupRom:
assert is_not_game is True
@pytest.mark.asyncio
async def test_returns_empty_on_daily_quota_exhausted(self):
"""A daily-quota 429 yields an empty match so the scan falls back to the
other providers instead of failing."""
async def test_reports_a_short_circuit_on_daily_quota_exhausted(self):
"""A breaker answered, so the caller has to hear that ScreenScraper did
not: an empty match would read as a miss it never made."""
handler = SSHandler()
mock_get_info = AsyncMock(
side_effect=HTTPException(
@@ -1346,12 +1347,12 @@ class TestLookupRom:
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
patch.object(handler.ss_service, "get_game_info", mock_get_info),
):
result, is_not_game = await handler.lookup_rom(
MagicMock(platform_slug="snes"), 3, [self._make_mock_file()]
)
with pytest.raises(ScreenScraperExhaustedError) as exc_info:
await handler.lookup_rom(
MagicMock(platform_slug="snes"), 3, [self._make_mock_file()]
)
mock_get_info.assert_awaited_once()
assert result["ss_id"] is None
assert is_not_game is False
assert exc_info.value.fallback["ss_id"] is None
@pytest.mark.asyncio
async def test_reraises_non_quota_http_error(self):
@@ -1377,80 +1378,72 @@ class TestLookupRom:
class TestScreenScraperQuotaFallback:
"""The scan-facing lookups return an empty match when the daily quota is
exhausted (HTTP 429), so a scan degrades to the other providers. Non-429
errors are real failures and must propagate."""
"""The scan-facing lookups report a short circuit when the daily quota is
exhausted (HTTP 429), so a scan degrades to the other providers without
reading the silence as a miss. Non-429 errors are real failures and must
propagate."""
@pytest.mark.asyncio
async def test_get_rom_by_id_returns_empty_on_daily_quota(self):
handler = SSHandler()
mock_get_info = AsyncMock(
@pytest.fixture(autouse=True)
def _credentials(self):
with (
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
):
yield
@staticmethod
def _exhausted() -> AsyncMock:
return AsyncMock(
side_effect=HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="quota"
)
)
with (
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
patch.object(handler.ss_service, "get_game_info", mock_get_info),
):
result = await handler.get_rom_by_id(MagicMock(), 1234)
@staticmethod
def _unavailable() -> AsyncMock:
return AsyncMock(
side_effect=HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="down"
)
)
@pytest.mark.asyncio
async def test_get_rom_by_id_reports_a_short_circuit_on_daily_quota(self):
handler = SSHandler()
mock_get_info = self._exhausted()
with patch.object(handler.ss_service, "get_game_info", mock_get_info):
with pytest.raises(ScreenScraperExhaustedError) as exc_info:
await handler.get_rom_by_id(MagicMock(), 1234)
mock_get_info.assert_awaited_once()
assert result["ss_id"] is None
assert exc_info.value.fallback["ss_id"] is None
@pytest.mark.asyncio
async def test_get_rom_by_id_reraises_non_quota_error(self):
handler = SSHandler()
with (
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
patch.object(
handler.ss_service,
"get_game_info",
AsyncMock(
side_effect=HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="down"
)
),
),
):
with patch.object(handler.ss_service, "get_game_info", self._unavailable()):
with pytest.raises(HTTPException):
await handler.get_rom_by_id(MagicMock(), 1234)
@pytest.mark.asyncio
async def test_get_rom_returns_empty_on_daily_quota(self):
async def test_get_rom_carries_its_name_only_fallback_on_daily_quota(self):
"""The filename lookup derives a name locally, so the short circuit hands
it back rather than dropping it."""
handler = SSHandler()
rom = MagicMock(platform_slug="genesis", platform_id=1, id=1, regions=[])
mock_search = AsyncMock(
side_effect=HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="quota"
)
)
with (
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
patch.object(handler.ss_service, "search_games", mock_search),
):
result = await handler.get_rom(rom, "Sonic.bin", platform_ss_id=3)
mock_search = self._exhausted()
with patch.object(handler.ss_service, "search_games", mock_search):
with pytest.raises(ScreenScraperExhaustedError) as exc_info:
await handler.get_rom(rom, "Sonic.bin", platform_ss_id=3)
mock_search.assert_awaited()
assert result["ss_id"] is None
assert exc_info.value.fallback["ss_id"] is None
@pytest.mark.asyncio
async def test_matching_by_name_returns_empty_on_daily_quota(self):
"""The manual-match search gathers every provider without
return_exceptions, so a raised ScreenScraper error takes the whole dialog
down with it."""
"""A manual search wants whatever the other providers found, so an
exhausted ScreenScraper contributes nothing rather than reporting."""
handler = SSHandler()
mock_search = AsyncMock(
side_effect=HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="quota"
)
)
with (
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
patch.object(handler.ss_service, "search_games", mock_search),
):
mock_search = self._exhausted()
with patch.object(handler.ss_service, "search_games", mock_search):
result = await handler.get_matched_roms_by_name(MagicMock(), "Sonic", 3)
mock_search.assert_awaited_once()
assert result == []
@@ -1458,26 +1451,23 @@ class TestScreenScraperQuotaFallback:
@pytest.mark.asyncio
async def test_matching_by_name_reraises_non_quota_error(self):
handler = SSHandler()
with (
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
patch.object(
handler.ss_service,
"search_games",
AsyncMock(
side_effect=HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="down"
)
),
),
):
with patch.object(handler.ss_service, "search_games", self._unavailable()):
with pytest.raises(HTTPException):
await handler.get_matched_roms_by_name(MagicMock(), "Sonic", 3)
@pytest.mark.asyncio
async def test_matching_by_id_returns_no_match_on_daily_quota(self):
"""A manual match wants the providers that can still answer, so this one
contributes nothing rather than reporting a short circuit."""
handler = SSHandler()
with patch.object(handler.ss_service, "get_game_info", self._exhausted()):
assert await handler.get_matched_rom_by_id(MagicMock(), 1234) is None
class TestScreenScraperCredentialFallback:
"""Rejected credentials are a configuration problem, not a scan failure: the
service reports them once and the scan carries on with the other providers."""
service reports them once and the scan carries on with the other providers,
hearing that ScreenScraper never answered rather than that it missed."""
def _make_file(self) -> MagicMock:
mock_file = MagicMock()
@@ -1492,7 +1482,7 @@ class TestScreenScraperCredentialFallback:
return mock_file
@pytest.mark.asyncio
async def test_lookup_rom_returns_empty_on_rejected_credentials(self):
async def test_lookup_rom_reports_a_short_circuit_on_rejected_credentials(self):
handler = SSHandler()
rom = MagicMock(
platform_slug="genesis", platform_id=1, id=1, fs_name="Sonic (USA).md"
@@ -1508,12 +1498,13 @@ class TestScreenScraperCredentialFallback:
),
),
):
result, _ = await handler.lookup_rom(rom, 1, [self._make_file()])
with pytest.raises(ScreenScraperExhaustedError) as exc_info:
await handler.lookup_rom(rom, 1, [self._make_file()])
assert result["ss_id"] is None
assert exc_info.value.fallback["ss_id"] is None
@pytest.mark.asyncio
async def test_get_rom_returns_empty_on_rejected_credentials(self):
async def test_get_rom_reports_a_short_circuit_on_rejected_credentials(self):
handler = SSHandler()
rom = MagicMock(platform_slug="genesis", platform_id=1, id=1, regions=[])
with (
@@ -1527,12 +1518,13 @@ class TestScreenScraperCredentialFallback:
),
),
):
result = await handler.get_rom(rom, "Sonic.bin", platform_ss_id=3)
with pytest.raises(ScreenScraperExhaustedError) as exc_info:
await handler.get_rom(rom, "Sonic.bin", platform_ss_id=3)
assert result["ss_id"] is None
assert exc_info.value.fallback["ss_id"] is None
@pytest.mark.asyncio
async def test_get_rom_by_id_returns_empty_on_rejected_credentials(self):
async def test_get_rom_by_id_reports_a_short_circuit_on_rejected_credentials(self):
handler = SSHandler()
with (
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
@@ -1545,9 +1537,10 @@ class TestScreenScraperCredentialFallback:
),
),
):
result = await handler.get_rom_by_id(MagicMock(), 1234)
with pytest.raises(ScreenScraperExhaustedError) as exc_info:
await handler.get_rom_by_id(MagicMock(), 1234)
assert result["ss_id"] is None
assert exc_info.value.fallback["ss_id"] is None
class TestScreenScraperRateLimitPropagation:

View File

@@ -4,7 +4,6 @@ A complete rescan clears every ID it could rematch; a provider that failed
answered nothing, so the ID it could not check has to survive.
"""
from collections.abc import Callable
from typing import Any
from unittest.mock import AsyncMock, patch
@@ -16,7 +15,7 @@ from handler.database import db_rom_handler
from handler.metadata.igdb_handler import IGDBRom
from handler.metadata.pouet_handler import PouetRom
from handler.metadata.sgdb_handler import SGDBRom
from handler.metadata.ss_handler import SSRom
from handler.metadata.ss_handler import ScreenScraperExhaustedError, SSRom
from handler.scan_handler import MetadataSource, ScanType
from models.rom import Rom
@@ -32,6 +31,8 @@ SGDB_MISS = SGDBRom(sgdb_id=None)
POUET_MISS = PouetRom(pouet_id=None)
MATCH = IGDBRom(igdb_id=9999, name="A Real Game")
UNREACHABLE = HTTPException(status_code=503, detail="provider is down")
SS_MISS = SSRom(ss_id=None)
SS_SHORT_CIRCUITED = ScreenScraperExhaustedError(SS_MISS)
def _lookup(result: Any) -> AsyncMock:
@@ -49,8 +50,8 @@ async def _rescan(
sgdb_result: SGDBRom | Exception = SGDB_MISS,
pouet_result: PouetRom | Exception = POUET_MISS,
platform_igdb_id: int | None = 4,
ss_breaker_tripped: bool | Callable[[], bool] = False,
ss_lookup_mock: AsyncMock | None = None,
ss_lookup_result: tuple[SSRom, bool] | Exception = (SS_MISS, False),
ss_get_rom_result: SSRom | Exception = SS_MISS,
) -> Rom:
"""Rescan a ROM carrying hand-set IDs, and persist the result."""
platform = add_n64_platform(igdb_id=platform_igdb_id, ss_id=14)
@@ -80,19 +81,11 @@ async def _rescan(
patch("handler.scan_handler.meta_pouet_handler.get_rom_by_id", new=pouet_mock),
patch(
"handler.scan_handler.meta_ss_handler.lookup_rom",
new=ss_lookup_mock or AsyncMock(return_value=(SSRom(ss_id=None), False)),
new=_lookup(ss_lookup_result),
),
patch(
"handler.scan_handler.meta_ss_handler.get_rom",
new=AsyncMock(return_value=SSRom(ss_id=None)),
),
patch(
"handler.scan_handler.is_breaker_tripped",
new=(
ss_breaker_tripped
if callable(ss_breaker_tripped)
else lambda: ss_breaker_tripped
),
new=_lookup(ss_get_rom_result),
),
):
scanned = await run_scan(
@@ -140,29 +133,23 @@ async def test_a_source_that_could_not_be_reached_keeps_its_id():
async def test_a_screenscraper_breaker_keeps_its_id():
"""An exhausted quota answers empty for every remaining ROM."""
"""A breaker answers every remaining ROM, so it rules nothing out."""
saved = await _rescan(
[MetadataSource.IGDB, MetadataSource.SS], ss_breaker_tripped=True
[MetadataSource.IGDB, MetadataSource.SS],
ss_lookup_result=SS_SHORT_CIRCUITED,
ss_get_rom_result=SS_SHORT_CIRCUITED,
)
assert saved.ss_id == STALE_SS_ID
async def test_a_screenscraper_breaker_that_recovers_mid_rom_keeps_its_id():
"""The breaker re-checks the account and can clear itself while a rom is
still gathering its other providers. ScreenScraper still refused *this*
rom, so its id must survive the rescan."""
recovered = False
async def refuse_then_recover(*args: Any, **kwargs: Any):
nonlocal recovered
recovered = True
return (SSRom(ss_id=None), False)
"""The breaker can clear between this rom's two lookups, but the hash lookup
it short-circuited still ruled nothing out."""
saved = await _rescan(
[MetadataSource.IGDB, MetadataSource.SS],
ss_breaker_tripped=lambda: not recovered,
ss_lookup_mock=AsyncMock(side_effect=refuse_then_recover),
ss_lookup_result=SS_SHORT_CIRCUITED,
ss_get_rom_result=SS_MISS,
)
assert saved.ss_id == STALE_SS_ID