Skip to content
This repository has been archived by the owner on Oct 21, 2024. It is now read-only.

Commit

Permalink
rfc: Allow reading current context for another thread
Browse files Browse the repository at this point in the history
I've been working on integrating Datadog's continuous profiler with
opentelemetry traces (see DataDog/dd-trace-rb#1568).

The profiler runs on a background thread, and needs to be able to
access the current context for a thread, to be able to get the
current span's trace id and span ids (if any active).

To do so, I was originally using

```ruby
thread = ...
::OpenTelemetry::Trace.current_span(thread[::OpenTelemetry::Context::KEY])
```

Unfortunately, after open-telemetry#807, this interface was changed, and more
importantly, `Context::KEY` was removed and replaced with
`Context::STACK_KEY`. `STACK_KEY` was marked as `private_constant`.

With 1.0.0.rc2, the only way of getting this information is by
relying on private implementation details, which isn't great.

Thus, I would like to ask if it'd be reasonable to add an optional
`thread` parameter to `Context.current`. This would make it easy to
access the needed information, and it would even be more future-proof
as the outside code doesn't need to care anymore where and how
the context is stored.
  • Loading branch information
ivoanjo committed Jun 25, 2021
1 parent 1f9aa49 commit 59921ee
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
8 changes: 4 additions & 4 deletions api/lib/opentelemetry/context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ def create_key(name)
# Returns current context, which is never nil
#
# @return [Context]
def current
stack.last || ROOT
def current(thread = nil)
stack(thread).last || ROOT
end

# Associates a Context with the caller's current Fiber. Every call to
Expand Down Expand Up @@ -123,8 +123,8 @@ def empty

private

def stack
Thread.current[STACK_KEY] ||= []
def stack(thread = nil)
(thread || Thread.current)[STACK_KEY] ||= []
end
end

Expand Down
20 changes: 20 additions & 0 deletions api/test/opentelemetry/context_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -333,5 +333,25 @@
_(Context.current[bar_key]).must_be_nil
end
end

it 'allows accessing the current context for another thread' do
another_thread_context = Queue.new

another_thread = Thread.new do
ctx = Context.empty.set_value(foo_key, 'bar')
Context.with_current(ctx) do
another_thread_context << Context.current
sleep
end
end

ctx = another_thread_context.pop

_(Context.current(another_thread)).must_equal(ctx)
_(Context.current).wont_equal(ctx)

another_thread.kill
another_thread.join
end
end
end

0 comments on commit 59921ee

Please sign in to comment.