Repository navigation
Expand file tree
/
Copy pathmanager.py
More file actions
622 lines (514 loc) · 24.2 KB
/
Copy pathmanager.py
File metadata and controls
622 lines (514 loc) · 24.2 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
"""Push subsystem manager class and helpers."""
import logging
from threading import Timer, Event
import abc
import sys
from splitio.optional.loaders import asyncio
from splitio.api import APIException
from splitio.util.time import get_current_epoch_time_ms
from splitio.push import AuthException
from splitio.push.splitsse import SplitSSEClient, SplitSSEClientAsync
from splitio.push.sse import SSE_EVENT_ERROR
from splitio.push.parser import parse_incoming_event, EventParsingException, EventType, \
MessageType
from splitio.push.processor import MessageProcessor, MessageProcessorAsync
from splitio.push.status_tracker import PushStatusTracker, Status, PushStatusTrackerAsync
from splitio.models.telemetry import StreamingEventTypes
if sys.version_info.major == 3 and sys.version_info.minor < 10:
from splitio.optional.loaders import _anext as anext
_TOKEN_REFRESH_GRACE_PERIOD = 10 * 60 # 10 minutes
_LOGGER = logging.getLogger(__name__)
class PushManagerBase(object, metaclass=abc.ABCMeta):
"""Worker template."""
@abc.abstractmethod
def update_workers_status(self, enabled):
"""Enable/Disable push update workers."""
@abc.abstractmethod
def start(self):
"""Start a new connection if not already running."""
@abc.abstractmethod
def stop(self, blocking=False):
"""Stop the current ongoing connection."""
def _get_time_period(self, token):
return (token.exp - token.iat) - _TOKEN_REFRESH_GRACE_PERIOD
class PushManager(PushManagerBase): # pylint:disable=too-many-instance-attributes
"""Push notifications susbsytem manager."""
def __init__(self, auth_api, synchronizer, feedback_loop, sdk_metadata, telemetry_runtime_producer, sse_url=None, client_key=None, proxy_url=None):
"""
Class constructor.
:param auth_api: sdk-auth-service api client
:type auth_api: splitio.api.auth.AuthAPI
:param synchronizer: split data synchronizer facade
:type synchronizer: splitio.sync.synchronizer.Synchronizer
:param feedback_loop: queue where push status updates are published.
:type feedback_loop: queue.Queue
:param sdk_metadata: SDK version & machine name & IP.
:type sdk_metadata: splitio.client.util.SdkMetadata
:param telemetry_runtime_producer: Telemetry object to record runtime events
:type sdk_metadata: splitio.engine.telemetry.TelemetryRunTimeProducer
:param sse_url: streaming base url.
:type sse_url: str
:param client_key: client key.
:type client_key: str
:param proxy_url: proxy url.
:type proxy_url: str
"""
self._auth_api = auth_api
self._feedback_loop = feedback_loop
self._processor = MessageProcessor(synchronizer, telemetry_runtime_producer)
self._status_tracker = PushStatusTracker(telemetry_runtime_producer)
self._event_handlers = {
EventType.MESSAGE: self._handle_message,
EventType.ERROR: self._handle_error
}
self._message_handlers = {
MessageType.UPDATE: self._handle_update,
MessageType.CONTROL: self._handle_control,
MessageType.OCCUPANCY: self._handle_occupancy
}
kwargs = {} if sse_url is None else {'base_url': sse_url}
self._sse_client = SplitSSEClient(self._event_handler, sdk_metadata, self._handle_connection_ready,
self._handle_connection_end, client_key, **kwargs, proxy_url=proxy_url)
self._running = False
self._stop_requested = Event() # set by stop() to abort an ongoing connection flow
self._next_refresh = Timer(0, lambda: 0)
self._telemetry_runtime_producer = telemetry_runtime_producer
def update_workers_status(self, enabled):
"""
Enable/Disable push update workers.
:param enabled: if True, enable workers. If False, disable them.
:type enabled: bool
"""
self._processor.update_workers_status(enabled)
def start(self):
"""Start a new connection if not already running."""
if self._running:
_LOGGER.warning('Push manager already has a connection running. Ignoring')
return
self._stop_requested.clear()
self._trigger_connection_flow()
def stop(self, blocking=False):
"""
Stop the current ongoing connection.
If called while connecting (e.g. waiting for the auth response), the connection flow is
aborted and no streaming connection is opened.
:param blocking: whether to wait for the connection to be successfully closed or not
:type blocking: bool
"""
self._stop_requested.set()
self._stop_connection(blocking)
def _stop_connection(self, blocking):
"""
Close the current connection, if any.
:param blocking: whether to wait for the connection to be successfully closed or not
:type blocking: bool
"""
if not self._running:
_LOGGER.warning('Push manager does not have an open SSE connection. Ignoring')
return
self._running = False
self._processor.update_workers_status(False)
self._status_tracker.notify_sse_shutdown_expected()
self._next_refresh.cancel()
self._sse_client.stop(blocking)
def _event_handler(self, event):
"""
Process an incoming event.
:param event: Incoming event
:type event: splitio.push.sse.SSEEvent
"""
try:
parsed = parse_incoming_event(event)
except EventParsingException:
_LOGGER.error('error parsing event of type %s', event.event_type)
_LOGGER.debug(str(event), exc_info=True)
return
try:
handle = self._event_handlers[parsed.event_type]
except KeyError:
_LOGGER.error('no handler for message of type %s', parsed.event_type)
_LOGGER.debug(str(event), exc_info=True)
return
try:
handle(parsed)
except Exception: # pylint:disable=broad-except
_LOGGER.error('something went wrong when processing message of type %s',
parsed.event_type)
_LOGGER.debug(str(parsed), exc_info=True)
def _token_refresh(self):
"""Refresh auth token."""
_LOGGER.info("retriggering authentication flow.")
try:
self._stop_connection(True)
self._trigger_connection_flow()
except Exception: # pylint:disable=broad-except
# This runs in the TokenRefresh timer thread. If it dies here, streaming stays
# stopped and polling is never started, so the SDK would stop receiving updates.
_LOGGER.error('unexpected error refreshing streaming token.')
_LOGGER.debug('stack trace: ', exc_info=True)
self._feedback_loop.put(Status.PUSH_RETRYABLE_ERROR)
def _trigger_connection_flow(self):
"""Authenticate and start a connection."""
try:
token = self._auth_api.authenticate()
except APIException:
_LOGGER.error('error performing sse auth request.')
_LOGGER.debug('stack trace: ', exc_info=True)
self._feedback_loop.put(Status.PUSH_RETRYABLE_ERROR)
return
except Exception: # pylint:disable=broad-except
# e.g. a non-JSON 200 response or a malformed token.
_LOGGER.error('unexpected error performing sse auth request.')
_LOGGER.debug('stack trace: ', exc_info=True)
self._feedback_loop.put(Status.PUSH_RETRYABLE_ERROR)
return
if self._stop_requested.is_set():
_LOGGER.debug('push manager stopped while authenticating. not connecting to streaming.')
return
if token is None or not token.push_enabled:
self._feedback_loop.put(Status.PUSH_NONRETRYABLE_ERROR)
return
self._telemetry_runtime_producer.record_token_refreshes()
_LOGGER.debug("auth token fetched. connecting to streaming.")
self._status_tracker.reset()
try:
connected = self._sse_client.start(token)
except Exception: # pylint:disable=broad-except
_LOGGER.error('unexpected error connecting to streaming.')
_LOGGER.debug('stack trace: ', exc_info=True)
self._feedback_loop.put(Status.PUSH_RETRYABLE_ERROR)
return
if connected and self._stop_requested.is_set():
_LOGGER.debug('push manager stopped while connecting. closing streaming connection.')
self._sse_client.stop()
return
if connected:
_LOGGER.debug("connected to streaming, scheduling next refresh")
self._setup_next_token_refresh(token)
self._running = True
self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.CONNECTION_ESTABLISHED, 0, get_current_epoch_time_ms()))
def _setup_next_token_refresh(self, token):
"""
Schedule next token refresh.
:param token: Last fetched token.
:type token: splitio.models.token.Token
"""
if self._next_refresh is not None:
self._next_refresh.cancel()
self._next_refresh = Timer(self._get_time_period(token), self._token_refresh)
self._next_refresh.setName('TokenRefresh')
self._next_refresh.start()
self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.TOKEN_REFRESH, 1000 * token.exp, get_current_epoch_time_ms()))
def _handle_message(self, event):
"""
Handle incoming update message.
:param event: Incoming Update message
:type event: splitio.push.sse.parser.Update
"""
try:
handle = self._message_handlers[event.message_type]
except KeyError:
_LOGGER.error('no handler for message of type %s', event.message_type)
_LOGGER.debug(str(event), exc_info=True)
return
handle(event)
def _handle_update(self, event):
"""
Handle incoming update message.
:param event: Incoming Update message
:type event: splitio.push.sse.parser.Update
"""
_LOGGER.debug('handling update event: %s', str(event))
self._processor.handle(event)
def _handle_control(self, event):
"""
Handle incoming control message.
:param event: Incoming control message.
:type event: splitio.push.sse.parser.ControlMessage
"""
_LOGGER.debug('handling control event: %s', str(event))
feedback = self._status_tracker.handle_control_message(event)
if feedback is not None:
self._feedback_loop.put(feedback)
def _handle_occupancy(self, event):
"""
Handle incoming notification message.
:param event: Incoming occupancy message.
:type event: splitio.push.sse.parser.Occupancy
"""
_LOGGER.debug('handling occupancy event: %s', str(event))
feedback = self._status_tracker.handle_occupancy(event)
if feedback is not None:
self._feedback_loop.put(feedback)
def _handle_error(self, event):
"""
Handle incoming error message.
:param event: Incoming ably error
:type event: splitio.push.sse.parser.AblyError
"""
_LOGGER.debug('handling ably error event: %s', str(event))
feedback = self._status_tracker.handle_ably_error(event)
if feedback is not None:
self._feedback_loop.put(feedback)
def _handle_connection_ready(self):
"""Handle a successful connection to SSE."""
self._feedback_loop.put(Status.PUSH_SUBSYSTEM_UP)
_LOGGER.info('sse initial event received. enabling')
def _handle_connection_end(self):
"""
Handle a connection ending.
If the connection shutdown was not requested, trigger a restart.
"""
feedback = self._status_tracker.handle_disconnect()
if feedback is not None:
self._feedback_loop.put(feedback)
class PushManagerAsync(PushManagerBase): # pylint:disable=too-many-instance-attributes
"""Push notifications susbsytem manager."""
def __init__(self, auth_api, synchronizer, feedback_loop, sdk_metadata, telemetry_runtime_producer, sse_url=None, client_key=None, proxy=None):
"""
Class constructor.
:param auth_api: sdk-auth-service api client
:type auth_api: splitio.api.auth.AuthAPI
:param synchronizer: split data synchronizer facade
:type synchronizer: splitio.sync.synchronizer.Synchronizer
:param feedback_loop: queue where push status updates are published.
:type feedback_loop: queue.Queue
:param sdk_metadata: SDK version & machine name & IP.
:type sdk_metadata: splitio.client.util.SdkMetadata
:param telemetry_runtime_producer: Telemetry object to record runtime events
:type sdk_metadata: splitio.engine.telemetry.TelemetryRunTimeProducer
:param sse_url: streaming base url.
:type sse_url: str
:param client_key: client key.
:type client_key: str
"""
self._auth_api = auth_api
self._feedback_loop = feedback_loop
self._processor = MessageProcessorAsync(synchronizer, telemetry_runtime_producer)
self._status_tracker = PushStatusTrackerAsync(telemetry_runtime_producer)
self._event_handlers = {
EventType.MESSAGE: self._handle_message,
EventType.ERROR: self._handle_error
}
self._message_handlers = {
MessageType.UPDATE: self._handle_update,
MessageType.CONTROL: self._handle_control,
MessageType.OCCUPANCY: self._handle_occupancy
}
kwargs = {} if sse_url is None else {'base_url': sse_url}
self._sse_client = SplitSSEClientAsync(sdk_metadata, client_key, **kwargs, proxy=proxy)
self._running = False
self._stop_requested = False # set by stop() to abort an ongoing connection flow
self._telemetry_runtime_producer = telemetry_runtime_producer
self._token_task = None
self._running_task = None
async def update_workers_status(self, enabled):
"""
Enable/Disable push update workers.
:param enabled: if True, enable workers. If False, disable them.
:type enabled: bool
"""
await self._processor.update_workers_status(enabled)
def start(self):
"""Start a new connection if not already running."""
if self._running:
_LOGGER.warning('Push manager already has a connection running. Ignoring')
return
self._stop_requested = False
self._running_task = asyncio.get_running_loop().create_task(self._trigger_connection_flow())
async def stop(self, blocking=False):
"""
Stop the current ongoing connection.
:param blocking: whether to wait for the connection to be successfully closed or not
:type blocking: bool
"""
self._stop_requested = True
if not self._running:
_LOGGER.warning('Push manager does not have an open SSE connection. Ignoring')
return
if self._token_task:
self._token_task.cancel()
self._token_task = None
if blocking:
await self._stop_current_conn()
else:
asyncio.get_running_loop().create_task(self._stop_current_conn())
async def close_sse_http_client(self):
await self._sse_client.close_sse_http_client()
async def _event_handler(self, event):
"""
Process an incoming event.
:param event: Incoming event
:type event: splitio.push.sse.SSEEvent
"""
parsed = None
try:
parsed = parse_incoming_event(event)
handle = self._event_handlers[parsed.event_type]
except Exception:
_LOGGER.error('Parsing exception or no handler for message of type %s', parsed.event_type if parsed else 'unknown')
_LOGGER.debug(str(event), exc_info=True)
return
try:
await handle(parsed)
except Exception: # pylint:disable=broad-except
event_type = "unknown" if parsed is None else parsed.event_type
_LOGGER.error('something went wrong when processing message of type %s', event_type)
_LOGGER.debug(str(parsed), exc_info=True)
async def _token_refresh(self, current_token):
"""Refresh auth token.
:param current_token: token (parsed) JWT
:type current_token: splitio.models.token.Token
"""
_LOGGER.debug("Next token refresh in " + str(self._get_time_period(current_token)) + " seconds")
await asyncio.sleep(self._get_time_period(current_token))
# This task is self._token_task. Detach it before closing the current connection,
# otherwise the connection task's cleanup cancels it and the new connection is never
# started, leaving the SDK without streaming and without polling.
self._token_task = None
try:
await self._stop_current_conn()
if self._stop_requested:
# stop() can't cancel this task once detached: don't reconnect after it.
_LOGGER.debug('push manager stopped while refreshing token. not reconnecting.')
return
self._running_task = asyncio.get_running_loop().create_task(
self._trigger_connection_flow())
except asyncio.CancelledError: # subclass of Exception in python 3.7
raise
except Exception: # pylint:disable=broad-except
# If this task ends here, streaming stays stopped and polling is never started.
_LOGGER.error('unexpected error refreshing streaming token.')
_LOGGER.debug('stack trace: ', exc_info=True)
await self._feedback_loop.put(Status.PUSH_RETRYABLE_ERROR)
async def _get_auth_token(self):
"""Get new auth token"""
try:
token = await self._auth_api.authenticate()
except APIException as e:
_LOGGER.error('error performing sse auth request.')
_LOGGER.debug('stack trace: ', exc_info=True)
await self._feedback_loop.put(Status.PUSH_RETRYABLE_ERROR)
raise AuthException(e)
if token is not None and not token.push_enabled:
await self._feedback_loop.put(Status.PUSH_NONRETRYABLE_ERROR)
raise AuthException("Push is not enabled")
await self._telemetry_runtime_producer.record_token_refreshes()
await self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.TOKEN_REFRESH, 1000 * token.exp, get_current_epoch_time_ms()))
_LOGGER.debug("auth token fetched. connecting to streaming.")
return token
async def _trigger_connection_flow(self):
"""Authenticate and start a connection."""
self._status_tracker.reset()
try:
token = await self._get_auth_token()
if self._stop_requested:
_LOGGER.debug('push manager stopped while authenticating. not connecting.')
return
events_source = self._sse_client.start(token)
self._running = True
first_event = await anext(events_source)
if first_event.data is not None:
await self._event_handler(first_event)
_LOGGER.debug("connected to streaming, scheduling next refresh")
self._token_task = asyncio.get_running_loop().create_task(self._token_refresh(token))
await self._handle_connection_ready()
await self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.CONNECTION_ESTABLISHED, 0, get_current_epoch_time_ms()))
async for event in events_source:
await self._event_handler(event)
await self._handle_connection_end() # TODO(mredolatti): this is not tested
except AuthException as e:
_LOGGER.error("error getting auth token: " + str(e))
_LOGGER.debug("trace: ", exc_info=True)
except StopAsyncIteration: # will enter here if there was an error
await self._feedback_loop.put(Status.PUSH_RETRYABLE_ERROR)
except asyncio.CancelledError: # subclass of Exception in python 3.7
raise
except Exception: # pylint:disable=broad-except
# e.g. a non-JSON 200 auth response, a malformed token or an sse client error.
# Without this the task ends silently and polling is never started.
_LOGGER.error('unexpected error in streaming connection flow.')
_LOGGER.debug('stack trace: ', exc_info=True)
await self._feedback_loop.put(Status.PUSH_RETRYABLE_ERROR)
finally:
if self._token_task is not None:
self._token_task.cancel()
self._token_task = None
self._running = False
await self._processor.update_workers_status(False)
async def _handle_message(self, event):
"""
Handle incoming update message.
:param event: Incoming Update message
:type event: splitio.push.sse.parser.Update
"""
try:
handle = self._message_handlers[event.message_type]
except KeyError:
_LOGGER.error('no handler for message of type %s', event.message_type)
_LOGGER.debug(str(event), exc_info=True)
return
await handle(event)
async def _handle_update(self, event):
"""
Handle incoming update message.
:param event: Incoming Update message
:type event: splitio.push.sse.parser.Update
"""
_LOGGER.debug('handling update event: %s', str(event))
await self._processor.handle(event)
async def _handle_control(self, event):
"""
Handle incoming control message.
:param event: Incoming control message.
:type event: splitio.push.sse.parser.ControlMessage
"""
_LOGGER.debug('handling control event: %s', str(event))
feedback = await self._status_tracker.handle_control_message(event)
if feedback is not None:
await self._feedback_loop.put(feedback)
async def _handle_occupancy(self, event):
"""
Handle incoming notification message.
:param event: Incoming occupancy message.
:type event: splitio.push.sse.parser.Occupancy
"""
_LOGGER.debug('handling occupancy event: %s', str(event))
feedback = await self._status_tracker.handle_occupancy(event)
if feedback is not None:
await self._feedback_loop.put(feedback)
async def _handle_error(self, event):
"""
Handle incoming error message.
:param event: Incoming ably error
:type event: splitio.push.sse.parser.AblyError
"""
_LOGGER.debug('handling ably error event: %s', str(event))
feedback = await self._status_tracker.handle_ably_error(event)
if feedback is not None:
await self._feedback_loop.put(feedback)
async def _handle_connection_ready(self):
"""Handle a successful connection to SSE."""
await self._feedback_loop.put(Status.PUSH_SUBSYSTEM_UP)
_LOGGER.info('sse initial event received. enabling')
async def _handle_connection_end(self):
"""
Handle a connection ending.
If the connection shutdown was not requested, trigger a restart.
"""
feedback = await self._status_tracker.handle_disconnect()
if feedback is not None:
await self._feedback_loop.put(feedback)
async def _stop_current_conn(self):
"""Abort current streaming connection and stop it's associated workers."""
_LOGGER.debug("Aborting SplitSSE tasks.")
await self._processor.update_workers_status(False)
self._status_tracker.notify_sse_shutdown_expected()
await self._sse_client.stop()
task, self._running_task = self._running_task, None
if task is not None:
task.cancel()
# Wait for the connection task to end. gather() keeps its cancellation from being
# raised here (only a cancellation of this coroutine is)
await asyncio.gather(task, return_exceptions=True)
_LOGGER.debug("SplitSSE tasks are stopped")