Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/RetryMiddlewareV2.php

raw symbols SCIP
1 <?php
2 namespace Aws;
3
4 use Aws\Exception\AwsException;
5 use Aws\Retry\ConfigurationInterface;
6 use Aws\Retry\QuotaManager;
7 use Aws\Retry\RateLimiter;
8 use Aws\Retry\RetryHelperTrait;
9 use Exception;
10 use GuzzleHttp\Exception\RequestException;
11 use GuzzleHttp\Promise;
12 use Psr\Http\Message\RequestInterface;
13
14 /**
15 * Middleware that retries failures. V2 implementation that supports 'standard'
16 * and 'adaptive' modes.
17 *
18 * @internal
19 */
20 class RetryMiddlewareV2
21 {
22 use RetryHelperTrait;
23
24 private static $standardThrottlingErrors = [
25 'Throttling' => true,
26 'ThrottlingException' => true,
27 'ThrottledException' => true,
28 'RequestThrottledException' => true,
29 'TooManyRequestsException' => true,
30 'ProvisionedThroughputExceededException' => true,
31 'TransactionInProgressException' => true,
32 'RequestLimitExceeded' => true,
33 'BandwidthLimitExceeded' => true,
34 'LimitExceededException' => true,
35 'RequestThrottled' => true,
36 'SlowDown' => true,
37 'PriorRequestNotComplete' => true,
38 'EC2ThrottledException' => true,
39 ];
40
41 private static $standardTransientErrors = [
42 'RequestTimeout' => true,
43 'RequestTimeoutException' => true,
44 ];
45
46 private static $standardTransientStatusCodes = [
47 500 => true,
48 502 => true,
49 503 => true,
50 504 => true,
51 ];
52
53 private $collectStats;
54 private $decider;
55 private $delayer;
56 private $maxAttempts;
57 private $maxBackoff;
58 private $mode;
59 private $nextHandler;
60 private $options;
61 private $quotaManager;
62 private $rateLimiter;
63
64 public static function wrap($config, $options)
65 {
66 return function (callable $handler) use (
67 $config,
68 $options
69 ) {
70 return new static(
71 $config,
72 $handler,
73 $options
74 );
75 };
76 }
77
78 public static function createDefaultDecider(
79 QuotaManager $quotaManager,
80 $maxAttempts = 3,
81 $options = []
82 ) {
83 $retryCurlErrors = [];
84 if (extension_loaded('curl')) {
85 $retryCurlErrors[CURLE_RECV_ERROR] = true;
86 }
87
88 return function(
89 $attempts,
90 CommandInterface $command,
91 $result
92 ) use ($options, $quotaManager, $retryCurlErrors, $maxAttempts) {
93
94 // Release retry tokens back to quota on a successful result
95 $quotaManager->releaseToQuota($result);
96
97 // Allow command-level option to override this value
98 // # of attempts = # of retries + 1
99 $maxAttempts = (null !== $command['@retries'])
100 ? $command['@retries'] + 1
101 : $maxAttempts;
102
103 $isRetryable = self::isRetryable(
104 $result,
105 $retryCurlErrors,
106 $options
107 );
108
109 if ($isRetryable) {
110
111 // Retrieve retry tokens and check if quota has been exceeded
112 if (!$quotaManager->hasRetryQuota($result)) {
113 return false;
114 }
115
116 if ($attempts >= $maxAttempts) {
117 if (!empty($result) && $result instanceof AwsException) {
118 $result->setMaxRetriesExceeded();
119 }
120 return false;
121 }
122 }
123
124 return $isRetryable;
125 };
126 }
127
128 public function __construct(
129 ConfigurationInterface $config,
130 callable $handler,
131 $options = []
132 ) {
133 $this->options = $options;
134 $this->maxAttempts = $config->getMaxAttempts();
135 $this->mode = $config->getMode();
136 $this->nextHandler = $handler;
137 $this->quotaManager = new QuotaManager();
138
139 $this->maxBackoff = isset($options['max_backoff'])
140 ? $options['max_backoff']
141 : 20000;
142
143 $this->collectStats = isset($options['collect_stats'])
144 ? (bool) $options['collect_stats']
145 : false;
146
147 $this->decider = isset($options['decider'])
148 ? $options['decider']
149 : self::createDefaultDecider(
150 $this->quotaManager,
151 $this->maxAttempts,
152 $options
153 );
154
155 $this->delayer = isset($options['delayer'])
156 ? $options['delayer']
157 : function ($attempts) {
158 return $this->exponentialDelayWithJitter($attempts);
159 };
160
161 if ($this->mode === 'adaptive') {
162 $this->rateLimiter = isset($options['rate_limiter'])
163 ? $options['rate_limiter']
164 : new RateLimiter();
165 }
166 }
167
168 public function __invoke(CommandInterface $cmd, RequestInterface $req)
169 {
170 $decider = $this->decider;
171 $delayer = $this->delayer;
172 $handler = $this->nextHandler;
173
174 $attempts = 1;
175 $monitoringEvents = [];
176 $requestStats = [];
177
178 $req = $this->addRetryHeader($req, 0, 0);
179
180 $callback = function ($value) use (
181 $handler,
182 $cmd,
183 $req,
184 $decider,
185 $delayer,
186 &$attempts,
187 &$requestStats,
188 &$monitoringEvents,
189 &$callback
190 ) {
191 if ($this->mode === 'adaptive') {
192 $this->rateLimiter->updateSendingRate($this->isThrottlingError($value));
193 }
194
195 $this->updateHttpStats($value, $requestStats);
196
197 if ($value instanceof MonitoringEventsInterface) {
198 $reversedEvents = array_reverse($monitoringEvents);
199 $monitoringEvents = array_merge($monitoringEvents, $value->getMonitoringEvents());
200 foreach ($reversedEvents as $event) {
201 $value->prependMonitoringEvent($event);
202 }
203 }
204 if ($value instanceof Exception || $value instanceof \Throwable) {
205 if (!$decider($attempts, $cmd, $value)) {
206 $callback = null;
207 return Promise\Create::rejectionFor(
208 $this->bindStatsToReturn($value, $requestStats)
209 );
210 }
211 } elseif ($value instanceof ResultInterface
212 && !$decider($attempts, $cmd, $value)
213 ) {
214 $callback = null;
215 return $this->bindStatsToReturn($value, $requestStats);
216 }
217
218 $delayBy = $delayer($attempts++);
219 $cmd['@http']['delay'] = $delayBy;
220 if ($this->collectStats) {
221 $this->updateStats($attempts - 1, $delayBy, $requestStats);
222 }
223
224 // Update retry header with retry count and delayBy
225 $req = $this->addRetryHeader($req, $attempts - 1, $delayBy);
226
227 // Get token from rate limiter, which will sleep if necessary
228 if ($this->mode === 'adaptive') {
229 $this->rateLimiter->getSendToken();
230 }
231
232 return $handler($cmd, $req)->then($callback, $callback);
233 };
234
235 // Get token from rate limiter, which will sleep if necessary
236 if ($this->mode === 'adaptive') {
237 $this->rateLimiter->getSendToken();
238 }
239
240 return $handler($cmd, $req)->then($callback, $callback);
241 }
242
243 /**
244 * Amount of milliseconds to delay as a function of attempt number
245 *
246 * @param $attempts
247 * @return mixed
248 */
249 public function exponentialDelayWithJitter($attempts)
250 {
251 $max = mt_getrandmax();
252 try {
253 $rand = random_int(0, $max) / $max;
254 } catch (Exception $_) {
255 // fallback to prevent failing
256 $rand = mt_rand(0, $max) / $max;
257 }
258
259 return min(1000 * $rand * pow(2, $attempts) , $this->maxBackoff);
260 }
261
262 private static function isRetryable(
263 $result,
264 $retryCurlErrors,
265 $options = []
266 ) {
267 $errorCodes = self::$standardThrottlingErrors + self::$standardTransientErrors;
268 if (!empty($options['transient_error_codes'])
269 && is_array($options['transient_error_codes'])
270 ) {
271 foreach($options['transient_error_codes'] as $code) {
272 $errorCodes[$code] = true;
273 }
274 }
275 if (!empty($options['throttling_error_codes'])
276 && is_array($options['throttling_error_codes'])
277 ) {
278 foreach($options['throttling_error_codes'] as $code) {
279 $errorCodes[$code] = true;
280 }
281 }
282
283 $statusCodes = self::$standardTransientStatusCodes;
284 if (!empty($options['status_codes'])
285 && is_array($options['status_codes'])
286 ) {
287 foreach($options['status_codes'] as $code) {
288 $statusCodes[$code] = true;
289 }
290 }
291
292 if (!empty($options['curl_errors'])
293 && is_array($options['curl_errors'])
294 ) {
295 foreach($options['curl_errors'] as $code) {
296 $retryCurlErrors[$code] = true;
297 }
298 }
299
300 if ($result instanceof Exception || $result instanceof \Throwable) {
301 $isError = true;
302 } else {
303 $isError = false;
304 }
305
306 if (!$isError) {
307 if (!isset($result['@metadata']['statusCode'])) {
308 return false;
309 }
310 return isset($statusCodes[$result['@metadata']['statusCode']]);
311 }
312
313 if (!($result instanceof AwsException)) {
314 return false;
315 }
316
317 if ($result->isConnectionError()) {
318 return true;
319 }
320
321 $awsCode = $result->getAwsErrorCode();
322 if (!is_null($awsCode) && isset($errorCodes[$awsCode])) {
323 return true;
324 }
325
326 $status = $result->getStatusCode();
327 if (!is_null($status) && isset($statusCodes[$status])) {
328 return true;
329 }
330
331 if (count($retryCurlErrors)
332 && ($previous = $result->getPrevious())
333 && $previous instanceof RequestException
334 ) {
335 if (method_exists($previous, 'getHandlerContext')) {
336 $context = $previous->getHandlerContext();
337 return !empty($context['errno'])
338 && isset($retryCurlErrors[$context['errno']]);
339 }
340
341 $message = $previous->getMessage();
342 foreach (array_keys($retryCurlErrors) as $curlError) {
343 if (strpos($message, 'cURL error ' . $curlError . ':') === 0) {
344 return true;
345 }
346 }
347 }
348
349 // Check error shape for the retryable trait
350 if (!empty($errorShape = $result->getAwsErrorShape())) {
351 $definition = $errorShape->toArray();
352 if (!empty($definition['retryable'])) {
353 return true;
354 }
355 }
356
357 return false;
358 }
359
360 private function isThrottlingError($result)
361 {
362 if ($result instanceof AwsException) {
363 // Check pre-defined throttling errors
364 $throttlingErrors = self::$standardThrottlingErrors;
365 if (!empty($this->options['throttling_error_codes'])
366 && is_array($this->options['throttling_error_codes'])
367 ) {
368 foreach($this->options['throttling_error_codes'] as $code) {
369 $throttlingErrors[$code] = true;
370 }
371 }
372 if (!empty($result->getAwsErrorCode())
373 && !empty($throttlingErrors[$result->getAwsErrorCode()])
374 ) {
375 return true;
376 }
377
378 // Check error shape for the throttling trait
379 if (!empty($errorShape = $result->getAwsErrorShape())) {
380 $definition = $errorShape->toArray();
381 if (!empty($definition['retryable']['throttling'])) {
382 return true;
383 }
384 }
385 }
386
387 return false;
388 }
389 }