-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathindex.ts
More file actions
1802 lines (1609 loc) · 63 KB
/
index.ts
File metadata and controls
1802 lines (1609 loc) · 63 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
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2020-2025, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { LoggerFacade } from '../logging/logger';
import { sprintf, objectValues } from '../utils/fns';
import { createNotificationCenter, DefaultNotificationCenter } from '../notification_center';
import { EventProcessor } from '../event_processor/event_processor';
import { OdpManager } from '../odp/odp_manager';
import { VuidManager } from '../vuid/vuid_manager';
import { OdpEvent } from '../odp/event_manager/odp_event';
import { OptimizelySegmentOption } from '../odp/segment_manager/optimizely_segment_option';
import { BaseService, ServiceState } from '../service';
import {
UserAttributes,
EventTags,
OptimizelyConfig,
UserProfileService,
Variation,
FeatureFlag,
FeatureVariable,
OptimizelyDecideOption,
FeatureVariableValue,
OptimizelyDecision,
Client,
UserProfileServiceAsync,
isHoldout,
} from '../shared_types';
import { newErrorDecision } from '../optimizely_decision';
import OptimizelyUserContext from '../optimizely_user_context';
import { ProjectConfigManager } from '../project_config/project_config_manager';
import { createDecisionService, DecisionService, DecisionObj } from '../core/decision_service';
import { buildLogEvent } from '../event_processor/event_builder/log_event';
import { buildImpressionEvent, buildConversionEvent } from '../event_processor/event_builder/user_event';
import { isSafeInteger } from '../utils/fns';
import { validate } from '../utils/attributes_validator';
import * as eventTagsValidator from '../utils/event_tags_validator';
import * as projectConfig from '../project_config/project_config';
import * as userProfileServiceValidator from '../utils/user_profile_service_validator';
import * as stringValidator from '../utils/string_value_validator';
import * as decision from '../core/decision';
import {
DECISION_SOURCES,
DECISION_MESSAGES,
FEATURE_VARIABLE_TYPES,
NODE_CLIENT_ENGINE,
CLIENT_VERSION,
} from '../utils/enums';
import { Fn, Maybe, OpType } from '../utils/type';
import { resolvablePromise } from '../utils/promise/resolvablePromise';
import { NOTIFICATION_TYPES, DecisionNotificationType, DECISION_NOTIFICATION_TYPES, ActivateListenerPayload } from '../notification_center/type';
import {
FEATURE_NOT_IN_DATAFILE,
INVALID_INPUT_FORMAT,
NO_EVENT_PROCESSOR,
ODP_EVENT_FAILED,
ODP_MANAGER_MISSING,
UNABLE_TO_GET_VUID_VUID_MANAGER_NOT_AVAILABLE,
UNRECOGNIZED_DECIDE_OPTION,
NO_PROJECT_CONFIG_FAILURE,
EVENT_KEY_NOT_FOUND,
NOT_TRACKING_USER,
VARIABLE_REQUESTED_WITH_WRONG_TYPE,
} from 'error_message';
import {
FEATURE_ENABLED_FOR_USER,
FEATURE_NOT_ENABLED_FOR_USER,
FEATURE_NOT_ENABLED_RETURN_DEFAULT_VARIABLE_VALUE,
INVALID_CLIENT_ENGINE,
INVALID_DECIDE_OPTIONS,
INVALID_DEFAULT_DECIDE_OPTIONS,
INVALID_EXPERIMENT_KEY_INFO,
NOT_ACTIVATING_USER,
SHOULD_NOT_DISPATCH_ACTIVATE,
TRACK_EVENT,
UPDATED_OPTIMIZELY_CONFIG,
USER_RECEIVED_DEFAULT_VARIABLE_VALUE,
USER_RECEIVED_VARIABLE_VALUE,
VALID_USER_PROFILE_SERVICE,
VARIABLE_NOT_USED_RETURN_DEFAULT_VARIABLE_VALUE,
} from 'log_message';
import { SERVICE_STOPPED_BEFORE_RUNNING } from '../service';
import { ErrorNotifier } from '../error/error_notifier';
import { ErrorReporter } from '../error/error_reporter';
import { OptimizelyError } from '../error/optimizly_error';
import { Value } from '../utils/promise/operation_value';
import { CmabService } from '../core/decision_service/cmab/cmab_service';
const DEFAULT_ONREADY_TIMEOUT = 30000;
// TODO: Make feature_key, user_id, variable_key, experiment_key, event_key camelCase
type InputKey = 'feature_key' | 'user_id' | 'variable_key' | 'experiment_key' | 'event_key' | 'variation_id';
type StringInputs = Partial<Record<InputKey, unknown>>;
type DecisionReasons = (string | number)[];
export const INSTANCE_CLOSED = 'Instance closed';
export const ONREADY_TIMEOUT = 'onReady timeout expired after %s ms';
export const INVALID_IDENTIFIER = 'Invalid identifier';
export const INVALID_ATTRIBUTES = 'Invalid attributes';
/**
* options required to create optimizely object
*/
export type OptimizelyOptions = {
projectConfigManager: ProjectConfigManager;
UNSTABLE_conditionEvaluators?: unknown;
cmabService: CmabService;
clientEngine: string;
clientVersion?: string;
errorNotifier?: ErrorNotifier;
eventProcessor?: EventProcessor;
jsonSchemaValidator?: {
validate(jsonObject: unknown): boolean;
};
logger?: LoggerFacade;
userProfileService?: UserProfileService | null;
userProfileServiceAsync?: UserProfileServiceAsync | null;
defaultDecideOptions?: OptimizelyDecideOption[];
odpManager?: OdpManager;
vuidManager?: VuidManager
disposable?: boolean;
}
export default class Optimizely extends BaseService implements Client {
private cleanupTasks: Map<number, Fn> = new Map();
private nextCleanupTaskId = 0;
private clientEngine: string;
private clientVersion: string;
private errorNotifier?: ErrorNotifier;
private errorReporter: ErrorReporter;
private projectConfigManager: ProjectConfigManager;
private decisionService: DecisionService;
private eventProcessor?: EventProcessor;
private defaultDecideOptions: { [key: string]: boolean };
private odpManager?: OdpManager;
public notificationCenter: DefaultNotificationCenter;
private vuidManager?: VuidManager;
constructor(config: OptimizelyOptions) {
super();
let clientEngine = config.clientEngine;
if (!clientEngine) {
config.logger?.info(INVALID_CLIENT_ENGINE, clientEngine);
clientEngine = NODE_CLIENT_ENGINE;
}
this.clientEngine = clientEngine;
this.clientVersion = config.clientVersion || CLIENT_VERSION;
this.errorNotifier = config.errorNotifier;
this.logger = config.logger;
this.projectConfigManager = config.projectConfigManager;
this.errorReporter = new ErrorReporter(this.logger, this.errorNotifier);
this.odpManager = config.odpManager;
this.vuidManager = config.vuidManager;
this.eventProcessor = config.eventProcessor;
if(config.disposable) {
this.projectConfigManager.makeDisposable();
this.eventProcessor?.makeDisposable();
this.odpManager?.makeDisposable();
}
// pass a child logger to sub-components
if (this.logger) {
this.projectConfigManager.setLogger(this.logger.child());
this.eventProcessor?.setLogger(this.logger.child());
this.odpManager?.setLogger(this.logger.child());
}
let decideOptionsArray = config.defaultDecideOptions ?? [];
if (!Array.isArray(decideOptionsArray)) {
this.logger?.debug(INVALID_DEFAULT_DECIDE_OPTIONS);
decideOptionsArray = [];
}
const defaultDecideOptions: { [key: string]: boolean } = {};
decideOptionsArray.forEach(option => {
// Filter out all provided default decide options that are not in OptimizelyDecideOption[]
if (OptimizelyDecideOption[option]) {
defaultDecideOptions[option] = true;
} else {
this.logger?.warn(UNRECOGNIZED_DECIDE_OPTION, option);
}
});
this.defaultDecideOptions = defaultDecideOptions;
this.projectConfigManager = config.projectConfigManager;
this.projectConfigManager.onUpdate((configObj: projectConfig.ProjectConfig) => {
this.logger?.info(
UPDATED_OPTIMIZELY_CONFIG,
configObj.revision,
configObj.projectId
);
this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.OPTIMIZELY_CONFIG_UPDATE, undefined);
this.updateOdpSettings();
});
this.eventProcessor = config.eventProcessor;
this.eventProcessor?.onDispatch((event) => {
this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.LOG_EVENT, event);
});
this.odpManager = config.odpManager;
let userProfileService: Maybe<UserProfileService> = undefined;
if (config.userProfileService) {
try {
if (userProfileServiceValidator.validate(config.userProfileService)) {
userProfileService = config.userProfileService;
this.logger?.info(VALID_USER_PROFILE_SERVICE);
}
} catch (ex) {
this.logger?.warn(ex);
}
}
this.decisionService = createDecisionService({
userProfileService: userProfileService,
userProfileServiceAsync: config.userProfileServiceAsync || undefined,
cmabService: config.cmabService,
logger: this.logger,
UNSTABLE_conditionEvaluators: config.UNSTABLE_conditionEvaluators,
});
this.notificationCenter = createNotificationCenter({ logger: this.logger, errorNotifier: this.errorNotifier });
this.start();
}
start(): void {
if (!this.isNew()) {
return;
}
super.start();
this.state = ServiceState.Starting;
this.projectConfigManager.start();
this.eventProcessor?.start();
this.odpManager?.start();
Promise.all([
this.projectConfigManager.onRunning(),
this.eventProcessor ? this.eventProcessor.onRunning() : Promise.resolve(),
this.odpManager ? this.odpManager.onRunning() : Promise.resolve(),
this.vuidManager ? this.vuidManager.initialize() : Promise.resolve(),
]).then(() => {
this.state = ServiceState.Running;
this.startPromise.resolve();
const vuid = this.vuidManager?.getVuid();
if (vuid) {
this.odpManager?.setVuid(vuid);
}
}).catch((err) => {
this.state = ServiceState.Failed;
this.errorReporter.report(err);
this.startPromise.reject(err);
});
}
/**
* Returns the project configuration retrieved from projectConfigManager
* @return {projectConfig.ProjectConfig}
*/
getProjectConfig(): projectConfig.ProjectConfig | null {
return this.projectConfigManager.getConfig() || null;
}
/**
* Buckets visitor and sends impression event to Optimizely.
* @param {string} experimentKey
* @param {string} userId
* @param {UserAttributes} attributes
* @return {string|null} variation key
*/
activate(experimentKey: string, userId: string, attributes?: UserAttributes): string | null {
try {
const configObj = this.getProjectConfig();
if (!configObj) {
this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'activate');
return null;
}
if (!this.validateInputs({ experiment_key: experimentKey, user_id: userId }, attributes)) {
return this.notActivatingExperiment(experimentKey, userId);
}
try {
const variationKey = this.getVariation(experimentKey, userId, attributes);
if (variationKey === null) {
return this.notActivatingExperiment(experimentKey, userId);
}
// If experiment is not set to 'Running' status, log accordingly and return variation key
if (!projectConfig.isRunning(configObj, experimentKey)) {
this.logger?.debug(SHOULD_NOT_DISPATCH_ACTIVATE, experimentKey);
return variationKey;
}
const experiment = projectConfig.getExperimentFromKey(configObj, experimentKey);
const variation = experiment.variationKeyMap[variationKey];
const decisionObj = {
experiment: experiment,
variation: variation,
decisionSource: DECISION_SOURCES.EXPERIMENT,
};
this.sendImpressionEvent(decisionObj, '', userId, true, attributes);
return variationKey;
} catch (ex) {
this.logger?.info(NOT_ACTIVATING_USER, userId, experimentKey);
this.errorReporter.report(ex);
return null;
}
} catch (e) {
this.errorReporter.report(e);
return null;
}
}
/**
* Create an impression event and call the event dispatcher's dispatch method to
* send this event to Optimizely. Then use the notification center to trigger
* any notification listeners for the ACTIVATE notification type.
* @param {DecisionObj} decisionObj Decision Object
* @param {string} flagKey Key for a feature flag
* @param {string} userId ID of user to whom the variation was shown
* @param {UserAttributes} attributes Optional user attributes
* @param {boolean} enabled Boolean representing if feature is enabled
*/
private sendImpressionEvent(
decisionObj: DecisionObj,
flagKey: string,
userId: string,
enabled: boolean,
attributes?: UserAttributes
): void {
if (!this.eventProcessor) {
this.logger?.error(NO_EVENT_PROCESSOR);
return;
}
const configObj = this.getProjectConfig();
if (!configObj) {
return;
}
const impressionEvent = buildImpressionEvent({
decisionObj: decisionObj,
flagKey: flagKey,
enabled: enabled,
userId: userId,
userAttributes: attributes,
clientEngine: this.clientEngine,
clientVersion: this.clientVersion,
configObj: configObj,
});
this.eventProcessor.process(impressionEvent);
const logEvent = buildLogEvent([impressionEvent]);
const activateNotificationPayload: ActivateListenerPayload = {
experiment: null,
holdout: null,
userId: userId,
attributes: attributes,
variation: decisionObj.variation,
logEvent,
};
if (decisionObj.experiment) {
if (isHoldout(decisionObj.experiment)) {
activateNotificationPayload.holdout = decisionObj.experiment;
} else {
activateNotificationPayload.experiment = decisionObj.experiment;
}
}
this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.ACTIVATE, activateNotificationPayload);
}
/**
* Sends conversion event to Optimizely.
* @param {string} eventKey
* @param {string} userId
* @param {UserAttributes} attributes
* @param {EventTags} eventTags Values associated with the event.
*/
track(eventKey: string, userId: string, attributes?: UserAttributes, eventTags?: EventTags): void {
try {
if (!this.eventProcessor) {
this.logger?.error(NO_EVENT_PROCESSOR);
return;
}
const configObj = this.getProjectConfig();
if (!configObj) {
this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'track');
return;
}
if (!this.validateInputs({ user_id: userId, event_key: eventKey }, attributes, eventTags)) {
return;
}
if (!projectConfig.eventWithKeyExists(configObj, eventKey)) {
this.logger?.warn(EVENT_KEY_NOT_FOUND, eventKey);
this.logger?.warn(NOT_TRACKING_USER, userId);
return;
}
// remove null values from eventTags
eventTags = this.filterEmptyValues(eventTags);
const conversionEvent = buildConversionEvent({
eventKey: eventKey,
eventTags: eventTags,
userId: userId,
userAttributes: attributes,
clientEngine: this.clientEngine,
clientVersion: this.clientVersion,
configObj: configObj,
}, this.logger);
this.logger?.info(TRACK_EVENT, eventKey, userId);
// TODO is it okay to not pass a projectConfig as second argument
this.eventProcessor.process(conversionEvent);
const logEvent = buildLogEvent([conversionEvent]);
this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.TRACK, {
eventKey,
userId,
attributes,
eventTags,
logEvent,
});
} catch (e) {
this.errorReporter.report(e);
this.logger?.error(NOT_TRACKING_USER, userId);
}
}
/**
* Gets variation where visitor will be bucketed.
* @param {string} experimentKey
* @param {string} userId
* @param {UserAttributes} attributes
* @return {string|null} variation key
*/
getVariation(experimentKey: string, userId: string, attributes?: UserAttributes): string | null {
try {
const configObj = this.getProjectConfig();
if (!configObj) {
this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'getVariation');
return null;
}
try {
if (!this.validateInputs({ experiment_key: experimentKey, user_id: userId }, attributes)) {
return null;
}
const experiment = configObj.experimentKeyMap[experimentKey];
if (!experiment || experiment.isRollout) {
this.logger?.debug(INVALID_EXPERIMENT_KEY_INFO, experimentKey);
return null;
}
const variationKey = this.decisionService.getVariation(
configObj,
experiment,
this.createInternalUserContext(userId, attributes) as OptimizelyUserContext
).result;
const decisionNotificationType: DecisionNotificationType = projectConfig.isFeatureExperiment(configObj, experiment.id)
? DECISION_NOTIFICATION_TYPES.FEATURE_TEST
: DECISION_NOTIFICATION_TYPES.AB_TEST;
this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.DECISION, {
type: decisionNotificationType,
userId: userId,
attributes: attributes || {},
decisionInfo: {
experimentKey: experimentKey,
variationKey: variationKey,
},
});
return variationKey;
} catch (ex) {
this.errorReporter.report(ex);
return null;
}
} catch (e) {
this.errorReporter.report(e);
return null;
}
}
/**
* Force a user into a variation for a given experiment.
* @param {string} experimentKey
* @param {string} userId
* @param {string|null} variationKey user will be forced into. If null,
* then clear the existing experiment-to-variation mapping.
* @return {boolean} A boolean value that indicates if the set completed successfully.
*/
setForcedVariation(experimentKey: string, userId: string, variationKey: string | null): boolean {
if (!this.validateInputs({ experiment_key: experimentKey, user_id: userId })) {
return false;
}
const configObj = this.getProjectConfig();
if (!configObj) {
return false;
}
try {
return this.decisionService.setForcedVariation(configObj, experimentKey, userId, variationKey);
} catch (ex) {
this.errorReporter.report(ex);
return false;
}
}
/**
* Gets the forced variation for a given user and experiment.
* @param {string} experimentKey
* @param {string} userId
* @return {string|null} The forced variation key.
*/
getForcedVariation(experimentKey: string, userId: string): string | null {
if (!this.validateInputs({ experiment_key: experimentKey, user_id: userId })) {
return null;
}
const configObj = this.getProjectConfig();
if (!configObj) {
return null;
}
try {
return this.decisionService.getForcedVariation(configObj, experimentKey, userId).result;
} catch (ex) {
this.errorReporter.report(ex);
return null;
}
}
/**
* Validate string inputs, user attributes and event tags.
* @param {StringInputs} stringInputs Map of string keys and associated values
* @param {unknown} userAttributes Optional parameter for user's attributes
* @param {unknown} eventTags Optional parameter for event tags
* @return {boolean} True if inputs are valid
*
*/
protected validateInputs(stringInputs: StringInputs, userAttributes?: unknown, eventTags?: unknown): boolean {
try {
if (stringInputs.hasOwnProperty('user_id')) {
const userId = stringInputs['user_id'];
if (typeof userId !== 'string' || userId === null || userId === 'undefined') {
throw new OptimizelyError(INVALID_INPUT_FORMAT, 'user_id');
}
delete stringInputs['user_id'];
}
Object.keys(stringInputs).forEach(key => {
if (!stringValidator.validate(stringInputs[key as InputKey])) {
throw new OptimizelyError(INVALID_INPUT_FORMAT, key);
}
});
if (userAttributes) {
validate(userAttributes);
}
if (eventTags) {
eventTagsValidator.validate(eventTags);
}
return true;
} catch (ex) {
this.errorReporter.report(ex);
return false;
}
}
/**
* Shows failed activation log message and returns null when user is not activated in experiment
* @param {string} experimentKey
* @param {string} userId
* @return {null}
*/
private notActivatingExperiment(experimentKey: string, userId: string): null {
this.logger?.info(NOT_ACTIVATING_USER, userId, experimentKey);
return null;
}
/**
* Filters out attributes/eventTags with null or undefined values
* @param {EventTags | undefined} map
* @returns {EventTags | undefined}
*/
private filterEmptyValues(map: EventTags | undefined): EventTags | undefined {
for (const key in map) {
const typedKey = key as keyof EventTags;
if (map.hasOwnProperty(typedKey) && (map[typedKey] === null || map[typedKey] === undefined)) {
delete map[typedKey];
}
}
return map;
}
/**
* Returns true if the feature is enabled for the given user.
* @param {string} featureKey Key of feature which will be checked
* @param {string} userId ID of user which will be checked
* @param {UserAttributes} attributes Optional user attributes
* @return {boolean} true if the feature is enabled for the user, false otherwise
*/
isFeatureEnabled(featureKey: string, userId: string, attributes?: UserAttributes): boolean {
try {
const configObj = this.getProjectConfig();
if (!configObj) {
this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'isFeatureEnabled');
return false;
}
if (!this.validateInputs({ feature_key: featureKey, user_id: userId }, attributes)) {
return false;
}
const feature = projectConfig.getFeatureFromKey(configObj, featureKey, this.logger);
if (!feature) {
return false;
}
let sourceInfo = {};
const user = this.createInternalUserContext(userId, attributes) as OptimizelyUserContext;
const decisionObj = this.decisionService.getVariationForFeature(configObj, feature, user).result;
const decisionSource = decisionObj.decisionSource;
const experimentKey = decision.getExperimentKey(decisionObj);
const variationKey = decision.getVariationKey(decisionObj);
let featureEnabled = decision.getFeatureEnabledFromVariation(decisionObj);
if (decisionSource === DECISION_SOURCES.FEATURE_TEST || decisionSource === DECISION_SOURCES.HOLDOUT) {
sourceInfo = {
experimentKey: experimentKey,
variationKey: variationKey,
};
}
if (
decisionSource === DECISION_SOURCES.FEATURE_TEST ||
decisionSource === DECISION_SOURCES.HOLDOUT ||
(decisionSource === DECISION_SOURCES.ROLLOUT && projectConfig.getSendFlagDecisionsValue(configObj))
) {
this.sendImpressionEvent(decisionObj, feature.key, userId, featureEnabled, attributes);
}
if (featureEnabled === true) {
this.logger?.info(FEATURE_ENABLED_FOR_USER, featureKey, userId);
} else {
this.logger?.info(FEATURE_NOT_ENABLED_FOR_USER, featureKey, userId);
featureEnabled = false;
}
const featureInfo = {
featureKey: featureKey,
featureEnabled: featureEnabled,
source: decisionObj.decisionSource,
sourceInfo: sourceInfo,
};
this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.DECISION, {
type: DECISION_NOTIFICATION_TYPES.FEATURE,
userId: userId,
attributes: attributes || {},
decisionInfo: featureInfo,
});
return featureEnabled;
} catch (e) {
this.errorReporter.report(e);
return false;
}
}
/**
* Returns an Array containing the keys of all features in the project that are
* enabled for the given user.
* @param {string} userId
* @param {UserAttributes} attributes
* @return {string[]} Array of feature keys (strings)
*/
getEnabledFeatures(userId: string, attributes?: UserAttributes): string[] {
try {
const enabledFeatures: string[] = [];
const configObj = this.getProjectConfig();
if (!configObj) {
this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'getEnabledFeatures');
return enabledFeatures;
}
if (!this.validateInputs({ user_id: userId })) {
return enabledFeatures;
}
objectValues(configObj.featureKeyMap).forEach((feature: FeatureFlag) => {
if (this.isFeatureEnabled(feature.key, userId, attributes)) {
enabledFeatures.push(feature.key);
}
});
return enabledFeatures;
} catch (e) {
this.errorReporter.report(e);
return [];
}
}
/**
* Returns dynamically-typed value of the variable attached to the given
* feature flag. Returns null if the feature key or variable key is invalid.
*
* @param {string} featureKey Key of the feature whose variable's
* value is being accessed
* @param {string} variableKey Key of the variable whose value is
* being accessed
* @param {string} userId ID for the user
* @param {UserAttributes} attributes Optional user attributes
* @return {unknown} Value of the variable cast to the appropriate
* type, or null if the feature key is invalid or
* the variable key is invalid
*/
getFeatureVariable(
featureKey: string,
variableKey: string,
userId: string,
attributes?: UserAttributes
): FeatureVariableValue {
try {
if (!this.getProjectConfig()) {
this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'getFeatureVariable');
return null;
}
return this.getFeatureVariableForType(featureKey, variableKey, null, userId, attributes);
} catch (e) {
this.errorReporter.report(e);
return null;
}
}
/**
* Helper method to get the value for a variable of a certain type attached to a
* feature flag. Returns null if the feature key is invalid, the variable key is
* invalid, the given variable type does not match the variable's actual type,
* or the variable value cannot be cast to the required type. If the given variable
* type is null, the value of the variable cast to the appropriate type is returned.
*
* @param {string} featureKey Key of the feature whose variable's value is
* being accessed
* @param {string} variableKey Key of the variable whose value is being
* accessed
* @param {string|null} variableType Type of the variable whose value is being
* accessed (must be one of FEATURE_VARIABLE_TYPES
* in lib/utils/enums/index.js), or null to return the
* value of the variable cast to the appropriate type
* @param {string} userId ID for the user
* @param {UserAttributes} attributes Optional user attributes
* @return {unknown} Value of the variable cast to the appropriate
* type, or null if the feature key is invalid, thevariable
* key is invalid, or there is a mismatch with the type of
* the variable
*/
private getFeatureVariableForType(
featureKey: string,
variableKey: string,
variableType: string | null,
userId: string,
attributes?: UserAttributes
): FeatureVariableValue {
if (!this.validateInputs({ feature_key: featureKey, variable_key: variableKey, user_id: userId }, attributes)) {
return null;
}
const configObj = this.getProjectConfig();
if (!configObj) {
return null;
}
const featureFlag = projectConfig.getFeatureFromKey(configObj, featureKey, this.logger);
if (!featureFlag) {
return null;
}
const variable = projectConfig.getVariableForFeature(configObj, featureKey, variableKey, this.logger);
if (!variable) {
return null;
}
if (variableType && variable.type !== variableType) {
this.logger?.warn(
VARIABLE_REQUESTED_WITH_WRONG_TYPE,
variableType,
variable.type
);
return null;
}
const user = this.createInternalUserContext(userId, attributes) as OptimizelyUserContext;
const decisionObj = this.decisionService.getVariationForFeature(configObj, featureFlag, user).result;
const featureEnabled = decision.getFeatureEnabledFromVariation(decisionObj);
const variableValue = this.getFeatureVariableValueFromVariation(
featureKey,
featureEnabled,
decisionObj.variation,
variable,
userId
);
let sourceInfo = {};
if (
decisionObj.decisionSource === DECISION_SOURCES.FEATURE_TEST &&
decisionObj.experiment !== null &&
decisionObj.variation !== null
) {
sourceInfo = {
experimentKey: decisionObj.experiment.key,
variationKey: decisionObj.variation.key,
};
}
this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.DECISION, {
type: DECISION_NOTIFICATION_TYPES.FEATURE_VARIABLE,
userId: userId,
attributes: attributes || {},
decisionInfo: {
featureKey: featureKey,
featureEnabled: featureEnabled,
source: decisionObj.decisionSource,
variableKey: variableKey,
variableValue: variableValue,
variableType: variable.type,
sourceInfo: sourceInfo,
},
});
return variableValue;
}
/**
* Helper method to get the non type-casted value for a variable attached to a
* feature flag. Returns appropriate variable value depending on whether there
* was a matching variation, feature was enabled or not or varible was part of the
* available variation or not. Also logs the appropriate message explaining how it
* evaluated the value of the variable.
*
* @param {string} featureKey Key of the feature whose variable's value is
* being accessed
* @param {boolean} featureEnabled Boolean indicating if feature is enabled or not
* @param {Variation} variation variation returned by decision service
* @param {FeatureVariable} variable varible whose value is being evaluated
* @param {string} userId ID for the user
* @return {unknown} Value of the variable or null if the
* config Obj is null
*/
private getFeatureVariableValueFromVariation(
featureKey: string,
featureEnabled: boolean,
variation: Variation | null,
variable: FeatureVariable,
userId: string
): FeatureVariableValue {
const configObj = this.getProjectConfig();
if (!configObj) {
return null;
}
let variableValue = variable.defaultValue;
if (variation !== null) {
const value = projectConfig.getVariableValueForVariation(configObj, variable, variation, this.logger);
if (value !== null) {
if (featureEnabled) {
variableValue = value;
this.logger?.info(
USER_RECEIVED_VARIABLE_VALUE,
variableValue,
variable.key,
featureKey
);
} else {
this.logger?.info(
FEATURE_NOT_ENABLED_RETURN_DEFAULT_VARIABLE_VALUE,
featureKey,
userId,
variableValue
);
}
} else {
this.logger?.info(
VARIABLE_NOT_USED_RETURN_DEFAULT_VARIABLE_VALUE,
variable.key,
variation.key
);
}
} else {
this.logger?.info(
USER_RECEIVED_DEFAULT_VARIABLE_VALUE,
userId,
variable.key,
featureKey
);
}
return projectConfig.getTypeCastValue(variableValue, variable.type, this.logger);
}
/**
* Returns value for the given boolean variable attached to the given feature
* flag.
* @param {string} featureKey Key of the feature whose variable's value is
* being accessed
* @param {string} variableKey Key of the variable whose value is being
* accessed
* @param {string} userId ID for the user
* @param {UserAttributes} attributes Optional user attributes
* @return {boolean|null} Boolean value of the variable, or null if the
* feature key is invalid, the variable key is invalid,
* or there is a mismatch with the type of the variable.
*/
getFeatureVariableBoolean(
featureKey: string,
variableKey: string,
userId: string,
attributes?: UserAttributes
): boolean | null {
try {
if (!this.getProjectConfig()) {
this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'getFeatureVariableBoolean');
return null;
}
return this.getFeatureVariableForType(
featureKey,
variableKey,
FEATURE_VARIABLE_TYPES.BOOLEAN,
userId,
attributes
) as boolean | null;
} catch (e) {
this.errorReporter.report(e);
return null;
}
}
/**
* Returns value for the given double variable attached to the given feature
* flag.
* @param {string} featureKey Key of the feature whose variable's value is
* being accessed
* @param {string} variableKey Key of the variable whose value is being
* accessed
* @param {string} userId ID for the user
* @param {UserAttributes} attributes Optional user attributes
* @return {number|null} Number value of the variable, or null if the
* feature key is invalid, the variable key is
* invalid, or there is a mismatch with the type
* of the variable
*/
getFeatureVariableDouble(
featureKey: string,
variableKey: string,
userId: string,
attributes?: UserAttributes
): number | null {
try {
if (!this.getProjectConfig()) {
this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'getFeatureVariableDouble');
return null;