-
Notifications
You must be signed in to change notification settings - Fork 12
/
LDClientImpl.ts
541 lines (475 loc) · 17.5 KB
/
LDClientImpl.ts
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
import {
AutoEnvAttributes,
ClientContext,
clone,
Context,
internal,
LDClientError,
LDContext,
LDEvaluationDetail,
LDEvaluationDetailTyped,
LDFlagSet,
LDFlagValue,
LDLogger,
Platform,
ProcessStreamResponse,
EventName as StreamEventName,
timedPromise,
TypeValidators,
} from '@launchdarkly/js-sdk-common';
import { ConnectionMode, LDClient, type LDOptions } from './api';
import LDEmitter, { EventName } from './api/LDEmitter';
import { LDIdentifyOptions } from './api/LDIdentifyOptions';
import Configuration from './configuration';
import createDiagnosticsManager from './diagnostics/createDiagnosticsManager';
import createEventProcessor from './events/createEventProcessor';
import EventFactory from './events/EventFactory';
import { DeleteFlag, Flags, PatchFlag } from './types';
import { addAutoEnv, calculateFlagChanges, ensureKey } from './utils';
const { createErrorEvaluationDetail, createSuccessEvaluationDetail, ClientMessages, ErrorKinds } =
internal;
export default class LDClientImpl implements LDClient {
config: Configuration;
context?: LDContext;
diagnosticsManager?: internal.DiagnosticsManager;
eventProcessor?: internal.EventProcessor;
identifyTimeout: number = 5;
logger: LDLogger;
streamer?: internal.StreamingProcessor;
readonly highTimeoutThreshold: number = 15;
private eventFactoryDefault = new EventFactory(false);
private eventFactoryWithReasons = new EventFactory(true);
private emitter: LDEmitter;
private flags: Flags = {};
private readonly clientContext: ClientContext;
/**
* Creates the client object synchronously. No async, no network calls.
*/
constructor(
public readonly sdkKey: string,
public readonly autoEnvAttributes: AutoEnvAttributes,
public readonly platform: Platform,
options: LDOptions,
internalOptions?: internal.LDInternalOptions,
) {
if (!sdkKey) {
throw new Error('You must configure the client with a client-side SDK key');
}
if (!platform.encoding) {
throw new Error('Platform must implement Encoding because btoa is required.');
}
this.config = new Configuration(options, internalOptions);
this.clientContext = new ClientContext(sdkKey, this.config, platform);
this.logger = this.config.logger;
this.diagnosticsManager = createDiagnosticsManager(sdkKey, this.config, platform);
this.eventProcessor = createEventProcessor(
sdkKey,
this.config,
platform,
this.diagnosticsManager,
!this.isOffline(),
);
this.emitter = new LDEmitter();
this.emitter.on('change', (c: LDContext, changedKeys: string[]) => {
this.logger.debug(`change: context: ${JSON.stringify(c)}, flags: ${changedKeys}`);
});
this.emitter.on('error', (c: LDContext, err: any) => {
this.logger.error(`error: ${err}, context: ${JSON.stringify(c)}`);
});
}
/**
* Sets the SDK connection mode.
*
* @param mode - One of supported {@link ConnectionMode}. Default is 'streaming'.
*/
async setConnectionMode(mode: ConnectionMode): Promise<void> {
if (this.config.connectionMode === mode) {
this.logger.debug(`setConnectionMode ignored. Mode is already '${mode}'.`);
return Promise.resolve();
}
this.config.connectionMode = mode;
this.logger.debug(`setConnectionMode ${mode}.`);
switch (mode) {
case 'offline':
return this.close();
case 'streaming':
this.eventProcessor?.start();
if (this.context) {
// identify will start streamer
return this.identify(this.context, { timeout: this.identifyTimeout });
}
break;
default:
this.logger.warn(
`Unknown ConnectionMode: ${mode}. Only 'offline' and 'streaming' are supported.`,
);
break;
}
return Promise.resolve();
}
/**
* Gets the SDK connection mode.
*/
getConnectionMode(): ConnectionMode {
return this.config.connectionMode;
}
isOffline() {
return this.config.connectionMode === 'offline';
}
allFlags(): LDFlagSet {
const result: LDFlagSet = {};
Object.entries(this.flags).forEach(([k, r]) => {
if (!r.deleted) {
result[k] = r.value;
}
});
return result;
}
async close(): Promise<void> {
await this.flush();
this.eventProcessor?.close();
this.streamer?.close();
this.logger.debug('Closed eventProcessor and streamer.');
}
async flush(): Promise<{ error?: Error; result: boolean }> {
try {
await this.eventProcessor?.flush();
this.logger.debug('Successfully flushed eventProcessor.');
} catch (e) {
this.logger.error(`Error flushing eventProcessor: ${e}.`);
return { error: e as Error, result: false };
}
return { result: true };
}
getContext(): LDContext | undefined {
return this.context ? clone<LDContext>(this.context) : undefined;
}
private createStreamListeners(
context: LDContext,
canonicalKey: string,
identifyResolve: any,
): Map<StreamEventName, ProcessStreamResponse> {
const listeners = new Map<StreamEventName, ProcessStreamResponse>();
listeners.set('put', {
deserializeData: JSON.parse,
processJson: async (dataJson: Flags) => {
this.logger.debug(`Streamer PUT: ${Object.keys(dataJson)}`);
this.onIdentifyResolve(identifyResolve, dataJson, context, 'streamer PUT');
await this.platform.storage?.set(canonicalKey, JSON.stringify(this.flags));
},
});
listeners.set('patch', {
deserializeData: JSON.parse,
processJson: async (dataJson: PatchFlag) => {
this.logger.debug(`Streamer PATCH ${JSON.stringify(dataJson, null, 2)}`);
const existing = this.flags[dataJson.key];
// add flag if it doesn't exist or update it if version is newer
if (!existing || (existing && dataJson.version > existing.version)) {
this.flags[dataJson.key] = dataJson;
await this.platform.storage?.set(canonicalKey, JSON.stringify(this.flags));
const changedKeys = [dataJson.key];
this.logger.debug(`Emitting changes from PATCH: ${changedKeys}`);
this.emitter.emit('change', context, changedKeys);
}
},
});
listeners.set('delete', {
deserializeData: JSON.parse,
processJson: async (dataJson: DeleteFlag) => {
this.logger.debug(`Streamer DELETE ${JSON.stringify(dataJson, null, 2)}`);
const existing = this.flags[dataJson.key];
// the deleted flag is saved as tombstoned
if (!existing || existing.version < dataJson.version) {
this.flags[dataJson.key] = {
...dataJson,
deleted: true,
// props below are set to sensible defaults. they are irrelevant
// because this flag has been deleted.
flagVersion: 0,
value: undefined,
variation: 0,
trackEvents: false,
};
await this.platform.storage?.set(canonicalKey, JSON.stringify(this.flags));
const changedKeys = [dataJson.key];
this.logger.debug(`Emitting changes from DELETE: ${changedKeys}`);
this.emitter.emit('change', context, changedKeys);
}
},
});
return listeners;
}
/**
* Generates the url path for streamer.
*
* For mobile key: /meval/${base64-encoded-context}
* For clientSideId: /eval/${envId}/${base64-encoded-context}
*
* the path.
*
* @protected This function must be overridden in subclasses for streamer
* to work.
* @param _context The LDContext object
*/
protected createStreamUriPath(_context: LDContext): string {
throw new Error(
'createStreamUriPath not implemented. Client sdks must implement createStreamUriPath for streamer to work.',
);
}
private createIdentifyPromise(timeout: number) {
let res: any;
let rej: any;
const slow = new Promise<void>((resolve, reject) => {
res = resolve;
rej = reject;
});
const timed = timedPromise(timeout, 'identify');
const raced = Promise.race([timed, slow]).catch((e) => {
if (e.message.includes('timed out')) {
this.logger.error(`identify error: ${e}`);
}
throw e;
});
return { identifyPromise: raced, identifyResolve: res, identifyReject: rej };
}
private async getFlagsFromStorage(canonicalKey: string): Promise<Flags | undefined> {
const f = await this.platform.storage?.get(canonicalKey);
return f ? JSON.parse(f) : undefined;
}
/**
* Identifies a context to LaunchDarkly. See {@link LDClient.identify}.
*
* @param pristineContext The LDContext object to be identified.
* @param identifyOptions Optional configuration. See {@link LDIdentifyOptions}.
* @returns A Promise which resolves when the flag values for the specified
* context are available. It rejects when:
*
* 1. The context is unspecified or has no key.
*
* 2. The identify timeout is exceeded. In client SDKs this defaults to 5s.
* You can customize this timeout with {@link LDIdentifyOptions | identifyOptions}.
*
* 3. A network error is encountered during initialization.
*/
async identify(pristineContext: LDContext, identifyOptions?: LDIdentifyOptions): Promise<void> {
if (identifyOptions?.timeout) {
this.identifyTimeout = identifyOptions.timeout;
}
if (this.identifyTimeout > this.highTimeoutThreshold) {
this.logger.warn(
'The identify function was called with a timeout greater than' +
`${this.highTimeoutThreshold} seconds. We recommend a timeout of less than` +
`${this.highTimeoutThreshold} seconds.`,
);
}
let context = await ensureKey(pristineContext, this.platform);
if (this.autoEnvAttributes === AutoEnvAttributes.Enabled) {
context = await addAutoEnv(context, this.platform, this.config);
}
const checkedContext = Context.fromLDContext(context);
if (!checkedContext.valid) {
const error = new Error('Context was unspecified or had no key');
this.emitter.emit('error', context, error);
return Promise.reject(error);
}
this.eventProcessor?.sendEvent(this.eventFactoryDefault.identifyEvent(checkedContext));
const { identifyPromise, identifyResolve, identifyReject } = this.createIdentifyPromise(
this.identifyTimeout,
);
this.logger.debug(`Identifying ${JSON.stringify(context)}`);
const flagsStorage = await this.getFlagsFromStorage(checkedContext.canonicalKey);
if (flagsStorage) {
this.logger.debug('Using storage');
this.onIdentifyResolve(identifyResolve, flagsStorage, context, 'identify storage');
}
if (this.isOffline()) {
if (flagsStorage) {
this.logger.debug('Offline identify using storage flags.');
} else {
this.logger.debug('Offline identify no storage. Defaults will be used.');
this.context = context;
this.flags = {};
identifyResolve();
}
} else {
this.streamer?.close();
let streamUri = this.createStreamUriPath(context);
if (this.config.withReasons) {
streamUri = `${streamUri}?withReasons=true`;
}
this.streamer = new internal.StreamingProcessor(
this.sdkKey,
this.clientContext,
streamUri,
this.createStreamListeners(context, checkedContext.canonicalKey, identifyResolve),
this.diagnosticsManager,
(e) => {
identifyReject(e);
this.emitter.emit('error', context, e);
},
);
this.streamer.start();
}
return identifyPromise;
}
/**
* Performs common tasks when resolving the identify promise:
* - resolve the promise
* - update in memory context
* - update in memory flags
* - emit change event if needed
*
* @param resolve
* @param flags
* @param context
* @param source For logging purposes
* @private
*/
private onIdentifyResolve(resolve: any, flags: Flags, context: LDContext, source: string) {
resolve();
const changedKeys = calculateFlagChanges(this.flags, flags);
this.context = context;
this.flags = flags;
if (changedKeys.length > 0) {
this.emitter.emit('change', context, changedKeys);
this.logger.debug(`OnIdentifyResolve emitting changes from: ${source}.`);
} else {
this.logger.debug(`OnIdentifyResolve no changes to emit from: ${source}.`);
}
}
off(eventName: EventName, listener: Function): void {
this.emitter.off(eventName, listener);
}
on(eventName: EventName, listener: Function): void {
this.emitter.on(eventName, listener);
}
track(key: string, data?: any, metricValue?: number): void {
if (!this.context) {
this.logger.warn(ClientMessages.missingContextKeyNoEvent);
return;
}
const checkedContext = Context.fromLDContext(this.context);
if (!checkedContext.valid) {
this.logger.warn(ClientMessages.missingContextKeyNoEvent);
return;
}
// 0 is valid, so do not truthy check the metric value
if (metricValue !== undefined && !TypeValidators.Number.is(metricValue)) {
this.logger?.warn(ClientMessages.invalidMetricValue(typeof metricValue));
}
this.eventProcessor?.sendEvent(
this.eventFactoryDefault.customEvent(key, checkedContext!, data, metricValue),
);
}
private variationInternal(
flagKey: string,
defaultValue: any,
eventFactory: EventFactory,
typeChecker?: (value: any) => [boolean, string],
): LDFlagValue {
if (!this.context) {
this.logger.debug(ClientMessages.missingContextKeyNoEvent);
return createErrorEvaluationDetail(ErrorKinds.UserNotSpecified, defaultValue);
}
const evalContext = Context.fromLDContext(this.context);
const found = this.flags[flagKey];
if (!found || found.deleted) {
const defVal = defaultValue ?? null;
const error = new LDClientError(
`Unknown feature flag "${flagKey}"; returning default value ${defVal}.`,
);
this.emitter.emit('error', this.context, error);
this.eventProcessor?.sendEvent(
this.eventFactoryDefault.unknownFlagEvent(flagKey, defVal, evalContext),
);
return createErrorEvaluationDetail(ErrorKinds.FlagNotFound, defaultValue);
}
const { reason, value, variation } = found;
if (typeChecker) {
const [matched, type] = typeChecker(value);
if (!matched) {
this.eventProcessor?.sendEvent(
eventFactory.evalEventClient(
flagKey,
defaultValue, // track default value on type errors
defaultValue,
found,
evalContext,
reason,
),
);
const error = new LDClientError(
`Wrong type "${type}" for feature flag "${flagKey}"; returning default value`,
);
this.emitter.emit('error', this.context, error);
return createErrorEvaluationDetail(ErrorKinds.WrongType, defaultValue);
}
}
const successDetail = createSuccessEvaluationDetail(value, variation, reason);
if (variation === undefined || variation === null) {
this.logger.debug('Result value is null in variation');
successDetail.value = defaultValue;
}
this.eventProcessor?.sendEvent(
eventFactory.evalEventClient(flagKey, value, defaultValue, found, evalContext, reason),
);
return successDetail;
}
variation(flagKey: string, defaultValue?: LDFlagValue): LDFlagValue {
const { value } = this.variationInternal(flagKey, defaultValue, this.eventFactoryDefault);
return value;
}
variationDetail(flagKey: string, defaultValue?: LDFlagValue): LDEvaluationDetail {
return this.variationInternal(flagKey, defaultValue, this.eventFactoryWithReasons);
}
private typedEval<T>(
key: string,
defaultValue: T,
eventFactory: EventFactory,
typeChecker: (value: unknown) => [boolean, string],
): LDEvaluationDetailTyped<T> {
return this.variationInternal(key, defaultValue, eventFactory, typeChecker);
}
boolVariation(key: string, defaultValue: boolean): boolean {
return this.typedEval(key, defaultValue, this.eventFactoryDefault, (value) => [
TypeValidators.Boolean.is(value),
TypeValidators.Boolean.getType(),
]).value;
}
jsonVariation(key: string, defaultValue: unknown): unknown {
return this.variation(key, defaultValue);
}
numberVariation(key: string, defaultValue: number): number {
return this.typedEval(key, defaultValue, this.eventFactoryDefault, (value) => [
TypeValidators.Number.is(value),
TypeValidators.Number.getType(),
]).value;
}
stringVariation(key: string, defaultValue: string): string {
return this.typedEval(key, defaultValue, this.eventFactoryDefault, (value) => [
TypeValidators.String.is(value),
TypeValidators.String.getType(),
]).value;
}
boolVariationDetail(key: string, defaultValue: boolean): LDEvaluationDetailTyped<boolean> {
return this.typedEval(key, defaultValue, this.eventFactoryWithReasons, (value) => [
TypeValidators.Boolean.is(value),
TypeValidators.Boolean.getType(),
]);
}
numberVariationDetail(key: string, defaultValue: number): LDEvaluationDetailTyped<number> {
return this.typedEval(key, defaultValue, this.eventFactoryWithReasons, (value) => [
TypeValidators.Number.is(value),
TypeValidators.Number.getType(),
]);
}
stringVariationDetail(key: string, defaultValue: string): LDEvaluationDetailTyped<string> {
return this.typedEval(key, defaultValue, this.eventFactoryWithReasons, (value) => [
TypeValidators.String.is(value),
TypeValidators.String.getType(),
]);
}
jsonVariationDetail(key: string, defaultValue: unknown): LDEvaluationDetailTyped<unknown> {
return this.variationDetail(key, defaultValue);
}
}