class Kameleoon::Client
Constants
- API_SSX_URL
- REFERENCE
Attributes
Public Class Methods
You should create Client
with the Client
Factory only.
# 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
Public Instance Methods
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.
@param [String] visitor_code @param [String | Integer] feature_key
@raise [Kameleoon::Exception::FeatureConfigurationNotFound] @raise [Kameleoon::Exception::NotTargeted]
# 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 => (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 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'] track_experiment(visitor_code, id, feature_flag["variationsId"].first) return true else track_experiment(visitor_code, id, REFERENCE, true) return false end else raise Exception::NotTargeted.new(visitor_code) end end end
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.
@param [String] visitor_code Visitor code @param […Data] data Data
to associate with the visitor code
# 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 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.
@param [String] visitor_code Optional field - Visitor code, without visitor code it flush all of the data
# File lib/kameleoon/client.rb, line 184 def flush(visitor_code = nil) track_data(visitor_code) end
Retrieve a feature variable.
A feature variable can be changed easily via our web application.
@param [String | Integer] feature_key @param [String ] variable_key
@raise [Kameleoon::Exception::FeatureConfigurationNotFound] @raise [Kameleoon::Exception::FeatureVariableNotFound]
# 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.
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.
@param [Integer] variation_id
@return [Hash] Hash object of the json object.
@raise [Kameleoon::Exception::VariationNotFound] Raise exception if the variation is not found.
# 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 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. @note The implementation logic is described here: 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.
@param [Hash] cookies Cookies of the request. @param [String] top_level_domain Top level domain of your website, settled while writing cookie. @param [String] default_visitor_code - Optional - Define your default visitor_code (maximum length 100 chars).
@return [String] visitor code
@example cookies = {'kameleoonVisitorCode' => '1234asdf4321fdsa'} visitor_code = obtain_visitor_code
(cookies, 'my-domaine.com')
# 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 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.
@param [String] visitor_code Visitor code @param [Integer] goal_id Id of the goal @param [Float] revenue Optional - Revenue of the conversion.
# 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 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.
@param [String] visitor_code Visitor code @param [Integer] experiment_id Id of the experiment you want to trigger.
@return [Integer] Id of the variation
@raise [Kameleoon::Exception::ExperimentConfigurationNotFound] Raise when experiment configuration is not found @raise [Kameleoon::Exception::NotActivated] The visitor triggered the experiment, but did not activate it. Usually, this happens because the user has been associated with excluded traffic @raise [Kameleoon::Exception::NotTargeted] The visitor is not targeted by the experiment, as the associated targeting segment conditions were not fulfilled. He should see the reference variation
# 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 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
Private Instance Methods
# File lib/kameleoon/client.rb, line 389 def complete_experiment(experiment) unless experiment['variationsId'].nil? experiment['variations'] = experiment['variationsId'].map { |variationId| obtain_variation(variationId) } end unless experiment['targetingSegmentId'].nil? experiment['targetingSegment'] = Kameleoon::Targeting::Segment.new(obtain_segment(experiment['targetingSegmentId'])) end experiment end
# File lib/kameleoon/client.rb, line 554 def data_not_sent(visitor_code = nil) if visitor_code.nil? @data.select {|key, values| values.any? {|data| !data.sent}} else @data.select { |key, values| key == visitor_code && values.any? {|data| !data.sent} } end end
# File lib/kameleoon/client.rb, line 428 def fetch_all(path, query_values = {}, filters = []) results = [] current_page = 1 loop do query_values['page'] = current_page http = fetch_one(path, query_values, filters) break if http == false results.push(http) break if http.response_header["X-Pagination-Page-Count"].to_i <= current_page current_page += 1 end results end
# File lib/kameleoon/client.rb, line 303 def fetch_configuration @scheduler = Rufus::Scheduler.singleton @scheduler.every @interval do log("Scheduled job to fetch configuration is starting.") fetch_configuration_job end @scheduler.schedule '0s' do log("Start-up, fetching is starting") fetch_configuration_job end end
# File lib/kameleoon/client.rb, line 315 def fetch_configuration_job EM.synchrony do obtain_access_token site = obtain_site if site.nil? || site.empty? @experiments ||= [] @feature_flags ||= [] else site_id = site.first['id'] @experiments = obtain_tests(site_id) || @experiments @feature_flags = obtain_feature_flags(site_id) || @feature_flags end EM.stop end end
# File lib/kameleoon/client.rb, line 442 def fetch_one(path, query_values = {}, filters = []) unless filters.empty? query_values['filter'] = filters.to_json end request = EM::Synchrony.sync get({ :path => path, :query => query_values, :head => hash_headers }) unless is_successful(request) log "Failed to fetch" + request.inspect return false end request end
# File lib/kameleoon/client.rb, line 454 def get_common_ssx_parameters(visitor_code) { :nonce => Kameleoon::Utils.generate_random_string(16), :siteCode => @site_code, :visitorCode => visitor_code } end
# File lib/kameleoon/client.rb, line 475 def get_data_register_url(visitor_code) "/dataTracking?" + URI.encode_www_form(get_common_ssx_parameters(visitor_code)) end
# File lib/kameleoon/client.rb, line 462 def get_experiment_register_url(visitor_code, experiment_id, variation_id = nil, none_variation = false) url = "/experimentTracking?" + URI.encode_www_form(get_common_ssx_parameters(visitor_code)) url += "&experimentId=" + experiment_id.to_s if variation_id.nil? return url end url += "&variationId=" + variation_id.to_s if none_variation url += "&noneVariation=true" end url end
# File lib/kameleoon/client.rb, line 479 def get_feature_flag(feature_key) if feature_key.is_a?(String) feature_flag = @feature_flags.select { |ff| ff['identificationKey'] == feature_key}.first elsif feature_key.is_a?(Integer) feature_flag = @feature_flags.select { |ff| ff['id'].to_i == feature_key}.first else raise TypeError.new("Feature key should be a String or an Integer.") end if feature_flag.nil? raise Exception::FeatureConfigurationNotFound.new(feature_key) end feature_flag end
# File lib/kameleoon/client.rb, line 341 def hash_filter(field, operator, parameters) { 'field' => field, 'operator' => operator, 'parameters' => parameters } end
# File lib/kameleoon/client.rb, line 331 def hash_headers if @access_token.nil? CredentialsNotFound.new end { 'Authorization' => 'Bearer ' + @access_token.to_s, 'Content-Type' => 'application/json' } end
# File lib/kameleoon/client.rb, line 562 def log(text) if @verbose_mode print "Kameleoon Log: " + text.to_s + "\n" end end
# File lib/kameleoon/client.rb, line 357 def obtain_access_token log "Fetching bearer token" body = { 'grant_type' => 'client_credentials', 'client_id' => @client_id, 'client_secret' => @client_secret } header = { 'Content-Type' => 'application/x-www-form-urlencoded' } request = EM::Synchrony.sync post({ :path => '/oauth/token', :body => body, :head => header }) if is_successful(request) @access_token = JSON.parse(request.response)['access_token'] log "Bearer Token is fetched: " + @access_token.to_s else log "Failed to fetch bearer token: " + request.inspect end end
# File lib/kameleoon/client.rb, line 414 def obtain_feature_flags(site_id, per_page = -1) log "Fetching feature flags" query_values = { 'perPage' => per_page } filters = [ hash_filter('siteId', 'EQUAL', [site_id]), hash_filter('status', 'EQUAL', ['ACTIVE']) ] feature_flags = fetch_all('feature-flags', query_values, filters).map { |it| JSON.parse(it.response) }.flatten.map do |ff| complete_experiment(ff) end log "Feature flags are fetched: " + feature_flags.inspect feature_flags end
# File lib/kameleoon/client.rb, line 382 def obtain_segment(segment_id) request = fetch_one('segments/' + segment_id.to_s) if request != false JSON.parse(request.response) end end
# File lib/kameleoon/client.rb, line 345 def obtain_site log "Fetching site" query_params = { 'perPage' => 1 } filters = [hash_filter('code', 'EQUAL', [@site_code])] request = fetch_one('sites', query_params, filters) if request != false sites = JSON.parse(request.response) log "Sites are fetched: " + sites.inspect sites end end
# File lib/kameleoon/client.rb, line 399 def obtain_tests(site_id, per_page = -1) log "Fetching experiments" query_values = { 'perPage' => per_page } filters = [ hash_filter('siteId', 'EQUAL', [site_id]), hash_filter('status', 'IN', ['ACTIVE', 'DEVIATED']), hash_filter('type', 'IN', ['SERVER_SIDE', 'HYBRID']) ] experiments = fetch_all('experiments', query_values, filters).map { |it| JSON.parse(it.response) }.flatten.map do |test| complete_experiment(test) end log "Experiment are fetched: " + experiments.inspect experiments end
# File lib/kameleoon/client.rb, line 375 def obtain_variation(variation_id) request = fetch_one('variations/' + variation_id.to_s) if request != false JSON.parse(request.response) end end
# File lib/kameleoon/client.rb, line 520 def track_data(visitor_code = nil) Thread.new do EM.synchrony do trials = 10 concurrency = 1 data_not_sent = data_not_sent(visitor_code) log "Start post tracking data: " + data_not_sent.inspect while trials > 0 && !data_not_sent.empty? EM::Synchrony::Iterator.new(data_not_sent, concurrency).map do |entry, iter| options = { :path => get_data_register_url(entry.first), :body => (entry.last.map { |data| data.obtain_full_post_text_line }.join("\n") || "").encode("UTF-8"), :head => { "Content-Type" => "text/plain" } } log "Post tracking data for visitor_code: " + entry.first + " with options: " + options.inspect request = post(options, @tracking_url) request.callback { if is_successful(request) entry.last.each { |data| data.sent = true } end iter.return(request) } request.errback { iter.return(request) } end data_not_sent = data_not_sent(visitor_code) trials -= 1 end log "Post to data tracking is done." EM.stop end Thread.exit end end
# File lib/kameleoon/client.rb, line 493 def track_experiment(visitor_code, experiment_id, variation_id = nil, none_variation = false) data_not_sent = data_not_sent(visitor_code) options = { :path => get_experiment_register_url(visitor_code, experiment_id, variation_id, none_variation), :body => ((data_not_sent.values[0] || []).map{ |it| it.obtain_full_post_text_line }.join("\n") || "").encode("UTF-8"), :head => { "Content-Type" => "text/plain"} } trial = 0 log "Start post tracking experiment: " + data_not_sent.inspect Thread.new do EM.synchrony do while trial < 10 request = EM::Synchrony.sync post(options, @tracking_url) log "Request " + request.inspect if is_successful(request) (data_not_sent.values[0] || []).each { |it| it.sent = true } EM.stop end trial += 1 end EM.stop end log "Post to experiment tracking is done after " + trial.to_s + " trials" Thread.exit end end