forked from launchdarkly/node-server-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
411 lines (356 loc) · 13.3 KB
/
index.js
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
var FeatureStoreEventWrapper = require('./feature_store_event_wrapper');
var RedisFeatureStore = require('./redis_feature_store');
var FileDataSource = require('./file_data_source');
var Requestor = require('./requestor');
var EventEmitter = require('events').EventEmitter;
var EventFactory = require('./event_factory');
var EventProcessor = require('./event_processor');
var PollingProcessor = require('./polling');
var StreamingProcessor = require('./streaming');
var FlagsStateBuilder = require('./flags_state');
var configuration = require('./configuration');
var evaluate = require('./evaluate_flag');
var messages = require('./messages');
var tunnel = require('tunnel');
var crypto = require('crypto');
var async = require('async');
var errors = require('./errors');
var wrapPromiseCallback = require('./utils/wrapPromiseCallback');
var dataKind = require('./versioned_data_kind');
function createErrorReporter(emitter, logger) {
return function(error) {
if (!error) {
return;
}
if (emitter.listenerCount('error')) {
emitter.emit('error', error);
} else {
logger.error(error.message);
}
};
}
global.setImmediate = global.setImmediate || process.nextTick.bind(process);
function NullEventProcessor() {
return {
sendEvent: function() {},
flush: function(callback) {
return wrapPromiseCallback(Promise.resolve(), callback);
},
close: function() {}
};
}
function NullUpdateProcessor() {
return {
start: function(callback) {
setImmediate(callback, null);
},
close: function() {}
};
}
var newClient = function(sdkKey, config) {
var client = new EventEmitter(),
initComplete = false,
failure,
requestor,
updateProcessor,
eventProcessor,
eventFactoryDefault,
eventFactoryWithReasons;
config = configuration.validate(config);
// Initialize global tunnel if proxy options are set
if (config.proxyHost && config.proxyPort ) {
config.proxyAgent = createProxyAgent(config);
}
config.featureStore = FeatureStoreEventWrapper(config.featureStore, client);
var maybeReportError = createErrorReporter(client, config.logger);
eventFactoryDefault = EventFactory(false);
eventFactoryWithReasons = EventFactory(true);
if (config.eventProcessor) {
eventProcessor = config.eventProcessor;
} else {
if (config.offline || !config.sendEvents) {
eventProcessor = NullEventProcessor();
} else {
eventProcessor = EventProcessor(sdkKey, config, maybeReportError);
}
}
if (!sdkKey && !config.offline) {
throw new Error("You must configure the client with an SDK key");
}
var createDefaultUpdateProcessor = function(config) {
if (config.useLdd || config.offline) {
return NullUpdateProcessor();
} else {
requestor = Requestor(sdkKey, config);
if (config.stream) {
config.logger.info("Initializing stream processor to receive feature flag updates");
return StreamingProcessor(sdkKey, config, requestor);
} else {
config.logger.info("Initializing polling processor to receive feature flag updates");
config.logger.warn("You should only disable the streaming API if instructed to do so by LaunchDarkly support");
return PollingProcessor(config, requestor);
}
}
}
var updateProcessorFactory = createDefaultUpdateProcessor;
if (config.updateProcessor) {
if (typeof config.updateProcessor === 'function') {
updateProcessorFactory = config.updateProcessor;
} else {
updateProcessor = config.updateProcessor;
}
}
if (!updateProcessor) {
updateProcessor = updateProcessorFactory(config);
}
updateProcessor.start(function(err) {
if (err) {
var error;
if ((err.status && err.status === 401) || (err.code && err.code === 401)) {
error = new Error("Authentication failed. Double check your SDK key.");
} else {
error = err;
}
maybeReportError(error);
client.emit('failed', error);
failure = error;
} else if (!initComplete) {
initComplete = true;
client.emit('ready');
}
});
client.initialized = function() {
return initComplete;
};
client.waitUntilReady = function() {
config.logger.warn(messages.deprecated("waitUntilReady", "waitForInitialization"));
if (initComplete) {
return Promise.resolve();
}
return new Promise(function(resolve) {
client.once('ready', resolve);
});
};
client.waitForInitialization = function() {
if (initComplete) {
return Promise.resolve(client);
}
if (failure) {
return Promise.reject(failure);
}
return new Promise(function(resolve, reject) {
client.once('ready', function() { resolve(client) });
client.once('failed', reject);
});
};
client.variation = function(key, user, defaultVal, callback) {
return wrapPromiseCallback(new Promise(function(resolve, reject) {
evaluateIfPossible(key, user, defaultVal, eventFactoryDefault,
function(detail) {
resolve(detail.value)
},
reject);
}.bind(this)), callback);
};
client.variationDetail = function(key, user, defaultVal, callback) {
return wrapPromiseCallback(new Promise(function(resolve, reject) {
evaluateIfPossible(key, user, defaultVal, eventFactoryWithReasons, resolve, reject);
}.bind(this)), callback);
};
function errorResult(errorKind, defaultVal) {
return { value: defaultVal, variationIndex: null, reason: { kind: 'ERROR', errorKind: errorKind } };
};
function evaluateIfPossible(key, user, defaultVal, eventFactory, resolve, reject) {
if (!initComplete) {
config.featureStore.initialized(function(storeInited) {
if (storeInited) {
config.logger.warn("Variation called before LaunchDarkly client initialization completed (did you wait for the 'ready' event?) - using last known values from feature store")
variationInternal(key, user, defaultVal, eventFactory, resolve, reject);
} else {
var err = new errors.LDClientError("Variation called before LaunchDarkly client initialization completed (did you wait for the 'ready' event?) - using default value");
maybeReportError(err);
var result = errorResult('CLIENT_NOT_READY', defaultVal);
eventProcessor.sendEvent(eventFactory.newUnknownFlagEvent(key, user, result));
return resolve(result);
}
});
} else {
variationInternal(key, user, defaultVal, eventFactory, resolve, reject);
}
}
// resolves to a "detail" object with properties "value", "variationIndex", "reason"
function variationInternal(key, user, defaultVal, eventFactory, resolve, reject) {
if (client.isOffline()) {
config.logger.info("Variation called in offline mode. Returning default value.");
return resolve(errorResult('CLIENT_NOT_READY', defaultVal));
}
else if (!key) {
var err = new errors.LDClientError('No feature flag key specified. Returning default value.');
maybeReportError(err);
return resolve(errorResult('FLAG_NOT_FOUND', defaultVal));
}
if (user && user.key === "") {
config.logger.warn("User key is blank. Flag evaluation will proceed, but the user will not be stored in LaunchDarkly");
}
config.featureStore.get(dataKind.features, key, function(flag) {
if (!flag) {
maybeReportError(new errors.LDClientError('Unknown feature flag "' + key + '"; returning default value'));
var result = errorResult('FLAG_NOT_FOUND', defaultVal);
eventProcessor.sendEvent(eventFactory.newUnknownFlagEvent(key, user, result));
return resolve(result);
}
if (!user) {
var variationErr = new errors.LDClientError('No user specified. Returning default value.');
maybeReportError(variationErr);
var result = errorResult('USER_NOT_SPECIFIED', defaultVal);
eventProcessor.sendEvent(eventFactory.newDefaultEvent(flag, user, result));
return resolve(result);
}
evaluate.evaluate(flag, user, config.featureStore, eventFactory, function(err, detail, events) {
if (err) {
maybeReportError(new errors.LDClientError('Encountered error evaluating feature flag:' + (err.message ? (': ' + err.message) : err)));
}
// Send off any events associated with evaluating prerequisites. The events
// have already been constructed, so we just have to push them onto the queue.
if (events) {
for (var i = 0; i < events.length; i++) {
eventProcessor.sendEvent(events[i]);
}
}
if (detail.variationIndex === null) {
config.logger.debug("Result value is null in variation");
detail.value = defaultVal;
}
eventProcessor.sendEvent(eventFactory.newEvalEvent(flag, user, detail, defaultVal));
return resolve(detail);
});
});
}
client.toggle = function(key, user, defaultVal, callback) {
config.logger.warn("toggle() is deprecated. Call 'variation' instead");
return client.variation(key, user, defaultVal, callback);
}
client.allFlags = function(user, callback) {
config.logger.warn("allFlags() is deprecated. Call 'allFlagsState' instead and call toJSON() on the result");
return wrapPromiseCallback(
client.allFlagsState(user).then(function(state) {
return state.allValues();
}),
callback);
}
client.allFlagsState = function(user, options, callback) {
if (callback === undefined && typeof(options) === 'function') {
callback = options;
options = {};
} else {
options = options || {};
}
return wrapPromiseCallback(new Promise(function(resolve, reject) {
if (this.isOffline()) {
config.logger.info("allFlagsState() called in offline mode. Returning empty state.");
return resolve(FlagsStateBuilder(false).build());
}
if (!user) {
config.logger.info("allFlagsState() called without user. Returning empty state.");
return resolve(FlagsStateBuilder(false).build());
}
var builder = FlagsStateBuilder(true);
var clientOnly = options.clientSideOnly;
var withReasons = options.withReasons;
var detailsOnlyIfTracked = options.detailsOnlyForTrackedFlags;
config.featureStore.all(dataKind.features, function(flags) {
async.forEachOf(flags, function(flag, key, iterateeCb) {
if (clientOnly && !flag.clientSide) {
setImmediate(iterateeCb);
} else {
// At the moment, we don't send any events here
evaluate.evaluate(flag, user, config.featureStore, eventFactoryDefault, function(err, detail, events) {
if (err != null) {
maybeReportError(new Error('Error for feature flag "' + flag.key + '" while evaluating all flags: ' + err));
}
builder.addFlag(flag, detail.value, detail.variationIndex, withReasons ? detail.reason : null, detailsOnlyIfTracked);
setImmediate(iterateeCb);
});
}
}, function(err) {
return err ? reject(err) : resolve(builder.build());
});
});
}.bind(this)), callback);
}
client.secureModeHash = function(user) {
var hmac = crypto.createHmac('sha256', sdkKey);
hmac.update(user.key);
return hmac.digest('hex');
}
client.close = function() {
eventProcessor.close();
if (updateProcessor) {
updateProcessor.close();
}
config.featureStore.close();
}
client.isOffline = function() {
return config.offline;
}
client.track = function(eventName, user, data, metricValue) {
if (!userExistsAndHasKey(user)) {
config.logger.warn(messages.missingUserKeyNoEvent());
return;
}
eventProcessor.sendEvent(eventFactoryDefault.newCustomEvent(eventName, user, data, metricValue));
};
client.identify = function(user) {
if (!userExistsAndHasKey(user)) {
config.logger.warn(messages.missingUserKeyNoEvent());
return;
}
eventProcessor.sendEvent(eventFactoryDefault.newIdentifyEvent(user));
};
client.flush = function(callback) {
return eventProcessor.flush(callback);
};
function userExistsAndHasKey(user) {
if (user) {
var key = user.key;
return key !== undefined && key !== null && key !== "";
}
return false;
}
function deprecatedMethod(oldName, newName) {
client[oldName] = function() {
config.logger.warn(messages.deprecated(oldName, newName));
return client[newName].apply(client, arguments);
};
}
deprecatedMethod('all_flags', 'allFlags');
deprecatedMethod('is_offline', 'isOffline');
deprecatedMethod('secure_mode_hash', 'secureModeHash');
return client;
};
module.exports = {
init: newClient,
RedisFeatureStore: RedisFeatureStore,
FileDataSource: FileDataSource,
errors: errors
};
function createProxyAgent(config) {
var options = {
proxy: {
host: config.proxyHost,
port: config.proxyPort,
proxyAuth: config.proxyAuth
}
};
if (config.proxyScheme === 'https') {
if (!config.baseUri || config.baseUri.startsWith('https')) {
return tunnel.httpsOverHttps(options);
} else {
return tunnel.httpOverHttps(options);
}
} else if (!config.baseUri || config.baseUri.startsWith('https')) {
return tunnel.httpsOverHttp(options);
} else {
return tunnel.httpOverHttp(options);
}
}