http-2 0.6.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: fb3959b06060d626b9065b6b267fc1e4f3906742
4
+ data.tar.gz: c7da3c39b1829b0458d6d550df7db911bcd69d29
5
+ SHA512:
6
+ metadata.gz: 293393327feb7f5aafd7017fb63ddb1a332957c8c5221c26050cb5045edf7067b8c2094ee8587227262c3be427838bab46ebd16c33ae8c0e05f8e08482d222ee
7
+ data.tar.gz: d619c4939dfe5daa0d861d190d9f83368cfd352e46e22b897eaca17318e12550612b855a0a1bf7f860d5443776d3ca9d1fe5e873bdde452c6e2b29c21b568292
data/.autotest ADDED
@@ -0,0 +1,19 @@
1
+ require 'autotest/growl'
2
+
3
+ Autotest.add_hook(:initialize) {|at|
4
+ at.add_exception %r{^\.git}
5
+ at.add_exception %r{^./tmp}
6
+
7
+ at.clear_mappings
8
+
9
+ at.add_mapping(%r%^spec/.*_spec\.rb$%) { |filename, _|
10
+ filename
11
+ }
12
+ at.add_mapping(%r%^lib/(.*)\.rb$%) { |_, m|
13
+ ["spec/#{m[1].split('/').last}_spec.rb"]
14
+ }
15
+ at.add_mapping(%r%^spec/(spec_helper|shared/.*)\.rb$%) {
16
+ files_matching %r%^spec/.*_spec\.rb$%
17
+ }
18
+ nil
19
+ }
data/.gitignore ADDED
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ autotest
2
+ --color
3
+ --format documentation
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.0.0
4
+ script: bundle exec rake test
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in http2-parser.gemspec
4
+ gemspec
data/README.md ADDED
@@ -0,0 +1,280 @@
1
+ # HTTP-2
2
+
3
+ Pure ruby, framework and transport agnostic implementation of [HTTP 2.0 protocol](http://tools.ietf.org/html/draft-ietf-httpbis-http2) with support for:
4
+
5
+ * [Binary framing](http://chimera.labs.oreilly.com/books/1230000000545/ch12.html#_binary_framing_layer) parsing and encoding
6
+ * [Stream multiplexing](http://chimera.labs.oreilly.com/books/1230000000545/ch12.html#HTTP2_STREAMS_MESSAGES_FRAMES) and [prioritization](http://chimera.labs.oreilly.com/books/1230000000545/ch12.html#HTTP2_PRIORITIZATION)
7
+ * Connection and stream [flow control](http://chimera.labs.oreilly.com/books/1230000000545/ch12.html#_flow_control)
8
+ * [Header compression](http://chimera.labs.oreilly.com/books/1230000000545/ch12.html#HTTP2_HEADER_COMPRESSION) and [server push](http://chimera.labs.oreilly.com/books/1230000000545/ch12.html#HTTP2_PUSH)
9
+ * Connection and stream management, and other HTTP 2.0 goodies...
10
+
11
+ Current implementation (see [HPBN chapter for HTTP 2.0 overview](http://chimera.labs.oreilly.com/books/1230000000545/ch12.html)), is based on:
12
+
13
+ * [draft-ietf-httpbis-http2-06](http://tools.ietf.org/html/draft-ietf-httpbis-http2-06)
14
+ * [draft-ietf-httpbis-header-compression-01](http://tools.ietf.org/html/draft-ietf-httpbis-header-compression)
15
+
16
+ _Note: the underlying specifications are still evolving, expect APIs to change and evolve also..._
17
+
18
+
19
+ ## Getting started
20
+
21
+ 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.
22
+
23
+ Your code is responsible for feeding data into the parser, which performs all of the necessary HTTP 2.0 decoding, state management and the rest, and vice versa, the parser will emit bytes (encoded HTTP 2.0 frames) that you can then route to the destination. Roughly, this works as follows:
24
+
25
+ ```ruby
26
+ socket = YourTransport.new
27
+
28
+ conn = HTTP2::Connection.new(:client)
29
+ conn.on(:frame) {|bytes| socket << bytes }
30
+
31
+ while bytes = socket.read
32
+ conn << bytes
33
+ end
34
+ ```
35
+
36
+ Checkout provided [client](https://github.com/igrigorik/http-2/blob/master/example/client.rb) and [server]((https://github.com/igrigorik/http-2/blob/master/example/server.rb) implementations for basic examples.
37
+
38
+
39
+ ### Connection lifecycle management
40
+
41
+ When the connection object is instantiated you must specify its role (`:client` or `:server`) to initialize 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:
42
+
43
+ ```ruby
44
+ # - Server ---------------
45
+ server = HTTP2::Connection.new(:server)
46
+
47
+ server.on(:stream) { |stream| ... } # process inbound stream
48
+ server.on(:frame) { |bytes| ... } # encoded HTTP 2.0 frames
49
+
50
+ server.ping { ... } # run liveness check, process pong response
51
+ server.goaway # send goaway frame to the client
52
+
53
+ # - Client ---------------
54
+ client = HTTP2::Connection.new(:client)
55
+ client.on(:promise) { |stream| ... } # process push promise
56
+
57
+ stream = client.new_stream # allocate new stream
58
+ stream.headers({':method' => 'post', ...}, end_stream: false)
59
+ stream.data(payload, end_stream: true)
60
+ ```
61
+
62
+ Events emitted by the connection object:
63
+
64
+ <table>
65
+ <tr>
66
+ <td><b>:promise</b></td>
67
+ <td>client role only, fires once for each new push promise</td>
68
+ </tr>
69
+ <tr>
70
+ <td><b>:stream</b></td>
71
+ <td>server role only, fires once for each new client stream</td>
72
+ </tr>
73
+ <tr>
74
+ <td><b>:frame</b></td>
75
+ <td>fires once for every encoded HTTP 2.0 frame that needs to be sent to the peer</td>
76
+ </tr>
77
+ </table>
78
+
79
+
80
+ ### Stream lifecycle management
81
+
82
+ A single HTTP 2.0 connection can [multiplex multiple streams](http://chimera.labs.oreilly.com/books/1230000000545/ch12.html#REQUEST_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).
83
+
84
+ 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.
85
+
86
+ ```
87
+ +--------+
88
+ PP | | PP
89
+ ,--------| idle |--------.
90
+ / | | \
91
+ v +--------+ v
92
+ +----------+ | +----------+
93
+ | | | H | |
94
+ ,---|:reserved | | |:reserved |---.
95
+ | | (local) | v | (remote) | |
96
+ | +----------+ +--------+ +----------+ |
97
+ | | :active | | :active | |
98
+ | | ,-------|:active |-------. | |
99
+ | | H / ES | | ES \ H | |
100
+ | v v +--------+ v v |
101
+ | +-----------+ | +-_---------+ |
102
+ | |:half_close| | |:half_close| |
103
+ | | (remote) | | | (local) | |
104
+ | +-----------+ | +-----------+ |
105
+ | | v | |
106
+ | | ES/R +--------+ ES/R | |
107
+ | `----------->| |<-----------' |
108
+ | R | :close | R |
109
+ `-------------------->| |<--------------------'
110
+ +--------+
111
+ ```
112
+
113
+ For sake of example, let's take a look at a simple server implementation:
114
+
115
+ ```ruby
116
+ conn = HTTP2::Connection.new(:server)
117
+
118
+ # emits new streams opened by the client
119
+ conn.on(:stream) do |stream|
120
+ stream.on(:active) { } # fires when stream transitions to open state
121
+ stream.on(:close) { } # stream is closed by client and server
122
+
123
+ stream.on(:headers) { |head| ... } # header callback
124
+ stream.on(:data) { |chunk| ... } # body payload callback
125
+
126
+ # fires when client terminates its request (i.e. request finished)
127
+ stream.on(:half_close) do
128
+
129
+ # ... generate_response
130
+
131
+ # send response
132
+ stream.headers({
133
+ ":status" => 200,
134
+ "content-type" => "text/plain"
135
+ })
136
+
137
+ # split response between multiple DATA frames
138
+ stream.data(response_chunk, end_stream: false)
139
+ stream.data(last_chunk)
140
+ end
141
+ end
142
+ ```
143
+
144
+ Events emitted by the stream object:
145
+
146
+ <table>
147
+ <tr>
148
+ <td><b>:reserved</b></td>
149
+ <td>fires exactly once when a push stream is initialized</td>
150
+ </tr>
151
+ <tr>
152
+ <td><b>:active</b></td>
153
+ <td>fires exactly once when the stream become active and is counted towards the open stream limit</td>
154
+ </tr>
155
+ <tr>
156
+ <td><b>:headers</b></td>
157
+ <td>fires once for each received header block (multi-frame blocks are reassembled before emitting this event)</td>
158
+ </tr>
159
+ <tr>
160
+ <td><b>:data</b></td>
161
+ <td>fires once for every DATA frame (no buffering)</td>
162
+ </tr>
163
+ <tr>
164
+ <td><b>:half_close</b></td>
165
+ <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>
166
+ </tr>
167
+ <tr>
168
+ <td><b>:close</b></td>
169
+ <td>fires exactly once when both peers close the stream, or if the stream is reset</td>
170
+ </tr>
171
+ <tr>
172
+ <td><b>:priority</b></td>
173
+ <td>fires once for each received priority update (server only)</td>
174
+ </tr>
175
+ </table>
176
+
177
+
178
+ ### Prioritization
179
+
180
+ Each HTTP 2.0 [stream has a priority value](http://chimera.labs.oreilly.com/books/1230000000545/ch12.html#HTTP2_PRIORITIZATION) that can be sent when the new stream is initialized, and optionally reprioritized later:
181
+
182
+ ```ruby
183
+ client = HTTP2::Connection.new(:client)
184
+
185
+ default_priority_stream = client.new_stream
186
+ custom_priority_stream = client.new_stream(42) # priority: 42
187
+
188
+ # sometime later: change priority value
189
+ custom_priority_stream.priority = 32000 # emits PRIORITY frame
190
+ ```
191
+
192
+ On the opposite side, the server can optimize its stream processing order or resource allocation by accessing the stream priority value (`stream.priority`).
193
+
194
+
195
+ ### Flow control
196
+
197
+ 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.0 provides a simple mechanism for [stream and connection flow control](http://chimera.labs.oreilly.com/books/1230000000545/ch12.html#_flow_control).
198
+
199
+ 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.
200
+
201
+ The only thing left is for your application to specify the logic as to when to emit window updates:
202
+
203
+ ```ruby
204
+ conn.buffered_amount # check amount of buffered data
205
+ conn.window # check current window size
206
+ conn.window_update(1024) # increment connection window by 1024 bytes
207
+
208
+ stream.buffered_amount # check amount of buffered data
209
+ stream.window # check current window size
210
+ stream.window_update(2048) # increment stream window by 2048 bytes
211
+ ```
212
+
213
+ Alternatively, flow control can be disabled by emitting an appropriate settings frame on the connection:
214
+
215
+ ```ruby
216
+ conn.settings({
217
+ settings_max_concurrent_streams: 100, # limit number of concurrent streams
218
+ settings_flow_control_options: 1 # disable flow control
219
+ })
220
+ ```
221
+
222
+ ### Server push
223
+
224
+ An HTTP 2.0 server can [send multiple replies](http://chimera.labs.oreilly.com/books/1230000000545/ch12.html#HTTP2_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:
225
+
226
+ ```ruby
227
+ conn = HTTP2::Connection.new(:server)
228
+
229
+ conn.on(:stream) do |stream|
230
+ stream.on(:headers) { |head| ... }
231
+ stream.on(:data) { |chunk| ... }
232
+
233
+ # fires when client terminates its request (i.e. request finished)
234
+ stream.on(:half_close) do
235
+ head = {
236
+ ":status" => 200,
237
+ ":path" => "/other_resource",
238
+ "content-type" => "text/plain"
239
+ }
240
+
241
+ # initiate server push stream
242
+ stream.promise(head) do |push|
243
+ push.headers({ ... })
244
+ push.data(...)
245
+ end
246
+
247
+ # send response
248
+ stream.headers({
249
+ ":status" => 200,
250
+ "content-type" => "text/plain"
251
+ })
252
+
253
+ # split response between multiple DATA frames
254
+ stream.data(response_chunk, end_stream: false)
255
+ promise.data(payload)
256
+ stream.data(last_chunk)
257
+ end
258
+ end
259
+ ```
260
+
261
+ When a new push promise stream is sent by the server, the client is notifed via the `:promise` event:
262
+
263
+ ```ruby
264
+ conn = HTTP2::Connection.new(:client)
265
+ conn.on(:promise) do |push|
266
+ # process push stream
267
+ end
268
+ ```
269
+
270
+ The client can cancel any given push stream (via `.close`), or disable server push entirely by sending the appropriate settings frame (note that below setting only impacts server > client direction):
271
+
272
+ ```ruby
273
+ client.settings({
274
+ settings_max_concurrent_streams: 0 # set number of server initiated streams to 0 (aka, disable push)
275
+ })
276
+ ```
277
+
278
+ ### License
279
+
280
+ (MIT License) - Copyright (c) 2013 Ilya Grigorik
data/Rakefile ADDED
@@ -0,0 +1,11 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ desc "Run all RSpec tests"
5
+ RSpec::Core::RakeTask.new(:spec)
6
+
7
+ task :default => :spec
8
+ task :test => [:spec]
9
+
10
+ require 'yard'
11
+ YARD::Rake::YardocTask.new
data/example/client.rb ADDED
@@ -0,0 +1,46 @@
1
+ require_relative 'helper'
2
+
3
+ Addrinfo.tcp("localhost", 8080).connect do |sock|
4
+ conn = HTTP2::Connection.new(:client)
5
+ conn.on(:frame) do |bytes|
6
+ puts "Sending bytes: #{bytes.inspect}"
7
+ sock.print bytes
8
+ sock.flush
9
+ end
10
+
11
+ stream = conn.new_stream
12
+ log = Logger.new(stream.id)
13
+
14
+ stream.on(:close) do
15
+ log.info "stream closed"
16
+ sock.close
17
+ end
18
+
19
+ stream.on(:half_close) do
20
+ log.info "closing client-end of the stream"
21
+ end
22
+
23
+ stream.on(:headers) do |h|
24
+ log.info "response headers: #{h}"
25
+ end
26
+
27
+ stream.on(:data) do |d|
28
+ log.info "response data chunk: <<#{d}>>"
29
+ end
30
+
31
+ puts "Sending POST request"
32
+ stream.headers({
33
+ ":method" => "post",
34
+ ":host" => "localhost",
35
+ ":path" => "/resource",
36
+ "accept" => "*/*"
37
+ })
38
+
39
+ stream.data("woot!")
40
+
41
+ while !sock.closed? && !sock.eof?
42
+ data = sock.readpartial(1024)
43
+ puts "Received bytes: #{data.inspect}"
44
+ conn << data
45
+ end
46
+ end
data/example/helper.rb ADDED
@@ -0,0 +1,14 @@
1
+ $: << 'lib' << '../lib'
2
+
3
+ require 'socket'
4
+ require 'http/2'
5
+
6
+ class Logger
7
+ def initialize(id)
8
+ @id = id
9
+ end
10
+
11
+ def info(msg)
12
+ puts "[Stream #{@id}]: #{msg}"
13
+ end
14
+ end
data/example/server.rb ADDED
@@ -0,0 +1,50 @@
1
+ require_relative 'helper'
2
+
3
+ puts "Starting server on port 8080"
4
+ Socket.tcp_server_loop(8080) do |sock|
5
+ puts "New TCP connection!"
6
+
7
+ conn = HTTP2::Connection.new(:server)
8
+ conn.on(:frame) do |bytes|
9
+ puts "Writing bytes: #{bytes.inspect}"
10
+ sock.write bytes
11
+ end
12
+
13
+ conn.on(:stream) do |stream|
14
+ log = Logger.new(stream.id)
15
+ buffer = ""
16
+
17
+ stream.on(:active) { log.info "cliend opened new stream" }
18
+ stream.on(:close) { log.info "stream closed" }
19
+
20
+ stream.on(:headers) do |h|
21
+ log.info "request headers: #{h}"
22
+ end
23
+
24
+ stream.on(:data) do |d|
25
+ log.info "payload chunk: <<#{d}>>"
26
+ buffer << d
27
+ end
28
+
29
+ stream.on(:half_close) do
30
+ log.info "client closed its end of the stream, " +
31
+ "payload size: #{buffer.size}"
32
+
33
+ response = "Hello HTTP 2.0! echo: #{buffer}"
34
+ stream.headers({
35
+ ":status" => "200",
36
+ "content-length" => response.bytesize.to_s,
37
+ "content-type" => "text/plain"
38
+ }, end_stream: false)
39
+
40
+ # split response into multiple DATA frames
41
+ stream.data(response.slice!(0,5), end_stream: false)
42
+ stream.data(response)
43
+ end
44
+ end
45
+
46
+ while !sock.closed? && !sock.eof?
47
+ data = sock.readpartial(1024)
48
+ conn << data
49
+ end
50
+ end
data/http-2.gemspec ADDED
@@ -0,0 +1,24 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'http/2/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "http-2"
8
+ spec.version = HTTP2::VERSION
9
+ spec.authors = ["Ilya Grigorik"]
10
+ spec.email = ["ilya@igvita.com"]
11
+ spec.description = "Pure-ruby HTTP 2.0 protocol implementation"
12
+ spec.summary = spec.description
13
+ spec.homepage = "https://github.com/igrigorik/http-2"
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files`.split($/)
17
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
18
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_development_dependency "bundler", "~> 1.3"
22
+ spec.add_development_dependency "rake"
23
+ spec.add_development_dependency "rspec"
24
+ end
@@ -0,0 +1,21 @@
1
+ module HTTP2
2
+
3
+ # Simple binary buffer backed by string.
4
+ #
5
+ class Buffer < String
6
+
7
+ # Forces binary encoding on the string
8
+ def initialize(*args)
9
+ force_encoding('binary')
10
+ super(*args)
11
+ end
12
+
13
+ # Emulate StringIO#read: slice first n bytes from the buffer.
14
+ #
15
+ # @param n [Integer] number of bytes to slice from the buffer
16
+ def read(n)
17
+ slice!(0,n)
18
+ end
19
+ end
20
+
21
+ end