2021-08-02 16:36:40 +00:00
|
|
|
'''
|
2020-06-29 02:44:16 +00:00
|
|
|
Infection apis for ``asyncio`` loops running ``trio`` using guest mode.
|
2021-08-02 16:36:40 +00:00
|
|
|
|
|
|
|
'''
|
2020-06-29 02:44:16 +00:00
|
|
|
import asyncio
|
2021-11-17 18:20:04 +00:00
|
|
|
from asyncio.exceptions import CancelledError
|
2021-10-08 03:14:34 +00:00
|
|
|
from contextlib import asynccontextmanager as acm
|
2020-06-29 02:44:16 +00:00
|
|
|
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,
|
2021-10-08 03:14:34 +00:00
|
|
|
Optional,
|
2020-06-29 02:44:16 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
import trio
|
|
|
|
|
2021-11-17 18:20:04 +00:00
|
|
|
from .log import get_logger
|
2020-06-29 02:44:16 +00:00
|
|
|
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
|
|
|
|
|
|
|
|
2021-04-27 16:20:33 +00:00
|
|
|
def _run_asyncio_task(
|
2020-06-29 02:44:16 +00:00
|
|
|
func: Callable,
|
2020-07-03 21:33:46 +00:00
|
|
|
*,
|
2021-04-27 16:20:33 +00:00
|
|
|
qsize: int = 1,
|
2021-10-08 03:14:34 +00:00
|
|
|
provide_channels: bool = False,
|
2020-06-29 02:44:16 +00:00
|
|
|
**kwargs,
|
2021-10-08 03:14:34 +00:00
|
|
|
|
2020-10-14 16:51:41 +00:00
|
|
|
) -> Any:
|
2021-10-14 21:33:56 +00:00
|
|
|
'''
|
2021-10-08 03:14:34 +00:00
|
|
|
Run an ``asyncio`` async function or generator in a task, return
|
2020-06-29 02:44:16 +00:00
|
|
|
or stream the result back to ``trio``.
|
2021-04-27 16:20:33 +00:00
|
|
|
|
2021-10-14 21:33:56 +00:00
|
|
|
'''
|
2021-09-18 18:10:21 +00:00
|
|
|
if not current_actor().is_infected_aio():
|
|
|
|
raise RuntimeError("`infect_asyncio` mode is not enabled!?")
|
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
|
|
|
|
2021-04-27 16:20:33 +00:00
|
|
|
from_aio._err = None
|
|
|
|
|
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
|
2021-04-27 16:20:33 +00:00
|
|
|
assert qsize > 1
|
2020-07-03 21:33:46 +00:00
|
|
|
|
2021-10-08 03:14:34 +00:00
|
|
|
if provide_channels:
|
|
|
|
assert 'to_trio' in args
|
|
|
|
|
2020-07-03 21:33:46 +00:00
|
|
|
# allow target func to accept/stream results manually by name
|
|
|
|
if 'to_trio' in args:
|
|
|
|
kwargs['to_trio'] = to_trio
|
2021-04-27 16:20:33 +00:00
|
|
|
|
2020-07-03 21:33:46 +00:00
|
|
|
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)
|
|
|
|
|
2021-07-28 16:32:46 +00:00
|
|
|
cancel_scope = trio.CancelScope()
|
2021-10-08 03:14:34 +00:00
|
|
|
aio_task_complete = trio.Event()
|
|
|
|
aio_err: Optional[BaseException] = None
|
|
|
|
|
|
|
|
async def wait_on_coro_final_result(
|
|
|
|
to_trio: trio.MemorySendChannel,
|
|
|
|
coro: Awaitable,
|
|
|
|
aio_task_complete: trio.Event,
|
|
|
|
|
|
|
|
) -> None:
|
2021-10-14 21:33:56 +00:00
|
|
|
'''
|
2021-10-08 03:14:34 +00:00
|
|
|
Await ``coro`` and relay result back to ``trio``.
|
|
|
|
|
2021-10-14 21:33:56 +00:00
|
|
|
'''
|
2021-10-08 03:14:34 +00:00
|
|
|
nonlocal aio_err
|
|
|
|
orig = result = id(coro)
|
|
|
|
try:
|
|
|
|
result = await coro
|
|
|
|
except BaseException as err:
|
|
|
|
aio_err = err
|
|
|
|
from_aio._err = aio_err
|
2021-10-14 21:30:18 +00:00
|
|
|
raise
|
2021-10-08 03:14:34 +00:00
|
|
|
finally:
|
|
|
|
aio_task_complete.set()
|
|
|
|
if result != orig and aio_err is None:
|
|
|
|
to_trio.send_nowait(result)
|
2020-06-29 02:44:16 +00:00
|
|
|
|
|
|
|
# start the asyncio task we submitted from trio
|
2020-07-21 14:32:37 +00:00
|
|
|
if inspect.isawaitable(coro):
|
2021-10-08 03:14:34 +00:00
|
|
|
task = asyncio.create_task(
|
|
|
|
wait_on_coro_final_result(to_trio, coro, aio_task_complete)
|
|
|
|
)
|
2021-04-27 16:20:33 +00:00
|
|
|
|
2020-07-21 14:32:37 +00:00
|
|
|
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
|
|
|
|
2021-10-14 21:30:18 +00:00
|
|
|
def cancel_trio(task) -> None:
|
|
|
|
'''
|
|
|
|
Cancel the calling ``trio`` task on error.
|
|
|
|
|
|
|
|
'''
|
2020-12-10 18:48:40 +00:00
|
|
|
nonlocal aio_err
|
2021-05-12 03:43:33 +00:00
|
|
|
try:
|
|
|
|
aio_err = task.exception()
|
2021-11-17 18:20:04 +00:00
|
|
|
except CancelledError as cerr:
|
|
|
|
log.exception("infected task was cancelled")
|
|
|
|
# raise
|
2021-05-12 03:43:33 +00:00
|
|
|
aio_err = cerr
|
2020-12-10 18:48:40 +00:00
|
|
|
|
2020-10-14 16:51:41 +00:00
|
|
|
if aio_err:
|
2021-11-17 18:20:04 +00:00
|
|
|
log.exception(f"infected task errorred with {type(aio_err)}")
|
2021-10-08 03:14:34 +00:00
|
|
|
from_aio._err = aio_err
|
|
|
|
from_aio.close()
|
2021-11-17 18:20:04 +00:00
|
|
|
cancel_scope.cancel()
|
2020-06-29 02:44:16 +00:00
|
|
|
|
|
|
|
task.add_done_callback(cancel_trio)
|
|
|
|
|
2021-10-08 03:14:34 +00:00
|
|
|
return task, from_aio, to_trio, cancel_scope, aio_task_complete
|
2021-04-27 16:20:33 +00:00
|
|
|
|
|
|
|
|
|
|
|
async def run_task(
|
|
|
|
func: Callable,
|
|
|
|
*,
|
2021-08-02 16:36:40 +00:00
|
|
|
|
2021-04-27 16:20:33 +00:00
|
|
|
qsize: int = 2**10,
|
|
|
|
**kwargs,
|
2021-08-02 16:36:40 +00:00
|
|
|
|
2021-04-27 16:20:33 +00:00
|
|
|
) -> Any:
|
2021-11-17 18:20:04 +00:00
|
|
|
'''
|
|
|
|
Run an ``asyncio`` async function or generator in a task, return
|
2021-04-27 16:20:33 +00:00
|
|
|
or stream the result back to ``trio``.
|
|
|
|
|
2021-11-17 18:20:04 +00:00
|
|
|
'''
|
2020-07-03 21:33:46 +00:00
|
|
|
# simple async func
|
2020-10-14 16:51:41 +00:00
|
|
|
try:
|
2021-10-08 03:14:34 +00:00
|
|
|
task, from_aio, to_trio, cs, _ = _run_asyncio_task(
|
2021-04-27 16:20:33 +00:00
|
|
|
func,
|
|
|
|
qsize=1,
|
|
|
|
**kwargs,
|
|
|
|
)
|
|
|
|
|
2021-08-02 16:36:40 +00:00
|
|
|
# return single value
|
2021-07-28 16:32:46 +00:00
|
|
|
with cs:
|
2021-10-08 03:14:34 +00:00
|
|
|
# naively expect the mem chan api to do the job
|
|
|
|
# of handling cross-framework cancellations / errors
|
2021-07-28 16:32:46 +00:00
|
|
|
return await from_aio.receive()
|
2020-06-29 02:44:16 +00:00
|
|
|
|
2021-07-28 16:32:46 +00:00
|
|
|
if cs.cancelled_caught:
|
2021-11-17 18:20:04 +00:00
|
|
|
aio_err = from_aio._err
|
|
|
|
|
2021-07-28 16:32:46 +00:00
|
|
|
# always raise from any captured asyncio error
|
2021-11-17 18:20:04 +00:00
|
|
|
if aio_err:
|
|
|
|
raise aio_err
|
2020-12-10 18:48:40 +00:00
|
|
|
|
2020-10-14 16:51:41 +00:00
|
|
|
# Do we need this?
|
2021-11-17 18:20:04 +00:00
|
|
|
except (
|
|
|
|
Exception,
|
|
|
|
CancelledError,
|
|
|
|
) as err:
|
2021-08-02 16:36:40 +00:00
|
|
|
|
2021-04-27 16:20:33 +00:00
|
|
|
aio_err = from_aio._err
|
2021-05-12 03:43:33 +00:00
|
|
|
|
2021-11-17 18:20:04 +00:00
|
|
|
if (
|
|
|
|
aio_err is not None and
|
|
|
|
type(aio_err) != CancelledError
|
|
|
|
):
|
2020-10-14 16:51:41 +00:00
|
|
|
# always raise from any captured asyncio error
|
|
|
|
raise err from aio_err
|
|
|
|
else:
|
|
|
|
raise
|
2021-11-17 18:20:04 +00:00
|
|
|
|
2021-09-18 18:10:21 +00:00
|
|
|
finally:
|
2021-10-08 03:14:34 +00:00
|
|
|
if not task.done():
|
|
|
|
task.cancel()
|
2021-04-27 16:20:33 +00:00
|
|
|
|
2021-11-17 18:20:04 +00:00
|
|
|
# if task.cancelled():
|
|
|
|
# ... do what ..
|
|
|
|
|
2021-04-27 16:20:33 +00:00
|
|
|
|
2021-10-14 21:33:56 +00:00
|
|
|
# TODO: explicitly api for the streaming case where
|
2021-08-02 16:36:40 +00:00
|
|
|
# we pull from the mem chan in an async generator?
|
|
|
|
# This ends up looking more like our ``Portal.open_stream_from()``
|
|
|
|
# NB: code below is untested.
|
|
|
|
|
|
|
|
|
2021-10-08 03:14:34 +00:00
|
|
|
@acm
|
|
|
|
async def open_channel_from(
|
|
|
|
target: Callable[[Any, ...], Any],
|
|
|
|
**kwargs,
|
|
|
|
|
|
|
|
) -> AsyncIterator[Any]:
|
|
|
|
|
|
|
|
try:
|
|
|
|
task, from_aio, to_trio, cs, aio_task_complete = _run_asyncio_task(
|
|
|
|
target,
|
|
|
|
qsize=2**8,
|
|
|
|
provide_channels=True,
|
|
|
|
**kwargs,
|
|
|
|
)
|
2021-08-02 16:36:40 +00:00
|
|
|
|
2021-10-08 03:14:34 +00:00
|
|
|
with cs:
|
|
|
|
# sync to "started()" call.
|
|
|
|
first = await from_aio.receive()
|
|
|
|
# stream values upward
|
|
|
|
async with from_aio:
|
|
|
|
yield first, from_aio
|
|
|
|
# await aio_task_complete.wait()
|
|
|
|
|
|
|
|
except BaseException as err:
|
|
|
|
|
|
|
|
aio_err = from_aio._err
|
|
|
|
|
|
|
|
if aio_err is not None:
|
|
|
|
# always raise from any captured asyncio error
|
|
|
|
raise err from aio_err
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
|
|
|
|
finally:
|
|
|
|
if cs.cancelled_caught:
|
|
|
|
# always raise from any captured asyncio error
|
|
|
|
if from_aio._err:
|
|
|
|
raise from_aio._err
|
|
|
|
|
|
|
|
if not task.done():
|
|
|
|
task.cancel()
|
2021-04-27 16:20:33 +00:00
|
|
|
|
2020-09-12 15:41:17 +00:00
|
|
|
|
2020-06-29 02:44:16 +00:00
|
|
|
def run_as_asyncio_guest(
|
2021-11-07 21:44:41 +00:00
|
|
|
|
2020-07-21 14:32:37 +00:00
|
|
|
trio_main: Callable,
|
2021-11-07 21:44:41 +00:00
|
|
|
|
2020-06-29 02:44:16 +00:00
|
|
|
) -> None:
|
2021-10-14 21:33:56 +00:00
|
|
|
'''
|
|
|
|
Entry for an "infected ``asyncio`` actor".
|
2020-06-29 02:44:16 +00:00
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
|
|
:)
|
2021-10-08 03:14:34 +00:00
|
|
|
|
2021-10-14 21:33:56 +00:00
|
|
|
'''
|
|
|
|
# Disable sigint handling in children? (nawp)
|
2021-10-08 03:14:34 +00:00
|
|
|
# import signal
|
|
|
|
# signal.signal(signal.SIGINT, signal.SIG_IGN)
|
|
|
|
|
2020-06-29 02:44:16 +00:00
|
|
|
async def aio_main(trio_main):
|
2020-12-10 18:49:11 +00:00
|
|
|
|
2020-06-29 02:44:16 +00:00
|
|
|
loop = asyncio.get_running_loop()
|
|
|
|
trio_done_fut = asyncio.Future()
|
|
|
|
|
|
|
|
def trio_done_callback(main_outcome):
|
2020-12-10 18:49:11 +00:00
|
|
|
|
2021-10-08 03:14:34 +00:00
|
|
|
print(f"trio_main finished: {main_outcome!r}")
|
2020-06-29 02:44:16 +00:00
|
|
|
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}")
|
2020-12-10 18:49:11 +00:00
|
|
|
|
2020-06-29 02:44:16 +00:00
|
|
|
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
|
|
|
|
|
2021-11-07 21:44:41 +00:00
|
|
|
return asyncio.run(aio_main(trio_main))
|