benchdog 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.
- checksums.yaml +7 -0
- data/LICENSE +21 -0
- data/README.md +67 -0
- data/lib/benchdog/admin_api/audit_routes.rb +94 -0
- data/lib/benchdog/admin_api/flag_routes.rb +139 -0
- data/lib/benchdog/admin_api/meta_routes.rb +159 -0
- data/lib/benchdog/admin_api/request.rb +41 -0
- data/lib/benchdog/admin_api.rb +208 -0
- data/lib/benchdog/approvals.rb +60 -0
- data/lib/benchdog/audit.rb +76 -0
- data/lib/benchdog/bucket.rb +11 -0
- data/lib/benchdog/client.rb +36 -0
- data/lib/benchdog/evaluator.rb +194 -0
- data/lib/benchdog/expression.rb +122 -0
- data/lib/benchdog/flag.schema.json +419 -0
- data/lib/benchdog/payload.rb +18 -0
- data/lib/benchdog/schedule.rb +57 -0
- data/lib/benchdog/spec/store_examples.rb +121 -0
- data/lib/benchdog/store.rb +137 -0
- data/lib/benchdog/usage.rb +39 -0
- data/lib/benchdog/validation.rb +27 -0
- data/lib/benchdog/values.rb +49 -0
- data/lib/benchdog/version.rb +5 -0
- data/lib/benchdog.rb +23 -0
- data/sig/admin_api.rbs +202 -0
- data/sig/benchdog.rbs +127 -0
- data/sig/json_schemer.rbs +10 -0
- metadata +86 -0
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "securerandom"
|
|
5
|
+
require "uri"
|
|
6
|
+
require_relative "admin_api/request"
|
|
7
|
+
|
|
8
|
+
module Benchdog
|
|
9
|
+
# The Benchdog admin and client API (spec/openapi.yaml) as a plain Rack app. Mount it where the
|
|
10
|
+
# dashboard looks for it, for example at /benchdog/api:
|
|
11
|
+
#
|
|
12
|
+
# map("/benchdog/api") { run Benchdog::AdminApi.new(store:, environments:, authenticate:, role_for:) }
|
|
13
|
+
#
|
|
14
|
+
# Options:
|
|
15
|
+
# - store: the flag store.
|
|
16
|
+
# - environments: [{ name:, protected:, promotes_to: }], in promotion order.
|
|
17
|
+
# - authenticate: ->(rack_env) { { "id" => ..., "name" => ... } or nil }.
|
|
18
|
+
# - role_for: ->(user, environment) { "viewer", "editor", "approver", "admin" or nil }.
|
|
19
|
+
# - actor_for: ->(rack_env, user) { actor hash or nil }, for GET /client. Default: the user id.
|
|
20
|
+
# - groups: name => callable on the actor hash.
|
|
21
|
+
# - audience: { groups: [{ key:, description: }], actor_types: [{ type:, label: }],
|
|
22
|
+
# lookup_actors: ->(query, user) { [{ id:, name:, note: }] } }.
|
|
23
|
+
# - cron_secret: the bearer secret of POST /cron/schedules. Without it, the route is off.
|
|
24
|
+
# - references: the output of `benchdog refs --json`, or a callable that gives it.
|
|
25
|
+
# - feed, approvals, backend, keep_alive (seconds), stale_days.
|
|
26
|
+
class AdminApi
|
|
27
|
+
# An error with an HTTP status and a code (application/problem+json).
|
|
28
|
+
class Problem < StandardError
|
|
29
|
+
attr_reader :status, :code
|
|
30
|
+
|
|
31
|
+
def initialize(status, code, message)
|
|
32
|
+
super(message)
|
|
33
|
+
@status = status
|
|
34
|
+
@code = code
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
RANK = { "viewer" => 1, "editor" => 2, "approver" => 3, "admin" => 4 }.freeze
|
|
39
|
+
SOURCES = %w[dashboard cli].freeze
|
|
40
|
+
|
|
41
|
+
ROUTES = [
|
|
42
|
+
["GET", %r{\A/capabilities\z}, :capabilities],
|
|
43
|
+
["GET", %r{\A/me\z}, :me],
|
|
44
|
+
["GET", %r{\A/references\z}, :references],
|
|
45
|
+
["GET", %r{\A/environments\z}, :environments],
|
|
46
|
+
["GET", %r{\A/environments/([^/]+)/flags\z}, :flag_set],
|
|
47
|
+
["GET", %r{\A/environments/([^/]+)/flags/([^/]+)\z}, :get_flag],
|
|
48
|
+
["PUT", %r{\A/environments/([^/]+)/flags/([^/]+)\z}, :put_flag],
|
|
49
|
+
["DELETE", %r{\A/environments/([^/]+)/flags/([^/]+)\z}, :delete_flag],
|
|
50
|
+
["POST", %r{\A/environments/([^/]+)/flags/([^/]+)/kill\z}, :kill],
|
|
51
|
+
["POST", %r{\A/environments/([^/]+)/flags/([^/]+)/promote\z}, :promote],
|
|
52
|
+
["PUT", %r{\A/environments/([^/]+)/segments/([^/]+)\z}, :put_segment],
|
|
53
|
+
["DELETE", %r{\A/environments/([^/]+)/segments/([^/]+)\z}, :delete_segment],
|
|
54
|
+
["GET", %r{\A/environments/([^/]+)/audit\z}, :audit],
|
|
55
|
+
["GET", %r{\A/environments/([^/]+)/audit/export\z}, :audit_export],
|
|
56
|
+
["GET", %r{\A/environments/([^/]+)/audit/verify\z}, :audit_verify],
|
|
57
|
+
["GET", %r{\A/environments/([^/]+)/approvals\z}, :approvals],
|
|
58
|
+
["POST", %r{\A/environments/([^/]+)/approvals/([^/]+)/(approve|reject)\z}, :decide],
|
|
59
|
+
["GET", %r{\A/environments/([^/]+)/usage\z}, :usage],
|
|
60
|
+
["POST", %r{\A/cron/schedules\z}, :cron],
|
|
61
|
+
["GET", %r{\A/client\z}, :client],
|
|
62
|
+
["GET", %r{\A/audience\z}, :audience],
|
|
63
|
+
["GET", %r{\A/actors\z}, :actors],
|
|
64
|
+
["GET", %r{\A/flags/([^/]+)/check\z}, :check],
|
|
65
|
+
["GET", %r{\A/stream\z}, :stream]
|
|
66
|
+
].freeze
|
|
67
|
+
|
|
68
|
+
def initialize(**options)
|
|
69
|
+
@options = options
|
|
70
|
+
@store = options.fetch(:store)
|
|
71
|
+
@environments = options.fetch(:environments)
|
|
72
|
+
@known = @environments.to_h { |e| [e[:name], e] }
|
|
73
|
+
@feed = options[:feed] || MemoryChangeFeed.new
|
|
74
|
+
@approvals = options[:approvals] || MemoryApprovalStore.new
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def call(env)
|
|
78
|
+
request = Request.new(env)
|
|
79
|
+
path = request.path
|
|
80
|
+
ROUTES.each do |method, pattern, handler|
|
|
81
|
+
match = pattern.match(path)
|
|
82
|
+
next unless match && method == request.method
|
|
83
|
+
|
|
84
|
+
return send(handler, request, *match.captures.map { |c| URI.decode_uri_component(c.to_s) })
|
|
85
|
+
end
|
|
86
|
+
raise Problem.new(404, "NOT_FOUND", "No route for #{request.method} #{path}")
|
|
87
|
+
rescue Problem => e
|
|
88
|
+
problem(e)
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
private
|
|
92
|
+
|
|
93
|
+
def json(body, status = 200, headers = {})
|
|
94
|
+
[status, { "content-type" => "application/json" }.merge(headers), [JSON.generate(body)]]
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def no_content = [204, {}, []]
|
|
98
|
+
|
|
99
|
+
def problem(error)
|
|
100
|
+
body = { "type" => "about:blank", "title" => error.message, "status" => error.status, "code" => error.code }
|
|
101
|
+
[error.status, { "content-type" => "application/problem+json" }, [JSON.generate(body)]]
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
def invalid(message) = Problem.new(422, "INVALID", message)
|
|
105
|
+
|
|
106
|
+
def not_found(message) = Problem.new(404, "NOT_FOUND", message)
|
|
107
|
+
|
|
108
|
+
def read_reason(value)
|
|
109
|
+
return value if value.is_a?(String) && !value.strip.empty? && value.length <= 1000
|
|
110
|
+
|
|
111
|
+
raise invalid("A reason (1 to 1000 characters) is required")
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
def environment(name)
|
|
115
|
+
raise not_found("No environment \"#{name}\"") unless @known.key?(name)
|
|
116
|
+
|
|
117
|
+
name
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
def signed_in(request)
|
|
121
|
+
user = @options.fetch(:authenticate).call(request.env)
|
|
122
|
+
raise Problem.new(401, "UNAUTHENTICATED", "Sign in first") unless user
|
|
123
|
+
|
|
124
|
+
user.transform_keys(&:to_s)
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
def role(user, env) = @options.fetch(:role_for).call(user, env)&.to_s
|
|
128
|
+
|
|
129
|
+
def need(user, env, role)
|
|
130
|
+
actual = role(user, env)
|
|
131
|
+
return if actual && RANK.fetch(actual) >= RANK.fetch(role)
|
|
132
|
+
|
|
133
|
+
raise Problem.new(403, "FORBIDDEN", "This needs the #{role} role in #{env}")
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
# A user with a role in one environment or more: for a read that has no environment.
|
|
137
|
+
def any_role(user)
|
|
138
|
+
raise Problem.new(403, "FORBIDDEN", "This needs a role") unless @environments.any? { |e| role(user, e[:name]) }
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
# A signed-in user with at least `role` in the environment of the path.
|
|
142
|
+
def authorize(request, name, role)
|
|
143
|
+
user = signed_in(request)
|
|
144
|
+
env = environment(name)
|
|
145
|
+
need(user, env, role)
|
|
146
|
+
[user, env]
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def etag(env) = "\"#{@store.version(env)}\""
|
|
150
|
+
|
|
151
|
+
def check_if_match(request, env)
|
|
152
|
+
expected = request.header("If-Match")
|
|
153
|
+
return if expected.nil? || expected == "*" || expected == etag(env)
|
|
154
|
+
|
|
155
|
+
raise Problem.new(412, "PRECONDITION_FAILED", "The flag set changed after you read it")
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
def audit_input(request, user, reason, action = nil)
|
|
159
|
+
source = request.header("X-Benchdog-Source")
|
|
160
|
+
{
|
|
161
|
+
"actor" => user.slice("id", "name").compact,
|
|
162
|
+
"source" => source && SOURCES.include?(source) ? source : "api",
|
|
163
|
+
"reason" => reason,
|
|
164
|
+
"action" => action
|
|
165
|
+
}.compact
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
def write(env, change, input)
|
|
169
|
+
begin
|
|
170
|
+
@store.write(env, change, input)
|
|
171
|
+
rescue NotFoundError => e
|
|
172
|
+
raise not_found(e.message)
|
|
173
|
+
rescue CapabilityMissing => e
|
|
174
|
+
raise Problem.new(422, "CAPABILITY_MISSING", e.message)
|
|
175
|
+
end
|
|
176
|
+
@feed.publish(env)
|
|
177
|
+
end
|
|
178
|
+
|
|
179
|
+
# Applies a change, or, in a protected environment, keeps it as an approval request and
|
|
180
|
+
# answers 202. The kill switch does not use this: it never waits.
|
|
181
|
+
def change(request, user, env, next_change, reason, action = nil)
|
|
182
|
+
if @known.dig(env, :protected)
|
|
183
|
+
approval = { "id" => SecureRandom.uuid, "environment" => env, "state" => "pending",
|
|
184
|
+
"requestedBy" => user["id"], "requestedAt" => Time.now.utc.iso8601(3), "reason" => reason,
|
|
185
|
+
"decidedBy" => nil, "change" => next_change }
|
|
186
|
+
@approvals.create(approval)
|
|
187
|
+
return json(approval, 202)
|
|
188
|
+
end
|
|
189
|
+
write(env, next_change, audit_input(request, user, reason, action))
|
|
190
|
+
yield
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
def flag_in(env, key)
|
|
194
|
+
@store.load(env)["flags"][key] or raise not_found("No flag \"#{key}\" in #{env}")
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
def query_environment(request)
|
|
198
|
+
name = request.query["environment"]
|
|
199
|
+
raise invalid("\"environment\" is required") if name.nil? || name.empty?
|
|
200
|
+
|
|
201
|
+
environment(name)
|
|
202
|
+
end
|
|
203
|
+
end
|
|
204
|
+
end
|
|
205
|
+
|
|
206
|
+
require_relative "admin_api/meta_routes"
|
|
207
|
+
require_relative "admin_api/flag_routes"
|
|
208
|
+
require_relative "admin_api/audit_routes"
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Benchdog
|
|
4
|
+
# Approval requests in memory: a change in a protected environment that waits for a second
|
|
5
|
+
# person. An approval is a JSON hash with "id", "environment", "state", "requestedBy",
|
|
6
|
+
# "requestedAt", "reason", "decidedBy" and "change".
|
|
7
|
+
class MemoryApprovalStore
|
|
8
|
+
def initialize
|
|
9
|
+
@items = {}
|
|
10
|
+
@lock = Mutex.new
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
def create(approval)
|
|
14
|
+
@lock.synchronize { @items[[approval["environment"], approval["id"]]] = Store.copy(approval) }
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def get(environment, id) = @lock.synchronize { @items[[environment, id]]&.then { |a| Store.copy(a) } }
|
|
18
|
+
|
|
19
|
+
# The requests of an environment, oldest first.
|
|
20
|
+
def list(environment, state = nil)
|
|
21
|
+
@lock.synchronize do
|
|
22
|
+
found = @items.values.select { |a| a["environment"] == environment && (state.nil? || a["state"] == state) }
|
|
23
|
+
Store.copy(found.sort_by { |a| a["requestedAt"] })
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# Moves a pending request to another state in one step. Gives nil when it is not pending.
|
|
28
|
+
def decide(environment, id, decision)
|
|
29
|
+
@lock.synchronize do
|
|
30
|
+
item = @items[[environment, id]]
|
|
31
|
+
next nil unless item && item["state"] == "pending"
|
|
32
|
+
|
|
33
|
+
item.merge!(decision)
|
|
34
|
+
Store.copy(item)
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def set_state(environment, id, state)
|
|
39
|
+
@lock.synchronize { @items[[environment, id]]&.store("state", state) }
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# Tells the listeners in this process that an environment changed.
|
|
44
|
+
class MemoryChangeFeed
|
|
45
|
+
def initialize
|
|
46
|
+
@listeners = Hash.new { |h, k| h[k] = [] }
|
|
47
|
+
@lock = Mutex.new
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Returns a callable that removes the listener.
|
|
51
|
+
def subscribe(environment, &listener)
|
|
52
|
+
@lock.synchronize { @listeners[environment] << listener }
|
|
53
|
+
-> { @lock.synchronize { @listeners[environment].delete(listener) } }
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def publish(environment)
|
|
57
|
+
@lock.synchronize { @listeners[environment].dup }.each(&:call)
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
end
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "digest"
|
|
4
|
+
require "json"
|
|
5
|
+
|
|
6
|
+
module Benchdog
|
|
7
|
+
# The audit hash chain (SPEC section 8).
|
|
8
|
+
module Audit
|
|
9
|
+
GENESIS_HASH = "0" * 64
|
|
10
|
+
|
|
11
|
+
module_function
|
|
12
|
+
|
|
13
|
+
# Canonical JSON (RFC 8785): keys in UTF-16 code unit order, no white space, numbers in
|
|
14
|
+
# their shortest form (an integral float has no ".0").
|
|
15
|
+
def canonical_json(value)
|
|
16
|
+
case value
|
|
17
|
+
when Hash then canonical_object(value)
|
|
18
|
+
when Array then "[#{value.map { |v| canonical_json(v) }.join(',')}]"
|
|
19
|
+
when Float then canonical_float(value)
|
|
20
|
+
else JSON.generate(value)
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def canonical_object(hash)
|
|
25
|
+
pairs = hash.sort_by { |k, _| k.to_s.encode("UTF-16BE").bytes }
|
|
26
|
+
"{#{pairs.map { |k, v| "#{JSON.generate(k.to_s)}:#{canonical_json(v)}" }.join(',')}}"
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def canonical_float(value)
|
|
30
|
+
raise ArgumentError, "Canonical JSON has no form for #{value}" unless value.finite?
|
|
31
|
+
|
|
32
|
+
value == value.floor && value.abs < 1e21 ? value.to_i.to_s : value.to_s
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# The SHA-256 of the entry without its "hash" field.
|
|
36
|
+
def hash_entry(entry)
|
|
37
|
+
Digest::SHA256.hexdigest(canonical_json(entry.except("hash")))
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Checks a chain in order (SPEC section 8).
|
|
41
|
+
def verify_chain(entries)
|
|
42
|
+
prev = GENESIS_HASH
|
|
43
|
+
entries.each_with_index do |entry, index|
|
|
44
|
+
error = entry_error(entry, index, prev)
|
|
45
|
+
return { "valid" => false, "seq" => entry["seq"], "error" => error } if error
|
|
46
|
+
|
|
47
|
+
prev = entry["hash"]
|
|
48
|
+
end
|
|
49
|
+
{ "valid" => true }
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
CSV_COLUMNS = %w[seq at environment flag segment action actor source reason hash].freeze
|
|
53
|
+
|
|
54
|
+
# The entries as CSV (RFC 4180). The actor column has the name, or the id.
|
|
55
|
+
def csv(entries)
|
|
56
|
+
rows = entries.map do |entry|
|
|
57
|
+
CSV_COLUMNS.map do |c|
|
|
58
|
+
csv_cell(c == "actor" ? entry["actor"]["name"] || entry["actor"]["id"] : entry[c])
|
|
59
|
+
end.join(",")
|
|
60
|
+
end
|
|
61
|
+
[CSV_COLUMNS.join(","), *rows].join("\r\n")
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def csv_cell(value)
|
|
65
|
+
text = value.to_s
|
|
66
|
+
text.match?(/[",\r\n]/) ? "\"#{text.gsub('"', '""')}\"" : text
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def entry_error(entry, index, prev)
|
|
70
|
+
return "SEQ_GAP" unless entry["seq"] == index + 1
|
|
71
|
+
return "PREV_HASH_MISMATCH" unless entry["prevHash"] == prev
|
|
72
|
+
|
|
73
|
+
"HASH_MISMATCH" unless hash_entry(entry) == entry["hash"]
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
end
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Benchdog
|
|
4
|
+
# Keeps a snapshot of one environment and evaluates from it, with no I/O.
|
|
5
|
+
#
|
|
6
|
+
# benchdog = Benchdog::Client.new(store: store, environment: "production")
|
|
7
|
+
# benchdog.enabled?("new-checkout", { "id" => "user:42" })
|
|
8
|
+
class Client
|
|
9
|
+
attr_reader :snapshot
|
|
10
|
+
|
|
11
|
+
# `groups`: name => callable on the actor hash.
|
|
12
|
+
def initialize(store:, environment:, groups: {})
|
|
13
|
+
@store = store
|
|
14
|
+
@environment = environment
|
|
15
|
+
@groups = groups
|
|
16
|
+
refresh
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# Loads the flag set again.
|
|
20
|
+
def refresh
|
|
21
|
+
@snapshot = @store.load(@environment)
|
|
22
|
+
nil
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# The full result (SPEC section 5.2).
|
|
26
|
+
def details(key, actor = nil, default = nil, context = {})
|
|
27
|
+
Benchdog.evaluate(@snapshot, key, actor ? context.merge("actor" => actor) : context, default, groups: @groups)
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# Is a boolean flag on for the actor?
|
|
31
|
+
def enabled?(key, actor = nil, context = {}) = details(key, actor, false, context).value == true
|
|
32
|
+
|
|
33
|
+
# The value of a flag, or `default` on an error.
|
|
34
|
+
def value(key, actor, default, context = {}) = details(key, actor, default, context).value
|
|
35
|
+
end
|
|
36
|
+
end
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "time"
|
|
4
|
+
|
|
5
|
+
# The Benchdog core.
|
|
6
|
+
module Benchdog
|
|
7
|
+
# The result of one evaluation (SPEC section 5.2).
|
|
8
|
+
class Result
|
|
9
|
+
attr_reader :value, :variation, :reason, :gate, :rule_id, :error_code
|
|
10
|
+
|
|
11
|
+
# `decision` has :variation, :reason and :gate, and can have :rule_id and :error_code.
|
|
12
|
+
def initialize(value, decision)
|
|
13
|
+
@value = value
|
|
14
|
+
@variation = decision[:variation]
|
|
15
|
+
@reason = decision.fetch(:reason)
|
|
16
|
+
@gate = decision[:gate]
|
|
17
|
+
@rule_id = decision[:rule_id]
|
|
18
|
+
@error_code = decision[:error_code]
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def self.error(default, code)
|
|
22
|
+
new(default, { variation: nil, reason: "ERROR", gate: nil, error_code: code })
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# The result as the vectors show it, with camelCase keys.
|
|
26
|
+
def to_h
|
|
27
|
+
h = { "value" => value, "variation" => variation, "reason" => reason, "gate" => gate }
|
|
28
|
+
h["ruleId"] = rule_id if rule_id
|
|
29
|
+
h["errorCode"] = error_code if error_code
|
|
30
|
+
h
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
BOOLEAN_VARIATIONS = [{ "key" => "off", "value" => false }, { "key" => "on", "value" => true }].freeze
|
|
35
|
+
|
|
36
|
+
# Raised inside an evaluation when a flag serves a variation that it does not have.
|
|
37
|
+
class InvalidFlag < StandardError; end
|
|
38
|
+
|
|
39
|
+
# Evaluates one flag (SPEC section 5). It never raises: a problem gives the default value.
|
|
40
|
+
# `flag_set` and `context` use string keys, as JSON.parse gives them. Options: `expected_type`,
|
|
41
|
+
# `groups` (name => callable on the actor), `clock` and `random` (callables).
|
|
42
|
+
def self.evaluate(flag_set, key, context, default, options = {})
|
|
43
|
+
flag = flag_set["flags"].to_h[key]
|
|
44
|
+
error = check(flag, options[:expected_type])
|
|
45
|
+
return Result.error(default, error) if error
|
|
46
|
+
|
|
47
|
+
decision = Evaluator.new(flag_set, context, options).inner(flag, [key])
|
|
48
|
+
Result.new(variation_value(flag, decision[:variation]), decision)
|
|
49
|
+
rescue InvalidFlag
|
|
50
|
+
Result.error(default, "INVALID_FLAG")
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def self.check(flag, expected_type)
|
|
54
|
+
return "FLAG_NOT_FOUND" unless flag
|
|
55
|
+
|
|
56
|
+
"TYPE_MISMATCH" if expected_type && expected_type != flag.fetch("type", "boolean")
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
def self.variation_value(flag, key)
|
|
60
|
+
(flag["variations"] || BOOLEAN_VARIATIONS).find { |v| v["key"] == key }["value"]
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# One evaluation run: the flag set, the actor, the time and the groups.
|
|
64
|
+
class Evaluator
|
|
65
|
+
STEPS = %i[kill_switch prerequisites boolean_gate actor_gate group_gate expression_gate rules
|
|
66
|
+
percentage_of_actors percentage_of_time].freeze
|
|
67
|
+
|
|
68
|
+
def initialize(flag_set, context, options)
|
|
69
|
+
@set = flag_set
|
|
70
|
+
@actor = context["actor"]
|
|
71
|
+
@now = start_time(context, options[:clock])
|
|
72
|
+
@random = context.fetch("random") { (options[:random] || -> { Kernel.rand }).call }
|
|
73
|
+
# With `memberOf` in the context, only that list counts (SPEC section 5.5).
|
|
74
|
+
member_of = context["memberOf"]
|
|
75
|
+
@groups = member_of ? member_of.to_h { |g| [g, ->(_) { true }] } : options[:groups].to_h
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def inner(flag, visiting)
|
|
79
|
+
flag = Benchdog.apply_schedule(flag, @now)
|
|
80
|
+
@flag = flag
|
|
81
|
+
@visiting = visiting
|
|
82
|
+
STEPS.each do |step|
|
|
83
|
+
decision = send(step)
|
|
84
|
+
return decision if decision
|
|
85
|
+
end
|
|
86
|
+
fallthrough
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
private
|
|
90
|
+
|
|
91
|
+
def start_time(context, clock)
|
|
92
|
+
return Time.iso8601(context["now"]).to_r if context["now"]
|
|
93
|
+
|
|
94
|
+
(clock || -> { Time.now.to_r }).call
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def gates = @flag["gates"].to_h
|
|
98
|
+
def off = @flag.fetch("offVariation", "off")
|
|
99
|
+
def on = @flag.fetch("onVariation", "on")
|
|
100
|
+
|
|
101
|
+
def decide(variation, reason, gate, rule_id = nil)
|
|
102
|
+
keys = (@flag["variations"] || BOOLEAN_VARIATIONS).map { |v| v["key"] }
|
|
103
|
+
raise InvalidFlag unless keys.include?(variation)
|
|
104
|
+
|
|
105
|
+
{ variation: variation, reason: reason, gate: gate, rule_id: rule_id }
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
def truthy?(expression)
|
|
109
|
+
scope = Expression::Scope.new(@flag["key"], @actor, @now, @set["segments"].to_h)
|
|
110
|
+
Expression.truthy?(Expression.evaluate(expression, scope))
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def kill_switch
|
|
114
|
+
decide(off, "DISABLED", "disabled") if @flag["enabled"] == false
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def prerequisites
|
|
118
|
+
failed = @flag["prerequisites"].to_a.any? { |pre| !met?(pre) }
|
|
119
|
+
decide(off, "PREREQUISITE_FAILED", "prerequisite") if failed
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
def met?(pre)
|
|
123
|
+
other = @set["flags"].to_h[pre["flag"]]
|
|
124
|
+
return false if other.nil? || @visiting.include?(pre["flag"])
|
|
125
|
+
|
|
126
|
+
flag = @flag
|
|
127
|
+
visiting = @visiting
|
|
128
|
+
result = inner(other, visiting + [pre["flag"]])
|
|
129
|
+
@flag = flag
|
|
130
|
+
@visiting = visiting
|
|
131
|
+
result[:variation] == pre["variation"]
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
def boolean_gate
|
|
135
|
+
decide(on, "STATIC", "boolean") if gates["boolean"] == true
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
def actor_gate
|
|
139
|
+
actor = @actor
|
|
140
|
+
decide(on, "TARGETING_MATCH", "actor") if actor && gates["actors"].to_a.include?(actor["id"])
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def group_gate
|
|
144
|
+
actor = @actor
|
|
145
|
+
return unless actor && gates["groups"].to_a.any? { |g| @groups[g]&.call(actor) == true }
|
|
146
|
+
|
|
147
|
+
decide(on, "TARGETING_MATCH", "group")
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
def expression_gate
|
|
151
|
+
decide(on, "TARGETING_MATCH", "expression") if !gates["expression"].nil? && truthy?(gates["expression"])
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
def rules
|
|
155
|
+
rule = @flag["rules"].to_a.find { |r| truthy?(r["expression"]) }
|
|
156
|
+
serve(rule["serve"], "rule", rule["id"]) if rule
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
def percentage_of_actors
|
|
160
|
+
actor = @actor
|
|
161
|
+
return unless actor
|
|
162
|
+
return unless Benchdog.bucket("#{@flag['key']}#{actor['id']}") < gates.fetch("percentageOfActors", 0) * 1000
|
|
163
|
+
|
|
164
|
+
decide(on, "SPLIT", "percentageOfActors")
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
def percentage_of_time
|
|
168
|
+
decide(on, "SPLIT", "percentageOfTime") if @random < gates.fetch("percentageOfTime", 0) / 100.0
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
def fallthrough
|
|
172
|
+
serve(@flag.fetch("fallthrough", { "variation" => off }), "fallthrough", nil)
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
def serve(target, gate, rule_id)
|
|
176
|
+
if target.key?("variation")
|
|
177
|
+
return decide(target["variation"], gate == "rule" ? "TARGETING_MATCH" : "DEFAULT", gate, rule_id)
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
actor = @actor
|
|
181
|
+
return decide(off, "DEFAULT", gate, rule_id) unless actor
|
|
182
|
+
|
|
183
|
+
decide(rollout(target["rollout"], rule_id || "variant", actor), "SPLIT", gate, rule_id)
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
# The variation of the first rollout band that holds the actor's bucket (SPEC section 7.2).
|
|
187
|
+
def rollout(items, salt, actor)
|
|
188
|
+
b = Benchdog.bucket("#{@flag['key']}:#{salt}#{actor['id']}")
|
|
189
|
+
sum = 0
|
|
190
|
+
found = items.find { |item| b < (sum += item["weight"] * 1000) }
|
|
191
|
+
(found || items.last)["variation"]
|
|
192
|
+
end
|
|
193
|
+
end
|
|
194
|
+
end
|