fb-python-sdk 1.1.0__py3-none-any.whl → 1.1.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.
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: fb-python-sdk
3
- Version: 1.1.0
3
+ Version: 1.1.2
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
7
7
  Author-email: featbit.master@gmail.com
8
8
  Project-URL: Code, https://github.com/featbit/featbit-python-sdk
9
9
  Project-URL: Issue tracker, https://github.com/featbit/featbit/issues
10
- Classifier: Development Status :: 4 - Beta
10
+ Classifier: Development Status :: 5 - Production/Stable
11
11
  Classifier: Intended Audience :: Developers
12
12
  Classifier: License :: OSI Approved :: Apache Software License
13
13
  Classifier: Operating System :: OS Independent
@@ -76,7 +76,7 @@ from fbclient.config import Config
76
76
 
77
77
  env_secret = '<replace-with-your-env-secret>'
78
78
  event_url = 'http://localhost:5100'
79
- streaming_url = '"ws://localhost:5100"'
79
+ streaming_url = 'ws://localhost:5100'
80
80
 
81
81
  set_config(Config(env_secret, event_url, streaming_url))
82
82
  client = get()
@@ -87,7 +87,7 @@ if client.initialize:
87
87
  user_name = 'bot'
88
88
  user = {'key': user_key, 'name': user_name}
89
89
  detail = client.variation_detail(flag_key, user, default=None)
90
- print(f'flag {flag_key} returns {detail.value} for user {user_key}, reason: {detail.reason}')
90
+ print(f'flag {flag_key} returns {detail.variation} for user {user_key}, reason: {detail.reason}')
91
91
 
92
92
  # ensure that the SDK shuts down cleanly and has a chance to deliver events to FeatBit before the program exits
93
93
  client.stop()
@@ -1,18 +1,18 @@
1
1
  fbclient/__init__.py,sha256=GMbobi6viAXPaNedEqyUOgIhoJsDqP2_W-PMUAFKC5A,2249
2
2
  fbclient/category.py,sha256=DzblPnzVwsPKK_FSnLkK3HyWXStbNdPiRfdgSoEODVY,1058
3
- fbclient/client.py,sha256=qlfjx8QMa7OL5diZZWgBG6pyCFopJd5bS2WCC7MElxQ,18094
3
+ fbclient/client.py,sha256=5X2dsukdfbllAa8xQ_RxDeGMjiy3yAs9rU5TYMHX8FU,17863
4
4
  fbclient/common_types.py,sha256=UzbiWvM_Rzo8L0ZIA8GvZWlkK0U8-jVnUzoMyalqbok,10775
5
5
  fbclient/config.py,sha256=BMWMAVcModtDVMrBmSFI3V4jZFEZX0jlKZ-ENqC0hDA,8913
6
6
  fbclient/data_storage.py,sha256=gLYBAUTV-cR0rzoCxTCRYqAeGXhbIhQ7-_xh5OwLkqw,3342
7
7
  fbclient/evaluator.py,sha256=nN30r1kOZZ5JpdvGF-jiglo_QGLl4jeVr2wye_vRcfs,12389
8
- fbclient/event_processor.py,sha256=arkoJ_-y2816Fi55dB3jbATNFgMXYZymQxLIHi3OYks,8523
8
+ fbclient/event_processor.py,sha256=tVnP_YLcIX4RakEqBv5VSCKBAHrMPZBJIPHDA04CtVI,9022
9
9
  fbclient/event_types.py,sha256=0gorQ-RIjEw9OUYmV8MUoAgd4u1xlIVGayTeXkM-gAI,4597
10
10
  fbclient/interfaces.py,sha256=fgBvRVx2NncJ9Cg614hAQWY2r1JNjxGP-TKV0dQQ2hE,9517
11
11
  fbclient/status.py,sha256=0QaC-N-8zzdP7NL3l31Q3UrFmegrDS66a_kceXaopus,3688
12
12
  fbclient/status_types.py,sha256=-xB4zf2qHPNE1GHOSkO1h3SJ_5vQZqrvOymBVvvh5ts,3160
13
13
  fbclient/streaming.py,sha256=pS73oFqkBlV-z1YFF9-nU4Mf7WOg2vW2G5GeGrnk4aE,10647
14
- fbclient/update_processor.py,sha256=cvfoe5Dp46QZuFBFm9BHIb31Lz9xdzNf5zA0Nhw5c3E,489
15
- fbclient/version.py,sha256=DFGnvNkISEu0RDsAfc03O0dRz9PfmIb63Kyi-am-trE,18
14
+ fbclient/update_processor.py,sha256=E2AChTLh38i_D2yR7Wz3p4nxO6TlaBoRmF3kj-0pCsw,629
15
+ fbclient/version.py,sha256=tr2dMUFshB0V7YlDRbNgwbPa_pUX5HAgJ388cVKIj1Y,18
16
16
  fbclient/utils/__init__.py,sha256=3HjFPtGBWwU_7GQarELbNV0VuuQMuPw9TCDsR93t7u0,4339
17
17
  fbclient/utils/exponential_backoff_jitter_strategy.py,sha256=xZk7Y0yi3__U8c3DaX3PRb55vZAsRX__Rna3b2Wj9JA,1950
18
18
  fbclient/utils/http_client.py,sha256=LCTZWg-ukoHGTRaf9gozhNqNZW-htKHS7DnSr1RZPV4,5502
@@ -20,15 +20,17 @@ fbclient/utils/repeatable_task.py,sha256=R8f9BgyoP0y2CHJYaVBEOYHYpH8XDcgmFmCVe3i
20
20
  fbclient/utils/rwlock.py,sha256=C5uP5UD_BiH2fivUeoCOGrSbCM-Kz0J0U9m4MZbYXMg,1158
21
21
  fbclient/utils/variation_splitting_algorithm.py,sha256=4_qBeVANWIFPacifmV1zl_JZXywOd-wv1fQmnb8qyAE,864
22
22
  intergration_tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
23
- intergration_tests/run_in_start_wait.py,sha256=K3jSODDVD-EZ5wHN8oPe8SV0a49aZwhtnqi3QY1VDUU,1437
23
+ intergration_tests/readme.py,sha256=8kipas95E7ZMbDPuQKqQqyjhIjwdtNAOsucgtFqN0D0,942
24
+ intergration_tests/run_in_start_no_wait.py,sha256=Cg3U4kzKU22kQUMXOiYcWeyrmkk6YaFudPdgJ49XQ7Q,1398
25
+ intergration_tests/run_in_start_wait.py,sha256=9qyJCwZEgNDvvyCndRL_srA8ty_zTdIgdhGBHpo0xHw,1437
24
26
  tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
25
27
  tests/test_data_storage.py,sha256=q5tgVI3smztXLMdNpFUF1ES-rFuanwamYAKF8K1cEWc,3785
26
28
  tests/test_data_update_status_provider.py,sha256=O5xVZqG7atwUZA-AnH4XwLljV5yJzsBA0IcwOB1NOs8,4435
27
29
  tests/test_evaluator.py,sha256=8SH9lfSzVXLCQ3NR_OKf2bwYGbZcnwkAhwMNNObprUI,4675
28
30
  tests/test_event_processor.py,sha256=ceKHT5U7X_JfAwrnu_KJuwAsOTCsM8AdoXuNILMpwKI,4475
29
- tests/test_fbclient.py,sha256=NA5jmVBhyKEglok5Wph3zS7ev2twfahY_4p3vr6PcS8,10605
30
- fb_python_sdk-1.1.0.dist-info/LICENSE,sha256=Pp1Gaxzlu2F3GAFJ314grnBHifZdIK7_ZvCFV_khanM,1064
31
- fb_python_sdk-1.1.0.dist-info/METADATA,sha256=VYazqPIo7qMAYBgj_HJ-ZzQfPryuafOv1JdmvfTLAcE,11044
32
- fb_python_sdk-1.1.0.dist-info/WHEEL,sha256=pkctZYzUS4AYVn6dJ-7367OJZivF2e8RA9b_ZBjif18,92
33
- fb_python_sdk-1.1.0.dist-info/top_level.txt,sha256=idCKt6r1kjFQAq6Ug6aYecJxA5KTECnWtab_PbZHgW0,34
34
- fb_python_sdk-1.1.0.dist-info/RECORD,,
31
+ tests/test_fbclient.py,sha256=8BG-OO2AnKzoUDP9u1nu0O4WcUS5eBw4zZoY9LkkOYI,10823
32
+ fb_python_sdk-1.1.2.dist-info/LICENSE,sha256=Pp1Gaxzlu2F3GAFJ314grnBHifZdIK7_ZvCFV_khanM,1064
33
+ fb_python_sdk-1.1.2.dist-info/METADATA,sha256=YiFgJQ7_vhapOn_YeCMl96fXd7HLFYF2Zxy170Wasf4,11059
34
+ fb_python_sdk-1.1.2.dist-info/WHEEL,sha256=pkctZYzUS4AYVn6dJ-7367OJZivF2e8RA9b_ZBjif18,92
35
+ fb_python_sdk-1.1.2.dist-info/top_level.txt,sha256=idCKt6r1kjFQAq6Ug6aYecJxA5KTECnWtab_PbZHgW0,34
36
+ fb_python_sdk-1.1.2.dist-info/RECORD,,
fbclient/client.py CHANGED
@@ -14,7 +14,6 @@ from fbclient.event_processor import DefaultEventProcessor, NullEventProcessor
14
14
  from fbclient.event_types import FlagEvent, Metric, MetricEvent, UserEvent
15
15
  from fbclient.interfaces import DataUpdateStatusProvider
16
16
  from fbclient.status import DataUpdateStatusProviderImpl
17
- from fbclient.status_types import State
18
17
  from fbclient.streaming import Streaming, _data_to_dict
19
18
  from fbclient.update_processor import NullUpdateProcessor
20
19
  from fbclient.utils import (cast_variation_by_flag_type, check_uwsgi, log,
@@ -67,7 +66,10 @@ class FBClient:
67
66
  raise ValueError("Config is not valid")
68
67
 
69
68
  self._config = config
70
- self._config.validate()
69
+ if self._config.is_offline:
70
+ log.info("FB Python SDK: SDK is in offline mode")
71
+ else:
72
+ self._config.validate()
71
73
 
72
74
  # init components
73
75
  # event processor
@@ -90,15 +92,10 @@ class FBClient:
90
92
  if not isinstance(self._update_processor, NullUpdateProcessor):
91
93
  log.info("FB Python SDK: Waiting for Client initialization in %s seconds" % str(start_wait))
92
94
 
93
- if isinstance(self._data_storage, NullDataStorage) or not self._data_storage.initialized:
94
- log.warning("FB Python SDK: SDK just returns default variation because of no data found in the given environment")
95
-
96
95
  update_processor_ready.wait(start_wait)
97
- if self._config.is_offline:
98
- log.info("FB Python SDK: SDK is in offline mode")
99
- elif self._update_processor.initialized:
100
- log.info("FB Python SDK: SDK initialization is completed")
101
- else:
96
+ if isinstance(self._data_storage, NullDataStorage) or (not self._data_storage.initialized and not self._config.is_offline):
97
+ log.warning("FB Python SDK: SDK just returns default variation because of no data found in the given environment")
98
+ if not self._update_processor.initialized:
102
99
  log.warning("FB Python SDK: SDK was not successfully initialized")
103
100
  else:
104
101
  log.info("FB Python SDK: SDK starts in asynchronous mode")
@@ -374,13 +371,10 @@ class FBClient:
374
371
  :param json_str: feature flags, segments...etc in the json format
375
372
  :return: True if the initialization is well done
376
373
  """
377
- if self._config.is_offline and json_str:
374
+ if self._config.is_offline:
378
375
  all_data = json.loads(json_str)
379
376
  if valide_all_data(all_data):
380
377
  version, data = _data_to_dict(all_data['data'])
381
- res = self._update_status_provider.init(data, version)
382
- if res:
383
- self._update_status_provider.update_state(State.ok_state())
384
- return res
378
+ return self._update_status_provider.init(data, version)
385
379
 
386
380
  return False
@@ -1,7 +1,7 @@
1
1
  import json
2
2
  from concurrent.futures import ThreadPoolExecutor
3
3
  from queue import Empty, Queue
4
- from threading import BoundedSemaphore, Lock, Thread
4
+ from threading import BoundedSemaphore, Condition, Lock, Thread
5
5
  from typing import List, Optional
6
6
 
7
7
  from fbclient.common_types import FBEvent
@@ -76,7 +76,7 @@ class DefaultEventProcessor(EventProcessor):
76
76
  log.info('FB Python SDK: event processor is stopping')
77
77
  self.__closed = True
78
78
  self.__flush_task.stop()
79
- self.flush()
79
+ self.__put_message_async(MessageType.FLUSH)
80
80
  self.__put_message_and_wait_terminate(MessageType.SHUTDOWN)
81
81
 
82
82
 
@@ -94,6 +94,7 @@ class EventDispatcher(Thread):
94
94
  self.__events_buffer_to_next_flush = []
95
95
  self.__flush_workers = ThreadPoolExecutor(max_workers=self.__MAX_FLUSH_WORKERS_NUMBER)
96
96
  self.__permits = BoundedSemaphore(value=self.__MAX_FLUSH_WORKERS_NUMBER)
97
+ self.__lock = Condition(Lock())
97
98
 
98
99
  # blocks until at least one message is available and then:
99
100
  # 1: transfer the events to event buffer
@@ -137,6 +138,11 @@ class EventDispatcher(Thread):
137
138
  self.__events_buffer_to_next_flush.append(event)
138
139
 
139
140
  def __trigger_flush(self):
141
+ def flush_payload_done(fn):
142
+ self.__permits.release()
143
+ with self.__lock:
144
+ self.__lock.notify_all()
145
+
140
146
  if not self.__closed and len(self.__events_buffer_to_next_flush) > 0:
141
147
  log.debug('trigger flush')
142
148
  # get all the current events from event buffer
@@ -146,21 +152,27 @@ class EventDispatcher(Thread):
146
152
  # get an available flush worker to send events
147
153
  self.__flush_workers \
148
154
  .submit(FlushPayloadRunner(self.__config, self.__sender, payloads).run) \
149
- .add_done_callback(lambda x: self.__permits.release())
155
+ .add_done_callback(flush_payload_done)
150
156
  # clear the buffer for the next flush
151
157
  self.__events_buffer_to_next_flush.clear()
152
158
  # if no available flush worker, keep the events in the buffer
153
159
 
154
160
  def __shutdown(self):
155
161
  if not self.__closed:
156
- try:
157
- log.debug('event dispatcher is cleaning up thread and conn pool')
158
- self.__closed = True
159
- log.debug('flush worker pool is stopping...')
160
- self.__flush_workers.shutdown(wait=True)
161
- self.__sender.stop()
162
- except Exception as e:
163
- log.exception('FB Python SDK: unexpected error when closing event dispatcher: %s' % str(e))
162
+ with self.__lock:
163
+ try:
164
+ log.debug('event dispatcher is cleaning up thread and conn pool')
165
+ self.__wait_until_flush_playload_worker_down()
166
+ self.__closed = True
167
+ log.debug('flush worker pool is stopping...')
168
+ self.__flush_workers.shutdown(wait=True)
169
+ self.__sender.stop()
170
+ except Exception as e:
171
+ log.exception('FB Python SDK: unexpected error when closing event dispatcher: %s' % str(e))
172
+
173
+ def __wait_until_flush_playload_worker_down(self):
174
+ while self.__permits._value != self.__MAX_FLUSH_WORKERS_NUMBER:
175
+ self.__lock.wait()
164
176
 
165
177
 
166
178
  class FlushPayloadRunner:
@@ -1,15 +1,18 @@
1
1
  from threading import Event
2
2
  from fbclient.config import Config
3
3
  from fbclient.interfaces import DataUpdateStatusProvider, UpdateProcessor
4
+ from fbclient.status_types import State
4
5
 
5
6
 
6
7
  class NullUpdateProcessor(UpdateProcessor):
7
8
 
8
9
  def __init__(self, config: Config, dataUpdateStatusProvider: DataUpdateStatusProvider, ready: Event):
9
10
  self.__ready = ready
11
+ self.__store = dataUpdateStatusProvider
10
12
 
11
13
  def start(self):
12
14
  self.__ready.set()
15
+ self.__store.update_state(State.ok_state())
13
16
 
14
17
  def stop(self):
15
18
  pass
fbclient/version.py CHANGED
@@ -1 +1 @@
1
- VERSION = "1.1.0"
1
+ VERSION = "1.1.2"
@@ -0,0 +1,25 @@
1
+ import logging
2
+ from fbclient import get, set_config
3
+ from fbclient.config import Config
4
+
5
+ logging.basicConfig(level=logging.DEBUG,
6
+ format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
7
+ datefmt='%m-%d %H:%M')
8
+
9
+ env_secret = 'fXWjg00OTEa-M_iBCyYiBwFPfdBisjAkiY3ycIMOWw1Q'
10
+ event_url = 'http://localhost:5100'
11
+ streaming_url = 'ws://localhost:5100'
12
+
13
+ set_config(Config(env_secret, event_url, streaming_url))
14
+ client = get()
15
+
16
+ if client.initialize:
17
+ flag_key = 'ff-test-bool'
18
+ user_key = 'user-test-1'
19
+ user_name = 'user-test-1'
20
+ user = {'key': user_key, 'name': user_name}
21
+ detail = client.variation_detail(flag_key, user, default=None)
22
+ print(f'flag {flag_key} returns {detail.variation} for user {user_key}, reason: {detail.reason}')
23
+
24
+ # ensure that the SDK shuts down cleanly and has a chance to deliver events to FeatBit before the program exits
25
+ client.stop()
@@ -0,0 +1,36 @@
1
+ import logging
2
+ from time import time
3
+
4
+ from fbclient.client import FBClient
5
+ from fbclient.common_types import FBUser
6
+ from fbclient.config import Config
7
+ from fbclient.utils import log
8
+
9
+ logging.basicConfig(level=logging.DEBUG,
10
+ format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
11
+ datefmt='%m-%d %H:%M')
12
+
13
+ env_secret = 'fXWjg00OTEa-M_iBCyYiBwFPfdBisjAkiY3ycIMOWw1Q'
14
+
15
+ config = Config(env_secret, event_url='http://localhost:5100', streaming_url='ws://localhost:5100')
16
+ client = FBClient(config, start_wait=0)
17
+
18
+ if client.update_status_provider.wait_for_OKState(timeout=15.):
19
+ while True:
20
+ line = input('input user key and flag key seperated by / \n')
21
+ if 'exit' == line.strip():
22
+ break
23
+ try:
24
+ user_key, flag_key, *_ = tuple(line.split('/'))
25
+ user = {'key': user_key, 'name': user_key, 'country': 'cn'}
26
+ fb_user = FBUser.from_dict(user)
27
+ log.info('FB Python SDK Test: user= %s' % fb_user.to_json_str())
28
+ t1 = time()
29
+ log.info('FB Python SDK Test: variation= %s' % client.variation_detail(flag_key, user).to_json_str())
30
+ t2 = time()
31
+ log.info('FB Python SDK Test: execution time= %f' % (t2 - t1))
32
+ except:
33
+ log.exception('FB Python SDK Test: unexpected error')
34
+ break
35
+
36
+ client.stop()
@@ -10,7 +10,7 @@ logging.basicConfig(level=logging.DEBUG,
10
10
  format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
11
11
  datefmt='%m-%d %H:%M')
12
12
 
13
- env_secret = '9T0GABTXokagxhUZ81hUnws9_E2uOpIEyTjScBRr6JKA'
13
+ env_secret = 'fXWjg00OTEa-M_iBCyYiBwFPfdBisjAkiY3ycIMOWw1Q'
14
14
 
15
15
  config = Config(env_secret, event_url='http://localhost:5100', streaming_url='ws://localhost:5100')
16
16
 
tests/test_fbclient.py CHANGED
@@ -93,15 +93,20 @@ def test_start_and_timeout(mock_start_method):
93
93
  assert not client.initialize
94
94
 
95
95
 
96
+ def test_start_and_nowait():
97
+ with make_fb_client(NullUpdateProcessor, NullEventProcessor, start_wait=0) as client:
98
+ assert client.update_status_provider.wait_for_OKState(timeout=0.1)
99
+ assert client.initialize
100
+
101
+
96
102
  @patch.object(NullUpdateProcessor, "start")
97
- def test_start_and_nowait(mock_start_method):
103
+ def test_start_nowait_and_timeout(mock_start_method):
98
104
  def start():
99
105
  pass
100
106
  mock_start_method.side_effect = start
101
107
  with make_fb_client(NullUpdateProcessor, NullEventProcessor, start_wait=0) as client:
102
- assert not client.initialize
103
- sleep(0.1)
104
108
  assert not client.update_status_provider.wait_for_OKState(timeout=0.1)
109
+ assert not client.initialize
105
110
 
106
111
 
107
112
  @patch.object(NullUpdateProcessor, "start")