This repository was archived by the owner on Oct 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathGrpcMetadataPropagator.php
101 lines (91 loc) · 2.75 KB
/
GrpcMetadataPropagator.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
99
100
101
<?php
/**
* Copyright 2017 OpenCensus Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace OpenCensus\Trace\Propagator;
use OpenCensus\Trace\SpanContext;
/**
* This propagator contains the logic for propagating SpanContext over
* grpc using its request metadata. It will default to using the BinaryFormatter
* to serialize/deserialize SpanContext.
*/
class GrpcMetadataPropagator implements PropagatorInterface
{
const DEFAULT_METADATA_KEY = 'grpc-trace-bin';
/**
* @var FormatterInterface
*/
private $formatter;
/**
* @var string
*/
private $key;
/**
* Create a new GrpcMetadataPropagator
*
* @param FormatterInterface $formatter [optional] The formatter used to serialize/deserialize SpanContext
* **Defaults to** a new BinaryFormatter.
* @param string $key [optional] The grpc metadata key to store/retrieve the encoded SpanContext.
* **Defaults to** `grpc-trace-bin`
*/
public function __construct(FormatterInterface $formatter = null, $key = null)
{
$this->formatter = $formatter ?: new BinaryFormatter();
$this->key = $key ?: self::DEFAULT_METADATA_KEY;
}
/**
* Generate a SpanContext object from the all the HTTP headers
*
* @param array $metadata
* @return SpanContext
*/
public function extract($metadata)
{
if (array_key_exists($this->key, $metadata)) {
return $this->formatter->deserialize($metadata[$this->key]);
}
return new SpanContext();
}
/**
* Persiste the current SpanContext back into the results of this request
*
* @param SpanContext $context
* @param array $container
* @return array
*/
public function inject(SpanContext $context, $metadata)
{
$metadata[$this->key] = [$this->formatter->serialize($context)];
return $metadata;
}
/**
* Fetch the formatter for propagating the SpanContext
*
* @return FormatterInterface
*/
public function formatter()
{
return $this->formatter;
}
/**
* Return the key used to propagate the SpanContext
*
* @return string
*/
public function key()
{
return $this->key;
}
}