Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use traceparent header from incoming shape requests to set parent span #2000

Merged
merged 4 commits into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/odd-walls-walk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@core/sync-service": patch
---

use traceparent header from incoming shape requests to set parent span
1 change: 1 addition & 0 deletions packages/sync-service/lib/electric/plug/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ defmodule Electric.Plug.Router do
plug Plug.Head
plug :match
plug Electric.Plug.LabelProcessPlug
plug Electric.Plug.TraceContextPlug
plug Plug.Telemetry, event_prefix: [:electric, :routing]
plug Plug.Logger
plug :put_cors_headers
Expand Down
58 changes: 58 additions & 0 deletions packages/sync-service/lib/electric/plug/trace_context_plug.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
defmodule Electric.Plug.TraceContextPlug do
@moduledoc """
A plug that extracts trace context from incoming HTTP headers and sets it as the parent span.
"""
@behaviour Plug

require Logger

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,
%{}
)

# 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

# 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 -> []
end
end

# Fallback clause for when carrier is not a list
defp header_getter(_key, _carrier), do: []
KyleAMathews marked this conversation as resolved.
Show resolved Hide resolved
end