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::DATE_OPERAND, Evaluation::NUMERIC_VERSION_COMPONENTS_REGEX, Evaluation::OPERATORS, Evaluation::SEMVER_OPERAND

Instance Method Summary collapse

Methods included from Evaluation

addZeroVersionComponent, #bucket_user, #bucketable_string_value, #clause_match_user, #clause_match_user_no_segments, comparator, #eval_internal, #eval_rules, #evaluate, #get_variation, #match_any, #maybe_negate, #rule_match_user, #segment_match_user, #segment_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
59
60
61
62
63
64
65
66
67
68
# 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

  if @config.offline? || !@config.send_events
    @event_processor = NullEventProcessor.new
  else
    @event_processor = EventProcessor.new(sdk_key, config)
  end

  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.update_processor.nil?
      if @config.stream?
        @update_processor = StreamProcessor.new(sdk_key, config, requestor)
      else
        @config.logger.info { "Disabling streaming API" }
        @config.logger.warn { "You should only disable the streaming API if instructed to do so by LaunchDarkly support" }
        @update_processor = PollingProcessor.new(config, requestor)
      end
    else
      @update_processor = @config.update_processor
    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
        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



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/ldclient-rb/ldclient.rb', line 197

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(FEATURES)

    # TODO rescue if necessary
    Hash[features.map{ |k, f| [k, evaluate(f, user, @store, @config.logger)[: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



221
222
223
224
225
226
227
228
# File 'lib/ldclient-rb/ldclient.rb', line 221

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

#flushObject



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

def flush
  @event_processor.flush
end

#identify(user) ⇒ void

This method returns an undefined value.

Registers the user

Parameters:

  • The (Hash)

    user to register



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

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



85
86
87
# File 'lib/ldclient-rb/ldclient.rb', line 85

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

#secure_mode_hash(user) ⇒ Object



79
80
81
# File 'lib/ldclient-rb/ldclient.rb', line 79

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

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

Returns:

  • (Boolean)


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

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



189
190
191
192
# File 'lib/ldclient-rb/ldclient.rb', line 189

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



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
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/ldclient-rb/ldclient.rb', line 121

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

  if !initialized?
    if @store.initialized?
      @config.logger.warn { "[LDClient] Client has not finished initializing; using last known values from feature store" }
    else
      @config.logger.error { "[LDClient] Client has not finished initializing; feature store unavailable, returning default value" }
      @event_processor.add_event(kind: "feature", key: key, value: default, default: default, user: user)
      return default
    end
  end

  sanitize_user(user) if !user.nil?
  feature = @store.get(FEATURES, key)

  if feature.nil?
    @config.logger.info { "[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

  unless user
    @config.logger.error { "[LDClient] Must specify user" }
    @event_processor.add_event(make_feature_event(feature, user, nil, default, default))
    return default
  end

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