Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions flagsmith/analytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ def __init__(
base_api_url: str,
timeout: typing.Optional[int] = 3,
analytics_url: typing.Optional[str] = None,
proxies: typing.Optional[typing.Dict[str, str]] = None,
):
"""
Initialise the AnalyticsProcessor to handle sending analytics on flag usage to
Expand All @@ -64,9 +65,11 @@ def __init__(
where flag evaluation traffic and analytics traffic must go to different
hosts (for example, evaluating through the Edge Proxy while sending
analytics to the core API).
:param proxies: as per requests.Session.proxies
"""
self.analytics_endpoint = analytics_url or (base_api_url + ANALYTICS_ENDPOINT)
self.environment_key = environment_key
self.proxies = proxies
self._last_flushed = datetime.now()
self.analytics_data: typing.MutableMapping[str, typing.Any] = {}
self.timeout = timeout or 3
Expand All @@ -86,6 +89,7 @@ def flush(self) -> None:
"X-Environment-Key": self.environment_key,
"Content-Type": "application/json",
},
proxies=self.proxies,
)

self.analytics_data.clear()
Expand Down Expand Up @@ -140,12 +144,14 @@ def __init__(
self,
config: EventProcessorConfig,
environment_key: str,
proxies: typing.Optional[typing.Dict[str, str]] = None,
) -> None:
url = config.events_api_url
if not url.endswith("/"):
url = f"{url}/"
self._batch_endpoint = f"{url}v1/events"
self._environment_key = environment_key
self._proxies = proxies
if config.max_buffer_items < 1:
logger.warning(
"max_buffer_items must be at least 1, not %d: using 1",
Expand All @@ -164,6 +170,7 @@ def _start_worker(self) -> None:
the parent's worker doesn't exist and the parent sends its own events.
"""
self._session = requests.Session()
self._session.proxies.update(self._proxies or {})
self._condition = threading.Condition()
self._buffer: typing.Deque[_BufferedEvent] = deque()
self._buffered_exposure_keys: typing.Set[ExposureKey] = set()
Expand Down
4 changes: 4 additions & 0 deletions flagsmith/flagsmith.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ def __init__(
"""

self.offline_mode = offline_mode
self.proxies = proxies
self.enable_local_evaluation = enable_local_evaluation
self.environment_refresh_interval_seconds = environment_refresh_interval_seconds
self.offline_handler = offline_handler
Expand Down Expand Up @@ -221,6 +222,7 @@ def _initialise_analytics(
self.api_url,
timeout=self.request_timeout_seconds,
analytics_url=analytics_url,
proxies=self.proxies,
)

def _initialise_events(
Expand All @@ -233,6 +235,7 @@ def _initialise_events(
self._event_processor = EventProcessor(
config=event_processor_config or EventProcessorConfig(),
environment_key=environment_key,
proxies=self.proxies,
)

def _initialise_local_evaluation(self) -> None:
Expand All @@ -252,6 +255,7 @@ def _initialise_local_evaluation(self) -> None:
self.event_stream_thread = EventStreamManager(
stream_url=stream_url,
on_event=self.handle_stream_event,
proxies=self.proxies,
daemon=True,
)

Expand Down
3 changes: 3 additions & 0 deletions flagsmith/streaming_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,15 @@ def __init__(
stream_url: str,
on_event: Callable[[StreamEvent], None],
request_timeout_seconds: Optional[int] = None,
proxies: Optional[typing.Dict[str, str]] = None,
**kwargs: typing.Any,
) -> None:
super().__init__(*args, **kwargs)
self._stop_event = threading.Event()
self.stream_url = stream_url
self.on_event = on_event
self.request_timeout_seconds = request_timeout_seconds
self.proxies = proxies

def run(self) -> None:
while not self._stop_event.is_set():
Expand All @@ -35,6 +37,7 @@ def run(self) -> None:
stream=True,
headers={"Accept": "application/json, text/event-stream"},
timeout=self.request_timeout_seconds,
proxies=self.proxies,
) as response:
sse_client = sseclient.SSEClient(chunk for chunk in response)
for event in sse_client.events():
Expand Down
16 changes: 16 additions & 0 deletions tests/test_event_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -911,3 +911,19 @@ def test_stop__processor_no_longer_referenced__garbage_collected(
# Then
assert len(mocked_responses.calls) == 1
assert collected() is None


def test_event_processor__proxies__set_on_session() -> None:
# Given
proxies = {"https": "http://proxy.example.com:3128"}

# When
processor = EventProcessor(
config=EventProcessorConfig(),
environment_key="key",
proxies=proxies,
)

# Then
assert processor._session.proxies == proxies
processor.close()
44 changes: 44 additions & 0 deletions tests/test_flagsmith.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json
import logging
import threading
import time
import typing

Expand Down Expand Up @@ -1675,3 +1676,46 @@ def test_get_environment_flags__local_evaluation__running_experiment__no_experim
assert isinstance(flag, Flag)
assert flag.value == "control"
assert flag.experiment is None


def test_flagsmith__proxies__used_by_realtime_analytics_and_events(
requests_session_response_ok: None,
server_api_key: str,
mocker: MockerFixture,
) -> None:
# Given
proxies = {"https": "http://proxy.example.com:3128"}
request_started = threading.Event()

def get_stream(*args: typing.Any, **kwargs: typing.Any) -> typing.NoReturn:
request_started.set()
raise requests.exceptions.ReadTimeout()

mock_get = mocker.patch(
"flagsmith.streaming_manager.requests.get", side_effect=get_stream
)
mock_session = mocker.patch("flagsmith.analytics.session")
mock_events = mocker.patch("flagsmith.flagsmith.EventProcessor")

# When
flagsmith = Flagsmith(
environment_key=server_api_key,
enable_local_evaluation=True,
enable_realtime_updates=True,
enable_analytics=True,
enable_events=True,
proxies=proxies,
)
try:
assert request_started.wait(timeout=5), "SSE request did not start"
finally:
flagsmith.event_stream_thread.stop()
flagsmith.event_stream_thread.join(timeout=5)
assert flagsmith._analytics_processor
flagsmith._analytics_processor.track_feature("my_feature")
flagsmith._analytics_processor.flush()

# Then
assert mock_get.call_args.kwargs["proxies"] == proxies
assert mock_session.post.call_args.kwargs["proxies"] == proxies
assert mock_events.call_args.kwargs["proxies"] == proxies