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

+47 -27
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import argparse
import contextlib
import http.client
import inspect
import json
@@ -14,18 +15,21 @@ import urllib.request
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
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.artifacts import copy_stream_atomic, write_text_atomic
from core.artifacts import write_text_atomic
from core.hashing import git_blob_sha
from core.upstream import (
MAX_RESPONSE_SIZE,
RateLimitError,
UpstreamError,
make_repo,
open_retrying,
read_limited,
resolve_head,
)
from core.upstream import download as upstream_download
from core.upstream import forge_headers as upstream_headers
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")
@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(
request: urllib.request.Request,
consume: Callable[[http.client.HTTPResponse], _T],
@@ -186,16 +205,8 @@ def _open(
for name, value in forge_headers(url).items():
if not request.has_header(name.capitalize()):
request.add_header(name, value)
try:
with _fetch_errors(url):
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(
@@ -245,19 +256,19 @@ def download(
"""Stream `url` into `destination`, whole or not at all, and return the
response's Content-Disposition ("" when absent or when skipped).
The bytes go through a scratch file renamed into place, so a reader or
an interrupted run never sees half an archive. `skip_existing` keeps a
file already there without asking the server.
core.upstream.download does the work: a scratch file renamed into place,
so a reader or an interrupted run never sees half an archive.
`skip_existing` keeps a file already there without asking the server.
A failure raises FetchError.
"""
if skip_existing and destination.is_file():
return ""
destination.parent.mkdir(parents=True, exist_ok=True)
def save(resp: http.client.HTTPResponse) -> str:
copy_stream_atomic(resp, str(destination))
return resp.headers.get("Content-Disposition", "") or ""
return _open(urllib.request.Request(url, headers=headers or {}), save, timeout)
with _fetch_errors(url):
served = upstream_download(
url, destination, headers=headers, timeout=timeout, user_agent=SCRAPER_AGENT
)
return (served.get("Content-Disposition", "") if served is not None else "") or ""
class BlobMismatchError(ValueError):
@@ -499,18 +510,27 @@ class BaseScraper(ABC):
...
def fetch_branch_head(repo: str, branch: str) -> str:
"""The commit a branch of a GitHub repo points at right now.
def fetch_branch_head(repo: str, branch: str | None = None) -> str:
"""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,
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}"
commit = github_json(url, f"cannot read the head of {repo}@{branch}")
sha = commit.get("sha") if isinstance(commit, dict) else None
owner, _, name = repo.partition("/")
forge = make_repo("github.com", owner, name)
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):
raise RuntimeError(f"{repo}@{branch} answered no commit sha")
raise RuntimeError(f"{ref} answered no commit 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"
"?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"
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
# the scrape past half an hour. GraphQL returns a batch of blobs at once.
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
targets scraper an empty core list.
"""
import json
systems: list[str] = []
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")
systems = [
item["name"] for item in tree_listing(SYSTEMS_DIR, self.tag)
if item.get("type") == "tree" and not item["name"].startswith(".")
]
if not systems:
raise RuntimeError(f"no Recalbox system found at {self.tag}")
return systems
+5 -8
View File
@@ -33,7 +33,6 @@ import argparse
import hashlib
import json
import sys
import urllib.parse
import zipfile
from collections.abc import Callable
from dataclasses import dataclass
@@ -51,6 +50,7 @@ from resolve.localfile import variant_base_name
from .base_scraper import (
BlobMismatchError,
download,
fetch_branch_head,
fetch_github_latest_version,
fetch_verified_blob,
github_json,
@@ -414,7 +414,8 @@ def mame_version(tag: str) -> str:
if raw.isdigit() and len(raw) >= 4:
return f"{raw[0]}.{raw[1:]}"
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:
@@ -451,11 +452,7 @@ def fetch_pack(
# 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
# could predate the listing that named their blob.
ref = "HEAD" if tag == "latest" else urllib.parse.quote(tag, safe="")
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}")
sha = fetch_branch_head(FBNEO_REPO, None if tag == "latest" else tag)
listing = _api_json(f"{FBNEO_API}/contents/dats?ref={sha}")
if not isinstance(listing, list):
raise BlobMismatchError(f"libretro/FBNeo lists no dats at {sha}")
@@ -612,7 +609,7 @@ def main() -> int:
pack, blobs = fetch_pack(
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)
return 1
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
import json
import re
import sys
from datetime import datetime, timezone
from . import BaseTargetScraper, target_cli
from ..base_scraper import fetch_bytes, fetch_text
from ..recalbox_scraper import Scraper as PlatformScraper, board_cores
from ..base_scraper import fetch_text
from ..recalbox_scraper import Scraper as PlatformScraper, board_cores, tree_listing
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_RE = re.compile(r"^recalbox-(\w+)_defconfig$")
_ENABLED_RE = re.compile(r"^(BR2_PACKAGE_\w+)=y\s*$", re.MULTILINE)
@@ -57,10 +52,9 @@ class Scraper(BaseTargetScraper):
def fetch_targets(self) -> dict:
tag = self.pinned_revision(PLATFORM_NAME)
platform = PlatformScraper(tag)
listing = json.loads(fetch_bytes(CONFIGS_TREE_URL.format(tag=tag)))
boards = {
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 not boards: