Class: Rack::Mux

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/mux.rb

Defined Under Namespace

Classes: Server

Constant Summary collapse

VERSION =
'0.1.2'
HEADER =
'X-Mux-Uri'

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Mux

Returns a new instance of Mux.



8
9
10
11
12
13
14
15
# File 'lib/rack/mux.rb', line 8

def initialize(app, options = {})
  @app, @rack_options = app, options
  @host = options[:Host] || '0.0.0.0'
  @port = options[:Port] || find_port
  @uri  = URI.parse("http://#{@host}:#{@port}")

  rackup
end

Instance Method Details

#call(env) ⇒ Object



17
18
19
# File 'lib/rack/mux.rb', line 17

def call(env)
  @app.call(env.merge(HEADER => @uri.to_s, 'SERVER_PORT' => @port.to_s))
end

#default_optionsObject



33
34
35
36
37
38
39
# File 'lib/rack/mux.rb', line 33

def default_options
  {
    :environment => ENV['RACK_ENV'] || "development",
    :Port        => @port,
    :Host        => @host
  }
end

#find_portObject



41
42
43
44
45
46
47
48
49
50
# File 'lib/rack/mux.rb', line 41

def find_port
  loop do
    port = rand(64510) + 1025
    begin
      TCPSocket.new(@host, port)
    rescue Errno::ECONNREFUSED
      return port
    end
  end
end

#rackupObject



21
22
23
24
25
26
27
# File 'lib/rack/mux.rb', line 21

def rackup
  Thread.new(server_options) do |options|
    Server.start(options)
  end

  wait_for_server
end

#server_optionsObject



29
30
31
# File 'lib/rack/mux.rb', line 29

def server_options
  default_options.merge(@rack_options).merge(:app => self)
end

#wait_for_serverObject



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/rack/mux.rb', line 52

def wait_for_server
  Timeout::timeout(30) do
    loop do
      begin
        return TCPSocket.new(@host, @port)
      rescue Errno::ECONNREFUSED
        sleep 1
      rescue => e
        raise Error, e.message
      end
    end
  end
end