diff --git a/optimizely/config_manager.py b/optimizely/config_manager.py index 22468b05b..ccad8d087 100644 --- a/optimizely/config_manager.py +++ b/optimizely/config_manager.py @@ -19,8 +19,6 @@ import threading from requests import codes as http_status_codes from requests import exceptions as requests_exceptions -from requests.adapters import HTTPAdapter -from urllib3.util.retry import Retry from . import exceptions as optimizely_exceptions from . import logger as optimizely_logger @@ -30,6 +28,7 @@ from .notification_center_registry import _NotificationCenterRegistry from .helpers import enums from .helpers import validator +from .helpers.retry_session import create_retry_session from .optimizely_config import OptimizelyConfig, OptimizelyConfigService @@ -392,15 +391,8 @@ def fetch_datafile(self) -> None: request_headers[enums.HTTPHeaders.IF_MODIFIED_SINCE] = self.last_modified try: - session = requests.Session() - - retries = Retry(total=self.retries, - backoff_factor=0.1, - status_forcelist=[500, 502, 503, 504]) - adapter = HTTPAdapter(max_retries=retries) - - session.mount('http://', adapter) - session.mount("https://", adapter) + session = create_retry_session(retries=self.retries, + backoff_factor=0.1) response = session.get(self.datafile_url, headers=request_headers, timeout=enums.ConfigManager.REQUEST_TIMEOUT) @@ -485,15 +477,8 @@ def fetch_datafile(self) -> None: request_headers[enums.HTTPHeaders.IF_MODIFIED_SINCE] = self.last_modified try: - session = requests.Session() - - retries = Retry(total=self.retries, - backoff_factor=0.1, - status_forcelist=[500, 502, 503, 504]) - adapter = HTTPAdapter(max_retries=retries) - - session.mount('http://', adapter) - session.mount("https://", adapter) + session = create_retry_session(retries=self.retries, + backoff_factor=0.1) response = session.get(self.datafile_url, headers=request_headers, timeout=enums.ConfigManager.REQUEST_TIMEOUT) diff --git a/optimizely/event_dispatcher.py b/optimizely/event_dispatcher.py index cf4683401..f97605981 100644 --- a/optimizely/event_dispatcher.py +++ b/optimizely/event_dispatcher.py @@ -15,13 +15,11 @@ import logging from typing import Protocol -import requests from requests import exceptions as request_exception -from requests.adapters import HTTPAdapter -from urllib3.util.retry import Retry from . import event_builder from .helpers.enums import HTTPVerbs, EventDispatchConfig +from .helpers.retry_session import create_retry_session class CustomEventDispatcher(Protocol): @@ -41,15 +39,8 @@ def dispatch_event(event: event_builder.Event) -> None: event: Object holding information about the request to be dispatched to the Optimizely backend. """ try: - session = requests.Session() - - retries = Retry(total=EventDispatchConfig.RETRIES, - backoff_factor=0.2, - status_forcelist=[500, 502, 503, 504]) - adapter = HTTPAdapter(max_retries=retries) - - session.mount('http://', adapter) - session.mount("https://", adapter) + session = create_retry_session(retries=EventDispatchConfig.RETRIES, + backoff_factor=0.2) if event.http_verb == HTTPVerbs.GET: session.get(event.url, params=event.params, diff --git a/optimizely/helpers/retry_session.py b/optimizely/helpers/retry_session.py new file mode 100644 index 000000000..b01f7232d --- /dev/null +++ b/optimizely/helpers/retry_session.py @@ -0,0 +1,50 @@ +# Copyright 2026, Optimizely +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from typing import Optional, Sequence + +import requests +from requests.adapters import HTTPAdapter +from urllib3.util.retry import Retry + + +def create_retry_session( + retries: Optional[int], backoff_factor: float, status_forcelist: Sequence[int] = (500, 502, 503, 504) +) -> requests.Session: + """ Create a requests session that retries failed requests. + + The same retry adapter is registered for both https:// and http:// URLs. + + Args: + retries: Total number of retries. None means no total limit (same as urllib3's Retry). + backoff_factor: Backoff factor between retries. + status_forcelist: HTTP status codes that should trigger a retry. Defaults to 500, 502, 503 and 504. + + Returns: + A configured requests.Session. + """ + session = requests.Session() + + retry = Retry(total=retries, + backoff_factor=backoff_factor, + status_forcelist=status_forcelist) + adapter = HTTPAdapter(max_retries=retry) + + # http:// kept so retries still apply to user-configured http:// datafile URLs / event endpoints. + # nosemgrep + session.mount('http://', adapter) + session.mount('https://', adapter) + + return session diff --git a/setup.py b/setup.py index 1954aa489..18c9d1d7b 100644 --- a/setup.py +++ b/setup.py @@ -1,4 +1,6 @@ +import ast import os +import re from setuptools import setup from setuptools import find_packages @@ -6,9 +8,12 @@ here = os.path.join(os.path.dirname(__file__)) -__version__ = None +# Read the version without executing version.py: parse the version_info tuple literal instead. with open(os.path.join(here, 'optimizely', 'version.py')) as _file: - exec(_file.read()) + _version_match = re.search(r'^version_info\s*=\s*(\(.*\))\s*$', _file.read(), re.MULTILINE) +if _version_match is None: + raise RuntimeError('Unable to find version_info in optimizely/version.py') +__version__ = '.'.join(str(v) for v in ast.literal_eval(_version_match.group(1))) with open(os.path.join(here, 'requirements', 'core.txt')) as _file: REQUIREMENTS = _file.read().splitlines() diff --git a/tests/helpers_tests/test_retry_session.py b/tests/helpers_tests/test_retry_session.py new file mode 100644 index 000000000..8f52ec763 --- /dev/null +++ b/tests/helpers_tests/test_retry_session.py @@ -0,0 +1,38 @@ +# Copyright 2026, Optimizely +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import requests +from requests.adapters import HTTPAdapter + +from optimizely.helpers.retry_session import create_retry_session + + +class CreateRetrySessionTest(unittest.TestCase): + def test_returns_session_with_retry_adapter_for_https_and_http(self): + session = create_retry_session(retries=3, backoff_factor=0.2, status_forcelist=[500, 503]) + + self.assertIsInstance(session, requests.Session) + for prefix in ('https://', 'http://'): + adapter = session.get_adapter(prefix + 'example.com') + self.assertIsInstance(adapter, HTTPAdapter) + self.assertEqual(3, adapter.max_retries.total) + self.assertEqual(0.2, adapter.max_retries.backoff_factor) + self.assertEqual([500, 503], list(adapter.max_retries.status_forcelist)) + + def test_status_forcelist_defaults_to_server_error_codes(self): + session = create_retry_session(retries=3, backoff_factor=0.2) + + adapter = session.get_adapter('https://example.com') + self.assertEqual([500, 502, 503, 504], list(adapter.max_retries.status_forcelist))