Class: Marlowe::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/marlowe/middleware.rb

Overview

Marlowe correlation id middleware. Including this into your middleware stack will add a correlation id header as an incoming request, and save that id in a request session variable.

Constant Summary collapse

CORRELATION_HEADER =

The name of the default header to look for and put the correlation id in.

'X-Request-Id'

Instance Method Summary collapse

Constructor Details

#initialize(app, opts = {}) ⇒ Middleware

Configure the Marlowe middleware to call app with options opts.

Options

:header

The name of the header to inspect. Defaults to ‘X-Request-Id’. Also available as :correlation_header.

:handler

The handler for request correlation IDs. Defaults to sanitizing provided request IDs or generating a UUID. If :simple is provided, provided request IDs will not be sanitized. A callable (expecting a single input of any possible existing request ID) may be provided to introduce more complex request ID handling.

:return

If true (the default), the request correlation ID will be returned as part of the response headers.

:action_dispatch

If true, Marlowe will add code to behave like ActionDispatch::RequestId. Depends on ActionDispatch::Request.



34
35
36
37
38
39
40
41
42
# File 'lib/marlowe/middleware.rb', line 34

def initialize(app, opts = {})
  @app = app
  @header, @http_header = format_header_name(
    opts[:header] || opts[:correlation_header] || CORRELATION_HEADER
  )
  @handler = opts.fetch(:handler, :clean)
  @return = opts.fetch(:return, true)
  @action_dispatch = opts.fetch(:action_dispatch, false)
end

Instance Method Details

#call(env) ⇒ Object

Stores the incoming correlation id from the env hash. If the correlation id has not been sent, a new UUID is generated and the env is modified.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/marlowe/middleware.rb', line 46

def call(env)
  req_id = make_request_id(env[@http_header])
  RequestStore.store[:correlation_id] = env[@http_header] = req_id

  if @action_dispatch
    req = ActionDispatch::Request.new(env)
    req.request_id = req_id
  end

  @app.call(env).tap { |_status, headers, _body|
    if @return
      headers[@header] = if @action_dispatch
                           req.request_id
                         else
                           RequestStore.store[:correlation_id]
                         end
    end
  }
end