Class: SpiderGazelle::Reactor

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/spider-gazelle/reactor.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeReactor

Returns a new instance of Reactor.



13
14
15
16
17
18
# File 'lib/spider-gazelle/reactor.rb', line 13

def initialize
    @thread = ::Libuv::Reactor.default
    @logger = Logger.instance
    @running = false
    @shutdown_called = false
end

Instance Attribute Details

#threadObject (readonly)

Returns the value of attribute thread.



10
11
12
# File 'lib/spider-gazelle/reactor.rb', line 10

def thread
  @thread
end

Instance Method Details

#log(error, context, trace = nil) ⇒ Object

This is an unhandled error on the Libuv Event loop



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/spider-gazelle/reactor.rb', line 54

def log(error, context, trace = nil)
    msg = String.new
    if error.respond_to?(:backtrace)
        msg << "unhandled exception: #{error.message} (#{context})"
        backtrace = error.backtrace
        msg << "\n#{backtrace.join("\n")}" if backtrace
        msg << "\n#{trace.join("\n")}" if trace
    else
        msg << "unhandled exception: #{args}"
    end
    @logger.error msg
end

#runObject



20
21
22
23
24
25
26
27
28
29
# File 'lib/spider-gazelle/reactor.rb', line 20

def run
    if @running
        @thread.schedule { yield }
    else
        @running = true
        @thread.notifier { |*args| log(*args) }
        @thread.on_program_interrupt { shutdown }
        @thread.run { yield }
    end
end

#shutdownObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/spider-gazelle/reactor.rb', line 31

def shutdown
    if @shutdown_called
        @logger.warn "Shutdown called twice! Callstack:\n#{caller.join("\n")}"
        return
    end

    @thread.schedule do
        if not @shutdown_called
            @shutdown_called = true

            # Signaller will manage the shutdown of the gazelles
            signaller = Signaller.instance.shutdown
            signaller.finally do
                @thread.stop
                # New line on exit to avoid any ctrl-c characters
                # We check for pipe as we only want the master process to print this
                puts "\nSpider-Gazelle leaps through the veldt\n"
            end
        end
    end
end