Class: Tolliver::Services::DeliveryService

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/tolliver/services/delivery_service.rb

Instance Method Summary collapse

Instance Method Details

#deliver(notification) ⇒ Object

Deliver notification to receivers by all configured methods



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/tolliver/services/delivery_service.rb', line 25

def deliver(notification)
  return nil if notification.nil?

  # Load balancing
  unless Tolliver.load_balance.blank?
    notifications_sent_in_protected_time_window = Tolliver.notification_model
                                                      .joins(:notification_deliveries)
                                                      .where.not(id: notification.id)
                                                      .where("notification_deliveries.sent_at > ?", Time.current - Tolliver.load_balance.minutes).distinct
    if notifications_sent_in_protected_time_window.count > 0

      # Sleep for given amount of time
      sleep(Tolliver.load_balance * 60) # seconds

      # Then try again
      enqueue_for_delivery(notification)

      return false
    end
  end

  # Process all notification deliveries
  notification.notification_deliveries.each do |notification_delivery|
    notification_delivery.policy_service.deliver(notification_delivery)
  end

  true
end

#enqueue_for_delivery(notification) ⇒ Object



19
20
21
22
# File 'lib/tolliver/services/delivery_service.rb', line 19

def enqueue_for_delivery(notification)
  return nil if notification.nil?
  Tolliver::Jobs::DeliveryJob.perform_later(notification.id)
end

#reset_delivery(notification) ⇒ Object



54
55
56
57
58
59
# File 'lib/tolliver/services/delivery_service.rb', line 54

def reset_delivery(notification)
  return nil if notification.nil?
  notification.notification_deliveries.update_all(sent_count: 0, sent_at: nil)
  notification.notification_receivers.update_all(sent_at: nil, received_at: nil, status: :created, error_message: nil)
  true
end