http-2-next 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0b8760a4af91eae4da3ae631c99b68cef2130cc0758ac7c91420bffe53582e55
4
+ data.tar.gz: ced41c1e91b125dd4ea957d026b27ccec5cd2aa79ca6376883f829c52199e758
5
+ SHA512:
6
+ metadata.gz: a3f421c1e495cb9bed15a3635dfdae9996074a77e221f1a3e5ebd75be0df0e154ab395ffc3caf3e333749b2fd4350ec226941f84c55c9c99ef023f18fe1da002
7
+ data.tar.gz: 4f0af698fbd7ac5a94b03fba9b93f47c6d8c34d0e44469a63dcec27609932a45e2b59f6ed08a8e55441d14756a238a8f0bea08ae795e3494e061f82d0a4668cf
@@ -0,0 +1,302 @@
1
+ # HTTP-2-Next
2
+
3
+ [![Gem Version](https://badge.fury.io/rb/http-2.svg)](http://rubygems.org/gems/http-2)
4
+ [![Build status](https://gitlab.com/honeyryderchuck/http-2-next/badges/master/pipeline.svg)](https://gitlab.com/honeyryderchuck/http-2-next/commits/master)
5
+ [![coverage report](https://gitlab.com/honeyryderchuck/httpx/badges/master/coverage.svg)](https://honeyryderchuck.gitlab.io/http-2-next/coverage/#_AllFiles)
6
+
7
+ **Attention!** This is a fork of the [http-2](https://github.com/igrigorik/http-2) gem.
8
+
9
+ Pure Ruby, framework and transport agnostic, implementation of HTTP/2 protocol and HPACK header compression with support for:
10
+
11
+
12
+ * [Binary framing](https://hpbn.co/http2/#binary-framing-layer) parsing and encoding
13
+ * [Stream multiplexing](https://hpbn.co/http2/#streams-messages-and-frames) and [prioritization](https://hpbn.co/http2/#stream-prioritization)
14
+ * Connection and stream [flow control](https://hpbn.co/http2/#flow-control)
15
+ * [Header compression](https://hpbn.co/http2/#header-compression) and [server push](https://hpbn.co/http2/#server-push)
16
+ * Connection and stream management
17
+ * And more... see [API docs](https://www.rubydoc.info/gems/http-2-next)
18
+
19
+ Protocol specifications:
20
+
21
+ * [Hypertext Transfer Protocol Version 2 (RFC 7540)](https://httpwg.github.io/specs/rfc7540.html)
22
+ * [HPACK: Header Compression for HTTP/2 (RFC 7541)](https://httpwg.github.io/specs/rfc7541.html)
23
+
24
+
25
+ ## Getting started
26
+
27
+ ```bash
28
+ $> gem install http-2-next
29
+ ```
30
+
31
+ This implementation makes no assumptions as how the data is delivered: it could be a regular Ruby TCP socket, your custom eventloop, or whatever other transport you wish to use - e.g. ZeroMQ, [avian carriers](http://www.ietf.org/rfc/rfc1149.txt), etc.
32
+
33
+ Your code is responsible for feeding data into the parser, which performs all of the necessary HTTP/2 decoding, state management and the rest, and vice versa, the parser will emit bytes (encoded HTTP/2 frames) that you can then route to the destination. Roughly, this works as follows:
34
+
35
+ ```ruby
36
+ require 'http/2/next'
37
+ HTTP2 = HTTP2Next
38
+
39
+ socket = YourTransport.new
40
+
41
+ conn = HTTP2::Client.new
42
+ conn.on(:frame) {|bytes| socket << bytes }
43
+
44
+ while bytes = socket.read
45
+ conn << bytes
46
+ end
47
+ ```
48
+
49
+ Checkout provided [client](example/client.rb) and [server](example/server.rb) implementations for basic examples.
50
+
51
+
52
+ ### Connection lifecycle management
53
+
54
+ Depending on the role of the endpoint you must initialize either a [Client](lib/http/2/next/client.rb) or a [Server](lib/http/2/next/server.rb) object. Doing so picks the appropriate header compression / decompression algorithms and stream management logic. From there, you can subscribe to connection level events, or invoke appropriate APIs to allocate new streams and manage the lifecycle. For example:
55
+
56
+ ```ruby
57
+ HTTP2 = HTTP2Next
58
+ # - Server ---------------
59
+ server = HTTP2::Server.new
60
+
61
+ server.on(:stream) { |stream| ... } # process inbound stream
62
+ server.on(:frame) { |bytes| ... } # encoded HTTP/2 frames
63
+
64
+ server.ping { ... } # run liveness check, process pong response
65
+ server.goaway # send goaway frame to the client
66
+
67
+ # - Client ---------------
68
+ client = HTTP2::Client.new
69
+ client.on(:promise) { |stream| ... } # process push promise
70
+
71
+ stream = client.new_stream # allocate new stream
72
+ stream.headers({':method' => 'post', ...}, end_stream: false)
73
+ stream.data(payload, end_stream: true)
74
+ ```
75
+
76
+ Events emitted by the connection object:
77
+
78
+ <table>
79
+ <tr>
80
+ <td><b>:promise</b></td>
81
+ <td>client role only, fires once for each new push promise</td>
82
+ </tr>
83
+ <tr>
84
+ <td><b>:stream</b></td>
85
+ <td>server role only, fires once for each new client stream</td>
86
+ </tr>
87
+ <tr>
88
+ <td><b>:frame</b></td>
89
+ <td>fires once for every encoded HTTP/2 frame that needs to be sent to the peer</td>
90
+ </tr>
91
+ </table>
92
+
93
+
94
+ ### Stream lifecycle management
95
+
96
+ A single HTTP/2 connection can [multiplex multiple streams](https://hpbn.co/http2/#request-and-response-multiplexing) in parallel: multiple requests and responses can be in flight simultaneously and stream data can be interleaved and prioritized. Further, the specification provides a well-defined lifecycle for each stream (see below).
97
+
98
+ The good news is, all of the stream management, and state transitions, and error checking is handled by the library. All you have to do is subscribe to appropriate events (marked with ":" prefix in diagram below) and provide your application logic to handle request and response processing.
99
+
100
+ ```
101
+ +--------+
102
+ PP | | PP
103
+ ,--------| idle |--------.
104
+ / | | \
105
+ v +--------+ v
106
+ +----------+ | +----------+
107
+ | | | H | |
108
+ ,---|:reserved | | |:reserved |---.
109
+ | | (local) | v | (remote) | |
110
+ | +----------+ +--------+ +----------+ |
111
+ | | :active | | :active | |
112
+ | | ,-------|:active |-------. | |
113
+ | | H / ES | | ES \ H | |
114
+ | v v +--------+ v v |
115
+ | +-----------+ | +-----------+ |
116
+ | |:half_close| | |:half_close| |
117
+ | | (remote) | | | (local) | |
118
+ | +-----------+ | +-----------+ |
119
+ | | v | |
120
+ | | ES/R +--------+ ES/R | |
121
+ | `----------->| |<-----------' |
122
+ | R | :close | R |
123
+ `-------------------->| |<--------------------'
124
+ +--------+
125
+ ```
126
+
127
+ For sake of example, let's take a look at a simple server implementation:
128
+
129
+ ```ruby
130
+ HTTP2 = HTTP2Next
131
+
132
+ conn = HTTP2::Server.new
133
+
134
+ # emits new streams opened by the client
135
+ conn.on(:stream) do |stream|
136
+ stream.on(:active) { } # fires when stream transitions to open state
137
+ stream.on(:close) { } # stream is closed by client and server
138
+
139
+ stream.on(:headers) { |head| ... } # header callback
140
+ stream.on(:data) { |chunk| ... } # body payload callback
141
+
142
+ # fires when client terminates its request (i.e. request finished)
143
+ stream.on(:half_close) do
144
+
145
+ # ... generate_response
146
+
147
+ # send response
148
+ stream.headers({
149
+ ":status" => 200,
150
+ "content-type" => "text/plain"
151
+ })
152
+
153
+ # split response between multiple DATA frames
154
+ stream.data(response_chunk, end_stream: false)
155
+ stream.data(last_chunk)
156
+ end
157
+ end
158
+ ```
159
+
160
+ Events emitted by the [Stream object](lib/http/2/next/stream.rb):
161
+
162
+ <table>
163
+ <tr>
164
+ <td><b>:reserved</b></td>
165
+ <td>fires exactly once when a push stream is initialized</td>
166
+ </tr>
167
+ <tr>
168
+ <td><b>:active</b></td>
169
+ <td>fires exactly once when the stream become active and is counted towards the open stream limit</td>
170
+ </tr>
171
+ <tr>
172
+ <td><b>:headers</b></td>
173
+ <td>fires once for each received header block (multi-frame blocks are reassembled before emitting this event)</td>
174
+ </tr>
175
+ <tr>
176
+ <td><b>:data</b></td>
177
+ <td>fires once for every DATA frame (no buffering)</td>
178
+ </tr>
179
+ <tr>
180
+ <td><b>:half_close</b></td>
181
+ <td>fires exactly once when the opposing peer closes its end of connection (e.g. client indicating that request is finished, or server indicating that response is finished)</td>
182
+ </tr>
183
+ <tr>
184
+ <td><b>:close</b></td>
185
+ <td>fires exactly once when both peers close the stream, or if the stream is reset</td>
186
+ </tr>
187
+ <tr>
188
+ <td><b>:priority</b></td>
189
+ <td>fires once for each received priority update (server only)</td>
190
+ </tr>
191
+ </table>
192
+
193
+
194
+ ### Prioritization
195
+
196
+ Each HTTP/2 [stream has a priority value](https://hpbn.co/http2/#stream-prioritization) that can be sent when the new stream is initialized, and optionally reprioritized later:
197
+
198
+ ```ruby
199
+ HTTP2 = HTTP2Next
200
+
201
+ client = HTTP2::Client.new
202
+
203
+ default_priority_stream = client.new_stream
204
+ custom_priority_stream = client.new_stream(priority: 42)
205
+
206
+ # sometime later: change priority value
207
+ custom_priority_stream.reprioritize(32000) # emits PRIORITY frame
208
+ ```
209
+
210
+ On the opposite side, the server can optimize its stream processing order or resource allocation by accessing the stream priority value (`stream.priority`).
211
+
212
+
213
+ ### Flow control
214
+
215
+ Multiplexing multiple streams over the same TCP connection introduces contention for shared bandwidth resources. Stream priorities can help determine the relative order of delivery, but priorities alone are insufficient to control how the resource allocation is performed between multiple streams. To address this, HTTP/2 provides a simple mechanism for [stream and connection flow control](https://hpbn.co/http2/#flow-control).
216
+
217
+ Connection and stream flow control is handled by the library: all streams are initialized with the default window size (64KB), and send/receive window updates are automatically processed - i.e. window is decremented on outgoing data transfers, and incremented on receipt of window frames. Similarly, if the window is exceeded, then data frames are automatically buffered until window is updated.
218
+
219
+ The only thing left is for your application to specify the logic as to when to emit window updates:
220
+
221
+ ```ruby
222
+ conn.buffered_amount # check amount of buffered data
223
+ conn.window # check current window size
224
+ conn.window_update(1024) # increment connection window by 1024 bytes
225
+
226
+ stream.buffered_amount # check amount of buffered data
227
+ stream.window # check current window size
228
+ stream.window_update(2048) # increment stream window by 2048 bytes
229
+ ```
230
+
231
+
232
+ ### Server push
233
+
234
+ An HTTP/2 server can [send multiple replies](https://hpbn.co/http2/#server-push) to a single client request. To do so, first it emits a "push promise" frame which contains the headers of the promised resource, followed by the response to the original request, as well as promised resource payloads (which may be interleaved). A simple example is in order:
235
+
236
+ ```ruby
237
+ HTTP2 = HTTP2Next
238
+
239
+ conn = HTTP2::Server.new
240
+
241
+ conn.on(:stream) do |stream|
242
+ stream.on(:headers) { |head| ... }
243
+ stream.on(:data) { |chunk| ... }
244
+
245
+ # fires when client terminates its request (i.e. request finished)
246
+ stream.on(:half_close) do
247
+ promise_header = { ':method' => 'GET',
248
+ ':authority' => 'localhost',
249
+ ':scheme' => 'https',
250
+ ':path' => "/other_resource" }
251
+
252
+ # initiate server push stream
253
+ push_stream = nil
254
+ stream.promise(promise_header) do |push|
255
+ push.headers({...})
256
+ push_stream = push
257
+ end
258
+
259
+ # send response
260
+ stream.headers({
261
+ ":status" => 200,
262
+ "content-type" => "text/plain"
263
+ })
264
+
265
+ # split response between multiple DATA frames
266
+ stream.data(response_chunk, end_stream: false)
267
+ stream.data(last_chunk)
268
+
269
+ # now send the previously promised data
270
+ push_stream.data(push_data)
271
+ end
272
+ end
273
+ ```
274
+
275
+ When a new push promise stream is sent by the server, the client is notified via the `:promise` event:
276
+
277
+ ```ruby
278
+ HTTP2 = HTTP2Next
279
+
280
+ conn = HTTP2::Client.new
281
+ conn.on(:promise) do |push|
282
+ # process push stream
283
+ end
284
+ ```
285
+
286
+ The client can cancel any given push stream (via `.close`), or disable server push entirely by sending the appropriate settings frame:
287
+
288
+ ```ruby
289
+ client.settings(settings_enable_push: 0)
290
+ ```
291
+ ### Specs
292
+
293
+ To run specs:
294
+
295
+ ```ruby
296
+ rake
297
+ ```
298
+
299
+ ### License
300
+
301
+ (MIT License) - Copyright (c) 2013-2019 Ilya Grigorik ![GA](https://www.google-analytics.com/__utm.gif?utmac=UA-71196-9&utmhn=github.com&utmdt=HTTP2&utmp=/http-2/readme)
302
+ (MIT License) - Copyright (c) 2019 Tiago Cardoso ![GA](https://www.google-analytics.com/__utm.gif?utmac=UA-71196-9&utmhn=github.com&utmdt=HTTP2&utmp=/http-2/readme)
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "http/2/next/version"
4
+ require "http/2/next/error"
5
+ require "http/2/next/emitter"
6
+ require "http/2/next/buffer"
7
+ require "http/2/next/flow_buffer"
8
+ require "http/2/next/huffman"
9
+ require "http/2/next/huffman_statemachine"
10
+ require "http/2/next/compressor"
11
+ require "http/2/next/framer"
12
+ require "http/2/next/connection"
13
+ require "http/2/next/client"
14
+ require "http/2/next/server"
15
+ require "http/2/next/stream"
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "forwardable"
4
+
5
+ module HTTP2Next
6
+ # Binary buffer wraps String.
7
+ #
8
+ class Buffer
9
+ extend Forwardable
10
+
11
+ def_delegators :@buffer, :ord, :encoding, :setbyte, :unpack,
12
+ :size, :each_byte, :to_str, :to_s, :length, :inspect,
13
+ :[], :[]=, :empty?, :bytesize, :include?
14
+
15
+ UINT32 = "N"
16
+ private_constant :UINT32
17
+
18
+ # Forces binary encoding on the string
19
+ def initialize(str = "".b)
20
+ str = str.dup if str.frozen?
21
+ @buffer = str.force_encoding(Encoding::BINARY)
22
+ end
23
+
24
+ # Emulate StringIO#read: slice first n bytes from the buffer.
25
+ #
26
+ # @param n [Integer] number of bytes to slice from the buffer
27
+ def read(n)
28
+ Buffer.new(@buffer.slice!(0, n))
29
+ end
30
+
31
+ # Emulate StringIO#getbyte: slice first byte from buffer.
32
+ def getbyte
33
+ read(1).ord
34
+ end
35
+
36
+ def slice!(*args)
37
+ Buffer.new(@buffer.slice!(*args))
38
+ end
39
+
40
+ def slice(*args)
41
+ Buffer.new(@buffer.slice(*args))
42
+ end
43
+
44
+ def force_encoding(*args)
45
+ @buffer = @buffer.force_encoding(*args)
46
+ end
47
+
48
+ def ==(other)
49
+ @buffer == other
50
+ end
51
+
52
+ def +(other)
53
+ @buffer += other
54
+ end
55
+
56
+ # Emulate String#getbyte: return nth byte from buffer.
57
+ def readbyte(n)
58
+ @buffer[n].ord
59
+ end
60
+
61
+ # Slice unsigned 32-bit integer from buffer.
62
+ # @return [Integer]
63
+ def read_uint32
64
+ read(4).unpack(UINT32).first
65
+ end
66
+
67
+ # Ensures that data that is added is binary encoded as well,
68
+ # otherwise this could lead to the Buffer instance changing its encoding.
69
+ %i[<< prepend].each do |mutating_method|
70
+ define_method(mutating_method) do |string|
71
+ string = string.dup if string.frozen?
72
+ @buffer.send mutating_method, string.force_encoding(Encoding::BINARY)
73
+
74
+ self
75
+ end
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module HTTP2Next
4
+ # HTTP 2.0 client connection class that implements appropriate header
5
+ # compression / decompression algorithms and stream management logic.
6
+ #
7
+ # Your code is responsible for driving the client object, which in turn
8
+ # performs all of the necessary HTTP 2.0 encoding / decoding, state
9
+ # management, and the rest. A simple example:
10
+ #
11
+ # @example
12
+ # socket = YourTransport.new
13
+ #
14
+ # conn = HTTP2Next::Client.new
15
+ # conn.on(:frame) {|bytes| socket << bytes }
16
+ #
17
+ # while bytes = socket.read
18
+ # conn << bytes
19
+ # end
20
+ #
21
+ class Client < Connection
22
+ # Initialize new HTTP 2.0 client object.
23
+ def initialize(**settings)
24
+ @stream_id = 1
25
+ @state = :waiting_connection_preface
26
+
27
+ @local_role = :client
28
+ @remote_role = :server
29
+
30
+ super
31
+ end
32
+
33
+ # Send an outgoing frame. Connection and stream flow control is managed
34
+ # by Connection class.
35
+ #
36
+ # @see Connection
37
+ # @param frame [Hash]
38
+ def send(frame)
39
+ send_connection_preface
40
+ super(frame)
41
+ end
42
+
43
+ def receive(frame)
44
+ send_connection_preface
45
+ super(frame)
46
+ end
47
+
48
+ # sends the preface and initializes the first stream in half-closed state
49
+ def upgrade
50
+ raise ProtocolError unless @stream_id == 1
51
+
52
+ send_connection_preface
53
+ new_stream(state: :half_closed_local)
54
+ end
55
+
56
+ # Emit the connection preface if not yet
57
+ def send_connection_preface
58
+ return unless @state == :waiting_connection_preface
59
+
60
+ @state = :connected
61
+ emit(:frame, CONNECTION_PREFACE_MAGIC)
62
+
63
+ payload = @local_settings.reject { |k, v| v == SPEC_DEFAULT_CONNECTION_SETTINGS[k] }
64
+ settings(payload)
65
+ end
66
+
67
+ def self.settings_header(**settings)
68
+ frame = Framer.new.generate(type: :settings, stream: 0, payload: settings)
69
+ Base64.urlsafe_encode64(frame[9..-1])
70
+ end
71
+ end
72
+ end