Skip to content

Commit b390f63

Browse files
authored
feat(request-loaders)!: Add sitemap timeout and retries options (#2519)
### Description `SitemapRequestLoader` takes `sitemap_timeout` and `sitemap_retries`. `sitemap_timeout` limits each attempt to fetch a sitemap, including reading its body, and defaults to 30 seconds. Reading pauses while the loader's buffer is full, so a slow crawl of a large sitemap may need a higher timeout. `None` disables it. `sitemap_retries` counts the retries after the first attempt and defaults to 3, so a sitemap that keeps failing is now fetched up to 4 times instead of 3. ### Testing - Unit tests that the timeout and the number of retries reach the sitemap fetch, also with the timeout disabled. The tests that count attempts now expect one more attempt. *✍️ Drafted by Claude Code*
1 parent 3ba709c commit b390f63

5 files changed

Lines changed: 83 additions & 14 deletions

File tree

‎docs/06_upgrading/upgrading_to_v2.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -650,6 +650,10 @@ class MyHttpClient(HttpClient):
650650

651651
`SitemapRequestLoader.fetch_next_request` skips a URL while its request is still in progress, for example when another sitemap lists it too. In v1, it returned a request for the URL again, and `get_total_count` counted the URL twice.
652652

653+
## Sitemap fetch retries
654+
655+
`SitemapRequestLoader` now fetches a sitemap that keeps failing up to 4 times instead of 3. Its `sitemap_retries` counts the retries after the first attempt, as in Crawlee JS. To keep 3 attempts, pass `sitemap_retries=2`.
656+
653657
## Crawlers manage only what they create
654658

655659
A crawler now enters and exits only the objects it creates, the same as Crawlee JS. An object you pass is yours to enter and exit. The `Statistics` and the event managers are the exceptions, since the crawler enters them on every run. You can enter an event manager yourself as well. In v1, the crawler entered a passed object that wasn't active yet and exited it when its run finished, even while another crawler still used it.

‎src/crawlee/_utils/sitemap.py‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,7 @@ async def _fetch_and_process_sitemap(
400400
depth: int,
401401
visited_sitemap_urls: set[str],
402402
sources: list[SitemapSource],
403-
retries_left: int,
403+
attempts_left: int,
404404
proxy_info: ProxyInfo | None = None,
405405
timeout: timedelta | None = None,
406406
emit_nested_sitemaps: bool,
@@ -413,8 +413,8 @@ async def _fetch_and_process_sitemap(
413413

414414
sitemap_url = source['url']
415415

416-
while retries_left > 0:
417-
retries_left -= 1
416+
while attempts_left > 0:
417+
attempts_left -= 1
418418
try:
419419
response = await http_client.send_request(
420420
sitemap_url, method='GET', headers=SITEMAP_HEADERS, proxy_info=proxy_info, timeout=timeout
@@ -514,21 +514,21 @@ async def _fetch_and_process_sitemap(
514514
parsed_ok.append(True)
515515

516516
except _RetryableSitemapStatusError as e:
517-
if retries_left > 0:
517+
if attempts_left > 0:
518518
logger.warning(
519519
'Error fetching sitemap %s: HTTP status %s. Retries left: %s',
520520
sitemap_url,
521521
e.status_code,
522-
retries_left,
522+
attempts_left,
523523
)
524524
await asyncio.sleep(SITEMAP_RETRY_DELAY)
525525
else:
526526
logger.warning(
527527
'Failed to fetch sitemap %s, no retries left: HTTP status %s.', sitemap_url, e.status_code
528528
)
529529
except Exception as e:
530-
if retries_left > 0:
531-
logger.warning('Error fetching sitemap %s: %s. Retries left: %s', sitemap_url, e, retries_left)
530+
if attempts_left > 0:
531+
logger.warning('Error fetching sitemap %s: %s. Retries left: %s', sitemap_url, e, attempts_left)
532532
await asyncio.sleep(SITEMAP_RETRY_DELAY)
533533
else:
534534
logger.exception('Failed to fetch sitemap %s, no retries left.', sitemap_url)
@@ -671,7 +671,7 @@ async def parse_sitemap(
671671
depth=depth,
672672
visited_sitemap_urls=visited_sitemap_urls,
673673
sources=sources,
674-
retries_left=sitemap_retries,
674+
attempts_left=sitemap_retries + 1,
675675
emit_nested_sitemaps=emit_nested_sitemaps,
676676
enqueue_strategy=enqueue_strategy,
677677
proxy_info=proxy_info,

‎src/crawlee/request_loaders/_sitemap_request_loader.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import asyncio
44
from collections import deque
55
from contextlib import aclosing, suppress
6+
from datetime import timedelta
67
from logging import getLogger
78
from typing import TYPE_CHECKING, Annotated, Any
89

@@ -136,6 +137,8 @@ def __init__(
136137
include: list[re.Pattern[Any] | Glob] | None = None,
137138
exclude: list[re.Pattern[Any] | Glob] | None = None,
138139
enqueue_strategy: EnqueueStrategy = 'same-hostname',
140+
sitemap_retries: int = 3,
141+
sitemap_timeout: timedelta | None = timedelta(seconds=30),
139142
max_buffer_size: int = 200,
140143
persist_state_key: str | None = None,
141144
transform_request_function: Callable[[RequestOptions], RequestOptions | RequestTransformAction] | None = None,
@@ -153,6 +156,10 @@ def __init__(
153156
the sitemap protocol's same-host expectation and the `enqueue_links` default; pass `'all'` to
154157
disable filtering. Note: regardless of `enqueue_strategy`, entries with non-`http(s)` schemes are
155158
always filtered out.
159+
sitemap_retries: Maximum number of retries of a failed sitemap fetch.
160+
sitemap_timeout: Timeout for each attempt to fetch a sitemap, including reading its body, or `None` for no
161+
timeout. Reading pauses while the buffer is full, so a slow crawl of a large sitemap needs a higher
162+
one, or the rest of the sitemap is skipped.
156163
max_buffer_size: Maximum number of URLs to buffer in memory.
157164
http_client: the instance of `HttpClient` to use for fetching sitemaps.
158165
persist_state_key: A key for persisting the loader's state in the KeyValueStore.
@@ -161,12 +168,20 @@ def __init__(
161168
transform_request_function: An optional function to transform requests
162169
generated by the loader. It receives `RequestOptions` with `url` and should return either
163170
modified `RequestOptions` or a `RequestTransformAction`.
171+
172+
Raises:
173+
ValueError: If `sitemap_retries` is negative.
164174
"""
175+
if sitemap_retries < 0:
176+
raise ValueError(f'sitemap_retries must not be negative, got {sitemap_retries}.')
177+
165178
self._http_client = http_client
166179
self._sitemap_urls = sitemap_urls
167180
self._include = include
168181
self._exclude = exclude
169182
self._enqueue_strategy = enqueue_strategy
183+
self._sitemap_retries = sitemap_retries
184+
self._sitemap_timeout = sitemap_timeout
170185
self._proxy_info = proxy_info
171186
self._max_buffer_size = max_buffer_size
172187
self._transform_request_function = transform_request_function
@@ -403,8 +418,9 @@ async def _load_sitemaps(self) -> None:
403418
parse_options = ParseSitemapOptions(
404419
max_depth=0,
405420
emit_nested_sitemaps=True,
406-
sitemap_retries=3,
421+
sitemap_retries=self._sitemap_retries,
407422
enqueue_strategy=self._enqueue_strategy,
423+
timeout=self._sitemap_timeout,
408424
)
409425
parsed_sitemap_url = URL(sitemap_url)
410426

‎tests/unit/_utils/test_sitemap.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ async def test_sitemap_fetch_raises_after_retries_exhausted(monkeypatch: pytest.
201201
with pytest.raises(ConnectionError):
202202
_ = [item async for item in parse_sitemap([{'type': 'url', 'url': f'{DEFAULT_URL}sitemap.xml'}], client)]
203203

204-
assert len(attempts) == 3
204+
assert len(attempts) == 4
205205

206206

207207
async def test_sitemap_fetch_retries_retryable_http_status(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -226,7 +226,7 @@ async def test_sitemap_fetch_skips_http_error_after_retries_exhausted(monkeypatc
226226

227227
items = [item async for item in parse_sitemap([{'type': 'url', 'url': sitemap_url}], client)]
228228

229-
assert attempts == [503, 503, 503]
229+
assert attempts == [503, 503, 503, 503]
230230
assert items == []
231231

232232

@@ -287,15 +287,15 @@ async def test_sitemap_partial_http_failure_keeps_healthy_source() -> None:
287287
async def test_sitemap_partial_fetch_failure_keeps_healthy_source(monkeypatch: pytest.MonkeyPatch) -> None:
288288
"""A fetch exception in one source is suppressed when another source succeeds."""
289289
monkeypatch.setattr('crawlee._utils.sitemap.SITEMAP_RETRY_DELAY', 0)
290-
client, attempts = _make_flaky_stream_client(get_basic_sitemap().encode(), fail_times=3)
290+
client, attempts = _make_flaky_stream_client(get_basic_sitemap().encode(), fail_times=4)
291291
sources: list[SitemapSource] = [
292292
{'type': 'url', 'url': f'{DEFAULT_URL}broken.xml'},
293293
{'type': 'url', 'url': f'{DEFAULT_URL}sitemap.xml'},
294294
]
295295

296296
items = [item async for item in parse_sitemap(sources, client)]
297297

298-
assert len(attempts) == 4
298+
assert len(attempts) == 5
299299
assert {item.loc for item in items} == get_basic_results()
300300

301301

‎tests/unit/request_loaders/test_sitemap_request_loader.py‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import gzip
2+
from datetime import timedelta
23
from typing import TYPE_CHECKING, Any, cast
34
from unittest.mock import AsyncMock, MagicMock, Mock
45

@@ -92,7 +93,55 @@ async def test_sitemap_http_error_is_skipped_after_retries_exhausted(monkeypatch
9293

9394
assert await loader.fetch_next_request() is None
9495

95-
assert attempts == [503, 503, 503]
96+
assert attempts == [503, 503, 503, 503]
97+
98+
99+
@pytest.mark.parametrize(
100+
('sitemap_timeout', 'sitemap_retries', 'expected_attempts'),
101+
[
102+
pytest.param(timedelta(seconds=5), 0, 1, id='timeout-no-retries'),
103+
pytest.param(None, 2, 3, id='no-timeout-two-retries'),
104+
],
105+
)
106+
async def test_sitemap_timeout_and_retries(
107+
monkeypatch: pytest.MonkeyPatch,
108+
sitemap_timeout: timedelta | None,
109+
sitemap_retries: int,
110+
expected_attempts: int,
111+
) -> None:
112+
"""`sitemap_timeout` and `sitemap_retries` apply to each sitemap fetch."""
113+
monkeypatch.setattr('crawlee._utils.sitemap.SITEMAP_RETRY_DELAY', 0)
114+
sitemap_url = f'{DEFAULT_URL}sitemap.xml'
115+
client, _ = make_status_stream_client({sitemap_url: [(503, b'')]})
116+
loader = SitemapRequestLoader(
117+
[sitemap_url],
118+
http_client=client,
119+
sitemap_retries=sitemap_retries,
120+
sitemap_timeout=sitemap_timeout,
121+
)
122+
123+
assert await loader.fetch_next_request() is None
124+
125+
timeouts = [call.kwargs['timeout'] for call in client.send_request.call_args_list]
126+
assert timeouts == [sitemap_timeout] * expected_attempts
127+
128+
129+
async def test_sitemap_timeout_defaults_to_30_seconds(monkeypatch: pytest.MonkeyPatch) -> None:
130+
"""Each attempt to fetch a sitemap times out after 30 seconds unless `sitemap_timeout` is set."""
131+
monkeypatch.setattr('crawlee._utils.sitemap.SITEMAP_RETRY_DELAY', 0)
132+
sitemap_url = f'{DEFAULT_URL}sitemap.xml'
133+
client, _ = make_status_stream_client({sitemap_url: [(503, b'')]})
134+
loader = SitemapRequestLoader([sitemap_url], http_client=client)
135+
136+
assert await loader.fetch_next_request() is None
137+
138+
assert client.send_request.call_args.kwargs['timeout'] == timedelta(seconds=30)
139+
140+
141+
async def test_negative_sitemap_retries_raises() -> None:
142+
"""A negative `sitemap_retries` is rejected."""
143+
with pytest.raises(ValueError, match='sitemap_retries must not be negative'):
144+
SitemapRequestLoader([f'{DEFAULT_URL}sitemap.xml'], http_client=AsyncMock(spec=HttpClient), sitemap_retries=-1)
96145

97146

98147
async def test_sitemap_loader_drains_requests_after_later_source_fails(monkeypatch: pytest.MonkeyPatch) -> None:

0 commit comments

Comments
 (0)