diff --git a/growthbook/growthbook.py b/growthbook/growthbook.py index e98e740..7eb0474 100644 --- a/growthbook/growthbook.py +++ b/growthbook/growthbook.py @@ -504,12 +504,39 @@ def user_agent_suffix(self) -> Optional[str]: def user_agent_suffix(self, value: Optional[str]) -> None: self._user_agent_suffix = value + def _http_timeout(self) -> Optional[Timeout]: + # Each timeout is optional on its own; an unset one stays unbounded. + if self.http_connect_timeout is None and self.http_read_timeout is None: + return None + return Timeout(connect=self.http_connect_timeout, read=self.http_read_timeout) + + def _aiohttp_session_kwargs(self) -> Dict[str, Any]: + # Async counterpart of _http_timeout(). Passing a bare ClientTimeout + # would drop aiohttp's own defaults (overall request limit, socket + # connect limit), so start from them and override only what is set. + if self.http_connect_timeout is None and self.http_read_timeout is None: + return {} + default = aiohttp.client.DEFAULT_TIMEOUT + return { + "timeout": aiohttp.ClientTimeout( + total=default.total, + connect=default.connect, + sock_connect=( + self.http_connect_timeout + if self.http_connect_timeout is not None + else default.sock_connect + ), + sock_read=( + self.http_read_timeout + if self.http_read_timeout is not None + else default.sock_read + ), + ) + } + # Perform the GET request (separate method for easy mocking) def _get(self, url: str, headers: Optional[Dict[str, str]] = None) -> "BaseHTTPResponse": - timeout = None - if self.http_connect_timeout and self.http_read_timeout: - timeout = Timeout(connect=self.http_connect_timeout, read=self.http_read_timeout) - self.http = self.http or PoolManager(timeout=timeout) + self.http = self.http or PoolManager(timeout=self._http_timeout()) return self.http.request("GET", url, headers=headers or {}) def _get_headers(self, client_key: str, existing_headers: Optional[Dict[str, str]] = None) -> Dict[str, str]: @@ -525,10 +552,7 @@ def _get_headers(self, client_key: str, existing_headers: Optional[Dict[str, str # Perform the POST request (separate method for easy mocking) def _post(self, url: str, payload: Dict[str, Any], headers: Optional[Dict[str, str]] = None) -> "BaseHTTPResponse": - timeout = None - if self.http_connect_timeout and self.http_read_timeout: - timeout = Timeout(connect=self.http_connect_timeout, read=self.http_read_timeout) - self.http = self.http or PoolManager(timeout=timeout) + self.http = self.http or PoolManager(timeout=self._http_timeout()) body = json.dumps(payload).encode("utf-8") return self.http.request("POST", url, body=body, headers=headers or {}) @@ -560,7 +584,7 @@ async def _fetch_and_decode_post_async( headers["Content-Type"] = "application/json" logger.debug(f"[Async] Remote-eval POST to {url}") try: - async with aiohttp.ClientSession() as session: + async with aiohttp.ClientSession(**self._aiohttp_session_kwargs()) as session: async with session.post(url, json=payload, headers=headers) as response: if response.status >= 400: logger.warning( @@ -657,7 +681,7 @@ async def _fetch_and_decode_async(self, api_host: str, client_key: str) -> Optio logger.debug(f"[Async] No ETag cache found for URL: {url}") try: - async with aiohttp.ClientSession() as session: + async with aiohttp.ClientSession(**self._aiohttp_session_kwargs()) as session: async with session.get(url, headers=headers) as response: # Handle 304 Not Modified - content hasn't changed if response.status == 304: @@ -1073,6 +1097,11 @@ def __init__( if self._client_key and not self._remoteEval: feature_repo.add_feature_update_callback(self._on_feature_update) + if http_connect_timeout is not None: + feature_repo.http_connect_timeout = http_connect_timeout + if http_read_timeout is not None: + feature_repo.http_read_timeout = http_read_timeout + self._initialize_plugins() if self._streaming: @@ -1090,10 +1119,6 @@ def __init__( # before the first eval. Matches the JS SDK init() behavior. self.load_features() - if http_connect_timeout and http_read_timeout: - feature_repo.http_connect_timeout = http_connect_timeout - feature_repo.http_read_timeout = http_read_timeout - def _remote_eval_payload(self) -> Dict[str, Any]: return build_remote_eval_payload( with_remote_group_ids(self._attributes, self._remote_group_ids), self._forcedVariations, self._url, diff --git a/tests/test_http_timeouts.py b/tests/test_http_timeouts.py new file mode 100644 index 0000000..df11b41 --- /dev/null +++ b/tests/test_http_timeouts.py @@ -0,0 +1,161 @@ +"""Options.http_connect_timeout / http_read_timeout must reach every HTTP path.""" +from unittest.mock import patch + +import aiohttp +import pytest + +from growthbook.growthbook import FeatureRepository, GrowthBook + + +class _FakeResponse: + status = 500 + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + +class _FakeSession: + """Stands in for aiohttp.ClientSession and records its constructor kwargs.""" + + created = [] + + def __init__(self, **kwargs): + self.kwargs = kwargs + _FakeSession.created.append(self) + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + def get(self, *args, **kwargs): + return _FakeResponse() + + def post(self, *args, **kwargs): + return _FakeResponse() + + +@pytest.fixture +def fake_session(): + _FakeSession.created = [] + with patch("growthbook.growthbook.aiohttp.ClientSession", _FakeSession): + yield _FakeSession + + +def _repo(connect=None, read=None): + repo = FeatureRepository() + repo.http_connect_timeout = connect + repo.http_read_timeout = read + return repo + + +@pytest.mark.asyncio +async def test_async_get_applies_http_timeouts(fake_session): + repo = _repo(connect=3, read=7) + + assert await repo._fetch_and_decode_async("https://cdn.growthbook.io", "sdk-abc123") is None + + (session,) = fake_session.created + timeout = session.kwargs["timeout"] + assert isinstance(timeout, aiohttp.ClientTimeout) + assert timeout.sock_connect == 3 + assert timeout.sock_read == 7 + + +@pytest.mark.asyncio +async def test_async_post_applies_http_timeouts(fake_session): + repo = _repo(connect=3, read=7) + + assert await repo._fetch_and_decode_post_async( + "https://cdn.growthbook.io", "sdk-abc123", {"attributes": {}} + ) is None + + (session,) = fake_session.created + timeout = session.kwargs["timeout"] + assert timeout.sock_connect == 3 + assert timeout.sock_read == 7 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("connect, read", [(3, 7), (3, None), (None, 7)]) +async def test_async_keeps_aiohttp_defaults_for_unset_fields(fake_session, connect, read): + default = aiohttp.client.DEFAULT_TIMEOUT + repo = _repo(connect=connect, read=read) + + await repo._fetch_and_decode_async("https://cdn.growthbook.io", "sdk-abc123") + + timeout = fake_session.created[0].kwargs["timeout"] + # The overall request limit must survive setting either option. + assert timeout.total == default.total + assert timeout.connect == default.connect + assert timeout.sock_connect == (connect if connect is not None else default.sock_connect) + assert timeout.sock_read == (read if read is not None else default.sock_read) + + +@pytest.mark.asyncio +async def test_async_keeps_aiohttp_defaults_without_timeouts(fake_session): + repo = _repo() + + await repo._fetch_and_decode_async("https://cdn.growthbook.io", "sdk-abc123") + + assert "timeout" not in fake_session.created[0].kwargs + + +@pytest.mark.parametrize( + "connect, read", + [(3, 7), (3, None), (None, 7)], +) +def test_sync_pool_manager_applies_each_timeout(connect, read): + repo = _repo(connect=connect, read=read) + + with patch("growthbook.growthbook.PoolManager") as pool_manager: + repo._get("https://cdn.growthbook.io/api/features/sdk-abc123") + + timeout = pool_manager.call_args.kwargs["timeout"] + assert timeout.connect_timeout == connect + assert timeout.read_timeout == read + + +def test_sync_pool_manager_has_no_timeout_by_default(): + repo = _repo() + + with patch("growthbook.growthbook.PoolManager") as pool_manager: + repo._get("https://cdn.growthbook.io/api/features/sdk-abc123") + + assert pool_manager.call_args.kwargs["timeout"] is None + + +@pytest.mark.parametrize("connect, read", [(3, 7), (3, None), (None, 7)]) +def test_remote_eval_constructor_configures_timeout_before_first_request(connect, read): + with patch("growthbook.growthbook.feature_repo", FeatureRepository()), patch( + "growthbook.growthbook.PoolManager" + ) as pool_manager: + request = pool_manager.return_value.request + request.return_value.status = 200 + request.return_value.data = b'{"features": {}}' + gb = GrowthBook( + api_host="https://proxy.example.com", + client_key="sdk-abc123", + remote_eval=True, + http_connect_timeout=connect, + http_read_timeout=read, + ) + try: + request.assert_called_once() + assert request.call_args.args == ( + "POST", "https://proxy.example.com/api/eval/sdk-abc123" + ) + timeout = pool_manager.call_args.kwargs["timeout"] + assert timeout is not None + assert timeout.connect_timeout == connect + assert timeout.read_timeout == read + + gb.load_features(force_refresh=True) + assert request.call_count == 2 + pool_manager.assert_called_once() + finally: + gb.destroy()