wait.py 6.5 KB

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