fix: let core.upstream refuse requests offline

RETROBIOS_OFFLINE was read by six callers and never by the network
gateway: a caller that did not pass offline=True sent the request,
untokened. core.offline holds the rule, open_retrying refuses with
OfflineError and the cached reads answer as an offline run. The callers
read the same predicate, and the tests that fake the network clear the
variable for themselves (tests.ONLINE).
This commit is contained in:
Abdessamad Derraz committed 2026-11-24 00:20:03 +01:00
1 parent 409cc843f9
commit 83e810d1b3
23 files changed
+124 -17

No files matched your search

+1
View File
@@ -22,6 +22,7 @@ on:
- "scripts/core/github.py"
- "scripts/core/hashing.py"
- "scripts/core/memo.py"
- "scripts/core/offline.py"
- "scripts/core/options.py"
- "scripts/core/paths.py"
- "scripts/core/romdir.py"
+3 -1
View File
@@ -5,6 +5,8 @@ from __future__ import annotations
import functools
import os
from core.offline import run_is_offline
@functools.lru_cache(maxsize=1)
def _gh_cli_token() -> str:
@@ -41,7 +43,7 @@ def github_token() -> str:
call and never ask gh.
"""
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN") or ""
if token or os.environ.get("RETROBIOS_OFFLINE"):
if token or run_is_offline():
return token
token = _gh_cli_token()
if token:
+14
View File
@@ -0,0 +1,14 @@
"""Whether a run fetches nothing: the one rule core.upstream and its callers read."""
from __future__ import annotations
import os
# Set, this run fetches nothing whatever its callers pass: the test runners
# and the PR checks set it.
OFFLINE_ENV = "RETROBIOS_OFFLINE"
def run_is_offline(offline: bool | None = False) -> bool:
"""Whether this run fetches nothing: the caller's flag, or RETROBIOS_OFFLINE."""
return bool(offline) or bool(os.environ.get(OFFLINE_ENV))
+16 -3
View File
@@ -27,6 +27,7 @@ from pathlib import Path
from typing import Callable, Mapping, Protocol, TypeVar
from core.artifacts import atomic_scratch, write_text_atomic
from core.offline import OFFLINE_ENV, run_is_offline
USER_AGENT = "retrobios-profile-sync/1.0"
# Where fetched upstream files live, shared by every reader of this cache.
@@ -123,6 +124,10 @@ class NotCachedError(UpstreamError):
"""
class OfflineError(NotCachedError):
"""A request a run that fetches nothing (RETROBIOS_OFFLINE) would have sent."""
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
@@ -379,9 +384,12 @@ def open_retrying(
limit is waited out, and a host that outlasts the waits is not asked
again in this process. What ends the attempts is raised as urllib gave
it, except a host that does not resolve (GoneError) and a host muted
earlier (RateLimitError).
earlier (RateLimitError). A run that fetches nothing (run_is_offline)
raises OfflineError before anything goes out.
"""
url = request.full_url
if run_is_offline():
raise OfflineError(f"{url}: {OFFLINE_ENV} is set, nothing is fetched")
host = urllib.parse.urlsplit(url).hostname or ""
if host in _exhausted_hosts:
raise RateLimitError(f"{url}: {host} rate limited earlier in this run", host)
@@ -554,6 +562,7 @@ def fetch_file(
Offline, a path the cache never stored raises NotCachedError: nothing
is known about it, which is not the same as knowing it is absent.
"""
offline = run_is_offline(offline)
target = cache_path(cache_dir, repo, sha, path)
if target.is_file():
text = target.read_text(encoding="utf-8")
@@ -585,7 +594,7 @@ def _require_cached(url: str, cache_dir: str, offline: bool, what: str) -> None:
cached_api answers None both for a resource the forge does not have and for
one never asked, and only the first is a fact.
"""
if offline and not _api_target(url, cache_dir).is_file():
if run_is_offline(offline) and not _api_target(url, cache_dir).is_file():
raise NotCachedError(f"{what} is not in the offline cache")
@@ -600,6 +609,7 @@ def cached_api(
``absent_max_age`` bounds a cached absence alone, for a resource that
can appear but, once there, does not change.
"""
offline = run_is_offline(offline)
target = _api_target(url, cache_dir)
if target.is_file():
raw = target.read_text(encoding="utf-8")
@@ -626,6 +636,7 @@ def fetch_page(url: str, cache_dir: str, offline: bool) -> str | None:
None is a page the site answers absent. Offline, a page the cache never
stored raises NotCachedError, as every other read of this module does.
"""
offline = run_is_offline(offline)
key = hashlib.sha256(url.encode()).hexdigest()
target = Path(cache_dir) / "_pages" / f"{key}.txt"
if target.is_file():
@@ -819,6 +830,7 @@ def _github_graphql(
"""
from core.github import github_token
offline = run_is_offline(offline)
body = json.dumps({"query": query, "variables": variables}, sort_keys=True)
target = Path(cache_dir) / "_api" / f"{hashlib.sha256(body.encode()).hexdigest()}.json"
if target.is_file():
@@ -1162,7 +1174,7 @@ def cache_gitlab_directory(
index = cache_path(cache_dir, repo, sha, f".archives/{directory}.json")
if index.is_file():
return set(json.loads(index.read_text(encoding="utf-8")))
if offline or repo.family != "gitlab":
if run_is_offline(offline) or repo.family != "gitlab":
return None
try:
files = _gitlab_archive_files(repo, sha, directory)
@@ -1434,6 +1446,7 @@ def _has_commit(clone: Path, sha: str) -> bool:
def _graph(repo: Repo, sha: str, cache_dir: str, offline: bool) -> Path:
"""A clone holding sha and every tag, fetched again once tags may have moved."""
offline = run_is_offline(offline)
clone = clone_dir(cache_dir, repo)
url = f"https://{repo.host}/{repo.slug}.git"
if not (clone / "HEAD").is_file():
+1 -1
View File
@@ -246,7 +246,7 @@ def _fetch_asset(
# shared cache filled the runner's disk and changed what later tests
# resolved. Decided once, so the release check of a cached copy obeys it
# as the download does.
offline = offline or bool(os.environ.get("RETROBIOS_OFFLINE"))
offline = upstream.run_is_offline(offline)
cached = os.path.join(dest_dir, name)
# Between the existence test and the hash, a concurrent run can drop the
# same stale entry: the file is gone by the time this one reads it, and
+2 -1
View File
@@ -5,13 +5,14 @@ from __future__ import annotations
import sys
from core.github import github_token
from core.offline import run_is_offline
ANON_QUOTA = 60
def check_quota(count: int, offline: bool) -> None:
"""Refuse a run the anonymous quota cannot carry to completion."""
if offline or github_token():
if run_is_offline(offline) or github_token():
return
if count * 5 > ANON_QUOTA:
print(
+2 -2
View File
@@ -3,12 +3,12 @@
from __future__ import annotations
import argparse
import os
import sys
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from core.offline import run_is_offline
from core.paths import EMULATORS_DIR, REPO_ROOT
from model.profiles import load_emulator_profiles
@@ -39,7 +39,7 @@ def refresh_source_paths(args: argparse.Namespace, written: set[str]) -> None:
another tree prints the command for it instead of reducing the record
to the trees that tree cites.
"""
if not written or args.dry_run or args.offline or os.environ.get("RETROBIOS_OFFLINE"):
if not written or args.dry_run or run_is_offline(args.offline):
return
if Path(args.emulators_dir).resolve() != (REPO_ROOT / EMULATORS_DIR).resolve():
print(
+1 -4
View File
@@ -150,10 +150,7 @@ def _fetched_asset(path: str, sha1: str, file_entry: dict, offline: bool) -> str
def run_is_offline(offline: bool | None = None) -> bool:
"""Whether this run fetches nothing: --offline, or RETROBIOS_OFFLINE."""
return bool(
(OFFLINE if offline is None else offline)
or os.environ.get("RETROBIOS_OFFLINE")
)
return upstream.run_is_offline(OFFLINE if offline is None else offline)
def release_asset_paths(
+2 -1
View File
@@ -8,6 +8,7 @@ from collections.abc import Callable
from pathlib import Path
from core.cli import InputMissing
from core.offline import run_is_offline
from core.paths import DB_FILE, EMULATORS_DIR, REPO_ROOT
from model import siteinputs
from model.largefiles import LARGE_FILES_CACHE
@@ -130,7 +131,7 @@ def _coverage_inputs(db_path: Path, platforms_dir: str, emulators_dir: str) -> s
for path in (REPO_ROOT / ".gitignore", REPO_ROOT / "_mame_clones.json",
REPO_ROOT / VERSIONS_FILE):
add_file(path)
digest.update(b"offline\0" + (b"1" if os.environ.get("RETROBIOS_OFFLINE") else b"0") + b"\n")
digest.update(b"offline\0" + (b"1" if run_is_offline() else b"0") + b"\n")
large = Path(LARGE_FILES_CACHE).resolve()
digest.update(str(large).encode() + b"\0")
for path in sorted(large.glob("*")) if large.is_dir() else ():
+1 -2
View File
@@ -3,7 +3,6 @@
from __future__ import annotations
import json
import os
import re
import sys
from collections.abc import Callable
@@ -155,7 +154,7 @@ def fetch_contributors() -> list[dict]:
"""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"):
if upstream.run_is_offline():
return []
url = f"https://api.github.com/repos/{REPO}/contributors"
try:
+7 -2
View File
@@ -2,8 +2,9 @@
The CI job sets RETROBIOS_OFFLINE, but a local run of the documented command
did not, and e2e fixtures queried the large-files release and wrote its
answers into the shared .cache/large. A test that serves its own assets
clears the variable for itself.
answers into the shared .cache/large. A test that serves its own assets,
or fakes the network core.upstream reaches, clears the variable for itself
(ONLINE).
Scratch files go under the repository's tmp/, which git does not track: a
fresh clone has none, and a module run alone raised FileNotFoundError on a
@@ -18,8 +19,12 @@ import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
os.environ.setdefault("RETROBIOS_OFFLINE", "1")
# A test or a test class that fakes the network runs as a run that fetches:
# under RETROBIOS_OFFLINE, core.upstream refuses every request before it goes out.
ONLINE = mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""})
# The modules under test import each other by bare name (common, verify), as
# the scripts do when run from scripts/, and install.py sits at the root.
_REPOSITORY = Path(__file__).resolve().parent.parent
+1
View File
@@ -137,6 +137,7 @@ class EveryWriterGoesThroughIt(unittest.TestCase):
)
@tests.ONLINE
class TheNativeIndexKeepsEveryPlatform(unittest.TestCase):
"""Native originals refresh platform by platform, in parallel. Each run
rewrote the whole URL index it had read before downloading, and the last
+1
View File
@@ -6894,6 +6894,7 @@ class ABrokenRegistryIsNotAnEmptyOne(unittest.TestCase):
self.assertIn("rocknix", str(caught.exception))
@tests.ONLINE
class AnUnansweredSearchIsNotANotFound(unittest.TestCase):
"""auto_fetch caught every network error and reported the file as
needing a community contribution: offline, each file became an issue
+4
View File
@@ -44,6 +44,7 @@ def _serving(payloads: dict[str, bytes]):
return urlopen, asked
@tests.ONLINE
class SoftwareHeritageAnswersByContent(unittest.TestCase):
def test_the_bytes_it_serves_are_kept_when_the_hash_holds(self):
urlopen, asked = _serving({f"{fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD})
@@ -65,6 +66,7 @@ class SoftwareHeritageAnswersByContent(unittest.TestCase):
self.assertEqual(found, fetch.SearchResult(None, None, ()))
@tests.ONLINE
class LookupBySha1(unittest.TestCase):
def setUp(self):
directory = tempfile.TemporaryDirectory()
@@ -130,6 +132,7 @@ class PlatformSearchLines(unittest.TestCase):
" [5] Search incomplete, 2 source(s) did not answer (first: u: offline)"])
@tests.ONLINE
class AStalledOrLimitedSourceIsNoAnswer(unittest.TestCase):
"""A timeout during the read is a TimeoutError, not a URLError: it
escaped every handler and ended the search for every remaining file.
@@ -188,6 +191,7 @@ class AStalledOrLimitedSourceIsNoAnswer(unittest.TestCase):
self.assertEqual(len(asked), 2)
@tests.ONLINE
class ArchiveOrgAnswersByHash(unittest.TestCase):
"""The platform search asked archive.org for the first item and then
downloaded the platform's name from it: an item storing the dump under
+7
View File
@@ -392,6 +392,11 @@ class DownloaderCase(unittest.TestCase):
platform_label = "Batocera 43.1"
def setUp(self):
# The downloaders fetch from the loopback release, in this process
# and in the commands env() starts.
online = mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""})
online.start()
self.addCleanup(online.stop)
self.server = ReleaseServer(
self.pack_name, self.payload, self.volumes, self.zip_parts
)
@@ -756,6 +761,7 @@ class TestZipPartsLibrary(ZipPartsCase, TestDownloadLibrary):
@tests.ONLINE
class AProgressBarOnlyOnATerminal(unittest.TestCase):
"""Redirected to a log, download.py wrote a carriage-return redraw per
64 KiB block: one line of nearly 3 MB for a 2 GiB part."""
@@ -819,6 +825,7 @@ class AProgressBarOnlyOnATerminal(unittest.TestCase):
self.assertEqual(answers, [])
@tests.ONLINE
class ATransferFailureIsADownloadError(unittest.TestCase):
"""download_file printed its own lines and raised a bare ValueError on a
short stream, so download.py, which catches DownloadError, ended in a
+1
View File
@@ -3857,6 +3857,7 @@ class APassedReleaseUnderAnUntaggedVersion(unittest.TestCase):
self.assertIsNone(version_warning(version, "head"))
@tests.ONLINE
class TestAncestry(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
+2
View File
@@ -49,6 +49,7 @@ class _Response(io.BytesIO):
return False
@tests.ONLINE
class RefreshConcurrency(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
@@ -412,6 +413,7 @@ class ASourceThatMovesIsPinnedOrFollowed(unittest.TestCase):
self.assertIn("{version}", entry["source_path"])
@tests.ONLINE
class TheRemoteCommitComesFromTheForgeClient(unittest.TestCase):
"""get_remote_sha read a GitLab subgroup as its first two segments,
asked the branches endpoint (no tag, no encoded name), sent the token to
+1
View File
@@ -46,6 +46,7 @@ def _opener(failure):
return urlopen
@tests.ONLINE
class ManifestErrors(unittest.TestCase):
def fetch(self, failure):
# A 503 is retried after a wait: the waits are skipped, not the retries.
+4
View File
@@ -143,6 +143,7 @@ class TestConnection(unittest.TestCase):
_StubScraper(error=KeyError("bug")).test_connection()
@tests.ONLINE
class RateLimitedForge(unittest.TestCase):
"""GitLab answered 429 midway through Recalbox's system.ini files and
the whole scrape stopped."""
@@ -257,6 +258,7 @@ class RecalboxReadsItsSystemsInBatches(unittest.TestCase):
self.assertEqual(len(cores), 120)
@tests.ONLINE
class AnEmptyRecalboxListingStopsTheTargets(unittest.TestCase):
"""The targets scraper kept its own copy of the systems listing, without
the empty check: an empty answer wrote every board with no core."""
@@ -749,6 +751,7 @@ class EveryTargetCoreReachesAProfile(unittest.TestCase):
self.assertEqual(unresolved, {})
@tests.ONLINE
class UnreadableReleaseStopsTheScrape(unittest.TestCase):
"""A failed tag lookup fell back to master, or to an empty or invented
version. BizHawk, RomM, Batocera and Recalbox then wrote a YAML read from
@@ -968,6 +971,7 @@ class CoreInfoCompareDbResolvesLikeTheCollection(unittest.TestCase):
self.assertEqual(split_by_holding([req], self.db), ([req], []))
@tests.ONLINE
class EveryGitHubApiCallerSendsTheToken(unittest.TestCase):
"""romset_dat_importer and coreinfo_scraper called api.github.com with no
token: past the anonymous quota, --fetch failed with 403 while
+4
View File
@@ -149,6 +149,7 @@ class SourceRevisionReadsEveryShape(unittest.TestCase):
platform_revision(path)
@tests.ONLINE
class TheTokenGoesToGitHubOnly(unittest.TestCase):
def setUp(self):
patcher = mock.patch.dict(os.environ, {"GITHUB_TOKEN": "t0k"})
@@ -174,6 +175,7 @@ class TheTokenGoesToGitHubOnly(unittest.TestCase):
self.assertEqual(opener.seen[0].get_header("Authorization"), "Bearer t0k")
@tests.ONLINE
class FetchFailures(unittest.TestCase):
def test_the_status_is_kept(self):
with mock.patch("urllib.request.urlopen", _answer(403)), \
@@ -195,6 +197,7 @@ class FetchFailures(unittest.TestCase):
fetch_bytes("https://x.example/f", max_bytes=5)
@tests.ONLINE
class GitHubAnswers(unittest.TestCase):
def test_a_truncated_tree_raises(self):
with mock.patch("urllib.request.urlopen", _answer({"tree": [], "truncated": True})), \
@@ -229,6 +232,7 @@ class GitHubAnswers(unittest.TestCase):
self.assertEqual(fetch_github_latest_version("o/r"), "v9")
@tests.ONLINE
class Downloads(unittest.TestCase):
def test_written_whole_with_its_disposition(self):
with tempfile.TemporaryDirectory() as tmp:
+1
View File
@@ -243,6 +243,7 @@ def goat_export(hourly: list[tuple[str, str, str, int]]) -> bytes:
return buffer.getvalue()
@tests.ONLINE
class GoatCounterExport(unittest.TestCase):
FIRST = dt.datetime(2026, 10, 20, tzinfo=dt.timezone.utc)
AFTER = dt.datetime(2026, 11, 17, tzinfo=dt.timezone.utc)
+3
View File
@@ -83,6 +83,7 @@ def _serve_batocera(boards: list[str], refuse_board: bool):
return urlopen
@tests.ONLINE
class FailedRequestsStopTheScrape(unittest.TestCase):
def test_every_scraper_raises(self):
for module in (
@@ -400,6 +401,7 @@ class DownloadedCoresReachTheirBoards(unittest.TestCase):
self.assertEqual(resolved, {"amiberry": {"amiberry"}, "amiberry, mgba": set()})
@tests.ONLINE
class KnulliPerBoard(unittest.TestCase):
"""KNULLI builds per board on Batocera's model from its own tree:
configs/knulli-*.board, package/system/knulli-system/Config.in and
@@ -773,6 +775,7 @@ def _retropie_tarball(modules: dict[str, str]) -> bytes:
return buffer.getvalue()
@tests.ONLINE
class TargetsReadThePlatformRevision(unittest.TestCase):
"""A target list read on master filtered packages by flags the pinned
package list does not have: every request names the platform's pin."""
+45
View File
@@ -244,6 +244,7 @@ class TestHttpFailure(unittest.TestCase):
self.assertNotIsInstance(failure, upstream.RateLimitError)
@tests.ONLINE
class TestFetchRetry(unittest.TestCase):
"""Transient network failures are retried, definitive answers are not."""
@@ -401,6 +402,7 @@ class TestFetchRetry(unittest.TestCase):
self.assertEqual((self.calls, self.slept), (1, []))
@tests.ONLINE
class TestGoneUpstream(unittest.TestCase):
"""A forge that will not come back is a fact, not a failure to retry.
@@ -480,6 +482,41 @@ class TestGoneUpstream(unittest.TestCase):
self.assertEqual(self.calls, upstream.RETRIES)
class TheOfflineSwitchHoldsAtTheGateway(unittest.TestCase):
"""RETROBIOS_OFFLINE is read by core.upstream itself: a caller that did
not pass offline=True made the request anyway, untokened."""
def setUp(self):
patcher = mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": "1"})
patcher.start()
self.addCleanup(patcher.stop)
def test_the_rule_is_the_flag_or_the_variable(self):
self.assertTrue(upstream.run_is_offline(False))
self.assertTrue(upstream.run_is_offline(None))
with mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}):
self.assertFalse(upstream.run_is_offline())
self.assertTrue(upstream.run_is_offline(True))
def test_no_request_goes_out(self):
with mock.patch.object(urllib.request, "urlopen", side_effect=_no_network) as urlopen:
with self.assertRaises(upstream.OfflineError):
upstream.fetch_body("https://api.github.com/rate_limit", accept_json=True)
with self.assertRaises(upstream.NotCachedError):
upstream.download("https://host/x", tests.scratch_dir(self) / "x")
urlopen.assert_not_called()
def test_the_cache_answers_as_an_offline_run(self):
cache = str(tests.scratch_dir(self))
with mock.patch.object(upstream, "http_json", side_effect=_no_network), \
mock.patch.object(upstream, "http_text", side_effect=_no_network):
self.assertIsNone(upstream.cached_api("https://api.github.com/x", cache, False))
with self.assertRaises(upstream.NotCachedError):
upstream.fetch_file(parse_repo("https://github.com/o/n"), "abc", "a.c", cache)
@tests.ONLINE
class TestCache(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
@@ -565,6 +602,7 @@ class TestCacheCollision(unittest.TestCase):
self.assertTrue((base / "C64DTV").is_file())
@tests.ONLINE
class TestRevisions(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
@@ -717,6 +755,7 @@ class TestRevisions(unittest.TestCase):
upstream.resolve_head(self.repo, self.dir)
@tests.ONLINE
class TestCompare(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
@@ -885,6 +924,7 @@ class TestCompare(unittest.TestCase):
self.assertEqual(upstream.tag_commit(self.repo, "v2.0", self.dir), "rel")
@tests.ONLINE
class TestGitlabTree(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
@@ -950,6 +990,7 @@ class TestGitlabTree(unittest.TestCase):
self.assertEqual(upstream.list_gitlinks(self.repo, "sha", self.dir), {"core": "c" * 40})
@tests.ONLINE
class TestGiteaCommitAt(unittest.TestCase):
"""Gitea and Forgejo ignore `until` and answer with the tip: the date
pin of a Codeberg view was the tip of the day of the first fetch."""
@@ -992,6 +1033,7 @@ class TestGiteaCommitAt(unittest.TestCase):
@tests.ONLINE
class TestCurrentSlug(unittest.TestCase):
"""The name a forge answers under, read from the repository payload."""
@@ -1041,6 +1083,7 @@ class TestNewestTag(unittest.TestCase):
self.assertEqual(upstream.newest_tag(self.repo, self.tmp.name), "2.5")
@tests.ONLINE
class TestNamedTagCommit(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
@@ -1063,6 +1106,7 @@ class TestNamedTagCommit(unittest.TestCase):
self.assertTrue(asked[0].endswith("/repository/tags/1.2.35"))
@tests.ONLINE
class TestForkBase(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
@@ -1104,6 +1148,7 @@ def _tarball(files: dict[str, str]) -> bytes:
return buf.getvalue()
@tests.ONLINE
class TestGitlabDirectoryArchive(unittest.TestCase):
"""One archive request fills the per-file cache of a GitLab directory."""