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/event_processor.py
CHANGED
|
@@ -6,13 +6,17 @@ from typing import List, Optional
|
|
|
6
6
|
|
|
7
7
|
from fbclient.common_types import FBEvent
|
|
8
8
|
from fbclient.config import Config
|
|
9
|
-
from fbclient.event_types import (
|
|
10
|
-
|
|
9
|
+
from fbclient.event_types import (
|
|
10
|
+
EventMessage,
|
|
11
|
+
FlagEvent,
|
|
12
|
+
MessageType,
|
|
13
|
+
MetricEvent,
|
|
14
|
+
UserEvent,
|
|
15
|
+
)
|
|
11
16
|
from fbclient.interfaces import EventProcessor, Sender
|
|
12
17
|
from fbclient.utils import log
|
|
13
18
|
from fbclient.utils.repeatable_task import RepeatableTask
|
|
14
19
|
|
|
15
|
-
|
|
16
20
|
_THREAD_JOIN_TIMEOUT_SECONDS = 5.0
|
|
17
21
|
|
|
18
22
|
|
|
@@ -23,9 +27,11 @@ class DefaultEventProcessor(EventProcessor):
|
|
|
23
27
|
self.__lock = Lock()
|
|
24
28
|
self.__dispatcher = EventDispatcher(config, sender, self.__inbox)
|
|
25
29
|
self.__dispatcher.start()
|
|
26
|
-
self.__flush_task = RepeatableTask(
|
|
30
|
+
self.__flush_task = RepeatableTask(
|
|
31
|
+
"featbit-insight-flush", config.events_flush_interval, self.flush
|
|
32
|
+
)
|
|
27
33
|
self.__flush_task.start()
|
|
28
|
-
log.debug(
|
|
34
|
+
log.debug("insight processor is ready")
|
|
29
35
|
|
|
30
36
|
def __enter__(self):
|
|
31
37
|
return self
|
|
@@ -45,18 +51,22 @@ class DefaultEventProcessor(EventProcessor):
|
|
|
45
51
|
# if it reaches here, it means the application is probably doing tons of flag
|
|
46
52
|
# evaluations across many threads -- so if we wait for a space in the inbox, we risk a very serious slowdown
|
|
47
53
|
# of the app. To avoid that, we'll just drop the event or you can increase the capacity of inbox
|
|
48
|
-
log.warning(
|
|
54
|
+
log.warning(
|
|
55
|
+
"FB Python SDK: Events are being produced faster than they can be processed; some events will be dropped"
|
|
56
|
+
)
|
|
49
57
|
return False
|
|
50
58
|
|
|
51
59
|
def __put_message_async(self, type: MessageType, event: Optional[FBEvent] = None):
|
|
52
60
|
message = EventMessage(type, event, False)
|
|
53
61
|
if self.__put_message_to_inbox(message):
|
|
54
|
-
log.trace(
|
|
62
|
+
log.trace("put %s message to inbox" % str(type)) # type: ignore
|
|
55
63
|
|
|
56
|
-
def __put_message_and_wait_terminate(
|
|
64
|
+
def __put_message_and_wait_terminate(
|
|
65
|
+
self, type: MessageType, event: Optional[FBEvent] = None
|
|
66
|
+
):
|
|
57
67
|
message = EventMessage(type, event, True)
|
|
58
68
|
if self.__put_message_to_inbox(message):
|
|
59
|
-
log.debug(
|
|
69
|
+
log.debug("put %s WaitTermination message to inbox" % str(type))
|
|
60
70
|
message.waitForComplete()
|
|
61
71
|
|
|
62
72
|
def send_event(self, event: FBEvent):
|
|
@@ -69,7 +79,7 @@ class DefaultEventProcessor(EventProcessor):
|
|
|
69
79
|
elif isinstance(event, UserEvent):
|
|
70
80
|
self.__put_message_async(MessageType.USER, event)
|
|
71
81
|
else:
|
|
72
|
-
log.debug(
|
|
82
|
+
log.debug("ignore unknown event type")
|
|
73
83
|
|
|
74
84
|
def flush(self):
|
|
75
85
|
with self.__lock:
|
|
@@ -83,7 +93,7 @@ class DefaultEventProcessor(EventProcessor):
|
|
|
83
93
|
# Close the producer gate atomically so no application thread can
|
|
84
94
|
# append an event behind the shutdown marker.
|
|
85
95
|
self.__closed = True
|
|
86
|
-
log.info(
|
|
96
|
+
log.info("FB Python SDK: event processor is stopping")
|
|
87
97
|
self.__flush_task.stop()
|
|
88
98
|
if current_thread() is self.__dispatcher:
|
|
89
99
|
# A synchronous shutdown message cannot be consumed while this
|
|
@@ -98,23 +108,24 @@ class DefaultEventProcessor(EventProcessor):
|
|
|
98
108
|
self.__put_message_and_wait_terminate(MessageType.SHUTDOWN)
|
|
99
109
|
self.__dispatcher.join(_THREAD_JOIN_TIMEOUT_SECONDS)
|
|
100
110
|
if self.__dispatcher.is_alive():
|
|
101
|
-
log.warning(
|
|
111
|
+
log.warning("FB Python SDK: event dispatcher did not stop in time")
|
|
102
112
|
|
|
103
113
|
|
|
104
114
|
class EventDispatcher(Thread):
|
|
105
|
-
|
|
106
115
|
__MAX_FLUSH_WORKERS_NUMBER = 5
|
|
107
116
|
__BATCH_SIZE = 50
|
|
108
117
|
|
|
109
118
|
def __init__(self, config: Config, sender: Sender, inbox: "Queue[EventMessage]"):
|
|
110
|
-
super().__init__(name=
|
|
119
|
+
super().__init__(name="featbit-event-dispatcher", daemon=True)
|
|
111
120
|
self.__config = config
|
|
112
121
|
self.__inbox = inbox
|
|
113
122
|
self.__closed = False
|
|
114
123
|
self.__shutdown_requested = Event()
|
|
115
124
|
self.__sender = sender
|
|
116
125
|
self.__events_buffer_to_next_flush = []
|
|
117
|
-
self.__flush_workers = ThreadPoolExecutor(
|
|
126
|
+
self.__flush_workers = ThreadPoolExecutor(
|
|
127
|
+
max_workers=self.__MAX_FLUSH_WORKERS_NUMBER
|
|
128
|
+
)
|
|
118
129
|
self.__permits = BoundedSemaphore(value=self.__MAX_FLUSH_WORKERS_NUMBER)
|
|
119
130
|
self.__lock = Condition(Lock())
|
|
120
131
|
|
|
@@ -123,14 +134,18 @@ class EventDispatcher(Thread):
|
|
|
123
134
|
# 2: try to flush events to featureflag if a flush message arrives
|
|
124
135
|
# 3: wait for releasing resources if a shutdown arrives
|
|
125
136
|
def run(self):
|
|
126
|
-
log.debug(
|
|
137
|
+
log.debug("event dispatcher is working...")
|
|
127
138
|
while True:
|
|
128
139
|
try:
|
|
129
140
|
msgs = self.__drain_inbox(size=self.__BATCH_SIZE)
|
|
130
141
|
for msg in msgs:
|
|
131
142
|
shutdown = False
|
|
132
143
|
try:
|
|
133
|
-
if
|
|
144
|
+
if (
|
|
145
|
+
msg.type == MessageType.FLAGS
|
|
146
|
+
or msg.type == MessageType.METRICS
|
|
147
|
+
or msg.type == MessageType.USER
|
|
148
|
+
):
|
|
134
149
|
self.__put_events_to_buffer(msg.event) # type: ignore
|
|
135
150
|
elif msg.type == MessageType.FLUSH:
|
|
136
151
|
self.__trigger_flush()
|
|
@@ -138,7 +153,10 @@ class EventDispatcher(Thread):
|
|
|
138
153
|
self.__shutdown()
|
|
139
154
|
shutdown = True
|
|
140
155
|
except Exception as inner:
|
|
141
|
-
log.exception(
|
|
156
|
+
log.exception(
|
|
157
|
+
"FB Python SDK: unexpected error in event dispatcher: %s"
|
|
158
|
+
% str(inner)
|
|
159
|
+
)
|
|
142
160
|
finally:
|
|
143
161
|
# Synchronous callers must never wait forever because a
|
|
144
162
|
# dispatcher operation failed.
|
|
@@ -152,7 +170,10 @@ class EventDispatcher(Thread):
|
|
|
152
170
|
self.__shutdown()
|
|
153
171
|
return
|
|
154
172
|
except Exception as outer:
|
|
155
|
-
log.exception(
|
|
173
|
+
log.exception(
|
|
174
|
+
"FB Python SDK: unexpected error in event dispatcher: %s"
|
|
175
|
+
% str(outer)
|
|
176
|
+
)
|
|
156
177
|
|
|
157
178
|
def request_shutdown(self):
|
|
158
179
|
self.__shutdown_requested.set()
|
|
@@ -170,7 +191,7 @@ class EventDispatcher(Thread):
|
|
|
170
191
|
|
|
171
192
|
def __put_events_to_buffer(self, event: FBEvent):
|
|
172
193
|
if not self.__closed and event.is_send_event:
|
|
173
|
-
log.debug(
|
|
194
|
+
log.debug("put event to buffer")
|
|
174
195
|
self.__events_buffer_to_next_flush.append(event)
|
|
175
196
|
|
|
176
197
|
def __trigger_flush(self):
|
|
@@ -180,15 +201,15 @@ class EventDispatcher(Thread):
|
|
|
180
201
|
self.__lock.notify_all()
|
|
181
202
|
|
|
182
203
|
if not self.__closed and len(self.__events_buffer_to_next_flush) > 0:
|
|
183
|
-
log.debug(
|
|
204
|
+
log.debug("trigger flush")
|
|
184
205
|
# get all the current events from event buffer
|
|
185
206
|
if self.__permits.acquire(blocking=False):
|
|
186
207
|
payloads = []
|
|
187
208
|
payloads.extend(self.__events_buffer_to_next_flush)
|
|
188
209
|
# get an available flush worker to send events
|
|
189
|
-
self.__flush_workers
|
|
190
|
-
|
|
191
|
-
|
|
210
|
+
self.__flush_workers.submit(
|
|
211
|
+
FlushPayloadRunner(self.__config, self.__sender, payloads).run
|
|
212
|
+
).add_done_callback(flush_payload_done)
|
|
192
213
|
# clear the buffer for the next flush
|
|
193
214
|
self.__events_buffer_to_next_flush.clear()
|
|
194
215
|
# if no available flush worker, keep the events in the buffer
|
|
@@ -197,7 +218,7 @@ class EventDispatcher(Thread):
|
|
|
197
218
|
if not self.__closed:
|
|
198
219
|
try:
|
|
199
220
|
with self.__lock:
|
|
200
|
-
log.debug(
|
|
221
|
+
log.debug("event dispatcher is cleaning up thread and conn pool")
|
|
201
222
|
self.__wait_until_flush_playload_worker_down()
|
|
202
223
|
if self.__events_buffer_to_next_flush:
|
|
203
224
|
payloads = list(self.__events_buffer_to_next_flush)
|
|
@@ -208,18 +229,21 @@ class EventDispatcher(Thread):
|
|
|
208
229
|
FlushPayloadRunner(self.__config, self.__sender, payloads).run()
|
|
209
230
|
self.__closed = True
|
|
210
231
|
except Exception as e:
|
|
211
|
-
log.exception(
|
|
232
|
+
log.exception(
|
|
233
|
+
"FB Python SDK: unexpected error when closing event dispatcher: %s"
|
|
234
|
+
% str(e)
|
|
235
|
+
)
|
|
212
236
|
finally:
|
|
213
237
|
try:
|
|
214
238
|
self.__closed = True
|
|
215
|
-
log.debug(
|
|
239
|
+
log.debug("flush worker pool is stopping...")
|
|
216
240
|
self.__flush_workers.shutdown(wait=True)
|
|
217
241
|
except Exception:
|
|
218
|
-
log.exception(
|
|
242
|
+
log.exception("FB Python SDK: could not stop event flush workers")
|
|
219
243
|
try:
|
|
220
244
|
self.__sender.stop()
|
|
221
245
|
except Exception:
|
|
222
|
-
log.exception(
|
|
246
|
+
log.exception("FB Python SDK: could not stop event sender")
|
|
223
247
|
|
|
224
248
|
def __wait_until_flush_playload_worker_down(self):
|
|
225
249
|
while self.__permits._value != self.__MAX_FLUSH_WORKERS_NUMBER:
|
|
@@ -238,15 +262,22 @@ class FlushPayloadRunner:
|
|
|
238
262
|
def partition(lst: List, size: int):
|
|
239
263
|
for i in range(0, len(lst), size):
|
|
240
264
|
yield lst[i : i + size]
|
|
265
|
+
|
|
241
266
|
try:
|
|
242
|
-
for payload in list(
|
|
267
|
+
for payload in list(
|
|
268
|
+
partition(self.__payloads, self.__MAX_EVENT_SIZE_PER_REQUEST)
|
|
269
|
+
):
|
|
243
270
|
payload_part = [event.to_json_dict() for event in payload]
|
|
244
271
|
json_str = json.dumps(payload_part)
|
|
245
272
|
log.trace(json_str) # type: ignore
|
|
246
|
-
self.__sender.postJson(
|
|
247
|
-
|
|
273
|
+
self.__sender.postJson(
|
|
274
|
+
self.__config.events_uri, json_str, fetch_response=False
|
|
275
|
+
)
|
|
276
|
+
log.debug("paload size: %s" % len(payload_part))
|
|
248
277
|
except Exception as e:
|
|
249
|
-
log.exception(
|
|
278
|
+
log.exception(
|
|
279
|
+
"FB Python SDK: unexpected error in sending payload: %s" % str(e)
|
|
280
|
+
)
|
|
250
281
|
return False
|
|
251
282
|
return True
|
|
252
283
|
|
fbclient/event_types.py
CHANGED
|
@@ -3,7 +3,7 @@ from threading import Event
|
|
|
3
3
|
from time import time
|
|
4
4
|
from typing import Optional
|
|
5
5
|
|
|
6
|
-
from fbclient.common_types import
|
|
6
|
+
from fbclient.common_types import FBEvent, FBUser, _EvalResult
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
class MessageType(Enum):
|
|
@@ -16,7 +16,9 @@ class MessageType(Enum):
|
|
|
16
16
|
|
|
17
17
|
|
|
18
18
|
class EventMessage:
|
|
19
|
-
def __init__(
|
|
19
|
+
def __init__(
|
|
20
|
+
self, type: MessageType, event: Optional[FBEvent], await_termination: bool
|
|
21
|
+
):
|
|
20
22
|
self.__type = type
|
|
21
23
|
self.__event = event
|
|
22
24
|
self.__wait_lock = Event() if await_termination else None
|
|
@@ -56,9 +58,9 @@ class Metric:
|
|
|
56
58
|
def __init__(self, event_name: str, value: float):
|
|
57
59
|
self.__event_name = event_name
|
|
58
60
|
self.__value = value
|
|
59
|
-
self.__route =
|
|
60
|
-
self.__type =
|
|
61
|
-
self.__app_type =
|
|
61
|
+
self.__route = "index/metric"
|
|
62
|
+
self.__type = "CustomEvent"
|
|
63
|
+
self.__app_type = "pythonserverside"
|
|
62
64
|
self.__timestamp = int(round(time() * 1000))
|
|
63
65
|
|
|
64
66
|
@property
|
|
@@ -98,7 +100,7 @@ class UserEvent(FBEvent):
|
|
|
98
100
|
return self._user is not None
|
|
99
101
|
|
|
100
102
|
def to_json_dict(self) -> dict:
|
|
101
|
-
return {
|
|
103
|
+
return {"user": self._user.to_json_dict()}
|
|
102
104
|
|
|
103
105
|
|
|
104
106
|
class FlagEvent(FBEvent):
|
|
@@ -117,19 +119,20 @@ class FlagEvent(FBEvent):
|
|
|
117
119
|
return self._user and len(self.__variations) > 0
|
|
118
120
|
|
|
119
121
|
def to_json_dict(self) -> dict:
|
|
120
|
-
json_dict = {
|
|
122
|
+
json_dict = {"user": self._user.to_json_dict()}
|
|
121
123
|
arr = []
|
|
122
124
|
for variation in self.__variations:
|
|
123
|
-
flag_json_dict = {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
125
|
+
flag_json_dict = {
|
|
126
|
+
"featureFlagKey": variation.variation.key_name,
|
|
127
|
+
"timestamp": variation.timestamp,
|
|
128
|
+
"variation": {
|
|
129
|
+
"id": variation.variation.id,
|
|
130
|
+
"value": variation.variation.value,
|
|
131
|
+
"reason": variation.variation.reason,
|
|
132
|
+
},
|
|
133
|
+
}
|
|
131
134
|
arr.append(flag_json_dict)
|
|
132
|
-
json_dict[
|
|
135
|
+
json_dict["variations"] = arr # type: ignore
|
|
133
136
|
return json_dict
|
|
134
137
|
|
|
135
138
|
|
|
@@ -149,15 +152,17 @@ class MetricEvent(FBEvent):
|
|
|
149
152
|
return self._user and len(self.__metrics) > 0
|
|
150
153
|
|
|
151
154
|
def to_json_dict(self) -> dict:
|
|
152
|
-
json_dict = {
|
|
155
|
+
json_dict = {"user": self._user.to_json_dict()}
|
|
153
156
|
arr = []
|
|
154
157
|
for metric in self.__metrics:
|
|
155
|
-
metric_json_dict = {
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
158
|
+
metric_json_dict = {
|
|
159
|
+
"eventName": metric.event_name,
|
|
160
|
+
"numericValue": metric.value,
|
|
161
|
+
"route": metric.route,
|
|
162
|
+
"type": metric.type,
|
|
163
|
+
"appType": metric.app_type,
|
|
164
|
+
"timestamp": metric.timestamp,
|
|
165
|
+
}
|
|
161
166
|
arr.append(metric_json_dict)
|
|
162
|
-
json_dict[
|
|
167
|
+
json_dict["metrics"] = arr # type: ignore
|
|
163
168
|
return json_dict
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
|
|
2
1
|
from abc import ABC, abstractmethod
|
|
3
2
|
from typing import Any, Callable
|
|
3
|
+
|
|
4
4
|
from fbclient.common_types import FBUser
|
|
5
5
|
from fbclient.interfaces import Notice
|
|
6
6
|
from fbclient.notice_broadcaster import NoticeBroadcater
|
|
7
7
|
|
|
8
|
-
FLAG_CHANGE_NOTICE_TYPE =
|
|
8
|
+
FLAG_CHANGE_NOTICE_TYPE = "flag_change_notice"
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
class FlagChangedNotice(Notice):
|
|
@@ -28,23 +28,28 @@ class FlagChangedListener(ABC):
|
|
|
28
28
|
This is an abstract class. You need to implement your own listener by overriding the :func:`on_flag_change` method.
|
|
29
29
|
|
|
30
30
|
"""
|
|
31
|
+
|
|
31
32
|
@abstractmethod
|
|
32
33
|
def on_flag_change(self, notice: FlagChangedNotice):
|
|
33
34
|
pass
|
|
34
35
|
|
|
35
36
|
|
|
36
37
|
class FlagValueChangedListener(FlagChangedListener):
|
|
37
|
-
def __init__(
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
flag_key: str,
|
|
41
|
+
user: dict,
|
|
42
|
+
evaluate_fn: Callable[[str, dict, Any], Any],
|
|
43
|
+
flag_value_changed_fn: Callable[[str, Any, Any], None],
|
|
44
|
+
):
|
|
42
45
|
self.__flag_key = flag_key
|
|
43
46
|
self.__user = user
|
|
44
47
|
self.__evaluate_fn = evaluate_fn
|
|
45
48
|
self.__fn = flag_value_changed_fn
|
|
46
49
|
# record the flag value when the listener is created
|
|
47
|
-
self.__prvious_flag_value = self.__evaluate_fn(
|
|
50
|
+
self.__prvious_flag_value = self.__evaluate_fn(
|
|
51
|
+
self.__flag_key, self.__user, None
|
|
52
|
+
)
|
|
48
53
|
|
|
49
54
|
def on_flag_change(self, notice: FlagChangedNotice):
|
|
50
55
|
if notice.flag_key == self.__flag_key:
|
|
@@ -56,11 +61,13 @@ class FlagValueChangedListener(FlagChangedListener):
|
|
|
56
61
|
|
|
57
62
|
|
|
58
63
|
class FlagValueMaybeChangedListener(FlagChangedListener):
|
|
59
|
-
def __init__(
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
+
def __init__(
|
|
65
|
+
self,
|
|
66
|
+
flag_key: str,
|
|
67
|
+
user: dict,
|
|
68
|
+
evaluate_fn: Callable[[str, dict, Any], Any],
|
|
69
|
+
flag_value_maybe_changed_fn: Callable[[str, Any], None],
|
|
70
|
+
):
|
|
64
71
|
self.__flag_key = flag_key
|
|
65
72
|
self.__user = user
|
|
66
73
|
self.__evaluate_fn = evaluate_fn
|
|
@@ -82,9 +89,11 @@ class FlagTracker:
|
|
|
82
89
|
Application code never needs to initialize or extend this class directly.
|
|
83
90
|
"""
|
|
84
91
|
|
|
85
|
-
def __init__(
|
|
86
|
-
|
|
87
|
-
|
|
92
|
+
def __init__(
|
|
93
|
+
self,
|
|
94
|
+
flag_change_broadcaster: NoticeBroadcater,
|
|
95
|
+
evaluate_fn: Callable[[str, dict, Any], Any],
|
|
96
|
+
):
|
|
88
97
|
"""
|
|
89
98
|
:param flag_change_broadcaster: The broadcaster that broadcasts the flag change notices
|
|
90
99
|
:param evaluate_fn: The function to evaluate the flag value
|
|
@@ -92,10 +101,12 @@ class FlagTracker:
|
|
|
92
101
|
self.__broadcater = flag_change_broadcaster
|
|
93
102
|
self.__evaluate_fn = evaluate_fn
|
|
94
103
|
|
|
95
|
-
def add_flag_value_changed_listener(
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
104
|
+
def add_flag_value_changed_listener(
|
|
105
|
+
self,
|
|
106
|
+
flag_key: str,
|
|
107
|
+
user: dict,
|
|
108
|
+
flag_value_changed_fn: Callable[[str, Any, Any], None],
|
|
109
|
+
) -> FlagValueChangedListener:
|
|
99
110
|
"""
|
|
100
111
|
Registers a listener to be notified of a change in a specific feature flag's value for a specific FeatBit user.
|
|
101
112
|
|
|
@@ -118,21 +129,25 @@ class FlagTracker:
|
|
|
118
129
|
|
|
119
130
|
# check flag key
|
|
120
131
|
if not isinstance(flag_key, str) or not flag_key:
|
|
121
|
-
raise ValueError(
|
|
132
|
+
raise ValueError("flag_key must be a non-empty string")
|
|
122
133
|
# check user
|
|
123
134
|
FBUser.from_dict(user)
|
|
124
135
|
# check flag_value_changed_fn
|
|
125
136
|
if not isinstance(flag_value_changed_fn, Callable) or not flag_value_changed_fn:
|
|
126
|
-
raise ValueError(
|
|
137
|
+
raise ValueError("flag_value_changed_fn must be a callable function")
|
|
127
138
|
|
|
128
|
-
listener = FlagValueChangedListener(
|
|
139
|
+
listener = FlagValueChangedListener(
|
|
140
|
+
flag_key, user, self.__evaluate_fn, flag_value_changed_fn
|
|
141
|
+
)
|
|
129
142
|
self.add_flag_changed_listener(listener)
|
|
130
143
|
return listener
|
|
131
144
|
|
|
132
|
-
def add_flag_value_maybe_changed_listener(
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
145
|
+
def add_flag_value_maybe_changed_listener(
|
|
146
|
+
self,
|
|
147
|
+
flag_key: str,
|
|
148
|
+
user: dict,
|
|
149
|
+
flag_value_maybe_changed_fn: Callable[[str, Any], None],
|
|
150
|
+
) -> FlagValueMaybeChangedListener:
|
|
136
151
|
"""
|
|
137
152
|
Registers a listener to be notified of a change in a specific feature flag's value for a specific FeatBit user.
|
|
138
153
|
|
|
@@ -156,14 +171,19 @@ class FlagTracker:
|
|
|
156
171
|
|
|
157
172
|
# check flag key
|
|
158
173
|
if not isinstance(flag_key, str) or not flag_key:
|
|
159
|
-
raise ValueError(
|
|
174
|
+
raise ValueError("flag_key must be a non-empty string")
|
|
160
175
|
# check user
|
|
161
176
|
FBUser.from_dict(user)
|
|
162
177
|
# check flag_value_changed_fn
|
|
163
|
-
if
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
178
|
+
if (
|
|
179
|
+
not isinstance(flag_value_maybe_changed_fn, Callable)
|
|
180
|
+
or not flag_value_maybe_changed_fn
|
|
181
|
+
):
|
|
182
|
+
raise ValueError("flag_value_changed_fn must be a callable function")
|
|
183
|
+
|
|
184
|
+
listener = FlagValueMaybeChangedListener(
|
|
185
|
+
flag_key, user, self.__evaluate_fn, flag_value_maybe_changed_fn
|
|
186
|
+
)
|
|
167
187
|
self.add_flag_changed_listener(listener)
|
|
168
188
|
return listener
|
|
169
189
|
|
|
@@ -184,4 +204,6 @@ class FlagTracker:
|
|
|
184
204
|
|
|
185
205
|
:param listener: The listener to be unregistered. The listener must be the same object that was passed to :func:`add_flag_changed_listner` or :func:`add_flag_value_changed_listerner`
|
|
186
206
|
"""
|
|
187
|
-
self.__broadcater.remove_listener(
|
|
207
|
+
self.__broadcater.remove_listener(
|
|
208
|
+
FLAG_CHANGE_NOTICE_TYPE, listener.on_flag_change
|
|
209
|
+
) # type: ignore
|
fbclient/interfaces.py
CHANGED
|
@@ -7,24 +7,24 @@ from fbclient.status_types import State
|
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
class UpdateProcessor(ABC):
|
|
10
|
-
|
|
10
|
+
"""
|
|
11
11
|
Interface for the component that obtains feature flag data in some way and passes it to a
|
|
12
12
|
:class:`DataStorage`. The built-in imp now of this is streaming, we will provide the polling update
|
|
13
13
|
and file update soon
|
|
14
|
-
|
|
14
|
+
"""
|
|
15
15
|
|
|
16
16
|
@abstractmethod
|
|
17
17
|
def start(self):
|
|
18
|
-
|
|
18
|
+
"""
|
|
19
19
|
Starts an operation in the background.
|
|
20
|
-
|
|
20
|
+
"""
|
|
21
21
|
pass
|
|
22
22
|
|
|
23
23
|
@abstractmethod
|
|
24
24
|
def stop(self):
|
|
25
|
-
|
|
25
|
+
"""
|
|
26
26
|
Stops an operation running in the background.
|
|
27
|
-
|
|
27
|
+
"""
|
|
28
28
|
pass
|
|
29
29
|
|
|
30
30
|
@property
|
|
@@ -37,13 +37,15 @@ class UpdateProcessor(ABC):
|
|
|
37
37
|
|
|
38
38
|
|
|
39
39
|
class DataUpdateStatusProvider(ABC):
|
|
40
|
-
|
|
40
|
+
"""
|
|
41
41
|
Interface for manipulating the data updates in :class: `DataStorage` and maintain the status of :class: `UpdateProcessor`.
|
|
42
42
|
The implementation should be called in :class: `UpdateProcessor`.
|
|
43
|
-
|
|
43
|
+
"""
|
|
44
44
|
|
|
45
45
|
@abstractmethod
|
|
46
|
-
def init(
|
|
46
|
+
def init(
|
|
47
|
+
self, all_data: Mapping[Category, Mapping[str, dict]], version: int = 0
|
|
48
|
+
) -> bool:
|
|
47
49
|
"""
|
|
48
50
|
Manipulate the init operation in data storage. If the underlying data storage throws an error during this operation, the SDK will catch it, log it,
|
|
49
51
|
and set the state of update process to INTERRUPTED. It will not rethrow the error to other level, but will simply return falseto indicate that the operation failed.
|
|
@@ -179,7 +181,9 @@ class DataStorage(ABC):
|
|
|
179
181
|
pass
|
|
180
182
|
|
|
181
183
|
@abstractmethod
|
|
182
|
-
def init(
|
|
184
|
+
def init(
|
|
185
|
+
self, all_data: Mapping[Category, Mapping[str, dict]], version: int = 0
|
|
186
|
+
) -> bool:
|
|
183
187
|
"""
|
|
184
188
|
Init (or re-init by data update process) the storage with the specified set of data.
|
|
185
189
|
Any existing entries will be removed if the new data set's version is greater than the current version
|
|
@@ -266,7 +270,9 @@ class Sender(ABC):
|
|
|
266
270
|
"""
|
|
267
271
|
|
|
268
272
|
@abstractmethod
|
|
269
|
-
def postJson(
|
|
273
|
+
def postJson(
|
|
274
|
+
self, url: str, json_str: str, fetch_response: bool = True
|
|
275
|
+
) -> Optional[str]:
|
|
270
276
|
"""
|
|
271
277
|
Sends a json object via HTTP POST to the given URL
|
|
272
278
|
|
|
@@ -290,6 +296,7 @@ class Notice(ABC):
|
|
|
290
296
|
This is not an insight event to be sent to FeatBit Flag Center; it is a notice to notify the SDK that something has happened,
|
|
291
297
|
such as flag values updated
|
|
292
298
|
"""
|
|
299
|
+
|
|
293
300
|
@property
|
|
294
301
|
@abstractmethod
|
|
295
302
|
def notice_type(self) -> str:
|
fbclient/notice_broadcaster.py
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
|
|
2
1
|
from queue import Queue
|
|
3
2
|
from threading import Lock, Thread, current_thread
|
|
4
3
|
from typing import Callable
|
|
5
|
-
from fbclient.interfaces import Notice
|
|
6
4
|
|
|
5
|
+
from fbclient.interfaces import Notice
|
|
7
6
|
from fbclient.utils import log
|
|
8
7
|
|
|
9
8
|
|
|
@@ -14,15 +13,19 @@ class NoticeBroadcater:
|
|
|
14
13
|
self.__listeners = {}
|
|
15
14
|
self.__lock = Lock()
|
|
16
15
|
self.__stop_notice = object()
|
|
17
|
-
self.__thread = Thread(
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
log.debug(
|
|
16
|
+
self.__thread = Thread(
|
|
17
|
+
name="featbit-notice-broadcaster", daemon=True, target=self.__run
|
|
18
|
+
)
|
|
19
|
+
log.debug("notice broadcaster starting...")
|
|
21
20
|
self.__thread.start()
|
|
22
21
|
|
|
23
22
|
def add_listener(self, notice_type: str, listener: Callable[[Notice], None]):
|
|
24
|
-
if
|
|
25
|
-
|
|
23
|
+
if (
|
|
24
|
+
isinstance(notice_type, str)
|
|
25
|
+
and notice_type.strip()
|
|
26
|
+
and listener is not None
|
|
27
|
+
):
|
|
28
|
+
log.debug("add a listener for notice type %s" % notice_type)
|
|
26
29
|
with self.__lock:
|
|
27
30
|
if self.__closed:
|
|
28
31
|
return
|
|
@@ -36,7 +39,7 @@ class NoticeBroadcater:
|
|
|
36
39
|
def remove_listener(self, notice_type: str, listener: Callable[[Notice], None]):
|
|
37
40
|
if listener is None:
|
|
38
41
|
return
|
|
39
|
-
log.debug(
|
|
42
|
+
log.debug("remove a listener for notice type %s" % notice_type)
|
|
40
43
|
with self.__lock:
|
|
41
44
|
notifiers = self.__listeners.get(notice_type)
|
|
42
45
|
if not notifiers:
|
|
@@ -57,7 +60,7 @@ class NoticeBroadcater:
|
|
|
57
60
|
self.__notice_queue.put(notice)
|
|
58
61
|
|
|
59
62
|
def stop(self):
|
|
60
|
-
log.debug(
|
|
63
|
+
log.debug("notice broadcaster stopping...")
|
|
61
64
|
with self.__lock:
|
|
62
65
|
if self.__closed:
|
|
63
66
|
return
|
|
@@ -66,7 +69,7 @@ class NoticeBroadcater:
|
|
|
66
69
|
if current_thread() is not self.__thread:
|
|
67
70
|
self.__thread.join(5.0)
|
|
68
71
|
if self.__thread.is_alive():
|
|
69
|
-
log.warning(
|
|
72
|
+
log.warning("FB Python SDK: notice broadcaster did not stop in time")
|
|
70
73
|
|
|
71
74
|
def __run(self):
|
|
72
75
|
while True:
|
|
@@ -82,4 +85,7 @@ class NoticeBroadcater:
|
|
|
82
85
|
try:
|
|
83
86
|
listener(notice)
|
|
84
87
|
except Exception as e:
|
|
85
|
-
log.exception(
|
|
88
|
+
log.exception(
|
|
89
|
+
"FB Python SDK: unexpected error in handle notice %s: %s"
|
|
90
|
+
% (notice.notice_type, str(e))
|
|
91
|
+
)
|