Class: Aspera::Rest

Inherits:
Object
  • Object
show all
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

Api::AoC, Api::Ats, Api::Node

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
@@global =

global settings also valid for any subclass

{ # rubocop:disable Style/ClassVars
  user_agent:              'Ruby',          # goes to HTTP request header: 'User-Agent'
  download_partial_suffix: '.http_partial', # suffix for partial download
  session_cb:              nil,             # a lambda which takes the Net::HTTP as arg, use this to change parameters
  progress_bar:            nil # progress bar object
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_url:, auth: nil, not_auth_codes: nil, redirect_max: 0, headers: nil) ⇒ Rest



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
# File 'lib/aspera/rest.rb', line 221

def initialize(
  base_url:,
  auth: nil,
  not_auth_codes: nil,
  redirect_max: 0,
  headers: nil
)
  Aspera.assert_type(base_url, String)
  # base url with max one trailing slashes (note: string may be frozen)
  @base_url = base_url.gsub(%r{//+$}, '/')
  # default is no auth
  @auth_params = auth.nil? ? {type: :none} : auth
  Aspera.assert_type(@auth_params, Hash)
  Aspera.assert(@auth_params.key?(:type)){'no auth type defined'}
  @not_auth_codes = not_auth_codes.nil? ? ['401'] : not_auth_codes
  Aspera.assert_type(@not_auth_codes, Array)
  # persistent session
  @http_session = nil
  # OAuth object (created on demand)
  @oauth = nil
  @redirect_max = redirect_max
  @headers = headers.nil? ? {} : headers
  Aspera.assert_type(@headers, Hash)
  @headers['User-Agent'] ||= @@global[:user_agent]
end

Instance Attribute Details

#auth_paramsObject (readonly)

Returns the value of attribute auth_params.



199
200
201
# File 'lib/aspera/rest.rb', line 199

def auth_params
  @auth_params
end

#base_urlObject (readonly)

Returns the value of attribute base_url.



200
201
202
# File 'lib/aspera/rest.rb', line 200

def base_url
  @base_url
end

Class Method Details

.array_params(values) ⇒ Object

used to build a parameter list prefixed with “[]”



51
52
53
# File 'lib/aspera/rest.rb', line 51

def array_params(values)
  return [ARRAY_PARAMS].concat(values)
end

.array_params?(values) ⇒ Boolean



55
56
57
# File 'lib/aspera/rest.rb', line 55

def array_params?(values)
  return values.first.eql?(ARRAY_PARAMS)
end

.basic_token(user, pass) ⇒ Object



47
# File 'lib/aspera/rest.rb', line 47

def basic_token(user, pass); return "Basic #{Base64.strict_encode64("#{user}:#{pass}")}"; end

.build_uri(url, query_hash = nil) ⇒ Object

build URI from URL and parameters and check it is http or https, encode array [] parameters



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/aspera/rest.rb', line 60

def build_uri(url, query_hash=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_hash.nil?
  Log.log.debug{Log.dump('query', query_hash)}
  Aspera.assert_type(query_hash, Hash)
  return uri if query_hash.empty?
  query = []
  query_hash.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.push(["#{k}#{suffix}", e])
      end
    else
      query.push([k, v])
    end
  end
  # [] is allowed in url parameters
  uri.query = URI.encode_www_form(query).gsub('%5B%5D=', '[]=')
  return uri
end

.decode_query(query) ⇒ Object



85
86
87
# File 'lib/aspera/rest.rb', line 85

def decode_query(query)
  URI.decode_www_form(query).each_with_object({}){|v, h|h[v.first] = v.last }
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



107
108
109
110
111
112
113
# File 'lib/aspera/rest.rb', line 107

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

.remote_certificate_chain(url, as_string: true) ⇒ String



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/aspera/rest.rb', line 116

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

.set_parameters(**options) ⇒ Object

set global parameters



133
134
135
136
137
138
# File 'lib/aspera/rest.rb', line 133

def set_parameters(**options)
  options.each do |key, value|
    Aspera.assert(@@global.key?(key)){"Unknown Rest option #{key}"}
    @@global[key] = value
  end
end

.start_http_session(base_url) ⇒ Net::HTTP

Start a HTTP/S session, also used for web sockets



92
93
94
95
96
97
98
99
100
101
102
# File 'lib/aspera/rest.rb', line 92

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
  @@global[: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

.user_agentString



141
142
143
# File 'lib/aspera/rest.rb', line 141

def user_agent
  return @@global[:user_agent]
end

Instance Method Details

#call(operation:, subpath: nil, json_params: nil, url_params: nil, www_body_params: nil, text_body_params: nil, save_to_file: nil, return_error: false, headers: nil) ⇒ Object

HTTP/S REST call



266
267
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
# File 'lib/aspera/rest.rb', line 266

def call(
  operation:,
  subpath: nil,
  json_params: nil,
  url_params: nil,
  www_body_params: nil,
  text_body_params: nil,
  save_to_file: nil,
  return_error: false,
  headers: nil
)
  subpath = subpath.to_s if subpath.is_a?(Symbol)
  subpath = '' if subpath.nil?
  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)
  Log.log.debug{"#{operation} [#{subpath}]".red.bold.bg_green}
  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_token unless headers.key?('Authorization')
  when :url
    url_params ||= {}
    @auth_params[:url_query].each do |key, value|
      url_params[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
  begin
    req = build_request(
      operation: operation, subpath: subpath, json_params: json_params, url_params: url_params, www_body_params: www_body_params,
      text_body_params: text_body_params, headers: headers)
    # 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
    # initialize with number of initial retries allowed, nil gives zero
    tries_remain_redirect = @redirect_max.to_i 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 = (result[:http]['Content-Type'] || 'text/plain').split(';').first.downcase
      # 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? && (m = response['Content-Disposition'].match(/filename="([^"]+)"/))
          target_file = File.join(File.dirname(target_file), m[1])
        end
        # download with temp filename
        target_file_tmp = "#{target_file}#{@@global[:download_partial_suffix]}"
        Log.log.debug{"saving to: #{target_file}"}
        written_size = 0
        @@global[:progress_bar]&.event(session_id: 1, type: :session_start)
        @@global[:progress_bar]&.event(session_id: 1, type: :session_size, info: total_size)
        File.open(target_file_tmp, 'wb') do |file|
          result[:http].read_body do |fragment|
            file.write(fragment)
            written_size += fragment.length
            @@global[:progress_bar]&.event(session_id: 1, type: :transfer, info: written_size)
          end
        end
        @@global[:progress_bar]&.event(session_id: 1, type: :end)
        # rename at the end
        File.rename(target_file_tmp, target_file)
        file_saved = true
      end # save_to_file
    end
    # 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}"}
    result[:data] = case result_mime
    when *JSON_DECODE
      JSON.parse(result[:http].body) rescue result[:http].body
    else # when 'text/plain'
      result[:http].body
    end
    Log.log.debug{"result: code=#{result[:http].code} mime=#{result_mime}"}
    Log.log.debug{Log.dump('data', result[:data])}
    RestErrorAnalyzer.instance.raise_on_error(req, result)
    File.write(save_to_file, result[:http].body) unless file_saved || save_to_file.nil?
  rescue RestCallError => e
    # 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_token(force_refresh: true)
      rescue RestCallError => e_tok
        e = e_tok
        Log.log.error('refresh failed'.bg_red)
        # regenerate a brand new token
        req['Authorization'] = oauth_token(force_refresh: true)
      end
      Log.log.debug{"using new token=#{headers['Authorization']}"}
      retry if (oauth_tries -= 1).nonzero?
    end # if oauth
    # 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, json_params: json_params,
        url_params: url_params, www_body_params: www_body_params, text_body_params: text_body_params,
        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 # begin request
  Log.log.debug{"result=#{result}"}
  return result
end

#cancel(subpath) ⇒ Object



425
426
427
# File 'lib/aspera/rest.rb', line 425

def cancel(subpath)
  return call(operation: 'CANCEL', subpath: subpath, headers: {'Accept' => 'application/json'})
end

#create(subpath, params, encoding = :json_params) ⇒ Object



409
410
411
# File 'lib/aspera/rest.rb', line 409

def create(subpath, params, encoding=:json_params)
  return call(operation: 'POST', subpath: subpath, headers: {'Accept' => 'application/json'}, encoding => params)
end

#delete(subpath, params = nil) ⇒ Object



421
422
423
# File 'lib/aspera/rest.rb', line 421

def delete(subpath, params=nil)
  return call(operation: 'DELETE', subpath: subpath, headers: {'Accept' => 'application/json'}, url_params: params)
end

#lookup_by_name(subpath, search_name, query = {}) ⇒ Object

Query entity by general search (read with parameter q) TODO: not generic enough ? move somewhere ? inheritance ?



435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
# File 'lib/aspera/rest.rb', line 435

def lookup_by_name(subpath, search_name, query={})
  # returns entities matching the query (it matches against several fields in case insensitive way)
  matching_items = read(subpath, query.merge({'q' => search_name}))[:data]
  # 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

#oauthObject



248
249
250
251
252
253
254
255
256
# File 'lib/aspera/rest.rb', line 248

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

#oauth_token(force_refresh: false) ⇒ Object



258
259
260
261
# File 'lib/aspera/rest.rb', line 258

def oauth_token(force_refresh: false)
  Aspera.assert_values(force_refresh, [true, false])
  return oauth.get_authorization(use_refresh_token: force_refresh)
end

#paramsObject



202
203
204
205
206
207
208
209
210
# File 'lib/aspera/rest.rb', line 202

def params
  return {
    base_url:       @base_url,
    auth:           @auth_params,
    not_auth_codes: @not_auth_codes,
    redirect_max:   @redirect_max,
    headers:        @headers
  }
end

#read(subpath, query = nil) ⇒ Object



413
414
415
# File 'lib/aspera/rest.rb', line 413

def read(subpath, query=nil)
  return call(operation: 'GET', subpath: subpath, headers: {'Accept' => 'application/json'}, url_params: query)
end

#update(subpath, params) ⇒ Object



417
418
419
# File 'lib/aspera/rest.rb', line 417

def update(subpath, params)
  return call(operation: 'PUT', subpath: subpath, headers: {'Accept' => 'application/json'}, json_params: params)
end