Skip to content

feat: add rest api manager #311

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 5 commits into from
Aug 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion lib/optimizely/helpers/constants.rb
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ module Constants

ODP_LOGS = {
FETCH_SEGMENTS_FAILED: 'Audience segments fetch failed (%s).',
ODP_EVENT_FAILED: 'ODP event send failed (invalid url).',
ODP_EVENT_FAILED: 'ODP event send failed (%s).',
ODP_NOT_ENABLED: 'ODP is not enabled.'
}.freeze

Expand Down
69 changes: 69 additions & 0 deletions lib/optimizely/odp/zaius_rest_api_manager.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# frozen_string_literal: true

#
# Copyright 2022, Optimizely and contributors
#
# 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.
#

require 'json'

module Optimizely
class ZaiusRestApiManager
# Interface that handles sending ODP events.

def initialize(logger: nil, proxy_config: nil)
@logger = logger || NoOpLogger.new
@proxy_config = proxy_config
end

# Send events to the ODP Events API.
#
# @param api_key - public api key
# @param api_host - domain url of the host
# @param events - array of events to send

def send_odp_events(api_key, api_host, events)
should_retry = false
url = "#{api_host}/v3/events"

headers = {'Content-Type' => 'application/json', 'x-api-key' => api_key.to_s}

begin
response = Helpers::HttpUtils.make_request(
url, :post, events.to_json, headers, Optimizely::Helpers::Constants::ODP_REST_API_CONFIG[:REQUEST_TIMEOUT], @proxy_config
)
rescue SocketError, Timeout::Error, Errno::ECONNRESET, Errno::EHOSTUNREACH, Errno::EFAULT, Errno::ENETUNREACH, Errno::ENETDOWN, Errno::ECONNREFUSED
log_failure('network error')
should_retry = true
return should_retry
rescue StandardError => e
log_failure(e)
return should_retry
end

status = response.code.to_i
if status >= 400
log_failure(!response.body.empty? ? response.body : "#{status}: #{response.message}")
should_retry = status >= 500
end
should_retry
end

private

def log_failure(message, level = Logger::ERROR)
@logger.log(level, format(Optimizely::Helpers::Constants::ODP_LOGS[:ODP_EVENT_FAILED], message))
end
end
end
99 changes: 99 additions & 0 deletions spec/odp/zaius_rest_api_manager_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# frozen_string_literal: true

#
# Copyright 2022, Optimizely and contributors
#
# 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.
#
require 'spec_helper'
require 'optimizely/odp/zaius_rest_api_manager'

describe Optimizely::ZaiusRestApiManager do
let(:user_key) { 'vuid' }
let(:user_value) { 'test-user-value' }
let(:api_key) { 'test-api-key' }
let(:api_host) { 'https://test-host.com' }
let(:spy_logger) { spy('logger') }
let(:events) do
[
{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'}}
]
end
let(:failure_response_data) do
{
title: 'Bad Request', status: 400, timestamp: '2022-07-01T20:44:00.945Z',
detail: {
invalids: [{event: 0, message: "missing 'type' field"}]
}
}.to_json
end

describe '.fetch_segments' do
it 'should send odp events successfully and return false' do
stub_request(:post, "#{api_host}/v3/events")
.with(
headers: {'content-type': 'application/json', 'x-api-key': api_key},
body: events.to_json
).to_return(status: 200)

api_manager = Optimizely::ZaiusRestApiManager.new
expect(spy_logger).not_to receive(:log)
should_retry = api_manager.send_odp_events(api_key, api_host, events)

expect(should_retry).to be false
end

it 'should return true on network error' do
allow(Optimizely::Helpers::HttpUtils).to receive(:make_request).and_raise(SocketError)
api_manager = Optimizely::ZaiusRestApiManager.new(logger: spy_logger)
expect(spy_logger).to receive(:log).with(Logger::ERROR, 'ODP event send failed (network error).')

should_retry = api_manager.send_odp_events(api_key, api_host, events)

expect(should_retry).to be true
end

it 'should return false with 400 error' do
stub_request(:post, "#{api_host}/v3/events")
.with(
body: events.to_json
).to_return(status: [400, 'Bad Request'], body: failure_response_data)

api_manager = Optimizely::ZaiusRestApiManager.new(logger: spy_logger)
expect(spy_logger).to receive(:log).with(
Logger::ERROR, 'ODP event send failed ({"title":"Bad Request","status":400,' \
'"timestamp":"2022-07-01T20:44:00.945Z","detail":{"invalids":' \
'[{"event":0,"message":"missing \'type\' field"}]}}).'
)

should_retry = api_manager.send_odp_events(api_key, api_host, events)

expect(should_retry).to be false
end

it 'should return true with 500 error' do
stub_request(:post, "#{api_host}/v3/events")
.with(
body: events.to_json
).to_return(status: [500, 'Internal Server Error'])

api_manager = Optimizely::ZaiusRestApiManager.new(logger: spy_logger)
expect(spy_logger).to receive(:log).with(Logger::ERROR, 'ODP event send failed (500: Internal Server Error).')

should_retry = api_manager.send_odp_events(api_key, api_host, events)

expect(should_retry).to be true
end
end
end