concurrent.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. #
  2. # Copyright 2012 Facebook
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. """Utilities for working with ``Future`` objects.
  16. Tornado previously provided its own ``Future`` class, but now uses
  17. `asyncio.Future`. This module contains utility functions for working
  18. with `asyncio.Future` in a way that is backwards-compatible with
  19. Tornado's old ``Future`` implementation.
  20. While this module is an important part of Tornado's internal
  21. implementation, applications rarely need to interact with it
  22. directly.
  23. """
  24. import asyncio
  25. from concurrent import futures
  26. import functools
  27. import sys
  28. import types
  29. from tornado.log import app_log
  30. import typing
  31. from typing import Any, Callable, Optional, Tuple, Union
  32. _T = typing.TypeVar("_T")
  33. class ReturnValueIgnoredError(Exception):
  34. # No longer used; was previously used by @return_future
  35. pass
  36. Future = asyncio.Future
  37. FUTURES = (futures.Future, Future)
  38. def is_future(x: Any) -> bool:
  39. return isinstance(x, FUTURES)
  40. class DummyExecutor(futures.Executor):
  41. def submit(
  42. self, fn: Callable[..., _T], *args: Any, **kwargs: Any
  43. ) -> "futures.Future[_T]":
  44. future = futures.Future() # type: futures.Future[_T]
  45. try:
  46. future_set_result_unless_cancelled(future, fn(*args, **kwargs))
  47. except Exception:
  48. future_set_exc_info(future, sys.exc_info())
  49. return future
  50. def shutdown(self, wait: bool = True) -> None:
  51. pass
  52. dummy_executor = DummyExecutor()
  53. def run_on_executor(*args: Any, **kwargs: Any) -> Callable:
  54. """Decorator to run a synchronous method asynchronously on an executor.
  55. The decorated method may be called with a ``callback`` keyword
  56. argument and returns a future.
  57. The executor to be used is determined by the ``executor``
  58. attributes of ``self``. To use a different attribute name, pass a
  59. keyword argument to the decorator::
  60. @run_on_executor(executor='_thread_pool')
  61. def foo(self):
  62. pass
  63. This decorator should not be confused with the similarly-named
  64. `.IOLoop.run_in_executor`. In general, using ``run_in_executor``
  65. when *calling* a blocking method is recommended instead of using
  66. this decorator when *defining* a method. If compatibility with older
  67. versions of Tornado is required, consider defining an executor
  68. and using ``executor.submit()`` at the call site.
  69. .. versionchanged:: 4.2
  70. Added keyword arguments to use alternative attributes.
  71. .. versionchanged:: 5.0
  72. Always uses the current IOLoop instead of ``self.io_loop``.
  73. .. versionchanged:: 5.1
  74. Returns a `.Future` compatible with ``await`` instead of a
  75. `concurrent.futures.Future`.
  76. .. deprecated:: 5.1
  77. The ``callback`` argument is deprecated and will be removed in
  78. 6.0. The decorator itself is discouraged in new code but will
  79. not be removed in 6.0.
  80. .. versionchanged:: 6.0
  81. The ``callback`` argument was removed.
  82. """
  83. # Fully type-checking decorators is tricky, and this one is
  84. # discouraged anyway so it doesn't have all the generic magic.
  85. def run_on_executor_decorator(fn: Callable) -> Callable[..., Future]:
  86. executor = kwargs.get("executor", "executor")
  87. @functools.wraps(fn)
  88. def wrapper(self: Any, *args: Any, **kwargs: Any) -> Future:
  89. async_future = Future() # type: Future
  90. conc_future = getattr(self, executor).submit(fn, self, *args, **kwargs)
  91. chain_future(conc_future, async_future)
  92. return async_future
  93. return wrapper
  94. if args and kwargs:
  95. raise ValueError("cannot combine positional and keyword args")
  96. if len(args) == 1:
  97. return run_on_executor_decorator(args[0])
  98. elif len(args) != 0:
  99. raise ValueError("expected 1 argument, got %d", len(args))
  100. return run_on_executor_decorator
  101. _NO_RESULT = object()
  102. def chain_future(a: "Future[_T]", b: "Future[_T]") -> None:
  103. """Chain two futures together so that when one completes, so does the other.
  104. The result (success or failure) of ``a`` will be copied to ``b``, unless
  105. ``b`` has already been completed or cancelled by the time ``a`` finishes.
  106. .. versionchanged:: 5.0
  107. Now accepts both Tornado/asyncio `Future` objects and
  108. `concurrent.futures.Future`.
  109. """
  110. def copy(future: "Future[_T]") -> None:
  111. assert future is a
  112. if b.done():
  113. return
  114. if hasattr(a, "exc_info") and a.exc_info() is not None: # type: ignore
  115. future_set_exc_info(b, a.exc_info()) # type: ignore
  116. elif a.exception() is not None:
  117. b.set_exception(a.exception())
  118. else:
  119. b.set_result(a.result())
  120. if isinstance(a, Future):
  121. future_add_done_callback(a, copy)
  122. else:
  123. # concurrent.futures.Future
  124. from tornado.ioloop import IOLoop
  125. IOLoop.current().add_future(a, copy)
  126. def future_set_result_unless_cancelled(
  127. future: "Union[futures.Future[_T], Future[_T]]", value: _T
  128. ) -> None:
  129. """Set the given ``value`` as the `Future`'s result, if not cancelled.
  130. Avoids ``asyncio.InvalidStateError`` when calling ``set_result()`` on
  131. a cancelled `asyncio.Future`.
  132. .. versionadded:: 5.0
  133. """
  134. if not future.cancelled():
  135. future.set_result(value)
  136. def future_set_exception_unless_cancelled(
  137. future: "Union[futures.Future[_T], Future[_T]]", exc: BaseException
  138. ) -> None:
  139. """Set the given ``exc`` as the `Future`'s exception.
  140. If the Future is already canceled, logs the exception instead. If
  141. this logging is not desired, the caller should explicitly check
  142. the state of the Future and call ``Future.set_exception`` instead of
  143. this wrapper.
  144. Avoids ``asyncio.InvalidStateError`` when calling ``set_exception()`` on
  145. a cancelled `asyncio.Future`.
  146. .. versionadded:: 6.0
  147. """
  148. if not future.cancelled():
  149. future.set_exception(exc)
  150. else:
  151. app_log.error("Exception after Future was cancelled", exc_info=exc)
  152. def future_set_exc_info(
  153. future: "Union[futures.Future[_T], Future[_T]]",
  154. exc_info: Tuple[
  155. Optional[type], Optional[BaseException], Optional[types.TracebackType]
  156. ],
  157. ) -> None:
  158. """Set the given ``exc_info`` as the `Future`'s exception.
  159. Understands both `asyncio.Future` and the extensions in older
  160. versions of Tornado to enable better tracebacks on Python 2.
  161. .. versionadded:: 5.0
  162. .. versionchanged:: 6.0
  163. If the future is already cancelled, this function is a no-op.
  164. (previously ``asyncio.InvalidStateError`` would be raised)
  165. """
  166. if exc_info[1] is None:
  167. raise Exception("future_set_exc_info called with no exception")
  168. future_set_exception_unless_cancelled(future, exc_info[1])
  169. @typing.overload
  170. def future_add_done_callback(
  171. future: "futures.Future[_T]", callback: Callable[["futures.Future[_T]"], None]
  172. ) -> None:
  173. pass
  174. @typing.overload # noqa: F811
  175. def future_add_done_callback(
  176. future: "Future[_T]", callback: Callable[["Future[_T]"], None]
  177. ) -> None:
  178. pass
  179. def future_add_done_callback( # noqa: F811
  180. future: "Union[futures.Future[_T], Future[_T]]", callback: Callable[..., None]
  181. ) -> None:
  182. """Arrange to call ``callback`` when ``future`` is complete.
  183. ``callback`` is invoked with one argument, the ``future``.
  184. If ``future`` is already done, ``callback`` is invoked immediately.
  185. This may differ from the behavior of ``Future.add_done_callback``,
  186. which makes no such guarantee.
  187. .. versionadded:: 5.0
  188. """
  189. if future.done():
  190. callback(future)
  191. else:
  192. future.add_done_callback(callback)