api_recipes 2.10.4 → 3.0.0.beta1
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.
- checksums.yaml +4 -4
- data/README.md +631 -81
- data/UPGRADING.md +473 -0
- data/exe/api_recipes +6 -0
- data/lib/api_recipes/api.rb +71 -49
- data/lib/api_recipes/cli/upgrade.rb +179 -0
- data/lib/api_recipes/cli.rb +70 -0
- data/lib/api_recipes/configuration.rb +185 -36
- data/lib/api_recipes/endpoint.rb +68 -118
- data/lib/api_recipes/errors.rb +137 -0
- data/lib/api_recipes/internals/compiler.rb +680 -0
- data/lib/api_recipes/internals/context.rb +237 -0
- data/lib/api_recipes/internals/credential.rb +86 -0
- data/lib/api_recipes/internals/declaration.rb +225 -0
- data/lib/api_recipes/internals/definition.rb +179 -0
- data/lib/api_recipes/internals/handles.rb +81 -0
- data/lib/api_recipes/internals/level.rb +192 -0
- data/lib/api_recipes/internals/path_template.rb +131 -0
- data/lib/api_recipes/internals/registry.rb +146 -0
- data/lib/api_recipes/internals/request.rb +285 -0
- data/lib/api_recipes/internals/template.rb +73 -0
- data/lib/api_recipes/response.rb +90 -9
- data/lib/api_recipes/version.rb +3 -1
- data/lib/api_recipes.rb +42 -152
- metadata +26 -12
- data/lib/api_recipes/exceptions.rb +0 -91
- data/lib/api_recipes/route.rb +0 -165
- data/lib/api_recipes/settings.rb +0 -30
- data/lib/api_recipes/utils.rb +0 -195
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ApiRecipes
|
|
4
|
+
module Internals
|
|
5
|
+
# What configure produced: the compiled trees, their handles and one global
|
|
6
|
+
# Api per tree. Immutable: configure builds a new registry and swaps it in
|
|
7
|
+
# with one assignment, so a reader sees the old one or the new one, never a
|
|
8
|
+
# mix. The generation grows at every swap, reset! included.
|
|
9
|
+
class Registry
|
|
10
|
+
LOCK = Mutex.new
|
|
11
|
+
WARNED_LOCK = Mutex.new
|
|
12
|
+
|
|
13
|
+
@warned = {}
|
|
14
|
+
|
|
15
|
+
@methods = [].freeze
|
|
16
|
+
@variable_names = [].freeze
|
|
17
|
+
|
|
18
|
+
class << self
|
|
19
|
+
attr_reader :current
|
|
20
|
+
|
|
21
|
+
# Loads and compiles the configuration, then swaps the registry in and
|
|
22
|
+
# calls the block, which keeps the configuration: both under one lock,
|
|
23
|
+
# so that two calls never pair the configuration of one with the
|
|
24
|
+
# registry of the other. If anything raises before the swap, the
|
|
25
|
+
# current registry stays and the block is not called.
|
|
26
|
+
def install(configuration)
|
|
27
|
+
LOCK.synchronize do
|
|
28
|
+
apis = configuration.load
|
|
29
|
+
definitions = Compiler.compile_all(apis, configuration.variables)
|
|
30
|
+
handles = definitions.transform_values { |definition| Handles.new(definition) }
|
|
31
|
+
variables = Compiler.normalize(configuration.variables).to_h { |name, values| [name, variable_values(values)] }
|
|
32
|
+
WARNED_LOCK.synchronize { @warned = {} }
|
|
33
|
+
@current = new(configs: Compiler.frozen_copy(apis), definitions: definitions, handles: handles,
|
|
34
|
+
generation: @current.generation + 1)
|
|
35
|
+
yield if block_given?
|
|
36
|
+
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"
|
|
39
|
+
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
|
+
warnings.each { |message| configuration.logger.warn(message) }
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Writes message at warn level the first time it sees key, unless the
|
|
51
|
+
# configuration turned the upgrade warnings off. The message never holds
|
|
52
|
+
# a value of the application.
|
|
53
|
+
def warn_once(key, message)
|
|
54
|
+
configuration = ApiRecipes.configuration
|
|
55
|
+
return unless configuration.upgrade_warnings
|
|
56
|
+
|
|
57
|
+
first = WARNED_LOCK.synchronize { @warned.key?(key) ? false : (@warned[key] = true) }
|
|
58
|
+
configuration.logger.warn(message) if first
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# The upgrade warning for a path parameter: kind is :slash or :encoded.
|
|
62
|
+
def warn_upgrade(endpoint, param, kind)
|
|
63
|
+
message = if kind == :slash
|
|
64
|
+
"#{endpoint}: the value of '#{param}' contains '/' and is now sent as %2F. " \
|
|
65
|
+
"To span several segments use *#{param} in the path."
|
|
66
|
+
else
|
|
67
|
+
"#{endpoint}: the value of '#{param}' looks already percent-encoded. " \
|
|
68
|
+
'ApiRecipes now encodes path parameters itself.'
|
|
69
|
+
end
|
|
70
|
+
warn_once([endpoint, param, kind], message)
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
# Removes the methods generated on ApiRecipes, empties the registry and
|
|
74
|
+
# the levels, then calls the block, all under the same lock.
|
|
75
|
+
def reset!
|
|
76
|
+
LOCK.synchronize do
|
|
77
|
+
LevelSet.reset!
|
|
78
|
+
@variable_names = [].freeze
|
|
79
|
+
define_methods([])
|
|
80
|
+
WARNED_LOCK.synchronize { @warned = {} }
|
|
81
|
+
@current = new(generation: @current.generation + 1)
|
|
82
|
+
yield if block_given?
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# Variable values as a level stores them: a frozen copy with Symbol keys,
|
|
87
|
+
# or nil. Anything else than a Hash or nil raises ConfigurationError.
|
|
88
|
+
def variable_values(values)
|
|
89
|
+
Compiler.resolve_options({ variables: values }, :with_api)[:variables]
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
private
|
|
93
|
+
|
|
94
|
+
# One method on ApiRecipes per api, unless the name is taken by another
|
|
95
|
+
# method of the module, with the rule of Handles.taken?. Returns the
|
|
96
|
+
# warnings.
|
|
97
|
+
def define_methods(names)
|
|
98
|
+
warnings = []
|
|
99
|
+
defined = names.select do |name|
|
|
100
|
+
next true if @methods.include?(name)
|
|
101
|
+
|
|
102
|
+
if Handles.taken?(ApiRecipes.singleton_class, name)
|
|
103
|
+
warnings << "api '#{name}' has the name of a method of ApiRecipes; reach it with ApiRecipes[#{name.inspect}]"
|
|
104
|
+
next false
|
|
105
|
+
end
|
|
106
|
+
ApiRecipes.define_singleton_method(name) { Registry.current.global(name) || ApiRecipes[name] }
|
|
107
|
+
true
|
|
108
|
+
end
|
|
109
|
+
(@methods - defined).each do |name|
|
|
110
|
+
ApiRecipes.singleton_class.remove_method(name) if ApiRecipes.singleton_class.method_defined?(name, false)
|
|
111
|
+
end
|
|
112
|
+
@methods = defined.freeze
|
|
113
|
+
warnings
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
attr_reader :configs, :definitions, :handles, :generation
|
|
118
|
+
|
|
119
|
+
def initialize(configs: {}, definitions: {}, handles: {}, generation: 0)
|
|
120
|
+
@configs = configs.freeze
|
|
121
|
+
@definitions = definitions.freeze
|
|
122
|
+
@handles = handles.freeze
|
|
123
|
+
@generation = generation
|
|
124
|
+
@globals = definitions.to_h do |name, definition|
|
|
125
|
+
context = Context.new(definition: definition, owner: ApiRecipes, global_definition: definition,
|
|
126
|
+
handles: handles[name], generation: generation)
|
|
127
|
+
[name, handles[name].for(definition).new(context)]
|
|
128
|
+
end.freeze
|
|
129
|
+
freeze
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
# The global api called name, always the same object; nil if unknown.
|
|
133
|
+
def global(name) = @globals[name]
|
|
134
|
+
|
|
135
|
+
def apis = @definitions.keys
|
|
136
|
+
|
|
137
|
+
def inspect = "#<#{self.class.name} generation #{@generation} apis: #{apis.join(', ')}>"
|
|
138
|
+
|
|
139
|
+
def to_s = inspect
|
|
140
|
+
|
|
141
|
+
def pretty_print(queue) = queue.text(inspect)
|
|
142
|
+
|
|
143
|
+
@current = new
|
|
144
|
+
end
|
|
145
|
+
end
|
|
146
|
+
end
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ApiRecipes
|
|
4
|
+
module Internals
|
|
5
|
+
# One request to one endpoint: builds the URL and the http.rb client, sends
|
|
6
|
+
# the request and checks the outcome.
|
|
7
|
+
class Request
|
|
8
|
+
ORIGIN = %r{\A(https?)://([^:/]+)(?::(\d+))?\z}
|
|
9
|
+
DEFAULT_EXPECTED = '200 <= CODE < 300'.freeze
|
|
10
|
+
FOLLOW_PROBLEM = 'follow: must be true, false or a Hash'.freeze
|
|
11
|
+
FOLLOW_OPTIONS = %i[strict max_hops on_redirect].freeze
|
|
12
|
+
CONTROL_BYTE = /[\x00-\x1f\x7f]/n
|
|
13
|
+
VALUE_CONTROL_BYTE = /[\x00-\x08\x0a-\x1f\x7f]/n
|
|
14
|
+
|
|
15
|
+
def initialize(context:, definition:, path:, options:, overrides: nil)
|
|
16
|
+
@context = context
|
|
17
|
+
@definition = definition
|
|
18
|
+
@path = path
|
|
19
|
+
@options = symbol_keys(options || {})
|
|
20
|
+
@overrides = overrides
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# Scheme, host, port and path. Never a query string: parameters and a
|
|
24
|
+
# credential sent in the query are added only when the request is sent.
|
|
25
|
+
# origin: the one the request already computed, if any.
|
|
26
|
+
def url(origin = nil)
|
|
27
|
+
return nil unless @definition.route?
|
|
28
|
+
|
|
29
|
+
scheme, host, port = parts(origin || @context.origin)
|
|
30
|
+
path = @path.start_with?('/') ? @path : "/#{@path}"
|
|
31
|
+
(scheme == 'https' ? URI::HTTPS : URI::HTTP).new(scheme, nil, host, port, nil, path, nil, nil, nil, nil, false)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# The levels of the context are read once: the origin, the credential and
|
|
35
|
+
# the headers all come from the same chain.
|
|
36
|
+
def perform
|
|
37
|
+
raise NoRouteExists.new(@definition.name) unless @definition.route?
|
|
38
|
+
|
|
39
|
+
check_follow
|
|
40
|
+
check_headers
|
|
41
|
+
chain = @context.levels
|
|
42
|
+
origin = @context.origin(chain: chain)
|
|
43
|
+
credential = @context.credential(origin, chain: chain)
|
|
44
|
+
address = checked(url(origin), origin)
|
|
45
|
+
logger = ApiRecipes.logger
|
|
46
|
+
logger.info(address) if ApiRecipes.configuration.print_urls
|
|
47
|
+
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
48
|
+
http_response = send_request(client(credential, chain), address, send_options(credential, origin))
|
|
49
|
+
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)")
|
|
51
|
+
respond(http_response)
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def inspect = "#<#{self.class.name} #{@definition.full_name}>"
|
|
55
|
+
|
|
56
|
+
def to_s = inspect
|
|
57
|
+
|
|
58
|
+
def pretty_print(queue) = queue.text(inspect)
|
|
59
|
+
|
|
60
|
+
private
|
|
61
|
+
|
|
62
|
+
def setting(key) = @context.setting(key, @definition, @overrides)
|
|
63
|
+
|
|
64
|
+
def auth = @context.definition.auth || {}
|
|
65
|
+
|
|
66
|
+
# [scheme, host, port] of an origin; port is nil when it is the default.
|
|
67
|
+
def parts(origin)
|
|
68
|
+
match = ORIGIN.match(origin)
|
|
69
|
+
raise InvalidUrl, "api '#{@context.definition.name}' has an origin that is not http or https" unless match
|
|
70
|
+
|
|
71
|
+
[match[1], match[2], match[3]&.to_i]
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# The url as http.rb reads it must point to the origin that was validated.
|
|
75
|
+
# http.rb hands to Addressable, an optional gem, what Ruby's URI cannot
|
|
76
|
+
# parse, and its failures there are not ours to predict. So the address is
|
|
77
|
+
# first read with Ruby's URI alone: anything that is not ASCII or that Ruby
|
|
78
|
+
# refuses is refused, and http.rb then never reaches Addressable.
|
|
79
|
+
def checked(url, origin)
|
|
80
|
+
address = url.to_s
|
|
81
|
+
scheme, host, port = parts(origin)
|
|
82
|
+
raise InvalidUrl, "the url of api '#{@context.definition.name}' cannot be parsed" unless plain_uri?(address)
|
|
83
|
+
|
|
84
|
+
stdlib = ::URI.parse(address)
|
|
85
|
+
same = stdlib.scheme.to_s.casecmp?(scheme) && stdlib.host.to_s.casecmp?(host) &&
|
|
86
|
+
stdlib.port == (port || Context::DEFAULT_PORTS.fetch(scheme))
|
|
87
|
+
raise InvalidUrl, "the url does not point to the origin of api '#{@context.definition.name}'" unless same
|
|
88
|
+
|
|
89
|
+
uri = HTTP::URI.parse(address)
|
|
90
|
+
raise InvalidUrl, "the url does not point to the origin of api '#{@context.definition.name}'" unless same_origin?(uri, origin)
|
|
91
|
+
|
|
92
|
+
address
|
|
93
|
+
rescue HTTP::URI::InvalidError
|
|
94
|
+
raise InvalidUrl, "the url of api '#{@context.definition.name}' cannot be parsed"
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
# http.rb reads the address of a redirect that Ruby's URI cannot parse
|
|
98
|
+
# with the optional addressable gem. Without the gem that is a LoadError,
|
|
99
|
+
# which a server must not be able to cause: it becomes InvalidUrl. Any
|
|
100
|
+
# other LoadError passes.
|
|
101
|
+
def send_request(client, address, options)
|
|
102
|
+
client.request(@definition.verb, address, **options)
|
|
103
|
+
rescue LoadError => e
|
|
104
|
+
raise unless e.path.to_s.start_with?('addressable')
|
|
105
|
+
|
|
106
|
+
raise InvalidUrl, "api '#{@context.definition.name}' was redirected to an address that " \
|
|
107
|
+
'cannot be read without the addressable gem'
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
def plain_uri?(address)
|
|
111
|
+
address.ascii_only? && ::URI.parse(address) && true
|
|
112
|
+
rescue ::URI::InvalidURIError
|
|
113
|
+
false
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
def same_origin?(uri, origin)
|
|
117
|
+
scheme, host, port = parts(origin)
|
|
118
|
+
port ||= Context::DEFAULT_PORTS.fetch(scheme)
|
|
119
|
+
uri.scheme.to_s.casecmp?(scheme) && uri.host.to_s.casecmp?(host) &&
|
|
120
|
+
uri.normalized_host.to_s.casecmp?(host) && uri.port == port
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
# An HTTP::Client, not the HTTP::Session the chainable methods of http.rb
|
|
124
|
+
# return: along redirects a session keeps a cookie jar and sets every
|
|
125
|
+
# cookie in it on each hop, after on_redirect and whatever the origin.
|
|
126
|
+
def client(credential, chain)
|
|
127
|
+
HTTP::Client.new(configured(credential, chain).default_options)
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# default_headers, then the credential, then headers: of the request.
|
|
131
|
+
def configured(credential, chain)
|
|
132
|
+
session = HTTP.headers(@context.headers(chain: chain)).timeout(setting(:timeout))
|
|
133
|
+
return session unless credential
|
|
134
|
+
|
|
135
|
+
if credential.kind == :basic_auth
|
|
136
|
+
if %i[header query].include?(auth[:type])
|
|
137
|
+
raise InvalidCredential, "basic_auth cannot be sent with auth type '#{auth[:type]}': assign it with authorization"
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
return session.basic_auth(**credential.value)
|
|
141
|
+
end
|
|
142
|
+
case auth[:type]
|
|
143
|
+
when :header then session.headers(auth[:name] => credential.value)
|
|
144
|
+
when :query then session
|
|
145
|
+
else session.auth(credential.value)
|
|
146
|
+
end
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def send_options(credential, origin)
|
|
150
|
+
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'])
|
|
154
|
+
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])
|
|
158
|
+
end
|
|
159
|
+
follow = options[:follow]
|
|
160
|
+
options = options.merge(follow: protected_follow(follow, origin)) if follow.equal?(true) || follow.is_a?(Hash)
|
|
161
|
+
options
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
# http.rb puts in its errors the headers it cannot read and the value of
|
|
165
|
+
# a header with a line break. The headers of the request are checked
|
|
166
|
+
# here, and named without their value. A tab is allowed inside a value.
|
|
167
|
+
def check_headers
|
|
168
|
+
headers = @options[:headers]
|
|
169
|
+
return if headers.nil?
|
|
170
|
+
unless headers.is_a?(Hash) || headers.is_a?(Array) || headers.is_a?(HTTP::Headers)
|
|
171
|
+
raise ConfigurationError.new(['headers: must be a Hash'])
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
headers.each do |name, value|
|
|
175
|
+
next unless bad_text?(name, CONTROL_BYTE) || Array(value).any? { |item| bad_text?(item, VALUE_CONTROL_BYTE) }
|
|
176
|
+
|
|
177
|
+
shown = name.to_s.scrub('?').gsub(/[^[:print:]]/, '?')[0, 40]
|
|
178
|
+
raise ConfigurationError.new(["headers: the name and the value of '#{shown}' must be valid text " \
|
|
179
|
+
'without control characters'])
|
|
180
|
+
end
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
def bad_text?(text, control)
|
|
184
|
+
text = text.to_s
|
|
185
|
+
!text.valid_encoding? || text.b.match?(control)
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
# http.rb follows any value that responds to fetch, so only the values the
|
|
189
|
+
# protection can wrap are accepted. http.rb reads the options of a Hash
|
|
190
|
+
# only once the first response is in: they are checked here, before
|
|
191
|
+
# anything is sent.
|
|
192
|
+
def check_follow
|
|
193
|
+
follow = @options[:follow]
|
|
194
|
+
case follow
|
|
195
|
+
when nil, true, false then nil
|
|
196
|
+
when Hash then check_follow_options(symbol_keys(follow))
|
|
197
|
+
else raise ConfigurationError.new([FOLLOW_PROBLEM])
|
|
198
|
+
end
|
|
199
|
+
end
|
|
200
|
+
|
|
201
|
+
def check_follow_options(settings)
|
|
202
|
+
unknown = settings.keys.find { |key| !FOLLOW_OPTIONS.include?(key) }
|
|
203
|
+
raise ConfigurationError.new(["follow: unknown option '#{unknown.to_s.scrub('?')}'"]) if unknown
|
|
204
|
+
|
|
205
|
+
return if !settings.key?(:max_hops) || settings[:max_hops].is_a?(Integer)
|
|
206
|
+
|
|
207
|
+
raise ConfigurationError.new(['follow.max_hops: must be an integer'])
|
|
208
|
+
end
|
|
209
|
+
|
|
210
|
+
# true or a Hash: follows redirects, but a request that leaves the origin
|
|
211
|
+
# loses Authorization, Cookie and what auth names, wherever they came from.
|
|
212
|
+
# Then the on_redirect of the caller is called.
|
|
213
|
+
def protected_follow(follow, origin)
|
|
214
|
+
settings = follow.is_a?(Hash) ? symbol_keys(follow) : {}
|
|
215
|
+
given = settings[:on_redirect]
|
|
216
|
+
settings.merge(on_redirect: lambda do |response, request|
|
|
217
|
+
leave_origin(request) unless same_origin?(request.uri, origin)
|
|
218
|
+
given.call(response, request) if given.respond_to?(:call)
|
|
219
|
+
end)
|
|
220
|
+
end
|
|
221
|
+
|
|
222
|
+
def leave_origin(request)
|
|
223
|
+
name = auth[:name]
|
|
224
|
+
['Authorization', 'Cookie', name].compact.each { |header| request.headers.delete(header) }
|
|
225
|
+
drop_param(request.uri, name) if auth[:type] == :query
|
|
226
|
+
end
|
|
227
|
+
|
|
228
|
+
def drop_param(uri, name)
|
|
229
|
+
return if uri.query.nil?
|
|
230
|
+
|
|
231
|
+
kept = uri.query.split('&').reject { |pair| param_named?(pair, name) }
|
|
232
|
+
uri.query = kept.empty? ? nil : kept.join('&')
|
|
233
|
+
end
|
|
234
|
+
|
|
235
|
+
def param_named?(pair, name)
|
|
236
|
+
key = pair.split('=', 2).first.to_s
|
|
237
|
+
key == name || URI.decode_www_form_component(key) == name
|
|
238
|
+
rescue ArgumentError
|
|
239
|
+
false
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
# A plain Hash whose String keys become Symbols, read as UTF-8 like the
|
|
243
|
+
# compiler reads names. A key that cannot be read is left as it is.
|
|
244
|
+
def symbol_keys(hash)
|
|
245
|
+
hash.each_with_object({}) { |(key, value), out| out[symbol_key(key)] = value }
|
|
246
|
+
end
|
|
247
|
+
|
|
248
|
+
def symbol_key(key)
|
|
249
|
+
return key unless key.is_a?(String)
|
|
250
|
+
|
|
251
|
+
key.encode(Encoding::UTF_8).to_sym
|
|
252
|
+
rescue EncodingError
|
|
253
|
+
key
|
|
254
|
+
end
|
|
255
|
+
|
|
256
|
+
def respond(http_response)
|
|
257
|
+
mime_type = setting(:mime_type)
|
|
258
|
+
hidden = auth[:type] == :query ? auth[:name] : nil
|
|
259
|
+
success, expected, message = outcome(http_response, mime_type, hidden)
|
|
260
|
+
response = Response.new(http_response, mime_type: mime_type, success: success, hidden_param: hidden)
|
|
261
|
+
if !success && setting(:on_bad_code).to_s == 'raise'
|
|
262
|
+
raise ResponseCodeNotAsExpected.new(@path, expected, response, message: message)
|
|
263
|
+
end
|
|
264
|
+
|
|
265
|
+
response
|
|
266
|
+
end
|
|
267
|
+
|
|
268
|
+
# [success, expected code, message of the error]
|
|
269
|
+
def outcome(http_response, mime_type, hidden)
|
|
270
|
+
verify_with = setting(:verify_with)
|
|
271
|
+
owner = @context.owner
|
|
272
|
+
if verify_with && owner.respond_to?(verify_with, true)
|
|
273
|
+
checked = Response.new(http_response, mime_type: mime_type, hidden_param: hidden)
|
|
274
|
+
valid = owner.send(verify_with, checked) ? true : false
|
|
275
|
+
return [valid, nil, "response for request on route '#{@path}' was not valid. Verified with #{verify_with}."]
|
|
276
|
+
end
|
|
277
|
+
|
|
278
|
+
ok_code = setting(:ok_code)
|
|
279
|
+
return [http_response.status.success?, DEFAULT_EXPECTED, nil] if ok_code.nil?
|
|
280
|
+
|
|
281
|
+
[Array(ok_code).include?(http_response.code), ok_code, nil]
|
|
282
|
+
end
|
|
283
|
+
end
|
|
284
|
+
end
|
|
285
|
+
end
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ApiRecipes
|
|
4
|
+
module Internals
|
|
5
|
+
# A string with {name} variables, used for the host, the base_url and the
|
|
6
|
+
# header values of an api. How a value is checked depends on the position.
|
|
7
|
+
class Template
|
|
8
|
+
VARIABLE = /\{([A-Za-z_]\w*)\}/
|
|
9
|
+
HOST_VALUE = /\A[A-Za-z0-9._-]+\z/
|
|
10
|
+
CONTROL = /[\x00-\x1F\x7F]/
|
|
11
|
+
POSITIONS = %i[host base_url header].freeze
|
|
12
|
+
|
|
13
|
+
def initialize(string, position)
|
|
14
|
+
raise ArgumentError, "unknown template position '#{position}'" unless POSITIONS.include?(position)
|
|
15
|
+
|
|
16
|
+
@string = string.to_s.dup.freeze
|
|
17
|
+
@position = position
|
|
18
|
+
@names = @string.scan(VARIABLE).flatten.map(&:to_sym).uniq.freeze
|
|
19
|
+
freeze
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
attr_reader :names
|
|
23
|
+
|
|
24
|
+
# Shows the variable names only: the string can hold a secret.
|
|
25
|
+
def inspect
|
|
26
|
+
"#<#{self.class} #{@position} variables: #{@names.empty? ? 'none' : @names.join(', ')}>"
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def pretty_print(printer)
|
|
30
|
+
printer.text(inspect)
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def static?
|
|
34
|
+
@names.empty?
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def to_s
|
|
38
|
+
@string
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def expand(values, api:)
|
|
42
|
+
@string.gsub(VARIABLE) do
|
|
43
|
+
name = Regexp.last_match(1).to_sym
|
|
44
|
+
raise MissingVariable.new(api, name) unless values.key?(name)
|
|
45
|
+
|
|
46
|
+
encode(values[name], name, api)
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
private
|
|
51
|
+
|
|
52
|
+
def encode(value, name, api)
|
|
53
|
+
text = value.to_s
|
|
54
|
+
bytes = text.b
|
|
55
|
+
case @position
|
|
56
|
+
when :host
|
|
57
|
+
reject(api, name, 'must contain only letters, digits, dots, hyphens and underscores') unless HOST_VALUE.match?(bytes)
|
|
58
|
+
text
|
|
59
|
+
when :base_url
|
|
60
|
+
reject(api, name, 'must not be blank, "." or ".."') if value.nil? || text.empty? || text == '.' || text == '..'
|
|
61
|
+
PathTemplate.escape(text)
|
|
62
|
+
else
|
|
63
|
+
reject(api, name, 'must not contain control characters') if CONTROL.match?(bytes)
|
|
64
|
+
text
|
|
65
|
+
end
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
def reject(api, name, reason)
|
|
69
|
+
raise InvalidVariable.new(api, name, reason)
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
end
|
data/lib/api_recipes/response.rb
CHANGED
|
@@ -1,23 +1,104 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'forwardable'
|
|
4
|
+
|
|
1
5
|
module ApiRecipes
|
|
6
|
+
# The result of a request: the http.rb response plus parsed data.
|
|
2
7
|
class Response
|
|
8
|
+
extend Forwardable
|
|
9
|
+
|
|
10
|
+
KEY_PATTERN = /\A[a-z_][A-Za-z0-9_]*\z/
|
|
3
11
|
|
|
4
12
|
attr_reader :original_response
|
|
5
13
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
14
|
+
# Public instance methods of HTTP::Response (http.rb 6) except request and
|
|
15
|
+
# deconstruct_keys, which would show the request, and uri and inspect,
|
|
16
|
+
# which are defined here.
|
|
17
|
+
def_delegators :@original_response,
|
|
18
|
+
:body, :charset, :chunked?, :code, :connection, :content_length, :content_type,
|
|
19
|
+
:cookies, :deconstruct, :flush, :headers, :mime_type, :parse, :proxy_headers,
|
|
20
|
+
:readpartial, :reason, :status, :to_a, :to_s, :to_str, :version
|
|
21
|
+
|
|
22
|
+
def initialize(http_response, mime_type: nil, success: nil, hidden_param: nil)
|
|
23
|
+
@original_response = http_response
|
|
24
|
+
@mime_type = mime_type
|
|
25
|
+
@success = success
|
|
26
|
+
@hidden_param = hidden_param&.to_s
|
|
27
|
+
@parsed = false
|
|
9
28
|
end
|
|
10
29
|
|
|
11
30
|
def data
|
|
12
|
-
return @data
|
|
31
|
+
return @data if @parsed
|
|
32
|
+
|
|
33
|
+
@data = @original_response.parse(@mime_type)
|
|
34
|
+
@parsed = true
|
|
35
|
+
@data
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def success?
|
|
39
|
+
return @success unless @success.nil?
|
|
40
|
+
|
|
41
|
+
@original_response.status.success?
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def uri
|
|
45
|
+
uri = @original_response.uri
|
|
46
|
+
return uri if @hidden_param.nil? || uri.query.nil?
|
|
47
|
+
|
|
48
|
+
kept = uri.query.split('&').reject { |pair| hidden_pair?(pair) }
|
|
49
|
+
uri.dup.tap { |copy| copy.query = kept.empty? ? nil : kept.join('&') }
|
|
50
|
+
end
|
|
13
51
|
|
|
14
|
-
|
|
15
|
-
|
|
52
|
+
def fill(object, only: nil, except: nil)
|
|
53
|
+
only = only && Array(only).map(&:to_sym)
|
|
54
|
+
except = except && Array(except).map(&:to_sym)
|
|
55
|
+
data = self.data
|
|
56
|
+
filled = case data
|
|
57
|
+
when Hash
|
|
58
|
+
fill_object(object, data, only, except)
|
|
59
|
+
when Array
|
|
60
|
+
data.map { |element| fill_object(object.new, element, only, except) }
|
|
61
|
+
end
|
|
62
|
+
yield filled, data, status if block_given?
|
|
63
|
+
filled
|
|
16
64
|
end
|
|
17
65
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
66
|
+
def inspect
|
|
67
|
+
"#<#{self.class.name} #{status} #{mime_type}>"
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# The http.rb response holds the request, with its credential: a Response
|
|
71
|
+
# is never serialized.
|
|
72
|
+
def marshal_dump = raise(TypeError, 'an ApiRecipes::Response cannot be serialized')
|
|
73
|
+
|
|
74
|
+
def encode_with(_coder) = raise(TypeError, 'an ApiRecipes::Response cannot be serialized')
|
|
75
|
+
|
|
76
|
+
def as_json(*) = raise(TypeError, 'an ApiRecipes::Response cannot be serialized: use response.data')
|
|
77
|
+
|
|
78
|
+
def to_json(*) = raise(TypeError, 'an ApiRecipes::Response cannot be serialized: use response.data')
|
|
79
|
+
|
|
80
|
+
private
|
|
81
|
+
|
|
82
|
+
def hidden_pair?(pair)
|
|
83
|
+
name = pair.split('=', 2).first.to_s
|
|
84
|
+
name == @hidden_param || URI.decode_www_form_component(name) == @hidden_param
|
|
85
|
+
rescue ArgumentError
|
|
86
|
+
false
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def fill_object(object, attributes, only, except)
|
|
90
|
+
return object unless attributes.is_a?(Hash)
|
|
91
|
+
|
|
92
|
+
attributes.each do |key, value|
|
|
93
|
+
key = key.to_s
|
|
94
|
+
next unless KEY_PATTERN.match?(key)
|
|
95
|
+
next if only && !only.include?(key.to_sym)
|
|
96
|
+
next if except&.include?(key.to_sym)
|
|
97
|
+
next unless object.respond_to?("#{key}=")
|
|
98
|
+
|
|
99
|
+
object.public_send("#{key}=", value)
|
|
100
|
+
end
|
|
101
|
+
object
|
|
21
102
|
end
|
|
22
103
|
end
|
|
23
104
|
end
|
data/lib/api_recipes/version.rb
CHANGED