Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds http client factories #271

Merged
merged 2 commits into from
Jan 30, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
- Added a test for the AWS signing client decorator
- Added PHPStan Deprecation rules and baseline
- Added PHPStan PHPUnit extensions and rules
- Added Guzzle and Symfony HTTP client factories
### Changed
- Switched to PSR Interfaces
- Increased PHP min version to 8.1
Expand Down
83 changes: 83 additions & 0 deletions src/OpenSearch/GuzzleHttpClientFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

declare(strict_types=1);

namespace OpenSearch;

use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Psr\Http\Client\ClientInterface;

/**
* Builds an OpenSearch client using Guzzle.
*/
class GuzzleHttpClientFactory implements HttpClientFactoryInterface
{
/**
* {@inheritdoc}
*/
public static function create(array $options): ClientInterface
{
if (!isset($options['base_uri'])) {
throw new \InvalidArgumentException('The base_uri option is required.');
}
// Set default configuration.
$defaults = [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'User-Agent' => sprintf('opensearch-php/%s (%s; PHP %s)', Client::VERSION, PHP_OS, PHP_VERSION),
],
];

$logger = $options['logger'] ?? null;
unset($options['logger']);

$maxRetries = $options['max_retries'] ?? 0;
unset($options['max_retries']);

// Merge the default options with the provided options.
$config = array_merge_recursive($defaults, $options);

$stack = HandlerStack::create();
kimpepper marked this conversation as resolved.
Show resolved Hide resolved

// Handle retries if max_retries is set.
if ($maxRetries > 0) {
$stack->push(Middleware::retry(function ($retries, $request, $response, $exception) use ($maxRetries, $logger) {
kimpepper marked this conversation as resolved.
Show resolved Hide resolved
if ($retries >= $maxRetries) {
return false;
}
if ($exception instanceof ConnectException) {
$logger?->warning(
'Retrying request {retries} of {maxRetries}: {exception}',
[
'retries' => $retries,
'maxRetries' => $maxRetries,
'exception' => $exception->getMessage(),
]
);
return true;
}
if ($response && $response->getStatusCode() >= 500) {
$logger?->warning(
'Retrying request {retries} of {maxRetries}: Status code {status}',
[
'retries' => $retries,
'maxRetries' => $maxRetries,
'status' => $response->getStatusCode(),
]
);
return true;
}
return false;
}));
}

$config['handler'] = $stack;

return new GuzzleClient($config);
}

}
21 changes: 21 additions & 0 deletions src/OpenSearch/HttpClientFactoryInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace OpenSearch;

use Psr\Http\Client\ClientInterface;

/**
* Interface for OpenSearch client factories.
*/
interface HttpClientFactoryInterface
{
/**
* Build the OpenSearch client.
*
* @param array<string,mixed> $options
*/
public static function create(array $options): ClientInterface;

}
49 changes: 49 additions & 0 deletions src/OpenSearch/SymfonyHttpClientFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

declare(strict_types=1);

namespace OpenSearch;

use Psr\Http\Client\ClientInterface;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpClient\Psr18Client;
use Symfony\Component\HttpClient\RetryableHttpClient;

/**
* Builds an OpenSearch client using Symfony.
*/
class SymfonyHttpClientFactory implements HttpClientFactoryInterface
{
/**
* {@inheritdoc}
*/
public static function create(array $options): ClientInterface
{
if (!isset($options['base_uri'])) {
throw new \InvalidArgumentException('The base_uri option is required.');
}
// Set default configuration.
$defaults = [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'User-Agent' => sprintf('opensearch-php/%s (%s; PHP %s)', Client::VERSION, PHP_OS, PHP_VERSION),
],
];
$options = array_merge_recursive($defaults, $options);
$maxRetries = $options['max_retries'] ?? 0;
unset($options['max_retries']);

$logger = $options['logger'] ?? null;
unset($options['logger']);

$symfonyClient = HttpClient::create()->withOptions($options);

if ($maxRetries > 0) {
$symfonyClient = new RetryableHttpClient($symfonyClient, null, $maxRetries, $logger);
}

return new Psr18Client($symfonyClient);
}

}
31 changes: 31 additions & 0 deletions tests/GuzzleHttpClientFactoryTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace OpenSearch\Tests;

use OpenSearch\GuzzleHttpClientFactory;
use PHPUnit\Framework\TestCase;
use Psr\Http\Client\ClientInterface;
use Psr\Log\NullLogger;

/**
* Test the Guzzle HTTP client factory.
*
* @coversDefaultClass \OpenSearch\GuzzleHttpClientFactory
*/
class GuzzleHttpClientFactoryTest extends TestCase
{
public function testCreate()
{
$client = GuzzleHttpClientFactory::create([
'base_uri' => 'http://example.com',
'verify' => true,
'max_retries' => 2,
'auth' => ['username', 'password'],
'logger' => new NullLogger(),
]);

$this->assertInstanceOf(ClientInterface::class, $client);
}
}
29 changes: 29 additions & 0 deletions tests/SymfonyHttpClientFactoryTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace OpenSearch\Tests;

use OpenSearch\SymfonyHttpClientFactory;
use PHPUnit\Framework\TestCase;
use Psr\Http\Client\ClientInterface;

/**
* Test the Symfony HTTP client factory.
*
* @coversDefaultClass \OpenSearch\SymfonyHttpClientFactory
*/
class SymfonyHttpClientFactoryTest extends TestCase
{
public function testCreate()
{
$client = SymfonyHttpClientFactory::create([
'base_uri' => 'http://example.com',
'verify_peer' => false,
'max_retries' => 2,
'auth_basic' => ['username', 'password'],
]);

$this->assertInstanceOf(ClientInterface::class, $client);
}
}
Loading