Skip to content

Commit

Permalink
Backported #1089
Browse files Browse the repository at this point in the history
  • Loading branch information
ezimuel committed Feb 25, 2021
1 parent c4c3bd3 commit 7c0e670
Show file tree
Hide file tree
Showing 4 changed files with 169 additions and 4 deletions.
21 changes: 17 additions & 4 deletions src/Elasticsearch/ClientBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,10 @@

use Elasticsearch\Common\Exceptions\InvalidArgumentException;
use Elasticsearch\Common\Exceptions\RuntimeException;
use Elasticsearch\ConnectionPool\AbstractConnectionPool;
use Elasticsearch\ConnectionPool\Selectors\SelectorInterface;
use Elasticsearch\ConnectionPool\StaticNoPingConnectionPool;
use Elasticsearch\Connections\Connection;
use Elasticsearch\Connections\ConnectionFactory;
use Elasticsearch\Connections\ConnectionFactoryInterface;
use Elasticsearch\Namespaces\NamespaceBuilderInterface;
use Elasticsearch\Serializers\SerializerInterface;
use Elasticsearch\ConnectionPool\Selectors;
use Elasticsearch\Serializers\SmartSerializer;
use GuzzleHttp\Ring\Client\CurlHandler;
Expand Down Expand Up @@ -100,6 +96,11 @@ class ClientBuilder
/** @var null|bool|string */
private $sslVerification = null;

/**
* @var bool
*/
private $elasticMetaHeader = true;

/**
* @return ClientBuilder
*/
Expand Down Expand Up @@ -431,6 +432,16 @@ public function setSSLVerification($value = true)
return $this;
}

/**
* Set or disable the x-elastic-client-meta header
*/
public function setElasticMetaHeader($value = true): ClientBuilder
{
$this->elasticMetaHeader = $value;

return $this;
}

/**
* @return Client
*/
Expand Down Expand Up @@ -474,6 +485,8 @@ public function build()
$this->serializer = new $this->serializer;
}

$this->connectionParams['client']['x-elastic-client-meta'] = $this->elasticMetaHeader;

if (is_null($this->connectionFactory)) {
if (is_null($this->connectionParams)) {
$this->connectionParams = [];
Expand Down
29 changes: 29 additions & 0 deletions src/Elasticsearch/Connections/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,11 @@ public function __construct(
phpversion()
)];

// Add x-elastic-client-meta header, if enabled
if (isset($connectionParams['client']['x-elastic-client-meta']) && $connectionParams['client']['x-elastic-client-meta']) {
$this->headers['x-elastic-client-meta'] = [$this->getElasticMetaHeader($connectionParams)];
}

$host = $hostDetails['host'].':'.$hostDetails['port'];
$path = null;
if (isset($hostDetails['path']) === true) {
Expand Down Expand Up @@ -762,4 +767,28 @@ private function tryDeserializeError($response, $errorClass)
// <2.0 "i just blew up" nonstructured exception
return new $errorClass($responseBody);
}

/**
* Get the x-elastic-client-meta header
*/
private function getElasticMetaHeader(array $connectionParams): string
{
$phpSemVersion = sprintf("%d.%d.%d", PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION);
// Reduce the size in case of '-snapshot' version (using 'p' as pre-release)
$clientVersion = str_replace('-snapshot', '-p', strtolower(Client::VERSION));
$clientMeta = sprintf(
"es=%s,php=%s,t=%s,a=%d",
$clientVersion,
$phpSemVersion,
$clientVersion,
isset($connectionParams['client']['future']) && $connectionParams['client']['future'] === 'lazy' ? 1 : 0
);
if (function_exists('curl_version')) {
$curlVersion = curl_version();
if (isset($curlVersion['version'])) {
$clientMeta .= sprintf(",cu=%s", $curlVersion['version']); // cu = curl library
}
}
return $clientMeta;
}
}
60 changes: 60 additions & 0 deletions tests/Elasticsearch/Tests/ClientBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@

namespace Elasticsearch\Tests;

use Elasticsearch\Client;
use Elasticsearch\ClientBuilder;
use Elasticsearch\Common\Exceptions\ElasticsearchException;
use Elasticsearch\Common\Exceptions\InvalidArgumentException;
use PHPUnit\Framework\TestCase;

Expand All @@ -40,4 +42,62 @@ public function testClientBuilderThrowsExceptionForIncorrectTracerClass()

ClientBuilder::create()->setTracer(new \Elasticsearch\Tests\ClientBuilder\DummyLogger());
}

public function testElasticClientMetaHeaderIsSentByDefault()
{
$client = ClientBuilder::create()
->build();
$this->assertInstanceOf(Client::class, $client);

try {
$result = $client->info();
} catch (ElasticsearchException $e) {
$request = $client->transport->getLastConnection()->getLastRequestInfo();
$this->assertTrue(isset($request['request']['headers']['x-elastic-client-meta']));
$this->assertEquals(
1,
preg_match(
'/^[a-z]{1,}=[a-z0-9\.\-]{1,}(?:,[a-z]{1,}=[a-z0-9\.\-]+)*$/',
$request['request']['headers']['x-elastic-client-meta'][0]
)
);
}
}

public function testElasticClientMetaHeaderIsSentWhenEnabled()
{
$client = ClientBuilder::create()
->setElasticMetaHeader(true)
->build();
$this->assertInstanceOf(Client::class, $client);

try {
$result = $client->info();
} catch (ElasticsearchException $e) {
$request = $client->transport->getLastConnection()->getLastRequestInfo();
$this->assertTrue(isset($request['request']['headers']['x-elastic-client-meta']));
$this->assertEquals(
1,
preg_match(
'/^[a-z]{1,}=[a-z0-9\.\-]{1,}(?:,[a-z]{1,}=[a-z0-9\.\-]+)*$/',
$request['request']['headers']['x-elastic-client-meta'][0]
)
);
}
}

public function testElasticClientMetaHeaderIsNotSentWhenDisabled()
{
$client = ClientBuilder::create()
->setElasticMetaHeader(false)
->build();
$this->assertInstanceOf(Client::class, $client);

try {
$result = $client->info();
} catch (ElasticsearchException $e) {
$request = $client->transport->getLastConnection()->getLastRequestInfo();
$this->assertFalse(isset($request['request']['headers']['x-elastic-client-meta']));
}
}
}
63 changes: 63 additions & 0 deletions tests/Elasticsearch/Tests/Connections/ConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,4 +153,67 @@ public function testHeaderClientParamIsResetAfterSent()
$headersAfter = $connection->getHeaders();
$this->assertEquals($headersBefore, $headersAfter);
}

/**
* Test if the x-elastic-client-meta header is sent if $params['client']['x-elastic-client-meta'] is true
*/
public function testElasticMetaClientHeaderIsSentWhenParameterIsTrue()
{
$params = [
'client' => [
'x-elastic-client-meta'=> true
]
];
$host = [
'host' => 'localhost'
];

$connection = new Connection(
ClientBuilder::defaultHandler(),
$host,
$params,
$this->serializer,
$this->logger,
$this->trace
);
$result = $connection->performRequest('GET', '/');
$request = $connection->getLastRequestInfo()['request'];

$this->assertArrayHasKey('x-elastic-client-meta', $request['headers']);
$this->assertEquals(
1,
preg_match(
'/^[a-z]{1,}=[a-z0-9\.\-]{1,}(?:,[a-z]{1,}=[a-z0-9\.\-]+)*$/',
$request['headers']['x-elastic-client-meta'][0]
)
);
}

/**
* Test if the x-elastic-client-meta header is sent if $params['client']['x-elastic-client-meta'] is true
*/
public function testElasticMetaClientHeaderIsNotSentWhenParameterIsFalse()
{
$params = [
'client' => [
'x-elastic-client-meta'=> false
]
];
$host = [
'host' => 'localhost'
];

$connection = new Connection(
ClientBuilder::defaultHandler(),
$host,
$params,
$this->serializer,
$this->logger,
$this->trace
);
$result = $connection->performRequest('GET', '/');
$request = $connection->getLastRequestInfo()['request'];

$this->assertArrayNotHasKey('x-elastic-client-meta', $request['headers']);
}
}

0 comments on commit 7c0e670

Please sign in to comment.