Class: Kameleoon::Client

Inherits:
Object
  • Object
show all
Includes:
Cookie, Exception, Request
Defined in:
lib/kameleoon/client.rb

Overview

Client for Kameleoon

Instance Method Summary collapse

Methods included from Cookie

#check_visitor_code, #obtain_hash_double, #read_and_write

Constructor Details

#initialize(site_code, path_config_file, blocking, interval, default_timeout, client_id = nil, client_secret = nil) ⇒ Client

You should create Client with the Client Factory only.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/kameleoon/client.rb', line 29

def initialize(site_code, path_config_file, blocking, interval, default_timeout, client_id = nil, client_secret = nil)
  config = YAML.load_file(path_config_file)
  @site_code = site_code
  @blocking = blocking
  @default_timeout = config['default_timeout'] || default_timeout # in ms
  @interval = config['actions_configuration_refresh_interval'].to_s + 'm' || interval
  @tracking_url = config['tracking_url'] || "https://api-ssx.kameleoon.com"
  @api_data_url = "https://api-data.kameleoon.com"
  @client_id = client_id || config['client_id']
  @client_secret = client_secret || config['client_secret']
  @data_maximum_size = config['visitor_data_maximum_size'] || 500 # mb
  @environment = config['environment'] || DEFAULT_ENVIRONMENT
  @verbose_mode = config['verbose_mode'] || false
  @experiments = []
  @feature_flags = []
  @data = {}
end

Instance Method Details

#activate_feature(visitor_code, feature_key, timeout = @default_timeout) ⇒ Object

Activate a feature toggle.

This method takes a visitor_code and feature_key (or feature_id) as mandatory arguments to check if the specified feature will be active for a given user. If such a user has never been associated with this feature flag, the SDK returns a boolean value randomly (true if the user should have this feature or false if not). If a user with a given visitorCode is already registered with this feature flag, it will detect the previous featureFlag value. You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.

Parameters:

  • visitor_code (String)
  • feature_key (String | Integer)

Raises:



246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/kameleoon/client.rb', line 246

def activate_feature(visitor_code, feature_key, timeout = @default_timeout)
  check_visitor_code(visitor_code)
  feature_flag = get_feature_flag(feature_key)
  id = feature_flag['id']
  if @blocking
    result = nil
    EM.synchrony do
      connexion_options = { :connect_timeout => (timeout.to_f / 1000.0) }
      request_options = {
        :path => get_experiment_register_url(visitor_code, id),
        :body => (data_not_sent(visitor_code).values.map { |data| data.obtain_full_post_text_line }.join("\n") || "").encode("UTF-8")
      }
      log "Activate feature request: " + request_options.inspect
      log "Activate feature connexion:" + connexion_options.inspect
      request = EM::Synchrony.sync post(request_options, @tracking_url, connexion_options)
      if is_successful(request)
        result = request.response
      else
        log "Failed to get activation:" + result.inspect
      end
      EM.stop
    end
    raise Exception::FeatureConfigurationNotFound.new(id) if result.nil?
    result.to_s != "null"

  else
    check_site_code_enable(feature_flag)
    visitor_data = @data.select { |key, value| key.to_s == visitor_code }.values.flatten! || []
    unless feature_flag['targetingSegment'].nil? || feature_flag['targetingSegment'].check_tree(visitor_data)
      raise Exception::NotTargeted.new(visitor_code)
    end

    if is_feature_flag_scheduled(feature_flag, Time.now.to_i)
      threshold = obtain_hash_double(visitor_code, {}, id)
      if threshold >= 1 - feature_flag['expositionRate']
        track_experiment(visitor_code, id, feature_flag["variations"].first['id'])
        true
      else
        track_experiment(visitor_code, id, REFERENCE, true)
        false
      end
    else
      false
    end
  end
end

#add_data(visitor_code, *args) ⇒ Object

Associate various data to a visitor.

Note that this method doesn’t return any value and doesn’t interact with the Kameleoon back-end servers by itself. Instead, the declared data is saved for future sending via the flush method. This reduces the number of server calls made, as data is usually grouped into a single server call triggered by the execution of the flush method.

Parameters:

  • visitor_code (String)

    Visitor code

  • data (...Data)

    Data to associate with the visitor code

Raises:



159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/kameleoon/client.rb', line 159

def add_data(visitor_code, *args)
  check_visitor_code(visitor_code)
  while ObjectSpace.memsize_of(@data) > @data_maximum_size * (2**20) do
    @data.shift
  end
  unless args.empty?
    if @data.key?(visitor_code)
      @data[visitor_code].push(*args)
    else
      @data[visitor_code] = args
    end
  end
end

#flush(visitor_code = nil) ⇒ Object

Flush the associated data.

The data added with the method add_data, is not directly sent to the kameleoon servers. It’s stored and accumulated until it is sent automatically by the trigger_experiment or track_conversion methods. With this method you can manually send it.

Parameters:

  • visitor_code (String) (defaults to: nil)

    Optional field - Visitor code, without visitor code it flush all of the data

Raises:



203
204
205
206
# File 'lib/kameleoon/client.rb', line 203

def flush(visitor_code = nil)
  check_visitor_code(visitor_code) unless visitor_code.nil?
  track_data(visitor_code)
end

#obtain_feature_variable(feature_key, variable_key) ⇒ Object

Retrieve a feature variable.

A feature variable can be changed easily via our web application.

Parameters:

  • feature_key (String | Integer)
  • variable_key (String)

Raises:



304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/kameleoon/client.rb', line 304

def obtain_feature_variable(feature_key, variable_key)
  feature_flag = get_feature_flag(feature_key)
  custom_json = JSON.parse(feature_flag["variations"].first['customJson'])[variable_key.to_s]
  if custom_json.nil?
    raise Exception::FeatureVariableNotFound.new("Feature variable not found")
  end
  case custom_json['type']
  when "Boolean"
    return custom_json['value'].downcase == "true"
  when "String"
    return custom_json['value']
  when "Number"
    return custom_json['value'].to_i
  when "JSON"
    return JSON.parse(custom_json['value'])
  else
    raise TypeError.new("Unknown type for feature variable")
  end
end

#obtain_variation_associated_data(variation_id) ⇒ Hash

Obtain variation associated data.

To retrieve JSON data associated with a variation, call the obtain_variation_associated_data method of our SDK. The JSON data usually represents some metadata of the variation, and can be configured on our web application interface or via our Automation API. This method takes the variationID as a parameter and will return the data as a json string. It will throw an exception () if the variation ID is wrong or corresponds to an experiment that is not yet online.

Parameters:

  • variation_id (Integer)

Returns:

  • (Hash)

    Hash object of the json object.

Raises:

  • (Kameleoon::Exception::VariationNotFound)

    Raise exception if the variation is not found.



223
224
225
226
227
228
229
230
# File 'lib/kameleoon/client.rb', line 223

def obtain_variation_associated_data(variation_id)
  variation = @experiments.map { |experiment| experiment['variations'] }.flatten.select { |variation| variation['id'].to_i == variation_id.to_i }.first
  if variation.nil?
    raise Exception::VariationConfigurationNotFound.new(variation_id)
  else
    JSON.parse(variation['customJson'])
  end
end

#obtain_visitor_code(cookies, top_level_domain, default_visitor_code = nil) ⇒ String

Note:

The implementation logic is described here:

Obtain a visitor code.

This method should be called to obtain the Kameleoon visitor_code for the current visitor. This is especially important when using Kameleoon in a mixed front-end and back-end environment, where user identification consistency must be guaranteed. First we check if a kameleoonVisitorCode cookie or query parameter associated with the current HTTP request can be found. If so, we will use this as the visitor identifier. If no cookie / parameter is found in the current request, we either randomly generate a new identifier, or use the defaultVisitorCode argument as identifier if it is passed. This allows our customers to use their own identifiers as visitor codes, should they wish to. This can have the added benefit of matching Kameleoon visitors with their own users without any additional look-ups in a matching table. In any case, the server-side (via HTTP header) kameleoonVisitorCode cookie is set with the value. Then this identifier value is finally returned by the method.

cookies = => ‘1234asdf4321fdsa’ visitor_code = obtain_visitor_code(cookies, ‘my-domaine.com’)

Parameters:

  • cookies (Hash)

    Cookies of the request.

  • top_level_domain (String)

    Top level domain of your website, settled while writing cookie.

  • default_visitor_code (String) (defaults to: nil)
    • Optional - Define your default visitor_code (maximum length 100 chars).

Returns:

  • (String)

    visitor code



73
74
75
# File 'lib/kameleoon/client.rb', line 73

def obtain_visitor_code(cookies, top_level_domain, default_visitor_code = nil)
  read_and_write(cookies, top_level_domain, cookies, default_visitor_code)
end

#retrieve_data_from_remote_source(key, timeout = @default_timeout) ⇒ Hash

The retrieved_data_from_remote_source method allows you to retrieve data (according to a key passed as argument) stored on a remote Kameleoon server. Usually data will be stored on our remote servers via the use of our Data API. This method, along with the availability of our highly scalable servers for this purpose, provides a convenient way to quickly store massive amounts of data that can be later retrieved for each of your visitors / users.

Parameters:

  • key (String)

    Key you want to retrieve data. This field is mandatory.

  • timeout (Int) (defaults to: @default_timeout)

    Timeout for request. Equals default_timeout in a config file. This field is optional.

Returns:

  • (Hash)

    Hash object of the json object.



336
337
338
339
340
341
342
343
344
345
346
# File 'lib/kameleoon/client.rb', line 336

def retrieve_data_from_remote_source(key, timeout = @default_timeout)
  connexion_options = { connect_timeout: (timeout.to_f / 1000.0) }
  path = get_api_data_request_url(key)
  log "Retrieve API Data connexion: #{connexion_options.inspect}"
  response = get_sync(@api_data_url + path, connexion_options)
  if is_successful_sync(response)
    JSON.parse(response.body) unless response.nil?
  else
    return nil
  end
end

#track_conversion(visitor_code, goal_id, revenue = 0.0) ⇒ Object

Track conversions on a particular goal

This method requires visitor_code and goal_id to track conversion on this particular goal. In addition, this method also accepts revenue as a third optional argument to track revenue. The visitor_code usually is identical to the one that was used when triggering the experiment. The track_conversion method doesn’t return any value. This method is non-blocking as the server call is made asynchronously.

Parameters:

  • visitor_code (String)

    Visitor code

  • goal_id (Integer)

    Id of the goal

  • revenue (Float) (defaults to: 0.0)

    Optional - Revenue of the conversion.

Raises:



186
187
188
189
190
# File 'lib/kameleoon/client.rb', line 186

def track_conversion(visitor_code, goal_id, revenue = 0.0)
  check_visitor_code(visitor_code)
  add_data(visitor_code, Conversion.new(goal_id, revenue))
  flush(visitor_code)
end

#trigger_experiment(visitor_code, experiment_id, timeout = @default_timeout) ⇒ Integer

Trigger an experiment.

If such a visitor_code has never been associated with any variation, the SDK returns a randomly selected variation. If a user with a given visitor_code is already registered with a variation, it will detect the previously registered variation and return the variation_id. You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.

Parameters:

  • visitor_code (String)

    Visitor code

  • experiment_id (Integer)

    Id of the experiment you want to trigger.

Returns:

  • (Integer)

    Id of the variation

Raises:



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
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/kameleoon/client.rb', line 96

def trigger_experiment(visitor_code, experiment_id, timeout = @default_timeout)
  check_visitor_code(visitor_code)
  experiment = @experiments.find { |experiment| experiment['id'].to_s == experiment_id.to_s }
  if experiment.nil?
    raise Exception::ExperimentConfigurationNotFound.new(experiment_id)
  end
  if @blocking
    variation_id = nil
    EM.synchrony do
      connexion_options = { :connect_timeout => (timeout.to_f / 1000.0) }
      body = @data.values.flatten.select { |data| !data.sent }.map { |data| data.obtain_full_post_text_line }
                  .join("\n") || ""
      path = get_experiment_register_url(visitor_code, experiment_id)
      request_options = { :path => path, :body => body }
      log "Trigger experiment request: " + request_options.inspect
      log "Trigger experiment connexion:" + connexion_options.inspect
      request = EM::Synchrony.sync post(request_options, @tracking_url, connexion_options)
      if is_successful(request)
        variation_id = request.response
      else
        log "Failed to trigger experiment: " + request.inspect
        raise Exception::ExperimentConfigurationNotFound.new(experiment_id) if variation_id.nil?
      end
      EM.stop
    end
    if variation_id.nil? || variation_id.to_s == "null" || variation_id.to_s == ""
      raise Exception::NotTargeted.new(visitor_code)
    elsif variation_id.to_s == "0"
      raise Exception::NotActivated.new(visitor_code)
    end
    variation_id.to_i
  else
    check_site_code_enable(experiment)
    visitor_data = @data.select { |key, value| key.to_s == visitor_code }.values.flatten! || []
    if experiment['targetingSegment'].nil? || experiment['targetingSegment'].check_tree(visitor_data)
      threshold = obtain_hash_double(visitor_code, experiment['respoolTime'], experiment['id'])
      experiment['deviations'].each do |key, value|
        threshold -= value
        if threshold < 0
          track_experiment(visitor_code, experiment_id, key)
          return key.to_s.to_i
        end
      end
      track_experiment(visitor_code, experiment_id, REFERENCE, true)
      raise Exception::NotActivated.new(visitor_code)
    end
    raise Exception::NotTargeted.new(visitor_code)
  end
end