1: <?php
2:
3: namespace OpenSearch\HttpClient;
4:
5: use GuzzleHttp\Exception\ConnectException;
6: use Psr\Http\Message\RequestInterface;
7: use Psr\Http\Message\ResponseInterface;
8: use Psr\Log\LoggerInterface;
9:
10: /**
11: * Retry decider for Guzzle HTTP Client.
12: */
13: class GuzzleRetryDecider
14: {
15: public function __construct(
16: protected ?int $maxRetries = 0,
17: protected ?LoggerInterface $logger = null,
18: ) {
19: }
20:
21: public function __invoke(int $retries, ?RequestInterface $request, ?ResponseInterface $response, $exception): bool
22: {
23: if ($retries >= $this->maxRetries) {
24: return false;
25: }
26: if ($exception instanceof ConnectException) {
27: $this->logger?->warning(
28: 'Retrying request {retries} of {maxRetries}: {exception}',
29: [
30: 'retries' => $retries,
31: 'maxRetries' => $this->maxRetries,
32: 'exception' => $exception->getMessage(),
33: ]
34: );
35: return true;
36: }
37: if ($response && $response->getStatusCode() >= 500) {
38: $this->logger?->warning(
39: 'Retrying request {retries} of {maxRetries}: Status code {status}',
40: [
41: 'retries' => $retries,
42: 'maxRetries' => $this->maxRetries,
43: 'status' => $response->getStatusCode(),
44: ]
45: );
46: return true;
47: }
48: // We only retry if there is a 500 or a ConnectException.
49: return false;
50: }
51: }
52: