Sha256: 85e1d8e14ae103034b7035436b895ba15966ec1073f7f739c9b1dfd25f97552e

Contents?: true

Size: 1.81 KB

Versions: 1

Compression:

Stored size: 1.81 KB

Contents

require 'active_record_stats'
require 'active_support/notifications'
require 'action_dispatch/http/mime_type'
require 'action_dispatch/http/parameters'

module ActiveRecordStats
  class RackMiddleware
    # 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.
    ENV_KEY = 'action_dispatch.request.parameters'.freeze

    def initialize(app)
      @app = app
    end

    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[:db_runtime]
      }

      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

    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
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
active_record_stats-0.1.4 lib/active_record_stats/rack_middleware.rb