summaryrefslogtreecommitdiff
path: root/lib/gitlab/graphql/query_analyzers/logger_analyzer.rb
blob: 01b55a1667f5da239bf7c709a7e2a5492932ea20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# frozen_string_literal: true

module Gitlab
  module Graphql
    module QueryAnalyzers
      class LoggerAnalyzer
        COMPLEXITY_ANALYZER = GraphQL::Analysis::QueryComplexity.new { |query, complexity_value| complexity_value }
        DEPTH_ANALYZER = GraphQL::Analysis::QueryDepth.new { |query, depth_value| depth_value }

        def analyze?(query)
          Feature.enabled?(:graphql_logging, default_enabled: true)
        end

        def initial_value(query)
          variables = process_variables(query.provided_variables)
          default_initial_values(query).merge({
            query_string: query.query_string,
            variables: variables
          })
        rescue => e
          Gitlab::Sentry.track_exception(e)
          default_initial_values(query)
        end

        def call(memo, visit_type, irep_node)
          memo
        end

        def final_value(memo)
          return if memo.nil?

          analyzers = [COMPLEXITY_ANALYZER, DEPTH_ANALYZER]
          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))
        rescue => e
          Gitlab::Sentry.track_exception(e)
        end

        private

        def process_variables(variables)
          if variables.respond_to?(:to_s)
            variables.to_s
          else
            variables
          end
        end

        def duration(time_started)
          nanoseconds = Gitlab::Metrics::System.monotonic_time - time_started
          nanoseconds * 1000000
        end

        def default_initial_values(query)
          {
            time_started: Gitlab::Metrics::System.monotonic_time,
            query_string: nil,
            query: query,
            variables: nil,
            duration: nil
          }
        end
      end
    end
  end
end