2021-08-08 21:23:48 +00:00
|
|
|
'''
|
2021-08-08 23:48:02 +00:00
|
|
|
``tokio`` style broadcast channel.
|
|
|
|
https://tokio-rs.github.io/tokio/doc/tokio/sync/broadcast/index.html
|
2021-08-08 21:23:48 +00:00
|
|
|
|
|
|
|
'''
|
|
|
|
from __future__ import annotations
|
|
|
|
from itertools import cycle
|
|
|
|
from collections import deque
|
2021-08-09 20:40:02 +00:00
|
|
|
from contextlib import asynccontextmanager
|
2021-08-08 21:23:48 +00:00
|
|
|
from functools import partial
|
|
|
|
from typing import Optional
|
|
|
|
|
|
|
|
import trio
|
|
|
|
import tractor
|
|
|
|
from trio.lowlevel import current_task
|
2021-08-08 23:48:02 +00:00
|
|
|
from trio.abc import ReceiveChannel
|
2021-08-08 21:23:48 +00:00
|
|
|
from trio._core._run import Task
|
|
|
|
|
|
|
|
|
|
|
|
class Lagged(trio.TooSlowError):
|
|
|
|
'''Subscribed consumer task was too slow'''
|
|
|
|
|
|
|
|
|
|
|
|
class BroadcastReceiver(ReceiveChannel):
|
2021-08-08 23:48:02 +00:00
|
|
|
'''A memory receive channel broadcaster which is non-lossy for the
|
|
|
|
fastest consumer.
|
|
|
|
|
|
|
|
Additional consumer tasks can receive all produced values by registering
|
2021-08-09 20:40:02 +00:00
|
|
|
with ``.subscribe()`` and receiving from thew new instance it delivers.
|
2021-08-08 21:23:48 +00:00
|
|
|
|
|
|
|
'''
|
2021-08-09 20:40:02 +00:00
|
|
|
# map of underlying clones to receiver wrappers
|
|
|
|
_subs: dict[trio.ReceiveChannel, BroadcastReceiver] = {}
|
|
|
|
|
2021-08-08 21:23:48 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
2021-08-08 23:48:02 +00:00
|
|
|
|
2021-08-09 20:40:02 +00:00
|
|
|
rx_chan: ReceiveChannel,
|
2021-08-08 23:48:02 +00:00
|
|
|
queue: deque,
|
2021-08-08 21:23:48 +00:00
|
|
|
|
|
|
|
) -> None:
|
|
|
|
|
|
|
|
self._rx = rx_chan
|
2021-08-08 23:48:02 +00:00
|
|
|
self._queue = queue
|
2021-08-08 21:23:48 +00:00
|
|
|
self._value_received: Optional[trio.Event] = None
|
|
|
|
|
|
|
|
async def receive(self):
|
|
|
|
|
2021-08-09 20:40:02 +00:00
|
|
|
key = self._rx
|
2021-08-08 21:23:48 +00:00
|
|
|
|
2021-08-09 20:40:02 +00:00
|
|
|
# TODO: ideally we can make some way to "lock out" the
|
|
|
|
# underlying receive channel in some way such that if some task
|
|
|
|
# tries to pull from it directly (i.e. one we're unaware of)
|
|
|
|
# then it errors out.
|
|
|
|
|
|
|
|
# only tasks which have entered ``.subscribe()`` can
|
|
|
|
# receive on this broadcaster.
|
2021-08-08 21:23:48 +00:00
|
|
|
try:
|
2021-08-09 20:40:02 +00:00
|
|
|
seq = self._subs[key]
|
2021-08-08 21:23:48 +00:00
|
|
|
except KeyError:
|
|
|
|
raise RuntimeError(
|
2021-08-09 20:40:02 +00:00
|
|
|
f'{self} is not registerd as subscriber')
|
2021-08-08 21:23:48 +00:00
|
|
|
|
2021-08-09 20:40:02 +00:00
|
|
|
# check that task does not already have a value it can receive
|
|
|
|
# immediately and/or that it has lagged.
|
2021-08-08 21:23:48 +00:00
|
|
|
if seq > -1:
|
|
|
|
# get the oldest value we haven't received immediately
|
|
|
|
try:
|
|
|
|
value = self._queue[seq]
|
|
|
|
except IndexError:
|
2021-08-09 20:40:02 +00:00
|
|
|
|
|
|
|
# adhere to ``tokio`` style "lagging":
|
|
|
|
# "Once RecvError::Lagged is returned, the lagging
|
|
|
|
# receiver's position is updated to the oldest value
|
|
|
|
# contained by the channel. The next call to recv will
|
|
|
|
# return this value."
|
|
|
|
# https://tokio-rs.github.io/tokio/doc/tokio/sync/broadcast/index.html#lagging
|
|
|
|
|
2021-08-08 23:48:02 +00:00
|
|
|
# decrement to the last value and expect
|
|
|
|
# consumer to either handle the ``Lagged`` and come back
|
2021-08-09 20:40:02 +00:00
|
|
|
# or bail out on its own (thus un-subscribing)
|
|
|
|
self._subs[key] = self._queue.maxlen - 1
|
2021-08-08 23:48:02 +00:00
|
|
|
|
|
|
|
# this task was overrun by the producer side
|
2021-08-09 20:40:02 +00:00
|
|
|
task: Task = current_task()
|
2021-08-08 21:23:48 +00:00
|
|
|
raise Lagged(f'Task {task.name} was overrun')
|
|
|
|
|
2021-08-09 20:40:02 +00:00
|
|
|
self._subs[key] -= 1
|
2021-08-08 21:23:48 +00:00
|
|
|
return value
|
|
|
|
|
2021-08-09 20:40:02 +00:00
|
|
|
# current task already has the latest value **and** is the
|
|
|
|
# first task to begin waiting for a new one
|
2021-08-08 21:23:48 +00:00
|
|
|
if self._value_received is None:
|
|
|
|
|
|
|
|
event = self._value_received = trio.Event()
|
|
|
|
value = await self._rx.receive()
|
|
|
|
|
|
|
|
# items with lower indices are "newer"
|
|
|
|
self._queue.appendleft(value)
|
|
|
|
|
|
|
|
# broadcast new value to all subscribers by increasing
|
|
|
|
# all sequence numbers that will point in the queue to
|
|
|
|
# their latest available value.
|
|
|
|
|
2021-08-08 23:48:02 +00:00
|
|
|
subs = self._subs.copy()
|
2021-08-09 20:40:02 +00:00
|
|
|
# don't decrement the sequence # for this task since we
|
2021-08-08 23:48:02 +00:00
|
|
|
# already retreived the last value
|
2021-08-09 20:40:02 +00:00
|
|
|
subs.pop(key)
|
2021-08-08 23:48:02 +00:00
|
|
|
for sub_key, seq in subs.items():
|
2021-08-08 21:23:48 +00:00
|
|
|
self._subs[sub_key] += 1
|
|
|
|
|
2021-08-08 23:48:02 +00:00
|
|
|
# reset receiver waiter task event for next blocking condition
|
2021-08-08 21:23:48 +00:00
|
|
|
self._value_received = None
|
|
|
|
event.set()
|
|
|
|
return value
|
|
|
|
|
2021-08-09 20:40:02 +00:00
|
|
|
# This task is all caught up and ready to receive the latest
|
|
|
|
# value, so queue sched it on the internal event.
|
2021-08-08 21:23:48 +00:00
|
|
|
else:
|
|
|
|
await self._value_received.wait()
|
|
|
|
|
2021-08-09 20:40:02 +00:00
|
|
|
seq = self._subs[key]
|
2021-08-08 23:48:02 +00:00
|
|
|
assert seq > -1, 'Internal error?'
|
2021-08-08 21:23:48 +00:00
|
|
|
|
2021-08-09 20:40:02 +00:00
|
|
|
self._subs[key] -= 1
|
2021-08-08 21:23:48 +00:00
|
|
|
return self._queue[0]
|
|
|
|
|
2021-08-09 20:40:02 +00:00
|
|
|
@asynccontextmanager
|
|
|
|
async def subscribe(
|
2021-08-08 21:23:48 +00:00
|
|
|
self,
|
|
|
|
) -> BroadcastReceiver:
|
2021-08-09 20:40:02 +00:00
|
|
|
'''Subscribe for values from this broadcast receiver.
|
|
|
|
|
|
|
|
Returns a new ``BroadCastReceiver`` which is registered for and
|
|
|
|
pulls data from a clone of the original ``trio.abc.ReceiveChannel``
|
|
|
|
provided at creation.
|
|
|
|
|
|
|
|
'''
|
|
|
|
clone = self._rx.clone()
|
|
|
|
self._subs[clone] = -1
|
2021-08-08 21:23:48 +00:00
|
|
|
try:
|
2021-08-09 20:40:02 +00:00
|
|
|
yield BroadcastReceiver(
|
|
|
|
clone,
|
|
|
|
self._queue,
|
|
|
|
)
|
2021-08-08 21:23:48 +00:00
|
|
|
finally:
|
2021-08-09 20:40:02 +00:00
|
|
|
# drop from subscribers and close
|
|
|
|
self._subs.pop(clone)
|
|
|
|
# XXX: this is the reason this function is async: the
|
|
|
|
# ``AsyncResource`` api.
|
|
|
|
await clone.aclose()
|
|
|
|
|
|
|
|
# TODO:
|
|
|
|
# - should there be some ._closed flag that causes
|
|
|
|
# consumers to die **before** they read all queued values?
|
|
|
|
# - if subs only open and close clones then the underlying
|
|
|
|
# will never be killed until the last instance closes?
|
|
|
|
# This is correct right?
|
|
|
|
async def aclose(
|
|
|
|
self,
|
|
|
|
) -> None:
|
|
|
|
# XXX: leaving it like this consumers can still get values
|
|
|
|
# up to the last received that still reside in the queue.
|
|
|
|
# Is this what we want?
|
|
|
|
await self._rx.aclose()
|
|
|
|
self._subs.pop(self._rx)
|
2021-08-08 21:23:48 +00:00
|
|
|
|
|
|
|
|
2021-08-08 23:48:02 +00:00
|
|
|
def broadcast_receiver(
|
2021-08-08 21:23:48 +00:00
|
|
|
|
2021-08-09 11:35:42 +00:00
|
|
|
recv_chan: ReceiveChannel,
|
2021-08-08 21:23:48 +00:00
|
|
|
max_buffer_size: int,
|
|
|
|
|
2021-08-08 23:48:02 +00:00
|
|
|
) -> BroadcastReceiver:
|
2021-08-08 21:23:48 +00:00
|
|
|
|
2021-08-08 23:48:02 +00:00
|
|
|
return BroadcastReceiver(
|
|
|
|
recv_chan,
|
|
|
|
queue=deque(maxlen=max_buffer_size),
|
|
|
|
)
|
2021-08-08 21:23:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
|
|
|
|
async def main():
|
|
|
|
|
|
|
|
async with tractor.open_root_actor(
|
|
|
|
debug_mode=True,
|
|
|
|
# loglevel='info',
|
|
|
|
):
|
|
|
|
|
2021-08-09 20:40:02 +00:00
|
|
|
retries = 3
|
2021-08-08 23:48:02 +00:00
|
|
|
size = 100
|
|
|
|
tx, rx = trio.open_memory_channel(size)
|
|
|
|
rx = broadcast_receiver(rx, size)
|
2021-08-08 21:23:48 +00:00
|
|
|
|
|
|
|
async def sub_and_print(
|
|
|
|
delay: float,
|
|
|
|
) -> None:
|
|
|
|
|
|
|
|
task = current_task()
|
|
|
|
count = 0
|
|
|
|
|
|
|
|
while True:
|
2021-08-09 20:40:02 +00:00
|
|
|
async with rx.subscribe() as brx:
|
2021-08-08 21:23:48 +00:00
|
|
|
try:
|
2021-08-09 20:40:02 +00:00
|
|
|
async for value in brx:
|
2021-08-08 21:23:48 +00:00
|
|
|
print(f'{task.name}: {value}')
|
|
|
|
await trio.sleep(delay)
|
|
|
|
count += 1
|
|
|
|
|
|
|
|
except Lagged:
|
|
|
|
print(
|
|
|
|
f'restarting slow ass {task.name}'
|
|
|
|
f'that bailed out on {count}:{value}')
|
2021-08-09 20:40:02 +00:00
|
|
|
if count <= retries:
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
print(
|
|
|
|
f'{task.name} was too slow and terminated '
|
|
|
|
f'on {count}:{value}')
|
|
|
|
return
|
2021-08-08 21:23:48 +00:00
|
|
|
|
|
|
|
async with trio.open_nursery() as n:
|
2021-08-09 20:40:02 +00:00
|
|
|
for i in range(1, size):
|
2021-08-08 21:23:48 +00:00
|
|
|
n.start_soon(
|
|
|
|
partial(
|
|
|
|
sub_and_print,
|
|
|
|
delay=i*0.01,
|
|
|
|
),
|
|
|
|
name=f'sub_{i}',
|
|
|
|
)
|
|
|
|
|
|
|
|
async with tx:
|
2021-08-09 20:40:02 +00:00
|
|
|
for i in cycle(range(size)):
|
2021-08-08 21:23:48 +00:00
|
|
|
print(f'sending: {i}')
|
|
|
|
await tx.send(i)
|
|
|
|
|
|
|
|
trio.run(main)
|