instance.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: instances
  5. #
  6. # domain :string primary key
  7. # accounts_count :bigint(8)
  8. #
  9. class Instance < ApplicationRecord
  10. include DatabaseViewRecord
  11. self.primary_key = :domain
  12. attr_accessor :failure_days
  13. with_options foreign_key: :domain, primary_key: :domain, inverse_of: false do
  14. belongs_to :domain_block
  15. belongs_to :domain_allow
  16. belongs_to :unavailable_domain
  17. has_many :accounts, dependent: nil
  18. end
  19. scope :searchable, -> { where.not(domain: DomainBlock.select(:domain)) }
  20. scope :matches_domain, ->(value) { where(arel_table[:domain].matches("%#{value}%")) }
  21. scope :domain_starts_with, ->(value) { where(arel_table[:domain].matches("#{sanitize_sql_like(value)}%", false, true)) }
  22. scope :by_domain_and_subdomains, ->(domain) { where("reverse('.' || domain) LIKE reverse(?)", "%.#{domain}") }
  23. scope :with_domain_follows, ->(domains) { where(domain: domains).where(domain_account_follows) }
  24. def self.domain_account_follows
  25. Arel.sql(
  26. <<~SQL.squish
  27. EXISTS (
  28. SELECT 1
  29. FROM follows
  30. JOIN accounts ON follows.account_id = accounts.id OR follows.target_account_id = accounts.id
  31. WHERE accounts.domain = instances.domain
  32. )
  33. SQL
  34. )
  35. end
  36. def delivery_failure_tracker
  37. @delivery_failure_tracker ||= DeliveryFailureTracker.new(domain)
  38. end
  39. def purgeable?
  40. unavailable? || domain_block&.suspend?
  41. end
  42. def unavailable?
  43. unavailable_domain.present?
  44. end
  45. def failing?
  46. failure_days.present? || unavailable?
  47. end
  48. def to_param
  49. domain
  50. end
  51. alias to_log_human_identifier to_param
  52. delegate :exhausted_deliveries_days, to: :delivery_failure_tracker
  53. def availability_over_days(num_days, end_date = Time.now.utc.to_date)
  54. failures_map = exhausted_deliveries_days.index_with { true }
  55. period_end_at = exhausted_deliveries_days.last || end_date
  56. period_start_at = period_end_at - num_days.days
  57. (period_start_at..period_end_at).map do |date|
  58. [date, failures_map[date]]
  59. end
  60. end
  61. end