Skip to content

Commit fbab73a

Browse files
committed
fix: Classify and retry failures while reading a streamed error body
1 parent 334e131 commit fbab73a

2 files changed

Lines changed: 81 additions & 10 deletions

File tree

‎src/apify_client/http_clients/_impit.py‎

Lines changed: 32 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import logging
55
import random
66
import time
7+
from contextlib import suppress
78
from datetime import timedelta
89
from http import HTTPStatus
910
from typing import TYPE_CHECKING, Any, TypeVar
@@ -53,6 +54,13 @@ def _is_retryable_error(exc: Exception) -> bool:
5354
)
5455

5556

57+
def _stop_retrying_if_permanent(exc: Exception, *, stop_retrying: Callable[[], None]) -> None:
58+
"""Stop the retry loop when an exception is not a transient transport failure."""
59+
if not _is_retryable_error(exc):
60+
logger.debug('Exception is not retryable', exc_info=exc)
61+
stop_retrying()
62+
63+
5664
@docs_group('HTTP clients')
5765
class ImpitHttpClient(HttpClient):
5866
"""Synchronous HTTP client for the Apify API built on top of [Impit](https://github.com/apify/impit).
@@ -232,9 +240,7 @@ def _make_request(
232240

233241
except Exception as exc:
234242
logger.debug('Request threw exception', exc_info=exc)
235-
if not _is_retryable_error(exc):
236-
logger.debug('Exception is not retryable', exc_info=exc)
237-
stop_retrying()
243+
_stop_retrying_if_permanent(exc, stop_retrying=stop_retrying)
238244
raise
239245

240246
# Retry only server errors (5xx) and rate limits (429).
@@ -246,8 +252,17 @@ def _make_request(
246252
logger.debug('Status code is not retryable', extra={'status_code': response.status_code})
247253
stop_retrying()
248254

249-
# Read the response in case it is a stream, so we can raise the error properly.
250-
response.read()
255+
# Read the response in case it is a stream, so we can raise the error properly. A read that fails is a
256+
# transport failure like any other, so it goes through the same classification as a failed send.
257+
try:
258+
response.read()
259+
except Exception as exc:
260+
logger.debug('Reading the error response failed', exc_info=exc)
261+
with suppress(Exception):
262+
response.close()
263+
_stop_retrying_if_permanent(exc, stop_retrying=stop_retrying)
264+
raise
265+
251266
raise ApifyApiError(response, attempt, method=method)
252267

253268
@staticmethod
@@ -494,9 +509,7 @@ async def _make_request(
494509

495510
except Exception as exc:
496511
logger.debug('Request threw exception', exc_info=exc)
497-
if not _is_retryable_error(exc):
498-
logger.debug('Exception is not retryable', exc_info=exc)
499-
stop_retrying()
512+
_stop_retrying_if_permanent(exc, stop_retrying=stop_retrying)
500513
raise
501514

502515
# Retry only server errors (5xx) and rate limits (429).
@@ -508,8 +521,17 @@ async def _make_request(
508521
logger.debug('Status code is not retryable', extra={'status_code': response.status_code})
509522
stop_retrying()
510523

511-
# Read the response in case it is a stream, so we can raise the error properly.
512-
await response.aread()
524+
# Read the response in case it is a stream, so we can raise the error properly. A read that fails is a
525+
# transport failure like any other, so it goes through the same classification as a failed send.
526+
try:
527+
await response.aread()
528+
except Exception as exc:
529+
logger.debug('Reading the error response failed', exc_info=exc)
530+
with suppress(Exception):
531+
await response.aclose()
532+
_stop_retrying_if_permanent(exc, stop_retrying=stop_retrying)
533+
raise
534+
513535
raise ApifyApiError(response, attempt, method=method)
514536

515537
@staticmethod

‎tests/unit/test_http_clients.py‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,55 @@ def test_is_retryable_error() -> None:
323323
assert not _is_retryable_error(Exception('test'))
324324

325325

326+
def test_error_response_read_failure_is_retried_and_closed() -> None:
327+
"""A failure while buffering a streamed error body is retried like a failed send, and the response is closed."""
328+
client = ImpitHttpClient(token='test_token', max_retries=1, min_delay_between_retries=timedelta(0))
329+
responses = [
330+
Mock(status_code=500, read=Mock(side_effect=impit.ReadError('truncated')), close=Mock()) for _ in range(2)
331+
]
332+
request = Mock(side_effect=responses)
333+
client._impit_client = Mock(request=request)
334+
335+
with pytest.raises(impit.ReadError):
336+
client.call(method='GET', url='https://api.test.com/endpoint', stream=True)
337+
338+
assert request.call_count == 2
339+
for response in responses:
340+
response.close.assert_called_once()
341+
342+
343+
async def test_error_response_read_failure_is_retried_and_closed_async() -> None:
344+
"""The async client also retries a failed buffering of a streamed error body and closes the response."""
345+
client = ImpitHttpClientAsync(token='test_token', max_retries=1, min_delay_between_retries=timedelta(0))
346+
responses = [
347+
Mock(status_code=500, aread=AsyncMock(side_effect=impit.ReadError('truncated')), aclose=AsyncMock())
348+
for _ in range(2)
349+
]
350+
request = AsyncMock(side_effect=responses)
351+
client._impit_async_client = Mock(request=request)
352+
353+
with pytest.raises(impit.ReadError):
354+
await client.call(method='GET', url='https://api.test.com/endpoint', stream=True)
355+
356+
assert request.call_count == 2
357+
for response in responses:
358+
response.aclose.assert_awaited_once()
359+
360+
361+
def test_non_retryable_error_response_read_failure_stops_retrying() -> None:
362+
"""A read failure that is not a transport error stops the retry loop instead of being retried."""
363+
client = ImpitHttpClient(token='test_token', min_delay_between_retries=timedelta(0))
364+
response = Mock(status_code=500, read=Mock(side_effect=ValueError('broken response')), close=Mock())
365+
request = Mock(return_value=response)
366+
client._impit_client = Mock(request=request)
367+
368+
with pytest.raises(ValueError, match='broken response'):
369+
client.call(method='GET', url='https://api.test.com/endpoint', stream=True)
370+
371+
request.assert_called_once()
372+
response.close.assert_called_once()
373+
374+
326375
@pytest.fixture(
327376
params=[
328377
pytest.param((GzipHttpCompressor(), 'gzip', gzip.decompress), id='gzip'),

0 commit comments

Comments
 (0)