10000 [HttpClient] Added TraceableHttpClient and WebProfiler panel by jeremyFreeAgent · Pull Request #30494 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[HttpClient] Added TraceableHttpClient and WebProfiler panel #30494

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

Closed
Closed
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
[HttpClient] Added TraceableHttpClient and WebProfiler panel
  • Loading branch information
jeremyFreeAgent authored and nicolas-grekas committed Jun 19, 2019
commit b4b2097cb2635004d4e844c230706ead4425ef7a
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
use Symfony\Component\Form\FormTypeInterface;
use Symfony\Component\HttpClient\Psr18Client;
use Symfony\Component\HttpClient\ScopingHttpClient;
use Symfony\Component\HttpClient\TraceableHttpClient;
use Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
Expand Down Expand Up @@ -1874,6 +1875,15 @@ private function registerHttpClientConfiguration(array $config, ContainerBuilder
{
$loader->load('http_client.xml');

$collectorDefinition = $container->getDefinition('data_collector.http_client');

if (!$debug = $container->getParameter('kernel.debug')) {
$container->removeDefinition('debug.http_client');
$collectorDefinition
->setMethodCalls([])
->clearTag('data_collector');
}

$container->getDefinition('http_client')->setArguments([$config['default_options'] ?? [], $config['max_host_connections'] ?? 6]);

if (!$hasPsr18 = interface_exists(ClientInterface::class)) {
Expand All @@ -1898,6 +1908,19 @@ private function registerHttpClientConfiguration(array $config, ContainerBuilder
->setArguments([new Reference('http_client'), [$scope => $scopeConfig], $scope]);
}

if ($debug) {
Copy link
Member

Choose a reason for hiding this comment

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

It could be interesting to add a tag to the service a this point, and to do the wiring logic in a compiler pass for all services having this tag. It will allow bundles to easily plug their own clients in the profiler.

For instance, we have this use case in API Platform.

Copy link
Contributor

Choose a reason for hiding this comment

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

I'm almost done except your comment.

To be sure to get your point I looked the Messenger stuff. So we are ok to add a tag to all http client here https://github.com/symfony/symfony/blob/4.4/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php#L1946-L1953
Like http_client.client ?

Then adding a HttpClientPass to make the call to the dataCollector in all service tagged with http_client.client. (if data_collector is registered of course).

Right ?

$innerId = '.'.$name.'.inner';

$container->setDefinition($innerId, $container->getDefinition($name)
->replaceArgument(0, new Reference('debug.http_client.inner'))
);

$container->register($name, TraceableHttpClient::class)
->setArguments([new Reference($innerId)]);

$collectorDefinition->addMethodCall('addClient', [$name, new Reference($name)]);
}

$container->registerAliasForArgument($name, HttpClientInterface::class);

if ($hasPsr18) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,17 @@
<argument type="service" id="Psr\Http\Message\StreamFactoryInterface" on-invalid="ignore" />
</service>
<service id="Psr\Http\Client\ClientInterface" alias="psr18.http_client" />

<service id="data_collector.http_client" class="Symfony\Component\HttpClient\DataCollector\HttpClientDataCollector">
<tag name="data_collector" template="@WebProfiler/Collector/http_client.html.twig" id="http_client" priority="240" />
<call method="addClient">
<argument>http_client</argument>
<argument type="service" id="debug.http_client" />
</call>
</service>

<service id="debug.http_client" class="Symfony\Component\HttpClient\TraceableHttpClient" decorates="http_client">
<argument type="service" id="debug.http_client.inner" />
</service>
Copy link
Member

Choose a reason for hiding this comment

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

I would move these definitions to a http_client_debug.xml file like done for other components.

</services>
</container>
3 changes: 2 additions & 1 deletion src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"symfony/polyfill-intl-icu": "~1.0",
"symfony/form": "^4.3|^5.0",
"symfony/expression-language": "^3.4|^4.0|^5.0",
"symfony/http-client": "^4.3|^5.0",
"symfony/http-client": "^4.4|^5.0",
"symfony/mailer": "^4.3|^5.0",
"symfony/messenger": "^4.3|^5.0",
"symfony/mime": "^4.3|^5.0",
Expand Down Expand Up @@ -71,6 +71,7 @@
"symfony/console": "<4.3",
"symfony/dotenv": "<4.2",
"symfony/dom-crawler": "<4.3",
"symfony/http-client": "<4.4",
"symfony/form": "<4.3",
"symfony/messenger": "<4.3",
"symfony/property-info": "<3.4",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
{% extends '@WebProfiler/Profiler/layout.html.twig' %}

{% block toolbar %}
{% if collector.requestCount %}
{% set icon %}
{{ include('@WebProfiler/Icon/http-client.svg') }}
{% set status_color = '' %}
<span class="sf-toolbar- 6D47 value">{{ collector.requestCount }}</span>
{% endset %}

{{ include('@WebProfiler/Profiler/toolbar_item.html.twig', { link: profiler_url, status: status_color }) }}
{% endif %}
{% endblock %}

{% block menu %}
<span class="label {{ collector.requestCount == 0 ? 'disabled' }}">
<span class="icon">{{ include('@WebProfiler/Icon/http-client.svg') }}</span>
<strong>HTTP Client</strong>
{% if collector.requestCount %}
<span class="count">
Copy link
Contributor

Choose a reason for hiding this comment

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

I think we should add colors for warning and error codes here.

{{ collector.requestCount }}
</span>
{% endif %}
</span>
{% endblock %}

{% block panel %}
<h2>HTTP Client</h2>
{% if collector.requestCount == 0 %}
<div class="empty">
<p>No HTTP requests were made.</p>
</div>
{% else %}
<div class="metrics">
<div class="metric">
<span class="value">{{ collector.requestCount }}</span>
<span class="label">Total requests</span>
</div>
<div class="metric">
<span class="value">{{ collector.errorCount }}</span>
<span class="label">HTTP errors</span>
</div>
</div>
<h2>Clients</h2>
<div class="sf-tabs">
{% for name, client in collector.clients %}
<div class="tab {{ client.traces|length == 0 ? 'disabled' }}">
<h3 class="tab-title">{{ name }} <span class="badge">{{ client.traces|length }}</span></h3>
<div class="tab-content">
{% if client.traces|length == 0 %}
<div class="empty">
<p>No requests were made with the "{{ name }}" service.</p>
</div>
{% else %}
<h4>Requests</h4>
{% for trace in client.traces %}
<table>
<thead>
<tr>
<th>
<span class="label">{{ trace.method }}</span>
</th>
<th>
{{ trace.url }}
{% if trace.options is not empty %}
{{ profiler_dump(trace.options, maxDepth=1) }}
{% endif %}
</th>
</tr>
</thead>
<tbody>
<tr>
<th>
{% if trace.http_code >= 500 %}
{% set responseStatus = 'error' %}
{% elseif trace.http_code >= 400 %}
{% set responseStatus = 'warning' %}
{% else %}
{% set responseStatus = 'success' %}
{% endif %}
<span class="label status-{{ responseStatus }}">
{{ trace.http_code }}
</span>
</th>
<td>
{{ profiler_dump(trace.info, maxDepth=1) }}
</td>
</tr>
</tbody>
</table>
{% endfor %}
{% endif %}
</div>
</div>
{% endfor %}
{% endif %}
</div>
{% endblock %}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpClient\DataCollector;

use Symfony\Component\HttpClient\TraceableHttpClient;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;

/**
* @author Jérémy Romey <jeremy@free-agent.fr>
*/
final class HttpClientDataCollector extends DataCollector
{
/**
* @var TraceableHttpClient[]
*/
private $clients = [];

public function addClient(string $name, TraceableHttpClient $client)
{
$this->clients[$name] = $client;
}

/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Exception $exception = null)
{
$this->data = [
'clients' => [],
'request_count' => 0,
'error_count' => 0,
];

foreach ($this->clients as $name => $client) {
$traces = $client->getTraces();

$this->data['request_count'] += \count($traces);
$errorCount = 0;

foreach ($traces as $i => $trace) {
if (400 <= ($trace['info']['http_code'] ?? 0)) {
++$errorCount;
}

$info = $trace['info'];
$traces[$i]['http_code'] = $info['http_code'];

unset($info['filetime'], $info['http_code'], $info['ssl_verify_result'], $info['content_type']);

if ($trace['method'] === $info['http_method']) {
unset($info['http_method']);
}

if ($trace['url'] === $info['url']) {
unset($info['url']);
}

foreach ($info as $k => $v) {
if (!$v || (is_numeric($v) && 0 > $v)) {
unset($info[$k]);
}
}

$traces[$i]['info'] = $this->cloneVar($info);
$traces[$i]['options'] = $this->cloneVar($trace['options']);
}

$this->data['clients'][$name] = [
'traces' => $traces,
'error_count' => $errorCount,
];
$this->data['error_count'] += $errorCount;
}
}

public function getClients(): array
{
return $this->data['clients'] ?? [];
}

public function getRequestCount(): int
{
return $this->data['request_count'] ?? 0;
}

public function getErrorCount(): int
{
return $this->data['error_count'] ?? 0;
}

/**
* {@inheritdoc}
*/
public function reset()
{
$this->data = [];
foreach ($this->clients as $client) {
$client->clearTraces();
}
}

/**
* {@inheritdoc}
*/
public function getName(): string
{
return 'http_client';
}
}
73 changes: 73 additions & 0 deletions src/Symfony/Component/HttpClient/TraceableHttpClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpClient;

use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Symfony\Contracts\HttpClient\ResponseStreamInterface;

/**
* @author Jérémy Romey <jeremy@free-agent.fr>
*/
final class TraceableHttpClient implements HttpClientInterface
{
private $client;
private $traces = [];

public function __construct(HttpClientInterface $client)
{
$this->client = $client;
}

/**
* {@inheritdoc}
*/
public function request(string $method, string $url, array $options = []): ResponseInterface
{
$traceInfo = [];
$this->traces[] = [
'method' => $method,
'url' => $url,
'options' => $options,
'info' => &$traceInfo,
];
$onProgress = $options['on_progress'] ?? null;

$options['on_progress'] = function (int $dlNow, int $dlSize, array $info) use (&$traceInfo, $onProgress) {
$traceInfo = $info;

if ($onProgress) {
$onProgress($dlNow, $dlSize, $info);
}
};

return $this->client->request($method, $url, $options);
}

/**
* {@inheritdoc}
*/
public function stream($responses, float $timeout = null): ResponseStreamInterface
{
return $this->client->stream($responses, $timeout);
}

public function getTraces(): array
{
return $this->traces;
}

public function clearTraces()
{
$this->traces = [];
}
}
0