From 68a9bc425785159ea8828aa7e7b13f2c8b7f5a92 Mon Sep 17 00:00:00 2001 From: Alex Date: Sat, 28 Nov 2026 08:06:25 -0400 Subject: [PATCH 1/2] fix: apply proxies to realtime, analytics and event requests The proxies passed to Flagsmith were only set on the session used for the main API. Forward them to the SSE stream, the analytics flush and the event processor too. Co-Authored-By: Claude Sonnet 5.5 --- flagsmith/analytics.py | 7 +++++++ flagsmith/flagsmith.py | 4 ++++ flagsmith/streaming_manager.py | 3 +++ tests/test_event_processor.py | 16 ++++++++++++++++ tests/test_flagsmith.py | 33 +++++++++++++++++++++++++++++++++ 5 files changed, 63 insertions(+) diff --git a/flagsmith/analytics.py b/flagsmith/analytics.py index 86abf3a..1ab4f21 100644 --- a/flagsmith/analytics.py +++ b/flagsmith/analytics.py @@ -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 @@ -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 @@ -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() @@ -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", @@ -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() diff --git a/flagsmith/flagsmith.py b/flagsmith/flagsmith.py index e28c5f0..6f63ebe 100644 --- a/flagsmith/flagsmith.py +++ b/flagsmith/flagsmith.py @@ -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 @@ -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( @@ -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: @@ -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, ) diff --git a/flagsmith/streaming_manager.py b/flagsmith/streaming_manager.py index dc402d0..cc01a7f 100644 --- a/flagsmith/streaming_manager.py +++ b/flagsmith/streaming_manager.py @@ -19,6 +19,7 @@ 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) @@ -26,6 +27,7 @@ def __init__( 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(): @@ -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(): diff --git a/tests/test_event_processor.py b/tests/test_event_processor.py index 7576d07..fe2acec 100644 --- a/tests/test_event_processor.py +++ b/tests/test_event_processor.py @@ -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() diff --git a/tests/test_flagsmith.py b/tests/test_flagsmith.py index b6879fc..2c44e73 100644 --- a/tests/test_flagsmith.py +++ b/tests/test_flagsmith.py @@ -1675,3 +1675,36 @@ 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"} + mock_get = mocker.patch("flagsmith.streaming_manager.requests.get") + mock_get.side_effect = requests.exceptions.ReadTimeout() + 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, + ) + 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 From dbbb6903d3831d0c5567548af982c7c10deb0535 Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 29 Nov 2026 08:46:50 -0400 Subject: [PATCH 2/2] test: wait for the realtime proxy request --- tests/test_flagsmith.py | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/tests/test_flagsmith.py b/tests/test_flagsmith.py index 2c44e73..ee9f9f1 100644 --- a/tests/test_flagsmith.py +++ b/tests/test_flagsmith.py @@ -1,5 +1,6 @@ import json import logging +import threading import time import typing @@ -1684,8 +1685,15 @@ def test_flagsmith__proxies__used_by_realtime_analytics_and_events( ) -> None: # Given proxies = {"https": "http://proxy.example.com:3128"} - mock_get = mocker.patch("flagsmith.streaming_manager.requests.get") - mock_get.side_effect = requests.exceptions.ReadTimeout() + 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") @@ -1698,8 +1706,11 @@ def test_flagsmith__proxies__used_by_realtime_analytics_and_events( enable_events=True, proxies=proxies, ) - flagsmith.event_stream_thread.stop() - flagsmith.event_stream_thread.join(timeout=5) + 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()