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.

88 lines
2.1 KiB

  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 clear_failures!
  16. Redis.current.del(exhausted_deliveries_key)
  17. end
  18. def days
  19. Redis.current.scard(exhausted_deliveries_key) || 0
  20. end
  21. def available?
  22. !UnavailableDomain.where(domain: @host).exists?
  23. end
  24. def exhausted_deliveries_days
  25. @exhausted_deliveries_days ||= Redis.current.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) }
  26. end
  27. alias reset! track_success!
  28. class << self
  29. def without_unavailable(urls)
  30. unavailable_domains_map = Rails.cache.fetch('unavailable_domains') { UnavailableDomain.pluck(:domain).index_with(true) }
  31. urls.reject do |url|
  32. host = Addressable::URI.parse(url).normalized_host
  33. unavailable_domains_map[host]
  34. end
  35. end
  36. def available?(url)
  37. new(url).available?
  38. end
  39. def reset!(url)
  40. new(url).reset!
  41. end
  42. def warning_domains
  43. domains = Redis.current.keys(exhausted_deliveries_key_by('*')).map do |key|
  44. key.delete_prefix(exhausted_deliveries_key_by(''))
  45. end
  46. domains - UnavailableDomain.all.pluck(:domain)
  47. end
  48. def warning_domains_map
  49. warning_domains.index_with { |domain| Redis.current.scard(exhausted_deliveries_key_by(domain)) }
  50. end
  51. private
  52. def exhausted_deliveries_key_by(host)
  53. "exhausted_deliveries:#{host}"
  54. end
  55. end
  56. private
  57. def exhausted_deliveries_key
  58. "exhausted_deliveries:#{@host}"
  59. end
  60. def today
  61. Time.now.utc.strftime('%Y%m%d')
  62. end
  63. def reached_failure_threshold?
  64. days >= FAILURE_DAYS_THRESHOLD
  65. end
  66. end