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
# 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
      @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
    @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



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/ldclient-rb/ldclient.rb', line 190

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)[: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



214
215
216
217
218
219
220
221
# File 'lib/ldclient-rb/ldclient.rb', line 214

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

#flushObject



62
63
64
# File 'lib/ldclient-rb/ldclient.rb', line 62

def flush
  @event_processor.flush
end

#identify(user) ⇒ void

This method returns an undefined value.

Registers the user

Parameters:

  • The (Hash)

    user to register



169
170
171
172
# File 'lib/ldclient-rb/ldclient.rb', line 169

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



77
78
79
# File 'lib/ldclient-rb/ldclient.rb', line 77

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

#secure_mode_hash(user) ⇒ Object



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

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

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

Returns:

  • (Boolean)


66
67
68
69
# File 'lib/ldclient-rb/ldclient.rb', line 66

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



182
183
184
185
# File 'lib/ldclient-rb/ldclient.rb', line 182

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



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
156
157
158
159
160
161
# File 'lib/ldclient-rb/ldclient.rb', line 113

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 !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)
  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

  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