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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +40 -20
- data/LICENSE +202 -202
- data/NOTICE +4 -4
- data/README.md +206 -152
- data/lib/nanoflags/client.rb +1225 -869
- data/lib/nanoflags/engine/js.rb +531 -531
- data/lib/nanoflags/engine/json.rb +200 -200
- data/lib/nanoflags/engine.rb +407 -407
- data/lib/nanoflags/evaluation_detail.rb +91 -87
- data/lib/nanoflags/http.rb +126 -119
- data/lib/nanoflags/keys.rb +14 -14
- data/lib/nanoflags/session.rb +137 -0
- data/lib/nanoflags/store.rb +59 -59
- data/lib/nanoflags/verify.rb +180 -180
- data/lib/nanoflags/version.rb +6 -6
- data/lib/nanoflags/websocket.rb +411 -0
- data/lib/nanoflags.rb +12 -10
- metadata +9 -6
|
@@ -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
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
#
|
|
25
|
-
#
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
#
|
|
29
|
-
#
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
@
|
|
39
|
-
@
|
|
40
|
-
@
|
|
41
|
-
@
|
|
42
|
-
@
|
|
43
|
-
@
|
|
44
|
-
@
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
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
|
data/lib/nanoflags/http.rb
CHANGED
|
@@ -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
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
def
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
@
|
|
24
|
-
@
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
@event
|
|
35
|
-
@
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
value =
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
when "
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
http
|
|
64
|
-
|
|
65
|
-
req
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
#
|
|
79
|
-
#
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
http
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
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
|
data/lib/nanoflags/keys.rb
CHANGED
|
@@ -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
|