Class: StatelyDB::Common::Auth::StatelyAccessTokenFetcher

Inherits:
TokenFetcher
  • Object
show all
Defined in:
lib/common/auth/token_fetcher.rb

Overview

StatelyAccessTokenFetcher is a TokenFetcher that fetches tokens from the StatelyDB API

Constant Summary collapse

NON_RETRYABLE_ERRORS =

Non-retryable errors that will not be retried.

Returns:

  • (Array<::GRPC::Core::StatusCodes>)
[
  GRPC::Core::StatusCodes::UNAUTHENTICATED,
  GRPC::Core::StatusCodes::PERMISSION_DENIED,
  GRPC::Core::StatusCodes::NOT_FOUND,
  GRPC::Core::StatusCodes::UNIMPLEMENTED,
  GRPC::Core::StatusCodes::INVALID_ARGUMENT
].freeze
RETRY_ATTEMPTS =

Number of retry attempts for requests.

Returns:

  • (Integer)
10

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(endpoint:, access_key:, base_retry_backoff_secs:) ⇒ StatelyAccessTokenFetcher

Returns a new instance of StatelyAccessTokenFetcher.

Parameters:

  • endpoint (String)

    The endpoint of the OAuth server

  • access_key (String)

    The StatelyDB access key credential

  • base_retry_backoff_secs (Float)

    The base backoff time in seconds



67
68
69
70
71
72
73
74
75
# File 'lib/common/auth/token_fetcher.rb', line 67

def initialize(endpoint:, access_key:, base_retry_backoff_secs:)
  super()
  @access_key = access_key
  @base_retry_backoff_secs = base_retry_backoff_secs
  @channel = Common::Net.new_channel(endpoint:)
  error_interceptor = Common::ErrorInterceptor.new
  @stub = Stately::Auth::AuthService::Stub.new(nil, nil, channel_override: @channel,
                                                         interceptors: [error_interceptor])
end

Class Method Details

.retryable_error?(err) ⇒ Boolean

Check if an error is retryable

Parameters:

Returns:

  • (Boolean)

    True if the error is retryable



101
102
103
# File 'lib/common/auth/token_fetcher.rb', line 101

def self.retryable_error?(err)
  !NON_RETRYABLE_ERRORS.include?(err.code)
end

Instance Method Details

#closevoid

This method returns an undefined value.

Close the token provider and kill any background operations



94
95
96
# File 'lib/common/auth/token_fetcher.rb', line 94

def close
  @channel&.close
end

#fetchStatelyDB::Common::Auth::TokenResult

Fetch a new token from the StatelyDB API

Returns:



79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/common/auth/token_fetcher.rb', line 79

def fetch
  RETRY_ATTEMPTS.times do |i|
    resp = @stub.get_auth_token(Stately::Auth::GetAuthTokenRequest.new(access_key: @access_key))
    return TokenResult.new(token: resp.auth_token, expires_in_secs: resp.expires_in_s)
  rescue StatelyDB::Error => e
    # raise if it's the final attempt or if the error is not retryable
    raise e unless self.class.retryable_error?(e) && i < RETRY_ATTEMPTS - 1

    # exponential backoff
    sleep(backoff(i, @base_retry_backoff_secs))
  end
end