tornadoweb.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # Copyright 2017 Elisey Zanko
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import sys
  15. import typing
  16. from tenacity import BaseRetrying
  17. from tenacity import DoAttempt
  18. from tenacity import DoSleep
  19. from tenacity import RetryCallState
  20. from tornado import gen
  21. if typing.TYPE_CHECKING:
  22. from tornado.concurrent import Future
  23. _RetValT = typing.TypeVar("_RetValT")
  24. class TornadoRetrying(BaseRetrying):
  25. def __init__(
  26. self,
  27. sleep: "typing.Callable[[float], Future[None]]" = gen.sleep,
  28. **kwargs: typing.Any,
  29. ) -> None:
  30. super().__init__(**kwargs)
  31. self.sleep = sleep
  32. @gen.coroutine # type: ignore[misc]
  33. def __call__(
  34. self,
  35. fn: "typing.Callable[..., typing.Union[typing.Generator[typing.Any, typing.Any, _RetValT], Future[_RetValT]]]",
  36. *args: typing.Any,
  37. **kwargs: typing.Any,
  38. ) -> "typing.Generator[typing.Any, typing.Any, _RetValT]":
  39. self.begin()
  40. retry_state = RetryCallState(retry_object=self, fn=fn, args=args, kwargs=kwargs)
  41. while True:
  42. do = self.iter(retry_state=retry_state)
  43. if isinstance(do, DoAttempt):
  44. try:
  45. result = yield fn(*args, **kwargs)
  46. except BaseException: # noqa: B902
  47. retry_state.set_exception(sys.exc_info()) # type: ignore[arg-type]
  48. else:
  49. retry_state.set_result(result)
  50. elif isinstance(do, DoSleep):
  51. retry_state.prepare_for_next_attempt()
  52. yield self.sleep(do)
  53. else:
  54. raise gen.Return(do)