fix(api): report a response body that ended early as a retryable NETWORK_ERROR

This commit is contained in:
imSp4rky
2026-12-05 00:59:27 -07:00
parent deb4b7846d
commit 96e4a314fb
3 changed files with 55 additions and 3 deletions
+50
View File
@@ -3,11 +3,17 @@
from __future__ import annotations
import json
import socket
import threading
from collections.abc import Callable
import pytest
import rnet
from rnet.exceptions import BodyError
from unshackle.core.api.errors import APIError, build_error_response, categorize_exception, handle_api_exception
from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.session import MaxRetriesError
pytestmark = pytest.mark.unit
@@ -135,6 +141,50 @@ def test_categorize_exception(exc: Exception, expected_code: APIErrorCode) -> No
assert api_err.details.get("service") == "EXAMPLE"
def rnet_error(response: bytes) -> Exception:
"""The exception rnet raises on reading the JSON body of a loopback server that sends ``response`` and closes."""
server = socket.create_server(("127.0.0.1", 0))
def answer() -> None:
conn, _ = server.accept()
conn.recv(65536)
conn.sendall(response)
conn.close()
threading.Thread(target=answer, daemon=True).start()
with server, pytest.raises(Exception) as caught:
rnet.BlockingClient(timeout=10).get(f"http://127.0.0.1:{server.getsockname()[1]}/").json()
return caught.value
SHORT_BODY = b"HTTP/1.1 200 OK\r\nContent-Length: 1000\r\n\r\n{"
SHORT_CHUNK_SIZE_LINE = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n1"
BAD_DEFLATE = b"HTTP/1.1 200 OK\r\nContent-Encoding: deflate\r\nContent-Length: 4\r\n\r\nZZZZ"
@pytest.mark.parametrize("wrapped", [False, True], ids=["bare", "after-retries"])
@pytest.mark.parametrize(
"make",
[
lambda: rnet_error(SHORT_BODY),
lambda: rnet_error(SHORT_CHUNK_SIZE_LINE),
lambda: BodyError("body read failed"),
],
ids=["short-body", "short-chunk-size-line", "body-error"],
)
def test_a_body_that_ended_early_is_a_retryable_network_error(make: Callable[[], Exception], wrapped: bool) -> None:
exc = make()
if wrapped:
exc = MaxRetriesError(f"GET cdn.example failed after 6 attempts: {type(exc).__name__}", cause=exc)
resp = handle_api_exception(exc)
body = _body(resp)
assert (resp.status, body["error_code"], body.get("retryable")) == (424, "NETWORK_ERROR", True)
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_categorize_preserves_context() -> None:
api_err = categorize_exception(ValueError("bad"), context={"op": "search"})
assert api_err.details["op"] == "search"