fix(session): retry an rnet response whose body ends early

This commit is contained in:
imSp4rky
2026-12-05 01:10:03 -07:00
parent 96e4a314fb
commit cd6046bf82
6 changed files with 137 additions and 34 deletions
+14
View File
@@ -83,6 +83,13 @@ class Handler(BaseHTTPRequestHandler):
ranged = bool(self.headers.get("Range")) and not path.startswith("/plain") ranged = bool(self.headers.get("Range")) and not path.startswith("/plain")
body = self.server.docs.get(path, BODY[:1] if ranged else BODY) body = self.server.docs.get(path, BODY[:1] if ranged else BODY)
body = body.encode() if isinstance(body, str) 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"): if path.startswith("/chunked"):
self.send_response(200) self.send_response(200)
self.send_header("Content-Type", self.server.types.get(path, "text/plain")) 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)] 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( @pytest.mark.parametrize(
("make_session", "kwargs", "error"), ("make_session", "kwargs", "error"),
[ [
+89
View File
@@ -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
+5 -2
View File
@@ -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: 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 pass
with pytest.raises(RuntimeError): 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: 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") raise ValueError("raised inside the with block")
with pytest.raises(RuntimeError): with pytest.raises(RuntimeError):
+3 -1
View File
@@ -15,7 +15,9 @@ def rate_limited(monkeypatch):
monkeypatch.setattr(s, "ensure_client", lambda: SimpleNamespace(request=lambda *a, **k: None)) monkeypatch.setattr(s, "ensure_client", lambda: SimpleNamespace(request=lambda *a, **k: None))
monkeypatch.setattr(s, "get_sleep_time", lambda *a: 0) monkeypatch.setattr(s, "get_sleep_time", lambda *a: 0)
monkeypatch.setattr( 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 return s
+14 -10
View File
@@ -121,7 +121,7 @@ class RnetResponseHeaders(MutableMapping):
class RnetResponse: class RnetResponse:
"""Wraps rnet.BlockingResponse with a requests-compatible API. """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. 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.ConnectionResetError, # sibling of ConnectionError; mid-request resets are retryable
rnet.TimeoutError, rnet.TimeoutError,
rnet.RequestError, rnet.RequestError,
rnet.BodyError,
rnet.DecodingError,
) )
self.log = logging.getLogger(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__)
@@ -1080,17 +1082,22 @@ class RnetSession:
url: str, url: str,
attempt: int, attempt: int,
record: bool, record: bool,
body: bool, read: bool,
sent: tuple[str, Any] | None, sent: tuple[str, Any] | None,
kwargs: dict[str, Any], kwargs: dict[str, Any],
) -> RnetResponse: ) -> RnetResponse:
"""Send one HTTP attempt. With debug_requests on, log it, and when ``record`` is set write its debug-log entry. """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() started = time.monotonic()
try: try:
response = self.absorb_cookies(RnetResponse(client.request(rnet_method, url, **kwargs))) 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: except Exception as e:
if record: if record:
record_request(method, url, attempt, duration=time.monotonic() - started, error=e, sent=sent) record_request(method, url, attempt, duration=time.monotonic() - started, error=e, sent=sent)
@@ -1111,9 +1118,7 @@ class RnetSession:
) )
self.log.debug(log_msg) self.log.debug(log_msg)
if record: if record:
record_request( record_request(method, url, attempt, duration=headers_at - started, response=response, body=read, sent=sent)
method, url, attempt, duration=time.monotonic() - started, response=response, body=body, sent=sent
)
return response return response
def request(self, method: str, url: str, **kwargs: Any) -> RnetResponse: def request(self, method: str, url: str, **kwargs: Any) -> RnetResponse:
@@ -1146,7 +1151,7 @@ class RnetSession:
kwargs.setdefault("allow_redirects", True) kwargs.setdefault("allow_redirects", True)
# Remove kwargs rnet doesn't understand # 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) data = kwargs.pop("data", None)
if data is not None: if data is not None:
@@ -1166,11 +1171,10 @@ class RnetSession:
kwargs["headers"] = dict(kwargs["headers"]) kwargs["headers"] = dict(kwargs["headers"])
record = kwargs.pop("record_request", True) and config.debug_requests 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 sent = rnet_sent(kwargs, self.headers) if record else None
if method_upper not in self.allowed_methods: 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 last_exception: Exception | None = None
response: RnetResponse | None = None response: RnetResponse | None = None
@@ -1178,7 +1182,7 @@ class RnetSession:
for attempt in range(max_retries + 1): for attempt in range(max_retries + 1):
try: try:
response = self.send_attempt( 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: if response.status_code not in self.status_forcelist:
+6 -15
View File
@@ -228,7 +228,9 @@ def probe_size(segment: Segment, session: Session | RnetSession) -> int | None:
# Require a 206 so a server that ignores Range (returning the whole 200 body) # Require a 206 so a server that ignores Range (returning the whole 200 body)
# is not mistaken for a valid size or downloaded wholesale. # is not mistaken for a valid size or downloaded wholesale.
try: try:
res = unrecorded(session, "get", segment.url, headers={"Range": "bytes=0-0"}, timeout=PROBE_TIMEOUT) 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: if getattr(res, "status_code", 0) == 206:
content_range = res.headers.get("Content-Range") content_range = res.headers.get("Content-Range")
if content_range and "/" in content_range: if content_range and "/" in content_range:
@@ -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: 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. """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 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 body and closes the response at that point. read streams the response and closes it at the end.
""" """
try: try:
res = unrecorded( with unrecorded(session, "get", url, headers={"Range": byte_range}, timeout=PROBE_TIMEOUT, stream=True) as res:
session,
"get",
url,
headers={"Range": byte_range},
timeout=PROBE_TIMEOUT,
stream=accept_200,
)
try:
status = getattr(res, "status_code", 0) status = getattr(res, "status_code", 0)
if accept_200 and status == 200 and byte_range.startswith("bytes=0-"): if accept_200 and status == 200 and byte_range.startswith("bytes=0-"):
size = int(byte_range.partition("-")[2]) + 1 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 return None
content = getattr(res, "content", None) content = getattr(res, "content", None)
return content if content else None return content if content else None
finally:
if accept_200:
res.close()
except Exception: except Exception:
return None return None