Sha256: c4a8cfdd01cd4f3044d5f3ffbe200c7e75fb070186e08033a5e034f6c7946065

Contents?: true

Size: 1.59 KB

Versions: 6

Compression:

Stored size: 1.59 KB

Contents

# frozen_string_literal: true

require 'thread'

module Aws

  # Base class used credential classes that can be refreshed. This
  # provides basic refresh logic in a thread-safe manner. Classes mixing in
  # this module are expected to implement a #refresh method that populates
  # the following instance variables:
  #
  # * `@access_key_id`
  # * `@secret_access_key`
  # * `@session_token`
  # * `@expiration`
  #
  # @api private
  module RefreshingCredentials

    def initialize(options = {})
      @mutex = Mutex.new
      @before_refresh = options.delete(:before_refresh) if Hash === options

      @before_refresh.call(self) if @before_refresh
      refresh
    end

    # @return [Credentials]
    def credentials
      refresh_if_near_expiration
      @credentials
    end

    # @return [Time,nil]
    def expiration
      refresh_if_near_expiration
      @expiration
    end

    # Refresh credentials.
    # @return [void]
    def refresh!
      @mutex.synchronize do
        @before_refresh.call(self) if @before_refresh

        refresh
      end
    end

    private

    # Refreshes instance metadata credentials if they are within
    # 5 minutes of expiration.
    def refresh_if_near_expiration
      if near_expiration?
        @mutex.synchronize do
          if near_expiration?
            @before_refresh.call(self) if @before_refresh

            refresh
          end
        end
      end
    end

    def near_expiration?
      if @expiration
        # are we within 5 minutes of expiration?
        (Time.now.to_i + 5 * 60) > @expiration.to_i
      else
        true
      end
    end

  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
aws-sdk-core-3.129.1 lib/aws-sdk-core/refreshing_credentials.rb
aws-sdk-core-3.129.0 lib/aws-sdk-core/refreshing_credentials.rb
aws-sdk-core-3.128.1 lib/aws-sdk-core/refreshing_credentials.rb
aws-sdk-core-3.128.0 lib/aws-sdk-core/refreshing_credentials.rb
aws-sdk-core-3.127.0 lib/aws-sdk-core/refreshing_credentials.rb
aws-sdk-core-3.126.2 lib/aws-sdk-core/refreshing_credentials.rb