eric-sse 0.0.5__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- eric_sse-0.0.5/LICENSE +21 -0
- eric_sse-0.0.5/PKG-INFO +13 -0
- eric_sse-0.0.5/eric_sse/__init__.py +10 -0
- eric_sse-0.0.5/eric_sse/entities.py +249 -0
- eric_sse-0.0.5/eric_sse/exception.py +15 -0
- eric_sse-0.0.5/eric_sse/servers.py +141 -0
- eric_sse-0.0.5/pyproject.toml +21 -0
eric_sse-0.0.5/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Luca Stretti
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
eric_sse-0.0.5/PKG-INFO
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: eric-sse
|
|
3
|
+
Version: 0.0.5
|
|
4
|
+
Summary: A lightweigth message dispatcher based on SSE protocol data transfer objects format
|
|
5
|
+
Keywords: sse,queue
|
|
6
|
+
Author: Luca Stretti
|
|
7
|
+
Author-email: laxertu@gmail.com
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Requires-Dist: asyncio (>=3.4.3)
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from threading import Lock
|
|
3
|
+
|
|
4
|
+
from abc import ABC, abstractmethod
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import AsyncIterable, Any, Callable
|
|
7
|
+
|
|
8
|
+
import eric_sse
|
|
9
|
+
from eric_sse.exception import InvalidChannelException, InvalidListenerException, NoMessagesException
|
|
10
|
+
|
|
11
|
+
logger = eric_sse.get_logger()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class Message:
|
|
16
|
+
"""
|
|
17
|
+
Models a message
|
|
18
|
+
|
|
19
|
+
It's just a container of information identified by a type.
|
|
20
|
+
For validation purposes you can override MessageQueueListener.on_message
|
|
21
|
+
"""
|
|
22
|
+
type: str
|
|
23
|
+
payload: dict | list | str | int | float | None = None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def create_simple_mesage(txt: str) -> Message:
|
|
27
|
+
return Message(type='txt', payload=txt)
|
|
28
|
+
|
|
29
|
+
class MessageQueueListener(ABC):
|
|
30
|
+
"""
|
|
31
|
+
Base class for listeners.
|
|
32
|
+
|
|
33
|
+
Optionally you can override on_message method if you need to inject code at message delivery time.
|
|
34
|
+
"""
|
|
35
|
+
NEXT_ID = 1
|
|
36
|
+
|
|
37
|
+
def __init__(self):
|
|
38
|
+
with Lock():
|
|
39
|
+
self.id: str = str(MessageQueueListener.NEXT_ID)
|
|
40
|
+
MessageQueueListener.NEXT_ID += 1
|
|
41
|
+
self.__is_running: bool = False
|
|
42
|
+
|
|
43
|
+
async def start(self) -> None:
|
|
44
|
+
"""Starts listening"""
|
|
45
|
+
self.__is_running = True
|
|
46
|
+
|
|
47
|
+
def start_sync(self) -> None:
|
|
48
|
+
"""Starts listening"""
|
|
49
|
+
self.__is_running = True
|
|
50
|
+
|
|
51
|
+
async def is_running(self) -> bool:
|
|
52
|
+
"""Returns listener's state: stopped vs. running"""
|
|
53
|
+
return self.__is_running
|
|
54
|
+
|
|
55
|
+
def is_running_sync(self) -> bool:
|
|
56
|
+
"""Returns listener's state: stopped vs. running"""
|
|
57
|
+
return self.__is_running
|
|
58
|
+
|
|
59
|
+
async def stop(self) -> None:
|
|
60
|
+
"""Stops listening"""
|
|
61
|
+
self.__is_running = False
|
|
62
|
+
|
|
63
|
+
def stop_sync(self) -> None:
|
|
64
|
+
"""Stops listening"""
|
|
65
|
+
self.__is_running = False
|
|
66
|
+
|
|
67
|
+
def on_message(self, msg: Message) -> None:
|
|
68
|
+
"""
|
|
69
|
+
Event handler. It executes whan a message is delivered to client
|
|
70
|
+
"""
|
|
71
|
+
pass
|
|
72
|
+
|
|
73
|
+
class AbstractChannel(ABC):
|
|
74
|
+
"""
|
|
75
|
+
Base class for channels.
|
|
76
|
+
|
|
77
|
+
Provides functionalities for listeners and message delivery management.
|
|
78
|
+
SSEChannel is the default implementation
|
|
79
|
+
"""
|
|
80
|
+
NEXT_ID = 1
|
|
81
|
+
|
|
82
|
+
def __init__(self, stream_delay_seconds: int = 0, retry_timeout_millisedonds: int = 5):
|
|
83
|
+
logger.info(f'Creating channel {AbstractChannel.NEXT_ID}')
|
|
84
|
+
with Lock():
|
|
85
|
+
self.id: str = str(AbstractChannel.NEXT_ID)
|
|
86
|
+
AbstractChannel.NEXT_ID += 1
|
|
87
|
+
|
|
88
|
+
self.listeners: dict[str: MessageQueueListener] = {}
|
|
89
|
+
self.queues: dict[str: list[Message]] = {}
|
|
90
|
+
self.stream_delay_seconds = stream_delay_seconds
|
|
91
|
+
self.retry_timeout_millisedonds = retry_timeout_millisedonds
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def add_listener(self) -> MessageQueueListener:
|
|
95
|
+
"""Add the default listener"""
|
|
96
|
+
logger.warning('Deprecated method, it will be removed from 0.0.4. Please movw to register_listener')
|
|
97
|
+
l = MessageQueueListener()
|
|
98
|
+
self.register_listener(l)
|
|
99
|
+
return l
|
|
100
|
+
|
|
101
|
+
def register_listener(self, l: MessageQueueListener):
|
|
102
|
+
"""
|
|
103
|
+
Adds a listener to channel
|
|
104
|
+
|
|
105
|
+
:param l:
|
|
106
|
+
"""
|
|
107
|
+
self.listeners[l.id] = l
|
|
108
|
+
self.queues[l.id] = []
|
|
109
|
+
|
|
110
|
+
def remove_listener(self, l_id: str):
|
|
111
|
+
del self.queues[l_id]
|
|
112
|
+
del self.listeners[l_id]
|
|
113
|
+
|
|
114
|
+
def deliver_next(self, listener_id: str) -> Message:
|
|
115
|
+
"""
|
|
116
|
+
Returns next message for given listener id.
|
|
117
|
+
Raises a NoMessagesException if queue is empty
|
|
118
|
+
|
|
119
|
+
:param listener_id:
|
|
120
|
+
"""
|
|
121
|
+
if self.get_listener(listener_id).is_running_sync():
|
|
122
|
+
try:
|
|
123
|
+
msg = self.__get_queue(listener_id).pop(0)
|
|
124
|
+
self.get_listener(listener_id).on_message(msg)
|
|
125
|
+
|
|
126
|
+
return msg
|
|
127
|
+
except IndexError:
|
|
128
|
+
raise NoMessagesException
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def __get_queue(self, listener_id: str) -> list[Message]:
|
|
132
|
+
try:
|
|
133
|
+
return self.queues[listener_id]
|
|
134
|
+
except KeyError:
|
|
135
|
+
raise InvalidListenerException(f"Invalid listener {listener_id}")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def dispatch(self, listener_id: str, msg: Message):
|
|
139
|
+
"""
|
|
140
|
+
Adds a message to listener's queue
|
|
141
|
+
|
|
142
|
+
:param listener_id:
|
|
143
|
+
:param msg:
|
|
144
|
+
"""
|
|
145
|
+
self._add_to_queue(listener_id, msg)
|
|
146
|
+
logger.debug(f"Pending {len(self.queues[listener_id])} messages")
|
|
147
|
+
|
|
148
|
+
def _add_to_queue(self, listener_id: str, msg: Message):
|
|
149
|
+
self.__get_queue(listener_id).append(msg)
|
|
150
|
+
|
|
151
|
+
def broadcast(self, msg: Message):
|
|
152
|
+
"""
|
|
153
|
+
Enqueue a message to all listeners
|
|
154
|
+
|
|
155
|
+
:param msg:
|
|
156
|
+
"""
|
|
157
|
+
for listener_id in self.listeners.keys():
|
|
158
|
+
self.dispatch(listener_id, msg=msg)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def get_listener(self, listener_id: str) -> MessageQueueListener:
|
|
162
|
+
try:
|
|
163
|
+
return self.listeners[listener_id]
|
|
164
|
+
except KeyError:
|
|
165
|
+
raise InvalidListenerException
|
|
166
|
+
|
|
167
|
+
@abstractmethod
|
|
168
|
+
def adapt(self, msg: Message) -> Any:
|
|
169
|
+
...
|
|
170
|
+
|
|
171
|
+
async def message_stream(self, listener: MessageQueueListener) -> AsyncIterable[dict]:
|
|
172
|
+
"""
|
|
173
|
+
In case of failure at channel resulution time, a special message with type='_eric_channel_closed' is sent, and
|
|
174
|
+
correspondant listener is stopped
|
|
175
|
+
|
|
176
|
+
:param listener:
|
|
177
|
+
:return:
|
|
178
|
+
"""
|
|
179
|
+
|
|
180
|
+
def new_messages():
|
|
181
|
+
try:
|
|
182
|
+
yield self.deliver_next(listener.id)
|
|
183
|
+
except NoMessagesException:
|
|
184
|
+
...
|
|
185
|
+
|
|
186
|
+
async def event_generator() -> AsyncIterable[dict]:
|
|
187
|
+
while True:
|
|
188
|
+
# If client closes connection, stop sending events
|
|
189
|
+
if not await listener.is_running():
|
|
190
|
+
break
|
|
191
|
+
|
|
192
|
+
try:
|
|
193
|
+
for message in new_messages():
|
|
194
|
+
yield self.adapt(message)
|
|
195
|
+
|
|
196
|
+
await asyncio.sleep(self.stream_delay_seconds)
|
|
197
|
+
except InvalidChannelException as e:
|
|
198
|
+
logger.info(f"Stopping listener {listener.id}")
|
|
199
|
+
logger.debug(e)
|
|
200
|
+
await listener.stop()
|
|
201
|
+
yield self.adapt(Message(type='_eric_channel_closed'))
|
|
202
|
+
|
|
203
|
+
return event_generator()
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class SSEChannel(AbstractChannel):
|
|
207
|
+
"""
|
|
208
|
+
SSE streaming channel.
|
|
209
|
+
|
|
210
|
+
See https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format
|
|
211
|
+
Currently, 'id' field is not supported.
|
|
212
|
+
"""
|
|
213
|
+
def adapt(self, msg: Message) -> Any:
|
|
214
|
+
return {
|
|
215
|
+
"event": msg.type,
|
|
216
|
+
"retry": self.retry_timeout_millisedonds,
|
|
217
|
+
"data": msg.payload
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class ThreadPoolListener(MessageQueueListener):
|
|
222
|
+
"""
|
|
223
|
+
Listener intended for consurrent processing of data.
|
|
224
|
+
|
|
225
|
+
Relies on concurrent.futures.ThreadPoolExecutor.
|
|
226
|
+
'_eric_channel_closed' Message type is intended as end of stream. Is shouls be considered as a reserved Message type
|
|
227
|
+
"""
|
|
228
|
+
def __init__(self, callback: Callable, max_workers: int):
|
|
229
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
230
|
+
super().__init__()
|
|
231
|
+
self.executor = ThreadPoolExecutor(max_workers=max_workers)
|
|
232
|
+
self.__callback = callback
|
|
233
|
+
|
|
234
|
+
def on_message(self, msg: Message) -> None:
|
|
235
|
+
if msg.type == '_eric_channel_closed':
|
|
236
|
+
self.stop_sync()
|
|
237
|
+
else:
|
|
238
|
+
self.executor.submit(self.__callback, msg.payload)
|
|
239
|
+
|
|
240
|
+
class DataProcessingChannel(SSEChannel):
|
|
241
|
+
|
|
242
|
+
def notify_end(self):
|
|
243
|
+
self.broadcast(Message(type='_eric_channel_closed'))
|
|
244
|
+
|
|
245
|
+
def add_threaded_listener(self, callback: Callable, max_workers: int) -> ThreadPoolListener:
|
|
246
|
+
|
|
247
|
+
l = ThreadPoolListener(callback, max_workers)
|
|
248
|
+
self.register_listener(l)
|
|
249
|
+
return l
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
class InvalidChannelException(Exception):
|
|
2
|
+
...
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class InvalidListenerException(Exception):
|
|
6
|
+
...
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class NoMessagesException(Exception):
|
|
10
|
+
"""Raised when trying to fetch from an empty queue"""
|
|
11
|
+
...
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class InvalidMessageFormat(Exception):
|
|
15
|
+
...
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import signal
|
|
5
|
+
|
|
6
|
+
from asyncio import StreamReader, StreamWriter, start_unix_server
|
|
7
|
+
from asyncio.exceptions import CancelledError
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import eric_sse
|
|
11
|
+
from eric_sse.entities import Message
|
|
12
|
+
from eric_sse.exception import InvalidChannelException, InvalidListenerException, InvalidMessageFormat
|
|
13
|
+
from eric_sse.entities import SSEChannel
|
|
14
|
+
|
|
15
|
+
logger = eric_sse.get_logger()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ChannelContainer:
|
|
19
|
+
"""Helper class for managment of multiple SSE channels cases of use."""
|
|
20
|
+
|
|
21
|
+
def __init__(self):
|
|
22
|
+
self.__channels: dict[str: SSEChannel] = {}
|
|
23
|
+
|
|
24
|
+
def add(self) -> SSEChannel:
|
|
25
|
+
channel = SSEChannel()
|
|
26
|
+
if channel.id in self.__channels:
|
|
27
|
+
raise InvalidListenerException(f'Channel with id {channel.id} already exists')
|
|
28
|
+
self.__channels[channel.id] = channel
|
|
29
|
+
return channel
|
|
30
|
+
|
|
31
|
+
def get(self, channel_id: str) -> SSEChannel:
|
|
32
|
+
try:
|
|
33
|
+
return self.__channels[channel_id]
|
|
34
|
+
except KeyError:
|
|
35
|
+
raise InvalidChannelException(f'No channel with id {channel_id}')
|
|
36
|
+
|
|
37
|
+
def rm(self, channel_id: str):
|
|
38
|
+
del self.__channels[channel_id]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class SocketServer:
|
|
42
|
+
"""
|
|
43
|
+
An implementation of a socket server that reveives and broadcasts automatically all messages that receives
|
|
44
|
+
|
|
45
|
+
A static shortcut for starting a basic server is provided. See examples.
|
|
46
|
+
"""
|
|
47
|
+
cc = ChannelContainer()
|
|
48
|
+
|
|
49
|
+
def __init__(self, file_descriptor_path: str):
|
|
50
|
+
self.__file_descriptor_path = file_descriptor_path
|
|
51
|
+
|
|
52
|
+
@staticmethod
|
|
53
|
+
def __parse(json_raw: str) -> (str, Message, str):
|
|
54
|
+
try:
|
|
55
|
+
parsed = json.loads(json_raw)
|
|
56
|
+
channel_id = parsed['c']
|
|
57
|
+
verb = parsed['v']
|
|
58
|
+
message = Message(type=parsed['t'], payload=parsed.get('p'))
|
|
59
|
+
receiver_id: str = parsed.get('r')
|
|
60
|
+
return channel_id, verb, message, receiver_id
|
|
61
|
+
|
|
62
|
+
except KeyError as e:
|
|
63
|
+
logger.error(repr(e))
|
|
64
|
+
raise InvalidMessageFormat(json_raw)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@staticmethod
|
|
68
|
+
async def connect_callback(reader: StreamReader, writer: StreamWriter):
|
|
69
|
+
try:
|
|
70
|
+
message_content = await reader.read()
|
|
71
|
+
channel_id, verb, message, receiver_id = SocketServer.__parse(message_content.decode())
|
|
72
|
+
channel = SocketServer.cc.get(channel_id)
|
|
73
|
+
|
|
74
|
+
logger.info(f'received command {verb}')
|
|
75
|
+
|
|
76
|
+
if verb == 'd':
|
|
77
|
+
channel.dispatch(receiver_id, message)
|
|
78
|
+
writer.write('ack'.encode())
|
|
79
|
+
writer.write_eof()
|
|
80
|
+
await writer.drain()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
elif verb == 'b':
|
|
84
|
+
channel.broadcast(message)
|
|
85
|
+
writer.write('ack'.encode())
|
|
86
|
+
writer.write_eof()
|
|
87
|
+
await writer.drain()
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
elif verb == 'c':
|
|
91
|
+
l = channel.add_listener()
|
|
92
|
+
writer.write(l.id.encode())
|
|
93
|
+
writer.write_eof()
|
|
94
|
+
await writer.drain()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
elif verb == 'w':
|
|
98
|
+
logger.info(f"Client watching on listener {receiver_id}")
|
|
99
|
+
async for m in await channel.message_stream(channel.get_listener(receiver_id)):
|
|
100
|
+
message = f'{json.dumps(m)}{os.linesep}'
|
|
101
|
+
logger.info(f"received message {message}")
|
|
102
|
+
writer.write(message.encode())
|
|
103
|
+
#await writer.drain()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
except Exception as e:
|
|
108
|
+
logger.error(e)
|
|
109
|
+
writer.write(repr(e).encode())
|
|
110
|
+
writer.write_eof()
|
|
111
|
+
await writer.drain()
|
|
112
|
+
|
|
113
|
+
async def shutdown(self, server: asyncio.Server):
|
|
114
|
+
logger.info("graceful shutdown")
|
|
115
|
+
server.close()
|
|
116
|
+
await server.wait_closed()
|
|
117
|
+
Path(self.__file_descriptor_path).unlink()
|
|
118
|
+
logger.info("done")
|
|
119
|
+
|
|
120
|
+
async def main(self):
|
|
121
|
+
server = await start_unix_server(SocketServer.connect_callback, path=Path(self.__file_descriptor_path))
|
|
122
|
+
addr = server.sockets[0].getsockname()
|
|
123
|
+
logger.info(f'Serving on {addr}')
|
|
124
|
+
|
|
125
|
+
async with server:
|
|
126
|
+
for sig in (signal.SIGINT, signal.SIGTERM):
|
|
127
|
+
server.get_loop().add_signal_handler(
|
|
128
|
+
sig, lambda: asyncio.ensure_future(self.shutdown(server))
|
|
129
|
+
)
|
|
130
|
+
await server.serve_forever()
|
|
131
|
+
|
|
132
|
+
@staticmethod
|
|
133
|
+
def start(file_descriptor_path: str):
|
|
134
|
+
"""Shortcut to start a server"""
|
|
135
|
+
logger.info('starting')
|
|
136
|
+
try:
|
|
137
|
+
server = SocketServer(file_descriptor_path)
|
|
138
|
+
asyncio.run(server.main())
|
|
139
|
+
except CancelledError:
|
|
140
|
+
exit(0)
|
|
141
|
+
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
[tool.poetry]
|
|
2
|
+
name = "eric-sse"
|
|
3
|
+
description = "A lightweigth message dispatcher based on SSE protocol data transfer objects format"
|
|
4
|
+
version = "0.0.5"
|
|
5
|
+
authors = [" Luca Stretti <laxertu@gmail.com>"]
|
|
6
|
+
keywords = ["sse", "queue"]
|
|
7
|
+
|
|
8
|
+
[tool.poetry.dependencies]
|
|
9
|
+
python = ">= 3.10"
|
|
10
|
+
asyncio = ">= 3.4.3"
|
|
11
|
+
|
|
12
|
+
[tool.setuptools_scm]
|
|
13
|
+
|
|
14
|
+
[build-system]
|
|
15
|
+
requires = ["poetry-core"]
|
|
16
|
+
build-backend = "poetry.core.masonry.api"
|
|
17
|
+
|
|
18
|
+
[tool.poetry.group.test]
|
|
19
|
+
[tool.poetry.group.test.dependencies]
|
|
20
|
+
pytest = {version = ">= 8.3.2", optional = true}
|
|
21
|
+
|