diff --git a/src/oc_propagation_http_b3.erl b/src/oc_propagation_http_b3.erl index f928c65..399aef6 100644 --- a/src/oc_propagation_http_b3.erl +++ b/src/oc_propagation_http_b3.erl @@ -39,7 +39,7 @@ to_headers(#span_ctx{trace_id=TraceId, trace_options=TraceOptions}) -> Options = case TraceOptions band 1 of 1 -> "1"; _ -> "0" end, %% iolist_to_binary only needed for versions before otp-21 - EncodedTraceId = iolist_to_binary(io_lib:format("~32.16.0b", [TraceId])), + EncodedTraceId = encode_trace_id(TraceId), EncodedSpanId = iolist_to_binary(io_lib:format("~16.16.0b", [SpanId])), [{?B3_TRACE_ID, EncodedTraceId}, {?B3_SPAN_ID, EncodedSpanId}, @@ -47,6 +47,13 @@ to_headers(#span_ctx{trace_id=TraceId, to_headers(undefined) -> []. +encode_trace_id(TraceId) -> + encode_trace_id(TraceId, binary:encode_unsigned(TraceId)). +encode_trace_id(TraceId, TraceIdBin) when bit_size(TraceIdBin) == 64 -> + iolist_to_binary(io_lib:format("~16.16.0b", [TraceId])); +encode_trace_id(TraceId, _TraceIdBin) -> + iolist_to_binary(io_lib:format("~32.16.0b", [TraceId])). + -spec from_headers(list() | map()) -> maybe(opencensus:span_ctx()). from_headers(Headers) when is_map(Headers) -> from_headers(maps:to_list(Headers)); diff --git a/test/oc_span_ctx_SUITE.erl b/test/oc_span_ctx_SUITE.erl index 3b55a51..949c551 100644 --- a/test/oc_span_ctx_SUITE.erl +++ b/test/oc_span_ctx_SUITE.erl @@ -134,6 +134,15 @@ b3_encode_decode_headers(_Config) -> compare_b3_headers(Encoded, Headers), ?assertEqual(Decoded, oc_propagation_http_b3:from_headers(Encoded)), + %% TraceId: 4bf92f3577b34da6 + %% SpanId: 00f067aa0ba902b7 + %% Enabled: true + ShortTraceIDHeaders = ?B3_HEADERS(<<"4bf92f3577b34da6">>, <<"00f067aa0ba902b7">>, <<"1">>), + ShortTraceIDDecoded = oc_propagation_http_b3:from_headers(ShortTraceIDHeaders), + ShortTraceIDEncoded = oc_propagation_http_b3:to_headers(ShortTraceIDDecoded), + compare_b3_headers(ShortTraceIDEncoded, ShortTraceIDHeaders), + ?assertEqual(ShortTraceIDDecoded, oc_propagation_http_b3:from_headers(ShortTraceIDEncoded)), + %% TraceId: 4bf92f3577b34da6a3ce929d0e0e4736 %% SpanId: 00f067aa0ba902b7 %% Enabled: false