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/common_types.py CHANGED
@@ -4,21 +4,18 @@ from typing import Any, Callable, Dict, Mapping, Optional
4
4
 
5
5
  from fbclient.utils import cast_variation_by_flag_type, is_numeric
6
6
 
7
- __BUILTINS_MAPING__ = {'key': 'keyid',
8
- 'name': 'name',
9
- 'keyid': 'keyid'}
7
+ __BUILTINS_MAPING__ = {"key": "keyid", "name": "name", "keyid": "keyid"}
10
8
 
11
- __NO_VARIATION__ = 'NE'
9
+ __NO_VARIATION__ = "NE"
12
10
 
13
- __FLAG_NOT_FOUND__ = 'flag not found'
11
+ __FLAG_NOT_FOUND__ = "flag not found"
14
12
 
15
- __FLAG_KEY_UNKNOWN__ = 'flag key unknown'
13
+ __FLAG_KEY_UNKNOWN__ = "flag key unknown"
16
14
 
17
- __FLAG_NAME_UNKNOWN__ = 'flag name unknown'
15
+ __FLAG_NAME_UNKNOWN__ = "flag name unknown"
18
16
 
19
17
 
20
18
  class Jsonfy(ABC):
21
-
22
19
  @abstractmethod
23
20
  def to_json_dict(self) -> dict:
24
21
  pass
@@ -28,27 +25,32 @@ class Jsonfy(ABC):
28
25
 
29
26
 
30
27
  class FBUser(Jsonfy):
31
-
32
28
  def __init__(self, key: Optional[str], name: Optional[str], **kwargs):
33
- self._check_argument(key, 'key is not valid')
34
- self._check_argument(name, 'name is not valid')
29
+ self._check_argument(key, "key is not valid")
30
+ self._check_argument(name, "name is not valid")
35
31
  self._commons = {}
36
- self._commons['keyid'] = key
37
- self._commons['name'] = name
32
+ self._commons["keyid"] = key
33
+ self._commons["name"] = name
38
34
  self._customs = {}
39
35
  if len(kwargs) > 0:
40
- self._customs \
41
- .update(dict((k, str(v)) for k, v in kwargs.items() if isinstance(k, str) and k.lower() not in __BUILTINS_MAPING__.keys()
42
- and (isinstance(v, str) or is_numeric(v) or isinstance(v, bool))))
36
+ self._customs.update(
37
+ dict(
38
+ (k, str(v))
39
+ for k, v in kwargs.items()
40
+ if isinstance(k, str)
41
+ and k.lower() not in __BUILTINS_MAPING__.keys()
42
+ and (isinstance(v, str) or is_numeric(v) or isinstance(v, bool))
43
+ )
44
+ )
43
45
 
44
46
  @staticmethod
45
47
  def from_dict(user: Dict[str, Any]) -> "FBUser":
46
48
  user_copy = {}
47
49
  if not isinstance(user, dict):
48
- raise ValueError('user is not valid')
50
+ raise ValueError("user is not valid")
49
51
  user_copy.update(user)
50
- key = user_copy.pop('key', None) or user_copy.pop('keyid', None)
51
- name = user_copy.pop('name', None)
52
+ key = user_copy.pop("key", None) or user_copy.pop("keyid", None)
53
+ name = user_copy.pop("name", None)
52
54
  return FBUser(key, name, **user_copy)
53
55
 
54
56
  def _check_argument(self, value, msg) -> bool:
@@ -70,9 +72,11 @@ class FBUser(Jsonfy):
70
72
 
71
73
  def to_json_dict(self) -> dict:
72
74
  json_dict = {}
73
- json_dict['keyId'] = self._commons['keyid']
74
- json_dict['name'] = self._commons['name']
75
- json_dict['customizedProperties'] = [{'name': k, 'value': v} for k, v in self._customs.items()]
75
+ json_dict["keyId"] = self._commons["keyid"]
76
+ json_dict["name"] = self._commons["name"]
77
+ json_dict["customizedProperties"] = [
78
+ {"name": k, "value": v} for k, v in self._customs.items()
79
+ ]
76
80
  return json_dict
77
81
 
78
82
 
@@ -86,12 +90,14 @@ class EvalDetail(Jsonfy):
86
90
  4: float if the feature flag is a numeric type
87
91
  """
88
92
 
89
- def __init__(self,
90
- reason: str,
91
- variation: Any,
92
- key_name: Optional[str] = None,
93
- name: Optional[str] = None,
94
- variation_id: Optional[str] = None):
93
+ def __init__(
94
+ self,
95
+ reason: str,
96
+ variation: Any,
97
+ key_name: Optional[str] = None,
98
+ name: Optional[str] = None,
99
+ variation_id: Optional[str] = None,
100
+ ):
95
101
  """Constructs an instance.
96
102
 
97
103
  :param reason: main factor that influenced the flag evaluation value
@@ -108,8 +114,7 @@ class EvalDetail(Jsonfy):
108
114
 
109
115
  @property
110
116
  def reason(self) -> str:
111
- """A string describing the main factor that influenced the flag evaluation value.
112
- """
117
+ """A string describing the main factor that influenced the flag evaluation value."""
113
118
  return self._reason
114
119
 
115
120
  @property
@@ -121,34 +126,30 @@ class EvalDetail(Jsonfy):
121
126
 
122
127
  @property
123
128
  def key_name(self) -> Optional[str]:
124
- """The flag key name
125
- """
129
+ """The flag key name"""
126
130
  return self._key_name
127
131
 
128
132
  @property
129
133
  def name(self) -> Optional[str]:
130
- """The flag name
131
- """
134
+ """The flag name"""
132
135
  return self._name
133
136
 
134
137
  @property
135
138
  def variation_id(self) -> Optional[str]:
136
- """The stable identifier of the resolved variation, if evaluation succeeded.
137
- """
139
+ """The stable identifier of the resolved variation, if evaluation succeeded."""
138
140
  return self._variation_id
139
141
 
140
142
  def to_json_dict(self) -> dict:
141
143
  json_dict = {}
142
- json_dict['reason'] = self.reason
143
- json_dict['variation'] = self.variation
144
- json_dict['keyName'] = self.key_name
145
- json_dict['name'] = self.name
144
+ json_dict["reason"] = self.reason
145
+ json_dict["variation"] = self.variation
146
+ json_dict["keyName"] = self.key_name
147
+ json_dict["name"] = self.name
146
148
  return json_dict
147
149
 
148
150
 
149
151
  class BasicFlagState:
150
- """Abstract class representing flag state after feature flag evaluaion
151
- """
152
+ """Abstract class representing flag state after feature flag evaluaion"""
152
153
 
153
154
  def __init__(self, success: bool, reason: str):
154
155
  """Constructs an instance.
@@ -157,18 +158,16 @@ class BasicFlagState:
157
158
  :param reason: the state of last evaluation; the value is OK if successful
158
159
  """
159
160
  self._success = success
160
- self._reason = 'OK' if success else reason
161
+ self._reason = "OK" if success else reason
161
162
 
162
163
  @property
163
164
  def success(self) -> bool:
164
- """Returns true if last evaluation was successful
165
- """
165
+ """Returns true if last evaluation was successful"""
166
166
  return self._success
167
167
 
168
168
  @property
169
169
  def reason(self) -> str:
170
- """reason the state of last evaluation; the value is OK if successful
171
- """
170
+ """reason the state of last evaluation; the value is OK if successful"""
172
171
  return self._reason
173
172
 
174
173
 
@@ -199,9 +198,11 @@ class FlagState(BasicFlagState, Jsonfy):
199
198
  return self._data
200
199
 
201
200
  def to_json_dict(self) -> dict:
202
- return {'success': self.success,
203
- 'reason': self.reason,
204
- 'data': self._data.to_json_dict() if self._data else None}
201
+ return {
202
+ "success": self.success,
203
+ "reason": self.reason,
204
+ "data": self._data.to_json_dict() if self._data else None,
205
+ }
205
206
 
206
207
 
207
208
  class AllFlagStates(BasicFlagState, Jsonfy):
@@ -209,9 +210,13 @@ class AllFlagStates(BasicFlagState, Jsonfy):
209
210
  :func:`get(key_name)` to get the state for a given feature flag key
210
211
  """
211
212
 
212
- def __init__(self, success: bool, reason: str,
213
- data: Mapping[EvalDetail, "FBEvent"],
214
- event_handler: Callable[["FBEvent"], None]):
213
+ def __init__(
214
+ self,
215
+ success: bool,
216
+ reason: str,
217
+ data: Mapping[EvalDetail, "FBEvent"],
218
+ event_handler: Callable[["FBEvent"], None],
219
+ ):
215
220
  """Constructs an instance.
216
221
 
217
222
  :param success: True if successful
@@ -220,7 +225,11 @@ class AllFlagStates(BasicFlagState, Jsonfy):
220
225
  :event_handler: callback function used to send events to feature flag center
221
226
  """
222
227
  super().__init__(success, reason)
223
- self._data = dict((ed.key_name, (ed, fb_event)) for ed, fb_event in data.items()) if data else {}
228
+ self._data = (
229
+ dict((ed.key_name, (ed, fb_event)) for ed, fb_event in data.items())
230
+ if data
231
+ else {}
232
+ )
224
233
  self._event_handler = event_handler
225
234
 
226
235
  def keys(self):
@@ -254,15 +263,25 @@ class AllFlagStates(BasicFlagState, Jsonfy):
254
263
  ed, fb_event = self._data.get(key_name, (None, False))
255
264
  if self._event_handler and fb_event:
256
265
  self._event_handler(fb_event)
257
- return ed if ed is not None else EvalDetail(reason=__FLAG_NOT_FOUND__,
258
- variation=default,
259
- key_name=key_name,
260
- name=__FLAG_NAME_UNKNOWN__)
266
+ return (
267
+ ed
268
+ if ed is not None
269
+ else EvalDetail(
270
+ reason=__FLAG_NOT_FOUND__,
271
+ variation=default,
272
+ key_name=key_name,
273
+ name=__FLAG_NAME_UNKNOWN__,
274
+ )
275
+ )
261
276
 
262
277
  def to_json_dict(self) -> dict:
263
- return {'success': self.success,
264
- 'message': self.reason,
265
- 'data': [ed.to_json_dict() for ed, _ in self._data.values()] if self._data else []}
278
+ return {
279
+ "success": self.success,
280
+ "message": self.reason,
281
+ "data": [ed.to_json_dict() for ed, _ in self._data.values()]
282
+ if self._data
283
+ else [],
284
+ }
266
285
 
267
286
 
268
287
  class FBEvent(Jsonfy, ABC):
@@ -270,7 +289,7 @@ class FBEvent(Jsonfy, ABC):
270
289
  self._user = user
271
290
 
272
291
  @abstractmethod
273
- def add(self, *elements) -> 'FBEvent':
292
+ def add(self, *elements) -> "FBEvent":
274
293
  pass
275
294
 
276
295
  @property
@@ -280,14 +299,15 @@ class FBEvent(Jsonfy, ABC):
280
299
 
281
300
 
282
301
  class _EvalResult:
283
-
284
- def __init__(self,
285
- id: str,
286
- value: Optional[str],
287
- reason: str,
288
- key_name: Optional[str] = None,
289
- name: Optional[str] = None,
290
- flag_type: Optional[str] = 'string'):
302
+ def __init__(
303
+ self,
304
+ id: str,
305
+ value: Optional[str],
306
+ reason: str,
307
+ key_name: Optional[str] = None,
308
+ name: Optional[str] = None,
309
+ flag_type: Optional[str] = "string",
310
+ ):
291
311
 
292
312
  self.__id = id
293
313
  self.__value = value
@@ -297,8 +317,20 @@ class _EvalResult:
297
317
  self.__flag_type = flag_type
298
318
 
299
319
  @staticmethod
300
- def error(default_value: Optional[str], reason: str, key_name: Optional[str] = None, flag_type: Optional[str] = 'string'):
301
- return _EvalResult(__NO_VARIATION__, default_value, reason, key_name if key_name else __FLAG_KEY_UNKNOWN__, __FLAG_NAME_UNKNOWN__, flag_type)
320
+ def error(
321
+ default_value: Optional[str],
322
+ reason: str,
323
+ key_name: Optional[str] = None,
324
+ flag_type: Optional[str] = "string",
325
+ ):
326
+ return _EvalResult(
327
+ __NO_VARIATION__,
328
+ default_value,
329
+ reason,
330
+ key_name if key_name else __FLAG_KEY_UNKNOWN__,
331
+ __FLAG_NAME_UNKNOWN__,
332
+ flag_type,
333
+ )
302
334
 
303
335
  @property
304
336
  def id(self) -> str:
@@ -332,7 +364,9 @@ class _EvalResult:
332
364
  def to_evail_detail(self) -> "EvalDetail":
333
365
  _value = cast_variation_by_flag_type(self.__flag_type, self.__value)
334
366
  variation_id = self.__id if self.is_success else None
335
- return EvalDetail(self.__reason, _value, self.__key_name, self.__name, variation_id)
367
+ return EvalDetail(
368
+ self.__reason, _value, self.__key_name, self.__name, variation_id
369
+ )
336
370
 
337
371
  @property
338
372
  def to_flag_state(self) -> "FlagState":
fbclient/config.py CHANGED
@@ -3,11 +3,16 @@ from threading import Event
3
3
  from typing import Any, Callable, Dict, Optional, Tuple
4
4
 
5
5
  from fbclient.data_storage import InMemoryDataStorage
6
- from fbclient.interfaces import (DataStorage, DataUpdateStatusProvider,
7
- EventProcessor, Sender, UpdateProcessor)
6
+ from fbclient.interfaces import (
7
+ DataStorage,
8
+ DataUpdateStatusProvider,
9
+ EventProcessor,
10
+ Sender,
11
+ UpdateProcessor,
12
+ )
8
13
  from fbclient.utils import is_ascii, is_url
9
14
 
10
- __all__ = ['Config', 'HTTPConfig', 'WebSocketConfig']
15
+ __all__ = ["Config", "HTTPConfig", "WebSocketConfig"]
11
16
 
12
17
  try:
13
18
  # https://websocket-client.readthedocs.io/en/latest/faq.html#why-is-this-library-slow
@@ -16,6 +21,7 @@ try:
16
21
  def _skip_utf8_validation(): # type: ignore
17
22
  return False
18
23
  except ImportError:
24
+
19
25
  def _skip_utf8_validation():
20
26
  return True
21
27
 
@@ -26,13 +32,15 @@ class WebSocketConfig:
26
32
  FBClient websocket supports ssl connection, please read the details in https://websocket-client.readthedocs.io/en/latest/faq.html#what-else-can-i-do-with-sslopts
27
33
  """
28
34
 
29
- def __init__(self,
30
- timeout: float = 5.0,
31
- sslopt: Optional[Dict[str, Any]] = None,
32
- proxy_type: Optional[str] = None,
33
- proxy_host: Optional[str] = None,
34
- proxy_port: Optional[str] = None,
35
- proxy_auth: Optional[Tuple[str, str]] = None):
35
+ def __init__(
36
+ self,
37
+ timeout: float = 5.0,
38
+ sslopt: Optional[Dict[str, Any]] = None,
39
+ proxy_type: Optional[str] = None,
40
+ proxy_host: Optional[str] = None,
41
+ proxy_port: Optional[str] = None,
42
+ proxy_auth: Optional[Tuple[str, str]] = None,
43
+ ):
36
44
  # a timeout is triggered if no connection response is received from the server after the timeout interval
37
45
  self.__timeout = 5.0 if timeout is None or timeout <= 0 else min(timeout, 10.0)
38
46
  self.__sslopt = sslopt
@@ -71,18 +79,23 @@ class WebSocketConfig:
71
79
 
72
80
 
73
81
  class HTTPConfig:
74
-
75
- def __init__(self,
76
- connect_timeout: float = 5.0,
77
- read_timeout: float = 10.0,
78
- http_proxy: Optional[str] = None,
79
- http_proxy_auth: Optional[Tuple[str, str]] = None,
80
- ca_certs: Optional[str] = None,
81
- cert_file: Optional[str] = None,
82
- disable_ssl_verification: bool = False):
83
-
84
- self.__connect_timeout = 5.0 if connect_timeout is None or connect_timeout <= 0 else connect_timeout
85
- self.__read_timeout = 10.0 if read_timeout is None or read_timeout <= 0 else read_timeout
82
+ def __init__(
83
+ self,
84
+ connect_timeout: float = 5.0,
85
+ read_timeout: float = 10.0,
86
+ http_proxy: Optional[str] = None,
87
+ http_proxy_auth: Optional[Tuple[str, str]] = None,
88
+ ca_certs: Optional[str] = None,
89
+ cert_file: Optional[str] = None,
90
+ disable_ssl_verification: bool = False,
91
+ ):
92
+
93
+ self.__connect_timeout = (
94
+ 5.0 if connect_timeout is None or connect_timeout <= 0 else connect_timeout
95
+ )
96
+ self.__read_timeout = (
97
+ 10.0 if read_timeout is None or read_timeout <= 0 else read_timeout
98
+ )
86
99
  self.__http_proxy = http_proxy
87
100
  self.__http_proxy_auth = http_proxy_auth
88
101
  self.__ca_certs = ca_certs
@@ -119,69 +132,95 @@ class HTTPConfig:
119
132
 
120
133
 
121
134
  class Config:
122
-
123
- __STREAMING_PATH = '/streaming'
124
- __EVENTS_PATH = '/api/public/insight/track'
125
-
126
- def __init__(self,
127
- env_secret: str,
128
- event_url: str,
129
- streaming_url: str,
130
- streaming_first_retry_delay: float = 1.0,
131
- events_max_in_queue: int = 10000,
132
- events_flush_interval: float = 1.0,
133
- events_retry_interval: float = 0.1,
134
- events_max_retries: int = 1,
135
- offline: bool = False,
136
- data_storage: Optional[DataStorage] = None,
137
- update_processor_imp: Optional[Callable[['Config', DataUpdateStatusProvider, Event], UpdateProcessor]] = None,
138
- event_processor_imp: Optional[Callable[['Config', Sender], EventProcessor]] = None,
139
- http: Optional[HTTPConfig] = None,
140
- websocket: Optional[WebSocketConfig] = None,
141
- defaults: Optional[dict] = None):
135
+ __STREAMING_PATH = "/streaming"
136
+ __EVENTS_PATH = "/api/public/insight/track"
137
+
138
+ def __init__(
139
+ self,
140
+ env_secret: str,
141
+ event_url: str,
142
+ streaming_url: str,
143
+ streaming_first_retry_delay: float = 1.0,
144
+ events_max_in_queue: int = 10000,
145
+ events_flush_interval: float = 1.0,
146
+ events_retry_interval: float = 0.1,
147
+ events_max_retries: int = 1,
148
+ offline: bool = False,
149
+ data_storage: Optional[DataStorage] = None,
150
+ update_processor_imp: Optional[
151
+ Callable[["Config", DataUpdateStatusProvider, Event], UpdateProcessor]
152
+ ] = None,
153
+ event_processor_imp: Optional[
154
+ Callable[["Config", Sender], EventProcessor]
155
+ ] = None,
156
+ http: Optional[HTTPConfig] = None,
157
+ websocket: Optional[WebSocketConfig] = None,
158
+ defaults: Optional[dict] = None,
159
+ ):
142
160
 
143
161
  self.__env_secret = env_secret
144
- self.__event_url = event_url.rstrip('/')
145
- self.__streaming_url = streaming_url.rstrip('/')
146
- self.__streaming_first_retry_delay = 1.0 if streaming_first_retry_delay is None or streaming_first_retry_delay <= 0 else min(
147
- streaming_first_retry_delay, 60.0)
162
+ self.__event_url = event_url.rstrip("/")
163
+ self.__streaming_url = streaming_url.rstrip("/")
164
+ self.__streaming_first_retry_delay = (
165
+ 1.0
166
+ if streaming_first_retry_delay is None or streaming_first_retry_delay <= 0
167
+ else min(streaming_first_retry_delay, 60.0)
168
+ )
148
169
  self.__offline = offline
149
- self.__data_storage = data_storage if data_storage is not None else InMemoryDataStorage()
170
+ self.__data_storage = (
171
+ data_storage if data_storage is not None else InMemoryDataStorage()
172
+ )
150
173
  self.__event_processor_imp = event_processor_imp
151
174
  self.__update_processor_imp = update_processor_imp
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
153
- self.__events_flush_interval = 1.0 if events_flush_interval is None or events_flush_interval <= 0 else min(
154
- events_flush_interval, 3.0)
155
- self.__events_retry_interval = 0.1 if events_retry_interval is None or events_retry_interval <= 0 else min(
156
- events_retry_interval, 1)
157
- self.__events_max_retries = 1 if events_max_retries is None or events_max_retries <= 0 else min(
158
- events_max_retries, 3)
175
+ self.__events_max_in_queue = (
176
+ 10000
177
+ if events_max_in_queue is None or events_max_in_queue <= 0
178
+ else events_max_in_queue
179
+ )
180
+ self.__events_flush_interval = (
181
+ 1.0
182
+ if events_flush_interval is None or events_flush_interval <= 0
183
+ else min(events_flush_interval, 3.0)
184
+ )
185
+ self.__events_retry_interval = (
186
+ 0.1
187
+ if events_retry_interval is None or events_retry_interval <= 0
188
+ else min(events_retry_interval, 1)
189
+ )
190
+ self.__events_max_retries = (
191
+ 1
192
+ if events_max_retries is None or events_max_retries <= 0
193
+ else min(events_max_retries, 3)
194
+ )
159
195
  # Avoid sharing mutable default configuration objects between SDK
160
196
  # clients created by unrelated applications or tests.
161
197
  self.__http = http if http is not None else HTTPConfig()
162
198
  self.__websocket = websocket if websocket is not None else WebSocketConfig()
163
199
  self.__defaults = deepcopy(defaults) if defaults is not None else {}
164
200
 
165
- def copy_config_in_a_new_env(self, env_secret: str, defaults=None,
166
- data_storage: Optional[DataStorage] = None) -> 'Config':
167
- return Config(env_secret,
168
- event_url=self.__event_url,
169
- streaming_url=self.__streaming_url,
170
- streaming_first_retry_delay=self.__streaming_first_retry_delay,
171
- events_max_in_queue=self.__events_max_in_queue,
172
- events_flush_interval=self.__events_flush_interval,
173
- events_retry_interval=self.__events_retry_interval,
174
- events_max_retries=self.__events_max_retries,
175
- offline=self.__offline,
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,
180
- update_processor_imp=self.__update_processor_imp,
181
- event_processor_imp=self.__event_processor_imp,
182
- http=deepcopy(self.__http),
183
- websocket=deepcopy(self.__websocket),
184
- defaults=defaults if defaults is not None else self.__defaults)
201
+ def copy_config_in_a_new_env(
202
+ self, env_secret: str, defaults=None, data_storage: Optional[DataStorage] = None
203
+ ) -> "Config":
204
+ return Config(
205
+ env_secret,
206
+ event_url=self.__event_url,
207
+ streaming_url=self.__streaming_url,
208
+ streaming_first_retry_delay=self.__streaming_first_retry_delay,
209
+ events_max_in_queue=self.__events_max_in_queue,
210
+ events_flush_interval=self.__events_flush_interval,
211
+ events_retry_interval=self.__events_retry_interval,
212
+ events_max_retries=self.__events_max_retries,
213
+ offline=self.__offline,
214
+ # Environment data must never leak between clients. A
215
+ # caller that intentionally wants a custom store can
216
+ # still provide one explicitly.
217
+ data_storage=data_storage,
218
+ update_processor_imp=self.__update_processor_imp,
219
+ event_processor_imp=self.__event_processor_imp,
220
+ http=deepcopy(self.__http),
221
+ websocket=deepcopy(self.__websocket),
222
+ defaults=defaults if defaults is not None else self.__defaults,
223
+ )
185
224
 
186
225
  def get_default_value(self, key, default=None) -> Any:
187
226
  return self.__defaults.get(key, default)
@@ -244,6 +283,6 @@ class Config:
244
283
 
245
284
  def validate(self):
246
285
  if not is_ascii(self.__env_secret):
247
- raise ValueError('env secret is invalid')
286
+ raise ValueError("env secret is invalid")
248
287
  elif not is_url(self.__streaming_url) or not is_url(self.__event_url):
249
- raise ValueError('streaming or event url is invalid')
288
+ raise ValueError("streaming or event url is invalid")
fbclient/data_storage.py CHANGED
@@ -7,7 +7,6 @@ from fbclient.utils.rwlock import ReadWriteLock
7
7
 
8
8
 
9
9
  class InMemoryDataStorage(DataStorage):
10
-
11
10
  def __init__(self):
12
11
  self.__rw_lock = ReadWriteLock()
13
12
  self.__initialized = False
@@ -20,7 +19,7 @@ class InMemoryDataStorage(DataStorage):
20
19
  self.__rw_lock.read_lock()
21
20
  keyItems = self.__storage.get(kind, {})
22
21
  item = keyItems.get(key, None)
23
- if (item is None) or item['isArchived']:
22
+ if (item is None) or item["isArchived"]:
24
23
  return None
25
24
  return item
26
25
  finally:
@@ -30,11 +29,13 @@ class InMemoryDataStorage(DataStorage):
30
29
  try:
31
30
  self.__rw_lock.read_lock()
32
31
  keyItems = self.__storage.get(kind, {})
33
- return dict((k, v) for k, v in keyItems.items() if not v['isArchived'])
32
+ return dict((k, v) for k, v in keyItems.items() if not v["isArchived"])
34
33
  finally:
35
34
  self.__rw_lock.release_read_lock()
36
35
 
37
- def init(self, all_data: Mapping[Category, Mapping[str, dict]], version: int = 0) -> bool:
36
+ def init(
37
+ self, all_data: Mapping[Category, Mapping[str, dict]], version: int = 0
38
+ ) -> bool:
38
39
  if (not all_data) or not isinstance(version, int) or version < 0:
39
40
  return False
40
41
  snapshot_is_empty = not any(bool(items) for items in all_data.values())
@@ -46,10 +47,11 @@ class InMemoryDataStorage(DataStorage):
46
47
  try:
47
48
  self.__rw_lock.write_lock()
48
49
  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())):
50
+ if (
51
+ version == self.__version == 0
52
+ and snapshot_is_empty
53
+ and not any(bool(items) for items in self.__storage.values())
54
+ ):
53
55
  # Empty environments repeatedly send the same version-zero
54
56
  # full snapshot after reconnecting. Treat it as an accepted
55
57
  # no-op instead of forcing another reconnect.
@@ -65,7 +67,13 @@ class InMemoryDataStorage(DataStorage):
65
67
  self.__rw_lock.release_write_lock()
66
68
 
67
69
  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:
70
+ if (
71
+ (not kind)
72
+ or (not item)
73
+ or (not key)
74
+ or not isinstance(version, int)
75
+ or version <= 0
76
+ ):
69
77
  return False
70
78
  try:
71
79
  self.__rw_lock.write_lock()
@@ -74,7 +82,7 @@ class InMemoryDataStorage(DataStorage):
74
82
  # Patches are versioned per entity. Comparing with the global
75
83
  # latest version would incorrectly discard a different flag or
76
84
  # segment that happens to have the same timestamp.
77
- if v is not None and v.get('timestamp', 0) >= version:
85
+ if v is not None and v.get("timestamp", 0) >= version:
78
86
  return False
79
87
  keyItems[key] = item
80
88
  self.__version = max(self.__version, version)
@@ -105,14 +113,15 @@ class InMemoryDataStorage(DataStorage):
105
113
 
106
114
 
107
115
  class NullDataStorage(DataStorage):
108
-
109
116
  def get(self, kind: Category, key: str) -> Optional[dict]:
110
117
  return None
111
118
 
112
119
  def get_all(self, kind: Category) -> Mapping[str, dict]:
113
120
  return dict()
114
121
 
115
- def init(self, all_data: Mapping[Category, Mapping[str, dict]], version: int = 0) -> bool:
122
+ def init(
123
+ self, all_data: Mapping[Category, Mapping[str, dict]], version: int = 0
124
+ ) -> bool:
116
125
  return True
117
126
 
118
127
  def upsert(self, kind: Category, key: str, item: dict, version: int = 0) -> bool: