nanoflags 0.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.
@@ -0,0 +1,200 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "strscan"
5
+
6
+ module NanoFlags
7
+ module Engine
8
+ # Raised by {Json.parse} for text that `JSON.parse` rejects.
9
+ class InvalidJsonError < ArgumentError; end
10
+
11
+ # `JSON.parse` / `JSON.stringify` with JavaScript semantics for the engine's value model ({Js}): numbers become
12
+ # Float (overflow becomes ±Infinity), objects become Hash in JavaScript key order, a repeated key keeps its first
13
+ # position and its last value, and lone UTF-16 surrogates survive as WTF-8.
14
+ module Json
15
+ module_function
16
+
17
+ PARSE_OPTS = begin
18
+ opts = { allow_nan: false, max_nesting: false, create_additions: false }
19
+ # json >= 2.13 warns about repeated keys unless told that JSON.parse semantics (last one wins) are wanted.
20
+ opts[:allow_duplicate_key] = true if Gem::Version.new(::JSON::VERSION) >= Gem::Version.new("2.13")
21
+ opts.freeze
22
+ end
23
+
24
+ # Parses JSON text exactly like JavaScript's `JSON.parse`.
25
+ def parse(text)
26
+ text = text.to_s
27
+ text = text.dup.force_encoding(Encoding::UTF_8) unless text.encoding == Encoding::UTF_8
28
+ # Fast path: the json extension, then the result is converted. Lone surrogates and invalid UTF-8 make it fail
29
+ # (or are not representable); the exact parser below handles those.
30
+ if text.valid_encoding?
31
+ begin
32
+ return convert(::JSON.parse(text, PARSE_OPTS))
33
+ rescue ::JSON::ParserError, EncodingError, ArgumentError
34
+ # fall through to the exact parser
35
+ end
36
+ end
37
+ Parser.new(text).parse_document
38
+ end
39
+
40
+ def convert(v)
41
+ case v
42
+ when Integer then v.bit_length <= 53 ? v.to_f : Js.integer_to_float(v)
43
+ when Array then v.map! { |e| convert(e) }
44
+ when Hash
45
+ v.transform_values! { |e| convert(e) }
46
+ Js.js_order(v)
47
+ else v
48
+ end
49
+ end
50
+
51
+ # JSON.stringify(v), or nil where JSON.stringify returns undefined.
52
+ def stringify(v) = Js.stringify(v)
53
+
54
+ # Byte-level `JSON.parse` for the inputs the json extension refuses: lone UTF-16 surrogates are kept as their
55
+ # three-byte WTF-8 form, invalid UTF-8 in the text becomes U+FFFD (as a TextDecoder would).
56
+ #
57
+ # @api private
58
+ class Parser
59
+ def initialize(text)
60
+ @s = StringScanner.new(text.b)
61
+ end
62
+
63
+ def parse_document
64
+ ws
65
+ v = value(0)
66
+ ws
67
+ fail!("unexpected trailing data") unless @s.eos?
68
+ v
69
+ end
70
+
71
+ private
72
+
73
+ def fail!(msg)
74
+ raise InvalidJsonError, "invalid JSON: #{msg} at offset #{@s.pos}"
75
+ end
76
+
77
+ def ws
78
+ @s.skip(/[ \t\n\r]*/)
79
+ end
80
+
81
+ def value(depth)
82
+ fail!("nesting too deep") if depth > 10_000
83
+ fail!("unexpected end") if @s.eos?
84
+ case @s.peek(1)
85
+ when "{"
86
+ @s.pos += 1
87
+ h = {}
88
+ ws
89
+ return Js.js_order(h) if @s.skip(/\}/)
90
+
91
+ loop do
92
+ ws
93
+ fail!("expected a string key") unless @s.peek(1) == '"'
94
+ k = str
95
+ ws
96
+ fail!("expected ':'") unless @s.skip(/:/)
97
+ ws
98
+ h[k] = value(depth + 1)
99
+ ws
100
+ next if @s.skip(/,/)
101
+ return Js.js_order(h) if @s.skip(/\}/)
102
+
103
+ fail!("expected ',' or '}'")
104
+ end
105
+ when "["
106
+ @s.pos += 1
107
+ a = []
108
+ ws
109
+ return a if @s.skip(/\]/)
110
+
111
+ loop do
112
+ ws
113
+ a << value(depth + 1)
114
+ ws
115
+ next if @s.skip(/,/)
116
+ return a if @s.skip(/\]/)
117
+
118
+ fail!("expected ',' or ']'")
119
+ end
120
+ when '"' then str
121
+ when "t" then lit("true", true)
122
+ when "f" then lit("false", false)
123
+ when "n" then lit("null", nil)
124
+ else
125
+ t = @s.scan(/-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/)
126
+ fail!("unexpected character") if t.nil?
127
+ fail!("invalid number") if @s.match?(/[0-9.eE+-]/)
128
+ t.to_f
129
+ end
130
+ end
131
+
132
+ def lit(word, v)
133
+ fail!("invalid literal") unless @s.skip(Regexp.new(Regexp.escape(word)))
134
+ v
135
+ end
136
+
137
+ def hex4
138
+ h = @s.scan(/[0-9a-fA-F]{4}/)
139
+ h&.to_i(16)
140
+ end
141
+
142
+ def str
143
+ @s.pos += 1 # opening quote
144
+ out = +""
145
+ loop do
146
+ run = @s.scan(/[^"\\\x00-\x1F\x80-\xFF]+/n)
147
+ out << run if run
148
+ fail!("unterminated string") if @s.eos?
149
+ c = @s.peek(1)
150
+ if c == '"'
151
+ @s.pos += 1
152
+ return out.force_encoding(Encoding::UTF_8)
153
+ end
154
+ o = c.ord
155
+ fail!("control character in string") if o < 0x20
156
+ if o >= 0x80
157
+ # One UTF-8 sequence; an invalid one becomes U+FFFD (one per byte).
158
+ chunk = @s.peek(4)
159
+ cp, size = Js.code_points(chunk.dup.force_encoding(Encoding::UTF_8)).first
160
+ if (cp == 0xFFFD && size == 1) || (cp >= 0xD800 && cp <= 0xDFFF)
161
+ out << Js::REPLACEMENT.b
162
+ @s.pos += 1
163
+ else
164
+ out << chunk[0, size]
165
+ @s.pos += size
166
+ end
167
+ next
168
+ end
169
+ @s.pos += 1 # backslash
170
+ fail!("unterminated escape") if @s.eos?
171
+ e = @s.getch
172
+ case e
173
+ when '"', "\\", "/" then out << e
174
+ when "b" then out << "\b"
175
+ when "f" then out << "\f"
176
+ when "n" then out << "\n"
177
+ when "r" then out << "\r"
178
+ when "t" then out << "\t"
179
+ when "u"
180
+ u = hex4
181
+ fail!("invalid unicode escape") if u.nil?
182
+ if u.between?(0xD800, 0xDBFF) && @s.peek(2) == "\\u"
183
+ save = @s.pos
184
+ @s.pos += 2
185
+ lo = hex4
186
+ if lo&.between?(0xDC00, 0xDFFF)
187
+ out << Js.encode_unit(0x10000 + ((u - 0xD800) << 10) + (lo - 0xDC00)).b
188
+ next
189
+ end
190
+ @s.pos = save
191
+ end
192
+ out << Js.encode_unit(u).b
193
+ else fail!("invalid escape")
194
+ end
195
+ end
196
+ end
197
+ end
198
+ end
199
+ end
200
+ end
@@ -0,0 +1,407 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "engine/js"
4
+ require_relative "engine/json"
5
+
6
+ module NanoFlags
7
+ # The NanoFlags evaluation engine: a port of the TypeScript engine (`@nanoflags/engine`) that the dashboard, the
8
+ # edge and every SDK share.
9
+ #
10
+ # Pure and deterministic: the same bundle, flag key and context always produce the same result, including the
11
+ # bucket of percentage rollouts (MurmurHash3 x86 32-bit over the NFC-normalised UTF-8 bytes of "seed:identity").
12
+ # Rules are data; no user code ever runs. Configuration is JSON evaluated with JavaScript semantics ({Engine::Js});
13
+ # the cross-language parity fixtures (packages/engine/fixtures/parity.json) pin the behaviour, malformed
14
+ # configurations included.
15
+ module Engine
16
+ # The engine version implemented here (`ENGINE_VERSION` of the TypeScript engine). Newer bundles are refused.
17
+ VERSION = 1
18
+
19
+ # One line of the human-readable explanation of an evaluation. +kind+ is "config", "rule", "allocation" or
20
+ # "result"; +matched+ is set for rule and allocation steps.
21
+ TraceStep = Struct.new(:kind, :title, :detail, :matched) do
22
+ def to_h
23
+ h = { "kind" => kind, "title" => title, "detail" => detail }
24
+ h["matched"] = matched unless matched.nil?
25
+ h
26
+ end
27
+ end
28
+
29
+ # The outcome of {Engine.evaluate}, mirroring the TypeScript engine's `Evaluation` object. Values are engine
30
+ # values; +value+ is {UNDEFINED} when the configuration served nothing, +rule_id+ is {UNDEFINED} when there is none.
31
+ Result = Struct.new(:flag_key, :value, :reason, :revision, :rule_index, :rule_id, :in_rollout, :bucket, :trace, :error)
32
+
33
+ OP_WORDS = {
34
+ "eq" => "=", "neq" => "≠", "in" => "in", "not_in" => "not in", "contains" => "contains",
35
+ "starts_with" => "starts with", "ends_with" => "ends with", "gt" => ">", "gte" => "≥", "lt" => "<", "lte" => "≤",
36
+ "exists" => "exists", "not_exists" => "does not exist", "segment" => "in segment", "not_segment" => "not in segment"
37
+ }.freeze
38
+
39
+ M32 = 0xFFFFFFFF
40
+
41
+ module_function
42
+
43
+ # ---------------------------------------------------------------- hashing
44
+
45
+ # `TextEncoder.encode(input.normalize("NFC"))`: lone surrogates and invalid bytes become U+FFFD.
46
+ def hash_input(s)
47
+ return s.b if s.ascii_only?
48
+ return s.unicode_normalize(:nfc).b if s.valid_encoding?
49
+
50
+ out = +"".b
51
+ run = +""
52
+ Js.code_points(s).each do |cp, size|
53
+ if cp.between?(0xD800, 0xDFFF) || (cp == 0xFFFD && size == 1)
54
+ out << run.unicode_normalize(:nfc).b << Js::REPLACEMENT.b
55
+ run = +""
56
+ next
57
+ end
58
+ run << Js.encode_unit(cp)
59
+ end
60
+ out << run.unicode_normalize(:nfc).b
61
+ end
62
+
63
+ # MurmurHash3 x86 32-bit over the NFC-normalised UTF-8 bytes of +input+ (unsigned). Distribution only.
64
+ def murmur3(input, seed = 0)
65
+ data = hash_input(input)
66
+ c1 = 0xCC9E2D51
67
+ c2 = 0x1B873593
68
+ h = seed & M32
69
+ n = data.bytesize
70
+ blocks = n >> 2
71
+ data.unpack("V#{blocks}").each do |k|
72
+ k = (k * c1) & M32
73
+ k = ((k << 15) | (k >> 17)) & M32
74
+ k = (k * c2) & M32
75
+ h ^= k
76
+ h = ((h << 13) | (h >> 19)) & M32
77
+ h = ((h * 5) + 0xE6546B64) & M32
78
+ end
79
+ tail = data.byteslice(blocks * 4, n & 3).bytes
80
+ k = 0
81
+ k ^= tail[2] << 16 if tail.length >= 3
82
+ k ^= tail[1] << 8 if tail.length >= 2
83
+ if tail.length >= 1
84
+ k ^= tail[0]
85
+ k = (k * c1) & M32
86
+ k = ((k << 15) | (k >> 17)) & M32
87
+ k = (k * c2) & M32
88
+ h ^= k
89
+ end
90
+ h ^= n & M32
91
+ h ^= h >> 16
92
+ h = (h * 0x85EBCA6B) & M32
93
+ h ^= h >> 13
94
+ h = (h * 0xC2B2AE35) & M32
95
+ h ^ (h >> 16)
96
+ end
97
+
98
+ # Bucket in [0, 100) with two decimals of resolution, stable for a given seed + identity.
99
+ def bucket_of(seed, identity)
100
+ (murmur3("#{seed}:#{identity}") % 10_000) / 100.0
101
+ end
102
+
103
+ # ---------------------------------------------------------------- conditions
104
+
105
+ def loose_eq?(a, b)
106
+ return false if a.equal?(UNDEFINED) || b.equal?(UNDEFINED)
107
+
108
+ obj = ->(v) { v.nil? || v.is_a?(Array) || v.is_a?(Hash) }
109
+ return Js.stringify(a) == Js.stringify(b) if obj.(a) || obj.(b)
110
+ return a == b if a.is_a?(Float) && b.is_a?(Float)
111
+ return a == b if (a == true || a == false) && (b == true || b == false)
112
+ return a == b if a.is_a?(String) && b.is_a?(String)
113
+
114
+ false
115
+ end
116
+
117
+ def num(v)
118
+ if v.is_a?(Float)
119
+ v.finite? ? v : nil
120
+ elsif v.is_a?(String) && !Js.trim(v).empty?
121
+ n = Js.string_to_number(v)
122
+ n.finite? ? n : nil
123
+ end
124
+ end
125
+
126
+ def lookup(ctx, name)
127
+ ctx.is_a?(Hash) ? ctx.fetch(name, UNDEFINED) : UNDEFINED
128
+ end
129
+
130
+ def match_condition(c, ctx, segments, depth)
131
+ op = Js.get(c, "op")
132
+ if op == "segment" || op == "not_segment"
133
+ value = Js.get(c, "value")
134
+ seg = value.is_a?(String) ? Js.own(segments, value) : UNDEFINED
135
+ in_seg = false
136
+ if !seg.equal?(UNDEFINED) && depth < 4
137
+ match = Js.get(seg, "match")
138
+ conds = Js.get(seg, "conditions")
139
+ in_seg = match_all(match, conds, ctx, segments, depth + 1)
140
+ end
141
+ return op == "segment" ? in_seg : (!seg.equal?(UNDEFINED) && !in_seg)
142
+ end
143
+ actual = lookup(ctx, Js.to_str(Js.get(c, "attribute")))
144
+ value = Js.get(c, "value")
145
+ return false unless op.is_a?(String)
146
+
147
+ case op
148
+ when "exists" then !Js.nullish?(actual)
149
+ when "not_exists" then Js.nullish?(actual)
150
+ when "eq" then loose_eq?(actual, value)
151
+ when "neq" then !actual.equal?(UNDEFINED) && !loose_eq?(actual, value)
152
+ when "in" then value.is_a?(Array) && value.any? { |v| loose_eq?(actual, v) }
153
+ when "not_in" then !actual.equal?(UNDEFINED) && value.is_a?(Array) && value.none? { |v| loose_eq?(actual, v) }
154
+ when "contains" then actual.is_a?(String) && value.is_a?(String) && Js.includes?(actual, value)
155
+ when "starts_with" then actual.is_a?(String) && value.is_a?(String) && Js.starts_with?(actual, value)
156
+ when "ends_with" then actual.is_a?(String) && value.is_a?(String) && Js.ends_with?(actual, value)
157
+ when "gt", "gte", "lt", "lte"
158
+ a = num(actual)
159
+ b = num(value)
160
+ return false if a.nil? || b.nil?
161
+
162
+ case op
163
+ when "gt" then a > b
164
+ when "gte" then a >= b
165
+ when "lt" then a < b
166
+ else a <= b
167
+ end
168
+ else false
169
+ end
170
+ end
171
+
172
+ # The engine's matchAll(mode, conditions, …), including its failure modes.
173
+ def match_all(mode, conditions, ctx, segments, depth)
174
+ length = Js.get(conditions, "length")
175
+ return true if length.is_a?(Float) && length.zero?
176
+
177
+ some = mode == "any"
178
+ raise JsTypeError, "conditions.#{some ? "some" : "every"} is not a function" unless conditions.is_a?(Array)
179
+
180
+ conditions.each do |c|
181
+ ok = match_condition(c, ctx, segments, depth)
182
+ return true if some && ok
183
+ return false if !some && !ok
184
+ end
185
+ !some
186
+ end
187
+
188
+ # Human-readable condition, as shown in traces (describeCondition of the TypeScript engine).
189
+ def describe_condition(c)
190
+ value = Js.get(c, "value")
191
+ v = if value.is_a?(Array) then Js.join(value, ", ")
192
+ elsif value.equal?(UNDEFINED) then ""
193
+ else Js.to_str(value)
194
+ end
195
+ op = Js.get(c, "op")
196
+ key = Js.to_str(op)
197
+ word = OP_WORDS[key] || Js::OBJECT_PROTO_STRINGS[key] || "undefined"
198
+ return "#{word} #{v}" if op == "segment" || op == "not_segment"
199
+
200
+ attribute = Js.to_str(Js.get(c, "attribute"))
201
+ return "#{attribute} #{word}" if op == "exists" || op == "not_exists"
202
+
203
+ "#{attribute} #{word} #{v}"
204
+ end
205
+
206
+ # The engine's fmt(v): strings as they are, everything else as JSON ("undefined" when there is none).
207
+ def fmt(v)
208
+ v.is_a?(String) ? v : (Js.stringify(v) || "undefined")
209
+ end
210
+
211
+ # ---------------------------------------------------------------- evaluation
212
+
213
+ # Evaluates one flag of +bundle+ (a parsed bundle document; nil or {UNDEFINED} for "no configuration loaded") for
214
+ # +ctx+ (a Hash of engine values). Never raises: on any problem it returns +fallback+ with reason
215
+ # "flag_not_found" or "error".
216
+ def evaluate(bundle, flag_key, ctx, fallback)
217
+ nullish = Js.nullish?(bundle)
218
+ revision = 0.0
219
+ unless nullish
220
+ r = begin
221
+ Js.get(bundle, "revision")
222
+ rescue StandardError
223
+ UNDEFINED
224
+ end
225
+ revision = r unless Js.nullish?(r)
226
+ end
227
+ trace = []
228
+ begin
229
+ flag = nullish ? UNDEFINED : Js.own(Js.get(bundle, "flags"), flag_key)
230
+ if !Js.truthy?(bundle) || !Js.truthy?(flag)
231
+ detail = if Js.truthy?(bundle)
232
+ "Flag is not in this configuration. The application fallback applies."
233
+ else
234
+ "No configuration is loaded. The application fallback applies."
235
+ end
236
+ trace << TraceStep.new("result", "Returned #{fmt(fallback)}", detail)
237
+ return Result.new(flag_key, fallback, "flag_not_found", revision, nil, UNDEFINED, nil, nil, trace, nil)
238
+ end
239
+ trace << TraceStep.new("config", "Configuration loaded", Js.to_number(revision) > 0 ? "r#{Js.to_str(revision)}" : "draft")
240
+ unless Js.truthy?(Js.get(flag, "enabled"))
241
+ off = Js.get(flag, "off")
242
+ trace << TraceStep.new("result", "Returned #{fmt(off)}", "Flag is disabled in this environment.")
243
+ return Result.new(flag_key, off, "off", revision, nil, UNDEFINED, nil, nil, trace, nil)
244
+ end
245
+ rules = Js.get(flag, "rules")
246
+ segments = Js.get(bundle, "segments")
247
+ i = 0
248
+ loop do
249
+ length = Js.get(rules, "length")
250
+ break unless i.to_f < Js.to_number(length)
251
+
252
+ rule = Js.get(rules, i.to_s)
253
+ match = Js.get(rule, "match")
254
+ conditions = Js.get(rule, "conditions")
255
+ matched = match_all(match, conditions, ctx, segments, 0)
256
+ label = format("Rule %02d", i + 1)
257
+ summary = "all contexts"
258
+ if Js.truthy?(Js.get(conditions, "length"))
259
+ summary = conditions.map { |c| describe_condition(c) }.join(match == "any" ? " OR " : " AND ")
260
+ end
261
+ trace << TraceStep.new("rule", matched ? "#{label} matched" : "#{label} did not match", summary, matched)
262
+ unless matched
263
+ i += 1
264
+ next
265
+ end
266
+ serve = Js.get(rule, "serve")
267
+ serve_type = Js.get(serve, "type")
268
+ rule_id = Js.get(rule, "id")
269
+ if serve_type == "fixed"
270
+ value = Js.get(serve, "value")
271
+ trace << TraceStep.new("result", "Returned #{fmt(value)}", "#{label} serves a fixed value.")
272
+ return Result.new(flag_key, value, "rule_match", revision, i, rule_id, nil, nil, trace, nil)
273
+ end
274
+ attr_v = Js.get(serve, "bucketBy")
275
+ attr = Js.nullish?(attr_v) ? "key" : Js.to_str(attr_v)
276
+ identity = lookup(ctx, attr)
277
+ otherwise = Js.get(serve, "otherwise")
278
+ if Js.nullish?(identity) || identity == ""
279
+ trace << TraceStep.new("allocation", "Allocation skipped", "Context has no \"#{attr}\" to bucket by; treated as outside the allocation.", false)
280
+ trace << TraceStep.new("result", "Returned #{fmt(otherwise)}", "Remaining eligible users.")
281
+ return Result.new(flag_key, otherwise, "rule_match", revision, i, rule_id, false, nil, trace, nil)
282
+ end
283
+ seed_v = Js.get(serve, "seed")
284
+ seed = Js.nullish?(seed_v) ? flag_key : Js.to_str(seed_v)
285
+ hash = murmur3("#{seed}:#{Js.to_str(identity)}") % 10_000
286
+ bucket = hash / 100.0
287
+ percentage = Js.get(serve, "percentage")
288
+ in_rollout = bucket < Js.to_number(percentage)
289
+ pct = Js.to_str(percentage)
290
+ fixed = format("%d.%02d", hash / 100, hash % 100)
291
+ trace << TraceStep.new("allocation", "Allocation evaluated", "#{pct}% rollout · #{attr} #{in_rollout ? "inside" : "outside"} allocation (bucket #{fixed})", in_rollout)
292
+ value = in_rollout ? Js.get(serve, "value") : otherwise
293
+ trace << TraceStep.new("result", "Returned #{fmt(value)}", in_rollout ? "Inside the #{pct}% allocation." : "Remaining eligible users.")
294
+ return Result.new(flag_key, value, "rule_match", revision, i, rule_id, in_rollout, bucket, trace, nil)
295
+ end
296
+ default = Js.get(flag, "default")
297
+ trace << TraceStep.new("result", "Returned #{fmt(default)}", "No rule matched. The flag default applies.")
298
+ Result.new(flag_key, default, "default", revision, nil, UNDEFINED, nil, nil, trace, nil)
299
+ rescue StandardError, SystemStackError => e
300
+ msg = e.message.to_s.empty? ? e.class.name : e.message
301
+ trace << TraceStep.new("result", "Returned #{fmt(fallback)}", "Evaluation error: #{msg}. The application fallback applies.")
302
+ Result.new(flag_key, fallback, "error", revision, nil, UNDEFINED, nil, nil, trace, msg)
303
+ end
304
+ end
305
+
306
+ # ---------------------------------------------------------------- bundles
307
+
308
+ # True when this engine can evaluate a bundle whose `engine` member is +e+ ({UNDEFINED} when absent).
309
+ def supports_engine?(e)
310
+ return true if e.equal?(UNDEFINED)
311
+
312
+ e.is_a?(Float) && e.finite? && e == e.floor && e >= 1 && e <= VERSION
313
+ end
314
+
315
+ # The shape the SDKs accept as a bundle: `schema` 1, a numeric `revision`, object `flags` and `segments`.
316
+ def bundle?(v)
317
+ v.is_a?(Hash) && v["schema"].is_a?(Float) && v["schema"] == 1.0 && v["revision"].is_a?(Float) &&
318
+ v["flags"].is_a?(Hash) && (v["segments"].is_a?(Hash) || v["segments"].is_a?(Array))
319
+ end
320
+
321
+ # The browser-key view: only client-exposed flags, and only the segments they reference (directly or through
322
+ # other segments). Mirrors `clientBundle()` of the TypeScript engine.
323
+ def client_bundle(bundle)
324
+ flags = bundle["flags"].is_a?(Hash) ? bundle["flags"] : {}
325
+ pending = []
326
+ refs = lambda do |conditions|
327
+ next unless conditions.is_a?(Array)
328
+
329
+ conditions.each do |c|
330
+ op = Js.own(c, "op")
331
+ v = Js.own(c, "value")
332
+ pending << v if (op == "segment" || op == "not_segment") && v.is_a?(String)
333
+ end
334
+ end
335
+ kept = {}
336
+ flags.each do |k, f|
337
+ next unless Js.own(f, "clientExposed") == true
338
+
339
+ kept[k] = f
340
+ rules = Js.own(f, "rules")
341
+ rules.each { |r| refs.(Js.own(r, "conditions")) } if rules.is_a?(Array)
342
+ end
343
+ segments = bundle["segments"]
344
+ needed = {}
345
+ until pending.empty?
346
+ k = pending.pop
347
+ next if needed.key?(k) || !segments.is_a?(Hash) || !segments.key?(k)
348
+
349
+ needed[k] = true
350
+ refs.(Js.own(segments[k], "conditions"))
351
+ end
352
+ seg_out = segments.is_a?(Hash) ? segments.select { |k, _| needed.key?(k) } : {}
353
+ out = bundle.to_h do |k, v|
354
+ [k, case k
355
+ when "flags" then kept
356
+ when "segments" then seg_out
357
+ else v
358
+ end]
359
+ end
360
+ out["flags"] ||= kept
361
+ out["segments"] ||= seg_out
362
+ out
363
+ end
364
+
365
+ # The context attributes that the rules of +flag_key+ reference (through segments up to the engine's nesting
366
+ # limit), plus the bucketing attribute of rollouts. The SDK reports only these attribute names, with the type of
367
+ # the value and never the value, in sampled evaluation events.
368
+ def attributes_used_by(bundle, flag_key)
369
+ names = {}
370
+ segments = Js.own(bundle, "segments")
371
+ visit = lambda do |conds, depth|
372
+ # `for…of` over a non-iterable throws in the TypeScript SDK: nothing is reported.
373
+ return conds.is_a?(String) unless conds.is_a?(Array)
374
+
375
+ conds.each do |c|
376
+ op = Js.get(c, "op")
377
+ if op == "segment" || op == "not_segment"
378
+ value = Js.get(c, "value")
379
+ if value.is_a?(String)
380
+ seg = Js.own(segments, value)
381
+ return false if Js.truthy?(seg) && depth < 4 && !visit.(Js.get(seg, "conditions"), depth + 1)
382
+ end
383
+ else
384
+ attr = Js.get(c, "attribute")
385
+ names[Js.to_str(attr)] = true if Js.truthy?(attr)
386
+ end
387
+ end
388
+ true
389
+ end
390
+ rules = Js.get(Js.own(Js.own(bundle, "flags"), flag_key), "rules")
391
+ return [] unless rules.is_a?(Array)
392
+
393
+ rules.each do |r|
394
+ return [] unless visit.(Js.get(r, "conditions"), 0)
395
+
396
+ serve = Js.get(r, "serve")
397
+ if Js.get(serve, "type") == "rollout"
398
+ by = Js.get(serve, "bucketBy")
399
+ names[Js.nullish?(by) ? "key" : Js.to_str(by)] = true
400
+ end
401
+ end
402
+ names.keys
403
+ rescue StandardError
404
+ []
405
+ end
406
+ end
407
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ module NanoFlags
4
+ # An error of the client. It is reported to +on_error+ listeners and {Client#last_error}; a variation call never
5
+ # raises it. A failed update never changes the configuration in use.
6
+ #
7
+ # Codes (+code+): :network, :unauthorized, :http, :invalid_bundle, :store, :config, :signature, :engine.
8
+ class Error < StandardError
9
+ attr_reader :code, :http_status
10
+
11
+ def initialize(message, code, http_status = nil)
12
+ super(message)
13
+ @code = code
14
+ @http_status = http_status
15
+ end
16
+
17
+ def inspect = "#<NanoFlags::Error #{code}: #{message}>"
18
+ end
19
+
20
+ # A new configuration is in use. +source+ is :network, :store or :bootstrap; +transport+ is :stream (fetched after
21
+ # an event-stream notification) or :poll; +previous_revision+ is nil when nothing was loaded before.
22
+ UpdateEvent = Struct.new(:revision, :previous_revision, :checksum, :source, :transport, keyword_init: true)
23
+
24
+ # The full result of an evaluation: value, reason, matched rule, rollout bucket and a human-readable trace.
25
+ #
26
+ # +value+ is plain Ruby data (the application default for reasons "flag_not_found" and "error"); +reason+ is one of
27
+ # "rule_match", "default", "off", "flag_not_found", "error"; +revision+ is the evaluated revision (0 without one);
28
+ # +rule_index+ / +rule_id+ identify the matching rule; +in_rollout+ and +bucket+ (0–99.99) are set for percentage
29
+ # rollouts; +error+ explains reason "error"; +trace+ is a list of {Engine::TraceStep}.
30
+ class EvaluationDetail
31
+ attr_reader :flag_key, :value, :reason, :revision, :rule_index, :rule_id, :in_rollout, :bucket, :trace, :error
32
+
33
+ def initialize(flag_key:, value:, reason:, revision:, rule_index: nil, rule_id: nil, in_rollout: nil, bucket: nil, trace: [], error: nil, raw: nil)
34
+ @flag_key = flag_key
35
+ @value = value
36
+ @reason = reason
37
+ @revision = revision
38
+ @rule_index = rule_index
39
+ @rule_id = rule_id
40
+ @in_rollout = in_rollout
41
+ @bucket = bucket
42
+ @trace = trace.freeze
43
+ @error = error
44
+ @raw = raw
45
+ freeze
46
+ end
47
+
48
+ # @api private
49
+ def self.from_result(r, default)
50
+ js = Engine::Js
51
+ use_default = r.reason == "flag_not_found" || r.reason == "error"
52
+ rev = js.to_number(r.revision)
53
+ rule_id = nil
54
+ if !r.rule_index.nil? && !r.rule_id.equal?(Engine::UNDEFINED)
55
+ rule_id = r.rule_id.is_a?(String) ? r.rule_id : js.stringify(r.rule_id)
56
+ end
57
+ new(
58
+ flag_key: r.flag_key,
59
+ value: use_default ? default : js.to_ruby(r.value),
60
+ reason: r.reason,
61
+ revision: rev.finite? ? rev.to_i : 0,
62
+ rule_index: r.rule_index,
63
+ rule_id: rule_id,
64
+ in_rollout: r.in_rollout,
65
+ bucket: r.bucket,
66
+ trace: r.trace,
67
+ error: r.error,
68
+ raw: use_default ? js.from_ruby(default) : r.value
69
+ )
70
+ end
71
+
72
+ # The served value as JSON text (object keys in configuration order), or nil when nothing was served.
73
+ def json = Engine::Js.stringify(@raw)
74
+
75
+ # The type of the served value: "boolean", "string", "number", "array", "object", "null" or "undefined".
76
+ def type_name = Engine::Js.type_name(@raw)
77
+
78
+ def to_h
79
+ {
80
+ flag_key: flag_key, value: value, reason: reason, revision: revision, rule_index: rule_index, rule_id: rule_id,
81
+ in_rollout: in_rollout, bucket: bucket, trace: trace.map(&:to_h), error: error
82
+ }
83
+ end
84
+
85
+ def inspect = "#<NanoFlags::EvaluationDetail #{flag_key}=#{value.inspect} (#{reason}, r#{revision})>"
86
+ end
87
+ end