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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +229 -0
- data/README.md +837 -33
- data/lib/generators/standard_flags/admin/admin_generator.rb +115 -0
- data/lib/generators/standard_flags/admin/templates/controller.rb.tt +103 -0
- data/lib/generators/standard_flags/admin/templates/index.tsx.tt +64 -0
- data/lib/generators/standard_flags/admin/templates/show.tsx.tt +275 -0
- data/lib/generators/standard_flags/install/install_generator.rb +16 -1
- data/lib/generators/standard_flags/install/templates/flags.rb.tt +3 -2
- data/lib/generators/standard_flags/install/templates/initializer.rb.tt +10 -0
- data/lib/generators/standard_flags/migrations/migrations_generator.rb +57 -0
- data/lib/generators/standard_flags/migrations/templates/create_standard_flags_tables.rb.tt +78 -0
- data/lib/standard_flags/actor.rb +50 -0
- data/lib/standard_flags/audit_trail.rb +56 -0
- data/lib/standard_flags/config.rb +78 -0
- data/lib/standard_flags/context.rb +5 -1
- data/lib/standard_flags/definition.rb +85 -13
- data/lib/standard_flags/diagnostics.rb +35 -3
- data/lib/standard_flags/engine.rb +10 -2
- data/lib/standard_flags/env_pin.rb +15 -4
- data/lib/standard_flags/errors.rb +4 -0
- data/lib/standard_flags/evaluation.rb +5 -4
- data/lib/standard_flags/evaluator.rb +14 -1
- data/lib/standard_flags/events.rb +49 -0
- data/lib/standard_flags/health_check.rb +12 -2
- data/lib/standard_flags/health_contribution.rb +65 -0
- data/lib/standard_flags/mcp/cohorts.rb +65 -0
- data/lib/standard_flags/mcp/flags.rb +143 -0
- data/lib/standard_flags/mcp/members.rb +154 -0
- data/lib/standard_flags/mcp/writes.rb +98 -0
- data/lib/standard_flags/mcp.rb +238 -0
- data/lib/standard_flags/memo.rb +15 -1
- data/lib/standard_flags/notifiers/logger.rb +14 -0
- data/lib/standard_flags/open_feature/provider.rb +232 -0
- data/lib/standard_flags/open_feature.rb +26 -0
- data/lib/standard_flags/operations/audit.rb +218 -0
- data/lib/standard_flags/operations/base.rb +290 -0
- data/lib/standard_flags/operations/cohorts.rb +80 -0
- data/lib/standard_flags/operations/failure.rb +16 -0
- data/lib/standard_flags/operations/members.rb +164 -0
- data/lib/standard_flags/operations/restore.rb +330 -0
- data/lib/standard_flags/operations/restore_target.rb +197 -0
- data/lib/standard_flags/operations/rules.rb +233 -0
- data/lib/standard_flags/operations/validation.rb +154 -0
- data/lib/standard_flags/operations.rb +43 -0
- data/lib/standard_flags/parser.rb +16 -0
- data/lib/standard_flags/purge_job.rb +14 -0
- data/lib/standard_flags/registry.rb +38 -5
- data/lib/standard_flags/reporting.rb +51 -7
- data/lib/standard_flags/resolvers.rb +14 -7
- data/lib/standard_flags/result.rb +43 -0
- data/lib/standard_flags/rspec.rb +67 -13
- data/lib/standard_flags/runtime/active_record_store.rb +428 -0
- data/lib/standard_flags/runtime/cache.rb +98 -0
- data/lib/standard_flags/runtime/evaluation_tracker.rb +93 -0
- data/lib/standard_flags/runtime/memory_store.rb +408 -0
- data/lib/standard_flags/runtime/models.rb +43 -0
- data/lib/standard_flags/runtime/resolver.rb +256 -0
- data/lib/standard_flags/runtime/rule_snapshot.rb +60 -0
- data/lib/standard_flags/runtime/store.rb +161 -0
- data/lib/standard_flags/runtime/values.rb +181 -0
- data/lib/standard_flags/runtime.rb +266 -0
- data/lib/standard_flags/sensor.rb +12 -5
- data/lib/standard_flags/subscribers.rb +6 -0
- data/lib/standard_flags/testing.rb +100 -1
- data/lib/standard_flags/tooling/changes.rb +196 -0
- data/lib/standard_flags/tooling.rb +232 -19
- data/lib/standard_flags/version.rb +1 -1
- data/lib/standard_flags.rb +33 -5
- data/lib/tasks/standard_flags.rake +45 -1
- metadata +41 -1
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
require "standard_flags/runtime/values"
|
|
2
|
+
require "standard_flags/runtime/rule_snapshot"
|
|
3
|
+
require "standard_flags/runtime/store"
|
|
4
|
+
require "standard_flags/runtime/memory_store"
|
|
5
|
+
require "standard_flags/runtime/evaluation_tracker"
|
|
6
|
+
require "standard_flags/runtime/cache"
|
|
7
|
+
require "standard_flags/runtime/resolver"
|
|
8
|
+
|
|
9
|
+
module StandardFlags
|
|
10
|
+
# Runtime rules: per-flag rules stored in the app's own database, read
|
|
11
|
+
# between the ENV pin and the code default. Opt in with
|
|
12
|
+
# `config.runtime_rules = true` after running the migrations generator.
|
|
13
|
+
#
|
|
14
|
+
# Nothing here touches ActiveRecord unless runtime rules are on and no
|
|
15
|
+
# other store is configured; the ActiveRecord store and its models are
|
|
16
|
+
# required only then.
|
|
17
|
+
module Runtime
|
|
18
|
+
MEMBERSHIPS_MEMO = :standard_flags_runtime_memberships
|
|
19
|
+
SNAPSHOT_MEMO = :standard_flags_runtime_snapshot
|
|
20
|
+
|
|
21
|
+
# What `memberships` returns, and memoises for the rest of the unit of
|
|
22
|
+
# work, when the lookup failed.
|
|
23
|
+
LOOKUP_FAILED = Object.new.tap { |o| def o.inspect = "#<StandardFlags::Runtime::LOOKUP_FAILED>" }.freeze
|
|
24
|
+
|
|
25
|
+
# Stands in for a unit key whose `from:` or `key:` raised.
|
|
26
|
+
UNRESOLVED = Object.new.tap { |o| def o.inspect = "#<StandardFlags::Runtime::UNRESOLVED>" }.freeze
|
|
27
|
+
|
|
28
|
+
class << self
|
|
29
|
+
# A monotonic clock for refresh intervals (specs only).
|
|
30
|
+
# @api private
|
|
31
|
+
attr_writer :clock
|
|
32
|
+
|
|
33
|
+
# On when the app turned runtime rules on, or a spec used `with_rule`
|
|
34
|
+
# and friends.
|
|
35
|
+
def enabled?
|
|
36
|
+
!test_store.nil? || StandardFlags.config.runtime_rules == true
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def store
|
|
40
|
+
test_store || StandardFlags.config.runtime_store || default_store
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# The process cache for the current store. Test stores are checked on
|
|
44
|
+
# every evaluation; in-memory revision checks cost nothing.
|
|
45
|
+
def cache
|
|
46
|
+
current = store
|
|
47
|
+
@cache = nil unless @cache&.store.equal?(current)
|
|
48
|
+
@cache ||= Cache.new(current, interval: current.equal?(test_store) ? 0 : nil, clock: method(:now))
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# The rules snapshot. Inside a unit of work the first call pins it, so
|
|
52
|
+
# every evaluation in that request or job sees one revision; outside
|
|
53
|
+
# one, each call reads the process cache.
|
|
54
|
+
def snapshot
|
|
55
|
+
current = cache
|
|
56
|
+
Memo.fetch([ SNAPSHOT_MEMO, current ]) { current.snapshot }
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# The flag's unit key in `context`, through the unit's `from:` and
|
|
60
|
+
# `key:`; nil when the flag has no unit or the context has no actor for
|
|
61
|
+
# it. A `from:` like `->(ctx) { ctx.account }` on a context without an
|
|
62
|
+
# account reads as no actor; anything else a host lambda raises
|
|
63
|
+
# propagates.
|
|
64
|
+
def unit_key(registry, definition, context)
|
|
65
|
+
return nil unless definition.unit
|
|
66
|
+
|
|
67
|
+
registry.units[definition.unit]&.key_from(context)
|
|
68
|
+
rescue NoMethodError => e
|
|
69
|
+
raise unless e.receiver.equal?(context)
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# Moves the stored revision on inside a write (`tx` is the store's
|
|
73
|
+
# transaction) and returns it. Every write calls this; stores take the
|
|
74
|
+
# number from a sequence, so it is never reused after a rollback.
|
|
75
|
+
def bump_revision!(tx)
|
|
76
|
+
tx.bump_revision
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# See Cache#expire!.
|
|
80
|
+
def expire!
|
|
81
|
+
@cache&.expire!
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# Which flags this process evaluated, for last_evaluated_at.
|
|
85
|
+
def tracker
|
|
86
|
+
@tracker ||= EvaluationTracker.new
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# Called by Memo::Hook when a unit of work ends, after its evaluations:
|
|
90
|
+
# flushes the EvaluationTracker if it is due (at most once per
|
|
91
|
+
# `config.evaluation_tracking_interval` per process). Never raises.
|
|
92
|
+
def unit_of_work_complete!
|
|
93
|
+
@tracker&.flush(store, now) if enabled?
|
|
94
|
+
rescue StandardError
|
|
95
|
+
nil
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
# Live memberships of one unit key across every rule and cohort: one
|
|
99
|
+
# store read per unit key per unit of work, memoised through Memo. A
|
|
100
|
+
# failed read is reported once and memoised as LOOKUP_FAILED, so an
|
|
101
|
+
# outage costs one failed query per unit per unit of work.
|
|
102
|
+
def memberships(unit, unit_key)
|
|
103
|
+
Memo.fetch([ MEMBERSHIPS_MEMO, unit, unit_key ]) do
|
|
104
|
+
store.memberships(unit, [ unit_key ]).freeze
|
|
105
|
+
rescue StandardError => e
|
|
106
|
+
read_failed(:memberships, e)
|
|
107
|
+
LOOKUP_FAILED
|
|
108
|
+
end
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
# Fills the memo for many units of one kind with a single read, so a
|
|
112
|
+
# loop over records doesn't run one membership query per record.
|
|
113
|
+
# Returns the number of keys read (0 when nothing needed reading).
|
|
114
|
+
#
|
|
115
|
+
# Never raises for a store error or a raising `key:`: it reports once
|
|
116
|
+
# and returns 0 without memoising, and each evaluation then reads (or
|
|
117
|
+
# fails) on its own.
|
|
118
|
+
def preload(unit, records_or_keys, registry: StandardFlags.registry)
|
|
119
|
+
return 0 unless enabled? && Memo.active?
|
|
120
|
+
|
|
121
|
+
unit = unit.to_sym
|
|
122
|
+
declared = registry.units[unit]
|
|
123
|
+
raise ArgumentError, "unknown unit :#{unit}" unless declared
|
|
124
|
+
|
|
125
|
+
preload_keys(declared, unit, records_or_keys, registry)
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# The state of the runtime layer, for diagnostics and the health check.
|
|
129
|
+
# `ready` is false only when the store answered that its tables are
|
|
130
|
+
# missing; `unreachable` names the error class when it couldn't answer.
|
|
131
|
+
def status(registry: StandardFlags.registry)
|
|
132
|
+
snapshot = self.snapshot
|
|
133
|
+
readiness = self.readiness
|
|
134
|
+
{
|
|
135
|
+
enabled: true,
|
|
136
|
+
store: store.class.name,
|
|
137
|
+
ready: readiness == true,
|
|
138
|
+
unreachable: (readiness unless readiness == true || readiness == false),
|
|
139
|
+
warnings: store_warnings,
|
|
140
|
+
loaded: snapshot.loaded,
|
|
141
|
+
stale: snapshot.stale,
|
|
142
|
+
revision: snapshot.revision,
|
|
143
|
+
age: snapshot.age,
|
|
144
|
+
loaded_at: snapshot.loaded_at&.iso8601,
|
|
145
|
+
rules: snapshot.rules.values.sort_by(&:key).map { |rule| rule_status(registry, rule) }
|
|
146
|
+
}
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
# Hard-deletes memberships removed or expired more than
|
|
150
|
+
# `config.membership_retention` ago. Returns `{ removed:, expired: }`.
|
|
151
|
+
# Run by `flags:purge` and StandardFlags::PurgeJob.
|
|
152
|
+
def purge!(before: Time.now.utc - StandardFlags.config.membership_retention)
|
|
153
|
+
counts = store.purge(before: before)
|
|
154
|
+
Reporting.instrument(:purge, **counts, before: before.utc.iso8601)
|
|
155
|
+
expire!
|
|
156
|
+
counts
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
# Whether the store's tables exist. Never raises: false when they are
|
|
160
|
+
# missing or the store can't be reached.
|
|
161
|
+
def ready?
|
|
162
|
+
readiness == true
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
# true, false (tables missing), or the class name of the error that
|
|
166
|
+
# stopped the store from answering. Never raises.
|
|
167
|
+
def readiness
|
|
168
|
+
store.ready? ? true : false
|
|
169
|
+
rescue StandardError => e
|
|
170
|
+
(e.cause_class if e.is_a?(StoreError)) || e.class.name
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
# Called by the engine after boot. With runtime rules on, adds
|
|
174
|
+
# `unit_key` to ActiveRecord::Base's filter once ActiveRecord loads, and
|
|
175
|
+
# loads the ActiveRecord store when it will be used, so the first
|
|
176
|
+
# request doesn't pay for the require. With them off, does nothing.
|
|
177
|
+
def boot!
|
|
178
|
+
return unless StandardFlags.config.runtime_rules == true
|
|
179
|
+
|
|
180
|
+
ActiveSupport.on_load(:active_record) { StandardFlags::Runtime.filter_unit_keys!(self) }
|
|
181
|
+
default_store if StandardFlags.config.runtime_store.nil?
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
# Adds `unit_key` to `base.filter_attributes` (ActiveRecord::Base),
|
|
185
|
+
# which SQL logs filter binds through. Global, so the name is narrow;
|
|
186
|
+
# idempotent.
|
|
187
|
+
def filter_unit_keys!(base)
|
|
188
|
+
current = base.filter_attributes
|
|
189
|
+
base.filter_attributes = current + [ :unit_key ] unless current.any? { |f| f.to_s == "unit_key" }
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
# Drops the cache (the default store and its loaded models stay).
|
|
193
|
+
def reset!
|
|
194
|
+
@cache = nil
|
|
195
|
+
@clock = nil
|
|
196
|
+
@tracker = nil
|
|
197
|
+
end
|
|
198
|
+
|
|
199
|
+
# The stored string for a Ruby value: true/false become "on"/"off".
|
|
200
|
+
def wire(value)
|
|
201
|
+
case value
|
|
202
|
+
when nil then nil
|
|
203
|
+
when true then "on"
|
|
204
|
+
when false then "off"
|
|
205
|
+
else value.to_s
|
|
206
|
+
end
|
|
207
|
+
end
|
|
208
|
+
|
|
209
|
+
private
|
|
210
|
+
|
|
211
|
+
def now
|
|
212
|
+
@clock ? @clock.call : Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
213
|
+
end
|
|
214
|
+
|
|
215
|
+
def test_store
|
|
216
|
+
Testing.runtime_store if Testing.active?
|
|
217
|
+
end
|
|
218
|
+
|
|
219
|
+
def default_store
|
|
220
|
+
@default_store ||= begin
|
|
221
|
+
require "standard_flags/runtime/active_record_store"
|
|
222
|
+
ActiveRecordStore.new
|
|
223
|
+
end
|
|
224
|
+
end
|
|
225
|
+
|
|
226
|
+
def preload_keys(declared, unit, records_or_keys, registry)
|
|
227
|
+
keys = Array(records_or_keys).filter_map { |item| declared.key_for(item) }.uniq
|
|
228
|
+
keys.reject! { |key| Memo.key?([ MEMBERSHIPS_MEMO, unit, key ]) }
|
|
229
|
+
return 0 if keys.empty? || !snapshot.member_rules?(registry, unit)
|
|
230
|
+
|
|
231
|
+
found = store.memberships(unit, keys).group_by(&:unit_key)
|
|
232
|
+
keys.each { |key| Memo.write([ MEMBERSHIPS_MEMO, unit, key ], (found[key] || []).freeze) }
|
|
233
|
+
keys.size
|
|
234
|
+
rescue StandardError => e
|
|
235
|
+
read_failed(:preload, e)
|
|
236
|
+
0
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
# Reports a failed read once per kind and error class. A store's own
|
|
240
|
+
# StoreError is already free of unit keys; anything else (a host
|
|
241
|
+
# `key:` lambda, say) is reported by class only, since its message
|
|
242
|
+
# could quote one.
|
|
243
|
+
def read_failed(kind, error)
|
|
244
|
+
name = (error.cause_class if error.is_a?(StoreError)) || error.class.name
|
|
245
|
+
Reporting.once(:runtime_read, kind, name) do
|
|
246
|
+
safe = error.is_a?(StoreError) ? error : StoreError.new("#{kind} failed: #{error.class}", cause_class: name)
|
|
247
|
+
Reporting.report(safe, runtime: kind.to_s)
|
|
248
|
+
end
|
|
249
|
+
end
|
|
250
|
+
|
|
251
|
+
def store_warnings
|
|
252
|
+
Array(store.warnings)
|
|
253
|
+
rescue StandardError
|
|
254
|
+
[]
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
def rule_status(registry, rule)
|
|
258
|
+
orphan = if registry.tombstoned?(rule.key) then :tombstoned
|
|
259
|
+
elsif !registry.key?(rule.key) then :undeclared
|
|
260
|
+
end
|
|
261
|
+
{ key: rule.key, status: rule.status, percentage_bps: rule.percentage_bps, member_count: rule.member_count,
|
|
262
|
+
cohorts: rule.cohort_attachments.map(&:first), orphan: orphan }
|
|
263
|
+
end
|
|
264
|
+
end
|
|
265
|
+
end
|
|
266
|
+
end
|
|
@@ -9,19 +9,26 @@ module StandardFlags
|
|
|
9
9
|
# * off — neither block runs; returns nil.
|
|
10
10
|
# * sensor — observe runs and its result goes into a `sensor.standard_flags`
|
|
11
11
|
# notification; returns the observation. An exception in observe
|
|
12
|
-
# is
|
|
13
|
-
#
|
|
12
|
+
# is swallowed, because sensor mode must not change behaviour,
|
|
13
|
+
# and reported unless `report: false` (for probes whose errors
|
|
14
|
+
# are expected; the notification still carries the error class).
|
|
14
15
|
# * on — observe runs, the notification fires, then enforce receives
|
|
15
16
|
# the observation; returns enforce's result. Exceptions propagate.
|
|
16
17
|
class Sensor
|
|
17
18
|
VALUES = Definition::PRESETS.fetch(:sensor)
|
|
18
19
|
|
|
19
|
-
def self.run(reader, key)
|
|
20
|
-
|
|
20
|
+
def self.run(reader, key, report: true)
|
|
21
|
+
raise ArgumentError, "report: must be true or false" unless [ true, false ].include?(report)
|
|
22
|
+
|
|
23
|
+
sensor = new(report: report)
|
|
21
24
|
yield sensor
|
|
22
25
|
sensor.call(reader, key)
|
|
23
26
|
end
|
|
24
27
|
|
|
28
|
+
def initialize(report: true)
|
|
29
|
+
@report = report
|
|
30
|
+
end
|
|
31
|
+
|
|
25
32
|
def observe(&block)
|
|
26
33
|
@observe = block
|
|
27
34
|
end
|
|
@@ -59,7 +66,7 @@ module StandardFlags
|
|
|
59
66
|
notify(key, :sensor, observed)
|
|
60
67
|
observed
|
|
61
68
|
rescue StandardError => e
|
|
62
|
-
Reporting.report(e, flag: key.to_s, mode: "sensor")
|
|
69
|
+
Reporting.report(e, flag: key.to_s, mode: "sensor") if @report
|
|
63
70
|
notify(key, :sensor, nil, e)
|
|
64
71
|
nil
|
|
65
72
|
end
|
|
@@ -9,6 +9,12 @@ module StandardFlags
|
|
|
9
9
|
# * pin_rejected.standard_flags — an ENV pin that didn't parse
|
|
10
10
|
# * forbidden.standard_flags — a `forbidden_in` flag pinned on
|
|
11
11
|
# * legacy_env.standard_flags — a legacy env name in use
|
|
12
|
+
# * runtime_refresh.standard_flags — runtime rules reloaded
|
|
13
|
+
# * runtime_stale.standard_flags — a runtime refresh failed; the
|
|
14
|
+
# last good rules keep serving
|
|
15
|
+
# * rule_invalid.standard_flags — a stored rule its flag can't serve
|
|
16
|
+
# * targeting_key_missing.standard_flags — a rule needs a unit key the
|
|
17
|
+
# context doesn't have
|
|
12
18
|
#
|
|
13
19
|
# @api private
|
|
14
20
|
class Subscribers
|
|
@@ -7,6 +7,7 @@ module StandardFlags
|
|
|
7
7
|
|
|
8
8
|
@overrides = {}
|
|
9
9
|
@active = false
|
|
10
|
+
@runtime_store = nil
|
|
10
11
|
|
|
11
12
|
class << self
|
|
12
13
|
def activate!
|
|
@@ -49,15 +50,113 @@ module StandardFlags
|
|
|
49
50
|
@overrides
|
|
50
51
|
end
|
|
51
52
|
|
|
52
|
-
#
|
|
53
|
+
# The in-memory runtime store behind `rule`, `members` and `cohort`, or
|
|
54
|
+
# nil when the example set none. While set, runtime rules are on and
|
|
55
|
+
# read from it, whatever the app's own runtime configuration.
|
|
56
|
+
def runtime_store
|
|
57
|
+
@runtime_store
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# Stores a runtime rule for a declared flag. Takes Ruby values:
|
|
61
|
+
#
|
|
62
|
+
# Testing.rule(:new_checkout, percentage: 5_000) # running, 50%
|
|
63
|
+
# Testing.rule(:strict_gates, fallthrough: :sensor)
|
|
64
|
+
# Testing.rule(:home_hero, variants: { "control" => 5_000, "savings" => 5_000 })
|
|
65
|
+
# Testing.rule(:new_checkout, status: :stopped, stop: true)
|
|
66
|
+
# Testing.rule(:new_checkout, cohorts: { staff: true }, platforms: %w[ios], versions: { ios: ">= 2.0" })
|
|
67
|
+
#
|
|
68
|
+
# The salt and hash version default to the flag's `bucketing:` or to
|
|
69
|
+
# (key, 2).
|
|
70
|
+
def rule(key, status: :running, percentage: nil, rollout: nil, variants: nil, fallthrough: nil, stop: nil,
|
|
71
|
+
cohorts: nil, segments: nil, platforms: nil, versions: nil, salt: nil, hash_version: nil)
|
|
72
|
+
definition = definition_for(key, nil)
|
|
73
|
+
conditions = { "segments" => segment_list(segments), "platforms" => platforms&.map(&:to_s),
|
|
74
|
+
"versions" => versions&.to_h { |platform, range| [ platform.to_s, range.to_s ] } }.compact
|
|
75
|
+
attributes = {
|
|
76
|
+
status: status, percentage_bps: percentage, rollout_value: rollout, variant_weights: variants || {},
|
|
77
|
+
fallthrough_value: fallthrough, stop_value: stop, conditions: conditions, cohorts: cohorts || [],
|
|
78
|
+
salt: salt || definition.bucketing&.salt || definition.key.to_s,
|
|
79
|
+
hash_version: hash_version || definition.bucketing&.version || 2
|
|
80
|
+
}
|
|
81
|
+
check_rule_values!(definition, rollout, fallthrough, stop, variants&.keys, cohorts, segments)
|
|
82
|
+
runtime_test_store.put_rule(definition.key, **attributes).tap { Memo.clear! }
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
# Adds units (records or keys) as direct members of a flag's rule,
|
|
86
|
+
# serving `value`. Creates a running rule with no other settings if
|
|
87
|
+
# there is none yet.
|
|
88
|
+
def members(key, units, value: true, expires_at: nil)
|
|
89
|
+
definition = definition_for(key, nil)
|
|
90
|
+
unit = unit_for(definition)
|
|
91
|
+
value = cast(definition, value)
|
|
92
|
+
rule(key) unless runtime_test_store.rule(definition.key)
|
|
93
|
+
unit_keys(unit, units).each do |unit_key|
|
|
94
|
+
runtime_test_store.add_member(rule: definition.key, unit: unit.name, unit_key: unit_key,
|
|
95
|
+
value: Runtime.wire(value), expires_at: expires_at)
|
|
96
|
+
end
|
|
97
|
+
Memo.clear!
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# Defines a cohort of one unit with these members (records or keys).
|
|
101
|
+
# Attach it with `rule(key, cohorts: { cohort_key => value })`.
|
|
102
|
+
def cohort(key, unit:, members: [], expires_at: nil, archived: false)
|
|
103
|
+
declared = StandardFlags.registry.units[unit.to_sym]
|
|
104
|
+
raise ArgumentError, "unknown unit :#{unit}" unless declared
|
|
105
|
+
|
|
106
|
+
store = runtime_test_store
|
|
107
|
+
store.put_cohort(key, unit: declared.name, archived_at: archived ? Time.now : nil)
|
|
108
|
+
unit_keys(declared, members).each do |unit_key|
|
|
109
|
+
store.add_member(cohort: key, unit: declared.name, unit_key: unit_key, value: "on", expires_at: expires_at)
|
|
110
|
+
end
|
|
111
|
+
Memo.clear!
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# Clears overrides, runtime test rules, the once-per-process report
|
|
115
|
+
# memory and the memo.
|
|
53
116
|
def reset!
|
|
54
117
|
@overrides = {}.freeze
|
|
118
|
+
@runtime_store = nil
|
|
119
|
+
Runtime.reset!
|
|
55
120
|
Reporting.reset!
|
|
56
121
|
Memo.clear!
|
|
57
122
|
end
|
|
58
123
|
|
|
59
124
|
private
|
|
60
125
|
|
|
126
|
+
def runtime_test_store
|
|
127
|
+
@runtime_store ||= Runtime::MemoryStore.new
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
def unit_for(definition)
|
|
131
|
+
unit = definition.unit && StandardFlags.registry.units[definition.unit]
|
|
132
|
+
raise ArgumentError, "flag :#{definition.key} has no unit: to target" unless unit
|
|
133
|
+
|
|
134
|
+
unit
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def unit_keys(unit, units)
|
|
138
|
+
units = [ units ] unless units.is_a?(Array)
|
|
139
|
+
units.map do |item|
|
|
140
|
+
unit.key_for(item) || raise(ArgumentError, "#{item.inspect} has no key for unit :#{unit.name}")
|
|
141
|
+
end
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
def segment_list(segments)
|
|
145
|
+
return nil if segments.nil?
|
|
146
|
+
|
|
147
|
+
segments.map { |name, value| { "name" => name.to_s, "value" => Runtime.wire(value) } }
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
# Every value a test rule serves must be one the flag can take, so a
|
|
151
|
+
# typo fails the spec. (Put invalid rows on a MemoryStore directly to
|
|
152
|
+
# test PARSE_ERROR.)
|
|
153
|
+
def check_rule_values!(definition, rollout, fallthrough, stop, variants, cohorts, segments)
|
|
154
|
+
served = [ rollout, fallthrough, stop ] + Array(variants)
|
|
155
|
+
served += cohorts.is_a?(Hash) ? cohorts.values : Array(cohorts).map { |a| a.to_h.transform_keys(&:to_s)["value"] }
|
|
156
|
+
served += Array(segments).map(&:last)
|
|
157
|
+
served.compact.each { |value| cast(definition, value) }
|
|
158
|
+
end
|
|
159
|
+
|
|
61
160
|
def definition_for(key, kind)
|
|
62
161
|
definition = StandardFlags.registry[key]
|
|
63
162
|
raise UnknownFlag, "cannot override unknown flag :#{key}" unless definition
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
module StandardFlags
|
|
2
|
+
module Tooling
|
|
3
|
+
# `flags:show KEY=`: one flag's declaration, its value here, any ENV pin,
|
|
4
|
+
# and its stored rule (read fresh from the store, not the cache).
|
|
5
|
+
# `KEY=cohort:<key>` shows a cohort.
|
|
6
|
+
class Show
|
|
7
|
+
def initialize(key, registry: StandardFlags.registry, store: nil)
|
|
8
|
+
@key = key.to_s
|
|
9
|
+
@registry = registry
|
|
10
|
+
@store = store
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
def render
|
|
14
|
+
return cohort_lines.join("\n") if @key.start_with?("cohort:")
|
|
15
|
+
|
|
16
|
+
definition = @registry[@key]
|
|
17
|
+
return "unknown flag :#{@key}" unless definition
|
|
18
|
+
|
|
19
|
+
evaluation = Evaluator.evaluate(@registry, definition.key, Context.empty)
|
|
20
|
+
lines = [ "#{definition.key} (#{definition.kind}, owner: #{definition.owner}#{", unit: #{definition.unit}" if definition.unit})",
|
|
21
|
+
" value here: #{evaluation.value.inspect} (#{evaluation.reason}#{", #{evaluation.rule_id}" if evaluation.rule_id})" ]
|
|
22
|
+
pin = EnvPin.scan(definition, StandardFlags.config.env_source).pin
|
|
23
|
+
lines << " pinned by #{pin.var}: operations refuse to change it" if pin
|
|
24
|
+
lines.concat(rule_lines(definition)).join("\n")
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
private
|
|
28
|
+
|
|
29
|
+
def store
|
|
30
|
+
@store || Runtime.store
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def rule_lines(definition)
|
|
34
|
+
return [ " runtime rules are off" ] unless Runtime.enabled?
|
|
35
|
+
|
|
36
|
+
loaded = store.load
|
|
37
|
+
rule = loaded.rules.find { |r| r.key == definition.key }
|
|
38
|
+
return [ " rule: none (store revision #{store.revision || "none"})" ] unless rule
|
|
39
|
+
|
|
40
|
+
[ " rule: #{rule.status}, revision #{rule.lock_version} (store revision #{store.revision || "none"})",
|
|
41
|
+
" percentage: #{rule.percentage_bps.nil? ? '-' : "#{rule.percentage_bps} bps"}" \
|
|
42
|
+
"#{" → #{rule.rollout_value}" if rule.rollout_value}#{", full since #{rule.full_since.utc.iso8601}" if rule.full_since}",
|
|
43
|
+
" variants: #{rule.variant_weights.empty? ? '-' : rule.variant_weights.map { |v, w| "#{v} #{w}" }.join(', ')}",
|
|
44
|
+
" fallthrough: #{rule.fallthrough_value || '-'} stop value: #{rule.stop_value || '-'}",
|
|
45
|
+
" conditions: #{rule.conditions.empty? ? '-' : JSON.generate(rule.conditions)}",
|
|
46
|
+
" cohorts: #{rule.cohort_attachments.empty? ? '-' : rule.cohort_attachments.map { |k, v| "#{k} → #{v}" }.join(', ')}",
|
|
47
|
+
" members: #{rule.member_count}",
|
|
48
|
+
" last evaluated: #{rule.last_evaluated_at&.utc&.iso8601 || '-'}" ]
|
|
49
|
+
rescue StandardError => e
|
|
50
|
+
[ " rule: could not read the store (#{(e.cause_class if e.is_a?(Runtime::StoreError)) || e.class})" ]
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def cohort_lines
|
|
54
|
+
key = @key.delete_prefix("cohort:")
|
|
55
|
+
return [ "runtime rules are off" ] unless Runtime.enabled?
|
|
56
|
+
|
|
57
|
+
loaded = store.load
|
|
58
|
+
cohort = loaded.cohorts.find { |c| c.key == key }
|
|
59
|
+
return [ "unknown cohort #{key.inspect}" ] unless cohort
|
|
60
|
+
|
|
61
|
+
attached = loaded.rules.select { |rule| rule.cohort_attachments.any? { |k, _| k == key } }.map(&:key).sort
|
|
62
|
+
[ "cohort #{key} (unit: #{cohort.unit}#{", archived #{cohort.archived_at.utc.iso8601}" if cohort.archived?})",
|
|
63
|
+
(" #{cohort.name}" if cohort.name), (" #{cohort.description}" if cohort.description),
|
|
64
|
+
" members: #{cohort.member_count}",
|
|
65
|
+
" attached to: #{attached.empty? ? '-' : attached.map { |k| ":#{k}" }.join(', ')}" ].compact
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# The rake tasks that change flags. Each needs REASON= and runs as
|
|
70
|
+
# `StandardFlags::Actor.system("rake")`; it prints the outcome and the
|
|
71
|
+
# new revision.
|
|
72
|
+
class Command
|
|
73
|
+
ACTOR = Actor.system("rake")
|
|
74
|
+
# How an AT= ends: Z or an offset. A bare local time would be read in
|
|
75
|
+
# the server's zone, which may not be the operator's, so it is refused.
|
|
76
|
+
ZONED = /(?:Z|[+-]\d\d:?\d\d)\z/i
|
|
77
|
+
Outcome = Data.define(:ok, :message) do
|
|
78
|
+
alias_method :ok?, :ok
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def initialize(env, registry: StandardFlags.registry)
|
|
82
|
+
@env = env
|
|
83
|
+
@registry = registry
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def run(task)
|
|
87
|
+
reason = fetch("REASON")
|
|
88
|
+
return refuse(task, "REASON= is required (it is written to the audit log)") unless reason
|
|
89
|
+
return purge(reason) if task == :purge
|
|
90
|
+
return restore(reason) if task == :restore
|
|
91
|
+
|
|
92
|
+
key = fetch("KEY")
|
|
93
|
+
return refuse(task, "KEY= is required") unless key
|
|
94
|
+
|
|
95
|
+
operation, args = operation_for(task)
|
|
96
|
+
report(task, key, operation.call(key, actor: ACTOR, reason: reason, registry: @registry, **args))
|
|
97
|
+
rescue ArgumentError => e
|
|
98
|
+
refuse(task, e.message)
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
private
|
|
102
|
+
|
|
103
|
+
def operation_for(task)
|
|
104
|
+
case task
|
|
105
|
+
when :set then [ Operations::SetValue, { value: required("VALUE") } ]
|
|
106
|
+
when :ramp then [ Operations::Ramp, { bps: Integer(required("BPS"), 10), **optional("VALUE" => :value) } ]
|
|
107
|
+
when :start then [ Operations::Start, {} ]
|
|
108
|
+
when :pause then [ Operations::Pause, {} ]
|
|
109
|
+
when :stop then [ Operations::Stop, { serve: required("SERVE") } ]
|
|
110
|
+
when :members_add
|
|
111
|
+
[ Operations::AddMembers, { keys: keys, **optional("UNIT" => :unit, "VALUE" => :value, "EXPIRES_AT" => :expires_at) } ]
|
|
112
|
+
when :members_remove then [ Operations::RemoveMembers, { keys: keys, **optional("UNIT" => :unit) } ]
|
|
113
|
+
else raise ArgumentError, "unknown task #{task.inspect}"
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def purge(reason)
|
|
118
|
+
return refuse(:purge, "runtime rules are off") unless Runtime.enabled?
|
|
119
|
+
|
|
120
|
+
counts = Runtime.purge!
|
|
121
|
+
Reporting.instrument(:purge_requested, actor: ACTOR.to_s, reason: reason, **counts)
|
|
122
|
+
Outcome.new(ok: true, message: "flags:purge: deleted #{counts[:removed]} removed and #{counts[:expired]} expired memberships")
|
|
123
|
+
rescue StandardError => e
|
|
124
|
+
refuse(:purge, "could not purge (#{(e.cause_class if e.is_a?(Runtime::StoreError)) || e.class})")
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
# Prints the plan (a dry run unless APPLY=1), member changes as counts.
|
|
128
|
+
def restore(reason)
|
|
129
|
+
at = iso8601(required("AT"))
|
|
130
|
+
return refuse(:restore, "AT= must be an ISO 8601 time with a zone (Z or an offset), e.g. 2026-11-20T09:00:00Z") unless at
|
|
131
|
+
|
|
132
|
+
keys = fetch("KEYS")&.split(",")&.map(&:strip)
|
|
133
|
+
result = Operations::Restore.call(at: at, reason: reason, keys: keys, apply: @env["APPLY"] == "1", registry: @registry)
|
|
134
|
+
return refuse_result("flags:restore", result) if result.value.nil?
|
|
135
|
+
|
|
136
|
+
Outcome.new(ok: result.success?, message: restore_lines(result).join("\n"))
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
def restore_lines(result)
|
|
140
|
+
value = result.value
|
|
141
|
+
lines = [ "flags:restore to #{value[:at]} (#{value[:applied] ? 'applied' : 'dry run; APPLY=1 applies it'})" ]
|
|
142
|
+
value[:entries].each do |entry|
|
|
143
|
+
changes = entry[:changes].empty? ? "" : ": #{entry[:changes].join('; ')}"
|
|
144
|
+
lines << " #{entry[:target]}: #{entry[:status]}#{changes}"
|
|
145
|
+
lines << " error: #{entry[:error]}" if entry[:error]
|
|
146
|
+
entry[:notes].each { |note| lines << " note: #{note}" }
|
|
147
|
+
end
|
|
148
|
+
lines << " nothing to restore" if value[:entries].empty?
|
|
149
|
+
lines << "flags:restore: #{result.errors.size} failed (#{result.code})" unless result.success?
|
|
150
|
+
lines
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
def report(task, key, result)
|
|
154
|
+
name = "flags:#{task.to_s.tr('_', ':')} #{key}"
|
|
155
|
+
return refuse_result(name, result) unless result.success?
|
|
156
|
+
|
|
157
|
+
value = result.value
|
|
158
|
+
state = value[:rule] || value[:state]
|
|
159
|
+
details = [ ("status #{state[:status]}" if state&.key?(:status)), *value.slice(:added, :updated, :removed).map { |k, v| "#{v} #{k}" } ]
|
|
160
|
+
Outcome.new(ok: true, message: "#{name}: ok, revision #{value[:revision]}#{" (#{details.compact.join(', ')})" unless details.compact.empty?}")
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
def refuse_result(name, result)
|
|
164
|
+
Outcome.new(ok: false, message: "#{name}: refused (#{result.code}): #{result.errors.join('; ')}")
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
def refuse(task, message)
|
|
168
|
+
Outcome.new(ok: false, message: "flags:#{task.to_s.tr('_', ':')}: #{message}")
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
def keys
|
|
172
|
+
required("KEYS").split(",").map(&:strip)
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
# nil unless it names its zone (ZONED).
|
|
176
|
+
def iso8601(text)
|
|
177
|
+
Time.iso8601(text) if text.strip.match?(ZONED)
|
|
178
|
+
rescue ArgumentError
|
|
179
|
+
nil
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
def fetch(name)
|
|
183
|
+
value = @env[name]
|
|
184
|
+
value unless value.nil? || value.strip.empty?
|
|
185
|
+
end
|
|
186
|
+
|
|
187
|
+
def required(name)
|
|
188
|
+
fetch(name) || raise(ArgumentError, "#{name}= is required")
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
def optional(names)
|
|
192
|
+
names.each_with_object({}) { |(var, arg), out| (value = fetch(var)) && out[arg] = value }
|
|
193
|
+
end
|
|
194
|
+
end
|
|
195
|
+
end
|
|
196
|
+
end
|