eric-sse 0.5.3__py3-none-any.whl

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/__init__.py ADDED
@@ -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
eric_sse/entities.py ADDED
@@ -0,0 +1,199 @@
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
+ MESSAGE_TYPE_END_OF_STREAM = '_eric_channel_closed'
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
+ self.__streaming_listeners: set[str] = set()
86
+
87
+
88
+ @property
89
+ def num_running_streams(self):
90
+ return len(self.__streaming_listeners)
91
+
92
+ def add_listener(self) -> MessageQueueListener:
93
+ """Add the default listener"""
94
+ l = MessageQueueListener()
95
+ self.register_listener(l)
96
+ return l
97
+
98
+ def register_listener(self, l: MessageQueueListener):
99
+ """
100
+ Adds a listener to channel
101
+ """
102
+ self.listeners[l.id] = l
103
+ self.queues[l.id] = []
104
+
105
+ def remove_listener(self, l_id: str):
106
+ del self.queues[l_id]
107
+ del self.listeners[l_id]
108
+ self.__streaming_listeners.discard(l_id)
109
+
110
+ def deliver_next(self, listener_id: str) -> Message:
111
+ """
112
+ Returns next message for given listener id.
113
+ Raises a NoMessagesException if queue is empty
114
+ """
115
+ if self.get_listener(listener_id).is_running_sync():
116
+ try:
117
+ with Lock():
118
+ msg = self.__get_queue(listener_id).pop(0)
119
+ self.get_listener(listener_id).on_message(msg)
120
+
121
+ return msg
122
+ except IndexError:
123
+ raise NoMessagesException
124
+
125
+ def __get_queue(self, listener_id: str) -> list[Message]:
126
+ try:
127
+ return self.queues[listener_id]
128
+ except KeyError:
129
+ raise InvalidListenerException(f"Invalid listener {listener_id}")
130
+
131
+ def dispatch(self, listener_id: str, msg: Message):
132
+ """Adds a message to listener's queue"""
133
+
134
+ self.__add_to_queue(listener_id, msg)
135
+ logger.debug(f"Pending {len(self.queues[listener_id])} messages")
136
+
137
+ def __add_to_queue(self, listener_id: str, msg: Message):
138
+ self.__get_queue(listener_id).append(msg)
139
+
140
+ def broadcast(self, msg: Message):
141
+ """Enqueue a message to all listeners"""
142
+ for listener_id in self.listeners.keys():
143
+ self.dispatch(listener_id, msg=msg)
144
+
145
+ def get_listener(self, listener_id: str) -> MessageQueueListener:
146
+ try:
147
+ return self.listeners[listener_id]
148
+ except KeyError:
149
+ raise InvalidListenerException
150
+
151
+ @abstractmethod
152
+ def adapt(self, msg: Message) -> Any:
153
+ ...
154
+
155
+ async def message_stream(self, listener: MessageQueueListener) -> AsyncIterable[dict]:
156
+ """
157
+ Entry point for message streaming
158
+
159
+ In case of failure at channel resolution time, a special message with type=MESSAGE_TYPE_CLOSED is sent, and
160
+ correspondant listener is stopped
161
+ """
162
+
163
+ def new_messages():
164
+ try:
165
+ yield self.deliver_next(listener.id)
166
+ except NoMessagesException:
167
+ ...
168
+
169
+ async def event_generator() -> AsyncIterable[dict]:
170
+
171
+
172
+ while True:
173
+ # If client closes connection, stop sending events
174
+ if not await listener.is_running():
175
+ break
176
+
177
+ try:
178
+ for message in new_messages():
179
+ yield self.adapt(message)
180
+
181
+ await asyncio.sleep(self.stream_delay_seconds)
182
+ except InvalidChannelException as e:
183
+ logger.info(f"Stopping listener {listener.id}")
184
+ logger.debug(e)
185
+ await listener.stop()
186
+ yield self.adapt(Message(type=MESSAGE_TYPE_CLOSED))
187
+
188
+ return event_generator()
189
+
190
+ def __prepare_stream(self, listener: MessageQueueListener):
191
+ if listener.id in self.__streaming_listeners:
192
+ raise InvalidListenerException(f'{listener.id} is already watching')
193
+ self.__streaming_listeners.add(listener.id)
194
+
195
+
196
+ def notify_end(self):
197
+ """Broadcasts a MESSAGE_TYPE_CLOSED Message"""
198
+ self.broadcast(Message(type=MESSAGE_TYPE_CLOSED))
199
+
eric_sse/exception.py ADDED
@@ -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
+ ...
eric_sse/prefabs.py ADDED
@@ -0,0 +1,87 @@
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
6
+ from concurrent.futures import ThreadPoolExecutor, Future, as_completed
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
+
57
+ async def event_generator(listener: MessageQueueListener) -> AsyncIterable[dict]:
58
+ for f in as_completed(self.__prepare_executor(listener)):
59
+ yield self.adapt(f.result())
60
+
61
+ return event_generator(listener=l)
62
+
63
+ def __prepare_executor(self, listener: MessageQueueListener) -> Iterator[Future]:
64
+ with ThreadPoolExecutor(self.max_workers) as e:
65
+ there_are_peding_messages = True
66
+ while there_are_peding_messages:
67
+ try:
68
+ msg = self.queues[listener.id].pop(0)
69
+ yield e.submit(self.__invoke_callback_and_return, listener.on_message, msg)
70
+
71
+ except IndexError:
72
+ there_are_peding_messages = False
73
+
74
+
75
+ @staticmethod
76
+ def __invoke_callback_and_return(callback: Callable[[Message], None], msg: Message):
77
+ callback(msg)
78
+ return msg
79
+
80
+
81
+ def adapt(self, msg: Message) -> Any:
82
+ """Models output returned to clients"""
83
+ return {
84
+ "event": msg.type,
85
+ "data": msg.payload
86
+ }
87
+
eric_sse/servers.py ADDED
@@ -0,0 +1,168 @@
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
+ ```
49
+ "c": "channel id"
50
+ "v": "verb"
51
+ "t": "message type"
52
+ "p": "message payload"
53
+ ```
54
+
55
+
56
+ Possible values of verb identifies a supported action:
57
+
58
+ ```
59
+ "d" dispatch
60
+ "b" broadcast
61
+ "c" add listener
62
+ "w" watch (opens a stream)
63
+ ```
64
+
65
+ See examples
66
+ """
67
+ cc = ChannelContainer()
68
+
69
+ def __init__(self, file_descriptor_path: str):
70
+ self.__file_descriptor_path = file_descriptor_path
71
+
72
+ @staticmethod
73
+ def __parse(json_raw: str) -> (str, str, Message | None, str):
74
+ try:
75
+ parsed = json.loads(json_raw)
76
+ channel_id = parsed['c']
77
+ verb = parsed['v']
78
+ message = None
79
+ if verb not in ['w', 'c']:
80
+ message = Message(type=parsed['t'], payload=parsed.get('p'))
81
+
82
+ receiver_id: str = parsed.get('r')
83
+ return channel_id, verb, message, receiver_id
84
+
85
+ except KeyError as e:
86
+ logger.error(repr(e))
87
+ raise InvalidMessageFormat(json_raw)
88
+
89
+
90
+ @staticmethod
91
+ async def connect_callback(reader: StreamReader, writer: StreamWriter):
92
+ """
93
+ Integration with SocketServer.
94
+
95
+ See https://docs.python.org/3/library/asyncio-stream.html#asyncio.start_unix_server
96
+ Handles low-lwvel communication and raw messages parsing
97
+ """
98
+ try:
99
+ message_content = await reader.read()
100
+ channel_id, verb, message, receiver_id = SocketServer.__parse(message_content.decode())
101
+ channel = SocketServer.cc.get(channel_id)
102
+
103
+ logger.info(f'received command {verb}')
104
+
105
+ if verb == 'd':
106
+ channel.dispatch(receiver_id, message)
107
+ writer.write('ack'.encode())
108
+ writer.write_eof()
109
+ await writer.drain()
110
+
111
+
112
+ elif verb == 'b':
113
+ channel.broadcast(message)
114
+ writer.write('ack'.encode())
115
+ writer.write_eof()
116
+ await writer.drain()
117
+
118
+
119
+ elif verb == 'c':
120
+ l = channel.add_listener()
121
+ writer.write(l.id.encode())
122
+ writer.write_eof()
123
+ await writer.drain()
124
+
125
+
126
+ elif verb == 'w':
127
+ logger.info(f"Client watching on listener {receiver_id}")
128
+ async for m in await channel.message_stream(channel.get_listener(receiver_id)):
129
+ message = f'{json.dumps(m)}{os.linesep}'
130
+ logger.info(f"received message {message}")
131
+ writer.write(message.encode())
132
+
133
+ except Exception as e:
134
+ logger.error(e)
135
+ writer.write(repr(e).encode())
136
+ writer.write_eof()
137
+ await writer.drain()
138
+
139
+ async def shutdown(self, server: asyncio.Server):
140
+ """Graceful Shutdown"""
141
+ logger.info("graceful shutdown")
142
+ server.close()
143
+ await server.wait_closed()
144
+ Path(self.__file_descriptor_path).unlink()
145
+ logger.info("done")
146
+
147
+ async def main(self):
148
+ server = await start_unix_server(SocketServer.connect_callback, path=Path(self.__file_descriptor_path))
149
+ addr = server.sockets[0].getsockname()
150
+ logger.info(f'Serving on {addr}')
151
+
152
+ async with server:
153
+ for sig in (signal.SIGINT, signal.SIGTERM):
154
+ server.get_loop().add_signal_handler(
155
+ sig, lambda: asyncio.ensure_future(self.shutdown(server))
156
+ )
157
+ await server.serve_forever()
158
+
159
+ @staticmethod
160
+ def start(file_descriptor_path: str):
161
+ """Shortcut to start a server"""
162
+ logger.info('starting')
163
+ try:
164
+ server = SocketServer(file_descriptor_path)
165
+ asyncio.run(server.main())
166
+ except CancelledError:
167
+ exit(0)
168
+
@@ -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,314 @@
1
+ Metadata-Version: 2.1
2
+ Name: eric-sse
3
+ Version: 0.5.3
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.notify_end"></a>
99
+
100
+ #### notify_end()
101
+
102
+ Broadcasts a MESSAGE_TYPE_CLOSED Message
103
+
104
+ <a id="eric_sse.entities.AbstractChannel.register_listener"></a>
105
+
106
+ #### register_listener(l: [MessageQueueListener](#eric_sse.entities.MessageQueueListener))
107
+
108
+ Adds a listener to channel
109
+
110
+ <a id="eric_sse.entities.Message"></a>
111
+
112
+ ### *class* eric_sse.entities.Message(type: str, payload: dict | list | str | int | float | None = None)
113
+
114
+ Models a message
115
+
116
+ It’s just a container of information identified by a type.
117
+ For validation purposes you can override MessageQueueListener.on_message
118
+
119
+ <a id="eric_sse.entities.MessageQueueListener"></a>
120
+
121
+ ### *class* eric_sse.entities.MessageQueueListener
122
+
123
+ Base class for listeners.
124
+
125
+ Optionally you can override on_message method if you need to inject code at message delivery time.
126
+
127
+ <a id="eric_sse.entities.MessageQueueListener.on_message"></a>
128
+
129
+ #### on_message(msg: [Message](#eric_sse.entities.Message)) → None
130
+
131
+ Event handler. It executes when a message is delivered to client
132
+
133
+ <a id="module-eric_sse.prefabs"></a>
134
+
135
+ <a id="prefab-channels-and-listeners"></a>
136
+
137
+ # Prefab channels and listeners
138
+
139
+ <a id="eric_sse.prefabs.DataProcessingChannel"></a>
140
+
141
+ ### *class* eric_sse.prefabs.DataProcessingChannel(max_workers: int, stream_delay_seconds: int = 0)
142
+
143
+ [Still experimental, it was never tested on some real use case] Channel intended for concurrent processing of data.
144
+
145
+ * **Parameters:**
146
+ * **max_workers** – Num og workers to use
147
+ * **stream_delay_seconds** – Can be used to limit response rate of streamings. Only applies to message_stream calls.
148
+
149
+ Relies on concurrent.futures.ThreadPoolExecutor.
150
+
151
+ Just override **adapt** method to control output returned to clients
152
+
153
+ MESSAGE_TYPE_CLOSED type is intended as end of stream. It should be considered as a reserved Message type.
154
+
155
+ Note that callback execution order is not guaranteed
156
+
157
+ <a id="eric_sse.prefabs.DataProcessingChannel.adapt"></a>
158
+
159
+ #### adapt(msg: [Message](#eric_sse.entities.Message)) → Any
160
+
161
+ Models output returned to clients
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
+ ``
204
+ "c": "channel id"
205
+ "v": "verb"
206
+ "t": "message type"
207
+ "p": "message payload"
208
+ ``
209
+
210
+ Possible values of verb identifies a supported action:
211
+
212
+ ``
213
+ "d" dispatch
214
+ "b" broadcast
215
+ "c" add listener
216
+ "w" watch (opens a stream)
217
+ ``
218
+
219
+ See examples
220
+
221
+ <a id="eric_sse.servers.SocketServer.connect_callback"></a>
222
+
223
+ #### *async static* connect_callback(reader: StreamReader, writer: StreamWriter)
224
+
225
+ Integration with SocketServer.
226
+
227
+ 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)
228
+ Handles low-lwvel communication and raw messages parsing
229
+
230
+ <a id="eric_sse.servers.SocketServer.shutdown"></a>
231
+
232
+ #### *async* shutdown(server: Server)
233
+
234
+ Graceful Shutdown
235
+
236
+ <a id="eric_sse.servers.SocketServer.start"></a>
237
+
238
+ #### *static* start(file_descriptor_path: str)
239
+
240
+ Shortcut to start a server
241
+
242
+ <a id="module-eric_sse.exception"></a>
243
+
244
+ <a id="exceptions"></a>
245
+
246
+ # Exceptions
247
+
248
+ <a id="eric_sse.exception.InvalidChannelException"></a>
249
+
250
+ ### *exception* eric_sse.exception.InvalidChannelException
251
+
252
+ <a id="eric_sse.exception.InvalidListenerException"></a>
253
+
254
+ ### *exception* eric_sse.exception.InvalidListenerException
255
+
256
+ <a id="eric_sse.exception.InvalidMessageFormat"></a>
257
+
258
+ ### *exception* eric_sse.exception.InvalidMessageFormat
259
+
260
+ <a id="eric_sse.exception.NoMessagesException"></a>
261
+
262
+ ### *exception* eric_sse.exception.NoMessagesException
263
+
264
+ Raised when trying to fetch from an empty queue
265
+
266
+ <a id="changelog"></a>
267
+
268
+ # Changelog
269
+
270
+ 0.5.3
271
+
272
+ * Restored behaviour of AbstractChannel.message_stream. Multiple streaming calls with same listener are allowed
273
+ * Added locking to queue pop
274
+
275
+ 0.5.2
276
+
277
+ Fixed close stream too early in AbstractChannel.message_stream
278
+
279
+ 0.5.1
280
+
281
+ AbstractChannel.message_stream raises and InvalidListenerException
282
+ if invoked more than one time with same listener
283
+
284
+ 0.5.0.2
285
+
286
+ Fix: SSEChannel must accept stream_delay_seconds as constructor parameter
287
+
288
+ 0.5.0
289
+
290
+ * Removed Threaded listener class
291
+ * Added DataProcessingChannel.process_queue
292
+
293
+ 0.4.1.0
294
+
295
+ * Breaking: Changed DataProcessingChannel adapter to suit with SSE
296
+
297
+ 0.4.0
298
+
299
+ Breaking changes:
300
+
301
+ * Rework of DataProcessingChannel, now extends AbstractChannel and its methods’ signatures have been updated
302
+ * AbstractChannel.retry_timeout_milliseconds have been moved to SSEChannel
303
+
304
+ 0.3.2
305
+
306
+ * Breaking change: now ThreadPoolListener callback only accepts Message as parameter
307
+ * Fixed a concurrency bug in ThreadPoolListener
308
+
309
+ <a id="developers-section"></a>
310
+
311
+ # Developers section
312
+
313
+ Update README.md scipt: update_docs.sh
314
+
@@ -0,0 +1,9 @@
1
+ eric_sse/__init__.py,sha256=R3UH4TFaFTgXNx9sQy0TxuS-rH_TA07eA94IDhuTuPk,259
2
+ eric_sse/entities.py,sha256=tKP6aIrCA4MBJYsIbM4rIgHhkUggUlb4pMGgmh_wQYI,6095
3
+ eric_sse/exception.py,sha256=nhuvWLUSWmnqiMzvVOaj0VG6axpzIdZlBheYeHx5lrY,258
4
+ eric_sse/prefabs.py,sha256=D9cSqgfU81vJ6DrOOyYIThHC17ntrMYdZNwORJAimoE,3076
5
+ eric_sse/servers.py,sha256=dteQfy3__0ILymK7b4aHTVZZ-md6Xe0RnQJim7OgvUo,5232
6
+ eric_sse-0.5.3.dist-info/LICENSE,sha256=3tC87d1at_76LKdchmFtrrXiU6_3xK8j4a7Sl-vC08c,1069
7
+ eric_sse-0.5.3.dist-info/METADATA,sha256=rvqp3gJI0HZvdrM5iPZB7A-je20dbHfii0yOYCJB9l8,8860
8
+ eric_sse-0.5.3.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
9
+ eric_sse-0.5.3.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 1.9.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any