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, #obtain_hash_double_helper, #obtain_hash_double_rule, #read_and_write

Constructor Details

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

You should create Client with the Client Factory only.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/kameleoon/client.rb', line 40

def initialize(site_code, path_config_file, interval, default_timeout, client_id = nil, client_secret = nil)
  config = YAML.load_file(path_config_file)
  @site_code = site_code
  @default_timeout = config['default_timeout'] || default_timeout # in ms
  refresh_interval = config['actions_configuration_refresh_interval']
  @interval = refresh_interval.nil? ? interval : "#{refresh_interval}m"
  data_api_url = config['tracking_url'] || Network::UrlProvider::DEFAULT_DATA_API_URL
  @url_provider = Network::UrlProvider.new(@site_code, data_api_url)
  @real_time_configuration_service = nil
  @update_configuration_handler = nil
  @fetch_configuration_update_job = nil
  @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
  @settings = Kameleoon::Configuration::Settings.new
  @verbose_mode = config['verbose_mode'] || false
  @experiments = []
  @feature_flags = []
  @data = {}
  @user_agents = {}
  @variation_storage = Kameleoon::Storage::VariationStorage.new
  @hybrid_manager = Kameleoon::Hybrid::ManagerImpl.new(
    CACHE_EXPIRATION_TIMEOUT,
    CACHE_EXPIRATION_TIMEOUT * 3,
    Kameleoon::Storage::CacheFactoryImpl.new,
    method(:log)
  )
end

Instance Method Details

#activate_feature(visitor_code, feature_key) ⇒ Object

associated targeting segment conditions were not fulfilled. He should see the reference variation DEPRECATED. Please use ‘is_feature_active` instead.

Raises:



272
273
274
275
# File 'lib/kameleoon/client.rb', line 272

def activate_feature(visitor_code, feature_key)
  warn '[DEPRECATION] `activate_feature` is deprecated.  Please use `feature_active?` instead.'
  feature_active?(visitor_code, feature_key)
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:



166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/kameleoon/client.rb', line 166

def add_data(visitor_code, *args)
  check_visitor_code(visitor_code)
  @data.shift while ObjectSpace.memsize_of(@data) > @data_maximum_size * (2**20)
  args.each do |data_element|
    if data_element.is_a?(UserAgent)
      add_user_agent_data(visitor_code, data_element)
      next
    end
    @data[visitor_code] = [] unless @data.key?(visitor_code)
    @data[visitor_code].push(data_element)
  end
end

#feature_active?(visitor_code, feature_key) ⇒ Boolean

Check if feature is active for a given visitor code

This method takes a visitor_code and feature_key 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 feature flag 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)

    Unique identifier of the user. This field is mandatory.

  • feature_key (String)

    Key of the feature flag you want to expose to a user. This field is mandatory.

Returns:

  • (Boolean)

Raises:



294
295
296
297
# File 'lib/kameleoon/client.rb', line 294

def feature_active?(visitor_code, feature_key)
  _, variation_key = _get_feature_variation_key(visitor_code, feature_key)
  variation_key != Kameleoon::Configuration::VariationType::VARIATION_OFF
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:



211
212
213
214
215
216
217
218
# File 'lib/kameleoon/client.rb', line 211

def flush(visitor_code = nil)
  check_visitor_code(visitor_code) unless visitor_code.nil?
  if !visitor_code.nil?
    _send_tracking_request(visitor_code)
  else
    @data.select { |_, values| values.any? { |data| !data.sent } }.each_key { |key| flush(key) }
  end
end

#get_active_feature_list_for_visitor(visitor_code) ⇒ Array

Returns a list of active feature flag keys for a visitor

Returns:

  • (Array)

    array of active feature flag keys for a visitor

Raises:



458
459
460
461
462
463
464
465
466
467
468
469
# File 'lib/kameleoon/client.rb', line 458

def get_active_feature_list_for_visitor(visitor_code)
  check_visitor_code(visitor_code)
  list_keys = []
  @feature_flags.each do |feature_flag|
    variation, rule, = _calculate_variation_key_for_feature(visitor_code, feature_flag)
    variation_key = _get_variation_key(variation, rule, feature_flag)
    if variation_key != Kameleoon::Configuration::VariationType::VARIATION_OFF
      list_keys.push(feature_flag.feature_key)
    end
  end
  list_keys
end

#get_engine_tracking_code(visitor_code) ⇒ String

The ‘get_engine_tracking_code` returns the JavasScript code to be inserted in your page to send automatically the exposure events to the analytics solution you are using.

the exposure events to the analytics solution you are using.

Parameters:

  • visitor_code (String)

    The user’s unique identifier. This field is mandatory.

Returns:

  • (String)

    JavasScript code to be inserted in your page to send automatically



490
491
492
# File 'lib/kameleoon/client.rb', line 490

def get_engine_tracking_code(visitor_code)
  @hybrid_manager.get_engine_tracking_code(visitor_code)
end

#get_experiment_listArray

Returns a list of all experiment ids

Returns:

  • (Array)

    array of all experiment ids



422
423
424
# File 'lib/kameleoon/client.rb', line 422

def get_experiment_list # rubocop:disable Naming/AccessorMethodName
  @experiments.map { |it| it.id.to_i }
end

#get_experiment_list_for_visitor(visitor_code, only_allocated: true) ⇒ Array

Returns a list of all experiment ids targeted for a visitor if only_allocated is ‘true` returns a list of allocated experiments for a visitor

Returns:

  • (Array)

    array of all experiment ids accorging to a only_allocated parameter

Raises:



433
434
435
436
437
438
439
440
441
442
# File 'lib/kameleoon/client.rb', line 433

def get_experiment_list_for_visitor(visitor_code, only_allocated: true)
  list_ids = []
  @experiments.each do |experiment|
    next unless check_targeting(visitor_code, experiment.id.to_i, experiment)
    next if only_allocated && calculate_variation_for_experiment(visitor_code, experiment).nil?

    list_ids.push(experiment.id.to_i)
  end
  list_ids
end

#get_feature_all_variables(feature_key, variation_key) ⇒ Object

Retrieves all feature variable values for a given variation

This method takes a feature_key and variation_key as mandatory arguments and returns a list of variables for a given variation key A feature variable can be changed easily via our web application.

Parameters:

  • feature_key (String)
  • variation_key (String)

Raises:



356
357
358
359
360
361
362
363
364
365
366
# File 'lib/kameleoon/client.rb', line 356

def get_feature_all_variables(feature_key, variation_key)
  feature_flag = find_feature_flag(feature_key)
  variation = feature_flag.get_variation_key(variation_key)
  if variation.nil?
    raise Exception::VariationConfigurationNotFound.new(variation_key),
          "Variation key #{variation_key} not found"
  end
  variables = {}
  variation.variables.each { |var| variables[var.key] = _parse_feature_variable(var) }
  variables
end

#get_feature_listArray

Returns a list of all feature flag keys

Returns:

  • (Array)

    array of all feature flag keys



448
449
450
# File 'lib/kameleoon/client.rb', line 448

def get_feature_list # rubocop:disable Naming/AccessorMethodName
  @feature_flags.map(&:feature_key)
end

#get_feature_variable(visitor_code, feature_key, variable_name) ⇒ Object

Retrieves a feature variable value from assigned for visitor variation

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

Parameters:

  • visitor_code (String)
  • feature_key (String)
  • variable_name (String)

Raises:



332
333
334
335
336
337
338
339
340
341
# File 'lib/kameleoon/client.rb', line 332

def get_feature_variable(visitor_code, feature_key, variable_name)
  feature_flag, variation_key = _get_feature_variation_key(visitor_code, feature_key)
  variation = feature_flag.get_variation_key(variation_key)
  variable = variation&.get_variable_by_key(variable_name)
  if variable.nil?
    raise Exception::FeatureVariableNotFound.new(variable_name),
          "Feature variable #{variable_name} not found"
  end
  _parse_feature_variable(variable)
end

#get_feature_variation_key(visitor_code, feature_key) ⇒ Object

get_feature_variation_key returns a variation key for visitor code

This method takes a visitorCode and featureKey as mandatory arguments and returns a variation assigned for a given visitor If such a user has never been associated with any feature flag rules, the SDK returns a default variation key 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)

Raises:



314
315
316
317
# File 'lib/kameleoon/client.rb', line 314

def get_feature_variation_key(visitor_code, feature_key)
  _, variation_key = _get_feature_variation_key(visitor_code, feature_key)
  variation_key
end

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

The get_remote_data 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.

This field is optional.

Parameters:

  • key (String)

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

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

    Timeout for request (in milliseconds). Equals default_timeout in a config file.

Returns:

  • (Hash)

    Hash object of the json object.



401
402
403
404
405
406
407
408
409
# File 'lib/kameleoon/client.rb', line 401

def get_remote_data(key, timeout = @default_timeout)
  connexion_options = { connect_timeout: (timeout.to_f / 1000.0) }
  url = @url_provider.make_api_data_get_request_url(key)
  log "Retrieve API Data connexion: #{connexion_options.inspect}"
  response = get_sync(url, connexion_options)
  return nil unless successful_sync?(response)

  JSON.parse(response.body) unless response.nil?
end

#get_variation_associated_data(variation_id) ⇒ Hash

Obtain variation associated data.

To retrieve JSON data associated with a variation, call the get_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.



235
236
237
238
239
240
241
242
243
# File 'lib/kameleoon/client.rb', line 235

def get_variation_associated_data(variation_id)
  variation = @experiments.map(&:variations).flatten.select { |var| var['id'].to_i == variation_id.to_i }.first
  if variation.nil?
    raise Exception::VariationConfigurationNotFound.new(variation_id),
          "Variation key #{variation_id} not found"
  else
    JSON.parse(variation['customJson'])
  end
end

#get_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 = get_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



96
97
98
# File 'lib/kameleoon/client.rb', line 96

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

DEPRECATED. Please use ‘get_feature_variable` instead.

Parameters:

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

Raises:



380
381
382
383
384
385
386
387
# File 'lib/kameleoon/client.rb', line 380

def obtain_feature_variable(feature_key, variable_key)
  warn '[DEPRECATION] `obtain_feature_variable` is deprecated.  Please use `get_feature_variable` instead.'
  all_variables = get_feature_all_variables(
    feature_key,
    Configuration::VariationType::VARIATION_OFF
  )
  all_variables[variable_key]
end

#obtain_variation_associated_data(variation_id) ⇒ Object

DEPRECATED. Please use ‘get_variation_associated_data` instead.



246
247
248
249
250
# File 'lib/kameleoon/client.rb', line 246

def obtain_variation_associated_data(variation_id)
  warn '[DEPRECATION] `obtain_variation_associated_data` is deprecated.
        Please use `get_variation_associated_data` instead.'
  get_variation_associated_data(variation_id)
end

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

DEPRECATED. Please use ‘get_visitor_code` instead.



101
102
103
104
# File 'lib/kameleoon/client.rb', line 101

def obtain_visitor_code(cookies, top_level_domain, default_visitor_code = nil)
  warn '[DEPRECATION] `obtain_visitor_code` is deprecated.  Please use `get_visitor_code` instead.'
  get_visitor_code(cookies, top_level_domain, default_visitor_code)
end

#on_update_configuration(handler) ⇒ Object

The ‘on_update_configuration()` method allows you to handle the event when configuration has updated data. It takes one input parameter: callable handler. The handler that will be called when the configuration is updated using a real-time configuration event.

is updated using a real-time configuration event.

Parameters:

  • handler (Callable | NilClass)

    The handler that will be called when the configuration



478
479
480
# File 'lib/kameleoon/client.rb', line 478

def on_update_configuration(handler)
  @update_configuration_handler = handler
end

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

DEPRECATED. Please use ‘get_feature_variable` instead.



413
414
415
416
# File 'lib/kameleoon/client.rb', line 413

def retrieve_data_from_remote_source(key, timeout = @default_timeout)
  warn '[DEPRECATION] `retrieve_data_from_remote_source` is deprecated.  Please use `get_remote_date` instead.'
  get_remote_data(key, timeout)
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:



194
195
196
197
198
# File 'lib/kameleoon/client.rb', line 194

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) ⇒ 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.

Usually, this happens because the user has been associated with excluded traffic associated targeting segment conditions were not fulfilled. He should see the reference variation

Parameters:

  • visitor_code (String)

    Visitor code

  • experiment_id (Integer)

    Id of the experiment you want to trigger.

Returns:

  • (Integer)

    Id of the variation

Raises:



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/kameleoon/client.rb', line 127

def trigger_experiment(visitor_code, experiment_id)
  check_visitor_code(visitor_code)
  experiment = @experiments.find { |exp| exp.id.to_s == experiment_id.to_s }
  if experiment.nil?
    raise Exception::ExperimentConfigurationNotFound.new(experiment_id),
          "Experiment #{experiment_id} is not found"
  end
  check_site_code_enable(experiment)
  targeted = check_targeting(visitor_code, experiment_id, experiment)
  if targeted
    # saved_variation = get_valid_saved_variation(visitor_code, experiment)
    variation_id = calculate_variation_for_experiment(visitor_code, experiment)
    save_variation(visitor_code, experiment_id, variation_id)
  end
  _send_tracking_request(visitor_code, experiment_id, variation_id)
  unless targeted
    raise Exception::NotTargeted.new(visitor_code),
          "Experiment #{experiment_id} is not targeted for visitor #{visitor_code}"
  end
  if variation_id.nil?
    raise Exception::NotAllocated.new(visitor_code),
          "Experiment #{experiment_id} is not active for visitor #{visitor_code}"
  end
  variation_id
end