retry.py 19 KB

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