Skip to content

[FSSDK-11458] Python - Add SDK Multi-Region Support for Data Hosting #459

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 36 commits into from
Aug 1, 2025
Merged
Show file tree
Hide file tree
Changes from 31 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
d9e8f83
[FSSDK-11458] Python - Add SDK Multi-Region Support for Data Hosting
esrakartalOpt Jul 2, 2025
0866962
Fix lint issues
esrakartalOpt Jul 2, 2025
5a0e19d
Fix lint issue
esrakartalOpt Jul 2, 2025
730fede
Fix errors
esrakartalOpt Jul 2, 2025
47ccb94
Add region on base test
esrakartalOpt Jul 2, 2025
a7d74ac
Update Region as enum
esrakartalOpt Jul 2, 2025
8a65e0f
Delete blank lines
esrakartalOpt Jul 2, 2025
24d2fcd
Fix lint issue
esrakartalOpt Jul 2, 2025
ba5beee
Fix lint issue
esrakartalOpt Jul 2, 2025
17c9280
Fix test errors
esrakartalOpt Jul 2, 2025
155ab25
Add enum
esrakartalOpt Jul 2, 2025
ba049b6
Fix region value
esrakartalOpt Jul 2, 2025
a777fa0
Fix type issue
esrakartalOpt Jul 2, 2025
c1f1693
Correct the event url
esrakartalOpt Jul 2, 2025
6de0889
Add region in params
esrakartalOpt Jul 2, 2025
83afabe
Fix region param
esrakartalOpt Jul 2, 2025
158aab3
Add region to create
esrakartalOpt Jul 2, 2025
0a0cdef
Fix test cases
esrakartalOpt Jul 2, 2025
f68d678
Fix test cases
esrakartalOpt Jul 2, 2025
81cd042
Fix lint
esrakartalOpt Jul 2, 2025
9d2c892
Add region
esrakartalOpt Jul 2, 2025
3c1332f
Fix test cases
esrakartalOpt Jul 4, 2025
11523cf
Fix tests
esrakartalOpt Jul 4, 2025
1af68db
Cast to string
esrakartalOpt Jul 4, 2025
7a09f1d
Fix tests
esrakartalOpt Jul 4, 2025
0b1e83f
Merge branch 'master' of https://github.com/optimizely/python-sdk int…
esrakartalOpt Jul 21, 2025
e07c1b4
Fix order
esrakartalOpt Jul 21, 2025
1d61988
Remove unnecessary region implementation
esrakartalOpt Jul 24, 2025
e24a34e
Fix lint issues
esrakartalOpt Jul 24, 2025
80365fa
Fix test cases
esrakartalOpt Jul 24, 2025
174a7d0
Fix error
esrakartalOpt Jul 24, 2025
f83865f
Implemented reviews and added new tests
esrakartalOpt Jul 28, 2025
8e92fda
Merge branch 'master' into esra/FSSDK-11458_eu_hosting
esrakartalOpt Jul 30, 2025
dafb205
Fix test cases
esrakartalOpt Jul 30, 2025
c774dde
Implement comments
esrakartalOpt Jul 31, 2025
c645e73
Fix lint issue
esrakartalOpt Jul 31, 2025
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
18 changes: 16 additions & 2 deletions optimizely/event/event_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,10 @@ class EventFactory:
to record the events via the Optimizely Events API ("https://developers.optimizely.com/x/events/api/index.html")
"""

EVENT_ENDPOINT: Final = 'https://logx.optimizely.com/v1/events'
EVENT_ENDPOINTS: Final = {
'US': 'https://logx.optimizely.com/v1/events',
'EU': 'https://eu.logx.optimizely.com/v1/events'
}
HTTP_VERB: Final = 'POST'
HTTP_HEADERS: Final = {'Content-Type': 'application/json'}
ACTIVATE_EVENT_KEY: Final = 'campaign_activated'
Expand Down Expand Up @@ -97,7 +100,18 @@ def create_log_event(

event_params = event_batch.get_event_params()

return log_event.LogEvent(cls.EVENT_ENDPOINT, event_params, cls.HTTP_VERB, cls.HTTP_HEADERS)
region = user_context.region
if hasattr(region, 'value'):
region_str = region.value
elif region is None:
region_str = 'US' # Default to US
else:
region_str = str(region)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can consider using a simple string type for region. The region will be handled in type-safe way when building into datafile. It looks like fallback to "US" for safety is good enough?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jaeopt by string type do you mean using Region.US instead of string 'US'?
That's what I have been suggesting further down the code. Just we don't contradict each other.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean we get string-type of region from datafile, and we can pass it down all the way to EventDispatcher to determine the URL (with fallback to US). The source of this region is datafile. Not much value of this enum-based type checking. It may be risky if you use defined enum set for strong-typed SDKs when we add new countries in the server.


region_key = region_str.upper()
endpoint = cls.EVENT_ENDPOINTS.get(region_key, cls.EVENT_ENDPOINTS['US'])

return log_event.LogEvent(endpoint, event_params, cls.HTTP_VERB, cls.HTTP_HEADERS)

@classmethod
def _create_visitor(cls, event: Optional[user_event.UserEvent], logger: Logger) -> Optional[payload.Visitor]:
Expand Down
4 changes: 3 additions & 1 deletion optimizely/event/user_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from sys import version_info

from optimizely import version
from optimizely.project_config import Region


if version_info < (3, 8):
Expand Down Expand Up @@ -97,10 +98,11 @@ def __init__(
class EventContext:
""" Class respresenting User Event Context. """

def __init__(self, account_id: str, project_id: str, revision: str, anonymize_ip: bool):
def __init__(self, account_id: str, project_id: str, revision: str, anonymize_ip: bool, region: Region):
self.account_id = account_id
self.project_id = project_id
self.revision = revision
self.client_name = CLIENT_NAME
self.client_version = version.__version__
self.anonymize_ip = anonymize_ip
self.region = region or 'US'
Copy link
Preview

Copilot AI Jul 31, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fallback logic uses a string literal 'US' instead of the Region enum. Consider using self.region = region or Region.US for consistency with the type system.

Suggested change
self.region = region or 'US'
self.region = region or Region.US

Copilot uses AI. Check for mistakes.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I second htis use. If yuo have Region class somewhere, then we should call country attribute on the Region object.

12 changes: 10 additions & 2 deletions optimizely/event/user_event_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,11 @@ def create_impression_event(
variation = project_config.get_variation_from_id_by_experiment_id(experiment_id, variation_id)

event_context = user_event.EventContext(
project_config.account_id, project_config.project_id, project_config.revision, project_config.anonymize_ip,
project_config.account_id,
project_config.project_id,
project_config.revision,
project_config.anonymize_ip,
project_config.region
)

return user_event.ImpressionEvent(
Expand Down Expand Up @@ -115,7 +119,11 @@ def create_conversion_event(
"""

event_context = user_event.EventContext(
project_config.account_id, project_config.project_id, project_config.revision, project_config.anonymize_ip,
project_config.account_id,
project_config.project_id,
project_config.revision,
project_config.anonymize_ip,
project_config.region
)

return user_event.ConversionEvent(
Expand Down
16 changes: 13 additions & 3 deletions optimizely/event_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,10 @@ class EventBuilder:
""" Class which encapsulates methods to build events for tracking
impressions and conversions using the new V3 event API (batch). """

EVENTS_URL: Final = 'https://logx.optimizely.com/v1/events'
EVENTS_URLS: Final = {
'US': 'https://logx.optimizely.com/v1/events',
'EU': 'https://eu.logx.optimizely.com/v1/events'
}
HTTP_VERB: Final = 'POST'
HTTP_HEADERS: Final = {'Content-Type': 'application/json'}

Expand Down Expand Up @@ -266,7 +269,10 @@ def create_impression_event(

params[self.EventParams.USERS][0][self.EventParams.SNAPSHOTS].append(impression_params)

return Event(self.EVENTS_URL, params, http_verb=self.HTTP_VERB, headers=self.HTTP_HEADERS)
region = project_config.region.value if hasattr(project_config.region, 'value') else 'US'
events_url = self.EVENTS_URLS.get(str(region), self.EVENTS_URLS['US'])
Copy link
Preview

Copilot AI Jul 31, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fallback to string literal 'US' should use Region.US.value for consistency. Also, this hasattr check suggests uncertainty about the type - consider using isinstance(project_config.region, Region) for more explicit type checking.

Suggested change
region = project_config.region.value if hasattr(project_config.region, 'value') else 'US'
events_url = self.EVENTS_URLS.get(str(region), self.EVENTS_URLS['US'])
region = project_config.region.value if isinstance(project_config.region, Region) else Region.US.value
events_url = self.EVENTS_URLS.get(str(region), self.EVENTS_URLS[Region.US.value])

Copilot uses AI. Check for mistakes.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again, I agree with copilot lol


return Event(events_url, params, http_verb=self.HTTP_VERB, headers=self.HTTP_HEADERS)

def create_conversion_event(
self, project_config: ProjectConfig, event_key: str,
Expand All @@ -289,4 +295,8 @@ def create_conversion_event(
conversion_params = self._get_required_params_for_conversion(project_config, event_key, event_tags)

params[self.EventParams.USERS][0][self.EventParams.SNAPSHOTS].append(conversion_params)
return Event(self.EVENTS_URL, params, http_verb=self.HTTP_VERB, headers=self.HTTP_HEADERS)

region = project_config.region.value if hasattr(project_config.region, 'value') else 'US'
events_url = self.EVENTS_URLS.get(str(region), self.EVENTS_URLS['US'])
Copy link
Preview

Copilot AI Jul 31, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same issue as line 272 - the fallback to string literal 'US' should use Region.US.value for consistency, and the hasattr check could be replaced with more explicit type checking.

Suggested change
region = project_config.region.value if hasattr(project_config.region, 'value') else 'US'
events_url = self.EVENTS_URLS.get(str(region), self.EVENTS_URLS['US'])
region = project_config.region.value if isinstance(project_config.region, enums.Region) else enums.Region.US.value
events_url = self.EVENTS_URLS.get(str(region), self.EVENTS_URLS[enums.Region.US.value])

Copilot uses AI. Check for mistakes.


return Event(events_url, params, http_verb=self.HTTP_VERB, headers=self.HTTP_HEADERS)
13 changes: 13 additions & 0 deletions optimizely/project_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import json
from typing import TYPE_CHECKING, Optional, Type, TypeVar, cast, Any, Iterable, List
from sys import version_info
from enum import Enum

from . import entities
from . import exceptions
Expand Down Expand Up @@ -42,6 +43,11 @@
EntityClass = TypeVar('EntityClass')


class Region(str, Enum):
US = 'US'
EU = 'EU'


class ProjectConfig:
""" Representation of the Optimizely project config. """

Expand Down Expand Up @@ -85,6 +91,13 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any):
self.host_for_odp: Optional[str] = None
self.all_segments: list[str] = []

region_value = config.get('region')
self.region: Region
if region_value == Region.EU.value:
self.region = Region.EU
else:
self.region = Region.US
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another area we can get benefits with string type. No need to change the code when we add countries.


# Utility maps for quick lookup
self.group_id_map: dict[str, entities.Group] = self._generate_key_map(self.groups, 'id', entities.Group)
self.experiment_id_map: dict[str, entities.Experiment] = self._generate_key_map(
Expand Down
24 changes: 23 additions & 1 deletion tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from optimizely import logger
from optimizely import optimizely
from optimizely.helpers import enums
from optimizely.project_config import ProjectConfig
from optimizely.project_config import ProjectConfig, Region
from . import base


Expand Down Expand Up @@ -154,6 +154,28 @@ def test_init(self):
self.assertEqual(expected_variation_key_map, self.project_config.variation_key_map)
self.assertEqual(expected_variation_id_map, self.project_config.variation_id_map)

def test_region_when_no_region(self):
""" Test that region defaults to 'US' when not specified in the config. """
config_dict = copy.deepcopy(self.config_dict_with_multiple_experiments)
opt_obj = optimizely.Optimizely(json.dumps(config_dict))
project_config = opt_obj.config_manager.get_config()
self.assertEqual(project_config.region, Region.US)

def test_region_when_specified_in_datafile(self):
""" Test that region is set to 'US' when specified in the config. """
config_dict_us = copy.deepcopy(self.config_dict_with_multiple_experiments)
config_dict_us['region'] = 'US'
opt_obj_us = optimizely.Optimizely(json.dumps(config_dict_us))
project_config_us = opt_obj_us.config_manager.get_config()
self.assertEqual(project_config_us.region, Region.US)

""" Test that region is set to 'EU' when specified in the config. """
config_dict_eu = copy.deepcopy(self.config_dict_with_multiple_experiments)
config_dict_eu['region'] = 'EU'
opt_obj_eu = optimizely.Optimizely(json.dumps(config_dict_eu))
project_config_eu = opt_obj_eu.config_manager.get_config()
self.assertEqual(project_config_eu.region, Region.EU)

def test_cmab_field_population(self):
""" Test that the cmab field is populated correctly in experiments."""

Expand Down
Loading