wait.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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 pip._vendor.tenacity import _utils
  20. if typing.TYPE_CHECKING:
  21. from pip._vendor.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[wait_base, typing.Callable[["RetryCallState"], typing.Union[float, int]]]
  35. class wait_fixed(wait_base):
  36. """Wait strategy that waits a fixed amount of time between each retry."""
  37. def __init__(self, wait: _utils.time_unit_type) -> None:
  38. self.wait_fixed = _utils.to_seconds(wait)
  39. def __call__(self, retry_state: "RetryCallState") -> float:
  40. return self.wait_fixed
  41. class wait_none(wait_fixed):
  42. """Wait strategy that doesn't wait at all before retrying."""
  43. def __init__(self) -> None:
  44. super().__init__(0)
  45. class wait_random(wait_base):
  46. """Wait strategy that waits a random amount of time between min/max."""
  47. def __init__(self, min: _utils.time_unit_type = 0, max: _utils.time_unit_type = 1) -> None: # noqa
  48. self.wait_random_min = _utils.to_seconds(min)
  49. self.wait_random_max = _utils.to_seconds(max)
  50. def __call__(self, retry_state: "RetryCallState") -> float:
  51. return self.wait_random_min + (random.random() * (self.wait_random_max - self.wait_random_min))
  52. class wait_combine(wait_base):
  53. """Combine several waiting strategies."""
  54. def __init__(self, *strategies: wait_base) -> None:
  55. self.wait_funcs = strategies
  56. def __call__(self, retry_state: "RetryCallState") -> float:
  57. return sum(x(retry_state=retry_state) for x in self.wait_funcs)
  58. class wait_chain(wait_base):
  59. """Chain two or more waiting strategies.
  60. If all strategies are exhausted, the very last strategy is used
  61. thereafter.
  62. For example::
  63. @retry(wait=wait_chain(*[wait_fixed(1) for i in range(3)] +
  64. [wait_fixed(2) for j in range(5)] +
  65. [wait_fixed(5) for k in range(4)))
  66. def wait_chained():
  67. print("Wait 1s for 3 attempts, 2s for 5 attempts and 5s
  68. thereafter.")
  69. """
  70. def __init__(self, *strategies: wait_base) -> None:
  71. self.strategies = strategies
  72. def __call__(self, retry_state: "RetryCallState") -> float:
  73. wait_func_no = min(max(retry_state.attempt_number, 1), len(self.strategies))
  74. wait_func = self.strategies[wait_func_no - 1]
  75. return wait_func(retry_state=retry_state)
  76. class wait_incrementing(wait_base):
  77. """Wait an incremental amount of time after each attempt.
  78. Starting at a starting value and incrementing by a value for each attempt
  79. (and restricting the upper limit to some maximum value).
  80. """
  81. def __init__(
  82. self,
  83. start: _utils.time_unit_type = 0,
  84. increment: _utils.time_unit_type = 100,
  85. max: _utils.time_unit_type = _utils.MAX_WAIT, # noqa
  86. ) -> None:
  87. self.start = _utils.to_seconds(start)
  88. self.increment = _utils.to_seconds(increment)
  89. self.max = _utils.to_seconds(max)
  90. def __call__(self, retry_state: "RetryCallState") -> float:
  91. result = self.start + (self.increment * (retry_state.attempt_number - 1))
  92. return max(0, min(result, self.max))
  93. class wait_exponential(wait_base):
  94. """Wait strategy that applies exponential backoff.
  95. It allows for a customized multiplier and an ability to restrict the
  96. upper and lower limits to some maximum and minimum value.
  97. The intervals are fixed (i.e. there is no jitter), so this strategy is
  98. suitable for balancing retries against latency when a required resource is
  99. unavailable for an unknown duration, but *not* suitable for resolving
  100. contention between multiple processes for a shared resource. Use
  101. wait_random_exponential for the latter case.
  102. """
  103. def __init__(
  104. self,
  105. multiplier: typing.Union[int, float] = 1,
  106. max: _utils.time_unit_type = _utils.MAX_WAIT, # noqa
  107. exp_base: typing.Union[int, float] = 2,
  108. min: _utils.time_unit_type = 0, # noqa
  109. ) -> None:
  110. self.multiplier = multiplier
  111. self.min = _utils.to_seconds(min)
  112. self.max = _utils.to_seconds(max)
  113. self.exp_base = exp_base
  114. def __call__(self, retry_state: "RetryCallState") -> float:
  115. try:
  116. exp = self.exp_base ** (retry_state.attempt_number - 1)
  117. result = self.multiplier * exp
  118. except OverflowError:
  119. return self.max
  120. return max(max(0, self.min), min(result, self.max))
  121. class wait_random_exponential(wait_exponential):
  122. """Random wait with exponentially widening window.
  123. An exponential backoff strategy used to mediate contention between multiple
  124. uncoordinated processes for a shared resource in distributed systems. This
  125. is the sense in which "exponential backoff" is meant in e.g. Ethernet
  126. networking, and corresponds to the "Full Jitter" algorithm described in
  127. this blog post:
  128. https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
  129. Each retry occurs at a random time in a geometrically expanding interval.
  130. It allows for a custom multiplier and an ability to restrict the upper
  131. limit of the random interval to some maximum value.
  132. Example::
  133. wait_random_exponential(multiplier=0.5, # initial window 0.5s
  134. max=60) # max 60s timeout
  135. When waiting for an unavailable resource to become available again, as
  136. opposed to trying to resolve contention for a shared resource, the
  137. wait_exponential strategy (which uses a fixed interval) may be preferable.
  138. """
  139. def __call__(self, retry_state: "RetryCallState") -> float:
  140. high = super().__call__(retry_state=retry_state)
  141. return random.uniform(0, high)
  142. class wait_exponential_jitter(wait_base):
  143. """Wait strategy that applies exponential backoff and jitter.
  144. It allows for a customized initial wait, maximum wait and jitter.
  145. This implements the strategy described here:
  146. https://cloud.google.com/storage/docs/retry-strategy
  147. The wait time is min(initial * 2**n + random.uniform(0, jitter), maximum)
  148. where n is the retry count.
  149. """
  150. def __init__(
  151. self,
  152. initial: float = 1,
  153. max: float = _utils.MAX_WAIT, # noqa
  154. exp_base: float = 2,
  155. jitter: float = 1,
  156. ) -> None:
  157. self.initial = initial
  158. self.max = max
  159. self.exp_base = exp_base
  160. self.jitter = jitter
  161. def __call__(self, retry_state: "RetryCallState") -> float:
  162. jitter = random.uniform(0, self.jitter)
  163. try:
  164. exp = self.exp_base ** (retry_state.attempt_number - 1)
  165. result = self.initial * exp + jitter
  166. except OverflowError:
  167. result = self.max
  168. return max(0, min(result, self.max))