Skip to content

Commit

Permalink
Update packages/sync-service/lib/electric/plug/trace_context_plug.ex
Browse files Browse the repository at this point in the history
Co-authored-by: Ilia Borovitinov <[email protected]>
  • Loading branch information
KyleAMathews and icehaunter authored Nov 20, 2024
1 parent 5903fee commit 6b0018c
Showing 1 changed file with 11 additions and 41 deletions.
52 changes: 11 additions & 41 deletions packages/sync-service/lib/electric/plug/trace_context_plug.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,51 +8,21 @@ defmodule Electric.Plug.TraceContextPlug do

def init(opts), do: opts

def call(conn, _opts) do
case extract_trace_context(conn) do
{:ok, span_ctx} ->
:otel_tracer.set_current_span(span_ctx)
conn

:error ->
conn
end
end

# Extract trace context using the OpenTelemetry propagator
defp extract_trace_context(conn) do
# Get all headers as a list of {key, value} tuples
headers =
conn
|> Plug.Conn.get_req_header("traceparent")
|> Enum.map(fn value -> {"traceparent", value} end)

# Create a new context and extract the trace context from headers
ctx =
:otel_propagator_trace_context.extract(
:otel_ctx.new(),
headers,
:undefined,
&header_getter/2,
%{}
)
def call(%Plug.Conn{req_headers: headers} = conn, _opts) do
# Extract function expects a list of headers as tuples and knows
# the expected header keys, so we don't have to prefilter.
ctx = :otel_propagator_text_map.extract_to(:otel_ctx.new(), headers)

# Get the span context from the extracted context
case :otel_tracer.current_span_ctx(ctx) do
:undefined -> :error
span_ctx -> {:ok, span_ctx}
end
end
:undefined ->
# No parent, continue as-is
conn

# Header getter function for the propagator
# Note: The key is passed first, carrier second by the propagator
defp header_getter(key, carrier) when is_list(carrier) do
case Enum.find(carrier, fn {k, _v} -> String.downcase(k) == String.downcase(key) end) do
{_key, value} -> value
nil -> []
span_ctx ->
# Parent found, set as current span
:otel_tracer.set_current_span(span_ctx)
conn
end
end

# Fallback clause for when carrier is not a list
defp header_getter(_key, _carrier), do: []
end

0 comments on commit 6b0018c

Please sign in to comment.