You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

417 regels
16 KiB

  1. import threading
  2. from asyncio import iscoroutine
  3. from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait
  4. from contextlib import AbstractContextManager, contextmanager
  5. from types import TracebackType
  6. from typing import (
  7. Any, AsyncContextManager, Callable, ContextManager, Coroutine, Dict, Generator, Iterable,
  8. Optional, Tuple, Type, TypeVar, Union, cast, overload)
  9. from warnings import warn
  10. from ._core import _eventloop
  11. from ._core._eventloop import get_asynclib, get_cancelled_exc_class, threadlocals
  12. from ._core._synchronization import Event
  13. from ._core._tasks import CancelScope, create_task_group
  14. from .abc._tasks import TaskStatus
  15. T_Retval = TypeVar('T_Retval')
  16. T_co = TypeVar('T_co')
  17. def run(func: Callable[..., Coroutine[Any, Any, T_Retval]], *args: object) -> T_Retval:
  18. """
  19. Call a coroutine function from a worker thread.
  20. :param func: a coroutine function
  21. :param args: positional arguments for the callable
  22. :return: the return value of the coroutine function
  23. """
  24. try:
  25. asynclib = threadlocals.current_async_module
  26. except AttributeError:
  27. raise RuntimeError('This function can only be run from an AnyIO worker thread')
  28. return asynclib.run_async_from_thread(func, *args)
  29. def run_async_from_thread(func: Callable[..., Coroutine[Any, Any, T_Retval]],
  30. *args: object) -> T_Retval:
  31. warn('run_async_from_thread() has been deprecated, use anyio.from_thread.run() instead',
  32. DeprecationWarning)
  33. return run(func, *args)
  34. def run_sync(func: Callable[..., T_Retval], *args: object) -> T_Retval:
  35. """
  36. Call a function in the event loop thread from a worker thread.
  37. :param func: a callable
  38. :param args: positional arguments for the callable
  39. :return: the return value of the callable
  40. """
  41. try:
  42. asynclib = threadlocals.current_async_module
  43. except AttributeError:
  44. raise RuntimeError('This function can only be run from an AnyIO worker thread')
  45. return asynclib.run_sync_from_thread(func, *args)
  46. def run_sync_from_thread(func: Callable[..., T_Retval], *args: object) -> T_Retval:
  47. warn('run_sync_from_thread() has been deprecated, use anyio.from_thread.run_sync() instead',
  48. DeprecationWarning)
  49. return run_sync(func, *args)
  50. class _BlockingAsyncContextManager(AbstractContextManager):
  51. _enter_future: Future
  52. _exit_future: Future
  53. _exit_event: Event
  54. _exit_exc_info: Tuple[Optional[Type[BaseException]], Optional[BaseException],
  55. Optional[TracebackType]] = (None, None, None)
  56. def __init__(self, async_cm: AsyncContextManager[T_co], portal: 'BlockingPortal'):
  57. self._async_cm = async_cm
  58. self._portal = portal
  59. async def run_async_cm(self) -> Optional[bool]:
  60. try:
  61. self._exit_event = Event()
  62. value = await self._async_cm.__aenter__()
  63. except BaseException as exc:
  64. self._enter_future.set_exception(exc)
  65. raise
  66. else:
  67. self._enter_future.set_result(value)
  68. try:
  69. # Wait for the sync context manager to exit.
  70. # This next statement can raise `get_cancelled_exc_class()` if
  71. # something went wrong in a task group in this async context
  72. # manager.
  73. await self._exit_event.wait()
  74. finally:
  75. # In case of cancellation, it could be that we end up here before
  76. # `_BlockingAsyncContextManager.__exit__` is called, and an
  77. # `_exit_exc_info` has been set.
  78. result = await self._async_cm.__aexit__(*self._exit_exc_info)
  79. return result
  80. def __enter__(self) -> T_co:
  81. self._enter_future = Future()
  82. self._exit_future = self._portal.start_task_soon(self.run_async_cm)
  83. cm = self._enter_future.result()
  84. return cast(T_co, cm)
  85. def __exit__(self, __exc_type: Optional[Type[BaseException]],
  86. __exc_value: Optional[BaseException],
  87. __traceback: Optional[TracebackType]) -> Optional[bool]:
  88. self._exit_exc_info = __exc_type, __exc_value, __traceback
  89. self._portal.call(self._exit_event.set)
  90. return self._exit_future.result()
  91. class _BlockingPortalTaskStatus(TaskStatus):
  92. def __init__(self, future: Future):
  93. self._future = future
  94. def started(self, value: object = None) -> None:
  95. self._future.set_result(value)
  96. class BlockingPortal:
  97. """An object that lets external threads run code in an asynchronous event loop."""
  98. def __new__(cls) -> 'BlockingPortal':
  99. return get_asynclib().BlockingPortal()
  100. def __init__(self) -> None:
  101. self._event_loop_thread_id: Optional[int] = threading.get_ident()
  102. self._stop_event = Event()
  103. self._task_group = create_task_group()
  104. self._cancelled_exc_class = get_cancelled_exc_class()
  105. async def __aenter__(self) -> 'BlockingPortal':
  106. await self._task_group.__aenter__()
  107. return self
  108. async def __aexit__(self, exc_type: Optional[Type[BaseException]],
  109. exc_val: Optional[BaseException],
  110. exc_tb: Optional[TracebackType]) -> Optional[bool]:
  111. await self.stop()
  112. return await self._task_group.__aexit__(exc_type, exc_val, exc_tb)
  113. def _check_running(self) -> None:
  114. if self._event_loop_thread_id is None:
  115. raise RuntimeError('This portal is not running')
  116. if self._event_loop_thread_id == threading.get_ident():
  117. raise RuntimeError('This method cannot be called from the event loop thread')
  118. async def sleep_until_stopped(self) -> None:
  119. """Sleep until :meth:`stop` is called."""
  120. await self._stop_event.wait()
  121. async def stop(self, cancel_remaining: bool = False) -> None:
  122. """
  123. Signal the portal to shut down.
  124. This marks the portal as no longer accepting new calls and exits from
  125. :meth:`sleep_until_stopped`.
  126. :param cancel_remaining: ``True`` to cancel all the remaining tasks, ``False`` to let them
  127. finish before returning
  128. """
  129. self._event_loop_thread_id = None
  130. self._stop_event.set()
  131. if cancel_remaining:
  132. self._task_group.cancel_scope.cancel()
  133. async def _call_func(self, func: Callable, args: tuple, kwargs: Dict[str, Any],
  134. future: Future) -> None:
  135. def callback(f: Future) -> None:
  136. if f.cancelled() and self._event_loop_thread_id not in (None, threading.get_ident()):
  137. self.call(scope.cancel)
  138. try:
  139. retval = func(*args, **kwargs)
  140. if iscoroutine(retval):
  141. with CancelScope() as scope:
  142. if future.cancelled():
  143. scope.cancel()
  144. else:
  145. future.add_done_callback(callback)
  146. retval = await retval
  147. except self._cancelled_exc_class:
  148. future.cancel()
  149. except BaseException as exc:
  150. if not future.cancelled():
  151. future.set_exception(exc)
  152. # Let base exceptions fall through
  153. if not isinstance(exc, Exception):
  154. raise
  155. else:
  156. if not future.cancelled():
  157. future.set_result(retval)
  158. finally:
  159. scope = None # type: ignore[assignment]
  160. def _spawn_task_from_thread(self, func: Callable, args: tuple, kwargs: Dict[str, Any],
  161. name: object, future: Future) -> None:
  162. """
  163. Spawn a new task using the given callable.
  164. Implementors must ensure that the future is resolved when the task finishes.
  165. :param func: a callable
  166. :param args: positional arguments to be passed to the callable
  167. :param kwargs: keyword arguments to be passed to the callable
  168. :param name: name of the task (will be coerced to a string if not ``None``)
  169. :param future: a future that will resolve to the return value of the callable, or the
  170. exception raised during its execution
  171. """
  172. raise NotImplementedError
  173. @overload
  174. def call(self, func: Callable[..., Coroutine[Any, Any, T_Retval]], *args: object) -> T_Retval:
  175. ...
  176. @overload
  177. def call(self, func: Callable[..., T_Retval], *args: object) -> T_Retval:
  178. ...
  179. def call(self, func: Callable[..., Union[Coroutine[Any, Any, T_Retval], T_Retval]],
  180. *args: object) -> T_Retval:
  181. """
  182. Call the given function in the event loop thread.
  183. If the callable returns a coroutine object, it is awaited on.
  184. :param func: any callable
  185. :raises RuntimeError: if the portal is not running or if this method is called from within
  186. the event loop thread
  187. """
  188. return cast(T_Retval, self.start_task_soon(func, *args).result())
  189. @overload
  190. def spawn_task(self, func: Callable[..., Coroutine[Any, Any, T_Retval]],
  191. *args: object, name: object = None) -> "Future[T_Retval]":
  192. ...
  193. @overload
  194. def spawn_task(self, func: Callable[..., T_Retval],
  195. *args: object, name: object = None) -> "Future[T_Retval]": ...
  196. def spawn_task(self, func: Callable[..., Union[Coroutine[Any, Any, T_Retval], T_Retval]],
  197. *args: object, name: object = None) -> "Future[T_Retval]":
  198. """
  199. Start a task in the portal's task group.
  200. :param func: the target coroutine function
  201. :param args: positional arguments passed to ``func``
  202. :param name: name of the task (will be coerced to a string if not ``None``)
  203. :return: a future that resolves with the return value of the callable if the task completes
  204. successfully, or with the exception raised in the task
  205. :raises RuntimeError: if the portal is not running or if this method is called from within
  206. the event loop thread
  207. .. versionadded:: 2.1
  208. .. deprecated:: 3.0
  209. Use :meth:`start_task_soon` instead. If your code needs AnyIO 2 compatibility, you
  210. can keep using this until AnyIO 4.
  211. """
  212. warn('spawn_task() is deprecated -- use start_task_soon() instead', DeprecationWarning)
  213. return self.start_task_soon(func, *args, name=name) # type: ignore[arg-type]
  214. @overload
  215. def start_task_soon(self, func: Callable[..., Coroutine[Any, Any, T_Retval]],
  216. *args: object, name: object = None) -> "Future[T_Retval]":
  217. ...
  218. @overload
  219. def start_task_soon(self, func: Callable[..., T_Retval],
  220. *args: object, name: object = None) -> "Future[T_Retval]": ...
  221. def start_task_soon(self, func: Callable[..., Union[Coroutine[Any, Any, T_Retval], T_Retval]],
  222. *args: object, name: object = None) -> "Future[T_Retval]":
  223. """
  224. Start a task in the portal's task group.
  225. The task will be run inside a cancel scope which can be cancelled by cancelling the
  226. returned future.
  227. :param func: the target coroutine function
  228. :param args: positional arguments passed to ``func``
  229. :param name: name of the task (will be coerced to a string if not ``None``)
  230. :return: a future that resolves with the return value of the callable if the task completes
  231. successfully, or with the exception raised in the task
  232. :raises RuntimeError: if the portal is not running or if this method is called from within
  233. the event loop thread
  234. .. versionadded:: 3.0
  235. """
  236. self._check_running()
  237. f: Future = Future()
  238. self._spawn_task_from_thread(func, args, {}, name, f)
  239. return f
  240. def start_task(self, func: Callable[..., Coroutine[Any, Any, Any]], *args: object,
  241. name: object = None) -> Tuple['Future[Any]', Any]:
  242. """
  243. Start a task in the portal's task group and wait until it signals for readiness.
  244. This method works the same way as :meth:`TaskGroup.start`.
  245. :param func: the target coroutine function
  246. :param args: positional arguments passed to ``func``
  247. :param name: name of the task (will be coerced to a string if not ``None``)
  248. :return: a tuple of (future, task_status_value) where the ``task_status_value`` is the
  249. value passed to ``task_status.started()`` from within the target function
  250. .. versionadded:: 3.0
  251. """
  252. def task_done(future: Future) -> None:
  253. if not task_status_future.done():
  254. if future.cancelled():
  255. task_status_future.cancel()
  256. elif future.exception():
  257. task_status_future.set_exception(future.exception())
  258. else:
  259. exc = RuntimeError('Task exited without calling task_status.started()')
  260. task_status_future.set_exception(exc)
  261. self._check_running()
  262. task_status_future: Future = Future()
  263. task_status = _BlockingPortalTaskStatus(task_status_future)
  264. f: Future = Future()
  265. f.add_done_callback(task_done)
  266. self._spawn_task_from_thread(func, args, {'task_status': task_status}, name, f)
  267. return f, task_status_future.result()
  268. def wrap_async_context_manager(self, cm: AsyncContextManager[T_co]) -> ContextManager[T_co]:
  269. """
  270. Wrap an async context manager as a synchronous context manager via this portal.
  271. Spawns a task that will call both ``__aenter__()`` and ``__aexit__()``, stopping in the
  272. middle until the synchronous context manager exits.
  273. :param cm: an asynchronous context manager
  274. :return: a synchronous context manager
  275. .. versionadded:: 2.1
  276. """
  277. return _BlockingAsyncContextManager(cm, self)
  278. def create_blocking_portal() -> BlockingPortal:
  279. """
  280. Create a portal for running functions in the event loop thread from external threads.
  281. Use this function in asynchronous code when you need to allow external threads access to the
  282. event loop where your asynchronous code is currently running.
  283. .. deprecated:: 3.0
  284. Use :class:`.BlockingPortal` directly.
  285. """
  286. warn('create_blocking_portal() has been deprecated -- use anyio.from_thread.BlockingPortal() '
  287. 'directly', DeprecationWarning)
  288. return BlockingPortal()
  289. @contextmanager
  290. def start_blocking_portal(
  291. backend: str = 'asyncio',
  292. backend_options: Optional[Dict[str, Any]] = None) -> Generator[BlockingPortal, Any, None]:
  293. """
  294. Start a new event loop in a new thread and run a blocking portal in its main task.
  295. The parameters are the same as for :func:`~anyio.run`.
  296. :param backend: name of the backend
  297. :param backend_options: backend options
  298. :return: a context manager that yields a blocking portal
  299. .. versionchanged:: 3.0
  300. Usage as a context manager is now required.
  301. """
  302. async def run_portal() -> None:
  303. async with BlockingPortal() as portal_:
  304. if future.set_running_or_notify_cancel():
  305. future.set_result(portal_)
  306. await portal_.sleep_until_stopped()
  307. future: Future[BlockingPortal] = Future()
  308. with ThreadPoolExecutor(1) as executor:
  309. run_future = executor.submit(_eventloop.run, run_portal, backend=backend,
  310. backend_options=backend_options)
  311. try:
  312. wait(cast(Iterable[Future], [run_future, future]), return_when=FIRST_COMPLETED)
  313. except BaseException:
  314. future.cancel()
  315. run_future.cancel()
  316. raise
  317. if future.done():
  318. portal = future.result()
  319. try:
  320. yield portal
  321. except BaseException:
  322. portal.call(portal.stop, True)
  323. raise
  324. portal.call(portal.stop, False)
  325. run_future.result()