forked from kenzuya/unshackle
fix(session): retry an rnet response whose body ends early
This commit is contained in:
@@ -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"),
|
||||
[
|
||||
|
||||
@@ -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
|
||||
@@ -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):
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user