Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

retry.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. from __future__ import annotations
  2. import email
  3. import logging
  4. import random
  5. import re
  6. import time
  7. import typing
  8. from itertools import takewhile
  9. from types import TracebackType
  10. from ..exceptions import (
  11. ConnectTimeoutError,
  12. InvalidHeader,
  13. MaxRetryError,
  14. ProtocolError,
  15. ProxyError,
  16. ReadTimeoutError,
  17. ResponseError,
  18. )
  19. from .util import reraise
  20. if typing.TYPE_CHECKING:
  21. from ..connectionpool import ConnectionPool
  22. from ..response import BaseHTTPResponse
  23. log = logging.getLogger(__name__)
  24. # Data structure for representing the metadata of requests that result in a retry.
  25. class RequestHistory(typing.NamedTuple):
  26. method: str | None
  27. url: str | None
  28. error: Exception | None
  29. status: int | None
  30. redirect_location: str | None
  31. class Retry:
  32. """Retry configuration.
  33. Each retry attempt will create a new Retry object with updated values, so
  34. they can be safely reused.
  35. Retries can be defined as a default for a pool:
  36. .. code-block:: python
  37. retries = Retry(connect=5, read=2, redirect=5)
  38. http = PoolManager(retries=retries)
  39. response = http.request("GET", "https://example.com/")
  40. Or per-request (which overrides the default for the pool):
  41. .. code-block:: python
  42. response = http.request("GET", "https://example.com/", retries=Retry(10))
  43. Retries can be disabled by passing ``False``:
  44. .. code-block:: python
  45. response = http.request("GET", "https://example.com/", retries=False)
  46. Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless
  47. retries are disabled, in which case the causing exception will be raised.
  48. :param int total:
  49. Total number of retries to allow. Takes precedence over other counts.
  50. Set to ``None`` to remove this constraint and fall back on other
  51. counts.
  52. Set to ``0`` to fail on the first retry.
  53. Set to ``False`` to disable and imply ``raise_on_redirect=False``.
  54. :param int connect:
  55. How many connection-related errors to retry on.
  56. These are errors raised before the request is sent to the remote server,
  57. which we assume has not triggered the server to process the request.
  58. Set to ``0`` to fail on the first retry of this type.
  59. :param int read:
  60. How many times to retry on read errors.
  61. These errors are raised after the request was sent to the server, so the
  62. request may have side-effects.
  63. Set to ``0`` to fail on the first retry of this type.
  64. :param int redirect:
  65. How many redirects to perform. Limit this to avoid infinite redirect
  66. loops.
  67. A redirect is a HTTP response with a status code 301, 302, 303, 307 or
  68. 308.
  69. Set to ``0`` to fail on the first retry of this type.
  70. Set to ``False`` to disable and imply ``raise_on_redirect=False``.
  71. :param int status:
  72. How many times to retry on bad status codes.
  73. These are retries made on responses, where status code matches
  74. ``status_forcelist``.
  75. Set to ``0`` to fail on the first retry of this type.
  76. :param int other:
  77. How many times to retry on other errors.
  78. Other errors are errors that are not connect, read, redirect or status errors.
  79. These errors might be raised after the request was sent to the server, so the
  80. request might have side-effects.
  81. Set to ``0`` to fail on the first retry of this type.
  82. If ``total`` is not set, it's a good idea to set this to 0 to account
  83. for unexpected edge cases and avoid infinite retry loops.
  84. :param Collection allowed_methods:
  85. Set of uppercased HTTP method verbs that we should retry on.
  86. By default, we only retry on methods which are considered to be
  87. idempotent (multiple requests with the same parameters end with the
  88. same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`.
  89. Set to a ``None`` value to retry on any verb.
  90. :param Collection status_forcelist:
  91. A set of integer HTTP status codes that we should force a retry on.
  92. A retry is initiated if the request method is in ``allowed_methods``
  93. and the response status code is in ``status_forcelist``.
  94. By default, this is disabled with ``None``.
  95. :param float backoff_factor:
  96. A backoff factor to apply between attempts after the second try
  97. (most errors are resolved immediately by a second try without a
  98. delay). urllib3 will sleep for::
  99. {backoff factor} * (2 ** ({number of previous retries}))
  100. seconds. If `backoff_jitter` is non-zero, this sleep is extended by::
  101. random.uniform(0, {backoff jitter})
  102. seconds. For example, if the backoff_factor is 0.1, then :func:`Retry.sleep` will
  103. sleep for [0.0s, 0.2s, 0.4s, 0.8s, ...] between retries. No backoff will ever
  104. be longer than `backoff_max`.
  105. By default, backoff is disabled (factor set to 0).
  106. :param bool raise_on_redirect: Whether, if the number of redirects is
  107. exhausted, to raise a MaxRetryError, or to return a response with a
  108. response code in the 3xx range.
  109. :param bool raise_on_status: Similar meaning to ``raise_on_redirect``:
  110. whether we should raise an exception, or return a response,
  111. if status falls in ``status_forcelist`` range and retries have
  112. been exhausted.
  113. :param tuple history: The history of the request encountered during
  114. each call to :meth:`~Retry.increment`. The list is in the order
  115. the requests occurred. Each list item is of class :class:`RequestHistory`.
  116. :param bool respect_retry_after_header:
  117. Whether to respect Retry-After header on status codes defined as
  118. :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.
  119. :param Collection remove_headers_on_redirect:
  120. Sequence of headers to remove from the request when a response
  121. indicating a redirect is returned before firing off the redirected
  122. request.
  123. """
  124. #: Default methods to be used for ``allowed_methods``
  125. DEFAULT_ALLOWED_METHODS = frozenset(
  126. ["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"]
  127. )
  128. #: Default status codes to be used for ``status_forcelist``
  129. RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])
  130. #: Default headers to be used for ``remove_headers_on_redirect``
  131. DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset(["Authorization"])
  132. #: Default maximum backoff time.
  133. DEFAULT_BACKOFF_MAX = 120
  134. # Backward compatibility; assigned outside of the class.
  135. DEFAULT: typing.ClassVar[Retry]
  136. def __init__(
  137. self,
  138. total: bool | int | None = 10,
  139. connect: int | None = None,
  140. read: int | None = None,
  141. redirect: bool | int | None = None,
  142. status: int | None = None,
  143. other: int | None = None,
  144. allowed_methods: typing.Collection[str] | None = DEFAULT_ALLOWED_METHODS,
  145. status_forcelist: typing.Collection[int] | None = None,
  146. backoff_factor: float = 0,
  147. backoff_max: float = DEFAULT_BACKOFF_MAX,
  148. raise_on_redirect: bool = True,
  149. raise_on_status: bool = True,
  150. history: tuple[RequestHistory, ...] | None = None,
  151. respect_retry_after_header: bool = True,
  152. remove_headers_on_redirect: typing.Collection[
  153. str
  154. ] = DEFAULT_REMOVE_HEADERS_ON_REDIRECT,
  155. backoff_jitter: float = 0.0,
  156. ) -> None:
  157. self.total = total
  158. self.connect = connect
  159. self.read = read
  160. self.status = status
  161. self.other = other
  162. if redirect is False or total is False:
  163. redirect = 0
  164. raise_on_redirect = False
  165. self.redirect = redirect
  166. self.status_forcelist = status_forcelist or set()
  167. self.allowed_methods = allowed_methods
  168. self.backoff_factor = backoff_factor
  169. self.backoff_max = backoff_max
  170. self.raise_on_redirect = raise_on_redirect
  171. self.raise_on_status = raise_on_status
  172. self.history = history or ()
  173. self.respect_retry_after_header = respect_retry_after_header
  174. self.remove_headers_on_redirect = frozenset(
  175. h.lower() for h in remove_headers_on_redirect
  176. )
  177. self.backoff_jitter = backoff_jitter
  178. def new(self, **kw: typing.Any) -> Retry:
  179. params = dict(
  180. total=self.total,
  181. connect=self.connect,
  182. read=self.read,
  183. redirect=self.redirect,
  184. status=self.status,
  185. other=self.other,
  186. allowed_methods=self.allowed_methods,
  187. status_forcelist=self.status_forcelist,
  188. backoff_factor=self.backoff_factor,
  189. backoff_max=self.backoff_max,
  190. raise_on_redirect=self.raise_on_redirect,
  191. raise_on_status=self.raise_on_status,
  192. history=self.history,
  193. remove_headers_on_redirect=self.remove_headers_on_redirect,
  194. respect_retry_after_header=self.respect_retry_after_header,
  195. backoff_jitter=self.backoff_jitter,
  196. )
  197. params.update(kw)
  198. return type(self)(**params) # type: ignore[arg-type]
  199. @classmethod
  200. def from_int(
  201. cls,
  202. retries: Retry | bool | int | None,
  203. redirect: bool | int | None = True,
  204. default: Retry | bool | int | None = None,
  205. ) -> Retry:
  206. """Backwards-compatibility for the old retries format."""
  207. if retries is None:
  208. retries = default if default is not None else cls.DEFAULT
  209. if isinstance(retries, Retry):
  210. return retries
  211. redirect = bool(redirect) and None
  212. new_retries = cls(retries, redirect=redirect)
  213. log.debug("Converted retries value: %r -> %r", retries, new_retries)
  214. return new_retries
  215. def get_backoff_time(self) -> float:
  216. """Formula for computing the current backoff
  217. :rtype: float
  218. """
  219. # We want to consider only the last consecutive errors sequence (Ignore redirects).
  220. consecutive_errors_len = len(
  221. list(
  222. takewhile(lambda x: x.redirect_location is None, reversed(self.history))
  223. )
  224. )
  225. if consecutive_errors_len <= 1:
  226. return 0
  227. backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))
  228. if self.backoff_jitter != 0.0:
  229. backoff_value += random.random() * self.backoff_jitter
  230. return float(max(0, min(self.backoff_max, backoff_value)))
  231. def parse_retry_after(self, retry_after: str) -> float:
  232. seconds: float
  233. # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4
  234. if re.match(r"^\s*[0-9]+\s*$", retry_after):
  235. seconds = int(retry_after)
  236. else:
  237. retry_date_tuple = email.utils.parsedate_tz(retry_after)
  238. if retry_date_tuple is None:
  239. raise InvalidHeader(f"Invalid Retry-After header: {retry_after}")
  240. retry_date = email.utils.mktime_tz(retry_date_tuple)
  241. seconds = retry_date - time.time()
  242. seconds = max(seconds, 0)
  243. return seconds
  244. def get_retry_after(self, response: BaseHTTPResponse) -> float | None:
  245. """Get the value of Retry-After in seconds."""
  246. retry_after = response.headers.get("Retry-After")
  247. if retry_after is None:
  248. return None
  249. return self.parse_retry_after(retry_after)
  250. def sleep_for_retry(self, response: BaseHTTPResponse) -> bool:
  251. retry_after = self.get_retry_after(response)
  252. if retry_after:
  253. time.sleep(retry_after)
  254. return True
  255. return False
  256. def _sleep_backoff(self) -> None:
  257. backoff = self.get_backoff_time()
  258. if backoff <= 0:
  259. return
  260. time.sleep(backoff)
  261. def sleep(self, response: BaseHTTPResponse | None = None) -> None:
  262. """Sleep between retry attempts.
  263. This method will respect a server's ``Retry-After`` response header
  264. and sleep the duration of the time requested. If that is not present, it
  265. will use an exponential backoff. By default, the backoff factor is 0 and
  266. this method will return immediately.
  267. """
  268. if self.respect_retry_after_header and response:
  269. slept = self.sleep_for_retry(response)
  270. if slept:
  271. return
  272. self._sleep_backoff()
  273. def _is_connection_error(self, err: Exception) -> bool:
  274. """Errors when we're fairly sure that the server did not receive the
  275. request, so it should be safe to retry.
  276. """
  277. if isinstance(err, ProxyError):
  278. err = err.original_error
  279. return isinstance(err, ConnectTimeoutError)
  280. def _is_read_error(self, err: Exception) -> bool:
  281. """Errors that occur after the request has been started, so we should
  282. assume that the server began processing it.
  283. """
  284. return isinstance(err, (ReadTimeoutError, ProtocolError))
  285. def _is_method_retryable(self, method: str) -> bool:
  286. """Checks if a given HTTP method should be retried upon, depending if
  287. it is included in the allowed_methods
  288. """
  289. if self.allowed_methods and method.upper() not in self.allowed_methods:
  290. return False
  291. return True
  292. def is_retry(
  293. self, method: str, status_code: int, has_retry_after: bool = False
  294. ) -> bool:
  295. """Is this method/status code retryable? (Based on allowlists and control
  296. variables such as the number of total retries to allow, whether to
  297. respect the Retry-After header, whether this header is present, and
  298. whether the returned status code is on the list of status codes to
  299. be retried upon on the presence of the aforementioned header)
  300. """
  301. if not self._is_method_retryable(method):
  302. return False
  303. if self.status_forcelist and status_code in self.status_forcelist:
  304. return True
  305. return bool(
  306. self.total
  307. and self.respect_retry_after_header
  308. and has_retry_after
  309. and (status_code in self.RETRY_AFTER_STATUS_CODES)
  310. )
  311. def is_exhausted(self) -> bool:
  312. """Are we out of retries?"""
  313. retry_counts = [
  314. x
  315. for x in (
  316. self.total,
  317. self.connect,
  318. self.read,
  319. self.redirect,
  320. self.status,
  321. self.other,
  322. )
  323. if x
  324. ]
  325. if not retry_counts:
  326. return False
  327. return min(retry_counts) < 0
  328. def increment(
  329. self,
  330. method: str | None = None,
  331. url: str | None = None,
  332. response: BaseHTTPResponse | None = None,
  333. error: Exception | None = None,
  334. _pool: ConnectionPool | None = None,
  335. _stacktrace: TracebackType | None = None,
  336. ) -> Retry:
  337. """Return a new Retry object with incremented retry counters.
  338. :param response: A response object, or None, if the server did not
  339. return a response.
  340. :type response: :class:`~urllib3.response.BaseHTTPResponse`
  341. :param Exception error: An error encountered during the request, or
  342. None if the response was received successfully.
  343. :return: A new ``Retry`` object.
  344. """
  345. if self.total is False and error:
  346. # Disabled, indicate to re-raise the error.
  347. raise reraise(type(error), error, _stacktrace)
  348. total = self.total
  349. if total is not None:
  350. total -= 1
  351. connect = self.connect
  352. read = self.read
  353. redirect = self.redirect
  354. status_count = self.status
  355. other = self.other
  356. cause = "unknown"
  357. status = None
  358. redirect_location = None
  359. if error and self._is_connection_error(error):
  360. # Connect retry?
  361. if connect is False:
  362. raise reraise(type(error), error, _stacktrace)
  363. elif connect is not None:
  364. connect -= 1
  365. elif error and self._is_read_error(error):
  366. # Read retry?
  367. if read is False or method is None or not self._is_method_retryable(method):
  368. raise reraise(type(error), error, _stacktrace)
  369. elif read is not None:
  370. read -= 1
  371. elif error:
  372. # Other retry?
  373. if other is not None:
  374. other -= 1
  375. elif response and response.get_redirect_location():
  376. # Redirect retry?
  377. if redirect is not None:
  378. redirect -= 1
  379. cause = "too many redirects"
  380. response_redirect_location = response.get_redirect_location()
  381. if response_redirect_location:
  382. redirect_location = response_redirect_location
  383. status = response.status
  384. else:
  385. # Incrementing because of a server error like a 500 in
  386. # status_forcelist and the given method is in the allowed_methods
  387. cause = ResponseError.GENERIC_ERROR
  388. if response and response.status:
  389. if status_count is not None:
  390. status_count -= 1
  391. cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status)
  392. status = response.status
  393. history = self.history + (
  394. RequestHistory(method, url, error, status, redirect_location),
  395. )
  396. new_retry = self.new(
  397. total=total,
  398. connect=connect,
  399. read=read,
  400. redirect=redirect,
  401. status=status_count,
  402. other=other,
  403. history=history,
  404. )
  405. if new_retry.is_exhausted():
  406. reason = error or ResponseError(cause)
  407. raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type]
  408. log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)
  409. return new_retry
  410. def __repr__(self) -> str:
  411. return (
  412. f"{type(self).__name__}(total={self.total}, connect={self.connect}, "
  413. f"read={self.read}, redirect={self.redirect}, status={self.status})"
  414. )
  415. # For backwards compatibility (equivalent to pre-v1.9):
  416. Retry.DEFAULT = Retry(3)