module Grape::Instrumentation

Constants

COMMON_TAGS
NOTIFICATIONS
VERSION

Attributes

tracer[RW]

Public Class Methods

instrument(tracer: OpenTracing.global_tracer, parent_span: nil) click to toggle source
# File lib/grape/instrumentation.rb, line 27
def instrument(tracer: OpenTracing.global_tracer, parent_span: nil)
  @tracer = tracer
  @parent_span = parent_span
  @subscriber_mutex = Mutex.new
  @subscribers = []

  add_subscribers
end
tag_endpoint(span, endpoint) click to toggle source
# File lib/grape/instrumentation.rb, line 84
def tag_endpoint(span, endpoint)
  # ideally there would be a member of endpoint that has the request path.
  # currently, it seems like only the Rack env contains it
  env = endpoint.env
  span.set_tag('http.url', env['PATH_INFO']) if env['PATH_INFO']

  span.set_tag('http.method', endpoint.options[:method].first)
end
tag_error(span, exception_object) click to toggle source
# File lib/grape/instrumentation.rb, line 93
def tag_error(span, exception_object)
  span.record_exception(exception_object)
end
trace_event(event) click to toggle source
# File lib/grape/instrumentation.rb, line 64
def trace_event(event)
  tags = {
    'request.id' => event.transaction_id
  }.merge(COMMON_TAGS)

  parent = @parent_span.respond_to?(:call) ? @parent_span.call(event.payload) : @parent_span
  span = @tracer.start_span(event.name.to_s,
                            tags: tags,
                            child_of: parent,
                            start_time: event.time,
                            finish_on_close: false)

  # tag relevant information from the event payload
  tag_endpoint(span, event.payload[:endpoint]) if event.payload[:endpoint]
  tag_error(span, event.payload[:exception_object]) if event.payload[:exception] &&
                                                       event.payload[:exception_object]

  span.finish(end_time: event.end)
end
uninstrument() click to toggle source
# File lib/grape/instrumentation.rb, line 36
def uninstrument
  clear_subscribers
end

Private Class Methods

add_subscribers() click to toggle source
# File lib/grape/instrumentation.rb, line 40
def add_subscribers
  clear_subscribers unless @subscribers.empty?

  @subscriber_mutex.synchronize do
    NOTIFICATIONS.each do |notification|
      subscriber = ::ActiveSupport::Notifications.subscribe(notification) do |*args|
        trace_event(::ActiveSupport::Notifications::Event.new(*args))
      end

      @subscribers.append(subscriber)
    end
  end
end
clear_subscribers() click to toggle source
# File lib/grape/instrumentation.rb, line 54
def clear_subscribers
  @subscriber_mutex.synchronize do
    @subscribers.each do |s|
      ::ActiveSupport::Notifications.unsubscribe(s)
    end

    @subscribers.clear
  end
end