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,87 +1,91 @@
1
- # frozen_string_literal: true
2
-
3
- module NanoFlags
4
- # An error of the client. It is reported to +on_error+ listeners and {Client#last_error}; a variation call never
5
- # raises it. A failed update never changes the configuration in use.
6
- #
7
- # Codes (+code+): :network, :unauthorized, :http, :invalid_bundle, :store, :config, :signature, :engine.
8
- class Error < StandardError
9
- attr_reader :code, :http_status
10
-
11
- def initialize(message, code, http_status = nil)
12
- super(message)
13
- @code = code
14
- @http_status = http_status
15
- end
16
-
17
- def inspect = "#<NanoFlags::Error #{code}: #{message}>"
18
- end
19
-
20
- # A new configuration is in use. +source+ is :network, :store or :bootstrap; +transport+ is :stream (fetched after
21
- # an event-stream notification) or :poll; +previous_revision+ is nil when nothing was loaded before.
22
- UpdateEvent = Struct.new(:revision, :previous_revision, :checksum, :source, :transport, keyword_init: true)
23
-
24
- # The full result of an evaluation: value, reason, matched rule, rollout bucket and a human-readable trace.
25
- #
26
- # +value+ is plain Ruby data (the application default for reasons "flag_not_found" and "error"); +reason+ is one of
27
- # "rule_match", "default", "off", "flag_not_found", "error"; +revision+ is the evaluated revision (0 without one);
28
- # +rule_index+ / +rule_id+ identify the matching rule; +in_rollout+ and +bucket+ (0–99.99) are set for percentage
29
- # rollouts; +error+ explains reason "error"; +trace+ is a list of {Engine::TraceStep}.
30
- class EvaluationDetail
31
- attr_reader :flag_key, :value, :reason, :revision, :rule_index, :rule_id, :in_rollout, :bucket, :trace, :error
32
-
33
- def initialize(flag_key:, value:, reason:, revision:, rule_index: nil, rule_id: nil, in_rollout: nil, bucket: nil, trace: [], error: nil, raw: nil)
34
- @flag_key = flag_key
35
- @value = value
36
- @reason = reason
37
- @revision = revision
38
- @rule_index = rule_index
39
- @rule_id = rule_id
40
- @in_rollout = in_rollout
41
- @bucket = bucket
42
- @trace = trace.freeze
43
- @error = error
44
- @raw = raw
45
- freeze
46
- end
47
-
48
- # @api private
49
- def self.from_result(r, default)
50
- js = Engine::Js
51
- use_default = r.reason == "flag_not_found" || r.reason == "error"
52
- rev = js.to_number(r.revision)
53
- rule_id = nil
54
- if !r.rule_index.nil? && !r.rule_id.equal?(Engine::UNDEFINED)
55
- rule_id = r.rule_id.is_a?(String) ? r.rule_id : js.stringify(r.rule_id)
56
- end
57
- new(
58
- flag_key: r.flag_key,
59
- value: use_default ? default : js.to_ruby(r.value),
60
- reason: r.reason,
61
- revision: rev.finite? ? rev.to_i : 0,
62
- rule_index: r.rule_index,
63
- rule_id: rule_id,
64
- in_rollout: r.in_rollout,
65
- bucket: r.bucket,
66
- trace: r.trace,
67
- error: r.error,
68
- raw: use_default ? js.from_ruby(default) : r.value
69
- )
70
- end
71
-
72
- # The served value as JSON text (object keys in configuration order), or nil when nothing was served.
73
- def json = Engine::Js.stringify(@raw)
74
-
75
- # The type of the served value: "boolean", "string", "number", "array", "object", "null" or "undefined".
76
- def type_name = Engine::Js.type_name(@raw)
77
-
78
- def to_h
79
- {
80
- flag_key: flag_key, value: value, reason: reason, revision: revision, rule_index: rule_index, rule_id: rule_id,
81
- in_rollout: in_rollout, bucket: bucket, trace: trace.map(&:to_h), error: error
82
- }
83
- end
84
-
85
- def inspect = "#<NanoFlags::EvaluationDetail #{flag_key}=#{value.inspect} (#{reason}, r#{revision})>"
86
- end
87
- end
1
+ # frozen_string_literal: true
2
+
3
+ module NanoFlags
4
+ # An error of the client. It is reported to +on_error+ listeners and {Client#last_error}; a variation call never
5
+ # raises it. A failed update never changes the configuration in use.
6
+ #
7
+ # Codes (+code+): :network, :unauthorized, :http, :invalid_bundle, :store, :config, :signature, :engine, :session
8
+ # (a test session could not be loaded), :environment_deleted (the live socket closed with 4004: the last
9
+ # configuration stays in use and is no longer updated).
10
+ class Error < StandardError
11
+ attr_reader :code, :http_status
12
+
13
+ def initialize(message, code, http_status = nil)
14
+ super(message)
15
+ @code = code
16
+ @http_status = http_status
17
+ end
18
+
19
+ def inspect = "#<NanoFlags::Error #{code}: #{message}>"
20
+ end
21
+
22
+ # A new configuration is in use. +source+ is :network, :store or :bootstrap; +transport+ is :live (pushed over the
23
+ # live socket), :stream (fetched after an event-stream notification) or :poll; +previous_revision+ is nil when
24
+ # nothing was loaded before; +latency_ms+ is the time from the database commit to this event, for pushed revisions
25
+ # that carry their commit time (nil otherwise).
26
+ UpdateEvent = Struct.new(:revision, :previous_revision, :checksum, :source, :transport, :latency_ms, keyword_init: true)
27
+
28
+ # The full result of an evaluation: value, reason, matched rule, rollout bucket and a human-readable trace.
29
+ #
30
+ # +value+ is plain Ruby data (the application default for reasons "flag_not_found" and "error"); +reason+ is one of
31
+ # "rule_match", "default", "off", "flag_not_found", "error"; +revision+ is the evaluated revision (0 without one);
32
+ # +rule_index+ / +rule_id+ identify the matching rule; +in_rollout+ and +bucket+ (0–99.99) are set for percentage
33
+ # rollouts; +error+ explains reason "error"; +trace+ is a list of {Engine::TraceStep}.
34
+ class EvaluationDetail
35
+ attr_reader :flag_key, :value, :reason, :revision, :rule_index, :rule_id, :in_rollout, :bucket, :trace, :error
36
+
37
+ def initialize(flag_key:, value:, reason:, revision:, rule_index: nil, rule_id: nil, in_rollout: nil, bucket: nil, trace: [], error: nil, raw: nil)
38
+ @flag_key = flag_key
39
+ @value = value
40
+ @reason = reason
41
+ @revision = revision
42
+ @rule_index = rule_index
43
+ @rule_id = rule_id
44
+ @in_rollout = in_rollout
45
+ @bucket = bucket
46
+ @trace = trace.freeze
47
+ @error = error
48
+ @raw = raw
49
+ freeze
50
+ end
51
+
52
+ # @api private
53
+ def self.from_result(r, default)
54
+ js = Engine::Js
55
+ use_default = r.reason == "flag_not_found" || r.reason == "error"
56
+ rev = js.to_number(r.revision)
57
+ rule_id = nil
58
+ if !r.rule_index.nil? && !r.rule_id.equal?(Engine::UNDEFINED)
59
+ rule_id = r.rule_id.is_a?(String) ? r.rule_id : js.stringify(r.rule_id)
60
+ end
61
+ new(
62
+ flag_key: r.flag_key,
63
+ value: use_default ? default : js.to_ruby(r.value),
64
+ reason: r.reason,
65
+ revision: rev.finite? ? rev.to_i : 0,
66
+ rule_index: r.rule_index,
67
+ rule_id: rule_id,
68
+ in_rollout: r.in_rollout,
69
+ bucket: r.bucket,
70
+ trace: r.trace,
71
+ error: r.error,
72
+ raw: use_default ? js.from_ruby(default) : r.value
73
+ )
74
+ end
75
+
76
+ # The served value as JSON text (object keys in configuration order), or nil when nothing was served.
77
+ def json = Engine::Js.stringify(@raw)
78
+
79
+ # The type of the served value: "boolean", "string", "number", "array", "object", "null" or "undefined".
80
+ def type_name = Engine::Js.type_name(@raw)
81
+
82
+ def to_h
83
+ {
84
+ flag_key: flag_key, value: value, reason: reason, revision: revision, rule_index: rule_index, rule_id: rule_id,
85
+ in_rollout: in_rollout, bucket: bucket, trace: trace.map(&:to_h), error: error
86
+ }
87
+ end
88
+
89
+ def inspect = "#<NanoFlags::EvaluationDetail #{flag_key}=#{value.inspect} (#{reason}, r#{revision})>"
90
+ end
91
+ end
@@ -1,119 +1,126 @@
1
- # frozen_string_literal: true
2
-
3
- require "net/http"
4
- require "uri"
5
-
6
- module NanoFlags
7
- # HTTP for the client: blocking requests and a server-sent event reader on Net::HTTP. Proxy settings come from the
8
- # environment (`HTTPS_PROXY`, `NO_PROXY`), the CA store from OpenSSL's defaults (`SSL_CERT_FILE`). Redirects are
9
- # never followed.
10
- #
11
- # Any object with the same two methods can be passed as the client's +http:+ option.
12
- module HTTP
13
- # A complete response; header names are lower-case.
14
- Response = Struct.new(:status, :headers, :body) do
15
- def header(name) = headers[name.to_s.downcase]
16
- def ok? = status.between?(200, 299)
17
- end
18
-
19
- # Incremental text/event-stream parser.
20
- class SseParser
21
- def initialize
22
- @buffer = +""
23
- @event = "message"
24
- @data = []
25
- end
26
-
27
- # Feeds a chunk; yields each complete event as (event, data).
28
- def feed(chunk)
29
- @buffer << chunk.b
30
- while (p = @buffer.index("\n"))
31
- line = @buffer.slice!(0, p + 1).chomp.delete_suffix("\r").force_encoding(Encoding::UTF_8)
32
- if line.empty?
33
- yield @event, @data.join("\n") unless @data.empty?
34
- @event = "message"
35
- @data = []
36
- next
37
- end
38
- next if line.start_with?(":")
39
-
40
- field, value = line.split(":", 2)
41
- value = value.to_s.delete_prefix(" ")
42
- case field
43
- when "event" then @event = value
44
- when "data" then @data << value
45
- end
46
- end
47
- @buffer.clear if @buffer.bytesize > 65_536
48
- end
49
- end
50
-
51
- # The default transport.
52
- class NetHttp
53
- MAX_BODY = 16 * 1024 * 1024
54
-
55
- def initialize(user_agent: nil)
56
- @user_agent = user_agent
57
- end
58
-
59
- # Performs one request and returns a {Response}. Raises on transport failures (no connection, timeout).
60
- def call(method, url, headers, body, timeout)
61
- uri = URI(url)
62
- http = connection(uri, timeout, timeout)
63
- http.start do |h|
64
- req = Net::HTTPGenericRequest.new(method, !body.nil?, method != "HEAD", uri.request_uri, headers)
65
- req.body = body if body
66
- h.request(req) do |res|
67
- buf = +""
68
- res.read_body do |chunk|
69
- buf << chunk
70
- raise IOError, "response body larger than 16 MiB" if buf.bytesize > MAX_BODY
71
- end
72
- return Response.new(res.code.to_i, res.each_header.to_h, buf.force_encoding(Encoding::UTF_8))
73
- end
74
- end
75
- end
76
-
77
- # Reads a server-sent event stream, yielding (event, data) until it ends, the block returns +:stop+, nothing
78
- # arrives for +read_timeout+ seconds, or +on_open+'s closer is called (from any thread). Returns the HTTP status
79
- # (0 when no response arrived).
80
- def stream(url, headers, open_timeout:, read_timeout:, on_open: nil)
81
- uri = URI(url)
82
- http = connection(uri, open_timeout, read_timeout)
83
- status = 0
84
- # Thrown through Net::HTTP, :stop skips reading the rest of the (endless) body; `start` closes the socket.
85
- catch(:stop) do
86
- http.start do |h|
87
- on_open&.call(-> { h.finish if h.started? })
88
- req = Net::HTTP::Get.new(uri.request_uri, headers)
89
- h.request(req) do |res|
90
- status = res.code.to_i
91
- next unless status == 200
92
-
93
- parser = SseParser.new
94
- res.read_body do |chunk|
95
- parser.feed(chunk) { |event, data| throw :stop if yield(event, data) == :stop }
96
- end
97
- end
98
- end
99
- end
100
- status
101
- rescue IOError, Errno::EBADF
102
- status # closed from another thread
103
- end
104
-
105
- private
106
-
107
- def connection(uri, open_timeout, read_timeout)
108
- http = Net::HTTP.new(uri.host, uri.port)
109
- http.use_ssl = uri.scheme == "https"
110
- http.open_timeout = open_timeout
111
- http.read_timeout = read_timeout
112
- http.write_timeout = open_timeout if http.respond_to?(:write_timeout=)
113
- http.ssl_timeout = open_timeout if http.use_ssl?
114
- http.keep_alive_timeout = 2
115
- http
116
- end
117
- end
118
- end
119
- end
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+
6
+ module NanoFlags
7
+ # HTTP for the client: blocking requests and a server-sent event reader on Net::HTTP. Proxy settings come from the
8
+ # environment (`HTTPS_PROXY`, `NO_PROXY`), the CA store from OpenSSL's defaults (`SSL_CERT_FILE`). Redirects are
9
+ # never followed.
10
+ #
11
+ # Any object with the same methods can be passed as the client's +http:+ option (+websocket+ is optional: without it
12
+ # the client uses the event stream instead of the live socket).
13
+ module HTTP
14
+ # A complete response; header names are lower-case.
15
+ Response = Struct.new(:status, :headers, :body) do
16
+ def header(name) = headers[name.to_s.downcase]
17
+ def ok? = status.between?(200, 299)
18
+ end
19
+
20
+ # Incremental text/event-stream parser.
21
+ class SseParser
22
+ def initialize
23
+ @buffer = +""
24
+ @event = "message"
25
+ @data = []
26
+ end
27
+
28
+ # Feeds a chunk; yields each complete event as (event, data).
29
+ def feed(chunk)
30
+ @buffer << chunk.b
31
+ while (p = @buffer.index("\n"))
32
+ line = @buffer.slice!(0, p + 1).chomp.delete_suffix("\r").force_encoding(Encoding::UTF_8)
33
+ if line.empty?
34
+ yield @event, @data.join("\n") unless @data.empty?
35
+ @event = "message"
36
+ @data = []
37
+ next
38
+ end
39
+ next if line.start_with?(":")
40
+
41
+ field, value = line.split(":", 2)
42
+ value = value.to_s.delete_prefix(" ")
43
+ case field
44
+ when "event" then @event = value
45
+ when "data" then @data << value
46
+ end
47
+ end
48
+ @buffer.clear if @buffer.bytesize > 65_536
49
+ end
50
+ end
51
+
52
+ # The default transport.
53
+ class NetHttp
54
+ MAX_BODY = 16 * 1024 * 1024
55
+
56
+ def initialize(user_agent: nil)
57
+ @user_agent = user_agent
58
+ end
59
+
60
+ # Performs one request and returns a {Response}. Raises on transport failures (no connection, timeout).
61
+ def call(method, url, headers, body, timeout)
62
+ uri = URI(url)
63
+ http = connection(uri, timeout, timeout)
64
+ http.start do |h|
65
+ req = Net::HTTPGenericRequest.new(method, !body.nil?, method != "HEAD", uri.request_uri, headers)
66
+ req.body = body if body
67
+ h.request(req) do |res|
68
+ buf = +""
69
+ res.read_body do |chunk|
70
+ buf << chunk
71
+ raise IOError, "response body larger than 16 MiB" if buf.bytesize > MAX_BODY
72
+ end
73
+ return Response.new(res.code.to_i, res.each_header.to_h, buf.force_encoding(Encoding::UTF_8))
74
+ end
75
+ end
76
+ end
77
+
78
+ # Reads a server-sent event stream, yielding (event, data) until it ends, the block returns +:stop+, nothing
79
+ # arrives for +read_timeout+ seconds, or +on_open+'s closer is called (from any thread). Returns the HTTP status
80
+ # (0 when no response arrived).
81
+ def stream(url, headers, open_timeout:, read_timeout:, on_open: nil)
82
+ uri = URI(url)
83
+ http = connection(uri, open_timeout, read_timeout)
84
+ status = 0
85
+ # Thrown through Net::HTTP, :stop skips reading the rest of the (endless) body; `start` closes the socket.
86
+ catch(:stop) do
87
+ http.start do |h|
88
+ on_open&.call(-> { h.finish if h.started? })
89
+ req = Net::HTTP::Get.new(uri.request_uri, headers)
90
+ h.request(req) do |res|
91
+ status = res.code.to_i
92
+ next unless status == 200
93
+
94
+ parser = SseParser.new
95
+ res.read_body do |chunk|
96
+ parser.feed(chunk) { |event, data| throw :stop if yield(event, data) == :stop }
97
+ end
98
+ end
99
+ end
100
+ end
101
+ status
102
+ rescue IOError, Errno::EBADF
103
+ status # closed from another thread
104
+ end
105
+
106
+ # Opens the live WebSocket (see {NanoFlags::WebSocket}); returns a {WebSocket::Connection}. Raises when no
107
+ # socket could be opened ({WebSocket::HandshakeError#status} carries the HTTP status of a refused upgrade).
108
+ def websocket(url, headers, protocols:, open_timeout:)
109
+ WebSocket.connect(url, headers: headers, protocols: protocols, open_timeout: open_timeout)
110
+ end
111
+
112
+ private
113
+
114
+ def connection(uri, open_timeout, read_timeout)
115
+ http = Net::HTTP.new(uri.host, uri.port)
116
+ http.use_ssl = uri.scheme == "https"
117
+ http.open_timeout = open_timeout
118
+ http.read_timeout = read_timeout
119
+ http.write_timeout = open_timeout if http.respond_to?(:write_timeout=)
120
+ http.ssl_timeout = open_timeout if http.use_ssl?
121
+ http.keep_alive_timeout = 2
122
+ http
123
+ end
124
+ end
125
+ end
126
+ end
@@ -1,14 +1,14 @@
1
- # frozen_string_literal: true
2
-
3
- module NanoFlags
4
- # The hosted NanoFlags edge. With this base URL (the default) every bundle is verified against
5
- # {OFFICIAL_SIGNING_KEYS}, and unsigned bundles are refused.
6
- OFFICIAL_EDGE_URL = "https://edge.nanoflags.io"
7
-
8
- # The public halves of the production bundle-signing keys (Ed25519, safe to embed). A bundle signed with a key id
9
- # that is not listed here (a rotation after this release) makes the client load `GET /v1/keys` once (again at
10
- # most once a minute). Keep in sync with packages/sdk/src/keys.ts.
11
- OFFICIAL_SIGNING_KEYS = [
12
- { "kty" => "OKP", "crv" => "Ed25519", "x" => "wQu1EsaE-yTjqpUbibGyBrajy3IiRb7LyaiqeYRxG4U", "kid" => "k1" }.freeze
13
- ].freeze
14
- end
1
+ # frozen_string_literal: true
2
+
3
+ module NanoFlags
4
+ # The hosted NanoFlags edge. With this base URL (the default) every bundle is verified against
5
+ # {OFFICIAL_SIGNING_KEYS}, and unsigned bundles are refused.
6
+ OFFICIAL_EDGE_URL = "https://edge.nanoflags.io"
7
+
8
+ # The public halves of the production bundle-signing keys (Ed25519, safe to embed). A bundle signed with a key id
9
+ # that is not listed here (a rotation after this release) makes the client load `GET /v1/keys` once (again at
10
+ # most once a minute). Keep in sync with packages/sdk/src/keys.ts.
11
+ OFFICIAL_SIGNING_KEYS = [
12
+ { "kty" => "OKP", "crv" => "Ed25519", "x" => "wQu1EsaE-yTjqpUbibGyBrajy3IiRb7LyaiqeYRxG4U", "kid" => "k1" }.freeze
13
+ ].freeze
14
+ end
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ module NanoFlags
4
+ # Header that carries a test-session token between services.
5
+ SESSION_HEADER = "x-nanoflags-session"
6
+ # The Rack env key of the header.
7
+ SESSION_RACK_HEADER = "HTTP_X_NANOFLAGS_SESSION"
8
+
9
+ # Evaluator bound to one test session ({Client#session}). While {#active?}, flags are evaluated against the session's
10
+ # pinned bundle with the context +session.context.merge(context)+, and sampled events carry the session id. When the
11
+ # session is unknown, not permitted for this service, or expired, it evaluates exactly like the client. Sessions
12
+ # change which snapshot and context an evaluation uses; they grant no data access and must not be used for
13
+ # authorization.
14
+ class SessionEvaluator
15
+ def initialize(client, state)
16
+ @client = client
17
+ @state = state
18
+ end
19
+
20
+ # True while the session is known and has not expired. Re-evaluated on every call.
21
+ def active? = !@state.nil? && Time.now.to_f < @state.expires_at_ts
22
+ alias active active?
23
+
24
+ # Session id, or nil when the session could not be resolved.
25
+ def id = @state&.id
26
+
27
+ # ISO 8601 expiry time, or nil when the session could not be resolved.
28
+ def expires_at = @state&.expires_at
29
+
30
+ # The revision evaluations currently run against.
31
+ def revision = active? ? @state.bundle["revision"].to_i : @client.revision
32
+
33
+ def bool_variation(key, default, context = nil) = run(key, default, context, Client::ACCEPT_BOOL).value
34
+ def string_variation(key, default, context = nil) = run(key, default, context, Client::ACCEPT_STRING).value
35
+ def number_variation(key, default, context = nil) = run(key, default, context, Client::ACCEPT_NUMBER).value
36
+ def json_variation(key, default, context = nil) = run(key, default, context, Client::ACCEPT_ANY).value
37
+ def bool_variation_detail(key, default, context = nil) = run(key, default, context, Client::ACCEPT_BOOL)
38
+ def string_variation_detail(key, default, context = nil) = run(key, default, context, Client::ACCEPT_STRING)
39
+ def number_variation_detail(key, default, context = nil) = run(key, default, context, Client::ACCEPT_NUMBER)
40
+ def json_variation_detail(key, default, context = nil) = run(key, default, context, Client::ACCEPT_ANY)
41
+ def evaluate(key, default, context = nil) = run(key, default, context, nil)
42
+
43
+ def inspect = "#<NanoFlags::SessionEvaluator active=#{active?} id=#{id.inspect} revision=#{revision.inspect}>"
44
+
45
+ private
46
+
47
+ def run(key, default, context, accepts) = @client.__send__(:run, key, default, context, accepts, active? ? @state : nil)
48
+ end
49
+
50
+ # Request-scoped test sessions: the session of the request (or job) being handled lives in fiber storage, so it
51
+ # follows the request through the code that handles it (and, on Ruby >= 3.2, into threads and fibers started from
52
+ # it) and is invisible to every other request. Nothing is stored on the client.
53
+ Scope = Struct.new(:token, :evaluators, :lock) # @api private
54
+ private_constant :Scope
55
+ SCOPE_KEY = :__nanoflags_session
56
+ private_constant :SCOPE_KEY
57
+
58
+ class << self
59
+ # A session token is opaque; it only has to be safe to put in a header (1–512 printable ASCII characters).
60
+ def session_token?(value) = value.is_a?(String) && value.match?(/\A[\x21-\x7e]{1,512}\z/)
61
+
62
+ # Runs the block with +token+ as the current test session (an absent or malformed token: outside any session),
63
+ # restoring the previous one afterwards. For jobs and queues: pass the token along with the job.
64
+ def with_session(token)
65
+ token = token.strip if token.is_a?(String)
66
+ previous = scope
67
+ self.scope = session_token?(token) ? Scope.new(token, {}.compare_by_identity, Mutex.new) : nil
68
+ yield
69
+ ensure
70
+ self.scope = previous
71
+ end
72
+
73
+ # The token of the current request's session, or nil.
74
+ def current_session = scope&.token
75
+
76
+ # Headers to add to downstream calls so the next service joins the same session: +{ "x-nanoflags-session" =>
77
+ # token }+ inside a session, else +{}+ (always safe to merge).
78
+ def session_headers
79
+ token = current_session
80
+ token ? { SESSION_HEADER => token } : {}
81
+ end
82
+
83
+ # The evaluator for the current request: scoped to its test session inside {with_session} (or the Rack
84
+ # middleware), resolved once per request and client; otherwise one that behaves exactly like the client.
85
+ # Never raises.
86
+ def flags_for(client, service: nil)
87
+ s = scope
88
+ return SessionEvaluator.new(client, nil) unless s
89
+
90
+ s.lock.synchronize { s.evaluators[client] ||= client.session(s.token, service: service) }
91
+ rescue StandardError
92
+ SessionEvaluator.new(client, nil)
93
+ end
94
+
95
+ private
96
+
97
+ if Fiber.respond_to?(:[]=) # Ruby >= 3.2: inherited by threads and fibers created inside the block
98
+ def scope = Fiber[SCOPE_KEY]
99
+ def scope=(value)
100
+ Fiber[SCOPE_KEY] = value
101
+ end
102
+ else
103
+ def scope = Thread.current[SCOPE_KEY]
104
+ def scope=(value)
105
+ Thread.current[SCOPE_KEY] = value
106
+ end
107
+ end
108
+ end
109
+
110
+ # Rack middleware (Rails, Sinatra, Hanami, Roda, …). Reads +x-nanoflags-session+, resolves the session once, and runs
111
+ # the rest of the request inside it: +env["nanoflags.flags"]+ (and {NanoFlags.flags_for}) is the request's
112
+ # evaluator, session-scoped while the session is active and the plain client behaviour otherwise;
113
+ # {NanoFlags.session_headers} carries the session to downstream calls. Needs no gem besides this one.
114
+ #
115
+ # # config/application.rb
116
+ # config.middleware.use NanoFlags::SessionMiddleware, FLAGS
117
+ # # a controller
118
+ # request.env["nanoflags.flags"].bool_variation("checkout-v2", false, { key: current_user.id })
119
+ #
120
+ # The session ends when +call+ returns: code that runs while a streaming body is iterated is outside it.
121
+ class SessionMiddleware
122
+ ENV_KEY = "nanoflags.flags"
123
+
124
+ def initialize(app, client, service: nil)
125
+ @app = app
126
+ @client = client
127
+ @service = service
128
+ end
129
+
130
+ def call(env)
131
+ NanoFlags.with_session(env[SESSION_RACK_HEADER]) do
132
+ env[ENV_KEY] = NanoFlags.flags_for(@client, service: @service)
133
+ @app.call(env)
134
+ end
135
+ end
136
+ end
137
+ end