mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-12-03 06:48:52 -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
@@ -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
|
||||
Reference in new issue
Block a user