2018-07-14 20:09:05 +00:00
|
|
|
"""
|
|
|
|
Portal api
|
|
|
|
"""
|
|
|
|
import importlib
|
2018-09-21 04:31:30 +00:00
|
|
|
import inspect
|
2021-04-28 03:08:45 +00:00
|
|
|
from typing import (
|
|
|
|
Tuple, Any, Dict, Optional, Set,
|
|
|
|
Callable, AsyncGenerator
|
|
|
|
)
|
2019-01-21 05:45:54 +00:00
|
|
|
from functools import partial
|
|
|
|
from dataclasses import dataclass
|
2020-12-21 14:09:55 +00:00
|
|
|
import warnings
|
2018-07-14 20:09:05 +00:00
|
|
|
|
|
|
|
import trio
|
2019-02-16 02:59:42 +00:00
|
|
|
from async_generator import asynccontextmanager
|
2018-07-14 20:09:05 +00:00
|
|
|
|
|
|
|
from ._state import current_actor
|
2018-08-31 21:16:24 +00:00
|
|
|
from ._ipc import Channel
|
2018-07-14 20:09:05 +00:00
|
|
|
from .log import get_logger
|
2021-06-13 23:58:52 +00:00
|
|
|
from ._exceptions import (
|
|
|
|
unpack_error,
|
|
|
|
NoResult,
|
|
|
|
RemoteActorError,
|
|
|
|
ContextCancelled,
|
|
|
|
)
|
2021-04-27 14:03:00 +00:00
|
|
|
from ._streaming import Context, ReceiveMsgStream
|
2018-07-14 20:09:05 +00:00
|
|
|
|
|
|
|
|
2021-04-27 14:03:00 +00:00
|
|
|
log = get_logger(__name__)
|
2018-07-14 20:09:05 +00:00
|
|
|
|
|
|
|
|
|
|
|
@asynccontextmanager
|
2019-12-10 05:55:03 +00:00
|
|
|
async def maybe_open_nursery(
|
2020-08-08 18:47:52 +00:00
|
|
|
nursery: trio.Nursery = None,
|
|
|
|
shield: bool = False,
|
2021-04-28 03:08:45 +00:00
|
|
|
) -> AsyncGenerator[trio.Nursery, Any]:
|
2018-07-14 20:09:05 +00:00
|
|
|
"""Create a new nursery if None provided.
|
|
|
|
|
|
|
|
Blocks on exit as expected if no input nursery is provided.
|
|
|
|
"""
|
|
|
|
if nursery is not None:
|
|
|
|
yield nursery
|
|
|
|
else:
|
|
|
|
async with trio.open_nursery() as nursery:
|
2020-08-08 18:47:52 +00:00
|
|
|
nursery.cancel_scope.shield = shield
|
2018-07-14 20:09:05 +00:00
|
|
|
yield nursery
|
|
|
|
|
|
|
|
|
2021-04-28 03:08:45 +00:00
|
|
|
def func_deats(func: Callable) -> Tuple[str, str]:
|
|
|
|
return (
|
|
|
|
func.__module__,
|
|
|
|
func.__name__,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2018-07-14 20:09:05 +00:00
|
|
|
class Portal:
|
|
|
|
"""A 'portal' to a(n) (remote) ``Actor``.
|
|
|
|
|
2021-04-27 14:03:00 +00:00
|
|
|
A portal is "opened" (and eventually closed) by one side of an
|
|
|
|
inter-actor communication context. The side which opens the portal
|
|
|
|
is equivalent to a "caller" in function parlance and usually is
|
|
|
|
either the called actor's parent (in process tree hierarchy terms)
|
|
|
|
or a client interested in scheduling work to be done remotely in a
|
|
|
|
far process.
|
|
|
|
|
|
|
|
The portal api allows the "caller" actor to invoke remote routines
|
|
|
|
and receive results through an underlying ``tractor.Channel`` as
|
|
|
|
though the remote (async) function / generator was called locally.
|
|
|
|
It may be thought of loosely as an RPC api where native Python
|
|
|
|
function calling semantics are supported transparently; hence it is
|
|
|
|
like having a "portal" between the seperate actor memory spaces.
|
2018-07-14 20:09:05 +00:00
|
|
|
|
|
|
|
"""
|
2018-08-31 21:16:24 +00:00
|
|
|
def __init__(self, channel: Channel) -> None:
|
2018-07-14 20:09:05 +00:00
|
|
|
self.channel = channel
|
2018-08-01 19:15:18 +00:00
|
|
|
# when this is set to a tuple returned from ``_submit()`` then
|
|
|
|
# it is expected that ``result()`` will be awaited at some point
|
|
|
|
# during the portal's lifetime
|
2018-11-19 13:47:42 +00:00
|
|
|
self._result: Optional[Any] = None
|
2018-11-19 09:05:07 +00:00
|
|
|
# set when _submit_for_result is called
|
2018-08-31 21:16:24 +00:00
|
|
|
self._expect_result: Optional[
|
|
|
|
Tuple[str, Any, str, Dict[str, Any]]
|
|
|
|
] = None
|
2021-04-27 14:03:00 +00:00
|
|
|
self._streams: Set[ReceiveMsgStream] = set()
|
2019-03-23 17:50:23 +00:00
|
|
|
self.actor = current_actor()
|
2018-07-14 20:09:05 +00:00
|
|
|
|
2018-08-20 02:13:13 +00:00
|
|
|
async def _submit(
|
2019-02-15 21:27:18 +00:00
|
|
|
self,
|
|
|
|
ns: str,
|
|
|
|
func: str,
|
|
|
|
kwargs,
|
2021-06-13 23:58:52 +00:00
|
|
|
) -> Tuple[str, trio.MemoryReceiveChannel, str, Dict[str, Any]]:
|
2018-08-01 19:15:18 +00:00
|
|
|
"""Submit a function to be scheduled and run by actor, return the
|
|
|
|
associated caller id, response queue, response type str,
|
|
|
|
first message packet as a tuple.
|
|
|
|
|
|
|
|
This is an async call.
|
|
|
|
"""
|
|
|
|
# ship a function call request to the remote actor
|
2019-03-23 17:50:23 +00:00
|
|
|
cid, recv_chan = await self.actor.send_cmd(
|
2019-02-15 21:27:18 +00:00
|
|
|
self.channel, ns, func, kwargs)
|
2018-08-01 19:15:18 +00:00
|
|
|
|
|
|
|
# wait on first response msg and handle (this should be
|
|
|
|
# in an immediate response)
|
2019-02-15 21:27:18 +00:00
|
|
|
|
|
|
|
first_msg = await recv_chan.receive()
|
2018-08-01 19:15:18 +00:00
|
|
|
functype = first_msg.get('functype')
|
|
|
|
|
2021-04-27 14:03:00 +00:00
|
|
|
if 'error' in first_msg:
|
2018-11-19 09:05:07 +00:00
|
|
|
raise unpack_error(first_msg, self.channel)
|
2021-04-27 14:03:00 +00:00
|
|
|
|
|
|
|
elif functype not in ('asyncfunc', 'asyncgen', 'context'):
|
2018-08-01 19:15:18 +00:00
|
|
|
raise ValueError(f"{first_msg} is an invalid response packet?")
|
|
|
|
|
2021-04-27 14:03:00 +00:00
|
|
|
return cid, recv_chan, functype, first_msg
|
2018-08-01 19:15:18 +00:00
|
|
|
|
2018-08-20 02:13:13 +00:00
|
|
|
async def _submit_for_result(self, ns: str, func: str, **kwargs) -> None:
|
2021-04-28 15:38:31 +00:00
|
|
|
|
2018-08-01 19:15:18 +00:00
|
|
|
assert self._expect_result is None, \
|
|
|
|
"A pending main result has already been submitted"
|
2021-04-28 15:38:31 +00:00
|
|
|
|
2019-02-15 21:27:18 +00:00
|
|
|
self._expect_result = await self._submit(ns, func, kwargs)
|
2018-08-01 19:15:18 +00:00
|
|
|
|
2021-04-28 03:08:45 +00:00
|
|
|
async def _return_once(
|
2019-02-15 21:27:18 +00:00
|
|
|
self,
|
|
|
|
cid: str,
|
|
|
|
recv_chan: trio.abc.ReceiveChannel,
|
|
|
|
resptype: str,
|
|
|
|
first_msg: dict
|
2018-08-31 21:16:24 +00:00
|
|
|
) -> Any:
|
2021-04-28 03:08:45 +00:00
|
|
|
assert resptype == 'asyncfunc' # single response
|
2021-04-27 14:03:00 +00:00
|
|
|
|
2021-04-28 03:08:45 +00:00
|
|
|
msg = await recv_chan.receive()
|
|
|
|
try:
|
|
|
|
return msg['return']
|
|
|
|
except KeyError:
|
|
|
|
# internal error should never get here
|
|
|
|
assert msg.get('cid'), "Received internal error at portal?"
|
|
|
|
raise unpack_error(msg, self.channel)
|
2018-07-14 20:09:05 +00:00
|
|
|
|
2018-08-31 21:16:24 +00:00
|
|
|
async def result(self) -> Any:
|
2018-07-14 20:09:05 +00:00
|
|
|
"""Return the result(s) from the remote actor's "main" task.
|
|
|
|
"""
|
2018-11-19 09:05:07 +00:00
|
|
|
# Check for non-rpc errors slapped on the
|
|
|
|
# channel for which we always raise
|
|
|
|
exc = self.channel._exc
|
|
|
|
if exc:
|
|
|
|
raise exc
|
|
|
|
|
|
|
|
# not expecting a "main" result
|
2018-08-01 19:15:18 +00:00
|
|
|
if self._expect_result is None:
|
2019-01-21 05:45:54 +00:00
|
|
|
log.warning(
|
2018-11-19 09:05:07 +00:00
|
|
|
f"Portal for {self.channel.uid} not expecting a final"
|
|
|
|
" result?\nresult() should only be called if subactor"
|
|
|
|
" was spawned with `ActorNursery.run_in_actor()`")
|
|
|
|
return NoResult
|
|
|
|
|
|
|
|
# expecting a "main" result
|
|
|
|
assert self._expect_result
|
|
|
|
if self._result is None:
|
|
|
|
try:
|
2021-04-28 03:08:45 +00:00
|
|
|
self._result = await self._return_once(*self._expect_result)
|
2018-11-19 09:05:07 +00:00
|
|
|
except RemoteActorError as err:
|
|
|
|
self._result = err
|
|
|
|
|
|
|
|
# re-raise error on every call
|
|
|
|
if isinstance(self._result, RemoteActorError):
|
|
|
|
raise self._result
|
|
|
|
|
2018-07-14 20:09:05 +00:00
|
|
|
return self._result
|
|
|
|
|
2019-02-16 02:59:42 +00:00
|
|
|
async def _cancel_streams(self):
|
|
|
|
# terminate all locally running async generator
|
|
|
|
# IPC calls
|
|
|
|
if self._streams:
|
|
|
|
log.warning(
|
|
|
|
f"Cancelling all streams with {self.channel.uid}")
|
|
|
|
for stream in self._streams.copy():
|
2020-12-21 14:09:55 +00:00
|
|
|
try:
|
2021-06-24 23:56:05 +00:00
|
|
|
# with trio.CancelScope(shield=True):
|
2020-12-21 14:09:55 +00:00
|
|
|
await stream.aclose()
|
|
|
|
except trio.ClosedResourceError:
|
|
|
|
# don't error the stream having already been closed
|
|
|
|
# (unless of course at some point down the road we
|
|
|
|
# won't expect this to always be the case or need to
|
|
|
|
# detect it for respawning purposes?)
|
|
|
|
log.debug(f"{stream} was already closed.")
|
2019-01-21 05:45:54 +00:00
|
|
|
|
2019-12-10 05:55:03 +00:00
|
|
|
async def aclose(self):
|
2019-02-16 02:59:42 +00:00
|
|
|
log.debug(f"Closing {self}")
|
2019-02-15 21:27:18 +00:00
|
|
|
# TODO: once we move to implementing our own `ReceiveChannel`
|
|
|
|
# (including remote task cancellation inside its `.aclose()`)
|
|
|
|
# we'll need to .aclose all those channels here
|
2019-02-16 02:59:42 +00:00
|
|
|
await self._cancel_streams()
|
2018-07-14 20:09:05 +00:00
|
|
|
|
2019-12-10 05:55:03 +00:00
|
|
|
async def cancel_actor(self):
|
2018-07-14 20:09:05 +00:00
|
|
|
"""Cancel the actor on the other end of this portal.
|
|
|
|
"""
|
2019-01-21 05:45:54 +00:00
|
|
|
if not self.channel.connected():
|
|
|
|
log.warning("This portal is already closed can't cancel")
|
|
|
|
return False
|
|
|
|
|
2019-02-16 02:59:42 +00:00
|
|
|
await self._cancel_streams()
|
2019-01-21 05:45:54 +00:00
|
|
|
|
2018-09-10 19:19:49 +00:00
|
|
|
log.warning(
|
2019-01-21 05:45:54 +00:00
|
|
|
f"Sending actor cancel request to {self.channel.uid} on "
|
2018-07-14 20:09:05 +00:00
|
|
|
f"{self.channel}")
|
|
|
|
try:
|
2019-01-21 05:45:54 +00:00
|
|
|
# send cancel cmd - might not get response
|
2020-08-08 18:47:52 +00:00
|
|
|
# XXX: sure would be nice to make this work with a proper shield
|
2020-09-28 17:56:42 +00:00
|
|
|
# with trio.CancelScope() as cancel_scope:
|
|
|
|
# with trio.CancelScope(shield=True) as cancel_scope:
|
2019-01-21 05:45:54 +00:00
|
|
|
with trio.move_on_after(0.5) as cancel_scope:
|
2018-07-14 20:09:05 +00:00
|
|
|
cancel_scope.shield = True
|
2020-12-22 15:19:52 +00:00
|
|
|
|
|
|
|
await self.run_from_ns('self', 'cancel')
|
2018-07-14 20:09:05 +00:00
|
|
|
return True
|
2020-12-22 15:19:52 +00:00
|
|
|
|
2019-01-24 00:17:03 +00:00
|
|
|
if cancel_scope.cancelled_caught:
|
|
|
|
log.warning(f"May have failed to cancel {self.channel.uid}")
|
2019-12-10 05:55:03 +00:00
|
|
|
|
|
|
|
# if we get here some weird cancellation case happened
|
|
|
|
return False
|
2020-12-22 15:19:52 +00:00
|
|
|
|
2018-07-25 04:43:31 +00:00
|
|
|
except trio.ClosedResourceError:
|
2018-09-10 19:19:49 +00:00
|
|
|
log.warning(
|
2018-07-14 20:09:05 +00:00
|
|
|
f"{self.channel} for {self.channel.uid} was already closed?")
|
|
|
|
return False
|
|
|
|
|
2021-04-28 03:08:45 +00:00
|
|
|
async def run_from_ns(
|
|
|
|
self,
|
|
|
|
namespace_path: str,
|
|
|
|
function_name: str,
|
|
|
|
**kwargs,
|
|
|
|
) -> Any:
|
|
|
|
"""Run a function from a (remote) namespace in a new task on the far-end actor.
|
|
|
|
|
|
|
|
This is a more explitcit way to run tasks in a remote-process
|
|
|
|
actor using explicit object-path syntax. Hint: this is how
|
|
|
|
`.run()` works underneath.
|
|
|
|
|
|
|
|
Note::
|
|
|
|
|
|
|
|
A special namespace `self` can be used to invoke `Actor`
|
|
|
|
instance methods in the remote runtime. Currently this should only
|
|
|
|
be used for `tractor` internals.
|
|
|
|
"""
|
|
|
|
return await self._return_once(
|
|
|
|
*(await self._submit(namespace_path, function_name, kwargs))
|
|
|
|
)
|
|
|
|
|
2021-04-27 14:03:00 +00:00
|
|
|
async def run(
|
|
|
|
self,
|
|
|
|
func: str,
|
|
|
|
fn_name: Optional[str] = None,
|
|
|
|
**kwargs
|
|
|
|
) -> Any:
|
|
|
|
"""Submit a remote function to be scheduled and run by actor, in
|
|
|
|
a new task, wrap and return its (stream of) result(s).
|
|
|
|
|
|
|
|
This is a blocking call and returns either a value from the
|
|
|
|
remote rpc task or a local async generator instance.
|
|
|
|
"""
|
|
|
|
if isinstance(func, str):
|
|
|
|
warnings.warn(
|
|
|
|
"`Portal.run(namespace: str, funcname: str)` is now"
|
|
|
|
"deprecated, pass a function reference directly instead\n"
|
|
|
|
"If you still want to run a remote function by name use"
|
|
|
|
"`Portal.run_from_ns()`",
|
|
|
|
DeprecationWarning,
|
|
|
|
stacklevel=2,
|
|
|
|
)
|
|
|
|
fn_mod_path = func
|
|
|
|
assert isinstance(fn_name, str)
|
|
|
|
|
|
|
|
else: # function reference was passed directly
|
2021-04-28 15:38:31 +00:00
|
|
|
if (
|
|
|
|
not inspect.iscoroutinefunction(func) or
|
|
|
|
(
|
|
|
|
inspect.iscoroutinefunction(func) and
|
|
|
|
getattr(func, '_tractor_stream_function', False)
|
|
|
|
)
|
2021-04-27 14:03:00 +00:00
|
|
|
):
|
2021-04-28 15:38:31 +00:00
|
|
|
raise TypeError(
|
|
|
|
f'{func} must be a non-streaming async function!')
|
2021-04-27 14:03:00 +00:00
|
|
|
|
2021-04-28 03:08:45 +00:00
|
|
|
fn_mod_path, fn_name = func_deats(func)
|
2021-04-27 14:03:00 +00:00
|
|
|
|
2021-04-28 03:08:45 +00:00
|
|
|
return await self._return_once(
|
2021-04-27 14:03:00 +00:00
|
|
|
*(await self._submit(fn_mod_path, fn_name, kwargs))
|
|
|
|
)
|
|
|
|
|
2021-04-28 03:08:45 +00:00
|
|
|
@asynccontextmanager
|
|
|
|
async def open_stream_from(
|
|
|
|
self,
|
|
|
|
async_gen_func: Callable, # typing: ignore
|
|
|
|
**kwargs,
|
2021-06-28 04:18:28 +00:00
|
|
|
|
2021-04-28 03:08:45 +00:00
|
|
|
) -> AsyncGenerator[ReceiveMsgStream, None]:
|
|
|
|
|
|
|
|
if not inspect.isasyncgenfunction(async_gen_func):
|
2021-04-28 15:38:31 +00:00
|
|
|
if not (
|
|
|
|
inspect.iscoroutinefunction(async_gen_func) and
|
|
|
|
getattr(async_gen_func, '_tractor_stream_function', False)
|
2021-04-28 03:08:45 +00:00
|
|
|
):
|
|
|
|
raise TypeError(
|
|
|
|
f'{async_gen_func} must be an async generator function!')
|
|
|
|
|
|
|
|
fn_mod_path, fn_name = func_deats(async_gen_func)
|
|
|
|
(
|
|
|
|
cid,
|
|
|
|
recv_chan,
|
|
|
|
functype,
|
|
|
|
first_msg
|
|
|
|
) = await self._submit(fn_mod_path, fn_name, kwargs)
|
|
|
|
|
|
|
|
# receive only stream
|
|
|
|
assert functype == 'asyncgen'
|
|
|
|
|
|
|
|
ctx = Context(self.channel, cid, _portal=self)
|
|
|
|
try:
|
2021-05-01 19:10:03 +00:00
|
|
|
# deliver receive only stream
|
|
|
|
async with ReceiveMsgStream(ctx, recv_chan) as rchan:
|
2021-04-28 03:08:45 +00:00
|
|
|
self._streams.add(rchan)
|
|
|
|
yield rchan
|
2021-05-01 19:10:03 +00:00
|
|
|
|
2021-04-28 03:08:45 +00:00
|
|
|
finally:
|
2021-05-01 19:10:03 +00:00
|
|
|
|
2021-04-28 03:08:45 +00:00
|
|
|
# cancel the far end task on consumer close
|
2021-05-01 19:10:03 +00:00
|
|
|
# NOTE: this is a special case since we assume that if using
|
|
|
|
# this ``.open_fream_from()`` api, the stream is one a one
|
|
|
|
# time use and we couple the far end tasks's lifetime to
|
|
|
|
# the consumer's scope; we don't ever send a `'stop'`
|
|
|
|
# message right now since there shouldn't be a reason to
|
|
|
|
# stop and restart the stream, right?
|
2021-04-28 03:08:45 +00:00
|
|
|
try:
|
|
|
|
await ctx.cancel()
|
2021-06-13 23:58:52 +00:00
|
|
|
|
2021-04-28 03:08:45 +00:00
|
|
|
except trio.ClosedResourceError:
|
|
|
|
# if the far end terminates before we send a cancel the
|
|
|
|
# underlying transport-channel may already be closed.
|
|
|
|
log.debug(f'Context {ctx} was already closed?')
|
|
|
|
|
|
|
|
self._streams.remove(rchan)
|
2021-04-27 14:03:00 +00:00
|
|
|
|
2021-05-01 19:10:03 +00:00
|
|
|
@asynccontextmanager
|
|
|
|
async def open_context(
|
2021-06-13 23:58:52 +00:00
|
|
|
|
2021-05-01 19:10:03 +00:00
|
|
|
self,
|
|
|
|
func: Callable,
|
|
|
|
**kwargs,
|
2021-06-13 23:58:52 +00:00
|
|
|
|
2021-05-07 15:52:08 +00:00
|
|
|
) -> AsyncGenerator[Tuple[Context, Any], None]:
|
2021-06-13 23:58:52 +00:00
|
|
|
'''Open an inter-actor task context.
|
2021-05-01 19:10:03 +00:00
|
|
|
|
|
|
|
This is a synchronous API which allows for deterministic
|
|
|
|
setup/teardown of a remote task. The yielded ``Context`` further
|
2021-06-13 23:58:52 +00:00
|
|
|
allows for opening bidirectional streams, explicit cancellation
|
|
|
|
and synchronized final result collection. See ``tractor.Context``.
|
2021-05-01 19:10:03 +00:00
|
|
|
|
2021-06-13 23:58:52 +00:00
|
|
|
'''
|
2021-06-28 04:18:28 +00:00
|
|
|
|
2021-05-01 19:10:03 +00:00
|
|
|
# conduct target func method structural checks
|
|
|
|
if not inspect.iscoroutinefunction(func) and (
|
|
|
|
getattr(func, '_tractor_contex_function', False)
|
|
|
|
):
|
|
|
|
raise TypeError(
|
|
|
|
f'{func} must be an async generator function!')
|
|
|
|
|
|
|
|
fn_mod_path, fn_name = func_deats(func)
|
|
|
|
|
2021-06-13 23:58:52 +00:00
|
|
|
recv_chan: Optional[trio.MemoryReceiveChannel] = None
|
2021-05-01 19:10:03 +00:00
|
|
|
|
2021-06-24 23:56:05 +00:00
|
|
|
cid, recv_chan, functype, first_msg = await self._submit(
|
|
|
|
fn_mod_path, fn_name, kwargs)
|
|
|
|
|
|
|
|
assert functype == 'context'
|
|
|
|
msg = await recv_chan.receive()
|
|
|
|
|
2021-05-01 19:10:03 +00:00
|
|
|
try:
|
2021-06-24 23:56:05 +00:00
|
|
|
# the "first" value here is delivered by the callee's
|
|
|
|
# ``Context.started()`` call.
|
|
|
|
first = msg['started']
|
2021-05-01 19:10:03 +00:00
|
|
|
|
2021-06-24 23:56:05 +00:00
|
|
|
except KeyError:
|
|
|
|
assert msg.get('cid'), ("Received internal error at context?")
|
2021-05-01 19:10:03 +00:00
|
|
|
|
2021-06-24 23:56:05 +00:00
|
|
|
if msg.get('error'):
|
|
|
|
# raise the error message
|
|
|
|
raise unpack_error(msg, self.channel)
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
|
2021-07-08 16:48:34 +00:00
|
|
|
_err: Optional[BaseException] = None
|
|
|
|
# deliver context instance and .started() msg value in open tuple.
|
2021-06-24 23:56:05 +00:00
|
|
|
try:
|
|
|
|
async with trio.open_nursery() as scope_nursery:
|
|
|
|
ctx = Context(
|
|
|
|
self.channel,
|
|
|
|
cid,
|
|
|
|
_portal=self,
|
|
|
|
_recv_chan=recv_chan,
|
|
|
|
_scope_nursery=scope_nursery,
|
|
|
|
)
|
2021-07-08 16:48:34 +00:00
|
|
|
|
|
|
|
# pairs with handling in ``Actor._push_result()``
|
|
|
|
# recv_chan._ctx = ctx
|
2021-06-13 23:58:52 +00:00
|
|
|
|
2021-06-28 04:18:28 +00:00
|
|
|
# await trio.lowlevel.checkpoint()
|
2021-05-10 11:23:39 +00:00
|
|
|
yield ctx, first
|
|
|
|
|
2021-06-28 04:18:28 +00:00
|
|
|
except ContextCancelled as err:
|
|
|
|
_err = err
|
2021-06-24 23:56:05 +00:00
|
|
|
if not ctx._cancel_called:
|
2021-06-28 04:18:28 +00:00
|
|
|
# context was cancelled at the far end but was
|
|
|
|
# not part of this end requesting that cancel
|
|
|
|
# so raise for the local task to respond and handle.
|
2021-06-13 23:58:52 +00:00
|
|
|
raise
|
|
|
|
|
2021-06-24 23:56:05 +00:00
|
|
|
# if the context was cancelled by client code
|
|
|
|
# then we don't need to raise since user code
|
|
|
|
# is expecting this and the block should exit.
|
|
|
|
else:
|
|
|
|
log.debug(f'Context {ctx} cancelled gracefully')
|
|
|
|
|
2021-06-28 04:18:28 +00:00
|
|
|
except (
|
|
|
|
trio.Cancelled,
|
|
|
|
trio.MultiError,
|
|
|
|
Exception,
|
|
|
|
) as err:
|
|
|
|
_err = err
|
|
|
|
# the context cancels itself on any cancel
|
|
|
|
# causing error.
|
|
|
|
log.error(f'Context {ctx} sending cancel to far end')
|
|
|
|
with trio.CancelScope(shield=True):
|
|
|
|
await ctx.cancel()
|
2021-06-24 23:56:05 +00:00
|
|
|
raise
|
|
|
|
|
2021-06-28 04:18:28 +00:00
|
|
|
finally:
|
|
|
|
result = await ctx.result()
|
|
|
|
|
|
|
|
# though it should be impossible for any tasks
|
|
|
|
# operating *in* this scope to have survived
|
|
|
|
# we tear down the runtime feeder chan last
|
|
|
|
# to avoid premature stream clobbers.
|
|
|
|
if recv_chan is not None:
|
|
|
|
await recv_chan.aclose()
|
|
|
|
|
|
|
|
if _err:
|
|
|
|
if ctx._cancel_called:
|
|
|
|
log.warning(
|
|
|
|
f'Context {fn_name} cancelled by caller with\n{_err}'
|
|
|
|
)
|
|
|
|
elif _err is not None:
|
|
|
|
log.warning(
|
|
|
|
f'Context {fn_name} cancelled by callee with\n{_err}'
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
log.info(
|
|
|
|
f'Context {fn_name} returned '
|
2021-07-08 16:48:34 +00:00
|
|
|
f'value from callee `{result}`'
|
2021-06-28 04:18:28 +00:00
|
|
|
)
|
2021-05-01 19:10:03 +00:00
|
|
|
|
2018-08-17 18:49:17 +00:00
|
|
|
|
2019-01-21 05:45:54 +00:00
|
|
|
@dataclass
|
2018-07-14 20:09:05 +00:00
|
|
|
class LocalPortal:
|
|
|
|
"""A 'portal' to a local ``Actor``.
|
|
|
|
|
|
|
|
A compatibility shim for normal portals but for invoking functions
|
|
|
|
using an in process actor instance.
|
|
|
|
"""
|
2020-12-17 16:58:48 +00:00
|
|
|
actor: 'Actor' # type: ignore # noqa
|
2020-02-09 06:59:10 +00:00
|
|
|
channel: Channel
|
2018-07-14 20:09:05 +00:00
|
|
|
|
2020-12-22 15:19:52 +00:00
|
|
|
async def run_from_ns(self, ns: str, func_name: str, **kwargs) -> Any:
|
|
|
|
"""Run a requested local function from a namespace path and
|
|
|
|
return it's result.
|
|
|
|
|
2018-07-14 20:09:05 +00:00
|
|
|
"""
|
|
|
|
obj = self.actor if ns == 'self' else importlib.import_module(ns)
|
2018-09-21 13:46:01 +00:00
|
|
|
func = getattr(obj, func_name)
|
2021-04-28 03:08:45 +00:00
|
|
|
return await func(**kwargs)
|
2018-07-14 20:09:05 +00:00
|
|
|
|
|
|
|
|
|
|
|
@asynccontextmanager
|
2018-08-20 02:13:13 +00:00
|
|
|
async def open_portal(
|
2021-06-28 04:18:28 +00:00
|
|
|
|
2018-08-31 21:16:24 +00:00
|
|
|
channel: Channel,
|
2020-07-23 17:23:36 +00:00
|
|
|
nursery: Optional[trio.Nursery] = None,
|
|
|
|
start_msg_loop: bool = True,
|
2020-08-08 18:47:52 +00:00
|
|
|
shield: bool = False,
|
2021-06-28 04:18:28 +00:00
|
|
|
|
2021-04-28 03:08:45 +00:00
|
|
|
) -> AsyncGenerator[Portal, None]:
|
2018-07-14 20:09:05 +00:00
|
|
|
"""Open a ``Portal`` through the provided ``channel``.
|
|
|
|
|
|
|
|
Spawns a background task to handle message processing.
|
|
|
|
"""
|
|
|
|
actor = current_actor()
|
|
|
|
assert actor
|
|
|
|
was_connected = False
|
|
|
|
|
2020-08-08 18:47:52 +00:00
|
|
|
async with maybe_open_nursery(nursery, shield=shield) as nursery:
|
2021-06-24 23:56:05 +00:00
|
|
|
|
2018-07-14 20:09:05 +00:00
|
|
|
if not channel.connected():
|
|
|
|
await channel.connect()
|
|
|
|
was_connected = True
|
|
|
|
|
|
|
|
if channel.uid is None:
|
2019-03-23 17:50:23 +00:00
|
|
|
await actor._do_handshake(channel)
|
2018-07-14 20:09:05 +00:00
|
|
|
|
2020-08-09 00:57:18 +00:00
|
|
|
msg_loop_cs: Optional[trio.CancelScope] = None
|
2020-07-23 17:23:36 +00:00
|
|
|
if start_msg_loop:
|
2020-08-09 00:57:18 +00:00
|
|
|
msg_loop_cs = await nursery.start(
|
2020-07-23 17:23:36 +00:00
|
|
|
partial(
|
|
|
|
actor._process_messages,
|
|
|
|
channel,
|
|
|
|
# if the local task is cancelled we want to keep
|
|
|
|
# the msg loop running until our block ends
|
|
|
|
shield=True,
|
|
|
|
)
|
2019-01-21 05:45:54 +00:00
|
|
|
)
|
2018-07-14 20:09:05 +00:00
|
|
|
portal = Portal(channel)
|
2018-12-15 07:20:55 +00:00
|
|
|
try:
|
|
|
|
yield portal
|
2021-06-24 23:56:05 +00:00
|
|
|
|
2018-12-15 07:20:55 +00:00
|
|
|
finally:
|
2019-02-15 21:27:18 +00:00
|
|
|
await portal.aclose()
|
2018-12-15 07:20:55 +00:00
|
|
|
|
2019-01-21 05:45:54 +00:00
|
|
|
if was_connected:
|
2021-06-24 23:56:05 +00:00
|
|
|
# gracefully signal remote channel-msg loop
|
2019-01-21 05:45:54 +00:00
|
|
|
await channel.send(None)
|
2021-06-28 04:18:28 +00:00
|
|
|
# await channel.aclose()
|
2018-12-15 07:20:55 +00:00
|
|
|
|
|
|
|
# cancel background msg loop task
|
2020-07-23 17:23:36 +00:00
|
|
|
if msg_loop_cs:
|
|
|
|
msg_loop_cs.cancel()
|
2019-01-24 00:17:03 +00:00
|
|
|
|
2018-12-15 07:20:55 +00:00
|
|
|
nursery.cancel_scope.cancel()
|