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,218 @@
|
|
|
1
|
+
require "securerandom"
|
|
2
|
+
|
|
3
|
+
module StandardFlags
|
|
4
|
+
module Operations
|
|
5
|
+
# Records each change (R16). Inside the operation's transaction
|
|
6
|
+
# (`record`), only the audit row, and only when standard_audit is loaded
|
|
7
|
+
# and enabled:
|
|
8
|
+
#
|
|
9
|
+
# * through StandardAudit::Operation's `audit!`, or,
|
|
10
|
+
# * when the app subscribes standard_audit to the event (for example with
|
|
11
|
+
# `StandardFlags::Events.auditable`), by publishing the event there, so
|
|
12
|
+
# its subscriber writes the row. One row either way.
|
|
13
|
+
#
|
|
14
|
+
# Either runs in its own savepoint. standard_audit swallows a failed
|
|
15
|
+
# write by default, and on Postgres a failed statement aborts the whole
|
|
16
|
+
# transaction; the savepoint confines that to the audit row. A failure
|
|
17
|
+
# the savepoint catches (or any error the writer raises) fails the
|
|
18
|
+
# operation with :audit_failed, rolled back, when standard_audit's
|
|
19
|
+
# `raise_on_audit_write_error` is set; otherwise it is reported and the
|
|
20
|
+
# change commits without its row, as standard_audit's own default does.
|
|
21
|
+
# (A failure standard_audit's subscriber swallows before reaching the
|
|
22
|
+
# database leaves nothing to detect; it reports those itself.)
|
|
23
|
+
#
|
|
24
|
+
# Once the change has committed (`announce`), never while its locks are
|
|
25
|
+
# held:
|
|
26
|
+
#
|
|
27
|
+
# * the event itself (`standard_flags.flag.ramped` and so on), through
|
|
28
|
+
# ActiveSupport::Notifications, unless `record` already published it;
|
|
29
|
+
# * `change.standard_flags`, a one-line summary for the gem's own
|
|
30
|
+
# subscribers (the Logger line, `config.add_notifier`).
|
|
31
|
+
#
|
|
32
|
+
# The row's metadata is the event payload without `actor`: the actor's
|
|
33
|
+
# label, the reason, the key or cohort, the new revision, and the full
|
|
34
|
+
# rule or cohort state before and after. Membership changes add the
|
|
35
|
+
# unit, the value and counts. No unit key ever appears.
|
|
36
|
+
#
|
|
37
|
+
# @api private
|
|
38
|
+
module Audit
|
|
39
|
+
WRITER_LOCK = Mutex.new
|
|
40
|
+
|
|
41
|
+
module_function
|
|
42
|
+
|
|
43
|
+
# Inside the write. Returns true when it published the event.
|
|
44
|
+
def record(tx, event, payload)
|
|
45
|
+
if direct?(event)
|
|
46
|
+
isolated(tx, event) { write(event, payload) }
|
|
47
|
+
false
|
|
48
|
+
elsif subscribed?(event)
|
|
49
|
+
isolated(tx, event) { ActiveSupport::Notifications.instrument(event, payload) }
|
|
50
|
+
true
|
|
51
|
+
else
|
|
52
|
+
false
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Outside any write: an operator read worth a row of its own (a reveal
|
|
57
|
+
# of unit keys, or a probe of one). One row, by whichever path writes
|
|
58
|
+
# it, then the event for everyone else. By default a failed row is
|
|
59
|
+
# reported and the read goes ahead.
|
|
60
|
+
#
|
|
61
|
+
# With standard_audit's `raise_on_audit_write_error` set, it fails
|
|
62
|
+
# closed: it raises Failure(:audit_failed), so the caller can refuse
|
|
63
|
+
# the read, unless the row is known to be written (record_read!).
|
|
64
|
+
def record_read(event, payload)
|
|
65
|
+
return record_read!(event, payload) if raise_on_write_error?
|
|
66
|
+
|
|
67
|
+
if subscribed?(event)
|
|
68
|
+
begin
|
|
69
|
+
ActiveSupport::Notifications.instrument(event, payload)
|
|
70
|
+
rescue StandardError => e
|
|
71
|
+
Reporting.report(Error.new("the audit row for #{event} was not written (#{e.class})"), event: event)
|
|
72
|
+
end
|
|
73
|
+
else
|
|
74
|
+
write(event, payload) if direct?(event)
|
|
75
|
+
Reporting.publish(event, payload)
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# The fail-closed read. The row is written inside a store write, in a
|
|
80
|
+
# savepoint, as the write path's is: a database failure that
|
|
81
|
+
# standard_audit's subscriber swallows still aborts the savepoint (on
|
|
82
|
+
# Postgres), and is raised here. The row also carries a one-off
|
|
83
|
+
# `audit_ref`, and when standard_audit's AuditLog is loaded it is read
|
|
84
|
+
# back inside the same write, which catches a failure swallowed before
|
|
85
|
+
# the database (and a row batched for later). `config.async` writes
|
|
86
|
+
# the row from a job, so it can never be confirmed: refused.
|
|
87
|
+
def record_read!(event, payload)
|
|
88
|
+
if ::StandardAudit.config.respond_to?(:async) && ::StandardAudit.config.async
|
|
89
|
+
raise Failure.new(:audit_failed, "standard_audit writes audit rows from a job (config.async), so this one can't be confirmed")
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
payload = payload.merge(audit_ref: SecureRandom.uuid)
|
|
93
|
+
subscribed = subscribed?(event)
|
|
94
|
+
in_savepoint do
|
|
95
|
+
if subscribed
|
|
96
|
+
ActiveSupport::Notifications.instrument(event, payload)
|
|
97
|
+
else
|
|
98
|
+
writer.new.write(event, actor: payload[:actor], metadata: payload.except(:actor))
|
|
99
|
+
end
|
|
100
|
+
confirm!(event, payload[:audit_ref])
|
|
101
|
+
end
|
|
102
|
+
Reporting.publish(event, payload) unless subscribed
|
|
103
|
+
rescue Failure
|
|
104
|
+
raise
|
|
105
|
+
rescue StandardError => e
|
|
106
|
+
raise if e.class.name == "StandardAudit::Operation::DeclarationError"
|
|
107
|
+
|
|
108
|
+
raise Failure.new(:audit_failed, "the audit row could not be written (#{(e.cause_class if e.is_a?(Runtime::StoreError)) || e.class})")
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
# With runtime rules off there is no store write to run in (only a
|
|
112
|
+
# probe of an ENV-pinned or default flag gets here); the read-back
|
|
113
|
+
# still applies.
|
|
114
|
+
def in_savepoint(&block)
|
|
115
|
+
return yield unless Runtime.enabled?
|
|
116
|
+
|
|
117
|
+
Runtime.store.write { |tx| tx.isolated(&block) }
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
# Reads the row back by its audit_ref, when standard_audit's AuditLog
|
|
121
|
+
# is there to read (a Postgres JSON read, as AuditTrail's).
|
|
122
|
+
def confirm!(event, ref)
|
|
123
|
+
log = defined?(::StandardAudit::AuditLog) ? ::StandardAudit::AuditLog : nil
|
|
124
|
+
return unless log.respond_to?(:where)
|
|
125
|
+
return if log.where(event_type: event).where("metadata->>'audit_ref' = ?", ref).exists?
|
|
126
|
+
|
|
127
|
+
raise Failure.new(:audit_failed, "the audit row could not be written (not found after the write)")
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# After the commit. Never raises.
|
|
131
|
+
def announce(event, payload, published:)
|
|
132
|
+
Reporting.publish(event, payload) unless published
|
|
133
|
+
Reporting.instrument(:change, event: event, key: payload[:key], cohort: payload[:cohort],
|
|
134
|
+
actor: payload[:actor_label], revision: payload[:revision],
|
|
135
|
+
store_revision: payload[:store_revision])
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
# Whether this process writes the row itself.
|
|
139
|
+
def direct?(event)
|
|
140
|
+
enabled? && !subscribed?(event)
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# Whether standard_audit's subscriber writes the row for this event.
|
|
144
|
+
def subscribed?(event)
|
|
145
|
+
enabled? && Array(::StandardAudit.config.respond_to?(:subscriptions) ? ::StandardAudit.config.subscriptions : nil).any? do |pattern|
|
|
146
|
+
pattern.is_a?(Regexp) ? pattern.match?(event) : pattern.to_s == event
|
|
147
|
+
end
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
def enabled?
|
|
151
|
+
return false unless defined?(::StandardAudit::Operation) && ::StandardAudit.respond_to?(:config)
|
|
152
|
+
|
|
153
|
+
config = ::StandardAudit.config
|
|
154
|
+
!(config.respond_to?(:enabled) && !config.enabled)
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def raise_on_write_error?
|
|
158
|
+
return false unless enabled?
|
|
159
|
+
|
|
160
|
+
config = ::StandardAudit.config
|
|
161
|
+
config.respond_to?(:raise_on_audit_write_error) && config.raise_on_audit_write_error ? true : false
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
def isolated(tx, event, &)
|
|
165
|
+
tx.isolated(&)
|
|
166
|
+
rescue Failure
|
|
167
|
+
raise
|
|
168
|
+
rescue StandardError => e
|
|
169
|
+
raise if e.class.name == "StandardAudit::Operation::DeclarationError"
|
|
170
|
+
if raise_on_write_error?
|
|
171
|
+
raise Failure.new(:audit_failed, "the audit row could not be written (#{e.class}); nothing was changed")
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
Reporting.report(Error.new("the audit row for #{event} was not written (#{e.class}); the change was kept"), event: event)
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
def write(event, payload)
|
|
178
|
+
writer.new.write(event, actor: payload[:actor], metadata: payload.except(:actor))
|
|
179
|
+
rescue StandardError => e
|
|
180
|
+
# standard_audit's own declaration check (dev and test only) always
|
|
181
|
+
# propagates, as it does for any operation.
|
|
182
|
+
raise if e.class.name == "StandardAudit::Operation::DeclarationError"
|
|
183
|
+
|
|
184
|
+
# Only reached when the app sets raise_on_audit_write_error; by
|
|
185
|
+
# default standard_audit reports a failed write and carries on.
|
|
186
|
+
raise Failure.new(:audit_failed, "the audit row could not be written (#{e.class}); nothing was changed")
|
|
187
|
+
end
|
|
188
|
+
|
|
189
|
+
# Forgets the writer class, so the next write builds it again. For the
|
|
190
|
+
# gem's own specs.
|
|
191
|
+
def reset!
|
|
192
|
+
WRITER_LOCK.synchronize do
|
|
193
|
+
Operations.send(:remove_const, :AuditWriter) if Operations.const_defined?(:AuditWriter, false)
|
|
194
|
+
end
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
# StandardFlags::Operations::AuditWriter, the one class that writes
|
|
198
|
+
# standard_flags audit rows through standard_audit. Built the first
|
|
199
|
+
# time it's needed, so neither gem has to load before the other. It is
|
|
200
|
+
# named before it includes the contract, so standard_audit registers a
|
|
201
|
+
# named operation.
|
|
202
|
+
def writer
|
|
203
|
+
WRITER_LOCK.synchronize do
|
|
204
|
+
next Operations::AuditWriter if Operations.const_defined?(:AuditWriter, false)
|
|
205
|
+
|
|
206
|
+
klass = Operations.const_set(:AuditWriter, Class.new do
|
|
207
|
+
def write(action, **attributes)
|
|
208
|
+
audit!(action, **attributes)
|
|
209
|
+
end
|
|
210
|
+
end)
|
|
211
|
+
klass.include(::StandardAudit::Operation)
|
|
212
|
+
klass.audits(*Events::AUDITABLE)
|
|
213
|
+
klass
|
|
214
|
+
end
|
|
215
|
+
end
|
|
216
|
+
end
|
|
217
|
+
end
|
|
218
|
+
end
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
require "securerandom"
|
|
2
|
+
|
|
3
|
+
module StandardFlags
|
|
4
|
+
module Operations
|
|
5
|
+
# The steps every operation takes, in order:
|
|
6
|
+
#
|
|
7
|
+
# 1. Resolve the actor: `actor:`, else `config.actor_resolver`. With
|
|
8
|
+
# neither, it fails (:actor_missing); pass `StandardFlags::Actor.system`
|
|
9
|
+
# for work no person does.
|
|
10
|
+
# 2. Authorise through `config.authorize.call(actor, scope, key)`
|
|
11
|
+
# (:unauthorized).
|
|
12
|
+
# 3. Refuse unknown (:unknown_flag) and tombstoned (:tombstoned_flag)
|
|
13
|
+
# keys, and flags an ENV pin decides (:pinned_by_env; the error names
|
|
14
|
+
# the variable, never its value).
|
|
15
|
+
# 4. In one store write: create the rule on first use (salt and hash
|
|
16
|
+
# version from the flag's `bucketing:`, else a random salt and v2) and
|
|
17
|
+
# lock it, then the cohorts it needs (by id); check
|
|
18
|
+
# `expected_revision` against its lock_version (:stale_revision);
|
|
19
|
+
# validate (:invalid, :limit_exceeded); save, keeping member_count and
|
|
20
|
+
# full_since in step; check the whole rule again if it is running, so
|
|
21
|
+
# no edit leaves one the read path can't serve; increment the state
|
|
22
|
+
# revision; write the audit row (Audit.record).
|
|
23
|
+
# 5. Once the write has committed: expire the process cache, clear the
|
|
24
|
+
# unit of work's memo, and publish (Audit.announce). Inside a host
|
|
25
|
+
# transaction that is when the host commits.
|
|
26
|
+
#
|
|
27
|
+
# Results carry `value: { key: or cohort:, rule: or state:, revision:,
|
|
28
|
+
# store_revision: }` plus what the operation changed. `revision` is the
|
|
29
|
+
# number `expected_revision` is checked against: a rule's lock_version,
|
|
30
|
+
# or for cohort operations the store's revision. `store_revision` is
|
|
31
|
+
# always the store's. Success means the write committed (or, inside a
|
|
32
|
+
# host transaction, will commit with it). Every failure is a Result,
|
|
33
|
+
# never an exception; store and unexpected errors are reported through
|
|
34
|
+
# `config.error_reporter` / Rails.error (:store_error, :error).
|
|
35
|
+
class Base
|
|
36
|
+
class << self
|
|
37
|
+
def call(target, actor: nil, reason: nil, expected_revision: nil, registry: StandardFlags.registry, **args)
|
|
38
|
+
new(target, actor: actor, reason: reason, expected_revision: expected_revision, registry: registry, args: args).call
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# "flags:write" unless the operation says otherwise.
|
|
42
|
+
def scope(name = nil)
|
|
43
|
+
@scope = name if name
|
|
44
|
+
@scope || "flags:write"
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# Argument names: `required` must be given, `optional` may be.
|
|
48
|
+
def arguments(required: [], optional: [])
|
|
49
|
+
@required = required.freeze
|
|
50
|
+
@optional = optional.freeze
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def required_arguments
|
|
54
|
+
@required || []
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def optional_arguments
|
|
58
|
+
@optional || []
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# The operation's name in errors and reports: "ramp", "add_members".
|
|
62
|
+
def operation_name
|
|
63
|
+
name.split("::").last.gsub(/([a-z])([A-Z])/, '\1_\2').downcase
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
attr_reader :actor, :reason, :registry, :args
|
|
68
|
+
|
|
69
|
+
def initialize(target, actor:, reason:, expected_revision:, registry:, args:)
|
|
70
|
+
@target = target
|
|
71
|
+
@given_actor = actor
|
|
72
|
+
@reason = reason
|
|
73
|
+
@expected_revision = expected_revision
|
|
74
|
+
@registry = registry
|
|
75
|
+
@args = args
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def call
|
|
79
|
+
@actor = resolve_actor
|
|
80
|
+
check_reason!
|
|
81
|
+
check_arguments!
|
|
82
|
+
parse_target!
|
|
83
|
+
authorize!
|
|
84
|
+
check_target!
|
|
85
|
+
check_runtime!
|
|
86
|
+
@announcements = []
|
|
87
|
+
value = Runtime.store.write do |tx|
|
|
88
|
+
@tx = tx
|
|
89
|
+
run.tap { tx.after_commit { committed } }
|
|
90
|
+
end
|
|
91
|
+
Result.success(value)
|
|
92
|
+
rescue Failure => e
|
|
93
|
+
Result.failure(e.code, e.message)
|
|
94
|
+
rescue Runtime::StoreError => e
|
|
95
|
+
Reporting.report(e, operation: self.class.operation_name, **report_context)
|
|
96
|
+
Result.failure(:store_error, e.message)
|
|
97
|
+
rescue StandardError => e
|
|
98
|
+
raise if e.class.name == "StandardAudit::Operation::DeclarationError"
|
|
99
|
+
|
|
100
|
+
report_unexpected(e)
|
|
101
|
+
Result.failure(:error, "#{self.class.operation_name} failed: #{e.class}")
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
private
|
|
105
|
+
|
|
106
|
+
attr_reader :tx, :definition
|
|
107
|
+
|
|
108
|
+
# -- steps -------------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
def resolve_actor
|
|
111
|
+
actor = @given_actor || StandardFlags.config.actor_resolver&.call
|
|
112
|
+
return actor unless actor.nil?
|
|
113
|
+
|
|
114
|
+
raise Failure.new(:actor_missing, "no actor: pass actor:, configure config.actor_resolver, " \
|
|
115
|
+
"or use StandardFlags::Actor.system(...)")
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
def check_reason!
|
|
119
|
+
return if @reason.is_a?(String) && !@reason.strip.empty?
|
|
120
|
+
|
|
121
|
+
raise Failure.new(:invalid, "a reason is required")
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
def check_arguments!
|
|
125
|
+
klass = self.class
|
|
126
|
+
unknown = args.keys - klass.required_arguments - klass.optional_arguments
|
|
127
|
+
missing = klass.required_arguments - args.keys
|
|
128
|
+
raise Failure.new(:invalid, "unknown argument(s): #{unknown.join(', ')}") unless unknown.empty?
|
|
129
|
+
raise Failure.new(:invalid, "missing argument(s): #{missing.join(', ')}") unless missing.empty?
|
|
130
|
+
return if @expected_revision.nil? || @expected_revision.is_a?(Integer)
|
|
131
|
+
|
|
132
|
+
raise Failure.new(:invalid, "expected_revision must be an Integer")
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
# Sets @key (a flag key Symbol) or @cohort_key (a String).
|
|
136
|
+
def parse_target!
|
|
137
|
+
text = @target.to_s
|
|
138
|
+
if text.start_with?("cohort:")
|
|
139
|
+
@cohort_key = text.delete_prefix("cohort:")
|
|
140
|
+
else
|
|
141
|
+
@key = text.to_sym
|
|
142
|
+
end
|
|
143
|
+
accepts = self.class.respond_to?(:targets) ? self.class.targets : %i[flag]
|
|
144
|
+
raise Failure.new(:invalid, "#{self.class.operation_name} takes a flag key, not a cohort") if @cohort_key && !accepts.include?(:cohort)
|
|
145
|
+
raise Failure.new(:invalid, "#{self.class.operation_name} takes a cohort, not a flag key") if @key && !accepts.include?(:flag)
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def authorization_key
|
|
149
|
+
@key || "cohort:#{@cohort_key}"
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
# Every key the policy must allow; operations that also touch a cohort
|
|
153
|
+
# add it.
|
|
154
|
+
def authorization_keys
|
|
155
|
+
[ authorization_key ]
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
def authorize!
|
|
159
|
+
authorization_keys.each do |key|
|
|
160
|
+
allowed = begin
|
|
161
|
+
StandardFlags.config.authorize.call(actor, self.class.scope, key)
|
|
162
|
+
rescue StandardError => e
|
|
163
|
+
Reporting.report(e, operation: self.class.operation_name, **report_context)
|
|
164
|
+
false
|
|
165
|
+
end
|
|
166
|
+
raise Failure.new(:unauthorized, "#{Actor.label(actor)} may not #{self.class.scope} #{key.inspect}") unless allowed
|
|
167
|
+
end
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
def check_target!
|
|
171
|
+
return check_cohort_key! if @cohort_key
|
|
172
|
+
|
|
173
|
+
if registry.tombstoned?(@key)
|
|
174
|
+
raise Failure.new(:tombstoned_flag, "flag :#{@key} was removed on #{registry.tombstones[@key].removed.iso8601}")
|
|
175
|
+
end
|
|
176
|
+
@definition = registry[@key]
|
|
177
|
+
raise Failure.new(:unknown_flag, "unknown flag :#{@key}") unless @definition
|
|
178
|
+
|
|
179
|
+
pin = EnvPin.scan(@definition, StandardFlags.config.env_source).pin
|
|
180
|
+
return unless pin
|
|
181
|
+
|
|
182
|
+
raise Failure.new(:pinned_by_env, "flag :#{@key} is pinned by #{pin.var}; unset it to change the flag here")
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
def check_cohort_key!
|
|
186
|
+
return if @cohort_key.match?(Definition::KEY_FORMAT)
|
|
187
|
+
|
|
188
|
+
raise Failure.new(:invalid, "cohort key #{@cohort_key.inspect} must match #{Definition::KEY_FORMAT.inspect}")
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
def check_runtime!
|
|
192
|
+
return if Runtime.enabled?
|
|
193
|
+
|
|
194
|
+
raise Failure.new(:runtime_rules_off, "runtime rules are off; set config.runtime_rules = true first")
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
# Rule operations: lock (creating on first use) the rule, then its
|
|
198
|
+
# cohorts, check the revision, perform, re-check a running rule, bump,
|
|
199
|
+
# record.
|
|
200
|
+
def run
|
|
201
|
+
@rule = tx.lock_rule(@key) || tx.create_rule(@key, **bucketing)
|
|
202
|
+
check_revision!(@rule.lock_version)
|
|
203
|
+
@cohorts = tx.lock_cohorts(cohort_keys)
|
|
204
|
+
before = @rule.audit_state
|
|
205
|
+
extra = perform || {}
|
|
206
|
+
validate.rule!(definition, @rule, registry, @cohorts) if @rule.running?
|
|
207
|
+
store_revision = Runtime.bump_revision!(tx)
|
|
208
|
+
revisions = { revision: @rule.lock_version, store_revision: store_revision }
|
|
209
|
+
publish(event, { key: @key.to_s, before: before, after: @rule.audit_state, **revisions, **extra })
|
|
210
|
+
{ key: @key, rule: @rule.audit_state, **revisions, **extra }
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
# The cohorts to lock (in id order, after the rule): those a running
|
|
214
|
+
# rule attaches, which its re-check reads, plus `extra_cohort_keys`.
|
|
215
|
+
def cohort_keys
|
|
216
|
+
attached = @rule.running? ? validate.attachments(definition, @rule) : []
|
|
217
|
+
(attached + extra_cohort_keys).uniq
|
|
218
|
+
end
|
|
219
|
+
|
|
220
|
+
def extra_cohort_keys
|
|
221
|
+
[]
|
|
222
|
+
end
|
|
223
|
+
|
|
224
|
+
def bucketing
|
|
225
|
+
declared = definition.bucketing
|
|
226
|
+
{ salt: declared&.salt || SecureRandom.hex(16), hash_version: declared&.version || 2 }
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
def check_revision!(current)
|
|
230
|
+
return if @expected_revision.nil? || @expected_revision == current
|
|
231
|
+
|
|
232
|
+
raise Failure.new(:stale_revision, "#{authorization_key.inspect} is at revision #{current}, " \
|
|
233
|
+
"not #{@expected_revision}; reload and try again")
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
# Records the audit row now, inside the write, and queues the
|
|
237
|
+
# announcement for after the commit.
|
|
238
|
+
def publish(event, payload)
|
|
239
|
+
payload = { actor: actor.is_a?(Actor) ? nil : actor, actor_label: Actor.label(actor), reason: @reason }.merge(payload)
|
|
240
|
+
published = Audit.record(tx, event, payload)
|
|
241
|
+
@announcements << -> { Audit.announce(event, payload, published: published) }
|
|
242
|
+
end
|
|
243
|
+
|
|
244
|
+
# Runs once the write has committed. Never raises: the change is in.
|
|
245
|
+
def committed
|
|
246
|
+
Runtime.expire!
|
|
247
|
+
Memo.clear!
|
|
248
|
+
@announcements.each(&:call)
|
|
249
|
+
rescue StandardError => e
|
|
250
|
+
warn "[standard_flags] after-commit step of #{self.class.operation_name} failed: #{e.class}"
|
|
251
|
+
end
|
|
252
|
+
|
|
253
|
+
def save!(attributes)
|
|
254
|
+
@rule = tx.save_rule(@rule, attributes)
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
# -- helpers -----------------------------------------------------------
|
|
258
|
+
|
|
259
|
+
def arg(name)
|
|
260
|
+
args[name]
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
def validate
|
|
264
|
+
Validation
|
|
265
|
+
end
|
|
266
|
+
|
|
267
|
+
def config
|
|
268
|
+
StandardFlags.config
|
|
269
|
+
end
|
|
270
|
+
|
|
271
|
+
def report_context
|
|
272
|
+
if @key then { flag: @key.to_s }
|
|
273
|
+
elsif @cohort_key then { cohort: @cohort_key }
|
|
274
|
+
else {}
|
|
275
|
+
end
|
|
276
|
+
end
|
|
277
|
+
|
|
278
|
+
# Unexpected errors are reported as they are, except from operations
|
|
279
|
+
# that handle unit keys, whose messages could quote one.
|
|
280
|
+
def report_unexpected(error)
|
|
281
|
+
error = Error.new("#{self.class.operation_name} failed: #{error.class}") if sensitive?
|
|
282
|
+
Reporting.report(error, operation: self.class.operation_name, **report_context)
|
|
283
|
+
end
|
|
284
|
+
|
|
285
|
+
def sensitive?
|
|
286
|
+
false
|
|
287
|
+
end
|
|
288
|
+
end
|
|
289
|
+
end
|
|
290
|
+
end
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
module StandardFlags
|
|
2
|
+
module Operations
|
|
3
|
+
# Shared by the cohort operations: they take a cohort key ("staff" or
|
|
4
|
+
# "cohort:staff") and check `expected_revision` against the store's
|
|
5
|
+
# revision, since cohorts have no lock_version of their own; `revision`
|
|
6
|
+
# in their Results is that number too. The state row is locked last, as
|
|
7
|
+
# in every write.
|
|
8
|
+
class CohortOperation < Base
|
|
9
|
+
def self.targets
|
|
10
|
+
%i[cohort]
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
private
|
|
14
|
+
|
|
15
|
+
def parse_target!
|
|
16
|
+
@target = "cohort:#{@target.to_s.delete_prefix('cohort:')}"
|
|
17
|
+
super
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def run
|
|
21
|
+
cohort = tx.lock_cohort(@cohort_key)
|
|
22
|
+
before = cohort&.audit_state
|
|
23
|
+
cohort, extra = perform(cohort)
|
|
24
|
+
check_revision!(tx.lock_revision)
|
|
25
|
+
revision = Runtime.bump_revision!(tx)
|
|
26
|
+
publish(event, { cohort: @cohort_key, before: before, after: cohort.audit_state,
|
|
27
|
+
revision: revision, store_revision: revision, **extra })
|
|
28
|
+
{ cohort: @cohort_key, state: cohort.audit_state, revision: revision, store_revision: revision, **extra }
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Creates a named member list of one unit (`unit:`), with optional
|
|
33
|
+
# `name:` and `description:`. A taken key fails with :already_exists,
|
|
34
|
+
# including when a concurrent CreateCohort took it first.
|
|
35
|
+
class CreateCohort < CohortOperation
|
|
36
|
+
arguments required: %i[unit], optional: %i[name description]
|
|
37
|
+
|
|
38
|
+
private
|
|
39
|
+
|
|
40
|
+
def event = Events::COHORT_EVENTS[:created]
|
|
41
|
+
|
|
42
|
+
def perform(existing)
|
|
43
|
+
already_exists! if existing
|
|
44
|
+
|
|
45
|
+
unit = registry.units[arg(:unit).to_s.to_sym]
|
|
46
|
+
raise Failure.new(:invalid, "unknown unit #{arg(:unit).inspect}") unless unit
|
|
47
|
+
|
|
48
|
+
created = tx.create_cohort(@cohort_key, unit: unit.name.to_s, name: arg(:name)&.to_s, description: arg(:description)&.to_s)
|
|
49
|
+
already_exists! unless created
|
|
50
|
+
[ created, {} ]
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def already_exists!
|
|
54
|
+
raise Failure.new(:already_exists, "cohort #{@cohort_key.inspect} already exists")
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# Archives a cohort: no new members, and rules ignore it. Detach it from
|
|
59
|
+
# every flag first.
|
|
60
|
+
class ArchiveCohort < CohortOperation
|
|
61
|
+
arguments
|
|
62
|
+
|
|
63
|
+
private
|
|
64
|
+
|
|
65
|
+
def event = Events::COHORT_EVENTS[:archived]
|
|
66
|
+
|
|
67
|
+
def perform(cohort)
|
|
68
|
+
raise Failure.new(:invalid, "cohort #{@cohort_key.inspect} does not exist") unless cohort
|
|
69
|
+
raise Failure.new(:invalid, "cohort #{@cohort_key.inspect} is already archived") if cohort.archived?
|
|
70
|
+
|
|
71
|
+
attached = tx.rules_attached_to(@cohort_key)
|
|
72
|
+
unless attached.empty?
|
|
73
|
+
raise Failure.new(:invalid, "cohort #{@cohort_key.inspect} is attached to #{attached.map { |k| ":#{k}" }.join(', ')}; detach it first")
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
[ tx.save_cohort(cohort, archived_at: Time.now.utc), {} ]
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
end
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
module StandardFlags
|
|
2
|
+
module Operations
|
|
3
|
+
# Raised inside an operation to stop it (rolling back its write) with a
|
|
4
|
+
# failed Result. Never escapes an operation.
|
|
5
|
+
#
|
|
6
|
+
# @api private
|
|
7
|
+
class Failure < StandardError
|
|
8
|
+
attr_reader :code
|
|
9
|
+
|
|
10
|
+
def initialize(code, message)
|
|
11
|
+
@code = code
|
|
12
|
+
super(message)
|
|
13
|
+
end
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
end
|