about summary refs log tree commit diff
path: root/app/lib/vacuum/statuses_vacuum.rb
blob: 41d6ba270cc53178398b8b1676a8e4ba3a56955c (plain) (blame)
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
# frozen_string_literal: true

class Vacuum::StatusesVacuum
  include Redisable

  def initialize(retention_period)
    @retention_period = retention_period
  end

  def perform
    vacuum_statuses! if retention_period?
  end

  private

  def vacuum_statuses!
    statuses_scope.find_in_batches do |statuses|
      # Side-effects not covered by foreign keys, such
      # as the search index, must be handled first.

      remove_from_account_conversations(statuses)
      remove_from_search_index(statuses)

      # Foreign keys take care of most associated records
      # for us. Media attachments will be orphaned.

      Status.where(id: statuses.map(&:id)).delete_all
    end
  end

  def statuses_scope
    Status.unscoped.kept.where(account: Account.remote).where(Status.arel_table[:id].lt(retention_period_as_id)).select(:id, :visibility)
  end

  def retention_period_as_id
    Mastodon::Snowflake.id_at(@retention_period.ago, with_random: false)
  end

  def analyze_statuses!
    ActiveRecord::Base.connection.execute('ANALYZE statuses')
  end

  def remove_from_account_conversations(statuses)
    Status.where(id: statuses.select(&:direct_visibility?).map(&:id)).includes(:account, mentions: :account).each(&:unlink_from_conversations)
  end

  def remove_from_search_index(statuses)
    with_redis { |redis| redis.sadd('chewy:queue:StatusesIndex', statuses.map(&:id)) } if Chewy.enabled?
  end

  def retention_period?
    @retention_period.present?
  end
end