class ActiveRecordStats::RackMiddleware

Constants

ENV_KEY

The location in the Rack `env` where ActionDispatch stores its `parameters` value. This may change across Rails versions, but I am not aware of any more reliable means of retrieving it.

Public Class Methods

new(app) click to toggle source
# File lib/active_record_stats/rack_middleware.rb, line 13
def initialize(app)
  @app = app
end

Public Instance Methods

call(env) click to toggle source
# File lib/active_record_stats/rack_middleware.rb, line 17
def call(env)
  totals  = {}
  db_time = 0

  gather_sql = ->(_name, _started_at, _finished_at, _unique_id, payload) {
    return if payload[:name] == 'SCHEMA' || payload[:sql].blank?
    return unless type = ActiveRecordStats.statement_type(payload[:sql])
    totals[type] ||= 0
    totals[type] += 1
  }

  gather_runtime = ->(_name, _started_at, _finished_at, _unique_id, payload) {
    db_time = payload.fetch(:db_runtime) { 0 }
  }

  subs = [
    ActiveSupport::Notifications.subscribe('sql.active_record', &gather_sql),
    ActiveSupport::Notifications.subscribe('process_action.action_controller', &gather_runtime)
  ]

  @app.call(env)

ensure
  subs.each do |sub|
    ActiveSupport::Notifications.unsubscribe(sub)
  end

  request_params = env[ENV_KEY]
  if request_params && controller = request_params['controller']
    controller = controller.gsub('/', '__')
    action = request_params['action']
    emit(controller, action, db_time, totals.dup)
  end
end

Private Instance Methods

emit(controller, action, db_time, totals) click to toggle source
# File lib/active_record_stats/rack_middleware.rb, line 54
def emit(controller, action, db_time, totals)
  totals.each do |verb, count|
    StatsD.gauge "db.web.#{controller}.#{action}.#{verb}", count
  end

  StatsD.measure "db.web.#{controller}.#{action}.runtime", db_time
end