class Fisher::Rack::Middleware

Constants

REQUEST_METHOD
VALID_METHODS

Public Class Methods

new(app, options = {}) click to toggle source

Initializes the middleware.

app - The next Rack app in the pipeline. options - Hash of options.

:stats        - Optional StatsD client.
:hostname     - Optional String hostname. Set to nil
                to exclude.
:stats_prefix - Optional String prefix for StatsD keys.
                Default: "rack"
# File lib/fisher/rack/middleware.rb, line 16
def initialize(app, options = {})
  @app = app

  if @stats = options[:stats]
    prefix = [options[:stats_prefix] || :rack]
    if options.has_key?(:hostname)
      prefix << options[:hostname].gsub(/\./, '_') unless options[:hostname].nil?
    else
      prefix << `hostname -s`.chomp.gsub(/\./, '_')
    end
    @stats_prefix = prefix.join(".")
  end
end

Public Instance Methods

call(env) click to toggle source

Rack entry point.

# File lib/fisher/rack/middleware.rb, line 99
def call(env)
  @start = Time.now

  status, headers, body = @app.call(env)
  body = Body.new(body) { record_request(status, env) }
  [status, headers, body]
end
record_request(status, env) click to toggle source

called immediately after a request to record statistics

# File lib/fisher/rack/middleware.rb, line 31
def record_request(status, env)
  now = Time.now
  diff = (now - @start)

  if @stats
    @stats.timing("#{@stats_prefix}.response_time", diff * 1000)
    if VALID_METHODS.include?(env[REQUEST_METHOD])
      stat = "#{@stats_prefix}.response_time.#{env[REQUEST_METHOD].downcase}"
      @stats.timing(stat, diff * 1000)
    end

    if suffix = status_suffix(status)
      @stats.increment "#{@stats_prefix}.status_code.#{status_suffix(status)}"
    end
  end
rescue => e
  warn "Middleware#record_request failed: #{e.inspect}"
end
status_suffix(status) click to toggle source
# File lib/fisher/rack/middleware.rb, line 50
def status_suffix(status)
  suffix = case status.to_i
    when 200 then :ok
    when 201 then :created
    when 202 then :accepted
    when 301 then :moved_permanently
    when 302 then :found
    when 303 then :see_other
    when 304 then :not_modified
    when 305 then :use_proxy
    when 307 then :temporary_redirect
    when 400 then :bad_request
    when 401 then :unauthorized
    when 402 then :payment_required
    when 403 then :forbidden
    when 404 then :missing
    when 410 then :gone
    when 422 then :invalid
    when 500 then :error
    when 502 then :bad_gateway
    when 503 then :node_down
    when 504 then :gateway_timeout
  end
end