Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 38 additions & 30 deletions src/crawlee/request_loaders/_throttling_request_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

import asyncio
import ipaddress
import time
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from datetime import timedelta
from logging import getLogger
from typing import TYPE_CHECKING, Generic, Protocol, TypeVar

Expand All @@ -30,7 +31,7 @@
TRequestManager_co = TypeVar('TRequestManager_co', bound=RequestManager, covariant=True)
"""Covariant counterpart of `TRequestManager`, for protocols that only ever return a request manager."""

_NEVER_THROTTLED = datetime.min.replace(tzinfo=timezone.utc)
_NEVER_THROTTLED = float('-inf')
"""Sentinel timestamp meaning one of a domain's throttle clocks has never been armed."""

_MAX_BACKOFF_EXPONENT = 20
Expand Down Expand Up @@ -332,7 +333,7 @@ async def is_empty(self) -> bool:
don't count either.
"""
await self._ensure_sub_managers()
now = datetime.now(timezone.utc)
now = time.monotonic()
results = await asyncio.gather(
self._inner.is_empty(),
*(
Expand All @@ -358,7 +359,7 @@ async def get_stall_reason(self) -> str | None:
only when nothing else can be dispatched and no domain in a cooldown has requests left.
"""
await self._ensure_sub_managers()
now = datetime.now(timezone.utc)
now = time.monotonic()
dispatchable: list[RequestManager] = [self._inner]
cooling: list[RequestManager] = []
candidates: list[str] = []
Expand Down Expand Up @@ -391,7 +392,7 @@ async def get_stall_reason(self) -> str | None:
return None

summary = ', '.join(
f'"{domain}" ({(now - since).total_seconds():.0f}s)'
f'"{domain}" ({now - since:.0f}s)'
for domain in stalled
if (since := self._domain_states[domain].rate_limited_since) is not None
)
Expand Down Expand Up @@ -423,7 +424,7 @@ def record_domain_delay(self, url: str, *, retry_after: timedelta | None = None)
if state is None:
return False

now = datetime.now(timezone.utc)
now = time.monotonic()

state.last_rate_limited_at = now
if state.rate_limited_since is None:
Expand Down Expand Up @@ -596,7 +597,7 @@ async def _fetch_from_inner(self) -> Request | None:
return None

state = self._get_domain_state(request.url)
if state is None or datetime.now(timezone.utc) >= state.throttled_until:
if state is None or time.monotonic() >= state.throttled_until:
return request

await self._migrate_to_sub_manager(request)
Expand Down Expand Up @@ -627,11 +628,11 @@ def _is_domain_throttled(self, domain: str) -> bool:
state = self._domain_states.get(domain)
if state is None:
return False
return datetime.now(timezone.utc) < state.throttled_until
return time.monotonic() < state.throttled_until

def _fetchable_domains(self) -> list[str]:
"""Return the configured domains that are not in a cooldown right now, longest-overdue first."""
now = datetime.now(timezone.utc)
now = time.monotonic()
available = [domain for domain, state in self._domain_states.items() if now >= state.throttled_until]
available.sort(key=lambda domain: self._domain_states[domain].throttled_until)
return available
Expand All @@ -640,7 +641,7 @@ def _mark_domain_dispatched(self, domain: str) -> None:
"""Push the domain's `crawl_delay_until` forward by its crawl-delay, if it has one."""
state = self._domain_states.get(domain)
if state is not None:
state.apply_crawl_delay(datetime.now(timezone.utc))
state.apply_crawl_delay(time.monotonic())

def _fetch_owner(self, request: Request) -> TRequestManager:
"""Return the manager the request must be given back to, leaving its in-flight record in place.
Expand Down Expand Up @@ -680,55 +681,62 @@ class _DomainState:
domain: str
"""The domain being tracked."""

backoff_until: datetime = _NEVER_THROTTLED
"""Earliest time the next request is allowed by the 429 backoff. Kept apart from `crawl_delay_until`, which is
armed on every dispatch and would otherwise pass for an active backoff.
backoff_until: float = _NEVER_THROTTLED
"""Earliest monotonic time the next request is allowed by the 429 backoff. Kept apart from `crawl_delay_until`,
which is armed on every dispatch and would otherwise pass for an active backoff.
"""

crawl_delay_until: datetime = _NEVER_THROTTLED
"""Earliest time the next request is allowed by the domain's crawl-delay."""
crawl_delay_until: float = _NEVER_THROTTLED
"""Earliest monotonic time the next request is allowed by the domain's crawl-delay."""

backoff_decays_at: datetime = _NEVER_THROTTLED
"""Time after which an incoming 429 is treated as a fresh burst rather than a continuation of the current one."""
backoff_decays_at: float = _NEVER_THROTTLED
"""Monotonic time after which an incoming 429 is treated as a fresh burst rather than a continuation."""

consecutive_429_count: int = 0
"""Number of consecutive 429 responses (for exponential backoff)."""

crawl_delay: timedelta | None = None
"""Minimum interval between requests, used to push `crawl_delay_until` on dispatch."""

rate_limited_since: datetime | None = None
"""Time of the first 429 since the domain last completed a request."""
rate_limited_since: float | None = None
"""Monotonic time of the first 429 since the domain last completed a request."""

last_rate_limited_at: datetime | None = None
"""Time of the most recent 429 from the domain."""
last_rate_limited_at: float | None = None
"""Monotonic time of the most recent 429 from the domain."""

@property
def throttled_until(self) -> datetime:
"""Earliest time the next request to this domain is allowed by either of its two independent clocks."""
def throttled_until(self) -> float:
"""Earliest monotonic time the next request to this domain is allowed by either of its two independent clocks."""
return max(self.backoff_until, self.crawl_delay_until)

def apply_backoff(self, now: datetime, delay: timedelta) -> None:
def apply_backoff(self, now: float, delay: timedelta) -> None:
"""Block the domain for `delay`.

If no 429 arrives for another `delay` after the domain becomes dispatchable again, the exponent resets.
"""
self.backoff_until = now + delay
delay_seconds = delay.total_seconds()
self.backoff_until = now + delay_seconds
# The quiet period runs from the moment the domain becomes dispatchable again, not from `backoff_until`. A
# crawl-delay longer than `delay` sets the retry cadence, and measuring from `backoff_until` would expire the
# window before the domain is even retried, making every 429 look like a fresh burst.
self.backoff_decays_at = self.throttled_until + delay
self.backoff_decays_at = self.throttled_until + delay_seconds

def is_stall_candidate(self, now: datetime, window: timedelta) -> bool:
def is_stall_candidate(self, now: float, window: timedelta) -> bool:
"""Check whether the domain still rate-limits us and has rate-limited every request for longer than `window`."""
since = self.rate_limited_since
last = self.last_rate_limited_at
return since is not None and last is not None and now - last <= window and now - since > window
window_seconds = window.total_seconds()
return (
since is not None
and last is not None
and now - last <= window_seconds
and now - since > window_seconds
)

def apply_crawl_delay(self, now: datetime) -> None:
def apply_crawl_delay(self, now: float) -> None:
"""Block the domain for its crawl-delay, if it declared one."""
if self.crawl_delay is not None:
self.crawl_delay_until = now + self.crawl_delay
self.crawl_delay_until = now + self.crawl_delay.total_seconds()

def reset_throttling(self) -> None:
"""Clear the transient throttle state."""
Expand Down