mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-12-02 14:28:54 -06:00
fix: raise download failures as DownloadError
This commit is contained in:
1 parent
1ab22ec956
commit
c1ff070863
6 files changed
+190
-62
No files matched your search
+4
-1
@@ -34,6 +34,7 @@ from release.latest import DEFAULT_API, checked_url, get_latest_release
|
||||
from release.packfetch import fetch_checksums, fetch_pack, make_staging
|
||||
from release.packgroups import find_pack, list_platforms
|
||||
from release.packinfo import exit_without_pack, show_info
|
||||
from release.progressbar import ProgressBar
|
||||
|
||||
FETCH_ERRORS = (
|
||||
urllib.error.URLError, OSError, http.client.HTTPException, UpstreamError,
|
||||
@@ -107,7 +108,9 @@ def main() -> None:
|
||||
|
||||
staging = make_staging(dest)
|
||||
try:
|
||||
archives = fetch_pack(pack, staging, fetch_checksums(release), print)
|
||||
archives = fetch_pack(
|
||||
pack, staging, fetch_checksums(release), print, ProgressBar()
|
||||
)
|
||||
print(f"Extracting to {dest}/...")
|
||||
for archive in archives:
|
||||
safe_extract_zip(str(archive), str(dest))
|
||||
|
||||
@@ -6,13 +6,13 @@ import shutil
|
||||
import tempfile
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import TYPE_CHECKING, Protocol
|
||||
|
||||
from core.hashing import compute_hashes, parse_sha256sums
|
||||
from core.upstream import open_retrying
|
||||
from release.downloaderror import DownloadError
|
||||
from release.latest import checked_url
|
||||
from release.transfer import download_file
|
||||
from release.transfer import TRANSFER_ERRORS, download_file
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
@@ -25,6 +25,16 @@ MAX_CHECKSUMS_BYTES = 1 << 20
|
||||
CHUNK = 1 << 20
|
||||
|
||||
|
||||
class Meter(Protocol):
|
||||
"""What draws a part's progress: the command's own presentation."""
|
||||
|
||||
def start(self, label: str) -> None: ...
|
||||
|
||||
def update(self, done: int, total: int) -> None: ...
|
||||
|
||||
def finish(self) -> None: ...
|
||||
|
||||
|
||||
def fetch_checksums(release: dict) -> dict[str, str]:
|
||||
"""Read the published SHA-256 of each pack, keyed by archive name."""
|
||||
for asset in release.get("assets", []):
|
||||
@@ -34,9 +44,11 @@ def fetch_checksums(release: dict) -> dict[str, str]:
|
||||
req = urllib.request.Request(
|
||||
url, headers={"User-Agent": "retrobios-downloader/1.0"}
|
||||
)
|
||||
body = open_retrying(
|
||||
req, lambda resp: resp.read(MAX_CHECKSUMS_BYTES), 60
|
||||
).decode("utf-8", "replace")
|
||||
try:
|
||||
raw = open_retrying(req, lambda resp: resp.read(MAX_CHECKSUMS_BYTES), 60)
|
||||
except TRANSFER_ERRORS as exc:
|
||||
raise DownloadError(f"Error: reading {CHECKSUMS_ASSET} failed: {exc}") from exc
|
||||
body = raw.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.
|
||||
@@ -85,12 +97,30 @@ def _check(archive: Path, checksums: dict[str, str], say: Callable[[str], None])
|
||||
)
|
||||
|
||||
|
||||
def _download_part(part: dict, target: Path, label: str, meter: Meter | None) -> None:
|
||||
"""Download one part, its progress drawn by *meter* when there is one."""
|
||||
url, size = part["browser_download_url"], part.get("size", 0)
|
||||
if meter is None:
|
||||
download_file(url, target, size)
|
||||
return
|
||||
meter.start(label)
|
||||
try:
|
||||
download_file(url, target, size, meter.update)
|
||||
finally:
|
||||
meter.finish()
|
||||
|
||||
|
||||
def fetch_pack(
|
||||
pack: Pack, staging: Path, checksums: dict[str, str], say: Callable[[str], None]
|
||||
pack: Pack,
|
||||
staging: Path,
|
||||
checksums: dict[str, str],
|
||||
say: Callable[[str], None],
|
||||
meter: Meter | None = None,
|
||||
) -> list[Path]:
|
||||
"""Download a pack and return the archives to extract, each one checked.
|
||||
|
||||
Each progress line goes to *say*, and a failure raises DownloadError.
|
||||
Each progress line goes to *say*, each part's byte count to *meter*, and
|
||||
a failure raises DownloadError.
|
||||
"""
|
||||
if len(pack.parts) != pack.expected_parts:
|
||||
raise DownloadError(
|
||||
@@ -103,7 +133,7 @@ def fetch_pack(
|
||||
label = f"part {index}/{len(pack.parts)} " if len(pack.parts) > 1 else ""
|
||||
target = staging / part["name"]
|
||||
say(f"Downloading {part['name']} ({part.get('size', 0):,} bytes)...")
|
||||
download_file(part["browser_download_url"], target, part.get("size", 0), label)
|
||||
_download_part(part, target, label, meter)
|
||||
volumes.append(target)
|
||||
|
||||
if pack.joined:
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""A download's progress, redrawn as a bar on a terminal or one line in a log."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
from core.sizes import size_text
|
||||
|
||||
|
||||
class ProgressBar:
|
||||
"""Draws each part's progress on standard output.
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.live = sys.stdout.isatty() and os.environ.get("TERM") != "dumb"
|
||||
self.label = ""
|
||||
self.done = 0
|
||||
self.shown = -1
|
||||
|
||||
def start(self, label: str) -> None:
|
||||
"""Begin the bar of one part, named *label*."""
|
||||
self.label = label
|
||||
self.done = 0
|
||||
self.shown = -1
|
||||
|
||||
def update(self, done: int, total: int) -> None:
|
||||
"""Count *done* bytes and redraw the bar when the percentage moves."""
|
||||
self.done = done
|
||||
if total <= 0 or not self.live:
|
||||
return
|
||||
pct = done * 100 // total
|
||||
if pct == self.shown:
|
||||
return
|
||||
self.shown = pct
|
||||
columns = shutil.get_terminal_size((80, 24)).columns
|
||||
line = progress_line(self.label, done, total, columns)
|
||||
print(f"\r\033[K{line}", end="", flush=True)
|
||||
|
||||
def finish(self) -> None:
|
||||
"""End the bar's line, or write the one line a log gets."""
|
||||
if self.live:
|
||||
print()
|
||||
else:
|
||||
print(f" {self.label}{self.done:,} bytes")
|
||||
|
||||
|
||||
def progress_line(label: str, done: int, total: int, columns: int) -> str:
|
||||
"""One physical line shorter than the terminal: a wrapped line leaves a
|
||||
copy of itself on every redraw, since \\r goes back one row only. The
|
||||
bar shrinks first, then goes."""
|
||||
pct = done * 100 // total
|
||||
figures = f" {pct}% ({size_text(done)}/{size_text(total)})"
|
||||
room = min(50, columns - 1 - len(f" {label}[]") - len(figures))
|
||||
if room < 10:
|
||||
return f" {label}{figures.strip()}"[: columns - 1]
|
||||
filled = room * pct // 100
|
||||
return f" {label}[{'=' * filled}{' ' * (room - filled)}]{figures}"
|
||||
+30
-44
@@ -1,74 +1,60 @@
|
||||
"""One release asset downloaded to disk, with its progress line."""
|
||||
"""One release asset downloaded to disk, its progress handed to a callback."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import http.client
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from core.sizes import size_text
|
||||
from core.upstream import open_retrying
|
||||
from core.upstream import UpstreamError, open_retrying
|
||||
from release.downloaderror import DownloadError
|
||||
from release.latest import checked_url
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import http.client
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
TRANSFER_ERRORS = (urllib.error.URLError, http.client.HTTPException, OSError, UpstreamError)
|
||||
|
||||
|
||||
def download_file(
|
||||
url: str, dest: Path, expected_size: int = 0, label: str = ""
|
||||
) -> None:
|
||||
"""Download a file with progress indication.
|
||||
url: str,
|
||||
dest: Path,
|
||||
expected_size: int = 0,
|
||||
progress: Callable[[int, int], None] | None = None,
|
||||
) -> int:
|
||||
"""Write the asset at *url* to *dest* and return its byte count.
|
||||
|
||||
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.
|
||||
*progress* receives the bytes written so far and the announced total
|
||||
after each block. 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. A transfer that fails or
|
||||
ends short of *expected_size* raises DownloadError.
|
||||
"""
|
||||
url = checked_url(url, "asset URL")
|
||||
req = urllib.request.Request(
|
||||
url, headers={"User-Agent": "retrobios-downloader/1.0"}
|
||||
)
|
||||
|
||||
# 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"
|
||||
|
||||
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 chunk := resp.read(65536):
|
||||
f.write(chunk)
|
||||
downloaded += len(chunk)
|
||||
if total > 0 and live:
|
||||
pct = downloaded * 100 // total
|
||||
if pct != shown:
|
||||
shown = pct
|
||||
columns = shutil.get_terminal_size((80, 24)).columns
|
||||
line = progress_line(label, downloaded, total, columns)
|
||||
print(f"\r\033[K{line}", end="", flush=True)
|
||||
if progress is not None:
|
||||
progress(downloaded, total)
|
||||
return downloaded
|
||||
|
||||
downloaded = open_retrying(req, save, 300)
|
||||
if live:
|
||||
print()
|
||||
else:
|
||||
print(f" {label}{downloaded:,} bytes")
|
||||
try:
|
||||
downloaded = open_retrying(req, save, 300)
|
||||
except TRANSFER_ERRORS as exc:
|
||||
raise DownloadError(f"Error: downloading {dest.name} failed: {exc}") from exc
|
||||
if expected_size and downloaded != expected_size:
|
||||
raise ValueError(f"downloaded {downloaded} bytes, expected {expected_size}")
|
||||
|
||||
|
||||
def progress_line(label: str, done: int, total: int, columns: int) -> str:
|
||||
"""One physical line shorter than the terminal: a wrapped line leaves a
|
||||
copy of itself on every redraw, since \\r goes back one row only. The
|
||||
bar shrinks first, then goes."""
|
||||
pct = done * 100 // total
|
||||
figures = f" {pct}% ({size_text(done)}/{size_text(total)})"
|
||||
room = min(50, columns - 1 - len(f" {label}[]") - len(figures))
|
||||
if room < 10:
|
||||
return f" {label}{figures.strip()}"[: columns - 1]
|
||||
filled = room * pct // 100
|
||||
return f" {label}[{'=' * filled}{' ' * (room - filled)}]{figures}"
|
||||
raise DownloadError(
|
||||
f"Error: downloaded {downloaded:,} bytes of {dest.name}, "
|
||||
f"expected {expected_size:,}."
|
||||
)
|
||||
return downloaded
|
||||
+1
-1
@@ -149,7 +149,7 @@ COMMANDS = {
|
||||
),
|
||||
"download.py": (
|
||||
"release/latest.py", "release/packgroups.py", "release/transfer.py", "release/packfetch.py",
|
||||
"release/packinfo.py", "release/downloaderror.py",
|
||||
"release/packinfo.py", "release/downloaderror.py", "release/progressbar.py",
|
||||
),
|
||||
"cleanup_disk.py": ("devtools/diskcleanup.py",),
|
||||
"migrate.py": ("devtools/biosclassify.py", "devtools/biosmigrate.py"),
|
||||
|
||||
+55
-8
@@ -31,7 +31,7 @@ from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from packs import parts as packs_parts
|
||||
from release import latest, packfetch, packgroups, packinfo, transfer
|
||||
from release import latest, packfetch, packgroups, packinfo, progressbar, transfer
|
||||
from release.downloaderror import DownloadError
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
@@ -250,14 +250,14 @@ class TestProgressLineWidth(unittest.TestCase):
|
||||
for columns in (20, 40, 80, 120, 200):
|
||||
for done in (0, 1_000_000_000, 2_000_000_000):
|
||||
with self.subTest(columns=columns, done=done):
|
||||
line = transfer.progress_line("part 1/2 ", done, 2_000_000_000, columns)
|
||||
line = progressbar.progress_line("part 1/2 ", done, 2_000_000_000, columns)
|
||||
self.assertLess(len(line), columns)
|
||||
self.assertIn("%", line)
|
||||
|
||||
def test_the_figures_read_like_the_site(self):
|
||||
"""The bar counted decimal megabytes (8,127 MB) where --info and the
|
||||
site gave the same pack as 7.6 GB."""
|
||||
line = transfer.progress_line("", 1024**3, 8_127_352_876, 200)
|
||||
line = progressbar.progress_line("", 1024**3, 8_127_352_876, 200)
|
||||
self.assertTrue(line.endswith(" 13% (1.0 GB/7.6 GB)"), line)
|
||||
|
||||
|
||||
@@ -544,10 +544,12 @@ class TestDownloadLibrary(DownloaderCase):
|
||||
assert pack is not None
|
||||
lines: list[str] = []
|
||||
staging = packfetch.make_staging(self.tmpdir)
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out):
|
||||
archives = packfetch.fetch_pack(
|
||||
pack, staging, packfetch.fetch_checksums(release), lines.append
|
||||
)
|
||||
self.assertEqual(out.getvalue(), "")
|
||||
return archives, lines
|
||||
|
||||
def test_progress_lines_go_to_the_callback(self):
|
||||
@@ -779,10 +781,12 @@ class AProgressBarOnlyOnATerminal(unittest.TestCase):
|
||||
mock.patch.object(transfer.urllib.request, "urlopen",
|
||||
lambda *a, **k: Body(b"x" * 200_000)), \
|
||||
contextlib.redirect_stdout(out):
|
||||
bar = progressbar.ProgressBar()
|
||||
bar.start("a.zip ")
|
||||
transfer.download_file("https://example.com/a.zip",
|
||||
_Path(directory) / "a.zip", 200_000, "a.zip ")
|
||||
self.assertNotIn("\r", out.getvalue())
|
||||
self.assertEqual(out.getvalue().count("\n"), 1)
|
||||
_Path(directory) / "a.zip", 200_000, bar.update)
|
||||
bar.finish()
|
||||
self.assertEqual(out.getvalue(), " a.zip 200,000 bytes\n")
|
||||
|
||||
def test_a_cut_stream_is_fetched_again_from_the_start(self):
|
||||
"""One reset midway through a 2 GiB part failed the whole download."""
|
||||
@@ -810,11 +814,54 @@ class AProgressBarOnlyOnATerminal(unittest.TestCase):
|
||||
mock.patch.object(upstream, "_sleep", lambda _s: None), \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
target = Path(directory) / "a.zip"
|
||||
transfer.download_file("https://example.com/a.zip", target, 6, "a.zip ")
|
||||
transfer.download_file("https://example.com/a.zip", target, 6)
|
||||
self.assertEqual(target.read_bytes(), b"packed")
|
||||
self.assertEqual(answers, [])
|
||||
|
||||
|
||||
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
|
||||
traceback. A transport failure after the retries escaped the same way."""
|
||||
|
||||
class Body(io.BytesIO):
|
||||
headers = {"Content-Length": "10"}
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
def test_a_short_stream_raises_and_prints_nothing(self):
|
||||
out = io.StringIO()
|
||||
with tempfile.TemporaryDirectory() as directory, \
|
||||
mock.patch.object(transfer.urllib.request, "urlopen",
|
||||
lambda *a, **k: self.Body(b"x" * 10)), \
|
||||
contextlib.redirect_stdout(out), \
|
||||
self.assertRaises(DownloadError) as raised:
|
||||
transfer.download_file("https://example.com/a.zip", Path(directory) / "a.zip", 20)
|
||||
self.assertEqual(out.getvalue(), "")
|
||||
self.assertEqual(
|
||||
str(raised.exception), "Error: downloaded 10 bytes of a.zip, expected 20."
|
||||
)
|
||||
|
||||
def test_a_transport_failure_raises(self):
|
||||
from core import upstream
|
||||
|
||||
def refuse(*_a, **_k):
|
||||
raise ConnectionResetError("reset by peer")
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory, \
|
||||
mock.patch.object(transfer.urllib.request, "urlopen", refuse), \
|
||||
mock.patch.object(upstream, "_sleep", lambda _s: None), \
|
||||
self.assertRaises(DownloadError) as raised:
|
||||
transfer.download_file("https://example.com/a.zip", Path(directory) / "a.zip", 20)
|
||||
self.assertEqual(
|
||||
str(raised.exception), "Error: downloading a.zip failed: reset by peer"
|
||||
)
|
||||
|
||||
|
||||
class TheShellDownloaderSendsTheToken(unittest.TestCase):
|
||||
"""download.py sent GITHUB_TOKEN to the API and download.sh did not, so
|
||||
past the anonymous quota the shell twin failed with 403 where the Python
|
||||
|
||||
Reference in new issue
Block a user