nanoflags 0.1.0 → 0.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.
@@ -1,407 +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
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