diff --git a/setup.py b/setup.py index 1bf7d6f..dc64293 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setuptools.setup( name="split_openfeature", - version="0.1.0", + version="1.0.0", author="Robert Grassian", author_email="robert.grassian@split.io", description="The official Python Split Provider for OpenFeature", diff --git a/split_openfeature/__init__.py b/split_openfeature/__init__.py index 29aab60..0af51b8 100644 --- a/split_openfeature/__init__.py +++ b/split_openfeature/__init__.py @@ -1 +1,3 @@ from split_openfeature.split_provider import SplitProvider +from split_openfeature.split_client_wrapper import SplitClientWrapper + diff --git a/split_openfeature/split_client_wrapper.py b/split_openfeature/split_client_wrapper.py new file mode 100644 index 0000000..09a8419 --- /dev/null +++ b/split_openfeature/split_client_wrapper.py @@ -0,0 +1,69 @@ +from splitio import get_factory +from splitio.client.client import Client +from splitio.exceptions import TimeoutException +import logging + +_LOGGER = logging.getLogger(__name__) + +class SplitClientWrapper(): + + def __init__(self, initial_context): + self.sdk_ready = False + self.split_client = None + + if not self._validate_context(initial_context): + raise AttributeError() + + if initial_context.get("SplitClient") != None: + self.split_client = initial_context.get("SplitClient") + self._factory = self.split_client._factory + return + + api_key = initial_context.get("SdkKey") + config = {} + if initial_context.get("ConfigOptions") != None: + config = initial_context.get("ConfigOptions") + + self._factory = get_factory(api_key, config=config) + ready_block_time = 10 + if initial_context.get("ReadyBlockTime") != None: + ready_block_time = initial_context.get("ReadyBlockTime") + + try: + self._factory.block_until_ready(ready_block_time) + self.sdk_ready = True + except TimeoutException: + _LOGGER.debug("Split SDK timed out") + + self.split_client = self._factory.client() + + def is_sdk_ready(self): + if self.sdk_ready: + return True + + try: + self._factory.block_until_ready(0.1) + self.sdk_ready = True + except TimeoutException: + _LOGGER.debug("Split SDK timed out") + + return self.sdk_ready + + def _validate_context(self, initial_context): + if initial_context != None and not isinstance(initial_context, dict): + _LOGGER.error("SplitClientWrapper: initial_context must be of type `dict`") + return False + + if initial_context.get("SplitClient") == None and initial_context.get("SdkKey") == None: + _LOGGER.error("SplitClientWrapper: initial_context must contain keys `SplitClient` or `SdkKey`") + return False + + if initial_context.get("SdkKey") != None and not isinstance(initial_context.get("SdkKey"), str): + _LOGGER.error("SplitClientWrapper: key `SdkKey` must be of type `str`") + return False + + if initial_context.get("ConfigOptions") != None and not isinstance(initial_context.get("ConfigOptions"), dict): + _LOGGER.error("SplitClientWrapper: key `ConfigOptions` must be of type `dict`") + return False + + return True \ No newline at end of file diff --git a/split_openfeature/split_provider.py b/split_openfeature/split_provider.py index 64029a3..d7a1366 100644 --- a/split_openfeature/split_provider.py +++ b/split_openfeature/split_provider.py @@ -6,28 +6,15 @@ from openfeature.exception import ErrorCode, GeneralError, ParseError, OpenFeatureError, TargetingKeyMissingError from openfeature.flag_evaluation import Reason, FlagResolutionDetails from openfeature.provider import AbstractProvider, Metadata -from splitio import get_factory -from splitio.exceptions import TimeoutException +from split_openfeature.split_client_wrapper import SplitClientWrapper import json _LOGGER = logging.getLogger(__name__) class SplitProvider(AbstractProvider): - def __init__(self, api_key="", client=None): - if api_key == "" and client is None: - raise Exception("Must provide apiKey or Split Client") - - if api_key != "": - factory = get_factory(api_key) - try: - factory.block_until_ready(1) - except TimeoutException: - raise GeneralError("Error occurred initializing the client.") - - self.split_client = factory.client() - else: - self.split_client = client + def __init__(self, initial_context): + self._split_client_wrapper = SplitClientWrapper(initial_context) def get_metadata(self) -> Metadata: return Metadata("Split") @@ -59,13 +46,17 @@ def _evaluate_treatment(self, key: str, evaluation_context: EvaluationContext, d if evaluation_context is None: raise GeneralError("Evaluation Context must be provided for the Split Provider") + if not self._split_client_wrapper.is_sdk_ready(): + return SplitProvider.construct_flag_resolution(default_value, None, None, Reason.ERROR, + ErrorCode.PROVIDER_NOT_READY) + targeting_key = evaluation_context.targeting_key if not targeting_key: raise TargetingKeyMissingError("Missing targeting key") try: attributes = SplitProvider.transform_context(evaluation_context) - evaluated = self.split_client.get_treatment_with_config(targeting_key, key, attributes) + evaluated = self._split_client_wrapper.split_client.get_treatment_with_config(targeting_key, key, attributes) treatment = None config = None if evaluated != None: diff --git a/tests/test_client.py b/tests/test_client.py index 1735317..b8966a6 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -6,9 +6,7 @@ from splitio import get_factory from split_openfeature import SplitProvider - class TestClient(object): - # The following are splits with treatments defined in the split.yaml file my_feature = "my_feature" # 'on' when targeting_key='key', else 'off' some_other_feature = "some_other_feature" # 'off' @@ -21,7 +19,7 @@ def provider(self): split_factory = get_factory("localhost", config={"splitFile": "split.yaml"}) split_factory.block_until_ready(5) split_client = split_factory.client() - return SplitProvider(client=split_client) + return SplitProvider({"SplitClient": split_client}) @pytest.fixture def set_provider(self, provider): @@ -197,4 +195,9 @@ def test_obj_fail(self, client): assert details.error_code == ErrorCode.PARSE_ERROR assert details.reason == Reason.ERROR assert details.variant is None - ''' \ No newline at end of file + ''' + +class TestClientInternal(TestClient): + @pytest.fixture + def provider(self): + return SplitProvider({"SdkKey": "localhost", "ConfigOptions": {"splitFile": "split.yaml"}}) diff --git a/tests/test_split_client_wrapper.py b/tests/test_split_client_wrapper.py new file mode 100644 index 0000000..4ae27aa --- /dev/null +++ b/tests/test_split_client_wrapper.py @@ -0,0 +1,41 @@ +import pytest +from splitio import get_factory +from split_openfeature import SplitClientWrapper +import unittest + +class TestSplitClientWrapper(unittest.TestCase): + + def test_using_external_splitclient(self): + split_factory = get_factory("localhost", config={"splitFile": "split.yaml"}) + split_factory.block_until_ready(5) + split_client = split_factory.client() + wrapper = SplitClientWrapper({"SplitClient": split_client}) + assert wrapper.split_client != None + assert wrapper.is_sdk_ready() + + def test_using_internal_splitclient(self): + wrapper = SplitClientWrapper({"ReadyBlockTime": 1, "SdkKey": "localhost", "ConfigOptions": {"splitFile": "split.yaml"}}) + assert wrapper.split_client != None + assert wrapper.is_sdk_ready() + assert wrapper.sdk_ready == 1 + + + def test_sdk_not_ready(self): + wrapper = SplitClientWrapper({"ReadyBlockTime": 0.1, "SdkKey": "api", "ConfigOptions": {}}) + assert not wrapper.is_sdk_ready() + + def test_invalid_apikey(self): + with self.assertRaises(AttributeError) as context: + wrapper = SplitClientWrapper({"SdkKey": 123}) + + def test_invalid_config(self): + with self.assertRaises(AttributeError) as context: + wrapper = SplitClientWrapper({"SdkKey": "123", "ConfigOptions": "234"}) + + def test_no_params(self): + with self.assertRaises(AttributeError) as context: + wrapper = SplitClientWrapper({}) + + def test_reqwuired_params(self): + with self.assertRaises(AttributeError) as context: + wrapper = SplitClientWrapper({"ConfigOptions": {}}) diff --git a/tests/test_split_provider.py b/tests/test_split_provider.py index f1538bb..dda79f8 100644 --- a/tests/test_split_provider.py +++ b/tests/test_split_provider.py @@ -12,7 +12,7 @@ class TestProvider(object): def reset_client(self): self.client = MagicMock() - self.provider = SplitProvider(client=self.client) + self.provider = SplitProvider({"SplitClient": self.client}) def mock_client_return(self, val): self.client.get_treatment_with_config.return_value = (val, "{'prop':'val'}") @@ -267,4 +267,10 @@ def test_obj_error(self): except OpenFeatureError as e: assert e.error_code == ErrorCode.PARSE_ERROR except Exception: - fail("Unexpected exception occurred") \ No newline at end of file + fail("Unexpected exception occurred") + + def test_sdk_not_ready(self): + provider = SplitProvider({"ReadyBlockTime": 0.1,"SdkKey": "api"}) + details = provider.resolve_boolean_details(self.flag_name, False, self.eval_context) + assert details.error_code == ErrorCode.PROVIDER_NOT_READY + assert details.value == False