feat(screenscraper): read the account limits before a scan starts

The limits ride along on every response, so learning them from the first
scrape response meant the opening requests of a scan ran at the default one
thread and 50 requests per minute, and the quota only became visible once a
platform finished.

ssuserInfos.php reports the same ssuser block up front. Unlike the scraping
endpoints it does not consume the daily quota (measured: two reads 90s apart
moved requeststoday by 0), so a scan can ask once at startup and pace itself
correctly from the first request, logging the quota and the SCAN_WORKERS
advisory before the first ROM is touched.

Best effort: a refused or unreachable lookup logs a warning and the scan
carries on.
This commit is contained in:
Spinnich
2026-07-28 19:01:04 +00:00
parent 5fb27a55f9
commit 8b51f37fd4
4 changed files with 151 additions and 0 deletions

View File

@@ -375,6 +375,29 @@ async def media_download_slot(url: str) -> AsyncIterator[int]:
yield media_download_timeout()
async def prime_account_limits() -> SSAccountLimits | None:
"""Read the account's allowances before a scan starts.
They ride along on every response, so waiting for the first scan request
means the first ROMs are scraped at the default one thread and 50 requests
per minute. ssuserInfos.php reports them up front for free: unlike the
scraping endpoints it does not consume the daily quota.
Best effort. A scan must still run when ScreenScraper cannot be reached.
"""
if not (SCREENSCRAPER_USER and SCREENSCRAPER_PASSWORD):
return None
try:
await ScreenScraperService().get_user_info()
except HTTPException as exc:
log.warning("ScreenScraper: could not read the account limits (%s)", exc.detail)
except (TimeoutError, aiohttp.ClientError) as exc:
log.warning("ScreenScraper: could not read the account limits (%s)", exc)
return _account_limits
async def auth_middleware(
req: aiohttp.ClientRequest, handler: aiohttp.ClientHandlerType
) -> aiohttp.ClientResponse:
@@ -556,6 +579,14 @@ class ScreenScraperService:
log.error("Error decoding JSON response from ScreenScraper: %s", exc)
return {}
async def get_user_info(self) -> dict:
"""Retrieve the account's allowances and quota counters.
Reference: https://api.screenscraper.fr/webapi2.php#ssuserInfos
"""
url = self.url.joinpath("ssuserInfos.php")
return await self._request(str(url))
async def get_infra_info(self) -> dict:
"""Retrieve information about the infrastructure.

View File

@@ -12,6 +12,9 @@ from rq.job import Job
from sqlalchemy.exc import IntegrityError
from adapters.services.screenscraper import get_account_limits as get_ss_account_limits
from adapters.services.screenscraper import (
prime_account_limits as prime_ss_account_limits,
)
from adapters.services.screenscraper import reset_scan_state as reset_ss_scan_state
from config import DEV_MODE, REDIS_URL, SCAN_TIMEOUT, SCAN_WORKERS, TASK_RESULT_TTL
from config.config_manager import MetadataMediaType
@@ -824,6 +827,13 @@ async def scan_platforms(
reset_ss_scan_state()
reset_ss_rate_limited_roms()
# Read the account's allowances before the first ROM, so pacing and the
# thread cap are right from the first request rather than from the first
# response, and the quota is visible up front.
if MetadataSource.SS in metadata_sources:
await prime_ss_account_limits()
_log_ss_quota()
try:
fs_platforms: list[str] = await fs_platform_handler.get_platforms()
except FolderStructureNotMatchException as e:

View File

@@ -23,6 +23,7 @@ from adapters.services.screenscraper import (
is_screenscraper_url,
media_download_slot,
media_download_timeout,
prime_account_limits,
reset_daily_quota,
reset_scan_state,
)
@@ -1371,6 +1372,89 @@ class TestAccountLimits:
assert get_account_limits() is None
class TestPrimingAccountLimits:
"""The limits ride along on every response, but piggybacking on the first
scan request means the first ROMs are scraped at the default pacing.
ssuserInfos.php reports them up front and costs no quota."""
@pytest.fixture(autouse=True)
def _credentials(self, monkeypatch):
monkeypatch.setattr(ss_module, "SCREENSCRAPER_USER", "user1")
monkeypatch.setattr(ss_module, "SCREENSCRAPER_PASSWORD", "pw1")
def _mock_session(self, payload: dict) -> tuple[MagicMock, MagicMock]:
session = AsyncMock()
response = MagicMock()
response.json = AsyncMock(return_value=payload)
response.text = AsyncMock(return_value="{}")
response.raise_for_status.return_value = None
session.get.return_value = response
context = MagicMock()
context.get.return_value = session
return session, context
@pytest.mark.asyncio
async def test_get_user_info_hits_the_account_endpoint(self):
service = ScreenScraperService()
with patch.object(
service, "_request", return_value={"response": {}}
) as mock_request:
await service.get_user_info()
assert mock_request.call_args[0][0].endswith("ssuserInfos.php")
@pytest.mark.asyncio
async def test_priming_applies_the_limits_before_any_rom_is_scraped(self):
session, context = self._mock_session(
_ssuser_response(
maxthreads="5",
maxrequestspermin="250",
maxrequestsperday="20000",
requeststoday="1500",
)
)
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
limits = await prime_account_limits()
assert limits is not None
assert limits.max_threads == 5
assert limits.remaining_requests == 18500
assert ss_module._concurrency_limiter.max_concurrency == 5
assert ss_module._rate_limiter.requests_per_second == pytest.approx(250 / 60)
session.get.assert_called_once()
@pytest.mark.asyncio
async def test_priming_is_skipped_without_credentials(self, monkeypatch):
monkeypatch.setattr(ss_module, "SCREENSCRAPER_USER", "")
monkeypatch.setattr(ss_module, "SCREENSCRAPER_PASSWORD", "")
session, context = self._mock_session(_ssuser_response(maxthreads="5"))
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
assert await prime_account_limits() is None
session.get.assert_not_called()
@pytest.mark.asyncio
async def test_priming_never_fails_the_scan(self, monkeypatch):
"""A scan must still run when the account lookup is refused."""
mock_log = MagicMock()
monkeypatch.setattr(ss_module, "log", mock_log)
session = AsyncMock()
session.get.side_effect = aiohttp.ClientResponseError(
request_info=MagicMock(), history=(), status=423
)
context = MagicMock()
context.get.return_value = session
with patch("adapters.services.screenscraper.ctx_aiohttp_session", context):
assert await prime_account_limits() is None
assert mock_log.warning.called
class TestQuotaWarnings:
@pytest.fixture
def mock_log(self, monkeypatch):

View File

@@ -236,6 +236,32 @@ class TestScreenScraperScanReporting:
reset_scan_state.assert_called_once()
reset_skips.assert_called_once()
async def test_primes_the_account_limits_before_scanning(self, patched, mocker):
"""Reading the limits up front means the first ROMs are already paced
correctly, instead of running at the default until the first response."""
prime = mocker.patch.object(
scan_module, "prime_ss_account_limits", new=AsyncMock(return_value=None)
)
await scan_platforms(
platform_ids=[],
metadata_sources=[MetadataSource.SS],
scan_type=ScanType.QUICK,
)
prime.assert_awaited_once()
async def test_does_not_prime_when_screenscraper_is_not_used(self, patched, mocker):
prime = mocker.patch.object(
scan_module, "prime_ss_account_limits", new=AsyncMock(return_value=None)
)
await scan_platforms(
platform_ids=[], metadata_sources=[], scan_type=ScanType.QUICK
)
prime.assert_not_awaited()
async def test_reports_remaining_quota_and_skipped_roms(self, patched, mocker):
mock_log = mocker.patch.object(scan_module, "log")
mocker.patch.object(