-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathstatus_tracker.py
More file actions
359 lines (276 loc) · 13.6 KB
/
status_tracker.py
File metadata and controls
359 lines (276 loc) · 13.6 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
"""NotificationManagerKeeper implementation."""
from enum import Enum
import logging
from splitio.push.parser import ControlType
from splitio.util.time import get_current_epoch_time_ms
from splitio.models.telemetry import StreamingEventTypes, SSEConnectionError, SSEStreamingStatus
_LOGGER = logging.getLogger(__name__)
class Status(Enum):
"""Push subsystem statuses."""
PUSH_SUBSYSTEM_UP = 0
PUSH_SUBSYSTEM_DOWN = 1
PUSH_RETRYABLE_ERROR = 2
PUSH_NONRETRYABLE_ERROR = 3
class LastEventTimestamps(object): # pylint:disable=too-few-public-methods
"""Simple class to keep track of the last time multiple events occurred."""
def __init__(self):
"""Class constructor."""
self.control = -1
self.occupancy = -1
def reset(self):
"""Restore original values."""
self.control = -1
self.occupancy = -1
class PushStatusTrackerBase(object):
"""Tracks status of notification manager/publishers."""
def __init__(self, telemetry_runtime_producer):
"""Class constructor."""
self._publishers = {}
self._last_control_message = None
self._last_status_propagated = None
self._timestamps = LastEventTimestamps()
self._shutdown_expected = None
self.reset() # Set proper initial values
self._telemetry_runtime_producer = telemetry_runtime_producer
def reset(self):
"""
Reset the status to initial conditions.
This asssumes a healthy connection until proven wrong.
"""
self._publishers.update({'control_pri': 2, 'control_sec': 2})
self._last_control_message = ControlType.STREAMING_ENABLED
self._last_status_propagated = Status.PUSH_SUBSYSTEM_UP
self._timestamps.reset()
self._shutdown_expected = False
def notify_sse_shutdown_expected(self):
"""Let the status tracker know that an sse shutdown has been requested."""
self._shutdown_expected = True
def _propagate_status(self, status):
"""
Store and propagates a new status.
:param status: Status to propagate.
:type status: Status
:returns: Status to propagate
:rtype: status
"""
self._last_status_propagated = status
return status
def _occupancy_ok(self):
"""
Return whether we have enough publishers.
:returns: True if publisher count is enough. False otherwise
:rtype: bool
"""
return any(count > 0 for (chan, count) in self._publishers.items())
def _get_event_type_occupancy(self, event):
return StreamingEventTypes.OCCUPANCY_PRI if event.channel[-3:] == 'pri' else StreamingEventTypes.OCCUPANCY_SEC
def _get_next_status(self):
"""
Return the next status to propagate based on the last status.
:returns: Next status and Streaming status for telemetry event.
:rtype: Tuple(splitio.push.status_tracker.Status, splitio.models.telemetry.SSEStreamingStatus)
"""
if self._last_status_propagated == Status.PUSH_SUBSYSTEM_UP:
if not self._occupancy_ok() \
or self._last_control_message == ControlType.STREAMING_PAUSED:
return self._propagate_status(Status.PUSH_SUBSYSTEM_DOWN), SSEStreamingStatus.PAUSED.value
if self._last_control_message == ControlType.STREAMING_DISABLED:
return self._propagate_status(Status.PUSH_NONRETRYABLE_ERROR), SSEStreamingStatus.DISABLED.value
if self._last_status_propagated == Status.PUSH_SUBSYSTEM_DOWN:
if self._occupancy_ok() and self._last_control_message == ControlType.STREAMING_ENABLED:
return self._propagate_status(Status.PUSH_SUBSYSTEM_UP), SSEStreamingStatus.ENABLED.value
if self._last_control_message == ControlType.STREAMING_DISABLED:
return self._propagate_status(Status.PUSH_NONRETRYABLE_ERROR), SSEStreamingStatus.DISABLED.value
return None, None
class PushStatusTracker(PushStatusTrackerBase):
"""Tracks status of notification manager/publishers."""
def __init__(self, telemetry_runtime_producer):
"""Class constructor."""
PushStatusTrackerBase.__init__(self, telemetry_runtime_producer)
def handle_occupancy(self, event):
"""
Handle an incoming occupancy event.
:param event: incoming occupancy event.
:type event: splitio.push.sse.parser.Occupancy
:returns: A new status if required. None otherwise
:rtype: Optional[Status]
"""
if self._shutdown_expected: # we don't care about occupancy if a disconnection is expected
return None
if event.channel not in self._publishers:
_LOGGER.info("received occupancy message from an unknown channel `%s`. Ignoring",
event.channel)
return None
if self._timestamps.occupancy > event.timestamp:
_LOGGER.info('received an old occupancy message. ignoring.')
return None
self._timestamps.occupancy = event.timestamp
self._publishers[event.channel] = event.publishers
self._telemetry_runtime_producer.record_streaming_event((
self._get_event_type_occupancy(event),
len(self._publishers),
event.timestamp
))
return self._update_status()
def handle_control_message(self, event):
"""
Handle an incoming Control event.
:param event: Incoming control event
:type event: splitio.push.parser.ControlMessage
"""
# we don't care about control messages if a disconnection is expected
if self._shutdown_expected:
return None
if self._timestamps.control > event.timestamp:
_LOGGER.info('receved an old control message. ignoring.')
return None
self._timestamps.control = event.timestamp
self._last_control_message = event.control_type
return self._update_status()
def handle_ably_error(self, event):
"""
Handle an ably-specific error.
:param event: parsed ably error
:type event: splitio.push.parser.AblyError
:returns: A new status if required. None otherwise
:rtype: Optional[Status]
"""
if self._shutdown_expected: # we don't care about an incoming error if a shutdown is expected
return None
_LOGGER.debug('handling ably error event: %s', str(event))
if event.should_be_ignored():
_LOGGER.debug('ignoring sse error message: %s', event)
return None
# Indicate that the connection will eventually end. 2 possibilities:
# 1. The server closes the connection after sending the error
# 2. RETRYABLE_ERROR is propagated and the connection is closed on the clint side.
# By doing this we guarantee that only one error will be propagated
self.notify_sse_shutdown_expected()
self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.ABLY_ERROR, event.code, event.timestamp))
if event.is_retryable():
_LOGGER.info('received retryable error message. '
'Restarting the whole flow with backoff.')
return self._propagate_status(Status.PUSH_RETRYABLE_ERROR)
_LOGGER.info('received non-retryable sse error message. Disabling streaming.')
return self._propagate_status(Status.PUSH_NONRETRYABLE_ERROR)
def _update_status(self):
"""
Evaluate the current/previous status and emit a new status message if appropriate.
:returns: A new status if required. None otherwise
:rtype: Optional[Status]
"""
next_status, telemetry_event_type = self._get_next_status()
if next_status is not None:
self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.STREAMING_STATUS, telemetry_event_type, get_current_epoch_time_ms()))
return next_status
return None
def handle_disconnect(self):
"""
Handle non-requested SSE disconnection.
It should properly handle:
- connection reset/timeout
- disconnection after an ably error
:returns: A new status if required. None otherwise
:rtype: Optional[Status]
"""
if not self._shutdown_expected:
self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.SSE_CONNECTION_ERROR, SSEConnectionError.NON_REQUESTED.value, get_current_epoch_time_ms()))
return self._propagate_status(Status.PUSH_RETRYABLE_ERROR)
self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.SSE_CONNECTION_ERROR, SSEConnectionError.REQUESTED.value, get_current_epoch_time_ms()))
return None
class PushStatusTrackerAsync(PushStatusTrackerBase):
"""Tracks status of notification manager/publishers."""
def __init__(self, telemetry_runtime_producer):
"""Class constructor."""
PushStatusTrackerBase.__init__(self, telemetry_runtime_producer)
async def handle_occupancy(self, event):
"""
Handle an incoming occupancy event.
:param event: incoming occupancy event.
:type event: splitio.push.sse.parser.Occupancy
:returns: A new status if required. None otherwise
:rtype: Optional[Status]
"""
if self._shutdown_expected: # we don't care about occupancy if a disconnection is expected
return None
if event.channel not in self._publishers:
_LOGGER.info("received occupancy message from an unknown channel `%s`. Ignoring",
event.channel)
return None
if self._timestamps.occupancy > event.timestamp:
_LOGGER.info('received an old occupancy message. ignoring.')
return None
self._timestamps.occupancy = event.timestamp
self._publishers[event.channel] = event.publishers
await self._telemetry_runtime_producer.record_streaming_event((
self._get_event_type_occupancy(event),
len(self._publishers),
event.timestamp
))
return await self._update_status()
async def handle_control_message(self, event):
"""
Handle an incoming Control event.
:param event: Incoming control event
:type event: splitio.push.parser.ControlMessage
"""
# we don't care about control messages if a disconnection is expected
if self._shutdown_expected:
return None
if self._timestamps.control > event.timestamp:
_LOGGER.info('receved an old control message. ignoring.')
return None
self._timestamps.control = event.timestamp
self._last_control_message = event.control_type
return await self._update_status()
async def handle_ably_error(self, event):
"""
Handle an ably-specific error.
:param event: parsed ably error
:type event: splitio.push.parser.AblyError
:returns: A new status if required. None otherwise
:rtype: Optional[Status]
"""
if self._shutdown_expected: # we don't care about an incoming error if a shutdown is expected
return None
_LOGGER.debug('handling ably error event: %s', str(event))
if event.should_be_ignored():
_LOGGER.debug('ignoring sse error message: %s', event)
return None
# Indicate that the connection will eventually end. 2 possibilities:
# 1. The server closes the connection after sending the error
# 2. RETRYABLE_ERROR is propagated and the connection is closed on the clint side.
# By doing this we guarantee that only one error will be propagated
self.notify_sse_shutdown_expected()
await self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.ABLY_ERROR, event.code, event.timestamp))
if event.is_retryable():
_LOGGER.info('received retryable error message. '
'Restarting the whole flow with backoff.')
return self._propagate_status(Status.PUSH_RETRYABLE_ERROR)
_LOGGER.info('received non-retryable sse error message. Disabling streaming.')
return self._propagate_status(Status.PUSH_NONRETRYABLE_ERROR)
async def _update_status(self):
"""
Evaluate the current/previous status and emit a new status message if appropriate.
:returns: A new status if required. None otherwise
:rtype: Optional[Status]
"""
next_status, telemetry_event_type = self._get_next_status()
if next_status is not None:
await self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.STREAMING_STATUS, telemetry_event_type, get_current_epoch_time_ms()))
return next_status
return None
async def handle_disconnect(self):
"""
Handle non-requested SSE disconnection.
It should properly handle:
- connection reset/timeout
- disconnection after an ably error
:returns: A new status if required. None otherwise
:rtype: Optional[Status]
"""
if not self._shutdown_expected:
await self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.SSE_CONNECTION_ERROR, SSEConnectionError.NON_REQUESTED.value, get_current_epoch_time_ms()))
return self._propagate_status(Status.PUSH_RETRYABLE_ERROR)
await self._telemetry_runtime_producer.record_streaming_event((StreamingEventTypes.SSE_CONNECTION_ERROR, SSEConnectionError.REQUESTED.value, get_current_epoch_time_ms()))
return None