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

#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.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/kameleoon/client.rb', line 23

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"
  @client_id = client_id || config['client_id']
  @client_secret = client_secret || config['client_secret']
  @data_maximum_size = config['visitor_data_maximum_size'] || 500 # mb
  @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:



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/kameleoon/client.rb', line 225

def activate_feature(visitor_code, feature_key, timeout = @default_timeout)
  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 => (select_data_to_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
    visitor_data = @data.select { |key, value| key.to_s == visitor_code }.values.flatten! || []
    if feature_flag['targetingSegment'].nil? || feature_flag['targetingSegment'].check_tree(visitor_data)
      threshold = obtain_hash_double(visitor_code, {}, id)
      if threshold <= feature_flag['expositionRate']
        post_beacon("experimentTracking", visitor_code, id, feature_flag["variationsId"].first)
        return true
      else
        post_beacon("experimentTracking", visitor_code, id, REFERENCE, true)
        return false
      end
    else
      raise Exception::NotTargeted.new(visitor_code)
    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



146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/kameleoon/client.rb', line 146

def add_data(visitor_code, *args)
  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



184
185
186
# File 'lib/kameleoon/client.rb', line 184

def flush(visitor_code = nil)
  post_beacon("dataTracking", 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:



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/kameleoon/client.rb', line 277

def obtain_feature_variable(feature_key, variable_key)
  feature_flag = get_feature_flag(feature_key)
  custom_json = 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']
  when "String"
    return custom_json['value'].to_s
  when "Number"
    return custom_json['value'].to_f
  when "Json"
    return 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:



203
204
205
206
207
208
209
210
# File 'lib/kameleoon/client.rb', line 203

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::VariationNotFound.new(variation_id)
  else
    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



65
66
67
# File 'lib/kameleoon/client.rb', line 65

def obtain_visitor_code(cookies, top_level_domain, default_visitor_code = nil)
  read_and_write(cookies, top_level_domain, cookies, default_visitor_code)
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.



170
171
172
173
# File 'lib/kameleoon/client.rb', line 170

def track_conversion(visitor_code, goal_id, revenue = 0.0)
  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:



87
88
89
90
91
92
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/kameleoon/client.rb', line 87

def trigger_experiment(visitor_code, experiment_id, timeout = @default_timeout)
  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
    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
          post_beacon("experimentTracking", visitor_code, experiment_id, key)
          return key.to_s.to_i
        end
      end
      post_beacon("experimentTracking", visitor_code, experiment_id, REFERENCE, true)
      raise Exception::NotActivated.new(visitor_code)
    end
    raise Exception::NotTargeted.new(visitor_code)
  end
end