Sha256: 3da4f9d707cd20a468b89d942249c2c53419688d24b0f6ac4ecf767cc33fa4e4

Contents?: true

Size: 1.67 KB

Versions: 3

Compression:

Stored size: 1.67 KB

Contents

module Backport
  # The Backport server controller.
  #
  class Machine
    def initialize
      @stopped = true
    end

    # Run the machine. If a block is provided, it gets executed before the
    # maching starts its main loop. The main loop blocks program execution
    # until the machine is stopped.
    #
    # @return [void]
    def run
      return unless stopped?
      servers.clear
      @stopped = false
      yield if block_given?
      run_server_thread
    end

    # Stop the machine.
    #
    # @return [void]
    def stop
      servers.map(&:stop)
      servers.clear
      @stopped = true
    end

    # True if the machine is stopped.
    #
    def stopped?
      @stopped ||= false
    end

    # Add a server to the machine. The server will be started when the machine
    # starts. If the machine is already running, the server will be started
    # immediately.
    #
    # @param server [Server::Base]
    # @return [void]
    def prepare server
      server.add_observer self
      servers.push server
      server.start unless stopped?
    end

    # @return [Array<Server::Base>]
    def servers
      @servers ||= []
    end

    # @param server [Server::Base]
    def update server
      if server.stopped?
        servers.delete server
        stop if servers.empty?
      else
        mutex.synchronize { server.tick }
      end
    end

    private

    def mutex
      @mutex ||= Mutex.new
    end

    # Start the thread that updates servers via the #tick method.
    #
    # @return [void]
    def run_server_thread
      servers.map(&:start)
      sleep 0.1 until stopped?
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
backport-1.1.2 lib/backport/machine.rb
backport-1.1.1 lib/backport/machine.rb
backport-1.1.0 lib/backport/machine.rb