Class: MTLibuv::Reactor

Inherits:
Object show all
Extended by:
Accessors, ClassMethods
Includes:
Assertions, Resource
Defined in:
lib/mt-libuv/reactor.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

LIBUV_MIN_POOL =
ENV['LIBUV_MIN_POOL'] || 8
LIBUV_MAX_POOL =
ENV['LIBUV_MAX_POOL'] || 40
LIBUV_MAX_QUEUE =
ENV['LIBUV_MAX_QUEUE'] || 50000
THREAD_POOL =
::Concurrent::ThreadPoolExecutor.new(
    min_threads: LIBUV_MIN_POOL,
    max_threads: LIBUV_MAX_POOL,
    max_queue: LIBUV_MAX_QUEUE
)
CRITICAL =
::Mutex.new

Constants included from Accessors

Accessors::Functions

Constants included from Assertions

Assertions::MSG_NO_PROC

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Accessors

reactor

Methods included from ClassMethods

create, current, default, new

Methods included from Resource

#check_result, #check_result!, #resolve, #to_ptr

Methods included from Assertions

#assert_block, #assert_boolean, #assert_type

Constructor Details

#initialize(pointer) ⇒ Reactor

Initialize a reactor using an FFI::Pointer to a libuv reactor



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/mt-libuv/reactor.rb', line 67

def initialize(pointer) # :notnew:
    @pointer = pointer
    @reactor = self
    @run_count = 0
    @ref_count = 0
    @fiber_pool = FiberPool.new(self)

    # Create an async call for scheduling work from other threads
    @run_queue = Queue.new
    @process_queue = @reactor.async { process_queue_cb }
    @process_queue.unref

    # Create a next tick timer
    @next_tick = @reactor.timer { next_tick_cb }
    @next_tick.unref

    # Create an async call for ending the reactor
    @stop_reactor = @reactor.async { stop_cb }
    @stop_reactor.unref

    # MTLibuv can prevent the application shutting down once the main thread has ended
    # The addition of a prepare function prevents this from happening.
    @reactor_prep = prepare {}
    @reactor_prep.unref
    @reactor_prep.start

    # LibUV ingnores program interrupt by default.
    # We provide normal behaviour and allow this to be overriden
    @on_signal = []
    sig_callback = proc { signal_cb }
    self.signal(:INT, &sig_callback).unref
    self.signal(:HUP, &sig_callback).unref
    self.signal(:TERM, &sig_callback).unref

    # Notify of errors
    @throw_on_exit = nil
    @reactor_notify_default = @reactor_notify = proc { |error|
        @throw_on_exit = error
    }
    @fiber_pool.on_error &@reactor_notify
end

Instance Attribute Details

#fiber_poolObject (readonly)

Returns the value of attribute fiber_pool.



109
110
111
# File 'lib/mt-libuv/reactor.rb', line 109

def fiber_pool
  @fiber_pool
end

#run_countObject (readonly)

Returns the value of attribute run_count.



109
110
111
# File 'lib/mt-libuv/reactor.rb', line 109

def run_count
  @run_count
end

Instance Method Details

#active_handlesObject

Return the number of active handles in the event loop



230
231
232
233
# File 'lib/mt-libuv/reactor.rb', line 230

def active_handles
    uvloop = Ext::UvLoop.new @pointer
    uvloop[:active_handles]
end

#all(*promises) ⇒ ::MTLibuv::Q::Promise

Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. (thread safe)

Parameters:

Returns:

  • (::MTLibuv::Q::Promise)

    Returns a single promise that will be resolved with an array of values, each value corresponding to the promise at the same index in the ‘promises` array. If any of the promises is resolved with a rejection, this resulting promise will be resolved with the same rejection.



264
265
266
# File 'lib/mt-libuv/reactor.rb', line 264

def all(*promises)
    Q.all(@reactor, *promises)
end

#any(*promises) ⇒ ::MTLibuv::Q::Promise

Combines multiple promises into a single promise that is resolved when any of the input promises are resolved.

Parameters:

Returns:



274
275
276
# File 'lib/mt-libuv/reactor.rb', line 274

def any(*promises)
    Q.any(@reactor, *promises)
end

#async(&block) ⇒ ::MTLibuv::Async

Get a new Async handle

Returns:



413
414
415
416
417
# File 'lib/mt-libuv/reactor.rb', line 413

def async(&block)
    handle = Async.new(@reactor)
    handle.progress &block if block_given?
    handle
end

#check(&block) ⇒ ::MTLibuv::Check

Get a new Check handle

Returns:



394
395
396
397
398
# File 'lib/mt-libuv/reactor.rb', line 394

def check(&block)
    handle = Check.new(@reactor)
    handle.progress &block if block_given?
    handle
end

#defer::MTLibuv::Q::Deferred

Creates a deferred result object for where the result of an operation may only be returned at some point in the future or is being processed on a different thread (thread safe)



252
253
254
# File 'lib/mt-libuv/reactor.rb', line 252

def defer
    Q.defer(@reactor)
end

#execObject

Execute the provided block of code in a fiber from the pool



209
210
211
# File 'lib/mt-libuv/reactor.rb', line 209

def exec
    @fiber_pool.exec { yield }
end

#file(path, flags = 0, mode: 0, **opts, &blk) ⇒ ::MTLibuv::File

Opens a file and returns an object that can be used to manipulate it

Parameters:

  • path (String)

    the path to the file or folder for watching

  • flags (Integer) (defaults to: 0)

    see ruby File::Constants

  • mode (Integer) (defaults to: 0)

Returns:



487
488
489
490
491
492
# File 'lib/mt-libuv/reactor.rb', line 487

def file(path, flags = 0, mode: 0, **opts, &blk)
    assert_type(String, path, "path must be a String")
    assert_type(Integer, flags, "flags must be an Integer")
    assert_type(Integer, mode, "mode must be an Integer")
    File.new(@reactor, path, flags, mode: mode, **opts, &blk)
end

#filesystem::MTLibuv::Filesystem

Returns an object for manipulating the filesystem



497
498
499
# File 'lib/mt-libuv/reactor.rb', line 497

def filesystem
    Filesystem.new(@reactor)
end

#finally(*promises) ⇒ ::MTLibuv::Q::Promise

Combines multiple promises into a single promise that is resolved when all of the input promises are resolved or rejected.

Parameters:

Returns:

  • (::MTLibuv::Q::Promise)

    Returns a single promise that will be resolved with an array of values, each [result, wasResolved] value pair corresponding to a at the same index in the ‘promises` array.



285
286
287
# File 'lib/mt-libuv/reactor.rb', line 285

def finally(*promises)
    Q.finally(@reactor, *promises)
end

#fs_event(path) ⇒ ::MTLibuv::FSEvent

Get a new FSEvent instance

Parameters:

  • path (String)

    the path to the file or folder for watching

Returns:

Raises:

  • (ArgumentError)

    if path is not a string



476
477
478
479
# File 'lib/mt-libuv/reactor.rb', line 476

def fs_event(path)
    assert_type(String, path)
    FSEvent.new(@reactor, path)
end

#handleObject



167
# File 'lib/mt-libuv/reactor.rb', line 167

def handle; @pointer; end

#idle(&block) ⇒ ::MTLibuv::Idle

Get a new Idle handle

Parameters:

  • callback (Proc)

    the callback to be called on idle trigger

Returns:



404
405
406
407
408
# File 'lib/mt-libuv/reactor.rb', line 404

def idle(&block)
    handle = Idle.new(@reactor)
    handle.progress &block if block_given?
    handle
end

#inspectObject

Overwrite as errors in jRuby can literally hang VM when inspecting as many many classes will reference this class



162
163
164
# File 'lib/mt-libuv/reactor.rb', line 162

def inspect
    "#<#{self.class}:0x#{self.__id__.to_s(16)} NT=#{@run_queue.length}>"
end

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

Notifies the reactor there was an event that should be logged

Parameters:

  • error (Exception)

    the error

  • msg (String|nil) (defaults to: nil)

    optional context on the error

  • trace (Array<String>) (defaults to: nil)

    optional additional trace of caller if async



542
543
544
# File 'lib/mt-libuv/reactor.rb', line 542

def log(error, msg = nil, trace = nil)
    @reactor_notify.call(error, msg, trace)
end

#lookup(hostname, hint = :IPv4, port = 9, wait: true, &block) ⇒ ::MTLibuv::Dns

Lookup a hostname

Parameters:

  • hostname (String)

    the domain name to lookup

  • port (Integer, String) (defaults to: 9)

    the service being connected too

  • callback (Proc)

    the callback to be called on success

Returns:



461
462
463
464
465
466
467
468
469
# File 'lib/mt-libuv/reactor.rb', line 461

def lookup(hostname, hint = :IPv4, port = 9, wait: true, &block)
    dns = Dns.new(@reactor, hostname, port, hint, wait: wait)    # Work is a promise object
    if wait
        dns.results
    else
        dns.then &block if block_given?
        dns
    end
end

#lookup_error(err) ⇒ ::MTLibuv::Error

Lookup an error code and return is as an error object

Parameters:

  • err (Integer)

    The error code to look up.

Returns:



315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'lib/mt-libuv/reactor.rb', line 315

def lookup_error(err)
    name = ::MTLibuv::Ext.err_name(err)

    if name
        msg  = ::MTLibuv::Ext.strerror(err)
        ::MTLibuv::Error.const_get(name.to_sym).new("#{msg}, #{name}:#{err}")
    else
        # We want a back-trace in this case
        raise "error lookup failed for code #{err}"
    end
rescue Exception => e
    @reactor.log e, 'performing error lookup'
    e
end

#next_tick(&block) ⇒ Object

Queue some work to be processed in the next iteration of the event reactor (thread safe)

Parameters:

  • callback (Proc)

    the callback to be called on the reactor thread



521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
# File 'lib/mt-libuv/reactor.rb', line 521

def next_tick(&block)
    @run_queue << block
    if reactor_thread?
        # Create a next tick timer
        if not @next_tick_scheduled
            @next_tick.start(0)
            @next_tick_scheduled = true
            @next_tick.ref
        end
    else
        @process_queue.call
    end

    self
end

#notifier(&block) ⇒ ::MTLibuv::Q::Promise

Provides a promise notifier for receiving un-handled exceptions



239
240
241
242
243
244
245
246
# File 'lib/mt-libuv/reactor.rb', line 239

def notifier(&block)
    @reactor_notify = if block_given?
        block
    else
        @reactor_notify_default
    end
    self
end

#nowInteger

Get current time in milliseconds

Returns:

  • (Integer)


307
308
309
# File 'lib/mt-libuv/reactor.rb', line 307

def now
    ::MTLibuv::Ext.now(@pointer)
end

#on_program_interrupt(&callback) ⇒ Object

Allows user defined behaviour when sig int is received



430
431
432
433
# File 'lib/mt-libuv/reactor.rb', line 430

def on_program_interrupt(&callback)
    @on_signal << callback
    self
end

#pipe(ipc = false) ⇒ ::MTLibuv::Pipe

Get a new Pipe instance

Parameters:

  • ipc (true, false) (defaults to: false)

    indicate if a handle will be used for ipc, useful for sharing tcp socket between processes

Returns:



368
369
370
# File 'lib/mt-libuv/reactor.rb', line 368

def pipe(ipc = false)
    Pipe.new(@reactor, ipc)
end

#prepare(&block) ⇒ ::MTLibuv::Prepare

Get a new Prepare handle

Returns:



385
386
387
388
389
# File 'lib/mt-libuv/reactor.rb', line 385

def prepare(&block)
    handle = Prepare.new(@reactor)
    handle.progress &block if block_given?
    handle
end

#reactor_running?Boolean Also known as: running?

Tells you whether the MTLibuv reactor reactor is currently running.

Returns:

  • (Boolean)


562
563
564
# File 'lib/mt-libuv/reactor.rb', line 562

def reactor_running?
    @reactor_running
end

#reactor_thread?Boolean

True if the calling thread is the same thread as the reactor.

Returns:

  • (Boolean)


555
556
557
# File 'lib/mt-libuv/reactor.rb', line 555

def reactor_thread?
    self == Thread.current.thread_variable_get(:reactor)
end

#refObject

Prevents the reactor loop from stopping



214
215
216
217
218
219
# File 'lib/mt-libuv/reactor.rb', line 214

def ref
    if reactor_thread? && reactor_running?
        @process_queue.ref if @ref_count == 0
        @ref_count += 1
    end
end

#reject(reason) ⇒ Object

Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don’t need to worry about it.



292
293
294
# File 'lib/mt-libuv/reactor.rb', line 292

def reject(reason)
    Q.reject(@reactor, reason)
end

#run(run_type = :UV_RUN_DEFAULT) {|promise| ... } ⇒ Object

Run the actual event reactor. This method will block until the reactor is stopped.

Parameters:

  • run_type (:UV_RUN_DEFAULT, :UV_RUN_ONCE, :UV_RUN_NOWAIT) (defaults to: :UV_RUN_DEFAULT)

Yield Parameters:

  • promise (::MTLibuv::Q::Promise)

    Yields a promise that can be used for logging unhandled exceptions on the reactor.



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/mt-libuv/reactor.rb', line 174

def run(run_type = :UV_RUN_DEFAULT)
    if not @reactor_running
        begin
            @reactor_running = true
            raise 'only one reactor allowed per-thread' if Thread.current.thread_variable_get(:reactor)

            Thread.current.thread_variable_set(:reactor, @reactor)
            @throw_on_exit = nil
            update_time
            @fiber_pool.reset
            @fiber_pool.exec { yield @reactor } if block_given?
            @run_count += 1
            ::MTLibuv::Ext.run(@pointer, run_type)  # This is blocking
        ensure
            Thread.current.thread_variable_set(:reactor, nil)
            @reactor_running = false
            @run_queue.clear
        end

        # Raise the last unhandled error to occur on the reactor thread
        raise @throw_on_exit if @throw_on_exit

    elsif block_given?
        if reactor_thread?
            update_time
            yield @reactor
        else
            raise 'reactor already running on another thread'
        end
    end

    @reactor
end

#schedule { ... } ⇒ Object

Schedule some work to be processed on the event reactor as soon as possible (thread safe)

Yields:

  • the callback to be called on the reactor thread



508
509
510
511
512
513
514
515
516
# File 'lib/mt-libuv/reactor.rb', line 508

def schedule(&block)
    if reactor_thread?
        yield
    else
        @run_queue << block
        @process_queue.call
    end
    self
end

#signal(signum = nil, &block) ⇒ ::MTLibuv::Signal

Get a new signal handler

Returns:



422
423
424
425
426
427
# File 'lib/mt-libuv/reactor.rb', line 422

def signal(signum = nil, &block)
    handle = Signal.new(@reactor)
    handle.progress &block if block_given?
    handle.start(signum) if signum
    handle
end

#sleep(msecs) ⇒ Object



330
331
332
333
334
335
336
337
# File 'lib/mt-libuv/reactor.rb', line 330

def sleep(msecs)
    fiber = Fiber.current
    time = timer {
        time.close
        fiber.resume
    }.start(msecs)
    Fiber.yield
end

#spawn(cmd, **args) ⇒ Object



501
502
503
# File 'lib/mt-libuv/reactor.rb', line 501

def spawn(cmd, **args)
    Spawn.new(@reactor, cmd, **args)
end

#stopObject

Closes handles opened by the reactor class and completes the current reactor iteration (thread safe)



547
548
549
550
# File 'lib/mt-libuv/reactor.rb', line 547

def stop
    return unless @reactor_running
    @stop_reactor.call
end

#tcp(**opts, &callback) ⇒ ::MTLibuv::TCP

Get a new TCP instance

Returns:



342
343
344
# File 'lib/mt-libuv/reactor.rb', line 342

def tcp(**opts, &callback)
    TCP.new(@reactor, progress: callback, **opts)
end

#timer(&block) ⇒ ::MTLibuv::Timer

Get a new timer instance

Parameters:

  • callback (Proc)

    the callback to be called on timer trigger

Returns:



376
377
378
379
380
# File 'lib/mt-libuv/reactor.rb', line 376

def timer(&block)
    handle = Timer.new(@reactor)
    handle.progress &block if block_given?
    handle
end

#tty(fileno, readable = false) ⇒ ::MTLibuv::TTY

Get a new TTY instance

Parameters:

  • fileno (Integer)

    Integer file descriptor of a tty device

  • readable (true, false) (defaults to: false)

    Boolean indicating if TTY is readable

Returns:



358
359
360
361
362
# File 'lib/mt-libuv/reactor.rb', line 358

def tty(fileno, readable = false)
    assert_type(Integer, fileno, "io#fileno must return an integer file descriptor, #{fileno.inspect} given")

    TTY.new(@reactor, fileno, readable)
end

#udp(**opts, &callback) ⇒ ::MTLibuv::UDP

Get a new UDP instance

Returns:



349
350
351
# File 'lib/mt-libuv/reactor.rb', line 349

def udp(**opts, &callback)
    UDP.new(@reactor, progress: callback, **opts)
end

#unrefObject

Allows the reactor loop to stop



222
223
224
225
226
227
# File 'lib/mt-libuv/reactor.rb', line 222

def unref
    if reactor_thread? && reactor_running? && @ref_count > 0
        @ref_count -= 1
        @process_queue.unref if @ref_count == 0
    end
end

#update_timeObject

forces reactor time update, useful for getting more granular times

Returns:

  • nil



299
300
301
302
# File 'lib/mt-libuv/reactor.rb', line 299

def update_time
    ::MTLibuv::Ext.update_time(@pointer)
    self
end

#work::MTLibuv::Work

Queue some work for processing in the libuv thread pool

Parameters:

  • callback (Proc)

    the callback to be called in the thread pool

Returns:

Raises:

  • (ArgumentError)

    if block is not given



440
441
442
443
444
445
446
447
448
449
450
451
452
453
# File 'lib/mt-libuv/reactor.rb', line 440

def work
    ref
    d = defer
    THREAD_POOL.post do
        begin
            d.resolve(yield)
        rescue Exception => e
            d.reject(e)
        end
    end
    promise = d.promise
    promise.finally { unref }
    promise
end