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.
fbclient/evaluator.py CHANGED
@@ -5,85 +5,92 @@ from typing import Callable, Optional
5
5
  from fbclient.common_types import FBEvent, FBUser, _EvalResult
6
6
  from fbclient.event_types import FlagEventVariation
7
7
  from fbclient.utils import is_numeric, log
8
- from fbclient.utils.variation_splitting_algorithm import \
9
- VariationSplittingAlgorithm
8
+ from fbclient.utils.variation_splitting_algorithm import VariationSplittingAlgorithm
10
9
 
11
- REASON_CLIENT_NOT_READY = 'client not ready'
10
+ REASON_CLIENT_NOT_READY = "client not ready"
12
11
 
13
- REASON_FLAG_NOT_FOUND = 'flag not found'
12
+ REASON_FLAG_NOT_FOUND = "flag not found"
14
13
 
15
- REASON_ERROR = 'error in evaluation'
14
+ REASON_ERROR = "error in evaluation"
16
15
 
17
- REASON_USER_NOT_SPECIFIED = 'user not specified'
16
+ REASON_USER_NOT_SPECIFIED = "user not specified"
18
17
 
19
- REASON_WRONG_TYPE = 'wrong type'
18
+ REASON_WRONG_TYPE = "wrong type"
20
19
 
21
- REASON_FLAG_OFF = 'flag off'
20
+ REASON_FLAG_OFF = "flag off"
22
21
 
23
- REASON_PREREQUISITE_FAILED = 'prerequisite failed'
22
+ REASON_PREREQUISITE_FAILED = "prerequisite failed"
24
23
 
25
- REASON_TARGET_MATCH = 'target match'
24
+ REASON_TARGET_MATCH = "target match"
26
25
 
27
- REASON_RULE_MATCH = 'rule match'
26
+ REASON_RULE_MATCH = "rule match"
28
27
 
29
- REASON_FALLTHROUGH = 'fall through all rules'
28
+ REASON_FALLTHROUGH = "fall through all rules"
30
29
 
31
- __THAN_CLAUSE__ = 'Than'
30
+ __THAN_CLAUSE__ = "Than"
32
31
 
33
- __GE_CLAUSE__ = 'BiggerEqualThan'
32
+ __GE_CLAUSE__ = "BiggerEqualThan"
34
33
 
35
- __GT_CLAUSE__ = 'BiggerThan'
34
+ __GT_CLAUSE__ = "BiggerThan"
36
35
 
37
- __LE_CLAUSE__ = 'LessEqualThan'
36
+ __LE_CLAUSE__ = "LessEqualThan"
38
37
 
39
- __LT_CLAUSE__ = 'LessThan'
38
+ __LT_CLAUSE__ = "LessThan"
40
39
 
41
- __EQ_CLAUSE__ = 'Equal'
40
+ __EQ_CLAUSE__ = "Equal"
42
41
 
43
- __NEQ_CLAUSE__ = 'NotEqual'
42
+ __NEQ_CLAUSE__ = "NotEqual"
44
43
 
45
- __CONTAINS_CLAUSE__ = 'Contains'
44
+ __CONTAINS_CLAUSE__ = "Contains"
46
45
 
47
- __NOT_CONTAIN_CLAUSE__ = 'NotContain'
46
+ __NOT_CONTAIN_CLAUSE__ = "NotContain"
48
47
 
49
- __IS_ONE_OF_CLAUSE__ = 'IsOneOf'
48
+ __IS_ONE_OF_CLAUSE__ = "IsOneOf"
50
49
 
51
- __NOT_ONE_OF_CLAUSE__ = 'NotOneOf'
50
+ __NOT_ONE_OF_CLAUSE__ = "NotOneOf"
52
51
 
53
- __STARTS_WITH_CLAUSE__ = 'StartsWith'
52
+ __STARTS_WITH_CLAUSE__ = "StartsWith"
54
53
 
55
- __ENDS_WITH_CLAUSE__ = 'EndsWith'
54
+ __ENDS_WITH_CLAUSE__ = "EndsWith"
56
55
 
57
- __IS_TRUE_CLAUSE__ = 'IsTrue'
56
+ __IS_TRUE_CLAUSE__ = "IsTrue"
58
57
 
59
- __IS_FALSE_CLAUSE__ = 'IsFalse'
58
+ __IS_FALSE_CLAUSE__ = "IsFalse"
60
59
 
61
- __MATCH_REGEX_CLAUSE__ = 'MatchRegex'
60
+ __MATCH_REGEX_CLAUSE__ = "MatchRegex"
62
61
 
63
- __NOT_MATCH_REGEX_CLAUSE__ = 'NotMatchRegex'
62
+ __NOT_MATCH_REGEX_CLAUSE__ = "NotMatchRegex"
64
63
 
65
- __IS_IN_SEGMENT_CLAUSE__ = 'User is in segment'
64
+ __IS_IN_SEGMENT_CLAUSE__ = "User is in segment"
66
65
 
67
- __NOT_IN_SEGMENT_CLAUSE__ = 'User is not in segment'
66
+ __NOT_IN_SEGMENT_CLAUSE__ = "User is not in segment"
68
67
 
69
68
 
70
69
  class Evaluator:
71
- def __init__(self,
72
- flag_getter: Callable[[str], Optional[dict]],
73
- segment_getter: Callable[[str], Optional[dict]]):
70
+ def __init__(
71
+ self,
72
+ flag_getter: Callable[[str], Optional[dict]],
73
+ segment_getter: Callable[[str], Optional[dict]],
74
+ ):
74
75
  self.__flag_getter = flag_getter
75
76
  self.__segment_getter = segment_getter
76
- self.__ops = [self._match_feature_flag_disabled_user_variation,
77
- self._match_targeted_user_variation,
78
- self._match_condition_user_variation,
79
- self._match_default_user_variation]
80
-
81
- def evaluate(self, flag: dict, user: FBUser, fb_event: Optional[FBEvent] = None) -> _EvalResult:
77
+ self.__ops = [
78
+ self._match_feature_flag_disabled_user_variation,
79
+ self._match_targeted_user_variation,
80
+ self._match_condition_user_variation,
81
+ self._match_default_user_variation,
82
+ ]
83
+
84
+ def evaluate(
85
+ self, flag: dict, user: FBUser, fb_event: Optional[FBEvent] = None
86
+ ) -> _EvalResult:
82
87
  if not flag or not user:
83
- raise ValueError('null flag or empty user')
88
+ raise ValueError("null flag or empty user")
84
89
  return self._match_user_variation(flag, user, fb_event) # type: ignore
85
90
 
86
- def _match_user_variation(self, flag: dict, user: FBUser, fb_event: Optional[FBEvent] = None) -> Optional[_EvalResult]:
91
+ def _match_user_variation(
92
+ self, flag: dict, user: FBUser, fb_event: Optional[FBEvent] = None
93
+ ) -> Optional[_EvalResult]:
87
94
  er = None
88
95
  try:
89
96
  for op in self.__ops:
@@ -92,64 +99,80 @@ class Evaluator:
92
99
  return er
93
100
  finally:
94
101
  if er is not None:
95
- log.info('FB Python SDK: User %s, Feature Flag %s, Flag Value %s' % (user.get('KeyId'), er.key_name, er.value))
102
+ log.info(
103
+ "FB Python SDK: User %s, Feature Flag %s, Flag Value %s"
104
+ % (user.get("KeyId"), er.key_name, er.value)
105
+ )
96
106
  # Match the server default: only an explicit boolean false
97
107
  # disables insights; evaluation stays unchanged.
98
- if fb_event is not None and flag.get('insightsEnabled') is not False:
108
+ if fb_event is not None and flag.get("insightsEnabled") is not False:
99
109
  fb_event.add(FlagEventVariation(er))
100
110
 
101
111
  # return a value when flag is off
102
- def _match_feature_flag_disabled_user_variation(self, flag: dict, user: FBUser) -> Optional[_EvalResult]:
103
- if not flag['isEnabled']:
104
- return _EvalResult(flag['disabledVariationId'],
105
- flag['variationMap'][flag['disabledVariationId']],
106
- REASON_FLAG_OFF,
107
- flag['key'],
108
- flag['name'],
109
- flag['variationType'])
112
+ def _match_feature_flag_disabled_user_variation(
113
+ self, flag: dict, user: FBUser
114
+ ) -> Optional[_EvalResult]:
115
+ if not flag["isEnabled"]:
116
+ return _EvalResult(
117
+ flag["disabledVariationId"],
118
+ flag["variationMap"][flag["disabledVariationId"]],
119
+ REASON_FLAG_OFF,
120
+ flag["key"],
121
+ flag["name"],
122
+ flag["variationType"],
123
+ )
110
124
  return None
111
125
 
112
126
  # return the value of target user
113
- def _match_targeted_user_variation(self, flag: dict, user: FBUser) -> Optional[_EvalResult]:
114
- for target in flag['targetUsers']:
115
- if any(key_id == user.get('keyid') for key_id in target['keyIds']):
116
- return _EvalResult(target['variationId'],
117
- flag['variationMap'][target['variationId']],
118
- REASON_TARGET_MATCH,
119
- flag['key'],
120
- flag['name'],
121
- flag['variationType'])
127
+ def _match_targeted_user_variation(
128
+ self, flag: dict, user: FBUser
129
+ ) -> Optional[_EvalResult]:
130
+ for target in flag["targetUsers"]:
131
+ if any(key_id == user.get("keyid") for key_id in target["keyIds"]):
132
+ return _EvalResult(
133
+ target["variationId"],
134
+ flag["variationMap"][target["variationId"]],
135
+ REASON_TARGET_MATCH,
136
+ flag["key"],
137
+ flag["name"],
138
+ flag["variationType"],
139
+ )
122
140
  return None
123
141
 
124
142
  # return the value of matched rule
125
- def _match_condition_user_variation(self, flag: dict, user: FBUser) -> Optional[_EvalResult]:
126
- for rule in flag['rules']:
143
+ def _match_condition_user_variation(
144
+ self, flag: dict, user: FBUser
145
+ ) -> Optional[_EvalResult]:
146
+ for rule in flag["rules"]:
127
147
  if self._match_any_rule(user, rule):
128
- return self._get_rollout_variation_option(flag,
129
- rule,
130
- user,
131
- REASON_RULE_MATCH,
132
- flag['key'],
133
- flag['name'])
148
+ return self._get_rollout_variation_option(
149
+ flag, rule, user, REASON_RULE_MATCH, flag["key"], flag["name"]
150
+ )
134
151
  return None
135
152
 
136
153
  # get value from default rule
137
- def _match_default_user_variation(self, flag: dict, user: FBUser) -> Optional[_EvalResult]:
138
- return self._get_rollout_variation_option(flag,
139
- flag['fallthrough'],
140
- user,
141
- REASON_FALLTHROUGH,
142
- flag['key'],
143
- flag['name'])
154
+ def _match_default_user_variation(
155
+ self, flag: dict, user: FBUser
156
+ ) -> Optional[_EvalResult]:
157
+ return self._get_rollout_variation_option(
158
+ flag,
159
+ flag["fallthrough"],
160
+ user,
161
+ REASON_FALLTHROUGH,
162
+ flag["key"],
163
+ flag["name"],
164
+ )
144
165
 
145
166
  def _match_any_rule(self, user: FBUser, rule: dict) -> bool:
146
167
  # conditions cannot be empty
147
- return all(self._process_condition(user, condition) for condition in rule['conditions'])
168
+ return all(
169
+ self._process_condition(user, condition) for condition in rule["conditions"]
170
+ )
148
171
 
149
172
  def _process_condition(self, user: FBUser, condition: dict) -> bool:
150
- op = condition['op']
173
+ op = condition["op"]
151
174
  # segment hasn't any operation
152
- op = condition['property'] if not op else op
175
+ op = condition["property"] if not op else op
153
176
  if __THAN_CLAUSE__ in str(op):
154
177
  return self._than(user, condition)
155
178
  elif op == __EQ_CLAUSE__:
@@ -184,11 +207,11 @@ class Evaluator:
184
207
  return False
185
208
 
186
209
  def _than(self, user: FBUser, condition: dict) -> bool:
187
- pv = user.get(condition['property'])
188
- if not is_numeric(pv) or not is_numeric(condition['value']):
210
+ pv = user.get(condition["property"])
211
+ if not is_numeric(pv) or not is_numeric(condition["value"]):
189
212
  return False
190
- pv_num, cv_num = round(float(pv), 5), round(float(condition['value']), 5) # type: ignore
191
- op = condition['op']
213
+ pv_num, cv_num = round(float(pv), 5), round(float(condition["value"]), 5) # type: ignore
214
+ op = condition["op"]
192
215
  if op == __GE_CLAUSE__:
193
216
  return pv_num >= cv_num
194
217
  elif op == __GT_CLAUSE__:
@@ -201,79 +224,92 @@ class Evaluator:
201
224
  return False
202
225
 
203
226
  def _equals(self, user: FBUser, condition: dict) -> bool:
204
- pv = user.get(condition['property'])
205
- cv = condition['value']
227
+ pv = user.get(condition["property"])
228
+ cv = condition["value"]
206
229
  return pv is not None and cv is not None and str(pv) == str(cv)
207
230
 
208
231
  def _contains(self, user: FBUser, condition: dict) -> bool:
209
- pv = user.get(condition['property'])
210
- cv = condition['value']
232
+ pv = user.get(condition["property"])
233
+ cv = condition["value"]
211
234
  return pv is not None and cv is not None and str(cv) in str(pv)
212
235
 
213
236
  def _one_of(self, user: FBUser, condition: dict) -> bool:
214
- pv = user.get(condition['property'])
237
+ pv = user.get(condition["property"])
215
238
  try:
216
- cv = json.loads(condition['value'])
239
+ cv = json.loads(condition["value"])
217
240
  return pv is not None and cv is not None and str(pv) in cv
218
241
  except:
219
242
  return False
220
243
 
221
244
  def _starts_with(self, user: FBUser, condition: dict) -> bool:
222
- pv = user.get(condition['property'])
223
- cv = condition['value']
245
+ pv = user.get(condition["property"])
246
+ cv = condition["value"]
224
247
  return pv is not None and cv is not None and str(pv).startswith(str(cv))
225
248
 
226
249
  def _ends_with(self, user: FBUser, condition: dict) -> bool:
227
- pv = user.get(condition['property'])
228
- cv = condition['value']
250
+ pv = user.get(condition["property"])
251
+ cv = condition["value"]
229
252
  return pv is not None and cv is not None and str(pv).endswith(str(cv))
230
253
 
231
254
  def _true(self, user: FBUser, condition: dict) -> bool:
232
- pv = user.get(condition['property'])
233
- return pv is not None and str(pv).lower() == 'true'
255
+ pv = user.get(condition["property"])
256
+ return pv is not None and str(pv).lower() == "true"
234
257
 
235
258
  def _false(self, user: FBUser, condition: dict) -> bool:
236
- pv = user.get(condition['property'])
237
- return pv is not None and str(pv).lower() == 'false'
259
+ pv = user.get(condition["property"])
260
+ return pv is not None and str(pv).lower() == "false"
238
261
 
239
262
  def _match_reg_exp(self, user: FBUser, clause: dict) -> bool:
240
- pv = user.get(clause['property'])
241
- cv = clause['value']
242
- return pv is not None and cv is not None and re.search(str(cv), str(pv)) is not None
263
+ pv = user.get(clause["property"])
264
+ cv = clause["value"]
265
+ return (
266
+ pv is not None
267
+ and cv is not None
268
+ and re.search(str(cv), str(pv)) is not None
269
+ )
243
270
 
244
271
  def _in_segment(self, user: FBUser, condition: dict) -> bool:
245
272
  def match_segment(user: FBUser, segment: Optional[dict]) -> bool:
246
273
  if not user or not segment:
247
274
  return False
248
- user_key = user.get('keyid')
249
- if user_key in segment['excluded']:
275
+ user_key = user.get("keyid")
276
+ if user_key in segment["excluded"]:
250
277
  return False
251
- if user_key in segment['included']:
278
+ if user_key in segment["included"]:
252
279
  return True
253
- return any(self._match_any_rule(user, rule) for rule in segment['rules'])
280
+ return any(self._match_any_rule(user, rule) for rule in segment["rules"])
281
+
254
282
  try:
255
- cv = json.loads(condition['value'])
256
- return cv and any(match_segment(user, self.__segment_getter(sgid)) for sgid in cv)
283
+ cv = json.loads(condition["value"])
284
+ return cv and any(
285
+ match_segment(user, self.__segment_getter(sgid)) for sgid in cv
286
+ )
257
287
  except:
258
288
  return False
259
289
 
260
- def _get_rollout_variation_option(self,
261
- flag: dict,
262
- rollout_variations: dict,
263
- user: FBUser,
264
- reason: str,
265
- key_name: str,
266
- name: str) -> Optional[_EvalResult]:
267
-
268
- dispatch_key = rollout_variations.get('dispatchKey')
269
- dispatch_key = dispatch_key if dispatch_key else 'keyid'
270
- dispatch_key_value = "".join((flag['key'], user.get(dispatch_key, ""))) # type: ignore
271
- for rollout in rollout_variations['variations']:
272
- if VariationSplittingAlgorithm(dispatch_key_value, rollout['rollout']).is_key_belongs_to_percentage(): # type: ignore
273
- return _EvalResult(rollout['id'],
274
- flag['variationMap'][rollout['id']],
275
- reason,
276
- key_name,
277
- name,
278
- flag['variationType'])
290
+ def _get_rollout_variation_option(
291
+ self,
292
+ flag: dict,
293
+ rollout_variations: dict,
294
+ user: FBUser,
295
+ reason: str,
296
+ key_name: str,
297
+ name: str,
298
+ ) -> Optional[_EvalResult]:
299
+
300
+ dispatch_key = rollout_variations.get("dispatchKey")
301
+ dispatch_key = dispatch_key if dispatch_key else "keyid"
302
+ dispatch_key_value = "".join((flag["key"], user.get(dispatch_key, ""))) # type: ignore
303
+ for rollout in rollout_variations["variations"]:
304
+ if VariationSplittingAlgorithm(
305
+ dispatch_key_value, rollout["rollout"]
306
+ ).is_key_belongs_to_percentage(): # type: ignore
307
+ return _EvalResult(
308
+ rollout["id"],
309
+ flag["variationMap"][rollout["id"]],
310
+ reason,
311
+ key_name,
312
+ name,
313
+ flag["variationType"],
314
+ )
279
315
  return None
@@ -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 (EventMessage, FlagEvent, MessageType,
10
- MetricEvent, UserEvent)
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('featbit-insight-flush', config.events_flush_interval, self.flush)
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('insight processor is ready')
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('FB Python SDK: Events are being produced faster than they can be processed; some events will be dropped')
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('put %s message to inbox' % str(type)) # type: ignore
62
+ log.trace("put %s message to inbox" % str(type)) # type: ignore
55
63
 
56
- def __put_message_and_wait_terminate(self, type: MessageType, event: Optional[FBEvent] = None):
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('put %s WaitTermination message to inbox' % str(type))
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('ignore unknown event type')
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('FB Python SDK: event processor is stopping')
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('FB Python SDK: event dispatcher did not stop in time')
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='featbit-event-dispatcher', daemon=True)
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(max_workers=self.__MAX_FLUSH_WORKERS_NUMBER)
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('event dispatcher is working...')
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 msg.type == MessageType.FLAGS or msg.type == MessageType.METRICS or msg.type == MessageType.USER:
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('FB Python SDK: unexpected error in event dispatcher: %s' % str(inner))
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('FB Python SDK: unexpected error in event dispatcher: %s' % str(outer))
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('put event to buffer')
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('trigger flush')
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
- .submit(FlushPayloadRunner(self.__config, self.__sender, payloads).run) \
191
- .add_done_callback(flush_payload_done)
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('event dispatcher is cleaning up thread and conn pool')
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('FB Python SDK: unexpected error when closing event dispatcher: %s' % str(e))
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('flush worker pool is stopping...')
239
+ log.debug("flush worker pool is stopping...")
216
240
  self.__flush_workers.shutdown(wait=True)
217
241
  except Exception:
218
- log.exception('FB Python SDK: could not stop event flush workers')
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('FB Python SDK: could not stop event sender')
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(partition(self.__payloads, self.__MAX_EVENT_SIZE_PER_REQUEST)):
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(self.__config.events_uri, json_str, fetch_response=False)
247
- log.debug('paload size: %s' % len(payload_part))
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('FB Python SDK: unexpected error in sending payload: %s' % str(e))
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