Class: Polyphony::HTTP::Server::HTTP2Adapter

Inherits:
Object
  • Object
show all
Defined in:
lib/polyphony/http/server/http2.rb

Overview

HTTP2 server adapter

Constant Summary collapse

UPGRADE_MESSAGE =
<<~HTTP.gsub("\n", "\r\n")
  HTTP/1.1 101 Switching Protocols
  Connection: Upgrade
  Upgrade: h2c

HTTP

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(conn, opts, upgrade_headers = nil) ⇒ HTTP2Adapter

Returns a new instance of HTTP2Adapter.



16
17
18
19
20
21
22
23
24
25
# File 'lib/polyphony/http/server/http2.rb', line 16

def initialize(conn, opts, upgrade_headers = nil)
  @conn = conn
  @opts = opts
  @upgrade_headers = upgrade_headers

  @interface = ::HTTP2::Server.new
  @connection_fiber = Fiber.current
  @interface.on(:frame, &method(:send_frame))
  @streams = {}
end

Class Method Details

.upgrade_each(socket, opts, headers, &block) ⇒ Object



11
12
13
14
# File 'lib/polyphony/http/server/http2.rb', line 11

def self.upgrade_each(socket, opts, headers, &block)
  adapter = new(socket, opts, headers)
  adapter.each(&block)
end

Instance Method Details

#closeObject



75
76
77
# File 'lib/polyphony/http/server/http2.rb', line 75

def close
  @conn.close
end

#each(&block) ⇒ Object

Iterates over incoming requests



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/polyphony/http/server/http2.rb', line 50

def each(&block)
  @interface.on(:stream) { |stream| start_stream(stream, &block) }
  upgrade if @upgrade_headers

  while (data = @conn.readpartial(8192))
    @interface << data
    snooze
  end
rescue SystemCallError, IOError
  # ignore
ensure
  finalize_client_loop
end

#finalize_client_loopObject



69
70
71
72
73
# File 'lib/polyphony/http/server/http2.rb', line 69

def finalize_client_loop
  @interface = nil
  @streams.each_key(&:stop)
  @conn.close
end

#send_frame(data) ⇒ Object



27
28
29
30
31
# File 'lib/polyphony/http/server/http2.rb', line 27

def send_frame(data)
  @conn << data
rescue Exception => e
  @connection_fiber.transfer e
end

#start_stream(stream, &block) ⇒ Object



64
65
66
67
# File 'lib/polyphony/http/server/http2.rb', line 64

def start_stream(stream, &block)
  stream = Stream.new(stream, &block)
  @streams[stream] = true
end

#upgradeObject



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

def upgrade
  @conn << UPGRADE_MESSAGE
  settings = @upgrade_headers['HTTP2-Settings']
  Fiber.current.schedule(nil)
  @interface.upgrade(settings, @upgrade_headers, '')
ensure
  @upgrade_headers = nil
end