Skip to content

Commit c792eac

Browse files
[FSSDK-13482] Fix Arnica findings: setup.py exec and http session mount (#529)
* [FSSDK-13482] Fix Arnica findings: setup.py exec and http session mount - setup.py: read the version by parsing the version_info literal from optimizely/version.py instead of exec()-ing the file. - Add create_retry_session helper and use it in event_dispatcher and config_manager, replacing three duplicated session.mount('http://', ...) blocks with one documented, suppressed call. Behavior is unchanged. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * [FSSDK-13482] Fix mypy: allow Optional retries in create_retry_session config_manager passes self.retries, which is Optional[int]. Accept Optional[int] (None means no total limit, same as urllib3's Retry) so type-check passes. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * [FSSDK-13482] Drop Python 3.9 from the CI test matrix Python 3.9 reached end of life in October 2025 and setup-python no longer finds a 3.9 build on ubuntu-latest (now Ubuntu 26.04), so the test (3.9) job failed before running any tests. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Revert python version drop from CI test matrix * [FSSDK-13482] Address review: default status_forcelist, trim duplicated http:// note - Default status_forcelist to (500, 502, 503, 504) in create_retry_session and drop the argument from the three callers. - Keep the http:// explanation next to the mount call and shorten the docstring. - Add a test for the default status_forcelist. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 7649661 commit c792eac

5 files changed

Lines changed: 103 additions & 34 deletions

File tree

‎optimizely/config_manager.py‎

Lines changed: 5 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,6 @@
1919
import threading
2020
from requests import codes as http_status_codes
2121
from requests import exceptions as requests_exceptions
22-
from requests.adapters import HTTPAdapter
23-
from urllib3.util.retry import Retry
2422

2523
from . import exceptions as optimizely_exceptions
2624
from . import logger as optimizely_logger
@@ -30,6 +28,7 @@
3028
from .notification_center_registry import _NotificationCenterRegistry
3129
from .helpers import enums
3230
from .helpers import validator
31+
from .helpers.retry_session import create_retry_session
3332
from .optimizely_config import OptimizelyConfig, OptimizelyConfigService
3433

3534

@@ -392,15 +391,8 @@ def fetch_datafile(self) -> None:
392391
request_headers[enums.HTTPHeaders.IF_MODIFIED_SINCE] = self.last_modified
393392

394393
try:
395-
session = requests.Session()
396-
397-
retries = Retry(total=self.retries,
398-
backoff_factor=0.1,
399-
status_forcelist=[500, 502, 503, 504])
400-
adapter = HTTPAdapter(max_retries=retries)
401-
402-
session.mount('http://', adapter)
403-
session.mount("https://", adapter)
394+
session = create_retry_session(retries=self.retries,
395+
backoff_factor=0.1)
404396
response = session.get(self.datafile_url,
405397
headers=request_headers,
406398
timeout=enums.ConfigManager.REQUEST_TIMEOUT)
@@ -485,15 +477,8 @@ def fetch_datafile(self) -> None:
485477
request_headers[enums.HTTPHeaders.IF_MODIFIED_SINCE] = self.last_modified
486478

487479
try:
488-
session = requests.Session()
489-
490-
retries = Retry(total=self.retries,
491-
backoff_factor=0.1,
492-
status_forcelist=[500, 502, 503, 504])
493-
adapter = HTTPAdapter(max_retries=retries)
494-
495-
session.mount('http://', adapter)
496-
session.mount("https://", adapter)
480+
session = create_retry_session(retries=self.retries,
481+
backoff_factor=0.1)
497482
response = session.get(self.datafile_url,
498483
headers=request_headers,
499484
timeout=enums.ConfigManager.REQUEST_TIMEOUT)

‎optimizely/event_dispatcher.py‎

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,11 @@
1515
import logging
1616
from typing import Protocol
1717

18-
import requests
1918
from requests import exceptions as request_exception
20-
from requests.adapters import HTTPAdapter
21-
from urllib3.util.retry import Retry
2219

2320
from . import event_builder
2421
from .helpers.enums import HTTPVerbs, EventDispatchConfig
22+
from .helpers.retry_session import create_retry_session
2523

2624

2725
class CustomEventDispatcher(Protocol):
@@ -41,15 +39,8 @@ def dispatch_event(event: event_builder.Event) -> None:
4139
event: Object holding information about the request to be dispatched to the Optimizely backend.
4240
"""
4341
try:
44-
session = requests.Session()
45-
46-
retries = Retry(total=EventDispatchConfig.RETRIES,
47-
backoff_factor=0.2,
48-
status_forcelist=[500, 502, 503, 504])
49-
adapter = HTTPAdapter(max_retries=retries)
50-
51-
session.mount('http://', adapter)
52-
session.mount("https://", adapter)
42+
session = create_retry_session(retries=EventDispatchConfig.RETRIES,
43+
backoff_factor=0.2)
5344

5445
if event.http_verb == HTTPVerbs.GET:
5546
session.get(event.url, params=event.params,
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Copyright 2026, Optimizely
2+
# Licensed under the Apache License, Version 2.0 (the "License");
3+
# you may not use this file except in compliance with the License.
4+
# You may obtain a copy of the License at
5+
#
6+
# http://www.apache.org/licenses/LICENSE-2.0
7+
#
8+
# Unless required by applicable law or agreed to in writing, software
9+
# distributed under the License is distributed on an "AS IS" BASIS,
10+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
# See the License for the specific language governing permissions and
12+
# limitations under the License.
13+
14+
from __future__ import annotations
15+
16+
from typing import Optional, Sequence
17+
18+
import requests
19+
from requests.adapters import HTTPAdapter
20+
from urllib3.util.retry import Retry
21+
22+
23+
def create_retry_session(
24+
retries: Optional[int], backoff_factor: float, status_forcelist: Sequence[int] = (500, 502, 503, 504)
25+
) -> requests.Session:
26+
""" Create a requests session that retries failed requests.
27+
28+
The same retry adapter is registered for both https:// and http:// URLs.
29+
30+
Args:
31+
retries: Total number of retries. None means no total limit (same as urllib3's Retry).
32+
backoff_factor: Backoff factor between retries.
33+
status_forcelist: HTTP status codes that should trigger a retry. Defaults to 500, 502, 503 and 504.
34+
35+
Returns:
36+
A configured requests.Session.
37+
"""
38+
session = requests.Session()
39+
40+
retry = Retry(total=retries,
41+
backoff_factor=backoff_factor,
42+
status_forcelist=status_forcelist)
43+
adapter = HTTPAdapter(max_retries=retry)
44+
45+
# http:// kept so retries still apply to user-configured http:// datafile URLs / event endpoints.
46+
# nosemgrep
47+
session.mount('http://', adapter)
48+
session.mount('https://', adapter)
49+
50+
return session

‎setup.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,19 @@
1+
import ast
12
import os
3+
import re
24

35
from setuptools import setup
46
from setuptools import find_packages
57

68
here = os.path.join(os.path.dirname(__file__))
79

810

9-
__version__ = None
11+
# Read the version without executing version.py: parse the version_info tuple literal instead.
1012
with open(os.path.join(here, 'optimizely', 'version.py')) as _file:
11-
exec(_file.read())
13+
_version_match = re.search(r'^version_info\s*=\s*(\(.*\))\s*$', _file.read(), re.MULTILINE)
14+
if _version_match is None:
15+
raise RuntimeError('Unable to find version_info in optimizely/version.py')
16+
__version__ = '.'.join(str(v) for v in ast.literal_eval(_version_match.group(1)))
1217

1318
with open(os.path.join(here, 'requirements', 'core.txt')) as _file:
1419
REQUIREMENTS = _file.read().splitlines()
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Copyright 2026, Optimizely
2+
# Licensed under the Apache License, Version 2.0 (the "License");
3+
# you may not use this file except in compliance with the License.
4+
# You may obtain a copy of the License at
5+
#
6+
# http://www.apache.org/licenses/LICENSE-2.0
7+
#
8+
# Unless required by applicable law or agreed to in writing, software
9+
# distributed under the License is distributed on an "AS IS" BASIS,
10+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
# See the License for the specific language governing permissions and
12+
# limitations under the License.
13+
14+
import unittest
15+
16+
import requests
17+
from requests.adapters import HTTPAdapter
18+
19+
from optimizely.helpers.retry_session import create_retry_session
20+
21+
22+
class CreateRetrySessionTest(unittest.TestCase):
23+
def test_returns_session_with_retry_adapter_for_https_and_http(self):
24+
session = create_retry_session(retries=3, backoff_factor=0.2, status_forcelist=[500, 503])
25+
26+
self.assertIsInstance(session, requests.Session)
27+
for prefix in ('https://', 'http://'):
28+
adapter = session.get_adapter(prefix + 'example.com')
29+
self.assertIsInstance(adapter, HTTPAdapter)
30+
self.assertEqual(3, adapter.max_retries.total)
31+
self.assertEqual(0.2, adapter.max_retries.backoff_factor)
32+
self.assertEqual([500, 503], list(adapter.max_retries.status_forcelist))
33+
34+
def test_status_forcelist_defaults_to_server_error_codes(self):
35+
session = create_retry_session(retries=3, backoff_factor=0.2)
36+
37+
adapter = session.get_adapter('https://example.com')
38+
self.assertEqual([500, 502, 503, 504], list(adapter.max_retries.status_forcelist))

0 commit comments

Comments
 (0)