Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .github/workflows/run_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,28 @@ jobs:
run: |
make lint
make test-unit

# composer.lock pins Guzzle 7, so the matrix above never runs Guzzle 8. This leg
# resolves the newest Guzzle 8 and runs the same lint and unit lane against it.
test-guzzle-8:
name: 🧪 Test & lint (8.3, Guzzle 8)
runs-on: { group: github-public-amd64 }
timeout-minutes: 20

steps:
- uses: actions/checkout@v4

- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: curl, json
tools: composer:v2

- name: Install dependencies with Guzzle 8
run: composer update "guzzlehttp/guzzle:^8.0" --with-all-dependencies --prefer-dist --no-interaction

- name: Lint & unit tests
run: |
make lint
make test-unit
2 changes: 1 addition & 1 deletion composer-generated.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"ext-json": "*",
"ext-curl": "*",
"firebase/php-jwt": "^7.0",
"guzzlehttp/guzzle": "^7.0",
"guzzlehttp/guzzle": "^7.0 || ^8.0",
"vlucas/phpdotenv": "^5.0"
},
"require-dev": {
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"ext-curl": "*",
"ext-json": "*",
"firebase/php-jwt": "^7.0",
"guzzlehttp/guzzle": "^7.0",
"guzzlehttp/guzzle": "^7.0 || ^8.0",
"psr/log": "^3.0",
"vlucas/phpdotenv": "^5.0"
},
Expand Down
82 changes: 66 additions & 16 deletions src/Http/GuzzleHttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@
use GetStream\StreamResponse;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Handler\CurlMultiHandler;
use GuzzleHttp\HandlerStack;
use Psr\Http\Client\NetworkExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
Expand Down Expand Up @@ -73,12 +73,25 @@ public function __construct(
// ReactPHP, CLI daemons). Under PHP-FPM the PHP process exits per request and
// the multi handle dies with it; the per-call request/connect timeouts still
// apply but there is no cross-request connection reuse.
$multi = new CurlMultiHandler([
'options' => [
CURLMOPT_MAX_HOST_CONNECTIONS => $pool->maxConnsPerHost,
CURLMOPT_MAXCONNECTS => $pool->maxConnsPerHost,
],
]);
//
// Guzzle 7 accepts CURLMOPT_MAX_HOST_CONNECTIONS in `options`. Guzzle 8 rejects
// it and requires the named max_host_connections / max_total_connections keys.
try {
$multi = new CurlMultiHandler([
'options' => [
CURLMOPT_MAX_HOST_CONNECTIONS => $pool->maxConnsPerHost,
CURLMOPT_MAXCONNECTS => $pool->maxConnsPerHost,
],
]);
} catch (\InvalidArgumentException) {
$multi = new CurlMultiHandler([
'max_host_connections' => $pool->maxConnsPerHost,
'max_total_connections' => $pool->maxConnsPerHost,
'options' => [
CURLMOPT_MAXCONNECTS => $pool->maxConnsPerHost,
],
]);
}
$defaultHandler = HandlerStack::create($multi);

$curlOptions = [
Expand Down Expand Up @@ -283,10 +296,20 @@ public function request(
$rawBody = $this->emitResponseReceived($e->getResponse(), $durationMs);

return $this->createStreamResponse($e->getResponse(), $e, $rawBody);
} catch (ConnectException $e) {
throw new StreamTransportException($e->getMessage(), self::mapConnectErrorType($e), $e);
} catch (NetworkExceptionInterface $e) {
// Guzzle 7: ConnectException. Guzzle 8: NetworkException and subclasses
// (ConnectException, NetworkTimeoutException, …) for no-response failures.
throw new StreamTransportException($e->getMessage(), self::mapNetworkErrorType($e), $e);
} catch (GuzzleException $e) {
throw new StreamTransportException($e->getMessage(), StreamTransportException::ERROR_TYPE_UNKNOWN, $e);
// Guzzle 8 reports a timeout after the response headers arrived as
// ResponseTimeoutException, which is not a NetworkExceptionInterface.
// Guzzle 7 reports the same failure as ConnectException (timeout above).
$errorType = class_exists(\GuzzleHttp\Exception\ResponseTimeoutException::class)
&& $e instanceof \GuzzleHttp\Exception\ResponseTimeoutException
? StreamTransportException::ERROR_TYPE_TIMEOUT
: StreamTransportException::ERROR_TYPE_UNKNOWN;

throw new StreamTransportException($e->getMessage(), $errorType, $e);
}

$rawBody = $this->emitResponseReceived($response, self::elapsedMs($start));
Expand Down Expand Up @@ -546,13 +569,25 @@ private static function parseRetryAfter(?string $header): ?int
}

/**
* Map a Guzzle ConnectException to a canonical transport-error type.
* Uses libcurl errno when available; falls back to message inspection.
* Map a no-response network failure to a canonical transport-error type.
*
* Guzzle 8 removed ConnectException::getHandlerContext(). Prefer curl errno from
* the handler context when present (Guzzle 7), then from the message ("cURL error N"),
* then Guzzle 8 timeout subclasses, then message inspection.
*/
private static function mapConnectErrorType(ConnectException $e): string
private static function mapNetworkErrorType(\Throwable $e): string
{
$ctx = $e->getHandlerContext();
$errno = is_array($ctx) && isset($ctx['errno']) ? (int) $ctx['errno'] : 0;
$errno = 0;
if (method_exists($e, 'getHandlerContext')) {
/** @var mixed $ctx */
$ctx = $e->getHandlerContext();
if (is_array($ctx) && isset($ctx['errno'])) {
$errno = (int) $ctx['errno'];
}
}
if ($errno === 0 && preg_match('/curl error (\d+)/i', $e->getMessage(), $matches) === 1) {
$errno = (int) $matches[1];
}

switch ($errno) {
case 6: // CURLE_COULDNT_RESOLVE_HOST
Expand All @@ -570,6 +605,14 @@ private static function mapConnectErrorType(ConnectException $e): string
return StreamTransportException::ERROR_TYPE_TLS_HANDSHAKE_FAILED;
}

// Guzzle 8 timeout subclasses (absent on Guzzle 7).
if (
(class_exists(\GuzzleHttp\Exception\ConnectTimeoutException::class) && $e instanceof \GuzzleHttp\Exception\ConnectTimeoutException)
|| (class_exists(\GuzzleHttp\Exception\NetworkTimeoutException::class) && $e instanceof \GuzzleHttp\Exception\NetworkTimeoutException)
) {
return StreamTransportException::ERROR_TYPE_TIMEOUT;
}

$msg = strtolower($e->getMessage());
if (str_contains($msg, 'could not resolve') || str_contains($msg, 'name or service not known')) {
return StreamTransportException::ERROR_TYPE_DNS_FAILURE;
Expand All @@ -580,7 +623,14 @@ private static function mapConnectErrorType(ConnectException $e): string
if (str_contains($msg, 'ssl') || str_contains($msg, 'tls') || str_contains($msg, 'certificate')) {
return StreamTransportException::ERROR_TYPE_TLS_HANDSHAKE_FAILED;
}
if (str_contains($msg, 'refused') || str_contains($msg, 'reset') || str_contains($msg, 'closed')) {
if (
str_contains($msg, 'refused')
|| str_contains($msg, 'reset')
|| str_contains($msg, 'closed')
|| str_contains($msg, 'failed to connect')
|| str_contains($msg, 'could not connect')
|| str_contains($msg, "couldn't connect")
) {
return StreamTransportException::ERROR_TYPE_CONNECTION_RESET;
}

Expand Down
78 changes: 69 additions & 9 deletions tests/Exceptions/ErrorHandlingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -224,14 +224,30 @@ public function rateLimitIsNotRetriedByDefault(): void
self::assertCount(1, $history, 'retries are opt-in: default RetryConfig performs exactly one attempt');
}

/**
* Build a ConnectException compatible with Guzzle 7 (optional handler context)
* and Guzzle 8 (no handler-context constructor argument).
*
* @param array<string, mixed> $handlerContext
*/
private function makeConnectException(string $message, Request $req, array $handlerContext = []): ConnectException
{
$ref = new \ReflectionClass(ConnectException::class);
$params = $ref->getConstructor()?->getNumberOfParameters() ?? 2;
if ($params >= 4) {
return new ConnectException($message, $req, null, $handlerContext);
}

return new ConnectException($message, $req);
}

/** @test */
public function connectionResetMapsToConnectionResetErrorType(): void
{
$req = new Request('GET', 'https://example.invalid/');
$exc = new ConnectException(
$exc = $this->makeConnectException(
'cURL error 7: Failed to connect',
$req,
null,
['errno' => 7],
);
$client = $this->makeClient([$exc]);
Expand All @@ -249,10 +265,9 @@ public function connectionResetMapsToConnectionResetErrorType(): void
public function dnsFailureMapsToDnsFailureErrorType(): void
{
$req = new Request('GET', 'https://example.invalid/');
$exc = new ConnectException(
$exc = $this->makeConnectException(
'cURL error 6: Could not resolve host',
$req,
null,
['errno' => 6],
);
$client = $this->makeClient([$exc]);
Expand All @@ -269,10 +284,9 @@ public function dnsFailureMapsToDnsFailureErrorType(): void
public function timeoutMapsToTimeoutErrorType(): void
{
$req = new Request('GET', 'https://example.invalid/');
$exc = new ConnectException(
$exc = $this->makeConnectException(
'cURL error 28: Operation timed out',
$req,
null,
['errno' => 28],
);
$client = $this->makeClient([$exc]);
Expand All @@ -289,10 +303,9 @@ public function timeoutMapsToTimeoutErrorType(): void
public function tlsFailureMapsToTlsHandshakeFailedErrorType(): void
{
$req = new Request('GET', 'https://example.invalid/');
$exc = new ConnectException(
$exc = $this->makeConnectException(
'cURL error 35: SSL connect error',
$req,
null,
['errno' => 35],
);
$client = $this->makeClient([$exc]);
Expand All @@ -309,7 +322,7 @@ public function tlsFailureMapsToTlsHandshakeFailedErrorType(): void
public function unknownTransportErrorMapsToUnknownErrorType(): void
{
$req = new Request('GET', 'https://example.invalid/');
$exc = new ConnectException('something weird', $req, null, []);
$exc = $this->makeConnectException('something weird', $req);
$client = $this->makeClient([$exc]);

try {
Expand All @@ -321,6 +334,53 @@ public function unknownTransportErrorMapsToUnknownErrorType(): void
}
}

/** @test */
public function guzzle8NetworkExceptionMapsSendRecvToConnectionReset(): void
{
if (!class_exists(\GuzzleHttp\Exception\NetworkException::class)) {
$this->markTestSkipped('Guzzle 8 NetworkException is not available');
}

$req = new Request('GET', 'https://example.invalid/');
// Guzzle 8 classifies some send/recv failures as NetworkException rather than ConnectException.
$exc = new \GuzzleHttp\Exception\NetworkException('cURL error 56: Failure when receiving data', $req);
$client = $this->makeClient([$exc]);

try {
$client->request('GET', 'https://example.invalid/');
self::fail('expected StreamTransportException');
} catch (StreamTransportException $e) {
self::assertSame(StreamTransportException::ERROR_TYPE_CONNECTION_RESET, $e->getErrorType());
self::assertInstanceOf(\GuzzleHttp\Exception\NetworkException::class, $e->getPrevious());
}
}

/** @test */
public function guzzle8ResponseTimeoutMapsToTimeoutErrorType(): void
{
if (!class_exists(\GuzzleHttp\Exception\ResponseTimeoutException::class)) {
$this->markTestSkipped('Guzzle 8 ResponseTimeoutException is not available');
}

$req = new Request('GET', 'https://example.invalid/');
// Guzzle 8 raises ResponseTimeoutException when the transfer times out after the
// response headers arrived. It is not a NetworkExceptionInterface.
$exc = new \GuzzleHttp\Exception\ResponseTimeoutException(
'cURL error 28: Operation timed out after 1001 milliseconds with 5 out of 100 bytes received',
$req,
new GuzzleResponse(200),
);
$client = $this->makeClient([$exc]);

try {
$client->request('GET', 'https://example.invalid/');
self::fail('expected StreamTransportException');
} catch (StreamTransportException $e) {
self::assertSame(StreamTransportException::ERROR_TYPE_TIMEOUT, $e->getErrorType());
self::assertInstanceOf(\GuzzleHttp\Exception\ResponseTimeoutException::class, $e->getPrevious());
}
}

/** @test */
public function streamRateLimitExceptionDirectConstructionPreservesCauseChain(): void
{
Expand Down
18 changes: 12 additions & 6 deletions tests/Http/GuzzleHttpClientPoolTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,10 @@ public function defaultsApplyWhenNoPoolConfigPassed(): void
public function defaultHandlerIsPersistentCurlMultiHandler(): void
{
// When no handler is supplied, the default stack must wrap a CurlMultiHandler
// so the per-host connection cap (CURLMOPT_MAX_HOST_CONNECTIONS) is real
// across requests in long-running runtimes.
// so the per-host connection cap is real across requests in long-running
// runtimes. Guzzle 8 applies max_host_connections / max_total_connections as
// named constructor options (raw CURLMOPT_MAX_*_CONNECTIONS in `options` is
// rejected); both Guzzle 7 and 8 expose the resolved caps on `$options`.
$sdk = new GuzzleHttpClient([], 0, new PoolConfig());

$clientProp = (new \ReflectionObject($sdk))->getProperty('client');
Expand All @@ -93,10 +95,14 @@ public function defaultHandlerIsPersistentCurlMultiHandler(): void

$optionsProp = (new \ReflectionObject($multi))->getProperty('options');
$optionsProp->setAccessible(true);
self::assertSame(
[CURLMOPT_MAX_HOST_CONNECTIONS => 100, CURLMOPT_MAXCONNECTS => 100],
$optionsProp->getValue($multi),
);
/** @var array<int, mixed> $options */
$options = $optionsProp->getValue($multi);
self::assertSame(100, $options[CURLMOPT_MAX_HOST_CONNECTIONS] ?? null);
self::assertSame(100, $options[CURLMOPT_MAXCONNECTS] ?? null);
// Guzzle 8 also applies max_total_connections via the named constructor option.
if (defined('CURLMOPT_MAX_TOTAL_CONNECTIONS') && array_key_exists(\constant('CURLMOPT_MAX_TOTAL_CONNECTIONS'), $options)) {
self::assertSame(100, $options[\constant('CURLMOPT_MAX_TOTAL_CONNECTIONS')]);
}
}

/** @test */
Expand Down
2 changes: 1 addition & 1 deletion tests/Http/RetryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ public function testTransportErrorRetryLogCarriesErrorType(): void
$retries = self::retryRecords($logger);
$this->assertCount(1, $retries);
// ConnectException message inspection (no handler-context errno on the mock):
// "reset" matches the connection_reset branch in mapConnectErrorType().
// "reset" matches the connection_reset branch in mapNetworkErrorType().
$this->assertSame(StreamTransportException::ERROR_TYPE_CONNECTION_RESET, $retries[0]['context']['error.type']);
$this->assertSame(1, $retries[0]['context']['retry.attempt']);
}
Expand Down
Loading