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
+2 -2
View File
@@ -148,7 +148,7 @@ while the server restarts.
| `INTERNAL_ERROR` | 422 | An unexpected server-side error. This is the fallback for any exception the server could not categorise, and for an exception that no handler caught. |
| `DOWNLOAD_ERROR` | 422 | The download process itself failed. |
| `WORKER_ERROR` | 422 | The download worker subprocess errored out. |
| `NETWORK_ERROR` | 424 | A network connectivity problem (connection, timeout, DNS, TLS). Retryable. |
| `NETWORK_ERROR` | 424 | A network connectivity problem (connection, timeout, DNS, TLS, or a response body that ended early). Retryable. |
| `SERVICE_UNAVAILABLE` | 424 | The service is temporarily unavailable or under maintenance. Retryable. |
!!! note "Fallback status"
@@ -180,7 +180,7 @@ exception that is not an `APIError` bubbles up, the server gives it a code in tw
| `geofence`, `geoblock`, `geo-block`, `geolocation`, `region`, `not available in`, `territory` | `GEOFENCE` (403) | no |
| `proxy` | `INVALID_PROXY` (400) | no |
| `auth`, `login`, `credential`, `unauthorized`, `forbidden`, `token` | `AUTH_FAILED` (401) | no |
| `connection`, `timeout`, `network`, `unreachable`, `socket`, `dns`, `resolve` (or `ConnectionError`, `TimeoutError`, `URLError`, `SSLError`) | `NETWORK_ERROR` (424) | yes |
| `connection`, `timeout`, `network`, `unreachable`, `socket`, `dns`, `resolve`, `incompletebody`, `unexpectedeof` (or `ConnectionError`, `TimeoutError`, `URLError`, `SSLError`, `BodyError`) | `NETWORK_ERROR` (424) | yes |
| `not found`, `404`, `does not exist`, `invalid id` | `NOT_FOUND` (404) | no |
| `rate limit`, `too many requests`, `429`, `throttle` | `RATE_LIMITED` (429) | yes |
| `drm`, `license`, `widevine`, `playready`, `decrypt` | `DRM_ERROR` (422) | no |
+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"
+3 -1
View File
@@ -199,8 +199,10 @@ def keyword_code(exc_str: str, root: BaseException) -> APIErrorCode:
"socket",
"dns",
"resolve",
"incompletebody",
"unexpectedeof",
]
) or exc_type in ["ConnectionError", "TimeoutError", "URLError", "SSLError"]:
) or exc_type in ["ConnectionError", "TimeoutError", "URLError", "SSLError", "BodyError"]:
return APIErrorCode.NETWORK_ERROR
if any(keyword in exc_str for keyword in ["not found", "404", "does not exist", "invalid id"]):
return APIErrorCode.NOT_FOUND