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
1 change: 0 additions & 1 deletion .github/workflows/python.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ jobs:
python-version:
- "pypy-3.9"
- "pypy-3.10"
- "3.9"
- "3.10"
- "3.11"
- "3.12"
Expand Down
27 changes: 7 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,9 @@ 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,
status_forcelist=[500, 502, 503, 504])
response = session.get(self.datafile_url,
headers=request_headers,
timeout=enums.ConfigManager.REQUEST_TIMEOUT)
Expand Down Expand Up @@ -485,15 +478,9 @@ 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,
status_forcelist=[500, 502, 503, 504])
response = session.get(self.datafile_url,
headers=request_headers,
timeout=enums.ConfigManager.REQUEST_TIMEOUT)
Expand Down
16 changes: 4 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,9 @@ 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,
status_forcelist=[500, 502, 503, 504])

if event.http_verb == HTTPVerbs.GET:
session.get(event.url, params=event.params,
Expand Down
54 changes: 54 additions & 0 deletions optimizely/helpers/retry_session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# 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]
) -> requests.Session:
""" Create a requests session that retries failed requests.

The same retry adapter is registered for both https:// and http:// URLs. The SDK defaults are all https://.
The http:// prefix is registered only so that retries also apply when a user configures a custom http://
datafile URL or event endpoint (for example an internal proxy or a local test server). Registering an adapter
does not send anything over http://, it only configures how requests to that prefix are retried.

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.

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)

# Intentional, see the docstring: this only registers the retry adapter, it does not send anything over http://.
# (Bare nosemgrep: the full rule id for request-session-with-http does not fit in the 120 character line limit.)
# 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
32 changes: 32 additions & 0 deletions tests/helpers_tests/test_retry_session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# 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))
Loading