standard_flags 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.
Files changed (71) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +229 -0
  3. data/README.md +837 -33
  4. data/lib/generators/standard_flags/admin/admin_generator.rb +115 -0
  5. data/lib/generators/standard_flags/admin/templates/controller.rb.tt +103 -0
  6. data/lib/generators/standard_flags/admin/templates/index.tsx.tt +64 -0
  7. data/lib/generators/standard_flags/admin/templates/show.tsx.tt +275 -0
  8. data/lib/generators/standard_flags/install/install_generator.rb +16 -1
  9. data/lib/generators/standard_flags/install/templates/flags.rb.tt +3 -2
  10. data/lib/generators/standard_flags/install/templates/initializer.rb.tt +10 -0
  11. data/lib/generators/standard_flags/migrations/migrations_generator.rb +57 -0
  12. data/lib/generators/standard_flags/migrations/templates/create_standard_flags_tables.rb.tt +78 -0
  13. data/lib/standard_flags/actor.rb +50 -0
  14. data/lib/standard_flags/audit_trail.rb +56 -0
  15. data/lib/standard_flags/config.rb +78 -0
  16. data/lib/standard_flags/context.rb +5 -1
  17. data/lib/standard_flags/definition.rb +85 -13
  18. data/lib/standard_flags/diagnostics.rb +35 -3
  19. data/lib/standard_flags/engine.rb +10 -2
  20. data/lib/standard_flags/env_pin.rb +15 -4
  21. data/lib/standard_flags/errors.rb +4 -0
  22. data/lib/standard_flags/evaluation.rb +5 -4
  23. data/lib/standard_flags/evaluator.rb +14 -1
  24. data/lib/standard_flags/events.rb +49 -0
  25. data/lib/standard_flags/health_check.rb +12 -2
  26. data/lib/standard_flags/health_contribution.rb +65 -0
  27. data/lib/standard_flags/mcp/cohorts.rb +65 -0
  28. data/lib/standard_flags/mcp/flags.rb +143 -0
  29. data/lib/standard_flags/mcp/members.rb +154 -0
  30. data/lib/standard_flags/mcp/writes.rb +98 -0
  31. data/lib/standard_flags/mcp.rb +238 -0
  32. data/lib/standard_flags/memo.rb +15 -1
  33. data/lib/standard_flags/notifiers/logger.rb +14 -0
  34. data/lib/standard_flags/open_feature/provider.rb +232 -0
  35. data/lib/standard_flags/open_feature.rb +26 -0
  36. data/lib/standard_flags/operations/audit.rb +218 -0
  37. data/lib/standard_flags/operations/base.rb +290 -0
  38. data/lib/standard_flags/operations/cohorts.rb +80 -0
  39. data/lib/standard_flags/operations/failure.rb +16 -0
  40. data/lib/standard_flags/operations/members.rb +164 -0
  41. data/lib/standard_flags/operations/restore.rb +330 -0
  42. data/lib/standard_flags/operations/restore_target.rb +197 -0
  43. data/lib/standard_flags/operations/rules.rb +233 -0
  44. data/lib/standard_flags/operations/validation.rb +154 -0
  45. data/lib/standard_flags/operations.rb +43 -0
  46. data/lib/standard_flags/parser.rb +16 -0
  47. data/lib/standard_flags/purge_job.rb +14 -0
  48. data/lib/standard_flags/registry.rb +38 -5
  49. data/lib/standard_flags/reporting.rb +51 -7
  50. data/lib/standard_flags/resolvers.rb +14 -7
  51. data/lib/standard_flags/result.rb +43 -0
  52. data/lib/standard_flags/rspec.rb +67 -13
  53. data/lib/standard_flags/runtime/active_record_store.rb +428 -0
  54. data/lib/standard_flags/runtime/cache.rb +98 -0
  55. data/lib/standard_flags/runtime/evaluation_tracker.rb +93 -0
  56. data/lib/standard_flags/runtime/memory_store.rb +408 -0
  57. data/lib/standard_flags/runtime/models.rb +43 -0
  58. data/lib/standard_flags/runtime/resolver.rb +256 -0
  59. data/lib/standard_flags/runtime/rule_snapshot.rb +60 -0
  60. data/lib/standard_flags/runtime/store.rb +161 -0
  61. data/lib/standard_flags/runtime/values.rb +181 -0
  62. data/lib/standard_flags/runtime.rb +266 -0
  63. data/lib/standard_flags/sensor.rb +12 -5
  64. data/lib/standard_flags/subscribers.rb +6 -0
  65. data/lib/standard_flags/testing.rb +100 -1
  66. data/lib/standard_flags/tooling/changes.rb +196 -0
  67. data/lib/standard_flags/tooling.rb +232 -19
  68. data/lib/standard_flags/version.rb +1 -1
  69. data/lib/standard_flags.rb +33 -5
  70. data/lib/tasks/standard_flags.rake +45 -1
  71. metadata +41 -1
@@ -0,0 +1,57 @@
1
+ require "rails/generators"
2
+ require "rails/generators/active_record"
3
+
4
+ module StandardFlags
5
+ module Generators
6
+ # `rails g standard_flags:migrations` writes one migration creating the
7
+ # runtime-rule tables (rules, cohorts, memberships and the single-row
8
+ # state). Keys are UUIDs when the app generates UUID primary keys.
9
+ #
10
+ # Skipped when a migration with the same name already exists.
11
+ class MigrationsGenerator < Rails::Generators::Base
12
+ include ActiveRecord::Generators::Migration
13
+
14
+ MIGRATION_NAME = "create_standard_flags_tables".freeze
15
+
16
+ source_root File.expand_path("templates", __dir__)
17
+
18
+ desc <<~DESC
19
+ Writes the migration for StandardFlags runtime rules. Run
20
+ bin/rails db:migrate, then set config.runtime_rules = true.
21
+ DESC
22
+
23
+ def create_migration_file
24
+ if self.class.migration_exists?(File.join(destination_root, db_migrate_path), MIGRATION_NAME)
25
+ say_status("skip", "#{MIGRATION_NAME} already present, skipping", :yellow)
26
+ return
27
+ end
28
+
29
+ migration_template "#{MIGRATION_NAME}.rb.tt", File.join(db_migrate_path, "#{MIGRATION_NAME}.rb")
30
+ end
31
+
32
+ private
33
+
34
+ def migration_version
35
+ "[#{ActiveRecord::VERSION::MAJOR}.#{ActiveRecord::VERSION::MINOR}]"
36
+ end
37
+
38
+ def uuid?
39
+ primary_key_type.to_s == "uuid"
40
+ end
41
+
42
+ def primary_key_type
43
+ generators = ::Rails.application&.config&.generators
44
+ generators&.options&.dig(:active_record, :primary_key_type)
45
+ end
46
+
47
+ # `, id: :uuid` when the app generates UUID keys.
48
+ def table_options
49
+ uuid? ? ", id: :uuid" : ""
50
+ end
51
+
52
+ def foreign_key_type
53
+ uuid? ? ":uuid" : ":bigint"
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,78 @@
1
+ # Runtime rules for StandardFlags. All four tables are new, so every index and
2
+ # constraint is created inside create_table.
3
+ class CreateStandardFlagsTables < ActiveRecord::Migration<%= migration_version %>
4
+ def change
5
+ # One row per flag, created by the first operation on it and never deleted.
6
+ create_table :standard_flags_rules<%= table_options %> do |t|
7
+ t.string :key, null: false, index: { unique: true }
8
+ t.string :status, null: false, default: "draft"
9
+ t.integer :hash_version, null: false, default: 2
10
+ t.string :salt, null: false
11
+ t.integer :percentage_bps
12
+ t.string :rollout_value
13
+ t.jsonb :variant_weights, null: false, default: {}
14
+ t.string :fallthrough_value
15
+ t.string :stop_value
16
+ t.jsonb :conditions, null: false, default: {}
17
+ t.jsonb :cohorts, null: false, default: []
18
+ t.integer :member_count, null: false, default: 0
19
+ t.integer :lock_version, null: false, default: 0
20
+ t.datetime :full_since
21
+ t.datetime :last_evaluated_at
22
+ t.timestamps
23
+
24
+ t.check_constraint "status IN ('draft', 'running', 'paused', 'stopped')", name: "standard_flags_rules_status"
25
+ t.check_constraint "percentage_bps IS NULL OR (percentage_bps >= 0 AND percentage_bps <= 10000)",
26
+ name: "standard_flags_rules_percentage_bps"
27
+ end
28
+
29
+ # Named member lists that any number of flags can attach. One unit each.
30
+ create_table :standard_flags_cohorts<%= table_options %> do |t|
31
+ t.string :key, null: false, index: { unique: true }
32
+ t.string :name
33
+ t.text :description
34
+ t.string :unit, null: false
35
+ t.integer :member_count, null: false, default: 0
36
+ t.datetime :archived_at
37
+ t.timestamps
38
+ end
39
+
40
+ # A unit's membership of exactly one rule or one cohort, with the value it
41
+ # serves. Removed rows are kept (removed_at) so they can be restored.
42
+ create_table :standard_flags_memberships<%= table_options %> do |t|
43
+ t.references :rule, type: <%= foreign_key_type %>, index: false,
44
+ foreign_key: { to_table: :standard_flags_rules }
45
+ t.references :cohort, type: <%= foreign_key_type %>, index: false,
46
+ foreign_key: { to_table: :standard_flags_cohorts }
47
+ t.string :unit, null: false
48
+ t.string :unit_key, null: false
49
+ t.string :value, null: false
50
+ t.datetime :expires_at
51
+ t.datetime :removed_at
52
+ t.timestamps
53
+
54
+ t.check_constraint "(rule_id IS NULL) <> (cohort_id IS NULL)", name: "standard_flags_memberships_one_owner"
55
+ t.index %i[rule_id unit unit_key], unique: true, where: "removed_at IS NULL",
56
+ name: "index_standard_flags_memberships_live_rule"
57
+ t.index %i[cohort_id unit unit_key], unique: true, where: "removed_at IS NULL",
58
+ name: "index_standard_flags_memberships_live_cohort"
59
+ t.index %i[unit unit_key], where: "removed_at IS NULL",
60
+ name: "index_standard_flags_memberships_live_lookup"
61
+ end
62
+
63
+ # A single row. Every write sets revision to the next value of its own
64
+ # sequence (bigserial), and each process reloads its rules when it sees
65
+ # the revision change. Sequence values are never handed out twice, even
66
+ # when the write that took one rolls back, so a revision number never
67
+ # stands for two different sets of rules.
68
+ create_table :standard_flags_state<%= table_options %> do |t|
69
+ t.bigserial :revision, null: false
70
+ end
71
+
72
+ up_only do
73
+ state = Class.new(ActiveRecord::Base) { self.table_name = "standard_flags_state" }
74
+ state.reset_column_information
75
+ state.insert_all!([ { revision: 0 } ])
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,50 @@
1
+ module StandardFlags
2
+ # Who an operation runs as when no person does: a rake task, a scheduled
3
+ # plan, a guard. Pass it as `actor:`:
4
+ #
5
+ # StandardFlags::Operations::Pause.call(:new_checkout, actor: StandardFlags::Actor.system("rake"), reason: "incident")
6
+ #
7
+ # The default `config.authorize` allows system actors and nothing else.
8
+ class Actor
9
+ attr_reader :name
10
+
11
+ def self.system(name = "system")
12
+ new(name)
13
+ end
14
+
15
+ def initialize(name)
16
+ @name = name.to_s
17
+ raise ArgumentError, "a system actor needs a name" if @name.strip.empty?
18
+
19
+ freeze
20
+ end
21
+
22
+ def system?
23
+ true
24
+ end
25
+
26
+ def to_s
27
+ "system:#{name}"
28
+ end
29
+ alias_method :inspect, :to_s
30
+
31
+ def ==(other)
32
+ other.is_a?(Actor) && other.name == name
33
+ end
34
+ alias_method :eql?, :==
35
+
36
+ def hash
37
+ [ self.class, name ].hash
38
+ end
39
+
40
+ # How audit rows and notifications name an actor: `system:<name>`, or the
41
+ # record's class and id. Never anything else about the actor.
42
+ def self.label(actor)
43
+ case actor
44
+ when Actor then actor.to_s
45
+ when nil then nil
46
+ else actor.respond_to?(:id) && !actor.id.nil? ? "#{actor.class.name}:#{actor.id}" : actor.class.name
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,56 @@
1
+ require "json"
2
+
3
+ module StandardFlags
4
+ # Reads the write path's history back out of standard_audit's audit_logs
5
+ # table, through its query API (StandardAudit::AuditLog). Used by Restore
6
+ # (a rule's state at a past time) and the admin page (recent changes).
7
+ # Only usable when the host has loaded standard_audit.
8
+ class AuditTrail
9
+ # The audit rows that carry a rule's full after-state.
10
+ RULE_EVENTS = (Events::FLAG_EVENTS.values + Events::COHORT_EVENTS.values_at(:attached, :detached)).freeze
11
+
12
+ def self.available?
13
+ defined?(::StandardAudit::AuditLog) ? true : false
14
+ end
15
+
16
+ def initialize(log = ::StandardAudit::AuditLog)
17
+ @log = log
18
+ end
19
+
20
+ # `{ key Symbol => after-state Hash (String keys) }` for every rule with
21
+ # an audit row at or before `at`: the after-state of the row with the
22
+ # highest revision (lock_version), so rows that share a timestamp still
23
+ # order correctly.
24
+ def rule_states(at)
25
+ rows = @log.where(event_type: RULE_EVENTS).where(occurred_at: ..at).reverse_chronological.pluck(:metadata)
26
+ rows.each_with_object({}) do |metadata, states|
27
+ metadata = parse(metadata)
28
+ key = metadata["key"]
29
+ after = metadata["after"]
30
+ next unless key && after.is_a?(Hash)
31
+
32
+ current = states[key.to_sym]
33
+ states[key.to_sym] = after if current.nil? || after["lock_version"].to_i > current["lock_version"].to_i
34
+ end
35
+ end
36
+
37
+ # The newest `limit` rows about one flag, as the admin page shows them:
38
+ # event, time, actor label, reason and revision. Never a unit key (the
39
+ # rows hold none). Matches on the metadata's key, a Postgres JSON read.
40
+ def entries(key, limit: 20)
41
+ @log.where(event_type: Events.auditable).where("metadata->>'key' = ?", key.to_s)
42
+ .reverse_chronological.limit(limit).pluck(:event_type, :occurred_at, :metadata).map do |event, occurred_at, metadata|
43
+ metadata = parse(metadata)
44
+ { event: event, occurred_at: occurred_at&.utc&.iso8601, actor: metadata["actor_label"],
45
+ reason: metadata["reason"], revision: metadata["revision"] }
46
+ end
47
+ end
48
+
49
+ private
50
+
51
+ def parse(metadata)
52
+ metadata = JSON.parse(metadata) if metadata.is_a?(String)
53
+ metadata.is_a?(Hash) ? metadata.transform_keys(&:to_s) : {}
54
+ end
55
+ end
56
+ end
@@ -30,6 +30,51 @@ module StandardFlags
30
30
  attr_accessor :controller_responder
31
31
  # Whose wire name `requires_flag` reports in `meta.feature`.
32
32
  attr_accessor :default_audience
33
+ # Runtime rules (rules stored in the app's database, between the ENV pin
34
+ # and the code default). Off by default; when off, nothing touches a
35
+ # database and ActiveRecord is never loaded. Turn on only after running
36
+ # `bin/rails g standard_flags:migrations` and migrating.
37
+ attr_accessor :runtime_rules
38
+ # Seconds between checks of the stored revision. Each check is one query;
39
+ # rules reload only when the revision has moved.
40
+ attr_accessor :refresh_interval
41
+ # Where runtime rules are read from. nil means the ActiveRecord store;
42
+ # pass a StandardFlags::Runtime::MemoryStore (or any Store) to run
43
+ # without a database.
44
+ attr_accessor :runtime_store
45
+ # `call(error, context)` replaces Rails.error for every report the gem
46
+ # makes (rejected and forbidden pins, unknown flags, evaluation errors,
47
+ # invalid runtime rules, runtime store failures). nil uses Rails.error;
48
+ # a reporter that raises falls back to it.
49
+ attr_reader :error_reporter
50
+ # `call(segment_name, context)` answers whether the context belongs to an
51
+ # app-defined segment. nil skips segment conditions. Through the
52
+ # OpenFeature provider the context's actors are unit keys (strings), not
53
+ # records, so a resolver used there must handle both.
54
+ attr_accessor :segment_resolver
55
+
56
+ # The write path's policy hook: `call(actor, scope, key)` is truthy when
57
+ # `actor` may use `scope` ("flags:read", "flags:write" or "flags:ramp")
58
+ # on `key` (a flag key Symbol, or "cohort:<key>"). The default allows
59
+ # StandardFlags::Actor.system actors and nobody else.
60
+ attr_reader :authorize
61
+ # `call` returns the actor for an operation called without `actor:`.
62
+ # Defaults to `Current.user` when the app defines Current with a `user`.
63
+ attr_reader :actor_resolver
64
+ # Write-time limits (never checked on read): live members per rule or
65
+ # cohort, unit keys per operation, cohorts attached to one rule, and the
66
+ # size of a rule's conditions in bytes of JSON.
67
+ attr_accessor :max_members, :max_keys_per_operation, :max_cohorts_per_rule, :max_conditions_bytes
68
+ # Seconds a removed or expired membership is kept (so it can be
69
+ # restored) before `flags:purge` / StandardFlags::PurgeJob deletes it.
70
+ attr_accessor :membership_retention
71
+ # Whether each process records which flags it evaluated, writing
72
+ # standard_flags_rules.last_evaluated_at for `flags:stale`, and at most
73
+ # how often (seconds) it writes.
74
+ attr_accessor :track_evaluations, :evaluation_tracking_interval
75
+
76
+ DEFAULT_AUTHORIZE = ->(actor, _scope, _key) { actor.is_a?(Actor) && actor.system? }
77
+ DEFAULT_ACTOR_RESOLVER = -> { ::Current.user if defined?(::Current) && ::Current.respond_to?(:user) }
33
78
 
34
79
  attr_writer :strict, :env_source
35
80
  attr_reader :extra_notifiers
@@ -47,6 +92,20 @@ module StandardFlags
47
92
  @typescript_path = "app/javascript/types/standard_flags.d.ts"
48
93
  @controller_responder = nil
49
94
  @default_audience = :web
95
+ @runtime_rules = false
96
+ @refresh_interval = 5
97
+ @runtime_store = nil
98
+ @segment_resolver = nil
99
+ @error_reporter = nil
100
+ @authorize = DEFAULT_AUTHORIZE
101
+ @actor_resolver = DEFAULT_ACTOR_RESOLVER
102
+ @max_members = 10_000
103
+ @max_keys_per_operation = 1_000
104
+ @max_cohorts_per_rule = 20
105
+ @max_conditions_bytes = 64 * 1024
106
+ @membership_retention = 90 * 86_400
107
+ @track_evaluations = true
108
+ @evaluation_tracking_interval = 3_600
50
109
  @strict = nil
51
110
  @env_source = nil
52
111
  @extra_notifiers = []
@@ -65,8 +124,27 @@ module StandardFlags
65
124
  @env_source || ENV
66
125
  end
67
126
 
127
+ def error_reporter=(reporter)
128
+ raise ArgumentError, "error_reporter must respond to call(error, context)" unless reporter.nil? || reporter.respond_to?(:call)
129
+
130
+ @error_reporter = reporter
131
+ end
132
+
133
+ def authorize=(policy)
134
+ raise ArgumentError, "authorize must respond to call(actor, scope, key)" unless policy.respond_to?(:call)
135
+
136
+ @authorize = policy
137
+ end
138
+
139
+ def actor_resolver=(resolver)
140
+ raise ArgumentError, "actor_resolver must respond to call" unless resolver.nil? || resolver.respond_to?(:call)
141
+
142
+ @actor_resolver = resolver
143
+ end
144
+
68
145
  # Adds a subscriber that responds to `call(event_name, payload)` for every
69
146
  # `*.standard_flags` event.
147
+
70
148
  def add_notifier(notifier)
71
149
  raise ArgumentError, "notifier must respond to call(event_name, payload)" unless notifier.respond_to?(:call)
72
150
 
@@ -63,10 +63,14 @@ module StandardFlags
63
63
 
64
64
  private
65
65
 
66
+ # An unsaved record (nil id) falls back to object identity, so two of
67
+ # them never share a memoised answer.
66
68
  def identity(object)
67
69
  case object
68
70
  when nil, String, Symbol, Numeric, true, false then object
69
- else [ object.class.name, object.respond_to?(:id) ? object.id : object.object_id ]
71
+ else
72
+ id = object.id if object.respond_to?(:id)
73
+ [ object.class.name, id.nil? ? object.object_id : id ]
70
74
  end
71
75
  end
72
76
  end
@@ -16,21 +16,36 @@ module StandardFlags
16
16
  shadow: %i[off shadow enforce]
17
17
  }.freeze
18
18
 
19
- COMMON_ATTRIBUTES = %i[owner description default env inverted forbidden_in fail expose unit].freeze
19
+ COMMON_ATTRIBUTES = %i[owner description default env inverted legacy_parser legacy_true forbidden_in fail
20
+ expose unit].freeze
20
21
  ATTRIBUTES = {
21
- flag: COMMON_ATTRIBUTES + %i[remove_by final permanent],
22
+ flag: COMMON_ATTRIBUTES + %i[remove_by final permanent bucketing],
22
23
  kill_switch: COMMON_ATTRIBUTES,
23
- mode: COMMON_ATTRIBUTES + %i[preset values],
24
- experiment: COMMON_ATTRIBUTES + %i[variants],
24
+ mode: COMMON_ATTRIBUTES + %i[preset values remove_by final permanent bucketing],
25
+ experiment: COMMON_ATTRIBUTES + %i[variants bucketing],
25
26
  compat: COMMON_ATTRIBUTES + %i[remove_by]
26
27
  }.freeze
27
28
 
28
29
  KEY_FORMAT = /\A[a-z][a-z0-9_]*\z/
29
30
  ENV_VAR_FORMAT = /\A[A-Z][A-Z0-9_]*\z/
30
31
  WIRE_FORMAT = /\A[A-Za-z][A-Za-z0-9_]*\z/
32
+ HASH_VERSIONS = [ 1, 2 ].freeze
33
+
34
+ # How legacy `env:` values are read. :strict is the one strict parser;
35
+ # :exact reproduces a hand-written `ENV["X"] == "on"` reader. Neither
36
+ # applies to the canonical STANDARD_FLAGS_<KEY> pin, which is always
37
+ # strict.
38
+ LEGACY_PARSERS = %i[strict exact].freeze
39
+ DEFAULT_LEGACY_TRUE = %w[on].freeze
40
+
41
+ # A declared `bucketing: { version:, salt: }`, for a flag migrated from
42
+ # another system that must keep its old buckets. Copied into the flag's
43
+ # runtime rule when the rule is first created.
44
+ Bucketing = Data.define(:version, :salt)
31
45
 
32
46
  attr_reader :key, :kind, :owner, :description, :env, :inverted, :forbidden_in,
33
- :expose, :unit, :remove_by, :final, :values, :variants, :permanent
47
+ :expose, :unit, :remove_by, :final, :values, :variants, :permanent, :bucketing,
48
+ :legacy_parser, :legacy_true
34
49
 
35
50
  def initialize(kind, key, attributes)
36
51
  @kind = kind.to_sym
@@ -59,8 +74,8 @@ module StandardFlags
59
74
  kind == :kill_switch
60
75
  end
61
76
 
62
- # A `flag` declared `permanent: true`: a standing switch (an environment
63
- # permission, say) with no remove_by: or final:, never stale.
77
+ # A `flag` or `mode` declared `permanent: true`: a standing switch (an
78
+ # environment permission, say) with no remove_by: or final:, never stale.
64
79
  def permanent?
65
80
  permanent
66
81
  end
@@ -113,6 +128,15 @@ module StandardFlags
113
128
  value ? "on" : "off"
114
129
  end
115
130
 
131
+ # The value a stored runtime string stands for ("on"/"off", a mode value,
132
+ # a variant), or Parser::INVALID when this flag can't take it.
133
+ def value_from_wire(text)
134
+ return Parser::INVALID unless text.is_a?(String)
135
+ return { "on" => true, "off" => false }.fetch(text, Parser::INVALID) if boolean?
136
+
137
+ allowed_values.find { |value| value.to_s == text } || Parser::INVALID
138
+ end
139
+
116
140
  # The canonical pin, STANDARD_FLAGS_<KEY>. It is never inverted.
117
141
  def canonical_env_var
118
142
  "STANDARD_FLAGS_#{key.to_s.upcase}"
@@ -161,6 +185,9 @@ module StandardFlags
161
185
  @description = attributes[:description]&.to_s
162
186
  @env = Array(attributes[:env]).map(&:to_s).freeze
163
187
  @inverted = attributes.fetch(:inverted, false)
188
+ @legacy_parser = attributes.fetch(:legacy_parser, :strict)
189
+ @legacy_parser = @legacy_parser.to_sym if @legacy_parser.respond_to?(:to_sym)
190
+ @legacy_true = normalize_legacy_true(attributes)
164
191
  @forbidden_in = Array(attributes[:forbidden_in]).map(&:to_s).freeze
165
192
  @expose = normalize_expose(attributes[:expose])
166
193
  @unit = attributes[:unit]&.to_sym
@@ -172,23 +199,32 @@ module StandardFlags
172
199
  @fail = attributes.key?(:fail) ? coerce(attributes[:fail], :fail) : nil
173
200
  @final = attributes.key?(:final) ? coerce(attributes[:final], :final) : nil
174
201
  @permanent = attributes.fetch(:permanent, false)
202
+ @bucketing = normalize_bucketing(attributes[:bucketing])
175
203
  end
176
204
 
177
205
  def validate!
178
206
  fail!("is missing owner:") if owner.nil? || owner.strip.empty?
179
- validate_flag_lifecycle!
207
+ validate_lifecycle!
180
208
  validate_env!
209
+ validate_legacy_parser!
181
210
  validate_forbidden_in!
211
+ fail!("bucketing: needs a unit: to bucket") if bucketing && unit.nil?
182
212
  end
183
213
 
184
- def validate_flag_lifecycle!
185
- return unless kind == :flag
186
-
214
+ # Flags must declare a lifecycle: remove_by: and final:, or permanent:.
215
+ # Modes may: remove_by: and final: together, or permanent:, or neither.
216
+ def validate_lifecycle!
187
217
  fail!("permanent: must be true or false") unless [ true, false ].include?(permanent)
188
218
  return validate_permanent! if permanent
189
219
 
190
- fail!("is missing remove_by: (release flags are temporary; declare permanent: true for a standing switch)") if remove_by.nil?
191
- fail!("is missing final: (the value it settles on when removed)") if @final.nil?
220
+ case kind
221
+ when :flag
222
+ fail!("is missing remove_by: (release flags are temporary; declare permanent: true for a standing switch)") if remove_by.nil?
223
+ fail!("is missing final: (the value it settles on when removed)") if @final.nil?
224
+ when :mode
225
+ fail!("has remove_by: but is missing final: (the value it settles on when removed)") if remove_by && @final.nil?
226
+ fail!("has final: but is missing remove_by:") if remove_by.nil? && !@final.nil?
227
+ end
192
228
  end
193
229
 
194
230
  def validate_permanent!
@@ -214,6 +250,27 @@ module StandardFlags
214
250
  end
215
251
  end
216
252
 
253
+ def validate_legacy_parser!
254
+ fail!("legacy_parser: must be one of #{LEGACY_PARSERS.inspect}") unless LEGACY_PARSERS.include?(legacy_parser)
255
+ fail!("legacy_parser: needs a legacy env: name") if legacy_parser == :exact && env.empty?
256
+ return if @legacy_true.nil? || @legacy_true.equal?(DEFAULT_LEGACY_TRUE)
257
+
258
+ fail!("legacy_true: needs legacy_parser: :exact") unless legacy_parser == :exact
259
+ fail!("legacy_true: only applies to on/off kinds") unless boolean?
260
+ return unless @legacy_true.empty? || @legacy_true.any? { |word| word.strip.empty? }
261
+
262
+ fail!("legacy_true: must list at least one non-blank value")
263
+ end
264
+
265
+ # The exact legacy values that mean on, for an on/off kind read with
266
+ # `legacy_parser: :exact`; nil otherwise (unless declared, so validation
267
+ # can reject it).
268
+ def normalize_legacy_true(attributes)
269
+ return Array(attributes[:legacy_true]).map(&:to_s).freeze if attributes.key?(:legacy_true)
270
+
271
+ DEFAULT_LEGACY_TRUE if @legacy_parser == :exact && boolean?
272
+ end
273
+
217
274
  def invalid_variants?
218
275
  variants.nil? || variants.size < 2 || variants.uniq.size != variants.size
219
276
  end
@@ -241,6 +298,21 @@ module StandardFlags
241
298
  default.to_h { |env_name, value| [ env_name.to_s, coerce(value, :default) ] }.freeze
242
299
  end
243
300
 
301
+ def normalize_bucketing(bucketing)
302
+ return nil if bucketing.nil?
303
+ fail!("bucketing: must be a Hash with version: and salt:") unless bucketing.is_a?(Hash)
304
+
305
+ bucketing = bucketing.transform_keys(&:to_sym)
306
+ unknown = bucketing.keys - %i[version salt]
307
+ fail!("bucketing: has unknown key(s): #{unknown.map(&:inspect).join(', ')}") unless unknown.empty?
308
+ version = bucketing[:version]
309
+ salt = bucketing[:salt]
310
+ fail!("bucketing: version: must be one of #{HASH_VERSIONS.inspect}") unless HASH_VERSIONS.include?(version)
311
+ fail!("bucketing: salt: must be a non-blank String") unless salt.is_a?(String) && !salt.strip.empty?
312
+
313
+ Bucketing.new(version: version, salt: salt.dup.freeze)
314
+ end
315
+
244
316
  def normalize_expose(expose)
245
317
  pairs =
246
318
  case expose
@@ -24,6 +24,7 @@ module StandardFlags
24
24
  stale: rows.select { |r| r[:stale] }.map { |r| { flag: r[:key], remove_by: r[:remove_by] } },
25
25
  unknown_env_vars: unknown_env_vars(registry, env)
26
26
  }
27
+ report[:runtime] = Runtime.status(registry: registry) if Runtime.enabled?
27
28
  report.merge(status: status(report))
28
29
  end
29
30
 
@@ -32,13 +33,42 @@ module StandardFlags
32
33
  report[:rejected_pins].map { |p| "#{p[:env_var]} for :#{p[:flag]} is not a valid value (ignored)" } +
33
34
  report[:legacy_env_vars].map { |p| "#{p[:env_var]} for :#{p[:flag]} is deprecated; rename to #{p[:canonical]}" } +
34
35
  report[:stale].map { |s| ":#{s[:flag]} is past remove_by #{s[:remove_by]}" } +
35
- report[:unknown_env_vars].map { |var| "#{var} does not match a declared flag" }
36
+ report[:unknown_env_vars].map { |var| "#{var} does not match a declared flag" } +
37
+ runtime_warnings(report[:runtime])
38
+ end
39
+
40
+ # Runtime rules are on but the store says their tables are missing. A
41
+ # store that can't be reached is a warning instead: flags keep serving
42
+ # the last good snapshot (or code defaults) through a database blip.
43
+ def runtime_unavailable?(report)
44
+ tables_missing?(report[:runtime])
45
+ end
46
+
47
+ def tables_missing?(runtime)
48
+ !runtime.nil? && !runtime[:ready] && runtime[:unreachable].nil?
49
+ end
50
+
51
+ def runtime_warnings(runtime)
52
+ return [] if runtime.nil? || tables_missing?(runtime)
53
+
54
+ warnings = []
55
+ if runtime[:unreachable]
56
+ warnings << "runtime rules store is unreachable (#{runtime[:unreachable]}); flags keep serving the last good snapshot"
57
+ end
58
+ if runtime[:stale]
59
+ serving = runtime[:loaded] ? "revision #{runtime[:revision]}, #{runtime[:age]}s old" : "code defaults"
60
+ warnings << "runtime rules are stale: the last refresh failed (serving #{serving})"
61
+ end
62
+ warnings.concat(runtime[:warnings])
63
+ warnings + runtime[:rules].select { |rule| rule[:orphan] }.map do |rule|
64
+ "runtime rule for :#{rule[:key]} has no declared flag (#{rule[:orphan]})"
65
+ end
36
66
  end
37
67
 
38
68
  def row(registry, definition, env, environment, today)
39
69
  evaluation = Evaluator.evaluate(registry, definition.key, Context.new(env: environment))
40
70
  scan = EnvPin.scan(definition, env)
41
- {
71
+ row = {
42
72
  key: definition.key,
43
73
  kind: definition.kind,
44
74
  owner: definition.owner,
@@ -53,6 +83,8 @@ module StandardFlags
53
83
  scan: scan,
54
84
  forbidden_pin: forbidden_pin(definition, scan, environment)
55
85
  }
86
+ row[:rule_status] = Runtime.snapshot.rule(definition.key)&.status if Runtime.enabled?
87
+ row
56
88
  end
57
89
 
58
90
  # The variable pinning a `forbidden_in` flag on here, if any.
@@ -86,7 +118,7 @@ module StandardFlags
86
118
  end
87
119
 
88
120
  def status(report)
89
- return :fail if report[:forbidden_pins].any?
121
+ return :fail if report[:forbidden_pins].any? || runtime_unavailable?(report)
90
122
  return :warn if warnings(report).any?
91
123
 
92
124
  :ok
@@ -1,11 +1,13 @@
1
1
  module StandardFlags
2
- # Library-only engine: no routes, no models. It wires three things into the
2
+ # Library-only engine: no routes, and no models in app/ (the runtime-rule
3
+ # models load only when runtime rules are on). It wires these into the
3
4
  # host:
4
5
  #
5
6
  # * an executor hook that opens a fresh memo per unit of work (requests,
6
7
  # jobs, mailers, console reloads), instead of Rack middleware;
7
8
  # * config/flags.rb, loaded on boot and on every code reload;
8
- # * the Logger / Sentry / Metrics subscribers, once initializers have run.
9
+ # * the Logger / Sentry / Metrics subscribers, once initializers have run;
10
+ # * the runtime-rule store, after boot, when runtime rules are on.
9
11
  #
10
12
  # Rake tasks need no `rake_tasks` block: Rails::Engine already loads
11
13
  # lib/tasks/**/*.rake, and loading the file again would give every task a
@@ -24,5 +26,11 @@ module StandardFlags
24
26
  config.to_prepare do
25
27
  StandardFlags.load_registry!
26
28
  end
29
+
30
+ # Loads the ActiveRecord store (and ActiveRecord) at boot, but only when
31
+ # the host has turned runtime rules on.
32
+ config.after_initialize do
33
+ StandardFlags::Runtime.boot!
34
+ end
27
35
  end
28
36
  end
@@ -4,7 +4,10 @@ module StandardFlags
4
4
  # The canonical STANDARD_FLAGS_<KEY> is read first, then each legacy `env:`
5
5
  # name in declared order. The first variable that parses wins, so a valid
6
6
  # canonical pin beats any legacy one. `inverted: true` flips legacy values
7
- # only (a legacy *_DISABLED=true means the flag is off).
7
+ # only (a legacy *_DISABLED=true means the flag is off), and
8
+ # `legacy_parser: :exact` changes how legacy values parse, never the
9
+ # canonical one. A blank value counts as unset, except a blank exact legacy
10
+ # value on a non-inverted on/off flag, which pins it off.
8
11
  #
9
12
  # Callers decide what to report; Diagnostics and the health check use the
10
13
  # same scan, so they can't disagree with evaluation.
@@ -31,11 +34,11 @@ module StandardFlags
31
34
 
32
35
  ([ definition.canonical_env_var ] + definition.env).each do |var|
33
36
  raw = env[var]
34
- next if Parser.blank?(raw)
35
-
36
37
  is_legacy = var != definition.canonical_env_var
38
+ next if Parser.blank?(raw) && !(is_legacy && blank_pins_off?(definition, raw))
39
+
37
40
  legacy << var if is_legacy
38
- value = Parser.parse(definition, raw)
41
+ value = is_legacy ? Parser.parse_legacy(definition, raw) : Parser.parse(definition, raw)
39
42
  if value.equal?(Parser::INVALID)
40
43
  rejected << var
41
44
  elsif pin.nil?
@@ -46,5 +49,13 @@ module StandardFlags
46
49
 
47
50
  Scan.new(pin: pin, rejected: rejected.freeze, legacy: legacy.freeze)
48
51
  end
52
+
53
+ # Under `legacy_parser: :exact`, a set-but-blank legacy value pins an
54
+ # on/off flag off, as `ENV["X"] == "on"` did; only an unset variable
55
+ # falls through. Not for inverted names: off there would turn the flag
56
+ # on, so a blank one stays unset. Modes keep blank as unset too.
57
+ def blank_pins_off?(definition, raw)
58
+ !raw.nil? && definition.legacy_parser == :exact && definition.boolean? && !definition.inverted
59
+ end
49
60
  end
50
61
  end
@@ -32,4 +32,8 @@ module StandardFlags
32
32
  # Reported (never raised) through Rails.error when a `forbidden_in` flag is
33
33
  # pinned on in an environment that forbids it.
34
34
  class ForbiddenPin < Error; end
35
+
36
+ # Reported (never raised) through Rails.error when a stored runtime rule
37
+ # holds something its flag can't serve. Only that flag fails.
38
+ class RuleInvalid < Error; end
35
39
  end