Class: ShieldPressTracker::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/shieldpress_tracker/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, tracker = nil) ⇒ Middleware

Returns a new instance of Middleware.



3
# File 'lib/shieldpress_tracker/middleware.rb', line 3

def initialize(app, tracker = nil); @app, @tracker = app, tracker || ShieldPress.instance end

Instance Method Details

#call(env) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/shieldpress_tracker/middleware.rb', line 4

def call(env)
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC); path = env["PATH_INFO"] || "/"; method = env["REQUEST_METHOD"] || "GET"
  headers = env.select { |k, _| k.start_with?("HTTP_") }.to_h { |k, v| [k.delete_prefix("HTTP_").tr("_", "-").downcase, v] }
  @tracker.analyze_request(url: path, method: method, headers: headers, ip: env["REMOTE_ADDR"], query: env["QUERY_STRING"])
  status, response_headers, body = @app.call(env)
  [status, response_headers, body]
rescue StandardError => e
  @tracker.capture_error(e, url: path, method: method); raise
ensure
  if started
    duration = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000
    @tracker.record_request(path: path, method: method, status_code: status || 500, duration_ms: duration)
  end
end