Class: EventMachine::HttpFetcher::RequestPool

Inherits:
Object
  • Object
show all
Defined in:
lib/em/http-fetcher/fetcher.rb

Instance Method Summary collapse

Constructor Details

#initialize(total_size, host_resource_size, host_reuse_wait = 0, opts = {}) ⇒ RequestPool

Returns a new instance of RequestPool.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/em/http-fetcher/fetcher.rb', line 23

def initialize(total_size, host_resource_size, host_reuse_wait = 0, opts = {})
  super()
  @total_size         = total_size
  @host_reuse_wait    = host_reuse_wait
  @host_resource_size = host_resource_size

  @total_queue        = EM::Queue.new
  total_size.times { @total_queue.push true }
  @host_pools         = Hash.new {|h, k|
    pool = EM::Pool.new
    def pool.add item
      super
      @removed.delete item
    end
    host_resource_size.times {
      pool.add EM::HttpRequest.new(k)
    }
    h[k] = { pool: pool, last_used: Time.now }
  }
  run
end

Instance Method Details

#perform(host, &b) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/em/http-fetcher/fetcher.rb', line 45

def perform(host, &b)
  @host_pools[host][:pool].perform do |conn|
    df = nil
    @total_queue.pop do |tqi|
      @host_pools[host][:last_used] = Time.now
      @host_pools[host][:pool].remove conn
      rq = proc { |req|
        @total_queue.push tqi
        lurl = req.last_effective_url
        unless "#{lurl.scheme}://#{lurl.host}" == host
          # Connection has been redirected another server.
          # Re-create connection instance.
          conn = EM::HttpRequest.new(host)
        end

        if @host_reuse_wait > 0
          EM.add_timer(@host_reuse_wait) {
            @host_pools[host][:pool].add conn
          }
        else
          @host_pools[host][:pool].add conn
        end
      }
      work = EM::Callback(&b)
      df = work.call(conn)
      df.callback(&rq)
      df.errback(&rq)
      df
    end
    df
  end
end

#runObject



78
79
80
81
82
83
84
85
86
87
88
# File 'lib/em/http-fetcher/fetcher.rb', line 78

def run
  # cleanup host pool timer
  EM.add_periodic_timer(10) do
    hrsize = @host_resource_size
    @host_pools.each do |host, info|
      info[:pool].instance_eval { @resources.size < hrsize } and next
      info[:last_used].to_i > Time.now.to_i - 5 * 60 and next
      @host_pools.delete host
    end
  end
end