Class: Coach::Handler

Inherits:
Object
  • Object
show all
Defined in:
lib/coach/handler.rb

Constant Summary collapse

STATUS_CODE_FOR_EXCEPTIONS =
500

Instance Method Summary collapse

Constructor Details

#initialize(middleware, config = {}) ⇒ Handler

Returns a new instance of Handler.



10
11
12
13
14
15
16
17
# File 'lib/coach/handler.rb', line 10

def initialize(middleware, config = {})
  @root_item = MiddlewareItem.new(middleware, config)
  validate!
rescue Coach::Errors::MiddlewareDependencyNotMet => e
  # Remove noise of validation stack trace, reset to the handler callsite
  e.backtrace.clear.concat(Thread.current.backtrace)
  raise e
end

Instance Method Details

#build_request_chain(sequence, context) ⇒ Object

Given a middleware sequence, filter out items not applicable to the current request, and set up a chain of instantiated middleware objects, ready to serve a request.



67
68
69
70
71
# File 'lib/coach/handler.rb', line 67

def build_request_chain(sequence, context)
  sequence.reverse.reduce(nil) do |successor, item|
    item.build_middleware(context, successor)
  end
end

#build_sequence(item, context) ⇒ Object

Traverse the middlware tree to build a linear middleware sequence, containing only middlewares that apply to this request.



56
57
58
59
60
61
62
# File 'lib/coach/handler.rb', line 56

def build_sequence(item, context)
  sequence = item.middleware.middleware_dependencies.map do |child_item|
    build_sequence(child_item.set_parent(item), context)
  end

  dedup_sequence([*sequence, item].flatten)
end

#call(env) ⇒ Object

The Rack interface to handler - builds a middleware chain based on the current request, and invokes it. rubocop:disable Metrics/MethodLength



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/coach/handler.rb', line 26

def call(env)
  context = { request: ActionDispatch::Request.new(env) }
  sequence = build_sequence(@root_item, context)
  chain = build_request_chain(sequence, context)

  event = build_event(context)

  publish("start_handler.coach", event.dup)
  instrument("finish_handler.coach", event) do
    begin
      response = chain.instrument.call
    ensure
      # We want to populate the response and metadata fields after the middleware
      # chain has completed so that the end of the instrumentation can see them. The
      # simplest way to do this is pass the event by reference to ActiveSupport, then
      # modify the hash to contain this detail before the instrumentation completes.
      #
      # This way, the last finish_handler.coach event will have all the details.
      status = response.try(:first) || STATUS_CODE_FOR_EXCEPTIONS
      event.merge!(
        response: { status: status },
        metadata: context.fetch(:_metadata, {}),
      )
    end
  end
end

#inspectObject



73
74
75
# File 'lib/coach/handler.rb', line 73

def inspect
  "#<Coach::Handler[#{@root_item.middleware.name}]>"
end