/
AbstractTraceableHttpClient.php
98 lines (83 loc) · 2.66 KB
/
AbstractTraceableHttpClient.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
declare(strict_types=1);
namespace Sentry\SentryBundle\Tracing\HttpClient;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Sentry\State\HubInterface;
use Sentry\Tracing\SpanContext;
use Symfony\Component\HttpClient\Response\ResponseStream;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Symfony\Contracts\HttpClient\ResponseStreamInterface;
use Symfony\Contracts\Service\ResetInterface;
/**
* This is an implementation of the {@see HttpClientInterface} that decorates
* an existing http client to support distributed tracing capabilities.
*
* @internal
*/
abstract class AbstractTraceableHttpClient implements HttpClientInterface, ResetInterface, LoggerAwareInterface
{
/**
* @var HttpClientInterface
*/
protected $client;
/**
* @var HubInterface
*/
protected $hub;
public function __construct(HttpClientInterface $client, HubInterface $hub)
{
$this->client = $client;
$this->hub = $hub;
}
/**
* {@inheritdoc}
*/
public function request(string $method, string $url, array $options = []): ResponseInterface
{
$span = null;
$parent = $this->hub->getSpan();
if (null !== $parent) {
$headers = $options['headers'] ?? [];
$headers['sentry-trace'] = $parent->toTraceparent();
$options['headers'] = $headers;
$context = new SpanContext();
$context->setOp('http.client');
$context->setDescription('HTTP ' . $method);
$context->setTags([
'http.method' => $method,
'http.url' => $url,
]);
$span = $parent->startChild($context);
}
return new TraceableResponse($this->client, $this->client->request($method, $url, $options), $span);
}
/**
* {@inheritdoc}
*
* @param AbstractTraceableResponse|iterable<AbstractTraceableResponse> $responses
*/
public function stream($responses, float $timeout = null): ResponseStreamInterface
{
if ($responses instanceof AbstractTraceableResponse) {
$responses = [$responses];
}
return new ResponseStream(AbstractTraceableResponse::stream($this->client, $responses, $timeout));
}
public function reset(): void
{
if ($this->client instanceof ResetInterface) {
$this->client->reset();
}
}
/**
* {@inheritdoc}
*/
public function setLogger(LoggerInterface $logger): void
{
if ($this->client instanceof LoggerAwareInterface) {
$this->client->setLogger($logger);
}
}
}