Class: Datadog::Tracing::Context

Inherits:
Object
  • Object
show all
Includes:
Core::Utils::Forking
Defined in:
lib/datadog/tracing/context.rb

Overview

Context is used to keep track of a the active trace for the current execution flow. During each logical execution, the same Context is used to represent a single logical trace, even if the trace is built asynchronously.

A single code execution may use multiple Context if part of the execution must not be related to the current tracing. As example, a delayed job may compose a standalone trace instead of being related to the same trace that generates the job itself. On the other hand, if it's part of the same Context, it will be related to the original trace.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Core::Utils::Forking

#after_fork!, extended, #fork_pid, #forked?, included, #update_fork_pid!

Constructor Details

#initialize(trace: nil, otel_thread_context: nil) ⇒ Context

Returns a new instance of Context.



26
27
28
29
30
31
32
33
# File 'lib/datadog/tracing/context.rb', line 26

def initialize(
  trace: nil,
  otel_thread_context: nil
)
  @otel_thread_context = otel_thread_context
  @active_trace = nil
  activate!(trace)
end

Instance Attribute Details

#active_trace ⇒ Object (readonly)

Returns the value of attribute active_trace.



20
21
22
# File 'lib/datadog/tracing/context.rb', line 20

def active_trace
  @active_trace
end

#otel_thread_context=(value) ⇒ Object (writeonly)

Sets the attribute otel_thread_context

Parameters:

  • value —

    the value to set the attribute otel_thread_context to.



23
24
25
# File 'lib/datadog/tracing/context.rb', line 23

def otel_thread_context=(value)
  @otel_thread_context = value
end

Instance Method Details

#activate!(trace) ⇒ Object

Handles trace activation.

Permits nil, allowing traces to be deactivated.

If given a block, it will reset to the original trace after the block completes.

When restoring the original trace, if it is finished, it will deactivate it. This prevents the context from holding references to completed traces thereby releasing its memory.



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/datadog/tracing/context.rb', line 46

def activate!(trace)
  if block_given?
    begin
      original_trace = @active_trace
      set_active_trace!(trace)
      yield
    ensure
      set_active_trace!(original_trace)
    end
  else
    set_active_trace!(trace)
  end
end

#fork_clone ⇒ Object

Creates a copy of the context, when forked.



61
62
63
64
65
66
67
68
# File 'lib/datadog/tracing/context.rb', line 61

def fork_clone
  forked_trace = @active_trace&.fork_clone

  self.class.new(
    trace: forked_trace,
    otel_thread_context: @otel_thread_context,
  )
end