mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-29 12:35:13 +00:00
Merge branch 'dev' into feat/downloader-speed
# Conflicts: # unshackle/core/api/download_manager.py # unshackle/core/downloaders/requests.py # unshackle/core/manifests/dash.py # unshackle/core/session.py # unshackle/core/utils/webvtt.py
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
Pins two teardown-safety invariants:
|
||||
|
||||
- ``_dispatch_parts`` must NOT finalize when the process-global ``DOWNLOAD_CANCELLED``
|
||||
- ``dispatch_parts`` must NOT finalize when the process-global ``DOWNLOAD_CANCELLED``
|
||||
fires mid-download: part workers return silently keeping partials, so every future
|
||||
completes without error, and finalizing would strip the ``.!dev`` control file and
|
||||
pass off a hole-filled pre-truncated file as complete on the next run.
|
||||
@@ -104,7 +104,7 @@ def test_dispatch_parts_does_not_finalize_on_global_cancel(server, tmp_path):
|
||||
canceller = threading.Thread(target=_cancel_when_started)
|
||||
canceller.start()
|
||||
events = list(
|
||||
dl._dispatch_parts(
|
||||
dl.dispatch_parts(
|
||||
url=_url(server),
|
||||
save_path=save_path,
|
||||
session=Session(),
|
||||
@@ -121,7 +121,7 @@ def test_dispatch_parts_does_not_finalize_on_global_cancel(server, tmp_path):
|
||||
|
||||
def test_backoff_wait_exits_promptly_on_batch_abort(server, tmp_path, monkeypatch):
|
||||
server.always_status = 503
|
||||
monkeypatch.setattr(dl, "_retry_sleep", lambda exc, attempts: 30.0)
|
||||
monkeypatch.setattr(dl, "retry_sleep", lambda exc, attempts: 30.0)
|
||||
abort = threading.Event()
|
||||
|
||||
def _consume() -> None:
|
||||
|
||||
@@ -6,7 +6,7 @@ import threading
|
||||
import pytest
|
||||
import requests as rq
|
||||
|
||||
from unshackle.core.downloaders.requests import _is_content_encoded, download
|
||||
from unshackle.core.downloaders.requests import download, is_content_encoded
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -35,7 +35,7 @@ from unshackle.core.downloaders.requests import _is_content_encoded, download
|
||||
],
|
||||
)
|
||||
def test_is_content_encoded(value, expected):
|
||||
assert _is_content_encoded(value) is expected
|
||||
assert is_content_encoded(value) is expected
|
||||
|
||||
|
||||
PLAIN = b"WEBVTT\n\n" + b"".join(f"{i:05d} cue text\n".encode() for i in range(2000))
|
||||
@@ -51,9 +51,9 @@ class _EncodingServer:
|
||||
self.sock.bind(("127.0.0.1", 0))
|
||||
self.sock.listen(8)
|
||||
self.url = f"http://127.0.0.1:{self.sock.getsockname()[1]}/sub.vtt"
|
||||
threading.Thread(target=self._serve, daemon=True).start()
|
||||
threading.Thread(target=self.serve, daemon=True).start()
|
||||
|
||||
def _serve(self):
|
||||
def serve(self):
|
||||
while True:
|
||||
try:
|
||||
conn, _ = self.sock.accept()
|
||||
@@ -146,7 +146,7 @@ class _FakeRnetSession:
|
||||
|
||||
def test_rnet_encoded_body_discards_a_partial_instead_of_range_resuming(tmp_path, monkeypatch):
|
||||
dl = importlib.import_module("unshackle.core.downloaders.requests")
|
||||
monkeypatch.setattr(dl, "_is_rnet_session", lambda s: isinstance(s, _FakeRnetSession))
|
||||
monkeypatch.setattr(dl, "is_rnet_session", lambda s: isinstance(s, _FakeRnetSession))
|
||||
session = _FakeRnetSession(PLAIN)
|
||||
save_path = tmp_path / "sub.vtt"
|
||||
save_path.with_name("sub.vtt.!dev").write_bytes(PLAIN[:5000])
|
||||
|
||||
@@ -99,7 +99,7 @@ def test_small_segments_never_probed(server, tmp_path, monkeypatch):
|
||||
def no_probe(*args, **kw):
|
||||
raise AssertionError("tail boost probed a small-segment batch")
|
||||
|
||||
monkeypatch.setattr(dl, "_probe_ranged", no_probe)
|
||||
monkeypatch.setattr(dl, "probe_ranged", no_probe)
|
||||
files = _run(server, tmp_path, [{"url": _url(server)} for _ in range(30)], max_workers=4, adaptive=True)
|
||||
assert len(files) == 30
|
||||
assert all(f.read_bytes() == PARENT for f in files)
|
||||
@@ -149,24 +149,24 @@ def _exc_with_headers(headers):
|
||||
|
||||
|
||||
def test_retry_sleep_honors_numeric_retry_after():
|
||||
assert dl._retry_sleep(_exc_with_headers({"Retry-After": "3"}), 1) == 3.0
|
||||
assert dl._retry_sleep(_exc_with_headers({"Retry-After": "9999"}), 1) == 60.0 # session.MAX_BACKOFF cap
|
||||
assert dl.retry_sleep(_exc_with_headers({"Retry-After": "3"}), 1) == 3.0
|
||||
assert dl.retry_sleep(_exc_with_headers({"Retry-After": "9999"}), 1) == 60.0 # session.MAX_BACKOFF cap
|
||||
|
||||
|
||||
def test_retry_sleep_honors_http_date_retry_after():
|
||||
when = format_datetime(datetime.now(timezone.utc) + timedelta(seconds=10), usegmt=True)
|
||||
assert 5 <= dl._retry_sleep(_exc_with_headers({"Retry-After": when}), 1) <= 10
|
||||
assert 5 <= dl.retry_sleep(_exc_with_headers({"Retry-After": when}), 1) <= 10
|
||||
|
||||
|
||||
def test_retry_sleep_exponential_backoff_with_jitter():
|
||||
# no response on the failure: exponential from RETRY_WAIT with up to 10% jitter
|
||||
for attempts, base in ((1, dl.RETRY_WAIT), (2, dl.RETRY_WAIT * 2), (3, dl.RETRY_WAIT * 4)):
|
||||
assert base <= dl._retry_sleep(Exception("reset"), attempts) <= base * 1.1
|
||||
assert dl._retry_sleep(Exception("reset"), 30) == 60.0 # capped
|
||||
assert base <= dl.retry_sleep(Exception("reset"), attempts) <= base * 1.1
|
||||
assert dl.retry_sleep(Exception("reset"), 30) == 60.0 # capped
|
||||
|
||||
|
||||
def test_retry_sleep_invalid_retry_after_falls_back():
|
||||
v = dl._retry_sleep(_exc_with_headers({"Retry-After": "soon"}), 1)
|
||||
v = dl.retry_sleep(_exc_with_headers({"Retry-After": "soon"}), 1)
|
||||
assert dl.RETRY_WAIT <= v <= dl.RETRY_WAIT * 1.1
|
||||
|
||||
|
||||
@@ -174,13 +174,13 @@ def test_retry_sleep_naive_http_date_treated_as_utc():
|
||||
# "-0000" makes parsedate_to_datetime return a naive datetime; must clamp, not raise
|
||||
when = format_datetime(datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(seconds=10))
|
||||
assert when.endswith("-0000")
|
||||
v = dl._retry_sleep(_exc_with_headers({"Retry-After": when}), 1)
|
||||
v = dl.retry_sleep(_exc_with_headers({"Retry-After": when}), 1)
|
||||
assert 5 <= v <= 10
|
||||
|
||||
|
||||
def test_retry_sleep_nan_retry_after_falls_back():
|
||||
# float("nan") parses; a non-finite wait must fall back to the exponential path
|
||||
v = dl._retry_sleep(_exc_with_headers({"Retry-After": "nan"}), 1)
|
||||
v = dl.retry_sleep(_exc_with_headers({"Retry-After": "nan"}), 1)
|
||||
assert dl.RETRY_WAIT <= v <= dl.RETRY_WAIT * 1.1
|
||||
|
||||
|
||||
@@ -188,7 +188,7 @@ def test_retry_sleep_honors_retry_after_on_wrapped_cause():
|
||||
# RnetSession raises MaxRetriesError whose __cause__ HTTPError carries the response
|
||||
exc = Exception("max retries exceeded")
|
||||
exc.__cause__ = _exc_with_headers({"Retry-After": "3"})
|
||||
assert dl._retry_sleep(exc, 1) == 3.0
|
||||
assert dl.retry_sleep(exc, 1) == 3.0
|
||||
|
||||
|
||||
def test_transient_429_with_retry_after_does_not_abort_track(server, tmp_path, monkeypatch):
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
import requests as rq
|
||||
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED
|
||||
from unshackle.core.downloaders.requests import download, has_range_header
|
||||
from unshackle.core.downloaders.requests import requests as requests_downloader
|
||||
|
||||
# the package re-exports the `requests` function, shadowing the module of the same name
|
||||
downloader = sys.modules[download.__module__]
|
||||
|
||||
BODY = b"".join(f"{i:05d} payload\n".encode() for i in range(500))
|
||||
|
||||
|
||||
class _Server:
|
||||
"""Serves BODY, with a switch for the two failure modes retries have to handle."""
|
||||
|
||||
def __init__(self, mode):
|
||||
self.mode = mode
|
||||
self.sock = socket.socket()
|
||||
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
self.sock.bind(("127.0.0.1", 0))
|
||||
self.sock.listen(8)
|
||||
self.url = f"http://127.0.0.1:{self.sock.getsockname()[1]}/seg.mp4"
|
||||
self.requests = []
|
||||
threading.Thread(target=self.serve, daemon=True).start()
|
||||
|
||||
def serve(self):
|
||||
while True:
|
||||
try:
|
||||
conn, _ = self.sock.accept()
|
||||
except OSError:
|
||||
return
|
||||
try:
|
||||
request = conn.recv(65536).decode("latin1")
|
||||
headers = dict(
|
||||
(name.strip().lower(), value.strip())
|
||||
for name, _, value in (line.partition(":") for line in request.split("\r\n"))
|
||||
if value
|
||||
)
|
||||
self.requests.append(headers)
|
||||
ranged = "range" in headers
|
||||
if self.mode == "unavailable":
|
||||
conn.sendall(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
|
||||
elif ranged:
|
||||
conn.sendall(
|
||||
b"HTTP/1.1 416 Range Not Satisfiable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
|
||||
)
|
||||
else:
|
||||
conn.sendall(
|
||||
f"HTTP/1.1 200 OK\r\nContent-Length: {len(BODY)}\r\nConnection: close\r\n\r\n".encode() + BODY
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def close(self):
|
||||
self.sock.close()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_cancel():
|
||||
# the batch failure path sets the process-global cancel; leaking it makes every later
|
||||
# test that waits on the event (the speed limiter) return instantly
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
yield
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def no_retry_wait(monkeypatch):
|
||||
monkeypatch.setattr(downloader, "RETRY_WAIT", 0)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def server(request, no_retry_wait):
|
||||
server = _Server(request.param)
|
||||
yield server
|
||||
server.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["unavailable"], indirect=True)
|
||||
def test_exhausted_retries_raise_instead_of_reporting_success(tmp_path, server):
|
||||
save_path = tmp_path / "0.mp4"
|
||||
with pytest.raises(rq.HTTPError):
|
||||
list(download(url=server.url, save_path=save_path, session=rq.Session()))
|
||||
assert len(server.requests) == downloader.MAX_ATTEMPTS
|
||||
assert not save_path.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["unavailable"], indirect=True)
|
||||
def test_cancelled_download_stays_silent(tmp_path, server, monkeypatch):
|
||||
# one attempt only, so a cancel check ordered after the exhaustion raise would fail here
|
||||
monkeypatch.setattr(downloader, "MAX_ATTEMPTS", 1)
|
||||
save_path = tmp_path / "0.mp4"
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
list(download(url=server.url, save_path=save_path, session=rq.Session()))
|
||||
assert not save_path.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["range_unsatisfiable"], indirect=True)
|
||||
def test_stale_partial_restarts_clean_on_416(tmp_path, server):
|
||||
save_path = tmp_path / "0.mp4"
|
||||
save_path.with_name("0.mp4.!dev").write_bytes(b"\x00" * len(BODY))
|
||||
list(download(url=server.url, save_path=save_path, session=rq.Session()))
|
||||
assert save_path.read_bytes() == BODY
|
||||
assert [r.get("range") for r in server.requests] == [f"bytes={len(BODY)}-", None]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["range_unsatisfiable"], indirect=True)
|
||||
def test_slice_segment_never_gets_a_resume_range(tmp_path, server):
|
||||
save_path = tmp_path / "0.mp4"
|
||||
save_path.with_name("0.mp4.!dev").write_bytes(b"\x00" * 128)
|
||||
with pytest.raises(OSError):
|
||||
list(download(url=server.url, save_path=save_path, session=rq.Session(), headers={"Range": "bytes=0-127"}))
|
||||
assert [r["range"] for r in server.requests] == ["bytes=0-127"] * downloader.MAX_ATTEMPTS
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["range_unsatisfiable"], indirect=True)
|
||||
def test_identity_encoding_requested_unless_the_caller_set_one(tmp_path, server):
|
||||
save_path = tmp_path / "0.mp4"
|
||||
list(download(url=server.url, save_path=save_path, session=rq.Session()))
|
||||
assert server.requests[-1]["accept-encoding"] == "identity"
|
||||
|
||||
list(
|
||||
download(
|
||||
url=server.url, save_path=tmp_path / "1.mp4", session=rq.Session(), headers={"accept-encoding": "gzip"}
|
||||
)
|
||||
)
|
||||
assert server.requests[-1]["accept-encoding"] == "gzip"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["unavailable"], indirect=True)
|
||||
def test_failed_segment_fails_the_batch(tmp_path, server):
|
||||
# a segment the batch never delivers must raise, not merge short of the segment count
|
||||
with pytest.raises(rq.HTTPError):
|
||||
list(
|
||||
requests_downloader(
|
||||
urls=[server.url, server.url],
|
||||
output_dir=tmp_path,
|
||||
filename="{i:01}.mp4",
|
||||
max_workers=2,
|
||||
)
|
||||
)
|
||||
assert sorted(p.name for p in tmp_path.iterdir() if p.suffix == ".mp4") == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["ok"], indirect=True)
|
||||
def test_batch_larger_than_the_queue_window_downloads_every_segment(tmp_path, server):
|
||||
# a broken top-up livelocks the drain loop instead of erroring, so consume on a thread and
|
||||
# let the timeout fail the test
|
||||
urls = [server.url] * 6
|
||||
advanced = 0
|
||||
|
||||
def consume():
|
||||
nonlocal advanced
|
||||
advanced = sum(
|
||||
event["advance"]
|
||||
for event in requests_downloader(urls=urls, output_dir=tmp_path, filename="{i:02}.mp4", max_workers=1)
|
||||
if "advance" in event
|
||||
)
|
||||
|
||||
consumer = threading.Thread(target=consume, daemon=True)
|
||||
consumer.start()
|
||||
consumer.join(timeout=30)
|
||||
assert not consumer.is_alive(), "downloader never finished the batch"
|
||||
assert advanced == len(urls)
|
||||
assert sorted(p.name for p in tmp_path.iterdir() if p.suffix == ".mp4") == [f"{i:02}.mp4" for i in range(6)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("item", "expected"),
|
||||
[
|
||||
({}, False),
|
||||
({"headers": None}, False),
|
||||
({"headers": {}}, False),
|
||||
({"headers": {"Accept": "*/*"}}, False),
|
||||
({"headers": {"Range": "bytes=0-127"}}, True),
|
||||
({"headers": {"range": "bytes=0-127"}}, True),
|
||||
],
|
||||
)
|
||||
def test_has_range_header(item, expected):
|
||||
assert has_range_header(item) is expected
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Multiprocess segment-download invariants.
|
||||
|
||||
Pins the spawned-child fan-out path in ``requests()``/``_download_multiprocess``:
|
||||
Pins the spawned-child fan-out path in ``requests()``/``download_multiprocess``:
|
||||
|
||||
- Strided assignment plus the ``index_offset``/``index_stride`` filename mapping puts every
|
||||
segment's bytes in the correctly named file (a broken stride mapping misfiles content).
|
||||
@@ -109,13 +109,13 @@ def test_multiprocess_stride_downloads_all_segments_correctly(server, tmp_path):
|
||||
|
||||
|
||||
def test_multiprocess_child_crash_raises(server, tmp_path):
|
||||
# _download_multiprocess has no MP_MIN_SEGMENTS gate, so drive it directly with 2 urls.
|
||||
# download_multiprocess has no MP_MIN_SEGMENTS gate, so drive it directly with 2 urls.
|
||||
# a dict url without "url" raises KeyError while requests() builds the save path (before
|
||||
# any retry loop), so the child sends __mp_error__ fast; the sibling downloads normally.
|
||||
good = {"url": _url(server, "/seg/0.bin")}
|
||||
bad = {"nourl": True}
|
||||
with pytest.raises(RuntimeError):
|
||||
for _ in dl._download_multiprocess(
|
||||
for _ in dl.download_multiprocess(
|
||||
urls=[good, bad],
|
||||
output_dir=tmp_path,
|
||||
filename="seg_{i:04}.bin",
|
||||
@@ -163,7 +163,7 @@ def test_speed_limit_forces_single_process(server, tmp_path, monkeypatch):
|
||||
def _no_mp(**kwargs):
|
||||
raise AssertionError("multiprocess fan-out engaged despite a speed limit")
|
||||
|
||||
monkeypatch.setattr(dl, "_download_multiprocess", _no_mp)
|
||||
monkeypatch.setattr(dl, "download_multiprocess", _no_mp)
|
||||
n = dl.MP_MIN_SEGMENTS
|
||||
urls = [{"url": _url(server, f"/seg/{i}.bin")} for i in range(n)]
|
||||
dl.set_speed_limit(1_000_000_000) # far above the tiny batch, so the test is not slowed
|
||||
|
||||
@@ -9,10 +9,10 @@ Pins the byte-range fan-out that splits one large file across parts:
|
||||
retries rather than writing a wrong-length body into the pre-truncated file;
|
||||
- that failure sets only the ranged download's LOCAL abort event, never the
|
||||
process-global DOWNLOAD_CANCELLED (which would poison sibling tracks);
|
||||
- ``_probe_ranged`` parses the Content-Range total on a 206 and declines a 200
|
||||
- ``probe_ranged`` parses the Content-Range total on a 206 and declines a 200
|
||||
or a content-encoded 206.
|
||||
|
||||
Tests 2/3 exercise ``_dispatch_parts`` directly: the public single-URL path in
|
||||
Tests 2/3 exercise ``dispatch_parts`` directly: the public single-URL path in
|
||||
``requests()`` deliberately swallows a ranged failure and falls back to a plain
|
||||
sequential download, so the raise the invariant guarantees is only observable at
|
||||
the dispatch layer.
|
||||
@@ -119,7 +119,7 @@ def test_ranged_part_requires_206(server, tmp_path, monkeypatch):
|
||||
server.mode = "probe_only_206"
|
||||
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
|
||||
save_path = tmp_path / "seg_0000.bin"
|
||||
gen = dl._dispatch_parts(
|
||||
gen = dl.dispatch_parts(
|
||||
url=_url(server),
|
||||
save_path=save_path,
|
||||
session=Session(),
|
||||
@@ -140,7 +140,7 @@ def test_ranged_part_failure_stays_local(server, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
|
||||
dl.DOWNLOAD_CANCELLED.clear()
|
||||
save_path = tmp_path / "seg_0000.bin"
|
||||
gen = dl._dispatch_parts(
|
||||
gen = dl.dispatch_parts(
|
||||
url=_url(server),
|
||||
save_path=save_path,
|
||||
session=Session(),
|
||||
@@ -157,8 +157,8 @@ def test_ranged_part_failure_stays_local(server, tmp_path, monkeypatch):
|
||||
def test_probe_ranged_parses_content_range(server):
|
||||
session = Session()
|
||||
server.mode = "range"
|
||||
assert dl._probe_ranged(_url(server), session) == (len(PAYLOAD), True)
|
||||
assert dl.probe_ranged(_url(server), session) == (len(PAYLOAD), True)
|
||||
server.mode = "always_200"
|
||||
assert dl._probe_ranged(_url(server), session) == (0, False)
|
||||
assert dl.probe_ranged(_url(server), session) == (0, False)
|
||||
server.mode = "gzip_probe"
|
||||
assert dl._probe_ranged(_url(server), session) == (0, False)
|
||||
assert dl.probe_ranged(_url(server), session) == (0, False)
|
||||
|
||||
@@ -113,11 +113,11 @@ def test_locked_limit_ignores_unlocked_calls():
|
||||
set_speed_limit(5_000_000, lock=True)
|
||||
set_speed_limit(None)
|
||||
set_speed_limit(1_000_000)
|
||||
limiter = requests_downloader._speed_limiter
|
||||
limiter = requests_downloader.speed_limiter
|
||||
assert limiter is not None and limiter.rate == 5_000_000
|
||||
finally:
|
||||
requests_downloader._speed_limit_locked = False
|
||||
requests_downloader._speed_limiter = None
|
||||
requests_downloader.speed_limit_locked = False
|
||||
requests_downloader.speed_limiter = None
|
||||
|
||||
|
||||
def test_bucket_wait_aborts_on_cancellation():
|
||||
|
||||
@@ -17,7 +17,7 @@ Determinism: with ``max_workers`` < segment count <= 2*max_workers and adaptive=
|
||||
the leading ``max_workers`` segments submit upfront and the trailing few stay in
|
||||
``remaining`` (the tail top-up only releases boost-declined indices). The controller
|
||||
starts at the cap and never grows, so as soon as two leaders finish the spare workers
|
||||
outnumber the tail and ``_tail_boost_engages`` fires. Module timing/size constants are
|
||||
outnumber the tail and ``tail_boost_engages`` fires. Module timing/size constants are
|
||||
lowered via monkeypatch; the whole batch runs in-process (threads), so the patched
|
||||
values are seen by the workers.
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user