Module: Polyphony::HTTP::Server

Defined in:
lib/polyphony/http/server.rb,
lib/polyphony/http/server/http1.rb,
lib/polyphony/http/server/http2.rb,
lib/polyphony/http/server/request.rb,
lib/polyphony/http/server/http2_stream.rb

Defined Under Namespace

Classes: HTTP1Adapter, HTTP2Adapter, HTTP2StreamHandler, Request

Constant Summary collapse

ALPN_PROTOCOLS =
%w[h2 http/1.1].freeze
H2_PROTOCOL =
'h2'

Class Method Summary collapse

Class Method Details

.accept_loop(server, opts, &handler) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/polyphony/http/server.rb', line 31

def accept_loop(server, opts, &handler)
  loop do
    client = server.accept
    spin { client_loop(client, opts, &handler) }
    snooze
  rescue OpenSSL::SSL::SSLError
    # disregard
  end
end

.client_loop(client, opts, &handler) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/polyphony/http/server.rb', line 41

def client_loop(client, opts, &handler)
  client.no_delay if client.respond_to?(:no_delay)
  adapter = protocol_adapter(client, opts)
  adapter.each(&handler)
ensure
  client.close
end

.listen(host, port, opts = {}) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/polyphony/http/server.rb', line 22

def listen(host, port, opts = {})
  opts[:alpn_protocols] = ALPN_PROTOCOLS
  Net.tcp_listen(host, port, opts).tap do |socket|
    socket.define_singleton_method(:each) do |&block|
      ::Polyphony::HTTP::Server.accept_loop(socket, opts, &block)
    end
  end
end

.protocol_adapter(socket, opts) ⇒ Object



49
50
51
52
53
54
# File 'lib/polyphony/http/server.rb', line 49

def protocol_adapter(socket, opts)
  use_http2 = socket.respond_to?(:alpn_protocol) &&
              socket.alpn_protocol == H2_PROTOCOL
  klass = use_http2 ? HTTP2Adapter : HTTP1Adapter
  klass.new(socket, opts)
end

.serve(host, port, opts = {}, &handler) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/polyphony/http/server.rb', line 14

def serve(host, port, opts = {}, &handler)
  opts[:alpn_protocols] = ALPN_PROTOCOLS
  server = Net.tcp_listen(host, port, opts)
  accept_loop(server, opts, &handler)
ensure
  server.close
end