|
1 | 1 | #include "wilson_trace.h"
|
2 | 2 |
|
| 3 | +#include <util/generic/algorithm.h> |
| 4 | +#include <util/string/hex.h> |
| 5 | + |
3 | 6 | namespace NWilson {
|
| 7 | + TTraceId TTraceId::FromTraceparentHeader(const TStringBuf header) { |
| 8 | + constexpr size_t versionChars = 2; // Only version 0 is supported |
| 9 | + constexpr size_t versionStart = 0; |
| 10 | + |
| 11 | + constexpr size_t traceIdChars = 32; |
| 12 | + constexpr size_t traceIdStart = versionStart + versionChars + 1; |
| 13 | + static_assert(traceIdChars == TTraceId::GetTraceIdSize() * 2); |
| 14 | + |
| 15 | + constexpr size_t parentSpanIdChars = 16; |
| 16 | + constexpr size_t parentSpanIdStart = traceIdStart + traceIdChars + 1; |
| 17 | + static_assert(parentSpanIdChars == TTraceId::GetSpanIdSize() * 2); |
| 18 | + |
| 19 | + constexpr size_t traceFlagsChars = 2; |
| 20 | + constexpr size_t traceFlagsStart = parentSpanIdStart + parentSpanIdChars + 1; |
| 21 | + |
| 22 | + constexpr size_t expectedHeaderSize = |
| 23 | + versionChars + traceIdChars + parentSpanIdChars + traceFlagsChars + 3; |
| 24 | + |
| 25 | + if (header.Size() != expectedHeaderSize) { |
| 26 | + return {}; |
| 27 | + } |
| 28 | + |
| 29 | + auto isHex = [](char c) { |
| 30 | + return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); |
| 31 | + }; |
| 32 | + |
| 33 | + if (!AllOf(header.substr(versionStart, versionChars), isHex) || |
| 34 | + !AllOf(header.substr(traceIdStart, traceIdChars), isHex) || |
| 35 | + !AllOf(header.substr(parentSpanIdStart, parentSpanIdChars), isHex) || |
| 36 | + !AllOf(header.substr(traceFlagsStart, traceFlagsChars), isHex)) { |
| 37 | + return {}; |
| 38 | + } |
| 39 | + |
| 40 | + if (header[traceIdStart - 1] != '-' || header[parentSpanIdStart - 1] != '-' || header[traceIdChars - 1] != '-') { |
| 41 | + return {}; |
| 42 | + } |
| 43 | + |
| 44 | + ui8 version; |
| 45 | + HexDecode(header.Data(), versionChars, &version); |
| 46 | + if (version != 0) { |
| 47 | + return {}; |
| 48 | + } |
| 49 | + |
| 50 | + TTrace traceId; |
| 51 | + ui64 spanId; |
| 52 | + static_assert(traceIdChars == 2 * sizeof(traceId)); |
| 53 | + static_assert(parentSpanIdChars == 2 * sizeof(spanId)); |
| 54 | + HexDecode(header.Data() + traceIdStart, traceIdChars, &traceId); |
| 55 | + HexDecode(header.Data() + parentSpanIdStart, parentSpanIdChars, &spanId); |
| 56 | + |
| 57 | + if ((traceId[0] == 0 && traceId[1] == 0) || spanId == 0) { |
| 58 | + return {}; |
| 59 | + } |
| 60 | + |
| 61 | + return TTraceId(traceId, spanId, 15, Max<ui32>()); |
| 62 | + } |
| 63 | + |
| 64 | + TString TTraceId::GetHexTraceId() const { |
| 65 | + return HexEncode(GetTraceIdPtr(), GetTraceIdSize()); |
| 66 | + } |
4 | 67 | }
|
0 commit comments