instance.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. self.primary_key = :domain
  11. attr_accessor :failure_days
  12. has_many :accounts, foreign_key: :domain, primary_key: :domain, inverse_of: false
  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 # skipcq: RB-RL1031
  17. end
  18. scope :searchable, -> { where.not(domain: DomainBlock.select(:domain)) }
  19. scope :matches_domain, ->(value) { where(arel_table[:domain].matches("%#{value}%")) }
  20. scope :by_domain_and_subdomains, ->(domain) { where("reverse('.' || domain) LIKE reverse(?)", "%.#{domain}") }
  21. def self.refresh
  22. Scenic.database.refresh_materialized_view(table_name, concurrently: true, cascade: false)
  23. end
  24. def readonly?
  25. true
  26. end
  27. def delivery_failure_tracker
  28. @delivery_failure_tracker ||= DeliveryFailureTracker.new(domain)
  29. end
  30. def purgeable?
  31. unavailable? || domain_block&.suspend?
  32. end
  33. def unavailable?
  34. unavailable_domain.present?
  35. end
  36. def failing?
  37. failure_days.present? || unavailable?
  38. end
  39. def to_param
  40. domain
  41. end
  42. alias to_log_human_identifier to_param
  43. delegate :exhausted_deliveries_days, to: :delivery_failure_tracker
  44. def availability_over_days(num_days, end_date = Time.now.utc.to_date)
  45. failures_map = exhausted_deliveries_days.index_with { true }
  46. period_end_at = exhausted_deliveries_days.last || end_date
  47. period_start_at = period_end_at - num_days.days
  48. (period_start_at..period_end_at).map do |date|
  49. [date, failures_map[date]]
  50. end
  51. end
  52. end