Class: AmplitudeExperiment::LocalEvaluationClient

Inherits:
Object
  • Object
show all
Defined in:
lib/experiment/local/client.rb

Overview

Main client for fetching variant data.

Instance Method Summary collapse

Constructor Details

#initialize(api_key, config = nil) ⇒ LocalEvaluationClient

Creates a new Experiment Client instance.

Parameters:

  • api_key (String)

    The environment API Key

  • config (LocalEvaluationConfig) (defaults to: nil)

    The config object

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/experiment/local/client.rb', line 12

def initialize(api_key, config = nil)
  @api_key = api_key
  @config = config || LocalEvaluationConfig.new
  @cache = InMemoryFlagConfigCache.new(@config.bootstrap)
  @logger = Logger.new($stdout)
  @logger.level = if @config.debug
                    Logger::DEBUG
                  else
                    Logger::INFO
                  end
  @fetcher = LocalEvaluationFetcher.new(api_key, @config.debug, @config.server_url)
  @poller = FlagConfigPoller.new(@fetcher, @cache, @config.debug)

  raise ArgumentError, 'Experiment API key is empty' if @api_key.nil? || @api_key.empty?
end

Instance Method Details

#evaluate(user, flag_keys = []) ⇒ Hash[String, Variant]

Locally evaluates flag variants for a user.

Parameters:

  • user (User)

    The user to evaluate

  • flag_keys (String[]) (defaults to: [])

    The flags to evaluate with the user. If empty, all flags from the flag cache are evaluated

Returns:

  • (Hash[String, Variant])

    The evaluated variants



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/experiment/local/client.rb', line 34

def evaluate(user, flag_keys = [])
  flag_configs = []
  if flag_keys.empty?
    @cache.cache.each do |_, value|
      flag_configs.push(value)
    end
  else
    flag_configs = get_flag_configs(flag_keys)
  end
  flag_configs_str = flag_configs.to_json
  user_str = user.to_json
  @logger.debug("[Experiment] Evaluate: User: #{user_str} - Rules: #{flag_configs_str}") if @config.debug
  result_json = evaluation(flag_configs_str, user_str)
  @logger.debug(`[Experiment] evaluate - result: #{variants}`) if @config.debug
  result = JSON.parse(result_json)
  variants = {}
  result.each do |key, value|
    next if value['isDefaultVariant']

    variant_key = value['variant']['key']
    variant_payload = value['variant']['payload']
    variants.store(key, Variant.new(variant_key, variant_payload))
  end
  variants
end

#startObject

Fetch initial flag configurations and start polling for updates. You must call this function to begin polling for flag config updates.



62
63
64
# File 'lib/experiment/local/client.rb', line 62

def start
  @poller.start
end

#stopObject

Stop polling for flag configurations. Close resource like connection pool with client



67
68
69
# File 'lib/experiment/local/client.rb', line 67

def stop
  @poller.stop
end