refactor(downloader): put one transport adapter per HTTP session kind under download()

This commit is contained in:
imSp4rky
2026-12-04 14:21:18 -07:00
parent 9e8647dd38
commit 6d04d19239
6 changed files with 303 additions and 109 deletions
+1 -2
View File
@@ -147,12 +147,11 @@ class _FakeRnetSession:
def test_rnet_encoded_body_discards_a_partial_instead_of_range_resuming(tmp_path, monkeypatch): def test_rnet_encoded_body_discards_a_partial_instead_of_range_resuming(tmp_path, monkeypatch):
dl = importlib.import_module("unshackle.core.downloaders.requests") dl = importlib.import_module("unshackle.core.downloaders.requests")
monkeypatch.setattr(dl, "is_rnet_session", lambda s: isinstance(s, _FakeRnetSession))
monkeypatch.setattr(dl, "RETRY_WAIT", 0) monkeypatch.setattr(dl, "RETRY_WAIT", 0)
session = _FakeRnetSession(PLAIN) session = _FakeRnetSession(PLAIN)
save_path = tmp_path / "sub.vtt" save_path = tmp_path / "sub.vtt"
save_path.with_name("sub.vtt.!dev").write_bytes(PLAIN[:5000]) save_path.with_name("sub.vtt.!dev").write_bytes(PLAIN[:5000])
list(download(url="http://127.0.0.1:1/sub.vtt", save_path=save_path, session=session)) list(download(url="http://127.0.0.1:1/sub.vtt", save_path=save_path, session=dl.RnetTransport(session)))
# the encoded 206 must be dropped, not appended; the clean restart fetches the whole body # the encoded 206 must be dropped, not appended; the clean restart fetches the whole body
assert session.range_requests == 1 assert session.range_requests == 1
assert save_path.read_bytes() == PLAIN assert save_path.read_bytes() == PLAIN
+1 -2
View File
@@ -170,12 +170,11 @@ class _RecoveringSession:
def test_outage_does_not_spend_the_status_budget(tmp_path, monkeypatch): 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) monkeypatch.setattr(dl, "retry_sleep", lambda exc, attempts: 0)
session = _RecoveringSession() session = _RecoveringSession()
save_path = tmp_path / "a.bin" save_path = tmp_path / "a.bin"
list(dl.download(url="http://127.0.0.1:1/a", save_path=save_path, session=session)) list(dl.download(url="http://127.0.0.1:1/a", save_path=save_path, session=dl.RnetTransport(session)))
assert save_path.read_bytes() == b"body-bytes" assert save_path.read_bytes() == b"body-bytes"
assert session.calls == 8 assert session.calls == 8
@@ -23,8 +23,7 @@ class FakeSession:
@pytest.fixture @pytest.fixture
def session(monkeypatch): def session():
monkeypatch.setattr(dl, "is_rnet_session", lambda s: isinstance(s, FakeSession))
return FakeSession() return FakeSession()
@@ -41,11 +40,12 @@ def test_segment_request_read_timeout(tmp_path, session, monkeypatch, network, m
monkeypatch.setattr(config, "network", network) monkeypatch.setattr(config, "network", network)
if module_default is not None: if module_default is not None:
monkeypatch.setattr(dl, "READ_TIMEOUT", module_default) 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)) transport = dl.RnetTransport(session)
list(dl.download(url="http://127.0.0.1:1/a", save_path=tmp_path / "a.bin", session=transport, **kwargs))
assert session.calls[0]["read_timeout"] == expected assert session.calls[0]["read_timeout"] == expected
def test_probe_uses_the_configured_read_timeout(session, monkeypatch): def test_probe_uses_the_configured_read_timeout(session, monkeypatch):
monkeypatch.setattr(config, "network", {"read_timeout": 7}) monkeypatch.setattr(config, "network", {"read_timeout": 7})
dl.probe_ranged("http://127.0.0.1:1/a", session) dl.probe_ranged("http://127.0.0.1:1/a", dl.RnetTransport(session))
assert session.calls[0]["read_timeout"] == 7 assert session.calls[0]["read_timeout"] == 7
@@ -145,6 +145,18 @@ def test_stalled_body_times_out_and_retries(tmp_path, server, make_session, monk
assert len(server.hits) == 2 assert len(server.hits) == 2
@pytest.mark.parametrize("make_session", SESSIONS)
def test_transport_body_reads_headers_in_any_case(server, make_session):
body = dl.transport_for(make_session()).get(f"{server.url}/plain", headers={"Range": "bytes=0-9"})
try:
assert body.status_code == 206
assert body.header("content-range") == body.header("CONTENT-RANGE") == f"bytes 0-9/{len(BODY)}"
assert body.content_length == 10
assert b"".join(body.chunks(4, None)) == BODY[:10]
finally:
body.close()
def test_complete_file_is_reported_without_a_request(tmp_path, server): def test_complete_file_is_reported_without_a_request(tmp_path, server):
save_path = tmp_path / "0.mp4" save_path = tmp_path / "0.mp4"
save_path.write_bytes(b"x" * 10) save_path.write_bytes(b"x" * 10)
+128
View File
@@ -0,0 +1,128 @@
"""Each session kind's transport switches session retries and the request record off, and reads the body its own way."""
import importlib
import io
import pytest
import requests as rq
from unshackle.core.session import RnetSession
dl = importlib.import_module("unshackle.core.downloaders.requests")
class _Response:
def __init__(self, headers=None, body=b"abcdef"):
self.status_code = 200
self.headers = rq.structures.CaseInsensitiveDict(headers or {})
self.raw = _Raw(body)
self.body = body
self.content_length = len(body)
def raise_for_status(self):
pass
def close(self):
pass
def iter_content(self, chunk_size):
yield self.body
class _Raw(io.BytesIO):
def __init__(self, body):
super().__init__(body)
self.calls: list[str] = []
def read(self, size=-1):
self.calls.append("read")
return super().read(size)
def read1(self, size=-1):
self.calls.append("read1")
return super().read1(size)
class _Session:
def __init__(self, response=None):
self.calls: list[dict] = []
self.response = response or _Response()
def get(self, url, **kwargs):
self.calls.append(kwargs)
return self.response
def test_each_session_kind_gets_its_transport():
assert isinstance(dl.transport_for(RnetSession()), dl.RnetTransport)
assert isinstance(dl.transport_for(rq.Session()), dl.RequestsTransport)
transport = dl.RnetTransport(_Session())
assert dl.transport_for(transport) is transport
def test_requests_transport_has_no_retries_and_no_record():
session = rq.Session()
view = dl.transport_for(session).session
assert view is not session
assert view.record_request is False
assert all(adapter.max_retries.total == 0 for adapter in view.adapters.values())
class _RnetSession(RnetSession):
def __init__(self):
super().__init__()
self.calls: list[dict] = []
def get(self, url, **kwargs):
self.calls.append(kwargs)
return _Response()
def test_rnet_transport_turns_retries_and_record_off():
session = _RnetSession()
dl.transport_for(session).get("http://127.0.0.1:1/a")
assert session.calls[0]["max_retries"] == 0
assert session.calls[0]["record_request"] is False
assert session.calls[0]["stream"] is True
def test_requests_body_reads_raw_and_read1_only_while_racing():
response = _Response({"Content-Length": "6"})
body = dl.RequestsBody(response, raw=True)
racing = iter([True, False, False])
assert b"".join(body.chunks(2, lambda: next(racing))) == b"abcdef"
assert response.raw.calls == ["read1", "read", "read"]
class _Transport(dl.Transport):
def __init__(self):
self.response = _Response({"Content-Length": "6"})
def get(self, url, **kwargs):
return dl.RequestsBody(self.response, raw=True)
@pytest.mark.parametrize("claimed, expected", [(None, {"read"}), (lambda: False, {"read1"})])
def test_download_reads_read1_only_for_a_claimable_segment(tmp_path, claimed, expected):
transport = _Transport()
events = dl.download("http://127.0.0.1:1/a", tmp_path / "a.bin", transport, claimed=claimed, racing=lambda: True)
list(events)
assert (tmp_path / "a.bin").read_bytes() == b"abcdef"
assert set(transport.response.raw.calls) == expected
def test_an_encoded_body_goes_through_iter_content():
response = _Response({"content-encoding": "gzip", "Content-Length": "6"})
body = dl.RequestsBody(response, raw=True)
assert body.content_encoded
assert body.content_length == 0
assert list(body.chunks(2, None)) == [b"abcdef"]
assert response.raw.calls == []
def test_another_session_kind_is_read_with_iter_content_and_a_timeout():
session = _Session()
transport = dl.transport_for(session)
assert transport.session is session
assert list(transport.get("http://127.0.0.1:1/a").chunks(2, None)) == [b"abcdef"]
assert session.calls[0]["timeout"] == (dl.CONNECT_TIMEOUT, dl.READ_TIMEOUT)
+153 -97
View File
@@ -12,7 +12,7 @@ import threading
import time import time
import traceback import traceback
from collections import OrderedDict, deque from collections import OrderedDict, deque
from collections.abc import Callable, Collection, Generator, MutableMapping from collections.abc import Callable, Collection, Generator, Iterator, MutableMapping
from concurrent.futures import FIRST_COMPLETED, wait from concurrent.futures import FIRST_COMPLETED, wait
from concurrent.futures.thread import ThreadPoolExecutor from concurrent.futures.thread import ThreadPoolExecutor
from copy import copy from copy import copy
@@ -444,6 +444,132 @@ def is_rnet_session(session: Any) -> bool:
return isinstance(session, RnetSession) return isinstance(session, RnetSession)
class Body:
"""One streamed media response as download() and probe_ranged read it.
header() relies on the case-insensitive headers of both HTTP session kinds. ``content_length`` is the declared
body length, 0 when unknown or encoded.
"""
content_length = 0
def __init__(self, resp: Any) -> None:
self.resp = resp
self.status_code: int = resp.status_code
self.content_encoded = is_content_encoded(self.header("Content-Encoding"))
def header(self, name: str) -> str | None:
return cast("str | None", self.resp.headers.get(name))
def raise_for_status(self) -> None:
self.resp.raise_for_status()
def read(self) -> bytes:
return cast(bytes, self.resp.content)
def chunks(self, chunk_size: int, racing: Callable[[], bool] | None) -> Iterator[bytes]:
"""The body as an iterator of chunks; ``racing`` is set only for a segment a hedge may supersede."""
raise NotImplementedError
def close(self) -> None:
self.resp.close()
def unblock(self) -> None:
"""Make a thread parked in a blocking read of this body return now, where the HTTP session kind allows it.
A superseded hedge loser can sit in a full-chunk read on a slow connection, and the batch's wait-gated
shutdown would otherwise drain that whole read before the merge sweep. rnet exposes no reachable socket.
"""
class RnetBody(Body):
def __init__(self, resp: Any) -> None:
super().__init__(resp)
self.content_length = 0 if self.content_encoded else (resp.content_length or 0)
def chunks(self, chunk_size: int, racing: Callable[[], bool] | None) -> Iterator[bytes]:
return cast(Iterator[bytes], self.resp.stream())
class RequestsBody(Body):
"""A requests body: the raw socket, or iter_content for a content-encoded body or an HTTP session without ``raw``.
Reading .raw skips urllib3's decoding, so only iter_content gives the decoded bytes of an encoded body.
"""
def __init__(self, resp: Any, raw: bool) -> None:
super().__init__(resp)
self.raw = raw and not self.content_encoded
try:
self.content_length = 0 if self.content_encoded else int(self.header("Content-Length") or 0)
except ValueError:
self.content_length = 0
def chunks(self, chunk_size: int, racing: Callable[[], bool] | None) -> Iterator[bytes]:
"""read1 (one network arrival per read) only while ``racing()``.
A superseded loser then sees ``claimed()`` mid-read.
"""
if not self.raw:
return cast(Iterator[bytes], self.resp.iter_content(chunk_size=chunk_size))
raw = self.resp.raw
read1 = getattr(raw, "read1", None)
if read1 is not None and racing is not None:
read = raw.read
return iter(lambda: read1(chunk_size) if racing() else read(chunk_size), b"")
return iter(partial(raw.read, chunk_size), b"")
def unblock(self) -> None:
"""Shut the socket so a thread parked in a blocking raw read returns now; it ignores a failure."""
try:
self.resp.raw._fp.fp.raw._sock.shutdown(socket.SHUT_RDWR)
except Exception:
pass
class Transport:
"""One HTTP session kind as the downloader sees it: a media GET with no session retries and no record entry.
download() keeps its own retries above this seam.
"""
def get(self, url: str, **kwargs: Any) -> Body:
raise NotImplementedError
class RnetTransport(Transport):
"""An RnetSession: per-request max_retries=0, unrecorded(), and the configured read timeout."""
def __init__(self, session: Any) -> None:
self.session = session
def get(self, url: str, **kwargs: Any) -> Body:
kwargs.setdefault("read_timeout", rnet_read_timeout())
from unshackle.core.session import unrecorded
kwargs.setdefault("max_retries", 0)
return RnetBody(unrecorded(self.session, "get", url, stream=True, **kwargs))
class RequestsTransport(Transport):
"""A requests.Session through no_retry_session(); any other session as it is, read with iter_content."""
def __init__(self, session: Any) -> None:
self.raw = is_requests_session(session)
self.session = no_retry_session(session) if self.raw else session
def get(self, url: str, **kwargs: Any) -> Body:
kwargs.setdefault("timeout", (CONNECT_TIMEOUT, READ_TIMEOUT))
return RequestsBody(self.session.get(url, stream=True, **kwargs), self.raw)
def transport_for(session: Any) -> Transport:
"""The transport for ``session``; a Transport passes through, so a caller or test can supply its own."""
if isinstance(session, Transport):
return session
return RnetTransport(session) if is_rnet_session(session) else RequestsTransport(session)
def is_outage(exc: BaseException) -> bool: def is_outage(exc: BaseException) -> bool:
"""Whether a failure reached no server: a refused or unreachable connection, or a failed name lookup. """Whether a failure reached no server: a refused or unreachable connection, or a failed name lookup.
@@ -476,31 +602,23 @@ def probe_ranged(url: str, session: Any, **kwargs: Any) -> tuple[int, bool]:
if not any(str(k).lower() == "accept-encoding" for k in headers): if not any(str(k).lower() == "accept-encoding" for k in headers):
headers["Accept-Encoding"] = "identity" headers["Accept-Encoding"] = "identity"
rest = {k: v for k, v in kwargs.items() if k != "headers"} rest = {k: v for k, v in kwargs.items() if k != "headers"}
if is_rnet_session(session):
rest.setdefault("read_timeout", rnet_read_timeout())
# let download() own segment retries, with no nested session-level retry loop
rest.setdefault("max_retries", 0)
rest.setdefault("record_request", False)
else:
rest.setdefault("timeout", (CONNECT_TIMEOUT, READ_TIMEOUT))
session = no_retry_session(session)
try: try:
resp = session.get(url, stream=True, headers=headers, **rest) resp = transport_for(session).get(url, headers=headers, **rest)
except Exception: except Exception:
return 0, False return 0, False
try: try:
if resp.status_code != 206: if resp.status_code != 206:
return 0, False return 0, False
if is_content_encoded(resp.headers.get("Content-Encoding") or resp.headers.get("content-encoding")): if resp.content_encoded:
return 0, False return 0, False
content_range = resp.headers.get("Content-Range") or resp.headers.get("content-range") or "" content_range = resp.header("Content-Range") or ""
total = content_range.rsplit("/", 1)[-1].strip() total = content_range.rsplit("/", 1)[-1].strip()
return (int(total), True) if total.isdigit() else (0, False) return (int(total), True) if total.isdigit() else (0, False)
finally: finally:
try: try:
declared = int(resp.headers.get("Content-Length") or resp.headers.get("content-length") or 0) declared = int(resp.header("Content-Length") or 0)
if resp.status_code == 206 and 0 < declared <= PROBE_DRAIN_LIMIT: if resp.status_code == 206 and 0 < declared <= PROBE_DRAIN_LIMIT:
_ = resp.content resp.read()
except Exception: except Exception:
pass pass
try: try:
@@ -594,22 +712,6 @@ def request_range(headers: MutableMapping[str, Any]) -> tuple[int, int | None] |
return int(match.group(1)), int(match.group(2)) if match.group(2) else None return int(match.group(1)), int(match.group(2)) if match.group(2) else None
def force_unblock_stream(stream: Any) -> None:
"""Best-effort: shut the stream's socket so a thread parked in a blocking read returns now.
A superseded hedge loser can sit in a full-chunk ``raw.read`` on a slow connection. The
batch's wait-gated shutdown (which guarantees that every thread has closed its file before
the merge sweep) would otherwise drain that whole slow read. ``socket.shutdown`` makes the
read return at once so the loser unwinds and closes its ``.!dev`` handle immediately.
Requests/urllib3 only (rnet exposes no reachable socket). This function ignores any failure,
and the caller falls back to waiting.
"""
try:
stream.raw._fp.fp.raw._sock.shutdown(socket.SHUT_RDWR)
except Exception:
pass
def split_ranges(size: int, max_parts: int | None, part_target: int) -> list[tuple[int, int]]: def split_ranges(size: int, max_parts: int | None, part_target: int) -> list[tuple[int, int]]:
"""Split ``[0, size)`` into inclusive ``[start, end]`` byte ranges with no gaps or overlaps. """Split ``[0, size)`` into inclusive ``[start, end]`` byte ranges with no gaps or overlaps.
@@ -784,7 +886,7 @@ def download(
racing: Callable[[], bool] | None = None, racing: Callable[[], bool] | None = None,
abort: threading.Event | None = None, abort: threading.Event | None = None,
on_retry: Callable[[Exception], None] | None = None, on_retry: Callable[[Exception], None] | None = None,
register: Callable[[Any, bool], None] | None = None, register: Callable[[Body, bool], None] | None = None,
**kwargs: Any, **kwargs: Any,
) -> Generator[dict[str, Any], None, None]: ) -> Generator[dict[str, Any], None, None]:
""" """
@@ -806,7 +908,7 @@ def download(
url: Web URL of a file to download. url: Web URL of a file to download.
save_path: The path to save the file to. If the save path's directory does not save_path: The path to save the file to. If the save path's directory does not
exist then it will be made automatically. exist then it will be made automatically.
session: A requests.Session or RnetSession to make HTTP requests with. session: A requests.Session or RnetSession to make HTTP requests with, or a Transport.
RnetSession preserves TLS fingerprinting for services that need it. RnetSession preserves TLS fingerprinting for services that need it.
segmented: If downloads are segments or parts of one bigger file. segmented: If downloads are segments or parts of one bigger file.
part_offset: Byte offset to write at within a pre-allocated file. When set part_offset: Byte offset to write at within a pre-allocated file. When set
@@ -831,16 +933,13 @@ def download(
the ``AdaptiveWorkerController``. The downloader ignores callback errors. the ``AdaptiveWorkerController``. The downloader ignores callback errors.
register: Optional callback ``(stream, active)`` invoked with active=True while the register: Optional callback ``(stream, active)`` invoked with active=True while the
downloader reads a response, and with active=False when that read ends. Lets the batch reach downloader reads a response, and with active=False when that read ends. Lets the batch reach
a superseded loser's socket to unblock its in-flight read at teardown (see a superseded loser's socket to unblock its in-flight read at teardown (see Body.unblock) instead of
force_unblock_stream) instead of waiting the slow read out. waiting the slow read out.
kwargs: Any extra keyword arguments to pass to the session.get() call. Use this kwargs: Any extra keyword arguments to pass to the session.get() call. Use this
for one-time request changes like a header, cookie, or proxy. For example, for one-time request changes like a header, cookie, or proxy. For example,
to request Byte-ranges use e.g., `headers={"Range": "bytes=0-128"}`. to request Byte-ranges use e.g., `headers={"Range": "bytes=0-128"}`.
""" """
session = session or Session() transport = transport_for(session or Session())
if is_requests_session(session):
# same reason as the rnet max_retries=0 below: download() owns segment retries
session = no_retry_session(session)
part_mode = part_offset is not None and part_end is not None part_mode = part_offset is not None and part_end is not None
# partial data lives at the .!dev name and is renamed into place on completion: # partial data lives at the .!dev name and is renamed into place on completion:
@@ -863,7 +962,6 @@ def download(
resume_offset = tmp_file.stat().st_size resume_offset = tmp_file.stat().st_size
_time = time.monotonic _time = time.monotonic
use_raw = is_requests_session(session)
item_range = has_range_header(kwargs) item_range = has_range_header(kwargs)
attempts = 1 attempts = 1
@@ -888,18 +986,9 @@ def download(
resume_start = resume_offset resume_start = resume_offset
last_speed_refresh = _time() last_speed_refresh = _time()
stream: Any = None stream: Body | None = None
try: try:
use_rnet = is_rnet_session(session)
request_kwargs = dict(kwargs) request_kwargs = dict(kwargs)
if use_rnet:
request_kwargs.setdefault("read_timeout", rnet_read_timeout())
# own segment retries here, suppressing RnetSession's nested retry loop
request_kwargs.setdefault("max_retries", 0)
request_kwargs.setdefault("record_request", False)
else:
request_kwargs.setdefault("timeout", (CONNECT_TIMEOUT, READ_TIMEOUT))
req_headers = dict(request_kwargs.get("headers", {}) or {}) req_headers = dict(request_kwargs.get("headers", {}) or {})
# media bytes must arrive unrecoded: transparent CDN (de)compression breaks # media bytes must arrive unrecoded: transparent CDN (de)compression breaks
# Content-Length accounting and is meaningless on ranged requests # Content-Length accounting and is meaningless on ranged requests
@@ -925,12 +1014,10 @@ def download(
req_headers["Range"] = f"bytes={resume_offset}-" req_headers["Range"] = f"bytes={resume_offset}-"
request_kwargs["headers"] = req_headers request_kwargs["headers"] = req_headers
stream = session.get(url, stream=True, **request_kwargs) stream = transport.get(url, **request_kwargs)
if (not part_mode) and (not item_range) and resume_offset > 0 and stream.status_code == 416: if (not part_mode) and (not item_range) and resume_offset > 0 and stream.status_code == 416:
complete = parse_content_range_unsatisfied( complete = parse_content_range_unsatisfied(stream.header("Content-Range"))
stream.headers.get("Content-Range") or stream.headers.get("content-range")
)
try: try:
stream.close() stream.close()
except Exception: except Exception:
@@ -954,9 +1041,7 @@ def download(
# item_range 206s reflect the slice's own Range, not a resume; those retries rewrite in "wb" # item_range 206s reflect the slice's own Range, not a resume; those retries rewrite in "wb"
resumed = (not part_mode) and (not item_range) and resume_offset > 0 and stream.status_code == 206 resumed = (not part_mode) and (not item_range) and resume_offset > 0 and stream.status_code == 206
if resumed: if resumed:
content_range = parse_content_range( content_range = parse_content_range(stream.header("Content-Range"))
stream.headers.get("Content-Range") or stream.headers.get("content-range")
)
if content_range is None or content_range[0] != resume_offset: if content_range is None or content_range[0] != resume_offset:
# some servers answer `bytes=X-` with a 206 for the whole resource; # some servers answer `bytes=X-` with a 206 for the whole resource;
# appending that body would misplace every byte after the partial. A # appending that body would misplace every byte after the partial. A
@@ -977,9 +1062,7 @@ def download(
if part_mode and part_offset is not None and part_end is not None: # spelled so mypy narrows if part_mode and part_offset is not None and part_end is not None: # spelled so mypy narrows
if stream.status_code != 206: if stream.status_code != 206:
raise OSError(f"expected 206 for ranged part, got {stream.status_code}") raise OSError(f"expected 206 for ranged part, got {stream.status_code}")
content_range = parse_content_range( content_range = parse_content_range(stream.header("Content-Range"))
stream.headers.get("Content-Range") or stream.headers.get("content-range")
)
if ( if (
content_range is None content_range is None
or content_range[0] != part_offset + written or content_range[0] != part_offset + written
@@ -991,28 +1074,14 @@ def download(
# part's region, and a total at or below part_end means the resource # part's region, and a total at or below part_end means the resource
# changed under the part plan; fail the attempt before any byte is written # changed under the part plan; fail the attempt before any byte is written
raise OSError(f"part {part_offset}-{part_end} got Content-Range {content_range!r}") raise OSError(f"part {part_offset}-{part_end} got Content-Range {content_range!r}")
if use_rnet: content_length = stream.content_length
content_encoded = is_content_encoded(
stream.headers.get("Content-Encoding") or stream.headers.get("content-encoding")
)
content_length = 0 if content_encoded else (stream.content_length or 0)
else:
content_encoded = is_content_encoded(stream.headers.get("Content-Encoding"))
try:
content_length = int(stream.headers.get("Content-Length", "0"))
if content_encoded:
content_length = 0
except ValueError:
content_length = 0
if known_total is None and not part_mode and not item_range and stream.status_code == 200: if known_total is None and not part_mode and not item_range and stream.status_code == 200:
# a 200 carries the whole resource, so its length is the complete length # a 200 carries the whole resource, so its length is the complete length
known_total = content_length or None known_total = content_length or None
if known_total is None and not part_mode and not item_range and stream.status_code == 206: if known_total is None and not part_mode and not item_range and stream.status_code == 206:
fresh_range = parse_content_range( fresh_range = parse_content_range(stream.header("Content-Range"))
stream.headers.get("Content-Range") or stream.headers.get("content-range")
)
if fresh_range is not None: if fresh_range is not None:
if fresh_range[0] != resume_offset: if fresh_range[0] != resume_offset:
raise OSError(f"206 body starts at byte {fresh_range[0]}, expected {resume_offset}") raise OSError(f"206 body starts at byte {fresh_range[0]}, expected {resume_offset}")
@@ -1033,18 +1102,16 @@ def download(
slice_range = request_range(req_headers) slice_range = request_range(req_headers)
if slice_range is not None: if slice_range is not None:
slice_start, slice_end = slice_range slice_start, slice_end = slice_range
content_range = parse_content_range( content_range = parse_content_range(stream.header("Content-Range"))
stream.headers.get("Content-Range") or stream.headers.get("content-range")
)
if content_range is None or not range_answers(content_range, slice_range): if content_range is None or not range_answers(content_range, slice_range):
raise OSError( raise OSError(
f"byte-range segment got Content-Range {content_range!r}, " f"byte-range segment got Content-Range {content_range!r}, "
f"expected {slice_start}-{slice_end if slice_end is not None else ''}" f"expected {slice_start}-{slice_end if slice_end is not None else ''}"
) )
if not content_encoded: if not stream.content_encoded:
content_length = content_range[1] - content_range[0] + 1 content_length = content_range[1] - content_range[0] + 1
if resumed and content_encoded: if resumed and stream.content_encoded:
tmp_file.unlink(missing_ok=True) tmp_file.unlink(missing_ok=True)
raise OSError(f"resume from byte {resume_offset} came back content-encoded") raise OSError(f"resume from byte {resume_offset} came back content-encoded")
@@ -1083,19 +1150,7 @@ def download(
_write = f.write _write = f.write
if use_rnet: chunks = stream.chunks(chunk_size, racing if claimed is not None else None)
chunks = stream.stream()
elif use_raw and not content_encoded:
_read1 = getattr(stream.raw, "read1", None) if claimed is not None else None
if _read1 is not None and racing is not None:
# only pay the per-arrival read1 tax while this segment is actually
# racing; a blocking full-chunk read otherwise (the common case)
_raw_read = stream.raw.read
chunks = iter(lambda: _read1(chunk_size) if racing() else _raw_read(chunk_size), b"") # noqa: B023
else:
chunks = iter(partial(stream.raw.read, chunk_size), b"")
else:
chunks = stream.iter_content(chunk_size=chunk_size)
_data_accumulated = 0 _data_accumulated = 0
_bytes_since_yield = 0 _bytes_since_yield = 0
@@ -1187,6 +1242,7 @@ def download(
yield dict(advance=1) yield dict(advance=1)
break break
except Exception as exc: except Exception as exc:
if stream is not None:
try: try:
stream.close() stream.close()
except Exception: except Exception:
@@ -1862,11 +1918,11 @@ def requests(
batch_abort = threading.Event() batch_abort = threading.Event()
# streams currently being read, so teardown can unblock a superseded loser parked in a # streams currently being read, so teardown can unblock a superseded loser parked in a
# slow read instead of the wait-gated shutdown draining it (see force_unblock_stream) # slow read instead of the wait-gated shutdown draining it (see Body.unblock)
active_streams: set = set() active_streams: set[Body] = set()
active_lock = threading.Lock() active_lock = threading.Lock()
def register_stream(stream: Any, active: bool) -> None: def register_stream(stream: Body, active: bool) -> None:
with active_lock: with active_lock:
if active: if active:
active_streams.add(stream) active_streams.add(stream)
@@ -2230,7 +2286,7 @@ def requests(
with active_lock: with active_lock:
losers = list(active_streams) losers = list(active_streams)
for stream in losers: for stream in losers:
force_unblock_stream(stream) stream.unblock()
pool.shutdown(wait=not DOWNLOAD_CANCELLED.is_set(), cancel_futures=True) pool.shutdown(wait=not DOWNLOAD_CANCELLED.is_set(), cancel_futures=True)
while True: while True: