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,869 +1,1225 @@
1
- # frozen_string_literal: true
2
-
3
- require "json"
4
- require "monitor"
5
- require "time"
6
-
7
- module NanoFlags
8
- # The NanoFlags client for Ruby servers (Rails, Puma, Sidekiq, Rack, plain scripts).
9
- #
10
- # Flags are evaluated locally and synchronously against an in-memory bundle; a variation call never performs I/O
11
- # and never raises. The network is used in background threads only: to load the bundle (`/v1/bundle`, with ETag
12
- # revalidation), to hear about new revisions as soon as they are published (server-sent events, `/v1/stream`,
13
- # with polling as the safety net), and to send sampled telemetry plus the periodic service report (`/v1/events`).
14
- #
15
- # Create one client per process and share it between threads. It is fork-safe: after a fork (Puma and Unicorn
16
- # workers, Passenger, Resque, Sidekiq Swarm) the child keeps the configuration it inherited and restarts the
17
- # background threads on its first call (a child that never evaluates a flag never opens a connection). Events
18
- # queued before the fork are sent by the parent only.
19
- #
20
- # FLAGS = NanoFlags::Client.new(ENV.fetch("NANOFLAGS_SDK_KEY"), service: "checkout-api")
21
- # FLAGS.wait_until_ready(5)
22
- # FLAGS.bool_variation("new-checkout", false, { key: current_user.id, plan: current_user.plan })
23
- class Client
24
- STATUS_NOT_READY = "not-ready"
25
- STATUS_READY = "ready"
26
- STATUS_STALE = "stale"
27
-
28
- MAX_QUEUE = 500
29
- MAX_BATCH = 50
30
- MAX_EVENT_VALUE_CHARS = 1024
31
- KEYS_REFETCH = 60.0
32
- ACCEPT_BOOL = ->(v) { v == true || v == false }
33
- ACCEPT_STRING = ->(v) { v.is_a?(String) }
34
- ACCEPT_NUMBER = ->(v) { v.is_a?(Float) && v.finite? }
35
- ACCEPT_ANY = ->(v) { !v.equal?(Engine::UNDEFINED) }
36
-
37
- REGISTRY = ObjectSpace::WeakMap.new
38
- REGISTRY_LOCK = Mutex.new
39
- private_constant :REGISTRY, :REGISTRY_LOCK
40
-
41
- attr_reader :base_url, :service
42
-
43
- # @param sdk_key [String] `nf_srv_…` (server view) or `nf_pub_…` (client-exposed flags only)
44
- # @param base_url [String] the edge; signatures are verified by default on the hosted edge
45
- # @param service [String, nil] the name shown in "which revision is each service running"
46
- # @param poll_interval [Numeric] seconds between polls (0 disables polling)
47
- # @param streaming [Boolean] hear about new revisions over server-sent events (false: polling only)
48
- # @param bootstrap [Hash, String, nil] a bundle (Hash or JSON text) to use until the edge answers
49
- # @param cache_path [String, nil] keep the last good bundle in this file (restored, and verified again, on start)
50
- # @param store [#get, #set, nil] custom persistence; overrides +cache_path+
51
- # @param events [Hash, false, nil] telemetry: false disables it; a Hash with :sample_rate (0.1), :flush_interval
52
- # (10 s), :report_interval (60 s), :redact (a callable receiving the context Hash)
53
- # @param verify [Hash, Boolean, nil] signature verification: nil (default) on for the hosted edge; false off;
54
- # true on with keys from the edge's /v1/keys; a Hash with :public_keys (JWKs), :require, :fetch_keys
55
- # @param on_change [#call, nil] called with an {UpdateEvent} whenever a new configuration is adopted
56
- # @param on_error [#call, nil] called with an {Error} for background failures
57
- # @param logger [Logger, nil] debug output of the background activity
58
- # @param start [Boolean] false defers the background work until {#start}
59
- # @param http [#call, nil] the transport (see {HTTP::NetHttp})
60
- def initialize(sdk_key, base_url: OFFICIAL_EDGE_URL, service: nil, poll_interval: 30, streaming: true, bootstrap: nil,
61
- cache_path: nil, store: nil, events: nil, verify: nil, on_change: nil, on_error: nil, logger: nil,
62
- start: true, http: nil, request_timeout: 10, stream_read_timeout: 90, random: nil)
63
- @sdk_key = sdk_key.to_s
64
- @base_url = base_url.to_s.sub(%r{/+\z}, "")
65
- @service = service.to_s.empty? ? "unknown" : service.to_s
66
- @poll_interval = poll_interval.to_f
67
- @streaming = streaming
68
- @request_timeout = request_timeout.to_f
69
- @stream_read_timeout = stream_read_timeout.to_f
70
- @http = http || HTTP::NetHttp.new
71
- @logger = logger
72
- @random = random || -> { rand }
73
- @id = format("%08x", Engine.murmur3("#{@base_url}|#{@sdk_key}"))
74
- @browser_key = @sdk_key.start_with?("nf_pub_")
75
- @store = store || (cache_path ? Store::File.new(cache_path) : nil)
76
- @pending_errors = []
77
-
78
- ev = events.is_a?(Hash) ? events.transform_keys(&:to_sym) : {}
79
- @events_enabled = events != false
80
- @sample_rate = Float(ev.fetch(:sample_rate, 0.1)).clamp(0.0, 1.0)
81
- @flush_interval = Float(ev.fetch(:flush_interval, 10.0))
82
- @report_interval = Float(ev.fetch(:report_interval, 60.0))
83
- @redact = ev[:redact]
84
-
85
- setup_verifier(verify)
86
- @fetched_keys = []
87
- @keys_fetched_at = nil
88
-
89
- @listeners = { change: [], error: [], status: [] }
90
- @listeners[:change] << on_change if on_change
91
- @listeners[:error] << on_error if on_error
92
-
93
- @bundle = nil
94
- @etag = nil
95
- @checksum = nil
96
- @sig = nil
97
- @raw = nil
98
- @status = STATUS_NOT_READY
99
- @last_error = nil
100
- @pinned_env = nil
101
- @failures = 0
102
- @closed = false
103
- @started = false
104
- @ready = false
105
- @stream_open = false
106
- @queue = []
107
- @last_report = monotonic
108
- @attrs = {}
109
- @attrs_for = nil
110
- init_concurrency
111
-
112
- if @sdk_key.strip.empty?
113
- @pending_errors << Error.new("An SDK key is required.", :config)
114
- end
115
- @pending_errors << Error.new("The base URL must be an http(s) URL, got #{base_url.inspect}.", :config) unless @base_url.match?(%r{\Ahttps?://}i)
116
- adopt_bootstrap(bootstrap) unless bootstrap.nil?
117
- REGISTRY_LOCK.synchronize { REGISTRY[self] = true }
118
- Client.install_exit_hook
119
- self.start if start
120
- end
121
-
122
- # ------------------------------------------------------------------ lifecycle
123
-
124
- # Starts the background threads (done by the constructor unless +start: false+).
125
- def start
126
- check_fork
127
- @mutex.synchronize do
128
- return self if @started || @closed
129
-
130
- @started = true
131
- end
132
- pending = @pending_errors
133
- @pending_errors = []
134
- pending.each { |e| emit_error(e) }
135
- if pending.any? { |e| e.code == :config && e.message.start_with?("An SDK key", "The base URL") }
136
- mark_ready
137
- return self
138
- end
139
- spawn("nanoflags-poll") { main_loop }
140
- self
141
- end
142
-
143
- # Stops the background threads after a best-effort final telemetry flush (at most 2 seconds). Evaluations keep
144
- # working on the last configuration. Idempotent.
145
- def close
146
- return if @closed
147
-
148
- flush(timeout: 2) if @started && Process.pid == @pid
149
- @mutex.synchronize do
150
- @closed = true
151
- @cv.broadcast
152
- @sleep_cv.broadcast
153
- end
154
- close_stream
155
- mark_ready
156
- @threads.each { |t| t.join(2) unless t == Thread.current }
157
- nil
158
- end
159
-
160
- def closed? = @closed
161
-
162
- # Blocks until the first load attempt has finished (or a configuration was adopted); returns whether a
163
- # configuration is in use. +timeout+ in seconds (nil: no limit).
164
- def wait_until_ready(timeout = nil)
165
- check_fork
166
- deadline = timeout && (monotonic + timeout)
167
- @mutex.synchronize do
168
- until @ready
169
- left = deadline && (deadline - monotonic)
170
- break if left && left <= 0
171
-
172
- @ready_cv.wait(left)
173
- end
174
- end
175
- !@bundle.nil?
176
- end
177
-
178
- # "not-ready", "ready" (known to be current) or "stale" (in use, not known to be current).
179
- def status = @status
180
-
181
- # The revision in use, or nil.
182
- def revision = @bundle && @bundle["revision"].to_i
183
-
184
- # True when a configuration is in use (ready or stale).
185
- def initialized? = !@bundle.nil?
186
-
187
- # :stream while the event stream is connected, otherwise :poll.
188
- def transport = @stream_open ? :stream : :poll
189
-
190
- # The last background error, if any.
191
- def last_error = @last_error
192
-
193
- # The bundle in use as JSON text (the signed bytes when it was signed), or nil.
194
- def bundle_json = @raw || (@bundle && Engine::Js.stringify(@bundle))
195
-
196
- # Registers a listener: +:change+ ({UpdateEvent}), +:error+ ({Error}) or +:status+ (a status string). Returns a
197
- # lambda that removes it. Listeners run on a background thread; exceptions they raise are swallowed.
198
- def on(event, callable = nil, &block)
199
- fn = callable || block
200
- list = @listeners.fetch(event.to_sym) { raise ArgumentError, "unknown event #{event.inspect}" }
201
- list << fn
202
- -> { list.delete(fn) }
203
- end
204
-
205
- def on_change(callable = nil, &block) = on(:change, callable, &block)
206
- def on_error(callable = nil, &block) = on(:error, callable, &block)
207
-
208
- # Revalidates now (blocking) and returns whether a configuration is in use. Errors are reported, never raised.
209
- def refresh
210
- check_fork
211
- sync
212
- initialized?
213
- end
214
-
215
- # ------------------------------------------------------------------ evaluation
216
-
217
- # The boolean value of +key+ for +context+; +default+ when the flag is unknown, not a boolean, or nothing is loaded.
218
- def bool_variation(key, default, context = nil) = run(key, default, context, ACCEPT_BOOL).value
219
- def string_variation(key, default, context = nil) = run(key, default, context, ACCEPT_STRING).value
220
- # A number flag; whole numbers are returned as Integer.
221
- def number_variation(key, default, context = nil) = run(key, default, context, ACCEPT_NUMBER).value
222
- # A JSON flag as plain Ruby data (Hash with String keys, Array, …); any served value is accepted.
223
- def json_variation(key, default, context = nil) = run(key, default, context, ACCEPT_ANY).value
224
-
225
- def bool_variation_detail(key, default, context = nil) = run(key, default, context, ACCEPT_BOOL)
226
- def string_variation_detail(key, default, context = nil) = run(key, default, context, ACCEPT_STRING)
227
- def number_variation_detail(key, default, context = nil) = run(key, default, context, ACCEPT_NUMBER)
228
- def json_variation_detail(key, default, context = nil) = run(key, default, context, ACCEPT_ANY)
229
-
230
- # The full engine result ({EvaluationDetail}) without any type check.
231
- def evaluate(key, default, context = nil) = run(key, default, context, nil)
232
-
233
- # Every flag of the configuration in use evaluated for +context+ ({} when nothing is loaded). Not sampled into
234
- # telemetry.
235
- def all_flags(context = nil)
236
- all_flags_detail(context).transform_values(&:value)
237
- end
238
-
239
- def all_flags_detail(context = nil)
240
- b = @bundle
241
- return {} if b.nil?
242
-
243
- ctx = to_context(context)
244
- out = {}
245
- b["flags"].each_key do |k|
246
- r = Engine.evaluate(b, k, ctx, nil)
247
- out[k] = EvaluationDetail.from_result(r, nil) unless r.reason == "flag_not_found"
248
- end
249
- out
250
- rescue StandardError
251
- {}
252
- end
253
-
254
- # ------------------------------------------------------------------ fork safety
255
-
256
- # @api private
257
- def self.install_exit_hook
258
- REGISTRY_LOCK.synchronize do
259
- return if @exit_hook
260
-
261
- @exit_hook = true
262
- at_exit { each_client { |c| c.close unless c.closed? } }
263
- end
264
- end
265
-
266
- # @api private
267
- def self.each_client(&block)
268
- clients = REGISTRY_LOCK.synchronize { REGISTRY.keys }
269
- clients.each(&block)
270
- end
271
-
272
- # Restarts the background threads of every client in a forked child now (for example from Puma's
273
- # +on_worker_boot+). Optional: a client notices the fork on its first call in the child and restarts then.
274
- def self.after_fork
275
- each_client { |c| c.send(:check_fork) }
276
- end
277
-
278
- private
279
-
280
- def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
281
-
282
- def init_concurrency
283
- @pid = Process.pid
284
- @mutex = Monitor.new
285
- @cv = @mutex.new_cond # wakes the poll loop (sync requested, close)
286
- @sleep_cv = @mutex.new_cond # wakes the other loops (close)
287
- @ready_cv = @mutex.new_cond
288
- @sync_mutex = Mutex.new
289
- @keys_mutex = Mutex.new
290
- @queue_mutex = Mutex.new
291
- @threads = []
292
- @sync_requested = false
293
- @stream_closer = nil
294
- @stream_thread = nil
295
- @stream_active = false
296
- @stream_gen = 0
297
- end
298
-
299
- # A fork keeps the configuration but not the threads: restart them in the child, and drop the parent's queued
300
- # events (the parent sends those).
301
- def check_fork
302
- return if Process.pid == @pid
303
-
304
- FORK_LOCK.synchronize do
305
- return if Process.pid == @pid
306
-
307
- was_started = @started
308
- init_concurrency
309
- @queue = []
310
- @stream_open = false
311
- @started = false
312
- @last_report = monotonic
313
- start if was_started && !@closed
314
- end
315
- end
316
-
317
- FORK_LOCK = Mutex.new
318
-
319
- def spawn(name, &block)
320
- t = Thread.new do
321
- Thread.current.name = name
322
- Thread.current.report_on_exception = false
323
- block.call
324
- rescue StandardError => e
325
- log { "#{name} stopped: #{e.class}: #{e.message}" }
326
- end
327
- @threads << t
328
- t
329
- end
330
-
331
- def log
332
- @logger&.debug("nanoflags") { yield }
333
- end
334
-
335
- def mark_ready
336
- @mutex.synchronize do
337
- @ready = true
338
- @ready_cv.broadcast
339
- end
340
- end
341
-
342
- def fire(event, arg)
343
- @listeners[event].dup.each do |fn|
344
- fn.call(arg)
345
- rescue StandardError => e
346
- log { "#{event} listener raised #{e.class}: #{e.message}" }
347
- end
348
- end
349
-
350
- def emit_error(e)
351
- @last_error = e
352
- log { "#{e.code}: #{e.message}" }
353
- fire(:error, e)
354
- end
355
-
356
- def set_status(status)
357
- changed = @mutex.synchronize do
358
- old = @status
359
- @status = status
360
- old != status
361
- end
362
- fire(:status, status) if changed
363
- end
364
-
365
- def setup_verifier(verify)
366
- official = @base_url == OFFICIAL_EDGE_URL
367
- official_keys = -> { Signature.import_keys(OFFICIAL_SIGNING_KEYS) }
368
- @verifier =
369
- case verify
370
- when false then nil
371
- when nil then official ? { base: official_keys.(), require: true, refetch: true } : nil
372
- when true then official ? { base: official_keys.(), require: true, refetch: true } : { base: [], require: true, refetch: true }
373
- when Hash
374
- v = verify.transform_keys(&:to_sym)
375
- req = v.key?(:require) ? v[:require] : official
376
- keys = v[:public_keys]
377
- if keys.is_a?(Array) && !keys.empty?
378
- unless keys.all? { |k| Signature.public_ed25519_jwk?(k.is_a?(Hash) ? k.transform_keys(&:to_s) : k) }
379
- @pending_errors << Error.new("`verify[:public_keys]` must contain public Ed25519 JWKs only. Other entries (including private keys) were ignored.", :config)
380
- end
381
- { base: Signature.import_keys(keys), require: req, refetch: v.fetch(:fetch_keys, false) }
382
- elsif v[:fetch_keys] || !official
383
- { base: [], require: req, refetch: true }
384
- else
385
- { base: official_keys.(), require: req, refetch: true }
386
- end
387
- else raise ArgumentError, "verify must be nil, true, false or a Hash"
388
- end
389
- end
390
-
391
- def adopt_bootstrap(bootstrap)
392
- b = bootstrap.is_a?(String) ? Engine::Json.parse(bootstrap) : Engine::Js.from_ruby(bootstrap)
393
- if !Engine.bundle?(b)
394
- @pending_errors << Error.new("The bootstrap bundle is invalid and was ignored.", :invalid_bundle)
395
- elsif !Engine.supports_engine?(b.fetch("engine", Engine::UNDEFINED))
396
- @pending_errors << engine_error(b)
397
- else
398
- adopt(b, etag: nil, checksum: nil, sig: nil, raw: nil, status: STATUS_READY, source: :bootstrap, transport: :poll)
399
- end
400
- rescue Engine::InvalidJsonError
401
- @pending_errors << Error.new("The bootstrap bundle is invalid and was ignored.", :invalid_bundle)
402
- end
403
-
404
- def engine_error(b)
405
- Error.new("Bundle r#{Engine::Js.to_str(b.fetch("revision", Engine::UNDEFINED))} needs evaluation engine #{Engine::Js.stringify(b.fetch("engine", Engine::UNDEFINED)) || "undefined"}; " \
406
- "this SDK supports up to #{Engine::VERSION}. Upgrade the nanoflags gem. The configuration in use is unchanged.", :engine)
407
- end
408
-
409
- def adopt(bundle, etag:, checksum:, sig:, raw:, status:, source:, transport:)
410
- event = nil
411
- @mutex.synchronize do
412
- prev = @bundle
413
- prev_rev = prev && prev["revision"].to_i
414
- is_new = prev.nil? || prev_rev != bundle["revision"].to_i || @checksum != checksum
415
- @bundle = bundle # one assignment: every evaluation sees one consistent revision
416
- @etag = etag
417
- @checksum = checksum
418
- @sig = sig
419
- @raw = raw
420
- event = UpdateEvent.new(revision: bundle["revision"].to_i, previous_revision: prev_rev, checksum: checksum, source: source, transport: transport) if is_new
421
- end
422
- set_status(status)
423
- mark_ready
424
- fire(:change, event) if event
425
- end
426
-
427
- # ------------------------------------------------------------------ evaluation internals
428
-
429
- def to_context(context)
430
- return {} if context.nil?
431
-
432
- v = Engine::Js.from_ruby(context)
433
- v.is_a?(Hash) ? v : {}
434
- end
435
-
436
- def run(key, default, context, accepts)
437
- check_fork
438
- b = @bundle
439
- ctx = to_context(context)
440
- fallback = Engine::Js.from_ruby(default)
441
- r = Engine.evaluate(b, key.to_s, ctx, fallback)
442
- if accepts && r.reason != "flag_not_found" && r.reason != "error" && !accepts.(r.value)
443
- error = "Flag \"#{key}\" has a #{Engine::Js.type_name(r.value)} value, which does not match the requested type."
444
- r = Engine::Result.new(key.to_s, fallback, "error", r.revision, nil, Engine::UNDEFINED, nil, nil,
445
- r.trace + [Engine::TraceStep.new("result", "Returned the fallback", error)], error)
446
- end
447
- record(r, context, ctx, b)
448
- EvaluationDetail.from_result(r, default)
449
- rescue StandardError => e
450
- EvaluationDetail.new(flag_key: key.to_s, value: default, reason: "error", revision: 0, error: e.message)
451
- end
452
-
453
- # ------------------------------------------------------------------ background loop
454
-
455
- def main_loop
456
- restore
457
- sync
458
- mark_ready # even without a bundle: callers must not hang; they check `status`
459
- return if @closed
460
-
461
- spawn("nanoflags-events") { events_loop } if @events_enabled && @flush_interval.positive?
462
- start_stream if @streaming
463
- loop do
464
- @mutex.synchronize do
465
- return if @closed
466
-
467
- unless @sync_requested
468
- if @poll_interval.positive?
469
- @cv.wait(next_delay)
470
- else
471
- @cv.wait
472
- end
473
- end
474
- return if @closed
475
-
476
- @sync_requested = false
477
- end
478
- sync
479
- end
480
- end
481
-
482
- def request_sync
483
- @mutex.synchronize do
484
- @sync_requested = true
485
- @cv.broadcast
486
- end
487
- end
488
-
489
- def next_delay
490
- jitter = 0.8 + (0.4 * @random.call)
491
- base = @failures.positive? ? [@poll_interval, 2.0**[@failures - 1, 10].min].min : @poll_interval
492
- [0.25, base * jitter].max
493
- end
494
-
495
- def headers(extra = nil)
496
- h = { "Authorization" => "Bearer #{@sdk_key}", "User-Agent" => "nanoflags-ruby/#{VERSION}" }
497
- extra ? h.merge(extra) : h
498
- end
499
-
500
- def request(method, path, extra_headers = nil, body = nil, timeout = @request_timeout)
501
- @http.call(method, "#{@base_url}#{path}", headers(extra_headers), body, timeout)
502
- end
503
-
504
- def sync
505
- @sync_mutex.synchronize { sync_once unless @closed }
506
- end
507
-
508
- def sync_once
509
- transport = @stream_triggered ? :stream : :poll
510
- @stream_triggered = false
511
- begin
512
- res = begin
513
- request("GET", "/v1/bundle", @etag ? { "If-None-Match" => @etag } : nil)
514
- rescue StandardError => e
515
- raise Error.new("Could not reach the NanoFlags edge: #{e.message}", :network)
516
- end
517
- return if @closed
518
-
519
- served_stale = res.header("X-NanoFlags-Stale") == "true"
520
- if res.status == 304 && @bundle
521
- @failures = 0
522
- set_status(served_stale ? STATUS_STALE : STATUS_READY)
523
- return
524
- end
525
- raise Error.new("The SDK key was rejected (unknown or revoked).", :unauthorized, res.status) if [401, 403].include?(res.status)
526
- raise Error.new("Bundle request failed with HTTP #{res.status}.", :http, res.status) unless res.ok?
527
-
528
- body = begin
529
- Engine::Json.parse(res.body)
530
- rescue Engine::InvalidJsonError
531
- nil
532
- end
533
- raise Error.new("The edge returned an invalid bundle.", :invalid_bundle) unless body.is_a?(Hash) && Engine.bundle?(body["bundle"])
534
-
535
- bundle = body["bundle"]
536
- sig, raw = check_signature(res, body, bundle)
537
- return if @closed
538
- raise engine_error(bundle) unless Engine.supports_engine?(bundle.fetch("engine", Engine::UNDEFINED))
539
-
540
- @failures = 0
541
- cur = @bundle
542
- # The edge is serving its last-known-good copy: never go backwards because of it.
543
- if served_stale && cur && cur["revision"] >= bundle["revision"]
544
- set_status(STATUS_STALE)
545
- return
546
- end
547
- checksum = body["checksum"].is_a?(String) ? body["checksum"] : nil
548
- @pinned_env = sig.environment_id if sig
549
- adopt(bundle, etag: res.header("ETag"), checksum: checksum, sig: sig, raw: raw,
550
- status: served_stale ? STATUS_STALE : STATUS_READY, source: :network, transport: transport)
551
- persist
552
- rescue Error => e
553
- return if @closed
554
-
555
- if e.code == :engine
556
- emit_error(e)
557
- return
558
- end
559
- @failures += 1
560
- if e.code == :signature
561
- emit_error(e) # same bundle, same status; polling retries with backoff
562
- return
563
- end
564
- set_status(STATUS_STALE) if @bundle
565
- emit_error(e)
566
- end
567
- end
568
-
569
- # Verifies a /v1/bundle response (when verification is on); returns [signature info or nil, bundle text to keep].
570
- def check_signature(res, body, bundle)
571
- raw = Signature.raw_member(res.body, "bundle")
572
- return [nil, raw] unless @verifier
573
-
574
- rev = bundle["revision"].to_i
575
- reject = ->(why) { Error.new("Bundle r#{rev} was rejected: #{why} The configuration in use is unchanged.", :signature) }
576
- unless res.header("X-NanoFlags-Signed") == "true"
577
- raise reject.("it is not signed (the edge is still distributing it) and unsigned bundles are refused; fetching again shortly.") if @verifier[:require]
578
-
579
- return [nil, raw]
580
- end
581
- signature = res.header("X-NanoFlags-Signature")
582
- env_id = res.header("X-NanoFlags-Environment-Id")
583
- kid = res.header("X-NanoFlags-Key-Id")
584
- checksum = body["checksum"]
585
- raise reject.("the signature headers are incomplete.") if signature.to_s.empty? || env_id.to_s.empty? || !checksum.is_a?(String)
586
- raise reject.("the signed revision does not match the bundle.") if body["revision"].is_a?(Float) && body["revision"].to_i != rev
587
- raise reject.("it was signed for a different environment.") if @pinned_env && @pinned_env != env_id
588
-
589
- info = Signature::Info.new(signature, kid.to_s.empty? ? nil : kid, env_id, rev, checksum)
590
- keys = begin
591
- load_keys(info.kid)
592
- rescue StandardError => e
593
- raise reject.("the signing keys could not be loaded (#{e.message}).")
594
- end
595
- # The edge embeds the stored bundle text byte-for-byte; re-serialisation is the fallback.
596
- return [info, raw] if raw && Signature.verify(keys, info, raw)
597
-
598
- again = Engine::Js.stringify(bundle)
599
- return [info, again] if again && again != raw && Signature.verify(keys, info, again)
600
-
601
- raise reject.("its signature does not verify.")
602
- end
603
-
604
- # The pinned or embedded keys plus those of /v1/keys; an unknown key id reloads /v1/keys (at most once a minute).
605
- def load_keys(kid)
606
- v = @verifier
607
- return [] unless v
608
- return v[:base] unless v[:refetch]
609
-
610
- @keys_mutex.synchronize do
611
- known = v[:base] + @fetched_keys
612
- return known if !known.empty? && (kid.nil? || known.any? { |k| k.kid == kid })
613
- return known if @keys_fetched_at && monotonic - @keys_fetched_at < KEYS_REFETCH
614
-
615
- begin
616
- # Public endpoint: the SDK key is deliberately not sent.
617
- res = @http.call("GET", "#{@base_url}/v1/keys", { "User-Agent" => "nanoflags-ruby/#{VERSION}" }, nil, @request_timeout)
618
- raise Error.new("Signing keys request failed with HTTP #{res.status}.", :signature, res.status) unless res.status == 200
619
-
620
- parsed = JSON.parse(res.body)
621
- keys = Signature.import_keys(parsed.is_a?(Hash) && parsed["keys"].is_a?(Array) ? parsed["keys"] : [])
622
- raise Error.new("The edge returned no usable signing keys.", :signature) if keys.empty?
623
-
624
- @fetched_keys = keys
625
- rescue StandardError
626
- raise if v[:base].empty?
627
- ensure
628
- @keys_fetched_at = monotonic
629
- end
630
- v[:base] + @fetched_keys
631
- end
632
- end
633
-
634
- # ------------------------------------------------------------------ persistence
635
-
636
- def persist
637
- return unless @store
638
-
639
- payload = @mutex.synchronize do
640
- p = { "v" => 1, "id" => @id, "etag" => @etag, "checksum" => @checksum, "savedAt" => Time.now.utc.iso8601(3), "bundle" => Engine::Js.stringify(@bundle) }
641
- if @sig
642
- p["sig"] = @sig.to_h
643
- p["raw"] = @raw if @raw
644
- end
645
- p
646
- end
647
- # "bundle" is JSON text inside the document, so the persisted bytes survive any re-encoding by the store.
648
- @store.set(JSON.generate(payload))
649
- rescue StandardError => e
650
- emit_error(Error.new("Could not persist the bundle: #{e.message}", :store))
651
- end
652
-
653
- def restore
654
- return unless @store
655
-
656
- text = @store.get
657
- return if text.nil? || text.empty? || @closed
658
-
659
- p = JSON.parse(text)
660
- return unless p.is_a?(Hash) && p["v"] == 1 && p["id"] == @id && p["bundle"].is_a?(String)
661
-
662
- restored = Engine::Json.parse(p["bundle"])
663
- return unless Engine.bundle?(restored)
664
- return emit_error(engine_error(restored)) unless Engine.supports_engine?(restored.fetch("engine", Engine::UNDEFINED))
665
- return if @bundle && @bundle["revision"] >= restored["revision"]
666
-
667
- sig = nil
668
- raw = nil
669
- if @verifier
670
- # The store is outside the trust boundary: a signed copy must verify again; with `require` an unsigned copy
671
- # is not used at all.
672
- s = Signature::Info.from_h(p["sig"])
673
- if s && s.revision == restored["revision"].to_i
674
- raw = p["raw"].is_a?(String) ? p["raw"] : p["bundle"]
675
- ok = begin
676
- Signature.verify(load_keys(s.kid), s, raw) && (parsed = Engine::Json.parse(raw)) && Engine.bundle?(parsed) && parsed["revision"].to_i == s.revision
677
- rescue StandardError
678
- false
679
- end
680
- return emit_error(Error.new("The persisted bundle failed signature verification and was ignored.", :signature)) unless ok
681
-
682
- restored = parsed
683
- sig = s
684
- @pinned_env ||= s.environment_id
685
- elsif @verifier[:require]
686
- return
687
- end
688
- end
689
- # Usable but not known to be current: stale until the edge confirms it.
690
- adopt(restored, etag: p["etag"], checksum: p["checksum"], sig: sig, raw: raw, status: STATUS_STALE, source: :store, transport: :poll)
691
- rescue StandardError => e
692
- emit_error(Error.new("Could not read the persisted bundle: #{e.message}", :store))
693
- end
694
-
695
- # ------------------------------------------------------------------ event stream (SSE)
696
-
697
- def start_stream
698
- gen = @mutex.synchronize do
699
- return if @closed || !@streaming || @stream_active
700
-
701
- @stream_active = true
702
- @stream_gen += 1
703
- end
704
- @stream_thread = spawn("nanoflags-stream") { stream_loop(gen) }
705
- end
706
-
707
- def close_stream
708
- closer, thread = @mutex.synchronize do
709
- @stream_gen += 1
710
- @stream_active = false
711
- [@stream_closer, @stream_thread]
712
- end
713
- begin
714
- closer&.call
715
- rescue StandardError
716
- nil
717
- end
718
- # A read blocked inside OpenSSL does not always notice the socket closing under it: the thread only reads.
719
- thread.kill if thread && thread != Thread.current && !thread.join(0.2)
720
- nil
721
- end
722
-
723
- def stream_loop(gen)
724
- attempt = 0
725
- current = -> { !@closed && gen == @stream_gen && Process.pid == @pid }
726
- while current.()
727
- started = monotonic
728
- stop = false
729
- begin
730
- status = @http.stream("#{@base_url}/v1/stream", headers("Accept" => "text/event-stream"),
731
- open_timeout: @request_timeout, read_timeout: @stream_read_timeout,
732
- on_open: ->(closer) { @stream_closer = closer }) do |event, data|
733
- next :stop unless current.()
734
-
735
- @stream_open = true
736
- case event
737
- when "revision" then on_revision(data)
738
- when "revoked"
739
- stop = true
740
- request_sync
741
- next :stop
742
- end
743
- nil
744
- end
745
- stop = true if [401, 403].include?(status) # polling keeps reporting the error
746
- rescue StandardError => e
747
- log { "stream failed: #{e.class}: #{e.message}" }
748
- ensure
749
- @stream_open = false
750
- @stream_closer = nil
751
- end
752
- return unless current.()
753
-
754
- if stop
755
- @mutex.synchronize { @stream_active = false if gen == @stream_gen }
756
- return
757
- end
758
- attempt = monotonic - started > 30 ? 0 : attempt + 1
759
- wait = [30.0, 2.0**[attempt, 5].min].min * (0.5 + @random.call)
760
- @mutex.synchronize { @sleep_cv.wait(wait) unless @closed }
761
- end
762
- end
763
-
764
- def on_revision(data)
765
- m = JSON.parse(data)
766
- return unless m.is_a?(Hash)
767
-
768
- b = @bundle
769
- return unless b.nil? || m["revision"] != b["revision"].to_i || m["checksum"] != @checksum || @status != STATUS_READY
770
-
771
- @stream_triggered = true
772
- request_sync
773
- rescue JSON::ParserError
774
- nil
775
- end
776
-
777
- # ------------------------------------------------------------------ telemetry
778
-
779
- def attrs_used_by(bundle, flag_key)
780
- return [] if bundle.nil?
781
-
782
- unless @attrs_for.equal?(bundle)
783
- @attrs = {}
784
- @attrs_for = bundle
785
- end
786
- @attrs[flag_key] ||= Engine.attributes_used_by(bundle, flag_key)
787
- end
788
-
789
- def record(r, user_context, ctx, bundle)
790
- return if !@events_enabled || @closed || @sample_rate <= 0 || @random.call >= @sample_rate
791
-
792
- context =
793
- if @redact
794
- c = Engine::Js.from_ruby(@redact.call(user_context.is_a?(Hash) ? user_context.dup : Engine::Js.to_ruby(ctx)))
795
- c.is_a?(Hash) ? c : {}
796
- else
797
- # No attribute values: only the names the flag's rules use that are present, with the value's type.
798
- attrs_used_by(bundle, r.flag_key).each_with_object({}) do |name, h|
799
- v = ctx.fetch(name, Engine::UNDEFINED)
800
- h[name] = Engine::Js.type_name(v) unless v.equal?(Engine::UNDEFINED)
801
- end
802
- end
803
- rev = Engine::Js.to_number(r.revision)
804
- ev = { "flagKey" => truncate(r.flag_key, 63), "value" => event_value(r.value), "reason" => r.reason }
805
- ev["ruleIndex"] = r.rule_index.to_f unless r.rule_index.nil?
806
- ev["revision"] = rev.finite? ? rev.to_i.to_f : 0.0
807
- ev["context"] = context
808
- ev["at"] = Time.now.utc.strftime("%Y-%m-%dT%H:%M:%S.%LZ")
809
- ev["sampleRate"] = @sample_rate
810
- text = Engine::Js.stringify(ev)
811
- @queue_mutex.synchronize { @queue << text if @queue.length < MAX_QUEUE } # bounded: drop instead of growing
812
- rescue StandardError
813
- nil # telemetry must never affect evaluation
814
- end
815
-
816
- def event_value(v)
817
- return truncate(v, MAX_EVENT_VALUE_CHARS) if v.is_a?(String)
818
-
819
- text = Engine::Js.stringify(v)
820
- return nil if text.nil? || ((v.is_a?(Array) || v.is_a?(Hash)) && Engine::Js.utf16_length(text) > MAX_EVENT_VALUE_CHARS)
821
-
822
- v
823
- end
824
-
825
- def truncate(s, n)
826
- return s if s.bytesize <= n || Engine::Js.utf16_length(s) <= n
827
-
828
- Engine::Js.units_to_string(Engine::Js.to_units(s).first(n))
829
- end
830
-
831
- public
832
-
833
- # Sends queued telemetry and the service report now (blocking, best effort, never raises).
834
- def flush(timeout: @request_timeout)
835
- return unless @events_enabled
836
-
837
- batch = @queue_mutex.synchronize { @queue.shift(MAX_BATCH) }
838
- @last_report = monotonic
839
- rev = revision || 0
840
- body = %({"service":#{Engine::Js.quote(truncate(@service, 60))},"sdk":"ruby/#{VERSION}","revision":#{[rev, 0].max},"events":[#{batch.join(",")}]})
841
- request("POST", "/v1/events", { "Content-Type" => "application/json" }, body, timeout)
842
- nil
843
- rescue StandardError
844
- nil # dropped on failure, by design: telemetry is never retried
845
- end
846
-
847
- def inspect
848
- "#<NanoFlags::Client base_url=#{@base_url.inspect} status=#{@status.inspect} revision=#{revision.inspect} transport=#{transport.inspect}>"
849
- end
850
-
851
- private
852
-
853
- def events_loop
854
- loop do
855
- @mutex.synchronize do
856
- return if @closed
857
-
858
- @sleep_cv.wait(@flush_interval)
859
- return if @closed
860
- end
861
- empty = @queue_mutex.synchronize { @queue.empty? }
862
- # Nothing queued: the service report alone goes out once per report interval.
863
- next if empty && monotonic - @last_report < @report_interval
864
-
865
- flush
866
- end
867
- end
868
- end
869
- end
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "monitor"
5
+ require "time"
6
+
7
+ module NanoFlags
8
+ # WebSocket subprotocol of the edge's live socket (+/v1/live+).
9
+ LIVE_PROTOCOL = "nanoflags.v1"
10
+ # Close code of the live socket for a deleted environment: the client keeps its last bundle and stops reconnecting.
11
+ CLOSE_ENVIRONMENT_DELETED = 4004
12
+
13
+ # The NanoFlags client for Ruby servers (Rails, Puma, Sidekiq, Rack, plain scripts).
14
+ #
15
+ # Flags are evaluated locally and synchronously against an in-memory bundle; a variation call never performs I/O
16
+ # and never raises. The network is used in background threads only: to load the bundle (`/v1/bundle`, with ETag
17
+ # revalidation), to receive new revisions as soon as they are published (pushed over the live WebSocket `/v1/live`;
18
+ # while no socket can be opened, server-sent events on `/v1/stream`; polling as the safety net), and to send sampled
19
+ # telemetry plus the periodic service report (`/v1/events`). Test sessions ({#session}) are resolved on demand.
20
+ #
21
+ # Create one client per process and share it between threads. It is fork-safe: after a fork (Puma and Unicorn
22
+ # workers, Passenger, Resque, Sidekiq Swarm) the child keeps the configuration it inherited and restarts the
23
+ # background threads on its first call (a child that never evaluates a flag never opens a connection). Events
24
+ # queued before the fork are sent by the parent only.
25
+ #
26
+ # FLAGS = NanoFlags::Client.new(ENV.fetch("NANOFLAGS_SDK_KEY"), service: "checkout-api")
27
+ # FLAGS.wait_until_ready(5)
28
+ # FLAGS.bool_variation("new-checkout", false, { key: current_user.id, plan: current_user.plan })
29
+ class Client
30
+ STATUS_NOT_READY = "not-ready"
31
+ STATUS_READY = "ready"
32
+ STATUS_STALE = "stale"
33
+
34
+ MAX_QUEUE = 500
35
+ MAX_BATCH = 50
36
+ MAX_EVENT_VALUE_CHARS = 1024
37
+ KEYS_REFETCH = 60.0
38
+ LIVE_CONNECT_TIMEOUT = 10.0
39
+ LIVE_PING = 30.0
40
+ LIVE_PONG_TIMEOUT = 10.0
41
+ LIVE_MAX_BACKOFF = 300.0
42
+ # A healthy socket is replaced after about this long, so the edge validates the key again (it drops sockets older
43
+ # than 2 h).
44
+ LIVE_ROTATE = 50 * 60.0
45
+ LIVE_STABLE = 30.0
46
+ MAX_SESSIONS = 1000
47
+ SESSION_MISS_TTL = 15.0
48
+ SESSION_ERROR_TTL = 3.0
49
+ ACCEPT_BOOL = ->(v) { v == true || v == false }
50
+ ACCEPT_STRING = ->(v) { v.is_a?(String) }
51
+ ACCEPT_NUMBER = ->(v) { v.is_a?(Float) && v.finite? }
52
+ ACCEPT_ANY = ->(v) { !v.equal?(Engine::UNDEFINED) }
53
+
54
+ REGISTRY = ObjectSpace::WeakMap.new
55
+ REGISTRY_LOCK = Mutex.new
56
+ private_constant :REGISTRY, :REGISTRY_LOCK
57
+
58
+ attr_reader :base_url, :service
59
+
60
+ # @param sdk_key [String] `nf_srv_…` (server view) or `nf_pub_…` (client-exposed flags only)
61
+ # @param base_url [String] the edge; signatures are verified by default on the hosted edge
62
+ # @param service [String, nil] the name shown in "which revision is each service running"
63
+ # @param poll_interval [Numeric] seconds between polls while no live socket is open (0 disables polling)
64
+ # @param streaming [Boolean] receive new revisions without polling (live WebSocket, else server-sent events);
65
+ # false: polling only
66
+ # @param live [Boolean] false skips the live WebSocket and uses server-sent events + polling
67
+ # @param live_poll_interval [Numeric] seconds between safety polls while the live socket is healthy
68
+ # @param live_url [String, nil] WebSocket URL of /v1/live when it is not +base_url+ with ws(s):// (advanced)
69
+ # @param bootstrap [Hash, String, nil] a bundle (Hash or JSON text) to use until the edge answers
70
+ # @param cache_path [String, nil] keep the last good bundle in this file (restored, and verified again, on start)
71
+ # @param store [#get, #set, nil] custom persistence; overrides +cache_path+
72
+ # @param events [Hash, false, nil] telemetry: false disables it; a Hash with :sample_rate (0.1), :flush_interval
73
+ # (10 s), :report_interval (60 s), :redact (a callable receiving the context Hash)
74
+ # @param verify [Hash, Boolean, nil] signature verification: nil (default) on for the hosted edge; false off;
75
+ # true on with keys from the edge's /v1/keys; a Hash with :public_keys (JWKs), :require, :fetch_keys
76
+ # @param on_change [#call, nil] called with an {UpdateEvent} whenever a new configuration is adopted
77
+ # @param on_error [#call, nil] called with an {Error} for background failures
78
+ # @param logger [Logger, nil] debug output of the background activity
79
+ # @param start [Boolean] false defers the background work until {#start}
80
+ # @param http [#call, nil] the transport (see {HTTP::NetHttp})
81
+ def initialize(sdk_key, base_url: OFFICIAL_EDGE_URL, service: nil, poll_interval: 30, streaming: true, live: true,
82
+ live_poll_interval: 300, live_url: nil, bootstrap: nil, cache_path: nil, store: nil, events: nil,
83
+ verify: nil, on_change: nil, on_error: nil, logger: nil, start: true, http: nil, request_timeout: 10,
84
+ stream_read_timeout: 90, random: nil)
85
+ @sdk_key = sdk_key.to_s
86
+ @base_url = base_url.to_s.sub(%r{/+\z}, "")
87
+ @service = service.to_s.empty? ? "unknown" : service.to_s
88
+ @poll_interval = poll_interval.to_f
89
+ @streaming = streaming
90
+ @live_enabled = live
91
+ @live_poll_interval = live_poll_interval.to_f
92
+ @live_url = live_url&.to_s
93
+ @request_timeout = request_timeout.to_f
94
+ @stream_read_timeout = stream_read_timeout.to_f
95
+ @http = http || HTTP::NetHttp.new
96
+ @logger = logger
97
+ @random = random || -> { rand }
98
+ @id = format("%08x", Engine.murmur3("#{@base_url}|#{@sdk_key}"))
99
+ @browser_key = @sdk_key.start_with?("nf_pub_")
100
+ @store = store || (cache_path ? Store::File.new(cache_path) : nil)
101
+ @pending_errors = []
102
+
103
+ ev = events.is_a?(Hash) ? events.transform_keys(&:to_sym) : {}
104
+ @events_enabled = events != false
105
+ @sample_rate = Float(ev.fetch(:sample_rate, 0.1)).clamp(0.0, 1.0)
106
+ @flush_interval = Float(ev.fetch(:flush_interval, 10.0))
107
+ @report_interval = Float(ev.fetch(:report_interval, 60.0))
108
+ @redact = ev[:redact]
109
+
110
+ setup_verifier(verify)
111
+ @fetched_keys = []
112
+ @keys_fetched_at = nil
113
+
114
+ @listeners = { change: [], error: [], status: [] }
115
+ @listeners[:change] << on_change if on_change
116
+ @listeners[:error] << on_error if on_error
117
+
118
+ @bundle = nil
119
+ @etag = nil
120
+ @checksum = nil
121
+ @sig = nil
122
+ @raw = nil
123
+ @status = STATUS_NOT_READY
124
+ @last_error = nil
125
+ @pinned_env = nil
126
+ @failures = 0
127
+ @closed = false
128
+ @started = false
129
+ @ready = false
130
+ @stream_open = false
131
+ @live_open = false
132
+ @live_socket = nil
133
+ @live_revision = 0
134
+ @environment_deleted = false
135
+ @sessions = {}
136
+ @session_locks = {}
137
+ @queue = []
138
+ @last_report = monotonic
139
+ @attrs = {}
140
+ @attrs_for = nil
141
+ init_concurrency
142
+
143
+ if @sdk_key.strip.empty?
144
+ @pending_errors << Error.new("An SDK key is required.", :config)
145
+ end
146
+ @pending_errors << Error.new("The base URL must be an http(s) URL, got #{base_url.inspect}.", :config) unless @base_url.match?(%r{\Ahttps?://}i)
147
+ adopt_bootstrap(bootstrap) unless bootstrap.nil?
148
+ REGISTRY_LOCK.synchronize { REGISTRY[self] = true }
149
+ Client.install_exit_hook
150
+ self.start if start
151
+ end
152
+
153
+ # ------------------------------------------------------------------ lifecycle
154
+
155
+ # Starts the background threads (done by the constructor unless +start: false+).
156
+ def start
157
+ check_fork
158
+ @mutex.synchronize do
159
+ return self if @started || @closed
160
+
161
+ @started = true
162
+ end
163
+ pending = @pending_errors
164
+ @pending_errors = []
165
+ pending.each { |e| emit_error(e) }
166
+ if pending.any? { |e| e.code == :config && e.message.start_with?("An SDK key", "The base URL") }
167
+ mark_ready
168
+ return self
169
+ end
170
+ spawn("nanoflags-poll") { main_loop }
171
+ self
172
+ end
173
+
174
+ # Stops the background threads after a best-effort final telemetry flush (at most 2 seconds). Evaluations keep
175
+ # working on the last configuration. Idempotent.
176
+ def close
177
+ return if @closed
178
+
179
+ flush(timeout: 2) if @started && Process.pid == @pid
180
+ @mutex.synchronize do
181
+ @closed = true
182
+ @cv.broadcast
183
+ @sleep_cv.broadcast
184
+ end
185
+ close_stream
186
+ drop_live
187
+ mark_ready
188
+ @threads.each { |t| t.join(2) unless t == Thread.current }
189
+ nil
190
+ end
191
+
192
+ def closed? = @closed
193
+
194
+ # Blocks until the first load attempt has finished (or a configuration was adopted); returns whether a
195
+ # configuration is in use. +timeout+ in seconds (nil: no limit).
196
+ def wait_until_ready(timeout = nil)
197
+ check_fork
198
+ deadline = timeout && (monotonic + timeout)
199
+ @mutex.synchronize do
200
+ until @ready
201
+ left = deadline && (deadline - monotonic)
202
+ break if left && left <= 0
203
+
204
+ @ready_cv.wait(left)
205
+ end
206
+ end
207
+ !@bundle.nil?
208
+ end
209
+
210
+ # "not-ready", "ready" (known to be current) or "stale" (in use, not known to be current).
211
+ def status = @status
212
+
213
+ # The revision in use, or nil.
214
+ def revision = @bundle && @bundle["revision"].to_i
215
+
216
+ # True when a configuration is in use (ready or stale).
217
+ def initialized? = !@bundle.nil?
218
+
219
+ # :live while the live socket is open, :stream while the event stream is connected, otherwise :poll.
220
+ def transport
221
+ return :poll if Process.pid != @pid # a forked child has none of the parent's connections
222
+ return :live if @live_open
223
+
224
+ @stream_open ? :stream : :poll
225
+ end
226
+
227
+ # The last background error, if any.
228
+ def last_error = @last_error
229
+
230
+ # The bundle in use as JSON text (the signed bytes when it was signed), or nil.
231
+ def bundle_json = @raw || (@bundle && Engine::Js.stringify(@bundle))
232
+
233
+ # Registers a listener: +:change+ ({UpdateEvent}), +:error+ ({Error}) or +:status+ (a status string). Returns a
234
+ # lambda that removes it. Listeners run on a background thread; exceptions they raise are swallowed.
235
+ def on(event, callable = nil, &block)
236
+ fn = callable || block
237
+ list = @listeners.fetch(event.to_sym) { raise ArgumentError, "unknown event #{event.inspect}" }
238
+ list << fn
239
+ -> { list.delete(fn) }
240
+ end
241
+
242
+ def on_change(callable = nil, &block) = on(:change, callable, &block)
243
+ def on_error(callable = nil, &block) = on(:error, callable, &block)
244
+
245
+ # Revalidates now (blocking) and returns whether a configuration is in use. Errors are reported, never raised.
246
+ def refresh
247
+ check_fork
248
+ sync
249
+ initialized?
250
+ end
251
+
252
+ # ------------------------------------------------------------------ evaluation
253
+
254
+ # The boolean value of +key+ for +context+; +default+ when the flag is unknown, not a boolean, or nothing is loaded.
255
+ def bool_variation(key, default, context = nil) = run(key, default, context, ACCEPT_BOOL).value
256
+ def string_variation(key, default, context = nil) = run(key, default, context, ACCEPT_STRING).value
257
+ # A number flag; whole numbers are returned as Integer.
258
+ def number_variation(key, default, context = nil) = run(key, default, context, ACCEPT_NUMBER).value
259
+ # A JSON flag as plain Ruby data (Hash with String keys, Array, …); any served value is accepted.
260
+ def json_variation(key, default, context = nil) = run(key, default, context, ACCEPT_ANY).value
261
+
262
+ def bool_variation_detail(key, default, context = nil) = run(key, default, context, ACCEPT_BOOL)
263
+ def string_variation_detail(key, default, context = nil) = run(key, default, context, ACCEPT_STRING)
264
+ def number_variation_detail(key, default, context = nil) = run(key, default, context, ACCEPT_NUMBER)
265
+ def json_variation_detail(key, default, context = nil) = run(key, default, context, ACCEPT_ANY)
266
+
267
+ # The full engine result ({EvaluationDetail}) without any type check.
268
+ def evaluate(key, default, context = nil) = run(key, default, context, nil)
269
+
270
+ # Every flag of the configuration in use evaluated for +context+ ({} when nothing is loaded). Not sampled into
271
+ # telemetry.
272
+ def all_flags(context = nil)
273
+ all_flags_detail(context).transform_values(&:value)
274
+ end
275
+
276
+ def all_flags_detail(context = nil)
277
+ b = @bundle
278
+ return {} if b.nil?
279
+
280
+ ctx = to_context(context)
281
+ out = {}
282
+ b["flags"].each_key do |k|
283
+ r = Engine.evaluate(b, k, ctx, nil)
284
+ out[k] = EvaluationDetail.from_result(r, nil) unless r.reason == "flag_not_found"
285
+ end
286
+ out
287
+ rescue StandardError
288
+ {}
289
+ end
290
+
291
+ # ------------------------------------------------------------------ test sessions
292
+
293
+ # Resolves a test session (+GET /v1/session+, once per token and service, cached until the session expires) and
294
+ # returns a {SessionEvaluator} scoped to it. Pass the incoming +x-nanoflags-session+ header value. Blocks on the
295
+ # first call per token; never raises. Unknown tokens are remembered for 15 s, failed lookups for 3 s. Without an
296
+ # active session the evaluator behaves exactly like the client.
297
+ #
298
+ # +service+ is sent as +X-NanoFlags-Service+ (default: the client's +service+); a session may be limited to
299
+ # certain services.
300
+ def session(token, service: nil)
301
+ check_fork
302
+ return SessionEvaluator.new(self, nil) if !NanoFlags.session_token?(token) || @closed || !@base_url.match?(%r{\Ahttps?://}i)
303
+
304
+ name = service.to_s.empty? ? (@service == "unknown" ? nil : @service) : service.to_s
305
+ key = "#{name}\n#{token}"
306
+ if (hit = cached_session(key))
307
+ return SessionEvaluator.new(self, hit[0])
308
+ end
309
+
310
+ # One lookup per token at a time: concurrent requests of the same session wait for it instead of repeating it.
311
+ lock = @sessions_mutex.synchronize { @session_locks[key] ||= Mutex.new }
312
+ lock.synchronize do
313
+ if (hit = cached_session(key))
314
+ return SessionEvaluator.new(self, hit[0])
315
+ end
316
+
317
+ state, failed = fetch_session(token, name)
318
+ until_ts = state ? state.expires_at_ts : Time.now.to_f + (failed ? SESSION_ERROR_TTL : SESSION_MISS_TTL)
319
+ @sessions_mutex.synchronize do
320
+ if @sessions.size >= MAX_SESSIONS
321
+ now = Time.now.to_f
322
+ @sessions.delete_if { |_, v| now >= v[1] }
323
+ @sessions.delete(@sessions.first[0]) while @sessions.size >= MAX_SESSIONS # oldest first
324
+ end
325
+ @sessions[key] = [state, until_ts]
326
+ @session_locks.delete(key)
327
+ end
328
+ SessionEvaluator.new(self, state)
329
+ end
330
+ rescue StandardError
331
+ SessionEvaluator.new(self, nil)
332
+ end
333
+
334
+ # ------------------------------------------------------------------ fork safety
335
+
336
+ # @api private
337
+ def self.install_exit_hook
338
+ REGISTRY_LOCK.synchronize do
339
+ return if @exit_hook
340
+
341
+ @exit_hook = true
342
+ at_exit { each_client { |c| c.close unless c.closed? } }
343
+ end
344
+ end
345
+
346
+ # @api private
347
+ def self.each_client(&block)
348
+ clients = REGISTRY_LOCK.synchronize { REGISTRY.keys }
349
+ clients.each(&block)
350
+ end
351
+
352
+ # Restarts the background threads of every client in a forked child now (for example from Puma's
353
+ # +on_worker_boot+). Optional: a client notices the fork on its first call in the child and restarts then.
354
+ def self.after_fork
355
+ each_client { |c| c.send(:check_fork) }
356
+ end
357
+
358
+ private
359
+
360
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
361
+
362
+ def init_concurrency
363
+ @pid = Process.pid
364
+ @mutex = Monitor.new
365
+ @cv = @mutex.new_cond # wakes the poll loop (sync requested, close)
366
+ @sleep_cv = @mutex.new_cond # wakes the other loops (close)
367
+ @ready_cv = @mutex.new_cond
368
+ @sessions_mutex = Mutex.new
369
+ @rescheduled = false
370
+ @sync_mutex = Mutex.new
371
+ @keys_mutex = Mutex.new
372
+ @queue_mutex = Mutex.new
373
+ @threads = []
374
+ @sync_requested = false
375
+ @stream_closer = nil
376
+ @stream_thread = nil
377
+ @stream_active = false
378
+ @stream_gen = 0
379
+ end
380
+
381
+ # A fork keeps the configuration but not the threads: restart them in the child, and drop the parent's queued
382
+ # events (the parent sends those).
383
+ def check_fork
384
+ return if Process.pid == @pid
385
+
386
+ FORK_LOCK.synchronize do
387
+ return if Process.pid == @pid
388
+
389
+ was_started = @started
390
+ init_concurrency
391
+ @queue = []
392
+ @stream_open = false
393
+ # The parent's socket is the parent's: never write to it (not even a close frame) from the child.
394
+ @live_open = false
395
+ @live_socket = nil
396
+ @session_locks = {}
397
+ @started = false
398
+ @last_report = monotonic
399
+ start if was_started && !@closed
400
+ end
401
+ end
402
+
403
+ FORK_LOCK = Mutex.new
404
+
405
+ def spawn(name, &block)
406
+ t = Thread.new do
407
+ Thread.current.name = name
408
+ Thread.current.report_on_exception = false
409
+ block.call
410
+ rescue StandardError => e
411
+ log { "#{name} stopped: #{e.class}: #{e.message}" }
412
+ end
413
+ @threads << t
414
+ t
415
+ end
416
+
417
+ def log
418
+ @logger&.debug("nanoflags") { yield }
419
+ end
420
+
421
+ def mark_ready
422
+ @mutex.synchronize do
423
+ @ready = true
424
+ @ready_cv.broadcast
425
+ end
426
+ end
427
+
428
+ def fire(event, arg)
429
+ @listeners[event].dup.each do |fn|
430
+ fn.call(arg)
431
+ rescue StandardError => e
432
+ log { "#{event} listener raised #{e.class}: #{e.message}" }
433
+ end
434
+ end
435
+
436
+ def emit_error(e)
437
+ @last_error = e
438
+ log { "#{e.code}: #{e.message}" }
439
+ fire(:error, e)
440
+ end
441
+
442
+ def set_status(status)
443
+ changed = @mutex.synchronize do
444
+ old = @status
445
+ @status = status
446
+ old != status
447
+ end
448
+ fire(:status, status) if changed
449
+ end
450
+
451
+ def setup_verifier(verify)
452
+ official = @base_url == OFFICIAL_EDGE_URL
453
+ official_keys = -> { Signature.import_keys(OFFICIAL_SIGNING_KEYS) }
454
+ @verifier =
455
+ case verify
456
+ when false then nil
457
+ when nil then official ? { base: official_keys.(), require: true, refetch: true } : nil
458
+ when true then official ? { base: official_keys.(), require: true, refetch: true } : { base: [], require: true, refetch: true }
459
+ when Hash
460
+ v = verify.transform_keys(&:to_sym)
461
+ req = v.key?(:require) ? v[:require] : official
462
+ keys = v[:public_keys]
463
+ if keys.is_a?(Array) && !keys.empty?
464
+ unless keys.all? { |k| Signature.public_ed25519_jwk?(k.is_a?(Hash) ? k.transform_keys(&:to_s) : k) }
465
+ @pending_errors << Error.new("`verify[:public_keys]` must contain public Ed25519 JWKs only. Other entries (including private keys) were ignored.", :config)
466
+ end
467
+ { base: Signature.import_keys(keys), require: req, refetch: v.fetch(:fetch_keys, false) }
468
+ elsif v[:fetch_keys] || !official
469
+ { base: [], require: req, refetch: true }
470
+ else
471
+ { base: official_keys.(), require: req, refetch: true }
472
+ end
473
+ else raise ArgumentError, "verify must be nil, true, false or a Hash"
474
+ end
475
+ end
476
+
477
+ def adopt_bootstrap(bootstrap)
478
+ b = bootstrap.is_a?(String) ? Engine::Json.parse(bootstrap) : Engine::Js.from_ruby(bootstrap)
479
+ if !Engine.bundle?(b)
480
+ @pending_errors << Error.new("The bootstrap bundle is invalid and was ignored.", :invalid_bundle)
481
+ elsif !Engine.supports_engine?(b.fetch("engine", Engine::UNDEFINED))
482
+ @pending_errors << engine_error(b)
483
+ else
484
+ adopt(b, etag: nil, checksum: nil, sig: nil, raw: nil, status: STATUS_READY, source: :bootstrap, transport: :poll)
485
+ end
486
+ rescue Engine::InvalidJsonError
487
+ @pending_errors << Error.new("The bootstrap bundle is invalid and was ignored.", :invalid_bundle)
488
+ end
489
+
490
+ def engine_error(b)
491
+ Error.new("Bundle r#{Engine::Js.to_str(b.fetch("revision", Engine::UNDEFINED))} needs evaluation engine #{Engine::Js.stringify(b.fetch("engine", Engine::UNDEFINED)) || "undefined"}; " \
492
+ "this SDK supports up to #{Engine::VERSION}. Upgrade the nanoflags gem. The configuration in use is unchanged.", :engine)
493
+ end
494
+
495
+ def adopt(bundle, etag:, checksum:, sig:, raw:, status:, source:, transport:, latency_ms: nil)
496
+ event = nil
497
+ @mutex.synchronize do
498
+ prev = @bundle
499
+ prev_rev = prev && prev["revision"].to_i
500
+ is_new = prev.nil? || prev_rev != bundle["revision"].to_i || @checksum != checksum
501
+ @bundle = bundle # one assignment: every evaluation sees one consistent revision
502
+ @etag = etag
503
+ @checksum = checksum
504
+ @sig = sig
505
+ @raw = raw
506
+ event = UpdateEvent.new(revision: bundle["revision"].to_i, previous_revision: prev_rev, checksum: checksum, source: source, transport: transport, latency_ms: latency_ms) if is_new
507
+ end
508
+ set_status(status)
509
+ mark_ready
510
+ fire(:change, event) if event
511
+ end
512
+
513
+ # ------------------------------------------------------------------ evaluation internals
514
+
515
+ def to_context(context)
516
+ return {} if context.nil?
517
+
518
+ v = Engine::Js.from_ruby(context)
519
+ v.is_a?(Hash) ? v : {}
520
+ end
521
+
522
+ # +scope+: a live test session ({SessionState}) or nil for the configuration in use.
523
+ def run(key, default, context, accepts, scope = nil)
524
+ check_fork
525
+ if scope
526
+ b = scope.bundle
527
+ ctx = scope.context.merge(to_context(context))
528
+ else
529
+ b = @bundle
530
+ ctx = to_context(context)
531
+ end
532
+ fallback = Engine::Js.from_ruby(default)
533
+ r = Engine.evaluate(b, key.to_s, ctx, fallback)
534
+ if accepts && r.reason != "flag_not_found" && r.reason != "error" && !accepts.(r.value)
535
+ error = "Flag \"#{key}\" has a #{Engine::Js.type_name(r.value)} value, which does not match the requested type."
536
+ r = Engine::Result.new(key.to_s, fallback, "error", r.revision, nil, Engine::UNDEFINED, nil, nil,
537
+ r.trace + [Engine::TraceStep.new("result", "Returned the fallback", error)], error)
538
+ end
539
+ record(r, scope ? nil : context, ctx, b, scope&.id)
540
+ EvaluationDetail.from_result(r, default)
541
+ rescue StandardError => e
542
+ EvaluationDetail.new(flag_key: key.to_s, value: default, reason: "error", revision: 0, error: e.message)
543
+ end
544
+
545
+ # ------------------------------------------------------------------ background loop
546
+
547
+ def main_loop
548
+ restore
549
+ sync
550
+ mark_ready # even without a bundle: callers must not hang; they check `status`
551
+ return if @closed
552
+
553
+ spawn("nanoflags-events") { events_loop } if @events_enabled && @flush_interval.positive?
554
+ if @streaming
555
+ if live_wanted?
556
+ spawn("nanoflags-socket") { live_loop }
557
+ else
558
+ start_stream
559
+ end
560
+ end
561
+ loop do
562
+ due = @mutex.synchronize do
563
+ return if @closed
564
+
565
+ unless @sync_requested || @rescheduled
566
+ if @poll_interval.positive?
567
+ @cv.wait(next_delay)
568
+ else
569
+ @cv.wait
570
+ end
571
+ end
572
+ return if @closed
573
+
574
+ # Rescheduled (the live socket opened or closed): wait again with the new interval, without a request.
575
+ if @rescheduled && !@sync_requested
576
+ @rescheduled = false
577
+ next false
578
+ end
579
+ @rescheduled = false
580
+ @sync_requested = false
581
+ true
582
+ end
583
+ sync if due
584
+ end
585
+ end
586
+
587
+ # Restarts the poll wait (its interval depends on whether the live socket is open).
588
+ def reschedule
589
+ @mutex.synchronize do
590
+ @rescheduled = true
591
+ @cv.broadcast
592
+ end
593
+ end
594
+
595
+ def request_sync
596
+ @mutex.synchronize do
597
+ @sync_requested = true
598
+ @cv.broadcast
599
+ end
600
+ end
601
+
602
+ def next_delay
603
+ jitter = 0.8 + (0.4 * @random.call)
604
+ interval = @live_open ? [@poll_interval, @live_poll_interval].max : @poll_interval
605
+ base = @failures.positive? ? [@poll_interval, 2.0**[@failures - 1, 10].min].min : interval
606
+ [0.25, base * jitter].max
607
+ end
608
+
609
+ def headers(extra = nil)
610
+ h = { "Authorization" => "Bearer #{@sdk_key}", "User-Agent" => "nanoflags-ruby/#{VERSION}" }
611
+ extra ? h.merge(extra) : h
612
+ end
613
+
614
+ def request(method, path, extra_headers = nil, body = nil, timeout = @request_timeout)
615
+ @http.call(method, "#{@base_url}#{path}", headers(extra_headers), body, timeout)
616
+ end
617
+
618
+ def sync
619
+ @sync_mutex.synchronize { sync_once unless @closed }
620
+ end
621
+
622
+ def sync_once
623
+ transport = @stream_triggered ? :stream : :poll
624
+ @stream_triggered = false
625
+ begin
626
+ res = begin
627
+ request("GET", "/v1/bundle", @etag ? { "If-None-Match" => @etag } : nil)
628
+ rescue StandardError => e
629
+ raise Error.new("Could not reach the NanoFlags edge: #{e.message}", :network)
630
+ end
631
+ return if @closed
632
+
633
+ served_stale = res.header("X-NanoFlags-Stale") == "true"
634
+ if res.status == 304 && @bundle
635
+ @failures = 0
636
+ set_status(served_stale ? STATUS_STALE : STATUS_READY)
637
+ return
638
+ end
639
+ raise Error.new("The SDK key was rejected (unknown or revoked).", :unauthorized, res.status) if [401, 403].include?(res.status)
640
+ raise Error.new("Bundle request failed with HTTP #{res.status}.", :http, res.status) unless res.ok?
641
+
642
+ body = begin
643
+ Engine::Json.parse(res.body)
644
+ rescue Engine::InvalidJsonError
645
+ nil
646
+ end
647
+ raise Error.new("The edge returned an invalid bundle.", :invalid_bundle) unless body.is_a?(Hash) && Engine.bundle?(body["bundle"])
648
+
649
+ bundle = body["bundle"]
650
+ sig, raw = check_signature(res, body, bundle)
651
+ return if @closed
652
+ raise engine_error(bundle) unless Engine.supports_engine?(bundle.fetch("engine", Engine::UNDEFINED))
653
+
654
+ @failures = 0
655
+ cur = @bundle
656
+ # The edge is serving its last-known-good copy: never go backwards because of it.
657
+ if served_stale && cur && cur["revision"] >= bundle["revision"]
658
+ set_status(STATUS_STALE)
659
+ return
660
+ end
661
+ checksum = body["checksum"].is_a?(String) ? body["checksum"] : nil
662
+ # A revision pushed while this request was under way (or that the edge's cache does not point at yet) wins.
663
+ return if cur && bundle["revision"].to_i < @live_revision && cur["revision"].to_i >= @live_revision
664
+
665
+ @pinned_env = sig.environment_id if sig
666
+ adopt(bundle, etag: res.header("ETag"), checksum: checksum, sig: sig, raw: raw,
667
+ status: served_stale ? STATUS_STALE : STATUS_READY, source: :network, transport: transport)
668
+ persist
669
+ rescue Error => e
670
+ return if @closed
671
+
672
+ if e.code == :engine
673
+ emit_error(e)
674
+ return
675
+ end
676
+ @failures += 1
677
+ if e.code == :signature
678
+ emit_error(e) # same bundle, same status; polling retries with backoff
679
+ return
680
+ end
681
+ drop_live if e.code == :unauthorized
682
+ set_status(STATUS_STALE) if @bundle
683
+ emit_error(e)
684
+ end
685
+ end
686
+
687
+ # Verifies a /v1/bundle response (when verification is on); returns [signature info or nil, bundle text to keep].
688
+ def check_signature(res, body, bundle)
689
+ raw = Signature.raw_member(res.body, "bundle")
690
+ return [nil, raw] unless @verifier
691
+
692
+ rev = bundle["revision"].to_i
693
+ reject = ->(why) { Error.new("Bundle r#{rev} was rejected: #{why} The configuration in use is unchanged.", :signature) }
694
+ unless res.header("X-NanoFlags-Signed") == "true"
695
+ raise reject.("it is not signed (the edge is still distributing it) and unsigned bundles are refused; fetching again shortly.") if @verifier[:require]
696
+
697
+ return [nil, raw]
698
+ end
699
+ signature = res.header("X-NanoFlags-Signature")
700
+ env_id = res.header("X-NanoFlags-Environment-Id")
701
+ kid = res.header("X-NanoFlags-Key-Id")
702
+ checksum = body["checksum"]
703
+ raise reject.("the signature headers are incomplete.") if signature.to_s.empty? || env_id.to_s.empty? || !checksum.is_a?(String)
704
+ raise reject.("the signed revision does not match the bundle.") if body["revision"].is_a?(Float) && body["revision"].to_i != rev
705
+ raise reject.("it was signed for a different environment.") if @pinned_env && @pinned_env != env_id
706
+
707
+ info = Signature::Info.new(signature, kid.to_s.empty? ? nil : kid, env_id, rev, checksum)
708
+ keys = begin
709
+ load_keys(info.kid)
710
+ rescue StandardError => e
711
+ raise reject.("the signing keys could not be loaded (#{e.message}).")
712
+ end
713
+ # The edge embeds the stored bundle text byte-for-byte; re-serialisation is the fallback.
714
+ return [info, raw] if raw && Signature.verify(keys, info, raw)
715
+
716
+ again = Engine::Js.stringify(bundle)
717
+ return [info, again] if again && again != raw && Signature.verify(keys, info, again)
718
+
719
+ raise reject.("its signature does not verify.")
720
+ end
721
+
722
+ # The pinned or embedded keys plus those of /v1/keys; an unknown key id reloads /v1/keys (at most once a minute).
723
+ def load_keys(kid)
724
+ v = @verifier
725
+ return [] unless v
726
+ return v[:base] unless v[:refetch]
727
+
728
+ @keys_mutex.synchronize do
729
+ known = v[:base] + @fetched_keys
730
+ return known if !known.empty? && (kid.nil? || known.any? { |k| k.kid == kid })
731
+ return known if @keys_fetched_at && monotonic - @keys_fetched_at < KEYS_REFETCH
732
+
733
+ begin
734
+ # Public endpoint: the SDK key is deliberately not sent.
735
+ res = @http.call("GET", "#{@base_url}/v1/keys", { "User-Agent" => "nanoflags-ruby/#{VERSION}" }, nil, @request_timeout)
736
+ raise Error.new("Signing keys request failed with HTTP #{res.status}.", :signature, res.status) unless res.status == 200
737
+
738
+ parsed = JSON.parse(res.body)
739
+ keys = Signature.import_keys(parsed.is_a?(Hash) && parsed["keys"].is_a?(Array) ? parsed["keys"] : [])
740
+ raise Error.new("The edge returned no usable signing keys.", :signature) if keys.empty?
741
+
742
+ @fetched_keys = keys
743
+ rescue StandardError
744
+ raise if v[:base].empty?
745
+ ensure
746
+ @keys_fetched_at = monotonic
747
+ end
748
+ v[:base] + @fetched_keys
749
+ end
750
+ end
751
+
752
+ # ------------------------------------------------------------------ persistence
753
+
754
+ def persist
755
+ return unless @store
756
+
757
+ payload = @mutex.synchronize do
758
+ p = { "v" => 1, "id" => @id, "etag" => @etag, "checksum" => @checksum, "savedAt" => Time.now.utc.iso8601(3), "bundle" => Engine::Js.stringify(@bundle) }
759
+ if @sig
760
+ p["sig"] = @sig.to_h
761
+ p["raw"] = @raw if @raw
762
+ end
763
+ p
764
+ end
765
+ # "bundle" is JSON text inside the document, so the persisted bytes survive any re-encoding by the store.
766
+ @store.set(JSON.generate(payload))
767
+ rescue StandardError => e
768
+ emit_error(Error.new("Could not persist the bundle: #{e.message}", :store))
769
+ end
770
+
771
+ def restore
772
+ return unless @store
773
+
774
+ text = @store.get
775
+ return if text.nil? || text.empty? || @closed
776
+
777
+ p = JSON.parse(text)
778
+ return unless p.is_a?(Hash) && p["v"] == 1 && p["id"] == @id && p["bundle"].is_a?(String)
779
+
780
+ restored = Engine::Json.parse(p["bundle"])
781
+ return unless Engine.bundle?(restored)
782
+ return emit_error(engine_error(restored)) unless Engine.supports_engine?(restored.fetch("engine", Engine::UNDEFINED))
783
+ return if @bundle && @bundle["revision"] >= restored["revision"]
784
+
785
+ sig = nil
786
+ raw = nil
787
+ if @verifier
788
+ # The store is outside the trust boundary: a signed copy must verify again; with `require` an unsigned copy
789
+ # is not used at all.
790
+ s = Signature::Info.from_h(p["sig"])
791
+ if s && s.revision == restored["revision"].to_i
792
+ raw = p["raw"].is_a?(String) ? p["raw"] : p["bundle"]
793
+ ok = begin
794
+ Signature.verify(load_keys(s.kid), s, raw) && (parsed = Engine::Json.parse(raw)) && Engine.bundle?(parsed) && parsed["revision"].to_i == s.revision
795
+ rescue StandardError
796
+ false
797
+ end
798
+ return emit_error(Error.new("The persisted bundle failed signature verification and was ignored.", :signature)) unless ok
799
+
800
+ restored = parsed
801
+ sig = s
802
+ @pinned_env ||= s.environment_id
803
+ elsif @verifier[:require]
804
+ return
805
+ end
806
+ end
807
+ # Usable but not known to be current: stale until the edge confirms it.
808
+ adopt(restored, etag: p["etag"], checksum: p["checksum"], sig: sig, raw: raw, status: STATUS_STALE, source: :store, transport: :poll)
809
+ rescue StandardError => e
810
+ emit_error(Error.new("Could not read the persisted bundle: #{e.message}", :store))
811
+ end
812
+
813
+ # ------------------------------------------------------------------ test sessions (internals)
814
+
815
+ # @api private
816
+ SessionState = Struct.new(:id, :bundle, :context, :expires_at, :expires_at_ts)
817
+
818
+ def cached_session(key)
819
+ @sessions_mutex.synchronize do
820
+ hit = @sessions[key]
821
+ return nil unless hit
822
+ return hit if Time.now.to_f < hit[1]
823
+
824
+ @sessions.delete(key)
825
+ nil
826
+ end
827
+ end
828
+
829
+ # [state or nil, failed]. nil without failure: no such session (unknown, expired, revoked, service not permitted).
830
+ def fetch_session(token, service)
831
+ extra = { "X-NanoFlags-Session" => token, "Cache-Control" => "no-store", "Accept" => "application/json" }
832
+ extra["X-NanoFlags-Service"] = service if service
833
+ res = begin
834
+ request("GET", "/v1/session", extra)
835
+ rescue StandardError => e
836
+ raise Error.new("Could not load the test session: #{e.message}", :session)
837
+ end
838
+ return [nil, false] if res.status == 404
839
+ raise Error.new("Session request failed with HTTP #{res.status}.", [401, 403].include?(res.status) ? :unauthorized : :session, res.status) unless res.ok?
840
+
841
+ body = begin
842
+ Engine::Json.parse(res.body)
843
+ rescue Engine::InvalidJsonError
844
+ nil
845
+ end
846
+ expires_ts = begin
847
+ body.is_a?(Hash) && body["expires_at"].is_a?(String) ? Time.iso8601(body["expires_at"]).to_f : nil
848
+ rescue ArgumentError
849
+ nil
850
+ end
851
+ raise Error.new("The edge returned an invalid session.", :session) unless body.is_a?(Hash) && body["id"].is_a?(String) && Engine.bundle?(body["bundle"]) && expires_ts
852
+
853
+ bundle = body["bundle"]
854
+ raise engine_error(bundle) unless Engine.supports_engine?(bundle.fetch("engine", Engine::UNDEFINED))
855
+ return [nil, false] if expires_ts <= Time.now.to_f
856
+
857
+ context = body["context"].is_a?(Hash) ? body["context"] : {}
858
+ [SessionState.new(body["id"], bundle, context, Time.at(expires_ts).utc.iso8601(3), expires_ts), false]
859
+ rescue StandardError => e
860
+ emit_error(e.is_a?(Error) ? e : Error.new("Could not load the test session: #{e.message}", :session)) unless @closed
861
+ [nil, true]
862
+ end
863
+
864
+ # ------------------------------------------------------------------ live WebSocket (/v1/live)
865
+
866
+ def live_url
867
+ return @live_url if @live_url && !@live_url.empty?
868
+
869
+ if @base_url.match?(%r{\Ahttps://}i) then "wss://#{@base_url.sub(%r{\Ahttps://}i, "")}/v1/live"
870
+ elsif @base_url.match?(%r{\Ahttp://}i) then "ws://#{@base_url.sub(%r{\Ahttp://}i, "")}/v1/live"
871
+ end
872
+ end
873
+
874
+ def live_wanted?
875
+ @streaming && @live_enabled && !live_url.nil? && @http.respond_to?(:websocket)
876
+ end
877
+
878
+ # Closes the current socket (for a rejected key); the loop reconnects with backoff.
879
+ def drop_live
880
+ ws = @live_socket
881
+ ws&.close(1000, "bye")
882
+ rescue StandardError
883
+ nil
884
+ end
885
+
886
+ # Keeps one live socket open, reconnecting with jittered exponential backoff (1 s · 2ⁿ, at most 5 min, × 0.5–1.5).
887
+ # While no socket can be opened, server-sent events + polling take over.
888
+ def live_loop
889
+ attempt = 0
890
+ current = -> { !@closed && !@environment_deleted && Process.pid == @pid }
891
+ while current.()
892
+ opened = false
893
+ opened_at = 0.0
894
+ rotating = false
895
+ close_code = nil
896
+ ws = nil
897
+ begin
898
+ ws = @http.websocket(live_url, headers, protocols: [LIVE_PROTOCOL], open_timeout: LIVE_CONNECT_TIMEOUT)
899
+ opened = true
900
+ opened_at = monotonic
901
+ rotating = live_session(ws, opened_at)
902
+ rescue WebSocket::Closed => e
903
+ close_code = e.code
904
+ log { "live socket closed: #{e.message}" }
905
+ rescue StandardError => e
906
+ log { "live socket failed: #{e.class}: #{e.message}" }
907
+ ensure
908
+ @live_open = false
909
+ @live_socket = nil
910
+ begin
911
+ ws&.close(1000, rotating ? "rotate" : "bye")
912
+ rescue StandardError
913
+ nil
914
+ end
915
+ end
916
+ return if @closed || Process.pid != @pid
917
+
918
+ if close_code == CLOSE_ENVIRONMENT_DELETED
919
+ # Keep evaluating the last bundle; it can no longer be updated. No socket, no stream; the regular poll stays
920
+ # (it reports the key as rejected, and recovers if the environment turns out to exist after all).
921
+ @environment_deleted = true
922
+ close_stream
923
+ set_status(STATUS_STALE) if @bundle
924
+ emit_error(Error.new("The environment of this SDK key was deleted. The last configuration stays in use; it will not be updated.", :environment_deleted))
925
+ reschedule
926
+ return
927
+ end
928
+ next if rotating # planned replacement: no fallback, no backoff
929
+
930
+ attempt = opened && monotonic - opened_at > LIVE_STABLE ? 1 : attempt + 1
931
+ if opened
932
+ reschedule # back to the normal poll interval
933
+ else
934
+ start_stream # SSE + polling take over until a socket opens again
935
+ end
936
+ wait = [LIVE_MAX_BACKOFF, 2.0**[attempt - 1, 10].min].min * (0.5 + @random.call)
937
+ @mutex.synchronize { @sleep_cv.wait(wait) unless @closed }
938
+ end
939
+ end
940
+
941
+ # Serves one open socket until it closes, dies or is due for rotation. Returns true for a rotation; raises
942
+ # {WebSocket::Closed} when the edge closed it.
943
+ def live_session(ws, opened_at)
944
+ @live_socket = ws
945
+ @live_open = true
946
+ close_stream # SSE is not used while the socket is healthy
947
+ reschedule # the poll becomes a safety net
948
+ rotate_at = opened_at + (LIVE_ROTATE * (0.9 + (0.2 * @random.call)))
949
+ next_ping = opened_at + (LIVE_PING * (0.9 + (0.2 * @random.call)))
950
+ pong_deadline = nil
951
+ until @closed || Process.pid != @pid
952
+ now = monotonic
953
+ return true if now >= rotate_at
954
+ return false if pong_deadline && now >= pong_deadline # silence after a ping: the connection is dead
955
+
956
+ if now >= next_ping
957
+ ws.send_text("ping") # the edge answers "pong" without waking anything up
958
+ pong_deadline ||= now + LIVE_PONG_TIMEOUT
959
+ next_ping = now + (LIVE_PING * (0.9 + (0.2 * @random.call)))
960
+ end
961
+ wait = [next_ping, rotate_at, pong_deadline || rotate_at].min - monotonic
962
+ msg = ws.recv([0.05, wait].max)
963
+ next if msg.nil?
964
+
965
+ pong_deadline = nil
966
+ next if msg == "pong"
967
+
968
+ m = begin
969
+ JSON.parse(msg)
970
+ rescue JSON::ParserError
971
+ nil
972
+ end
973
+ apply_push(m) if m.is_a?(Hash)
974
+ end
975
+ false
976
+ end
977
+
978
+ # Applies one +rev+ / +hello+ message. A message that cannot be trusted changes nothing.
979
+ def apply_push(m)
980
+ return if @closed || !%w[rev hello].include?(m["t"])
981
+
982
+ revision = m["revision"]
983
+ text = m["bundle"]
984
+ revision = revision.to_i if revision.is_a?(Float) && revision.finite? && revision == revision.floor
985
+ return unless revision.is_a?(Integer) && revision >= 1 && text.is_a?(String) # revision 0 / no bundle: nothing published yet
986
+
987
+ cur = @bundle
988
+ return if cur && revision < cur["revision"].to_i # never backwards
989
+
990
+ checksum = m["checksum"].is_a?(String) ? m["checksum"] : nil
991
+ info = nil
992
+ if @verifier
993
+ reject = lambda do |why|
994
+ emit_error(Error.new("Pushed bundle r#{revision} was rejected: #{why} The configuration in use is unchanged.", :signature))
995
+ request_sync # the regular (verified) request path says what is really current
996
+ end
997
+ signature = m["signature"]
998
+ env_id = m["environmentId"]
999
+ return reject.("it carries no complete signature.") unless signature.is_a?(String) && !signature.empty? && env_id.is_a?(String) && !env_id.empty? && checksum
1000
+ return reject.("it was signed for a different environment.") if @pinned_env && @pinned_env != env_id
1001
+
1002
+ kid = m["kid"].is_a?(String) && !m["kid"].empty? ? m["kid"] : nil
1003
+ info = Signature::Info.new(signature, kid, env_id, revision, checksum)
1004
+ ok = begin
1005
+ Signature.verify(load_keys(kid), info, text)
1006
+ rescue StandardError
1007
+ false
1008
+ end
1009
+ return if @closed
1010
+ return reject.("its signature does not verify.") unless ok
1011
+ end
1012
+ parsed = begin
1013
+ Engine::Json.parse(text)
1014
+ rescue Engine::InvalidJsonError
1015
+ nil
1016
+ end
1017
+ unless Engine.bundle?(parsed) && parsed["revision"].is_a?(Float) && parsed["revision"] == revision.to_f
1018
+ return emit_error(Error.new("The edge pushed an invalid bundle; it was ignored.", :invalid_bundle))
1019
+ end
1020
+ return emit_error(engine_error(parsed)) unless Engine.supports_engine?(parsed.fetch("engine", Engine::UNDEFINED))
1021
+
1022
+ confirm = false
1023
+ proceed = @mutex.synchronize do
1024
+ cur = @bundle
1025
+ next false if cur && revision < cur["revision"].to_i
1026
+
1027
+ @failures = 0
1028
+ if cur && revision == cur["revision"].to_i
1029
+ # Already in use: the push only confirms that it is current.
1030
+ confirm = @checksum.nil? || @checksum == checksum
1031
+ next false
1032
+ end
1033
+ @pinned_env = info.environment_id if info
1034
+ @live_revision = revision
1035
+ true
1036
+ end
1037
+ set_status(STATUS_READY) if confirm
1038
+ return unless proceed
1039
+
1040
+ committed = m["committedAt"]
1041
+ latency = committed.is_a?(Numeric) && committed.to_f.finite? ? (Time.now.to_f * 1000) - committed : nil
1042
+ adopt(parsed,
1043
+ # What /v1/bundle would send as ETag for this revision, so the safety poll gets a 304.
1044
+ etag: checksum ? %("#{checksum}-#{@browser_key ? "client" : "server"}") : nil,
1045
+ checksum: checksum, sig: info, raw: text,
1046
+ status: STATUS_READY, source: :network, transport: :live, latency_ms: latency)
1047
+ persist
1048
+ end
1049
+
1050
+ # ------------------------------------------------------------------ event stream (SSE)
1051
+
1052
+ def start_stream
1053
+ gen = @mutex.synchronize do
1054
+ return if @closed || !@streaming || @stream_active || @environment_deleted
1055
+
1056
+ @stream_active = true
1057
+ @stream_gen += 1
1058
+ end
1059
+ @stream_thread = spawn("nanoflags-stream") { stream_loop(gen) }
1060
+ end
1061
+
1062
+ def close_stream
1063
+ closer, thread = @mutex.synchronize do
1064
+ @stream_gen += 1
1065
+ @stream_active = false
1066
+ [@stream_closer, @stream_thread]
1067
+ end
1068
+ begin
1069
+ closer&.call
1070
+ rescue StandardError
1071
+ nil
1072
+ end
1073
+ # A read blocked inside OpenSSL does not always notice the socket closing under it: the thread only reads.
1074
+ thread.kill if thread && thread != Thread.current && !thread.join(0.2)
1075
+ nil
1076
+ end
1077
+
1078
+ def stream_loop(gen)
1079
+ attempt = 0
1080
+ current = -> { !@closed && gen == @stream_gen && Process.pid == @pid }
1081
+ while current.()
1082
+ started = monotonic
1083
+ stop = false
1084
+ begin
1085
+ status = @http.stream("#{@base_url}/v1/stream", headers("Accept" => "text/event-stream"),
1086
+ open_timeout: @request_timeout, read_timeout: @stream_read_timeout,
1087
+ on_open: ->(closer) { @stream_closer = closer }) do |event, data|
1088
+ next :stop unless current.()
1089
+
1090
+ @stream_open = true
1091
+ case event
1092
+ when "revision" then on_revision(data)
1093
+ when "revoked"
1094
+ stop = true
1095
+ request_sync
1096
+ next :stop
1097
+ end
1098
+ nil
1099
+ end
1100
+ stop = true if [401, 403].include?(status) # polling keeps reporting the error
1101
+ rescue StandardError => e
1102
+ log { "stream failed: #{e.class}: #{e.message}" }
1103
+ ensure
1104
+ @stream_open = false
1105
+ @stream_closer = nil
1106
+ end
1107
+ return unless current.()
1108
+
1109
+ if stop
1110
+ @mutex.synchronize { @stream_active = false if gen == @stream_gen }
1111
+ return
1112
+ end
1113
+ attempt = monotonic - started > 30 ? 0 : attempt + 1
1114
+ wait = [30.0, 2.0**[attempt, 5].min].min * (0.5 + @random.call)
1115
+ @mutex.synchronize { @sleep_cv.wait(wait) unless @closed }
1116
+ end
1117
+ end
1118
+
1119
+ def on_revision(data)
1120
+ m = JSON.parse(data)
1121
+ return unless m.is_a?(Hash)
1122
+
1123
+ b = @bundle
1124
+ return unless b.nil? || m["revision"] != b["revision"].to_i || m["checksum"] != @checksum || @status != STATUS_READY
1125
+
1126
+ @stream_triggered = true
1127
+ request_sync
1128
+ rescue JSON::ParserError
1129
+ nil
1130
+ end
1131
+
1132
+ # ------------------------------------------------------------------ telemetry
1133
+
1134
+ def attrs_used_by(bundle, flag_key)
1135
+ return [] if bundle.nil?
1136
+
1137
+ unless @attrs_for.equal?(bundle)
1138
+ @attrs = {}
1139
+ @attrs_for = bundle
1140
+ end
1141
+ @attrs[flag_key] ||= Engine.attributes_used_by(bundle, flag_key)
1142
+ end
1143
+
1144
+ def record(r, user_context, ctx, bundle, session_id = nil)
1145
+ return if !@events_enabled || @closed || @sample_rate <= 0 || @random.call >= @sample_rate
1146
+
1147
+ context =
1148
+ if @redact
1149
+ c = Engine::Js.from_ruby(@redact.call(user_context.is_a?(Hash) ? user_context.dup : Engine::Js.to_ruby(ctx)))
1150
+ c.is_a?(Hash) ? c : {}
1151
+ else
1152
+ # No attribute values: only the names the flag's rules use that are present, with the value's type.
1153
+ attrs_used_by(bundle, r.flag_key).each_with_object({}) do |name, h|
1154
+ v = ctx.fetch(name, Engine::UNDEFINED)
1155
+ h[name] = Engine::Js.type_name(v) unless v.equal?(Engine::UNDEFINED)
1156
+ end
1157
+ end
1158
+ rev = Engine::Js.to_number(r.revision)
1159
+ ev = { "flagKey" => truncate(r.flag_key, 63), "value" => event_value(r.value), "reason" => r.reason }
1160
+ ev["ruleIndex"] = r.rule_index.to_f unless r.rule_index.nil?
1161
+ ev["revision"] = rev.finite? ? rev.to_i.to_f : 0.0
1162
+ ev["context"] = context
1163
+ ev["at"] = Time.now.utc.strftime("%Y-%m-%dT%H:%M:%S.%LZ")
1164
+ ev["sessionId"] = session_id unless session_id.nil?
1165
+ ev["sampleRate"] = @sample_rate
1166
+ text = Engine::Js.stringify(ev)
1167
+ @queue_mutex.synchronize { @queue << text if @queue.length < MAX_QUEUE } # bounded: drop instead of growing
1168
+ rescue StandardError
1169
+ nil # telemetry must never affect evaluation
1170
+ end
1171
+
1172
+ def event_value(v)
1173
+ return truncate(v, MAX_EVENT_VALUE_CHARS) if v.is_a?(String)
1174
+
1175
+ text = Engine::Js.stringify(v)
1176
+ return nil if text.nil? || ((v.is_a?(Array) || v.is_a?(Hash)) && Engine::Js.utf16_length(text) > MAX_EVENT_VALUE_CHARS)
1177
+
1178
+ v
1179
+ end
1180
+
1181
+ def truncate(s, n)
1182
+ return s if s.bytesize <= n || Engine::Js.utf16_length(s) <= n
1183
+
1184
+ Engine::Js.units_to_string(Engine::Js.to_units(s).first(n))
1185
+ end
1186
+
1187
+ public
1188
+
1189
+ # Sends queued telemetry and the service report now (blocking, best effort, never raises).
1190
+ def flush(timeout: @request_timeout)
1191
+ return unless @events_enabled
1192
+
1193
+ batch = @queue_mutex.synchronize { @queue.shift(MAX_BATCH) }
1194
+ @last_report = monotonic
1195
+ rev = revision || 0
1196
+ body = %({"service":#{Engine::Js.quote(truncate(@service, 60))},"sdk":"ruby/#{VERSION}","revision":#{[rev, 0].max},"events":[#{batch.join(",")}]})
1197
+ request("POST", "/v1/events", { "Content-Type" => "application/json" }, body, timeout)
1198
+ nil
1199
+ rescue StandardError
1200
+ nil # dropped on failure, by design: telemetry is never retried
1201
+ end
1202
+
1203
+ def inspect
1204
+ "#<NanoFlags::Client base_url=#{@base_url.inspect} status=#{@status.inspect} revision=#{revision.inspect} transport=#{transport.inspect}>"
1205
+ end
1206
+
1207
+ private
1208
+
1209
+ def events_loop
1210
+ loop do
1211
+ @mutex.synchronize do
1212
+ return if @closed
1213
+
1214
+ @sleep_cv.wait(@flush_interval)
1215
+ return if @closed
1216
+ end
1217
+ empty = @queue_mutex.synchronize { @queue.empty? }
1218
+ # Nothing queued: the service report alone goes out once per report interval.
1219
+ next if empty && monotonic - @last_report < @report_interval
1220
+
1221
+ flush
1222
+ end
1223
+ end
1224
+ end
1225
+ end