eric-sse 0.5.0.2__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.
@@ -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.
@@ -0,0 +1,299 @@
1
+ Metadata-Version: 2.1
2
+ Name: eric-sse
3
+ Version: 0.5.0.2
4
+ Summary: A lightweight message dispatcher based on SSE protocol data transfer objects format
5
+ Home-page: https://github.com/laxertu/eric
6
+ License: MIT
7
+ Keywords: sse,queue,API,concurrency
8
+ Author: Luca Stretti
9
+ Author-email: laxertu@gmail.com
10
+ Requires-Python: >=3.10
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Requires-Dist: asyncio (>=3.4.3)
17
+ Description-Content-Type: text/markdown
18
+
19
+ <a id="the-lightweight-library-for-async-messaging-nobody-expects"></a>
20
+
21
+ # The lightweight library for async messaging nobody expects.
22
+
23
+ <a id="installation"></a>
24
+
25
+ # Installation
26
+
27
+ pip install eric-sse
28
+
29
+ <a id="features"></a>
30
+
31
+ # Features
32
+
33
+ * Send to one listener and broadcast
34
+ * SSE format was adopted by design, is order to make library suitable for such kind of model
35
+ * Sockets
36
+ * Callbacks
37
+ * [**Experimental**] Threading support for large data processing
38
+
39
+ Possible applications
40
+
41
+ * Message delivery mechanisms based on SSE
42
+ * Message queue processing (logging, etc)
43
+ * See [https://github.com/laxertu/eric-api](https://github.com/laxertu/eric-api)
44
+
45
+ Trivia
46
+
47
+ Library name pretends to be a tribute to the following movie [https://en.wikipedia.org/wiki/Looking_for_Eric](https://en.wikipedia.org/wiki/Looking_for_Eric)
48
+
49
+ <a id="module-eric_sse.entities"></a>
50
+
51
+ <a id="entities"></a>
52
+
53
+ # Entities
54
+
55
+ <a id="eric_sse.entities.AbstractChannel"></a>
56
+
57
+ ### *class* eric_sse.entities.AbstractChannel(stream_delay_seconds: int = 0)
58
+
59
+ Base class for channels.
60
+
61
+ Provides functionalities for listeners and message delivery management.
62
+ SSEChannel is the default implementation
63
+
64
+ <a id="eric_sse.entities.AbstractChannel.add_listener"></a>
65
+
66
+ #### add_listener() → [MessageQueueListener](#eric_sse.entities.MessageQueueListener)
67
+
68
+ Add the default listener
69
+
70
+ <a id="eric_sse.entities.AbstractChannel.broadcast"></a>
71
+
72
+ #### broadcast(msg: [Message](#eric_sse.entities.Message))
73
+
74
+ Enqueue a message to all listeners
75
+
76
+ <a id="eric_sse.entities.AbstractChannel.deliver_next"></a>
77
+
78
+ #### deliver_next(listener_id: str) → [Message](#eric_sse.entities.Message)
79
+
80
+ Returns next message for given listener id.
81
+ Raises a NoMessagesException if queue is empty
82
+
83
+ <a id="eric_sse.entities.AbstractChannel.dispatch"></a>
84
+
85
+ #### dispatch(listener_id: str, msg: [Message](#eric_sse.entities.Message))
86
+
87
+ Adds a message to listener’s queue
88
+
89
+ <a id="eric_sse.entities.AbstractChannel.message_stream"></a>
90
+
91
+ #### *async* message_stream(listener: [MessageQueueListener](#eric_sse.entities.MessageQueueListener)) → AsyncIterable[dict]
92
+
93
+ Entry point for message streaming
94
+
95
+ In case of failure at channel resolution time, a special message with type=MESSAGE_TYPE_CLOSED is sent, and
96
+ correspondant listener is stopped
97
+
98
+ <a id="eric_sse.entities.AbstractChannel.register_listener"></a>
99
+
100
+ #### register_listener(l: [MessageQueueListener](#eric_sse.entities.MessageQueueListener))
101
+
102
+ Adds a listener to channel
103
+
104
+ <a id="eric_sse.entities.Message"></a>
105
+
106
+ ### *class* eric_sse.entities.Message(type: str, payload: dict | list | str | int | float | None = None)
107
+
108
+ Models a message
109
+
110
+ It’s just a container of information identified by a type.
111
+ For validation purposes you can override MessageQueueListener.on_message
112
+
113
+ <a id="eric_sse.entities.MessageQueueListener"></a>
114
+
115
+ ### *class* eric_sse.entities.MessageQueueListener
116
+
117
+ Base class for listeners.
118
+
119
+ Optionally you can override on_message method if you need to inject code at message delivery time.
120
+
121
+ <a id="eric_sse.entities.MessageQueueListener.on_message"></a>
122
+
123
+ #### on_message(msg: [Message](#eric_sse.entities.Message)) → None
124
+
125
+ Event handler. It executes when a message is delivered to client
126
+
127
+ <a id="module-eric_sse.prefabs"></a>
128
+
129
+ <a id="prefab-channels-and-listeners"></a>
130
+
131
+ # Prefab channels and listeners
132
+
133
+ <a id="eric_sse.prefabs.DataProcessingChannel"></a>
134
+
135
+ ### *class* eric_sse.prefabs.DataProcessingChannel(max_workers: int, stream_delay_seconds: int = 0)
136
+
137
+ [Still experimental, it was never tested on some real use case] Channel intended for concurrent processing of data.
138
+
139
+ * **Parameters:**
140
+ * **max_workers** – Num og workers to use
141
+ * **stream_delay_seconds** – Can be used to limit response rate of streamings. Only applies to message_stream calls.
142
+
143
+ Relies on concurrent.futures.ThreadPoolExecutor.
144
+
145
+ Just override **adapt** method to control output returned to clients
146
+
147
+ MESSAGE_TYPE_CLOSED type is intended as end of stream. It should be considered as a reserved Message type.
148
+
149
+ Note that callback execution order is not guaranteed
150
+
151
+ <a id="eric_sse.prefabs.DataProcessingChannel.adapt"></a>
152
+
153
+ #### adapt(msg: [Message](#eric_sse.entities.Message)) → Any
154
+
155
+ Models output returned to clients
156
+
157
+ <a id="eric_sse.prefabs.DataProcessingChannel.notify_end"></a>
158
+
159
+ #### notify_end()
160
+
161
+ Broadcasts a MESSAGE_TYPE_CLOSED Message
162
+
163
+ <a id="eric_sse.prefabs.DataProcessingChannel.process_queue"></a>
164
+
165
+ #### *async* process_queue(l: [MessageQueueListener](#eric_sse.entities.MessageQueueListener)) → AsyncIterable[dict]
166
+
167
+ Launches the processing of the given listener’s queue
168
+
169
+ <a id="eric_sse.prefabs.SSEChannel"></a>
170
+
171
+ ### *class* eric_sse.prefabs.SSEChannel(stream_delay_seconds: int = 0, retry_timeout_milliseconds: int = 5)
172
+
173
+ SSE streaming channel.
174
+
175
+ * **Parameters:**
176
+ **retry_timeout_milliseconds** – Used to indicate waiting time to clients
177
+
178
+ See [https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format)
179
+
180
+ Currently, ‘id’ field is not supported.
181
+
182
+ <a id="module-eric_sse.servers"></a>
183
+
184
+ <a id="prefab-servers"></a>
185
+
186
+ # Prefab servers
187
+
188
+ <a id="eric_sse.servers.ChannelContainer"></a>
189
+
190
+ ### *class* eric_sse.servers.ChannelContainer
191
+
192
+ Helper class for management of multiple SSE channels cases of use.
193
+
194
+ <a id="eric_sse.servers.SocketServer"></a>
195
+
196
+ ### *class* eric_sse.servers.SocketServer(file_descriptor_path: str)
197
+
198
+ An implementation of a socket server that acts as a controller to interact with library
199
+
200
+ A static shortcut for starting a basic server is provided. See examples.
201
+ **Accepted format**: a plain (no nested) JSON with the following keys:
202
+ ``
203
+ "c": "channel id"
204
+ "v": "verb"
205
+ "t": "message type"
206
+ "p": "message payload"
207
+ ``
208
+
209
+ Possible values of verb identifies a supported action:
210
+
211
+ ``
212
+ "d" dispatch
213
+ "b" broadcast
214
+ "c" add listener
215
+ "w" watch (opens a stream)
216
+ ``
217
+
218
+ See examples
219
+
220
+ <a id="eric_sse.servers.SocketServer.connect_callback"></a>
221
+
222
+ #### *async static* connect_callback(reader: StreamReader, writer: StreamWriter)
223
+
224
+ Integration with SocketServer.
225
+
226
+ See [https://docs.python.org/3/library/asyncio-stream.html#asyncio.start_unix_server](https://docs.python.org/3/library/asyncio-stream.html#asyncio.start_unix_server)
227
+ Handles low-lwvel communication and raw messages parsing
228
+
229
+ <a id="eric_sse.servers.SocketServer.shutdown"></a>
230
+
231
+ #### *async* shutdown(server: Server)
232
+
233
+ Graceful Shutdown
234
+
235
+ <a id="eric_sse.servers.SocketServer.start"></a>
236
+
237
+ #### *static* start(file_descriptor_path: str)
238
+
239
+ Shortcut to start a server
240
+
241
+ <a id="module-eric_sse.exception"></a>
242
+
243
+ <a id="exceptions"></a>
244
+
245
+ # Exceptions
246
+
247
+ <a id="eric_sse.exception.InvalidChannelException"></a>
248
+
249
+ ### *exception* eric_sse.exception.InvalidChannelException
250
+
251
+ <a id="eric_sse.exception.InvalidListenerException"></a>
252
+
253
+ ### *exception* eric_sse.exception.InvalidListenerException
254
+
255
+ <a id="eric_sse.exception.InvalidMessageFormat"></a>
256
+
257
+ ### *exception* eric_sse.exception.InvalidMessageFormat
258
+
259
+ <a id="eric_sse.exception.NoMessagesException"></a>
260
+
261
+ ### *exception* eric_sse.exception.NoMessagesException
262
+
263
+ Raised when trying to fetch from an empty queue
264
+
265
+ <a id="changelog"></a>
266
+
267
+ # Changelog
268
+
269
+ 0.5.0.2
270
+
271
+ Fix: SSEChannel must accept stream_delay_seconds as constructor parameter
272
+
273
+ 0.5.0
274
+
275
+ * Removed Threaded listener class
276
+ * Added DataProcessingChannel.process_queue
277
+
278
+ 0.4.1.0
279
+
280
+ * Breaking: Changed DataProcessingChannel adapter to suit with SSE
281
+
282
+ 0.4.0
283
+
284
+ Breaking changes:
285
+
286
+ * Rework of DataProcessingChannel, now extends AbstractChannel and its methods’ signatures have been updated
287
+ * AbstractChannel.retry_timeout_milliseconds have been moved to SSEChannel
288
+
289
+ 0.3.2
290
+
291
+ * Breaking change: now ThreadPoolListener callback only accepts Message as parameter
292
+ * Fixed a concurrency bug in ThreadPoolListener
293
+
294
+ <a id="developers-section"></a>
295
+
296
+ # Developers section
297
+
298
+ Update README.md scipt: update_docs.sh
299
+
@@ -0,0 +1,280 @@
1
+ <a id="the-lightweight-library-for-async-messaging-nobody-expects"></a>
2
+
3
+ # The lightweight library for async messaging nobody expects.
4
+
5
+ <a id="installation"></a>
6
+
7
+ # Installation
8
+
9
+ pip install eric-sse
10
+
11
+ <a id="features"></a>
12
+
13
+ # Features
14
+
15
+ * Send to one listener and broadcast
16
+ * SSE format was adopted by design, is order to make library suitable for such kind of model
17
+ * Sockets
18
+ * Callbacks
19
+ * [**Experimental**] Threading support for large data processing
20
+
21
+ Possible applications
22
+
23
+ * Message delivery mechanisms based on SSE
24
+ * Message queue processing (logging, etc)
25
+ * See [https://github.com/laxertu/eric-api](https://github.com/laxertu/eric-api)
26
+
27
+ Trivia
28
+
29
+ Library name pretends to be a tribute to the following movie [https://en.wikipedia.org/wiki/Looking_for_Eric](https://en.wikipedia.org/wiki/Looking_for_Eric)
30
+
31
+ <a id="module-eric_sse.entities"></a>
32
+
33
+ <a id="entities"></a>
34
+
35
+ # Entities
36
+
37
+ <a id="eric_sse.entities.AbstractChannel"></a>
38
+
39
+ ### *class* eric_sse.entities.AbstractChannel(stream_delay_seconds: int = 0)
40
+
41
+ Base class for channels.
42
+
43
+ Provides functionalities for listeners and message delivery management.
44
+ SSEChannel is the default implementation
45
+
46
+ <a id="eric_sse.entities.AbstractChannel.add_listener"></a>
47
+
48
+ #### add_listener() → [MessageQueueListener](#eric_sse.entities.MessageQueueListener)
49
+
50
+ Add the default listener
51
+
52
+ <a id="eric_sse.entities.AbstractChannel.broadcast"></a>
53
+
54
+ #### broadcast(msg: [Message](#eric_sse.entities.Message))
55
+
56
+ Enqueue a message to all listeners
57
+
58
+ <a id="eric_sse.entities.AbstractChannel.deliver_next"></a>
59
+
60
+ #### deliver_next(listener_id: str) → [Message](#eric_sse.entities.Message)
61
+
62
+ Returns next message for given listener id.
63
+ Raises a NoMessagesException if queue is empty
64
+
65
+ <a id="eric_sse.entities.AbstractChannel.dispatch"></a>
66
+
67
+ #### dispatch(listener_id: str, msg: [Message](#eric_sse.entities.Message))
68
+
69
+ Adds a message to listener’s queue
70
+
71
+ <a id="eric_sse.entities.AbstractChannel.message_stream"></a>
72
+
73
+ #### *async* message_stream(listener: [MessageQueueListener](#eric_sse.entities.MessageQueueListener)) → AsyncIterable[dict]
74
+
75
+ Entry point for message streaming
76
+
77
+ In case of failure at channel resolution time, a special message with type=MESSAGE_TYPE_CLOSED is sent, and
78
+ correspondant listener is stopped
79
+
80
+ <a id="eric_sse.entities.AbstractChannel.register_listener"></a>
81
+
82
+ #### register_listener(l: [MessageQueueListener](#eric_sse.entities.MessageQueueListener))
83
+
84
+ Adds a listener to channel
85
+
86
+ <a id="eric_sse.entities.Message"></a>
87
+
88
+ ### *class* eric_sse.entities.Message(type: str, payload: dict | list | str | int | float | None = None)
89
+
90
+ Models a message
91
+
92
+ It’s just a container of information identified by a type.
93
+ For validation purposes you can override MessageQueueListener.on_message
94
+
95
+ <a id="eric_sse.entities.MessageQueueListener"></a>
96
+
97
+ ### *class* eric_sse.entities.MessageQueueListener
98
+
99
+ Base class for listeners.
100
+
101
+ Optionally you can override on_message method if you need to inject code at message delivery time.
102
+
103
+ <a id="eric_sse.entities.MessageQueueListener.on_message"></a>
104
+
105
+ #### on_message(msg: [Message](#eric_sse.entities.Message)) → None
106
+
107
+ Event handler. It executes when a message is delivered to client
108
+
109
+ <a id="module-eric_sse.prefabs"></a>
110
+
111
+ <a id="prefab-channels-and-listeners"></a>
112
+
113
+ # Prefab channels and listeners
114
+
115
+ <a id="eric_sse.prefabs.DataProcessingChannel"></a>
116
+
117
+ ### *class* eric_sse.prefabs.DataProcessingChannel(max_workers: int, stream_delay_seconds: int = 0)
118
+
119
+ [Still experimental, it was never tested on some real use case] Channel intended for concurrent processing of data.
120
+
121
+ * **Parameters:**
122
+ * **max_workers** – Num og workers to use
123
+ * **stream_delay_seconds** – Can be used to limit response rate of streamings. Only applies to message_stream calls.
124
+
125
+ Relies on concurrent.futures.ThreadPoolExecutor.
126
+
127
+ Just override **adapt** method to control output returned to clients
128
+
129
+ MESSAGE_TYPE_CLOSED type is intended as end of stream. It should be considered as a reserved Message type.
130
+
131
+ Note that callback execution order is not guaranteed
132
+
133
+ <a id="eric_sse.prefabs.DataProcessingChannel.adapt"></a>
134
+
135
+ #### adapt(msg: [Message](#eric_sse.entities.Message)) → Any
136
+
137
+ Models output returned to clients
138
+
139
+ <a id="eric_sse.prefabs.DataProcessingChannel.notify_end"></a>
140
+
141
+ #### notify_end()
142
+
143
+ Broadcasts a MESSAGE_TYPE_CLOSED Message
144
+
145
+ <a id="eric_sse.prefabs.DataProcessingChannel.process_queue"></a>
146
+
147
+ #### *async* process_queue(l: [MessageQueueListener](#eric_sse.entities.MessageQueueListener)) → AsyncIterable[dict]
148
+
149
+ Launches the processing of the given listener’s queue
150
+
151
+ <a id="eric_sse.prefabs.SSEChannel"></a>
152
+
153
+ ### *class* eric_sse.prefabs.SSEChannel(stream_delay_seconds: int = 0, retry_timeout_milliseconds: int = 5)
154
+
155
+ SSE streaming channel.
156
+
157
+ * **Parameters:**
158
+ **retry_timeout_milliseconds** – Used to indicate waiting time to clients
159
+
160
+ See [https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format)
161
+
162
+ Currently, ‘id’ field is not supported.
163
+
164
+ <a id="module-eric_sse.servers"></a>
165
+
166
+ <a id="prefab-servers"></a>
167
+
168
+ # Prefab servers
169
+
170
+ <a id="eric_sse.servers.ChannelContainer"></a>
171
+
172
+ ### *class* eric_sse.servers.ChannelContainer
173
+
174
+ Helper class for management of multiple SSE channels cases of use.
175
+
176
+ <a id="eric_sse.servers.SocketServer"></a>
177
+
178
+ ### *class* eric_sse.servers.SocketServer(file_descriptor_path: str)
179
+
180
+ An implementation of a socket server that acts as a controller to interact with library
181
+
182
+ A static shortcut for starting a basic server is provided. See examples.
183
+ **Accepted format**: a plain (no nested) JSON with the following keys:
184
+ ``
185
+ "c": "channel id"
186
+ "v": "verb"
187
+ "t": "message type"
188
+ "p": "message payload"
189
+ ``
190
+
191
+ Possible values of verb identifies a supported action:
192
+
193
+ ``
194
+ "d" dispatch
195
+ "b" broadcast
196
+ "c" add listener
197
+ "w" watch (opens a stream)
198
+ ``
199
+
200
+ See examples
201
+
202
+ <a id="eric_sse.servers.SocketServer.connect_callback"></a>
203
+
204
+ #### *async static* connect_callback(reader: StreamReader, writer: StreamWriter)
205
+
206
+ Integration with SocketServer.
207
+
208
+ See [https://docs.python.org/3/library/asyncio-stream.html#asyncio.start_unix_server](https://docs.python.org/3/library/asyncio-stream.html#asyncio.start_unix_server)
209
+ Handles low-lwvel communication and raw messages parsing
210
+
211
+ <a id="eric_sse.servers.SocketServer.shutdown"></a>
212
+
213
+ #### *async* shutdown(server: Server)
214
+
215
+ Graceful Shutdown
216
+
217
+ <a id="eric_sse.servers.SocketServer.start"></a>
218
+
219
+ #### *static* start(file_descriptor_path: str)
220
+
221
+ Shortcut to start a server
222
+
223
+ <a id="module-eric_sse.exception"></a>
224
+
225
+ <a id="exceptions"></a>
226
+
227
+ # Exceptions
228
+
229
+ <a id="eric_sse.exception.InvalidChannelException"></a>
230
+
231
+ ### *exception* eric_sse.exception.InvalidChannelException
232
+
233
+ <a id="eric_sse.exception.InvalidListenerException"></a>
234
+
235
+ ### *exception* eric_sse.exception.InvalidListenerException
236
+
237
+ <a id="eric_sse.exception.InvalidMessageFormat"></a>
238
+
239
+ ### *exception* eric_sse.exception.InvalidMessageFormat
240
+
241
+ <a id="eric_sse.exception.NoMessagesException"></a>
242
+
243
+ ### *exception* eric_sse.exception.NoMessagesException
244
+
245
+ Raised when trying to fetch from an empty queue
246
+
247
+ <a id="changelog"></a>
248
+
249
+ # Changelog
250
+
251
+ 0.5.0.2
252
+
253
+ Fix: SSEChannel must accept stream_delay_seconds as constructor parameter
254
+
255
+ 0.5.0
256
+
257
+ * Removed Threaded listener class
258
+ * Added DataProcessingChannel.process_queue
259
+
260
+ 0.4.1.0
261
+
262
+ * Breaking: Changed DataProcessingChannel adapter to suit with SSE
263
+
264
+ 0.4.0
265
+
266
+ Breaking changes:
267
+
268
+ * Rework of DataProcessingChannel, now extends AbstractChannel and its methods’ signatures have been updated
269
+ * AbstractChannel.retry_timeout_milliseconds have been moved to SSEChannel
270
+
271
+ 0.3.2
272
+
273
+ * Breaking change: now ThreadPoolListener callback only accepts Message as parameter
274
+ * Fixed a concurrency bug in ThreadPoolListener
275
+
276
+ <a id="developers-section"></a>
277
+
278
+ # Developers section
279
+
280
+ Update README.md scipt: update_docs.sh
@@ -0,0 +1,11 @@
1
+ import logging
2
+ from logging import getLogger, StreamHandler, Logger
3
+
4
+
5
+ def get_logger() -> Logger:
6
+ logger = getLogger(__name__)
7
+ if not logger.handlers:
8
+ logger.setLevel(logging.INFO)
9
+ logger.addHandler(StreamHandler())
10
+
11
+ return logger
@@ -0,0 +1,177 @@
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
7
+
8
+ import eric_sse
9
+ from eric_sse.exception import InvalidChannelException, InvalidListenerException, NoMessagesException
10
+
11
+ logger = eric_sse.get_logger()
12
+
13
+ MESSAGE_TYPE_CLOSED = '_eric_channel_closed'
14
+
15
+
16
+ @dataclass
17
+ class Message:
18
+ """
19
+ Models a message
20
+
21
+ It's just a container of information identified by a type.
22
+ For validation purposes you can override MessageQueueListener.on_message
23
+ """
24
+ type: str
25
+ payload: dict | list | str | int | float | None = None
26
+
27
+
28
+ class MessageQueueListener(ABC):
29
+ """
30
+ Base class for listeners.
31
+
32
+ Optionally you can override on_message method if you need to inject code at message delivery time.
33
+ """
34
+ NEXT_ID = 1
35
+
36
+ def __init__(self):
37
+ with Lock():
38
+ self.id: str = str(MessageQueueListener.NEXT_ID)
39
+ MessageQueueListener.NEXT_ID += 1
40
+ self.__is_running: bool = False
41
+
42
+ async def start(self) -> None:
43
+ self.__is_running = True
44
+
45
+ def start_sync(self) -> None:
46
+ self.__is_running = True
47
+
48
+ async def is_running(self) -> bool:
49
+ return self.__is_running
50
+
51
+ def is_running_sync(self) -> bool:
52
+ return self.__is_running
53
+
54
+ async def stop(self) -> None:
55
+ self.__is_running = False
56
+
57
+ def stop_sync(self) -> None:
58
+ self.__is_running = False
59
+
60
+ def on_message(self, msg: Message) -> None:
61
+ """
62
+ Event handler. It executes when a message is delivered to client
63
+ """
64
+ pass
65
+
66
+
67
+ class AbstractChannel(ABC):
68
+ """
69
+ Base class for channels.
70
+
71
+ Provides functionalities for listeners and message delivery management.
72
+ SSEChannel is the default implementation
73
+ """
74
+ NEXT_ID = 1
75
+
76
+ def __init__(self, stream_delay_seconds: int = 0):
77
+ logger.info(f'Creating channel {AbstractChannel.NEXT_ID}')
78
+ with Lock():
79
+ self.id: str = str(AbstractChannel.NEXT_ID)
80
+ AbstractChannel.NEXT_ID += 1
81
+
82
+ self.listeners: dict[str: MessageQueueListener] = {}
83
+ self.queues: dict[str: list[Message]] = {}
84
+ self.stream_delay_seconds = stream_delay_seconds
85
+
86
+ def add_listener(self) -> MessageQueueListener:
87
+ """Add the default listener"""
88
+ l = MessageQueueListener()
89
+ self.register_listener(l)
90
+ return l
91
+
92
+ def register_listener(self, l: MessageQueueListener):
93
+ """
94
+ Adds a listener to channel
95
+ """
96
+ self.listeners[l.id] = l
97
+ self.queues[l.id] = []
98
+
99
+ def remove_listener(self, l_id: str):
100
+ del self.queues[l_id]
101
+ del self.listeners[l_id]
102
+
103
+ def deliver_next(self, listener_id: str) -> Message:
104
+ """
105
+ Returns next message for given listener id.
106
+ Raises a NoMessagesException if queue is empty
107
+ """
108
+ if self.get_listener(listener_id).is_running_sync():
109
+ try:
110
+ msg = self.__get_queue(listener_id).pop(0)
111
+ self.get_listener(listener_id).on_message(msg)
112
+
113
+ return msg
114
+ except IndexError:
115
+ raise NoMessagesException
116
+
117
+ def __get_queue(self, listener_id: str) -> list[Message]:
118
+ try:
119
+ return self.queues[listener_id]
120
+ except KeyError:
121
+ raise InvalidListenerException(f"Invalid listener {listener_id}")
122
+
123
+ def dispatch(self, listener_id: str, msg: Message):
124
+ """Adds a message to listener's queue"""
125
+
126
+ self.__add_to_queue(listener_id, msg)
127
+ logger.debug(f"Pending {len(self.queues[listener_id])} messages")
128
+
129
+ def __add_to_queue(self, listener_id: str, msg: Message):
130
+ self.__get_queue(listener_id).append(msg)
131
+
132
+ def broadcast(self, msg: Message):
133
+ """Enqueue a message to all listeners"""
134
+ for listener_id in self.listeners.keys():
135
+ self.dispatch(listener_id, msg=msg)
136
+
137
+ def get_listener(self, listener_id: str) -> MessageQueueListener:
138
+ try:
139
+ return self.listeners[listener_id]
140
+ except KeyError:
141
+ raise InvalidListenerException
142
+
143
+ @abstractmethod
144
+ def adapt(self, msg: Message) -> Any:
145
+ ...
146
+
147
+ async def message_stream(self, listener: MessageQueueListener) -> AsyncIterable[dict]:
148
+ """
149
+ Entry point for message streaming
150
+
151
+ In case of failure at channel resolution time, a special message with type=MESSAGE_TYPE_CLOSED is sent, and
152
+ correspondant listener is stopped
153
+ """
154
+ def new_messages():
155
+ try:
156
+ yield self.deliver_next(listener.id)
157
+ except NoMessagesException:
158
+ ...
159
+
160
+ async def event_generator() -> AsyncIterable[dict]:
161
+ while True:
162
+ # If client closes connection, stop sending events
163
+ if not await listener.is_running():
164
+ break
165
+
166
+ try:
167
+ for message in new_messages():
168
+ yield self.adapt(message)
169
+
170
+ await asyncio.sleep(self.stream_delay_seconds)
171
+ except InvalidChannelException as e:
172
+ logger.info(f"Stopping listener {listener.id}")
173
+ logger.debug(e)
174
+ await listener.stop()
175
+ yield self.adapt(Message(type=MESSAGE_TYPE_CLOSED))
176
+
177
+ return event_generator()
@@ -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,92 @@
1
+ from typing import Any, Callable, AsyncIterable, Iterator
2
+
3
+
4
+ from eric_sse import get_logger
5
+ from eric_sse.entities import AbstractChannel, Message, MessageQueueListener, MESSAGE_TYPE_CLOSED
6
+ from concurrent.futures import ThreadPoolExecutor, Future
7
+
8
+ logger = get_logger()
9
+
10
+ class SSEChannel(AbstractChannel):
11
+
12
+ """
13
+ SSE streaming channel.
14
+
15
+ :param retry_timeout_milliseconds: Used to indicate waiting time to clients
16
+
17
+ See https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format
18
+
19
+ Currently, 'id' field is not supported.
20
+ """
21
+ def __init__(self, stream_delay_seconds: int = 0, retry_timeout_milliseconds: int = 5):
22
+ super().__init__(stream_delay_seconds = stream_delay_seconds)
23
+ self.retry_timeout_milliseconds = retry_timeout_milliseconds
24
+
25
+ def adapt(self, msg: Message) -> Any:
26
+ return {
27
+ "event": msg.type,
28
+ "retry": self.retry_timeout_milliseconds,
29
+ "data": msg.payload
30
+ }
31
+
32
+
33
+ class DataProcessingChannel(AbstractChannel):
34
+ """
35
+ [Still experimental, it was never tested on some real use case] Channel intended for concurrent processing of data.
36
+
37
+ :param max_workers: Num og workers to use
38
+ :param stream_delay_seconds: Can be used to limit response rate of streamings. Only applies to message_stream calls.
39
+
40
+ Relies on concurrent.futures.ThreadPoolExecutor.
41
+
42
+ Just override **adapt** method to control output returned to clients
43
+
44
+
45
+ MESSAGE_TYPE_CLOSED type is intended as end of stream. It should be considered as a reserved Message type.
46
+
47
+ Note that callback execution order is not guaranteed
48
+ """
49
+
50
+ def __init__(self, max_workers: int, stream_delay_seconds: int = 0):
51
+ super().__init__(stream_delay_seconds=stream_delay_seconds)
52
+ self.max_workers = max_workers
53
+
54
+ async def process_queue(self, l: MessageQueueListener) -> AsyncIterable[dict]:
55
+ """Launches the processing of the given listener's queue"""
56
+ from concurrent.futures import as_completed
57
+ async def event_generator(listener: MessageQueueListener) -> AsyncIterable[dict]:
58
+ fs: Iterator[Future] = self._prepare_executor(listener)
59
+ for f in as_completed(fs):
60
+ yield self.adapt(f.result())
61
+
62
+ return event_generator(listener=l)
63
+
64
+ def _prepare_executor(self, listener: MessageQueueListener) -> Iterator[Future]:
65
+ with ThreadPoolExecutor(self.max_workers) as e:
66
+ there_are_peding_messages = True
67
+ while there_are_peding_messages:
68
+ try:
69
+ msg = self.queues[listener.id].pop(0)
70
+ yield e.submit(self.__invoke_callback_and_return, listener.on_message, msg)
71
+
72
+ except IndexError:
73
+ there_are_peding_messages = False
74
+
75
+
76
+ @staticmethod
77
+ def __invoke_callback_and_return(callback: Callable[[Message], None], msg: Message):
78
+ callback(msg)
79
+ return msg
80
+
81
+ def notify_end(self):
82
+ """Broadcasts a MESSAGE_TYPE_CLOSED Message"""
83
+ self.broadcast(Message(type=MESSAGE_TYPE_CLOSED))
84
+
85
+
86
+ def adapt(self, msg: Message) -> Any:
87
+ """Models output returned to clients"""
88
+ return {
89
+ "event": msg.type,
90
+ "data": msg.payload
91
+ }
92
+
@@ -0,0 +1,166 @@
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.prefabs import SSEChannel
14
+
15
+ logger = eric_sse.get_logger()
16
+
17
+
18
+ class ChannelContainer:
19
+ """Helper class for management 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 acts as a controller to interact with library
44
+
45
+ A static shortcut for starting a basic server is provided. See examples.
46
+ **Accepted format**: a plain (no nested) JSON with the following keys:
47
+ ```
48
+ "c": "channel id"
49
+ "v": "verb"
50
+ "t": "message type"
51
+ "p": "message payload"
52
+ ```
53
+
54
+ Possible values of verb identifies a supported action:
55
+
56
+ ```
57
+ "d" dispatch
58
+ "b" broadcast
59
+ "c" add listener
60
+ "w" watch (opens a stream)
61
+ ```
62
+
63
+ See examples
64
+ """
65
+ cc = ChannelContainer()
66
+
67
+ def __init__(self, file_descriptor_path: str):
68
+ self.__file_descriptor_path = file_descriptor_path
69
+
70
+ @staticmethod
71
+ def __parse(json_raw: str) -> (str, str, Message | None, str):
72
+ try:
73
+ parsed = json.loads(json_raw)
74
+ channel_id = parsed['c']
75
+ verb = parsed['v']
76
+ message = None
77
+ if verb not in ['w', 'c']:
78
+ message = Message(type=parsed['t'], payload=parsed.get('p'))
79
+
80
+ receiver_id: str = parsed.get('r')
81
+ return channel_id, verb, message, receiver_id
82
+
83
+ except KeyError as e:
84
+ logger.error(repr(e))
85
+ raise InvalidMessageFormat(json_raw)
86
+
87
+
88
+ @staticmethod
89
+ async def connect_callback(reader: StreamReader, writer: StreamWriter):
90
+ """
91
+ Integration with SocketServer.
92
+
93
+ See https://docs.python.org/3/library/asyncio-stream.html#asyncio.start_unix_server
94
+ Handles low-lwvel communication and raw messages parsing
95
+ """
96
+ try:
97
+ message_content = await reader.read()
98
+ channel_id, verb, message, receiver_id = SocketServer.__parse(message_content.decode())
99
+ channel = SocketServer.cc.get(channel_id)
100
+
101
+ logger.info(f'received command {verb}')
102
+
103
+ if verb == 'd':
104
+ channel.dispatch(receiver_id, message)
105
+ writer.write('ack'.encode())
106
+ writer.write_eof()
107
+ await writer.drain()
108
+
109
+
110
+ elif verb == 'b':
111
+ channel.broadcast(message)
112
+ writer.write('ack'.encode())
113
+ writer.write_eof()
114
+ await writer.drain()
115
+
116
+
117
+ elif verb == 'c':
118
+ l = channel.add_listener()
119
+ writer.write(l.id.encode())
120
+ writer.write_eof()
121
+ await writer.drain()
122
+
123
+
124
+ elif verb == 'w':
125
+ logger.info(f"Client watching on listener {receiver_id}")
126
+ async for m in await channel.message_stream(channel.get_listener(receiver_id)):
127
+ message = f'{json.dumps(m)}{os.linesep}'
128
+ logger.info(f"received message {message}")
129
+ writer.write(message.encode())
130
+
131
+ except Exception as e:
132
+ logger.error(e)
133
+ writer.write(repr(e).encode())
134
+ writer.write_eof()
135
+ await writer.drain()
136
+
137
+ async def shutdown(self, server: asyncio.Server):
138
+ """Graceful Shutdown"""
139
+ logger.info("graceful shutdown")
140
+ server.close()
141
+ await server.wait_closed()
142
+ Path(self.__file_descriptor_path).unlink()
143
+ logger.info("done")
144
+
145
+ async def main(self):
146
+ server = await start_unix_server(SocketServer.connect_callback, path=Path(self.__file_descriptor_path))
147
+ addr = server.sockets[0].getsockname()
148
+ logger.info(f'Serving on {addr}')
149
+
150
+ async with server:
151
+ for sig in (signal.SIGINT, signal.SIGTERM):
152
+ server.get_loop().add_signal_handler(
153
+ sig, lambda: asyncio.ensure_future(self.shutdown(server))
154
+ )
155
+ await server.serve_forever()
156
+
157
+ @staticmethod
158
+ def start(file_descriptor_path: str):
159
+ """Shortcut to start a server"""
160
+ logger.info('starting')
161
+ try:
162
+ server = SocketServer(file_descriptor_path)
163
+ asyncio.run(server.main())
164
+ except CancelledError:
165
+ exit(0)
166
+
@@ -0,0 +1,24 @@
1
+ [tool.poetry]
2
+ name = "eric-sse"
3
+ description = "A lightweight message dispatcher based on SSE protocol data transfer objects format"
4
+ version = "0.5.0.2"
5
+ authors = ["Luca Stretti <laxertu@gmail.com>"]
6
+ keywords = ["sse", "queue", "API", "concurrency"]
7
+ license = "MIT"
8
+ readme = "README.md"
9
+ homepage = "https://github.com/laxertu/eric"
10
+
11
+ [tool.poetry.dependencies]
12
+ python = ">= 3.10"
13
+ asyncio = ">= 3.4.3"
14
+
15
+ [tool.setuptools_scm]
16
+
17
+ [build-system]
18
+ requires = ["poetry-core"]
19
+ build-backend = "poetry.core.masonry.api"
20
+
21
+ [tool.poetry.group.test]
22
+ [tool.poetry.group.test.dependencies]
23
+ pytest = {version = ">= 8.3.2", optional = true}
24
+