forked from hyperledger/indy-plenum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchannel.py
192 lines (145 loc) · 5.4 KB
/
channel.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
from abc import ABC, abstractmethod
from asyncio import Queue, QueueFull, wait
from collections import deque
from inspect import isawaitable, iscoroutinefunction
from typing import Any, Type, Callable, Tuple, Optional, Dict
# TODO: DEPRECATE
# After playing with concept a bit it feels like using EventBus
# is more appropriate.
class TxChannel(ABC):
@abstractmethod
async def put(self, msg: Any):
pass
@abstractmethod
def put_nowait(self, msg: Any) -> bool:
pass
class RxChannel(ABC):
@abstractmethod
def subscribe(self, handler: Callable):
pass
class _RxChannel(RxChannel):
def __init__(self):
self._sync_handlers = []
self._async_handlers = []
def subscribe(self, handler: Callable):
if iscoroutinefunction(handler):
self._async_handlers.append(handler)
else:
self._sync_handlers.append(handler)
@property
def has_async_handlers(self):
return len(self._async_handlers) > 0
def notify_sync(self, msg: Any):
for handler in self._sync_handlers:
handler(msg)
async def notify(self, msg: Any):
self.notify_sync(msg)
if self.has_async_handlers:
await wait([handler(msg) for handler in self._async_handlers])
def create_direct_channel() -> Tuple[TxChannel, RxChannel]:
class Channel(TxChannel):
def __init__(self, observable: _RxChannel):
self._observable = observable
async def put(self, msg: Any):
await self._observable.notify(msg)
def put_nowait(self, msg: Any):
# TODO: What if observable has async handlers?
self._observable.notify_sync(msg)
return True
router = _RxChannel()
return Channel(router), router
class QueuedChannelService:
class Channel(TxChannel):
def __init__(self, queue: deque):
self._queue = queue
async def put(self, msg: Any):
self._queue.append(msg)
def put_nowait(self, msg: Any):
self._queue.append(msg)
def __init__(self):
self._queue = deque()
self._inbox = self.Channel(self._queue)
self._observable = _RxChannel()
def inbox(self) -> TxChannel:
return self._inbox
def observable(self) -> RxChannel:
return self._observable
async def service(self, limit: Optional[int] = None) -> int:
count = 0
while len(self._queue) > 0 and (limit is None or count < limit):
count += 1
msg = self._queue.popleft()
await self._observable.notify(msg)
return count
def service_sync(self, limit: Optional[int] = None) -> int:
count = 0
while len(self._queue) > 0 and (limit is None or count < limit):
count += 1
msg = self._queue.popleft()
self._observable.notify_sync(msg)
return count
class AsyncioChannelService:
class Channel(TxChannel):
def __init__(self, queue: Queue):
self._queue = queue
async def put(self, msg: Any):
await self._queue.put(msg)
def put_nowait(self, msg: Any) -> bool:
try:
self._queue.put_nowait(msg)
return True
except QueueFull:
return False
def __init__(self):
self._queue = Queue()
self._inbox = self.Channel(self._queue)
self._observable = _RxChannel()
self._is_running = False
def inbox(self) -> TxChannel:
return self._inbox
def router(self) -> RxChannel:
return self._observable
async def run(self):
self._is_running = True
while self._is_running:
msg = await self._queue.get()
await self._observable.notify(msg)
def stop(self):
self._is_running = False
class RouterBase:
def __init__(self, strict: bool = False):
self._strict = strict
self._routes = {} # type: Dict[Type, Callable]
def add(self, msg_type: Type, handler: Callable):
self._routes[msg_type] = handler
def _process_sync(self, msg: Any):
# This is done so that messages can include additional metadata
# isinstance is not used here because it returns true for NamedTuple
# as well.
if type(msg) != tuple:
msg = (msg,)
handler = self._find_handler(msg[0])
if handler is None:
if self._strict:
raise RuntimeError("unhandled msg: {}".format(msg))
return
return handler(*msg)
def _find_handler(self, msg: Any) -> Optional[Callable]:
for cls, handler in self._routes.items():
if isinstance(msg, cls):
return handler
class Router(RouterBase):
def __init__(self, input: RxChannel, strict: bool = False):
RouterBase.__init__(self, strict)
input.subscribe(self._process_sync)
def add(self, msg_type: Type, handler: Callable):
if iscoroutinefunction(handler):
raise ValueError('Router works only with synchronous handlers')
RouterBase.add(self, msg_type, handler)
class AsyncRouter(RouterBase):
def __init__(self, input: RxChannel, strict: bool = True):
RouterBase.__init__(self, strict)
input.subscribe(self._process)
async def _process(self, msg: Any):
result = self._process_sync(msg)
return await result if isawaitable(result) else result