Class: WorkerArmy::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/worker_army/client.rb

Class Method Summary collapse

Class Method Details

.client_retry_count(config) ⇒ Object



51
52
53
54
55
56
57
58
59
# File 'lib/worker_army/client.rb', line 51

def client_retry_count(config)
  if ENV['worker_army_client_retry_count']
    return ENV['worker_army_client_retry_count'].to_i
  elsif config and config['client_retry_count']
    return config['client_retry_count'].to_i
  else
    return 10
  end
end

.push_job(job_class, data = {}, callback_url = nil, queue_prefix = 'queue', retry_count = 0) ⇒ Object



8
9
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
# File 'lib/worker_army/client.rb', line 8

def push_job(job_class, data = {}, callback_url = nil, queue_prefix = 'queue', retry_count = 0)
  raise "No data" unless data
  raise "No job class provided" unless job_class
  
  if ENV['worker_army_endpoint']
    # puts "Using environment variables for config..."
    @config = { endpoint: ENV['worker_army_endpoint'] }
  else
    begin
      # puts "Using config in your home directory"
      @config = YAML.load(File.read("#{ENV['HOME']}/.worker_army.yml"))
    rescue Errno::ENOENT
      raise "worker_army.yml expected in ~/.worker_army.yml"
    end
  end

  worker_army_base_url = @config['endpoint']
  callback_url = "#{worker_army_base_url}/generic_callback" unless callback_url
  response = nil
  begin
    response = RestClient.post "#{worker_army_base_url}/jobs",
      data.merge(
        job_class: job_class,
        callback_url: "#{worker_army_base_url}/callback?callback_url=#{callback_url}",
        queue_prefix: queue_prefix
      ).to_json,
      :content_type => :json, :accept => :json
  rescue => e
    puts "Failed! Retrying (#{retry_count})..."
    retry_count += 1
    if retry_count < client_retry_count(@config)
      sleep (retry_count * 2)
      push_job(job_class, data, callback_url, queue_prefix, retry_count)
    end
  end
  if response and response.body and response.code == 200
    hash = JSON.parse(response.body)
    hash.merge(success: true)
  else
    { success: false }
  end
end