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) ⇒ Context

Returns a new instance of Context.



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

def initialize(
  trace: nil
)
  activate!(trace)
end

Instance Attribute Details

#active_traceObject (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

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.



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/datadog/tracing/context.rb', line 40

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_cloneObject

Creates a copy of the context, when forked.



55
56
57
58
# File 'lib/datadog/tracing/context.rb', line 55

def fork_clone
  forked_trace = @active_trace && @active_trace.fork_clone
  self.class.new(trace: forked_trace)
end