Lukasa/hyper — pull request #43 by alekstorm (2014-04-13 20:16:09+00:00)
Title: Create connection pool with support for multiple protocols, security levels, and alt-svc/prior knowledge

After trying a couple times to come up with a design for `Alt-Svc` or `Upgrade` support, I realized the logic needs to be contained in a connection pool class. This turned out to be a powerful abstraction - for example, if an HTTP/1.1 connection is requested to a given host, and we have a pre-existing HTTP/2.0 connection, we can return the latter instead (this is where @lukasa's decision to mimic the standard `HTTPConnection` API was prescient). Similarly, a request for an unencrypted connection may return an encrypted one.

After reading [the opportunistic encryption IETF draft](http://tools.ietf.org/html/draft-nottingham-http2-encryption-02#section-2), I've decided to include three default security levels: null (no encryption), weak (encryption w/o hostname verification or certificate validation), and strong (encryption with all the bells and whistles). Perhaps the "weak" category could also include connections with broken or non-PFS ciphers in the future.

Note that for HTTP/2.0 connections, the class doesn't function as a traditional connection pool: rather than removing connections from the pool, processing a request/response pair, and returning them to the pool, they are used for multiple concurrent request streams.

Additionally, upgrading an HTTP/1.1 connection to HTTP/2.0 is exposed in an unusual way: to ensure the user handles the switch properly (since HTTP/1.1 can no longer be spoken on the socket), an `UpgradedConnection` exception is raised from `getresponse()` if the `Upgrade` dance completed successfully (i.e. the server returned a `101` response with the proper header fields).

This is meant as a proof-of-concept only - the code is less than stellar, minimally tested, and almost certainly does not work against real servers; I haven't even bothered to try it. It's also quite complicated, mostly due to my decision to make it extensible by introducing a precedence hierarchy for both protocols and security levels (it did come in handy for testing, though). Hopefully a lot of the list iteration can be factored out into utility functions in the future. In addition, it doesn't offer much of the functionality of the `HTTP(S)ConnectionPool` class in urllib3, but we could remedy that soon as well.