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
78
79
80
81
82
# 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?

  results = Array.new(work.length)
  worker_count = [@concurrency, work.length].min
  failures = []
  next_index = 0
  mutex = Mutex.new

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

      begin
        loop do
          index = mutex.synchronize do
            if next_index < work.length
              current = next_index
              next_index += 1
              current
            end
          end
          break if index.nil?

          url = work[index]

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

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

  results
end