Class: Braintrust::Trace::SpanProcessor

Inherits:
Object
  • Object
show all
Defined in:
lib/braintrust/trace/span_processor.rb

Overview

Custom span processor that adds Braintrust-specific attributes to spans and optionally filters spans based on custom filter functions.

Constant Summary collapse

PARENT_ATTR_KEY =
"braintrust.parent"
ORG_ATTR_KEY =
"braintrust.org"
APP_URL_ATTR_KEY =
"braintrust.app_url"

Instance Method Summary collapse

Constructor Details

#initialize(wrapped_processor, state, filters = []) ⇒ SpanProcessor

Returns a new instance of SpanProcessor.



14
15
16
17
18
# File 'lib/braintrust/trace/span_processor.rb', line 14

def initialize(wrapped_processor, state, filters = [])
  @wrapped = wrapped_processor
  @state = state
  @filters = filters || []
end

Instance Method Details

#force_flush(timeout: nil) ⇒ Object

Force flush any buffered spans



50
51
52
# File 'lib/braintrust/trace/span_processor.rb', line 50

def force_flush(timeout: nil)
  @wrapped.force_flush(timeout: timeout)
end

#on_finish(span) ⇒ Object

Called when a span ends - apply filters before forwarding



39
40
41
42
# File 'lib/braintrust/trace/span_processor.rb', line 39

def on_finish(span)
  # Only forward span if it passes filters
  @wrapped.on_finish(span) if should_forward_span?(span)
end

#on_start(span, parent_context) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/braintrust/trace/span_processor.rb', line 20

def on_start(span, parent_context)
  # Add default parent if span doesn't already have one
  has_parent = span.respond_to?(:attributes) && span.attributes&.key?(PARENT_ATTR_KEY)

  unless has_parent
    # Try to inherit parent from parent span in context
    parent_value = get_parent_from_context(parent_context) || default_parent
    span.set_attribute(PARENT_ATTR_KEY, parent_value)
  end

  # Always add org and app_url
  span.set_attribute(ORG_ATTR_KEY, @state.org_name) if @state.org_name
  span.set_attribute(APP_URL_ATTR_KEY, @state.app_url) if @state.app_url

  # Delegate to wrapped processor
  @wrapped.on_start(span, parent_context)
end

#shutdown(timeout: nil) ⇒ Object

Shutdown the processor



45
46
47
# File 'lib/braintrust/trace/span_processor.rb', line 45

def shutdown(timeout: nil)
  @wrapped.shutdown(timeout: timeout)
end