You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

171 lines
6.6 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: account_statuses_cleanup_policies
  5. #
  6. # id :bigint not null, primary key
  7. # account_id :bigint not null
  8. # enabled :boolean default(TRUE), not null
  9. # min_status_age :integer default(1209600), not null
  10. # keep_direct :boolean default(TRUE), not null
  11. # keep_pinned :boolean default(TRUE), not null
  12. # keep_polls :boolean default(FALSE), not null
  13. # keep_media :boolean default(FALSE), not null
  14. # keep_self_fav :boolean default(TRUE), not null
  15. # keep_self_bookmark :boolean default(TRUE), not null
  16. # min_favs :integer
  17. # min_reblogs :integer
  18. # created_at :datetime not null
  19. # updated_at :datetime not null
  20. #
  21. class AccountStatusesCleanupPolicy < ApplicationRecord
  22. include Redisable
  23. ALLOWED_MIN_STATUS_AGE = [
  24. 2.weeks.seconds,
  25. 1.month.seconds,
  26. 2.months.seconds,
  27. 3.months.seconds,
  28. 6.months.seconds,
  29. 1.year.seconds,
  30. 2.years.seconds,
  31. ].freeze
  32. EXCEPTION_BOOLS = %w(keep_direct keep_pinned keep_polls keep_media keep_self_fav keep_self_bookmark).freeze
  33. EXCEPTION_THRESHOLDS = %w(min_favs min_reblogs).freeze
  34. # Depending on the cleanup policy, the query to discover the next
  35. # statuses to delete my get expensive if the account has a lot of old
  36. # statuses otherwise excluded from deletion by the other exceptions.
  37. #
  38. # Therefore, `EARLY_SEARCH_CUTOFF` is meant to be the maximum number of
  39. # old statuses to be considered for deletion prior to checking exceptions.
  40. #
  41. # This is used in `compute_cutoff_id` to provide a `max_id` to
  42. # `statuses_to_delete`.
  43. EARLY_SEARCH_CUTOFF = 5_000
  44. belongs_to :account
  45. validates :min_status_age, inclusion: { in: ALLOWED_MIN_STATUS_AGE }
  46. validates :min_favs, numericality: { greater_than_or_equal_to: 1, allow_nil: true }
  47. validates :min_reblogs, numericality: { greater_than_or_equal_to: 1, allow_nil: true }
  48. validate :validate_local_account
  49. before_save :update_last_inspected
  50. def statuses_to_delete(limit = 50, max_id = nil, min_id = nil)
  51. scope = account.statuses
  52. scope.merge!(old_enough_scope(max_id))
  53. scope = scope.where(Status.arel_table[:id].gteq(min_id)) if min_id.present?
  54. scope.merge!(without_popular_scope) unless min_favs.nil? && min_reblogs.nil?
  55. scope.merge!(without_direct_scope) if keep_direct?
  56. scope.merge!(without_pinned_scope) if keep_pinned?
  57. scope.merge!(without_poll_scope) if keep_polls?
  58. scope.merge!(without_media_scope) if keep_media?
  59. scope.merge!(without_self_fav_scope) if keep_self_fav?
  60. scope.merge!(without_self_bookmark_scope) if keep_self_bookmark?
  61. scope.reorder(id: :asc).limit(limit)
  62. end
  63. # This computes a toot id such that:
  64. # - the toot would be old enough to be candidate for deletion
  65. # - there are at most EARLY_SEARCH_CUTOFF toots between the last inspected toot and this one
  66. #
  67. # The idea is to limit expensive SQL queries when an account has lots of toots excluded from
  68. # deletion, while not starting anew on each run.
  69. def compute_cutoff_id
  70. min_id = last_inspected || 0
  71. max_id = Mastodon::Snowflake.id_at(min_status_age.seconds.ago, with_random: false)
  72. subquery = account.statuses.where(Status.arel_table[:id].gteq(min_id)).where(Status.arel_table[:id].lteq(max_id))
  73. subquery = subquery.select(:id).reorder(id: :asc).limit(EARLY_SEARCH_CUTOFF)
  74. # We're textually interpolating a subquery here as ActiveRecord seem to not provide
  75. # a way to apply the limit to the subquery
  76. Status.connection.execute("SELECT MAX(id) FROM (#{subquery.to_sql}) t").values.first.first
  77. end
  78. # The most important thing about `last_inspected` is that any toot older than it is guaranteed
  79. # not to be kept by the policy regardless of its age.
  80. def record_last_inspected(last_id)
  81. redis.set("account_cleanup:#{account.id}", last_id, ex: 1.week.seconds)
  82. end
  83. def last_inspected
  84. redis.get("account_cleanup:#{account.id}")&.to_i
  85. end
  86. def invalidate_last_inspected(status, action)
  87. last_value = last_inspected
  88. return if last_value.nil? || status.id > last_value || status.account_id != account_id
  89. case action
  90. when :unbookmark
  91. return unless keep_self_bookmark?
  92. when :unfav
  93. return unless keep_self_fav?
  94. when :unpin
  95. return unless keep_pinned?
  96. end
  97. record_last_inspected(status.id)
  98. end
  99. private
  100. def update_last_inspected
  101. if EXCEPTION_BOOLS.map { |name| attribute_change_to_be_saved(name) }.compact.include?([true, false])
  102. # Policy has been widened in such a way that any previously-inspected status
  103. # may need to be deleted, so we'll have to start again.
  104. redis.del("account_cleanup:#{account.id}")
  105. end
  106. if EXCEPTION_THRESHOLDS.map { |name| attribute_change_to_be_saved(name) }.compact.any? { |old, new| old.present? && (new.nil? || new > old) }
  107. redis.del("account_cleanup:#{account.id}")
  108. end
  109. end
  110. def validate_local_account
  111. errors.add(:account, :invalid) unless account&.local?
  112. end
  113. def without_direct_scope
  114. Status.where.not(visibility: :direct)
  115. end
  116. def old_enough_scope(max_id = nil)
  117. # Filtering on `id` rather than `min_status_age` ago will treat
  118. # non-snowflake statuses as older than they really are, but Mastodon
  119. # has switched to snowflake IDs significantly over 2 years ago anyway.
  120. max_id = [max_id, Mastodon::Snowflake.id_at(min_status_age.seconds.ago, with_random: false)].compact.min
  121. Status.where(Status.arel_table[:id].lteq(max_id))
  122. end
  123. def without_self_fav_scope
  124. Status.where('NOT EXISTS (SELECT * FROM favourites fav WHERE fav.account_id = statuses.account_id AND fav.status_id = statuses.id)')
  125. end
  126. def without_self_bookmark_scope
  127. Status.where('NOT EXISTS (SELECT * FROM bookmarks bookmark WHERE bookmark.account_id = statuses.account_id AND bookmark.status_id = statuses.id)')
  128. end
  129. def without_pinned_scope
  130. Status.where('NOT EXISTS (SELECT * FROM status_pins pin WHERE pin.account_id = statuses.account_id AND pin.status_id = statuses.id)')
  131. end
  132. def without_media_scope
  133. Status.where('NOT EXISTS (SELECT * FROM media_attachments media WHERE media.status_id = statuses.id)')
  134. end
  135. def without_poll_scope
  136. Status.where(poll_id: nil)
  137. end
  138. def without_popular_scope
  139. scope = Status.left_joins(:status_stat)
  140. scope = scope.where('COALESCE(status_stats.reblogs_count, 0) <= ?', min_reblogs) unless min_reblogs.nil?
  141. scope = scope.where('COALESCE(status_stats.favourites_count, 0) <= ?', min_favs) unless min_favs.nil?
  142. scope
  143. end
  144. end