wait.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. # Copyright 2016–2021 Julien Danjou
  2. # Copyright 2016 Joshua Harlow
  3. # Copyright 2013-2014 Ray Holder
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import abc
  17. import random
  18. import typing
  19. from tenacity import _utils
  20. if typing.TYPE_CHECKING:
  21. from tenacity import RetryCallState
  22. class wait_base(abc.ABC):
  23. """Abstract base class for wait strategies."""
  24. @abc.abstractmethod
  25. def __call__(self, retry_state: "RetryCallState") -> float:
  26. pass
  27. def __add__(self, other: "wait_base") -> "wait_combine":
  28. return wait_combine(self, other)
  29. def __radd__(self, other: "wait_base") -> typing.Union["wait_combine", "wait_base"]:
  30. # make it possible to use multiple waits with the built-in sum function
  31. if other == 0: # type: ignore[comparison-overlap]
  32. return self
  33. return self.__add__(other)
  34. WaitBaseT = typing.Union[
  35. wait_base, typing.Callable[["RetryCallState"], typing.Union[float, int]]
  36. ]
  37. class wait_fixed(wait_base):
  38. """Wait strategy that waits a fixed amount of time between each retry."""
  39. def __init__(self, wait: _utils.time_unit_type) -> None:
  40. self.wait_fixed = _utils.to_seconds(wait)
  41. def __call__(self, retry_state: "RetryCallState") -> float:
  42. return self.wait_fixed
  43. class wait_none(wait_fixed):
  44. """Wait strategy that doesn't wait at all before retrying."""
  45. def __init__(self) -> None:
  46. super().__init__(0)
  47. class wait_random(wait_base):
  48. """Wait strategy that waits a random amount of time between min/max."""
  49. def __init__(
  50. self, min: _utils.time_unit_type = 0, max: _utils.time_unit_type = 1
  51. ) -> None: # noqa
  52. self.wait_random_min = _utils.to_seconds(min)
  53. self.wait_random_max = _utils.to_seconds(max)
  54. def __call__(self, retry_state: "RetryCallState") -> float:
  55. return self.wait_random_min + (
  56. random.random() * (self.wait_random_max - self.wait_random_min)
  57. )
  58. class wait_combine(wait_base):
  59. """Combine several waiting strategies."""
  60. def __init__(self, *strategies: wait_base) -> None:
  61. self.wait_funcs = strategies
  62. def __call__(self, retry_state: "RetryCallState") -> float:
  63. return sum(x(retry_state=retry_state) for x in self.wait_funcs)
  64. class wait_chain(wait_base):
  65. """Chain two or more waiting strategies.
  66. If all strategies are exhausted, the very last strategy is used
  67. thereafter.
  68. For example::
  69. @retry(wait=wait_chain(*[wait_fixed(1) for i in range(3)] +
  70. [wait_fixed(2) for j in range(5)] +
  71. [wait_fixed(5) for k in range(4)))
  72. def wait_chained():
  73. print("Wait 1s for 3 attempts, 2s for 5 attempts and 5s
  74. thereafter.")
  75. """
  76. def __init__(self, *strategies: wait_base) -> None:
  77. self.strategies = strategies
  78. def __call__(self, retry_state: "RetryCallState") -> float:
  79. wait_func_no = min(max(retry_state.attempt_number, 1), len(self.strategies))
  80. wait_func = self.strategies[wait_func_no - 1]
  81. return wait_func(retry_state=retry_state)
  82. class wait_incrementing(wait_base):
  83. """Wait an incremental amount of time after each attempt.
  84. Starting at a starting value and incrementing by a value for each attempt
  85. (and restricting the upper limit to some maximum value).
  86. """
  87. def __init__(
  88. self,
  89. start: _utils.time_unit_type = 0,
  90. increment: _utils.time_unit_type = 100,
  91. max: _utils.time_unit_type = _utils.MAX_WAIT, # noqa
  92. ) -> None:
  93. self.start = _utils.to_seconds(start)
  94. self.increment = _utils.to_seconds(increment)
  95. self.max = _utils.to_seconds(max)
  96. def __call__(self, retry_state: "RetryCallState") -> float:
  97. result = self.start + (self.increment * (retry_state.attempt_number - 1))
  98. return max(0, min(result, self.max))
  99. class wait_exponential(wait_base):
  100. """Wait strategy that applies exponential backoff.
  101. It allows for a customized multiplier and an ability to restrict the
  102. upper and lower limits to some maximum and minimum value.
  103. The intervals are fixed (i.e. there is no jitter), so this strategy is
  104. suitable for balancing retries against latency when a required resource is
  105. unavailable for an unknown duration, but *not* suitable for resolving
  106. contention between multiple processes for a shared resource. Use
  107. wait_random_exponential for the latter case.
  108. """
  109. def __init__(
  110. self,
  111. multiplier: typing.Union[int, float] = 1,
  112. max: _utils.time_unit_type = _utils.MAX_WAIT, # noqa
  113. exp_base: typing.Union[int, float] = 2,
  114. min: _utils.time_unit_type = 0, # noqa
  115. ) -> None:
  116. self.multiplier = multiplier
  117. self.min = _utils.to_seconds(min)
  118. self.max = _utils.to_seconds(max)
  119. self.exp_base = exp_base
  120. def __call__(self, retry_state: "RetryCallState") -> float:
  121. try:
  122. exp = self.exp_base ** (retry_state.attempt_number - 1)
  123. result = self.multiplier * exp
  124. except OverflowError:
  125. return self.max
  126. return max(max(0, self.min), min(result, self.max))
  127. class wait_random_exponential(wait_exponential):
  128. """Random wait with exponentially widening window.
  129. An exponential backoff strategy used to mediate contention between multiple
  130. uncoordinated processes for a shared resource in distributed systems. This
  131. is the sense in which "exponential backoff" is meant in e.g. Ethernet
  132. networking, and corresponds to the "Full Jitter" algorithm described in
  133. this blog post:
  134. https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
  135. Each retry occurs at a random time in a geometrically expanding interval.
  136. It allows for a custom multiplier and an ability to restrict the upper
  137. limit of the random interval to some maximum value.
  138. Example::
  139. wait_random_exponential(multiplier=0.5, # initial window 0.5s
  140. max=60) # max 60s timeout
  141. When waiting for an unavailable resource to become available again, as
  142. opposed to trying to resolve contention for a shared resource, the
  143. wait_exponential strategy (which uses a fixed interval) may be preferable.
  144. """
  145. def __call__(self, retry_state: "RetryCallState") -> float:
  146. high = super().__call__(retry_state=retry_state)
  147. return random.uniform(self.min, high)
  148. class wait_exponential_jitter(wait_base):
  149. """Wait strategy that applies exponential backoff and jitter.
  150. It allows for a customized initial wait, maximum wait and jitter.
  151. This implements the strategy described here:
  152. https://cloud.google.com/storage/docs/retry-strategy
  153. The wait time is min(initial * 2**n + random.uniform(0, jitter), maximum)
  154. where n is the retry count.
  155. """
  156. def __init__(
  157. self,
  158. initial: float = 1,
  159. max: float = _utils.MAX_WAIT, # noqa
  160. exp_base: float = 2,
  161. jitter: float = 1,
  162. ) -> None:
  163. self.initial = initial
  164. self.max = max
  165. self.exp_base = exp_base
  166. self.jitter = jitter
  167. def __call__(self, retry_state: "RetryCallState") -> float:
  168. jitter = random.uniform(0, self.jitter)
  169. try:
  170. exp = self.exp_base ** (retry_state.attempt_number - 1)
  171. result = self.initial * exp + jitter
  172. except OverflowError:
  173. result = self.max
  174. return max(0, min(result, self.max))