standard_flags 0.2.2 → 0.3.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 (51) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +158 -0
  3. data/README.md +566 -35
  4. data/conformance/README.md +166 -0
  5. data/conformance/bucket_vectors.json +46 -0
  6. data/conformance/guards_and_errors.json +35 -0
  7. data/conformance/legacy_env.json +38 -0
  8. data/conformance/legacy_exact.json +90 -0
  9. data/conformance/operations/write_path.json +723 -0
  10. data/conformance/permanent_flags.json +38 -0
  11. data/conformance/resolution.json +68 -0
  12. data/conformance/runtime/client.json +1431 -0
  13. data/conformance/runtime/rules.json +1305 -0
  14. data/conformance/schema/fixture.schema.json +1340 -0
  15. data/conformance/versions/legacy_ranges.json +183 -0
  16. data/conformance/versions/version_ranges.json +503 -0
  17. data/conformance/wire/client_state.json +1905 -0
  18. data/conformance/wire/delivery.json +1541 -0
  19. data/lib/standard_flags/audience.rb +49 -0
  20. data/lib/standard_flags/client.rb +157 -0
  21. data/lib/standard_flags/config.rb +21 -0
  22. data/lib/standard_flags/context.rb +70 -17
  23. data/lib/standard_flags/controller.rb +92 -10
  24. data/lib/standard_flags/definition.rb +71 -8
  25. data/lib/standard_flags/delivery.rb +195 -0
  26. data/lib/standard_flags/errors.rb +33 -0
  27. data/lib/standard_flags/job.rb +12 -1
  28. data/lib/standard_flags/mcp/flags.rb +3 -3
  29. data/lib/standard_flags/mcp/gating.rb +151 -0
  30. data/lib/standard_flags/mcp.rb +64 -5
  31. data/lib/standard_flags/notifiers/logger.rb +4 -0
  32. data/lib/standard_flags/ofrep/controller.rb +211 -0
  33. data/lib/standard_flags/ofrep.rb +115 -0
  34. data/lib/standard_flags/open_feature/provider.rb +1 -1
  35. data/lib/standard_flags/operations/rules.rb +17 -4
  36. data/lib/standard_flags/operations/validation.rb +25 -4
  37. data/lib/standard_flags/operations.rb +0 -2
  38. data/lib/standard_flags/payload.rb +8 -3
  39. data/lib/standard_flags/registry.rb +157 -12
  40. data/lib/standard_flags/runtime/cache.rb +1 -0
  41. data/lib/standard_flags/runtime/resolver.rb +26 -17
  42. data/lib/standard_flags/runtime/values.rb +8 -1
  43. data/lib/standard_flags/runtime.rb +42 -1
  44. data/lib/standard_flags/semantic_version.rb +141 -0
  45. data/lib/standard_flags/subscribers.rb +3 -0
  46. data/lib/standard_flags/testing.rb +4 -2
  47. data/lib/standard_flags/tooling.rb +25 -3
  48. data/lib/standard_flags/version.rb +1 -1
  49. data/lib/standard_flags/version_range.rb +309 -0
  50. data/lib/standard_flags.rb +38 -4
  51. metadata +24 -1
@@ -25,7 +25,36 @@ module StandardFlags
25
25
  key_for(resolver.call(context))
26
26
  end
27
27
  end
28
- Tombstone = Data.define(:key, :removed)
28
+ # A removed key. `serve` keeps client wires answering a static value
29
+ # after the flag is gone (`{ audience => { "wire" => value } }`), until
30
+ # `serve_until` (a Date, served through that day in UTC; required with
31
+ # `serve`) and, per platform, only for clients older than
32
+ # `until_clients` (`{ "platform" => Version }`).
33
+ Tombstone = Data.define(:key, :removed, :serve, :serve_until, :until_clients) do
34
+ def initialize(key:, removed:, serve: {}, serve_until: nil, until_clients: {})
35
+ super
36
+ end
37
+
38
+ # Whether the static wires are still served on `today` (a UTC date).
39
+ def serving?(today)
40
+ !serve.empty? && !serve_until.nil? && today <= serve_until
41
+ end
42
+
43
+ # Whether the serve block is past `until:` and can be deleted.
44
+ def serve_expired?(today)
45
+ !serve.empty? && !serve_until.nil? && today > serve_until
46
+ end
47
+
48
+ # Whether `client` still receives the static wires: a client on a
49
+ # platform `until_clients` lists stops at that version; one with an
50
+ # unknown platform or version keeps receiving them until `until:`.
51
+ # `until_clients` can only stop the wires sooner than `until:`.
52
+ def serves_client?(client)
53
+ platform = client.platform
54
+ cutoff = platform && until_clients[platform]
55
+ cutoff.nil? || client.version.nil? || client.version < cutoff
56
+ end
57
+ end
29
58
 
30
59
  attr_reader :tombstones, :units
31
60
 
@@ -85,10 +114,38 @@ module StandardFlags
85
114
  definitions.select { |definition| definition.wire_name(audience) }.sort_by { |d| d.wire_name(audience) }
86
115
  end
87
116
 
117
+ # `[[wire, definition], ...]` for `audience`, every alias included,
118
+ # ordered by wire name.
119
+ def wires(audience)
120
+ definitions.flat_map { |definition| definition.wire_names(audience).map { |wire| [ wire, definition ] } }
121
+ .sort_by(&:first)
122
+ end
123
+
124
+ # `[[wire, value, tombstone], ...]`: the static wires removed flags still
125
+ # serve to `audience` (whatever the date), ordered by wire name.
126
+ def deprecated_wires(audience)
127
+ audience = audience.to_sym
128
+ @tombstones.values.flat_map do |tombstone|
129
+ tombstone.serve.fetch(audience, {}).map { |wire, value| [ wire, value, tombstone ] }
130
+ end.sort_by(&:first)
131
+ end
132
+
88
133
  def audiences
89
134
  definitions.flat_map(&:audiences).uniq.sort
90
135
  end
91
136
 
137
+ # The Audience named `name`: from `config.audiences` when it is set,
138
+ # else a private audience for any name a flag exposes to. nil when
139
+ # unknown.
140
+ def audience(name)
141
+ name = name.to_sym
142
+ declared = StandardFlags.config.audiences
143
+ return declared[name] if declared
144
+
145
+ served = audiences.include?(name) || @tombstones.each_value.any? { |tombstone| tombstone.serve.key?(name) }
146
+ Audience.new(name: name, public: false, unit: nil) if served
147
+ end
148
+
92
149
  # The logical environment name ("staging", "production", ...). Apps whose
93
150
  # staging boots with RAILS_ENV=production pass their own `env_resolver`.
94
151
  def current_env
@@ -140,25 +197,72 @@ module StandardFlags
140
197
  end
141
198
  end
142
199
 
143
- def tombstone(key, removed:)
200
+ # `serve:` keeps a removed flag's client wires answering a static value
201
+ # (`{ audience => { wire => value } }`) until `until:` (a date, served
202
+ # through that day in UTC; required), and, per platform, only for
203
+ # clients below `until_clients:` (`{ platform => version }`), which can
204
+ # stop them sooner but never extend them.
205
+ #
206
+ # tombstone :chat_v1, removed: "2026-12-01", serve: { mobile: { chat_v1: false } },
207
+ # until: "2027-03-01", until_clients: { android: "0.6.0" }
208
+ def tombstone(key, removed:, serve: nil, until: nil, until_clients: nil)
144
209
  key = key.to_sym
145
210
  raise DefinitionError, "tombstone :#{key} is declared twice" if @tombstones.key?(key)
146
211
 
147
- date = Date.iso8601(removed.to_s)
148
- @tombstones[key] = Tombstone.new(key: key, removed: date)
149
- rescue Date::Error
150
- raise DefinitionError, "tombstone :#{key} removed: #{removed.inspect} is not a YYYY-MM-DD date"
212
+ removed = tombstone_date(key, :removed, removed)
213
+ serve_until = binding.local_variable_get(:until)
214
+ @tombstones[key] = Tombstone.new(key: key, removed: removed, **tombstone_serve(key, removed, serve, serve_until, until_clients))
151
215
  end
152
216
 
153
217
  def build
154
218
  validate_tombstones!
155
219
  validate_units!
220
+ validate_audiences!
156
221
  validate_wire_names!
157
222
  Registry.new(flags: @flags, tombstones: @tombstones, units: @units, env_resolver: @env_resolver)
158
223
  end
159
224
 
160
225
  private
161
226
 
227
+ def tombstone_date(key, attribute, value)
228
+ Date.iso8601(value.to_s)
229
+ rescue Date::Error
230
+ raise DefinitionError, "tombstone :#{key} #{attribute}: #{value.inspect} is not a YYYY-MM-DD date"
231
+ end
232
+
233
+ def tombstone_serve(key, removed, serve, serve_until, until_clients)
234
+ fail = ->(message) { raise DefinitionError, "tombstone :#{key} #{message}" }
235
+ if serve.nil?
236
+ fail.call("until: needs serve:") unless serve_until.nil?
237
+ fail.call("until_clients: needs serve:") unless until_clients.nil?
238
+ return {}
239
+ end
240
+
241
+ fail.call("serve: must be a Hash of audience => { wire => value }") unless serve.is_a?(Hash) && !serve.empty?
242
+ fail.call("serve: needs until: (the last day the wire is served; until_clients: can only stop it sooner)") if serve_until.nil?
243
+ statics = serve.to_h do |audience, wires|
244
+ fail.call("serve: for :#{audience} must be a Hash of wire => value") unless wires.is_a?(Hash) && !wires.empty?
245
+ [ audience.to_sym, wires.to_h { |wire, value| tombstone_wire(fail, wire, value) }.freeze ]
246
+ end
247
+ date = serve_until && tombstone_date(key, :until, serve_until)
248
+ fail.call("until: #{date.iso8601} is before removed: #{removed.iso8601}") if date && date < removed
249
+ clients =
250
+ if until_clients.nil? then {}
251
+ elsif until_clients.is_a?(Hash) then Definition.client_versions(until_clients) { |message| fail.call("until_clients: #{message}") }
252
+ else fail.call("until_clients: must be a Hash of platform => version")
253
+ end
254
+ { serve: statics.freeze, serve_until: date, until_clients: clients }
255
+ end
256
+
257
+ def tombstone_wire(fail, wire, value)
258
+ wire = wire.to_s
259
+ fail.call("serve: wire name #{wire.inspect} must match #{Definition::WIRE_FORMAT.inspect}") unless wire.match?(Definition::WIRE_FORMAT)
260
+ value = value.to_s if value.is_a?(Symbol)
261
+ fail.call("serve: #{wire} must serve true, false or a String, not #{value.inspect}") unless [ true, false ].include?(value) || value.is_a?(String)
262
+ fail.call("serve: #{wire} must be valid UTF-8") if value.is_a?(String) && !value.dup.force_encoding(Encoding::UTF_8).valid_encoding?
263
+ [ wire.freeze, value.is_a?(String) ? value.dup.force_encoding(Encoding::UTF_8).freeze : value ]
264
+ end
265
+
162
266
  def add(definition)
163
267
  raise DefinitionError, "flag :#{definition.key} is declared twice" if @flags.key?(definition.key)
164
268
 
@@ -184,18 +288,59 @@ module StandardFlags
184
288
  end
185
289
  end
186
290
 
291
+ # A wire name is unique within an audience across flags, their aliases
292
+ # and tombstones' static wires.
187
293
  def validate_wire_names!
188
294
  seen = Hash.new { |hash, audience| hash[audience] = {} }
295
+ claim = lambda do |audience, wire, owner|
296
+ if (other = seen[audience][wire])
297
+ raise DefinitionError, "wire name #{wire.inspect} for audience :#{audience} is used by both #{other} and #{owner}"
298
+ end
299
+ seen[audience][wire] = owner
300
+ end
189
301
  @flags.each_value do |definition|
190
- definition.expose.each do |audience, wire|
191
- if (other = seen[audience][wire])
192
- raise DefinitionError,
193
- "wire name #{wire.inspect} for audience :#{audience} is used by both :#{other} and :#{definition.key}"
194
- end
195
- seen[audience][wire] = definition.key
302
+ definition.exposure.each do |audience, wires|
303
+ wires.each { |wire| claim.call(audience, wire, ":#{definition.key}") }
304
+ end
305
+ end
306
+ @tombstones.each_value do |tombstone|
307
+ tombstone.serve.each do |audience, wires|
308
+ wires.each_key { |wire| claim.call(audience, wire, "tombstone :#{tombstone.key}") }
196
309
  end
197
310
  end
198
311
  end
312
+
313
+ # With `config.audiences` set, every audience used must be declared. A
314
+ # public audience's unit must be declared, and its flags may only use
315
+ # that unit (or none): nothing else is known before authentication.
316
+ def validate_audiences!
317
+ declared = StandardFlags.config.audiences
318
+ return if declared.nil?
319
+
320
+ used = @flags.values.flat_map { |definition| definition.audiences.map { |audience| [ audience, ":#{definition.key}" ] } } +
321
+ @tombstones.values.flat_map { |tombstone| tombstone.serve.keys.map { |audience| [ audience, "tombstone :#{tombstone.key}" ] } }
322
+ used.each do |audience, owner|
323
+ next if declared.key?(audience)
324
+
325
+ raise DefinitionError, "#{owner} uses audience :#{audience}, which config.audiences doesn't declare"
326
+ end
327
+ declared.each_value { |audience| validate_public_audience!(audience) if audience.public? }
328
+ end
329
+
330
+ def validate_public_audience!(audience)
331
+ if audience.unit && !@units.key?(audience.unit)
332
+ raise DefinitionError, "audience :#{audience.name} uses undeclared unit :#{audience.unit}"
333
+ end
334
+
335
+ @flags.each_value do |definition|
336
+ next unless definition.audiences.include?(audience.name)
337
+ next if definition.unit.nil? || definition.unit == audience.unit
338
+
339
+ raise DefinitionError,
340
+ "#{definition.kind} :#{definition.key} is exposed to public audience :#{audience.name} but uses unit " \
341
+ ":#{definition.unit}; a public audience can only target #{audience.unit ? "unit :#{audience.unit}" : 'no unit'}"
342
+ end
343
+ end
199
344
  end
200
345
  end
201
346
  end
@@ -73,6 +73,7 @@ module StandardFlags
73
73
 
74
74
  snapshot = RuleSnapshot.build(store.load, revision: revision, checked_at: checked_at)
75
75
  Reporting.instrument(:runtime_refresh, revision: snapshot.revision, rules: snapshot.rules.size)
76
+ Runtime.warn_public_targeting(snapshot)
76
77
  snapshot
77
78
  rescue StandardError => e
78
79
  failed(current || RuleSnapshot.empty, checked_at, e)
@@ -14,8 +14,10 @@ module StandardFlags
14
14
  # wins over any other (TARGETING_MATCH, "deny" / "allow");
15
15
  # 2. attached cohorts the unit belongs to; one serving the off value
16
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
17
+ # 3. segments, asked of `config.segment_resolver` ("segment:<name>"),
18
+ # never for an AnonymousContext;
19
+ # 4. client conditions (platforms, version and build ranges for the
20
+ # client's platform, all of which must hold); when unmet, skip
19
21
  # straight to the fallthrough;
20
22
  # 5. the percentage: a unit whose rollout bucket is below
21
23
  # `percentage_bps` gets the variant weights' pick when there are
@@ -146,9 +148,11 @@ module StandardFlags
146
148
  end
147
149
  end
148
150
 
151
+ # Skipped for an anonymous (pre-authentication) context: the app's
152
+ # resolver may read whoever is signed in.
149
153
  def segments
150
154
  resolver = StandardFlags.config.segment_resolver
151
- return unless resolver
155
+ return if resolver.nil? || context.anonymous?
152
156
 
153
157
  rule.segments.each do |segment|
154
158
  name = segment["name"].to_s
@@ -157,29 +161,34 @@ module StandardFlags
157
161
  nil
158
162
  end
159
163
 
164
+ # A client with no platform skips per-platform ranges (as 0.2.2 did);
165
+ # one whose platform is unknown meets no platform-scoped condition.
160
166
  def client_conditions_met?
161
167
  platforms = rule.platforms
162
168
  versions = rule.versions
163
- return true if platforms.empty? && versions.empty?
169
+ builds = rule.builds
170
+ return true if platforms.empty? && versions.empty? && builds.empty?
164
171
 
165
- platform = context.client[:platform]&.to_s&.downcase
172
+ client = context.client
173
+ return false if client.unknown_platform?
174
+
175
+ platform = client.platform
166
176
  return false if platforms.any? && !platforms.include?(platform)
177
+ return true if platform.nil?
167
178
 
168
- requirement = platform && versions[platform]
169
- requirement.nil? || version_satisfies?(requirement, context.client[:version])
179
+ in_range?(VersionRange, versions[platform], client[:version]) && in_range?(BuildRange, builds[platform], client[:build])
170
180
  end
171
181
 
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?
182
+ # A missing range is met; a client value that's missing (or didn't
183
+ # parse) meets no range; a stored range that doesn't parse fails the
184
+ # flag.
185
+ def in_range?(kind, stored, value)
186
+ return true if stored.nil?
187
+
188
+ range = kind.parse(stored.to_s)
189
+ raise Invalid, "has an invalid #{kind == BuildRange ? 'build' : 'version'} range #{stored.inspect}" unless range
179
190
 
180
- parsed.satisfied_by?(Gem::Version.new(version.to_s.strip))
181
- rescue ArgumentError
182
- false # an unparseable client version meets no range
191
+ range.satisfied_by?(value)
183
192
  end
184
193
 
185
194
  def split(key)
@@ -68,12 +68,19 @@ module StandardFlags
68
68
  shaped(condition("platforms") || [], Array, "conditions.platforms").map { |platform| platform.to_s.downcase }
69
69
  end
70
70
 
71
- # `{ "android" => ">= 1.4.0" }`
71
+ # `{ "android" => ">=1.4.0 <2.0.0" }` (a StandardFlags::VersionRange;
72
+ # RubyGems requirements stored by 0.2.x still read)
72
73
  def versions
73
74
  shaped(condition("versions") || {}, Hash, "conditions.versions")
74
75
  .to_h { |platform, requirement| [ platform.to_s.downcase, requirement ] }
75
76
  end
76
77
 
78
+ # `{ "android" => ">=120 <200" }` (a StandardFlags::BuildRange)
79
+ def builds
80
+ shaped(condition("builds") || {}, Hash, "conditions.builds")
81
+ .to_h { |platform, range| [ platform.to_s.downcase, range ] }
82
+ end
83
+
77
84
  # `{ variant => weight }`
78
85
  def weights
79
86
  shaped(variant_weights, Hash, "variant_weights")
@@ -136,7 +136,7 @@ module StandardFlags
136
136
  store: store.class.name,
137
137
  ready: readiness == true,
138
138
  unreachable: (readiness unless readiness == true || readiness == false),
139
- warnings: store_warnings,
139
+ warnings: store_warnings + public_targeting(registry, snapshot).map { |found| public_targeting_message(found) },
140
140
  loaded: snapshot.loaded,
141
141
  stale: snapshot.stale,
142
142
  revision: snapshot.revision,
@@ -206,6 +206,41 @@ module StandardFlags
206
206
  end
207
207
  end
208
208
 
209
+ # `[{ key:, audience: }, ...]` for flags exposed to a public audience
210
+ # whose stored rule has members or attached cohorts. Pre-auth answers
211
+ # are public: anyone who knows (or guesses) an install key reads what
212
+ # it gets, so a membership there is visible to the world.
213
+ def public_targeting(registry, snapshot)
214
+ declared = StandardFlags.config.audiences
215
+ return [] if declared.nil?
216
+
217
+ public = declared.values.select(&:public?).map(&:name)
218
+ return [] if public.empty?
219
+
220
+ snapshot.rules.values.sort_by(&:key).filter_map do |rule|
221
+ definition = registry[rule.key]
222
+ audience = definition && (definition.audiences & public).first
223
+ next unless audience && targeted?(rule)
224
+
225
+ { key: rule.key, audience: audience }
226
+ end
227
+ end
228
+
229
+ def public_targeting_message(found)
230
+ ":#{found[:key]} is exposed to public audience :#{found[:audience]} and its runtime rule has members or " \
231
+ "cohorts; pre-auth answers are public, so use unguessable install keys"
232
+ end
233
+
234
+ # Logs (through the `public_targeting.standard_flags` event) each flag
235
+ # public_targeting finds, once per process, whenever rules load.
236
+ def warn_public_targeting(snapshot)
237
+ public_targeting(StandardFlags.registry, snapshot).each do |found|
238
+ Reporting.once(:public_targeting, found[:key]) { Reporting.instrument(:public_targeting, found) }
239
+ end
240
+ rescue StandardError
241
+ nil
242
+ end
243
+
209
244
  private
210
245
 
211
246
  def now
@@ -254,6 +289,12 @@ module StandardFlags
254
289
  []
255
290
  end
256
291
 
292
+ def targeted?(rule)
293
+ rule.members? || rule.cohort_attachments.any?
294
+ rescue StandardError
295
+ false
296
+ end
297
+
257
298
  def rule_status(registry, rule)
258
299
  orphan = if registry.tombstoned?(rule.key) then :tombstoned
259
300
  elsif !registry.key?(rule.key) then :undeclared
@@ -0,0 +1,141 @@
1
+ module StandardFlags
2
+ # A client version: SemVer 2.0 (`MAJOR.MINOR.PATCH`, an optional
3
+ # `-prerelease` and an ignored `+build`), plus the shorthands `MAJOR.MINOR`
4
+ # and `MAJOR`, whose missing parts are 0. A shorthand takes no prerelease
5
+ # or build suffix.
6
+ #
7
+ # StandardFlags::Version.parse("1.4.0-beta.2") < StandardFlags::Version.parse("1.4") # => true
8
+ # StandardFlags::Version.parse("v1.4") # => nil
9
+ #
10
+ # Surrounding ASCII spaces and tabs are ignored; anything else outside the
11
+ # grammar (other whitespace, non-ASCII bytes, more than 128 characters)
12
+ # doesn't parse. Values that aren't Strings are read through `to_s`, so a
13
+ # Gem::Version or a Float (`1.4`) parses too.
14
+ #
15
+ # Ordering follows SemVer §11: numbers compare by value; a prerelease sorts
16
+ # before its release; prerelease identifiers compare left to right,
17
+ # numeric ones by value and below alphanumeric ones, alphanumeric ones in
18
+ # ASCII order, and a shorter list first when the rest are equal. Build
19
+ # metadata is ignored, so `1.4.0+381 == 1.4.0`. Numbers have no size limit
20
+ # (with no leading zeros, comparing by length and then digit by digit
21
+ # gives the same order, which is how a language without big integers
22
+ # matches).
23
+ class Version
24
+ include Comparable
25
+
26
+ NUMBER = /0|[1-9]\d*/
27
+ IDENTIFIER = /0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*/
28
+ PATTERN = /
29
+ \A(?<major>#{NUMBER})
30
+ (?:\.(?<minor>#{NUMBER})
31
+ (?:\.(?<patch>#{NUMBER})
32
+ (?:-(?<prerelease>#{IDENTIFIER}(?:\.#{IDENTIFIER})*))?
33
+ (?:\+(?<build>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?
34
+ )?
35
+ )?\z
36
+ /x
37
+ # Longest string `parse` reads, so a header can't make it do much work.
38
+ MAX_LENGTH = 128
39
+ # ASCII space and tab, the only blanks ignored around a version.
40
+ BLANKS = [ 32, 9 ].freeze
41
+
42
+ attr_reader :major, :minor, :patch, :prerelease, :build
43
+
44
+ # The Version for `text`, or nil when it isn't one. Takes a Version too.
45
+ def self.parse(text)
46
+ return text if text.is_a?(Version)
47
+
48
+ text = clean(text)
49
+ return nil if text.nil? || text.length > MAX_LENGTH
50
+
51
+ match = PATTERN.match(text)
52
+ match && new(match)
53
+ end
54
+
55
+ # `value.to_s` without surrounding ASCII spaces and tabs, or nil when it
56
+ # is nil or holds anything but ASCII (invalid UTF-8 included), so
57
+ # nothing downstream can raise on its encoding.
58
+ #
59
+ # @api private
60
+ def self.clean(value)
61
+ return nil if value.nil?
62
+
63
+ bytes = value.to_s.b
64
+ return nil unless bytes.ascii_only?
65
+
66
+ # A byte scan rather than a regex, so a long run of blanks costs
67
+ # linear time.
68
+ first = 0
69
+ last = bytes.bytesize
70
+ first += 1 while first < last && BLANKS.include?(bytes.getbyte(first))
71
+ last -= 1 while last > first && BLANKS.include?(bytes.getbyte(last - 1))
72
+ bytes.byteslice(first, last - first).force_encoding(Encoding::UTF_8)
73
+ end
74
+
75
+ def self.parse!(text)
76
+ parse(text) || raise(ArgumentError, "#{text.inspect} is not a version")
77
+ end
78
+
79
+ def initialize(match)
80
+ @major = match[:major].to_i
81
+ @minor = match[:minor].to_i
82
+ @patch = match[:patch].to_i
83
+ @prerelease = match[:prerelease].to_s.split(".").map { |id| id.match?(/\A\d+\z/) ? id.to_i : id.freeze }.freeze
84
+ @build = match[:build]&.freeze
85
+ freeze
86
+ end
87
+
88
+ def prerelease?
89
+ !prerelease.empty?
90
+ end
91
+
92
+ def <=>(other)
93
+ return nil unless other.is_a?(Version)
94
+
95
+ ([ major, minor, patch ] <=> [ other.major, other.minor, other.patch ]).nonzero? ||
96
+ compare_prerelease(other.prerelease)
97
+ end
98
+
99
+ def eql?(other)
100
+ other.is_a?(Version) && (self <=> other).zero?
101
+ end
102
+
103
+ def hash
104
+ [ self.class, major, minor, patch, prerelease ].hash
105
+ end
106
+
107
+ # The full form without build metadata: "1.4.0", "1.4.0-beta.2".
108
+ def to_s
109
+ release = "#{major}.#{minor}.#{patch}"
110
+ prerelease? ? "#{release}-#{prerelease.join('.')}" : release
111
+ end
112
+
113
+ def inspect
114
+ "#<StandardFlags::Version #{self}>"
115
+ end
116
+
117
+ private
118
+
119
+ def compare_prerelease(other)
120
+ return 0 if prerelease.empty? && other.empty?
121
+ return 1 if prerelease.empty?
122
+ return -1 if other.empty?
123
+
124
+ prerelease.zip(other).each do |mine, theirs|
125
+ return 1 if theirs.nil?
126
+
127
+ order = compare_identifier(mine, theirs)
128
+ return order unless order.zero?
129
+ end
130
+ prerelease.size <=> other.size
131
+ end
132
+
133
+ def compare_identifier(mine, theirs)
134
+ case [ mine.is_a?(Integer), theirs.is_a?(Integer) ]
135
+ when [ true, false ] then -1
136
+ when [ false, true ] then 1
137
+ else mine <=> theirs
138
+ end
139
+ end
140
+ end
141
+ end
@@ -10,11 +10,14 @@ module StandardFlags
10
10
  # * forbidden.standard_flags — a `forbidden_in` flag pinned on
11
11
  # * legacy_env.standard_flags — a legacy env name in use
12
12
  # * runtime_refresh.standard_flags — runtime rules reloaded
13
+ # * public_targeting.standard_flags — a public-audience flag's rule has members or cohorts
13
14
  # * runtime_stale.standard_flags — a runtime refresh failed; the
14
15
  # last good rules keep serving
15
16
  # * rule_invalid.standard_flags — a stored rule its flag can't serve
16
17
  # * targeting_key_missing.standard_flags — a rule needs a unit key the
17
18
  # context doesn't have
19
+ # * client_invalid.standard_flags — a client header that didn't
20
+ # parse (field and header name)
18
21
  #
19
22
  # @api private
20
23
  class Subscribers
@@ -64,14 +64,16 @@ module StandardFlags
64
64
  # Testing.rule(:home_hero, variants: { "control" => 5_000, "savings" => 5_000 })
65
65
  # Testing.rule(:new_checkout, status: :stopped, stop: true)
66
66
  # Testing.rule(:new_checkout, cohorts: { staff: true }, platforms: %w[ios], versions: { ios: ">= 2.0" })
67
+ # Testing.rule(:new_checkout, percentage: 10_000, builds: { android: ">=120" })
67
68
  #
68
69
  # The salt and hash version default to the flag's `bucketing:` or to
69
70
  # (key, 2).
70
71
  def rule(key, status: :running, percentage: nil, rollout: nil, variants: nil, fallthrough: nil, stop: nil,
71
- cohorts: nil, segments: nil, platforms: nil, versions: nil, salt: nil, hash_version: nil)
72
+ cohorts: nil, segments: nil, platforms: nil, versions: nil, builds: nil, salt: nil, hash_version: nil)
72
73
  definition = definition_for(key, nil)
73
74
  conditions = { "segments" => segment_list(segments), "platforms" => platforms&.map(&:to_s),
74
- "versions" => versions&.to_h { |platform, range| [ platform.to_s, range.to_s ] } }.compact
75
+ "versions" => versions&.to_h { |platform, range| [ platform.to_s, range.to_s ] },
76
+ "builds" => builds&.to_h { |platform, range| [ platform.to_s, range.to_s ] } }.compact
75
77
  attributes = {
76
78
  status: status, percentage_bps: percentage, rollout_value: rollout, variant_weights: variants || {},
77
79
  fallthrough_value: fallthrough, stop_value: stop, conditions: conditions, cohorts: cohorts || [],
@@ -63,7 +63,9 @@ module StandardFlags
63
63
 
64
64
  # `flags:stale`: flags and modes past their remove_by date. Each one's
65
65
  # `final:` value says which branch to keep when deleting it. Permanent
66
- # flags have no remove_by date, so they never appear.
66
+ # flags have no remove_by date, so they never appear. Tombstones whose
67
+ # `serve:` block is past its `until:` date are listed too: their static
68
+ # wires are no longer served, so the block can be deleted.
67
69
  #
68
70
  # With runtime rules on it also lists rules worth cleaning up: at 100%
69
71
  # or stopped for 30 days or more, not evaluated in 14 days (when
@@ -85,6 +87,11 @@ module StandardFlags
85
87
  @registry.definitions.select { |definition| definition.stale?(@today) }.sort_by(&:remove_by)
86
88
  end
87
89
 
90
+ # Tombstones whose static wires stopped being served after `until:`.
91
+ def expired_serves
92
+ @registry.tombstones.values.select { |tombstone| tombstone.serve_expired?(@today) }.sort_by(&:key)
93
+ end
94
+
88
95
  def render
89
96
  stale = definitions
90
97
  lines =
@@ -97,6 +104,7 @@ module StandardFlags
97
104
  "was due for removal on #{definition.remove_by.iso8601}#{final}"
98
105
  end
99
106
  end
107
+ lines.concat(serve_lines)
100
108
  lines.concat(runtime_lines) if Runtime.enabled?
101
109
  lines.join("\n")
102
110
  end
@@ -118,6 +126,14 @@ module StandardFlags
118
126
  @store || Runtime.store
119
127
  end
120
128
 
129
+ def serve_lines
130
+ expired_serves.map do |tombstone|
131
+ wires = tombstone.serve.flat_map { |audience, statics| statics.keys.map { |wire| "#{audience}.#{wire}" } }
132
+ "tombstone #{tombstone.key} stopped serving #{wires.sort.join(', ')} after #{tombstone.serve_until.iso8601}; " \
133
+ "its serve: block can be removed"
134
+ end
135
+ end
136
+
121
137
  def runtime_lines
122
138
  findings = runtime_findings
123
139
  findings.empty? ? [ "No stale runtime rules." ] : findings
@@ -217,6 +233,9 @@ module StandardFlags
217
233
  # `standard_flags:manifest`: a deterministic description of the flag set
218
234
  # (keys, wire names, kinds, values, audiences, defaults) for client CI.
219
235
  # Entries of kind `flag` and `mode` also say whether they are permanent.
236
+ # `audiences` maps each audience to its first wire name, as in version 1;
237
+ # a flag with aliases also lists every wire name per audience under
238
+ # `wires`, so a version 1 reader still reads it.
220
239
  class Manifest
221
240
  VERSION = 1
222
241
  LIFECYCLE_KINDS = %i[flag mode].freeze
@@ -250,6 +269,9 @@ module StandardFlags
250
269
  "default" => default(definition),
251
270
  "audiences" => definition.expose.sort.to_h { |audience, name| [ audience.to_s, name ] }
252
271
  }
272
+ if definition.exposure.any? { |_, wires| wires.size > 1 }
273
+ entry["wires"] = definition.exposure.sort.to_h { |audience, wires| [ audience.to_s, wires ] }
274
+ end
253
275
  entry["permanent"] = definition.permanent? if LIFECYCLE_KINDS.include?(definition.kind)
254
276
  entry
255
277
  end
@@ -391,8 +413,8 @@ module StandardFlags
391
413
  out = [ "// Generated by `bin/rails standard_flags:typescript`. Do not edit by hand.", "" ]
392
414
  audiences.each do |audience|
393
415
  out << "export interface #{interface_name(audience)} {"
394
- @registry.exposed(audience).each do |definition|
395
- out << " readonly #{property(definition.wire_name(audience))}: #{type(definition)};"
416
+ @registry.wires(audience).each do |wire, definition|
417
+ out << " readonly #{property(wire)}: #{type(definition)};"
396
418
  end
397
419
  out << "}" << ""
398
420
  end
@@ -1,3 +1,3 @@
1
1
  module StandardFlags
2
- VERSION = "0.2.2"
2
+ VERSION = "0.3.0"
3
3
  end