-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathsse.py
More file actions
233 lines (187 loc) · 7.78 KB
/
sse.py
File metadata and controls
233 lines (187 loc) · 7.78 KB
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
"""Low-level SSE Client."""
import logging
import socket
from collections import namedtuple
from http.client import HTTPConnection, HTTPSConnection
from urllib.parse import urlparse
from splitio.optional.loaders import asyncio, aiohttp
_LOGGER = logging.getLogger(__name__)
SSE_EVENT_ERROR = 'error'
SSE_EVENT_MESSAGE = 'message'
_DEFAULT_HEADERS = {'accept': 'text/event-stream'}
_EVENT_SEPARATORS = set([b'\n', b'\r\n'])
_DEFAULT_SOCKET_READ_TIMEOUT = 70
SSEEvent = namedtuple('SSEEvent', ['event_id', 'event', 'retry', 'data'])
__ENDING_CHARS = set(['\n', ''])
class EventBuilder(object):
"""Event builder class."""
_SEPARATOR = b':'
def __init__(self):
"""Construct a builder."""
self._lines = {}
def process_line(self, line):
"""
Process a new line.
:param line: Line to process
:type line: bytes
"""
try:
key, val = line.split(self._SEPARATOR, 1)
self._lines[key.decode('utf8').strip()] = val.decode('utf8').strip()
except ValueError: # key without a value
self._lines[line.decode('utf8').strip()] = None
def build(self):
"""Construct an event with relevant fields."""
return SSEEvent(self._lines.get('id'), self._lines.get('event'),
self._lines.get('retry'), self._lines.get('data'))
class SSEClient(object):
"""SSE Client implementation."""
def __init__(self, callback):
"""
Construct an SSE client.
:param callback: function to call when an event is received
:type callback: callable
"""
self._conn = None
self._event_callback = callback
self._shutdown_requested = False
def _read_events(self):
"""
Read events from the supplied connection.
:returns: True if the connection was ended by us. False if it was closed by the serve.
:rtype: bool
"""
try:
response = self._conn.getresponse()
event_builder = EventBuilder()
while True:
line = response.readline()
if line is None or len(line) <= 0: # connection ended
break
elif line.startswith(b':'): # comment. Skip
_LOGGER.debug("skipping sse comment")
continue
elif line in _EVENT_SEPARATORS:
event = event_builder.build()
_LOGGER.debug("dispatching event: %s", event)
self._event_callback(event)
event_builder = EventBuilder()
else:
event_builder.process_line(line)
except Exception: # pylint:disable=broad-except
_LOGGER.debug('sse connection ended.')
_LOGGER.debug('stack trace: ', exc_info=True)
finally:
self._conn.close()
self._conn = None # clear so it can be started again
return self._shutdown_requested
def start(self, url, extra_headers=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): # pylint:disable=protected-access
"""
Connect and start listening for events.
:param url: url to connect to
:type url: str
:param extra_headers: additional headers
:type extra_headers: dict[str, str]
:param timeout: connection & read timeout
:type timeout: float
:returns: True if the connection was ended by us. False if it was closed by the serve.
:rtype: bool
"""
if self._conn is not None:
raise RuntimeError('Client already started.')
self._shutdown_requested = False
url, headers = urlparse(url), get_headers(extra_headers)
self._conn = (HTTPSConnection(url.hostname, url.port, timeout=timeout)
if url.scheme == 'https'
else HTTPConnection(url.hostname, port=url.port, timeout=timeout))
self._conn.request('GET', '%s?%s' % (url.path, url.query), headers=headers)
return self._read_events()
def shutdown(self):
"""Shutdown the current connection."""
if self._conn is None or self._conn.sock is None:
_LOGGER.warning("no sse connection has been started on this SSEClient instance. Ignoring")
return
if self._shutdown_requested:
_LOGGER.warning("shutdown already requested")
return
self._shutdown_requested = True
self._conn.sock.shutdown(socket.SHUT_RDWR)
class SSEClientAsync(object):
"""SSE Client implementation."""
def __init__(self, socket_read_timeout=_DEFAULT_SOCKET_READ_TIMEOUT):
"""
Construct an SSE client.
:param url: url to connect to
:type url: str
:param extra_headers: additional headers
:type extra_headers: dict[str, str]
:param timeout: connection & read timeout
:type timeout: float
"""
self._socket_read_timeout = socket_read_timeout + socket_read_timeout * .3
self._response = None
self._done = asyncio.Event()
client_timeout = aiohttp.ClientTimeout(total=0, sock_read=self._socket_read_timeout)
self._sess = aiohttp.ClientSession(timeout=client_timeout)
async def start(self, url, extra_headers=None): # pylint:disable=protected-access
"""
Connect and start listening for events.
:returns: yield event when received
:rtype: SSEEvent
"""
_LOGGER.debug("Async SSEClient Started")
if self._response is not None:
raise RuntimeError('Client already started.')
self._done.clear()
try:
async with self._sess.get(url, headers=get_headers(extra_headers)) as response:
self._response = response
event_builder = EventBuilder()
async for line in response.content:
if line.startswith(b':'):
_LOGGER.debug("skipping emtpy line / comment")
continue
elif line in _EVENT_SEPARATORS:
_LOGGER.debug("dispatching event: %s", event_builder.build())
yield event_builder.build()
event_builder = EventBuilder()
else:
event_builder.process_line(line)
except Exception as exc: # pylint:disable=broad-except
if self._is_conn_closed_error(exc):
_LOGGER.debug('sse connection ended.')
return
_LOGGER.error('http client is throwing exceptions')
_LOGGER.error('stack trace: ', exc_info=True)
finally:
self._response = None
self._done.set()
async def shutdown(self):
"""Close connection"""
if self._response:
self._response.close()
# catching exception to avoid task hanging if a canceled exception occurred
try:
await self._done.wait()
except asyncio.CancelledError:
_LOGGER.debug("Exception waiting for SSE connection to end")
_LOGGER.debug('stack trace: ', exc_info=True)
pass
@staticmethod
def _is_conn_closed_error(exc):
"""Check if the ReadError is caused by the connection being closed."""
return isinstance(exc, aiohttp.ClientConnectionError) and str(exc) == "Connection closed"
async def close_session(self):
if not self._sess.closed:
await self._sess.close()
def get_headers(extra=None):
"""
Return default headers with added custom ones if specified.
:param extra: additional headers
:type extra: dict[str, str]
:returns: processed Headers
:rtype: dict
"""
headers = _DEFAULT_HEADERS.copy()
headers.update(extra if extra is not None else {})
return headers