-
Notifications
You must be signed in to change notification settings - Fork 29
/
optimizely.rb
1262 lines (1077 loc) · 49.9 KB
/
optimizely.rb
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
# frozen_string_literal: true
#
# Copyright 2016-2023, Optimizely and contributors
#
# 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.
#
require_relative 'optimizely/audience'
require_relative 'optimizely/config/datafile_project_config'
require_relative 'optimizely/config_manager/http_project_config_manager'
require_relative 'optimizely/config_manager/static_project_config_manager'
require_relative 'optimizely/decide/optimizely_decide_option'
require_relative 'optimizely/decide/optimizely_decision'
require_relative 'optimizely/decide/optimizely_decision_message'
require_relative 'optimizely/decision_service'
require_relative 'optimizely/error_handler'
require_relative 'optimizely/event_builder'
require_relative 'optimizely/event/batch_event_processor'
require_relative 'optimizely/event/event_factory'
require_relative 'optimizely/event/user_event_factory'
require_relative 'optimizely/event_dispatcher'
require_relative 'optimizely/exceptions'
require_relative 'optimizely/helpers/constants'
require_relative 'optimizely/helpers/group'
require_relative 'optimizely/helpers/validator'
require_relative 'optimizely/helpers/variable_type'
require_relative 'optimizely/logger'
require_relative 'optimizely/notification_center'
require_relative 'optimizely/notification_center_registry'
require_relative 'optimizely/optimizely_config'
require_relative 'optimizely/optimizely_user_context'
require_relative 'optimizely/odp/lru_cache'
require_relative 'optimizely/odp/odp_manager'
require_relative 'optimizely/helpers/sdk_settings'
module Optimizely
class Project
include Optimizely::Decide
attr_reader :notification_center
# @api no-doc
attr_reader :config_manager, :decision_service, :error_handler, :event_dispatcher,
:event_processor, :logger, :odp_manager, :stopped
# Constructor for Projects.
#
# @param datafile - JSON string representing the project.
# @param event_dispatcher - Provides a dispatch_event method which if given a URL and params sends a request to it.
# @param logger - Optional component which provides a log method to log messages. By default nothing would be logged.
# @param error_handler - Optional component which provides a handle_error method to handle exceptions.
# By default all exceptions will be suppressed.
# @param user_profile_service - Optional component which provides methods to store and retreive user profiles.
# @param skip_json_validation - Optional boolean param to skip JSON schema validation of the provided datafile.
# @params sdk_key - Optional string uniquely identifying the datafile corresponding to project and environment combination.
# Must provide at least one of datafile or sdk_key.
# @param config_manager - Optional Responds to 'config' method.
# @param notification_center - Optional Instance of NotificationCenter.
# @param event_processor - Optional Responds to process.
# @param default_decide_options: Optional default decision options.
# @param event_processor_options: Optional hash of options to be passed to the default batch event processor.
# @param settings: Optional instance of OptimizelySdkSettings for sdk configuration.
def initialize(
datafile: nil,
event_dispatcher: nil,
logger: nil,
error_handler: nil,
skip_json_validation: false,
user_profile_service: nil,
sdk_key: nil,
config_manager: nil,
notification_center: nil,
event_processor: nil,
default_decide_options: [],
event_processor_options: {},
settings: nil
)
@logger = logger || NoOpLogger.new
@error_handler = error_handler || NoOpErrorHandler.new
@event_dispatcher = event_dispatcher || EventDispatcher.new(logger: @logger, error_handler: @error_handler)
@user_profile_service = user_profile_service
@default_decide_options = []
@sdk_settings = settings
if default_decide_options.is_a? Array
@default_decide_options = default_decide_options.clone
else
@logger.log(Logger::DEBUG, 'Provided default decide options is not an array.')
@default_decide_options = []
end
unless event_processor_options.is_a? Hash
@logger.log(Logger::DEBUG, 'Provided event processor options is not a hash.')
event_processor_options = {}
end
begin
validate_instantiation_options
rescue InvalidInputError => e
@logger = SimpleLogger.new
@logger.log(Logger::ERROR, e.message)
end
@notification_center = notification_center.is_a?(Optimizely::NotificationCenter) ? notification_center : NotificationCenter.new(@logger, @error_handler)
@config_manager = if config_manager.respond_to?(:config) && config_manager.respond_to?(:sdk_key)
config_manager
elsif sdk_key
HTTPProjectConfigManager.new(
sdk_key: sdk_key,
datafile: datafile,
logger: @logger,
error_handler: @error_handler,
skip_json_validation: skip_json_validation,
notification_center: @notification_center
)
else
StaticProjectConfigManager.new(datafile, @logger, @error_handler, skip_json_validation)
end
setup_odp!(@config_manager.sdk_key)
@decision_service = DecisionService.new(@logger, @user_profile_service)
@event_processor = if event_processor.respond_to?(:process)
event_processor
else
BatchEventProcessor.new(
event_dispatcher: @event_dispatcher,
logger: @logger,
notification_center: @notification_center,
batch_size: event_processor_options[:batch_size] || BatchEventProcessor::DEFAULT_BATCH_SIZE,
flush_interval: event_processor_options[:flush_interval] || BatchEventProcessor::DEFAULT_BATCH_INTERVAL
)
end
end
# Create a context of the user for which decision APIs will be called.
#
# A user context will be created successfully even when the SDK is not fully configured yet.
#
# @param user_id - The user ID to be used for bucketing.
# @param attributes - A Hash representing user attribute names and values.
#
# @return [OptimizelyUserContext] An OptimizelyUserContext associated with this OptimizelyClient.
# @return [nil] If user attributes are not in valid format.
def create_user_context(user_id, attributes = nil)
# We do not check for is_valid here as a user context can be created successfully
# even when the SDK is not fully configured.
# validate user_id
return nil unless Optimizely::Helpers::Validator.inputs_valid?(
{
user_id: user_id
}, @logger, Logger::ERROR
)
# validate attributes
return nil unless user_inputs_valid?(attributes)
OptimizelyUserContext.new(self, user_id, attributes)
end
def decide(user_context, key, decide_options = [])
# raising on user context as it is internal and not provided directly by the user.
raise if user_context.class != OptimizelyUserContext
reasons = []
# check if SDK is ready
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('decide').message)
reasons.push(OptimizelyDecisionMessage::SDK_NOT_READY)
return OptimizelyDecision.new(flag_key: key, user_context: user_context, reasons: reasons)
end
# validate that key is a string
unless key.is_a?(String)
@logger.log(Logger::ERROR, 'Provided key is invalid')
reasons.push(format(OptimizelyDecisionMessage::FLAG_KEY_INVALID, key))
return OptimizelyDecision.new(flag_key: key, user_context: user_context, reasons: reasons)
end
# validate that key maps to a feature flag
config = project_config
feature_flag = config.get_feature_flag_from_key(key)
unless feature_flag
@logger.log(Logger::ERROR, "No feature flag was found for key '#{key}'.")
reasons.push(format(OptimizelyDecisionMessage::FLAG_KEY_INVALID, key))
return OptimizelyDecision.new(flag_key: key, user_context: user_context, reasons: reasons)
end
# merge decide_options and default_decide_options
if decide_options.is_a? Array
decide_options += @default_decide_options
else
@logger.log(Logger::DEBUG, 'Provided decide options is not an array. Using default decide options.')
decide_options = @default_decide_options
end
# Create Optimizely Decision Result.
user_id = user_context.user_id
attributes = user_context.user_attributes
variation_key = nil
feature_enabled = false
rule_key = nil
flag_key = key
all_variables = {}
decision_event_dispatched = false
experiment = nil
decision_source = Optimizely::DecisionService::DECISION_SOURCES['ROLLOUT']
context = Optimizely::OptimizelyUserContext::OptimizelyDecisionContext.new(key, nil)
variation, reasons_received = @decision_service.validated_forced_decision(config, context, user_context)
reasons.push(*reasons_received)
if variation
decision = Optimizely::DecisionService::Decision.new(nil, variation, Optimizely::DecisionService::DECISION_SOURCES['FEATURE_TEST'])
else
decision, reasons_received = @decision_service.get_variation_for_feature(config, feature_flag, user_context, decide_options)
reasons.push(*reasons_received)
end
# Send impression event if Decision came from a feature test and decide options doesn't include disableDecisionEvent
if decision.is_a?(Optimizely::DecisionService::Decision)
experiment = decision.experiment
rule_key = experiment ? experiment['key'] : nil
variation = decision['variation']
variation_key = variation ? variation['key'] : nil
feature_enabled = variation ? variation['featureEnabled'] : false
decision_source = decision.source
end
if !decide_options.include?(OptimizelyDecideOption::DISABLE_DECISION_EVENT) && (decision_source == Optimizely::DecisionService::DECISION_SOURCES['FEATURE_TEST'] || config.send_flag_decisions)
send_impression(config, experiment, variation_key || '', flag_key, rule_key || '', feature_enabled, decision_source, user_id, attributes)
decision_event_dispatched = true
end
# Generate all variables map if decide options doesn't include excludeVariables
unless decide_options.include? OptimizelyDecideOption::EXCLUDE_VARIABLES
feature_flag['variables'].each do |variable|
variable_value = get_feature_variable_for_variation(key, feature_enabled, variation, variable, user_id)
all_variables[variable['key']] = Helpers::VariableType.cast_value_to_type(variable_value, variable['type'], @logger)
end
end
should_include_reasons = decide_options.include? OptimizelyDecideOption::INCLUDE_REASONS
# Send notification
@notification_center.send_notifications(
NotificationCenter::NOTIFICATION_TYPES[:DECISION],
Helpers::Constants::DECISION_NOTIFICATION_TYPES['FLAG'],
user_id, (attributes || {}),
flag_key: flag_key,
enabled: feature_enabled,
variables: all_variables,
variation_key: variation_key,
rule_key: rule_key,
reasons: should_include_reasons ? reasons : [],
decision_event_dispatched: decision_event_dispatched
)
OptimizelyDecision.new(
variation_key: variation_key,
enabled: feature_enabled,
variables: all_variables,
rule_key: rule_key,
flag_key: flag_key,
user_context: user_context,
reasons: should_include_reasons ? reasons : []
)
end
def decide_all(user_context, decide_options = [])
# raising on user context as it is internal and not provided directly by the user.
raise if user_context.class != OptimizelyUserContext
# check if SDK is ready
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('decide_all').message)
return {}
end
keys = []
project_config.feature_flags.each do |feature_flag|
keys.push(feature_flag['key'])
end
decide_for_keys(user_context, keys, decide_options)
end
def decide_for_keys(user_context, keys, decide_options = [])
# raising on user context as it is internal and not provided directly by the user.
raise if user_context.class != OptimizelyUserContext
# check if SDK is ready
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('decide_for_keys').message)
return {}
end
enabled_flags_only = (!decide_options.nil? && (decide_options.include? OptimizelyDecideOption::ENABLED_FLAGS_ONLY)) || (@default_decide_options.include? OptimizelyDecideOption::ENABLED_FLAGS_ONLY)
decisions = {}
keys.each do |key|
decision = decide(user_context, key, decide_options)
decisions[key] = decision unless enabled_flags_only && !decision.enabled
end
decisions
end
# Gets variation using variation key or id and flag key.
#
# @param flag_key - flag key from which the variation is required.
# @param target_value - variation value either id or key that will be matched.
# @param attribute - string representing variation attribute.
#
# @return [variation]
# @return [nil] if no variation found in flag_variation_map.
def get_flag_variation(flag_key, target_value, attribute)
project_config.get_variation_from_flag(flag_key, target_value, attribute)
end
# Buckets visitor and sends impression event to Optimizely.
#
# @param experiment_key - Experiment which needs to be activated.
# @param user_id - String ID for user.
# @param attributes - Hash representing user attributes and values to be recorded.
#
# @return [Variation Key] representing the variation the user will be bucketed in.
# @return [nil] if experiment is not Running, if user is not in experiment, or if datafile is invalid.
def activate(experiment_key, user_id, attributes = nil)
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('activate').message)
return nil
end
return nil unless Optimizely::Helpers::Validator.inputs_valid?(
{
experiment_key: experiment_key,
user_id: user_id
}, @logger, Logger::ERROR
)
config = project_config
variation_key = get_variation_with_config(experiment_key, user_id, attributes, config)
if variation_key.nil?
@logger.log(Logger::INFO, "Not activating user '#{user_id}'.")
return nil
end
# Create and dispatch impression event
experiment = config.get_experiment_from_key(experiment_key)
send_impression(
config, experiment, variation_key, '', experiment_key, true,
Optimizely::DecisionService::DECISION_SOURCES['EXPERIMENT'], user_id, attributes
)
variation_key
end
# Gets variation where visitor will be bucketed.
#
# @param experiment_key - Experiment for which visitor variation needs to be determined.
# @param user_id - String ID for user.
# @param attributes - Hash representing user attributes.
#
# @return [variation key] where visitor will be bucketed.
# @return [nil] if experiment is not Running, if user is not in experiment, or if datafile is invalid.
def get_variation(experiment_key, user_id, attributes = nil)
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_variation').message)
return nil
end
return nil unless Optimizely::Helpers::Validator.inputs_valid?(
{
experiment_key: experiment_key,
user_id: user_id
}, @logger, Logger::ERROR
)
config = project_config
get_variation_with_config(experiment_key, user_id, attributes, config)
end
# Force a user into a variation for a given experiment.
#
# @param experiment_key - String - key identifying the experiment.
# @param user_id - String - The user ID to be used for bucketing.
# @param variation_key - The variation key specifies the variation which the user will
# be forced into. If nil, then clear the existing experiment-to-variation mapping.
#
# @return [Boolean] indicates if the set completed successfully.
def set_forced_variation(experiment_key, user_id, variation_key)
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('set_forced_variation').message)
return nil
end
input_values = {experiment_key: experiment_key, user_id: user_id}
input_values[:variation_key] = variation_key unless variation_key.nil?
return false unless Optimizely::Helpers::Validator.inputs_valid?(input_values, @logger, Logger::ERROR)
config = project_config
@decision_service.set_forced_variation(config, experiment_key, user_id, variation_key)
end
# Gets the forced variation for a given user and experiment.
#
# @param experiment_key - String - Key identifying the experiment.
# @param user_id - String - The user ID to be used for bucketing.
#
# @return [String] The forced variation key.
def get_forced_variation(experiment_key, user_id)
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_forced_variation').message)
return nil
end
return nil unless Optimizely::Helpers::Validator.inputs_valid?(
{
experiment_key: experiment_key,
user_id: user_id
}, @logger, Logger::ERROR
)
config = project_config
forced_variation_key = nil
forced_variation, = @decision_service.get_forced_variation(config, experiment_key, user_id)
forced_variation_key = forced_variation['key'] if forced_variation
forced_variation_key
end
# Send conversion event to Optimizely.
#
# @param event_key - Event key representing the event which needs to be recorded.
# @param user_id - String ID for user.
# @param attributes - Hash representing visitor attributes and values which need to be recorded.
# @param event_tags - Hash representing metadata associated with the event.
def track(event_key, user_id, attributes = nil, event_tags = nil)
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('track').message)
return nil
end
return nil unless Optimizely::Helpers::Validator.inputs_valid?(
{
event_key: event_key,
user_id: user_id
}, @logger, Logger::ERROR
)
return nil unless user_inputs_valid?(attributes, event_tags)
config = project_config
event = config.get_event_from_key(event_key)
unless event
@logger.log(Logger::INFO, "Not tracking user '#{user_id}' for event '#{event_key}'.")
return nil
end
user_event = UserEventFactory.create_conversion_event(config, event, user_id, attributes, event_tags)
@event_processor.process(user_event)
@logger.log(Logger::INFO, "Tracking event '#{event_key}' for user '#{user_id}'.")
if @notification_center.notification_count(NotificationCenter::NOTIFICATION_TYPES[:TRACK]).positive?
log_event = EventFactory.create_log_event(user_event, @logger)
@notification_center.send_notifications(
NotificationCenter::NOTIFICATION_TYPES[:TRACK],
event_key, user_id, attributes, event_tags, log_event
)
end
nil
end
# Determine whether a feature is enabled.
# Sends an impression event if the user is bucketed into an experiment using the feature.
#
# @param feature_flag_key - String unique key of the feature.
# @param user_id - String ID of the user.
# @param attributes - Hash representing visitor attributes and values which need to be recorded.
#
# @return [True] if the feature is enabled.
# @return [False] if the feature is disabled.
# @return [False] if the feature is not found.
def is_feature_enabled(feature_flag_key, user_id, attributes = nil)
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('is_feature_enabled').message)
return false
end
return false unless Optimizely::Helpers::Validator.inputs_valid?(
{
feature_flag_key: feature_flag_key,
user_id: user_id
}, @logger, Logger::ERROR
)
return false unless user_inputs_valid?(attributes)
config = project_config
feature_flag = config.get_feature_flag_from_key(feature_flag_key)
unless feature_flag
@logger.log(Logger::ERROR, "No feature flag was found for key '#{feature_flag_key}'.")
return false
end
user_context = OptimizelyUserContext.new(self, user_id, attributes, identify: false)
decision, = @decision_service.get_variation_for_feature(config, feature_flag, user_context)
feature_enabled = false
source_string = Optimizely::DecisionService::DECISION_SOURCES['ROLLOUT']
if decision.is_a?(Optimizely::DecisionService::Decision)
variation = decision['variation']
feature_enabled = variation['featureEnabled']
if decision.source == Optimizely::DecisionService::DECISION_SOURCES['FEATURE_TEST']
source_string = Optimizely::DecisionService::DECISION_SOURCES['FEATURE_TEST']
source_info = {
experiment_key: decision.experiment['key'],
variation_key: variation['key']
}
# Send event if Decision came from a feature test.
send_impression(
config, decision.experiment, variation['key'], feature_flag_key, decision.experiment['key'], feature_enabled, source_string, user_id, attributes
)
elsif decision.source == Optimizely::DecisionService::DECISION_SOURCES['ROLLOUT'] && config.send_flag_decisions
send_impression(
config, decision.experiment, variation['key'], feature_flag_key, decision.experiment['key'], feature_enabled, source_string, user_id, attributes
)
end
end
if decision.nil? && config.send_flag_decisions
send_impression(
config, nil, '', feature_flag_key, '', feature_enabled, source_string, user_id, attributes
)
end
@notification_center.send_notifications(
NotificationCenter::NOTIFICATION_TYPES[:DECISION],
Helpers::Constants::DECISION_NOTIFICATION_TYPES['FEATURE'],
user_id, (attributes || {}),
feature_key: feature_flag_key,
feature_enabled: feature_enabled,
source: source_string,
source_info: source_info || {}
)
if feature_enabled == true
@logger.log(Logger::INFO,
"Feature '#{feature_flag_key}' is enabled for user '#{user_id}'.")
return true
end
@logger.log(Logger::INFO,
"Feature '#{feature_flag_key}' is not enabled for user '#{user_id}'.")
false
end
# Gets keys of all feature flags which are enabled for the user.
#
# @param user_id - ID for user.
# @param attributes - Dict representing user attributes.
# @return [feature flag keys] A List of feature flag keys that are enabled for the user.
def get_enabled_features(user_id, attributes = nil)
enabled_features = []
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_enabled_features').message)
return enabled_features
end
return enabled_features unless Optimizely::Helpers::Validator.inputs_valid?(
{
user_id: user_id
}, @logger, Logger::ERROR
)
return enabled_features unless user_inputs_valid?(attributes)
config = project_config
config.feature_flags.each do |feature|
enabled_features.push(feature['key']) if is_feature_enabled(
feature['key'],
user_id,
attributes
) == true
end
enabled_features
end
# Get the value of the specified variable in the feature flag.
#
# @param feature_flag_key - String key of feature flag the variable belongs to
# @param variable_key - String key of variable for which we are getting the value
# @param user_id - String user ID
# @param attributes - Hash representing visitor attributes and values which need to be recorded.
#
# @return [*] the type-casted variable value.
# @return [nil] if the feature flag or variable are not found.
def get_feature_variable(feature_flag_key, variable_key, user_id, attributes = nil)
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_feature_variable').message)
return nil
end
get_feature_variable_for_type(
feature_flag_key,
variable_key,
nil,
user_id,
attributes
)
end
# Get the String value of the specified variable in the feature flag.
#
# @param feature_flag_key - String key of feature flag the variable belongs to
# @param variable_key - String key of variable for which we are getting the string value
# @param user_id - String user ID
# @param attributes - Hash representing visitor attributes and values which need to be recorded.
#
# @return [String] the string variable value.
# @return [nil] if the feature flag or variable are not found.
def get_feature_variable_string(feature_flag_key, variable_key, user_id, attributes = nil)
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_feature_variable_string').message)
return nil
end
get_feature_variable_for_type(
feature_flag_key,
variable_key,
Optimizely::Helpers::Constants::VARIABLE_TYPES['STRING'],
user_id,
attributes
)
end
# Get the Json value of the specified variable in the feature flag in a Dict.
#
# @param feature_flag_key - String key of feature flag the variable belongs to
# @param variable_key - String key of variable for which we are getting the string value
# @param user_id - String user ID
# @param attributes - Hash representing visitor attributes and values which need to be recorded.
#
# @return [Dict] the Dict containing variable value.
# @return [nil] if the feature flag or variable are not found.
def get_feature_variable_json(feature_flag_key, variable_key, user_id, attributes = nil)
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_feature_variable_json').message)
return nil
end
get_feature_variable_for_type(
feature_flag_key,
variable_key,
Optimizely::Helpers::Constants::VARIABLE_TYPES['JSON'],
user_id,
attributes
)
end
# Get the Boolean value of the specified variable in the feature flag.
#
# @param feature_flag_key - String key of feature flag the variable belongs to
# @param variable_key - String key of variable for which we are getting the string value
# @param user_id - String user ID
# @param attributes - Hash representing visitor attributes and values which need to be recorded.
#
# @return [Boolean] the boolean variable value.
# @return [nil] if the feature flag or variable are not found.
def get_feature_variable_boolean(feature_flag_key, variable_key, user_id, attributes = nil)
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_feature_variable_boolean').message)
return nil
end
get_feature_variable_for_type(
feature_flag_key,
variable_key,
Optimizely::Helpers::Constants::VARIABLE_TYPES['BOOLEAN'],
user_id,
attributes
)
end
# Get the Double value of the specified variable in the feature flag.
#
# @param feature_flag_key - String key of feature flag the variable belongs to
# @param variable_key - String key of variable for which we are getting the string value
# @param user_id - String user ID
# @param attributes - Hash representing visitor attributes and values which need to be recorded.
#
# @return [Boolean] the double variable value.
# @return [nil] if the feature flag or variable are not found.
def get_feature_variable_double(feature_flag_key, variable_key, user_id, attributes = nil)
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_feature_variable_double').message)
return nil
end
get_feature_variable_for_type(
feature_flag_key,
variable_key,
Optimizely::Helpers::Constants::VARIABLE_TYPES['DOUBLE'],
user_id,
attributes
)
end
# Get values of all the variables in the feature flag and returns them in a Dict
#
# @param feature_flag_key - String key of feature flag
# @param user_id - String user ID
# @param attributes - Hash representing visitor attributes and values which need to be recorded.
#
# @return [Dict] the Dict containing all the varible values
# @return [nil] if the feature flag is not found.
def get_all_feature_variables(feature_flag_key, user_id, attributes = nil)
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_all_feature_variables').message)
return nil
end
return nil unless Optimizely::Helpers::Validator.inputs_valid?(
{
feature_flag_key: feature_flag_key,
user_id: user_id
},
@logger, Logger::ERROR
)
return nil unless user_inputs_valid?(attributes)
config = project_config
feature_flag = config.get_feature_flag_from_key(feature_flag_key)
unless feature_flag
@logger.log(Logger::INFO, "No feature flag was found for key '#{feature_flag_key}'.")
return nil
end
user_context = OptimizelyUserContext.new(self, user_id, attributes, identify: false)
decision, = @decision_service.get_variation_for_feature(config, feature_flag, user_context)
variation = decision ? decision['variation'] : nil
feature_enabled = variation ? variation['featureEnabled'] : false
all_variables = {}
feature_flag['variables'].each do |variable|
variable_value = get_feature_variable_for_variation(feature_flag_key, feature_enabled, variation, variable, user_id)
all_variables[variable['key']] = Helpers::VariableType.cast_value_to_type(variable_value, variable['type'], @logger)
end
source_string = Optimizely::DecisionService::DECISION_SOURCES['ROLLOUT']
if decision && decision['source'] == Optimizely::DecisionService::DECISION_SOURCES['FEATURE_TEST']
source_info = {
experiment_key: decision.experiment['key'],
variation_key: variation['key']
}
source_string = Optimizely::DecisionService::DECISION_SOURCES['FEATURE_TEST']
end
@notification_center.send_notifications(
NotificationCenter::NOTIFICATION_TYPES[:DECISION],
Helpers::Constants::DECISION_NOTIFICATION_TYPES['ALL_FEATURE_VARIABLES'], user_id, (attributes || {}),
feature_key: feature_flag_key,
feature_enabled: feature_enabled,
source: source_string,
variable_values: all_variables,
source_info: source_info || {}
)
all_variables
end
# Get the Integer value of the specified variable in the feature flag.
#
# @param feature_flag_key - String key of feature flag the variable belongs to
# @param variable_key - String key of variable for which we are getting the string value
# @param user_id - String user ID
# @param attributes - Hash representing visitor attributes and values which need to be recorded.
#
# @return [Integer] variable value.
# @return [nil] if the feature flag or variable are not found.
def get_feature_variable_integer(feature_flag_key, variable_key, user_id, attributes = nil)
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_feature_variable_integer').message)
return nil
end
get_feature_variable_for_type(
feature_flag_key,
variable_key,
Optimizely::Helpers::Constants::VARIABLE_TYPES['INTEGER'],
user_id,
attributes
)
end
def is_valid
config = project_config
config.is_a?(Optimizely::ProjectConfig)
end
def close
return if @stopped
@stopped = true
@config_manager.stop! if @config_manager.respond_to?(:stop!)
@event_processor.stop! if @event_processor.respond_to?(:stop!)
@odp_manager.stop!
end
def get_optimizely_config
# Get OptimizelyConfig object containing experiments and features data
# Returns Object
#
# OptimizelyConfig Object Schema
# {
# 'experimentsMap' => {
# 'my-fist-experiment' => {
# 'id' => '111111',
# 'key' => 'my-fist-experiment'
# 'variationsMap' => {
# 'variation_1' => {
# 'id' => '121212',
# 'key' => 'variation_1',
# 'variablesMap' => {
# 'age' => {
# 'id' => '222222',
# 'key' => 'age',
# 'type' => 'integer',
# 'value' => '0',
# }
# }
# }
# }
# }
# },
# 'featuresMap' => {
# 'awesome-feature' => {
# 'id' => '333333',
# 'key' => 'awesome-feature',
# 'experimentsMap' => Object,
# 'variablesMap' => Object,
# }
# },
# 'revision' => '13',
# }
#
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('get_optimizely_config').message)
return nil
end
# config_manager might not contain optimizely_config if its supplied by the consumer
# Generating a new OptimizelyConfig object in this case as a fallback
if @config_manager.respond_to?(:optimizely_config)
@config_manager.optimizely_config
else
OptimizelyConfig.new(project_config, @logger).config
end
end
# Send an event to the ODP server.
#
# @param action - the event action name. Cannot be nil or empty string.
# @param identifiers - a hash for identifiers. The caller must provide at least one key-value pair.
# @param type - the event type (default = "fullstack").
# @param data - a hash for associated data. The default event data will be added to this data before sending to the ODP server.
def send_odp_event(action:, identifiers:, type: Helpers::Constants::ODP_MANAGER_CONFIG[:EVENT_TYPE], data: {})
unless identifiers.is_a?(Hash) && !identifiers.empty?
@logger.log(Logger::ERROR, 'ODP events must have at least one key-value pair in identifiers.')
return
end
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('send_odp_event').message)
return
end
if action.nil? || action.empty?
@logger.log(Logger::ERROR, Helpers::Constants::ODP_LOGS[:ODP_INVALID_ACTION])
return
end
type = Helpers::Constants::ODP_MANAGER_CONFIG[:EVENT_TYPE] if type.nil? || type.empty?
@odp_manager.send_event(type: type, action: action, identifiers: identifiers, data: data)
end
def identify_user(user_id:)
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('identify_user').message)
return
end
@odp_manager.identify_user(user_id: user_id)
end
def fetch_qualified_segments(user_id:, options: [])
unless is_valid
@logger.log(Logger::ERROR, InvalidProjectConfigError.new('fetch_qualified_segments').message)
return
end
@odp_manager.fetch_qualified_segments(user_id: user_id, options: options)
end
private
def get_variation_with_config(experiment_key, user_id, attributes, config)
# Gets variation where visitor will be bucketed.
#
# experiment_key - Experiment for which visitor variation needs to be determined.
# user_id - String ID for user.
# attributes - Hash representing user attributes.
# config - Instance of DatfileProjectConfig
#
# Returns [variation key] where visitor will be bucketed.
# Returns [nil] if experiment is not Running, if user is not in experiment, or if datafile is invalid.
experiment = config.get_experiment_from_key(experiment_key)
return nil if experiment.nil?
experiment_id = experiment['id']
return nil unless user_inputs_valid?(attributes)
user_context = OptimizelyUserContext.new(self, user_id, attributes, identify: false)
variation_id, = @decision_service.get_variation(config, experiment_id, user_context)
variation = config.get_variation_from_id(experiment_key, variation_id) unless variation_id.nil?
variation_key = variation['key'] if variation
decision_notification_type = if config.feature_experiment?(experiment_id)
Helpers::Constants::DECISION_NOTIFICATION_TYPES['FEATURE_TEST']
else
Helpers::Constants::DECISION_NOTIFICATION_TYPES['AB_TEST']
end
@notification_center.send_notifications(
NotificationCenter::NOTIFICATION_TYPES[:DECISION],
decision_notification_type, user_id, (attributes || {}),
experiment_key: experiment_key,
variation_key: variation_key
)
variation_key
end
def get_feature_variable_for_type(feature_flag_key, variable_key, variable_type, user_id, attributes = nil)
# Get the variable value for the given feature variable and cast it to the specified type
# The default value is returned if the feature flag is not enabled for the user.
#
# feature_flag_key - String key of feature flag the variable belongs to
# variable_key - String key of variable for which we are getting the string value
# variable_type - String requested type for feature variable
# user_id - String user ID
# attributes - Hash representing visitor attributes and values which need to be recorded.
#
# Returns the type-casted variable value.
# Returns nil if the feature flag or variable or user ID is empty
# in case of variable type mismatch
return nil unless Optimizely::Helpers::Validator.inputs_valid?(
{
feature_flag_key: feature_flag_key,
variable_key: variable_key,
user_id: user_id,
variable_type: variable_type
},