Skip to content

Commit 021be66

Browse files
fix: use random_int instead of mt_rand for retry jitter (#3221)
1 parent 981ae91 commit 021be66

2 files changed

Lines changed: 18 additions & 3 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
[
2+
{
3+
"type": "enhancement",
4+
"category": "",
5+
"description": "Enhance exponential delay calculation to reduce the possibilities of having 0 as the delay."
6+
}
7+
]

src/RetryMiddlewareV2.php

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use Aws\Retry\QuotaManager;
77
use Aws\Retry\RateLimiter;
88
use Aws\Retry\RetryHelperTrait;
9+
use Exception;
910
use GuzzleHttp\Exception\RequestException;
1011
use GuzzleHttp\Promise;
1112
use Psr\Http\Message\RequestInterface;
@@ -200,7 +201,7 @@ public function __invoke(CommandInterface $cmd, RequestInterface $req)
200201
$value->prependMonitoringEvent($event);
201202
}
202203
}
203-
if ($value instanceof \Exception || $value instanceof \Throwable) {
204+
if ($value instanceof Exception || $value instanceof \Throwable) {
204205
if (!$decider($attempts, $cmd, $value)) {
205206
return Promise\Create::rejectionFor(
206207
$this->bindStatsToReturn($value, $requestStats)
@@ -245,7 +246,14 @@ public function __invoke(CommandInterface $cmd, RequestInterface $req)
245246
*/
246247
public function exponentialDelayWithJitter($attempts)
247248
{
248-
$rand = mt_rand() / mt_getrandmax();
249+
$max = mt_getrandmax();
250+
try {
251+
$rand = random_int(0, $max) / $max;
252+
} catch (Exception $_) {
253+
// fallback to prevent failing
254+
$rand = mt_rand(0, $max) / $max;
255+
}
256+
249257
return min(1000 * $rand * pow(2, $attempts) , $this->maxBackoff);
250258
}
251259

@@ -287,7 +295,7 @@ private static function isRetryable(
287295
}
288296
}
289297

290-
if ($result instanceof \Exception || $result instanceof \Throwable) {
298+
if ($result instanceof Exception || $result instanceof \Throwable) {
291299
$isError = true;
292300
} else {
293301
$isError = false;

0 commit comments

Comments
 (0)