diff --git a/src/crawlee/request_loaders/_throttling_request_manager.py b/src/crawlee/request_loaders/_throttling_request_manager.py index 5634155913..358a1b0931 100644 --- a/src/crawlee/request_loaders/_throttling_request_manager.py +++ b/src/crawlee/request_loaders/_throttling_request_manager.py @@ -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 @@ -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 @@ -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(), *( @@ -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] = [] @@ -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 ) @@ -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: @@ -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) @@ -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 @@ -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. @@ -680,16 +681,16 @@ 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).""" @@ -697,38 +698,45 @@ class _DomainState: 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."""