]> cat aescling's git repositories - mastodon.git/blob - app/lib/delivery_failure_tracker.rb
Update Mastodon to Rails 6.1 (#15910)
[mastodon.git] / app / lib / delivery_failure_tracker.rb
1 # frozen_string_literal: true
2
3 class DeliveryFailureTracker
4 FAILURE_DAYS_THRESHOLD = 7
5
6 def initialize(url_or_host)
7 @host = url_or_host.start_with?('https://') || url_or_host.start_with?('http://') ? Addressable::URI.parse(url_or_host).normalized_host : url_or_host
8 end
9
10 def track_failure!
11 Redis.current.sadd(exhausted_deliveries_key, today)
12 UnavailableDomain.create(domain: @host) if reached_failure_threshold?
13 end
14
15 def track_success!
16 Redis.current.del(exhausted_deliveries_key)
17 UnavailableDomain.find_by(domain: @host)&.destroy
18 end
19
20 def days
21 Redis.current.scard(exhausted_deliveries_key) || 0
22 end
23
24 def available?
25 !UnavailableDomain.where(domain: @host).exists?
26 end
27
28 alias reset! track_success!
29
30 class << self
31 def without_unavailable(urls)
32 unavailable_domains_map = Rails.cache.fetch('unavailable_domains') { UnavailableDomain.pluck(:domain).index_with(true) }
33
34 urls.reject do |url|
35 host = Addressable::URI.parse(url).normalized_host
36 unavailable_domains_map[host]
37 end
38 end
39
40 def available?(url)
41 new(url).available?
42 end
43
44 def reset!(url)
45 new(url).reset!
46 end
47 end
48
49 private
50
51 def exhausted_deliveries_key
52 "exhausted_deliveries:#{@host}"
53 end
54
55 def today
56 Time.now.utc.strftime('%Y%m%d')
57 end
58
59 def reached_failure_threshold?
60 days >= FAILURE_DAYS_THRESHOLD
61 end
62 end
This page took 0.102439 seconds and 4 git commands to generate.