Class: Wildsight::Rack::TopMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/wildsight/rack/top_middleware.rb

Constant Summary collapse

METRICS =
[:middleware, :rails, :view, :database]
REQUEST_INCLUDE_KEYS =
['SCRIPT_NAME', 'QUERY_STRING', 'PATH_INFO', 'REMOTE_ADDR']
REQUEST_EXCLUDE_KEYS =
['HTTP_COOKIE']
RESPONSE_EXCLUDE_KEYS =
['Set-Cookie']

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ TopMiddleware

Returns a new instance of TopMiddleware.



12
13
14
# File 'lib/wildsight/rack/top_middleware.rb', line 12

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# 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