aboutsummaryrefslogtreecommitdiffstats
path: root/lib/plum/client/upgrade_client_session.rb
blob: a098c71f19160ccd347efdc2c8d33b89d9260ed2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
# frozen-string-literal: true

module Plum
  # Try upgrade to HTTP/2
  class UpgradeClientSession
    def initialize(socket, config)
      prepare_session(socket, config)
    end

    def succ
      @session.succ
    end

    def empty?
      @session.empty?
    end

    def close
      @session.close
    end

    def request(headers, body, options, &headers_cb)
      @session.request(headers, body, options, &headers_cb)
    end

    private
    def prepare_session(socket, config)
      lcs = LegacyClientSession.new(socket, config)
      opt_res = lcs.request({ ":method" => "OPTIONS",
                              ":path" => "*",
                              "User-Agent" => config[:user_agent],
                              "Connection" => "Upgrade, HTTP2-Settings",
                              "Upgrade" => "h2c",
                              "HTTP2-Settings" => "" }, nil, {})
      lcs.succ until opt_res.finished?

      if opt_res.status == "101"
        lcs.close
        @session = ClientSession.new(socket, config)
        @session.plum.stream(1).set_state(:half_closed_local)
      else
        @session = lcs
      end
    end
  end
end