-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathldclient.rb
275 lines (245 loc) · 8.87 KB
/
ldclient.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
require "concurrent/atomics"
require "digest/sha1"
require "logger"
require "benchmark"
require "json"
require "openssl"
module LaunchDarkly
#
# A client for LaunchDarkly. Client instances are thread-safe. Users
# should create a single client instance for the lifetime of the application.
#
#
class LDClient
include Evaluation
#
# 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.
#
#
# @param sdk_key [String] the SDK key for your LaunchDarkly account
# @param config [Config] an optional client configuration object
#
# @return [LDClient] The LaunchDarkly client instance
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?
@update_processor = NullUpdateProcessor.new
else
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
end
ready = @update_processor.start
if wait_for_sec > 0
ok = ready.wait(wait_for_sec)
if !ok
@config.logger.error { "[LDClient] Timeout encountered waiting for LaunchDarkly client initialization" }
elsif !@update_processor.initialized?
@config.logger.error { "[LDClient] LaunchDarkly client initialization failed" }
end
end
end
def flush
@event_processor.flush
end
def toggle?(key, user, default = False)
@config.logger.warn { "[LDClient] toggle? is deprecated. Use variation instead" }
variation(key, user, default)
end
def secure_mode_hash(user)
OpenSSL::HMAC.hexdigest("sha256", @sdk_key, user[:key].to_s)
end
# Returns whether the client has been initialized and is ready to serve feature flag requests
# @return [Boolean] true if the client has been initialized
def initialized?
@config.offline? || @config.use_ldd? || @update_processor.initialized?
end
#
# Determines the variation of a feature flag to present to a user. At a minimum,
# the user hash should contain a +:key+ .
#
# @example Basic user hash
# {key: "user@example.com"}
#
# 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.
#
# @example More complete user hash
# {key: "user@example.com", ip: "127.0.0.1", country: "US"}
#
# The user hash can contain arbitrary custom attributes stored in a +:custom+ sub-hash:
#
# @example A user hash with custom attributes
# {key: "user@example.com", custom: {customer_rank: 1000, groups: ["google", "microsoft"]}}
#
# Attribute values in the custom hash can be integers, booleans, strings, or
# lists of integers, booleans, or strings.
#
# @param key [String] the unique feature key for the feature flag, as shown
# on the LaunchDarkly dashboard
# @param user [Hash] a hash containing parameters for the end user requesting the flag
# @param default=false the default value of the flag
#
# @return the variation to show the user, or the
# default value if there's an an error
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
#
# Registers the user
#
# @param [Hash] The user to register
#
# @return [void]
def identify(user)
sanitize_user(user)
@event_processor.add_event(kind: "identify", key: user[:key], user: user)
end
#
# Tracks that a user performed an event
#
# @param event_name [String] The name of the event
# @param user [Hash] The user that performed the event. This should be the same user hash used in calls to {#toggle?}
# @param data [Hash] A hash containing any additional data associated with the event
#
# @return [void]
def track(event_name, user, data)
sanitize_user(user)
@event_processor.add_event(kind: "custom", key: event_name, user: user, data: data)
end
#
# Returns all feature flag values for the given user
#
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
#
# Releases all network connections and other resources held by the client, making it no longer usable
#
# @return [void]
def close
@config.logger.info { "[LDClient] Closing LaunchDarkly client..." }
@update_processor.stop
@event_processor.stop
@store.stop
end
def log_exception(caller, exn)
error_traceback = "#{exn.inspect} #{exn}\n\t#{exn.backtrace.join("\n\t")}"
error = "[LDClient] Unexpected exception in #{caller}: #{error_traceback}"
@config.logger.error { error }
end
def sanitize_user(user)
if user[:key]
user[:key] = user[:key].to_s
end
end
def make_feature_event(flag, user, variation, value, default)
{
kind: "feature",
key: flag[:key],
user: user,
variation: variation,
value: value,
default: default,
version: flag[:version],
trackEvents: flag[:trackEvents],
debugEventsUntilDate: flag[:debugEventsUntilDate]
}
end
private :evaluate, :log_exception, :sanitize_user, :make_feature_event
end
#
# Used internally when the client is offline.
#
class NullUpdateProcessor
def start
e = Concurrent::Event.new
e.set
e
end
def initialized?
true
end
def stop
end
end
end