mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-22 17:05:05 +00:00
fix(downloader): harden ranged reads, teardown and multiprocess sessions
Validates the 206 range end, bounds the DASH collapse, and preserves cookie domains and pool size in spawned children.
This commit is contained in:
@@ -6,7 +6,7 @@ import pytest
|
||||
import requests as rq
|
||||
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED
|
||||
from unshackle.core.downloaders.requests import download, has_range_header, parse_content_range, request_range_start
|
||||
from unshackle.core.downloaders.requests import download, has_range_header, parse_content_range, request_range
|
||||
from unshackle.core.downloaders.requests import requests as requests_downloader
|
||||
|
||||
# the package re-exports the `requests` function, shadowing the module of the same name
|
||||
@@ -76,6 +76,12 @@ class _Server:
|
||||
self.send_206(conn, BODY[5:], f"bytes 5-{len(BODY) - 1}/{len(BODY)}")
|
||||
elif self.mode == "resume_missing_content_range":
|
||||
self.send_206(conn, BODY)
|
||||
elif self.mode == "range_capped_206":
|
||||
# honors the requested start but caps the span, as size-capping CDNs do
|
||||
start, _, end = headers["range"].removeprefix("bytes=").partition("-")
|
||||
start, end = int(start), int(end)
|
||||
capped = start + (end - start) // 2
|
||||
self.send_206(conn, BODY[start : capped + 1], f"bytes {start}-{capped}/{len(BODY)}")
|
||||
else:
|
||||
conn.sendall(
|
||||
b"HTTP/1.1 416 Range Not Satisfiable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
|
||||
@@ -197,6 +203,23 @@ def test_slice_segment_rejects_a_206_for_the_wrong_range(tmp_path, server):
|
||||
assert len(server.requests) == downloader.MAX_ATTEMPTS
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["range_capped_206"], indirect=True)
|
||||
def test_slice_segment_rejects_a_206_capped_short_of_the_requested_end(tmp_path, server):
|
||||
# the body is a valid prefix of the slice, so only the Content-Range end catches it;
|
||||
# writing it would finalize a truncated segment and corrupt the merge
|
||||
save_path = tmp_path / "0.mp4"
|
||||
with pytest.raises(OSError):
|
||||
list(
|
||||
download(
|
||||
url=server.url,
|
||||
save_path=save_path,
|
||||
session=rq.Session(),
|
||||
headers={"Range": f"bytes=0-{len(BODY) - 1}"},
|
||||
)
|
||||
)
|
||||
assert not save_path.exists()
|
||||
|
||||
|
||||
@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"
|
||||
@@ -295,9 +318,9 @@ def test_parse_content_range(value, expected):
|
||||
({}, None),
|
||||
({"Accept": "*/*"}, None),
|
||||
({"Range": "bytes=-500"}, None),
|
||||
({"Range": "bytes=100-"}, 100),
|
||||
({"range": "bytes=100-227"}, 100),
|
||||
({"Range": "bytes=100-"}, (100, None)),
|
||||
({"range": "bytes=100-227"}, (100, 227)),
|
||||
],
|
||||
)
|
||||
def test_request_range_start(headers, expected):
|
||||
assert request_range_start(headers) == expected
|
||||
def test_request_range(headers, expected):
|
||||
assert request_range(headers) == expected
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Session spec fidelity across the multiprocess spawn boundary.
|
||||
|
||||
``build_session_spec``/``rebuild_session`` are how a spawned child gets the parent's session
|
||||
state. The cross-process half needs a live CDN to observe, so these tests pin the two halves
|
||||
that can be checked deterministically: the spec is picklable (spawn requires it), and a
|
||||
rebuilt session carries the same cookie domains as the parent. A spec that flattens cookies
|
||||
to name/value rebuilds every cookie scoped to localhost, so a cookie-authed CDN sees none of
|
||||
them and 403s only when ``--download-processes`` is above 1.
|
||||
"""
|
||||
|
||||
import pickle
|
||||
|
||||
from requests import Session
|
||||
|
||||
from unshackle.core.downloaders.requests import build_session_spec, rebuild_session
|
||||
from unshackle.core.session import RnetSession
|
||||
from unshackle.core.session import session as make_session
|
||||
|
||||
|
||||
def rnet_session_with_cookies() -> RnetSession:
|
||||
"""RnetSession carrying two domain-scoped cookies plus one set from a plain dict.
|
||||
|
||||
The dict-set cookie lands in the adapter's flat map only, never in its domain map, so it
|
||||
is the case a domain-only serialization would silently drop.
|
||||
"""
|
||||
ns = make_session("Chrome131")
|
||||
ns.cookies.set("cdn_token", "abc", domain="cdn.example.com")
|
||||
ns.cookies.set("api_token", "def", domain="api.example.com")
|
||||
ns.cookies.update({"loose": "ghi"})
|
||||
return ns
|
||||
|
||||
|
||||
def test_rnet_spec_round_trips_cookie_domains() -> None:
|
||||
ns = rnet_session_with_cookies()
|
||||
|
||||
spec = build_session_spec(ns)
|
||||
assert spec is not None
|
||||
rebuilt = rebuild_session(pickle.loads(pickle.dumps(spec)), 1)
|
||||
assert rebuilt is not None
|
||||
|
||||
assert rebuilt.cookies.get_dict_by_domain() == ns.cookies.get_dict_by_domain()
|
||||
assert rebuilt.cookies.get_dict() == ns.cookies.get_dict()
|
||||
assert rebuilt.cookies.get("cdn_token", domain="cdn.example.com") == "abc"
|
||||
assert rebuilt.cookies.get("api_token", domain="api.example.com") == "def"
|
||||
assert rebuilt.cookies.get_dict(domain="localhost") == {}
|
||||
|
||||
|
||||
def test_rnet_spec_keeps_dict_set_cookies() -> None:
|
||||
ns = rnet_session_with_cookies()
|
||||
|
||||
spec = build_session_spec(ns)
|
||||
assert spec is not None
|
||||
rebuilt = rebuild_session(spec, 1)
|
||||
assert rebuilt is not None
|
||||
|
||||
assert rebuilt.cookies["loose"] == "ghi"
|
||||
|
||||
|
||||
def test_rnet_spec_cookies_carry_domain_information() -> None:
|
||||
ns = rnet_session_with_cookies()
|
||||
|
||||
spec = build_session_spec(ns)
|
||||
assert spec is not None
|
||||
|
||||
cookies = spec["cookies"]
|
||||
assert set(cookies) == {"cdn.example.com", "api.example.com", ""}
|
||||
assert all(isinstance(jar, dict) for jar in cookies.values())
|
||||
assert cookies["cdn.example.com"] == {"cdn_token": "abc"}
|
||||
|
||||
|
||||
def test_rnet_spec_is_picklable() -> None:
|
||||
spec = build_session_spec(rnet_session_with_cookies())
|
||||
assert spec is not None
|
||||
|
||||
assert pickle.loads(pickle.dumps(spec)) == spec
|
||||
|
||||
|
||||
def test_rnet_spec_without_impersonate_is_not_rebuildable() -> None:
|
||||
assert build_session_spec(RnetSession()) is None
|
||||
|
||||
|
||||
def test_rebuilt_requests_session_pool_is_sized_to_worker_count() -> None:
|
||||
"""A child rebuilding a requests session must size its pool, not inherit urllib3's default 10."""
|
||||
spec = build_session_spec(Session())
|
||||
assert spec is not None
|
||||
|
||||
rebuilt = rebuild_session(spec, 24)
|
||||
assert rebuilt is not None
|
||||
|
||||
for scheme in ("https://example.com", "http://example.com"):
|
||||
adapter = rebuilt.get_adapter(scheme)
|
||||
assert adapter._pool_maxsize == 24
|
||||
assert adapter._pool_connections == 24
|
||||
assert adapter._pool_block is True
|
||||
assert adapter.poolmanager.connection_pool_kw["maxsize"] == 24
|
||||
|
||||
|
||||
def test_rebuilt_rnet_session_has_no_adapters() -> None:
|
||||
"""rnet pools internally; the sizing fix must not reach into that path."""
|
||||
spec = build_session_spec(rnet_session_with_cookies())
|
||||
assert spec is not None
|
||||
|
||||
rebuilt = rebuild_session(spec, 24)
|
||||
assert rebuilt is not None
|
||||
|
||||
assert not isinstance(rebuilt, Session)
|
||||
assert not hasattr(rebuilt, "adapters")
|
||||
|
||||
|
||||
def test_unrebuildable_spec_stays_none() -> None:
|
||||
assert rebuild_session({"kind": "none"}, 24) is None
|
||||
|
||||
|
||||
def test_requests_spec_round_trips_cookie_domains() -> None:
|
||||
rs = Session()
|
||||
rs.cookies.set("cdn_token", "abc", domain="cdn.example.com")
|
||||
rs.cookies.set("api_token", "def", domain="api.example.com")
|
||||
|
||||
spec = build_session_spec(rs)
|
||||
assert spec is not None
|
||||
rebuilt = rebuild_session(pickle.loads(pickle.dumps(spec)), 1)
|
||||
assert rebuilt is not None
|
||||
|
||||
assert rebuilt.cookies.get_dict(domain="cdn.example.com") == {"cdn_token": "abc"}
|
||||
assert rebuilt.cookies.get_dict(domain="api.example.com") == {"api_token": "def"}
|
||||
Reference in New Issue
Block a user