-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathindex.ts
1545 lines (1417 loc) · 51.1 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
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 2017-2022, 2024-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
*
* http://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 { bucket } from '../bucketer';
import {
AUDIENCE_EVALUATION_TYPES,
CONTROL_ATTRIBUTES,
DECISION_SOURCES,
DecisionSource,
} from '../../utils/enums';
import {
getAudiencesById,
getExperimentAudienceConditions,
getExperimentFromId,
getExperimentFromKey,
getFlagVariationByKey,
getTrafficAllocation,
getVariationIdFromExperimentAndVariationKey,
getVariationFromId,
getVariationKeyFromId,
isActive,
ProjectConfig,
} from '../../project_config/project_config';
import { AudienceEvaluator, createAudienceEvaluator } from '../audience_evaluator';
import * as stringValidator from '../../utils/string_value_validator';
import {
BucketerParams,
DecisionResponse,
Experiment,
ExperimentBucketMap,
FeatureFlag,
OptimizelyDecideOption,
OptimizelyUserContext,
UserAttributes,
UserProfile,
UserProfileService,
UserProfileServiceAsync,
Variation,
} from '../../shared_types';
import {
INVALID_USER_ID,
INVALID_VARIATION_KEY,
NO_VARIATION_FOR_EXPERIMENT_KEY,
USER_NOT_IN_FORCED_VARIATION,
USER_PROFILE_LOOKUP_ERROR,
USER_PROFILE_SAVE_ERROR,
BUCKETING_ID_NOT_STRING,
} from 'error_message';
import {
SAVED_USER_VARIATION,
SAVED_VARIATION_NOT_FOUND,
USER_HAS_NO_FORCED_VARIATION,
USER_MAPPED_TO_FORCED_VARIATION,
USER_HAS_NO_FORCED_VARIATION_FOR_EXPERIMENT,
VALID_BUCKETING_ID,
VARIATION_REMOVED_FOR_USER,
} from 'log_message';
import { OptimizelyError } from '../../error/optimizly_error';
import { CmabService } from './cmab/cmab_service';
import { Maybe, OpType, OpValue } from '../../utils/type';
import { Value } from '../../utils/promise/operation_value';
export const EXPERIMENT_NOT_RUNNING = 'Experiment %s is not running.';
export const RETURNING_STORED_VARIATION =
'Returning previously activated variation "%s" of experiment "%s" for user "%s" from user profile.';
export const USER_NOT_IN_EXPERIMENT = 'User %s does not meet conditions to be in experiment %s.';
export const USER_HAS_NO_VARIATION = 'User %s is in no variation of experiment %s.';
export const USER_HAS_VARIATION = 'User %s is in variation %s of experiment %s.';
export const USER_FORCED_IN_VARIATION = 'User %s is forced in variation %s.';
export const FORCED_BUCKETING_FAILED = 'Variation key %s is not in datafile. Not activating user %s.';
export const EVALUATING_AUDIENCES_COMBINED = 'Evaluating audiences for %s "%s": %s.';
export const AUDIENCE_EVALUATION_RESULT_COMBINED = 'Audiences for %s %s collectively evaluated to %s.';
export const USER_IN_ROLLOUT = 'User %s is in rollout of feature %s.';
export const USER_NOT_IN_ROLLOUT = 'User %s is not in rollout of feature %s.';
export const FEATURE_HAS_NO_EXPERIMENTS = 'Feature %s is not attached to any experiments.';
export const USER_DOESNT_MEET_CONDITIONS_FOR_TARGETING_RULE =
'User %s does not meet conditions for targeting rule %s.';
export const USER_NOT_BUCKETED_INTO_TARGETING_RULE =
'User %s not bucketed into targeting rule %s due to traffic allocation. Trying everyone rule.';
export const USER_BUCKETED_INTO_TARGETING_RULE = 'User %s bucketed into targeting rule %s.';
export const NO_ROLLOUT_EXISTS = 'There is no rollout of feature %s.';
export const INVALID_ROLLOUT_ID = 'Invalid rollout ID %s attached to feature %s';
export const ROLLOUT_HAS_NO_EXPERIMENTS = 'Rollout of feature %s has no experiments';
export const IMPROPERLY_FORMATTED_EXPERIMENT = 'Experiment key %s is improperly formatted.';
export const USER_HAS_FORCED_VARIATION =
'Variation %s is mapped to experiment %s and user %s in the forced variation map.';
export const USER_MEETS_CONDITIONS_FOR_TARGETING_RULE = 'User %s meets conditions for targeting rule %s.';
export const USER_HAS_FORCED_DECISION_WITH_RULE_SPECIFIED =
'Variation (%s) is mapped to flag (%s), rule (%s) and user (%s) in the forced decision map.';
export const USER_HAS_FORCED_DECISION_WITH_NO_RULE_SPECIFIED =
'Variation (%s) is mapped to flag (%s) and user (%s) in the forced decision map.';
export const USER_HAS_FORCED_DECISION_WITH_RULE_SPECIFIED_BUT_INVALID =
'Invalid variation is mapped to flag (%s), rule (%s) and user (%s) in the forced decision map.';
export const USER_HAS_FORCED_DECISION_WITH_NO_RULE_SPECIFIED_BUT_INVALID =
'Invalid variation is mapped to flag (%s) and user (%s) in the forced decision map.';
export const CMAB_NOT_SUPPORTED_IN_SYNC = 'CMAB is not supported in sync mode.';
export const CMAB_FETCH_FAILED = 'Failed to fetch CMAB data for experiment %s.';
export const CMAB_FETCHED_VARIATION_INVALID = 'Fetched variation %s for cmab experiment %s is invalid.';
export interface DecisionObj {
experiment: Experiment | null;
variation: Variation | null;
decisionSource: DecisionSource;
cmabUuid?: string;
}
interface DecisionServiceOptions {
userProfileService?: UserProfileService;
userProfileServiceAsync?: UserProfileServiceAsync;
logger?: LoggerFacade;
UNSTABLE_conditionEvaluators: unknown;
cmabService: CmabService;
}
interface DeliveryRuleResponse<T, K> extends DecisionResponse<T> {
skipToEveryoneElse: K;
}
interface UserProfileTracker {
userProfile: ExperimentBucketMap | null;
isProfileUpdated: boolean;
}
type VarationKeyWithCmabParams = {
variationKey?: string;
cmabUuid?: string;
};
export type DecisionReason = [string, ...any[]];
export type VariationResult = DecisionResponse<VarationKeyWithCmabParams>;
export type DecisionResult = DecisionResponse<DecisionObj>;
type VariationIdWithCmabParams = {
variationId? : string;
cmabUuid?: string;
};
export type DecideOptionsMap = Partial<Record<OptimizelyDecideOption, boolean>>;
/**
* Optimizely's decision service that determines which variation of an experiment the user will be allocated to.
*
* The decision service contains all logic around how a user decision is made. This includes all of the following (in order):
* 1. Checking experiment status
* 2. Checking forced bucketing
* 3. Checking whitelisting
* 4. Checking user profile service for past bucketing decisions (sticky bucketing)
* 5. Checking audience targeting
* 6. Using Murmurhash3 to bucket the user.
*
* @constructor
* @param {DecisionServiceOptions} options
* @returns {DecisionService}
*/
export class DecisionService {
private logger?: LoggerFacade;
private audienceEvaluator: AudienceEvaluator;
private forcedVariationMap: { [key: string]: { [id: string]: string } };
private userProfileService?: UserProfileService;
private userProfileServiceAsync?: UserProfileServiceAsync;
private cmabService: CmabService;
constructor(options: DecisionServiceOptions) {
this.logger = options.logger;
this.audienceEvaluator = createAudienceEvaluator(options.UNSTABLE_conditionEvaluators, this.logger);
this.forcedVariationMap = {};
this.userProfileService = options.userProfileService;
this.userProfileServiceAsync = options.userProfileServiceAsync;
this.cmabService = options.cmabService;
}
private isCmab(experiment: Experiment): boolean {
return !!experiment.cmab;
}
/**
* Resolves the variation into which the visitor will be bucketed.
*
* @param {ProjectConfig} configObj - The parsed project configuration object.
* @param {Experiment} experiment - The experiment for which the variation is being resolved.
* @param {OptimizelyUserContext} user - The user context associated with this decision.
* @returns {DecisionResponse<string|null>} - A DecisionResponse containing the variation the user is bucketed into,
* along with the decision reasons.
*/
private resolveVariation<OP extends OpType>(
op: OP,
configObj: ProjectConfig,
experiment: Experiment,
user: OptimizelyUserContext,
decideOptions: DecideOptionsMap,
userProfileTracker?: UserProfileTracker,
): Value<OP, VariationResult> {
const userId = user.getUserId();
const experimentKey = experiment.key;
if (!isActive(configObj, experimentKey)) {
this.logger?.info(EXPERIMENT_NOT_RUNNING, experimentKey);
return Value.of(op, {
result: {},
reasons: [[EXPERIMENT_NOT_RUNNING, experimentKey]],
});
}
const decideReasons: DecisionReason[] = [];
const decisionForcedVariation = this.getForcedVariation(configObj, experimentKey, userId);
decideReasons.push(...decisionForcedVariation.reasons);
const forcedVariationKey = decisionForcedVariation.result;
if (forcedVariationKey) {
return Value.of(op, {
result: { variationKey: forcedVariationKey },
reasons: decideReasons,
});
}
const decisionWhitelistedVariation = this.getWhitelistedVariation(experiment, userId);
decideReasons.push(...decisionWhitelistedVariation.reasons);
let variation = decisionWhitelistedVariation.result;
if (variation) {
return Value.of(op, {
result: { variationKey: variation.key },
reasons: decideReasons,
});
}
// check for sticky bucketing
if (userProfileTracker) {
variation = this.getStoredVariation(configObj, experiment, userId, userProfileTracker.userProfile);
if (variation) {
this.logger?.info(
RETURNING_STORED_VARIATION,
variation.key,
experimentKey,
userId,
);
decideReasons.push([
RETURNING_STORED_VARIATION,
variation.key,
experimentKey,
userId,
]);
return Value.of(op, {
result: { variationKey: variation.key },
reasons: decideReasons,
});
}
}
const decisionifUserIsInAudience = this.checkIfUserIsInAudience(
configObj,
experiment,
AUDIENCE_EVALUATION_TYPES.EXPERIMENT,
user,
''
);
decideReasons.push(...decisionifUserIsInAudience.reasons);
if (!decisionifUserIsInAudience.result) {
this.logger?.info(
USER_NOT_IN_EXPERIMENT,
userId,
experimentKey,
);
decideReasons.push([
USER_NOT_IN_EXPERIMENT,
userId,
experimentKey,
]);
return Value.of(op, {
result: {},
reasons: decideReasons,
});
}
const decisionVariationValue = this.isCmab(experiment) ?
this.getDecisionForCmabExperiment(op, configObj, experiment, user, decideOptions) :
this.getDecisionFromBucketer(op, configObj, experiment, user);
return decisionVariationValue.then((variationResult): Value<OP, VariationResult> => {
decideReasons.push(...variationResult.reasons);
if (variationResult.error) {
return Value.of(op, {
error: true,
result: {},
reasons: decideReasons,
});
}
const variationId = variationResult.result.variationId;
variation = variationId ? configObj.variationIdMap[variationId] : null;
if (!variation) {
this.logger?.debug(
USER_HAS_NO_VARIATION,
userId,
experimentKey,
);
decideReasons.push([
USER_HAS_NO_VARIATION,
userId,
experimentKey,
]);
return Value.of(op, {
result: {},
reasons: decideReasons,
});
}
this.logger?.info(
USER_HAS_VARIATION,
userId,
variation.key,
experimentKey,
);
decideReasons.push([
USER_HAS_VARIATION,
userId,
variation.key,
experimentKey,
]);
// update experiment bucket map if decide options do not include shouldIgnoreUPS
if (userProfileTracker) {
this.updateUserProfile(experiment, variation, userProfileTracker);
}
return Value.of(op, {
result: { variationKey: variation.key, cmabUuid: variationResult.result.cmabUuid },
reasons: decideReasons,
});
});
}
private getDecisionForCmabExperiment<OP extends OpType>(
op: OP,
configObj: ProjectConfig,
experiment: Experiment,
user: OptimizelyUserContext,
decideOptions: DecideOptionsMap,
): Value<OP, DecisionResponse<VariationIdWithCmabParams>> {
if (op === 'sync') {
return Value.of(op, {
error: false, // this is not considered an error, the evaluation should continue to next rule
result: {},
reasons: [[CMAB_NOT_SUPPORTED_IN_SYNC]],
});
}
const cmabPromise = this.cmabService.getDecision(configObj, user, experiment.id, decideOptions).then(
(cmabDecision) => {
return {
error: false,
result: cmabDecision,
reasons: [] as DecisionReason[],
};
}
).catch((ex: any) => {
this.logger?.error(CMAB_FETCH_FAILED, experiment.key);
return {
error: true,
result: {},
reasons: [[CMAB_FETCH_FAILED, experiment.key]] as DecisionReason[],
};
});
return Value.of(op, cmabPromise);
}
private getDecisionFromBucketer<OP extends OpType>(
op: OP,
configObj: ProjectConfig,
experiment: Experiment,
user: OptimizelyUserContext
): Value<OP, DecisionResponse<VariationIdWithCmabParams>> {
const userId = user.getUserId();
const attributes = user.getAttributes();
// by default, the bucketing ID should be the user ID
const bucketingId = this.getBucketingId(userId, attributes);
const bucketerParams = this.buildBucketerParams(configObj, experiment, bucketingId, userId);
const decisionVariation = bucket(bucketerParams);
return Value.of(op, {
result: {
variationId: decisionVariation.result || undefined,
},
reasons: decisionVariation.reasons,
});
}
/**
* Gets variation where visitor will be bucketed.
* @param {ProjectConfig} configObj The parsed project configuration object
* @param {Experiment} experiment
* @param {OptimizelyUserContext} user A user context
* @param {[key: string]: boolean} options Optional map of decide options
* @return {DecisionResponse<string|null>} DecisionResponse containing the variation the user is bucketed into
* and the decide reasons.
*/
getVariation(
configObj: ProjectConfig,
experiment: Experiment,
user: OptimizelyUserContext,
options: DecideOptionsMap = {}
): DecisionResponse<string | null> {
const shouldIgnoreUPS = options[OptimizelyDecideOption.IGNORE_USER_PROFILE_SERVICE];
const userProfileTracker: Maybe<UserProfileTracker> = shouldIgnoreUPS ? undefined
: {
isProfileUpdated: false,
userProfile: this.resolveExperimentBucketMap('sync', user.getUserId(), user.getAttributes()).get(),
};
const result = this.resolveVariation('sync', configObj, experiment, user, options, userProfileTracker).get();
if(userProfileTracker) {
this.saveUserProfile('sync', user.getUserId(), userProfileTracker)
}
return {
result: result.result.variationKey || null,
reasons: result.reasons,
}
}
/**
* Merges attributes from attributes[STICKY_BUCKETING_KEY] and userProfileService
* @param {string} userId
* @param {UserAttributes} attributes
* @return {ExperimentBucketMap} finalized copy of experiment_bucket_map
*/
private resolveExperimentBucketMap<OP extends OpType>(
op: OP,
userId: string,
attributes: UserAttributes = {},
): Value<OP, ExperimentBucketMap> {
const fromAttributes = (attributes[CONTROL_ATTRIBUTES.STICKY_BUCKETING_KEY] || {}) as any as ExperimentBucketMap;
return this.getUserProfile(op, userId).then((userProfile) => {
const fromUserProfileService = userProfile?.experiment_bucket_map || {};
return Value.of(op, {
...fromUserProfileService,
...fromAttributes,
});
});
}
/**
* Checks if user is whitelisted into any variation and return that variation if so
* @param {Experiment} experiment
* @param {string} userId
* @return {DecisionResponse<Variation|null>} DecisionResponse containing the forced variation if it exists
* or user ID and the decide reasons.
*/
private getWhitelistedVariation(
experiment: Experiment,
userId: string
): DecisionResponse<Variation | null> {
const decideReasons: DecisionReason[] = [];
if (experiment.forcedVariations && experiment.forcedVariations.hasOwnProperty(userId)) {
const forcedVariationKey = experiment.forcedVariations[userId];
if (experiment.variationKeyMap.hasOwnProperty(forcedVariationKey)) {
this.logger?.info(
USER_FORCED_IN_VARIATION,
userId,
forcedVariationKey,
);
decideReasons.push([
USER_FORCED_IN_VARIATION,
userId,
forcedVariationKey,
]);
return {
result: experiment.variationKeyMap[forcedVariationKey],
reasons: decideReasons,
};
} else {
this.logger?.error(
FORCED_BUCKETING_FAILED,
forcedVariationKey,
userId,
);
decideReasons.push([
FORCED_BUCKETING_FAILED,
forcedVariationKey,
userId,
]);
return {
result: null,
reasons: decideReasons,
};
}
}
return {
result: null,
reasons: decideReasons,
};
}
/**
* Checks whether the user is included in experiment audience
* @param {ProjectConfig} configObj The parsed project configuration object
* @param {string} experimentKey Key of experiment being validated
* @param {string} evaluationAttribute String representing experiment key or rule
* @param {string} userId ID of user
* @param {UserAttributes} attributes Optional parameter for user's attributes
* @param {string} loggingKey String representing experiment key or rollout rule. To be used in log messages only.
* @return {DecisionResponse<boolean>} DecisionResponse DecisionResponse containing result true if user meets audience conditions and
* the decide reasons.
*/
private checkIfUserIsInAudience(
configObj: ProjectConfig,
experiment: Experiment,
evaluationAttribute: string,
user: OptimizelyUserContext,
loggingKey?: string | number,
): DecisionResponse<boolean> {
const decideReasons: DecisionReason[] = [];
const experimentAudienceConditions = getExperimentAudienceConditions(configObj, experiment.id);
const audiencesById = getAudiencesById(configObj);
this.logger?.debug(
EVALUATING_AUDIENCES_COMBINED,
evaluationAttribute,
loggingKey || experiment.key,
JSON.stringify(experimentAudienceConditions),
);
decideReasons.push([
EVALUATING_AUDIENCES_COMBINED,
evaluationAttribute,
loggingKey || experiment.key,
JSON.stringify(experimentAudienceConditions),
]);
const result = this.audienceEvaluator.evaluate(experimentAudienceConditions, audiencesById, user);
this.logger?.info(
AUDIENCE_EVALUATION_RESULT_COMBINED,
evaluationAttribute,
loggingKey || experiment.key,
result.toString().toUpperCase(),
);
decideReasons.push([
AUDIENCE_EVALUATION_RESULT_COMBINED,
evaluationAttribute,
loggingKey || experiment.key,
result.toString().toUpperCase(),
]);
return {
result: result,
reasons: decideReasons,
};
}
/**
* Given an experiment key and user ID, returns params used in bucketer call
* @param {ProjectConfig} configObj The parsed project configuration object
* @param {string} experimentKey Experiment key used for bucketer
* @param {string} bucketingId ID to bucket user into
* @param {string} userId ID of user to be bucketed
* @return {BucketerParams}
*/
private buildBucketerParams(
configObj: ProjectConfig,
experiment: Experiment,
bucketingId: string,
userId: string
): BucketerParams {
return {
bucketingId,
experimentId: experiment.id,
experimentKey: experiment.key,
experimentIdMap: configObj.experimentIdMap,
experimentKeyMap: configObj.experimentKeyMap,
groupIdMap: configObj.groupIdMap,
logger: this.logger,
trafficAllocationConfig: getTrafficAllocation(configObj, experiment.id),
userId,
variationIdMap: configObj.variationIdMap,
}
}
/**
* Pull the stored variation out of the experimentBucketMap for an experiment/userId
* @param {ProjectConfig} configObj The parsed project configuration object
* @param {Experiment} experiment
* @param {string} userId
* @param {ExperimentBucketMap} experimentBucketMap mapping experiment => { variation_id: <variationId> }
* @return {Variation|null} the stored variation or null if the user profile does not have one for the given experiment
*/
private getStoredVariation(
configObj: ProjectConfig,
experiment: Experiment,
userId: string,
experimentBucketMap: ExperimentBucketMap | null
): Variation | null {
if (experimentBucketMap?.hasOwnProperty(experiment.id)) {
const decision = experimentBucketMap[experiment.id];
const variationId = decision.variation_id;
if (configObj.variationIdMap.hasOwnProperty(variationId)) {
return configObj.variationIdMap[decision.variation_id];
} else {
this.logger?.info(
SAVED_VARIATION_NOT_FOUND,
userId,
variationId,
experiment.key,
);
}
}
return null;
}
/**
* Get the user profile with the given user ID
* @param {string} userId
* @return {UserProfile} the stored user profile or an empty profile if one isn't found or error
*/
private getUserProfile<OP extends OpType>(op: OP, userId: string): Value<OP, UserProfile> {
const emptyProfile = {
user_id: userId,
experiment_bucket_map: {},
};
if (this.userProfileService) {
try {
return Value.of(op, this.userProfileService.lookup(userId));
} catch (ex: any) {
this.logger?.error(
USER_PROFILE_LOOKUP_ERROR,
userId,
ex.message,
);
}
return Value.of(op, emptyProfile);
}
if (this.userProfileServiceAsync && op === 'async') {
return Value.of(op, this.userProfileServiceAsync.lookup(userId).catch((ex: any) => {
this.logger?.error(
USER_PROFILE_LOOKUP_ERROR,
userId,
ex.message,
);
return emptyProfile;
}));
}
return Value.of(op, emptyProfile);
}
private updateUserProfile(
experiment: Experiment,
variation: Variation,
userProfileTracker: UserProfileTracker
): void {
if(!userProfileTracker.userProfile) {
return
}
userProfileTracker.userProfile[experiment.id] = {
variation_id: variation.id
}
userProfileTracker.isProfileUpdated = true
}
/**
* Saves the bucketing decision to the user profile
* @param {Experiment} experiment
* @param {Variation} variation
* @param {string} userId
* @param {ExperimentBucketMap} experimentBucketMap
*/
private saveUserProfile<OP extends OpType>(
op: OP,
userId: string,
userProfileTracker: UserProfileTracker
): Value<OP, unknown> {
const { userProfile, isProfileUpdated } = userProfileTracker;
if (!userProfile || !isProfileUpdated) {
return Value.of(op, undefined);
}
if (op === 'sync' && !this.userProfileService) {
return Value.of(op, undefined);
}
if (this.userProfileService) {
try {
this.userProfileService.save({
user_id: userId,
experiment_bucket_map: userProfile,
});
this.logger?.info(
SAVED_USER_VARIATION,
userId,
);
} catch (ex: any) {
this.logger?.error(USER_PROFILE_SAVE_ERROR, userId, ex.message);
}
return Value.of(op, undefined);
}
if (this.userProfileServiceAsync) {
return Value.of(op, this.userProfileServiceAsync.save({
user_id: userId,
experiment_bucket_map: userProfile,
}).catch((ex: any) => {
this.logger?.error(USER_PROFILE_SAVE_ERROR, userId, ex.message);
}));
}
return Value.of(op, undefined);
}
/**
* Determines variations for the specified feature flags.
*
* @param {ProjectConfig} configObj - The parsed project configuration object.
* @param {FeatureFlag[]} featureFlags - The feature flags for which variations are to be determined.
* @param {OptimizelyUserContext} user - The user context associated with this decision.
* @param {Record<string, boolean>} options - An optional map of decision options.
* @returns {DecisionResponse<DecisionObj>[]} - An array of DecisionResponse containing objects with
* experiment, variation, decisionSource properties, and decision reasons.
*/
getVariationsForFeatureList(
configObj: ProjectConfig,
featureFlags: FeatureFlag[],
user: OptimizelyUserContext,
options: DecideOptionsMap = {}): DecisionResult[] {
return this.resolveVariationsForFeatureList('sync', configObj, featureFlags, user, options).get();
}
resolveVariationsForFeatureList<OP extends OpType>(
op: OP,
configObj: ProjectConfig,
featureFlags: FeatureFlag[],
user: OptimizelyUserContext,
options: DecideOptionsMap): Value<OP, DecisionResult[]> {
const userId = user.getUserId();
const attributes = user.getAttributes();
const decisions: DecisionResponse<DecisionObj>[] = [];
// const userProfileTracker : UserProfileTracker = {
// isProfileUpdated: false,
// userProfile: null,
// }
const shouldIgnoreUPS = !!options[OptimizelyDecideOption.IGNORE_USER_PROFILE_SERVICE];
const userProfileTrackerValue: Value<OP, Maybe<UserProfileTracker>> = shouldIgnoreUPS ? Value.of(op, undefined)
: this.resolveExperimentBucketMap(op, userId, attributes).then((userProfile) => {
return Value.of(op, {
isProfileUpdated: false,
userProfile: userProfile,
});
});
return userProfileTrackerValue.then((userProfileTracker) => {
const flagResults = featureFlags.map((feature) => this.resolveVariationForFlag(op, configObj, feature, user, options, userProfileTracker));
const opFlagResults = Value.all(op, flagResults);
return opFlagResults.then(() => {
if(userProfileTracker) {
this.saveUserProfile(op, userId, userProfileTracker);
}
return opFlagResults;
});
});
}
private resolveVariationForFlag<OP extends OpType>(
op: OP,
configObj: ProjectConfig,
feature: FeatureFlag,
user: OptimizelyUserContext,
decideOptions: DecideOptionsMap,
userProfileTracker?: UserProfileTracker
): Value<OP, DecisionResult> {
const decideReasons: DecisionReason[] = [];
const forcedDecisionResponse = this.findValidatedForcedDecision(configObj, user, feature.key);
decideReasons.push(...forcedDecisionResponse.reasons);
if (forcedDecisionResponse.result) {
return Value.of(op, {
result: {
variation: forcedDecisionResponse.result,
experiment: null,
decisionSource: DECISION_SOURCES.FEATURE_TEST,
},
reasons: decideReasons,
});
}
return this.getVariationForFeatureExperiment(op, configObj, feature, user, decideOptions, userProfileTracker).then((experimentDecision) => {
if (experimentDecision.error || experimentDecision.result.variation !== null) {
return Value.of(op, {
...experimentDecision,
reasons: [...decideReasons, ...experimentDecision.reasons],
});
}
decideReasons.push(...experimentDecision.reasons);
const rolloutDecision = this.getVariationForRollout(configObj, feature, user);
decideReasons.push(...rolloutDecision.reasons);
const rolloutDecisionResult = rolloutDecision.result;
const userId = user.getUserId();
if (rolloutDecisionResult.variation) {
this.logger?.debug(USER_IN_ROLLOUT, userId, feature.key);
decideReasons.push([USER_IN_ROLLOUT, userId, feature.key]);
} else {
this.logger?.debug(USER_NOT_IN_ROLLOUT, userId, feature.key);
decideReasons.push([USER_NOT_IN_ROLLOUT, userId, feature.key]);
}
return Value.of(op, {
result: rolloutDecisionResult,
reasons: decideReasons,
});
});
}
/**
* Given a feature, user ID, and attributes, returns a decision response containing
* an object representing a decision and decide reasons. If the user was bucketed into
* a variation for the given feature and attributes, the decision object will have variation and
* experiment properties (both objects), as well as a decisionSource property.
* decisionSource indicates whether the decision was due to a rollout or an
* experiment.
* @param {ProjectConfig} configObj The parsed project configuration object
* @param {FeatureFlag} feature A feature flag object from project configuration
* @param {OptimizelyUserContext} user A user context
* @param {[key: string]: boolean} options Map of decide options
* @return {DecisionResponse} DecisionResponse DecisionResponse containing an object with experiment, variation, and decisionSource
* properties and decide reasons. If the user was not bucketed into a variation, the variation
* property in decision object is null.
*/
getVariationForFeature(
configObj: ProjectConfig,
feature: FeatureFlag,
user: OptimizelyUserContext,
options: DecideOptionsMap = {}
): DecisionResponse<DecisionObj> {
return this.resolveVariationsForFeatureList('sync', configObj, [feature], user, options).get()[0]
}
private getVariationForFeatureExperiment<OP extends OpType>(
op: OP,
configObj: ProjectConfig,
feature: FeatureFlag,
user: OptimizelyUserContext,
decideOptions: DecideOptionsMap,
userProfileTracker?: UserProfileTracker,
): Value<OP, DecisionResult> {
// const decideReasons: DecisionReason[] = [];
// let variationKey = null;
// let decisionVariation;
// let index;
// let variationForFeatureExperiment;
if (feature.experimentIds.length === 0) {
this.logger?.debug(FEATURE_HAS_NO_EXPERIMENTS, feature.key);
return Value.of(op, {
result: {
experiment: null,
variation: null,
decisionSource: DECISION_SOURCES.FEATURE_TEST,
},
reasons: [
[FEATURE_HAS_NO_EXPERIMENTS, feature.key],
],
});
}
return this.traverseFeatureExperimentList(op, configObj, feature, 0, user, [], decideOptions, userProfileTracker);
}
private traverseFeatureExperimentList<OP extends OpType>(
op: OP,
configObj: ProjectConfig,
feature: FeatureFlag,
fromIndex: number,
user: OptimizelyUserContext,
decideReasons: DecisionReason[],
decideOptions: DecideOptionsMap,
userProfileTracker?: UserProfileTracker,
): Value<OP, DecisionResult> {
const experimentIds = feature.experimentIds;
if (fromIndex >= experimentIds.length) {
return Value.of(op, {
result: {
experiment: null,
variation: null,
decisionSource: DECISION_SOURCES.FEATURE_TEST,
},
reasons: decideReasons,
});
}
const experiment = getExperimentFromId(configObj, experimentIds[fromIndex], this.logger);
if (!experiment) {
return this.traverseFeatureExperimentList(
op, configObj, feature, fromIndex + 1, user, decideReasons, decideOptions, userProfileTracker);
}
const decisionVariationValue = this.getVariationFromExperimentRule(
op, configObj, feature.key, experiment, user, decideOptions, userProfileTracker,
);
return decisionVariationValue.then((decisionVariation) => {
decideReasons.push(...decisionVariation.reasons);
if (decisionVariation.error) {
return Value.of(op, {
error: true,
result: {
experiment,
variation: null,
decisionSource: DECISION_SOURCES.FEATURE_TEST,
},
reasons: decideReasons,
});
}
if(!decisionVariation.result.variationKey) {
return this.traverseFeatureExperimentList(
op, configObj, feature, fromIndex + 1, user, decideReasons, decideOptions, userProfileTracker);
}
const variationKey = decisionVariation.result.variationKey;
let variation: Variation | null = experiment.variationKeyMap[variationKey];
if (!variation) {
variation = getFlagVariationByKey(configObj, feature.key, variationKey);
}
return Value.of(op, {
result: {
cmabUuid: decisionVariation.result.cmabUuid,
experiment,
variation,
decisionSource: DECISION_SOURCES.FEATURE_TEST,
},
reasons: decideReasons,
});
});
}
private getVariationForRollout(
configObj: ProjectConfig,
feature: FeatureFlag,
user: OptimizelyUserContext,
): DecisionResponse<DecisionObj> {
const decideReasons: DecisionReason[] = [];
let decisionObj: DecisionObj;
if (!feature.rolloutId) {
this.logger?.debug(NO_ROLLOUT_EXISTS, feature.key);
decideReasons.push([NO_ROLLOUT_EXISTS, feature.key]);
decisionObj = {
experiment: null,
variation: null,
decisionSource: DECISION_SOURCES.ROLLOUT,
};
return {
result: decisionObj,
reasons: decideReasons,
};
}
const rollout = configObj.rolloutIdMap[feature.rolloutId];
if (!rollout) {
this.logger?.error(
INVALID_ROLLOUT_ID,
feature.rolloutId,
feature.key,
);
decideReasons.push([INVALID_ROLLOUT_ID, feature.rolloutId, feature.key]);
decisionObj = {
experiment: null,
variation: null,
decisionSource: DECISION_SOURCES.ROLLOUT,
};
return {
result: decisionObj,
reasons: decideReasons,
};
}