Skip to content

Commit ad28444

Browse files
committed
Handle map-based headers in inject_context
1 parent 7cf4b70 commit ad28444

File tree

2 files changed

+34
-6
lines changed

2 files changed

+34
-6
lines changed

lib/spandex_datadog/adapter.ex

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,12 +53,17 @@ defmodule SpandexDatadog.Adapter do
5353
"""
5454
@impl Spandex.Adapter
5555
@spec inject_context([{term(), term()}], SpanContext.t(), Tracer.opts()) :: [{term(), term()}]
56-
def inject_context(headers, %SpanContext{trace_id: trace_id, parent_id: parent_id, priority: priority}, _opts) do
57-
[
58-
{"x-datadog-trace-id", to_string(trace_id)},
59-
{"x-datadog-parent-id", to_string(parent_id)},
60-
{"x-datadog-sampling-priority", to_string(priority)}
61-
] ++ headers
56+
def inject_context(headers, %SpanContext{} = span_context, _opts) when is_list(headers) do
57+
span_context
58+
|> tracing_headers()
59+
|> Kernel.++(headers)
60+
end
61+
62+
def inject_context(headers, %SpanContext{} = span_context, _opts) when is_map(headers) do
63+
span_context
64+
|> tracing_headers()
65+
|> Enum.into(%{})
66+
|> Map.merge(headers)
6267
end
6368

6469
# Private Helpers
@@ -79,4 +84,12 @@ defmodule SpandexDatadog.Adapter do
7984
end
8085

8186
defp parse_header(_header), do: nil
87+
88+
defp tracing_headers(%SpanContext{trace_id: trace_id, parent_id: parent_id, priority: priority}) do
89+
[
90+
{"x-datadog-trace-id", to_string(trace_id)},
91+
{"x-datadog-parent-id", to_string(parent_id)},
92+
{"x-datadog-sampling-priority", to_string(priority)}
93+
]
94+
end
8295
end

test/support/adapter_test.exs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,5 +121,20 @@ defmodule Spandex.Test.Datadog.AdapterTest do
121121
{"header2", "value2"}
122122
]
123123
end
124+
125+
test "Merges distributed tracing headers with an existing map of headers" do
126+
span_context = %SpanContext{trace_id: 123, parent_id: 456, priority: 10}
127+
headers = %{"header1" => "value1", "header2" => "value2"}
128+
129+
result = Adapter.inject_context(headers, span_context, [])
130+
131+
assert result == %{
132+
"x-datadog-trace-id" => "123",
133+
"x-datadog-parent-id" => "456",
134+
"x-datadog-sampling-priority" => "10",
135+
"header1" => "value1",
136+
"header2" => "value2"
137+
}
138+
end
124139
end
125140
end

0 commit comments

Comments
 (0)