summaryrefslogtreecommitdiff
path: root/lib/gitlab/tracking.rb
blob: 02d354ec43abc229d021d7cf61b188725231ea04 (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
72
73
# frozen_string_literal: true

require 'snowplow-tracker'

module Gitlab
  module Tracking
    SNOWPLOW_NAMESPACE = 'gl'

    module ControllerConcern
      extend ActiveSupport::Concern

      protected

      def track_event(action = action_name, **args)
        category = args.delete(:category) || self.class.name
        Gitlab::Tracking.event(category, action.to_s, **args)
      end

      def track_self_describing_event(schema_url, event_data_json, **args)
        Gitlab::Tracking.self_describing_event(schema_url, event_data_json, **args)
      end
    end

    class << self
      def enabled?
        Gitlab::CurrentSettings.snowplow_enabled?
      end

      def event(category, action, label: nil, property: nil, value: nil, context: nil)
        return unless enabled?

        snowplow.track_struct_event(category, action, label, property, value, context, (Time.now.to_f * 1000).to_i)
      end

      def self_describing_event(schema_url, event_data_json, context: nil)
        return unless enabled?

        event_json = SnowplowTracker::SelfDescribingJson.new(schema_url, event_data_json)
        snowplow.track_self_describing_event(event_json, context, (Time.now.to_f * 1000).to_i)
      end

      def snowplow_options(group)
        additional_features = Feature.enabled?(:additional_snowplow_tracking, group)
        {
          namespace: SNOWPLOW_NAMESPACE,
          hostname: Gitlab::CurrentSettings.snowplow_collector_hostname,
          cookie_domain: Gitlab::CurrentSettings.snowplow_cookie_domain,
          app_id: Gitlab::CurrentSettings.snowplow_app_id,
          form_tracking: additional_features,
          link_click_tracking: additional_features
        }.transform_keys! { |key| key.to_s.camelize(:lower).to_sym }
      end

      private

      def snowplow
        @snowplow ||= SnowplowTracker::Tracker.new(
          emitter,
          SnowplowTracker::Subject.new,
          SNOWPLOW_NAMESPACE,
          Gitlab::CurrentSettings.snowplow_app_id
        )
      end

      def emitter
        SnowplowTracker::AsyncEmitter.new(
          Gitlab::CurrentSettings.snowplow_collector_hostname,
          protocol: 'https'
        )
      end
    end
  end
end