Skip to content

Commit 889e93c

Browse files
committed
Add support for context propagation.
1 parent 2bca4c9 commit 889e93c

File tree

2 files changed

+45
-12
lines changed

2 files changed

+45
-12
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# frozen_string_literal: true
2+
3+
# Released under the MIT License.
4+
# Copyright, 2021-2025, by Samuel Williams.
5+
6+
require "opentelemetry"
7+
require "traces/context"
8+
9+
module Traces
10+
module Backend
11+
module OpenTelemetry
12+
class Context < Traces::Context
13+
def initialize(*arguments, **options, context: nil)
14+
super(*arguments, **options)
15+
@context = context
16+
end
17+
18+
attr :context
19+
end
20+
end
21+
end
22+
end

lib/traces/backend/open_telemetry/interface.rb

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
require "opentelemetry"
77

8-
require "traces/context"
8+
require_relative "context"
99
require_relative "version"
1010

1111
module Traces
@@ -21,20 +21,30 @@ def trace(name, attributes: nil, &block)
2121
end
2222

2323
def trace_context=(context)
24-
span_context = ::OpenTelemetry::Trace::SpanContext.new(
25-
trace_id: context.trace_id,
26-
span_id: context.parent_id,
27-
trace_flags: ::OpenTelemetry::Trace::TraceFlags.from_byte(context.flags),
28-
tracestate: context.state,
29-
remote: context.remote?
30-
)
24+
if context.context
25+
context = context.context
26+
else
27+
span_context = ::OpenTelemetry::Trace::SpanContext.new(
28+
trace_id: context.trace_id,
29+
span_id: context.parent_id,
30+
trace_flags: ::OpenTelemetry::Trace::TraceFlags.from_byte(context.flags),
31+
tracestate: context.state,
32+
remote: context.remote?
33+
)
34+
35+
span = ::OpenTelemetry::Trace.non_recording_span(span_context)
36+
context = ::OpenTelemetry::Trace.context_with_span(span)
37+
end
3138

32-
span = ::OpenTelemetry::Trace.non_recording_span(span_context)
33-
context = ::OpenTelemetry::Trace.context_with_span(span)
3439
::OpenTelemetry::Context.attach(context)
3540
end
3641

37-
def trace_context(span = ::OpenTelemetry::Trace.current_span)
42+
def trace_context(span = nil)
43+
if span.nil?
44+
span = ::OpenTelemetry::Trace.current_span
45+
context = ::OpenTelemetry::Context.current
46+
end
47+
3848
if span_context = span.context
3949
flags = 0
4050

@@ -47,7 +57,8 @@ def trace_context(span = ::OpenTelemetry::Trace.current_span)
4757
span_context.span_id,
4858
flags,
4959
span_context.tracestate,
50-
remote: span_context.remote?
60+
remote: span_context.remote?,
61+
context: context,
5162
)
5263
end
5364
end

0 commit comments

Comments
 (0)