fix: name why an external download failed

download_external returns an ExternalFetch outcome instead of printing and returning a bare bool, so the pack report names the real cause. lookup_hashes resolves offline and counts a release asset as held without downloading it.
This commit is contained in:
Abdessamad Derraz committed 2026-11-23 21:02:46 +01:00
1 parent 5b3f0c3f4c
commit d6abe6fd95
4 files changed
+111 -40

No files matched your search

+6 -3
View File
@@ -324,9 +324,12 @@ class _EmulatorPackBuild:
try:
# Built in memory, nothing is fetched: verify --emulator
# cannot fetch either and reports the file missing.
if self.record is None and download_external(fe, tmp_path):
self._add(tmp_path, dest, None)
return (alternatives, True, None)
if self.record is None:
fetch = download_external(fe, tmp_path)
if fetch.fetched:
self._add(tmp_path, dest, None)
return (alternatives, True, None)
self.progress(f" WARNING: {fe['name']}: {fetch.reason}")
return (alternatives, False, functools.partial(
self.missing_files.append, fe["name"]
))
+10 -2
View File
@@ -636,7 +636,12 @@ class _PlatformPackBuild:
# filling it on a failed download made the two differ.
self.placed.take(full_dest)
try:
if self.plan.opts.record is None and download_external(file_entry, tmp_path):
# Built in memory, nothing is fetched: verify cannot fetch either.
fetch = (
download_external(file_entry, tmp_path)
if self.plan.opts.record is None else None
)
if fetch is not None and fetch.fetched:
extract = file_entry.get("extract", False)
if extract and tmp_path.endswith(".zip"):
extract_zip_to_archive(tmp_path, self._flat(full_dest), self.zf)
@@ -646,7 +651,10 @@ class _PlatformPackBuild:
self.total_files += 1
else:
self.file_status[full_dest] = "missing"
self.file_reasons[full_dest] = "external download failed"
self.file_reasons[full_dest] = (
fetch.reason if fetch is not None
else "external file not fetched for an in-memory build"
)
finally:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
+55 -20
View File
@@ -12,6 +12,7 @@ import os
import urllib.error
from collections.abc import Iterator
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from core import upstream
@@ -52,30 +53,65 @@ def scratch_dir() -> str:
return str(path)
class ExternalOutcome(Enum):
"""How a `storage: external` download ended."""
FETCHED = "fetched"
NO_URL = "no_url"
NO_HASH = "no_hash"
OFFLINE = "offline"
NETWORK_ERROR = "network_error"
MISMATCH = "mismatch"
@dataclass(frozen=True)
class ExternalFetch:
"""The end of one external download, with what the caller reports.
``detail`` is the URL and error for NETWORK_ERROR and the hash field for
MISMATCH."""
outcome: ExternalOutcome
detail: str = ""
@property
def fetched(self) -> bool:
return self.outcome is ExternalOutcome.FETCHED
@property
def reason(self) -> str:
"""Why the file is not in the pack, empty once it is."""
return {
ExternalOutcome.FETCHED: "",
ExternalOutcome.NO_URL: "external file without a source_url",
ExternalOutcome.NO_HASH: "external file without a hash, download unverifiable",
ExternalOutcome.OFFLINE: "external file not fetched, the run is offline",
ExternalOutcome.NETWORK_ERROR: f"external download failed: {self.detail}",
ExternalOutcome.MISMATCH: f"external download fails its declared {self.detail}",
}[self.outcome]
def download_external(
file_entry: dict, dest_path: str, offline: bool | None = None
) -> bool:
) -> ExternalFetch:
"""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. 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.
declared value. Nothing is printed: the caller reports the outcome.
"""
url = file_entry.get("source_url")
if not url:
return False
name = file_entry.get("name", url)
return ExternalFetch(ExternalOutcome.NO_URL)
# The strongest field declared, every value it accepts: a stringified
# list or a comma-joined field matched no digest at all.
declared = next(iter(declared_hash_lists(file_entry, ("sha256", "sha1", "md5")).items()), None)
if declared is None:
print(f" WARNING: no hash for {name}, skipping unverifiable download")
return False
return ExternalFetch(ExternalOutcome.NO_HASH)
if run_is_offline(offline):
print(f" WARNING: {name} is external and the run is offline, not fetched")
return False
return ExternalFetch(ExternalOutcome.OFFLINE)
algo, expected = declared[0], set(declared[1])
Path(dest_path).parent.mkdir(parents=True, exist_ok=True)
try:
@@ -85,12 +121,11 @@ def download_external(
)
except (urllib.error.URLError, OSError, http.client.HTTPException,
upstream.UpstreamError, ValueError) as exc:
print(f" WARNING: Failed to download {url}: {exc}")
return False
return ExternalFetch(ExternalOutcome.NETWORK_ERROR, f"{url}: {exc}")
if served is None:
print(f" WARNING: {algo.upper()} mismatch for {name}")
return False
return True
return ExternalFetch(ExternalOutcome.MISMATCH, algo.upper())
return ExternalFetch(ExternalOutcome.FETCHED)
def _fetched_asset(path: str, sha1: str, file_entry: dict, offline: bool) -> str | None:
"""The release asset of a registered path, downloaded if allowed and
@@ -188,7 +223,8 @@ def lookup_hashes(
hashes: list[tuple[str, str]], db: dict, bios_dir: str,
) -> list[HashLookup]:
"""One record per hash: the file the database names, and whether the
repository holds its bytes (at its path, or wherever resolution finds them)."""
repository holds its bytes (at its path, wherever resolution finds them,
or as a release asset). Nothing is downloaded to answer."""
files_db = db.get("files", {})
records: list[HashLookup] = []
for hash_type, hash_val in hashes:
@@ -202,12 +238,11 @@ def lookup_hashes(
path = entry.get("path", "")
in_repo = bool(path) and os.path.exists(path)
if not in_repo:
try:
fe_check = {"name": name, "sha1": sha1, "md5": md5}
local, status = resolve_file(fe_check, db, bios_dir, {})
in_repo = bool(local) and status != "not_found"
except (KeyError, OSError):
pass
fe_check = {"name": name, "sha1": sha1, "md5": md5}
local, status = resolve_file(fe_check, db, bios_dir, {}, offline=True)
in_repo = (bool(local) and status != "not_found") or bool(
release_asset_paths(fe_check, db)
)
records.append(HashLookup(hash_type, hash_val, sha1, md5, name, path, in_repo))
return records
+40 -15
View File
@@ -7743,11 +7743,35 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmp, \
mock.patch("urllib.request.urlopen") as urlopen, \
contextlib.redirect_stdout(io.StringIO()):
ok = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=True)
self.assertFalse(ok)
contextlib.redirect_stdout(io.StringIO()) as out:
fetch = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=True)
self.assertIs(fetch.outcome, packresolve.ExternalOutcome.OFFLINE)
self.assertFalse(fetch.fetched)
self.assertEqual(out.getvalue(), "")
urlopen.assert_not_called()
def test_each_failure_names_its_own_cause(self):
"""Four causes came back as one False, reported as a download failure."""
from core import upstream
from resolve import packfiles as packresolve
outcome = packresolve.ExternalOutcome
with tempfile.TemporaryDirectory() as tmp:
no_hash = packresolve.download_external(
{"name": "ext.bin", "source_url": "https://example.invalid/x"},
f"{tmp}/x", offline=False)
offline = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=True)
with mock.patch("urllib.request.urlopen",
side_effect=urllib.error.URLError("refused")), \
mock.patch.object(upstream, "_sleep", lambda _s: None):
failed = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=False)
self.assertIs(no_hash.outcome, outcome.NO_HASH)
self.assertIs(offline.outcome, outcome.OFFLINE)
self.assertIs(failed.outcome, outcome.NETWORK_ERROR)
self.assertIn("offline", offline.reason)
self.assertIn("hash", no_hash.reason)
self.assertIn("refused", failed.reason)
def test_the_run_switch_is_inherited(self):
from resolve import packfiles as packresolve
@@ -7755,9 +7779,8 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
packresolve.set_offline(True)
try:
with tempfile.TemporaryDirectory() as tmp, \
mock.patch("urllib.request.urlopen") as urlopen, \
contextlib.redirect_stdout(io.StringIO()):
self.assertFalse(packresolve.download_external(self.ENTRY, f"{tmp}/x"))
mock.patch("urllib.request.urlopen") as urlopen:
self.assertFalse(packresolve.download_external(self.ENTRY, f"{tmp}/x").fetched)
urlopen.assert_not_called()
finally:
packresolve.set_offline(saved)
@@ -7768,10 +7791,9 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmp, \
mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": "1"}), \
mock.patch("urllib.request.urlopen") as urlopen, \
contextlib.redirect_stdout(io.StringIO()):
mock.patch("urllib.request.urlopen") as urlopen:
self.assertFalse(
packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=False))
packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=False).fetched)
urlopen.assert_not_called()
def test_a_verified_body_lands_and_a_wrong_one_is_removed(self):
@@ -7781,13 +7803,14 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
target = Path(tmp) / "x"
with mock.patch("urllib.request.urlopen",
return_value=self._response(b"payload")):
self.assertTrue(packresolve.download_external(self.ENTRY, str(target), offline=False))
self.assertTrue(
packresolve.download_external(self.ENTRY, str(target), offline=False).fetched)
self.assertEqual(target.read_bytes(), b"payload")
target.unlink()
with mock.patch("urllib.request.urlopen",
return_value=self._response(b"other")), \
contextlib.redirect_stdout(io.StringIO()):
self.assertFalse(packresolve.download_external(self.ENTRY, str(target), offline=False))
return_value=self._response(b"other")):
fetch = packresolve.download_external(self.ENTRY, str(target), offline=False)
self.assertIs(fetch.outcome, packresolve.ExternalOutcome.MISMATCH)
self.assertFalse(target.exists())
def test_every_accepted_value_of_a_listed_field_verifies(self):
@@ -7801,7 +7824,8 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
mock.patch.object(packresolve.urllib.request, "urlopen",
return_value=self._response(b"payload")):
entry = {**self.ENTRY, "sha1": sha1}
self.assertTrue(packresolve.download_external(entry, f"{tmp}/x", offline=False))
self.assertTrue(
packresolve.download_external(entry, f"{tmp}/x", offline=False).fetched)
def test_a_transient_failure_is_retried_and_no_scratch_remains(self):
"""One 503 failed the external file for the whole build."""
@@ -7814,7 +7838,8 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
with mock.patch("urllib.request.urlopen",
side_effect=[refusal, self._response(b"payload")]), \
mock.patch.object(upstream, "_sleep", lambda _s: None):
self.assertTrue(packresolve.download_external(self.ENTRY, str(target), offline=False))
self.assertTrue(
packresolve.download_external(self.ENTRY, str(target), offline=False).fetched)
self.assertEqual(target.read_bytes(), b"payload")
self.assertEqual(os.listdir(tmp), ["x"])