ExpiredCredentialsChecker.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License").
  6. * You may not use this file except in compliance with the License.
  7. * A copy of the License is located at
  8. *
  9. * http://aws.amazon.com/apache2.0
  10. *
  11. * or in the "license" file accompanying this file. This file is distributed
  12. * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  13. * express or implied. See the License for the specific language governing
  14. * permissions and limitations under the License.
  15. */
  16. namespace Aws\Common\Client;
  17. use Aws\Common\Credentials\AbstractRefreshableCredentials;
  18. use Aws\Common\Client\AwsClientInterface;
  19. use Aws\Common\Exception\Parser\ExceptionParserInterface;
  20. use Guzzle\Http\Exception\HttpException;
  21. use Guzzle\Http\Message\RequestInterface;
  22. use Guzzle\Http\Message\Response;
  23. use Guzzle\Plugin\Backoff\BackoffStrategyInterface;
  24. use Guzzle\Plugin\Backoff\AbstractBackoffStrategy;
  25. /**
  26. * Backoff logic that handles retrying requests when credentials expire
  27. */
  28. class ExpiredCredentialsChecker extends AbstractBackoffStrategy
  29. {
  30. /**
  31. * @var array Array of known retrying exception codes
  32. */
  33. protected $retryable = array(
  34. 'RequestExpired' => true,
  35. 'ExpiredTokenException' => true,
  36. 'ExpiredToken' => true
  37. );
  38. /**
  39. * @var ExceptionParserInterface Exception parser used to parse exception responses
  40. */
  41. protected $exceptionParser;
  42. public function __construct(ExceptionParserInterface $exceptionParser, BackoffStrategyInterface $next = null) {
  43. $this->exceptionParser = $exceptionParser;
  44. $this->next = $next;
  45. }
  46. public function makesDecision()
  47. {
  48. return true;
  49. }
  50. protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
  51. {
  52. if ($response && $response->isClientError()) {
  53. $parts = $this->exceptionParser->parse($request, $response);
  54. if (!isset($this->retryable[$parts['code']]) || !$request->getClient()) {
  55. return null;
  56. }
  57. /** @var $client AwsClientInterface */
  58. $client = $request->getClient();
  59. // Only retry if the credentials can be refreshed
  60. if (!($client->getCredentials() instanceof AbstractRefreshableCredentials)) {
  61. return null;
  62. }
  63. // Resign the request using new credentials
  64. $client->getSignature()->signRequest($request, $client->getCredentials()->setExpiration(-1));
  65. // Retry immediately with no delay
  66. return 0;
  67. }
  68. }
  69. }