2020-06-29 02:44:16 +00:00
|
|
|
"""
|
|
|
|
Infection apis for ``asyncio`` loops running ``trio`` using guest mode.
|
|
|
|
"""
|
|
|
|
import asyncio
|
|
|
|
import inspect
|
|
|
|
from typing import (
|
2020-07-21 14:32:37 +00:00
|
|
|
Any,
|
2020-06-29 02:44:16 +00:00
|
|
|
Callable,
|
2020-10-14 16:51:41 +00:00
|
|
|
AsyncIterator,
|
2020-06-29 02:44:16 +00:00
|
|
|
Awaitable,
|
|
|
|
)
|
|
|
|
|
|
|
|
import trio
|
|
|
|
|
|
|
|
from .log import get_logger
|
|
|
|
from ._state import current_actor
|
|
|
|
|
|
|
|
log = get_logger(__name__)
|
|
|
|
|
|
|
|
|
2020-07-03 21:33:46 +00:00
|
|
|
__all__ = ['run_task', 'run_as_asyncio_guest']
|
2020-06-29 02:44:16 +00:00
|
|
|
|
|
|
|
|
2020-07-21 14:32:37 +00:00
|
|
|
async def run_coro(
|
|
|
|
to_trio: trio.MemorySendChannel,
|
2020-06-29 02:44:16 +00:00
|
|
|
coro: Awaitable,
|
2020-07-03 21:33:46 +00:00
|
|
|
) -> None:
|
2020-07-21 14:32:37 +00:00
|
|
|
"""Await ``coro`` and relay result back to ``trio``.
|
|
|
|
"""
|
|
|
|
to_trio.send_nowait(await coro)
|
|
|
|
|
|
|
|
|
|
|
|
async def consume_asyncgen(
|
|
|
|
to_trio: trio.MemorySendChannel,
|
2020-10-14 16:51:41 +00:00
|
|
|
coro: AsyncIterator,
|
2020-07-21 14:32:37 +00:00
|
|
|
) -> None:
|
|
|
|
"""Stream async generator results back to ``trio``.
|
2020-06-29 02:44:16 +00:00
|
|
|
|
2020-07-21 14:32:37 +00:00
|
|
|
``from_trio`` might eventually be used here for
|
|
|
|
bidirectional streaming.
|
2020-07-03 21:33:46 +00:00
|
|
|
"""
|
2020-07-21 14:32:37 +00:00
|
|
|
async for item in coro:
|
|
|
|
to_trio.send_nowait(item)
|
2020-06-29 02:44:16 +00:00
|
|
|
|
|
|
|
|
|
|
|
async def run_task(
|
|
|
|
func: Callable,
|
2020-07-03 21:33:46 +00:00
|
|
|
*,
|
2020-06-29 02:44:16 +00:00
|
|
|
qsize: int = 2**10,
|
2020-07-03 21:33:46 +00:00
|
|
|
_treat_as_stream: bool = False,
|
2020-06-29 02:44:16 +00:00
|
|
|
**kwargs,
|
2020-10-14 16:51:41 +00:00
|
|
|
) -> Any:
|
2020-06-29 02:44:16 +00:00
|
|
|
"""Run an ``asyncio`` async function or generator in a task, return
|
|
|
|
or stream the result back to ``trio``.
|
|
|
|
"""
|
2020-07-03 21:33:46 +00:00
|
|
|
assert current_actor().is_infected_aio()
|
2020-06-29 02:44:16 +00:00
|
|
|
|
|
|
|
# ITC (inter task comms)
|
2020-07-21 14:32:37 +00:00
|
|
|
from_trio = asyncio.Queue(qsize) # type: ignore
|
|
|
|
to_trio, from_aio = trio.open_memory_channel(qsize) # type: ignore
|
2020-06-29 02:44:16 +00:00
|
|
|
|
2020-07-03 21:33:46 +00:00
|
|
|
args = tuple(inspect.getfullargspec(func).args)
|
|
|
|
|
|
|
|
if getattr(func, '_tractor_steam_function', None):
|
|
|
|
# the assumption is that the target async routine accepts the
|
|
|
|
# send channel then it intends to yield more then one return
|
|
|
|
# value otherwise it would just return ;P
|
|
|
|
_treat_as_stream = True
|
|
|
|
|
|
|
|
# allow target func to accept/stream results manually by name
|
|
|
|
if 'to_trio' in args:
|
|
|
|
kwargs['to_trio'] = to_trio
|
|
|
|
if 'from_trio' in args:
|
2020-07-21 14:32:37 +00:00
|
|
|
kwargs['from_trio'] = from_trio
|
2020-06-29 02:44:16 +00:00
|
|
|
|
|
|
|
coro = func(**kwargs)
|
|
|
|
|
|
|
|
cancel_scope = trio.CancelScope()
|
|
|
|
|
|
|
|
# start the asyncio task we submitted from trio
|
2020-07-21 14:32:37 +00:00
|
|
|
if inspect.isawaitable(coro):
|
|
|
|
task = asyncio.create_task(run_coro(to_trio, coro))
|
|
|
|
elif inspect.isasyncgen(coro):
|
|
|
|
task = asyncio.create_task(consume_asyncgen(to_trio, coro))
|
|
|
|
else:
|
2020-10-14 16:51:41 +00:00
|
|
|
raise TypeError(f"No support for invoking {coro}")
|
2020-07-21 14:32:37 +00:00
|
|
|
|
2020-10-14 16:51:41 +00:00
|
|
|
aio_err = None
|
2020-06-29 02:44:16 +00:00
|
|
|
|
|
|
|
def cancel_trio(task):
|
|
|
|
"""Cancel the calling ``trio`` task on error.
|
|
|
|
"""
|
2020-12-10 18:48:40 +00:00
|
|
|
nonlocal aio_err
|
2020-10-14 16:51:41 +00:00
|
|
|
aio_err = task.exception()
|
2020-12-10 18:48:40 +00:00
|
|
|
|
2020-10-14 16:51:41 +00:00
|
|
|
if aio_err:
|
|
|
|
log.exception(f"asyncio task errorred:\n{aio_err}")
|
2020-12-10 18:48:40 +00:00
|
|
|
|
2020-06-29 02:44:16 +00:00
|
|
|
cancel_scope.cancel()
|
|
|
|
|
|
|
|
task.add_done_callback(cancel_trio)
|
|
|
|
|
2020-10-14 16:51:41 +00:00
|
|
|
# async iterator
|
2020-07-03 21:33:46 +00:00
|
|
|
if inspect.isasyncgen(coro) or _treat_as_stream:
|
2020-07-21 14:32:37 +00:00
|
|
|
|
|
|
|
async def stream_results():
|
2020-10-14 16:51:41 +00:00
|
|
|
try:
|
|
|
|
with cancel_scope:
|
|
|
|
# stream values upward
|
|
|
|
async with from_aio:
|
|
|
|
async for item in from_aio:
|
|
|
|
yield item
|
2020-12-10 18:48:40 +00:00
|
|
|
|
|
|
|
if cancel_scope.cancelled_caught:
|
|
|
|
# always raise from any captured asyncio error
|
|
|
|
if aio_err:
|
|
|
|
raise aio_err
|
|
|
|
|
2020-10-14 16:51:41 +00:00
|
|
|
except BaseException as err:
|
|
|
|
if aio_err is not None:
|
|
|
|
# always raise from any captured asyncio error
|
|
|
|
raise err from aio_err
|
|
|
|
else:
|
|
|
|
raise
|
2020-06-29 02:44:16 +00:00
|
|
|
|
2020-07-21 14:32:37 +00:00
|
|
|
return stream_results()
|
2020-07-03 21:33:46 +00:00
|
|
|
|
|
|
|
# simple async func
|
2020-10-14 16:51:41 +00:00
|
|
|
try:
|
2020-07-03 21:33:46 +00:00
|
|
|
with cancel_scope:
|
2020-07-21 14:32:37 +00:00
|
|
|
# return single value
|
|
|
|
return await from_aio.receive()
|
2020-06-29 02:44:16 +00:00
|
|
|
|
2020-12-10 18:48:40 +00:00
|
|
|
if cancel_scope.cancelled_caught:
|
|
|
|
# always raise from any captured asyncio error
|
|
|
|
if aio_err:
|
|
|
|
raise aio_err
|
|
|
|
|
2020-10-14 16:51:41 +00:00
|
|
|
# Do we need this?
|
|
|
|
except BaseException as err:
|
|
|
|
if aio_err is not None:
|
|
|
|
# always raise from any captured asyncio error
|
|
|
|
raise err from aio_err
|
|
|
|
else:
|
|
|
|
raise
|
2020-06-29 02:44:16 +00:00
|
|
|
|
2020-09-12 15:41:17 +00:00
|
|
|
|
2020-06-29 02:44:16 +00:00
|
|
|
def run_as_asyncio_guest(
|
2020-07-21 14:32:37 +00:00
|
|
|
trio_main: Callable,
|
2020-06-29 02:44:16 +00:00
|
|
|
) -> None:
|
|
|
|
"""Entry for an "infected ``asyncio`` actor".
|
|
|
|
|
|
|
|
Uh, oh. :o
|
|
|
|
|
|
|
|
It looks like your event loop has caught a case of the ``trio``s.
|
|
|
|
|
|
|
|
:()
|
|
|
|
|
|
|
|
Don't worry, we've heard you'll barely notice. You might hallucinate
|
|
|
|
a few more propagating errors and feel like your digestion has
|
|
|
|
slowed but if anything get's too bad your parents will know about
|
|
|
|
it.
|
|
|
|
|
|
|
|
:)
|
|
|
|
"""
|
|
|
|
async def aio_main(trio_main):
|
|
|
|
loop = asyncio.get_running_loop()
|
|
|
|
|
|
|
|
trio_done_fut = asyncio.Future()
|
|
|
|
|
|
|
|
def trio_done_callback(main_outcome):
|
|
|
|
log.info(f"trio_main finished: {main_outcome!r}")
|
|
|
|
trio_done_fut.set_result(main_outcome)
|
|
|
|
|
|
|
|
# start the infection: run trio on the asyncio loop in "guest mode"
|
|
|
|
log.info(f"Infecting asyncio process with {trio_main}")
|
|
|
|
trio.lowlevel.start_guest_run(
|
|
|
|
trio_main,
|
|
|
|
run_sync_soon_threadsafe=loop.call_soon_threadsafe,
|
|
|
|
done_callback=trio_done_callback,
|
|
|
|
)
|
|
|
|
|
|
|
|
(await trio_done_fut).unwrap()
|
|
|
|
|
|
|
|
# might as well if it's installed.
|
|
|
|
try:
|
|
|
|
import uvloop
|
|
|
|
loop = uvloop.new_event_loop()
|
|
|
|
asyncio.set_event_loop(loop)
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
asyncio.run(aio_main(trio_main))
|