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,256 @@
1
+ module StandardFlags
2
+ module Runtime
3
+ # The runtime-rule layer of the evaluation chain, between the ENV pin and
4
+ # the code default. Returns nil (so the code default serves) unless
5
+ # runtime rules are on, the snapshot has loaded, and the flag's rule
6
+ # decides.
7
+ #
8
+ # By status:
9
+ #
10
+ # * draft, paused — nil; a paused rule keeps its settings for Start.
11
+ # * stopped — `stop_value` for everyone (STATIC, "stopped").
12
+ # * running — the first of these that answers:
13
+ # 1. direct memberships of this unit; one serving the off value (deny)
14
+ # wins over any other (TARGETING_MATCH, "deny" / "allow");
15
+ # 2. attached cohorts the unit belongs to; one serving the off value
16
+ # wins, else the first in declared order ("cohort:<key>");
17
+ # 3. segments, asked of `config.segment_resolver` ("segment:<name>");
18
+ # 4. client conditions (platforms, version ranges); when unmet, skip
19
+ # straight to the fallthrough;
20
+ # 5. the percentage: a unit whose rollout bucket is below
21
+ # `percentage_bps` gets the variant weights' pick when there are
22
+ # weights ("variants"), else `rollout_value` ("percentage"), both
23
+ # SPLIT; with weights and no percentage, every unit gets a variant;
24
+ # 6. `fallthrough_value` (TARGETING_MATCH, "fallthrough"), else nil.
25
+ #
26
+ # A rule that needs the unit when the context has no key for it returns
27
+ # the fallthrough (or the code default) with TARGETING_KEY_MISSING. A
28
+ # stored value or shape the flag can't take fails only this flag (its
29
+ # fail value, PARSE_ERROR), reported once. A kill switch served false
30
+ # reads as KILL_SWITCH.
31
+ #
32
+ # When the unit's membership lookup fails, steps 1 and 2 are skipped and
33
+ # the rest still decide, marked ERROR / GENERAL with the deciding step's
34
+ # rule_id (none for the code default). The failure is memoised for the
35
+ # unit of work and reported once, so it costs one failed query.
36
+ class Resolver
37
+ # A stored rule this flag can't serve. Internal; reported as RuleInvalid.
38
+ class Invalid < StandardError; end
39
+
40
+ def call(request)
41
+ return unless Runtime.enabled?
42
+
43
+ snapshot = Runtime.snapshot
44
+ return unless snapshot.loaded
45
+
46
+ rule = snapshot.rule(request.definition.key)
47
+ return unless rule
48
+
49
+ Runtime.tracker.track(rule.key) unless EvaluationTracker.untracked?
50
+ Decision.new(request, rule, snapshot).call
51
+ rescue Invalid => e
52
+ invalid(request.definition, e)
53
+ end
54
+
55
+ private
56
+
57
+ def invalid(definition, error)
58
+ Reporting.once(:rule_invalid, definition.key, error.message) do
59
+ Reporting.instrument(:rule_invalid, key: definition.key, error: error.message)
60
+ Reporting.report(RuleInvalid.new("runtime rule for :#{definition.key} #{error.message}"), flag: definition.key.to_s)
61
+ end
62
+ Evaluation.build(definition, definition.fail_value, reason: Reason::ERROR, error_code: ErrorCode::PARSE_ERROR)
63
+ end
64
+
65
+ # One evaluation of one rule.
66
+ class Decision
67
+ attr_reader :definition, :context, :rule, :snapshot
68
+
69
+ def initialize(request, rule, snapshot)
70
+ @request = request
71
+ @definition = request.definition
72
+ @context = request.context
73
+ @rule = rule
74
+ @snapshot = snapshot
75
+ end
76
+
77
+ def call
78
+ if rule.stopped? then serve(rule.stop_value, "stop_value", Reason::STATIC, "stopped")
79
+ elsif rule.running? then running
80
+ elsif !rule.draft? && !rule.paused? then raise Invalid, "has unknown status #{rule.status.inspect}"
81
+ end
82
+ end
83
+
84
+ private
85
+
86
+ def running
87
+ key = unit_key
88
+ return missing_unit if key.nil? && rule.needs_unit?
89
+
90
+ members = key ? memberships(key) : []
91
+ return without_members(key) if members.equal?(LOOKUP_FAILED)
92
+
93
+ direct(members) || cohorts(members) || targeting(key)
94
+ end
95
+
96
+ def targeting(key)
97
+ segments || (client_conditions_met? && split(key)) || fallthrough
98
+ end
99
+
100
+ def without_members(key)
101
+ decided = targeting(key)
102
+ value = decided ? decided.value : definition.default_for(@request.env_name)
103
+ Evaluation.build(definition, value, reason: Reason::ERROR, error_code: ErrorCode::GENERAL, rule_id: decided&.rule_id)
104
+ end
105
+
106
+ def unit_key
107
+ Runtime.unit_key(@request.registry, definition, context)
108
+ end
109
+
110
+ # Skipped entirely when no direct member or attached cohort member
111
+ # could match.
112
+ def memberships(key)
113
+ return [] unless rule.members? || attached_cohorts.any? { |cohort, _| cohort.member_count.positive? }
114
+
115
+ found = Runtime.memberships(definition.unit, key)
116
+ return found if found.equal?(LOOKUP_FAILED)
117
+
118
+ now = Time.now
119
+ found.select { |membership| membership.live?(now) }
120
+ end
121
+
122
+ def direct(members)
123
+ values = members.select { |m| m.rule_id == rule.id }.map { |m| cast(m.value, "a membership value") }
124
+ return if values.empty?
125
+
126
+ denied = values.include?(definition.off_value)
127
+ build(denied ? definition.off_value : values.first, Reason::TARGETING_MATCH, denied ? "deny" : "allow")
128
+ end
129
+
130
+ def cohorts(members)
131
+ ids = members.filter_map(&:cohort_id)
132
+ matched = attached_cohorts.filter_map do |cohort, value|
133
+ [ cohort.key, cast(value, "cohort #{cohort.key}'s value") ] if ids.include?(cohort.id)
134
+ end
135
+ return if matched.empty?
136
+
137
+ key, value = matched.find { |_, served| served == definition.off_value } || matched.first
138
+ build(value, Reason::TARGETING_MATCH, "cohort:#{key}")
139
+ end
140
+
141
+ # [[Cohort, stored value], ...] for live cohorts of this flag's unit.
142
+ def attached_cohorts
143
+ @attached_cohorts ||= rule.cohort_attachments.filter_map do |key, value|
144
+ cohort = snapshot.cohort(key)
145
+ [ cohort, value ] if cohort && !cohort.archived? && cohort.unit == definition.unit
146
+ end
147
+ end
148
+
149
+ def segments
150
+ resolver = StandardFlags.config.segment_resolver
151
+ return unless resolver
152
+
153
+ rule.segments.each do |segment|
154
+ name = segment["name"].to_s
155
+ return serve(segment["value"], "segment #{name}'s value", Reason::TARGETING_MATCH, "segment:#{name}") if resolver.call(name, context)
156
+ end
157
+ nil
158
+ end
159
+
160
+ def client_conditions_met?
161
+ platforms = rule.platforms
162
+ versions = rule.versions
163
+ return true if platforms.empty? && versions.empty?
164
+
165
+ platform = context.client[:platform]&.to_s&.downcase
166
+ return false if platforms.any? && !platforms.include?(platform)
167
+
168
+ requirement = platform && versions[platform]
169
+ requirement.nil? || version_satisfies?(requirement, context.client[:version])
170
+ end
171
+
172
+ def version_satisfies?(requirement, version)
173
+ parsed = begin
174
+ Gem::Requirement.new(*requirement.to_s.split(",").map(&:strip))
175
+ rescue Gem::Requirement::BadRequirementError
176
+ raise Invalid, "has an invalid version range #{requirement.inspect}"
177
+ end
178
+ return false if version.to_s.strip.empty?
179
+
180
+ parsed.satisfied_by?(Gem::Version.new(version.to_s.strip))
181
+ rescue ArgumentError
182
+ false # an unparseable client version meets no range
183
+ end
184
+
185
+ def split(key)
186
+ bps = rule.percentage_bps
187
+ return if bps.nil? && rule.weights.empty?
188
+ raise Invalid, "has percentage_bps #{bps.inspect} outside 0..10000" if bps && !(0..Bucket::BUCKETS).cover?(bps)
189
+ return if bps && bucket("rollout", key) >= bps
190
+ return variants(key) if rule.weights.any?
191
+
192
+ serve(rule.rollout_value || default_rollout_value, "rollout_value", Reason::SPLIT, "percentage")
193
+ end
194
+
195
+ # Booleans roll out to "on"; other kinds must name the value.
196
+ def default_rollout_value
197
+ definition.boolean? ? "on" : nil
198
+ end
199
+
200
+ def variants(key)
201
+ weights = rule.weights.to_h { |variant, weight| [ cast(variant, "variant weights"), weight ] }
202
+ unless weights.values.all?(Integer) && weights.values.all? { |w| w >= 0 } && weights.values.sum == Bucket::BUCKETS
203
+ raise Invalid, "has variant weights that don't sum to #{Bucket::BUCKETS}"
204
+ end
205
+
206
+ position = bucket("variant", key)
207
+ upper = 0
208
+ value = definition.allowed_values.find { |candidate| position < (upper += weights.fetch(candidate, 0)) }
209
+ build(value, Reason::SPLIT, "variants")
210
+ end
211
+
212
+ def bucket(decision, key)
213
+ case rule.hash_version
214
+ when 1 then Bucket.v1(rule.salt, key)
215
+ when 2 then Bucket.v2(decision, rule.salt, key)
216
+ else raise Invalid, "has unknown hash_version #{rule.hash_version.inspect}"
217
+ end
218
+ end
219
+
220
+ def fallthrough
221
+ return if rule.fallthrough_value.nil?
222
+
223
+ serve(rule.fallthrough_value, "fallthrough_value", Reason::TARGETING_MATCH, "fallthrough")
224
+ end
225
+
226
+ def missing_unit
227
+ Reporting.instrument(:targeting_key_missing, key: definition.key, unit: definition.unit)
228
+ if rule.fallthrough_value
229
+ value = cast(rule.fallthrough_value, "fallthrough_value")
230
+ rule_id = "fallthrough"
231
+ else
232
+ value = definition.default_for(@request.env_name)
233
+ end
234
+ Evaluation.build(definition, value, reason: Reason::ERROR, error_code: ErrorCode::TARGETING_KEY_MISSING,
235
+ rule_id: rule_id)
236
+ end
237
+
238
+ def serve(stored, field, reason, rule_id)
239
+ build(cast(stored, field), reason, rule_id)
240
+ end
241
+
242
+ def build(value, reason, rule_id)
243
+ reason = Reason::KILL_SWITCH if definition.kill_switch? && value == false
244
+ Evaluation.build(definition, value, reason: reason, rule_id: rule_id)
245
+ end
246
+
247
+ def cast(stored, field)
248
+ value = definition.value_from_wire(stored)
249
+ raise Invalid, "has #{stored.inspect} in #{field}, not one of #{definition.allowed_values.map { |v| Runtime.wire(v) }.join('/')}" if value.equal?(Parser::INVALID)
250
+
251
+ value
252
+ end
253
+ end
254
+ end
255
+ end
256
+ end
@@ -0,0 +1,60 @@
1
+ module StandardFlags
2
+ module Runtime
3
+ # The process-wide view of the rules table: every rule, plus each cohort's
4
+ # key, unit and member count (never its members). Immutable, so any
5
+ # thread can read it while the cache swaps in a newer one.
6
+ #
7
+ # * revision — standard_flags_state.revision when it was loaded.
8
+ # * loaded — false until a load has succeeded in this process; the
9
+ # resolver then defers to code defaults.
10
+ # * stale — the last refresh failed, so this is the last good copy.
11
+ # * loaded_at — wall-clock time of the last successful load.
12
+ # * checked_at — monotonic time of the last revision check (or attempt).
13
+ RuleSnapshot = Data.define(:revision, :rules, :cohorts, :cohorts_by_id, :loaded, :stale, :loaded_at, :checked_at) do
14
+ def self.empty(checked_at: nil)
15
+ new(revision: nil, rules: {}.freeze, cohorts: {}.freeze, cohorts_by_id: {}.freeze,
16
+ loaded: false, stale: false, loaded_at: nil, checked_at: checked_at)
17
+ end
18
+
19
+ # `revision` is the one read just before `loaded`, so a write in between
20
+ # only makes the next check reload again.
21
+ def self.build(loaded, revision:, checked_at:, loaded_at: Time.now.utc)
22
+ cohorts = loaded.cohorts.to_h { |cohort| [ cohort.key, cohort ] }.freeze
23
+ new(
24
+ revision: revision,
25
+ rules: loaded.rules.to_h { |rule| [ rule.key, rule ] }.freeze,
26
+ cohorts: cohorts,
27
+ cohorts_by_id: cohorts.values.to_h { |cohort| [ cohort.id, cohort ] }.freeze,
28
+ loaded: true, stale: false, loaded_at: loaded_at, checked_at: checked_at
29
+ )
30
+ end
31
+
32
+ def rule(key)
33
+ rules[key.to_sym]
34
+ end
35
+
36
+ def cohort(key)
37
+ cohorts[key.to_s]
38
+ end
39
+
40
+ # Seconds since the last successful load, or nil if there never was one.
41
+ def age(now = Time.now.utc)
42
+ loaded_at && (now - loaded_at).round(3)
43
+ end
44
+
45
+ # Running rules for flags of `unit` that have direct members or an
46
+ # attached cohort with members: the only ones a membership lookup can
47
+ # change. A malformed rule doesn't count; evaluating it fails that flag.
48
+ def member_rules?(registry, unit)
49
+ rules.each_value.any? do |rule|
50
+ definition = registry[rule.key]
51
+ next false unless rule.running? && definition && definition.unit == unit
52
+
53
+ rule.members? || rule.cohort_attachments.any? { |key, _| cohort(key)&.member_count.to_i.positive? }
54
+ rescue Resolver::Invalid
55
+ false
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,161 @@
1
+ module StandardFlags
2
+ module Runtime
3
+ # Raised by a store when it can't read. The message names the failing
4
+ # read and the underlying error class, never a unit key.
5
+ class StoreError < StandardFlags::Error
6
+ # The class name of the error underneath, which is deliberately not
7
+ # kept as `cause` (a driver message can quote a unit key).
8
+ attr_reader :cause_class
9
+
10
+ def initialize(message, cause_class: nil)
11
+ super(message)
12
+ @cause_class = cause_class
13
+ end
14
+ end
15
+
16
+ # Where runtime rules come from. The read path calls four methods:
17
+ #
18
+ # * revision — the current standard_flags_state
19
+ # revision (Integer), or nil when there
20
+ # is none yet; the cache then reloads at
21
+ # every check.
22
+ # * load — a Loaded with every rule and cohort.
23
+ # The cache calls it after `revision`.
24
+ # * memberships(unit, unit_keys) — live (not removed) memberships for
25
+ # those keys of one unit, across every
26
+ # rule and cohort, in one read.
27
+ # * ready? — whether the tables exist, for the
28
+ # health check. Return false when they
29
+ # are missing; raise when the store
30
+ # can't be reached, so the check can
31
+ # tell the two apart.
32
+ #
33
+ # Optionally, `warnings` returns strings for the health check (a
34
+ # configuration that exposes unit keys, say).
35
+ #
36
+ # The write path (StandardFlags::Operations) calls `write`, which runs
37
+ # its block in one transaction and yields a store-specific transaction
38
+ # object with these methods. Anything the block raises rolls the whole
39
+ # write back, and `write` must raise rather than return when the write
40
+ # did not commit.
41
+ #
42
+ # * isolated { } — runs the block in a savepoint; an error
43
+ # in it rolls back only the block, and is
44
+ # raised from here.
45
+ # * after_commit { } — runs the block once the write has
46
+ # committed (with the host's transaction,
47
+ # inside one), never after a rollback.
48
+ # * lock_rule(key) — the Rule for `key`, locked until the
49
+ # write ends, or nil.
50
+ # * create_rule(key, salt:, hash_version:)
51
+ # — creates a draft rule (or, if another
52
+ # writer just did, returns theirs), locked.
53
+ # * save_rule(rule, attributes) — updates the rule and returns it, with
54
+ # lock_version moved on by one.
55
+ # * lock_cohort(key) / create_cohort(key, unit:, name:, description:) /
56
+ # save_cohort(cohort, attributes)
57
+ # — the same for cohorts, except that
58
+ # create_cohort returns nil when the key
59
+ # is taken, even by a concurrent writer.
60
+ # * lock_cohorts(keys) — `{ key => Cohort }` for those that
61
+ # exist, locked in id order.
62
+ # * rules_attached_to(cohort_key) — keys of rules that attach a cohort.
63
+ # * upsert_members(owner, unit:, unit_keys:, value:, expires_at:)
64
+ # — adds live memberships to a Rule or
65
+ # Cohort. A live one whose value or expiry
66
+ # changes is versioned: marked removed,
67
+ # and a new row added (so members_at can
68
+ # read it back); an unchanged one is left
69
+ # alone. Returns { added:, updated: }.
70
+ # * remove_members(owner, unit:, unit_keys:)
71
+ # — sets removed_at on live ones; returns
72
+ # the number removed.
73
+ # * count_members(owner, now: nil) — memberships not removed (and, with
74
+ # `now`, not expired).
75
+ # * lock_revision / bump_revision — the state revision, locked; then
76
+ # moved to a number never used before (a
77
+ # sequence, so a rolled-back write's
78
+ # number is not reused) and returned.
79
+ # Both create the state row if it is
80
+ # missing. Call bump_revision through
81
+ # Runtime.bump_revision!.
82
+ #
83
+ # Maintenance, outside a write:
84
+ #
85
+ # * purge(before:) — hard-deletes memberships removed or
86
+ # expired before `before`; returns counts.
87
+ # * purgeable(before:) — the same counts, deleting nothing.
88
+ # * touch_evaluated(keys, before:)
89
+ # — sets last_evaluated_at on those rules
90
+ # where it is unset or older than `before`,
91
+ # in one statement that never waits on a
92
+ # lock and changes nothing else on the
93
+ # rule; nil when it didn't run (and should
94
+ # be tried again).
95
+ #
96
+ # Operator reads (the MCP tools, the admin page, Restore), outside a
97
+ # write. Each takes `rule:` (a flag key) or `cohort:` (a cohort key):
98
+ #
99
+ # * members(rule:|cohort:, offset:, limit:)
100
+ # — a MemberPage of the owner's memberships
101
+ # that are not removed (expired ones
102
+ # included), oldest first, with
103
+ # created_at set; an empty page when the
104
+ # owner doesn't exist.
105
+ # * members_at(at, rule:|cohort:)
106
+ # — the owner's memberships as they were at
107
+ # `at`: created at or before it, not yet
108
+ # removed and not yet expired then. Needs
109
+ # the removed rows, so only as far back as
110
+ # `config.membership_retention`.
111
+ #
112
+ # Implementations: ActiveRecordStore (the default when runtime rules are
113
+ # on) and MemoryStore (specs, and apps without a database).
114
+ class Store
115
+ def revision
116
+ raise NotImplementedError, "#{self.class} must implement revision"
117
+ end
118
+
119
+ def load
120
+ raise NotImplementedError, "#{self.class} must implement load"
121
+ end
122
+
123
+ def memberships(_unit, _unit_keys)
124
+ raise NotImplementedError, "#{self.class} must implement memberships"
125
+ end
126
+
127
+ def ready?
128
+ true
129
+ end
130
+
131
+ def write
132
+ raise StoreError, "#{self.class} does not support writes"
133
+ end
134
+
135
+ def purge(before:) # rubocop:disable Lint/UnusedMethodArgument
136
+ raise StoreError, "#{self.class} does not support purge"
137
+ end
138
+
139
+ def purgeable(before:) # rubocop:disable Lint/UnusedMethodArgument
140
+ raise StoreError, "#{self.class} does not support purge"
141
+ end
142
+
143
+ def members(rule: nil, cohort: nil, offset: 0, limit: nil) # rubocop:disable Lint/UnusedMethodArgument
144
+ raise StoreError, "#{self.class} does not support listing members"
145
+ end
146
+
147
+ def members_at(_at, rule: nil, cohort: nil) # rubocop:disable Lint/UnusedMethodArgument
148
+ raise StoreError, "#{self.class} does not support reading past members"
149
+ end
150
+
151
+ # nil means "not done": a store that doesn't track evaluations.
152
+ def touch_evaluated(_keys, before:) # rubocop:disable Lint/UnusedMethodArgument
153
+ nil
154
+ end
155
+
156
+ def warnings
157
+ []
158
+ end
159
+ end
160
+ end
161
+ end
@@ -0,0 +1,181 @@
1
+ require "time"
2
+
3
+
4
+ module StandardFlags
5
+ module Runtime
6
+ # Immutable, store-independent copies of runtime rows. Stores build them;
7
+ # the resolver reads them. Values are the stored strings ("on", "off", a
8
+ # mode value or a variant); the resolver casts them through the flag's
9
+ # definition.
10
+ module Values
11
+ STATUSES = %w[draft running paused stopped].freeze
12
+
13
+ module_function
14
+
15
+ def deep_freeze(value)
16
+ case value
17
+ when Hash then value.to_h { |k, v| [ k.to_s.freeze, deep_freeze(v) ] }.freeze
18
+ when Array then value.map { |v| deep_freeze(v) }.freeze
19
+ when String then value.dup.freeze
20
+ else value
21
+ end
22
+ end
23
+ end
24
+
25
+ # One flag's runtime rule (a row of standard_flags_rules).
26
+ Rule = Data.define(
27
+ :id, :key, :status, :hash_version, :salt, :percentage_bps, :rollout_value, :variant_weights,
28
+ :fallthrough_value, :stop_value, :conditions, :cohorts, :member_count, :lock_version, :full_since,
29
+ :last_evaluated_at, :updated_at
30
+ ) do
31
+ def self.build(**attributes)
32
+ new(
33
+ id: attributes[:id],
34
+ key: attributes.fetch(:key).to_sym,
35
+ status: attributes.fetch(:status, "draft").to_s.freeze,
36
+ hash_version: attributes.fetch(:hash_version, 2),
37
+ salt: attributes.fetch(:salt).to_s.freeze,
38
+ percentage_bps: attributes[:percentage_bps],
39
+ rollout_value: attributes[:rollout_value]&.to_s&.freeze,
40
+ variant_weights: Values.deep_freeze(attributes[:variant_weights] || {}),
41
+ fallthrough_value: attributes[:fallthrough_value]&.to_s&.freeze,
42
+ stop_value: attributes[:stop_value]&.to_s&.freeze,
43
+ conditions: Values.deep_freeze(attributes[:conditions] || {}),
44
+ cohorts: Values.deep_freeze(attributes[:cohorts] || []),
45
+ member_count: attributes.fetch(:member_count, 0).to_i,
46
+ lock_version: attributes.fetch(:lock_version, 0).to_i,
47
+ full_since: attributes[:full_since],
48
+ last_evaluated_at: attributes[:last_evaluated_at],
49
+ updated_at: attributes[:updated_at]
50
+ )
51
+ end
52
+
53
+ Values::STATUSES.each do |name|
54
+ define_method(:"#{name}?") { status == name }
55
+ end
56
+
57
+ # The accessors below check the stored shapes that jsonb allows but a
58
+ # rule can't have, raising Resolver::Invalid so only that flag fails,
59
+ # with PARSE_ERROR.
60
+
61
+ # `[{ "name" => n, "value" => v }, ...]`
62
+ def segments
63
+ list = shaped(condition("segments") || [], Array, "conditions.segments")
64
+ list.each { |segment| shaped(segment, Hash, "each of conditions.segments") }
65
+ end
66
+
67
+ def platforms
68
+ shaped(condition("platforms") || [], Array, "conditions.platforms").map { |platform| platform.to_s.downcase }
69
+ end
70
+
71
+ # `{ "android" => ">= 1.4.0" }`
72
+ def versions
73
+ shaped(condition("versions") || {}, Hash, "conditions.versions")
74
+ .to_h { |platform, requirement| [ platform.to_s.downcase, requirement ] }
75
+ end
76
+
77
+ # `{ variant => weight }`
78
+ def weights
79
+ shaped(variant_weights, Hash, "variant_weights")
80
+ end
81
+
82
+ # `[[cohort_key, value], ...]` in declared order.
83
+ def cohort_attachments
84
+ shaped(cohorts, Array, "cohorts").map do |attachment|
85
+ shaped(attachment, Hash, "each of cohorts")
86
+ [ attachment["cohort"].to_s, attachment["value"] ]
87
+ end
88
+ end
89
+
90
+ def members?
91
+ member_count.positive?
92
+ end
93
+
94
+ # Whether serving this rule needs the flag's unit key.
95
+ def needs_unit?
96
+ members? || cohort_attachments.any? || segments.any? || !percentage_bps.nil? || weights.any?
97
+ end
98
+
99
+ # The rule's state as audit rows and notifications record it: every
100
+ # setting, never a member.
101
+ def audit_state
102
+ {
103
+ status: status, hash_version: hash_version, salt: salt, percentage_bps: percentage_bps,
104
+ rollout_value: rollout_value, variant_weights: variant_weights, fallthrough_value: fallthrough_value,
105
+ stop_value: stop_value, conditions: conditions, cohorts: cohorts, member_count: member_count,
106
+ lock_version: lock_version, full_since: full_since&.utc&.iso8601
107
+ }
108
+ end
109
+
110
+ private
111
+
112
+ def condition(name)
113
+ shaped(conditions, Hash, "conditions")[name]
114
+ end
115
+
116
+ def shaped(value, type, field)
117
+ return value if value.is_a?(type)
118
+
119
+ raise Resolver::Invalid, "has a malformed #{field} (expected #{type == Hash ? 'an object' : 'a list'})"
120
+ end
121
+ end
122
+
123
+ # A named, reusable member list (a row of standard_flags_cohorts).
124
+ Cohort = Data.define(:id, :key, :name, :description, :unit, :member_count, :archived_at) do
125
+ def self.build(**attributes)
126
+ new(
127
+ id: attributes[:id],
128
+ key: attributes.fetch(:key).to_s.freeze,
129
+ name: attributes[:name]&.to_s&.freeze,
130
+ description: attributes[:description]&.to_s&.freeze,
131
+ unit: attributes.fetch(:unit).to_sym,
132
+ member_count: attributes.fetch(:member_count, 0).to_i,
133
+ archived_at: attributes[:archived_at]
134
+ )
135
+ end
136
+
137
+ def archived?
138
+ !archived_at.nil?
139
+ end
140
+
141
+ # The cohort as audit rows and notifications record it, without members.
142
+ def audit_state
143
+ { key: key, name: name, description: description, unit: unit.to_s, member_count: member_count,
144
+ archived_at: archived_at&.utc&.iso8601 }
145
+ end
146
+ end
147
+
148
+ # One live membership of a unit in a rule or a cohort. Stores never
149
+ # return removed memberships; expired ones are dropped at read time.
150
+ # `created_at` is set by the operator reads (Store#members,
151
+ # Store#members_at) and may be nil on the read path.
152
+ Membership = Data.define(:rule_id, :cohort_id, :unit, :unit_key, :value, :expires_at, :created_at) do
153
+ def initialize(created_at: nil, **attributes)
154
+ super
155
+ end
156
+
157
+ def live?(now)
158
+ expires_at.nil? || expires_at > now
159
+ end
160
+
161
+ # Keeps unit keys (phone numbers, emails) out of logs and consoles.
162
+ def inspect
163
+ "#<StandardFlags::Runtime::Membership unit=#{unit} rule_id=#{rule_id.inspect} cohort_id=#{cohort_id.inspect}>"
164
+ end
165
+ alias_method :to_s, :inspect
166
+
167
+ # pp and IRB's inspector would otherwise print every member. `to_h`
168
+ # still includes the unit key.
169
+ def pretty_print(q)
170
+ q.text(inspect)
171
+ end
172
+ end
173
+
174
+ # Everything a store returns from one load.
175
+ Loaded = Data.define(:rules, :cohorts)
176
+
177
+ # One page of an owner's memberships (Store#members): `total` counts
178
+ # every membership not removed, expired ones included.
179
+ MemberPage = Data.define(:memberships, :total)
180
+ end
181
+ end