2018-01-15 10:21:04 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Gitlab
|
|
|
|
module QueryLimiting
|
|
|
|
# Middleware for reporting (or raising) when a request performs more than a
|
|
|
|
# certain amount of database queries.
|
|
|
|
class Middleware
|
2019-08-31 15:25:25 -04:00
|
|
|
CONTROLLER_KEY = 'action_controller.instance'
|
|
|
|
ENDPOINT_KEY = 'api.endpoint'
|
2018-01-15 10:21:04 -05:00
|
|
|
|
|
|
|
def initialize(app)
|
|
|
|
@app = app
|
|
|
|
end
|
|
|
|
|
|
|
|
def call(env)
|
|
|
|
transaction, retval = Transaction.run do
|
|
|
|
@app.call(env)
|
|
|
|
end
|
|
|
|
|
|
|
|
transaction.action = action_name(env)
|
|
|
|
transaction.act_upon_results
|
|
|
|
|
|
|
|
retval
|
|
|
|
end
|
|
|
|
|
|
|
|
def action_name(env)
|
|
|
|
if env[CONTROLLER_KEY]
|
|
|
|
action_for_rails(env)
|
|
|
|
elsif env[ENDPOINT_KEY]
|
|
|
|
action_for_grape(env)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def action_for_rails(env)
|
|
|
|
controller = env[CONTROLLER_KEY]
|
|
|
|
action = "#{controller.class.name}##{controller.action_name}"
|
|
|
|
|
|
|
|
if controller.content_type == 'text/html'
|
|
|
|
action
|
|
|
|
else
|
|
|
|
"#{action} (#{controller.content_type})"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def action_for_grape(env)
|
|
|
|
endpoint = env[ENDPOINT_KEY]
|
|
|
|
route = endpoint.route rescue nil
|
|
|
|
|
|
|
|
"#{route.request_method} #{route.path}" if route
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|