8000 [HttpClient] Add a Stopwatch on TraceableHttpClient by jderusse · Pull Request #38688 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[HttpClient] Add a Stopwatch on TraceableHttpClient #38688

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

Merged
merged 1 commit into from
Oct 23, 2020
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,7 @@ class Theme {
'doctrine': '#ff6633',
'messenger_middleware': '#bdb81e',
'controller.argument_value_resolver': '#8c5de6',
'http_client': '#ffa333',
};

this.customCategoryColors = [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpClient\TraceableHttpClient;

Expand All @@ -36,7 +37,7 @@ public function process(ContainerBuilder $container)

foreach ($container->findTaggedServiceIds($this->clientTag) as $id => $tags) {
$container->register('.debug.'.$id, TraceableHttpClient::class)
->setArguments([new Reference('.debug.'.$id.'.inner')])
->setArguments([new Reference('.debug.'.$id.'.inner'), new Reference('debug.stopwatch', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)])
->setDecoratedService($id);
$container->getDefinition('data_collector.http_client')
->addMethodCall('registerClient', [$id, new Reference('.debug.'.$id)]);
Expand Down
100 changes: 81 additions & 19 deletions src/Symfony/Component/HttpClient/Response/TraceableResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@

namespace Symfony\Component\HttpClient\Response;

use Symfony\Component\HttpClient\Chunk\ErrorChunk;
use Symfony\Component\HttpClient\Exception\ClientException;
use Symfony\Component\HttpClient\Exception\RedirectionException;
use Symfony\Component\HttpClient\Exception\ServerException;
use Symfony\Component\HttpClient\TraceableHttpClient;
use Symfony\Component\Stopwatch\StopwatchEvent;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
Expand All @@ -32,57 +34,98 @@ class TraceableResponse implements ResponseInterface, StreamableInterface
private $client;
private $response;
private $content;
private $event;

public function __construct(HttpClientInterface $client, ResponseInterface $response, &$content)
public function __construct(HttpClientInterface $client, ResponseInterface $response, &$content, StopwatchEvent $event = null)
{
$this->client = $client;
$this->response = $response;
$this->content = &$content;
$this->event = $event;
}

public function __destruct()
{
try {
$this->response->__destruct();
} finally {
if ($this->event && $this->event->isStarted()) {
$this->event->stop();
}
}
}

public function getStatusCode(): int
{
return $this->response->getStatusCode();
try {
return $this->response->getStatusCode();
} finally {
if ($this->event && $this->event->isStarted()) {
$this->event->lap();
}
}
}

public function getHeaders(bool $throw = true): array
{
return $this->response->getHeaders($throw);
try {
return $this->response->getHeaders($throw);
} finally {
if ($this->event && $this->event->isStarted()) {
$this->event->lap();
}
}
}

public function getContent(bool $throw = true): string
{
if (false === $this->content) {
return $this->response->getContent($throw);
}
try {
if (false === $this->content) {
return $this->response->getContent($throw);
}

$this->content = $this->response->getContent(false);
$this->content = $this->response->getContent(false);

if ($throw) {
$this->check 10000 StatusCode($this->response->getStatusCode());
}
if ($throw) {
$this->checkStatusCode($this->response->getStatusCode());
}

return $this->content;
return $this->content;
} finally {
if ($this->event && $this->event->isStarted()) {
$this->event->stop();
}
}
}

public function toArray(bool $throw = true): array
{
if (false === $this->content) {
return $this->response->toArray($throw);
}
try {
if (false === $this->content) {
return $this->response->toArray($throw);
}

$this->content = $this->response->toArray(false);
$this->content = $this->response->toArray(false);

if ($throw) {
$this->checkStatusCode($this->response->getStatusCode());
}
if ($throw) {
$this->checkStatusCode($this->response->getStatusCode());
}

return $this->content;
return $this->content;
} finally {
if ($this->event && $this->event->isStarted()) {
$this->event->stop();
}
}
}

public function cancel(): void
{
$this->response->cancel();

if ($this->event && $this->event->isStarted()) {
$this->event->stop();
}
}

public function getInfo(string $type = null)
Expand Down Expand Up @@ -129,9 +172,28 @@ public static function stream(HttpClientInterface $client, iterable $responses,

$traceableMap[$r->response] = $r;
$wrappedResponses[] = $r->response;
if ($r->event && !$r->event->isStarted()) {
$r->event->start();
}
}

foreach ($client->stream($wrappedResponses, $timeout) as $r => $chunk) {
if ($traceableMap[$r]->event && $traceableMap[$r]->event->isStarted()) {
try {
if ($chunk->isTimeout() || !$chunk->isLast()) {
$traceableMap[$r]->event->lap();
} else {
$traceableMap[$r]->event->stop();
}
} catch (TransportExceptionInterface $e) {
$traceableMap[$r]->event->stop();
if ($chunk instanceof ErrorChunk) {
$chunk->didThrow(false);
} else {
$chunk = new ErrorChunk($chunk->getOffset(), $e);
}
}
}
yield $traceableMap[$r] => $chunk;
}
}
Expand Down
90 changes: 90 additions & 0 deletions src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@
namespace Symfony\Component\HttpClient\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\Exception\ClientException;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\NativeHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
use Symfony\Component\HttpClient\TraceableHttpClient;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\Test\TestHttpServer;

Expand Down Expand Up @@ -115,4 +117,92 @@ public function testStream()
$this->assertGreaterThan(1, \count($chunks));
$this->assertSame('Symfony is awesome!', implode('', $chunks));
}

public function testStopwatch()
{
$sw = new Stopwatch(true);
$sut = new TraceableHttpClient(new NativeHttpClient(), $sw);
$response = $sut->request('GET', 'http://localhost:8057');

$response->getStatusCode();
$response->getHeaders();
$response->getContent();

$this->assertArrayHasKey('__root__', $sections = $sw->getSections());
$this->assertCount(1, $events = $sections['__root__']->getEvents());
$this->assertArrayHasKey('GET http://localhost:8057', $events);
$this->assertCount(3, $events['GET http://localhost:8057']->getPeriods());
$this->assertGreaterThan(0.0, $events['GET http://localhost:8057']->getDuration());
}

public function testStopwatchError()
{
$sw = new Stopwatch(true);
$sut = new TraceableHttpClient(new NativeHttpClient(), $sw);
$response = $sut->request('GET', 'http://localhost:8057/404');

try {
$response->getContent();
$this->fail('Response should have thrown an exception');
} catch (ClientException $e) {
// no-op
}

$this->assertArrayHasKey('__root__', $sections = $sw->getSections());
$this->assertCount(1, $events = $sections['__root__']->getEvents());
$this->assertArrayHasKey('GET http://localhost:8057/404', $events);
$this->assertCount(1, $events['GET http://localhost:8057/404']->getPeriods());
}

public function testStopwatchStream()
{
$sw = new Stopwatch(true);
$sut = new TraceableHttpClient(new NativeHttpClient(), $sw);
$response = $sut->request('GET', 'http://localhost:8057');

$chunkCount = 0;
foreach ($sut->stream([$response]) as $chunk) {
++$chunkCount;
}

$this->assertArrayHasKey('__root__', $sections = $sw->getSections());
$this->assertCount(1, $events = $sections['__root__']->getEvents());
$this->assertArrayHasKey('GET http://localhost:8057', $events);
$this->assertGreaterThanOrEqual($chunkCount, \count($events['GET http://localhost:8057']->getPeriods()));
}

public function testStopwatchStreamError()
{
$sw = new Stopwatch(true);
$sut = new TraceableHttpClient(new NativeHttpClient(), $sw);
$response = $sut->request('GET', 'http://localhost:8057/404');

try {
$chunkCount = 0;
foreach ($sut->stream([$response]) as $chunk) {
++$chunkCount;
}
$this->fail('Response should have thrown an exception');
} catch (ClientException $e) {
// no-op
}

$this->assertArrayHasKey('__root__', $sections = $sw->getSections());
$this->assertCount(1, $events = $sections['__root__']->getEvents());
$this->assertArrayHasKey('GET http://localhost:8057/404', $events);
$this->assertGreaterThanOrEqual($chunkCount, \count($events['GET http://localhost:8057/404']->getPeriods()));
}

public function testStopwatchDestruct()
{
$sw = new Stopwatch(true);
$sut = new TraceableHttpClient(new NativeHttpClient(), $sw);
$sut->request('GET', 'http://localhost:8057');

$this->assertArrayHasKey('__root__', $sections = $sw->getSections());
$this->assertCount(1, $events = $sections['__root__']->getEvents());
$this->assertArrayHasKey('GET http://localhost:8057', $events);
$this->assertCount(1, $events['GET http://localhost:8057']->getPeriods());
$this->assertGreaterThan(0.0, $events['GET http://localhost:8057']->getDuration());
}
}
D98E
7 changes: 5 additions & 2 deletions src/Symfony/Component/HttpClient/TraceableHttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpClient\Response\ResponseStream;
use Symfony\Component\HttpClient\Response\TraceableResponse;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Symfony\Contracts\HttpClient\ResponseStreamInterface;
Expand All @@ -27,10 +28,12 @@ final class TraceableHttpClient implements HttpClientInterface, ResetInterface,
{
private $client;
private $tracedRequests = [];
private $stopwatch;

public function __construct(HttpClientInterface $client)
public function __construct(HttpClientInterface $client, Stopwatch $stopwatch = null)
{
$this->client = $client;
$this->stopwatch = $stopwatch;
}

/**
Expand Down Expand Up @@ -62,7 +65,7 @@ public function request(string $method, string $url, array $options = []): Respo
}
};

return new TraceableResponse($this->client, $this->client->request($method, $url, $options), $content);
return new TraceableResponse($this->client, $this->client->request($method, $url, $options), $content, null === $this->stopwatch ? null : $this->stopwatch->start("$method $url", 'http_client'));
}

/**
Expand Down
0