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

+5 -18
View File
@@ -29,7 +29,6 @@ import gzip
import json
import re
import sys
import urllib.request
import zipfile
from collections.abc import Iterator
from dataclasses import dataclass
@@ -39,12 +38,12 @@ from pathlib import Path
if (_SCRIPTS_DIR := str(Path(__file__).resolve().parents[1])) not in sys.path:
sys.path.insert(0, _SCRIPTS_DIR)
from core.artifacts import copy_stream_atomic, write_if_changed, write_text_atomic
from core.artifacts import write_if_changed, write_text_atomic
from model.safeparse import parse_untrusted_xml
from model.region import REGIONS, WORLD
from model.region import NOINTRO
from .base_scraper import github_headers
from .base_scraper import download, github_json
SOURCES = ("no-intro", "redump")
CACHE_DIR = Path(".cache") / "game-dats"
@@ -286,15 +285,6 @@ class NotCachedError(RuntimeError):
"""An offline run asked for a download the cache does not hold."""
def _download(url: str, destination: Path, headers: dict[str, str] | None = None) -> dict[str, str]:
"""Stream url to destination and return the response headers kept."""
destination.parent.mkdir(parents=True, exist_ok=True)
request = urllib.request.Request(url, headers={"User-Agent": "retrobios", **(headers or {})})
with urllib.request.urlopen(request, timeout=300) as response:
copy_stream_atomic(response, str(destination))
return {"content_disposition": response.headers.get("Content-Disposition", "")}
def _today() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%d")
@@ -309,15 +299,13 @@ def fetch_nointro(cache_dir: Path, offline: bool, refresh: bool) -> tuple[Path,
return pack, meta
if offline:
raise NotCachedError(f"{meta_path} or its pack is not cached")
request = urllib.request.Request(NOINTRO_RELEASE_API, headers=github_headers())
with urllib.request.urlopen(request, timeout=60) as response:
release = json.loads(response.read())
release = github_json(NOINTRO_RELEASE_API, "cannot read the No-Intro release")
asset = next(a for a in release["assets"] if a["name"] == NOINTRO_ASSET)
stamp = asset["updated_at"].replace(":", "").replace("-", "")
file = f"no-intro-{stamp}.zip"
pack = cache_dir / file
if not pack.is_file():
_download(asset["browser_download_url"], pack)
download(asset["browser_download_url"], pack)
if pack.stat().st_size != asset["size"]:
pack.unlink()
raise RuntimeError(f"{NOINTRO_ASSET}: size differs from the release's {asset['size']}")
@@ -342,8 +330,7 @@ def fetch_redump(code: str, cache_dir: Path, offline: bool, refresh: bool) -> tu
if offline:
raise NotCachedError(f"{pack} is not cached")
url = REDUMP_DATFILE_URL.format(code=code)
kept = _download(url, pack)
match = DISPOSITION.search(kept["content_disposition"])
match = DISPOSITION.search(download(url, pack))
if not match:
raise RuntimeError(f"{url} answered without a datfile name")
meta = {"file": match["file"], "url": url, "fetched": _today()}