Skip to content
Merged
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
25 changes: 5 additions & 20 deletions optimizely/config_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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


Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
15 changes: 3 additions & 12 deletions optimizely/event_dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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,
Expand Down
50 changes: 50 additions & 0 deletions optimizely/helpers/retry_session.py
Original file line number Diff line number Diff line change
@@ -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
9 changes: 7 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import ast
import os
import re

from setuptools import setup
from setuptools import find_packages

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()
Expand Down
38 changes: 38 additions & 0 deletions tests/helpers_tests/test_retry_session.py
Original file line number Diff line number Diff line change
@@ -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))
Loading