Skip to content

Commit

Permalink
Do not store invalid response
Browse files Browse the repository at this point in the history
  • Loading branch information
v.bartusevicius committed Nov 8, 2023
1 parent 373b7d6 commit 0c6b9f7
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Repository/DefaultUnleashRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ public function getFeatures(): iterable
$response = $this->httpClient->sendRequest($request);
if ($response->getStatusCode() === 200) {
$data = (string) $response->getBody();
json_decode($data, true, 512, JSON_THROW_ON_ERROR);
$this->setLastValidState($data);
} else {
throw new HttpResponseException("Invalid status code: '{$response->getStatusCode()}'");
Expand Down
44 changes: 44 additions & 0 deletions tests/Repository/DefaultUnleashRepositoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\HttpFactory;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use JsonException;
use LogicException;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
Expand All @@ -15,6 +17,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 +427,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(JsonException::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);
}
}

0 comments on commit 0c6b9f7

Please sign in to comment.