refactor: one network layer for the scrapers

Each network job had several copies. One is kept per job and
every caller uses it.

- Source revision: model.sourcerevision (source_revision, required_revision,
  platform_revision) replaces BaseTargetScraper's pattern list, the
  exporter's _REVISION, the four launcher_revision copies and RetroBat's
  own YAML reader. It reads the union of the shapes: GitHub raw, blob and
  tree with or without a path after the revision, GitLab raw, blob, tree
  and archive, codeload tar.gz and zip. The target scrapers now answer
  for RetroDECK, NextUI, MinUI and MyMinUI, whose tree URLs end at the
  commit, and the exporter reads GitLab blob and tree and codeload zip.
  EmuDeck and RetroBat still require a 40-hex commit, and each launcher
  reader requires its own repository in the URL.
- Latest release: fetch_github_latest_version, type-checked, is the only
  lookup. mame_hash_scraper, romset_dat_importer and the Lakka target
  scraper call it. romset_dat_importer's NoReleaseError is gone: a
  release without a tag raises RuntimeError.
- Tree listing: github_tree and tree_entries refuse a truncated or
  unreadable listing. The libretro and core-info scrapers share
  core_info_files and fetch_info_file, with libretro's refusal of an empty
  listing. The core-info listing and the RetroDECK, ROCKNIX launcher and
  libretro listings were not checked for truncation before.
- GET: fetch_bytes is the one request path. fetch_text, fetch_present
  (None on 404 only), github_json and download are built on it, so every
  read retries 429 and 5xx, caps the body and raises FetchError, a
  ConnectionError carrying the HTTP status. The target scrapers' own
  fetch_text raised RuntimeError: they now raise FetchError, and an
  optional Batocera board include is skipped on 404 only, not on any
  failure. The exporter's originals, MiSTer, RetroPie, redump and the
  buildbot index go through it too.
- Headers: core.upstream.forge_headers is the one builder. The token goes
  to api.github.com and raw.githubusercontent.com, the host compared
  whole, as Bearer. A URL that only names api.github.com in its query
  got the scrapers' token before, and profile_sync sent its token to
  github.com, whose release downloads redirect to asset storage with the
  header. Scraper reads of raw files now carry the token.
- Submodule commit: submodule_commit checks that the path is a
  submodule. Batocera's target scraper accepted any contents answer with
  a sha, a directory's tree sha included.
- Download: download streams through a scratch file renamed into place,
  retries like fetch_bytes, can keep an existing file and returns the
  Content-Disposition. It replaces the _download of romset_dat_importer
  and game_dat_importer.
This commit is contained in:
Abdessamad Derraz committed 2026-11-20 20:02:15 +01:00
1 parent c25426f14c
commit f61c2cb7d4
43 files changed
+791 -670

No files matched your search

+9 -43
View File
@@ -8,13 +8,17 @@ from __future__ import annotations
import argparse
import importlib
import pkgutil
import re
import urllib.error
import urllib.request
from abc import ABC, abstractmethod
from pathlib import Path
from core.github import github_token
from model.sourcerevision import platform_revision
# Every target scraper reads the network through the platform scrapers'
# helpers: one retry policy, one size cap, one token rule.
from ..base_scraper import fetch_text, forge_headers
__all__ = ["BaseTargetScraper", "discover_target_scrapers", "fetch_text", "forge_headers",
"target_cli"]
class BaseTargetScraper(ABC):
@@ -37,26 +41,10 @@ class BaseTargetScraper(ABC):
filtered 10.1.1 systems. Moving to a new release is a rescrape of the
platform first.
"""
import yaml
directory = Path(platforms_dir) if platforms_dir else (
Path(__file__).resolve().parents[3] / "platforms"
)
with open(directory / f"{platform}.yml", encoding="utf-8") as handle:
source = str((yaml.safe_load(handle) or {}).get("source", ""))
for pattern in (
r"^https://raw\.githubusercontent\.com/[^/]+/[^/]+/([^/]+)/",
r"^https://github\.com/[^/]+/[^/]+/(?:blob|tree)/([^/]+)/",
r"^https://gitlab\.com/.+?/-/(?:raw|blob|tree)/([^/]+)/",
r"^https://codeload\.github\.com/[^/]+/[^/]+/(?:tar\.gz|zip)/([^/]+)$",
):
match = re.match(pattern, source)
if match:
return match.group(1)
raise RuntimeError(
f"platforms/{platform}.yml names no pinned revision in its source "
f"({source!r}): rescrape the platform first"
)
return platform_revision(directory / f"{platform}.yml")
def write_output(self, data: dict, output_path: str) -> None:
"""Write target data to YAML file."""
@@ -71,28 +59,6 @@ class BaseTargetScraper(ABC):
)
def fetch_text(url: str, headers: dict[str, str] | None = None) -> str:
"""GET a URL as UTF-8 text, RuntimeError with the URL when it fails."""
try:
req = urllib.request.Request(url, headers=headers or {"User-Agent": "retrobios-scraper/1.0"})
with urllib.request.urlopen(req, timeout=30) as resp:
return resp.read().decode("utf-8")
except urllib.error.URLError as e:
# A target written from a failed request loses its cores in silence.
raise RuntimeError(f"cannot fetch {url}: {e}") from e
def forge_headers(url: str, accept: str | None = None) -> dict[str, str]:
"""Request headers, with the GitHub token when the URL is api.github.com."""
headers = {"User-Agent": "retrobios-scraper/1.0"}
if accept is not None:
headers["Accept"] = accept
token = github_token()
if token and "api.github.com" in url:
headers["Authorization"] = f"Bearer {token}"
return headers
def target_cli(scraper_class: type[BaseTargetScraper], description: str, unit: str = "cores") -> None:
"""The command line every target scraper shares: --dry-run prints each
target and its count of `unit`, --output writes the YAML, else it is printed."""
@@ -23,7 +23,7 @@ from datetime import datetime, timezone
from . import BaseTargetScraper, target_cli
from ..amberelec_scraper import BUILDS_OF, ES_SYSTEMS_TEMPLATE, RUNNERS
from ..base_scraper import fetch_bytes
from ..base_scraper import fetch_text
from ..batocera_scraper import _not_cores
from ..es_emulators import es_cores, xml_systems
@@ -104,12 +104,12 @@ class Scraper(BaseTargetScraper):
self.ref = ""
def _raw(self, path: str) -> str:
return fetch_bytes(f"{RAW_BASE.format(ref=self.ref)}/{path}").decode("utf-8")
return fetch_text(f"{RAW_BASE.format(ref=self.ref)}/{path}")
def fetch_targets(self) -> dict:
self.ref = self.pinned_revision(PLATFORM_NAME)
extra, keep = extra_cores(self._raw(META_MK))
es_systems = fetch_bytes(ES_SYSTEMS_TEMPLATE.format(ref=self.ref)).decode("utf-8")
es_systems = fetch_text(ES_SYSTEMS_TEMPLATE.format(ref=self.ref))
targets: dict[str, dict] = {}
for device, arch in sorted(devices(self._raw("Makefile")).items()):
cores = device_cores(es_systems, extra, device in keep)
@@ -15,11 +15,8 @@ Sources (batocera-linux/buildroot, at the submodule commit the tag pins):
from __future__ import annotations
import json
import re
import sys
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from datetime import datetime, timezone
@@ -28,8 +25,8 @@ import yaml
from model.safeparse import yaml_load_upstream
from . import BaseTargetScraper, fetch_text, target_cli
from ..base_scraper import github_headers
from . import BaseTargetScraper, target_cli
from ..base_scraper import fetch_present, fetch_text, github_json, github_tree, submodule_commit
PLATFORM_NAME = "batocera"
@@ -68,24 +65,6 @@ _IF_RE = re.compile(r"^if\s+(.*)$")
_DEFAULT_Y_RE = re.compile(r"^\s*default\s+y\s*(?:#.*)?$")
def _fetch_present(url: str) -> str | None:
"""A file's text, or None when the server answers that it does not exist."""
try:
return fetch_text(url)
except RuntimeError as e:
if isinstance(e.__cause__, urllib.error.HTTPError) and e.__cause__.code == 404:
return None
raise
def _fetch_json(url: str) -> list | dict:
text = fetch_text(url, headers=github_headers())
try:
return json.loads(text)
except json.JSONDecodeError as e:
raise RuntimeError(f"cannot parse {url}: {e}") from e
def _normalise_condition(raw: str) -> str:
"""Strip backslash-continuations and collapse whitespace."""
return re.sub(r"\\\n\s*", " ", raw).strip()
@@ -454,12 +433,12 @@ class Scraper(BaseTargetScraper):
def _raw(self, path: str) -> str:
return f"https://raw.githubusercontent.com/{self.REPO}/{self.tag}/{path}"
def _api(self, path: str) -> str:
return f"https://api.github.com/repos/{self.REPO}/contents/{path}?ref={self.tag}"
def _list_boards(self) -> list[str]:
"""List <prefix>*.board files from configs/ via GitHub API."""
data = _fetch_json(self._api("configs"))
data = github_json(
f"https://api.github.com/repos/{self.REPO}/contents/configs?ref={self.tag}",
f"cannot list configs/ at {self.tag}",
)
boards = [
item["name"]
for item in data
@@ -487,12 +466,12 @@ class Scraper(BaseTargetScraper):
if name in seen:
continue
seen.add(name)
try:
text = fetch_text(self._raw(f"configs/{name}"))
except RuntimeError:
found = fetch_present(self._raw(f"configs/{name}"))
if found is None:
if optional:
continue
raise
raise RuntimeError(f"configs/{name} is absent at {self.tag}")
text = found
flags |= set(_BOARD_FLAG_RE.findall(text))
if target is None:
m = _TARGET_FLAG_RE.search(text)
@@ -511,10 +490,7 @@ class Scraper(BaseTargetScraper):
"""
bases: list[tuple[str, str]] = []
for prefix, repo in self.SUBMODULES.items():
pin = _fetch_json(self._api(prefix.rstrip("/")))
sha = pin.get("sha") if isinstance(pin, dict) else None
if not sha:
raise RuntimeError(f"no {prefix.rstrip('/')} submodule commit at {self.tag}")
sha = submodule_commit(self.REPO, prefix.rstrip("/"), self.tag)
bases.append((prefix, f"https://raw.githubusercontent.com/{repo}/{sha}/"))
def url(path: str) -> str:
@@ -528,7 +504,7 @@ class Scraper(BaseTargetScraper):
pending = ["Config.in"]
with ThreadPoolExecutor(max_workers=8) as pool:
while pending:
found = dict(zip(pending, pool.map(lambda path: _fetch_present(url(path)), pending)))
found = dict(zip(pending, pool.map(lambda path: fetch_present(url(path)), pending)))
absent += [path for path, text in found.items() if text is None]
files.update((path, text or "") for path, text in found.items())
pending = sorted({src for text in found.values() if text
@@ -543,16 +519,10 @@ class Scraper(BaseTargetScraper):
"""Every retroarch.cfg the tree ships, its submodules included."""
repos = [("", self.REPO, self.tag)]
for prefix, repo in self.SUBMODULES.items():
pin = _fetch_json(self._api(prefix.rstrip("/")))
if not isinstance(pin, dict) or not isinstance(pin.get("sha"), str):
raise RuntimeError(f"no submodule commit for {prefix} at {self.tag}")
repos.append((prefix, repo, pin["sha"]))
repos.append((prefix, repo, submodule_commit(self.REPO, prefix.rstrip("/"), self.tag)))
found: dict[str, str] = {}
for prefix, repo, ref in repos:
listing = _fetch_json(f"https://api.github.com/repos/{repo}/git/trees/{ref}?recursive=1")
if not isinstance(listing, dict) or listing.get("truncated"):
raise RuntimeError(f"{repo} tree at {ref} is unreadable or truncated")
for entry in listing.get("tree", []):
for entry in github_tree(repo, ref):
if re.search(r"(^|/)retroarch\.cfg$", entry["path"]):
raw = f"https://raw.githubusercontent.com/{repo}/{ref}/{entry['path']}"
found[prefix + entry["path"]] = fetch_text(raw)
@@ -560,10 +530,7 @@ class Scraper(BaseTargetScraper):
def _buildroot_rules(self) -> list[tuple[str, str, str]]:
"""Buildroot's selects for the symbols the tree tests, at its pin."""
pin = _fetch_json(self._api("buildroot"))
sha = pin.get("sha") if isinstance(pin, dict) else None
if not sha:
raise RuntimeError(f"no buildroot submodule commit at {self.tag}")
sha = submodule_commit(self.REPO, "buildroot", self.tag)
raw = f"https://raw.githubusercontent.com/{self.BUILDROOT_REPO}/{sha}"
rules: list[tuple[str, str, str]] = []
for path in BUILDROOT_KCONFIG:
@@ -33,7 +33,7 @@ from typing import NamedTuple
from . import BaseTargetScraper, target_cli
from ..base_scraper import fetch_bytes, github_headers
from ..base_scraper import fetch_text, github_json
from ..batocera_scraper import _not_cores
from ..emuelec_systems import (
BUILDS_OF,
@@ -601,7 +601,7 @@ class Scraper(BaseTargetScraper):
self.ref = ""
def _raw(self, path: str) -> str:
return fetch_bytes(RAW.format(ref=self.ref, path=path)).decode("utf-8")
return fetch_text(RAW.format(ref=self.ref, path=path))
def fetch_targets(self) -> dict:
return self.device_targets()
@@ -610,15 +610,18 @@ class Scraper(BaseTargetScraper):
"""The targets file, read at `ref`, by default the revision
platforms/emuelec.yml was scraped at."""
self.ref = ref or self.pinned_revision(PLATFORM_NAME)
release = json.loads(
fetch_bytes(RELEASE_API.format(ref=self.ref), headers=github_headers())
release = github_json(
RELEASE_API.format(ref=self.ref), f"cannot read the {self.ref} release"
)
devices = release_devices([asset["name"] for asset in release.get("assets", [])])
assets = release.get("assets") if isinstance(release, dict) else None
if not isinstance(assets, list):
raise RuntimeError(f"the {self.ref} release lists no asset")
devices = release_devices([asset["name"] for asset in assets])
meta = read_metapackage(self._raw(META_MK), self._raw(OPTIONS))
paths = sorted({i.path for installs in PROVIDERS.values() for i in installs})
archs = check_installs({path: self._raw(path) for path in paths})
es_json = fetch_bytes(ES_SYSTEMS_TEMPLATE.format(ref=self.ref)).decode("utf-8")
ports = port_engines(fetch_bytes(PORTS_TEMPLATE.format(ref=self.ref)).decode("utf-8"))
es_json = fetch_text(ES_SYSTEMS_TEMPLATE.format(ref=self.ref))
ports = port_engines(fetch_text(PORTS_TEMPLATE.format(ref=self.ref)))
es_mk = self._raw(ES_MK)
check_names(with_ports(es_systems_for(es_json, es_mk, "Amlogic-ng"), ports))
targets: dict[str, dict] = {}
@@ -12,20 +12,18 @@ a target list, its pack shipped their firmware anyway.
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, github_headers
from ..base_scraper import fetch_github_latest_version, fetch_text, github_tree
PLATFORM_NAME = "lakka"
REPO = "libretro/Lakka-LibreELEC"
RAW_BASE = "https://raw.githubusercontent.com/" + REPO + "/{tag}"
API_BASE = "https://api.github.com/repos/" + REPO
CORES_MK = "packages/lakka/libretro_cores/package.mk"
_IF_RE = re.compile(r"^(if|elif)\s+\[\s+(.*?)\s+\];?\s*(?:then)?\s*$")
@@ -207,33 +205,22 @@ class Scraper(BaseTargetScraper):
self.paths: set[str] = set()
def _raw(self, path: str) -> str:
return fetch_bytes(f"{RAW_BASE.format(tag=self.tag)}/{path}").decode("utf-8")
def _latest_tag(self) -> str:
release = json.loads(fetch_bytes(f"{API_BASE}/releases/latest", headers=github_headers()))
tag = release.get("tag_name") if isinstance(release, dict) else None
if not tag:
raise RuntimeError(f"{REPO} names no latest release")
return tag
return fetch_text(f"{RAW_BASE.format(tag=self.tag)}/{path}")
def _devices(self) -> list[tuple[str, str]]:
tree = json.loads(fetch_bytes(
f"{API_BASE}/git/trees/{self.tag}?recursive=1", headers=github_headers()
))
if tree.get("truncated"):
raise RuntimeError(f"the {self.tag} tree listing is truncated")
self.paths = {item.get("path", "") for item in tree.get("tree", [])}
tree = github_tree(REPO, self.tag)
self.paths = {item["path"] for item in tree}
found = sorted({
(match.group(1), match.group(2))
for item in tree.get("tree", [])
if (match := re.match(r"^projects/([^/]+)/devices/([^/]+)/options$", item.get("path", "")))
for item in tree
if (match := re.match(r"^projects/([^/]+)/devices/([^/]+)/options$", item["path"]))
})
if not found:
raise RuntimeError(f"no projects/*/devices/*/options at {self.tag}")
return found
def fetch_targets(self) -> dict:
self.tag = self._latest_tag()
self.tag = fetch_github_latest_version(REPO)
cores_mk = self._raw(CORES_MK)
targets: dict[str, dict] = {}
for project, device in self._devices():
@@ -20,7 +20,7 @@ from datetime import datetime, timezone
from . import BaseTargetScraper, target_cli
from ..base_scraper import fetch_bytes
from ..base_scraper import fetch_bytes, fetch_text
from ..recalbox_scraper import SYSTEMS_TREE_URL, Scraper as PlatformScraper, board_cores
PLATFORM_NAME = "recalbox"
@@ -79,7 +79,7 @@ class Scraper(BaseTargetScraper):
targets: dict[str, dict] = {}
for board, name in sorted(boards.items()):
defconfig = fetch_bytes(DEFCONFIG_URL.format(tag=tag, name=name)).decode("utf-8")
defconfig = fetch_text(DEFCONFIG_URL.format(tag=tag, name=name))
enabled = enabled_packages(defconfig)
cores: set[str] = set()
for text in inis:
@@ -14,20 +14,20 @@ target list, its pack shipped the PS2, GameCube and PS3 firmware anyway.
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, github_headers
from ..base_scraper import fetch_text, github_json, github_tree
from ..rocknix_packages import standalone_emulators
PLATFORM_NAME = "rocknix"
RAW_BASE = "https://raw.githubusercontent.com/ROCKNIX/distribution/{tag}"
GITHUB_API = "https://api.github.com/repos/ROCKNIX/distribution/contents"
REPO = "ROCKNIX/distribution"
GITHUB_API = f"https://api.github.com/repos/{REPO}/contents"
EMULATORS_MK = "projects/ROCKNIX/packages/virtual/emulators/package.mk"
DEVICES_DIR = "projects/ROCKNIX/devices"
@@ -214,27 +214,19 @@ class Scraper(BaseTargetScraper):
self.tag = ""
def _raw(self, path: str) -> str:
return fetch_bytes(f"{RAW_BASE.format(tag=self.tag)}/{path}").decode("utf-8")
return fetch_text(f"{RAW_BASE.format(tag=self.tag)}/{path}")
def _devices(self) -> list[str]:
import json
listing = json.loads(fetch_bytes(
f"{GITHUB_API}/{DEVICES_DIR}?ref={self.tag}", headers=github_headers()
))
devices = [item["name"] for item in listing if item.get("type") == "dir"]
url = f"{GITHUB_API}/{DEVICES_DIR}?ref={self.tag}"
listing = github_json(url, f"cannot list {DEVICES_DIR} at {self.tag}")
devices = [item["name"] for item in listing
if isinstance(item, dict) and item.get("type") == "dir"]
if not devices:
raise RuntimeError(f"no device in {DEVICES_DIR} at {self.tag}")
return sorted(devices)
def _tree(self) -> list[str]:
listing = json.loads(fetch_bytes(
f"https://api.github.com/repos/ROCKNIX/distribution/git/trees/{self.tag}?recursive=1",
headers=github_headers(),
))
if listing.get("truncated"):
raise RuntimeError(f"ROCKNIX tree at {self.tag} is truncated")
return [entry["path"] for entry in listing.get("tree", [])]
return [entry["path"] for entry in github_tree(REPO, self.tag)]
def device_builds(self, tag: str | None = None) -> dict[str, tuple[str, list[str], list[str]]]:
"""{device: (architecture, libretro cores, standalone packages)}.