fix(downloader): outlast network outages and harden segment merges

Outage-only retry budget, fail fast on a full disk, rnet read_timeout from config, fixed-size shared range parts, Windows-safe segment deletes, merge benchmark.
This commit is contained in:
imSp4rky
2026-11-23 13:43:38 -07:00
parent 138782f38b
commit 91fbe67fa6
14 changed files with 708 additions and 55 deletions
+6 -5
View File
@@ -156,11 +156,12 @@ the next segment it needs and appends every segment that is ready in order, then
segment file. With [`decrypt_segments`](drm.md#decrypt_segments) also on, each segment is
appended after its decryption completes, never before.
This option is off by default because it disables resume, and because its cost during the
download is not measured. The append reads each segment straight after a worker wrote it, so
the read usually comes from the page cache. On a hard disk, the append to one file while the
workers write many segment files can still make the head seek. If a download gets slower with
the option on, turn it off.
This option is off by default because it disables resume. In a measurement of a 3 GiB track in
1500 segments with 16 workers, on an SSD and a loopback server, the merge during the download took
0.9 s more than the merge after it on Linux and 1.1 s less on Windows. With each connection limited
to 8 MiB/s, it took 2.2 s less on Linux and 8.0 s less on Windows. On a hard disk, the append to one
file while the workers write many segment files can make the head seek. If a download gets slower
with the option on, turn it off.
This applies to video and audio tracks from DASH, ISM, and HLS. An HLS track qualifies
only when every segment shares one init segment and one `EXT-X-KEY`, with no
+1 -1
View File
@@ -12,7 +12,7 @@ TLS-fingerprinting and HTTP client settings for the rnet-based HTTP session.
| `http1_only` | bool | *(unset)* | Force HTTP/1.1. |
| `http2_only` | bool | *(unset)* | Force HTTP/2. |
| `connect_timeout` | int | `10` | Connect timeout in seconds. |
| `read_timeout` | int | `30` | Read timeout in seconds (max gap between response chunks). |
| `read_timeout` | int | `30` | Read timeout in seconds (max gap between response chunks). Applies to every request of an rnet session, segment downloads included. |
| `timeout` | int | *(unset)* | Total request timeout in seconds. |
| `allow_redirects` | bool | *(unset)* | Follow redirects automatically (rnet client default when unset). |
| `pool_idle_timeout` | int | `55` | Seconds an idle pooled connection is kept (default stays under typical ~60s CDN idle kills). |
+38
View File
@@ -47,6 +47,7 @@ import fault_server # local sibling (scripts/): fault-injection server + payloa
from rich.console import Console
from rich.table import Table
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.downloaders.requests import requests as download_batch
@@ -57,6 +58,7 @@ dl_mod = importlib.import_module("unshackle.core.downloaders.requests")
MIB = 1024 * 1024
TAIL_FRACTION = 0.25 # last quarter of segments (by completion order)
TAIL_SLOW_KIB = 256 # crawl rate forced onto --fault-tail-slow segments
SLOW_CONN_KIB = 2048
console = Console()
@@ -76,6 +78,7 @@ class SegmentServer(socketserver.ThreadingTCPServer):
self.faults = faults
self.total_segments = total_segments
self.attempts: dict[int, int] = {} # per-segment GET count, drives first-attempt faults
self.connections = 0
self.lock = threading.Lock()
self.stall_event = threading.Event() # set at teardown to release stalled handlers
super().__init__(("127.0.0.1", 0), SegmentHandler)
@@ -83,6 +86,7 @@ class SegmentServer(socketserver.ThreadingTCPServer):
def reset(self) -> None:
with self.lock:
self.attempts.clear()
self.connections = 0
def handle_error(self, request: Any, client_address: Any) -> None: # silence expected fault noise
pass
@@ -94,6 +98,13 @@ class SegmentHandler(http.server.BaseHTTPRequestHandler):
def log_message(self, *_: Any) -> None: # silence per-request logging
pass
def setup(self) -> None:
super().setup()
server: SegmentServer = self.server # type: ignore[assignment]
with server.lock:
server.connections += 1
self.slow_conn = server.connections <= server.faults["slow_conn"]
def _parse_range(self, total: int) -> Optional[tuple[int, int]]:
header = self.headers.get("Range")
if not header or not header.startswith("bytes="):
@@ -137,6 +148,8 @@ class SegmentHandler(http.server.BaseHTTPRequestHandler):
# first attempt only: models a bad CDN connection, so a hedge racer gets full speed
if f["tail_slow_once"] and attempt == 1 and idx >= server.total_segments - f["tail_slow_once"]:
rate = TAIL_SLOW_KIB
if self.slow_conn:
rate = SLOW_CONN_KIB
self._serve(rate=rate)
def _serve(self, rate: int = 0, stall: bool = False, reset: bool = False) -> None:
@@ -587,6 +600,19 @@ def run_fault_mode(
show_default=True,
help=f"Last N segments throttled to {TAIL_SLOW_KIB} KiB/s on attempt 1 only; a hedge/retry runs full speed.",
)
@click.option(
"--fault-slow-conn",
default=0,
show_default=True,
help=f"First N accepted connections are throttled to {SLOW_CONN_KIB} KiB/s for their whole life.",
)
@click.option(
"--part-size-mib",
type=int,
default=0,
show_default=True,
help="Bench-only: override RANGE_PARALLEL_PART_SIZE (MiB); a very large value gives one part per worker.",
)
@click.option(
"--fast-timeouts",
is_flag=True,
@@ -621,6 +647,8 @@ def main(
fault_503: int,
fault_tail_slow: int,
fault_tail_slow_once: int,
fault_slow_conn: int,
part_size_mib: int,
fast_timeouts: bool,
urls_file: Optional[str],
impersonate: Optional[str],
@@ -638,10 +666,12 @@ def main(
"http503": fault_503,
"tail_slow": fault_tail_slow,
"tail_slow_once": fault_tail_slow_once,
"slow_conn": fault_slow_conn,
}
server: Optional[SegmentServer] = None
session: Optional[Any] = None
saved: dict[str, Any] = {}
saved_network: Optional[dict] = None
total = segments
expected_bytes: Optional[bytes] = None # synthetic reference buffer; None in real-URL mode
@@ -650,9 +680,15 @@ def main(
saved = {k: getattr(dl_mod, k) for k in fast}
for k, v in fast.items():
setattr(dl_mod, k, v)
saved_network = config.network
config.network = {**config.network, "read_timeout": fast["READ_TIMEOUT"]}
# --procs children are spawned fresh and would otherwise keep the real timeouts
os.environ["UNSHACKLE_DL_TIMING_OVERRIDES"] = ",".join(f"{k}={v}" for k, v in fast.items())
if part_size_mib and hasattr(dl_mod, "RANGE_PARALLEL_PART_SIZE"):
saved["RANGE_PARALLEL_PART_SIZE"] = dl_mod.RANGE_PARALLEL_PART_SIZE
dl_mod.RANGE_PARALLEL_PART_SIZE = part_size_mib * MIB
if no_read1:
if hasattr(dl_mod, "RACER_READ1"):
saved["RACER_READ1"] = dl_mod.RACER_READ1
@@ -716,6 +752,8 @@ def main(
server.shutdown()
for k, v in saved.items():
setattr(dl_mod, k, v)
if saved_network is not None:
config.network = saved_network
os.environ.pop("UNSHACKLE_DL_TIMING_OVERRIDES", None)
+46
View File
@@ -138,3 +138,49 @@ def test_cleanup_never_climbs_past_the_segment_store(tmp_path: Path, monkeypatch
assert keep.exists(), "cleanup deleted an unrelated file in the download directory"
assert library.exists()
assert not (library / "temp" / "task_x" / "Audio_1.mp4_segments").exists(), "the segment store was left behind"
@pytest.fixture
def ffmpeg_ok(monkeypatch: pytest.MonkeyPatch) -> list[dict]:
"""Patch in an ffmpeg that writes b"merged" and succeeds; gives the kwargs of each call."""
calls: list[dict] = []
def fake_run(args, **kwargs):
calls.append(kwargs)
Path(args[-1]).write_bytes(b"merged")
return subprocess.CompletedProcess(args, 0, "", "")
monkeypatch.setattr("unshackle.core.manifests.hls.binaries.FFMPEG", Path("ffmpeg"))
monkeypatch.setattr("unshackle.core.manifests.hls.subprocess.run", fake_run)
return calls
def test_segment_delete_error_after_ffmpeg_success_keeps_the_output(
tmp_path: Path, segments: list[Path], ffmpeg_ok: list[dict], monkeypatch: pytest.MonkeyPatch
) -> None:
real_unlink = Path.unlink
def locked_unlink(self, *args, **kwargs):
if self == segments[1]:
raise PermissionError(13, "The process cannot access the file", str(self))
return real_unlink(self, *args, **kwargs)
monkeypatch.setattr(Path, "unlink", locked_unlink)
save_path = tmp_path / "out.mp4"
size = HLS.merge_segments(segments=segments, save_path=save_path)
assert size == len(b"merged")
assert save_path.read_bytes() == b"merged"
def test_ffmpeg_timeout_grows_with_input_size(tmp_path: Path, segments: list[Path], ffmpeg_ok: list[dict]) -> None:
HLS.merge_segments(segments=segments, save_path=tmp_path / "small.mp4")
segments[0].parent.mkdir(exist_ok=True)
for i, path in enumerate(segments):
path.write_bytes(f"segment-{i}".encode())
segments[0].write_bytes(b"\0" * 10 * 1024 * 1024)
HLS.merge_segments(segments=segments, save_path=tmp_path / "large.mp4")
assert [call["timeout"] for call in ffmpeg_ok] == [300, 302]
+42 -14
View File
@@ -20,6 +20,7 @@ real spawns stay fast.
import importlib
import multiprocessing
import os
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -98,6 +99,27 @@ def clear_cancel():
dl.DOWNLOAD_CANCELLED.clear()
def die_without_result(queue, kwargs):
os._exit(3)
def run_mp(urls, tmp_path):
for _ in dl.download_multiprocess(
urls=urls,
output_dir=tmp_path,
filename="seg_{i:04}.bin",
headers=None,
cookies=None,
proxy=None,
max_workers=2,
adaptive=False,
spec={"kind": "none"},
processes=2,
debug_logger=None,
):
pass
def url(srv, path):
return f"http://127.0.0.1:{srv.server_address[1]}{path}"
@@ -127,20 +149,26 @@ def test_multiprocess_child_crash_raises(server, tmp_path):
good = {"url": url(server, "/seg/0.bin")}
bad = {"nourl": True}
with pytest.raises(RuntimeError):
for _ in dl.download_multiprocess(
urls=[good, bad],
output_dir=tmp_path,
filename="seg_{i:04}.bin",
headers=None,
cookies=None,
proxy=None,
max_workers=2,
adaptive=False,
spec={"kind": "none"},
processes=2,
debug_logger=None,
):
pass
run_mp([good, bad], tmp_path)
def test_multiprocess_child_death_raises(tmp_path, monkeypatch):
monkeypatch.setattr(dl, "mp_worker", die_without_result)
raised: list[BaseException] = []
def drive():
try:
run_mp([{"url": "http://127.0.0.1:1/a"}, {"url": "http://127.0.0.1:1/b"}], tmp_path)
except BaseException as exc:
raised.append(exc)
thread = threading.Thread(target=drive, daemon=True)
thread.start()
thread.join(timeout=30)
assert not thread.is_alive()
assert len(raised) == 1 and isinstance(raised[0], RuntimeError)
assert "died without result" in str(raised[0])
def test_multiprocess_cancel_terminates_children(server, tmp_path):
+178
View File
@@ -0,0 +1,178 @@
"""A failure with no HTTP response gets the longer outage budget, and a full disk fails on the first attempt.
A failure that carries an HTTP response keeps the normal MAX_ATTEMPTS budget.
"""
import errno
import importlib
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
import requests as rq
import rnet
from tests.downloaders.test_content_encoding import _FakeRnetResponse
from tests.downloaders.test_rnet_session_paths import SESSIONS
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.session import MaxRetriesError
from unshackle.core.utilities import get_free_port
dl = importlib.import_module("unshackle.core.downloaders.requests")
BODY = b"\0" * 4096
class _Server(ThreadingHTTPServer):
daemon_threads = True
def __init__(self, status):
self.status = status
self.requests = 0
super().__init__(("127.0.0.1", 0), _Handler)
self.url = f"http://127.0.0.1:{self.server_address[1]}/a"
def handle_error(self, request, client_address):
pass
class _Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *_):
pass
def do_GET(self):
self.server.requests += 1
body = BODY if self.server.status == 200 else b""
self.send_response(self.server.status)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
@pytest.fixture(autouse=True)
def fast_retries(monkeypatch):
DOWNLOAD_CANCELLED.clear()
monkeypatch.setattr(dl, "RETRY_WAIT", 0)
yield
DOWNLOAD_CANCELLED.clear()
@pytest.fixture
def serve():
servers: list[_Server] = []
def start(status):
server = _Server(status)
threading.Thread(target=server.serve_forever, daemon=True).start()
servers.append(server)
return server
yield start
for server in servers:
server.shutdown()
server.server_close()
@pytest.mark.parametrize("make_session", SESSIONS)
def test_no_response_failure_gets_the_outage_budget(tmp_path, make_session):
port = get_free_port()
retried: list[Exception] = []
with pytest.raises(Exception) as raised:
list(
dl.download(
url=f"http://127.0.0.1:{port}/a",
save_path=tmp_path / "a.bin",
session=make_session(),
on_retry=retried.append,
)
)
assert len(retried) == dl.OUTAGE_ATTEMPTS - 1
assert any(f"gave up after {dl.OUTAGE_ATTEMPTS} failed attempts" in note for note in raised.value.__notes__)
class _FullDisk:
def __init__(self, *args, **kwargs):
self.file = open(*args, **kwargs)
def __enter__(self):
return self
def __exit__(self, *exc):
self.file.close()
def write(self, data):
raise OSError(errno.ENOSPC, "No space left on device")
def test_disk_full_is_not_retried(tmp_path, monkeypatch, serve):
server = serve(200)
monkeypatch.setattr(dl, "open", _FullDisk, raising=False)
with pytest.raises(OSError) as raised:
list(dl.download(url=server.url, save_path=tmp_path / "a.bin", session=rq.Session()))
assert raised.value.errno == errno.ENOSPC
assert server.requests == 1
assert dl.retries_exhausted(raised.value)
def test_status_failure_keeps_the_normal_budget(tmp_path, serve):
server = serve(503)
with pytest.raises(Exception):
list(dl.download(url=server.url, save_path=tmp_path / "a.bin", session=rq.Session()))
assert server.requests == dl.MAX_ATTEMPTS
@pytest.mark.parametrize("make_session", SESSIONS)
def test_malformed_url_keeps_the_normal_budget(tmp_path, make_session):
retried: list[Exception] = []
with pytest.raises(Exception) as raised:
list(
dl.download(
url="htp://127.0.0.1/a",
save_path=tmp_path / "a.bin",
session=make_session(),
on_retry=retried.append,
)
)
assert len(retried) == dl.MAX_ATTEMPTS - 1
assert any(f"gave up after {dl.MAX_ATTEMPTS} failed attempts" in note for note in raised.value.__notes__)
class _StatusError(Exception):
def __init__(self, response):
super().__init__(f"HTTP {response.status_code}")
self.response = response
class _RecoveringSession:
"""Refuses six connections, answers one 503, then serves the body."""
def __init__(self):
self.calls = 0
def get(self, url, stream=True, **kwargs):
self.calls += 1
if self.calls <= 6:
raise MaxRetriesError("GET 127.0.0.1 failed", cause=rnet.ConnectionError("connection refused"))
if self.calls == 7:
raise _StatusError(_FakeRnetResponse(503, {}, b""))
return _FakeRnetResponse(200, {}, b"body-bytes")
def test_outage_does_not_spend_the_status_budget(tmp_path, monkeypatch):
monkeypatch.setattr(dl, "is_rnet_session", lambda s: isinstance(s, _RecoveringSession))
monkeypatch.setattr(dl, "retry_sleep", lambda exc, attempts: 0)
session = _RecoveringSession()
save_path = tmp_path / "a.bin"
list(dl.download(url="http://127.0.0.1:1/a", save_path=save_path, session=session))
assert save_path.read_bytes() == b"body-bytes"
assert session.calls == 8
@@ -0,0 +1,88 @@
"""The workers of a ranged single-file download share fixed-size parts from one queue.
A connection that the host holds keeps one part, and the other worker completes the rest.
"""
import importlib
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from requests import Session
from unshackle.core.constants import DOWNLOAD_CANCELLED
dl = importlib.import_module("unshackle.core.downloaders.requests")
BODY = bytes(range(256)) * 256
class _Server(ThreadingHTTPServer):
daemon_threads = True
def __init__(self):
self.lock = threading.Lock()
self.served: list[str] = []
self.held: str | None = None
self.release = threading.Event()
self.others_done_at_release = -1
super().__init__(("127.0.0.1", 0), _Handler)
self.url = f"http://127.0.0.1:{self.server_address[1]}/big.bin"
def handle_error(self, request, client_address):
pass
class _Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *_):
pass
def do_GET(self):
server = self.server
header = self.headers.get("Range")
start, end = 0, len(BODY) - 1
if header:
start_s, _, end_s = header.removeprefix("bytes=").partition("-")
start, end = int(start_s), (int(end_s) if end_s else len(BODY) - 1)
body = BODY[start : end + 1]
with server.lock:
held = server.held is None
if held:
server.held = header
if held:
server.release.wait(5)
with server.lock:
server.others_done_at_release = len(server.served)
self.send_response(206)
self.send_header("Content-Range", f"bytes {start}-{end}/{len(BODY)}")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
with server.lock:
server.served.append(header)
if not held and len(server.served) == 7:
server.release.set()
def test_fast_connection_takes_the_parts_a_held_connection_cannot(tmp_path, monkeypatch):
monkeypatch.setattr(dl, "RANGE_PARALLEL_PART_SIZE", 8 * 1024)
monkeypatch.setattr(dl, "RANGE_PARALLEL_MIN_PART_SIZE", 2 * 1024)
DOWNLOAD_CANCELLED.clear()
server = _Server()
threading.Thread(target=server.serve_forever, daemon=True).start()
save_path = tmp_path / "big.bin"
try:
for _ in dl.dispatch_parts(
url=server.url, save_path=save_path, session=Session(), total_size=len(BODY), max_workers=2
):
pass
finally:
server.release.set()
server.shutdown()
server.server_close()
DOWNLOAD_CANCELLED.clear()
assert save_path.read_bytes() == BODY
assert len(set(server.served)) == 8
assert server.others_done_at_release == 7
@@ -0,0 +1,51 @@
"""Segment requests on rnet carry network.read_timeout from the config, or READ_TIMEOUT when it is unset.
A per-request read_timeout overrides the one on the rnet client, so the downloader must pass the configured value.
"""
import importlib
import pytest
from tests.downloaders.test_content_encoding import _FakeRnetResponse
from unshackle.core.config import config
dl = importlib.import_module("unshackle.core.downloaders.requests")
class FakeSession:
def __init__(self):
self.calls: list[dict] = []
def get(self, url, stream=True, **kwargs):
self.calls.append(kwargs)
return _FakeRnetResponse(200, {}, b"body-bytes")
@pytest.fixture
def session(monkeypatch):
monkeypatch.setattr(dl, "is_rnet_session", lambda s: isinstance(s, FakeSession))
return FakeSession()
@pytest.mark.parametrize(
"network, module_default, kwargs, expected",
[
pytest.param({"read_timeout": 7}, None, {}, 7, id="configured"),
pytest.param({}, None, {}, dl.READ_TIMEOUT, id="unset"),
pytest.param({}, 2, {}, 2, id="patched-default"),
pytest.param({"read_timeout": 7}, None, {"read_timeout": 3}, 3, id="caller-wins"),
],
)
def test_segment_request_read_timeout(tmp_path, session, monkeypatch, network, module_default, kwargs, expected):
monkeypatch.setattr(config, "network", network)
if module_default is not None:
monkeypatch.setattr(dl, "READ_TIMEOUT", module_default)
list(dl.download(url="http://127.0.0.1:1/a", save_path=tmp_path / "a.bin", session=session, **kwargs))
assert session.calls[0]["read_timeout"] == expected
def test_probe_uses_the_configured_read_timeout(session, monkeypatch):
monkeypatch.setattr(config, "network", {"read_timeout": 7})
dl.probe_ranged("http://127.0.0.1:1/a", session)
assert session.calls[0]["read_timeout"] == 7
@@ -0,0 +1,167 @@
"""Downloader transport tests that send real requests through both session types.
Each case runs against a loopback server with a plain requests.Session and with a real RnetSession, so an rnet
upgrade that changes how a cut body, a read timeout or a Retry-After header surfaces fails here.
"""
import importlib
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
import requests as rq
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.session import RnetSession
dl = importlib.import_module("unshackle.core.downloaders.requests")
BODY = bytes(range(256)) * 256
CUT_AFTER = 10 * 1024
CHUNK = 16 * 1024
SESSIONS = [pytest.param(rq.Session, id="requests"), pytest.param(RnetSession, id="rnet")]
class _Server(ThreadingHTTPServer):
allow_reuse_address = True
daemon_threads = True
def __init__(self):
self.hits: list[tuple[str, str | None]] = []
self.release = threading.Event()
self.lock = threading.Lock()
super().__init__(("127.0.0.1", 0), _Handler)
self.url = f"http://127.0.0.1:{self.server_address[1]}"
def handle_error(self, request, client_address):
pass
class _Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *_):
pass
def do_GET(self):
header = self.headers.get("Range")
with self.server.lock:
first = not any(path == self.path for path, _ in self.server.hits)
self.server.hits.append((self.path, header))
start, end = 0, len(BODY) - 1
if header:
start_s, _, end_s = header.removeprefix("bytes=").partition("-")
start, end = int(start_s), (int(end_s) if end_s else len(BODY) - 1)
body = BODY[start : end + 1]
if self.path == "/busy" and first:
self.send_response(503)
self.send_header("Retry-After", "1")
self.send_header("Content-Length", "0")
self.end_headers()
return
self.send_response(206 if header else 200)
if header:
self.send_header("Content-Range", f"bytes {start}-{end}/{len(BODY)}")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
if self.path == "/cut" and len(body) > CUT_AFTER:
self.wfile.write(body[:CUT_AFTER])
self.close_connection = True
return
if self.path == "/stall" and first:
self.wfile.write(body[:1000])
self.wfile.flush()
self.server.release.wait(10)
self.close_connection = True
return
self.wfile.write(body)
@pytest.fixture
def server(monkeypatch):
DOWNLOAD_CANCELLED.clear()
monkeypatch.setattr(dl, "RETRY_WAIT", 0)
monkeypatch.setattr(dl, "REQUEST_CHUNK_SIZE", CHUNK)
monkeypatch.setattr(dl, "MIN_REQUEST_CHUNK", 4 * 1024)
monkeypatch.setattr(dl, "MIN_RESUME_PROGRESS", 1024)
server = _Server()
threading.Thread(target=server.serve_forever, daemon=True).start()
yield server
server.release.set()
server.shutdown()
server.server_close()
DOWNLOAD_CANCELLED.clear()
@pytest.mark.parametrize("make_session", SESSIONS)
def test_plain_body_arrives_whole(tmp_path, server, make_session):
save_path = tmp_path / "0.mp4"
list(dl.download(url=f"{server.url}/plain", save_path=save_path, session=make_session()))
assert save_path.read_bytes() == BODY
assert len(server.hits) == 1
@pytest.mark.parametrize("make_session", SESSIONS)
def test_cut_body_resumes_with_range(tmp_path, server, make_session):
save_path = tmp_path / "0.mp4"
list(dl.download(url=f"{server.url}/cut", save_path=save_path, session=make_session()))
assert save_path.read_bytes() == BODY
assert server.hits[0][1] is None
assert len(server.hits) > 1
assert all(r is not None and r.startswith("bytes=") for _, r in server.hits[1:])
@pytest.mark.parametrize("make_session", SESSIONS)
def test_retry_after_header_sets_the_wait(tmp_path, server, make_session, monkeypatch):
real = dl.retry_sleep
waits: list[float] = []
def spy(exc, attempts):
waits.append(real(exc, attempts))
return 0
monkeypatch.setattr(dl, "retry_sleep", spy)
save_path = tmp_path / "0.mp4"
list(dl.download(url=f"{server.url}/busy", save_path=save_path, session=make_session()))
assert save_path.read_bytes() == BODY
assert len(server.hits) == 2
assert waits == [1.0]
@pytest.mark.parametrize("make_session", SESSIONS)
def test_stalled_body_times_out_and_retries(tmp_path, server, make_session, monkeypatch):
monkeypatch.setattr(dl, "READ_TIMEOUT", 1)
monkeypatch.setattr("unshackle.core.config.config.network", {})
save_path = tmp_path / "0.mp4"
list(dl.download(url=f"{server.url}/stall", save_path=save_path, session=make_session()))
assert save_path.read_bytes() == BODY
assert len(server.hits) == 2
def test_complete_file_is_reported_without_a_request(tmp_path, server):
save_path = tmp_path / "0.mp4"
save_path.write_bytes(b"x" * 10)
events = list(dl.download(url=f"{server.url}/plain", save_path=save_path, session=rq.Session()))
assert server.hits == []
assert save_path.read_bytes() == b"x" * 10
assert {"file_downloaded": save_path, "written": 10} in events
def test_legacy_layout_restarts_clean(tmp_path, server):
save_path = tmp_path / "0.mp4"
save_path.write_bytes(b"partial")
marker = save_path.with_name(save_path.name + ".!dev")
marker.write_bytes(b"")
list(dl.download(url=f"{server.url}/plain", save_path=save_path, session=rq.Session()))
assert save_path.read_bytes() == BODY
assert not marker.exists()
assert server.hits[0][1] is None
+61 -13
View File
@@ -1,3 +1,4 @@
import errno
import math
import multiprocessing
import os
@@ -24,8 +25,11 @@ from typing import Any, Callable, Generator, MutableMapping, Optional, Union, ca
from requests import Session
from requests.adapters import HTTPAdapter, Retry
from requests.exceptions import ConnectionError as RequestsConnectionError
from requests.exceptions import ProxyError, SSLError
from rich import filesize
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED, DownloadCancelled
from unshackle.core.utilities import get_debug_logger, get_extension, log_event
from unshackle.core.utils import run_proxy
@@ -33,6 +37,10 @@ from unshackle.core.utils import run_proxy
MAX_ATTEMPTS = 5
RETRY_WAIT = 2
GAVE_UP_NOTE = "gave up after"
# a failure with no HTTP response (DNS, refused, unreachable) is the network, not the host: it
# fails in milliseconds, so MAX_ATTEMPTS would spend its whole backoff in about 30 seconds
OUTAGE_ATTEMPTS = 9
LOCAL_DISK_ERRNOS = (errno.ENOSPC, errno.EDQUOT, errno.EROFS)
# a cut that still delivered bytes is resumable and refreshes the attempt budget; bound it
# so a server that sends a little and closes, over and over, still terminates
MAX_RESUMES = 50
@@ -65,6 +73,8 @@ SPEED_ROLLING_WINDOW = 10 # seconds of history to keep for speed calculation
RANGE_PARALLEL_MIN_SIZE = 64 * 1024 * 1024
RANGE_PARALLEL_MIN_PART_SIZE = 4 * 1024 * 1024
# the workers take parts from a shared queue, so a slow connection holds one part of this size
RANGE_PARALLEL_PART_SIZE = 16 * 1024 * 1024
# One CPython interpreter caps sustained segment throughput (GIL in the ssl read path);
# fan a big segment batch across spawned children to reach line rate. Below this count the
@@ -184,6 +194,14 @@ def adaptive_chunk_size(content_length: int) -> int:
return min(MAX_CHUNK, max(MIN_CHUNK, content_length // 4))
def rnet_read_timeout() -> float:
"""The stall timeout for a segment request on rnet: ``network.read_timeout`` when configured, else READ_TIMEOUT.
A per-request value overrides the rnet client's own, so this must give the configured one.
"""
return config.network.get("read_timeout") or READ_TIMEOUT
ADAPTIVE_TICK = 4.0
ADAPTIVE_STEP = 2
ADAPTIVE_MIN = 2
@@ -419,6 +437,21 @@ def is_rnet_session(session: Any) -> bool:
return isinstance(session, RnetSession)
def is_outage(exc: BaseException) -> bool:
"""Whether a failure reached no server: a refused or unreachable connection, or a failed name lookup.
A TLS, proxy or URL error is not an outage, so it keeps the MAX_ATTEMPTS budget.
"""
import rnet
for error in (exc, exc.__cause__):
if isinstance(error, (rnet.ConnectionError, rnet.ConnectionResetError, rnet.DNSResolverError)):
return True
if isinstance(error, RequestsConnectionError) and not isinstance(error, (ProxyError, SSLError)):
return True
return False
def is_content_encoded(value: Optional[str]) -> bool:
"""
Whether a Content-Encoding value names any coding other than absent or `identity`.
@@ -437,7 +470,7 @@ def probe_ranged(url: str, session: Any, **kwargs: Any) -> tuple[int, bool]:
headers["Accept-Encoding"] = "identity"
rest = {k: v for k, v in kwargs.items() if k != "headers"}
if is_rnet_session(session):
rest.setdefault("read_timeout", READ_TIMEOUT)
rest.setdefault("read_timeout", rnet_read_timeout())
# let download() own segment retries, with no nested session-level retry loop
rest.setdefault("max_retries", 0)
else:
@@ -559,12 +592,14 @@ def force_unblock_stream(stream: Any) -> None:
pass
def split_ranges(size: int, max_parts: int, part_target: int) -> list[tuple[int, int]]:
def split_ranges(size: int, max_parts: Optional[int], part_target: int) -> list[tuple[int, int]]:
"""Split ``[0, size)`` into inclusive ``[start, end]`` byte ranges with no gaps or overlaps.
At most ``max_parts`` parts of ~``part_target`` bytes each. Pure, with no I/O, so testable.
Parts of ~``part_target`` bytes each, at most ``max_parts`` of them when given. Pure, with no I/O, so testable.
"""
n_parts = max(1, min(max_parts, math.ceil(size / part_target)))
n_parts = max(1, math.ceil(size / part_target))
if max_parts is not None:
n_parts = max(1, min(max_parts, n_parts))
part_size = math.ceil(size / n_parts)
return [
(s, e) for i in range(n_parts) for s, e in [(i * part_size, min(size - 1, (i + 1) * part_size - 1))] if s <= e
@@ -619,8 +654,8 @@ def dispatch_parts(
save_path.parent.mkdir(parents=True, exist_ok=True)
control_file = save_path.with_name(f"{save_path.name}.!dev")
part_target = max(RANGE_PARALLEL_MIN_PART_SIZE, math.ceil(total_size / max_workers))
parts = split_ranges(total_size, max_workers, part_target)
part_target = min(RANGE_PARALLEL_PART_SIZE, max(RANGE_PARALLEL_MIN_PART_SIZE, math.ceil(total_size / max_workers)))
parts = split_ranges(total_size, None, part_target)
control_file.write_bytes(b"")
with open(save_path, "wb") as f:
@@ -643,7 +678,7 @@ def dispatch_parts(
):
events.put(ev)
pool = ThreadPoolExecutor(max_workers=len(parts))
pool = ThreadPoolExecutor(max_workers=min(max_workers, len(parts)))
futures = [pool.submit(worker, s, e) for s, e in parts]
pending = set(futures)
@@ -814,6 +849,7 @@ def download(
item_range = has_range_header(kwargs)
attempts = 1
outages = 0
# attempts resets on progress, so the give-up note counts failures on their own
failures = 0
started = _time()
@@ -834,12 +870,13 @@ def download(
resume_start = resume_offset
last_speed_refresh = _time()
stream: Any = None
try:
use_rnet = is_rnet_session(session)
request_kwargs = dict(kwargs)
if use_rnet:
request_kwargs.setdefault("read_timeout", READ_TIMEOUT)
request_kwargs.setdefault("read_timeout", rnet_read_timeout())
# own segment retries here, suppressing RnetSession's nested retry loop
request_kwargs.setdefault("max_retries", 0)
else:
@@ -869,7 +906,7 @@ def download(
req_headers["Range"] = f"bytes={resume_offset}-"
request_kwargs["headers"] = req_headers
stream: Any = session.get(url, stream=True, **request_kwargs)
stream = session.get(url, stream=True, **request_kwargs)
if (not part_mode) and (not item_range) and resume_offset > 0 and stream.status_code == 416:
complete = parse_content_range_unsatisfied(
@@ -1110,6 +1147,7 @@ def download(
# this request's sub-range arrived whole; the rest of the part is the next
# request, not a retry, so the attempt budget starts over for it
attempts = 1
outages = 0
continue
elif content_length and written < content_length:
# applies to segments too: a connection FIN'd mid-body is a clean EOF, so the
@@ -1130,6 +1168,7 @@ def download(
if resume_offset > high_water:
high_water = resume_offset
attempts = 1
outages = 0
continue
os.replace(tmp_file, save_path)
yield dict(file_downloaded=save_path, written=resume_offset + written)
@@ -1146,7 +1185,12 @@ def download(
return
failures += 1
cancelled = DOWNLOAD_CANCELLED.is_set() or (abort is not None and abort.is_set())
if cancelled or attempts == MAX_ATTEMPTS:
outage = stream is None and is_outage(exc)
if outage:
outages += 1
disk_error = getattr(exc, "errno", None) in LOCAL_DISK_ERRNOS
limit = OUTAGE_ATTEMPTS if outage else MAX_ATTEMPTS
if cancelled or disk_error or (outages if outage else attempts) >= limit:
# cancel/abort is not an error, but a genuine retry-exhaustion is, so surface it
# so the caller fails fast instead of hitting a missing segment at merge time
if not cancelled:
@@ -1173,12 +1217,13 @@ def download(
on_retry(exc)
except Exception:
pass
delay = retry_sleep(exc, max(1, attempts))
tries = outages if outage else max(1, attempts)
delay = retry_sleep(exc, tries)
from unshackle.core.session import failure_reason
log_event(
"segment_retry",
message=f"{failure_reason(exc)}, retry {max(1, attempts)}/{MAX_ATTEMPTS - 1} in {delay:.1f}s",
message=f"{failure_reason(exc)}, retry {tries}/{limit - 1} in {delay:.1f}s",
context={"file": save_path.name, "failures": failures, "resumes": resumes},
)
if abort is not None:
@@ -1192,7 +1237,8 @@ def download(
# parked worker rather than stall teardown for the full backoff
if DOWNLOAD_CANCELLED.wait(delay):
return
attempts += 1
if not outage:
attempts += 1
def rebuildable_adapter(adapter: Any) -> bool:
@@ -1316,6 +1362,8 @@ def mp_worker(queue: Any, kwargs: dict[str, Any]) -> None:
# must not be able to rewrite arbitrary module globals in every child
if name in ("READ_TIMEOUT", "RETRY_WAIT", "HEDGE_MIN_WAIT"):
setattr(sys.modules[__name__], name, float(value))
if name == "READ_TIMEOUT":
config.network = {**config.network, "read_timeout": float(value)}
spec = kwargs.pop("_session_spec")
kwargs["session"] = rebuild_session(spec, int(kwargs.get("max_workers") or 1))
for event in requests(**kwargs):
+3 -2
View File
@@ -10,7 +10,7 @@ import re
import shutil
from bisect import bisect_right
from concurrent.futures import Future
from contextlib import ExitStack, closing
from contextlib import ExitStack, closing, suppress
from copy import deepcopy
from functools import lru_cache, partial
from pathlib import Path
@@ -958,7 +958,8 @@ class DASH:
progress(downloaded="Merging", completed=0, total=len(segments_to_merge))
for segment_file in segments_to_merge:
append(f, segment_file)
segment_file.unlink()
with suppress(OSError):
segment_file.unlink()
progress(advance=1)
track.path = save_path
+22 -17
View File
@@ -9,7 +9,7 @@ import re
import shutil
import subprocess
import time
from contextlib import ExitStack, closing
from contextlib import ExitStack, closing, suppress
from functools import partial
from itertools import accumulate
from pathlib import Path
@@ -1255,7 +1255,8 @@ class HLS:
append(f, discontinuity_file)
f.flush()
os.fsync(f.fileno())
discontinuity_file.unlink()
with suppress(OSError):
discontinuity_file.unlink()
if save_dir.exists() and save_dir.name.endswith("_segments"):
try:
@@ -1319,7 +1320,8 @@ class HLS:
def cleanup_segments_and_dirs() -> None:
"""Clean up segments and directories after successful merge."""
for segment in segments:
segment.unlink(missing_ok=True)
with suppress(OSError):
segment.unlink(missing_ok=True)
for segment_dir in segment_dirs:
if segment_dir.exists():
try:
@@ -1328,8 +1330,9 @@ class HLS:
pass # Directory cleanup failed, but merge succeeded
if binaries.FFMPEG:
demuxer_file = save_path.parent / f"ffmpeg_concat_demuxer_{save_path.stem}.txt"
try:
demuxer_file = save_path.parent / f"ffmpeg_concat_demuxer_{save_path.stem}.txt"
concat_timeout = 300 + sum(s.stat().st_size for s in segments) // (5 * 1024 * 1024)
demuxer_file.write_text(
"\n".join([f"file '{segment.absolute()}'" for segment in segments]),
encoding="utf-8",
@@ -1357,13 +1360,23 @@ class HLS:
save_path,
],
check=True,
timeout=300,
timeout=concat_timeout,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
demuxer_file.unlink(missing_ok=True)
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError) as e:
stderr = getattr(e, "stderr", None) or ""
if isinstance(stderr, bytes):
stderr = stderr.decode("utf-8", "replace")
logging.getLogger("HLS").debug(
f"FFmpeg concat failed ({e}), falling back to binary concatenation"
+ (f": {stderr.strip()}" if stderr.strip() else "")
)
with suppress(OSError):
save_path.unlink(missing_ok=True)
else:
if progress:
progress(completed=len(segments))
cleanup_segments_and_dirs()
@@ -1376,17 +1389,9 @@ class HLS:
output_size=save_path.stat().st_size if save_path.exists() else 0,
)
return save_path.stat().st_size
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError) as e:
stderr = getattr(e, "stderr", None) or ""
if isinstance(stderr, bytes):
stderr = stderr.decode("utf-8", "replace")
logging.getLogger("HLS").debug(
f"FFmpeg concat failed ({e}), falling back to binary concatenation"
+ (f": {stderr.strip()}" if stderr.strip() else "")
)
demuxer_file.unlink(missing_ok=True)
save_path.unlink(missing_ok=True)
finally:
with suppress(OSError):
demuxer_file.unlink(missing_ok=True)
logging.getLogger("HLS").debug(f"Using binary concatenation for {len(segments)} segments")
with open(save_path, "wb") as output_file:
+3 -2
View File
@@ -8,7 +8,7 @@ import re
import shutil
import struct
import urllib.parse
from contextlib import ExitStack, closing
from contextlib import ExitStack, closing, suppress
from pathlib import Path
from typing import Any, BinaryIO, Optional, Union
@@ -629,7 +629,8 @@ class ISM:
else:
with open(segment_file, "rb") as src:
shutil.copyfileobj(src, f, 1024 * 1024)
segment_file.unlink()
with suppress(OSError):
segment_file.unlink()
progress(advance=1)
track.path = save_path
+2 -1
View File
@@ -884,7 +884,8 @@ class Track:
with save_path.open("wb") as joined, media_path.open("rb") as media:
joined.write(sample_range[0])
shutil.copyfileobj(media, joined)
media_path.unlink()
with contextlib.suppress(OSError):
media_path.unlink()
self.path = save_path
events.emit(events.Types.TRACK_DOWNLOADED, track=self)