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,319 @@
1
+ require "digest"
2
+ require "set"
3
+ require "active_support/core_ext/string/inflections"
4
+
5
+ module StandardFlags
6
+ module Tooling
7
+ # `standard_flags:kotlin`: plain Kotlin (no dependencies) generated from
8
+ # the version 2 manifest, written to `config.kotlin_path` in
9
+ # `config.kotlin_package`:
10
+ #
11
+ # * `StandardFlagsManifest`: the manifest version and the SHA-256 of the
12
+ # canonical manifest (`Manifest#digest`: what `standard_flags:manifest`
13
+ # writes, LF line endings), so a client build can tell it is out of
14
+ # date;
15
+ # * `FeatureType`: BOOLEAN or STRING, a wire's JSON type;
16
+ # * per audience, `enum class <Audience>Feature(val wire: String, val
17
+ # type: FeatureType)`, one entry per wire (aliases and deprecated
18
+ # static wires included, the latter `@Deprecated`), ordered by wire
19
+ # name, with `fromWire`;
20
+ # * per string flag exposed to any audience (modes and experiments),
21
+ # `enum class <Key>Value(val value: String)` in declared order, with
22
+ # `fromValue`.
23
+ #
24
+ # Entry names are the wire name or value in SCREAMING_SNAKE_CASE
25
+ # (`homeHero` → `HOME_HERO`).
26
+ #
27
+ # Names are stable across regenerations: given the file written last
28
+ # time (`previous:`; the rake task passes the existing
29
+ # `config.kotlin_path`), every wire and value keeps the name it had there,
30
+ # and only new ones are named. So a `new_checkout` alias added later never
31
+ # takes `NEW_CHECKOUT` from a shipped `newCheckout`.
32
+ #
33
+ # A new name never fails on a clash:
34
+ #
35
+ # * Wires of one audience that map to the same name (`new_checkout` and
36
+ # `newCheckout`, an alias pair a rename leaves behind): the spelling
37
+ # that already is the name in some case (`new_checkout`, else
38
+ # `NEW_CHECKOUT`) keeps it, unless an existing wire holds it; every
39
+ # other spelling gets `_` and the first 8 hex digits of the SHA-256 of
40
+ # its exact spelling (`NEW_CHECKOUT_1F0A2B3C`), and its KDoc says why.
41
+ # * Values of one flag that map to the same name: the first keeps it, and
42
+ # each later one, in declared order, gets the first free `_2`, `_3`, …
43
+ #
44
+ # NameClash is left for what can't be resolved: two generated type names
45
+ # that are equal, or a name that isn't an identifier.
46
+ class Kotlin
47
+ # Two generated names would be the same Kotlin identifier, or a name
48
+ # isn't one.
49
+ class NameClash < Error; end
50
+
51
+ PACKAGE_SEGMENT = /\A[A-Za-z_][A-Za-z0-9_]*\z/
52
+ # Kotlin's hard keywords, which can't be package segments.
53
+ HARD_KEYWORDS = %w[as break class continue do else false for fun if in interface is null object package return
54
+ super this throw true try typealias typeof val var when while].freeze
55
+ INDENT = " ".freeze
56
+
57
+ # `previous` is the Kotlin source this generator wrote last time (or
58
+ # nil); its entry names are kept.
59
+ def initialize(registry: StandardFlags.registry, package: StandardFlags.config.kotlin_package, manifest: nil, previous: nil)
60
+ @manifest = manifest || Manifest.new(registry: registry)
61
+ @package = package&.to_s
62
+ @previous = self.class.previous_names(previous)
63
+ validate_package!
64
+ end
65
+
66
+ ENUM_BLOCK = /^enum class ([A-Za-z_][A-Za-z0-9_]*)\((?:val wire: String, val type: FeatureType|val value: String)\) \{\n(.*?)^\}/m
67
+ ENTRY = /^ {4}([A-Z][A-Z0-9_]*)\(("(?:[^"\\]|\\.)*")/
68
+
69
+ # `{ enum name => { wire or value => entry name } }` from a file this
70
+ # generator wrote. An enum whose entries can't be read back
71
+ # unambiguously is left out, so its names are made afresh.
72
+ def self.previous_names(source)
73
+ return {} unless source.is_a?(String)
74
+
75
+ source.scan(ENUM_BLOCK).to_h do |enum, body|
76
+ pairs = body.scan(ENTRY).map { |name, literal| [ unstring(literal), name ] }
77
+ valid = pairs.none? { |text, _| text.nil? } && pairs.map(&:first).uniq.size == pairs.size &&
78
+ pairs.map(&:last).uniq.size == pairs.size
79
+ [ enum, valid ? pairs.to_h : {} ]
80
+ end
81
+ end
82
+
83
+ # The text of a `"..."` literal this generator wrote (`.string`), or
84
+ # nil.
85
+ def self.unstring(literal)
86
+ units = []
87
+ body = literal[1...-1]
88
+ index = 0
89
+ while index < body.length
90
+ char = body[index]
91
+ if char != "\\"
92
+ units.concat(char.encode("UTF-16BE").unpack("n*"))
93
+ index += 1
94
+ elsif body[index + 1] == "u" && body[index + 2, 4].to_s.match?(/\A\h{4}\z/)
95
+ units << body[index + 2, 4].hex
96
+ index += 6
97
+ elsif %w[\\ " $].include?(body[index + 1])
98
+ units << body[index + 1].ord
99
+ index += 2
100
+ else
101
+ return nil
102
+ end
103
+ end
104
+ units.pack("n*").force_encoding(Encoding::UTF_16BE).encode(Encoding::UTF_8)
105
+ rescue EncodingError
106
+ nil
107
+ end
108
+
109
+ def render
110
+ data = @manifest.to_h
111
+ out = [ "// Generated by `bin/rails standard_flags:kotlin`. Do not edit by hand.",
112
+ "// Manifest version #{data.fetch('version')}, sha256 #{@manifest.digest}.", "" ]
113
+ out << "package #{@package}" << "" if @package
114
+ out.concat(manifest_object(data))
115
+ out.concat(feature_type)
116
+ names = {}
117
+ audience_names(data).each do |audience|
118
+ out.concat(audience_enum(audience, wires_for(data, audience), names))
119
+ end
120
+ value_flags(data).each { |flag| out.concat(value_enum(flag, names)) }
121
+ "#{out.join("\n").rstrip}\n"
122
+ end
123
+
124
+ # `"..."` with every character outside printable ASCII escaped, so the
125
+ # source is ASCII whatever the values hold.
126
+ def self.string(text)
127
+ body = text.to_s.each_char.map do |char|
128
+ case char
129
+ when "\\" then "\\\\"
130
+ when "\"" then "\\\""
131
+ when "$" then "\\$"
132
+ when /[ -~]/ then char
133
+ else char.encode("UTF-16BE").unpack("n*").map { |unit| format("\\u%04X", unit) }.join
134
+ end
135
+ end.join
136
+ "\"#{body}\""
137
+ end
138
+
139
+ # Entry names for one audience's wires, `{ wire => name }` (see the
140
+ # class comment). Wires in `previous` (`{ wire => name }`) keep their
141
+ # names. Raises NameClash only if a suffixed name is itself taken.
142
+ def self.wire_constants(wires, previous = {})
143
+ names = {}
144
+ used = Set.new
145
+ wires.each do |wire|
146
+ name = previous[wire]
147
+ next if name.nil? || used.include?(name)
148
+
149
+ names[wire] = name
150
+ used << name
151
+ end
152
+ fresh = wires.reject { |wire| names.key?(wire) }
153
+ fresh.group_by { |wire| constant(wire) }.each do |base, spellings|
154
+ plain = spellings.size == 1 ? spellings.first : plain_spelling(base, spellings)
155
+ spellings.sort.each do |wire|
156
+ name = wire == plain && !used.include?(base) ? base : "#{base}_#{spelling_hash(wire)}"
157
+ raise NameClash, "wire #{wire.inspect} would be #{name} in Kotlin, which another wire already is; rename one" if used.include?(name)
158
+
159
+ names[wire] = name
160
+ used << name
161
+ end
162
+ end
163
+ names
164
+ end
165
+
166
+ # Of several spellings that map to `base`, the one that already is
167
+ # `base` in lower or upper case (`new_checkout`, else `NEW_CHECKOUT`).
168
+ def self.plain_spelling(base, spellings)
169
+ spellings.find { |wire| wire == base.downcase } || spellings.find { |wire| wire == base }
170
+ end
171
+
172
+ def self.spelling_hash(wire)
173
+ Digest::SHA256.hexdigest(wire)[0, 8].upcase
174
+ end
175
+
176
+ # Entry names for one flag's values, in declared order: values in
177
+ # `previous` (`{ value => name }`) keep their names; a clash gets the
178
+ # first free `_2`, `_3`, …
179
+ def self.value_constants(values, previous = {})
180
+ used = Set.new
181
+ kept = values.to_h do |value|
182
+ name = previous[value]
183
+ name = nil if name.nil? || used.include?(name)
184
+ used << name if name
185
+ [ value, name ]
186
+ end
187
+ values.map do |value|
188
+ next kept[value] if kept[value]
189
+
190
+ base = constant(value)
191
+ name = base
192
+ suffix = 1
193
+ name = "#{base}_#{suffix += 1}" while used.include?(name)
194
+ used << name
195
+ name
196
+ end
197
+ end
198
+
199
+ # SCREAMING_SNAKE_CASE for a wire name or value; "V_" in front of one
200
+ # that would start with a digit or be empty.
201
+ def self.constant(text)
202
+ name = text.to_s.gsub(/[^A-Za-z0-9]+/, "_").underscore.upcase.gsub(/_+/, "_").delete_prefix("_").delete_suffix("_")
203
+ name.empty? || name.match?(/\A[0-9]/) ? "V_#{name}".delete_suffix("_") : name
204
+ end
205
+
206
+ private
207
+
208
+ def validate_package!
209
+ return if @package.nil?
210
+
211
+ segments = @package.split(".", -1)
212
+ valid = !segments.empty? && segments.all? { |segment| segment.match?(PACKAGE_SEGMENT) && !HARD_KEYWORDS.include?(segment) }
213
+ raise ConfigurationError, "config.kotlin_package #{@package.inspect} is not a Kotlin package name" unless valid
214
+ end
215
+
216
+ def manifest_object(data)
217
+ [ "/** The manifest this file was generated from. */",
218
+ "object StandardFlagsManifest {",
219
+ "#{INDENT}const val VERSION: Int = #{Integer(data.fetch('version'))}",
220
+ "#{INDENT}const val SHA256: String = #{self.class.string(@manifest.digest)}",
221
+ "}", "" ]
222
+ end
223
+
224
+ def feature_type
225
+ [ "/** A wire's JSON type. */",
226
+ "enum class FeatureType { BOOLEAN, STRING }", "" ]
227
+ end
228
+
229
+ def audience_names(data)
230
+ data.fetch("audiences").keys.sort
231
+ end
232
+
233
+ # `[[wire, type, flag entry or nil, tombstone entry or nil], ...]`
234
+ # ordered by wire name.
235
+ def wires_for(data, audience)
236
+ wires = data.fetch("flags").flat_map do |flag|
237
+ flag.fetch("audiences").fetch(audience, []).map { |wire| [ wire, flag.fetch("type"), flag, nil ] }
238
+ end
239
+ data.fetch("tombstones").each do |tombstone|
240
+ tombstone.fetch("serve", {}).fetch(audience, {}).each do |wire, value|
241
+ wires << [ wire, [ true, false ].include?(value) ? "boolean" : "string", nil, tombstone ]
242
+ end
243
+ end
244
+ wires.sort_by(&:first)
245
+ end
246
+
247
+ def audience_enum(audience, wires, names)
248
+ name = claim(names, "#{audience.camelize}Feature", "audience #{audience}")
249
+ constants = self.class.wire_constants(wires.map(&:first), @previous.fetch(name, {}))
250
+ out = [ "/** The wires the #{audience} audience is told, ordered by wire name. */",
251
+ "enum class #{name}(val wire: String, val type: FeatureType) {" ]
252
+ wires.each do |wire, type, flag, tombstone|
253
+ constant = constants.fetch(wire)
254
+ notes = []
255
+ note = rename_note(wire, constant, constants)
256
+ notes << note if note
257
+ notes << "Values: [#{value_enum_name(flag)}]." if flag && type == "string" && value_flag?(flag)
258
+ out << "#{INDENT}/** #{notes.join(' ')} */" unless notes.empty?
259
+ if tombstone
260
+ out << "#{INDENT}@Deprecated(#{self.class.string("No longer declared; served as a static value through #{tombstone.fetch('until')}")})"
261
+ end
262
+ out << "#{INDENT}#{constant}(#{self.class.string(wire)}, FeatureType.#{type.upcase}),"
263
+ end
264
+ out << "#{INDENT};" << "" << "#{INDENT}companion object {"
265
+ out << "#{INDENT * 2}fun fromWire(wire: String): #{name}? = values().firstOrNull { it.wire == wire }"
266
+ out << "#{INDENT}}" << "}" << ""
267
+ end
268
+
269
+ # Why a wire's entry isn't its plain name, or nil when it is.
270
+ def rename_note(wire, constant, constants)
271
+ base = self.class.constant(wire)
272
+ return nil if constant == base
273
+
274
+ holder = constants.key(base)
275
+ others = constants.keys.select { |other| other != wire && self.class.constant(other) == base }
276
+ if holder then "Wire #{wire} (#{base} is the wire #{holder})."
277
+ elsif !others.empty? then "Wire #{wire} (it shares #{base} with #{others.join(', ')}, so each carries a suffix)."
278
+ else "Wire #{wire} (named when another wire held #{base}; kept so client code keeps compiling)."
279
+ end
280
+ end
281
+
282
+ def value_flags(data)
283
+ data.fetch("flags").select { |flag| value_flag?(flag) }.sort_by { |flag| flag.fetch("key") }
284
+ end
285
+
286
+ def value_flag?(flag)
287
+ flag.fetch("type") == "string" && flag.fetch("audiences").any? { |_, wires| !wires.empty? }
288
+ end
289
+
290
+ def value_enum_name(flag)
291
+ "#{flag.fetch('key').camelize}Value"
292
+ end
293
+
294
+ def value_enum(flag, names)
295
+ name = claim(names, value_enum_name(flag), "flag #{flag.fetch('key')}")
296
+ values = flag.fetch("values").map(&:to_s)
297
+ constants = self.class.value_constants(values, @previous.fetch(name, {}))
298
+ wires = flag.fetch("audiences").sort.map { |audience, list| "#{audience}: #{list.join(', ')}" }.join("; ")
299
+ out = [ "/** Values of #{wires}. */", "enum class #{name}(val value: String) {" ]
300
+ values.zip(constants).each { |value, constant| out << "#{INDENT}#{constant}(#{self.class.string(value)})," }
301
+ out << "#{INDENT};" << "" << "#{INDENT}companion object {"
302
+ out << "#{INDENT * 2}fun fromValue(value: String?): #{name}? = values().firstOrNull { it.value == value }"
303
+ out << "#{INDENT}}" << "}" << ""
304
+ end
305
+
306
+ def claim(names, name, owner)
307
+ raise NameClash, "#{owner} generates #{name.inspect}, which is not a Kotlin identifier" unless name.match?(PACKAGE_SEGMENT)
308
+
309
+ reserved = %w[StandardFlagsManifest FeatureType]
310
+ if reserved.include?(name) || names.key?(name)
311
+ raise NameClash, "#{owner} and #{names.fetch(name, 'a generated type')} both generate Kotlin type #{name}"
312
+ end
313
+
314
+ names[name] = owner
315
+ name
316
+ end
317
+ end
318
+ end
319
+ end