nanoflags 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,869 @@
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