Class: Magent::Processor

Inherits:
Object
  • Object
show all
Defined in:
lib/magent/processor.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(actor) ⇒ Processor

Returns a new instance of Processor.



5
6
7
8
9
10
11
12
13
14
# File 'lib/magent/processor.rb', line 5

def initialize(actor)
  @actor = actor
  @shutdown = false

  @actor.class.actions.each do |action|
    if !@actor.respond_to?(action)
      raise ArgumentError, "action '#{action}' is not defined"
    end
  end
end

Instance Attribute Details

#actorObject (readonly)

Returns the value of attribute actor.



3
4
5
# File 'lib/magent/processor.rb', line 3

def actor
  @actor
end

Instance Method Details

#run!Object



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
55
56
57
58
# File 'lib/magent/processor.rb', line 16

def run!
  processed_messages = 0
  delay = 0

  trap('TERM') { shutdown!; exit 0 }
  trap('SIGINT') { shutdown!; exit 0 }

  loop do
    break if @shutdown

    delay = 0 if @actor._run_tasks

    @method, @payload = @actor.class.channel.dequeue

    if @method.nil?
      delay += 0.1 if delay <= 5
    else
      delay = 0
      $stderr.puts "#{@actor.class}##{@method}(#{@payload.inspect})"
      begin
        if @actor.class.can_handle?(@method)
          processed_messages += 1
          @actor.send(@method, @payload)

          if processed_messages > 20
            processed_messages = 0
            GC.start
          end
        else
          $stderr.puts "Unknown action: #{@method} (payload=#{@payload.inspect})"
        end
      rescue SystemExit
      rescue Exception => e
        $stderr.puts "Error while executing #{@method.inspect} #{@payload.inspect}"
        $stderr.puts "#{e.to_s}\n#{e.backtrace.join("\t\n")}"
        @actor.class.channel.failed(:message => e.message, :method => @method, :payload => @payload, :backtrace => e.backtrace, :date => Time.now.utc)
      ensure
        @method, @payload = nil
      end
    end
    sleep delay
  end
end

#shutdown!Object



60
61
62
63
64
65
66
# File 'lib/magent/processor.rb', line 60

def shutdown!
  @shutdown = true
  $stderr.puts "Shutting down..."
  if @method
    @actor.class.channel.enqueue(@method, @payload)
  end
end