logger_analyzer.rb 1.9 KB
Newer Older
C
charlieablett 已提交
1 2 3 4 5 6
# frozen_string_literal: true

module Gitlab
  module Graphql
    module QueryAnalyzers
      class LoggerAnalyzer
C
charlie ablett 已提交
7 8 9
        COMPLEXITY_ANALYZER = GraphQL::Analysis::QueryComplexity.new { |query, complexity_value| complexity_value }
        DEPTH_ANALYZER = GraphQL::Analysis::QueryDepth.new { |query, depth_value| depth_value }

C
charlieablett 已提交
10
        def analyze?(query)
C
charlieablett 已提交
11
          Feature.enabled?(:graphql_logging, default_enabled: true)
C
charlieablett 已提交
12 13 14
        end

        def initial_value(query)
C
charlie ablett 已提交
15 16
          variables = process_variables(query.provided_variables)
          default_initial_values(query).merge({
C
charlieablett 已提交
17
            query_string: query.query_string,
C
charlie ablett 已提交
18 19 20 21 22
            variables: variables
          })
        rescue => e
          Gitlab::Sentry.track_exception(e)
          default_initial_values(query)
C
charlieablett 已提交
23 24 25
        end

        def call(memo, visit_type, irep_node)
26
          memo
C
charlieablett 已提交
27 28 29
        end

        def final_value(memo)
C
charlie ablett 已提交
30 31 32
          return if memo.nil?

          analyzers = [COMPLEXITY_ANALYZER, DEPTH_ANALYZER]
33 34 35 36 37 38 39
          complexity, depth = GraphQL::Analysis.analyze_query(memo[:query], analyzers)

          memo[:depth] = depth
          memo[:complexity] = complexity
          memo[:duration] = duration(memo[:time_started]).round(1)

          GraphqlLogger.info(memo.except!(:time_started, :query))
C
charlie ablett 已提交
40 41
        rescue => e
          Gitlab::Sentry.track_exception(e)
C
charlieablett 已提交
42 43 44 45
        end

        private

C
charlieablett 已提交
46
        def process_variables(variables)
C
charlie ablett 已提交
47 48
          if variables.respond_to?(:to_s)
            variables.to_s
C
charlieablett 已提交
49 50 51 52 53
          else
            variables
          end
        end

C
charlieablett 已提交
54
        def duration(time_started)
C
charlieablett 已提交
55 56
          nanoseconds = Gitlab::Metrics::System.monotonic_time - time_started
          nanoseconds * 1000000
C
charlieablett 已提交
57
        end
C
charlie ablett 已提交
58 59 60 61 62 63 64 65 66 67

        def default_initial_values(query)
          {
            time_started: Gitlab::Metrics::System.monotonic_time,
            query_string: nil,
            query: query,
            variables: nil,
            duration: nil
          }
        end
C
charlieablett 已提交
68 69 70 71
      end
    end
  end
end