class Wildsight::Rack::TopMiddleware

Constants

METRICS
REQUEST_EXCLUDE_KEYS
REQUEST_INCLUDE_KEYS
RESPONSE_EXCLUDE_KEYS

Public Class Methods

new(app) click to toggle source
# File lib/wildsight/rack/top_middleware.rb, line 12
def initialize(app)
  @app = app
end

Public Instance Methods

call(env) click to toggle source
# File lib/wildsight/rack/top_middleware.rb, line 16
def call(env)
  context = Wildsight::Agent.default.context
  context.bind_thread

  context.data[:rack] ||= {
      request: {
          target: env['SCRIPT_NAME'].to_s + env['PATH_INFO'].to_s,
          headers: {}
      },
      response: {
      }
  }

  env.each_pair do |key,value|
    name = key.to_s
    context.data[:rack][:request][:headers][key] = value if REQUEST_INCLUDE_KEYS.include?(name)
    context.data[:rack][:request][:headers][key] = value if name.start_with?('HTTP_')
    context.data[:rack][:request][:headers][key] = value if name.start_with?('REQUEST_')
    context.data[:rack][:request][:headers][key] = value if name.start_with?('SERVER_')
  end

  env[Wildsight::Rack::RACK_ENV_KEY] = context

  response = context.profiler.duration(:request, nil, raw: true) {
    context.profiler.duration(:middleware) {
      @app.call(env)
    }
  }

  if !context.data[:session] && !env['rack.session'].nil? && env['rack.session'].respond_to?(:id)
    context.data[:session] ||= {id: env['rack.session'].id}
  end

  REQUEST_EXCLUDE_KEYS.each { |key| context.data[:rack][:request][:headers].delete(key) }

  if response
    context.data[:rack][:response][:code] ||= response[0]
    context.data[:rack][:response][:headers] ||= response[1].dup
    RESPONSE_EXCLUDE_KEYS.each { |key| context.data[:rack][:response][:headers].delete(key) }
  end

  values = {}
  context.profiler.data.keys.each do |key|
    values[key] = context.profiler.data[key][:duration]
  end

  context.event(:action_controller, context.data[:rack], values)

  return response
ensure
  env.delete(Wildsight::Rack::RACK_ENV_KEY)
  context.release_thread
  context.unregister
end