Sha256: 05221d471dc13b80646d95e6e91b562c7c9e12c7a56e1e84c0072da79430e81d

Contents?: true

Size: 1.34 KB

Versions: 34

Compression:

Stored size: 1.34 KB

Contents

require 'messaging'
require_relative 'consumer_supervisor'

module Messaging
  # @private
  # Starts up the consumer supervisor and handles signals
  class CLI

    SIGNALS = %i[INT TERM QUIT].freeze

    def initialize
      @signal_queue = []
      @reader, @writer = IO.pipe
      @consumer_supervisor = Messaging::ConsumerSupervisor.new
    end

    def run
      setup_signals
      consumer_supervisor.start
      wait_for_signal
    end

    # See https://www.sitepoint.com/the-self-pipe-trick-explained/ for background on this
    def wait_for_signal
      loop do
        case signal_queue.pop
        when *SIGNALS
          consumer_supervisor.stop
          break
        when "USR1"
          consumer_supervisor.status
        else
          ready = IO.select([reader, writer])

          # drain the self-pipe so it won't be returned again next time
          reader.read_nonblock(1) if ready[0].include?(reader)
        end
      end
    end

    private

    attr_reader :reader, :writer, :signal_queue, :consumer_supervisor

    def logger
      @logger ||= Logger.new(STDOUT)
    end

    def setup_signals
      SIGNALS.each do |signal|
        Signal.trap(signal) { unblock(signal) }
      end
      Signal.trap("USR1") { unblock("USR1") }
    end

    def unblock(signal)
      writer.write_nonblock('.')
      signal_queue << signal
    end

  end
end

Version data entries

34 entries across 34 versions & 1 rubygems

Version Path
messaging-4.0.12 lib/messaging/cli.rb
messaging-4.0.11 lib/messaging/cli.rb
messaging-4.0.10 lib/messaging/cli.rb
messaging-4.0.10.pre lib/messaging/cli.rb
messaging-4.0.9 lib/messaging/cli.rb
messaging-4.0.8 lib/messaging/cli.rb
messaging-4.0.7 lib/messaging/cli.rb
messaging-4.0.6 lib/messaging/cli.rb
messaging-4.0.5 lib/messaging/cli.rb
messaging-4.0.4.pre lib/messaging/cli.rb
messaging-4.0.3.pre lib/messaging/cli.rb
messaging-4.0.2.pre lib/messaging/cli.rb
messaging-4.0.1.pre lib/messaging/cli.rb
messaging-4.0.0.pre lib/messaging/cli.rb
messaging-3.8.2 lib/messaging/cli.rb
messaging-3.8.1 lib/messaging/cli.rb
messaging-3.8.0 lib/messaging/cli.rb
messaging-3.7.3 lib/messaging/cli.rb
messaging-3.7.2 lib/messaging/cli.rb
messaging-3.7.1 lib/messaging/cli.rb