Class: LaunchDarkly::LDClient

Inherits:
Object
  • Object
show all
Includes:
Evaluation
Defined in:
lib/ldclient-rb/ldclient.rb

Overview

A client for LaunchDarkly. Client instances are thread-safe. Users should create a single client instance for the lifetime of the application.

Constant Summary

Constants included from Evaluation

Evaluation::BUILTINS, Evaluation::OPERATORS

Instance Method Summary collapse

Methods included from Evaluation

#bucket_user, #clause_match_user, #eval_internal, #eval_rules, #evaluate, #get_variation, #match_any, #maybe_negate, #rule_match_user, #user_value, #variation_for_user

Constructor Details

#initialize(sdk_key, config = Config.default, wait_for_sec = 5) ⇒ LDClient

Creates a new client instance that connects to LaunchDarkly. A custom configuration parameter can also supplied to specify advanced options, but for most use cases, the default configuration is appropriate.

Parameters:

  • sdk_key (String)

    the SDK key for your LaunchDarkly account

  • config (Config) (defaults to: Config.default)

    an optional client configuration object



26
27
28
29
30
31
32
33
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/ldclient-rb/ldclient.rb', line 26

def initialize(sdk_key, config = Config.default, wait_for_sec = 5)
  @sdk_key = sdk_key
  @config = config
  @store = config.feature_store

  @event_processor = EventProcessor.new(sdk_key, config)

  if @config.use_ldd?
    @config.logger.info("[LDClient] Started LaunchDarkly Client in LDD mode")
    return  # requestor and update processor are not used in this mode
  end

  requestor = Requestor.new(sdk_key, config)

  if !@config.offline?
    if @config.stream?
      @update_processor = StreamProcessor.new(sdk_key, config, requestor)
    else
      @update_processor = PollingProcessor.new(config, requestor)
    end
    @update_processor.start
  end

  if !@config.offline? && wait_for_sec > 0
    begin
      WaitUtil.wait_for_condition("LaunchDarkly client initialization", timeout_sec: wait_for_sec, delay_sec: 0.1) do
        @update_processor.initialized?
      end
    rescue WaitUtil::TimeoutError
      @config.logger.error("[LDClient] Timeout encountered waiting for LaunchDarkly client initialization")
    end
  end
end

Instance Method Details

#all_flags(user) ⇒ Object

Returns all feature flag values for the given user



184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/ldclient-rb/ldclient.rb', line 184

def all_flags(user)
  sanitize_user(user)
  return Hash.new if @config.offline?

  unless user
    @config.logger.error("[LDClient] Must specify user in all_flags")
    return Hash.new
  end

  begin
    features = @store.all

    # TODO rescue if necessary
    Hash[features.map{ |k, f| [k, evaluate(f, user, @store)[:value]] }]
  rescue => exn
    @config.logger.warn("[LDClient] Error evaluating all flags: #{exn.inspect}. \nTrace: #{exn.backtrace}")
    return Hash.new
  end
end

#closevoid

This method returns an undefined value.

Releases all network connections and other resources held by the client, making it no longer usable



208
209
210
211
212
213
214
215
# File 'lib/ldclient-rb/ldclient.rb', line 208

def close
  @config.logger.info("[LDClient] Closing LaunchDarkly client...")
  if not @config.offline?
    @update_processor.stop
  end
  @event_processor.stop
  @store.stop
end

#flushObject



60
61
62
# File 'lib/ldclient-rb/ldclient.rb', line 60

def flush
  @event_processor.flush
end

#identify(user) ⇒ void

This method returns an undefined value.

Registers the user

Parameters:

  • The (Hash)

    user to register



163
164
165
166
# File 'lib/ldclient-rb/ldclient.rb', line 163

def identify(user)
  sanitize_user(user)
  @event_processor.add_event(kind: "identify", key: user[:key], user: user)
end

#initialized?Boolean

Returns whether the client has been initialized and is ready to serve feature flag requests

Returns:

  • (Boolean)

    true if the client has been initialized



75
76
77
# File 'lib/ldclient-rb/ldclient.rb', line 75

def initialized?
  @config.offline? || @config.use_ldd? || @update_processor.initialized?
end

#secure_mode_hash(user) ⇒ Object



69
70
71
# File 'lib/ldclient-rb/ldclient.rb', line 69

def secure_mode_hash(user)
  OpenSSL::HMAC.hexdigest("sha256", @sdk_key, user[:key].to_s)
end

#toggle?(key, user, default = False) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
67
# File 'lib/ldclient-rb/ldclient.rb', line 64

def toggle?(key, user, default = False)
  @config.logger.warn("[LDClient] toggle? is deprecated. Use variation instead")
  variation(key, user, default)
end

#track(event_name, user, data) ⇒ void

This method returns an undefined value.

Tracks that a user performed an event

Parameters:

  • event_name (String)

    The name of the event

  • user (Hash)

    The user that performed the event. This should be the same user hash used in calls to #toggle?

  • data (Hash)

    A hash containing any additional data associated with the event



176
177
178
179
# File 'lib/ldclient-rb/ldclient.rb', line 176

def track(event_name, user, data)
  sanitize_user(user)
  @event_processor.add_event(kind: "custom", key: event_name, user: user, data: data)
end

#variation(key, user, default) ⇒ Object

Determines the variation of a feature flag to present to a user. At a minimum, the user hash should contain a :key .

For authenticated users, the :key should be the unique identifier for your user. For anonymous users, the :key should be a session identifier or cookie. In either case, the only requirement is that the key is unique to a user.

You can also pass IP addresses and country codes in the user hash.

The user hash can contain arbitrary custom attributes stored in a :custom sub-hash:

Attribute values in the custom hash can be integers, booleans, strings, or

lists of integers, booleans, or strings.

Examples:

Basic user hash

{key: "[email protected]"}

More complete user hash

{key: "[email protected]", ip: "127.0.0.1", country: "US"}

A user hash with custom attributes

{key: "[email protected]", custom: {customer_rank: 1000, groups: ["google", "microsoft"]}}

Parameters:

  • key (String)

    the unique feature key for the feature flag, as shown on the LaunchDarkly dashboard

  • user (Hash)

    a hash containing parameters for the end user requesting the flag

  • default=false

    the default value of the flag

Returns:

  • the variation to show the user, or the default value if there’s an an error



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
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/ldclient-rb/ldclient.rb', line 111

def variation(key, user, default)
  return default if @config.offline?

  unless user
    @config.logger.error("[LDClient] Must specify user")
    @event_processor.add_event(kind: "feature", key: key, value: default, default: default, user: user)
    return default
  end

  if !@update_processor.nil? && !@update_processor.initialized?
    @config.logger.error("[LDClient] Client has not finished initializing. Returning default value")
    @event_processor.add_event(kind: "feature", key: key, value: default, default: default, user: user)
    return default
  end

  sanitize_user(user)
  feature = @store.get(key)

  if feature.nil?
    @config.logger.error("[LDClient] Unknown feature flag #{key}. Returning default value")
    @event_processor.add_event(kind: "feature", key: key, value: default, default: default, user: user)
    return default
  end

  begin
    res = evaluate(feature, user, @store)
    if !res[:events].nil?
      res[:events].each do |event|
        @event_processor.add_event(event)
      end
    end
    if !res[:value].nil?
      @event_processor.add_event(kind: "feature", key: key, user: user, value: res[:value], default: default, version: feature[:version])
      return res[:value]
    else
      @config.logger.debug("[LDClient] Result value is null in toggle")
      @event_processor.add_event(kind: "feature", key: key, user: user, value: default, default: default, version: feature[:version])
      return default
    end
  rescue => exn
    @config.logger.warn("[LDClient] Error evaluating feature flag: #{exn.inspect}. \nTrace: #{exn.backtrace}")
    @event_processor.add_event(kind: "feature", key: key, user: user, value: default, default: default, version: feature[:version])
    return default
  end
end