| 1 |
<?php |
| 2 |
namespace Aws\Retry\V3; |
| 3 |
|
| 4 |
use Aws\CommandInterface; |
| 5 |
use Aws\Exception\AwsException; |
| 6 |
use Aws\MonitoringEventsInterface; |
| 7 |
use Aws\ResultInterface; |
| 8 |
use Aws\Retry\ConfigurationInterface; |
| 9 |
use Aws\Retry\RateLimiter; |
| 10 |
use Aws\Retry\RetryHelperTrait; |
| 11 |
use GuzzleHttp\Exception\RequestException; |
| 12 |
use GuzzleHttp\Promise; |
| 13 |
use GuzzleHttp\Promise\PromiseInterface; |
| 14 |
use Psr\Http\Message\RequestInterface; |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
class RetryMiddleware |
| 26 |
{ |
| 27 |
use RetryHelperTrait; |
| 28 |
|
| 29 |
private const THROTTLING_BASE_DELAY_MS = 1_000; |
| 30 |
private const DEFAULT_BASE_DELAY_MS = 50; |
| 31 |
private const DEFAULT_MAX_BACKOFF_MS = 20_000; |
| 32 |
private const RETRY_AFTER_HEADER = 'x-amz-retry-after'; |
| 33 |
|
| 34 |
private static array $standardThrottlingErrors = [ |
| 35 |
'Throttling' => true, |
| 36 |
'ThrottlingException' => true, |
| 37 |
'ThrottledException' => true, |
| 38 |
'RequestThrottledException' => true, |
| 39 |
'TooManyRequestsException' => true, |
| 40 |
'ProvisionedThroughputExceededException' => true, |
| 41 |
'TransactionInProgressException' => true, |
| 42 |
'RequestLimitExceeded' => true, |
| 43 |
'BandwidthLimitExceeded' => true, |
| 44 |
'LimitExceededException' => true, |
| 45 |
'RequestThrottled' => true, |
| 46 |
'SlowDown' => true, |
| 47 |
'PriorRequestNotComplete' => true, |
| 48 |
'EC2ThrottledException' => true, |
| 49 |
]; |
| 50 |
|
| 51 |
private static array $standardTransientErrors = [ |
| 52 |
'RequestTimeout' => true, |
| 53 |
'RequestTimeoutException' => true, |
| 54 |
]; |
| 55 |
|
| 56 |
private static array $standardTransientStatusCodes = [ |
| 57 |
500 => true, |
| 58 |
502 => true, |
| 59 |
503 => true, |
| 60 |
504 => true, |
| 61 |
]; |
| 62 |
|
| 63 |
private float $baseDelayMs; |
| 64 |
private bool $collectStats; |
| 65 |
private ?\Closure $customDecider; |
| 66 |
private ?\Closure $delayer; |
| 67 |
private ?float $exponentialBase; |
| 68 |
private int $maxAttempts; |
| 69 |
private int $maxBackoffMs; |
| 70 |
private string $mode; |
| 71 |
private \Closure $nextHandler; |
| 72 |
private array $options; |
| 73 |
private QuotaManager $quotaManager; |
| 74 |
private ?RateLimiter $rateLimiter = null; |
| 75 |
private array $retryCurlErrors; |
| 76 |
private ?string $service; |
| 77 |
|
| 78 |
public static function wrap(ConfigurationInterface $config, array $options): \Closure |
| 79 |
{ |
| 80 |
return function (callable $handler) use ($config, $options) { |
| 81 |
return new static($config, $handler, $options); |
| 82 |
}; |
| 83 |
} |
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
public static function createDefaultDecider(array $options = []): \Closure |
| 92 |
{ |
| 93 |
$retryCurlErrors = []; |
| 94 |
if (extension_loaded('curl')) { |
| 95 |
$retryCurlErrors[CURLE_RECV_ERROR] = true; |
| 96 |
} |
| 97 |
|
| 98 |
return function ( |
| 99 |
int $attempts, |
| 100 |
CommandInterface $command, |
| 101 |
mixed $result |
| 102 |
) use ($options, $retryCurlErrors): bool { |
| 103 |
return self::isRetryable($result, $retryCurlErrors, $options); |
| 104 |
}; |
| 105 |
} |
| 106 |
|
| 107 |
public function __construct( |
| 108 |
ConfigurationInterface $config, |
| 109 |
callable $handler, |
| 110 |
array $options = [] |
| 111 |
) { |
| 112 |
$this->options = $options; |
| 113 |
$this->maxAttempts = $config->getMaxAttempts(); |
| 114 |
$this->mode = $config->getMode(); |
| 115 |
$this->nextHandler = $handler(...); |
| 116 |
$this->service = $options['service'] ?? null; |
| 117 |
$this->quotaManager = $options['quota_manager'] ?? new QuotaManager(); |
| 118 |
$this->maxBackoffMs = $options['max_backoff'] ?? self::DEFAULT_MAX_BACKOFF_MS; |
| 119 |
$this->baseDelayMs = $options['base_delay'] ?? self::DEFAULT_BASE_DELAY_MS; |
| 120 |
$this->exponentialBase = $options['exponential_base'] ?? null; |
| 121 |
$this->collectStats = (bool) ($options['collect_stats'] ?? false); |
| 122 |
|
| 123 |
$this->customDecider = isset($options['decider']) |
| 124 |
? ($options['decider'])(...) |
| 125 |
: null; |
| 126 |
|
| 127 |
$this->delayer = isset($options['delayer']) |
| 128 |
? ($options['delayer'])(...) |
| 129 |
: null; |
| 130 |
|
| 131 |
$this->retryCurlErrors = []; |
| 132 |
if (extension_loaded('curl')) { |
| 133 |
$this->retryCurlErrors[CURLE_RECV_ERROR] = true; |
| 134 |
} |
| 135 |
if (!empty($options['curl_errors']) && is_array($options['curl_errors'])) { |
| 136 |
foreach ($options['curl_errors'] as $code) { |
| 137 |
$this->retryCurlErrors[$code] = true; |
| 138 |
} |
| 139 |
} |
| 140 |
|
| 141 |
if ($this->mode === 'adaptive') { |
| 142 |
$this->rateLimiter = $options['rate_limiter'] ?? new RateLimiter(); |
| 143 |
} |
| 144 |
} |
| 145 |
|
| 146 |
public function __invoke(CommandInterface $cmd, RequestInterface $req): PromiseInterface |
| 147 |
{ |
| 148 |
$handler = $this->nextHandler; |
| 149 |
|
| 150 |
$attempts = 1; |
| 151 |
$monitoringEvents = []; |
| 152 |
$requestStats = []; |
| 153 |
$capacityUsed = null; |
| 154 |
|
| 155 |
$req = $this->addRetryHeader($req, 0, 0); |
| 156 |
|
| 157 |
$callback = function ($value) use ( |
| 158 |
$handler, |
| 159 |
$cmd, |
| 160 |
$req, |
| 161 |
&$attempts, |
| 162 |
&$requestStats, |
| 163 |
&$monitoringEvents, |
| 164 |
&$callback, |
| 165 |
&$capacityUsed |
| 166 |
) { |
| 167 |
if ($this->mode === 'adaptive') { |
| 168 |
$this->rateLimiter->updateSendingRate($this->isThrottlingError($value)); |
| 169 |
} |
| 170 |
|
| 171 |
$this->updateHttpStats($value, $requestStats); |
| 172 |
|
| 173 |
if ($value instanceof MonitoringEventsInterface) { |
| 174 |
$reversedEvents = array_reverse($monitoringEvents); |
| 175 |
$monitoringEvents = array_merge($monitoringEvents, $value->getMonitoringEvents()); |
| 176 |
foreach ($reversedEvents as $event) { |
| 177 |
$value->prependMonitoringEvent($event); |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
$isError = $value instanceof \Throwable; |
| 182 |
|
| 183 |
$isSuccess = false; |
| 184 |
if (!$isError && $value instanceof ResultInterface) { |
| 185 |
$statusCode = isset($value['@metadata']['statusCode']) |
| 186 |
? (int) $value['@metadata']['statusCode'] |
| 187 |
: null; |
| 188 |
if (!empty($statusCode) && $statusCode >= 200 && $statusCode < 300) { |
| 189 |
$isSuccess = true; |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
if ($isSuccess) { |
| 194 |
$this->quotaManager->releaseQuota($capacityUsed); |
| 195 |
$callback = null; |
| 196 |
return $this->bindStatsToReturn($value, $requestStats); |
| 197 |
} |
| 198 |
|
| 199 |
$isRetryable = self::isRetryable( |
| 200 |
$value, |
| 201 |
$this->retryCurlErrors, |
| 202 |
$this->options |
| 203 |
); |
| 204 |
|
| 205 |
|
| 206 |
if (!$isRetryable && $this->customDecider !== null) { |
| 207 |
$isRetryable = ($this->customDecider)($attempts, $cmd, $value); |
| 208 |
} |
| 209 |
|
| 210 |
if (!$isRetryable) { |
| 211 |
if ($isError) { |
| 212 |
$callback = null; |
| 213 |
return Promise\Create::rejectionFor( |
| 214 |
$this->bindStatsToReturn($value, $requestStats) |
| 215 |
); |
| 216 |
} |
| 217 |
$callback = null; |
| 218 |
return $this->bindStatsToReturn($value, $requestStats); |
| 219 |
} |
| 220 |
|
| 221 |
|
| 222 |
$maxAttempts = ($cmd['@retries'] !== null) |
| 223 |
? $cmd['@retries'] + 1 |
| 224 |
: $this->maxAttempts; |
| 225 |
|
| 226 |
if ($attempts >= $maxAttempts) { |
| 227 |
if ($value instanceof AwsException) { |
| 228 |
$value->setMaxRetriesExceeded(); |
| 229 |
} |
| 230 |
if ($isError) { |
| 231 |
$callback = null; |
| 232 |
return Promise\Create::rejectionFor( |
| 233 |
$this->bindStatsToReturn($value, $requestStats) |
| 234 |
); |
| 235 |
} |
| 236 |
$callback = null; |
| 237 |
return $this->bindStatsToReturn($value, $requestStats); |
| 238 |
} |
| 239 |
|
| 240 |
$isThrottling = $this->isThrottlingError($value); |
| 241 |
$attemptIndex = $attempts - 1; |
| 242 |
$delayByMs = $this->computeRetryDelay( |
| 243 |
$attemptIndex, |
| 244 |
$isThrottling, |
| 245 |
$value |
| 246 |
); |
| 247 |
|
| 248 |
$acquired = $this->quotaManager->acquireRetryQuota($isThrottling); |
| 249 |
if ($acquired === false) { |
| 250 |
|
| 251 |
if (LongPolling::isLongPolling($this->service, $cmd->getName())) { |
| 252 |
$cmd['@http']['delay'] = $delayByMs; |
| 253 |
usleep((int) ($delayByMs * 1000)); |
| 254 |
} |
| 255 |
|
| 256 |
if ($isError) { |
| 257 |
$callback = null; |
| 258 |
return Promise\Create::rejectionFor( |
| 259 |
$this->bindStatsToReturn($value, $requestStats) |
| 260 |
); |
| 261 |
} |
| 262 |
$callback = null; |
| 263 |
return $this->bindStatsToReturn($value, $requestStats); |
| 264 |
} |
| 265 |
$capacityUsed = $acquired; |
| 266 |
|
| 267 |
if ($this->delayer !== null) { |
| 268 |
$delayByMs = ($this->delayer)($attempts); |
| 269 |
} |
| 270 |
|
| 271 |
$attempts++; |
| 272 |
$cmd['@http']['delay'] = $delayByMs; |
| 273 |
|
| 274 |
if ($this->collectStats) { |
| 275 |
$this->updateStats($attempts - 1, $delayByMs, $requestStats); |
| 276 |
} |
| 277 |
|
| 278 |
$req = $this->addRetryHeader($req, $attempts - 1, $delayByMs); |
| 279 |
|
| 280 |
if ($this->mode === 'adaptive') { |
| 281 |
$this->rateLimiter->getSendToken(); |
| 282 |
} |
| 283 |
|
| 284 |
return $handler($cmd, $req)->then($callback, $callback); |
| 285 |
}; |
| 286 |
|
| 287 |
if ($this->mode === 'adaptive') { |
| 288 |
$this->rateLimiter->getSendToken(); |
| 289 |
} |
| 290 |
|
| 291 |
return $handler($cmd, $req)->then($callback, $callback); |
| 292 |
} |
| 293 |
|
| 294 |
public function exponentialDelayWithJitter(int $attempts): int |
| 295 |
{ |
| 296 |
return $this->computeRetryDelay($attempts - 1, false, null); |
| 297 |
} |
| 298 |
|
| 299 |
private function computeRetryDelay(int $attemptIndex, bool $isThrottling, mixed $value): int |
| 300 |
{ |
| 301 |
$baseMs = $isThrottling |
| 302 |
? self::THROTTLING_BASE_DELAY_MS |
| 303 |
: $this->baseDelayMs; |
| 304 |
|
| 305 |
if ($this->exponentialBase !== null) { |
| 306 |
$jitter = $this->exponentialBase; |
| 307 |
} else { |
| 308 |
$max = mt_getrandmax(); |
| 309 |
try { |
| 310 |
$jitter = random_int(0, $max) / $max; |
| 311 |
} catch (\Exception $_) { |
| 312 |
$jitter = mt_rand(0, $max) / $max; |
| 313 |
} |
| 314 |
} |
| 315 |
|
| 316 |
$delayMs = $jitter * min( |
| 317 |
$baseMs * pow(2, $attemptIndex), |
| 318 |
$this->maxBackoffMs |
| 319 |
); |
| 320 |
|
| 321 |
$retryAfterHeader = null; |
| 322 |
if ($value instanceof AwsException) { |
| 323 |
$response = $value->getResponse(); |
| 324 |
$retryAfterHeader = $response?->getHeaderLine( |
| 325 |
self::RETRY_AFTER_HEADER |
| 326 |
) ?? null; |
| 327 |
} elseif ($value instanceof ResultInterface) { |
| 328 |
$retryAfterHeader = $value['@metadata']['headers'][ |
| 329 |
self::RETRY_AFTER_HEADER |
| 330 |
] ?? null; |
| 331 |
} |
| 332 |
|
| 333 |
if (ctype_digit((string) $retryAfterHeader)) { |
| 334 |
$retryAfterMs = (int) $retryAfterHeader; |
| 335 |
$retryAfterMs = max($retryAfterMs, $delayMs); |
| 336 |
$retryAfterMs = min($retryAfterMs, 5000 + $delayMs); |
| 337 |
$delayMs = $retryAfterMs; |
| 338 |
} |
| 339 |
|
| 340 |
return (int) $delayMs; |
| 341 |
} |
| 342 |
|
| 343 |
private static function isRetryable( |
| 344 |
mixed $result, |
| 345 |
array $retryCurlErrors, |
| 346 |
array $options = [] |
| 347 |
): bool |
| 348 |
{ |
| 349 |
$errorCodes = self::$standardThrottlingErrors + self::$standardTransientErrors; |
| 350 |
if (!empty($options['transient_error_codes']) |
| 351 |
&& is_array($options['transient_error_codes']) |
| 352 |
) { |
| 353 |
foreach ($options['transient_error_codes'] as $code) { |
| 354 |
$errorCodes[$code] = true; |
| 355 |
} |
| 356 |
} |
| 357 |
if (!empty($options['throttling_error_codes']) |
| 358 |
&& is_array($options['throttling_error_codes']) |
| 359 |
) { |
| 360 |
foreach ($options['throttling_error_codes'] as $code) { |
| 361 |
$errorCodes[$code] = true; |
| 362 |
} |
| 363 |
} |
| 364 |
|
| 365 |
$statusCodes = self::$standardTransientStatusCodes; |
| 366 |
if (!empty($options['status_codes']) |
| 367 |
&& is_array($options['status_codes']) |
| 368 |
) { |
| 369 |
foreach ($options['status_codes'] as $code) { |
| 370 |
$statusCodes[$code] = true; |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
if (!empty($options['curl_errors']) |
| 375 |
&& is_array($options['curl_errors']) |
| 376 |
) { |
| 377 |
foreach ($options['curl_errors'] as $code) { |
| 378 |
$retryCurlErrors[$code] = true; |
| 379 |
} |
| 380 |
} |
| 381 |
|
| 382 |
$isError = $result instanceof \Throwable; |
| 383 |
|
| 384 |
if (!$isError) { |
| 385 |
if (!isset($result['@metadata']['statusCode'])) { |
| 386 |
return false; |
| 387 |
} |
| 388 |
return isset($statusCodes[$result['@metadata']['statusCode']]); |
| 389 |
} |
| 390 |
|
| 391 |
if (!($result instanceof AwsException)) { |
| 392 |
return false; |
| 393 |
} |
| 394 |
|
| 395 |
if ($result->isConnectionError()) { |
| 396 |
return true; |
| 397 |
} |
| 398 |
|
| 399 |
$awsCode = $result->getAwsErrorCode(); |
| 400 |
if ($awsCode !== null && isset($errorCodes[$awsCode])) { |
| 401 |
return true; |
| 402 |
} |
| 403 |
|
| 404 |
$status = $result->getStatusCode(); |
| 405 |
if ($status !== null && isset($statusCodes[$status])) { |
| 406 |
return true; |
| 407 |
} |
| 408 |
|
| 409 |
if (count($retryCurlErrors) |
| 410 |
&& ($previous = $result->getPrevious()) |
| 411 |
&& $previous instanceof RequestException |
| 412 |
) { |
| 413 |
if (method_exists($previous, 'getHandlerContext')) { |
| 414 |
$context = $previous->getHandlerContext(); |
| 415 |
return !empty($context['errno']) |
| 416 |
&& isset($retryCurlErrors[$context['errno']]); |
| 417 |
} |
| 418 |
|
| 419 |
$message = $previous->getMessage(); |
| 420 |
foreach (array_keys($retryCurlErrors) as $curlError) { |
| 421 |
if (str_starts_with($message, 'cURL error ' . $curlError . ':')) { |
| 422 |
return true; |
| 423 |
} |
| 424 |
} |
| 425 |
} |
| 426 |
|
| 427 |
if (!empty($errorShape = $result->getAwsErrorShape())) { |
| 428 |
$definition = $errorShape->toArray(); |
| 429 |
if (!empty($definition['retryable'])) { |
| 430 |
return true; |
| 431 |
} |
| 432 |
} |
| 433 |
|
| 434 |
return false; |
| 435 |
} |
| 436 |
|
| 437 |
private function isThrottlingError(mixed $result): bool |
| 438 |
{ |
| 439 |
if ($result instanceof AwsException) { |
| 440 |
$throttlingErrors = self::$standardThrottlingErrors; |
| 441 |
if (!empty($this->options['throttling_error_codes']) |
| 442 |
&& is_array($this->options['throttling_error_codes']) |
| 443 |
) { |
| 444 |
foreach ($this->options['throttling_error_codes'] as $code) { |
| 445 |
$throttlingErrors[$code] = true; |
| 446 |
} |
| 447 |
} |
| 448 |
if (!empty($result->getAwsErrorCode()) |
| 449 |
&& !empty($throttlingErrors[$result->getAwsErrorCode()]) |
| 450 |
) { |
| 451 |
return true; |
| 452 |
} |
| 453 |
|
| 454 |
if (!empty($errorShape = $result->getAwsErrorShape())) { |
| 455 |
$definition = $errorShape->toArray(); |
| 456 |
if (!empty($definition['retryable']['throttling'])) { |
| 457 |
return true; |
| 458 |
} |
| 459 |
} |
| 460 |
} |
| 461 |
|
| 462 |
return false; |
| 463 |
} |
| 464 |
} |