summaryrefslogtreecommitdiff
path: root/lib/service_ping/build_payload.rb
blob: 4d3b32a1fc0e967e1de18d005b5d75ba1a9157bd (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
# frozen_string_literal: true

module ServicePing
  class BuildPayload
    def execute
      return {} unless ServicePingSettings.product_intelligence_enabled?

      filtered_usage_data
    end

    private

    def raw_payload
      @raw_payload ||= ::Gitlab::Usage::ServicePingReport.for(output: :all_metrics_values)
    end

    def filtered_usage_data(payload = raw_payload, parents = [])
      return unless payload.is_a?(Hash)

      payload.keep_if do |label, node|
        key_path = parents.dup.append(label).join('.')

        if has_metric_definition?(key_path)
          include_metric?(key_path)
        else
          filtered_usage_data(node, parents.dup << label) if node.is_a?(Hash)
        end
      end
    end

    def include_metric?(key_path)
      valid_metric_status?(key_path) && permitted_metric?(key_path)
    end

    def valid_metric_status?(key_path)
      metric_definitions[key_path]&.valid_service_ping_status?
    end

    def permitted_categories
      @permitted_categories ||= ::ServicePing::PermitDataCategories.new.execute
    end

    def permitted_metric?(key_path)
      permitted_categories.include?(metric_category(key_path))
    end

    def has_metric_definition?(key_path)
      metric_definitions[key_path].present?
    end

    def metric_category(key_path)
      metric_definitions[key_path]
        &.attributes
        &.fetch(:data_category, ::ServicePing::PermitDataCategories::OPTIONAL_CATEGORY)
    end

    def metric_definitions
      @metric_definitions ||= ::Gitlab::Usage::MetricDefinition.definitions
    end
  end
end

ServicePing::BuildPayload.prepend_mod_with('ServicePing::BuildPayload')