|
| 1 | +"""Shared request-shaping and response-handling helpers for the sync and async clients. |
| 2 | +
|
| 3 | +Both ``Diffbot`` and ``DiffbotAsync`` delegate here so the two don't carry duplicate |
| 4 | +copies of retry/timeout/error-raising logic; the only difference between them is |
| 5 | +whether the underlying ``httpx.Client``/``httpx.AsyncClient`` call is awaited. |
| 6 | +""" |
| 7 | + |
| 8 | +import asyncio |
| 9 | +import random |
| 10 | +import time |
| 11 | +from dataclasses import dataclass |
| 12 | +from email.utils import parsedate_to_datetime |
| 13 | +from typing import Any, Dict, Optional, Sequence, Union |
| 14 | + |
| 15 | +import httpx |
| 16 | + |
| 17 | +from .errors import APIError, AuthError, NotFoundError, RateLimitError |
| 18 | + |
| 19 | +QueryParamValue = Union[str, int, float, bool] |
| 20 | +QueryParams = Dict[str, Union[QueryParamValue, Sequence[QueryParamValue], None]] |
| 21 | + |
| 22 | + |
| 23 | +@dataclass |
| 24 | +class RetryPolicy: |
| 25 | + """Retry policy for transient failures (429, 5xx, connection errors). |
| 26 | +
|
| 27 | + ``max_attempts`` counts the initial try, so ``3`` means up to 2 retries. Disable |
| 28 | + per client with ``retry=False`` on the client constructor; disable per call with |
| 29 | + ``retryable=False`` — required for GET-shaped mutations (e.g. ``crawl?delete=1``) |
| 30 | + that must never be retried blindly. |
| 31 | + """ |
| 32 | + |
| 33 | + max_attempts: int = 3 |
| 34 | + base_delay: float = 0.25 |
| 35 | + max_delay: float = 5.0 |
| 36 | + jitter: bool = True |
| 37 | + |
| 38 | + |
| 39 | +DEFAULT_RETRY_POLICY = RetryPolicy() |
| 40 | + |
| 41 | + |
| 42 | +def resolve_retry_policy(retry: Union[RetryPolicy, bool, None]) -> Optional[RetryPolicy]: |
| 43 | + """``None``/``True`` -> default policy (retries on by default); ``False`` -> disabled.""" |
| 44 | + if retry is False: |
| 45 | + return None |
| 46 | + if retry is None or retry is True: |
| 47 | + return DEFAULT_RETRY_POLICY |
| 48 | + return retry |
| 49 | + |
| 50 | + |
| 51 | +def _is_retryable_status(status_code: int) -> bool: |
| 52 | + return status_code == 429 or status_code >= 500 |
| 53 | + |
| 54 | + |
| 55 | +def _compute_delay(attempt: int, retry_after: Optional[str], policy: RetryPolicy) -> float: |
| 56 | + """Parses ``Retry-After`` as seconds or an HTTP date; falls back to exponential backoff.""" |
| 57 | + if retry_after: |
| 58 | + try: |
| 59 | + return max(0.0, float(retry_after)) |
| 60 | + except ValueError: |
| 61 | + pass |
| 62 | + try: |
| 63 | + dt = parsedate_to_datetime(retry_after) |
| 64 | + return max(0.0, dt.timestamp() - time.time()) |
| 65 | + except (TypeError, ValueError): |
| 66 | + pass |
| 67 | + exponential = min(policy.max_delay, policy.base_delay * (2 ** (attempt - 1))) |
| 68 | + return exponential * (0.5 + random.random() * 0.5) if policy.jitter else exponential |
| 69 | + |
| 70 | + |
| 71 | +def raise_for_status(response: httpx.Response) -> None: |
| 72 | + if response.is_success: |
| 73 | + return |
| 74 | + status = response.status_code |
| 75 | + body = response.text |
| 76 | + headers = dict(response.headers) |
| 77 | + if status in (401, 403): |
| 78 | + raise AuthError(status, body, headers=headers) |
| 79 | + if status == 404: |
| 80 | + raise NotFoundError(status, body, headers=headers) |
| 81 | + if status == 429: |
| 82 | + raise RateLimitError(status, body, retry_after=response.headers.get("retry-after"), headers=headers) |
| 83 | + raise APIError(status, body, headers=headers) |
| 84 | + |
| 85 | + |
| 86 | +def _build_kwargs( |
| 87 | + params: Optional[QueryParams], |
| 88 | + headers: Optional[Dict[str, str]], |
| 89 | + json: Optional[Any], |
| 90 | + content: Optional[Union[str, bytes]], |
| 91 | + data: Optional[Dict[str, Any]], |
| 92 | + timeout: Optional[float], |
| 93 | +) -> Dict[str, Any]: |
| 94 | + kwargs: Dict[str, Any] = {} |
| 95 | + if params is not None: |
| 96 | + kwargs["params"] = params |
| 97 | + if headers is not None: |
| 98 | + kwargs["headers"] = headers |
| 99 | + if json is not None: |
| 100 | + kwargs["json"] = json |
| 101 | + if content is not None: |
| 102 | + kwargs["content"] = content |
| 103 | + if data is not None: |
| 104 | + kwargs["data"] = data |
| 105 | + if timeout is not None: |
| 106 | + kwargs["timeout"] = timeout |
| 107 | + return kwargs |
| 108 | + |
| 109 | + |
| 110 | +def request( |
| 111 | + http: httpx.Client, |
| 112 | + retry_policy: Optional[RetryPolicy], |
| 113 | + method: str, |
| 114 | + url: str, |
| 115 | + *, |
| 116 | + params: Optional[QueryParams] = None, |
| 117 | + headers: Optional[Dict[str, str]] = None, |
| 118 | + json: Optional[Any] = None, |
| 119 | + content: Optional[Union[str, bytes]] = None, |
| 120 | + data: Optional[Dict[str, Any]] = None, |
| 121 | + timeout: Optional[float] = None, |
| 122 | + retryable: bool = True, |
| 123 | + follow_redirects: Optional[bool] = None, |
| 124 | + stream: bool = False, |
| 125 | +) -> httpx.Response: |
| 126 | + """Send a request, retrying on 429/5xx/connection errors per ``retry_policy``, then |
| 127 | + raise for a non-2xx status. The request is rebuilt fresh on each attempt so a |
| 128 | + request body is never resent from an already-consumed stream. |
| 129 | +
|
| 130 | + With ``stream=True`` the response body is left unread on success (the caller |
| 131 | + must iterate it and call ``.close()``), but is still read before raising on a |
| 132 | + non-2xx status — without that, accessing the error body (e.g. via |
| 133 | + ``RateLimitError.message``) would raise ``httpx.ResponseNotRead``. |
| 134 | + """ |
| 135 | + kwargs = _build_kwargs(params, headers, json, content, data, timeout) |
| 136 | + send_kwargs: Dict[str, Any] = {} if follow_redirects is None else {"follow_redirects": follow_redirects} |
| 137 | + if stream: |
| 138 | + send_kwargs["stream"] = True |
| 139 | + policy = retry_policy if retryable else None |
| 140 | + max_attempts = policy.max_attempts if policy else 1 |
| 141 | + attempt = 1 |
| 142 | + while True: |
| 143 | + req = http.build_request(method, url, **kwargs) |
| 144 | + try: |
| 145 | + response = http.send(req, **send_kwargs) |
| 146 | + except httpx.TransportError: |
| 147 | + if policy and attempt < max_attempts: |
| 148 | + time.sleep(_compute_delay(attempt, None, policy)) |
| 149 | + attempt += 1 |
| 150 | + continue |
| 151 | + raise |
| 152 | + if policy and attempt < max_attempts and _is_retryable_status(response.status_code): |
| 153 | + if stream: |
| 154 | + response.close() |
| 155 | + time.sleep(_compute_delay(attempt, response.headers.get("retry-after"), policy)) |
| 156 | + attempt += 1 |
| 157 | + continue |
| 158 | + if response.is_success: |
| 159 | + return response |
| 160 | + response.read() |
| 161 | + raise_for_status(response) |
| 162 | + |
| 163 | + |
| 164 | +async def request_async( |
| 165 | + http: httpx.AsyncClient, |
| 166 | + retry_policy: Optional[RetryPolicy], |
| 167 | + method: str, |
| 168 | + url: str, |
| 169 | + *, |
| 170 | + params: Optional[QueryParams] = None, |
| 171 | + headers: Optional[Dict[str, str]] = None, |
| 172 | + json: Optional[Any] = None, |
| 173 | + content: Optional[Union[str, bytes]] = None, |
| 174 | + data: Optional[Dict[str, Any]] = None, |
| 175 | + timeout: Optional[float] = None, |
| 176 | + retryable: bool = True, |
| 177 | + follow_redirects: Optional[bool] = None, |
| 178 | + stream: bool = False, |
| 179 | +) -> httpx.Response: |
| 180 | + """Async twin of :func:`request`.""" |
| 181 | + kwargs = _build_kwargs(params, headers, json, content, data, timeout) |
| 182 | + send_kwargs: Dict[str, Any] = {} if follow_redirects is None else {"follow_redirects": follow_redirects} |
| 183 | + if stream: |
| 184 | + send_kwargs["stream"] = True |
| 185 | + policy = retry_policy if retryable else None |
| 186 | + max_attempts = policy.max_attempts if policy else 1 |
| 187 | + attempt = 1 |
| 188 | + while True: |
| 189 | + req = http.build_request(method, url, **kwargs) |
| 190 | + try: |
| 191 | + response = await http.send(req, **send_kwargs) |
| 192 | + except httpx.TransportError: |
| 193 | + if policy and attempt < max_attempts: |
| 194 | + await asyncio.sleep(_compute_delay(attempt, None, policy)) |
| 195 | + attempt += 1 |
| 196 | + continue |
| 197 | + raise |
| 198 | + if policy and attempt < max_attempts and _is_retryable_status(response.status_code): |
| 199 | + if stream: |
| 200 | + await response.aclose() |
| 201 | + await asyncio.sleep(_compute_delay(attempt, response.headers.get("retry-after"), policy)) |
| 202 | + attempt += 1 |
| 203 | + continue |
| 204 | + if response.is_success: |
| 205 | + return response |
| 206 | + await response.aread() |
| 207 | + raise_for_status(response) |
0 commit comments