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/retry.py
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import contextvars
|
|
6
8
|
import datetime
|
|
7
9
|
import functools
|
|
8
10
|
import inspect
|
|
@@ -10,17 +12,23 @@ import logging
|
|
|
10
12
|
import math
|
|
11
13
|
import random
|
|
12
14
|
import sys
|
|
13
|
-
import threading
|
|
14
15
|
import time
|
|
15
16
|
import warnings
|
|
16
|
-
from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine, Iterator
|
|
17
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine, Iterator, Sequence
|
|
17
18
|
from dataclasses import dataclass
|
|
18
19
|
from types import TracebackType
|
|
19
20
|
from typing import Any, NoReturn, Protocol, TypeVar, cast, overload
|
|
20
21
|
|
|
21
|
-
from python_wrap import _core, config
|
|
22
|
+
from python_wrap import _core, _fork, config
|
|
22
23
|
from python_wrap._core import F, LoggerLike, P, R
|
|
23
24
|
from python_wrap.deadline import remaining as _deadline_remaining
|
|
25
|
+
from python_wrap.errors import CircuitOpenError
|
|
26
|
+
|
|
27
|
+
# retry engine id -> monotonic start of its current attempt, per thread/task; set only
|
|
28
|
+
# while event listeners exist, so events can carry attempt_seconds for real spans.
|
|
29
|
+
_ATTEMPT_STARTS: contextvars.ContextVar[dict[int, float] | None] = contextvars.ContextVar(
|
|
30
|
+
"python_wrap_attempt_starts", default=None
|
|
31
|
+
)
|
|
24
32
|
|
|
25
33
|
T = TypeVar("T")
|
|
26
34
|
T_co = TypeVar("T_co", covariant=True)
|
|
@@ -29,12 +37,15 @@ ExceptionTypes = type[BaseException] | tuple[type[BaseException], ...]
|
|
|
29
37
|
|
|
30
38
|
__all__ = [
|
|
31
39
|
"Attempt",
|
|
40
|
+
"AttemptRecord",
|
|
32
41
|
"RetryBudget",
|
|
33
42
|
"RetryBudgetStats",
|
|
34
43
|
"RetryState",
|
|
35
44
|
"RetryStats",
|
|
36
45
|
"Retrying",
|
|
46
|
+
"attempt_history",
|
|
37
47
|
"fallback",
|
|
48
|
+
"http_status",
|
|
38
49
|
"retry",
|
|
39
50
|
"retry_after_header",
|
|
40
51
|
"retry_on_exception",
|
|
@@ -76,7 +87,7 @@ def _validate(
|
|
|
76
87
|
delay: float,
|
|
77
88
|
backoff: float,
|
|
78
89
|
max_delay: float | None,
|
|
79
|
-
jitter: float,
|
|
90
|
+
jitter: float | str,
|
|
80
91
|
max_time: float | None = None,
|
|
81
92
|
) -> None:
|
|
82
93
|
if max_attempts is not None and max_attempts < 1:
|
|
@@ -85,16 +96,37 @@ def _validate(
|
|
|
85
96
|
raise ValueError(f"delay must be >= 0, got {delay!r}")
|
|
86
97
|
if backoff < 1:
|
|
87
98
|
raise ValueError(f"backoff must be >= 1, got {backoff!r}")
|
|
88
|
-
if jitter
|
|
89
|
-
|
|
99
|
+
if jitter not in ("full", "equal") and (
|
|
100
|
+
isinstance(jitter, str) or not isinstance(jitter, (int, float)) or jitter < 0
|
|
101
|
+
):
|
|
102
|
+
raise ValueError(f"jitter must be >= 0, 'full' or 'equal', got {jitter!r}")
|
|
90
103
|
if max_delay is not None and max_delay < 0:
|
|
91
104
|
raise ValueError(f"max_delay must be >= 0, got {max_delay!r}")
|
|
92
105
|
if max_time is not None and max_time < 0:
|
|
93
106
|
raise ValueError(f"max_time must be >= 0 or None, got {max_time!r}")
|
|
94
107
|
|
|
95
108
|
|
|
109
|
+
def _validate_delays(delays: Sequence[float] | None) -> tuple[float, ...] | None:
|
|
110
|
+
if delays is None:
|
|
111
|
+
return None
|
|
112
|
+
if not isinstance(delays, Sequence) or isinstance(delays, (str, bytes)) or not delays:
|
|
113
|
+
raise ValueError("delays must be a nonempty sequence of finite nonnegative seconds")
|
|
114
|
+
values = []
|
|
115
|
+
for value in delays:
|
|
116
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
117
|
+
raise ValueError("delays must contain finite nonnegative seconds")
|
|
118
|
+
try:
|
|
119
|
+
normalized = float(value)
|
|
120
|
+
except OverflowError as exc:
|
|
121
|
+
raise ValueError("delays must contain finite nonnegative seconds") from exc
|
|
122
|
+
if not math.isfinite(normalized) or normalized < 0:
|
|
123
|
+
raise ValueError("delays must contain finite nonnegative seconds")
|
|
124
|
+
values.append(normalized)
|
|
125
|
+
return tuple(values)
|
|
126
|
+
|
|
127
|
+
|
|
96
128
|
def _compute_delay(
|
|
97
|
-
attempt: int, delay: float, backoff: float, max_delay: float | None, jitter: float
|
|
129
|
+
attempt: int, delay: float, backoff: float, max_delay: float | None, jitter: float | str
|
|
98
130
|
) -> float:
|
|
99
131
|
try:
|
|
100
132
|
wait = delay * backoff ** (attempt - 1)
|
|
@@ -102,8 +134,12 @@ def _compute_delay(
|
|
|
102
134
|
wait = sys.float_info.max
|
|
103
135
|
if max_delay is not None:
|
|
104
136
|
wait = min(wait, max_delay)
|
|
137
|
+
if jitter == "full":
|
|
138
|
+
return random.uniform(0, wait)
|
|
139
|
+
if jitter == "equal":
|
|
140
|
+
return random.uniform(wait / 2, wait)
|
|
105
141
|
if jitter:
|
|
106
|
-
wait += random.uniform(0, jitter)
|
|
142
|
+
wait += random.uniform(0, float(jitter))
|
|
107
143
|
return wait
|
|
108
144
|
|
|
109
145
|
|
|
@@ -124,7 +160,7 @@ class RetryStats:
|
|
|
124
160
|
"""
|
|
125
161
|
|
|
126
162
|
def __init__(self) -> None:
|
|
127
|
-
self._lock =
|
|
163
|
+
self._lock = _fork.ForkSafeLock()
|
|
128
164
|
self.calls = 0
|
|
129
165
|
self.attempts_total = 0
|
|
130
166
|
self.retries = 0
|
|
@@ -164,6 +200,8 @@ class RetryStats:
|
|
|
164
200
|
|
|
165
201
|
|
|
166
202
|
_STATS_ATTR = "__retry_stats__"
|
|
203
|
+
# (role, settings) read by python_wrap.doctor to explain a decorated function.
|
|
204
|
+
_LAYER_ATTR = "__python_wrap_layer__"
|
|
167
205
|
|
|
168
206
|
|
|
169
207
|
def retry_stats(func: Callable[..., Any]) -> RetryStats | None:
|
|
@@ -226,6 +264,9 @@ class RetryBudget:
|
|
|
226
264
|
ratio: Retries allowed per request in the window (`0.1` = 10 %). `>= 0`.
|
|
227
265
|
min_per_second: Retries per second always allowed regardless of traffic. `>= 0`.
|
|
228
266
|
window: Length of the sliding window in seconds. `> 0`.
|
|
267
|
+
backend: A shared counter store with ``deposit(budget)``, ``try_withdraw(budget)``
|
|
268
|
+
and ``totals(budget)`` such as `python_wrap.shared.RedisRetryBudget`, so the
|
|
269
|
+
cap holds across every worker process instead of per process.
|
|
229
270
|
|
|
230
271
|
Raises:
|
|
231
272
|
ValueError: If an argument is out of range.
|
|
@@ -249,7 +290,12 @@ class RetryBudget:
|
|
|
249
290
|
_core.refuse_pickle(self)
|
|
250
291
|
|
|
251
292
|
def __init__(
|
|
252
|
-
self,
|
|
293
|
+
self,
|
|
294
|
+
ratio: float = 0.1,
|
|
295
|
+
min_per_second: float = 10,
|
|
296
|
+
window: float = 10.0,
|
|
297
|
+
*,
|
|
298
|
+
backend: Any = None,
|
|
253
299
|
) -> None:
|
|
254
300
|
if not ratio >= 0 or math.isinf(ratio):
|
|
255
301
|
raise ValueError(f"ratio must be a finite number >= 0, got {ratio!r}")
|
|
@@ -260,9 +306,17 @@ class RetryBudget:
|
|
|
260
306
|
self.ratio = float(ratio)
|
|
261
307
|
self.min_per_second = float(min_per_second)
|
|
262
308
|
self.window = float(window)
|
|
309
|
+
self.backend = backend
|
|
263
310
|
self._reserve = self.min_per_second * self.window
|
|
264
311
|
self._width = self.window / _BUDGET_SLOTS
|
|
265
|
-
self._lock =
|
|
312
|
+
self._lock = _fork.ForkSafeLock()
|
|
313
|
+
self._epochs = [-1] * _BUDGET_SLOTS
|
|
314
|
+
self._requests = [0] * _BUDGET_SLOTS
|
|
315
|
+
self._retries = [0] * _BUDGET_SLOTS
|
|
316
|
+
self._rejected = 0
|
|
317
|
+
_fork.register(self)
|
|
318
|
+
|
|
319
|
+
def _reset_after_fork(self) -> None:
|
|
266
320
|
self._epochs = [-1] * _BUDGET_SLOTS
|
|
267
321
|
self._requests = [0] * _BUDGET_SLOTS
|
|
268
322
|
self._retries = [0] * _BUDGET_SLOTS
|
|
@@ -292,6 +346,12 @@ class RetryBudget:
|
|
|
292
346
|
|
|
293
347
|
def deposit(self) -> None:
|
|
294
348
|
"""Record one request (a first attempt). `retry` calls this for you."""
|
|
349
|
+
if self.backend is not None:
|
|
350
|
+
self.backend.deposit(self)
|
|
351
|
+
return
|
|
352
|
+
self._deposit_local()
|
|
353
|
+
|
|
354
|
+
def _deposit_local(self) -> None:
|
|
295
355
|
with self._lock:
|
|
296
356
|
index, _ = self._slot()
|
|
297
357
|
self._requests[index] += 1
|
|
@@ -306,6 +366,15 @@ class RetryBudget:
|
|
|
306
366
|
`True` if the retry is allowed (and was recorded), `False` if the budget is
|
|
307
367
|
exhausted (recorded as rejected).
|
|
308
368
|
"""
|
|
369
|
+
if self.backend is not None:
|
|
370
|
+
if self.backend.try_withdraw(self):
|
|
371
|
+
return True
|
|
372
|
+
with self._lock:
|
|
373
|
+
self._rejected += 1
|
|
374
|
+
return False
|
|
375
|
+
return self._withdraw_local()
|
|
376
|
+
|
|
377
|
+
def _withdraw_local(self) -> bool:
|
|
309
378
|
with self._lock:
|
|
310
379
|
index, epoch = self._slot()
|
|
311
380
|
if self._available(*self._totals(epoch)) >= 1:
|
|
@@ -317,6 +386,12 @@ class RetryBudget:
|
|
|
317
386
|
@property
|
|
318
387
|
def stats(self) -> RetryBudgetStats:
|
|
319
388
|
"""A consistent `RetryBudgetStats` snapshot of the current window."""
|
|
389
|
+
if self.backend is not None:
|
|
390
|
+
requests, retries = self.backend.totals(self)
|
|
391
|
+
with self._lock:
|
|
392
|
+
rejected = self._rejected
|
|
393
|
+
allowed = max(math.floor(self._available(requests, retries)), 0)
|
|
394
|
+
return RetryBudgetStats(requests, retries, rejected, allowed)
|
|
320
395
|
with self._lock:
|
|
321
396
|
_, epoch = self._slot()
|
|
322
397
|
requests, retries = self._totals(epoch)
|
|
@@ -352,11 +427,16 @@ def _parse_seconds(value: Any) -> float | None:
|
|
|
352
427
|
else:
|
|
353
428
|
text = str(value).strip()
|
|
354
429
|
try:
|
|
430
|
+
if "_" in text:
|
|
431
|
+
raise ValueError(text) # float() accepts "1_0"; HTTP does not
|
|
355
432
|
seconds = float(text)
|
|
356
433
|
except ValueError:
|
|
357
434
|
import email.utils # only HTTP-date headers need it; keeps import fast
|
|
358
435
|
|
|
359
|
-
|
|
436
|
+
try:
|
|
437
|
+
moment = email.utils.parsedate_to_datetime(text)
|
|
438
|
+
except (TypeError, ValueError, IndexError, OverflowError):
|
|
439
|
+
return None # unparseable: ignore the header, let other sources apply
|
|
360
440
|
if moment.tzinfo is None:
|
|
361
441
|
moment = moment.replace(tzinfo=datetime.timezone.utc)
|
|
362
442
|
seconds = moment.timestamp() - time.time()
|
|
@@ -365,16 +445,39 @@ def _parse_seconds(value: Any) -> float | None:
|
|
|
365
445
|
return max(seconds, 0.0)
|
|
366
446
|
|
|
367
447
|
|
|
368
|
-
def
|
|
369
|
-
"""
|
|
448
|
+
def _header(headers: Any, name: str) -> Any:
|
|
449
|
+
"""Read a header from a mapping or pairs, case-insensitively."""
|
|
450
|
+
if headers is None:
|
|
451
|
+
return None
|
|
452
|
+
try:
|
|
453
|
+
items = headers.items() if hasattr(headers, "items") else headers
|
|
454
|
+
for key, value in items:
|
|
455
|
+
if str(key).casefold() == name.casefold():
|
|
456
|
+
return value
|
|
457
|
+
except (TypeError, ValueError, AttributeError):
|
|
458
|
+
return None
|
|
459
|
+
return None
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def retry_after_header(value: Any, *, json_key: str | None = None) -> float | None:
|
|
463
|
+
"""Extract a server-requested wait for `delay_from=`, from an error **or a result**.
|
|
464
|
+
|
|
465
|
+
Accepts either an exception or a returned response-like object, so result-based
|
|
466
|
+
retries (``retry_if_result=``) can honour the server's wait too. Looks at:
|
|
370
467
|
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
468
|
+
* a ``retry_after`` attribute;
|
|
469
|
+
* a ``Retry-After`` header (case-insensitive), on the object itself or on
|
|
470
|
+
``exc.response``;
|
|
471
|
+
* with ``json_key=``, that key in the response's JSON body (some APIs put
|
|
472
|
+
``retry_after`` there). A failing ``.json()`` is ignored.
|
|
473
|
+
|
|
474
|
+
Values may be seconds or an HTTP-date; dates become seconds from now. Works with
|
|
475
|
+
``httpx``, ``requests``, ``aiohttp`` and duck-typed responses without importing them,
|
|
476
|
+
and never raises.
|
|
375
477
|
|
|
376
478
|
Args:
|
|
377
|
-
|
|
479
|
+
value: An exception or a response-like object.
|
|
480
|
+
json_key: Optional JSON field holding the wait, e.g. ``"retry_after"``.
|
|
378
481
|
|
|
379
482
|
Returns:
|
|
380
483
|
Seconds to wait (never negative), or `None` if nothing usable was found.
|
|
@@ -386,27 +489,94 @@ def retry_after_header(exc: BaseException) -> float | None:
|
|
|
386
489
|
3.0
|
|
387
490
|
"""
|
|
388
491
|
try:
|
|
389
|
-
found = _parse_seconds(getattr(
|
|
492
|
+
found = _parse_seconds(getattr(value, "retry_after", None))
|
|
493
|
+
if found is not None:
|
|
494
|
+
return found
|
|
495
|
+
headers = getattr(value, "headers", None)
|
|
496
|
+
if headers is None:
|
|
497
|
+
response = getattr(value, "response", None)
|
|
498
|
+
headers = getattr(response, "headers", None)
|
|
499
|
+
found = _parse_seconds(_header(headers, "Retry-After"))
|
|
390
500
|
if found is not None:
|
|
391
501
|
return found
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
502
|
+
if json_key:
|
|
503
|
+
response = getattr(value, "response", None)
|
|
504
|
+
target = value if hasattr(value, "json") else response
|
|
505
|
+
body = getattr(target, "json", None)
|
|
506
|
+
if callable(body):
|
|
507
|
+
try:
|
|
508
|
+
payload = body()
|
|
509
|
+
except Exception:
|
|
510
|
+
payload = None
|
|
511
|
+
if inspect.iscoroutine(payload):
|
|
512
|
+
payload.close() # sync helper cannot await an async response decoder
|
|
513
|
+
return None
|
|
514
|
+
if isinstance(payload, dict):
|
|
515
|
+
return _parse_seconds(payload.get(json_key))
|
|
516
|
+
return None
|
|
400
517
|
except Exception:
|
|
401
518
|
return None
|
|
402
519
|
|
|
403
520
|
|
|
521
|
+
def http_status(*codes: int) -> Callable[[Any], bool]:
|
|
522
|
+
"""Build a ``retry_if_result`` predicate that matches HTTP status codes.
|
|
523
|
+
|
|
524
|
+
Reads a duck-typed ``.status_code`` or ``.status`` attribute, so it works with
|
|
525
|
+
``requests``, ``httpx``, ``aiohttp`` and simple stubs. A value without either
|
|
526
|
+
attribute never matches.
|
|
527
|
+
|
|
528
|
+
Args:
|
|
529
|
+
*codes: Status codes to retry, e.g. ``429, 500, 502, 503, 504``.
|
|
530
|
+
|
|
531
|
+
Returns:
|
|
532
|
+
A predicate for ``retry_if_result=``.
|
|
533
|
+
|
|
534
|
+
Raises:
|
|
535
|
+
ValueError: If no code is given or a code is outside 100-599.
|
|
536
|
+
|
|
537
|
+
Example:
|
|
538
|
+
```python
|
|
539
|
+
from python_wrap import http_status, retry, retry_after_header
|
|
540
|
+
|
|
541
|
+
@retry(retry_if_result=http_status(429, 503), delay_from=retry_after_header)
|
|
542
|
+
def call(url):
|
|
543
|
+
return client.get(url)
|
|
544
|
+
```
|
|
545
|
+
"""
|
|
546
|
+
if not codes:
|
|
547
|
+
raise ValueError("http_status() needs at least one status code")
|
|
548
|
+
wanted = frozenset(codes)
|
|
549
|
+
for code in wanted:
|
|
550
|
+
if not 100 <= code <= 599:
|
|
551
|
+
raise ValueError(f"not an HTTP status code: {code!r}")
|
|
552
|
+
|
|
553
|
+
def matches(result: Any) -> bool:
|
|
554
|
+
status = getattr(result, "status_code", None)
|
|
555
|
+
if status is None:
|
|
556
|
+
status = getattr(result, "status", None)
|
|
557
|
+
return status in wanted
|
|
558
|
+
|
|
559
|
+
return matches
|
|
560
|
+
|
|
561
|
+
|
|
404
562
|
# Never retried, even with ``on=BaseException``: retrying these hangs shutdown/cancellation.
|
|
405
|
-
_NEVER_RETRY = (
|
|
563
|
+
_NEVER_RETRY = (
|
|
564
|
+
asyncio.CancelledError,
|
|
565
|
+
KeyboardInterrupt,
|
|
566
|
+
SystemExit,
|
|
567
|
+
GeneratorExit,
|
|
568
|
+
CircuitOpenError,
|
|
569
|
+
)
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
#: Longest wait a `delay_from` hint (such as a server's ``Retry-After``) may impose when
|
|
573
|
+
#: ``max_delay`` is not set. A hostile or broken upstream could otherwise park a worker
|
|
574
|
+
#: for days with one header. Set ``max_delay`` to choose another bound.
|
|
575
|
+
HINT_CEILING = 600.0
|
|
406
576
|
|
|
407
577
|
|
|
408
578
|
def _parse_hint(value: Any) -> float | None:
|
|
409
|
-
if isinstance(value, bool) or not isinstance(value, (int, float)) or math.
|
|
579
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
|
|
410
580
|
return None
|
|
411
581
|
return max(float(value), 0.0)
|
|
412
582
|
|
|
@@ -444,24 +614,27 @@ class _Engine:
|
|
|
444
614
|
delay: float,
|
|
445
615
|
backoff: float,
|
|
446
616
|
max_delay: float | None,
|
|
447
|
-
jitter: float,
|
|
617
|
+
jitter: float | str,
|
|
448
618
|
max_time: float | None,
|
|
449
619
|
on: ExceptionTypes,
|
|
450
620
|
retry_if: ExceptionPredicate | None,
|
|
451
621
|
retry_if_result: ResultPredicate | None,
|
|
452
622
|
on_retry: RetryCallback | None,
|
|
453
|
-
delay_from: Callable[[
|
|
623
|
+
delay_from: Callable[[Any], float | None] | None,
|
|
454
624
|
budget: RetryBudget | None,
|
|
455
625
|
logger: LoggerLike,
|
|
456
626
|
log_level: int | None,
|
|
457
627
|
log_exc_info: bool,
|
|
458
628
|
stats: RetryStats,
|
|
629
|
+
delays: Sequence[float] | None = None,
|
|
630
|
+
log_values: bool = True,
|
|
459
631
|
) -> None:
|
|
460
632
|
_validate(max_attempts, delay, backoff, max_delay, jitter, max_time)
|
|
461
633
|
_check_budget(budget)
|
|
462
634
|
self.name = name
|
|
463
635
|
self.max_attempts = max_attempts
|
|
464
636
|
self.delay = delay
|
|
637
|
+
self.delays = _validate_delays(delays)
|
|
465
638
|
self.backoff = backoff
|
|
466
639
|
self.max_delay = max_delay
|
|
467
640
|
self.jitter = jitter
|
|
@@ -470,9 +643,12 @@ class _Engine:
|
|
|
470
643
|
self.retry_if = retry_if
|
|
471
644
|
self.retry_if_result = retry_if_result
|
|
472
645
|
self.on_retry = on_retry
|
|
646
|
+
if delay_from is not None and _core.is_async(delay_from):
|
|
647
|
+
raise TypeError("delay_from must be synchronous")
|
|
473
648
|
self.delay_from = delay_from
|
|
474
649
|
self.budget = budget
|
|
475
650
|
self.log = _core.get_logger(logger)
|
|
651
|
+
self.log_values = log_values
|
|
476
652
|
self.log_level = log_level
|
|
477
653
|
self.log_exc_info = log_exc_info
|
|
478
654
|
self.stats = stats
|
|
@@ -503,9 +679,21 @@ class _Engine:
|
|
|
503
679
|
def start_attempt(self) -> None:
|
|
504
680
|
with self.stats._lock:
|
|
505
681
|
self.stats.attempts_total += 1
|
|
682
|
+
if _core.listeners:
|
|
683
|
+
_ATTEMPT_STARTS.set({**(_ATTEMPT_STARTS.get() or {}), id(self): _core.monotonic()})
|
|
684
|
+
|
|
685
|
+
def _attempt_seconds(self) -> float | None:
|
|
686
|
+
started = (_ATTEMPT_STARTS.get() or {}).get(id(self))
|
|
687
|
+
return None if started is None else max(0.0, _core.monotonic() - started)
|
|
506
688
|
|
|
507
689
|
def success(self, attempts: int) -> None:
|
|
508
|
-
_core.
|
|
690
|
+
if _core.listeners:
|
|
691
|
+
_core.emit(
|
|
692
|
+
"retry.succeeded",
|
|
693
|
+
self.name,
|
|
694
|
+
attempts=attempts,
|
|
695
|
+
attempt_seconds=self._attempt_seconds(),
|
|
696
|
+
)
|
|
509
697
|
|
|
510
698
|
def slept(self, seconds: float) -> None:
|
|
511
699
|
with self.stats._lock:
|
|
@@ -521,26 +709,47 @@ class _Engine:
|
|
|
521
709
|
"`async for attempt in retrying(...)` with `async with attempt:`"
|
|
522
710
|
)
|
|
523
711
|
|
|
524
|
-
def _wait_for(self, attempt: int, exc: BaseException | None) -> float:
|
|
525
|
-
if self.delay_from is not None
|
|
712
|
+
def _wait_for(self, attempt: int, exc: BaseException | None, result: Any = None) -> float:
|
|
713
|
+
if self.delay_from is not None:
|
|
526
714
|
try:
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
self.
|
|
715
|
+
# A result-based retry passes the rejected value, so a response-like
|
|
716
|
+
# object with Retry-After (or retry_after in its JSON) is honoured.
|
|
717
|
+
raw_hint = self.delay_from(exc if exc is not None else result)
|
|
718
|
+
if inspect.iscoroutine(raw_hint):
|
|
719
|
+
raw_hint.close()
|
|
720
|
+
hint = None
|
|
721
|
+
else:
|
|
722
|
+
hint = _parse_hint(raw_hint)
|
|
723
|
+
except Exception as hint_error:
|
|
724
|
+
with contextlib.suppress(Exception):
|
|
725
|
+
self.log.debug(
|
|
726
|
+
"%s: delay_from raised (%s); using backoff",
|
|
727
|
+
self.name,
|
|
728
|
+
type(hint_error).__name__,
|
|
729
|
+
exc_info=self.log_values,
|
|
730
|
+
)
|
|
530
731
|
hint = None
|
|
531
732
|
if hint is not None:
|
|
532
|
-
return hint if self.max_delay is None else
|
|
733
|
+
return min(hint, HINT_CEILING if self.max_delay is None else self.max_delay)
|
|
734
|
+
if self.delays is not None:
|
|
735
|
+
delay = self.delays[min(attempt - 1, len(self.delays) - 1)]
|
|
736
|
+
return _compute_delay(1, delay, 1.0, self.max_delay, self.jitter)
|
|
533
737
|
return _compute_delay(attempt, self.delay, self.backoff, self.max_delay, self.jitter)
|
|
534
738
|
|
|
535
739
|
def _plan(
|
|
536
|
-
self,
|
|
740
|
+
self,
|
|
741
|
+
attempt: int,
|
|
742
|
+
exc: BaseException | None,
|
|
743
|
+
wanted: bool,
|
|
744
|
+
started: float,
|
|
745
|
+
result: Any = None,
|
|
537
746
|
) -> float | None:
|
|
538
747
|
"""The wait before the next attempt, or None to stop (counted and emitted)."""
|
|
539
748
|
wait: float | None = None
|
|
540
749
|
denied = False
|
|
541
750
|
limit = self.limit()
|
|
542
751
|
if wanted and (limit is None or attempt < limit):
|
|
543
|
-
wait = self._wait_for(attempt, exc)
|
|
752
|
+
wait = self._wait_for(attempt, exc, result)
|
|
544
753
|
if self.max_time is not None and _core.monotonic() - started + wait > self.max_time:
|
|
545
754
|
wait = None
|
|
546
755
|
left = _deadline_remaining()
|
|
@@ -556,7 +765,13 @@ class _Engine:
|
|
|
556
765
|
self.stats.budget_exhausted += 1
|
|
557
766
|
if denied:
|
|
558
767
|
_core.emit("retry.budget_exhausted", self.name, attempts=attempt, exception=exc)
|
|
559
|
-
_core.emit(
|
|
768
|
+
_core.emit(
|
|
769
|
+
"retry.gave_up",
|
|
770
|
+
self.name,
|
|
771
|
+
attempts=attempt,
|
|
772
|
+
exception=exc,
|
|
773
|
+
attempt_seconds=self._attempt_seconds(),
|
|
774
|
+
)
|
|
560
775
|
return None
|
|
561
776
|
with self.stats._lock:
|
|
562
777
|
self.stats.retries += 1
|
|
@@ -570,7 +785,12 @@ class _Engine:
|
|
|
570
785
|
def _announce(self, attempt: int, exc: BaseException | None, result: Any, wait: float) -> None:
|
|
571
786
|
if self.log_level is not None:
|
|
572
787
|
limit = self.limit()
|
|
573
|
-
|
|
788
|
+
if self.log_values:
|
|
789
|
+
what = repr(exc) if exc is not None else f"returned {result!r}"
|
|
790
|
+
else:
|
|
791
|
+
what = (
|
|
792
|
+
type(exc).__name__ if exc is not None else f"returned {type(result).__name__}"
|
|
793
|
+
)
|
|
574
794
|
self.log.log(
|
|
575
795
|
self.log_level,
|
|
576
796
|
"%s failed (attempt %d/%s): %s; retrying in %.3fs",
|
|
@@ -581,18 +801,50 @@ class _Engine:
|
|
|
581
801
|
wait,
|
|
582
802
|
exc_info=(
|
|
583
803
|
(type(exc), exc, exc.__traceback__)
|
|
584
|
-
if self.log_exc_info and exc is not None
|
|
804
|
+
if self.log_values and self.log_exc_info and exc is not None
|
|
585
805
|
else None
|
|
586
806
|
),
|
|
587
807
|
)
|
|
588
808
|
_core.emit(
|
|
589
|
-
"retry.attempt_failed",
|
|
809
|
+
"retry.attempt_failed",
|
|
810
|
+
self.name,
|
|
811
|
+
attempt=attempt,
|
|
812
|
+
exception=exc,
|
|
813
|
+
next_delay=wait,
|
|
814
|
+
attempt_seconds=self._attempt_seconds(),
|
|
590
815
|
)
|
|
591
816
|
|
|
592
817
|
def _record(self, exc: BaseException) -> None:
|
|
593
818
|
with self.stats._lock:
|
|
594
819
|
self.stats.last_exception = exc
|
|
595
820
|
|
|
821
|
+
def _run_hook(self, state: RetryState) -> None:
|
|
822
|
+
"""Run `on_retry`; a failing hook must never replace the original outcome."""
|
|
823
|
+
if self.on_retry is None:
|
|
824
|
+
return
|
|
825
|
+
try:
|
|
826
|
+
self.on_retry(state)
|
|
827
|
+
except Exception as hook_error:
|
|
828
|
+
self._hook_failure(hook_error)
|
|
829
|
+
|
|
830
|
+
def _hook_failure(self, error: Exception) -> None:
|
|
831
|
+
with contextlib.suppress(Exception):
|
|
832
|
+
self.log.error(
|
|
833
|
+
"%s: on_retry hook failed (%s); the original error/result is kept",
|
|
834
|
+
self.name,
|
|
835
|
+
type(error).__name__,
|
|
836
|
+
exc_info=self.log_values,
|
|
837
|
+
)
|
|
838
|
+
|
|
839
|
+
async def _arun_hook(self, state: RetryState) -> None:
|
|
840
|
+
"""`_run_hook` for async callers: an async hook is awaited, failures swallowed."""
|
|
841
|
+
if self.on_retry is None:
|
|
842
|
+
return
|
|
843
|
+
try:
|
|
844
|
+
await _maybe_await(self.on_retry(state))
|
|
845
|
+
except Exception as hook_error:
|
|
846
|
+
self._hook_failure(hook_error)
|
|
847
|
+
|
|
596
848
|
# -- sync decisions -------------------------------------------------------------------
|
|
597
849
|
def failure(self, attempt: int, exc: BaseException, started: float) -> float | None:
|
|
598
850
|
"""Decide after a failed attempt: the wait in seconds, or None to re-raise."""
|
|
@@ -603,8 +855,7 @@ class _Engine:
|
|
|
603
855
|
wanted = self.retry_if is None or bool(self.retry_if(exc))
|
|
604
856
|
wait = self._plan(attempt, exc, wanted, started)
|
|
605
857
|
if wait is not None:
|
|
606
|
-
|
|
607
|
-
self.on_retry(self._state(attempt, exc, None, wait, started))
|
|
858
|
+
self._run_hook(self._state(attempt, exc, None, wait, started))
|
|
608
859
|
self._announce(attempt, exc, None, wait)
|
|
609
860
|
return wait
|
|
610
861
|
|
|
@@ -618,10 +869,9 @@ class _Engine:
|
|
|
618
869
|
def result_failure(self, attempt: int, result: Any, started: float) -> float | None:
|
|
619
870
|
"""Decide after a rejected result: the wait, or None to return it as is."""
|
|
620
871
|
self.check_sync("on_retry")
|
|
621
|
-
wait = self._plan(attempt, None, True, started)
|
|
872
|
+
wait = self._plan(attempt, None, True, started, result)
|
|
622
873
|
if wait is not None:
|
|
623
|
-
|
|
624
|
-
self.on_retry(self._state(attempt, None, result, wait, started))
|
|
874
|
+
self._run_hook(self._state(attempt, None, result, wait, started))
|
|
625
875
|
self._announce(attempt, None, result, wait)
|
|
626
876
|
return wait
|
|
627
877
|
|
|
@@ -634,8 +884,7 @@ class _Engine:
|
|
|
634
884
|
wanted = self.retry_if is None or bool(await _maybe_await(self.retry_if(exc)))
|
|
635
885
|
wait = self._plan(attempt, exc, wanted, started)
|
|
636
886
|
if wait is not None:
|
|
637
|
-
|
|
638
|
-
await _maybe_await(self.on_retry(self._state(attempt, exc, None, wait, started)))
|
|
887
|
+
await self._arun_hook(self._state(attempt, exc, None, wait, started))
|
|
639
888
|
self._announce(attempt, exc, None, wait)
|
|
640
889
|
return wait
|
|
641
890
|
|
|
@@ -647,15 +896,89 @@ class _Engine:
|
|
|
647
896
|
|
|
648
897
|
async def aresult_failure(self, attempt: int, result: Any, started: float) -> float | None:
|
|
649
898
|
"""`result_failure` for async callers."""
|
|
650
|
-
wait = self._plan(attempt, None, True, started)
|
|
899
|
+
wait = self._plan(attempt, None, True, started, result)
|
|
651
900
|
if wait is not None:
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
await _maybe_await(self.on_retry(state))
|
|
901
|
+
state = self._state(attempt, None, result, wait, started)
|
|
902
|
+
await self._arun_hook(state)
|
|
655
903
|
self._announce(attempt, None, result, wait)
|
|
656
904
|
return wait
|
|
657
905
|
|
|
658
906
|
|
|
907
|
+
_HISTORY_ATTR = "__python_wrap_attempts__"
|
|
908
|
+
|
|
909
|
+
|
|
910
|
+
@dataclass(frozen=True)
|
|
911
|
+
class AttemptRecord:
|
|
912
|
+
"""One failed attempt of a `retry`-decorated call, as kept by `attempt_history`.
|
|
913
|
+
|
|
914
|
+
Only the exception's type name is kept (never its message), so the record is safe to
|
|
915
|
+
log or send to an error tracker.
|
|
916
|
+
|
|
917
|
+
Attributes:
|
|
918
|
+
number: The attempt number, 1-based.
|
|
919
|
+
duration: Seconds the attempt took.
|
|
920
|
+
exception: The exception's qualified type name.
|
|
921
|
+
next_delay: Seconds waited before the next attempt, or None for the last one.
|
|
922
|
+
"""
|
|
923
|
+
|
|
924
|
+
number: int
|
|
925
|
+
duration: float
|
|
926
|
+
exception: str
|
|
927
|
+
next_delay: float | None
|
|
928
|
+
|
|
929
|
+
|
|
930
|
+
def _remember(
|
|
931
|
+
history: list[AttemptRecord],
|
|
932
|
+
attempt: int,
|
|
933
|
+
began: float,
|
|
934
|
+
exc: BaseException,
|
|
935
|
+
wait: float | None,
|
|
936
|
+
) -> None:
|
|
937
|
+
kind = type(exc)
|
|
938
|
+
history.append(
|
|
939
|
+
AttemptRecord(
|
|
940
|
+
attempt, _core.perf_counter() - began, f"{kind.__module__}.{kind.__qualname__}", wait
|
|
941
|
+
)
|
|
942
|
+
)
|
|
943
|
+
if wait is None:
|
|
944
|
+
# Exceptions with __slots__ or a read-only __dict__ simply carry no history.
|
|
945
|
+
with contextlib.suppress(AttributeError, TypeError):
|
|
946
|
+
setattr(exc, _HISTORY_ATTR, tuple(history))
|
|
947
|
+
|
|
948
|
+
|
|
949
|
+
def attempt_history(exc: BaseException) -> tuple[AttemptRecord, ...]:
|
|
950
|
+
"""The attempt timeline a `retry` decorator attached to the exception it re-raised.
|
|
951
|
+
|
|
952
|
+
When `retry` gives up, the exception it re-raises carries one `AttemptRecord` per
|
|
953
|
+
failed attempt (durations, exception types and the waits in between), so a
|
|
954
|
+
postmortem or an error tracker sees the whole retry sequence, not just the last error.
|
|
955
|
+
|
|
956
|
+
Args:
|
|
957
|
+
exc: Any exception.
|
|
958
|
+
|
|
959
|
+
Returns:
|
|
960
|
+
The records, oldest first; empty if the exception did not come out of `retry`.
|
|
961
|
+
|
|
962
|
+
Example:
|
|
963
|
+
```python
|
|
964
|
+
from python_wrap import attempt_history, retry
|
|
965
|
+
|
|
966
|
+
@retry(max_attempts=3, delay=0, on=ConnectionError)
|
|
967
|
+
def fetch() -> None:
|
|
968
|
+
raise ConnectionError("refused")
|
|
969
|
+
|
|
970
|
+
try:
|
|
971
|
+
fetch()
|
|
972
|
+
except ConnectionError as exc:
|
|
973
|
+
timeline = attempt_history(exc)
|
|
974
|
+
assert [record.number for record in timeline] == [1, 2, 3]
|
|
975
|
+
assert timeline[-1].next_delay is None
|
|
976
|
+
```
|
|
977
|
+
"""
|
|
978
|
+
history = getattr(exc, _HISTORY_ATTR, ())
|
|
979
|
+
return history if isinstance(history, tuple) else ()
|
|
980
|
+
|
|
981
|
+
|
|
659
982
|
def _check_budget(budget: Any) -> None:
|
|
660
983
|
if budget is not None and not isinstance(budget, RetryBudget):
|
|
661
984
|
raise TypeError(f"budget must be a RetryBudget or None, got {budget!r}")
|
|
@@ -670,17 +993,19 @@ def retry(
|
|
|
670
993
|
delay: float = ...,
|
|
671
994
|
backoff: float = ...,
|
|
672
995
|
max_delay: float | None = ...,
|
|
673
|
-
jitter: float = ...,
|
|
996
|
+
jitter: float | str = ...,
|
|
674
997
|
max_time: float | None = ...,
|
|
675
998
|
on: ExceptionTypes = ...,
|
|
676
999
|
retry_if: ExceptionPredicate | None = ...,
|
|
677
1000
|
retry_if_result: ResultPredicate | None = ...,
|
|
678
1001
|
on_retry: RetryCallback | None = ...,
|
|
679
|
-
delay_from: Callable[[
|
|
1002
|
+
delay_from: Callable[[Any], float | None] | None = ...,
|
|
1003
|
+
delays: Sequence[float] | None = ...,
|
|
680
1004
|
budget: RetryBudget | None = ...,
|
|
681
1005
|
logger: LoggerLike = ...,
|
|
682
1006
|
log_level: int | None = ...,
|
|
683
1007
|
log_exc_info: bool = ...,
|
|
1008
|
+
log_values: bool = ...,
|
|
684
1009
|
) -> F: ...
|
|
685
1010
|
@overload
|
|
686
1011
|
def retry(
|
|
@@ -691,17 +1016,19 @@ def retry(
|
|
|
691
1016
|
delay: float = ...,
|
|
692
1017
|
backoff: float = ...,
|
|
693
1018
|
max_delay: float | None = ...,
|
|
694
|
-
jitter: float = ...,
|
|
1019
|
+
jitter: float | str = ...,
|
|
695
1020
|
max_time: float | None = ...,
|
|
696
1021
|
on: ExceptionTypes = ...,
|
|
697
1022
|
retry_if: ExceptionPredicate | None = ...,
|
|
698
1023
|
retry_if_result: ResultPredicate | None = ...,
|
|
699
1024
|
on_retry: RetryCallback | None = ...,
|
|
700
|
-
delay_from: Callable[[
|
|
1025
|
+
delay_from: Callable[[Any], float | None] | None = ...,
|
|
1026
|
+
delays: Sequence[float] | None = ...,
|
|
701
1027
|
budget: RetryBudget | None = ...,
|
|
702
1028
|
logger: LoggerLike = ...,
|
|
703
1029
|
log_level: int | None = ...,
|
|
704
1030
|
log_exc_info: bool = ...,
|
|
1031
|
+
log_values: bool = ...,
|
|
705
1032
|
) -> Callable[[F], F]: ...
|
|
706
1033
|
def retry(
|
|
707
1034
|
func: Callable[..., Any] | None = None,
|
|
@@ -711,17 +1038,19 @@ def retry(
|
|
|
711
1038
|
delay: float = _UNSET,
|
|
712
1039
|
backoff: float = _UNSET,
|
|
713
1040
|
max_delay: float | None = _UNSET,
|
|
714
|
-
jitter: float = _UNSET,
|
|
1041
|
+
jitter: float | str = _UNSET,
|
|
715
1042
|
max_time: float | None = _UNSET,
|
|
716
1043
|
on: ExceptionTypes = Exception,
|
|
717
1044
|
retry_if: ExceptionPredicate | None = None,
|
|
718
1045
|
retry_if_result: ResultPredicate | None = None,
|
|
719
1046
|
on_retry: RetryCallback | None = None,
|
|
720
|
-
delay_from: Callable[[
|
|
1047
|
+
delay_from: Callable[[Any], float | None] | None = None,
|
|
1048
|
+
delays: Sequence[float] | None = None,
|
|
721
1049
|
budget: RetryBudget | None = _UNSET,
|
|
722
1050
|
logger: LoggerLike = None,
|
|
723
1051
|
log_level: int | None = _UNSET,
|
|
724
1052
|
log_exc_info: bool = False,
|
|
1053
|
+
log_values: bool = True,
|
|
725
1054
|
) -> Any:
|
|
726
1055
|
"""Retry a function when it raises (or returns a bad value), with optional backoff.
|
|
727
1056
|
|
|
@@ -759,10 +1088,15 @@ def retry(
|
|
|
759
1088
|
Args:
|
|
760
1089
|
func: The function to wrap (when used without parentheses).
|
|
761
1090
|
max_attempts: Total number of calls allowed, or `None` for no limit.
|
|
1091
|
+
delays: Optional nonempty sequence of finite nonnegative waits. Failure n
|
|
1092
|
+
uses entry n (one-based), repeating the last entry after exhaustion.
|
|
1093
|
+
Overrides delay/backoff; max_delay caps before jitter. A valid delay_from
|
|
1094
|
+
hint takes priority. Does not change max_attempts. Copied at creation.
|
|
762
1095
|
delay: Base wait in seconds before the second attempt.
|
|
763
1096
|
backoff: Multiplier applied to the wait after each failure (>= 1).
|
|
764
1097
|
max_delay: Upper bound for the backoff wait (before jitter is added); also caps
|
|
765
|
-
waits returned by `delay_from
|
|
1098
|
+
waits returned by `delay_from` (which are otherwise capped at
|
|
1099
|
+
``HINT_CEILING``, 600 s; non-finite hints fall back to the backoff).
|
|
766
1100
|
jitter: Up to this many random extra seconds are added to each wait.
|
|
767
1101
|
max_time: Total time budget in seconds, measured from the first attempt. If the
|
|
768
1102
|
next wait would run past it, the last exception is re-raised instead.
|
|
@@ -772,14 +1106,19 @@ def retry(
|
|
|
772
1106
|
retry_if_result: Predicate on the return value; True means "retry". When no
|
|
773
1107
|
retry is left the last value is returned. May be async for async functions.
|
|
774
1108
|
on_retry: Called with a `RetryState` before each wait. May be async for async
|
|
775
|
-
functions.
|
|
776
|
-
|
|
1109
|
+
functions. An exception raised by the hook is logged and swallowed: it never
|
|
1110
|
+
replaces the original error or rejected result.
|
|
1111
|
+
delay_from: Called with the exception, or with the rejected return value when
|
|
1112
|
+
``retry_if_result`` scheduled the retry; a number is the exact wait for this
|
|
777
1113
|
attempt (no backoff, no jitter; still capped by `max_delay` and `max_time`),
|
|
778
1114
|
`None` means use the normal backoff. See `retry_after_header`.
|
|
779
1115
|
budget: A `RetryBudget` shared with other retried code. When it refuses a retry
|
|
780
1116
|
the last exception is re-raised (or the last result returned) at once.
|
|
781
1117
|
logger: Logger (or logger name) for the per-retry message.
|
|
782
1118
|
log_level: Level of the per-retry message, or `None` to not log.
|
|
1119
|
+
log_values: False logs only exception/result type names, including hook/hint
|
|
1120
|
+
failures, and suppresses log_exc_info. Events, stats and callbacks still
|
|
1121
|
+
receive original objects; function names and custom loggers are caller-owned.
|
|
783
1122
|
log_exc_info: Attach the traceback to the per-retry log record.
|
|
784
1123
|
|
|
785
1124
|
Returns:
|
|
@@ -815,6 +1154,21 @@ def retry(
|
|
|
815
1154
|
# Validate eagerly so a bad option fails at decoration time, even with no function yet.
|
|
816
1155
|
_validate(max_attempts, delay, backoff, max_delay, jitter, max_time)
|
|
817
1156
|
_check_budget(budget)
|
|
1157
|
+
delays = _validate_delays(delays)
|
|
1158
|
+
|
|
1159
|
+
settings = {
|
|
1160
|
+
"max_attempts": max_attempts,
|
|
1161
|
+
"delay": delay,
|
|
1162
|
+
"backoff": backoff,
|
|
1163
|
+
"max_delay": max_delay,
|
|
1164
|
+
"jitter": jitter,
|
|
1165
|
+
"max_time": max_time,
|
|
1166
|
+
"delays": delays,
|
|
1167
|
+
"on": on,
|
|
1168
|
+
"retry_if": retry_if is not None,
|
|
1169
|
+
"retry_if_result": retry_if_result is not None,
|
|
1170
|
+
"budget": budget is not None,
|
|
1171
|
+
}
|
|
818
1172
|
|
|
819
1173
|
def decorate(f: Callable[P, R]) -> Callable[P, R]:
|
|
820
1174
|
stats = RetryStats()
|
|
@@ -831,10 +1185,12 @@ def retry(
|
|
|
831
1185
|
retry_if_result=retry_if_result,
|
|
832
1186
|
on_retry=on_retry,
|
|
833
1187
|
delay_from=delay_from,
|
|
1188
|
+
delays=delays,
|
|
834
1189
|
budget=budget,
|
|
835
1190
|
logger=logger,
|
|
836
1191
|
log_level=log_level,
|
|
837
1192
|
log_exc_info=log_exc_info,
|
|
1193
|
+
log_values=log_values,
|
|
838
1194
|
stats=stats,
|
|
839
1195
|
)
|
|
840
1196
|
check_result = retry_if_result is not None
|
|
@@ -846,12 +1202,15 @@ def retry(
|
|
|
846
1202
|
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
847
1203
|
started = engine.start_call()
|
|
848
1204
|
attempt = 1
|
|
1205
|
+
history: list[AttemptRecord] = []
|
|
849
1206
|
while True:
|
|
850
1207
|
engine.start_attempt()
|
|
1208
|
+
began = _core.perf_counter()
|
|
851
1209
|
try:
|
|
852
1210
|
result = await af(*args, **kwargs)
|
|
853
1211
|
except on as exc:
|
|
854
1212
|
wait = await engine.afailure(attempt, exc, started)
|
|
1213
|
+
_remember(history, attempt, began, exc, wait)
|
|
855
1214
|
if wait is None:
|
|
856
1215
|
raise
|
|
857
1216
|
else:
|
|
@@ -866,6 +1225,7 @@ def retry(
|
|
|
866
1225
|
attempt += 1
|
|
867
1226
|
|
|
868
1227
|
setattr(async_wrapper, _STATS_ATTR, stats)
|
|
1228
|
+
setattr(async_wrapper, _LAYER_ATTR, ("retry", settings))
|
|
869
1229
|
return cast("Callable[P, R]", async_wrapper)
|
|
870
1230
|
|
|
871
1231
|
engine.check_sync(*engine.async_hooks)
|
|
@@ -874,12 +1234,15 @@ def retry(
|
|
|
874
1234
|
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
|
875
1235
|
started = engine.start_call()
|
|
876
1236
|
attempt = 1
|
|
1237
|
+
history: list[AttemptRecord] = []
|
|
877
1238
|
while True:
|
|
878
1239
|
engine.start_attempt()
|
|
1240
|
+
began = _core.perf_counter()
|
|
879
1241
|
try:
|
|
880
1242
|
result = f(*args, **kwargs)
|
|
881
1243
|
except on as exc:
|
|
882
1244
|
wait = engine.failure(attempt, exc, started)
|
|
1245
|
+
_remember(history, attempt, began, exc, wait)
|
|
883
1246
|
if wait is None:
|
|
884
1247
|
raise
|
|
885
1248
|
else:
|
|
@@ -894,8 +1257,10 @@ def retry(
|
|
|
894
1257
|
attempt += 1
|
|
895
1258
|
|
|
896
1259
|
setattr(wrapper, _STATS_ATTR, stats)
|
|
1260
|
+
setattr(wrapper, _LAYER_ATTR, ("retry", settings))
|
|
897
1261
|
return wrapper
|
|
898
1262
|
|
|
1263
|
+
setattr(decorate, _LAYER_ATTR, ("retry", settings))
|
|
899
1264
|
return decorate if func is None else decorate(func)
|
|
900
1265
|
|
|
901
1266
|
|
|
@@ -1034,17 +1399,19 @@ def retrying(
|
|
|
1034
1399
|
delay: float = _UNSET,
|
|
1035
1400
|
backoff: float = _UNSET,
|
|
1036
1401
|
max_delay: float | None = _UNSET,
|
|
1037
|
-
jitter: float = _UNSET,
|
|
1402
|
+
jitter: float | str = _UNSET,
|
|
1038
1403
|
max_time: float | None = _UNSET,
|
|
1039
1404
|
on: ExceptionTypes = Exception,
|
|
1040
1405
|
retry_if: ExceptionPredicate | None = None,
|
|
1041
1406
|
retry_if_result: ResultPredicate | None = None,
|
|
1042
1407
|
on_retry: RetryCallback | None = None,
|
|
1043
|
-
delay_from: Callable[[
|
|
1408
|
+
delay_from: Callable[[Any], float | None] | None = None,
|
|
1409
|
+
delays: Sequence[float] | None = None,
|
|
1044
1410
|
budget: RetryBudget | None = _UNSET,
|
|
1045
1411
|
logger: LoggerLike = None,
|
|
1046
1412
|
log_level: int | None = _UNSET,
|
|
1047
1413
|
log_exc_info: bool = False,
|
|
1414
|
+
log_values: bool = True,
|
|
1048
1415
|
name: str = "retrying",
|
|
1049
1416
|
) -> Retrying:
|
|
1050
1417
|
"""Retry an inline block of code instead of a whole function.
|
|
@@ -1065,6 +1432,10 @@ def retrying(
|
|
|
1065
1432
|
|
|
1066
1433
|
Args:
|
|
1067
1434
|
max_attempts: Total attempts allowed, or `None` for no limit.
|
|
1435
|
+
delays: Optional nonempty sequence of finite nonnegative waits. Failure n
|
|
1436
|
+
uses entry n (one-based), repeating the last entry after exhaustion.
|
|
1437
|
+
Overrides delay/backoff; max_delay caps before jitter. A valid delay_from
|
|
1438
|
+
hint takes priority. Does not change max_attempts. Copied at creation.
|
|
1068
1439
|
delay: Base wait in seconds before the second attempt.
|
|
1069
1440
|
backoff: Multiplier applied to the wait after each failure (>= 1).
|
|
1070
1441
|
max_delay: Upper bound for the backoff wait (before jitter).
|
|
@@ -1073,11 +1444,16 @@ def retrying(
|
|
|
1073
1444
|
on: Exception type(s) that trigger a retry.
|
|
1074
1445
|
retry_if: Extra predicate on the exception; retry only if it returns True.
|
|
1075
1446
|
retry_if_result: Predicate on `attempt.result`; True means "retry".
|
|
1076
|
-
on_retry: Called with a `RetryState` before each wait
|
|
1077
|
-
|
|
1447
|
+
on_retry: Called with a `RetryState` before each wait; a failing hook is logged
|
|
1448
|
+
and swallowed.
|
|
1449
|
+
delay_from: Exact wait derived from the exception or rejected result, or `None`
|
|
1450
|
+
for backoff.
|
|
1078
1451
|
budget: A shared `RetryBudget`; when it refuses, the loop stops retrying.
|
|
1079
1452
|
logger: Logger (or logger name) for the per-retry message.
|
|
1080
1453
|
log_level: Level of the per-retry message, or `None` to not log.
|
|
1454
|
+
log_values: False logs only exception/result type names, including hook/hint
|
|
1455
|
+
failures, and suppresses log_exc_info. Events, stats and callbacks still
|
|
1456
|
+
receive original objects; function names and custom loggers are caller-owned.
|
|
1081
1457
|
log_exc_info: Attach the traceback to the per-retry log record.
|
|
1082
1458
|
name: Name used in log messages and events.
|
|
1083
1459
|
|
|
@@ -1124,10 +1500,12 @@ def retrying(
|
|
|
1124
1500
|
retry_if_result=retry_if_result,
|
|
1125
1501
|
on_retry=on_retry,
|
|
1126
1502
|
delay_from=delay_from,
|
|
1503
|
+
delays=delays,
|
|
1127
1504
|
budget=ds["budget"],
|
|
1128
1505
|
logger=logger,
|
|
1129
1506
|
log_level=log_level,
|
|
1130
1507
|
log_exc_info=log_exc_info,
|
|
1508
|
+
log_values=log_values,
|
|
1131
1509
|
stats=RetryStats(),
|
|
1132
1510
|
)
|
|
1133
1511
|
)
|
|
@@ -1139,7 +1517,7 @@ def retry_on_exception(
|
|
|
1139
1517
|
delay: float = 0.0,
|
|
1140
1518
|
backoff: float = 1.0,
|
|
1141
1519
|
max_delay: float | None = None,
|
|
1142
|
-
jitter: float = 0.0,
|
|
1520
|
+
jitter: float | str = 0.0,
|
|
1143
1521
|
retry_if: Callable[[BaseException], bool] | None = None,
|
|
1144
1522
|
on_retry: Callable[[RetryState], None] | None = None,
|
|
1145
1523
|
logger: LoggerLike = None,
|