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,43 @@
1
+ module StandardFlags
2
+ # What every operation returns, in the shape the host apps' own operations
3
+ # use: `success?`, `value` and `errors` (human-readable messages), plus
4
+ # `code`, a Symbol a caller can branch on:
5
+ #
6
+ # result = StandardFlags::Operations::Ramp.call(:new_checkout, bps: 500, actor: user, reason: "canary")
7
+ # result.success? # => true
8
+ # result.value # => { key: :new_checkout, rule: {...}, revision: 3, store_revision: 12 }
9
+ #
10
+ # result.code # on failure, e.g. :pinned_by_env, :stale_revision,
11
+ # # :unauthorized, :invalid, :limit_exceeded
12
+ class Result
13
+ attr_reader :value, :errors, :code
14
+
15
+ def self.success(value)
16
+ new(success: true, value: value)
17
+ end
18
+
19
+ def self.failure(code, errors)
20
+ new(success: false, code: code, errors: Array(errors))
21
+ end
22
+
23
+ def initialize(success:, value: nil, errors: [], code: nil)
24
+ @success = success
25
+ @value = value
26
+ @errors = errors.map(&:to_s).freeze
27
+ @code = code
28
+ freeze
29
+ end
30
+
31
+ def success?
32
+ @success
33
+ end
34
+
35
+ def failure?
36
+ !@success
37
+ end
38
+
39
+ def inspect
40
+ success? ? "#<StandardFlags::Result success>" : "#<StandardFlags::Result failure #{code} #{errors.inspect}>"
41
+ end
42
+ end
43
+ end
@@ -13,10 +13,25 @@ require "standard_flags"
13
13
  #
14
14
  # it "shows the new checkout", flags: { new_checkout: true } do ... end
15
15
  #
16
+ # Runtime rules, held in an in-memory store for the example (no database,
17
+ # whatever the app's own runtime configuration):
18
+ #
19
+ # with_rule(:new_checkout, percentage: 5_000) # running, 50%
20
+ # with_rule(:new_checkout, status: :paused)
21
+ # with_members(:new_checkout, account, value: false) # a deny
22
+ # with_cohort(:staff, unit: :account, members: [ a, b ])
23
+ # with_rule(:new_checkout, cohorts: { staff: true })
24
+ #
16
25
  # Overrides are the first evaluation layer, so they beat `forbidden_in:`
17
26
  # guards, ENV pins and defaults: prove a guard with a real ENV pin, not an
18
- # override. Unknown keys and values outside the declaration raise, unknown
19
- # keys raise on read (strict mode), and everything resets after each example.
27
+ # override. Runtime rules sit below overrides and pins, so `with_flag` beats
28
+ # `with_rule`. Unknown keys and values outside the declaration raise, unknown
29
+ # keys raise on read (strict mode), and everything resets around each example.
30
+ #
31
+ # Any of these may be set in the example, in a `before` hook, or in an
32
+ # `around` hook that wraps `example.run`:
33
+ #
34
+ # around { |example| with_flag(:new_checkout, true) { example.run } }
20
35
  module StandardFlags
21
36
  module TestHelpers
22
37
  def with_flag(key, value, &)
@@ -31,6 +46,19 @@ module StandardFlags
31
46
  apply_override(key, value, :experiment, &)
32
47
  end
33
48
 
49
+ # See StandardFlags::Testing.rule for the options.
50
+ def with_rule(key, **options)
51
+ StandardFlags::Testing.rule(key, **options)
52
+ end
53
+
54
+ def with_members(key, units, value: true, expires_at: nil)
55
+ StandardFlags::Testing.members(key, units, value: value, expires_at: expires_at)
56
+ end
57
+
58
+ def with_cohort(key, unit:, members: [], expires_at: nil, archived: false)
59
+ StandardFlags::Testing.cohort(key, unit: unit, members: members, expires_at: expires_at, archived: archived)
60
+ end
61
+
34
62
  private
35
63
 
36
64
  def apply_override(key, value, kind, &block)
@@ -39,20 +67,46 @@ module StandardFlags
39
67
  StandardFlags::Testing.override(key, value, kind: kind)
40
68
  end
41
69
  end
42
- end
43
70
 
44
- StandardFlags::Testing.activate!
45
- StandardFlags.config.strict = true
71
+ # Wires the helpers into an RSpec configuration. `require
72
+ # "standard_flags/rspec"` calls it on RSpec's own; call it directly only
73
+ # for a custom or sandboxed configuration.
74
+ #
75
+ # The reset is an `around` hook, not `before`/`after`: config-level
76
+ # `around` hooks wrap every group-level one, and `before` hooks run inside
77
+ # `example.run`, so a reset in `before` would discard what a spec's own
78
+ # `around { |ex| with_flag(:x, true) { ex.run } }` had just set. `flags:`
79
+ # metadata is applied in `before`, so it works as before and wins over an
80
+ # `around` override of the same key.
81
+ module RSpecSupport
82
+ module_function
83
+
84
+ def install(config)
85
+ config.include TestHelpers
86
+ config.around { |example| RSpecSupport.isolate(example) }
87
+ config.before { |example| RSpecSupport.apply_metadata(example) }
88
+ end
46
89
 
47
- RSpec.configure do |config|
48
- config.include StandardFlags::TestHelpers
90
+ def isolate(example)
91
+ unless Testing.overrides.empty? && Testing.runtime_store.nil?
92
+ raise Error, "standard_flags test overrides were set before the example started (in before(:context), " \
93
+ "at load time, or in a config.around hook registered before require \"standard_flags/rspec\"); " \
94
+ "they would be discarded. Set them inside the example, in a before hook, or in a group-level around hook"
95
+ end
49
96
 
50
- config.before do |example|
51
- StandardFlags::Testing.reset!
52
- Array(example.metadata[:flags]).each { |key, value| StandardFlags::Testing.override(key, value) }
53
- end
97
+ Testing.reset!
98
+ example.run
99
+ ensure
100
+ Testing.reset!
101
+ end
54
102
 
55
- config.after do
56
- StandardFlags::Testing.reset!
103
+ def apply_metadata(example)
104
+ Array(example.metadata[:flags]).each { |key, value| Testing.override(key, value) }
105
+ end
57
106
  end
58
107
  end
108
+
109
+ StandardFlags::Testing.activate!
110
+ StandardFlags.config.strict = true
111
+
112
+ RSpec.configure { |config| StandardFlags::RSpecSupport.install(config) }
@@ -0,0 +1,428 @@
1
+ require "standard_flags/runtime/models"
2
+
3
+ module StandardFlags
4
+ module Runtime
5
+ # The default store when runtime rules are on: the four tables written by
6
+ # `bin/rails g standard_flags:migrations`, read through the host's
7
+ # ActiveRecord connection. Required (with ActiveRecord) only when runtime
8
+ # rules are on and no other store is configured.
9
+ #
10
+ # Inside a host transaction each read runs in a savepoint, so a failed
11
+ # read can't abort the host's transaction. Read errors are re-raised as
12
+ # StoreError without the driver's message for membership reads, which
13
+ # could quote a unit key.
14
+ class ActiveRecordStore < Store
15
+ TABLES = %w[standard_flags_rules standard_flags_cohorts standard_flags_memberships standard_flags_state].freeze
16
+ RULE_COLUMNS = %i[
17
+ id key status hash_version salt percentage_bps rollout_value variant_weights fallthrough_value
18
+ stop_value conditions cohorts member_count lock_version full_since last_evaluated_at updated_at
19
+ ].freeze
20
+ COHORT_COLUMNS = %i[id key name description unit member_count archived_at].freeze
21
+ MEMBERSHIP_COLUMNS = %i[rule_id cohort_id unit unit_key value expires_at].freeze
22
+ NEXT_REVISION = "nextval(pg_get_serial_sequence('standard_flags_state', 'revision'))".freeze
23
+ BUMP_REVISION = "UPDATE standard_flags_state SET revision = #{NEXT_REVISION} RETURNING revision".freeze
24
+ # Seeds the single row when it is missing (a database built from
25
+ # schema.rb or structure.sql never ran the migration's insert). Runs
26
+ # under LOCK_STATE, so two writers can't both insert one.
27
+ SEED_STATE = "INSERT INTO standard_flags_state (revision) SELECT #{NEXT_REVISION} " \
28
+ "WHERE NOT EXISTS (SELECT 1 FROM standard_flags_state)".freeze
29
+ LOCK_STATE = "LOCK TABLE standard_flags_state IN SHARE ROW EXCLUSIVE MODE".freeze
30
+ MEMBERSHIP_INSERT_COLUMNS = %i[rule_id cohort_id unit unit_key value expires_at created_at updated_at].freeze
31
+
32
+ # nil when standard_flags_state has no row yet: there is no revision,
33
+ # and the cache reloads at every check until a write creates one.
34
+ def revision
35
+ read("revision check") { Models::State.pick(:revision) }
36
+ end
37
+
38
+ def load
39
+ read("rule load") do
40
+ Loaded.new(
41
+ rules: Models::Rule.pluck(*RULE_COLUMNS).map { |row| Rule.build(**RULE_COLUMNS.zip(row).to_h) },
42
+ cohorts: Models::Cohort.pluck(*COHORT_COLUMNS).map { |row| Cohort.build(**COHORT_COLUMNS.zip(row).to_h) }
43
+ )
44
+ end
45
+ end
46
+
47
+ def memberships(unit, unit_keys)
48
+ read("membership lookup", quote: false) do
49
+ Models::Membership.where(unit: unit.to_s, unit_key: unit_keys, removed_at: nil)
50
+ .pluck(*MEMBERSHIP_COLUMNS)
51
+ .map { |row| membership(row) }
52
+ end
53
+ end
54
+
55
+ # Two queries (the owner's id, then the page) and a count. Unit keys
56
+ # are read but never put into SQL text.
57
+ def members(rule: nil, cohort: nil, offset: 0, limit: nil)
58
+ read("member listing", quote: false) do
59
+ scope = owner_scope(rule, cohort)
60
+ next MemberPage.new(memberships: [], total: 0) unless scope
61
+
62
+ live = scope.where(removed_at: nil)
63
+ page = live.order(:created_at, :id).offset(offset)
64
+ page = page.limit(limit) if limit
65
+ MemberPage.new(memberships: page.pluck(*MEMBERSHIP_COLUMNS, :created_at).map { |row| membership(row) },
66
+ total: live.count)
67
+ end
68
+ end
69
+
70
+ # Rows removed (or expired) since `at` are still here until purge, so
71
+ # this reads the table as it was then.
72
+ def members_at(at, rule: nil, cohort: nil)
73
+ read("past member read", quote: false) do
74
+ scope = owner_scope(rule, cohort)
75
+ next [] unless scope
76
+
77
+ scope.where(created_at: ..at)
78
+ .where("removed_at IS NULL OR removed_at > ?", at)
79
+ .where("expires_at IS NULL OR expires_at > ?", at)
80
+ .order(:created_at, :id)
81
+ .pluck(*MEMBERSHIP_COLUMNS, :created_at).map { |row| membership(row) }
82
+ end
83
+ end
84
+
85
+ # false when a table is missing; raises (so the health check warns
86
+ # instead of failing) when the database can't be reached.
87
+ def ready?
88
+ Models::Record.with_connection { |connection| TABLES.all? { |table| connection.data_source_exists?(table) } }
89
+ rescue ::ActiveRecord::StatementInvalid => e
90
+ raise unless e.cause&.class&.name == "PG::UndefinedTable"
91
+
92
+ false
93
+ end
94
+
95
+ # With prepared statements off (common behind a transaction-mode
96
+ # pooler), bind values are inlined into the SQL text, so unit keys reach
97
+ # SQL logs, notification payloads and APM spans unfiltered.
98
+ def warnings
99
+ list = []
100
+ unless prepared_statements?
101
+ list << "prepared statements are off, so unit keys are inlined into membership lookup SQL " \
102
+ "(logs, APM spans); see the README's runtime rules privacy notes"
103
+ end
104
+ if state_row_missing?
105
+ list << "standard_flags_state has no row (a database loaded from schema.rb skips the migration's " \
106
+ "insert); the next change creates it, and until then every check reloads the rules"
107
+ end
108
+ list
109
+ end
110
+
111
+ # One write (see Store), in a transaction, or a savepoint inside the
112
+ # host's own transaction, so it commits or rolls back with it. Database
113
+ # errors are re-raised as StoreError naming only the error class: a
114
+ # driver message can quote a unit key.
115
+ #
116
+ # Its last statement is a `SELECT 1`. Postgres answers COMMIT on a
117
+ # transaction that a swallowed error aborted with a silent ROLLBACK,
118
+ # and ActiveRecord still runs after_commit callbacks; the check makes
119
+ # that case raise here, so the write fails instead of reporting a
120
+ # change that never committed.
121
+ def write
122
+ Models::Record.transaction(requires_new: true) do
123
+ transaction = Transaction.new
124
+ yield(transaction).tap { transaction.verify! }
125
+ end
126
+ rescue ::ActiveRecord::ActiveRecordError => e
127
+ raise StoreError.new("write failed: #{e.class}", cause_class: e.class.name), cause: nil
128
+ end
129
+
130
+ # Locks the owners of expired memberships first (rules, then cohorts,
131
+ # each by id, as every write does), then deletes and recounts. The
132
+ # recount is a new statement after the locks, so it sees any
133
+ # AddMembers that committed while purge waited.
134
+ def purge(before:)
135
+ guard("purge") do
136
+ Models::Record.transaction(requires_new: true) do
137
+ owners = expired_before(before).distinct.pluck(:rule_id, :cohort_id)
138
+ rule_ids = Models::Rule.where(id: owners.filter_map(&:first).uniq).order(:id).lock.pluck(:id)
139
+ cohort_ids = Models::Cohort.where(id: owners.filter_map(&:last).uniq).order(:id).lock.pluck(:id)
140
+ removed = Models::Membership.where(removed_at: ...before).delete_all
141
+ expired = expired_before(before).where(rule_id: rule_ids).or(expired_before(before).where(cohort_id: cohort_ids)).delete_all
142
+ unless expired.zero?
143
+ recount(Models::Rule, :rule_id, rule_ids)
144
+ recount(Models::Cohort, :cohort_id, cohort_ids)
145
+ Runtime.bump_revision!(Transaction.new)
146
+ end
147
+ { removed: removed, expired: expired }
148
+ end
149
+ end
150
+ end
151
+
152
+ def purgeable(before:)
153
+ guard("purge count") do
154
+ { removed: Models::Membership.where(removed_at: ...before).count, expired: expired_before(before).count }
155
+ end
156
+ end
157
+
158
+ # One UPDATE that never waits: rows another write holds are skipped
159
+ # (FOR UPDATE SKIP LOCKED), and it is skipped (nil) inside an open
160
+ # transaction. The assignment is SQL, not a Hash, so ActiveRecord
161
+ # leaves lock_version alone, and updated_at isn't touched: neither is
162
+ # a change to the rule.
163
+ def touch_evaluated(keys, before:)
164
+ return nil if Models::Record.connection_pool.active_connection&.transaction_open?
165
+
166
+ guard("evaluation tracking") do
167
+ due = Models::Rule.where(key: keys.map(&:to_s))
168
+ .where("last_evaluated_at IS NULL OR last_evaluated_at < ?", before)
169
+ .lock("FOR UPDATE SKIP LOCKED").select(:id)
170
+ Models::Record.with_connection do
171
+ Models::Rule.where(id: due).update_all([ "last_evaluated_at = ?", Time.now.utc ])
172
+ end
173
+ end
174
+ end
175
+
176
+ # One write's view of the tables. Rows are locked FOR UPDATE as they
177
+ # are read, and held until the write ends.
178
+ #
179
+ # Every write takes its locks in one order: the owner row (a rule or a
180
+ # cohort), then cohorts by id (lock_cohorts, one statement), then
181
+ # memberships, then the state row last (lock_revision, bump_revision).
182
+ # Purge locks the rules, then the cohorts, it is about to recount, each
183
+ # by id, before touching a membership. A write only ever waits on a
184
+ # row later in that order than every row it holds, so two of them
185
+ # can't wait on each other: Start and AttachCohort (rule, then its
186
+ # cohorts) against AddMembers on a cohort (that cohort, then its
187
+ # memberships) or on a rule (that rule, then its memberships), and
188
+ # purge against any of them.
189
+ class Transaction
190
+ def initialize
191
+ @rules = {}
192
+ @cohorts = {}
193
+ end
194
+
195
+ # Raises if a swallowed error aborted the transaction (see write).
196
+ def verify!
197
+ Models::Record.with_connection { |connection| connection.select_value("SELECT 1") }
198
+ end
199
+
200
+ # Runs the block in a savepoint: an error inside it, even one the
201
+ # block swallowed, rolls back only the savepoint and is raised here.
202
+ def isolated(&)
203
+ Models::Record.transaction(requires_new: true, &)
204
+ end
205
+
206
+ # Runs the block once the write commits: at the end of `write`, or
207
+ # when the host's own transaction commits. Never when it rolls back.
208
+ def after_commit(&)
209
+ Models::Record.current_transaction.after_commit(&)
210
+ end
211
+
212
+ def lock_rule(key)
213
+ record = Models::Rule.lock.find_by(key: key.to_s)
214
+ record && rule(@rules[record.key] = record)
215
+ end
216
+
217
+ # ON CONFLICT DO NOTHING, then the locking read: two writers creating
218
+ # the same rule end up holding the one row in turn.
219
+ def create_rule(key, salt:, hash_version:)
220
+ Models::Rule.insert_all([ { key: key.to_s, salt: salt, hash_version: hash_version, status: "draft" } ], unique_by: :key)
221
+ lock_rule(key)
222
+ end
223
+
224
+ # lock_version is ActiveRecord's optimistic-locking column, so
225
+ # update! moves it on by one.
226
+ def save_rule(rule, attributes)
227
+ record = @rules.fetch(rule.key.to_s)
228
+ record.update!(attributes.merge(updated_at: Time.now.utc))
229
+ rule(record)
230
+ end
231
+
232
+ def lock_cohort(key)
233
+ record = Models::Cohort.lock.find_by(key: key.to_s)
234
+ record && cohort(@cohorts[record.key] = record)
235
+ end
236
+
237
+ # One statement, locking in id order.
238
+ def lock_cohorts(keys)
239
+ return {} if keys.empty?
240
+
241
+ Models::Cohort.where(key: keys.map(&:to_s).uniq).order(:id).lock.to_a.to_h do |record|
242
+ [ record.key, cohort(@cohorts[record.key] = record) ]
243
+ end
244
+ end
245
+
246
+ # nil when the key was taken, by an earlier cohort or a writer that
247
+ # committed it while this one waited on the unique index.
248
+ def create_cohort(key, unit:, name: nil, description: nil)
249
+ inserted = Models::Cohort.insert_all([ { key: key.to_s, unit: unit.to_s, name: name, description: description } ],
250
+ unique_by: :key, returning: :id)
251
+ lock_cohort(key) unless inserted.rows.empty?
252
+ end
253
+
254
+ def save_cohort(cohort, attributes)
255
+ record = @cohorts.fetch(cohort.key)
256
+ record.update!(attributes.merge(updated_at: Time.now.utc))
257
+ cohort(record)
258
+ end
259
+
260
+ def rules_attached_to(cohort_key)
261
+ Models::Rule.where("cohorts @> ?", [ { cohort: cohort_key.to_s } ].to_json).order(:key).pluck(:key).map(&:to_sym)
262
+ end
263
+
264
+ # A live membership whose value or expiry changes is versioned, not
265
+ # edited: its row is marked removed and a new one inserted, so
266
+ # members_at (Restore) reads the value it had at any time within the
267
+ # retention. Re-adding it unchanged writes nothing.
268
+ def upsert_members(owner, unit:, unit_keys:, value:, expires_at:)
269
+ live = members_of(owner).where(unit: unit.to_s, unit_key: unit_keys)
270
+ existing = live.pluck(:unit_key, :value, :expires_at)
271
+ now = Time.now.utc
272
+ changed = existing.reject { |_, current, until_at| current == value && until_at&.round(6) == expires_at&.round(6) }.map(&:first)
273
+ live.where(unit_key: changed).update_all(removed_at: now, updated_at: now) unless changed.empty?
274
+ fresh = unit_keys - existing.map(&:first)
275
+ inserts = fresh + changed
276
+ insert_members(owner, inserts, unit: unit.to_s, value: value, expires_at: expires_at, now: now) unless inserts.empty?
277
+ recount(owner)
278
+ { added: fresh.size, updated: existing.size }
279
+ end
280
+
281
+ def remove_members(owner, unit:, unit_keys:)
282
+ now = Time.now.utc
283
+ removed = members_of(owner).where(unit: unit.to_s, unit_key: unit_keys).update_all(removed_at: now, updated_at: now)
284
+ recount(owner) unless removed.zero?
285
+ removed
286
+ end
287
+
288
+ def count_members(owner, now: nil)
289
+ scope = members_of(owner)
290
+ scope = scope.where("expires_at IS NULL OR expires_at > ?", now) if now
291
+ scope.count
292
+ end
293
+
294
+ # Creates the state row first when it is missing.
295
+ def lock_revision
296
+ locked = Models::State.lock.pick(:revision)
297
+ return locked unless locked.nil?
298
+
299
+ seed_state
300
+ Models::State.lock.pick(:revision)
301
+ end
302
+
303
+ # The next value of the revision column's own sequence, never
304
+ # revision + 1: a number taken by a write that rolls back is never
305
+ # reused, so a process that saw the uncommitted rules under it
306
+ # reloads at its next check. Creates the state row first when it is
307
+ # missing, so a write never "succeeds" without moving the revision.
308
+ def bump_revision
309
+ seed_state unless Models::State.exists?
310
+ bumped = Models::Record.with_connection { |connection| connection.select_value(BUMP_REVISION) }
311
+ raise StoreError, "revision bump failed: standard_flags_state has no row" if bumped.nil?
312
+
313
+ Integer(bumped)
314
+ end
315
+
316
+ private
317
+
318
+ # Under a table lock (held to the end of the write, and taken only
319
+ # when the row is missing), so concurrent writers insert one row.
320
+ # Callers check for the row with a plain read first and take the lock
321
+ # before any UPDATE of the table: a writer holding the UPDATE's lock
322
+ # while waiting for this one would deadlock with another doing the
323
+ # same.
324
+ def seed_state
325
+ Models::Record.with_connection do |connection|
326
+ connection.execute(LOCK_STATE)
327
+ connection.execute(SEED_STATE)
328
+ end
329
+ end
330
+
331
+ # One INSERT with every value bound, never inlined: unit keys can be
332
+ # phone numbers or emails, and SQL text reaches logs, notification
333
+ # payloads and APM spans. The binds are named `unit_key` and so on,
334
+ # so log filtering applies to them (Runtime.filter_unit_keys!). Not
335
+ # prepared: each key count would be a new statement.
336
+ def insert_members(owner, unit_keys, unit:, value:, expires_at:, now:)
337
+ ids = owner.is_a?(Runtime::Rule) ? [ owner.id, nil ] : [ nil, owner.id ]
338
+ width = MEMBERSHIP_INSERT_COLUMNS.size
339
+ rows = unit_keys.each_index.map { |row| "(#{Array.new(width) { |i| "$#{(row * width) + i + 1}" }.join(', ')})" }
340
+ binds = unit_keys.flat_map do |unit_key|
341
+ MEMBERSHIP_INSERT_COLUMNS.zip([ *ids, unit, unit_key, value, expires_at, now, now ]).map do |column, bound|
342
+ ::ActiveRecord::Relation::QueryAttribute.new(column.to_s, bound, Models::Membership.type_for_attribute(column))
343
+ end
344
+ end
345
+ sql = "INSERT INTO standard_flags_memberships (#{MEMBERSHIP_INSERT_COLUMNS.join(', ')}) " \
346
+ "VALUES #{rows.join(', ')} ON CONFLICT DO NOTHING"
347
+ Models::Record.with_connection { |connection| connection.exec_query(sql, "StandardFlags membership insert", binds, prepare: false) }
348
+ end
349
+
350
+ def members_of(owner)
351
+ Models::Membership.where(owner_column(owner) => owner.id, removed_at: nil)
352
+ end
353
+
354
+ def owner_column(owner)
355
+ owner.is_a?(Runtime::Rule) ? :rule_id : :cohort_id
356
+ end
357
+
358
+ # member_count counts memberships not removed, expired or not.
359
+ def recount(owner)
360
+ count = members_of(owner).count
361
+ (owner.is_a?(Runtime::Rule) ? @rules.fetch(owner.key.to_s) : @cohorts.fetch(owner.key)).update_columns(member_count: count)
362
+ end
363
+
364
+ def rule(record)
365
+ Runtime::Rule.build(**RULE_COLUMNS.to_h { |column| [ column, record.public_send(column) ] })
366
+ end
367
+
368
+ def cohort(record)
369
+ Runtime::Cohort.build(**COHORT_COLUMNS.to_h { |column| [ column, record.public_send(column) ] })
370
+ end
371
+ end
372
+
373
+ private
374
+
375
+ def expired_before(before)
376
+ Models::Membership.where(removed_at: nil).where(expires_at: ...before)
377
+ end
378
+
379
+ def recount(model, column, ids)
380
+ return if ids.empty?
381
+
382
+ owner = Models::Membership.arel_table[column].eq(model.arel_table[:id])
383
+ count = Models::Membership.where(removed_at: nil).where(owner).select(Arel.star.count).to_sql
384
+ model.where(id: ids.uniq).update_all("member_count = (#{count})")
385
+ end
386
+
387
+ def guard(what)
388
+ yield
389
+ rescue StandardError => e
390
+ raise StoreError.new("#{what} failed: #{e.class}", cause_class: e.class.name), cause: nil
391
+ end
392
+
393
+ def state_row_missing?
394
+ Models::Record.with_connection { |connection| connection.data_source_exists?("standard_flags_state") } &&
395
+ !Models::State.exists?
396
+ rescue StandardError
397
+ false
398
+ end
399
+
400
+ def prepared_statements?
401
+ value = Models::Record.connection_db_config.configuration_hash.fetch(:prepared_statements, true)
402
+ ::ActiveRecord::Type::Boolean.new.cast(value) != false
403
+ end
404
+
405
+ def membership(row)
406
+ attributes = MEMBERSHIP_COLUMNS.zip(row).to_h
407
+ attributes[:created_at] = row[MEMBERSHIP_COLUMNS.size] if row.size > MEMBERSHIP_COLUMNS.size
408
+ Membership.new(**attributes, unit: attributes[:unit].to_sym)
409
+ end
410
+
411
+ # The memberships of one rule or cohort, or nil when it doesn't exist.
412
+ def owner_scope(rule, cohort)
413
+ raise ArgumentError, "pass exactly one of rule: or cohort:" unless rule.nil? ^ cohort.nil?
414
+
415
+ id = rule ? Models::Rule.where(key: rule.to_s).pick(:id) : Models::Cohort.where(key: cohort.to_s).pick(:id)
416
+ id && Models::Membership.where((rule ? :rule_id : :cohort_id) => id)
417
+ end
418
+
419
+ def read(what, quote: true, &)
420
+ connection = Models::Record.connection_pool.active_connection
421
+ connection&.transaction_open? ? Models::Record.transaction(requires_new: true, &) : yield
422
+ rescue StandardError => e
423
+ message = quote ? "#{what} failed: #{e.class}: #{e.message}" : "#{what} failed: #{e.class}"
424
+ raise StoreError.new(message, cause_class: e.class.name), cause: nil
425
+ end
426
+ end
427
+ end
428
+ end
@@ -0,0 +1,98 @@
1
+ module StandardFlags
2
+ module Runtime
3
+ # Holds the process-wide RuleSnapshot and refreshes it lazily, on
4
+ # evaluation: once `interval` seconds have passed it reads the store's
5
+ # revision (one query) and reloads only when the revision has moved.
6
+ #
7
+ # No background thread is started, so it is fork-safe: after a fork the
8
+ # child keeps the inherited snapshot. The lock is never replaced; Ruby
9
+ # releases a mutex held by a thread that doesn't survive the fork, and
10
+ # the forking thread can't be mid-refresh.
11
+ #
12
+ # If the store errors, the last good snapshot keeps serving, marked
13
+ # stale; the error is reported once per class and `runtime_stale` is
14
+ # emitted. The next attempt waits a full interval, so a database outage
15
+ # costs one failed query per interval, not one per evaluation. A process
16
+ # that has never loaded serves an empty, unloaded snapshot, and every
17
+ # flag falls back to its code default.
18
+ #
19
+ # A refresh only reads. A store with no revision yet (nil) never counts
20
+ # as unchanged, so the rules reload at every check until a write
21
+ # creates one.
22
+ class Cache
23
+ attr_reader :store
24
+
25
+ def initialize(store, interval: nil, clock: nil)
26
+ @store = store
27
+ @interval = interval
28
+ @clock = clock
29
+ @snapshot = nil
30
+ @mutex = Mutex.new
31
+ end
32
+
33
+ # The current snapshot, refreshed first if it is due. Never raises.
34
+ def snapshot
35
+ current = @snapshot
36
+ return current if fresh?(current)
37
+
38
+ if current
39
+ return current unless @mutex.try_lock # another thread is refreshing
40
+ else
41
+ @mutex.lock
42
+ end
43
+ begin
44
+ current = @snapshot
45
+ fresh?(current) ? current : (@snapshot = refresh(current))
46
+ ensure
47
+ @mutex.unlock
48
+ end
49
+ end
50
+
51
+ # The snapshot as it stands, without refreshing (for diagnostics).
52
+ def peek
53
+ @snapshot
54
+ end
55
+
56
+ # Makes the next read check the revision, whatever the interval. The
57
+ # write path calls it, so the writing process sees its own change.
58
+ def expire!
59
+ current = @snapshot
60
+ @snapshot = current.with(checked_at: nil) if current
61
+ end
62
+
63
+ private
64
+
65
+ def fresh?(snapshot)
66
+ snapshot && snapshot.checked_at && now - snapshot.checked_at < interval
67
+ end
68
+
69
+ def refresh(current)
70
+ checked_at = now
71
+ revision = store.revision
72
+ return current.with(checked_at: checked_at, stale: false) if current&.loaded && !revision.nil? && current.revision == revision
73
+
74
+ snapshot = RuleSnapshot.build(store.load, revision: revision, checked_at: checked_at)
75
+ Reporting.instrument(:runtime_refresh, revision: snapshot.revision, rules: snapshot.rules.size)
76
+ snapshot
77
+ rescue StandardError => e
78
+ failed(current || RuleSnapshot.empty, checked_at, e)
79
+ end
80
+
81
+ def failed(current, checked_at, error)
82
+ name = (error.cause_class if error.is_a?(StoreError)) || error.class.name
83
+ Reporting.once(:runtime_store, name) { Reporting.report(error, runtime: "refresh") }
84
+ Reporting.instrument(:runtime_stale,
85
+ error_class: name, revision: current.revision, loaded: current.loaded, age: current.age)
86
+ current.with(checked_at: checked_at, stale: true)
87
+ end
88
+
89
+ def interval
90
+ (@interval || StandardFlags.config.refresh_interval).to_f
91
+ end
92
+
93
+ def now
94
+ @clock ? @clock.call : Process.clock_gettime(Process::CLOCK_MONOTONIC)
95
+ end
96
+ end
97
+ end
98
+ end