summaryrefslogtreecommitdiff
path: root/lib/gitlab/error_tracking/context_payload_generator.rb
blob: 3d0a707608f9c3da6158f0d50b685c1e6bb61a3c (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
# frozen_string_literal: true

module Gitlab
  module ErrorTracking
    class ContextPayloadGenerator
      def self.generate(exception, extra = {})
        new.generate(exception, extra)
      end

      def generate(exception, extra = {})
        {
          extra: extra_payload(exception, extra),
          tags: tags_payload,
          user: user_payload
        }
      end

      private

      def extra_payload(exception, extra)
        inline_extra = exception.try(:sentry_extra_data)
        if inline_extra.present? && inline_extra.is_a?(Hash)
          extra = extra.merge(inline_extra)
        end

        sanitize_request_parameters(extra)
      end

      def sanitize_request_parameters(parameters)
        filter = ActiveSupport::ParameterFilter.new(::Rails.application.config.filter_parameters)
        filter.filter(parameters)
      end

      def tags_payload
        extra_tags_from_env.merge!(
          program: Gitlab.process_name,
          locale: I18n.locale,
          feature_category: current_context['meta.feature_category'],
          Labkit::Correlation::CorrelationId::LOG_KEY.to_sym => Labkit::Correlation::CorrelationId.current_id
        )
      end

      def user_payload
        {
          username: current_context['meta.user']
        }
      end

      # Static tags that are set on application start
      def extra_tags_from_env
        Gitlab::Json.parse(ENV.fetch('GITLAB_SENTRY_EXTRA_TAGS', '{}')).to_hash
      rescue StandardError => e
        Gitlab::AppLogger.debug("GITLAB_SENTRY_EXTRA_TAGS could not be parsed as JSON: #{e.class.name}: #{e.message}")

        {}
      end

      def current_context
        # In case Gitlab::ErrorTracking is used when the app starts
        return {} unless defined?(::Gitlab::ApplicationContext)

        ::Gitlab::ApplicationContext.current.to_h
      end
    end
  end
end