-
Notifications
You must be signed in to change notification settings - Fork 0
/
asyncio_rpc_aiopqueue.py
75 lines (61 loc) · 2.21 KB
/
asyncio_rpc_aiopqueue.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from asyncio_rpc.commlayers.base import AbstractRPCCommLayer
from asyncio_rpc.models import RPCBase
from aioprocessing import AioQueue
from typing import Tuple
class AiopQueueCommLayer(AbstractRPCCommLayer):
"""
aioprocessing.Queue remote procedure call communication layer
"""
@classmethod
def create_pair(cls) \
-> Tuple["AiopQueueCommLayer", "AiopQueueCommLayer"]:
"""Create connected pair of AiopQueueCommLayers"""
q1, q2 = AioQueue(), AioQueue()
return cls(q1, q2), cls(q2, q1)
def __init__(self, in_queue: AioQueue, out_queue: AioQueue):
self.in_queue = in_queue
self.out_queue = out_queue
async def do_subscribe(self):
pass
async def publish(self, rpc_instance: RPCBase, channel=None):
"""
Publish implementation, publishes RPCBase instances.
:return: the number of receivers
"""
# rpc_instance should be a subclass of RPCBase
# For now just check if instance of RPCBase
assert isinstance(rpc_instance, RPCBase)
self.out_queue.put(rpc_instance)
return 1 # dummy
async def subscribe(self, on_rpc_event_callback, channel=None):
"""
Implementation for subscribe method, receives messages from
subscription channel.
Note: does block in while loop until .unsubscribe() is called.
"""
try:
self.subscribed = True
# Inside a while loop, wait for incoming events.
while True:
event = await self.in_queue.coro_get()
if event == "UNSUB":
break
await on_rpc_event_callback(event, channel=channel)
finally:
# Close connections and cleanup
self.subscribed = False
async def unsubscribe(self):
"""
Implementation for unsubscribe. Stops subscription and breaks
out of the while loop in .subscribe()
"""
if self.subscribed:
self.in_queue.put("UNSUB")
self.subscribed = False
async def close(self):
"""
Stop subscription & close everything
"""
await self.unsubscribe()
class Unsubscribe(Exception):
pass