Skip to content

Commit 292090c

Browse files
committed
fix: decode retry bodies as JSON bytes to keep encoding detection
1 parent b72b356 commit 292090c

3 files changed

Lines changed: 9 additions & 6 deletions

File tree

‎_test_unstructured_client/unit/test_retries.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -599,6 +599,8 @@ async def run():
599599
(b'upstream error', "text/plain", False),
600600
(b'{"retryable":false}', "text/plain", True),
601601
(b'{"retryable":false}', "", True),
602+
(b'\xef\xbb\xbf{"retryable":false}', "application/json", True),
603+
('{"retryable":false}'.encode("utf-16"), "application/json", True),
602604
],
603605
)
604606
def test_declared_retry_verdict(

‎src/unstructured_client/utils/declared_errors.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import json
99
from dataclasses import dataclass
10-
from typing import Any, Optional
10+
from typing import Any, Optional, Union
1111

1212

1313
@dataclass(frozen=True)
@@ -34,13 +34,14 @@ def _declared_error_fields(body: Any) -> DeclaredErrorFields:
3434
)
3535

3636

37-
def parse_declared_error_fields(text: Optional[str]) -> DeclaredErrorFields:
37+
def parse_declared_error_fields(raw: Union[str, bytes, None]) -> DeclaredErrorFields:
3838
"""Read the declared fields from a raw body, dropping any of the wrong type.
3939
40-
A body that is not a JSON object declares nothing.
40+
Bytes are decoded as JSON, which detects UTF-8, UTF-16 and UTF-32 and skips a
41+
UTF-8 byte order mark. A body that is not a JSON object declares nothing.
4142
"""
4243
try:
43-
body = json.loads(text) if text else None
44+
body = json.loads(raw) if raw else None
4445
except (ValueError, TypeError, RecursionError):
4546
return DeclaredErrorFields()
4647
return _declared_error_fields(body)

‎src/unstructured_client/utils/retries.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,10 @@ def __init__(self, inner: Exception):
9292
def _declares_non_retryable(response: httpx.Response) -> bool:
9393
# Inspect buffered error bodies without consuming unread response streams.
9494
try:
95-
text = response.text
95+
content = response.content
9696
except httpx.ResponseNotRead:
9797
return False
98-
return parse_declared_error_fields(text).retryable is False
98+
return parse_declared_error_fields(content).retryable is False
9999

100100

101101
def _is_retry_status(response: httpx.Response, status_codes: List[str]) -> bool:

0 commit comments

Comments
 (0)