-
Notifications
You must be signed in to change notification settings - Fork 9
/
DecisionUtil.js
1176 lines (1100 loc) · 35.3 KB
/
DecisionUtil.js
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 2019-2022 Wingify Software Pvt. Ltd.
*
* 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.
*/
const VariationDecider = require('../core/VariationDecider');
const BucketingService = require('../core/BucketingService');
const CampaignUtil = require('./CampaignUtil');
const DataTypeUtil = require('./DataTypeUtil');
const FunctionUtil = require('./FunctionUtil');
const logging = require('../services/logging');
const FileNameEnum = require('../enums/FileNameEnum');
const StatusEnum = require('../enums/StatusEnum');
const { LogLevelEnum, LogMessageEnum, LogMessageUtil } = logging;
const logger = logging.getLogger();
const SegmentEvaluator = require('../core/SegmentEvaluator');
const HooksManager = require('../services/HooksManager');
const HooksEnum = require('../enums/HooksEnum');
const UuidUtil = require('./UuidUtil');
const Constants = require('../constants');
const CampaignTypeEnum = require('../enums/CampaignTypeEnum');
const ApiEnum = require('../enums/ApiEnum');
const RandomAlgo = 1;
const file = FileNameEnum.DecisionUtil;
const SegmentationTypeEnum = {
WHITELISTING: 'whitelisting',
PRE_SEGMENTATION: 'pre-segmentation'
};
let DecisionUtil = {
// PUBLIC METHODS
/**
* 1. Checks if there is a variation stored in userStorage, returns it
* 2. If Whitelisting is applicable, evaluate it, if any eligible variation is found, store it in User Storage service and return, otherwise skip it.
* 3. Check if the campaign is part of mutually exclusive group, if yes, get the winner campaign using campaign traffic normalization.
* 4. If Pre-segmentation is applied and passes then go further otherwise return early and no further processing
* 5. If no user storage value, no whitelisted variation and pre-segmentation evaluates to true, get variation using hashing logic if campaign traffic passes for that userId
*
*
* @param {Object} config
* @param {Object} settingsFile
* @param {Object} campaign
* @param {Object} campaignKey
* @param {String} userId
* @param {Object} customVariables
* @param {Object} variationTargetingVariables
*
* @return {Object|null} - Object if a variation is assigned, otherwise null
*/
getVariation: (
config,
settingsFile,
campaign,
campaignKey,
userId,
customVariables,
variationTargetingVariables = {},
userStorageData = {},
metaData,
isTrackUserAPI,
newGoalIdentifier,
api = ''
) => {
let vwoUserId = UuidUtil.generateFor(userId, settingsFile.accountId);
logger.log(
LogLevelEnum.DEBUG,
LogMessageUtil.build(LogMessageEnum.DEBUG_MESSAGES.USER_UUID, {
file: FileNameEnum.UuidUtil,
userId,
accountId: settingsFile.accountId,
uuid: vwoUserId
})
);
let decision = {
// campaign info
campaignId: campaign.id,
campaignKey,
campaignType: campaign.type,
campaignName: campaign.name,
// campaign segmentation conditions
customVariables,
// event name
event: HooksEnum.DECISION_TYPES.CAMPAIGN_DECISION,
// goal tracked in case of track API
goalIdentifier: newGoalIdentifier,
// campaign whitelisting flag
isForcedVariationEnabled: campaign.isForcedVariationEnabled,
sdkVersion: Constants.SDK_VERSION,
// API name which triggered the event
source: api,
// Passed in API
userId,
// Campaign Whitelisting conditions
variationTargetingVariables,
// VWO generated UUID based on passed UserId and Account ID
vwoUserId
};
// check if the campaign is a part of group
const { groupId, groupName } = CampaignUtil.isPartOfGroup(settingsFile, campaign.id);
if (groupId) {
// append groupId and groupName, if campaign is a part of group
decision['groupId'] = groupId;
decision['groupName'] = groupName;
}
variationTargetingVariables = Object.assign({}, variationTargetingVariables, {
_vwoUserId: campaign.isUserListEnabled ? vwoUserId : userId
});
// check if tbe campaign satisfies the whitelisting before checking for the group
const whitelistedVariation = DecisionUtil._checkForWhitelisting(
campaign,
campaignKey,
userId,
variationTargetingVariables,
decision
);
if (whitelistedVariation) {
return whitelistedVariation;
}
// check if the campaign is present in the storage before checking for the group
const storedVariation = DecisionUtil._checkForUserStorage(
config,
settingsFile,
campaign,
campaignKey,
userId,
userStorageData,
isTrackUserAPI,
decision
);
if (storedVariation) {
return storedVariation;
}
// check if the called campaign satisfies the pre-segmentatin before further proccessing.
if (
!(
DecisionUtil._checkForPreSegmentation(campaign, campaignKey, userId, customVariables, decision) &&
BucketingService.isUserPartOfCampaign(userId, campaign, true)
)
) {
return {};
}
if (groupId) {
// mutually exclusive group exists
// get the list of the all the campaigns in a group
const campaignList = CampaignUtil.getGroupCampaigns(settingsFile, groupId);
if (campaignList.length === 0) {
// return if no campaigns are active in a group
return {};
}
// checking other campaigns for whitelisting and user storage.
let isWhitelistedOrStoredVariation = DecisionUtil._checkForStorageAndWhitelisting(
config,
settingsFile,
groupName,
campaignList,
campaign,
userId,
userStorageData,
variationTargetingVariables,
isTrackUserAPI
);
if (isWhitelistedOrStoredVariation) {
// other campaigns satisfy the whitelisting or storage, therfore returning
logger.log(
LogLevelEnum.INFO,
LogMessageUtil.build(LogMessageEnum.INFO_MESSAGES.MEG_CALLED_CAMPAIGN_NOT_WINNER, {
userId,
groupName,
file,
campaignKey: campaignKey
})
);
return {};
}
// none of the group campaigns satisfy whitelisting or user storage
// check each campaign for pre-segmentation and traffic allocation.
let inEligibleCampaignKeys = '';
let eligibleCampaignKeys = '';
const { eligibleCampaigns, inEligibleCampaigns } = DecisionUtil.getEligbleCampaigns(
campaignList,
userId,
customVariables
);
inEligibleCampaigns.forEach(campaign => {
inEligibleCampaignKeys = inEligibleCampaignKeys + campaign.key + ',';
});
eligibleCampaigns.forEach(campaign => {
eligibleCampaignKeys = eligibleCampaignKeys + campaign.key + ',';
});
logger.log(
LogLevelEnum.DEBUG,
LogMessageUtil.build(LogMessageEnum.DEBUG_MESSAGES.MEG_ELIGIBLE_CAMPAIGNS, {
userId,
groupName,
file,
eligibleCampaignKeys: eligibleCampaignKeys.slice(0, -1),
inEligibleText:
inEligibleCampaignKeys === '' ? 'no campaigns' : `campaigns: ${inEligibleCampaignKeys.slice(0, -1)}`
})
);
logger.log(
LogLevelEnum.INFO,
LogMessageUtil.build(LogMessageEnum.INFO_MESSAGES.MEG_ELIGIBLE_CAMPAIGNS, {
userId,
groupName,
file,
noOfEligibleCampaigns: eligibleCampaigns.length,
noOfGroupCampaigns: inEligibleCampaigns.length + eligibleCampaigns.length
})
);
// Whether normalised/random implementation has to be done or advanced
let megAlgoNumber =
typeof settingsFile.groups[groupId].et !== 'undefined' ? settingsFile.groups[groupId].et : RandomAlgo;
if (eligibleCampaigns.length === 1) {
// if the called campaign is the only winner.
return DecisionUtil.evaluateTrafficAndGetVariation(
config,
eligibleCampaigns[0],
eligibleCampaigns[0].key,
userId,
metaData,
newGoalIdentifier,
decision
);
} else {
if (megAlgoNumber === RandomAlgo) {
// normalize the eligible campaigns and decide winner
return DecisionUtil._normalizeAndFindWinningCampaign(
config,
campaign,
eligibleCampaigns,
userId,
groupName,
groupId,
metaData,
newGoalIdentifier,
decision
);
} else {
return DecisionUtil._advancedAlgoFindWinningCampaign(
config,
settingsFile,
campaign,
eligibleCampaigns,
userId,
groupName,
groupId,
metaData,
newGoalIdentifier,
decision
);
}
}
} else {
// campaign is not a part of mutually exclusive group
// check if the user is eligible to become part of the campaign and assign variation.
return DecisionUtil.evaluateTrafficAndGetVariation(
config,
campaign,
campaignKey,
userId,
metaData,
newGoalIdentifier,
decision
);
}
},
// PRIVATE METHODS
_evaluateWhitelisting: (campaign, campaignKey, userId, variationTargetingVariables, disableLogs = false) => {
let whitelistedVariation;
let status;
const targetedVariations = [];
campaign.variations.forEach(variation => {
if (DataTypeUtil.isObject(variation.segments) && !Object.keys(variation.segments).length) {
logger.log(
LogLevelEnum.DEBUG,
LogMessageUtil.build(LogMessageEnum.DEBUG_MESSAGES.SEGMENTATION_SKIPPED, {
campaignKey,
userId,
file,
variation: campaign.type === CampaignTypeEnum.FEATURE_ROLLOUT ? '' : `, for ${variation.name}`
}),
disableLogs
);
return;
}
if (
DataTypeUtil.isObject(variation.segments) &&
SegmentEvaluator(variation.segments, variationTargetingVariables, campaignKey, userId, variation.name)
) {
status = StatusEnum.PASSED;
targetedVariations.push(FunctionUtil.cloneObject(variation));
} else {
status = StatusEnum.FAILED;
}
logger.log(
LogLevelEnum.DEBUG,
LogMessageUtil.build(LogMessageEnum.DEBUG_MESSAGES.SEGMENTATION_STATUS, {
campaignKey,
userId,
customVariables: JSON.stringify(variationTargetingVariables),
file,
status,
segmentationType: SegmentationTypeEnum.WHITELISTING,
variation:
campaign.type === CampaignTypeEnum.FEATURE_ROLLOUT && status === StatusEnum.PASSED
? 'and becomes part of the rollout'
: `for ${variation.name}`
}),
disableLogs
);
});
if (targetedVariations.length > 1) {
CampaignUtil.scaleVariationWeights(targetedVariations);
for (let i = 0, currentAllocation = 0, stepFactor = 0; i < targetedVariations.length; i++) {
stepFactor = CampaignUtil.assignRangeValues(targetedVariations[i], currentAllocation);
currentAllocation += stepFactor;
}
whitelistedVariation = BucketingService._getVariation(
targetedVariations,
BucketingService.calculateBucketValue(CampaignUtil.getBucketingSeed(userId, campaign))
);
} else {
whitelistedVariation = targetedVariations[0];
}
if (whitelistedVariation) {
return {
variation: whitelistedVariation,
variationName: whitelistedVariation.name,
variationId: whitelistedVariation.id
};
}
},
/**
* If userStorageService is provided and variation was stored, get the stored variation
*
* @param {Object} config
* @param {Object} settingsFile - cloned settingsFile
* @param {String} campaignKey
* @param {String} userId
*
* @return {Object|null} - if found then variation and goalIdentifier settings object otherwise null
*/
_getStoredVariationAndGoalIdentifiers: function(
config,
settingsFile,
campaignKey,
userId,
userStorageData,
disableLogs = false
) {
let userData = DecisionUtil._getStoredUserData(config, userId, campaignKey, userStorageData, disableLogs);
let { variationName, goalIdentifier } = userData;
if (userData && userData.campaignKey && variationName) {
return {
storedVariation: CampaignUtil.getCampaignVariation(settingsFile, campaignKey, variationName),
goalIdentifier
};
}
// Log if stored variation is not found even after implementing UserStorageService
logger.log(
LogLevelEnum.DEBUG,
LogMessageUtil.build(LogMessageEnum.DEBUG_MESSAGES.USER_STORAGE_SERVICE_NO_STORED_DATA, {
file,
campaignKey,
userId
}),
disableLogs
);
return null;
},
/**
* If userStorageService is provided and variation was stored, get the stored variation
*
* @param {Object} config
* @param {Object} settingsFile - cloned settingsFile
* @param {String} campaignKey
* @param {String} userId
*
* @return {Object|null} - if found then variation settings object otherwise null
*/
_getStoredVariation: function(config, settingsFile, campaignKey, userId, userStorageData) {
const data = DecisionUtil._getStoredVariationAndGoalIdentifiers(
config,
settingsFile,
campaignKey,
userId,
userStorageData
);
if (data && data.storedVariation) {
return data.storedVariation;
}
return null;
},
/**
* Get the User Variation mapping by calling get method of UserStorageService being provided
*
* @param {Object} config
* @param {String} UserID
* @param {String} campaignKey
*
* @return {Object} - User Campaign Mapping
*/
_getStoredUserData: function(config, userId, campaignKey, userStorageData, disableLogs) {
let userStorageMap = {
userId: userId,
variationName: null,
campaignKey: campaignKey,
goalIdentifier: null
};
if (!config.userStorageService) {
logger.log(
LogLevelEnum.DEBUG,
LogMessageUtil.build(LogMessageEnum.DEBUG_MESSAGES.USER_STORAGE_SERVICE_NOT_CONFIGURED, {
file
}),
disableLogs
);
return userStorageMap;
}
try {
let data = config.userStorageService.get(userId, campaignKey) || {};
// if data found
logger.log(
LogLevelEnum.INFO,
LogMessageUtil.build(LogMessageEnum.INFO_MESSAGES.GETTING_DATA_USER_STORAGE_SERVICE, {
file,
userId,
campaignKey
}),
disableLogs
);
return Object.assign({}, data, userStorageData);
} catch (err) {
// if no data found
logger.log(
LogLevelEnum.ERROR,
LogMessageUtil.build(LogMessageEnum.ERROR_MESSAGES.USER_STORAGE_SERVICE_GET_FAILED, {
file,
userId,
error: err
}),
disableLogs
);
}
},
/**
* If UserStorageService is provided and variation was stored, save the assigned variation
*
* @param {Object} campaign
* @param {String} variationName
* @param {String} userId
*
* @return {Boolean} - true if found otherwise false
*/
_saveUserData: function(config, campaign, variationName, userId, metaData, goalIdentifier) {
let isSaved = false;
if (!config.userStorageService) {
logger.log(
LogLevelEnum.DEBUG,
LogMessageUtil.build(LogMessageEnum.DEBUG_MESSAGES.USER_STORAGE_SERVICE_NOT_CONFIGURED, {
file
})
);
return isSaved;
}
try {
const properties = {
userId: userId,
variationName,
campaignKey: campaign.key
};
if (!DataTypeUtil.isUndefined(goalIdentifier)) {
properties.goalIdentifier = goalIdentifier;
}
if (!DataTypeUtil.isUndefined(metaData)) {
properties.metaData = metaData;
}
config.userStorageService.set(properties);
logger.log(
LogLevelEnum.INFO,
LogMessageUtil.build(LogMessageEnum.INFO_MESSAGES.SETTING_DATA_USER_STORAGE_SERVICE, {
file,
userId,
campaignKey: campaign.key
})
);
isSaved = true;
} catch (err) {
logger.log(
LogLevelEnum.ERROR,
LogMessageUtil.build(LogMessageEnum.ERROR_MESSAGES.USER_STORAGE_SERVICE_SET_FAILED, {
file,
userId,
error: err
})
);
isSaved = false;
}
return isSaved;
},
/**
* Evaluate the campaign for whitelisting and store
* This method would be run only for MEG campaigns
*
* @param {Object} config
* @param {Object} settingsFile
* @param {Array} campaignList
* @param {Object} calledCampaign
* @param {String} userId
* @param {Object} userStorageData
* @param {Object} variationTargetingVariables
* @param {Boolean} isTrackUserAPI
*
* @returns {Boolean} - true, if whitelisting/storage is satisfied for any campaign
*/
_checkForStorageAndWhitelisting(
config,
settingsFile,
groupName,
campaignList,
calledCampaign,
userId,
userStorageData,
variationTargetingVariables,
isTrackUserAPI
) {
let otherCampaignWinner = false;
campaignList.some(groupCampaign => {
if (groupCampaign.id === calledCampaign.id) {
return;
}
// create a local copy of the campaigns
// groupCampaign = FunctionUtil.cloneObject(groupCampaign);
// checking other campaigns for whitelisting or user storage.
const whitelistedVariation = DecisionUtil._checkForWhitelisting(
groupCampaign,
groupCampaign.key,
userId,
variationTargetingVariables
);
if (whitelistedVariation) {
// other campaign satisfy the whitelisting
otherCampaignWinner = true;
logger.log(
LogLevelEnum.INFO,
LogMessageUtil.build(LogMessageEnum.INFO_MESSAGES.OTHER_CAMPAIGN_SATISFIES_WHITELISTING_STORAGE, {
file,
campaignKey: groupCampaign.key,
groupName,
userId,
type: 'whitelisting'
})
);
return true;
}
const storedVariation = DecisionUtil._checkForUserStorage(
config,
settingsFile,
groupCampaign,
groupCampaign.key,
userId,
userStorageData,
isTrackUserAPI
);
if (storedVariation && DataTypeUtil.isObject(storedVariation) && Object.keys(storedVariation).length > 0) {
// other campaign sastisfy the user storage
otherCampaignWinner = true;
logger.log(
LogLevelEnum.INFO,
LogMessageUtil.build(LogMessageEnum.INFO_MESSAGES.OTHER_CAMPAIGN_SATISFIES_WHITELISTING_STORAGE, {
file,
campaignKey: groupCampaign.key,
groupName,
userId,
type: 'user storage'
})
);
return true;
}
});
return otherCampaignWinner;
},
/**
* Evaluate a campaign for pre-segmentation.
*
* @param {Object} campaign
* @param {String} campaignKey
* @param {String} userId
* @param {Object} customVariables
* @param {Object} decision
*
* @returns {Boolean} true, if the pre-segmentation is satisfied.
*/
_checkForPreSegmentation: (campaign, campaignKey, userId, customVariables, decision) => {
let status;
if (DataTypeUtil.isObject(campaign.segments) && !Object.keys(campaign.segments).length) {
logger.log(
LogLevelEnum.DEBUG,
LogMessageUtil.build(LogMessageEnum.DEBUG_MESSAGES.SEGMENTATION_SKIPPED, {
campaignKey,
userId,
file
}),
!decision
);
return true;
} else {
const preSegmentationResult = SegmentEvaluator(
campaign.segments,
customVariables,
campaignKey,
userId,
!decision
);
if (!preSegmentationResult) {
status = StatusEnum.FAILED;
} else {
status = StatusEnum.PASSED;
}
logger.log(
LogLevelEnum.INFO,
LogMessageUtil.build(LogMessageEnum.INFO_MESSAGES.SEGMENTATION_STATUS, {
campaignKey,
userId,
customVariables: JSON.stringify(customVariables || {}),
file,
status,
segmentationType: SegmentationTypeEnum.PRE_SEGMENTATION,
variation: ''
}),
!decision
);
if (status === StatusEnum.FAILED) {
return false;
} else {
return true;
}
}
},
/**
* Check if user is eligible for the camapign based on traffic percentage and assign variation.
* @param {Object} config
* @param {Object} campaign
* @param {String} campaignKey
* @param {String} userId
* @param {Object} metaData
* @param {String} newGoalIdentifier
* @param {Object} decision
* @returns {Object} variation assigned to the user
*/
evaluateTrafficAndGetVariation(config, campaign, campaignKey, userId, metaData, newGoalIdentifier, decision) {
let variation, variationName, variationId;
// Use our core's VariationDecider utility to get the deterministic variation assigned to the userId for that campaign
({ variation, variationName, variationId } = VariationDecider.getVariationAllotted(
userId,
campaign,
config.settingsFile.accountId
));
logger.log(
LogLevelEnum.INFO,
LogMessageUtil.build(LogMessageEnum.INFO_MESSAGES.USER_VARIATION_ALLOCATION_STATUS, {
file,
campaignKey,
userId,
status: variationName ? `got variation:${variationName}` : 'did not get any variation'
})
);
// Check if variation-name has been assigned to the userId. If not, return no variation
if (variationName) {
// If userStorageService is provided, look into it for the saved variation for the campaign and userId
DecisionUtil._saveUserData(config, campaign, variationName, userId, metaData, newGoalIdentifier);
}
// Executing the callback when SDK makes the decision
HooksManager.execute(
Object.assign(
{
fromUserStorageService: false,
isUserWhitelisted: false
},
campaign.type === CampaignTypeEnum.FEATURE_ROLLOUT
? {
isFeatureEnabled: !!variationName
}
: {
variationName,
variationId
},
decision
)
);
return {
variation: variation && variation.variation,
variationName,
variationId
};
},
/**
* Evaluate a campaign for whitelisting
*
* @param {Object} campaign
* @param {String} campaignKey
* @param {String} userId
* @param {Object} variationTargetingVariables
* @param {Object} decision
*
* @returns {Object} whitelisted variation
*/
_checkForWhitelisting: (campaign, campaignKey, userId, variationTargetingVariables, decision) => {
let status;
let variationName, variationId;
if (campaign.isForcedVariationEnabled) {
let whitelistingResult = DecisionUtil._evaluateWhitelisting(
campaign,
campaignKey,
userId,
variationTargetingVariables,
!decision
);
let variationString;
if (whitelistingResult) {
status = StatusEnum.PASSED;
variationString = whitelistingResult.variationName;
} else {
status = StatusEnum.FAILED;
variationString = '';
}
logger.log(
LogLevelEnum.INFO,
LogMessageUtil.build(LogMessageEnum.INFO_MESSAGES.SEGMENTATION_STATUS, {
campaignKey,
userId,
customVariables: JSON.stringify(variationTargetingVariables),
file,
status,
segmentationType: SegmentationTypeEnum.WHITELISTING,
variation: campaign.type === CampaignTypeEnum.FEATURE_ROLLOUT ? '' : `for variation: ${variationString}`
}),
!decision
);
if (whitelistingResult) {
variationName = whitelistingResult.variationName;
variationId = whitelistingResult.variationId;
// Executing the callback when SDK has made a decision in case of whitelisting
if (decision) {
HooksManager.execute(
Object.assign(
{
fromUserStorageService: false,
isUserWhitelisted: !!variationName
},
campaign.type === CampaignTypeEnum.FEATURE_ROLLOUT
? {
isFeatureEnabled: !!variationName
}
: {
variationName,
variationId
},
decision
)
);
}
return whitelistingResult;
}
} else {
logger.log(
LogLevelEnum.DEBUG,
LogMessageUtil.build(LogMessageEnum.DEBUG_MESSAGES.WHITELISTING_SKIPPED, {
campaignKey,
userId,
file
}),
!decision
);
}
},
/**
* Check if the variation is present in the user storage
*
* @param {Object} config
* @param {Object} settingsFile
* @param {Object} campaign
* @param {String} campaignKey
* @param {String} userId
* @param {Object} userStorageData
* @param {Boolean} isTrackUserAPI
* @param {Object} decision
*
* @returns {Object} stored variaition
*/
_checkForUserStorage: (
config,
settingsFile,
campaign,
campaignKey,
userId,
userStorageData,
isTrackUserAPI,
decision
) => {
let variationName, variationId;
let storedVariation, goalIdentifier;
// If userStorageService is used, get the variation from the stored data
({ storedVariation, goalIdentifier } =
DecisionUtil._getStoredVariationAndGoalIdentifiers(
config,
settingsFile,
campaign.key,
userId,
userStorageData,
!decision
) || {});
// If stored variation is found, simply return the same
if (storedVariation) {
variationName = storedVariation.name;
variationId = storedVariation.id;
logger.log(
LogLevelEnum.INFO,
LogMessageUtil.build(LogMessageEnum.INFO_MESSAGES.GOT_STORED_VARIATION, {
file,
campaignKey,
userId,
variationName: storedVariation.name
}),
!decision
);
// Executing the callback when SDK gets the decision from user storage service
if (decision) {
HooksManager.execute(
Object.assign(
{
fromUserStorageService: !!variationName,
isUserWhitelisted: false
},
campaign.type === CampaignTypeEnum.FEATURE_ROLLOUT
? {
isFeatureEnabled: !!variationName
}
: {
variationName,
variationId
},
decision
)
);
}
return {
variation: storedVariation,
variationName: storedVariation.name,
variationId: storedVariation.id,
storedGoalIdentifier: goalIdentifier,
isStoredVariation: true
};
} else if (
!DataTypeUtil.isUndefined(config.userStorageService) &&
!isTrackUserAPI &&
DataTypeUtil.isUndefined(storedVariation)
) {
logger.log(
LogLevelEnum.WARN,
LogMessageUtil.build(LogMessageEnum.WARNING_MESSAGES.CAMPAIGN_NOT_ACTIVATED, {
file,
campaignKey,
userId,
api: config.apiName
}),
!decision
);
logger.log(
LogLevelEnum.INFO,
LogMessageUtil.build(LogMessageEnum.INFO_MESSAGES.CAMPAIGN_NOT_ACTIVATED, {
file,
campaignKey,
userId,
reason: config.apiName === ApiEnum.TRACK ? 'track it' : 'get the decision/value'
}),
!decision
);
return {};
}
},
/**
* Evaluate the list of campaigns for pre-segmentation and campaign traffic allocation and assign variation to the user.
* This method will be used for MEG campaigns
*
* @param {Object} config
* @param {Array} campaignList
* @param {String} userId
* @param {Object} customVariables
* @param {Object} metaData
* @param {String} newGoalIdentifier
*
* @returns {Array} list of campaigns which satisfies the conditions.
*/
getEligbleCampaigns(campaignList, userId, customVariables) {
let eligibleCampaigns = [];
let inEligibleCampaigns = [];
campaignList.forEach(groupCampaign => {
const isPartOfCampaign =
DecisionUtil._checkForPreSegmentation(groupCampaign, groupCampaign.key, userId, customVariables) &&
BucketingService.isUserPartOfCampaign(userId, groupCampaign, true);
if (isPartOfCampaign) {
groupCampaign = FunctionUtil.cloneObject(groupCampaign);
// campaign satisfies the pre-segmentation
eligibleCampaigns.push(groupCampaign);
} else {
inEligibleCampaigns.push(groupCampaign);
}
});
return {
eligibleCampaigns,
inEligibleCampaigns
};
},
/**
* Equally distribute the traffic of campaigns and assign a winner campaign by murmur hash.
*
* @param {Object} config
* @param {Object} calledCampaign
* @param {Array} shortlistedCampaigns
* @param {String} userId
* @param {Object} metaData
* @param {String} newGoalIdentifier
* @param {Object} decision
*