summaryrefslogtreecommitdiff
path: root/app/workers/users/deactivate_dormant_users_worker.rb
blob: d7ea20e4b62c8b026dd7877fb0b1d0983ac63c2a (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
# frozen_string_literal: true

module Users
  class DeactivateDormantUsersWorker # rubocop:disable Scalability/IdempotentWorker
    include ApplicationWorker

    data_consistency :always

    include CronjobQueue

    feature_category :utilization

    NUMBER_OF_BATCHES = 50
    BATCH_SIZE = 200
    PAUSE_SECONDS = 0.25

    def perform
      return if Gitlab.com?

      return unless ::Gitlab::CurrentSettings.current_application_settings.deactivate_dormant_users

      with_context(caller_id: self.class.name.to_s) do
        NUMBER_OF_BATCHES.times do
          result = User.connection.execute(update_query)

          break if result.cmd_tuples == 0

          sleep(PAUSE_SECONDS)
        end
      end
    end

    private

    def update_query
      <<~SQL
        UPDATE "users"
        SET "state" = 'deactivated'
        WHERE "users"."id" IN (
          (#{users.dormant.to_sql})
          UNION
          (#{users.with_no_activity.to_sql})
          LIMIT #{BATCH_SIZE}
        )
      SQL
    end

    def users
      User.select(:id).limit(BATCH_SIZE)
    end
  end
end