mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-23 01:57:48 -06:00
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:
1 parent
526d7f09c7
commit
8a8fa71fbc
25 files changed
+708
-266
No files matched your search
+131
-48
@@ -24,9 +24,9 @@ import urllib.request
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
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"
|
||||
# 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):
|
||||
"""The upstream is not coming back.
|
||||
|
||||
@@ -307,17 +313,36 @@ def _resolver_answers() -> bool:
|
||||
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:
|
||||
"""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
|
||||
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):
|
||||
return None
|
||||
retry_after = (exc.headers.get("Retry-After") or "").strip() if exc.headers else ""
|
||||
if retry_after.isdigit():
|
||||
delay = float(retry_after)
|
||||
delay = requested_wait(exc.headers)
|
||||
if delay is not None:
|
||||
return delay if delay <= RATE_LIMIT_WAIT_CAP else None
|
||||
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")
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
return resp.headers.get("ETag") or resp.headers.get("Last-Modified") or ""
|
||||
except (urllib.error.URLError, OSError):
|
||||
return open_retrying(
|
||||
req,
|
||||
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
|
||||
|
||||
|
||||
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:
|
||||
"""Parsed JSON body of a GET, or None on 404. Replaced in tests."""
|
||||
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(
|
||||
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,
|
||||
) -> 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
|
||||
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
|
||||
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
|
||||
None read as a branch the forge does not have, and profile_sync dropped
|
||||
xenios-jp/XeniOS, judging its citations against the other repository.
|
||||
"""
|
||||
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(
|
||||
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
|
||||
|
||||
|
||||
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(
|
||||
repo: Repo, sha: str, directory: str, cache_dir: str, offline: bool = False
|
||||
) -> 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)
|
||||
|
||||
|
||||
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."""
|
||||
def _tree_entries(
|
||||
repo: Repo, sha: str, cache_dir: str, offline: bool
|
||||
) -> tuple[list[dict], bool] | None:
|
||||
"""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":
|
||||
return _gitlab_tree(repo, sha, cache_dir, offline)
|
||||
return gitlab_tree_entries(repo, sha, cache_dir, offline)
|
||||
url = _tree_url(repo, sha)
|
||||
if url is None:
|
||||
return [], True
|
||||
return None
|
||||
payload = cached_api(url, cache_dir, offline)
|
||||
if not isinstance(payload, dict):
|
||||
return [], True
|
||||
return None
|
||||
entries = list(payload.get("tree") or [])
|
||||
truncated = bool(payload.get("truncated"))
|
||||
# Forgejo pages a recursive tree, 1000 entries at a time, and says how
|
||||
@@ -1177,10 +1252,20 @@ def list_tree(
|
||||
break
|
||||
entries.extend(more["tree"])
|
||||
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 = [
|
||||
entry["path"]
|
||||
for entry in entries
|
||||
if isinstance(entry, dict) and entry.get("type") == "blob" and entry.get("path")
|
||||
entry["path"] for entry in entries
|
||||
if entry.get("type") == "blob" and entry.get("path")
|
||||
]
|
||||
return paths, truncated
|
||||
|
||||
@@ -1191,24 +1276,22 @@ def list_gitlinks(
|
||||
"""Submodule path -> the commit it points at, at one revision.
|
||||
|
||||
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":
|
||||
entries, _truncated = gitlab_tree_entries(repo, sha, cache_dir, offline)
|
||||
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):
|
||||
listing = _tree_entries(repo, sha, cache_dir, offline)
|
||||
if listing is None:
|
||||
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 {
|
||||
entry["path"]: entry["sha"]
|
||||
for entry in payload.get("tree") or []
|
||||
if isinstance(entry, dict) and entry.get("type") == "commit"
|
||||
and entry.get("path") and entry.get("sha")
|
||||
entry["path"]: entry[key]
|
||||
for entry in entries
|
||||
if entry.get("type") == "commit" and entry.get("path") and entry.get(key)
|
||||
}
|
||||
|
||||
|
||||
|
||||
+21
-14
@@ -18,6 +18,7 @@ Usage:
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -34,7 +35,7 @@ sys.path.insert(0, os.path.dirname(__file__))
|
||||
from core.hashing import compute_hashes, parse_sha256sums
|
||||
from core.paths import REPO_ROOT
|
||||
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 packs.parts import part_of
|
||||
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)
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return json.loads(resp.read())
|
||||
return json.loads(open_retrying(req, lambda resp: resp.read(), 30))
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code == 404:
|
||||
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(
|
||||
url, headers={"User-Agent": "retrobios-downloader/1.0"}
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||
body = resp.read(MAX_CHECKSUMS_BYTES).decode("utf-8", "replace")
|
||||
body = open_retrying(
|
||||
req, lambda resp: resp.read(MAX_CHECKSUMS_BYTES), 60
|
||||
).decode("utf-8", "replace")
|
||||
# A file that is not sha256sum output refuses the download: read
|
||||
# leniently, a `*name` line matched nothing and the pack went
|
||||
# unchecked.
|
||||
@@ -197,7 +198,12 @@ def fetch_checksums(release: dict) -> dict[str, str]:
|
||||
def download_file(
|
||||
url: str, dest: Path, expected_size: int = 0, label: str = ""
|
||||
) -> 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")
|
||||
req = urllib.request.Request(
|
||||
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
|
||||
# 2 GiB part made one line of nearly 3 MB.
|
||||
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))
|
||||
downloaded = 0
|
||||
shown = -1
|
||||
|
||||
with open(dest, "wb") as f:
|
||||
while True:
|
||||
chunk = resp.read(65536)
|
||||
if not chunk:
|
||||
break
|
||||
while chunk := resp.read(65536):
|
||||
f.write(chunk)
|
||||
downloaded += len(chunk)
|
||||
|
||||
if total > 0 and live:
|
||||
pct = downloaded * 100 // total
|
||||
if pct != shown:
|
||||
@@ -226,7 +228,9 @@ def download_file(
|
||||
columns = shutil.get_terminal_size((80, 24)).columns
|
||||
line = _progress_line(label, downloaded, total, columns)
|
||||
print(f"\r\033[K{line}", end="", flush=True)
|
||||
return downloaded
|
||||
|
||||
downloaded = open_retrying(req, save, 300)
|
||||
if live:
|
||||
print()
|
||||
else:
|
||||
@@ -373,6 +377,8 @@ To check files already in place, use: python install.py --check
|
||||
urllib.error.URLError,
|
||||
urllib.error.HTTPError,
|
||||
OSError,
|
||||
http.client.HTTPException,
|
||||
UpstreamError,
|
||||
json.JSONDecodeError,
|
||||
) as e:
|
||||
print(f"Error: {e}", file=sys.stderr)
|
||||
@@ -384,7 +390,8 @@ To check files already in place, use: python install.py --check
|
||||
|
||||
try:
|
||||
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)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
+3
-10
@@ -22,11 +22,10 @@ import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
from core import upstream
|
||||
from sitegen.agents import INDEXNOW_FILE, INDEXNOW_KEY, SITE
|
||||
|
||||
HOST = "abdess.github.io"
|
||||
@@ -38,14 +37,8 @@ USER_AGENT = "retrobios-indexnow"
|
||||
def live_digests(url: str = f"{SITE}digests.json") -> dict[str, str]:
|
||||
"""The digests the live site serves. None yet (the first deploy that
|
||||
writes them) is an empty map: every page is new."""
|
||||
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
||||
try:
|
||||
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
|
||||
body = upstream.fetch_body(url, timeout=60, user_agent=USER_AGENT)
|
||||
return {} if body is None else json.loads(body.decode("utf-8"))
|
||||
|
||||
|
||||
def changed_urls(new: dict[str, str], old: dict[str, str]) -> list[str]:
|
||||
|
||||
+15
-15
@@ -31,6 +31,7 @@ LARGE_FILES_RELEASE = "large-files"
|
||||
LARGE_FILES_REPO = "Abdess/retrobios"
|
||||
RELEASE_DOWNLOAD = f"https://github.com/{LARGE_FILES_REPO}/releases/download/{LARGE_FILES_RELEASE}/"
|
||||
LARGE_FILES_CACHE = ".cache/large"
|
||||
USER_AGENT = "retrobios/1.0"
|
||||
# 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
|
||||
# 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)
|
||||
|
||||
|
||||
_FAILURES = (urllib.error.URLError, OSError, http.client.HTTPException, upstream.UpstreamError)
|
||||
|
||||
|
||||
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
|
||||
# published dotted, and logging its first 404 read as a missing asset.
|
||||
failures: list[str] = []
|
||||
for candidate, url in _asset_urls(name):
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "retrobios/1.0"})
|
||||
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)
|
||||
upstream.download(url, tmp_path, timeout=300, user_agent=USER_AGENT)
|
||||
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 URLError: it escaped this handler and left its scratch.
|
||||
failures.append(f" large file {candidate}: {exc}")
|
||||
@@ -432,7 +431,7 @@ def _served_digests() -> dict[str, str]:
|
||||
f"{LARGE_FILES_RELEASE}"
|
||||
)
|
||||
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 {}
|
||||
except (upstream.UpstreamError, ValueError) as exc:
|
||||
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:
|
||||
"""Size of the asset the release serves now, or None when unreadable."""
|
||||
for candidate, url in _asset_urls(name):
|
||||
req = urllib.request.Request(
|
||||
url, method="HEAD", headers=upstream.forge_headers(url, user_agent=USER_AGENT)
|
||||
)
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
url, method="HEAD", headers={"User-Agent": "retrobios/1.0"}
|
||||
length = upstream.open_retrying(
|
||||
req, lambda resp: resp.headers.get("Content-Length"), 60
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||
length = resp.headers.get("Content-Length")
|
||||
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
|
||||
except _FAILURES as exc:
|
||||
print(f" large file {candidate}: {exc}", file=sys.stderr)
|
||||
continue
|
||||
if length and length.isdigit():
|
||||
|
||||
+32
-25
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import http.client
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
@@ -30,9 +31,14 @@ REQUEST_TIMEOUT = 30
|
||||
DOWNLOAD_TIMEOUT = 300
|
||||
# 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
|
||||
# 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)
|
||||
_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(
|
||||
@@ -172,13 +178,14 @@ def revisioned(entry: dict) -> bool:
|
||||
|
||||
|
||||
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)
|
||||
if repo is None:
|
||||
log.warning("cannot parse repo from URL: %s", source_url)
|
||||
return None
|
||||
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:
|
||||
log.warning("failed to fetch remote SHA for %s@%s: %s", repo.slug, version, exc)
|
||||
return None
|
||||
@@ -223,13 +230,9 @@ def _download_and_extract(
|
||||
tarball_path = Path(tmpdir) / "archive.tar.gz"
|
||||
log.info("downloading %s", source_url)
|
||||
|
||||
req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp, open(tarball_path, "wb") as f:
|
||||
while True:
|
||||
chunk = resp.read(65536)
|
||||
if not chunk:
|
||||
break
|
||||
f.write(chunk)
|
||||
upstream.download(
|
||||
source_url, tarball_path, timeout=DOWNLOAD_TIMEOUT, user_agent=USER_AGENT
|
||||
)
|
||||
if measured is not None:
|
||||
measured(tarball_path.stat().st_size)
|
||||
|
||||
@@ -304,13 +307,9 @@ def _download_and_extract_zip(
|
||||
zip_path = Path(tmpdir) / "archive.zip"
|
||||
log.info("downloading %s", source_url)
|
||||
|
||||
req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp, open(zip_path, "wb") as f:
|
||||
while True:
|
||||
chunk = resp.read(65536)
|
||||
if not chunk:
|
||||
break
|
||||
f.write(chunk)
|
||||
upstream.download(
|
||||
source_url, zip_path, timeout=DOWNLOAD_TIMEOUT, user_agent=USER_AGENT
|
||||
)
|
||||
if measured is not None:
|
||||
measured(zip_path.stat().st_size)
|
||||
|
||||
@@ -352,13 +351,19 @@ def _download_and_extract_zip(
|
||||
def _measure_archive(source_url: str) -> int | None:
|
||||
"""The size of the archive at source_url, read by streaming it: a
|
||||
tarball GitHub builds on request is sent without a Content-Length."""
|
||||
req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT})
|
||||
size = 0
|
||||
req = urllib.request.Request(
|
||||
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:
|
||||
with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp:
|
||||
while chunk := resp.read(65536):
|
||||
size += len(chunk)
|
||||
except _TRANSIENT as exc:
|
||||
size = upstream.open_retrying(req, count, DOWNLOAD_TIMEOUT)
|
||||
except (*_TRANSIENT, upstream.UpstreamError) as exc:
|
||||
log.warning("could not measure %s: %s", source_url, exc)
|
||||
return None
|
||||
return size or None
|
||||
@@ -517,7 +522,9 @@ def _refresh_entry(
|
||||
try:
|
||||
file_count = fetch()
|
||||
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)
|
||||
return None
|
||||
except _TRANSIENT as exc:
|
||||
|
||||
@@ -165,6 +165,9 @@ def _follow_submodule(
|
||||
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
|
||||
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)
|
||||
behind = [v for v in views if v.field == "upstream" and v.pin != v.head]
|
||||
|
||||
@@ -7,7 +7,7 @@ import itertools
|
||||
import posixpath
|
||||
import re
|
||||
import sys
|
||||
from collections.abc import Callable, Iterable, Sequence
|
||||
from collections.abc import Callable, Iterable, Iterator, Sequence
|
||||
from dataclasses import dataclass, field, replace
|
||||
|
||||
from core import upstream
|
||||
@@ -406,11 +406,16 @@ class _Resolver:
|
||||
(self.context_for(v)[1] for v in self.views),
|
||||
)
|
||||
|
||||
def gitlinks_in_order(self) -> Iterable[Iterable[str]]:
|
||||
return (
|
||||
upstream.list_gitlinks(v.repo, v.pin, self.cache_dir, self.offline)
|
||||
for v in self.views
|
||||
)
|
||||
def gitlinks_in_order(self) -> Iterator[Iterable[str]]:
|
||||
"""Submodule paths of each declared tree at its pin. A tree the
|
||||
forge lists in part is said once and searched as far as it is
|
||||
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:
|
||||
# A bare filename, the way prose cites files. Resolved against the
|
||||
@@ -589,9 +594,17 @@ class _Resolver:
|
||||
if found is None and "/" in wanted:
|
||||
# A file of a submodule is read at the commit its gitlink
|
||||
# pins in this revision, so a bump moves it with the port.
|
||||
inner = upstream.through_gitlink(
|
||||
repo, sha, wanted, self.cache_dir, self.offline
|
||||
)
|
||||
try:
|
||||
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:
|
||||
found = upstream.fetch_file(*inner, self.cache_dir, self.offline)
|
||||
return found
|
||||
|
||||
@@ -7,17 +7,17 @@ and the offline switch that forbids reaching for the network."""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import hashlib
|
||||
import http.client
|
||||
import os
|
||||
import re
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
from core import upstream
|
||||
from model.database import record_at, record_for_hash
|
||||
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.localfile import resolution_is_hash_exact, resolve_local_file
|
||||
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.
|
||||
|
||||
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
|
||||
dest_path and hashed on the way, and removed when the hash disagrees.
|
||||
the entry stays missing, as verify reports it. core.upstream.download
|
||||
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")
|
||||
if not url:
|
||||
@@ -75,21 +77,18 @@ def download_external(
|
||||
print(f" WARNING: {name} is external and the run is offline, not fetched")
|
||||
return False
|
||||
algo, expected = declared[0], set(declared[1])
|
||||
digest = hashlib.new(algo)
|
||||
Path(dest_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "retrobios-pack-gen/1.0"})
|
||||
with urllib.request.urlopen(req, timeout=120) as resp, open(dest_path, "wb") as out:
|
||||
for chunk in iter(lambda: resp.read(1 << 20), b""):
|
||||
digest.update(chunk)
|
||||
out.write(chunk)
|
||||
except (urllib.error.URLError, OSError) as exc:
|
||||
served = upstream.download(
|
||||
url, dest_path, timeout=120, user_agent="retrobios-pack-gen/1.0",
|
||||
accept=lambda scratch: file_digest(Path(scratch), algo) in expected,
|
||||
)
|
||||
except (urllib.error.URLError, OSError, http.client.HTTPException,
|
||||
upstream.UpstreamError, ValueError) as exc:
|
||||
print(f" WARNING: Failed to download {url}: {exc}")
|
||||
Path(dest_path).unlink(missing_ok=True)
|
||||
return False
|
||||
if digest.hexdigest() not in expected:
|
||||
if served is None:
|
||||
print(f" WARNING: {algo.upper()} mismatch for {name}")
|
||||
Path(dest_path).unlink(missing_ok=True)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
+28
-26
@@ -19,6 +19,7 @@ from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from core import upstream
|
||||
from core.artifacts import write_text_atomic
|
||||
from core.github import github_token
|
||||
|
||||
@@ -28,14 +29,14 @@ SITE_PROPERTY = "https://abdess.github.io/retrobios/"
|
||||
GOATCOUNTER = "https://retrobios.goatcounter.com/api/v0"
|
||||
REPOSITORY = "Abdess/retrobios"
|
||||
SOURCES = ("gsc", "goatcounter", "github")
|
||||
USER_AGENT = "retrobios-site-insights"
|
||||
# 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 = 5
|
||||
EXPORT_TRIES = 60
|
||||
# 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.
|
||||
RATE_LIMIT_TRIES = 8
|
||||
RATE_LIMIT_LONGEST_WAIT = 60
|
||||
# when to come back in X-Rate-Limit-Reset. core.upstream.open_retrying waits
|
||||
# a short wait and gives up on a long one, which ends the run.
|
||||
|
||||
# Expected click-through rate: the site's own rate at each rounded
|
||||
# position, positions past 20 pooled in LAST_BUCKET. A bucket under
|
||||
@@ -67,25 +68,26 @@ class Query:
|
||||
# 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]:
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
request = urllib.request.Request(url, data=data, headers={
|
||||
"User-Agent": "retrobios-site-insights", **({"Content-Type": "application/json"} if data else {}),
|
||||
**(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()
|
||||
return _open(urllib.request.Request(url, data=data, headers={
|
||||
"User-Agent": USER_AGENT, **({"Content-Type": "application/json"} if data else {}),
|
||||
**(headers or {})}))
|
||||
|
||||
|
||||
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
|
||||
body = urllib.parse.urlencode({"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
|
||||
"assertion": f"{unsigned}.{b64(signature)}"}).encode()
|
||||
request = urllib.request.Request(key["token_uri"], data=body)
|
||||
with urllib.request.urlopen(request, timeout=60) as response:
|
||||
return json.load(response)["access_token"]
|
||||
request = urllib.request.Request(key["token_uri"], data=body, headers={"User-Agent": USER_AGENT})
|
||||
return json.loads(_open(request)[1])["access_token"]
|
||||
|
||||
|
||||
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:
|
||||
token = github_token()
|
||||
if not token:
|
||||
# Traffic figures are only served to the owner: without a token there
|
||||
# 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")
|
||||
auth = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json"}
|
||||
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)
|
||||
return {
|
||||
"views": _get_json(f"{api}/traffic/views", auth),
|
||||
|
||||
+21
-20
@@ -18,7 +18,7 @@ from core.artifacts import write_if_changed
|
||||
from core.cli import InputMissing
|
||||
from core.paths import DB_FILE, REPO_ROOT
|
||||
from core.sizes import size_text
|
||||
from core.upstream import forge_headers
|
||||
from core import upstream
|
||||
from installer_build.module import installer_module
|
||||
from model.composition import compute_composition, count_catalog_matched
|
||||
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]:
|
||||
"""Fetch contributors from GitHub API, exclude bots."""
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
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):
|
||||
"""Contributors from the GitHub API, bots and the owner left out. Empty
|
||||
when the API cannot be read, or under RETROBIOS_OFFLINE: the caller then
|
||||
keeps the published list."""
|
||||
if os.environ.get("RETROBIOS_OFFLINE"):
|
||||
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"}
|
||||
|
||||
@@ -39,7 +39,6 @@ import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
@@ -48,6 +47,7 @@ from typing import IO
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
import core_probe as cp
|
||||
from core import upstream
|
||||
from core.statefile import now_iso
|
||||
|
||||
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]:
|
||||
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",
|
||||
headers=github_headers())
|
||||
with urllib.request.urlopen(request, timeout=60) as response:
|
||||
return json.load(response)
|
||||
return github_json(f"https://api.github.com/repos/{repo}/releases",
|
||||
f"cannot list the releases of {repo}", timeout=60)
|
||||
|
||||
|
||||
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.mkdir(parents=True, exist_ok=True)
|
||||
partial = folder / f"{asset['name']}.part"
|
||||
with urllib.request.urlopen(asset["url"], timeout=600) as response, partial.open("wb") as out:
|
||||
shutil.copyfileobj(response, out)
|
||||
# Whole or absent, retried on a cut stream (core.upstream.download).
|
||||
upstream.download(asset["url"], partial, timeout=600)
|
||||
sha256 = cp.file_digest(partial, "sha256")
|
||||
target = folder / sha256 / asset["name"]
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
Reference in new issue
Block a user