Repository navigation
Expand file tree
/
Copy pathsse.py
More file actions
305 lines (250 loc) · 10.8 KB
/
Copy pathsse.py
File metadata and controls
305 lines (250 loc) · 10.8 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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
"""Low-level SSE Client."""
import logging
import os
import socket
import base64
import urllib
from urllib.parse import urlsplit
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'])
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._sock = 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()
if response.status != 200:
_LOGGER.error('sse request status code: %d', response.status)
return self._shutdown_requested
# Signal the connection is open before reading events (like EventSource `open`)
self._event_callback(SSEEvent(None, None, None, None))
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:
_LOGGER.debug('sse connection ended.')
if not self._shutdown_requested:
_LOGGER.debug('stack trace: ', exc_info=True)
finally:
sock, self._sock = self._sock, None
self._conn.close()
if sock is not None:
sock.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, proxy_url=None):
"""
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)
if proxy_url is None:
proxy_url = os.getenv("HTTPS_PROXY") if os.getenv("HTTPS_PROXY") else None
if proxy_url is not None:
proxy_host, proxy_port, proxy_headers = self._get_proxy_info(proxy_url)
self._conn = (HTTPSConnection(proxy_host, proxy_port, timeout=timeout)
if url.scheme == 'https'
else HTTPConnection(proxy_host, proxy_port, timeout=timeout))
self._conn.set_tunnel(url.hostname, url.port, headers=proxy_headers)
else:
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)
# Keep the socket: for responses delimited by connection close (no chunked encoding nor
# content-length), getresponse() clears self._conn.sock while the response keeps reading.
self._sock = self._conn.sock
return self._read_events()
def _get_proxy_info(self, proxy_url):
proxy_host = urlsplit(proxy_url).hostname
proxy_port = urlsplit(proxy_url).port
if proxy_port is None:
proxy_port = 443 if urlsplit(proxy_url).scheme == 'https' else 80
proxy_user = urllib.parse.unquote(urlsplit(proxy_url).username) if urlsplit(
proxy_url).username is not None else None
proxy_pass = urllib.parse.unquote(urlsplit(proxy_url).password) if urlsplit(
proxy_url).password is not None else ''
proxy_headers = {}
if proxy_user is not None:
auth_str = f"{proxy_user}:{proxy_pass}"
b64_auth = base64.b64encode(auth_str.encode("utf-8")).decode("ascii")
proxy_headers = {
"Proxy-Authorization": f"Basic {b64_auth}"
}
return proxy_host, proxy_port, proxy_headers
def shutdown(self):
"""Shutdown the current connection."""
sock = self._sock
if self._conn is None or 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
try:
sock.shutdown(socket.SHUT_RDWR)
except OSError: # connection ended (and socket closed) concurrently
_LOGGER.debug('sse connection already ended.')
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()
self._client_timeout = aiohttp.ClientTimeout(
total=60*60, sock_read=self._socket_read_timeout)
self._sess = aiohttp.ClientSession(timeout=self._client_timeout)
# aiohttp silently re-sends an idempotent request once if the server drops the connection,
# which would hide a failed attempt from the push manager's retry/backoff logic.
if hasattr(self._sess, '_retry_connection'):
self._sess._retry_connection = False
async def start(self, url, extra_headers=None, proxy_url=None):
"""
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:
_LOGGER.debug(self._socket_read_timeout)
async with self._sess.get(
url,
headers=get_headers(extra_headers),
timeout=self._client_timeout,
proxy=proxy_url,
) as response:
if response.status != 200:
_LOGGER.error('sse request status code: %d', response.status)
return
self._response = response
# Signal the connection is open before reading events (like EventSource `open`)
yield SSEEvent(None, None, None, None)
event_builder = EventBuilder()
async for line in response.content:
if line.startswith(b':'):
_LOGGER.debug("skipping empty 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:
if self._is_conn_closed_error(exc):
_LOGGER.debug('sse connection ended.')
return
_LOGGER.error('http client is throwing exceptions')
_LOGGER.debug('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