1
0

delivery_failure_tracker.rb 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # frozen_string_literal: true
  2. class DeliveryFailureTracker
  3. FAILURE_DAYS_THRESHOLD = 7
  4. def initialize(url_or_host)
  5. @host = url_or_host.start_with?('https://') || url_or_host.start_with?('http://') ? Addressable::URI.parse(url_or_host).normalized_host : url_or_host
  6. end
  7. def track_failure!
  8. Redis.current.sadd(exhausted_deliveries_key, today)
  9. UnavailableDomain.create(domain: @host) if reached_failure_threshold?
  10. end
  11. def track_success!
  12. Redis.current.del(exhausted_deliveries_key)
  13. UnavailableDomain.find_by(domain: @host)&.destroy
  14. end
  15. def days
  16. Redis.current.scard(exhausted_deliveries_key) || 0
  17. end
  18. def available?
  19. !UnavailableDomain.where(domain: @host).exists?
  20. end
  21. alias reset! track_success!
  22. class << self
  23. def without_unavailable(urls)
  24. unavailable_domains_map = Rails.cache.fetch('unavailable_domains') { UnavailableDomain.pluck(:domain).each_with_object({}) { |domain, hash| hash[domain] = true } }
  25. urls.reject do |url|
  26. host = Addressable::URI.parse(url).normalized_host
  27. unavailable_domains_map[host]
  28. end
  29. end
  30. def available?(url)
  31. new(url).available?
  32. end
  33. def reset!(url)
  34. new(url).reset!
  35. end
  36. end
  37. private
  38. def exhausted_deliveries_key
  39. "exhausted_deliveries:#{@host}"
  40. end
  41. def today
  42. Time.now.utc.strftime('%Y%m%d')
  43. end
  44. def reached_failure_threshold?
  45. days >= FAILURE_DAYS_THRESHOLD
  46. end
  47. end