forked from open-feature/js-sdk-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlaunchdarkly-client-provider.ts
165 lines (141 loc) · 5.09 KB
/
launchdarkly-client-provider.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
import {
EvaluationContext,
Provider,
JsonValue,
ResolutionDetails,
StandardResolutionReasons,
ErrorCode,
ProviderMetadata,
Logger,
GeneralError,
OpenFeatureEventEmitter,
ProviderEvents,
ProviderStatus,
TrackingEventDetails,
} from '@openfeature/web-sdk';
import isEmpty from 'lodash.isempty';
import { basicLogger, LDClient, initialize, LDOptions, LDFlagChangeset } from 'launchdarkly-js-client-sdk';
import { LaunchDarklyProviderOptions } from './launchdarkly-provider-options';
import translateContext from './translate-context';
import translateResult from './translate-result';
/**
* Create a ResolutionDetails for an evaluation that produced a type different
* from the expected type.
* @param value The default value to populate the ResolutionDetails with.
* @returns A ResolutionDetails with the default value.
*/
function wrongTypeResult<T>(value: T): ResolutionDetails<T> {
return {
value,
reason: StandardResolutionReasons.ERROR,
errorCode: ErrorCode.TYPE_MISMATCH,
};
}
export class LaunchDarklyClientProvider implements Provider {
readonly metadata: ProviderMetadata = {
name: 'launchdarkly-client-provider',
};
private readonly ldOptions: LDOptions | undefined;
private readonly logger: Logger;
private readonly initializationTimeout?: number;
private _client?: LDClient;
public events = new OpenFeatureEventEmitter();
/*
* implement status field/accessor
* https://openfeature.dev/specification/sections/providers#requirement-242
* */
private _status: ProviderStatus = ProviderStatus.NOT_READY;
set status(status: ProviderStatus) {
this._status = status;
}
get status() {
return this._status;
}
constructor(
private readonly envKey: string,
{ logger, initializationTimeout, ...ldOptions }: LaunchDarklyProviderOptions,
) {
if (logger) {
this.logger = logger;
} else {
this.logger = basicLogger({ level: 'info' });
}
this.initializationTimeout = initializationTimeout;
this.ldOptions = { ...ldOptions, logger: this.logger };
}
private get client(): LDClient {
if (!this._client) {
throw new GeneralError('Provider is not initialized');
}
return this._client;
}
async initialize(context?: EvaluationContext): Promise<void> {
const _context = isEmpty(context) ? { anonymous: true } : this.translateContext(context);
this._client = initialize(this.envKey, _context, this.ldOptions);
/*
* set event listeners to propagate ld events to open feature provider,
* use LD property streaming, since when enabled you are opting in for straming updates
* */
if (this.ldOptions?.streaming) {
this.setListeners();
}
try {
await this._client.waitForInitialization(this.initializationTimeout);
this.status = ProviderStatus.READY;
} catch {
this.status = ProviderStatus.ERROR;
}
}
onClose(): Promise<void> {
return this.client.close();
}
/** set listeners to LD client and event the correspodent event in the Provider
* necessary for LD streaming changes
* */
private setListeners() {
this.client.on('change', (changeset: LDFlagChangeset) => {
this.events.emit(ProviderEvents.ConfigurationChanged, {
flagsChanged: Object.keys(changeset),
});
});
}
async onContextChange(oldContext: EvaluationContext, newContext: EvaluationContext): Promise<void> {
// update the context on the LaunchDarkly client, this is so it does not have to be checked on each evaluation
await this.client.identify(this.translateContext(newContext));
}
resolveBooleanEvaluation(flagKey: string, defaultValue: boolean): ResolutionDetails<boolean> {
const res = this.client.variationDetail(flagKey, defaultValue);
if (typeof res.value === 'boolean') {
return translateResult(res);
}
return wrongTypeResult(defaultValue);
}
resolveNumberEvaluation(flagKey: string, defaultValue: number): ResolutionDetails<number> {
const res = this.client.variationDetail(flagKey, defaultValue);
if (typeof res.value === 'number') {
return translateResult(res);
}
return wrongTypeResult(defaultValue);
}
resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T): ResolutionDetails<T> {
const res = this.client.variationDetail(flagKey, defaultValue);
if (typeof res.value === 'object') {
return translateResult(res);
}
return wrongTypeResult<T>(defaultValue);
}
resolveStringEvaluation(flagKey: string, defaultValue: string): ResolutionDetails<string> {
const res = this.client.variationDetail(flagKey, defaultValue);
if (typeof res.value === 'string') {
return translateResult(res);
}
return wrongTypeResult(defaultValue);
}
track(trackingEventName: string, _context: EvaluationContext, { value, ...details }: TrackingEventDetails): void {
// The LD Client already has the context form the identify method, so we can omit it here.
this.client.track(trackingEventName, details, value);
}
private translateContext(context: EvaluationContext) {
return translateContext(this.logger, context);
}
}