Module: Bitfab::SpanContext

Defined in:
lib/bitfab/span_context.rb

Overview

Thread-local span stack for tracking nested spans. Each entry is a Hash with :trace_id and :span_id keys.

Constant Summary collapse

STACK_KEY =
:__bitfab_span_stack
FIBER_BRIDGE_STACK_KEY =
:__bitfab_span_fiber_bridge_stack

Class Method Summary collapse

Class Method Details

.currentObject



125
126
127
# File 'lib/bitfab/span_context.rb', line 125

def current
  stack.last || fiber_bridge_stack.last
end

.fiber_bridge_stackObject



150
151
152
153
154
155
156
157
# File 'lib/bitfab/span_context.rb', line 150

def fiber_bridge_stack
  current_thread = Thread.current
  current_thread.thread_variable_get(FIBER_BRIDGE_STACK_KEY) || begin
    value = []
    current_thread.thread_variable_set(FIBER_BRIDGE_STACK_KEY, value)
    value
  end
end

.stackObject



121
122
123
# File 'lib/bitfab/span_context.rb', line 121

def stack
  Thread.current[STACK_KEY] ||= []
end

.with_fiber_bridge(trace_id:, span_id:) ⇒ Object

Enumerator.new and enum_for run their source body in another Fiber on the same thread. Bridge only the active Enumerator parent across that boundary; ordinary fiber-local span stacks remain isolated.



132
133
134
135
136
137
138
# File 'lib/bitfab/span_context.rb', line 132

def with_fiber_bridge(trace_id:, span_id:)
  entry = {trace_id:, span_id:}
  fiber_bridge_stack.push(entry)
  yield
ensure
  fiber_bridge_stack.pop
end

.with_span(trace_id:, span_id:) ⇒ Object

Execute a block with a new span pushed onto the stack. The span is automatically popped when the block completes.



142
143
144
145
146
147
148
# File 'lib/bitfab/span_context.rb', line 142

def with_span(trace_id:, span_id:)
  entry = {trace_id:, span_id:}
  stack.push(entry)
  yield
ensure
  stack.pop
end