mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-23 10:07:48 -06:00
fix: build github api headers with forge_headers
download.py read GITHUB_TOKEN only and missed the gh login token, the readme built its header by hand, and the large files listing cached one failed request as an empty release for the whole run.
This commit is contained in:
1 parent
6138d43dfb
commit
8bfa188960
5 files changed
+44
-27
No files matched your search
+2
-7
@@ -33,6 +33,7 @@ from pathlib import Path
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
from core.hashing import compute_hashes, parse_sha256sums
|
||||
from core.paths import REPO_ROOT
|
||||
from core.upstream import forge_headers
|
||||
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
|
||||
@@ -96,15 +97,9 @@ NO_PACK_HINT = (
|
||||
def get_latest_release() -> dict:
|
||||
"""Fetch latest release info from GitHub API."""
|
||||
url = f"{API}/repos/{REPO}/releases/latest"
|
||||
headers = {
|
||||
"User-Agent": "retrobios-downloader/1.0",
|
||||
"Accept": "application/vnd.github.v3+json",
|
||||
}
|
||||
# The anonymous quota is 60 calls an hour per address. The token goes to
|
||||
# GitHub's API only: RETROBIOS_API can name any host.
|
||||
token = os.environ.get("GITHUB_TOKEN")
|
||||
if token and urllib.parse.urlsplit(url).hostname == "api.github.com":
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
headers = forge_headers(url, "application/vnd.github.v3+json", "retrobios-downloader/1.0")
|
||||
req = urllib.request.Request(url, headers=headers)
|
||||
|
||||
try:
|
||||
|
||||
@@ -21,6 +21,7 @@ from collections import Counter
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
|
||||
from core import upstream
|
||||
from core.artifacts import set_plain_mode
|
||||
from core.hashing import compute_hashes, file_digest, parse_hash_list
|
||||
from core.paths import REPO_ROOT
|
||||
@@ -411,7 +412,9 @@ _digests_cache: dict[str, str] | None = None
|
||||
|
||||
def _served_digests() -> dict[str, str]:
|
||||
"""sha256 of each asset the release serves, by asset name, empty when
|
||||
the API cannot be read."""
|
||||
the API cannot be read. A failed listing is not kept: one dropped
|
||||
connection made every asset fall back to its Content-Length for the
|
||||
rest of the run."""
|
||||
global _digests_cache
|
||||
if _digests_cache is not None:
|
||||
return _digests_cache
|
||||
@@ -419,21 +422,13 @@ def _served_digests() -> dict[str, str]:
|
||||
f"https://api.github.com/repos/{LARGE_FILES_REPO}/releases/tags/"
|
||||
f"{LARGE_FILES_RELEASE}"
|
||||
)
|
||||
headers = {"User-Agent": "retrobios/1.0", "Accept": "application/vnd.github+json"}
|
||||
from core.github import github_token
|
||||
|
||||
token = github_token()
|
||||
if token:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
digests: dict[str, str] = {}
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
urllib.request.Request(url, headers=headers), timeout=60
|
||||
) as resp:
|
||||
release = json.load(resp)
|
||||
except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as exc:
|
||||
body = upstream.fetch_body(url, accept_json=True, timeout=60, user_agent="retrobios/1.0")
|
||||
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)
|
||||
release = {}
|
||||
return {}
|
||||
digests: dict[str, str] = {}
|
||||
for asset in release.get("assets") or []:
|
||||
digest = str(asset.get("digest") or "")
|
||||
if digest.startswith("sha256:"):
|
||||
|
||||
@@ -16,9 +16,9 @@ from devtools import prchecks
|
||||
from model import releaserecord
|
||||
from core.artifacts import write_if_changed
|
||||
from core.cli import InputMissing
|
||||
from core.github import github_token
|
||||
from core.paths import DB_FILE, PLATFORMS_DIR, REPO_ROOT
|
||||
from core.sizes import size_text
|
||||
from core.upstream import forge_headers
|
||||
from model.composition import compute_composition, count_catalog_matched
|
||||
from model.declarations import declared_root
|
||||
from model.guides import PACKAGE_COMMAND, install_command
|
||||
@@ -513,10 +513,7 @@ def fetch_contributors() -> list[dict]:
|
||||
import urllib.request
|
||||
|
||||
url = f"https://api.github.com/repos/{REPO}/contributors"
|
||||
headers = {"User-Agent": "retrobios-readme/1.0"}
|
||||
token = github_token()
|
||||
if token:
|
||||
headers["Authorization"] = f"token {token}"
|
||||
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:
|
||||
|
||||
@@ -92,6 +92,10 @@ class LargeFileCacheTest(unittest.TestCase):
|
||||
_test_registry(self)
|
||||
self.dir = tempfile.mkdtemp()
|
||||
self._urlopen = largefiles.urllib.request.urlopen
|
||||
# No release digests: a replaced asset is told by its size.
|
||||
digests = mock.patch.object(largefiles, "_digests_cache", {})
|
||||
digests.start()
|
||||
self.addCleanup(digests.stop)
|
||||
|
||||
def tearDown(self):
|
||||
largefiles.urllib.request.urlopen = self._urlopen
|
||||
@@ -909,5 +913,27 @@ class AVerifiedPathKeepsItsBytes(unittest.TestCase):
|
||||
)
|
||||
|
||||
|
||||
class AFailedReleaseListingIsAskedAgain(unittest.TestCase):
|
||||
"""One dropped connection on the release listing was kept as {} for the
|
||||
run, and every asset fell back to its Content-Length."""
|
||||
|
||||
def test_the_listing_is_read_again_after_a_failure(self):
|
||||
from core import upstream
|
||||
|
||||
release = {"assets": [{"name": "a.zip", "digest": "sha256:ABC"}]}
|
||||
answers = [upstream.UpstreamError("reset"), json.dumps(release).encode()]
|
||||
|
||||
def fetch_body(*_args, **_kwargs):
|
||||
answer = answers.pop(0)
|
||||
if isinstance(answer, Exception):
|
||||
raise answer
|
||||
return answer
|
||||
|
||||
with mock.patch.object(largefiles, "_digests_cache", None), \
|
||||
mock.patch.object(upstream, "fetch_body", fetch_body):
|
||||
self.assertEqual(largefiles._served_digests(), {})
|
||||
self.assertEqual(largefiles._served_digests(), {"a.zip": "abc"})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -821,12 +821,15 @@ class EveryGitHubApiCallerSendsTheToken(unittest.TestCase):
|
||||
if "api.github.com" in (source := path.read_text(encoding="utf-8"))
|
||||
# arcade_parent_importer names API URLs and sends them through
|
||||
# romset_dat_importer._api_json, which holds the token, and the
|
||||
# scrapers through base_scraper.github_json.
|
||||
# scrapers through base_scraper.github_json, the rest through
|
||||
# core.upstream.fetch_body or forge_headers.
|
||||
and ("Request(" in source or "urlopen(" in source or path.suffix == ".sh")
|
||||
and "GITHUB_TOKEN" not in source
|
||||
and "github_headers(" not in source
|
||||
and "github_json(" not in source
|
||||
and "github_token(" not in source
|
||||
and "forge_headers(" not in source
|
||||
and "fetch_body(" not in source
|
||||
)
|
||||
self.assertEqual(silent, [])
|
||||
|
||||
@@ -855,6 +858,7 @@ class EveryGitHubApiCallerSendsTheToken(unittest.TestCase):
|
||||
and "github_headers(" not in body
|
||||
and "github_token(" not in body
|
||||
and "GITHUB_TOKEN" not in body
|
||||
and "forge_headers(" not in body
|
||||
):
|
||||
silent.append(f"{path.relative_to(scripts)}:{node.name}")
|
||||
self.assertEqual(silent, [])
|
||||
|
||||
Reference in new issue
Block a user