Sha256: e9762a01d34574bbb34e64414f1b4629b0774c4262f84223090e83a952da3f70

Contents?: true

Size: 1.09 KB

Versions: 1

Compression:

Stored size: 1.09 KB

Contents

# frozen_string_literal: true

module Nonnative
  class Process
    def initialize(configuration)
      @configuration = configuration
    end

    def start
      @pid = spawn(configuration.process, %i[out err] => [configuration.file, 'a'])
      [port_open?, pid]
    end

    def stop
      ::Process.kill('SIGINT', pid)
      [port_closed?, pid]
    end

    private

    attr_reader :configuration, :pid

    def port_open?
      timeout do
        open_socket
        true
      rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
        sleep_interval
        retry
      end
    end

    def port_closed?
      timeout do
        open_socket
        raise Nonnative::Error
      rescue Nonnative::Error
        sleep_interval
        retry
      rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
        true
      end
    end

    def timeout
      Timeout.timeout(configuration.timeout) do
        yield
      end
    rescue Timeout::Error
      false
    end

    def open_socket
      TCPSocket.new('127.0.0.1', configuration.port).close
    end

    def sleep_interval
      sleep 0.01
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
nonnative-0.7.0 lib/nonnative/process.rb