Class: Google::Apis::Core::HttpCommand

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/google/apis/core/http_command.rb

Overview

Command for HTTP request/response.

Direct Known Subclasses

ApiCommand, BatchCommand

Defined Under Namespace

Modules: RedactingPPMethods Classes: RedactingPP, RedactingSingleLine

Constant Summary collapse

RETRIABLE_ERRORS =
[Google::Apis::ServerError,
Google::Apis::RateLimitError,
Google::Apis::TransmissionError,
Google::Apis::RequestTimeOutError]

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Logging

#logger

Constructor Details

#initialize(method, url, body: nil) ⇒ HttpCommand

Returns a new instance of HttpCommand.

Parameters:

  • method (symbol)

    HTTP method

  • url (String, Addressable::URI, Addressable::Template)

    HTTP URL or template

  • body (String, #read) (defaults to: nil)

    Request body



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/google/apis/core/http_command.rb', line 81

def initialize(method, url, body: nil)
  self.options = Google::Apis::RequestOptions.default.dup
  self.url = url
  self.url = Addressable::Template.new(url) if url.is_a?(String)
  self.method = method
  self.header = Hash.new
  self.body = body
  self.query = {}
  self.params = {}
  @opencensus_span = nil
  if OPENCENSUS_AVAILABLE
    logger.warn  'OpenCensus support is now deprecated. ' +
                 'Please refer https://github.com/googleapis/google-api-ruby-client#tracing for migrating to use OpenTelemetry.' 
    
  end
end

Instance Attribute Details

#body#read

Request body

Returns:

  • (#read)


57
58
59
# File 'lib/google/apis/core/http_command.rb', line 57

def body
  @body
end

#connectionFaraday::Connection

Faraday connection

Returns:

  • (Faraday::Connection)


65
66
67
# File 'lib/google/apis/core/http_command.rb', line 65

def connection
  @connection
end

#headerHash

HTTP headers

Returns:

  • (Hash)


53
54
55
# File 'lib/google/apis/core/http_command.rb', line 53

def header
  @header
end

#methodsymbol

HTTP method

Returns:

  • (symbol)


61
62
63
# File 'lib/google/apis/core/http_command.rb', line 61

def method
  @method
end

#optionsGoogle::Apis::RequestOptions

Request options



45
46
47
# File 'lib/google/apis/core/http_command.rb', line 45

def options
  @options
end

#paramsHash

Path params for URL Template

Returns:

  • (Hash)


73
74
75
# File 'lib/google/apis/core/http_command.rb', line 73

def params
  @params
end

#queryHash

Query params

Returns:

  • (Hash)


69
70
71
# File 'lib/google/apis/core/http_command.rb', line 69

def query
  @query
end

#urlString, Addressable::URI

HTTP request URL

Returns:

  • (String, Addressable::URI)


49
50
51
# File 'lib/google/apis/core/http_command.rb', line 49

def url
  @url
end

Instance Method Details

#allow_form_encoding?Boolean

Returns:

  • (Boolean)


345
346
347
# File 'lib/google/apis/core/http_command.rb', line 345

def allow_form_encoding?
  [:post, :put].include?(method) && body.nil?
end

#apply_request_options(req_header)

This method returns an undefined value.

Update the request with any specified options.

Parameters:

  • req_header (Hash)

    HTTP headers



336
337
338
339
340
341
342
343
# File 'lib/google/apis/core/http_command.rb', line 336

def apply_request_options(req_header)
  if options.authorization.respond_to?(:apply!)
    options.authorization.apply!(req_header)
  elsif options.authorization.is_a?(String)
    req_header['Authorization'] = sprintf('Bearer %s', options.authorization)
  end
  req_header.update(header)
end

#authorization_refreshable?Boolean

Check if attached credentials can be automatically refreshed

Returns:

  • (Boolean)


159
160
161
# File 'lib/google/apis/core/http_command.rb', line 159

def authorization_refreshable?
  options.authorization.respond_to?(:apply!)
end

#check_status(status, header = nil, body = nil, message = nil)

This method returns an undefined value.

Check the response and raise error if needed

Parameters:

  • status (Fixnum)

    HTTP status code of response

  • header (Hash) (defaults to: nil)

    HTTP response headers

  • body (String) (defaults to: nil)

    HTTP response body

  • message (String) (defaults to: nil)

    Error message text

Raises:



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/google/apis/core/http_command.rb', line 229

def check_status(status, header = nil, body = nil, message = nil)
  # TODO: 304 Not Modified depends on context...
  case status
  when 200...300, 308
    nil
  when 301, 302, 303, 307
    message ||= sprintf('Redirect to %s', header['Location'])
    raise Google::Apis::RedirectError.new(message, status_code: status, header: header, body: body)
  when 401
    message ||= 'Unauthorized'
    raise Google::Apis::AuthorizationError.new(message, status_code: status, header: header, body: body)
  when 429
    message ||= 'Rate limit exceeded'
    raise Google::Apis::RateLimitError.new(message, status_code: status, header: header, body: body)
  when 408
    message ||= 'Request time out'
    raise Google::Apis::RequestTimeOutError.new(message, status_code: status, header: header, body: body)
  when 304, 400, 402...500
    message ||= 'Invalid request'
    raise Google::Apis::ClientError.new(message, status_code: status, header: header, body: body)
  when 500...600
    message ||= 'Server error'
    raise Google::Apis::ServerError.new(message, status_code: status, header: header, body: body)
  else
    logger.warn(sprintf('Encountered unexpected status code %s', status))
    message ||= 'Unknown error'
    raise Google::Apis::TransmissionError.new(message, status_code: status, header: header, body: body)
  end
end

#decode_response_body(_content_type, body) ⇒ Object

Process the actual response body. Intended to be overridden by subclasses

Parameters:

  • _content_type (String)

    Content type of body

  • body (String, #read)

    Response body

Returns:

  • (Object)


266
267
268
# File 'lib/google/apis/core/http_command.rb', line 266

def decode_response_body(_content_type, body)
  body
end

#do_retry(func, client) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/google/apis/core/http_command.rb', line 117

def do_retry func, client
  begin
    Retriable.retriable tries: options.retries + 1,
                        max_elapsed_time: options.max_elapsed_time,
                        base_interval: options.base_interval,
                        max_interval: options.max_interval,
                        multiplier: options.multiplier,
                        on: RETRIABLE_ERRORS do |try|
      # This 2nd level retriable only catches auth errors, and supports 1 retry, which allows
      # auth to be re-attempted without having to retry all sorts of other failures like
      # NotFound, etc
      auth_tries = (try == 1 && authorization_refreshable? ? 2 : 1)
      Retriable.retriable tries: auth_tries,
                          on: [Google::Apis::AuthorizationError, Signet::AuthorizationError, Signet::RemoteServerError, Signet::UnexpectedStatusError],
                          on_retry: proc { |*| refresh_authorization } do
        send(func, client).tap do |result|
          if block_given?
            yield result, nil
          end
        end
      end
    end
  rescue => e
    if block_given?
      yield nil, e
    else
      raise e
    end
  end
end

#error(err, rethrow: false) {|nil, err| ... }

This method returns an undefined value.

Process an error response

Parameters:

  • err (StandardError)

    Error object

  • rethrow (Boolean) (defaults to: false)

    True if error should be raised again after handling

Yields:

  • (nil, err)

    if block given

Raises:

  • (StandardError)

    if no block



289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/google/apis/core/http_command.rb', line 289

def error(err, rethrow: false, &block)
  logger.debug { sprintf('Error - %s', PP.pp(err, +'')) }
  if err.is_a?(Faraday::FollowRedirects::RedirectLimitReached)
    err = Google::Apis::RedirectError.new(err)
  elsif err.is_a?(Faraday::Error) ||
        err.is_a?(SocketError) ||
        err.is_a?(Errno::ECONNREFUSED) ||
        err.is_a?(Errno::ETIMEDOUT) ||
        err.is_a?(Errno::ECONNRESET)
    err = Google::Apis::TransmissionError.new(err)
  end
  block.call(nil, err) if block_given?
  fail err if rethrow || block.nil?
end

#execute(client) {|result, err| ... } ⇒ Object

Execute the command, retrying as necessary

Parameters:

  • client (Faraday::Connection)

    Faraday connection

Yields:

  • (result, err)

    Result or error if block supplied

Returns:

  • (Object)

Raises:



107
108
109
110
111
112
113
114
115
# File 'lib/google/apis/core/http_command.rb', line 107

def execute(client, &block)
  prepare!
  opencensus_begin_span
  do_retry :execute_once, client, &block
ensure
  opencensus_end_span
  @http_res = nil
  release!
end

#process_response(status, header, body) ⇒ Object

Check the response and either decode body or raise error

Parameters:

  • status (Fixnum)

    HTTP status code of response

  • header (Hash)

    Response headers

  • body (String, #read)

    Response body

Returns:

  • (Object)

    Response object

Raises:



210
211
212
213
# File 'lib/google/apis/core/http_command.rb', line 210

def process_response(status, header, body)
  check_status(status, header, body)
  decode_response_body(Array(header['Content-Type']).first, body)
end

#set_api_version_header(api_version)

This method returns an undefined value.

Set the API version header for the service if not empty.



351
352
353
# File 'lib/google/apis/core/http_command.rb', line 351

def set_api_version_header api_version
  self.header['X-Goog-Api-Version'] = api_version unless api_version.empty?
end

#success(result) {|result, nil| ... } ⇒ Object

Process a success response

Parameters:

  • result (Object)

    Result object

Yields:

  • (result, nil)

    if block given

Returns:

  • (Object)

    result if no block given



275
276
277
278
279
# File 'lib/google/apis/core/http_command.rb', line 275

def success(result, &block)
  logger.debug { sprintf('Success - %s', safe_pretty_representation(result)) }
  block.call(result, nil) if block_given?
  result
end