gitlab-org--gitlab-foss/lib/peek/views/detailed_view.rb
Sean McGivern 23c1cfcc11 Return warnings for performance bar from backend
For each DetailedView subclass, we add a `warnings` array to:

1. The top-level response.
2. Each individual call under the `details` key.

We use the `.thresholds` hash on the DetailedView to determine what's a
warning. If that hash is empty (the default), then the warnings array
will always be empty.
2019-08-28 16:39:33 +01:00

76 lines
1.7 KiB
Ruby

# frozen_string_literal: true
module Peek
module Views
class DetailedView < View
def self.thresholds
{}
end
def results
{
duration: format_duration(duration),
calls: calls,
details: details,
warnings: warnings
}
end
def detail_store
::Gitlab::SafeRequestStore["#{key}_call_details"] ||= []
end
private
def duration
detail_store.map { |entry| entry[:duration] }.sum * 1000 # rubocop:disable CodeReuse/ActiveRecord
end
def calls
detail_store.count
end
def details
call_details
.sort { |a, b| b[:duration] <=> a[:duration] }
.map(&method(:format_call_details))
end
def warnings
[
warning_for(calls, self.class.thresholds[:calls], label: "#{key} calls"),
warning_for(duration, self.class.thresholds[:duration], label: "#{key} duration")
].flatten.compact
end
def call_details
detail_store
end
def format_call_details(call)
duration = (call[:duration] * 1000).round(3)
call.merge(duration: duration,
warnings: warning_for(duration, self.class.thresholds[:individual_call]))
end
def warning_for(actual, threshold, label: nil)
if threshold && actual > threshold
prefix = "#{label}: " if label
["#{prefix}#{actual} over #{threshold}"]
else
[]
end
end
def format_duration(ms)
if ms >= 1000
"%.2fms" % ms
else
"%.0fms" % ms
end
end
end
end
end