Skip to content

Commit fbc7216

Browse files
committed
refactor: Remove duplicate retry classifier and correct transport error docs
1 parent d5197a5 commit fbc7216

5 files changed

Lines changed: 72 additions & 100 deletions

File tree

‎src/apify_client/_utils/errors.py‎

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,7 @@
22

33
from typing import TYPE_CHECKING
44

5-
import impit
6-
7-
from apify_client.errors import InvalidResponseBodyError, NotFoundError
5+
from apify_client.errors import NotFoundError
86

97
if TYPE_CHECKING:
108
from apify_client.errors import ApifyApiError
@@ -33,19 +31,3 @@ def catch_not_found_for_resource_or_throw(exc: ApifyApiError, resource_id: str |
3331
if resource_id is None:
3432
raise exc
3533
catch_not_found_or_throw(exc)
36-
37-
38-
def is_retryable_error(exc: Exception) -> bool:
39-
"""Check if the given error is retryable.
40-
41-
All `impit.HTTPError` subclasses are considered retryable because they represent transport-level failures
42-
(network issues, timeouts, protocol errors, body decoding errors) that are typically transient. HTTP status
43-
code errors are handled separately in `_make_request` based on the response status code, not here.
44-
"""
45-
return isinstance(
46-
exc,
47-
(
48-
InvalidResponseBodyError,
49-
impit.HTTPError,
50-
),
51-
)

‎src/apify_client/errors.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,9 +137,9 @@ class ServerError(ApifyApiError):
137137
class InvalidResponseBodyError(ApifyClientError):
138138
"""Error raised when a response body cannot be parsed.
139139
140-
This typically occurs when the API returns a partial or malformed JSON response, for example due to a network
141-
interruption. The client retries such requests automatically, so this error is only raised after all retry
142-
attempts have been exhausted.
140+
This occurs when the API returns a body that does not match its content type, for example a malformed JSON
141+
document. It is raised on a response the client already accepted, so it is not retried - a transfer that breaks
142+
mid-body surfaces as a transport error inside the retry loop instead.
143143
"""
144144

145145
def __init__(self, response: HttpResponse) -> None:

‎src/apify_client/http_clients/_impit.py‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,24 +38,28 @@
3838

3939

4040
_PERMANENT_ERRORS = (
41-
# A bad URL scheme or a request Impit itself rejects cannot succeed on a retry.
42-
impit.UnsupportedProtocol,
41+
# A request Impit rejects before sending it, e.g. one carrying an invalid header value.
4342
impit.LocalProtocolError,
43+
# The class Impit declares for a scheme it refuses to speak, but does not raise today - it reports an unsupported
44+
# scheme as `impit.InvalidURL`, which sits outside the `impit.HTTPError` tree and is non-retryable anyway. Listed
45+
# so the classifier stays right if Impit switches over.
46+
impit.UnsupportedProtocol,
4447
# An over-long redirect chain is a routing loop, which repeating the request cannot break.
4548
impit.TooManyRedirects,
46-
# Status codes are decided by `_make_request` from the response itself, never as a transport error.
49+
# Only `Response.raise_for_status()` raises this, and the client never calls it - `_make_request` decides on
50+
# status codes from the response itself.
4751
impit.HTTPStatusError,
4852
)
49-
"""Impit errors that a retry cannot fix. Everything else in the `impit.HTTPError` tree is treated as transient."""
5053

5154

5255
def _is_retryable_error(exc: Exception) -> bool:
5356
"""Check if an exception represents a transient transport failure that should be retried.
5457
5558
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.
59+
`_PERMANENT_ERRORS`. Retrying is the default because Impit also reports genuinely transient failures through
60+
its generic base class, e.g. a bare `impit.HTTPError` wrapping a failure its internal HTTP library did not
61+
classify. HTTP status code errors are handled separately in `_make_request` based on the response status code,
62+
not here.
5963
"""
6064
return isinstance(exc, impit.HTTPError) and not isinstance(exc, _PERMANENT_ERRORS)
6165

‎tests/unit/test_http_clients.py‎

Lines changed: 55 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -309,67 +309,84 @@ 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,
312+
@pytest.mark.parametrize(
313+
'exc',
314+
[
315+
# Impit wraps a failure its internal HTTP library did not classify in a bare `HTTPError`, so even the
316+
# generic base class is transient.
317+
pytest.param(impit.HTTPError('unclassified failure'), id='bare HTTPError'),
318+
pytest.param(impit.TimeoutException('timeout'), id='TimeoutException'),
319+
pytest.param(impit.NetworkError('network error'), id='NetworkError'),
320+
pytest.param(impit.RemoteProtocolError('remote protocol error'), id='RemoteProtocolError'),
321+
pytest.param(impit.DecodingError('decoding error'), id='DecodingError'),
322+
# One `ProxyError` covers both a proxy rejecting the CONNECT tunnel and a 407, so a transient case cannot
323+
# be told from a permanent one - retrying is the safer default.
324+
pytest.param(impit.ProxyError('proxy error'), id='ProxyError'),
325+
],
330326
)
331-
"""Transport errors that a retry cannot fix, so they must fail on the first attempt."""
327+
def test_is_retryable_error(exc: Exception) -> None:
328+
"""A transient transport failure is retried."""
329+
assert _is_retryable_error(exc)
332330

333331

334-
def test_is_retryable_error() -> None:
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()))
344-
assert not _is_retryable_error(ValueError('test'))
345-
assert not _is_retryable_error(RuntimeError('test'))
346-
assert not _is_retryable_error(Exception('test'))
332+
@pytest.mark.parametrize(
333+
'exc',
334+
[
335+
pytest.param(impit.LocalProtocolError('invalid header value'), id='LocalProtocolError'),
336+
pytest.param(impit.UnsupportedProtocol('unsupported scheme'), id='UnsupportedProtocol'),
337+
pytest.param(impit.TooManyRedirects('too many redirects'), id='TooManyRedirects'),
338+
pytest.param(impit.HTTPStatusError('status error'), id='HTTPStatusError'),
339+
# Impit reports a bad URL outside the `impit.HTTPError` tree entirely.
340+
pytest.param(impit.InvalidURL('unsupported scheme'), id='InvalidURL'),
341+
# `InvalidResponseBodyError` is raised by a resource client once `call` has returned, never in the retry loop.
342+
pytest.param(InvalidResponseBodyError(Mock()), id='InvalidResponseBodyError'),
343+
pytest.param(ValueError('value error'), id='ValueError'),
344+
pytest.param(RuntimeError('runtime error'), id='RuntimeError'),
345+
pytest.param(Exception('generic exception'), id='Exception'),
346+
],
347+
)
348+
def test_is_not_retryable_error(exc: Exception) -> None:
349+
"""A transport failure a retry cannot fix, and anything outside Impit's hierarchy, is not retried."""
350+
assert not _is_retryable_error(exc)
347351

348352

349353
def test_permanent_transport_error_is_not_retried() -> None:
350354
"""A transport error a retry cannot fix fails on the first attempt instead of burning the whole backoff."""
351355
client = ImpitHttpClient(token='test_token', min_delay_between_retries=timedelta(0))
352-
request = Mock(side_effect=impit.UnsupportedProtocol('unsupported scheme'))
356+
request = Mock(side_effect=impit.LocalProtocolError('invalid header value'))
353357
client._impit_client = Mock(request=request)
354358

355-
with pytest.raises(impit.UnsupportedProtocol):
356-
client.call(method='GET', url='ftp://api.test.com/endpoint')
359+
with pytest.raises(impit.LocalProtocolError):
360+
client.call(method='GET', url='https://api.test.com/endpoint')
357361

358362
request.assert_called_once()
359363

360364

361365
async def test_permanent_transport_error_is_not_retried_async() -> None:
362366
"""The async client applies the same policy, failing on the first attempt."""
363367
client = ImpitHttpClientAsync(token='test_token', min_delay_between_retries=timedelta(0))
364-
request = AsyncMock(side_effect=impit.UnsupportedProtocol('unsupported scheme'))
368+
request = AsyncMock(side_effect=impit.LocalProtocolError('invalid header value'))
365369
client._impit_async_client = Mock(request=request)
366370

367-
with pytest.raises(impit.UnsupportedProtocol):
368-
await client.call(method='GET', url='ftp://api.test.com/endpoint')
371+
with pytest.raises(impit.LocalProtocolError):
372+
await client.call(method='GET', url='https://api.test.com/endpoint')
369373

370374
request.assert_awaited_once()
371375

372376

377+
def test_transient_transport_error_is_retried() -> None:
378+
"""A transient transport failure keeps being retried until the attempts run out."""
379+
client = ImpitHttpClient(token='test_token', max_retries=2, min_delay_between_retries=timedelta(0))
380+
request = Mock(side_effect=impit.TimeoutException('timeout'))
381+
client._impit_client = Mock(request=request)
382+
383+
with pytest.raises(impit.TimeoutException):
384+
client.call(method='GET', url='https://api.test.com/endpoint')
385+
386+
# `max_retries` attempts inside the backoff loop, plus the final one it makes after the last delay.
387+
assert request.call_count == 3
388+
389+
373390
@pytest.fixture(
374391
params=[
375392
pytest.param((GzipHttpCompressor(), 'gzip', gzip.decompress), id='gzip'),

‎tests/unit/test_utils.py‎

Lines changed: 2 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -11,22 +11,21 @@
1111
from typing import TYPE_CHECKING, Any
1212
from unittest.mock import Mock
1313

14-
import impit
1514
import pytest
1615

1716
from apify_client._models import WebhookCondition, WebhookCreate
1817
from apify_client._resource_clients._resource_client import ResourceClientBase
1918
from apify_client._utils.crypto import create_hmac_signature, create_storage_content_signature, encode_base62
2019
from apify_client._utils.encoding import encode_key_value_store_record_value, encode_webhooks_to_base64
21-
from apify_client._utils.errors import catch_not_found_or_throw, is_retryable_error
20+
from apify_client._utils.errors import catch_not_found_or_throw
2221
from apify_client._utils.http import (
2322
is_compressible_content_type,
2423
response_to_dict,
2524
response_to_list,
2625
to_safe_id,
2726
)
2827
from apify_client._utils.try_import import FailedImport, try_import
29-
from apify_client.errors import ApifyApiError, InvalidResponseBodyError
28+
from apify_client.errors import ApifyApiError
3029

3130
if TYPE_CHECKING:
3231
from apify_client._typeddicts import WebhookRepresentationDict
@@ -187,36 +186,6 @@ def test_encode_webhooks_to_base64_from_dicts() -> None:
187186
assert result == result_from_models
188187

189188

190-
@pytest.mark.parametrize(
191-
'exc',
192-
[
193-
InvalidResponseBodyError(impit.Response(status_code=200)),
194-
impit.HTTPError('generic http error'),
195-
impit.NetworkError('network error'),
196-
impit.TimeoutException('timeout'),
197-
impit.RemoteProtocolError('remote protocol error'),
198-
impit.ReadError('read error'),
199-
impit.ConnectError('connect error'),
200-
impit.WriteError('write error'),
201-
impit.DecodingError('decoding error'),
202-
],
203-
)
204-
def test__is_retryable_error(exc: Exception) -> None:
205-
assert is_retryable_error(exc) is True
206-
207-
208-
@pytest.mark.parametrize(
209-
'exc',
210-
[
211-
Exception('generic exception'),
212-
ValueError('value error'),
213-
RuntimeError('runtime error'),
214-
],
215-
)
216-
def test__is_not_retryable_error(exc: Exception) -> None:
217-
assert is_retryable_error(exc) is False
218-
219-
220189
@pytest.mark.parametrize(
221190
('status_code', 'error_type', 'should_suppress'),
222191
[

0 commit comments

Comments
 (0)