From cd6046bf82d8f5f070e2dbf8ee6d5dab1d474dfb Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Sat, 5 Dec 2026 01:10:02 -0700 Subject: [PATCH] fix(session): retry an rnet response whose body ends early --- tests/core/test_request_record.py | 14 ++++ tests/core/test_session_body_retry.py | 89 +++++++++++++++++++++ tests/core/test_session_response_context.py | 7 +- tests/core/test_session_retry_log.py | 4 +- unshackle/core/session.py | 24 +++--- unshackle/core/utils/bitrate.py | 33 +++----- 6 files changed, 137 insertions(+), 34 deletions(-) create mode 100644 tests/core/test_session_body_retry.py diff --git a/tests/core/test_request_record.py b/tests/core/test_request_record.py index 799c56908..69e28a025 100644 --- a/tests/core/test_request_record.py +++ b/tests/core/test_request_record.py @@ -83,6 +83,13 @@ class Handler(BaseHTTPRequestHandler): ranged = bool(self.headers.get("Range")) and not path.startswith("/plain") body = self.server.docs.get(path, BODY[:1] if ranged else BODY) body = body.encode() if isinstance(body, str) else body + if path == "/cut": + self.send_response(200) + self.send_header("Content-Length", str(len(body) + 100)) + self.end_headers() + self.wfile.write(body) + self.close_connection = True + return if path.startswith("/chunked"): self.send_response(200) self.send_header("Content-Type", self.server.types.get(path, "text/plain")) @@ -183,6 +190,13 @@ def test_a_retried_request_writes_one_entry_per_attempt(server, debug_log, make_ assert [(e["request"]["attempt"], e["response"]["status"]) for e in entries] == [(1, 503), (2, 200)] +def test_each_rnet_attempt_with_a_cut_body_names_its_failure(server, debug_log): + with pytest.raises(MaxRetriesError): + rnet_session().get(f"{server.url}/cut", max_retries=1) + + assert [(e["request"]["attempt"], bool(e["failure"])) for e in records(debug_log)] == [(1, True), (2, True)] + + @pytest.mark.parametrize( ("make_session", "kwargs", "error"), [ diff --git a/tests/core/test_session_body_retry.py b/tests/core/test_session_body_retry.py new file mode 100644 index 000000000..d493e2112 --- /dev/null +++ b/tests/core/test_session_body_retry.py @@ -0,0 +1,89 @@ +"""RnetSession.request retries a response whose body ends before its Content-Length.""" + +import socket +import threading + +import pytest +import rnet + +from unshackle.core.session import MaxRetriesError, RnetSession +from unshackle.core.utils.bitrate import Segment, probe_size, ranged_get + +pytestmark = pytest.mark.unit + +WHOLE = b'HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\nContent-Length: 8\r\n\r\n{"a": 1}' +CUT = b'HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\nContent-Length: 1000\r\n\r\n{"a": 1' +CUT_403 = b"HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 222\r\n\r\n" +NO_HEAD = b"HTTP/1.1 405 Method Not Allowed\r\nConnection: close\r\nContent-Length: 0\r\n\r\n" + + +@pytest.fixture +def server(): + """A loopback server that answers each connection with the next reply of ``plan``, then with CUT.""" + srv = socket.socket() + srv.bind(("127.0.0.1", 0)) + srv.listen(8) + plan: list[bytes] = [] + hits: list[int] = [] + + def serve() -> None: + while True: + try: + conn, _ = srv.accept() + except OSError: + return + with conn: + conn.recv(65536) + conn.sendall(plan[len(hits)] if len(hits) < len(plan) else CUT) + hits.append(1) + + threading.Thread(target=serve, daemon=True).start() + yield f"http://127.0.0.1:{srv.getsockname()[1]}/x", plan, hits + srv.close() + + +def session() -> RnetSession: + return RnetSession(max_retries=2, backoff_factor=0) + + +def test_every_attempt_cut_spends_the_budget(server): + url, _, hits = server + with pytest.raises(MaxRetriesError) as raised: + session().get(url) + assert len(hits) == 3 + assert isinstance(raised.value.__cause__, (rnet.BodyError, rnet.DecodingError)) + + +def test_cut_first_attempt_retries_to_the_whole_body(server): + url, plan, hits = server + plan[:] = [CUT, WHOLE] + assert session().get(url).json() == {"a": 1} + assert len(hits) == 2 + + +def test_stream_keeps_the_body_lazy_and_does_not_retry(server): + url, _, hits = server + response = session().get(url, stream=True) + with pytest.raises((rnet.BodyError, rnet.DecodingError)): + response.json() + assert len(hits) == 1 + + +def test_an_error_status_with_a_cut_body_keeps_its_status(server): + url, plan, hits = server + plan[:] = [CUT_403] + assert session().post(url).status_code == 403 + assert len(hits) == 1 + + +def test_a_size_probe_reads_no_body_of_a_200(server): + url, plan, hits = server + plan[:] = [NO_HEAD] + assert probe_size(Segment(url, None, None, 0.0), session()) is None + assert len(hits) == 2 + + +def test_a_ranged_read_reads_no_body_of_a_200(server): + url, _, hits = server + assert ranged_get(url, session(), "bytes=0-9") is None + assert len(hits) == 1 diff --git a/tests/core/test_session_response_context.py b/tests/core/test_session_response_context.py index ee05c5152..079514a4a 100644 --- a/tests/core/test_session_response_context.py +++ b/tests/core/test_session_response_context.py @@ -55,7 +55,7 @@ def test_a_with_block_gives_the_response_itself_and_its_content(cover_url: str) def test_the_end_of_the_with_block_closes_the_response(cover_url: str) -> None: - with RnetSession().get(cover_url) as response: + with RnetSession().get(cover_url, stream=True) as response: pass with pytest.raises(RuntimeError): @@ -63,7 +63,10 @@ def test_the_end_of_the_with_block_closes_the_response(cover_url: str) -> None: def test_an_exception_in_the_with_block_propagates_and_the_response_still_closes(cover_url: str) -> None: - with pytest.raises(ValueError, match="raised inside the with block"), RnetSession().get(cover_url) as response: + with ( + pytest.raises(ValueError, match="raised inside the with block"), + RnetSession().get(cover_url, stream=True) as response, + ): raise ValueError("raised inside the with block") with pytest.raises(RuntimeError): diff --git a/tests/core/test_session_retry_log.py b/tests/core/test_session_retry_log.py index 6dbb77934..292c58629 100644 --- a/tests/core/test_session_retry_log.py +++ b/tests/core/test_session_retry_log.py @@ -15,7 +15,9 @@ def rate_limited(monkeypatch): monkeypatch.setattr(s, "ensure_client", lambda: SimpleNamespace(request=lambda *a, **k: None)) monkeypatch.setattr(s, "get_sleep_time", lambda *a: 0) monkeypatch.setattr( - session_module, "RnetResponse", lambda raw: SimpleNamespace(status_code=429, reason="Too Many Requests") + session_module, + "RnetResponse", + lambda raw: SimpleNamespace(status_code=429, reason="Too Many Requests", ok=False), ) return s diff --git a/unshackle/core/session.py b/unshackle/core/session.py index 71941feab..763f50e75 100644 --- a/unshackle/core/session.py +++ b/unshackle/core/session.py @@ -121,7 +121,7 @@ class RnetResponseHeaders(MutableMapping): class RnetResponse: """Wraps rnet.BlockingResponse with a requests-compatible API. - A ``with`` block gives this response and closes it at the end. Read the body inside the block: + A ``with`` block gives this response and closes it at the end. Read a ``stream=True`` body inside the block: a body left unread cannot be read after it. """ @@ -840,6 +840,8 @@ class RnetSession: rnet.ConnectionResetError, # sibling of ConnectionError; mid-request resets are retryable rnet.TimeoutError, rnet.RequestError, + rnet.BodyError, + rnet.DecodingError, ) self.log = logging.getLogger(self.__class__.__name__) @@ -1080,17 +1082,22 @@ class RnetSession: url: str, attempt: int, record: bool, - body: bool, + read: bool, sent: tuple[str, Any] | None, kwargs: dict[str, Any], ) -> RnetResponse: """Send one HTTP attempt. With debug_requests on, log it, and when ``record`` is set write its debug-log entry. - ``body`` writes the response body to a body file, and ``sent`` the request body. + ``read`` reads the whole body of a 2xx response in the attempt, so a body cut short fails the attempt, and + writes the body to a body file. Any other response keeps its status and a lazy body. ``sent`` writes the + request body. """ started = time.monotonic() try: response = self.absorb_cookies(RnetResponse(client.request(rnet_method, url, **kwargs))) + headers_at = time.monotonic() + if read and response.ok: + _ = response.content except Exception as e: if record: record_request(method, url, attempt, duration=time.monotonic() - started, error=e, sent=sent) @@ -1111,9 +1118,7 @@ class RnetSession: ) self.log.debug(log_msg) if record: - record_request( - method, url, attempt, duration=time.monotonic() - started, response=response, body=body, sent=sent - ) + record_request(method, url, attempt, duration=headers_at - started, response=response, body=read, sent=sent) return response def request(self, method: str, url: str, **kwargs: Any) -> RnetResponse: @@ -1146,7 +1151,7 @@ class RnetSession: kwargs.setdefault("allow_redirects", True) # Remove kwargs rnet doesn't understand - stream = kwargs.pop("stream", None) # rnet responses are always lazy + read = not kwargs.pop("stream", None) data = kwargs.pop("data", None) if data is not None: @@ -1166,11 +1171,10 @@ class RnetSession: kwargs["headers"] = dict(kwargs["headers"]) record = kwargs.pop("record_request", True) and config.debug_requests - body = record and not stream sent = rnet_sent(kwargs, self.headers) if record else None if method_upper not in self.allowed_methods: - return self.send_attempt(client, rnet_method, method_upper, url, 1, record, body, sent, kwargs) + return self.send_attempt(client, rnet_method, method_upper, url, 1, record, read, sent, kwargs) last_exception: Exception | None = None response: RnetResponse | None = None @@ -1178,7 +1182,7 @@ class RnetSession: for attempt in range(max_retries + 1): try: response = self.send_attempt( - client, rnet_method, method_upper, url, attempt + 1, record, body, sent, kwargs + client, rnet_method, method_upper, url, attempt + 1, record, read, sent, kwargs ) if response.status_code not in self.status_forcelist: diff --git a/unshackle/core/utils/bitrate.py b/unshackle/core/utils/bitrate.py index 89b27737e..83dc22bd7 100644 --- a/unshackle/core/utils/bitrate.py +++ b/unshackle/core/utils/bitrate.py @@ -228,13 +228,15 @@ def probe_size(segment: Segment, session: Session | RnetSession) -> int | None: # Require a 206 so a server that ignores Range (returning the whole 200 body) # is not mistaken for a valid size or downloaded wholesale. try: - res = unrecorded(session, "get", segment.url, headers={"Range": "bytes=0-0"}, timeout=PROBE_TIMEOUT) - if getattr(res, "status_code", 0) == 206: - content_range = res.headers.get("Content-Range") - if content_range and "/" in content_range: - total = content_range.rsplit("/", 1)[-1].strip() - if total.isdigit(): - return int(total) + with unrecorded( + session, "get", segment.url, headers={"Range": "bytes=0-0"}, timeout=PROBE_TIMEOUT, stream=True + ) as res: + if getattr(res, "status_code", 0) == 206: + content_range = res.headers.get("Content-Range") + if content_range and "/" in content_range: + total = content_range.rsplit("/", 1)[-1].strip() + if total.isdigit(): + return int(total) except Exception: pass @@ -434,19 +436,11 @@ def ffprobe_duration(url: str, session: Session | RnetSession, *, log: logging.L def ranged_get(url: str, session: Session | RnetSession, byte_range: str, accept_200: bool = False) -> bytes | None: """Fetch a byte range, only accepting a real 206 partial response. - With ``accept_200``, a 200 answer to a range from byte 0 gives the start of its body up to the range end. The - read streams the body and closes the response at that point. + With ``accept_200``, a 200 answer to a range from byte 0 gives the start of its body up to the range end. Each + read streams the response and closes it at the end. """ try: - res = unrecorded( - session, - "get", - url, - headers={"Range": byte_range}, - timeout=PROBE_TIMEOUT, - stream=accept_200, - ) - try: + with unrecorded(session, "get", url, headers={"Range": byte_range}, timeout=PROBE_TIMEOUT, stream=True) as res: status = getattr(res, "status_code", 0) if accept_200 and status == 200 and byte_range.startswith("bytes=0-"): size = int(byte_range.partition("-")[2]) + 1 @@ -460,9 +454,6 @@ def ranged_get(url: str, session: Session | RnetSession, byte_range: str, accept return None content = getattr(res, "content", None) return content if content else None - finally: - if accept_200: - res.close() except Exception: return None