1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
# 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
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 { refresh }
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
refresh if near_expiration?
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
|