Class: ReportsMash::Engine::WorkerLoop

Inherits:
Object
  • Object
show all
Defined in:
lib/reportsmash/engine/worker.rb

Overview

A worker loop executes a set of registered tasks on a single thread. A task is a proc or block with a specified call period in seconds.

Instance Method Summary collapse

Constructor Details

#initializeWorkerLoop

Returns a new instance of WorkerLoop.



12
13
14
# File 'lib/reportsmash/engine/worker.rb', line 12

def initialize
  @engine = ReportsMash::Engine.engine
end

Instance Method Details

#runObject



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
# File 'lib/reportsmash/engine/worker.rb', line 15

def run
  #$stderr.puts "ReportsMash worker running #{@engine}\n"
  authkey = Base64.strict_encode64("#{ENV['REPORTSMASH_APP_ID']}:#{ENV['REPORTSMASH_APP_KEY']}")
  if Rails.env.development?
    remote_host = "https://in.reportsmash.com:8091/w"
  else
    remote_host = "https://in.reportsmash.com:443/w"
  end
  data = {}
  batch = []

  loop do
    sleep 5
    while item = @engine.delivery_queue.pop do
      batch << item.payload
    end
    next if batch.count == 0
    data[:transactions] = batch

    begin 
      json_data = data.to_json
      compressed_data = Snappy.deflate(json_data)
    
      req = Typhoeus::Request.new(remote_host, method: :post, body: compressed_data, headers: { 
        "X-REPORTSMASH-AUTH" => authkey,
        "Content-Length" => compressed_data.size,
        "Content-Type" => "application/octet-stream" })
      req.run
    rescue Exception => e
      $stderr.puts "ReportsMash::Engine.worker - could not send data to servers: #{e.inspect}"
    end
    #data[:transactions].each do |item|
    #  $stderr.puts "Batch running #{item}" if Rails.env.development?
    #end

    data.clear()
    batch.clear()
  end
end