forked from nginx/nginx-otel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrace_context.hpp
More file actions
89 lines (71 loc) · 2.45 KB
/
Copy pathtrace_context.hpp
File metadata and controls
89 lines (71 loc) · 2.45 KB
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
#pragma once
#include <array>
#include <opentelemetry/trace/trace_id.h>
#include <opentelemetry/trace/span_id.h>
#include <opentelemetry/trace/propagation/http_trace_context.h>
#include <opentelemetry/sdk/trace/random_id_generator.h>
#include "str_view.hpp"
struct TraceContext {
opentelemetry::trace::TraceId traceId;
opentelemetry::trace::SpanId spanId;
bool sampled;
StrView state;
static const auto Size =
opentelemetry::trace::propagation::kTraceParentSize;
static TraceContext generate(bool sampled, TraceContext parent = {})
{
opentelemetry::sdk::trace::RandomIdGenerator idGen;
return {parent.traceId.IsValid() ?
parent.traceId : idGen.GenerateTraceId(),
idGen.GenerateSpanId(),
sampled,
parent.state};
}
static TraceContext parse(StrView trace, StrView state)
{
using namespace opentelemetry::trace::propagation;
std::array<StrView, 4> parts;
if (detail::SplitString(trace, '-', parts.data(), 4) != 4) {
return TraceContext{};
}
auto version = parts[0];
auto traceId = parts[1];
auto spanId = parts[2];
auto flags = parts[3];
if (version != "00") {
return TraceContext{};
}
if (traceId.size() != kTraceIdSize || spanId.size() != kSpanIdSize ||
flags.size() != kTraceFlagsSize)
{
return TraceContext{};
}
if (!detail::IsValidHex(traceId) || !detail::IsValidHex(spanId) ||
!detail::IsValidHex(flags))
{
return TraceContext{};
}
return {HttpTraceContext::TraceIdFromHex(traceId),
HttpTraceContext::SpanIdFromHex(spanId),
HttpTraceContext::TraceFlagsFromHex(flags).IsSampled(),
state};
}
static void serialize(const TraceContext& tc, char* out)
{
using namespace opentelemetry::trace::propagation;
namespace nostd = opentelemetry::nostd;
*out++ = '0';
*out++ = '0';
*out++ = '-';
tc.traceId.ToLowerBase16(
nostd::span<char, kTraceIdSize>{out, kTraceIdSize});
out += kTraceIdSize;
*out++ = '-';
tc.spanId.ToLowerBase16(
nostd::span<char, kSpanIdSize>{out, kSpanIdSize});
out += kSpanIdSize;
*out++ = '-';
*out++ = '0';
*out++ = tc.sampled ? '1' : '0';
}
};