retry.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. """
  125. #: Default methods to be used for ``allowed_methods``
  126. DEFAULT_ALLOWED_METHODS = frozenset(
  127. ["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"]
  128. )
  129. #: Default status codes to be used for ``status_forcelist``
  130. RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])
  131. #: Default headers to be used for ``remove_headers_on_redirect``
  132. DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset(
  133. ["Cookie", "Authorization", "Proxy-Authorization"]
  134. )
  135. #: Default maximum backoff time.
  136. DEFAULT_BACKOFF_MAX = 120
  137. # Backward compatibility; assigned outside of the class.
  138. DEFAULT: typing.ClassVar[Retry]
  139. def __init__(
  140. self,
  141. total: bool | int | None = 10,
  142. connect: int | None = None,
  143. read: int | None = None,
  144. redirect: bool | int | None = None,
  145. status: int | None = None,
  146. other: int | None = None,
  147. allowed_methods: typing.Collection[str] | None = DEFAULT_ALLOWED_METHODS,
  148. status_forcelist: typing.Collection[int] | None = None,
  149. backoff_factor: float = 0,
  150. backoff_max: float = DEFAULT_BACKOFF_MAX,
  151. raise_on_redirect: bool = True,
  152. raise_on_status: bool = True,
  153. history: tuple[RequestHistory, ...] | None = None,
  154. respect_retry_after_header: bool = True,
  155. remove_headers_on_redirect: typing.Collection[
  156. str
  157. ] = DEFAULT_REMOVE_HEADERS_ON_REDIRECT,
  158. backoff_jitter: float = 0.0,
  159. ) -> None:
  160. self.total = total
  161. self.connect = connect
  162. self.read = read
  163. self.status = status
  164. self.other = other
  165. if redirect is False or total is False:
  166. redirect = 0
  167. raise_on_redirect = False
  168. self.redirect = redirect
  169. self.status_forcelist = status_forcelist or set()
  170. self.allowed_methods = allowed_methods
  171. self.backoff_factor = backoff_factor
  172. self.backoff_max = backoff_max
  173. self.raise_on_redirect = raise_on_redirect
  174. self.raise_on_status = raise_on_status
  175. self.history = history or ()
  176. self.respect_retry_after_header = respect_retry_after_header
  177. self.remove_headers_on_redirect = frozenset(
  178. h.lower() for h in remove_headers_on_redirect
  179. )
  180. self.backoff_jitter = backoff_jitter
  181. def new(self, **kw: typing.Any) -> Self:
  182. params = dict(
  183. total=self.total,
  184. connect=self.connect,
  185. read=self.read,
  186. redirect=self.redirect,
  187. status=self.status,
  188. other=self.other,
  189. allowed_methods=self.allowed_methods,
  190. status_forcelist=self.status_forcelist,
  191. backoff_factor=self.backoff_factor,
  192. backoff_max=self.backoff_max,
  193. raise_on_redirect=self.raise_on_redirect,
  194. raise_on_status=self.raise_on_status,
  195. history=self.history,
  196. remove_headers_on_redirect=self.remove_headers_on_redirect,
  197. respect_retry_after_header=self.respect_retry_after_header,
  198. backoff_jitter=self.backoff_jitter,
  199. )
  200. params.update(kw)
  201. return type(self)(**params) # type: ignore[arg-type]
  202. @classmethod
  203. def from_int(
  204. cls,
  205. retries: Retry | bool | int | None,
  206. redirect: bool | int | None = True,
  207. default: Retry | bool | int | None = None,
  208. ) -> Retry:
  209. """Backwards-compatibility for the old retries format."""
  210. if retries is None:
  211. retries = default if default is not None else cls.DEFAULT
  212. if isinstance(retries, Retry):
  213. return retries
  214. redirect = bool(redirect) and None
  215. new_retries = cls(retries, redirect=redirect)
  216. log.debug("Converted retries value: %r -> %r", retries, new_retries)
  217. return new_retries
  218. def get_backoff_time(self) -> float:
  219. """Formula for computing the current backoff
  220. :rtype: float
  221. """
  222. # We want to consider only the last consecutive errors sequence (Ignore redirects).
  223. consecutive_errors_len = len(
  224. list(
  225. takewhile(lambda x: x.redirect_location is None, reversed(self.history))
  226. )
  227. )
  228. if consecutive_errors_len <= 1:
  229. return 0
  230. backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))
  231. if self.backoff_jitter != 0.0:
  232. backoff_value += random.random() * self.backoff_jitter
  233. return float(max(0, min(self.backoff_max, backoff_value)))
  234. def parse_retry_after(self, retry_after: str) -> float:
  235. seconds: float
  236. # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4
  237. if re.match(r"^\s*[0-9]+\s*$", retry_after):
  238. seconds = int(retry_after)
  239. else:
  240. retry_date_tuple = email.utils.parsedate_tz(retry_after)
  241. if retry_date_tuple is None:
  242. raise InvalidHeader(f"Invalid Retry-After header: {retry_after}")
  243. retry_date = email.utils.mktime_tz(retry_date_tuple)
  244. seconds = retry_date - time.time()
  245. seconds = max(seconds, 0)
  246. return seconds
  247. def get_retry_after(self, response: BaseHTTPResponse) -> float | None:
  248. """Get the value of Retry-After in seconds."""
  249. retry_after = response.headers.get("Retry-After")
  250. if retry_after is None:
  251. return None
  252. return self.parse_retry_after(retry_after)
  253. def sleep_for_retry(self, response: BaseHTTPResponse) -> bool:
  254. retry_after = self.get_retry_after(response)
  255. if retry_after:
  256. time.sleep(retry_after)
  257. return True
  258. return False
  259. def _sleep_backoff(self) -> None:
  260. backoff = self.get_backoff_time()
  261. if backoff <= 0:
  262. return
  263. time.sleep(backoff)
  264. def sleep(self, response: BaseHTTPResponse | None = None) -> None:
  265. """Sleep between retry attempts.
  266. This method will respect a server's ``Retry-After`` response header
  267. and sleep the duration of the time requested. If that is not present, it
  268. will use an exponential backoff. By default, the backoff factor is 0 and
  269. this method will return immediately.
  270. """
  271. if self.respect_retry_after_header and response:
  272. slept = self.sleep_for_retry(response)
  273. if slept:
  274. return
  275. self._sleep_backoff()
  276. def _is_connection_error(self, err: Exception) -> bool:
  277. """Errors when we're fairly sure that the server did not receive the
  278. request, so it should be safe to retry.
  279. """
  280. if isinstance(err, ProxyError):
  281. err = err.original_error
  282. return isinstance(err, ConnectTimeoutError)
  283. def _is_read_error(self, err: Exception) -> bool:
  284. """Errors that occur after the request has been started, so we should
  285. assume that the server began processing it.
  286. """
  287. return isinstance(err, (ReadTimeoutError, ProtocolError))
  288. def _is_method_retryable(self, method: str) -> bool:
  289. """Checks if a given HTTP method should be retried upon, depending if
  290. it is included in the allowed_methods
  291. """
  292. if self.allowed_methods and method.upper() not in self.allowed_methods:
  293. return False
  294. return True
  295. def is_retry(
  296. self, method: str, status_code: int, has_retry_after: bool = False
  297. ) -> bool:
  298. """Is this method/status code retryable? (Based on allowlists and control
  299. variables such as the number of total retries to allow, whether to
  300. respect the Retry-After header, whether this header is present, and
  301. whether the returned status code is on the list of status codes to
  302. be retried upon on the presence of the aforementioned header)
  303. """
  304. if not self._is_method_retryable(method):
  305. return False
  306. if self.status_forcelist and status_code in self.status_forcelist:
  307. return True
  308. return bool(
  309. self.total
  310. and self.respect_retry_after_header
  311. and has_retry_after
  312. and (status_code in self.RETRY_AFTER_STATUS_CODES)
  313. )
  314. def is_exhausted(self) -> bool:
  315. """Are we out of retries?"""
  316. retry_counts = [
  317. x
  318. for x in (
  319. self.total,
  320. self.connect,
  321. self.read,
  322. self.redirect,
  323. self.status,
  324. self.other,
  325. )
  326. if x
  327. ]
  328. if not retry_counts:
  329. return False
  330. return min(retry_counts) < 0
  331. def increment(
  332. self,
  333. method: str | None = None,
  334. url: str | None = None,
  335. response: BaseHTTPResponse | None = None,
  336. error: Exception | None = None,
  337. _pool: ConnectionPool | None = None,
  338. _stacktrace: TracebackType | None = None,
  339. ) -> Self:
  340. """Return a new Retry object with incremented retry counters.
  341. :param response: A response object, or None, if the server did not
  342. return a response.
  343. :type response: :class:`~urllib3.response.BaseHTTPResponse`
  344. :param Exception error: An error encountered during the request, or
  345. None if the response was received successfully.
  346. :return: A new ``Retry`` object.
  347. """
  348. if self.total is False and error:
  349. # Disabled, indicate to re-raise the error.
  350. raise reraise(type(error), error, _stacktrace)
  351. total = self.total
  352. if total is not None:
  353. total -= 1
  354. connect = self.connect
  355. read = self.read
  356. redirect = self.redirect
  357. status_count = self.status
  358. other = self.other
  359. cause = "unknown"
  360. status = None
  361. redirect_location = None
  362. if error and self._is_connection_error(error):
  363. # Connect retry?
  364. if connect is False:
  365. raise reraise(type(error), error, _stacktrace)
  366. elif connect is not None:
  367. connect -= 1
  368. elif error and self._is_read_error(error):
  369. # Read retry?
  370. if read is False or method is None or not self._is_method_retryable(method):
  371. raise reraise(type(error), error, _stacktrace)
  372. elif read is not None:
  373. read -= 1
  374. elif error:
  375. # Other retry?
  376. if other is not None:
  377. other -= 1
  378. elif response and response.get_redirect_location():
  379. # Redirect retry?
  380. if redirect is not None:
  381. redirect -= 1
  382. cause = "too many redirects"
  383. response_redirect_location = response.get_redirect_location()
  384. if response_redirect_location:
  385. redirect_location = response_redirect_location
  386. status = response.status
  387. else:
  388. # Incrementing because of a server error like a 500 in
  389. # status_forcelist and the given method is in the allowed_methods
  390. cause = ResponseError.GENERIC_ERROR
  391. if response and response.status:
  392. if status_count is not None:
  393. status_count -= 1
  394. cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status)
  395. status = response.status
  396. history = self.history + (
  397. RequestHistory(method, url, error, status, redirect_location),
  398. )
  399. new_retry = self.new(
  400. total=total,
  401. connect=connect,
  402. read=read,
  403. redirect=redirect,
  404. status=status_count,
  405. other=other,
  406. history=history,
  407. )
  408. if new_retry.is_exhausted():
  409. reason = error or ResponseError(cause)
  410. raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type]
  411. log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)
  412. return new_retry
  413. def __repr__(self) -> str:
  414. return (
  415. f"{type(self).__name__}(total={self.total}, connect={self.connect}, "
  416. f"read={self.read}, redirect={self.redirect}, status={self.status})"
  417. )
  418. # For backwards compatibility (equivalent to pre-v1.9):
  419. Retry.DEFAULT = Retry(3)