2011-10-19 15:15:25 -04:00
|
|
|
require 'securerandom'
|
2011-10-19 15:17:54 -04:00
|
|
|
require 'active_support/core_ext/string/access'
|
2011-10-19 13:59:33 -04:00
|
|
|
|
|
|
|
module ActionDispatch
|
|
|
|
# Makes a unique request id available to the action_dispatch.request_id env variable (which is then accessible through
|
|
|
|
# ActionDispatch::Request#uuid) and sends the same id to the client via the X-Request-Id header.
|
|
|
|
#
|
|
|
|
# The unique request id is either based off the X-Request-Id header in the request, which would typically be generated
|
|
|
|
# by a firewall, load balancer, or the web server, or, if this header is not available, a random uuid. If the
|
|
|
|
# header is accepted from the outside world, we sanitize it to a max of 255 chars and alphanumeric and dashes only.
|
|
|
|
#
|
|
|
|
# The unique request id can be used to trace a request end-to-end and would typically end up being part of log files
|
|
|
|
# from multiple pieces of the stack.
|
|
|
|
class RequestId
|
|
|
|
def initialize(app)
|
|
|
|
@app = app
|
|
|
|
end
|
|
|
|
|
|
|
|
def call(env)
|
|
|
|
env["action_dispatch.request_id"] = external_request_id(env) || internal_request_id
|
2012-02-29 20:43:49 -05:00
|
|
|
@app.call(env).tap { |status, headers, body| headers["X-Request-Id"] = env["action_dispatch.request_id"] }
|
2011-10-19 13:59:33 -04:00
|
|
|
end
|
2011-10-19 16:09:36 -04:00
|
|
|
|
2011-10-19 13:59:33 -04:00
|
|
|
private
|
|
|
|
def external_request_id(env)
|
2011-10-19 16:10:43 -04:00
|
|
|
if request_id = env["HTTP_X_REQUEST_ID"].presence
|
2011-10-20 03:00:42 -04:00
|
|
|
request_id.gsub(/[^\w\-]/, "").first(255)
|
2011-10-19 13:59:33 -04:00
|
|
|
end
|
|
|
|
end
|
2011-10-19 16:09:36 -04:00
|
|
|
|
2011-10-19 13:59:33 -04:00
|
|
|
def internal_request_id
|
2011-12-21 07:25:57 -05:00
|
|
|
SecureRandom.uuid
|
2011-10-19 13:59:33 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|