mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-23 18:17:53 -06:00
refactor: one retrying fetch loop in core.upstream
fetch_bytes and fetch_body now share open_retrying and read_limited: scrapers retry a 500 or a dropped connection like profile_sync, and fetch_body caps the body it reads.
This commit is contained in:
1 parent
75b5fb987e
commit
fdd7595a71
5 files changed
+145
-92
No files matched your search
+66
-19
@@ -24,6 +24,7 @@ import urllib.request
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Callable, Protocol, TypeVar
|
||||
|
||||
from core.artifacts import write_text_atomic
|
||||
|
||||
@@ -32,6 +33,8 @@ USER_AGENT = "retrobios-profile-sync/1.0"
|
||||
CACHE_DIR = ".cache/upstream"
|
||||
ABSENT = "\0absent\0"
|
||||
GITHUB_COMPARE_CAP = 300
|
||||
# A body read whole into memory is capped at this many bytes.
|
||||
MAX_RESPONSE_SIZE = 50 * 1024 * 1024
|
||||
RETRIES = 3
|
||||
RETRY_BACKOFF = (0.5, 2.0)
|
||||
# A 429 is waited out, as base_scraper does: git.libretro.com answers it
|
||||
@@ -93,6 +96,7 @@ _HOSTS: dict[str, tuple[str, str, str]] = {
|
||||
}
|
||||
|
||||
|
||||
_T = TypeVar("_T")
|
||||
_sleep = time.sleep
|
||||
# Hosts still refusing after every wait. Asking them again in the same pass
|
||||
# only spends the waits again, while the other forges keep answering.
|
||||
@@ -246,10 +250,6 @@ def forge_headers(
|
||||
return headers
|
||||
|
||||
|
||||
def _headers(url: str, accept_json: bool = False) -> dict[str, str]:
|
||||
return forge_headers(url, "application/json" if accept_json else None)
|
||||
|
||||
|
||||
def _http_failure(url: str, exc: urllib.error.HTTPError) -> UpstreamError:
|
||||
"""Classify an HTTP error. Only a real quota signal is fatal.
|
||||
|
||||
@@ -322,50 +322,97 @@ def _rate_limit_wait(exc: urllib.error.HTTPError, waited: int) -> float | None:
|
||||
return RATE_LIMIT_WAITS[waited]
|
||||
|
||||
|
||||
def fetch_body(url: str, accept_json: bool = False) -> bytes | None:
|
||||
"""Body of a GET, or None on 404.
|
||||
class _Readable(Protocol):
|
||||
def read(self, size: int = ..., /) -> bytes: ...
|
||||
|
||||
|
||||
def read_limited(resp: _Readable, max_bytes: int = MAX_RESPONSE_SIZE) -> bytes:
|
||||
"""Read a response whole, ValueError past `max_bytes`."""
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
while True:
|
||||
chunk = resp.read(65536)
|
||||
if not chunk:
|
||||
break
|
||||
total += len(chunk)
|
||||
if total > max_bytes:
|
||||
raise ValueError(f"Response exceeds {max_bytes} byte limit")
|
||||
chunks.append(chunk)
|
||||
return b"".join(chunks)
|
||||
|
||||
|
||||
def open_retrying(
|
||||
request: urllib.request.Request,
|
||||
consume: Callable[[http.client.HTTPResponse], _T],
|
||||
timeout: float = 30,
|
||||
) -> _T:
|
||||
"""Open `request` and hand the response to `consume`.
|
||||
|
||||
A pass over every profile issues thousands of requests, so a dropped
|
||||
connection or a transient 5xx is a certainty rather than an accident.
|
||||
Those are retried, a definitive answer from the forge is not. A rate
|
||||
limit is waited out, and a host that outlasts the waits is not asked
|
||||
again in this process.
|
||||
again in this process. What ends the attempts is raised as urllib gave
|
||||
it, except a host that does not resolve (GoneError) and a host muted
|
||||
earlier (RateLimitError).
|
||||
"""
|
||||
url = request.full_url
|
||||
host = urllib.parse.urlsplit(url).hostname or ""
|
||||
if host in _exhausted_hosts:
|
||||
raise RateLimitError(f"{url}: {host} rate limited earlier in this run", host)
|
||||
failure: UpstreamError | None = None
|
||||
attempt = 0
|
||||
waited = 0
|
||||
while True:
|
||||
req = urllib.request.Request(url, headers=_headers(url, accept_json))
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return resp.read()
|
||||
with urllib.request.urlopen(request, timeout=timeout) as resp:
|
||||
return consume(resp)
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 404:
|
||||
return None
|
||||
failure = _http_failure(url, exc)
|
||||
if isinstance(failure, RateLimitError):
|
||||
if isinstance(_http_failure(url, exc), RateLimitError):
|
||||
delay = _rate_limit_wait(exc, waited)
|
||||
if delay is None:
|
||||
_exhausted_hosts.add(host)
|
||||
raise failure from exc
|
||||
raise
|
||||
waited += 1
|
||||
_sleep(delay)
|
||||
continue
|
||||
if exc.code < 500:
|
||||
raise failure from exc
|
||||
raise
|
||||
failure: BaseException = exc
|
||||
except (urllib.error.URLError, http.client.HTTPException, OSError) as exc:
|
||||
if _host_is_unresolvable(exc):
|
||||
raise GoneError(f"{url}: host does not resolve") from exc
|
||||
failure = UpstreamError(f"{url}: {exc}")
|
||||
failure = exc
|
||||
attempt += 1
|
||||
if attempt >= RETRIES:
|
||||
raise failure
|
||||
_sleep(RETRY_BACKOFF[attempt - 1])
|
||||
|
||||
|
||||
def fetch_body(
|
||||
url: str,
|
||||
accept_json: bool = False,
|
||||
*,
|
||||
timeout: float = 30,
|
||||
max_bytes: int = MAX_RESPONSE_SIZE,
|
||||
user_agent: str = USER_AGENT,
|
||||
) -> bytes | None:
|
||||
"""Body of a GET, or None on 404, retried as open_retrying does.
|
||||
|
||||
A failure raises UpstreamError (RateLimitError, GoneError), a body over
|
||||
`max_bytes` ValueError.
|
||||
"""
|
||||
accept = "application/json" if accept_json else None
|
||||
req = urllib.request.Request(url, headers=forge_headers(url, accept, user_agent))
|
||||
try:
|
||||
return open_retrying(req, lambda resp: read_limited(resp, max_bytes), timeout)
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 404:
|
||||
return None
|
||||
raise _http_failure(url, exc) from exc
|
||||
except (urllib.error.URLError, http.client.HTTPException, OSError) as exc:
|
||||
raise UpstreamError(f"{url}: {exc}") from exc
|
||||
|
||||
|
||||
def http_text(url: str) -> str | None:
|
||||
"""Text body of a GET, or None on 404. Replaced in tests."""
|
||||
body = fetch_body(url)
|
||||
@@ -681,7 +728,7 @@ def _github_graphql(
|
||||
token = github_token()
|
||||
if offline or not token:
|
||||
return None
|
||||
headers = _headers(GITHUB_GRAPHQL, accept_json=True)
|
||||
headers = forge_headers(GITHUB_GRAPHQL, "application/json")
|
||||
headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(
|
||||
GITHUB_GRAPHQL, data=body.encode(), headers=headers, method="POST"
|
||||
|
||||
@@ -8,17 +8,23 @@ import inspect
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, NoReturn, Protocol, TypeVar
|
||||
from typing import Any, Callable, NoReturn, TypeVar
|
||||
|
||||
from core.github import github_token
|
||||
from core.artifacts import copy_stream_atomic, write_text_atomic
|
||||
from core.upstream import (
|
||||
MAX_RESPONSE_SIZE,
|
||||
RateLimitError,
|
||||
UpstreamError,
|
||||
open_retrying,
|
||||
read_limited,
|
||||
)
|
||||
from core.upstream import forge_headers as upstream_headers
|
||||
from model.safeparse import require_yaml, yaml_load
|
||||
|
||||
@@ -81,9 +87,6 @@ class ChangeSet:
|
||||
return ", ".join(parts) if parts else "no changes"
|
||||
|
||||
|
||||
MAX_RESPONSE_SIZE = 50 * 1024 * 1024 # 50 MB
|
||||
|
||||
|
||||
def md5_field(raw: object) -> tuple[list[str], bool]:
|
||||
"""The md5 values a batocera-systems item declares, and whether it
|
||||
writes them as a list.
|
||||
@@ -139,31 +142,9 @@ def requirement_entry(req: BiosRequirement) -> dict:
|
||||
return entry
|
||||
|
||||
|
||||
class _Readable(Protocol):
|
||||
def read(self, size: int = ..., /) -> bytes: ...
|
||||
|
||||
|
||||
def _read_limited(resp: _Readable, max_bytes: int = MAX_RESPONSE_SIZE) -> bytes:
|
||||
"""Read an HTTP response with a size limit to prevent OOM."""
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
while True:
|
||||
chunk = resp.read(65536)
|
||||
if not chunk:
|
||||
break
|
||||
total += len(chunk)
|
||||
if total > max_bytes:
|
||||
raise ValueError(f"Response exceeds {max_bytes} byte limit")
|
||||
chunks.append(chunk)
|
||||
return b"".join(chunks)
|
||||
|
||||
|
||||
SCRAPER_AGENT = "retrobios-scraper/1.0"
|
||||
GITHUB_API = "https://api.github.com"
|
||||
|
||||
# Statuses a forge answers when it asks the client to slow down.
|
||||
_RETRYABLE = frozenset({429, 502, 503, 504})
|
||||
|
||||
_T = TypeVar("_T")
|
||||
|
||||
|
||||
@@ -196,37 +177,29 @@ def _open(
|
||||
request: urllib.request.Request,
|
||||
consume: Callable[[http.client.HTTPResponse], _T],
|
||||
timeout: float,
|
||||
attempts: int = 5,
|
||||
sleep: Callable[[float], None] | None = None,
|
||||
) -> _T:
|
||||
"""Open `request` and hand the response to `consume`, waiting out a rate
|
||||
limit: the wait is the server's Retry-After when it gives one, else 2,
|
||||
4, 8, 16 s. A header the request does not set comes from
|
||||
forge_headers()."""
|
||||
"""Open `request` and hand the response to `consume`, retried as
|
||||
core.upstream.open_retrying does. A header the request does not set
|
||||
comes from forge_headers(). A failure raises FetchError."""
|
||||
url = request.full_url
|
||||
for name, value in forge_headers(url).items():
|
||||
if not request.has_header(name.capitalize()):
|
||||
request.add_header(name, value)
|
||||
for attempt in range(attempts):
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=timeout) as resp:
|
||||
return consume(resp)
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code not in _RETRYABLE or attempt == attempts - 1:
|
||||
raise FetchError(url, e, e.code) from e
|
||||
retry_after = e.headers.get("Retry-After", "") if e.headers else ""
|
||||
delay = float(retry_after) if retry_after.isdigit() else 2.0 ** (attempt + 1)
|
||||
(sleep or time.sleep)(min(delay, 120.0))
|
||||
except (urllib.error.URLError, http.client.HTTPException, TimeoutError) as e:
|
||||
raise FetchError(url, e) from e
|
||||
raise AssertionError("unreachable")
|
||||
try:
|
||||
return open_retrying(request, consume, timeout)
|
||||
except urllib.error.HTTPError as e:
|
||||
raise FetchError(url, e, e.code) from e
|
||||
except (urllib.error.URLError, http.client.HTTPException, OSError) as e:
|
||||
raise FetchError(url, e) from e
|
||||
except RateLimitError as e:
|
||||
raise FetchError(url, e, 429) from e
|
||||
except UpstreamError as e:
|
||||
raise FetchError(url, e) from e
|
||||
|
||||
|
||||
def fetch_bytes(
|
||||
url: str,
|
||||
headers: dict[str, str] | None = None,
|
||||
attempts: int = 5,
|
||||
sleep: Callable[[float], None] | None = None,
|
||||
data: bytes | None = None,
|
||||
timeout: float = 30,
|
||||
max_bytes: int = MAX_RESPONSE_SIZE,
|
||||
@@ -239,7 +212,7 @@ def fetch_bytes(
|
||||
add to or replace forge_headers(url).
|
||||
"""
|
||||
request = urllib.request.Request(url, data=data, headers=headers or {})
|
||||
return _open(request, lambda resp: _read_limited(resp, max_bytes), timeout, attempts, sleep)
|
||||
return _open(request, lambda resp: read_limited(resp, max_bytes), timeout)
|
||||
|
||||
|
||||
def fetch_text(url: str, headers: dict[str, str] | None = None) -> str:
|
||||
|
||||
@@ -142,12 +142,22 @@ class RateLimitedForge(unittest.TestCase):
|
||||
headers["Retry-After"] = retry_after
|
||||
return urllib.error.HTTPError("u", 429, "Too Many Requests", headers, io.BytesIO())
|
||||
|
||||
def setUp(self):
|
||||
from core import upstream
|
||||
|
||||
self.waits: list[float] = []
|
||||
patcher = mock.patch.object(upstream, "_sleep", self.waits.append)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
upstream._exhausted_hosts.clear()
|
||||
self.addCleanup(upstream._exhausted_hosts.clear)
|
||||
|
||||
def test_a_rate_limit_is_waited_out(self):
|
||||
import io
|
||||
|
||||
from core import upstream
|
||||
from scraper.base_scraper import fetch_bytes
|
||||
|
||||
waits: list[float] = []
|
||||
answers = [self._limited("7"), self._limited(None), io.BytesIO(b"ok")]
|
||||
|
||||
def urlopen(_request, timeout):
|
||||
@@ -157,25 +167,47 @@ class RateLimitedForge(unittest.TestCase):
|
||||
return answer
|
||||
|
||||
with mock.patch("urllib.request.urlopen", urlopen):
|
||||
self.assertEqual(fetch_bytes("https://x", sleep=waits.append), b"ok")
|
||||
self.assertEqual(waits, [7.0, 4.0])
|
||||
self.assertEqual(fetch_bytes("https://x"), b"ok")
|
||||
self.assertEqual(self.waits, [7.0, upstream.RATE_LIMIT_WAITS[1]])
|
||||
|
||||
def test_a_lasting_limit_or_a_missing_file_fails(self):
|
||||
from scraper.base_scraper import fetch_bytes
|
||||
from scraper.base_scraper import FetchError, fetch_bytes
|
||||
|
||||
def limited(_request, timeout):
|
||||
raise self._limited(None)
|
||||
|
||||
with mock.patch("urllib.request.urlopen", limited), self.assertRaises(ConnectionError):
|
||||
fetch_bytes("https://x", attempts=3, sleep=lambda _s: None)
|
||||
with mock.patch("urllib.request.urlopen", limited), self.assertRaises(FetchError) as caught:
|
||||
fetch_bytes("https://x")
|
||||
self.assertEqual(caught.exception.status, 429)
|
||||
|
||||
def gone(_request, timeout):
|
||||
raise urllib.error.HTTPError("u", 404, "Not Found", None, None)
|
||||
|
||||
waits: list[float] = []
|
||||
with mock.patch("urllib.request.urlopen", gone), self.assertRaises(ConnectionError):
|
||||
fetch_bytes("https://x", sleep=waits.append)
|
||||
self.assertEqual(waits, [])
|
||||
self.waits.clear()
|
||||
with mock.patch("urllib.request.urlopen", gone), self.assertRaises(FetchError) as caught:
|
||||
fetch_bytes("https://y")
|
||||
self.assertEqual((caught.exception.status, self.waits), (404, []))
|
||||
|
||||
def test_a_server_error_or_a_dropped_connection_is_retried(self):
|
||||
"""A scrape stopped on the first 500 or reset, where profile_sync
|
||||
retried the same forge."""
|
||||
import http.client
|
||||
import io
|
||||
|
||||
from scraper.base_scraper import fetch_bytes
|
||||
|
||||
answers = [urllib.error.HTTPError("u", 500, "Error", None, None),
|
||||
http.client.RemoteDisconnected("closed"), io.BytesIO(b"ok")]
|
||||
|
||||
def urlopen(_request, timeout):
|
||||
answer = answers.pop(0)
|
||||
if isinstance(answer, Exception):
|
||||
raise answer
|
||||
return answer
|
||||
|
||||
with mock.patch("urllib.request.urlopen", urlopen):
|
||||
self.assertEqual(fetch_bytes("https://x"), b"ok")
|
||||
self.assertEqual(len(self.waits), 2)
|
||||
|
||||
|
||||
class RecalboxReadsItsSystemsInBatches(unittest.TestCase):
|
||||
|
||||
@@ -915,7 +915,7 @@ class TheGitHubTokenComesFromGh(unittest.TestCase):
|
||||
|
||||
with self._gh():
|
||||
self.assertEqual(
|
||||
upstream._headers("https://api.github.com/repos/o/n")["Authorization"],
|
||||
upstream.forge_headers("https://api.github.com/repos/o/n")["Authorization"],
|
||||
"Bearer gho_fromgh",
|
||||
)
|
||||
os.environ.pop("GITHUB_TOKEN")
|
||||
@@ -930,7 +930,7 @@ class TheGitHubTokenComesFromGh(unittest.TestCase):
|
||||
from core import upstream
|
||||
|
||||
with self._gh() as run:
|
||||
headers = upstream._headers("https://gitlab.com/api/v4/projects/1")
|
||||
headers = upstream.forge_headers("https://gitlab.com/api/v4/projects/1")
|
||||
self.assertNotIn("Authorization", headers)
|
||||
run.assert_not_called()
|
||||
|
||||
|
||||
+13
-12
@@ -6,6 +6,7 @@ import tests
|
||||
|
||||
import contextlib
|
||||
import http.client
|
||||
import io
|
||||
import os
|
||||
import tempfile
|
||||
import socket
|
||||
@@ -26,10 +27,10 @@ def _no_network(url: str):
|
||||
|
||||
class _Body:
|
||||
def __init__(self, payload: bytes):
|
||||
self._payload = payload
|
||||
self._stream = io.BytesIO(payload)
|
||||
|
||||
def read(self) -> bytes:
|
||||
return self._payload
|
||||
def read(self, size: int = -1) -> bytes:
|
||||
return self._stream.read(size)
|
||||
|
||||
|
||||
def _http_error(code: int, headers=None) -> urllib.error.HTTPError:
|
||||
@@ -168,43 +169,43 @@ class TestTokenScope(unittest.TestCase):
|
||||
os.environ["GITHUB_TOKEN"] = self._orig
|
||||
|
||||
def test_sent_to_github_api(self):
|
||||
h = upstream._headers("https://api.github.com/repos/o/n/commits")
|
||||
h = upstream.forge_headers("https://api.github.com/repos/o/n/commits")
|
||||
self.assertEqual(h["Authorization"], "Bearer gho_secret")
|
||||
|
||||
def test_sent_to_github_raw(self):
|
||||
h = upstream._headers("https://raw.githubusercontent.com/o/n/sha/a.c")
|
||||
h = upstream.forge_headers("https://raw.githubusercontent.com/o/n/sha/a.c")
|
||||
self.assertIn("Authorization", h)
|
||||
|
||||
def test_withheld_from_codeberg(self):
|
||||
h = upstream._headers("https://codeberg.org/api/v1/repos/o/n/commits")
|
||||
h = upstream.forge_headers("https://codeberg.org/api/v1/repos/o/n/commits")
|
||||
self.assertNotIn("Authorization", h)
|
||||
|
||||
def test_withheld_from_gitlab(self):
|
||||
h = upstream._headers("https://gitlab.com/api/v4/projects/x/repository/commits")
|
||||
h = upstream.forge_headers("https://gitlab.com/api/v4/projects/x/repository/commits")
|
||||
self.assertNotIn("Authorization", h)
|
||||
|
||||
def test_withheld_from_forgejo_instances(self):
|
||||
for host in ("git.citron-emu.org", "git.eden-emu.dev", "git.ryujinx.app"):
|
||||
h = upstream._headers(f"https://{host}/api/v1/repos/o/n/commits")
|
||||
h = upstream.forge_headers(f"https://{host}/api/v1/repos/o/n/commits")
|
||||
self.assertNotIn("Authorization", h, host)
|
||||
|
||||
def test_withheld_from_a_lookalike_host(self):
|
||||
h = upstream._headers("https://github.com.evil.example/repos/o/n")
|
||||
h = upstream.forge_headers("https://github.com.evil.example/repos/o/n")
|
||||
self.assertNotIn("Authorization", h)
|
||||
|
||||
def test_withheld_from_a_url_that_only_names_the_api(self):
|
||||
h = upstream._headers("https://evil.example/x?next=https://api.github.com/")
|
||||
h = upstream.forge_headers("https://evil.example/x?next=https://api.github.com/")
|
||||
self.assertNotIn("Authorization", h)
|
||||
|
||||
def test_withheld_from_the_web_host(self):
|
||||
# A release download on github.com redirects to asset storage, and
|
||||
# urllib carries the header across the redirect.
|
||||
h = upstream._headers("https://github.com/o/n/releases/download/v1/a.zip")
|
||||
h = upstream.forge_headers("https://github.com/o/n/releases/download/v1/a.zip")
|
||||
self.assertNotIn("Authorization", h)
|
||||
|
||||
def test_absent_token_adds_no_header(self):
|
||||
os.environ.pop("GITHUB_TOKEN", None)
|
||||
h = upstream._headers("https://api.github.com/repos/o/n")
|
||||
h = upstream.forge_headers("https://api.github.com/repos/o/n")
|
||||
self.assertNotIn("Authorization", h)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user