forked from lxl0928/retrying-async
-
Notifications
You must be signed in to change notification settings - Fork 0
/
retrying_async.py
179 lines (141 loc) · 5.45 KB
/
retrying_async.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# coding: utf-8
import copy
import inspect
import logging
import asyncio
import random
from functools import wraps
import async_timeout
propagate = ...
forever = ...
__version__ = '2.1.0'
logger = logging.getLogger(__name__)
class RetryError(Exception):
pass
class ConditionError(Exception):
pass
def unpartial(fn):
while hasattr(fn, 'func'):
fn = fn.func
return fn
def is_exception(obj):
return (
isinstance(obj, Exception) or
(inspect.isclass(obj) and (issubclass(obj, Exception)))
)
@asyncio.coroutine
def callback(attempt, exc, args, kwargs, delay=0.5, *, loop):
yield from asyncio.sleep(delay)
return retry
def retry(
*, fn=None, attempts=3, delay=0.5, max_delay=None, backoff=1, jitter=0, timeout=30, immutable=False,
callback=callback, fallback=RetryError, retry_exceptions=(Exception,),
fatal_exceptions=(asyncio.CancelledError,)
):
"""
:param fn: 被装饰的函数
:param attempts: 设置最大重试次数
:param delay: 添加每次方法执行之间的等待时间
:param max_delay: the maximum value of delay. default: None (no limit).
:param backoff: multiplier applied to delay between attempts. default: 1 (no backoff).
:param jitter: extra seconds added to delay between attempts. default: 0.
fixed if a number, random if a range tuple (min, max)
:param timeout:
:param immutable:
:param callback:
:param fallback: a callable function or a value to return when all attempts are tried.
:param retry_exceptions:
:param fatal_exceptions:
:return:
"""
def wrapper(fn):
@wraps(fn)
@asyncio.coroutine
def wrapped(*fn_args, **fn_kwargs):
_loop = asyncio.get_event_loop()
if (
timeout is not None and
asyncio.TimeoutError not in retry_exceptions
):
_retry_exceptions = (asyncio.TimeoutError,) + retry_exceptions
else:
_retry_exceptions = retry_exceptions
attempt = 1
_delay = delay
while True:
if immutable:
_fn_args = copy.deepcopy(fn_args)
_fn_kwargs = copy.deepcopy(fn_kwargs)
else:
_fn_args, _fn_kwargs = fn_args, fn_kwargs
try:
ret = fn(*_fn_args, **_fn_kwargs)
if timeout is None:
if asyncio.iscoroutinefunction(unpartial(fn)):
ret = yield from ret
else:
if not asyncio.iscoroutinefunction(unpartial(fn)):
raise ConditionError(
'Can\'t set timeout for non coroutinefunction',
)
with async_timeout.timeout(timeout):
ret = yield from ret
return ret
except ConditionError:
raise
except fatal_exceptions:
raise
except _retry_exceptions as exc:
_attempts = 'infinity' if attempts is forever else attempts
context = {
'fn': fn,
'attempt': attempt,
'attempts': _attempts,
}
if (
_loop.get_debug() or
(attempts is not forever and attempt == attempts)
):
logger.warning(
exc.__class__.__name__ + ' -> Attempts (%(attempt)d) are over for %(fn)r', # noqa
context,
exc_info=exc,
)
if fallback is propagate:
raise exc
if is_exception(fallback):
raise fallback from exc
if callable(fallback):
ret = fallback(fn_args, fn_kwargs)
if asyncio.iscoroutinefunction(unpartial(fallback)): # noqa
ret = yield from ret
else:
ret = fallback
return ret
logger.debug(
exc.__class__.__name__ + ' -> Tried attempt #%(attempt)d from total %(attempts)s for %(fn)r',
# noqa
context,
exc_info=exc,
)
ret = callback(
attempt, exc, fn_args, fn_kwargs, delay=_delay, loop=_loop,
)
_delay *= backoff
if isinstance(jitter, tuple):
_delay += random.uniform(*jitter)
else:
_delay += jitter
if max_delay is not None:
_delay = min(_delay, max_delay)
attempt += 1
if asyncio.iscoroutinefunction(unpartial(callback)):
ret = yield from ret
if ret is not retry:
return ret
return wrapped
if fn is None:
return wrapper
if callable(fn):
return wrapper(fn)
raise NotImplementedError