Class: Datadog::Tracing::DefaultContextProvider

Inherits:
Object
  • Object
show all
Defined in:
lib/datadog/tracing/context_provider.rb

Overview

DefaultContextProvider is a default context provider that retrieves all contexts from the current fiber-local storage. It is suitable for synchronous programming.

Instance Method Summary collapse

Constructor Details

#initialize(otel_thread_context: nil) ⇒ DefaultContextProvider

Initializes the default context provider with a fiber-bound context.



15
16
17
18
# File 'lib/datadog/tracing/context_provider.rb', line 15

def initialize(otel_thread_context: nil)
  @otel_thread_context = otel_thread_context
  @context = FiberLocalContext.new(otel_thread_context: otel_thread_context)
end

Instance Method Details

#context(key = nil) ⇒ Object

Return the local context.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/datadog/tracing/context_provider.rb', line 36

def context(key = nil)
  current_context = key.nil? ? @context.local : @context.local(key)

  # Rebuild/reset context after a fork
  #
  # We don't want forked processes to copy and retransmit spans
  # that were generated from the parent process. Reset it such
  # that it acts like a distributed trace.
  current_context.after_fork! do
    # TODO: Only assign to `self.context` when working on the current thread (`key == nil`)
    current_context = self.context = current_context.fork_clone
  end

  current_context
end

#context=(ctx) ⇒ Object

Sets the current context.



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/datadog/tracing/context_provider.rb', line 21

def context=(ctx)
  ctx.otel_thread_context = @otel_thread_context if ctx.respond_to?(:otel_thread_context=)

  if (otel_thread_context = @otel_thread_context)
    if (trace = ctx&.active_trace)
      otel_thread_context.update_from_trace_op(trace)
    else
      otel_thread_context.clear
    end
  end

  @context.local = ctx
end