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,164 @@
1
+ module StandardFlags
2
+ module Operations
3
+ # Unit keys as an operation stores them: each normalised through the
4
+ # registry's unit (`key:`), so records and raw keys both work, or, for
5
+ # keys already read back from the store (`normalized: true`), taken as
6
+ # they are, since a `key:` written for records can't take its own
7
+ # output. Checked for blanks, and (unless `limit: false`, for a write
8
+ # that chunks them itself) against `config.max_keys_per_operation`;
9
+ # errors never quote a key.
10
+ module MemberKeys
11
+ private
12
+
13
+ def member_keys(unit, items, normalized:, limit: true)
14
+ items = items.respond_to?(:to_ary) ? items.to_ary : [ items ]
15
+ validate.keys_count!(items.size, config) if limit
16
+ keys = normalized ? items.map { |item| stored_key(item) } : items.map { |item| normalize(unit, item) }
17
+ blank = keys.count(&:nil?)
18
+ raise Failure.new(:invalid, "#{blank} of the keys #{blank == 1 ? 'is' : 'are'} blank") unless blank.zero?
19
+ raise Failure.new(:invalid, "keys must not be empty") if keys.empty?
20
+
21
+ keys.uniq
22
+ end
23
+
24
+ def normalize(unit, item)
25
+ unit.key_for(item)
26
+ rescue StandardError => e
27
+ raise Failure.new(:invalid, "a key could not be normalised for :#{unit.name} (#{e.class})")
28
+ end
29
+
30
+ def stored_key(item)
31
+ raise Failure.new(:invalid, "normalized keys must be Strings") unless item.is_a?(String)
32
+
33
+ item.strip.empty? ? nil : item
34
+ end
35
+ end
36
+
37
+ # Shared by AddMembers and RemoveMembers: the owner is a flag's rule or
38
+ # a cohort, and unit keys go through MemberKeys. `normalized: true`
39
+ # (keys exactly as the store holds them) is internal: only a system
40
+ # actor may pass it, and no MCP tool or admin page does. Unit keys are
41
+ # written raw but never appear in a Result, an audit row, a
42
+ # notification or a report: those carry the unit, the value and counts
43
+ # only.
44
+ class MembershipOperation < Base
45
+ include MemberKeys
46
+
47
+ def self.targets
48
+ %i[flag cohort]
49
+ end
50
+
51
+ private
52
+
53
+ def event
54
+ (@cohort_key ? Events::COHORT_EVENTS : Events::FLAG_EVENTS)[self.class::VERB]
55
+ end
56
+
57
+ def sensitive?
58
+ true
59
+ end
60
+
61
+ def run
62
+ @cohort_key ? run_cohort : super
63
+ end
64
+
65
+ # Rule owners go through Base#run.
66
+ def perform
67
+ unit = validate.unit!(definition, registry, "members")
68
+ change(@rule, unit).tap { save!({}) }
69
+ end
70
+
71
+ # Locks the cohort, then its memberships, then (last, as every write
72
+ # does) the state row for the revision check.
73
+ def run_cohort
74
+ cohort = tx.lock_cohort(@cohort_key)
75
+ raise Failure.new(:invalid, "cohort #{@cohort_key.inspect} does not exist") unless cohort
76
+ raise Failure.new(:invalid, "cohort #{@cohort_key.inspect} is archived") if cohort.archived? && self.class::VERB == :members_added
77
+
78
+ before = cohort.audit_state
79
+ unit = registry.units[cohort.unit]
80
+ raise Failure.new(:invalid, "cohort #{@cohort_key.inspect} holds :#{cohort.unit}, which is not declared") unless unit
81
+
82
+ extra = change(cohort, unit)
83
+ cohort = tx.save_cohort(cohort, {})
84
+ check_revision!(tx.lock_revision)
85
+ revision = Runtime.bump_revision!(tx)
86
+ publish(event, { cohort: @cohort_key, before: before, after: cohort.audit_state,
87
+ revision: revision, store_revision: revision, **extra })
88
+ { cohort: @cohort_key, state: cohort.audit_state, revision: revision, store_revision: revision, **extra }
89
+ end
90
+
91
+ def unit_keys(unit)
92
+ if args.key?(:unit) && args[:unit].to_s != unit.name.to_s
93
+ raise Failure.new(:invalid, "unit: #{args[:unit].inspect} does not match :#{unit.name}")
94
+ end
95
+
96
+ member_keys(unit, arg(:keys), normalized: normalized?)
97
+ end
98
+
99
+ def normalized?
100
+ return false unless args.key?(:normalized)
101
+ raise Failure.new(:invalid, "normalized: must be true or false") unless [ true, false ].include?(arg(:normalized))
102
+ raise Failure.new(:invalid, "normalized: is for system actors only") if arg(:normalized) && !actor.is_a?(Actor)
103
+
104
+ arg(:normalized)
105
+ end
106
+ end
107
+
108
+ # Adds units (records or keys) to a flag's rule or a cohort, serving
109
+ # `value:` (a flag's value; on/off flags default to on, and cohort
110
+ # members always store "on", since the attachment decides what a cohort
111
+ # serves). Optional `expires_at:` (a future Time). Adding a unit that is
112
+ # already a member changes its value and expiry (the old row is kept,
113
+ # removed, for Restore).
114
+ class AddMembers < MembershipOperation
115
+ VERB = :members_added
116
+ arguments required: %i[keys], optional: %i[unit value expires_at normalized]
117
+
118
+ private
119
+
120
+ def change(owner, unit)
121
+ keys = unit_keys(unit)
122
+ value = member_value
123
+ expires_at = validate.expires_at!(arg(:expires_at), Time.now.utc)
124
+ counts = tx.upsert_members(owner, unit: unit.name, unit_keys: keys, value: value, expires_at: expires_at)
125
+ validate.members_count!(tx.count_members(owner, now: Time.now.utc), owner_name, config)
126
+ { unit: unit.name.to_s, value: value, expires_at: expires_at&.iso8601, requested: keys.size, **counts }
127
+ end
128
+
129
+ def member_value
130
+ if @cohort_key
131
+ raise Failure.new(:invalid, "cohort members serve the attachment's value; leave out value:") if args.key?(:value)
132
+
133
+ return "on"
134
+ end
135
+ unless args.key?(:value)
136
+ return "on" if definition.boolean?
137
+
138
+ raise Failure.new(:invalid, ":#{@key} is a #{definition.kind}; pass value:")
139
+ end
140
+ validate.value!(definition, arg(:value), "value")
141
+ end
142
+
143
+ def owner_name
144
+ @cohort_key ? "cohort #{@cohort_key.inspect}" : ":#{@key}"
145
+ end
146
+ end
147
+
148
+ # Removes units (records or keys) from a flag's rule or a cohort. The
149
+ # rows are kept, marked removed_at, until `flags:purge` deletes them
150
+ # after `config.membership_retention`.
151
+ class RemoveMembers < MembershipOperation
152
+ VERB = :members_removed
153
+ arguments required: %i[keys], optional: %i[unit normalized]
154
+
155
+ private
156
+
157
+ def change(owner, unit)
158
+ keys = unit_keys(unit)
159
+ removed = tx.remove_members(owner, unit: unit.name, unit_keys: keys)
160
+ { unit: unit.name.to_s, requested: keys.size, removed: removed }
161
+ end
162
+ end
163
+ end
164
+ end
@@ -0,0 +1,330 @@
1
+ require "json"
2
+ require "time"
3
+
4
+ module StandardFlags
5
+ module Operations
6
+ # Puts rules and memberships back as they were at a past time T (R16):
7
+ #
8
+ # StandardFlags::Operations::Restore.call(at: Time.utc(2026, 11, 20, 9), reason: "bad ramp") # dry run
9
+ # StandardFlags::Operations::Restore.call(at: ..., keys: %w[new_checkout], apply: true, reason: "bad ramp")
10
+ #
11
+ # * A rule's state at T is the after-state of its latest audit row at or
12
+ # before T, read through standard_audit's query API (the audit_logs
13
+ # table). Without standard_audit loaded it fails (:audit_unavailable).
14
+ # Only an audited state drives a change: a flag with no row at or
15
+ # before T (rows pruned by the audit log's retention, written before
16
+ # auditing was set up, or lost) is skipped, "no audit history at T;
17
+ # left unchanged", never treated as "no rule then".
18
+ # * Memberships at T come from the memberships table: rows created by T
19
+ # and not removed (or expired) by then. Removed rows are kept for
20
+ # `config.membership_retention`, so a T older than that is refused
21
+ # (:retention_exceeded).
22
+ #
23
+ # A dry run (the default) only plans: the Result's value lists each
24
+ # cohort and flag with the changes it would make, member changes as
25
+ # counts. `apply: true` writes each one's state at T as a whole, in one
26
+ # store write (RestoreTarget: one revision bump, one
27
+ # `standard_flags.flag.restored` or `standard_flags.cohort.restored`
28
+ # row), as `Actor.system("restore")`, with the reason "restore to T:
29
+ # <reason>". Nothing in between is ever served, and a target that fails
30
+ # is left as it was. Cohorts go first, so a flag that attaches one
31
+ # serves its members as they were. A flag's write expects the revision
32
+ # it was planned at, so a change made meanwhile stops that flag
33
+ # (:stale_revision) rather than being overwritten. Targets are
34
+ # independent: when some fail, the Result is a failure
35
+ # (:partial_failure) whose value still lists what was applied and what
36
+ # wasn't.
37
+ #
38
+ # Skipped, with a note: ENV-pinned flags, undeclared or tombstoned keys,
39
+ # flags with no audit history at T, and changes the operations don't
40
+ # make (un-stopping a rule, clearing a percentage, changing a rule's
41
+ # salt).
42
+ #
43
+ # Break-glass: run from `flags:restore` or a console, not from a request.
44
+ # It authorises as the system actor, so it is not exposed as an MCP tool.
45
+ class Restore
46
+ ACTOR = Actor.system("restore")
47
+ NO_HISTORY = "no audit history at T; left unchanged".freeze
48
+
49
+ # One target's planned write: change summaries, the rule columns to
50
+ # set, and member groups to remove and add (unit keys stay in here).
51
+ Plan = Data.define(:changes, :attributes, :remove, :add) do
52
+ def self.empty
53
+ new(changes: [], attributes: {}, remove: [], add: [])
54
+ end
55
+
56
+ def +(other)
57
+ Plan.new(changes: changes + other.changes, attributes: attributes.merge(other.attributes),
58
+ remove: remove + other.remove, add: add + other.add)
59
+ end
60
+ end
61
+
62
+ # One flag or cohort in the plan. `status` is "unchanged", "planned",
63
+ # "skipped", "applied" or "failed".
64
+ Entry = Data.define(:target, :status, :changes, :notes, :error) do
65
+ def to_h
66
+ { target: target, status: status, changes: changes, notes: notes, error: error }.compact
67
+ end
68
+ end
69
+
70
+ def self.call(at:, reason:, keys: nil, apply: false, registry: StandardFlags.registry, trail: nil, now: Time.now.utc)
71
+ new(at: at, reason: reason, keys: keys, apply: apply, registry: registry, trail: trail, now: now).call
72
+ end
73
+
74
+ def initialize(at:, reason:, keys:, apply:, registry:, trail:, now:)
75
+ @at = at
76
+ @reason = reason
77
+ @keys = keys
78
+ @apply = apply
79
+ @registry = registry
80
+ @trail = trail
81
+ @now = now
82
+ end
83
+
84
+ def call
85
+ check!
86
+ states = trail.rule_states(@at)
87
+ loaded = Runtime.store.load
88
+ entries = targets(states, loaded).map { |target| entry(target, states, loaded) }
89
+ report(entries)
90
+ rescue Failure => e
91
+ Result.failure(e.code, e.message)
92
+ rescue Runtime::StoreError => e
93
+ Reporting.report(e, operation: "restore")
94
+ Result.failure(:store_error, e.message)
95
+ end
96
+
97
+ private
98
+
99
+ attr_reader :registry
100
+
101
+ def check!
102
+ raise Failure.new(:invalid, "a reason is required") unless @reason.is_a?(String) && !@reason.strip.empty?
103
+ raise Failure.new(:invalid, "at: must be a Time") unless @at.is_a?(Time)
104
+ raise Failure.new(:invalid, "at: #{@at.utc.iso8601} is in the future") if @at > @now
105
+ raise Failure.new(:runtime_rules_off, "runtime rules are off; set config.runtime_rules = true first") unless Runtime.enabled?
106
+
107
+ oldest = @now - StandardFlags.config.membership_retention
108
+ if @at < oldest
109
+ raise Failure.new(:retention_exceeded, "at: #{@at.utc.iso8601} is older than config.membership_retention " \
110
+ "(#{oldest.utc.iso8601}); removed memberships before then may be purged")
111
+ end
112
+ return if @trail || StandardFlags::AuditTrail.available?
113
+
114
+ raise Failure.new(:audit_unavailable, "restore reads rule history from standard_audit's audit_logs, " \
115
+ "and standard_audit is not loaded")
116
+ end
117
+
118
+ def trail
119
+ @trail ||= StandardFlags::AuditTrail.new
120
+ end
121
+
122
+ # "cohort:<key>" Strings, then flag keys (Symbols): the ones asked for,
123
+ # else every cohort and every rule with history or a row. Cohorts go
124
+ # first, so their members are back before any flag that attaches them
125
+ # serves again.
126
+ def targets(states, loaded)
127
+ return Array(@keys).map { |key| target(key) }.uniq.partition { |t| t.is_a?(String) }.flatten(1) if @keys
128
+
129
+ loaded.cohorts.map { |cohort| "cohort:#{cohort.key}" }.sort + (states.keys + loaded.rules.map(&:key)).uniq.sort
130
+ end
131
+
132
+ def target(key)
133
+ key.to_s.start_with?("cohort:") ? key.to_s : key.to_s.to_sym
134
+ end
135
+
136
+ def entry(target, states, loaded)
137
+ return cohort_entry(target, loaded) if target.is_a?(String)
138
+
139
+ skip = skip_reason(target) || (NO_HISTORY unless states[target])
140
+ return Entry.new(target: target.to_s, status: "skipped", changes: [], notes: [ skip ], error: nil) if skip
141
+
142
+ rule = loaded.rules.find { |r| r.key == target }
143
+ past = plain(states[target])
144
+ notes = []
145
+ plan = rule_plan(target, past, rule, notes) + member_plan({ rule: target }, notes)
146
+ bucketing = { salt: past["salt"], hash_version: past["hash_version"] } unless rule
147
+ run(target, plan, notes, revision: rule&.lock_version, bucketing: bucketing)
148
+ end
149
+
150
+ def cohort_entry(target, loaded)
151
+ key = target.delete_prefix("cohort:")
152
+ unless loaded.cohorts.any? { |cohort| cohort.key == key }
153
+ return Entry.new(target: target, status: "skipped", changes: [], notes: [ "cohort does not exist now" ], error: nil)
154
+ end
155
+
156
+ notes = []
157
+ run(target, member_plan({ cohort: key }, notes), notes, revision: nil, bucketing: nil)
158
+ end
159
+
160
+ def skip_reason(key)
161
+ return "tombstoned flag" if registry.tombstoned?(key)
162
+
163
+ definition = registry[key]
164
+ return "undeclared flag" unless definition
165
+
166
+ pin = EnvPin.scan(definition, StandardFlags.config.env_source).pin
167
+ "pinned by #{pin.var}; skipped" if pin
168
+ end
169
+
170
+ # -- the rule -----------------------------------------------------------
171
+
172
+ def rule_plan(key, past, rule, notes)
173
+ current = plain((rule || Runtime::Rule.build(key: key, salt: past["salt"], hash_version: past["hash_version"])).audit_state)
174
+ notes << "bucketing (salt, hash version) differs and can't change; kept" if bucketing(past) != bucketing(current)
175
+ status_plan(past, current, notes) + conditions_plan(past, current) + ramp_plan(past, current, notes) +
176
+ variants_plan(past, current) + value_plan(past, current) + cohorts_plan(past, current)
177
+ end
178
+
179
+ def status_plan(past, current, notes)
180
+ from = current["status"]
181
+ to = past["status"]
182
+ stop = past["stop_value"]
183
+ return Plan.empty if from == to && (to != "stopped" || current["stop_value"] == stop)
184
+
185
+ if from == "stopped" && to != "stopped"
186
+ notes << "stopped now and #{to} then; operations can't un-stop a rule"
187
+ return Plan.empty
188
+ end
189
+
190
+ case to
191
+ when "running" then change("status #{from} → running", status: "running")
192
+ when "stopped" then change("status #{from} → stopped, serving #{stop}", status: "stopped", stop_value: stop)
193
+ else
194
+ return change("status running → paused", status: "paused") if from == "running"
195
+
196
+ notes << "draft and paused both serve the code default; left #{from}"
197
+ Plan.empty
198
+ end
199
+ end
200
+
201
+ def conditions_plan(past, current)
202
+ return Plan.empty if past["conditions"] == current["conditions"]
203
+
204
+ change("conditions #{json(current['conditions'])} → #{json(past['conditions'])}", conditions: past["conditions"])
205
+ end
206
+
207
+ def ramp_plan(past, current, notes)
208
+ bps = past["percentage_bps"]
209
+ return Plan.empty if bps == current["percentage_bps"] && past["rollout_value"] == current["rollout_value"]
210
+
211
+ if bps.nil?
212
+ notes << "no percentage then, #{current['percentage_bps']} bps now; operations can't clear a percentage, so it was kept"
213
+ return Plan.empty
214
+ end
215
+ # As Ramp: with no rollout value then, the current one stays.
216
+ rollout = past["rollout_value"].nil? ? current["rollout_value"] : past["rollout_value"]
217
+ change("percentage #{bps_text(current)} → #{bps_text(past)}", percentage_bps: bps, rollout_value: rollout)
218
+ end
219
+
220
+ def variants_plan(past, current)
221
+ return Plan.empty if past["variant_weights"] == current["variant_weights"]
222
+
223
+ change("variants #{json(current['variant_weights'])} → #{json(past['variant_weights'])}",
224
+ variant_weights: past["variant_weights"])
225
+ end
226
+
227
+ def value_plan(past, current)
228
+ return Plan.empty if past["fallthrough_value"] == current["fallthrough_value"]
229
+
230
+ change("fallthrough #{current['fallthrough_value'] || '-'} → #{past['fallthrough_value'] || '-'}",
231
+ fallthrough_value: past["fallthrough_value"])
232
+ end
233
+
234
+ # The attachments exactly as they were, order included.
235
+ def cohorts_plan(past, current)
236
+ return Plan.empty if past["cohorts"] == current["cohorts"]
237
+
238
+ before = current["cohorts"].to_h { |a| [ a["cohort"], a["value"] ] }
239
+ after = past["cohorts"].to_h { |a| [ a["cohort"], a["value"] ] }
240
+ summaries = (before.keys - after.keys).map { |cohort| "detach cohort #{cohort}" } +
241
+ after.reject { |cohort, value| before[cohort] == value }.map { |cohort, value| "attach cohort #{cohort} → #{value}" }
242
+ summaries << "cohort order #{before.keys.join(', ')} → #{after.keys.join(', ')}" if summaries.empty?
243
+ Plan.new(changes: summaries, attributes: { cohorts: past["cohorts"] }, remove: [], add: [])
244
+ end
245
+
246
+ # -- memberships -------------------------------------------------------
247
+
248
+ # Removes the members added since T, then adds those there at T (with
249
+ # their value and expiry). Unit keys stay inside the plan; summaries
250
+ # carry counts.
251
+ def member_plan(owner, notes)
252
+ past = Runtime.store.members_at(@at, **owner).to_h { |m| [ m.unit_key, m ] }
253
+ now = Runtime.store.members(**owner).memberships.select { |m| m.live?(@now) }.to_h { |m| [ m.unit_key, m ] }
254
+ expired, wanted = past.values.reject { |m| same?(now[m.unit_key], m) }.partition { |m| !m.live?(@now) }
255
+ gone = now.values.reject { |m| past.key?(m.unit_key) }
256
+ notes << "#{expired.size} member(s) expired since then; not restored" unless expired.empty?
257
+ remove_plan(gone) + add_plan(owner, wanted)
258
+ end
259
+
260
+ def same?(current, past)
261
+ current && current.value == past.value && current.expires_at&.to_i == past.expires_at&.to_i
262
+ end
263
+
264
+ def remove_plan(memberships)
265
+ memberships.group_by(&:unit).map do |unit, group|
266
+ Plan.new(changes: [ "members −#{group.size} (#{unit})" ], attributes: {},
267
+ remove: [ { unit: unit, keys: group.map(&:unit_key) } ], add: [])
268
+ end.reduce(Plan.empty, :+)
269
+ end
270
+
271
+ def add_plan(owner, memberships)
272
+ memberships.group_by { |m| [ m.unit, m.value, m.expires_at ] }.map do |(unit, value, expires_at), group|
273
+ Plan.new(changes: [ "members +#{group.size} (#{unit}#{" → #{value}" if owner[:rule]})" ], attributes: {}, remove: [],
274
+ add: [ { unit: unit, keys: group.map(&:unit_key), value: value, expires_at: expires_at } ])
275
+ end.reduce(Plan.empty, :+)
276
+ end
277
+
278
+ # -- running the plan --------------------------------------------------
279
+
280
+ # Plans, or with apply: writes, one target's state at T in one write.
281
+ def run(target, plan, notes, revision:, bucketing:)
282
+ name = target.to_s
283
+ return Entry.new(target: name, status: "unchanged", changes: [], notes: notes, error: nil) if plan.changes.empty?
284
+ return Entry.new(target: name, status: "planned", changes: plan.changes, notes: notes, error: nil) unless @apply
285
+
286
+ args = { attributes: plan.attributes, remove: plan.remove, add: plan.add, restored_to: @at.utc.iso8601 }
287
+ args[:bucketing] = bucketing if bucketing
288
+ result = RestoreTarget.call(target, actor: ACTOR, reason: "restore to #{@at.utc.iso8601}: #{@reason}",
289
+ expected_revision: revision, registry: registry, **args)
290
+ return Entry.new(target: name, status: "applied", changes: plan.changes, notes: notes, error: nil) if result.success?
291
+
292
+ Entry.new(target: name, status: "failed", changes: [], notes: notes + [ "nothing was changed; not applied: #{plan.changes.join('; ')}" ],
293
+ error: "#{result.code}: #{result.errors.join('; ')}")
294
+ end
295
+
296
+ def report(entries)
297
+ value = { at: @at.utc.iso8601, applied: @apply, entries: entries.map(&:to_h) }
298
+ failed = entries.select { |e| e.status == "failed" }
299
+ return Result.success(value) if failed.empty?
300
+
301
+ Result.new(success: false, value: value, code: :partial_failure,
302
+ errors: failed.map { |e| "#{e.target}: #{e.error}" })
303
+ end
304
+
305
+ # -- helpers -----------------------------------------------------------
306
+
307
+ def change(summary, **attributes)
308
+ Plan.new(changes: [ summary ], attributes: attributes, remove: [], add: [])
309
+ end
310
+
311
+ # String keys, JSON values: audit metadata and live state compare equal.
312
+ def plain(state)
313
+ JSON.parse(JSON.generate(state))
314
+ end
315
+
316
+ def bucketing(state)
317
+ state.values_at("salt", "hash_version")
318
+ end
319
+
320
+ def bps_text(state)
321
+ bps = state["percentage_bps"]
322
+ bps.nil? ? "-" : "#{bps} bps#{" → #{state['rollout_value']}" if state['rollout_value']}"
323
+ end
324
+
325
+ def json(value)
326
+ JSON.generate(value)
327
+ end
328
+ end
329
+ end
330
+ end
@@ -0,0 +1,197 @@
1
+ require "time"
2
+
3
+ module StandardFlags
4
+ module Operations
5
+ # Restore's write: one flag's rule (its settings, attached cohorts and
6
+ # direct members) or one cohort's members, put back as a whole in one
7
+ # store write, with one revision bump and one audit row
8
+ # (`standard_flags.flag.restored` or `standard_flags.cohort.restored`:
9
+ # the full state before and after, member changes as counts). Evaluators
10
+ # see the state before or the state after, never one in between, and a
11
+ # failure changes nothing.
12
+ #
13
+ # Inside the write, members are removed before any are added, so
14
+ # `config.max_members` is checked against the end state; the
15
+ # per-operation key limit doesn't apply (keys go to the store in chunks
16
+ # of it). Unit keys are the store's own (`normalized: true`), never
17
+ # passed through the unit's `key:` again.
18
+ #
19
+ # Its arguments are Restore's plan: `attributes:` (rule columns, in
20
+ # their stored form), `remove:` and `add:` (groups of unit keys, each
21
+ # `{ unit:, keys: }`, adds also `value:` and `expires_at:`),
22
+ # `bucketing:` (salt and hash version, for a rule created again) and
23
+ # `restored_to:` (T, ISO 8601). Only Restore calls it; it is not an MCP
24
+ # tool.
25
+ #
26
+ # @api private
27
+ class RestoreTarget < Base
28
+ include MemberKeys
29
+
30
+ STATUSES = %w[draft paused running stopped].freeze
31
+ ATTRIBUTES = %i[status stop_value conditions percentage_bps rollout_value variant_weights fallthrough_value cohorts].freeze
32
+
33
+ arguments optional: %i[attributes remove add bucketing restored_to]
34
+
35
+ def self.targets
36
+ %i[flag cohort]
37
+ end
38
+
39
+ def self.operation_name
40
+ "restore"
41
+ end
42
+
43
+ private
44
+
45
+ def event
46
+ (@cohort_key ? Events::COHORT_EVENTS : Events::FLAG_EVENTS)[:restored]
47
+ end
48
+
49
+ def sensitive?
50
+ true
51
+ end
52
+
53
+ def run
54
+ @cohort_key ? run_cohort : super
55
+ end
56
+
57
+ def attributes
58
+ (arg(:attributes) || {}).transform_keys(&:to_sym)
59
+ end
60
+
61
+ # A rule created again keeps the salt and hash version it had at T.
62
+ def bucketing
63
+ given = arg(:bucketing)
64
+ return super unless given
65
+
66
+ { salt: given[:salt], hash_version: given[:hash_version] }
67
+ end
68
+
69
+ # Every cohort the rule ends up attaching, so the check below can read
70
+ # them (locked after the rule, as every write does).
71
+ def extra_cohort_keys
72
+ (attributes[:cohorts] || @rule.cohorts).filter_map { |a| a["cohort"] if a.is_a?(Hash) }
73
+ end
74
+
75
+ # Members first (removals, then additions), then every column in one
76
+ # save. Base re-checks a running rule; any other is checked here, as
77
+ # the operations that set each column would have.
78
+ def perform
79
+ members = restore_members(@rule) { validate.unit!(definition, registry, "members") }
80
+ save!(rule_attributes)
81
+ validate.conditions_size!(@rule.conditions, config)
82
+ validate.rule!(definition, @rule, registry, @cohorts) unless @rule.running?
83
+ { restored_to: arg(:restored_to), members: members }
84
+ end
85
+
86
+ def rule_attributes
87
+ unknown = attributes.keys - ATTRIBUTES
88
+ raise Failure.new(:invalid, "unknown rule attribute(s): #{unknown.join(', ')}") unless unknown.empty?
89
+
90
+ attributes.to_h { |name, value| [ name, column(name, value) ] }.merge(full_since_for(attributes))
91
+ end
92
+
93
+ def column(name, value)
94
+ case name
95
+ when :status then status!(value)
96
+ when :conditions then conditions!(value)
97
+ when :percentage_bps then value.nil? ? nil : validate.bps!(value)
98
+ when :variant_weights then value.nil? || value.empty? ? {} : validate.weights!(definition, value)
99
+ when :cohorts then attachments!(value)
100
+ else value.nil? ? nil : validate.value!(definition, value, name.to_s)
101
+ end
102
+ end
103
+
104
+ def status!(status)
105
+ status = status.to_s
106
+ raise Failure.new(:invalid, "status #{status.inspect} is not one of #{STATUSES.join('/')}") unless STATUSES.include?(status)
107
+ raise Failure.new(:invalid, ":#{@key} is stopped; operations can't un-stop a rule") if @rule.stopped? && status != "stopped"
108
+
109
+ status
110
+ end
111
+
112
+ def conditions!(conditions)
113
+ raise Failure.new(:invalid, "conditions must be a Hash") unless conditions.is_a?(Hash)
114
+
115
+ conditions
116
+ end
117
+
118
+ def attachments!(attachments)
119
+ list = Array(attachments).map do |a|
120
+ a = a.to_h.transform_keys(&:to_s)
121
+ { "cohort" => a["cohort"].to_s, "value" => validate.value!(definition, a["value"], "cohort #{a['cohort']}'s value") }
122
+ end
123
+ if list.size > config.max_cohorts_per_rule
124
+ raise Failure.new(:limit_exceeded, ":#{@key} would have #{list.size} cohorts; the limit is #{config.max_cohorts_per_rule}")
125
+ end
126
+
127
+ list
128
+ end
129
+
130
+ # As Ramp sets it: reaching 10,000 keeps (or starts) full_since.
131
+ def full_since_for(attributes)
132
+ return {} unless attributes.key?(:percentage_bps)
133
+
134
+ { full_since: attributes[:percentage_bps] == Bucket::BUCKETS ? (@rule.full_since || Time.now.utc) : nil }
135
+ end
136
+
137
+ # Locks the cohort, then its memberships, then (last, as every write
138
+ # does) the state row for the revision check.
139
+ def run_cohort
140
+ cohort = tx.lock_cohort(@cohort_key)
141
+ raise Failure.new(:invalid, "cohort #{@cohort_key.inspect} does not exist") unless cohort
142
+ raise Failure.new(:invalid, "cohort #{@cohort_key.inspect} is archived") if cohort.archived? && groups(:add).any?
143
+
144
+ before = cohort.audit_state
145
+ members = restore_members(cohort) do
146
+ registry.units[cohort.unit] ||
147
+ raise(Failure.new(:invalid, "cohort #{@cohort_key.inspect} holds :#{cohort.unit}, which is not declared"))
148
+ end
149
+ cohort = tx.save_cohort(cohort, {})
150
+ check_revision!(tx.lock_revision)
151
+ revision = Runtime.bump_revision!(tx)
152
+ extra = { restored_to: arg(:restored_to), members: members }
153
+ publish(event, { cohort: @cohort_key, before: before, after: cohort.audit_state,
154
+ revision: revision, store_revision: revision, **extra })
155
+ { cohort: @cohort_key, state: cohort.audit_state, revision: revision, store_revision: revision, **extra }
156
+ end
157
+
158
+ # Removals, then additions, then the limit on the end state. Yields
159
+ # for the owner's unit only when there are members to change.
160
+ def restore_members(owner)
161
+ counts = { removed: 0, added: 0, updated: 0 }
162
+ return counts if groups(:remove).empty? && groups(:add).empty?
163
+
164
+ unit = yield
165
+ groups(:remove).each do |group|
166
+ chunks(unit, group).each { |keys| counts[:removed] += tx.remove_members(owner, unit: unit.name, unit_keys: keys) }
167
+ end
168
+ groups(:add).each do |group|
169
+ value = @cohort_key ? "on" : validate.value!(definition, group[:value], "value")
170
+ expires_at = validate.expires_at!(group[:expires_at], Time.now.utc)
171
+ chunks(unit, group).each do |keys|
172
+ tx.upsert_members(owner, unit: unit.name, unit_keys: keys, value: value, expires_at: expires_at)
173
+ .each { |name, count| counts[name] += count }
174
+ end
175
+ end
176
+ validate.members_count!(tx.count_members(owner, now: Time.now.utc), owner_name, config) if groups(:add).any?
177
+ counts
178
+ end
179
+
180
+ def groups(name)
181
+ Array(arg(name)).map { |group| group.to_h.transform_keys(&:to_sym) }
182
+ end
183
+
184
+ def chunks(unit, group)
185
+ if group[:unit].to_s != unit.name.to_s
186
+ raise Failure.new(:invalid, "unit: #{group[:unit].inspect} does not match :#{unit.name}")
187
+ end
188
+
189
+ member_keys(unit, group[:keys], normalized: true, limit: false).each_slice(config.max_keys_per_operation)
190
+ end
191
+
192
+ def owner_name
193
+ @cohort_key ? "cohort #{@cohort_key.inspect}" : ":#{@key}"
194
+ end
195
+ end
196
+ end
197
+ end