-
Notifications
You must be signed in to change notification settings - Fork 23
feat: implement basic functionality of OFREP provider #88
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
beeme1mr
merged 8 commits into
open-feature:main
from
federicobond:feat/ofrep-provider-impl
Oct 2, 2024
Merged
Changes from 3 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
a9c96f2
feat: implement basic functionality of OFREP provider
federicobond 535fd27
refactor: reduce _resolve function complexity
federicobond b06c54a
add types-requests dependency
gruebel ecbdbaf
refactor: use NoReturn for _handle_error type
federicobond 873f5e2
feat: implement type checking for resolved values
federicobond b7b5e27
feat: take a headers_factory callable instead of fixed headers in OFR…
federicobond dfe87eb
Merge branch 'main' into feat/ofrep-provider-impl
lukas-reining b15f651
Merge branch 'main' into feat/ofrep-provider-impl
beeme1mr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
155 changes: 143 additions & 12 deletions
155
providers/openfeature-provider-ofrep/src/openfeature/contrib/provider/ofrep/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,49 +1,180 @@ | ||
| from typing import List, Optional, Union | ||
| import re | ||
| from datetime import datetime, timedelta, timezone | ||
| from email.utils import parsedate_to_datetime | ||
| from typing import Any, Dict, List, Optional, Union | ||
| from urllib.parse import urljoin | ||
|
|
||
| import requests | ||
| from requests.exceptions import JSONDecodeError | ||
|
|
||
| from openfeature.evaluation_context import EvaluationContext | ||
| from openfeature.flag_evaluation import FlagResolutionDetails | ||
| from openfeature.exception import ( | ||
| ErrorCode, | ||
| FlagNotFoundError, | ||
| GeneralError, | ||
| InvalidContextError, | ||
| OpenFeatureError, | ||
| ParseError, | ||
| TargetingKeyMissingError, | ||
| ) | ||
| from openfeature.flag_evaluation import FlagResolutionDetails, Reason | ||
| from openfeature.hook import Hook | ||
| from openfeature.provider import AbstractProvider, Metadata | ||
|
|
||
| __all__ = ["OFREPProvider"] | ||
|
|
||
|
|
||
| class OFREPProvider(AbstractProvider): | ||
| def __init__( | ||
| self, | ||
| base_url: str, | ||
| *, | ||
| headers: Optional[Dict[str, str]] = None, | ||
| timeout: float = 5.0, | ||
| ): | ||
| self.base_url = base_url | ||
| self.headers = headers | ||
| self.timeout = timeout | ||
| self.retry_after: Optional[datetime] = None | ||
| self.session = requests.Session() | ||
| self.session.headers["User-Agent"] = "OpenFeature/1.0.0" | ||
| if headers: | ||
| self.session.headers.update(headers) | ||
|
|
||
| def get_metadata(self) -> Metadata: | ||
| return Metadata(name="OpenFeature Remote Evaluation Protocol Provider") | ||
|
|
||
| def get_provider_hooks(self) -> List[Hook]: | ||
| return [] | ||
|
|
||
| def resolve_boolean_details( # type: ignore[empty-body] | ||
| def resolve_boolean_details( | ||
| self, | ||
| flag_key: str, | ||
| default_value: bool, | ||
| evaluation_context: Optional[EvaluationContext] = None, | ||
| ) -> FlagResolutionDetails[bool]: ... | ||
| ) -> FlagResolutionDetails[bool]: | ||
| return self._resolve(flag_key, default_value, evaluation_context) | ||
|
|
||
| def resolve_string_details( # type: ignore[empty-body] | ||
| def resolve_string_details( | ||
| self, | ||
| flag_key: str, | ||
| default_value: str, | ||
| evaluation_context: Optional[EvaluationContext] = None, | ||
| ) -> FlagResolutionDetails[str]: ... | ||
| ) -> FlagResolutionDetails[str]: | ||
| return self._resolve(flag_key, default_value, evaluation_context) | ||
|
|
||
| def resolve_integer_details( # type: ignore[empty-body] | ||
| def resolve_integer_details( | ||
| self, | ||
| flag_key: str, | ||
| default_value: int, | ||
| evaluation_context: Optional[EvaluationContext] = None, | ||
| ) -> FlagResolutionDetails[int]: ... | ||
| ) -> FlagResolutionDetails[int]: | ||
| return self._resolve(flag_key, default_value, evaluation_context) | ||
|
|
||
| def resolve_float_details( # type: ignore[empty-body] | ||
| def resolve_float_details( | ||
| self, | ||
| flag_key: str, | ||
| default_value: float, | ||
| evaluation_context: Optional[EvaluationContext] = None, | ||
| ) -> FlagResolutionDetails[float]: ... | ||
| ) -> FlagResolutionDetails[float]: | ||
| return self._resolve(flag_key, default_value, evaluation_context) | ||
|
|
||
| def resolve_object_details( # type: ignore[empty-body] | ||
| def resolve_object_details( | ||
| self, | ||
| flag_key: str, | ||
| default_value: Union[dict, list], | ||
| evaluation_context: Optional[EvaluationContext] = None, | ||
| ) -> FlagResolutionDetails[Union[dict, list]]: ... | ||
| ) -> FlagResolutionDetails[Union[dict, list]]: | ||
| return self._resolve(flag_key, default_value, evaluation_context) | ||
|
|
||
| def _resolve( | ||
| self, | ||
| flag_key: str, | ||
| default_value: Union[bool, str, int, float, dict, list], | ||
| evaluation_context: Optional[EvaluationContext] = None, | ||
| ) -> FlagResolutionDetails[Any]: | ||
federicobond marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| now = datetime.now(timezone.utc) | ||
| if self.retry_after and now <= self.retry_after: | ||
| raise GeneralError( | ||
| f"OFREP evaluation paused due to TooManyRequests until {self.retry_after}" | ||
| ) | ||
| elif self.retry_after: | ||
| self.retry_after = None | ||
|
|
||
| try: | ||
| response = self.session.post( | ||
| urljoin(self.base_url, f"/ofrep/v1/evaluate/flags/{flag_key}"), | ||
| json=_build_request_data(evaluation_context), | ||
| timeout=self.timeout, | ||
| ) | ||
| response.raise_for_status() | ||
|
|
||
| except requests.RequestException as e: | ||
| self._handle_error(e) | ||
|
|
||
| try: | ||
| data = response.json() | ||
federicobond marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| except JSONDecodeError as e: | ||
| raise ParseError(str(e)) from e | ||
|
|
||
| return FlagResolutionDetails( | ||
| value=data["value"], | ||
| reason=Reason[data["reason"]], | ||
| variant=data["variant"], | ||
| flag_metadata=data["metadata"], | ||
| ) | ||
|
|
||
| def _handle_error(self, exception: requests.RequestException) -> None: | ||
federicobond marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| response = exception.response | ||
| if response is None: | ||
| raise GeneralError(str(exception)) from exception | ||
|
|
||
| if response.status_code == 429: | ||
| retry_after = response.headers.get("Retry-After") | ||
| self.retry_after = _parse_retry_after(retry_after) | ||
| raise GeneralError( | ||
| f"Rate limited, retry after: {retry_after}" | ||
| ) from exception | ||
|
|
||
| try: | ||
| data = response.json() | ||
| except JSONDecodeError: | ||
| raise ParseError(str(exception)) from exception | ||
|
|
||
| error_code = ErrorCode(data["errorCode"]) | ||
| error_details = data["errorDetails"] | ||
|
|
||
| if response.status_code == 404: | ||
| raise FlagNotFoundError(error_details) from exception | ||
|
|
||
| if error_code == ErrorCode.PARSE_ERROR: | ||
| raise ParseError(error_details) from exception | ||
| if error_code == ErrorCode.TARGETING_KEY_MISSING: | ||
| raise TargetingKeyMissingError(error_details) from exception | ||
| if error_code == ErrorCode.INVALID_CONTEXT: | ||
| raise InvalidContextError(error_details) from exception | ||
| if error_code == ErrorCode.GENERAL: | ||
| raise GeneralError(error_details) from exception | ||
|
|
||
| raise OpenFeatureError(error_code, error_details) from exception | ||
|
|
||
|
|
||
| def _build_request_data( | ||
| evaluation_context: Optional[EvaluationContext], | ||
| ) -> Dict[str, Any]: | ||
| data: Dict[str, Any] = {} | ||
| if evaluation_context: | ||
| data["context"] = {} | ||
| if evaluation_context.targeting_key: | ||
| data["context"]["targetingKey"] = evaluation_context.targeting_key | ||
| data["context"].update(evaluation_context.attributes) | ||
| return data | ||
|
|
||
|
|
||
| def _parse_retry_after(retry_after: Optional[str]) -> Optional[datetime]: | ||
| if retry_after is None: | ||
| return None | ||
| if re.match(r"^\s*[0-9]+\s*$", retry_after): | ||
beeme1mr marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| seconds = int(retry_after) | ||
| return datetime.now(timezone.utc) + timedelta(seconds=seconds) | ||
| return parsedate_to_datetime(retry_after) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| import pytest | ||
|
|
||
| from openfeature.contrib.provider.ofrep import OFREPProvider | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def ofrep_provider(): | ||
| return OFREPProvider("http://localhost:8080") |
119 changes: 119 additions & 0 deletions
119
providers/openfeature-provider-ofrep/tests/test_provider.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| import pytest | ||
|
|
||
| from openfeature.contrib.provider.ofrep import OFREPProvider | ||
| from openfeature.evaluation_context import EvaluationContext | ||
| from openfeature.exception import ( | ||
| FlagNotFoundError, | ||
| GeneralError, | ||
| InvalidContextError, | ||
| ParseError, | ||
| ) | ||
| from openfeature.flag_evaluation import FlagResolutionDetails, Reason | ||
|
|
||
|
|
||
| def test_provider_init(): | ||
| OFREPProvider("http://localhost:8080", headers={"Authorization": "Bearer token"}) | ||
|
|
||
|
|
||
| def test_provider_successful_resolution(ofrep_provider, requests_mock): | ||
| requests_mock.post( | ||
| "http://localhost:8080/ofrep/v1/evaluate/flags/flag_key", | ||
| json={ | ||
| "key": "flag_key", | ||
| "reason": "TARGETING_MATCH", | ||
| "variant": "true", | ||
| "metadata": {"foo": "bar"}, | ||
| "value": True, | ||
| }, | ||
| ) | ||
|
|
||
| resolution = ofrep_provider.resolve_boolean_details("flag_key", False) | ||
|
|
||
| assert resolution == FlagResolutionDetails( | ||
| value=True, | ||
| reason=Reason.TARGETING_MATCH, | ||
| variant="true", | ||
| flag_metadata={"foo": "bar"}, | ||
| ) | ||
|
|
||
|
|
||
| def test_provider_flag_not_found(ofrep_provider, requests_mock): | ||
| requests_mock.post( | ||
| "http://localhost:8080/ofrep/v1/evaluate/flags/flag_key", | ||
| status_code=404, | ||
| json={ | ||
| "key": "flag_key", | ||
| "errorCode": "FLAG_NOT_FOUND", | ||
| "errorDetails": "Flag 'flag_key' not found", | ||
| }, | ||
| ) | ||
|
|
||
| with pytest.raises(FlagNotFoundError): | ||
| ofrep_provider.resolve_boolean_details("flag_key", False) | ||
|
|
||
|
|
||
| def test_provider_invalid_context(ofrep_provider, requests_mock): | ||
| requests_mock.post( | ||
| "http://localhost:8080/ofrep/v1/evaluate/flags/flag_key", | ||
| status_code=400, | ||
| json={ | ||
| "key": "flag_key", | ||
| "errorCode": "INVALID_CONTEXT", | ||
| "errorDetails": "Invalid context provided", | ||
| }, | ||
| ) | ||
|
|
||
| with pytest.raises(InvalidContextError): | ||
| ofrep_provider.resolve_boolean_details("flag_key", False) | ||
|
|
||
|
|
||
| def test_provider_invalid_response(ofrep_provider, requests_mock): | ||
| requests_mock.post( | ||
| "http://localhost:8080/ofrep/v1/evaluate/flags/flag_key", text="invalid" | ||
| ) | ||
|
|
||
| with pytest.raises(ParseError): | ||
| ofrep_provider.resolve_boolean_details("flag_key", False) | ||
|
|
||
|
|
||
| def test_provider_evaluation_context(ofrep_provider, requests_mock): | ||
| def match_request_json(request): | ||
| return request.json() == {"context": {"targetingKey": "1", "foo": "bar"}} | ||
|
|
||
| requests_mock.post( | ||
| "http://localhost:8080/ofrep/v1/evaluate/flags/flag_key", | ||
| json={ | ||
| "key": "flag_key", | ||
| "reason": "TARGETING_MATCH", | ||
| "variant": "true", | ||
| "metadata": {}, | ||
| "value": True, | ||
| }, | ||
| additional_matcher=match_request_json, | ||
| ) | ||
|
|
||
| context = EvaluationContext("1", {"foo": "bar"}) | ||
| resolution = ofrep_provider.resolve_boolean_details( | ||
| "flag_key", False, evaluation_context=context | ||
| ) | ||
|
|
||
| assert resolution == FlagResolutionDetails( | ||
| value=True, | ||
| reason=Reason.TARGETING_MATCH, | ||
| variant="true", | ||
| ) | ||
|
|
||
|
|
||
| def test_provider_retry_after_shortcircuit_resolution(ofrep_provider, requests_mock): | ||
| requests_mock.post( | ||
| "http://localhost:8080/ofrep/v1/evaluate/flags/flag_key", | ||
| status_code=429, | ||
| headers={"Retry-After": "1"}, | ||
| ) | ||
|
|
||
| with pytest.raises(GeneralError, match="Rate limited, retry after: 1"): | ||
| ofrep_provider.resolve_boolean_details("flag_key", False) | ||
| with pytest.raises( | ||
| GeneralError, match="OFREP evaluation paused due to TooManyRequests" | ||
| ): | ||
| ofrep_provider.resolve_boolean_details("flag_key", False) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.