standard_flags 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/CHANGELOG.md +84 -0
- data/LICENSE +21 -0
- data/README.md +548 -0
- data/Rakefile +6 -0
- data/lib/generators/standard_flags/install/install_generator.rb +40 -0
- data/lib/generators/standard_flags/install/templates/flags.rb.tt +58 -0
- data/lib/generators/standard_flags/install/templates/initializer.rb.tt +43 -0
- data/lib/standard_flags/bucket.rb +61 -0
- data/lib/standard_flags/config.rb +77 -0
- data/lib/standard_flags/context.rb +73 -0
- data/lib/standard_flags/controller.rb +107 -0
- data/lib/standard_flags/definition.rb +285 -0
- data/lib/standard_flags/diagnostics.rb +101 -0
- data/lib/standard_flags/engine.rb +28 -0
- data/lib/standard_flags/env_pin.rb +50 -0
- data/lib/standard_flags/errors.rb +35 -0
- data/lib/standard_flags/evaluation.rb +41 -0
- data/lib/standard_flags/evaluator.rb +58 -0
- data/lib/standard_flags/health_check.rb +50 -0
- data/lib/standard_flags/job.rb +75 -0
- data/lib/standard_flags/memo.rb +57 -0
- data/lib/standard_flags/mode.rb +78 -0
- data/lib/standard_flags/notifiers/logger.rb +49 -0
- data/lib/standard_flags/notifiers/metrics.rb +29 -0
- data/lib/standard_flags/notifiers/sentry.rb +27 -0
- data/lib/standard_flags/parser.rb +36 -0
- data/lib/standard_flags/payload.rb +29 -0
- data/lib/standard_flags/reader.rb +69 -0
- data/lib/standard_flags/reason.rb +34 -0
- data/lib/standard_flags/registry.rb +168 -0
- data/lib/standard_flags/reporting.rb +56 -0
- data/lib/standard_flags/resolvers.rb +103 -0
- data/lib/standard_flags/rspec.rb +58 -0
- data/lib/standard_flags/sensor.rb +77 -0
- data/lib/standard_flags/snapshot.rb +34 -0
- data/lib/standard_flags/subscribers.rb +45 -0
- data/lib/standard_flags/testing.rb +85 -0
- data/lib/standard_flags/tooling.rb +224 -0
- data/lib/standard_flags/version.rb +3 -0
- data/lib/standard_flags.rb +140 -0
- data/lib/tasks/standard_flags.rake +37 -0
- metadata +156 -0
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
require "rails/generators"
|
|
2
|
+
|
|
3
|
+
module StandardFlags
|
|
4
|
+
module Generators
|
|
5
|
+
# `rails g standard_flags:install` writes:
|
|
6
|
+
#
|
|
7
|
+
# * config/initializers/standard_flags.rb — runtime settings, commented.
|
|
8
|
+
# * config/flags.rb — the registry, with one commented example per kind.
|
|
9
|
+
#
|
|
10
|
+
# Idempotent: existing files are skipped. Pass --force to overwrite.
|
|
11
|
+
class InstallGenerator < Rails::Generators::Base
|
|
12
|
+
source_root File.expand_path("templates", __dir__)
|
|
13
|
+
|
|
14
|
+
desc <<~DESC
|
|
15
|
+
Installs StandardFlags: writes config/initializers/standard_flags.rb
|
|
16
|
+
and config/flags.rb with commented examples. Existing files are
|
|
17
|
+
skipped; pass --force to overwrite.
|
|
18
|
+
DESC
|
|
19
|
+
|
|
20
|
+
def create_initializer_file
|
|
21
|
+
write_template("initializer.rb.tt", "config/initializers/standard_flags.rb")
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def create_registry_file
|
|
25
|
+
write_template("flags.rb.tt", "config/flags.rb")
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
private
|
|
29
|
+
|
|
30
|
+
def write_template(source, path)
|
|
31
|
+
if File.exist?(File.join(destination_root, path)) && !options[:force]
|
|
32
|
+
say_status("skip", "#{path} already present, skipping (use --force to overwrite)", :yellow)
|
|
33
|
+
return
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
template source, path
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
end
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# The flag registry. Every flag is declared once, here, with an owner.
|
|
2
|
+
# Keys are immutable: never rename or reuse one. Remove a flag by replacing
|
|
3
|
+
# its declaration with a tombstone.
|
|
4
|
+
#
|
|
5
|
+
# Each flag can be pinned with STANDARD_FLAGS_<KEY> (on/off, true/false, 1/0,
|
|
6
|
+
# yes/no, or a declared mode value or variant). A pin beats the code default.
|
|
7
|
+
|
|
8
|
+
StandardFlags.define do
|
|
9
|
+
# The logical environment name. Pass your own if staging boots with
|
|
10
|
+
# RAILS_ENV=production.
|
|
11
|
+
# env_resolver -> { ENV.fetch("APP_ENVIRONMENT", Rails.env) }
|
|
12
|
+
|
|
13
|
+
# Units a flag can target. Carried in the context today; used for targeting
|
|
14
|
+
# once runtime rules arrive.
|
|
15
|
+
# unit :account, from: ->(ctx) { ctx.account }
|
|
16
|
+
|
|
17
|
+
# A release flag: temporary, so it needs remove_by: and the final: value it
|
|
18
|
+
# settles on.
|
|
19
|
+
# flag :new_checkout,
|
|
20
|
+
# owner: "payments",
|
|
21
|
+
# description: "Rebuilt checkout flow",
|
|
22
|
+
# remove_by: "2027-03-01",
|
|
23
|
+
# final: true,
|
|
24
|
+
# default: { staging: true, production: false },
|
|
25
|
+
# expose: { web: :newCheckout }
|
|
26
|
+
|
|
27
|
+
# A kill switch: on by default, fails open, permanent. `env:` keeps reading
|
|
28
|
+
# an existing variable; `inverted: true` because the legacy name is a
|
|
29
|
+
# *_DISABLED variable.
|
|
30
|
+
# kill_switch :ai_assistant,
|
|
31
|
+
# owner: "assistant",
|
|
32
|
+
# env: "ACME_LEGACY_DISABLED",
|
|
33
|
+
# inverted: true,
|
|
34
|
+
# expose: { web: :assistant, mobile: :assistant }
|
|
35
|
+
|
|
36
|
+
# A mode. Presets: :sensor (off/sensor/on), :cutover (off/allowlist/all),
|
|
37
|
+
# :shadow (off/shadow/enforce); or values: %i[...].
|
|
38
|
+
# mode :strict_gates, owner: "platform", preset: :sensor
|
|
39
|
+
|
|
40
|
+
# An experiment. Resolves to its first variant (control) unless pinned.
|
|
41
|
+
# experiment :home_hero, owner: "growth", variants: %w[control savings privacy]
|
|
42
|
+
|
|
43
|
+
# A compatibility shim: on until removed.
|
|
44
|
+
# compat :legacy_form_auth, owner: "identity"
|
|
45
|
+
|
|
46
|
+
# A flag that must never be on in an environment: forced off there, and a
|
|
47
|
+
# pin that tries reports once per process.
|
|
48
|
+
# flag :demo_data, owner: "platform", remove_by: "2027-06-01", final: false,
|
|
49
|
+
# forbidden_in: :production
|
|
50
|
+
|
|
51
|
+
# A permanent flag: a standing switch, such as an environment permission,
|
|
52
|
+
# with no remove_by: or final:. Never stale; may default off or on.
|
|
53
|
+
# flag :demo_pages, owner: "platform", permanent: true,
|
|
54
|
+
# default: { development: true, staging: true }, forbidden_in: :production
|
|
55
|
+
|
|
56
|
+
# A removed key that can never be declared again.
|
|
57
|
+
# tombstone :manual_entry, removed: "2026-12-01"
|
|
58
|
+
end
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# StandardFlags runtime settings. Flags themselves live in config/flags.rb.
|
|
2
|
+
#
|
|
3
|
+
# StandardFlags.configure do |config|
|
|
4
|
+
# # Unknown keys and kind mismatches raise when strict. Defaults to true
|
|
5
|
+
# # everywhere except a production Rails process, where reads fail safe.
|
|
6
|
+
# # config.strict = true
|
|
7
|
+
#
|
|
8
|
+
# # Fraction of evaluations that emit evaluate.standard_flags (0.0..1.0).
|
|
9
|
+
# # config.evaluate_sample_rate = 0.0
|
|
10
|
+
#
|
|
11
|
+
# # Rejected and forbidden pins already go to Rails.error. Turn this on only
|
|
12
|
+
# # if Rails.error isn't wired to Sentry, or each warning arrives twice.
|
|
13
|
+
# # config.sentry_enabled = false
|
|
14
|
+
#
|
|
15
|
+
# # Sentry::Metrics counters per event, when sentry-ruby is loaded.
|
|
16
|
+
# # config.metrics_enabled = true
|
|
17
|
+
# # config.metric_prefix = "standard_flags"
|
|
18
|
+
#
|
|
19
|
+
# # Where flags:refs looks for flag reads.
|
|
20
|
+
# # config.refs_paths = %w[app lib config]
|
|
21
|
+
#
|
|
22
|
+
# # Outputs of standard_flags:manifest and standard_flags:typescript.
|
|
23
|
+
# # config.manifest_path = "config/flags.manifest.json"
|
|
24
|
+
# # config.typescript_path = "app/javascript/types/standard_flags.d.ts"
|
|
25
|
+
#
|
|
26
|
+
# # Whose wire name requires_flag reports in meta.feature.
|
|
27
|
+
# # config.default_audience = :web
|
|
28
|
+
#
|
|
29
|
+
# # Replace the requires_flag response (denial has key, error, status,
|
|
30
|
+
# # feature and body).
|
|
31
|
+
# # config.controller_responder = ->(controller, denial) do
|
|
32
|
+
# # controller.render json: denial.body, status: denial.status
|
|
33
|
+
# # end
|
|
34
|
+
#
|
|
35
|
+
# # Your own subscriber for every *.standard_flags event.
|
|
36
|
+
# # config.add_notifier(->(name, payload) { MyMetrics.increment(name, tags: { flag: payload[:key] }) })
|
|
37
|
+
# end
|
|
38
|
+
#
|
|
39
|
+
# Opt-in health check (needs standard_health):
|
|
40
|
+
#
|
|
41
|
+
# StandardHealth.configure do |c|
|
|
42
|
+
# c.register_check :flags, StandardFlags::HealthCheck
|
|
43
|
+
# end
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
require "digest"
|
|
2
|
+
|
|
3
|
+
module StandardFlags
|
|
4
|
+
# Deterministic bucketing into 10,000 basis points. These functions are a
|
|
5
|
+
# permanent contract: changing them would move every unit to a new bucket.
|
|
6
|
+
# A new algorithm gets a new version; old flags keep theirs. The shared
|
|
7
|
+
# conformance fixtures pin test vectors for every version.
|
|
8
|
+
#
|
|
9
|
+
# Not yet used by evaluation; runtime percentage rules build on it.
|
|
10
|
+
module Bucket
|
|
11
|
+
BUCKETS = 10_000
|
|
12
|
+
DECISIONS = %w[rollout variant].freeze
|
|
13
|
+
COLUMN_FORMAT = /\A[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)?\z/
|
|
14
|
+
|
|
15
|
+
module_function
|
|
16
|
+
|
|
17
|
+
# Version 1: SHA-256 of "salt:unit_key", first 15 hex digits, mod 10,000.
|
|
18
|
+
def v1(salt, unit_key)
|
|
19
|
+
return nil if blank?(unit_key)
|
|
20
|
+
|
|
21
|
+
bucket("#{salt}:#{unit_key}")
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# Version 2, the default for new flags. The rollout check and the variant
|
|
25
|
+
# choice hash different inputs, and the delimiters are explicit so two
|
|
26
|
+
# different (salt, unit) pairs can never produce the same input.
|
|
27
|
+
def v2(decision, salt, unit_key)
|
|
28
|
+
decision = check_decision!(decision)
|
|
29
|
+
return nil if blank?(unit_key)
|
|
30
|
+
|
|
31
|
+
bucket("v2|#{decision}|#{salt}|#{unit_key}")
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# The Postgres twin of `v2`, so counting eligible rows and serving agree.
|
|
35
|
+
# Bind the salt with `sanitize_sql([sql, salt: salt])`. A NULL or blank
|
|
36
|
+
# column yields NULL, matching `v2`'s nil, never a random bucket.
|
|
37
|
+
def sql_v2(column:, decision: "rollout")
|
|
38
|
+
decision = check_decision!(decision)
|
|
39
|
+
raise ArgumentError, "column #{column.inspect} is not a plain identifier" unless column.to_s.match?(COLUMN_FORMAT)
|
|
40
|
+
|
|
41
|
+
unit = "(CASE WHEN btrim(#{column}::text) = '' THEN NULL ELSE #{column}::text END)"
|
|
42
|
+
"('x' || substr(encode(sha256(convert_to('v2|#{decision}|' || :salt || '|' || #{unit}, 'UTF8')), " \
|
|
43
|
+
"'hex'), 1, 15))::bit(60)::bigint % #{BUCKETS}"
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def bucket(input)
|
|
47
|
+
Digest::SHA256.hexdigest(input)[0, 15].to_i(16) % BUCKETS
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def check_decision!(decision)
|
|
51
|
+
decision = decision.to_s
|
|
52
|
+
raise ArgumentError, "decision must be one of #{DECISIONS.inspect}" unless DECISIONS.include?(decision)
|
|
53
|
+
|
|
54
|
+
decision
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def blank?(unit_key)
|
|
58
|
+
unit_key.nil? || unit_key.to_s.strip.empty?
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
end
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
module StandardFlags
|
|
2
|
+
# Runtime settings, set from `config/initializers/standard_flags.rb`:
|
|
3
|
+
#
|
|
4
|
+
# StandardFlags.configure do |config|
|
|
5
|
+
# config.evaluate_sample_rate = 0.01
|
|
6
|
+
# end
|
|
7
|
+
#
|
|
8
|
+
# Flags themselves are declared in config/flags.rb with StandardFlags.define.
|
|
9
|
+
class Config
|
|
10
|
+
# Fraction (0.0..1.0) of evaluations that emit `evaluate.standard_flags`.
|
|
11
|
+
attr_accessor :evaluate_sample_rate
|
|
12
|
+
# Logger for the Logger subscriber; defaults to Rails.logger.
|
|
13
|
+
attr_accessor :logger
|
|
14
|
+
# Off by default: Rails.error already carries rejected and forbidden pins
|
|
15
|
+
# to an error tracker wired to it. Turn on only when it isn't, or you get
|
|
16
|
+
# each warning twice.
|
|
17
|
+
attr_accessor :sentry_enabled
|
|
18
|
+
# Sentry::Metrics counters, when sentry-ruby is loaded.
|
|
19
|
+
attr_accessor :metrics_enabled
|
|
20
|
+
attr_accessor :metric_prefix
|
|
21
|
+
# The registry file loaded on boot and on every code reload.
|
|
22
|
+
attr_accessor :registry_path
|
|
23
|
+
# Where `flags:refs` looks for flag reads.
|
|
24
|
+
attr_accessor :refs_paths
|
|
25
|
+
attr_accessor :refs_extensions
|
|
26
|
+
# Outputs of `standard_flags:manifest` and `standard_flags:typescript`.
|
|
27
|
+
attr_accessor :manifest_path
|
|
28
|
+
attr_accessor :typescript_path
|
|
29
|
+
# `call(controller, denial)` replaces the default `requires_flag` response.
|
|
30
|
+
attr_accessor :controller_responder
|
|
31
|
+
# Whose wire name `requires_flag` reports in `meta.feature`.
|
|
32
|
+
attr_accessor :default_audience
|
|
33
|
+
|
|
34
|
+
attr_writer :strict, :env_source
|
|
35
|
+
attr_reader :extra_notifiers
|
|
36
|
+
|
|
37
|
+
def initialize
|
|
38
|
+
@evaluate_sample_rate = 0.0
|
|
39
|
+
@logger = nil
|
|
40
|
+
@sentry_enabled = false
|
|
41
|
+
@metrics_enabled = true
|
|
42
|
+
@metric_prefix = "standard_flags"
|
|
43
|
+
@registry_path = "config/flags.rb"
|
|
44
|
+
@refs_paths = %w[app lib config]
|
|
45
|
+
@refs_extensions = %w[rb erb rake haml slim jbuilder]
|
|
46
|
+
@manifest_path = "config/flags.manifest.json"
|
|
47
|
+
@typescript_path = "app/javascript/types/standard_flags.d.ts"
|
|
48
|
+
@controller_responder = nil
|
|
49
|
+
@default_audience = :web
|
|
50
|
+
@strict = nil
|
|
51
|
+
@env_source = nil
|
|
52
|
+
@extra_notifiers = []
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# Unknown keys and kind mismatches raise when strict. Defaults to true
|
|
56
|
+
# everywhere except a production Rails process.
|
|
57
|
+
def strict?
|
|
58
|
+
return @strict unless @strict.nil?
|
|
59
|
+
|
|
60
|
+
!(defined?(::Rails) && ::Rails.respond_to?(:env) && ::Rails.env.production?)
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# Where ENV pins are read from. Anything that responds to `[]`.
|
|
64
|
+
def env_source
|
|
65
|
+
@env_source || ENV
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
# Adds a subscriber that responds to `call(event_name, payload)` for every
|
|
69
|
+
# `*.standard_flags` event.
|
|
70
|
+
def add_notifier(notifier)
|
|
71
|
+
raise ArgumentError, "notifier must respond to call(event_name, payload)" unless notifier.respond_to?(:call)
|
|
72
|
+
|
|
73
|
+
@extra_notifiers << notifier unless @extra_notifiers.include?(notifier)
|
|
74
|
+
notifier
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
end
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
module StandardFlags
|
|
2
|
+
# Who and what a flag is being evaluated for: one actor per unit, an
|
|
3
|
+
# optional environment override, and the calling client (platform, version,
|
|
4
|
+
# build). Runtime rules and client targeting read these in later phases;
|
|
5
|
+
# today they only feed the per-unit-of-work memo key.
|
|
6
|
+
#
|
|
7
|
+
# StandardFlags.on?(:new_checkout, for: account) # a single target
|
|
8
|
+
# StandardFlags.on?(:new_checkout, for: { account: account, organization: org })
|
|
9
|
+
# StandardFlags.on?(:new_checkout, for: StandardFlags::Context.new(env: "staging"))
|
|
10
|
+
#
|
|
11
|
+
# The memo key covers env, target, actors and client, so two clients in one
|
|
12
|
+
# unit of work never share an answer once rules target platform or version.
|
|
13
|
+
#
|
|
14
|
+
# A unit's `from:` lambda receives the context: actors passed by unit name
|
|
15
|
+
# read as methods (`ctx.account`), and anything else is asked of the single
|
|
16
|
+
# target (`ctx.organization` calls `target.organization`).
|
|
17
|
+
class Context
|
|
18
|
+
attr_reader :actors, :target, :env, :client, :cache_key
|
|
19
|
+
|
|
20
|
+
def self.wrap(value)
|
|
21
|
+
case value
|
|
22
|
+
when Context then value
|
|
23
|
+
when nil then empty
|
|
24
|
+
when Hash then new(actors: value)
|
|
25
|
+
else new(target: value)
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def self.empty
|
|
30
|
+
@empty ||= new
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def initialize(actors: {}, target: nil, env: nil, client: {})
|
|
34
|
+
@actors = actors.transform_keys(&:to_sym).freeze
|
|
35
|
+
@target = target
|
|
36
|
+
@env = env&.to_s
|
|
37
|
+
@client = client.transform_keys(&:to_sym).freeze
|
|
38
|
+
@cache_key = [
|
|
39
|
+
@env,
|
|
40
|
+
identity(@target),
|
|
41
|
+
@actors.sort.map { |unit, actor| [ unit, identity(actor) ] },
|
|
42
|
+
@client.sort
|
|
43
|
+
].freeze
|
|
44
|
+
freeze
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def actor(unit)
|
|
48
|
+
unit = unit.to_sym
|
|
49
|
+
return actors[unit] if actors.key?(unit)
|
|
50
|
+
|
|
51
|
+
target.public_send(unit) if target.respond_to?(unit)
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def respond_to_missing?(name, include_private = false)
|
|
55
|
+
actors.key?(name) || target.respond_to?(name) || super
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def method_missing(name, *args, &block)
|
|
59
|
+
return super unless args.empty? && block.nil? && respond_to_missing?(name)
|
|
60
|
+
|
|
61
|
+
actor(name)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
private
|
|
65
|
+
|
|
66
|
+
def identity(object)
|
|
67
|
+
case object
|
|
68
|
+
when nil, String, Symbol, Numeric, true, false then object
|
|
69
|
+
else [ object.class.name, object.respond_to?(:id) ? object.id : object.object_id ]
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
end
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
require "active_support/concern"
|
|
2
|
+
|
|
3
|
+
module StandardFlags
|
|
4
|
+
# Controller guards and the payload helper.
|
|
5
|
+
#
|
|
6
|
+
# class ApplicationController < ActionController::Base
|
|
7
|
+
# include StandardFlags::Controller
|
|
8
|
+
#
|
|
9
|
+
# inertia_share features: -> { standard_flags_payload(:web) }
|
|
10
|
+
#
|
|
11
|
+
# private
|
|
12
|
+
#
|
|
13
|
+
# def standard_flags_context = Current.account
|
|
14
|
+
# end
|
|
15
|
+
#
|
|
16
|
+
# class ReportsController < ApplicationController
|
|
17
|
+
# requires_flag :new_reports, except: :index
|
|
18
|
+
# requires_flag :legacy_export, error: :not_found # keep a 404 contract
|
|
19
|
+
# requires_flag :report_api, with: :render_api_error # keep this endpoint's own error shape
|
|
20
|
+
# end
|
|
21
|
+
#
|
|
22
|
+
# A JSON request that hits a disabled flag gets one JSON:API error:
|
|
23
|
+
#
|
|
24
|
+
# {"errors":[{"status":"403","code":"feature_disabled","meta":{"feature":"new_reports"}}]}
|
|
25
|
+
#
|
|
26
|
+
# `meta.feature` is the flag's wire name for `config.default_audience` when
|
|
27
|
+
# it has one, else the key. `error: :not_found` answers 404 with no meta,
|
|
28
|
+
# so it reveals nothing. Other formats get the bare status.
|
|
29
|
+
# `config.controller_responder` replaces the response entirely, and a
|
|
30
|
+
# guard's own `with:` (a callable or the name of a controller method)
|
|
31
|
+
# replaces it for that guard only.
|
|
32
|
+
module Controller
|
|
33
|
+
extend ActiveSupport::Concern
|
|
34
|
+
|
|
35
|
+
ERRORS = { feature_disabled: 403, not_found: 404 }.freeze
|
|
36
|
+
|
|
37
|
+
# What a guard hands the responder.
|
|
38
|
+
Denial = Data.define(:key, :error, :status, :feature) do
|
|
39
|
+
def body
|
|
40
|
+
error_object = { status: status.to_s, code: error.to_s }
|
|
41
|
+
error_object[:meta] = { feature: feature } if error == :feature_disabled
|
|
42
|
+
{ errors: [ error_object ] }
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
included do
|
|
47
|
+
helper_method :standard_flags_payload if respond_to?(:helper_method)
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
class_methods do
|
|
51
|
+
# `with:` answers a denial for this guard only, instead of
|
|
52
|
+
# `config.controller_responder` or the default response: a callable
|
|
53
|
+
# taking `(controller, denial)`, or a Symbol naming a controller method
|
|
54
|
+
# that takes `(denial)`. It must render or redirect to halt the action.
|
|
55
|
+
def requires_flag(key, only: nil, except: nil, error: :feature_disabled, status: nil, with: nil)
|
|
56
|
+
raise ArgumentError, "error: must be one of #{ERRORS.keys.inspect}" unless ERRORS.key?(error)
|
|
57
|
+
unless with.nil? || with.is_a?(Symbol) || with.respond_to?(:call)
|
|
58
|
+
raise ArgumentError, "with: must respond to call(controller, denial) or be a Symbol naming a controller method"
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
status ||= ERRORS.fetch(error)
|
|
62
|
+
before_action(**{ only: only, except: except }.compact) do
|
|
63
|
+
standard_flags_require!(key, error: error, status: status, responder: with)
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
# The payload for one audience, evaluated for this request's context.
|
|
69
|
+
def standard_flags_payload(audience)
|
|
70
|
+
StandardFlags.payload(audience, for: standard_flags_context)
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
private
|
|
74
|
+
|
|
75
|
+
# Override to say who flags are evaluated for in this controller.
|
|
76
|
+
def standard_flags_context
|
|
77
|
+
nil
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
def standard_flags_require!(key, error:, status:, responder: nil)
|
|
81
|
+
return if StandardFlags.reader(for: standard_flags_context).enabled?(key)
|
|
82
|
+
|
|
83
|
+
denial = Denial.new(key: key.to_sym, error: error, status: status, feature: standard_flags_feature_name(key))
|
|
84
|
+
responder ||= StandardFlags.config.controller_responder
|
|
85
|
+
case responder
|
|
86
|
+
when nil then standard_flags_render_denial(denial)
|
|
87
|
+
when Symbol then send(responder, denial)
|
|
88
|
+
else responder.call(self, denial)
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
def standard_flags_render_denial(denial)
|
|
93
|
+
if request.format.json? || request.content_mime_type&.json?
|
|
94
|
+
render json: denial.body, status: denial.status
|
|
95
|
+
else
|
|
96
|
+
head denial.status
|
|
97
|
+
end
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
def standard_flags_feature_name(key)
|
|
101
|
+
definition = StandardFlags.registry[key]
|
|
102
|
+
return key.to_s unless definition
|
|
103
|
+
|
|
104
|
+
definition.wire_name(StandardFlags.config.default_audience) || definition.expose.values.first || key.to_s
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
end
|