growthbook 1.2.2 → 2.0.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.
@@ -27,14 +27,20 @@ module Growthbook
27
27
  # @return [Growthbook::InlineExperimentResult, nil]
28
28
  attr_reader :experiment_result
29
29
 
30
+ # The id of the rule (if any) that was used to assign the value
31
+ # @return [String]
32
+ attr_reader :rule_id
33
+
30
34
  def initialize(
31
35
  value,
32
36
  source,
33
37
  experiment,
34
- experiment_result
38
+ experiment_result,
39
+ rule_id = ''
35
40
  )
36
41
 
37
- on = !value.nil? && value != 0 && value != '' && value != false
42
+ # JS truthiness: [], {} and "off" are on
43
+ on = !value.nil? && value != 0 && value != '' && value != false && !(value.is_a?(Float) && value.nan?)
38
44
 
39
45
  @value = value
40
46
  @on = on
@@ -42,6 +48,7 @@ module Growthbook
42
48
  @source = source
43
49
  @experiment = experiment
44
50
  @experiment_result = experiment_result
51
+ @rule_id = rule_id || ''
45
52
  end
46
53
 
47
54
  def to_json(*_args)
@@ -50,6 +57,7 @@ module Growthbook
50
57
  json['off'] = @off
51
58
  json['value'] = @value
52
59
  json['source'] = @source
60
+ json['ruleId'] = @rule_id
53
61
 
54
62
  if @experiment
55
63
  json['experiment'] = @experiment.to_json
@@ -3,6 +3,9 @@
3
3
  module Growthbook
4
4
  # Internal class that overrides the default value of a Feature based on a set of requirements.
5
5
  class FeatureRule
6
+ # @return [String , nil] Unique identifier for this rule
7
+ attr_reader :id
8
+
6
9
  # @return [Hash , nil] Optional targeting condition
7
10
  attr_reader :condition
8
11
 
@@ -54,7 +57,26 @@ module Growthbook
54
57
  # @return [TrackData[] , nil] Array of tracking calls to fire
55
58
  attr_reader :tracks
56
59
 
60
+ # @return [String, nil] The attribute to use when hash_attribute is missing (requires Sticky Bucketing)
61
+ attr_accessor :fallback_attribute
62
+
63
+ # @return [String, nil] When true, disables sticky bucketing
64
+ attr_accessor :disable_sticky_bucketing
65
+
66
+ # @return [integer] Appended to the experiment key for sticky bucketing
67
+ attr_accessor :bucket_version
68
+
69
+ # @return [integer] Minimum bucket version required for sticky bucketing
70
+ attr_accessor :min_bucket_version
71
+
72
+ # @return [Array<Hash>] Array of prerequisite flags
73
+ attr_accessor :parent_conditions
74
+
75
+ # @return [Hash, nil] Arbitrary custom fields attached to the rule
76
+ attr_reader :custom_fields
77
+
57
78
  def initialize(rule)
79
+ @id = get_option(rule, :id)
58
80
  @coverage = get_option(rule, :coverage)
59
81
  @force = get_option(rule, :force)
60
82
  @variations = get_option(rule, :variations)
@@ -74,6 +96,17 @@ module Growthbook
74
96
 
75
97
  cond = get_option(rule, :condition)
76
98
  @condition = Growthbook::Conditions.parse_condition(cond) unless cond.nil?
99
+
100
+ @fallback_attribute = get_option(rule, :fallback_attribute) || get_option(rule, :fallbackAttribute)
101
+ @disable_sticky_bucketing = get_option(rule, :disable_sticky_bucketing, false) || get_option(rule, :disableStickyBucketing, false)
102
+ @bucket_version = get_option(rule, :bucket_version) || get_option(rule, :bucketVersion) || 0
103
+ @min_bucket_version = get_option(rule, :min_bucket_version) || get_option(rule, :minBucketVersion) || 0
104
+ @parent_conditions = get_option(rule, :parent_conditions) || get_option(rule, :parentConditions) || []
105
+ @custom_fields = get_option(rule, :custom_fields) || get_option(rule, :customFields)
106
+
107
+ return unless @disable_sticky_bucketing
108
+
109
+ @fallback_attribute = nil
77
110
  end
78
111
 
79
112
  # @return [Growthbook::InlineExperiment, nil]
@@ -83,6 +116,7 @@ module Growthbook
83
116
  Growthbook::InlineExperiment.new(
84
117
  key: @key || feature_key,
85
118
  variations: @variations,
119
+ condition: @condition,
86
120
  coverage: @coverage,
87
121
  weights: @weights,
88
122
  hash_attribute: @hash_attribute,
@@ -93,7 +127,12 @@ module Growthbook
93
127
  filters: @filters,
94
128
  name: @name,
95
129
  phase: @phase,
96
- seed: @seed
130
+ seed: @seed,
131
+ fallback_attribute: @fallback_attribute,
132
+ disable_sticky_bucketing: @disable_sticky_bucketing,
133
+ bucket_version: @bucket_version,
134
+ min_bucket_version: @min_bucket_version,
135
+ custom_fields: @custom_fields
97
136
  )
98
137
  end
99
138
 
@@ -109,32 +148,37 @@ module Growthbook
109
148
 
110
149
  def to_json(*_args)
111
150
  {
112
- 'condition' => @condition,
113
- 'coverage' => @coverage,
114
- 'force' => @force,
115
- 'variations' => @variations,
116
- 'key' => @key,
117
- 'weights' => @weights,
118
- 'namespace' => @namespace,
119
- 'hashAttribute' => @hash_attribute,
120
- 'range' => @range,
121
- 'ranges' => @ranges,
122
- 'meta' => @meta,
123
- 'filters' => @filters,
124
- 'seed' => @seed,
125
- 'name' => @name,
126
- 'phase' => @phase,
127
- 'tracks' => @tracks
151
+ 'condition' => @condition,
152
+ 'coverage' => @coverage,
153
+ 'force' => @force,
154
+ 'variations' => @variations,
155
+ 'key' => @key,
156
+ 'weights' => @weights,
157
+ 'namespace' => @namespace,
158
+ 'hashAttribute' => @hash_attribute,
159
+ 'range' => @range,
160
+ 'ranges' => @ranges,
161
+ 'meta' => @meta,
162
+ 'filters' => @filters,
163
+ 'seed' => @seed,
164
+ 'name' => @name,
165
+ 'phase' => @phase,
166
+ 'tracks' => @tracks,
167
+ 'fallbackAttribute' => @fallback_attribute,
168
+ 'disableStickyBucketing' => @disable_sticky_bucketing,
169
+ 'bucketVersion' => @bucket_version,
170
+ 'minBucketVersion' => @min_bucket_version,
171
+ 'parentConditions' => @parent_conditions
128
172
  }.compact
129
173
  end
130
174
 
131
175
  private
132
176
 
133
- def get_option(hash, key)
177
+ def get_option(hash, key, default = nil)
134
178
  return hash[key.to_sym] if hash.key?(key.to_sym)
135
179
  return hash[key.to_s] if hash.key?(key.to_s)
136
180
 
137
- nil
181
+ default
138
182
  end
139
183
  end
140
184
  end
@@ -10,11 +10,14 @@ class FNV
10
10
  MOD32 = 4_294_967_296
11
11
  MOD64 = 18_446_744_073_709_551_616
12
12
 
13
+ # Hashes UTF-16 code units, like JavaScript's charCodeAt, so a character
14
+ # above U+FFFF counts as two units
13
15
  def fnv1a_32(data)
14
16
  hash = INIT32
15
17
 
16
- data.bytes.each do |byte|
17
- hash = hash ^ byte
18
+ units = data.ascii_only? ? data.bytes : data.encode('UTF-16LE').unpack('v*').map(&:to_i)
19
+ units.each do |unit|
20
+ hash = hash ^ unit
18
21
  hash = (hash * PRIME32) % MOD32
19
22
  end
20
23
 
@@ -51,12 +51,32 @@ module Growthbook
51
51
  # @return [String, nil] Id of the current experiment phase
52
52
  attr_accessor :phase
53
53
 
54
+ # @return [String, nil] The attribute to use when hash_attribute is missing (requires Sticky Bucketing)
55
+ attr_accessor :fallback_attribute
56
+
57
+ # @return [bool, nil] When true, disables sticky bucketing
58
+ attr_accessor :disable_sticky_bucketing
59
+
60
+ # @return [integer] Appended to the experiment key for sticky bucketing
61
+ attr_accessor :bucket_version
62
+
63
+ # @return [integer] Minimum bucket version required for sticky bucketing
64
+ attr_accessor :min_bucket_version
65
+
66
+ # @return [Array<Hash>] Array of prerequisite flags
67
+ attr_accessor :parent_conditions
68
+
69
+ # @return [Hash, nil] Arbitrary custom fields attached to the experiment
70
+ attr_accessor :custom_fields
71
+
54
72
  def initialize(options = {})
55
73
  @key = get_option(options, :key, '').to_s
56
74
  @variations = get_option(options, :variations, [])
57
75
  @weights = get_option(options, :weights)
58
76
  @active = get_option(options, :active, true)
59
77
  @coverage = get_option(options, :coverage, 1.0)
78
+ # Serialize coverage whenever it was given, even when it's 1 (like the JS SDK)
79
+ @coverage_given = !get_option(options, :coverage).nil?
60
80
  @ranges = get_option(options, :ranges)
61
81
  @condition = get_option(options, :condition)
62
82
  @namespace = get_option(options, :namespace)
@@ -68,6 +88,16 @@ module Growthbook
68
88
  @seed = get_option(options, :seed)
69
89
  @name = get_option(options, :name)
70
90
  @phase = get_option(options, :phase)
91
+ @fallback_attribute = get_option(options, :fallback_attribute) || get_option(options, :fallbackAttribute)
92
+ @disable_sticky_bucketing = get_option(options, :disable_sticky_bucketing, false) || get_option(options, :disableStickyBucketing, false)
93
+ @bucket_version = get_option(options, :bucket_version) || get_option(options, :bucketVersion) || 0
94
+ @min_bucket_version = get_option(options, :min_bucket_version) || get_option(options, :minBucketVersion) || 0
95
+ @parent_conditions = get_option(options, :parent_conditions) || get_option(options, :parentConditions) || []
96
+ @custom_fields = get_option(options, :custom_fields) || get_option(options, :customFields)
97
+
98
+ return unless @disable_sticky_bucketing
99
+
100
+ @fallback_attribute = nil
71
101
  end
72
102
 
73
103
  def to_json(*_args)
@@ -76,7 +106,7 @@ module Growthbook
76
106
  res['variations'] = @variations
77
107
  res['weights'] = @weights unless @weights.nil?
78
108
  res['active'] = @active if @active != true && !@active.nil?
79
- res['coverage'] = @coverage if @coverage != 1 && !@coverage.nil?
109
+ res['coverage'] = @coverage if @coverage_given || (@coverage != 1 && !@coverage.nil?)
80
110
  res['ranges'] = @ranges
81
111
  res['condition'] = @condition
82
112
  res['namespace'] = @namespace
@@ -88,6 +118,12 @@ module Growthbook
88
118
  res['seed'] = @seed
89
119
  res['name'] = @name
90
120
  res['phase'] = @phase
121
+ res['fallbackAttribute'] = @fallback_attribute unless @fallback_attribute.nil?
122
+ res['disableStickyBucketing'] = @disable_sticky_bucketing if @disable_sticky_bucketing
123
+ res['bucketVersion'] = @bucket_version if @bucket_version != 0
124
+ res['minBucketVersion'] = @min_bucket_version if @min_bucket_version != 0
125
+ res['parentConditions'] = @parent_conditions unless @parent_conditions.empty?
126
+
91
127
  res.compact
92
128
  end
93
129
 
@@ -36,6 +36,9 @@ module Growthbook
36
36
  # @return [Boolean] Used for holdout groups
37
37
  attr_accessor :passthrough
38
38
 
39
+ # @return [Boolean] When true, sticky bucketing was used to assign a variation
40
+ attr_accessor :sticky_bucket_used
41
+
39
42
  def initialize(options = {})
40
43
  @key = options[:key]
41
44
  @in_experiment = options[:in_experiment]
@@ -48,6 +51,7 @@ module Growthbook
48
51
  @bucket = options[:bucket]
49
52
  @name = options[:name]
50
53
  @passthrough = options[:passthrough]
54
+ @sticky_bucket_used = options[:sticky_bucket_used]
51
55
  end
52
56
 
53
57
  # If the variation was randomly assigned based on user attribute hashes
@@ -56,6 +60,10 @@ module Growthbook
56
60
  @hash_used
57
61
  end
58
62
 
63
+ def sticky_bucket_used?
64
+ @sticky_bucket_used || false
65
+ end
66
+
59
67
  # Whether or not the user is in the experiment
60
68
  # @return [Bool]
61
69
  def in_experiment?
@@ -64,17 +72,18 @@ module Growthbook
64
72
 
65
73
  def to_json(*_args)
66
74
  {
67
- 'inExperiment' => @in_experiment,
68
- 'variationId' => @variation_id,
69
- 'value' => @value,
70
- 'hashUsed' => @hash_used,
71
- 'hashAttribute' => @hash_attribute,
72
- 'hashValue' => @hash_value,
73
- 'featureId' => @feature_id.to_s,
74
- 'key' => @key.to_s,
75
- 'bucket' => @bucket,
76
- 'name' => @name,
77
- 'passthrough' => @passthrough
75
+ 'inExperiment' => @in_experiment,
76
+ 'variationId' => @variation_id,
77
+ 'value' => @value,
78
+ 'hashUsed' => @hash_used,
79
+ 'hashAttribute' => @hash_attribute,
80
+ 'hashValue' => @hash_value,
81
+ 'featureId' => @feature_id.to_s,
82
+ 'key' => @key.to_s,
83
+ 'bucket' => @bucket,
84
+ 'name' => @name,
85
+ 'passthrough' => @passthrough,
86
+ 'stickyBucketUsed' => @sticky_bucket_used
78
87
  }.compact
79
88
  end
80
89
  end
@@ -0,0 +1,278 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Growthbook
4
+ # internal use only
5
+ # Shrinks a features payload for a user whose attributes are only partly known,
6
+ # e.g. on a server bootstrapping a client SDK. The result evaluates the same as
7
+ # the full payload for anyone who agrees with the known attributes.
8
+ class PayloadReducer
9
+ # @param payload [Hash] A decrypted features payload, as returned by the SDK API
10
+ # @param attributes [Hash] The attributes known for the user
11
+ # @param include [Hash] Keep only what matches every filter: projects, tags, customFields
12
+ # @param exclude [Hash] Drop what matches any filter: projects, tags, customFields
13
+ # @param prerequisites ['keep', 'filter'] With 'keep', prerequisites of kept features
14
+ # and experiments are kept even when the filters drop them
15
+ def initialize(payload, attributes:, include:, exclude:, prerequisites:)
16
+ @payload = payload
17
+ @attributes = attributes
18
+ @include = include
19
+ @exclude = exclude
20
+ @filter_prerequisites = prerequisites.to_s == 'filter'
21
+ @saved_groups = payload['savedGroups'] || {}
22
+ @all_features = payload['features'] || {}
23
+ @added = {}
24
+ @as_written = {}
25
+ @on_cycle = nil
26
+ end
27
+
28
+ def reduce
29
+ @all_features.each do |id, feature|
30
+ add(id) if matches?(feature.is_a?(Hash) ? feature['metadata'] : nil)
31
+ end
32
+ experiments = (@payload['experiments'] || []).select { |e| matches?(e['metadata']) }.map { |e| prune(e, false) }
33
+ experiments.each { |e| add_parents(e) }
34
+
35
+ reduced = @payload.merge('features' => @added, 'experiments' => experiments)
36
+ # Only when there were any, as with the payload's other optional keys
37
+ if @payload['contextualBandits']
38
+ reduced['contextualBandits'] = contextual_bandits(experiments)
39
+ else
40
+ reduced.delete('contextualBandits')
41
+ end
42
+ used = [@added, experiments, reduced['contextualBandits']]
43
+ # Walking the payload is only needed when there are groups to find
44
+ unless @saved_groups.empty?
45
+ mark_as_written(used, true, {})
46
+ groups = used_saved_groups(used)
47
+ end
48
+ reduced['savedGroups'] = groups || {}
49
+ reduced
50
+ end
51
+
52
+ private
53
+
54
+ # Only an array counts, as with `$in`, and any one of its values is enough
55
+ def has?(actual, want)
56
+ want.is_a?(Array) && Growthbook::Conditions.in?(actual, want)
57
+ end
58
+
59
+ # A rule without projects applies wherever its feature is delivered
60
+ def rule_in_projects?(meta)
61
+ @include['projects'].nil? || meta.nil? || meta['projects'].nil? || has?(meta['projects'], @include['projects'])
62
+ end
63
+
64
+ # A feature or experiment has to list one of the projects, or be in all of
65
+ # them. One without projects is in none, like one without tags.
66
+ def in_projects?(meta)
67
+ @include['projects'].nil? || meta['allProjects'] || has?(meta['projects'], @include['projects'])
68
+ end
69
+
70
+ # Kept when it matches every `include` filter and no `exclude` filter. Only
71
+ # listed projects are excluded, so one in all projects stays.
72
+ def matches?(meta)
73
+ meta ||= {}
74
+ fields = meta['customFields'] || {}
75
+ in_fields = @include['customFields'] || {}
76
+ out_fields = @exclude['customFields'] || {}
77
+ in_projects?(meta) &&
78
+ (@include['tags'].nil? || has?(meta['tags'], @include['tags'])) &&
79
+ in_fields.all? { |k, want| has?(fields[k], want) } &&
80
+ !has?(meta['projects'], @exclude['projects']) &&
81
+ !has?(meta['tags'], @exclude['tags']) &&
82
+ out_fields.none? { |k, want| has?(fields[k], want) }
83
+ end
84
+
85
+ # Reduces a rule or an auto experiment
86
+ def prune(item, rule)
87
+ condition = item['condition'] ? Growthbook::Conditions.prune_condition(@attributes, item['condition'], @saved_groups) : nil
88
+ item = item.dup
89
+ if condition == true
90
+ item.delete('condition')
91
+ elsif condition == false
92
+ # Kept, since sticky buckets and forced variations skip an experiment's
93
+ # condition, and a rule's prerequisites are checked before it
94
+ item['condition'] = { '$not' => {} }
95
+ # A force rule that never passes never returns its value. An auto
96
+ # experiment's forced variation still applies to a sticky bucketed user.
97
+ item['force'] = nil if rule && item.key?('force')
98
+ elsif condition
99
+ item['condition'] = condition
100
+ end
101
+ item
102
+ end
103
+
104
+ # Adds the prerequisites the client evaluates for a rule or experiment, even
105
+ # when the filters drop them. With 'filter', only the filters decide, except
106
+ # for holdouts, which aren't app features and are always kept.
107
+ def add_parents(item)
108
+ (item['parentConditions'] || []).each do |parent|
109
+ id = parent['id']
110
+ add(id) if !@filter_prerequisites || id.to_s.start_with?('$holdout:')
111
+ end
112
+ end
113
+
114
+ def add(id)
115
+ feature = @all_features[id]
116
+ return if !feature.is_a?(Hash) || @added.key?(id)
117
+
118
+ # Rules scoped to other projects aren't served. A prerequisite from another
119
+ # project keeps its own, as on the server.
120
+ scoped = in_projects?(feature['metadata'] || {})
121
+ rules = feature['rules']&.select { |r| !scoped || rule_in_projects?(r['metadata']) }&.map { |r| prune(r, true) }
122
+ # Stored before its parents are added, so a prerequisite cycle ends
123
+ @added[id] = rules ? feature.merge('rules' => rules) : feature
124
+ (rules || []).each { |r| add_parents(r) }
125
+ end
126
+
127
+ # The contextual bandits that kept rules and experiments use. A context whose
128
+ # condition never passes can't be the first that does, so it goes.
129
+ def contextual_bandits(experiments)
130
+ all_bandits = @payload['contextualBandits'] || {}
131
+ bandits = {}
132
+ (@added.values.flat_map { |f| f['rules'] || [] } + experiments).each do |item|
133
+ ref = item['contextualBanditRef']
134
+ next if !ref || bandits.key?(ref) || !all_bandits.key?(ref)
135
+
136
+ bandit = all_bandits[ref]
137
+ # Evaluation tolerates a definition that isn't a Hash, so it stays
138
+ unless bandit.is_a?(Hash)
139
+ bandits[ref] = bandit
140
+ next
141
+ end
142
+
143
+ contexts = (bandit['contexts'] || []).flat_map do |c|
144
+ condition = Growthbook::Conditions.prune_condition(@attributes, c['condition'] || {}, @saved_groups)
145
+ next [] if condition == false
146
+
147
+ [c.merge('condition' => condition == true ? {} : condition)]
148
+ end
149
+ bandits[ref] = bandit.merge('contexts' => contexts)
150
+ end
151
+ bandits
152
+ end
153
+
154
+ # A list's values are attribute values, never references to other groups
155
+ def can_reference?(group)
156
+ group.is_a?(Hash) && group['type'] != 'list'
157
+ end
158
+
159
+ # Each saved group whose id appears as a string anywhere in `value`, with
160
+ # condition groups reduced. This needs no list of the operators that
161
+ # reference groups.
162
+ def used_saved_groups(value, groups = {})
163
+ case value
164
+ when String
165
+ return groups if !@saved_groups.key?(value) || groups.key?(value)
166
+
167
+ # Groups evaluated against something other than the user, or on a
168
+ # cycle, keep their condition as written
169
+ reducible = !@as_written.key?(value) && !on_cycle.key?(value)
170
+ condition = reducible ? Growthbook::Conditions.prune_saved_group(@attributes, { 'id' => value }, @saved_groups) : nil
171
+ groups[value] = condition.is_a?(Hash) ? @saved_groups[value].merge('condition' => condition) : @saved_groups[value]
172
+ used_saved_groups(groups[value], groups) if can_reference?(@saved_groups[value])
173
+ when Hash
174
+ value.each_value { |v| used_saved_groups(v, groups) }
175
+ when Array
176
+ value.each { |v| used_saved_groups(v, groups) }
177
+ end
178
+ groups
179
+ end
180
+
181
+ # Marks the groups that keep their condition as written: those evaluated
182
+ # against something other than the user (each item in $elemMatch, or the
183
+ # parent's value in a prerequisite), and the groups those reference
184
+ def mark_as_written(value, user, seen)
185
+ case value
186
+ when String
187
+ return if !@saved_groups.key?(value) || @as_written.key?(value)
188
+ return if user && seen.key?(value)
189
+
190
+ (user ? seen : @as_written)[value] = true
191
+ mark_as_written(@saved_groups[value], user, seen) if can_reference?(@saved_groups[value])
192
+ when Hash
193
+ value.each { |k, v| mark_as_written(v, user && k != '$elemMatch' && k != 'parentConditions', seen) }
194
+ when Array
195
+ value.each { |v| mark_as_written(v, user, seen) }
196
+ end
197
+ end
198
+
199
+ # A group on a cycle can't be reduced on its own: its result depends on
200
+ # which group the evaluation entered the cycle from. The groups on a cycle
201
+ # are found once, as strongly connected components with more than one
202
+ # group or a group that references itself.
203
+ def on_cycle
204
+ @on_cycle ||= groups_on_cycles
205
+ end
206
+
207
+ # Iterative Tarjan's algorithm over the group reference graph, so each
208
+ # group's entry is scanned once however many groups share it
209
+ def groups_on_cycles
210
+ edges = {}
211
+ @saved_groups.each do |id, group|
212
+ edges[id] = can_reference?(group) ? group_ids(group).uniq : []
213
+ end
214
+
215
+ index = {}
216
+ low = {}
217
+ on_stack = {}
218
+ stack = []
219
+ result = {}
220
+ counter = 0
221
+ edges.each_key do |root|
222
+ next if index.key?(root)
223
+
224
+ work = [[root, 0]]
225
+ index[root] = low[root] = counter
226
+ counter += 1
227
+ stack << root
228
+ on_stack[root] = true
229
+ until work.empty?
230
+ node, i = work.last
231
+ children = edges[node]
232
+ if i < children.length
233
+ work.last[1] = i + 1
234
+ child = children[i]
235
+ if !index.key?(child)
236
+ index[child] = low[child] = counter
237
+ counter += 1
238
+ stack << child
239
+ on_stack[child] = true
240
+ work << [child, 0]
241
+ elsif on_stack[child]
242
+ low[node] = [low[node], index[child]].min
243
+ end
244
+ next
245
+ end
246
+
247
+ work.pop
248
+ low[work.last[0]] = [low[work.last[0]], low[node]].min unless work.empty?
249
+ next unless low[node] == index[node]
250
+
251
+ component = []
252
+ loop do
253
+ member = stack.pop
254
+ on_stack.delete(member)
255
+ component << member
256
+ break if member == node
257
+ end
258
+ next unless component.length > 1 || children.include?(node)
259
+
260
+ component.each { |member| result[member] = true }
261
+ end
262
+ end
263
+ result
264
+ end
265
+
266
+ def group_ids(value, found = [])
267
+ case value
268
+ when String
269
+ found << value if @saved_groups.key?(value)
270
+ when Hash
271
+ value.each_value { |v| group_ids(v, found) }
272
+ when Array
273
+ value.each { |v| group_ids(v, found) }
274
+ end
275
+ found
276
+ end
277
+ end
278
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Growthbook
4
+ # Extendable class that can be used as the tracking callback
5
+ class StickyBucketService
6
+ def get_assignments(_attribute_name, _attribute_value)
7
+ nil
8
+ end
9
+
10
+ def save_assignments(_doc)
11
+ nil
12
+ end
13
+
14
+ def get_key(attribute_name, attribute_value)
15
+ "#{attribute_name}||#{attribute_value}"
16
+ end
17
+
18
+ def get_all_assignments(attributes)
19
+ docs = {}
20
+ attributes.each do |attribute_name, attribute_value|
21
+ doc = get_assignments(attribute_name, attribute_value)
22
+ docs[get_key(attribute_name, attribute_value)] = doc if doc
23
+ end
24
+ docs
25
+ end
26
+ end
27
+
28
+ # Sample implementation (not meant for production use)
29
+ class InMemoryStickyBucketService < StickyBucketService
30
+ attr_accessor :assignments
31
+
32
+ def initialize
33
+ super
34
+ @assignments = {}
35
+ end
36
+
37
+ def get_assignments(attribute_name, attribute_value)
38
+ @assignments[get_key(attribute_name, attribute_value)]
39
+ end
40
+
41
+ def save_assignments(doc)
42
+ @assignments[get_key(doc['attributeName'], doc['attributeValue'])] = doc
43
+ end
44
+ end
45
+ end
@@ -141,5 +141,41 @@ module Growthbook
141
141
  def self.in_range?(num, range)
142
142
  num >= range[0] && num < range[1]
143
143
  end
144
+
145
+ # Formats a number like JavaScript's String(number) (ECMAScript Number::toString),
146
+ # e.g. 2.0 -> "2", 0.000002 -> "0.000002", 1e21 -> "1e+21".
147
+ #
148
+ # @param number [Numeric] An Integer is formatted as the double JavaScript would parse
149
+ # @return [String]
150
+ def self.js_number_to_s(number)
151
+ x = number.to_f
152
+ return 'NaN' if x.nan?
153
+ return x.positive? ? 'Infinity' : '-Infinity' if x.infinite?
154
+ return '0' if x.zero?
155
+ return "-#{js_number_to_s(-x)}" if x.negative?
156
+
157
+ # Float#to_s gives the same shortest round-trip digits as JavaScript, but
158
+ # switches to scientific notation at different thresholds
159
+ mantissa, exponent = x.to_s.split('e')
160
+ whole, fraction = mantissa.to_s.split('.')
161
+ all_digits = "#{whole}#{fraction}"
162
+ digits = all_digits.sub(/\A0+/, '')
163
+ # x = 0.digits * 10**point
164
+ point = whole.to_s.length + exponent.to_i - (all_digits.length - digits.length)
165
+ digits = digits.sub(/0+\z/, '')
166
+ format_js_digits(digits, point)
167
+ end
168
+
169
+ # Lays out digits d1..dk with x = 0.d1..dk * 10**point, as ECMAScript Number::toString does
170
+ def self.format_js_digits(digits, point)
171
+ k = digits.length
172
+ return digits + ('0' * (point - k)) if k <= point && point <= 21
173
+ return "#{digits[0, point]}.#{digits[point..-1]}" if point.positive? && point <= 21
174
+ return "0.#{'0' * -point}#{digits}" if point > -6 && point <= 0
175
+
176
+ e = point - 1
177
+ fraction = k > 1 ? ".#{digits[1..-1]}" : ''
178
+ "#{digits[0]}#{fraction}e#{e.negative? ? '-' : '+'}#{e.abs}"
179
+ end
144
180
  end
145
181
  end