Class: Revactor::HttpFetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/revactor/http_fetcher.rb

Overview

A concurrent HTTP fetcher, implemented using a central dispatcher which scatters requests to a worker pool.

The HttpFetcher class is callback-driven and intended for subclassing. When a request completes successfully, the on_success callback is called. An on_failure callback represents non-200 HTTP responses, and on_error delivers any exceptions which occured during the fetch.

Defined Under Namespace

Classes: Worker

Instance Method Summary collapse

Constructor Details

#initialize(nworkers = 8) ⇒ HttpFetcher

Returns a new instance of HttpFetcher.



19
20
21
22
23
# File 'lib/revactor/http_fetcher.rb', line 19

def initialize(nworkers = 8)
  @_nworkers = nworkers
  @_workers, @_queue = [], []
  nworkers.times { @_workers << Worker.spawn(Actor.current) }
end

Instance Method Details

#get(url, *args) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/revactor/http_fetcher.rb', line 25

def get(url, *args)
  if @_workers.empty?
    @_queue << T[url, args]
  else
    @_workers.shift << T[:fetch, url, args]
  end
end

#on_emptyObject



55
# File 'lib/revactor/http_fetcher.rb', line 55

def on_empty; exit; end

#on_error(url, ex, *args) ⇒ Object



54
# File 'lib/revactor/http_fetcher.rb', line 54

def on_error(url, ex, *args); end

#on_failure(url, status, *args) ⇒ Object



53
# File 'lib/revactor/http_fetcher.rb', line 53

def on_failure(url, status, *args); end

#on_success(url, document, *args) ⇒ Object



52
# File 'lib/revactor/http_fetcher.rb', line 52

def on_success(url, document, *args); end

#runObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/revactor/http_fetcher.rb', line 33

def run
  while true
    Actor.receive do |filter|
      filter.when(T[:ready]) do |_, worker|
        if @_queue.empty?
          @_workers << worker
          on_empty if @_workers.size == @_nworkers
        else
          worker << T[:fetch, *@_queue.shift]
        end
      end

      filter.when(T[:fetched]) { |_, url, document, args| on_success url, document, *args }
      filter.when(T[:failed])  { |_, url, status, args| on_failure url, status, *args }
      filter.when(T[:error])   { |_, url, ex, args| on_error url, ex, *args }
    end
  end
end