Class: LibyearRb::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/libyear_rb/runner.rb

Constant Summary collapse

MAX_WORKERS_PER_HOST =
10
RATE_LIMIT =

requests per second per host

10

Instance Method Summary collapse

Instance Method Details

#run(lockfile_contents, as_of: nil) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/libyear_rb/runner.rb', line 10

def run(lockfile_contents, as_of: nil)
  specs_by_host = parse_specs(lockfile_contents)
  threads = []
  replenishers = []

  specs_by_host.each do |host, specs|
    token_queue = Thread::SizedQueue.new(RATE_LIMIT)
    rate_limiter = -> { token_queue.pop }

    work_queue = Thread::Queue.new
    specs.each { |spec| work_queue << spec }
    work_queue.close

    replenishers << Thread.new do
      loop do
        sleep(1.0 / RATE_LIMIT)
        token_queue << :token
      end
    end

    [specs.size, MAX_WORKERS_PER_HOST].min.times do
      threads << Thread.new do
        fetcher = GemInfoFetcher.new(host, rate_limiter: rate_limiter)
        thread_results = []
        while (spec = work_queue.pop)
          begin
            versions = fetcher.versions_for(spec.name)
            thread_results << [spec, versions]
          rescue => e
            LibyearRb.logger.error("Error fetching #{spec.name}: #{e.message}")
          end
        end
        thread_results
      end
    end
  end

  spec_versions = threads.flat_map(&:value)
  spec_versions.filter_map { |spec, versions| analyze(spec, versions, as_of: as_of) }
rescue Exception # rubocop:disable Lint/RescueException
  threads.each { |t| t.kill unless t == Thread.current }
  raise
ensure
  replenishers.each(&:kill)
end