-
-
Notifications
You must be signed in to change notification settings - Fork 66
/
RetryRequests.php
55 lines (46 loc) · 1.61 KB
/
RetryRequests.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
namespace Amp\Http\Client\Interceptor;
use Amp\CancellationToken;
use Amp\Http\Client\ApplicationInterceptor;
use Amp\Http\Client\Connection\Http2ConnectionException;
use Amp\Http\Client\Connection\UnprocessedRequestException;
use Amp\Http\Client\DelegateHttpClient;
use Amp\Http\Client\Internal\ForbidCloning;
use Amp\Http\Client\Internal\ForbidSerialization;
use Amp\Http\Client\Request;
use Amp\Http\Client\SocketException;
use Amp\Promise;
use function Amp\call;
final class RetryRequests implements ApplicationInterceptor
{
use ForbidCloning;
use ForbidSerialization;
/** @var int */
private $retryLimit;
public function __construct(int $retryLimit)
{
$this->retryLimit = $retryLimit;
}
public function request(
Request $request,
CancellationToken $cancellation,
DelegateHttpClient $httpClient
): Promise {
return call(function () use ($request, $cancellation, $httpClient) {
$attempt = 1;
do {
try {
return yield $httpClient->request(clone $request, $cancellation);
} catch (UnprocessedRequestException $exception) {
// Request was deemed retryable by connection, so carry on.
} catch (SocketException | Http2ConnectionException $exception) {
if (!$request->isIdempotent()) {
throw $exception;
}
// Request can safely be retried.
}
} while ($attempt++ <= $this->retryLimit);
throw $exception;
});
}
}