optimizely-sdk 5.1.0 → 5.2.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 79f6fce62ba26147eef50a92fefb2cb443df50b2b3a0f4c15f75352f4052aaa8
4
- data.tar.gz: d09bfd23ad927fa5ae62c03467647c65bc21ac68d19d88dc81ef6dea441a25bf
3
+ metadata.gz: f3e60440f1cc553ee8c1eac5ffc7657b6f4de011a4d53a31674c0f5f68843b68
4
+ data.tar.gz: 2e9f30000ddabe5118f32d4afda400f02db039b0e1e8ffca23d0bd96439ef71c
5
5
  SHA512:
6
- metadata.gz: 74e1e587ffdcadfcbbea0677d0de60376e7f677a8254d1e121d37994301c5ebd1959e21ff7bfea1493a441835a20e135dc4d4a4f1577939772b6e167d35f2789
7
- data.tar.gz: 57c17f7508daeaed88755b9dc4463f019fb5b5a523c32cf5639375c06a07dd563786001282e59496d5e8c149c5d884ea5c16522d52edef03c40a0b9ff1890879
6
+ metadata.gz: b563647ea0496d3c1b65d478c00918729e95b32b74e1260c34b92c2115d791101bfa0f22450b92185172773a8c16ae2cb36854f69792652da259b99499f28acd
7
+ data.tar.gz: '038f0fd4bf0280b7d68a33bf7b0bb27f3efe482ef94995bb53751966e9fa7c4b3229fb62a513c2b88458557280b27e339a3222a459649d8b91e837e3e13adb00'
@@ -49,7 +49,7 @@ module Optimizely
49
49
  logger.log(Logger::DEBUG, message)
50
50
 
51
51
  # Return true if there are no audiences
52
- if audience_conditions.empty?
52
+ if audience_conditions.nil? || audience_conditions.empty?
53
53
  message = format(logs_hash['AUDIENCE_EVALUATION_RESULT_COMBINED'], logging_key, 'TRUE')
54
54
  logger.log(Logger::INFO, message)
55
55
  decide_reasons.push(message)
@@ -72,6 +72,20 @@ module Optimizely
72
72
  decide_reasons.push(message)
73
73
 
74
74
  audience_conditions = JSON.parse(audience_conditions) if audience_conditions.is_a?(String)
75
+ # Convert all symbol keys to string keys in the parsed conditions
76
+ stringify_keys = lambda do |obj|
77
+ case obj
78
+ when Hash
79
+ obj.transform_keys(&:to_s).transform_values { |v| stringify_keys.call(v) }
80
+ when Array
81
+ obj.map { |item| stringify_keys.call(item) }
82
+ else
83
+ obj
84
+ end
85
+ end
86
+
87
+ audience_conditions = stringify_keys.call(audience_conditions)
88
+
75
89
  result = ConditionTreeEvaluator.evaluate(audience_conditions, evaluate_user_conditions)
76
90
  result_str = result.nil? ? 'UNKNOWN' : result.to_s.upcase
77
91
  message = format(logs_hash['AUDIENCE_EVALUATION_RESULT'], audience_id, result_str)
@@ -44,6 +44,31 @@ module Optimizely
44
44
  # user_id - String ID for user.
45
45
  #
46
46
  # Returns variation in which visitor with ID user_id has been placed. Nil if no variation.
47
+
48
+ if experiment.nil? || experiment['key'].to_s.strip.empty?
49
+ message = 'Invalid entity key provided for bucketing. Returning nil.'
50
+ @logger.log(Logger::DEBUG, message)
51
+ return nil, []
52
+ end
53
+
54
+ variation_id, decide_reasons = bucket_to_entity_id(project_config, experiment, bucketing_id, user_id)
55
+ if variation_id && variation_id != ''
56
+ experiment_id = experiment['id']
57
+ variation = project_config.get_variation_from_id_by_experiment_id(experiment_id, variation_id)
58
+ return variation, decide_reasons
59
+ end
60
+
61
+ # Handle the case when the traffic range is empty due to sticky bucketing
62
+ if variation_id == ''
63
+ message = 'Bucketed into an empty traffic range. Returning nil.'
64
+ @logger.log(Logger::DEBUG, message)
65
+ decide_reasons.push(message)
66
+ end
67
+
68
+ [nil, decide_reasons]
69
+ end
70
+
71
+ def bucket_to_entity_id(project_config, experiment, bucketing_id, user_id)
47
72
  return nil, [] if experiment.nil?
48
73
 
49
74
  decide_reasons = []
@@ -84,22 +109,18 @@ module Optimizely
84
109
  end
85
110
 
86
111
  traffic_allocations = experiment['trafficAllocation']
112
+ if experiment['cmab']
113
+ traffic_allocations = [
114
+ {
115
+ 'entityId' => '$',
116
+ 'endOfRange' => experiment['cmab']['trafficAllocation']
117
+ }
118
+ ]
119
+ end
87
120
  variation_id, find_bucket_reasons = find_bucket(bucketing_id, user_id, experiment_id, traffic_allocations)
88
121
  decide_reasons.push(*find_bucket_reasons)
89
122
 
90
- if variation_id && variation_id != ''
91
- variation = project_config.get_variation_from_id_by_experiment_id(experiment_id, variation_id)
92
- return variation, decide_reasons
93
- end
94
-
95
- # Handle the case when the traffic range is empty due to sticky bucketing
96
- if variation_id == ''
97
- message = 'Bucketed into an empty traffic range. Returning nil.'
98
- @logger.log(Logger::DEBUG, message)
99
- decide_reasons.push(message)
100
- end
101
-
102
- [nil, decide_reasons]
123
+ [variation_id, decide_reasons]
103
124
  end
104
125
 
105
126
  def find_bucket(bucketing_id, user_id, parent_id, traffic_allocations)
@@ -0,0 +1,230 @@
1
+ # frozen_string_literal: true
2
+
3
+ #
4
+ # Copyright 2025 Optimizely and contributors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+ require 'optimizely/helpers/http_utils'
19
+ require 'optimizely/helpers/constants'
20
+
21
+ module Optimizely
22
+ # Default constants for CMAB requests
23
+ DEFAULT_MAX_RETRIES = 1
24
+ DEFAULT_INITIAL_BACKOFF = 0.1 # in seconds (100 ms)
25
+ DEFAULT_MAX_BACKOFF = 10 # in seconds
26
+ DEFAULT_BACKOFF_MULTIPLIER = 2.0
27
+ MAX_WAIT_TIME = 10
28
+
29
+ class CmabRetryConfig
30
+ # Configuration for retrying CMAB requests.
31
+ # Contains parameters for maximum retries, backoff intervals, and multipliers.
32
+ attr_reader :max_retries, :initial_backoff, :max_backoff, :backoff_multiplier
33
+
34
+ def initialize(max_retries: DEFAULT_MAX_RETRIES, initial_backoff: DEFAULT_INITIAL_BACKOFF, max_backoff: DEFAULT_MAX_BACKOFF, backoff_multiplier: DEFAULT_BACKOFF_MULTIPLIER)
35
+ @max_retries = max_retries
36
+ @initial_backoff = initial_backoff
37
+ @max_backoff = max_backoff
38
+ @backoff_multiplier = backoff_multiplier
39
+ end
40
+ end
41
+
42
+ class DefaultCmabClient
43
+ # Client for interacting with the CMAB service.
44
+ # Provides methods to fetch decisions with optional retry logic.
45
+
46
+ def initialize(http_client: nil, retry_config: nil, logger: nil, prediction_endpoint: nil)
47
+ # Initialize the CMAB client.
48
+ # Args:
49
+ # http_client: HTTP client for making requests.
50
+ # retry_config: Configuration for retry settings.
51
+ # logger: Logger for logging errors and info.
52
+ # prediction_endpoint: Custom prediction endpoint URL template.
53
+ # Use #{rule_id} as placeholder for rule_id.
54
+ @http_client = http_client || DefaultHttpClient.new
55
+ @retry_config = retry_config || CmabRetryConfig.new
56
+ @logger = logger || NoOpLogger.new
57
+ @prediction_endpoint = if prediction_endpoint.to_s.strip.empty?
58
+ 'https://prediction.cmab.optimizely.com/predict/%s'
59
+ else
60
+ prediction_endpoint
61
+ end
62
+ end
63
+
64
+ def fetch_decision(rule_id, user_id, attributes, cmab_uuid, timeout: MAX_WAIT_TIME)
65
+ # Fetches a decision from the CMAB service.
66
+ # Args:
67
+ # rule_id: The rule ID for the experiment.
68
+ # user_id: The user ID for the request.
69
+ # attributes: User attributes for the request.
70
+ # cmab_uuid: Unique identifier for the CMAB request.
71
+ # timeout: Maximum wait time for the request to respond in seconds. (default is 10 seconds).
72
+ # Returns:
73
+ # The variation ID.
74
+ url = format(@prediction_endpoint, rule_id)
75
+ cmab_attributes = attributes.map { |key, value| {'id' => key.to_s, 'value' => value, 'type' => 'custom_attribute'} }
76
+
77
+ request_body = {
78
+ instances: [{
79
+ visitorId: user_id,
80
+ experimentId: rule_id,
81
+ attributes: cmab_attributes,
82
+ cmabUUID: cmab_uuid
83
+ }]
84
+ }
85
+
86
+ if @retry_config && @retry_config.max_retries.to_i.positive?
87
+ _do_fetch_with_retry(url, request_body, @retry_config, timeout)
88
+ else
89
+ _do_fetch(url, request_body, timeout)
90
+ end
91
+ end
92
+
93
+ def _do_fetch(url, request_body, timeout)
94
+ # Perform a single fetch request to the CMAB prediction service.
95
+
96
+ # Args:
97
+ # url: The endpoint URL.
98
+ # request_body: The request payload.
99
+ # timeout: Maximum wait time for the request to respond in seconds.
100
+ # Returns:
101
+ # The variation ID from the response.
102
+
103
+ headers = {'Content-Type' => 'application/json'}
104
+ begin
105
+ response = @http_client.post(url, json: request_body, headers: headers, timeout: timeout.to_i)
106
+ rescue StandardError => e
107
+ error_message = Optimizely::Helpers::Constants::CMAB_FETCH_FAILED % e.message
108
+ @logger.log(Logger::ERROR, error_message)
109
+ raise CmabFetchError, error_message
110
+ end
111
+
112
+ unless (200..299).include?(response.status_code)
113
+ error_message = Optimizely::Helpers::Constants::CMAB_FETCH_FAILED % response.status_code
114
+ @logger.log(Logger::ERROR, error_message)
115
+ raise CmabFetchError, error_message
116
+ end
117
+
118
+ begin
119
+ body = response.json
120
+ rescue JSON::ParserError, Optimizely::CmabInvalidResponseError
121
+ error_message = Optimizely::Helpers::Constants::INVALID_CMAB_FETCH_RESPONSE
122
+ @logger.log(Logger::ERROR, error_message)
123
+ raise CmabInvalidResponseError, error_message
124
+ end
125
+
126
+ unless validate_response(body)
127
+ error_message = Optimizely::Helpers::Constants::INVALID_CMAB_FETCH_RESPONSE
128
+ @logger.log(Logger::ERROR, error_message)
129
+ raise CmabInvalidResponseError, error_message
130
+ end
131
+
132
+ body['predictions'][0]['variation_id']
133
+ end
134
+
135
+ def validate_response(body)
136
+ # Validate the response structure from the CMAB service.
137
+ # Args:
138
+ # body: The JSON response body to validate.
139
+ # Returns:
140
+ # true if valid, false otherwise.
141
+
142
+ body.is_a?(Hash) &&
143
+ body.key?('predictions') &&
144
+ body['predictions'].is_a?(Array) &&
145
+ !body['predictions'].empty? &&
146
+ body['predictions'][0].is_a?(Hash) &&
147
+ body['predictions'][0].key?('variation_id')
148
+ end
149
+
150
+ def _do_fetch_with_retry(url, request_body, retry_config, timeout)
151
+ # Perform a fetch request with retry logic.
152
+ # Args:
153
+ # url: The endpoint URL.
154
+ # request_body: The request payload.
155
+ # retry_config: Configuration for retry settings.
156
+ # timeout: Maximum wait time for the request to respond in seconds.
157
+ # Returns:
158
+ # The variation ID from the response.
159
+
160
+ backoff = retry_config.initial_backoff
161
+
162
+ (0..retry_config.max_retries).each do |attempt|
163
+ variation_id = _do_fetch(url, request_body, timeout)
164
+ return variation_id
165
+ rescue StandardError => e
166
+ if attempt < retry_config.max_retries
167
+ @logger.log(Logger::INFO, "Retrying CMAB request (attempt #{attempt + 1}) after #{backoff} seconds...")
168
+ Kernel.sleep(backoff)
169
+
170
+ backoff = [
171
+ backoff * retry_config.backoff_multiplier,
172
+ retry_config.max_backoff
173
+ ].min
174
+ else
175
+ @logger.log(Logger::ERROR, "Max retries exceeded for CMAB request: #{e.message}")
176
+ raise Optimizely::CmabFetchError, "CMAB decision fetch failed (#{e.message})."
177
+ end
178
+ end
179
+ end
180
+ end
181
+
182
+ class DefaultHttpClient
183
+ # Default HTTP client for making requests.
184
+ # Uses Optimizely::Helpers::HttpUtils to make requests.
185
+
186
+ def post(url, json: nil, headers: {}, timeout: nil)
187
+ # Makes a POST request to the specified URL with JSON body and headers.
188
+ # Args:
189
+ # url: The endpoint URL.
190
+ # json: The JSON payload to send in the request body.
191
+ # headers: Additional headers for the request.
192
+ # timeout: Maximum wait time for the request to respond in seconds.
193
+ # Returns:
194
+ # The response object.
195
+
196
+ response = Optimizely::Helpers::HttpUtils.make_request(url, :post, json.to_json, headers, timeout)
197
+
198
+ HttpResponseAdapter.new(response)
199
+ end
200
+
201
+ class HttpResponseAdapter
202
+ # Adapter for HTTP response to provide a consistent interface.
203
+ # Args:
204
+ # response: The raw HTTP response object.
205
+
206
+ def initialize(response)
207
+ @response = response
208
+ end
209
+
210
+ def status_code
211
+ @response.code.to_i
212
+ end
213
+
214
+ def json
215
+ JSON.parse(@response.body)
216
+ rescue JSON::ParserError
217
+ raise Optimizely::CmabInvalidResponseError, Optimizely::Helpers::Constants::INVALID_CMAB_FETCH_RESPONSE
218
+ end
219
+
220
+ def body
221
+ @response.body
222
+ end
223
+ end
224
+ end
225
+
226
+ class NoOpLogger
227
+ # A no-operation logger that does nothing.
228
+ def log(_level, _message); end
229
+ end
230
+ end
@@ -0,0 +1,218 @@
1
+ # frozen_string_literal: true
2
+
3
+ #
4
+ # Copyright 2025 Optimizely and contributors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+ require 'optimizely/odp/lru_cache'
19
+ require 'optimizely/decide/optimizely_decide_option'
20
+ require 'optimizely/logger'
21
+ require 'digest'
22
+ require 'json'
23
+ require 'securerandom'
24
+ require 'murmurhash3'
25
+
26
+ module Optimizely
27
+ CmabDecision = Struct.new(:variation_id, :cmab_uuid, keyword_init: true)
28
+ CmabCacheValue = Struct.new(:attributes_hash, :variation_id, :cmab_uuid, keyword_init: true)
29
+
30
+ class DefaultCmabCacheOptions
31
+ # CMAB Constants
32
+ DEFAULT_CMAB_CACHE_TIMEOUT = (30 * 60) # in seconds
33
+ DEFAULT_CMAB_CACHE_SIZE = 10_000
34
+ end
35
+
36
+ # Default CMAB service implementation
37
+ class DefaultCmabService
38
+ # Initializes a new instance of the CmabService.
39
+ #
40
+ # @param cmab_cache [LRUCache] The cache object used for storing CMAB data. Must be an instance of LRUCache.
41
+ # @param cmab_client [DefaultCmabClient] The client used to interact with the CMAB service. Must be an instance of DefaultCmabClient.
42
+ # @param logger [Logger, nil] Optional logger for logging messages. Defaults to nil.
43
+ #
44
+ # @raise [ArgumentError] If cmab_cache is not an instance of LRUCache.
45
+ # @raise [ArgumentError] If cmab_client is not an instance of DefaultCmabClient.
46
+
47
+ NUM_LOCK_STRIPES = 1000
48
+
49
+ def initialize(cmab_cache, cmab_client, logger = nil)
50
+ @cmab_cache = cmab_cache
51
+ @cmab_client = cmab_client
52
+ @logger = logger || NoOpLogger.new
53
+ @locks = Array.new(NUM_LOCK_STRIPES) { Mutex.new }
54
+ end
55
+
56
+ def get_decision(project_config, user_context, rule_id, options)
57
+ lock_index = get_lock_index(user_context.user_id, rule_id)
58
+
59
+ @locks[lock_index].synchronize do
60
+ get_decision_impl(project_config, user_context, rule_id, options)
61
+ end
62
+ end
63
+
64
+ private
65
+
66
+ def get_lock_index(user_id, rule_id)
67
+ # Create a hash of user_id + rule_id for consistent lock selection
68
+ hash_input = "#{user_id}#{rule_id}"
69
+ hash_value = MurmurHash3::V32.str_hash(hash_input, 1) & 0xFFFFFFFF # Convert to unsigned 32-bit equivalent
70
+ hash_value % NUM_LOCK_STRIPES
71
+ end
72
+
73
+ def get_decision_impl(project_config, user_context, rule_id, options)
74
+ # Retrieves a decision for a given user and rule, utilizing a cache for efficiency.
75
+ #
76
+ # This method filters user attributes, checks for various cache-related options,
77
+ # and either fetches a fresh decision or returns a cached one if appropriate.
78
+ # It supports options to ignore the cache, reset the cache, or invalidate a specific user's cache entry.
79
+ #
80
+ # @param project_config [Object] The project configuration object.
81
+ # @param user_context [Object] The user context containing user_id and attributes.
82
+ # @param rule_id [String] The identifier for the decision rule.
83
+ # @param options [Array<Symbol>, nil] Optional flags to control cache behavior. Supported options:
84
+ # - OptimizelyDecideOption::IGNORE_CMAB_CACHE: Bypass cache and fetch a new decision.
85
+ # - OptimizelyDecideOption::RESET_CMAB_CACHE: Reset the entire cache.
86
+ # - OptimizelyDecideOption::INVALIDATE_USER_CMAB_CACHE: Invalidate cache for the specific user and rule.
87
+ #
88
+ # @return [CmabDecision] The decision object containing variation_id and cmab_uuid.
89
+
90
+ filtered_attributes = filter_attributes(project_config, user_context, rule_id)
91
+ reasons = []
92
+
93
+ if options&.include?(Decide::OptimizelyDecideOption::IGNORE_CMAB_CACHE)
94
+ reason = "Ignoring CMAB cache for user '#{user_context.user_id}' and rule '#{rule_id}'"
95
+ @logger.log(Logger::DEBUG, reason)
96
+ reasons << reason
97
+ cmab_decision = fetch_decision(rule_id, user_context.user_id, filtered_attributes)
98
+ return [cmab_decision, reasons]
99
+ end
100
+
101
+ if options&.include?(Decide::OptimizelyDecideOption::RESET_CMAB_CACHE)
102
+ reason = "Resetting CMAB cache for user '#{user_context.user_id}' and rule '#{rule_id}'"
103
+ @logger.log(Logger::DEBUG, reason)
104
+ reasons << reason
105
+ @cmab_cache.reset
106
+ end
107
+
108
+ cache_key = get_cache_key(user_context.user_id, rule_id)
109
+
110
+ if options&.include?(Decide::OptimizelyDecideOption::INVALIDATE_USER_CMAB_CACHE)
111
+ reason = "Invalidating CMAB cache for user '#{user_context.user_id}' and rule '#{rule_id}'"
112
+ @logger.log(Logger::DEBUG, reason)
113
+ reasons << reason
114
+ @cmab_cache.remove(cache_key)
115
+ end
116
+
117
+ cached_value = @cmab_cache.lookup(cache_key)
118
+ attributes_hash = hash_attributes(filtered_attributes)
119
+
120
+ if cached_value
121
+ if cached_value.attributes_hash == attributes_hash
122
+ reason = "CMAB cache hit for user '#{user_context.user_id}' and rule '#{rule_id}'"
123
+ @logger.log(Logger::DEBUG, reason)
124
+ reasons << reason
125
+ return [CmabDecision.new(variation_id: cached_value.variation_id, cmab_uuid: cached_value.cmab_uuid), reasons]
126
+ else
127
+ reason = "CMAB cache attributes mismatch for user '#{user_context.user_id}' and rule '#{rule_id}', fetching new decision."
128
+ @logger.log(Logger::DEBUG, reason)
129
+ reasons << reason
130
+ @cmab_cache.remove(cache_key)
131
+ end
132
+ else
133
+ reason = "CMAB cache miss for user '#{user_context.user_id}' and rule '#{rule_id}'"
134
+ @logger.log(Logger::DEBUG, reason)
135
+ reasons << reason
136
+ end
137
+
138
+ cmab_decision = fetch_decision(rule_id, user_context.user_id, filtered_attributes)
139
+ reason = "CMAB decision is #{cmab_decision.to_h}"
140
+ @logger.log(Logger::DEBUG, reason)
141
+ reasons << reason
142
+
143
+ @cmab_cache.save(cache_key,
144
+ CmabCacheValue.new(
145
+ attributes_hash: attributes_hash,
146
+ variation_id: cmab_decision.variation_id,
147
+ cmab_uuid: cmab_decision.cmab_uuid
148
+ ))
149
+ [cmab_decision, reasons]
150
+ end
151
+
152
+ def fetch_decision(rule_id, user_id, attributes)
153
+ # Fetches a decision for a given rule and user, along with user attributes.
154
+ #
155
+ # Generates a unique UUID for the decision request, then delegates to the CMAB client
156
+ # to fetch the variation ID. Returns a CmabDecision object containing the variation ID
157
+ # and the generated UUID.
158
+ #
159
+ # @param rule_id [String] The identifier for the rule to evaluate.
160
+ # @param user_id [String] The identifier for the user.
161
+ # @param attributes [Hash] A hash of user attributes to be used in decision making.
162
+ # @return [CmabDecision] The decision object containing the variation ID and UUID.
163
+ cmab_uuid = SecureRandom.uuid
164
+ variation_id = @cmab_client.fetch_decision(rule_id, user_id, attributes, cmab_uuid)
165
+ CmabDecision.new(variation_id: variation_id, cmab_uuid: cmab_uuid)
166
+ end
167
+
168
+ def filter_attributes(project_config, user_context, rule_id)
169
+ # Filters the user attributes based on the CMAB attribute IDs defined in the experiment.
170
+ #
171
+ # @param project_config [Object] The project configuration object containing experiment and attribute mappings.
172
+ # @param user_context [Object] The user context object containing user attributes.
173
+ # @param rule_id [String] The ID of the experiment (rule) to filter attributes for.
174
+ # @return [Hash] A hash of filtered user attributes whose keys match the CMAB attribute IDs for the given experiment.
175
+ user_attributes = user_context.user_attributes
176
+ filtered_user_attributes = {}
177
+
178
+ experiment = project_config.experiment_id_map[rule_id]
179
+ return filtered_user_attributes if experiment.nil? || experiment['cmab'].nil?
180
+
181
+ cmab_attribute_ids = experiment['cmab']['attributeIds']
182
+ cmab_attribute_ids.each do |attribute_id|
183
+ attribute = project_config.attribute_id_map[attribute_id]
184
+ next unless attribute
185
+
186
+ attribute_key = attribute['key']
187
+ filtered_user_attributes[attribute_key] = user_attributes[attribute_key] if user_attributes.key?(attribute_key)
188
+ end
189
+
190
+ filtered_user_attributes
191
+ end
192
+
193
+ def get_cache_key(user_id, rule_id)
194
+ # Generates a cache key string based on the provided user ID and rule ID.
195
+ #
196
+ # The cache key is constructed in the format: "<user_id_length>-<user_id>-<rule_id>",
197
+ # where <user_id_length> is the length of the user_id string.
198
+ #
199
+ # @param user_id [String] The unique identifier for the user.
200
+ # @param rule_id [String] The unique identifier for the rule.
201
+ # @return [String] The generated cache key.
202
+ "#{user_id.length}-#{user_id}-#{rule_id}"
203
+ end
204
+
205
+ def hash_attributes(attributes)
206
+ # Generates an MD5 hash for a given attributes hash.
207
+ #
208
+ # The method sorts the attributes by key, serializes them to a JSON string,
209
+ # and then computes the MD5 hash of the resulting string. This ensures that
210
+ # the hash is consistent regardless of the original key order in the input hash.
211
+ #
212
+ # @param attributes [Hash] The attributes to be hashed.
213
+ # @return [String] The MD5 hash of the sorted and serialized attributes.
214
+ sorted_attrs = JSON.generate(attributes.sort.to_h)
215
+ Digest::MD5.hexdigest(sorted_attrs)
216
+ end
217
+ end
218
+ end