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:
Abdessamad Derraz committed 2026-11-21 06:00:20 +01:00
1 parent 75b5fb987e
commit fdd7595a71
5 files changed
+145 -92

No files matched your search

+42 -10
View File
@@ -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):
+2 -2
View File
@@ -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
View File
@@ -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)