diff --git a/docs/dev/rest-api/errors.md b/docs/dev/rest-api/errors.md index 5c15aacf..d266d02e 100644 --- a/docs/dev/rest-api/errors.md +++ b/docs/dev/rest-api/errors.md @@ -170,7 +170,9 @@ exception that is not an `APIError` bubbles up, the server gives it a code in tw 1. **The code the failure names.** An unshackle core failure states its own code: a region check gives `GEOFENCE`, a proxy that fails gives `INVALID_PROXY`, a login that needs - an absent user gives `AUTH_FAILED`, and a DRM failure gives `DRM_ERROR`. The server + an absent user gives `AUTH_FAILED`, and a DRM failure gives `DRM_ERROR`. A request that + fails on each retry gives `NETWORK_ERROR` for a connection fault or a body that ended early, + `RATE_LIMITED` for a `429` and `SERVICE_UNAVAILABLE` for a `503`. The server reads this code first, so the wording of the message does not change it. 2. **The keywords of the message.** A failure that names no code, such as the plain text that a service raises, gets a code from the words in its message, checked in order: diff --git a/tests/core/test_session_error_codes.py b/tests/core/test_session_error_codes.py new file mode 100644 index 00000000..d21916fb --- /dev/null +++ b/tests/core/test_session_error_codes.py @@ -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 diff --git a/tests/core/test_session_websocket.py b/tests/core/test_session_websocket.py index 87ed7acf..2d3bd736 100644 --- a/tests/core/test_session_websocket.py +++ b/tests/core/test_session_websocket.py @@ -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)"), ] diff --git a/tests/remote/unit/test_errors.py b/tests/remote/unit/test_errors.py index 674e7830..b6f4df8d 100644 --- a/tests/remote/unit/test_errors.py +++ b/tests/remote/unit/test_errors.py @@ -185,6 +185,11 @@ def test_a_bad_content_encoding_is_no_network_error() -> None: assert categorize_exception(rnet_error(BAD_DEFLATE)).error_code != APIErrorCode.NETWORK_ERROR +def test_a_bare_rnet_error_reads_as_its_short_cause() -> None: + err = categorize_exception(rnet_error(SHORT_BODY)) + assert err.message == "Network error occurred: DecodingError (IncompleteBody)" + + def test_categorize_preserves_context() -> None: api_err = categorize_exception(ValueError("bad"), context={"op": "search"}) assert api_err.details["op"] == "search" diff --git a/unshackle/core/api/errors.py b/unshackle/core/api/errors.py index 6e7175db..364916f6 100644 --- a/unshackle/core/api/errors.py +++ b/unshackle/core/api/errors.py @@ -12,9 +12,11 @@ import traceback from datetime import UTC, datetime from typing import Any +import rnet.exceptions from aiohttp import web from unshackle.core.remote_protocol import APIErrorCode +from unshackle.core.session import failure_reason from unshackle.core.utils.redact import redact_secrets @@ -161,6 +163,8 @@ CATEGORIES: dict[APIErrorCode, tuple[str, str]] = { RETRYABLE = {APIErrorCode.NETWORK_ERROR, APIErrorCode.RATE_LIMITED, APIErrorCode.SERVICE_UNAVAILABLE} +RNET_ERRORS = tuple(v for v in vars(rnet.exceptions).values() if isinstance(v, type) and issubclass(v, Exception)) + def categorized(code: APIErrorCode, text: str, context: dict[str, Any]) -> APIError: """The APIError of ``code`` for an exception with message ``text``.""" @@ -253,6 +257,8 @@ def categorize_exception( if isinstance(code := getattr(carrier, "error_code", None), APIErrorCode): return categorized(code, str(carrier), context) code = keyword_code(f"{exc} {root}".lower(), root) + if isinstance(exc, RNET_ERRORS): + return categorized(code, failure_reason(exc), context) return categorized(code, str(root if code == APIErrorCode.INVALID_PROXY else exc), context) diff --git a/unshackle/core/session.py b/unshackle/core/session.py index 763f50e7..db27ccd2 100644 --- a/unshackle/core/session.py +++ b/unshackle/core/session.py @@ -27,6 +27,7 @@ from requests.cookies import create_cookie from requests.structures import CaseInsensitiveDict from unshackle.core.config import config +from unshackle.core.remote_protocol import APIErrorCode, coded from unshackle.core.utilities import get_debug_logger, log_event from unshackle.core.utils import run_proxy @@ -567,8 +568,12 @@ class MaxRetriesError(Exception): self.__cause__ = cause -# the innermost io error text in rnet's wreq::Error debug form, e.g. "stream closed because of a broken pipe" -RNET_ERROR_TEXT_RE = re.compile(r'error: "([^"]+)"') +RNET_ERROR_TEXT_RE = re.compile(r', (?:error|message|source): (?:"([^"]+)"|(\w+)(?= \}))') +"""The innermost error of rnet's wreq::Error debug text: a quoted text, or a bare kind that ends its struct.""" + +NETWORK_ERRORS = (rnet.ConnectionError, rnet.ConnectionResetError, rnet.TimeoutError, rnet.RequestError, rnet.BodyError) +STATUS_CODES = {429: APIErrorCode.RATE_LIMITED, 503: APIErrorCode.SERVICE_UNAVAILABLE} +CUT_BODY = "hyper::Error(Body" def failure_response(exc: BaseException) -> Any: @@ -592,7 +597,23 @@ def failure_reason(exc: BaseException) -> str: if isinstance(status, int): return f"{status} {getattr(response, 'reason', '') or ''}".strip() texts = RNET_ERROR_TEXT_RE.findall(str(inner)) - return f"{type(inner).__name__} ({texts[-1]})" if texts else type(inner).__name__ + return f"{type(inner).__name__} ({''.join(texts[-1])})" if texts else type(inner).__name__ + + +def failure_code(exc: BaseException) -> APIErrorCode | None: + """The API error code of a request failure: 429, 503 or an rnet transport error, else None. + + rnet raises DecodingError for a cut body and for a broken content encoding, so only a body that hyper failed to read + is a network fault. A proxy failure stays uncoded, so that categorize_exception reports it as INVALID_PROXY. + """ + status = getattr(failure_response(exc), "status_code", None) + if isinstance(status, int): + return STATUS_CODES.get(status) + text = str(exc) + if "proxy" in text.lower(): + return None + cut_body = isinstance(exc, rnet.DecodingError) and CUT_BODY in text + return APIErrorCode.NETWORK_ERROR if cut_body or isinstance(exc, NETWORK_ERRORS) else None MANIFEST_SUFFIXES = (".mpd", ".m3u8") @@ -835,14 +856,7 @@ class RnetSession: self.max_backoff = max_backoff self.status_forcelist = status_forcelist or list(STATUS_FORCELIST) self.allowed_methods = allowed_methods or set(RETRY_METHODS) - self.catch_exceptions = catch_exceptions or ( - rnet.ConnectionError, - rnet.ConnectionResetError, # sibling of ConnectionError; mid-request resets are retryable - rnet.TimeoutError, - rnet.RequestError, - rnet.BodyError, - rnet.DecodingError, - ) + self.catch_exceptions = catch_exceptions or (*NETWORK_ERRORS, rnet.DecodingError) self.log = logging.getLogger(self.__class__.__name__) client_kwargs: dict[str, Any] = {} @@ -1127,7 +1141,8 @@ class RnetSession: This method retries only the methods in allowed_methods. Any other method gets one try. A max_retries kwarg overrides the HTTP session retry budget for this call alone, where 0 means one try with no retries. Once the budget is spent, this method raises - MaxRetriesError with the last failure as its cause. A record_request=False kwarg keeps + MaxRetriesError with the last failure as its cause, and with its API error code when it + retried. With max_retries=0 the caller owns the retries and the code. A record_request=False kwarg keeps this call out of the debug_requests debug-log entries. """ client = self.ensure_client() @@ -1207,9 +1222,11 @@ class RnetSession: break attempts = f" after {max_retries + 1} attempts" if max_retries else "" - raise MaxRetriesError( + error = MaxRetriesError( f"{method_upper} {parsed_origin.hostname} failed{attempts}: {failure}", cause=last_exception ) + code = failure_code(last_exception) if max_retries and last_exception else None + raise coded(error, code) if code else error def get(self, url: str, **kwargs: Any) -> RnetResponse: return self.request("GET", url, **kwargs)