forked from kenzuya/unshackle
fix(session): name the API error code and the short rnet cause of an exhausted request
This commit is contained in:
@@ -0,0 +1,147 @@
|
||||
"""An exhausted RnetSession request names its API error code and a short cause."""
|
||||
|
||||
import gzip
|
||||
import logging
|
||||
import socket
|
||||
import threading
|
||||
from collections.abc import Callable, Iterator
|
||||
|
||||
import pytest
|
||||
import rnet
|
||||
|
||||
from unshackle.core.api.errors import categorize_exception
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.session import MaxRetriesError, RnetSession, failure_reason
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
CUT = b"HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 1000\r\n\r\n{"
|
||||
BAD_DEFLATE = b"HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Encoding: deflate\r\nContent-Length: 4\r\n\r\nZZZZ"
|
||||
TOO_MANY = b"HTTP/1.1 429 Too Many Requests\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"
|
||||
UNAVAILABLE = b"HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"
|
||||
HALF_GZIP = gzip.compress(b"x" * 5000)[:20]
|
||||
CUT_GZIP = b"HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Encoding: gzip\r\nContent-Length: 20\r\n\r\n" + HALF_GZIP
|
||||
SERVER_ERROR = b"HTTP/1.1 500 Internal Server Error\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"
|
||||
|
||||
QUOTED = (
|
||||
'is_request error: wreq::Error { kind: Request, url: "https://cdn.example.invalid/seg", source: hyper::Error(Io, '
|
||||
'Custom { kind: BrokenPipe, error: "stream closed because of a broken pipe" }) }'
|
||||
)
|
||||
UNQUOTED = (
|
||||
"is_decode error: wreq::Error { kind: Decode, source: wreq::Error { kind: Body, source: hyper::Error(Body, "
|
||||
"Custom { kind: UnexpectedEof, error: IncompleteBody }) } }"
|
||||
)
|
||||
REFUSED = (
|
||||
'is_connect error: wreq::Error { kind: Request, url: "http://127.0.0.1:1/x", source: crate::util::client::Error('
|
||||
'Connect, ConnectError("tcp connect error", Os { code: 111, kind: ConnectionRefused, message: "refused" })) }'
|
||||
)
|
||||
|
||||
|
||||
class DecodingError(Exception):
|
||||
"""Stands in for an rnet error, which carries its debug text."""
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text, reason",
|
||||
[
|
||||
(QUOTED, "DecodingError (stream closed because of a broken pipe)"),
|
||||
(UNQUOTED, "DecodingError (IncompleteBody)"),
|
||||
(REFUSED, "DecodingError (refused)"),
|
||||
(
|
||||
'is_timeout error: wreq::Error { kind: Request, url: "http://x/", source: TimedOut }',
|
||||
"DecodingError (TimedOut)",
|
||||
),
|
||||
("is_decode error: wreq::Error { kind: Decode, source: wreq::Error { kind: Body } }", "DecodingError"),
|
||||
],
|
||||
ids=["quoted", "unquoted", "message", "bare-source", "no-inner-error"],
|
||||
)
|
||||
def test_failure_reason_names_the_innermost_rnet_error(text: str, reason: str) -> None:
|
||||
assert failure_reason(DecodingError(text)) == reason
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def reply() -> Iterator[Callable[[bytes], str]]:
|
||||
"""Start a loopback server that answers each connection with the given bytes, and give its URL."""
|
||||
servers: list[socket.socket] = []
|
||||
|
||||
def start(answer: bytes) -> str:
|
||||
srv = socket.create_server(("127.0.0.1", 0))
|
||||
servers.append(srv)
|
||||
|
||||
def serve() -> None:
|
||||
while True:
|
||||
try:
|
||||
conn, _ = srv.accept()
|
||||
except OSError:
|
||||
return
|
||||
with conn:
|
||||
conn.recv(65536)
|
||||
conn.sendall(answer)
|
||||
|
||||
threading.Thread(target=serve, daemon=True).start()
|
||||
return f"http://127.0.0.1:{srv.getsockname()[1]}/x"
|
||||
|
||||
yield start
|
||||
for srv in servers:
|
||||
srv.close()
|
||||
|
||||
|
||||
def dead_url() -> str:
|
||||
"""A loopback URL with nothing listening."""
|
||||
with socket.create_server(("127.0.0.1", 0)) as srv:
|
||||
return f"http://127.0.0.1:{srv.getsockname()[1]}/x"
|
||||
|
||||
|
||||
def exhausted(url: str, session: RnetSession | None = None, max_retries: int = 1) -> MaxRetriesError:
|
||||
with pytest.raises(MaxRetriesError) as raised:
|
||||
(session or RnetSession(backoff_factor=0)).get(url, max_retries=max_retries)
|
||||
return raised.value
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"answer, code, cause",
|
||||
[
|
||||
(TOO_MANY, APIErrorCode.RATE_LIMITED, "429 Too Many Requests"),
|
||||
(UNAVAILABLE, APIErrorCode.SERVICE_UNAVAILABLE, "503 Service Unavailable"),
|
||||
(CUT, APIErrorCode.NETWORK_ERROR, "DecodingError (IncompleteBody)"),
|
||||
],
|
||||
ids=["429", "503", "cut-body"],
|
||||
)
|
||||
def test_an_exhausted_request_names_its_code(reply, answer: bytes, code: APIErrorCode, cause: str) -> None:
|
||||
exc = exhausted(reply(answer))
|
||||
err = categorize_exception(exc, {"service": "EXAMPLE"})
|
||||
assert (exc.error_code, err.error_code, err.retryable) == (code, code, True)
|
||||
assert err.message.endswith(f"GET 127.0.0.1 failed after 2 attempts: {cause}")
|
||||
|
||||
|
||||
def test_a_cut_body_retry_warning_names_the_short_cause(reply, caplog) -> None:
|
||||
with caplog.at_level(logging.WARNING):
|
||||
exhausted(reply(CUT))
|
||||
assert "DecodingError (IncompleteBody)(/x). Retrying... (1/1)" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("answer", [BAD_DEFLATE, CUT_GZIP, SERVER_ERROR], ids=["bad-deflate", "cut-gzip", "500"])
|
||||
def test_an_exhausted_request_without_a_known_code_names_none(reply, answer: bytes) -> None:
|
||||
assert getattr(exhausted(reply(answer)), "error_code", None) is None
|
||||
|
||||
|
||||
def test_a_bad_content_encoding_after_retries_is_no_network_error(reply) -> None:
|
||||
assert categorize_exception(exhausted(reply(BAD_DEFLATE))).error_code != APIErrorCode.NETWORK_ERROR
|
||||
|
||||
|
||||
def test_a_refused_connection_is_a_network_error() -> None:
|
||||
exc = exhausted(dead_url())
|
||||
assert isinstance(exc.__cause__, rnet.ConnectionError)
|
||||
assert exc.error_code == categorize_exception(exc).error_code == APIErrorCode.NETWORK_ERROR
|
||||
|
||||
|
||||
def test_an_unreachable_proxy_stays_a_proxy_error() -> None:
|
||||
session = RnetSession(backoff_factor=0)
|
||||
session.proxies["all"] = dead_url().replace("http://", "socks5://").removesuffix("/x")
|
||||
exc = exhausted("http://127.0.0.1:9/x", session)
|
||||
assert getattr(exc, "error_code", None) is None
|
||||
assert categorize_exception(exc).error_code == APIErrorCode.INVALID_PROXY
|
||||
|
||||
|
||||
def test_a_request_with_no_retries_names_no_code() -> None:
|
||||
assert getattr(exhausted(dead_url(), max_retries=0), "error_code", None) is None
|
||||
@@ -110,5 +110,5 @@ async def test_each_handshake_writes_one_debug_entry(debug_log: Path) -> None:
|
||||
(entry["request"]["method"], entry["response"]["status"], entry["failure"]) for entry in records(debug_log)
|
||||
] == [
|
||||
("GET", 101, None),
|
||||
("GET", None, "ConnectionError"),
|
||||
("GET", None, "ConnectionError (Connection refused)"),
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user