Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/redis/retry.py: 30%
23 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 07:16 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 07:16 +0000
1import socket
2from time import sleep
4from redis.exceptions import ConnectionError, TimeoutError
7class Retry:
8 """Retry a specific number of times after a failure"""
10 def __init__(
11 self,
12 backoff,
13 retries,
14 supported_errors=(ConnectionError, TimeoutError, socket.timeout),
15 ):
16 """
17 Initialize a `Retry` object with a `Backoff` object
18 that retries a maximum of `retries` times.
19 `retries` can be negative to retry forever.
20 You can specify the types of supported errors which trigger
21 a retry with the `supported_errors` parameter.
22 """
23 self._backoff = backoff
24 self._retries = retries
25 self._supported_errors = supported_errors
27 def update_supported_errors(self, specified_errors: list):
28 """
29 Updates the supported errors with the specified error types
30 """
31 self._supported_errors = tuple(
32 set(self._supported_errors + tuple(specified_errors))
33 )
35 def call_with_retry(self, do, fail):
36 """
37 Execute an operation that might fail and returns its result, or
38 raise the exception that was thrown depending on the `Backoff` object.
39 `do`: the operation to call. Expects no argument.
40 `fail`: the failure handler, expects the last error that was thrown
41 """
42 self._backoff.reset()
43 failures = 0
44 while True:
45 try:
46 return do()
47 except self._supported_errors as error:
48 failures += 1
49 fail(error)
50 if self._retries >= 0 and failures > self._retries:
51 raise error
52 backoff = self._backoff.compute(failures)
53 if backoff > 0:
54 sleep(backoff)