summaryrefslogtreecommitdiff
path: root/app/services/users/activity_service.rb
blob: c8f9c28061f06e04d96f7f9414c4d5aa4e8aa376 (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
# frozen_string_literal: true

module Users
  class ActivityService
    LEASE_TIMEOUT = 1.minute.to_i

    def initialize(author:, namespace: nil, project: nil)
      @user = if author.respond_to?(:username)
                author
              elsif author.respond_to?(:user)
                author.user
              end

      @user = nil unless user.is_a?(User)
      @namespace = namespace
      @project = project
    end

    def execute
      return unless user

      ::Gitlab::Database::LoadBalancing::Session.without_sticky_writes { record_activity }
    end

    private

    attr_reader :user, :namespace, :project

    def record_activity
      return if Gitlab::Database.read_only?

      today = Date.today

      return if user.last_activity_on == today

      lease = Gitlab::ExclusiveLease.new("activity_service:#{user.id}",
                                         timeout: LEASE_TIMEOUT)
      return unless lease.try_obtain

      user.update_attribute(:last_activity_on, today)

      Gitlab::UsageDataCounters::HLLRedisCounter.track_event('unique_active_user', values: user.id)

      return unless Feature.enabled?(:route_hll_to_snowplow_phase3)

      Gitlab::Tracking.event(
        'Users::ActivityService',
        'perform_action',
        user: user,
        namespace: namespace,
        project: project,
        label: 'redis_hll_counters.manage.unique_active_users_monthly',
        context: [
          Gitlab::Tracking::ServicePingContext.new(data_source: :redis_hll, event: 'unique_active_user').to_context
        ]
      )
    end
  end
end