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.

92 lines
2.1 KiB

  1. # frozen_string_literal: true
  2. class DeliveryFailureTracker
  3. include Redisable
  4. FAILURE_DAYS_THRESHOLD = 7
  5. def initialize(url_or_host)
  6. @host = url_or_host.start_with?('https://') || url_or_host.start_with?('http://') ? Addressable::URI.parse(url_or_host).normalized_host : url_or_host
  7. end
  8. def track_failure!
  9. redis.sadd(exhausted_deliveries_key, today)
  10. UnavailableDomain.create(domain: @host) if reached_failure_threshold?
  11. end
  12. def track_success!
  13. redis.del(exhausted_deliveries_key)
  14. UnavailableDomain.find_by(domain: @host)&.destroy
  15. end
  16. def clear_failures!
  17. redis.del(exhausted_deliveries_key)
  18. end
  19. def days
  20. redis.scard(exhausted_deliveries_key) || 0
  21. end
  22. def available?
  23. !UnavailableDomain.where(domain: @host).exists?
  24. end
  25. def exhausted_deliveries_days
  26. @exhausted_deliveries_days ||= redis.smembers(exhausted_deliveries_key).sort.map { |date| Date.new(date.slice(0, 4).to_i, date.slice(4, 2).to_i, date.slice(6, 2).to_i) }
  27. end
  28. alias reset! track_success!
  29. class << self
  30. include Redisable
  31. def without_unavailable(urls)
  32. unavailable_domains_map = Rails.cache.fetch('unavailable_domains') { UnavailableDomain.pluck(:domain).index_with(true) }
  33. urls.reject do |url|
  34. host = Addressable::URI.parse(url).normalized_host
  35. unavailable_domains_map[host]
  36. end
  37. end
  38. def available?(url)
  39. new(url).available?
  40. end
  41. def reset!(url)
  42. new(url).reset!
  43. end
  44. def warning_domains
  45. domains = redis.keys(exhausted_deliveries_key_by('*')).map do |key|
  46. key.delete_prefix(exhausted_deliveries_key_by(''))
  47. end
  48. domains - UnavailableDomain.all.pluck(:domain)
  49. end
  50. def warning_domains_map
  51. warning_domains.index_with { |domain| redis.scard(exhausted_deliveries_key_by(domain)) }
  52. end
  53. private
  54. def exhausted_deliveries_key_by(host)
  55. "exhausted_deliveries:#{host}"
  56. end
  57. end
  58. private
  59. def exhausted_deliveries_key
  60. "exhausted_deliveries:#{@host}"
  61. end
  62. def today
  63. Time.now.utc.strftime('%Y%m%d')
  64. end
  65. def reached_failure_threshold?
  66. days >= FAILURE_DAYS_THRESHOLD
  67. end
  68. end