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

Do not store invalid response #183

Merged
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
52 changes: 40 additions & 12 deletions src/Repository/DefaultUnleashRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,24 @@
* type:string,
* value: string,
* }
* @phpstan-type StrategyArray array{
* constraints?: array<ConstraintArray>,
* variants?: array<VariantArray>,
* segments?: array<string>,
* name: string,
* parameters: array<string, string>,
* }
* @phpstan-type SegmentArray array{
* id: int,
* constraints: array<ConstraintArray>,
* }
* @phpstan-type FeatureArray array{
* strategies: array<StrategyArray>,
* variants: array<VariantArray>,
* name: string,
* enabled: bool,
* impressionData?: bool,
* }
*/
final readonly class DefaultUnleashRepository implements UnleashRepository
{
Expand Down Expand Up @@ -89,8 +107,9 @@ public function getFeatures(): iterable
{
$features = $this->getCachedFeatures();
if ($features === null) {
$data = null;
if (!$this->configuration->isFetchingEnabled()) {
if (!$data = $this->getBootstrappedResponse()) {
if (!$rawData = $this->getBootstrappedResponse()) {
throw new LogicException('Fetching of Unleash api is disabled but no bootstrap is provided');
}
} else {
Expand All @@ -108,8 +127,15 @@ public function getFeatures(): iterable
try {
$response = $this->httpClient->sendRequest($request);
if ($response->getStatusCode() === 200) {
$data = (string) $response->getBody();
$this->setLastValidState($data);
$rawData = (string) $response->getBody();
$data = json_decode($rawData, true);
if (($lastError = json_last_error()) !== JSON_ERROR_NONE) {
throw new InvalidValueException(
sprintf("JsonException: '%s'", json_last_error_msg()),
$lastError
);
}
$this->setLastValidState($rawData);
} else {
throw new HttpResponseException("Invalid status code: '{$response->getStatusCode()}'");
}
Expand All @@ -118,17 +144,22 @@ public function getFeatures(): iterable
new FetchingDataFailedEvent($exception),
UnleashEvents::FETCHING_DATA_FAILED,
);
$data = $this->getLastValidState();
$rawData = $this->getLastValidState();
}
$data ??= $this->getBootstrappedResponse();
if ($data === null) {
$rawData ??= $this->getBootstrappedResponse();
if ($rawData === null) {
throw new HttpResponseException(sprintf(
'Got invalid response code when getting features and no default bootstrap provided: %s',
isset($response) ? $response->getStatusCode() : 'unknown response status code'
), 0, $exception ?? null);
}
}

if ($data === null) {
$data = json_decode($rawData, true);
}

assert(is_array($data));
$features = $this->parseFeatures($data);
$this->setCache($features);
}
Expand Down Expand Up @@ -167,16 +198,13 @@ private function setCache(array $features): void
}

/**
* @throws JsonException
* @param array{segments?: array<SegmentArray>, features?: array<FeatureArray>} $body
*
* @return array<Feature>
*/
private function parseFeatures(string $rawBody): array
private function parseFeatures(array $body): array
{
$features = [];
$body = json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
assert(is_array($body));

$globalSegments = $this->parseSegments($body['segments'] ?? []);

if (!isset($body['features']) || !is_array($body['features'])) {
Expand Down Expand Up @@ -253,7 +281,7 @@ private function setLastValidState(string $data): void
}

/**
* @param array<array{id: int, constraints: array<ConstraintArray>}> $segmentsRaw
* @param array<SegmentArray> $segmentsRaw
*
* @return array<Segment>
*/
Expand Down
43 changes: 43 additions & 0 deletions tests/Repository/DefaultUnleashRepositoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\HttpFactory;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use LogicException;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
Expand All @@ -15,6 +16,7 @@
use Unleash\Client\Bootstrap\JsonSerializableBootstrapProvider;
use Unleash\Client\Configuration\UnleashConfiguration;
use Unleash\Client\DTO\Feature;
use Unleash\Client\Enum\CacheKey;
use Unleash\Client\Event\FetchingDataFailedEvent;
use Unleash\Client\Event\UnleashEvents;
use Unleash\Client\Exception\HttpResponseException;
Expand Down Expand Up @@ -424,4 +426,45 @@ public function testFallbackStaleCacheDifferentHandlers()
$this->expectException(HttpResponseException::class);
$repository->getFeatures();
}

public function testGetFeaturesCorruptedBodyIsNotStored()
{
$this->mockHandler->append(new Response(
200,
['Content-Type' => 'application/json'],
'{"version":1,"features":['
));

$cache = $this->getRealCache();
$failCount = 0;

$eventDispatcher = new EventDispatcher();
$eventDispatcher->addListener(
UnleashEvents::FETCHING_DATA_FAILED,
function (FetchingDataFailedEvent $event) use (&$failCount): void {
self::assertInstanceOf(InvalidValueException::class, $event->getException());
++$failCount;
}
);

$repository = new DefaultUnleashRepository(
new Client([
'handler' => $this->handlerStack,
]),
new HttpFactory(),
(new UnleashConfiguration('', '', ''))
->setCache($cache)
->setFetchingEnabled(true)
->setTtl(5)
->setBootstrapProvider(new JsonSerializableBootstrapProvider(['features' => []]))
->setEventDispatcher($eventDispatcher)
);

$features = $repository->getFeatures();
$lastResponse = $cache->get(CacheKey::FEATURES_RESPONSE);

self::assertEmpty($features);
self::assertNull($lastResponse);
self::assertEquals(1, $failCount);
}
}