fb-python-sdk 1.1.6__py3-none-any.whl → 1.1.8__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.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: fb-python-sdk
3
- Version: 1.1.6
3
+ Version: 1.1.8
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
@@ -20,24 +20,36 @@ Classifier: Programming Language :: Python :: 3.9
20
20
  Classifier: Programming Language :: Python :: 3.10
21
21
  Classifier: Programming Language :: Python :: 3.11
22
22
  Classifier: Programming Language :: Python :: 3.12
23
- Requires-Python: >=3.6, <=3.12
23
+ Requires-Python: >=3.6, <3.13
24
24
  Description-Content-Type: text/markdown
25
25
  License-File: LICENSE
26
- Requires-Dist: certifi >=2018.4.16
27
- Requires-Dist: urllib3 >=1.22.0
28
- Requires-Dist: python-dateutil >=2.8.2
29
- Requires-Dist: websocket-client >=1.0.0
26
+ Requires-Dist: certifi>=2018.4.16
27
+ Requires-Dist: urllib3>=1.22.0
28
+ Requires-Dist: python-dateutil>=2.8.2
29
+ Requires-Dist: websocket-client>=1.0.0
30
30
  Provides-Extra: dev
31
- Requires-Dist: certifi >=2018.4.16 ; extra == 'dev'
32
- Requires-Dist: urllib3 >=1.22.0 ; extra == 'dev'
33
- Requires-Dist: websocket-client >=1.0.0 ; extra == 'dev'
34
- Requires-Dist: python-dateutil >=2.8.2 ; extra == 'dev'
35
- Requires-Dist: flake8 ; extra == 'dev'
36
- Requires-Dist: pytest ; extra == 'dev'
37
- Requires-Dist: pytest-mock ; extra == 'dev'
38
- Requires-Dist: autopep8 ; extra == 'dev'
39
- Requires-Dist: build ; extra == 'dev'
40
- Requires-Dist: twine ; extra == 'dev'
31
+ Requires-Dist: certifi>=2018.4.16; extra == "dev"
32
+ Requires-Dist: urllib3>=1.22.0; extra == "dev"
33
+ Requires-Dist: websocket-client>=1.0.0; extra == "dev"
34
+ Requires-Dist: python-dateutil>=2.8.2; extra == "dev"
35
+ Requires-Dist: flake8; extra == "dev"
36
+ Requires-Dist: pytest; extra == "dev"
37
+ Requires-Dist: pytest-mock; extra == "dev"
38
+ Requires-Dist: autopep8; extra == "dev"
39
+ Requires-Dist: build; extra == "dev"
40
+ Requires-Dist: twine; extra == "dev"
41
+ Dynamic: author
42
+ Dynamic: author-email
43
+ Dynamic: classifier
44
+ Dynamic: description
45
+ Dynamic: description-content-type
46
+ Dynamic: home-page
47
+ Dynamic: license-file
48
+ Dynamic: project-url
49
+ Dynamic: provides-extra
50
+ Dynamic: requires-dist
51
+ Dynamic: requires-python
52
+ Dynamic: summary
41
53
 
42
54
  # FeatBit Server-Side SDK for Python
43
55
 
@@ -59,7 +71,7 @@ If you want to use your own data source, see [Offline Mode](#offline-mode).
59
71
  ## Get Started
60
72
 
61
73
  ### Installation
62
- install the sdk in using pip, this version of the SDK is compatible with Python 3.6 through 3.11.
74
+ Install the SDK using pip. This version is compatible with Python 3.6 through 3.12.
63
75
 
64
76
  ```shell
65
77
  pip install fb-python-sdk
@@ -107,6 +119,29 @@ client.stop()
107
119
 
108
120
  - [Python Demo](https://github.com/featbit/featbit-samples/blob/main/samples/dino-game/demo-python/demo_python.py)
109
121
 
122
+ ### SDK reliability and live verification
123
+
124
+ The repository includes a repeatable [reliability review](docs/REVIEW.md)
125
+ covering unit tests, thread safety, memory retention, background-thread
126
+ shutdown, public runtime exception isolation, and redundant code. Run the
127
+ local resource audit with:
128
+
129
+ ```shell
130
+ python scripts/resource_audit.py --evaluations 80000 --workers 8
131
+ ```
132
+
133
+ To verify WebSocket synchronization, remote evaluation, status changes, event
134
+ delivery, and clean shutdown against FeatBit Cloud or a self-hosted evaluation
135
+ service, set `FEATBIT_ENV_SECRET` and run:
136
+
137
+ ```shell
138
+ python scripts/live_integration_check.py
139
+ ```
140
+
141
+ The live script never prints or persists the environment secret. See the
142
+ review document for all supported environment variables and verification
143
+ criteria.
144
+
110
145
  ### FBClient
111
146
 
112
147
  Applications **SHOULD instantiate a single FBClient instance** for the lifetime of the application. In the case where an application
@@ -153,6 +188,16 @@ if client.update_status_provider.wait_for_OKState():
153
188
 
154
189
  It's possible to set a timeout in seconds for the `wait_for_OKState` method. If the timeout is reached, the method will return `False` and the client will still be in an uninitialized state. If you do not specify a timeout, the method will wait indefinitely.
155
190
 
191
+ You can also observe later connection interruptions and recoveries:
192
+
193
+ ```python
194
+ def on_status_change(state):
195
+ print(state.state_type, state.error_track)
196
+
197
+ client.update_status_provider.add_listener(on_status_change)
198
+ # Remove it during application shutdown:
199
+ client.update_status_provider.remove_listener(on_status_change)
200
+ ```
156
201
 
157
202
  > To check if the client is ready is optional. Even if the client is not ready, you can still evaluate feature flags, but the default value will be returned if SDK is not yet initialized.
158
203
 
@@ -177,6 +222,7 @@ if client.initialize:
177
222
  flag_value = client.variation(flag_key, user, default_value)
178
223
  # evaluate the flag value and get the detail
179
224
  detail = client.variation_detail(flag_key, user, default=None)
225
+ print(detail.variation, detail.variation_id, detail.reason)
180
226
  ```
181
227
 
182
228
  If you would like to get variations of all feature flags in a special environment, you can use `fbclient.client.FBClient.get_all_latest_flag_variations`, SDK will return `fbclient.common_types.AllFlagStates`, that explain the details of all feature flags. `fbclient.common_types.AllFlagStates.get()` returns the detail of a given feature flag key.
@@ -196,6 +242,10 @@ if client.initialize:
196
242
 
197
243
  > **Note**
198
244
  > If evaluation happened before the client is initialized, or you provide the wrong flag key/user for evaluation, the `variation` calls will return the default value. The `fbclient.common_types.EvalDetail` will explain the details of the latest evaluation including error reason.
245
+ > Runtime evaluation does not raise solely because a supplied default has an
246
+ > unsupported type. If no flag value can be produced, that default object is
247
+ > returned unchanged and a diagnostic message is logged. Required client
248
+ > configuration remains fail-fast during construction.
199
249
 
200
250
  ### Flag Tracking
201
251
 
@@ -0,0 +1,27 @@
1
+ fb_python_sdk-1.1.8.dist-info/licenses/LICENSE,sha256=Pp1Gaxzlu2F3GAFJ314grnBHifZdIK7_ZvCFV_khanM,1064
2
+ fbclient/__init__.py,sha256=ApEOR6dqgunNQ1mCeazg28z69DNRzVpQS39ApQ8Mf2M,2193
3
+ fbclient/category.py,sha256=DzblPnzVwsPKK_FSnLkK3HyWXStbNdPiRfdgSoEODVY,1058
4
+ fbclient/client.py,sha256=QPLkC2C1J3B5VenJz6xslVVheK9jM34dqpFWkf7371M,21236
5
+ fbclient/common_types.py,sha256=0wMr-LzTQ6Q9GtSXkS7lXooYzgrK0smMKEu47CTq5Y8,11824
6
+ fbclient/config.py,sha256=jP0QEoSKpUdvKdm2mjFpd_Vz0y2v5njFCQotasykbSs,9482
7
+ fbclient/data_storage.py,sha256=FEOeoPLUZ2G1xJCa59XYtIgzIFsuqZHLKs2nP_NO8QQ,4632
8
+ fbclient/evaluator.py,sha256=OqPTmUXHl30NCb0RvD6fxBeSEpXHdZti-sWNPMIShlE,12387
9
+ fbclient/event_processor.py,sha256=DW2J2VhTxEv1EdWrUfWWot6q6VFNSzeCw9qANPZESDU,11681
10
+ fbclient/event_types.py,sha256=0gorQ-RIjEw9OUYmV8MUoAgd4u1xlIVGayTeXkM-gAI,4597
11
+ fbclient/flag_change_notification.py,sha256=0JTd2w7nkgJtawKlnqmdB6JFQ_mcpLU2L3y_FNvdUQM,8664
12
+ fbclient/interfaces.py,sha256=YJ454VaIfOdGIgaNjZn6DxnW_-VkITwR3FYblTrXiZs,10461
13
+ fbclient/notice_broadcaster.py,sha256=5LGfY-D_TVU29qJqj8lJ5cskL3c7EWFcewZoNX6_Bpk,3231
14
+ fbclient/status.py,sha256=gn5rl8yowdyze8IbvgZThI50Xic_xKpPqtgrJswdaKA,5992
15
+ fbclient/status_types.py,sha256=-xB4zf2qHPNE1GHOSkO1h3SJ_5vQZqrvOymBVvvh5ts,3160
16
+ fbclient/streaming.py,sha256=BVcAXxBf7O4HqShMC3BYj93jcoc0HnMS96C7qtrCyCY,16651
17
+ fbclient/update_processor.py,sha256=GCri2RzYSXuE-3nMtRJZRKrj0b1vtd4-rW1RpjG6bro,937
18
+ fbclient/utils/__init__.py,sha256=QWoIKTk2sJn_P_5VbY6GSWiNmHYqye44gzq91whePYs,4380
19
+ fbclient/utils/exponential_backoff_jitter_strategy.py,sha256=xZk7Y0yi3__U8c3DaX3PRb55vZAsRX__Rna3b2Wj9JA,1950
20
+ fbclient/utils/http_client.py,sha256=1G9mGVvU4X166VFoQyL43ORvpzTVPGZCuoDve_R75j4,5754
21
+ fbclient/utils/repeatable_task.py,sha256=mLkxlUkfHHmT5OOKlbh3vE1QrAH9JPecErvrwqsNgtc,1835
22
+ fbclient/utils/rwlock.py,sha256=BfgKYNwZ8y63yk-CphlFTCZ1-0Txh4XQ8Pzh2pohh5A,1159
23
+ fbclient/utils/variation_splitting_algorithm.py,sha256=4_qBeVANWIFPacifmV1zl_JZXywOd-wv1fQmnb8qyAE,864
24
+ fb_python_sdk-1.1.8.dist-info/METADATA,sha256=eftoGQBlVYPHDWPYd18BCJPmuLdT2y7RsIVfxCP6M_c,15071
25
+ fb_python_sdk-1.1.8.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
26
+ fb_python_sdk-1.1.8.dist-info/top_level.txt,sha256=m0lqkwRY4CCAR7ABfB47YE1I62JGd4v0yixam1hlTZk,9
27
+ fb_python_sdk-1.1.8.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.43.0)
2
+ Generator: setuptools (83.0.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
fbclient/__init__.py CHANGED
@@ -24,9 +24,7 @@ def get() -> FBClient:
24
24
  If you need to create multiple client instances with different environments, instead of this
25
25
  singleton approach you can call directly the :class:`fbclient.client.FBClient` constructor.
26
26
  """
27
- global __config
28
27
  global __client
29
- global __lock
30
28
 
31
29
  try:
32
30
  __lock.read_lock()
@@ -58,7 +56,6 @@ def set_config(config: Config):
58
56
  """
59
57
  global __config
60
58
  global __client
61
- global __lock
62
59
 
63
60
  try:
64
61
  __lock.write_lock()
fbclient/client.py CHANGED
@@ -16,6 +16,7 @@ from fbclient.flag_change_notification import FlagTracker
16
16
  from fbclient.interfaces import DataUpdateStatusProvider
17
17
  from fbclient.notice_broadcaster import NoticeBroadcater
18
18
  from fbclient.status import DataUpdateStatusProviderImpl
19
+ from fbclient.status_types import State
19
20
  from fbclient.streaming import Streaming, _data_to_dict
20
21
  from fbclient.update_processor import NullUpdateProcessor
21
22
  from fbclient.utils import (cast_variation_by_flag_type, check_uwsgi, log,
@@ -68,6 +69,10 @@ class FBClient:
68
69
  raise ValueError("Config is not valid")
69
70
 
70
71
  self._config = config
72
+ self._stop_lock = threading.Lock()
73
+ self._stop_complete = threading.Event()
74
+ self._stop_owner = None
75
+ self._closed = False
71
76
  if self._config.is_offline:
72
77
  log.info("FB Python SDK: SDK is in offline mode")
73
78
  else:
@@ -79,7 +84,7 @@ class FBClient:
79
84
  # init components
80
85
  # event processor
81
86
  self._event_processor = self._build_event_processor(config)
82
- self._event_handler = lambda event: self._event_processor.send_event(event)
87
+ self._event_handler = self._send_event_safely
83
88
  # data storage
84
89
  self._data_storage = config.data_storage
85
90
  # evaluator
@@ -126,6 +131,15 @@ class FBClient:
126
131
 
127
132
  return Streaming(config, broadcaster, update_status_provider, update_processor_event)
128
133
 
134
+ def _send_event_safely(self, event):
135
+ try:
136
+ if not self._closed:
137
+ self._event_processor.send_event(event)
138
+ except Exception:
139
+ # Event delivery must never affect the application request that
140
+ # produced the event, including when a custom processor is used.
141
+ log.exception('FB Python SDK: event processor failed')
142
+
129
143
  @property
130
144
  def initialize(self) -> bool:
131
145
  """Returns true if the client has successfully connected to feature flag center.
@@ -154,11 +168,46 @@ class FBClient:
154
168
 
155
169
  Do not attempt to use the client after calling this method.
156
170
  """
157
- log.info("FB Python SDK: Python SDK client is closing...")
158
- self._data_storage.stop()
159
- self._update_processor.stop()
160
- self._event_processor.stop()
161
- self._broadcaster.stop()
171
+ current_thread_id = threading.current_thread().ident
172
+ owns_shutdown = False
173
+ with self._stop_lock:
174
+ if self._closed:
175
+ # A recursive call from a synchronous shutdown callback must
176
+ # return immediately. Unrelated callers wait until the owner
177
+ # has released every SDK resource.
178
+ if self._stop_owner == current_thread_id:
179
+ return
180
+ else:
181
+ self._closed = True
182
+ self._stop_owner = current_thread_id
183
+ owns_shutdown = True
184
+
185
+ if not owns_shutdown:
186
+ self._stop_complete.wait()
187
+ return
188
+
189
+ try:
190
+ # The client was marked closed atomically above. Component
191
+ # shutdown can synchronously publish status changes, and an
192
+ # application listener is allowed to call client.stop() again, so
193
+ # no component method may run under the lifecycle lock.
194
+ log.info("FB Python SDK: Python SDK client is closing...")
195
+ # Stop producers before consumers, and isolate every component so
196
+ # one extension failure cannot prevent the remaining resources
197
+ # from being released or escape into application shutdown code.
198
+ for name, component in (
199
+ ('update processor', self._update_processor),
200
+ ('event processor', self._event_processor),
201
+ ('notice broadcaster', self._broadcaster),
202
+ ('data storage', self._data_storage)):
203
+ try:
204
+ component.stop()
205
+ except Exception:
206
+ log.exception('FB Python SDK: %s failed to stop' % name)
207
+ finally:
208
+ with self._stop_lock:
209
+ self._stop_owner = None
210
+ self._stop_complete.set()
162
211
 
163
212
  def __enter__(self):
164
213
  return self
@@ -174,17 +223,21 @@ class FBClient:
174
223
  def _get_flag_internal(self, key: str) -> Optional[dict]:
175
224
  return self._data_storage.get(FEATURE_FLAGS, key)
176
225
 
177
- def __handle_default_value(self, key: str, default: Any) -> Tuple[Optional[str], Optional[str]]:
226
+ def __handle_default_value(self, key: str, default: Any) -> Tuple[Optional[str], Any]:
178
227
  default_value = self._config.get_default_value(key, default)
179
- default_value_type = simple_type_inference(default_value)
180
- if default_value is None:
181
- return None, None
182
- elif default_value_type == 'boolean':
183
- return default_value_type, str(default).lower()
184
- elif default_value_type == 'json':
185
- return default_value_type, json.dumps(default_value)
186
- else:
187
- return default_value_type, str(default_value)
228
+ try:
229
+ default_value_type = simple_type_inference(default_value)
230
+ if default_value is None:
231
+ return None, None
232
+ elif default_value_type == 'boolean':
233
+ return default_value_type, str(default_value).lower()
234
+ elif default_value_type == 'json':
235
+ return default_value_type, json.dumps(default_value)
236
+ else:
237
+ return default_value_type, str(default_value)
238
+ except Exception:
239
+ log.warning('FB Python SDK: unsupported default value; returning it unchanged on evaluation failure')
240
+ return None, default_value
188
241
 
189
242
  def _evaluate_internal(self, key: str, user: dict, default: Any = None) -> _EvalResult:
190
243
  default_value_type, default_value = self.__handle_default_value(key, default)
@@ -235,7 +288,7 @@ class FBClient:
235
288
  :param default: the default value of the flag, to be used if the return value is not available
236
289
  :return: one of the flag's values in any type in any type of string, bool, float, json
237
290
  or the default value if flag evaluation fails
238
- :raises: ValueError if the default is not a string, boolean, numeric, or json type
291
+ Unsupported defaults are returned unchanged if evaluation cannot produce a flag value.
239
292
  """
240
293
  er = self._evaluate_internal(key, user, default)
241
294
  return cast_variation_by_flag_type(er.flag_type, er.value)
@@ -252,7 +305,7 @@ class FBClient:
252
305
  :param user: the attributes of the user
253
306
  :param default: the default value of the flag, to be used if the return value is not available
254
307
  :return: an :class:`fbclient.common_types.EvalDetail` object
255
- :raises: ValueError if the default is not a string, boolean, numeric, or json type
308
+ Unsupported defaults are returned unchanged if evaluation cannot produce a flag value.
256
309
  """
257
310
  return self._evaluate_internal(key, user, default).to_evail_detail
258
311
 
@@ -318,7 +371,11 @@ class FBClient:
318
371
  schedules the next event delivery to be as soon as possible; however, the delivery still
319
372
  happens asynchronously on a thread, so this method will return immediately.
320
373
  """
321
- self._event_processor.flush()
374
+ try:
375
+ if not self._closed:
376
+ self._event_processor.flush()
377
+ except Exception:
378
+ log.exception('FB Python SDK: event processor flush failed')
322
379
 
323
380
  def identify(self, user: dict):
324
381
  """register an end user in the feature flag center
@@ -352,7 +409,6 @@ class FBClient:
352
409
  log.warning('FB Python SDK: user invalid')
353
410
  return
354
411
 
355
- fb_user = FBUser.from_dict(user)
356
412
  metric_event = MetricEvent(fb_user).add(Metric(event_name, metric_value))
357
413
  self._event_handler(metric_event)
358
414
 
@@ -385,10 +441,15 @@ class FBClient:
385
441
  :param json_str: feature flags, segments...etc in the json format
386
442
  :return: True if the initialization is well done
387
443
  """
388
- if self._config.is_offline:
389
- all_data = json.loads(json_str)
390
- if valide_all_data(all_data):
391
- version, data = _data_to_dict(all_data['data'])
392
- return self._update_status_provider.init(data, version)
444
+ try:
445
+ if self._config.is_offline:
446
+ all_data = json.loads(json_str)
447
+ if valide_all_data(all_data):
448
+ version, data = _data_to_dict(all_data['data'])
449
+ if self._update_status_provider.init(data, version):
450
+ self._update_status_provider.update_state(State.ok_state())
451
+ return True
452
+ except Exception:
453
+ log.exception('FB Python SDK: invalid external bootstrap data')
393
454
 
394
455
  return False
fbclient/common_types.py CHANGED
@@ -90,19 +90,21 @@ class EvalDetail(Jsonfy):
90
90
  reason: str,
91
91
  variation: Any,
92
92
  key_name: Optional[str] = None,
93
- name: Optional[str] = None):
93
+ name: Optional[str] = None,
94
+ variation_id: Optional[str] = None):
94
95
  """Constructs an instance.
95
96
 
96
- :param id: variation id
97
97
  :param reason: main factor that influenced the flag evaluation value
98
98
  :param variation: result of the flag evaluation in any type of string, bool, float/int, json(Python object) or default value if flag evaluation fails
99
99
  :param key_name: key name of the flag
100
100
  :param name: name of the flag
101
+ :param variation_id: stable identifier of the resolved variation, or None if evaluation failed
101
102
  """
102
103
  self._reason = reason
103
104
  self._variation = variation
104
105
  self._key_name = key_name
105
106
  self._name = name
107
+ self._variation_id = variation_id
106
108
 
107
109
  @property
108
110
  def reason(self) -> str:
@@ -129,6 +131,12 @@ class EvalDetail(Jsonfy):
129
131
  """
130
132
  return self._name
131
133
 
134
+ @property
135
+ def variation_id(self) -> Optional[str]:
136
+ """The stable identifier of the resolved variation, if evaluation succeeded.
137
+ """
138
+ return self._variation_id
139
+
132
140
  def to_json_dict(self) -> dict:
133
141
  json_dict = {}
134
142
  json_dict['reason'] = self.reason
@@ -329,7 +337,8 @@ class _EvalResult:
329
337
  @property
330
338
  def to_evail_detail(self) -> "EvalDetail":
331
339
  _value = cast_variation_by_flag_type(self.__flag_type, self.__value)
332
- return EvalDetail(self.__reason, _value, self.__key_name, self.__name)
340
+ variation_id = self.__id if self.is_success else None
341
+ return EvalDetail(self.__reason, _value, self.__key_name, self.__name, variation_id)
333
342
 
334
343
  @property
335
344
  def to_flag_state(self) -> "FlagState":
fbclient/config.py CHANGED
@@ -1,3 +1,4 @@
1
+ from copy import deepcopy
1
2
  from threading import Event
2
3
  from typing import Any, Callable, Dict, Optional, Tuple
3
4
 
@@ -135,8 +136,8 @@ class Config:
135
136
  data_storage: Optional[DataStorage] = None,
136
137
  update_processor_imp: Optional[Callable[['Config', DataUpdateStatusProvider, Event], UpdateProcessor]] = None,
137
138
  event_processor_imp: Optional[Callable[['Config', Sender], EventProcessor]] = None,
138
- http: HTTPConfig = HTTPConfig(),
139
- websocket: WebSocketConfig = WebSocketConfig(),
139
+ http: Optional[HTTPConfig] = None,
140
+ websocket: Optional[WebSocketConfig] = None,
140
141
  defaults: Optional[dict] = None):
141
142
 
142
143
  self.__env_secret = env_secret
@@ -145,21 +146,24 @@ class Config:
145
146
  self.__streaming_first_retry_delay = 1.0 if streaming_first_retry_delay is None or streaming_first_retry_delay <= 0 else min(
146
147
  streaming_first_retry_delay, 60.0)
147
148
  self.__offline = offline
148
- self.__data_storage = data_storage if data_storage else InMemoryDataStorage()
149
+ self.__data_storage = data_storage if data_storage is not None else InMemoryDataStorage()
149
150
  self.__event_processor_imp = event_processor_imp
150
151
  self.__update_processor_imp = update_processor_imp
151
- self.__events_max_in_queue = 10000 if events_max_in_queue is None else max(events_max_in_queue, 10000)
152
+ self.__events_max_in_queue = 10000 if events_max_in_queue is None or events_max_in_queue <= 0 else events_max_in_queue
152
153
  self.__events_flush_interval = 1.0 if events_flush_interval is None or events_flush_interval <= 0 else min(
153
154
  events_flush_interval, 3.0)
154
155
  self.__events_retry_interval = 0.1 if events_retry_interval is None or events_retry_interval <= 0 else min(
155
156
  events_retry_interval, 1)
156
157
  self.__events_max_retries = 1 if events_max_retries is None or events_max_retries <= 0 else min(
157
158
  events_max_retries, 3)
158
- self.__http = http
159
- self.__websocket = websocket
160
- self.__defaults = defaults if defaults is not None else {}
161
-
162
- def copy_config_in_a_new_env(self, env_secret: str, defaults=None) -> 'Config':
159
+ # Avoid sharing mutable default configuration objects between SDK
160
+ # clients created by unrelated applications or tests.
161
+ self.__http = http if http is not None else HTTPConfig()
162
+ self.__websocket = websocket if websocket is not None else WebSocketConfig()
163
+ self.__defaults = deepcopy(defaults) if defaults is not None else {}
164
+
165
+ def copy_config_in_a_new_env(self, env_secret: str, defaults=None,
166
+ data_storage: Optional[DataStorage] = None) -> 'Config':
163
167
  return Config(env_secret,
164
168
  event_url=self.__event_url,
165
169
  streaming_url=self.__streaming_url,
@@ -169,14 +173,17 @@ class Config:
169
173
  events_retry_interval=self.__events_retry_interval,
170
174
  events_max_retries=self.__events_max_retries,
171
175
  offline=self.__offline,
172
- data_storage=self.__data_storage,
176
+ # Environment data must never leak between clients. A
177
+ # caller that intentionally wants a custom store can
178
+ # still provide one explicitly.
179
+ data_storage=data_storage,
173
180
  update_processor_imp=self.__update_processor_imp,
174
181
  event_processor_imp=self.__event_processor_imp,
175
- http=self.__http,
176
- websocket=self.__websocket,
182
+ http=deepcopy(self.__http),
183
+ websocket=deepcopy(self.__websocket),
177
184
  defaults=defaults if defaults is not None else self.__defaults)
178
185
 
179
- def get_default_value(self, key, default=None) -> Dict[str, Any]:
186
+ def get_default_value(self, key, default=None) -> Any:
180
187
  return self.__defaults.get(key, default)
181
188
 
182
189
  @property
fbclient/data_storage.py CHANGED
@@ -18,7 +18,7 @@ class InMemoryDataStorage(DataStorage):
18
18
  def get(self, kind: Category, key: str) -> Optional[dict]:
19
19
  try:
20
20
  self.__rw_lock.read_lock()
21
- keyItems = self.__storage[kind]
21
+ keyItems = self.__storage.get(kind, {})
22
22
  item = keyItems.get(key, None)
23
23
  if (item is None) or item['isArchived']:
24
24
  return None
@@ -29,35 +29,58 @@ class InMemoryDataStorage(DataStorage):
29
29
  def get_all(self, kind: Category) -> Mapping[str, dict]:
30
30
  try:
31
31
  self.__rw_lock.read_lock()
32
- keyItems = self.__storage[kind]
32
+ keyItems = self.__storage.get(kind, {})
33
33
  return dict((k, v) for k, v in keyItems.items() if not v['isArchived'])
34
34
  finally:
35
35
  self.__rw_lock.release_read_lock()
36
36
 
37
- def init(self, all_data: Mapping[Category, Mapping[str, dict]], version: int = 0):
38
- if (not all_data) or not isinstance(version, int) or version <= self.__version:
39
- return
37
+ def init(self, all_data: Mapping[Category, Mapping[str, dict]], version: int = 0) -> bool:
38
+ if (not all_data) or not isinstance(version, int) or version < 0:
39
+ return False
40
+ snapshot_is_empty = not any(bool(items) for items in all_data.values())
41
+ # A version-zero snapshot is valid only when the environment is empty.
42
+ # This is how the service represents a successful full sync containing
43
+ # no flags or segments.
44
+ if version == 0 and not snapshot_is_empty:
45
+ return False
40
46
  try:
41
47
  self.__rw_lock.write_lock()
48
+ if self.__initialized:
49
+ if (version == self.__version == 0
50
+ and snapshot_is_empty
51
+ and not any(bool(items)
52
+ for items in self.__storage.values())):
53
+ # Empty environments repeatedly send the same version-zero
54
+ # full snapshot after reconnecting. Treat it as an accepted
55
+ # no-op instead of forcing another reconnect.
56
+ return True
57
+ if version <= self.__version:
58
+ return False
42
59
  self.__storage.clear()
43
60
  self.__storage.update(all_data) # type: ignore
44
61
  self.__initialized = True
45
62
  self.__version = version
63
+ return True
46
64
  finally:
47
65
  self.__rw_lock.release_write_lock()
48
66
 
49
- def upsert(self, kind: Category, key: str, item: dict, version: int = 0):
50
- if (not kind) or (not item) or (not key) or not isinstance(version, int) or version <= self.__version:
51
- return
67
+ def upsert(self, kind: Category, key: str, item: dict, version: int = 0) -> bool:
68
+ if (not kind) or (not item) or (not key) or not isinstance(version, int) or version <= 0:
69
+ return False
52
70
  try:
53
71
  self.__rw_lock.write_lock()
54
72
  keyItems = self.__storage[kind]
55
73
  v = keyItems.get(key, None)
56
- if (v is None) or v['timestamp'] < version:
57
- keyItems[key] = item
58
- self.__version = version
59
- if not self.__initialized:
60
- self.__initialized = True
74
+ # Patches are versioned per entity. Comparing with the global
75
+ # latest version would incorrectly discard a different flag or
76
+ # segment that happens to have the same timestamp.
77
+ if v is not None and v.get('timestamp', 0) >= version:
78
+ return False
79
+ keyItems[key] = item
80
+ self.__version = max(self.__version, version)
81
+ if not self.__initialized:
82
+ self.__initialized = True
83
+ return True
61
84
  finally:
62
85
  self.__rw_lock.release_write_lock()
63
86
 
@@ -89,11 +112,11 @@ class NullDataStorage(DataStorage):
89
112
  def get_all(self, kind: Category) -> Mapping[str, dict]:
90
113
  return dict()
91
114
 
92
- def init(self, all_data: Mapping[Category, Mapping[str, dict]], version: int = 0):
93
- pass
115
+ def init(self, all_data: Mapping[Category, Mapping[str, dict]], version: int = 0) -> bool:
116
+ return True
94
117
 
95
- def upsert(self, kind: Category, key: str, item: dict, version: int = 0):
96
- pass
118
+ def upsert(self, kind: Category, key: str, item: dict, version: int = 0) -> bool:
119
+ return True
97
120
 
98
121
  @property
99
122
  def initialized(self) -> bool: