Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/retry.py: 49%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

69 statements  

1import abc 

2import errno 

3import socket 

4from time import sleep 

5from typing import ( 

6 TYPE_CHECKING, 

7 Any, 

8 Callable, 

9 Generic, 

10 Iterable, 

11 Tuple, 

12 Type, 

13 TypeVar, 

14 Union, 

15) 

16 

17from redis.exceptions import ConnectionError, TimeoutError 

18 

19T = TypeVar("T") 

20E = TypeVar("E", bound=Exception, covariant=True) 

21 

22if TYPE_CHECKING: 

23 from redis.backoff import AbstractBackoff 

24 

25 

26class AbstractRetry(Generic[E], abc.ABC): 

27 """Retry a specific number of times after a failure""" 

28 

29 _supported_errors: Tuple[Type[E], ...] 

30 

31 def __init__( 

32 self, 

33 backoff: "AbstractBackoff", 

34 retries: int, 

35 supported_errors: Tuple[Type[E], ...], 

36 is_retryable: Callable[[E], bool] | None = None, 

37 ): 

38 """ 

39 Initialize a `Retry` object with a `Backoff` object 

40 that retries a maximum of `retries` times. 

41 `retries` can be negative to retry forever. 

42 You can specify the types of supported errors which trigger 

43 a retry with the `supported_errors` parameter. 

44 You can pass an optional ``is_retryable`` checker to refine the 

45 classification: an error is retried only if its type is one of the 

46 ``supported_errors`` AND the checker returns ``True`` for it. When no 

47 checker is set, the behavior is unchanged. 

48 """ 

49 self._backoff = backoff 

50 self._retries = retries 

51 self._supported_errors = supported_errors 

52 self._is_retryable = is_retryable 

53 

54 @property 

55 def is_retryable(self) -> Callable[[E], bool] | None: 

56 """Optional checker applied in addition to ``supported_errors``.""" 

57 return self._is_retryable 

58 

59 @is_retryable.setter 

60 def is_retryable(self, value: Callable[[E], bool] | None) -> None: 

61 self._is_retryable = value 

62 

63 @abc.abstractmethod 

64 def __eq__(self, other: Any) -> bool: 

65 return NotImplemented 

66 

67 def __hash__(self) -> int: 

68 # A callable checker is not necessarily hashable, and equality already 

69 # allows unequal policies to share a hash. Keep the policy fields that 

70 # defined the hash before the checker existed. 

71 return hash((self._backoff, self._retries, frozenset(self._supported_errors))) 

72 

73 def update_supported_errors(self, specified_errors: Iterable[Type[E]]) -> None: 

74 """ 

75 Updates the supported errors with the specified error types 

76 """ 

77 self._supported_errors = tuple( 

78 set(self._supported_errors + tuple(specified_errors)) 

79 ) 

80 

81 def get_retries(self) -> int: 

82 """ 

83 Get the number of retries. 

84 """ 

85 return self._retries 

86 

87 def update_retries(self, value: int) -> None: 

88 """ 

89 Set the number of retries. 

90 """ 

91 self._retries = value 

92 

93 

94class Retry(AbstractRetry[Exception]): 

95 __hash__ = AbstractRetry.__hash__ 

96 

97 def __init__( 

98 self, 

99 backoff: "AbstractBackoff", 

100 retries: int, 

101 supported_errors: Tuple[Type[Exception], ...] = ( 

102 ConnectionError, 

103 TimeoutError, 

104 socket.timeout, 

105 ), 

106 is_retryable: Callable[[Exception], bool] | None = None, 

107 ): 

108 super().__init__(backoff, retries, supported_errors, is_retryable) 

109 

110 def __eq__(self, other: Any) -> bool: 

111 if not isinstance(other, Retry): 

112 return NotImplemented 

113 

114 return ( 

115 self._backoff == other._backoff 

116 and self._retries == other._retries 

117 and set(self._supported_errors) == set(other._supported_errors) 

118 and self._is_retryable == other._is_retryable 

119 ) 

120 

121 def call_with_retry( 

122 self, 

123 do: Callable[[], T], 

124 fail: Union[Callable[[Exception], Any], Callable[[Exception, int], Any]], 

125 is_retryable: Callable[[Exception], bool] | None = None, 

126 with_failure_count: bool = False, 

127 ) -> T: 

128 """ 

129 Execute an operation that might fail and returns its result, or 

130 raise the exception that was thrown depending on the `Backoff` object. 

131 `do`: the operation to call. Expects no argument. 

132 `fail`: the failure handler, expects the last error that was thrown 

133 ``is_retryable``: optional function to determine if an error is retryable. 

134 It is composed with the checker set on this object (if any) using AND: 

135 an error is retried only if both checkers return True. 

136 ``with_failure_count``: if True, the failure count is passed to the failure handler 

137 """ 

138 self._backoff.reset() 

139 failures = 0 

140 while True: 

141 try: 

142 return do() 

143 except self._supported_errors as error: 

144 if self._is_retryable is not None and not self._is_retryable(error): 

145 # Run the failure handler before raising so connection-scoped 

146 # cleanup (for example a pipeline's WATCH state) still happens. 

147 if with_failure_count: 

148 fail(error, failures + 1) 

149 else: 

150 fail(error) 

151 raise 

152 if is_retryable is not None and not is_retryable(error): 

153 raise 

154 failures += 1 

155 

156 if with_failure_count: 

157 fail(error, failures) 

158 else: 

159 fail(error) 

160 

161 if self._retries >= 0 and failures > self._retries: 

162 raise error 

163 backoff = self._backoff.compute(failures) 

164 if backoff > 0: 

165 sleep(backoff) 

166 

167 

168# OS-level errno values for which reconnecting can never succeed, so there is 

169# no point in spending the retry/backoff budget on them. 

170_UNRETRYABLE_CONNECT_ERRNOS = frozenset({errno.ENOENT}) 

171 

172 

173def is_retryable_connect_error(error: Exception) -> bool: 

174 """``is_retryable`` checker that fails fast on unrecoverable connect errors. 

175 

176 Returns ``False`` only when ``error`` was raised from an ``OSError`` whose 

177 ``errno`` is in a conservative set of definitively unrecoverable socket 

178 errors (currently only ``ENOENT``: the socket path does not exist). Every 

179 other error, including transient failures such as ``ECONNREFUSED`` while a 

180 server is still starting, is left to the normal retry policy. 

181 

182 Use it as the optional checker on a :class:`Retry` object to stop a missing 

183 Unix socket path from consuming the full backoff budget:: 

184 

185 retry = Retry( 

186 NoBackoff(), 3, is_retryable=is_retryable_connect_error 

187 ) 

188 """ 

189 cause = error.__cause__ 

190 return not ( 

191 isinstance(cause, OSError) and cause.errno in _UNRETRYABLE_CONNECT_ERRNOS 

192 )