fb-python-sdk 1.1.10__tar.gz → 1.2.1__tar.gz

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.
Files changed (46) hide show
  1. {fb_python_sdk-1.1.10/fb_python_sdk.egg-info → fb_python_sdk-1.2.1}/PKG-INFO +1 -1
  2. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1/fb_python_sdk.egg-info}/PKG-INFO +1 -1
  3. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fb_python_sdk.egg-info/SOURCES.txt +1 -0
  4. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/client.py +4 -2
  5. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/common_types.py +3 -9
  6. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/evaluator.py +3 -27
  7. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/event_types.py +0 -1
  8. fb_python_sdk-1.2.1/release/package.json +3 -0
  9. fb_python_sdk-1.2.1/tests/test_insights_enabled.py +168 -0
  10. fb_python_sdk-1.1.10/release/package.json +0 -3
  11. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/LICENSE +0 -0
  12. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/MANIFEST.in +0 -0
  13. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/README.md +0 -0
  14. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/dev-requirements.txt +0 -0
  15. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fb_python_sdk.egg-info/dependency_links.txt +0 -0
  16. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fb_python_sdk.egg-info/requires.txt +0 -0
  17. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fb_python_sdk.egg-info/top_level.txt +0 -0
  18. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/__init__.py +0 -0
  19. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/category.py +0 -0
  20. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/config.py +0 -0
  21. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/data_storage.py +0 -0
  22. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/event_processor.py +0 -0
  23. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/flag_change_notification.py +0 -0
  24. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/interfaces.py +0 -0
  25. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/notice_broadcaster.py +0 -0
  26. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/status.py +0 -0
  27. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/status_types.py +0 -0
  28. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/streaming.py +0 -0
  29. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/update_processor.py +0 -0
  30. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/utils/__init__.py +0 -0
  31. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/utils/exponential_backoff_jitter_strategy.py +0 -0
  32. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/utils/http_client.py +0 -0
  33. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/utils/repeatable_task.py +0 -0
  34. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/utils/rwlock.py +0 -0
  35. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/fbclient/utils/variation_splitting_algorithm.py +0 -0
  36. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/pyproject.toml +0 -0
  37. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/requirements.txt +0 -0
  38. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/setup.cfg +0 -0
  39. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/setup.py +0 -0
  40. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/tests/test_data_storage.py +0 -0
  41. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/tests/test_data_update_status_provider.py +0 -0
  42. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/tests/test_evaluator.py +0 -0
  43. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/tests/test_event_processor.py +0 -0
  44. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/tests/test_fbclient.py +0 -0
  45. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/tests/test_flag_change_notification.py +0 -0
  46. {fb_python_sdk-1.1.10 → fb_python_sdk-1.2.1}/tests/test_runtime_safety.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fb-python-sdk
3
- Version: 1.1.10
3
+ Version: 1.2.1
4
4
  Summary: A Python SDK for FeatBit plateform
5
5
  Home-page: https://github.com/featbit/featbit-python-sdk
6
6
  Author: Dian SUN
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fb-python-sdk
3
- Version: 1.1.10
3
+ Version: 1.2.1
4
4
  Summary: A Python SDK for FeatBit plateform
5
5
  Home-page: https://github.com/featbit/featbit-python-sdk
6
6
  Author: Dian SUN
@@ -39,4 +39,5 @@ tests/test_evaluator.py
39
39
  tests/test_event_processor.py
40
40
  tests/test_fbclient.py
41
41
  tests/test_flag_change_notification.py
42
+ tests/test_insights_enabled.py
42
43
  tests/test_runtime_safety.py
@@ -133,6 +133,8 @@ class FBClient:
133
133
 
134
134
  def _send_event_safely(self, event):
135
135
  try:
136
+ if isinstance(event, FlagEvent) and not event.is_send_event:
137
+ return
136
138
  if not self._closed:
137
139
  self._event_processor.send_event(event)
138
140
  except Exception:
@@ -273,7 +275,7 @@ class FBClient:
273
275
  def variation(self, key: str, user: dict, default: Any = None) -> Any:
274
276
  """Return the variation of a feature flag for a given user.
275
277
 
276
- This method will send an event back to feature flag center immediately if no error occurs.
278
+ This method collects an evaluation event if evaluation succeeds and insights are enabled for the flag.
277
279
 
278
280
  The default value should be a string, boolean, numeric, or json type.
279
281
 
@@ -297,7 +299,7 @@ class FBClient:
297
299
  """"Return the variation of a feature flag for a given user, but also provides additional information
298
300
  about how this value was calculated, in the property `data` of the :class:`fbclient.common_types.EvalDetail`.
299
301
 
300
- This method will send an event back to feature flag center immediately if no error occurs.
302
+ This method collects an evaluation event if evaluation succeeds and insights are enabled for the flag.
301
303
 
302
304
  The default value should be a string, boolean, numeric, or json type.
303
305
 
@@ -232,7 +232,7 @@ class AllFlagStates(BasicFlagState, Jsonfy):
232
232
  def get_variation(self, key_name: str, default: Any = None) -> Any:
233
233
  """Return the variation of a given feature flag key
234
234
 
235
- This method will send event to back to feature flag center immediately
235
+ This method submits the evaluation event only if insights were enabled when the flag was evaluated.
236
236
 
237
237
  The default value should be a string, boolean, numeric, or json type.
238
238
 
@@ -244,7 +244,7 @@ class AllFlagStates(BasicFlagState, Jsonfy):
244
244
  def get(self, key_name: str, default: Any = None) -> EvalDetail:
245
245
  """Return the flag evaluation details of a given feature flag key
246
246
 
247
- This method will send event to back to feature flag center immediately
247
+ This method submits the evaluation event only if insights were enabled when the flag was evaluated.
248
248
 
249
249
  The default value should be a string, boolean, numeric, or json type.
250
250
 
@@ -285,7 +285,6 @@ class _EvalResult:
285
285
  id: str,
286
286
  value: Optional[str],
287
287
  reason: str,
288
- is_send_to_expt: bool = False,
289
288
  key_name: Optional[str] = None,
290
289
  name: Optional[str] = None,
291
290
  flag_type: Optional[str] = 'string'):
@@ -293,14 +292,13 @@ class _EvalResult:
293
292
  self.__id = id
294
293
  self.__value = value
295
294
  self.__reason = reason
296
- self.__is_send_to_expt = is_send_to_expt
297
295
  self.__key_name = key_name
298
296
  self.__name = name
299
297
  self.__flag_type = flag_type
300
298
 
301
299
  @staticmethod
302
300
  def error(default_value: Optional[str], reason: str, key_name: Optional[str] = None, flag_type: Optional[str] = 'string'):
303
- return _EvalResult(__NO_VARIATION__, default_value, reason, False, key_name if key_name else __FLAG_KEY_UNKNOWN__, __FLAG_NAME_UNKNOWN__, flag_type)
301
+ return _EvalResult(__NO_VARIATION__, default_value, reason, key_name if key_name else __FLAG_KEY_UNKNOWN__, __FLAG_NAME_UNKNOWN__, flag_type)
304
302
 
305
303
  @property
306
304
  def id(self) -> str:
@@ -314,10 +312,6 @@ class _EvalResult:
314
312
  def reason(self) -> str:
315
313
  return self.__reason
316
314
 
317
- @property
318
- def is_send_to_expt(self) -> bool:
319
- return self.__is_send_to_expt
320
-
321
315
  @property
322
316
  def key_name(self) -> Optional[str]:
323
317
  return self.__key_name
@@ -66,8 +66,6 @@ __IS_IN_SEGMENT_CLAUSE__ = 'User is in segment'
66
66
 
67
67
  __NOT_IN_SEGMENT_CLAUSE__ = 'User is not in segment'
68
68
 
69
- __EXPT_KEY_PREFIX__ = "expt"
70
-
71
69
 
72
70
  class Evaluator:
73
71
  def __init__(self,
@@ -95,7 +93,9 @@ class Evaluator:
95
93
  finally:
96
94
  if er is not None:
97
95
  log.info('FB Python SDK: User %s, Feature Flag %s, Flag Value %s' % (user.get('KeyId'), er.key_name, er.value))
98
- if fb_event is not None:
96
+ # Match the server default: only an explicit boolean false
97
+ # disables insights; evaluation stays unchanged.
98
+ if fb_event is not None and flag.get('insightsEnabled') is not False:
99
99
  fb_event.add(FlagEventVariation(er))
100
100
 
101
101
  # return a value when flag is off
@@ -104,7 +104,6 @@ class Evaluator:
104
104
  return _EvalResult(flag['disabledVariationId'],
105
105
  flag['variationMap'][flag['disabledVariationId']],
106
106
  REASON_FLAG_OFF,
107
- False,
108
107
  flag['key'],
109
108
  flag['name'],
110
109
  flag['variationType'])
@@ -117,7 +116,6 @@ class Evaluator:
117
116
  return _EvalResult(target['variationId'],
118
117
  flag['variationMap'][target['variationId']],
119
118
  REASON_TARGET_MATCH,
120
- flag['exptIncludeAllTargets'],
121
119
  flag['key'],
122
120
  flag['name'],
123
121
  flag['variationType'])
@@ -267,36 +265,14 @@ class Evaluator:
267
265
  key_name: str,
268
266
  name: str) -> Optional[_EvalResult]:
269
267
 
270
- def is_send_to_expt(dispatch_key: str,
271
- rollout: dict,
272
- expt_include_all_targets: bool,
273
- rule_inclued_in_expt: bool) -> bool:
274
- if expt_include_all_targets:
275
- return True
276
- if rule_inclued_in_expt:
277
- send_to_expt_percentage = rollout['exptRollout']
278
- splitting_percentage = rollout['rollout'][1] - rollout['rollout'][0]
279
-
280
- if send_to_expt_percentage == 0 or splitting_percentage == 0:
281
- return False
282
-
283
- upper_bound = send_to_expt_percentage / splitting_percentage
284
- if upper_bound > 1:
285
- upper_bound = 1
286
- new_dispatch_key = "".join((__EXPT_KEY_PREFIX__, dispatch_key))
287
- return VariationSplittingAlgorithm(new_dispatch_key, [0, upper_bound]).is_key_belongs_to_percentage()
288
- return False
289
-
290
268
  dispatch_key = rollout_variations.get('dispatchKey')
291
269
  dispatch_key = dispatch_key if dispatch_key else 'keyid'
292
270
  dispatch_key_value = "".join((flag['key'], user.get(dispatch_key, ""))) # type: ignore
293
271
  for rollout in rollout_variations['variations']:
294
272
  if VariationSplittingAlgorithm(dispatch_key_value, rollout['rollout']).is_key_belongs_to_percentage(): # type: ignore
295
- send_to_expt = is_send_to_expt(dispatch_key_value, rollout, flag['exptIncludeAllTargets'], rollout_variations['includedInExpt']) # type: ignore
296
273
  return _EvalResult(rollout['id'],
297
274
  flag['variationMap'][rollout['id']],
298
275
  reason,
299
- send_to_expt,
300
276
  key_name,
301
277
  name,
302
278
  flag['variationType'])
@@ -121,7 +121,6 @@ class FlagEvent(FBEvent):
121
121
  arr = []
122
122
  for variation in self.__variations:
123
123
  flag_json_dict = {'featureFlagKey': variation.variation.key_name,
124
- 'sendToExperiment': variation.variation.is_send_to_expt,
125
124
  'timestamp': variation.timestamp,
126
125
  'variation': {
127
126
  'id': variation.variation.id,
@@ -0,0 +1,3 @@
1
+ {
2
+ "version":"1.2.1"
3
+ }
@@ -0,0 +1,168 @@
1
+ import base64
2
+ import json
3
+ from pathlib import Path
4
+ from threading import Event
5
+ from unittest.mock import Mock
6
+
7
+ import pytest
8
+
9
+ from fbclient.client import FBClient
10
+ from fbclient.common_types import FBUser
11
+ from fbclient.config import Config
12
+ from fbclient.event_processor import DefaultEventProcessor, NullEventProcessor
13
+ from fbclient.event_types import FlagEvent, MetricEvent, UserEvent
14
+ from fbclient.streaming import Streaming
15
+ from fbclient.update_processor import NullUpdateProcessor
16
+
17
+
18
+ MISSING = object()
19
+ USER = {'key': 'test-user-1', 'name': 'Test User', 'country': 'us'}
20
+ FLAG_KEY = 'ff-test-bool'
21
+ SETTINGS = [MISSING, True, False, None, 0, 'false']
22
+
23
+
24
+ def payload(setting, event_type='full', revision=1):
25
+ message = json.loads(Path('tests/fbclient_test_data.json').read_text())
26
+ message['data']['eventType'] = event_type
27
+ for flag in message['data']['featureFlags']:
28
+ flag.pop('insightsEnabled', None)
29
+ if setting is not MISSING:
30
+ flag['insightsEnabled'] = setting
31
+ flag['updatedAt'] = '2030-01-01T00:00:%02dZ' % revision
32
+ return json.dumps(message)
33
+
34
+
35
+ @pytest.fixture
36
+ def client():
37
+ processor = Mock()
38
+ config = Config(base64.b64encode(b'insights-test').decode(),
39
+ event_url='http://fake', streaming_url='http://fake',
40
+ update_processor_imp=NullUpdateProcessor,
41
+ event_processor_imp=lambda *_: processor)
42
+ with FBClient(config) as instance:
43
+ yield instance
44
+
45
+
46
+ def sync(client, message):
47
+ # Exercise the real WebSocket message parser and storage update without
48
+ # starting a network connection or a ping thread.
49
+ streaming = Streaming(Config('unused', 'http://fake', 'http://fake', offline=True), client._broadcaster,
50
+ client._update_status_provider, Event())
51
+ streaming._on_message(None, message)
52
+
53
+
54
+ @pytest.mark.parametrize('setting', SETTINGS)
55
+ @pytest.mark.parametrize('entry', ['variation', 'variation_detail', 'get', 'get_variation'])
56
+ def test_synced_insights_setting_controls_all_evaluation_entries(client, setting, entry):
57
+ sync(client, payload(setting))
58
+ flag = client._get_flag_internal(FLAG_KEY)
59
+ if setting is MISSING:
60
+ assert 'insightsEnabled' not in flag
61
+ else:
62
+ assert flag['insightsEnabled'] == setting
63
+ assert type(flag['insightsEnabled']) is type(setting)
64
+
65
+ if entry in ('get', 'get_variation'):
66
+ states = client.get_all_latest_flag_variations(USER)
67
+ client._event_processor.send_event.assert_not_called()
68
+ result = getattr(states, entry)(FLAG_KEY, False)
69
+ else:
70
+ result = getattr(client, entry)(FLAG_KEY, USER, False)
71
+ assert (result.variation if entry in ('get', 'variation_detail') else result) is True
72
+
73
+ calls = client._event_processor.send_event.call_args_list
74
+ assert len(calls) == (0 if setting is False else 1)
75
+ if calls:
76
+ variation = calls[0][0][0].to_json_dict()['variations'][0]['variation']
77
+ assert variation['id'] == flag['fallthrough']['variations'][0]['id']
78
+ assert variation['value'] == 'true'
79
+
80
+
81
+ @pytest.mark.parametrize('setting', SETTINGS)
82
+ def test_external_json_preserves_insights_setting(setting):
83
+ with FBClient(Config('unused', 'http://fake', 'http://fake', offline=True)) as client:
84
+ assert client.initialize_from_external_json(payload(setting))
85
+ flag = client._get_flag_internal(FLAG_KEY)
86
+ assert flag.get('insightsEnabled', MISSING) == setting
87
+ event = FlagEvent(FBUser.from_dict(USER))
88
+ client._evaluator.evaluate(flag, FBUser.from_dict(USER), event)
89
+ assert bool(event.is_send_event) == (setting is not False)
90
+ # Enabling insights does not replace offline event suppression.
91
+ client.variation(FLAG_KEY, USER, False)
92
+ assert isinstance(client._event_processor, NullEventProcessor)
93
+
94
+
95
+ @pytest.mark.parametrize('key,user', [
96
+ ('ff-test-off', USER),
97
+ ('ff-evaluation-test', {'key': 'test-target-user'}),
98
+ ('ff-evaluation-test', {'key': 'rule-user', 'graduated': 'true'}),
99
+ ('ff-evaluation-test', {'key': 'fallthrough-user'}),
100
+ ])
101
+ def test_insights_does_not_change_evaluation(client, key, user):
102
+ sync(client, payload(True))
103
+ flag = client._get_flag_internal(key)
104
+ user = FBUser.from_dict(dict(user, name='Test User'))
105
+ enabled_event = FlagEvent(user)
106
+ before = client._evaluator.evaluate(flag, user, enabled_event)
107
+ flag = dict(flag, insightsEnabled=False)
108
+ disabled_event = FlagEvent(user)
109
+ after = client._evaluator.evaluate(flag, user, disabled_event)
110
+ assert (after.id, after.value, after.reason) == (
111
+ before.id, before.value, before.reason)
112
+ assert enabled_event.is_send_event
113
+ reported = enabled_event.to_json_dict()['variations'][0]
114
+ assert reported == {
115
+ 'featureFlagKey': key,
116
+ 'timestamp': reported['timestamp'],
117
+ 'variation': {'id': before.id, 'value': before.value, 'reason': before.reason},
118
+ }
119
+ assert isinstance(reported['timestamp'], int)
120
+ assert not disabled_event.is_send_event
121
+
122
+
123
+ def test_patch_updates_future_evaluations_but_preserves_snapshot_eligibility(client):
124
+ sync(client, payload(True))
125
+ enabled_snapshot = client.get_all_latest_flag_variations(USER)
126
+ sync(client, payload(False, 'patch', 2))
127
+ assert client._get_flag_internal(FLAG_KEY)['insightsEnabled'] is False
128
+ disabled_snapshot = client.get_all_latest_flag_variations(USER)
129
+ assert client.variation(FLAG_KEY, USER) is True
130
+ client._event_processor.send_event.assert_not_called()
131
+ enabled_snapshot.get(FLAG_KEY)
132
+ assert client._event_processor.send_event.call_count == 1
133
+
134
+ sync(client, payload(True, 'patch', 3))
135
+ assert client._get_flag_internal(FLAG_KEY)['insightsEnabled'] is True
136
+ disabled_snapshot.get_variation(FLAG_KEY)
137
+ assert client._event_processor.send_event.call_count == 1
138
+ assert client.variation(FLAG_KEY, USER) is True
139
+ assert client._event_processor.send_event.call_count == 2
140
+
141
+
142
+ def test_metrics_and_identify_are_unaffected_and_closed_client_stays_silent(client):
143
+ sync(client, payload(False))
144
+ client.track_metric(USER, 'purchase')
145
+ client.identify(USER)
146
+ events = [call[0][0] for call in client._event_processor.send_event.call_args_list]
147
+ assert [type(event) for event in events] == [MetricEvent, UserEvent]
148
+ sync(client, payload(True, 'patch', 2))
149
+ client.stop()
150
+ client.variation(FLAG_KEY, USER)
151
+ assert client._event_processor.send_event.call_count == 2
152
+
153
+
154
+ def test_default_processor_only_delivers_enabled_evaluations(client):
155
+ sender = Mock()
156
+ processor = DefaultEventProcessor(client._config, sender)
157
+ client._event_processor = processor
158
+ sync(client, payload(True))
159
+ client.variation(FLAG_KEY, USER)
160
+ sync(client, payload(False, 'patch', 2))
161
+ client.variation(FLAG_KEY, USER)
162
+ client.get_all_latest_flag_variations(USER).get(FLAG_KEY)
163
+ # Shutdown drains accepted events, including the one collected before disable.
164
+ client.stop()
165
+ delivered = [event for call in sender.postJson.call_args_list
166
+ for event in json.loads(call[0][1])]
167
+ assert len(delivered) == 1
168
+ assert delivered[0]['variations'][0]['featureFlagKey'] == FLAG_KEY
@@ -1,3 +0,0 @@
1
- {
2
- "version":"1.1.10"
3
- }
File without changes
File without changes
File without changes
File without changes