backon 3.0.0__tar.gz
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.
- backon-3.0.0/LICENSE +21 -0
- backon-3.0.0/PKG-INFO +179 -0
- backon-3.0.0/README.md +153 -0
- backon-3.0.0/backon/__init__.py +23 -0
- backon-3.0.0/backon/_async.py +208 -0
- backon-3.0.0/backon/_common.py +117 -0
- backon-3.0.0/backon/_decorator.py +150 -0
- backon-3.0.0/backon/_jitter.py +9 -0
- backon-3.0.0/backon/_retry.py +464 -0
- backon-3.0.0/backon/_sync.py +173 -0
- backon-3.0.0/backon/_typing.py +51 -0
- backon-3.0.0/backon/_wait_gen.py +62 -0
- backon-3.0.0/backon/py.typed +0 -0
- backon-3.0.0/backon/types.py +3 -0
- backon-3.0.0/pyproject.toml +79 -0
- backon-3.0.0/tests/__init__.py +0 -0
- backon-3.0.0/tests/test_backon.py +45 -0
- backon-3.0.0/tests/test_backon_async.py +183 -0
- backon-3.0.0/tests/test_backon_predicate.py +84 -0
- backon-3.0.0/tests/test_backon_sync.py +225 -0
- backon-3.0.0/tests/test_features.py +145 -0
- backon-3.0.0/tests/test_jitter.py +30 -0
- backon-3.0.0/tests/test_retry.py +202 -0
- backon-3.0.0/tests/test_types.py +29 -0
- backon-3.0.0/tests/test_typing.py +58 -0
- backon-3.0.0/tests/test_wait_gen.py +84 -0
backon-3.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Llucs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
backon-3.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: backon
|
|
3
|
+
Version: 3.0.0
|
|
4
|
+
Summary: Function decoration for backoff and retry
|
|
5
|
+
Keywords: retry,backoff,decorators
|
|
6
|
+
Author-Email: Llucs <c307lucas@gmail.com>
|
|
7
|
+
License: MIT
|
|
8
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Natural Language :: English
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
21
|
+
Classifier: Topic :: Utilities
|
|
22
|
+
Project-URL: homepage, https://github.com/Llucs/backon
|
|
23
|
+
Project-URL: repository, https://github.com/Llucs/backon
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# backon
|
|
28
|
+
|
|
29
|
+
> Function decoration for backoff and retry — modern, fast, and zero dependencies.
|
|
30
|
+
|
|
31
|
+
[](https://github.com/Llucs/backon/actions/workflows/ci.yml)
|
|
32
|
+
[](https://pypi.org/project/backon/)
|
|
33
|
+
[](https://pypi.org/project/backon/)
|
|
34
|
+
[](https://github.com/Llucs/backon/blob/main/LICENSE)
|
|
35
|
+
|
|
36
|
+
## Why backon?
|
|
37
|
+
|
|
38
|
+
**backon** is the evolution of [backoff](https://github.com/litl/backoff) — a zero-dependency Python library for retry with exponential backoff. If you know backoff, you already know backon.
|
|
39
|
+
|
|
40
|
+
| Feature | backoff | tenacity | backon |
|
|
41
|
+
|---|---|---|---|
|
|
42
|
+
| Python 3.10+ native | ❌ | ❌ | ✅ |
|
|
43
|
+
| Type hints | ❌ partial | ✅ | ✅ full |
|
|
44
|
+
| `disable()` / `enable()` toggle | ❌ | ❌ | ✅ |
|
|
45
|
+
| Context manager API | ❌ | ✅ | ✅ |
|
|
46
|
+
| Functional `retry()` API | ❌ | ✅ | ✅ |
|
|
47
|
+
| `on_attempt` callback | ❌ | ✅ | ✅ |
|
|
48
|
+
| Custom sleep injection | ❌ | ❌ | ✅ |
|
|
49
|
+
| `time.monotonic()` | ❌ | ✅ | ✅ |
|
|
50
|
+
| PDM / PEP 621 build | ❌ | ❌ | ✅ |
|
|
51
|
+
| Zero dependencies | ✅ | ✅ | ✅ |
|
|
52
|
+
|
|
53
|
+
## Quick Start
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
pip install backon
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### Retry on exception
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
import backon
|
|
63
|
+
|
|
64
|
+
@backon.on_exception(backon.expo, ValueError, max_tries=3)
|
|
65
|
+
def fetch_data():
|
|
66
|
+
return api.call()
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### Retry on predicate
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
@backon.on_predicate(backon.constant, max_tries=5, interval=0.5)
|
|
73
|
+
def poll_status():
|
|
74
|
+
return check_ready()
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### Functional API
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
result = backon.retry(fetch_data, backon.expo, exception=ValueError, max_tries=3)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Context manager
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
with backon.Retrying(backon.expo, exception=ValueError, max_tries=3) as r:
|
|
87
|
+
result = r.call(fetch_data)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Wait Generators
|
|
91
|
+
|
|
92
|
+
| Generator | Description |
|
|
93
|
+
|---|---|
|
|
94
|
+
| `expo(base=2, factor=1, max_value=None)` | Exponential backoff |
|
|
95
|
+
| `constant(interval=1)` | Constant interval |
|
|
96
|
+
| `fibo(max_value=None)` | Fibonacci backoff |
|
|
97
|
+
| `runtime(value=callable)` | Dynamic wait from return value |
|
|
98
|
+
| `decay(initial_value=1, decay_factor=1, min_value=None)` | Exponential decay |
|
|
99
|
+
|
|
100
|
+
## Jitter
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
@backon.on_exception(backon.expo, ValueError, jitter=backon.full_jitter)
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
- `full_jitter` — random between 0 and the wait value
|
|
107
|
+
- `random_jitter` — random ±25% around the wait value
|
|
108
|
+
- `None` — no jitter
|
|
109
|
+
|
|
110
|
+
## Handlers
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
def log_attempt(details):
|
|
114
|
+
print(f"Attempt {details['tries']} for {details['target'].__name__}")
|
|
115
|
+
|
|
116
|
+
@backon.on_exception(
|
|
117
|
+
backon.expo, ValueError, max_tries=3,
|
|
118
|
+
on_attempt=log_attempt,
|
|
119
|
+
on_backoff=log_attempt,
|
|
120
|
+
on_success=log_attempt,
|
|
121
|
+
on_giveup=log_attempt,
|
|
122
|
+
)
|
|
123
|
+
def f():
|
|
124
|
+
...
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Available `details` keys: `target`, `args`, `kwargs`, `tries`, `elapsed`, `value` (on_success/on_backoff/on_giveup), `exception` (on_backoff/on_giveup), `wait` (on_backoff).
|
|
128
|
+
|
|
129
|
+
## Global Toggle
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
backon.disable() # skip retry, call function directly
|
|
133
|
+
backon.enable() # re-enable retry
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Async Support
|
|
137
|
+
|
|
138
|
+
Everything works with `async def` functions — no extra flags needed.
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
@backon.on_exception(backon.expo, ValueError, max_tries=3)
|
|
142
|
+
async def fetch_data():
|
|
143
|
+
return await api.call()
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## Custom Sleep
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
@backon.on_exception(backon.expo, ValueError, max_tries=3,
|
|
150
|
+
sleep=lambda s: print(f"waiting {s}s"))
|
|
151
|
+
def f():
|
|
152
|
+
...
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## Installation
|
|
156
|
+
|
|
157
|
+
```bash
|
|
158
|
+
pip install backon
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Requires Python 3.10+.
|
|
162
|
+
|
|
163
|
+
## Migrating from backoff
|
|
164
|
+
|
|
165
|
+
backon is a drop-in replacement for most backoff users. Just change:
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
# before
|
|
169
|
+
import backoff
|
|
170
|
+
@backoff.on_exception(backoff.expo, ValueError, max_tries=3)
|
|
171
|
+
|
|
172
|
+
# after
|
|
173
|
+
import backon
|
|
174
|
+
@backon.on_exception(backon.expo, ValueError, max_tries=3)
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
## License
|
|
178
|
+
|
|
179
|
+
MIT
|
backon-3.0.0/README.md
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# backon
|
|
2
|
+
|
|
3
|
+
> Function decoration for backoff and retry — modern, fast, and zero dependencies.
|
|
4
|
+
|
|
5
|
+
[](https://github.com/Llucs/backon/actions/workflows/ci.yml)
|
|
6
|
+
[](https://pypi.org/project/backon/)
|
|
7
|
+
[](https://pypi.org/project/backon/)
|
|
8
|
+
[](https://github.com/Llucs/backon/blob/main/LICENSE)
|
|
9
|
+
|
|
10
|
+
## Why backon?
|
|
11
|
+
|
|
12
|
+
**backon** is the evolution of [backoff](https://github.com/litl/backoff) — a zero-dependency Python library for retry with exponential backoff. If you know backoff, you already know backon.
|
|
13
|
+
|
|
14
|
+
| Feature | backoff | tenacity | backon |
|
|
15
|
+
|---|---|---|---|
|
|
16
|
+
| Python 3.10+ native | ❌ | ❌ | ✅ |
|
|
17
|
+
| Type hints | ❌ partial | ✅ | ✅ full |
|
|
18
|
+
| `disable()` / `enable()` toggle | ❌ | ❌ | ✅ |
|
|
19
|
+
| Context manager API | ❌ | ✅ | ✅ |
|
|
20
|
+
| Functional `retry()` API | ❌ | ✅ | ✅ |
|
|
21
|
+
| `on_attempt` callback | ❌ | ✅ | ✅ |
|
|
22
|
+
| Custom sleep injection | ❌ | ❌ | ✅ |
|
|
23
|
+
| `time.monotonic()` | ❌ | ✅ | ✅ |
|
|
24
|
+
| PDM / PEP 621 build | ❌ | ❌ | ✅ |
|
|
25
|
+
| Zero dependencies | ✅ | ✅ | ✅ |
|
|
26
|
+
|
|
27
|
+
## Quick Start
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install backon
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### Retry on exception
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import backon
|
|
37
|
+
|
|
38
|
+
@backon.on_exception(backon.expo, ValueError, max_tries=3)
|
|
39
|
+
def fetch_data():
|
|
40
|
+
return api.call()
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Retry on predicate
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
@backon.on_predicate(backon.constant, max_tries=5, interval=0.5)
|
|
47
|
+
def poll_status():
|
|
48
|
+
return check_ready()
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Functional API
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
result = backon.retry(fetch_data, backon.expo, exception=ValueError, max_tries=3)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Context manager
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
with backon.Retrying(backon.expo, exception=ValueError, max_tries=3) as r:
|
|
61
|
+
result = r.call(fetch_data)
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Wait Generators
|
|
65
|
+
|
|
66
|
+
| Generator | Description |
|
|
67
|
+
|---|---|
|
|
68
|
+
| `expo(base=2, factor=1, max_value=None)` | Exponential backoff |
|
|
69
|
+
| `constant(interval=1)` | Constant interval |
|
|
70
|
+
| `fibo(max_value=None)` | Fibonacci backoff |
|
|
71
|
+
| `runtime(value=callable)` | Dynamic wait from return value |
|
|
72
|
+
| `decay(initial_value=1, decay_factor=1, min_value=None)` | Exponential decay |
|
|
73
|
+
|
|
74
|
+
## Jitter
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
@backon.on_exception(backon.expo, ValueError, jitter=backon.full_jitter)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
- `full_jitter` — random between 0 and the wait value
|
|
81
|
+
- `random_jitter` — random ±25% around the wait value
|
|
82
|
+
- `None` — no jitter
|
|
83
|
+
|
|
84
|
+
## Handlers
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
def log_attempt(details):
|
|
88
|
+
print(f"Attempt {details['tries']} for {details['target'].__name__}")
|
|
89
|
+
|
|
90
|
+
@backon.on_exception(
|
|
91
|
+
backon.expo, ValueError, max_tries=3,
|
|
92
|
+
on_attempt=log_attempt,
|
|
93
|
+
on_backoff=log_attempt,
|
|
94
|
+
on_success=log_attempt,
|
|
95
|
+
on_giveup=log_attempt,
|
|
96
|
+
)
|
|
97
|
+
def f():
|
|
98
|
+
...
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Available `details` keys: `target`, `args`, `kwargs`, `tries`, `elapsed`, `value` (on_success/on_backoff/on_giveup), `exception` (on_backoff/on_giveup), `wait` (on_backoff).
|
|
102
|
+
|
|
103
|
+
## Global Toggle
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
backon.disable() # skip retry, call function directly
|
|
107
|
+
backon.enable() # re-enable retry
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Async Support
|
|
111
|
+
|
|
112
|
+
Everything works with `async def` functions — no extra flags needed.
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
@backon.on_exception(backon.expo, ValueError, max_tries=3)
|
|
116
|
+
async def fetch_data():
|
|
117
|
+
return await api.call()
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Custom Sleep
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
@backon.on_exception(backon.expo, ValueError, max_tries=3,
|
|
124
|
+
sleep=lambda s: print(f"waiting {s}s"))
|
|
125
|
+
def f():
|
|
126
|
+
...
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## Installation
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
pip install backon
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Requires Python 3.10+.
|
|
136
|
+
|
|
137
|
+
## Migrating from backoff
|
|
138
|
+
|
|
139
|
+
backon is a drop-in replacement for most backoff users. Just change:
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
# before
|
|
143
|
+
import backoff
|
|
144
|
+
@backoff.on_exception(backoff.expo, ValueError, max_tries=3)
|
|
145
|
+
|
|
146
|
+
# after
|
|
147
|
+
import backon
|
|
148
|
+
@backon.on_exception(backon.expo, ValueError, max_tries=3)
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## License
|
|
152
|
+
|
|
153
|
+
MIT
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from backon._common import disable, enable
|
|
2
|
+
from backon._decorator import on_exception, on_predicate
|
|
3
|
+
from backon._jitter import full_jitter, random_jitter
|
|
4
|
+
from backon._retry import Retrying, retry
|
|
5
|
+
from backon._wait_gen import constant, decay, expo, fibo, runtime
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"on_predicate",
|
|
9
|
+
"on_exception",
|
|
10
|
+
"retry",
|
|
11
|
+
"Retrying",
|
|
12
|
+
"constant",
|
|
13
|
+
"expo",
|
|
14
|
+
"decay",
|
|
15
|
+
"fibo",
|
|
16
|
+
"runtime",
|
|
17
|
+
"full_jitter",
|
|
18
|
+
"random_jitter",
|
|
19
|
+
"disable",
|
|
20
|
+
"enable",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
__version__ = "3.0.0"
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import functools
|
|
3
|
+
|
|
4
|
+
from backon._common import (
|
|
5
|
+
_elapsed,
|
|
6
|
+
_init_wait_gen,
|
|
7
|
+
_maybe_call,
|
|
8
|
+
_next_wait,
|
|
9
|
+
_now,
|
|
10
|
+
is_enabled,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _unwrap(target):
|
|
15
|
+
if isinstance(target, staticmethod):
|
|
16
|
+
return target.__func__
|
|
17
|
+
return target
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _ensure_coroutine(coro_or_func):
|
|
21
|
+
if asyncio.iscoroutinefunction(coro_or_func):
|
|
22
|
+
return coro_or_func
|
|
23
|
+
else:
|
|
24
|
+
|
|
25
|
+
@functools.wraps(coro_or_func)
|
|
26
|
+
async def f(*args, **kwargs):
|
|
27
|
+
return coro_or_func(*args, **kwargs)
|
|
28
|
+
|
|
29
|
+
return f
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _ensure_coroutines(coros_or_funcs):
|
|
33
|
+
return [_ensure_coroutine(f) for f in coros_or_funcs]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
async def _call_handlers(handlers, *, target, args, kwargs, tries, elapsed, **extra):
|
|
37
|
+
details = {
|
|
38
|
+
"target": target,
|
|
39
|
+
"args": args,
|
|
40
|
+
"kwargs": kwargs,
|
|
41
|
+
"tries": tries,
|
|
42
|
+
"elapsed": elapsed,
|
|
43
|
+
}
|
|
44
|
+
details.update(extra)
|
|
45
|
+
for handler in handlers:
|
|
46
|
+
await handler(details)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def retry_predicate(
|
|
50
|
+
target,
|
|
51
|
+
wait_gen,
|
|
52
|
+
predicate,
|
|
53
|
+
*,
|
|
54
|
+
max_tries,
|
|
55
|
+
max_time,
|
|
56
|
+
jitter,
|
|
57
|
+
on_success,
|
|
58
|
+
on_backoff,
|
|
59
|
+
on_giveup,
|
|
60
|
+
on_attempt,
|
|
61
|
+
sleep,
|
|
62
|
+
wait_gen_kwargs,
|
|
63
|
+
):
|
|
64
|
+
target = _unwrap(target)
|
|
65
|
+
on_success = _ensure_coroutines(on_success)
|
|
66
|
+
on_backoff = _ensure_coroutines(on_backoff)
|
|
67
|
+
on_giveup = _ensure_coroutines(on_giveup)
|
|
68
|
+
on_attempt = _ensure_coroutines(on_attempt)
|
|
69
|
+
|
|
70
|
+
assert not asyncio.iscoroutinefunction(max_tries)
|
|
71
|
+
assert not asyncio.iscoroutinefunction(jitter)
|
|
72
|
+
|
|
73
|
+
assert asyncio.iscoroutinefunction(target)
|
|
74
|
+
|
|
75
|
+
@functools.wraps(target)
|
|
76
|
+
async def retry(*args, **kwargs):
|
|
77
|
+
if not is_enabled():
|
|
78
|
+
return await target(*args, **kwargs)
|
|
79
|
+
|
|
80
|
+
max_tries_value = _maybe_call(max_tries)
|
|
81
|
+
max_time_value = _maybe_call(max_time)
|
|
82
|
+
|
|
83
|
+
tries = 0
|
|
84
|
+
start = _now()
|
|
85
|
+
wait = _init_wait_gen(wait_gen, wait_gen_kwargs)
|
|
86
|
+
while True:
|
|
87
|
+
tries += 1
|
|
88
|
+
elapsed = _elapsed(start)
|
|
89
|
+
details = {
|
|
90
|
+
"target": target,
|
|
91
|
+
"args": args,
|
|
92
|
+
"kwargs": kwargs,
|
|
93
|
+
"tries": tries,
|
|
94
|
+
"elapsed": elapsed,
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
await _call_handlers(on_attempt, **details)
|
|
98
|
+
|
|
99
|
+
ret = await target(*args, **kwargs)
|
|
100
|
+
if predicate(ret):
|
|
101
|
+
max_tries_exceeded = tries == max_tries_value
|
|
102
|
+
max_time_exceeded = (
|
|
103
|
+
max_time_value is not None and elapsed >= max_time_value
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
if max_tries_exceeded or max_time_exceeded:
|
|
107
|
+
await _call_handlers(on_giveup, **details, value=ret)
|
|
108
|
+
break
|
|
109
|
+
|
|
110
|
+
try:
|
|
111
|
+
seconds = _next_wait(wait, ret, jitter, elapsed, max_time_value)
|
|
112
|
+
except StopIteration:
|
|
113
|
+
await _call_handlers(on_giveup, **details, value=ret)
|
|
114
|
+
break
|
|
115
|
+
|
|
116
|
+
await _call_handlers(on_backoff, **details, value=ret, wait=seconds)
|
|
117
|
+
|
|
118
|
+
await sleep(seconds)
|
|
119
|
+
continue
|
|
120
|
+
else:
|
|
121
|
+
await _call_handlers(on_success, **details, value=ret)
|
|
122
|
+
break
|
|
123
|
+
|
|
124
|
+
return ret
|
|
125
|
+
|
|
126
|
+
return retry
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def retry_exception(
|
|
130
|
+
target,
|
|
131
|
+
wait_gen,
|
|
132
|
+
exception,
|
|
133
|
+
*,
|
|
134
|
+
max_tries,
|
|
135
|
+
max_time,
|
|
136
|
+
jitter,
|
|
137
|
+
giveup,
|
|
138
|
+
on_success,
|
|
139
|
+
on_backoff,
|
|
140
|
+
on_giveup,
|
|
141
|
+
on_attempt,
|
|
142
|
+
raise_on_giveup,
|
|
143
|
+
sleep,
|
|
144
|
+
wait_gen_kwargs,
|
|
145
|
+
):
|
|
146
|
+
target = _unwrap(target)
|
|
147
|
+
on_success = _ensure_coroutines(on_success)
|
|
148
|
+
on_backoff = _ensure_coroutines(on_backoff)
|
|
149
|
+
on_giveup = _ensure_coroutines(on_giveup)
|
|
150
|
+
on_attempt = _ensure_coroutines(on_attempt)
|
|
151
|
+
giveup = _ensure_coroutine(giveup)
|
|
152
|
+
|
|
153
|
+
assert not asyncio.iscoroutinefunction(max_tries)
|
|
154
|
+
assert not asyncio.iscoroutinefunction(jitter)
|
|
155
|
+
|
|
156
|
+
@functools.wraps(target)
|
|
157
|
+
async def retry(*args, **kwargs):
|
|
158
|
+
if not is_enabled():
|
|
159
|
+
return await target(*args, **kwargs)
|
|
160
|
+
|
|
161
|
+
max_tries_value = _maybe_call(max_tries)
|
|
162
|
+
max_time_value = _maybe_call(max_time)
|
|
163
|
+
|
|
164
|
+
tries = 0
|
|
165
|
+
start = _now()
|
|
166
|
+
wait = _init_wait_gen(wait_gen, wait_gen_kwargs)
|
|
167
|
+
while True:
|
|
168
|
+
tries += 1
|
|
169
|
+
elapsed = _elapsed(start)
|
|
170
|
+
details = {
|
|
171
|
+
"target": target,
|
|
172
|
+
"args": args,
|
|
173
|
+
"kwargs": kwargs,
|
|
174
|
+
"tries": tries,
|
|
175
|
+
"elapsed": elapsed,
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
await _call_handlers(on_attempt, **details)
|
|
179
|
+
|
|
180
|
+
try:
|
|
181
|
+
ret = await target(*args, **kwargs)
|
|
182
|
+
except exception as e:
|
|
183
|
+
giveup_result = await giveup(e)
|
|
184
|
+
max_tries_exceeded = tries == max_tries_value
|
|
185
|
+
max_time_exceeded = (
|
|
186
|
+
max_time_value is not None and elapsed >= max_time_value
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
if giveup_result or max_tries_exceeded or max_time_exceeded:
|
|
190
|
+
await _call_handlers(on_giveup, **details, exception=e)
|
|
191
|
+
if raise_on_giveup:
|
|
192
|
+
raise
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
try:
|
|
196
|
+
seconds = _next_wait(wait, e, jitter, elapsed, max_time_value)
|
|
197
|
+
except StopIteration:
|
|
198
|
+
await _call_handlers(on_giveup, **details, exception=e)
|
|
199
|
+
raise e
|
|
200
|
+
|
|
201
|
+
await _call_handlers(on_backoff, **details, wait=seconds, exception=e)
|
|
202
|
+
|
|
203
|
+
await sleep(seconds)
|
|
204
|
+
else:
|
|
205
|
+
await _call_handlers(on_success, **details)
|
|
206
|
+
return ret
|
|
207
|
+
|
|
208
|
+
return retry
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
import logging
|
|
3
|
+
import sys
|
|
4
|
+
import time as time_module
|
|
5
|
+
import traceback
|
|
6
|
+
|
|
7
|
+
_logger = logging.getLogger("backon")
|
|
8
|
+
_logger.addHandler(logging.NullHandler())
|
|
9
|
+
|
|
10
|
+
_GLOBAL_ENABLED = True
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def disable():
|
|
14
|
+
global _GLOBAL_ENABLED
|
|
15
|
+
_GLOBAL_ENABLED = False
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def enable():
|
|
19
|
+
global _GLOBAL_ENABLED
|
|
20
|
+
_GLOBAL_ENABLED = True
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def is_enabled():
|
|
24
|
+
return _GLOBAL_ENABLED
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _maybe_call(f, *args, **kwargs):
|
|
28
|
+
if callable(f):
|
|
29
|
+
try:
|
|
30
|
+
return f(*args, **kwargs)
|
|
31
|
+
except TypeError:
|
|
32
|
+
return f
|
|
33
|
+
else:
|
|
34
|
+
return f
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _init_wait_gen(wait_gen, wait_gen_kwargs):
|
|
38
|
+
kwargs = {k: _maybe_call(v) for k, v in wait_gen_kwargs.items()}
|
|
39
|
+
initialized = wait_gen(**kwargs)
|
|
40
|
+
initialized.send(None)
|
|
41
|
+
return initialized
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _next_wait(wait, send_value, jitter, elapsed, max_time):
|
|
45
|
+
value = wait.send(send_value)
|
|
46
|
+
if jitter is not None:
|
|
47
|
+
seconds = jitter(value)
|
|
48
|
+
else:
|
|
49
|
+
seconds = value
|
|
50
|
+
|
|
51
|
+
if max_time is not None:
|
|
52
|
+
seconds = min(seconds, max_time - elapsed)
|
|
53
|
+
|
|
54
|
+
return seconds
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _prepare_logger(logger):
|
|
58
|
+
if isinstance(logger, str):
|
|
59
|
+
logger = logging.getLogger(logger)
|
|
60
|
+
return logger
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _config_handlers(
|
|
64
|
+
user_handlers, *, default_handler=None, logger=None, log_level=None
|
|
65
|
+
):
|
|
66
|
+
handlers = []
|
|
67
|
+
if logger is not None:
|
|
68
|
+
assert log_level is not None
|
|
69
|
+
log_handler = functools.partial(
|
|
70
|
+
default_handler, logger=logger, log_level=log_level
|
|
71
|
+
)
|
|
72
|
+
handlers.append(log_handler)
|
|
73
|
+
|
|
74
|
+
if user_handlers is None:
|
|
75
|
+
return handlers
|
|
76
|
+
|
|
77
|
+
if hasattr(user_handlers, "__iter__"):
|
|
78
|
+
handlers += list(user_handlers)
|
|
79
|
+
else:
|
|
80
|
+
handlers.append(user_handlers)
|
|
81
|
+
|
|
82
|
+
return handlers
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _log_backoff(details, logger, log_level):
|
|
86
|
+
msg = "Backing off %s(...) for %.1fs (%s)"
|
|
87
|
+
log_args = [details["target"].__name__, details["wait"]]
|
|
88
|
+
|
|
89
|
+
exc_typ, exc, _ = sys.exc_info()
|
|
90
|
+
if exc is not None:
|
|
91
|
+
exc_fmt = traceback.format_exception_only(exc_typ, exc)[-1]
|
|
92
|
+
log_args.append(exc_fmt.rstrip("\n"))
|
|
93
|
+
else:
|
|
94
|
+
log_args.append(details["value"])
|
|
95
|
+
logger.log(log_level, msg, *log_args)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _log_giveup(details, logger, log_level):
|
|
99
|
+
msg = "Giving up %s(...) after %d tries (%s)"
|
|
100
|
+
log_args = [details["target"].__name__, details["tries"]]
|
|
101
|
+
|
|
102
|
+
exc_typ, exc, _ = sys.exc_info()
|
|
103
|
+
if exc is not None:
|
|
104
|
+
exc_fmt = traceback.format_exception_only(exc_typ, exc)[-1]
|
|
105
|
+
log_args.append(exc_fmt.rstrip("\n"))
|
|
106
|
+
else:
|
|
107
|
+
log_args.append(details["value"])
|
|
108
|
+
|
|
109
|
+
logger.log(log_level, msg, *log_args)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _now():
|
|
113
|
+
return time_module.monotonic()
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _elapsed(start):
|
|
117
|
+
return _now() - start
|