Class: Optimizely::DefaultCmabClient

Inherits:
Object
  • Object
show all
Defined in:
lib/optimizely/cmab/cmab_client.rb

Instance Method Summary collapse

Constructor Details

#initialize(http_client: nil, retry_config: nil, logger: nil, prediction_endpoint: nil) ⇒ DefaultCmabClient

Client for interacting with the CMAB service. Provides methods to fetch decisions with optional retry logic.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/optimizely/cmab/cmab_client.rb', line 46

def initialize(http_client: nil, retry_config: nil, logger: nil, prediction_endpoint: nil)
  # Initialize the CMAB client.
  # Args:
  #   http_client: HTTP client for making requests.
  #   retry_config: Configuration for retry settings.
  #   logger: Logger for logging errors and info.
  #   prediction_endpoint: Custom prediction endpoint URL template.
  #                        Use #{rule_id} as placeholder for rule_id.
  @http_client = http_client || DefaultHttpClient.new
  @retry_config = retry_config || CmabRetryConfig.new
  @logger = logger || NoOpLogger.new
  @prediction_endpoint = if prediction_endpoint.to_s.strip.empty?
                           'https://prediction.cmab.optimizely.com/predict/%s'
                         else
                           prediction_endpoint
                         end
end

Instance Method Details

#_do_fetch(url, request_body, timeout) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/optimizely/cmab/cmab_client.rb', line 93

def _do_fetch(url, request_body, timeout)
  # Perform a single fetch request to the CMAB prediction service.

  # Args:
  #   url: The endpoint URL.
  #   request_body: The request payload.
  #   timeout: Maximum wait time for the request to respond in seconds.
  # Returns:
  #   The variation ID from the response.

  headers = {'Content-Type' => 'application/json'}
  begin
    response = @http_client.post(url, json: request_body, headers: headers, timeout: timeout.to_i)
  rescue StandardError => e
    error_message = Optimizely::Helpers::Constants::CMAB_FETCH_FAILED % e.message
    @logger.log(Logger::ERROR, error_message)
    raise CmabFetchError, error_message
  end

  unless (200..299).include?(response.status_code)
    error_message = Optimizely::Helpers::Constants::CMAB_FETCH_FAILED % response.status_code
    @logger.log(Logger::ERROR, error_message)
    raise CmabFetchError, error_message
  end

  begin
    body = response.json
  rescue JSON::ParserError, Optimizely::CmabInvalidResponseError
    error_message = Optimizely::Helpers::Constants::INVALID_CMAB_FETCH_RESPONSE
    @logger.log(Logger::ERROR, error_message)
    raise CmabInvalidResponseError, error_message
  end

  unless validate_response(body)
    error_message = Optimizely::Helpers::Constants::INVALID_CMAB_FETCH_RESPONSE
    @logger.log(Logger::ERROR, error_message)
    raise CmabInvalidResponseError, error_message
  end

  body['predictions'][0]['variation_id']
end

#_do_fetch_with_retry(url, request_body, retry_config, timeout) ⇒ Object



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/optimizely/cmab/cmab_client.rb', line 150

def _do_fetch_with_retry(url, request_body, retry_config, timeout)
  # Perform a fetch request with retry logic.
  # Args:
  #   url: The endpoint URL.
  #   request_body: The request payload.
  #   retry_config: Configuration for retry settings.
  #   timeout: Maximum wait time for the request to respond in seconds.
  # Returns:
  #   The variation ID from the response.

  backoff = retry_config.initial_backoff

  (0..retry_config.max_retries).each do |attempt|
    variation_id = _do_fetch(url, request_body, timeout)
    return variation_id
  rescue StandardError => e
    if attempt < retry_config.max_retries
      @logger.log(Logger::INFO, "Retrying CMAB request (attempt #{attempt + 1}) after #{backoff} seconds...")
      Kernel.sleep(backoff)

      backoff = [
        backoff * retry_config.backoff_multiplier,
        retry_config.max_backoff
      ].min
    else
      @logger.log(Logger::ERROR, "Max retries exceeded for CMAB request: #{e.message}")
      raise Optimizely::CmabFetchError, "CMAB decision fetch failed (#{e.message})."
    end
  end
end

#fetch_decision(rule_id, user_id, attributes, cmab_uuid, timeout: MAX_WAIT_TIME) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/optimizely/cmab/cmab_client.rb', line 64

def fetch_decision(rule_id, user_id, attributes, cmab_uuid, timeout: MAX_WAIT_TIME)
  # Fetches a decision from the CMAB service.
  # Args:
  #   rule_id: The rule ID for the experiment.
  #   user_id: The user ID for the request.
  #   attributes: User attributes for the request.
  #   cmab_uuid: Unique identifier for the CMAB request.
  #   timeout: Maximum wait time for the request to respond in seconds. (default is 10 seconds).
  # Returns:
  #   The variation ID.
  url = format(@prediction_endpoint, rule_id)
  cmab_attributes = attributes.map { |key, value| {'id' => key.to_s, 'value' => value, 'type' => 'custom_attribute'} }

  request_body = {
    instances: [{
      visitorId: user_id,
      experimentId: rule_id,
      attributes: cmab_attributes,
      cmabUUID: cmab_uuid
    }]
  }

  if @retry_config && @retry_config.max_retries.to_i.positive?
    _do_fetch_with_retry(url, request_body, @retry_config, timeout)
  else
    _do_fetch(url, request_body, timeout)
  end
end

#validate_response(body) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/optimizely/cmab/cmab_client.rb', line 135

def validate_response(body)
  # Validate the response structure from the CMAB service.
  # Args:
  #   body: The JSON response body to validate.
  # Returns:
  #   true if valid, false otherwise.

  body.is_a?(Hash) &&
    body.key?('predictions') &&
    body['predictions'].is_a?(Array) &&
    !body['predictions'].empty? &&
    body['predictions'][0].is_a?(Hash) &&
    body['predictions'][0].key?('variation_id')
end