-
Notifications
You must be signed in to change notification settings - Fork 706
feat: Add opt-in per-domain request throttling for HTTP 429 backoff #1762
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from 2 commits
64f7247
62ab3b8
1065e9b
138fd67
abdf51c
dd99d9d
497b782
902f885
e02dd68
2e3493c
ac18556
44b93bb
412df15
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| """HTTP utility functions for Crawlee.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from datetime import datetime, timedelta, timezone | ||
|
|
||
|
|
||
| def parse_retry_after_header(value: str | None) -> timedelta | None: | ||
| """Parse the Retry-After HTTP header value. | ||
|
|
||
| The header can contain either a number of seconds or an HTTP-date. | ||
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After | ||
|
|
||
| Args: | ||
| value: The raw Retry-After header value. | ||
|
|
||
| Returns: | ||
| A timedelta representing the delay, or None if the header is missing or unparseable. | ||
| """ | ||
| if not value: | ||
| return None | ||
|
|
||
| # Try parsing as integer seconds first. | ||
| try: | ||
| seconds = int(value) | ||
| return timedelta(seconds=seconds) | ||
| except ValueError: | ||
| pass | ||
|
|
||
| # Try parsing as HTTP-date (e.g., "Wed, 21 Oct 2015 07:28:00 GMT"). | ||
| from email.utils import parsedate_to_datetime # noqa: PLC0415 | ||
|
|
||
| try: | ||
| retry_date = parsedate_to_datetime(value) | ||
| delay = retry_date - datetime.now(retry_date.tzinfo or timezone.utc) | ||
| if delay.total_seconds() > 0: | ||
| return delay | ||
| except (ValueError, TypeError): | ||
| pass | ||
|
|
||
| return None | ||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -12,7 +12,7 @@ | |||||
| from asyncio import CancelledError | ||||||
| from collections.abc import AsyncGenerator, Awaitable, Callable, Iterable, Sequence | ||||||
| from contextlib import AsyncExitStack, suppress | ||||||
| from datetime import timedelta | ||||||
| from datetime import datetime, timedelta, timezone | ||||||
| from functools import partial | ||||||
| from io import StringIO | ||||||
| from pathlib import Path | ||||||
|
|
@@ -46,6 +46,8 @@ | |||||
| from crawlee._utils.docs import docs_group | ||||||
| from crawlee._utils.file import atomic_write, export_csv_to_stream, export_json_to_stream | ||||||
| from crawlee._utils.recurring_task import RecurringTask | ||||||
| from crawlee._utils.http import parse_retry_after_header | ||||||
| from crawlee.request_loaders import ThrottlingRequestManager | ||||||
| from crawlee._utils.robots import RobotsTxtFile | ||||||
| from crawlee._utils.urls import convert_to_absolute_url, is_url_absolute | ||||||
| from crawlee._utils.wait import wait_for | ||||||
|
|
@@ -485,6 +487,7 @@ async def persist_state_factory() -> KeyValueStore: | |||||
| self._robots_txt_file_cache: LRUCache[str, RobotsTxtFile] = LRUCache(maxsize=1000) | ||||||
| self._robots_txt_lock = asyncio.Lock() | ||||||
| self._tld_extractor = TLDExtract(cache_dir=tempfile.TemporaryDirectory().name) | ||||||
| self._throttling_manager: ThrottlingRequestManager | None = None | ||||||
| self._snapshotter = Snapshotter.from_config(config) | ||||||
| self._autoscaled_pool = AutoscaledPool( | ||||||
| system_status=SystemStatus(self._snapshotter), | ||||||
|
|
@@ -611,12 +614,18 @@ async def _get_proxy_info(self, request: Request, session: Session | None) -> Pr | |||||
| ) | ||||||
|
|
||||||
| async def get_request_manager(self) -> RequestManager: | ||||||
| """Return the configured request manager. If none is configured, open and return the default request queue.""" | ||||||
| """Return the configured request manager. If none is configured, open and return the default request queue. | ||||||
|
|
||||||
| The returned manager is wrapped with `ThrottlingRequestManager` to enforce | ||||||
| per-domain delays from 429 responses and robots.txt crawl-delay directives. | ||||||
| """ | ||||||
| if not self._request_manager: | ||||||
| self._request_manager = await RequestQueue.open( | ||||||
| inner = await RequestQueue.open( | ||||||
| storage_client=self._service_locator.get_storage_client(), | ||||||
| configuration=self._service_locator.get_configuration(), | ||||||
| ) | ||||||
| self._throttling_manager = ThrottlingRequestManager(inner) | ||||||
| self._request_manager = self._throttling_manager | ||||||
|
||||||
|
|
||||||
| return self._request_manager | ||||||
|
|
||||||
|
|
@@ -1442,6 +1451,10 @@ async def __run_task_function(self) -> None: | |||||
|
|
||||||
| await self._mark_request_as_handled(request) | ||||||
|
|
||||||
| # Record successful request to reset rate limit backoff for this domain. | ||||||
| if self._throttling_manager: | ||||||
| self._throttling_manager.record_success(request.url) | ||||||
|
||||||
|
|
||||||
| if session and session.is_usable: | ||||||
| session.mark_good() | ||||||
|
|
||||||
|
|
@@ -1542,22 +1555,41 @@ def _raise_for_error_status_code(self, status_code: int) -> None: | |||||
| if is_status_code_server_error(status_code) and not is_ignored_status: | ||||||
| raise HttpStatusCodeError('Error status code returned', status_code) | ||||||
|
|
||||||
| def _raise_for_session_blocked_status_code(self, session: Session | None, status_code: int) -> None: | ||||||
| def _raise_for_session_blocked_status_code( | ||||||
| self, | ||||||
| session: Session | None, | ||||||
| status_code: int, | ||||||
janbuchar marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
| *, | ||||||
| url: str = '', | ||||||
| retry_after_header: str | None = None, | ||||||
| ) -> None: | ||||||
| """Raise an exception if the given status code indicates the session is blocked. | ||||||
|
|
||||||
| If the status code is 429 (Too Many Requests), the domain is recorded as | ||||||
| rate-limited in the `RequestThrottler` for per-domain backoff. | ||||||
|
||||||
|
|
||||||
| Args: | ||||||
| session: The session used for the request. If None, no check is performed. | ||||||
| status_code: The HTTP status code to check. | ||||||
| url: The request URL, used for per-domain rate limit tracking. | ||||||
|
||||||
| retry_after_header: The value of the Retry-After response header, if present. | ||||||
|
|
||||||
| Raises: | ||||||
| SessionError: If the status code indicates the session is blocked. | ||||||
| """ | ||||||
| if status_code == 429 and url: | ||||||
| retry_after = parse_retry_after_header(retry_after_header) | ||||||
| if self._throttling_manager: | ||||||
| self._throttling_manager.record_domain_delay(url, retry_after=retry_after) | ||||||
|
|
||||||
| if session is not None and session.is_blocked_status_code( | ||||||
| status_code=status_code, | ||||||
| ignore_http_error_status_codes=self._ignore_http_error_status_codes, | ||||||
| ): | ||||||
| raise SessionError(f'Assuming the session is blocked based on HTTP status code {status_code}') | ||||||
|
|
||||||
| # NOTE: _parse_retry_after_header has been moved to crawlee._utils.http.parse_retry_after_header | ||||||
|
|
||||||
|
||||||
| # NOTE: _parse_retry_after_header has been moved to crawlee._utils.http.parse_retry_after_header |
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| # Wire robots.txt crawl-delay into ThrottlingRequestManager (#1396). | |
| # Wire robots.txt crawl-delay into ThrottlingRequestManager |
Uh oh!
There was an error while loading. Please reload this page.