Class: Google::Cloud::Core::GrpcBackoff

Inherits:
Object
  • Object
show all
Defined in:
lib/google/cloud/core/backoff.rb,
lib/google/cloud/core/grpc_backoff.rb

Overview

Backoff allows users to control how Google API calls are retried. If an API call fails the response will be checked to see if the call can be retried. If the response matches the criteria, then it will be retried with an incremental backoff. This means that an increasing delay will be added between each retried call. The first retry will be delayed one second, the second retry will be delayed two seconds, and so on.

Class Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ GrpcBackoff

Creates a new Backoff object to catch common errors when calling the Google API and handle the error by retrying the call.

Google::Cloud::Core::GrpcBackoff.new(options).execute do
  datastore.lookup lookup_ref
end


66
67
68
69
70
# File 'lib/google/cloud/core/backoff.rb', line 66

def initialize options = {}
  @retries    = (options[:retries]    || GrpcBackoff.retries).to_i
  @grpc_codes = (options[:grpc_codes] || GrpcBackoff.grpc_codes).to_a
  @backoff    =  options[:backoff]    || GrpcBackoff.backoff
end

Class Attribute Details

.backoffObject

The code to run when a backoff is handled. This must be a Proc and must take the number of retries as an argument.

Note: This method is undocumented and may change.



51
52
53
# File 'lib/google/cloud/core/backoff.rb', line 51

def backoff
  @backoff
end

.grpc_codesObject

The GRPC Status Codes that should be retried.

The default values are ‘14`.



43
44
45
# File 'lib/google/cloud/core/backoff.rb', line 43

def grpc_codes
  @grpc_codes
end

.retriesObject

The number of times a retriable API call should be retried.

The default value is ‘3`.



34
35
36
# File 'lib/google/cloud/core/backoff.rb', line 34

def retries
  @retries
end

Instance Method Details

#executeObject



73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/google/cloud/core/backoff.rb', line 73

def execute
  current_retries = 0
  loop do
    begin
      return yield
    rescue GRPC::BadStatus => e
      raise e unless @grpc_codes.include?(e.code) &&
                     (current_retries < @retries)
      current_retries += 1
      @backoff.call current_retries
    end
  end
end