-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathoptimizely.py
More file actions
1613 lines (1334 loc) · 68.4 KB
/
optimizely.py
File metadata and controls
1613 lines (1334 loc) · 68.4 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 2016-2023, 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.
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optional, Union
from optimizely.helpers.types import VariationDict
from . import decision_service
from . import entities
from . import event_builder
from . import exceptions
from . import logger as _logging
from . import project_config
from . import user_profile
from .config_manager import AuthDatafilePollingConfigManager
from .config_manager import BaseConfigManager
from .config_manager import PollingConfigManager
from .config_manager import StaticConfigManager
from .decision.optimizely_decide_option import OptimizelyDecideOption
from .decision.optimizely_decision import OptimizelyDecision
from .decision.optimizely_decision_message import OptimizelyDecisionMessage
from .decision_service import Decision
from .error_handler import NoOpErrorHandler, BaseErrorHandler
from .event import event_factory, user_event_factory
from .event.event_processor import BatchEventProcessor, BaseEventProcessor
from .event_dispatcher import EventDispatcher, CustomEventDispatcher
from .helpers import enums, validator
from .helpers.sdk_settings import OptimizelySdkSettings
from .helpers.enums import DecisionSources
from .notification_center import NotificationCenter
from .notification_center_registry import _NotificationCenterRegistry
from .odp.lru_cache import LRUCache
from .odp.odp_manager import OdpManager
from .optimizely_config import OptimizelyConfig, OptimizelyConfigService
from .optimizely_user_context import OptimizelyUserContext, UserAttributes
from .project_config import ProjectConfig
from .cmab.cmab_client import DefaultCmabClient, CmabRetryConfig
from .cmab.cmab_service import DefaultCmabService, CmabCacheValue, DEFAULT_CMAB_CACHE_SIZE, DEFAULT_CMAB_CACHE_TIMEOUT
if TYPE_CHECKING:
# prevent circular dependency by skipping import at runtime
from .user_profile import UserProfileService
from .helpers.event_tag_utils import EventTags
class Optimizely:
""" Class encapsulating all SDK functionality. """
def __init__(
self,
datafile: Optional[str] = None,
event_dispatcher: Optional[CustomEventDispatcher] = None,
logger: Optional[_logging.Logger] = None,
error_handler: Optional[BaseErrorHandler] = None,
skip_json_validation: Optional[bool] = False,
user_profile_service: Optional[UserProfileService] = None,
sdk_key: Optional[str] = None,
config_manager: Optional[BaseConfigManager] = None,
notification_center: Optional[NotificationCenter] = None,
event_processor: Optional[BaseEventProcessor] = None,
datafile_access_token: Optional[str] = None,
default_decide_options: Optional[list[str]] = None,
event_processor_options: Optional[dict[str, Any]] = None,
settings: Optional[OptimizelySdkSettings] = None,
cmab_service: Optional[DefaultCmabService] = None,
) -> None:
""" Optimizely init method for managing Custom projects.
Args:
datafile: Optional JSON string representing the project. Must provide at least one of datafile or sdk_key.
event_dispatcher: Provides a dispatch_event method which if given a URL and params sends a request to it.
logger: Optional component which provides a log method to log messages. By default nothing would be logged.
error_handler: Optional component which provides a handle_error method to handle exceptions.
By default all exceptions will be suppressed.
skip_json_validation: Optional boolean param which allows skipping JSON schema validation upon object
invocation.
By default JSON schema validation will be performed.
user_profile_service: Optional component which provides methods to store and manage user profiles.
sdk_key: Optional string uniquely identifying the datafile corresponding to project and environment
combination.
Must provide at least one of datafile or sdk_key.
config_manager: Optional component which implements optimizely.config_manager.BaseConfigManager.
notification_center: Optional instance of notification_center.NotificationCenter. Useful when providing own
config_manager.BaseConfigManager implementation which can be using the
same NotificationCenter instance.
event_processor: Optional component which processes the given event(s).
By default optimizely.event.event_processor.BatchEventProcessor is used
which batches events. To simply forward events to the event dispatcher
configure and use optimizely.event.event_processor.ForwardingEventProcessor.
datafile_access_token: Optional string used to fetch authenticated datafile for a secure project environment.
default_decide_options: Optional list of decide options used with the decide APIs.
event_processor_options: Optional dict of options to be passed to the default batch event processor.
settings: Optional instance of OptimizelySdkSettings for sdk configuration.
"""
self.logger_name = '.'.join([__name__, self.__class__.__name__])
self.is_valid = True
self.event_dispatcher = event_dispatcher or EventDispatcher
self.logger = _logging.adapt_logger(logger or _logging.NoOpLogger())
self.error_handler = error_handler or NoOpErrorHandler
self.config_manager: BaseConfigManager = config_manager # type: ignore[assignment]
self.notification_center = notification_center or NotificationCenter(self.logger)
event_processor_defaults = {
'batch_size': 1,
'flush_interval': 30,
'timeout_interval': 5,
'start_on_init': True
}
if event_processor_options:
event_processor_defaults.update(event_processor_options)
self.event_processor = event_processor or BatchEventProcessor(
self.event_dispatcher,
logger=self.logger,
notification_center=self.notification_center,
**event_processor_defaults # type: ignore[arg-type]
)
self.default_decide_options: list[str]
if default_decide_options is None:
self.default_decide_options = []
else:
self.default_decide_options = default_decide_options
if isinstance(self.default_decide_options, list):
self.default_decide_options = self.default_decide_options[:]
else:
self.logger.debug('Provided default decide options is not a list.')
self.default_decide_options = []
self.sdk_settings: OptimizelySdkSettings = settings # type: ignore[assignment]
try:
self._validate_instantiation_options()
except exceptions.InvalidInputException as error:
self.is_valid = False
# We actually want to log this error to stderr, so make sure the logger
# has a handler capable of doing that.
self.logger = _logging.reset_logger(self.logger_name)
self.logger.exception(str(error))
return
config_manager_options: dict[str, Any] = {
'datafile': datafile,
'logger': self.logger,
'error_handler': self.error_handler,
'notification_center': self.notification_center,
'skip_json_validation': skip_json_validation,
}
if not self.config_manager:
if sdk_key:
config_manager_options['sdk_key'] = sdk_key
if datafile_access_token:
config_manager_options['datafile_access_token'] = datafile_access_token
self.config_manager = AuthDatafilePollingConfigManager(**config_manager_options)
else:
self.config_manager = PollingConfigManager(**config_manager_options)
else:
self.config_manager = StaticConfigManager(**config_manager_options)
self.odp_manager: OdpManager
self._setup_odp(self.config_manager.get_sdk_key())
self.event_builder = event_builder.EventBuilder()
# Initialize CMAB components
if cmab_service:
self.cmab_service = cmab_service
else:
# Get custom prediction endpoint from settings if provided
cmab_prediction_endpoint = None
if self.sdk_settings and self.sdk_settings.cmab_prediction_endpoint:
cmab_prediction_endpoint = self.sdk_settings.cmab_prediction_endpoint
self.cmab_client = DefaultCmabClient(
retry_config=CmabRetryConfig(),
logger=self.logger,
prediction_endpoint=cmab_prediction_endpoint
)
self.cmab_cache: LRUCache[str, CmabCacheValue] = LRUCache(DEFAULT_CMAB_CACHE_SIZE,
DEFAULT_CMAB_CACHE_TIMEOUT)
self.cmab_service = DefaultCmabService(
cmab_cache=self.cmab_cache,
cmab_client=self.cmab_client,
logger=self.logger
)
self.decision_service = decision_service.DecisionService(self.logger, user_profile_service, self.cmab_service)
self.user_profile_service = user_profile_service
def _get_variation_key(self, variation: Optional[Union[entities.Variation, VariationDict]]) -> Optional[str]:
"""Helper to extract variation key from either dict (holdout) or Variation object.
Args:
variation: Either a dict (from holdout) or entities.Variation object
Returns:
The variation key as a string, or None if not available
"""
if variation is None:
return None
try:
# Try dict access first (for holdouts)
if isinstance(variation, dict):
return variation.get('key')
# Otherwise assume it's a Variation entity object
else:
return variation.key
except (AttributeError, KeyError, TypeError):
self.logger.warning(f"Unable to extract variation key from {type(variation)}")
return None
def _get_variation_id(self, variation: Optional[Union[entities.Variation, VariationDict]]) -> Optional[str]:
"""Helper to extract variation id from either dict (holdout) or Variation object.
Args:
variation: Either a dict (from holdout) or entities.Variation object
Returns:
The variation id as a string, or None if not available
"""
if variation is None:
return None
try:
# Try dict access first (for holdouts)
if isinstance(variation, dict):
return variation.get('id')
# Otherwise assume it's a Variation entity object
else:
return variation.id
except (AttributeError, KeyError, TypeError):
self.logger.warning(f"Unable to extract variation id from {type(variation)}")
return None
def _get_feature_enabled(self, variation: Optional[Union[entities.Variation, VariationDict]]) -> bool:
"""Helper to extract featureEnabled flag from either dict (holdout) or Variation object.
Args:
variation: Either a dict (from holdout) or entities.Variation object
Returns:
The featureEnabled value, defaults to False if not available
"""
if variation is None:
return False
try:
if isinstance(variation, dict):
feature_enabled = variation.get('featureEnabled', False)
return bool(feature_enabled) if feature_enabled is not None else False
else:
return variation.featureEnabled if hasattr(variation, 'featureEnabled') else False
except (AttributeError, KeyError, TypeError):
return False
def _validate_instantiation_options(self) -> None:
""" Helper method to validate all instantiation parameters.
Raises:
Exception if provided instantiation options are valid.
"""
if self.config_manager and not validator.is_config_manager_valid(self.config_manager):
raise exceptions.InvalidInputException(enums.Errors.INVALID_INPUT.format('config_manager'))
if not validator.is_event_dispatcher_valid(self.event_dispatcher):
raise exceptions.InvalidInputException(enums.Errors.INVALID_INPUT.format('event_dispatcher'))
if not validator.is_logger_valid(self.logger):
raise exceptions.InvalidInputException(enums.Errors.INVALID_INPUT.format('logger'))
if not validator.is_error_handler_valid(self.error_handler):
raise exceptions.InvalidInputException(enums.Errors.INVALID_INPUT.format('error_handler'))
if not validator.is_notification_center_valid(self.notification_center):
raise exceptions.InvalidInputException(enums.Errors.INVALID_INPUT.format('notification_center'))
if not validator.is_event_processor_valid(self.event_processor):
raise exceptions.InvalidInputException(enums.Errors.INVALID_INPUT.format('event_processor'))
if not isinstance(self.sdk_settings, OptimizelySdkSettings):
if self.sdk_settings is not None:
self.logger.debug('Provided sdk_settings is not an OptimizelySdkSettings instance.')
self.sdk_settings = OptimizelySdkSettings()
if self.sdk_settings.segments_cache:
if not validator.is_segments_cache_valid(self.sdk_settings.segments_cache):
raise exceptions.InvalidInputException(enums.Errors.INVALID_INPUT.format('segments_cache'))
if self.sdk_settings.odp_segment_manager:
if not validator.is_segment_manager_valid(self.sdk_settings.odp_segment_manager):
raise exceptions.InvalidInputException(enums.Errors.INVALID_INPUT.format('segment_manager'))
if self.sdk_settings.odp_event_manager:
if not validator.is_event_manager_valid(self.sdk_settings.odp_event_manager):
raise exceptions.InvalidInputException(enums.Errors.INVALID_INPUT.format('event_manager'))
def _validate_user_inputs(
self, attributes: Optional[UserAttributes] = None, event_tags: Optional[EventTags] = None
) -> bool:
""" Helper method to validate user inputs.
Args:
attributes: Dict representing user attributes.
event_tags: Dict representing metadata associated with an event.
Returns:
Boolean True if inputs are valid. False otherwise.
"""
if attributes and not validator.are_attributes_valid(attributes):
self.logger.error('Provided attributes are in an invalid format.')
self.error_handler.handle_error(exceptions.InvalidAttributeException(enums.Errors.INVALID_ATTRIBUTE_FORMAT))
return False
if event_tags and not validator.are_event_tags_valid(event_tags):
self.logger.error('Provided event tags are in an invalid format.')
self.error_handler.handle_error(exceptions.InvalidEventTagException(enums.Errors.INVALID_EVENT_TAG_FORMAT))
return False
return True
def _send_impression_event(
self, project_config: project_config.ProjectConfig,
experiment: Optional[Union[entities.Experiment, entities.Holdout]],
variation: Optional[Union[entities.Variation, VariationDict]], flag_key: str, rule_key: str, rule_type: str,
enabled: bool, user_id: str, attributes: Optional[UserAttributes], cmab_uuid: Optional[str] = None
) -> None:
""" Helper method to send impression event.
Args:
project_config: Instance of ProjectConfig.
experiment: Experiment for which impression event is being sent.
variation: Variation picked for user for the given experiment.
flag_key: key for a feature flag.
rule_key: key for an experiment.
rule_type: type for the source.
enabled: boolean representing if feature is enabled
user_id: ID for user.
attributes: Dict representing user attributes and values which need to be recorded.
"""
if not experiment:
experiment = entities.Experiment.get_default()
variation_id = self._get_variation_id(variation) if variation is not None else None
user_event = user_event_factory.UserEventFactory.create_impression_event(
project_config, experiment, variation_id,
flag_key, rule_key, rule_type,
enabled, user_id, attributes, cmab_uuid
)
if user_event is None:
self.logger.error('Cannot process None event.')
return
self.event_processor.process(user_event)
# Kept for backward compatibility.
# This notification is deprecated and new Decision notifications
# are sent via their respective method calls.
if len(self.notification_center.notification_listeners[enums.NotificationTypes.ACTIVATE]) > 0:
log_event = event_factory.EventFactory.create_log_event(user_event, self.logger)
self.notification_center.send_notifications(
enums.NotificationTypes.ACTIVATE, experiment, user_id, attributes, variation, log_event.__dict__,
)
def _get_feature_variable_for_type(
self, project_config: project_config.ProjectConfig, feature_key: str, variable_key: str,
variable_type: Optional[str], user_id: str, attributes: Optional[UserAttributes]
) -> Any:
""" Helper method to determine value for a certain variable attached to a feature flag based on
type of variable.
Args:
project_config: Instance of ProjectConfig.
feature_key: Key of the feature whose variable's value is being accessed.
variable_key: Key of the variable whose value is to be accessed.
variable_type: Type of variable which could be one of boolean/double/integer/string.
user_id: ID for user.
attributes: Dict representing user attributes.
Returns:
Value of the variable. None if:
- Feature key is invalid.
- Variable key is invalid.
- Mismatch with type of variable.
"""
if not validator.is_non_empty_string(feature_key):
self.logger.error(enums.Errors.INVALID_INPUT.format('feature_key'))
return None
if not validator.is_non_empty_string(variable_key):
self.logger.error(enums.Errors.INVALID_INPUT.format('variable_key'))
return None
if not isinstance(user_id, str):
self.logger.error(enums.Errors.INVALID_INPUT.format('user_id'))
return None
if not self._validate_user_inputs(attributes):
return None
feature_flag = project_config.get_feature_from_key(feature_key)
if not feature_flag:
return None
variable = project_config.get_variable_for_feature(feature_key, variable_key)
if not variable:
return None
# For non-typed method, use type of variable; else, return None if type differs
variable_type = variable_type or variable.type
if variable.type != variable_type:
self.logger.warning(
f'Requested variable type "{variable_type}", but variable is of '
f'type "{variable.type}". Use correct API to retrieve value. Returning None.'
)
return None
feature_enabled = False
source_info = {}
variable_value = variable.defaultValue
user_context = OptimizelyUserContext(self, self.logger, user_id, attributes, False)
decision_result = self.decision_service.get_variation_for_feature(project_config, feature_flag, user_context)
decision = decision_result['decision']
if decision.variation:
feature_enabled = self._get_feature_enabled(decision.variation)
if feature_enabled:
variable_value = project_config.get_variable_value_for_variation(variable, decision.variation)
self.logger.info(
f'Got variable value "{variable_value}" for '
f'variable "{variable_key}" of feature flag "{feature_key}".'
)
else:
self.logger.info(
f'Feature "{feature_key}" is not enabled for user "{user_id}". '
f'Returning the default variable value "{variable_value}".'
)
else:
self.logger.info(
f'User "{user_id}" is not in any variation or rollout rule. '
f'Returning default value for variable "{variable_key}" of feature flag "{feature_key}".'
)
if decision.source in (enums.DecisionSources.FEATURE_TEST, enums.DecisionSources.HOLDOUT):
source_info = {
'experiment_key': decision.experiment.key if decision.experiment else None,
'variation_key': self._get_variation_key(decision.variation),
}
try:
actual_value = project_config.get_typecast_value(variable_value, variable_type)
except:
self.logger.error('Unable to cast value. Returning None.')
actual_value = None
self.notification_center.send_notifications(
enums.NotificationTypes.DECISION,
enums.DecisionNotificationTypes.FEATURE_VARIABLE,
user_id,
attributes or {},
{
'feature_key': feature_key,
'feature_enabled': feature_enabled,
'source': decision.source,
'variable_key': variable_key,
'variable_value': actual_value,
'variable_type': variable_type,
'source_info': source_info,
},
)
return actual_value
def _get_all_feature_variables_for_type(
self, project_config: project_config.ProjectConfig, feature_key: str,
user_id: str, attributes: Optional[UserAttributes],
) -> Optional[dict[str, Any]]:
""" Helper method to determine value for all variables attached to a feature flag.
Args:
project_config: Instance of ProjectConfig.
feature_key: Key of the feature whose variable's value is being accessed.
user_id: ID for user.
attributes: Dict representing user attributes.
Returns:
Dictionary of all variables. None if:
- Feature key is invalid.
"""
if not validator.is_non_empty_string(feature_key):
self.logger.error(enums.Errors.INVALID_INPUT.format('feature_key'))
return None
if not isinstance(user_id, str):
self.logger.error(enums.Errors.INVALID_INPUT.format('user_id'))
return None
if not self._validate_user_inputs(attributes):
return None
feature_flag = project_config.get_feature_from_key(feature_key)
if not feature_flag:
return None
feature_enabled = False
source_info = {}
user_context = OptimizelyUserContext(self, self.logger, user_id, attributes, False)
decision = self.decision_service.get_variation_for_feature(project_config,
feature_flag,
user_context)['decision']
if decision.variation:
feature_enabled = self._get_feature_enabled(decision.variation)
if feature_enabled:
self.logger.info(
f'Feature "{feature_key}" is enabled for user "{user_id}".'
)
else:
self.logger.info(
f'Feature "{feature_key}" is not enabled for user "{user_id}".'
)
else:
self.logger.info(
f'User "{user_id}" is not in any variation or rollout rule. '
f'Returning default value for all variables of feature flag "{feature_key}".'
)
all_variables = {}
for variable_key, variable in feature_flag.variables.items():
variable_value = variable.defaultValue
if feature_enabled:
variable_value = project_config.get_variable_value_for_variation(variable, decision.variation)
self.logger.debug(
f'Got variable value "{variable_value}" for '
f'variable "{variable_key}" of feature flag "{feature_key}".'
)
try:
actual_value = project_config.get_typecast_value(variable_value, variable.type)
except:
self.logger.error('Unable to cast value. Returning None.')
actual_value = None
all_variables[variable_key] = actual_value
if decision.source == enums.DecisionSources.FEATURE_TEST:
source_info = {
'experiment_key': decision.experiment.key if decision.experiment else None,
'variation_key': self._get_variation_key(decision.variation),
}
self.notification_center.send_notifications(
enums.NotificationTypes.DECISION,
enums.DecisionNotificationTypes.ALL_FEATURE_VARIABLES,
user_id,
attributes or {},
{
'feature_key': feature_key,
'feature_enabled': feature_enabled,
'variable_values': all_variables,
'source': decision.source,
'source_info': source_info,
},
)
return all_variables
def activate(self, experiment_key: str, user_id: str, attributes: Optional[UserAttributes] = None) -> Optional[str]:
""" Buckets visitor and sends impression event to Optimizely.
Args:
experiment_key: Experiment which needs to be activated.
user_id: ID for user.
attributes: Dict representing user attributes and values which need to be recorded.
Returns:
Variation key representing the variation the user will be bucketed in.
None if user is not in experiment or if experiment is not Running.
"""
if not self.is_valid:
self.logger.error(enums.Errors.INVALID_OPTIMIZELY.format('activate'))
return None
if not validator.is_non_empty_string(experiment_key):
self.logger.error(enums.Errors.INVALID_INPUT.format('experiment_key'))
return None
if not isinstance(user_id, str):
self.logger.error(enums.Errors.INVALID_INPUT.format('user_id'))
return None
project_config = self.config_manager.get_config()
if not project_config:
self.logger.error(enums.Errors.INVALID_PROJECT_CONFIG.format('activate'))
return None
variation_key = self.get_variation(experiment_key, user_id, attributes)
if not variation_key:
self.logger.info(f'Not activating user "{user_id}".')
return None
experiment = project_config.get_experiment_from_key(experiment_key)
variation = project_config.get_variation_from_key(experiment_key, variation_key)
if not variation or not experiment:
self.logger.info(f'Not activating user "{user_id}".')
return None
# Create and dispatch impression event
self.logger.info(f'Activating user "{user_id}" in experiment "{experiment.key}".')
self._send_impression_event(project_config, experiment, variation, '', experiment.key,
enums.DecisionSources.EXPERIMENT, True, user_id, attributes)
# Handle both Variation entity and VariationDict
return variation['key'] if isinstance(variation, dict) else variation.key
def track(
self, event_key: str, user_id: str,
attributes: Optional[UserAttributes] = None,
event_tags: Optional[EventTags] = None
) -> None:
""" Send conversion event to Optimizely.
Args:
event_key: Event key representing the event which needs to be recorded.
user_id: ID for user.
attributes: Dict representing visitor attributes and values which need to be recorded.
event_tags: Dict representing metadata associated with the event.
"""
if not self.is_valid:
self.logger.error(enums.Errors.INVALID_OPTIMIZELY.format('track'))
return
if not validator.is_non_empty_string(event_key):
self.logger.error(enums.Errors.INVALID_INPUT.format('event_key'))
return
if not isinstance(user_id, str):
self.logger.error(enums.Errors.INVALID_INPUT.format('user_id'))
return
if not self._validate_user_inputs(attributes, event_tags):
return
project_config = self.config_manager.get_config()
if not project_config:
self.logger.error(enums.Errors.INVALID_PROJECT_CONFIG.format('track'))
return
event = project_config.get_event(event_key)
if not event:
self.logger.info(f'Not tracking user "{user_id}" for event "{event_key}".')
return
user_event = user_event_factory.UserEventFactory.create_conversion_event(
project_config, event_key, user_id, attributes, event_tags
)
if user_event is None:
self.logger.error('Cannot process None event.')
return
self.event_processor.process(user_event)
self.logger.info(f'Tracking event "{event_key}" for user "{user_id}".')
if len(self.notification_center.notification_listeners[enums.NotificationTypes.TRACK]) > 0:
log_event = event_factory.EventFactory.create_log_event(user_event, self.logger)
self.notification_center.send_notifications(
enums.NotificationTypes.TRACK, event_key, user_id, attributes, event_tags, log_event.__dict__,
)
def get_variation(
self, experiment_key: str, user_id: str, attributes: Optional[UserAttributes] = None
) -> Optional[str]:
""" Gets variation where user will be bucketed.
Args:
experiment_key: Experiment for which user variation needs to be determined.
user_id: ID for user.
attributes: Dict representing user attributes.
Returns:
Variation key representing the variation the user will be bucketed in.
None if user is not in experiment or if experiment is not Running.
"""
if not self.is_valid:
self.logger.error(enums.Errors.INVALID_OPTIMIZELY.format('get_variation'))
return None
if not validator.is_non_empty_string(experiment_key):
self.logger.error(enums.Errors.INVALID_INPUT.format('experiment_key'))
return None
if not isinstance(user_id, str):
self.logger.error(enums.Errors.INVALID_INPUT.format('user_id'))
return None
project_config = self.config_manager.get_config()
if not project_config:
self.logger.error(enums.Errors.INVALID_PROJECT_CONFIG.format('get_variation'))
return None
experiment = project_config.get_experiment_from_key(experiment_key)
variation_key = None
if not experiment:
self.logger.info(f'Experiment key "{experiment_key}" is invalid. Not activating user "{user_id}".')
return None
if not self._validate_user_inputs(attributes):
return None
user_context = OptimizelyUserContext(self, self.logger, user_id, attributes, False)
user_profile_tracker = user_profile.UserProfileTracker(user_id, self.user_profile_service, self.logger)
user_profile_tracker.load_user_profile()
variation_result = self.decision_service.get_variation(project_config, experiment,
user_context, user_profile_tracker)
variation = variation_result['variation']
user_profile_tracker.save_user_profile()
if variation:
variation_key = self._get_variation_key(variation)
if project_config.is_feature_experiment(experiment.id):
decision_notification_type = enums.DecisionNotificationTypes.FEATURE_TEST
else:
decision_notification_type = enums.DecisionNotificationTypes.AB_TEST
self.notification_center.send_notifications(
enums.NotificationTypes.DECISION,
decision_notification_type,
user_id,
attributes or {},
{'experiment_key': experiment_key, 'variation_key': variation_key},
)
return variation_key
def is_feature_enabled(self, feature_key: str, user_id: str, attributes: Optional[UserAttributes] = None) -> bool:
""" Returns true if the feature is enabled for the given user.
Args:
feature_key: The key of the feature for which we are determining if it is enabled or not for the given user.
user_id: ID for user.
attributes: Dict representing user attributes.
Returns:
True if the feature is enabled for the user. False otherwise.
"""
if not self.is_valid:
self.logger.error(enums.Errors.INVALID_OPTIMIZELY.format('is_feature_enabled'))
return False
if not validator.is_non_empty_string(feature_key):
self.logger.error(enums.Errors.INVALID_INPUT.format('feature_key'))
return False
if not isinstance(user_id, str):
self.logger.error(enums.Errors.INVALID_INPUT.format('user_id'))
return False
if not self._validate_user_inputs(attributes):
return False
project_config = self.config_manager.get_config()
if not project_config:
self.logger.error(enums.Errors.INVALID_PROJECT_CONFIG.format('is_feature_enabled'))
return False
feature = project_config.get_feature_from_key(feature_key)
if not feature:
return False
feature_enabled = False
source_info = {}
user_context = OptimizelyUserContext(self, self.logger, user_id, attributes, False)
decision = self.decision_service.get_variation_for_feature(project_config, feature, user_context)['decision']
cmab_uuid = decision.cmab_uuid
is_source_experiment = decision.source == enums.DecisionSources.FEATURE_TEST
is_source_rollout = decision.source == enums.DecisionSources.ROLLOUT
if decision.variation:
if self._get_feature_enabled(decision.variation) is True:
feature_enabled = True
if (is_source_rollout or not decision.variation) and project_config.get_send_flag_decisions_value():
self._send_impression_event(
project_config, decision.experiment, decision.variation, feature.key, decision.experiment.key if
decision.experiment else '', str(decision.source), feature_enabled, user_id, attributes, cmab_uuid
)
# Send event if Decision came from an experiment.
if is_source_experiment and decision.variation and decision.experiment:
source_info = {
'experiment_key': decision.experiment.key,
'variation_key': self._get_variation_key(decision.variation),
}
self._send_impression_event(
project_config, decision.experiment, decision.variation, feature.key, decision.experiment.key,
str(decision.source), feature_enabled, user_id, attributes, cmab_uuid
)
if feature_enabled:
self.logger.info(f'Feature "{feature_key}" is enabled for user "{user_id}".')
else:
self.logger.info(f'Feature "{feature_key}" is not enabled for user "{user_id}".')
self.notification_center.send_notifications(
enums.NotificationTypes.DECISION,
enums.DecisionNotificationTypes.FEATURE,
user_id,
attributes or {},
{
'feature_key': feature_key,
'feature_enabled': feature_enabled,
'source': decision.source,
'source_info': source_info,
},
)
return feature_enabled
def get_enabled_features(self, user_id: str, attributes: Optional[UserAttributes] = None) -> list[str]:
""" Returns the list of features that are enabled for the user.
Args:
user_id: ID for user.
attributes: Dict representing user attributes.
Returns:
A list of the keys of the features that are enabled for the user.
"""
enabled_features: list[str] = []
if not self.is_valid:
self.logger.error(enums.Errors.INVALID_OPTIMIZELY.format('get_enabled_features'))
return enabled_features
if not isinstance(user_id, str):
self.logger.error(enums.Errors.INVALID_INPUT.format('user_id'))
return enabled_features
if not self._validate_user_inputs(attributes):
return enabled_features
project_config = self.config_manager.get_config()
if not project_config:
self.logger.error(enums.Errors.INVALID_PROJECT_CONFIG.format('get_enabled_features'))
return enabled_features
for feature in project_config.feature_key_map.values():
if self.is_feature_enabled(feature.key, user_id, attributes):
enabled_features.append(feature.key)
return enabled_features
def get_feature_variable(
self, feature_key: str, variable_key: str, user_id: str, attributes: Optional[UserAttributes] = None
) -> Any:
""" Returns value for a variable attached to a feature flag.
Args:
feature_key: Key of the feature whose variable's value is being accessed.
variable_key: Key of the variable whose value is to be accessed.
user_id: ID for user.
attributes: Dict representing user attributes.
Returns:
Value of the variable. None if:
- Feature key is invalid.
- Variable key is invalid.
"""
project_config = self.config_manager.get_config()
if not project_config:
self.logger.error(enums.Errors.INVALID_PROJECT_CONFIG.format('get_feature_variable'))
return None
return self._get_feature_variable_for_type(project_config, feature_key, variable_key, None, user_id, attributes)
def get_feature_variable_boolean(
self, feature_key: str, variable_key: str, user_id: str, attributes: Optional[UserAttributes] = None
) -> Optional[bool]:
""" Returns value for a certain boolean variable attached to a feature flag.
Args:
feature_key: Key of the feature whose variable's value is being accessed.
variable_key: Key of the variable whose value is to be accessed.
user_id: ID for user.
attributes: Dict representing user attributes.
Returns:
Boolean value of the variable. None if:
- Feature key is invalid.
- Variable key is invalid.
- Mismatch with type of variable.
"""
variable_type = entities.Variable.Type.BOOLEAN
project_config = self.config_manager.get_config()
if not project_config:
self.logger.error(enums.Errors.INVALID_PROJECT_CONFIG.format('get_feature_variable_boolean'))
return None
return self._get_feature_variable_for_type( # type: ignore[no-any-return]
project_config, feature_key, variable_key, variable_type, user_id, attributes,
)
def get_feature_variable_double(
self, feature_key: str, variable_key: str, user_id: str, attributes: Optional[UserAttributes] = None
) -> Optional[float]:
""" Returns value for a certain double variable attached to a feature flag.
Args:
feature_key: Key of the feature whose variable's value is being accessed.
variable_key: Key of the variable whose value is to be accessed.
user_id: ID for user.
attributes: Dict representing user attributes.
Returns:
Double value of the variable. None if:
- Feature key is invalid.
- Variable key is invalid.
- Mismatch with type of variable.
"""
variable_type = entities.Variable.Type.DOUBLE
project_config = self.config_manager.get_config()
if not project_config:
self.logger.error(enums.Errors.INVALID_PROJECT_CONFIG.format('get_feature_variable_double'))
return None
return self._get_feature_variable_for_type( # type: ignore[no-any-return]
project_config, feature_key, variable_key, variable_type, user_id, attributes,
)
def get_feature_variable_integer(
self, feature_key: str, variable_key: str, user_id: str, attributes: Optional[UserAttributes] = None
) -> Optional[int]:
""" Returns value for a certain integer variable attached to a feature flag.
Args:
feature_key: Key of the feature whose variable's value is being accessed.
variable_key: Key of the variable whose value is to be accessed.
user_id: ID for user.
attributes: Dict representing user attributes.
Returns:
Integer value of the variable. None if:
- Feature key is invalid.
- Variable key is invalid.
- Mismatch with type of variable.
"""
variable_type = entities.Variable.Type.INTEGER
project_config = self.config_manager.get_config()
if not project_config:
self.logger.error(enums.Errors.INVALID_PROJECT_CONFIG.format('get_feature_variable_integer'))
return None
return self._get_feature_variable_for_type( # type: ignore[no-any-return]
project_config, feature_key, variable_key, variable_type, user_id, attributes,
)
def get_feature_variable_string(
self, feature_key: str, variable_key: str, user_id: str, attributes: Optional[UserAttributes] = None
) -> Optional[str]:
""" Returns value for a certain string variable attached to a feature.
Args:
feature_key: Key of the feature whose variable's value is being accessed.
variable_key: Key of the variable whose value is to be accessed.
user_id: ID for user.
attributes: Dict representing user attributes.
Returns:
String value of the variable. None if:
- Feature key is invalid.
- Variable key is invalid.
- Mismatch with type of variable.
"""