fb-python-sdk 1.2.1__py3-none-any.whl → 1.2.2__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.
- {fb_python_sdk-1.2.1.dist-info → fb_python_sdk-1.2.2.dist-info}/METADATA +51 -34
- fb_python_sdk-1.2.2.dist-info/RECORD +26 -0
- {fb_python_sdk-1.2.1.dist-info → fb_python_sdk-1.2.2.dist-info}/WHEEL +1 -2
- fbclient/__init__.py +2 -2
- fbclient/category.py +4 -4
- fbclient/client.py +137 -62
- fbclient/common_types.py +107 -73
- fbclient/config.py +115 -76
- fbclient/data_storage.py +21 -12
- fbclient/evaluator.py +161 -125
- fbclient/event_processor.py +64 -33
- fbclient/event_types.py +29 -23
- fbclient/flag_change_notification.py +55 -33
- fbclient/interfaces.py +18 -11
- fbclient/notice_broadcaster.py +18 -12
- fbclient/status.py +26 -11
- fbclient/status_types.py +18 -12
- fbclient/streaming.py +166 -93
- fbclient/update_processor.py +7 -2
- fbclient/utils/__init__.py +47 -26
- fbclient/utils/exponential_backoff_jitter_strategy.py +14 -8
- fbclient/utils/http_client.py +48 -34
- fbclient/utils/repeatable_task.py +13 -5
- fbclient/utils/rwlock.py +7 -7
- fbclient/utils/variation_splitting_algorithm.py +6 -4
- fb_python_sdk-1.2.1.dist-info/RECORD +0 -27
- fb_python_sdk-1.2.1.dist-info/top_level.txt +0 -1
- {fb_python_sdk-1.2.1.dist-info → fb_python_sdk-1.2.2.dist-info}/licenses/LICENSE +0 -0
fbclient/streaming.py
CHANGED
|
@@ -11,14 +11,24 @@ from fbclient.flag_change_notification import FlagChangedNotice
|
|
|
11
11
|
from fbclient.interfaces import UpdateProcessor
|
|
12
12
|
from fbclient.notice_broadcaster import NoticeBroadcater
|
|
13
13
|
from fbclient.status import DataUpdateStatusProviderImpl
|
|
14
|
-
from fbclient.status_types import (
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
14
|
+
from fbclient.status_types import (
|
|
15
|
+
NETWORK_ERROR,
|
|
16
|
+
REQUEST_INVALID_ERROR,
|
|
17
|
+
RUNTIME_ERROR,
|
|
18
|
+
SYSTEM_QUIT,
|
|
19
|
+
UNKNOWN_CLOSE_CODE,
|
|
20
|
+
UNKNOWN_ERROR,
|
|
21
|
+
WEBSOCKET_ERROR,
|
|
22
|
+
State,
|
|
23
|
+
)
|
|
24
|
+
from fbclient.utils import (
|
|
25
|
+
build_headers,
|
|
26
|
+
build_token,
|
|
27
|
+
from_str_datetime_to_millis,
|
|
28
|
+
log,
|
|
29
|
+
valide_all_data,
|
|
30
|
+
)
|
|
31
|
+
from fbclient.utils.exponential_backoff_jitter_strategy import BackoffAndJitterStrategy
|
|
22
32
|
from fbclient.utils.repeatable_task import RepeatableTask
|
|
23
33
|
|
|
24
34
|
WS_NORMAL_CLOSE = 1000
|
|
@@ -34,10 +44,12 @@ _WEBSOCKET_TIMEOUT_LOCK = Lock()
|
|
|
34
44
|
|
|
35
45
|
|
|
36
46
|
class _SelfClosed:
|
|
37
|
-
def __init__(
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
is_self_close: bool = False,
|
|
50
|
+
is_reconn: bool = False,
|
|
51
|
+
state: Optional[State] = None,
|
|
52
|
+
):
|
|
41
53
|
self.is_self_close = is_self_close
|
|
42
54
|
self.is_reconn = is_reconn
|
|
43
55
|
self.state = state
|
|
@@ -53,19 +65,39 @@ def _data_to_dict(data: dict) -> Tuple[int, dict]:
|
|
|
53
65
|
segments = {}
|
|
54
66
|
all_data[FEATURE_FLAGS] = flags
|
|
55
67
|
all_data[SEGMENTS] = segments
|
|
56
|
-
for flag in data[
|
|
57
|
-
flag[
|
|
58
|
-
flag[
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
flag[
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
68
|
+
for flag in data["featureFlags"]:
|
|
69
|
+
flag["timestamp"] = from_str_datetime_to_millis(flag["updatedAt"])
|
|
70
|
+
flag["variationMap"] = dict(
|
|
71
|
+
(var["id"], var["value"]) for var in flag["variations"]
|
|
72
|
+
)
|
|
73
|
+
flag["_id"] = flag["id"]
|
|
74
|
+
flag["id"] = flag["key"]
|
|
75
|
+
flag["cat"] = FEATURE_FLAGS
|
|
76
|
+
flags[flag["id"]] = (
|
|
77
|
+
{
|
|
78
|
+
"id": flag["id"],
|
|
79
|
+
"cat": FEATURE_FLAGS,
|
|
80
|
+
"timestamp": flag["timestamp"],
|
|
81
|
+
"isArchived": True,
|
|
82
|
+
}
|
|
83
|
+
if flag["isArchived"]
|
|
84
|
+
else flag
|
|
85
|
+
)
|
|
86
|
+
version = max(version, flag["timestamp"])
|
|
87
|
+
for segment in data["segments"]:
|
|
88
|
+
segment["timestamp"] = from_str_datetime_to_millis(segment["updatedAt"])
|
|
89
|
+
segment["cat"] = SEGMENTS
|
|
90
|
+
segments[segment["id"]] = (
|
|
91
|
+
{
|
|
92
|
+
"id": segment["id"],
|
|
93
|
+
"cat": SEGMENTS,
|
|
94
|
+
"timestamp": segment["timestamp"],
|
|
95
|
+
"isArchived": True,
|
|
96
|
+
}
|
|
97
|
+
if segment["isArchived"]
|
|
98
|
+
else segment
|
|
99
|
+
)
|
|
100
|
+
version = max(version, segment["timestamp"])
|
|
69
101
|
return version, all_data
|
|
70
102
|
|
|
71
103
|
|
|
@@ -84,8 +116,14 @@ def _handle_ws_error(error: BaseException) -> Tuple[bool, bool, State]:
|
|
|
84
116
|
class Streaming(Thread, UpdateProcessor):
|
|
85
117
|
__ping_interval = 10.0
|
|
86
118
|
|
|
87
|
-
def __init__(
|
|
88
|
-
|
|
119
|
+
def __init__(
|
|
120
|
+
self,
|
|
121
|
+
config: Config,
|
|
122
|
+
broadcaster: NoticeBroadcater,
|
|
123
|
+
dataUpdateStatusProvider: DataUpdateStatusProviderImpl,
|
|
124
|
+
ready: Event,
|
|
125
|
+
):
|
|
126
|
+
super().__init__(name="featbit-streaming", daemon=True)
|
|
89
127
|
self.__config = config
|
|
90
128
|
self.__broadcaster = broadcaster
|
|
91
129
|
self.__storage = dataUpdateStatusProvider
|
|
@@ -102,25 +140,29 @@ class Streaming(Thread, UpdateProcessor):
|
|
|
102
140
|
self.__previous_websocket_timeout = None
|
|
103
141
|
self.__has_network = not config.is_offline
|
|
104
142
|
if self.__has_network:
|
|
105
|
-
self.__ping_task = RepeatableTask(
|
|
143
|
+
self.__ping_task = RepeatableTask(
|
|
144
|
+
"featbit-streaming-ping", self.__ping_interval, self._on_ping
|
|
145
|
+
)
|
|
106
146
|
self.__ping_task.start()
|
|
107
147
|
|
|
108
148
|
def _init_wsapp(self):
|
|
109
149
|
|
|
110
150
|
# authenfication and headers
|
|
111
151
|
token = build_token(self.__config.env_secret)
|
|
112
|
-
params =
|
|
152
|
+
params = "?token=%s&type=server" % token
|
|
113
153
|
url = self.__config.streaming_uri + params
|
|
114
154
|
headers = build_headers(self.__config.env_secret)
|
|
115
155
|
|
|
116
156
|
# init web socket app
|
|
117
|
-
self.__wsapp = websocket.WebSocketApp(
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
157
|
+
self.__wsapp = websocket.WebSocketApp(
|
|
158
|
+
url,
|
|
159
|
+
header=headers,
|
|
160
|
+
on_open=self._on_open,
|
|
161
|
+
on_message=self._on_message,
|
|
162
|
+
on_close=self._on_close,
|
|
163
|
+
on_error=self._on_error,
|
|
164
|
+
)
|
|
165
|
+
log.debug("Streaming WebSocket is connecting...")
|
|
124
166
|
|
|
125
167
|
def __prepare_connection_timeout(self):
|
|
126
168
|
# websocket-client exposes connection timeout as process-global state.
|
|
@@ -128,9 +170,11 @@ class Streaming(Thread, UpdateProcessor):
|
|
|
128
170
|
# environment's stalled connection attempt; in that case the second
|
|
129
171
|
# client proceeds with the timeout value already in effect.
|
|
130
172
|
if not _WEBSOCKET_TIMEOUT_LOCK.acquire(blocking=False):
|
|
131
|
-
log.warning(
|
|
132
|
-
|
|
133
|
-
|
|
173
|
+
log.warning(
|
|
174
|
+
"FB Python SDK: another WebSocket connection is "
|
|
175
|
+
"configuring the process timeout; using the current "
|
|
176
|
+
"timeout value"
|
|
177
|
+
)
|
|
134
178
|
return False
|
|
135
179
|
with self.__timeout_state_lock:
|
|
136
180
|
self.__timeout_lock_held = True
|
|
@@ -155,16 +199,18 @@ class Streaming(Thread, UpdateProcessor):
|
|
|
155
199
|
_WEBSOCKET_TIMEOUT_LOCK.release()
|
|
156
200
|
|
|
157
201
|
def run(self):
|
|
158
|
-
while
|
|
202
|
+
while not self.__force_close and self.__running and self.__has_network:
|
|
159
203
|
try:
|
|
160
204
|
self.__prepare_connection_timeout()
|
|
161
205
|
self._init_wsapp()
|
|
162
|
-
self.__wsapp.run_forever(
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
206
|
+
self.__wsapp.run_forever(
|
|
207
|
+
sslopt=self.__config.websocket.sslopt, # type: ignore
|
|
208
|
+
http_proxy_host=self.__config.websocket.proxy_host,
|
|
209
|
+
http_proxy_port=self.__config.websocket.proxy_port,
|
|
210
|
+
http_proxy_auth=self.__config.websocket.proxy_auth,
|
|
211
|
+
proxy_type=self.__config.websocket.proxy_type,
|
|
212
|
+
skip_utf8_validation=self.__config.websocket.skip_utf8_validation,
|
|
213
|
+
)
|
|
168
214
|
self.__restore_connection_timeout()
|
|
169
215
|
if self.__running:
|
|
170
216
|
# calculate the delay for reconn
|
|
@@ -173,11 +219,15 @@ class Streaming(Thread, UpdateProcessor):
|
|
|
173
219
|
# exponential-backoff delay immediately.
|
|
174
220
|
self.__stop_event.wait(delay)
|
|
175
221
|
except Exception as e:
|
|
176
|
-
log.exception(
|
|
222
|
+
log.exception("FB Python SDK: Streaming unexpected error: %s", str(e))
|
|
177
223
|
try:
|
|
178
|
-
self.__storage.update_state(
|
|
224
|
+
self.__storage.update_state(
|
|
225
|
+
State.interrupted_state(UNKNOWN_ERROR, str(e))
|
|
226
|
+
)
|
|
179
227
|
except Exception:
|
|
180
|
-
log.exception(
|
|
228
|
+
log.exception(
|
|
229
|
+
"FB Python SDK: could not publish streaming error state"
|
|
230
|
+
)
|
|
181
231
|
if self.__running and not self.__force_close:
|
|
182
232
|
# Constructor failures occur outside websocket-client's
|
|
183
233
|
# callback path, so they need the same backoff as normal
|
|
@@ -189,7 +239,7 @@ class Streaming(Thread, UpdateProcessor):
|
|
|
189
239
|
self.__wsapp = None
|
|
190
240
|
self.__self_closed = _SelfClosed()
|
|
191
241
|
self.__closed_by_error = False
|
|
192
|
-
log.debug(
|
|
242
|
+
log.debug("Streaming WebSocket process is over")
|
|
193
243
|
if not self.__ready.is_set():
|
|
194
244
|
# if an error like data format invalid occurs in the first attempt, set ready to make client not to wait
|
|
195
245
|
self.__ready.set()
|
|
@@ -197,8 +247,8 @@ class Streaming(Thread, UpdateProcessor):
|
|
|
197
247
|
# handle websocket auto close issue
|
|
198
248
|
def _on_ping(self):
|
|
199
249
|
if self.__wsapp and self.__wsapp.sock and self.__wsapp.sock.connected:
|
|
200
|
-
log.trace(
|
|
201
|
-
self.__wsapp.send(json.dumps({
|
|
250
|
+
log.trace("ping") # type: ignore
|
|
251
|
+
self.__wsapp.send(json.dumps({"messageType": "ping", "data": None}))
|
|
202
252
|
|
|
203
253
|
def _on_close(self, wsapp, close_code, close_msg):
|
|
204
254
|
self.__restore_connection_timeout()
|
|
@@ -206,20 +256,20 @@ class Streaming(Thread, UpdateProcessor):
|
|
|
206
256
|
# close by client
|
|
207
257
|
self.__running = self.__self_closed.is_reconn
|
|
208
258
|
state = self.__self_closed.state
|
|
209
|
-
log.debug(
|
|
259
|
+
log.debug("Streaming WebSocket close reason: self close")
|
|
210
260
|
elif self.__closed_by_error:
|
|
211
261
|
return
|
|
212
262
|
elif close_code == WS_INVALID_REQUEST_CLOSE:
|
|
213
263
|
# close by server with code 4003
|
|
214
264
|
self.__running = False
|
|
215
265
|
state = State.error_off_state(REQUEST_INVALID_ERROR, REQUEST_INVALID_ERROR)
|
|
216
|
-
log.debug(
|
|
266
|
+
log.debug("Streaming WebSocket close reason: %s" % REQUEST_INVALID_ERROR)
|
|
217
267
|
else:
|
|
218
268
|
# close by server with an unknown close code, restart immediately
|
|
219
269
|
self.__running = True
|
|
220
270
|
msg = close_msg if close_msg else UNKNOWN_CLOSE_CODE
|
|
221
271
|
state = State.interrupted_state(UNKNOWN_CLOSE_CODE, msg)
|
|
222
|
-
log.debug(
|
|
272
|
+
log.debug("Streaming WebSocket close reason: %s" % close_code)
|
|
223
273
|
|
|
224
274
|
if state:
|
|
225
275
|
self.__storage.update_state(state)
|
|
@@ -227,9 +277,11 @@ class Streaming(Thread, UpdateProcessor):
|
|
|
227
277
|
def _on_error(self, wsapp: websocket.WebSocketApp, error):
|
|
228
278
|
self.__restore_connection_timeout()
|
|
229
279
|
is_reconn, is_close_ws, state = _handle_ws_error(error)
|
|
230
|
-
log.warning(
|
|
280
|
+
log.warning("FB Python SDK: Streaming WebSocket Failure: %s" % str(error))
|
|
231
281
|
if is_close_ws:
|
|
232
|
-
self.__self_closed = _SelfClosed(
|
|
282
|
+
self.__self_closed = _SelfClosed(
|
|
283
|
+
is_self_close=True, is_reconn=is_reconn, state=state
|
|
284
|
+
)
|
|
233
285
|
wsapp.close(status=WS_GOING_AWAY_CLOSE)
|
|
234
286
|
else:
|
|
235
287
|
self.__running = is_reconn
|
|
@@ -239,9 +291,11 @@ class Streaming(Thread, UpdateProcessor):
|
|
|
239
291
|
def _on_open(self, wsapp: websocket.WebSocketApp):
|
|
240
292
|
self.__restore_connection_timeout()
|
|
241
293
|
self.__strategy.set_good_run()
|
|
242
|
-
log.debug(
|
|
243
|
-
version =
|
|
244
|
-
|
|
294
|
+
log.debug("Asking Data updating on WebSocket")
|
|
295
|
+
version = (
|
|
296
|
+
self.__storage.latest_version if self.__storage.latest_version > 0 else 0
|
|
297
|
+
)
|
|
298
|
+
data_sync_msg = {"messageType": "data-sync", "data": {"timestamp": version}}
|
|
245
299
|
json_str = json.dumps(data_sync_msg)
|
|
246
300
|
wsapp.send(json_str)
|
|
247
301
|
|
|
@@ -250,41 +304,48 @@ class Streaming(Thread, UpdateProcessor):
|
|
|
250
304
|
def get_feature_flag_keys_from_segment(flags, segment_id):
|
|
251
305
|
flag_keys = []
|
|
252
306
|
for flag in flags.values():
|
|
253
|
-
for rule in flag[
|
|
254
|
-
for condition in rule[
|
|
255
|
-
op = condition[
|
|
307
|
+
for rule in flag["rules"]: # type: ignore
|
|
308
|
+
for condition in rule["conditions"]: # type: ignore
|
|
309
|
+
op = condition["op"] # type: ignore
|
|
256
310
|
if not op:
|
|
257
311
|
try:
|
|
258
|
-
segment_ids = json.loads(condition[
|
|
312
|
+
segment_ids = json.loads(condition["value"]) # type: ignore
|
|
259
313
|
if segment_id in segment_ids: # type: ignore
|
|
260
|
-
flag_keys.append(flag[
|
|
314
|
+
flag_keys.append(flag["id"]) # type: ignore
|
|
261
315
|
except:
|
|
262
316
|
pass
|
|
263
317
|
return set(flag_keys)
|
|
264
318
|
|
|
265
319
|
def broacasting():
|
|
266
320
|
flags = self.__storage.get_all(FEATURE_FLAGS)
|
|
267
|
-
for items in all_data.values()
|
|
268
|
-
for item in sorted(items.values(), key=lambda x: x[
|
|
269
|
-
if item[
|
|
321
|
+
for items in all_data.values():
|
|
322
|
+
for item in sorted(items.values(), key=lambda x: x["timestamp"]):
|
|
323
|
+
if item["cat"] == FEATURE_FLAGS:
|
|
270
324
|
# listen flag changes
|
|
271
|
-
if item[
|
|
272
|
-
broacasting_ingnored_flag_keys.append(item[
|
|
273
|
-
self.__broadcaster.broadcast(FlagChangedNotice(item[
|
|
274
|
-
elif item[
|
|
325
|
+
if item["id"] not in broacasting_ingnored_flag_keys:
|
|
326
|
+
broacasting_ingnored_flag_keys.append(item["id"])
|
|
327
|
+
self.__broadcaster.broadcast(FlagChangedNotice(item["id"]))
|
|
328
|
+
elif item["cat"] == SEGMENTS:
|
|
275
329
|
# listen segment changes
|
|
276
|
-
flag_keys = get_feature_flag_keys_from_segment(
|
|
330
|
+
flag_keys = get_feature_flag_keys_from_segment(
|
|
331
|
+
flags, item["id"]
|
|
332
|
+
)
|
|
277
333
|
for flag_key in flag_keys:
|
|
278
334
|
if flag_key not in broacasting_ingnored_flag_keys:
|
|
279
335
|
broacasting_ingnored_flag_keys.append(flag_key)
|
|
280
|
-
self.__broadcaster.broadcast(
|
|
336
|
+
self.__broadcaster.broadcast(
|
|
337
|
+
FlagChangedNotice(flag_key)
|
|
338
|
+
)
|
|
281
339
|
|
|
282
|
-
log.debug(
|
|
340
|
+
log.debug("Streaming WebSocket is processing data")
|
|
283
341
|
version, all_data = _data_to_dict(data)
|
|
284
342
|
op_ok = False
|
|
285
|
-
if
|
|
286
|
-
op_ok = all(
|
|
287
|
-
|
|
343
|
+
if "patch" == data["eventType"]:
|
|
344
|
+
op_ok = all(
|
|
345
|
+
self.__storage.upsert(cat, item["id"], item, item["timestamp"])
|
|
346
|
+
for cat, items in all_data.items()
|
|
347
|
+
for item in sorted(items.values(), key=lambda x: x["timestamp"])
|
|
348
|
+
)
|
|
288
349
|
else:
|
|
289
350
|
op_ok = self.__storage.init(all_data, version)
|
|
290
351
|
if op_ok:
|
|
@@ -299,51 +360,63 @@ class Streaming(Thread, UpdateProcessor):
|
|
|
299
360
|
return op_ok
|
|
300
361
|
|
|
301
362
|
def _on_message(self, wsapp: websocket.WebSocketApp, msg):
|
|
302
|
-
log.trace(
|
|
363
|
+
log.trace("Streaming WebSocket data: %s" % msg) # type: ignore
|
|
303
364
|
try:
|
|
304
365
|
all_data = json.loads(msg)
|
|
305
366
|
except Exception:
|
|
306
|
-
log.exception(
|
|
367
|
+
log.exception(
|
|
368
|
+
"FB Python SDK: could not parse data-sync message; skipping message: %r",
|
|
369
|
+
msg,
|
|
370
|
+
)
|
|
307
371
|
return
|
|
308
|
-
if isinstance(all_data, dict) and all_data.get(
|
|
372
|
+
if isinstance(all_data, dict) and all_data.get("messageType") == "data-sync":
|
|
309
373
|
try:
|
|
310
374
|
self._handle_data_sync_message(wsapp, all_data)
|
|
311
375
|
except Exception:
|
|
312
|
-
log.exception(
|
|
376
|
+
log.exception(
|
|
377
|
+
"FB Python SDK: could not process data-sync message; skipping message: %r",
|
|
378
|
+
all_data,
|
|
379
|
+
)
|
|
313
380
|
|
|
314
381
|
def _handle_data_sync_message(self, wsapp: websocket.WebSocketApp, all_data):
|
|
315
382
|
if not valide_all_data(all_data):
|
|
316
|
-
log.error(
|
|
383
|
+
log.error(
|
|
384
|
+
"FB Python SDK: invalid data-sync message; skipping message: %r",
|
|
385
|
+
all_data,
|
|
386
|
+
)
|
|
317
387
|
return
|
|
318
|
-
if not self._on_process_data(all_data[
|
|
319
|
-
log.error(
|
|
388
|
+
if not self._on_process_data(all_data["data"]):
|
|
389
|
+
log.error(
|
|
390
|
+
"FB Python SDK: could not apply data-sync message; skipping message: %r",
|
|
391
|
+
all_data,
|
|
392
|
+
)
|
|
320
393
|
|
|
321
394
|
def stop(self):
|
|
322
|
-
log.info(
|
|
395
|
+
log.info("FB Python SDK: Streaming is stopping...")
|
|
323
396
|
self.__force_close = True
|
|
324
397
|
self.__running = False
|
|
325
398
|
self.__stop_event.set()
|
|
326
399
|
try:
|
|
327
400
|
self.__storage.update_state(State.normal_off_state())
|
|
328
401
|
except Exception:
|
|
329
|
-
log.exception(
|
|
402
|
+
log.exception("FB Python SDK: could not publish streaming shutdown state")
|
|
330
403
|
try:
|
|
331
404
|
if self.__wsapp:
|
|
332
|
-
self.__self_closed = _SelfClosed(
|
|
333
|
-
|
|
334
|
-
|
|
405
|
+
self.__self_closed = _SelfClosed(
|
|
406
|
+
is_self_close=True, is_reconn=False, state=State.normal_off_state()
|
|
407
|
+
)
|
|
335
408
|
self.__wsapp.close(status=WS_NORMAL_CLOSE)
|
|
336
409
|
except Exception:
|
|
337
|
-
log.exception(
|
|
410
|
+
log.exception("FB Python SDK: could not close the WebSocket connection")
|
|
338
411
|
if self.__has_network:
|
|
339
412
|
try:
|
|
340
413
|
self.__ping_task.stop()
|
|
341
414
|
except Exception:
|
|
342
|
-
log.exception(
|
|
415
|
+
log.exception("FB Python SDK: could not stop the streaming ping task")
|
|
343
416
|
if current_thread() is not self and self.is_alive():
|
|
344
417
|
self.join(self.__config.websocket.timeout + 1.0)
|
|
345
418
|
if self.is_alive():
|
|
346
|
-
log.warning(
|
|
419
|
+
log.warning("FB Python SDK: streaming thread did not stop in time")
|
|
347
420
|
|
|
348
421
|
@property
|
|
349
422
|
def initialized(self) -> bool:
|
fbclient/update_processor.py
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
from threading import Event
|
|
2
|
+
|
|
2
3
|
from fbclient.config import Config
|
|
3
4
|
from fbclient.interfaces import DataUpdateStatusProvider, UpdateProcessor
|
|
4
5
|
from fbclient.status_types import State
|
|
5
6
|
|
|
6
7
|
|
|
7
8
|
class NullUpdateProcessor(UpdateProcessor):
|
|
8
|
-
|
|
9
|
-
|
|
9
|
+
def __init__(
|
|
10
|
+
self,
|
|
11
|
+
config: Config,
|
|
12
|
+
dataUpdateStatusProvider: DataUpdateStatusProvider,
|
|
13
|
+
ready: Event,
|
|
14
|
+
):
|
|
10
15
|
self.__ready = ready
|
|
11
16
|
self.__store = dataUpdateStatusProvider
|
|
12
17
|
self.__offline = config.is_offline
|
fbclient/utils/__init__.py
CHANGED
|
@@ -11,7 +11,7 @@ from dateutil.parser import isoparse
|
|
|
11
11
|
|
|
12
12
|
TRACE_LEVEL = logging.DEBUG - 5
|
|
13
13
|
|
|
14
|
-
logging.addLevelName(TRACE_LEVEL,
|
|
14
|
+
logging.addLevelName(TRACE_LEVEL, "TRACE")
|
|
15
15
|
|
|
16
16
|
|
|
17
17
|
class _MyLogger(logging.getLoggerClass()):
|
|
@@ -26,16 +26,27 @@ logging.getLogger("schedule").setLevel(logging.ERROR)
|
|
|
26
26
|
|
|
27
27
|
log = logging.getLogger(sys.modules[__name__].__name__)
|
|
28
28
|
|
|
29
|
-
ALPHABETS = {
|
|
29
|
+
ALPHABETS = {
|
|
30
|
+
"0": "Q",
|
|
31
|
+
"1": "B",
|
|
32
|
+
"2": "W",
|
|
33
|
+
"3": "S",
|
|
34
|
+
"4": "P",
|
|
35
|
+
"5": "H",
|
|
36
|
+
"6": "D",
|
|
37
|
+
"7": "X",
|
|
38
|
+
"8": "Z",
|
|
39
|
+
"9": "U",
|
|
40
|
+
}
|
|
30
41
|
|
|
31
42
|
|
|
32
43
|
def build_headers(env_secret: str, extra_headers=None):
|
|
33
44
|
|
|
34
45
|
def build_default_headers():
|
|
35
46
|
return {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
47
|
+
"Authorization": env_secret,
|
|
48
|
+
"User-Agent": "fb-python-server-sdk",
|
|
49
|
+
"Content-Type": "application/json",
|
|
39
50
|
}
|
|
40
51
|
|
|
41
52
|
headers = build_default_headers()
|
|
@@ -47,7 +58,7 @@ def build_token(env_secret: str) -> str:
|
|
|
47
58
|
|
|
48
59
|
def encodeNumber(num, length):
|
|
49
60
|
s = "000000000000" + str(num)
|
|
50
|
-
return
|
|
61
|
+
return "".join(list(map(lambda ch: ALPHABETS[ch], s[len(s) - length :])))
|
|
51
62
|
|
|
52
63
|
text = env_secret.rstrip("=")
|
|
53
64
|
now = unix_timestamp_in_milliseconds()
|
|
@@ -58,7 +69,7 @@ def build_token(env_secret: str) -> str:
|
|
|
58
69
|
part3 = text[0:start]
|
|
59
70
|
part4 = timestampCode
|
|
60
71
|
part5 = text[start:]
|
|
61
|
-
return
|
|
72
|
+
return "%s%s%s%s%s" % (part1, part2, part3, part4, part5)
|
|
62
73
|
|
|
63
74
|
|
|
64
75
|
def unix_timestamp_in_milliseconds():
|
|
@@ -66,13 +77,18 @@ def unix_timestamp_in_milliseconds():
|
|
|
66
77
|
|
|
67
78
|
|
|
68
79
|
def valide_all_data(all_data=None) -> bool:
|
|
69
|
-
return
|
|
70
|
-
|
|
71
|
-
and
|
|
72
|
-
and
|
|
73
|
-
and
|
|
74
|
-
and
|
|
75
|
-
|
|
80
|
+
return (
|
|
81
|
+
isinstance(all_data, dict)
|
|
82
|
+
and all_data.get("messageType") == "data-sync"
|
|
83
|
+
and "data" in all_data
|
|
84
|
+
and isinstance(all_data["data"], dict)
|
|
85
|
+
and all(
|
|
86
|
+
k in all_data["data"] for k in ("eventType", "featureFlags", "segments")
|
|
87
|
+
)
|
|
88
|
+
and any(k == all_data["data"]["eventType"] for k in ("full", "patch"))
|
|
89
|
+
and isinstance(all_data["data"]["featureFlags"], Iterable)
|
|
90
|
+
and isinstance(all_data["data"]["segments"], Iterable)
|
|
91
|
+
)
|
|
76
92
|
|
|
77
93
|
|
|
78
94
|
def is_ascii(value: str) -> bool:
|
|
@@ -90,18 +106,21 @@ def is_url(value: str) -> bool:
|
|
|
90
106
|
|
|
91
107
|
|
|
92
108
|
def check_uwsgi():
|
|
93
|
-
if
|
|
109
|
+
if "uwsgi" in sys.modules:
|
|
94
110
|
# noinspection PyPackageRequirements,PyUnresolvedReferences
|
|
95
111
|
import uwsgi
|
|
96
|
-
|
|
112
|
+
|
|
113
|
+
if not hasattr(uwsgi, "opt"):
|
|
97
114
|
# means that we are not running under uwsgi
|
|
98
115
|
return
|
|
99
116
|
|
|
100
|
-
if uwsgi.opt.get(
|
|
117
|
+
if uwsgi.opt.get("enable-threads"):
|
|
101
118
|
return
|
|
102
|
-
if uwsgi.opt.get(
|
|
119
|
+
if uwsgi.opt.get("threads") is not None and int(uwsgi.opt.get("threads")) > 1:
|
|
103
120
|
return
|
|
104
|
-
raise ValueError(
|
|
121
|
+
raise ValueError(
|
|
122
|
+
"The Python Server SDK requires the 'enable-threads' or 'threads' option be passed to uWSGI."
|
|
123
|
+
)
|
|
105
124
|
|
|
106
125
|
|
|
107
126
|
def is_numeric(value) -> bool:
|
|
@@ -119,11 +138,13 @@ def from_str_datetime_to_millis(value: str) -> int:
|
|
|
119
138
|
return 0
|
|
120
139
|
|
|
121
140
|
|
|
122
|
-
def cast_variation_by_flag_type(
|
|
141
|
+
def cast_variation_by_flag_type(
|
|
142
|
+
flag_type: Optional[str], variation: Optional[str]
|
|
143
|
+
) -> Any:
|
|
123
144
|
try:
|
|
124
|
-
if
|
|
145
|
+
if "boolean" == flag_type or "json" == flag_type:
|
|
125
146
|
return json.loads(variation) # type: ignore
|
|
126
|
-
elif
|
|
147
|
+
elif "number" == flag_type:
|
|
127
148
|
float_value = float(variation) # type: ignore
|
|
128
149
|
return int(float_value) if float_value.is_integer() else float_value
|
|
129
150
|
else:
|
|
@@ -134,13 +155,13 @@ def cast_variation_by_flag_type(flag_type: Optional[str], variation: Optional[st
|
|
|
134
155
|
|
|
135
156
|
def simple_type_inference(value: Any) -> Optional[str]:
|
|
136
157
|
if isinstance(value, bool):
|
|
137
|
-
return
|
|
158
|
+
return "boolean"
|
|
138
159
|
elif isinstance(value, str):
|
|
139
|
-
return
|
|
160
|
+
return "string"
|
|
140
161
|
elif isinstance(value, Iterable) or isinstance(value, Mapping):
|
|
141
|
-
return
|
|
162
|
+
return "json"
|
|
142
163
|
elif is_numeric(value):
|
|
143
|
-
return
|
|
164
|
+
return "number"
|
|
144
165
|
elif value is None:
|
|
145
166
|
return None
|
|
146
167
|
else:
|
|
@@ -5,16 +5,18 @@ Base in https://docs.aws.amazon.com/general/latest/gr/api-retries.html
|
|
|
5
5
|
|
|
6
6
|
import random
|
|
7
7
|
from time import time
|
|
8
|
+
|
|
8
9
|
from fbclient.utils import log
|
|
9
10
|
|
|
10
11
|
|
|
11
12
|
class BackoffAndJitterStrategy:
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
13
|
+
def __init__(
|
|
14
|
+
self,
|
|
15
|
+
first_delay_in_seconds: float = 1.0,
|
|
16
|
+
max_delay_in_seconds: float = 60.0,
|
|
17
|
+
reset_interval_in_seconds: float = 60,
|
|
18
|
+
jitter_ratio: float = 0.5,
|
|
19
|
+
):
|
|
18
20
|
self.__retry_times = 0
|
|
19
21
|
self.__first_delay = first_delay_in_seconds
|
|
20
22
|
self.__reset_interval = reset_interval_in_seconds
|
|
@@ -37,7 +39,11 @@ class BackoffAndJitterStrategy:
|
|
|
37
39
|
|
|
38
40
|
def next_delay(self, force_to_restart_in_max_delay=False):
|
|
39
41
|
current_time = time()
|
|
40
|
-
if
|
|
42
|
+
if (
|
|
43
|
+
self.__latest_good_run > 0
|
|
44
|
+
and self.__reset_interval > 0
|
|
45
|
+
and current_time - self.__latest_good_run > self.__reset_interval
|
|
46
|
+
):
|
|
41
47
|
self.__retry_times = 0
|
|
42
48
|
if force_to_restart_in_max_delay:
|
|
43
49
|
self.__retry_times = 0
|
|
@@ -47,5 +53,5 @@ class BackoffAndJitterStrategy:
|
|
|
47
53
|
delay = self.__count_jitter_time(backoff) + backoff / 2
|
|
48
54
|
self.__retry_times += 1
|
|
49
55
|
self.__latest_good_run = 0
|
|
50
|
-
log.debug(
|
|
56
|
+
log.debug("next delay is %s" % str(delay))
|
|
51
57
|
return delay
|