-
Notifications
You must be signed in to change notification settings - Fork 0
/
JaegerBaggagePropagator.php
85 lines (67 loc) · 2.75 KB
/
JaegerBaggagePropagator.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
<?php
declare(strict_types=1);
namespace OpenTelemetry\Extension\Propagator\Jaeger;
use OpenTelemetry\API\Baggage\Baggage;
use OpenTelemetry\API\Baggage\Entry; /** @phan-suppress-current-line PhanUnreferencedUseNormal */
use OpenTelemetry\Context\Context;
use OpenTelemetry\Context\ContextInterface;
use OpenTelemetry\Context\Propagation\ArrayAccessGetterSetter;
use OpenTelemetry\Context\Propagation\PropagationGetterInterface;
use OpenTelemetry\Context\Propagation\PropagationSetterInterface;
use OpenTelemetry\Context\Propagation\TextMapPropagatorInterface;
/**
* JaegerBaggagePropagator is a baggage propagator that supports the specification for the header
* "uberctx" used for baggage propagation.
* (https://www.jaegertracing.io/docs/1.52/client-libraries/#baggage)
*/
class JaegerBaggagePropagator implements TextMapPropagatorInterface
{
private const UBER_BAGGAGE_HEADER_PREFIX = 'uberctx-';
private static ?TextMapPropagatorInterface $instance = null;
public static function getInstance(): TextMapPropagatorInterface
{
if (self::$instance === null) {
self::$instance = new JaegerBaggagePropagator();
}
return self::$instance;
}
public function fields(): array
{
return [];
}
/** {@inheritdoc} */
public function inject(&$carrier, ?PropagationSetterInterface $setter = null, ?ContextInterface $context = null): void
{
$setter ??= ArrayAccessGetterSetter::getInstance();
$context ??= Context::getCurrent();
$baggage = Baggage::fromContext($context);
if ($baggage->isEmpty()) {
return;
}
/** @var Entry $entry */
foreach ($baggage->getAll() as $key => $entry) {
$key = self::UBER_BAGGAGE_HEADER_PREFIX . $key;
$value = rawurlencode((string) $entry->getValue());
$setter->set($carrier, $key, $value);
}
}
/** {@inheritdoc} */
public function extract($carrier, ?PropagationGetterInterface $getter = null, ?ContextInterface $context = null): ContextInterface
{
$getter ??= ArrayAccessGetterSetter::getInstance();
$context ??= Context::getCurrent();
$baggageKeys = $getter->keys($carrier);
if ($baggageKeys === []) {
return $context;
}
$baggageBuilder = Baggage::getBuilder();
foreach ($baggageKeys as $key) {
if (str_starts_with($key, self::UBER_BAGGAGE_HEADER_PREFIX)) {
$baggageKey = substr($key, strlen(self::UBER_BAGGAGE_HEADER_PREFIX));
$value = $getter->get($carrier, $key) ?? '';
$baggageBuilder->set($baggageKey, rawurldecode($value));
}
}
return $context->withContextValue($baggageBuilder->build());
}
}