| 1 |
<?php |
| 2 |
namespace Aws\Retry\V3; |
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
class QuotaManager |
| 11 |
{ |
| 12 |
private int $availableCapacity; |
| 13 |
private readonly int $maxCapacity; |
| 14 |
private readonly int $noRetryIncrement; |
| 15 |
private readonly int $retryCost; |
| 16 |
private readonly int $throttlingRetryCost; |
| 17 |
|
| 18 |
public function __construct(array $config = []) |
| 19 |
{ |
| 20 |
$initialTokens = $config['initial_retry_tokens'] ?? 500; |
| 21 |
$this->noRetryIncrement = $config['no_retry_increment'] ?? 1; |
| 22 |
$this->retryCost = $config['retry_cost'] ?? 14; |
| 23 |
$this->throttlingRetryCost = $config['throttling_retry_cost'] ?? 5; |
| 24 |
$this->maxCapacity = $initialTokens; |
| 25 |
$this->availableCapacity = $initialTokens; |
| 26 |
} |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
public function acquireRetryQuota(bool $isThrottling): int|false |
| 36 |
{ |
| 37 |
$cost = $isThrottling ? $this->throttlingRetryCost : $this->retryCost; |
| 38 |
|
| 39 |
if ($cost > $this->availableCapacity) { |
| 40 |
return false; |
| 41 |
} |
| 42 |
|
| 43 |
$this->availableCapacity -= $cost; |
| 44 |
|
| 45 |
return $cost; |
| 46 |
} |
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
public function releaseQuota(?int $capacityUsed): void |
| 55 |
{ |
| 56 |
$amount = $capacityUsed ?? $this->noRetryIncrement; |
| 57 |
|
| 58 |
$this->availableCapacity = min( |
| 59 |
$this->availableCapacity + $amount, |
| 60 |
$this->maxCapacity |
| 61 |
); |
| 62 |
} |
| 63 |
|
| 64 |
public function getAvailableCapacity(): int |
| 65 |
{ |
| 66 |
return $this->availableCapacity; |
| 67 |
} |
| 68 |
} |