featurevisor 3.1.0 → 4.1.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.
@@ -10,9 +10,13 @@ module Featurevisor
10
10
  @sticky_variables = options[:sticky_variables] || {}
11
11
  @emitter = Featurevisor::Emitter.new
12
12
  @parent_unsubscribers = []
13
+ @closed = false
14
+ @evaluation_generation = 0
13
15
  end
14
16
 
15
17
  def on(event_name, callback = nil, &block)
18
+ return -> {} if @closed
19
+
16
20
  callback = block if block_given?
17
21
  if %w[context_set sticky_features_set sticky_variables_set].include?(event_name)
18
22
  return @emitter.on(event_name, callback)
@@ -33,14 +37,24 @@ module Featurevisor
33
37
  end
34
38
 
35
39
  def close
40
+ return if @closed
41
+
42
+ @closed = true
36
43
  @parent_unsubscribers.dup.each(&:call)
37
44
  @parent_unsubscribers.clear
38
45
  @emitter.clear_all
39
46
  end
40
47
 
41
48
  def set_context(context, replace = false)
49
+ previous = @context
42
50
  @context = replace ? context : { **@context, **context }
43
- @emitter.trigger("context_set", context: @context, replaced: replace)
51
+ @evaluation_generation += 1
52
+ details = { context: @context, replaced: replace }
53
+ # Only a listener reads the changed keys, so only then are they worked out.
54
+ if @emitter.listeners["context_set"]&.any?
55
+ details[:keys] = Events.get_changed_context_keys(previous, @context, replace ? nil : context)
56
+ end
57
+ @emitter.trigger("context_set", details)
44
58
  end
45
59
 
46
60
  def get_context(context = nil)
@@ -50,6 +64,7 @@ module Featurevisor
50
64
  def set_sticky_features(sticky, replace = false)
51
65
  previous = @sticky_features
52
66
  @sticky_features = replace ? sticky : { **@sticky_features, **sticky }
67
+ @evaluation_generation += 1
53
68
  params = Featurevisor::Events.get_params_for_sticky_features_set_event(previous, @sticky_features, replace)
54
69
  @emitter.trigger("sticky_features_set", params)
55
70
  end
@@ -57,6 +72,7 @@ module Featurevisor
57
72
  def set_sticky_variables(sticky, replace = false)
58
73
  previous = @sticky_variables
59
74
  @sticky_variables = replace ? sticky : { **@sticky_variables, **sticky }
75
+ @evaluation_generation += 1
60
76
  @emitter.trigger(
61
77
  "sticky_variables_set",
62
78
  Featurevisor::Events.get_params_for_sticky_variables_set_event(previous, @sticky_variables, replace)
@@ -87,7 +103,7 @@ module Featurevisor
87
103
  delegate_variable(:evaluate_variable, feature_or_variable_key, variable_key_or_context, context_or_options, options)
88
104
  end
89
105
 
90
- %i[boolean string integer double array object json].each do |type|
106
+ %i[boolean string integer number array object json].each do |type|
91
107
  define_method("get_variable_#{type}") do |feature_or_variable_key, variable_key_or_context = nil, context_or_options = {}, options = {}|
92
108
  delegate_variable("get_variable_#{type}".to_sym, feature_or_variable_key, variable_key_or_context, context_or_options, options)
93
109
  end
@@ -111,7 +127,10 @@ module Featurevisor
111
127
  {
112
128
  **options,
113
129
  __featurevisor_child_sticky_features: @sticky_features,
114
- __featurevisor_child_sticky_variables: @sticky_variables
130
+ __featurevisor_child_sticky_variables: @sticky_variables,
131
+ __featurevisor_sticky_features_source: -> { @sticky_features },
132
+ __featurevisor_sticky_variables_source: -> { @sticky_variables },
133
+ __featurevisor_child_generation: -> { @evaluation_generation }
115
134
  }
116
135
  end
117
136
 
@@ -19,7 +19,7 @@ module Featurevisor
19
19
  end
20
20
 
21
21
  match = version.match(SEMVER_REGEX)
22
- unless match
22
+ unless match && version.ascii_only? && match[0] == version
23
23
  raise ArgumentError, "Invalid argument not valid semver ('#{version}' received)"
24
24
  end
25
25
 
@@ -34,50 +34,29 @@ module Featurevisor
34
34
  s == "*" || s.downcase == "x"
35
35
  end
36
36
 
37
- # Forces types to be the same for comparison
38
- # @param a [String, Integer] First value
39
- # @param b [String, Integer] Second value
40
- # @return [Array] Array with both values converted to same type
41
- def self.force_type(a, b)
42
- if a.is_a?(Integer) != b.is_a?(Integer)
43
- [a.to_s, b.to_s]
44
- else
45
- [a, b]
46
- end
47
- end
48
-
49
- # Tries to parse a string as an integer
50
- # @param v [String] String to parse
51
- # @return [Integer, String] Parsed integer or original string
52
- def self.try_parse(v)
53
- Integer(v, 10)
54
- rescue ArgumentError
55
- v
56
- end
57
-
58
37
  # Compares two strings for version comparison
59
38
  # @param a [String] First string
60
39
  # @param b [String] Second string
61
40
  # @return [Integer] -1 if a < b, 0 if equal, 1 if a > b
62
- def self.compare_strings(a, b)
63
- return 0 if wildcard?(a) || wildcard?(b)
64
-
65
- ap, bp = force_type(try_parse(a), try_parse(b))
66
-
67
- if ap > bp
68
- 1
69
- elsif ap < bp
70
- -1
71
- else
72
- 0
41
+ def self.compare_strings(a, b, prerelease = false)
42
+ return 0 if !prerelease && (wildcard?(a) || wildcard?(b))
43
+ an = /\A[0-9]+\z/.match?(a)
44
+ bn = /\A[0-9]+\z/.match?(b)
45
+ if an && bn
46
+ a = a.sub(/\A0+/, "")
47
+ b = b.sub(/\A0+/, "")
48
+ return a.length <=> b.length if a.length != b.length
49
+ elsif prerelease && an != bn
50
+ return an ? -1 : 1
73
51
  end
52
+ a <=> b
74
53
  end
75
54
 
76
55
  # Compares version segments
77
56
  # @param a [Array<String>, MatchData] First version segments
78
57
  # @param b [Array<String>, MatchData] Second version segments
79
58
  # @return [Integer] -1 if a < b, 0 if equal, 1 if a > b
80
- def self.compare_segments(a, b)
59
+ def self.compare_segments(a, b, prerelease = false)
81
60
  # Convert to arrays if needed
82
61
  a_array = a.is_a?(MatchData) ? a.to_a[1..-1] : a.to_a
83
62
  b_array = b.is_a?(MatchData) ? b.to_a[1..-1] : b.to_a
@@ -85,10 +64,13 @@ module Featurevisor
85
64
  max_length = [a_array.length, b_array.length].max
86
65
 
87
66
  (0...max_length).each do |i|
67
+ if prerelease && (i == a_array.length || i == b_array.length)
68
+ return a_array.length <=> b_array.length
69
+ end
88
70
  a_val = a_array[i] || "0"
89
71
  b_val = b_array[i] || "0"
90
72
 
91
- result = compare_strings(a_val, b_val)
73
+ result = compare_strings(a_val, b_val, prerelease)
92
74
  return result unless result == 0
93
75
  end
94
76
 
@@ -116,7 +98,7 @@ module Featurevisor
116
98
 
117
99
  # Validate pre-release
118
100
  if p1 && p2
119
- compare_segments(p1.split("."), p2.split("."))
101
+ compare_segments(p1.split("."), p2.split("."), true)
120
102
  elsif p1 || p2
121
103
  p1 ? -1 : 1
122
104
  else
@@ -23,6 +23,16 @@ module Featurevisor
23
23
  def self.get_value_with_presence(obj, path)
24
24
  return MISSING unless obj.is_a?(Hash) && path.is_a?(String)
25
25
 
26
+ # Most attributes are direct keys. Avoid allocating a path array for
27
+ # every condition while retaining the existing nested path behaviour.
28
+ unless path.empty? || path.include?(".")
29
+ symbol = path.to_sym
30
+ return obj[symbol] if obj.key?(symbol)
31
+ return obj[path] if obj.key?(path)
32
+
33
+ return MISSING
34
+ end
35
+
26
36
  path.split(".").reduce(obj) do |current, key|
27
37
  break MISSING unless current.is_a?(Hash)
28
38
 
@@ -37,9 +47,14 @@ module Featurevisor
37
47
  end
38
48
  private_class_method :get_value_with_presence
39
49
 
50
+ # A number as JavaScript reads it, a double, so integers above 2^53 compare as JavaScript compares them.
51
+ def self.binary64(number)
52
+ number.to_f
53
+ end
54
+
40
55
  def self.strict_equal?(left, right)
41
56
  return true if left.nil? && right.nil?
42
- return left.to_f == right.to_f if left.is_a?(Numeric) && right.is_a?(Numeric)
57
+ return binary64(left) == binary64(right) if left.is_a?(Numeric) && right.is_a?(Numeric)
43
58
  return left == right if left.is_a?(String) && right.is_a?(String)
44
59
  return left == right if (left == true || left == false) && (right == true || right == false)
45
60
 
@@ -47,6 +62,15 @@ module Featurevisor
47
62
  end
48
63
  private_class_method :strict_equal?
49
64
 
65
+ def self.missing_value
66
+ MISSING
67
+ end
68
+
69
+ def self.value_is_matched(raw_value, condition, get_regex)
70
+ context = raw_value.equal?(MISSING) ? {} : { value: raw_value }
71
+ condition_is_matched(condition.merge(attribute: "value"), context, get_regex)
72
+ end
73
+
50
74
  # Check if a condition is matched against context
51
75
  # @param condition [Hash] Condition to evaluate
52
76
  # @param context [Hash] Context to evaluate against
@@ -55,7 +79,11 @@ module Featurevisor
55
79
  def self.condition_is_matched(condition, context, get_regex)
56
80
  attribute = condition["attribute"] || condition[:attribute]
57
81
  operator = condition["operator"] || condition[:operator]
58
- value = condition["value"] || condition[:value]
82
+ value = if condition.key?(:value)
83
+ condition[:value]
84
+ elsif condition.key?("value")
85
+ condition["value"]
86
+ end
59
87
  regex_flags = condition["regexFlags"] || condition[:regexFlags]
60
88
 
61
89
  raw_context_value = get_value_with_presence(context, attribute)
@@ -63,6 +91,18 @@ module Featurevisor
63
91
  attribute_exists = !raw_context_value.equal?(MISSING)
64
92
 
65
93
  case operator
94
+ when "empty", "notEmpty"
95
+ return false unless attribute_exists && !context_value_from_path.nil?
96
+
97
+ size = if context_value_from_path.is_a?(String) || context_value_from_path.is_a?(Array) ||
98
+ context_value_from_path.is_a?(Hash)
99
+ context_value_from_path.size
100
+ end
101
+ !size.nil? && (operator == "empty" ? size.zero? : size.positive?)
102
+ when "isNull"
103
+ attribute_exists && context_value_from_path.nil?
104
+ when "notNull"
105
+ attribute_exists && !context_value_from_path.nil?
66
106
  when "equals"
67
107
  attribute_exists && strict_equal?(context_value_from_path, value)
68
108
  when "notEquals"
@@ -129,17 +169,18 @@ module Featurevisor
129
169
  when "greaterThan", "greaterThanOrEquals", "lessThan", "lessThanOrEquals"
130
170
  # numeric operations
131
171
  if context_value_from_path.is_a?(Numeric) && value.is_a?(Numeric)
132
- value_in_context = context_value_from_path
172
+ value_in_context = binary64(context_value_from_path)
173
+ compared = binary64(value)
133
174
 
134
175
  case operator
135
176
  when "greaterThan"
136
- value_in_context > value
177
+ value_in_context > compared
137
178
  when "greaterThanOrEquals"
138
- value_in_context >= value
179
+ value_in_context >= compared
139
180
  when "lessThan"
140
- value_in_context < value
181
+ value_in_context < compared
141
182
  when "lessThanOrEquals"
142
- value_in_context <= value
183
+ value_in_context <= compared
143
184
  end
144
185
  else
145
186
  false
@@ -148,6 +189,12 @@ module Featurevisor
148
189
  attribute_exists
149
190
  when "notExists"
150
191
  !attribute_exists
192
+ when "includesAny", "notIncludesAny"
193
+ return false unless context_value_from_path.is_a?(Array) && value.is_a?(Array)
194
+ return false unless value.all? { |candidate| candidate.nil? || candidate.is_a?(String) || candidate.is_a?(Integer) || candidate.is_a?(Float) || candidate == true || candidate == false }
195
+
196
+ matched = value.any? { |candidate| context_value_from_path.any? { |actual| strict_equal?(actual, candidate) } }
197
+ operator == "includesAny" ? matched : !matched
151
198
  when "includes", "notIncludes"
152
199
  # includes / notIncludes (where context value is an array)
153
200
  if context_value_from_path.is_a?(Array) &&
@@ -167,15 +214,92 @@ module Featurevisor
167
214
  end
168
215
 
169
216
  def self.portable_date(value)
170
- return value if value.is_a?(Time) || value.is_a?(DateTime)
171
- return value.to_time if value.is_a?(Date)
172
- return nil unless value.is_a?(String)
173
- return nil unless value.match?(/T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+\-]\d{2}:\d{2})\z/)
174
-
175
- Time.iso8601(value)
176
- rescue ArgumentError
217
+ if value.is_a?(String)
218
+ match = /\A[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,9})?(?:Z|([+\-])([0-9]{2}):([0-9]{2}))\z/.match(value)
219
+ return nil unless match
220
+ return nil if value.start_with?("0000-")
221
+ if match[2] && (match[2].to_i > 14 || match[3].to_i > 59 || (match[2] == "14" && match[3] != "00"))
222
+ return nil
223
+ end
224
+ parsed = Time.iso8601(value)
225
+ # Time.iso8601 must not normalize an invalid calendar date or clock time.
226
+ return nil unless parsed.getlocal(match[1] ? "#{match[1]}#{match[2]}:#{match[3]}" : "+00:00").strftime("%Y-%m-%dT%H:%M:%S") == value[0, 19]
227
+ elsif value.is_a?(Time) || value.is_a?(DateTime)
228
+ return nil unless (1..9999).cover?(value.year)
229
+ offset_seconds = value.is_a?(DateTime) ? value.offset * 86400 : value.utc_offset
230
+ return nil if offset_seconds.abs > 14 * 3600
231
+ parsed = value.to_time
232
+ else
233
+ return nil
234
+ end
235
+ milliseconds = (parsed.to_r * 1000).floor
236
+ result = Time.at(Rational(milliseconds, 1000)).utc
237
+ return nil if result.year < 1 || result.year > 9999
238
+ result
239
+ rescue ArgumentError, RangeError
177
240
  nil
178
241
  end
179
242
  private_class_method :portable_date
243
+
244
+ # A portable timestamp, as before, after and a schema's format "date-time" read
245
+ # it, to the millisecond, or nil: years 0001 to 9999, offsets up to 14 hours,
246
+ # and fractions up to nine digits.
247
+ def self.portable_timestamp(value)
248
+ portable_date(value)
249
+ end
250
+
251
+ # JavaScript's whitespace and line terminators, for \s.
252
+ PORTABLE_SPACES = '\t\n\x0B\f\r \u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF'
253
+ # Everything else, for \S inside a class.
254
+ PORTABLE_NOT_SPACES = '\x00-\x08\x0E-\x1F\x21-\x7F\u0080-\u009F\u00A1-\u167F\u1681-\u1FFF\u200B-\u2027' \
255
+ '\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uFEFE\uFF00-\u{10FFFF}'
256
+
257
+ # A portable pattern in Onigmo's syntax, meaning what it means in JavaScript
258
+ # with the same flags: \d and \w are ASCII, \s is JavaScript's whitespace, a
259
+ # dot refuses only JavaScript's line terminators, and without m, ^ and $
260
+ # match at the start and end of the value only, where Onigmo's match at every
261
+ # line.
262
+ def self.normalize_portable_regex(pattern, flags = '')
263
+ multiline = flags.to_s.include?('m')
264
+ dot_all = flags.to_s.include?('s')
265
+ inside = {
266
+ 'd' => '0-9', 'D' => '\u{0}-\u{2F}\u{3A}-\u{10FFFF}',
267
+ 'w' => 'A-Za-z0-9_', 'W' => '\u{0}-\u{2F}\u{3A}-\u{40}\u{5B}-\u{5E}\u{60}\u{7B}-\u{10FFFF}',
268
+ 's' => PORTABLE_SPACES, 'S' => PORTABLE_NOT_SPACES
269
+ }
270
+ outside = {
271
+ 'd' => '[0-9]', 'D' => '[^0-9]', 'w' => '(?-i:[A-Za-z0-9_])', 'W' => '(?-i:[^A-Za-z0-9_])',
272
+ 's' => "[#{PORTABLE_SPACES}]", 'S' => "[^#{PORTABLE_SPACES}]"
273
+ }
274
+ output = +''
275
+ in_class = false
276
+ index = 0
277
+ while index < pattern.length
278
+ char = pattern[index]
279
+ if char == '\\' && index + 1 < pattern.length
280
+ code = pattern[index + 1]
281
+ output << (in_class ? inside : outside).fetch(code, pattern[index, 2])
282
+ index += 2
283
+ next
284
+ end
285
+ if in_class
286
+ in_class = false if char == ']'
287
+ output << char
288
+ elsif char == '['
289
+ in_class = true
290
+ output << char
291
+ elsif char == '^' && !multiline
292
+ output << '\A'
293
+ elsif char == '$' && !multiline
294
+ output << '\z'
295
+ elsif char == '.' && !dot_all
296
+ output << '[^\n\r\u2028\u2029]'
297
+ else
298
+ output << char
299
+ end
300
+ index += 1
301
+ end
302
+ output
303
+ end
180
304
  end
181
305
  end
@@ -0,0 +1,150 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Featurevisor
6
+ module Dependencies
7
+ def self.extract_entity_dependencies(entry)
8
+ sources = {}
9
+ add = lambda do |kind, key, dependent|
10
+ source = [kind, key.to_sym]
11
+ sources[source] = true
12
+ end
13
+ conditions = nil
14
+ conditions = lambda do |value, dependent|
15
+ case value
16
+ when String
17
+ next if value == "*"
18
+ if value.lstrip.match?(/\A[\{\[\"]/)
19
+ begin
20
+ conditions.call(JSON.parse(value, symbolize_names: true), dependent)
21
+ rescue JSON::ParserError
22
+ nil
23
+ end
24
+ else
25
+ add.call(:segment, value, dependent)
26
+ end
27
+ when Array
28
+ value.each { |child| conditions.call(child, dependent) }
29
+ when Hash
30
+ if value.key?(:variable)
31
+ add.call(value[:feature] ? :feature : :variable, value[:feature] || value[:variable], dependent)
32
+ elsif value.key?(:feature)
33
+ add.call(:feature, value[:feature], dependent)
34
+ elsif !value.key?(:attribute)
35
+ %i[and or not].each { |group| conditions.call(value[group], dependent) if value.key?(group) }
36
+ end
37
+ end
38
+ end
39
+ visit = nil
40
+ visit = lambda do |entry, dependent|
41
+ conditions.call(entry[:conditions], dependent) if entry.key?(:conditions)
42
+ %i[force traffic variations overrides overrideProgram].each do |name|
43
+ (entry[name] || []).each { |child| visit.call(child, dependent) }
44
+ end
45
+ (entry[:variableOverrides] || {}).each_value do |overrides|
46
+ overrides.each { |child| visit.call(child, dependent) }
47
+ end
48
+ end
49
+ visit.call(entry, nil)
50
+ compose = entry[:compose]
51
+ if compose.is_a?(String)
52
+ add.call(:variable, compose, nil)
53
+ elsif compose.is_a?(Array)
54
+ compose.each do |reference|
55
+ add.call(reference[:feature] ? :feature : :variable, reference[:feature] || reference[:variable], nil)
56
+ end
57
+ end
58
+ sources.keys
59
+ end
60
+
61
+ COLLECTIONS = { segments: :segment, features: :feature, variables: :variable }.freeze
62
+
63
+ # Edge identities do not retain old providers, definitions or caller values.
64
+ class Index
65
+ EMPTY = [].freeze
66
+
67
+ def initialize
68
+ @reverse = {}
69
+ @owners = {}
70
+ @order = {}
71
+ @next_order = 0
72
+ end
73
+
74
+ def update(datafile, incoming, previous = nil)
75
+ updates = []
76
+ COLLECTIONS.each do |name, kind|
77
+ definitions = datafile[name] || {}
78
+ (incoming[name] || {}).each_key do |key|
79
+ owner = [kind, key.to_sym]
80
+ entry = definitions[key.to_sym]
81
+ # Hashes do not identify edges. Reuse only an identical definition.
82
+ next if previous && @owners.key?(owner) && entry && entry == (previous[name] || {})[key.to_sym]
83
+ updates << [owner, entry && Dependencies.extract_entity_dependencies(entry)]
84
+ end
85
+ end
86
+ updates.each do |owner, sources|
87
+ (@owners.delete(owner) || []).each do |source|
88
+ dependents = @reverse[source]
89
+ dependents.delete(owner)
90
+ @reverse.delete(source) if dependents.empty?
91
+ end
92
+ unless sources
93
+ @order.delete(owner)
94
+ next
95
+ end
96
+ unless @order.key?(owner)
97
+ @order[owner] = @next_order
98
+ @next_order += 1
99
+ end
100
+ @owners[owner] = sources
101
+ sources.each { |source| (@reverse[source] ||= {})[owner] = true }
102
+ end
103
+ end
104
+
105
+ def reorder(datafile)
106
+ @order = {}
107
+ COLLECTIONS.each do |name, kind|
108
+ (datafile[name] || {}).each_key.with_index { |key, rank| @order[[kind, key.to_sym]] = rank }
109
+ end
110
+ @next_order = (@order.values.max || -1) + 1
111
+ end
112
+
113
+ def dependents(identity)
114
+ dependents = @reverse[identity]
115
+ dependents ? dependents.keys.sort_by { |owner| @order.fetch(owner) } : EMPTY
116
+ end
117
+ end
118
+
119
+ def self.create_index(datafile)
120
+ index = Index.new
121
+ index.update(datafile, datafile)
122
+ index
123
+ end
124
+
125
+ def self.add_changes(features, variables, changed_segments, index)
126
+ kinds = %i[feature variable segment]
127
+ affected = [features, variables, changed_segments].map { |keys| keys.to_h { |key| [key.to_sym, true] } }
128
+ queues = affected.map(&:keys)
129
+ cursors = [0, 0, 0]
130
+ loop do
131
+ advanced = false
132
+ kinds.each_with_index do |kind, source|
133
+ next if cursors[source] >= queues[source].length
134
+ advanced = true
135
+ key = queues[source][cursors[source]]
136
+ cursors[source] += 1
137
+ index.dependents([kind, key]).each do |target_kind, target_key|
138
+ target = kinds.index(target_kind)
139
+ next if affected[target].key?(target_key)
140
+ affected[target][target_key] = true
141
+ queues[target] << target_key
142
+ end
143
+ end
144
+ break unless advanced
145
+ end
146
+ features.replace(affected[0].keys)
147
+ variables.replace(affected[1].keys)
148
+ end
149
+ end
150
+ end
@@ -31,6 +31,7 @@ module Featurevisor
31
31
  is_active = false
32
32
  index = listeners.index(callback)
33
33
  listeners.delete_at(index) if index && index >= 0
34
+ callback = nil
34
35
  end
35
36
  end
36
37
 
@@ -54,6 +55,9 @@ module Featurevisor
54
55
 
55
56
  # Clear all event listeners
56
57
  def clear_all
58
+ # Cleanup functions may still reference the previous listener arrays.
59
+ # Empty those arrays too, rather than retaining unrelated callbacks.
60
+ @listeners.each_value(&:clear)
57
61
  @listeners = {}
58
62
  end
59
63
  end