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