featurevisor-schemas 4.1.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.
@@ -0,0 +1,299 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Featurevisor
6
+ module Schemas
7
+ # What a Schemas instance reads through its Featurevisor instance: the module
8
+ # API, and schemas compiled by the entry the datafile holds, so a datafile that
9
+ # changes one compiles it again and references resolve at call time.
10
+ class Store
11
+ SECTION = "schemas"
12
+ NAME = "@featurevisor/schemas"
13
+ # The object ids of Featurevisor instances whose schemas module holds the
14
+ # package's name, which only one module on an instance can. Ids, not
15
+ # instances, so an instance nobody closes is still collected.
16
+ NAMED = {}
17
+ NAMED_MUTEX = Mutex.new
18
+ # Compiled validators and mutated rules held at most, before they are dropped to be made again.
19
+ CACHE_LIMIT = 4096
20
+ # The items of an array without items, which are strings, as one object, so its validator is kept.
21
+ STRING_ITEMS = { type: "string" }.freeze
22
+
23
+ attr_reader :f, :api
24
+
25
+ def initialize(f)
26
+ unless f.respond_to?(:add_module)
27
+ raise ArgumentError, "Featurevisor::Schemas takes the instance create_featurevisor returns, not a child. " \
28
+ "Pass a child's context to validate instead."
29
+ end
30
+
31
+ @f = f
32
+ @mutex = Mutex.new
33
+ @compiled = {}.compare_by_identity
34
+ @mutated = {}.compare_by_identity
35
+ @compiled_before = {}.compare_by_identity
36
+ @mutated_before = {}.compare_by_identity
37
+ @unlisten = f.on("datafile_set", ->(_details) { @mutex.synchronize { rotate_caches } })
38
+ @reported = {}
39
+ @reported_revision = nil
40
+ @context_changes = 0
41
+ @context_unlisten = nil
42
+ @listen_mutex = Mutex.new
43
+ @closed = false
44
+ captured = nil
45
+ takes_name = NAMED_MUTEX.synchronize { NAMED.key?(f.object_id) ? false : (NAMED[f.object_id] = true) }
46
+ # A module without evaluation hooks costs evaluations nothing.
47
+ remove = f.add_module({ name: takes_name ? NAME : nil, setup: ->(api) { captured = api } }.compact)
48
+ if remove.nil? && takes_name
49
+ # A module of the same name was added by hand.
50
+ NAMED_MUTEX.synchronize { NAMED.delete(f.object_id) }
51
+ takes_name = false
52
+ remove = f.add_module({ setup: ->(api) { captured = api } })
53
+ end
54
+ @holds_name = takes_name
55
+ @remove = remove
56
+ unless captured.is_a?(Hash) && captured[:get_entry] && captured[:evaluate]
57
+ close
58
+ raise ArgumentError, "featurevisor-schemas needs a featurevisor gem whose modules can read datafile sections"
59
+ end
60
+ @api = captured
61
+ end
62
+
63
+ def close
64
+ @closed = true
65
+ @unlisten&.call
66
+ @unlisten = nil
67
+ stops = @listen_mutex.synchronize { @context_unlisten.tap { @context_unlisten = nil } }
68
+ stops&.each(&:call)
69
+ @remove&.call
70
+ @remove = nil
71
+ NAMED_MUTEX.synchronize { NAMED.delete(@f.object_id) } if @holds_name
72
+ @holds_name = false
73
+ end
74
+
75
+ def entry(key)
76
+ value = @api[:get_entry].call(SECTION, key)
77
+ value.is_a?(Hash) ? value : nil
78
+ end
79
+
80
+ def keys
81
+ @api[:get_entry_keys].call(SECTION).sort
82
+ end
83
+
84
+ # What changes when the schema does, through the schemas it references too, since its hash covers them.
85
+ def version(key)
86
+ node = entry(key)
87
+ node && (node[:hash] || node.object_id)
88
+ end
89
+
90
+ # A schema's node, without compiling it, for what reads a node: references, annotations and messages.
91
+ def node(key)
92
+ entry(key)
93
+ end
94
+
95
+ # The schema's node and validator. Compiling reads only the nodes of the schemas it references,
96
+ # so a schema that references itself compiles.
97
+ def resolve(key)
98
+ node = entry(key)
99
+ node && [node, compile(node)]
100
+ end
101
+
102
+ # A node's validator, compiled once per node object for every handle of the instance. A datafile
103
+ # that changes a schema holds a new node, so it compiles again, a view's nodes compile once since
104
+ # they are the same object for the same mutations, and references resolve when a value is validated.
105
+ def compile(node)
106
+ return Engine::NOTHING unless node.is_a?(Hash)
107
+
108
+ cached = @mutex.synchronize { current_caches && held(@compiled, @compiled_before, node) }
109
+ return cached if cached
110
+
111
+ validate = Engine.compile_node(node, self)
112
+ @mutex.synchronize { current_caches && (@compiled[node] = validate) }
113
+ end
114
+
115
+ # A node's rules with the mutations an id names applied, made by the block once per node and id.
116
+ def mutated(node, id)
117
+ found = @mutex.synchronize { current_caches && held(@mutated, @mutated_before, node)&.[](id) }
118
+ return found if found
119
+
120
+ rules = yield
121
+ @mutex.synchronize { current_caches && ((held(@mutated, @mutated_before, node) || (@mutated[node] = {}))[id] = rules) }
122
+ end
123
+
124
+ # Runs the block in the schema's package evaluation, so modules see it as they see a
125
+ # getter, and its conditions read the context they leave. Conditions read through the
126
+ # SDK, so a segment means in a schema what it means in a flag. The block gets the
127
+ # context and a matcher of conditions and an input reader.
128
+ def evaluate(schema, context)
129
+ @api[:evaluate].call({ type: "schema", key: schema, context: context || {} }) do |scope|
130
+ yield scope.context, ->(conditions, reader) { scope.match_conditions(conditions, { "input" => reader }) }
131
+ end
132
+ end
133
+
134
+ # A number that changes when the instance's context or sticky values do, which a view's conditions
135
+ # read. It listens from the first call on, so an instance without a view never makes the SDK work out what changed.
136
+ def context_version
137
+ # Registered under a mutex of its own, so no lock of the instance is taken while this one is held.
138
+ @listen_mutex.synchronize do
139
+ if @context_unlisten.nil? && !@closed
140
+ bump = ->(_details) { @mutex.synchronize { @context_changes += 1 } }
141
+ @context_unlisten = %w[context_set sticky_features_set sticky_variables_set].map { |event| @f.on(event, bump) }
142
+ end
143
+ end
144
+ @mutex.synchronize { @context_changes }
145
+ end
146
+
147
+ # Whether this is the first report of the id in the current datafile. What was reported is
148
+ # forgotten when the datafile's revision changes.
149
+ def once?(id)
150
+ revision = @api[:get_revision].call
151
+ @mutex.synchronize do
152
+ if revision != @reported_revision
153
+ @reported_revision = revision
154
+ @reported.clear
155
+ end
156
+ @reported.key?(id) ? false : (@reported[id] = true)
157
+ end
158
+ end
159
+
160
+ def unsupported_pattern(pattern)
161
+ return unless once?("pattern #{pattern}")
162
+
163
+ @api[:report_diagnostic].call(level: "error", code: "schema_pattern_unsupported",
164
+ message: "Pattern #{JSON.generate(pattern)} does not compile in Ruby, so it fails every value.",
165
+ details: { pattern: pattern })
166
+ end
167
+
168
+ def mutation_failed(schema, error)
169
+ return unless once?("mutation #{schema}")
170
+
171
+ @api[:report_diagnostic].call(level: "error", code: "schema_mutation_error",
172
+ message: "A mutation of schema #{JSON.generate(schema)} cannot be applied, so the rules it changes fail every value.",
173
+ original_error: error, details: { schemaKey: schema })
174
+ end
175
+
176
+ def reference_too_deep(schema)
177
+ return unless once?("depth #{schema}")
178
+
179
+ @api[:report_diagnostic].call(level: "error", code: "schema_reference_depth",
180
+ message: "Schema #{JSON.generate(schema)} fails the value closed, since the value is " \
181
+ "nested more than #{Engine::MAX_REFERENCE_DEPTH} references deep.",
182
+ details: { schemaKey: schema })
183
+ end
184
+
185
+ # A check in code, or an option source's lookup, that raised: its value fails closed, said once per check.
186
+ def check_failed(schema, check, path, error)
187
+ return unless once?("check #{JSON.generate([schema, check])}")
188
+
189
+ @api[:report_diagnostic].call(level: "error", code: "schema_check_error",
190
+ message: "Check #{JSON.generate(check)} of schema #{JSON.generate(schema)} threw or rejected, " \
191
+ "so the value it checks fails closed.",
192
+ original_error: error, details: { schemaKey: schema, check: check, path: path || "" })
193
+ end
194
+
195
+ # Reports schema_not_found once per key.
196
+ def report_missing(key)
197
+ return unless once?("missing #{key}")
198
+
199
+ @api[:report_diagnostic].call(level: "warn", code: "schema_not_found",
200
+ message: "Schema \"#{key}\" is not in the datafile. Check that a target delivers it.",
201
+ details: { schemaKey: key })
202
+ end
203
+
204
+ # Two generations of each cache. A new datafile, or a full generation, makes the current maps the
205
+ # previous ones and starts new ones, so a node a datafile keeps survives it and one unused for two
206
+ # changes is dropped. Called with the mutex held.
207
+ def current_caches
208
+ rotate_caches if @compiled.size > CACHE_LIMIT || @mutated.size > CACHE_LIMIT
209
+ true
210
+ end
211
+
212
+ def rotate_caches
213
+ @compiled_before = @compiled
214
+ @mutated_before = @mutated
215
+ @compiled = {}.compare_by_identity
216
+ @mutated = {}.compare_by_identity
217
+ end
218
+
219
+ # A node's entry in the current generation, or the previous one, whose hit moves into the current.
220
+ def held(current, before, node)
221
+ found = current[node]
222
+ return found unless found.nil?
223
+
224
+ found = before[node]
225
+ current[node] = found unless found.nil?
226
+ found
227
+ end
228
+ private :current_caches, :rotate_caches, :held
229
+
230
+ Location = Struct.new(:node, :mpath, :scopes, :value, :required)
231
+ Walk = Struct.new(:value, :start, :adjust)
232
+
233
+ # Follows a path from a node, through references, properties, array items
234
+ # and the values an open object allows. It stops at oneOf, and gives nil for
235
+ # a path the schema does not describe. In a view, each node on the way, and
236
+ # each schema it references, has its matching mutations applied for the value there.
237
+ def self.locate(resolver, root, steps, mpath = [], scopes = [], walk = nil)
238
+ node = root
239
+ value = walk&.value
240
+ required = false
241
+ mpath = mpath.dup
242
+ scopes = scopes.dup
243
+ steps.each_with_index do |step, index|
244
+ in_view = walk && index >= walk.start
245
+ adjust = in_view ? walk.adjust : nil
246
+ required = false
247
+ # The node's messages, then those of each schema it references, at the same depth.
248
+ seen = []
249
+ resolved = adjust ? adjust.call(node, value) : node
250
+ loop do
251
+ return nil unless resolved.is_a?(Hash)
252
+
253
+ scopes << Messages::Scope.new(resolved[:messages], mpath.length) if resolved[:messages].is_a?(Hash)
254
+ key = resolved[:schema]
255
+ break unless key.is_a?(String)
256
+ return nil if seen.include?(key)
257
+
258
+ seen << key
259
+ target = resolver.node(key)
260
+ resolved = adjust ? adjust.call(target, value) : target
261
+ end
262
+ return nil if resolved[:oneOf].is_a?(Array)
263
+
264
+ case step.kind
265
+ when :key
266
+ properties = resolved[:properties]
267
+ # A key required lists is required whatever properties holds.
268
+ required = resolved[:required].is_a?(Array) && resolved[:required].include?(step.key)
269
+ if properties.is_a?(Hash) && properties.key?(step.key.to_sym)
270
+ node = properties[step.key.to_sym]
271
+ mpath << step.key
272
+ elsif resolved[:additionalProperties].is_a?(Hash)
273
+ node = resolved[:additionalProperties]
274
+ mpath << "*"
275
+ else
276
+ return nil
277
+ end
278
+ value = value.is_a?(Hash) ? value[step.key] : nil if in_view
279
+ when :values
280
+ return nil unless resolved[:additionalProperties].is_a?(Hash)
281
+
282
+ node = resolved[:additionalProperties]
283
+ mpath << "*"
284
+ # * names no one value.
285
+ value = nil if in_view
286
+ else
287
+ # An index or []: every item of an array is described alike.
288
+ return nil unless resolved[:type] == "array"
289
+
290
+ node = resolved.key?(:items) ? resolved[:items] : STRING_ITEMS
291
+ mpath << "[]"
292
+ value = step.kind == :index && value.is_a?(Array) ? value[step.index] : nil if in_view
293
+ end
294
+ end
295
+ Location.new(node, mpath, scopes, value, required)
296
+ end
297
+ end
298
+ end
299
+ end