Skip to content

Commit d5197a5

Browse files
committed
fix: Fail fast on transport errors a retry cannot fix
1 parent 334e131 commit d5197a5

2 files changed

Lines changed: 74 additions & 20 deletions

File tree

‎src/apify_client/http_clients/_impit.py‎

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from apify_client._docs import docs_group
2222
from apify_client._logging import log_context, logger_name
2323
from apify_client._utils.time import to_seconds
24-
from apify_client.errors import ApifyApiError, InvalidResponseBodyError
24+
from apify_client.errors import ApifyApiError
2525
from apify_client.http_clients._base import HttpClient, HttpClientAsync
2626

2727
if TYPE_CHECKING:
@@ -37,20 +37,27 @@
3737
logger = logging.getLogger(logger_name)
3838

3939

40+
_PERMANENT_ERRORS = (
41+
# A bad URL scheme or a request Impit itself rejects cannot succeed on a retry.
42+
impit.UnsupportedProtocol,
43+
impit.LocalProtocolError,
44+
# An over-long redirect chain is a routing loop, which repeating the request cannot break.
45+
impit.TooManyRedirects,
46+
# Status codes are decided by `_make_request` from the response itself, never as a transport error.
47+
impit.HTTPStatusError,
48+
)
49+
"""Impit errors that a retry cannot fix. Everything else in the `impit.HTTPError` tree is treated as transient."""
50+
51+
4052
def _is_retryable_error(exc: Exception) -> bool:
41-
"""Check if an exception represents a transient error that should be retried.
53+
"""Check if an exception represents a transient transport failure that should be retried.
4254
43-
All `impit.HTTPError` subclasses are considered retryable because they represent transport-level failures
44-
(network issues, timeouts, protocol errors, body decoding errors) that are typically transient. HTTP status
45-
code errors are handled separately in `_make_request` based on the response status code, not here.
55+
Every error from Impit's own hierarchy counts as transient except the permanently-failing types listed in
56+
`_PERMANENT_ERRORS`. Retrying is the default because Impit also reports genuinely transient failures through its
57+
generic base class, e.g. a bare `impit.HTTPError` for a body that ends mid-chunk. HTTP status code errors are
58+
handled separately in `_make_request` based on the response status code, not here.
4659
"""
47-
return isinstance(
48-
exc,
49-
(
50-
InvalidResponseBodyError,
51-
impit.HTTPError,
52-
),
53-
)
60+
return isinstance(exc, impit.HTTPError) and not isinstance(exc, _PERMANENT_ERRORS)
5461

5562

5663
@docs_group('HTTP clients')

‎tests/unit/test_http_clients.py‎

Lines changed: 55 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -309,20 +309,67 @@ def test_parse_params_mixed() -> None:
309309
}
310310

311311

312+
RETRYABLE_TRANSPORT_ERRORS = (
313+
# Impit raises a bare `HTTPError` for a body that ends mid-chunk, so even the generic base class is transient.
314+
impit.HTTPError,
315+
impit.TimeoutException,
316+
impit.NetworkError,
317+
impit.RemoteProtocolError,
318+
impit.DecodingError,
319+
# A proxy rejecting the tunnel is often transient, e.g. one that is overloaded or rate-limiting.
320+
impit.ProxyError,
321+
)
322+
"""Transport errors that must stay retryable."""
323+
324+
NON_RETRYABLE_TRANSPORT_ERRORS = (
325+
impit.UnsupportedProtocol,
326+
impit.LocalProtocolError,
327+
impit.TooManyRedirects,
328+
# No built-in client ever raises this one, because `_make_request` decides on status codes from the response.
329+
impit.HTTPStatusError,
330+
)
331+
"""Transport errors that a retry cannot fix, so they must fail on the first attempt."""
332+
333+
312334
def test_is_retryable_error() -> None:
313-
"""Test _is_retryable_error correctly identifies retryable errors."""
314-
mock_response = Mock()
315-
assert _is_retryable_error(InvalidResponseBodyError(mock_response))
316-
assert _is_retryable_error(impit.NetworkError('test'))
317-
assert _is_retryable_error(impit.TimeoutException('test'))
318-
assert _is_retryable_error(impit.RemoteProtocolError('test'))
319-
320-
# Non-retryable errors
335+
"""Transient transport failures are retried, and the ones a retry cannot fix are not."""
336+
for error_class in RETRYABLE_TRANSPORT_ERRORS:
337+
assert _is_retryable_error(error_class('test')), error_class.__name__
338+
339+
for error_class in NON_RETRYABLE_TRANSPORT_ERRORS:
340+
assert not _is_retryable_error(error_class('test')), error_class.__name__
341+
342+
# `InvalidResponseBodyError` is raised by a resource client once `call` has returned, never inside the retry loop.
343+
assert not _is_retryable_error(InvalidResponseBodyError(Mock()))
321344
assert not _is_retryable_error(ValueError('test'))
322345
assert not _is_retryable_error(RuntimeError('test'))
323346
assert not _is_retryable_error(Exception('test'))
324347

325348

349+
def test_permanent_transport_error_is_not_retried() -> None:
350+
"""A transport error a retry cannot fix fails on the first attempt instead of burning the whole backoff."""
351+
client = ImpitHttpClient(token='test_token', min_delay_between_retries=timedelta(0))
352+
request = Mock(side_effect=impit.UnsupportedProtocol('unsupported scheme'))
353+
client._impit_client = Mock(request=request)
354+
355+
with pytest.raises(impit.UnsupportedProtocol):
356+
client.call(method='GET', url='ftp://api.test.com/endpoint')
357+
358+
request.assert_called_once()
359+
360+
361+
async def test_permanent_transport_error_is_not_retried_async() -> None:
362+
"""The async client applies the same policy, failing on the first attempt."""
363+
client = ImpitHttpClientAsync(token='test_token', min_delay_between_retries=timedelta(0))
364+
request = AsyncMock(side_effect=impit.UnsupportedProtocol('unsupported scheme'))
365+
client._impit_async_client = Mock(request=request)
366+
367+
with pytest.raises(impit.UnsupportedProtocol):
368+
await client.call(method='GET', url='ftp://api.test.com/endpoint')
369+
370+
request.assert_awaited_once()
371+
372+
326373
@pytest.fixture(
327374
params=[
328375
pytest.param((GzipHttpCompressor(), 'gzip', gzip.decompress), id='gzip'),

0 commit comments

Comments
 (0)