2023-11-07 07:33:12 +01:00
|
|
|
class Expired::MailRateLimiter
|
2023-06-26 10:37:32 +02:00
|
|
|
attr_reader :delay, :current_window
|
|
|
|
|
|
|
|
def send_with_delay(mail)
|
|
|
|
if current_window_full?
|
|
|
|
@delay += @window
|
|
|
|
end
|
|
|
|
if current_window_full? || current_window_expired?
|
|
|
|
@current_window = { started_at: Time.current, sent: 0 }
|
|
|
|
end
|
|
|
|
@current_window[:sent] += 1
|
|
|
|
|
|
|
|
mail.deliver_later(wait: delay)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2023-11-07 07:33:12 +01:00
|
|
|
def initialize(limit: 200, window: 10.minutes)
|
2023-06-26 10:37:32 +02:00
|
|
|
@limit = limit
|
|
|
|
@window = window
|
|
|
|
@current_window = { started_at: Time.current, sent: 0 }
|
|
|
|
@delay = 0
|
|
|
|
end
|
|
|
|
|
|
|
|
def current_window_expired?
|
2023-06-26 15:23:59 +02:00
|
|
|
(@current_window[:started_at] + @window).past?
|
2023-06-26 10:37:32 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def current_window_full?
|
2023-06-26 15:23:59 +02:00
|
|
|
@current_window[:sent] >= @limit
|
2023-06-26 10:37:32 +02:00
|
|
|
end
|
|
|
|
end
|