1# frozen_string_literal: true
2
3require 'connection_pool'
4require 'mail/smtp_pool/connection'
5
6module Mail
7  class SMTPPool
8    POOL_DEFAULTS = {
9      pool_size: 5,
10      pool_timeout: 5
11    }.freeze
12
13    class << self
14      def create_pool(settings = {})
15        pool_settings = POOL_DEFAULTS.merge(settings)
16        smtp_settings = settings.reject { |k, v| POOL_DEFAULTS.keys.include?(k) }
17
18        ConnectionPool.new(size: pool_settings[:pool_size], timeout: pool_settings[:pool_timeout]) do
19          Mail::SMTPPool::Connection.new(smtp_settings)
20        end
21      end
22    end
23
24    def initialize(settings)
25      raise ArgumentError, 'pool is required. You can create one using Mail::SMTPPool.create_pool.' if settings[:pool].nil?
26
27      @pool = settings[:pool]
28    end
29
30    def deliver!(mail)
31      @pool.with { |conn| conn.deliver!(mail) }
32    end
33
34    # This makes it compatible with Mail's `#deliver!` method
35    # https://github.com/mikel/mail/blob/22a7afc23f253319965bf9228a0a430eec94e06d/lib/mail/message.rb#L271
36    def settings
37      {}
38    end
39  end
40end
41