fix: retry archives and the app like files

One decision says whether a failed request is asked again and when:
5xx and 429 wait what Retry-After asks, a clock in the past or no certificate
list stops at once. A data archive and the handheld app waited 1 s on a
429 that asked for 30 and gave up where a BIOS file arrived, and the app
took a body cut short of its Content-Length as the file.
This commit is contained in:
Abdessamad Derraz committed 2026-11-21 06:04:39 +01:00
1 parent c41fb9e609
commit 6acdf4b193
9 files changed
+144 -58

No files matched your search

+1 -1
View File
@@ -16,7 +16,7 @@
# and Invoke-WebRequest throws on a cut transfer before the hash is read:
# the site's build rewrites this line there (scripts/sitebootstrap.py).
$mismatchAdvice = "The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that."
$defaultInstallSha256 = "85408a5c448b08de3f1a45ec5f830826f9cd079e1f18973c3cc117b62866c259"
$defaultInstallSha256 = "154d91a0c03bda14317a9ca48b2c3be607ffb255575c3d5ac1cbb42da4c58961"
# The pin above refuses any changed byte: this cap only stops a body that
# cannot be the installer (a sign-in portal's page) before it is hashed.
$maximumInstallerBytes = 8MB
+51 -22
View File
@@ -7316,10 +7316,8 @@ def _offline_only() -> bool:
# --- installer/network.py ----------------------------------------------------
def _read_limited_json(
response: http.client.HTTPResponse, limit: int, label: str, raw: bool = False
) -> object:
"""Read a bounded UTF-8 JSON response, its bytes as they came with raw.
def _read_limited(response: http.client.HTTPResponse, limit: int, label: str) -> bytes:
"""Read a response of limit bytes at most.
A body shorter than its Content-Length is a dropped connection, raised
as one so the caller retries: parsed, the cut read as an invalid file
@@ -7344,6 +7342,14 @@ def _read_limited_json(
raise ValueError(f"{label} exceeds {limit} bytes")
if expected is not None and len(payload) < expected:
raise ConnectionError(f"{label} cut after {len(payload)} of {expected} bytes")
return payload
def _read_limited_json(
response: http.client.HTTPResponse, limit: int, label: str, raw: bool = False
) -> object:
"""Read a bounded UTF-8 JSON response, its bytes as they came with raw."""
payload = _read_limited(response, limit, label)
if raw:
return payload
try:
@@ -7583,21 +7589,21 @@ def _fetch_json(
return _read_limited_json(resp, limit, label, raw=True)
return _read_limited_json(resp, limit, label)
except urllib.error.HTTPError as exc:
if exc.code < 500 and exc.code != 429 or attempt == attempts:
wait = _retry_after_failure(exc, attempt, attempts)
if wait is None:
raise
delay = _retry_delay(attempt, exc.headers.get("Retry-After") if exc.headers else None)
delay = wait
problem = f"HTTP {exc.code}"
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
code, problem = network_words(exc)
# A wrong clock or no certificate list fails every attempt alike.
if (attempt == attempts or code != "network"
or (_stalled(exc) and attempt >= STALLED_ATTEMPTS)):
problem = network_words(exc)[1]
wait = _retry_after_failure(exc, attempt, attempts)
if wait is None or (_stalled(exc) and attempt >= STALLED_ATTEMPTS):
if isinstance(exc, http.client.HTTPException):
raise ConnectionError(f"connection cut: {exc!r}") from exc
# How many were made, for the line that says so.
exc.__dict__["attempts"] = attempt
raise
delay = _retry_delay(attempt, None)
delay = wait
if _stalled(exc):
tries = min(attempts, STALLED_ATTEMPTS)
# Said, or three 30-second attempts read as a frozen program.
@@ -7814,6 +7820,26 @@ def _retry_delay(attempt: int, retry_after: str | None) -> float:
return float(min(2 ** (attempt - 1), 8))
def _server_delay(exc: urllib.error.HTTPError, attempt: int) -> float:
"""Seconds before asking a server that refused again: its Retry-After."""
return _retry_delay(attempt, exc.headers.get("Retry-After") if exc.headers else None)
def _retry_after_failure(exc: BaseException, attempt: int, attempts: int) -> float | None:
"""Seconds before the attempt after exc, None when it is final: the last
attempt, a refusal other than 429, a wrong clock or no certificate list,
which fail every attempt alike."""
if attempt >= attempts:
return None
if isinstance(exc, urllib.error.HTTPError):
if exc.code < 500 and exc.code != 429:
return None
return _server_delay(exc, attempt)
if network_words(exc)[0] != "network":
return None
return _retry_delay(attempt, None)
def _read_capped(path: Path, limit: int) -> bytes | None:
try:
with open(path, "rb") as handle:
@@ -16301,7 +16327,7 @@ def _fetch_file(job: _FileFetch) -> tuple[str, bool, str]:
except urllib.error.HTTPError as exc:
reason = _http_attempt_failure(job, exc, attempt)
delay = _retry_delay(attempt, exc.headers.get("Retry-After") if exc.headers else None)
delay = _server_delay(exc, attempt)
# http.client raises IncompleteRead (an HTTPException, not an
# OSError) when a chunked transfer is cut, as a proxy re-encoding
@@ -16846,10 +16872,14 @@ def _fetch_archive(url: str, directory: Path, progress: Progress | None = None,
if exc.code < 500 and exc.code not in (416, 429):
raise
reason = exc
# A range past an archive that shrank is asked again whole.
delay = (_retry_delay(attempt, None) if exc.code == 416 and attempt < MAX_RETRIES
else _retry_after_failure(exc, attempt, MAX_RETRIES))
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
if keep is None:
Path(handle.name).unlink(missing_ok=True)
reason = exc if isinstance(exc, OSError) else ConnectionError(repr(exc))
delay = _retry_after_failure(exc, attempt, MAX_RETRIES)
except ValueError:
_drop_archive(Path(handle.name), note)
raise
@@ -16859,8 +16889,9 @@ def _fetch_archive(url: str, directory: Path, progress: Progress | None = None,
Path(handle.name).unlink(missing_ok=True)
raise
count.take_back()
if attempt < MAX_RETRIES:
time.sleep(_retry_delay(attempt, None))
if delay is None:
break
time.sleep(delay)
raise reason if reason else OSError("download failed")
@@ -17363,19 +17394,17 @@ def app_archive(members: list[tuple[dict, bytes]]) -> bytes:
def _app_download(url: str, size: int) -> bytes:
"""The bytes at url, tried MAX_RETRIES times, never more than size + 1."""
"""The bytes at url, tried MAX_RETRIES times, refused past size."""
_network_allowed("the RetroBIOS app")
for attempt in range(1, MAX_RETRIES + 1):
try:
with urllib.request.urlopen(url, timeout=60) as resp:
return resp.read(size + 1)
except urllib.error.HTTPError as exc:
if exc.code < 500 and exc.code != 429 or attempt == MAX_RETRIES:
return _read_limited(resp, size, url)
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
delay = _retry_after_failure(exc, attempt, MAX_RETRIES)
if delay is None:
raise
except (urllib.error.URLError, OSError, http.client.HTTPException):
if attempt == MAX_RETRIES:
raise
time.sleep(_retry_delay(attempt, None))
time.sleep(delay)
raise AssertionError("unreachable")
+1 -1
View File
@@ -23,7 +23,7 @@ DEFAULT_INSTALL_URL="https://raw.githubusercontent.com/Abdess/retrobios/main/ins
# curl or wget stop on a cut transfer before the hash is read: the site's
# build rewrites this line there (scripts/sitebootstrap.py).
MISMATCH_ADVICE="The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that."
DEFAULT_INSTALL_SHA256="85408a5c448b08de3f1a45ec5f830826f9cd079e1f18973c3cc117b62866c259"
DEFAULT_INSTALL_SHA256="154d91a0c03bda14317a9ca48b2c3be607ffb255575c3d5ac1cbb42da4c58961"
# The pin above refuses any changed byte: this cap only stops a body that
# cannot be the installer (a sign-in portal's page) before it is hashed.
MAX_INSTALLER_BYTES=8388608
+8 -8
View File
@@ -27,8 +27,8 @@
{
"dest": "roms/ports/retrobios/install.py",
"repo_path": "install.py",
"size": 1450226,
"sha256": "85408a5c448b08de3f1a45ec5f830826f9cd079e1f18973c3cc117b62866c259",
"size": 1451276,
"sha256": "154d91a0c03bda14317a9ca48b2c3be607ffb255575c3d5ac1cbb42da4c58961",
"executable": false
},
{
@@ -71,8 +71,8 @@
"muos": {
"archive": {
"dest": "ARCHIVE/RetroBIOS.muxapp",
"size": 1503851,
"sha256": "b094342bb630abe551ea6858f44cc0db586642878f03ec1ff107757a18a9b442"
"size": 1504901,
"sha256": "ddce5206da1834e94e3481a3d677a8329e46e7626e239e6d4d27a0ad9bb06745"
},
"members": [
{
@@ -92,8 +92,8 @@
{
"name": "RetroBIOS/install.py",
"repo_path": "install.py",
"size": 1450226,
"sha256": "85408a5c448b08de3f1a45ec5f830826f9cd079e1f18973c3cc117b62866c259",
"size": 1451276,
"sha256": "154d91a0c03bda14317a9ca48b2c3be607ffb255575c3d5ac1cbb42da4c58961",
"executable": false
},
{
@@ -166,8 +166,8 @@
{
"dest": ".config/modules/retrobios/install.py",
"repo_path": "install.py",
"size": 1450226,
"sha256": "85408a5c448b08de3f1a45ec5f830826f9cd079e1f18973c3cc117b62866c259",
"size": 1451276,
"sha256": "154d91a0c03bda14317a9ca48b2c3be607ffb255575c3d5ac1cbb42da4c58961",
"executable": false
},
{
+8 -3
View File
@@ -30,7 +30,7 @@ from installer.host_fs import (
)
from installer.local_check import _read_digests
from installer.manifest import OTHER_SYSTEMS
from installer.network import _retry_delay
from installer.network import _retry_after_failure, _retry_delay
from installer.offline import LOCAL, _Offline, _network_allowed, _offline_only
from installer.outcome import OfflineReason
from installer.paths import _destination_path
@@ -168,10 +168,14 @@ def _fetch_archive(url: str, directory: Path, progress: Progress | None = None,
if exc.code < 500 and exc.code not in (416, 429):
raise
reason = exc
# A range past an archive that shrank is asked again whole.
delay = (_retry_delay(attempt, None) if exc.code == 416 and attempt < MAX_RETRIES
else _retry_after_failure(exc, attempt, MAX_RETRIES))
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
if keep is None:
Path(handle.name).unlink(missing_ok=True)
reason = exc if isinstance(exc, OSError) else ConnectionError(repr(exc))
delay = _retry_after_failure(exc, attempt, MAX_RETRIES)
except ValueError:
_drop_archive(Path(handle.name), note)
raise
@@ -181,8 +185,9 @@ def _fetch_archive(url: str, directory: Path, progress: Progress | None = None,
Path(handle.name).unlink(missing_ok=True)
raise
count.take_back()
if attempt < MAX_RETRIES:
time.sleep(_retry_delay(attempt, None))
if delay is None:
break
time.sleep(delay)
raise reason if reason else OSError("download failed")
+2 -2
View File
@@ -36,7 +36,7 @@ from installer.host_fs import (
)
from installer.invocation import offline_requested
from installer.local_check import _digest_file, _digest_handle, expected_hashes, unreachable_words
from installer.network import _retry_delay, network_words
from installer.network import _retry_delay, _server_delay, network_words
from installer.offline import LOCAL, offline_words
from installer.outcome import HttpReason, NetworkReason, OfflineReason, _transfer_failure
from installer.pack_source import NOT_IN_PACK, _extract_from_pack
@@ -217,7 +217,7 @@ def _fetch_file(job: _FileFetch) -> tuple[str, bool, str]:
except urllib.error.HTTPError as exc:
reason = _http_attempt_failure(job, exc, attempt)
delay = _retry_delay(attempt, exc.headers.get("Retry-After") if exc.headers else None)
delay = _server_delay(exc, attempt)
# http.client raises IncompleteRead (an HTTPException, not an
# OSError) when a chunked transfer is cut, as a proxy re-encoding
+7 -9
View File
@@ -22,7 +22,7 @@ from installer.console import _ask
from installer.events import EVENTS
from installer.host_fs import NOT_WRITABLE, _write_refused
from installer.local_check import _sha256_file
from installer.network import _fetch_json, _retry_delay, network_words
from installer.network import _fetch_json, _read_limited, _retry_after_failure, network_words
from installer.offline import LOCAL, _Offline, _network_allowed
from installer.outcome import _transfer_failure
from installer.paths import _destination_path, _safe_relative_path
@@ -205,19 +205,17 @@ def app_archive(members: list[tuple[dict, bytes]]) -> bytes:
def _app_download(url: str, size: int) -> bytes:
"""The bytes at url, tried MAX_RETRIES times, never more than size + 1."""
"""The bytes at url, tried MAX_RETRIES times, refused past size."""
_network_allowed("the RetroBIOS app")
for attempt in range(1, MAX_RETRIES + 1):
try:
with urllib.request.urlopen(url, timeout=60) as resp:
return resp.read(size + 1)
except urllib.error.HTTPError as exc:
if exc.code < 500 and exc.code != 429 or attempt == MAX_RETRIES:
return _read_limited(resp, size, url)
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
delay = _retry_after_failure(exc, attempt, MAX_RETRIES)
if delay is None:
raise
except (urllib.error.URLError, OSError, http.client.HTTPException):
if attempt == MAX_RETRIES:
raise
time.sleep(_retry_delay(attempt, None))
time.sleep(delay)
raise AssertionError("unreachable")
+37 -11
View File
@@ -36,10 +36,8 @@ from installer.remote import (
)
def _read_limited_json(
response: http.client.HTTPResponse, limit: int, label: str, raw: bool = False
) -> object:
"""Read a bounded UTF-8 JSON response, its bytes as they came with raw.
def _read_limited(response: http.client.HTTPResponse, limit: int, label: str) -> bytes:
"""Read a response of limit bytes at most.
A body shorter than its Content-Length is a dropped connection, raised
as one so the caller retries: parsed, the cut read as an invalid file
@@ -64,6 +62,14 @@ def _read_limited_json(
raise ValueError(f"{label} exceeds {limit} bytes")
if expected is not None and len(payload) < expected:
raise ConnectionError(f"{label} cut after {len(payload)} of {expected} bytes")
return payload
def _read_limited_json(
response: http.client.HTTPResponse, limit: int, label: str, raw: bool = False
) -> object:
"""Read a bounded UTF-8 JSON response, its bytes as they came with raw."""
payload = _read_limited(response, limit, label)
if raw:
return payload
try:
@@ -303,21 +309,21 @@ def _fetch_json(
return _read_limited_json(resp, limit, label, raw=True)
return _read_limited_json(resp, limit, label)
except urllib.error.HTTPError as exc:
if exc.code < 500 and exc.code != 429 or attempt == attempts:
wait = _retry_after_failure(exc, attempt, attempts)
if wait is None:
raise
delay = _retry_delay(attempt, exc.headers.get("Retry-After") if exc.headers else None)
delay = wait
problem = f"HTTP {exc.code}"
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
code, problem = network_words(exc)
# A wrong clock or no certificate list fails every attempt alike.
if (attempt == attempts or code != "network"
or (_stalled(exc) and attempt >= STALLED_ATTEMPTS)):
problem = network_words(exc)[1]
wait = _retry_after_failure(exc, attempt, attempts)
if wait is None or (_stalled(exc) and attempt >= STALLED_ATTEMPTS):
if isinstance(exc, http.client.HTTPException):
raise ConnectionError(f"connection cut: {exc!r}") from exc
# How many were made, for the line that says so.
exc.__dict__["attempts"] = attempt
raise
delay = _retry_delay(attempt, None)
delay = wait
if _stalled(exc):
tries = min(attempts, STALLED_ATTEMPTS)
# Said, or three 30-second attempts read as a frozen program.
@@ -534,6 +540,26 @@ def _retry_delay(attempt: int, retry_after: str | None) -> float:
return float(min(2 ** (attempt - 1), 8))
def _server_delay(exc: urllib.error.HTTPError, attempt: int) -> float:
"""Seconds before asking a server that refused again: its Retry-After."""
return _retry_delay(attempt, exc.headers.get("Retry-After") if exc.headers else None)
def _retry_after_failure(exc: BaseException, attempt: int, attempts: int) -> float | None:
"""Seconds before the attempt after exc, None when it is final: the last
attempt, a refusal other than 429, a wrong clock or no certificate list,
which fail every attempt alike."""
if attempt >= attempts:
return None
if isinstance(exc, urllib.error.HTTPError):
if exc.code < 500 and exc.code != 429:
return None
return _server_delay(exc, attempt)
if network_words(exc)[0] != "network":
return None
return _retry_delay(attempt, None)
def _read_capped(path: Path, limit: int) -> bytes | None:
try:
with open(path, "rb") as handle:
+29 -1
View File
@@ -23,6 +23,7 @@ import sys
import tempfile
import threading
import unittest
import urllib.error
from pathlib import Path
from unittest import mock
@@ -39,6 +40,7 @@ class _RangeHandler(http.server.BaseHTTPRequestHandler):
ranges: list[str] = []
fail_first: list[int] = []
retry_after = "0"
def log_message(self, *args) -> None:
pass
@@ -47,7 +49,7 @@ class _RangeHandler(http.server.BaseHTTPRequestHandler):
if self.fail_first:
code = self.fail_first.pop(0)
self.send_response(code)
self.send_header("Retry-After", "0")
self.send_header("Retry-After", self.retry_after)
self.end_headers()
return
header = self.headers.get("Range")
@@ -69,6 +71,7 @@ class _Server:
def __enter__(self):
_RangeHandler.ranges = []
_RangeHandler.fail_first = []
_RangeHandler.retry_after = "0"
self.httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _RangeHandler)
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
port = self.httpd.server_address[1]
@@ -293,6 +296,31 @@ class RetriesWait(unittest.TestCase):
dest, ok, _ = install._download_one(dict(ENTRY), Path(tmp))
self.assertTrue(ok)
def test_an_archive_and_the_app_wait_what_the_server_asks(self):
# Both waited 1 s on a 429 that asked for 7, and gave up in 3 s
# where a BIOS file waited and arrived.
with _Server() as server, tempfile.TemporaryDirectory() as tmp, \
mock.patch.object(install.time, "sleep") as slept:
port = server.httpd.server_address[1]
url = f"http://127.0.0.1:{port}/a.zip"
_RangeHandler.retry_after = "7"
_RangeHandler.fail_first = [429]
self.assertEqual(install._fetch_archive(url, Path(tmp)).read_bytes(), PAYLOAD)
_RangeHandler.fail_first = [429]
self.assertEqual(install._app_download(url, len(PAYLOAD)), PAYLOAD)
self.assertEqual([c.args for c in slept.call_args_list], [(7.0,), (7.0,)])
def test_a_failure_no_attempt_changes_is_final(self):
import ssl
no_list = urllib.error.URLError(ssl.SSLCertVerificationError("unable to get issuer"))
refused = urllib.error.HTTPError("u", 404, "Not Found", {}, None)
with mock.patch.object(install, "_ca_bundle_found", return_value=False):
self.assertIsNone(install._retry_after_failure(no_list, 1, 3))
self.assertIsNone(install._retry_after_failure(refused, 1, 3))
self.assertEqual(install._retry_after_failure(ConnectionResetError(), 1, 3), 1.0)
self.assertIsNone(install._retry_after_failure(ConnectionResetError(), 3, 3))
def test_the_delay_doubles_and_follows_retry_after(self):
self.assertEqual([install._retry_delay(n, None) for n in (1, 2, 3, 4, 5)],
[1.0, 2.0, 4.0, 8.0, 8.0])