kameleoon-client-python 3.22.2__py2.py3-none-any.whl → 3.23.0__py2.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.
@@ -0,0 +1,23 @@
1
+ """Kameleoon Configuration"""
2
+
3
+ from typing import Optional
4
+ from kameleoon.logging.kameleoon_logger import KameleoonLogger
5
+
6
+
7
+ class ConfigUpdateMode:
8
+ """ConfigUpdateMode is the way the SDK receives configuration updates, as set in the configuration."""
9
+
10
+ POLLING = "POLLING"
11
+ STREAMING = "STREAMING"
12
+ # Streaming for server-side SDKs only, this one included
13
+ STREAMING_SERVER_ONLY = "STREAMING_SERVER_ONLY"
14
+
15
+ @staticmethod
16
+ def is_streaming(value: Optional[str]) -> bool:
17
+ """Returns `True` if the given `configUpdateMode` value enables streaming."""
18
+ mode = value.upper() if isinstance(value, str) else None
19
+ if mode in (ConfigUpdateMode.STREAMING, ConfigUpdateMode.STREAMING_SERVER_ONLY):
20
+ return True
21
+ if mode != ConfigUpdateMode.POLLING:
22
+ KameleoonLogger.warning("Unexpected ConfigUpdateMode %s", value)
23
+ return False
@@ -1,6 +1,7 @@
1
1
  """Kameleoon Configuration"""
2
2
 
3
3
  from typing import Any, Dict, Optional
4
+ from kameleoon.configuration.config_update_mode import ConfigUpdateMode
4
5
  from kameleoon.configuration.consent_blocking_behaviour import ConsentBlockingBehaviour
5
6
 
6
7
 
@@ -16,16 +17,16 @@ class Settings:
16
17
  def __init__(self, configuration: Optional[Dict[str, Any]] = None):
17
18
  if configuration is None:
18
19
  configuration = {}
19
- self.__real_time_update: bool = bool(configuration.get("realTimeUpdate"))
20
+ self.__streaming_mode = ConfigUpdateMode.is_streaming(configuration.get("configUpdateMode"))
20
21
  self.__is_consent_required = configuration.get("consentType") == self._CONSENT_TYPE_REQUIRED
21
22
  self.__blocking_behaviour_if_consent_not_given = \
22
23
  ConsentBlockingBehaviour.from_str(configuration.get("consentOptOutBehavior", ""))
23
24
  self.__data_api_domain = configuration.get("dataApiDomain")
24
25
 
25
26
  @property
26
- def real_time_update(self) -> bool:
27
- """Returns streaming mode flag state"""
28
- return self.__real_time_update
27
+ def streaming_mode(self) -> bool:
28
+ """`True` when configuration updates are to be received as streaming events rather than polled."""
29
+ return self.__streaming_mode
29
30
 
30
31
  @property
31
32
  def is_consent_required(self) -> bool:
@@ -44,7 +45,7 @@ class Settings:
44
45
 
45
46
  def __str__(self):
46
47
  return (
47
- f"Settings{{real_time_update:{self.__real_time_update},"
48
+ f"Settings{{streaming_mode:{self.__streaming_mode},"
48
49
  f"is_consent_required:{self.__is_consent_required},"
49
50
  f"blocking_behaviour_if_consent_not_given:{self.__blocking_behaviour_if_consent_not_given},"
50
51
  f"data_api_domain:'{self.__data_api_domain}'}}"
@@ -15,19 +15,30 @@ class SemVersion:
15
15
  def from_string(version_string: str) -> Optional["SemVersion"]:
16
16
  """
17
17
  Parses a version string into a Version object.
18
+ A pre-release (-) or build (+) suffix is ignored (e.g., "1.2.3-beta.1+build" is parsed as "1.2.3").
18
19
 
19
- :param version_string: The version string to parse (e.g., "1", "1.2", "1.2.3")
20
+ :param version_string: The version string to parse (e.g., "1", "1.2", "1.2.3", "1.2.3-beta")
20
21
  :return: Version object or None if parsing failed
21
22
  """
22
23
  versions = [0, 0, 0]
23
- version_parts = version_string.split(".")
24
-
25
- for i in range(min(len(versions), len(version_parts))):
26
- try:
27
- versions[i] = int(version_parts[i])
28
- except ValueError:
29
- KameleoonLogger.error("Invalid version component, index: %s, value: %s", i, version_parts[i])
30
- return None
24
+ index = 0
25
+ has_digits = False
26
+ valid = True
27
+ # Single pass without splitting, stops at pre-release (-) or build (+) suffix
28
+ for char in version_string:
29
+ if "0" <= char <= "9":
30
+ versions[index] = versions[index] * 10 + (ord(char) - 48)
31
+ has_digits = True
32
+ elif char == "." and has_digits and index < 2:
33
+ index += 1
34
+ has_digits = False
35
+ else:
36
+ valid = char in ".-+"
37
+ break
38
+ # Each parsed component must have at least one digit
39
+ if not valid or not has_digits:
40
+ KameleoonLogger.error("Invalid version component, index: %s, version: %s", index, version_string)
41
+ return None
31
42
 
32
43
  return SemVersion(versions[0], versions[1], versions[2])
33
44
 
@@ -1,5 +1,6 @@
1
1
  """Client for Kameleoon"""
2
2
 
3
+ import threading
3
4
  from http.cookies import Morsel
4
5
  from typing import cast, Callable, Optional, Tuple, TypeVar, Union, Any, List, Dict, Iterable
5
6
 
@@ -49,7 +50,8 @@ from kameleoon.network.network_manager_factory import NetworkManagerFactory
49
50
  from kameleoon.network.network_manager_factory_impl import NetworkManagerFactoryImpl
50
51
  from kameleoon.network.sendable import Sendable
51
52
  from kameleoon.network.services.configuration_service import ConfigurationService, FetchedConfiguration
52
- from kameleoon.real_time.real_time_event_service import RealTimeEventService
53
+ from kameleoon.network.streaming.data_file_update_message import DataFileUpdateMessage
54
+ from kameleoon.network.streaming.streaming_service import StreamingService
53
55
  from kameleoon.targeting.targeting_manager import TargetingManager
54
56
  from kameleoon.types.remote_visitor_data_filter import RemoteVisitorDataFilter
55
57
  from kameleoon.types.variation import Variation
@@ -67,6 +69,10 @@ STATUS_ACTIVE = "ACTIVE"
67
69
  FEATURE_STATUS_DEACTIVATED = "DEACTIVATED"
68
70
  # pylint: disable=W0511
69
71
  HYBRID_EXPIRATION_TIME = 5000 # TODO: hybrid manager timeout is less than call timeout; affects on sync-monothread mode
72
+ # Period of the polls made while the settings enable streaming but it is not running, so that the
73
+ # streaming is retried soon (each successful poll switches back to it), unless the regular polls are
74
+ # even more frequent.
75
+ STREAMING_RETRY_INTERVAL_SECONDS = 60
70
76
 
71
77
  T = TypeVar("T", bound=EventHandler)
72
78
 
@@ -119,8 +125,10 @@ class KameleoonClient:
119
125
  self.site_code = site_code
120
126
  self._config = config
121
127
  KameleoonLogger.set_logger(DefaultLogger(config.logger))
122
- self._real_time_event_service: Optional[RealTimeEventService] = None
128
+ self._streaming_service: Optional[StreamingService] = None
123
129
  self._update_configuration_handler: Optional[Callable[[], None]] = None
130
+ self._configuration_update_lock = threading.Lock()
131
+ self._apply_configuration_lock = threading.Lock()
124
132
  self._async_executor = AsyncExecutor()
125
133
  self.__add_fetch_configuration_job()
126
134
  self._threading_readiness = ThreadingClientReadiness(site_code, config.environment)
@@ -167,9 +175,8 @@ class KameleoonClient:
167
175
  return
168
176
  self._disposed = True
169
177
  KameleoonLogger.info("CALL: KameleoonClient.__del__()")
170
- if self._real_time_event_service is not None:
171
- self._real_time_event_service.close()
172
- self._real_time_event_service = None
178
+ with self._configuration_update_lock:
179
+ self._stop_streaming_service()
173
180
  self._async_executor.scheduler.stop()
174
181
  try:
175
182
  self._async_executor.run_coro(self._network_manager.net_provider.close(), "net_provider.close")
@@ -1540,27 +1547,51 @@ class KameleoonClient:
1540
1547
  fetched_configuration.last_modified,
1541
1548
  fetched_configuration.configuration,
1542
1549
  )
1543
- self._data_manager.data_file = data_file
1544
- self._network_manager.url_provider.apply_data_api_domain(data_file.settings.data_api_domain)
1545
1550
  source = (
1546
1551
  DataFileUpdateEvent.Source.STREAMING
1547
1552
  if time_stamp is not None
1548
1553
  else DataFileUpdateEvent.Source.POLLING
1549
1554
  )
1550
- self._event_manager.fire_data_file_update(DataFileUpdateEvent(source, data_file.date_modified))
1551
- if source == DataFileUpdateEvent.Source.STREAMING:
1552
- self._call_deprecated_update_handler()
1555
+ self._apply_new_configuration(data_file, source)
1553
1556
  success = True
1554
1557
  except Exception as ex:
1555
1558
  cause = ex
1556
1559
  KameleoonLogger.error("Error occurred during configuration fetching: %s", ex)
1557
1560
  self._settle_readiness(success, cause)
1558
- self._manage_configuration_update(success and self._data_manager.data_file.settings.real_time_update)
1561
+ self._manage_configuration_update(success and self._data_manager.data_file.settings.streaming_mode)
1559
1562
  KameleoonLogger.debug(
1560
1563
  "RETURN: KameleoonClient._fetch_configuration(time_stamp: %s) -> (success: %s)", time_stamp, success
1561
1564
  )
1562
1565
  return success
1563
1566
 
1567
+ def _apply_new_configuration(self, data_file: DataFile, source: DataFileUpdateEvent.Source) -> None:
1568
+ """
1569
+ The data file is only ever replaced by one at least as new: fetches may run concurrently (a
1570
+ streaming event can arrive while another fetch is in flight) and finish out of order, and a stale
1571
+ reply must not roll the configuration back. The comparison and the replacement are atomic, and
1572
+ the update event fires under the same lock, so handlers see the data files in the applied order.
1573
+ """
1574
+ KameleoonLogger.debug(
1575
+ "CALL: KameleoonClient._apply_new_configuration(data_file: %s, source: %s)", data_file, source
1576
+ )
1577
+ with self._apply_configuration_lock:
1578
+ current_date_modified = self._data_manager.data_file.date_modified
1579
+ if data_file.date_modified < current_date_modified:
1580
+ KameleoonLogger.info(
1581
+ "Fetched configuration (dateModified: %s) is older than the current one (dateModified: %s), "
1582
+ "skipping",
1583
+ data_file.date_modified, current_date_modified,
1584
+ )
1585
+ else:
1586
+ self._data_manager.data_file = data_file
1587
+ self._network_manager.url_provider.apply_data_api_domain(data_file.settings.data_api_domain)
1588
+ self._event_manager.fire_data_file_update(DataFileUpdateEvent(source, data_file.date_modified))
1589
+ if source == DataFileUpdateEvent.Source.STREAMING:
1590
+ self._call_deprecated_update_handler()
1591
+ KameleoonLogger.debug(
1592
+ "RETURN: KameleoonClient._apply_new_configuration(data_file: %s, source: %s)", data_file, source
1593
+ )
1594
+
1564
1595
  def _settle_readiness(self, success: bool, cause: Optional[Exception]) -> None:
1565
1596
  # A successful fetch marks the SDK ready, a failed one reports the failure so
1566
1597
  # `wait_init` fails fast instead of sleeping out its timeout. A failure never
@@ -1588,31 +1619,72 @@ class KameleoonClient:
1588
1619
  KameleoonLogger.warning("Update configuration handler failed: %s", ex)
1589
1620
  KameleoonLogger.debug("RETURN: KameleoonClient._call_deprecated_update_handler()")
1590
1621
 
1591
- def _manage_configuration_update(self, is_real_time_update: bool):
1622
+ def _manage_configuration_update(self, streaming_mode: bool) -> None:
1623
+ """
1624
+ A disposed client must not (re)create the streaming service: a fetch which was in
1625
+ flight when `__del__` ran would otherwise resurrect the SSE thread. `_disposed` is
1626
+ set before `__del__` closes the service, so a fetch completing after that point can
1627
+ only stop things. The polling job keeps running and is gated by the streaming service
1628
+ (see `_fetch_configuration_job`), so a failed start never leaves the SDK without updates.
1629
+ Whenever the current settings enable streaming but it is not running (a failed fetch,
1630
+ a failed start), `_retry_streaming_job` polls soon, so that streaming is retried without
1631
+ waiting a full refresh interval.
1632
+ """
1633
+ KameleoonLogger.debug("CALL: KameleoonClient._manage_configuration_update(streaming_mode: %s)", streaming_mode)
1634
+ with self._configuration_update_lock:
1635
+ if self._disposed or not (streaming_mode and self._start_streaming_service()):
1636
+ self._stop_streaming_service()
1592
1637
  KameleoonLogger.debug(
1593
- "CALL: KameleoonClient._manage_configuration_update(is_real_time_update: %s)", is_real_time_update
1594
- )
1595
- # A disposed client must not (re)create the service: a fetch which was in
1596
- # flight when `__del__` ran would otherwise resurrect the SSE thread.
1597
- # `_disposed` is set before `__del__` closes the service, so a fetch
1598
- # completing after that point always takes the closing branch.
1599
- if is_real_time_update and not self._disposed:
1600
- if self._real_time_event_service is None:
1601
- url = self._network_manager.url_provider.make_real_time_url()
1602
- self._real_time_event_service = RealTimeEventService(
1603
- url,
1604
- lambda real_time_event: self._async_executor.run_coro(
1605
- self._fetch_configuration(real_time_event.time_stamp), "fetch_configuration"
1606
- ),
1607
- )
1608
- else:
1609
- if self._real_time_event_service is not None:
1610
- self._real_time_event_service.close()
1611
- self._real_time_event_service = None
1612
- KameleoonLogger.debug(
1613
- "RETURN: KameleoonClient._manage_configuration_update(is_real_time_update: %s)", is_real_time_update
1638
+ "RETURN: KameleoonClient._manage_configuration_update(streaming_mode: %s)", streaming_mode
1614
1639
  )
1615
1640
 
1641
+ def _start_streaming_service(self) -> bool:
1642
+ """
1643
+ Returns whether the service runs. A service which gave up reconnecting is replaced right away; its
1644
+ pending fallback notification is then ignored, see `_on_streaming_unavailable`.
1645
+ """
1646
+ if self._streaming_service is not None and not self._streaming_service.closed:
1647
+ return True
1648
+ try:
1649
+ url = self._network_manager.url_provider.make_real_time_url()
1650
+ self._streaming_service = StreamingService(
1651
+ url, self._on_data_file_update_message, streaming_unavailable_handler=self._on_streaming_unavailable
1652
+ )
1653
+ return True
1654
+ except Exception as ex: # pylint: disable=W0703 # e.g. `RuntimeError` when no thread can be created
1655
+ KameleoonLogger.error("Failed to start the streaming service: %s; switching to polling", ex)
1656
+ return False
1657
+
1658
+ def _stop_streaming_service(self) -> None:
1659
+ if self._streaming_service is not None:
1660
+ self._streaming_service.close()
1661
+ self._streaming_service = None
1662
+
1663
+ def _on_data_file_update_message(self, message: DataFileUpdateMessage) -> None:
1664
+ """
1665
+ Every event (a configuration update, or the connection open event sent on every (re)connection)
1666
+ carries the timestamp of the current configuration, so the SDK fetches it only when it is newer
1667
+ than the one it holds.
1668
+ """
1669
+ time_stamp = message.time_stamp
1670
+ date_modified = self._data_manager.data_file.date_modified
1671
+ if time_stamp <= date_modified:
1672
+ KameleoonLogger.debug(
1673
+ "Configuration is up to date (ts: %s, dateModified: %s), skipping update", time_stamp, date_modified
1674
+ )
1675
+ return
1676
+ self._async_executor.run_coro(self._fetch_configuration(time_stamp), "fetch_configuration")
1677
+
1678
+ def _on_streaming_unavailable(self, service: StreamingService) -> None:
1679
+ """
1680
+ Called by the service which gave up reconnecting. A fetch completing meanwhile may have replaced
1681
+ the service already, in which case there is nothing to fall back from.
1682
+ """
1683
+ with self._configuration_update_lock:
1684
+ if self._disposed or service is not self._streaming_service:
1685
+ return
1686
+ self._stop_streaming_service()
1687
+
1616
1688
  def get_engine_tracking_code(self, visitor_code: str) -> str:
1617
1689
  """
1618
1690
  The `get_engine_tracking_code` returns the JavaScript code to be inserted in your page
@@ -1683,9 +1755,26 @@ class KameleoonClient:
1683
1755
  self._config.refresh_interval_second,
1684
1756
  self._fetch_configuration_job,
1685
1757
  )
1758
+ # With a refresh interval this short the regular polls retry streaming soon enough themselves
1759
+ if self._config.refresh_interval_second > STREAMING_RETRY_INTERVAL_SECONDS:
1760
+ self._async_executor.scheduler.schedule_job(
1761
+ "Client._retry_streaming_job",
1762
+ STREAMING_RETRY_INTERVAL_SECONDS,
1763
+ self._retry_streaming_job,
1764
+ )
1686
1765
 
1687
1766
  async def _fetch_configuration_job(self) -> None:
1688
- if self._real_time_event_service is None:
1767
+ # The job polls only while the streaming service does not run; the scheduler awaits the fetch,
1768
+ # so a slow poll delays the next tick instead of overlapping with it.
1769
+ if self._streaming_service is None:
1770
+ KameleoonLogger.info("Scheduled job to fetch configuration is started.")
1771
+ await self._fetch_configuration()
1772
+
1773
+ async def _retry_streaming_job(self) -> None:
1774
+ # The settings enable streaming but it is not running (it gave up reconnecting, could not be
1775
+ # started, or a fetch failed): poll, since each successful poll switches back to streaming.
1776
+ if self._streaming_service is None and self._data_manager.data_file.settings.streaming_mode:
1777
+ KameleoonLogger.info("Scheduled job to retry streaming is started.")
1689
1778
  await self._fetch_configuration()
1690
1779
 
1691
1780
  async def _obtain_configuration(self, time_stamp: Optional[int]) -> Optional[FetchedConfiguration]:
@@ -6,7 +6,6 @@ from kameleoon.network.uri_helper import encode_uri
6
6
 
7
7
  class QueryParams(str, Enum):
8
8
  """Enum representing various query parameter keys used in requests."""
9
- BODY_UA = "bodyUa"
10
9
  BROWSER_INDEX = "browserIndex"
11
10
  BROWSER_VERSION = "browserVersion"
12
11
  CBS = "cbs"
@@ -24,7 +24,7 @@ class DataServiceImpl(DataService, ServiceImpl):
24
24
  if timeout is None:
25
25
  timeout = self.network_manager.call_timeout
26
26
  url = self.network_manager.url_provider.make_tracking_url()
27
- request = Request(HttpMethod.POST, url, timeout, body=lines, headers={"Content-Type": "*/*"})
27
+ request = Request(HttpMethod.POST, url, timeout, body=lines, headers={"Content-Type": "text/plain"})
28
28
  response = self._make_call(
29
29
  RequestType.TRACKING, request, True,
30
30
  self.NUMBER_OF_RECONNECTION_ON_FAILURE_UNCRITICAL, self._TRACKING_CALL_RETRY_DELAY
@@ -0,0 +1 @@
1
+ """Kameleoon Streaming"""
@@ -0,0 +1,26 @@
1
+ """Kameleoon Data File Update Message"""
2
+ from typing import Any, Dict
3
+
4
+
5
+ class DataFileUpdateMessage:
6
+ """
7
+ DataFileUpdateMessage contains information about timestamp when configuration was updated.
8
+ Timestamp parameter is used to fetch the latest configuration.
9
+ """
10
+
11
+ def __init__(self, event_dict: Dict[str, Any]) -> None:
12
+ """
13
+ Gets the new time stamp from a JSON message.
14
+
15
+ :param event_dict: Dict of SSE message data.
16
+ """
17
+ # Both hold milliseconds; `ts` is only read while the server still sends events without `tsMs`
18
+ time_stamp = event_dict.get("tsMs")
19
+ if time_stamp is None:
20
+ time_stamp = event_dict.get("ts")
21
+ self.__time_stamp: Any = time_stamp
22
+
23
+ @property
24
+ def time_stamp(self) -> Any:
25
+ """Returns the timestamp of the configuration the message is about; validated by the receiver."""
26
+ return self.__time_stamp
@@ -0,0 +1,201 @@
1
+ """Kameleoon Streaming Service"""
2
+ import json
3
+ import threading
4
+ from typing import Any, Callable, Dict, Optional
5
+
6
+ import requests
7
+ import sseclient
8
+
9
+ from kameleoon.helpers.multi_threading import run_in_thread
10
+ from kameleoon.logging.kameleoon_logger import KameleoonLogger
11
+ from kameleoon.network.streaming.data_file_update_message import DataFileUpdateMessage
12
+
13
+ KAMELEOON_STREAMING_THREAD = "KameleoonStreamingThread"
14
+ KAMELEOON_STREAMING_CLOSE_THREAD = "KameleoonStreamingCloseThread"
15
+ # The server pushed a new configuration.
16
+ CONFIGURATION_UPDATE_EVENT = "configuration-update-event"
17
+ # Sent by the server on every (re)connection with the timestamp of the current
18
+ # configuration, so that an update published while the SDK was disconnected is not missed.
19
+ CONNECTION_OPEN_EVENT = "connection-open-event"
20
+ STREAMING_EVENT_TYPES = (CONFIGURATION_UPDATE_EVENT, CONNECTION_OPEN_EVENT)
21
+
22
+
23
+ class StreamingService:
24
+ """
25
+ StreamingService is used for fetching updates of configuration
26
+ (experiments and feature flags) through the streaming (SSE) connection.
27
+ """
28
+
29
+ # Delay before re-establishing the SSE connection after a failure or a server-side close.
30
+ RECONNECT_DELAY_SECONDS = 10.0
31
+ # Reconnections attempted after a failed connection before giving up.
32
+ MAX_RETRIES = 1
33
+ # Detects stalled and half-dead connections (e.g. silently dropped by a NAT or load balancer), which
34
+ # would otherwise hang forever. Must stay above the server's keep-alive interval (180 s,
35
+ # `server.sse.keepalive.writer-idle` in ms-client-configs), so don't change it without the agreement
36
+ # of the ms-client-configs team.
37
+ READ_TIMEOUT_SECONDS = 6 * 60.0
38
+ # Upper bound for establishing the connection, so that an unreachable server is reported as a failure
39
+ # promptly instead of after the (long) read timeout.
40
+ CONNECT_TIMEOUT_SECONDS = 10.0
41
+ _CLOSED_BY_SERVER = "was closed by server"
42
+
43
+ def __init__( # pylint: disable=R0913
44
+ self,
45
+ url: str,
46
+ data_file_update_handler: Callable[[DataFileUpdateMessage], Any],
47
+ reconnect_delay: float = RECONNECT_DELAY_SECONDS,
48
+ streaming_unavailable_handler: Optional[Callable[["StreamingService"], Any]] = None,
49
+ read_timeout: float = READ_TIMEOUT_SECONDS,
50
+ ) -> None:
51
+ """
52
+ :param url: URL of the SSE event stream.
53
+ :param data_file_update_handler: Handler which is synchronously called (on the streaming thread)
54
+ for each received `DataFileUpdateMessage`.
55
+ :param reconnect_delay: Delay in seconds before a reconnect attempt.
56
+ :param streaming_unavailable_handler: Handler which is called once `MAX_RETRIES + 1` connections
57
+ in a row have ended without delivering an event; the service is closed by then.
58
+ :param read_timeout: Seconds of silence after which the connection is considered stalled and failed.
59
+ """
60
+ self.url = url
61
+ self.headers = {
62
+ "Accept": "text/event-stream",
63
+ "Cache-Control": "no-cache",
64
+ "Connection": "Keep-Alive",
65
+ }
66
+ self._data_file_update_handler = data_file_update_handler
67
+ self._streaming_unavailable_handler = streaming_unavailable_handler
68
+ self._reconnect_delay = reconnect_delay
69
+ self._read_timeout = read_timeout
70
+ self._closed = threading.Event() # also interrupts the reconnect delay
71
+ self._consecutive_disconnects = 0
72
+ self._response: Optional[Any] = None
73
+ self._response_lock = threading.Lock()
74
+ self._thread = run_in_thread(self._run_sse_client, KAMELEOON_STREAMING_THREAD)
75
+
76
+ @property
77
+ def closed(self) -> bool:
78
+ """`True` once the service has been closed, or has given up reconnecting."""
79
+ return self._closed.is_set()
80
+
81
+ def close(self) -> None:
82
+ """Closes the connection to the server, without waiting for the connection to be released."""
83
+ if self._closed.is_set():
84
+ return
85
+ KameleoonLogger.info("Streaming service is shutting down")
86
+ self._closed.set()
87
+ # Closing a response blocks while the streaming thread is reading from it, until data arrives
88
+ # or the read times out, so it must not run on the caller's thread (e.g. the SDK's event loop).
89
+ try:
90
+ run_in_thread(self._close_response, KAMELEOON_STREAMING_CLOSE_THREAD)
91
+ except Exception as ex: # pylint: disable=W0703 # e.g. no thread can be created at shutdown
92
+ # The streaming thread releases the connection itself once its read returns
93
+ KameleoonLogger.debug("SSE connection: %s is left to be closed by the streaming thread: %s", self.url, ex)
94
+
95
+ # Every end of a connection is followed by a delayed reconnection, whether it is a routine close
96
+ # by the server (which recycles connections periodically) or a failure (error response, network
97
+ # error, stalled stream). Every received event resets the count of disconnects, and the server
98
+ # sends the connection open event on every connection, so a working stream keeps the count low.
99
+ # Once more than `MAX_RETRIES` connections in a row end without an event, the service gives up
100
+ # and reports it, so that the SDK can fall back to polling instead of retrying forever.
101
+ def _run_sse_client(self) -> None:
102
+ while True:
103
+ failure_reason = self._run_sse_connection()
104
+ if self._closed.is_set():
105
+ return
106
+ self._consecutive_disconnects += 1
107
+ if self._consecutive_disconnects > self.MAX_RETRIES:
108
+ self._give_up(failure_reason)
109
+ return
110
+ self._log_reconnection(failure_reason)
111
+ if self._closed.wait(self._reconnect_delay):
112
+ return # closed during the delay
113
+
114
+ def _run_sse_connection(self) -> Optional[str]:
115
+ """
116
+ Runs one SSE connection until it ends. Returns the failure reason, or `None` when the
117
+ established stream was closed (by the server or by the SDK).
118
+ """
119
+ KameleoonLogger.debug("Create SSE client")
120
+ try:
121
+ response = self._with_requests(self.url, self.headers, self._read_timeout)
122
+ self._response = response
123
+ if response.status_code != 200:
124
+ return f"failed with status code {response.status_code}"
125
+ KameleoonLogger.info("Established a new SSE connection with: %s", self.url)
126
+ client = sseclient.SSEClient(response)
127
+ for message in client.events():
128
+ if self._closed.is_set():
129
+ break
130
+ self._consecutive_disconnects = 0
131
+ self._handle_message(message)
132
+ return None
133
+ except Exception as ex: # pylint: disable=W0703
134
+ if self._closed.is_set():
135
+ KameleoonLogger.debug("SSE connection: %s was closed by SDK: %s", self.url, ex)
136
+ return None
137
+ return f"failed: {ex}"
138
+ finally:
139
+ self._close_response()
140
+
141
+ def _close_response(self) -> None:
142
+ with self._response_lock:
143
+ response, self._response = self._response, None
144
+ if response is not None:
145
+ response.close()
146
+
147
+ def _handle_message(self, message: Any) -> None:
148
+ KameleoonLogger.debug("Got SSE event: %s", message.event)
149
+ if message.event not in STREAMING_EVENT_TYPES:
150
+ return
151
+ try:
152
+ update = DataFileUpdateMessage(json.loads(message.data))
153
+ if not self._is_timestamp(update.time_stamp):
154
+ raise ValueError("timestamp is missing")
155
+ except Exception as ex: # pylint: disable=W0703
156
+ KameleoonLogger.error("Received event from SSE server with wrong format: %s; %s", message.data, ex)
157
+ return
158
+ try:
159
+ self._data_file_update_handler(update)
160
+ except Exception as ex: # pylint: disable=W0703
161
+ # a handler failure must not drop the connection
162
+ KameleoonLogger.error("Data file update handler failed: %s", ex)
163
+
164
+ @staticmethod
165
+ def _is_timestamp(value: Any) -> bool:
166
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
167
+
168
+ def _log_reconnection(self, failure_reason: Optional[str]) -> None:
169
+ if failure_reason is not None:
170
+ KameleoonLogger.error(
171
+ self._connection_message(f"{failure_reason}; reconnecting in {self._reconnect_delay} s")
172
+ )
173
+ else:
174
+ KameleoonLogger.info(
175
+ self._connection_message(f"{self._CLOSED_BY_SERVER}; reconnecting in {self._reconnect_delay} s")
176
+ )
177
+
178
+ def _give_up(self, failure_reason: Optional[str]) -> None:
179
+ self._closed.set()
180
+ KameleoonLogger.error(self._connection_message(
181
+ f"{failure_reason or self._CLOSED_BY_SERVER}; streaming is unavailable after "
182
+ f"{self.MAX_RETRIES + 1} consecutive disconnects, switching to polling"
183
+ ))
184
+ if self._streaming_unavailable_handler is None:
185
+ return
186
+ try:
187
+ self._streaming_unavailable_handler(self)
188
+ except Exception as ex: # pylint: disable=W0703
189
+ KameleoonLogger.error("Streaming unavailable handler failed: %s", ex)
190
+
191
+ def _connection_message(self, suffix: str) -> str:
192
+ # Formatted here rather than through the logger's `%s`, which would quote the suffix
193
+ return f"SSE connection: '{self.url}' {suffix}"
194
+
195
+ @staticmethod
196
+ def _with_requests(url: str, headers: Dict[str, Any], read_timeout: float) -> Any:
197
+ """Get a streaming response for the given event feed using requests."""
198
+ # The read timeout applies to every read: the stream is silent between events, but the server
199
+ # sends keep-alives more often than the timeout.
200
+ timeout = (StreamingService.CONNECT_TIMEOUT_SECONDS, read_timeout)
201
+ return requests.get(url, stream=True, headers=headers, timeout=timeout)
@@ -34,12 +34,7 @@ class UrlProvider:
34
34
  self.site_code = site_code
35
35
  self._data_api_domain = self.DEFAULT_DATA_API_DOMAIN # if remove W0201 error (pylint)
36
36
  self.__setup_domains(network_domain)
37
- query_builder = self.__make_sdk_sitecode_query_builder()
38
- self.__sdk_sitecode_query_base = str(query_builder)
39
- query_builder.append(
40
- QueryParam(QueryParams.BODY_UA, "true"),
41
- )
42
- self.__tracking_query_base = str(query_builder)
37
+ self.__sdk_sitecode_query_base = str(self.__make_sdk_sitecode_query_builder())
43
38
 
44
39
  def __make_sdk_sitecode_query_builder(self) -> QueryBuilder:
45
40
  # fmt: off
@@ -77,7 +72,9 @@ class UrlProvider:
77
72
 
78
73
  def make_tracking_url(self) -> str:
79
74
  """Constructs the URL for tracking events."""
80
- return self._DATA_API_URL_FORMAT.format(self._data_api_domain, self._TRACKING_PATH, self.__tracking_query_base)
75
+ return self._DATA_API_URL_FORMAT.format(
76
+ self._data_api_domain, self._TRACKING_PATH, self.__sdk_sitecode_query_base
77
+ )
81
78
 
82
79
  def make_visitor_data_get_url(
83
80
  self, visitor_code: str, data_filter: RemoteVisitorDataFilter, is_unique_identifier: bool = False
@@ -85,7 +82,6 @@ class UrlProvider:
85
82
  """Constructs the URL for fetching visitor data with specified filters."""
86
83
  # fmt: off
87
84
  query_builder = QueryBuilder(
88
- QueryParam(QueryParams.SITE_CODE, self.site_code, encoding_required=False),
89
85
  QueryParam(QueryParams.MAPPING_VALUE if is_unique_identifier else QueryParams.VISITOR_CODE, visitor_code),
90
86
  QueryParam(QueryParams.MAX_NUMBER_PREVIOUS_VISITS, str(data_filter.previous_visit_amount)),
91
87
  QueryParam(QueryParams.VERSION, "0", encoding_required=False),
@@ -101,7 +97,8 @@ class UrlProvider:
101
97
  self.__add_flag_param_if_required(query_builder, QueryParams.PAGE, data_filter.page_views)
102
98
  self.__add_flag_param_if_required(query_builder, QueryParams.PERSONALIZATION, data_filter.personalization)
103
99
  self.__add_flag_param_if_required(query_builder, QueryParams.CBS, data_filter.cbs)
104
- return self._DATA_API_URL_FORMAT.format(self._data_api_domain, self._VISITOR_DATA_PATH, str(query_builder))
100
+ query = f"{self.__sdk_sitecode_query_base}&{query_builder}"
101
+ return self._DATA_API_URL_FORMAT.format(self._data_api_domain, self._VISITOR_DATA_PATH, query)
105
102
 
106
103
  @staticmethod
107
104
  def __add_flag_param_if_required(query_builder: QueryBuilder, param_name: QueryParams, state: bool) -> None:
@@ -110,13 +107,8 @@ class UrlProvider:
110
107
 
111
108
  def make_api_data_get_request_url(self, key: str) -> str:
112
109
  """Constructs the URL for fetching remote data from the Data API."""
113
- # fmt: off
114
- query_builder = QueryBuilder(
115
- QueryParam(QueryParams.SITE_CODE, self.site_code),
116
- QueryParam(QueryParams.KEY, key),
117
- )
118
- # fmt: on
119
- return self._DATA_API_URL_FORMAT.format(self._data_api_domain, self._GET_DATA_PATH, str(query_builder))
110
+ query = f"{self.__sdk_sitecode_query_base}&{QueryParam(QueryParams.KEY, key)}"
111
+ return self._DATA_API_URL_FORMAT.format(self._data_api_domain, self._GET_DATA_PATH, query)
120
112
 
121
113
  def make_configuration_url(self, environment: Optional[str] = None, time_stamp: Optional[int] = None) -> str:
122
114
  """Constructs the URL for fetching configuration data with optional query parameters."""
kameleoon/sdk_version.py CHANGED
@@ -1,6 +1,6 @@
1
1
  """Kameleoon SDK version"""
2
2
 
3
- version_info = (3, 22, 2)
3
+ version_info = (3, 23, 0)
4
4
  __version__ = ".".join(str(v) for v in version_info) # uses in scripts
5
5
 
6
6
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: kameleoon-client-python
3
- Version: 3.22.2
3
+ Version: 3.23.0
4
4
  Summary: Kameleoon Client Python Software Development Kit.
5
5
  Home-page: https://developers.kameleoon.com/python-sdk.html
6
6
  Author: Kameleoon
@@ -20,27 +20,27 @@ Requires-Dist: requests<3.0.0,>=2.25
20
20
  Requires-Dist: sseclient-py<1.9.0,>=1.7.0
21
21
  Requires-Dist: aiohttp<4.0.0,>=3.8.0
22
22
  Provides-Extra: test
23
- Requires-Dist: sseclient-py<1.9.0,>=1.7.0; extra == "test"
23
+ Requires-Dist: types-requests==2.25.0; extra == "test"
24
+ Requires-Dist: mypy==0.991; extra == "test"
25
+ Requires-Dist: Django==4.2.*; extra == "test"
24
26
  Requires-Dist: pytest-cov==2.12.1; extra == "test"
25
- Requires-Dist: pytest-django==4.5.2; extra == "test"
26
- Requires-Dist: pylint==2.12.*; extra == "test"
27
- Requires-Dist: wheel==0.36.2; extra == "test"
28
27
  Requires-Dist: types-PyYAML==5.4.3; extra == "test"
29
- Requires-Dist: types-requests==2.25.0; extra == "test"
30
- Requires-Dist: types-python-dateutil==2.8.2; extra == "test"
31
28
  Requires-Dist: aiohttp<4.0.0,>=3.8.0; extra == "test"
32
- Requires-Dist: Django==4.2.*; extra == "test"
29
+ Requires-Dist: pytest-ordering==0.6; extra == "test"
30
+ Requires-Dist: pytest-pythonpath==0.7.3; extra == "test"
33
31
  Requires-Dist: aioresponses==0.7.*; extra == "test"
34
- Requires-Dist: freezegun==1.1.0; extra == "test"
35
- Requires-Dist: pytest-asyncio==0.21.*; extra == "test"
36
32
  Requires-Dist: Werkzeug==2.0.1; extra == "test"
37
- Requires-Dist: mypy==0.991; extra == "test"
33
+ Requires-Dist: requests<3.0.0,>=2.25; extra == "test"
34
+ Requires-Dist: sseclient-py<1.9.0,>=1.7.0; extra == "test"
35
+ Requires-Dist: pytest-asyncio==0.21.*; extra == "test"
36
+ Requires-Dist: pylint==2.12.*; extra == "test"
37
+ Requires-Dist: flake8==4.0.1; extra == "test"
38
38
  Requires-Dist: twine==3.4.1; extra == "test"
39
39
  Requires-Dist: pyyaml<6.1.0,>=5.4.0; extra == "test"
40
- Requires-Dist: flake8==4.0.1; extra == "test"
41
- Requires-Dist: pytest-pythonpath==0.7.3; extra == "test"
42
- Requires-Dist: requests<3.0.0,>=2.25; extra == "test"
43
- Requires-Dist: pytest-ordering==0.6; extra == "test"
40
+ Requires-Dist: freezegun==1.1.0; extra == "test"
41
+ Requires-Dist: types-python-dateutil==2.8.2; extra == "test"
42
+ Requires-Dist: wheel==0.36.2; extra == "test"
43
+ Requires-Dist: pytest-django==4.5.2; extra == "test"
44
44
  Dynamic: author
45
45
  Dynamic: author-email
46
46
  Dynamic: classifier
@@ -1,15 +1,16 @@
1
1
  kameleoon/__init__.py,sha256=G3jQ-8_U7nuT5elasWS9kyBSr_DBAOc7K_ksKasIEOY,349
2
2
  kameleoon/defaults.py,sha256=lA67znAePfFapxATCy5X-E2naHAWbQFt3rgVA5qkGMo,153
3
3
  kameleoon/exceptions.py,sha256=l-ImW0NQUg-0o_tBYCsdsne179jZx8KPvmiAN_Y_pTU,3458
4
- kameleoon/kameleoon_client.py,sha256=Gg1NTcI0JUmYKPFYDRhJSG_Z2fxKaO8ECZ7R0yRgffA,96630
4
+ kameleoon/kameleoon_client.py,sha256=r9EP8wf1TRpbXOfYMKbwJes0dhrtx4IUtD9efpXV1MI,101766
5
5
  kameleoon/kameleoon_client_config.py,sha256=DJm--TtaTPc_09q3uv8XjHrX_q7C-sh0tf65lL2TxCw,11181
6
6
  kameleoon/kameleoon_client_factory.py,sha256=9_VXYnfZ0A5GNY6Y3j9aCfUV2uc-_-SQhslU3uUoeSQ,3228
7
7
  kameleoon/middleware.py,sha256=gwbt2YK0D6Uvmm3M7WqkTdwUIZEA85Use39Tt3oVeus,1584
8
- kameleoon/sdk_version.py,sha256=7ZsKymIDnKmWCSJ-FIVDMmzAxUjdAcZfrkndtWxSG08,289
8
+ kameleoon/sdk_version.py,sha256=TQ8ai_liepIaBtno2IrsC_N-vyjpttr-ptNzQxg3VKg,289
9
9
  kameleoon/client_readiness/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
10
  kameleoon/client_readiness/async_readiness.py,sha256=NTzreGNJ9jOdpia0gAnkOwjn14Vu6m53l7QC_eJQ5ig,1569
11
11
  kameleoon/client_readiness/threading_readiness.py,sha256=bpld4cxl4H6ZIvJxomU_Qmhii2ru7fRK1yzYp2SQhTw,5794
12
12
  kameleoon/configuration/__init__.py,sha256=soJL7ddciHfFr_BkbdrQ6B3buvIw8o06mcxaUGBGnAc,162
13
+ kameleoon/configuration/config_update_mode.py,sha256=0F88CKCItBL2-LyED9IKqCNxEdbmtCHP2N0Wd_K-iWU,899
13
14
  kameleoon/configuration/consent_blocking_behaviour.py,sha256=l6h05VkbEpI_1tVKsFh8bfY0FrNKYEaAr-R_gIDfG54,523
14
15
  kameleoon/configuration/custom_data_info.py,sha256=RGqK5spwOu0HWEcIBBZWBvDck7IjG7ENTelnbtCFxlE,2718
15
16
  kameleoon/configuration/data_file.py,sha256=Ke1qNTgvzWDRqlnG5HhqJeFycZ4_a584fXvGQ5J4o90,10735
@@ -18,7 +19,7 @@ kameleoon/configuration/feature_flag.py,sha256=EK7yma_0KiRUcW2SLuP4Gc75_VXDNluhY
18
19
  kameleoon/configuration/me_group.py,sha256=Guikw-zPqmdy4X0gXi5D0ZqeC_ral3WDQIpfqbVHgzA,806
19
20
  kameleoon/configuration/rule.py,sha256=BL_79wn4KtTGtgDw72wp6TVcxsETjGKlEGbiCtWynr0,1696
20
21
  kameleoon/configuration/rule_type.py,sha256=5CspeaWHhrFzYXIv0-2-Y3C4QXz-FvpkC3VihgW4dxA,456
21
- kameleoon/configuration/settings.py,sha256=IIUa7V3y8K1PREBq2KHNLbu8gO1k_QmH6h7KjvOqj1E,1946
22
+ kameleoon/configuration/settings.py,sha256=HECyl9j1UswedfSncDDewmrn8A77oaIEsmlCyWmDt20,2088
22
23
  kameleoon/configuration/variable.py,sha256=hvWoHmIXsEIZDxPJSDzmYYSarhKZD-gaxjue5ZULOTY,1759
23
24
  kameleoon/configuration/variation.py,sha256=hn4V06L3r7gtJosGK94WlGCoXsco0CIEDuKBR8p2J4Q,1261
24
25
  kameleoon/configuration/variation_by_exposition.py,sha256=6MLEmftMVjm1hef59AtZTNk1qrBlSFzuHYzKNvfts6c,925
@@ -69,7 +70,7 @@ kameleoon/helpers/multi_threading.py,sha256=Em1DeYRH5Vx7GUSv5m6sdAxc43za3WSijUah
69
70
  kameleoon/helpers/nonce.py,sha256=QmdCkHvzcdwY2yC7XsHzVLjUKxKdSyvgG1fi8Xz8Xh8,254
70
71
  kameleoon/helpers/repeat_timer.py,sha256=S8nC4jbK5z6C8on-FJ_CN8kZynBN22PsPcgaO8gOMwc,412
71
72
  kameleoon/helpers/scheduler.py,sha256=8VFnX8WpWItcuO1fDBZKV150wcR0jm5UM0nwqzcaKbw,4149
72
- kameleoon/helpers/sem_version.py,sha256=BGqUkPo5jx0nTgr7m_paIl0l8xCgi_zFsiS1D4gzNDo,1976
73
+ kameleoon/helpers/sem_version.py,sha256=ufOBsx79H7JKQgst4n2Td95kaBskyjtGbqFZLIJHOtg,2510
73
74
  kameleoon/helpers/string_utils.py,sha256=g2ofE2oF_04JsbG43xDS3clrVuxZIPq1cMKqeSqRthM,1855
74
75
  kameleoon/helpers/time.py,sha256=E7279NV9pDuYqVesIIrEhixMviKEoNhDLO9XQXNaWdk,486
75
76
  kameleoon/helpers/visitor_code.py,sha256=boya6fmyixNaOwdvxDzt91C7-XN8T9T_0mm3C5JQGIA,745
@@ -106,13 +107,13 @@ kameleoon/network/network_manager.py,sha256=OoE0PaKIDmsJbZV0F9KKroPHOWJGIiKx2ejk
106
107
  kameleoon/network/network_manager_factory.py,sha256=SAaiNF_Fw6xoyOCZ3y9Wu3BLZwW74JsBmkTSIJhtilw,850
107
108
  kameleoon/network/network_manager_factory_impl.py,sha256=SVsomvYY1Pb0VFEPTad5XVn29koo48i8Y0VYkNk-374,2258
108
109
  kameleoon/network/network_manager_impl.py,sha256=dNy0Qs_Lnmhve7AHhD4OplHFaIRn7jaBU4QsIwGi8js,2249
109
- kameleoon/network/query_builder.py,sha256=OUpVjLCLjjoXH6flxw4kVnzgNthKqebmCxWm6y3f3Q0,2973
110
+ kameleoon/network/query_builder.py,sha256=Gsgqw3C2MmGU9xqOLIk-9sd058MA-vw7sWtpHIHuIxs,2950
110
111
  kameleoon/network/query_encodable.py,sha256=9E8zt06-LuSPx2bgV9b5fLw_KV1VB-oi9OZkGsBBApE,209
111
112
  kameleoon/network/sendable.py,sha256=XTn7_mFkf8gDf5PKSokRvuso1QuJR5tHRnUUjL5ASFw,2741
112
113
  kameleoon/network/service_initialize_context.py,sha256=lIHf26tNVvFG_FGLoYMCCzHcbXHFqW95YStAZuOoPSY,355
113
114
  kameleoon/network/service_initialize_context_impl.py,sha256=jg0-YrfGrKje9cXJEFufdnqfgkyG5Tn2Bl8soxzG7AU,546
114
115
  kameleoon/network/uri_helper.py,sha256=0erdfjTrDtApT3b99a09AHllDu2fb6xhoapylpx_MLo,318
115
- kameleoon/network/url_provider.py,sha256=dHBBDs4-WxR4iJPIt4N1D2BGCIsDVBryyB70YhoM4Fw,7147
116
+ kameleoon/network/url_provider.py,sha256=5XCKMqKyNYgNbfSVrtMYD6cN-hBihKi7gTtvr5UtWhc,6833
116
117
  kameleoon/network/cookie/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
117
118
  kameleoon/network/cookie/cookie_manager.py,sha256=M68IGYP1TU4CwexKRC3v86MsW1Ss7h1lcIBPequ4dv8,9549
118
119
  kameleoon/network/services/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -121,12 +122,12 @@ kameleoon/network/services/automation_service_impl.py,sha256=K-lEquriHw5Ry4kXkK5
121
122
  kameleoon/network/services/configuration_service.py,sha256=Aa8VVEieS4DMUIT9B-ltVTCSfMkRZ5bAn5W5CIRd1Xk,998
122
123
  kameleoon/network/services/configuration_service_impl.py,sha256=-xFKFtkhd0Hk_nOnDTRzSUPLu5vBdu33kN-ap9y3qck,2919
123
124
  kameleoon/network/services/data_service.py,sha256=wWrb98JmlNCILvmG3JZPqdc8Sp5aUsMrDWaABvA0iKk,1098
124
- kameleoon/network/services/data_service_impl.py,sha256=1BegpK7towoXCy5eqztFfG0XeNrtgjoSiQz219saLDA,3859
125
+ kameleoon/network/services/data_service_impl.py,sha256=OhiwdJTuFpfZoebc0PB_UCMKUw7Qqsjur13LKYO93QQ,3866
125
126
  kameleoon/network/services/service.py,sha256=G2paqnw_1XjCC_eCbuOq9MWe0RqScIQMbnJUJj3ehtk,192
126
127
  kameleoon/network/services/service_impl.py,sha256=7DIpo9_BX_s6usZqVDlT_Ao3FBdzVQgmQ9Gk940Ue-U,5465
127
- kameleoon/real_time/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
128
- kameleoon/real_time/real_time_event.py,sha256=84d1wcd34ZbctjWFa1EIt8LdDSNt6c49xZA5NKQn-IA,548
129
- kameleoon/real_time/real_time_event_service.py,sha256=NOyQqs9704afYIIgLpsFcue1riFc6cbrTOOFIbOmbmQ,3060
128
+ kameleoon/network/streaming/__init__.py,sha256=txADgt8zd5FZxNADewZjDDHM_-dnHBJcBm-Lu-pTsfc,26
129
+ kameleoon/network/streaming/data_file_update_message.py,sha256=3Z1Vz04fxJVledt9hBiV3V3Jee9fkCVf2zIDe7WbIAg,926
130
+ kameleoon/network/streaming/streaming_service.py,sha256=I-AmMtDH21WUMygcBbfzcYCXK6tBHuil3CjLoa4Z38w,9916
130
131
  kameleoon/targeting/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
131
132
  kameleoon/targeting/models.py,sha256=21QikRumqRRlimD_qGnr9xzuFyLcCii3b398F7wf10Q,1018
132
133
  kameleoon/targeting/targeting_manager.py,sha256=IH1LcAptfCB4KhcWrHWROzE1aXCG5eElcgt_UGf96qI,7722
@@ -170,7 +171,7 @@ kameleoon/types/remote_visitor_data_filter.py,sha256=YqInU1WvVwdBC9cTLhVXK7JYLic
170
171
  kameleoon/types/rule.py,sha256=RrnZA_nkIbvzfUSUcuKCqxqs48aVVk6WhlGfg2WrPns,1307
171
172
  kameleoon/types/variable.py,sha256=txEU9O07WPQOz6NjRIibyJWQ_mFexyqRa8YaR6W6eSE,833
172
173
  kameleoon/types/variation.py,sha256=vrgQWDeDc1FvsG5_O7CfsB5Xl4QhiKgKsWQMyoF1BkQ,2771
173
- kameleoon_client_python-3.22.2.dist-info/METADATA,sha256=5yUAN6CSAN7zbIPgZEcJxK9p-qPsCaxS03iKdDuM9VM,13195
174
- kameleoon_client_python-3.22.2.dist-info/WHEEL,sha256=AeO2BvogYWm3eGaHCvhzmUYt8ia7KfURiHzO_1atlys,109
175
- kameleoon_client_python-3.22.2.dist-info/top_level.txt,sha256=i6mIQRivSZ-iWKzQ7WnfUr-c19Hkt0uJR_PKO53yZEc,10
176
- kameleoon_client_python-3.22.2.dist-info/RECORD,,
174
+ kameleoon_client_python-3.23.0.dist-info/METADATA,sha256=fWGB68O0rPARe0WWknZoEcXPz6G-4ZpUokZFxqpav3Q,13195
175
+ kameleoon_client_python-3.23.0.dist-info/WHEEL,sha256=AeO2BvogYWm3eGaHCvhzmUYt8ia7KfURiHzO_1atlys,109
176
+ kameleoon_client_python-3.23.0.dist-info/top_level.txt,sha256=i6mIQRivSZ-iWKzQ7WnfUr-c19Hkt0uJR_PKO53yZEc,10
177
+ kameleoon_client_python-3.23.0.dist-info/RECORD,,
File without changes
@@ -1,19 +0,0 @@
1
- """ Kameleoon Real Time Event """
2
- from typing import Any, Dict
3
-
4
-
5
- class RealTimeEvent:
6
- """
7
- RealTimeEvent contains information about timestamp when configuration was updated.
8
- Timestamp parameter uses for fetching the latest configuration
9
- """
10
-
11
- def __init__(self, event_dict: Dict[str, Any]):
12
- """
13
- RealTimeEvent gets the new timestamp from and JSON message
14
- """
15
- self.time_stamp = event_dict["ts"]
16
-
17
- def get_time_stamp(self) -> int:
18
- """Returns the timestamp"""
19
- return self.time_stamp
@@ -1,81 +0,0 @@
1
- """ Kameleoon Real Time Event Service """
2
- import json
3
- import time
4
- from typing import Any, Callable, Dict, Optional
5
-
6
- import requests
7
- import sseclient
8
-
9
- from kameleoon.logging.kameleoon_logger import KameleoonLogger
10
- from kameleoon.helpers.multi_threading import run_in_thread
11
- from kameleoon.real_time.real_time_event import RealTimeEvent
12
-
13
- KAMELEOON_REAL_TIME_EVENT_THREAD = "KameleoonRealTimeEventThread"
14
- DATA_FILE_UPDATE_EVENT = "configuration-update-event"
15
- # Delay before re-establishing a failed SSE connection, so a persistent
16
- # failure does not turn into a hot reconnect loop.
17
- RECONNECT_DELAY_SECONDS = 3.0
18
-
19
-
20
- class RealTimeEventService:
21
- """
22
- RealTimeEventService uses for fetching updates of configuration
23
- (experiments and feature flags) in real time
24
- """
25
-
26
- def __init__(
27
- self,
28
- url: str,
29
- update_handler: Callable[[RealTimeEvent], Any],
30
- reconnect_delay: float = RECONNECT_DELAY_SECONDS,
31
- ):
32
- """
33
- For RealTimeEventService must be provided an url
34
- from where it can read the updates
35
- """
36
- self.url = url
37
- self.update_handler = update_handler
38
- self.need_close = False
39
- self.headers = {
40
- "Accept": "text/event-stream",
41
- "Cache-Control": "no-cache",
42
- "Connection": "Keep-Alive",
43
- }
44
- self.response: Optional[Any] = None
45
- self._reconnect_delay = reconnect_delay
46
- self._create_sse_client()
47
-
48
- def _create_sse_client(self) -> None:
49
- if not self.need_close:
50
- run_in_thread(self._run_sse_client, KAMELEOON_REAL_TIME_EVENT_THREAD, with_event_loop=True)
51
-
52
- def _run_sse_client(self):
53
- KameleoonLogger.debug("Create SSE client")
54
- try:
55
- self.response = RealTimeEventService._with_requests(self.url, self.headers)
56
- client = sseclient.SSEClient(self.response)
57
- for message in client.events():
58
- if self.need_close:
59
- return
60
- if message.event == DATA_FILE_UPDATE_EVENT:
61
- event_dict = json.loads(message.data)
62
- self.update_handler(RealTimeEvent(event_dict))
63
- except Exception as ex: # pylint: disable=W0703
64
- KameleoonLogger.error("Error occurred within SSE client: %s", ex)
65
- # The delay is applied to every re-establishment (a failed connection and
66
- # a dropped stream alike), so a persistent failure cannot produce a hot loop.
67
- if not self.need_close:
68
- time.sleep(self._reconnect_delay)
69
- self._create_sse_client()
70
-
71
- def close(self) -> None:
72
- """Closes the connection to the server"""
73
- KameleoonLogger.info("Real-time event service is shutting down")
74
- self.need_close = True
75
- if self.response is not None:
76
- self.response.close()
77
-
78
- @staticmethod
79
- def _with_requests(url: str, headers: Dict[str, Any]):
80
- """Get a streaming response for the given event feed using requests."""
81
- return requests.get(url, stream=True, headers=headers)