Skip to content

Commit

Permalink
Feat: support ecs ramrole (#292)
Browse files Browse the repository at this point in the history
feat: refine credentials, add ecs ram role
  • Loading branch information
crimson-gao authored Sep 5, 2024
1 parent 0bbc541 commit c24f68d
Show file tree
Hide file tree
Showing 5 changed files with 268 additions and 284 deletions.
53 changes: 12 additions & 41 deletions credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,60 +10,31 @@ type Credentials struct {
SecurityToken string
}

const DEFAULT_EXPIRED_FACTOR = 0.8

// Expirable credentials with an expiration.
type TempCredentials struct {
type tempCredentials struct {
Credentials
expiredFactor float64
expirationInMills int64 // The time when the credentials expires, unix timestamp in millis
lastUpdatedInMills int64
Expiration time.Time // The time when the credentials expires, unix timestamp in millis
LastUpdateTime time.Time
}

func NewTempCredentials(accessKeyId, accessKeySecret, securityToken string,
expirationInMills, lastUpdatedInMills int64) *TempCredentials {
func newTempCredentials(accessKeyId, accessKeySecret, securityToken string,
expiration time.Time, lastUpdateTime time.Time) *tempCredentials {

return &TempCredentials{
return &tempCredentials{
Credentials: Credentials{
AccessKeyID: accessKeyId,
AccessKeySecret: accessKeySecret,
SecurityToken: securityToken,
},
expirationInMills: expirationInMills,
lastUpdatedInMills: lastUpdatedInMills,
expiredFactor: DEFAULT_EXPIRED_FACTOR,
}
}

// @param factor must > 0.0 and <= 1.0, the less the factor is,
// the more frequently the credentials will be updated.
//
// If factor is set to 0, the credentials will be fetched every time
// [GetCredentials] is called.
//
// If factor is set to 1, the credentials will be fetched only when expired .
func (t *TempCredentials) WithExpiredFactor(factor float64) *TempCredentials {
if factor > 0.0 && factor <= 1.0 {
t.expiredFactor = factor
Expiration: expiration,
LastUpdateTime: lastUpdateTime,
}
return t
}

// Returns true if credentials has expired already or will expire soon.
func (t *TempCredentials) ShouldRefresh() bool {
nowInMills := time.Now().UnixNano() / 1e6
if nowInMills >= t.expirationInMills {
return true
}
duration := (float64)(t.expirationInMills-t.lastUpdatedInMills) * t.expiredFactor
if duration < 0.0 { // check here
duration = 0
}
return (nowInMills - t.lastUpdatedInMills) >= int64(duration)
func (t *tempCredentials) isExpired() bool {
return time.Now().After(t.Expiration)
}

// Returns true if credentials has expired already.
func (t *TempCredentials) HasExpired() bool {
nowInMills := time.Now().UnixNano() / 1e6
return nowInMills >= t.expirationInMills
func (t *tempCredentials) isValid() bool {
return t.Credentials.AccessKeyID != "" && t.Credentials.AccessKeySecret != "" && !t.Expiration.IsZero()
}
Loading

0 comments on commit c24f68d

Please sign in to comment.