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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: da74d7d97b0df582abd22655f267712903b87e801b033bacb127a4821758ed3c
4
+ data.tar.gz: f515dea8729ed46daff15a10380ebd40f2dba15d3a855b40f4ea5a37cdc642f3
5
+ SHA512:
6
+ metadata.gz: 8015dc34dadc8d0fe0eec136d4e8e787f3101bc7a77b98506a1607479348274519e77e73ac4c33a78c22f130069536ce162cd273c02b7996ef9a324ef060af51
7
+ data.tar.gz: d14d17774c0d056e05875741636cc239b449de6b4450b384e32abc707399f0d064269a276f9130afa9f350d64dcdb4484b867bbb88fd109551149f01ea875245
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Joe Gaudet
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,67 @@
1
+ # benchdog (Ruby)
2
+
3
+ The Ruby core of [Benchdog](https://joegaudet.com/benchdog/), feature flags for Ember, Rails,
4
+ Django and Node. The gem has no Rails dependency. It has:
5
+
6
+ - The evaluator, which passes the shared vectors in `spec/vectors/`.
7
+ - The store interface and `Benchdog::MemoryStore`.
8
+ - `Benchdog::Client`, which evaluates from a snapshot of one environment, with no I/O.
9
+ - `Benchdog::AdminApi`, the admin and client API of the dashboard, as a plain Rack app.
10
+
11
+ For Rails, use the `benchdog-rails` gem. For Flipper data, use `benchdog-flipper`.
12
+
13
+ ## The client
14
+
15
+ ```ruby
16
+ store = Benchdog::MemoryStore.new
17
+ benchdog = Benchdog::Client.new(store: store, environment: "production",
18
+ groups: { "staff" => ->(actor) { actor["id"].start_with?("staff:") } })
19
+ benchdog.enabled?("new-checkout", { "id" => "user:42" })
20
+ benchdog.value("page-size", { "id" => "user:42" }, 20)
21
+ benchdog.refresh # Loads the flag set again.
22
+ ```
23
+
24
+ ## The admin API
25
+
26
+ ```ruby
27
+ # config.ru
28
+ require "benchdog"
29
+
30
+ api = Benchdog::AdminApi.new(
31
+ store: store,
32
+ environments: [{ name: "development", promotes_to: "production" }, { name: "production", protected: true }],
33
+ authenticate: ->(env) { env["warden"]&.user&.then { |u| { "id" => u.id.to_s, "name" => u.name } } },
34
+ role_for: ->(user, environment) { "admin" }
35
+ )
36
+ map("/benchdog/api") { run api }
37
+ ```
38
+
39
+ The other options are `actor_for`, `groups`, `audience`, `cron_secret` and `references`. The
40
+ comment on `Benchdog::AdminApi` tells what each one does.
41
+
42
+ ## Your own store
43
+
44
+ A store has `capabilities`, `load`, `version`, `write` and `audit_log`. The shared examples test a
45
+ store against the contract:
46
+
47
+ ```ruby
48
+ require "benchdog/spec/store_examples"
49
+
50
+ RSpec.describe MyStore do
51
+ it_behaves_like "a Benchdog store", Benchdog::CAPABILITIES do
52
+ let(:store) { MyStore.new }
53
+ end
54
+ end
55
+ ```
56
+
57
+ ## Checks
58
+
59
+ ```bash
60
+ bundle install
61
+ bundle exec rubocop
62
+ bundle exec steep check
63
+ bundle exec rspec
64
+ ```
65
+
66
+ `pnpm ruby:check` at the repo root runs these checks for each gem. It also runs the admin API
67
+ contract (`packages/api-tests`) against the Rack app.
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Benchdog
4
+ # The routes for the audit log, approvals, usage and the cron.
5
+ class AdminApi
6
+ private
7
+
8
+ def audit(request, name)
9
+ _, env = authorize(request, name, "viewer")
10
+ q = request.query
11
+ limit = number(q["limit"], 50.0)
12
+ limit = 50 if limit.zero? || limit.nan?
13
+ before = q.key?("before") ? number(q["before"], Float::NAN) : Float::INFINITY
14
+ matching = @store.audit_log(env).reverse.select do |e|
15
+ e["seq"] < before && (!q.key?("flag") || e["flag"] == q["flag"]) &&
16
+ (!q.key?("actor") || e["actor"]["id"] == q["actor"])
17
+ end
18
+ entries = matching.first(limit.clamp(1, 500).to_i)
19
+ json({ "entries" => entries, "next" => matching.size > entries.size ? entries.last["seq"] : nil })
20
+ end
21
+
22
+ # A query number, as JavaScript's Number() reads it: no value gives the default.
23
+ def number(text, default)
24
+ if text.nil?
25
+ default
26
+ else
27
+ Float(text.empty? ? "0" : text, exception: false) || Float::NAN
28
+ end
29
+ end
30
+
31
+ def audit_export(request, name)
32
+ _, env = authorize(request, name, "viewer")
33
+ entries = @store.audit_log(env)
34
+ format = request.query.fetch("format", "json")
35
+ if format == "csv"
36
+ return [200, { "content-type" => "text/csv; charset=utf-8",
37
+ "content-disposition" => "attachment; filename=\"benchdog-audit-#{env}.csv\"" },
38
+ [Audit.csv(entries)]]
39
+ end
40
+ raise invalid("\"format\" must be csv or json") unless format == "json"
41
+
42
+ json(entries, 200, { "content-disposition" => "attachment; filename=\"benchdog-audit-#{env}.json\"" })
43
+ end
44
+
45
+ def audit_verify(request, name)
46
+ _, env = authorize(request, name, "viewer")
47
+ json(Audit.verify_chain(@store.audit_log(env)))
48
+ end
49
+
50
+ def approvals(request, name)
51
+ _, env = authorize(request, name, "viewer")
52
+ json({ "approvals" => @approvals.list(env, "pending") })
53
+ end
54
+
55
+ def decide(request, name, id, decision)
56
+ user, env = authorize(request, name, "approver")
57
+ reason = read_reason(request.body["reason"])
58
+ approval = @approvals.get(env, id) or raise not_found("No approval \"#{id}\"")
59
+ if approval["requestedBy"] == user["id"]
60
+ raise Problem.new(403, "FORBIDDEN", "A second person must decide a request")
61
+ end
62
+
63
+ decided = @approvals.decide(env, id, { "state" => decision == "approve" ? "approved" : "rejected",
64
+ "decidedBy" => user["id"], "decisionReason" => reason })
65
+ raise Problem.new(409, "CONFLICT", "The request is already #{approval['state']}") unless decided
66
+ return json(decided) if decision == "reject"
67
+
68
+ text = "#{approval['reason']} (asked by #{approval['requestedBy']}; approved: #{reason})"
69
+ write(env, decided["change"], audit_input(request, user, text, "approval.approve"))
70
+ @approvals.set_state(env, id, "applied")
71
+ json(decided.merge("state" => "applied"))
72
+ end
73
+
74
+ def usage(request, name)
75
+ _, env = authorize(request, name, "viewer")
76
+ last_changed = @store.audit_log(env).filter_map { |e| [e["flag"], e["at"]] if e["flag"] }.to_h
77
+ json({ "flags" => Benchdog.stale_flags(@store.load(env), last_changed, days: @options.fetch(:stale_days, 30)) })
78
+ end
79
+
80
+ def cron(request)
81
+ secret = @options[:cron_secret]
82
+ unless secret && request.header("Authorization") == "Bearer #{secret}"
83
+ raise Problem.new(401, "UNAUTHENTICATED", "The cron secret is wrong or not set")
84
+ end
85
+
86
+ applied = @environments.to_h do |e|
87
+ keys = Benchdog.apply_due_schedules(@store, e[:name])
88
+ @feed.publish(e[:name]) if keys.any?
89
+ [e[:name], keys]
90
+ end
91
+ json({ "applied" => applied })
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Benchdog
4
+ # The routes that read and change flags and segments.
5
+ class AdminApi
6
+ private
7
+
8
+ def flag_set(request, name)
9
+ _, env = authorize(request, name, "viewer")
10
+ json(@store.load(env), 200, { "etag" => etag(env) })
11
+ end
12
+
13
+ def get_flag(request, name, key)
14
+ _, env = authorize(request, name, "viewer")
15
+ json(flag_in(env, key), 200, { "etag" => etag(env) })
16
+ end
17
+
18
+ def put_flag(request, name, key)
19
+ user, env = authorize(request, name, "editor")
20
+ reason = read_reason(request.body["reason"])
21
+ flag = request.body["flag"]
22
+ error = Validation.flag_error(flag)
23
+ raise invalid(error) if error
24
+ raise invalid("The body key \"#{flag['key']}\" is not the path key \"#{key}\"") unless flag["key"] == key
25
+
26
+ check_variations(flag)
27
+ check_prerequisites(flag, @store.load(env))
28
+ check_if_match(request, env)
29
+ change(request, user, env, { "kind" => "putFlag", "flag" => flag }, reason) do
30
+ json(flag, 200, { "etag" => etag(env) })
31
+ end
32
+ end
33
+
34
+ def delete_flag(request, name, key)
35
+ user, env = authorize(request, name, "editor")
36
+ reason = read_reason(request.query["reason"])
37
+ check_if_match(request, env)
38
+ flag_in(env, key)
39
+ change(request, user, env, { "kind" => "deleteFlag", "key" => key }, reason) { no_content }
40
+ end
41
+
42
+ def kill(request, name, key)
43
+ user = signed_in(request)
44
+ env = environment(name)
45
+ reason = read_reason(request.body["reason"])
46
+ targets = request.body["allEnvironments"] == true ? @environments.map { |e| e[:name] } : [env]
47
+ flag_in(env, key)
48
+ found = targets.filter_map do |target|
49
+ flag = @store.load(target)["flags"][key] or next
50
+ need(user, target, "editor")
51
+ [target, flag]
52
+ end
53
+ found.each do |target, flag|
54
+ write(target, { "kind" => "putFlag", "flag" => flag.merge("enabled" => false) },
55
+ audit_input(request, user, reason, "flag.kill"))
56
+ end
57
+ json(flag_in(env, key))
58
+ end
59
+
60
+ def promote(request, name, key)
61
+ user, env = authorize(request, name, "viewer")
62
+ reason = read_reason(request.body["reason"])
63
+ to = request.body["to"]
64
+ raise invalid("\"to\" must be an environment") unless to.is_a?(String) && @known.key?(to)
65
+
66
+ need(user, to, "editor")
67
+ flag = flag_in(env, key)
68
+ change(request, user, to, { "kind" => "putFlag", "flag" => flag }, reason, "flag.promote") { json(flag) }
69
+ end
70
+
71
+ def put_segment(request, name, segment)
72
+ user, env = authorize(request, name, "editor")
73
+ reason = read_reason(request.body["reason"])
74
+ expression = request.body["expression"]
75
+ unless request.body.key?("expression") && Validation.expression?(expression)
76
+ raise invalid("The expression is not valid")
77
+ end
78
+
79
+ next_change = { "kind" => "putSegment", "name" => segment, "expression" => expression }
80
+ change(request, user, env, next_change, reason) { json({ "name" => segment, "expression" => expression }) }
81
+ end
82
+
83
+ def delete_segment(request, name, segment)
84
+ user, env = authorize(request, name, "editor")
85
+ reason = read_reason(request.query["reason"])
86
+ users = segment_users(@store.load(env), segment)
87
+ raise Problem.new(409, "CONFLICT", "The segment is in use: #{users.join(', ')}") if users.any?
88
+
89
+ change(request, user, env, { "kind" => "deleteSegment", "name" => segment }, reason) { no_content }
90
+ end
91
+
92
+ # Each variation key that a flag names must exist (SPEC section 5.3).
93
+ def check_variations(flag)
94
+ keys = variation_keys(flag)
95
+ named = [flag.fetch("offVariation", "off"), flag.fetch("onVariation", "on"), *serve_keys(flag["fallthrough"]),
96
+ *flag["rules"].to_a.flat_map { |r| serve_keys(r["serve"]) },
97
+ *flag["schedule"].to_a.flat_map { |s| serve_keys(s.dig("set", "fallthrough")) }]
98
+ missing = named.find { |k| !keys.include?(k) }
99
+ raise invalid("The flag names the variation \"#{missing}\", which it does not have") if missing
100
+ end
101
+
102
+ # Each prerequisite must name a flag of the set, and a variation of that flag.
103
+ def check_prerequisites(flag, set)
104
+ flag["prerequisites"].to_a.each do |pre|
105
+ other = set["flags"][pre["flag"]] or raise invalid("The prerequisite flag \"#{pre['flag']}\" does not exist")
106
+ next if variation_keys(other).include?(pre["variation"])
107
+
108
+ raise invalid("The flag \"#{pre['flag']}\" has no variation \"#{pre['variation']}\"")
109
+ end
110
+ end
111
+
112
+ def variation_keys(flag) = (flag["variations"] || BOOLEAN_VARIATIONS).map { |v| v["key"] }
113
+
114
+ def serve_keys(serve)
115
+ return [] unless serve
116
+
117
+ serve.key?("variation") ? [serve["variation"]] : serve["rollout"].map { |r| r["variation"] }
118
+ end
119
+
120
+ # Does the expression call Segment with this name?
121
+ def uses_segment?(expression, name)
122
+ return false unless expression.is_a?(Hash)
123
+
124
+ expression.any? do |fn, args|
125
+ list = args.is_a?(Array) ? args : [args]
126
+ (fn == "Segment" && list[0] == name) || list.any? { |arg| uses_segment?(arg, name) }
127
+ end
128
+ end
129
+
130
+ def segment_users(set, name)
131
+ flags = set["flags"].values.select do |flag|
132
+ [flag.dig("gates", "expression"), *flag["rules"].to_a.map { |r| r["expression"] },
133
+ *flag["schedule"].to_a.map { |s| s.dig("set", "gates", "expression") }].any? { |e| uses_segment?(e, name) }
134
+ end
135
+ segments = set["segments"].to_h.select { |other, e| other != name && uses_segment?(e, name) }
136
+ flags.map { |f| "flag \"#{f['key']}\"" } + segments.keys.map { |s| "segment \"#{s}\"" }
137
+ end
138
+ end
139
+ end
@@ -0,0 +1,159 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Benchdog
4
+ # The routes that read the user, the environments, the audience and the client payload.
5
+ class AdminApi
6
+ # The text of GET /flags/:key/check for each step that can decide an evaluation.
7
+ CHECK_REASONS = {
8
+ "disabled" => "The flag is off",
9
+ "prerequisite" => "A prerequisite flag does not have the necessary variation",
10
+ "boolean" => "The flag is on for each actor",
11
+ "actor" => "The actor is in the actor list",
12
+ "group" => "The actor is in a group of the flag",
13
+ "expression" => "The actor matches the expression, with no attributes",
14
+ "rule" => "A rule matches",
15
+ "percentageOfActors" => "The actor is in the percentage of actors",
16
+ "percentageOfTime" => "The percentage of time gate is on for this request",
17
+ "fallthrough" => "No gate matches"
18
+ }.freeze
19
+
20
+ # A Rack body for GET /stream: a comment at the start, one event for each change, and a
21
+ # keep-alive comment when nothing happens. The server calls `close` when the client goes.
22
+ class EventStream
23
+ def initialize(feed, env, keep_alive)
24
+ @queue = Thread::Queue.new
25
+ event = "event: change\ndata: #{JSON.generate('environment' => env)}\n\n"
26
+ # Subscribe now, so a write after the response starts is not lost.
27
+ @unsubscribe = feed.subscribe(env) { @queue << event }
28
+ @keep_alive = keep_alive
29
+ end
30
+
31
+ def each
32
+ yield ": connected\n\n"
33
+ loop { yield @queue.pop(timeout: @keep_alive) || ": keep-alive\n\n" }
34
+ end
35
+
36
+ def close = @unsubscribe.call
37
+ end
38
+
39
+ private
40
+
41
+ def groups = @options[:groups].to_h
42
+
43
+ def capabilities(request)
44
+ signed_in(request)
45
+ json({ "backend" => @options.fetch(:backend, "benchdog"), "capabilities" => @store.capabilities,
46
+ "audience" => true })
47
+ end
48
+
49
+ def me(request)
50
+ user = signed_in(request)
51
+ roles = @environments.to_h { |e| [e[:name], role(user, e[:name])] }.compact
52
+ json({ "user" => user, "roles" => roles })
53
+ end
54
+
55
+ def references(request)
56
+ any_role(signed_in(request))
57
+ refs = @options[:references] or raise not_found("Code references are not configured")
58
+ json(refs.respond_to?(:call) ? refs.call : refs)
59
+ end
60
+
61
+ def environments(request)
62
+ signed_in(request)
63
+ json({ "environments" => @environments.map do |e|
64
+ { "name" => e[:name], "protected" => e.fetch(:protected, false), "promotesTo" => e[:promotes_to] }
65
+ end })
66
+ end
67
+
68
+ def client(request)
69
+ user = @options.fetch(:authenticate).call(request.env)&.transform_keys(&:to_s)
70
+ env = environment(request.query.fetch("env", @environments.first[:name]))
71
+ actor_for = @options[:actor_for]
72
+ actor = actor_for ? actor_for.call(request.env, user) : user && { "id" => user["id"] }
73
+ json(Benchdog.client_payload(@store.load(env), actor ? { "actor" => actor } : {}, groups: groups))
74
+ end
75
+
76
+ def audience(request)
77
+ user = signed_in(request)
78
+ env = query_environment(request)
79
+ need(user, env, "viewer")
80
+ options = @options[:audience].to_h
81
+ descriptions = options[:groups].to_a.to_h { |g| g.transform_keys(&:to_s).values_at("key", "description") }
82
+ flags = flags_by_group(env)
83
+ keys = (descriptions.keys + groups.keys + flags.keys).uniq.sort
84
+ lookup = !options[:lookup_actors].nil?
85
+ json({
86
+ "groups" => keys.map { |k| audience_group(k, descriptions[k], flags) },
87
+ "actorTypes" => options[:actor_types].to_a.map do |t|
88
+ t.transform_keys(&:to_s).merge("lookup" => lookup)
89
+ end,
90
+ "actorLookup" => lookup
91
+ })
92
+ end
93
+
94
+ def flags_by_group(env)
95
+ pairs = @store.load(env)["flags"].values.flat_map do |flag|
96
+ flag.dig("gates", "groups").to_a.uniq.map { |key| [key, flag["key"]] }
97
+ end
98
+ pairs.group_by(&:first).transform_values { |list| list.map(&:last) }
99
+ end
100
+
101
+ def audience_group(key, description, flags)
102
+ { "key" => key, "description" => description, "registered" => groups.key?(key),
103
+ "flags" => flags.fetch(key, []).sort }.compact
104
+ end
105
+
106
+ def actors(request)
107
+ user = signed_in(request)
108
+ any_role(user)
109
+ q = request.query
110
+ raise invalid("\"q\" or \"ids\" is required") unless q.key?("q") || q.key?("ids")
111
+
112
+ query = actor_query(q)
113
+ lookup = @options[:audience].to_h[:lookup_actors]
114
+ found = lookup&.call(query, user)
115
+ json({ "actors" => found.to_a.first(query[:limit]) })
116
+ end
117
+
118
+ def actor_query(params)
119
+ ids = params["ids"]&.split(",")&.reject(&:empty?)
120
+ ids = ids&.first(50)
121
+ asked = Float(params["limit"].to_s, exception: false)
122
+ # With "ids", the default is one actor for each id.
123
+ wanted = asked&.finite? ? asked.truncate : (ids&.size || 10)
124
+ { ids: ids, q: ids ? nil : params["q"], type: params["type"], limit: wanted.clamp(1, 50) }.compact
125
+ end
126
+
127
+ def check(request, key)
128
+ user = signed_in(request)
129
+ env = query_environment(request)
130
+ need(user, env, "viewer")
131
+ id = request.query["actor"]
132
+ raise invalid("\"actor\" is required") if id.nil? || id.empty?
133
+
134
+ set = @store.load(env)
135
+ flag = set["flags"][key] or raise not_found("No flag \"#{key}\" in #{env}")
136
+ # The actor has an id only, so an expression or a group that reads an attribute sees none.
137
+ actor = { "id" => id }
138
+ result = Benchdog.evaluate(set, key, { "actor" => actor }, nil, groups: groups)
139
+ json({ "enabled" => !result.variation.nil? && result.variation != flag.fetch("offVariation", "off"),
140
+ "reason" => check_reason(result, flag, actor) })
141
+ end
142
+
143
+ def check_reason(result, flag, actor)
144
+ group = flag.dig("gates", "groups").to_a.find { |name| groups[name]&.call(actor) == true }
145
+ case result.gate
146
+ when nil then "The flag is not valid"
147
+ when "group" then group ? "The actor is in the group \"#{group}\"" : CHECK_REASONS["group"]
148
+ when "rule" then result.rule_id ? "The rule \"#{result.rule_id}\" matches" : CHECK_REASONS["rule"]
149
+ else CHECK_REASONS.fetch(result.gate)
150
+ end
151
+ end
152
+
153
+ def stream(request)
154
+ env = environment(request.query.fetch("env", @environments.first[:name]))
155
+ body = EventStream.new(@feed, env, @options.fetch(:keep_alive, 25.0))
156
+ [200, { "content-type" => "text/event-stream", "cache-control" => "no-cache" }, body]
157
+ end
158
+ end
159
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "uri"
5
+
6
+ module Benchdog
7
+ class AdminApi
8
+ # The parts of a Rack request that the API reads. The API needs no Rack gem.
9
+ class Request
10
+ attr_reader :env
11
+
12
+ def initialize(env)
13
+ @env = env
14
+ end
15
+
16
+ def method = @env["REQUEST_METHOD"]
17
+
18
+ # The path below the mount point.
19
+ def path = @env["PATH_INFO"].to_s.then { |p| p.empty? ? "/" : p }
20
+
21
+ def header(name) = @env["HTTP_#{name.upcase.tr('-', '_')}"]
22
+
23
+ # The query parameters. For a repeated name, the first value counts.
24
+ def query
25
+ @query ||= URI.decode_www_form(@env["QUERY_STRING"].to_s).reverse.to_h
26
+ end
27
+
28
+ # The body as a JSON object.
29
+ def body
30
+ @body ||= begin
31
+ parsed = JSON.parse(@env["rack.input"]&.read.to_s)
32
+ raise JSON::ParserError unless parsed.is_a?(Hash)
33
+
34
+ parsed
35
+ rescue JSON::ParserError
36
+ raise Problem.new(422, "INVALID", "The body must be a JSON object")
37
+ end
38
+ end
39
+ end
40
+ end
41
+ end