-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathBaseOpenFeatureProvider.ts
More file actions
301 lines (276 loc) · 9.9 KB
/
BaseOpenFeatureProvider.ts
File metadata and controls
301 lines (276 loc) · 9.9 KB
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
import type {
EvaluationContext,
Hook,
JsonValue,
Paradigm,
Provider,
ProviderMetadata,
ResolutionDetails,
TrackingEventDetails,
} from '@openfeature/server-sdk';
import {
ErrorCode,
OpenFeatureEventEmitter,
ProviderEvents,
StandardResolutionReasons,
} from '@openfeature/server-sdk';
import { createSafeLogger, type LDLogger } from '@launchdarkly/js-sdk-common';
import type { OpenFeatureLDClientContract } from './OpenFeatureLDClientContract';
import { translateContext } from './translateContext';
import { translateResult } from './translateResult';
import { translateTrackingEventDetails } from './translateTrackingEventDetails';
/**
* Create a ResolutionDetails for an evaluation that produced a type different
* than 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,
};
}
/**
* Configuration for constructing a {@link BaseOpenFeatureProvider}.
*/
export interface BaseProviderConfig {
/** The logger to use for diagnostics. */
logger: LDLogger;
/** The provider name reported in OpenFeature metadata. */
providerName: string;
/** The default timeout in seconds for waitForInitialization. Defaults to 10. */
initTimeoutSeconds?: number;
}
/**
* Base OpenFeature provider for LaunchDarkly server-side SDKs.
*
* Subclasses must:
* 1. Construct or receive an LDClient and pass it to {@link setClient} in their constructor.
* 2. Optionally wire SDK-specific events by calling {@link emitConfigurationChanged}.
*/
export abstract class BaseOpenFeatureProvider<
TClient extends OpenFeatureLDClientContract = OpenFeatureLDClientContract,
> implements Provider {
/**
* Metadata reported to OpenFeature. The provider name is supplied by each
* concrete subclass via the {@link BaseProviderConfig.providerName} field.
*/
readonly metadata: ProviderMetadata;
/**
* The OpenFeature paradigm this provider runs on. LaunchDarkly server-side
* SDKs always run on the server.
*/
readonly runsOn: Paradigm = 'server';
/**
* Event emitter used to surface OpenFeature provider events such as
* {@link ProviderEvents.ConfigurationChanged}.
*/
readonly events = new OpenFeatureEventEmitter();
private _client?: TClient;
private _clientConstructionError?: unknown;
private _logger: LDLogger;
private _initTimeoutSeconds: number;
protected constructor(config: BaseProviderConfig) {
this.metadata = { name: config.providerName };
this._logger = createSafeLogger(config.logger);
this._initTimeoutSeconds = config.initTimeoutSeconds ?? 10;
}
/**
* Called by subclass constructors to register the LDClient instance.
*/
protected setClient(client: TClient): void {
this._client = client;
}
/**
* Called by subclass constructors when client construction throws.
* The error will be re-thrown from {@link initialize}.
*/
protected setClientError(error: unknown): void {
this._clientConstructionError = error;
this._logger.error(`Encountered unrecoverable initialization error, ${error}`);
}
/**
* Emit an OpenFeature ConfigurationChanged event for the given flag key.
* Per-SDK providers call this from their event wiring.
*/
protected emitConfigurationChanged(flagKey: string): void {
this.events.emit(ProviderEvents.ConfigurationChanged, {
flagsChanged: [flagKey],
});
}
/**
* Called by OpenFeature once the provider is registered. Waits for the
* underlying LDClient to finish initialization, or rethrows the error that
* was captured if client construction failed.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async initialize(context?: EvaluationContext): Promise<void> {
if (!this._client) {
if (this._clientConstructionError) {
throw this._clientConstructionError;
}
throw new Error('Unknown problem encountered during initialization');
}
await this._client.waitForInitialization({ timeout: this._initTimeoutSeconds });
}
/**
* Determines the boolean variation of a feature flag for a context, along with information about
* how it was calculated.
*
* If the flag does not evaluate to a boolean value, then the defaultValue will be returned.
*
* @param flagKey The unique key of the feature flag.
* @param defaultValue The default value of the flag, to be used if the value is not available
* from LaunchDarkly.
* @param context The context requesting the flag. The client will generate an analytics event to
* register this context with LaunchDarkly if the context does not already exist.
* @returns A promise which will resolve to a ResolutionDetails.
*/
async resolveBooleanEvaluation(
flagKey: string,
defaultValue: boolean,
context: EvaluationContext,
): Promise<ResolutionDetails<boolean>> {
const res = await this._client!.variationDetail(
flagKey,
translateContext(this._logger, context),
defaultValue,
);
if (typeof res.value === 'boolean') {
return translateResult(res);
}
return wrongTypeResult(defaultValue);
}
/**
* Determines the string variation of a feature flag for a context, along with information about
* how it was calculated.
*
* If the flag does not evaluate to a string value, then the defaultValue will be returned.
*
* @param flagKey The unique key of the feature flag.
* @param defaultValue The default value of the flag, to be used if the value is not available
* from LaunchDarkly.
* @param context The context requesting the flag. The client will generate an analytics event to
* register this context with LaunchDarkly if the context does not already exist.
* @returns A promise which will resolve to a ResolutionDetails.
*/
async resolveStringEvaluation(
flagKey: string,
defaultValue: string,
context: EvaluationContext,
): Promise<ResolutionDetails<string>> {
const res = await this._client!.variationDetail(
flagKey,
translateContext(this._logger, context),
defaultValue,
);
if (typeof res.value === 'string') {
return translateResult(res);
}
return wrongTypeResult(defaultValue);
}
/**
* Determines the numeric variation of a feature flag for a context, along with information about
* how it was calculated.
*
* If the flag does not evaluate to a numeric value, then the defaultValue will be returned.
*
* @param flagKey The unique key of the feature flag.
* @param defaultValue The default value of the flag, to be used if the value is not available
* from LaunchDarkly.
* @param context The context requesting the flag. The client will generate an analytics event to
* register this context with LaunchDarkly if the context does not already exist.
* @returns A promise which will resolve to a ResolutionDetails.
*/
async resolveNumberEvaluation(
flagKey: string,
defaultValue: number,
context: EvaluationContext,
): Promise<ResolutionDetails<number>> {
const res = await this._client!.variationDetail(
flagKey,
translateContext(this._logger, context),
defaultValue,
);
if (typeof res.value === 'number') {
return translateResult(res);
}
return wrongTypeResult(defaultValue);
}
/**
* Determines the object variation of a feature flag for a context, along with information about
* how it was calculated.
*
* If the flag does not evaluate to a JSON object value, then the defaultValue will be returned.
*
* @param flagKey The unique key of the feature flag.
* @param defaultValue The default value of the flag, to be used if the value is not available
* from LaunchDarkly.
* @param context The context requesting the flag. The client will generate an analytics event to
* register this context with LaunchDarkly if the context does not already exist.
* @returns A promise which will resolve to a ResolutionDetails.
*/
async resolveObjectEvaluation<U extends JsonValue>(
flagKey: string,
defaultValue: U,
context: EvaluationContext,
): Promise<ResolutionDetails<U>> {
const res = await this._client!.variationDetail(
flagKey,
translateContext(this._logger, context),
defaultValue,
);
if (res.value !== null && typeof res.value === 'object') {
return translateResult(res);
}
return wrongTypeResult<U>(defaultValue);
}
/**
* Returns the OpenFeature hooks registered for this provider. The
* LaunchDarkly provider does not currently register any provider-level
* hooks, so this always returns an empty array.
*/
get hooks(): Hook[] {
return [];
}
/**
* Get the LDClient instance used by this provider.
*
* @returns The client for this provider.
*/
getClient(): TClient {
return this._client!;
}
/**
* Called by OpenFeature when it needs to close the provider. This will flush
* events from the LDClient and then close it.
*/
async onClose(): Promise<void> {
try {
await this._client?.flush();
} finally {
this._client?.close();
}
}
/**
* Track a user action or application state, usually representing a business objective or outcome.
* @param trackingEventName The name of the event, which may correspond to a metric
* in Experimentation.
* @param context The context to track.
* @param trackingEventDetails Optional additional information to associate with the event.
*/
track(
trackingEventName: string,
context: EvaluationContext,
trackingEventDetails?: TrackingEventDetails,
): void {
this._client?.track(
trackingEventName,
translateContext(this._logger, context),
trackingEventDetails ? translateTrackingEventDetails(trackingEventDetails) : undefined,
trackingEventDetails?.value,
);
}
}