tornadoweb.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 pip._vendor.tenacity import BaseRetrying
  17. from pip._vendor.tenacity import DoAttempt
  18. from pip._vendor.tenacity import DoSleep
  19. from pip._vendor.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__(self, sleep: "typing.Callable[[float], Future[None]]" = gen.sleep, **kwargs: typing.Any) -> None:
  26. super().__init__(**kwargs)
  27. self.sleep = sleep
  28. @gen.coroutine
  29. def __call__( # type: ignore # Change signature from supertype
  30. self,
  31. fn: "typing.Callable[..., typing.Union[typing.Generator[typing.Any, typing.Any, _RetValT], Future[_RetValT]]]",
  32. *args: typing.Any,
  33. **kwargs: typing.Any,
  34. ) -> "typing.Generator[typing.Any, typing.Any, _RetValT]":
  35. self.begin()
  36. retry_state = RetryCallState(retry_object=self, fn=fn, args=args, kwargs=kwargs)
  37. while True:
  38. do = self.iter(retry_state=retry_state)
  39. if isinstance(do, DoAttempt):
  40. try:
  41. result = yield fn(*args, **kwargs)
  42. except BaseException: # noqa: B902
  43. retry_state.set_exception(sys.exc_info())
  44. else:
  45. retry_state.set_result(result)
  46. elif isinstance(do, DoSleep):
  47. retry_state.prepare_for_next_attempt()
  48. yield self.sleep(do)
  49. else:
  50. raise gen.Return(do)