class Coach::RequestBenchmark

This class is built to aggregate data during the course of the request. It relies on 'start_middleware.coach' and 'finish_middleware.coach' events to register the start/end of each middleware element, and thereby calculate running times for each.

Coach::Notifications makes use of this class to produce benchmark data for requests.

Public Class Methods

new(endpoint_name) click to toggle source
# File lib/coach/request_benchmark.rb, line 11
def initialize(endpoint_name)
  @endpoint_name = endpoint_name
  @events = []
end

Public Instance Methods

complete(start, finish) click to toggle source
# File lib/coach/request_benchmark.rb, line 26
def complete(start, finish)
  @start = start
  @duration = finish - start
end
notify(name, start, finish) click to toggle source
# File lib/coach/request_benchmark.rb, line 16
def notify(name, start, finish)
  event = { name: name, start: start, finish: finish }

  duration_of_children = child_events_for(event).
    inject(0) { |total, e| total + e[:duration] }
  event[:duration] = (finish - start) - duration_of_children

  @events.push(event)
end
stats() click to toggle source

Serialize the results of the benchmarking

# File lib/coach/request_benchmark.rb, line 32
def stats
  {
    endpoint_name: @endpoint_name,
    started_at: @start,
    duration: format_ms(@duration),
    duration_seconds: @duration,
    chain: sorted_chain.map do |event|
      {
        name: event[:name],
        duration: format_ms(event[:duration]),
        duration_seconds: event[:duration],
      }
    end,
  }
end

Private Instance Methods

child_events_for(parent) click to toggle source
# File lib/coach/request_benchmark.rb, line 54
def child_events_for(parent)
  @events.select do |child|
    parent[:start] < child[:start] && child[:finish] < parent[:finish]
  end
end
format_ms(duration) click to toggle source
# File lib/coach/request_benchmark.rb, line 64
def format_ms(duration)
  (1000 * duration).round
end
previous_event() click to toggle source
# File lib/coach/request_benchmark.rb, line 50
def previous_event
  @events.last
end
sorted_chain() click to toggle source
# File lib/coach/request_benchmark.rb, line 60
def sorted_chain
  @events.sort_by { |event| event[:start] }
end