absmartly-sdk 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop.yml +2 -1
  3. data/CHANGELOG.md +52 -1
  4. data/Gemfile +4 -0
  5. data/Gemfile.lock +5 -1
  6. data/README.md +463 -145
  7. data/lib/a_b_smartly.rb +118 -22
  8. data/lib/absmartly/version.rb +1 -1
  9. data/lib/absmartly.rb +4 -0
  10. data/lib/audience_matcher.rb +93 -1
  11. data/lib/client.rb +44 -12
  12. data/lib/client_config.rb +3 -1
  13. data/lib/context.rb +1288 -236
  14. data/lib/context_data_result.rb +27 -0
  15. data/lib/context_event_logger.rb +3 -0
  16. data/lib/context_event_logger_callback.rb +1 -1
  17. data/lib/context_publisher.rb +9 -0
  18. data/lib/default_audience_deserializer.rb +2 -2
  19. data/lib/default_context_data_deserializer.rb +3 -3
  20. data/lib/default_context_event_serializer.rb +2 -1
  21. data/lib/default_context_publisher.rb +9 -0
  22. data/lib/default_http_client.rb +26 -5
  23. data/lib/default_http_client_config.rb +6 -1
  24. data/lib/default_variable_parser.rb +1 -1
  25. data/lib/hashing.rb +39 -2
  26. data/lib/json/context_data.rb +26 -3
  27. data/lib/json/experiment.rb +36 -10
  28. data/lib/json/exposure.rb +8 -4
  29. data/lib/json_expr/expr_evaluator.rb +7 -9
  30. data/lib/json_expr/json_expr.rb +23 -17
  31. data/lib/json_expr/operators/and_combinator.rb +2 -1
  32. data/lib/json_expr/operators/in_operator.rb +3 -1
  33. data/lib/json_expr/operators/match_operator.rb +9 -5
  34. data/lib/json_expr/operators/or_combinator.rb +4 -2
  35. data/lib/json_expr/operators/semver_operator.rb +17 -0
  36. data/lib/json_expr/operators/semver_operators.rb +50 -0
  37. data/lib/json_expr/semver_comparator.rb +98 -0
  38. data/lib/publish_error.rb +11 -0
  39. data/lib/scheduled_thread_pool_executor.rb +8 -0
  40. data/lib/type_utils.rb +59 -0
  41. data/lib/variant_assigner.rb +1 -1
  42. metadata +10 -4
  43. data/absmartly.gemspec +0 -45
  44. data/example/example.rb +0 -85
data/lib/a_b_smartly.rb CHANGED
@@ -4,10 +4,15 @@ require "time"
4
4
  require_relative "context"
5
5
  require_relative "audience_matcher"
6
6
  require_relative "default_context_data_provider"
7
+ require_relative "default_context_publisher"
8
+ require_relative "context_event_handler"
7
9
  require_relative "default_context_event_handler"
8
10
  require_relative "default_variable_parser"
9
11
  require_relative "default_audience_deserializer"
10
12
  require_relative "scheduled_thread_pool_executor"
13
+ require_relative "client_config"
14
+ require_relative "client"
15
+ require_relative "context_data_result"
11
16
 
12
17
  class ABSmartly
13
18
  attr_accessor :context_data_provider, :context_event_handler,
@@ -18,51 +23,125 @@ class ABSmartly
18
23
  ABSmartly.new(config)
19
24
  end
20
25
 
21
- def initialize(config)
22
- @context_data_provider = config.context_data_provider
23
- @context_event_handler = config.context_event_handler
24
- @context_event_logger = config.context_event_logger
25
- @variable_parser = config.variable_parser
26
- @audience_deserializer = config.audience_deserializer
27
- @scheduler = config.scheduler
26
+ OPTIONS = %i[api_key application environment timeout retries context_event_logger].freeze
27
+
28
+ # Accepts either a config object (ABSmartlyConfig or anything that responds
29
+ # like it) or an endpoint String with keyword options. Options are read from
30
+ # *args rather than keyword parameters so that Ruby 2.7 doesn't splat a
31
+ # config that responds to to_hash into keywords.
32
+ def initialize(*args)
33
+ options = args.size > 1 && args.last.is_a?(Hash) ? args.pop : {}
34
+ options = args.pop if args.size == 1 && args.first.instance_of?(Hash)
35
+ raise ArgumentError.new("wrong number of arguments (given #{args.size}, expected 0..1)") if args.size > 1
36
+
37
+ config_or_endpoint = args.first
38
+ if config_or_endpoint.nil? || config_or_endpoint.is_a?(String)
39
+ unknown = options.keys - OPTIONS
40
+ raise ArgumentError.new("unknown keyword#{'s' if unknown.size > 1}: #{unknown.map(&:inspect).join(', ')}") unless unknown.empty?
41
+
42
+ initialize_from_params(config_or_endpoint, *options.values_at(*OPTIONS))
43
+ else
44
+ initialize_from_config(config_or_endpoint)
45
+ end
46
+ end
47
+
48
+ private
49
+ def initialize_from_config(config)
50
+ @context_data_provider = config.context_data_provider
51
+ @context_event_handler = config.context_event_handler
52
+ @context_event_logger = config.context_event_logger
53
+ @variable_parser = config.variable_parser
54
+ @audience_deserializer = config.audience_deserializer
55
+ @scheduler = config.scheduler
28
56
 
29
- if @context_data_provider.nil? || @context_event_handler.nil?
30
57
  @client = config.client
31
- raise ArgumentError.new("Missing Client instance configuration") if @client.nil?
32
58
 
33
- if @context_data_provider.nil?
34
- @context_data_provider = DefaultContextDataProvider.new(@client)
59
+ if @context_data_provider.nil? || @context_event_handler.nil?
60
+ raise ArgumentError.new("Missing Client instance configuration") if @client.nil?
61
+
62
+ if @context_data_provider.nil?
63
+ @context_data_provider = DefaultContextDataProvider.new(@client)
64
+ end
65
+
66
+ if @context_event_handler.nil?
67
+ @context_event_handler = DefaultContextEventHandler.new(@client)
68
+ end
35
69
  end
36
70
 
37
- if @context_event_handler.nil?
38
- @context_event_handler = DefaultContextEventHandler.new(@client)
71
+ if @variable_parser.nil?
72
+ @variable_parser = DefaultVariableParser.new
39
73
  end
40
- end
41
74
 
42
- if @variable_parser.nil?
43
- @variable_parser = DefaultVariableParser.new
75
+ if @audience_deserializer.nil?
76
+ @audience_deserializer = DefaultAudienceDeserializer.new
77
+ end
78
+ if @scheduler.nil?
79
+ @scheduler = ScheduledThreadPoolExecutor.new(1)
80
+ end
44
81
  end
45
82
 
46
- if @audience_deserializer.nil?
83
+ def initialize_from_params(endpoint, api_key, application, environment, timeout, retries, event_logger)
84
+ raise ArgumentError.new("Missing required parameter: endpoint") if endpoint.nil? || endpoint.to_s.strip.empty?
85
+ raise ArgumentError.new("Missing required parameter: api_key") if api_key.nil? || api_key.to_s.strip.empty?
86
+ raise ArgumentError.new("Missing required parameter: application") if application.nil? || application.to_s.strip.empty?
87
+ raise ArgumentError.new("Missing required parameter: environment") if environment.nil? || environment.to_s.strip.empty?
88
+
89
+ timeout = parse_number(timeout || 3000, "timeout") { |value| Float(value) }
90
+ retries = parse_number(retries || 5, "retries") { |value| value.is_a?(Float) ? Integer(value.to_s) : Integer(value) }
91
+
92
+ raise ArgumentError.new("timeout must be a positive number") if timeout <= 0
93
+ raise ArgumentError.new("retries must be a non-negative number") if retries < 0
94
+
95
+ client_config = ClientConfig.create
96
+ client_config.endpoint = endpoint
97
+ client_config.api_key = api_key
98
+ client_config.application = application
99
+ client_config.environment = environment
100
+ client_config.connect_timeout = timeout / 1000.0
101
+ client_config.connection_request_timeout = timeout / 1000.0
102
+ client_config.max_retries = retries
103
+
104
+ @client = Client.create(client_config)
105
+ @context_data_provider = DefaultContextDataProvider.new(@client)
106
+ @context_event_handler = DefaultContextEventHandler.new(@client)
107
+ @context_event_logger = event_logger
108
+ @variable_parser = DefaultVariableParser.new
47
109
  @audience_deserializer = DefaultAudienceDeserializer.new
48
- end
49
- if @scheduler.nil?
50
110
  @scheduler = ScheduledThreadPoolExecutor.new(1)
51
111
  end
52
- end
112
+
113
+ public
53
114
 
54
115
  def create_context(config)
55
116
  validate_params(config)
56
117
  Context.create(get_utc_format, config, @context_data_provider.context_data,
57
118
  @context_data_provider, @context_event_handler, @context_event_logger, @variable_parser,
58
- AudienceMatcher.new(@audience_deserializer))
119
+ AudienceMatcher.new(@audience_deserializer),
120
+ application: client_application, environment: client_environment)
121
+ end
122
+
123
+ def create_context_async(config)
124
+ validate_params(config)
125
+ context = Context.create_async(get_utc_format, config, @context_data_provider,
126
+ @context_event_handler, @context_event_logger, @variable_parser,
127
+ AudienceMatcher.new(@audience_deserializer),
128
+ application: client_application, environment: client_environment)
129
+ data_provider = @context_data_provider
130
+ Thread.new do
131
+ data_future = data_provider.context_data
132
+ context.set_data(data_future)
133
+ rescue => e
134
+ context.set_data(Absmartly::ContextDataResult.failure(e))
135
+ end
136
+ context
59
137
  end
60
138
 
61
139
  def create_context_with(config, data)
62
140
  validate_params(config)
63
141
  Context.create(get_utc_format, config, data,
64
142
  @context_data_provider, @context_event_handler, @context_event_logger, @variable_parser,
65
- AudienceMatcher.new(@audience_deserializer))
143
+ AudienceMatcher.new(@audience_deserializer),
144
+ application: client_application, environment: client_environment)
66
145
  end
67
146
 
68
147
  def context_data
@@ -74,6 +153,17 @@ class ABSmartly
74
153
  Time.now.utc.iso8601(3)
75
154
  end
76
155
 
156
+ # The application and environment names configured on the client seed the
157
+ # audience evaluation map (the collector adds them server-side for publish).
158
+ # Custom data providers may leave @client nil, so guard the reads.
159
+ def client_application
160
+ @client.application if @client.respond_to?(:application)
161
+ end
162
+
163
+ def client_environment
164
+ @client.environment if @client.respond_to?(:environment)
165
+ end
166
+
77
167
  def validate_params(params)
78
168
  params.units.each do |key, value|
79
169
  unless value.is_a?(String) || value.is_a?(Numeric)
@@ -85,4 +175,10 @@ class ABSmartly
85
175
  end
86
176
  end
87
177
  end
178
+
179
+ def parse_number(value, name)
180
+ yield value
181
+ rescue ArgumentError, TypeError
182
+ raise ArgumentError.new("#{name} must be a number")
183
+ end
88
184
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Absmartly
4
- VERSION = "1.3.0"
4
+ VERSION = "1.4.0"
5
5
  end
data/lib/absmartly.rb CHANGED
@@ -32,6 +32,10 @@ module Absmartly
32
32
  sdk.create_context(context_config)
33
33
  end
34
34
 
35
+ def create_context_async(context_config)
36
+ sdk.create_context_async(context_config)
37
+ end
38
+
35
39
  def create_context_with(context_config, data)
36
40
  sdk.create_context_with(context_config, data)
37
41
  end
@@ -6,6 +6,17 @@ require_relative "json_expr/json_expr"
6
6
  class AudienceMatcher
7
7
  attr_accessor :deserializer, :json_expr
8
8
 
9
+ SPLIT_PERCENTAGES_SUM_TOLERANCE = 0.01
10
+ # The longest decimal prefix JavaScript's parseFloat accepts, after the
11
+ # ECMAScript white space and line terminators (U+FEFF included, U+0085 not).
12
+ FLOAT_PREFIX = /\A[\t\n\v\f\r\u2028\u2029\uFEFF\p{Zs}]*([+-]?(?:Infinity|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?))/.freeze
13
+
14
+ RuleAction = Struct.new(:variant, :split) do
15
+ def split?
16
+ !split.nil?
17
+ end
18
+ end
19
+
9
20
  def initialize(deserializer)
10
21
  @deserializer = deserializer
11
22
  @json_expr = JsonExpr.new
@@ -32,7 +43,88 @@ class AudienceMatcher
32
43
  Result.new(@json_expr.evaluate_boolean_expr(filter, attributes))
33
44
  end
34
45
  end
35
- rescue
46
+ rescue StandardError
47
+ nil
48
+ end
49
+
50
+ def parse_rules(assignment_rules)
51
+ return nil unless assignment_rules.is_a?(String)
52
+
53
+ parsed = JSON.parse(assignment_rules)
54
+ rules = parsed["rules"] if parsed.is_a?(Hash)
55
+ rules.is_a?(Array) ? rules : nil
56
+ rescue JSON::ParserError
57
+ nil
58
+ end
59
+
60
+ def evaluate_rules(assignment_rules, environment, attributes)
61
+ rules = parse_rules(assignment_rules)
62
+ rules.nil? ? nil : evaluate_parsed_rules(rules, environment, attributes)
63
+ end
64
+
65
+ def evaluate_parsed_rules(rules, environment, attributes)
66
+ rules.each do |rule|
67
+ next unless rule.is_a?(Hash)
68
+
69
+ action = parse_rule_action(rule)
70
+ next if action.nil?
71
+
72
+ environments = rule["environments"]
73
+ unless environments.nil?
74
+ next unless environments.is_a?(Array)
75
+ next if !environments.empty? && (environment.nil? || !environments.include?(environment))
76
+ end
77
+
78
+ conditions = rule["conditions"]
79
+ return action if conditions.nil?
80
+ next unless conditions.is_a?(Hash)
81
+
82
+ begin
83
+ return action if @json_expr.evaluate_boolean_expr(conditions, attributes) == true
84
+ rescue StandardError, SystemStackError
85
+ next
86
+ end
87
+ end
36
88
  nil
37
89
  end
90
+
91
+ private
92
+ def parse_rule_action(rule)
93
+ case rule["type"]
94
+ when "assign"
95
+ variant = rule["variant"]
96
+ integer = variant.is_a?(Integer) || (variant.is_a?(Float) && variant.finite? && variant == variant.floor)
97
+ integer ? RuleAction.new(variant.to_i, nil) : nil
98
+ when "split"
99
+ split = parse_split_percentages(rule["percentages"])
100
+ split.nil? ? nil : RuleAction.new(nil, split)
101
+ end
102
+ end
103
+
104
+ def parse_split_percentages(percentages)
105
+ return nil unless percentages.is_a?(String)
106
+
107
+ values = percentages.split("/", -1).map { |value| parse_float(value) }
108
+ return nil if values.any? { |value| value.nil? || value.negative? }
109
+
110
+ gap = (100 - values.sum).abs
111
+ return nil unless gap.finite? && round_half_up(gap, 2) <= SPLIT_PERCENTAGES_SUM_TOLERANCE
112
+
113
+ values.map { |value| value / 100 }
114
+ end
115
+
116
+ def parse_float(value)
117
+ match = FLOAT_PREFIX.match(value)
118
+ return nil if match.nil?
119
+
120
+ text = match[1]
121
+ return text.start_with?("-") ? -Float::INFINITY : Float::INFINITY if text.end_with?("Infinity")
122
+
123
+ Float(text.sub(/\.(?=\z|[eE])/, ""))
124
+ end
125
+
126
+ # Like JavaScript's toFixed: rounds the exact binary value half up.
127
+ def round_half_up(value, digits)
128
+ value.to_r.round(digits, half: :up).to_f
129
+ end
38
130
  end
data/lib/client.rb CHANGED
@@ -1,12 +1,15 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "absmartly/version"
3
4
  require_relative "default_http_client"
4
5
  require_relative "default_context_data_deserializer"
5
6
  require_relative "default_context_event_serializer"
7
+ require_relative "context_data_result"
8
+ require_relative "publish_error"
6
9
 
7
10
  class Client
8
11
  attr_accessor :url, :query, :headers, :http_client, :executor, :deserializer, :serializer
9
- attr_reader :data_future, :promise, :exception
12
+ attr_reader :data_future, :promise, :exception, :application, :environment
10
13
 
11
14
  def self.create(config, http_client = nil)
12
15
  Client.new(config, http_client || DefaultHttpClient.create(config.http_client_config))
@@ -27,6 +30,8 @@ class Client
27
30
 
28
31
  @url = "#{endpoint}/context"
29
32
  @http_client = http_client
33
+ @application = application
34
+ @environment = environment
30
35
  @deserializer = config.context_data_deserializer
31
36
  @serializer = config.context_event_serializer
32
37
  @executor = config.executor
@@ -40,7 +45,7 @@ class Client
40
45
  "X-Application": application,
41
46
  "X-Environment": environment,
42
47
  "X-Application-Version": "0",
43
- "X-Agent": "absmartly-ruby-sdk"
48
+ "X-Agent": "absmartly-ruby-sdk/#{Absmartly::VERSION}"
44
49
  }
45
50
 
46
51
  @query = {
@@ -49,22 +54,26 @@ class Client
49
54
  }
50
55
  end
51
56
 
57
+ # Returns a ContextDataResult for this fetch. The data_future, exception
58
+ # and promise readers on the client still mirror the latest fetch.
52
59
  def context_data
53
- @promise = @http_client.get(@url, @query, @headers)
54
- unless @promise.success?
55
- @exception = Exception.new(@promise.body)
56
- return self
57
- end
58
-
59
- content = (@promise.body || {}).to_s
60
- @data_future = @deserializer.deserialize(content, 0, content.size)
61
- self
60
+ result = fetch_context_data
61
+ @promise = result.promise
62
+ @exception = result.exception
63
+ @data_future = result.data_future
64
+ result
62
65
  end
63
66
 
64
67
  def publish(event)
65
68
  content = @serializer.serialize(event)
66
69
  response = @http_client.put(@url, nil, @headers, content)
67
- return Exception.new(response.body) unless response.success?
70
+
71
+ unless response.success?
72
+ # A routine collector rejection must stay catchable with a normal
73
+ # `rescue StandardError` when close/finalize raises it, so use a
74
+ # StandardError subclass rather than Ruby's base Exception.
75
+ return Absmartly::PublishError.new(response.body)
76
+ end
68
77
 
69
78
  response
70
79
  end
@@ -76,4 +85,27 @@ class Client
76
85
  def success?
77
86
  @promise&.success? || false
78
87
  end
88
+
89
+ def inspect
90
+ "#<Client url=#{@url.inspect}>"
91
+ end
92
+
93
+ private
94
+ def fetch_context_data
95
+ begin
96
+ promise = @http_client.get(@url, @query, @headers)
97
+ rescue StandardError => e
98
+ return Absmartly::ContextDataResult.failure(e)
99
+ end
100
+
101
+ unless promise.success?
102
+ return Absmartly::ContextDataResult.failure(Exception.new(promise.body), promise)
103
+ end
104
+
105
+ content = (promise.body || {}).to_s
106
+ data = @deserializer.deserialize(content, 0, content.size)
107
+ return Absmartly::ContextDataResult.failure(StandardError.new("Failed to deserialize context data"), promise) if data.nil?
108
+
109
+ Absmartly::ContextDataResult.new(data, nil, promise)
110
+ end
79
111
  end
data/lib/client_config.rb CHANGED
@@ -5,7 +5,7 @@ require_relative "default_http_client_config"
5
5
  class ClientConfig
6
6
  attr_accessor :endpoint, :api_key, :environment, :application, :deserializer,
7
7
  :serializer, :executor, :connect_timeout, :connection_request_timeout,
8
- :retry_interval, :max_retries
8
+ :retry_interval, :max_retries, :retry_statuses, :retry_connection_failures
9
9
 
10
10
  def self.create
11
11
  ClientConfig.new
@@ -50,6 +50,8 @@ class ClientConfig
50
50
  http_config.connection_request_timeout = @connection_request_timeout unless @connection_request_timeout.nil?
51
51
  http_config.retry_interval = @retry_interval unless @retry_interval.nil?
52
52
  http_config.max_retries = @max_retries unless @max_retries.nil?
53
+ http_config.retry_statuses = @retry_statuses unless @retry_statuses.nil?
54
+ http_config.retry_connection_failures = @retry_connection_failures unless @retry_connection_failures.nil?
53
55
  http_config
54
56
  end
55
57
  end