refactor: route network access through upstream

Branch heads (scrapers, FBNeo import, data directories) resolve through
core.upstream.resolve_head, with cache_dir=None to keep nothing under
.cache/upstream. Streaming downloads (large files, external pack files,
data directory archives, scraper downloads, standalone probe) go through
one core.upstream.download: scratch then rename, size cap, retries of a
cut stream, a 5xx or a rate limit. The shared rate limit wait reads
GoatCounter's X-Rate-Limit-Reset, so site insights, download.py,
indexnow and the contributor list use the same retrying client.

list_gitlinks raises TruncatedListingError on a partial tree, read
from one tree walk shared with list_tree (Forgejo paging included).
The Recalbox configs/ listing is paged with the shared page cap.
This commit is contained in:
Abdessamad Derraz committed 2026-11-21 10:30:13 +01:00
1 parent 526d7f09c7
commit 8a8fa71fbc
25 files changed
+708 -266

No files matched your search

+131 -48
View File
@@ -24,9 +24,9 @@ import urllib.request
from dataclasses import dataclass from dataclasses import dataclass
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
from typing import Callable, Protocol, TypeVar from typing import Callable, Mapping, Protocol, TypeVar
from core.artifacts import write_text_atomic from core.artifacts import atomic_scratch, write_text_atomic
USER_AGENT = "retrobios-profile-sync/1.0" USER_AGENT = "retrobios-profile-sync/1.0"
# Where fetched upstream files live, shared by every reader of this cache. # Where fetched upstream files live, shared by every reader of this cache.
@@ -123,6 +123,12 @@ class NotCachedError(UpstreamError):
""" """
class TruncatedListingError(UpstreamError):
"""A listing the forge served in part: a page that could not be read,
the page cap, or a tree GitHub cut short. What it holds is real, but an
absence from it proves nothing."""
class GoneError(UpstreamError): class GoneError(UpstreamError):
"""The upstream is not coming back. """The upstream is not coming back.
@@ -307,17 +313,36 @@ def _resolver_answers() -> bool:
return True return True
class _Headers(Protocol):
def get(self, name: str, /) -> str | None: ...
def requested_wait(headers: _Headers | None) -> float | None:
"""Seconds a 429 asks the client to wait, None when it names none.
Retry-After is the standard header. GoatCounter sends X-Rate-Limit-Reset
instead, the whole seconds left in its window, so one more second is
added: asked again on the second it names, the window is still closed.
"""
if not headers:
return None
retry_after = (headers.get("Retry-After") or "").strip()
if retry_after.isdigit():
return float(retry_after)
reset = (headers.get("X-Rate-Limit-Reset") or "").strip()
return float(reset) + 1 if reset.isdigit() else None
def _rate_limit_wait(exc: urllib.error.HTTPError, waited: int) -> float | None: def _rate_limit_wait(exc: urllib.error.HTTPError, waited: int) -> float | None:
"""Seconds to wait before asking again, or None when waiting is futile. """Seconds to wait before asking again, or None when waiting is futile.
GitHub's exhausted quota (403) resets on the hour. A 429 names its wait GitHub's exhausted quota (403) resets on the hour. A 429 names its wait
in Retry-After, which is followed up to a cap, else the fixed steps. (requested_wait), which is followed up to a cap, else the fixed steps.
""" """
if exc.code != 429 or waited >= len(RATE_LIMIT_WAITS): if exc.code != 429 or waited >= len(RATE_LIMIT_WAITS):
return None return None
retry_after = (exc.headers.get("Retry-After") or "").strip() if exc.headers else "" delay = requested_wait(exc.headers)
if retry_after.isdigit(): if delay is not None:
delay = float(retry_after)
return delay if delay <= RATE_LIMIT_WAIT_CAP else None return delay if delay <= RATE_LIMIT_WAIT_CAP else None
return RATE_LIMIT_WAITS[waited] return RATE_LIMIT_WAITS[waited]
@@ -426,12 +451,65 @@ def remote_etag(url: str, timeout: float = 30) -> str | None:
url, method="HEAD", headers=forge_headers(url, user_agent="retrobios/1.0") url, method="HEAD", headers=forge_headers(url, user_agent="retrobios/1.0")
) )
try: try:
with urllib.request.urlopen(req, timeout=timeout) as resp: return open_retrying(
return resp.headers.get("ETag") or resp.headers.get("Last-Modified") or "" req,
except (urllib.error.URLError, OSError): lambda resp: resp.headers.get("ETag") or resp.headers.get("Last-Modified") or "",
timeout,
)
except (urllib.error.URLError, http.client.HTTPException, OSError, UpstreamError):
return None return None
class _Refused(Exception):
"""A finished download the caller's check turned down."""
def download(
url: str,
destination: str | os.PathLike[str],
*,
headers: Mapping[str, str] | None = None,
timeout: float = 300,
max_bytes: int | None = None,
user_agent: str = USER_AGENT,
accept: Callable[[str], bool] | None = None,
) -> http.client.HTTPMessage | None:
"""Stream `url` into `destination`, whole or not at all, and return the
response headers.
The body goes to a unique scratch beside the destination, renamed into
place once complete, so a reader or an interrupted run never sees half a
file and two runs never interleave their bytes. Each attempt of
open_retrying starts the scratch over: a stream cut midway is retried
like a refused connection. `headers` add to or replace forge_headers().
A body past `max_bytes` raises ValueError. `accept` judges the finished
scratch by its path: refused, nothing is written and None is returned.
A failure raises as open_retrying raises it.
"""
request = urllib.request.Request(
url, headers={**forge_headers(url, user_agent=user_agent), **(headers or {})}
)
def save(scratch: str, resp: http.client.HTTPResponse) -> http.client.HTTPMessage:
total = 0
with open(scratch, "wb") as out:
while chunk := resp.read(1 << 20):
total += len(chunk)
if max_bytes is not None and total > max_bytes:
raise ValueError(f"{url}: response exceeds {max_bytes} byte limit")
out.write(chunk)
return resp.headers
try:
with atomic_scratch(destination) as scratch:
served = open_retrying(request, lambda resp: save(scratch, resp), timeout)
if accept is not None and not accept(scratch):
raise _Refused
except _Refused:
return None
return served
def http_json(url: str) -> object | None: def http_json(url: str) -> object | None:
"""Parsed JSON body of a GET, or None on 404. Replaced in tests.""" """Parsed JSON body of a GET, or None on 404. Replaced in tests."""
body = fetch_body(url, accept_json=True) body = fetch_body(url, accept_json=True)
@@ -611,21 +689,28 @@ def current_slug(repo: Repo, cache_dir: str, offline: bool = False) -> str | Non
def resolve_head( def resolve_head(
repo: Repo, cache_dir: str, offline: bool = False, branch: str | None = None, repo: Repo, cache_dir: str | None, offline: bool = False, branch: str | None = None,
fresh: bool = False, fresh: bool = False,
) -> str | None: ) -> str | None:
"""Sha of a branch tip, the default branch unless one is named. """Sha of a branch tip, the default branch unless one is named. A tag
resolves too: every forge's commit listing starts from any ref.
A libretro port often lives on a branch of a fork rather than on the A libretro port often lives on a branch of a fork rather than on the
default branch, so the code a profile documents can be absent from the default branch, so the code a profile documents can be absent from the
tip the forge serves by default. ``fresh`` asks the forge again whatever tip the forge serves by default. ``fresh`` asks the forge again whatever
the cache holds. the cache holds. A ``cache_dir`` of None asks the forge and keeps
nothing: a scraper records the sha it read in its own output, and an
answer it never reads back has no place in the profile cache.
Offline, a tip the cache never stored raises NotCachedError: returning Offline, a tip the cache never stored raises NotCachedError: returning
None read as a branch the forge does not have, and profile_sync dropped None read as a branch the forge does not have, and profile_sync dropped
xenios-jp/XeniOS, judging its citations against the other repository. xenios-jp/XeniOS, judging its citations against the other repository.
""" """
url = _commits_url(repo, None, branch) url = _commits_url(repo, None, branch)
if cache_dir is None:
if offline:
raise NotCachedError(f"{repo.slug}: no cache to read offline")
return _first_sha(http_json(url))
_require_cached( _require_cached(
url, cache_dir, offline, f"{repo.slug}: tip of {branch or 'the default branch'}" url, cache_dir, offline, f"{repo.slug}: tip of {branch or 'the default branch'}"
) )
@@ -1057,17 +1142,6 @@ def gitlab_tree_entries(
return entries, True return entries, True
def _gitlab_tree(
repo: Repo, sha: str, cache_dir: str, offline: bool
) -> tuple[list[str], bool]:
entries, truncated = gitlab_tree_entries(repo, sha, cache_dir, offline)
paths = [
entry["path"] for entry in entries
if entry.get("type") == "blob" and entry.get("path")
]
return paths, truncated
def cache_gitlab_directory( def cache_gitlab_directory(
repo: Repo, sha: str, directory: str, cache_dir: str, offline: bool = False repo: Repo, sha: str, directory: str, cache_dir: str, offline: bool = False
) -> set[str] | None: ) -> set[str] | None:
@@ -1149,18 +1223,19 @@ def _sparse_git_files(repo: Repo, sha: str, directory: str, cache_dir: str) -> d
shutil.rmtree(work, ignore_errors=True) shutil.rmtree(work, ignore_errors=True)
def list_tree( def _tree_entries(
repo: Repo, sha: str, cache_dir: str, offline: bool = False repo: Repo, sha: str, cache_dir: str, offline: bool
) -> tuple[list[str], bool]: ) -> tuple[list[dict], bool] | None:
"""Every blob path at one revision, and whether the forge truncated it.""" """Every entry of the tree at one revision, and whether the forge served
it in part. None when the forge serves no tree for it."""
if repo.family == "gitlab": if repo.family == "gitlab":
return _gitlab_tree(repo, sha, cache_dir, offline) return gitlab_tree_entries(repo, sha, cache_dir, offline)
url = _tree_url(repo, sha) url = _tree_url(repo, sha)
if url is None: if url is None:
return [], True return None
payload = cached_api(url, cache_dir, offline) payload = cached_api(url, cache_dir, offline)
if not isinstance(payload, dict): if not isinstance(payload, dict):
return [], True return None
entries = list(payload.get("tree") or []) entries = list(payload.get("tree") or [])
truncated = bool(payload.get("truncated")) truncated = bool(payload.get("truncated"))
# Forgejo pages a recursive tree, 1000 entries at a time, and says how # Forgejo pages a recursive tree, 1000 entries at a time, and says how
@@ -1177,10 +1252,20 @@ def list_tree(
break break
entries.extend(more["tree"]) entries.extend(more["tree"])
truncated = len(entries) < total truncated = len(entries) < total
return [entry for entry in entries if isinstance(entry, dict)], truncated
def list_tree(
repo: Repo, sha: str, cache_dir: str, offline: bool = False
) -> tuple[list[str], bool]:
"""Every blob path at one revision, and whether the forge truncated it."""
listing = _tree_entries(repo, sha, cache_dir, offline)
if listing is None:
return [], True
entries, truncated = listing
paths = [ paths = [
entry["path"] entry["path"] for entry in entries
for entry in entries if entry.get("type") == "blob" and entry.get("path")
if isinstance(entry, dict) and entry.get("type") == "blob" and entry.get("path")
] ]
return paths, truncated return paths, truncated
@@ -1191,24 +1276,22 @@ def list_gitlinks(
"""Submodule path -> the commit it points at, at one revision. """Submodule path -> the commit it points at, at one revision.
Read from the same tree listing as list_tree, so the call costs nothing Read from the same tree listing as list_tree, so the call costs nothing
once the tree is cached. once the tree is cached. A listing the forge served in part raises
TruncatedListingError: a partial answer read as "no submodule there",
and a port then lost the upstream commit its gitlink pins.
""" """
if repo.family == "gitlab": listing = _tree_entries(repo, sha, cache_dir, offline)
entries, _truncated = gitlab_tree_entries(repo, sha, cache_dir, offline) if listing is None:
return {
entry["path"]: entry["id"]
for entry in entries
if entry.get("type") == "commit" and entry.get("path") and entry.get("id")
}
tree_url = _tree_url(repo, sha)
payload = cached_api(tree_url, cache_dir, offline) if tree_url else None
if not isinstance(payload, dict):
return {} return {}
entries, truncated = listing
if truncated:
raise TruncatedListingError(f"{repo.slug}@{sha[:8]}: tree listing truncated")
# GitLab names the target commit `id`, GitHub and Forgejo `sha`.
key = "id" if repo.family == "gitlab" else "sha"
return { return {
entry["path"]: entry["sha"] entry["path"]: entry[key]
for entry in payload.get("tree") or [] for entry in entries
if isinstance(entry, dict) and entry.get("type") == "commit" if entry.get("type") == "commit" and entry.get("path") and entry.get(key)
and entry.get("path") and entry.get("sha")
} }
+21 -14
View File
@@ -18,6 +18,7 @@ Usage:
from __future__ import annotations from __future__ import annotations
import argparse import argparse
import http.client
import json import json
import os import os
import re import re
@@ -34,7 +35,7 @@ sys.path.insert(0, os.path.dirname(__file__))
from core.hashing import compute_hashes, parse_sha256sums from core.hashing import compute_hashes, parse_sha256sums
from core.paths import REPO_ROOT from core.paths import REPO_ROOT
from core.sizes import size_text from core.sizes import size_text
from core.upstream import forge_headers from core.upstream import UpstreamError, forge_headers, open_retrying
from core.ziptools import safe_extract_zip from core.ziptools import safe_extract_zip
from packs.parts import part_of from packs.parts import part_of
from model.releaserecord import PACK_SUFFIX, RECORD, load_record, match_key, pack_label, recorded_pack from model.releaserecord import PACK_SUFFIX, RECORD, load_record, match_key, pack_label, recorded_pack
@@ -104,8 +105,7 @@ def get_latest_release() -> dict:
req = urllib.request.Request(url, headers=headers) req = urllib.request.Request(url, headers=headers)
try: try:
with urllib.request.urlopen(req, timeout=30) as resp: return json.loads(open_retrying(req, lambda resp: resp.read(), 30))
return json.loads(resp.read())
except urllib.error.HTTPError as e: except urllib.error.HTTPError as e:
if e.code == 404: if e.code == 404:
print("No releases found. The repository may not have any releases yet.") print("No releases found. The repository may not have any releases yet.")
@@ -182,8 +182,9 @@ def fetch_checksums(release: dict) -> dict[str, str]:
req = urllib.request.Request( req = urllib.request.Request(
url, headers={"User-Agent": "retrobios-downloader/1.0"} url, headers={"User-Agent": "retrobios-downloader/1.0"}
) )
with urllib.request.urlopen(req, timeout=60) as resp: body = open_retrying(
body = resp.read(MAX_CHECKSUMS_BYTES).decode("utf-8", "replace") req, lambda resp: resp.read(MAX_CHECKSUMS_BYTES), 60
).decode("utf-8", "replace")
# A file that is not sha256sum output refuses the download: read # A file that is not sha256sum output refuses the download: read
# leniently, a `*name` line matched nothing and the pack went # leniently, a `*name` line matched nothing and the pack went
# unchecked. # unchecked.
@@ -197,7 +198,12 @@ def fetch_checksums(release: dict) -> dict[str, str]:
def download_file( def download_file(
url: str, dest: Path, expected_size: int = 0, label: str = "" url: str, dest: Path, expected_size: int = 0, label: str = ""
) -> None: ) -> None:
"""Download a file with progress indication.""" """Download a file with progress indication.
core.upstream.open_retrying asks again after a dropped connection, a
stream cut midway or a 5xx, and waits out a rate limit: each attempt
writes `dest` from its first byte.
"""
url = _checked_url(url, "asset URL") url = _checked_url(url, "asset URL")
req = urllib.request.Request( req = urllib.request.Request(
url, headers={"User-Agent": "retrobios-downloader/1.0"} url, headers={"User-Agent": "retrobios-downloader/1.0"}
@@ -206,19 +212,15 @@ def download_file(
# A redrawn bar only on a terminal: written to a log, 32,768 redraws of a # A redrawn bar only on a terminal: written to a log, 32,768 redraws of a
# 2 GiB part made one line of nearly 3 MB. # 2 GiB part made one line of nearly 3 MB.
live = sys.stdout.isatty() and os.environ.get("TERM") != "dumb" live = sys.stdout.isatty() and os.environ.get("TERM") != "dumb"
with urllib.request.urlopen(req, timeout=300) as resp:
def save(resp: http.client.HTTPResponse) -> int:
total = int(resp.headers.get("Content-Length", expected_size)) total = int(resp.headers.get("Content-Length", expected_size))
downloaded = 0 downloaded = 0
shown = -1 shown = -1
with open(dest, "wb") as f: with open(dest, "wb") as f:
while True: while chunk := resp.read(65536):
chunk = resp.read(65536)
if not chunk:
break
f.write(chunk) f.write(chunk)
downloaded += len(chunk) downloaded += len(chunk)
if total > 0 and live: if total > 0 and live:
pct = downloaded * 100 // total pct = downloaded * 100 // total
if pct != shown: if pct != shown:
@@ -226,7 +228,9 @@ def download_file(
columns = shutil.get_terminal_size((80, 24)).columns columns = shutil.get_terminal_size((80, 24)).columns
line = _progress_line(label, downloaded, total, columns) line = _progress_line(label, downloaded, total, columns)
print(f"\r\033[K{line}", end="", flush=True) print(f"\r\033[K{line}", end="", flush=True)
return downloaded
downloaded = open_retrying(req, save, 300)
if live: if live:
print() print()
else: else:
@@ -373,6 +377,8 @@ To check files already in place, use: python install.py --check
urllib.error.URLError, urllib.error.URLError,
urllib.error.HTTPError, urllib.error.HTTPError,
OSError, OSError,
http.client.HTTPException,
UpstreamError,
json.JSONDecodeError, json.JSONDecodeError,
) as e: ) as e:
print(f"Error: {e}", file=sys.stderr) print(f"Error: {e}", file=sys.stderr)
@@ -384,7 +390,8 @@ To check files already in place, use: python install.py --check
try: try:
release = get_latest_release() release = get_latest_release()
except (urllib.error.URLError, urllib.error.HTTPError, OSError) as e: except (urllib.error.URLError, OSError, http.client.HTTPException, UpstreamError,
json.JSONDecodeError) as e:
print(f"Error fetching release info: {e}", file=sys.stderr) print(f"Error fetching release info: {e}", file=sys.stderr)
sys.exit(1) sys.exit(1)
+3 -10
View File
@@ -22,11 +22,10 @@ import argparse
import json import json
import os import os
import sys import sys
import urllib.error
import urllib.request
from pathlib import Path from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__)) sys.path.insert(0, os.path.dirname(__file__))
from core import upstream
from sitegen.agents import INDEXNOW_FILE, INDEXNOW_KEY, SITE from sitegen.agents import INDEXNOW_FILE, INDEXNOW_KEY, SITE
HOST = "abdess.github.io" HOST = "abdess.github.io"
@@ -38,14 +37,8 @@ USER_AGENT = "retrobios-indexnow"
def live_digests(url: str = f"{SITE}digests.json") -> dict[str, str]: def live_digests(url: str = f"{SITE}digests.json") -> dict[str, str]:
"""The digests the live site serves. None yet (the first deploy that """The digests the live site serves. None yet (the first deploy that
writes them) is an empty map: every page is new.""" writes them) is an empty map: every page is new."""
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) body = upstream.fetch_body(url, timeout=60, user_agent=USER_AGENT)
try: return {} if body is None else json.loads(body.decode("utf-8"))
with urllib.request.urlopen(request, timeout=60) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
if exc.code == 404:
return {}
raise
def changed_urls(new: dict[str, str], old: dict[str, str]) -> list[str]: def changed_urls(new: dict[str, str], old: dict[str, str]) -> list[str]:
+15 -15
View File
@@ -31,6 +31,7 @@ LARGE_FILES_RELEASE = "large-files"
LARGE_FILES_REPO = "Abdess/retrobios" LARGE_FILES_REPO = "Abdess/retrobios"
RELEASE_DOWNLOAD = f"https://github.com/{LARGE_FILES_REPO}/releases/download/{LARGE_FILES_RELEASE}/" RELEASE_DOWNLOAD = f"https://github.com/{LARGE_FILES_REPO}/releases/download/{LARGE_FILES_RELEASE}/"
LARGE_FILES_CACHE = ".cache/large" LARGE_FILES_CACHE = ".cache/large"
USER_AGENT = "retrobios/1.0"
# Verified revisions, hard-linked as <sha1>/<asset> beside the cache. A name # Verified revisions, hard-linked as <sha1>/<asset> beside the cache. A name
# in the cache is replaced when the release serves new bytes under it, so a # in the cache is replaced when the release serves new bytes under it, so a
# path handed out by name could hold other bytes by the time the caller read # path handed out by name could hold other bytes by the time the caller read
@@ -210,22 +211,20 @@ def restore_verified(source: str, path: str, sha1: str) -> bool:
os.unlink(scratch) os.unlink(scratch)
_FAILURES = (urllib.error.URLError, OSError, http.client.HTTPException, upstream.UpstreamError)
def _download(name: str, tmp_path: str) -> bool: def _download(name: str, tmp_path: str) -> bool:
"""Stream the first release URL of *name* that answers into *tmp_path*.""" """Stream the first release URL of *name* that answers into *tmp_path*,
each through core.upstream.download (scratch, rename, retries)."""
# Only a name no candidate answers is reported: a spaced name is # Only a name no candidate answers is reported: a spaced name is
# published dotted, and logging its first 404 read as a missing asset. # published dotted, and logging its first 404 read as a missing asset.
failures: list[str] = [] failures: list[str] = []
for candidate, url in _asset_urls(name): for candidate, url in _asset_urls(name):
try: try:
req = urllib.request.Request(url, headers={"User-Agent": "retrobios/1.0"}) upstream.download(url, tmp_path, timeout=300, user_agent=USER_AGENT)
with urllib.request.urlopen(req, timeout=300) as resp, open(tmp_path, "wb") as f:
while True:
chunk = resp.read(65536)
if not chunk:
break
f.write(chunk)
return True return True
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc: except _FAILURES as exc:
# A stalled or cut stream is a timeout or IncompleteRead, not # A stalled or cut stream is a timeout or IncompleteRead, not
# a URLError: it escaped this handler and left its scratch. # a URLError: it escaped this handler and left its scratch.
failures.append(f" large file {candidate}: {exc}") failures.append(f" large file {candidate}: {exc}")
@@ -432,7 +431,7 @@ def _served_digests() -> dict[str, str]:
f"{LARGE_FILES_RELEASE}" f"{LARGE_FILES_RELEASE}"
) )
try: try:
body = upstream.fetch_body(url, accept_json=True, timeout=60, user_agent="retrobios/1.0") body = upstream.fetch_body(url, accept_json=True, timeout=60, user_agent=USER_AGENT)
release = json.loads(body) if body is not None else {} release = json.loads(body) if body is not None else {}
except (upstream.UpstreamError, ValueError) as exc: except (upstream.UpstreamError, ValueError) as exc:
print(f" large files release listing: {exc}", file=sys.stderr) print(f" large files release listing: {exc}", file=sys.stderr)
@@ -445,13 +444,14 @@ def _served_digests() -> dict[str, str]:
def _served_size(name: str) -> int | None: def _served_size(name: str) -> int | None:
"""Size of the asset the release serves now, or None when unreadable.""" """Size of the asset the release serves now, or None when unreadable."""
for candidate, url in _asset_urls(name): for candidate, url in _asset_urls(name):
req = urllib.request.Request(
url, method="HEAD", headers=upstream.forge_headers(url, user_agent=USER_AGENT)
)
try: try:
req = urllib.request.Request( length = upstream.open_retrying(
url, method="HEAD", headers={"User-Agent": "retrobios/1.0"} req, lambda resp: resp.headers.get("Content-Length"), 60
) )
with urllib.request.urlopen(req, timeout=60) as resp: except _FAILURES as exc:
length = resp.headers.get("Content-Length")
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
print(f" large file {candidate}: {exc}", file=sys.stderr) print(f" large file {candidate}: {exc}", file=sys.stderr)
continue continue
if length and length.isdigit(): if length and length.isdigit():
+32 -25
View File
@@ -3,6 +3,7 @@
from __future__ import annotations from __future__ import annotations
import contextlib import contextlib
import http.client
import json import json
import logging import logging
import os import os
@@ -30,9 +31,14 @@ REQUEST_TIMEOUT = 30
DOWNLOAD_TIMEOUT = 300 DOWNLOAD_TIMEOUT = 300
# A mirror sometimes answers with a page that is not the archive: the # A mirror sometimes answers with a page that is not the archive: the
# buildbot's ScummVM.zip failed CI once as "File is not a zip file" and # buildbot's ScummVM.zip failed CI once as "File is not a zip file" and
# downloaded fine minutes later. Seconds to wait before each retry. # downloaded fine minutes later. Seconds to wait before each retry. The
# transfer itself is retried by core.upstream.download: these waits cover
# an archive that arrived whole and does not read.
DOWNLOAD_RETRY_WAITS = (5, 20) DOWNLOAD_RETRY_WAITS = (5, 20)
_TRANSIENT = (urllib.error.URLError, OSError, tarfile.TarError, zipfile.BadZipFile, EOFError) _TRANSIENT = (
urllib.error.URLError, OSError, http.client.HTTPException,
tarfile.TarError, zipfile.BadZipFile, EOFError,
)
def cache_lock( def cache_lock(
@@ -172,13 +178,14 @@ def revisioned(entry: dict) -> bool:
def get_remote_sha(source_url: str, version: str) -> str | None: def get_remote_sha(source_url: str, version: str) -> str | None:
"""The commit a branch or tag of the source's repository points at now.""" """The commit a branch or tag of the source's repository points at now,
asked of the forge each time and kept nowhere but the versions file."""
repo = upstream.parse_repo(source_url) repo = upstream.parse_repo(source_url)
if repo is None: if repo is None:
log.warning("cannot parse repo from URL: %s", source_url) log.warning("cannot parse repo from URL: %s", source_url)
return None return None
try: try:
return upstream.resolve_head(repo, upstream.CACHE_DIR, branch=version, fresh=True) return upstream.resolve_head(repo, None, branch=version)
except (upstream.UpstreamError, ValueError) as exc: except (upstream.UpstreamError, ValueError) as exc:
log.warning("failed to fetch remote SHA for %s@%s: %s", repo.slug, version, exc) log.warning("failed to fetch remote SHA for %s@%s: %s", repo.slug, version, exc)
return None return None
@@ -223,13 +230,9 @@ def _download_and_extract(
tarball_path = Path(tmpdir) / "archive.tar.gz" tarball_path = Path(tmpdir) / "archive.tar.gz"
log.info("downloading %s", source_url) log.info("downloading %s", source_url)
req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT}) upstream.download(
with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp, open(tarball_path, "wb") as f: source_url, tarball_path, timeout=DOWNLOAD_TIMEOUT, user_agent=USER_AGENT
while True: )
chunk = resp.read(65536)
if not chunk:
break
f.write(chunk)
if measured is not None: if measured is not None:
measured(tarball_path.stat().st_size) measured(tarball_path.stat().st_size)
@@ -304,13 +307,9 @@ def _download_and_extract_zip(
zip_path = Path(tmpdir) / "archive.zip" zip_path = Path(tmpdir) / "archive.zip"
log.info("downloading %s", source_url) log.info("downloading %s", source_url)
req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT}) upstream.download(
with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp, open(zip_path, "wb") as f: source_url, zip_path, timeout=DOWNLOAD_TIMEOUT, user_agent=USER_AGENT
while True: )
chunk = resp.read(65536)
if not chunk:
break
f.write(chunk)
if measured is not None: if measured is not None:
measured(zip_path.stat().st_size) measured(zip_path.stat().st_size)
@@ -352,13 +351,19 @@ def _download_and_extract_zip(
def _measure_archive(source_url: str) -> int | None: def _measure_archive(source_url: str) -> int | None:
"""The size of the archive at source_url, read by streaming it: a """The size of the archive at source_url, read by streaming it: a
tarball GitHub builds on request is sent without a Content-Length.""" tarball GitHub builds on request is sent without a Content-Length."""
req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT}) req = urllib.request.Request(
size = 0 source_url, headers=upstream.forge_headers(source_url, user_agent=USER_AGENT)
)
def count(resp: http.client.HTTPResponse) -> int:
size = 0
while chunk := resp.read(65536):
size += len(chunk)
return size
try: try:
with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp: size = upstream.open_retrying(req, count, DOWNLOAD_TIMEOUT)
while chunk := resp.read(65536): except (*_TRANSIENT, upstream.UpstreamError) as exc:
size += len(chunk)
except _TRANSIENT as exc:
log.warning("could not measure %s: %s", source_url, exc) log.warning("could not measure %s: %s", source_url, exc)
return None return None
return size or None return size or None
@@ -517,7 +522,9 @@ def _refresh_entry(
try: try:
file_count = fetch() file_count = fetch()
break break
except (NothingExtractedError, ValueError) as exc: except (NothingExtractedError, ValueError, upstream.UpstreamError) as exc:
# A host gone or still rate limited after core.upstream's own
# waits answers the same way on the next try.
log.warning("[%s] download failed: %s", key, exc) log.warning("[%s] download failed: %s", key, exc)
return None return None
except _TRANSIENT as exc: except _TRANSIENT as exc:
+3
View File
@@ -165,6 +165,9 @@ def _follow_submodule(
HEAD, the view reported changes the shipped core never had, and a bump HEAD, the view reported changes the shipped core never had, and a bump
would have moved upstream_commit past what it builds. The commit the would have moved upstream_commit past what it builds. The commit the
port's HEAD points the submodule at is the upstream HEAD that matters. port's HEAD points the submodule at is the upstream HEAD that matters.
A tree the forge lists in part raises TruncatedListingError: the
submodule may be in the lost part, and the upstream HEAD in its place
is the commit a bump must not move to.
""" """
source = next((v for v in views if v.field == "source"), None) source = next((v for v in views if v.field == "source"), None)
behind = [v for v in views if v.field == "upstream" and v.pin != v.head] behind = [v for v in views if v.field == "upstream" and v.pin != v.head]
+22 -9
View File
@@ -7,7 +7,7 @@ import itertools
import posixpath import posixpath
import re import re
import sys import sys
from collections.abc import Callable, Iterable, Sequence from collections.abc import Callable, Iterable, Iterator, Sequence
from dataclasses import dataclass, field, replace from dataclasses import dataclass, field, replace
from core import upstream from core import upstream
@@ -406,11 +406,16 @@ class _Resolver:
(self.context_for(v)[1] for v in self.views), (self.context_for(v)[1] for v in self.views),
) )
def gitlinks_in_order(self) -> Iterable[Iterable[str]]: def gitlinks_in_order(self) -> Iterator[Iterable[str]]:
return ( """Submodule paths of each declared tree at its pin. A tree the
upstream.list_gitlinks(v.repo, v.pin, self.cache_dir, self.offline) forge lists in part is said once and searched as far as it is
for v in self.views known: the parts it cannot place stay external, as before."""
) for view in self.views:
try:
yield upstream.list_gitlinks(view.repo, view.pin, self.cache_dir, self.offline)
except upstream.TruncatedListingError as exc:
print(f"{self.name}: submodule paths unknown, {exc}", file=sys.stderr)
yield ()
def _add_bare_name_matches(self, path: str, candidates: list[str]) -> None: def _add_bare_name_matches(self, path: str, candidates: list[str]) -> None:
# A bare filename, the way prose cites files. Resolved against the # A bare filename, the way prose cites files. Resolved against the
@@ -589,9 +594,17 @@ class _Resolver:
if found is None and "/" in wanted: if found is None and "/" in wanted:
# A file of a submodule is read at the commit its gitlink # A file of a submodule is read at the commit its gitlink
# pins in this revision, so a bump moves it with the port. # pins in this revision, so a bump moves it with the port.
inner = upstream.through_gitlink( try:
repo, sha, wanted, self.cache_dir, self.offline inner = upstream.through_gitlink(
) repo, sha, wanted, self.cache_dir, self.offline
)
except upstream.TruncatedListingError as exc:
# The tree is listed in part: the path may sit in a
# submodule nobody can see, which is no reason to mute
# every other file of the repository.
print(f"{self.name}: {wanted} not followed into a submodule, {exc}",
file=sys.stderr)
inner = None
if inner is not None: if inner is not None:
found = upstream.fetch_file(*inner, self.cache_dir, self.offline) found = upstream.fetch_file(*inner, self.cache_dir, self.offline)
return found return found
+14 -15
View File
@@ -7,17 +7,17 @@ and the offline switch that forbids reaching for the network."""
from __future__ import annotations from __future__ import annotations
import contextlib import contextlib
import hashlib import http.client
import os import os
import re import re
import urllib.error import urllib.error
import urllib.request
from collections.abc import Iterator from collections.abc import Iterator
from pathlib import Path from pathlib import Path
from core import upstream
from model.database import record_at, record_for_hash from model.database import record_at, record_for_hash
from model.largefiles import fetch_large_file from model.largefiles import fetch_large_file
from core.hashing import declared_hash_lists from core.hashing import declared_hash_lists, file_digest
from resolve.content import declared_hash_verdict from resolve.content import declared_hash_verdict
from resolve.localfile import resolution_is_hash_exact, resolve_local_file from resolve.localfile import resolution_is_hash_exact, resolve_local_file
from core.paths import REPO_ROOT, declared_destination from core.paths import REPO_ROOT, declared_destination
@@ -58,8 +58,10 @@ def download_external(
"""Download a `storage: external` file, verify its hash, write dest_path. """Download a `storage: external` file, verify its hash, write dest_path.
The run's network policy applies: under --offline nothing is fetched and The run's network policy applies: under --offline nothing is fetched and
the entry stays missing, as verify reports it. The body is streamed to the entry stays missing, as verify reports it. core.upstream.download
dest_path and hashed on the way, and removed when the hash disagrees. streams the body to a scratch beside dest_path, retried on a transient
failure, and dest_path is written only once the scratch hashes to the
declared value.
""" """
url = file_entry.get("source_url") url = file_entry.get("source_url")
if not url: if not url:
@@ -75,21 +77,18 @@ def download_external(
print(f" WARNING: {name} is external and the run is offline, not fetched") print(f" WARNING: {name} is external and the run is offline, not fetched")
return False return False
algo, expected = declared[0], set(declared[1]) algo, expected = declared[0], set(declared[1])
digest = hashlib.new(algo)
Path(dest_path).parent.mkdir(parents=True, exist_ok=True) Path(dest_path).parent.mkdir(parents=True, exist_ok=True)
try: try:
req = urllib.request.Request(url, headers={"User-Agent": "retrobios-pack-gen/1.0"}) served = upstream.download(
with urllib.request.urlopen(req, timeout=120) as resp, open(dest_path, "wb") as out: url, dest_path, timeout=120, user_agent="retrobios-pack-gen/1.0",
for chunk in iter(lambda: resp.read(1 << 20), b""): accept=lambda scratch: file_digest(Path(scratch), algo) in expected,
digest.update(chunk) )
out.write(chunk) except (urllib.error.URLError, OSError, http.client.HTTPException,
except (urllib.error.URLError, OSError) as exc: upstream.UpstreamError, ValueError) as exc:
print(f" WARNING: Failed to download {url}: {exc}") print(f" WARNING: Failed to download {url}: {exc}")
Path(dest_path).unlink(missing_ok=True)
return False return False
if digest.hexdigest() not in expected: if served is None:
print(f" WARNING: {algo.upper()} mismatch for {name}") print(f" WARNING: {algo.upper()} mismatch for {name}")
Path(dest_path).unlink(missing_ok=True)
return False return False
return True return True
+47 -27
View File
@@ -3,6 +3,7 @@
from __future__ import annotations from __future__ import annotations
import argparse import argparse
import contextlib
import http.client import http.client
import inspect import inspect
import json import json
@@ -14,18 +15,21 @@ import urllib.request
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from dataclasses import dataclass, field from dataclasses import dataclass, field
from pathlib import Path from pathlib import Path
from typing import Any, Callable, NoReturn, TypeVar from typing import Any, Callable, Iterator, NoReturn, TypeVar
from core.github import github_token from core.github import github_token
from core.artifacts import copy_stream_atomic, write_text_atomic from core.artifacts import write_text_atomic
from core.hashing import git_blob_sha from core.hashing import git_blob_sha
from core.upstream import ( from core.upstream import (
MAX_RESPONSE_SIZE, MAX_RESPONSE_SIZE,
RateLimitError, RateLimitError,
UpstreamError, UpstreamError,
make_repo,
open_retrying, open_retrying,
read_limited, read_limited,
resolve_head,
) )
from core.upstream import download as upstream_download
from core.upstream import forge_headers as upstream_headers from core.upstream import forge_headers as upstream_headers
from model.safeparse import require_yaml, yaml_load from model.safeparse import require_yaml, yaml_load
@@ -174,6 +178,21 @@ def github_headers() -> dict[str, str]:
return forge_headers(GITHUB_API, "application/vnd.github.v3+json") return forge_headers(GITHUB_API, "application/vnd.github.v3+json")
@contextlib.contextmanager
def _fetch_errors(url: str) -> Iterator[None]:
"""Raise what a request to `url` failed with as FetchError."""
try:
yield
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 _open( def _open(
request: urllib.request.Request, request: urllib.request.Request,
consume: Callable[[http.client.HTTPResponse], _T], consume: Callable[[http.client.HTTPResponse], _T],
@@ -186,16 +205,8 @@ def _open(
for name, value in forge_headers(url).items(): for name, value in forge_headers(url).items():
if not request.has_header(name.capitalize()): if not request.has_header(name.capitalize()):
request.add_header(name, value) request.add_header(name, value)
try: with _fetch_errors(url):
return open_retrying(request, consume, timeout) 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( def fetch_bytes(
@@ -245,19 +256,19 @@ def download(
"""Stream `url` into `destination`, whole or not at all, and return the """Stream `url` into `destination`, whole or not at all, and return the
response's Content-Disposition ("" when absent or when skipped). response's Content-Disposition ("" when absent or when skipped).
The bytes go through a scratch file renamed into place, so a reader or core.upstream.download does the work: a scratch file renamed into place,
an interrupted run never sees half an archive. `skip_existing` keeps a so a reader or an interrupted run never sees half an archive.
file already there without asking the server. `skip_existing` keeps a file already there without asking the server.
A failure raises FetchError.
""" """
if skip_existing and destination.is_file(): if skip_existing and destination.is_file():
return "" return ""
destination.parent.mkdir(parents=True, exist_ok=True) destination.parent.mkdir(parents=True, exist_ok=True)
with _fetch_errors(url):
def save(resp: http.client.HTTPResponse) -> str: served = upstream_download(
copy_stream_atomic(resp, str(destination)) url, destination, headers=headers, timeout=timeout, user_agent=SCRAPER_AGENT
return resp.headers.get("Content-Disposition", "") or "" )
return (served.get("Content-Disposition", "") if served is not None else "") or ""
return _open(urllib.request.Request(url, headers=headers or {}), save, timeout)
class BlobMismatchError(ValueError): class BlobMismatchError(ValueError):
@@ -499,18 +510,27 @@ class BaseScraper(ABC):
... ...
def fetch_branch_head(repo: str, branch: str) -> str: def fetch_branch_head(repo: str, branch: str | None = None) -> str:
"""The commit a branch of a GitHub repo points at right now. """The commit a branch or tag of a GitHub repo points at right now, the
default branch when none is named.
A platform read from a moving branch records this sha in its source URL, A platform read from a moving branch records this sha in its source URL,
so the exporter later patches the revision the data was read from and so the exporter later patches the revision the data was read from and
not whatever the branch has become. Raises like the release lookup. not whatever the branch has become. core.upstream.resolve_head asks the
forge and keeps no copy: the sha lives in the scraper's output. Raises
RuntimeError like the release lookup.
""" """
url = f"{GITHUB_API}/repos/{repo}/commits/{branch}" owner, _, name = repo.partition("/")
commit = github_json(url, f"cannot read the head of {repo}@{branch}") forge = make_repo("github.com", owner, name)
sha = commit.get("sha") if isinstance(commit, dict) else None ref = f"{repo}@{branch or 'default branch'}"
if forge is None:
raise RuntimeError(f"{ref}: not a GitHub repository")
try:
sha = resolve_head(forge, None, branch=branch)
except (UpstreamError, ValueError) as e:
raise RuntimeError(f"cannot read the head of {ref}: {e}") from e
if not isinstance(sha, str) or not re.fullmatch(r"[0-9a-f]{40}", sha): if not isinstance(sha, str) or not re.fullmatch(r"[0-9a-f]{40}", sha):
raise RuntimeError(f"{repo}@{branch} answered no commit sha") raise RuntimeError(f"{ref} answered no commit sha")
return sha return sha
+24 -15
View File
@@ -105,11 +105,29 @@ SYSTEM_SLUG_MAP = {
} }
SYSTEMS_TREE_URL = ( TREE_URL = (
"https://gitlab.com/api/v4/projects/recalbox%2Frecalbox/repository/tree" "https://gitlab.com/api/v4/projects/recalbox%2Frecalbox/repository/tree"
"?path=package/recalbox-romfs2/systems&ref={tag}&per_page=100&page={page}" "?path={path}&ref={tag}&per_page={per_page}&page={page}"
) )
SYSTEMS_DIR = "package/recalbox-romfs2/systems" SYSTEMS_DIR = "package/recalbox-romfs2/systems"
def tree_listing(directory: str, tag: str) -> list[dict]:
"""The entries of one directory of recalbox/recalbox at `tag`, read page
by page. RuntimeError past core.upstream's page cap: a listing cut
there would drop entries without a word."""
import json
entries: list[dict] = []
for page in range(1, upstream.MAX_TREE_PAGES + 1):
url = TREE_URL.format(
path=directory, tag=tag, per_page=upstream.TREE_PAGE_SIZE, page=page
)
listing = json.loads(fetch_bytes(url))
entries += [item for item in listing if isinstance(item, dict)]
if len(listing) < upstream.TREE_PAGE_SIZE:
return entries
raise RuntimeError(f"{directory} at {tag} outruns the page cap")
# One raw read per system.ini made about 150 requests and GitLab throttled # One raw read per system.ini made about 150 requests and GitLab throttled
# the scrape past half an hour. GraphQL returns a batch of blobs at once. # the scrape past half an hour. GraphQL returns a batch of blobs at once.
GRAPHQL_URL = "https://gitlab.com/api/graphql" GRAPHQL_URL = "https://gitlab.com/api/graphql"
@@ -257,19 +275,10 @@ class Scraper(BaseScraper):
An empty listing raises: written as is, it gave every board of the An empty listing raises: written as is, it gave every board of the
targets scraper an empty core list. targets scraper an empty core list.
""" """
import json systems = [
item["name"] for item in tree_listing(SYSTEMS_DIR, self.tag)
systems: list[str] = [] if item.get("type") == "tree" and not item["name"].startswith(".")
for page in range(1, upstream.MAX_TREE_PAGES + 1): ]
listing = json.loads(fetch_bytes(SYSTEMS_TREE_URL.format(tag=self.tag, page=page)))
systems += [
item["name"] for item in listing
if item.get("type") == "tree" and not item["name"].startswith(".")
]
if len(listing) < upstream.TREE_PAGE_SIZE:
break
else:
raise RuntimeError(f"{SYSTEMS_DIR} at {self.tag} outruns the page cap")
if not systems: if not systems:
raise RuntimeError(f"no Recalbox system found at {self.tag}") raise RuntimeError(f"no Recalbox system found at {self.tag}")
return systems return systems
+5 -8
View File
@@ -33,7 +33,6 @@ import argparse
import hashlib import hashlib
import json import json
import sys import sys
import urllib.parse
import zipfile import zipfile
from collections.abc import Callable from collections.abc import Callable
from dataclasses import dataclass from dataclasses import dataclass
@@ -51,6 +50,7 @@ from resolve.localfile import variant_base_name
from .base_scraper import ( from .base_scraper import (
BlobMismatchError, BlobMismatchError,
download, download,
fetch_branch_head,
fetch_github_latest_version, fetch_github_latest_version,
fetch_verified_blob, fetch_verified_blob,
github_json, github_json,
@@ -414,7 +414,8 @@ def mame_version(tag: str) -> str:
if raw.isdigit() and len(raw) >= 4: if raw.isdigit() and len(raw) >= 4:
return f"{raw[0]}.{raw[1:]}" return f"{raw[0]}.{raw[1:]}"
return raw return raw
FBNEO_API = "https://api.github.com/repos/libretro/FBNeo" FBNEO_REPO = "libretro/FBNeo"
FBNEO_API = f"https://api.github.com/repos/{FBNEO_REPO}"
def _api_json(url: str) -> object: def _api_json(url: str) -> object:
@@ -451,11 +452,7 @@ def fetch_pack(
# The revision is resolved to a commit first and everything is read at # The revision is resolved to a commit first and everything is read at
# that commit: a branch URL is served through a CDN cache, so the bytes # that commit: a branch URL is served through a CDN cache, so the bytes
# could predate the listing that named their blob. # could predate the listing that named their blob.
ref = "HEAD" if tag == "latest" else urllib.parse.quote(tag, safe="") sha = fetch_branch_head(FBNEO_REPO, None if tag == "latest" else tag)
commit = _api_json(f"{FBNEO_API}/commits/{ref}")
sha = commit.get("sha") if isinstance(commit, dict) else None
if not sha:
raise BlobMismatchError(f"libretro/FBNeo has no revision {tag}")
listing = _api_json(f"{FBNEO_API}/contents/dats?ref={sha}") listing = _api_json(f"{FBNEO_API}/contents/dats?ref={sha}")
if not isinstance(listing, list): if not isinstance(listing, list):
raise BlobMismatchError(f"libretro/FBNeo lists no dats at {sha}") raise BlobMismatchError(f"libretro/FBNeo lists no dats at {sha}")
@@ -612,7 +609,7 @@ def main() -> int:
pack, blobs = fetch_pack( pack, blobs = fetch_pack(
args.source, fetch_tag(args.source, args.fetch), Path(args.cache_dir) args.source, fetch_tag(args.source, args.fetch), Path(args.cache_dir)
) )
except BlobMismatchError as exc: except (BlobMismatchError, ConnectionError, RuntimeError) as exc:
print(f"ERROR: {exc}", file=sys.stderr) print(f"ERROR: {exc}", file=sys.stderr)
return 1 return 1
print(f" Recupere {pack}") print(f" Recupere {pack}")
@@ -13,22 +13,17 @@ target list, a Pi 3 pack carried the firmware of emulators only x86_64 builds.
from __future__ import annotations from __future__ import annotations
import json
import re import re
import sys import sys
from datetime import datetime, timezone from datetime import datetime, timezone
from . import BaseTargetScraper, target_cli from . import BaseTargetScraper, target_cli
from ..base_scraper import fetch_bytes, fetch_text from ..base_scraper import fetch_text
from ..recalbox_scraper import Scraper as PlatformScraper, board_cores from ..recalbox_scraper import Scraper as PlatformScraper, board_cores, tree_listing
PLATFORM_NAME = "recalbox" PLATFORM_NAME = "recalbox"
CONFIGS_TREE_URL = (
"https://gitlab.com/api/v4/projects/recalbox%2Frecalbox/repository/tree"
"?path=configs&ref={tag}&per_page=100"
)
DEFCONFIG_URL = "https://gitlab.com/recalbox/recalbox/-/raw/{tag}/configs/{name}" DEFCONFIG_URL = "https://gitlab.com/recalbox/recalbox/-/raw/{tag}/configs/{name}"
_DEFCONFIG_RE = re.compile(r"^recalbox-(\w+)_defconfig$") _DEFCONFIG_RE = re.compile(r"^recalbox-(\w+)_defconfig$")
_ENABLED_RE = re.compile(r"^(BR2_PACKAGE_\w+)=y\s*$", re.MULTILINE) _ENABLED_RE = re.compile(r"^(BR2_PACKAGE_\w+)=y\s*$", re.MULTILINE)
@@ -57,10 +52,9 @@ class Scraper(BaseTargetScraper):
def fetch_targets(self) -> dict: def fetch_targets(self) -> dict:
tag = self.pinned_revision(PLATFORM_NAME) tag = self.pinned_revision(PLATFORM_NAME)
platform = PlatformScraper(tag) platform = PlatformScraper(tag)
listing = json.loads(fetch_bytes(CONFIGS_TREE_URL.format(tag=tag)))
boards = { boards = {
match.group(1): item["name"] match.group(1): item["name"]
for item in listing for item in tree_listing("configs", tag)
if (match := _DEFCONFIG_RE.match(item.get("name", ""))) if (match := _DEFCONFIG_RE.match(item.get("name", "")))
} }
if not boards: if not boards:
+28 -26
View File
@@ -19,6 +19,7 @@ from collections import defaultdict
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from core import upstream
from core.artifacts import write_text_atomic from core.artifacts import write_text_atomic
from core.github import github_token from core.github import github_token
@@ -28,14 +29,14 @@ SITE_PROPERTY = "https://abdess.github.io/retrobios/"
GOATCOUNTER = "https://retrobios.goatcounter.com/api/v0" GOATCOUNTER = "https://retrobios.goatcounter.com/api/v0"
REPOSITORY = "Abdess/retrobios" REPOSITORY = "Abdess/retrobios"
SOURCES = ("gsc", "goatcounter", "github") SOURCES = ("gsc", "goatcounter", "github")
USER_AGENT = "retrobios-site-insights"
# GoatCounter builds an export in the background: it is asked for every # GoatCounter builds an export in the background: it is asked for every
# EXPORT_POLL seconds, EXPORT_TRIES times. It allows one export an hour. # EXPORT_POLL seconds, EXPORT_TRIES times. It allows one export an hour.
EXPORT_POLL = 5 EXPORT_POLL = 5
EXPORT_TRIES = 60 EXPORT_TRIES = 60
# GoatCounter answers four requests a second and 500 per window, and says # GoatCounter answers four requests a second and 500 per window, and says
# when to come back: a short wait is waited, a long one ends the run. # when to come back in X-Rate-Limit-Reset. core.upstream.open_retrying waits
RATE_LIMIT_TRIES = 8 # a short wait and gives up on a long one, which ends the run.
RATE_LIMIT_LONGEST_WAIT = 60
# Expected click-through rate: the site's own rate at each rounded # Expected click-through rate: the site's own rate at each rounded
# position, positions past 20 pooled in LAST_BUCKET. A bucket under # position, positions past 20 pooled in LAST_BUCKET. A bucket under
@@ -67,25 +68,26 @@ class Query:
# Reading the sources # Reading the sources
def _open(request: urllib.request.Request) -> tuple[int, bytes]:
"""Status and body of a request, retried by core.upstream.open_retrying:
a dropped connection or a 5xx is asked again, a rate limit waited out."""
try:
return upstream.open_retrying(request, lambda response: (response.status, response.read()), 60)
except (urllib.error.HTTPError, upstream.RateLimitError) as error:
if isinstance(error, urllib.error.HTTPError) and error.code != 429:
raise
headers = error.headers if isinstance(error, urllib.error.HTTPError) else None
wait = upstream.requested_wait(headers)
delay = f" for {wait:.0f} s" if wait is not None else ""
raise SystemExit(f"{urllib.parse.urlsplit(request.full_url).hostname} refuses requests{delay} "
"(rate limit); run again then, or --skip that source") from error
def _fetch(url: str, headers: dict[str, str] | None = None, body: dict | None = None) -> tuple[int, bytes]: def _fetch(url: str, headers: dict[str, str] | None = None, body: dict | None = None) -> tuple[int, bytes]:
data = json.dumps(body).encode() if body is not None else None data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(url, data=data, headers={ return _open(urllib.request.Request(url, data=data, headers={
"User-Agent": "retrobios-site-insights", **({"Content-Type": "application/json"} if data else {}), "User-Agent": USER_AGENT, **({"Content-Type": "application/json"} if data else {}),
**(headers or {})}) **(headers or {})}))
for _ in range(RATE_LIMIT_TRIES - 1):
try:
with urllib.request.urlopen(request, timeout=60) as response:
return response.status, response.read()
except urllib.error.HTTPError as error:
if error.code != 429:
raise
wait = int(error.headers.get("X-Rate-Limit-Reset") or 1) + 1
if wait > RATE_LIMIT_LONGEST_WAIT:
raise SystemExit(f"{urllib.parse.urlsplit(url).hostname} refuses requests for "
f"{wait} s (rate limit); run again then, or --skip that source") from error
time.sleep(wait)
with urllib.request.urlopen(request, timeout=60) as response:
return response.status, response.read()
def _get_json(url: str, headers: dict[str, str] | None = None, body: dict | None = None) -> dict | list: def _get_json(url: str, headers: dict[str, str] | None = None, body: dict | None = None) -> dict | list:
@@ -112,9 +114,8 @@ def _google_token(key_file: Path) -> str:
input=unsigned.encode(), capture_output=True, check=True).stdout input=unsigned.encode(), capture_output=True, check=True).stdout
body = urllib.parse.urlencode({"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", body = urllib.parse.urlencode({"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": f"{unsigned}.{b64(signature)}"}).encode() "assertion": f"{unsigned}.{b64(signature)}"}).encode()
request = urllib.request.Request(key["token_uri"], data=body) request = urllib.request.Request(key["token_uri"], data=body, headers={"User-Agent": USER_AGENT})
with urllib.request.urlopen(request, timeout=60) as response: return json.loads(_open(request)[1])["access_token"]
return json.load(response)["access_token"]
def fetch_queries(start: dt.date, end: dt.date) -> list[Query]: def fetch_queries(start: dt.date, end: dt.date) -> list[Query]:
@@ -193,11 +194,12 @@ def fetch_goatcounter(start: dt.date, end: dt.date) -> dict:
def fetch_github() -> dict: def fetch_github() -> dict:
token = github_token() # Traffic figures are only served to the owner: without a token there
if not token: # is nothing to read, not a smaller quota.
if not github_token():
raise SystemExit("GitHub traffic needs a token: GITHUB_TOKEN, or gh auth login") raise SystemExit("GitHub traffic needs a token: GITHUB_TOKEN, or gh auth login")
auth = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json"}
api = f"https://api.github.com/repos/{REPOSITORY}" api = f"https://api.github.com/repos/{REPOSITORY}"
auth = upstream.forge_headers(api, "application/vnd.github+json", USER_AGENT)
releases = _get_json(f"{api}/releases?per_page=10", auth) releases = _get_json(f"{api}/releases?per_page=10", auth)
return { return {
"views": _get_json(f"{api}/traffic/views", auth), "views": _get_json(f"{api}/traffic/views", auth),
+21 -20
View File
@@ -18,7 +18,7 @@ from core.artifacts import write_if_changed
from core.cli import InputMissing from core.cli import InputMissing
from core.paths import DB_FILE, REPO_ROOT from core.paths import DB_FILE, REPO_ROOT
from core.sizes import size_text from core.sizes import size_text
from core.upstream import forge_headers from core import upstream
from installer_build.module import installer_module from installer_build.module import installer_module
from model.composition import compute_composition, count_catalog_matched from model.composition import compute_composition, count_catalog_matched
from model.declarations import declared_root from model.declarations import declared_root
@@ -503,26 +503,27 @@ def _existing_contributor_block(readme_path: str = "README.md") -> list[str]:
def fetch_contributors() -> list[dict]: def fetch_contributors() -> list[dict]:
"""Fetch contributors from GitHub API, exclude bots.""" """Contributors from the GitHub API, bots and the owner left out. Empty
import urllib.error when the API cannot be read, or under RETROBIOS_OFFLINE: the caller then
import urllib.request keeps the published list."""
if os.environ.get("RETROBIOS_OFFLINE"):
url = f"https://api.github.com/repos/{REPO}/contributors"
headers = forge_headers(url, user_agent="retrobios-readme/1.0")
try:
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, timeout=10) as resp:
data = json.loads(resp.read().decode())
owner = REPO.split("/")[0]
return [
c
for c in data
if not c.get("login", "").endswith("[bot]")
and c.get("type") == "User"
and c.get("login") != owner
]
except (urllib.error.URLError, urllib.error.HTTPError):
return [] return []
url = f"https://api.github.com/repos/{REPO}/contributors"
try:
body = upstream.fetch_body(url, accept_json=True, timeout=10, user_agent="retrobios-readme/1.0")
data = json.loads(body) if body is not None else []
except (upstream.UpstreamError, ValueError) as exc:
print(f"contributors: {exc}", file=sys.stderr)
return []
owner = REPO.split("/")[0]
return [
c
for c in data
if isinstance(c, dict)
and not c.get("login", "").endswith("[bot]")
and c.get("type") == "User"
and c.get("login") != owner
]
_CATALOG_LABELS = {"redump": "Redump", "no-intro": "No-Intro", "tosec": "TOSEC"} _CATALOG_LABELS = {"redump": "Redump", "no-intro": "No-Intro", "tosec": "TOSEC"}
+6 -8
View File
@@ -39,7 +39,6 @@ import sys
import tempfile import tempfile
import threading import threading
import time import time
import urllib.request
from collections.abc import Sequence from collections.abc import Sequence
from dataclasses import dataclass, field from dataclasses import dataclass, field
from pathlib import Path from pathlib import Path
@@ -48,6 +47,7 @@ from typing import IO
sys.path.insert(0, str(Path(__file__).resolve().parent)) sys.path.insert(0, str(Path(__file__).resolve().parent))
import core_probe as cp import core_probe as cp
from core import upstream
from core.statefile import now_iso from core.statefile import now_iso
ROOT = Path(__file__).resolve().parent.parent ROOT = Path(__file__).resolve().parent.parent
@@ -230,12 +230,10 @@ def parse_xwd(data: bytes) -> tuple[int, int, bytes]:
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
def github_releases(repo: str) -> list[dict]: def github_releases(repo: str) -> list[dict]:
from scraper.base_scraper import github_headers from scraper.base_scraper import github_json
request = urllib.request.Request(f"https://api.github.com/repos/{repo}/releases", return github_json(f"https://api.github.com/repos/{repo}/releases",
headers=github_headers()) f"cannot list the releases of {repo}", timeout=60)
with urllib.request.urlopen(request, timeout=60) as response:
return json.load(response)
def fetch(emu: Emulator, cache: Path = CACHE) -> dict: def fetch(emu: Emulator, cache: Path = CACHE) -> dict:
@@ -246,8 +244,8 @@ def fetch(emu: Emulator, cache: Path = CACHE) -> dict:
folder = cache / emu.name folder = cache / emu.name
folder.mkdir(parents=True, exist_ok=True) folder.mkdir(parents=True, exist_ok=True)
partial = folder / f"{asset['name']}.part" partial = folder / f"{asset['name']}.part"
with urllib.request.urlopen(asset["url"], timeout=600) as response, partial.open("wb") as out: # Whole or absent, retried on a cut stream (core.upstream.download).
shutil.copyfileobj(response, out) upstream.download(asset["url"], partial, timeout=600)
sha256 = cp.file_digest(partial, "sha256") sha256 = cp.file_digest(partial, "sha256")
target = folder / sha256 / asset["name"] target = folder / sha256 / asset["name"]
target.parent.mkdir(parents=True, exist_ok=True) target.parent.mkdir(parents=True, exist_ok=True)
+42 -4
View File
@@ -17,6 +17,7 @@ import subprocess
import sys import sys
import tempfile import tempfile
import unittest import unittest
import urllib.error
import zipfile import zipfile
import zlib import zlib
from pathlib import Path from pathlib import Path
@@ -3409,6 +3410,27 @@ class ContributorsSurviveAFailedRequest(unittest.TestCase):
"the section is present but empty", "the section is present but empty",
) )
def test_the_contributor_list_is_not_asked_offline(self):
from sitegen import readme
with mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": "1"}), \
mock.patch.object(readme.upstream, "fetch_body",
side_effect=AssertionError("network")):
self.assertEqual(readme.fetch_contributors(), [])
def test_contributors_are_read_through_the_retrying_client(self):
from sitegen import readme
answer = json.dumps([
{"login": "someone", "type": "User"},
{"login": "dependabot[bot]", "type": "Bot"},
{"login": readme.REPO.split("/")[0], "type": "User"},
]).encode()
with mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \
mock.patch.object(readme.upstream, "fetch_body", return_value=answer) as fetch:
self.assertEqual([c["login"] for c in readme.fetch_contributors()], ["someone"])
self.assertIn("/contributors", fetch.call_args.args[0])
class APackNameFitsAFileName(unittest.TestCase): class APackNameFitsAFileName(unittest.TestCase):
"""--system snes joined 23 emulator names and died on ENAMETOOLONG """--system snes joined 23 emulator names and died on ENAMETOOLONG
@@ -7578,6 +7600,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
def _response(self, body: bytes): def _response(self, body: bytes):
stream = io.BytesIO(body) stream = io.BytesIO(body)
stream.headers = {}
response = mock.MagicMock() response = mock.MagicMock()
response.__enter__.return_value = stream response.__enter__.return_value = stream
response.__exit__.return_value = False response.__exit__.return_value = False
@@ -7587,7 +7610,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
from resolve import packfiles as packresolve from resolve import packfiles as packresolve
with tempfile.TemporaryDirectory() as tmp, \ with tempfile.TemporaryDirectory() as tmp, \
mock.patch.object(packresolve.urllib.request, "urlopen") as urlopen, \ mock.patch("urllib.request.urlopen") as urlopen, \
contextlib.redirect_stdout(io.StringIO()): contextlib.redirect_stdout(io.StringIO()):
ok = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=True) ok = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=True)
self.assertFalse(ok) self.assertFalse(ok)
@@ -7600,7 +7623,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
packresolve.set_offline(True) packresolve.set_offline(True)
try: try:
with tempfile.TemporaryDirectory() as tmp, \ with tempfile.TemporaryDirectory() as tmp, \
mock.patch.object(packresolve.urllib.request, "urlopen") as urlopen, \ mock.patch("urllib.request.urlopen") as urlopen, \
contextlib.redirect_stdout(io.StringIO()): contextlib.redirect_stdout(io.StringIO()):
self.assertFalse(packresolve.download_external(self.ENTRY, f"{tmp}/x")) self.assertFalse(packresolve.download_external(self.ENTRY, f"{tmp}/x"))
urlopen.assert_not_called() urlopen.assert_not_called()
@@ -7612,12 +7635,12 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmp: with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "x" target = Path(tmp) / "x"
with mock.patch.object(packresolve.urllib.request, "urlopen", with mock.patch("urllib.request.urlopen",
return_value=self._response(b"payload")): return_value=self._response(b"payload")):
self.assertTrue(packresolve.download_external(self.ENTRY, str(target), offline=False)) self.assertTrue(packresolve.download_external(self.ENTRY, str(target), offline=False))
self.assertEqual(target.read_bytes(), b"payload") self.assertEqual(target.read_bytes(), b"payload")
target.unlink() target.unlink()
with mock.patch.object(packresolve.urllib.request, "urlopen", with mock.patch("urllib.request.urlopen",
return_value=self._response(b"other")), \ return_value=self._response(b"other")), \
contextlib.redirect_stdout(io.StringIO()): contextlib.redirect_stdout(io.StringIO()):
self.assertFalse(packresolve.download_external(self.ENTRY, str(target), offline=False)) self.assertFalse(packresolve.download_external(self.ENTRY, str(target), offline=False))
@@ -7636,6 +7659,21 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
entry = {**self.ENTRY, "sha1": sha1} entry = {**self.ENTRY, "sha1": sha1}
self.assertTrue(packresolve.download_external(entry, f"{tmp}/x", offline=False)) self.assertTrue(packresolve.download_external(entry, f"{tmp}/x", offline=False))
def test_a_transient_failure_is_retried_and_no_scratch_remains(self):
"""One 503 failed the external file for the whole build."""
from core import upstream
from resolve import packfiles as packresolve
refusal = urllib.error.HTTPError(self.ENTRY["source_url"], 503, "busy", {}, None)
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "x"
with mock.patch("urllib.request.urlopen",
side_effect=[refusal, self._response(b"payload")]), \
mock.patch.object(upstream, "_sleep", lambda _s: None):
self.assertTrue(packresolve.download_external(self.ENTRY, str(target), offline=False))
self.assertEqual(target.read_bytes(), b"payload")
self.assertEqual(os.listdir(tmp), ["x"])
def test_scratch_files_stay_in_the_repository(self): def test_scratch_files_stay_in_the_repository(self):
source = script_source("generate_pack.py") source = script_source("generate_pack.py")
self.assertNotIn("def download_external", source) self.assertNotIn("def download_external", source)
+30
View File
@@ -720,6 +720,36 @@ class AProgressBarOnlyOnATerminal(unittest.TestCase):
self.assertNotIn("\r", out.getvalue()) self.assertNotIn("\r", out.getvalue())
self.assertEqual(out.getvalue().count("\n"), 1) self.assertEqual(out.getvalue().count("\n"), 1)
def test_a_cut_stream_is_fetched_again_from_the_start(self):
"""One reset midway through a 2 GiB part failed the whole download."""
import http.client
from core import upstream
class Body(io.BytesIO):
headers = {"Content-Length": "6"}
def __enter__(self):
return self
def __exit__(self, *exc):
return False
class Cut(Body):
def read(self, size: int = -1) -> bytes:
raise http.client.IncompleteRead(b"pa")
answers = [Cut(b""), Body(b"packed")]
with tempfile.TemporaryDirectory() as directory, \
mock.patch.object(download.urllib.request, "urlopen",
lambda *a, **k: answers.pop(0)), \
mock.patch.object(upstream, "_sleep", lambda _s: None), \
contextlib.redirect_stdout(io.StringIO()):
target = Path(directory) / "a.zip"
download.download_file("https://example.com/a.zip", target, 6, "a.zip ")
self.assertEqual(target.read_bytes(), b"packed")
self.assertEqual(answers, [])
class TheShellDownloaderSendsTheToken(unittest.TestCase): class TheShellDownloaderSendsTheToken(unittest.TestCase):
"""download.py sent GITHUB_TOKEN to the API and download.sh did not, so """download.py sent GITHUB_TOKEN to the API and download.sh did not, so
+32 -3
View File
@@ -37,6 +37,9 @@ PAYLOAD_B = b"B" * (256 * 1024)
# the CI test job sets RETROBIOS_OFFLINE to keep every other test off the # the CI test job sets RETROBIOS_OFFLINE to keep every other test off the
# network, so it is cleared here. # network, so it is cleared here.
_ONLINE = mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}) _ONLINE = mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""})
# core.upstream retries a failed transfer after a pause: the pauses are
# skipped, the retries are not.
_NO_PAUSE = mock.patch.object(largefiles.upstream, "_sleep", lambda _s: None)
# The names these tests fetch, registered as .gitignore registers an asset: # The names these tests fetch, registered as .gitignore registers an asset:
# a bare name no registered path carries is never asked of the release. # a bare name no registered path carries is never asked of the release.
@@ -58,15 +61,19 @@ def _test_registry(case: unittest.TestCase) -> None:
def setUpModule(): def setUpModule():
_ONLINE.start() _ONLINE.start()
_NO_PAUSE.start()
def tearDownModule(): def tearDownModule():
_NO_PAUSE.stop()
_ONLINE.stop() _ONLINE.stop()
class _SlowResponse(io.BytesIO): class _SlowResponse(io.BytesIO):
"""Serve a payload in chunks, yielding between them.""" """Serve a payload in chunks, yielding between them."""
headers: dict[str, str] = {}
def __init__(self, data: bytes, barrier: threading.Barrier | None = None): def __init__(self, data: bytes, barrier: threading.Barrier | None = None):
super().__init__(data) super().__init__(data)
self._barrier = barrier self._barrier = barrier
@@ -629,16 +636,18 @@ class ReleaseAssetNames(unittest.TestCase):
largefiles.fetch_large_file( largefiles.fetch_large_file(
self.RTCW, dest_dir=cache, registered=self.REGISTERED self.RTCW, dest_dir=cache, registered=self.REGISTERED
) )
# A refused connection is retried: each asset is asked
# more than once, and only the assets asked matter here.
self.assertEqual( self.assertEqual(
requested, set(requested),
[largefiles.urllib.parse.quote(expected[self.RTCW])], {largefiles.urllib.parse.quote(expected[self.RTCW])},
) )
requested.clear() requested.clear()
largefiles.fetch_large_file( largefiles.fetch_large_file(
"pak0.pk3", dest_dir=cache, registered=self.REGISTERED "pak0.pk3", dest_dir=cache, registered=self.REGISTERED
) )
self.assertEqual( self.assertEqual(
sorted(requested), sorted(set(requested)),
sorted( sorted(
largefiles.urllib.parse.quote(expected[p]) largefiles.urllib.parse.quote(expected[p])
for p in (self.ET, self.RTCW) for p in (self.ET, self.RTCW)
@@ -667,6 +676,8 @@ class ReleaseAssetNames(unittest.TestCase):
class _StalledResponse(io.BytesIO): class _StalledResponse(io.BytesIO):
"""Serves one chunk, then the stream stalls.""" """Serves one chunk, then the stream stalls."""
headers: dict[str, str] = {}
def __init__(self): def __init__(self):
super().__init__(PAYLOAD_A) super().__init__(PAYLOAD_A)
self._served = False self._served = False
@@ -702,6 +713,24 @@ class DownloadFailuresAndRevisions(unittest.TestCase):
self.assertIsNone(result) self.assertIsNone(result)
self.assertEqual(os.listdir(self.dir), []) self.assertEqual(os.listdir(self.dir), [])
def test_a_transient_server_error_is_retried(self):
"""One 503 from the release CDN dropped the asset from the build."""
answers: list = [urllib.error.HTTPError("u", 503, "busy", {}, None), _SlowResponse(PAYLOAD_A)]
def urlopen(*_args, **_kwargs):
answer = answers.pop(0)
if isinstance(answer, Exception):
raise answer
return answer
largefiles.urllib.request.urlopen = urlopen
result = largefiles.fetch_large_file(
"big.bin", self.dir, expected_md5=hashlib.md5(PAYLOAD_A).hexdigest(),
registered=TEST_REGISTERED,
)
self.assertIsNotNone(result)
self.assertEqual(answers, [])
def test_another_revision_is_kept_not_evicted(self): def test_another_revision_is_kept_not_evicted(self):
cached = Path(self.dir, "PS3UPDAT.PUP") cached = Path(self.dir, "PS3UPDAT.PUP")
cached.write_bytes(PAYLOAD_A) cached.write_bytes(PAYLOAD_A)
+34
View File
@@ -5579,6 +5579,40 @@ class UpstreamVendoredAsASubmodule(unittest.TestCase):
views = self._views({"src-pin": {"deps/zlib": "other"}, "src-head": {}}) views = self._views({"src-pin": {"deps/zlib": "other"}, "src-head": {}})
self.assertEqual(views[1].head, "nesbox-tip") self.assertEqual(views[1].head, "nesbox-tip")
def test_a_truncated_port_tree_is_not_read_as_no_submodule(self):
"""A partial listing kept nesbox's tip, the commit a bump must not
move upstream_commit to."""
views = [
profiling_repos.RepoView(object(), "src-pin", "src-head", "source_commit", "source"),
profiling_repos.RepoView(object(), "sub-old", "nesbox-tip", "upstream_commit", "upstream"),
]
with mock.patch.object(
upstream, "list_gitlinks",
side_effect=upstream.TruncatedListingError("tree listing truncated"),
), self.assertRaises(upstream.TruncatedListingError):
profiling_repos._follow_submodule(views, "cache", True)
class TruncatedGitlinksInTheResolver(unittest.TestCase):
"""A read-only report goes on past a partial listing, and says so."""
def test_the_lost_tree_yields_no_link_and_the_next_is_read(self):
from types import SimpleNamespace
views = [SimpleNamespace(repo="a", pin="p1"), SimpleNamespace(repo="b", pin="p2")]
state = SimpleNamespace(views=views, cache_dir="c", offline=True, name="demo")
def links(repo, sha, *_args):
if repo == "a":
raise upstream.TruncatedListingError("a@p1: tree listing truncated")
return {"sub": "s"}
with mock.patch.object(upstream, "list_gitlinks", side_effect=links), \
contextlib.redirect_stderr(io.StringIO()) as err:
found = [list(paths) for paths in resolver._Resolver.gitlinks_in_order(state)]
self.assertEqual(found, [[], ["sub"]])
self.assertIn("submodule paths unknown", err.getvalue())
class AMirrorOutlivesAGoneSource(unittest.TestCase): class AMirrorOutlivesAGoneSource(unittest.TestCase):
"""yuzu's source answers 451. select_views stopped on it and never read """yuzu's source answers 451. select_views stopped on it and never read
+13
View File
@@ -38,6 +38,8 @@ def _zip_bytes(files: dict[str, bytes]) -> bytes:
class _Response(io.BytesIO): class _Response(io.BytesIO):
headers: dict[str, str] = {}
def __enter__(self): def __enter__(self):
return self return self
@@ -466,6 +468,17 @@ class TheRemoteCommitComesFromTheForgeClient(unittest.TestCase):
self.assertEqual((sha, len(seen)), ("b" * 40, 2)) self.assertEqual((sha, len(seen)), ("b" * 40, 2))
self.assertEqual(seen[0].get_header("Authorization"), "Bearer SECRET") self.assertEqual(seen[0].get_header("Authorization"), "Bearer SECRET")
def test_the_answer_is_not_cached(self):
from core import upstream
with mock.patch.object(upstream, "write_cache") as write:
sha, _seen = self._resolve(
"https://github.com/o/n/archive/{version}.tar.gz", "master",
[[{"sha": "c" * 40}]],
)
self.assertEqual(sha, "c" * 40)
write.assert_not_called()
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+25 -3
View File
@@ -28,11 +28,16 @@ class _Response(io.BytesIO):
return False return False
def _is_head(url):
# core.upstream.resolve_head lists one commit from the branch.
return "/commits?per_page=1" in url
def _opener(failure): def _opener(failure):
def urlopen(req, timeout=0): def urlopen(req, timeout=0):
url = req.full_url url = req.full_url
if "/commits/" in url: if _is_head(url):
return _Response(json.dumps({"sha": "a" * 40}).encode()) return _Response(json.dumps([{"sha": "a" * 40}]).encode())
if "api.github.com" in url: if "api.github.com" in url:
return _Response(json.dumps(TREE).encode()) return _Response(json.dumps(TREE).encode())
if "pcsx2" in url and failure is not None: if "pcsx2" in url and failure is not None:
@@ -71,10 +76,27 @@ class ManifestErrors(unittest.TestCase):
with mock.patch("urllib.request.urlopen", recording): with mock.patch("urllib.request.urlopen", recording):
Scraper()._fetch_remote_manifests() Scraper()._fetch_remote_manifests()
reads = [url for url in seen if "/commits/" not in url] reads = [url for url in seen if not _is_head(url)]
self.assertTrue(reads) self.assertTrue(reads)
self.assertTrue(all("a" * 40 in url for url in reads), reads) self.assertTrue(all("a" * 40 in url for url in reads), reads)
def test_the_head_is_read_without_a_cache_write(self):
"""The branch head is asked of the forge each scrape and never
written to the profile cache under .cache/upstream."""
seen = []
opener = _opener(None)
def recording(req, timeout=0):
seen.append(req.full_url)
return opener(req, timeout)
with mock.patch("urllib.request.urlopen", recording), \
mock.patch("core.upstream.write_cache") as write:
scraper = Scraper()
self.assertEqual(scraper.revision, "a" * 40)
self.assertTrue(any(_is_head(url) for url in seen), seen)
write.assert_not_called()
def test_a_truncated_tree_stops_the_scrape(self): def test_a_truncated_tree_stops_the_scrape(self):
TREE["truncated"] = True TREE["truncated"] = True
self.addCleanup(TREE.pop, "truncated") self.addCleanup(TREE.pop, "truncated")
+11 -3
View File
@@ -906,10 +906,12 @@ class FbneoFetchReadsOneRevision(unittest.TestCase):
def tearDown(self): def tearDown(self):
self._tmp.cleanup() self._tmp.cleanup()
def _head(self, repo: str, branch: str | None = None) -> str:
self.calls.append(f"{repo}@{branch}")
return "c0ffee"
def _api(self, url: str) -> object: def _api(self, url: str) -> object:
self.calls.append(url) self.calls.append(url)
if "/commits/" in url:
return {"sha": "c0ffee"}
return [{ return [{
"type": "file", "name": "Demo.dat", "type": "file", "name": "Demo.dat",
"sha": git_blob_sha(FBNEO_DAT), "sha": git_blob_sha(FBNEO_DAT),
@@ -927,6 +929,7 @@ class FbneoFetchReadsOneRevision(unittest.TestCase):
from scripts.scraper import base_scraper from scripts.scraper import base_scraper
with mock.patch.object(self.importer, "_api_json", self._api), \ with mock.patch.object(self.importer, "_api_json", self._api), \
mock.patch.object(self.importer, "fetch_branch_head", self._head), \
mock.patch.object(base_scraper, "download", self._download): mock.patch.object(base_scraper, "download", self._download):
yield yield
@@ -941,11 +944,16 @@ class FbneoFetchReadsOneRevision(unittest.TestCase):
target, blobs = self.importer.fetch_pack("fbneo", "v1.0.0.02", self.dir) target, blobs = self.importer.fetch_pack("fbneo", "v1.0.0.02", self.dir)
self.assertEqual( self.assertEqual(
self.calls, self.calls,
[f"{self.importer.FBNEO_API}/commits/v1.0.0.02", ["libretro/FBNeo@v1.0.0.02",
f"{self.importer.FBNEO_API}/contents/dats?ref=c0ffee"], f"{self.importer.FBNEO_API}/contents/dats?ref=c0ffee"],
) )
self.assertEqual(list(blobs), ["Demo.dat"]) self.assertEqual(list(blobs), ["Demo.dat"])
def test_latest_reads_the_default_branch(self):
with self._patched():
self.importer.fetch_pack("fbneo", "latest", self.dir)
self.assertEqual(self.calls[0], "libretro/FBNeo@None")
def test_a_revision_import_is_labelled_and_leaves_the_tip_blobs(self): def test_a_revision_import_is_labelled_and_leaves_the_tip_blobs(self):
import contextlib import contextlib
import io import io
+35 -2
View File
@@ -271,11 +271,40 @@ class AnEmptyRecalboxListingStopsTheTargets(unittest.TestCase):
scraper = targets.Scraper() scraper = targets.Scraper()
with mock.patch.object(scraper, "pinned_revision", lambda _name: "10.1.1"), \ with mock.patch.object(scraper, "pinned_revision", lambda _name: "10.1.1"), \
mock.patch.object(targets, "fetch_bytes", fetch), \
mock.patch.object(recalbox_scraper, "fetch_bytes", fetch), \ mock.patch.object(recalbox_scraper, "fetch_bytes", fetch), \
self.assertRaisesRegex(RuntimeError, "no Recalbox system"): self.assertRaisesRegex(RuntimeError, "no Recalbox system"):
scraper.fetch_targets() scraper.fetch_targets()
def test_the_configs_listing_is_read_past_its_first_page(self):
"""configs/ was asked for one page of 100 entries: a defconfig past
it was a board the targets never listed."""
import json
from scraper import recalbox_scraper
asked: list[str] = []
def fetch(url, data=None, headers=None):
asked.append(url)
page = int(url.rsplit("page=", 1)[1])
if page == 1:
return json.dumps([{"name": f"other{i}"} for i in range(100)]).encode()
return b'[{"name": "recalbox-rpi5_64_defconfig"}]'
with mock.patch.object(recalbox_scraper, "fetch_bytes", fetch):
names = [item["name"] for item in recalbox_scraper.tree_listing("configs", "10.1.1")]
self.assertEqual(len(names), 101)
self.assertIn("recalbox-rpi5_64_defconfig", names)
self.assertTrue(all("path=configs" in url for url in asked))
def test_a_listing_past_the_page_cap_raises(self):
import json
from scraper import recalbox_scraper
full = json.dumps([{"name": "x"}] * 100).encode()
with mock.patch.object(recalbox_scraper, "fetch_bytes", lambda *a, **k: full), \
self.assertRaisesRegex(RuntimeError, "page cap"):
recalbox_scraper.tree_listing("configs", "10.1.1")
class EveryNamedScraperExists(unittest.TestCase): class EveryNamedScraperExists(unittest.TestCase):
"""The registry named lakka_targets, a scraper no file defines: a refresh """The registry named lakka_targets, a scraper no file defines: a refresh
@@ -787,7 +816,11 @@ class UnreadableReleaseStopsTheScrape(unittest.TestCase):
return False return False
def answer(request, timeout=None): def answer(request, timeout=None):
return Answer(json.dumps({"sha": sha}).encode()) # A branch head is the first entry of the commit listing
# (core.upstream.resolve_head), a release lookup one object.
commit = {"sha": sha}
listing = "/commits?" in request.full_url
return Answer(json.dumps([commit] if listing else commit).encode())
branch_read = [s for s in self._registry_scrapers() if s not in self.TAG_PINNED] branch_read = [s for s in self._registry_scrapers() if s not in self.TAG_PINNED]
self.assertGreater(len(branch_read), 8) self.assertGreater(len(branch_read), 8)
+31 -2
View File
@@ -291,7 +291,8 @@ class GoatCounterExport(unittest.TestCase):
refusal = urllib.error.HTTPError("https://retrobios.goatcounter.com/api/v0/stats/hits", 429, refusal = urllib.error.HTTPError("https://retrobios.goatcounter.com/api/v0/stats/hits", 429,
"Too Many Requests", headers, io.BytesIO(b"")) "Too Many Requests", headers, io.BytesIO(b""))
with mock.patch.object(insights.urllib.request, "urlopen", side_effect=refusal), \ with mock.patch.object(insights.urllib.request, "urlopen", side_effect=refusal), \
mock.patch.object(insights.time, "sleep") as sleep, \ mock.patch.object(insights.upstream, "_sleep") as sleep, \
mock.patch.object(insights.upstream, "_exhausted_hosts", set()), \
self.assertRaisesRegex(SystemExit, "2356 s"): self.assertRaisesRegex(SystemExit, "2356 s"):
insights._get_json("https://retrobios.goatcounter.com/api/v0/stats/hits") insights._get_json("https://retrobios.goatcounter.com/api/v0/stats/hits")
sleep.assert_not_called() sleep.assert_not_called()
@@ -304,10 +305,38 @@ class GoatCounterExport(unittest.TestCase):
answer.__enter__.return_value.status = 200 answer.__enter__.return_value.status = 200
answer.__enter__.return_value.read.return_value = json.dumps({"ok": 1}).encode() answer.__enter__.return_value.read.return_value = json.dumps({"ok": 1}).encode()
with mock.patch.object(insights.urllib.request, "urlopen", side_effect=[refusal, answer]), \ with mock.patch.object(insights.urllib.request, "urlopen", side_effect=[refusal, answer]), \
mock.patch.object(insights.time, "sleep") as sleep: mock.patch.object(insights.upstream, "_sleep") as sleep:
self.assertEqual(insights._get_json("https://x/api"), {"ok": 1}) self.assertEqual(insights._get_json("https://x/api"), {"ok": 1})
sleep.assert_called_once_with(2) sleep.assert_called_once_with(2)
def test_a_server_error_is_asked_again(self) -> None:
"""A 502 from GoatCounter ended the run on the first try."""
refusal = urllib.error.HTTPError("https://x/api", 502, "Bad Gateway", email.message.Message(),
io.BytesIO(b""))
answer = mock.MagicMock()
answer.__enter__.return_value.status = 200
answer.__enter__.return_value.read.return_value = json.dumps({"ok": 1}).encode()
with mock.patch.object(insights.urllib.request, "urlopen", side_effect=[refusal, answer]), \
mock.patch.object(insights.upstream, "_sleep"):
self.assertEqual(insights._get_json("https://x/api"), {"ok": 1})
def test_github_headers_come_from_the_forge_helper(self) -> None:
seen: list[dict[str, str]] = []
def get_json(url: str, headers: dict[str, str] | None = None, body: dict | None = None):
seen.append(dict(headers or {}))
return [] if "releases" in url else {}
with mock.patch.object(insights, "github_token", return_value="SECRET"), \
mock.patch("core.github.github_token", return_value="SECRET"), \
mock.patch.object(insights, "_get_json", get_json):
insights.fetch_github()
self.assertTrue(seen)
for headers in seen:
self.assertEqual(headers["Authorization"], "Bearer SECRET")
self.assertEqual(headers["Accept"], "application/vnd.github+json")
self.assertEqual(headers["User-Agent"], insights.USER_AGENT)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+80
View File
@@ -334,6 +334,62 @@ class TestFetchRetry(unittest.TestCase):
upstream.fetch_body("https://host/x") upstream.fetch_body("https://host/x")
self.assertEqual((self.calls, self.slept), (1, [])) self.assertEqual((self.calls, self.slept), (1, []))
def test_goatcounter_reset_header_is_waited_with_a_second_more(self):
import email.message
headers = email.message.Message()
headers["X-Rate-Limit-Reset"] = "3"
self._serve([_http_error(429, headers), b"payload"])
self.assertEqual(upstream.fetch_body("https://host/x"), b"payload")
self.assertEqual(self.slept, [4.0])
def test_download_retries_a_cut_stream_and_writes_whole(self):
class Cut:
def read(self, size: int = -1) -> bytes:
raise http.client.IncompleteRead(b"par")
outcomes: list = [Cut(), _Body(b"payload")]
def opener(req, timeout=None):
body = outcomes.pop(0)
body.headers = {"Content-Disposition": "attachment"}
return contextlib.nullcontext(body)
urllib.request.urlopen = opener
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "file.bin"
served = upstream.download("https://host/file.bin", target)
self.assertEqual(target.read_bytes(), b"payload")
self.assertEqual(served["Content-Disposition"], "attachment")
self.assertEqual(os.listdir(tmp), ["file.bin"])
self.assertEqual(len(self.slept), 1)
def test_download_refused_by_its_check_writes_nothing(self):
def opener(req, timeout=None):
body = _Body(b"payload")
body.headers = {}
return contextlib.nullcontext(body)
urllib.request.urlopen = opener
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "file.bin"
target.write_bytes(b"old")
self.assertIsNone(upstream.download("https://host/f", target, accept=lambda _p: False))
self.assertEqual(target.read_bytes(), b"old")
self.assertEqual(os.listdir(tmp), ["file.bin"])
def test_download_past_the_cap_raises_and_leaves_nothing(self):
def opener(req, timeout=None):
body = _Body(b"x" * 10)
body.headers = {}
return contextlib.nullcontext(body)
urllib.request.urlopen = opener
with tempfile.TemporaryDirectory() as tmp:
with self.assertRaises(ValueError):
upstream.download("https://host/f", Path(tmp) / "f", max_bytes=4)
self.assertEqual(os.listdir(tmp), [])
def test_exhausted_github_quota_is_not_waited(self): def test_exhausted_github_quota_is_not_waited(self):
import email.message import email.message
@@ -535,6 +591,17 @@ class TestRevisions(unittest.TestCase):
self.responses["/commits"] = [{"sha": "deadbeef"}] self.responses["/commits"] = [{"sha": "deadbeef"}]
self.assertEqual(upstream.resolve_head(self.repo, self.dir), "deadbeef") self.assertEqual(upstream.resolve_head(self.repo, self.dir), "deadbeef")
def test_resolve_head_without_a_cache_keeps_nothing(self):
"""A scraper's branch head is asked each time and never cached."""
self.responses["/commits"] = [{"sha": "f00d"}]
self.assertEqual(upstream.resolve_head(self.repo, None, branch="main"), "f00d")
self.assertEqual(upstream.resolve_head(self.repo, None, branch="main"), "f00d")
self.assertEqual(len(self.calls), 2)
self.assertIn("sha=main", self.calls[0])
self.assertEqual(os.listdir(self.dir), [])
with self.assertRaises(upstream.NotCachedError):
upstream.resolve_head(self.repo, None, offline=True)
def test_resolve_head_gitlab_uses_id(self): def test_resolve_head_gitlab_uses_id(self):
repo = parse_repo("https://gitlab.com/g/p") repo = parse_repo("https://gitlab.com/g/p")
self.responses["/repository/commits"] = [{"id": "cafe"}] self.responses["/repository/commits"] = [{"id": "cafe"}]
@@ -869,6 +936,19 @@ class TestGitlabTree(unittest.TestCase):
self.assertEqual(len(paths), upstream.TREE_PAGE_SIZE) self.assertEqual(len(paths), upstream.TREE_PAGE_SIZE)
self.assertTrue(truncated) self.assertTrue(truncated)
def test_gitlinks_of_a_truncated_listing_raise(self):
"""A lost page read as "no submodule there"."""
self.pages[1] = [{"type": "commit", "path": "core", "id": "c" * 40}] + self._blobs(
*[f"f{i}.c" for i in range(upstream.TREE_PAGE_SIZE - 1)]
)
self.pages[2] = None
with self.assertRaises(upstream.TruncatedListingError):
upstream.list_gitlinks(self.repo, "sha", self.dir)
def test_gitlinks_of_a_whole_listing(self):
self.pages[1] = [{"type": "commit", "path": "core", "id": "c" * 40}]
self.assertEqual(upstream.list_gitlinks(self.repo, "sha", self.dir), {"core": "c" * 40})
class TestGiteaCommitAt(unittest.TestCase): class TestGiteaCommitAt(unittest.TestCase):
"""Gitea and Forgejo ignore `until` and answer with the tip: the date """Gitea and Forgejo ignore `until` and answer with the tip: the date