class Google::Apis::Core::BaseService

Base service for all APIs. Not to be used directly.

Constants

ENDPOINT_SUBSTITUTION

A substitution string for the universe domain in an endpoint template @return [String]

Attributes

base_path[RW]

Additional path prefix for all API methods @return [Addressable::URI]

batch_path[RW]

Alternate path prefix for all batch methods @return [Addressable::URI]

client[RW]

HTTP client @return [HTTPClient]

client_name[RW]

Client library name. @return [String]

client_options[RW]

General settings @return [Google::Apis::ClientOptions]

client_version[RW]

Client library version. @return [String]

request_options[RW]

Default options for all requests @return [Google::Apis::RequestOptions]

root_url[R]

Root URL (host/port) for the API @return [Addressable::URI, String]

universe_domain[R]

Universe domain @return [String]

upload_path[RW]

Alternate path prefix for media uploads @return [Addressable::URI]

Public Class Methods

new(root_url, base_path, client_name: nil, client_version: nil, universe_domain: nil) click to toggle source

@param [String,Addressable::URI] root_url

Root URL for the API

@param [String,Addressable::URI] base_path

Additional path prefix for all API methods

@api private

# File lib/google/apis/core/base_service.rb, line 177
def initialize(root_url, base_path, client_name: nil, client_version: nil, universe_domain: nil)
  @root_url_template = nil
  self.universe_domain = universe_domain
  self.root_url = root_url
  self.base_path = base_path
  self.client_name = client_name || 'google-api-ruby-client'
  self.client_version = client_version || Google::Apis::Core::VERSION
  self.upload_path = "upload/#{base_path}"
  self.batch_path = 'batch'
  self.client_options = Google::Apis::ClientOptions.default.dup
  self.request_options = Google::Apis::RequestOptions.default.dup
end

Public Instance Methods

authorization() click to toggle source
# File lib/google/apis/core/base_service.rb, line 197
def authorization
  request_options.authorization
end
authorization=(authorization) click to toggle source

@!attribute [rw] authorization @return [Signet::OAuth2::Client]

OAuth2 credentials
# File lib/google/apis/core/base_service.rb, line 193
def authorization=(authorization)
  request_options.authorization = authorization
end
batch(options = nil) { |self| ... } click to toggle source

Perform a batch request. Calls made within the block are sent in a single network request to the server.

@example

service.batch do |s|
  s.get_item(id1) do |res, err|
    # process response for 1st call
  end
  # ...
  s.get_item(idN) do |res, err|
    # process response for Nth call
  end
end

@param [Hash, Google::Apis::RequestOptions] options

Request-specific options

@yield [self] @return [void]

# File lib/google/apis/core/base_service.rb, line 221
def batch(options = nil)
  batch_command = BatchCommand.new(:post, Addressable::URI.parse(root_url + batch_path))
  batch_command.options = request_options.merge(options)
  apply_command_defaults(batch_command)
  begin
    start_batch(batch_command)
    yield self
  ensure
    end_batch
  end
  batch_command.execute(client)
end
batch_upload(options = nil) { |self| ... } click to toggle source

Perform a batch upload request. Calls made within the block are sent in a single network request to the server. Batch uploads are useful for uploading multiple small files. For larger files, use single requests which use a resumable upload protocol.

@example

service.batch do |s|
  s.insert_item(upload_source: 'file1.txt') do |res, err|
    # process response for 1st call
  end
  # ...
  s.insert_item(upload_source: 'fileN.txt') do |res, err|
    # process response for Nth call
  end
end

@param [Hash, Google::Apis::RequestOptions] options

Request-specific options

@yield [self] @return [void]

# File lib/google/apis/core/base_service.rb, line 253
def batch_upload(options = nil)
  batch_command = BatchUploadCommand.new(:put, Addressable::URI.parse(root_url + upload_path))
  batch_command.options = request_options.merge(options)
  apply_command_defaults(batch_command)
  begin
    start_batch(batch_command)
    yield self
  ensure
    end_batch
  end
  batch_command.execute(client)
end
fetch_all(max: nil, items: :items, cache: true, response_page_token: :next_page_token, &block) click to toggle source

Executes a given query with paging, automatically retrieving additional pages as necessary. Requires a block that returns the result set of a page. The current page token is supplied as an argument to the block.

Note: The returned enumerable also contains a ‘last_result` field containing the full result of the last query executed.

@param [Fixnum] max

Maximum number of items to iterate over. Defaults to nil -- no upper bound.

@param [Symbol] items

Name of the field in the result containing the items. Defaults to :items

@param [Boolean] cache

True (default) if results should be cached so multiple iterations can be used.

@return [Enumerable] @yield [token, service]

Current page token & service instance

@yieldparam [String] token

Current page token to be used in the query

@yieldparam [service]

Current service instance

@since 0.9.4

@example Retrieve all files,

file_list = service.fetch_all { |token, s| s.list_files(page_token: token) }
file_list.each { |f| ... }
# File lib/google/apis/core/base_service.rb, line 334
def fetch_all(max: nil, items: :items, cache: true, response_page_token: :next_page_token, &block)
  fail "fetch_all may not be used inside a batch" if batch?
  return PagedResults.new(self, max: max, items: items, cache: cache, response_page_token: response_page_token, &block)
end
http(method, url, params: nil, body: nil, download_dest: nil, options: nil, &block) click to toggle source

Simple escape hatch for making API requests directly to a given URL. This is not intended to be used as a generic HTTP client and should be used only in cases where no service method exists (e.g. fetching an export link for a Google Drive file.)

@param [Symbol] method

HTTP method as symbol (e.g. :get, :post, :put, ...)

@param [String] url

URL to call

@param [Hash<String,String>] params

Optional hash of query parameters

@param [#read] body

Optional body for POST/PUT

@param [IO, String] download_dest

IO stream or filename to receive content download

@param [Google::Apis::RequestOptions] options

Request-specific options

@yield [result, err] Result & error if block supplied @yieldparam result [String] HTTP response body @yieldparam err [StandardError] error object if request failed

@return [String] HTTP response body

# File lib/google/apis/core/base_service.rb, line 296
def http(method, url, params: nil, body: nil, download_dest: nil, options: nil, &block)
  if download_dest
    command = DownloadCommand.new(method, url, body: body, client_version: client_version)
  else
    command = HttpCommand.new(method, url, body: body)
  end
  command.options = request_options.merge(options)
  apply_command_defaults(command)
  command.query.merge(Hash(params))
  execute_or_queue_command(command, &block)
end
root_url=(url_or_template) click to toggle source

Set the root URL. If the given url includes a universe domain substitution, it is resolved in the current universe domain

@param url_or_template [Addressable::URI, String] The URL, which can include a universe domain substitution

# File lib/google/apis/core/base_service.rb, line 130
def root_url= url_or_template
  if url_or_template.is_a?(String) && url_or_template.include?(ENDPOINT_SUBSTITUTION)
    @root_url_template = url_or_template
    @root_url = url_or_template.gsub ENDPOINT_SUBSTITUTION, universe_domain
  else
    @root_url_template = nil
    @root_url = url_or_template
  end
end
universe_domain=(new_ud) click to toggle source

Set the universe domain. If the root URL was set with a universe domain substitution, it is updated to reflect the new universe domain.

@param new_ud [String,nil] The new universe domain, or nil to use the Google Default Universe

# File lib/google/apis/core/base_service.rb, line 113
def universe_domain= new_ud
  new_ud ||= ENV["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] || "googleapis.com"
  if @root_url_template
    @root_url = @root_url_template.gsub ENDPOINT_SUBSTITUTION, new_ud
  end
  @universe_domain = new_ud
end
verify_universe_domain!() click to toggle source

Verify that the universe domain setting matches the universe domain in the credentials, if present.

@raise [Google::Apis::UniverseDomainError] if there is a mismatch

# File lib/google/apis/core/base_service.rb, line 343
def verify_universe_domain!
  auth = authorization
  auth_universe_domain = auth.universe_domain if auth.respond_to? :universe_domain
  if auth_universe_domain && auth_universe_domain != universe_domain
    raise UniverseDomainError,
          "Universe domain is #{universe_domain} but credentials are in #{auth_universe_domain}"
  end
  true
end

Protected Instance Methods

apply_command_defaults(_command) click to toggle source

Update commands with service-specific options. To be implemented by subclasses @param [Google::Apis::Core::HttpCommand] _command

# File lib/google/apis/core/base_service.rb, line 483
def apply_command_defaults(_command)
end
execute_or_queue_command(command, &callback) click to toggle source

Execute the request. If a batch is in progress, the request is added to the batch instead.

@param [Google::Apis::Core::HttpCommand] command

Command to execute

@return [Object] response object if command executed and no callback supplied @yield [result, err] Result & error if block supplied @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification @raise [Google::Apis::AuthorizationError] Authorization is required

# File lib/google/apis/core/base_service.rb, line 470
def execute_or_queue_command(command, &callback)
  batch_command = current_batch
  if batch_command
    fail "Can not combine services in a batch" if Thread.current[:google_api_batch_service] != self
    batch_command.add(command, &callback)
    nil
  else
    command.execute(client, &callback)
  end
end
make_download_command(method, path, options) click to toggle source

Create a new download command.

@param [symbol] method

HTTP method for uploading (typically :get)

@param [String] path

Additional path to download endpoint, appended to API base path

@param [Hash, Google::Apis::RequestOptions] options

Request-specific options

@return [Google::Apis::Core::DownloadCommand]

# File lib/google/apis/core/base_service.rb, line 407
def make_download_command(method, path, options)
  verify_universe_domain!
  template = Addressable::Template.new(root_url + base_path + path)
  command = DownloadCommand.new(method, template, client_version: client_version)
  command.options = request_options.merge(options)
  command.query['alt'] = 'media'
  apply_command_defaults(command)
  command
end
make_simple_command(method, path, options) click to toggle source

Create a new command.

@param [symbol] method

HTTP method (:get, :post, :delete, etc...)

@param [String] path

Additional path, appended to API base path

@param [Hash, Google::Apis::RequestOptions] options

Request-specific options

@return [Google::Apis::Core::DownloadCommand]

# File lib/google/apis/core/base_service.rb, line 446
def make_simple_command(method, path, options)
  verify_universe_domain!
  full_path =
    if path.start_with? "/"
      path[1..-1]
    else
      base_path + path
    end
  template = Addressable::Template.new(root_url + full_path)
  command = ApiCommand.new(method, template, client_version: client_version)
  command.options = request_options.merge(options)
  apply_command_defaults(command)
  command
end
make_storage_download_command(method, path, options) click to toggle source

Create a new storage download command. This is specifically for storage because we want to return response header too in the response.

@param [symbol] method

HTTP method for uploading (typically :get)

@param [String] path

Additional path to download endpoint, appended to API base path

@param [Hash, Google::Apis::RequestOptions] options

Request-specific options

@return [Google::Apis::Core::StorageDownloadCommand]

# File lib/google/apis/core/base_service.rb, line 427
def make_storage_download_command(method, path, options)
  verify_universe_domain!
  template = Addressable::Template.new(root_url + base_path + path)
  command = StorageDownloadCommand.new(method, template, client_version: client_version)
  command.options = request_options.merge(options)
  command.query['alt'] = 'media'
  apply_command_defaults(command)
  command
end
make_storage_upload_command(method, path, options) click to toggle source

Create a new storage upload command. This is specifically for storage because we are moving to a new upload protocol. Ref: cloud.google.com/storage/docs/performing-resumable-uploads

@param [Symbol] method

HTTP method for uploading. The initial request to initiate a resumable session
is :post and the subsequent chunks uploaded to the session are :put

@param [String] path

Additional path to upload endpoint, appended to API base path

@param [Hash, Google::Apis::RequestOptions] options

Request-specific options

@return [Google::Apis::Core::StorageUploadCommand]

# File lib/google/apis/core/base_service.rb, line 389
def make_storage_upload_command(method, path, options)
  verify_universe_domain!
  template = Addressable::Template.new(root_url + upload_path + path)
  command = StorageUploadCommand.new(method, template, client_version: client_version)
  command.options = request_options.merge(options)
  apply_command_defaults(command)
  command
end
make_upload_command(method, path, options) click to toggle source

Create a new upload command.

@param [symbol] method

HTTP method for uploading (typically :put or :post)

@param [String] path

Additional path to upload endpoint, appended to API base path

@param [Hash, Google::Apis::RequestOptions] options

Request-specific options

@return [Google::Apis::Core::UploadCommand]

# File lib/google/apis/core/base_service.rb, line 364
def make_upload_command(method, path, options)
  verify_universe_domain!
  template = Addressable::Template.new(root_url + upload_path + path)
  if batch?
    command = MultipartUploadCommand.new(method, template, client_version: client_version)
  else
    command = ResumableUploadCommand.new(method, template, client_version: client_version)
  end
  command.options = request_options.merge(options)
  apply_command_defaults(command)
  command
end

Private Instance Methods

batch?() click to toggle source

Check if a batch is in progress @return [Boolean]

# File lib/google/apis/core/base_service.rb, line 497
def batch?
  !current_batch.nil?
end
current_batch() click to toggle source

Get the current batch context

@return [Google:Apis::Core::BatchRequest]

# File lib/google/apis/core/base_service.rb, line 491
def current_batch
  Thread.current[:google_api_batch]
end
end_batch() click to toggle source

Clear thread-local batch context

# File lib/google/apis/core/base_service.rb, line 510
def end_batch
  Thread.current[:google_api_batch] = nil
  Thread.current[:google_api_batch_service] = nil
end
new_client() click to toggle source

Create a new HTTP client @return [HTTPClient]

# File lib/google/apis/core/base_service.rb, line 517
def new_client
  client = ::HTTPClient.new

  if client_options.transparent_gzip_decompression
    client.transparent_gzip_decompression = client_options.transparent_gzip_decompression
  end
  
  client.proxy = client_options.proxy_url if client_options.proxy_url

  if client_options.open_timeout_sec
    client.connect_timeout = client_options.open_timeout_sec
  end

  if client_options.read_timeout_sec
    client.receive_timeout = client_options.read_timeout_sec
  end

  if client_options.send_timeout_sec
    client.send_timeout = client_options.send_timeout_sec
  end

  client.follow_redirect_count = 5
  client.default_header = { 'User-Agent' => user_agent }

  client.debug_dev = logger if client_options.log_http_requests

  # Make HttpClient use system default root CA path
  # https://github.com/nahi/httpclient/issues/445
  client.ssl_config.clear_cert_store
  client.ssl_config.cert_store.set_default_paths
  client
end
start_batch(cmd) click to toggle source

Start a new thread-local batch context @param [Google::Apis::Core::BatchCommand] cmd

# File lib/google/apis/core/base_service.rb, line 503
def start_batch(cmd)
  fail "Batch already in progress" if batch?
  Thread.current[:google_api_batch] = cmd
  Thread.current[:google_api_batch_service] = self
end
user_agent() click to toggle source

Build the user agent header @return [String]

# File lib/google/apis/core/base_service.rb, line 553
def user_agent
  sprintf('%s/%s %s/%s %s (gzip)',
          client_options.application_name,
          client_options.application_version,
          client_name,
          client_version,
          Google::Apis::OS_VERSION)
end