|
2 | 2 |
|
3 | 3 | namespace HubSpot; |
4 | 4 |
|
| 5 | +use GuzzleHttp\Exception\ConnectException; |
5 | 6 | use GuzzleHttp\Middleware; |
6 | 7 | use GuzzleHttp\Psr7\Request; |
7 | 8 | use GuzzleHttp\Psr7\Response; |
8 | 9 |
|
9 | 10 | class RetryMiddlewareFactory |
10 | 11 | { |
11 | 12 | public const DEFAULT_MAX_RETRIES = 5; |
| 13 | + public const TRANSIENT_CURL_ERROR_CODES = [52, 55, 56]; |
12 | 14 | public const INTERNAL_ERROR_RANGES = [ |
13 | 15 | ['from' => 500, 'to' => 503], |
14 | 16 | ['from' => 520, 'to' => 599], |
15 | 17 | ]; |
16 | 18 |
|
| 19 | + public static function createConnectionErrorsMiddleware( |
| 20 | + ?callable $delayFunction = null, |
| 21 | + int $maxRetries = self::DEFAULT_MAX_RETRIES, |
| 22 | + array $curlErrorCodes = self::TRANSIENT_CURL_ERROR_CODES |
| 23 | + ): callable { |
| 24 | + return Middleware::retry( |
| 25 | + static::getRetryFunctionByConnectionErrors($maxRetries, $curlErrorCodes), |
| 26 | + $delayFunction |
| 27 | + ); |
| 28 | + } |
| 29 | + |
17 | 30 | public static function createInternalErrorsMiddleware( |
18 | 31 | ?callable $delayFunction = null, |
19 | 32 | int $maxRetries = self::DEFAULT_MAX_RETRIES |
@@ -131,4 +144,37 @@ public static function getRetryFunction( |
131 | 144 | return false; |
132 | 145 | }; |
133 | 146 | } |
| 147 | + |
| 148 | + public static function getRetryFunctionByConnectionErrors( |
| 149 | + int $maxRetries = self::DEFAULT_MAX_RETRIES, |
| 150 | + array $curlErrorCodes = self::TRANSIENT_CURL_ERROR_CODES |
| 151 | + ): callable { |
| 152 | + return function ( |
| 153 | + $retries, |
| 154 | + Request $request, |
| 155 | + ?Response $response = null, |
| 156 | + $exception = null |
| 157 | + ) use ($maxRetries, $curlErrorCodes) { |
| 158 | + if ($retries >= $maxRetries) { |
| 159 | + return false; |
| 160 | + } |
| 161 | + |
| 162 | + if (!$exception instanceof ConnectException) { |
| 163 | + return false; |
| 164 | + } |
| 165 | + |
| 166 | + $handlerContext = $exception->getHandlerContext(); |
| 167 | + $errno = $handlerContext['errno'] ?? null; |
| 168 | + |
| 169 | + if (is_numeric($errno) && in_array((int) $errno, $curlErrorCodes, true)) { |
| 170 | + return true; |
| 171 | + } |
| 172 | + |
| 173 | + if (preg_match('/cURL error\s+(\d+):/i', $exception->getMessage(), $matches) === 1) { |
| 174 | + return in_array((int) $matches[1], $curlErrorCodes, true); |
| 175 | + } |
| 176 | + |
| 177 | + return false; |
| 178 | + }; |
| 179 | + } |
134 | 180 | } |
0 commit comments