QuotaManager.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace Aws\Retry;
  3. use Aws\Exception\AwsException;
  4. use Aws\ResultInterface;
  5. /**
  6. * @internal
  7. */
  8. class QuotaManager
  9. {
  10. private $availableCapacity;
  11. private $capacityAmount;
  12. private $initialRetryTokens;
  13. private $maxCapacity;
  14. private $noRetryIncrement;
  15. private $retryCost;
  16. private $timeoutRetryCost;
  17. public function __construct($config = [])
  18. {
  19. $this->initialRetryTokens = isset($config['initial_retry_tokens'])
  20. ? $config['initial_retry_tokens']
  21. : 500;
  22. $this->noRetryIncrement = isset($config['no_retry_increment'])
  23. ? $config['no_retry_increment']
  24. : 1;
  25. $this->retryCost = isset($config['retry_cost'])
  26. ? $config['retry_cost']
  27. : 5;
  28. $this->timeoutRetryCost = isset($config['timeout_retry_cost'])
  29. ? $config['timeout_retry_cost']
  30. : 10;
  31. $this->maxCapacity = $this->initialRetryTokens;
  32. $this->availableCapacity = $this->initialRetryTokens;
  33. }
  34. public function hasRetryQuota($result)
  35. {
  36. if ($result instanceof AwsException && $result->isConnectionError()) {
  37. $this->capacityAmount = $this->timeoutRetryCost;
  38. } else {
  39. $this->capacityAmount = $this->retryCost;
  40. }
  41. if ($this->capacityAmount > $this->availableCapacity) {
  42. return false;
  43. }
  44. $this->availableCapacity -= $this->capacityAmount;
  45. return true;
  46. }
  47. public function releaseToQuota($result)
  48. {
  49. if ($result instanceof AwsException) {
  50. $statusCode = (int) $result->getStatusCode();
  51. } elseif ($result instanceof ResultInterface) {
  52. $statusCode = isset($result['@metadata']['statusCode'])
  53. ? (int) $result['@metadata']['statusCode']
  54. : null;
  55. }
  56. if (!empty($statusCode) && $statusCode >= 200 && $statusCode < 300) {
  57. if (isset($this->capacityAmount)) {
  58. $amount = $this->capacityAmount;
  59. $this->availableCapacity += $amount;
  60. unset($this->capacityAmount);
  61. } else {
  62. $amount = $this->noRetryIncrement;
  63. $this->availableCapacity += $amount;
  64. }
  65. $this->availableCapacity = min(
  66. $this->availableCapacity,
  67. $this->maxCapacity
  68. );
  69. }
  70. return (isset($amount) ? $amount : 0);
  71. }
  72. public function getAvailableCapacity()
  73. {
  74. return $this->availableCapacity;
  75. }
  76. }