detailed_view.rb 1.65 KB
Newer Older
Stan Hu's avatar
Stan Hu committed
1 2 3 4 5
# frozen_string_literal: true

module Peek
  module Views
    class DetailedView < View
6 7 8 9
      def self.thresholds
        {}
      end

Stan Hu's avatar
Stan Hu committed
10 11
      def results
        {
12
          duration: format_duration(duration),
Stan Hu's avatar
Stan Hu committed
13
          calls: calls,
14 15
          details: details,
          warnings: warnings
Stan Hu's avatar
Stan Hu committed
16 17 18
        }
      end

19 20 21 22
      def detail_store
        ::Gitlab::SafeRequestStore["#{key}_call_details"] ||= []
      end

Stan Hu's avatar
Stan Hu committed
23 24 25
      private

      def duration
26
        detail_store.map { |entry| entry[:duration] }.sum * 1000 # rubocop:disable CodeReuse/ActiveRecord
Stan Hu's avatar
Stan Hu committed
27 28 29
      end

      def calls
30
        detail_store.count
Stan Hu's avatar
Stan Hu committed
31 32
      end

33 34 35 36 37 38 39 40 41 42 43 44 45
      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

Stan Hu's avatar
Stan Hu committed
46
      def call_details
47
        detail_store
Stan Hu's avatar
Stan Hu committed
48 49 50
      end

      def format_call_details(call)
51
        duration = (call[:duration] * 1000).round(3)
Stan Hu's avatar
Stan Hu committed
52

53 54
        call.merge(duration: duration,
                   warnings: warning_for(duration, self.class.thresholds[:individual_call]))
Stan Hu's avatar
Stan Hu committed
55 56
      end

57 58 59 60 61 62 63 64 65
      def warning_for(actual, threshold, label: nil)
        if threshold && actual > threshold
          prefix = "#{label}: " if label

          ["#{prefix}#{actual} over #{threshold}"]
        else
          []
        end
      end
Stan Hu's avatar
Stan Hu committed
66

67
      def format_duration(ms)
Stan Hu's avatar
Stan Hu committed
68 69 70 71 72 73 74 75 76
        if ms >= 1000
          "%.2fms" % ms
        else
          "%.0fms" % ms
        end
      end
    end
  end
end