-
Notifications
You must be signed in to change notification settings - Fork 23
/
index.ts
467 lines (419 loc) · 18.5 KB
/
index.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
import { RequestInit } from 'node-fetch';
import { getEnvironmentFeatureStates, getIdentityFeatureStates } from '../flagsmith-engine';
import { EnvironmentModel } from '../flagsmith-engine/environments/models';
import { buildEnvironmentModel } from '../flagsmith-engine/environments/util';
import { IdentityModel } from '../flagsmith-engine/identities/models';
import { TraitModel } from '../flagsmith-engine/identities/traits/models';
import { AnalyticsProcessor } from './analytics';
import { BaseOfflineHandler } from './offline_handlers';
import { FlagsmithAPIError, FlagsmithClientError } from './errors';
import { DefaultFlag, Flags } from './models';
import { EnvironmentDataPollingManager } from './polling_manager';
import { generateIdentitiesData, retryFetch } from './utils';
import { SegmentModel } from '../flagsmith-engine/segments/models';
import { getIdentitySegments } from '../flagsmith-engine/segments/evaluators';
import { FlagsmithCache, FlagsmithConfig } from './types';
import pino, { Logger } from 'pino';
export { AnalyticsProcessor } from './analytics';
export { FlagsmithAPIError, FlagsmithClientError } from './errors';
export { DefaultFlag, Flags } from './models';
export { EnvironmentDataPollingManager } from './polling_manager';
export { FlagsmithCache, FlagsmithConfig } from './types';
const DEFAULT_API_URL = 'https://edge.api.flagsmith.com/api/v1/';
const DEFAULT_REQUEST_TIMEOUT_SECONDS = 10;
export class Flagsmith {
environmentKey?: string = undefined;
apiUrl?: string = undefined;
customHeaders?: { [key: string]: any };
agent: RequestInit['agent'];
requestTimeoutMs?: number;
enableLocalEvaluation?: boolean = false;
environmentRefreshIntervalSeconds: number = 60;
retries?: number;
enableAnalytics: boolean = false;
defaultFlagHandler?: (featureName: string) => DefaultFlag;
environmentFlagsUrl?: string;
identitiesUrl?: string;
environmentUrl?: string;
environmentDataPollingManager?: EnvironmentDataPollingManager;
environment!: EnvironmentModel;
offlineMode: boolean = false;
offlineHandler?: BaseOfflineHandler = undefined;
private cache?: FlagsmithCache;
private onEnvironmentChange?: (error: Error | null, result: EnvironmentModel) => void;
private analyticsProcessor?: AnalyticsProcessor;
private logger: Logger;
/**
* A Flagsmith client.
*
* Provides an interface for interacting with the Flagsmith http API.
* Basic Usage::
*
* import flagsmith from Flagsmith
* const flagsmith = new Flagsmith({environmentKey: '<your API key>'});
* const environmentFlags = flagsmith.getEnvironmentFlags();
* const featureEnabled = environmentFlags.isFeatureEnabled('foo');
* const identityFlags = flagsmith.getIdentityFlags('identifier', {'foo': 'bar'});
* const featureEnabledForIdentity = identityFlags.isFeatureEnabled("foo")
*
* @param {string} data.environmentKey: The environment key obtained from Flagsmith interface
* Required unless offlineMode is True.
@param {string} data.apiUrl: Override the URL of the Flagsmith API to communicate with
@param data.customHeaders: Additional headers to add to requests made to the
Flagsmith API
@param {number} data.requestTimeoutSeconds: Number of seconds to wait for a request to
complete before terminating the request
@param {boolean} data.enableLocalEvaluation: Enables local evaluation of flags
@param {number} data.environmentRefreshIntervalSeconds: If using local evaluation,
specify the interval period between refreshes of local environment data
@param {number} data.retries: a urllib3.Retry object to use on all http requests to the
Flagsmith API
@param {boolean} data.enableAnalytics: if enabled, sends additional requests to the Flagsmith
API to power flag analytics charts
@param data.defaultFlagHandler: callable which will be used in the case where
flags cannot be retrieved from the API or a non-existent feature is
requested
@param data.logger: an instance of the pino Logger class to use for logging
@param {boolean} data.offlineMode: sets the client into offline mode. Relies on offlineHandler for
evaluating flags.
@param {BaseOfflineHandler} data.offlineHandler: provide a handler for offline logic. Used to get environment
document from another source when in offlineMode. Works in place of
defaultFlagHandler if offlineMode is not set and using remote evaluation.
*/
constructor(data: FlagsmithConfig = {}) {
// if (!data.offlineMode && !data.environmentKey) {
// throw new Error('ValueError: environmentKey is required.');
// }
this.agent = data.agent;
this.environmentKey = data.environmentKey;
this.apiUrl = data.apiUrl || this.apiUrl;
this.customHeaders = data.customHeaders;
this.requestTimeoutMs =
1000 * (data.requestTimeoutSeconds ?? DEFAULT_REQUEST_TIMEOUT_SECONDS);
this.enableLocalEvaluation = data.enableLocalEvaluation;
this.environmentRefreshIntervalSeconds =
data.environmentRefreshIntervalSeconds || this.environmentRefreshIntervalSeconds;
this.retries = data.retries;
this.enableAnalytics = data.enableAnalytics || false;
this.defaultFlagHandler = data.defaultFlagHandler;
this.onEnvironmentChange = data.onEnvironmentChange;
this.logger = data.logger || pino();
this.offlineMode = data.offlineMode || false;
this.offlineHandler = data.offlineHandler;
// argument validation
if (this.offlineMode && !this.offlineHandler) {
throw new Error('ValueError: offlineHandler must be provided to use offline mode.');
} else if (this.defaultFlagHandler && this.offlineHandler) {
throw new Error('ValueError: Cannot use both defaultFlagHandler and offlineHandler.');
}
if (this.offlineHandler) {
this.environment = this.offlineHandler.getEnvironment();
}
if (!!data.cache) {
const missingMethods: string[] = ['has', 'get', 'set'].filter(
method => data.cache && !data.cache[method]
);
if (missingMethods.length > 0) {
throw new Error(
`Please implement the following methods in your cache: ${missingMethods.join(
', '
)}`
);
}
this.cache = data.cache;
}
if (!this.offlineMode) {
if (!this.environmentKey) {
throw new Error('ValueError: environmentKey is required.');
}
const apiUrl = data.apiUrl || DEFAULT_API_URL;
this.apiUrl = apiUrl.endsWith('/') ? apiUrl : `${apiUrl}/`;
this.environmentFlagsUrl = `${this.apiUrl}flags/`;
this.identitiesUrl = `${this.apiUrl}identities/`;
this.environmentUrl = `${this.apiUrl}environment-document/`;
if (this.enableLocalEvaluation) {
if (!this.environmentKey.startsWith('ser.')) {
console.error(
'In order to use local evaluation, please generate a server key in the environment settings page.'
);
}
this.environmentDataPollingManager = new EnvironmentDataPollingManager(
this,
this.environmentRefreshIntervalSeconds
);
this.environmentDataPollingManager.start();
this.updateEnvironment();
}
this.analyticsProcessor = data.enableAnalytics
? new AnalyticsProcessor({
environmentKey: this.environmentKey,
baseApiUrl: this.apiUrl,
requestTimeoutMs: this.requestTimeoutMs,
logger: this.logger
})
: undefined;
}
}
/**
* Get all the default for flags for the current environment.
*
* @returns Flags object holding all the flags for the current environment.
*/
async getEnvironmentFlags(): Promise<Flags> {
const cachedItem = !!this.cache && (await this.cache.get(`flags`));
if (!!cachedItem) {
return cachedItem;
}
if (this.enableLocalEvaluation && !this.offlineMode) {
return new Promise((resolve, reject) =>
this.environmentPromise!.then(() => {
resolve(this.getEnvironmentFlagsFromDocument());
}).catch(e => reject(e))
);
}
if (this.environment) {
return this.getEnvironmentFlagsFromDocument();
}
return this.getEnvironmentFlagsFromApi();
}
/**
* Get all the flags for the current environment for a given identity. Will also
upsert all traits to the Flagsmith API for future evaluations. Providing a
trait with a value of None will remove the trait from the identity if it exists.
*
* @param {string} identifier a unique identifier for the identity in the current
environment, e.g. email address, username, uuid
* @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
Flagsmith, e.g. {"num_orders": 10}
* @returns Flags object holding all the flags for the given identity.
*/
async getIdentityFlags(identifier: string, traits?: { [key: string]: any }): Promise<Flags> {
if (!identifier) {
throw new Error('`identifier` argument is missing or invalid.');
}
const cachedItem = !!this.cache && (await this.cache.get(`flags-${identifier}`));
if (!!cachedItem) {
return cachedItem;
}
traits = traits || {};
if (this.enableLocalEvaluation) {
return new Promise((resolve, reject) =>
this.environmentPromise!.then(() => {
resolve(this.getIdentityFlagsFromDocument(identifier, traits || {}));
}).catch(e => reject(e))
);
}
if (this.offlineMode) {
return this.getIdentityFlagsFromDocument(identifier, traits || {});
}
return this.getIdentityFlagsFromApi(identifier, traits);
}
/**
* Get the segments for the current environment for a given identity. Will also
upsert all traits to the Flagsmith API for future evaluations. Providing a
trait with a value of None will remove the trait from the identity if it exists.
*
* @param {string} identifier a unique identifier for the identity in the current
environment, e.g. email address, username, uuid
* @param {{[key:string]:any}} traits? a dictionary of traits to add / update on the identity in
Flagsmith, e.g. {"num_orders": 10}
* @returns Segments that the given identity belongs to.
*/
getIdentitySegments(
identifier: string,
traits?: { [key: string]: any }
): Promise<SegmentModel[]> {
if (!identifier) {
throw new Error('`identifier` argument is missing or invalid.');
}
traits = traits || {};
if (this.enableLocalEvaluation) {
return new Promise((resolve, reject) => {
return this.environmentPromise!.then(() => {
const identityModel = this.buildIdentityModel(
identifier,
Object.keys(traits || {}).map(key => ({
key,
value: traits?.[key]
}))
);
const segments = getIdentitySegments(this.environment, identityModel);
return resolve(segments);
}).catch(e => reject(e));
});
}
console.error('This function is only permitted with local evaluation.');
return Promise.resolve([]);
}
/**
* Updates the environment state for local flag evaluation.
* Sets a local promise to prevent race conditions in getIdentityFlags / getIdentitySegments.
* You only need to call this if you wish to bypass environmentRefreshIntervalSeconds.
*/
async updateEnvironment() {
try {
const request = this.getEnvironmentFromApi();
if (!this.environmentPromise) {
this.environmentPromise = request.then(res => {
this.environment = res;
});
await this.environmentPromise;
} else {
this.environment = await request;
}
if (this.onEnvironmentChange) {
this.onEnvironmentChange(null, this.environment);
}
} catch (e) {
if (this.onEnvironmentChange) {
this.onEnvironmentChange(e as Error, this.environment);
}
}
}
async close() {
this.environmentDataPollingManager?.stop();
}
private async getJSONResponse(
url: string,
method: string,
body?: { [key: string]: any }
): Promise<any> {
const headers: { [key: string]: any } = { 'Content-Type': 'application/json' };
if (this.environmentKey) {
headers['X-Environment-Key'] = this.environmentKey as string;
}
if (this.customHeaders) {
for (const [k, v] of Object.entries(this.customHeaders)) {
headers[k] = v;
}
}
const data = await retryFetch(
url,
{
agent: this.agent,
method: method,
body: JSON.stringify(body),
headers: headers
},
this.retries,
this.requestTimeoutMs || undefined
);
if (data.status !== 200) {
throw new FlagsmithAPIError(
`Invalid request made to Flagsmith API. Response status code: ${data.status}`
);
}
return data.json();
}
/**
* This promise ensures that the environment is retrieved before attempting to locally evaluate.
*/
private environmentPromise: Promise<any> | undefined;
private async getEnvironmentFromApi() {
if (!this.environmentUrl) {
throw new Error('`apiUrl` argument is missing or invalid.');
}
const environment_data = await this.getJSONResponse(this.environmentUrl, 'GET');
return buildEnvironmentModel(environment_data);
}
private async getEnvironmentFlagsFromDocument(): Promise<Flags> {
const flags = Flags.fromFeatureStateModels({
featureStates: getEnvironmentFeatureStates(this.environment),
analyticsProcessor: this.analyticsProcessor,
defaultFlagHandler: this.defaultFlagHandler
});
if (!!this.cache) {
// @ts-ignore node-cache types are incorrect, ttl should be optional
await this.cache.set('flags', flags);
}
return flags;
}
private async getIdentityFlagsFromDocument(
identifier: string,
traits: { [key: string]: any }
): Promise<Flags> {
const identityModel = this.buildIdentityModel(
identifier,
Object.keys(traits).map(key => ({
key,
value: traits[key]
}))
);
const featureStates = getIdentityFeatureStates(this.environment, identityModel);
const flags = Flags.fromFeatureStateModels({
featureStates: featureStates,
analyticsProcessor: this.analyticsProcessor,
defaultFlagHandler: this.defaultFlagHandler,
identityID: identityModel.djangoID || identityModel.compositeKey
});
if (!!this.cache) {
// @ts-ignore node-cache types are incorrect, ttl should be optional
await this.cache.set(`flags-${identifier}`, flags);
}
return flags;
}
private async getEnvironmentFlagsFromApi() {
if (!this.environmentFlagsUrl) {
throw new Error('`apiUrl` argument is missing or invalid.');
}
try {
const apiFlags = await this.getJSONResponse(this.environmentFlagsUrl, 'GET');
const flags = Flags.fromAPIFlags({
apiFlags: apiFlags,
analyticsProcessor: this.analyticsProcessor,
defaultFlagHandler: this.defaultFlagHandler
});
if (!!this.cache) {
// @ts-ignore node-cache types are incorrect, ttl should be optional
await this.cache.set('flags', flags);
}
return flags;
} catch (e) {
if (this.offlineHandler) {
return this.getEnvironmentFlagsFromDocument();
}
if (this.defaultFlagHandler) {
return new Flags({
flags: {},
defaultFlagHandler: this.defaultFlagHandler
});
}
throw e;
}
}
private async getIdentityFlagsFromApi(identifier: string, traits: { [key: string]: any }) {
if (!this.identitiesUrl) {
throw new Error('`apiUrl` argument is missing or invalid.');
}
try {
const data = generateIdentitiesData(identifier, traits);
const jsonResponse = await this.getJSONResponse(this.identitiesUrl, 'POST', data);
const flags = Flags.fromAPIFlags({
apiFlags: jsonResponse['flags'],
analyticsProcessor: this.analyticsProcessor,
defaultFlagHandler: this.defaultFlagHandler
});
if (!!this.cache) {
// @ts-ignore node-cache types are incorrect, ttl should be optional
await this.cache.set(`flags-${identifier}`, flags);
}
return flags;
} catch (e) {
if (this.offlineHandler) {
return this.getIdentityFlagsFromDocument(identifier, traits);
}
if (this.defaultFlagHandler) {
return new Flags({
flags: {},
defaultFlagHandler: this.defaultFlagHandler
});
}
throw e;
}
}
private buildIdentityModel(identifier: string, traits: { key: string; value: any }[]) {
const traitModels = traits.map(trait => new TraitModel(trait.key, trait.value));
return new IdentityModel('0', traitModels, [], this.environment.apiKey, identifier);
}
}
export default Flagsmith;