python-wrap 0.2.1__py3-none-any.whl → 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- python_wrap/__init__.py +348 -1
- python_wrap/__main__.py +57 -0
- python_wrap/_backend.py +133 -0
- python_wrap/_buckets.py +162 -0
- python_wrap/_core.py +12 -3
- python_wrap/_data/agent_guide.md +103 -0
- python_wrap/_data/recipes.json +703 -0
- python_wrap/_fork.py +113 -0
- python_wrap/_integration.py +29 -0
- python_wrap/_runtime.py +157 -0
- python_wrap/adapters/__init__.py +101 -0
- python_wrap/adapters/_frameworks.py +251 -0
- python_wrap/adapters/_sdk.py +1978 -0
- python_wrap/adapters/anthropic.py +139 -0
- python_wrap/adapters/langchain.py +288 -0
- python_wrap/adapters/openai.py +169 -0
- python_wrap/adapters/openai_agents.py +468 -0
- python_wrap/adapters/pydantic_ai.py +459 -0
- python_wrap/adaptive.py +605 -0
- python_wrap/agents.py +2503 -0
- python_wrap/alerts.py +293 -0
- python_wrap/async_cache.py +745 -0
- python_wrap/batching.py +17 -4
- python_wrap/buffering.py +952 -0
- python_wrap/bulkhead.py +58 -6
- python_wrap/caching.py +425 -56
- python_wrap/celery.py +528 -0
- python_wrap/chaos.py +519 -0
- python_wrap/circuit.py +454 -23
- python_wrap/compat.py +267 -0
- python_wrap/concurrency.py +82 -1746
- python_wrap/config.py +25 -4
- python_wrap/coordination.py +638 -0
- python_wrap/credentials.py +126 -0
- python_wrap/dashboard.py +358 -0
- python_wrap/debounce.py +538 -0
- python_wrap/django.py +100 -0
- python_wrap/doctor.py +599 -0
- python_wrap/events.py +145 -4
- python_wrap/exporters.py +663 -0
- python_wrap/fastapi.py +81 -0
- python_wrap/flask.py +61 -0
- python_wrap/genai.py +1101 -0
- python_wrap/health.py +187 -0
- python_wrap/http.py +940 -0
- python_wrap/idempotency.py +446 -0
- python_wrap/introspect.py +738 -0
- python_wrap/lifecycle.py +620 -0
- python_wrap/llm.py +2574 -0
- python_wrap/llm_cassette.py +948 -0
- python_wrap/llm_http_chaos.py +326 -0
- python_wrap/llm_shared.py +772 -0
- python_wrap/llm_testing.py +990 -0
- python_wrap/llm_validate.py +383 -0
- python_wrap/local_state.py +395 -0
- python_wrap/logs.py +82 -26
- python_wrap/mcp.py +490 -0
- python_wrap/mcp_guard.py +357 -0
- python_wrap/metrics.py +6 -3
- python_wrap/migrate.py +1452 -0
- python_wrap/observability.py +484 -0
- python_wrap/periodic.py +24 -2
- python_wrap/policies.py +396 -0
- python_wrap/policy.py +14 -0
- python_wrap/predicates.py +276 -0
- python_wrap/presets.py +378 -0
- python_wrap/processing.py +227 -0
- python_wrap/propagation.py +62 -0
- python_wrap/pytest_plugin.py +85 -0
- python_wrap/quotas.py +319 -0
- python_wrap/ratelimit.py +560 -0
- python_wrap/redaction.py +228 -0
- python_wrap/retry.py +448 -70
- python_wrap/shared.py +653 -0
- python_wrap/singleflight.py +255 -0
- python_wrap/slow.py +72 -0
- python_wrap/stores.py +168 -0
- python_wrap/switches.py +164 -0
- python_wrap/testing.py +34 -8
- python_wrap/timeouts.py +874 -0
- python_wrap/timing.py +239 -17
- python_wrap/validation.py +187 -12
- python_wrap/web.py +723 -0
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
- python_wrap-0.4.0.dist-info/RECORD +95 -0
- python_wrap-0.2.1.dist-info/RECORD +0 -29
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
python_wrap/http.py
ADDED
|
@@ -0,0 +1,940 @@
|
|
|
1
|
+
"""HTTP client integration: retry policy, httpx transports, requests adapter, generic decorator.
|
|
2
|
+
|
|
3
|
+
Everything here is duck-typed or imports its third-party library lazily, so
|
|
4
|
+
``python_wrap`` keeps zero runtime dependencies. The decision logic lives in two pure
|
|
5
|
+
helpers, `should_retry` and `retry_delay`, which every integration shares.
|
|
6
|
+
|
|
7
|
+
Method safety is the core rule: a request is retried only when its method is idempotent
|
|
8
|
+
(GET, HEAD, OPTIONS, PUT, DELETE, TRACE) or it carries an idempotency header
|
|
9
|
+
(``Idempotency-Key`` by default). A bare POST or PATCH is never retried, neither on a
|
|
10
|
+
retryable status nor on a transport error, because the server may already have acted.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import contextlib
|
|
16
|
+
import importlib
|
|
17
|
+
import logging
|
|
18
|
+
import threading
|
|
19
|
+
from collections.abc import Awaitable, Callable, Iterable, Mapping
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from python_wrap import _core
|
|
24
|
+
from python_wrap.deadline import remaining as _deadline_remaining
|
|
25
|
+
from python_wrap.retry import RetryBudget, _compute_delay, http_status, retry, retry_after_header
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"IDEMPOTENT_METHODS",
|
|
29
|
+
"RETRYABLE_STATUSES",
|
|
30
|
+
"AsyncPolicyTransport",
|
|
31
|
+
"AsyncRetryTransport",
|
|
32
|
+
"HttpPolicy",
|
|
33
|
+
"HttpRetryPolicy",
|
|
34
|
+
"PolicyTransport",
|
|
35
|
+
"RetryTransport",
|
|
36
|
+
"http_retry",
|
|
37
|
+
"mount_policy",
|
|
38
|
+
"mount_retries",
|
|
39
|
+
"retry_delay",
|
|
40
|
+
"should_retry",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
_log = logging.getLogger("python_wrap")
|
|
44
|
+
|
|
45
|
+
IDEMPOTENT_METHODS: frozenset[str] = frozenset({"GET", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"})
|
|
46
|
+
"""Methods that are safe to repeat (RFC 9110)."""
|
|
47
|
+
|
|
48
|
+
RETRYABLE_STATUSES: frozenset[int] = frozenset({408, 425, 429, 500, 502, 503, 504})
|
|
49
|
+
"""Statuses that usually mean "try again": timeouts, throttling and server-side failures."""
|
|
50
|
+
|
|
51
|
+
_TRANSPORT_NAMES: frozenset[str] = frozenset(
|
|
52
|
+
{
|
|
53
|
+
"TransportError",
|
|
54
|
+
"ConnectError",
|
|
55
|
+
"ReadTimeout",
|
|
56
|
+
"ConnectTimeout",
|
|
57
|
+
"ConnectionError",
|
|
58
|
+
"Timeout",
|
|
59
|
+
"ClientConnectionError",
|
|
60
|
+
"ServerDisconnectedError",
|
|
61
|
+
"ClientOSError",
|
|
62
|
+
}
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class HttpRetryPolicy:
|
|
68
|
+
"""What to retry, how long to wait, and when to stop, for HTTP calls.
|
|
69
|
+
|
|
70
|
+
Attributes:
|
|
71
|
+
max_attempts: Total tries including the first (>= 1).
|
|
72
|
+
delay: Base wait before the second attempt, in seconds.
|
|
73
|
+
backoff: Multiplier applied to the wait after each failure (>= 1).
|
|
74
|
+
max_delay: Cap on the backoff wait (before jitter).
|
|
75
|
+
jitter: Up to this many random extra seconds are added to a backoff wait.
|
|
76
|
+
statuses: Response statuses that trigger a retry.
|
|
77
|
+
methods: Methods considered safe to repeat (upper-case).
|
|
78
|
+
retry_on: Exception types treated as transport failures.
|
|
79
|
+
retry_on_names: Class names matched along an exception's MRO, so httpx, requests
|
|
80
|
+
and aiohttp errors are recognised without importing those libraries.
|
|
81
|
+
respect_retry_after: Use a ``Retry-After`` header as the exact wait.
|
|
82
|
+
max_retry_after: A ``Retry-After`` larger than this means "do not retry": the
|
|
83
|
+
response is returned (or the error raised) instead.
|
|
84
|
+
budget: Optional shared `RetryBudget`; when it refuses, retrying stops.
|
|
85
|
+
idempotency_header: A request carrying this header may be retried whatever its
|
|
86
|
+
method.
|
|
87
|
+
|
|
88
|
+
Raises:
|
|
89
|
+
ValueError: If a numeric option is out of range.
|
|
90
|
+
|
|
91
|
+
Example:
|
|
92
|
+
>>> policy = HttpRetryPolicy(max_attempts=4, delay=0.2)
|
|
93
|
+
>>> should_retry("GET", {}, status=503, policy=policy)
|
|
94
|
+
True
|
|
95
|
+
>>> should_retry("POST", {}, status=503, policy=policy)
|
|
96
|
+
False
|
|
97
|
+
>>> should_retry("POST", {"Idempotency-Key": "k1"}, status=503, policy=policy)
|
|
98
|
+
True
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
max_attempts: int = 3
|
|
102
|
+
delay: float = 0.5
|
|
103
|
+
backoff: float = 2.0
|
|
104
|
+
max_delay: float = 30.0
|
|
105
|
+
jitter: float | str = 0.0
|
|
106
|
+
statuses: frozenset[int] = RETRYABLE_STATUSES
|
|
107
|
+
methods: frozenset[str] = IDEMPOTENT_METHODS
|
|
108
|
+
retry_on: tuple[type[BaseException], ...] = (ConnectionError, TimeoutError, OSError)
|
|
109
|
+
retry_on_names: frozenset[str] = _TRANSPORT_NAMES
|
|
110
|
+
respect_retry_after: bool = True
|
|
111
|
+
max_retry_after: float = 60.0
|
|
112
|
+
budget: RetryBudget | None = field(default=None, compare=False)
|
|
113
|
+
idempotency_header: str | None = "Idempotency-Key"
|
|
114
|
+
|
|
115
|
+
def __post_init__(self) -> None:
|
|
116
|
+
if self.max_attempts < 1:
|
|
117
|
+
raise ValueError(f"max_attempts must be >= 1, got {self.max_attempts!r}")
|
|
118
|
+
if not self.delay >= 0:
|
|
119
|
+
raise ValueError(f"delay must be >= 0, got {self.delay!r}")
|
|
120
|
+
if not self.backoff >= 1:
|
|
121
|
+
raise ValueError(f"backoff must be >= 1, got {self.backoff!r}")
|
|
122
|
+
if not self.max_delay >= 0:
|
|
123
|
+
raise ValueError(f"max_delay must be >= 0, got {self.max_delay!r}")
|
|
124
|
+
if self.jitter not in ("full", "equal") and (
|
|
125
|
+
isinstance(self.jitter, str)
|
|
126
|
+
or not isinstance(self.jitter, (int, float))
|
|
127
|
+
or self.jitter < 0
|
|
128
|
+
):
|
|
129
|
+
raise ValueError(f"jitter must be >= 0, 'full' or 'equal', got {self.jitter!r}")
|
|
130
|
+
if not self.max_retry_after >= 0:
|
|
131
|
+
raise ValueError(f"max_retry_after must be >= 0, got {self.max_retry_after!r}")
|
|
132
|
+
if self.budget is not None and not isinstance(self.budget, RetryBudget):
|
|
133
|
+
raise TypeError("budget must be a RetryBudget or None")
|
|
134
|
+
object.__setattr__(self, "statuses", frozenset(self.statuses))
|
|
135
|
+
object.__setattr__(self, "methods", frozenset(m.upper() for m in self.methods))
|
|
136
|
+
object.__setattr__(self, "retry_on", tuple(self.retry_on))
|
|
137
|
+
object.__setattr__(self, "retry_on_names", frozenset(self.retry_on_names))
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
_DEFAULT_POLICY = HttpRetryPolicy()
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _has_header(headers: Any, name: str | None) -> bool:
|
|
144
|
+
if not name or headers is None:
|
|
145
|
+
return False
|
|
146
|
+
try:
|
|
147
|
+
if headers.get(name) is not None:
|
|
148
|
+
return True
|
|
149
|
+
except Exception:
|
|
150
|
+
pass
|
|
151
|
+
try:
|
|
152
|
+
wanted = name.lower()
|
|
153
|
+
items = headers.items() if hasattr(headers, "items") else headers
|
|
154
|
+
return any(str(k).lower() == wanted for k, _ in items)
|
|
155
|
+
except Exception:
|
|
156
|
+
return False
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _method_allowed(method: str, headers: Any, policy: HttpRetryPolicy) -> bool:
|
|
160
|
+
if str(method).upper() in policy.methods:
|
|
161
|
+
return True
|
|
162
|
+
return _has_header(headers, policy.idempotency_header)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _is_transport_error(exc: BaseException, policy: HttpRetryPolicy) -> bool:
|
|
166
|
+
if isinstance(exc, policy.retry_on):
|
|
167
|
+
return True
|
|
168
|
+
return any(cls.__name__ in policy.retry_on_names for cls in type(exc).__mro__)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _status_of(response: Any) -> int | None:
|
|
172
|
+
status = getattr(response, "status_code", None)
|
|
173
|
+
if status is None:
|
|
174
|
+
status = getattr(response, "status", None)
|
|
175
|
+
return status if isinstance(status, int) else None
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def should_retry(
|
|
179
|
+
method: str,
|
|
180
|
+
headers: Mapping[str, str] | Any,
|
|
181
|
+
status: int | None = None,
|
|
182
|
+
exc: BaseException | None = None,
|
|
183
|
+
policy: HttpRetryPolicy | None = None,
|
|
184
|
+
) -> bool:
|
|
185
|
+
"""Decide whether a failed HTTP attempt may be retried (pure; no attempt counting).
|
|
186
|
+
|
|
187
|
+
Args:
|
|
188
|
+
method: The request method, any case.
|
|
189
|
+
headers: The request headers (any mapping-like, case-insensitive or not).
|
|
190
|
+
status: The response status, if a response came back.
|
|
191
|
+
exc: The exception, if the call raised.
|
|
192
|
+
policy: The policy; the defaults when omitted.
|
|
193
|
+
|
|
194
|
+
Returns:
|
|
195
|
+
`True` if the method is safe to repeat (idempotent or carrying the idempotency
|
|
196
|
+
header) and the status is retryable or the exception is a transport error.
|
|
197
|
+
With neither `status` nor `exc`, `False`.
|
|
198
|
+
|
|
199
|
+
Example:
|
|
200
|
+
>>> should_retry("GET", {}, exc=ConnectionError())
|
|
201
|
+
True
|
|
202
|
+
>>> should_retry("POST", {}, exc=ConnectionError())
|
|
203
|
+
False
|
|
204
|
+
>>> should_retry("GET", {}, status=404)
|
|
205
|
+
False
|
|
206
|
+
"""
|
|
207
|
+
policy = policy or _DEFAULT_POLICY
|
|
208
|
+
if not _method_allowed(method, headers, policy):
|
|
209
|
+
return False
|
|
210
|
+
if exc is not None:
|
|
211
|
+
return _is_transport_error(exc, policy)
|
|
212
|
+
return status is not None and status in policy.statuses
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def retry_delay(
|
|
216
|
+
response_or_exc: Any, attempt: int, policy: HttpRetryPolicy | None = None
|
|
217
|
+
) -> float | None:
|
|
218
|
+
"""Seconds to wait after failed attempt number `attempt` (1-based).
|
|
219
|
+
|
|
220
|
+
A ``Retry-After`` on the response (or on ``exc.response``) wins and is used exactly;
|
|
221
|
+
otherwise the capped exponential backoff plus jitter applies.
|
|
222
|
+
|
|
223
|
+
Args:
|
|
224
|
+
response_or_exc: The failed response or exception.
|
|
225
|
+
attempt: The attempt that just failed, starting at 1.
|
|
226
|
+
policy: The policy; the defaults when omitted.
|
|
227
|
+
|
|
228
|
+
Returns:
|
|
229
|
+
The wait in seconds, or `None` when the server asked for longer than
|
|
230
|
+
`policy.max_retry_after` (the caller should stop retrying).
|
|
231
|
+
|
|
232
|
+
Example:
|
|
233
|
+
>>> class Resp:
|
|
234
|
+
... headers = {"Retry-After": "2"}
|
|
235
|
+
>>> retry_delay(Resp(), 1)
|
|
236
|
+
2.0
|
|
237
|
+
>>> retry_delay(object(), 3, HttpRetryPolicy(delay=1, backoff=2))
|
|
238
|
+
4.0
|
|
239
|
+
"""
|
|
240
|
+
policy = policy or _DEFAULT_POLICY
|
|
241
|
+
if policy.respect_retry_after:
|
|
242
|
+
hinted = retry_after_header(response_or_exc)
|
|
243
|
+
if hinted is not None:
|
|
244
|
+
return None if hinted > policy.max_retry_after else hinted
|
|
245
|
+
return _compute_delay(
|
|
246
|
+
max(attempt, 1), policy.delay, policy.backoff, policy.max_delay, policy.jitter
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
class _Run:
|
|
251
|
+
"""One logical call: shared decision, budget and event logic for every integration."""
|
|
252
|
+
|
|
253
|
+
def __init__(self, policy: HttpRetryPolicy, method: str, headers: Any, host: str) -> None:
|
|
254
|
+
self.policy = policy
|
|
255
|
+
self.method = str(method).upper()
|
|
256
|
+
self.headers = headers
|
|
257
|
+
self.name = f"http {self.method} {host}".rstrip()
|
|
258
|
+
if policy.budget is not None:
|
|
259
|
+
policy.budget.deposit()
|
|
260
|
+
|
|
261
|
+
def next_delay(
|
|
262
|
+
self, attempt: int, response: Any = None, exc: BaseException | None = None
|
|
263
|
+
) -> float | None:
|
|
264
|
+
"""The wait before the next attempt, or `None` to stop (response/exception stands)."""
|
|
265
|
+
policy = self.policy
|
|
266
|
+
subject = exc if exc is not None else response
|
|
267
|
+
status = _status_of(response) if exc is None else None
|
|
268
|
+
if not should_retry(self.method, self.headers, status, exc, policy):
|
|
269
|
+
return None
|
|
270
|
+
fields: dict[str, Any] = {"attempts": attempt, "exception": exc, "status": status}
|
|
271
|
+
if attempt >= policy.max_attempts:
|
|
272
|
+
_core.emit("retry.gave_up", self.name, **fields)
|
|
273
|
+
return None
|
|
274
|
+
wait = retry_delay(subject, attempt, policy)
|
|
275
|
+
if wait is None:
|
|
276
|
+
_core.emit("retry.gave_up", self.name, **fields)
|
|
277
|
+
return None
|
|
278
|
+
left = _deadline_remaining()
|
|
279
|
+
if left is not None and wait >= left:
|
|
280
|
+
_core.emit("retry.gave_up", self.name, **fields)
|
|
281
|
+
return None
|
|
282
|
+
if policy.budget is not None and not policy.budget.try_withdraw():
|
|
283
|
+
_core.emit("retry.budget_exhausted", self.name, **fields)
|
|
284
|
+
_core.emit("retry.gave_up", self.name, **fields)
|
|
285
|
+
return None
|
|
286
|
+
_core.emit(
|
|
287
|
+
"retry.attempt_failed",
|
|
288
|
+
self.name,
|
|
289
|
+
attempt=attempt,
|
|
290
|
+
exception=exc,
|
|
291
|
+
status=status,
|
|
292
|
+
next_delay=wait,
|
|
293
|
+
)
|
|
294
|
+
return wait
|
|
295
|
+
|
|
296
|
+
def succeeded(self, attempt: int) -> None:
|
|
297
|
+
if attempt > 1:
|
|
298
|
+
_core.emit("retry.succeeded", self.name, attempts=attempt)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
class _ServerError(Exception):
|
|
302
|
+
"""Carries a 5xx response through a circuit breaker so it counts as a failure."""
|
|
303
|
+
|
|
304
|
+
def __init__(self, response: Any) -> None:
|
|
305
|
+
super().__init__(_status_of(response))
|
|
306
|
+
self.response = response
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
@dataclass(frozen=True)
|
|
310
|
+
class HttpPolicy:
|
|
311
|
+
"""Retries plus a circuit breaker, rate limiter, bulkhead and timeouts for HTTP calls.
|
|
312
|
+
|
|
313
|
+
Attributes:
|
|
314
|
+
retry: The `HttpRetryPolicy` (method safety, backoff, ``Retry-After``).
|
|
315
|
+
breaker: ``True`` (5 failures, 30 s), a `CircuitBreaker`, or with ``per_host`` a
|
|
316
|
+
factory ``name -> CircuitBreaker``. 5xx responses and transport errors count
|
|
317
|
+
as failures; 4xx responses never do.
|
|
318
|
+
limiter: A `RateLimiter`, or with ``per_host`` a factory ``name -> RateLimiter``.
|
|
319
|
+
A 429 ``Retry-After`` pauses later calls to that host instead of failing them.
|
|
320
|
+
bulkhead: A `Bulkhead`, or with ``per_host`` a factory ``name -> Bulkhead``.
|
|
321
|
+
connect_timeout: Used when the caller set no connect timeout.
|
|
322
|
+
read_timeout: Used when the caller set no read timeout.
|
|
323
|
+
per_host: Give every host its own breaker, limiter and bulkhead, named
|
|
324
|
+
``http:<host>``, built from the factories.
|
|
325
|
+
shared: A Redis client or `python_wrap.shared.SharedBackends` for the breakers
|
|
326
|
+
this policy builds with ``breaker=True`` (default: ``configure(shared=...)``).
|
|
327
|
+
propagate: Send ``X-Request-ID`` and the remaining ``X-Request-Deadline`` (in
|
|
328
|
+
milliseconds) on every attempt, so the receiving service sees both.
|
|
329
|
+
|
|
330
|
+
Every attempt's timeouts are also shortened to the surrounding `deadline`.
|
|
331
|
+
|
|
332
|
+
Example:
|
|
333
|
+
>>> policy = HttpPolicy(breaker=True, per_host=True)
|
|
334
|
+
>>> policy.guards("a.example")[0] is policy.guards("a.example")[0]
|
|
335
|
+
True
|
|
336
|
+
>>> policy.guards("a.example")[0] is policy.guards("b.example")[0]
|
|
337
|
+
False
|
|
338
|
+
"""
|
|
339
|
+
|
|
340
|
+
retry: HttpRetryPolicy = field(default_factory=HttpRetryPolicy)
|
|
341
|
+
breaker: Any = None
|
|
342
|
+
limiter: Any = None
|
|
343
|
+
bulkhead: Any = None
|
|
344
|
+
connect_timeout: float | None = None
|
|
345
|
+
read_timeout: float | None = None
|
|
346
|
+
per_host: bool = False
|
|
347
|
+
shared: Any = None
|
|
348
|
+
propagate: bool = False
|
|
349
|
+
_hosts: dict[str, tuple[Any, Any, Any]] = field(
|
|
350
|
+
default_factory=dict, init=False, repr=False, compare=False
|
|
351
|
+
)
|
|
352
|
+
_blocked: dict[str, float] = field(default_factory=dict, init=False, repr=False, compare=False)
|
|
353
|
+
_lock: Any = field(default_factory=threading.Lock, init=False, repr=False, compare=False)
|
|
354
|
+
|
|
355
|
+
def __post_init__(self) -> None:
|
|
356
|
+
for name in ("connect_timeout", "read_timeout"):
|
|
357
|
+
value = getattr(self, name)
|
|
358
|
+
if value is not None and not value > 0:
|
|
359
|
+
raise ValueError(f"{name} must be > 0, got {value!r}")
|
|
360
|
+
for name in ("limiter", "bulkhead"):
|
|
361
|
+
if getattr(self, name) is True:
|
|
362
|
+
raise ValueError(f"{name}=True is not allowed: pass the object or a factory")
|
|
363
|
+
if self.per_host:
|
|
364
|
+
from python_wrap.bulkhead import Bulkhead
|
|
365
|
+
from python_wrap.circuit import CircuitBreaker
|
|
366
|
+
from python_wrap.concurrency import RateLimiter
|
|
367
|
+
|
|
368
|
+
for name in ("breaker", "limiter", "bulkhead"):
|
|
369
|
+
value = getattr(self, name)
|
|
370
|
+
if isinstance(value, (CircuitBreaker, RateLimiter, Bulkhead)):
|
|
371
|
+
raise ValueError(
|
|
372
|
+
f"per_host=True needs a factory for {name}= (name -> object), "
|
|
373
|
+
"not one shared instance"
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
# -- per-host state ----------------------------------------------------------------
|
|
377
|
+
def _build(self, kind: str, value: Any, name: str) -> Any:
|
|
378
|
+
if value is None or (not callable(value) and value is not True):
|
|
379
|
+
return value
|
|
380
|
+
if value is True: # only the breaker has a default
|
|
381
|
+
from python_wrap.circuit import CircuitBreaker
|
|
382
|
+
from python_wrap.shared import resolve_shared
|
|
383
|
+
|
|
384
|
+
sb = resolve_shared(self.shared)
|
|
385
|
+
return CircuitBreaker(
|
|
386
|
+
failure_threshold=5,
|
|
387
|
+
recovery_timeout=30.0,
|
|
388
|
+
name=name,
|
|
389
|
+
backend=None if sb is None else sb.breaker(),
|
|
390
|
+
)
|
|
391
|
+
from python_wrap.bulkhead import Bulkhead
|
|
392
|
+
from python_wrap.circuit import CircuitBreaker
|
|
393
|
+
from python_wrap.concurrency import RateLimiter
|
|
394
|
+
|
|
395
|
+
if isinstance(value, (CircuitBreaker, RateLimiter, Bulkhead)):
|
|
396
|
+
return value
|
|
397
|
+
return value(name)
|
|
398
|
+
|
|
399
|
+
def guards(self, host: str) -> tuple[Any, Any, Any]:
|
|
400
|
+
"""The ``(breaker, limiter, bulkhead)`` for ``host`` (one set unless ``per_host``)."""
|
|
401
|
+
key = host if self.per_host else ""
|
|
402
|
+
with self._lock:
|
|
403
|
+
found = self._hosts.get(key)
|
|
404
|
+
if found is None:
|
|
405
|
+
name = f"http:{host}" if self.per_host else "http"
|
|
406
|
+
found = tuple(
|
|
407
|
+
self._build(kind, getattr(self, kind), name)
|
|
408
|
+
for kind in ("breaker", "limiter", "bulkhead")
|
|
409
|
+
)
|
|
410
|
+
self._hosts[key] = found
|
|
411
|
+
return found
|
|
412
|
+
|
|
413
|
+
# -- helpers shared by the sync and async paths ------------------------------------
|
|
414
|
+
def _blocked_wait(self, host: str) -> float:
|
|
415
|
+
with self._lock:
|
|
416
|
+
until = self._blocked.get(host, 0.0)
|
|
417
|
+
wait = until - _core.monotonic()
|
|
418
|
+
if wait <= 0:
|
|
419
|
+
return 0.0
|
|
420
|
+
left = _deadline_remaining()
|
|
421
|
+
if wait > self.retry.max_retry_after or (left is not None and wait >= left):
|
|
422
|
+
from python_wrap.errors import RateLimitExceeded
|
|
423
|
+
|
|
424
|
+
raise RateLimitExceeded(f"{host} asked clients to wait {wait:.1f}s", retry_after=wait)
|
|
425
|
+
return wait
|
|
426
|
+
|
|
427
|
+
def _note(self, host: str, response: Any) -> None:
|
|
428
|
+
if self.limiter is None or _status_of(response) != 429:
|
|
429
|
+
return
|
|
430
|
+
hinted = retry_after_header(response)
|
|
431
|
+
if hinted:
|
|
432
|
+
with self._lock:
|
|
433
|
+
self._blocked[host] = _core.monotonic() + hinted
|
|
434
|
+
|
|
435
|
+
def _request_headers(self, headers: Any) -> None:
|
|
436
|
+
"""Add the request id and the remaining deadline to an outgoing header mapping."""
|
|
437
|
+
from python_wrap.propagation import outgoing_headers
|
|
438
|
+
|
|
439
|
+
for name, value in outgoing_headers().items():
|
|
440
|
+
headers[name] = value
|
|
441
|
+
|
|
442
|
+
def _prepare_httpx(self, request: Any) -> None:
|
|
443
|
+
extensions = getattr(request, "extensions", None)
|
|
444
|
+
if isinstance(extensions, dict):
|
|
445
|
+
current = dict(extensions.get("timeout") or {})
|
|
446
|
+
for key, default in (("connect", self.connect_timeout), ("read", self.read_timeout)):
|
|
447
|
+
if current.get(key) is None and default is not None:
|
|
448
|
+
current[key] = default
|
|
449
|
+
left = _deadline_remaining()
|
|
450
|
+
if left is not None:
|
|
451
|
+
for key in ("connect", "read", "write", "pool"):
|
|
452
|
+
value = current.get(key)
|
|
453
|
+
current[key] = (
|
|
454
|
+
max(left, 0.001) if value is None else min(value, max(left, 0.001))
|
|
455
|
+
)
|
|
456
|
+
if current:
|
|
457
|
+
extensions["timeout"] = current
|
|
458
|
+
if self.propagate:
|
|
459
|
+
self._request_headers(request.headers)
|
|
460
|
+
|
|
461
|
+
def requests_timeout(self, timeout: Any) -> Any:
|
|
462
|
+
"""The ``timeout=`` for a ``requests`` call: defaults filled in, capped by the deadline."""
|
|
463
|
+
if isinstance(timeout, tuple):
|
|
464
|
+
connect, read = timeout
|
|
465
|
+
else:
|
|
466
|
+
connect = read = timeout
|
|
467
|
+
connect = self.connect_timeout if connect is None else connect
|
|
468
|
+
read = self.read_timeout if read is None else read
|
|
469
|
+
left = _deadline_remaining()
|
|
470
|
+
if left is not None:
|
|
471
|
+
left = max(left, 0.001)
|
|
472
|
+
connect = left if connect is None else min(connect, left)
|
|
473
|
+
read = left if read is None else min(read, left)
|
|
474
|
+
return None if connect is None and read is None else (connect, read)
|
|
475
|
+
|
|
476
|
+
def call(self, host: str, send: Callable[[], Any]) -> Any:
|
|
477
|
+
"""One attempt through the guards: limiter, bulkhead, breaker, then ``send()``."""
|
|
478
|
+
breaker, limiter, bulkhead = self.guards(host)
|
|
479
|
+
if limiter is not None:
|
|
480
|
+
wait = self._blocked_wait(host)
|
|
481
|
+
if wait:
|
|
482
|
+
_core.sleep(wait)
|
|
483
|
+
|
|
484
|
+
def counted() -> Any:
|
|
485
|
+
response = send()
|
|
486
|
+
status = _status_of(response)
|
|
487
|
+
if breaker is not None and status is not None and status >= 500:
|
|
488
|
+
raise _ServerError(response)
|
|
489
|
+
return response
|
|
490
|
+
|
|
491
|
+
try:
|
|
492
|
+
with contextlib.ExitStack() as stack:
|
|
493
|
+
if limiter is not None:
|
|
494
|
+
stack.enter_context(limiter)
|
|
495
|
+
if bulkhead is not None:
|
|
496
|
+
stack.enter_context(bulkhead)
|
|
497
|
+
response = breaker.call(counted) if breaker is not None else counted()
|
|
498
|
+
except _ServerError as exc:
|
|
499
|
+
response = exc.response
|
|
500
|
+
self._note(host, response)
|
|
501
|
+
return response
|
|
502
|
+
|
|
503
|
+
async def acall(self, host: str, send: Callable[[], Awaitable[Any]]) -> Any:
|
|
504
|
+
"""`call` for coroutines."""
|
|
505
|
+
breaker, limiter, bulkhead = self.guards(host)
|
|
506
|
+
if limiter is not None:
|
|
507
|
+
wait = self._blocked_wait(host)
|
|
508
|
+
if wait:
|
|
509
|
+
await _core.async_sleep(wait)
|
|
510
|
+
|
|
511
|
+
async def counted() -> Any:
|
|
512
|
+
response = await send()
|
|
513
|
+
status = _status_of(response)
|
|
514
|
+
if breaker is not None and status is not None and status >= 500:
|
|
515
|
+
raise _ServerError(response)
|
|
516
|
+
return response
|
|
517
|
+
|
|
518
|
+
try:
|
|
519
|
+
async with contextlib.AsyncExitStack() as stack:
|
|
520
|
+
if limiter is not None:
|
|
521
|
+
await stack.enter_async_context(limiter)
|
|
522
|
+
if bulkhead is not None:
|
|
523
|
+
await stack.enter_async_context(bulkhead)
|
|
524
|
+
response = await breaker.call(counted) if breaker is not None else await counted()
|
|
525
|
+
except _ServerError as exc:
|
|
526
|
+
response = exc.response
|
|
527
|
+
self._note(host, response)
|
|
528
|
+
return response
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def _close(response: Any) -> None:
|
|
532
|
+
closer = getattr(response, "close", None)
|
|
533
|
+
if callable(closer):
|
|
534
|
+
try:
|
|
535
|
+
closer()
|
|
536
|
+
except Exception:
|
|
537
|
+
_log.debug("closing a discarded response failed", exc_info=True)
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
async def _aclose(response: Any) -> None:
|
|
541
|
+
closer = getattr(response, "aclose", None)
|
|
542
|
+
if callable(closer):
|
|
543
|
+
try:
|
|
544
|
+
result = closer()
|
|
545
|
+
if isinstance(result, Awaitable):
|
|
546
|
+
await result
|
|
547
|
+
except Exception:
|
|
548
|
+
_log.debug("closing a discarded response failed", exc_info=True)
|
|
549
|
+
return
|
|
550
|
+
_close(response)
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _host(url: Any) -> str:
|
|
554
|
+
host = getattr(url, "host", None)
|
|
555
|
+
if isinstance(host, str):
|
|
556
|
+
return host
|
|
557
|
+
if isinstance(url, str):
|
|
558
|
+
from urllib.parse import urlsplit
|
|
559
|
+
|
|
560
|
+
return urlsplit(url).hostname or ""
|
|
561
|
+
return ""
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
class PolicyTransport:
|
|
565
|
+
"""A synchronous httpx transport that applies a whole `HttpPolicy`.
|
|
566
|
+
|
|
567
|
+
Retries (method-safe), a circuit breaker, rate limiter and bulkhead (optionally per
|
|
568
|
+
host), default timeouts shortened to the surrounding deadline, and optional
|
|
569
|
+
request-id / deadline headers. Wrap any object with httpx's transport interface.
|
|
570
|
+
|
|
571
|
+
Args:
|
|
572
|
+
inner: The transport to wrap, e.g. ``httpx.HTTPTransport()``.
|
|
573
|
+
policy: The `HttpPolicy`; retries only with its defaults when omitted.
|
|
574
|
+
|
|
575
|
+
Example:
|
|
576
|
+
```python
|
|
577
|
+
import httpx
|
|
578
|
+
from python_wrap.http import HttpPolicy, PolicyTransport
|
|
579
|
+
|
|
580
|
+
policy = HttpPolicy(breaker=True, per_host=True, read_timeout=10)
|
|
581
|
+
client = httpx.Client(transport=PolicyTransport(httpx.HTTPTransport(), policy))
|
|
582
|
+
```
|
|
583
|
+
"""
|
|
584
|
+
|
|
585
|
+
def __init__(self, inner: Any, policy: HttpPolicy | None = None) -> None:
|
|
586
|
+
self.inner = inner
|
|
587
|
+
self.policy: Any = policy or HttpPolicy()
|
|
588
|
+
|
|
589
|
+
@property
|
|
590
|
+
def _full(self) -> HttpPolicy:
|
|
591
|
+
return self.policy # type: ignore[no-any-return]
|
|
592
|
+
|
|
593
|
+
def _send(self, request: Any) -> Any:
|
|
594
|
+
self._full._prepare_httpx(request)
|
|
595
|
+
return self.inner.handle_request(request)
|
|
596
|
+
|
|
597
|
+
def handle_request(self, request: Any) -> Any:
|
|
598
|
+
"""Send `request`, applying the policy."""
|
|
599
|
+
full = self._full
|
|
600
|
+
host = _host(request.url)
|
|
601
|
+
run = _Run(full.retry, request.method, request.headers, host)
|
|
602
|
+
attempt = 0
|
|
603
|
+
while True:
|
|
604
|
+
attempt += 1
|
|
605
|
+
try:
|
|
606
|
+
response = full.call(host, lambda: self._send(request))
|
|
607
|
+
except Exception as exc:
|
|
608
|
+
wait = run.next_delay(attempt, exc=exc)
|
|
609
|
+
if wait is None:
|
|
610
|
+
raise
|
|
611
|
+
else:
|
|
612
|
+
wait = run.next_delay(attempt, response=response)
|
|
613
|
+
if wait is None:
|
|
614
|
+
run.succeeded(attempt)
|
|
615
|
+
return response
|
|
616
|
+
_close(response)
|
|
617
|
+
_core.sleep(wait)
|
|
618
|
+
|
|
619
|
+
def close(self) -> None:
|
|
620
|
+
"""Close the wrapped transport."""
|
|
621
|
+
closer = getattr(self.inner, "close", None)
|
|
622
|
+
if callable(closer):
|
|
623
|
+
closer()
|
|
624
|
+
|
|
625
|
+
def __enter__(self) -> PolicyTransport:
|
|
626
|
+
return self
|
|
627
|
+
|
|
628
|
+
def __exit__(self, *exc_info: Any) -> None:
|
|
629
|
+
self.close()
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
class RetryTransport(PolicyTransport):
|
|
633
|
+
"""A synchronous httpx transport wrapper that retries per an `HttpRetryPolicy`.
|
|
634
|
+
|
|
635
|
+
Wrap any object with httpx's transport interface (``handle_request`` and
|
|
636
|
+
``close``). Discarded responses are closed before the next attempt. The request body
|
|
637
|
+
must be replayable (bytes or str content; not a one-shot stream).
|
|
638
|
+
|
|
639
|
+
Args:
|
|
640
|
+
inner: The transport to wrap, e.g. ``httpx.HTTPTransport()``.
|
|
641
|
+
policy: The retry policy; defaults apply when omitted.
|
|
642
|
+
|
|
643
|
+
Example:
|
|
644
|
+
```python
|
|
645
|
+
import httpx
|
|
646
|
+
from python_wrap.http import HttpRetryPolicy, RetryTransport
|
|
647
|
+
|
|
648
|
+
client = httpx.Client(
|
|
649
|
+
transport=RetryTransport(httpx.HTTPTransport(), policy=HttpRetryPolicy())
|
|
650
|
+
)
|
|
651
|
+
```
|
|
652
|
+
"""
|
|
653
|
+
|
|
654
|
+
def __init__(self, inner: Any, policy: HttpRetryPolicy | None = None) -> None:
|
|
655
|
+
retry_policy = policy or HttpRetryPolicy()
|
|
656
|
+
super().__init__(inner, HttpPolicy(retry=retry_policy))
|
|
657
|
+
self._full_policy = self.policy
|
|
658
|
+
self.policy = retry_policy
|
|
659
|
+
|
|
660
|
+
@property
|
|
661
|
+
def _full(self) -> HttpPolicy:
|
|
662
|
+
return self._full_policy # type: ignore[no-any-return]
|
|
663
|
+
|
|
664
|
+
def __enter__(self) -> RetryTransport:
|
|
665
|
+
return self
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
class AsyncPolicyTransport:
|
|
669
|
+
"""The asyncio counterpart of `PolicyTransport` for ``httpx.AsyncClient``.
|
|
670
|
+
|
|
671
|
+
Args:
|
|
672
|
+
inner: The async transport to wrap, e.g. ``httpx.AsyncHTTPTransport()``.
|
|
673
|
+
policy: The `HttpPolicy`; retries only with its defaults when omitted.
|
|
674
|
+
"""
|
|
675
|
+
|
|
676
|
+
def __init__(self, inner: Any, policy: HttpPolicy | None = None) -> None:
|
|
677
|
+
self.inner = inner
|
|
678
|
+
self.policy: Any = policy or HttpPolicy()
|
|
679
|
+
|
|
680
|
+
@property
|
|
681
|
+
def _full(self) -> HttpPolicy:
|
|
682
|
+
return self.policy # type: ignore[no-any-return]
|
|
683
|
+
|
|
684
|
+
async def _send(self, request: Any) -> Any:
|
|
685
|
+
self._full._prepare_httpx(request)
|
|
686
|
+
return await self.inner.handle_async_request(request)
|
|
687
|
+
|
|
688
|
+
async def handle_async_request(self, request: Any) -> Any:
|
|
689
|
+
"""Send `request`, applying the policy."""
|
|
690
|
+
full = self._full
|
|
691
|
+
host = _host(request.url)
|
|
692
|
+
run = _Run(full.retry, request.method, request.headers, host)
|
|
693
|
+
attempt = 0
|
|
694
|
+
while True:
|
|
695
|
+
attempt += 1
|
|
696
|
+
try:
|
|
697
|
+
response = await full.acall(host, lambda: self._send(request))
|
|
698
|
+
except Exception as exc:
|
|
699
|
+
wait = run.next_delay(attempt, exc=exc)
|
|
700
|
+
if wait is None:
|
|
701
|
+
raise
|
|
702
|
+
else:
|
|
703
|
+
wait = run.next_delay(attempt, response=response)
|
|
704
|
+
if wait is None:
|
|
705
|
+
run.succeeded(attempt)
|
|
706
|
+
return response
|
|
707
|
+
await _aclose(response)
|
|
708
|
+
await _core.async_sleep(wait)
|
|
709
|
+
|
|
710
|
+
async def aclose(self) -> None:
|
|
711
|
+
"""Close the wrapped transport."""
|
|
712
|
+
closer = getattr(self.inner, "aclose", None)
|
|
713
|
+
if callable(closer):
|
|
714
|
+
result = closer()
|
|
715
|
+
if isinstance(result, Awaitable):
|
|
716
|
+
await result
|
|
717
|
+
|
|
718
|
+
async def __aenter__(self) -> AsyncPolicyTransport:
|
|
719
|
+
return self
|
|
720
|
+
|
|
721
|
+
async def __aexit__(self, *exc_info: Any) -> None:
|
|
722
|
+
await self.aclose()
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
class AsyncRetryTransport(AsyncPolicyTransport):
|
|
726
|
+
"""The asyncio counterpart of `RetryTransport` for ``httpx.AsyncClient``.
|
|
727
|
+
|
|
728
|
+
Args:
|
|
729
|
+
inner: The async transport to wrap, e.g. ``httpx.AsyncHTTPTransport()``.
|
|
730
|
+
policy: The retry policy; defaults apply when omitted.
|
|
731
|
+
|
|
732
|
+
Example:
|
|
733
|
+
```python
|
|
734
|
+
import httpx
|
|
735
|
+
from python_wrap.http import AsyncRetryTransport
|
|
736
|
+
|
|
737
|
+
client = httpx.AsyncClient(transport=AsyncRetryTransport(httpx.AsyncHTTPTransport()))
|
|
738
|
+
```
|
|
739
|
+
"""
|
|
740
|
+
|
|
741
|
+
def __init__(self, inner: Any, policy: HttpRetryPolicy | None = None) -> None:
|
|
742
|
+
retry_policy = policy or HttpRetryPolicy()
|
|
743
|
+
super().__init__(inner, HttpPolicy(retry=retry_policy))
|
|
744
|
+
self._full_policy = self.policy
|
|
745
|
+
self.policy = retry_policy
|
|
746
|
+
|
|
747
|
+
@property
|
|
748
|
+
def _full(self) -> HttpPolicy:
|
|
749
|
+
return self._full_policy # type: ignore[no-any-return]
|
|
750
|
+
|
|
751
|
+
async def __aenter__(self) -> AsyncRetryTransport:
|
|
752
|
+
return self
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
def mount_policy(
|
|
756
|
+
session: Any,
|
|
757
|
+
policy: HttpPolicy | None = None,
|
|
758
|
+
prefixes: Iterable[str] = ("http://", "https://"),
|
|
759
|
+
) -> Any:
|
|
760
|
+
"""Mount an adapter that applies a whole `HttpPolicy` on a ``requests.Session``.
|
|
761
|
+
|
|
762
|
+
``requests`` is imported lazily. The adapter subclasses
|
|
763
|
+
``requests.adapters.HTTPAdapter`` and wraps its ``send`` with the policy, so it
|
|
764
|
+
replaces any adapter already mounted on those prefixes. Default timeouts apply when
|
|
765
|
+
the call passed none (``requests`` has none by default) and are shortened to the
|
|
766
|
+
surrounding deadline.
|
|
767
|
+
|
|
768
|
+
Args:
|
|
769
|
+
session: A ``requests.Session`` (anything with ``mount``).
|
|
770
|
+
policy: The `HttpPolicy`; retries only with its defaults when omitted.
|
|
771
|
+
prefixes: URL prefixes to mount on.
|
|
772
|
+
|
|
773
|
+
Returns:
|
|
774
|
+
The mounted adapter (its ``http_policy`` attribute holds the policy).
|
|
775
|
+
|
|
776
|
+
Raises:
|
|
777
|
+
ImportError: If ``requests`` is not installed.
|
|
778
|
+
|
|
779
|
+
Example:
|
|
780
|
+
```python
|
|
781
|
+
import requests
|
|
782
|
+
from python_wrap.http import HttpPolicy, mount_policy
|
|
783
|
+
|
|
784
|
+
session = requests.Session()
|
|
785
|
+
mount_policy(session, HttpPolicy(breaker=True, per_host=True, read_timeout=10))
|
|
786
|
+
```
|
|
787
|
+
"""
|
|
788
|
+
adapters = importlib.import_module("requests.adapters")
|
|
789
|
+
base: Any = adapters.HTTPAdapter
|
|
790
|
+
resolved = policy or HttpPolicy()
|
|
791
|
+
|
|
792
|
+
class PolicyAdapter(base): # type: ignore[misc]
|
|
793
|
+
http_policy = resolved
|
|
794
|
+
retry_policy = resolved.retry
|
|
795
|
+
|
|
796
|
+
def send(self, request: Any, **kwargs: Any) -> Any:
|
|
797
|
+
full = self.http_policy
|
|
798
|
+
host = _host(request.url)
|
|
799
|
+
run = _Run(full.retry, request.method, request.headers, host)
|
|
800
|
+
|
|
801
|
+
def once() -> Any:
|
|
802
|
+
full_timeout = full.requests_timeout(kwargs.get("timeout"))
|
|
803
|
+
options = dict(kwargs)
|
|
804
|
+
if full_timeout is not None:
|
|
805
|
+
options["timeout"] = full_timeout
|
|
806
|
+
if full.propagate:
|
|
807
|
+
full._request_headers(request.headers)
|
|
808
|
+
return super(PolicyAdapter, self).send(request, **options)
|
|
809
|
+
|
|
810
|
+
attempt = 0
|
|
811
|
+
while True:
|
|
812
|
+
attempt += 1
|
|
813
|
+
try:
|
|
814
|
+
response = full.call(host, once)
|
|
815
|
+
except Exception as exc:
|
|
816
|
+
wait = run.next_delay(attempt, exc=exc)
|
|
817
|
+
if wait is None:
|
|
818
|
+
raise
|
|
819
|
+
else:
|
|
820
|
+
wait = run.next_delay(attempt, response=response)
|
|
821
|
+
if wait is None:
|
|
822
|
+
run.succeeded(attempt)
|
|
823
|
+
return response
|
|
824
|
+
_close(response)
|
|
825
|
+
_core.sleep(wait)
|
|
826
|
+
|
|
827
|
+
adapter = PolicyAdapter()
|
|
828
|
+
for prefix in prefixes:
|
|
829
|
+
session.mount(prefix, adapter)
|
|
830
|
+
return adapter
|
|
831
|
+
|
|
832
|
+
|
|
833
|
+
def mount_retries(
|
|
834
|
+
session: Any,
|
|
835
|
+
policy: HttpRetryPolicy | None = None,
|
|
836
|
+
prefixes: Iterable[str] = ("http://", "https://"),
|
|
837
|
+
) -> Any:
|
|
838
|
+
"""Mount a retrying adapter on a ``requests.Session`` (retries only).
|
|
839
|
+
|
|
840
|
+
A thin wrapper over `mount_policy` with ``HttpPolicy(retry=policy)``; the returned
|
|
841
|
+
adapter's ``retry_policy`` attribute holds the retry policy.
|
|
842
|
+
|
|
843
|
+
Args:
|
|
844
|
+
session: A ``requests.Session`` (anything with ``mount``).
|
|
845
|
+
policy: The retry policy; defaults apply when omitted.
|
|
846
|
+
prefixes: URL prefixes to mount on.
|
|
847
|
+
|
|
848
|
+
Raises:
|
|
849
|
+
ImportError: If ``requests`` is not installed.
|
|
850
|
+
|
|
851
|
+
Example:
|
|
852
|
+
```python
|
|
853
|
+
import requests
|
|
854
|
+
from python_wrap.http import HttpRetryPolicy, mount_retries
|
|
855
|
+
|
|
856
|
+
session = requests.Session()
|
|
857
|
+
mount_retries(session, HttpRetryPolicy(max_attempts=4))
|
|
858
|
+
```
|
|
859
|
+
"""
|
|
860
|
+
return mount_policy(session, HttpPolicy(retry=policy or HttpRetryPolicy()), prefixes)
|
|
861
|
+
|
|
862
|
+
|
|
863
|
+
def http_retry(
|
|
864
|
+
policy: HttpRetryPolicy | None = None,
|
|
865
|
+
*,
|
|
866
|
+
method: str = "GET",
|
|
867
|
+
idempotent: bool | None = None,
|
|
868
|
+
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
|
869
|
+
"""Decorate any function or coroutine that returns a response-like object.
|
|
870
|
+
|
|
871
|
+
Built on `retry`: a result with a retryable ``.status``/``.status_code`` is retried,
|
|
872
|
+
waiting for its ``Retry-After`` when present, as are transport errors. Works for
|
|
873
|
+
aiohttp and hand-written clients. Because the function's own arguments are opaque,
|
|
874
|
+
declare the method here.
|
|
875
|
+
|
|
876
|
+
A non-idempotent `method` is **not retried at all** (the function is returned
|
|
877
|
+
unchanged) unless `idempotent=True` asserts the call is safe, e.g. because it sends
|
|
878
|
+
an idempotency key.
|
|
879
|
+
|
|
880
|
+
Args:
|
|
881
|
+
policy: The retry policy; defaults apply when omitted.
|
|
882
|
+
method: The HTTP method the decorated function performs.
|
|
883
|
+
idempotent: Override the method-based decision: `True` allows retries, `False`
|
|
884
|
+
forbids them. `None` decides from `method` and `policy.methods`.
|
|
885
|
+
|
|
886
|
+
Returns:
|
|
887
|
+
A decorator.
|
|
888
|
+
|
|
889
|
+
Example:
|
|
890
|
+
>>> from python_wrap.http import http_retry
|
|
891
|
+
>>> class Resp:
|
|
892
|
+
... status = 200
|
|
893
|
+
... headers = {}
|
|
894
|
+
>>> @http_retry(method="GET")
|
|
895
|
+
... def fetch():
|
|
896
|
+
... return Resp()
|
|
897
|
+
>>> fetch().status
|
|
898
|
+
200
|
|
899
|
+
"""
|
|
900
|
+
resolved = policy or HttpRetryPolicy()
|
|
901
|
+
allowed = idempotent if idempotent is not None else method.upper() in resolved.methods
|
|
902
|
+
|
|
903
|
+
def decorate(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
904
|
+
if not allowed:
|
|
905
|
+
return func
|
|
906
|
+
status_hit = http_status(*resolved.statuses) if resolved.statuses else None
|
|
907
|
+
|
|
908
|
+
def too_long(value: Any) -> bool:
|
|
909
|
+
if not resolved.respect_retry_after:
|
|
910
|
+
return False
|
|
911
|
+
hinted = retry_after_header(value)
|
|
912
|
+
return hinted is not None and hinted > resolved.max_retry_after
|
|
913
|
+
|
|
914
|
+
def result_rejected(result: Any) -> bool:
|
|
915
|
+
return status_hit is not None and status_hit(result) and not too_long(result)
|
|
916
|
+
|
|
917
|
+
def error_rejected(exc: BaseException) -> bool:
|
|
918
|
+
return _is_transport_error(exc, resolved) and not too_long(exc)
|
|
919
|
+
|
|
920
|
+
def hint(value: Any) -> float | None:
|
|
921
|
+
return retry_after_header(value) if resolved.respect_retry_after else None
|
|
922
|
+
|
|
923
|
+
steps = [
|
|
924
|
+
min(resolved.delay * resolved.backoff**i, resolved.max_delay)
|
|
925
|
+
for i in range(max(resolved.max_attempts - 1, 1))
|
|
926
|
+
]
|
|
927
|
+
return retry(
|
|
928
|
+
max_attempts=resolved.max_attempts,
|
|
929
|
+
delays=steps,
|
|
930
|
+
max_delay=max(resolved.max_delay, resolved.max_retry_after),
|
|
931
|
+
jitter=resolved.jitter,
|
|
932
|
+
on=Exception,
|
|
933
|
+
retry_if=error_rejected,
|
|
934
|
+
retry_if_result=result_rejected,
|
|
935
|
+
delay_from=hint,
|
|
936
|
+
budget=resolved.budget,
|
|
937
|
+
log_level=None,
|
|
938
|
+
)(func)
|
|
939
|
+
|
|
940
|
+
return decorate
|