credential_updater.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Licensed under the Apache License, Version 2.0 (the "License");
  3. * you may not use this file except in compliance with the License.
  4. * You may obtain a copy of the License at
  5. *
  6. * http://www.apache.org/licenses/LICENSE-2.0
  7. *
  8. * Unless required by applicable law or agreed to in writing, software
  9. * distributed under the License is distributed on an "AS IS" BASIS,
  10. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. * See the License for the specific language governing permissions and
  12. * limitations under the License.
  13. */
  14. package signers
  15. import (
  16. "time"
  17. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
  18. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
  19. )
  20. const defaultInAdvanceScale = 0.95
  21. type credentialUpdater struct {
  22. credentialExpiration int
  23. lastUpdateTimestamp int64
  24. inAdvanceScale float64
  25. buildRequestMethod func() (*requests.CommonRequest, error)
  26. responseCallBack func(response *responses.CommonResponse) error
  27. refreshApi func(request *requests.CommonRequest) (response *responses.CommonResponse, err error)
  28. }
  29. func (updater *credentialUpdater) needUpdateCredential() (result bool) {
  30. if updater.inAdvanceScale == 0 {
  31. updater.inAdvanceScale = defaultInAdvanceScale
  32. }
  33. return time.Now().Unix()-updater.lastUpdateTimestamp >= int64(float64(updater.credentialExpiration)*updater.inAdvanceScale)
  34. }
  35. func (updater *credentialUpdater) updateCredential() (err error) {
  36. request, err := updater.buildRequestMethod()
  37. if err != nil {
  38. return
  39. }
  40. response, err := updater.refreshApi(request)
  41. if err != nil {
  42. return
  43. }
  44. updater.lastUpdateTimestamp = time.Now().Unix()
  45. err = updater.responseCallBack(response)
  46. return
  47. }