Class: MetrixWire::Rack

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

Overview

Rack middleware — opens exactly one trace per incoming request, runs the app inside that trace's context, and enqueues the finished trace. Works for Sinatra, bare Rack, Rails (inserted via the Railtie) and anything else Rack.

It is intentionally defensive at every step: a failure in instrumentation must never change the response the app returns.

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Rack

Returns a new instance of Rack.



11
12
13
# File 'lib/metrixwire/rack.rb', line 11

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



15
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
# File 'lib/metrixwire/rack.rb', line 15

def call(env)
  return @app.call(env) unless MetrixWire.enabled?

  method = env["REQUEST_METHOD"] || "GET"
  route = "#{method} #{derive_path(env)}"
  trace = Trace.new(route: route, method: method)
  start_heap = MetrixWire.rss_kb

  status, headers, body = nil
  Context.with(trace) do
    begin
      status, headers, body = @app.call(env)
    rescue Exception => e # rubocop:disable Lint/RescueException
      trace.capture_exception(e)
      finish(trace, 500, nil, start_heap)
      raise
    end

    # Refine the route from the framework's matched pattern if available
    # (Sinatra exposes sinatra.route; Rails sets it via notifications).
    refine_route(trace, env)
    finish(trace, status, headers, start_heap)
  end

  [status, headers, body]
rescue Exception # rubocop:disable Lint/RescueException
  # If we've already opened a trace it was handled above; re-raise so the
  # host app's own error handling runs unchanged.
  raise
end