Class: FetchUtil::ParallelFetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/fetch_util/parallel_fetcher.rb

Defined Under Namespace

Classes: Failure, ParallelFetchError

Constant Summary collapse

DEFAULT_CONCURRENCY =
4

Instance Method Summary collapse

Constructor Details

#initialize(fetcher_factory: nil, concurrency: DEFAULT_CONCURRENCY, **fetch_options) ⇒ ParallelFetcher

Returns a new instance of ParallelFetcher.



32
33
34
35
# File 'lib/fetch_util/parallel_fetcher.rb', line 32

def initialize(fetcher_factory: nil, concurrency: DEFAULT_CONCURRENCY, **fetch_options)
  @fetcher_factory = fetcher_factory || -> { Fetcher.new(**fetch_options) }
  @concurrency = [concurrency.to_i, 1].max
end

Instance Method Details

#fetch(urls) ⇒ Object



37
38
39
40
41
42
43
44
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
77
# File 'lib/fetch_util/parallel_fetcher.rb', line 37

def fetch(urls)
  work = Array(urls).compact.map(&:to_s).reject(&:empty?)
  return [] if work.empty?

  jobs = Queue.new
  failures = Queue.new
  work.each_with_index { |url, index| jobs << [index, url] }
  results = Array.new(work.length)
  worker_count = [@concurrency, work.length].min

  threads = Array.new(worker_count) do
    Thread.new do
      fetcher = @fetcher_factory.call

      begin
        loop do
          begin
            index, url = jobs.pop(true)
          rescue ThreadError
            break
          end

          begin
            results[index] = fetcher.fetch(url)
          rescue StandardError => e
            failures << Failure.new(index: index, url: url, error: e)
          end
        end
      ensure
        fetcher.quit if fetcher.respond_to?(:quit)
      end
    rescue StandardError => e
      failures << Failure.new(index: nil, url: nil, error: e)
    end
  end

  threads.each(&:join)
  raise_for_failures(drain_queue(failures), results)

  results
end