Class: Aspera::Rest
- Inherits:
-
Object
- Object
- Aspera::Rest
- Defined in:
- lib/aspera/rest.rb
Overview
a simple class to make HTTP calls, equivalent to rest-client rest call errors are raised as exception RestCallError and error are analyzed in RestErrorAnalyzer
Direct Known Subclasses
Constant Summary collapse
- ENTITY_NOT_FOUND =
error message when entity not found (TODO: use specific exception)
'No such'
- JSON_DECODE =
Content-Type that are JSON
['application/json', 'application/vnd.api+json', 'application/x-javascript'].freeze
Instance Attribute Summary collapse
-
#auth_params ⇒ Object
readonly
Returns the value of attribute auth_params.
-
#base_url ⇒ Object
readonly
Returns the value of attribute base_url.
Class Method Summary collapse
-
.array_params(values) ⇒ Object
Build a parameter list prefixed with “[]”.
- .array_params?(values) ⇒ Boolean
-
.basic_authorization(user, pass) ⇒ String
Basic auth token.
-
.build_uri(url, query = nil) ⇒ Object
Build URI from URL and parameters and check it is http or https encode array [] parameters.
-
.io_http_session(http_session) ⇒ Object
get Net::HTTP underlying socket i/o little hack, handy because HTTP debug, proxy, etc…
- .parse_header(header) ⇒ Object
-
.query_to_h(query) ⇒ Hash
Decode query string as Hash Does not support arrays in query string, no standard, e.g.
-
.remote_certificate_chain(url, as_string: true) ⇒ String
PEM certificates of remote server.
-
.start_http_session(base_url) ⇒ Net::HTTP
Start a HTTP/S session, also used for web sockets.
Instance Method Summary collapse
-
#call(operation:, subpath: nil, query: nil, body: nil, body_type: nil, save_to_file: nil, return_error: false, headers: nil) ⇒ Object
HTTP/S REST call.
- #cancel(subpath) ⇒ Object
-
#create(subpath, params) ⇒ Object
CRUD simplified methods here If specific elements are needed, then use the full ‘call` method.
- #delete(subpath, params = nil) ⇒ Object
-
#initialize(base_url:, auth: {type: :none}, not_auth_codes: ['401'], redirect_max: 0, headers: {}) ⇒ Rest
constructor
Create a REST object for API calls HTTP sessions parameters can be modified using global parameters in RestParameters For example, TLS verification can be skipped.
-
#lookup_by_name(subpath, search_name, query: nil) ⇒ Object
Query entity by general search (read with parameter ‘q`) TODO: not generic enough ? move somewhere ? inheritance ?.
-
#oauth ⇒ Object
The OAuth object (create, or cached if already created).
-
#params ⇒ Object
Creation parameters.
- #read(subpath, query = nil) ⇒ Object
- #update(subpath, params) ⇒ Object
Constructor Details
#initialize(base_url:, auth: {type: :none}, not_auth_codes: ['401'], redirect_max: 0, headers: {}) ⇒ Rest
Create a REST object for API calls HTTP sessions parameters can be modified using global parameters in RestParameters For example, TLS verification can be skipped.
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 |
# File 'lib/aspera/rest.rb', line 217 def initialize( base_url:, auth: {type: :none}, not_auth_codes: ['401'], redirect_max: 0, headers: {} ) Aspera.assert_type(base_url, String) # base url with no trailing slashes (note: string may be frozen) @base_url = base_url.gsub(%r{/+$}, '') # remove trailing port if it is 443 and scheme is https @base_url = @base_url.gsub(/:443$/, '') if @base_url.start_with?('https://') @base_url = @base_url.gsub(/:80$/, '') if @base_url.start_with?('http://') Log.log.debug{"Rest.new(#{@base_url})"} # default is no auth @auth_params = auth Aspera.assert_type(@auth_params, Hash) Aspera.assert(@auth_params.key?(:type)){'no auth type defined'} @not_auth_codes = not_auth_codes Aspera.assert_type(@not_auth_codes, Array) # persistent session @http_session = nil @redirect_max = redirect_max Aspera.assert_type(@redirect_max, Integer) @headers = headers Aspera.assert_type(@headers, Hash) @headers['User-Agent'] ||= RestParameters.instance.user_agent # OAuth object (created on demand) @oauth = nil end |
Instance Attribute Details
#auth_params ⇒ Object (readonly)
Returns the value of attribute auth_params.
191 192 193 |
# File 'lib/aspera/rest.rb', line 191 def auth_params @auth_params end |
#base_url ⇒ Object (readonly)
Returns the value of attribute base_url.
190 191 192 |
# File 'lib/aspera/rest.rb', line 190 def base_url @base_url end |
Class Method Details
.array_params(values) ⇒ Object
Build a parameter list prefixed with “[]”
69 70 71 |
# File 'lib/aspera/rest.rb', line 69 def array_params(values) return [ARRAY_PARAMS].concat(values) end |
.array_params?(values) ⇒ Boolean
73 74 75 |
# File 'lib/aspera/rest.rb', line 73 def array_params?(values) return values.first.eql?(ARRAY_PARAMS) end |
.basic_authorization(user, pass) ⇒ String
Returns Basic auth token.
65 |
# File 'lib/aspera/rest.rb', line 65 def (user, pass); return "Basic #{Base64.strict_encode64("#{user}:#{pass}")}"; end |
.build_uri(url, query = nil) ⇒ Object
Build URI from URL and parameters and check it is http or https encode array [] parameters
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
# File 'lib/aspera/rest.rb', line 80 def build_uri(url, query=nil) uri = URI.parse(url) Aspera.assert(%w[http https].include?(uri.scheme)){"REST endpoint shall be http/s not #{uri.scheme}"} return uri if query.nil? || query.respond_to?(:empty?) && query.empty? Log.log.debug{Log.dump('query', query)} query_array = [] case query when Hash query.each do |k, v| case v when Array # support array for query parameter, there is no standard. Either p[]=1&p[]=2, or p=1&p=2 suffix = array_params?(v) ? v.shift : '' v.each do |e| query_array.push(["#{k}#{suffix}", e]) end else query_array.push([k, v]) end end when Array Aspera.assert(query.all?{|i| i.is_a?(Array) && i.length.eql?(2)}) {'Query must be array of arrays or 2 elements'} query_array = query else raise "Query must be Hash or Array, not #{query.class}" end # [] is allowed in url parameters uri.query = URI.encode_www_form(query_array).gsub('%5B%5D=', '[]=') return uri end |
.io_http_session(http_session) ⇒ Object
get Net::HTTP underlying socket i/o little hack, handy because HTTP debug, proxy, etc… will be available used implement web sockets after ‘start_http_session`
141 142 143 144 145 146 147 |
# File 'lib/aspera/rest.rb', line 141 def io_http_session(http_session) Aspera.assert_type(http_session, Net::HTTP) # Net::BufferedIO in net/protocol.rb result = http_session.instance_variable_get(:@socket) Aspera.assert(!result.nil?){"no socket for #{http_session}"} return result end |
.parse_header(header) ⇒ Object
166 167 168 169 170 171 172 173 174 175 |
# File 'lib/aspera/rest.rb', line 166 def parse_header(header) type, *params = header.split(/;\s*/) parameters = params.map do |param| one = param.split(/=\s*/) one[0] = one[0].to_sym one[1] = one[1].gsub(/\A"|"\z/, '') one end.to_h { type: type.downcase, parameters: parameters } end |
.query_to_h(query) ⇒ Hash
Decode query string as Hash Does not support arrays in query string, no standard, e.g. PHP’s way is p[]=1&p=2
115 116 117 118 119 120 121 |
# File 'lib/aspera/rest.rb', line 115 def query_to_h(query) URI.decode_www_form(query).each_with_object({}) do |pair, h| key = pair.first raise "Array not supported in query string: #{key}" if key.include?('[]') || h.key?(key) h[key] = pair.last end end |
.remote_certificate_chain(url, as_string: true) ⇒ String
Returns PEM certificates of remote server.
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
# File 'lib/aspera/rest.rb', line 150 def remote_certificate_chain(url, as_string: true) result = [] # initiate a session to retrieve remote certificate http_session = Rest.start_http_session(url) begin # retrieve underlying openssl socket result = Rest.io_http_session(http_session).io.peer_cert_chain rescue result = http_session.peer_cert ensure http_session.finish end result = result.map(&:to_pem).join("\n") if as_string return result end |
.start_http_session(base_url) ⇒ Net::HTTP
Start a HTTP/S session, also used for web sockets
126 127 128 129 130 131 132 133 134 135 136 |
# File 'lib/aspera/rest.rb', line 126 def start_http_session(base_url) uri = build_uri(base_url) # this honors http_proxy env var http_session = Net::HTTP.new(uri.host, uri.port) http_session.use_ssl = uri.scheme.eql?('https') # set http options in callback, such as timeout and cert. verification RestParameters.instance.session_cb&.call(http_session) # manually start session for keep alive (if supported by server, else, session is closed every time) http_session.start return http_session end |
Instance Method Details
#call(operation:, subpath: nil, query: nil, body: nil, body_type: nil, save_to_file: nil, return_error: false, headers: nil) ⇒ Object
HTTP/S REST call
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 |
# File 'lib/aspera/rest.rb', line 268 def call( operation:, subpath: nil, query: nil, body: nil, body_type: nil, save_to_file: nil, return_error: false, headers: nil ) subpath = subpath.to_s if subpath.is_a?(Symbol) subpath = '' if subpath.nil? Log.log.debug{"#{operation} [#{subpath}]".red.bold.bg_green} Log.log.debug{Log.dump(:body, body)} Aspera.assert_type(subpath, String) if headers.nil? headers = @headers.clone else h = headers headers = @headers.clone headers.merge!(h) end Aspera.assert_type(headers, Hash) case @auth_params[:type] when :none # no auth when :basic Log.log.debug('using Basic auth') # done in build_req when :oauth2 headers['Authorization'] = oauth. unless headers.key?('Authorization') when :url query ||= {} @auth_params[:url_query].each do |key, value| query[key] = value end else Aspera.error_unexpected_value(@auth_params[:type]) end result = {http: nil} # start a block to be able to retry the actual HTTP request in case of OAuth token expiration begin # TODO: shall we percent encode subpath (spaces) test with access key delete with space in id # URI.escape() separator = ['', '/'].include?(subpath) ? '' : '/' uri = self.class.build_uri("#{@base_url}#{separator}#{subpath}", query) Log.log.debug{"URI=#{uri}"} begin # instantiate request object based on string name req = Net::HTTP.const_get(operation.capitalize).new(uri) rescue NameError raise "unsupported operation : #{operation}" end case body_type when :json req.body = JSON.generate(body) # , ascii_only: true req['Content-Type'] = 'application/json' when :www req.body = URI.encode_www_form(body) req['Content-Type'] = 'application/x-www-form-urlencoded' when :text req.body = body req['Content-Type'] = 'text/plain' when nil else raise "unsupported body type : #{body_type}" end # set headers headers.each do |key, value| req[key] = value end # :type = :basic req.basic_auth(@auth_params[:username], @auth_params[:password]) if @auth_params[:type].eql?(:basic) Log.log.trace1{Log.dump(:req_body, req.body)} # we try the call, and will retry only if oauth, as we can, first with refresh, and then re-auth if refresh is bad oauth_tries ||= 2 timeout_tries ||= 5 general_tries ||= 1 + RestParameters.instance.retry_on_error # initialize with number of initial retries allowed, nil gives zero tries_remain_redirect = @redirect_max if tries_remain_redirect.nil? Log.log.debug("send request (retries=#{tries_remain_redirect})") result_mime = nil file_saved = false # make http request (pipelined) http_session.request(req) do |response| result[:http] = response result_mime = self.class.parse_header(result[:http]['Content-Type'] || 'text/plain')[:type] # JSON data needs to be parsed, in case it contains an error code if !save_to_file.nil? && result[:http].code.to_s.start_with?('2') && !result[:http]['Content-Length'].nil? && !JSON_DECODE.include?(result_mime) total_size = result[:http]['Content-Length'].to_i Log.log.debug('before write file') target_file = save_to_file # override user's path to path in header if !response['Content-Disposition'].nil? disposition = self.class.parse_header(response['Content-Disposition']) if disposition[:parameters].key?(:filename) target_file = File.join(File.dirname(target_file), disposition[:parameters][:filename]) end end # download with temp filename target_file_tmp = "#{target_file}#{RestParameters.instance.download_partial_suffix}" Log.log.debug{"saving to: #{target_file}"} written_size = 0 session_id = SecureRandom.uuid.freeze RestParameters.instance.&.event(:session_start, session_id: session_id) RestParameters.instance.&.event(:session_size, session_id: session_id, info: total_size) File.open(target_file_tmp, 'wb') do |file| result[:http].read_body do |fragment| file.write(fragment) written_size += fragment.length RestParameters.instance.&.event(:transfer, session_id: session_id, info: written_size) end end RestParameters.instance.&.event(:end, session_id: session_id) # rename at the end File.rename(target_file_tmp, target_file) file_saved = true end end Log.log.debug{"result: code=#{result[:http].code} mime=#{result_mime}"} # sometimes there is a UTF8 char (e.g. (c) ), TODO : related to mime type encoding ? # result[:http].body.force_encoding('UTF-8') if result[:http].body.is_a?(String) # Log.log.debug{"result: body=#{result[:http].body}"} case result_mime when *JSON_DECODE result[:data] = JSON.parse(result[:http].body) rescue result[:http].body Log.log.debug{Log.dump('result_data', result[:data])} else # when 'text/plain' result[:data] = result[:http].body end RestErrorAnalyzer.instance.raise_on_error(req, result) File.write(save_to_file, result[:http].body, binmode: true) unless file_saved || save_to_file.nil? rescue RestCallError => e do_retry = false # AoC have some timeout , like Connect to platform.bss.asperasoft.com:443 ... do_retry = true if e.response.body.include?('failed: connect timed out') && (timeout_tries -= 1).positive? # possibility to retry anything if it fails do_retry = true if (general_tries -= 1).positive? # not authorized: oauth token expired if @not_auth_codes.include?(result[:http].code.to_s) && @auth_params[:type].eql?(:oauth2) begin # try to use refresh token req['Authorization'] = oauth.(refresh: true) rescue RestCallError => e_tok e = e_tok Log.log.error('refresh failed'.bg_red) # regenerate a brand new token req['Authorization'] = oauth.(cache: false) end Log.log.debug{"using new token=#{headers['Authorization']}"} do_retry = true if (oauth_tries -= 1).positive? end if do_retry sleep(RestParameters.instance.retry_sleep) unless RestParameters.instance.retry_sleep.nil? retry end # redirect ? (any code beginning with 3) if e.response.is_a?(Net::HTTPRedirection) && tries_remain_redirect.positive? tries_remain_redirect -= 1 current_uri = URI.parse(@base_url) new_url = e.response['location'] # special case: relative redirect if URI.parse(new_url).host.nil? # we don't manage relative redirects with non-absolute path Aspera.assert(new_url.start_with?('/')){"redirect location is relative: #{new_url}, but does not start with /."} new_url = "#{current_uri.scheme}://#{current_uri.host}#{new_url}" end # forwards the request to the new location return self.class.new(base_url: new_url, redirect_max: tries_remain_redirect).call( operation: operation, query: query, body: body, body_type: body_type, save_to_file: save_to_file, return_error: return_error, headers: headers) end # raise exception if could not retry and not return error in result raise e unless return_error end Log.log.debug{"result=#{result}"} return result end |
#cancel(subpath) ⇒ Object
470 471 472 |
# File 'lib/aspera/rest.rb', line 470 def cancel(subpath) return call(operation: 'CANCEL', subpath: subpath, headers: {'Accept' => 'application/json'})[:data] end |
#create(subpath, params) ⇒ Object
CRUD simplified methods here If specific elements are needed, then use the full ‘call` method
454 455 456 |
# File 'lib/aspera/rest.rb', line 454 def create(subpath, params) return call(operation: 'POST', subpath: subpath, headers: {'Accept' => 'application/json'}, body: params, body_type: :json)[:data] end |
#delete(subpath, params = nil) ⇒ Object
466 467 468 |
# File 'lib/aspera/rest.rb', line 466 def delete(subpath, params=nil) return call(operation: 'DELETE', subpath: subpath, headers: {'Accept' => 'application/json'}, query: params)[:data] end |
#lookup_by_name(subpath, search_name, query: nil) ⇒ Object
Query entity by general search (read with parameter ‘q`) TODO: not generic enough ? move somewhere ? inheritance ?
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 |
# File 'lib/aspera/rest.rb', line 480 def lookup_by_name(subpath, search_name, query: nil) query = {} if query.nil? # returns entities matching the query (it matches against several fields in case insensitive way) matching_items = read(subpath, query.merge({'q' => search_name})) # API style: {totalcount:, ...} cspell: disable-line matching_items = matching_items[subpath] if matching_items.is_a?(Hash) Aspera.assert_type(matching_items, Array) case matching_items.length when 1 then return matching_items.first when 0 then raise %Q{#{ENTITY_NOT_FOUND} #{subpath}: "#{search_name}"} else # multiple case insensitive partial matches, try case insensitive full match # (anyway AoC does not allow creation of 2 entities with same case insensitive name) name_matches = matching_items.select{|i|i['name'].casecmp?(search_name)} case name_matches.length when 1 then return name_matches.first when 0 then raise %Q(#{subpath}: multiple case insensitive partial match for: "#{search_name}": #{matching_items.map{|i|i['name']}} but no case insensitive full match. Please be more specific or give exact name.) # rubocop:disable Layout/LineLength else raise "Two entities cannot have the same case insensitive name: #{name_matches.map{|i|i['name']}}" end end end |
#oauth ⇒ Object
Returns the OAuth object (create, or cached if already created).
249 250 251 252 253 254 255 256 257 |
# File 'lib/aspera/rest.rb', line 249 def oauth if @oauth.nil? Aspera.assert(@auth_params[:type].eql?(:oauth2)){'no OAuth defined'} oauth_parameters = @auth_params.reject { |k, _v| k.eql?(:type) } Log.log.debug{Log.dump('oauth parameters', oauth_parameters)} @oauth = OAuth::Factory.instance.create(**oauth_parameters) end return @oauth end |
#params ⇒ Object
Returns creation parameters.
194 195 196 197 198 199 200 201 202 |
# File 'lib/aspera/rest.rb', line 194 def params return { base_url: @base_url, # String auth: @auth_params, # Hash not_auth_codes: @not_auth_codes, # Array redirect_max: @redirect_max, # Integer headers: @headers # Hash } end |
#read(subpath, query = nil) ⇒ Object
458 459 460 |
# File 'lib/aspera/rest.rb', line 458 def read(subpath, query=nil) return call(operation: 'GET', subpath: subpath, headers: {'Accept' => 'application/json'}, query: query)[:data] end |
#update(subpath, params) ⇒ Object
462 463 464 |
# File 'lib/aspera/rest.rb', line 462 def update(subpath, params) return call(operation: 'PUT', subpath: subpath, headers: {'Accept' => 'application/json'}, body: params, body_type: :json)[:data] end |