summaryrefslogtreecommitdiff
path: root/lib/gitlab/database/reindexing/reindex_action.rb
blob: 7e58201889fc2e359d61da920495fa1ce88c5253 (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
# frozen_string_literal: true

module Gitlab
  module Database
    module Reindexing
      class ReindexAction < ActiveRecord::Base
        self.table_name = 'postgres_reindex_actions'

        belongs_to :index, foreign_key: :index_identifier, class_name: 'Gitlab::Database::PostgresIndex'
        enum state: { started: 0, finished: 1, failed: 2 }

        # Amount of time to consider a previous reindexing *recent*
        RECENT_THRESHOLD = 7.days

        scope :recent, -> { where(state: :finished).where('action_end > ?', Time.zone.now - RECENT_THRESHOLD) }

        def self.create_for(index)
          create!(
            index_identifier: index.identifier,
            action_start: Time.zone.now,
            ondisk_size_bytes_start: index.ondisk_size_bytes,
            bloat_estimate_bytes_start: index.bloat_size
          )
        end

        def finish
          index.reload # rubocop:disable Cop/ActiveRecordAssociationReload

          self.state = :finished unless failed?
          self.action_end = Time.zone.now
          self.ondisk_size_bytes_end = index.ondisk_size_bytes

          save!
        end
      end
    end
  end
end