fb-python-sdk 1.2.0__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.0.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.0.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 -79
- fbclient/config.py +115 -76
- fbclient/data_storage.py +21 -12
- fbclient/evaluator.py +162 -152
- fbclient/event_processor.py +64 -33
- fbclient/event_types.py +29 -24
- 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.0.dist-info/RECORD +0 -27
- fb_python_sdk-1.2.0.dist-info/top_level.txt +0 -1
- {fb_python_sdk-1.2.0.dist-info → fb_python_sdk-1.2.2.dist-info}/licenses/LICENSE +0 -0
fbclient/status.py
CHANGED
|
@@ -5,13 +5,16 @@ from typing import Callable, Deque, List, Mapping, Tuple
|
|
|
5
5
|
|
|
6
6
|
from fbclient.category import Category
|
|
7
7
|
from fbclient.interfaces import DataStorage, DataUpdateStatusProvider
|
|
8
|
-
from fbclient.status_types import (
|
|
9
|
-
|
|
8
|
+
from fbclient.status_types import (
|
|
9
|
+
DATA_STORAGE_INIT_ERROR,
|
|
10
|
+
DATA_STORAGE_UPDATE_ERROR,
|
|
11
|
+
State,
|
|
12
|
+
StateType,
|
|
13
|
+
)
|
|
10
14
|
from fbclient.utils import log
|
|
11
15
|
|
|
12
16
|
|
|
13
17
|
class DataUpdateStatusProviderImpl(DataUpdateStatusProvider):
|
|
14
|
-
|
|
15
18
|
def __init__(self, storage: DataStorage):
|
|
16
19
|
self.__storage = storage
|
|
17
20
|
self.__current_state = State.intializing_state()
|
|
@@ -22,7 +25,9 @@ class DataUpdateStatusProviderImpl(DataUpdateStatusProvider):
|
|
|
22
25
|
] = deque()
|
|
23
26
|
self.__is_publishing_notifications = False
|
|
24
27
|
|
|
25
|
-
def init(
|
|
28
|
+
def init(
|
|
29
|
+
self, all_data: Mapping[Category, Mapping[str, dict]], version: int = 0
|
|
30
|
+
) -> bool:
|
|
26
31
|
try:
|
|
27
32
|
result = self.__storage.init(all_data, version)
|
|
28
33
|
except Exception as e:
|
|
@@ -42,7 +47,10 @@ class DataUpdateStatusProviderImpl(DataUpdateStatusProvider):
|
|
|
42
47
|
return result is not False
|
|
43
48
|
|
|
44
49
|
def __handle_exception(self, error: Exception, error_type: str, message: str):
|
|
45
|
-
log.exception(
|
|
50
|
+
log.exception(
|
|
51
|
+
"FB Python SDK: Data Storage error: %s, UpdateProcessor will attempt to receive the data"
|
|
52
|
+
% str(error)
|
|
53
|
+
)
|
|
46
54
|
self.update_state(State.interrupted_state(error_type, message))
|
|
47
55
|
|
|
48
56
|
def get_all(self, kind: Category) -> Mapping[str, dict]:
|
|
@@ -71,12 +79,19 @@ class DataUpdateStatusProviderImpl(DataUpdateStatusProvider):
|
|
|
71
79
|
error = new_state.error_track
|
|
72
80
|
# special case: if ``new_state`` is INTERRUPTED, but the previous state was INITIALIZING, the state will remain at INITIALIZING
|
|
73
81
|
# INTERRUPTED is only meaningful after a successful startup
|
|
74
|
-
if
|
|
82
|
+
if (
|
|
83
|
+
new_state_type == StateType.INTERRUPTED
|
|
84
|
+
and old_state_type == StateType.INITIALIZING
|
|
85
|
+
):
|
|
75
86
|
new_state_type = StateType.INITIALIZING
|
|
76
87
|
|
|
77
88
|
# normal case
|
|
78
89
|
if new_state_type != old_state_type or error is not None:
|
|
79
|
-
state_since =
|
|
90
|
+
state_since = (
|
|
91
|
+
time()
|
|
92
|
+
if new_state_type != old_state_type
|
|
93
|
+
else self.__current_state.state_since
|
|
94
|
+
)
|
|
80
95
|
self.__current_state = State(new_state_type, state_since, error)
|
|
81
96
|
# wakes up all threads waiting for the ok state to check the new state
|
|
82
97
|
self.__lock.notify_all()
|
|
@@ -102,7 +117,7 @@ class DataUpdateStatusProviderImpl(DataUpdateStatusProvider):
|
|
|
102
117
|
try:
|
|
103
118
|
listener(state)
|
|
104
119
|
except Exception:
|
|
105
|
-
log.exception(
|
|
120
|
+
log.exception("FB Python SDK: Update status listener failed")
|
|
106
121
|
|
|
107
122
|
def add_listener(self, listener: Callable[[State], None]):
|
|
108
123
|
if not callable(listener):
|
|
@@ -112,7 +127,7 @@ class DataUpdateStatusProviderImpl(DataUpdateStatusProvider):
|
|
|
112
127
|
if listener not in self.__listeners:
|
|
113
128
|
self.__listeners.append(listener)
|
|
114
129
|
except Exception:
|
|
115
|
-
log.exception(
|
|
130
|
+
log.exception("FB Python SDK: Could not add update status listener")
|
|
116
131
|
|
|
117
132
|
def remove_listener(self, listener: Callable[[State], None]):
|
|
118
133
|
with self.__lock:
|
|
@@ -121,7 +136,7 @@ class DataUpdateStatusProviderImpl(DataUpdateStatusProvider):
|
|
|
121
136
|
except ValueError:
|
|
122
137
|
pass
|
|
123
138
|
except Exception:
|
|
124
|
-
log.exception(
|
|
139
|
+
log.exception("FB Python SDK: Could not remove update status listener")
|
|
125
140
|
|
|
126
141
|
def wait_for_OKState(self, timeout: float = 0) -> bool:
|
|
127
142
|
_timeout = 0 if timeout is None or timeout <= 0 else timeout
|
|
@@ -133,7 +148,7 @@ class DataUpdateStatusProviderImpl(DataUpdateStatusProvider):
|
|
|
133
148
|
elif StateType.OFF == self.__current_state.state_type:
|
|
134
149
|
return False
|
|
135
150
|
else:
|
|
136
|
-
if
|
|
151
|
+
if _timeout == 0:
|
|
137
152
|
self.__lock.wait()
|
|
138
153
|
else:
|
|
139
154
|
now = time()
|
fbclient/status_types.py
CHANGED
|
@@ -2,27 +2,27 @@ from enum import Enum
|
|
|
2
2
|
from time import time
|
|
3
3
|
from typing import Optional
|
|
4
4
|
|
|
5
|
-
DATA_STORAGE_INIT_ERROR =
|
|
5
|
+
DATA_STORAGE_INIT_ERROR = "Data Storage init error"
|
|
6
6
|
|
|
7
|
-
DATA_STORAGE_UPDATE_ERROR =
|
|
7
|
+
DATA_STORAGE_UPDATE_ERROR = "Data Storage update error"
|
|
8
8
|
|
|
9
|
-
REQUEST_INVALID_ERROR =
|
|
9
|
+
REQUEST_INVALID_ERROR = "Request invalid"
|
|
10
10
|
|
|
11
|
-
DATA_INVALID_ERROR =
|
|
11
|
+
DATA_INVALID_ERROR = "Received Data invalid"
|
|
12
12
|
|
|
13
|
-
NETWORK_ERROR =
|
|
13
|
+
NETWORK_ERROR = "Network error"
|
|
14
14
|
|
|
15
|
-
RUNTIME_ERROR =
|
|
15
|
+
RUNTIME_ERROR = "Runtime error"
|
|
16
16
|
|
|
17
|
-
WEBSOCKET_ERROR =
|
|
17
|
+
WEBSOCKET_ERROR = "WebSocket error"
|
|
18
18
|
|
|
19
|
-
UNKNOWN_ERROR =
|
|
19
|
+
UNKNOWN_ERROR = "Unknown error"
|
|
20
20
|
|
|
21
|
-
UNKNOWN_CLOSE_CODE =
|
|
21
|
+
UNKNOWN_CLOSE_CODE = "Unknown close code"
|
|
22
22
|
|
|
23
|
-
SYSTEM_ERROR =
|
|
23
|
+
SYSTEM_ERROR = "System error"
|
|
24
24
|
|
|
25
|
-
SYSTEM_QUIT =
|
|
25
|
+
SYSTEM_QUIT = "System quit"
|
|
26
26
|
|
|
27
27
|
|
|
28
28
|
class StateType(Enum):
|
|
@@ -31,6 +31,7 @@ class StateType(Enum):
|
|
|
31
31
|
If it encounters an error that requires it to retry initialization, the state will remain at
|
|
32
32
|
INITIALIZING until it either succeeds and becomes OK, or permanently fails and becomes OFF.
|
|
33
33
|
"""
|
|
34
|
+
|
|
34
35
|
INITIALIZING = 1
|
|
35
36
|
"""
|
|
36
37
|
Indicates that the update processing is currently operational and has not had any problems since the
|
|
@@ -68,7 +69,12 @@ class ErrorTrack:
|
|
|
68
69
|
|
|
69
70
|
|
|
70
71
|
class State:
|
|
71
|
-
def __init__(
|
|
72
|
+
def __init__(
|
|
73
|
+
self,
|
|
74
|
+
state_type: "StateType",
|
|
75
|
+
state_since: float,
|
|
76
|
+
error_track: Optional["ErrorTrack"] = None,
|
|
77
|
+
):
|
|
72
78
|
self.__state_type = state_type
|
|
73
79
|
self.__state_since = state_since
|
|
74
80
|
self.__error_track = error_track
|
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
|