api_recipes 3.0.0.beta2 → 3.0.0.beta4

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 (35) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +704 -81
  3. data/UPGRADING.md +149 -46
  4. data/lib/api_recipes/api.rb +14 -10
  5. data/lib/api_recipes/cli/code.rb +153 -0
  6. data/lib/api_recipes/cli/convert/migration.rb +624 -0
  7. data/lib/api_recipes/cli/convert/snippet.rb +67 -0
  8. data/lib/api_recipes/cli/convert.rb +533 -0
  9. data/lib/api_recipes/cli/recipes/git.rb +197 -0
  10. data/lib/api_recipes/cli/recipes/lock_file.rb +34 -0
  11. data/lib/api_recipes/cli/recipes/summary.rb +245 -0
  12. data/lib/api_recipes/cli/recipes.rb +287 -0
  13. data/lib/api_recipes/cli/routes.rb +8 -3
  14. data/lib/api_recipes/cli/upgrade/project.rb +194 -0
  15. data/lib/api_recipes/cli/upgrade.rb +361 -24
  16. data/lib/api_recipes/cli.rb +161 -8
  17. data/lib/api_recipes/configuration.rb +68 -18
  18. data/lib/api_recipes/endpoint.rb +10 -4
  19. data/lib/api_recipes/errors.rb +2 -1
  20. data/lib/api_recipes/internals/compiler.rb +174 -33
  21. data/lib/api_recipes/internals/context.rb +87 -20
  22. data/lib/api_recipes/internals/declaration.rb +18 -18
  23. data/lib/api_recipes/internals/definition.rb +76 -23
  24. data/lib/api_recipes/internals/level.rb +54 -43
  25. data/lib/api_recipes/internals/option_value.rb +92 -0
  26. data/lib/api_recipes/internals/path_template.rb +29 -4
  27. data/lib/api_recipes/internals/plain_yaml.rb +133 -0
  28. data/lib/api_recipes/internals/recipe.rb +297 -0
  29. data/lib/api_recipes/internals/recipe_lock.rb +115 -0
  30. data/lib/api_recipes/internals/registry.rb +61 -15
  31. data/lib/api_recipes/internals/request.rb +42 -14
  32. data/lib/api_recipes/internals/template.rb +17 -5
  33. data/lib/api_recipes/version.rb +1 -1
  34. data/lib/api_recipes.rb +8 -3
  35. metadata +14 -1
@@ -0,0 +1,297 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'digest'
4
+
5
+ module ApiRecipes
6
+ module Internals
7
+ # A portable recipe: a file with one api that is only data, written by
8
+ # someone else. It is never evaluated with ERB, it is read as plain YAML,
9
+ # and it must say its name and its version under the key `recipe`.
10
+ class Recipe
11
+ MAX_BYTES = 1_048_576
12
+ SUFFIX = '.recipe.yml'
13
+ FORMAT = 1
14
+ NAME = /\A[a-z0-9_][a-z0-9_-]{0,63}\z/
15
+ VERSION = /\A[0-9A-Za-z]+(?:\.[0-9A-Za-z]+)*\z/
16
+ MAX_VERSION = 32
17
+ KEYS = %w[name version format summary homepage].freeze
18
+ HOMEPAGE = %r{\Ahttps?://[!-~]+\z}
19
+ MAX_TEXT = 200
20
+ # What keeps the cost of compiling a recipe in proportion to its size.
21
+ MAX_LENGTH = 2_000
22
+ MAX_ENDPOINTS = 10_000
23
+ MAX_PATH = 4_000
24
+ MAX_SENT = 100_000
25
+ SENT_KEYS = %w[default_headers default_params].freeze
26
+ WHOLE_HOST = /\A\{[A-Za-z_]\w*\}\z/
27
+ FIXED_END = /\A\.[A-Za-z0-9]/
28
+
29
+ class << self
30
+ # The recipe in the file at path. Raises RecipeFileError, which names
31
+ # the file. With compile: false the rules of the gem for an api are
32
+ # left to whoever compiles the result.
33
+ def read(path, compile: true)
34
+ text, file_name = read_text(path)
35
+ new(text, path, file_name: file_name, compile: compile)
36
+ end
37
+
38
+ # The recipe written in text. where names it in the errors.
39
+ def parse(text, where, file_name: nil, compile: true)
40
+ new(text, where, file_name: file_name, compile: compile)
41
+ end
42
+
43
+ # The apis of the files, as { name => options }. Each file must be in
44
+ # the recipes.lock of its folder with the checksum it has now, and is
45
+ # not parsed otherwise. taken: the names that other sources define.
46
+ # Every problem is reported, in one ConfigurationError.
47
+ def load_all(paths, taken: [])
48
+ errors = []
49
+ locks = {}
50
+ apis = {}
51
+ paths.each do |path|
52
+ recipe = load_one(path, locks)
53
+ name = recipe.apis.keys.first
54
+ if taken.include?(name)
55
+ raise RecipeFileError.new(path, "the api '#{name}' is already defined by apis_configs or apis_files_paths: " \
56
+ 'a recipe never takes the place of an api')
57
+ end
58
+ raise RecipeFileError.new(path, "the api '#{name}' is already given by another recipe file") if apis.key?(name)
59
+
60
+ apis.merge!(recipe.apis)
61
+ rescue ConfigurationError => e
62
+ errors.concat(e.errors)
63
+ end
64
+ raise ConfigurationError.new(errors) unless errors.empty?
65
+
66
+ apis
67
+ end
68
+
69
+ def digest(text) = Digest::SHA256.hexdigest(text)
70
+
71
+ # The text of the file at path and the name of the file. The text is
72
+ # read as bytes and tagged as UTF-8; no more than the limit is read.
73
+ def read_text(path)
74
+ unless (path.is_a?(String) || path.is_a?(Pathname)) && !path.to_s.include?("\0")
75
+ raise ConfigurationError.new(['recipes_paths: every path must be a String or a Pathname, without null bytes'])
76
+ end
77
+
78
+ full = File.expand_path(path)
79
+ file_name = File.basename(full)
80
+ unless file_name.end_with?(SUFFIX)
81
+ raise RecipeFileError.new(path, "is not called NAME#{SUFFIX}: only portable recipes go in recipes_paths")
82
+ end
83
+ raise RecipeFileError.new(path, 'file not found') unless File.exist?(full)
84
+ raise RecipeFileError.new(path, 'is not a file') unless File.file?(full)
85
+
86
+ text = File.open(full, 'rb') { |file| file.read(MAX_BYTES + 1) } || +''
87
+ raise RecipeFileError.new(path, "is larger than #{MAX_BYTES} bytes") if text.bytesize > MAX_BYTES
88
+
89
+ [text.force_encoding(Encoding::UTF_8), file_name]
90
+ rescue SystemCallError => e
91
+ raise RecipeFileError.new(path, "cannot read file (#{e.class.name.split('::').last})")
92
+ end
93
+
94
+ private
95
+
96
+ def load_one(path, locks)
97
+ text, file_name = read_text(path)
98
+ directory = File.dirname(File.expand_path(path))
99
+ lock = locks[directory] ||= RecipeLock.read(directory)
100
+ problem = lock.problem_for(file_name.delete_suffix(SUFFIX), digest(text))
101
+ raise RecipeFileError.new(path, "#{problem} `api_recipes install #{path}`") if problem
102
+
103
+ new(text, path, file_name: file_name, compile: false)
104
+ end
105
+ end
106
+
107
+ # name and version are text; apis is { name => options } as the compiler
108
+ # takes it; definition is the compiled api, or nil with compile: false.
109
+ attr_reader :name, :version, :apis, :definition, :text, :sha256
110
+
111
+ def initialize(text, where, file_name: nil, compile: true)
112
+ @where = where
113
+ @text = text
114
+ @sha256 = self.class.digest(text)
115
+ refuse('contains <%: a recipe is never evaluated with ERB, and must not hold text that ERB would run') if text.include?('<%')
116
+ data = plain_data(text)
117
+ refused = text_problem(data)
118
+ refuse(refused) if refused
119
+ name, options = one_api(data)
120
+ problems = name_problems(name, file_name) + recipe_problems(name, options['recipe']) +
121
+ verify_with_problems(name, options) + host_problems(options['host']) + size_problems(options)
122
+ refuse(problems) unless problems.empty?
123
+
124
+ @name = name
125
+ @version = options['recipe']['version']
126
+ @apis = compiled { Compiler.normalize({ name => options }, :options_map) }
127
+ @definition = compiled { Compiler.compile_all(@apis).values.first } if compile
128
+ freeze
129
+ end
130
+
131
+ private
132
+
133
+ def refuse(reasons) = raise(RecipeFileError.new(@where, reasons))
134
+
135
+ def compiled
136
+ yield
137
+ rescue ConfigurationError => e
138
+ refuse(e.errors)
139
+ end
140
+
141
+ def plain_data(text)
142
+ PlainYaml.load(text, max_bytes: MAX_BYTES)
143
+ rescue PlainYaml::Refused => e
144
+ refuse(e.message)
145
+ end
146
+
147
+ # Why the first name or value, at any depth, that is not short visible
148
+ # text is refused; nil when every one is.
149
+ def text_problem(value)
150
+ case value
151
+ when String
152
+ if value.match?(PlainYaml::UNPRINTABLE)
153
+ "#{PlainYaml.label(value)}: contains a character that is not printed (a control or a format character): " \
154
+ 'a recipe holds visible text only'
155
+ elsif value.length > MAX_LENGTH
156
+ "#{PlainYaml.label(value)}...: a name or a value of a recipe has at most #{MAX_LENGTH} characters"
157
+ end
158
+ when Array then value.each { |item| (found = text_problem(item)) && (return found) } && nil
159
+ when Hash then value.each { |key, item| (found = text_problem(key) || text_problem(item)) && (return found) } && nil
160
+ end
161
+ end
162
+
163
+ # The endpoints are counted, those that `resource` adds among them, and
164
+ # the path of each is measured with the paths above it: every endpoint
165
+ # keeps its whole path.
166
+ def size_problems(options)
167
+ count = 0
168
+ longest = 0
169
+ held = 0
170
+ # taken: how many headers and how many parameters the endpoints above
171
+ # give. An endpoint that adds some holds them with its own.
172
+ walk = lambda do |endpoints, above, taken|
173
+ next unless endpoints.is_a?(Hash)
174
+
175
+ endpoints.each do |name, child|
176
+ count += 1
177
+ own = child.is_a?(Hash) && child['path'].is_a?(String) ? child['path'] : name
178
+ length = above + own.length + 1
179
+ longest = length if length > longest
180
+ next unless child.is_a?(Hash)
181
+
182
+ given = SENT_KEYS.each_with_index.map do |key, index|
183
+ added = child[key].is_a?(Hash) ? child[key].size : 0
184
+ held += taken[index] + added unless added.zero?
185
+ taken[index] + added
186
+ end
187
+ written = child['endpoints']
188
+ generated(child['resource'], written).each do |path|
189
+ count += 1
190
+ longest = [longest, length + path.length + 1].max
191
+ end
192
+ walk.call(written, length, given)
193
+ end
194
+ end
195
+ walk.call(options['endpoints'], options['base_url'].to_s.length, [0, 0])
196
+ problems = []
197
+ if held > MAX_SENT
198
+ problems << "its endpoints hold #{held} headers and parameters, counting for each endpoint those of the " \
199
+ "endpoints above it: a recipe has at most #{MAX_SENT}"
200
+ end
201
+ problems << "has #{count} endpoints: a recipe has at most #{MAX_ENDPOINTS}" if count > MAX_ENDPOINTS
202
+ problems << "the path of an endpoint, with the paths above it, has at most #{MAX_PATH} characters" if longest > MAX_PATH
203
+ problems
204
+ end
205
+
206
+ # The paths of the endpoints that a value of `resource` adds and that
207
+ # are not written by hand as well.
208
+ def generated(resource, written)
209
+ names = Compiler.resource_names(resource) || []
210
+ names -= written.keys.map { |name| name.to_s.to_sym } if written.is_a?(Hash)
211
+ names.map { |name| Compiler::RESOURCE[name][:path] }
212
+ end
213
+
214
+ def one_api(data)
215
+ refuse('file is empty') if data.nil?
216
+ refuse('must contain one api: a mapping from its name to its options') unless data.is_a?(Hash)
217
+ unless data.size == 1
218
+ refuse("must contain one api, but it has #{data.size}: #{data.keys.first(5).map { |key| PlainYaml.label(key) }.join(', ')}")
219
+ end
220
+ name, options = data.first
221
+ refuse("the api '#{PlainYaml.label(name)}' must be a mapping of options") unless options.is_a?(Hash)
222
+
223
+ [name, options]
224
+ end
225
+
226
+ def name_problems(name, file_name)
227
+ unless NAME.match?(name)
228
+ return ["the api name '#{PlainYaml.label(name)}' must be made of lowercase letters, digits, - and _, " \
229
+ 'at most 64, and must not start with -']
230
+ end
231
+ return [] if file_name.nil? || file_name == "#{name}#{SUFFIX}"
232
+
233
+ ["the file must be called #{name}#{SUFFIX}, after its api"]
234
+ end
235
+
236
+ def recipe_problems(name, recipe)
237
+ return ['the key recipe is required, with name and version'] unless recipe.is_a?(Hash)
238
+
239
+ problems = (recipe.keys - KEYS).reject { |key| Compiler::IGNORED_KEY.match?(key) }.map do |key|
240
+ "recipe: unknown key '#{PlainYaml.label(key)}'"
241
+ end
242
+ problems << "recipe.name must be '#{name}', the name of the api" unless recipe['name'] == name
243
+ problems.concat(version_problems(recipe['version']))
244
+ unless recipe['format'].nil? || recipe['format'] == FORMAT
245
+ problems << "recipe.format #{PlainYaml.label(recipe['format'])} is not known to this version of api_recipes " \
246
+ "(it knows #{FORMAT}): update the gem"
247
+ end
248
+ summary = recipe['summary']
249
+ unless summary.nil? || (summary.is_a?(String) && summary.length <= MAX_TEXT)
250
+ problems << "recipe.summary must be text, at most #{MAX_TEXT} characters"
251
+ end
252
+ homepage = recipe['homepage']
253
+ unless homepage.nil? || (homepage.is_a?(String) && homepage.length <= MAX_TEXT && HOMEPAGE.match?(homepage))
254
+ problems << 'recipe.homepage must be an http or https address, without spaces'
255
+ end
256
+ problems
257
+ end
258
+
259
+ def version_problems(version)
260
+ return ['recipe.version is required'] if version.nil?
261
+ return ['recipe.version must be text: write it between quotes'] unless version.is_a?(String)
262
+ return [] if version.length <= MAX_VERSION && VERSION.match?(version)
263
+
264
+ ["recipe.version must be made of digits, letters and dots, at most #{MAX_VERSION} characters"]
265
+ end
266
+
267
+ # verify_with names a method of the application: a recipe cannot ask for it.
268
+ def verify_with_problems(name, options, location = '')
269
+ problems = []
270
+ if options.key?('verify_with')
271
+ problems << "#{location}verify_with is not allowed in a recipe: add it in your code, with " \
272
+ "`api :#{name}, verify_with: ...`"
273
+ end
274
+ endpoints = options['endpoints']
275
+ return problems unless endpoints.is_a?(Hash)
276
+
277
+ endpoints.each do |child, child_options|
278
+ next unless child_options.is_a?(Hash)
279
+
280
+ problems.concat(verify_with_problems(name, child_options, "#{location}endpoints.#{PlainYaml.label(child)}."))
281
+ end
282
+ problems
283
+ end
284
+
285
+ # A variable can be the whole host, or stand before fixed text that
286
+ # starts with a dot: its value never decides where the host ends.
287
+ def host_problems(host)
288
+ return ['host is required'] if host.nil?
289
+ return [] unless host.is_a?(String) && host.match?(Template::VARIABLE)
290
+ return [] if WHOLE_HOST.match?(host) || FIXED_END.match?(host.rpartition(Template::VARIABLE).last)
291
+
292
+ ["host: a variable must be the whole host or stand before fixed text that starts with a dot, as in " \
293
+ "'{shop}.example.com': here a variable would decide where the host ends"]
294
+ end
295
+ end
296
+ end
297
+ end
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiRecipes
4
+ module Internals
5
+ # The recipes.lock of a folder: for each installed recipe its version,
6
+ # where it came from and the checksum of its file. It is written by the
7
+ # api_recipes command and only read here.
8
+ class RecipeLock
9
+ FILE_NAME = 'recipes.lock'
10
+ FORMAT = 1
11
+ KEYS = %w[format recipes].freeze
12
+ ENTRY_KEYS = %w[version source commit sha256].freeze
13
+ SHA256 = /\A[0-9a-f]{64}\z/
14
+ COMMIT = /\A(?:[0-9a-f]{40}|[0-9a-f]{64})\z/
15
+ SOURCE = /\A[!-~]{1,2000}\z/
16
+
17
+ Entry = Data.define(:version, :source, :commit, :sha256)
18
+
19
+ class << self
20
+ # The lock of the folder; an empty one when the folder has none.
21
+ def read(directory)
22
+ path = File.join(directory, FILE_NAME)
23
+ return new(path, {}, false) unless File.exist?(path)
24
+ raise RecipeFileError.new(path, 'is not a file') unless File.file?(path)
25
+
26
+ text = File.open(path, 'rb') { |file| file.read(Recipe::MAX_BYTES + 1) } || +''
27
+ raise RecipeFileError.new(path, "is larger than #{Recipe::MAX_BYTES} bytes") if text.bytesize > Recipe::MAX_BYTES
28
+
29
+ new(path, entries(path, text.force_encoding(Encoding::UTF_8)), true)
30
+ rescue SystemCallError => e
31
+ raise RecipeFileError.new(path, "cannot read file (#{e.class.name.split('::').last})")
32
+ end
33
+
34
+ private
35
+
36
+ def entries(path, text)
37
+ data = PlainYaml.load(text, max_bytes: Recipe::MAX_BYTES)
38
+ problems = problems_of(data)
39
+ raise RecipeFileError.new(path, problems) unless problems.empty?
40
+
41
+ (data['recipes'] || {}).to_h do |name, entry|
42
+ [name, Entry.new(version: entry['version'], source: entry['source'], commit: entry['commit'],
43
+ sha256: entry['sha256'])]
44
+ end
45
+ rescue PlainYaml::Refused => e
46
+ raise RecipeFileError.new(path, e.message)
47
+ end
48
+
49
+ def problems_of(data)
50
+ return ['must be a mapping with format and recipes'] unless data.is_a?(Hash)
51
+
52
+ problems = (data.keys - KEYS).map { |key| "unknown key '#{PlainYaml.label(key)}'" }
53
+ unless data['format'] == FORMAT
54
+ problems << "format #{PlainYaml.label(data['format'])} is not known to this version of api_recipes " \
55
+ "(it knows #{FORMAT}): update the gem"
56
+ end
57
+ recipes = data['recipes']
58
+ return problems if recipes.nil?
59
+ return problems << 'recipes must be a mapping' unless recipes.is_a?(Hash)
60
+
61
+ recipes.each { |name, entry| problems.concat(entry_problems(name, entry)) }
62
+ problems
63
+ end
64
+
65
+ def entry_problems(name, entry)
66
+ shown = PlainYaml.label(name)
67
+ return ["recipes: '#{shown}' is not the name of a recipe"] unless Recipe::NAME.match?(name)
68
+ return ["recipes.#{shown} must be a mapping"] unless entry.is_a?(Hash)
69
+
70
+ problems = (entry.keys - ENTRY_KEYS).map { |key| "recipes.#{shown}: unknown key '#{PlainYaml.label(key)}'" }
71
+ version = entry['version']
72
+ unless version.is_a?(String) && version.length <= Recipe::MAX_VERSION && Recipe::VERSION.match?(version)
73
+ problems << "recipes.#{shown}.version must be the version of the recipe, as text"
74
+ end
75
+ problems << "recipes.#{shown}.sha256 must be a SHA-256 checksum" unless text?(entry['sha256'], SHA256)
76
+ source = entry['source']
77
+ commit = entry['commit']
78
+ problems << "recipes.#{shown}.source must be an address without spaces" unless source.nil? || text?(source, SOURCE)
79
+ problems << "recipes.#{shown}.commit must be the id of a commit" unless commit.nil? || text?(commit, COMMIT)
80
+ problems << "recipes.#{shown}: source and commit go together" unless source.nil? == commit.nil?
81
+ problems
82
+ end
83
+
84
+ def text?(value, pattern) = value.is_a?(String) && pattern.match?(value)
85
+ end
86
+
87
+ attr_reader :path, :entries
88
+
89
+ def initialize(path, entries, exists)
90
+ @path = path
91
+ @entries = entries.freeze
92
+ @exists = exists
93
+ freeze
94
+ end
95
+
96
+ def exists? = @exists
97
+
98
+ def [](name) = @entries[name]
99
+
100
+ # Why the file of the recipe called name, with this checksum, is not
101
+ # what was installed; nil when it is. The sentence ends where the
102
+ # command that settles it goes.
103
+ def problem_for(name, sha256)
104
+ entry = @entries[name]
105
+ if entry.nil?
106
+ missing = exists? ? '' : " (there is no #{FILE_NAME} in its folder)"
107
+ return "is not in #{FILE_NAME}#{missing}: a recipe is loaded only after it was installed. Install it with"
108
+ end
109
+ return nil if entry.sha256 == sha256
110
+
111
+ "was changed after it was installed: its checksum is not the one in #{FILE_NAME}. To accept the file as it is now, run"
112
+ end
113
+ end
114
+ end
115
+ end
@@ -13,7 +13,7 @@ module ApiRecipes
13
13
  @warned = {}
14
14
 
15
15
  @methods = [].freeze
16
- @variable_names = [].freeze
16
+ VALUE_KEYS = %i[variables authorization basic_auth].freeze
17
17
 
18
18
  class << self
19
19
  attr_reader :current
@@ -26,23 +26,21 @@ module ApiRecipes
26
26
  def install(configuration)
27
27
  LOCK.synchronize do
28
28
  apis = configuration.load
29
- definitions = Compiler.compile_all(apis, configuration.variables)
29
+ # A configuration that gives no values keeps those in force now,
30
+ # read under the lock: not those of when its block started.
31
+ levels = configuration.value_levels || @current.levels
32
+ definitions = Compiler.compile_all(apis, levels.transform_values(&:variables))
30
33
  handles = definitions.transform_values { |definition| Handles.new(definition) }
31
- variables = Compiler.normalize(configuration.variables).to_h { |name, values| [name, variable_values(values)] }
32
34
  WARNED_LOCK.synchronize { @warned = {} }
35
+ # One assignment: the trees and the values of the application
36
+ # change together, for every reader.
33
37
  @current = new(configs: Compiler.frozen_copy(apis), definitions: definitions, handles: handles,
34
- generation: @current.generation + 1)
38
+ levels: levels, generation: @current.generation + 1)
35
39
  yield if block_given?
36
40
  warnings = define_methods(@current.apis) + handles.values.flat_map(&:warnings)
37
- (variables.keys - definitions.keys).each do |name|
38
- warnings << "variables are given for '#{name}', which is not a configured api"
41
+ (levels.keys - definitions.keys).each do |name|
42
+ warnings << "values are given for '#{PlainYaml.label(name.to_s, 40)}', which is not a configured api"
39
43
  end
40
- # A name that configure set belongs to the configuration: the next
41
- # successful configure applies its variables again or removes them,
42
- # so a value assigned directly under such a name is replaced. A value
43
- # assigned directly to a name that configure never set is not touched.
44
- LevelSet.replace_variables(ApiRecipes, variables, @variable_names - variables.keys)
45
- @variable_names = variables.keys.freeze
46
44
  warnings.each { |message| configuration.logger.warn(message) }
47
45
  end
48
46
  end
@@ -75,7 +73,6 @@ module ApiRecipes
75
73
  def reset!
76
74
  LOCK.synchronize do
77
75
  LevelSet.reset!
78
- @variable_names = [].freeze
79
76
  define_methods([])
80
77
  WARNED_LOCK.synchronize { @warned = {} }
81
78
  @current = new(generation: @current.generation + 1)
@@ -89,6 +86,50 @@ module ApiRecipes
89
86
  Compiler.resolve_options({ variables: values }, :with_api)[:variables]
90
87
  end
91
88
 
89
+ # values as { api name => Level }: what config.values holds. Raises
90
+ # ConfigurationError, or InvalidCredential, without showing a value.
91
+ def value_levels(values)
92
+ values.each_with_object({}) do |(name, given), levels|
93
+ unless name.is_a?(Symbol) || (name.is_a?(String) && name.valid_encoding?)
94
+ raise ConfigurationError.new(['values: the name of an api must be a String or a Symbol'])
95
+ end
96
+ key = name.to_sym
97
+ shown = PlainYaml.label(name.to_s, 40)
98
+ raise ConfigurationError.new(["values.#{shown}: is not the name of an api"]) unless shown == name.to_s && !shown.empty?
99
+ raise ConfigurationError.new(["values.#{key}: is given twice"]) if levels.key?(key)
100
+
101
+ levels[key] = level_from(given, "values.#{key}")
102
+ end.freeze
103
+ end
104
+
105
+ # The level that given describes: variables, and authorization or
106
+ # basic_auth. A credential given as nil means "send none".
107
+ def level_from(given, where)
108
+ raise ConfigurationError.new(["#{where}: must be a Hash"]) unless given.is_a?(Hash)
109
+
110
+ texts = given.keys.map(&:to_s)
111
+ # What is not one of the three names is not shown: a credential
112
+ # written in the wrong place would be.
113
+ unless (texts - VALUE_KEYS.map(&:to_s)).empty?
114
+ raise ConfigurationError.new(["#{where}: takes variables, authorization and basic_auth, and nothing else"])
115
+ end
116
+ twice = texts.find { |text| texts.count(text) > 1 }
117
+ raise ConfigurationError.new(["#{where}: #{twice} is given twice"]) if twice
118
+
119
+ names = texts.map(&:to_sym)
120
+ if names.include?(:authorization) && names.include?(:basic_auth)
121
+ raise ConfigurationError.new(["#{where}: takes authorization or basic_auth, not both"])
122
+ end
123
+
124
+ resolved = Compiler.resolve_options(given, :with_api)
125
+ kind = (names & %i[authorization basic_auth]).first
126
+ Level.new(credential: kind && Credential.from(kind, resolved[kind]), variables: resolved[:variables])
127
+ rescue ConfigurationError => e
128
+ raise e if e.errors.all? { |problem| problem.start_with?(where) }
129
+
130
+ raise ConfigurationError.new(e.errors.map { |problem| "#{where}.#{problem}" })
131
+ end
132
+
92
133
  private
93
134
 
94
135
  # One method on ApiRecipes per api, unless the name is taken by another
@@ -114,12 +155,14 @@ module ApiRecipes
114
155
  end
115
156
  end
116
157
 
117
- attr_reader :configs, :definitions, :handles, :generation
158
+ # levels: what the whole application gives to each api, name => Level.
159
+ attr_reader :configs, :definitions, :handles, :levels, :generation
118
160
 
119
- def initialize(configs: {}, definitions: {}, handles: {}, generation: 0)
161
+ def initialize(configs: {}, definitions: {}, handles: {}, levels: {}, generation: 0)
120
162
  @configs = configs.freeze
121
163
  @definitions = definitions.freeze
122
164
  @handles = handles.freeze
165
+ @levels = levels.freeze
123
166
  @generation = generation
124
167
  @globals = definitions.to_h do |name, definition|
125
168
  context = Context.new(definition: definition, owner: ApiRecipes, global_definition: definition,
@@ -129,6 +172,9 @@ module ApiRecipes
129
172
  freeze
130
173
  end
131
174
 
175
+ # The level of the application for the api called name, or nil.
176
+ def level(name) = @levels[name]
177
+
132
178
  # The global api called name, always the same object; nil if unknown.
133
179
  def global(name) = @globals[name]
134
180
 
@@ -38,16 +38,18 @@ module ApiRecipes
38
38
 
39
39
  check_follow
40
40
  check_headers
41
- chain = @context.levels
41
+ chain = @chain = @context.levels
42
42
  origin = @context.origin(chain: chain)
43
43
  credential = @context.credential(origin, chain: chain)
44
44
  address = checked(url(origin), origin)
45
45
  logger = ApiRecipes.logger
46
46
  logger.info(address) if ApiRecipes.configuration.print_urls
47
47
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
48
- http_response = send_request(client(credential, chain), address, send_options(credential, origin))
48
+ verb = @context.resolve(:verb, @definition.verb, chain: chain)
49
+ SETTINGS.each { |key| setting(key) }
50
+ http_response = send_request(client(credential, chain), verb, address, send_options(credential, origin, chain))
49
51
  elapsed = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000
50
- logger.debug("#{@definition.verb.to_s.upcase} #{address} -> #{http_response.code} (#{elapsed.round(1)}ms)")
52
+ logger.debug("#{verb.to_s.upcase} #{address} -> #{http_response.code} (#{elapsed.round(1)}ms)")
51
53
  respond(http_response)
52
54
  end
53
55
 
@@ -59,7 +61,16 @@ module ApiRecipes
59
61
 
60
62
  private
61
63
 
62
- def setting(key) = @context.setting(key, @definition, @overrides)
64
+ # The levels are those the request read: a variable in an option gets
65
+ # the value the origin and the credential were made with.
66
+ def setting(key)
67
+ @settings ||= {}
68
+ @settings.fetch(key) { @settings[key] = @context.setting(key, @definition, @overrides, chain: @chain) }
69
+ end
70
+
71
+ # The options written with variables are made before anything is sent:
72
+ # a value that does not fit stops the request, whatever the answer.
73
+ SETTINGS = %i[timeout on_bad_code mime_type ok_code].freeze
63
74
 
64
75
  def auth = @context.definition.auth || {}
65
76
 
@@ -98,8 +109,8 @@ module ApiRecipes
98
109
  # with the optional addressable gem. Without the gem that is a LoadError,
99
110
  # which a server must not be able to cause: it becomes InvalidUrl. Any
100
111
  # other LoadError passes.
101
- def send_request(client, address, options)
102
- client.request(@definition.verb, address, **options)
112
+ def send_request(client, verb, address, options)
113
+ client.request(verb, address, **options)
103
114
  rescue LoadError => e
104
115
  raise unless e.path.to_s.start_with?('addressable')
105
116
 
@@ -129,7 +140,7 @@ module ApiRecipes
129
140
 
130
141
  # default_headers, then the credential, then headers: of the request.
131
142
  def configured(credential, chain)
132
- session = HTTP.headers(@context.headers(chain: chain)).timeout(setting(:timeout))
143
+ session = HTTP.headers(@context.headers(chain: chain, endpoint: @definition)).timeout(setting(:timeout))
133
144
  return session unless credential
134
145
 
135
146
  if credential.kind == :basic_auth
@@ -146,21 +157,38 @@ module ApiRecipes
146
157
  end
147
158
  end
148
159
 
149
- def send_options(credential, origin)
160
+ # default_params, then params: of the request, then the credential
161
+ # when it travels in the query. A name is sent once: the later wins.
162
+ def send_options(credential, origin, chain)
150
163
  options = @options
151
- if credential && credential.kind == :authorization && auth[:type] == :query
152
- unless options[:params].nil? || options[:params].is_a?(Hash)
153
- raise ConfigurationError.new(['params: must be a Hash when the credential is sent in the query'])
164
+ defaults = @context.params(chain: chain, endpoint: @definition)
165
+ in_query = credential && credential.kind == :authorization && auth[:type] == :query
166
+ if in_query || !defaults.empty?
167
+ params = given_params(options[:params], in_query)
168
+ unless defaults.empty?
169
+ given = params.map { |key, _| key.to_s }
170
+ params = defaults.reject { |name, _| given.include?(name) }.to_a + params
154
171
  end
155
-
156
- params = options[:params].to_a.reject { |key, _| key.to_s == auth[:name] }
157
- options = options.merge(params: params << [auth[:name], credential.value])
172
+ if in_query
173
+ params = params.reject { |key, _| key.to_s == auth[:name] }
174
+ params << [auth[:name], credential.value]
175
+ end
176
+ options = options.merge(params: params)
158
177
  end
159
178
  follow = options[:follow]
160
179
  options = options.merge(follow: protected_follow(follow, origin)) if follow.equal?(true) || follow.is_a?(Hash)
161
180
  options
162
181
  end
163
182
 
183
+ # The params: of the request as pairs. They are joined with others by
184
+ # name, so they must be a Hash.
185
+ def given_params(params, in_query)
186
+ return params.to_a if params.nil? || params.is_a?(Hash)
187
+
188
+ why = in_query ? 'the credential is sent in the query' : 'the api has default_params'
189
+ raise ConfigurationError.new(["params: must be a Hash when #{why}"])
190
+ end
191
+
164
192
  # http.rb puts in its errors the headers it cannot read and the value of
165
193
  # a header with a line break. The headers of the request are checked
166
194
  # here, and named without their value. A tab is allowed inside a value.