retry.py 20 KB

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