retry.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import socket
  2. from time import sleep
  3. from typing import TYPE_CHECKING, Any, Callable, Iterable, Tuple, Type, TypeVar
  4. from redis.exceptions import ConnectionError, TimeoutError
  5. T = TypeVar("T")
  6. if TYPE_CHECKING:
  7. from redis.backoff import AbstractBackoff
  8. class Retry:
  9. """Retry a specific number of times after a failure"""
  10. def __init__(
  11. self,
  12. backoff: "AbstractBackoff",
  13. retries: int,
  14. supported_errors: Tuple[Type[Exception], ...] = (
  15. ConnectionError,
  16. TimeoutError,
  17. socket.timeout,
  18. ),
  19. ):
  20. """
  21. Initialize a `Retry` object with a `Backoff` object
  22. that retries a maximum of `retries` times.
  23. `retries` can be negative to retry forever.
  24. You can specify the types of supported errors which trigger
  25. a retry with the `supported_errors` parameter.
  26. """
  27. self._backoff = backoff
  28. self._retries = retries
  29. self._supported_errors = supported_errors
  30. def __eq__(self, other: Any) -> bool:
  31. if not isinstance(other, Retry):
  32. return NotImplemented
  33. return (
  34. self._backoff == other._backoff
  35. and self._retries == other._retries
  36. and set(self._supported_errors) == set(other._supported_errors)
  37. )
  38. def __hash__(self) -> int:
  39. return hash((self._backoff, self._retries, frozenset(self._supported_errors)))
  40. def update_supported_errors(
  41. self, specified_errors: Iterable[Type[Exception]]
  42. ) -> None:
  43. """
  44. Updates the supported errors with the specified error types
  45. """
  46. self._supported_errors = tuple(
  47. set(self._supported_errors + tuple(specified_errors))
  48. )
  49. def get_retries(self) -> int:
  50. """
  51. Get the number of retries.
  52. """
  53. return self._retries
  54. def update_retries(self, value: int) -> None:
  55. """
  56. Set the number of retries.
  57. """
  58. self._retries = value
  59. def call_with_retry(
  60. self,
  61. do: Callable[[], T],
  62. fail: Callable[[Exception], Any],
  63. ) -> T:
  64. """
  65. Execute an operation that might fail and returns its result, or
  66. raise the exception that was thrown depending on the `Backoff` object.
  67. `do`: the operation to call. Expects no argument.
  68. `fail`: the failure handler, expects the last error that was thrown
  69. """
  70. self._backoff.reset()
  71. failures = 0
  72. while True:
  73. try:
  74. return do()
  75. except self._supported_errors as error:
  76. failures += 1
  77. fail(error)
  78. if self._retries >= 0 and failures > self._retries:
  79. raise error
  80. backoff = self._backoff.compute(failures)
  81. if backoff > 0:
  82. sleep(backoff)