standard_flags 0.3.0 → 0.4.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 (45) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +188 -0
  3. data/README.md +531 -59
  4. data/conformance/README.md +152 -3
  5. data/conformance/legacy_env.json +7 -1
  6. data/conformance/schema/fixture.schema.json +390 -21
  7. data/conformance/schema/manifest.schema.json +347 -0
  8. data/conformance/upgrade/client_status_server.json +297 -0
  9. data/conformance/wire/client_state.json +2115 -2
  10. data/conformance/wire/client_status.json +359 -0
  11. data/conformance/wire/manifest_check.json +5713 -0
  12. data/lib/generators/standard_flags/install/templates/initializer.rb.tt +4 -1
  13. data/lib/generators/standard_flags/migrations/migrations_generator.rb +37 -9
  14. data/lib/generators/standard_flags/migrations/templates/create_standard_flags_compat_stats.rb.tt +17 -0
  15. data/lib/standard_flags/client_app.rb +229 -0
  16. data/lib/standard_flags/client_status/controller.rb +59 -0
  17. data/lib/standard_flags/client_status.rb +110 -0
  18. data/lib/standard_flags/config.rb +18 -1
  19. data/lib/standard_flags/controller.rb +110 -5
  20. data/lib/standard_flags/definition.rb +37 -35
  21. data/lib/standard_flags/diagnostics.rb +61 -3
  22. data/lib/standard_flags/env_pin.rb +5 -15
  23. data/lib/standard_flags/errors.rb +31 -0
  24. data/lib/standard_flags/evaluator.rb +1 -0
  25. data/lib/standard_flags/mcp/flags.rb +12 -1
  26. data/lib/standard_flags/open_feature/provider.rb +2 -1
  27. data/lib/standard_flags/parser.rb +0 -16
  28. data/lib/standard_flags/registry.rb +46 -4
  29. data/lib/standard_flags/runtime/active_record_store.rb +64 -0
  30. data/lib/standard_flags/runtime/compat_tracker.rb +228 -0
  31. data/lib/standard_flags/runtime/memory_store.rb +20 -0
  32. data/lib/standard_flags/runtime/models.rb +6 -0
  33. data/lib/standard_flags/runtime/store.rb +18 -0
  34. data/lib/standard_flags/runtime.rb +33 -3
  35. data/lib/standard_flags/stores/app_store.rb +172 -0
  36. data/lib/standard_flags/stores.rb +37 -0
  37. data/lib/standard_flags/tooling/kotlin.rb +319 -0
  38. data/lib/standard_flags/tooling/manifest.rb +401 -0
  39. data/lib/standard_flags/tooling/manifest_check.rb +355 -0
  40. data/lib/standard_flags/tooling.rb +150 -55
  41. data/lib/standard_flags/version.rb +1 -1
  42. data/lib/standard_flags.rb +3 -0
  43. data/lib/tasks/standard_flags.rake +47 -0
  44. metadata +15 -2
  45. data/conformance/legacy_exact.json +0 -90
@@ -38,6 +38,14 @@ module StandardFlags
38
38
  # subclass) takes it over. One raised with `status: 404` answers like
39
39
  # `error: :not_found`, with no meta.
40
40
  #
41
+ # `requires_client_version` answers 426 `client_upgrade_required` to a
42
+ # build below its enforced minimum (see StandardFlags::ClientStatus),
43
+ # through the same responders, always with a JSON body; a raised
44
+ # StandardFlags::ClientUpgradeRequired is answered the same way, and as
45
+ # robustly. It reads `standard_flags_upgrade_client`, as the status
46
+ # endpoint does, and that is the same client the flag guards use, so
47
+ # none of them disagree about one request.
48
+ #
41
49
  # Flags are evaluated for `standard_flags_context` plus the calling client,
42
50
  # read once per request from the X-Client-Platform, X-Client-Version and
43
51
  # X-Client-Build headers (`standard_flags_client`). A context that already
@@ -59,7 +67,22 @@ module StandardFlags
59
67
  end
60
68
  end
61
69
 
70
+ # What `requires_client_version` (or a raised ClientUpgradeRequired)
71
+ # hands the responder: `error` is :client_upgrade_required and `status`
72
+ # 426. `key` is the declared client's name (nil when the request's
73
+ # version is unknown and `config.require_client_version` refused it),
74
+ # and `feature` is always nil, so a responder written for Denial can
75
+ # tell them apart by `error`.
76
+ UpgradeDenial = Data.define(:key, :error, :status, :feature, :platform, :version, :min_version, :store_url) do
77
+ def body
78
+ { errors: [ { status: status.to_s, code: error.to_s, meta: { min_version: min_version, store_url: store_url } } ] }
79
+ end
80
+ end
81
+
62
82
  included do
83
+ if respond_to?(:class_attribute)
84
+ class_attribute :standard_flags_client_version_options, instance_writer: false, default: nil
85
+ end
63
86
  if respond_to?(:helper_method)
64
87
  helper_method :standard_flags_payload, :standard_flags_client, :standard_flags_request_context, :standard_flags_reader
65
88
  end
@@ -82,6 +105,46 @@ module StandardFlags
82
105
  standard_flags_require!(key, error: error, status: status, responder: with)
83
106
  end
84
107
  end
108
+
109
+ # Answers 426 `client_upgrade_required` when the request's client is
110
+ # below its enforced minimum (StandardFlags::ClientStatus says
111
+ # `upgrade_required`), through `with:`, `config.controller_responder`
112
+ # or the default JSON:API body, whose meta carries `min_version` and
113
+ # `store_url`. A client in its grace window, or below `recommended`
114
+ # only, passes. So does one whose platform or version is unknown,
115
+ # unless `config.require_client_version` is true. `group:` picks the
116
+ # client group (see StandardFlags::ClientApp).
117
+ #
118
+ # One guard per controller hierarchy: declaring it again, in the same
119
+ # class or under a class that inherits one, raises
120
+ # StandardFlags::ConfigurationError, because the new declaration
121
+ # would silently replace the earlier one (its actions, group and
122
+ # responder). Pass `override: true` to replace it on purpose; to
123
+ # narrow an inherited guard, use `skip_client_version_check`.
124
+ def requires_client_version(only: nil, except: nil, group: nil, with: nil, override: false)
125
+ unless with.nil? || with.is_a?(Symbol) || with.respond_to?(:call)
126
+ raise ArgumentError, "with: must respond to call(controller, denial) or be a Symbol naming a controller method"
127
+ end
128
+ raise ArgumentError, "override: must be true or false" unless [ true, false ].include?(override)
129
+
130
+ existing = standard_flags_client_version_options
131
+ if existing && !override
132
+ where = existing[:owner].equal?(self) ? "already declared here" : "inherited from #{existing[:owner].name || 'a parent'}"
133
+ raise ConfigurationError,
134
+ "#{name || 'this controller'} declares requires_client_version again (#{where}); a second declaration would " \
135
+ "replace the first. Pass override: true to replace it, or use skip_client_version_check to narrow it"
136
+ end
137
+
138
+ self.standard_flags_client_version_options = { group: group&.to_sym, responder: with, owner: self }.freeze
139
+ before_action :standard_flags_check_client_version, **{ only: only, except: except }.compact
140
+ end
141
+
142
+ # Skips an inherited `requires_client_version` for these actions (all
143
+ # of them by default): a status or health endpoint under a guarded
144
+ # base controller, say.
145
+ def skip_client_version_check(only: nil, except: nil)
146
+ skip_before_action :standard_flags_check_client_version, raise: false, **{ only: only, except: except }.compact
147
+ end
85
148
  end
86
149
 
87
150
  # The payload for one audience, evaluated for this request's context
@@ -139,14 +202,19 @@ module StandardFlags
139
202
  end
140
203
  public :rescue_with_handler, :handler_for_rescue
141
204
 
205
+ STANDARD_FLAGS_HANDLERS = { FeatureDisabled => :standard_flags_feature_disabled,
206
+ ClientUpgradeRequired => :standard_flags_client_upgrade_required }.freeze
207
+ private_constant :STANDARD_FLAGS_HANDLERS
208
+
142
209
  def standard_flags_handler(exception)
143
- return unless exception.is_a?(FeatureDisabled)
210
+ base, handler_name = STANDARD_FLAGS_HANDLERS.find { |klass, _| exception.is_a?(klass) }
211
+ return unless base
144
212
 
145
213
  targeted = self.class.rescue_handlers.any? do |name, handler|
146
- klass = name.safe_constantize if handler != :standard_flags_feature_disabled
147
- klass.is_a?(Class) && klass <= FeatureDisabled
214
+ klass = name.safe_constantize unless STANDARD_FLAGS_HANDLERS.value?(handler)
215
+ klass.is_a?(Class) && klass <= base
148
216
  end
149
- method(:standard_flags_feature_disabled) unless targeted
217
+ method(handler_name) unless targeted
150
218
  end
151
219
 
152
220
  def standard_flags_require!(key, error:, status:, responder: nil)
@@ -156,6 +224,41 @@ module StandardFlags
156
224
  responder)
157
225
  end
158
226
 
227
+ # The client the upgrade checks read (the 426 guard and the status
228
+ # endpoint), with the precedence the flag guards use: the client
229
+ # `standard_flags_context` names, whole, when it names one (the app
230
+ # chose it, from a trusted device record, say), else the X-Client-*
231
+ # headers' client, whole. Fields are never mixed from the two.
232
+ def standard_flags_upgrade_client
233
+ standard_flags_request_context.client
234
+ end
235
+
236
+ def standard_flags_check_client_version
237
+ options = standard_flags_client_version_options || {}
238
+ standard_flags_require_client!(group: options[:group], responder: options[:responder])
239
+ end
240
+
241
+ # The 426 guard.
242
+ def standard_flags_require_client!(group:, responder: nil)
243
+ result = ClientStatus.for(standard_flags_upgrade_client, group: group)
244
+ return unless result.upgrade_required? || (result.unknown? && StandardFlags.config.require_client_version)
245
+
246
+ standard_flags_deny(standard_flags_upgrade_denial(result.client_app&.name, result.platform, result.version,
247
+ result.min_version, result.store_url), responder)
248
+ end
249
+
250
+ def standard_flags_client_upgrade_required(exception)
251
+ return if performed?
252
+
253
+ standard_flags_deny(standard_flags_upgrade_denial(exception.client, exception.platform, exception.version,
254
+ exception.min_version, exception.store_url), nil)
255
+ end
256
+
257
+ def standard_flags_upgrade_denial(client, platform, version, min_version, store_url)
258
+ UpgradeDenial.new(key: client, error: :client_upgrade_required, status: 426, feature: nil, platform: platform,
259
+ version: version&.to_s, min_version: min_version&.to_s, store_url: store_url)
260
+ end
261
+
159
262
  # A 404 answers like `error: :not_found`, revealing no feature name.
160
263
  # Nothing is rendered when the action already has.
161
264
  def standard_flags_feature_disabled(exception)
@@ -174,8 +277,10 @@ module StandardFlags
174
277
  end
175
278
  end
176
279
 
280
+ # A 426 always carries its JSON body, whatever the request accepts: the
281
+ # client needs `min_version` and `store_url` to act on it.
177
282
  def standard_flags_render_denial(denial)
178
- if request.format.json? || request.content_mime_type&.json?
283
+ if denial.is_a?(UpgradeDenial) || request.format.json? || request.content_mime_type&.json?
179
284
  render json: denial.body, status: denial.status
180
285
  else
181
286
  head denial.status
@@ -16,14 +16,14 @@ module StandardFlags
16
16
  shadow: %i[off shadow enforce]
17
17
  }.freeze
18
18
 
19
- COMMON_ATTRIBUTES = %i[owner description default env inverted legacy_parser legacy_true forbidden_in fail
20
- expose min_client unit].freeze
19
+ COMMON_ATTRIBUTES = %i[owner description default env inverted forbidden_in fail expose min_client
20
+ unit].freeze
21
21
  ATTRIBUTES = {
22
22
  flag: COMMON_ATTRIBUTES + %i[remove_by final permanent bucketing],
23
23
  kill_switch: COMMON_ATTRIBUTES,
24
24
  mode: COMMON_ATTRIBUTES + %i[preset values remove_by final permanent bucketing],
25
25
  experiment: COMMON_ATTRIBUTES + %i[variants bucketing],
26
- compat: COMMON_ATTRIBUTES + %i[remove_by]
26
+ compat: COMMON_ATTRIBUTES + %i[remove_by until_clients]
27
27
  }.freeze
28
28
 
29
29
  KEY_FORMAT = /\A[a-z][a-z0-9_]*\z/
@@ -31,12 +31,9 @@ module StandardFlags
31
31
  WIRE_FORMAT = /\A[A-Za-z][A-Za-z0-9_]*\z/
32
32
  HASH_VERSIONS = [ 1, 2 ].freeze
33
33
 
34
- # How legacy `env:` values are read. :strict is the one strict parser;
35
- # :exact reproduces a hand-written `ENV["X"] == "on"` reader. Neither
36
- # applies to the canonical STANDARD_FLAGS_<KEY> pin, which is always
37
- # strict.
38
- LEGACY_PARSERS = %i[strict exact].freeze
39
- DEFAULT_LEGACY_TRUE = %w[on].freeze
34
+ # Attributes removed in 0.4.0. Declaring one raises ArgumentError naming
35
+ # the replacement rather than the generic unknown-attribute error.
36
+ REMOVED_ATTRIBUTES = %i[legacy_parser legacy_true].freeze
40
37
 
41
38
  # A declared `bucketing: { version:, salt: }`, for a flag migrated from
42
39
  # another system that must keep its old buckets. Copied into the flag's
@@ -45,13 +42,14 @@ module StandardFlags
45
42
 
46
43
  attr_reader :key, :kind, :owner, :description, :env, :inverted, :forbidden_in,
47
44
  :expose, :exposure, :min_client, :unit, :remove_by, :final, :values, :variants, :permanent,
48
- :bucketing, :legacy_parser, :legacy_true
45
+ :bucketing, :until_clients
49
46
 
50
47
  def initialize(kind, key, attributes)
51
48
  @kind = kind.to_sym
52
49
  raise DefinitionError, "unknown flag kind #{kind.inspect}" unless KINDS.include?(@kind)
53
50
 
54
51
  @key = normalize_key(key)
52
+ check_removed_attributes!(attributes)
55
53
  check_attributes!(attributes)
56
54
  assign(attributes)
57
55
  validate!
@@ -180,6 +178,12 @@ module StandardFlags
180
178
  !client.version.nil? && client.version >= minimum
181
179
  end
182
180
 
181
+ # A compat flag's window: `until_clients:` lists, per platform, the first
182
+ # client version that no longer needs the shim. Empty for other flags.
183
+ def compat_window?
184
+ !until_clients.empty?
185
+ end
186
+
183
187
  # Permanent flags have no remove_by:, so they are never stale.
184
188
  def stale?(today = Date.today)
185
189
  !remove_by.nil? && remove_by < today
@@ -198,6 +202,18 @@ module StandardFlags
198
202
  key.to_sym
199
203
  end
200
204
 
205
+ # legacy_parser: :exact read legacy env: names the way a hand-written
206
+ # `ENV["X"] == "on"` reader did. Every env name is now read by the one
207
+ # strict parser, so the canonical pin replaces it.
208
+ def check_removed_attributes!(attributes)
209
+ removed = attributes.keys.map(&:to_sym) & REMOVED_ATTRIBUTES
210
+ return if removed.empty?
211
+
212
+ raise ArgumentError,
213
+ "#{kind} :#{key} declares #{removed.map { |name| "#{name}:" }.join(' and ')}, removed in 0.4.0. " \
214
+ "Set the canonical #{canonical_env_var} instead; the strict parser reads it."
215
+ end
216
+
201
217
  def check_attributes!(attributes)
202
218
  unknown = attributes.keys.map(&:to_sym) - ATTRIBUTES.fetch(kind)
203
219
  return if unknown.empty?
@@ -211,13 +227,11 @@ module StandardFlags
211
227
  @description = attributes[:description]&.to_s
212
228
  @env = Array(attributes[:env]).map(&:to_s).freeze
213
229
  @inverted = attributes.fetch(:inverted, false)
214
- @legacy_parser = attributes.fetch(:legacy_parser, :strict)
215
- @legacy_parser = @legacy_parser.to_sym if @legacy_parser.respond_to?(:to_sym)
216
- @legacy_true = normalize_legacy_true(attributes)
217
230
  @forbidden_in = Array(attributes[:forbidden_in]).map(&:to_s).freeze
218
231
  @exposure = normalize_expose(attributes[:expose])
219
232
  @expose = @exposure.transform_values(&:first).freeze
220
233
  @min_client = normalize_min_client(attributes[:min_client])
234
+ @until_clients = normalize_until_clients(attributes[:until_clients])
221
235
  @unit = attributes[:unit]&.to_sym
222
236
  @remove_by = parse_date(attributes[:remove_by], :remove_by)
223
237
  @values = resolve_values(attributes)
@@ -234,7 +248,6 @@ module StandardFlags
234
248
  fail!("is missing owner:") if owner.nil? || owner.strip.empty?
235
249
  validate_lifecycle!
236
250
  validate_env!
237
- validate_legacy_parser!
238
251
  validate_forbidden_in!
239
252
  fail!("bucketing: needs a unit: to bucket") if bucketing && unit.nil?
240
253
  end
@@ -278,27 +291,6 @@ module StandardFlags
278
291
  end
279
292
  end
280
293
 
281
- def validate_legacy_parser!
282
- fail!("legacy_parser: must be one of #{LEGACY_PARSERS.inspect}") unless LEGACY_PARSERS.include?(legacy_parser)
283
- fail!("legacy_parser: needs a legacy env: name") if legacy_parser == :exact && env.empty?
284
- return if @legacy_true.nil? || @legacy_true.equal?(DEFAULT_LEGACY_TRUE)
285
-
286
- fail!("legacy_true: needs legacy_parser: :exact") unless legacy_parser == :exact
287
- fail!("legacy_true: only applies to on/off kinds") unless boolean?
288
- return unless @legacy_true.empty? || @legacy_true.any? { |word| word.strip.empty? }
289
-
290
- fail!("legacy_true: must list at least one non-blank value")
291
- end
292
-
293
- # The exact legacy values that mean on, for an on/off kind read with
294
- # `legacy_parser: :exact`; nil otherwise (unless declared, so validation
295
- # can reject it).
296
- def normalize_legacy_true(attributes)
297
- return Array(attributes[:legacy_true]).map(&:to_s).freeze if attributes.key?(:legacy_true)
298
-
299
- DEFAULT_LEGACY_TRUE if @legacy_parser == :exact && boolean?
300
- end
301
-
302
294
  def invalid_variants?
303
295
  variants.nil? || variants.size < 2 || variants.uniq.size != variants.size
304
296
  end
@@ -375,6 +367,16 @@ module StandardFlags
375
367
  Definition.client_versions(min_client) { |message| fail!("min_client: #{message}") }
376
368
  end
377
369
 
370
+ # `{ "platform" => Version }`: a compat flag's window. Its evaluations
371
+ # are counted (`config.track_compat`) and `flags:stale` reports it once
372
+ # every listed platform is past its version and it has gone unused.
373
+ def normalize_until_clients(until_clients)
374
+ return {}.freeze if until_clients.nil?
375
+ fail!("until_clients: must be a Hash of platform => version") unless until_clients.is_a?(Hash)
376
+
377
+ Definition.client_versions(until_clients) { |message| fail!("until_clients: #{message}") }
378
+ end
379
+
378
380
  # Casts a declared value to this kind's type, raising for anything outside
379
381
  # the declared set.
380
382
  def coerce(value, attribute)
@@ -12,7 +12,9 @@ module StandardFlags
12
12
 
13
13
  def report(registry: StandardFlags.registry, env: StandardFlags.config.env_source, today: Date.today)
14
14
  environment = safe_env(registry)
15
- rows = registry.definitions.map { |definition| row(registry, definition, env, environment, today) }
15
+ rows = Runtime::CompatTracker.untracked do
16
+ registry.definitions.map { |definition| row(registry, definition, env, environment, today) }
17
+ end
16
18
 
17
19
  report = {
18
20
  environment: environment,
@@ -25,16 +27,71 @@ module StandardFlags
25
27
  unknown_env_vars: unknown_env_vars(registry, env)
26
28
  }
27
29
  report[:runtime] = Runtime.status(registry: registry) if Runtime.enabled?
30
+ report[:clients] = clients(registry, env) unless registry.clients.empty?
31
+ report[:compat] = compat(registry) if registry.definitions.any?(&:compat_window?)
28
32
  report.merge(status: status(report))
29
33
  end
30
34
 
35
+ # The client registry with its ENV pins applied: the values in force
36
+ # (versions as Strings, dates as YYYY-MM-DD), the pins that applied and
37
+ # those ignored. Pins in force are listed here, as flags' pins are, and
38
+ # never warn; only ignored ones do. `available` is the declared or
39
+ # pinned one; a store lookup isn't asked here.
40
+ def clients(registry, env)
41
+ registry.clients.values.sort_by(&:name).map do |app|
42
+ policy = app.resolve(env)
43
+ { name: app.name, platform: app.platform, group: app.group, min_version: policy.min_version&.to_s,
44
+ since: policy.since&.iso8601, enforce_on: policy.enforce_on&.iso8601, grace_days: app.grace_days,
45
+ recommended: policy.recommended&.to_s, available: policy.available&.to_s, store_url: app.store_url,
46
+ store_lookup: app.store_lookup?, pinned: policy.pinned, rejected: policy.rejected }
47
+ end
48
+ end
49
+
50
+ # Compat flags with `until_clients:`, and their stored counts when
51
+ # `config.track_compat` is on (`stats` is nil when off, or when the
52
+ # store keeps none; `error` names the error class when it can't be read).
53
+ def compat(registry)
54
+ windows = registry.definitions.select(&:compat_window?).sort_by(&:key)
55
+ tracking = StandardFlags.config.track_compat == true && Runtime.enabled?
56
+ stats, error = compat_stats(windows) if tracking
57
+ grouped = (stats || []).group_by { |stat| stat.key.to_s }
58
+ { tracking: tracking, error: error, flags: windows.map do |definition|
59
+ markers, rows = grouped.fetch(definition.key.to_s, []).partition(&:marker?)
60
+ { flag: definition.key, until_clients: definition.until_clients.transform_values(&:to_s),
61
+ tracking_since: markers.first&.first_seen_at&.utc&.iso8601,
62
+ last_flushed_at: markers.first&.last_flushed_at&.utc&.iso8601, stats: stats && rows.map(&:to_h) }
63
+ end }
64
+ end
65
+
66
+ def compat_stats(windows)
67
+ [ Runtime.compat_stats(windows.map(&:key)), nil ]
68
+ rescue StandardError => e
69
+ [ nil, (e.cause_class if e.is_a?(Runtime::StoreError)) || e.class.name ]
70
+ end
71
+
31
72
  # One line per warning, names only.
32
73
  def warnings(report)
33
74
  report[:rejected_pins].map { |p| "#{p[:env_var]} for :#{p[:flag]} is not a valid value (ignored)" } +
34
75
  report[:legacy_env_vars].map { |p| "#{p[:env_var]} for :#{p[:flag]} is deprecated; rename to #{p[:canonical]}" } +
35
76
  report[:stale].map { |s| ":#{s[:flag]} is past remove_by #{s[:remove_by]}" } +
36
77
  report[:unknown_env_vars].map { |var| "#{var} does not match a declared flag" } +
37
- runtime_warnings(report[:runtime])
78
+ runtime_warnings(report[:runtime]) + client_warnings(report[:clients]) + compat_warnings(report[:compat])
79
+ end
80
+
81
+ # Only ignored pins warn: a valid break-glass pin is listed under
82
+ # `clients:`, never turned into a health warning.
83
+ def client_warnings(clients)
84
+ Array(clients).flat_map do |client|
85
+ client[:rejected].map { |var| "#{var} for client :#{client[:name]} was ignored (invalid, or a raised minimum without _SINCE)" }
86
+ end
87
+ end
88
+
89
+ def compat_warnings(compat)
90
+ return [] if compat.nil?
91
+ return [ "compat stats could not be read (#{compat[:error]})" ] if compat[:error]
92
+ return [] unless StandardFlags.config.track_compat == true && !compat[:tracking]
93
+
94
+ [ "config.track_compat is on but runtime rules are off, so compat hits are not counted" ]
38
95
  end
39
96
 
40
97
  # Runtime rules are on but the store says their tables are missing. A
@@ -113,7 +170,8 @@ module StandardFlags
113
170
  def unknown_env_vars(registry, env)
114
171
  return [] unless env.respond_to?(:keys)
115
172
 
116
- declared = registry.keys.map { |key| "#{CANONICAL_PREFIX}#{key.to_s.upcase}" }
173
+ declared = registry.keys.map { |key| "#{CANONICAL_PREFIX}#{key.to_s.upcase}" } +
174
+ registry.clients.each_value.flat_map(&:env_vars)
117
175
  env.keys.select { |name| name.to_s.start_with?(CANONICAL_PREFIX) }.map(&:to_s).reject { |n| declared.include?(n) }.sort
118
176
  end
119
177
 
@@ -4,10 +4,8 @@ module StandardFlags
4
4
  # The canonical STANDARD_FLAGS_<KEY> is read first, then each legacy `env:`
5
5
  # name in declared order. The first variable that parses wins, so a valid
6
6
  # canonical pin beats any legacy one. `inverted: true` flips legacy values
7
- # only (a legacy *_DISABLED=true means the flag is off), and
8
- # `legacy_parser: :exact` changes how legacy values parse, never the
9
- # canonical one. A blank value counts as unset, except a blank exact legacy
10
- # value on a non-inverted on/off flag, which pins it off.
7
+ # only (a legacy *_DISABLED=true means the flag is off). Every name is
8
+ # read by the one strict parser, and a blank value counts as unset.
11
9
  #
12
10
  # Callers decide what to report; Diagnostics and the health check use the
13
11
  # same scan, so they can't disagree with evaluation.
@@ -34,11 +32,11 @@ module StandardFlags
34
32
 
35
33
  ([ definition.canonical_env_var ] + definition.env).each do |var|
36
34
  raw = env[var]
37
- is_legacy = var != definition.canonical_env_var
38
- next if Parser.blank?(raw) && !(is_legacy && blank_pins_off?(definition, raw))
35
+ next if Parser.blank?(raw)
39
36
 
37
+ is_legacy = var != definition.canonical_env_var
40
38
  legacy << var if is_legacy
41
- value = is_legacy ? Parser.parse_legacy(definition, raw) : Parser.parse(definition, raw)
39
+ value = Parser.parse(definition, raw)
42
40
  if value.equal?(Parser::INVALID)
43
41
  rejected << var
44
42
  elsif pin.nil?
@@ -49,13 +47,5 @@ module StandardFlags
49
47
 
50
48
  Scan.new(pin: pin, rejected: rejected.freeze, legacy: legacy.freeze)
51
49
  end
52
-
53
- # Under `legacy_parser: :exact`, a set-but-blank legacy value pins an
54
- # on/off flag off, as `ENV["X"] == "on"` did; only an unset variable
55
- # falls through. Not for inverted names: off there would turn the flag
56
- # on, so a blank one stays unset. Modes keep blank as unset too.
57
- def blank_pins_off?(definition, raw)
58
- !raw.nil? && definition.legacy_parser == :exact && definition.boolean? && !definition.inverted
59
- end
60
50
  end
61
51
  end
@@ -58,6 +58,37 @@ module StandardFlags
58
58
  end
59
59
  end
60
60
 
61
+ # A client-facing "this build is too old" answer. StandardFlags::Controller
62
+ # raises nothing for `requires_client_version` (the guard answers
63
+ # directly), but app code can raise it, and the controller renders it
64
+ # exactly like the guard: 426 `client_upgrade_required`, through
65
+ # `config.controller_responder` when set.
66
+ #
67
+ # status = StandardFlags::ClientStatus.for(client)
68
+ # raise StandardFlags::ClientUpgradeRequired.new(status) if status.upgrade_required?
69
+ #
70
+ # Takes a StandardFlags::ClientStatus::Result, or keywords.
71
+ class ClientUpgradeRequired < Error
72
+ attr_reader :client, :platform, :version, :min_version, :store_url, :status
73
+
74
+ def initialize(result = nil, message = nil, client: nil, platform: nil, version: nil, min_version: nil, store_url: nil)
75
+ if result
76
+ client ||= result.client_app&.name
77
+ platform ||= result.platform
78
+ version ||= result.version
79
+ min_version ||= result.min_version
80
+ store_url ||= result.store_url
81
+ end
82
+ @client = client&.to_sym
83
+ @platform = platform
84
+ @version = version&.to_s
85
+ @min_version = min_version&.to_s
86
+ @store_url = store_url
87
+ @status = 426
88
+ super(message || [ "client", platform, @version, "must upgrade", (@min_version && "to #{@min_version}") ].compact.join(" "))
89
+ end
90
+ end
91
+
61
92
  # Reported (never raised) through Rails.error when an ENV pin can't be
62
93
  # parsed. The message names the variable, never its value.
63
94
  class PinRejected < Error; end
@@ -15,6 +15,7 @@ module StandardFlags
15
15
  return unknown(registry, key) unless definition
16
16
 
17
17
  evaluation = Memo.fetch(memo_key(registry, definition, context)) { resolve(registry, definition, context) }
18
+ Runtime.track_compat(definition, context) if definition.compat_window?
18
19
  sample(evaluation)
19
20
  evaluation
20
21
  end
@@ -87,7 +87,18 @@ module StandardFlags
87
87
  runtime_rules: Runtime.enabled?,
88
88
  rule: readable_rule(rule_for(definition.key)),
89
89
  store_revision: store_revision
90
- }
90
+ }.merge(compat(definition))
91
+ end
92
+
93
+ # For a compat flag with `until_clients:` only: its window and, when
94
+ # `config.track_compat` is on, its stored counts per platform.
95
+ def compat(definition)
96
+ return {} unless definition.compat_window?
97
+
98
+ report = Diagnostics.compat(registry)
99
+ entry = report[:flags].find { |flag| flag[:flag] == definition.key }
100
+ { compat: { until_clients: entry[:until_clients], tracking: report[:tracking], error: report[:error],
101
+ tracking_since: entry[:tracking_since], last_flushed_at: entry[:last_flushed_at], stats: entry[:stats] } }
91
102
  end
92
103
 
93
104
  # The evaluation, and the unit key it was for, masked.
@@ -183,7 +183,8 @@ module StandardFlags
183
183
  flags: source.keys.zip(source.definitions).to_h,
184
184
  tombstones: source.tombstones,
185
185
  units: units,
186
- env_resolver: -> { source.current_env }
186
+ env_resolver: -> { source.current_env },
187
+ clients: source.clients
187
188
  )
188
189
  @registries = [ source, keyed ].freeze
189
190
  keyed
@@ -6,12 +6,6 @@ module StandardFlags
6
6
  #
7
7
  # Matching is trimmed and case-insensitive. Anything else is INVALID: the
8
8
  # caller ignores it and reports it. A blank value counts as unset.
9
- #
10
- # A flag declared `legacy_parser: :exact` reads its legacy `env:` names
11
- # (never the canonical pin) the way a hand-written reader did, with no
12
- # trimming or case folding: on/off kinds are on for a `legacy_true:` value
13
- # and off for anything else (EnvPin pins a set-but-blank value off too);
14
- # modes and experiments match a value exactly.
15
9
  module Parser
16
10
  INVALID = Object.new.tap { |o| def o.inspect = "StandardFlags::Parser::INVALID" }.freeze
17
11
 
@@ -27,16 +21,6 @@ module StandardFlags
27
21
  definition.allowed_values.find { |value| value.to_s.downcase == text } || INVALID
28
22
  end
29
23
 
30
- # Parses a legacy `env:` value with the flag's `legacy_parser:`.
31
- def parse_legacy(definition, raw)
32
- return parse(definition, raw) unless definition.legacy_parser == :exact
33
-
34
- text = raw.to_s
35
- return definition.legacy_true.include?(text) if definition.boolean?
36
-
37
- definition.allowed_values.find { |value| value.to_s == text } || INVALID
38
- end
39
-
40
24
  def boolean(raw)
41
25
  text = raw.to_s.strip.downcase
42
26
  return true if TRUE_WORDS.include?(text)
@@ -56,16 +56,17 @@ module StandardFlags
56
56
  end
57
57
  end
58
58
 
59
- attr_reader :tombstones, :units
59
+ attr_reader :tombstones, :units, :clients
60
60
 
61
61
  def self.empty
62
62
  new(flags: {}, tombstones: {}, units: {}, env_resolver: nil)
63
63
  end
64
64
 
65
- def initialize(flags:, tombstones:, units:, env_resolver:)
65
+ def initialize(flags:, tombstones:, units:, env_resolver:, clients: {})
66
66
  @flags = flags.freeze
67
67
  @tombstones = tombstones.freeze
68
68
  @units = units.freeze
69
+ @clients = clients.freeze
69
70
  @env_resolver = env_resolver
70
71
  freeze
71
72
  end
@@ -82,7 +83,16 @@ module StandardFlags
82
83
  raise ArgumentError, "unknown unit :#{unit}" unless @units.key?(unit)
83
84
 
84
85
  probe = Unit.new(name: unit, resolver: ->(_context) { unit_key }, key: nil)
85
- Registry.new(flags: @flags, tombstones: @tombstones, units: @units.merge(unit => probe), env_resolver: @env_resolver)
86
+ Registry.new(flags: @flags, tombstones: @tombstones, units: @units.merge(unit => probe), env_resolver: @env_resolver,
87
+ clients: @clients)
88
+ end
89
+
90
+ # The declared client (a ClientApp) for `platform` in `group` (nil is the
91
+ # default group), or nil.
92
+ def client_for(platform, group: nil)
93
+ platform = platform.to_s
94
+ group = group&.to_sym
95
+ @clients.each_value.find { |client| client.platform == platform && client.group == group }
86
96
  end
87
97
 
88
98
  def key?(key)
@@ -168,6 +178,7 @@ module StandardFlags
168
178
  @flags = {}
169
179
  @tombstones = {}
170
180
  @units = {}
181
+ @clients = {}
171
182
  @env_resolver = nil
172
183
  end
173
184
 
@@ -214,12 +225,32 @@ module StandardFlags
214
225
  @tombstones[key] = Tombstone.new(key: key, removed: removed, **tombstone_serve(key, removed, serve, serve_until, until_clients))
215
226
  end
216
227
 
228
+ # A client app build channel: its minimum and recommended versions,
229
+ # store ceiling and store URL (see StandardFlags::ClientApp). One per
230
+ # platform, or per platform within a `group:`.
231
+ #
232
+ # client :android_app, platform: :android, min_version: "0.4.0", since: "2026-12-01",
233
+ # recommended: "0.5.0", available: "0.5.0", store_url: "https://example.com/app", grace: 7.days
234
+ def client(name, **attributes)
235
+ client = ClientApp.declare(name, **attributes)
236
+ raise DefinitionError, "client :#{client.name} is declared twice" if @clients.key?(client.name)
237
+
238
+ clash = @clients.each_value.find { |other| other.platform == client.platform && other.group == client.group }
239
+ if clash
240
+ scope = client.group ? "group :#{client.group}" : "the default group"
241
+ raise DefinitionError, "client :#{client.name} and client :#{clash.name} are both #{client.platform} in #{scope}; " \
242
+ "give one a group: to serve two apps on one platform"
243
+ end
244
+ @clients[client.name] = client
245
+ end
246
+
217
247
  def build
218
248
  validate_tombstones!
219
249
  validate_units!
220
250
  validate_audiences!
221
251
  validate_wire_names!
222
- Registry.new(flags: @flags, tombstones: @tombstones, units: @units, env_resolver: @env_resolver)
252
+ validate_client_pins!
253
+ Registry.new(flags: @flags, tombstones: @tombstones, units: @units, env_resolver: @env_resolver, clients: @clients)
223
254
  end
224
255
 
225
256
  private
@@ -280,6 +311,17 @@ module StandardFlags
280
311
  "flag :#{key} was removed on #{@tombstones[key].removed.iso8601}; keys are never reused, pick a new one"
281
312
  end
282
313
 
314
+ # A client's ENV pins share the STANDARD_FLAGS_ prefix with flags' pins,
315
+ # so no flag's canonical pin may be one of them.
316
+ def validate_client_pins!
317
+ pins = @clients.each_value.flat_map { |client| client.env_vars.map { |var| [ var, client ] } }.to_h
318
+ @flags.each_value do |definition|
319
+ client = pins[definition.canonical_env_var] or next
320
+ raise DefinitionError, "#{definition.kind} :#{definition.key}'s pin #{definition.canonical_env_var} is " \
321
+ "client :#{client.name}'s pin; rename one"
322
+ end
323
+ end
324
+
283
325
  def validate_units!
284
326
  @flags.each_value do |definition|
285
327
  next if definition.unit.nil? || @units.key?(definition.unit)