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.
fbclient/evaluator.py CHANGED
@@ -5,87 +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'
68
-
69
- __EXPT_KEY_PREFIX__ = "expt"
66
+ __NOT_IN_SEGMENT_CLAUSE__ = "User is not in segment"
70
67
 
71
68
 
72
69
  class Evaluator:
73
- def __init__(self,
74
- flag_getter: Callable[[str], Optional[dict]],
75
- 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
+ ):
76
75
  self.__flag_getter = flag_getter
77
76
  self.__segment_getter = segment_getter
78
- self.__ops = [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
- 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:
84
87
  if not flag or not user:
85
- raise ValueError('null flag or empty user')
88
+ raise ValueError("null flag or empty user")
86
89
  return self._match_user_variation(flag, user, fb_event) # type: ignore
87
90
 
88
- 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]:
89
94
  er = None
90
95
  try:
91
96
  for op in self.__ops:
@@ -94,66 +99,80 @@ class Evaluator:
94
99
  return er
95
100
  finally:
96
101
  if er is not None:
97
- 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
+ )
98
106
  # Match the server default: only an explicit boolean false
99
- # disables insights; evaluation and experiment eligibility stay unchanged.
100
- if fb_event is not None and flag.get('insightsEnabled') is not False:
107
+ # disables insights; evaluation stays unchanged.
108
+ if fb_event is not None and flag.get("insightsEnabled") is not False:
101
109
  fb_event.add(FlagEventVariation(er))
102
110
 
103
111
  # return a value when flag is off
104
- def _match_feature_flag_disabled_user_variation(self, flag: dict, user: FBUser) -> Optional[_EvalResult]:
105
- if not flag['isEnabled']:
106
- return _EvalResult(flag['disabledVariationId'],
107
- flag['variationMap'][flag['disabledVariationId']],
108
- REASON_FLAG_OFF,
109
- False,
110
- flag['key'],
111
- flag['name'],
112
- 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
+ )
113
124
  return None
114
125
 
115
126
  # return the value of target user
116
- def _match_targeted_user_variation(self, flag: dict, user: FBUser) -> Optional[_EvalResult]:
117
- for target in flag['targetUsers']:
118
- if any(key_id == user.get('keyid') for key_id in target['keyIds']):
119
- return _EvalResult(target['variationId'],
120
- flag['variationMap'][target['variationId']],
121
- REASON_TARGET_MATCH,
122
- flag['exptIncludeAllTargets'],
123
- flag['key'],
124
- flag['name'],
125
- 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
+ )
126
140
  return None
127
141
 
128
142
  # return the value of matched rule
129
- def _match_condition_user_variation(self, flag: dict, user: FBUser) -> Optional[_EvalResult]:
130
- 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"]:
131
147
  if self._match_any_rule(user, rule):
132
- return self._get_rollout_variation_option(flag,
133
- rule,
134
- user,
135
- REASON_RULE_MATCH,
136
- flag['key'],
137
- flag['name'])
148
+ return self._get_rollout_variation_option(
149
+ flag, rule, user, REASON_RULE_MATCH, flag["key"], flag["name"]
150
+ )
138
151
  return None
139
152
 
140
153
  # get value from default rule
141
- def _match_default_user_variation(self, flag: dict, user: FBUser) -> Optional[_EvalResult]:
142
- return self._get_rollout_variation_option(flag,
143
- flag['fallthrough'],
144
- user,
145
- REASON_FALLTHROUGH,
146
- flag['key'],
147
- 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
+ )
148
165
 
149
166
  def _match_any_rule(self, user: FBUser, rule: dict) -> bool:
150
167
  # conditions cannot be empty
151
- 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
+ )
152
171
 
153
172
  def _process_condition(self, user: FBUser, condition: dict) -> bool:
154
- op = condition['op']
173
+ op = condition["op"]
155
174
  # segment hasn't any operation
156
- op = condition['property'] if not op else op
175
+ op = condition["property"] if not op else op
157
176
  if __THAN_CLAUSE__ in str(op):
158
177
  return self._than(user, condition)
159
178
  elif op == __EQ_CLAUSE__:
@@ -188,11 +207,11 @@ class Evaluator:
188
207
  return False
189
208
 
190
209
  def _than(self, user: FBUser, condition: dict) -> bool:
191
- pv = user.get(condition['property'])
192
- 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"]):
193
212
  return False
194
- pv_num, cv_num = round(float(pv), 5), round(float(condition['value']), 5) # type: ignore
195
- op = condition['op']
213
+ pv_num, cv_num = round(float(pv), 5), round(float(condition["value"]), 5) # type: ignore
214
+ op = condition["op"]
196
215
  if op == __GE_CLAUSE__:
197
216
  return pv_num >= cv_num
198
217
  elif op == __GT_CLAUSE__:
@@ -205,101 +224,92 @@ class Evaluator:
205
224
  return False
206
225
 
207
226
  def _equals(self, user: FBUser, condition: dict) -> bool:
208
- pv = user.get(condition['property'])
209
- cv = condition['value']
227
+ pv = user.get(condition["property"])
228
+ cv = condition["value"]
210
229
  return pv is not None and cv is not None and str(pv) == str(cv)
211
230
 
212
231
  def _contains(self, user: FBUser, condition: dict) -> bool:
213
- pv = user.get(condition['property'])
214
- cv = condition['value']
232
+ pv = user.get(condition["property"])
233
+ cv = condition["value"]
215
234
  return pv is not None and cv is not None and str(cv) in str(pv)
216
235
 
217
236
  def _one_of(self, user: FBUser, condition: dict) -> bool:
218
- pv = user.get(condition['property'])
237
+ pv = user.get(condition["property"])
219
238
  try:
220
- cv = json.loads(condition['value'])
239
+ cv = json.loads(condition["value"])
221
240
  return pv is not None and cv is not None and str(pv) in cv
222
241
  except:
223
242
  return False
224
243
 
225
244
  def _starts_with(self, user: FBUser, condition: dict) -> bool:
226
- pv = user.get(condition['property'])
227
- cv = condition['value']
245
+ pv = user.get(condition["property"])
246
+ cv = condition["value"]
228
247
  return pv is not None and cv is not None and str(pv).startswith(str(cv))
229
248
 
230
249
  def _ends_with(self, user: FBUser, condition: dict) -> bool:
231
- pv = user.get(condition['property'])
232
- cv = condition['value']
250
+ pv = user.get(condition["property"])
251
+ cv = condition["value"]
233
252
  return pv is not None and cv is not None and str(pv).endswith(str(cv))
234
253
 
235
254
  def _true(self, user: FBUser, condition: dict) -> bool:
236
- pv = user.get(condition['property'])
237
- 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"
238
257
 
239
258
  def _false(self, user: FBUser, condition: dict) -> bool:
240
- pv = user.get(condition['property'])
241
- 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"
242
261
 
243
262
  def _match_reg_exp(self, user: FBUser, clause: dict) -> bool:
244
- pv = user.get(clause['property'])
245
- cv = clause['value']
246
- 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
+ )
247
270
 
248
271
  def _in_segment(self, user: FBUser, condition: dict) -> bool:
249
272
  def match_segment(user: FBUser, segment: Optional[dict]) -> bool:
250
273
  if not user or not segment:
251
274
  return False
252
- user_key = user.get('keyid')
253
- if user_key in segment['excluded']:
275
+ user_key = user.get("keyid")
276
+ if user_key in segment["excluded"]:
254
277
  return False
255
- if user_key in segment['included']:
278
+ if user_key in segment["included"]:
256
279
  return True
257
- 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
+
258
282
  try:
259
- cv = json.loads(condition['value'])
260
- 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
+ )
261
287
  except:
262
288
  return False
263
289
 
264
- def _get_rollout_variation_option(self,
265
- flag: dict,
266
- rollout_variations: dict,
267
- user: FBUser,
268
- reason: str,
269
- key_name: str,
270
- name: str) -> Optional[_EvalResult]:
271
-
272
- def is_send_to_expt(dispatch_key: str,
273
- rollout: dict,
274
- expt_include_all_targets: bool,
275
- rule_inclued_in_expt: bool) -> bool:
276
- if expt_include_all_targets:
277
- return True
278
- if rule_inclued_in_expt:
279
- send_to_expt_percentage = rollout['exptRollout']
280
- splitting_percentage = rollout['rollout'][1] - rollout['rollout'][0]
281
-
282
- if send_to_expt_percentage == 0 or splitting_percentage == 0:
283
- return False
284
-
285
- upper_bound = send_to_expt_percentage / splitting_percentage
286
- if upper_bound > 1:
287
- upper_bound = 1
288
- new_dispatch_key = "".join((__EXPT_KEY_PREFIX__, dispatch_key))
289
- return VariationSplittingAlgorithm(new_dispatch_key, [0, upper_bound]).is_key_belongs_to_percentage()
290
- return False
291
-
292
- dispatch_key = rollout_variations.get('dispatchKey')
293
- dispatch_key = dispatch_key if dispatch_key else 'keyid'
294
- dispatch_key_value = "".join((flag['key'], user.get(dispatch_key, ""))) # type: ignore
295
- for rollout in rollout_variations['variations']:
296
- if VariationSplittingAlgorithm(dispatch_key_value, rollout['rollout']).is_key_belongs_to_percentage(): # type: ignore
297
- send_to_expt = is_send_to_expt(dispatch_key_value, rollout, flag['exptIncludeAllTargets'], rollout_variations['includedInExpt']) # type: ignore
298
- return _EvalResult(rollout['id'],
299
- flag['variationMap'][rollout['id']],
300
- reason,
301
- send_to_expt,
302
- key_name,
303
- name,
304
- 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
+ )
305
315
  return None