Class: Robe::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/robe/server.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(handler, port) ⇒ Server

Returns a new instance of Server.



11
12
13
14
15
16
# File 'lib/robe/server.rb', line 11

def initialize(handler, port)
  @handler = handler
  @server = TCPServer.new("127.0.0.1", port)
  @running = true
  @port = @server.addr[1]
end

Instance Attribute Details

#portObject (readonly)

Returns the value of attribute port.



9
10
11
# File 'lib/robe/server.rb', line 9

def port
  @port
end

#runningObject (readonly)

Returns the value of attribute running.



9
10
11
# File 'lib/robe/server.rb', line 9

def running
  @running
end

Instance Method Details

#shutdownObject



77
78
79
80
81
82
83
84
85
# File 'lib/robe/server.rb', line 77

def shutdown
  @running = false
  begin
    @server && @server.shutdown(Socket::SHUT_RDWR)
  rescue Errno::ENOTCONN
    # Hello JRuby
    @server.close
  end
end

#startObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/robe/server.rb', line 18

def start
  access = File.open("#{Dir.tmpdir}/robe-access-#{@port}.log", "w")
  access.sync = true

  error_logger = Logger.new($stderr)
  access_logger = Logger.new(access)

  client = nil

  loop do
    begin
      client = @server.accept

      next if client.eof?

      req = WEBrick::HTTPRequest.new(:InputBufferSize => 1024,
                                     :Logger => error_logger)
      req.parse(client)
      access_logger.info "#{req.request_method} #{req.path}"

      begin
        body = @handler.call(req.path, req.body)
      rescue Exception => e
        error_logger.error "Request failed: #{req.path}. Please file an issue."
        error_logger.error "#{e.message}\n#{e.backtrace.join("\n")}"
      end

      resp = WEBrick::HTTPResponse.new(:OutputBufferSize => 1024,
                                       :Logger => error_logger,
                                       :HTTPVersion => "1.1")
      resp.status = 200
      resp.content_type = "application/json; charset=utf-8"
      resp.body = body

      begin
        resp.send_response(client)
        client.close
      rescue Errno::EPIPE
        error_logger.error "Connection lost, unsent response:"
        error_logger.error body
      end
    rescue Errno::EINVAL
      break
    rescue IOError
      # Hello JRuby
      break
    end
  end
end

#wait_for_itObject



68
69
70
71
72
73
74
75
# File 'lib/robe/server.rb', line 68

def wait_for_it
  begin
    TCPSocket.new("127.0.0.1", @port).close
  rescue
    sleep 0.05
    retry
  end
end