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

feat: client identification headers #232

Draft
wants to merge 13 commits into
base: main
Choose a base branch
from
11 changes: 7 additions & 4 deletions src/Client/DefaultRegistrationService.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,9 @@ public function __construct(
private readonly ClientInterface $httpClient,
private readonly RequestFactoryInterface $requestFactory,
private readonly UnleashConfiguration $configuration,
private ?string $sdkName = null,
private ?string $sdkVersion = null,
private ?string $sdkName = Unleash::SDK_NAME,
private ?string $sdkVersion = Unleash::SDK_VERSION,
) {
$this->sdkName ??= 'unleash-client-php';
$this->sdkVersion ??= Unleash::SDK_VERSION;
}

/**
Expand Down Expand Up @@ -66,6 +64,11 @@ public function register(iterable $strategyHandlers): bool
$request = $request->withHeader($name, $value);
}

$request = $request
->withHeader('x-unleash-appname', $this->configuration->getAppName())
->withHeader('x-unleash-sdk', $this->sdkName . ':' . $this->sdkVersion)
->withHeader('x-unleash-connection-id', $this->configuration->getConnectionId());

try {
$response = $this->httpClient->sendRequest($request);
$result = $response->getStatusCode() >= 200 && $response->getStatusCode() < 300;
Expand Down
17 changes: 17 additions & 0 deletions src/Configuration/UnleashConfiguration.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,16 @@
use Unleash\Client\Bootstrap\EmptyBootstrapProvider;
use Unleash\Client\ContextProvider\DefaultUnleashContextProvider;
use Unleash\Client\ContextProvider\UnleashContextProvider;
use Unleash\Client\Enum\CacheKey;
use Unleash\Client\Helper\Url;
use Unleash\Client\Helper\Uuid;
use Unleash\Client\Metrics\DefaultMetricsBucketSerializer;
use Unleash\Client\Metrics\MetricsBucketSerializer;

final class UnleashConfiguration
{
private string $connectionId;

/**
* @param array<string,string> $headers
*/
Expand All @@ -45,6 +49,7 @@
private MetricsBucketSerializer $metricsBucketSerializer = new DefaultMetricsBucketSerializer(),
) {
$this->contextProvider ??= new DefaultUnleashContextProvider();
$this->connectionId = Uuid::v4();
}

public function getCache(): CacheInterface
Expand Down Expand Up @@ -298,4 +303,16 @@

return $this;
}

public function getConnectionId(): string
{
$cachedConnectionId = $this->getCache()->get(CacheKey::CONNECTION_ID);

return $cachedConnectionId ?? $this->connectionId;

Check failure on line 311 in src/Configuration/UnleashConfiguration.php

View workflow job for this annotation

GitHub Actions / Static analysis (8.3)

Method Unleash\Client\Configuration\UnleashConfiguration::getConnectionId() should return string but returns mixed.
}

public function updateCachedConnectionId(): void
{
$this->getCache()->set(CacheKey::CONNECTION_ID, $this->connectionId);
}
}
2 changes: 2 additions & 0 deletions src/Enum/CacheKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,6 @@ final class CacheKey
public const string REGISTRATION = 'unleash.client.metrics.registration';

public const string FEATURES_RESPONSE = 'unleash.client.feature.response';

public const string CONNECTION_ID = 'unleash.client.connection.id';
}
12 changes: 11 additions & 1 deletion src/Repository/DefaultUnleashRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ public function __construct(
private ClientInterface $httpClient,
private RequestFactoryInterface $requestFactory,
private UnleashConfiguration $configuration,
private string $sdkName = Unleash::SDK_NAME,
private string $sdkVersion = Unleash::SDK_VERSION,
) {
}

Expand Down Expand Up @@ -158,7 +160,9 @@ private function getCachedFeatures(): ?array
private function setCache(array $features): void
{
$cache = $this->configuration->getCache();
$cache->set(CacheKey::FEATURES, $features, $this->configuration->getTtl());
$ttl = $this->configuration->getTtl();
$cache->set(CacheKey::FEATURES, $features, $ttl);
$this->configuration->updateCachedConnectionId();
}

/**
Expand Down Expand Up @@ -510,6 +514,7 @@ private function fetchFeatures(): array
} else {
$request = $this->requestFactory
->createRequest('GET', (string) Url::appendPath($this->configuration->getUrl(), 'client/features'))
// TODO: remove non-standard headers
Copy link
Member Author

@Tymek Tymek Jan 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe after some time, for example in a next major version

->withHeader('UNLEASH-APPNAME', $this->configuration->getAppName())
->withHeader('UNLEASH-INSTANCEID', $this->configuration->getInstanceId())
->withHeader('Unleash-Client-Spec', Unleash::SPECIFICATION_VERSION);
Expand All @@ -518,6 +523,11 @@ private function fetchFeatures(): array
$request = $request->withHeader($name, $value);
}

$request = $request
->withHeader('x-unleash-appname', $this->configuration->getAppName())
->withHeader('x-unleash-sdk', $this->sdkName . ':' . $this->sdkVersion)
->withHeader('x-unleash-connection-id', $this->configuration->getConnectionId());

try {
$response = $this->httpClient->sendRequest($request);
if ($response->getStatusCode() === 200) {
Expand Down
2 changes: 2 additions & 0 deletions src/Unleash.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

interface Unleash
{
public const string SDK_NAME = 'unleash-client-php';

public const string SDK_VERSION = '2.6.1';

public const string SPECIFICATION_VERSION = '5.0.2';
Expand Down
17 changes: 15 additions & 2 deletions src/UnleashBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
use Unleash\Client\Helper\Builder\StickinessCalculatorAware;
use Unleash\Client\Helper\DefaultImplementationLocator;
use Unleash\Client\Helper\UnleashBuilderContainer;
use Unleash\Client\Helper\Uuid;
use Unleash\Client\Metrics\DefaultMetricsBucketSerializer;
use Unleash\Client\Metrics\DefaultMetricsHandler;
use Unleash\Client\Metrics\DefaultMetricsSender;
Expand Down Expand Up @@ -69,6 +70,8 @@ final class UnleashBuilder

private ?string $appName = null;

private string $connectionId;

private ?ClientInterface $httpClient = null;

private ?RequestFactoryInterface $requestFactory = null;
Expand Down Expand Up @@ -131,6 +134,8 @@ public function __construct()
$this->eventDispatcher = new EventDispatcher();
}

$this->connectionId = Uuid::v4();

$rolloutStrategyHandler = new GradualRolloutStrategyHandler(new MurmurHashCalculator());
$this->strategies = [
new DefaultStrategyHandler(),
Expand Down Expand Up @@ -406,7 +411,11 @@ public function build(): Unleash
);

assert($dependencyContainer->getConfiguration() !== null);
$registrationService = $this->registrationService ?? new DefaultRegistrationService($dependencyContainer->getHttpClient(), $dependencyContainer->getRequestFactory(), $dependencyContainer->getConfiguration());
$registrationService = $this->registrationService ?? new DefaultRegistrationService(
$dependencyContainer->getHttpClient(),
$dependencyContainer->getRequestFactory(),
$dependencyContainer->getConfiguration(),
);
$metricsHandler = $this->metricsHandler ?? new DefaultMetricsHandler($metricsSender, $dependencyContainer->getConfiguration());
$variantHandler = $this->variantHandler ?? new DefaultVariantHandler(new MurmurHashCalculator());

Expand Down Expand Up @@ -671,6 +680,10 @@ private function createRepository(UnleashBuilderContainer $dependencyContainer):
{
assert($dependencyContainer->getConfiguration() !== null);

return new DefaultUnleashRepository($dependencyContainer->getHttpClient(), $dependencyContainer->getRequestFactory(), $dependencyContainer->getConfiguration());
return new DefaultUnleashRepository(
$dependencyContainer->getHttpClient(),
$dependencyContainer->getRequestFactory(),
$dependencyContainer->getConfiguration(),
);
}
}
26 changes: 26 additions & 0 deletions tests/Client/DefaultRegistrationServiceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,4 +131,30 @@ public function testUrl()
self::assertCount(1, $this->requestHistory);
self::assertSame('https://localhost/api/client/register?namePrefix=somePrefix', (string) $this->requestHistory[0]['request']->getUri());
}

public function testRequestHeaders()
{
$configuration = (new UnleashConfiguration('', 'customAppName', ''))
->setCache($this->getCache())
->setHeaders([
'Some-Header' => 'some-value',
'x-unleash-connection-id' => 'should not override',
])->setCache($this->getCache());

$instance = new DefaultRegistrationService(
$this->httpClient,
new HttpFactory(),
$configuration
);
$this->pushResponse([]);

$instance->register([]);
self::assertCount(1, $this->requestHistory);

$request = $this->requestHistory[0]['request'];
self::assertSame('some-value', $request->getHeaderLine('Some-Header'));
self::assertEquals('customAppName', $request->getHeaderLine('x-unleash-appname'));
self::assertStringStartsWith('unleash-client-php:', $request->getHeaderLine('x-unleash-sdk'));
self::assertStringMatchesFormat('%s-%s-%s-%s-%s', $request->getHeaderLine('x-unleash-connection-id'));
}
}
Loading