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
@@ -6,19 +6,20 @@ module StandardFlags
6
6
  # * `variant` — the value as a string ("on"/"off" for booleans).
7
7
  # * `reason` — one of StandardFlags::Reason.
8
8
  # * `error_code` — one of StandardFlags::ErrorCode, only when reason is ERROR.
9
- # * `rule_id` — the matching runtime rule; always nil until runtime
10
- # rules exist.
9
+ # * `rule_id` — which part of a runtime rule decided: "allow",
10
+ # "deny", "cohort:<key>", "segment:<name>", "percentage",
11
+ # "variants", "fallthrough" or "stopped". nil otherwise.
11
12
  # * `source_env_var` — the NAME of the environment variable that decided the
12
13
  # value, never its contents.
13
14
  Evaluation = Data.define(:key, :value, :variant, :reason, :error_code, :rule_id, :source_env_var) do
14
- def self.build(definition, value, reason:, error_code: nil, source_env_var: nil)
15
+ def self.build(definition, value, reason:, error_code: nil, rule_id: nil, source_env_var: nil)
15
16
  new(
16
17
  key: definition.key,
17
18
  value: value,
18
19
  variant: definition.variant_for(value),
19
20
  reason: reason,
20
21
  error_code: error_code,
21
- rule_id: nil,
22
+ rule_id: rule_id,
22
23
  source_env_var: source_env_var
23
24
  )
24
25
  end
@@ -14,13 +14,26 @@ module StandardFlags
14
14
  definition = registry[key]
15
15
  return unknown(registry, key) unless definition
16
16
 
17
- evaluation = Memo.fetch([ key, context.cache_key ]) { resolve(registry, definition, context) }
17
+ evaluation = Memo.fetch(memo_key(registry, definition, context)) { resolve(registry, definition, context) }
18
18
  sample(evaluation)
19
19
  evaluation
20
20
  end
21
21
 
22
+ # With runtime rules on, the answer depends on the flag's unit key, which
23
+ # a unit's `key:` can derive from something other than the actor's id;
24
+ # so the resolved key joins the memo key.
25
+ def memo_key(registry, definition, context)
26
+ key = [ definition.key, context.cache_key ]
27
+ return key unless definition.unit && Runtime.enabled?
28
+
29
+ key + [ Runtime.unit_key(registry, definition, context) ]
30
+ rescue StandardError
31
+ key + [ Runtime::UNRESOLVED ]
32
+ end
33
+
22
34
  def resolve(registry, definition, context)
23
35
  request = Resolvers::Request.new(
36
+ registry: registry,
24
37
  definition: definition,
25
38
  context: context,
26
39
  env_name: (context.env || registry.current_env).to_s,
@@ -0,0 +1,49 @@
1
+ module StandardFlags
2
+ # The events the write path publishes, one per operation, through
3
+ # ActiveSupport::Notifications. Their payload carries the actor (a record,
4
+ # or nil for a system actor), `actor_label`, `reason`, the flag `key` or
5
+ # `cohort`, `revision` (a rule's lock_version, or for cohorts the store's
6
+ # revision) and `store_revision`, and the rule or cohort state `before`
7
+ # and `after`. Membership changes carry `unit`, `value` and counts, never
8
+ # a unit key.
9
+ module Events
10
+ NAMESPACE = "standard_flags".freeze
11
+
12
+ FLAG = %w[started paused stopped ramped variants_set value_set conditions_set members_added members_removed restored].freeze
13
+ COHORT = %w[created archived attached detached members_added members_removed restored].freeze
14
+
15
+ FLAG_EVENTS = FLAG.to_h { |verb| [ verb.to_sym, "#{NAMESPACE}.flag.#{verb}".freeze ] }.freeze
16
+ # Membership changes on a cohort publish `standard_flags.cohort.members_*`.
17
+ COHORT_EVENTS = COHORT.to_h { |verb| [ verb.to_sym, "#{NAMESPACE}.cohort.#{verb}".freeze ] }.freeze
18
+
19
+ # Operator reads that show what only a reveal may (not changes): unit
20
+ # keys revealed by list_members, and get_flag evaluated for one unit key
21
+ # (which says whether it is a member). Counts only, never a key.
22
+ MEMBERS_REVEALED = "#{NAMESPACE}.members.revealed".freeze
23
+ FLAG_PROBED = "#{NAMESPACE}.flag.probed".freeze
24
+ READS = [ MEMBERS_REVEALED, FLAG_PROBED ].freeze
25
+
26
+ # Every event an audit log should keep: all of them.
27
+ AUDITABLE = (FLAG_EVENTS.values + COHORT_EVENTS.values + READS).freeze
28
+
29
+ class << self
30
+ # The event names a host should persist to its audit log, as full
31
+ # Strings that ActiveSupport::Notifications and standard_audit's
32
+ # `subscribe_to` both accept:
33
+ #
34
+ # StandardAudit.configure do |config|
35
+ # StandardFlags::Events.auditable.each { |pattern| config.subscribe_to(pattern) }
36
+ # end
37
+ #
38
+ # When standard_audit subscribes to an event, operations leave the row
39
+ # to its subscriber (which runs inside the operation's transaction);
40
+ # otherwise they write it themselves. Either way there is one row per
41
+ # change. New releases may add to the list.
42
+ #
43
+ # @return [Array<String>] frozen
44
+ def auditable
45
+ AUDITABLE
46
+ end
47
+ end
48
+ end
49
+ end
@@ -8,9 +8,13 @@ module StandardFlags
8
8
  # c.register_check :flags, StandardFlags::HealthCheck
9
9
  # end
10
10
  #
11
- # * Fails when a `forbidden_in` flag is pinned on in this environment.
11
+ # * Fails when a `forbidden_in` flag is pinned on in this environment, or
12
+ # when runtime rules are on and their tables are missing.
12
13
  # * Warns on unparseable pins, legacy env names in use (deprecated), flags
13
- # past remove_by, and STANDARD_FLAGS_* variables that match no flag.
14
+ # past remove_by, STANDARD_FLAGS_* variables that match no flag, a
15
+ # runtime-rule store that can't be reached, a stale runtime-rule
16
+ # snapshot, store warnings (such as prepared statements being off), and
17
+ # rules for undeclared or tombstoned keys.
14
18
  #
15
19
  # standard_health has no warning status, so warnings ride on the row as
16
20
  # `warnings:` and the check stays :ok. Pass `warn_as: :fail` to let them
@@ -18,6 +22,7 @@ module StandardFlags
18
22
  # to look, not to pull an instance out of rotation.
19
23
  class HealthCheck < ::StandardHealth::Check
20
24
  VIOLATION_LABEL = "StandardFlags::ForbiddenPin".freeze
25
+ RUNTIME_LABEL = "StandardFlags::RuntimeUnavailable".freeze
21
26
  WARNING_LABEL = "StandardFlags::FlagWarning".freeze
22
27
 
23
28
  attr_reader :warn_as
@@ -39,6 +44,11 @@ module StandardFlags
39
44
  names = forbidden.map { |p| "#{p[:flag]} (#{p[:env_var]})" }.join(", ")
40
45
  return timing.merge(status: :fail, error: "forbidden flags pinned on: #{names}", error_class: VIOLATION_LABEL)
41
46
  end
47
+ if Diagnostics.runtime_unavailable?(report)
48
+ return timing.merge(status: :fail, error: "runtime rules are on but their tables are missing; run the " \
49
+ "standard_flags:migrations generator and migrate",
50
+ error_class: RUNTIME_LABEL)
51
+ end
42
52
 
43
53
  warnings = Diagnostics.warnings(report)
44
54
  return timing if warnings.empty?
@@ -0,0 +1,65 @@
1
+ module StandardFlags
2
+ # Announces StandardFlags to standard_health 0.9+ through its load hook, so
3
+ # an app that calls `register_default_checks` gets the flags check without
4
+ # registering it, and `/diagnostics/env` lists the pins that must stay
5
+ # unset. Neither gem depends on the other: with standard_health absent (or
6
+ # older than 0.9) the hook never runs, and apps register
7
+ # StandardFlags::HealthCheck by hand as before.
8
+ #
9
+ # Env vars contributed: the canonical STANDARD_FLAGS_<KEY> pin and every
10
+ # legacy `env:` name of each `forbidden_in:` flag, as `forbidden` in those
11
+ # environments when they pin the flag on. Other pins are optional, which
12
+ # EnvSpec has no level for, so they are not declared. An app's own
13
+ # env_spec entry for a name overrides the contribution. The declarations
14
+ # are re-contributed whenever the registry is (re)defined.
15
+ #
16
+ # @api private
17
+ module HealthContribution
18
+ CONTRIBUTOR = "standard_flags".freeze
19
+ CHECK_NAME = :standard_flags
20
+ HOOK = proc { |health| HealthContribution.register!(health) }
21
+
22
+ class << self
23
+ def register!(health)
24
+ @health = health
25
+ health.contribute_check CHECK_NAME, "StandardFlags::HealthCheck", critical: false
26
+ contribute_env_vars(StandardFlags.registry)
27
+ end
28
+
29
+ def refresh!(registry)
30
+ contribute_env_vars(registry) if @health
31
+ end
32
+
33
+ # Forget the yielded object (specs only).
34
+ def reset!
35
+ @health = nil
36
+ end
37
+
38
+ def env_entries(registry, env: -> { StandardFlags.config.env_source })
39
+ registry.definitions.reject { |definition| definition.forbidden_in.empty? }.flat_map do |definition|
40
+ pinned_on = -> { pinned_on?(definition, env.call) }
41
+ ([ definition.canonical_env_var ] + definition.env).map do |name|
42
+ { name: name.to_sym, in: definition.forbidden_in.dup,
43
+ description: "Pins :#{definition.key}, which is forbidden_in: these environments", if: pinned_on }
44
+ end
45
+ end
46
+ end
47
+
48
+ private
49
+
50
+ def contribute_env_vars(registry)
51
+ entries = env_entries(registry)
52
+ @health.contribute_env_vars(CONTRIBUTOR) do
53
+ entries.each { |entry| forbidden entry[:name], in: entry[:in], description: entry[:description], if: entry[:if] }
54
+ end
55
+ rescue StandardError => e
56
+ warn "[standard_flags] standard_health env contribution failed: #{e.class}: #{e.message}"
57
+ end
58
+
59
+ def pinned_on?(definition, env)
60
+ pin = EnvPin.scan(definition, env).pin
61
+ !pin.nil? && pin.value != definition.off_value
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,65 @@
1
+ module StandardFlags
2
+ module MCP
3
+ # Shared by the cohort tools.
4
+ module CohortView
5
+ private
6
+
7
+ # The flags it is attached to are those the actor may read; the rest
8
+ # are counted in `hidden_flags`.
9
+ def cohort_summary(cohort)
10
+ attached = loaded.rules.filter_map do |rule|
11
+ value = rule.cohort_attachments.find { |key, _| key == cohort.key }&.last
12
+ { key: rule.key, value: value } if value
13
+ end
14
+ readable, hidden = attached.partition { |a| allowed?("flags:read", a[:key]) }
15
+ cohort.audit_state.merge(archived: cohort.archived?, attached_to: readable.sort_by { |a| a[:key] },
16
+ hidden_flags: hidden.size)
17
+ end
18
+
19
+ def runtime!
20
+ raise ToolError.new(:runtime_rules_off, "runtime rules are off") unless Runtime.enabled?
21
+ end
22
+ end
23
+
24
+ # Every cohort the actor may read, with its unit, member count and the
25
+ # flags it is attached to.
26
+ class ListCohorts < Tool
27
+ include CohortView
28
+
29
+ tool_name "list_cohorts"
30
+ description "List cohorts (named member lists): unit, member count, archived state and the flags each is attached to."
31
+ schema({ include_archived: { type: "boolean", description: "Include archived cohorts (default false)" } })
32
+
33
+ private
34
+
35
+ def perform(args)
36
+ runtime!
37
+ cohorts = loaded.cohorts.sort_by(&:key)
38
+ cohorts = cohorts.reject(&:archived?) unless args["include_archived"] == true
39
+ { cohorts: cohorts.select { |cohort| allowed?("flags:read", "cohort:#{cohort.key}") }.map { |c| cohort_summary(c) },
40
+ store_revision: store_revision }
41
+ end
42
+ end
43
+
44
+ # One cohort. Its members are listed by list_members (cohort:).
45
+ class GetCohort < Tool
46
+ include CohortView
47
+
48
+ tool_name "get_cohort"
49
+ description "Show one cohort: name, description, unit, member count, archived state and attached flags."
50
+ schema({ cohort: { type: "string", description: "The cohort key" } }, required: %w[cohort])
51
+
52
+ private
53
+
54
+ def perform(args)
55
+ key = args["cohort"].to_s.delete_prefix("cohort:")
56
+ authorize!("flags:read", "cohort:#{key}")
57
+ runtime!
58
+ cohort = loaded.cohorts.find { |candidate| candidate.key == key }
59
+ raise ToolError.new(:unknown_cohort, "unknown cohort #{key.inspect}") unless cohort
60
+
61
+ cohort_summary(cohort).merge(store_revision: store_revision)
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,143 @@
1
+ module StandardFlags
2
+ module MCP
3
+ # What decided an evaluation, in one word.
4
+ module Source
5
+ module_function
6
+
7
+ def of(evaluation)
8
+ if evaluation.source_env_var then "env_pin"
9
+ elsif evaluation.rule_id then "runtime_rule"
10
+ elsif evaluation.reason == Reason::DISABLED then "guard"
11
+ elsif evaluation.reason == Reason::ERROR then "error"
12
+ elsif evaluation.reason == Reason::STATIC then "test_override"
13
+ else "code_default"
14
+ end
15
+ end
16
+ end
17
+
18
+ # Every declared flag the actor may read: its declaration, its value with
19
+ # no unit, any ENV pin, and a summary of its stored rule.
20
+ class ListFlags < Tool
21
+ tool_name "list_flags"
22
+ description "List the declared feature flags: kind, owner, current value with no unit, " \
23
+ "ENV pin (variable name only) and runtime rule status."
24
+ schema({})
25
+
26
+ private
27
+
28
+ def perform(_args)
29
+ definitions = registry.definitions.sort_by(&:key)
30
+ readable = definitions.select { |definition| allowed?("flags:read", definition.key) }
31
+ if readable.empty? && !definitions.empty?
32
+ raise ToolError.new(:unauthorized, "#{Actor.label(actor)} may not flags:read any flag")
33
+ end
34
+
35
+ { flags: readable.map { |definition| summary(definition) }, runtime_rules: Runtime.enabled?,
36
+ store_revision: store_revision }
37
+ end
38
+
39
+ def summary(definition)
40
+ evaluation = Evaluator.evaluate(registry, definition.key, Context.empty)
41
+ rule = rule_for(definition.key)
42
+ {
43
+ key: definition.key, kind: definition.kind, owner: definition.owner, description: definition.description,
44
+ unit: definition.unit, values: definition.allowed_values.map { |value| Runtime.wire(value) },
45
+ value: Runtime.wire(evaluation.value), reason: evaluation.reason, source: Source.of(evaluation),
46
+ pinned: pin(definition),
47
+ rule: rule && { status: rule.status, revision: rule.lock_version, percentage_bps: rule.percentage_bps,
48
+ member_count: rule.member_count }
49
+ }
50
+ end
51
+ end
52
+
53
+ # One flag: its declaration, what it evaluates to (for one unit when
54
+ # `unit_key` is given), any ENV pin, and its stored rule in full. The
55
+ # rule's cohorts are those the actor may read (`cohort:<key>`); the
56
+ # rest are counted in `hidden_cohorts`.
57
+ #
58
+ # An evaluation for one unit says whether that unit is a member, so it
59
+ # is a reveal: it needs "flags:write" on the flag and a `reason`, and is
60
+ # audited as `standard_flags.flag.probed` (counts only, no key) before
61
+ # anything is returned.
62
+ class GetFlag < Tool
63
+ tool_name "get_flag"
64
+ description "Show one feature flag: declaration, evaluated value, reason, rule_id and source " \
65
+ "(optionally for one unit key: needs flags:write and a reason; audited), ENV pin status " \
66
+ "and the stored runtime rule."
67
+ schema({ key: { type: "string", description: "The flag key, e.g. new_checkout" },
68
+ unit: { type: "string", description: "The flag's unit (optional; must match the declaration)" },
69
+ unit_key: { type: "string", description: "Evaluate for this unit key (needs flags:write and a reason)" },
70
+ reason: { type: "string", description: "Why one unit is evaluated; written to the audit log" } },
71
+ required: %w[key])
72
+
73
+ private
74
+
75
+ def perform(args)
76
+ definition = definition!(args["key"])
77
+ authorize!("flags:read", definition.key)
78
+ evaluation, masked = evaluate(definition, args)
79
+ {
80
+ key: definition.key, kind: definition.kind, owner: definition.owner, description: definition.description,
81
+ unit: definition.unit, values: definition.allowed_values.map { |value| Runtime.wire(value) },
82
+ default: Runtime.wire(definition.default_for(registry.current_env)),
83
+ evaluation: { unit_key: masked, value: Runtime.wire(evaluation.value), variant: evaluation.variant,
84
+ reason: evaluation.reason, error_code: evaluation.error_code, rule_id: evaluation.rule_id,
85
+ source: Source.of(evaluation) },
86
+ pinned: pin(definition),
87
+ runtime_rules: Runtime.enabled?,
88
+ rule: readable_rule(rule_for(definition.key)),
89
+ store_revision: store_revision
90
+ }
91
+ end
92
+
93
+ # The evaluation, and the unit key it was for, masked.
94
+ def evaluate(definition, args)
95
+ if args.key?("unit") && args["unit"].to_s != definition.unit.to_s
96
+ raise ToolError.new(:invalid_arguments, "unit #{args['unit'].inspect} is not :#{definition.key}'s unit (#{definition.unit.inspect})")
97
+ end
98
+ return [ Evaluator.evaluate(registry, definition.key, Context.empty), nil ] unless args.key?("unit_key")
99
+ raise ToolError.new(:invalid_arguments, ":#{definition.key} has no unit, so it can't be evaluated per unit") unless definition.unit
100
+
101
+ check_probe!(definition, args)
102
+ key = unit_key(definition, args["unit_key"])
103
+ evaluation = Evaluator.evaluate(registry.with_unit_key(definition.unit, key), definition.key, Context.empty)
104
+ audit_probe(definition, args)
105
+ [ evaluation, MCP.mask(key) ]
106
+ end
107
+
108
+ def check_probe!(definition, args)
109
+ authorize!("flags:write", definition.key)
110
+ return if args["reason"].is_a?(String) && !args["reason"].strip.empty?
111
+
112
+ raise ToolError.new(:invalid_arguments, "a reason is required to evaluate one unit key")
113
+ end
114
+
115
+ def audit_probe(definition, args)
116
+ payload = { actor: actor.is_a?(Actor) ? nil : actor, actor_label: Actor.label(actor), reason: args["reason"],
117
+ key: definition.key, unit: definition.unit.to_s, probed: 1 }
118
+ Operations::Audit.record_read(Events::FLAG_PROBED, payload)
119
+ rescue Operations::Failure => e
120
+ raise ToolError.new(e.code, "#{e.message}; nothing was evaluated")
121
+ end
122
+
123
+ def readable_rule(rule)
124
+ state = rule_state(rule)
125
+ return state unless state
126
+
127
+ cohorts, hidden = Array(state[:cohorts]).partition do |attachment|
128
+ attachment.is_a?(Hash) && allowed?("flags:read", "cohort:#{attachment['cohort']}")
129
+ end
130
+ state.merge(cohorts: cohorts, hidden_cohorts: hidden.size)
131
+ end
132
+
133
+ def unit_key(definition, given)
134
+ key = begin
135
+ registry.units[definition.unit].key_for(given.to_s)
136
+ rescue StandardError => e
137
+ raise ToolError.new(:invalid_arguments, "the unit key could not be normalised for :#{definition.unit} (#{e.class})")
138
+ end
139
+ key || raise(ToolError.new(:invalid_arguments, "unit_key is blank"))
140
+ end
141
+ end
142
+ end
143
+ end
@@ -0,0 +1,154 @@
1
+ module StandardFlags
2
+ module MCP
3
+ # Shared by the member tools: they act on a flag's rule (`key`) or a
4
+ # cohort (`cohort`), exactly one of them.
5
+ module MemberTarget
6
+ TARGET = {
7
+ key: { type: "string", description: "The flag key (or give cohort)" },
8
+ cohort: { type: "string", description: "The cohort key (or give key)" }
9
+ }.freeze
10
+
11
+ private
12
+
13
+ # A flag key Symbol, or "cohort:<key>": what operations and the policy
14
+ # take.
15
+ def target(args)
16
+ flag, cohort = args.values_at("key", "cohort")
17
+ raise ToolError.new(:invalid_arguments, "give exactly one of key or cohort") unless flag.nil? ^ cohort.nil?
18
+
19
+ flag ? definition!(flag).key : "cohort:#{cohort.to_s.delete_prefix('cohort:')}"
20
+ end
21
+ end
22
+
23
+ # One page of a flag's or a cohort's members, unit keys masked
24
+ # (`•••4567`). With `reveal: true` and a `reason`, an actor allowed
25
+ # "flags:write" on the target sees the keys; the reveal is audited as
26
+ # `standard_flags.members.revealed`, with counts only.
27
+ class ListMembers < Tool
28
+ include MemberTarget
29
+
30
+ MAX_LIMIT = 200
31
+
32
+ tool_name "list_members"
33
+ description "List one page of a flag's or a cohort's members. Unit keys are masked unless reveal is true " \
34
+ "(needs flags:write and a reason; audited)."
35
+ schema(TARGET.merge(
36
+ offset: { type: "integer", description: "Members to skip (default 0)" },
37
+ limit: { type: "integer", description: "Page size, 1-#{MAX_LIMIT} (default 50)" },
38
+ reveal: { type: "boolean", description: "Show unit keys in full (needs flags:write and a reason)" },
39
+ reason: { type: "string", description: "Why the keys are revealed; written to the audit log" }
40
+ ))
41
+
42
+ private
43
+
44
+ def perform(args)
45
+ owner = target(args)
46
+ authorize!("flags:read", owner)
47
+ raise ToolError.new(:runtime_rules_off, "runtime rules are off") unless Runtime.enabled?
48
+
49
+ offset, limit = page_bounds(args)
50
+ reveal = args["reveal"] == true
51
+ check_reveal!(owner, args) if reveal
52
+ page = read_page(owner, offset, limit)
53
+ audit_reveal(owner, args, page) if reveal
54
+ {
55
+ **owner_field(owner), total: page.total, offset: offset, limit: limit,
56
+ next_offset: (offset + limit if offset + limit < page.total), revealed: reveal,
57
+ members: page.memberships.map { |membership| member(membership, reveal) }
58
+ }
59
+ end
60
+
61
+ def page_bounds(args)
62
+ offset = args.fetch("offset", 0)
63
+ limit = args.fetch("limit", 50)
64
+ raise ToolError.new(:invalid_arguments, "offset must be 0 or more") if offset.negative?
65
+ raise ToolError.new(:invalid_arguments, "limit must be 1-#{MAX_LIMIT}") unless (1..MAX_LIMIT).cover?(limit)
66
+
67
+ [ offset, limit ]
68
+ end
69
+
70
+ def check_reveal!(owner, args)
71
+ authorize!("flags:write", owner)
72
+ return if args["reason"].is_a?(String) && !args["reason"].strip.empty?
73
+
74
+ raise ToolError.new(:invalid_arguments, "a reason is required to reveal unit keys")
75
+ end
76
+
77
+ def read_page(owner, offset, limit)
78
+ Runtime.store.members(**owner_lookup(owner), offset: offset, limit: limit)
79
+ rescue StandardError => e
80
+ raise ToolError.new(:store_error, "could not read the store (#{(e.cause_class if e.is_a?(Runtime::StoreError)) || e.class})")
81
+ end
82
+
83
+ def audit_reveal(owner, args, page)
84
+ payload = { actor: actor.is_a?(Actor) ? nil : actor, actor_label: Actor.label(actor), reason: args["reason"],
85
+ **owner_field(owner), units: page.memberships.map { |m| m.unit.to_s }.uniq.sort,
86
+ revealed: page.memberships.size, total: page.total }
87
+ Operations::Audit.record_read(Events::MEMBERS_REVEALED, payload)
88
+ rescue Operations::Failure => e
89
+ raise ToolError.new(e.code, "#{e.message}; nothing was revealed")
90
+ end
91
+
92
+ def member(membership, reveal)
93
+ expires_at = membership.expires_at
94
+ { unit: membership.unit, unit_key: reveal ? membership.unit_key : MCP.mask(membership.unit_key),
95
+ value: membership.value, expires_at: expires_at, expired: !membership.live?(Time.now.utc),
96
+ added_at: membership.created_at }
97
+ end
98
+
99
+ def owner_lookup(owner)
100
+ owner.is_a?(Symbol) ? { rule: owner } : { cohort: owner.delete_prefix("cohort:") }
101
+ end
102
+
103
+ def owner_field(owner)
104
+ owner.is_a?(Symbol) ? { key: owner } : { cohort: owner.delete_prefix("cohort:") }
105
+ end
106
+ end
107
+
108
+ class AddMembers < OperationTool
109
+ include MemberTarget
110
+
111
+ tool_name "add_members"
112
+ description "Add units (by key) to a flag's rule or a cohort. Flag members serve value (on/off flags default " \
113
+ "to on); cohort members serve the cohort's attachment value. Keys never appear in the result."
114
+ operation Operations::AddMembers
115
+ schema(TARGET.merge(OperationTool::COMMON.except(:key)).merge(
116
+ keys: { type: "array", items: { type: "string" }, description: "Unit keys" },
117
+ value: { type: "string", description: "What flag members get: on/off, a mode value or a variant" },
118
+ unit: { type: "string", description: "The unit (optional; must match)" },
119
+ expires_at: { type: "string", description: "ISO 8601 time the memberships end (optional)" }
120
+ ), required: %w[keys reason])
121
+
122
+ private
123
+
124
+ def operation_args(args)
125
+ out = args.slice("keys", "value", "unit").transform_keys(&:to_sym)
126
+ out[:expires_at] = expires_at(args["expires_at"]) if args.key?("expires_at")
127
+ out
128
+ end
129
+
130
+ def expires_at(text)
131
+ Time.iso8601(text.to_s)
132
+ rescue ArgumentError
133
+ raise ToolError.new(:invalid_arguments, "expires_at must be an ISO 8601 time")
134
+ end
135
+ end
136
+
137
+ class RemoveMembers < OperationTool
138
+ include MemberTarget
139
+
140
+ tool_name "remove_members"
141
+ description "Remove units (by key) from a flag's rule or a cohort. Rows are kept for " \
142
+ "config.membership_retention so they can be restored. Keys never appear in the result."
143
+ operation Operations::RemoveMembers
144
+ schema(TARGET.merge(OperationTool::COMMON.except(:key)).merge(
145
+ keys: { type: "array", items: { type: "string" }, description: "Unit keys" },
146
+ unit: { type: "string", description: "The unit (optional; must match)" }
147
+ ), required: %w[keys reason])
148
+
149
+ private
150
+
151
+ def operation_args(args) = args.slice("keys", "unit").transform_keys(&:to_sym)
152
+ end
153
+ end
154
+ end
@@ -0,0 +1,98 @@
1
+ module StandardFlags
2
+ module MCP
3
+ # A tool that runs one operation. `reason` is required and
4
+ # `expected_revision` (the rule's revision from get_flag) optional; the
5
+ # operation authorises, refuses pins, validates and audits, and its
6
+ # failure code becomes the error code.
7
+ class OperationTool < Tool
8
+ COMMON = {
9
+ key: { type: "string", description: "The flag key" },
10
+ reason: { type: "string", description: "Why; written to the audit log" },
11
+ expected_revision: { type: "integer", description: "Refuse unless the rule is still at this revision (from get_flag)" }
12
+ }.freeze
13
+
14
+ class << self
15
+ def operation(klass = nil)
16
+ @operation = klass if klass
17
+ @operation
18
+ end
19
+
20
+ # The common arguments plus the operation's own.
21
+ def arguments(properties = {}, required: [])
22
+ schema(COMMON.merge(properties), required: %w[key reason] + required)
23
+ end
24
+ end
25
+
26
+ private
27
+
28
+ def perform(args)
29
+ result = self.class.operation.call(target(args), actor: actor, reason: args["reason"],
30
+ expected_revision: args["expected_revision"],
31
+ registry: registry, **operation_args(args))
32
+ raise ToolError.new(result.code, result.errors.join("; ")) unless result.success?
33
+
34
+ result.value
35
+ end
36
+
37
+ def target(args)
38
+ args["key"]
39
+ end
40
+
41
+ def operation_args(_args)
42
+ {}
43
+ end
44
+ end
45
+
46
+ class StartFlag < OperationTool
47
+ tool_name "start_flag"
48
+ description "Start a draft or paused runtime rule, so it serves."
49
+ operation Operations::Start
50
+ arguments
51
+ end
52
+
53
+ class PauseFlag < OperationTool
54
+ tool_name "pause_flag"
55
+ description "Pause a running runtime rule: the code default serves, and the rule's settings are kept."
56
+ operation Operations::Pause
57
+ arguments
58
+ end
59
+
60
+ class StopFlag < OperationTool
61
+ tool_name "stop_flag"
62
+ description "Stop a runtime rule, serving one value to everyone (the winner, or the flag's final value)."
63
+ operation Operations::Stop
64
+ arguments({ serve: { type: "string", description: "The value to serve: on/off, a mode value or a variant" } },
65
+ required: %w[serve])
66
+
67
+ private
68
+
69
+ def operation_args(args) = { serve: args["serve"] }
70
+ end
71
+
72
+ class RampFlag < OperationTool
73
+ tool_name "ramp_flag"
74
+ description "Set the percentage of units (basis points, 0-10000) that get the rollout value. Needs flags:ramp."
75
+ operation Operations::Ramp
76
+ arguments({ bps: { type: "integer", description: "Basis points, 0-10000 (500 = 5%)" },
77
+ value: { type: "string", description: "The rollout value (modes and experiments; on/off flags roll out on)" } },
78
+ required: %w[bps])
79
+
80
+ private
81
+
82
+ def operation_args(args) = args.slice("bps", "value").transform_keys(&:to_sym)
83
+ end
84
+
85
+ class SetFlagValue < OperationTool
86
+ tool_name "set_flag_value"
87
+ description "Set a runtime rule's fallthrough value, served to every unit nothing else matched " \
88
+ "(how a mode moves off → sensor → on, or a kill switch is thrown). null clears it."
89
+ operation Operations::SetValue
90
+ arguments({ value: { type: %w[string null], description: "on/off, a mode value or a variant; null clears" } },
91
+ required: %w[value])
92
+
93
+ private
94
+
95
+ def operation_args(args) = { value: args["value"] }
96
+ end
97
+ end
98
+ end