class Periskop::Rack::Middleware

Attributes

collector[RW]

Public Class Methods

new(app, options = {}) click to toggle source
# File lib/periskop/rack/middleware.rb, line 10
def initialize(app, options = {})
  @app = app
  @pushgateway_address = options.fetch(:pushgateway_address, nil)
  options[:collector] ||= Periskop::Client::ExceptionCollector.new
  @collector = options.fetch(:collector)

  @exporter =
    unless @pushgateway_address.nil? || @pushgateway_address.empty?
      @exporter = Periskop::Client::Exporter.new(@collector)
    end
end

Public Instance Methods

call(env) click to toggle source
# File lib/periskop/rack/middleware.rb, line 22
def call(env)
  begin
    response = @app.call(env)
  rescue Exception => ex
    report_push(env, ex)
    raise(ex)
  end

  maybe_ex = framework_exception(env)
  report_push(env, maybe_ex) if maybe_ex

  response
end

Private Instance Methods

find_request(env) click to toggle source
# File lib/periskop/rack/middleware.rb, line 50
def find_request(env)
  if defined?(ActionDispatch::Request)
    ActionDispatch::Request.new(env)
  elsif defined?(Sinatra::Request)
    Sinatra::Request.new(env)
  else
    ::Rack::Request.new(env)
  end
end
framework_exception(env) click to toggle source

Web framework middlewares often store rescued exceptions inside the Rack env, but Rack doesn’t have a standard key for it:

# File lib/periskop/rack/middleware.rb, line 44
def framework_exception(env)
  env['rack.exception'] ||
    env['sinatra.error'] ||
    env['action_dispatch.exception']
end
get_http_context(env) click to toggle source
# File lib/periskop/rack/middleware.rb, line 75
def get_http_context(env)
  request = find_request(env)
  Periskop::Client::HTTPContext.new(request.request_method, request.url, get_http_headers(request.env), nil)
end
get_http_headers(request_env) click to toggle source
# File lib/periskop/rack/middleware.rb, line 60
def get_http_headers(request_env)
  header_prefixes = %w[
    HTTP_
    CONTENT_TYPE
    CONTENT_LENGTH
  ].freeze

  request_env.map.with_object({}) do |(key, value), headers|
    if header_prefixes.any? { |prefix| key.to_s.start_with?(prefix) }
      headers[key] = value
    end
    headers
  end
end
report_push(env, maybe_ex) click to toggle source
# File lib/periskop/rack/middleware.rb, line 80
def report_push(env, maybe_ex)
  ex =
    if maybe_ex.is_a?(Exception)
      maybe_ex
    else
      RuntimeError.new(maybe_ex.to_s)
    end
  @collector.report_with_context(ex, get_http_context(env))
  @exporter&.push_to_gateway(@pushgateway_address)
end