2019-01-16 17:19:01 +00:00
|
|
|
"""
|
|
|
|
Messaging pattern APIs and helpers.
|
|
|
|
"""
|
2019-01-25 05:10:13 +00:00
|
|
|
import inspect
|
2019-01-16 17:19:01 +00:00
|
|
|
import typing
|
2021-01-14 23:18:44 +00:00
|
|
|
from typing import Dict, Any, Set, Callable
|
2019-01-16 17:19:01 +00:00
|
|
|
from functools import partial
|
2019-01-21 13:35:43 +00:00
|
|
|
from async_generator import aclosing
|
2019-01-16 17:19:01 +00:00
|
|
|
|
|
|
|
import trio
|
|
|
|
import wrapt
|
|
|
|
|
|
|
|
from .log import get_logger
|
2019-03-29 23:10:32 +00:00
|
|
|
from ._streaming import Context
|
2019-01-16 17:19:01 +00:00
|
|
|
|
|
|
|
__all__ = ['pub']
|
|
|
|
|
|
|
|
log = get_logger('messaging')
|
|
|
|
|
|
|
|
|
|
|
|
async def fan_out_to_ctxs(
|
2019-01-21 13:35:43 +00:00
|
|
|
pub_async_gen_func: typing.Callable, # it's an async gen ... gd mypy
|
2019-01-16 21:50:30 +00:00
|
|
|
topics2ctxs: Dict[str, set],
|
2019-01-21 13:35:43 +00:00
|
|
|
packetizer: typing.Callable = None,
|
2019-01-16 17:19:01 +00:00
|
|
|
) -> None:
|
|
|
|
"""Request and fan out quotes to each subscribed actor channel.
|
|
|
|
"""
|
|
|
|
def get_topics():
|
|
|
|
return tuple(topics2ctxs.keys())
|
|
|
|
|
2019-01-21 13:35:43 +00:00
|
|
|
agen = pub_async_gen_func(get_topics=get_topics)
|
|
|
|
async with aclosing(agen) as pub_gen:
|
|
|
|
async for published in pub_gen:
|
|
|
|
ctx_payloads: Dict[str, Any] = {}
|
|
|
|
for topic, data in published.items():
|
|
|
|
log.debug(f"publishing {topic, data}")
|
|
|
|
# build a new dict packet or invoke provided packetizer
|
|
|
|
if packetizer is None:
|
|
|
|
packet = {topic: data}
|
|
|
|
else:
|
|
|
|
packet = packetizer(topic, data)
|
|
|
|
for ctx in topics2ctxs.get(topic, set()):
|
|
|
|
ctx_payloads.setdefault(ctx, {}).update(packet),
|
|
|
|
|
2019-02-16 19:05:24 +00:00
|
|
|
if not ctx_payloads:
|
|
|
|
log.debug(f"Unconsumed values:\n{published}")
|
|
|
|
|
2019-01-21 13:35:43 +00:00
|
|
|
# deliver to each subscriber (fan out)
|
|
|
|
if ctx_payloads:
|
|
|
|
for ctx, payload in ctx_payloads.items():
|
|
|
|
try:
|
|
|
|
await ctx.send_yield(payload)
|
|
|
|
except (
|
|
|
|
# That's right, anything you can think of...
|
2019-02-16 19:05:24 +00:00
|
|
|
trio.ClosedResourceError, ConnectionResetError,
|
2019-01-21 13:35:43 +00:00
|
|
|
ConnectionRefusedError,
|
|
|
|
):
|
|
|
|
log.warning(f"{ctx.chan} went down?")
|
|
|
|
for ctx_set in topics2ctxs.values():
|
|
|
|
ctx_set.discard(ctx)
|
|
|
|
|
|
|
|
if not get_topics():
|
|
|
|
log.warning(f"No subscribers left for {pub_gen}")
|
|
|
|
break
|
2019-01-16 17:19:01 +00:00
|
|
|
|
|
|
|
|
|
|
|
def modify_subs(topics2ctxs, topics, ctx):
|
|
|
|
"""Absolute symbol subscription list for each quote stream.
|
|
|
|
|
|
|
|
Effectively a symbol subscription api.
|
|
|
|
"""
|
2019-01-21 13:35:43 +00:00
|
|
|
log.info(f"{ctx.chan.uid} changed subscription to {topics}")
|
2019-01-16 17:19:01 +00:00
|
|
|
|
|
|
|
# update map from each symbol to requesting client's chan
|
2019-01-24 03:35:59 +00:00
|
|
|
for topic in topics:
|
|
|
|
topics2ctxs.setdefault(topic, set()).add(ctx)
|
2019-01-16 17:19:01 +00:00
|
|
|
|
|
|
|
# remove any existing symbol subscriptions if symbol is not
|
|
|
|
# found in ``symbols``
|
|
|
|
# TODO: this can likely be factored out into the pub-sub api
|
2019-01-24 03:35:59 +00:00
|
|
|
for topic in filter(
|
2019-01-16 17:19:01 +00:00
|
|
|
lambda topic: topic not in topics, topics2ctxs.copy()
|
|
|
|
):
|
2019-01-24 03:35:59 +00:00
|
|
|
ctx_set = topics2ctxs.get(topic)
|
2019-01-16 17:19:01 +00:00
|
|
|
ctx_set.discard(ctx)
|
|
|
|
|
|
|
|
if not ctx_set:
|
|
|
|
# pop empty sets which will trigger bg quoter task termination
|
2019-01-24 03:35:59 +00:00
|
|
|
topics2ctxs.pop(topic)
|
2019-01-16 17:19:01 +00:00
|
|
|
|
|
|
|
|
2020-12-23 00:30:51 +00:00
|
|
|
_pub_state: Dict[str, dict] = {}
|
2021-01-14 23:18:44 +00:00
|
|
|
_pubtask2lock: Dict[str, trio.StrictFIFOLock] = {}
|
2020-12-23 00:30:51 +00:00
|
|
|
|
|
|
|
|
2019-01-21 13:35:43 +00:00
|
|
|
def pub(
|
|
|
|
wrapped: typing.Callable = None,
|
|
|
|
*,
|
2019-01-23 05:41:45 +00:00
|
|
|
tasks: Set[str] = set(),
|
2019-01-21 13:35:43 +00:00
|
|
|
):
|
2019-01-16 17:19:01 +00:00
|
|
|
"""Publisher async generator decorator.
|
|
|
|
|
2019-03-29 23:10:32 +00:00
|
|
|
A publisher can be called multiple times from different actors but
|
|
|
|
will only spawn a finite set of internal tasks to stream values to
|
|
|
|
each caller. The ``tasks: Set[str]`` argument to the decorator
|
|
|
|
specifies the names of the mutex set of publisher tasks. When the
|
|
|
|
publisher function is called, an argument ``task_name`` must be
|
|
|
|
passed to specify which task (of the set named in ``tasks``) should
|
|
|
|
be used. This allows for using the same publisher with different
|
|
|
|
input (arguments) without allowing more concurrent tasks then
|
|
|
|
necessary.
|
|
|
|
|
|
|
|
Values yielded from the decorated async generator must be
|
|
|
|
``Dict[str, Dict[str, Any]]`` where the fist level key is the topic
|
|
|
|
string and determines which subscription the packet will be
|
|
|
|
delivered to and the value is a packet ``Dict[str, Any]`` by default
|
|
|
|
of the form:
|
2019-01-21 13:35:43 +00:00
|
|
|
|
|
|
|
.. ::python
|
|
|
|
|
2019-03-29 23:10:32 +00:00
|
|
|
{topic: str: value: Any}
|
2019-01-21 13:35:43 +00:00
|
|
|
|
2019-03-29 23:10:32 +00:00
|
|
|
The caller can instead opt to pass a ``packetizer`` callback who's
|
|
|
|
return value will be delivered as the published response.
|
2019-01-21 13:35:43 +00:00
|
|
|
|
2019-03-29 23:10:32 +00:00
|
|
|
The decorated async generator function must accept an argument
|
|
|
|
:func:`get_topics` which dynamically returns the tuple of current
|
|
|
|
subscriber topics:
|
2019-01-21 13:35:43 +00:00
|
|
|
|
|
|
|
.. code:: python
|
|
|
|
|
|
|
|
from tractor.msg import pub
|
|
|
|
|
|
|
|
@pub(tasks={'source_1', 'source_2'})
|
|
|
|
async def pub_service(get_topics):
|
|
|
|
data = await web_request(endpoints=get_topics())
|
|
|
|
for item in data:
|
|
|
|
yield data['key'], data
|
2019-01-16 17:19:01 +00:00
|
|
|
|
2019-01-21 13:35:43 +00:00
|
|
|
|
|
|
|
The publisher must be called passing in the following arguments:
|
2019-01-23 05:41:45 +00:00
|
|
|
- ``topics: Set[str]`` the topic sequence or "subscriptions"
|
2019-01-21 13:35:43 +00:00
|
|
|
- ``task_name: str`` the task to use (if ``tasks`` was passed)
|
|
|
|
- ``ctx: Context`` the tractor context (only needed if calling the
|
|
|
|
pub func without a nursery, otherwise this is provided implicitly)
|
|
|
|
- packetizer: ``Callable[[str, Any], Any]`` a callback who receives
|
|
|
|
the topic and value from the publisher function each ``yield`` such that
|
|
|
|
whatever is returned is sent as the published value to subscribers of
|
2020-08-09 02:29:57 +00:00
|
|
|
that topic. By default this is a dict ``{topic: str: value: Any}``.
|
2019-01-21 13:35:43 +00:00
|
|
|
|
|
|
|
As an example, to make a subscriber call the above function:
|
|
|
|
|
|
|
|
.. code:: python
|
|
|
|
|
|
|
|
from functools import partial
|
|
|
|
import tractor
|
|
|
|
|
|
|
|
async with tractor.open_nursery() as n:
|
|
|
|
portal = n.run_in_actor(
|
|
|
|
'publisher', # actor name
|
|
|
|
partial( # func to execute in it
|
|
|
|
pub_service,
|
|
|
|
topics=('clicks', 'users'),
|
|
|
|
task_name='source1',
|
|
|
|
)
|
|
|
|
)
|
2020-08-09 02:29:57 +00:00
|
|
|
async for value in await portal.result():
|
2019-01-21 13:35:43 +00:00
|
|
|
print(f"Subscriber received {value}")
|
|
|
|
|
|
|
|
|
2019-03-29 23:10:32 +00:00
|
|
|
Here, you don't need to provide the ``ctx`` argument since the
|
|
|
|
remote actor provides it automatically to the spawned task. If you
|
|
|
|
were to call ``pub_service()`` directly from a wrapping function you
|
|
|
|
would need to provide this explicitly.
|
2019-01-21 13:35:43 +00:00
|
|
|
|
2019-03-29 23:10:32 +00:00
|
|
|
Remember you only need this if you need *a finite set of tasks*
|
|
|
|
running in a single actor to stream data to an arbitrary number of
|
|
|
|
subscribers. If you are ok to have a new task running for every call
|
|
|
|
to ``pub_service()`` then probably don't need this.
|
2019-01-16 17:19:01 +00:00
|
|
|
"""
|
2021-01-09 01:46:42 +00:00
|
|
|
global _pubtask2lock
|
2020-12-23 00:30:51 +00:00
|
|
|
|
2019-01-21 13:35:43 +00:00
|
|
|
# handle the decorator not called with () case
|
|
|
|
if wrapped is None:
|
|
|
|
return partial(pub, tasks=tasks)
|
|
|
|
|
2021-01-14 23:18:44 +00:00
|
|
|
task2lock: Dict[str, trio.StrictFIFOLock] = {}
|
2020-12-23 00:30:51 +00:00
|
|
|
|
2019-01-16 17:19:01 +00:00
|
|
|
for name in tasks:
|
|
|
|
task2lock[name] = trio.StrictFIFOLock()
|
|
|
|
|
2019-03-29 23:10:32 +00:00
|
|
|
@wrapt.decorator
|
2019-01-16 17:19:01 +00:00
|
|
|
async def wrapper(agen, instance, args, kwargs):
|
2021-01-09 01:46:42 +00:00
|
|
|
|
|
|
|
# XXX: this is used to extract arguments properly as per the
|
|
|
|
# `wrapt` docs
|
2019-01-25 05:10:13 +00:00
|
|
|
async def _execute(
|
|
|
|
ctx: Context,
|
|
|
|
topics: Set[str],
|
|
|
|
*args,
|
|
|
|
# *,
|
2020-09-24 14:04:56 +00:00
|
|
|
task_name: str = None, # default: only one task allocated
|
2019-01-25 05:10:13 +00:00
|
|
|
packetizer: Callable = None,
|
|
|
|
**kwargs,
|
|
|
|
):
|
2021-01-09 01:46:42 +00:00
|
|
|
if task_name is None:
|
|
|
|
task_name = trio.lowlevel.current_task().name
|
|
|
|
|
|
|
|
if tasks and task_name not in tasks:
|
2019-01-16 17:19:01 +00:00
|
|
|
raise TypeError(
|
2019-01-25 05:10:13 +00:00
|
|
|
f"{agen} must be called with a `task_name` named "
|
2021-01-09 01:46:42 +00:00
|
|
|
f"argument with a value from {tasks}")
|
|
|
|
|
|
|
|
elif not tasks and not task2lock:
|
|
|
|
# add a default root-task lock if none defined
|
|
|
|
task2lock[task_name] = trio.StrictFIFOLock()
|
|
|
|
|
|
|
|
_pubtask2lock.update(task2lock)
|
2019-01-25 05:10:13 +00:00
|
|
|
|
2020-09-24 14:04:56 +00:00
|
|
|
topics = set(topics)
|
2021-01-09 01:46:42 +00:00
|
|
|
lock = _pubtask2lock[task_name]
|
2019-01-25 05:10:13 +00:00
|
|
|
|
2020-12-23 00:30:51 +00:00
|
|
|
all_subs = _pub_state.setdefault('_subs', {})
|
2019-01-25 05:10:13 +00:00
|
|
|
topics2ctxs = all_subs.setdefault(task_name, {})
|
|
|
|
|
|
|
|
try:
|
|
|
|
modify_subs(topics2ctxs, topics, ctx)
|
|
|
|
# block and let existing feed task deliver
|
|
|
|
# stream data until it is cancelled in which case
|
|
|
|
# the next waiting task will take over and spawn it again
|
|
|
|
async with lock:
|
|
|
|
# no data feeder task yet; so start one
|
|
|
|
respawn = True
|
|
|
|
while respawn:
|
|
|
|
respawn = False
|
|
|
|
log.info(
|
|
|
|
f"Spawning data feed task for {funcname}")
|
|
|
|
try:
|
|
|
|
# unblocks when no more symbols subscriptions exist
|
|
|
|
# and the streamer task terminates
|
|
|
|
await fan_out_to_ctxs(
|
|
|
|
pub_async_gen_func=partial(
|
|
|
|
agen, *args, **kwargs),
|
|
|
|
topics2ctxs=topics2ctxs,
|
|
|
|
packetizer=packetizer,
|
|
|
|
)
|
|
|
|
log.info(
|
|
|
|
f"Terminating stream task {task_name or ''}"
|
|
|
|
f" for {agen.__name__}")
|
|
|
|
except trio.BrokenResourceError:
|
|
|
|
log.exception("Respawning failed data feed task")
|
|
|
|
respawn = True
|
|
|
|
finally:
|
|
|
|
# remove all subs for this context
|
|
|
|
modify_subs(topics2ctxs, (), ctx)
|
|
|
|
|
|
|
|
# if there are truly no more subscriptions with this broker
|
|
|
|
# drop from broker subs dict
|
|
|
|
if not any(topics2ctxs.values()):
|
|
|
|
log.info(
|
|
|
|
f"No more subscriptions for publisher {task_name}")
|
|
|
|
|
|
|
|
# invoke it
|
|
|
|
await _execute(*args, **kwargs)
|
|
|
|
|
|
|
|
funcname = wrapped.__name__
|
|
|
|
if not inspect.isasyncgenfunction(wrapped):
|
|
|
|
raise TypeError(
|
|
|
|
f"Publisher {funcname} must be an async generator function"
|
|
|
|
)
|
|
|
|
if 'get_topics' not in inspect.signature(wrapped).parameters:
|
|
|
|
raise TypeError(
|
|
|
|
f"Publisher async gen {funcname} must define a "
|
|
|
|
"`get_topics` argument"
|
|
|
|
)
|
2019-01-16 17:19:01 +00:00
|
|
|
|
2019-03-29 23:10:32 +00:00
|
|
|
# XXX: manually monkey the wrapped function since
|
|
|
|
# ``wrapt.decorator`` doesn't seem to want to play nice with its
|
|
|
|
# whole "adapter" thing...
|
|
|
|
wrapped._tractor_stream_function = True # type: ignore
|
2020-08-09 02:29:57 +00:00
|
|
|
|
2019-03-29 23:10:32 +00:00
|
|
|
return wrapper(wrapped)
|