-
Notifications
You must be signed in to change notification settings - Fork 36
feat: add odp rest api manager #398
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
Changes from 1 commit
f6a767f
0d254cb
92099d4
c9db45a
94e546b
14a1f82
74b2ff8
0d541b5
0c669af
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
# Copyright 2022, 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 Any, Dict | ||
|
||
|
||
class OdpEvent: | ||
""" Representation of an odp event which can be sent to the Optimizely odp platform. """ | ||
|
||
def __init__(self, type: str, action: str, | ||
identifiers: Dict[str, str], data: Dict[str, Any]) -> None: | ||
self.type = type, | ||
self.action = action, | ||
self.identifiers = identifiers, | ||
self.data = data |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
# Copyright 2022, 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 | ||
|
||
import json | ||
from typing import Optional, List | ||
|
||
import requests | ||
from requests.exceptions import RequestException, ConnectionError, Timeout, JSONDecodeError, InvalidURL | ||
|
||
from optimizely import logger as optimizely_logger | ||
from optimizely.helpers.enums import Errors, OdpRestApiConfig | ||
from optimizely.odp.odp_event import OdpEvent | ||
|
||
""" | ||
ODP REST Events API | ||
- https://api.zaius.com/v3/events | ||
- test ODP public API key = "W4WzcEs-ABgXorzY7h1LCQ" | ||
|
||
[Event Request] | ||
curl -i -H 'Content-Type: application/json' -H 'x-api-key: W4WzcEs-ABgXorzY7h1LCQ' -X POST -d '{"type":"fullstack","action":"identified","identifiers":{"vuid": "123","fs_user_id": "abc"},"data":{"idempotence_id":"xyz","source":"swift-sdk"}}' https://api.zaius.com/v3/events | ||
[Event Response] | ||
{"title":"Accepted","status":202,"timestamp":"2022-06-30T20:59:52.046Z"} | ||
""" | ||
|
||
|
||
class ZaiusRestApiManager: | ||
"""Provides an internal service for ODP event REST api access.""" | ||
|
||
def __init__(self, logger: Optional[optimizely_logger.Logger] = None): | ||
self.logger = logger or optimizely_logger.NoOpLogger() | ||
|
||
def sendOdpEvents(self, api_key: str, api_host: str, events: List[OdpEvent]) -> Optional[bool]: | ||
""" | ||
Dispatch the event being represented by the OdpEvent object. | ||
|
||
Args: | ||
api_key: public api key | ||
api_host: domain url of the host | ||
events: list of odp events to be sent to optimizely's odp platform. | ||
|
||
Returns: | ||
retry is True - if network or server error (5xx), otherwise False | ||
""" | ||
can_retry: bool = True | ||
Mat001 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
url = f'{api_host}/v3/events' | ||
request_headers = {'content-type': 'application/json', 'x-api-key': api_key} | ||
|
||
try: | ||
response = requests.post(url=url, | ||
headers=request_headers, | ||
data=json.dumps(events), | ||
Mat001 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
timeout=OdpRestApiConfig.REQUEST_TIMEOUT) | ||
|
||
response.raise_for_status() | ||
can_retry = False | ||
|
||
except (ConnectionError, Timeout): | ||
self.logger.error(Errors.ODP_EVENT_FAILED.format('network error')) | ||
# we do retry, can_retry = True | ||
except JSONDecodeError: | ||
Mat001 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.logger.error(Errors.ODP_EVENT_FAILED.format('JSON decode error')) | ||
can_retry = False | ||
except InvalidURL: | ||
self.logger.error(Errors.ODP_EVENT_FAILED.format('invalid URL')) | ||
can_retry = False | ||
except RequestException as err: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think so, but can you confirm that this catches all other exceptions? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @jaeopt yes, confirm. We use the same exception handling in event_dispatcher and fetch_datafile: It'll catch all these: https://requests.readthedocs.io/en/latest/_modules/requests/exceptions/ |
||
if 400 <= err.response.status_code < 500: | ||
self.logger.error(Errors.ODP_EVENT_FAILED.format(err)) | ||
Mat001 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
can_retry = False | ||
else: | ||
self.logger.error(Errors.ODP_EVENT_FAILED.format(err)) | ||
# we do retry, can_retry = True | ||
finally: | ||
return can_retry | ||
Mat001 marked this conversation as resolved.
Show resolved
Hide resolved
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
# Copyright 2022, 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 requests import Response | ||
from typing import Optional | ||
|
||
|
||
def fake_server_response(status_code: int = None, content: bytes = None, url: str = None) -> Optional[Response]: | ||
Mat001 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""Mock the server response.""" | ||
response = Response() | ||
response.status_code = status_code | ||
if content: | ||
response._content = content.encode('utf-8') | ||
response.url = url | ||
return response |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
# Copyright 2022, 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 json | ||
from unittest import mock | ||
|
||
from requests import exceptions as request_exception | ||
|
||
from tests.helpers_for_tests import fake_server_response | ||
from optimizely.helpers.enums import OdpRestApiConfig | ||
from optimizely.odp.zaius_rest_api_manager import ZaiusRestApiManager | ||
from . import base | ||
|
||
|
||
class ZaiusRestApiManagerTest(base.BaseTest): | ||
user_key = "vuid" | ||
user_value = "test-user-value" | ||
api_key = "test-api-key" | ||
api_host = "test-host" | ||
|
||
events = [ | ||
{"type": "t1", "action": "a1", "identifiers": {"id-key-1": "id-value-1"}, "data": {"key-1": "value1"}}, | ||
{"type": "t2", "action": "a2", "identifiers": {"id-key-2": "id-value-2"}, "data": {"key-2": "value2"}}, | ||
] | ||
|
||
def test_send_odp_events__valid_request(self): | ||
with mock.patch('requests.post') as mock_request_post: | ||
api = ZaiusRestApiManager() | ||
api.sendOdpEvents(api_key=self.api_key, | ||
api_host=self.api_host, | ||
events=self.events) | ||
|
||
request_headers = {'content-type': 'application/json', 'x-api-key': self.api_key} | ||
mock_request_post.assert_called_once_with(url=self.api_host + "/v3/events", | ||
headers=request_headers, | ||
data=json.dumps(self.events), | ||
timeout=OdpRestApiConfig.REQUEST_TIMEOUT) | ||
|
||
def testSendOdpEvents_success(self): | ||
with mock.patch('requests.post') as mock_request_post: | ||
mock_request_post.return_value = \ | ||
fake_server_response(status_code=200) | ||
|
||
api = ZaiusRestApiManager() | ||
response = api.sendOdpEvents(api_key=self.api_key, | ||
Mat001 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
api_host=self.api_host, | ||
events=self.events) # content of events doesn't matter for the test | ||
|
||
self.assertFalse(response) | ||
|
||
def testSendOdpEvents_network_error_retry(self): | ||
with mock.patch('requests.post', | ||
side_effect=request_exception.ConnectionError('Connection error')) as mock_request_post, \ | ||
mock.patch('optimizely.logger') as mock_logger: | ||
api = ZaiusRestApiManager(logger=mock_logger) | ||
response = api.sendOdpEvents(api_key=self.api_key, | ||
api_host=self.api_host, | ||
events=self.events) | ||
|
||
self.assertTrue(response) | ||
mock_request_post.assert_called_once() | ||
mock_logger.error.assert_called_once_with('ODP event send failed (network error).') | ||
|
||
def testSendOdpEvents_400_no_retry(self): | ||
with mock.patch('requests.post') as mock_request_post, \ | ||
mock.patch('optimizely.logger') as mock_logger: | ||
mock_request_post.return_value = fake_server_response(status_code=403, url=self.api_host) | ||
|
||
api = ZaiusRestApiManager(logger=mock_logger) | ||
response = api.sendOdpEvents(api_key=self.api_key, | ||
api_host=self.api_host, | ||
events=self.events) | ||
|
||
self.assertFalse(response) | ||
mock_request_post.assert_called_once() | ||
mock_logger.error.assert_called_once_with('ODP event send failed (403 Client Error: None for url: test-host).') | ||
|
||
def testSendOdpEvents_500_retry(self): | ||
with mock.patch('requests.post') as mock_request_post, \ | ||
mock.patch('optimizely.logger') as mock_logger: | ||
mock_request_post.return_value = fake_server_response(status_code=500, url=self.api_host) | ||
|
||
api = ZaiusRestApiManager(logger=mock_logger) | ||
response = api.sendOdpEvents(api_key=self.api_key, | ||
api_host=self.api_host, | ||
events=self.events) | ||
|
||
self.assertTrue(response) | ||
mock_request_post.assert_called_once() | ||
mock_logger.error.assert_called_once_with('ODP event send failed (500 Server Error: None for url: test-host).') |
Uh oh!
There was an error while loading. Please reload this page.