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
@@ -0,0 +1,355 @@
1
+ require "date"
2
+ require "json"
3
+
4
+ module StandardFlags
5
+ module Tooling
6
+ # `standard_flags:manifest:check`: fails server CI when the committed
7
+ # manifest no longer describes the registry, or when the registry broke
8
+ # the contract shipped clients were built against.
9
+ #
10
+ # * **stale**: the committed file differs from what
11
+ # `standard_flags:manifest` writes now, ignoring CRLF line endings and
12
+ # trailing newlines (or there is no committed file). Regenerating and
13
+ # committing fixes it.
14
+ # * **removed wire**: a wire the baseline manifest tells an audience is
15
+ # gone from that audience, and no tombstone still serves it (`serve:`
16
+ # with `until:` today or later, in UTC). A shipped client reading it
17
+ # would silently fall back to its code default. A deprecated wire whose
18
+ # `until:` has passed in the baseline may go: its window is over.
19
+ # * **type change**: a wire the baseline and the registry both tell an
20
+ # audience changed JSON type (boolean and string).
21
+ # * **audience made private**: a public audience in the baseline that
22
+ # served wires is no longer public, so clients before sign-in lose
23
+ # every one of them.
24
+ #
25
+ # The baseline is `base:`: in CI, the base branch's manifest, so a PR
26
+ # that regenerates the file in the same commit still can't drop a wire.
27
+ # Without it (`base: :committed`) the committed file is the baseline, and
28
+ # the result warns that a regenerated file hides removals. `base: nil` or
29
+ # an Unavailable (a BASE file that is missing or unreadable) fails with
30
+ # :baseline_unavailable, still reporting a stale committed file, unless
31
+ # `base_optional: true` and the file is genuinely missing (`missing:
32
+ # true`; first adoption: the base branch has no manifest yet), which skips
33
+ # the contract checks with
34
+ # a warning. Any manifest may be version 1.
35
+ #
36
+ # Shortening a deprecated wire's `until:` is a warning, not a break; so
37
+ # is a new wire whose generated Kotlin name (`Kotlin.constant`) is an
38
+ # existing wire's in the same audience (`new_checkout` beside a shipped
39
+ # `newCheckout`): `standard_flags:kotlin` keeps the existing constant when
40
+ # its previous output is in place, and client code should be checked.
41
+ #
42
+ # check = StandardFlags::Tooling::ManifestCheck.new(committed: File.read(path), base: base_json)
43
+ # result = check.call
44
+ # puts check.render(result)
45
+ # exit result.exit_code
46
+ #
47
+ # Exit codes: 0 ok; 1 stale or missing (regenerate); 2 a contract break,
48
+ # an unavailable baseline or an unreadable manifest (regenerating won't
49
+ # fix it, unless the unreadable one is the committed file).
50
+ class ManifestCheck
51
+ STATUSES = %i[ok missing stale breaking unreadable baseline_unavailable].freeze
52
+ EXIT_CODES = { ok: 0, missing: 1, stale: 1, breaking: 2, unreadable: 2, baseline_unavailable: 2 }.freeze
53
+ NO_BASE_WARNING = "no BASE was given: the removed-wire and type checks compared the registry with the committed " \
54
+ "file only, which a regenerated file passes; pass BASE= the base branch's manifest in CI".freeze
55
+
56
+ # A baseline that couldn't be read, and why ("tmp/base.json does not
57
+ # exist"). `missing` is true only when the file doesn't exist, the one
58
+ # case `base_optional:` forgives; a directory or a read error never is.
59
+ Unavailable = Data.define(:reason, :missing) do
60
+ def initialize(reason:, missing: false)
61
+ super
62
+ end
63
+ end
64
+
65
+ # One contract break. `kind` is :removed_wire, :type_changed or
66
+ # :audience_made_private (`wire` nil).
67
+ Finding = Data.define(:kind, :audience, :wire, :from, :to, :detail) do
68
+ def to_h
69
+ case kind
70
+ when :removed_wire then { "audience" => audience, "wire" => wire }
71
+ when :audience_made_private then { "audience" => audience }
72
+ else { "audience" => audience, "wire" => wire, "from" => from, "to" => to }
73
+ end
74
+ end
75
+ end
76
+
77
+ Result = Data.define(:status, :stale, :changes, :removed_wires, :type_changes, :audiences_made_private,
78
+ :warnings, :error, :error_source) do
79
+ def ok?
80
+ status == :ok
81
+ end
82
+
83
+ def exit_code
84
+ EXIT_CODES.fetch(status)
85
+ end
86
+
87
+ def findings
88
+ removed_wires + type_changes + audiences_made_private
89
+ end
90
+
91
+ # Whether regenerating the committed file is (part of) the fix.
92
+ def regenerate?
93
+ case status
94
+ when :missing, :stale then true
95
+ when :breaking, :baseline_unavailable then stale
96
+ when :unreadable then error_source == :committed
97
+ else false
98
+ end
99
+ end
100
+ end
101
+
102
+ # A manifest that can't be read, and which one (:committed, :base or
103
+ # :current).
104
+ class SourceError < Error
105
+ attr_reader :source
106
+
107
+ def initialize(source, message)
108
+ @source = source
109
+ super(message)
110
+ end
111
+ end
112
+ private_constant :SourceError
113
+
114
+ # `committed` and `base` are a manifest's JSON text (as read from disk)
115
+ # or a parsed Hash; `committed` is nil when there is no such file.
116
+ # `current` is the registry's manifest as a Hash (Manifest#to_h);
117
+ # `current_render` its text, compared with a committed String. `today`
118
+ # is a UTC date.
119
+ def initialize(committed:, base: :committed, base_optional: false, current: nil, current_render: nil,
120
+ today: Delivery.utc_today, registry: StandardFlags.registry)
121
+ manifest = Manifest.new(registry: registry) if current.nil? || current_render.nil?
122
+ @committed = committed
123
+ @base = base
124
+ @base_optional = base_optional
125
+ @current = current || manifest.to_h
126
+ @current_render = current_render || (current ? Manifest.format(current) : manifest.render)
127
+ @today = today
128
+ end
129
+
130
+ def call
131
+ warnings = []
132
+ current = read(@current, :current)
133
+ committed = @committed.nil? ? nil : read(@committed, :committed)
134
+ base =
135
+ case @base
136
+ when :committed
137
+ warnings << NO_BASE_WARNING
138
+ committed
139
+ when nil, Unavailable
140
+ reason = @base.is_a?(Unavailable) ? @base.reason : "no baseline was given"
141
+ forgiven = @base_optional && (@base.nil? || @base.missing)
142
+ return unavailable(reason, committed, current) unless forgiven
143
+
144
+ warnings << "no baseline (#{reason}; BASE_OPTIONAL): the removed-wire and type checks were skipped"
145
+ nil
146
+ else read(@base, :base)
147
+ end
148
+ stale = committed.nil? || stale?
149
+ removed, changed, privatised = base ? breaks(base, current) : [ [], [], [] ]
150
+ warnings.concat(shortened_until(base, current) + kotlin_collisions(base, current)) if base
151
+ result(status(removed + changed + privatised, committed, stale), stale: stale, changes: committed && stale ? self.class.changes(committed.data, current.data) : [],
152
+ removed_wires: removed, type_changes: changed, audiences_made_private: privatised, warnings: warnings)
153
+ rescue SourceError => e
154
+ result(:unreadable, stale: e.source == :committed, error: e.message, error_source: e.source)
155
+ end
156
+
157
+ # The report printed by the rake task. `path` names the committed file.
158
+ def render(result, path: "the committed manifest")
159
+ lines =
160
+ case result.status
161
+ when :ok then [ "standard_flags:manifest:check OK: #{path} matches the registry" ]
162
+ when :unreadable then [ "standard_flags:manifest:check: can't read the #{result.error_source} manifest: #{result.error}" ]
163
+ when :baseline_unavailable
164
+ [ "standard_flags:manifest:check: the baseline manifest is unavailable (#{result.error}). The removed-wire and " \
165
+ "type checks need it; set BASE_OPTIONAL=1 only when the base branch has no manifest yet." ]
166
+ else []
167
+ end
168
+ lines.concat(result.warnings.map { |warning| "standard_flags:manifest:check: warning: #{warning}" })
169
+ lines << "standard_flags:manifest:check: #{path} does not exist" if result.status == :missing || (result.status == :breaking && @committed.nil?)
170
+ lines.concat(break_lines(result)) unless result.findings.empty?
171
+ unless result.changes.empty?
172
+ lines << "standard_flags:manifest:check: #{path} is stale:"
173
+ lines.concat(result.changes.map { |change| " #{change}" })
174
+ end
175
+ lines << "Run bin/rails standard_flags:manifest and commit the result." if result.regenerate?
176
+ lines.join("\n")
177
+ end
178
+
179
+ # Human-readable differences between two manifest Hashes, one String
180
+ # each: `+`/`-` for an added or removed flag, tombstone or top-level
181
+ # entry, `~` with the fields that changed.
182
+ def self.changes(old, new)
183
+ lines = []
184
+ same_version = old["version"] == new["version"]
185
+ unless same_version
186
+ lines << "~ version: #{old['version'].inspect} → #{new['version'].inspect} (regenerating upgrades the format)"
187
+ end
188
+ ((old.keys | new.keys) - %w[version flags tombstones]).sort.each do |field|
189
+ lines.concat(field_changes(field, old[field], new[field]))
190
+ end
191
+ lines.concat(keyed_changes("flag", old["flags"], new["flags"], same_version))
192
+ lines.concat(keyed_changes("tombstone", old["tombstones"], new["tombstones"], same_version))
193
+ lines << "the content is identical but the bytes differ; regenerate instead of editing by hand" if lines.empty?
194
+ lines
195
+ end
196
+
197
+ def self.field_changes(field, old, new)
198
+ return [] if old == new
199
+ return [ "+ #{field}" ] if old.nil?
200
+ return [ "- #{field}" ] if new.nil?
201
+ return [ "~ #{field}: #{json(old)} → #{json(new)}" ] unless old.is_a?(Hash) && new.is_a?(Hash)
202
+
203
+ (old.keys | new.keys).sort.filter_map do |name|
204
+ if !old.key?(name) then "+ #{field}.#{name}"
205
+ elsif !new.key?(name) then "- #{field}.#{name}"
206
+ elsif old[name] != new[name] then "~ #{field}.#{name}: #{json(old[name])} → #{json(new[name])}"
207
+ end
208
+ end
209
+ end
210
+
211
+ def self.keyed_changes(label, old, new, detail)
212
+ old = Array(old).to_h { |entry| [ entry["key"], entry ] }
213
+ new = Array(new).to_h { |entry| [ entry["key"], entry ] }
214
+ (old.keys | new.keys).sort_by(&:to_s).filter_map do |key|
215
+ if !old.key?(key) then "+ #{label} :#{key}"
216
+ elsif !new.key?(key) then "- #{label} :#{key}"
217
+ elsif old[key] != new[key]
218
+ next "~ #{label} :#{key}" unless detail
219
+
220
+ fields = (old[key].keys | new[key].keys).reject { |field| old[key][field] == new[key][field] }
221
+ "~ #{label} :#{key}: " + fields.map { |field| "#{field} #{json(old[key][field])} → #{json(new[key][field])}" }.join("; ")
222
+ end
223
+ end
224
+ end
225
+
226
+ def self.json(value)
227
+ value.nil? ? "(none)" : JSON.generate(value)
228
+ end
229
+
230
+ private
231
+
232
+ # :baseline_unavailable, with the staleness of the committed file still
233
+ # reported.
234
+ def unavailable(reason, committed, current)
235
+ stale = committed.nil? || stale?
236
+ changes = committed && stale ? self.class.changes(committed.data, current.data) : []
237
+ result(:baseline_unavailable, stale: stale, changes: changes, error: reason)
238
+ end
239
+
240
+ def status(findings, committed, stale)
241
+ return :breaking unless findings.empty?
242
+ return :missing if committed.nil?
243
+
244
+ stale ? :stale : :ok
245
+ end
246
+
247
+ def read(value, source)
248
+ Manifest.read(value)
249
+ rescue Manifest::Unreadable => e
250
+ raise SourceError.new(source, e.message)
251
+ end
252
+
253
+ # A committed String is compared as text with CRLF turned into LF and
254
+ # trailing newlines folded into one, so a checkout with CRLF line
255
+ # endings isn't permanently stale; a parsed Hash as a value.
256
+ def stale?
257
+ return normalize(@committed) != normalize(@current_render) if @committed.is_a?(String)
258
+
259
+ @committed != @current
260
+ end
261
+
262
+ # A byte scan rather than a `\n*\z` regex, which is polynomial on a
263
+ # long run of newlines.
264
+ def normalize(text)
265
+ text = text.b.gsub("\r\n", "\n")
266
+ last = text.bytesize
267
+ last -= 1 while last.positive? && text.getbyte(last - 1) == 10
268
+ "#{text.byteslice(0, last)}\n"
269
+ end
270
+
271
+ # Removed wires, type changes and audiences made private, from `base`
272
+ # to `current`.
273
+ def breaks(base, current)
274
+ removed = []
275
+ changed = []
276
+ base.each_wire do |wire|
277
+ now = current.wire(wire.audience, wire.name)
278
+ if now && now.type != wire.type
279
+ changed << finding(:type_changed, wire, from: wire.type, to: now.type,
280
+ detail: "type changed: #{wire} was #{wire.type} and is now #{now.type}")
281
+ end
282
+ next unless wire.served_on?(@today)
283
+ next if now&.served_on?(@today)
284
+
285
+ removed << finding(:removed_wire, wire, detail: removed_detail(wire, now))
286
+ end
287
+ [ removed, changed, privatised(base, current) ]
288
+ end
289
+
290
+ # Public audiences in `base` that served a wire today and aren't public
291
+ # in `current` (one gone altogether shows up as removed wires).
292
+ def privatised(base, current)
293
+ base.audiences.select { |name, public| public && current.audiences[name] == false }.keys.sort.filter_map do |name|
294
+ served = base.wires.fetch(name, {}).values.select { |wire| wire.served_on?(@today) }
295
+ next if served.empty?
296
+
297
+ Finding.new(kind: :audience_made_private, audience: name, wire: nil, from: nil, to: nil,
298
+ detail: "audience made private: #{name} was public, so clients before sign-in lose its " \
299
+ "#{served.size} wire#{'s' unless served.size == 1}; keep it public, or serve those wires elsewhere first")
300
+ end
301
+ end
302
+
303
+ # Deprecated wires whose `until:` moved earlier than the baseline promised.
304
+ def shortened_until(base, current)
305
+ base.each_wire.filter_map do |wire|
306
+ now = current.wire(wire.audience, wire.name)
307
+ next unless wire.static? && wire.served_on?(@today) && now&.static? && now.until < wire.until
308
+
309
+ "tombstone :#{now.key} now serves #{wire} through #{now.until.iso8601}, earlier than the " \
310
+ "#{wire.until.iso8601} shipped clients were promised"
311
+ end
312
+ end
313
+
314
+ # New wires that would take an existing wire's Kotlin entry name.
315
+ def kotlin_collisions(base, current)
316
+ current.each_wire.filter_map do |wire|
317
+ next if base.wire(wire.audience, wire.name)
318
+
319
+ name = Kotlin.constant(wire.name)
320
+ existing = base.wires.fetch(wire.audience, {}).keys.sort.find { |other| Kotlin.constant(other) == name }
321
+ next unless existing
322
+
323
+ "new wire #{wire} and existing wire #{wire.audience}.#{existing} are both #{name} in generated Kotlin; " \
324
+ "regenerate with the previous standard_flags:kotlin output in place so #{existing} keeps #{name}, " \
325
+ "and check which wire client code means"
326
+ end
327
+ end
328
+
329
+ def finding(kind, wire, detail:, from: nil, to: nil)
330
+ Finding.new(kind: kind, audience: wire.audience, wire: wire.name, from: from, to: to, detail: detail)
331
+ end
332
+
333
+ def removed_detail(wire, now)
334
+ if now
335
+ "removed wire: #{wire} is served by tombstone :#{now.key} only through #{now.until.iso8601}, which has passed"
336
+ else
337
+ what = wire.static? ? "tombstone :#{wire.key}, until #{wire.until.iso8601}" : "flag :#{wire.key}"
338
+ "removed wire: #{wire} (#{what}) is gone and no tombstone serves it; keep it exposed, or add " \
339
+ "serve: { #{wire.audience}: { #{wire.name}: <value> } }, until: \"YYYY-MM-DD\" to the tombstone"
340
+ end
341
+ end
342
+
343
+ def break_lines(result)
344
+ [ "standard_flags:manifest:check: the client contract is broken:" ] +
345
+ result.findings.map { |finding| " #{finding.detail}" }
346
+ end
347
+
348
+ def result(status, stale:, changes: [], removed_wires: [], type_changes: [], audiences_made_private: [], warnings: [],
349
+ error: nil, error_source: nil)
350
+ Result.new(status: status, stale: stale, changes: changes, removed_wires: removed_wires, type_changes: type_changes,
351
+ audiences_made_private: audiences_made_private, warnings: warnings, error: error, error_source: error_source)
352
+ end
353
+ end
354
+ end
355
+ end
@@ -3,6 +3,9 @@ require "json"
3
3
  require "pathname"
4
4
  require "active_support/core_ext/string/inflections"
5
5
  require "standard_flags/tooling/changes"
6
+ require "standard_flags/tooling/manifest"
7
+ require "standard_flags/tooling/manifest_check"
8
+ require "standard_flags/tooling/kotlin"
6
9
 
7
10
  module StandardFlags
8
11
  # The logic behind the rake tasks, kept out of the rake file so it can be
@@ -72,6 +75,18 @@ module StandardFlags
72
75
  # `config.track_evaluations` is on), and rules for undeclared or
73
76
  # tombstoned keys; and memberships past `config.membership_retention`
74
77
  # that `flags:purge` would delete.
78
+ #
79
+ # With `config.track_compat` on, it says a compat window "can be
80
+ # removed" only when tracking has run for at least 14 days (the flag's
81
+ # tracking marker), a write has succeeded in the last 2 days (the
82
+ # marker's last flush, so missing hits really mean no use), no hit has
83
+ # landed in the last 14 days, and the window has passed on every
84
+ # platform `until_clients:` names. A platform's window has passed when
85
+ # every client declared for it enforces a minimum at or above the listed
86
+ # version today (UTC), or when no client below that version has used
87
+ # the flag (no hits from the platform, or its oldest version seen is at
88
+ # or above it). Until tracking is old enough it says "not enough data";
89
+ # when writes have stopped succeeding, "tracking unhealthy since …".
75
90
  class Stale
76
91
  SETTLED_AFTER = 30 * 86_400
77
92
  UNUSED_AFTER = 14 * 86_400
@@ -105,6 +120,7 @@ module StandardFlags
105
120
  end
106
121
  end
107
122
  lines.concat(serve_lines)
123
+ lines.concat(compat_lines)
108
124
  lines.concat(runtime_lines) if Runtime.enabled?
109
125
  lines.join("\n")
110
126
  end
@@ -134,6 +150,62 @@ module StandardFlags
134
150
  end
135
151
  end
136
152
 
153
+ def compat_lines
154
+ windows = @registry.definitions.select(&:compat_window?).sort_by(&:key)
155
+ return [] if windows.empty? || !StandardFlags.config.track_compat || !Runtime.enabled?
156
+
157
+ stats = store.compat_stats(windows.map { |definition| definition.key.to_s })
158
+ return [ "compat windows: the runtime store doesn't keep compat stats" ] if stats.nil?
159
+
160
+ by_key = stats.group_by { |stat| stat.key.to_s }
161
+ windows.filter_map { |definition| compat_finding(definition, by_key.fetch(definition.key.to_s, [])) }
162
+ rescue StandardError => e
163
+ [ "compat windows: could not read the stats (#{(e.cause_class if e.is_a?(Runtime::StoreError)) || e.class})" ]
164
+ end
165
+
166
+ def compat_finding(definition, stats)
167
+ marker, stats = stats.partition(&:marker?)
168
+ since = marker.first&.first_seen_at
169
+ if since.nil? || since > @now - Runtime::CompatTracker::IDLE
170
+ tracking = since ? "tracking since #{day(since)}" : "no tracking recorded yet"
171
+ return "compat #{definition.key}: not enough data to judge its window (#{tracking}; needs 14 days)"
172
+ end
173
+ flushed = marker.first.last_flushed_at
174
+ if flushed.nil? || flushed < @now - Runtime::CompatTracker::HEALTHY
175
+ return "compat #{definition.key}: tracking unhealthy since #{day(flushed || since)} (no successful write since); " \
176
+ "not enough data to judge its window"
177
+ end
178
+
179
+ last = stats.filter_map(&:last_hit_at).max
180
+ return if last && last > @now - Runtime::CompatTracker::IDLE
181
+ return unless definition.until_clients.all? { |platform, cutoff| window_passed?(platform, cutoff, stats) }
182
+
183
+ windows = definition.until_clients.map { |platform, cutoff| "#{platform} #{cutoff}" }.join(", ")
184
+ seen = last ? "no hits since #{day(last)}" : "no hits since tracking began on #{day(since)}"
185
+ "compat #{definition.key} (owner: #{definition.owner}) is past its window on every platform (#{windows}) " \
186
+ "and has had #{seen}; it can be removed"
187
+ end
188
+
189
+ def window_passed?(platform, cutoff, stats)
190
+ apps = @registry.clients.each_value.select { |app| app.platform == platform }
191
+ return true if !apps.empty? && apps.all? { |app| enforced_at_least?(app, cutoff) }
192
+
193
+ stat = stats.find { |entry| entry.platform == platform }
194
+ return true if stat.nil?
195
+
196
+ oldest = Version.parse(stat.oldest_version)
197
+ !oldest.nil? && oldest >= cutoff
198
+ end
199
+
200
+ def enforced_at_least?(app, cutoff)
201
+ policy = app.resolve
202
+ return false if policy.min_version.nil? || @now.utc.to_date < policy.enforce_on
203
+
204
+ ceiling = policy.ceiling
205
+ minimum = ceiling ? [ policy.min_version, ceiling ].min : policy.min_version
206
+ minimum >= cutoff
207
+ end
208
+
137
209
  def runtime_lines
138
210
  findings = runtime_findings
139
211
  findings.empty? ? [ "No stale runtime rules." ] : findings
@@ -230,71 +302,73 @@ module StandardFlags
230
302
  end
231
303
  end
232
304
 
233
- # `standard_flags:manifest`: a deterministic description of the flag set
234
- # (keys, wire names, kinds, values, audiences, defaults) for client CI.
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.
239
- class Manifest
240
- VERSION = 1
241
- LIFECYCLE_KINDS = %i[flag mode].freeze
305
+ # `standard_flags:typescript`: a `.d.ts` with one Features interface per
306
+ # audience, keyed by wire name; one `<Audience>Wire` union per audience
307
+ # (every wire it is told, deprecated static wires included, as in the
308
+ # manifest); every flag key and its stored values; the OFREP request and
309
+ # response shapes of StandardFlags::OFREP::Controller; and the shapes of
310
+ # StandardFlags::MCP's results, which the admin pages
311
+ # (`standard_flags:admin`) are typed from.
312
+ class TypeScript
313
+ IDENTIFIER = /\A[A-Za-z_$][A-Za-z0-9_$]*\z/
242
314
 
243
- def initialize(registry: StandardFlags.registry)
244
- @registry = registry
245
- end
315
+ # What the OFREP endpoint (StandardFlags::OFREP::Controller) and
316
+ # `payload(format: :ofrep)` send. Static apart from the wire unions
317
+ # each response is parameterised with.
318
+ OFREP_TYPES = <<~TS.freeze
319
+ // OFREP requests and responses (StandardFlags::OFREP::Controller).
320
+ export type OfrepReason = #{(Reason::ALL - [ Reason::ERROR ]).map(&:to_json).join(' | ')};
321
+ export type OfrepErrorCode = #{Delivery::ERROR_CODES.map(&:to_json).join(' | ')};
322
+
323
+ // Other context fields are ignored by the server; a header wins over the body.
324
+ export interface OfrepEvaluationRequest {
325
+ readonly context: {
326
+ readonly targetingKey?: string;
327
+ readonly platform?: string;
328
+ readonly appVersion?: string;
329
+ readonly app_version?: string;
330
+ readonly build?: string | number;
331
+ readonly [field: string]: unknown;
332
+ };
333
+ }
246
334
 
247
- def to_h
248
- {
249
- "version" => VERSION,
250
- "flags" => @registry.definitions.sort_by(&:key).map { |definition| flag(definition) },
251
- "tombstones" => @registry.tombstones.values.sort_by(&:key).map do |tombstone|
252
- { "key" => tombstone.key.to_s, "removed" => tombstone.removed.iso8601 }
253
- end
335
+ export interface OfrepEvaluationSuccess<W extends string = string> {
336
+ readonly key: W;
337
+ readonly value: boolean | string;
338
+ readonly reason: OfrepReason;
339
+ readonly variant: string;
254
340
  }
255
- end
256
341
 
257
- def render
258
- "#{JSON.pretty_generate(to_h)}\n"
259
- end
342
+ export interface OfrepEvaluationFailure<W extends string = string> {
343
+ readonly key: W;
344
+ readonly errorCode: OfrepErrorCode;
345
+ readonly errorDetails: string;
346
+ }
260
347
 
261
- private
348
+ export type OfrepEvaluation<W extends string = string> = OfrepEvaluationSuccess<W> | OfrepEvaluationFailure<W>;
262
349
 
263
- def flag(definition)
264
- entry = {
265
- "key" => definition.key.to_s,
266
- "kind" => definition.kind.to_s,
267
- "type" => definition.boolean? ? "boolean" : "string",
268
- "values" => definition.allowed_values.map { |value| wire(value) },
269
- "default" => default(definition),
270
- "audiences" => definition.expose.sort.to_h { |audience, name| [ audience.to_s, name ] }
350
+ export interface OfrepBulkResponse<W extends string = string> {
351
+ readonly flags: ReadonlyArray<OfrepEvaluation<W>>;
352
+ readonly metadata: { readonly version: string };
271
353
  }
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
275
- entry["permanent"] = definition.permanent? if LIFECYCLE_KINDS.include?(definition.kind)
276
- entry
277
- end
278
-
279
- def default(definition)
280
- declared = definition.declared_default
281
- return wire(definition.kind_default) if declared.nil?
282
- return wire(declared) unless declared.is_a?(Hash)
283
354
 
284
- { "*" => wire(definition.kind_default) }.merge(declared.sort.to_h { |env, value| [ env, wire(value) ] })
285
- end
355
+ // The single-flag 404. FLAG_NOT_FOUND never appears in a bulk entry.
356
+ export interface OfrepFlagNotFound {
357
+ readonly key: string;
358
+ readonly errorCode: "FLAG_NOT_FOUND";
359
+ readonly errorDetails: string;
360
+ }
286
361
 
287
- def wire(value)
288
- value.is_a?(Symbol) ? value.to_s : value
289
- end
290
- end
362
+ export interface OfrepInvalidContext {
363
+ readonly key?: string;
364
+ readonly errorCode: "INVALID_CONTEXT";
365
+ readonly errorDetails: string;
366
+ }
291
367
 
292
- # `standard_flags:typescript`: a `.d.ts` with one Features interface per
293
- # audience, keyed by wire name; every flag key and its stored values; and
294
- # the shapes of StandardFlags::MCP's results, which the admin pages
295
- # (`standard_flags:admin`) are typed from.
296
- class TypeScript
297
- IDENTIFIER = /\A[A-Za-z_$][A-Za-z0-9_$]*\z/
368
+ export type OfrepBulkResponseByAudience = {
369
+ readonly [A in keyof WiresByAudience]: OfrepBulkResponse<WiresByAudience[A]>;
370
+ };
371
+ TS
298
372
 
299
373
  # The JSON StandardFlags::MCP returns (and the admin controller passes
300
374
  # as props). Static: the flag-specific parts are FlagKey and FlagValues.
@@ -421,13 +495,34 @@ module StandardFlags
421
495
  out << "export type FeaturesByAudience = {"
422
496
  audiences.each { |audience| out << " #{property(audience.to_s)}: #{interface_name(audience)};" }
423
497
  out << "};" << ""
498
+ out.concat(wire_types)
424
499
  out.concat(flag_types)
500
+ out << OFREP_TYPES
425
501
  out << MCP_TYPES
426
502
  out.join("\n")
427
503
  end
428
504
 
429
505
  private
430
506
 
507
+ # `<Audience>Wire` per manifest audience, and WiresByAudience.
508
+ def wire_types
509
+ manifest = Manifest.new(registry: @registry).to_h
510
+ wires = Manifest.wires_in(manifest)
511
+ names = manifest.fetch("audiences").keys.sort
512
+ out = names.map do |audience|
513
+ list = wires.fetch(audience, {}).keys.sort.map(&:to_json)
514
+ "export type #{wire_type_name(audience)} = #{list.empty? ? 'never' : list.join(' | ')};"
515
+ end
516
+ out << "" << "// Every audience the manifest lists, so it may name audiences FeaturesByAudience doesn't."
517
+ out << "export type WiresByAudience = {"
518
+ names.each { |audience| out << " readonly #{property(audience)}: #{wire_type_name(audience)};" }
519
+ out << "};" << ""
520
+ end
521
+
522
+ def wire_type_name(audience)
523
+ "#{audience.to_s.camelize}Wire"
524
+ end
525
+
431
526
  # FlagKey (every declared key) and FlagValues (each flag's stored
432
527
  # values: "on"/"off", mode values, variants).
433
528
  def flag_types
@@ -1,3 +1,3 @@
1
1
  module StandardFlags
2
- VERSION = "0.3.0"
2
+ VERSION = "0.4.0"
3
3
  end
@@ -15,6 +15,9 @@ require "standard_flags/registry"
15
15
  require "standard_flags/semantic_version"
16
16
  require "standard_flags/version_range"
17
17
  require "standard_flags/client"
18
+ require "standard_flags/client_app"
19
+ require "standard_flags/stores"
20
+ require "standard_flags/client_status"
18
21
  require "standard_flags/context"
19
22
  require "standard_flags/memo"
20
23
  require "standard_flags/reporting"