repo
stringclasses
1 value
pull_number
int64
20
3.81k
instance_id
stringlengths
18
20
issue_numbers
listlengths
1
2
base_commit
stringlengths
40
40
patch
stringlengths
214
153k
test_patch
stringlengths
288
262k
problem_statement
stringlengths
22
7.42k
hints_text
stringlengths
0
66.9k
created_at
stringlengths
20
20
version
stringclasses
21 values
environment_setup_commit
stringclasses
21 values
hyperium/hyper
1,674
hyperium__hyper-1674
[ "1517" ]
8bfe3c220c450d6a3d049fab4d7a591fa2ea0d82
diff --git a/src/client/connect/dns.rs b/src/client/connect/dns.rs --- a/src/client/connect/dns.rs +++ b/src/client/connect/dns.rs @@ -1,45 +1,183 @@ -use std::io; +use std::{fmt, io, vec}; use std::net::{ - Ipv4Addr, Ipv6Addr, + IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs, SocketAddrV4, SocketAddrV6, }; -use std::vec; +use std::sync::Arc; -use ::futures::{Async, Future, Poll}; +use futures::{Async, Future, Poll}; +use futures::future::{Executor, ExecuteError}; +use futures::sync::oneshot; +use futures_cpupool::{Builder as CpuPoolBuilder}; -pub struct Work { +use self::sealed::GaiTask; + +/// Resolve a hostname to a set of IP addresses. +pub trait Resolve { + /// The set of IP addresses to try to connect to. + type Addrs: Iterator<Item=IpAddr>; + /// A Future of the resolved set of addresses. + type Future: Future<Item=Self::Addrs, Error=io::Error>; + /// Resolve a hostname. + fn resolve(&self, name: Name) -> Self::Future; +} + +/// A domain name to resolve into IP addresses. +pub struct Name { + host: String, +} + +/// A resolver using blocking `getaddrinfo` calls in a threadpool. +#[derive(Clone)] +pub struct GaiResolver { + executor: GaiExecutor, +} + +pub struct GaiAddrs { + inner: IpAddrs, +} + +pub struct GaiFuture { + rx: oneshot::SpawnHandle<IpAddrs, io::Error>, +} + +impl Name { + pub(super) fn new(host: String) -> Name { + Name { + host, + } + } + + /// View the hostname as a string slice. + pub fn as_str(&self) -> &str { + &self.host + } +} + +impl fmt::Debug for Name { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self.host, f) + } +} + +impl GaiResolver { + /// Construct a new `GaiResolver`. + /// + /// Takes number of DNS worker threads. + pub fn new(threads: usize) -> Self { + let pool = CpuPoolBuilder::new() + .name_prefix("hyper-dns") + .pool_size(threads) + .create(); + GaiResolver::new_with_executor(pool) + } + + /// Construct a new `GaiResolver` with a shared thread pool executor. + /// + /// Takes an executor to run blocking `getaddrinfo` tasks on. + pub fn new_with_executor<E: 'static>(executor: E) -> Self + where + E: Executor<GaiTask> + Send + Sync, + { + GaiResolver { + executor: GaiExecutor(Arc::new(executor)), + } + } +} + +impl Resolve for GaiResolver { + type Addrs = GaiAddrs; + type Future = GaiFuture; + + fn resolve(&self, name: Name) -> Self::Future { + let blocking = GaiBlocking::new(name.host); + let rx = oneshot::spawn(blocking, &self.executor); + GaiFuture { + rx, + } + } +} + +impl fmt::Debug for GaiResolver { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad("GaiResolver") + } +} + +impl Future for GaiFuture { + type Item = GaiAddrs; + type Error = io::Error; + + fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + let addrs = try_ready!(self.rx.poll()); + Ok(Async::Ready(GaiAddrs { + inner: addrs, + })) + } +} + +impl fmt::Debug for GaiFuture { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad("GaiFuture") + } +} + +impl Iterator for GaiAddrs { + type Item = IpAddr; + + fn next(&mut self) -> Option<Self::Item> { + self.inner.next().map(|sa| sa.ip()) + } +} + +impl fmt::Debug for GaiAddrs { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad("GaiAddrs") + } +} + +#[derive(Clone)] +struct GaiExecutor(Arc<Executor<GaiTask> + Send + Sync>); + +impl Executor<oneshot::Execute<GaiBlocking>> for GaiExecutor { + fn execute(&self, future: oneshot::Execute<GaiBlocking>) -> Result<(), ExecuteError<oneshot::Execute<GaiBlocking>>> { + self.0.execute(GaiTask { work: future }) + .map_err(|err| ExecuteError::new(err.kind(), err.into_future().work)) + } +} + +pub(super) struct GaiBlocking { host: String, - port: u16 } -impl Work { - pub fn new(host: String, port: u16) -> Work { - Work { host: host, port: port } +impl GaiBlocking { + pub(super) fn new(host: String) -> GaiBlocking { + GaiBlocking { host } } } -impl Future for Work { +impl Future for GaiBlocking { type Item = IpAddrs; type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - debug!("resolving host={:?}, port={:?}", self.host, self.port); - (&*self.host, self.port).to_socket_addrs() + debug!("resolving host={:?}", self.host); + (&*self.host, 0).to_socket_addrs() .map(|i| Async::Ready(IpAddrs { iter: i })) } } -pub struct IpAddrs { +pub(super) struct IpAddrs { iter: vec::IntoIter<SocketAddr>, } impl IpAddrs { - pub fn new(addrs: Vec<SocketAddr>) -> Self { + pub(super) fn new(addrs: Vec<SocketAddr>) -> Self { IpAddrs { iter: addrs.into_iter() } } - pub fn try_parse(host: &str, port: u16) -> Option<IpAddrs> { + pub(super) fn try_parse(host: &str, port: u16) -> Option<IpAddrs> { if let Ok(addr) = host.parse::<Ipv4Addr>() { let addr = SocketAddrV4::new(addr, port); return Some(IpAddrs { iter: vec![SocketAddr::V4(addr)].into_iter() }) diff --git a/src/client/connect/dns.rs b/src/client/connect/dns.rs --- a/src/client/connect/dns.rs +++ b/src/client/connect/dns.rs @@ -51,7 +189,7 @@ impl IpAddrs { None } - pub fn split_by_preference(self) -> (IpAddrs, IpAddrs) { + pub(super) fn split_by_preference(self) -> (IpAddrs, IpAddrs) { let preferring_v6 = self.iter .as_slice() .first() diff --git a/src/client/connect/dns.rs b/src/client/connect/dns.rs --- a/src/client/connect/dns.rs +++ b/src/client/connect/dns.rs @@ -64,7 +202,7 @@ impl IpAddrs { (IpAddrs::new(preferred), IpAddrs::new(fallback)) } - pub fn is_empty(&self) -> bool { + pub(super) fn is_empty(&self) -> bool { self.iter.as_slice().is_empty() } } diff --git a/src/client/connect/http.rs b/src/client/connect/http.rs --- a/src/client/connect/http.rs +++ b/src/client/connect/http.rs @@ -4,22 +4,18 @@ use std::error::Error as StdError; use std::io; use std::mem; use std::net::{IpAddr, SocketAddr}; -use std::sync::Arc; use std::time::{Duration, Instant}; use futures::{Async, Future, Poll}; -use futures::future::{Executor, ExecuteError}; -use futures::sync::oneshot; -use futures_cpupool::{Builder as CpuPoolBuilder}; +use futures::future::{Executor}; use http::uri::Scheme; use net2::TcpBuilder; use tokio_reactor::Handle; use tokio_tcp::{TcpStream, ConnectFuture}; use tokio_timer::Delay; -use super::{dns, Connect, Connected, Destination}; - -use self::sealed::HttpConnectorBlockingTask; +use super::{Connect, Connected, Destination}; +use super::dns::{self, GaiResolver, Resolve}; /// A connector for the `http` scheme. /// diff --git a/src/client/connect/http.rs b/src/client/connect/http.rs --- a/src/client/connect/http.rs +++ b/src/client/connect/http.rs @@ -30,14 +26,14 @@ use self::sealed::HttpConnectorBlockingTask; /// Sets the [`HttpInfo`](HttpInfo) value on responses, which includes /// transport information such as the remote socket address used. #[derive(Clone)] -pub struct HttpConnector { - executor: HttpConnectExecutor, +pub struct HttpConnector<R = GaiResolver> { enforce_http: bool, handle: Option<Handle>, + happy_eyeballs_timeout: Option<Duration>, keep_alive_timeout: Option<Duration>, - nodelay: bool, local_address: Option<IpAddr>, - happy_eyeballs_timeout: Option<Duration>, + nodelay: bool, + resolver: R, reuse_address: bool, } diff --git a/src/client/connect/http.rs b/src/client/connect/http.rs --- a/src/client/connect/http.rs +++ b/src/client/connect/http.rs @@ -78,36 +74,45 @@ impl HttpConnector { /// Takes number of DNS worker threads. #[inline] pub fn new(threads: usize) -> HttpConnector { - HttpConnector::new_with_handle_opt(threads, None) + HttpConnector::new_with_resolver(GaiResolver::new(threads)) } - /// Construct a new HttpConnector with a specific Tokio handle. + #[doc(hidden)] + #[deprecated(note = "Use HttpConnector::set_reactor to set a reactor handle")] pub fn new_with_handle(threads: usize, handle: Handle) -> HttpConnector { - HttpConnector::new_with_handle_opt(threads, Some(handle)) - } - - fn new_with_handle_opt(threads: usize, handle: Option<Handle>) -> HttpConnector { - let pool = CpuPoolBuilder::new() - .name_prefix("hyper-dns") - .pool_size(threads) - .create(); - HttpConnector::new_with_executor(pool, handle) + let resolver = GaiResolver::new(threads); + let mut http = HttpConnector::new_with_resolver(resolver); + http.set_reactor(Some(handle)); + http } /// Construct a new HttpConnector. /// - /// Takes an executor to run blocking tasks on. + /// Takes an executor to run blocking `getaddrinfo` tasks on. pub fn new_with_executor<E: 'static>(executor: E, handle: Option<Handle>) -> HttpConnector - where E: Executor<HttpConnectorBlockingTask> + Send + Sync + where E: Executor<dns::sealed::GaiTask> + Send + Sync { + let resolver = GaiResolver::new_with_executor(executor); + let mut http = HttpConnector::new_with_resolver(resolver); + http.set_reactor(handle); + http + } +} + + +impl<R> HttpConnector<R> { + /// Construct a new HttpConnector. + /// + /// Takes a `Resolve` to handle DNS lookups. + pub fn new_with_resolver(resolver: R) -> HttpConnector<R> { HttpConnector { - executor: HttpConnectExecutor(Arc::new(executor)), enforce_http: true, - handle, + handle: None, + happy_eyeballs_timeout: Some(Duration::from_millis(300)), keep_alive_timeout: None, - nodelay: false, local_address: None, - happy_eyeballs_timeout: Some(Duration::from_millis(300)), + nodelay: false, + resolver, reuse_address: false, } } diff --git a/src/client/connect/http.rs b/src/client/connect/http.rs --- a/src/client/connect/http.rs +++ b/src/client/connect/http.rs @@ -120,6 +125,14 @@ impl HttpConnector { self.enforce_http = is_enforced; } + /// Set a handle to a `Reactor` to register connections to. + /// + /// If `None`, the implicit default reactor will be used. + #[inline] + pub fn set_reactor(&mut self, handle: Option<Handle>) { + self.handle = handle; + } + /// Set that all sockets have `SO_KEEPALIVE` set with the supplied duration. /// /// If `None`, the option will not be set. diff --git a/src/client/connect/http.rs b/src/client/connect/http.rs --- a/src/client/connect/http.rs +++ b/src/client/connect/http.rs @@ -175,17 +188,22 @@ impl HttpConnector { } } -impl fmt::Debug for HttpConnector { +// R: Debug required for now to allow adding it to debug output later... +impl<R: fmt::Debug> fmt::Debug for HttpConnector<R> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("HttpConnector") .finish() } } -impl Connect for HttpConnector { +impl<R> Connect for HttpConnector<R> +where + R: Resolve + Clone + Send + Sync, + R::Future: Send, +{ type Transport = TcpStream; type Error = io::Error; - type Future = HttpConnecting; + type Future = HttpConnecting<R>; fn connect(&self, dst: Destination) -> Self::Future { trace!( diff --git a/src/client/connect/http.rs b/src/client/connect/http.rs --- a/src/client/connect/http.rs +++ b/src/client/connect/http.rs @@ -213,11 +231,12 @@ impl Connect for HttpConnector { }; HttpConnecting { - state: State::Lazy(self.executor.clone(), host.into(), port, self.local_address), + state: State::Lazy(self.resolver.clone(), host.into(), self.local_address), handle: self.handle.clone(), + happy_eyeballs_timeout: self.happy_eyeballs_timeout, keep_alive_timeout: self.keep_alive_timeout, nodelay: self.nodelay, - happy_eyeballs_timeout: self.happy_eyeballs_timeout, + port, reuse_address: self.reuse_address, } } diff --git a/src/client/connect/http.rs b/src/client/connect/http.rs --- a/src/client/connect/http.rs +++ b/src/client/connect/http.rs @@ -231,12 +250,13 @@ impl HttpInfo { } #[inline] -fn invalid_url(err: InvalidUrl, handle: &Option<Handle>) -> HttpConnecting { +fn invalid_url<R: Resolve>(err: InvalidUrl, handle: &Option<Handle>) -> HttpConnecting<R> { HttpConnecting { state: State::Error(Some(io::Error::new(io::ErrorKind::InvalidInput, err))), handle: handle.clone(), keep_alive_timeout: None, nodelay: false, + port: 0, happy_eyeballs_timeout: None, reuse_address: false, } diff --git a/src/client/connect/http.rs b/src/client/connect/http.rs --- a/src/client/connect/http.rs +++ b/src/client/connect/http.rs @@ -266,23 +286,24 @@ impl StdError for InvalidUrl { } /// A Future representing work to connect to a URL. #[must_use = "futures do nothing unless polled"] -pub struct HttpConnecting { - state: State, +pub struct HttpConnecting<R: Resolve = GaiResolver> { + state: State<R>, handle: Option<Handle>, + happy_eyeballs_timeout: Option<Duration>, keep_alive_timeout: Option<Duration>, nodelay: bool, - happy_eyeballs_timeout: Option<Duration>, + port: u16, reuse_address: bool, } -enum State { - Lazy(HttpConnectExecutor, String, u16, Option<IpAddr>), - Resolving(oneshot::SpawnHandle<dns::IpAddrs, io::Error>, Option<IpAddr>), +enum State<R: Resolve> { + Lazy(R, String, Option<IpAddr>), + Resolving(R::Future, Option<IpAddr>), Connecting(ConnectingTcp), Error(Option<io::Error>), } -impl Future for HttpConnecting { +impl<R: Resolve> Future for HttpConnecting<R> { type Item = (TcpStream, Connected); type Error = io::Error; diff --git a/src/client/connect/http.rs b/src/client/connect/http.rs --- a/src/client/connect/http.rs +++ b/src/client/connect/http.rs @@ -290,22 +311,26 @@ impl Future for HttpConnecting { loop { let state; match self.state { - State::Lazy(ref executor, ref mut host, port, local_addr) => { + State::Lazy(ref resolver, ref mut host, local_addr) => { // If the host is already an IP addr (v4 or v6), // skip resolving the dns and start connecting right away. - if let Some(addrs) = dns::IpAddrs::try_parse(host, port) { + if let Some(addrs) = dns::IpAddrs::try_parse(host, self.port) { state = State::Connecting(ConnectingTcp::new( local_addr, addrs, self.happy_eyeballs_timeout, self.reuse_address)); } else { - let host = mem::replace(host, String::new()); - let work = dns::Work::new(host, port); - state = State::Resolving(oneshot::spawn(work, executor), local_addr); + let name = dns::Name::new(mem::replace(host, String::new())); + state = State::Resolving(resolver.resolve(name), local_addr); } }, State::Resolving(ref mut future, local_addr) => { match try!(future.poll()) { Async::NotReady => return Ok(Async::NotReady), Async::Ready(addrs) => { + let port = self.port; + let addrs = addrs + .map(|addr| SocketAddr::new(addr, port)) + .collect(); + let addrs = dns::IpAddrs::new(addrs); state = State::Connecting(ConnectingTcp::new( local_addr, addrs, self.happy_eyeballs_timeout, self.reuse_address)); } diff --git a/src/client/connect/http.rs b/src/client/connect/http.rs --- a/src/client/connect/http.rs +++ b/src/client/connect/http.rs @@ -335,7 +360,7 @@ impl Future for HttpConnecting { } } -impl fmt::Debug for HttpConnecting { +impl<R: Resolve + fmt::Debug> fmt::Debug for HttpConnecting<R> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad("HttpConnecting") } diff --git a/src/client/connect/mod.rs b/src/client/connect/mod.rs --- a/src/client/connect/mod.rs +++ b/src/client/connect/mod.rs @@ -15,6 +15,7 @@ use tokio_io::{AsyncRead, AsyncWrite}; #[cfg(feature = "runtime")] mod dns; #[cfg(feature = "runtime")] mod http; +#[cfg(feature = "runtime")] pub use self::dns::{GaiResolver, Name, Resolve}; #[cfg(feature = "runtime")] pub use self::http::{HttpConnector, HttpInfo}; /// Connect to a destination, returning an IO transport.
diff --git a/src/client/connect/dns.rs b/src/client/connect/dns.rs --- a/src/client/connect/dns.rs +++ b/src/client/connect/dns.rs @@ -77,6 +215,30 @@ impl Iterator for IpAddrs { } } +// Make this Future unnameable outside of this crate. +pub(super) mod sealed { + use super::*; + // Blocking task to be executed on a thread pool. + pub struct GaiTask { + pub(super) work: oneshot::Execute<GaiBlocking> + } + + impl fmt::Debug for GaiTask { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad("GaiTask") + } + } + + impl Future for GaiTask { + type Item = (); + type Error = (); + + fn poll(&mut self) -> Poll<(), ()> { + self.work.poll() + } + } +} + #[cfg(test)] mod tests { use std::net::{Ipv4Addr, Ipv6Addr}; diff --git a/src/client/connect/http.rs b/src/client/connect/http.rs --- a/src/client/connect/http.rs +++ b/src/client/connect/http.rs @@ -522,40 +547,6 @@ impl ConnectingTcp { } } -// Make this Future unnameable outside of this crate. -mod sealed { - use super::*; - // Blocking task to be executed on a thread pool. - pub struct HttpConnectorBlockingTask { - pub(super) work: oneshot::Execute<dns::Work> - } - - impl fmt::Debug for HttpConnectorBlockingTask { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad("HttpConnectorBlockingTask") - } - } - - impl Future for HttpConnectorBlockingTask { - type Item = (); - type Error = (); - - fn poll(&mut self) -> Poll<(), ()> { - self.work.poll() - } - } -} - -#[derive(Clone)] -struct HttpConnectExecutor(Arc<Executor<HttpConnectorBlockingTask> + Send + Sync>); - -impl Executor<oneshot::Execute<dns::Work>> for HttpConnectExecutor { - fn execute(&self, future: oneshot::Execute<dns::Work>) -> Result<(), ExecuteError<oneshot::Execute<dns::Work>>> { - self.0.execute(HttpConnectorBlockingTask { work: future }) - .map_err(|err| ExecuteError::new(err.kind(), err.into_future().work)) - } -} - #[cfg(test)] mod tests { use std::io; diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -17,7 +17,6 @@ use hyper::{Body, Client, Method, Request, StatusCode}; use futures::{Future, Stream}; use futures::sync::oneshot; -use tokio::reactor::Handle; use tokio::runtime::current_thread::Runtime; use tokio::net::tcp::{ConnectFuture, TcpStream}; diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -226,7 +225,7 @@ macro_rules! test { let addr = server.local_addr().expect("local_addr"); let mut rt = $runtime; - let connector = ::hyper::client::HttpConnector::new_with_handle(1, Handle::default()); + let connector = ::hyper::client::HttpConnector::new(1); let client = Client::builder() .set_host($set_host) .http1_title_case_headers($title_case_headers)
Substitute DNS Resolver This relates to #1174. It would be great if we could substitute a resolver instead of using `to_socket_addrs` and `getaddrinfo`. It seems there was already a good amount of discussion around this in #1174, but I'm not sure what the conclusion was. It seems like there are three options: 1. Implement custom connector with `Connect` instead of HttpConnector 2. Add resolver type to HttpConnector (#1174) 3. Modifying tokio's `ClientProto`(?). I admit I'm not sure what this actually means for end-users. Honestly I think 2) makes a lot of sense because we get to avoid any duplication and maintenance efforts to keep a custom connector up-to-date / bug-free with HttpConnector. But again, I'm not sure if 3) is better? Context for this is: we're trying to update from an old fork of hyper and had previously swapped out the resolver in the fork :). @seanmonstar thoughts?
The `ClientProto` stuff is long gone, nothing to worry about there :) I've seen others ask to replace the resolve in `HttpConnector` also, and it would be nice to be do so. The *only* thing that has held me back is that it would be another trait to need to stabilize. I don't have a good design for one, and haven't spent time trying to solve this, since so far I've figured that just copying the TCP connecting bits from the `HttpConnector` is pretty simple. I'd be open to working this out, though! I'd follow this issue and maybe even help: https://github.com/tokio-rs/tokio/issues/363 Would be pretty nice to just use Tokio's DNS resolver in Hyper when it's ready. There are some unofficial crates to use in your custom connector that should not be that hard to add to your stack, e.g: https://github.com/sbstp/tokio-dns Ah okay great, forget about the `ClientProto` stuff then. I think thinking about a stable trait design is a fair point and might be more involved than I expected given the wide range of use-cases `hyper` needs to support. However, if a trait-bound on `HttpConnector` is the goal, then the only logic we can replace is here, right? ```rust let work = dns::Work::new(host, port); state = State::Resolving(oneshot::spawn(work, executor)); ``` The input on some hypothetical resolve function would be: `fn resolve(host: String, port: u16)` as per `dns::Work::new()` and it would return a `Future<Item=Iterator<Item=SocketAddr>, Error=io::Error>` (This is the same trait structure as #1174). Okay, but maybe that's not the end goal, what other possible use cases might be brought up? * Return results synchronously instead of a Future * This would be a strange use-case for `hyper` as "async I/O" is a point in the main page, is it fair to call this one a "write a custom HttpConnector"? * Take in more context than `host: String` and `port: u16` * Looking at several different DNS crates ([trust-dns](https://github.com/bluejekyll/trust-dns), [abstract-ns](https://docs.rs/abstract-ns/0.4.3/abstract_ns/trait.Resolve.html)) as well as the standard [ToSocketAddrs trait](https://doc.rust-lang.org/std/net/trait.ToSocketAddrs.html), this set of arguments seems reasonable and standard. Maybe instead of String it could take an [IpAddr](https://doc.rust-lang.org/std/net/enum.IpAddr.html)? * Using a trait provided by another crate (like abstract-ns as discussed in #1174) * This would be a good point, I could see some sort of `ToSocketAddrsFuture` trait that's implemented and shared amongst crates so there's no need for new types to bridge implementations. Let me know if I'm missing anything, or if you're worried about any other use-cases! The only thing I can see is possibly supporting a generic `ToSocketAddrsFuture` (or something) trait with other crates, which would include research into what crates are used, what should be on a generic trait, etc. It expands the scope from a trait for `HttpConnector` to a trait of any DNS resolver to plug into, which is quite a leap. Anyways I think an initial step is for me to duplicate the HttpConnector and add in DNS substitution. That way I can continue without being blocked and if supporting a larger scope is required it can be prototyped outside of Hyper without requiring releases for the crate as a whole. If no larger scope is required though, it would be good to get the trait bound merged in! > Maybe instead of String it could take an IpAddr? If we already had an `IpAddr`, we wouldn't need to do resolution, right? :D In fact, hyper does skip resolution if the hostname parses as an `IpAddr`. I think it'd be reasonable to try to include a `Resolve` trait specifically for `HttpConnector`. What does it look like? Should it only be allowed to return `io::Error`, or should it allow any error, like `Connect` does? ```rust trait Resolve { type Future: Future<Item=Self::Addrs, Error=io::Error>; type Addrs: Iterator<Item=SocketAddr>; fn resolve(&self, host: &str, port: u16) -> Self::Future; } ``` Does it make sense to include a port as input? Or should the `HttpConnect` just override the any port when it receives the `SocketAddr`? Didn't see your reply @pimeys, thanks for the links! I'll definitely keep an eye on tokio-dns, and would be happy to wait for it if that's the right solution. @seanmonstar: Ah, yeah oops, that would not be necessary :P. Does `Connect` allow users to define any error? From the code it looks to have some sort of bound on `io:Error` like the proposed trait, although you could just create `io::Error` from your Error. Ah, okay, I'm looking at the 0.11 branch, on `master` branch it does allow any error. Given that `HttpConnector` is an implementation of `Connect` and defines its error type as `io::Error` it would make sense to me to have the `Resolve` trait (bounded on `HttpConnector`) as `io::Error` as well. Good point with the port: * Looking at `trust-dns`, the implementation for [lookup_ip](https://docs.rs/trust-dns-resolver/0.8.2/trust_dns_resolver/struct.ResolverFuture.html#method.lookup_ip) does not take in a port and returns `IpAddr`s * `tokio-dns::Resolver`only operates on the host and returns `IpAddr`s as well. * [abstract_ns::Resolve](https://docs.rs/abstract-ns/0.4.3/abstract_ns/trait.Resolve.html) operates on only a string as well, it returns `SocketAddr`s though. Given the API for these crates, I would lean towards avoiding passing in the port and have the future return `Iterator<Item=IpAddr>` and constructing the `SocketAddr`s from the `IpAddr`s and port. ```rust trait Resolve { type Future: Future<Item=Self::Addrs, Error=io::Error>; type Addrs: Iterator<Item=IpAddr>; fn resolve(&self, host: &str) -> Self::Future; } ``` Let me know what you think! As an update on this, I've created a duplicate of `hyper 0.11`'s `HttpConnector` and have swapped out the DNS resolver on a branch to use `trust-dns` and `c-ares` (after running into some internal `trust-dns` issues (https://github.com/bluejekyll/trust-dns/issues/470)). Both implementations would match the latest proposed trait without any problems :+1:. Great! How does the generic on `HttpConnector` play out in practice? Annoying? Ignorable? I've wanted to be able to change out the default resolver for trust-dns for a while, and besides wanting to wait for it to be as reliable as `getaddrinfo`, the other problem is some of the constructors for `HttpConnector` would break. This change could actually make the switch compatible. Basically, it could be similar to `HashMap` that has a default hasher that doesn't otherwise expose what it is, which allowed switching from SipHash-2-4 to 1-3. There could be a `DefaultResolver` newtype that hides its details, besides a GAI resolver type. I'll be of limited availability for the next week, but I'd welcome this change for the 0.12 release if someone would like to make a PR! This may slip out of 0.12, as it isn't high on my priorities, and I'd like to release this week. Oh, sorry for ignoring this thread! Happy to contribute a PR once we're satisfied with the code, we're still on 0.11 so it would require some changes to work with 0.12.
2018-10-17T23:07:16Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,662
hyperium__hyper-1662
[ "1661" ]
0cfa7231b2483715e3bd886a059e2792c090e635
diff --git a/src/client/connect/mod.rs b/src/client/connect/mod.rs --- a/src/client/connect/mod.rs +++ b/src/client/connect/mod.rs @@ -8,7 +8,7 @@ use std::error::Error as StdError; use std::mem; -use bytes::{BufMut, BytesMut}; +use bytes::{BufMut, Bytes, BytesMut}; use futures::Future; use http::{uri, Uri}; use tokio_io::{AsyncRead, AsyncWrite}; diff --git a/src/client/connect/mod.rs b/src/client/connect/mod.rs --- a/src/client/connect/mod.rs +++ b/src/client/connect/mod.rs @@ -131,13 +131,20 @@ impl Destination { /// /// Returns an error if the string is not a valid hostname. pub fn set_host(&mut self, host: &str) -> ::Result<()> { - if host.contains(&['@',':'][..]) { + // Prevent any userinfo setting, it's bad! + if host.contains('@') { return Err(::error::Parse::Uri.into()); } let auth = if let Some(port) = self.port() { - format!("{}:{}", host, port).parse().map_err(::error::Parse::from)? + let bytes = Bytes::from(format!("{}:{}", host, port)); + uri::Authority::from_shared(bytes) + .map_err(::error::Parse::from)? } else { - host.parse().map_err(::error::Parse::from)? + let auth = host.parse::<uri::Authority>().map_err(::error::Parse::from)?; + if auth.port().is_some() { + return Err(::error::Parse::Uri.into()); + } + auth }; self.update_uri(move |parts| { parts.authority = Some(auth); diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -371,6 +371,12 @@ impl From<http::uri::InvalidUri> for Parse { } } +impl From<http::uri::InvalidUriBytes> for Parse { + fn from(_: http::uri::InvalidUriBytes) -> Parse { + Parse::Uri + } +} + impl From<http::uri::InvalidUriParts> for Parse { fn from(_: http::uri::InvalidUriParts) -> Parse { Parse::Uri
diff --git a/src/client/connect/mod.rs b/src/client/connect/mod.rs --- a/src/client/connect/mod.rs +++ b/src/client/connect/mod.rs @@ -305,6 +312,30 @@ mod tests { assert_eq!(dst.host(), "seanmonstar.com", "error doesn't modify dst"); assert_eq!(dst.port(), None, "error doesn't modify dst"); + // Check port isn't snuck into `set_host`. + dst.set_host("seanmonstar.com:3030").expect_err("set_host sneaky port"); + assert_eq!(dst.scheme(), "http", "error doesn't modify dst"); + assert_eq!(dst.host(), "seanmonstar.com", "error doesn't modify dst"); + assert_eq!(dst.port(), None, "error doesn't modify dst"); + + // Check userinfo isn't snuck into `set_host`. + dst.set_host("sean@nope").expect_err("set_host sneaky userinfo"); + assert_eq!(dst.scheme(), "http", "error doesn't modify dst"); + assert_eq!(dst.host(), "seanmonstar.com", "error doesn't modify dst"); + assert_eq!(dst.port(), None, "error doesn't modify dst"); + + // Allow IPv6 hosts + dst.set_host("[::1]").expect("set_host with IPv6"); + assert_eq!(dst.host(), "::1"); + assert_eq!(dst.port(), None, "IPv6 didn't affect port"); + + // However, IPv6 with a port is rejected. + dst.set_host("[::2]:1337").expect_err("set_host with IPv6 and sneaky port"); + assert_eq!(dst.host(), "::1"); + assert_eq!(dst.port(), None); + + // ----------------- + // Also test that an exist port is set correctly. let mut dst = Destination { uri: "http://hyper.rs:8080".parse().expect("initial parse 2"), diff --git a/src/client/connect/mod.rs b/src/client/connect/mod.rs --- a/src/client/connect/mod.rs +++ b/src/client/connect/mod.rs @@ -335,6 +366,16 @@ mod tests { assert_eq!(dst.scheme(), "http", "error doesn't modify dst"); assert_eq!(dst.host(), "seanmonstar.com", "error doesn't modify dst"); assert_eq!(dst.port(), Some(8080), "error doesn't modify dst"); + + // Allow IPv6 hosts + dst.set_host("[::1]").expect("set_host with IPv6"); + assert_eq!(dst.host(), "::1"); + assert_eq!(dst.port(), Some(8080), "IPv6 didn't affect port"); + + // However, IPv6 with a port is rejected. + dst.set_host("[::2]:1337").expect_err("set_host with IPv6 and sneaky port"); + assert_eq!(dst.host(), "::1"); + assert_eq!(dst.port(), Some(8080)); } #[test]
Calling Destination::set_host with an IPv6 string errors
2018-09-27T22:16:59Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,643
hyperium__hyper-1643
[ "1642" ]
168c7d2155952ba09f781c331fd67593b820af20
diff --git a/src/proto/h2/client.rs b/src/proto/h2/client.rs --- a/src/proto/h2/client.rs +++ b/src/proto/h2/client.rs @@ -108,7 +108,7 @@ where } let (head, body) = req.into_parts(); let mut req = ::http::Request::from_parts(head, ()); - super::strip_connection_headers(req.headers_mut()); + super::strip_connection_headers(req.headers_mut(), true); if let Some(len) = body.content_length() { headers::set_content_length_if_missing(req.headers_mut(), len); } diff --git a/src/proto/h2/mod.rs b/src/proto/h2/mod.rs --- a/src/proto/h2/mod.rs +++ b/src/proto/h2/mod.rs @@ -35,6 +37,17 @@ fn strip_connection_headers(headers: &mut HeaderMap) { } } + if is_request { + if headers.get(TE).map(|te_header| te_header != "trailers").unwrap_or(false) { + warn!("TE headers not set to \"trailers\" are illegal in HTTP/2 requests"); + headers.remove(TE); + } + } else { + if headers.remove(TE).is_some() { + warn!("TE headers illegal in HTTP/2 responses"); + } + } + if let Some(header) = headers.remove(CONNECTION) { warn!( "Connection header illegal in HTTP/2: {}", diff --git a/src/proto/h2/server.rs b/src/proto/h2/server.rs --- a/src/proto/h2/server.rs +++ b/src/proto/h2/server.rs @@ -192,7 +192,7 @@ where let (head, body) = res.into_parts(); let mut res = ::http::Response::from_parts(head, ()); - super::strip_connection_headers(res.headers_mut()); + super::strip_connection_headers(res.headers_mut(), false); if let Some(len) = body.content_length() { headers::set_content_length_if_missing(res.headers_mut(), len); }
diff --git a/src/proto/h2/mod.rs b/src/proto/h2/mod.rs --- a/src/proto/h2/mod.rs +++ b/src/proto/h2/mod.rs @@ -15,15 +15,17 @@ mod server; pub(crate) use self::client::Client; pub(crate) use self::server::Server; -fn strip_connection_headers(headers: &mut HeaderMap) { +fn strip_connection_headers(headers: &mut HeaderMap, is_request: bool) { // List of connection headers from: // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Connection + // + // TE headers are allowed in HTTP/2 requests as long as the value is "trailers", so they're + // tested separately. let connection_headers = [ HeaderName::from_lowercase(b"keep-alive").unwrap(), HeaderName::from_lowercase(b"proxy-connection").unwrap(), PROXY_AUTHENTICATE, PROXY_AUTHORIZATION, - TE, TRAILER, TRANSFER_ENCODING, UPGRADE, diff --git a/tests/integration.rs b/tests/integration.rs --- a/tests/integration.rs +++ b/tests/integration.rs @@ -184,6 +184,30 @@ t! { ; } +t! { + get_allow_te_trailers_header, + client: + request: + uri: "/", + headers: { + // http2 strips connection headers other than TE "trailers" + "te" => "trailers", + }, + ; + response: + status: 200, + ; + server: + request: + uri: "/", + headers: { + "te" => "trailers", + }, + ; + response: + ; +} + t! { get_body_chunked, client:
TE "trailers" header incorrectly stripped from HTTP/2 requests According to the HTTP/2 spec (https://http2.github.io/http2-spec/#rfc.section.8.1.2.2), connection-specific headers are not supposed to be in HTTP/2 messages, but a TE header is allowed for request messages as long as it only contains the value "trailers". `hyper` currently strips all connection-specific headers, including TE, regardless of whether the header is a TE "trailers" header belonging to an HTTP/2 request.
Yep, looks like hyper is being too eager here.
2018-08-25T07:58:17Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,641
hyperium__hyper-1641
[ "1639" ]
1448e4067b10da6fe4584921314afc1f5f4e3c8d
diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -753,8 +753,7 @@ pub struct Builder { keep_alive_timeout: Option<Duration>, h1_writev: bool, h1_title_case_headers: bool, - //TODO: make use of max_idle config - max_idle: usize, + max_idle_per_host: usize, retry_canceled_requests: bool, set_host: bool, ver: Ver, diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -768,7 +767,7 @@ impl Default for Builder { keep_alive_timeout: Some(Duration::from_secs(90)), h1_writev: true, h1_title_case_headers: false, - max_idle: 5, + max_idle_per_host: ::std::usize::MAX, retry_canceled_requests: true, set_host: true, ver: Ver::Http1, diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -839,6 +838,14 @@ impl Builder { self } + /// Sets the maximum idle connection per host allowed in the pool. + /// + /// Default is `usize::MAX` (no limit). + pub fn max_idle_per_host(&mut self, max_idle: usize) -> &mut Self { + self.max_idle_per_host = max_idle; + self + } + /// Set whether to retry requests that get disrupted before ever starting /// to write. /// diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -905,7 +912,12 @@ impl Builder { executor: self.exec.clone(), h1_writev: self.h1_writev, h1_title_case_headers: self.h1_title_case_headers, - pool: Pool::new(self.keep_alive, self.keep_alive_timeout, &self.exec), + pool: Pool::new( + pool::Enabled(self.keep_alive), + pool::IdleTimeout(self.keep_alive_timeout), + pool::MaxIdlePerHost(self.max_idle_per_host), + &self.exec, + ), retry_canceled_requests: self.retry_canceled_requests, set_host: self.set_host, ver: self.ver, diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -919,7 +931,7 @@ impl fmt::Debug for Builder { .field("keep_alive", &self.keep_alive) .field("keep_alive_timeout", &self.keep_alive_timeout) .field("http1_writev", &self.h1_writev) - .field("max_idle", &self.max_idle) + .field("max_idle_per_host", &self.max_idle_per_host) .field("set_host", &self.set_host) .field("version", &self.ver) .finish() diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -60,6 +60,7 @@ struct Connections<T> { // These are internal Conns sitting in the event loop in the KeepAlive // state, waiting to receive a new Request to send on the socket. idle: HashMap<Key, Vec<Idle<T>>>, + max_idle_per_host: usize, // These are outstanding Checkouts that are waiting for a socket to be // able to send a Request one. This is used when "racing" for a new // connection. diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -83,8 +84,13 @@ struct Connections<T> { // doesn't need it! struct WeakOpt<T>(Option<Weak<T>>); +// Newtypes to act as keyword arguments for `Pool::new`... +pub(super) struct Enabled(pub(super) bool); +pub(super) struct IdleTimeout(pub(super) Option<Duration>); +pub(super) struct MaxIdlePerHost(pub(super) usize); + impl<T> Pool<T> { - pub fn new(enabled: bool, timeout: Option<Duration>, __exec: &Exec) -> Pool<T> { + pub fn new(enabled: Enabled, timeout: IdleTimeout, max_idle: MaxIdlePerHost, __exec: &Exec) -> Pool<T> { Pool { inner: Arc::new(PoolInner { connections: Mutex::new(Connections { diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -92,12 +98,13 @@ impl<T> Pool<T> { idle: HashMap::new(), #[cfg(feature = "runtime")] idle_interval_ref: None, + max_idle_per_host: max_idle.0, waiters: HashMap::new(), #[cfg(feature = "runtime")] exec: __exec.clone(), - timeout, + timeout: timeout.0, }), - enabled, + enabled: enabled.0, }), } } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -376,13 +383,23 @@ impl<T: Poolable> Connections<T> { match value { Some(value) => { - debug!("pooling idle connection for {:?}", key); - self.idle.entry(key) - .or_insert(Vec::new()) - .push(Idle { - value: value, - idle_at: Instant::now(), - }); + // borrow-check scope... + { + let idle_list = self + .idle + .entry(key.clone()) + .or_insert(Vec::new()); + if self.max_idle_per_host <= idle_list.len() { + trace!("max idle per host for {:?}, dropping connection", key); + return; + } + + debug!("pooling idle connection for {:?}", key); + idle_list.push(Idle { + value: value, + idle_at: Instant::now(), + }); + } #[cfg(feature = "runtime")] {
diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -773,7 +790,16 @@ mod tests { } fn pool_no_timer<T>() -> Pool<T> { - let pool = Pool::new(true, Some(Duration::from_millis(100)), &Exec::Default); + pool_max_idle_no_timer(::std::usize::MAX) + } + + fn pool_max_idle_no_timer<T>(max_idle: usize) -> Pool<T> { + let pool = Pool::new( + super::Enabled(true), + super::IdleTimeout(Some(Duration::from_millis(100))), + super::MaxIdlePerHost(max_idle), + &Exec::Default, + ); pool.no_timer(); pool } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -826,13 +852,35 @@ mod tests { }).wait().unwrap(); } + #[test] + fn test_pool_max_idle_per_host() { + future::lazy(|| { + let pool = pool_max_idle_no_timer(2); + let key = (Arc::new("foo".to_string()), Ver::Http1); + + pool.pooled(c(key.clone()), Uniq(41)); + pool.pooled(c(key.clone()), Uniq(5)); + pool.pooled(c(key.clone()), Uniq(99)); + + // pooled and dropped 3, max_idle should only allow 2 + assert_eq!(pool.inner.connections.lock().unwrap().idle.get(&key).map(|entries| entries.len()), Some(2)); + + Ok::<(), ()>(()) + }).wait().unwrap(); + } + #[cfg(feature = "runtime")] #[test] fn test_pool_timer_removes_expired() { use std::time::Instant; use tokio_timer::Delay; let mut rt = ::tokio::runtime::current_thread::Runtime::new().unwrap(); - let pool = Pool::new(true, Some(Duration::from_millis(100)), &Exec::Default); + let pool = Pool::new( + super::Enabled(true), + super::IdleTimeout(Some(Duration::from_millis(100))), + super::MaxIdlePerHost(::std::usize::MAX), + &Exec::Default, + ); let key = (Arc::new("foo".to_string()), Ver::Http1);
Enable max idle Client Pool option There is currently a `max_idle` option for the `Client` connection pool, that claims it is the maximum number of idle connections that will be kept per host, but it's a lie. That config is currently ignored. It should be plugged into the pool so that each time a connection is ready to be idle, it should check there aren't already `max_idle` idle connections for that pool key. It currently claims a default of 5, but I assume suddenly turning it on could hurt throughput for people who weren't expecting it...
2018-08-21T23:06:58Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,596
hyperium__hyper-1596
[ "1595" ]
396e6022e02bdbcabced5235528cb61bee29e3b7
diff --git a/examples/client_json.rs b/examples/client_json.rs --- a/examples/client_json.rs +++ b/examples/client_json.rs @@ -11,14 +11,32 @@ use hyper::rt::{self, Future, Stream}; fn main() { let url = "http://jsonplaceholder.typicode.com/users".parse().unwrap(); + let fut = fetch_json(url) + // use the parsed vector + .map(|users| { + // print users + println!("users: {:#?}", users); + + // print the sum of ids + let sum = users.iter().fold(0, |acc, user| acc + user.id); + println!("sum of ids: {}", sum); + }) + // if there was an error print it + .map_err(|e| { + match e { + FetchError::Http(e) => eprintln!("http error: {}", e), + FetchError::Json(e) => eprintln!("json parsing error: {}", e), + } + }); + // Run the runtime with the future trying to fetch, parse and print json. // // Note that in more complicated use cases, the runtime should probably // run on its own, and futures should just be spawned into it. - rt::run(fetch_json(url)); + rt::run(fut); } -fn fetch_json(url: hyper::Uri) -> impl Future<Item=(), Error=()> { +fn fetch_json(url: hyper::Uri) -> impl Future<Item=Vec<User>, Error=FetchError> { let client = Client::new(); client diff --git a/examples/client_json.rs b/examples/client_json.rs --- a/examples/client_json.rs +++ b/examples/client_json.rs @@ -29,22 +47,37 @@ fn fetch_json(url: hyper::Uri) -> impl Future<Item=(), Error=()> { // asynchronously concatenate chunks of the body res.into_body().concat2() }) + .from_err::<FetchError>() // use the body after concatenation - .map(|body| { + .and_then(|body| { // try to parse as json with serde_json - let users: Vec<User> = serde_json::from_slice(&body).expect("parse json"); + let users = serde_json::from_slice(&body)?; - // pretty print result - println!("{:#?}", users); - }) - // If there was an error, let the user know... - .map_err(|err| { - eprintln!("Error {}", err); + Ok(users) }) + .from_err() } #[derive(Deserialize, Debug)] struct User { id: i32, name: String, +} + +// Define a type so we can return multile types of errors +enum FetchError { + Http(hyper::Error), + Json(serde_json::Error), +} + +impl From<hyper::Error> for FetchError { + fn from(err: hyper::Error) -> FetchError { + FetchError::Http(err) + } +} + +impl From<serde_json::Error> for FetchError { + fn from(err: serde_json::Error) -> FetchError { + FetchError::Json(err) + } } \ No newline at end of file diff --git a/examples/web_api.rs b/examples/web_api.rs --- a/examples/web_api.rs +++ b/examples/web_api.rs @@ -2,10 +2,11 @@ extern crate futures; extern crate hyper; extern crate pretty_env_logger; +extern crate serde_json; use futures::{future, Future, Stream}; -use hyper::{Body, Chunk, Client, Method, Request, Response, Server, StatusCode}; +use hyper::{Body, Chunk, Client, Method, Request, Response, Server, StatusCode, header}; use hyper::client::HttpConnector; use hyper::service::service_fn;
diff --git a/examples/web_api.rs b/examples/web_api.rs --- a/examples/web_api.rs +++ b/examples/web_api.rs @@ -27,32 +28,65 @@ fn response_examples(req: Request<Body>, client: &Client<HttpConnector>) }, (&Method::GET, "/test.html") => { // Run a web query against the web api below + + // build the request let req = Request::builder() .method(Method::POST) .uri(URL) .body(LOWERCASE.into()) .unwrap(); + // use the request with client let web_res_future = client.request(req); Box::new(web_res_future.map(|web_res| { + // return the response that came from the web api and the original text together + // to show the difference let body = Body::wrap_stream(web_res.into_body().map(|b| { - Chunk::from(format!("before: '{:?}'<br>after: '{:?}'", + Chunk::from(format!("<b>before</b>: {}<br><b>after</b>: {}", std::str::from_utf8(LOWERCASE).unwrap(), std::str::from_utf8(&b).unwrap())) })); + Response::new(body) })) }, (&Method::POST, "/web_api") => { - // A web api to run against. Simple upcasing of the body. + // A web api to run against. Uppercases the body and returns it back. let body = Body::wrap_stream(req.into_body().map(|chunk| { + // uppercase the letters let upper = chunk.iter().map(|byte| byte.to_ascii_uppercase()) .collect::<Vec<u8>>(); Chunk::from(upper) })); Box::new(future::ok(Response::new(body))) }, + (&Method::GET, "/json") => { + let data = vec!["foo", "bar"]; + let res = match serde_json::to_string(&data) { + Ok(json) => { + // return a json response + Response::builder() + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(json)) + .unwrap() + } + // This is unnecessary here because we know + // this can't fail. But if we were serializing json that came from another + // source we could handle an error like this. + Err(e) => { + eprintln!("serializing json: {}", e); + + Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from("Internal Server Error")) + .unwrap() + } + }; + + Box::new(future::ok(res)) + } _ => { + // Return 404 not found response. let body = Body::from(NOTFOUND); Box::new(future::ok(Response::builder() .status(StatusCode::NOT_FOUND)
JSON server example Would it be nice to have example for server responding with json? I think it's common use case (especially useful when API frequently change) It can be like this: (what I came up with) ```rust use futures::{future, Future}; use hyper::{self, Method, StatusCode, Request, Response, Body, Server}; use hyper::service::service_fn; use serde_json; use std::thread; fn stats_server(req: Request<Body>) -> Box<Future<Item=Response<Body>, Error=hyper::Error> + Send> { match (req.method(), req.uri().path()) { (&Method::GET, "/") => { // response content let data = vec!("foo", "bar"); let json = serde_json::to_string_pretty(&data).unwrap(); Box::new(future::ok( Response::builder() .header("Content-Type", "application/json") // ContentType::json() not there anymore .body(Body::from(json)) .unwrap() )) }, _ => { Box::new(future::ok( Response::builder() .status(StatusCode::NOT_FOUND) .body(Body::empty()) .unwrap() )) } } } pub fn start_stats_server() { thread::spawn(move || { let addr = "0.0.0.0:9000".parse().unwrap(); let server = Server::bind(&addr) .serve(|| service_fn(stats_server)) .map_err(|e| eprintln!("server error: {}", e)); hyper::rt::run(server); }); } ```
Perhaps this could be added to the web_api example that already exists? That probably could use some cleanup, and some comments explaining what each part does... But it otherwise seems like a good fit for this.
2018-07-06T15:47:17Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,594
hyperium__hyper-1594
[ "1402" ]
ced949cb6b798f25c2ffbdb3ebda6858c18393a7
diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -10,7 +10,6 @@ static PHRASE: &'static [u8] = b"Hello World!"; fn main() { pretty_env_logger::init(); - let addr = ([127, 0, 0, 1], 3000).into(); // new_service is run for each connection, creating a 'service' diff --git a/src/client/connect/http.rs b/src/client/connect/http.rs --- a/src/client/connect/http.rs +++ b/src/client/connect/http.rs @@ -24,6 +24,11 @@ use self::sealed::HttpConnectorBlockingTask; /// A connector for the `http` scheme. /// /// Performs DNS resolution in a thread pool, and then connects over TCP. +/// +/// # Note +/// +/// Sets the [`HttpInfo`](HttpInfo) value on responses, which includes +/// transport information such as the remote socket address used. #[derive(Clone)] pub struct HttpConnector { executor: HttpConnectExecutor, diff --git a/src/client/connect/http.rs b/src/client/connect/http.rs --- a/src/client/connect/http.rs +++ b/src/client/connect/http.rs @@ -36,6 +41,37 @@ pub struct HttpConnector { reuse_address: bool, } +/// Extra information about the transport when an HttpConnector is used. +/// +/// # Example +/// +/// ```rust +/// use hyper::client::{Client, connect::HttpInfo}; +/// use hyper::rt::Future; +/// +/// let client = Client::new(); +/// +/// let fut = client.get("http://example.local".parse().unwrap()) +/// .inspect(|resp| { +/// resp +/// .extensions() +/// .get::<HttpInfo>() +/// .map(|info| { +/// println!("remote addr = {}", info.remote_addr()); +/// }); +/// }); +/// ``` +/// +/// # Note +/// +/// If a different connector is used besides [`HttpConnector`](HttpConnector), +/// this value will not exist in the extensions. Consult that specific +/// connector to see what "extra" information it might provide to responses. +#[derive(Clone, Debug)] +pub struct HttpInfo { + remote_addr: SocketAddr, +} + impl HttpConnector { /// Construct a new HttpConnector. /// diff --git a/src/client/connect/http.rs b/src/client/connect/http.rs --- a/src/client/connect/http.rs +++ b/src/client/connect/http.rs @@ -187,6 +223,13 @@ impl Connect for HttpConnector { } } +impl HttpInfo { + /// Get the remote address of the transport used. + pub fn remote_addr(&self) -> SocketAddr { + self.remote_addr + } +} + #[inline] fn invalid_url(err: InvalidUrl, handle: &Option<Handle>) -> HttpConnecting { HttpConnecting { diff --git a/src/client/connect/http.rs b/src/client/connect/http.rs --- a/src/client/connect/http.rs +++ b/src/client/connect/http.rs @@ -277,7 +320,13 @@ impl Future for HttpConnecting { sock.set_nodelay(self.nodelay)?; - return Ok(Async::Ready((sock, Connected::new()))); + let extra = HttpInfo { + remote_addr: sock.peer_addr()?, + }; + let connected = Connected::new() + .extra(extra); + + return Ok(Async::Ready((sock, connected))); }, State::Error(ref mut e) => return Err(e.take().expect("polled more than once")), } diff --git a/src/client/connect/mod.rs b/src/client/connect/mod.rs --- a/src/client/connect/mod.rs +++ b/src/client/connect/mod.rs @@ -6,16 +6,16 @@ //! establishes connections over TCP. //! - The [`Connect`](Connect) trait and related types to build custom connectors. use std::error::Error as StdError; -use std::mem; +use std::{fmt, mem}; use bytes::{BufMut, Bytes, BytesMut}; use futures::Future; -use http::{uri, Uri}; +use http::{uri, Response, Uri}; use tokio_io::{AsyncRead, AsyncWrite}; #[cfg(feature = "runtime")] mod dns; #[cfg(feature = "runtime")] mod http; -#[cfg(feature = "runtime")] pub use self::http::HttpConnector; +#[cfg(feature = "runtime")] pub use self::http::{HttpConnector, HttpInfo}; /// Connect to a destination, returning an IO transport. /// diff --git a/src/client/connect/mod.rs b/src/client/connect/mod.rs --- a/src/client/connect/mod.rs +++ b/src/client/connect/mod.rs @@ -48,8 +48,11 @@ pub struct Destination { pub struct Connected { //alpn: Alpn, pub(super) is_proxied: bool, + pub(super) extra: Option<Extra>, } +pub(super) struct Extra(Box<ExtraInner>); + /*TODO: when HTTP1 Upgrades to H2 are added, this will be needed #[derive(Debug)] pub(super) enum Alpn { diff --git a/src/client/connect/mod.rs b/src/client/connect/mod.rs --- a/src/client/connect/mod.rs +++ b/src/client/connect/mod.rs @@ -245,6 +248,7 @@ impl Connected { Connected { //alpn: Alpn::Http1, is_proxied: false, + extra: None, } } diff --git a/src/client/connect/mod.rs b/src/client/connect/mod.rs --- a/src/client/connect/mod.rs +++ b/src/client/connect/mod.rs @@ -260,6 +264,12 @@ impl Connected { self } + /// Set extra connection information to be set in the extensions of every `Response`. + pub fn extra<T: Clone + Send + Sync + 'static>(mut self, extra: T) -> Connected { + self.extra = Some(Extra(Box::new(ExtraEnvelope(extra)))); + self + } + /* /// Set that the connected transport negotiated HTTP/2 as it's /// next protocol. diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -91,7 +91,7 @@ use http::uri::Scheme; use body::{Body, Payload}; use common::{Exec, lazy as hyper_lazy, Lazy}; -use self::connect::{Connect, Destination}; +use self::connect::{Connect, Connected, Destination}; use self::pool::{Key as PoolKey, Pool, Poolable, Pooled, Reservation}; #[cfg(feature = "runtime")] pub use self::connect::HttpConnector; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -290,7 +290,7 @@ where C: Connect + Sync + 'static, // CONNECT always sends origin-form, so check it first... if req.method() == &Method::CONNECT { authority_form(req.uri_mut()); - } else if pooled.is_proxied { + } else if pooled.conn_info.is_proxied { absolute_form(req.uri_mut()); } else { origin_form(req.uri_mut()); diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -305,6 +305,15 @@ where C: Connect + Sync + 'static, let fut = pooled.send_request_retryable(req) .map_err(ClientError::map_with_reused(pooled.is_reused())); + // If the Connector included 'extra' info, add to Response... + let extra_info = pooled.conn_info.extra.clone(); + let fut = fut.map(move |mut res| { + if let Some(extra) = extra_info { + extra.set(&mut res); + } + res + }); + // As of futures@0.1.21, there is a race condition in the mpsc // channel, such that sending when the receiver is closing can // result in the message being stuck inside the queue. It won't diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -499,7 +508,7 @@ where C: Connect + Sync + 'static, }) .map(move |tx| { pool.pooled(connecting, PoolClient { - is_proxied: connected.is_proxied, + conn_info: connected, tx: match ver { Ver::Http1 => PoolTx::Http1(tx), Ver::Http2 => PoolTx::Http2(tx.into_http2()), diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -565,7 +574,7 @@ impl Future for ResponseFuture { // FIXME: allow() required due to `impl Trait` leaking types to this lint #[allow(missing_debug_implementations)] struct PoolClient<B> { - is_proxied: bool, + conn_info: Connected, tx: PoolTx<B>, } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -624,17 +633,17 @@ where match self.tx { PoolTx::Http1(tx) => { Reservation::Unique(PoolClient { - is_proxied: self.is_proxied, + conn_info: self.conn_info, tx: PoolTx::Http1(tx), }) }, PoolTx::Http2(tx) => { let b = PoolClient { - is_proxied: self.is_proxied, + conn_info: self.conn_info.clone(), tx: PoolTx::Http2(tx.clone()), }; let a = PoolClient { - is_proxied: self.is_proxied, + conn_info: self.conn_info, tx: PoolTx::Http2(tx), }; Reservation::Shared(a, b)
diff --git a/src/client/connect/mod.rs b/src/client/connect/mod.rs --- a/src/client/connect/mod.rs +++ b/src/client/connect/mod.rs @@ -268,6 +278,61 @@ impl Connected { self } */ + + // Don't public expose that `Connected` is `Clone`, unsure if we want to + // keep that contract... + pub(super) fn clone(&self) -> Connected { + Connected { + is_proxied: self.is_proxied, + extra: self.extra.clone(), + } + } +} + +// ===== impl Extra ===== + +impl Extra { + pub(super) fn set(&self, res: &mut Response<::Body>) { + self.0.set(res); + } +} + +impl Clone for Extra { + fn clone(&self) -> Extra { + Extra(self.0.clone_box()) + } +} + +impl fmt::Debug for Extra { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Extra") + .finish() + } +} + +// This indirection allows the `Connected` to have a type-erased "extra" value, +// while that type still knows its inner extra type. This allows the correct +// TypeId to be used when inserting into `res.extensions_mut()`. +#[derive(Clone)] +struct ExtraEnvelope<T>(T); + +trait ExtraInner: Send + Sync { + fn clone_box(&self) -> Box<ExtraInner>; + fn set(&self, res: &mut Response<::Body>); +} + +impl<T> ExtraInner for ExtraEnvelope<T> +where + T: Clone + Send + Sync + 'static +{ + fn clone_box(&self) -> Box<ExtraInner> { + Box::new(self.clone()) + } + + fn set(&self, res: &mut Response<::Body>) { + let extra = self.0.clone(); + res.extensions_mut().insert(extra); + } } #[cfg(test)] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -274,7 +274,17 @@ macro_rules! test { let rx = rx.expect("thread panicked"); - rt.block_on(res.join(rx).map(|r| r.0)) + rt.block_on(res.join(rx).map(|r| r.0)).map(move |mut resp| { + // Always check that HttpConnector has set the "extra" info... + let extra = resp + .extensions_mut() + .remove::<::hyper::client::connect::HttpInfo>() + .expect("HttpConnector should set HttpInfo"); + + assert_eq!(extra.remote_addr(), addr, "HttpInfo should have server addr"); + + resp + }) }); }
Get socket parameters in Client or Server When a `Client` makes a request, it may connect to one of many hosts associated with the URL. I would like to have a way to access the IP address associated with the remote host. This is accessible from tokio via `NetSocket::peer_addr()`. Logically, one should also be able to access the local address with `local_addr()`, and so it makes sense to support access to many of the apis made available on the socket-level from tokio.
I agree there are cases where this is desirable, but there are also reasons it doesn't exist yet. These are properties specific to TCP, whereas hyper (and HTTP even) don't require the underlying transport to be TCP (Unix domain sockets don't have a concept of addresses, for example). It'd probably need some sort of middleware between when a transport is chosen ready to use and when a `Response` is given back to the user, but there isn't currently anything to really do that. For now, you'd probably need a custom `Connect` implementation that stores the relevant socket information in something that you can check outside of hyper. When would one expect to be able to receive this information? You generally give a `Request` to the `Client`, and don't know what connection it will use at that point. If it's fine that this information is received on the `Response`, we could optionally put this information in the `Response::extensions`. If we went that way, I'd think that instead of exposing exactly that the type is in `extensions`, some sort of `ConnectionInfo` type could exist that can be get and set on the `Response` (and similar info could be useful on the incoming server `Request`). A possible API: ```rust pub struct ConnectionInfo { local_addr: Option<SocketAddr>, remote_addr: Option<SocketAddr>, // maybe new fields in the future } impl ConnectionInfo { pub fn get(res: &Response) -> ConnectionInfo { // fetch an internal type from `extensions()`, // fill in whatever info was possible } pub fn set(&self, res: &mut Response) { } } ``` Sometimes you want to write logs and include the remote host in the log. Yes, of course. I was asking at what point would it be expected to access the remote info? Is it fine as a property of the response? I guess you could also want it even earlier than that: you establish a TCP connection, log the remote host and then SSL auth fails.
2018-07-05T18:54:23Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,572
hyperium__hyper-1572
[ "1564" ]
e4ebf4482372497f0cd5fa63d6492bd1c51d7b21
diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -6,9 +6,11 @@ //! establishes connections over TCP. //! - The [`Connect`](Connect) trait and related types to build custom connectors. use std::error::Error as StdError; +use std::mem; +use bytes::{BufMut, BytesMut}; use futures::Future; -use http::Uri; +use http::{uri, Uri}; use tokio_io::{AsyncRead, AsyncWrite}; #[cfg(feature = "runtime")] pub use self::http::HttpConnector; diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -79,6 +81,144 @@ impl Destination { self.uri.port() } + /// Update the scheme of this destination. + /// + /// # Example + /// + /// ```rust + /// # use hyper::client::connect::Destination; + /// # fn with_dst(mut dst: Destination) { + /// // let mut dst = some_destination... + /// // Change from "http://"... + /// assert_eq!(dst.scheme(), "http"); + /// + /// // to "ws://"... + /// dst.set_scheme("ws"); + /// assert_eq!(dst.scheme(), "ws"); + /// # } + /// ``` + /// + /// # Error + /// + /// Returns an error if the string is not a valid scheme. + pub fn set_scheme(&mut self, scheme: &str) -> ::Result<()> { + let scheme = scheme.parse().map_err(::error::Parse::from)?; + self.update_uri(move |parts| { + parts.scheme = Some(scheme); + }) + } + + /// Update the host of this destination. + /// + /// # Example + /// + /// ```rust + /// # use hyper::client::connect::Destination; + /// # fn with_dst(mut dst: Destination) { + /// // let mut dst = some_destination... + /// // Change from "hyper.rs"... + /// assert_eq!(dst.host(), "hyper.rs"); + /// + /// // to "some.proxy"... + /// dst.set_host("some.proxy"); + /// assert_eq!(dst.host(), "some.proxy"); + /// # } + /// ``` + /// + /// # Error + /// + /// Returns an error if the string is not a valid hostname. + pub fn set_host(&mut self, host: &str) -> ::Result<()> { + if host.contains(&['@',':'][..]) { + return Err(::error::Parse::Uri.into()); + } + let auth = if let Some(port) = self.port() { + format!("{}:{}", host, port).parse().map_err(::error::Parse::from)? + } else { + host.parse().map_err(::error::Parse::from)? + }; + self.update_uri(move |parts| { + parts.authority = Some(auth); + }) + } + + /// Update the port of this destination. + /// + /// # Example + /// + /// ```rust + /// # use hyper::client::connect::Destination; + /// # fn with_dst(mut dst: Destination) { + /// // let mut dst = some_destination... + /// // Change from "None"... + /// assert_eq!(dst.port(), None); + /// + /// // to "4321"... + /// dst.set_port(4321); + /// assert_eq!(dst.port(), Some(4321)); + /// + /// // Or remove the port... + /// dst.set_port(None); + /// assert_eq!(dst.port(), None); + /// # } + /// ``` + pub fn set_port<P>(&mut self, port: P) + where + P: Into<Option<u16>>, + { + self.set_port_opt(port.into()); + } + + fn set_port_opt(&mut self, port: Option<u16>) { + use std::fmt::Write; + + let auth = if let Some(port) = port { + let host = self.host(); + // Need space to copy the hostname, plus ':', + // plus max 5 port digits... + let cap = host.len() + 1 + 5; + let mut buf = BytesMut::with_capacity(cap); + buf.put_slice(host.as_bytes()); + buf.put_u8(b':'); + write!(buf, "{}", port) + .expect("should have space for 5 digits"); + + uri::Authority::from_shared(buf.freeze()) + .expect("valid host + :port should be valid authority") + } else { + self.host().parse() + .expect("valid host without port should be valid authority") + }; + + self.update_uri(move |parts| { + parts.authority = Some(auth); + }) + .expect("valid uri should be valid with port"); + } + + fn update_uri<F>(&mut self, f: F) -> ::Result<()> + where + F: FnOnce(&mut uri::Parts) + { + // Need to store a default Uri while we modify the current one... + let old_uri = mem::replace(&mut self.uri, Uri::default()); + // However, mutate a clone, so we can revert if there's an error... + let mut parts: uri::Parts = old_uri.clone().into(); + + f(&mut parts); + + match Uri::from_parts(parts) { + Ok(uri) => { + self.uri = uri; + Ok(()) + }, + Err(err) => { + self.uri = old_uri; + Err(::error::Parse::from(err).into()) + }, + } + } + /* /// Returns whether this connection must negotiate HTTP/2 via ALPN. pub fn must_h2(&self) -> bool { diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -350,6 +350,12 @@ impl From<http::uri::InvalidUri> for Parse { } } +impl From<http::uri::InvalidUriParts> for Parse { + fn from(_: http::uri::InvalidUriParts) -> Parse { + Parse::Uri + } +} + #[doc(hidden)] trait AssertSendSync: Send + Sync + 'static {} #[doc(hidden)]
diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -121,6 +261,121 @@ impl Connected { */ } +#[cfg(test)] +mod tests { + use super::Destination; + + #[test] + fn test_destination_set_scheme() { + let mut dst = Destination { + uri: "http://hyper.rs".parse().expect("initial parse"), + }; + + assert_eq!(dst.scheme(), "http"); + assert_eq!(dst.host(), "hyper.rs"); + + dst.set_scheme("https").expect("set https"); + assert_eq!(dst.scheme(), "https"); + assert_eq!(dst.host(), "hyper.rs"); + + dst.set_scheme("<im not a scheme//?>").unwrap_err(); + assert_eq!(dst.scheme(), "https", "error doesn't modify dst"); + assert_eq!(dst.host(), "hyper.rs", "error doesn't modify dst"); + } + + #[test] + fn test_destination_set_host() { + let mut dst = Destination { + uri: "http://hyper.rs".parse().expect("initial parse"), + }; + + assert_eq!(dst.scheme(), "http"); + assert_eq!(dst.host(), "hyper.rs"); + assert_eq!(dst.port(), None); + + dst.set_host("seanmonstar.com").expect("set https"); + assert_eq!(dst.scheme(), "http"); + assert_eq!(dst.host(), "seanmonstar.com"); + assert_eq!(dst.port(), None); + + dst.set_host("/im-not a host! >:)").unwrap_err(); + assert_eq!(dst.scheme(), "http", "error doesn't modify dst"); + assert_eq!(dst.host(), "seanmonstar.com", "error doesn't modify dst"); + assert_eq!(dst.port(), None, "error doesn't modify dst"); + + // Also test that an exist port is set correctly. + let mut dst = Destination { + uri: "http://hyper.rs:8080".parse().expect("initial parse 2"), + }; + + assert_eq!(dst.scheme(), "http"); + assert_eq!(dst.host(), "hyper.rs"); + assert_eq!(dst.port(), Some(8080)); + + dst.set_host("seanmonstar.com").expect("set host"); + assert_eq!(dst.scheme(), "http"); + assert_eq!(dst.host(), "seanmonstar.com"); + assert_eq!(dst.port(), Some(8080)); + + dst.set_host("/im-not a host! >:)").unwrap_err(); + assert_eq!(dst.scheme(), "http", "error doesn't modify dst"); + assert_eq!(dst.host(), "seanmonstar.com", "error doesn't modify dst"); + assert_eq!(dst.port(), Some(8080), "error doesn't modify dst"); + + // Check port isn't snuck into `set_host`. + dst.set_host("seanmonstar.com:3030").expect_err("set_host sneaky port"); + assert_eq!(dst.scheme(), "http", "error doesn't modify dst"); + assert_eq!(dst.host(), "seanmonstar.com", "error doesn't modify dst"); + assert_eq!(dst.port(), Some(8080), "error doesn't modify dst"); + + // Check userinfo isn't snuck into `set_host`. + dst.set_host("sean@nope").expect_err("set_host sneaky userinfo"); + assert_eq!(dst.scheme(), "http", "error doesn't modify dst"); + assert_eq!(dst.host(), "seanmonstar.com", "error doesn't modify dst"); + assert_eq!(dst.port(), Some(8080), "error doesn't modify dst"); + } + + #[test] + fn test_destination_set_port() { + let mut dst = Destination { + uri: "http://hyper.rs".parse().expect("initial parse"), + }; + + assert_eq!(dst.scheme(), "http"); + assert_eq!(dst.host(), "hyper.rs"); + assert_eq!(dst.port(), None); + + dst.set_port(None); + assert_eq!(dst.scheme(), "http"); + assert_eq!(dst.host(), "hyper.rs"); + assert_eq!(dst.port(), None); + + dst.set_port(8080); + assert_eq!(dst.scheme(), "http"); + assert_eq!(dst.host(), "hyper.rs"); + assert_eq!(dst.port(), Some(8080)); + + // Also test that an exist port is set correctly. + let mut dst = Destination { + uri: "http://hyper.rs:8080".parse().expect("initial parse 2"), + }; + + assert_eq!(dst.scheme(), "http"); + assert_eq!(dst.host(), "hyper.rs"); + assert_eq!(dst.port(), Some(8080)); + + dst.set_port(3030); + assert_eq!(dst.scheme(), "http"); + assert_eq!(dst.host(), "hyper.rs"); + assert_eq!(dst.port(), Some(3030)); + + dst.set_port(None); + assert_eq!(dst.scheme(), "http"); + assert_eq!(dst.host(), "hyper.rs"); + assert_eq!(dst.port(), None); + } +} + #[cfg(feature = "runtime")] mod http { use super::*;
Can't create or modify hyper::client::connect::Destination I'm trying to write a connector that takes a destination, modifies it and passes it to the next connector. It seems this is currently not possible because there's no way to get a mutable reference to the internal state and only hyper can create new `Destination` objects. My usecase is having a custom dns resolver as a Connector that resolves the domain before passing it to the final HttpConnector that creates the connection.
I definitely get the use case! I'd like to find a way to support it, but I'd also like to list why the constructor was so far private: - The `Destination` type *may* gain more fields, such as in #1485 to support ALPN. - I worried that if a `Destination` gained more fields in new release, and a connector didn't know that and could create their own, then it could be possible for some intent on the connect action could be silently lost. What if, without adding a constructor, you could just mutate the internal URI of the `Destination`? that would work for me as well This would be nice for me as well. In hyper 0.11, I had a "stack" of composed connectors: `HttpsConnector<ProxyConnector<HttpConnector>>`. The ProxyConnector handled CONNECT tunneling for HTTPS proxies, and so needs to tell the underlying connector to point to the proxy address. In 0.12, that isn't currently possible so I ended up using a non-connector type under the ProxyConnector that just took a host/port.
2018-06-18T21:21:52Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,563
hyperium__hyper-1563
[ "1395" ]
1c3fbfd6bf6b627f75ef694e69c8074745276e9b
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -29,7 +29,7 @@ iovec = "0.1" log = "0.4" net2 = { version = "0.2.32", optional = true } time = "0.1" -tokio = { version = "0.1.5", optional = true } +tokio = { version = "0.1.7", optional = true } tokio-executor = { version = "0.1.0", optional = true } tokio-io = "0.1" tokio-reactor = { version = "0.1", optional = true } diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -101,6 +101,12 @@ name = "send_file" path = "examples/send_file.rs" required-features = ["runtime"] +[[example]] +name = "upgrades" +path = "examples/upgrades.rs" +required-features = ["runtime"] + + [[example]] name = "web_api" path = "examples/web_api.rs" diff --git a/examples/README.md b/examples/README.md --- a/examples/README.md +++ b/examples/README.md @@ -16,4 +16,6 @@ Run examples with `cargo run --example example_name`. * [`send_file`](send_file.rs) - A server that sends back content of files using tokio_fs to read the files asynchronously. +* [`upgrades`](upgrades.rs) - A server and client demonstrating how to do HTTP upgrades (such as WebSockets or `CONNECT` tunneling). + * [`web_api`](web_api.rs) - A server consisting in a service that returns incoming POST request's content in the response in uppercase and a service that call that call the first service and includes the first service response in its own response. diff --git /dev/null b/examples/upgrades.rs new file mode 100644 --- /dev/null +++ b/examples/upgrades.rs @@ -0,0 +1,127 @@ +// Note: `hyper::upgrade` docs link to this upgrade. +extern crate futures; +extern crate hyper; +extern crate tokio; + +use std::str; + +use futures::sync::oneshot; + +use hyper::{Body, Client, Request, Response, Server, StatusCode}; +use hyper::header::{UPGRADE, HeaderValue}; +use hyper::rt::{self, Future}; +use hyper::service::service_fn_ok; + +/// Our server HTTP handler to initiate HTTP upgrades. +fn server_upgrade(req: Request<Body>) -> Response<Body> { + let mut res = Response::new(Body::empty()); + + // Send a 400 to any request that doesn't have + // an `Upgrade` header. + if !req.headers().contains_key(UPGRADE) { + *res.status_mut() = StatusCode::BAD_REQUEST; + return res; + } + + // Setup a future that will eventually receive the upgraded + // connection and talk a new protocol, and spawn the future + // into the runtime. + // + // Note: This can't possibly be fulfilled until the 101 response + // is returned below, so it's better to spawn this future instead + // waiting for it to complete to then return a response. + let on_upgrade = req + .into_body() + .on_upgrade() + .map_err(|err| eprintln!("upgrade error: {}", err)) + .and_then(|upgraded| { + // We have an upgraded connection that we can read and + // write on directly. + // + // Since we completely control this example, we know exactly + // how many bytes the client will write, so just read exact... + tokio::io::read_exact(upgraded, vec![0; 7]) + .and_then(|(upgraded, vec)| { + println!("server[foobar] recv: {:?}", str::from_utf8(&vec)); + + // And now write back the server 'foobar' protocol's + // response... + tokio::io::write_all(upgraded, b"bar=foo") + }) + .map(|_| println!("server[foobar] sent")) + .map_err(|e| eprintln!("server foobar io error: {}", e)) + }); + + rt::spawn(on_upgrade); + + + // Now return a 101 Response saying we agree to the upgrade to some + // made-up 'foobar' protocol. + *res.status_mut() = StatusCode::SWITCHING_PROTOCOLS; + res.headers_mut().insert(UPGRADE, HeaderValue::from_static("foobar")); + res +} + +fn main() { + // For this example, we just make a server and our own client to talk to + // it, so the exact port isn't important. Instead, let the OS give us an + // unused port. + let addr = ([127, 0, 0, 1], 0).into(); + + let server = Server::bind(&addr) + .serve(|| service_fn_ok(server_upgrade)); + + // We need the assigned address for the client to send it messages. + let addr = server.local_addr(); + + + // For this example, a oneshot is used to signal that after 1 request, + // the server should be shutdown. + let (tx, rx) = oneshot::channel(); + + let server = server + .map_err(|e| eprintln!("server error: {}", e)) + .select2(rx) + .then(|_| Ok(())); + + rt::run(rt::lazy(move || { + rt::spawn(server); + + let req = Request::builder() + .uri(format!("http://{}/", addr)) + .header(UPGRADE, "foobar") + .body(Body::empty()) + .unwrap(); + + Client::new() + .request(req) + .and_then(|res| { + if res.status() != StatusCode::SWITCHING_PROTOCOLS { + panic!("Our server didn't upgrade: {}", res.status()); + } + + res + .into_body() + .on_upgrade() + }) + .map_err(|e| eprintln!("client error: {}", e)) + .and_then(|upgraded| { + // We've gotten an upgraded connection that we can read + // and write directly on. Let's start out 'foobar' protocol. + tokio::io::write_all(upgraded, b"foo=bar") + .and_then(|(upgraded, _)| { + println!("client[foobar] sent"); + tokio::io::read_to_end(upgraded, Vec::new()) + }) + .map(|(_upgraded, vec)| { + println!("client[foobar] recv: {:?}", str::from_utf8(&vec)); + + + // Complete the oneshot so that the server stops + // listening and the process can close down. + let _ = tx.send(()); + }) + .map_err(|e| eprintln!("client foobar io error: {}", e)) + }) + })); +} diff --git a/src/body/body.rs b/src/body/body.rs --- a/src/body/body.rs +++ b/src/body/body.rs @@ -10,6 +10,7 @@ use http::HeaderMap; use common::Never; use super::{Chunk, Payload}; use super::internal::{FullDataArg, FullDataRet}; +use upgrade::OnUpgrade; type BodySender = mpsc::Sender<Result<Chunk, ::Error>>; diff --git a/src/body/body.rs b/src/body/body.rs --- a/src/body/body.rs +++ b/src/body/body.rs @@ -21,15 +22,9 @@ type BodySender = mpsc::Sender<Result<Chunk, ::Error>>; #[must_use = "streams do nothing unless polled"] pub struct Body { kind: Kind, - /// Allow the client to pass a future to delay the `Body` from returning - /// EOF. This allows the `Client` to try to put the idle connection - /// back into the pool before the body is "finished". - /// - /// The reason for this is so that creating a new request after finishing - /// streaming the body of a response could sometimes result in creating - /// a brand new connection, since the pool didn't know about the idle - /// connection yet. - delayed_eof: Option<DelayEof>, + /// Keep the extra bits in an `Option<Box<Extra>>`, so that + /// Body stays small in the common case (no extras needed). + extra: Option<Box<Extra>>, } enum Kind { diff --git a/src/body/body.rs b/src/body/body.rs --- a/src/body/body.rs +++ b/src/body/body.rs @@ -43,6 +38,19 @@ enum Kind { Wrapped(Box<Stream<Item=Chunk, Error=Box<::std::error::Error + Send + Sync>> + Send>), } +struct Extra { + /// Allow the client to pass a future to delay the `Body` from returning + /// EOF. This allows the `Client` to try to put the idle connection + /// back into the pool before the body is "finished". + /// + /// The reason for this is so that creating a new request after finishing + /// streaming the body of a response could sometimes result in creating + /// a brand new connection, since the pool didn't know about the idle + /// connection yet. + delayed_eof: Option<DelayEof>, + on_upgrade: OnUpgrade, +} + type DelayEofUntil = oneshot::Receiver<Never>; enum DelayEof { diff --git a/src/body/body.rs b/src/body/body.rs --- a/src/body/body.rs +++ b/src/body/body.rs @@ -89,7 +97,6 @@ impl Body { Self::new_channel(None) } - #[inline] pub(crate) fn new_channel(content_length: Option<u64>) -> (Sender, Body) { let (tx, rx) = mpsc::channel(0); let (abort_tx, abort_rx) = oneshot::channel(); diff --git a/src/body/body.rs b/src/body/body.rs --- a/src/body/body.rs +++ b/src/body/body.rs @@ -139,10 +146,20 @@ impl Body { Body::new(Kind::Wrapped(Box::new(mapped))) } + /// Converts this `Body` into a `Future` of a pending HTTP upgrade. + /// + /// See [the `upgrade` module](::upgrade) for more. + pub fn on_upgrade(self) -> OnUpgrade { + self + .extra + .map(|ex| ex.on_upgrade) + .unwrap_or_else(OnUpgrade::none) + } + fn new(kind: Kind) -> Body { Body { kind: kind, - delayed_eof: None, + extra: None, } } diff --git a/src/body/body.rs b/src/body/body.rs --- a/src/body/body.rs +++ b/src/body/body.rs @@ -150,23 +167,46 @@ impl Body { Body::new(Kind::H2(recv)) } + pub(crate) fn set_on_upgrade(&mut self, upgrade: OnUpgrade) { + debug_assert!(!upgrade.is_none(), "set_on_upgrade with empty upgrade"); + let extra = self.extra_mut(); + debug_assert!(extra.on_upgrade.is_none(), "set_on_upgrade twice"); + extra.on_upgrade = upgrade; + } + pub(crate) fn delayed_eof(&mut self, fut: DelayEofUntil) { - self.delayed_eof = Some(DelayEof::NotEof(fut)); + self.extra_mut().delayed_eof = Some(DelayEof::NotEof(fut)); + } + + fn take_delayed_eof(&mut self) -> Option<DelayEof> { + self + .extra + .as_mut() + .and_then(|extra| extra.delayed_eof.take()) + } + + fn extra_mut(&mut self) -> &mut Extra { + self + .extra + .get_or_insert_with(|| Box::new(Extra { + delayed_eof: None, + on_upgrade: OnUpgrade::none(), + })) } fn poll_eof(&mut self) -> Poll<Option<Chunk>, ::Error> { - match self.delayed_eof.take() { + match self.take_delayed_eof() { Some(DelayEof::NotEof(mut delay)) => { match self.poll_inner() { ok @ Ok(Async::Ready(Some(..))) | ok @ Ok(Async::NotReady) => { - self.delayed_eof = Some(DelayEof::NotEof(delay)); + self.extra_mut().delayed_eof = Some(DelayEof::NotEof(delay)); ok }, Ok(Async::Ready(None)) => match delay.poll() { Ok(Async::Ready(never)) => match never {}, Ok(Async::NotReady) => { - self.delayed_eof = Some(DelayEof::Eof(delay)); + self.extra_mut().delayed_eof = Some(DelayEof::Eof(delay)); Ok(Async::NotReady) }, Err(_done) => { diff --git a/src/body/body.rs b/src/body/body.rs --- a/src/body/body.rs +++ b/src/body/body.rs @@ -180,7 +220,7 @@ impl Body { match delay.poll() { Ok(Async::Ready(never)) => match never {}, Ok(Async::NotReady) => { - self.delayed_eof = Some(DelayEof::Eof(delay)); + self.extra_mut().delayed_eof = Some(DelayEof::Eof(delay)); Ok(Async::NotReady) }, Err(_done) => { diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -9,6 +9,7 @@ //! higher-level [Client](super) API. use std::fmt; use std::marker::PhantomData; +use std::mem; use bytes::Bytes; use futures::{Async, Future, Poll}; diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -17,9 +18,21 @@ use tokio_io::{AsyncRead, AsyncWrite}; use body::Payload; use common::Exec; +use upgrade::Upgraded; use proto; use super::dispatch; -use {Body, Request, Response, StatusCode}; +use {Body, Request, Response}; + +type Http1Dispatcher<T, B, R> = proto::dispatch::Dispatcher< + proto::dispatch::Client<B>, + B, + T, + R, +>; +type ConnEither<T, B> = Either< + Http1Dispatcher<T, B, proto::h1::ClientTransaction>, + proto::h2::Client<T, B>, +>; /// Returns a `Handshake` future over some IO. /// diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -48,15 +61,7 @@ where T: AsyncRead + AsyncWrite + Send + 'static, B: Payload + 'static, { - inner: Either< - proto::dispatch::Dispatcher< - proto::dispatch::Client<B>, - B, - T, - proto::ClientUpgradeTransaction, - >, - proto::h2::Client<T, B>, - >, + inner: Option<ConnEither<T, B>>, } diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -76,7 +81,9 @@ pub struct Builder { /// If successful, yields a `(SendRequest, Connection)` pair. #[must_use = "futures do nothing unless polled"] pub struct Handshake<T, B> { - inner: HandshakeInner<T, B, proto::ClientUpgradeTransaction>, + builder: Builder, + io: Option<T>, + _marker: PhantomData<B>, } /// A future returned by `SendRequest::send_request`. diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -112,27 +119,18 @@ pub struct Parts<T> { // ========== internal client api /// A `Future` for when `SendRequest::poll_ready()` is ready. +#[must_use = "futures do nothing unless polled"] pub(super) struct WhenReady<B> { tx: Option<SendRequest<B>>, } // A `SendRequest` that can be cloned to send HTTP2 requests. // private for now, probably not a great idea of a type... +#[must_use = "futures do nothing unless polled"] pub(super) struct Http2SendRequest<B> { dispatch: dispatch::UnboundedSender<Request<B>, Response<Body>>, } -#[must_use = "futures do nothing unless polled"] -pub(super) struct HandshakeNoUpgrades<T, B> { - inner: HandshakeInner<T, B, proto::ClientTransaction>, -} - -struct HandshakeInner<T, B, R> { - builder: Builder, - io: Option<T>, - _marker: PhantomData<(B, R)>, -} - // ===== impl SendRequest impl<B> SendRequest<B> diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -354,7 +352,7 @@ where /// /// Only works for HTTP/1 connections. HTTP/2 connections will panic. pub fn into_parts(self) -> Parts<T> { - let (io, read_buf, _) = match self.inner { + let (io, read_buf, _) = match self.inner.expect("already upgraded") { Either::A(h1) => h1.into_inner(), Either::B(_h2) => { panic!("http2 cannot into_inner"); diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -376,12 +374,12 @@ where /// but it is not desired to actally shutdown the IO object. Instead you /// would take it back using `into_parts`. pub fn poll_without_shutdown(&mut self) -> Poll<(), ::Error> { - match self.inner { - Either::A(ref mut h1) => { + match self.inner.as_mut().expect("already upgraded") { + &mut Either::A(ref mut h1) => { h1.poll_without_shutdown() }, - Either::B(ref mut h2) => { - h2.poll() + &mut Either::B(ref mut h2) => { + h2.poll().map(|x| x.map(|_| ())) } } } diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -396,7 +394,22 @@ where type Error = ::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - self.inner.poll() + match try_ready!(self.inner.poll()) { + Some(proto::Dispatched::Shutdown) | + None => { + Ok(Async::Ready(())) + }, + Some(proto::Dispatched::Upgrade(pending)) => { + let h1 = match mem::replace(&mut self.inner, None) { + Some(Either::A(h1)) => h1, + _ => unreachable!("Upgrade expects h1"), + }; + + let (io, buf, _) = h1.into_inner(); + pending.fulfill(Upgraded::new(Box::new(io), buf)); + Ok(Async::Ready(())) + } + } } } diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -456,25 +469,9 @@ impl Builder { B: Payload + 'static, { Handshake { - inner: HandshakeInner { - builder: self.clone(), - io: Some(io), - _marker: PhantomData, - } - } - } - - pub(super) fn handshake_no_upgrades<T, B>(&self, io: T) -> HandshakeNoUpgrades<T, B> - where - T: AsyncRead + AsyncWrite + Send + 'static, - B: Payload + 'static, - { - HandshakeNoUpgrades { - inner: HandshakeInner { - builder: self.clone(), - io: Some(io), - _marker: PhantomData, - } + builder: self.clone(), + io: Some(io), + _marker: PhantomData, } } } diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -489,64 +486,6 @@ where type Item = (SendRequest<B>, Connection<T, B>); type Error = ::Error; - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - self.inner.poll() - .map(|async| { - async.map(|(tx, dispatch)| { - (tx, Connection { inner: dispatch }) - }) - }) - } -} - -impl<T, B> fmt::Debug for Handshake<T, B> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("Handshake") - .finish() - } -} - -impl<T, B> Future for HandshakeNoUpgrades<T, B> -where - T: AsyncRead + AsyncWrite + Send + 'static, - B: Payload + 'static, -{ - type Item = (SendRequest<B>, Either< - proto::h1::Dispatcher< - proto::h1::dispatch::Client<B>, - B, - T, - proto::ClientTransaction, - >, - proto::h2::Client<T, B>, - >); - type Error = ::Error; - - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - self.inner.poll() - } -} - -impl<T, B, R> Future for HandshakeInner<T, B, R> -where - T: AsyncRead + AsyncWrite + Send + 'static, - B: Payload, - R: proto::h1::Http1Transaction< - Incoming=StatusCode, - Outgoing=proto::RequestLine, - >, -{ - type Item = (SendRequest<B>, Either< - proto::h1::Dispatcher< - proto::h1::dispatch::Client<B>, - B, - T, - R, - >, - proto::h2::Client<T, B>, - >); - type Error = ::Error; - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { let io = self.io.take().expect("polled more than once"); let (tx, rx) = dispatch::channel(); diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -570,11 +509,20 @@ where SendRequest { dispatch: tx, }, - either, + Connection { + inner: Some(either), + }, ))) } } +impl<T, B> fmt::Debug for Handshake<T, B> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Handshake") + .finish() + } +} + // ===== impl ResponseFuture impl Future for ResponseFuture { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -268,7 +268,7 @@ where C: Connect + Sync + 'static, .h1_writev(h1_writev) .h1_title_case_headers(h1_title_case_headers) .http2_only(pool_key.1 == Ver::Http2) - .handshake_no_upgrades(io) + .handshake(io) .and_then(move |(tx, conn)| { executor.execute(conn.map_err(|e| { debug!("client connection error: {}", e) diff --git /dev/null b/src/common/io/mod.rs new file mode 100644 --- /dev/null +++ b/src/common/io/mod.rs @@ -0,0 +1,3 @@ +mod rewind; + +pub(crate) use self::rewind::Rewind; diff --git a/src/server/rewind.rs b/src/common/io/rewind.rs --- a/src/server/rewind.rs +++ b/src/common/io/rewind.rs @@ -1,26 +1,40 @@ +use std::cmp; +use std::io::{self, Read, Write}; + use bytes::{Buf, BufMut, Bytes, IntoBuf}; use futures::{Async, Poll}; -use std::io::{self, Read, Write}; -use std::cmp; use tokio_io::{AsyncRead, AsyncWrite}; +/// Combine a buffer with an IO, rewinding reads to use the buffer. #[derive(Debug)] -pub struct Rewind<T> { +pub(crate) struct Rewind<T> { pre: Option<Bytes>, inner: T, } impl<T> Rewind<T> { - pub(super) fn new(tcp: T) -> Rewind<T> { + pub(crate) fn new(io: T) -> Self { Rewind { pre: None, - inner: tcp, + inner: io, + } + } + + pub(crate) fn new_buffered(io: T, buf: Bytes) -> Self { + Rewind { + pre: Some(buf), + inner: io, } } - pub fn rewind(&mut self, bs: Bytes) { + + pub(crate) fn rewind(&mut self, bs: Bytes) { debug_assert!(self.pre.is_none()); self.pre = Some(bs); } + + pub(crate) fn into_inner(self) -> (T, Bytes) { + (self.inner, self.pre.unwrap_or_else(Bytes::new)) + } } impl<T> Read for Rewind<T> diff --git a/src/common/mod.rs b/src/common/mod.rs --- a/src/common/mod.rs +++ b/src/common/mod.rs @@ -1,5 +1,6 @@ mod buf; mod exec; +pub(crate) mod io; mod never; pub(crate) use self::buf::StaticBuf; diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -61,6 +61,12 @@ pub(crate) enum Kind { UnsupportedVersion, /// User tried to create a CONNECT Request with the Client. UnsupportedRequestMethod, + + /// User tried polling for an upgrade that doesn't exist. + NoUpgrade, + + /// User polled for an upgrade, but low-level API is not using upgrades. + ManualUpgrade, } #[derive(Debug, PartialEq)] diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -72,9 +78,6 @@ pub(crate) enum Parse { Header, TooLarge, Status, - - /// A protocol upgrade was encountered, but not yet supported in hyper. - UpgradeNotSupported, } /* diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -110,7 +113,8 @@ impl Error { Kind::Service | Kind::Closed | Kind::UnsupportedVersion | - Kind::UnsupportedRequestMethod => true, + Kind::UnsupportedRequestMethod | + Kind::NoUpgrade => true, _ => false, } } diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -216,6 +220,14 @@ impl Error { Error::new(Kind::UnsupportedRequestMethod, None) } + pub(crate) fn new_user_no_upgrade() -> Error { + Error::new(Kind::NoUpgrade, None) + } + + pub(crate) fn new_user_manual_upgrade() -> Error { + Error::new(Kind::ManualUpgrade, None) + } + pub(crate) fn new_user_new_service<E: Into<Cause>>(cause: E) -> Error { Error::new(Kind::NewService, Some(cause.into())) } diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -266,7 +278,6 @@ impl StdError for Error { Kind::Parse(Parse::Header) => "invalid Header provided", Kind::Parse(Parse::TooLarge) => "message head is too large", Kind::Parse(Parse::Status) => "invalid Status provided", - Kind::Parse(Parse::UpgradeNotSupported) => "unsupported protocol upgrade", Kind::Incomplete => "message is incomplete", Kind::MismatchedResponse => "response received without matching request", Kind::Closed => "connection closed", diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -284,6 +295,8 @@ impl StdError for Error { Kind::Http2 => "http2 general error", Kind::UnsupportedVersion => "request has unsupported HTTP version", Kind::UnsupportedRequestMethod => "request has unsupported HTTP method", + Kind::NoUpgrade => "no upgrade available", + Kind::ManualUpgrade => "upgrade expected but low level API in use", Kind::Io => "an IO error occurred", } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -62,3 +62,4 @@ mod proto; pub mod server; pub mod service; #[cfg(feature = "runtime")] pub mod rt; +pub mod upgrade; diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -79,6 +79,7 @@ pub struct AsyncIo<T> { inner: T, max_read_vecs: usize, num_writes: usize, + panic: bool, park_tasks: bool, task: Option<Task>, } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -93,6 +94,7 @@ impl<T> AsyncIo<T> { inner: inner, max_read_vecs: READ_VECS_CNT, num_writes: 0, + panic: false, park_tasks: false, task: None, } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -110,6 +112,11 @@ impl<T> AsyncIo<T> { self.error = Some(err); } + #[cfg(feature = "nightly")] + pub fn panic(&mut self) { + self.panic = true; + } + pub fn max_read_vecs(&mut self, cnt: usize) { assert!(cnt <= READ_VECS_CNT); self.max_read_vecs = cnt; diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -185,6 +192,7 @@ impl<S: AsRef<[u8]>, T: AsRef<[u8]>> PartialEq<S> for AsyncIo<T> { impl<T: Read> Read for AsyncIo<T> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + assert!(!self.panic, "AsyncIo::read panic"); self.blocked = false; if let Some(err) = self.error.take() { Err(err) diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -201,6 +209,7 @@ impl<T: Read> Read for AsyncIo<T> { impl<T: Write> Write for AsyncIo<T> { fn write(&mut self, data: &[u8]) -> io::Result<usize> { + assert!(!self.panic, "AsyncIo::write panic"); self.num_writes += 1; if let Some(err) = self.error.take() { trace!("AsyncIo::write error"); diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -233,6 +242,7 @@ impl<T: Read + Write> AsyncWrite for AsyncIo<T> { } fn write_buf<B: Buf>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { + assert!(!self.panic, "AsyncIo::write_buf panic"); if self.max_read_vecs == 0 { return self.write_no_vecs(buf); } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -8,9 +8,9 @@ use http::{HeaderMap, Method, Version}; use tokio_io::{AsyncRead, AsyncWrite}; use ::Chunk; -use proto::{BodyLength, MessageHead}; +use proto::{BodyLength, DecodedLength, MessageHead}; use super::io::{Buffered}; -use super::{EncodedBuf, Encode, Encoder, Decode, Decoder, Http1Transaction, ParseContext}; +use super::{EncodedBuf, Encode, Encoder, /*Decode,*/ Decoder, Http1Transaction, ParseContext}; const H2_PREFACE: &'static [u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -44,6 +44,7 @@ where I: AsyncRead + AsyncWrite, notify_read: false, reading: Reading::Init, writing: Writing::Init, + upgrade: None, // We assume a modern world where the remote speaks HTTP/1.1. // If they tell us otherwise, we'll downgrade in `read_head`. version: Version::HTTP_11, diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -72,6 +73,10 @@ where I: AsyncRead + AsyncWrite, self.io.into_inner() } + pub fn pending_upgrade(&mut self) -> Option<::upgrade::Pending> { + self.state.upgrade.take() + } + pub fn is_read_closed(&self) -> bool { self.state.is_read_closed() } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -114,80 +119,61 @@ where I: AsyncRead + AsyncWrite, read_buf.len() >= 24 && read_buf[..24] == *H2_PREFACE } - pub fn read_head(&mut self) -> Poll<Option<(MessageHead<T::Incoming>, Option<BodyLength>)>, ::Error> { + pub fn read_head(&mut self) -> Poll<Option<(MessageHead<T::Incoming>, DecodedLength, bool)>, ::Error> { debug_assert!(self.can_read_head()); trace!("Conn::read_head"); - loop { - let msg = match self.io.parse::<T>(ParseContext { - cached_headers: &mut self.state.cached_headers, - req_method: &mut self.state.method, - }) { - Ok(Async::Ready(msg)) => msg, - Ok(Async::NotReady) => return Ok(Async::NotReady), - Err(e) => { - // If we are currently waiting on a message, then an empty - // message should be reported as an error. If not, it is just - // the connection closing gracefully. - let must_error = self.should_error_on_eof(); - self.state.close_read(); - self.io.consume_leading_lines(); - let was_mid_parse = e.is_parse() || !self.io.read_buf().is_empty(); - return if was_mid_parse || must_error { - // We check if the buf contains the h2 Preface - debug!("parse error ({}) with {} bytes", e, self.io.read_buf().len()); - self.on_parse_error(e) - .map(|()| Async::NotReady) - } else { - debug!("read eof"); - Ok(Async::Ready(None)) - }; - } - }; + let msg = match self.io.parse::<T>(ParseContext { + cached_headers: &mut self.state.cached_headers, + req_method: &mut self.state.method, + }) { + Ok(Async::Ready(msg)) => msg, + Ok(Async::NotReady) => return Ok(Async::NotReady), + Err(e) => return self.on_read_head_error(e), + }; - self.state.version = msg.head.version; - let head = msg.head; - let decoder = match msg.decode { - Decode::Normal(d) => { - d - }, - Decode::Final(d) => { - trace!("final decoder, HTTP ending"); - debug_assert!(d.is_eof()); - self.state.close_read(); - d - }, - Decode::Ignore => { - // likely a 1xx message that we can ignore - continue; - } - }; - debug!("incoming body is {}", decoder); + // Note: don't deconstruct `msg` into local variables, it appears + // the optimizer doesn't remove the extra copies. - self.state.busy(); + debug!("incoming body is {}", msg.decode); + + self.state.busy(); + self.state.keep_alive &= msg.keep_alive; + self.state.version = msg.head.version; + + if msg.decode == DecodedLength::ZERO { + debug_assert!(!msg.expect_continue, "expect-continue needs a body"); + self.state.reading = Reading::KeepAlive; + if !T::should_read_first() { + self.try_keep_alive(); + } + } else { if msg.expect_continue { let cont = b"HTTP/1.1 100 Continue\r\n\r\n"; self.io.headers_buf().extend_from_slice(cont); } - let wants_keep_alive = msg.keep_alive; - self.state.keep_alive &= wants_keep_alive; - - let content_length = decoder.content_length(); + self.state.reading = Reading::Body(Decoder::new(msg.decode)); + }; - if let Reading::Closed = self.state.reading { - // actually want an `if not let ...` - } else { - self.state.reading = if content_length.is_none() { - Reading::KeepAlive - } else { - Reading::Body(decoder) - }; - } - if content_length.is_none() { - self.try_keep_alive(); - } + Ok(Async::Ready(Some((msg.head, msg.decode, msg.wants_upgrade)))) + } - return Ok(Async::Ready(Some((head, content_length)))); + fn on_read_head_error<Z>(&mut self, e: ::Error) -> Poll<Option<Z>, ::Error> { + // If we are currently waiting on a message, then an empty + // message should be reported as an error. If not, it is just + // the connection closing gracefully. + let must_error = self.should_error_on_eof(); + self.state.close_read(); + self.io.consume_leading_lines(); + let was_mid_parse = e.is_parse() || !self.io.read_buf().is_empty(); + if was_mid_parse || must_error { + // We check if the buf contains the h2 Preface + debug!("parse error ({}) with {} bytes", e, self.io.read_buf().len()); + self.on_parse_error(e) + .map(|()| Async::NotReady) + } else { + debug!("read eof"); + Ok(Async::Ready(None)) } } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -649,6 +639,8 @@ struct State { reading: Reading, /// State of allowed writes writing: Writing, + /// An expected pending HTTP upgrade. + upgrade: Option<::upgrade::Pending>, /// Either HTTP/1.0 or 1.1 connection version: Version, } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -697,6 +689,7 @@ impl fmt::Debug for Writing { impl ::std::ops::BitAndAssign<bool> for KA { fn bitand_assign(&mut self, enabled: bool) { if !enabled { + trace!("remote disabling keep-alive"); *self = KA::Disabled; } } diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -7,7 +7,7 @@ use futures::{Async, Poll}; use bytes::Bytes; use super::io::MemRead; -use super::BodyLength; +use super::{DecodedLength}; use self::Kind::{Length, Chunked, Eof}; diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -74,6 +74,14 @@ impl Decoder { Decoder { kind: Kind::Eof(false) } } + pub(super) fn new(len: DecodedLength) -> Self { + match len { + DecodedLength::CHUNKED => Decoder::chunked(), + DecodedLength::CLOSE_DELIMITED => Decoder::eof(), + length => Decoder::length(length.danger_len()), + } + } + // methods pub fn is_eof(&self) -> bool { diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -85,16 +93,6 @@ impl Decoder { } } - pub fn content_length(&self) -> Option<BodyLength> { - match self.kind { - Length(0) | - Chunked(ChunkedState::End, _) | - Eof(true) => None, - Length(len) => Some(BodyLength::Known(len)), - _ => Some(BodyLength::Unknown), - } - } - pub fn decode<R: MemRead>(&mut self, body: &mut R) -> Poll<Bytes, io::Error> { trace!("decode; state={:?}", self.kind); match self.kind { diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -152,16 +150,6 @@ impl fmt::Debug for Decoder { } } -impl fmt::Display for Decoder { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self.kind { - Kind::Length(n) => write!(f, "content-length ({} bytes)", n), - Kind::Chunked(..) => f.write_str("chunked encoded"), - Kind::Eof(..) => f.write_str("until end-of-file"), - } - } -} - macro_rules! byte ( ($rdr:ident) => ({ let buf = try_ready!($rdr.read_mem(1)); diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -5,7 +5,7 @@ use tokio_io::{AsyncRead, AsyncWrite}; use body::{Body, Payload}; use body::internal::FullDataArg; -use proto::{BodyLength, Conn, MessageHead, RequestHead, RequestLine, ResponseHead}; +use proto::{BodyLength, DecodedLength, Conn, Dispatched, MessageHead, RequestHead, RequestLine, ResponseHead}; use super::Http1Transaction; use service::Service; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -65,32 +65,34 @@ where (io, buf, self.dispatch) } - /// The "Future" poll function. Runs this dispatcher until the - /// connection is shutdown, or an error occurs. - pub fn poll_until_shutdown(&mut self) -> Poll<(), ::Error> { - self.poll_catch(true) - } - /// Run this dispatcher until HTTP says this connection is done, /// but don't call `AsyncWrite::shutdown` on the underlying IO. /// - /// This is useful for HTTP upgrades. + /// This is useful for old-style HTTP upgrades, but ignores + /// newer-style upgrade API. pub fn poll_without_shutdown(&mut self) -> Poll<(), ::Error> { self.poll_catch(false) + .map(|x| { + x.map(|ds| if let Dispatched::Upgrade(pending) = ds { + pending.manual(); + }) + }) } - fn poll_catch(&mut self, should_shutdown: bool) -> Poll<(), ::Error> { + fn poll_catch(&mut self, should_shutdown: bool) -> Poll<Dispatched, ::Error> { self.poll_inner(should_shutdown).or_else(|e| { // An error means we're shutting down either way. // We just try to give the error to the user, // and close the connection with an Ok. If we // cannot give it to the user, then return the Err. - self.dispatch.recv_msg(Err(e)).map(Async::Ready) + self.dispatch.recv_msg(Err(e))?; + Ok(Async::Ready(Dispatched::Shutdown)) }) } - fn poll_inner(&mut self, should_shutdown: bool) -> Poll<(), ::Error> { + fn poll_inner(&mut self, should_shutdown: bool) -> Poll<Dispatched, ::Error> { T::update_date(); + loop { self.poll_read()?; self.poll_write()?; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -110,11 +112,14 @@ where } if self.is_done() { - if should_shutdown { + if let Some(pending) = self.conn.pending_upgrade() { + self.conn.take_error()?; + return Ok(Async::Ready(Dispatched::Upgrade(pending))); + } else if should_shutdown { try_ready!(self.conn.shutdown().map_err(::Error::new_shutdown)); } self.conn.take_error()?; - Ok(Async::Ready(())) + Ok(Async::Ready(Dispatched::Shutdown)) } else { Ok(Async::NotReady) } diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -190,20 +195,18 @@ where } // dispatch is ready for a message, try to read one match self.conn.read_head() { - Ok(Async::Ready(Some((head, body_len)))) => { - let body = if let Some(body_len) = body_len { - let (mut tx, rx) = - Body::new_channel(if let BodyLength::Known(len) = body_len { - Some(len) - } else { - None - }); - let _ = tx.poll_ready(); // register this task if rx is dropped - self.body_tx = Some(tx); - rx - } else { - Body::empty() + Ok(Async::Ready(Some((head, body_len, wants_upgrade)))) => { + let mut body = match body_len { + DecodedLength::ZERO => Body::empty(), + other => { + let (tx, rx) = Body::new_channel(other.into_opt()); + self.body_tx = Some(tx); + rx + }, }; + if wants_upgrade { + body.set_on_upgrade(self.conn.on_upgrade()); + } self.dispatch.recv_msg(Ok((head, body)))?; Ok(Async::Ready(())) } diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -326,7 +329,6 @@ where } } - impl<D, Bs, I, T> Future for Dispatcher<D, Bs, I, T> where D: Dispatch<PollItem=MessageHead<T::Outgoing>, PollBody=Bs, RecvItem=MessageHead<T::Incoming>>, diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -334,12 +336,12 @@ where T: Http1Transaction, Bs: Payload, { - type Item = (); + type Item = Dispatched; type Error = ::Error; #[inline] fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - self.poll_until_shutdown() + self.poll_catch(true) } } diff --git a/src/proto/h1/mod.rs b/src/proto/h1/mod.rs --- a/src/proto/h1/mod.rs +++ b/src/proto/h1/mod.rs @@ -1,7 +1,7 @@ use bytes::BytesMut; use http::{HeaderMap, Method}; -use proto::{MessageHead, BodyLength}; +use proto::{MessageHead, BodyLength, DecodedLength}; pub(crate) use self::conn::Conn; pub(crate) use self::dispatch::Dispatcher; diff --git a/src/proto/h1/mod.rs b/src/proto/h1/mod.rs --- a/src/proto/h1/mod.rs +++ b/src/proto/h1/mod.rs @@ -19,12 +19,8 @@ mod io; mod role; -pub(crate) type ServerTransaction = self::role::Server<self::role::YesUpgrades>; -//pub type ServerTransaction = self::role::Server<self::role::NoUpgrades>; -//pub type ServerUpgradeTransaction = self::role::Server<self::role::YesUpgrades>; - -pub(crate) type ClientTransaction = self::role::Client<self::role::NoUpgrades>; -pub(crate) type ClientUpgradeTransaction = self::role::Client<self::role::YesUpgrades>; +pub(crate) type ServerTransaction = role::Server; +pub(crate) type ClientTransaction = role::Client; pub(crate) trait Http1Transaction { type Incoming; diff --git a/src/proto/h1/mod.rs b/src/proto/h1/mod.rs --- a/src/proto/h1/mod.rs +++ b/src/proto/h1/mod.rs @@ -40,14 +36,16 @@ pub(crate) trait Http1Transaction { fn update_date() {} } +/// Result newtype for Http1Transaction::parse. pub(crate) type ParseResult<T> = Result<Option<ParsedMessage<T>>, ::error::Parse>; #[derive(Debug)] pub(crate) struct ParsedMessage<T> { head: MessageHead<T>, - decode: Decode, + decode: DecodedLength, expect_continue: bool, keep_alive: bool, + wants_upgrade: bool, } pub(crate) struct ParseContext<'a> { diff --git a/src/proto/h1/mod.rs b/src/proto/h1/mod.rs --- a/src/proto/h1/mod.rs +++ b/src/proto/h1/mod.rs @@ -64,12 +62,3 @@ pub(crate) struct Encode<'a, T: 'a> { title_case_headers: bool, } -#[derive(Debug, PartialEq)] -pub enum Decode { - /// Decode normally. - Normal(Decoder), - /// After this decoder is done, HTTP is done. - Final(Decoder), - /// A header block that should be ignored, like unknown 1xx responses. - Ignore, -} diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -8,25 +8,19 @@ use httparse; use error::Parse; use headers; -use proto::{BodyLength, MessageHead, RequestLine, RequestHead}; -use proto::h1::{Decode, Decoder, Encode, Encoder, Http1Transaction, ParseResult, ParseContext, ParsedMessage, date}; +use proto::{BodyLength, DecodedLength, MessageHead, RequestLine, RequestHead}; +use proto::h1::{Encode, Encoder, Http1Transaction, ParseResult, ParseContext, ParsedMessage, date}; const MAX_HEADERS: usize = 100; const AVERAGE_HEADER_SIZE: usize = 30; // totally scientific // There are 2 main roles, Client and Server. -// -// There is 1 modifier, OnUpgrade, which can wrap Client and Server, -// to signal that HTTP upgrades are not supported. -pub(crate) struct Client<T>(T); +pub(crate) enum Client {} -pub(crate) struct Server<T>(T); +pub(crate) enum Server {} -impl<T> Http1Transaction for Server<T> -where - T: OnUpgrade, -{ +impl Http1Transaction for Server { type Incoming = RequestLine; type Outgoing = StatusCode; diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -34,31 +28,45 @@ where if buf.len() == 0 { return Ok(None); } + + let mut keep_alive; + let is_http_11; + let subject; + let version; + let len; + let headers_len; + // Unsafe: both headers_indices and headers are using unitialized memory, // but we *never* read any of it until after httparse has assigned // values into it. By not zeroing out the stack memory, this saves // a good ~5% on pipeline benchmarks. let mut headers_indices: [HeaderIndices; MAX_HEADERS] = unsafe { mem::uninitialized() }; - let (len, subject, version, headers_len) = { + { let mut headers: [httparse::Header; MAX_HEADERS] = unsafe { mem::uninitialized() }; trace!("Request.parse([Header; {}], [u8; {}])", headers.len(), buf.len()); let mut req = httparse::Request::new(&mut headers); let bytes = buf.as_ref(); match req.parse(bytes)? { - httparse::Status::Complete(len) => { - trace!("Request.parse Complete({})", len); - let method = Method::from_bytes(req.method.unwrap().as_bytes())?; - let path = req.path.unwrap().parse()?; - let subject = RequestLine(method, path); - let version = if req.version.unwrap() == 1 { + httparse::Status::Complete(parsed_len) => { + trace!("Request.parse Complete({})", parsed_len); + len = parsed_len; + subject = RequestLine( + Method::from_bytes(req.method.unwrap().as_bytes())?, + req.path.unwrap().parse()? + ); + version = if req.version.unwrap() == 1 { + keep_alive = true; + is_http_11 = true; Version::HTTP_11 } else { + keep_alive = false; + is_http_11 = false; Version::HTTP_10 }; record_header_indices(bytes, &req.headers, &mut headers_indices); - let headers_len = req.headers.len(); - (len, subject, version, headers_len) + headers_len = req.headers.len(); + //(len, subject, version, headers_len) } httparse::Status::Partial => return Ok(None), } diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -76,12 +84,12 @@ where // 7. (irrelevant to Request) - let mut decoder = None; + let mut decoder = DecodedLength::ZERO; let mut expect_continue = false; - let mut keep_alive = version == Version::HTTP_11; let mut con_len = None; let mut is_te = false; let mut is_te_chunked = false; + let mut wants_upgrade = subject.0 == Method::CONNECT; let mut headers = ctx.cached_headers .take() diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -104,16 +112,14 @@ where // If Transfer-Encoding header is present, and 'chunked' is // not the final encoding, and this is a Request, then it is // mal-formed. A server should respond with 400 Bad Request. - if version == Version::HTTP_10 { + if !is_http_11 { debug!("HTTP/1.0 cannot have Transfer-Encoding header"); return Err(Parse::Header); } is_te = true; if headers::is_chunked_(&value) { is_te_chunked = true; - decoder = Some(Decoder::chunked()); - //debug!("request with transfer-encoding header, but not chunked, bad request"); - //return Err(Parse::Header); + decoder = DecodedLength::CHUNKED; } }, header::CONTENT_LENGTH => { diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -135,8 +141,8 @@ where // we don't need to append this secondary length continue; } + decoder = DecodedLength::checked_new(len)?; con_len = Some(len); - decoder = Some(Decoder::length(len)); }, header::CONNECTION => { // keep_alive was previously set to default for Version diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -152,6 +158,10 @@ where header::EXPECT => { expect_continue = value.as_bytes() == b"100-continue"; }, + header::UPGRADE => { + // Upgrades are only allowed with HTTP/1.1 + wants_upgrade = is_http_11; + }, _ => (), } diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -159,15 +169,10 @@ where headers.append(name, value); } - let decoder = if let Some(decoder) = decoder { - decoder - } else { - if is_te && !is_te_chunked { - debug!("request with transfer-encoding header, but not chunked, bad request"); - return Err(Parse::Header); - } - Decoder::length(0) - }; + if is_te && !is_te_chunked { + debug!("request with transfer-encoding header, but not chunked, bad request"); + return Err(Parse::Header); + } *ctx.req_method = Some(subject.0.clone()); diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -177,9 +182,10 @@ where subject, headers, }, - decode: Decode::Normal(decoder), + decode: decoder, expect_continue, keep_alive, + wants_upgrade, })) } diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -194,7 +200,7 @@ where let is_upgrade = msg.head.subject == StatusCode::SWITCHING_PROTOCOLS || (msg.req_method == &Some(Method::CONNECT) && msg.head.subject.is_success()); let (ret, mut is_last) = if is_upgrade { - (T::on_encode_upgrade(&mut msg), true) + (Ok(()), true) } else if msg.head.subject.is_informational() { error!("response with 1xx status code not supported"); *msg.head = MessageHead::default(); diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -485,7 +491,7 @@ where } } -impl Server<()> { +impl Server { fn can_have_body(method: &Option<Method>, status: StatusCode) -> bool { Server::can_chunked(method, status) } diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -508,65 +514,69 @@ impl Server<()> { } } -impl<T> Http1Transaction for Client<T> -where - T: OnUpgrade, -{ +impl Http1Transaction for Client { type Incoming = StatusCode; type Outgoing = RequestLine; fn parse(buf: &mut BytesMut, ctx: ParseContext) -> ParseResult<StatusCode> { - if buf.len() == 0 { - return Ok(None); - } - // Unsafe: see comment in Server Http1Transaction, above. - let mut headers_indices: [HeaderIndices; MAX_HEADERS] = unsafe { mem::uninitialized() }; - let (len, status, version, headers_len) = { - let mut headers: [httparse::Header; MAX_HEADERS] = unsafe { mem::uninitialized() }; - trace!("Response.parse([Header; {}], [u8; {}])", headers.len(), buf.len()); - let mut res = httparse::Response::new(&mut headers); - let bytes = buf.as_ref(); - match res.parse(bytes)? { - httparse::Status::Complete(len) => { - trace!("Response.parse Complete({})", len); - let status = StatusCode::from_u16(res.code.unwrap())?; - let version = if res.version.unwrap() == 1 { - Version::HTTP_11 - } else { - Version::HTTP_10 - }; - record_header_indices(bytes, &res.headers, &mut headers_indices); - let headers_len = res.headers.len(); - (len, status, version, headers_len) - }, - httparse::Status::Partial => return Ok(None), + // Loop to skip information status code headers (100 Continue, etc). + loop { + if buf.len() == 0 { + return Ok(None); } - }; + // Unsafe: see comment in Server Http1Transaction, above. + let mut headers_indices: [HeaderIndices; MAX_HEADERS] = unsafe { mem::uninitialized() }; + let (len, status, version, headers_len) = { + let mut headers: [httparse::Header; MAX_HEADERS] = unsafe { mem::uninitialized() }; + trace!("Response.parse([Header; {}], [u8; {}])", headers.len(), buf.len()); + let mut res = httparse::Response::new(&mut headers); + let bytes = buf.as_ref(); + match res.parse(bytes)? { + httparse::Status::Complete(len) => { + trace!("Response.parse Complete({})", len); + let status = StatusCode::from_u16(res.code.unwrap())?; + let version = if res.version.unwrap() == 1 { + Version::HTTP_11 + } else { + Version::HTTP_10 + }; + record_header_indices(bytes, &res.headers, &mut headers_indices); + let headers_len = res.headers.len(); + (len, status, version, headers_len) + }, + httparse::Status::Partial => return Ok(None), + } + }; - let slice = buf.split_to(len).freeze(); + let slice = buf.split_to(len).freeze(); - let mut headers = ctx.cached_headers - .take() - .unwrap_or_else(HeaderMap::new); + let mut headers = ctx.cached_headers + .take() + .unwrap_or_else(HeaderMap::new); - headers.reserve(headers_len); - fill_headers(&mut headers, slice, &headers_indices[..headers_len]); + headers.reserve(headers_len); + fill_headers(&mut headers, slice, &headers_indices[..headers_len]); - let keep_alive = version == Version::HTTP_11; + let keep_alive = version == Version::HTTP_11; - let head = MessageHead { - version, - subject: status, - headers, - }; - let decode = Client::<T>::decoder(&head, ctx.req_method)?; + let head = MessageHead { + version, + subject: status, + headers, + }; + if let Some((decode, is_upgrade)) = Client::decoder(&head, ctx.req_method)? { + return Ok(Some(ParsedMessage { + head, + decode, + expect_continue: false, + // a client upgrade means the connection can't be used + // again, as it is definitely upgrading. + keep_alive: keep_alive && !is_upgrade, + wants_upgrade: is_upgrade, + })); + } - Ok(Some(ParsedMessage { - head, - decode, - expect_continue: false, - keep_alive, - })) + } } fn encode(msg: Encode<Self::Outgoing>, dst: &mut Vec<u8>) -> ::Result<Encoder> { diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -617,8 +627,11 @@ where } } -impl<T: OnUpgrade> Client<T> { - fn decoder(inc: &MessageHead<StatusCode>, method: &mut Option<Method>) -> Result<Decode, Parse> { +impl Client { + /// Returns Some(length, wants_upgrade) if successful. + /// + /// Returns None if this message head should be skipped (like a 100 status). + fn decoder(inc: &MessageHead<StatusCode>, method: &mut Option<Method>) -> Result<Option<(DecodedLength, bool)>, Parse> { // According to https://tools.ietf.org/html/rfc7230#section-3.3.3 // 1. HEAD responses, and Status 1xx, 204, and 304 cannot have a body. // 2. Status 2xx to a CONNECT cannot have a body. diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -630,23 +643,23 @@ impl<T: OnUpgrade> Client<T> { match inc.subject.as_u16() { 101 => { - return T::on_decode_upgrade().map(Decode::Final); + return Ok(Some((DecodedLength::ZERO, true))); }, 100...199 => { trace!("ignoring informational response: {}", inc.subject.as_u16()); - return Ok(Decode::Ignore); + return Ok(None); }, 204 | - 304 => return Ok(Decode::Normal(Decoder::length(0))), + 304 => return Ok(Some((DecodedLength::ZERO, false))), _ => (), } match *method { Some(Method::HEAD) => { - return Ok(Decode::Normal(Decoder::length(0))); + return Ok(Some((DecodedLength::ZERO, false))); } Some(Method::CONNECT) => match inc.subject.as_u16() { 200...299 => { - return Ok(Decode::Final(Decoder::length(0))); + return Ok(Some((DecodedLength::ZERO, true))); }, _ => {}, }, diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -665,24 +678,24 @@ impl<T: OnUpgrade> Client<T> { debug!("HTTP/1.0 cannot have Transfer-Encoding header"); Err(Parse::Header) } else if headers::transfer_encoding_is_chunked(&inc.headers) { - Ok(Decode::Normal(Decoder::chunked())) + Ok(Some((DecodedLength::CHUNKED, false))) } else { trace!("not chunked, read till eof"); - Ok(Decode::Normal(Decoder::eof())) + Ok(Some((DecodedLength::CHUNKED, false))) } } else if let Some(len) = headers::content_length_parse_all(&inc.headers) { - Ok(Decode::Normal(Decoder::length(len))) + Ok(Some((DecodedLength::checked_new(len)?, false))) } else if inc.headers.contains_key(header::CONTENT_LENGTH) { debug!("illegal Content-Length header"); Err(Parse::Header) } else { trace!("neither Transfer-Encoding nor Content-Length"); - Ok(Decode::Normal(Decoder::eof())) + Ok(Some((DecodedLength::CLOSE_DELIMITED, false))) } } } -impl Client<()> { +impl Client { fn set_length(head: &mut RequestHead, body: Option<BodyLength>) -> Encoder { if let Some(body) = body { let can_chunked = head.version == Version::HTTP_11 diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -830,51 +843,6 @@ fn set_content_length(headers: &mut HeaderMap, len: u64) -> Encoder { } } -pub(crate) trait OnUpgrade { - fn on_encode_upgrade(msg: &mut Encode<StatusCode>) -> ::Result<()>; - fn on_decode_upgrade() -> Result<Decoder, Parse>; -} - -pub(crate) enum YesUpgrades {} - -pub(crate) enum NoUpgrades {} - -impl OnUpgrade for YesUpgrades { - fn on_encode_upgrade(_: &mut Encode<StatusCode>) -> ::Result<()> { - Ok(()) - } - - fn on_decode_upgrade() -> Result<Decoder, Parse> { - debug!("101 response received, upgrading"); - // 101 upgrades always have no body - Ok(Decoder::length(0)) - } -} - -impl OnUpgrade for NoUpgrades { - fn on_encode_upgrade(msg: &mut Encode<StatusCode>) -> ::Result<()> { - *msg.head = MessageHead::default(); - msg.head.subject = ::StatusCode::INTERNAL_SERVER_ERROR; - msg.body = None; - - if msg.head.subject == StatusCode::SWITCHING_PROTOCOLS { - error!("response with 101 status code not supported"); - Err(Parse::UpgradeNotSupported.into()) - } else if msg.req_method == &Some(Method::CONNECT) { - error!("200 response to CONNECT request not supported"); - Err(::Error::new_user_unsupported_request_method()) - } else { - debug_assert!(false, "upgrade incorrectly detected"); - Err(::Error::new_status()) - } - } - - fn on_decode_upgrade() -> Result<Decoder, Parse> { - debug!("received 101 upgrade response, not supported"); - Err(Parse::UpgradeNotSupported) - } -} - #[derive(Clone, Copy)] struct HeaderIndices { name: (usize, usize), diff --git a/src/proto/h2/client.rs b/src/proto/h2/client.rs --- a/src/proto/h2/client.rs +++ b/src/proto/h2/client.rs @@ -8,6 +8,7 @@ use tokio_io::{AsyncRead, AsyncWrite}; use body::Payload; use ::common::{Exec, Never}; use headers; +use ::proto::Dispatched; use super::{PipeToSendStream, SendBuf}; use ::{Body, Request, Response}; diff --git a/src/proto/h2/client.rs b/src/proto/h2/client.rs --- a/src/proto/h2/client.rs +++ b/src/proto/h2/client.rs @@ -16,7 +17,7 @@ type ClientRx<B> = ::client::dispatch::Receiver<Request<B>, Response<Body>>; /// other handles to it have been dropped, so that it can shutdown. type ConnDropRef = mpsc::Sender<Never>; -pub struct Client<T, B> +pub(crate) struct Client<T, B> where B: Payload, { diff --git a/src/proto/h2/client.rs b/src/proto/h2/client.rs --- a/src/proto/h2/client.rs +++ b/src/proto/h2/client.rs @@ -54,7 +55,7 @@ where T: AsyncRead + AsyncWrite + Send + 'static, B: Payload + 'static, { - type Item = (); + type Item = Dispatched; type Error = ::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { diff --git a/src/proto/h2/client.rs b/src/proto/h2/client.rs --- a/src/proto/h2/client.rs +++ b/src/proto/h2/client.rs @@ -153,7 +154,7 @@ where Ok(Async::Ready(None)) | Err(_) => { trace!("client::dispatch::Sender dropped"); - return Ok(Async::Ready(())); + return Ok(Async::Ready(Dispatched::Shutdown)); } } }, diff --git a/src/proto/h2/server.rs b/src/proto/h2/server.rs --- a/src/proto/h2/server.rs +++ b/src/proto/h2/server.rs @@ -7,6 +7,7 @@ use ::body::Payload; use ::common::Exec; use ::headers; use ::service::Service; +use ::proto::Dispatched; use super::{PipeToSendStream, SendBuf}; use ::{Body, Response}; diff --git a/src/proto/h2/server.rs b/src/proto/h2/server.rs --- a/src/proto/h2/server.rs +++ b/src/proto/h2/server.rs @@ -82,7 +83,7 @@ where S::Future: Send + 'static, B: Payload, { - type Item = (); + type Item = Dispatched; type Error = ::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { diff --git a/src/proto/h2/server.rs b/src/proto/h2/server.rs --- a/src/proto/h2/server.rs +++ b/src/proto/h2/server.rs @@ -95,12 +96,13 @@ where }) }, State::Serving(ref mut srv) => { - return srv.poll_server(&mut self.service, &self.exec); + try_ready!(srv.poll_server(&mut self.service, &self.exec)); + return Ok(Async::Ready(Dispatched::Shutdown)); } State::Closed => { // graceful_shutdown was called before handshaking finished, // nothing to do here... - return Ok(Async::Ready(())); + return Ok(Async::Ready(Dispatched::Shutdown)); } }; self.state = next; diff --git a/src/proto/mod.rs b/src/proto/mod.rs --- a/src/proto/mod.rs +++ b/src/proto/mod.rs @@ -1,12 +1,12 @@ //! Pieces pertaining to the HTTP message protocol. use http::{HeaderMap, Method, StatusCode, Uri, Version}; -pub(crate) use self::h1::{dispatch, Conn, ClientTransaction, ClientUpgradeTransaction, ServerTransaction}; +pub(crate) use self::h1::{dispatch, Conn, ServerTransaction}; +use self::body_length::DecodedLength; pub(crate) mod h1; pub(crate) mod h2; - /// An Incoming Message head. Includes request/status line, and headers. #[derive(Clone, Debug, Default, PartialEq)] pub struct MessageHead<S> { diff --git a/src/proto/mod.rs b/src/proto/mod.rs --- a/src/proto/mod.rs +++ b/src/proto/mod.rs @@ -27,34 +27,6 @@ pub struct RequestLine(pub Method, pub Uri); /// An incoming response message. pub type ResponseHead = MessageHead<StatusCode>; -/* -impl<S> MessageHead<S> { - pub fn should_keep_alive(&self) -> bool { - should_keep_alive(self.version, &self.headers) - } - - pub fn expecting_continue(&self) -> bool { - expecting_continue(self.version, &self.headers) - } -} - -/// Checks if a connection should be kept alive. -#[inline] -pub fn should_keep_alive(version: Version, headers: &HeaderMap) -> bool { - if version == Version::HTTP_10 { - headers::connection_keep_alive(headers) - } else { - !headers::connection_close(headers) - } -} - -/// Checks if a connection is expecting a `100 Continue` before sending its body. -#[inline] -pub fn expecting_continue(version: Version, headers: &HeaderMap) -> bool { - version == Version::HTTP_11 && headers::expect_continue(headers) -} -*/ - #[derive(Debug)] pub enum BodyLength { /// Content-Length diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -9,22 +9,26 @@ //! higher-level [Server](super) API. use std::fmt; +use std::mem; #[cfg(feature = "runtime")] use std::net::SocketAddr; use std::sync::Arc; #[cfg(feature = "runtime")] use std::time::Duration; -use super::rewind::Rewind; use bytes::Bytes; use futures::{Async, Future, Poll, Stream}; use futures::future::{Either, Executor}; use tokio_io::{AsyncRead, AsyncWrite}; #[cfg(feature = "runtime")] use tokio_reactor::Handle; +use body::{Body, Payload}; use common::Exec; +use common::io::Rewind; +use error::{Kind, Parse}; use proto; -use body::{Body, Payload}; use service::{NewService, Service}; -use error::{Kind, Parse}; +use upgrade::Upgraded; + +use self::upgrades::UpgradeableConnection; #[cfg(feature = "runtime")] pub use super::tcp::AddrIncoming; diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -109,6 +113,8 @@ where fallback: bool, } + + /// Deconstructed parts of a `Connection`. /// /// This allows taking apart a `Connection` at a later time, in order to diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -429,7 +435,7 @@ where loop { let polled = match *self.conn.as_mut().unwrap() { Either::A(ref mut h1) => h1.poll_without_shutdown(), - Either::B(ref mut h2) => h2.poll(), + Either::B(ref mut h2) => return h2.poll().map(|x| x.map(|_| ())), }; match polled { Ok(x) => return Ok(x), diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -466,6 +472,18 @@ where debug_assert!(self.conn.is_none()); self.conn = Some(Either::B(h2)); } + + /// Enable this connection to support higher-level HTTP upgrades. + /// + /// See [the `upgrade` module](::upgrade) for more. + pub fn with_upgrades(self) -> UpgradeableConnection<I, S> + where + I: Send, + { + UpgradeableConnection { + inner: self, + } + } } impl<I, B, S> Future for Connection<I, S> diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -482,7 +500,15 @@ where fn poll(&mut self) -> Poll<Self::Item, Self::Error> { loop { match self.conn.poll() { - Ok(x) => return Ok(x.map(|o| o.unwrap_or_else(|| ()))), + Ok(x) => return Ok(x.map(|opt| { + if let Some(proto::Dispatched::Upgrade(pending)) = opt { + // With no `Send` bound on `I`, we can't try to do + // upgrades here. In case a user was trying to use + // `Body::on_upgrade` with this API, send a special + // error letting them know about that. + pending.manual(); + } + })), Err(e) => { debug!("error polling connection protocol: {}", e); match *e.kind() { diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -507,7 +533,6 @@ where .finish() } } - // ===== impl Serve ===== impl<I, S> Serve<I, S> { diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -614,7 +639,7 @@ where let fut = connecting .map_err(::Error::new_user_new_service) // flatten basically - .and_then(|conn| conn) + .and_then(|conn| conn.with_upgrades()) .map_err(|err| debug!("conn error: {}", err)); self.serve.protocol.exec.execute(fut); } else { diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -623,3 +648,82 @@ where } } } + +mod upgrades { + use super::*; + + // A future binding a connection with a Service with Upgrade support. + // + // This type is unnameable outside the crate, and so basically just an + // `impl Future`, without requiring Rust 1.26. + #[must_use = "futures do nothing unless polled"] + #[allow(missing_debug_implementations)] + pub struct UpgradeableConnection<T, S> + where + S: Service, + { + pub(super) inner: Connection<T, S>, + } + + impl<I, B, S> UpgradeableConnection<I, S> + where + S: Service<ReqBody=Body, ResBody=B> + 'static, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + S::Future: Send, + I: AsyncRead + AsyncWrite + Send + 'static, + B: Payload + 'static, + { + /// Start a graceful shutdown process for this connection. + /// + /// This `Connection` should continue to be polled until shutdown + /// can finish. + pub fn graceful_shutdown(&mut self) { + self.inner.graceful_shutdown() + } + } + + impl<I, B, S> Future for UpgradeableConnection<I, S> + where + S: Service<ReqBody=Body, ResBody=B> + 'static, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + S::Future: Send, + I: AsyncRead + AsyncWrite + Send + 'static, + B: Payload + 'static, + { + type Item = (); + type Error = ::Error; + + fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + loop { + match self.inner.conn.poll() { + Ok(Async::NotReady) => return Ok(Async::NotReady), + Ok(Async::Ready(Some(proto::Dispatched::Shutdown))) | + Ok(Async::Ready(None)) => { + return Ok(Async::Ready(())); + }, + Ok(Async::Ready(Some(proto::Dispatched::Upgrade(pending)))) => { + let h1 = match mem::replace(&mut self.inner.conn, None) { + Some(Either::A(h1)) => h1, + _ => unreachable!("Upgrade expects h1"), + }; + + let (io, buf, _) = h1.into_inner(); + pending.fulfill(Upgraded::new(Box::new(io), buf)); + return Ok(Async::Ready(())); + }, + Err(e) => { + debug!("error polling connection protocol: {}", e); + match *e.kind() { + Kind::Parse(Parse::VersionH2) if self.inner.fallback => { + self.inner.upgrade_h2(); + continue; + } + _ => return Err(e), + } + } + } + } + } + } +} + diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -50,7 +50,6 @@ pub mod conn; #[cfg(feature = "runtime")] mod tcp; -mod rewind; use std::fmt; #[cfg(feature = "runtime")] use std::net::SocketAddr; diff --git /dev/null b/src/upgrade.rs new file mode 100644 --- /dev/null +++ b/src/upgrade.rs @@ -0,0 +1,254 @@ +//! HTTP Upgrades +//! +//! See [this example][example] showing how upgrades work with both +//! Clients and Servers. +//! +//! [example]: https://github.com/hyperium/hyper/master/examples/upgrades.rs + +use std::any::TypeId; +use std::error::Error as StdError; +use std::fmt; +use std::io::{self, Read, Write}; + +use bytes::{Buf, BufMut, Bytes}; +use futures::{Async, Future, Poll}; +use futures::sync::oneshot; +use tokio_io::{AsyncRead, AsyncWrite}; + +use common::io::Rewind; + +/// An upgraded HTTP connection. +/// +/// This type holds a trait object internally of the original IO that +/// was used to speak HTTP before the upgrade. It can be used directly +/// as a `Read` or `Write` for convenience. +/// +/// Alternatively, if the exact type is known, this can be deconstructed +/// into its parts. +pub struct Upgraded { + io: Rewind<Box<Io + Send>>, +} + +/// A future for a possible HTTP upgrade. +/// +/// If no upgrade was available, or it doesn't succeed, yields an `Error`. +pub struct OnUpgrade { + rx: Option<oneshot::Receiver<::Result<Upgraded>>>, +} + +/// The deconstructed parts of an [`Upgraded`](Upgraded) type. +/// +/// Includes the original IO type, and a read buffer of bytes that the +/// HTTP state machine may have already read before completing an upgrade. +#[derive(Debug)] +pub struct Parts<T> { + /// The original IO object used before the upgrade. + pub io: T, + /// A buffer of bytes that have been read but not processed as HTTP. + /// + /// For instance, if the `Connection` is used for an HTTP upgrade request, + /// it is possible the server sent back the first bytes of the new protocol + /// along with the response upgrade. + /// + /// You will want to check for any existing bytes if you plan to continue + /// communicating on the IO object. + pub read_buf: Bytes, + _inner: (), +} + +pub(crate) struct Pending { + tx: oneshot::Sender<::Result<Upgraded>> +} + +/// Error cause returned when an upgrade was expected but canceled +/// for whatever reason. +/// +/// This likely means the actual `Conn` future wasn't polled and upgraded. +#[derive(Debug)] +struct UpgradeExpected(()); + +pub(crate) fn pending() -> (Pending, OnUpgrade) { + let (tx, rx) = oneshot::channel(); + ( + Pending { + tx, + }, + OnUpgrade { + rx: Some(rx), + }, + ) +} + +pub(crate) trait Io: AsyncRead + AsyncWrite + 'static { + fn __hyper_type_id(&self) -> TypeId { + TypeId::of::<Self>() + } +} + +impl Io + Send { + fn __hyper_is<T: Io>(&self) -> bool { + let t = TypeId::of::<T>(); + self.__hyper_type_id() == t + } + + fn __hyper_downcast<T: Io>(self: Box<Self>) -> Result<Box<T>, Box<Self>> { + if self.__hyper_is::<T>() { + // Taken from `std::error::Error::downcast()`. + unsafe { + let raw: *mut Io = Box::into_raw(self); + Ok(Box::from_raw(raw as *mut T)) + } + } else { + Err(self) + } + } +} + +impl<T: AsyncRead + AsyncWrite + 'static> Io for T {} + +// ===== impl Upgraded ===== + +impl Upgraded { + pub(crate) fn new(io: Box<Io + Send>, read_buf: Bytes) -> Self { + Upgraded { + io: Rewind::new_buffered(io, read_buf), + } + } + + /// Tries to downcast the internal trait object to the type passed. + /// + /// On success, returns the downcasted parts. On error, returns the + /// `Upgraded` back. + pub fn downcast<T: AsyncRead + AsyncWrite + 'static>(self) -> Result<Parts<T>, Self> { + let (io, buf) = self.io.into_inner(); + match io.__hyper_downcast() { + Ok(t) => Ok(Parts { + io: *t, + read_buf: buf, + _inner: (), + }), + Err(io) => Err(Upgraded { + io: Rewind::new_buffered(io, buf), + }) + } + } +} + +impl Read for Upgraded { + #[inline] + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.io.read(buf) + } +} + +impl Write for Upgraded { + #[inline] + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.io.write(buf) + } + + #[inline] + fn flush(&mut self) -> io::Result<()> { + self.io.flush() + } +} + +impl AsyncRead for Upgraded { + #[inline] + unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool { + self.io.prepare_uninitialized_buffer(buf) + } + + #[inline] + fn read_buf<B: BufMut>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { + self.io.read_buf(buf) + } +} + +impl AsyncWrite for Upgraded { + #[inline] + fn shutdown(&mut self) -> Poll<(), io::Error> { + AsyncWrite::shutdown(&mut self.io) + } + + #[inline] + fn write_buf<B: Buf>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { + self.io.write_buf(buf) + } +} + +impl fmt::Debug for Upgraded { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Upgraded") + .finish() + } +} + +// ===== impl OnUpgrade ===== + +impl OnUpgrade { + pub(crate) fn none() -> Self { + OnUpgrade { + rx: None, + } + } + + pub(crate) fn is_none(&self) -> bool { + self.rx.is_none() + } +} + +impl Future for OnUpgrade { + type Item = Upgraded; + type Error = ::Error; + + fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + match self.rx { + Some(ref mut rx) => match rx.poll() { + Ok(Async::NotReady) => Ok(Async::NotReady), + Ok(Async::Ready(Ok(upgraded))) => Ok(Async::Ready(upgraded)), + Ok(Async::Ready(Err(err))) => Err(err), + Err(_oneshot_canceled) => Err( + ::Error::new_canceled(Some(UpgradeExpected(()))) + ), + }, + None => Err(::Error::new_user_no_upgrade()), + } + } +} + +impl fmt::Debug for OnUpgrade { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("OnUpgrade") + .finish() + } +} + +// ===== impl Pending ===== + +impl Pending { + pub(crate) fn fulfill(self, upgraded: Upgraded) { + let _ = self.tx.send(Ok(upgraded)); + } + + /// Don't fulfill the pending Upgrade, but instead signal that + /// upgrades are handled manually. + pub(crate) fn manual(self) { + let _ = self.tx.send(Err(::Error::new_user_manual_upgrade())); + } +} + +// ===== impl UpgradeExpected ===== + +impl fmt::Display for UpgradeExpected { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(self.description()) + } +} + +impl StdError for UpgradeExpected { + fn description(&self) -> &str { + "upgrade expected but not completed" + } +} +
diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -612,6 +598,10 @@ where I: AsyncRead + AsyncWrite, } } + pub(super) fn on_upgrade(&mut self) -> ::upgrade::OnUpgrade { + self.state.prepare_upgrade() + } + // Used in h1::dispatch tests #[cfg(test)] pub(super) fn io_mut(&mut self) -> &mut I { diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -821,11 +814,53 @@ impl State { _ => false } } + + fn prepare_upgrade(&mut self) -> ::upgrade::OnUpgrade { + trace!("prepare possible HTTP upgrade"); + debug_assert!(self.upgrade.is_none()); + let (tx, rx) = ::upgrade::pending(); + self.upgrade = Some(tx); + rx + } } #[cfg(test)] //TODO: rewrite these using dispatch mod tests { + + #[cfg(feature = "nightly")] + #[bench] + fn bench_read_head_short(b: &mut ::test::Bencher) { + use super::*; + let s = b"GET / HTTP/1.1\r\nHost: localhost:8080\r\n\r\n"; + let len = s.len(); + b.bytes = len as u64; + + let mut io = ::mock::AsyncIo::new_buf(Vec::new(), 0); + io.panic(); + let mut conn = Conn::<_, ::Chunk, ::proto::h1::ServerTransaction>::new(io); + *conn.io.read_buf_mut() = ::bytes::BytesMut::from(&s[..]); + conn.state.cached_headers = Some(HeaderMap::with_capacity(2)); + + b.iter(|| { + match conn.read_head().unwrap() { + Async::Ready(Some(x)) => { + ::test::black_box(&x); + let mut headers = x.0.headers; + headers.clear(); + conn.state.cached_headers = Some(headers); + }, + f => panic!("expected Ready(Some(..)): {:?}", f) + } + + + conn.io.read_buf_mut().reserve(1); + unsafe { + conn.io.read_buf_mut().set_len(len); + } + conn.state.reading = Reading::Init; + }); + } /* use futures::{Async, Future, Stream, Sink}; use futures::future; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -519,7 +521,7 @@ mod tests { use super::*; use mock::AsyncIo; - use proto::ClientTransaction; + use proto::h1::ClientTransaction; #[test] fn client_read_bytes_before_writing_request() { diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -93,6 +93,12 @@ where self.read_buf.as_ref() } + #[cfg(test)] + #[cfg(feature = "nightly")] + pub(super) fn read_buf_mut(&mut self) -> &mut BytesMut { + &mut self.read_buf + } + pub fn headers_buf(&mut self) -> &mut Vec<u8> { let buf = self.write_buf.headers_mut(); &mut buf.bytes diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -595,7 +601,7 @@ mod tests { cached_headers: &mut None, req_method: &mut None, }; - assert!(buffered.parse::<::proto::ClientTransaction>(ctx).unwrap().is_not_ready()); + assert!(buffered.parse::<::proto::h1::ClientTransaction>(ctx).unwrap().is_not_ready()); assert!(buffered.io.blocked()); } diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -978,10 +946,6 @@ mod tests { use bytes::BytesMut; use super::*; - use super::{Server as S, Client as C}; - - type Server = S<NoUpgrades>; - type Client = C<NoUpgrades>; #[test] fn test_parse_request() { diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1033,8 +997,6 @@ mod tests { #[test] fn test_decoder_request() { - use super::Decoder; - fn parse(s: &str) -> ParsedMessage<RequestLine> { let mut bytes = BytesMut::from(s); Server::parse(&mut bytes, ParseContext { diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1058,39 +1020,39 @@ mod tests { assert_eq!(parse("\ GET / HTTP/1.1\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::length(0))); + ").decode, DecodedLength::ZERO); assert_eq!(parse("\ POST / HTTP/1.1\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::length(0))); + ").decode, DecodedLength::ZERO); // transfer-encoding: chunked assert_eq!(parse("\ POST / HTTP/1.1\r\n\ transfer-encoding: chunked\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::chunked())); + ").decode, DecodedLength::CHUNKED); assert_eq!(parse("\ POST / HTTP/1.1\r\n\ transfer-encoding: gzip, chunked\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::chunked())); + ").decode, DecodedLength::CHUNKED); assert_eq!(parse("\ POST / HTTP/1.1\r\n\ transfer-encoding: gzip\r\n\ transfer-encoding: chunked\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::chunked())); + ").decode, DecodedLength::CHUNKED); // content-length assert_eq!(parse("\ POST / HTTP/1.1\r\n\ content-length: 10\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::length(10))); + ").decode, DecodedLength::new(10)); // transfer-encoding and content-length = chunked assert_eq!(parse("\ diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1098,14 +1060,14 @@ mod tests { content-length: 10\r\n\ transfer-encoding: chunked\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::chunked())); + ").decode, DecodedLength::CHUNKED); assert_eq!(parse("\ POST / HTTP/1.1\r\n\ transfer-encoding: chunked\r\n\ content-length: 10\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::chunked())); + ").decode, DecodedLength::CHUNKED); assert_eq!(parse("\ POST / HTTP/1.1\r\n\ diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1113,7 +1075,7 @@ mod tests { content-length: 10\r\n\ transfer-encoding: chunked\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::chunked())); + ").decode, DecodedLength::CHUNKED); // multiple content-lengths of same value are fine diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1122,7 +1084,7 @@ mod tests { content-length: 10\r\n\ content-length: 10\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::length(10))); + ").decode, DecodedLength::new(10)); // multiple content-lengths with different values is an error diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1153,7 +1115,7 @@ mod tests { POST / HTTP/1.0\r\n\ content-length: 10\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::length(10))); + ").decode, DecodedLength::new(10)); // 1.0 doesn't understand chunked, so its an error diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1171,6 +1133,16 @@ mod tests { parse_with_method(s, Method::GET) } + fn parse_ignores(s: &str) { + let mut bytes = BytesMut::from(s); + assert!(Client::parse(&mut bytes, ParseContext { + cached_headers: &mut None, + req_method: &mut Some(Method::GET), + }) + .expect("parse ok") + .is_none()) + } + fn parse_with_method(s: &str, m: Method) -> ParsedMessage<StatusCode> { let mut bytes = BytesMut::from(s); Client::parse(&mut bytes, ParseContext { diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1195,32 +1167,32 @@ mod tests { assert_eq!(parse("\ HTTP/1.1 200 OK\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::eof())); + ").decode, DecodedLength::CLOSE_DELIMITED); // 204 and 304 never have a body assert_eq!(parse("\ HTTP/1.1 204 No Content\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::length(0))); + ").decode, DecodedLength::ZERO); assert_eq!(parse("\ HTTP/1.1 304 Not Modified\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::length(0))); + ").decode, DecodedLength::ZERO); // content-length assert_eq!(parse("\ HTTP/1.1 200 OK\r\n\ content-length: 8\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::length(8))); + ").decode, DecodedLength::new(8)); assert_eq!(parse("\ HTTP/1.1 200 OK\r\n\ content-length: 8\r\n\ content-length: 8\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::length(8))); + ").decode, DecodedLength::new(8)); parse_err("\ HTTP/1.1 200 OK\r\n\ diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1235,7 +1207,7 @@ mod tests { HTTP/1.1 200 OK\r\n\ transfer-encoding: chunked\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::chunked())); + ").decode, DecodedLength::CHUNKED); // transfer-encoding and content-length = chunked assert_eq!(parse("\ diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1243,7 +1215,7 @@ mod tests { content-length: 10\r\n\ transfer-encoding: chunked\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::chunked())); + ").decode, DecodedLength::CHUNKED); // HEAD can have content-length, but not body diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1251,44 +1223,54 @@ mod tests { HTTP/1.1 200 OK\r\n\ content-length: 8\r\n\ \r\n\ - ", Method::HEAD).decode, Decode::Normal(Decoder::length(0))); + ", Method::HEAD).decode, DecodedLength::ZERO); // CONNECT with 200 never has body - assert_eq!(parse_with_method("\ - HTTP/1.1 200 OK\r\n\ - \r\n\ - ", Method::CONNECT).decode, Decode::Final(Decoder::length(0))); + { + let msg = parse_with_method("\ + HTTP/1.1 200 OK\r\n\ + \r\n\ + ", Method::CONNECT); + assert_eq!(msg.decode, DecodedLength::ZERO); + assert!(!msg.keep_alive, "should be upgrade"); + assert!(msg.wants_upgrade, "should be upgrade"); + } // CONNECT receiving non 200 can have a body assert_eq!(parse_with_method("\ HTTP/1.1 400 Bad Request\r\n\ \r\n\ - ", Method::CONNECT).decode, Decode::Normal(Decoder::eof())); + ", Method::CONNECT).decode, DecodedLength::CLOSE_DELIMITED); // 1xx status codes - assert_eq!(parse("\ + parse_ignores("\ HTTP/1.1 100 Continue\r\n\ \r\n\ - ").decode, Decode::Ignore); + "); - assert_eq!(parse("\ + parse_ignores("\ HTTP/1.1 103 Early Hints\r\n\ \r\n\ - ").decode, Decode::Ignore); + "); // 101 upgrade not supported yet - parse_err("\ - HTTP/1.1 101 Switching Protocols\r\n\ - \r\n\ - "); + { + let msg = parse("\ + HTTP/1.1 101 Switching Protocols\r\n\ + \r\n\ + "); + assert_eq!(msg.decode, DecodedLength::ZERO); + assert!(!msg.keep_alive, "should be last"); + assert!(msg.wants_upgrade, "should be upgrade"); + } // http/1.0 assert_eq!(parse("\ HTTP/1.0 200 OK\r\n\ \r\n\ - ").decode, Decode::Normal(Decoder::eof())); + ").decode, DecodedLength::CLOSE_DELIMITED); // 1.0 doesn't understand chunked parse_err("\ diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1320,28 +1302,11 @@ mod tests { } #[test] - fn test_server_no_upgrades_connect_method() { - let mut head = MessageHead::default(); - - let mut vec = Vec::new(); - let err = Server::encode(Encode { - head: &mut head, - body: None, - keep_alive: true, - req_method: &mut Some(Method::CONNECT), - title_case_headers: false, - }, &mut vec).unwrap_err(); - - assert!(err.is_user()); - assert_eq!(err.kind(), &::error::Kind::UnsupportedRequestMethod); - } - - #[test] - fn test_server_yes_upgrades_connect_method() { + fn test_server_encode_connect_method() { let mut head = MessageHead::default(); let mut vec = Vec::new(); - let encoder = S::<YesUpgrades>::encode(Encode { + let encoder = Server::encode(Encode { head: &mut head, body: None, keep_alive: true, diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1382,10 +1347,12 @@ mod tests { b.bytes = len as u64; b.iter(|| { - let msg = Server::parse(&mut raw, ParseContext { + let mut msg = Server::parse(&mut raw, ParseContext { cached_headers: &mut headers, req_method: &mut None, }).unwrap().unwrap(); + ::test::black_box(&msg); + msg.head.headers.clear(); headers = Some(msg.head.headers); restart(&mut raw, len); }); diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1402,18 +1369,19 @@ mod tests { #[cfg(feature = "nightly")] #[bench] fn bench_parse_short(b: &mut Bencher) { - let mut raw = BytesMut::from( - b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n".to_vec() - ); + let s = &b"GET / HTTP/1.1\r\nHost: localhost:8080\r\n\r\n"[..]; + let mut raw = BytesMut::from(s.to_vec()); let len = raw.len(); let mut headers = Some(HeaderMap::new()); b.bytes = len as u64; b.iter(|| { - let msg = Server::parse(&mut raw, ParseContext { + let mut msg = Server::parse(&mut raw, ParseContext { cached_headers: &mut headers, req_method: &mut None, }).unwrap().unwrap(); + ::test::black_box(&msg); + msg.head.headers.clear(); headers = Some(msg.head.headers); restart(&mut raw, len); }); diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1480,3 +1448,4 @@ mod tests { }) } } + diff --git a/src/proto/mod.rs b/src/proto/mod.rs --- a/src/proto/mod.rs +++ b/src/proto/mod.rs @@ -63,32 +35,72 @@ pub enum BodyLength { Unknown, } -/* -#[test] -fn test_should_keep_alive() { - let mut headers = HeaderMap::new(); - - assert!(!should_keep_alive(Version::HTTP_10, &headers)); - assert!(should_keep_alive(Version::HTTP_11, &headers)); - - headers.insert("connection", ::http::header::HeaderValue::from_static("close")); - assert!(!should_keep_alive(Version::HTTP_10, &headers)); - assert!(!should_keep_alive(Version::HTTP_11, &headers)); - - headers.insert("connection", ::http::header::HeaderValue::from_static("keep-alive")); - assert!(should_keep_alive(Version::HTTP_10, &headers)); - assert!(should_keep_alive(Version::HTTP_11, &headers)); +/// Status of when an Disaptcher future completes. +pub(crate) enum Dispatched { + /// Dispatcher completely shutdown connection. + Shutdown, + /// Dispatcher has pending upgrade, and so did not shutdown. + Upgrade(::upgrade::Pending), } -#[test] -fn test_expecting_continue() { - let mut headers = HeaderMap::new(); - - assert!(!expecting_continue(Version::HTTP_10, &headers)); - assert!(!expecting_continue(Version::HTTP_11, &headers)); +/// A separate module to encapsulate the invariants of the DecodedLength type. +mod body_length { + use std::fmt; + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) struct DecodedLength(u64); + + const MAX_LEN: u64 = ::std::u64::MAX - 2; + + impl DecodedLength { + pub(crate) const CLOSE_DELIMITED: DecodedLength = DecodedLength(::std::u64::MAX); + pub(crate) const CHUNKED: DecodedLength = DecodedLength(::std::u64::MAX - 1); + pub(crate) const ZERO: DecodedLength = DecodedLength(0); + + #[cfg(test)] + pub(crate) fn new(len: u64) -> Self { + debug_assert!(len <= MAX_LEN); + DecodedLength(len) + } + + /// Takes the length as a content-length without other checks. + /// + /// Should only be called if previously confirmed this isn't + /// CLOSE_DELIMITED or CHUNKED. + #[inline] + pub(crate) fn danger_len(self) -> u64 { + debug_assert!(self.0 < Self::CHUNKED.0); + self.0 + } + + /// Converts to an Option<u64> representing a Known or Unknown length. + pub(crate) fn into_opt(self) -> Option<u64> { + match self { + DecodedLength::CHUNKED | + DecodedLength::CLOSE_DELIMITED => None, + DecodedLength(known) => Some(known) + } + } + + /// Checks the `u64` is within the maximum allowed for content-length. + pub(crate) fn checked_new(len: u64) -> Result<Self, ::error::Parse> { + if len <= MAX_LEN { + Ok(DecodedLength(len)) + } else { + warn!("content-length bigger than maximum: {} > {}", len, MAX_LEN); + Err(::error::Parse::TooLarge) + } + } + } - headers.insert("expect", ::http::header::HeaderValue::from_static("100-continue")); - assert!(!expecting_continue(Version::HTTP_10, &headers)); - assert!(expecting_continue(Version::HTTP_11, &headers)); + impl fmt::Display for DecodedLength { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + DecodedLength::CLOSE_DELIMITED => f.write_str("close-delimited"), + DecodedLength::CHUNKED => f.write_str("chunked encoding"), + DecodedLength::ZERO => f.write_str("empty"), + DecodedLength(n) => write!(f, "content-length ({} bytes)", n), + } + } + } } -*/ diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -596,33 +596,6 @@ test! { body: None, } - -test! { - name: client_101_upgrade, - - server: - expected: "\ - GET /upgrade HTTP/1.1\r\n\ - host: {addr}\r\n\ - \r\n\ - ", - reply: "\ - HTTP/1.1 101 Switching Protocols\r\n\ - Upgrade: websocket\r\n\ - Connection: upgrade\r\n\ - \r\n\ - ", - - client: - request: - method: GET, - url: "http://{addr}/upgrade", - headers: {}, - body: None, - error: |err| err.to_string() == "unsupported protocol upgrade", - -} - test! { name: client_connect_method, diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1277,6 +1250,68 @@ mod dispatch_impl { res.join(rx).map(|r| r.0).wait().unwrap(); } + #[test] + fn client_upgrade() { + use tokio_io::io::{read_to_end, write_all}; + let _ = pretty_env_logger::try_init(); + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = server.local_addr().unwrap(); + let runtime = Runtime::new().unwrap(); + let handle = runtime.reactor(); + + let connector = DebugConnector::new(&handle); + + let client = Client::builder() + .executor(runtime.executor()) + .build(connector); + + let (tx1, rx1) = oneshot::channel(); + thread::spawn(move || { + let mut sock = server.accept().unwrap().0; + sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut buf = [0; 4096]; + sock.read(&mut buf).expect("read 1"); + sock.write_all(b"\ + HTTP/1.1 101 Switching Protocols\r\n\ + Upgrade: foobar\r\n\ + \r\n\ + foobar=ready\ + ").unwrap(); + let _ = tx1.send(()); + + let n = sock.read(&mut buf).expect("read 2"); + assert_eq!(&buf[..n], b"foo=bar"); + sock.write_all(b"bar=foo").expect("write 2"); + }); + + let rx = rx1.expect("thread panicked"); + + let req = Request::builder() + .method("GET") + .uri(&*format!("http://{}/up", addr)) + .body(Body::empty()) + .unwrap(); + + let res = client.request(req); + let res = res.join(rx).map(|r| r.0).wait().unwrap(); + + assert_eq!(res.status(), 101); + let upgraded = res + .into_body() + .on_upgrade() + .wait() + .expect("on_upgrade"); + + let parts = upgraded.downcast::<DebugStream>().unwrap(); + assert_eq!(s(&parts.read_buf), "foobar=ready"); + + let io = parts.io; + let io = write_all(io, b"foo=bar").wait().unwrap().0; + let vec = read_to_end(io, vec![]).wait().unwrap().1; + assert_eq!(vec, b"bar=foo"); + } + struct DebugConnector { http: HttpConnector, diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -24,7 +24,7 @@ use futures::future::{self, FutureResult, Either}; use futures::sync::oneshot; use futures_timer::Delay; use http::header::{HeaderName, HeaderValue}; -use tokio::net::TcpListener; +use tokio::net::{TcpListener, TcpStream as TkTcpStream}; use tokio::runtime::Runtime; use tokio::reactor::Handle; use tokio_io::{AsyncRead, AsyncWrite}; diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -33,7 +33,7 @@ use tokio_io::{AsyncRead, AsyncWrite}; use hyper::{Body, Request, Response, StatusCode}; use hyper::client::Client; use hyper::server::conn::Http; -use hyper::service::{service_fn, Service}; +use hyper::service::{service_fn, service_fn_ok, Service}; fn tcp_bind(addr: &SocketAddr, handle: &Handle) -> ::tokio::io::Result<TcpListener> { let std_listener = StdTcpListener::bind(addr).unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1270,6 +1270,142 @@ fn http_connect() { assert_eq!(vec, b"bar=foo"); } +#[test] +fn upgrades_new() { + use tokio_io::io::{read_to_end, write_all}; + let _ = pretty_env_logger::try_init(); + let mut rt = Runtime::new().unwrap(); + let listener = tcp_bind(&"127.0.0.1:0".parse().unwrap(), &rt.reactor()).unwrap(); + let addr = listener.local_addr().unwrap(); + let (read_101_tx, read_101_rx) = oneshot::channel(); + + thread::spawn(move || { + let mut tcp = connect(&addr); + tcp.write_all(b"\ + GET / HTTP/1.1\r\n\ + Upgrade: foobar\r\n\ + Connection: upgrade\r\n\ + \r\n\ + eagerly optimistic\ + ").expect("write 1"); + let mut buf = [0; 256]; + tcp.read(&mut buf).expect("read 1"); + + let expected = "HTTP/1.1 101 Switching Protocols\r\n"; + assert_eq!(s(&buf[..expected.len()]), expected); + let _ = read_101_tx.send(()); + + let n = tcp.read(&mut buf).expect("read 2"); + assert_eq!(s(&buf[..n]), "foo=bar"); + tcp.write_all(b"bar=foo").expect("write 2"); + }); + + let (upgrades_tx, upgrades_rx) = mpsc::channel(); + let svc = service_fn_ok(move |req: Request<Body>| { + let on_upgrade = req + .into_body() + .on_upgrade(); + let _ = upgrades_tx.send(on_upgrade); + Response::builder() + .status(101) + .header("upgrade", "foobar") + .body(hyper::Body::empty()) + .unwrap() + }); + + let fut = listener.incoming() + .into_future() + .map_err(|_| -> hyper::Error { unreachable!() }) + .and_then(move |(item, _incoming)| { + let socket = item.unwrap(); + Http::new() + .serve_connection(socket, svc) + .with_upgrades() + }); + + rt.block_on(fut).unwrap(); + let on_upgrade = upgrades_rx.recv().unwrap(); + + // wait so that we don't write until other side saw 101 response + rt.block_on(read_101_rx).unwrap(); + + let upgraded = rt.block_on(on_upgrade).unwrap(); + let parts = upgraded.downcast::<TkTcpStream>().unwrap(); + let io = parts.io; + assert_eq!(parts.read_buf, "eagerly optimistic"); + + let io = rt.block_on(write_all(io, b"foo=bar")).unwrap().0; + let vec = rt.block_on(read_to_end(io, vec![])).unwrap().1; + assert_eq!(s(&vec), "bar=foo"); +} + +#[test] +fn http_connect_new() { + use tokio_io::io::{read_to_end, write_all}; + let _ = pretty_env_logger::try_init(); + let mut rt = Runtime::new().unwrap(); + let listener = tcp_bind(&"127.0.0.1:0".parse().unwrap(), &rt.reactor()).unwrap(); + let addr = listener.local_addr().unwrap(); + let (read_200_tx, read_200_rx) = oneshot::channel(); + + thread::spawn(move || { + let mut tcp = connect(&addr); + tcp.write_all(b"\ + CONNECT localhost HTTP/1.1\r\n\ + \r\n\ + eagerly optimistic\ + ").expect("write 1"); + let mut buf = [0; 256]; + tcp.read(&mut buf).expect("read 1"); + + let expected = "HTTP/1.1 200 OK\r\n"; + assert_eq!(s(&buf[..expected.len()]), expected); + let _ = read_200_tx.send(()); + + let n = tcp.read(&mut buf).expect("read 2"); + assert_eq!(s(&buf[..n]), "foo=bar"); + tcp.write_all(b"bar=foo").expect("write 2"); + }); + + let (upgrades_tx, upgrades_rx) = mpsc::channel(); + let svc = service_fn_ok(move |req: Request<Body>| { + let on_upgrade = req + .into_body() + .on_upgrade(); + let _ = upgrades_tx.send(on_upgrade); + Response::builder() + .status(200) + .body(hyper::Body::empty()) + .unwrap() + }); + + let fut = listener.incoming() + .into_future() + .map_err(|_| -> hyper::Error { unreachable!() }) + .and_then(move |(item, _incoming)| { + let socket = item.unwrap(); + Http::new() + .serve_connection(socket, svc) + .with_upgrades() + }); + + rt.block_on(fut).unwrap(); + let on_upgrade = upgrades_rx.recv().unwrap(); + + // wait so that we don't write until other side saw 200 + rt.block_on(read_200_rx).unwrap(); + + let upgraded = rt.block_on(on_upgrade).unwrap(); + let parts = upgraded.downcast::<TkTcpStream>().unwrap(); + let io = parts.io; + assert_eq!(parts.read_buf, "eagerly optimistic"); + + let io = rt.block_on(write_all(io, b"foo=bar")).unwrap().0; + let vec = rt.block_on(read_to_end(io, vec![])).unwrap().1; + assert_eq!(s(&vec), "bar=foo"); +} + + #[test] fn parse_errors_send_4xx_response() { let runtime = Runtime::new().unwrap();
Client Protocol Upgrades (For handling server protocol upgrades, see #1323) HTTP/1 allows starting a different protocol with an HTTP/1 request, and the desired protocol in an `Upgrade` header. We should support this. Edit: removed bad API proposal.
This looks great! The channel based approach we discussed also seems to be equally ergonomic and a looks much simpler to implement without adding another type parameter to virtually all types in `proto`. Is there any reason you prefer this over that? Well, shoot. The reason I liked this was for the end user API, but I think it might be impossible to do in 0.11 because: - `Body` is `Send + Sync` - We can't enforce the transport is `Send + Sync`, so we can't add `Box<AsyncRead + AsyncWrite>` to the internals of `Body`. What exact user API were you thinking with channels? ```rust struct Upgrade<T: AsyncRead + AsyncWrite> { io: T, response: MessageHead<RawStatus> handle: Handle } fn main() { let client = Client::configure().enable_upgrades().build(); let upgrade_rx = client.upgrades(); let upgrade_task = upgrade_rx.then(|upgrade: Upgrade| { do_something(upgrade); Ok(()) }); let handle = client.handle(); handle.spawn(upgrade_task); let req = Request::new(Method::Get, "https://example.domain/".parse()?) .with_header(Connection::upgrade()) .with_header(Upgrade::websocket()); let req = client.request(req).and_then(|res| { handle_req(res); Ok(()) }); core.run(req).unwrap(); } ``` But come to think of it, that is a lot of boilerplate for a single request. My use case is kind of like a proxy I would make a stream of requests, so I am biased. If there is an upgrade, what does `res` look like? Does a `Response` get generated and called? What goes in the `Upgrade` struct? What I preferred about the initial proposed API is that handling an upgrade was local to the `Response`, and so obvious. My concern with configuring the `Client` is that it can happen in different places, and thus it might not be obvious that upgrades are handled... > Does a Response get generated and called? Yes. > What goes in the Upgrade struct? `Upgrade` struct is right at the top of the example. > `Upgrade` struct is right at the top of the example. Ah OK, it wasn't in the original message I got in email, didn't notice the edit. ---- So, a user would receive the `Response` like normal, and would be able to inspect it, and if it wasn't an upgrade, try to read the body. Regardless, if it is an upgrade, the `upgrades` receiver would also receive an `Upgrade`... I suppose it allows working without a breaking change, but my personal opinion is that it kind of feels far away from the rest of the code. Hm, does that even matter? I suppose that the underlying connection is being used in an upgrade perhaps doesn't matter to the other place that received a `Response`... Ok, sorry it's taken so long to get back here, I haven't had much time to focus on this feature, but it's now needed in Conduit, so it's got my attention again. I've started with the idea that the client could use a lower-level API of running HTTP over a single connection, and there is where upgrades can be handled at first (as well as custom pools and whatever else). I feel that designing an API to work directly with the higher level `Client`, which manages connections for you, is holding back this feature work, so that's why I've gone this direction. I think it could be possible to eventually design an API that works with the higher level `Client`, but here's a proposal to get things started: https://github.com/hyperium/hyper/issues/1449#issuecomment-368121931 I too tried to take a stab at it a while ago. The problem seems to be with the pool. At the dispatcher level, I could extract the `io` object out of the `Conn` to the dispatcher(this was ~2 months ago). But the fact that the pool knows it is only as a `KeepAlive` was a big hurdle. I had to remove the pool or rewrite it. Eventually I gave up. A solution for #1449 was just merged to master, that introduces a lower-level connection API, where it is possible to make `CONNECT` and upgrade requests on it. The `Client` uses it internally, but still specifically errors on `CONNECT` and upgrades since there is no exposed way to handle them correctly. There's a proposed PR at #1563 to add this feature (and for servers).
2018-06-11T23:35:42Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,556
hyperium__hyper-1556
[ "1547" ]
f20afba57d6fabb04085968342e5fd62b45bc8df
diff --git a/src/headers.rs b/src/headers.rs --- a/src/headers.rs +++ b/src/headers.rs @@ -78,6 +78,13 @@ pub fn content_length_value(len: u64) -> HeaderValue { } } +pub fn set_content_length_if_missing(headers: &mut HeaderMap, len: u64) { + headers + .entry(CONTENT_LENGTH) + .unwrap() + .or_insert(content_length_value(len)); +} + pub fn transfer_encoding_is_chunked(headers: &HeaderMap) -> bool { is_chunked(headers.get_all(TRANSFER_ENCODING).into_iter()) } diff --git a/src/proto/h2/client.rs b/src/proto/h2/client.rs --- a/src/proto/h2/client.rs +++ b/src/proto/h2/client.rs @@ -7,6 +7,7 @@ use tokio_io::{AsyncRead, AsyncWrite}; use body::Payload; use ::common::{Exec, Never}; +use headers; use super::{PipeToSendStream, SendBuf}; use ::{Body, Request, Response}; diff --git a/src/proto/h2/client.rs b/src/proto/h2/client.rs --- a/src/proto/h2/client.rs +++ b/src/proto/h2/client.rs @@ -106,6 +107,9 @@ where let (head, body) = req.into_parts(); let mut req = ::http::Request::from_parts(head, ()); super::strip_connection_headers(req.headers_mut()); + if let Some(len) = body.content_length() { + headers::set_content_length_if_missing(req.headers_mut(), len); + } let eos = body.is_end_stream(); let (fut, body_tx) = match tx.send_request(req, eos) { Ok(ok) => ok, diff --git a/src/proto/h2/server.rs b/src/proto/h2/server.rs --- a/src/proto/h2/server.rs +++ b/src/proto/h2/server.rs @@ -5,6 +5,7 @@ use tokio_io::{AsyncRead, AsyncWrite}; use ::body::Payload; use ::common::Exec; +use ::headers; use ::service::Service; use super::{PipeToSendStream, SendBuf}; diff --git a/src/proto/h2/server.rs b/src/proto/h2/server.rs --- a/src/proto/h2/server.rs +++ b/src/proto/h2/server.rs @@ -171,6 +172,9 @@ where let (head, body) = res.into_parts(); let mut res = ::http::Response::from_parts(head, ()); super::strip_connection_headers(res.headers_mut()); + if let Some(len) = body.content_length() { + headers::set_content_length_if_missing(res.headers_mut(), len); + } macro_rules! reply { ($eos:expr) => ({ match self.reply.send_response(res, $eos) {
diff --git a/tests/integration.rs b/tests/integration.rs --- a/tests/integration.rs +++ b/tests/integration.rs @@ -166,6 +166,29 @@ t! { ; } +t! { + post_outgoing_length, + client: + request: + method: "POST", + uri: "/hello", + body: "hello, world!", + ; + response: + ; + server: + request: + method: "POST", + uri: "/hello", + headers: { + "content-length" => "13", + }, + body: "hello, world!", + ; + response: + ; +} + t! { post_chunked, client: diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -353,6 +353,65 @@ mod response_body_lengths { expects_con_len: false, }); } + + #[test] + fn http2_auto_response_with_known_length() { + use hyper::body::Payload; + + let server = serve(); + let addr_str = format!("http://{}", server.addr()); + server.reply().body("Hello, World!"); + + hyper::rt::run(hyper::rt::lazy(move || { + let client: Client<_, hyper::Body> = Client::builder().http2_only(true).build_http(); + let uri = addr_str + .parse::<hyper::Uri>() + .expect("server addr should parse"); + + client + .get(uri) + .and_then(|res| { + assert_eq!(res.headers().get("content-length").unwrap(), "13"); + // TODO: enable this after #1546 + let _ = res.body().content_length(); + // assert_eq!(res.body().content_length(), Some(13)); + Ok(()) + }) + .map(|_| ()) + .map_err(|_e| ()) + })); + } + + #[test] + fn http2_auto_response_with_conflicting_lengths() { + use hyper::body::Payload; + + let server = serve(); + let addr_str = format!("http://{}", server.addr()); + server + .reply() + .header("content-length", "10") + .body("Hello, World!"); + + hyper::rt::run(hyper::rt::lazy(move || { + let client: Client<_, hyper::Body> = Client::builder().http2_only(true).build_http(); + let uri = addr_str + .parse::<hyper::Uri>() + .expect("server addr should parse"); + + client + .get(uri) + .and_then(|res| { + assert_eq!(res.headers().get("content-length").unwrap(), "10"); + // TODO: enable or remove this after #1546 + let _ = res.body().content_length(); + // assert_eq!(res.body().content_length(), Some(10)); + Ok(()) + }) + .map(|_| ()) + .map_err(|_e| ()) + })); + } } #[test]
HTTP2 outgoing messages should set content-length if payload knows it For instance, a server replying with `Response::new(Body::from("Hello, World!"))` over HTTP2 should set the `content-length: 13` header. ## Steps to fix - In `proto::h2::server`, before calling `SendResponse::send_response`, check `body.content_length()`. If it returns `Some(len)`, check if the headers contain `CONTENT_LENGTH`, and if not, add the header with the serialized length. - Do the same in `proto::h2::client`, before calling `SendRequest::send_request`. - Serializing into a header value can make use of `hyper::headers::content_length_value`. - A new function, `set_content_length_if_not_present`, could probably be added to `hyper::headers`, making use of `HeaderMap::entry`.
2018-06-08T21:21:11Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,554
hyperium__hyper-1554
[ "1545" ]
396fe80e76840dea9373ca448b20cf7a9babd2f8
diff --git a/src/body/body.rs b/src/body/body.rs --- a/src/body/body.rs +++ b/src/body/body.rs @@ -35,6 +35,7 @@ pub struct Body { enum Kind { Once(Option<Chunk>), Chan { + content_length: Option<u64>, abort_rx: oneshot::Receiver<()>, rx: mpsc::Receiver<Result<Chunk, ::Error>>, }, diff --git a/src/body/body.rs b/src/body/body.rs --- a/src/body/body.rs +++ b/src/body/body.rs @@ -85,6 +86,11 @@ impl Body { /// Useful when wanting to stream chunks from another thread. #[inline] pub fn channel() -> (Sender, Body) { + Self::new_channel(None) + } + + #[inline] + pub(crate) fn new_channel(content_length: Option<u64>) -> (Sender, Body) { let (tx, rx) = mpsc::channel(0); let (abort_tx, abort_rx) = oneshot::channel(); diff --git a/src/body/body.rs b/src/body/body.rs --- a/src/body/body.rs +++ b/src/body/body.rs @@ -93,8 +99,9 @@ impl Body { tx: tx, }; let rx = Body::new(Kind::Chan { - abort_rx: abort_rx, - rx: rx, + content_length, + abort_rx, + rx, }); (tx, rx) diff --git a/src/body/body.rs b/src/body/body.rs --- a/src/body/body.rs +++ b/src/body/body.rs @@ -188,13 +195,19 @@ impl Body { fn poll_inner(&mut self) -> Poll<Option<Chunk>, ::Error> { match self.kind { Kind::Once(ref mut val) => Ok(Async::Ready(val.take())), - Kind::Chan { ref mut rx, ref mut abort_rx } => { + Kind::Chan { content_length: ref mut len, ref mut rx, ref mut abort_rx } => { if let Ok(Async::Ready(())) = abort_rx.poll() { return Err(::Error::new_body_write("body write aborted")); } match rx.poll().expect("mpsc cannot error") { - Async::Ready(Some(Ok(chunk))) => Ok(Async::Ready(Some(chunk))), + Async::Ready(Some(Ok(chunk))) => { + if let Some(ref mut len) = *len { + debug_assert!(*len >= chunk.len() as u64); + *len = *len - chunk.len() as u64; + } + Ok(Async::Ready(Some(chunk))) + } Async::Ready(Some(Err(err))) => Err(err), Async::Ready(None) => Ok(Async::Ready(None)), Async::NotReady => Ok(Async::NotReady), diff --git a/src/body/body.rs b/src/body/body.rs --- a/src/body/body.rs +++ b/src/body/body.rs @@ -243,7 +256,7 @@ impl Payload for Body { fn is_end_stream(&self) -> bool { match self.kind { Kind::Once(ref val) => val.is_none(), - Kind::Chan { .. } => false, + Kind::Chan { content_length: len, .. } => len == Some(0), Kind::H2(ref h2) => h2.is_end_stream(), Kind::Wrapped(..) => false, } diff --git a/src/body/body.rs b/src/body/body.rs --- a/src/body/body.rs +++ b/src/body/body.rs @@ -253,7 +266,7 @@ impl Payload for Body { match self.kind { Kind::Once(Some(ref val)) => Some(val.len() as u64), Kind::Once(None) => Some(0), - Kind::Chan { .. } => None, + Kind::Chan { content_length: len, .. } => len, Kind::H2(..) => None, Kind::Wrapped(..) => None, } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -114,7 +114,7 @@ where I: AsyncRead + AsyncWrite, read_buf.len() >= 24 && read_buf[..24] == *H2_PREFACE } - pub fn read_head(&mut self) -> Poll<Option<(MessageHead<T::Incoming>, bool)>, ::Error> { + pub fn read_head(&mut self) -> Poll<Option<(MessageHead<T::Incoming>, Option<BodyLength>)>, ::Error> { debug_assert!(self.can_read_head()); trace!("Conn::read_head"); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -162,7 +162,6 @@ where I: AsyncRead + AsyncWrite, continue; } }; - debug!("incoming body is {}", decoder); self.state.busy(); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -172,20 +171,23 @@ where I: AsyncRead + AsyncWrite, } let wants_keep_alive = msg.keep_alive; self.state.keep_alive &= wants_keep_alive; - let (body, reading) = if decoder.is_eof() { - (false, Reading::KeepAlive) - } else { - (true, Reading::Body(decoder)) - }; + + let content_length = decoder.content_length(); + if let Reading::Closed = self.state.reading { // actually want an `if not let ...` } else { - self.state.reading = reading; + self.state.reading = if content_length.is_none() { + Reading::KeepAlive + } else { + Reading::Body(decoder) + }; } - if !body { + if content_length.is_none() { self.try_keep_alive(); } - return Ok(Async::Ready(Some((head, body)))); + + return Ok(Async::Ready(Some((head, content_length)))); } } diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -7,6 +7,7 @@ use futures::{Async, Poll}; use bytes::Bytes; use super::io::MemRead; +use super::BodyLength; use self::Kind::{Length, Chunked, Eof}; diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -84,6 +85,16 @@ impl Decoder { } } + pub fn content_length(&self) -> Option<BodyLength> { + match self.kind { + Length(0) | + Chunked(ChunkedState::End, _) | + Eof(true) => None, + Length(len) => Some(BodyLength::Known(len)), + _ => Some(BodyLength::Unknown), + } + } + pub fn decode<R: MemRead>(&mut self, body: &mut R) -> Poll<Bytes, io::Error> { trace!("decode; state={:?}", self.kind); match self.kind { diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -190,9 +190,14 @@ where } // dispatch is ready for a message, try to read one match self.conn.read_head() { - Ok(Async::Ready(Some((head, has_body)))) => { - let body = if has_body { - let (mut tx, rx) = Body::channel(); + Ok(Async::Ready(Some((head, body_len)))) => { + let body = if let Some(body_len) = body_len { + let (mut tx, rx) = + Body::new_channel(if let BodyLength::Known(len) = body_len { + Some(len) + } else { + None + }); let _ = tx.poll_ready(); // register this task if rx is dropped self.body_tx = Some(tx); rx diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -201,7 +206,7 @@ where }; self.dispatch.recv_msg(Ok((head, body)))?; Ok(Async::Ready(())) - }, + } Ok(Async::Ready(None)) => { // read eof, conn will start to shutdown automatically Ok(Async::Ready(()))
diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1424,6 +1424,63 @@ mod conn { res.join(rx).map(|r| r.0).wait().unwrap(); } + #[test] + fn incoming_content_length() { + use hyper::body::Payload; + + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = server.local_addr().unwrap(); + let mut runtime = Runtime::new().unwrap(); + + let (tx1, rx1) = oneshot::channel(); + + thread::spawn(move || { + let mut sock = server.accept().unwrap().0; + sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut buf = [0; 4096]; + let n = sock.read(&mut buf).expect("read 1"); + + let expected = "GET / HTTP/1.1\r\n\r\n"; + assert_eq!(s(&buf[..n]), expected); + + sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello").unwrap(); + let _ = tx1.send(()); + }); + + let tcp = tcp_connect(&addr).wait().unwrap(); + + let (mut client, conn) = conn::handshake(tcp).wait().unwrap(); + + runtime.spawn(conn.map(|_| ()).map_err(|e| panic!("conn error: {}", e))); + + let req = Request::builder() + .uri("/") + .body(Default::default()) + .unwrap(); + let res = client.send_request(req).and_then(move |mut res| { + assert_eq!(res.status(), hyper::StatusCode::OK); + assert_eq!(res.body().content_length(), Some(5)); + assert!(!res.body().is_end_stream()); + loop { + let chunk = res.body_mut().poll_data().unwrap(); + match chunk { + Async::Ready(Some(chunk)) => { + assert_eq!(chunk.len(), 5); + break; + } + _ => continue + } + } + res.into_body().concat2() + }); + let rx = rx1.expect("thread panicked"); + + let timeout = Delay::new(Duration::from_millis(200)); + let rx = rx.and_then(move |_| timeout.expect("timeout")); + res.join(rx).map(|r| r.0).wait().unwrap(); + } + #[test] fn aborted_body_isnt_completed() { let _ = ::pretty_env_logger::try_init();
Incoming HTTP1 bodies should know content_length and is_end_stream For instance, if a server receives the follow request: ``` POST /foo HTTP/1.1 content-length: 15 ``` The `Body` in the `Request` should know these things, neither of which are currently true: - `Body::content_length()` should be `Some(15)`. - `Body::is_end_stream()` should return true after `poll_data` has returned chunks of length totaling 15 bytes. ## Steps to fixing - Adding an `Option<u64>` to the `Kind::Chan` variant of `Body`. - Changing `h1::Conn::read_head` to return an `Option<BodyLength>` instead of `bool`. - Updating the `h1::Dispatcher` to use the `Option<BodyLength>` to optionally set the new `Option<u64>` field of the `Chan` variant. - Updating `Body::content_length` to return the new field from `Kind::Chan`. - Updating `Body::poll_data` in the `Kind::Chan` variant to subtract from the new field the length of each chunk that passes by. - Updating `Body::is_end_stream` in the `Kind::Chan` variant to return true **if**` the field is exactly `Some(0)`. ### Testing it works - Add a test to `tests/client.rs` with a server replying with the bytes `HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nhello`. - In the test, make a `GET` request to the server, and wait for the `Response<Body>`. - Add an `assert_eq!(res.body().content_length(), Some(5))`. - Add an `assert!(!res.body().is_end_stream())` (the body should be done yet, there's still 5 bytes to stream). - Call `res.body_mut().poll_data()` to get the chunk. Assert it is 5 bytes for sanity. - Finally, `assert!(res.body().is_end_stream())`, as the 5 bytes have now been streamed.
2018-06-08T03:56:07Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,503
hyperium__hyper-1503
[ "1486" ]
18f4dd240631df55064696de865b6d818cb76ba7
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -45,6 +45,7 @@ num_cpus = "1.0" pretty_env_logger = "0.2.0" spmc = "0.2" url = "1.0" +tokio-mockstream = "1.1.0" [features] default = [ diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -69,6 +69,7 @@ pub(crate) enum Kind { pub(crate) enum Parse { Method, Version, + VersionH2, Uri, Header, TooLarge, diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -164,6 +165,10 @@ impl Error { Error::new(Kind::Parse(Parse::Version), None) } + pub(crate) fn new_version_h2() -> Error { + Error::new(Kind::Parse(Parse::VersionH2), None) + } + pub(crate) fn new_mismatched_response() -> Error { Error::new(Kind::MismatchedResponse, None) } diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -250,6 +255,7 @@ impl StdError for Error { match self.inner.kind { Kind::Parse(Parse::Method) => "invalid Method specified", Kind::Parse(Parse::Version) => "invalid HTTP version specified", + Kind::Parse(Parse::VersionH2) => "invalid HTTP version specified (Http2)", Kind::Parse(Parse::Uri) => "invalid URI", Kind::Parse(Parse::Header) => "invalid Header provided", Kind::Parse(Parse::TooLarge) => "message head is too large", diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -12,6 +12,7 @@ use proto::{BodyLength, Decode, Http1Transaction, MessageHead}; use super::io::{Buffered}; use super::{EncodedBuf, Encoder, Decoder}; +const H2_PREFACE: &'static [u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; /// This handles a connection, which will have been established over an /// `AsyncRead + AsyncWrite` (like a socket), and will likely include multiple diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -107,6 +108,11 @@ where I: AsyncRead + AsyncWrite, T::should_error_on_parse_eof() && !self.state.is_idle() } + fn has_h2_prefix(&self) -> bool { + let read_buf = self.io.read_buf(); + read_buf.len() >= 24 && read_buf[..24] == *H2_PREFACE + } + pub fn read_head(&mut self) -> Poll<Option<(MessageHead<T::Incoming>, bool)>, ::Error> { debug_assert!(self.can_read_head()); trace!("Conn::read_head"); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -124,6 +130,7 @@ where I: AsyncRead + AsyncWrite, self.io.consume_leading_lines(); let was_mid_parse = e.is_parse() || !self.io.read_buf().is_empty(); return if was_mid_parse || must_error { + // We check if the buf contains the h2 Preface debug!("parse error ({}) with {} bytes", e, self.io.read_buf().len()); self.on_parse_error(e) .map(|()| Async::NotReady) diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -529,8 +536,12 @@ where I: AsyncRead + AsyncWrite, // - Client: there is nothing we can do // - Server: if Response hasn't been written yet, we can send a 4xx response fn on_parse_error(&mut self, err: ::Error) -> ::Result<()> { + match self.state.writing { Writing::Init => { + if self.has_h2_prefix() { + return Err(::Error::new_version_h2()) + } if let Some(msg) = T::on_error(&err) { self.write_head(msg, None); self.state.error = Some(err); diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -332,6 +332,9 @@ impl<S> Server<S> where S: Service { service: service, } } + pub fn into_service(self) -> S { + self.service + } } impl<S, Bs> Dispatch for Server<S> diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -186,14 +186,14 @@ where use ::error::{Kind, Parse}; let status = match *err.kind() { Kind::Parse(Parse::Method) | - Kind::Parse(Parse::Version) | Kind::Parse(Parse::Header) | - Kind::Parse(Parse::Uri) => { + Kind::Parse(Parse::Uri) | + Kind::Parse(Parse::Version) => { StatusCode::BAD_REQUEST }, Kind::Parse(Parse::TooLarge) => { StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE - } + }, _ => return None, }; diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -13,6 +13,7 @@ use std::fmt; use std::sync::Arc; #[cfg(feature = "runtime")] use std::time::Duration; +use super::rewind::Rewind; use bytes::Bytes; use futures::{Async, Future, Poll, Stream}; use futures::future::{Either, Executor}; diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -23,6 +24,7 @@ use common::Exec; use proto; use body::{Body, Payload}; use service::{NewService, Service}; +use error::{Kind, Parse}; #[cfg(feature = "runtime")] pub use super::tcp::AddrIncoming; diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -74,23 +76,24 @@ pub(super) struct SpawnAll<I, S> { /// /// Polling this future will drive HTTP forward. #[must_use = "futures do nothing unless polled"] -pub struct Connection<I, S> +pub struct Connection<T, S> where S: Service, { - pub(super) conn: Either< + pub(super) conn: Option< + Either< proto::h1::Dispatcher< proto::h1::dispatch::Server<S>, S::ResBody, - I, + T, proto::ServerTransaction, >, proto::h2::Server< - I, + Rewind<T>, S, S::ResBody, >, - >, + >>, } /// Deconstructed parts of a `Connection`. diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -98,7 +101,7 @@ where /// This allows taking apart a `Connection` at a later time, in order to /// reclaim the IO object, and additional related pieces. #[derive(Debug)] -pub struct Parts<T, S> { +pub struct Parts<T, S> { /// The original IO object used in the handshake. pub io: T, /// A buffer of bytes that have been read but not processed as HTTP. diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -239,12 +242,13 @@ impl Http { let sd = proto::h1::dispatch::Server::new(service); Either::A(proto::h1::Dispatcher::new(sd, conn)) } else { - let h2 = proto::h2::Server::new(io, service, self.exec.clone()); + let rewind_io = Rewind::new(io); + let h2 = proto::h2::Server::new(rewind_io, service, self.exec.clone()); Either::B(h2) }; Connection { - conn: either, + conn: Some(either), } } diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -322,7 +326,7 @@ where /// This `Connection` should continue to be polled until shutdown /// can finish. pub fn graceful_shutdown(&mut self) { - match self.conn { + match *self.conn.as_mut().unwrap() { Either::A(ref mut h1) => { h1.disable_keep_alive(); }, diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -334,11 +338,12 @@ where /// Return the inner IO object, and additional information. /// + /// If the IO object has been "rewound" the io will not contain those bytes rewound. /// This should only be called after `poll_without_shutdown` signals /// that the connection is "done". Otherwise, it may not have finished /// flushing all necessary HTTP bytes. pub fn into_parts(self) -> Parts<I, S> { - let (io, read_buf, dispatch) = match self.conn { + let (io, read_buf, dispatch) = match self.conn.unwrap() { Either::A(h1) => { h1.into_inner() }, diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -349,7 +354,7 @@ where Parts { io: io, read_buf: read_buf, - service: dispatch.service, + service: dispatch.into_service(), _inner: (), } } diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -362,7 +367,7 @@ where /// but it is not desired to actally shutdown the IO object. Instead you /// would take it back using `into_parts`. pub fn poll_without_shutdown(&mut self) -> Poll<(), ::Error> { - match self.conn { + match *self.conn.as_mut().unwrap() { Either::A(ref mut h1) => { try_ready!(h1.poll_without_shutdown()); Ok(().into()) diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -370,6 +375,29 @@ where Either::B(ref mut h2) => h2.poll(), } } + + fn try_h2(&mut self) -> Poll<(), ::Error> { + trace!("Trying to upgrade connection to h2"); + let conn = self.conn.take(); + + let (io, read_buf, dispatch) = match conn.unwrap() { + Either::A(h1) => { + h1.into_inner() + }, + Either::B(_h2) => { + panic!("h2 cannot into_inner"); + } + }; + let mut rewind_io = Rewind::new(io); + rewind_io.rewind(read_buf); + let mut h2 = proto::h2::Server::new(rewind_io, dispatch.into_service(), Exec::Default); + let pr = h2.poll(); + + debug_assert!(self.conn.is_none()); + self.conn = Some(Either::B(h2)); + + pr + } } impl<I, B, S> Future for Connection<I, S> diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -384,7 +412,16 @@ where type Error = ::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - self.conn.poll() + match self.conn.poll() { + Ok(x) => Ok(x.map(|o| o.unwrap_or_else(|| ()))), + Err(e) => { + debug!("error polling connection protocol: {}", e); + match *e.kind() { + Kind::Parse(Parse::VersionH2) => self.try_h2(), + _ => Err(e), + } + } + } } } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -50,6 +50,7 @@ pub mod conn; #[cfg(feature = "runtime")] mod tcp; +mod rewind; use std::fmt; #[cfg(feature = "runtime")] use std::net::SocketAddr;
diff --git /dev/null b/src/server/rewind.rs new file mode 100644 --- /dev/null +++ b/src/server/rewind.rs @@ -0,0 +1,208 @@ +use bytes::{Buf, BufMut, Bytes, IntoBuf}; +use futures::{Async, Poll}; +use std::io::{self, Read, Write}; +use std::cmp; +use tokio_io::{AsyncRead, AsyncWrite}; + +#[derive(Debug)] +pub struct Rewind<T> { + pre: Option<Bytes>, + inner: T, +} + +impl<T> Rewind<T> { + pub(super) fn new(tcp: T) -> Rewind<T> { + Rewind { + pre: None, + inner: tcp, + } + } + pub fn rewind(&mut self, bs: Bytes) { + debug_assert!(self.pre.is_none()); + self.pre = Some(bs); + } +} + +impl<T> Read for Rewind<T> +where + T: Read, +{ + #[inline] + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + if let Some(pre_bs) = self.pre.take() { + // If there are no remaining bytes, let the bytes get dropped. + if pre_bs.len() > 0 { + let mut pre_reader = pre_bs.into_buf().reader(); + let read_cnt = pre_reader.read(buf)?; + + let mut new_pre = pre_reader.into_inner().into_inner(); + new_pre.advance(read_cnt); + + // Put back whats left + if new_pre.len() > 0 { + self.pre = Some(new_pre); + } + + return Ok(read_cnt); + } + } + self.inner.read(buf) + } +} + +impl<T> Write for Rewind<T> +where + T: Write, +{ + #[inline] + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.inner.write(buf) + } + + #[inline] + fn flush(&mut self) -> io::Result<()> { + self.inner.flush() + } +} + +impl<T> AsyncRead for Rewind<T> +where + T: AsyncRead, +{ + #[inline] + unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool { + self.inner.prepare_uninitialized_buffer(buf) + } + + #[inline] + fn read_buf<B: BufMut>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { + if let Some(bs) = self.pre.take() { + let pre_len = bs.len(); + // If there are no remaining bytes, let the bytes get dropped. + if pre_len > 0 { + let cnt = cmp::min(buf.remaining_mut(), pre_len); + let pre_buf = bs.into_buf(); + let mut xfer = Buf::take(pre_buf, cnt); + buf.put(&mut xfer); + + let mut new_pre = xfer.into_inner().into_inner(); + new_pre.advance(cnt); + + // Put back whats left + if new_pre.len() > 0 { + self.pre = Some(new_pre); + } + + return Ok(Async::Ready(cnt)); + } + } + self.inner.read_buf(buf) + } +} + +impl<T> AsyncWrite for Rewind<T> +where + T: AsyncWrite, +{ + #[inline] + fn shutdown(&mut self) -> Poll<(), io::Error> { + AsyncWrite::shutdown(&mut self.inner) + } + + #[inline] + fn write_buf<B: Buf>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { + self.inner.write_buf(buf) + } +} + +#[cfg(test)] +mod tests { + use super::*; + extern crate tokio_mockstream; + use self::tokio_mockstream::MockStream; + use std::io::Cursor; + + // Test a partial rewind + #[test] + fn async_partial_rewind() { + let bs = &mut [104, 101, 108, 108, 111]; + let o1 = &mut [0, 0]; + let o2 = &mut [0, 0, 0, 0, 0]; + + let mut stream = Rewind::new(MockStream::new(bs)); + let mut o1_cursor = Cursor::new(o1); + // Read off some bytes, ensure we filled o1 + match stream.read_buf(&mut o1_cursor).unwrap() { + Async::NotReady => panic!("should be ready"), + Async::Ready(cnt) => assert_eq!(2, cnt), + } + + // Rewind the stream so that it is as if we never read in the first place. + let read_buf = Bytes::from(&o1_cursor.into_inner()[..]); + stream.rewind(read_buf); + + // We poll 2x here since the first time we'll only get what is in the + // prefix (the rewinded part) of the Rewind.\ + let mut o2_cursor = Cursor::new(o2); + stream.read_buf(&mut o2_cursor).unwrap(); + stream.read_buf(&mut o2_cursor).unwrap(); + let o2_final = o2_cursor.into_inner(); + + // At this point we should have read everything that was in the MockStream + assert_eq!(&o2_final, &bs); + } + // Test a full rewind + #[test] + fn async_full_rewind() { + let bs = &mut [104, 101, 108, 108, 111]; + let o1 = &mut [0, 0, 0, 0, 0]; + let o2 = &mut [0, 0, 0, 0, 0]; + + let mut stream = Rewind::new(MockStream::new(bs)); + let mut o1_cursor = Cursor::new(o1); + match stream.read_buf(&mut o1_cursor).unwrap() { + Async::NotReady => panic!("should be ready"), + Async::Ready(cnt) => assert_eq!(5, cnt), + } + + let read_buf = Bytes::from(&o1_cursor.into_inner()[..]); + stream.rewind(read_buf); + + let mut o2_cursor = Cursor::new(o2); + stream.read_buf(&mut o2_cursor).unwrap(); + stream.read_buf(&mut o2_cursor).unwrap(); + let o2_final = o2_cursor.into_inner(); + + assert_eq!(&o2_final, &bs); + } + #[test] + fn partial_rewind() { + let bs = &mut [104, 101, 108, 108, 111]; + let o1 = &mut [0, 0]; + let o2 = &mut [0, 0, 0, 0, 0]; + + let mut stream = Rewind::new(MockStream::new(bs)); + stream.read(o1).unwrap(); + + let read_buf = Bytes::from(&o1[..]); + stream.rewind(read_buf); + let cnt = stream.read(o2).unwrap(); + stream.read(&mut o2[cnt..]).unwrap(); + assert_eq!(&o2, &bs); + } + #[test] + fn full_rewind() { + let bs = &mut [104, 101, 108, 108, 111]; + let o1 = &mut [0, 0, 0, 0, 0]; + let o2 = &mut [0, 0, 0, 0, 0]; + + let mut stream = Rewind::new(MockStream::new(bs)); + stream.read(o1).unwrap(); + + let read_buf = Bytes::from(&o1[..]); + stream.rewind(read_buf); + let cnt = stream.read(o2).unwrap(); + stream.read(&mut o2[cnt..]).unwrap(); + assert_eq!(&o2, &bs); + } +} diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -31,6 +31,7 @@ use tokio_io::{AsyncRead, AsyncWrite}; use hyper::{Body, Request, Response, StatusCode}; +use hyper::client::Client; use hyper::server::conn::Http; use hyper::service::{service_fn, Service}; diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -39,6 +40,24 @@ fn tcp_bind(addr: &SocketAddr, handle: &Handle) -> ::tokio::io::Result<TcpListen TcpListener::from_std(std_listener, handle) } +#[test] +fn try_h2() { + let server = serve(); + let addr_str = format!("http://{}", server.addr()); + + hyper::rt::run(hyper::rt::lazy(move || { + let client: Client<_, hyper::Body> = Client::builder().http2_only(true).build_http(); + let uri = addr_str.parse::<hyper::Uri>().expect("server addr should parse"); + + client.get(uri) + .and_then(|_res| { Ok(()) }) + .map(|_| { () }) + .map_err(|_e| { () }) + })); + + assert_eq!(server.body(), b""); +} + #[test] fn get_should_ignore_body() { let server = serve();
Try parsing HTTP2 on server connections if HTTP1 parsing fails This would be a next step to allowing the server to have HTTP2 support on by default.
I'd like to take this one on. @estk cool! I haven't personally thought out an exact implementation yet... One way could be for `server::conn::Connection` to be able to inspect a returned error, and if it's a parse error, try to take the IO and read buffer back out and use them to try the `h2::server::handshake`... Excellent thanks for the head start.
2018-04-27T23:34:32Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,502
hyperium__hyper-1502
[ "1484" ]
5e3b43af09fda86df59486edbeb9e68c6801a503
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -24,7 +24,6 @@ include = [ bytes = "0.4.4" futures = "0.1.21" futures-cpupool = { version = "0.1.6", optional = true } -futures-timer = "0.1.0" http = "0.1.5" httparse = "1.0" h2 = "0.1.5" diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -37,9 +36,11 @@ tokio-executor = { version = "0.1.0", optional = true } tokio-io = "0.1" tokio-reactor = { version = "0.1", optional = true } tokio-tcp = { version = "0.1", optional = true } +tokio-timer = { version = "0.2", optional = true } want = "0.0.4" [dev-dependencies] +futures-timer = "0.1" num_cpus = "1.0" pretty_env_logger = "0.2.0" spmc = "0.2" diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -55,6 +56,7 @@ runtime = [ "tokio-executor", "tokio-reactor", "tokio-tcp", + "tokio-timer", ] [[example]] diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -113,14 +113,6 @@ where C: Connect + Sync + 'static, /// Send a constructed Request using this Client. pub fn request(&self, mut req: Request<B>) -> FutureResponse { - // TODO(0.12): do this at construction time. - // - // It cannot be done in the constructor because the Client::configured - // does not have `B: 'static` bounds, which are required to spawn - // the interval. In 0.12, add a static bounds to the constructor, - // and move this. - self.schedule_pool_timer(); - match req.version() { Version::HTTP_10 | Version::HTTP_11 => (), diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -302,7 +294,7 @@ where C: Connect + Sync + 'static, // for a new request to start. // // It won't be ready if there is a body to stream. - if ver == Ver::Http2 || pooled.is_ready() { + if ver == Ver::Http2 || !pooled.is_pool_enabled() || pooled.is_ready() { drop(pooled); } else if !res.body().is_empty() { let (delayed_tx, delayed_rx) = oneshot::channel(); diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -336,10 +328,6 @@ where C: Connect + Sync + 'static, Box::new(resp) } - - fn schedule_pool_timer(&self) { - self.pool.spawn_expired_interval(&self.executor); - } } impl<C, B> Clone for Client<C, B> { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -474,7 +462,7 @@ impl<B: Payload + 'static> PoolClient<B> { impl<B> Poolable for PoolClient<B> where - B: 'static, + B: Send + 'static, { fn is_open(&self) -> bool { match self.tx { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -700,7 +688,7 @@ impl Builder { executor: self.exec.clone(), h1_writev: self.h1_writev, h1_title_case_headers: self.h1_title_case_headers, - pool: Pool::new(self.keep_alive, self.keep_alive_timeout), + pool: Pool::new(self.keep_alive, self.keep_alive_timeout, &self.exec), retry_canceled_requests: self.retry_canceled_requests, set_host: self.set_host, ver: self.ver, diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -4,15 +4,16 @@ use std::ops::{Deref, DerefMut}; use std::sync::{Arc, Mutex, Weak}; use std::time::{Duration, Instant}; -use futures::{Future, Async, Poll, Stream}; +use futures::{Future, Async, Poll}; use futures::sync::oneshot; -use futures_timer::Interval; +#[cfg(feature = "runtime")] +use tokio_timer::Interval; -use common::{Exec, Never}; +use common::Exec; use super::Ver; pub(super) struct Pool<T> { - inner: Arc<Mutex<PoolInner<T>>>, + inner: Arc<PoolInner<T>>, } // Before using a pooled connection, make sure the sender is not dead. diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -47,11 +48,20 @@ pub(super) enum Reservation<T> { type Key = (Arc<String>, Ver); struct PoolInner<T> { + connections: Mutex<Connections<T>>, + enabled: bool, + /// A single Weak pointer used every time a proper weak reference + /// is not needed. This prevents allocating space in the heap to hold + /// a PoolInner<T> *every single time*, and instead we just allocate + /// this one extra per pool. + weak: Weak<PoolInner<T>>, +} + +struct Connections<T> { // A flag that a connection is being estabilished, and the connection // should be shared. This prevents making multiple HTTP/2 connections // to the same host. connecting: HashSet<Key>, - enabled: bool, // These are internal Conns sitting in the event loop in the KeepAlive // state, waiting to receive a new Request to send on the socket. idle: HashMap<Key, Vec<Idle<T>>>, diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -100,8 +131,8 @@ impl<T: Poolable> Pool<T> { /// Ensure that there is only ever 1 connecting task for HTTP/2 /// connections. This does nothing for HTTP/1. pub(super) fn connecting(&self, key: &Key) -> Option<Connecting<T>> { - if key.1 == Ver::Http2 { - let mut inner = self.inner.lock().unwrap(); + if key.1 == Ver::Http2 && self.inner.enabled { + let mut inner = self.inner.connections.lock().unwrap(); if inner.connecting.insert(key.clone()) { let connecting = Connecting { key: key.clone(), diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -117,14 +148,14 @@ impl<T: Poolable> Pool<T> { key: key.clone(), // in HTTP/1's case, there is never a lock, so we don't // need to do anything in Drop. - pool: Weak::new(), + pool: self.inner.weak.clone(), }) } } fn take(&self, key: &Key) -> Option<Pooled<T>> { let entry = { - let mut inner = self.inner.lock().unwrap(); + let mut inner = self.inner.connections.lock().unwrap(); let expiration = Expiration::new(inner.timeout); let maybe_entry = inner.idle.get_mut(key) .and_then(|list| { diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -158,35 +189,45 @@ impl<T: Poolable> Pool<T> { } pub(super) fn pooled(&self, mut connecting: Connecting<T>, value: T) -> Pooled<T> { - let (value, pool_ref) = match value.reserve() { - Reservation::Shared(to_insert, to_return) => { - debug_assert_eq!( - connecting.key.1, - Ver::Http2, - "shared reservation without Http2" - ); - let mut inner = self.inner.lock().unwrap(); - inner.put(connecting.key.clone(), to_insert); - // Do this here instead of Drop for Connecting because we - // already have a lock, no need to lock the mutex twice. - inner.connected(&connecting.key); - // prevent the Drop of Connecting from repeating inner.connected() - connecting.pool = Weak::new(); - - // Shared reservations don't need a reference to the pool, - // since the pool always keeps a copy. - (to_return, Weak::new()) - }, - Reservation::Unique(value) => { - // Unique reservations must take a reference to the pool - // since they hope to reinsert once the reservation is - // completed - (value, Arc::downgrade(&self.inner)) - }, + let (value, pool_ref, has_pool) = if self.inner.enabled { + match value.reserve() { + Reservation::Shared(to_insert, to_return) => { + debug_assert_eq!( + connecting.key.1, + Ver::Http2, + "shared reservation without Http2" + ); + let mut inner = self.inner.connections.lock().unwrap(); + inner.put(connecting.key.clone(), to_insert, &self.inner); + // Do this here instead of Drop for Connecting because we + // already have a lock, no need to lock the mutex twice. + inner.connected(&connecting.key); + // prevent the Drop of Connecting from repeating inner.connected() + connecting.pool = self.inner.weak.clone(); + + // Shared reservations don't need a reference to the pool, + // since the pool always keeps a copy. + (to_return, self.inner.weak.clone(), false) + }, + Reservation::Unique(value) => { + // Unique reservations must take a reference to the pool + // since they hope to reinsert once the reservation is + // completed + (value, Arc::downgrade(&self.inner), true) + }, + } + } else { + // If pool is not enabled, skip all the things... + + // The Connecting should have had no pool ref + debug_assert!(connecting.pool.upgrade().is_none()); + + (value, self.inner.weak.clone(), false) }; Pooled { - is_reused: false, key: connecting.key.clone(), + has_pool, + is_reused: false, pool: pool_ref, value: Some(value) } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -202,13 +243,14 @@ impl<T: Poolable> Pool<T> { // we just have the final value, without knowledge of if this is // unique or shared. So, the hack is to just assume Ver::Http2 means // shared... :( - let pool_ref = if key.1 == Ver::Http2 { - Weak::new() + let (pool_ref, has_pool) = if key.1 == Ver::Http2 { + (self.inner.weak.clone(), false) } else { - Arc::downgrade(&self.inner) + (Arc::downgrade(&self.inner), true) }; Pooled { + has_pool, is_reused: true, key: key.clone(), pool: pool_ref, diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -218,7 +260,7 @@ impl<T: Poolable> Pool<T> { fn waiter(&mut self, key: Key, tx: oneshot::Sender<T>) { trace!("checkout waiting for idle connection: {:?}", key); - self.inner.lock().unwrap() + self.inner.connections.lock().unwrap() .waiters.entry(key) .or_insert(VecDeque::new()) .push_back(tx); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -274,11 +316,8 @@ impl<'a, T: Poolable + 'a> IdlePopper<'a, T> { } } -impl<T: Poolable> PoolInner<T> { - fn put(&mut self, key: Key, value: T) { - if !self.enabled { - return; - } +impl<T: Poolable> Connections<T> { + fn put(&mut self, key: Key, value: T, __pool_ref: &Arc<PoolInner<T>>) { if key.1 == Ver::Http2 && self.idle.contains_key(&key) { trace!("put; existing idle HTTP/2 connection for {:?}", key); return; diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -328,6 +367,11 @@ impl<T: Poolable> PoolInner<T> { value: value, idle_at: Instant::now(), }); + + #[cfg(feature = "runtime")] + { + self.spawn_idle_interval(__pool_ref); + } } None => trace!("put; found waiter for {:?}", key), } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -346,9 +390,37 @@ impl<T: Poolable> PoolInner<T> { // those waiters would never receive a connection. self.waiters.remove(key); } + + #[cfg(feature = "runtime")] + fn spawn_idle_interval(&mut self, pool_ref: &Arc<PoolInner<T>>) { + let (dur, rx) = { + debug_assert!(pool_ref.enabled); + + if self.idle_interval_ref.is_some() { + return; + } + + if let Some(dur) = self.timeout { + let (tx, rx) = oneshot::channel(); + self.idle_interval_ref = Some(tx); + (dur, rx) + } else { + return + } + }; + + let start = Instant::now() + dur; + + let interval = Interval::new(start, dur); + self.exec.execute(IdleInterval { + interval: interval, + pool: Arc::downgrade(pool_ref), + pool_drop_notifier: rx, + }); + } } -impl<T> PoolInner<T> { +impl<T> Connections<T> { /// Any `FutureResponse`s that were created will have made a `Checkout`, /// and possibly inserted into the pool that it is waiting for an idle /// connection. If a user ever dropped that future, we need to clean out diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -367,7 +439,8 @@ impl<T> PoolInner<T> { } } -impl<T: Poolable> PoolInner<T> { +#[cfg(feature = "runtime")] +impl<T: Poolable> Connections<T> { /// This should *only* be called by the IdleInterval. fn clear_expired(&mut self) { let dur = self.timeout.expect("interval assumes timeout"); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -396,38 +469,6 @@ impl<T: Poolable> PoolInner<T> { } } - -impl<T: Poolable + Send + 'static> Pool<T> { - pub(super) fn spawn_expired_interval(&self, exec: &Exec) { - let (dur, rx) = { - let mut inner = self.inner.lock().unwrap(); - - if !inner.enabled { - return; - } - - if inner.idle_interval_ref.is_some() { - return; - } - - if let Some(dur) = inner.timeout { - let (tx, rx) = oneshot::channel(); - inner.idle_interval_ref = Some(tx); - (dur, rx) - } else { - return - } - }; - - let interval = Interval::new(dur); - exec.execute(IdleInterval { - interval: interval, - pool: Arc::downgrade(&self.inner), - pool_drop_notifier: rx, - }); - } -} - impl<T> Clone for Pool<T> { fn clone(&self) -> Pool<T> { Pool { diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -440,9 +481,10 @@ impl<T> Clone for Pool<T> { // Note: The bounds `T: Poolable` is needed for the Drop impl. pub(super) struct Pooled<T: Poolable> { value: Option<T>, + has_pool: bool, is_reused: bool, key: Key, - pool: Weak<Mutex<PoolInner<T>>>, + pool: Weak<PoolInner<T>>, } impl<T: Poolable> Pooled<T> { diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -450,6 +492,10 @@ impl<T: Poolable> Pooled<T> { self.is_reused } + pub fn is_pool_enabled(&self) -> bool { + self.has_pool + } + fn as_ref(&self) -> &T { self.value.as_ref().expect("not dropped") } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -481,9 +527,13 @@ impl<T: Poolable> Drop for Pooled<T> { return; } - if let Some(inner) = self.pool.upgrade() { - if let Ok(mut inner) = inner.lock() { - inner.put(self.key.clone(), value); + if let Some(pool) = self.pool.upgrade() { + // Pooled should not have had a real reference if pool is + // not enabled! + debug_assert!(pool.enabled); + + if let Ok(mut inner) = pool.connections.lock() { + inner.put(self.key.clone(), value, &pool); } } else if self.key.1 == Ver::Http1 { trace!("pool dropped, dropping pooled ({:?})", self.key); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -569,7 +619,7 @@ impl<T: Poolable> Future for Checkout<T> { impl<T> Drop for Checkout<T> { fn drop(&mut self) { if self.waiter.take().is_some() { - if let Ok(mut inner) = self.pool.inner.lock() { + if let Ok(mut inner) = self.pool.inner.connections.lock() { inner.clean_waiters(&self.key); } } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -578,14 +628,14 @@ impl<T> Drop for Checkout<T> { pub(super) struct Connecting<T: Poolable> { key: Key, - pool: Weak<Mutex<PoolInner<T>>>, + pool: Weak<PoolInner<T>>, } impl<T: Poolable> Drop for Connecting<T> { fn drop(&mut self) { if let Some(pool) = self.pool.upgrade() { // No need to panic on drop, that could abort! - if let Ok(mut inner) = pool.lock() { + if let Ok(mut inner) = pool.connections.lock() { debug_assert_eq!( self.key.1, Ver::Http2, diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -612,20 +662,25 @@ impl Expiration { } } +#[cfg(feature = "runtime")] struct IdleInterval<T> { interval: Interval, - pool: Weak<Mutex<PoolInner<T>>>, + pool: Weak<PoolInner<T>>, // This allows the IdleInterval to be notified as soon as the entire // Pool is fully dropped, and shutdown. This channel is never sent on, // but Err(Canceled) will be received when the Pool is dropped. - pool_drop_notifier: oneshot::Receiver<Never>, + pool_drop_notifier: oneshot::Receiver<::common::Never>, } +#[cfg(feature = "runtime")] impl<T: Poolable + 'static> Future for IdleInterval<T> { type Item = (); type Error = (); fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + // Interval is a Stream + use futures::Stream; + loop { match self.pool_drop_notifier.poll() { Ok(Async::Ready(n)) => match n {}, diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -636,10 +691,13 @@ impl<T: Poolable + 'static> Future for IdleInterval<T> { } } - try_ready!(self.interval.poll().map_err(|_| unreachable!("interval cannot error"))); + try_ready!(self.interval.poll().map_err(|err| { + error!("idle interval timer error: {}", err); + })); if let Some(inner) = self.pool.upgrade() { - if let Ok(mut inner) = inner.lock() { + if let Ok(mut inner) = inner.connections.lock() { + trace!("idle interval checking for expired"); inner.clear_expired(); continue; } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -19,7 +19,6 @@ extern crate bytes; #[macro_use] extern crate futures; #[cfg(feature = "runtime")] extern crate futures_cpupool; -extern crate futures_timer; extern crate h2; extern crate http; extern crate httparse; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -423,7 +423,7 @@ where Ok(Async::Ready(None)) }, Ok(Async::NotReady) => return Ok(Async::NotReady), - Err(_) => unreachable!("receiver cannot error"), + Err(never) => match never {}, } } diff --git a/src/server/tcp.rs b/src/server/tcp.rs --- a/src/server/tcp.rs +++ b/src/server/tcp.rs @@ -1,12 +1,12 @@ use std::fmt; use std::io; use std::net::{SocketAddr, TcpListener as StdTcpListener}; -use std::time::Duration; +use std::time::{Duration, Instant}; use futures::{Async, Future, Poll, Stream}; -use futures_timer::Delay; -use tokio_tcp::TcpListener; use tokio_reactor::Handle; +use tokio_tcp::TcpListener; +use tokio_timer::Delay; use self::addr_stream::AddrStream; diff --git a/src/server/tcp.rs b/src/server/tcp.rs --- a/src/server/tcp.rs +++ b/src/server/tcp.rs @@ -93,9 +93,12 @@ impl Stream for AddrIncoming { fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { // Check if a previous timeout is active that was set by IO errors. if let Some(ref mut to) = self.timeout { - match to.poll().expect("timeout never fails") { - Async::Ready(_) => {} - Async::NotReady => return Ok(Async::NotReady), + match to.poll() { + Ok(Async::Ready(())) => {} + Ok(Async::NotReady) => return Ok(Async::NotReady), + Err(err) => { + error!("sleep timer error: {}", err); + } } } self.timeout = None; diff --git a/src/server/tcp.rs b/src/server/tcp.rs --- a/src/server/tcp.rs +++ b/src/server/tcp.rs @@ -113,28 +116,38 @@ impl Stream for AddrIncoming { return Ok(Async::Ready(Some(AddrStream::new(socket, addr)))); }, Ok(Async::NotReady) => return Ok(Async::NotReady), - Err(ref e) if self.sleep_on_errors => { - // Connection errors can be ignored directly, continue by - // accepting the next request. - if is_connection_error(e) { - debug!("accepted connection already errored: {}", e); - continue; - } - // Sleep 1s. - let delay = Duration::from_secs(1); - error!("accept error: {}", e); - let mut timeout = Delay::new(delay); - let result = timeout.poll() - .expect("timeout never fails"); - match result { - Async::Ready(()) => continue, - Async::NotReady => { - self.timeout = Some(timeout); - return Ok(Async::NotReady); + Err(e) => { + if self.sleep_on_errors { + // Connection errors can be ignored directly, continue by + // accepting the next request. + if is_connection_error(&e) { + debug!("accepted connection already errored: {}", e); + continue; + } + // Sleep 1s. + let delay = Instant::now() + Duration::from_secs(1); + let mut timeout = Delay::new(delay); + + match timeout.poll() { + Ok(Async::Ready(())) => { + // Wow, it's been a second already? Ok then... + error!("accept error: {}", e); + continue + }, + Ok(Async::NotReady) => { + error!("accept error: {}", e); + self.timeout = Some(timeout); + return Ok(Async::NotReady); + }, + Err(timer_err) => { + error!("couldn't sleep on error, timer error: {}", timer_err); + return Err(e); + } } + } else { + return Err(e); } }, - Err(e) => return Err(e), } } }
diff --git a/.travis.yml b/.travis.yml --- a/.travis.yml +++ b/.travis.yml @@ -18,7 +18,7 @@ cache: script: - ./.travis/readme.py - cargo build $FEATURES - - 'if [ "$BUILD_ONLY" != "1" ]; then RUST_LOG=hyper cargo test $FEATURES; fi' + - 'if [ "$BUILD_ONLY" != "1" ]; then RUST_LOG=hyper cargo test $FEATURES -- --test-threads=1; fi' - 'if [ $TRAVIS_RUST_VERSION = nightly ]; then for f in ./benches/*.rs; do cargo test --bench $(basename $f .rs) $FEATURES; done; fi' addons: diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -20,7 +21,7 @@ pub(super) struct Pool<T> { // This is a trait to allow the `client::pool::tests` to work for `i32`. // // See https://github.com/hyperium/hyper/issues/1429 -pub(super) trait Poolable: Sized { +pub(super) trait Poolable: Send + Sized + 'static { fn is_open(&self) -> bool; /// Reserve this connection. /// diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -65,23 +75,44 @@ struct PoolInner<T> { // them that the Conn could be used instead of waiting for a brand new // connection. waiters: HashMap<Key, VecDeque<oneshot::Sender<T>>>, - timeout: Option<Duration>, // A oneshot channel is used to allow the interval to be notified when // the Pool completely drops. That way, the interval can cancel immediately. - idle_interval_ref: Option<oneshot::Sender<Never>>, + #[cfg(feature = "runtime")] + idle_interval_ref: Option<oneshot::Sender<::common::Never>>, + #[cfg(feature = "runtime")] + exec: Exec, + timeout: Option<Duration>, } impl<T> Pool<T> { - pub fn new(enabled: bool, timeout: Option<Duration>) -> Pool<T> { + pub fn new(enabled: bool, timeout: Option<Duration>, __exec: &Exec) -> Pool<T> { Pool { - inner: Arc::new(Mutex::new(PoolInner { - connecting: HashSet::new(), - enabled: enabled, - idle: HashMap::new(), - idle_interval_ref: None, - waiters: HashMap::new(), - timeout: timeout, - })), + inner: Arc::new(PoolInner { + connections: Mutex::new(Connections { + connecting: HashSet::new(), + idle: HashMap::new(), + #[cfg(feature = "runtime")] + idle_interval_ref: None, + waiters: HashMap::new(), + #[cfg(feature = "runtime")] + exec: __exec.clone(), + timeout, + }), + enabled, + weak: Weak::new(), + }), + } + } + + #[cfg(test)] + pub(super) fn no_timer(&self) { + // Prevent an actual interval from being created for this pool... + #[cfg(feature = "runtime")] + { + let mut inner = self.inner.connections.lock().unwrap(); + assert!(inner.idle_interval_ref.is_none(), "timer already spawned"); + let (tx, _) = oneshot::channel(); + inner.idle_interval_ref = Some(tx); } } } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -655,13 +713,14 @@ mod tests { use std::time::Duration; use futures::{Async, Future}; use futures::future; + use common::Exec; use super::{Connecting, Key, Poolable, Pool, Reservation, Ver}; /// Test unique reservations. #[derive(Debug, PartialEq, Eq)] struct Uniq<T>(T); - impl<T> Poolable for Uniq<T> { + impl<T: Send + 'static> Poolable for Uniq<T> { fn is_open(&self) -> bool { true } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -678,9 +737,15 @@ mod tests { } } + fn pool_no_timer<T>() -> Pool<T> { + let pool = Pool::new(true, Some(Duration::from_millis(100)), &Exec::Default); + pool.no_timer(); + pool + } + #[test] fn test_pool_checkout_smoke() { - let pool = Pool::new(true, Some(Duration::from_secs(5))); + let pool = pool_no_timer(); let key = (Arc::new("foo".to_string()), Ver::Http1); let pooled = pool.pooled(c(key.clone()), Uniq(41)); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -695,11 +760,11 @@ mod tests { #[test] fn test_pool_checkout_returns_none_if_expired() { future::lazy(|| { - let pool = Pool::new(true, Some(Duration::from_millis(100))); + let pool = pool_no_timer(); let key = (Arc::new("foo".to_string()), Ver::Http1); let pooled = pool.pooled(c(key.clone()), Uniq(41)); drop(pooled); - ::std::thread::sleep(pool.inner.lock().unwrap().timeout.unwrap()); + ::std::thread::sleep(pool.inner.connections.lock().unwrap().timeout.unwrap()); assert!(pool.checkout(key).poll().unwrap().is_not_ready()); ::futures::future::ok::<(), ()>(()) }).wait().unwrap(); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -708,19 +773,19 @@ mod tests { #[test] fn test_pool_checkout_removes_expired() { future::lazy(|| { - let pool = Pool::new(true, Some(Duration::from_millis(100))); + let pool = pool_no_timer(); let key = (Arc::new("foo".to_string()), Ver::Http1); pool.pooled(c(key.clone()), Uniq(41)); pool.pooled(c(key.clone()), Uniq(5)); pool.pooled(c(key.clone()), Uniq(99)); - assert_eq!(pool.inner.lock().unwrap().idle.get(&key).map(|entries| entries.len()), Some(3)); - ::std::thread::sleep(pool.inner.lock().unwrap().timeout.unwrap()); + assert_eq!(pool.inner.connections.lock().unwrap().idle.get(&key).map(|entries| entries.len()), Some(3)); + ::std::thread::sleep(pool.inner.connections.lock().unwrap().timeout.unwrap()); // checkout.poll() should clean out the expired pool.checkout(key.clone()).poll().unwrap(); - assert!(pool.inner.lock().unwrap().idle.get(&key).is_none()); + assert!(pool.inner.connections.lock().unwrap().idle.get(&key).is_none()); Ok::<(), ()>(()) }).wait().unwrap(); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -730,30 +795,26 @@ mod tests { #[test] fn test_pool_timer_removes_expired() { use std::sync::Arc; - use common::Exec; let runtime = ::tokio::runtime::Runtime::new().unwrap(); - let pool = Pool::new(true, Some(Duration::from_millis(100))); - let executor = runtime.executor(); - pool.spawn_expired_interval(&Exec::Executor(Arc::new(executor))); + let pool = Pool::new(true, Some(Duration::from_millis(100)), &Exec::Executor(Arc::new(executor))); + let key = (Arc::new("foo".to_string()), Ver::Http1); pool.pooled(c(key.clone()), Uniq(41)); pool.pooled(c(key.clone()), Uniq(5)); pool.pooled(c(key.clone()), Uniq(99)); - assert_eq!(pool.inner.lock().unwrap().idle.get(&key).map(|entries| entries.len()), Some(3)); + assert_eq!(pool.inner.connections.lock().unwrap().idle.get(&key).map(|entries| entries.len()), Some(3)); - ::futures_timer::Delay::new( - Duration::from_millis(400) // allow for too-good resolution - ).wait().unwrap(); + ::std::thread::sleep(Duration::from_millis(400)); // allow for too-good resolution - assert!(pool.inner.lock().unwrap().idle.get(&key).is_none()); + assert!(pool.inner.connections.lock().unwrap().idle.get(&key).is_none()); } #[test] fn test_pool_checkout_task_unparked() { - let pool = Pool::new(true, Some(Duration::from_secs(10))); + let pool = pool_no_timer(); let key = (Arc::new("foo".to_string()), Ver::Http1); let pooled = pool.pooled(c(key.clone()), Uniq(41)); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -772,7 +833,7 @@ mod tests { #[test] fn test_pool_checkout_drop_cleans_up_waiters() { future::lazy(|| { - let pool = Pool::<Uniq<i32>>::new(true, Some(Duration::from_secs(10))); + let pool = pool_no_timer::<Uniq<i32>>(); let key = (Arc::new("localhost:12345".to_string()), Ver::Http1); let mut checkout1 = pool.checkout(key.clone()); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -780,16 +841,16 @@ mod tests { // first poll needed to get into Pool's parked checkout1.poll().unwrap(); - assert_eq!(pool.inner.lock().unwrap().waiters.get(&key).unwrap().len(), 1); + assert_eq!(pool.inner.connections.lock().unwrap().waiters.get(&key).unwrap().len(), 1); checkout2.poll().unwrap(); - assert_eq!(pool.inner.lock().unwrap().waiters.get(&key).unwrap().len(), 2); + assert_eq!(pool.inner.connections.lock().unwrap().waiters.get(&key).unwrap().len(), 2); // on drop, clean up Pool drop(checkout1); - assert_eq!(pool.inner.lock().unwrap().waiters.get(&key).unwrap().len(), 1); + assert_eq!(pool.inner.connections.lock().unwrap().waiters.get(&key).unwrap().len(), 1); drop(checkout2); - assert!(pool.inner.lock().unwrap().waiters.get(&key).is_none()); + assert!(pool.inner.connections.lock().unwrap().waiters.get(&key).is_none()); ::futures::future::ok::<(), ()>(()) }).wait().unwrap(); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -813,13 +874,13 @@ mod tests { #[test] fn pooled_drop_if_closed_doesnt_reinsert() { - let pool = Pool::new(true, Some(Duration::from_secs(10))); + let pool = pool_no_timer(); let key = (Arc::new("localhost:12345".to_string()), Ver::Http1); pool.pooled(c(key.clone()), CanClose { val: 57, closed: true, }); - assert!(!pool.inner.lock().unwrap().idle.contains_key(&key)); + assert!(!pool.inner.connections.lock().unwrap().idle.contains_key(&key)); } } diff --git a/src/client/tests.rs b/src/client/tests.rs --- a/src/client/tests.rs +++ b/src/client/tests.rs @@ -25,6 +25,8 @@ fn retryable_request() { .executor(executor.sender().clone()) .build::<_, ::Body>(connector); + client.pool.no_timer(); + { let req = Request::builder() diff --git a/src/client/tests.rs b/src/client/tests.rs --- a/src/client/tests.rs +++ b/src/client/tests.rs @@ -71,6 +73,8 @@ fn conn_reset_after_write() { .executor(executor.sender().clone()) .build::<_, ::Body>(connector); + client.pool.no_timer(); + { let req = Request::builder() .uri("http://mock.local/a") diff --git a/src/client/tests.rs b/src/client/tests.rs --- a/src/client/tests.rs +++ b/src/client/tests.rs @@ -88,7 +92,7 @@ fn conn_reset_after_write() { } // sleep to allow some time for the connection to return to the pool - thread::sleep(Duration::from_millis(50)); + thread::sleep(Duration::from_millis(10)); let req = Request::builder() .uri("http://mock.local/a") diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -32,6 +31,7 @@ extern crate time; #[macro_use] extern crate tokio_io; #[cfg(feature = "runtime")] extern crate tokio_reactor; #[cfg(feature = "runtime")] extern crate tokio_tcp; +#[cfg(feature = "runtime")] extern crate tokio_timer; extern crate want; #[cfg(all(test, feature = "nightly"))] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -160,6 +160,8 @@ macro_rules! test { let expected_res_body = Option::<&[u8]>::from($response_body) .unwrap_or_default(); assert_eq!(body.as_ref(), expected_res_body); + + runtime.shutdown_on_idle().wait().expect("rt shutdown"); } ); ( diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -202,8 +204,10 @@ macro_rules! test { let closure = infer_closure($err); if !closure(&err) { - panic!("expected error, unexpected variant: {:?}", err) + panic!("expected error, unexpected variant: {:?}", err); } + + runtime.shutdown_on_idle().wait().expect("rt shutdown"); } ); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -227,11 +231,6 @@ macro_rules! test { let addr = server.local_addr().expect("local_addr"); let runtime = $runtime; - let mut config = Client::builder(); - config.http1_title_case_headers($title_case_headers); - if !$set_host { - config.set_host(false); - } let connector = ::hyper::client::HttpConnector::new_with_handle(1, runtime.reactor().clone()); let client = Client::builder() .set_host($set_host) diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -923,7 +922,6 @@ mod dispatch_impl { client.request(req) }; - //let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); res.select2(rx1).wait().unwrap(); // res now dropped let t = Delay::new(Duration::from_millis(100)) diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1088,54 +1086,6 @@ mod dispatch_impl { let _ = t.select(close).wait(); } - #[test] - fn client_custom_executor() { - let server = TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = server.local_addr().unwrap(); - let runtime = Runtime::new().unwrap(); - let handle = runtime.reactor(); - let (closes_tx, closes) = mpsc::channel(10); - - let (tx1, rx1) = oneshot::channel(); - - thread::spawn(move || { - let mut sock = server.accept().unwrap().0; - sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); - sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); - let mut buf = [0; 4096]; - sock.read(&mut buf).expect("read 1"); - sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap(); - let _ = tx1.send(()); - }); - - let client = Client::builder() - .executor(runtime.executor()) - .build(DebugConnector::with_http_and_closes(HttpConnector::new_with_handle(1, handle.clone()), closes_tx)); - - let req = Request::builder() - .uri(&*format!("http://{}/a", addr)) - .body(Body::empty()) - .unwrap(); - let res = client.request(req).and_then(move |res| { - assert_eq!(res.status(), hyper::StatusCode::OK); - res.into_body().concat2() - }); - let rx = rx1.expect("thread panicked"); - - let timeout = Delay::new(Duration::from_millis(200)); - let rx = rx.and_then(move |_| timeout.expect("timeout")); - res.join(rx).map(|r| r.0).wait().unwrap(); - - let t = Delay::new(Duration::from_millis(100)) - .map(|_| panic!("time out")); - let close = closes.into_future() - .map(|(opt, _)| { - opt.expect("closes"); - }) - .map_err(|_| panic!("closes dropped")); - let _ = t.select(close).wait(); - } - #[test] fn connect_call_is_lazy() { // We especially don't want connects() triggered if there's diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1168,8 +1118,7 @@ mod dispatch_impl { let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let runtime = Runtime::new().unwrap(); - let handle = runtime.reactor(); - let connector = DebugConnector::new(&handle); + let connector = DebugConnector::new(runtime.reactor()); let connects = connector.connects.clone(); let client = Client::builder() diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1222,6 +1171,9 @@ mod dispatch_impl { res.join(rx).map(|r| r.0).wait().unwrap(); assert_eq!(connects.load(Ordering::SeqCst), 1, "second request should still only have 1 connect"); + drop(client); + + runtime.shutdown_on_idle().wait().expect("rt shutdown"); } #[test]
Replace futures-timer usage with tokio-timer
I'll happily take this one! @srijs I try to port it last night, but tokio-timer require work with `Runtime`, so in many test cases, `res.join(...).wait()` not work well. Good luck! Oh, interesting! If tokio's `current_thread` executor could be updated to use a timer as well, we could probably change all `wait`s to use that, but it doesn't currently do so. I've also been thinking that hyper could have some `common::Timer` internal type, kind of like `common::Exec`. Doing this would probably even be easier than switching all `wait`s over. Benefits: - Finer control over a specific timer, if someone doesn't want to use the implicit default. - Would support making the tokio Runtime optional, in case someone wanted to build hyper with their own runtime. - Would allow it to work with `wait`. If no timer were available, timeouts and intervals would effectively just be disabled. That shouldn't be a problem. Here's some code I was thinking of: ```rust enum TimerImpl { Default, Empty, Timer(Arc<Timer>), } trait Timer { type Delay: Future; fn delay(&self, until: Instant) -> Self::Delay; } ``` The default would use tokio-timer implicitly, the empty would simply return `future::empty()`, and the trait would allow for custom timers. We'd implement `Timer` for `tokio_timer::Handle`. Probably the types wouldn't be exported publicly, but the client and server builders could have `timer` functions like their respective `executor` functions. Maybe the "require" not correct, use `wait()` directly will get a `Shutdown` error, but it work fine with `Runtime::spawn(..)`. I can't find a doc clarify this behavior. Maybe it can work with the `current_thread`. I like the idea of making the timer optional, that seems like it would work well with keeping the current calls to `wait()` as they are, and just not use a timer in those cases (unless the test explicitly tests timeouts/intervals). However I'm not sure if it's worth abstracting away `tokio-timer`? The `Timer` logic in `tokio-timer` can be used independently of the tokio runtime, so it should be flexible enough for most use-cases. So what about a slightly simpler solution? ```rust enum Timer { Empty, Default, Custom(tokio_timer::Handle) } ``` That avoids having to box futures to abstract across `Timer` impls, and still allows for some degree of flexibility. That's probably fine too. I mostly was thinking that there are cases where you could want to use hyper, but already have some other runtime. For that reason, I do expect to make the tokio dependency optional (enabled by default) likely by the 0.12 release. I also figured people might already be using a different timer implementation, such as using the older tokio-core. But it's not required to provide that yet. I just would rather not actually expose a dependency on tokio-timer in a type signature, so I actually would rather box a trait object, like is done with `Executor`, instead of accepting tokio's `TaskExecutor` directly.
2018-04-27T23:17:09Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,497
hyperium__hyper-1497
[ "1492" ]
988dc7c637bc54e97a325a95d1e10d39d5fc8b2d
diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -67,6 +67,7 @@ where pub struct Builder { exec: Exec, h1_writev: bool, + h1_title_case_headers: bool, http2: bool, } diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -419,6 +420,7 @@ impl Builder { Builder { exec: Exec::Default, h1_writev: true, + h1_title_case_headers: false, http2: false, } } diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -435,6 +437,11 @@ impl Builder { self } + pub(super) fn h1_title_case_headers(&mut self, enabled: bool) -> &mut Builder { + self.h1_title_case_headers = enabled; + self + } + /// Sets whether HTTP2 is required. /// /// Default is false. diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -550,6 +557,9 @@ where if !self.builder.h1_writev { conn.set_write_strategy_flatten(); } + if self.builder.h1_title_case_headers { + conn.set_title_case_headers(); + } let cd = proto::h1::dispatch::Client::new(rx); let dispatch = proto::h1::Dispatcher::new(cd, conn); Either::A(dispatch) diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -34,6 +34,7 @@ pub struct Client<C, B = Body> { connector: Arc<C>, executor: Exec, h1_writev: bool, + h1_title_case_headers: bool, pool: Pool<PoolClient<B>>, retry_canceled_requests: bool, set_host: bool, diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -186,6 +187,7 @@ where C: Connect + Sync + 'static, let executor = self.executor.clone(); let pool = self.pool.clone(); let h1_writev = self.h1_writev; + let h1_title_case_headers = self.h1_title_case_headers; let connector = self.connector.clone(); let dst = Destination { uri: url, diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -197,6 +199,7 @@ where C: Connect + Sync + 'static, .and_then(move |(io, connected)| { conn::Builder::new() .h1_writev(h1_writev) + .h1_title_case_headers(h1_title_case_headers) .http2_only(pool_key.1 == Ver::Http2) .handshake_no_upgrades(io) .and_then(move |(tx, conn)| { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -335,6 +338,7 @@ impl<C, B> Clone for Client<C, B> { connector: self.connector.clone(), executor: self.executor.clone(), h1_writev: self.h1_writev, + h1_title_case_headers: self.h1_title_case_headers, pool: self.pool.clone(), retry_canceled_requests: self.retry_canceled_requests, set_host: self.set_host, diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -526,6 +530,7 @@ pub struct Builder { keep_alive: bool, keep_alive_timeout: Option<Duration>, h1_writev: bool, + h1_title_case_headers: bool, //TODO: make use of max_idle config max_idle: usize, retry_canceled_requests: bool, diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -540,6 +545,7 @@ impl Default for Builder { keep_alive: true, keep_alive_timeout: Some(Duration::from_secs(90)), h1_writev: true, + h1_title_case_headers: false, max_idle: 5, retry_canceled_requests: true, set_host: true, diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -583,6 +589,17 @@ impl Builder { self } + /// Set whether HTTP/1 connections will write header names as title case at + /// the socket level. + /// + /// Note that this setting does not affect HTTP/2. + /// + /// Default is false. + pub fn http1_title_case_headers(&mut self, val: bool) -> &mut Self { + self.h1_title_case_headers = val; + self + } + /// Set whether the connection **must** use HTTP/2. /// /// Note that setting this to true prevents HTTP/1 from being allowed. diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -662,6 +679,7 @@ impl Builder { connector: Arc::new(connector), executor: self.exec.clone(), h1_writev: self.h1_writev, + h1_title_case_headers: self.h1_title_case_headers, pool: Pool::new(self.keep_alive, self.keep_alive_timeout), retry_canceled_requests: self.retry_canceled_requests, set_host: self.set_host, diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -50,6 +50,7 @@ where I: AsyncRead + AsyncWrite, error: None, keep_alive: KA::Busy, method: None, + title_case_headers: false, read_task: None, reading: Reading::Init, writing: Writing::Init, diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -73,6 +74,10 @@ where I: AsyncRead + AsyncWrite, self.io.set_write_strategy_flatten(); } + pub fn set_title_case_headers(&mut self) { + self.state.title_case_headers = true; + } + pub fn into_inner(self) -> (I, Bytes) { self.io.into_inner() } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -430,7 +435,7 @@ where I: AsyncRead + AsyncWrite, self.enforce_version(&mut head); let buf = self.io.write_buf_mut(); - self.state.writing = match T::encode(head, body, &mut self.state.method, buf) { + self.state.writing = match T::encode(head, body, &mut self.state.method, self.state.title_case_headers, buf) { Ok(encoder) => { if !encoder.is_eof() { Writing::Body(encoder) diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -620,6 +625,7 @@ struct State { error: Option<::Error>, keep_alive: KA, method: Option<Method>, + title_case_headers: bool, read_task: Option<Task>, reading: Reading, writing: Writing, diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -649,6 +655,7 @@ impl fmt::Debug for State { .field("keep_alive", &self.keep_alive) .field("error", &self.error) //.field("method", &self.method) + //.field("title_case_headers", &self.title_case_headers) .field("read_task", &self.read_task) .finish() } diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -126,6 +126,7 @@ where mut head: MessageHead<Self::Outgoing>, body: Option<BodyLength>, method: &mut Option<Method>, + _title_case_headers: bool, dst: &mut Vec<u8>, ) -> ::Result<Encoder> { trace!("Server::encode body={:?}, method={:?}", body, method); diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -367,6 +368,7 @@ where mut head: MessageHead<Self::Outgoing>, body: Option<BodyLength>, method: &mut Option<Method>, + title_case_headers: bool, dst: &mut Vec<u8>, ) -> ::Result<Encoder> { trace!("Client::encode body={:?}, method={:?}", body, method); diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -391,7 +393,11 @@ where } extend(dst, b"\r\n"); - write_headers(&head.headers, dst); + if title_case_headers { + write_headers_title_case(&head.headers, dst); + } else { + write_headers(&head.headers, dst); + } extend(dst, b"\r\n"); Ok(body) diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -635,6 +641,44 @@ impl<'a> Iterator for HeadersAsBytesIter<'a> { } } +// Write header names as title case. The header name is assumed to be ASCII, +// therefore it is trivial to convert an ASCII character from lowercase to +// uppercase. It is as simple as XORing the lowercase character byte with +// space. +fn title_case(dst: &mut Vec<u8>, name: &[u8]) { + dst.reserve(name.len()); + + let mut iter = name.iter(); + + // Uppercase the first character + if let Some(c) = iter.next() { + if *c >= b'a' && *c <= b'z' { + dst.push(*c ^ b' '); + } + } + + while let Some(c) = iter.next() { + dst.push(*c); + + if *c == b'-' { + if let Some(c) = iter.next() { + if *c >= b'a' && *c <= b'z' { + dst.push(*c ^ b' '); + } + } + } + } +} + +fn write_headers_title_case(headers: &HeaderMap, dst: &mut Vec<u8>) { + for (name, value) in headers { + title_case(dst, name.as_str().as_bytes()); + extend(dst, b": "); + extend(dst, value.as_bytes()); + extend(dst, b"\r\n"); + } +} + fn write_headers(headers: &HeaderMap, dst: &mut Vec<u8>) { for (name, value) in headers { extend(dst, name.as_str().as_bytes()); diff --git a/src/proto/mod.rs b/src/proto/mod.rs --- a/src/proto/mod.rs +++ b/src/proto/mod.rs @@ -72,6 +72,7 @@ pub(crate) trait Http1Transaction { head: MessageHead<Self::Outgoing>, body: Option<BodyLength>, method: &mut Option<Method>, + title_case_headers: bool, dst: &mut Vec<u8>, ) -> ::Result<h1::Encoder>; fn on_error(err: &::Error) -> Option<MessageHead<Self::Outgoing>>;
diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -857,6 +901,21 @@ mod tests { Client::decoder(&head, method).unwrap_err(); } + #[test] + fn test_client_request_encode_title_case() { + use http::header::HeaderValue; + use proto::BodyLength; + + let mut head = MessageHead::default(); + head.headers.insert("content-length", HeaderValue::from_static("10")); + head.headers.insert("content-type", HeaderValue::from_static("application/json")); + + let mut vec = Vec::new(); + Client::encode(head, Some(BodyLength::Known(10)), &mut None, true, &mut vec).unwrap(); + + assert_eq!(vec, b"GET / HTTP/1.1\r\nContent-Length: 10\r\nContent-Type: application/json\r\n\r\n".to_vec()); + } + #[cfg(feature = "nightly")] use test::Bencher; diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -914,7 +973,7 @@ mod tests { b.iter(|| { let mut vec = Vec::new(); - Server::encode(head.clone(), Some(BodyLength::Known(10)), &mut None, &mut vec).unwrap(); + Server::encode(head.clone(), Some(BodyLength::Known(10)), &mut None, false, &mut vec).unwrap(); assert_eq!(vec.len(), len); ::test::black_box(vec); }) diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -84,6 +84,45 @@ macro_rules! test { headers: { $($response_header_name:expr => $response_header_val:expr,)* }, body: $response_body:expr, ) => ( + test! { + name: $name, + server: + expected: $server_expected, + reply: $server_reply, + client: + set_host: $set_host, + title_case_headers: false, + request: + method: $client_method, + url: $client_url, + headers: { $($request_header_name => $request_header_val,)* }, + body: $request_body, + + response: + status: $client_status, + headers: { $($response_header_name => $response_header_val,)* }, + body: $response_body, + } + ); + ( + name: $name:ident, + server: + expected: $server_expected:expr, + reply: $server_reply:expr, + client: + set_host: $set_host:expr, + title_case_headers: $title_case_headers:expr, + request: + method: $client_method:ident, + url: $client_url:expr, + headers: { $($request_header_name:expr => $request_header_val:expr,)* }, + body: $request_body:expr, + + response: + status: $client_status:ident, + headers: { $($response_header_name:expr => $response_header_val:expr,)* }, + body: $response_body:expr, + ) => ( #[test] fn $name() { let _ = pretty_env_logger::try_init(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -98,6 +137,7 @@ macro_rules! test { reply: $server_reply, client: set_host: $set_host, + title_case_headers: $title_case_headers, request: method: $client_method, url: $client_url, diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -113,7 +153,6 @@ macro_rules! test { let body = res .into_body() - .concat2() .wait() .expect("body concat wait"); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -151,6 +190,7 @@ macro_rules! test { reply: $server_reply, client: set_host: true, + title_case_headers: false, request: method: $client_method, url: $client_url, diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -176,6 +216,7 @@ macro_rules! test { reply: $server_reply:expr, client: set_host: $set_host:expr, + title_case_headers: $title_case_headers:expr, request: method: $client_method:ident, url: $client_url:expr, diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -187,12 +228,14 @@ macro_rules! test { let runtime = $runtime; let mut config = Client::builder(); + config.http1_title_case_headers($title_case_headers); if !$set_host { config.set_host(false); } let connector = ::hyper::client::HttpConnector::new_with_handle(1, runtime.reactor().clone()); let client = Client::builder() .set_host($set_host) + .http1_title_case_headers($title_case_headers) .executor(runtime.executor()) .build(connector); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -631,6 +674,38 @@ test! { body: None, } +test! { + name: client_set_http1_title_case_headers, + + server: + expected: "\ + GET / HTTP/1.1\r\n\ + X-Test-Header: test\r\n\ + Host: {addr}\r\n\ + \r\n\ + ", + reply: "\ + HTTP/1.1 200 OK\r\n\ + Content-Length: 0\r\n\ + \r\n\ + ", + + client: + set_host: true, + title_case_headers: true, + request: + method: GET, + url: "http://{addr}/", + headers: { + "X-Test-Header" => "test", + }, + body: None, + response: + status: OK, + headers: {}, + body: None, +} + mod dispatch_impl { use super::*; use std::io::{self, Read, Write};
Headers are lower-cased when sent and no option to disable this feature. I am trying to use Hyper with a stubborn web service that does not like requests with headers that do not have the first letter of each word capitalized (`Content-Length` for example). I tried out some other HTTP client libraries for Rust (like `tk-http` which hasn't been updated recently and `mio_httpc` which doesn't work all the time with said web service), but Hyper doesn't have the issues as with the other libraries except for the header name mangling. After reading the RFC regarding header casing, I see that header names are supposed to be case-insensitive, so Hyper is not at fault here and from looking at `HeaderMap` I see that it relies on headers being lower-cased for performance. If it is not possible to accommodate case-sensitive header names, then could it be possible to directly provide an array of headers to be used in an HTTP request?
I expected this problem to appear eventually. Clearly, the best thing to happen is for that server software to be fixed. But, I realized that there is likely other janky server software out there that also relies on title case, just rotting with no fix to ever come... Possibly a solution could be for hyper to add an configuration option to force all header names to Title Case **when writing to the socket**. It could be some `title_case(dst: &mut Vec<u8>, name: &str) {}`, that intercepts and pushes upper-case bytes onto the destination... That would perfectly fit my use case and not affect the functionality of the headers API for general use of the client library part of Hyper. Currently investigating how headers are written for HTTP/1.0 and HTTP/1.1 connections. I found the `write_headers` function[1] and see that the client calls it when it is encoding the response. Is it more preferable to include a boolean parameter to tell `write_headers` to use title case or duplicate the `write_headers` function into one named, for example, `write_headers_title_case` and replace the `extend` call for the header name with one to `title_case(dst, name)`? [1] https://github.com/hyperium/hyper/blob/dfdca25c004aeb583b931f57e19510b3096362e3/src/proto/h1/role.rs#L638-L645 It's probably preferable to not have to check a boolean in a loop, so probably a second function. Alright, that's what I did for my naive example code (that's still WIP and unpublished). Is it preferable to search for the hyphen and capitalize the next character? Or go character by character in a for loop keeping state in a boolean to capitalize the next character? Or using a `while let Some` loop so I could use `chars.next()` to avoid using a boolean to store state? My naive example: ```rust fn title_case(dst: &mut Vec<u8>, name: &str) { dst.reserve(name.len()); let mut should_capitalize = true; for c in name.chars() { if should_capitalize { should_capitalize = false; for c in c.to_uppercase() { dst.push(c as u8); } } else { if c == '-' { should_capitalize = true; } dst.push(c as u8); } } } ``` A `while let Some` version: ```rust fn title_case(dst: &mut Vec<u8>, name: &str) { dst.reserve(name.len()); let mut iter = name.chars(); let push_uppercase = |dst: &mut Vec<u8>, iter: &mut ::std::str::Chars| { if let Some(c) = iter.next() { for c in c.to_uppercase() { dst.push(c as u8); } } }; push_uppercase(dst, &mut iter); while let Some(c) = iter.next() { dst.push(c as u8); if c == '-' { push_uppercase(dst, &mut iter); } } } ``` Since header names are required to be ASCII, you can just work with the bytes directly. That has better performance than `char`. Revised this to use a byte slice (`&[u8]`) instead of a `&str`. I see that lowercase to uppercase conversion of ASCII characters can be done by XORing the lowercase byte with `b' '` to get the uppercase character byte. I probably should open up a PR for this now, but I am still trying to work out how to add a configuration option to toggle between title case and straight lowercase output. Your use case is the client, right? So it could start there... 1. Add some sort of `http1_title_case_headers` method to `hyper::client::Builder`. 2. Pass the value of that when constructing the `hyper::proto::h1::Conn`. 3. Pass that value to `Http1Transaction::decode`.
2018-04-23T21:21:54Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,490
hyperium__hyper-1490
[ "1461" ]
71a15c25f583dcb8dacc21904cf44c658cf429b8
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -34,7 +34,6 @@ net2 = "0.2.32" time = "0.1" tokio = "0.1.5" tokio-executor = "0.1.0" -tokio-service = "0.1" tokio-io = "0.1" want = "0.0.3" diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -92,8 +92,7 @@ fn spawn_hello(rt: &mut Runtime) -> SocketAddr { .map_err(|(e, _inc)| panic!("accept error: {}", e)) .and_then(move |(accepted, _inc)| { let socket = accepted.expect("accepted socket"); - http.serve_connection(socket, service.new_service().expect("new_service")) - .map(|_| ()) + http.serve_connection(socket, service) .map_err(|_| ()) }); rt.spawn(srv); diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -11,11 +11,11 @@ use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::mpsc; -use futures::{future, stream, Future, Stream}; +use futures::{stream, Future, Stream}; use futures::sync::oneshot; -use hyper::{Body, Request, Response, Server}; -use hyper::server::Service; +use hyper::{Body, Response, Server}; +use hyper::service::service_fn_ok; macro_rules! bench_server { ($b:ident, $header:expr, $body:expr) => ({ diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -26,10 +26,17 @@ macro_rules! bench_server { ::std::thread::spawn(move || { let addr = "127.0.0.1:0".parse().unwrap(); let srv = Server::bind(&addr) - .serve(|| Ok(BenchPayload { - header: $header, - body: $body, - })); + .serve(|| { + let header = $header; + let body = $body; + service_fn_ok(move |_| { + Response::builder() + .header(header.0, header.1) + .header("content-type", "text/plain") + .body(body()) + .unwrap() + }) + }); addr_tx.send(srv.local_addr()).unwrap(); let fut = srv .map_err(|e| panic!("server error: {}", e)) diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -6,8 +6,8 @@ extern crate tokio; use futures::Future; -use hyper::{Body, Response}; -use hyper::server::{Server, const_service, service_fn}; +use hyper::{Body, Response, Server}; +use hyper::service::service_fn_ok; static PHRASE: &'static [u8] = b"Hello World!"; diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -16,10 +16,16 @@ fn main() { let addr = ([127, 0, 0, 1], 3000).into(); - let new_service = const_service(service_fn(|_| { - //TODO: when `!` is stable, replace error type - Ok::<_, hyper::Error>(Response::new(Body::from(PHRASE))) - })); + // new_service is run for each connection, creating a 'service' + // to handle requests for that specific connection. + let new_service = || { + // This is the `Service` that will handle the connection. + // `service_fn_ok` is a helper to convert a function that + // returns a Response into a `Service`. + service_fn_ok(|_| { + Response::new(Body::from(PHRASE)) + }) + }; let server = Server::bind(&addr) .serve(new_service) diff --git a/examples/multi_server.rs b/examples/multi_server.rs --- a/examples/multi_server.rs +++ b/examples/multi_server.rs @@ -5,39 +5,14 @@ extern crate pretty_env_logger; extern crate tokio; use futures::{Future}; -use futures::future::{FutureResult, lazy}; +use futures::future::{lazy}; -use hyper::{Body, Method, Request, Response, StatusCode}; -use hyper::server::{Server, Service}; +use hyper::{Body, Response, Server}; +use hyper::service::service_fn_ok; static INDEX1: &'static [u8] = b"The 1st service!"; static INDEX2: &'static [u8] = b"The 2nd service!"; -struct Srv(&'static [u8]); - -impl Service for Srv { - type Request = Request<Body>; - type Response = Response<Body>; - type Error = hyper::Error; - type Future = FutureResult<Response<Body>, hyper::Error>; - - fn call(&self, req: Request<Body>) -> Self::Future { - futures::future::ok(match (req.method(), req.uri().path()) { - (&Method::GET, "/") => { - Response::new(self.0.into()) - }, - _ => { - Response::builder() - .status(StatusCode::NOT_FOUND) - .body(Body::empty()) - .unwrap() - } - }) - } - -} - - fn main() { pretty_env_logger::init(); diff --git a/examples/multi_server.rs b/examples/multi_server.rs --- a/examples/multi_server.rs +++ b/examples/multi_server.rs @@ -46,11 +21,11 @@ fn main() { tokio::run(lazy(move || { let srv1 = Server::bind(&addr1) - .serve(|| Ok(Srv(INDEX1))) + .serve(|| service_fn_ok(|_| Response::new(Body::from(INDEX1)))) .map_err(|e| eprintln!("server 1 error: {}", e)); let srv2 = Server::bind(&addr2) - .serve(|| Ok(Srv(INDEX2))) + .serve(|| service_fn_ok(|_| Response::new(Body::from(INDEX2)))) .map_err(|e| eprintln!("server 2 error: {}", e)); println!("Listening on http://{} and http://{}", addr1, addr2); diff --git a/examples/params.rs b/examples/params.rs --- a/examples/params.rs +++ b/examples/params.rs @@ -5,10 +5,10 @@ extern crate pretty_env_logger; extern crate tokio; extern crate url; -use futures::{Future, Stream}; +use futures::{future, Future, Stream}; -use hyper::{Body, Method, Request, Response, StatusCode}; -use hyper::server::{Server, Service}; +use hyper::{Body, Method, Request, Response, Server, StatusCode}; +use hyper::service::service_fn; use std::collections::HashMap; use url::form_urlencoded; diff --git a/examples/params.rs b/examples/params.rs --- a/examples/params.rs +++ b/examples/params.rs @@ -17,89 +17,80 @@ static INDEX: &[u8] = b"<html><body><form action=\"post\" method=\"post\">Name: static MISSING: &[u8] = b"Missing field"; static NOTNUMERIC: &[u8] = b"Number field is not numeric"; -struct ParamExample; +// Using service_fn, we can turn this function into a `Service`. +fn param_example(req: Request<Body>) -> Box<Future<Item=Response<Body>, Error=hyper::Error> + Send> { + match (req.method(), req.uri().path()) { + (&Method::GET, "/") | (&Method::GET, "/post") => { + Box::new(future::ok(Response::new(INDEX.into()))) + }, + (&Method::POST, "/post") => { + Box::new(req.into_body().concat2().map(|b| { + // Parse the request body. form_urlencoded::parse + // always succeeds, but in general parsing may + // fail (for example, an invalid post of json), so + // returning early with BadRequest may be + // necessary. + // + // Warning: this is a simplified use case. In + // principle names can appear multiple times in a + // form, and the values should be rolled up into a + // HashMap<String, Vec<String>>. However in this + // example the simpler approach is sufficient. + let params = form_urlencoded::parse(b.as_ref()).into_owned().collect::<HashMap<String, String>>(); -impl Service for ParamExample { - type Request = Request<Body>; - type Response = Response<Body>; - type Error = hyper::Error; - type Future = Box<Future<Item = Self::Response, Error = Self::Error> + Send>; - - fn call(&self, req: Request<Body>) -> Self::Future { - match (req.method(), req.uri().path()) { - (&Method::GET, "/") | (&Method::GET, "/post") => { - Box::new(futures::future::ok(Response::new(INDEX.into()))) - }, - (&Method::POST, "/post") => { - Box::new(req.into_body().concat2().map(|b| { - // Parse the request body. form_urlencoded::parse - // always succeeds, but in general parsing may - // fail (for example, an invalid post of json), so - // returning early with BadRequest may be - // necessary. - // - // Warning: this is a simplified use case. In - // principle names can appear multiple times in a - // form, and the values should be rolled up into a - // HashMap<String, Vec<String>>. However in this - // example the simpler approach is sufficient. - let params = form_urlencoded::parse(b.as_ref()).into_owned().collect::<HashMap<String, String>>(); - - // Validate the request parameters, returning - // early if an invalid input is detected. - let name = if let Some(n) = params.get("name") { - n + // Validate the request parameters, returning + // early if an invalid input is detected. + let name = if let Some(n) = params.get("name") { + n + } else { + return Response::builder() + .status(StatusCode::UNPROCESSABLE_ENTITY) + .body(MISSING.into()) + .unwrap(); + }; + let number = if let Some(n) = params.get("number") { + if let Ok(v) = n.parse::<f64>() { + v } else { return Response::builder() .status(StatusCode::UNPROCESSABLE_ENTITY) - .body(MISSING.into()) + .body(NOTNUMERIC.into()) .unwrap(); - }; - let number = if let Some(n) = params.get("number") { - if let Ok(v) = n.parse::<f64>() { - v - } else { - return Response::builder() - .status(StatusCode::UNPROCESSABLE_ENTITY) - .body(NOTNUMERIC.into()) - .unwrap(); - } - } else { - return Response::builder() - .status(StatusCode::UNPROCESSABLE_ENTITY) - .body(MISSING.into()) - .unwrap(); - }; + } + } else { + return Response::builder() + .status(StatusCode::UNPROCESSABLE_ENTITY) + .body(MISSING.into()) + .unwrap(); + }; - // Render the response. This will often involve - // calls to a database or web service, which will - // require creating a new stream for the response - // body. Since those may fail, other error - // responses such as InternalServiceError may be - // needed here, too. - let body = format!("Hello {}, your number is {}", name, number); - Response::new(body.into()) - })) - }, - _ => { - Box::new(futures::future::ok(Response::builder() - .status(StatusCode::NOT_FOUND) - .body(Body::empty()) - .unwrap())) - } + // Render the response. This will often involve + // calls to a database or web service, which will + // require creating a new stream for the response + // body. Since those may fail, other error + // responses such as InternalServiceError may be + // needed here, too. + let body = format!("Hello {}, your number is {}", name, number); + Response::new(body.into()) + })) + }, + _ => { + Box::new(future::ok(Response::builder() + .status(StatusCode::NOT_FOUND) + .body(Body::empty()) + .unwrap())) } } } - fn main() { pretty_env_logger::init(); let addr = ([127, 0, 0, 1], 1337).into(); let server = Server::bind(&addr) - .serve(|| Ok(ParamExample)) + .serve(|| service_fn(param_example)) .map_err(|e| eprintln!("server error: {}", e)); tokio::run(server); diff --git a/examples/send_file.rs b/examples/send_file.rs --- a/examples/send_file.rs +++ b/examples/send_file.rs @@ -4,11 +4,11 @@ extern crate hyper; extern crate pretty_env_logger; extern crate tokio; -use futures::{Future/*, Sink*/}; +use futures::{future, Future}; use futures::sync::oneshot; -use hyper::{Body, /*Chunk,*/ Method, Request, Response, StatusCode}; -use hyper::server::{Server, Service}; +use hyper::{Body, Method, Request, Response, Server, StatusCode}; +use hyper::service::service_fn; use std::fs::File; use std::io::{self, copy/*, Read*/}; diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -5,37 +5,27 @@ extern crate pretty_env_logger; extern crate tokio; use futures::Future; -use futures::future::{FutureResult}; -use hyper::{Body, Method, Request, Response, StatusCode}; -use hyper::server::{Server, Service}; +use hyper::{Body, Method, Request, Response, Server, StatusCode}; +use hyper::service::service_fn_ok; static INDEX: &'static [u8] = b"Try POST /echo"; -struct Echo; - -impl Service for Echo { - type Request = Request<Body>; - type Response = Response<Body>; - type Error = hyper::Error; - type Future = FutureResult<Self::Response, Self::Error>; - - fn call(&self, req: Self::Request) -> Self::Future { - futures::future::ok(match (req.method(), req.uri().path()) { - (&Method::GET, "/") | (&Method::POST, "/") => { - Response::new(INDEX.into()) - }, - (&Method::POST, "/echo") => { - Response::new(req.into_body()) - }, - _ => { - let mut res = Response::new(Body::empty()); - *res.status_mut() = StatusCode::NOT_FOUND; - res - } - }) +// Using service_fn_ok, we can convert this function into a `Service`. +fn echo(req: Request<Body>) -> Response<Body> { + match (req.method(), req.uri().path()) { + (&Method::GET, "/") | (&Method::POST, "/") => { + Response::new(INDEX.into()) + }, + (&Method::POST, "/echo") => { + Response::new(req.into_body()) + }, + _ => { + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::NOT_FOUND; + res + } } - } diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -45,7 +35,7 @@ fn main() { let addr = ([127, 0, 0, 1], 1337).into(); let server = Server::bind(&addr) - .serve(|| Ok(Echo)) + .serve(|| service_fn_ok(echo)) .map_err(|e| eprintln!("server error: {}", e)); println!("Listening on http://{}", addr); diff --git a/examples/web_api.rs b/examples/web_api.rs --- a/examples/web_api.rs +++ b/examples/web_api.rs @@ -4,12 +4,11 @@ extern crate hyper; extern crate pretty_env_logger; extern crate tokio; -use futures::{Future, Stream}; -use futures::future::lazy; +use futures::{future, Future, Stream}; -use hyper::{Body, Chunk, Client, Method, Request, Response, StatusCode}; +use hyper::{Body, Chunk, Client, Method, Request, Response, Server, StatusCode}; use hyper::client::HttpConnector; -use hyper::server::{Server, Service}; +use hyper::service::service_fn; #[allow(unused, deprecated)] use std::ascii::AsciiExt; diff --git a/examples/web_api.rs b/examples/web_api.rs --- a/examples/web_api.rs +++ b/examples/web_api.rs @@ -89,3 +89,4 @@ fn main() { server })); } + diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -11,7 +11,6 @@ use futures::sync::oneshot; use http::{Method, Request, Response, Uri, Version}; use http::header::{Entry, HeaderValue, HOST}; use http::uri::Scheme; -pub use tokio_service::Service; use body::{Body, Payload}; use common::Exec; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -295,22 +294,6 @@ where C: Connect + Sync + 'static, } } -impl<C, B> Service for Client<C, B> -where C: Connect + 'static, - C::Future: 'static, - B: Payload + Send + 'static, - B::Data: Send, -{ - type Request = Request<B>; - type Response = Response<Body>; - type Error = ::Error; - type Future = FutureResponse; - - fn call(&self, req: Self::Request) -> Self::Future { - self.request(req) - } -} - impl<C, B> Clone for Client<C, B> { fn clone(&self) -> Client<C, B> { Client { diff --git a/src/common/mod.rs b/src/common/mod.rs --- a/src/common/mod.rs +++ b/src/common/mod.rs @@ -1,6 +1,5 @@ mod exec; +mod never; pub(crate) use self::exec::Exec; - -#[derive(Debug)] -pub enum Never {} +pub use self::never::Never; diff --git /dev/null b/src/common/never.rs new file mode 100644 --- /dev/null +++ b/src/common/never.rs @@ -0,0 +1,22 @@ +//! An uninhabitable type meaning it can never happen. +//! +//! To be replaced with `!` once it is stable. + +use std::error::Error; +use std::fmt; + +#[derive(Debug)] +pub enum Never {} + +impl fmt::Display for Never { + fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { + match *self {} + } +} + +impl Error for Never { + fn description(&self) -> &str { + match *self {} + } +} + diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -203,8 +203,8 @@ impl Error { Error::new(Kind::UnsupportedRequestMethod, None) } - pub(crate) fn new_user_new_service(err: io::Error) -> Error { - Error::new(Kind::NewService, Some(Box::new(err))) + pub(crate) fn new_user_new_service<E: Into<Cause>>(cause: E) -> Error { + Error::new(Kind::NewService, Some(cause.into())) } pub(crate) fn new_user_service<E: Into<Cause>>(cause: E) -> Error { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -62,3 +61,4 @@ pub mod error; mod headers; mod proto; pub mod server; +pub mod service; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -2,10 +2,10 @@ use bytes::Bytes; use futures::{Async, Future, Poll, Stream}; use http::{Request, Response, StatusCode}; use tokio_io::{AsyncRead, AsyncWrite}; -use tokio_service::Service; use body::{Body, Payload}; use proto::{BodyLength, Conn, Http1Transaction, MessageHead, RequestHead, RequestLine, ResponseHead}; +use service::Service; pub(crate) struct Dispatcher<D, Bs: Payload, I, T> { conn: Conn<I, Bs::Data, T>, diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -312,7 +312,7 @@ impl<S> Server<S> where S: Service { impl<S, Bs> Dispatch for Server<S> where - S: Service<Request=Request<Body>, Response=Response<Bs>>, + S: Service<ReqBody=Body, ResBody=Bs>, S::Error: Into<Box<::std::error::Error + Send + Sync>>, Bs: Payload, { diff --git a/src/proto/h2/server.rs b/src/proto/h2/server.rs --- a/src/proto/h2/server.rs +++ b/src/proto/h2/server.rs @@ -5,10 +5,10 @@ use tokio_io::{AsyncRead, AsyncWrite}; use ::body::Payload; use ::common::Exec; -use ::server::Service; +use ::service::Service; use super::{PipeToSendStream, SendBuf}; -use ::{Body, Request, Response}; +use ::{Body, Response}; pub(crate) struct Server<T, S, B> where diff --git a/src/proto/h2/server.rs b/src/proto/h2/server.rs --- a/src/proto/h2/server.rs +++ b/src/proto/h2/server.rs @@ -39,7 +39,7 @@ where impl<T, S, B> Server<T, S, B> where T: AsyncRead + AsyncWrite, - S: Service<Request=Request<Body>, Response=Response<B>>, + S: Service<ReqBody=Body, ResBody=B>, S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Future: Send + 'static, B: Payload, diff --git a/src/proto/h2/server.rs b/src/proto/h2/server.rs --- a/src/proto/h2/server.rs +++ b/src/proto/h2/server.rs @@ -62,7 +62,7 @@ where impl<T, S, B> Future for Server<T, S, B> where T: AsyncRead + AsyncWrite, - S: Service<Request=Request<Body>, Response=Response<B>>, + S: Service<ReqBody=Body, ResBody=B>, S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Future: Send + 'static, B: Payload, diff --git a/src/proto/h2/server.rs b/src/proto/h2/server.rs --- a/src/proto/h2/server.rs +++ b/src/proto/h2/server.rs @@ -96,8 +96,8 @@ where fn poll_server<S>(&mut self, service: &mut S, exec: &Exec) -> Poll<(), ::Error> where S: Service< - Request=Request<Body>, - Response=Response<B>, + ReqBody=Body, + ResBody=B, >, S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Future: Send + 'static, diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -23,7 +23,7 @@ use tokio::reactor::Handle; use common::Exec; use proto; use body::{Body, Payload}; -use super::{HyperService, NewService, Request, Response, Service}; +use service::{NewService, Service}; pub use super::tcp::AddrIncoming; diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -44,7 +44,7 @@ pub struct Http { /// A stream mapping incoming IOs to new services. /// -/// Yields `Connection`s that are futures that should be put on a reactor. +/// Yields `Connecting`s that are futures that should be put on a reactor. #[must_use = "streams do nothing unless polled"] #[derive(Debug)] pub struct Serve<I, S> { diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -53,6 +53,18 @@ pub struct Serve<I, S> { protocol: Http, } +/// A future binding a `Service` to a `Connection`. +/// +/// Wraps the future returned from `NewService` into one that returns +/// a `Connection`. +#[must_use = "futures do nothing unless polled"] +#[derive(Debug)] +pub struct Connecting<I, F> { + future: F, + io: Option<I>, + protocol: Http, +} + #[must_use = "futures do nothing unless polled"] #[derive(Debug)] pub(super) struct SpawnAll<I, S> { diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -65,20 +77,19 @@ pub(super) struct SpawnAll<I, S> { #[must_use = "futures do nothing unless polled"] pub struct Connection<I, S> where - S: HyperService, - S::ResponseBody: Payload, + S: Service, { pub(super) conn: Either< proto::h1::Dispatcher< proto::h1::dispatch::Server<S>, - S::ResponseBody, + S::ResBody, I, proto::ServerTransaction, >, proto::h2::Server< I, S, - S::ResponseBody, + S::ResBody, >, >, } diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -163,7 +174,7 @@ impl Http { self } - /// Bind a connection together with a `Service`. + /// Bind a connection together with a [`Service`](::service::Service). /// /// This returns a Future that must be polled in order for HTTP to be /// driven on the connection. diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -177,14 +188,14 @@ impl Http { /// # extern crate tokio_io; /// # use futures::Future; /// # use hyper::{Body, Request, Response}; - /// # use hyper::server::Service; + /// # use hyper::service::Service; /// # use hyper::server::conn::Http; /// # use tokio_io::{AsyncRead, AsyncWrite}; /// # use tokio::reactor::Handle; /// # fn run<I, S>(some_io: I, some_service: S) /// # where /// # I: AsyncRead + AsyncWrite + Send + 'static, - /// # S: Service<Request=Request<Body>, Response=Response<Body>, Error=hyper::Error> + Send + 'static, + /// # S: Service<ReqBody=Body, ResBody=Body> + Send + 'static, /// # S::Future: Send /// # { /// let http = Http::new(); diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -200,7 +211,7 @@ impl Http { /// ``` pub fn serve_connection<S, I, Bd>(&self, io: I, service: S) -> Connection<I, S> where - S: Service<Request = Request<Body>, Response = Response<Bd>>, + S: Service<ReqBody=Body, ResBody=Bd>, S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Future: Send + 'static, Bd: Payload, diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -235,7 +246,7 @@ impl Http { /// connection. pub fn serve_addr<S, Bd>(&self, addr: &SocketAddr, new_service: S) -> ::Result<Serve<AddrIncoming, S>> where - S: NewService<Request=Request<Body>, Response=Response<Bd>>, + S: NewService<ReqBody=Body, ResBody=Bd>, S::Error: Into<Box<::std::error::Error + Send + Sync>>, Bd: Payload, { diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -254,7 +265,7 @@ impl Http { /// connection. pub fn serve_addr_handle<S, Bd>(&self, addr: &SocketAddr, handle: &Handle, new_service: S) -> ::Result<Serve<AddrIncoming, S>> where - S: NewService<Request = Request<Body>, Response = Response<Bd>>, + S: NewService<ReqBody=Body, ResBody=Bd>, S::Error: Into<Box<::std::error::Error + Send + Sync>>, Bd: Payload, { diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -271,7 +282,7 @@ impl Http { I: Stream, I::Error: Into<Box<::std::error::Error + Send + Sync>>, I::Item: AsyncRead + AsyncWrite, - S: NewService<Request = Request<Body>, Response = Response<Bd>>, + S: NewService<ReqBody=Body, ResBody=Bd>, S::Error: Into<Box<::std::error::Error + Send + Sync>>, Bd: Payload, { diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -288,7 +299,7 @@ impl Http { impl<I, B, S> Connection<I, S> where - S: Service<Request=Request<Body>, Response=Response<B>> + 'static, + S: Service<ReqBody=Body, ResBody=B> + 'static, S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Future: Send, I: AsyncRead + AsyncWrite + 'static, diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -350,7 +361,7 @@ where impl<I, B, S> Future for Connection<I, S> where - S: Service<Request=Request<Body>, Response=Response<B>> + 'static, + S: Service<ReqBody=Body, ResBody=B> + 'static, S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Future: Send, I: AsyncRead + AsyncWrite + 'static, diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -366,8 +377,7 @@ where impl<I, S> fmt::Debug for Connection<I, S> where - S: HyperService, - S::ResponseBody: Payload, + S: Service, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Connection") diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -403,24 +413,48 @@ where I: Stream, I::Item: AsyncRead + AsyncWrite, I::Error: Into<Box<::std::error::Error + Send + Sync>>, - S: NewService<Request=Request<Body>, Response=Response<B>>, + S: NewService<ReqBody=Body, ResBody=B>, S::Error: Into<Box<::std::error::Error + Send + Sync>>, - <S::Instance as Service>::Future: Send + 'static, + <S::Service as Service>::Future: Send + 'static, B: Payload, { - type Item = Connection<I::Item, S::Instance>; + type Item = Connecting<I::Item, S::Future>; type Error = ::Error; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { if let Some(io) = try_ready!(self.incoming.poll().map_err(::Error::new_accept)) { - let service = self.new_service.new_service().map_err(::Error::new_user_new_service)?; - Ok(Async::Ready(Some(self.protocol.serve_connection(io, service)))) + let new_fut = self.new_service.new_service(); + Ok(Async::Ready(Some(Connecting { + future: new_fut, + io: Some(io), + protocol: self.protocol.clone(), + }))) } else { Ok(Async::Ready(None)) } } } +// ===== impl Connecting ===== + +impl<I, F, S, B> Future for Connecting<I, F> +where + I: AsyncRead + AsyncWrite, + F: Future<Item=S>, + S: Service<ReqBody=Body, ResBody=B>, + S::Future: Send + 'static, + B: Payload, +{ + type Item = Connection<I, S>; + type Error = F::Error; + + fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + let service = try_ready!(self.future.poll()); + let io = self.io.take().expect("polled after complete"); + Ok(self.protocol.serve_connection(io, service).into()) + } +} + // ===== impl SpawnAll ===== impl<S> SpawnAll<AddrIncoming, S> { diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -440,10 +474,11 @@ where I: Stream, I::Error: Into<Box<::std::error::Error + Send + Sync>>, I::Item: AsyncRead + AsyncWrite + Send + 'static, - S: NewService<Request = Request<Body>, Response = Response<B>> + Send + 'static, + S: NewService<ReqBody=Body, ResBody=B> + Send + 'static, S::Error: Into<Box<::std::error::Error + Send + Sync>>, - <S as NewService>::Instance: Send, - <<S as NewService>::Instance as Service>::Future: Send + 'static, + S::Service: Send, + S::Future: Send + 'static, + <S::Service as Service>::Future: Send + 'static, B: Payload, { type Item = (); diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -451,8 +486,11 @@ where fn poll(&mut self) -> Poll<Self::Item, Self::Error> { loop { - if let Some(conn) = try_ready!(self.serve.poll()) { - let fut = conn + if let Some(connecting) = try_ready!(self.serve.poll()) { + let fut = connecting + .map_err(::Error::new_user_new_service) + // flatten basically + .and_then(|conn| conn) .map_err(|err| debug!("conn error: {}", err)); self.serve.protocol.exec.execute(fut); } else { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -7,9 +7,47 @@ //! //! - The higher-level [`Server`](Server). //! - The lower-level [conn](conn) module. +//! +//! # Server +//! +//! The [`Server`](Server) is main way to start listening for HTTP requests. +//! It wraps a listener with a [`NewService`](::service), and then should +//! be executed to start serving requests. +//! +//! ## Example +//! +//! ```no_run +//! extern crate futures; +//! extern crate hyper; +//! extern crate tokio; +//! +//! use futures::Future; +//! use hyper::{Body, Response, Server}; +//! use hyper::service::service_fn_ok; +//! +//! fn main() { +//! // Construct our SocketAddr to listen on... +//! let addr = ([127, 0, 0, 1], 3000).into(); +//! +//! // And a NewService to handle each connection... +//! let new_service = || { +//! service_fn_ok(|_req| { +//! Response::new(Body::from("Hello World")) +//! }) +//! }; +//! +//! // Then bind and serve... +//! let server = Server::bind(&addr) +//! .serve(new_service); +//! +//! // Finally, spawn `server` onto an Executor... +//! tokio::run(server.map_err(|e| { +//! eprintln!("server error: {}", e); +//! })); +//! } +//! ``` pub mod conn; -mod service; mod tcp; use std::fmt; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -17,19 +55,16 @@ use std::net::SocketAddr; use std::time::Duration; use futures::{Future, Stream, Poll}; -use http::{Request, Response}; use tokio_io::{AsyncRead, AsyncWrite}; -pub use tokio_service::{NewService, Service}; use body::{Body, Payload}; +use service::{NewService, Service}; // Renamed `Http` as `Http_` for now so that people upgrading don't see an // error that `hyper::server::Http` is private... use self::conn::{Http as Http_, SpawnAll}; -use self::hyper_service::HyperService; +//use self::hyper_service::HyperService; use self::tcp::{AddrIncoming}; -pub use self::service::{const_service, service_fn}; - /// A listening HTTP server. /// /// `Server` is a `Future` mapping a bound listener with a set of service diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -93,10 +128,11 @@ where I: Stream, I::Error: Into<Box<::std::error::Error + Send + Sync>>, I::Item: AsyncRead + AsyncWrite + Send + 'static, - S: NewService<Request = Request<Body>, Response = Response<B>> + Send + 'static, + S: NewService<ReqBody=Body, ResBody=B> + Send + 'static, S::Error: Into<Box<::std::error::Error + Send + Sync>>, - <S as NewService>::Instance: Send, - <<S as NewService>::Instance as Service>::Future: Send + 'static, + S::Service: Send, + S::Future: Send + 'static, + <S::Service as Service>::Future: Send + 'static, B: Payload, { type Item = (); diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -137,15 +173,38 @@ impl<I> Builder<I> { } /// Consume this `Builder`, creating a [`Server`](Server). + /// + /// # Example + /// + /// ```rust + /// use hyper::{Body, Response, Server}; + /// use hyper::service::service_fn_ok; + /// + /// // Construct our SocketAddr to listen on... + /// let addr = ([127, 0, 0, 1], 3000).into(); + /// + /// // And a NewService to handle each connection... + /// let new_service = || { + /// service_fn_ok(|_req| { + /// Response::new(Body::from("Hello World")) + /// }) + /// }; + /// + /// // Then bind and serve... + /// let server = Server::bind(&addr) + /// .serve(new_service); + /// + /// // Finally, spawn `server` onto an Executor... + /// ``` pub fn serve<S, B>(self, new_service: S) -> Server<I, S> where I: Stream, I::Error: Into<Box<::std::error::Error + Send + Sync>>, I::Item: AsyncRead + AsyncWrite + Send + 'static, - S: NewService<Request = Request<Body>, Response = Response<B>>, + S: NewService<ReqBody=Body, ResBody=B> + Send + 'static, S::Error: Into<Box<::std::error::Error + Send + Sync>>, - <S as NewService>::Instance: Send, - <<S as NewService>::Instance as Service>::Future: Send + 'static, + S::Service: Send, + <S::Service as Service>::Future: Send + 'static, B: Payload, { let serve = self.protocol.serve_incoming(self.incoming, new_service); diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -174,52 +233,3 @@ impl Builder<AddrIncoming> { } } -mod hyper_service { - use super::{Body, Payload, Request, Response, Service}; - /// A "trait alias" for any type that implements `Service` with hyper's - /// Request, Response, and Error types, and a streaming body. - /// - /// There is an auto implementation inside hyper, so no one can actually - /// implement this trait. It simply exists to reduce the amount of generics - /// needed. - pub trait HyperService: Service + Sealed { - #[doc(hidden)] - type ResponseBody; - #[doc(hidden)] - type Sealed: Sealed2; - } - - pub trait Sealed {} - pub trait Sealed2 {} - - #[allow(missing_debug_implementations)] - pub struct Opaque { - _inner: (), - } - - impl Sealed2 for Opaque {} - - impl<S, B> Sealed for S - where - S: Service< - Request=Request<Body>, - Response=Response<B>, - >, - S::Error: Into<Box<::std::error::Error + Send + Sync>>, - B: Payload, - {} - - impl<S, B> HyperService for S - where - S: Service< - Request=Request<Body>, - Response=Response<B>, - >, - S::Error: Into<Box<::std::error::Error + Send + Sync>>, - S: Sealed, - B: Payload, - { - type ResponseBody = B; - type Sealed = Opaque; - } -} diff --git a/src/server/service.rs /dev/null --- a/src/server/service.rs +++ /dev/null @@ -1,64 +0,0 @@ -use std::marker::PhantomData; -use std::sync::Arc; - -use futures::IntoFuture; -use tokio_service::{NewService, Service}; - -/// Create a `Service` from a function. -pub fn service_fn<F, R, S>(f: F) -> ServiceFn<F, R> -where - F: Fn(R) -> S, - S: IntoFuture, -{ - ServiceFn { - f: f, - _req: PhantomData, - } -} - -/// Create a `NewService` by sharing references of `service. -pub fn const_service<S>(service: S) -> ConstService<S> { - ConstService { - svc: Arc::new(service), - } -} - -#[derive(Debug)] -pub struct ServiceFn<F, R> { - f: F, - _req: PhantomData<fn() -> R>, -} - -impl<F, R, S> Service for ServiceFn<F, R> -where - F: Fn(R) -> S, - S: IntoFuture, -{ - type Request = R; - type Response = S::Item; - type Error = S::Error; - type Future = S::Future; - - fn call(&self, req: Self::Request) -> Self::Future { - (self.f)(req).into_future() - } -} - -#[derive(Debug)] -pub struct ConstService<S> { - svc: Arc<S>, -} - -impl<S> NewService for ConstService<S> -where - S: Service, -{ - type Request = S::Request; - type Response = S::Response; - type Error = S::Error; - type Instance = Arc<S>; - - fn new_service(&self) -> ::std::io::Result<Self::Instance> { - Ok(self.svc.clone()) - } -} diff --git /dev/null b/src/service/mod.rs new file mode 100644 --- /dev/null +++ b/src/service/mod.rs @@ -0,0 +1,35 @@ +//! Services and NewServices +//! +//! - A [`Service`](Service) is a trait representing an asynchronous function +//! of a request to a response. It's similar to +//! `async fn(Request) -> Result<Response, Error>`. +//! - A [`NewService`](NewService) is a trait creating specific instances of a +//! `Service`. +//! +//! These types are conceptually similar to those in +//! [tower](https://crates.io/crates/tower), while being specific to hyper. +//! +//! # Service +//! +//! In hyper, especially in the server setting, a `Service` is usually bound +//! to a single connection. It defines how to respond to **all** requests that +//! connection will receive. +//! +//! While it's possible to implement `Service` for a type manually, the helpers +//! [`service_fn`](service_fn) and [`service_fn_ok`](service_fn_ok) should be +//! sufficient for most cases. +//! +//! # NewService +//! +//! Since a `Service` is bound to a single connection, a [`Server`](::Server) +//! needs a way to make them as it accepts connections. This is what a +//! `NewService` does. +//! +//! Resources that need to be shared by all `Service`s can be put into a +//! `NewService`, and then passed to individual `Service`s when `new_service` +//! is called. +mod new_service; +mod service; + +pub use self::new_service::{NewService}; +pub use self::service::{service_fn, service_fn_ok, Service}; diff --git /dev/null b/src/service/new_service.rs new file mode 100644 --- /dev/null +++ b/src/service/new_service.rs @@ -0,0 +1,55 @@ +use std::error::Error as StdError; + +use futures::{Future, IntoFuture}; + +use body::Payload; +use super::Service; + +/// An asynchronous constructor of `Service`s. +pub trait NewService { + /// The `Payload` body of the `http::Request`. + type ReqBody: Payload; + + /// The `Payload` body of the `http::Response`. + type ResBody: Payload; + + /// The error type that can be returned by `Service`s. + type Error: Into<Box<StdError + Send + Sync>>; + + /// The resolved `Service` from `new_service()`. + type Service: Service< + ReqBody=Self::ReqBody, + ResBody=Self::ResBody, + Error=Self::Error, + >; + + /// The future returned from `new_service` of a `Service`. + type Future: Future<Item=Self::Service, Error=Self::InitError>; + + /// The error type that can be returned when creating a new `Service. + type InitError: Into<Box<StdError + Send + Sync>>; + + /// Create a new `Service`. + fn new_service(&self) -> Self::Future; +} + +impl<F, R, S> NewService for F +where + F: Fn() -> R, + R: IntoFuture<Item=S>, + R::Error: Into<Box<StdError + Send + Sync>>, + S: Service, +{ + type ReqBody = S::ReqBody; + type ResBody = S::ResBody; + type Error = S::Error; + type Service = S; + type Future = R::Future; + type InitError = R::Error; + + + fn new_service(&self) -> Self::Future { + (*self)().into_future() + } +} + diff --git /dev/null b/src/service/service.rs new file mode 100644 --- /dev/null +++ b/src/service/service.rs @@ -0,0 +1,165 @@ +use std::error::Error as StdError; +use std::fmt; +use std::marker::PhantomData; + +use futures::{future, Future, IntoFuture}; + +use body::Payload; +use common::Never; +use ::{Request, Response}; + +/// An asynchronous function from `Request` to `Response`. +pub trait Service { + /// The `Payload` body of the `http::Request`. + type ReqBody: Payload; + + /// The `Payload` body of the `http::Response`. + type ResBody: Payload; + + /// The error type that can occur within this `Service. + /// + /// Note: Returning an `Error` to a hyper server will cause the connection + /// to be abruptly aborted. In most cases, it is better to return a `Response` + /// with a 4xx or 5xx status code. + type Error: Into<Box<StdError + Send + Sync>>; + + /// The `Future` returned by this `Service`. + type Future: Future<Item=Response<Self::ResBody>, Error=Self::Error>; + + /// Calls this `Service` with a request, returning a `Future` of the response. + fn call(&mut self, req: Request<Self::ReqBody>) -> Self::Future; +} + + +/// Create a `Service` from a function. +/// +/// # Example +/// +/// ```rust +/// use hyper::{Body, Request, Response, Version}; +/// use hyper::service::service_fn; +/// +/// let service = service_fn(|req: Request<Body>| { +/// if req.version() == Version::HTTP_11 { +/// Ok(Response::new(Body::from("Hello World"))) +/// } else { +/// // Note: it's usually better to return a Response +/// // with an appropriate StatusCode instead of an Err. +/// Err("not HTTP/1.1, abort connection") +/// } +/// }); +/// ``` +pub fn service_fn<F, R, S>(f: F) -> ServiceFn<F, R> +where + F: FnMut(Request<R>) -> S, + S: IntoFuture, +{ + ServiceFn { + f, + _req: PhantomData, + } +} + +/// Create a `Service` from a function that never errors. +/// +/// # Example +/// +/// ```rust +/// use hyper::{Body, Request, Response}; +/// use hyper::service::service_fn_ok; +/// +/// let service = service_fn_ok(|req: Request<Body>| { +/// println!("request: {} {}", req.method(), req.uri()); +/// Response::new(Body::from("Hello World")) +/// }); +/// ``` +pub fn service_fn_ok<F, R, S>(f: F) -> ServiceFnOk<F, R> +where + F: FnMut(Request<R>) -> Response<S>, + S: Payload, +{ + ServiceFnOk { + f, + _req: PhantomData, + } +} + +// Not exported from crate as this will likely be replaced with `impl Service`. +pub struct ServiceFn<F, R> { + f: F, + _req: PhantomData<fn(R)>, +} + +impl<F, ReqBody, Ret, ResBody> Service for ServiceFn<F, ReqBody> +where + F: FnMut(Request<ReqBody>) -> Ret, + ReqBody: Payload, + Ret: IntoFuture<Item=Response<ResBody>>, + Ret::Error: Into<Box<StdError + Send + Sync>>, + ResBody: Payload, +{ + type ReqBody = ReqBody; + type ResBody = ResBody; + type Error = Ret::Error; + type Future = Ret::Future; + + fn call(&mut self, req: Request<Self::ReqBody>) -> Self::Future { + (self.f)(req).into_future() + } +} + +impl<F, R> IntoFuture for ServiceFn<F, R> { + type Future = future::FutureResult<Self::Item, Self::Error>; + type Item = Self; + type Error = Never; + + fn into_future(self) -> Self::Future { + future::ok(self) + } +} + +impl<F, R> fmt::Debug for ServiceFn<F, R> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("impl Service") + .finish() + } +} + +// Not exported from crate as this will likely be replaced with `impl Service`. +pub struct ServiceFnOk<F, R> { + f: F, + _req: PhantomData<fn(R)>, +} + +impl<F, ReqBody, ResBody> Service for ServiceFnOk<F, ReqBody> +where + F: FnMut(Request<ReqBody>) -> Response<ResBody>, + ReqBody: Payload, + ResBody: Payload, +{ + type ReqBody = ReqBody; + type ResBody = ResBody; + type Error = Never; + type Future = future::FutureResult<Response<ResBody>, Never>; + + fn call(&mut self, req: Request<Self::ReqBody>) -> Self::Future { + future::ok((self.f)(req)) + } +} + +impl<F, R> IntoFuture for ServiceFnOk<F, R> { + type Future = future::FutureResult<Self::Item, Self::Error>; + type Item = Self; + type Error = Never; + + fn into_future(self) -> Self::Future { + future::ok(self) + } +} + +impl<F, R> fmt::Debug for ServiceFnOk<F, R> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("impl Service") + .finish() + } +}
diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -71,20 +71,20 @@ fn post_one_at_a_time(b: &mut test::Bencher) { static PHRASE: &'static [u8] = include_bytes!("../CHANGELOG.md"); //b"Hello, World!"; fn spawn_hello(rt: &mut Runtime) -> SocketAddr { - use hyper::server::{const_service, service_fn, NewService}; + use hyper::service::{service_fn}; let addr = "127.0.0.1:0".parse().unwrap(); let listener = TcpListener::bind(&addr).unwrap(); let addr = listener.local_addr().unwrap(); let http = Http::new(); - let service = const_service(service_fn(|req: Request<Body>| { + let service = service_fn(|req: Request<Body>| { req.into_body() .concat2() .map(|_| { Response::new(Body::from(PHRASE)) }) - })); + }); // Specifically only accept 1 connection. let srv = listener.incoming() diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -182,26 +189,3 @@ fn raw_tcp_throughput_large_payload(b: &mut test::Bencher) { tx.send(()).unwrap(); } -struct BenchPayload<F> { - header: (&'static str, &'static str), - body: F, -} - -impl<F, B> Service for BenchPayload<F> -where - F: Fn() -> B, -{ - type Request = Request<Body>; - type Response = Response<B>; - type Error = hyper::Error; - type Future = future::FutureResult<Self::Response, hyper::Error>; - fn call(&self, _req: Self::Request) -> Self::Future { - future::ok( - Response::builder() - .header(self.header.0, self.header.1) - .header("content-type", "text/plain") - .body((self.body)()) - .unwrap() - ) - } -} diff --git a/examples/send_file.rs b/examples/send_file.rs --- a/examples/send_file.rs +++ b/examples/send_file.rs @@ -17,7 +17,92 @@ use std::thread; static NOTFOUND: &[u8] = b"Not Found"; static INDEX: &str = "examples/send_file_index.html"; -fn simple_file_send(f: &str) -> Box<Future<Item = Response<Body>, Error = io::Error> + Send> { + +fn main() { + pretty_env_logger::init(); + + let addr = "127.0.0.1:1337".parse().unwrap(); + + let server = Server::bind(&addr) + .serve(|| service_fn(response_examples)) + .map_err(|e| eprintln!("server error: {}", e)); + + println!("Listening on http://{}", addr); + + tokio::run(server); +} + +type ResponseFuture = Box<Future<Item=Response<Body>, Error=io::Error> + Send>; + +fn response_examples(req: Request<Body>) -> ResponseFuture { + match (req.method(), req.uri().path()) { + (&Method::GET, "/") | (&Method::GET, "/index.html") => { + simple_file_send(INDEX) + }, + (&Method::GET, "/big_file.html") => { + // Stream a large file in chunks. This requires a + // little more overhead with two channels, (one for + // the response future, and a second for the response + // body), but can handle arbitrarily large files. + // + // We use an artificially small buffer, since we have + // a small test file. + let (tx, rx) = oneshot::channel(); + thread::spawn(move || { + let _file = match File::open(INDEX) { + Ok(f) => f, + Err(_) => { + tx.send(Response::builder() + .status(StatusCode::NOT_FOUND) + .body(NOTFOUND.into()) + .unwrap()) + .expect("Send error on open"); + return; + }, + }; + let (_tx_body, rx_body) = Body::channel(); + let res = Response::new(rx_body.into()); + tx.send(res).expect("Send error on successful file read"); + /* TODO: fix once we have futures 0.2 Sink working + let mut buf = [0u8; 16]; + loop { + match file.read(&mut buf) { + Ok(n) => { + if n == 0 { + // eof + tx_body.close().expect("panic closing"); + break; + } else { + let chunk: Chunk = buf[0..n].to_vec().into(); + match tx_body.send_data(chunk).wait() { + Ok(t) => { tx_body = t; }, + Err(_) => { break; } + }; + } + }, + Err(_) => { break; } + } + } + */ + }); + + Box::new(rx.map_err(|e| io::Error::new(io::ErrorKind::Other, e))) + }, + (&Method::GET, "/no_file.html") => { + // Test what happens when file cannot be be found + simple_file_send("this_file_should_not_exist.html") + }, + _ => { + Box::new(future::ok(Response::builder() + .status(StatusCode::NOT_FOUND) + .body(Body::empty()) + .unwrap())) + } + } + +} + +fn simple_file_send(f: &str) -> ResponseFuture { // Serve a file by reading it entirely into memory. As a result // this is limited to serving small files, but it is somewhat // simpler with a little less overhead. diff --git a/examples/send_file.rs b/examples/send_file.rs --- a/examples/send_file.rs +++ b/examples/send_file.rs @@ -57,94 +142,3 @@ fn simple_file_send(f: &str) -> Box<Future<Item = Response<Body>, Error = io::Er Box::new(rx.map_err(|e| io::Error::new(io::ErrorKind::Other, e))) } -struct ResponseExamples; - -impl Service for ResponseExamples { - type Request = Request<Body>; - type Response = Response<Body>; - type Error = io::Error; - type Future = Box<Future<Item = Self::Response, Error = Self::Error> + Send>; - - fn call(&self, req: Request<Body>) -> Self::Future { - match (req.method(), req.uri().path()) { - (&Method::GET, "/") | (&Method::GET, "/index.html") => { - simple_file_send(INDEX) - }, - (&Method::GET, "/big_file.html") => { - // Stream a large file in chunks. This requires a - // little more overhead with two channels, (one for - // the response future, and a second for the response - // body), but can handle arbitrarily large files. - // - // We use an artificially small buffer, since we have - // a small test file. - let (tx, rx) = oneshot::channel(); - thread::spawn(move || { - let _file = match File::open(INDEX) { - Ok(f) => f, - Err(_) => { - tx.send(Response::builder() - .status(StatusCode::NOT_FOUND) - .body(NOTFOUND.into()) - .unwrap()) - .expect("Send error on open"); - return; - }, - }; - let (_tx_body, rx_body) = Body::channel(); - let res = Response::new(rx_body.into()); - tx.send(res).expect("Send error on successful file read"); - /* TODO: fix once we have futures 0.2 Sink working - let mut buf = [0u8; 16]; - loop { - match file.read(&mut buf) { - Ok(n) => { - if n == 0 { - // eof - tx_body.close().expect("panic closing"); - break; - } else { - let chunk: Chunk = buf[0..n].to_vec().into(); - match tx_body.send_data(chunk).wait() { - Ok(t) => { tx_body = t; }, - Err(_) => { break; } - }; - } - }, - Err(_) => { break; } - } - } - */ - }); - - Box::new(rx.map_err(|e| io::Error::new(io::ErrorKind::Other, e))) - }, - (&Method::GET, "/no_file.html") => { - // Test what happens when file cannot be be found - simple_file_send("this_file_should_not_exist.html") - }, - _ => { - Box::new(futures::future::ok(Response::builder() - .status(StatusCode::NOT_FOUND) - .body(Body::empty()) - .unwrap())) - } - } - } - -} - - -fn main() { - pretty_env_logger::init(); - - let addr = "127.0.0.1:1337".parse().unwrap(); - - let server = Server::bind(&addr) - .serve(|| Ok(ResponseExamples)) - .map_err(|e| eprintln!("server error: {}", e)); - - println!("Listening on http://{}", addr); - - tokio::run(server); -} diff --git a/examples/web_api.rs b/examples/web_api.rs --- a/examples/web_api.rs +++ b/examples/web_api.rs @@ -19,69 +18,70 @@ static URL: &str = "http://127.0.0.1:1337/web_api"; static INDEX: &[u8] = b"<a href=\"test.html\">test.html</a>"; static LOWERCASE: &[u8] = b"i am a lower case string"; -struct ResponseExamples(Client<HttpConnector>); +fn response_examples(req: Request<Body>, client: &Client<HttpConnector>) + -> Box<Future<Item=Response<Body>, Error=hyper::Error> + Send> +{ + match (req.method(), req.uri().path()) { + (&Method::GET, "/") | (&Method::GET, "/index.html") => { + let body = Body::from(INDEX); + Box::new(future::ok(Response::new(body))) + }, + (&Method::GET, "/test.html") => { + // Run a web query against the web api below + let req = Request::builder() + .method(Method::POST) + .uri(URL) + .body(LOWERCASE.into()) + .unwrap(); + let web_res_future = client.request(req); -impl Service for ResponseExamples { - type Request = Request<Body>; - type Response = Response<Body>; - type Error = hyper::Error; - type Future = Box<Future<Item = Self::Response, Error = Self::Error> + Send>; - - fn call(&self, req: Self::Request) -> Self::Future { - match (req.method(), req.uri().path()) { - (&Method::GET, "/") | (&Method::GET, "/index.html") => { - let body = Body::from(INDEX); - Box::new(futures::future::ok(Response::new(body))) - }, - (&Method::GET, "/test.html") => { - // Run a web query against the web api below - let req = Request::builder() - .method(Method::POST) - .uri(URL) - .body(LOWERCASE.into()) - .unwrap(); - let web_res_future = self.0.request(req); - - Box::new(web_res_future.map(|web_res| { - let body = Body::wrap_stream(web_res.into_body().map(|b| { - Chunk::from(format!("before: '{:?}'<br>after: '{:?}'", - std::str::from_utf8(LOWERCASE).unwrap(), - std::str::from_utf8(&b).unwrap())) - })); - Response::new(body) - })) - }, - (&Method::POST, "/web_api") => { - // A web api to run against. Simple upcasing of the body. - let body = Body::wrap_stream(req.into_body().map(|chunk| { - let upper = chunk.iter().map(|byte| byte.to_ascii_uppercase()) - .collect::<Vec<u8>>(); - Chunk::from(upper) + Box::new(web_res_future.map(|web_res| { + let body = Body::wrap_stream(web_res.into_body().map(|b| { + Chunk::from(format!("before: '{:?}'<br>after: '{:?}'", + std::str::from_utf8(LOWERCASE).unwrap(), + std::str::from_utf8(&b).unwrap())) })); - Box::new(futures::future::ok(Response::new(body))) - }, - _ => { - let body = Body::from(NOTFOUND); - Box::new(futures::future::ok(Response::builder() - .status(StatusCode::NOT_FOUND) - .body(body) - .unwrap())) - } + Response::new(body) + })) + }, + (&Method::POST, "/web_api") => { + // A web api to run against. Simple upcasing of the body. + let body = Body::wrap_stream(req.into_body().map(|chunk| { + let upper = chunk.iter().map(|byte| byte.to_ascii_uppercase()) + .collect::<Vec<u8>>(); + Chunk::from(upper) + })); + Box::new(future::ok(Response::new(body))) + }, + _ => { + let body = Body::from(NOTFOUND); + Box::new(future::ok(Response::builder() + .status(StatusCode::NOT_FOUND) + .body(body) + .unwrap())) } } - } - fn main() { pretty_env_logger::init(); let addr = "127.0.0.1:1337".parse().unwrap(); - tokio::run(lazy(move || { + tokio::run(future::lazy(move || { + // Share a `Client` with all `Service`s let client = Client::new(); + + let new_service = move || { + // Move a clone of `client` into the `service_fn`. + let client = client.clone(); + service_fn(move |req| { + response_examples(req, &client) + }) + }; + let server = Server::bind(&addr) - .serve(move || Ok(ResponseExamples(client.clone()))) + .serve(new_service) .map_err(|e| eprintln!("server error: {}", e)); println!("Listening on http://{}", addr); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -30,7 +30,6 @@ extern crate time; extern crate tokio; extern crate tokio_executor; #[macro_use] extern crate tokio_io; -extern crate tokio_service; extern crate want; #[cfg(all(test, feature = "nightly"))] diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -31,8 +31,8 @@ use tokio_io::{AsyncRead, AsyncWrite}; use hyper::{Body, Request, Response, StatusCode}; -use hyper::server::{Service, NewService, service_fn}; use hyper::server::conn::Http; +use hyper::service::{service_fn, Service}; fn tcp_bind(addr: &SocketAddr, handle: &Handle) -> ::tokio::io::Result<TcpListener> { let std_listener = StdTcpListener::bind(addr).unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -95,28 +95,17 @@ fn get_implicitly_empty() { .map_err(|_| unreachable!()) .and_then(|(item, _incoming)| { let socket = item.unwrap(); - Http::new().serve_connection(socket, GetImplicitlyEmpty) + Http::new().serve_connection(socket, service_fn(|req: Request<Body>| { + req.into_body() + .concat2() + .map(|buf| { + assert!(buf.is_empty()); + Response::new(Body::empty()) + }) + })) }); fut.wait().unwrap(); - - struct GetImplicitlyEmpty; - - impl Service for GetImplicitlyEmpty { - type Request = Request<Body>; - type Response = Response<Body>; - type Error = hyper::Error; - type Future = Box<Future<Item=Self::Response, Error=Self::Error> + Send>; - - fn call(&self, req: Request<Body>) -> Self::Future { - Box::new(req.into_body() - .concat2() - .map(|buf| { - assert!(buf.is_empty()); - Response::new(Body::empty()) - })) - } - } } mod response_body_lengths { diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1258,24 +1247,9 @@ enum Msg { End, } -impl NewService for TestService { - type Request = Request<Body>; - type Response = Response<Body>; - type Error = hyper::Error; - - type Instance = TestService; - - fn new_service(&self) -> std::io::Result<TestService> { - Ok(self.clone()) - } -} - -impl Service for TestService { - type Request = Request<Body>; - type Response = Response<Body>; - type Error = hyper::Error; - type Future = Box<Future<Item=Response<Body>, Error=hyper::Error> + Send>; - fn call(&self, req: Request<Body>) -> Self::Future { +impl TestService { + // Box is needed until we can return `impl Future` from a fn + fn call(&self, req: Request<Body>) -> Box<Future<Item=Response<Body>, Error=hyper::Error> + Send> { let tx1 = self.tx.clone(); let tx2 = self.tx.clone(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1309,7 +1283,6 @@ impl Service for TestService { res })) } - } const HELLO: &'static str = "hello"; diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1317,12 +1290,12 @@ const HELLO: &'static str = "hello"; struct HelloWorld; impl Service for HelloWorld { - type Request = Request<Body>; - type Response = Response<Body>; + type ReqBody = Body; + type ResBody = Body; type Error = hyper::Error; - type Future = FutureResult<Self::Response, Self::Error>; + type Future = FutureResult<Response<Body>, Self::Error>; - fn call(&self, _req: Request<Body>) -> Self::Future { + fn call(&mut self, _req: Request<Body>) -> Self::Future { let response = Response::new(HELLO.into()); future::ok(response) } diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1376,10 +1349,13 @@ fn serve_with_options(options: ServeOptions) -> Serve { let serve = Http::new() .keep_alive(keep_alive) .pipeline_flush(pipeline) - .serve_addr(&addr, TestService { - tx: Arc::new(Mutex::new(msg_tx.clone())), - _timeout: dur, - reply: reply_rx, + .serve_addr(&addr, move || { + let ts = TestService { + tx: Arc::new(Mutex::new(msg_tx.clone())), + _timeout: dur, + reply: reply_rx.clone(), + }; + service_fn(move |req| ts.call(req)) }) .expect("bind to address"); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1390,10 +1366,12 @@ fn serve_with_options(options: ServeOptions) -> Serve { ).expect("server addr tx"); // spawn_all() is private for now, so just duplicate it here - let spawn_all = serve.for_each(|conn| { - tokio::spawn(conn.map_err(|e| { - println!("server error: {}", e); - })); + let spawn_all = serve.for_each(|connecting| { + let fut = connecting + .map_err(|never| -> hyper::Error { match never {} }) + .flatten() + .map_err(|e| println!("server error: {}", e)); + tokio::spawn(fut); Ok(()) }).map_err(|e| { println!("accept error: {}", e) diff --git a/tests/support/mod.rs b/tests/support/mod.rs --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -187,7 +187,7 @@ pub fn __run_test(cfg: __TestConfig) { extern crate pretty_env_logger; use hyper::{Body, Client, Request, Response}; use hyper::client::HttpConnector; - use std::sync::Arc; + use std::sync::{Arc, Mutex}; let _ = pretty_env_logger::try_init(); let rt = Runtime::new().expect("new rt"); let handle = rt.reactor().clone(); diff --git a/tests/support/mod.rs b/tests/support/mod.rs --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -198,37 +198,40 @@ pub fn __run_test(cfg: __TestConfig) { .executor(rt.executor()) .build::<_, Body>(connector); - let serve_handles = ::std::sync::Mutex::new( + let serve_handles = Arc::new(Mutex::new( cfg.server_msgs - ); - let service = hyper::server::service_fn(move |req: Request<Body>| -> Box<Future<Item=Response<Body>, Error=hyper::Error> + Send> { - let (sreq, sres) = serve_handles.lock() - .unwrap() - .remove(0); + )); + let new_service = move || { + // Move a clone into the service_fn + let serve_handles = serve_handles.clone(); + hyper::service::service_fn(move |req: Request<Body>| { + let (sreq, sres) = serve_handles.lock() + .unwrap() + .remove(0); - assert_eq!(req.uri().path(), sreq.uri); - assert_eq!(req.method(), &sreq.method); - for (name, value) in &sreq.headers { - assert_eq!( - req.headers()[name], - value - ); - } - let sbody = sreq.body; - Box::new(req.into_body() - .concat2() - .map(move |body| { - assert_eq!(body.as_ref(), sbody.as_slice()); + assert_eq!(req.uri().path(), sreq.uri); + assert_eq!(req.method(), &sreq.method); + for (name, value) in &sreq.headers { + assert_eq!( + req.headers()[name], + value + ); + } + let sbody = sreq.body; + req.into_body() + .concat2() + .map(move |body| { + assert_eq!(body.as_ref(), sbody.as_slice()); - let mut res = Response::builder() - .status(sres.status) - .body(sres.body.into()) - .expect("Response::build"); - *res.headers_mut() = sres.headers; - res - })) - }); - let new_service = hyper::server::const_service(service); + let mut res = Response::builder() + .status(sres.status) + .body(Body::from(sres.body)) + .expect("Response::build"); + *res.headers_mut() = sres.headers; + res + }) + }) + }; let serve = hyper::server::conn::Http::new() .http2_only(cfg.server_version == 2) diff --git a/tests/support/mod.rs b/tests/support/mod.rs --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -246,8 +249,12 @@ pub fn __run_test(cfg: __TestConfig) { let (success_tx, success_rx) = oneshot::channel(); let expected_connections = cfg.connections; let server = serve - .fold(0, move |cnt, conn| { - exe.spawn(conn.map_err(|e| panic!("server connection error: {}", e))); + .fold(0, move |cnt, connecting| { + let fut = connecting + .map_err(|never| -> hyper::Error { match never {} }) + .flatten() + .map_err(|e| panic!("server connection error: {}", e)); + exe.spawn(fut); Ok::<_, hyper::Error>(cnt + 1) }) .map(move |cnt| {
Update Service trait from tokio-service to tower
Hi, I want to have a try, any mentoring instructions for this change? This wouldn't be too much work in hyper directly, but it does require [tower](https://github.com/tower-rs/tower) to publish a version to crates.io. I'd probably expect it to do so only after futures 0.2, since it needs to update to the new futures.
2018-04-17T23:34:09Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,488
hyperium__hyper-1488
[ "1263" ]
35c38cba6e13e1d2122f46bd0e02eafcebf776f7
diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -13,7 +13,8 @@ use tokio::runtime::Runtime; use tokio::net::TcpListener; use hyper::{Body, Method, Request, Response}; -use hyper::server::Http; +use hyper::client::HttpConnector; +use hyper::server::conn::Http; #[bench] diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -71,7 +76,7 @@ fn spawn_hello(rt: &mut Runtime) -> SocketAddr { let listener = TcpListener::bind(&addr).unwrap(); let addr = listener.local_addr().unwrap(); - let http = Http::<hyper::Chunk>::new(); + let http = Http::new(); let service = const_service(service_fn(|req: Request<Body>| { req.into_body() diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -81,6 +86,7 @@ fn spawn_hello(rt: &mut Runtime) -> SocketAddr { }) })); + // Specifically only accept 1 connection. let srv = listener.incoming() .into_future() .map_err(|(e, _inc)| panic!("accept error: {}", e)) diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -14,24 +14,28 @@ use std::sync::mpsc; use futures::{future, stream, Future, Stream}; use futures::sync::oneshot; -use hyper::{Body, Request, Response}; +use hyper::{Body, Request, Response, Server}; use hyper::server::Service; macro_rules! bench_server { ($b:ident, $header:expr, $body:expr) => ({ let _ = pretty_env_logger::try_init(); - let (_until_tx, until_rx) = oneshot::channel(); + let (_until_tx, until_rx) = oneshot::channel::<()>(); let addr = { let (addr_tx, addr_rx) = mpsc::channel(); ::std::thread::spawn(move || { let addr = "127.0.0.1:0".parse().unwrap(); - let srv = hyper::server::Http::new().bind(&addr, || Ok(BenchPayload { - header: $header, - body: $body, - })).unwrap(); - let addr = srv.local_addr().unwrap(); - addr_tx.send(addr).unwrap(); - tokio::run(srv.run_until(until_rx.map_err(|_| ())).map_err(|e| panic!("server error: {}", e))); + let srv = Server::bind(&addr) + .serve(|| Ok(BenchPayload { + header: $header, + body: $body, + })); + addr_tx.send(srv.local_addr()).unwrap(); + let fut = srv + .map_err(|e| panic!("server error: {}", e)) + .select(until_rx.then(|_| Ok(()))) + .then(|_| Ok(())); + tokio::run(fut); }); addr_rx.recv().unwrap() diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -5,15 +5,15 @@ extern crate pretty_env_logger; extern crate tokio; use futures::Future; -use futures::future::lazy; use hyper::{Body, Response}; -use hyper::server::{Http, const_service, service_fn}; +use hyper::server::{Server, const_service, service_fn}; static PHRASE: &'static [u8] = b"Hello World!"; fn main() { pretty_env_logger::init(); + let addr = ([127, 0, 0, 1], 3000).into(); let new_service = const_service(service_fn(|_| { diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -21,13 +21,11 @@ fn main() { Ok::<_, hyper::Error>(Response::new(Body::from(PHRASE))) })); - tokio::run(lazy(move || { - let server = Http::new() - .sleep_on_errors(true) - .bind(&addr, new_service) - .unwrap(); + let server = Server::bind(&addr) + .serve(new_service) + .map_err(|e| eprintln!("server error: {}", e)); - println!("Listening on http://{} with 1 thread.", server.local_addr().unwrap()); - server.run().map_err(|err| eprintln!("Server error {}", err)) - })); + println!("Listening on http://{}", addr); + + tokio::run(server); } diff --git a/examples/multi_server.rs b/examples/multi_server.rs --- a/examples/multi_server.rs +++ b/examples/multi_server.rs @@ -4,11 +4,11 @@ extern crate futures; extern crate pretty_env_logger; extern crate tokio; -use futures::{Future, Stream}; +use futures::{Future}; use futures::future::{FutureResult, lazy}; use hyper::{Body, Method, Request, Response, StatusCode}; -use hyper::server::{Http, Service}; +use hyper::server::{Server, Service}; static INDEX1: &'static [u8] = b"The 1st service!"; static INDEX2: &'static [u8] = b"The 2nd service!"; diff --git a/examples/multi_server.rs b/examples/multi_server.rs --- a/examples/multi_server.rs +++ b/examples/multi_server.rs @@ -40,25 +40,23 @@ impl Service for Srv { fn main() { pretty_env_logger::init(); - let addr1 = "127.0.0.1:1337".parse().unwrap(); - let addr2 = "127.0.0.1:1338".parse().unwrap(); + + let addr1 = ([127, 0, 0, 1], 1337).into(); + let addr2 = ([127, 0, 0, 1], 1338).into(); tokio::run(lazy(move || { - let srv1 = Http::new().serve_addr(&addr1, || Ok(Srv(INDEX1))).unwrap(); - let srv2 = Http::new().serve_addr(&addr2, || Ok(Srv(INDEX2))).unwrap(); + let srv1 = Server::bind(&addr1) + .serve(|| Ok(Srv(INDEX1))) + .map_err(|e| eprintln!("server 1 error: {}", e)); - println!("Listening on http://{}", srv1.incoming_ref().local_addr()); - println!("Listening on http://{}", srv2.incoming_ref().local_addr()); + let srv2 = Server::bind(&addr2) + .serve(|| Ok(Srv(INDEX2))) + .map_err(|e| eprintln!("server 2 error: {}", e)); - tokio::spawn(srv1.for_each(move |conn| { - tokio::spawn(conn.map_err(|err| println!("srv1 error: {:?}", err))); - Ok(()) - }).map_err(|_| ())); + println!("Listening on http://{} and http://{}", addr1, addr2); - tokio::spawn(srv2.for_each(move |conn| { - tokio::spawn(conn.map_err(|err| println!("srv2 error: {:?}", err))); - Ok(()) - }).map_err(|_| ())); + tokio::spawn(srv1); + tokio::spawn(srv2); Ok(()) })); diff --git a/examples/params.rs b/examples/params.rs --- a/examples/params.rs +++ b/examples/params.rs @@ -6,10 +6,9 @@ extern crate tokio; extern crate url; use futures::{Future, Stream}; -use futures::future::lazy; use hyper::{Body, Method, Request, Response, StatusCode}; -use hyper::server::{Http, Service}; +use hyper::server::{Server, Service}; use std::collections::HashMap; use url::form_urlencoded; diff --git a/examples/params.rs b/examples/params.rs --- a/examples/params.rs +++ b/examples/params.rs @@ -96,11 +95,12 @@ impl Service for ParamExample { fn main() { pretty_env_logger::init(); - let addr = "127.0.0.1:1337".parse().unwrap(); - tokio::run(lazy(move || { - let server = Http::new().bind(&addr, || Ok(ParamExample)).unwrap(); - println!("Listening on http://{} with 1 thread.", server.local_addr().unwrap()); - server.run().map_err(|err| eprintln!("Server error {}", err)) - })); + let addr = ([127, 0, 0, 1], 1337).into(); + + let server = Server::bind(&addr) + .serve(|| Ok(ParamExample)) + .map_err(|e| eprintln!("server error: {}", e)); + + tokio::run(server); } diff --git a/examples/send_file.rs b/examples/send_file.rs --- a/examples/send_file.rs +++ b/examples/send_file.rs @@ -5,11 +5,10 @@ extern crate pretty_env_logger; extern crate tokio; use futures::{Future/*, Sink*/}; -use futures::future::lazy; use futures::sync::oneshot; use hyper::{Body, /*Chunk,*/ Method, Request, Response, StatusCode}; -use hyper::server::{Http, Service}; +use hyper::server::{Server, Service}; use std::fs::File; use std::io::{self, copy/*, Read*/}; diff --git a/examples/send_file.rs b/examples/send_file.rs --- a/examples/send_file.rs +++ b/examples/send_file.rs @@ -138,11 +137,14 @@ impl Service for ResponseExamples { fn main() { pretty_env_logger::init(); + let addr = "127.0.0.1:1337".parse().unwrap(); - tokio::run(lazy(move || { - let server = Http::new().bind(&addr, || Ok(ResponseExamples)).unwrap(); - println!("Listening on http://{} with 1 thread.", server.local_addr().unwrap()); - server.run().map_err(|err| eprintln!("Server error {}", err)) - })); + let server = Server::bind(&addr) + .serve(|| Ok(ResponseExamples)) + .map_err(|e| eprintln!("server error: {}", e)); + + println!("Listening on http://{}", addr); + + tokio::run(server); } diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -5,10 +5,10 @@ extern crate pretty_env_logger; extern crate tokio; use futures::Future; -use futures::future::{FutureResult, lazy}; +use futures::future::{FutureResult}; use hyper::{Body, Method, Request, Response, StatusCode}; -use hyper::server::{Http, Service}; +use hyper::server::{Server, Service}; static INDEX: &'static [u8] = b"Try POST /echo"; diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -41,11 +41,14 @@ impl Service for Echo { fn main() { pretty_env_logger::init(); - let addr = "127.0.0.1:1337".parse().unwrap(); - tokio::run(lazy(move || { - let server = Http::new().bind(&addr, || Ok(Echo)).unwrap(); - println!("Listening on http://{} with 1 thread.", server.local_addr().unwrap()); - server.run().map_err(|err| eprintln!("Server error {}", err)) - })); + let addr = ([127, 0, 0, 1], 1337).into(); + + let server = Server::bind(&addr) + .serve(|| Ok(Echo)) + .map_err(|e| eprintln!("server error: {}", e)); + + println!("Listening on http://{}", addr); + + tokio::run(server); } diff --git a/examples/web_api.rs b/examples/web_api.rs --- a/examples/web_api.rs +++ b/examples/web_api.rs @@ -9,7 +9,7 @@ use futures::future::lazy; use hyper::{Body, Chunk, Client, Method, Request, Response, StatusCode}; use hyper::client::HttpConnector; -use hyper::server::{Http, Service}; +use hyper::server::{Server, Service}; #[allow(unused, deprecated)] use std::ascii::AsciiExt; diff --git a/examples/web_api.rs b/examples/web_api.rs --- a/examples/web_api.rs +++ b/examples/web_api.rs @@ -75,15 +75,17 @@ impl Service for ResponseExamples { fn main() { pretty_env_logger::init(); + let addr = "127.0.0.1:1337".parse().unwrap(); tokio::run(lazy(move || { let client = Client::new(); - let serve = Http::new().serve_addr(&addr, move || Ok(ResponseExamples(client.clone()))).unwrap(); - println!("Listening on http://{} with 1 thread.", serve.incoming_ref().local_addr()); + let server = Server::bind(&addr) + .serve(move || Ok(ResponseExamples(client.clone()))) + .map_err(|e| eprintln!("server error: {}", e)); + + println!("Listening on http://{}", addr); - serve.map_err(|_| ()).for_each(move |conn| { - tokio::spawn(conn.map_err(|err| println!("serve error: {:?}", err))) - }) + server })); } diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -171,12 +171,12 @@ impl Error { Error::new(Kind::Io, Some(cause.into())) } - pub(crate) fn new_listen(err: io::Error) -> Error { - Error::new(Kind::Listen, Some(err.into())) + pub(crate) fn new_listen<E: Into<Cause>>(cause: E) -> Error { + Error::new(Kind::Listen, Some(cause.into())) } - pub(crate) fn new_accept(err: io::Error) -> Error { - Error::new(Kind::Accept, Some(Box::new(err))) + pub(crate) fn new_accept<E: Into<Cause>>(cause: E) -> Error { + Error::new(Kind::Accept, Some(cause.into())) } pub(crate) fn new_connect<E: Into<Cause>>(cause: E) -> Error { diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -10,8 +10,19 @@ use tokio_io::{AsyncRead, AsyncWrite}; use proto::{Http1Transaction, MessageHead}; -const INIT_BUFFER_SIZE: usize = 8192; -pub const DEFAULT_MAX_BUFFER_SIZE: usize = 8192 + 4096 * 100; +/// The initial buffer size allocated before trying to read from IO. +pub(crate) const INIT_BUFFER_SIZE: usize = 8192; + +/// The default maximum read buffer size. If the buffer gets this big and +/// a message is still not complete, a `TooLarge` error is triggered. +// Note: if this changes, update server::conn::Http::max_buf_size docs. +pub(crate) const DEFAULT_MAX_BUFFER_SIZE: usize = 8192 + 4096 * 100; + +/// The maximum number of distinct `Buf`s to hold in a list before requiring +/// a flush. Only affects when the buffer strategy is to queue buffers. +/// +/// Note that a flush can happen before reaching the maximum. This simply +/// forces a flush if the queue gets this big. const MAX_BUF_LIST_BUFFERS: usize = 16; pub struct Buffered<T, B> { diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -5,19 +5,59 @@ //! are not handled at this level. This module provides the building blocks to //! customize those things externally. //! -//! If don't have need to manage connections yourself, consider using the +//! If you don't have need to manage connections yourself, consider using the //! higher-level [Server](super) API. use std::fmt; +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; use bytes::Bytes; -use futures::{Future, Poll}; -use futures::future::{Either}; +use futures::{Async, Future, Poll, Stream}; +use futures::future::{Either, Executor}; use tokio_io::{AsyncRead, AsyncWrite}; +//TODO: change these tokio:: to sub-crates +use tokio::reactor::Handle; +use common::Exec; use proto; use body::{Body, Payload}; -use super::{HyperService, Request, Response, Service}; +use super::{HyperService, NewService, Request, Response, Service}; + +pub use super::tcp::AddrIncoming; + +/// A lower-level configuration of the HTTP protocol. +/// +/// This structure is used to configure options for an HTTP server connection. +/// +/// If don't have need to manage connections yourself, consider using the +/// higher-level [Server](super) API. +#[derive(Clone, Debug)] +pub struct Http { + exec: Exec, + http2: bool, + keep_alive: bool, + max_buf_size: Option<usize>, + pipeline_flush: bool, +} + +/// A stream mapping incoming IOs to new services. +/// +/// Yields `Connection`s that are futures that should be put on a reactor. +#[must_use = "streams do nothing unless polled"] +#[derive(Debug)] +pub struct Serve<I, S> { + incoming: I, + new_service: S, + protocol: Http, +} + +#[must_use = "futures do nothing unless polled"] +#[derive(Debug)] +pub(super) struct SpawnAll<I, S> { + serve: Serve<I, S>, +} /// A future binding a connection with a Service. /// diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -63,6 +103,187 @@ pub struct Parts<T> { _inner: (), } +// ===== impl Http ===== + +impl Http { + /// Creates a new instance of the HTTP protocol, ready to spawn a server or + /// start accepting connections. + pub fn new() -> Http { + Http { + exec: Exec::Default, + http2: false, + keep_alive: true, + max_buf_size: None, + pipeline_flush: false, + } + } + + /// Sets whether HTTP2 is required. + /// + /// Default is false + pub fn http2_only(&mut self, val: bool) -> &mut Self { + self.http2 = val; + self + } + + /// Enables or disables HTTP keep-alive. + /// + /// Default is true. + pub fn keep_alive(&mut self, val: bool) -> &mut Self { + self.keep_alive = val; + self + } + + /// Set the maximum buffer size for the connection. + /// + /// Default is ~400kb. + pub fn max_buf_size(&mut self, max: usize) -> &mut Self { + self.max_buf_size = Some(max); + self + } + + /// Aggregates flushes to better support pipelined responses. + /// + /// Experimental, may be have bugs. + /// + /// Default is false. + pub fn pipeline_flush(&mut self, enabled: bool) -> &mut Self { + self.pipeline_flush = enabled; + self + } + + /// Set the executor used to spawn background tasks. + /// + /// Default uses implicit default (like `tokio::spawn`). + pub fn executor<E>(&mut self, exec: E) -> &mut Self + where + E: Executor<Box<Future<Item=(), Error=()> + Send>> + Send + Sync + 'static + { + self.exec = Exec::Executor(Arc::new(exec)); + self + } + + /// Bind a connection together with a `Service`. + /// + /// This returns a Future that must be polled in order for HTTP to be + /// driven on the connection. + /// + /// # Example + /// + /// ``` + /// # extern crate futures; + /// # extern crate hyper; + /// # extern crate tokio; + /// # extern crate tokio_io; + /// # use futures::Future; + /// # use hyper::{Body, Request, Response}; + /// # use hyper::server::Service; + /// # use hyper::server::conn::Http; + /// # use tokio_io::{AsyncRead, AsyncWrite}; + /// # use tokio::reactor::Handle; + /// # fn run<I, S>(some_io: I, some_service: S) + /// # where + /// # I: AsyncRead + AsyncWrite + Send + 'static, + /// # S: Service<Request=Request<Body>, Response=Response<Body>, Error=hyper::Error> + Send + 'static, + /// # S::Future: Send + /// # { + /// let http = Http::new(); + /// let conn = http.serve_connection(some_io, some_service); + /// + /// let fut = conn.map_err(|e| { + /// eprintln!("server connection error: {}", e); + /// }); + /// + /// tokio::spawn(fut); + /// # } + /// # fn main() {} + /// ``` + pub fn serve_connection<S, I, Bd>(&self, io: I, service: S) -> Connection<I, S> + where + S: Service<Request = Request<Body>, Response = Response<Bd>>, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + S::Future: Send + 'static, + Bd: Payload, + I: AsyncRead + AsyncWrite, + { + let either = if !self.http2 { + let mut conn = proto::Conn::new(io); + if !self.keep_alive { + conn.disable_keep_alive(); + } + conn.set_flush_pipeline(self.pipeline_flush); + if let Some(max) = self.max_buf_size { + conn.set_max_buf_size(max); + } + let sd = proto::h1::dispatch::Server::new(service); + Either::A(proto::h1::Dispatcher::new(sd, conn)) + } else { + let h2 = proto::h2::Server::new(io, service, self.exec.clone()); + Either::B(h2) + }; + + Connection { + conn: either, + } + } + + /// Bind the provided `addr` with the default `Handle` and return [`Serve`](Serve). + /// + /// This method will bind the `addr` provided with a new TCP listener ready + /// to accept connections. Each connection will be processed with the + /// `new_service` object provided, creating a new service per + /// connection. + pub fn serve_addr<S, Bd>(&self, addr: &SocketAddr, new_service: S) -> ::Result<Serve<AddrIncoming, S>> + where + S: NewService<Request=Request<Body>, Response=Response<Bd>>, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + Bd: Payload, + { + let mut incoming = AddrIncoming::new(addr, None)?; + if self.keep_alive { + incoming.set_keepalive(Some(Duration::from_secs(90))); + } + Ok(self.serve_incoming(incoming, new_service)) + } + + /// Bind the provided `addr` with the `Handle` and return a [`Serve`](Serve) + /// + /// This method will bind the `addr` provided with a new TCP listener ready + /// to accept connections. Each connection will be processed with the + /// `new_service` object provided, creating a new service per + /// connection. + pub fn serve_addr_handle<S, Bd>(&self, addr: &SocketAddr, handle: &Handle, new_service: S) -> ::Result<Serve<AddrIncoming, S>> + where + S: NewService<Request = Request<Body>, Response = Response<Bd>>, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + Bd: Payload, + { + let mut incoming = AddrIncoming::new(addr, Some(handle))?; + if self.keep_alive { + incoming.set_keepalive(Some(Duration::from_secs(90))); + } + Ok(self.serve_incoming(incoming, new_service)) + } + + /// Bind the provided stream of incoming IO objects with a `NewService`. + pub fn serve_incoming<I, S, Bd>(&self, incoming: I, new_service: S) -> Serve<I, S> + where + I: Stream, + I::Error: Into<Box<::std::error::Error + Send + Sync>>, + I::Item: AsyncRead + AsyncWrite, + S: NewService<Request = Request<Body>, Response = Response<Bd>>, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + Bd: Payload, + { + Serve { + incoming: incoming, + new_service: new_service, + protocol: self.clone(), + } + } +} + + // ===== impl Connection ===== impl<I, B, S> Connection<I, S> diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -154,3 +375,89 @@ where } } +// ===== impl Serve ===== + +impl<I, S> Serve<I, S> { + /// Spawn all incoming connections onto the executor in `Http`. + pub(super) fn spawn_all(self) -> SpawnAll<I, S> { + SpawnAll { + serve: self, + } + } + + /// Get a reference to the incoming stream. + #[inline] + pub fn incoming_ref(&self) -> &I { + &self.incoming + } + + /// Get a mutable reference to the incoming stream. + #[inline] + pub fn incoming_mut(&mut self) -> &mut I { + &mut self.incoming + } +} + +impl<I, S, B> Stream for Serve<I, S> +where + I: Stream, + I::Item: AsyncRead + AsyncWrite, + I::Error: Into<Box<::std::error::Error + Send + Sync>>, + S: NewService<Request=Request<Body>, Response=Response<B>>, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + <S::Instance as Service>::Future: Send + 'static, + B: Payload, +{ + type Item = Connection<I::Item, S::Instance>; + type Error = ::Error; + + fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { + if let Some(io) = try_ready!(self.incoming.poll().map_err(::Error::new_accept)) { + let service = self.new_service.new_service().map_err(::Error::new_user_new_service)?; + Ok(Async::Ready(Some(self.protocol.serve_connection(io, service)))) + } else { + Ok(Async::Ready(None)) + } + } +} + +// ===== impl SpawnAll ===== + +impl<S> SpawnAll<AddrIncoming, S> { + pub(super) fn local_addr(&self) -> SocketAddr { + self.serve.incoming.local_addr() + } +} + +impl<I, S> SpawnAll<I, S> { + pub(super) fn incoming_ref(&self) -> &I { + self.serve.incoming_ref() + } +} + +impl<I, S, B> Future for SpawnAll<I, S> +where + I: Stream, + I::Error: Into<Box<::std::error::Error + Send + Sync>>, + I::Item: AsyncRead + AsyncWrite + Send + 'static, + S: NewService<Request = Request<Body>, Response = Response<B>> + Send + 'static, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + <S as NewService>::Instance: Send, + <<S as NewService>::Instance as Service>::Future: Send + 'static, + B: Payload, +{ + type Item = (); + type Error = ::Error; + + fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + loop { + if let Some(conn) = try_ready!(self.serve.poll()) { + let fut = conn + .map_err(|err| debug!("conn error: {}", err)); + self.serve.protocol.exec.execute(fut); + } else { + return Ok(Async::Ready(())) + } + } + } +} diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -2,797 +2,175 @@ //! //! A `Server` is created to listen on a port, parse HTTP requests, and hand //! them off to a `Service`. +//! +//! There are two levels of APIs provide for constructing HTTP servers: +//! +//! - The higher-level [`Server`](Server). +//! - The lower-level [conn](conn) module. pub mod conn; mod service; +mod tcp; use std::fmt; -use std::io; -use std::net::{SocketAddr, TcpListener as StdTcpListener}; -use std::sync::{Arc, Mutex, Weak}; +use std::net::SocketAddr; use std::time::Duration; -use futures::task::{self, Task}; -use futures::future::{self, Either, Executor}; -use futures::{Future, Stream, Poll, Async}; -use futures_timer::Delay; +use futures::{Future, Stream, Poll}; use http::{Request, Response}; use tokio_io::{AsyncRead, AsyncWrite}; -use tokio::spawn; -use tokio::reactor::Handle; -use tokio::net::TcpListener; pub use tokio_service::{NewService, Service}; use body::{Body, Payload}; -use common::Exec; -use proto; -use self::addr_stream::AddrStream; +// Renamed `Http` as `Http_` for now so that people upgrading don't see an +// error that `hyper::server::Http` is private... +use self::conn::{Http as Http_, SpawnAll}; use self::hyper_service::HyperService; +use self::tcp::{AddrIncoming}; -pub use self::conn::Connection; pub use self::service::{const_service, service_fn}; -/// A configuration of the HTTP protocol. +/// A listening HTTP server. /// -/// This structure is used to create instances of `Server` or to spawn off tasks -/// which handle a connection to an HTTP server. Each instance of `Http` can be -/// configured with various protocol-level options such as keepalive. -#[derive(Clone, Debug)] -pub struct Http { - exec: Exec, - http2: bool, - keep_alive: bool, - max_buf_size: Option<usize>, - pipeline: bool, - sleep_on_errors: bool, +/// `Server` is a `Future` mapping a bound listener with a set of service +/// handlers. It is built using the [`Builder`](Builder), and the future +/// completes when the server has been shutdown. It should be run by an +/// `Executor`. +pub struct Server<I, S> { + spawn_all: SpawnAll<I, S>, } -/// An instance of a server created through `Http::bind`. -/// -/// This server is intended as a convenience for creating a TCP listener on an -/// address and then serving TCP connections accepted with the service provided. -pub struct Server<S> { - protocol: Http, - new_service: S, - handle: Handle, - listener: TcpListener, - shutdown_timeout: Duration, -} - -/// A stream mapping incoming IOs to new services. -/// -/// Yields `Connection`s that are futures that should be put on a reactor. -#[must_use = "streams do nothing unless polled"] +/// A builder for a [`Server`](Server). #[derive(Debug)] -pub struct Serve<I, S> { +pub struct Builder<I> { incoming: I, - new_service: S, - protocol: Http, -} - -/* -#[must_use = "futures do nothing unless polled"] -#[derive(Debug)] -pub struct SpawnAll<I, S, E> { - executor: E, - serve: Serve<I, S>, -} -*/ - -/// A stream of connections from binding to an address. -#[must_use = "streams do nothing unless polled"] -pub struct AddrIncoming { - addr: SocketAddr, - keep_alive_timeout: Option<Duration>, - listener: TcpListener, - handle: Handle, - sleep_on_errors: bool, - timeout: Option<Delay>, + protocol: Http_, } -impl fmt::Debug for AddrIncoming { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("AddrIncoming") - .field("addr", &self.addr) - .field("keep_alive_timeout", &self.keep_alive_timeout) - .field("listener", &self.listener) - .field("handle", &self.handle) - .field("sleep_on_errors", &self.sleep_on_errors) - .finish() - } -} - -// ===== impl Http ===== - -impl Http { - /// Creates a new instance of the HTTP protocol, ready to spawn a server or - /// start accepting connections. - pub fn new() -> Http { - Http { - exec: Exec::Default, - http2: false, - keep_alive: true, - max_buf_size: None, - pipeline: false, - sleep_on_errors: false, - } - } - - /// Sets whether HTTP2 is required. - /// - /// Default is false - pub fn http2_only(&mut self, val: bool) -> &mut Self { - self.http2 = val; - self - } - - /// Enables or disables HTTP keep-alive. - /// - /// Default is true. - pub fn keep_alive(&mut self, val: bool) -> &mut Self { - self.keep_alive = val; - self - } - - /// Set the maximum buffer size for the connection. - pub fn max_buf_size(&mut self, max: usize) -> &mut Self { - self.max_buf_size = Some(max); - self - } - - /// Aggregates flushes to better support pipelined responses. - /// - /// Experimental, may be have bugs. - /// - /// Default is false. - pub fn pipeline(&mut self, enabled: bool) -> &mut Self { - self.pipeline = enabled; - self - } - - /// Set the executor used to spawn background tasks. - /// - /// Default uses implicit default (like `tokio::spawn`). - pub fn executor<E>(&mut self, exec: E) -> &mut Self - where - E: Executor<Box<Future<Item=(), Error=()> + Send>> + Send + Sync + 'static - { - self.exec = Exec::Executor(Arc::new(exec)); - self - } - - /// Swallow connection accept errors. Instead of passing up IO errors when - /// the server is under heavy load the errors will be ignored. Some - /// connection accept errors (like "connection reset") can be ignored, some - /// (like "too many files open") may consume 100% CPU and a timout of 10ms - /// is used in that case. - /// - /// Default is false. - pub fn sleep_on_errors(&mut self, enabled: bool) -> &mut Self { - self.sleep_on_errors = enabled; - self - } - - /// Bind the provided `addr` and return a server ready to handle - /// connections. - /// - /// This method will bind the `addr` provided with a new TCP listener ready - /// to accept connections. Each connection will be processed with the - /// `new_service` object provided as well, creating a new service per - /// connection. - /// - /// The returned `Server` contains one method, `run`, which is used to - /// actually run the server. - pub fn bind<S, Bd>(&self, addr: &SocketAddr, new_service: S) -> ::Result<Server<S>> - where - S: NewService<Request=Request<Body>, Response=Response<Bd>> + 'static, - S::Error: Into<Box<::std::error::Error + Send + Sync>>, - Bd: Payload, - { - let handle = Handle::current(); - let std_listener = StdTcpListener::bind(addr).map_err(::Error::new_listen)?; - let listener = TcpListener::from_std(std_listener, &handle).map_err(::Error::new_listen)?; - - Ok(Server { - new_service: new_service, - handle: handle, - listener: listener, - protocol: self.clone(), - shutdown_timeout: Duration::new(1, 0), - }) - } - - /// Bind the provided `addr` and return a server with the default `Handle`. - /// - /// This is method will bind the `addr` provided with a new TCP listener ready - /// to accept connections. Each connection will be processed with the - /// `new_service` object provided as well, creating a new service per - /// connection. - pub fn serve_addr<S, Bd>(&self, addr: &SocketAddr, new_service: S) -> ::Result<Serve<AddrIncoming, S>> - where - S: NewService<Request=Request<Body>, Response=Response<Bd>>, - S::Error: Into<Box<::std::error::Error + Send + Sync>>, - Bd: Payload, - { - let handle = Handle::current(); - let std_listener = StdTcpListener::bind(addr).map_err(::Error::new_listen)?; - let listener = TcpListener::from_std(std_listener, &handle).map_err(::Error::new_listen)?; - let mut incoming = AddrIncoming::new(listener, handle.clone(), self.sleep_on_errors).map_err(::Error::new_listen)?; - if self.keep_alive { - incoming.set_keepalive(Some(Duration::from_secs(90))); - } - Ok(self.serve_incoming(incoming, new_service)) - } - - /// Bind the provided `addr` and return a server with a shared `Core`. - /// - /// This method allows the ability to share a `Core` with multiple servers. - /// - /// This is method will bind the `addr` provided with a new TCP listener ready - /// to accept connections. Each connection will be processed with the - /// `new_service` object provided as well, creating a new service per - /// connection. - pub fn serve_addr_handle<S, Bd>(&self, addr: &SocketAddr, handle: &Handle, new_service: S) -> ::Result<Serve<AddrIncoming, S>> - where - S: NewService<Request = Request<Body>, Response = Response<Bd>>, - S::Error: Into<Box<::std::error::Error + Send + Sync>>, - Bd: Payload, - { - let std_listener = StdTcpListener::bind(addr).map_err(::Error::new_listen)?; - let listener = TcpListener::from_std(std_listener, &handle).map_err(::Error::new_listen)?; - let mut incoming = AddrIncoming::new(listener, handle.clone(), self.sleep_on_errors).map_err(::Error::new_listen)?; - - if self.keep_alive { - incoming.set_keepalive(Some(Duration::from_secs(90))); - } - Ok(self.serve_incoming(incoming, new_service)) - } +// ===== impl Server ===== - /// Bind the provided stream of incoming IO objects with a `NewService`. - /// - /// This method allows the ability to share a `Core` with multiple servers. - pub fn serve_incoming<I, S, Bd>(&self, incoming: I, new_service: S) -> Serve<I, S> - where - I: Stream<Error=::std::io::Error>, - I::Item: AsyncRead + AsyncWrite, - S: NewService<Request = Request<Body>, Response = Response<Bd>>, - S::Error: Into<Box<::std::error::Error + Send + Sync>>, - Bd: Payload, - { - Serve { - incoming: incoming, - new_service: new_service, - protocol: self.clone(), +impl<I> Server<I, ()> { + /// Starts a [`Builder`](Builder) with the provided incoming stream. + pub fn builder(incoming: I) -> Builder<I> { + Builder { + incoming, + protocol: Http_::new(), } } +} - /// Bind a connection together with a Service. - /// - /// This returns a Future that must be polled in order for HTTP to be - /// driven on the connection. - /// - /// # Example +impl Server<AddrIncoming, ()> { + /// Binds to the provided address, and returns a [`Builder`](Builder). /// - /// ``` - /// # extern crate futures; - /// # extern crate hyper; - /// # extern crate tokio; - /// # extern crate tokio_io; - /// # use futures::Future; - /// # use hyper::{Body, Request, Response}; - /// # use hyper::server::{Http, Service}; - /// # use tokio_io::{AsyncRead, AsyncWrite}; - /// # use tokio::reactor::Handle; - /// # fn run<I, S>(some_io: I, some_service: S) - /// # where - /// # I: AsyncRead + AsyncWrite + Send + 'static, - /// # S: Service<Request=Request<Body>, Response=Response<Body>, Error=hyper::Error> + Send + 'static, - /// # S::Future: Send - /// # { - /// let http = Http::new(); - /// let conn = http.serve_connection(some_io, some_service); + /// # Panics /// - /// let fut = conn - /// .map_err(|e| eprintln!("server connection error: {}", e)); - /// - /// tokio::spawn(fut); - /// # } - /// # fn main() {} - /// ``` - pub fn serve_connection<S, I, Bd>(&self, io: I, service: S) -> Connection<I, S> - where - S: Service<Request = Request<Body>, Response = Response<Bd>>, - S::Error: Into<Box<::std::error::Error + Send + Sync>>, - S::Future: Send + 'static, - Bd: Payload, - I: AsyncRead + AsyncWrite, - { - let either = if !self.http2 { - let mut conn = proto::Conn::new(io); - if !self.keep_alive { - conn.disable_keep_alive(); - } - conn.set_flush_pipeline(self.pipeline); - if let Some(max) = self.max_buf_size { - conn.set_max_buf_size(max); - } - let sd = proto::h1::dispatch::Server::new(service); - Either::A(proto::h1::Dispatcher::new(sd, conn)) - } else { - let h2 = proto::h2::Server::new(io, service, self.exec.clone()); - Either::B(h2) - }; - - Connection { - conn: either, - } + /// This method will panic if binding to the address fails. For a method + /// to bind to an address and return a `Result`, see `Server::try_bind`. + pub fn bind(addr: &SocketAddr) -> Builder<AddrIncoming> { + let incoming = AddrIncoming::new(addr, None) + .unwrap_or_else(|e| { + panic!("error binding to {}: {}", addr, e); + }); + Server::builder(incoming) } -} - - -// ===== impl Server ===== - -/// TODO: add docs -pub struct Run(Box<Future<Item=(), Error=::Error> + Send + 'static>); - -impl fmt::Debug for Run { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("Run").finish() + /// Tries to bind to the provided address, and returns a [`Builder`](Builder). + pub fn try_bind(addr: &SocketAddr) -> ::Result<Builder<AddrIncoming>> { + AddrIncoming::new(addr, None) + .map(Server::builder) } } -impl Future for Run { - type Item = (); - type Error = ::Error; - - fn poll(&mut self) -> Poll<(), ::Error> { - self.0.poll() +impl<S> Server<AddrIncoming, S> { + /// Returns the local address that this server is bound to. + pub fn local_addr(&self) -> SocketAddr { + self.spawn_all.local_addr() } } - -impl<S, B> Server<S> +impl<I, S, B> Future for Server<I, S> where + I: Stream, + I::Error: Into<Box<::std::error::Error + Send + Sync>>, + I::Item: AsyncRead + AsyncWrite + Send + 'static, S: NewService<Request = Request<Body>, Response = Response<B>> + Send + 'static, S::Error: Into<Box<::std::error::Error + Send + Sync>>, <S as NewService>::Instance: Send, <<S as NewService>::Instance as Service>::Future: Send + 'static, - B: Payload + Send + 'static, - B::Data: Send, -{ - /// Returns the local address that this server is bound to. - pub fn local_addr(&self) -> ::Result<SocketAddr> { - //TODO: this shouldn't return an error at all, but should get the - //local_addr at construction - self.listener.local_addr().map_err(::Error::new_io) - } - - /// Configure the amount of time this server will wait for a "graceful - /// shutdown". - /// - /// This is the amount of time after the shutdown signal is received the - /// server will wait for all pending connections to finish. If the timeout - /// elapses then the server will be forcibly shut down. - /// - /// This defaults to 1s. - pub fn shutdown_timeout(&mut self, timeout: Duration) -> &mut Self { - self.shutdown_timeout = timeout; - self - } - - /// Execute this server infinitely. - /// - /// This method does not currently return, but it will return an error if - /// one occurs. - pub fn run(self) -> Run { - self.run_until(future::empty()) - } - - /// Execute this server until the given future, `shutdown_signal`, resolves. - /// - /// This method, like `run` above, is used to execute this HTTP server. The - /// difference with `run`, however, is that this method allows for shutdown - /// in a graceful fashion. The future provided is interpreted as a signal to - /// shut down the server when it resolves. - /// - /// This method will block the current thread executing the HTTP server. - /// When the `shutdown_signal` has resolved then the TCP listener will be - /// unbound (dropped). The thread will continue to block for a maximum of - /// `shutdown_timeout` time waiting for active connections to shut down. - /// Once the `shutdown_timeout` elapses or all active connections are - /// cleaned out then this method will return. - pub fn run_until<F>(self, shutdown_signal: F) -> Run - where F: Future<Item = (), Error = ()> + Send + 'static, - { - let Server { protocol, new_service, handle, listener, shutdown_timeout } = self; - - let mut incoming = match AddrIncoming::new(listener, handle.clone(), protocol.sleep_on_errors) { - Ok(incoming) => incoming, - Err(err) => return Run(Box::new(future::err(::Error::new_listen(err)))), - }; - - if protocol.keep_alive { - incoming.set_keepalive(Some(Duration::from_secs(90))); - } - - // Mini future to track the number of active services - let info = Arc::new(Mutex::new(Info { - active: 0, - blocker: None, - })); - - // Future for our server's execution - let info_cloned = info.clone(); - let srv = incoming.for_each(move |socket| { - let addr = socket.remote_addr; - debug!("accepted new connection ({})", addr); - - let service = new_service.new_service()?; - let s = NotifyService { - inner: service, - info: Arc::downgrade(&info_cloned), - }; - info_cloned.lock().unwrap().active += 1; - let fut = protocol.serve_connection(socket, s) - .map(|_| ()) - .map_err(move |err| error!("server connection error: ({}) {}", addr, err)); - spawn(fut); - Ok(()) - }); - - // for now, we don't care if the shutdown signal succeeds or errors - // as long as it resolves, we will shutdown. - let shutdown_signal = shutdown_signal.then(|_| Ok(())); - - // Main execution of the server. Here we use `select` to wait for either - // `incoming` or `f` to resolve. We know that `incoming` will never - // resolve with a success (it's infinite) so we're actually just waiting - // for an error or for `f`, our shutdown signal. - // - // When we get a shutdown signal (`Ok`) then we drop the TCP listener to - // stop accepting incoming connections. - let main_execution = shutdown_signal.select(srv).then(move |result| { - match result { - Ok(((), _incoming)) => {}, - Err((e, _other)) => return future::Either::A(future::err(::Error::new_accept(e))), - } - - // Ok we've stopped accepting new connections at this point, but we want - // to give existing connections a chance to clear themselves out. Wait - // at most `shutdown_timeout` time before we just return clearing - // everything out. - // - // Our custom `WaitUntilZero` will resolve once all services constructed - // here have been destroyed. - let timeout = Delay::new(shutdown_timeout); - let wait = WaitUntilZero { info: info.clone() }; - future::Either::B(wait.select(timeout).then(|result| { - match result { - Ok(_) => Ok(()), - //TODO: error variant should be "timed out waiting for graceful shutdown" - Err((e, _)) => Err(::Error::new_io(e)) - } - })) - }); - - Run(Box::new(main_execution)) - } -} - -impl<S: fmt::Debug> fmt::Debug for Server<S> -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("Server") - .field("listener", &self.listener) - .field("new_service", &self.new_service) - .field("protocol", &self.protocol) - .finish() - } -} - -// ===== impl Serve ===== - -impl<I, S> Serve<I, S> { - /* - /// Spawn all incoming connections onto the provide executor. - pub fn spawn_all<E>(self, executor: E) -> SpawnAll<I, S, E> { - SpawnAll { - executor: executor, - serve: self, - } - } - */ - - /// Get a reference to the incoming stream. - #[inline] - pub fn incoming_ref(&self) -> &I { - &self.incoming - } -} - -impl<I, S, B> Stream for Serve<I, S> -where - I: Stream<Error=io::Error>, - I::Item: AsyncRead + AsyncWrite, - S: NewService<Request=Request<Body>, Response=Response<B>>, - S::Error: Into<Box<::std::error::Error + Send + Sync>>, - <S::Instance as Service>::Future: Send + 'static, B: Payload, -{ - type Item = Connection<I::Item, S::Instance>; - type Error = ::Error; - - fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { - if let Some(io) = try_ready!(self.incoming.poll().map_err(::Error::new_accept)) { - let service = self.new_service.new_service().map_err(::Error::new_user_new_service)?; - Ok(Async::Ready(Some(self.protocol.serve_connection(io, service)))) - } else { - Ok(Async::Ready(None)) - } - } -} - -// ===== impl SpawnAll ===== - -/* -impl<I, S, E> Future for SpawnAll<I, S, E> -where - I: Stream<Error=io::Error>, - I::Item: AsyncRead + AsyncWrite, - S: NewService<Request=Request<Body>, Response=Response<B>, Error=::Error>, - B: Stream<Error=::Error>, - B::Item: AsRef<[u8]>, - //E: Executor<Connection<I::Item, S::Instance>>, { type Item = (); type Error = ::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - loop { - if let Some(conn) = try_ready!(self.serve.poll()) { - let fut = conn - .map(|_| ()) - .map_err(|err| debug!("conn error: {}", err)); - match self.executor.execute(fut) { - Ok(()) => (), - Err(err) => match err.kind() { - ExecuteErrorKind::NoCapacity => { - debug!("SpawnAll::poll; executor no capacity"); - // continue loop - }, - ExecuteErrorKind::Shutdown | _ => { - debug!("SpawnAll::poll; executor shutdown"); - return Ok(Async::Ready(())) - } - } - } - } else { - return Ok(Async::Ready(())) - } - } + self.spawn_all.poll() } } -*/ - -// ===== impl AddrIncoming ===== -impl AddrIncoming { - fn new(listener: TcpListener, handle: Handle, sleep_on_errors: bool) -> io::Result<AddrIncoming> { - Ok(AddrIncoming { - addr: listener.local_addr()?, - keep_alive_timeout: None, - listener: listener, - handle: handle, - sleep_on_errors: sleep_on_errors, - timeout: None, - }) - } - - /// Get the local address bound to this listener. - pub fn local_addr(&self) -> SocketAddr { - self.addr - } - - fn set_keepalive(&mut self, dur: Option<Duration>) { - self.keep_alive_timeout = dur; - } - - /* - fn set_sleep_on_errors(&mut self, val: bool) { - self.sleep_on_errors = val; - } - */ -} - -impl Stream for AddrIncoming { - // currently unnameable... - type Item = AddrStream; - type Error = ::std::io::Error; - - fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { - // Check if a previous timeout is active that was set by IO errors. - if let Some(ref mut to) = self.timeout { - match to.poll().expect("timeout never fails") { - Async::Ready(_) => {} - Async::NotReady => return Ok(Async::NotReady), - } - } - self.timeout = None; - loop { - match self.listener.poll_accept() { - Ok(Async::Ready((socket, addr))) => { - if let Some(dur) = self.keep_alive_timeout { - if let Err(e) = socket.set_keepalive(Some(dur)) { - trace!("error trying to set TCP keepalive: {}", e); - } - } - return Ok(Async::Ready(Some(AddrStream::new(socket, addr)))); - }, - Ok(Async::NotReady) => return Ok(Async::NotReady), - Err(ref e) if self.sleep_on_errors => { - // Connection errors can be ignored directly, continue by - // accepting the next request. - if connection_error(e) { - continue; - } - // Sleep 10ms. - let delay = ::std::time::Duration::from_millis(10); - debug!("accept error: {}; sleeping {:?}", - e, delay); - let mut timeout = Delay::new(delay); - let result = timeout.poll() - .expect("timeout never fails"); - match result { - Async::Ready(()) => continue, - Async::NotReady => { - self.timeout = Some(timeout); - return Ok(Async::NotReady); - } - } - }, - Err(e) => return Err(e), - } - } +impl<I: fmt::Debug, S: fmt::Debug> fmt::Debug for Server<I, S> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Server") + .field("listener", &self.spawn_all.incoming_ref()) + .finish() } } -/// This function defines errors that are per-connection. Which basically -/// means that if we get this error from `accept()` system call it means -/// next connection might be ready to be accepted. -/// -/// All other errors will incur a timeout before next `accept()` is performed. -/// The timeout is useful to handle resource exhaustion errors like ENFILE -/// and EMFILE. Otherwise, could enter into tight loop. -fn connection_error(e: &io::Error) -> bool { - e.kind() == io::ErrorKind::ConnectionRefused || - e.kind() == io::ErrorKind::ConnectionAborted || - e.kind() == io::ErrorKind::ConnectionReset -} - -mod addr_stream { - use std::io::{self, Read, Write}; - use std::net::SocketAddr; - use bytes::{Buf, BufMut}; - use futures::Poll; - use tokio::net::TcpStream; - use tokio_io::{AsyncRead, AsyncWrite}; - - - #[derive(Debug)] - pub struct AddrStream { - inner: TcpStream, - pub(super) remote_addr: SocketAddr, - } - - impl AddrStream { - pub(super) fn new(tcp: TcpStream, addr: SocketAddr) -> AddrStream { - AddrStream { - inner: tcp, - remote_addr: addr, - } - } - } +// ===== impl Builder ===== - impl Read for AddrStream { - #[inline] - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.inner.read(buf) - } - } - - impl Write for AddrStream { - #[inline] - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.inner.write(buf) - } - - #[inline] - fn flush(&mut self ) -> io::Result<()> { - self.inner.flush() +impl<I> Builder<I> { + /// Start a new builder, wrapping an incoming stream and low-level options. + /// + /// For a more convenient constructor, see [`Server::bind`](Server::bind). + pub fn new(incoming: I, protocol: Http_) -> Self { + Builder { + incoming, + protocol, } } - impl AsyncRead for AddrStream { - #[inline] - unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool { - self.inner.prepare_uninitialized_buffer(buf) - } - - #[inline] - fn read_buf<B: BufMut>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { - self.inner.read_buf(buf) - } + /// Sets whether HTTP/2 is required. + /// + /// Default is `false`. + pub fn http2_only(mut self, val: bool) -> Self { + self.protocol.http2_only(val); + self } - impl AsyncWrite for AddrStream { - #[inline] - fn shutdown(&mut self) -> Poll<(), io::Error> { - AsyncWrite::shutdown(&mut self.inner) - } - - #[inline] - fn write_buf<B: Buf>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { - self.inner.write_buf(buf) + /// Consume this `Builder`, creating a [`Server`](Server). + pub fn serve<S, B>(self, new_service: S) -> Server<I, S> + where + I: Stream, + I::Error: Into<Box<::std::error::Error + Send + Sync>>, + I::Item: AsyncRead + AsyncWrite + Send + 'static, + S: NewService<Request = Request<Body>, Response = Response<B>>, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + <S as NewService>::Instance: Send, + <<S as NewService>::Instance as Service>::Future: Send + 'static, + B: Payload, + { + let serve = self.protocol.serve_incoming(self.incoming, new_service); + let spawn_all = serve.spawn_all(); + Server { + spawn_all, } } } -// ===== NotifyService ===== - -struct NotifyService<S> { - inner: S, - info: Weak<Mutex<Info>>, -} - -struct WaitUntilZero { - info: Arc<Mutex<Info>>, -} - -struct Info { - active: usize, - blocker: Option<Task>, -} - -impl<S: Service> Service for NotifyService<S> { - type Request = S::Request; - type Response = S::Response; - type Error = S::Error; - type Future = S::Future; - - fn call(&self, message: Self::Request) -> Self::Future { - self.inner.call(message) - } -} - -impl<S> Drop for NotifyService<S> { - fn drop(&mut self) { - let info = match self.info.upgrade() { - Some(info) => info, - None => return, - }; - let mut info = info.lock().unwrap(); - info.active -= 1; - if info.active == 0 { - if let Some(task) = info.blocker.take() { - task.notify(); - } - } +impl Builder<AddrIncoming> { + /// Set whether TCP keepalive messages are enabled on accepted connections. + /// + /// If `None` is specified, keepalive is disabled, otherwise the duration + /// specified will be the time to remain idle before sending TCP keepalive + /// probes. + pub fn tcp_keepalive(mut self, keepalive: Option<Duration>) -> Self { + self.incoming.set_keepalive(keepalive); + self } -} - -impl Future for WaitUntilZero { - type Item = (); - type Error = io::Error; - fn poll(&mut self) -> Poll<(), io::Error> { - let mut info = self.info.lock().unwrap(); - if info.active == 0 { - Ok(().into()) - } else { - info.blocker = Some(task::current()); - Ok(Async::NotReady) - } + /// Set the value of `TCP_NODELAY` option for accepted connections. + pub fn tcp_nodelay(mut self, enabled: bool) -> Self { + self.incoming.set_nodelay(enabled); + self } } diff --git /dev/null b/src/server/tcp.rs new file mode 100644 --- /dev/null +++ b/src/server/tcp.rs @@ -0,0 +1,234 @@ +use std::fmt; +use std::io; +use std::net::{SocketAddr, TcpListener as StdTcpListener}; +use std::time::Duration; + +use futures::{Async, Future, Poll, Stream}; +use futures_timer::Delay; +//TODO: change to tokio_tcp::net::TcpListener +use tokio::net::TcpListener; +use tokio::reactor::Handle; + +use self::addr_stream::AddrStream; + +/// A stream of connections from binding to an address. +#[must_use = "streams do nothing unless polled"] +pub struct AddrIncoming { + addr: SocketAddr, + listener: TcpListener, + sleep_on_errors: bool, + tcp_keepalive_timeout: Option<Duration>, + tcp_nodelay: bool, + timeout: Option<Delay>, +} + +impl AddrIncoming { + pub(super) fn new(addr: &SocketAddr, handle: Option<&Handle>) -> ::Result<AddrIncoming> { + let listener = if let Some(handle) = handle { + let std_listener = StdTcpListener::bind(addr) + .map_err(::Error::new_listen)?; + TcpListener::from_std(std_listener, handle) + .map_err(::Error::new_listen)? + } else { + TcpListener::bind(addr).map_err(::Error::new_listen)? + }; + + let addr = listener.local_addr().map_err(::Error::new_listen)?; + + Ok(AddrIncoming { + addr: addr, + listener: listener, + sleep_on_errors: true, + tcp_keepalive_timeout: None, + tcp_nodelay: false, + timeout: None, + }) + } + + /// Get the local address bound to this listener. + pub fn local_addr(&self) -> SocketAddr { + self.addr + } + + /// Set whether TCP keepalive messages are enabled on accepted connections. + /// + /// If `None` is specified, keepalive is disabled, otherwise the duration + /// specified will be the time to remain idle before sending TCP keepalive + /// probes. + pub fn set_keepalive(&mut self, keepalive: Option<Duration>) -> &mut Self { + self.tcp_keepalive_timeout = keepalive; + self + } + + /// Set the value of `TCP_NODELAY` option for accepted connections. + pub fn set_nodelay(&mut self, enabled: bool) -> &mut Self { + self.tcp_nodelay = enabled; + self + } + + /// Set whether to sleep on accept errors. + /// + /// A possible scenario is that the process has hit the max open files + /// allowed, and so trying to accept a new connection will fail with + /// `EMFILE`. In some cases, it's preferable to just wait for some time, if + /// the application will likely close some files (or connections), and try + /// to accept the connection again. If this option is `true`, the error + /// will be logged at the `error` level, since it is still a big deal, + /// and then the listener will sleep for 1 second. + /// + /// In other cases, hitting the max open files should be treat similarly + /// to being out-of-memory, and simply error (and shutdown). Setting + /// this option to `false` will allow that. + /// + /// Default is `true`. + pub fn set_sleep_on_errors(&mut self, val: bool) { + self.sleep_on_errors = val; + } +} + +impl Stream for AddrIncoming { + // currently unnameable... + type Item = AddrStream; + type Error = ::std::io::Error; + + fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { + // Check if a previous timeout is active that was set by IO errors. + if let Some(ref mut to) = self.timeout { + match to.poll().expect("timeout never fails") { + Async::Ready(_) => {} + Async::NotReady => return Ok(Async::NotReady), + } + } + self.timeout = None; + loop { + match self.listener.poll_accept() { + Ok(Async::Ready((socket, addr))) => { + if let Some(dur) = self.tcp_keepalive_timeout { + if let Err(e) = socket.set_keepalive(Some(dur)) { + trace!("error trying to set TCP keepalive: {}", e); + } + } + if let Err(e) = socket.set_nodelay(self.tcp_nodelay) { + trace!("error trying to set TCP nodelay: {}", e); + } + return Ok(Async::Ready(Some(AddrStream::new(socket, addr)))); + }, + Ok(Async::NotReady) => return Ok(Async::NotReady), + Err(ref e) if self.sleep_on_errors => { + // Connection errors can be ignored directly, continue by + // accepting the next request. + if is_connection_error(e) { + debug!("accepted connection already errored: {}", e); + continue; + } + // Sleep 1s. + let delay = Duration::from_secs(1); + error!("accept error: {}", e); + let mut timeout = Delay::new(delay); + let result = timeout.poll() + .expect("timeout never fails"); + match result { + Async::Ready(()) => continue, + Async::NotReady => { + self.timeout = Some(timeout); + return Ok(Async::NotReady); + } + } + }, + Err(e) => return Err(e), + } + } + } +} + +/// This function defines errors that are per-connection. Which basically +/// means that if we get this error from `accept()` system call it means +/// next connection might be ready to be accepted. +/// +/// All other errors will incur a timeout before next `accept()` is performed. +/// The timeout is useful to handle resource exhaustion errors like ENFILE +/// and EMFILE. Otherwise, could enter into tight loop. +fn is_connection_error(e: &io::Error) -> bool { + e.kind() == io::ErrorKind::ConnectionRefused || + e.kind() == io::ErrorKind::ConnectionAborted || + e.kind() == io::ErrorKind::ConnectionReset +} + +impl fmt::Debug for AddrIncoming { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("AddrIncoming") + .field("addr", &self.addr) + .field("sleep_on_errors", &self.sleep_on_errors) + .field("tcp_keepalive_timeout", &self.tcp_keepalive_timeout) + .field("tcp_nodelay", &self.tcp_nodelay) + .finish() + } +} + +mod addr_stream { + use std::io::{self, Read, Write}; + use std::net::SocketAddr; + use bytes::{Buf, BufMut}; + use futures::Poll; + use tokio::net::TcpStream; + use tokio_io::{AsyncRead, AsyncWrite}; + + + #[derive(Debug)] + pub struct AddrStream { + inner: TcpStream, + pub(super) remote_addr: SocketAddr, + } + + impl AddrStream { + pub(super) fn new(tcp: TcpStream, addr: SocketAddr) -> AddrStream { + AddrStream { + inner: tcp, + remote_addr: addr, + } + } + } + + impl Read for AddrStream { + #[inline] + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.inner.read(buf) + } + } + + impl Write for AddrStream { + #[inline] + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.inner.write(buf) + } + + #[inline] + fn flush(&mut self ) -> io::Result<()> { + self.inner.flush() + } + } + + impl AsyncRead for AddrStream { + #[inline] + unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool { + self.inner.prepare_uninitialized_buffer(buf) + } + + #[inline] + fn read_buf<B: BufMut>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { + self.inner.read_buf(buf) + } + } + + impl AsyncWrite for AddrStream { + #[inline] + fn shutdown(&mut self) -> Poll<(), io::Error> { + AsyncWrite::shutdown(&mut self.inner) + } + + #[inline] + fn write_buf<B: Buf>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { + self.inner.write_buf(buf) + } + } +}
diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -21,8 +22,10 @@ fn get_one_at_a_time(b: &mut test::Bencher) { let mut rt = Runtime::new().unwrap(); let addr = spawn_hello(&mut rt); - let client = hyper::Client::configure() - .build_with_executor(&rt.reactor(), rt.executor()); + let connector = HttpConnector::new_with_handle(1, rt.reactor().clone()); + let client = hyper::Client::builder() + .executor(rt.executor()) + .build::<_, Body>(connector); let url: hyper::Uri = format!("http://{}/get", addr).parse().unwrap(); diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -43,8 +46,10 @@ fn post_one_at_a_time(b: &mut test::Bencher) { let mut rt = Runtime::new().unwrap(); let addr = spawn_hello(&mut rt); - let client = hyper::Client::configure() - .build_with_executor(&rt.reactor(), rt.executor()); + let connector = HttpConnector::new_with_handle(1, rt.reactor().clone()); + let client = hyper::Client::builder() + .executor(rt.executor()) + .build::<_, Body>(connector); let url: hyper::Uri = format!("http://{}/post", addr).parse().unwrap(); diff --git a/tests/integration.rs b/tests/integration.rs --- a/tests/integration.rs +++ b/tests/integration.rs @@ -1,3 +1,4 @@ +#![deny(warnings)] #[macro_use] mod support; use self::support::*; diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -24,7 +24,6 @@ use futures::future::{self, FutureResult, Either}; use futures::sync::oneshot; use futures_timer::Delay; use http::header::{HeaderName, HeaderValue}; -//use net2::TcpBuilder; use tokio::net::TcpListener; use tokio::runtime::Runtime; use tokio::reactor::Handle; diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -32,7 +31,8 @@ use tokio_io::{AsyncRead, AsyncWrite}; use hyper::{Body, Request, Response, StatusCode}; -use hyper::server::{Http, Service, NewService, service_fn}; +use hyper::server::{Service, NewService, service_fn}; +use hyper::server::conn::Http; fn tcp_bind(addr: &SocketAddr, handle: &Handle) -> ::tokio::io::Result<TcpListener> { let std_listener = StdTcpListener::bind(addr).unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1363,8 +1363,9 @@ fn serve_with_options(options: ServeOptions) -> Serve { let (msg_tx, msg_rx) = mpsc::channel(); let (reply_tx, reply_rx) = spmc::channel(); let (shutdown_tx, shutdown_rx) = oneshot::channel(); + let shutdown_rx = shutdown_rx.then(|_| Ok(())); - let addr = "127.0.0.1:0".parse().unwrap(); + let addr = ([127, 0, 0, 1], 0).into(); let keep_alive = !options.keep_alive_disabled; let pipeline = options.pipeline; diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1372,22 +1373,40 @@ fn serve_with_options(options: ServeOptions) -> Serve { let thread_name = format!("test-server-{:?}", dur); let thread = thread::Builder::new().name(thread_name).spawn(move || { - tokio::run(::futures::future::lazy(move || { - let srv = Http::new() - .keep_alive(keep_alive) - .pipeline(pipeline) - .bind(&addr, TestService { - tx: Arc::new(Mutex::new(msg_tx.clone())), - _timeout: dur, - reply: reply_rx, - }).unwrap(); - addr_tx.send(srv.local_addr().unwrap()).unwrap(); - srv.run_until(shutdown_rx.then(|_| Ok(()))) - .map_err(|err| println!("error {}", err)) - })) - }).unwrap(); + let serve = Http::new() + .keep_alive(keep_alive) + .pipeline_flush(pipeline) + .serve_addr(&addr, TestService { + tx: Arc::new(Mutex::new(msg_tx.clone())), + _timeout: dur, + reply: reply_rx, + }) + .expect("bind to address"); + + addr_tx.send( + serve + .incoming_ref() + .local_addr() + ).expect("server addr tx"); + + // spawn_all() is private for now, so just duplicate it here + let spawn_all = serve.for_each(|conn| { + tokio::spawn(conn.map_err(|e| { + println!("server error: {}", e); + })); + Ok(()) + }).map_err(|e| { + println!("accept error: {}", e) + }); + + let fut = spawn_all + .select(shutdown_rx) + .then(|_| Ok(())); + + tokio::run(fut); + }).expect("thread spawn"); - let addr = addr_rx.recv().unwrap(); + let addr = addr_rx.recv().expect("server addr rx"); Serve { msg_rx: msg_rx, diff --git a/tests/support/mod.rs b/tests/support/mod.rs --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -123,9 +123,11 @@ macro_rules! __internal_req_res_prop { ); (headers: $map:tt) => ({ #[allow(unused_mut)] + { let mut headers = HeaderMap::new(); __internal_headers!(headers, $map); headers + } }); ($prop_name:ident: $prop_val:expr) => ( From::from($prop_val) diff --git a/tests/support/mod.rs b/tests/support/mod.rs --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -228,7 +230,7 @@ pub fn __run_test(cfg: __TestConfig) { }); let new_service = hyper::server::const_service(service); - let serve = hyper::server::Http::new() + let serve = hyper::server::conn::Http::new() .http2_only(cfg.server_version == 2) .executor(rt.executor()) .serve_addr_handle( diff --git a/tests/support/mod.rs b/tests/support/mod.rs --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -244,7 +246,7 @@ pub fn __run_test(cfg: __TestConfig) { let (success_tx, success_rx) = oneshot::channel(); let expected_connections = cfg.connections; let server = serve - .fold(0, move |cnt, conn: hyper::server::Connection<_, _>| { + .fold(0, move |cnt, conn| { exe.spawn(conn.map_err(|e| panic!("server connection error: {}", e))); Ok::<_, hyper::Error>(cnt + 1) })
Http::bind does not scale to uses where a Handle is needed So, I have a [`ReverseProxy` type that requires a `Client`](https://docs.rs/hyper-reverse-proxy/0.2.1/hyper_reverse_proxy/struct.ReverseProxy.html#method.new) in order to be constructed. But in order to do that I need to [do the manual set up of the Tokio event loop](https://docs.rs/hyper-reverse-proxy/0.2.1/hyper_reverse_proxy/#example), because constructing a `Client` requires access to the `Handle`, which I can't get when calling `Http::bind`. ```rust fn run() -> hyper::Result<()> { // Set up the Tokio reactor core let mut core = Core::new()?; let handle = core.handle(); // Set up a TCP socket to listen to let listen_addr = SocketAddr::new(Ipv4Addr::new(127, 0, 0, 1).into(), 8080); let listener = TcpListener::bind(&listen_addr, &handle)?; // Listen to incoming requests over TCP, and forward them to a new `ReverseProxy` let http = Http::new(); let server = listener.incoming().for_each(|(socket, addr)| { let client = Client::new(&handle); let service = ReverseProxy::new(client, Some(addr.ip())); http.bind_connection(&handle, socket, addr, service); Ok(()) }); // Start our server on the reactor core core.run(server)?; Ok(()) } ``` This gets pretty horrific once I start needing the graceful shutdown behavior of `Server::run_until`, as shown by [hyper-reverse-proxy/examples/extended.rs](https://github.com/brendanzab/hyper-reverse-proxy/blob/2b2ef26523aca56f822622dc287b4fab925a7b42/examples/extended.rs). I pretty much need to re-implement all of that stuff myself... Is there a better way to go about this? Or could we have a `Http::bind_with_handle` which could allow us to pass a handle to our own reactor core into Hyper?
Same here, exposing a handle is not enough: I'm running two HTTP servers on the same event loop (one http handling let's encrypt, and redirecting other requests to https), plus a pleingres database connection, and an SSH server. I would be able to spawn the pleingres and SSH server using just the current handle, but not to run the two HTTP servers, because each wants its own event loop. I'd be willing to write the two extra lines in my program to start the event loop myself, though. I've put this off for a while claiming that it will be solved in tokio-proto, but I'm now leaning towards may as well fix it in hyper, if a generic way appears in the future, no harm done. The proposal is in #1322.
2018-04-16T19:04:36Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,480
hyperium__hyper-1480
[ "1338" ]
33874f9a7577eb20374c6d8943ce665feb9619e0
diff --git a/examples/client.rs b/examples/client.rs --- a/examples/client.rs +++ b/examples/client.rs @@ -40,8 +40,9 @@ fn main() { println!("Response: {}", res.status()); println!("Headers: {:#?}", res.headers()); - res.into_parts().1.into_stream().for_each(|chunk| { - io::stdout().write_all(&chunk).map_err(From::from) + res.into_body().into_stream().for_each(|chunk| { + io::stdout().write_all(&chunk) + .map_err(|e| panic!("example expects stdout is open, error={}", e)) }) }).map(|_| { println!("\n\nDone."); diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -17,7 +17,8 @@ fn main() { let addr = ([127, 0, 0, 1], 3000).into(); let new_service = const_service(service_fn(|_| { - Ok(Response::new(Body::from(PHRASE))) + //TODO: when `!` is stable, replace error type + Ok::<_, hyper::Error>(Response::new(Body::from(PHRASE))) })); tokio::run(lazy(move || { diff --git a/examples/send_file.rs b/examples/send_file.rs --- a/examples/send_file.rs +++ b/examples/send_file.rs @@ -9,7 +9,6 @@ use futures::future::lazy; use futures::sync::oneshot; use hyper::{Body, /*Chunk,*/ Method, Request, Response, StatusCode}; -use hyper::error::Error; use hyper::server::{Http, Service}; use std::fs::File; diff --git a/examples/send_file.rs b/examples/send_file.rs --- a/examples/send_file.rs +++ b/examples/send_file.rs @@ -19,7 +18,7 @@ use std::thread; static NOTFOUND: &[u8] = b"Not Found"; static INDEX: &str = "examples/send_file_index.html"; -fn simple_file_send(f: &str) -> Box<Future<Item = Response<Body>, Error = hyper::Error> + Send> { +fn simple_file_send(f: &str) -> Box<Future<Item = Response<Body>, Error = io::Error> + Send> { // Serve a file by reading it entirely into memory. As a result // this is limited to serving small files, but it is somewhat // simpler with a little less overhead. diff --git a/examples/send_file.rs b/examples/send_file.rs --- a/examples/send_file.rs +++ b/examples/send_file.rs @@ -56,7 +55,7 @@ fn simple_file_send(f: &str) -> Box<Future<Item = Response<Body>, Error = hyper: }; }); - Box::new(rx.map_err(|e| Error::from(io::Error::new(io::ErrorKind::Other, e)))) + Box::new(rx.map_err(|e| io::Error::new(io::ErrorKind::Other, e))) } struct ResponseExamples; diff --git a/examples/send_file.rs b/examples/send_file.rs --- a/examples/send_file.rs +++ b/examples/send_file.rs @@ -64,7 +63,7 @@ struct ResponseExamples; impl Service for ResponseExamples { type Request = Request<Body>; type Response = Response<Body>; - type Error = hyper::Error; + type Error = io::Error; type Future = Box<Future<Item = Self::Response, Error = Self::Error> + Send>; fn call(&self, req: Request<Body>) -> Self::Future { diff --git a/examples/send_file.rs b/examples/send_file.rs --- a/examples/send_file.rs +++ b/examples/send_file.rs @@ -119,7 +118,7 @@ impl Service for ResponseExamples { */ }); - Box::new(rx.map_err(|e| Error::from(io::Error::new(io::ErrorKind::Other, e)))) + Box::new(rx.map_err(|e| io::Error::new(io::ErrorKind::Other, e))) }, (&Method::GET, "/no_file.html") => { // Test what happens when file cannot be be found diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -45,7 +45,7 @@ pub struct SendRequest<B> { pub struct Connection<T, B> where T: AsyncRead + AsyncWrite, - B: Entity<Error=::Error> + 'static, + B: Entity + 'static, { inner: proto::dispatch::Dispatcher< proto::dispatch::Client<B>, diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -138,7 +138,7 @@ impl<B> SendRequest<B> impl<B> SendRequest<B> where - B: Entity<Error=::Error> + 'static, + B: Entity + 'static, { /// Sends a `Request` on the associated connection. /// diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -262,7 +262,7 @@ impl<B> fmt::Debug for SendRequest<B> { impl<T, B> Connection<T, B> where T: AsyncRead + AsyncWrite, - B: Entity<Error=::Error> + 'static, + B: Entity + 'static, { /// Return the inner IO object, and additional information. pub fn into_parts(self) -> Parts<T> { diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -289,7 +289,7 @@ where impl<T, B> Future for Connection<T, B> where T: AsyncRead + AsyncWrite, - B: Entity<Error=::Error> + 'static, + B: Entity + 'static, { type Item = (); type Error = ::Error; diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -302,7 +302,7 @@ where impl<T, B> fmt::Debug for Connection<T, B> where T: AsyncRead + AsyncWrite + fmt::Debug, - B: Entity<Error=::Error> + 'static, + B: Entity + 'static, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Connection") diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -331,7 +331,7 @@ impl Builder { pub fn handshake<T, B>(&self, io: T) -> Handshake<T, B> where T: AsyncRead + AsyncWrite, - B: Entity<Error=::Error> + 'static, + B: Entity + 'static, { Handshake { inner: HandshakeInner { diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -345,7 +345,7 @@ impl Builder { pub(super) fn handshake_no_upgrades<T, B>(&self, io: T) -> HandshakeNoUpgrades<T, B> where T: AsyncRead + AsyncWrite, - B: Entity<Error=::Error> + 'static, + B: Entity + 'static, { HandshakeNoUpgrades { inner: HandshakeInner { diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -362,7 +362,7 @@ impl Builder { impl<T, B> Future for Handshake<T, B> where T: AsyncRead + AsyncWrite, - B: Entity<Error=::Error> + 'static, + B: Entity + 'static, { type Item = (SendRequest<B>, Connection<T, B>); type Error = ::Error; diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -387,7 +387,7 @@ impl<T, B> fmt::Debug for Handshake<T, B> { impl<T, B> Future for HandshakeNoUpgrades<T, B> where T: AsyncRead + AsyncWrite, - B: Entity<Error=::Error> + 'static, + B: Entity + 'static, { type Item = (SendRequest<B>, proto::dispatch::Dispatcher< proto::dispatch::Client<B>, diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -406,7 +406,7 @@ where impl<T, B, R> Future for HandshakeInner<T, B, R> where T: AsyncRead + AsyncWrite, - B: Entity<Error=::Error> + 'static, + B: Entity + 'static, R: proto::Http1Transaction< Incoming=StatusCode, Outgoing=proto::RequestLine, diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -470,7 +470,7 @@ impl<B: Send> AssertSendSync for SendRequest<B> {} impl<T: Send, B: Send> AssertSend for Connection<T, B> where T: AsyncRead + AsyncWrite, - B: Entity<Error=::Error> + 'static, + B: Entity + 'static, B::Data: Send + 'static, {} diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -478,7 +478,7 @@ where impl<T: Send + Sync, B: Send + Sync> AssertSendSync for Connection<T, B> where T: AsyncRead + AsyncWrite, - B: Entity<Error=::Error> + 'static, + B: Entity + 'static, B::Data: Send + Sync + 'static, {} diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -36,7 +36,7 @@ pub trait Connect: Send + Sync { /// The connected IO Stream. type Transport: AsyncRead + AsyncWrite + Send + 'static; /// An error occured when trying to connect. - type Error; + type Error: Into<Box<StdError + Send + Sync>>; /// A Future that will resolve to the connected Transport. type Future: Future<Item=(Self::Transport, Connected), Error=Self::Error> + Send; /// Connect to a destination. diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -39,10 +39,10 @@ impl<T, U> Sender<T, U> { // there's room in the queue, but does the Connection // want a message yet? self.giver.poll_want() - .map_err(|_| ::Error::Closed) + .map_err(|_| ::Error::new_closed()) }, Ok(Async::NotReady) => Ok(Async::NotReady), - Err(_) => Err(::Error::Closed), + Err(_) => Err(::Error::new_closed()), } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -96,10 +96,10 @@ impl<C, B> Client<C, B> { } impl<C, B> Client<C, B> -where C: Connect<Error=io::Error> + Sync + 'static, +where C: Connect + Sync + 'static, C::Transport: 'static, C::Future: 'static, - B: Entity<Error=::Error> + Send + 'static, + B: Entity + Send + 'static, B::Data: Send, { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -139,13 +139,14 @@ where C: Connect<Error=io::Error> + Sync + 'static, Version::HTTP_11 => (), other => { error!("Request has unsupported version \"{:?}\"", other); - return FutureResponse(Box::new(future::err(::Error::Version))); + //TODO: replace this with a proper variant + return FutureResponse(Box::new(future::err(::Error::new_user_unsupported_version()))); } } if req.method() == &Method::CONNECT { debug!("Client does not support CONNECT requests"); - return FutureResponse(Box::new(future::err(::Error::Method))); + return FutureResponse(Box::new(future::err(::Error::new_user_unsupported_request_method()))); } let uri = req.uri().clone(); diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -154,7 +155,8 @@ where C: Connect<Error=io::Error> + Sync + 'static, format!("{}://{}", scheme, auth) } _ => { - return FutureResponse(Box::new(future::err(::Error::Io( + //TODO: replace this with a proper variant + return FutureResponse(Box::new(future::err(::Error::new_io( io::Error::new( io::ErrorKind::InvalidInput, "invalid URI for Client Request" diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -203,13 +205,13 @@ where C: Connect<Error=io::Error> + Sync + 'static, }; future::lazy(move || { connector.connect(dst) - .from_err() + .map_err(::Error::new_connect) .and_then(move |(io, connected)| { conn::Builder::new() .h1_writev(h1_writev) .handshake_no_upgrades(io) .and_then(move |(tx, conn)| { - executor.execute(conn.map_err(|e| debug!("client connection error: {}", e)))?; + executor.execute(conn.map_err(|e| debug!("client connection error: {}", e))); Ok(pool.pooled(pool_key, PoolClient { is_proxied: connected.is_proxied, tx: tx, diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -260,9 +262,7 @@ where C: Connect<Error=io::Error> + Sync + 'static, } else if !res.body().is_empty() { let (delayed_tx, delayed_rx) = oneshot::channel(); res.body_mut().delayed_eof(delayed_rx); - // If the executor doesn't have room, oh well. Things will likely - // be blowing up soon, but this specific task isn't required. - let _ = executor.execute( + executor.execute( future::poll_fn(move || { pooled.tx.poll_ready() }) diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -277,7 +277,6 @@ where C: Connect<Error=io::Error> + Sync + 'static, Ok(res) }); - fut }); diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -290,9 +289,9 @@ where C: Connect<Error=io::Error> + Sync + 'static, } impl<C, B> Service for Client<C, B> -where C: Connect<Error=io::Error> + 'static, +where C: Connect + 'static, C::Future: 'static, - B: Entity<Error=::Error> + Send + 'static, + B: Entity + Send + 'static, B::Data: Send, { type Request = Request<B>; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -353,9 +352,9 @@ struct RetryableSendRequest<C, B> { impl<C, B> Future for RetryableSendRequest<C, B> where - C: Connect<Error=io::Error> + 'static, + C: Connect + 'static, C::Future: 'static, - B: Entity<Error=::Error> + Send + 'static, + B: Entity + Send + 'static, B::Data: Send, { type Item = Response<Body>; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -564,10 +563,10 @@ impl<C, B> Config<C, B> { } impl<C, B> Config<C, B> -where C: Connect<Error=io::Error>, +where C: Connect, C::Transport: 'static, C::Future: 'static, - B: Entity<Error=::Error> + Send, + B: Entity + Send, B::Data: Send, { /// Construct the Client with this configuration. diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -590,7 +589,7 @@ where C: Connect<Error=io::Error>, impl<B> Config<UseDefaultConnector, B> where - B: Entity<Error=::Error> + Send, + B: Entity + Send, B::Data: Send, { /// Construct the Client with this configuration. diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -640,7 +639,6 @@ impl<C: Clone, B> Clone for Config<C, B> { } } - // ===== impl Exec ===== #[derive(Clone)] diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -655,24 +653,19 @@ impl Exec { Exec::Executor(Arc::new(executor)) } - fn execute<F>(&self, fut: F) -> io::Result<()> + fn execute<F>(&self, fut: F) where F: Future<Item=(), Error=()> + Send + 'static, { match *self { Exec::Default => spawn(fut), Exec::Executor(ref e) => { - e.execute(bg(Box::new(fut))) + let _ = e.execute(bg(Box::new(fut))) .map_err(|err| { - debug!("executor error: {:?}", err.kind()); - io::Error::new( - io::ErrorKind::Other, - "executor error", - ) - })? + panic!("executor error: {:?}", err.kind()); + }); }, } - Ok(()) } } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -245,7 +245,7 @@ impl<T: Closed + Send + 'static> Pool<T> { interval: interval, pool: Arc::downgrade(&self.inner), pool_drop_notifier: rx, - }).unwrap(); + }); } } diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -1,188 +1,316 @@ //! Error and Result module. use std::error::Error as StdError; use std::fmt; -use std::io::Error as IoError; -use std::str::Utf8Error; -use std::string::FromUtf8Error; +use std::io; use httparse; use http; -use self::Error::{ - Method, - Version, - Uri, - Header, - Status, - Timeout, - Upgrade, - Closed, - Cancel, - Io, - TooLarge, - Incomplete, - Utf8 -}; - /// Result type often returned from methods that can have hyper `Error`s. pub type Result<T> = ::std::result::Result<T, Error>; -/// A set of errors that can occur parsing HTTP streams. -#[derive(Debug)] -pub enum Error { - /// An invalid `Method`, such as `GE,T`. - Method, - /// An invalid `HttpVersion`, such as `HTP/1.1` - Version, - /// Uri Errors - Uri, - /// An invalid `Header`. - Header, - /// A message head is too large to be reasonable. - TooLarge, +type Cause = Box<StdError + Send + Sync>; + +/// Represents errors that can occur handling HTTP streams. +pub struct Error { + inner: Box<ErrorImpl>, +} + +struct ErrorImpl { + kind: Kind, + cause: Option<Cause>, +} + +#[derive(Debug, PartialEq)] +pub(crate) enum Kind { + Parse(Parse), /// A message reached EOF, but is not complete. Incomplete, - /// An invalid `Status`, such as `1337 ELITE`. - Status, - /// A timeout occurred waiting for an IO event. - Timeout, /// A protocol upgrade was encountered, but not yet supported in hyper. Upgrade, + /// A client connection received a response when not waiting for one. + MismatchedResponse, /// A pending item was dropped before ever being processed. - Cancel(Canceled), + Canceled, /// Indicates a connection is closed. Closed, /// An `io::Error` that occurred while trying to read or write to a network stream. - Io(IoError), - /// Parsing a field as string failed - Utf8(Utf8Error), + Io, + /// Error occurred while connecting. + Connect, + /// Error creating a TcpListener. + Listen, + /// Error accepting on an Incoming stream. + Accept, + /// Error calling user's NewService::new_service(). + NewService, + /// Error from future of user's Service::call(). + Service, + /// Error while reading a body from connection. + Body, + /// Error while writing a body to connection. + BodyWrite, + /// Error calling user's Entity::poll_data(). + BodyUser, + /// Error calling AsyncWrite::shutdown() + Shutdown, - #[doc(hidden)] - __Nonexhaustive(Void) + /// User tried to create a Request with bad version. + UnsupportedVersion, + /// User tried to create a CONNECT Request with the Client. + UnsupportedRequestMethod, } -impl Error { - pub(crate) fn new_canceled<E: Into<Box<StdError + Send + Sync>>>(cause: Option<E>) -> Error { - Error::Cancel(Canceled { - cause: cause.map(Into::into), - }) - } +#[derive(Debug, PartialEq)] +pub(crate) enum Parse { + Method, + Version, + Uri, + Header, + TooLarge, + Status, } -/// A pending item was dropped before ever being processed. -/// -/// For example, a `Request` could be queued in the `Client`, *just* -/// as the related connection gets closed by the remote. In that case, -/// when the connection drops, the pending response future will be -/// fulfilled with this error, signaling the `Request` was never started. +/* #[derive(Debug)] -pub struct Canceled { - cause: Option<Box<StdError + Send + Sync>>, +pub(crate) enum User { + VersionNotSupported, + MethodNotSupported, + InvalidRequestUri, } +*/ -impl Canceled { - fn description(&self) -> &str { - "an operation was canceled internally before starting" +impl Error { + //TODO(error): should there be these kinds of inspection methods? + // + // - is_io() + // - is_connect() + // - is_closed() + // - etc? + + /// Returns true if this was an HTTP parse error. + pub fn is_parse(&self) -> bool { + match self.inner.kind { + Kind::Parse(_) => true, + _ => false, + } } -} -impl fmt::Display for Canceled { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad(self.description()) + /// Returns true if this error was caused by user code. + pub fn is_user(&self) -> bool { + match self.inner.kind { + Kind::BodyUser | + Kind::NewService | + Kind::Service | + Kind::Closed | + Kind::UnsupportedVersion | + Kind::UnsupportedRequestMethod => true, + _ => false, + } } -} -#[doc(hidden)] -pub struct Void(()); + /// Returns true if this was about a `Request` that was canceled. + pub fn is_canceled(&self) -> bool { + self.inner.kind == Kind::Canceled + } -impl fmt::Debug for Void { - fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { - unreachable!() + /// Returns true if a sender's channel is closed. + pub fn is_closed(&self) -> bool { + self.inner.kind == Kind::Closed + } + + pub(crate) fn new(kind: Kind, cause: Option<Cause>) -> Error { + Error { + inner: Box::new(ErrorImpl { + kind, + cause, + }), + } + } + + pub(crate) fn kind(&self) -> &Kind { + &self.inner.kind + } + + pub(crate) fn new_canceled<E: Into<Cause>>(cause: Option<E>) -> Error { + Error::new(Kind::Canceled, cause.map(Into::into)) + } + + pub(crate) fn new_upgrade() -> Error { + Error::new(Kind::Upgrade, None) + } + + pub(crate) fn new_incomplete() -> Error { + Error::new(Kind::Incomplete, None) + } + + pub(crate) fn new_too_large() -> Error { + Error::new(Kind::Parse(Parse::TooLarge), None) + } + + pub(crate) fn new_header() -> Error { + Error::new(Kind::Parse(Parse::Header), None) + } + + pub(crate) fn new_status() -> Error { + Error::new(Kind::Parse(Parse::Status), None) + } + + pub(crate) fn new_version() -> Error { + Error::new(Kind::Parse(Parse::Version), None) + } + + pub(crate) fn new_mismatched_response() -> Error { + Error::new(Kind::MismatchedResponse, None) + } + + pub(crate) fn new_io(cause: io::Error) -> Error { + Error::new(Kind::Io, Some(cause.into())) + } + + pub(crate) fn new_listen(err: io::Error) -> Error { + Error::new(Kind::Listen, Some(err.into())) + } + + pub(crate) fn new_accept(err: io::Error) -> Error { + Error::new(Kind::Accept, Some(Box::new(err))) + } + + pub(crate) fn new_connect<E: Into<Cause>>(cause: E) -> Error { + Error::new(Kind::Connect, Some(cause.into())) + } + + pub(crate) fn new_closed() -> Error { + Error::new(Kind::Closed, None) + } + + pub(crate) fn new_body<E: Into<Cause>>(cause: E) -> Error { + Error::new(Kind::Body, Some(cause.into())) + } + + pub(crate) fn new_body_write(cause: io::Error) -> Error { + Error::new(Kind::BodyWrite, Some(Box::new(cause))) + } + + pub(crate) fn new_user_unsupported_version() -> Error { + Error::new(Kind::UnsupportedVersion, None) + } + + pub(crate) fn new_user_unsupported_request_method() -> Error { + Error::new(Kind::UnsupportedRequestMethod, None) + } + + pub(crate) fn new_user_new_service(err: io::Error) -> Error { + Error::new(Kind::NewService, Some(Box::new(err))) + } + + pub(crate) fn new_user_service<E: Into<Cause>>(cause: E) -> Error { + Error::new(Kind::Service, Some(cause.into())) + } + + pub(crate) fn new_user_body<E: Into<Cause>>(cause: E) -> Error { + Error::new(Kind::BodyUser, Some(cause.into())) + } + + pub(crate) fn new_shutdown(cause: io::Error) -> Error { + Error::new(Kind::Shutdown, Some(Box::new(cause))) + } +} + +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Error") + .field("kind", &self.inner.kind) + .field("cause", &self.inner.cause) + .finish() } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Io(ref e) => fmt::Display::fmt(e, f), - Utf8(ref e) => fmt::Display::fmt(e, f), - ref e => f.write_str(e.description()), + if let Some(ref cause) = self.inner.cause { + write!(f, "{}: {}", self.description(), cause) + } else { + f.write_str(self.description()) } } } impl StdError for Error { fn description(&self) -> &str { - match *self { - Method => "invalid Method specified", - Version => "invalid HTTP version specified", - Uri => "invalid URI", - Header => "invalid Header provided", - TooLarge => "message head is too large", - Status => "invalid Status provided", - Incomplete => "message is incomplete", - Timeout => "timeout", - Upgrade => "unsupported protocol upgrade", - Closed => "connection is closed", - Cancel(ref e) => e.description(), - Io(ref e) => e.description(), - Utf8(ref e) => e.description(), - Error::__Nonexhaustive(..) => unreachable!(), - } - } + match self.inner.kind { + Kind::Parse(Parse::Method) => "invalid Method specified", + Kind::Parse(Parse::Version) => "invalid HTTP version specified", + Kind::Parse(Parse::Uri) => "invalid URI", + Kind::Parse(Parse::Header) => "invalid Header provided", + Kind::Parse(Parse::TooLarge) => "message head is too large", + Kind::Parse(Parse::Status) => "invalid Status provided", + Kind::Incomplete => "message is incomplete", + Kind::Upgrade => "unsupported protocol upgrade", + Kind::MismatchedResponse => "response received without matching request", + Kind::Closed => "connection closed", + Kind::Connect => "an error occurred trying to connect", + Kind::Canceled => "an operation was canceled internally before starting", + Kind::Listen => "error creating server listener", + Kind::Accept => "error accepting connection", + Kind::NewService => "calling user's new_service failed", + Kind::Service => "error from user's server service", + Kind::Body => "error reading a body from connection", + Kind::BodyWrite => "error write a body to connection", + Kind::BodyUser => "error from user's Entity stream", + Kind::Shutdown => "error shutting down connection", + Kind::UnsupportedVersion => "request has unsupported HTTP version", + Kind::UnsupportedRequestMethod => "request has unsupported HTTP method", - fn cause(&self) -> Option<&StdError> { - match *self { - Io(ref error) => Some(error), - Utf8(ref error) => Some(error), - Cancel(ref e) => e.cause.as_ref().map(|e| &**e as &StdError), - Error::__Nonexhaustive(..) => unreachable!(), - _ => None, + Kind::Io => "an IO error occurred", } } -} -impl From<IoError> for Error { - fn from(err: IoError) -> Error { - Io(err) - } -} - -impl From<Utf8Error> for Error { - fn from(err: Utf8Error) -> Error { - Utf8(err) + fn cause(&self) -> Option<&StdError> { + self + .inner + .cause + .as_ref() + .map(|cause| &**cause as &StdError) } } -impl From<FromUtf8Error> for Error { - fn from(err: FromUtf8Error) -> Error { - Utf8(err.utf8_error()) +#[doc(hidden)] +impl From<Parse> for Error { + fn from(err: Parse) -> Error { + Error::new(Kind::Parse(err), None) } } -impl From<httparse::Error> for Error { - fn from(err: httparse::Error) -> Error { +impl From<httparse::Error> for Parse { + fn from(err: httparse::Error) -> Parse { match err { httparse::Error::HeaderName | httparse::Error::HeaderValue | httparse::Error::NewLine | - httparse::Error::Token => Header, - httparse::Error::Status => Status, - httparse::Error::TooManyHeaders => TooLarge, - httparse::Error::Version => Version, + httparse::Error::Token => Parse::Header, + httparse::Error::Status => Parse::Status, + httparse::Error::TooManyHeaders => Parse::TooLarge, + httparse::Error::Version => Parse::Version, } } } -impl From<http::method::InvalidMethod> for Error { - fn from(_: http::method::InvalidMethod) -> Error { - Error::Method +impl From<http::method::InvalidMethod> for Parse { + fn from(_: http::method::InvalidMethod) -> Parse { + Parse::Method + } +} + +impl From<http::status::InvalidStatusCode> for Parse { + fn from(_: http::status::InvalidStatusCode) -> Parse { + Parse::Status } } -impl From<http::uri::InvalidUriBytes> for Error { - fn from(_: http::uri::InvalidUriBytes) -> Error { - Error::Uri +impl From<http::uri::InvalidUriBytes> for Parse { + fn from(_: http::uri::InvalidUriBytes) -> Parse { + Parse::Uri } } diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -18,8 +18,7 @@ pub trait Entity { type Data: AsRef<[u8]>; /// The error type of this stream. - //TODO: add bounds Into<::error::User> (or whatever it is called) - type Error; + type Error: Into<Box<::std::error::Error + Send + Sync>>; /// Poll for a `Data` buffer. /// diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -141,7 +140,7 @@ enum Kind { _close_tx: oneshot::Sender<()>, rx: mpsc::Receiver<Result<Chunk, ::Error>>, }, - Wrapped(Box<Stream<Item=Chunk, Error=::Error> + Send>), + Wrapped(Box<Stream<Item=Chunk, Error=Box<::std::error::Error + Send + Sync>> + Send>), Once(Option<Chunk>), Empty, } diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -212,17 +211,22 @@ impl Body { /// " ", /// "world", /// ]; - /// let stream = futures::stream::iter_ok(chunks); + /// + /// let stream = futures::stream::iter_ok::<_, ::std::io::Error>(chunks); /// /// let body = Body::wrap_stream(stream); /// # } /// ``` pub fn wrap_stream<S>(stream: S) -> Body where - S: Stream<Error=::Error> + Send + 'static, + S: Stream + Send + 'static, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, Chunk: From<S::Item>, { - Body::new(Kind::Wrapped(Box::new(stream.map(Chunk::from)))) + let mapped = stream + .map(Chunk::from) + .map_err(Into::into); + Body::new(Kind::Wrapped(Box::new(mapped))) } /// Convert this `Body` into a `Stream<Item=Chunk, Error=hyper::Error>`. diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -327,7 +331,7 @@ impl Body { Async::Ready(None) => Ok(Async::Ready(None)), Async::NotReady => Ok(Async::NotReady), }, - Kind::Wrapped(ref mut s) => s.poll(), + Kind::Wrapped(ref mut s) => s.poll().map_err(::Error::new_body), Kind::Once(ref mut val) => Ok(Async::Ready(val.take())), Kind::Empty => Ok(Async::Ready(None)), } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -20,7 +20,7 @@ use super::{EncodedBuf, Encoder, Decoder}; /// The connection will determine when a message begins and ends as well as /// determine if this connection can be kept alive after the message, /// or if it is complete. -pub struct Conn<I, B, T> { +pub(crate) struct Conn<I, B, T> { io: Buffered<I, EncodedBuf<Cursor<B>>>, state: State, _marker: PhantomData<T> diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -146,7 +146,8 @@ where I: AsyncRead + AsyncWrite, _ => { error!("unimplemented HTTP Version = {:?}", version); self.state.close_read(); - return Err(::Error::Version); + //TODO: replace this with a more descriptive error + return Err(::Error::new_version()); } }; self.state.version = version; diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -245,7 +246,7 @@ where I: AsyncRead + AsyncWrite, if self.is_mid_message() { self.maybe_park_read(); } else { - self.require_empty_read()?; + self.require_empty_read().map_err(::Error::new_io)?; } Ok(()) } diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -1,5 +1,3 @@ -use std::io; - use bytes::Bytes; use futures::{Async, Future, Poll, Stream}; use http::{Request, Response, StatusCode}; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -9,7 +7,7 @@ use tokio_service::Service; use proto::body::Entity; use proto::{Body, BodyLength, Conn, Http1Transaction, MessageHead, RequestHead, RequestLine, ResponseHead}; -pub struct Dispatcher<D, Bs, I, B, T> { +pub(crate) struct Dispatcher<D, Bs, I, B, T> { conn: Conn<I, B, T>, dispatch: D, body_tx: Option<::proto::body::Sender>, diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -17,7 +15,7 @@ pub struct Dispatcher<D, Bs, I, B, T> { is_closing: bool, } -pub trait Dispatch { +pub(crate) trait Dispatch { type PollItem; type PollBody; type RecvItem; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -47,7 +45,7 @@ where I: AsyncRead + AsyncWrite, B: AsRef<[u8]>, T: Http1Transaction, - Bs: Entity<Data=B, Error=::Error>, + Bs: Entity<Data=B>, { pub fn new(dispatch: D, conn: Conn<I, B, T>) -> Self { Dispatcher { diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -98,7 +96,7 @@ where if self.is_done() { if should_shutdown { - try_ready!(self.conn.shutdown()); + try_ready!(self.conn.shutdown().map_err(::Error::new_shutdown)); } self.conn.take_error()?; Ok(Async::Ready(())) diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -152,7 +150,7 @@ where return Ok(Async::NotReady); } Err(e) => { - body.send_error(::Error::Io(e)); + body.send_error(::Error::new_body(e)); } } } else { diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -225,14 +223,14 @@ where } else if !self.conn.can_buffer_body() { try_ready!(self.poll_flush()); } else if let Some(mut body) = self.body_rx.take() { - let chunk = match body.poll_data()? { + let chunk = match body.poll_data().map_err(::Error::new_user_body)? { Async::Ready(Some(chunk)) => { self.body_rx = Some(body); chunk }, Async::Ready(None) => { if self.conn.can_write_body() { - self.conn.write_body(None)?; + self.conn.write_body(None).map_err(::Error::new_body_write)?; } continue; }, diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -243,7 +241,7 @@ where }; if self.conn.can_write_body() { - assert!(self.conn.write_body(Some(chunk))?.is_ready()); + self.conn.write_body(Some(chunk)).map_err(::Error::new_body_write)?; // This allows when chunk is `None`, or `Some([])`. } else if chunk.as_ref().len() == 0 { // ok diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -259,7 +257,7 @@ where fn poll_flush(&mut self) -> Poll<(), ::Error> { self.conn.flush().map_err(|err| { debug!("error writing: {}", err); - err.into() + ::Error::new_body_write(err) }) } diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -294,7 +292,7 @@ where I: AsyncRead + AsyncWrite, B: AsRef<[u8]>, T: Http1Transaction, - Bs: Entity<Data=B, Error=::Error>, + Bs: Entity<Data=B>, { type Item = (); type Error = ::Error; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -318,8 +316,9 @@ impl<S> Server<S> where S: Service { impl<S, Bs> Dispatch for Server<S> where - S: Service<Request=Request<Body>, Response=Response<Bs>, Error=::Error>, - Bs: Entity<Error=::Error>, + S: Service<Request=Request<Body>, Response=Response<Bs>>, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + Bs: Entity, { type PollItem = MessageHead<StatusCode>; type PollBody = Bs; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -327,7 +326,7 @@ where fn poll_msg(&mut self) -> Poll<Option<(Self::PollItem, Option<Self::PollBody>)>, ::Error> { if let Some(mut fut) = self.in_flight.take() { - let resp = match fut.poll()? { + let resp = match fut.poll().map_err(::Error::new_user_service)? { Async::Ready(res) => res, Async::NotReady => { self.in_flight = Some(fut); diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -389,7 +388,7 @@ impl<B> Client<B> { impl<B> Dispatch for Client<B> where - B: Entity<Error=::Error>, + B: Entity, { type PollItem = RequestHead; type PollBody = B; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -443,7 +442,7 @@ where let _ = cb.send(Ok(res)); Ok(()) } else { - Err(::Error::Io(io::Error::new(io::ErrorKind::InvalidData, "response received without matching request"))) + Err(::Error::new_mismatched_response()) } }, Err(err) => { diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -108,7 +108,7 @@ where } } - pub fn parse<S: Http1Transaction>(&mut self) -> Poll<MessageHead<S::Incoming>, ::Error> { + pub(super) fn parse<S: Http1Transaction>(&mut self) -> Poll<MessageHead<S::Incoming>, ::Error> { loop { match try!(S::parse(&mut self.read_buf)) { Some((head, len)) => { diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -118,14 +118,14 @@ where None => { if self.read_buf.capacity() >= self.max_buf_size { debug!("max_buf_size ({}) reached, closing", self.max_buf_size); - return Err(::Error::TooLarge); + return Err(::Error::new_too_large()); } }, } - match try_ready!(self.read_from_io()) { + match try_ready!(self.read_from_io().map_err(::Error::new_io)) { 0 => { trace!("parse eof"); - return Err(::Error::Incomplete); + return Err(::Error::new_incomplete()); } _ => {}, } diff --git a/src/proto/h1/mod.rs b/src/proto/h1/mod.rs --- a/src/proto/h1/mod.rs +++ b/src/proto/h1/mod.rs @@ -1,11 +1,11 @@ -pub use self::conn::Conn; +pub(crate) use self::conn::Conn; pub use self::decode::Decoder; pub use self::encode::{EncodedBuf, Encoder}; mod conn; mod date; mod decode; -pub mod dispatch; +pub(crate) mod dispatch; mod encode; mod io; pub mod role; diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -40,7 +40,7 @@ where let mut headers = [httparse::EMPTY_HEADER; MAX_HEADERS]; trace!("Request.parse([Header; {}], [u8; {}])", headers.len(), buf.len()); let mut req = httparse::Request::new(&mut headers); - match try!(req.parse(&buf)) { + match req.parse(&buf)? { httparse::Status::Complete(len) => { trace!("Request.parse Complete({})", len); let method = Method::from_bytes(req.method.unwrap().as_bytes())?; diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -104,18 +104,18 @@ where // mal-formed. A server should respond with 400 Bad Request. if head.version == Version::HTTP_10 { debug!("HTTP/1.0 cannot have Transfer-Encoding header"); - Err(::Error::Header) + Err(::Error::new_header()) } else if headers::transfer_encoding_is_chunked(&head.headers) { Ok(Decode::Normal(Decoder::chunked())) } else { debug!("request with transfer-encoding header, but not chunked, bad request"); - Err(::Error::Header) + Err(::Error::new_header()) } } else if let Some(len) = headers::content_length_parse(&head.headers) { Ok(Decode::Normal(Decoder::length(len))) } else if head.headers.contains_key(CONTENT_LENGTH) { debug!("illegal Content-Length header"); - Err(::Error::Header) + Err(::Error::new_header()) } else { Ok(Decode::Normal(Decoder::length(0))) } diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -146,7 +146,8 @@ where head = MessageHead::default(); head.subject = StatusCode::INTERNAL_SERVER_ERROR; headers::content_length_zero(&mut head.headers); - Err(::Error::Status) + //TODO: change this to a more descriptive error than just a parse error + Err(::Error::new_status()) } else { Ok(Server::set_length(&mut head, body, method.as_ref())) }; diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -184,14 +185,15 @@ where } fn on_error(err: &::Error) -> Option<MessageHead<Self::Outgoing>> { - let status = match err { - &::Error::Method | - &::Error::Version | - &::Error::Header /*| - &::Error::Uri(_)*/ => { + use ::error::{Kind, Parse}; + let status = match *err.kind() { + Kind::Parse(Parse::Method) | + Kind::Parse(Parse::Version) | + Kind::Parse(Parse::Header) | + Kind::Parse(Parse::Uri) => { StatusCode::BAD_REQUEST }, - &::Error::TooLarge => { + Kind::Parse(Parse::TooLarge) => { StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE } _ => return None, diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -271,7 +273,7 @@ where match try!(res.parse(bytes)) { httparse::Status::Complete(len) => { trace!("Response.parse Complete({})", len); - let status = try!(StatusCode::from_u16(res.code.unwrap()).map_err(|_| ::Error::Status)); + let status = StatusCode::from_u16(res.code.unwrap())?; let version = if res.version.unwrap() == 1 { Version::HTTP_11 } else { diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -343,7 +345,7 @@ where // mal-formed. A server should respond with 400 Bad Request. if inc.version == Version::HTTP_10 { debug!("HTTP/1.0 cannot have Transfer-Encoding header"); - Err(::Error::Header) + Err(::Error::new_header()) } else if headers::transfer_encoding_is_chunked(&inc.headers) { Ok(Decode::Normal(Decoder::chunked())) } else { diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -354,7 +356,7 @@ where Ok(Decode::Normal(Decoder::length(len))) } else if inc.headers.contains_key(CONTENT_LENGTH) { debug!("illegal Content-Length header"); - Err(::Error::Header) + Err(::Error::new_header()) } else { trace!("neither Transfer-Encoding nor Content-Length"); Ok(Decode::Normal(Decoder::eof())) diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -577,12 +579,13 @@ impl OnUpgrade for NoUpgrades { *head = MessageHead::default(); head.subject = ::StatusCode::INTERNAL_SERVER_ERROR; headers::content_length_zero(&mut head.headers); - Err(::Error::Status) + //TODO: replace with more descriptive error + return Err(::Error::new_status()); } fn on_decode_upgrade() -> ::Result<Decoder> { debug!("received 101 upgrade response, not supported"); - return Err(::Error::Upgrade); + return Err(::Error::new_upgrade()); } } diff --git a/src/proto/mod.rs b/src/proto/mod.rs --- a/src/proto/mod.rs +++ b/src/proto/mod.rs @@ -6,7 +6,7 @@ use headers; pub use self::body::Body; pub use self::chunk::Chunk; -pub use self::h1::{dispatch, Conn}; +pub(crate) use self::h1::{dispatch, Conn}; pub mod body; mod chunk; diff --git a/src/proto/mod.rs b/src/proto/mod.rs --- a/src/proto/mod.rs +++ b/src/proto/mod.rs @@ -60,14 +60,14 @@ pub fn expecting_continue(version: Version, headers: &HeaderMap) -> bool { version == Version::HTTP_11 && headers::expect_continue(headers) } -pub type ServerTransaction = h1::role::Server<h1::role::YesUpgrades>; +pub(crate) type ServerTransaction = h1::role::Server<h1::role::YesUpgrades>; //pub type ServerTransaction = h1::role::Server<h1::role::NoUpgrades>; //pub type ServerUpgradeTransaction = h1::role::Server<h1::role::YesUpgrades>; -pub type ClientTransaction = h1::role::Client<h1::role::NoUpgrades>; -pub type ClientUpgradeTransaction = h1::role::Client<h1::role::YesUpgrades>; +pub(crate) type ClientTransaction = h1::role::Client<h1::role::NoUpgrades>; +pub(crate) type ClientUpgradeTransaction = h1::role::Client<h1::role::YesUpgrades>; -pub trait Http1Transaction { +pub(crate) trait Http1Transaction { type Incoming; type Outgoing: Default; fn parse(bytes: &mut BytesMut) -> ParseResult<Self::Incoming>; diff --git a/src/proto/mod.rs b/src/proto/mod.rs --- a/src/proto/mod.rs +++ b/src/proto/mod.rs @@ -84,7 +84,7 @@ pub trait Http1Transaction { fn should_read_first() -> bool; } -pub type ParseResult<T> = ::Result<Option<(MessageHead<T>, usize)>>; +pub(crate) type ParseResult<T> = Result<Option<(MessageHead<T>, usize)>, ::error::Parse>; #[derive(Debug)] pub enum BodyLength { diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -25,7 +25,7 @@ use super::{HyperService, Request, Response, Service}; pub struct Connection<I, S> where S: HyperService, - S::ResponseBody: Entity<Error=::Error>, + S::ResponseBody: Entity, { pub(super) conn: proto::dispatch::Dispatcher< proto::dispatch::Server<S>, diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -59,9 +59,11 @@ pub struct Parts<T> { // ===== impl Connection ===== impl<I, B, S> Connection<I, S> -where S: Service<Request = Request<Body>, Response = Response<B>, Error = ::Error> + 'static, - I: AsyncRead + AsyncWrite + 'static, - B: Entity<Error=::Error> + 'static, +where + S: Service<Request=Request<Body>, Response=Response<B>> + 'static, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + I: AsyncRead + AsyncWrite + 'static, + B: Entity + 'static, { /// Disables keep-alive for this connection. pub fn disable_keep_alive(&mut self) { diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -96,9 +98,11 @@ where S: Service<Request = Request<Body>, Response = Response<B>, Error = ::Erro } impl<I, B, S> Future for Connection<I, S> -where S: Service<Request = Request<Body>, Response = Response<B>, Error = ::Error> + 'static, - I: AsyncRead + AsyncWrite + 'static, - B: Entity<Error=::Error> + 'static, +where + S: Service<Request=Request<Body>, Response=Response<B>> + 'static, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + I: AsyncRead + AsyncWrite + 'static, + B: Entity + 'static, { type Item = (); type Error = ::Error; diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -111,7 +115,7 @@ where S: Service<Request = Request<Body>, Response = Response<B>, Error = ::Erro impl<I, S> fmt::Debug for Connection<I, S> where S: HyperService, - S::ResponseBody: Entity<Error=::Error>, + S::ResponseBody: Entity, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Connection") diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -51,7 +51,7 @@ pub struct Http<B = ::Chunk> { /// address and then serving TCP connections accepted with the service provided. pub struct Server<S, B> where - B: Entity<Error=::Error>, + B: Entity, { protocol: Http<B::Data>, new_service: S, diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -165,12 +165,14 @@ impl<B: AsRef<[u8]> + 'static> Http<B> { /// The returned `Server` contains one method, `run`, which is used to /// actually run the server. pub fn bind<S, Bd>(&self, addr: &SocketAddr, new_service: S) -> ::Result<Server<S, Bd>> - where S: NewService<Request = Request<Body>, Response = Response<Bd>, Error = ::Error> + 'static, - Bd: Entity<Data=B, Error=::Error>, + where + S: NewService<Request=Request<Body>, Response=Response<Bd>> + 'static, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + Bd: Entity<Data=B>, { let handle = Handle::current(); - let std_listener = StdTcpListener::bind(addr)?; - let listener = try!(TcpListener::from_std(std_listener, &handle)); + let std_listener = StdTcpListener::bind(addr).map_err(::Error::new_listen)?; + let listener = TcpListener::from_std(std_listener, &handle).map_err(::Error::new_listen)?; Ok(Server { new_service: new_service, diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -188,13 +190,15 @@ impl<B: AsRef<[u8]> + 'static> Http<B> { /// `new_service` object provided as well, creating a new service per /// connection. pub fn serve_addr<S, Bd>(&self, addr: &SocketAddr, new_service: S) -> ::Result<Serve<AddrIncoming, S>> - where S: NewService<Request = Request<Body>, Response = Response<Bd>, Error = ::Error>, - Bd: Entity<Data=B, Error=::Error>, + where + S: NewService<Request=Request<Body>, Response=Response<Bd>>, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + Bd: Entity<Data=B>, { let handle = Handle::current(); - let std_listener = StdTcpListener::bind(addr)?; - let listener = TcpListener::from_std(std_listener, &handle)?; - let mut incoming = AddrIncoming::new(listener, handle.clone(), self.sleep_on_errors)?; + let std_listener = StdTcpListener::bind(addr).map_err(::Error::new_listen)?; + let listener = TcpListener::from_std(std_listener, &handle).map_err(::Error::new_listen)?; + let mut incoming = AddrIncoming::new(listener, handle.clone(), self.sleep_on_errors).map_err(::Error::new_listen)?; if self.keep_alive { incoming.set_keepalive(Some(Duration::from_secs(90))); } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -210,12 +214,15 @@ impl<B: AsRef<[u8]> + 'static> Http<B> { /// `new_service` object provided as well, creating a new service per /// connection. pub fn serve_addr_handle<S, Bd>(&self, addr: &SocketAddr, handle: &Handle, new_service: S) -> ::Result<Serve<AddrIncoming, S>> - where S: NewService<Request = Request<Body>, Response = Response<Bd>, Error = ::Error>, - Bd: Entity<Data=B, Error=::Error>, + where + S: NewService<Request = Request<Body>, Response = Response<Bd>>, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + Bd: Entity<Data=B>, { - let std_listener = StdTcpListener::bind(addr)?; - let listener = TcpListener::from_std(std_listener, &handle)?; - let mut incoming = AddrIncoming::new(listener, handle.clone(), self.sleep_on_errors)?; + let std_listener = StdTcpListener::bind(addr).map_err(::Error::new_listen)?; + let listener = TcpListener::from_std(std_listener, &handle).map_err(::Error::new_listen)?; + let mut incoming = AddrIncoming::new(listener, handle.clone(), self.sleep_on_errors).map_err(::Error::new_listen)?; + if self.keep_alive { incoming.set_keepalive(Some(Duration::from_secs(90))); } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -226,10 +233,12 @@ impl<B: AsRef<[u8]> + 'static> Http<B> { /// /// This method allows the ability to share a `Core` with multiple servers. pub fn serve_incoming<I, S, Bd>(&self, incoming: I, new_service: S) -> Serve<I, S> - where I: Stream<Error=::std::io::Error>, - I::Item: AsyncRead + AsyncWrite, - S: NewService<Request = Request<Body>, Response = Response<Bd>, Error = ::Error>, - Bd: Entity<Data=B, Error=::Error>, + where + I: Stream<Error=::std::io::Error>, + I::Item: AsyncRead + AsyncWrite, + S: NewService<Request = Request<Body>, Response = Response<Bd>>, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + Bd: Entity<Data=B>, { Serve { incoming: incoming, diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -279,9 +288,11 @@ impl<B: AsRef<[u8]> + 'static> Http<B> { /// # fn main() {} /// ``` pub fn serve_connection<S, I, Bd>(&self, io: I, service: S) -> Connection<I, S> - where S: Service<Request = Request<Body>, Response = Response<Bd>, Error = ::Error>, - Bd: Entity<Error=::Error>, - I: AsyncRead + AsyncWrite, + where + S: Service<Request = Request<Body>, Response = Response<Bd>>, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + Bd: Entity, + I: AsyncRead + AsyncWrite, { let mut conn = proto::Conn::new(io); if !self.keep_alive { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -341,15 +352,19 @@ impl Future for Run { impl<S, B> Server<S, B> - where S: NewService<Request = Request<Body>, Response = Response<B>, Error = ::Error> + Send + 'static, - <S as NewService>::Instance: Send, - <<S as NewService>::Instance as Service>::Future: Send, - B: Entity<Error=::Error> + Send + 'static, - B::Data: Send, +where + S: NewService<Request = Request<Body>, Response = Response<B>> + Send + 'static, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + <S as NewService>::Instance: Send, + <<S as NewService>::Instance as Service>::Future: Send, + B: Entity + Send + 'static, + B::Data: Send, { /// Returns the local address that this server is bound to. pub fn local_addr(&self) -> ::Result<SocketAddr> { - Ok(try!(self.listener.local_addr())) + //TODO: this shouldn't return an error at all, but should get the + //local_addr at construction + self.listener.local_addr().map_err(::Error::new_io) } /// Configure the amount of time this server will wait for a "graceful diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -393,7 +408,7 @@ impl<S, B> Server<S, B> let mut incoming = match AddrIncoming::new(listener, handle.clone(), protocol.sleep_on_errors) { Ok(incoming) => incoming, - Err(err) => return Run(Box::new(future::err(err.into()))), + Err(err) => return Run(Box::new(future::err(::Error::new_listen(err)))), }; if protocol.keep_alive { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -439,7 +454,7 @@ impl<S, B> Server<S, B> let main_execution = shutdown_signal.select(srv).then(move |result| { match result { Ok(((), _incoming)) => {}, - Err((e, _other)) => return future::Either::A(future::err(e.into())) + Err((e, _other)) => return future::Either::A(future::err(::Error::new_accept(e))), } // Ok we've stopped accepting new connections at this point, but we want diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -454,7 +469,8 @@ impl<S, B> Server<S, B> future::Either::B(wait.select(timeout).then(|result| { match result { Ok(_) => Ok(()), - Err((e, _)) => Err(e.into()) + //TODO: error variant should be "timed out waiting for graceful shutdown" + Err((e, _)) => Err(::Error::new_io(e)) } })) }); diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -463,11 +479,10 @@ impl<S, B> Server<S, B> } } -impl<S: fmt::Debug, B: Entity<Error=::Error>> fmt::Debug for Server<S, B> +impl<S: fmt::Debug, B: Entity> fmt::Debug for Server<S, B> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Server") - .field("reactor", &"...") .field("listener", &self.listener) .field("new_service", &self.new_service) .field("protocol", &self.protocol) diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -499,15 +514,16 @@ impl<I, S, B> Stream for Serve<I, S> where I: Stream<Error=io::Error>, I::Item: AsyncRead + AsyncWrite, - S: NewService<Request=Request<Body>, Response=Response<B>, Error=::Error>, - B: Entity<Error=::Error>, + S: NewService<Request=Request<Body>, Response=Response<B>>, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + B: Entity, { type Item = Connection<I::Item, S::Instance>; type Error = ::Error; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { - if let Some(io) = try_ready!(self.incoming.poll()) { - let service = self.new_service.new_service()?; + if let Some(io) = try_ready!(self.incoming.poll().map_err(::Error::new_accept)) { + let service = self.new_service.new_service().map_err(::Error::new_user_new_service)?; Ok(Async::Ready(Some(self.protocol.serve_connection(io, service)))) } else { Ok(Async::Ready(None)) diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -579,6 +595,12 @@ impl AddrIncoming { fn set_keepalive(&mut self, dur: Option<Duration>) { self.keep_alive_timeout = dur; } + + /* + fn set_sleep_on_errors(&mut self, val: bool) { + self.sleep_on_errors = val; + } + */ } impl Stream for AddrIncoming { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -802,9 +824,9 @@ mod hyper_service { S: Service< Request=Request<Body>, Response=Response<B>, - Error=::Error, >, - B: Entity<Error=::Error>, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, + B: Entity, {} impl<S, B> HyperService for S diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -812,10 +834,10 @@ mod hyper_service { S: Service< Request=Request<Body>, Response=Response<B>, - Error=::Error, >, + S::Error: Into<Box<::std::error::Error + Send + Sync>>, S: Sealed, - B: Entity<Error=::Error>, + B: Entity, { type ResponseBody = B; type Sealed = Opaque;
diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -78,7 +78,7 @@ fn throughput_fixedsize_large_payload(b: &mut test::Bencher) { fn throughput_fixedsize_many_chunks(b: &mut test::Bencher) { bench_server!(b, ("content-length", "1000000"), || { static S: &'static [&'static [u8]] = &[&[b'x'; 1_000] as &[u8]; 1_000] as _; - Body::wrap_stream(stream::iter_ok(S.iter()).map(|&s| s)) + Body::wrap_stream(stream::iter_ok::<_, String>(S.iter()).map(|&s| s)) }) } diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -96,7 +96,7 @@ fn throughput_chunked_large_payload(b: &mut test::Bencher) { fn throughput_chunked_many_chunks(b: &mut test::Bencher) { bench_server!(b, ("transfer-encoding", "chunked"), || { static S: &'static [&'static [u8]] = &[&[b'x'; 1_000] as &[u8]; 1_000] as _; - Body::wrap_stream(stream::iter_ok(S.iter()).map(|&s| s)) + Body::wrap_stream(stream::iter_ok::<_, String>(S.iter()).map(|&s| s)) }) } diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -184,9 +184,12 @@ mod tests { drop(rx); promise.then(|fulfilled| { - let res = fulfilled.expect("fulfilled"); - match res.unwrap_err() { - (::Error::Cancel(_), Some(_)) => (), + let err = fulfilled + .expect("fulfilled") + .expect_err("promise should error"); + + match (err.0.kind(), err.1) { + (&::error::Kind::Canceled, Some(_)) => (), e => panic!("expected Error::Cancel(_), found {:?}", e), } diff --git a/src/client/tests.rs b/src/client/tests.rs --- a/src/client/tests.rs +++ b/src/client/tests.rs @@ -35,7 +35,7 @@ fn retryable_request() { try_ready!(sock1.read(&mut [0u8; 512])); try_ready!(sock1.write(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")); Ok(Async::Ready(())) - }); + }).map_err(|e: ::std::io::Error| panic!("srv1 poll_fn error: {}", e)); res1.join(srv1).wait().expect("res1"); } drop(sock1); diff --git a/src/client/tests.rs b/src/client/tests.rs --- a/src/client/tests.rs +++ b/src/client/tests.rs @@ -52,7 +52,7 @@ fn retryable_request() { try_ready!(sock2.read(&mut [0u8; 512])); try_ready!(sock2.write(b"HTTP/1.1 222 OK\r\nContent-Length: 0\r\n\r\n")); Ok(Async::Ready(())) - }); + }).map_err(|e: ::std::io::Error| panic!("srv2 poll_fn error: {}", e)); res2.join(srv2).wait().expect("res2"); } diff --git a/src/client/tests.rs b/src/client/tests.rs --- a/src/client/tests.rs +++ b/src/client/tests.rs @@ -82,7 +82,7 @@ fn conn_reset_after_write() { try_ready!(sock1.read(&mut [0u8; 512])); try_ready!(sock1.write(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")); Ok(Async::Ready(())) - }); + }).map_err(|e: ::std::io::Error| panic!("srv1 poll_fn error: {}", e)); res1.join(srv1).wait().expect("res1"); } diff --git a/src/client/tests.rs b/src/client/tests.rs --- a/src/client/tests.rs +++ b/src/client/tests.rs @@ -105,10 +105,10 @@ fn conn_reset_after_write() { try_ready!(sock1.as_mut().unwrap().read(&mut [0u8; 512])); sock1.take(); Ok(Async::Ready(())) - }); + }).map_err(|e: ::std::io::Error| panic!("srv2 poll_fn error: {}", e)); let err = res2.join(srv2).wait().expect_err("res2"); - match err { - ::Error::Incomplete => (), + match err.kind() { + &::error::Kind::Incomplete => (), other => panic!("expected Incomplete, found {:?}", other) } } diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -191,58 +319,3 @@ trait AssertSendSync: Send + Sync + 'static {} #[doc(hidden)] impl AssertSendSync for Error {} -#[cfg(test)] -mod tests { - use std::error::Error as StdError; - use std::io; - use httparse; - use super::Error; - use super::Error::*; - - #[test] - fn test_cause() { - let orig = io::Error::new(io::ErrorKind::Other, "other"); - let desc = orig.description().to_owned(); - let e = Io(orig); - assert_eq!(e.cause().unwrap().description(), desc); - } - - macro_rules! from { - ($from:expr => $error:pat) => { - match Error::from($from) { - e @ $error => { - assert!(e.description().len() >= 5); - } , - e => panic!("{:?}", e) - } - } - } - - macro_rules! from_and_cause { - ($from:expr => $error:pat) => { - match Error::from($from) { - e @ $error => { - let desc = e.cause().unwrap().description(); - assert_eq!(desc, $from.description().to_owned()); - assert_eq!(desc, e.description()); - }, - _ => panic!("{:?}", $from) - } - } - } - - #[test] - fn test_from() { - - from_and_cause!(io::Error::new(io::ErrorKind::Other, "other") => Io(..)); - - from!(httparse::Error::HeaderName => Header); - from!(httparse::Error::HeaderName => Header); - from!(httparse::Error::HeaderValue => Header); - from!(httparse::Error::NewLine => Header); - from!(httparse::Error::Status => Status); - from!(httparse::Error::Token => Header); - from!(httparse::Error::TooManyHeaders => TooLarge); - from!(httparse::Error::Version => Version); - } -} diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -507,8 +506,15 @@ mod tests { .expect("callback poll") .expect_err("callback response"); - match err { - (::Error::Cancel(_), Some(_)) => (), + /* + let err = match async { + Async::Ready(result) => result.unwrap_err(), + Async::Pending => panic!("callback should be ready"), + }; + */ + + match (err.0.kind(), err.1) { + (&::error::Kind::Canceled, Some(_)) => (), other => panic!("expected Canceled, got {:?}", other), } Ok::<(), ()>(()) diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -8,7 +8,7 @@ extern crate tokio; extern crate tokio_io; extern crate pretty_env_logger; -use std::io::{self, Read, Write}; +use std::io::{Read, Write}; use std::net::{SocketAddr, TcpListener}; use std::thread; use std::time::Duration; diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -142,7 +142,7 @@ macro_rules! test { let _ = pretty_env_logger::try_init(); let runtime = Runtime::new().expect("runtime new"); - let err = test! { + let err: ::hyper::Error = test! { INNER; name: $name, runtime: &runtime, diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -157,7 +157,11 @@ macro_rules! test { headers: { $($request_header_name => $request_header_val,)* }, body: $request_body, }.unwrap_err(); - if !$err(&err) { + + fn infer_closure<F: FnOnce(&::hyper::Error) -> bool>(f: F) -> F { f } + + let closure = infer_closure($err); + if !closure(&err) { panic!("expected error, unexpected variant: {:?}", err) } } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -228,7 +232,7 @@ macro_rules! test { let _ = tx.send(()); }).expect("thread spawn"); - let rx = rx.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx.expect("thread panicked"); res.join(rx).map(|r| r.0).wait() }); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -485,10 +489,7 @@ test! { url: "http://{addr}/err", headers: {}, body: None, - error: |err| match err { - &hyper::Error::Incomplete => true, - _ => false, - }, + error: |err| err.to_string() == "message is incomplete", } test! { diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -511,10 +512,8 @@ test! { url: "http://{addr}/err", headers: {}, body: None, - error: |err| match err { - &hyper::Error::Version => true, - _ => false, - }, + // should get a Parse(Version) error + error: |err| err.is_parse(), } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -574,10 +573,7 @@ test! { url: "http://{addr}/upgrade", headers: {}, body: None, - error: |err| match err { - &hyper::Error::Upgrade => true, - _ => false, - }, + error: |err| err.to_string() == "unsupported protocol upgrade", } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -599,10 +595,7 @@ test! { url: "http://{addr}/", headers: {}, body: None, - error: |err| match err { - &hyper::Error::Method => true, - _ => false, - }, + error: |err| err.is_user(), } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -689,9 +682,9 @@ mod dispatch_impl { let res = client.request(req).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); Delay::new(Duration::from_secs(1)) - .from_err() + .expect("timeout") }); - let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx1.expect("thread panicked"); res.join(rx).map(|r| r.0).wait().unwrap(); closes.into_future().wait().unwrap().0.expect("closes"); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -736,11 +729,11 @@ mod dispatch_impl { res.into_body().into_stream().concat2() }).and_then(|_| { Delay::new(Duration::from_secs(1)) - .from_err() + .expect("timeout") }) }; // client is dropped - let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx1.expect("thread panicked"); res.join(rx).map(|r| r.0).wait().unwrap(); closes.into_future().wait().unwrap().0.expect("closes"); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -788,7 +781,7 @@ mod dispatch_impl { assert_eq!(res.status(), hyper::StatusCode::OK); res.into_body().into_stream().concat2() }); - let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx1.expect("thread panicked"); res.join(rx).map(|r| r.0).wait().unwrap(); // not closed yet, just idle diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -904,7 +897,7 @@ mod dispatch_impl { client.request(req) }; - let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx1.expect("thread panicked"); res.join(rx).map(|r| r.0).wait().unwrap(); let t = Delay::new(Duration::from_millis(100)) diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -955,7 +948,7 @@ mod dispatch_impl { assert_eq!(res.status(), hyper::StatusCode::OK); res.into_body().into_stream().concat2() }); - let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx1.expect("thread panicked"); res.join(rx).map(|r| r.0).wait().unwrap(); let t = Delay::new(Duration::from_millis(100)) diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1003,10 +996,9 @@ mod dispatch_impl { assert_eq!(res.status(), hyper::StatusCode::OK); res.into_body().into_stream().concat2() }); - let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx1.expect("thread panicked"); res.join(rx).map(|r| r.0).wait().unwrap(); - let t = Delay::new(Duration::from_millis(100)) .map(|_| panic!("time out")); let close = closes.into_future() diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1049,13 +1041,12 @@ mod dispatch_impl { assert_eq!(res.status(), hyper::StatusCode::OK); res.into_body().into_stream().concat2() }); - let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx1.expect("thread panicked"); let timeout = Delay::new(Duration::from_millis(200)); - let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); + let rx = rx.and_then(move |_| timeout.expect("timeout")); res.join(rx).map(|r| r.0).wait().unwrap(); - let t = Delay::new(Duration::from_millis(100)) .map(|_| panic!("time out")); let close = closes.into_future() diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1129,7 +1120,7 @@ mod dispatch_impl { assert_eq!(connects.load(Ordering::SeqCst), 0); - let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx1.expect("thread panicked"); let req = Request::builder() .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1143,7 +1134,7 @@ mod dispatch_impl { // state and back into client pool thread::sleep(Duration::from_millis(50)); - let rx = rx2.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx2.expect("thread panicked"); let req = Request::builder() .uri(&*format!("http://{}/b", addr)) .body(Body::empty()) diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1194,7 +1185,7 @@ mod dispatch_impl { assert_eq!(connects.load(Ordering::Relaxed), 0); - let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx1.expect("thread panicked"); let req = Request::builder() .method("HEAD") .uri(&*format!("http://{}/a", addr)) diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1205,7 +1196,7 @@ mod dispatch_impl { assert_eq!(connects.load(Ordering::Relaxed), 1); - let rx = rx2.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx2.expect("thread panicked"); let req = Request::builder() .uri(&*format!("http://{}/b", addr)) .body(Body::empty()) diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1246,7 +1237,7 @@ mod dispatch_impl { }); - let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx1.expect("thread panicked"); let req = Request::builder() .uri(&*format!("http://{}/foo/bar", addr)) .body(Body::empty()) diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1354,7 +1345,7 @@ mod conn { use hyper::{self, Request}; use hyper::client::conn; - use super::{s, tcp_connect}; + use super::{s, tcp_connect, FutureHyperExt}; #[test] fn get() { diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1395,10 +1386,10 @@ mod conn { assert_eq!(res.status(), hyper::StatusCode::OK); res.into_body().into_stream().concat2() }); - let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx1.expect("thread panicked"); let timeout = Delay::new(Duration::from_millis(200)); - let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); + let rx = rx.and_then(move |_| timeout.expect("timeout")); res.join(rx).map(|r| r.0).wait().unwrap(); } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1441,10 +1432,10 @@ mod conn { assert_eq!(res.status(), hyper::StatusCode::OK); res.into_body().into_stream().concat2() }); - let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx1.expect("thread panicked"); let timeout = Delay::new(Duration::from_millis(200)); - let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); + let rx = rx.and_then(move |_| timeout.expect("timeout")); res.join(rx).map(|r| r.0).wait().unwrap(); } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1490,17 +1481,14 @@ mod conn { let res2 = client.send_request(req) .then(|result| { let err = result.expect_err("res2"); - match err { - hyper::Error::Cancel(..) => (), - other => panic!("expected Cancel, found {:?}", other), - } + assert!(err.is_canceled(), "err not canceled, {:?}", err); Ok(()) }); - let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx1.expect("thread panicked"); let timeout = Delay::new(Duration::from_millis(200)); - let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); + let rx = rx.and_then(move |_| timeout.expect("timeout")); res1.join(res2).join(rx).map(|r| r.0).wait().unwrap(); } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1558,10 +1546,10 @@ mod conn { res.into_body().into_stream().concat2() }); - let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx1.expect("thread panicked"); let timeout = Delay::new(Duration::from_millis(200)); - let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); + let rx = rx.and_then(move |_| timeout.expect("timeout")); until_upgrade.join(res).join(rx).map(|r| r.0).wait().unwrap(); // should not be ready now diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1641,10 +1629,10 @@ mod conn { assert_eq!(body.as_ref(), b""); }); - let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + let rx = rx1.expect("thread panicked"); let timeout = Delay::new(Duration::from_millis(200)); - let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); + let rx = rx.and_then(move |_| timeout.expect("timeout")); until_tunneled.join(res).join(rx).map(|r| r.0).wait().unwrap(); // should not be ready now diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1697,3 +1685,17 @@ mod conn { impl AsyncRead for DebugStream {} } + +trait FutureHyperExt: Future { + fn expect<E>(self, msg: &'static str) -> Box<Future<Item=Self::Item, Error=E>>; +} + +impl<F> FutureHyperExt for F +where + F: Future + 'static, + F::Error: ::std::fmt::Debug, +{ + fn expect<E>(self, msg: &'static str) -> Box<Future<Item=Self::Item, Error=E>> { + Box::new(self.map_err(move |e| panic!("expect: {}; error={:?}", msg, e))) + } +} diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -935,7 +935,7 @@ fn returning_1xx_response_is_error() { let socket = item.unwrap(); Http::<hyper::Chunk>::new() .serve_connection(socket, service_fn(|_| { - Ok(Response::builder() + Ok::<_, hyper::Error>(Response::builder() .status(StatusCode::CONTINUE) .body(Body::empty()) .unwrap()) diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -988,7 +988,7 @@ fn upgrades() { .header("upgrade", "foobar") .body(hyper::Body::empty()) .unwrap(); - Ok(res) + Ok::<_, hyper::Error>(res) })); let mut conn_opt = Some(conn); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1144,10 +1144,10 @@ fn streaming_body() { .keep_alive(false) .serve_connection(socket, service_fn(|_| { static S: &'static [&'static [u8]] = &[&[b'x'; 1_000] as &[u8]; 1_00] as _; - let b = ::futures::stream::iter_ok(S.into_iter()) + let b = ::futures::stream::iter_ok::<_, String>(S.into_iter()) .map(|&s| s); let b = hyper::Body::wrap_stream(b); - Ok(Response::new(b)) + Ok::<_, hyper::Error>(Response::new(b)) })) .map(|_| ()) });
From-trait based error conversion for request bodies Picking up that particular thread from #1328, I was wondering whether it might be worth it to implement a From/Into-based error coercion for request bodies. This would be different from #1129 in so far as I believe that it should be possible to ship it as a non-breaking change, ergo before 0.12, and therefore solve at least one pain point in the short-term which users are currently experiencing when using custom request bodies. What do you think?
That seems fine to me. I think I tried it out a few months ago, and ran into issues propagating the generics everywhere, but maybe I did it wrong!
2018-04-06T21:13:43Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,470
hyperium__hyper-1470
[ "1448" ]
5db85316a10d0b7bdd36524d85a746a23bd10190
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -22,20 +22,17 @@ include = [ [dependencies] bytes = "0.4.4" -futures = "0.1.17" -futures-cpupool = "0.1.6" -futures-timer = "0.1.0" +futures = "0.2.0-beta" +futures-timer = { git = "https://github.com/alexcrichton/futures-timer.git" } http = "0.1.5" httparse = "1.0" iovec = "0.1" log = "0.4" net2 = "0.2.32" time = "0.1" -tokio = "0.1.3" -tokio-executor = "0.1.0" -tokio-service = "0.1" -tokio-io = "0.1" -want = "0.0.2" +tokio = { git = "https://github.com/seanmonstar/tokio.git", branch = "futures2-use-after-free", features = ["unstable-futures"] } +tokio-executor = { git = "https://github.com/seanmonstar/tokio.git", branch = "futures2-use-after-free", features = ["unstable-futures"] } +want = { git = "https://github.com/srijs/want.git", branch = "futures-0.2" } [dev-dependencies] num_cpus = "1.0" diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -45,3 +42,6 @@ url = "1.0" [features] nightly = [] + +[replace] +"futures:0.2.0-beta" = { git = "https://github.com/srijs/futures-rs.git", branch = "with-executor" } diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -8,7 +8,8 @@ extern crate tokio; use std::net::SocketAddr; -use futures::{Future, Stream}; +use futures::{FutureExt, StreamExt}; +use futures::executor::block_on; use tokio::runtime::Runtime; use tokio::net::TcpListener; diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -76,21 +81,22 @@ fn spawn_hello(rt: &mut Runtime) -> SocketAddr { let service = const_service(service_fn(|req: Request<Body>| { req.into_body() .into_stream() - .concat2() + .concat() .map(|_| { Response::new(Body::from(PHRASE)) }) })); let srv = listener.incoming() - .into_future() + .next() .map_err(|(e, _inc)| panic!("accept error: {}", e)) .and_then(move |(accepted, _inc)| { let socket = accepted.expect("accepted socket"); http.serve_connection(socket, service.new_service().expect("new_service")) .map(|_| ()) .map_err(|_| ()) - }); - rt.spawn(srv); + }) + .map_err(|_| panic!("server error")); + rt.spawn2(srv); return addr } diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -11,8 +11,8 @@ use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::mpsc; -use futures::{future, stream, Future, Stream}; -use futures::sync::oneshot; +use futures::{future, stream, FutureExt, StreamExt}; +use futures::channel::oneshot; use hyper::{Body, Request, Response}; use hyper::server::Service; diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -31,7 +31,7 @@ macro_rules! bench_server { })).unwrap(); let addr = srv.local_addr().unwrap(); addr_tx.send(addr).unwrap(); - tokio::run(srv.run_until(until_rx.map_err(|_| ())).map_err(|e| panic!("server error: {}", e))); + tokio::runtime::run2(srv.run_until(until_rx.map_err(|_| ())).map_err(|e| panic!("server error: {}", e))); }); addr_rx.recv().unwrap() diff --git a/examples/client.rs b/examples/client.rs --- a/examples/client.rs +++ b/examples/client.rs @@ -8,7 +8,7 @@ extern crate pretty_env_logger; use std::env; use std::io::{self, Write}; -use futures::{Future, Stream}; +use futures::{FutureExt, StreamExt}; use futures::future::lazy; use hyper::{Body, Client, Request}; diff --git a/examples/client.rs b/examples/client.rs --- a/examples/client.rs +++ b/examples/client.rs @@ -30,7 +30,7 @@ fn main() { return; } - tokio::run(lazy(move || { + tokio::runtime::run2(lazy(move |_| { let client = Client::default(); let mut req = Request::new(Body::empty()); diff --git a/examples/client.rs b/examples/client.rs --- a/examples/client.rs +++ b/examples/client.rs @@ -43,10 +43,13 @@ fn main() { res.into_parts().1.into_stream().for_each(|chunk| { io::stdout().write_all(&chunk).map_err(From::from) }) - }).map(|_| { - println!("\n\nDone."); - }).map_err(|err| { - eprintln!("Error {}", err); + }).then(|result| { + if let Some(err) = result.err() { + eprintln!("Error {}", err); + } else { + println!("\n\nDone."); + } + Ok(()) }) })); } diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -4,7 +4,7 @@ extern crate futures; extern crate pretty_env_logger; extern crate tokio; -use futures::Future; +use futures::FutureExt; use futures::future::lazy; use hyper::{Body, Response}; diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -20,13 +20,13 @@ fn main() { Ok(Response::new(Body::from(PHRASE))) })); - tokio::run(lazy(move || { + tokio::runtime::run2(lazy(move |_| { let server = Http::new() .sleep_on_errors(true) .bind(&addr, new_service) .unwrap(); - println!("Listening on http://{} with 1 thread.", server.local_addr().unwrap()); - server.run().map_err(|err| eprintln!("Server error {}", err)) + println!("Listening on http://{}", server.local_addr().unwrap()); + server.run().map_err(|err| panic!("Server error {}", err)) })); } diff --git a/examples/multi_server.rs b/examples/multi_server.rs --- a/examples/multi_server.rs +++ b/examples/multi_server.rs @@ -4,8 +4,9 @@ extern crate futures; extern crate pretty_env_logger; extern crate tokio; -use futures::{Future, Stream}; +use futures::{FutureExt, StreamExt}; use futures::future::{FutureResult, lazy}; +use futures::executor::spawn; use hyper::{Body, Method, Request, Response, StatusCode}; use hyper::server::{Http, Service}; diff --git a/examples/multi_server.rs b/examples/multi_server.rs --- a/examples/multi_server.rs +++ b/examples/multi_server.rs @@ -43,22 +44,20 @@ fn main() { let addr1 = "127.0.0.1:1337".parse().unwrap(); let addr2 = "127.0.0.1:1338".parse().unwrap(); - tokio::run(lazy(move || { + tokio::runtime::run2(lazy(move |_| { let srv1 = Http::new().serve_addr(&addr1, || Ok(Srv(INDEX1))).unwrap(); let srv2 = Http::new().serve_addr(&addr2, || Ok(Srv(INDEX2))).unwrap(); println!("Listening on http://{}", srv1.incoming_ref().local_addr()); println!("Listening on http://{}", srv2.incoming_ref().local_addr()); - tokio::spawn(srv1.for_each(move |conn| { - tokio::spawn(conn.map(|_| ()).map_err(|err| println!("srv1 error: {:?}", err))); - Ok(()) - }).map_err(|_| ())); + spawn(srv1.map_err(|err| panic!("srv1 error: {:?}", err)).for_each(move |conn| { + spawn(conn.map(|_| ()).map_err(|err| panic!("srv1 error: {:?}", err))) + }).map(|_| ())); - tokio::spawn(srv2.for_each(move |conn| { - tokio::spawn(conn.map(|_| ()).map_err(|err| println!("srv2 error: {:?}", err))); - Ok(()) - }).map_err(|_| ())); + spawn(srv2.map_err(|err| panic!("srv2 error: {:?}", err)).for_each(move |conn| { + spawn(conn.map(|_| ()).map_err(|err| panic!("srv2 error: {:?}", err))) + }).map(|_| ())); Ok(()) })); diff --git a/examples/params.rs b/examples/params.rs --- a/examples/params.rs +++ b/examples/params.rs @@ -5,7 +5,7 @@ extern crate pretty_env_logger; extern crate tokio; extern crate url; -use futures::{Future, Stream}; +use futures::{Future, FutureExt, StreamExt}; use futures::future::lazy; use hyper::{Body, Method, Request, Response, StatusCode}; diff --git a/examples/params.rs b/examples/params.rs --- a/examples/params.rs +++ b/examples/params.rs @@ -32,7 +32,7 @@ impl Service for ParamExample { Box::new(futures::future::ok(Response::new(INDEX.into()))) }, (&Method::POST, "/post") => { - Box::new(req.into_parts().1.into_stream().concat2().map(|b| { + Box::new(req.into_parts().1.into_stream().concat().map(|b| { // Parse the request body. form_urlencoded::parse // always succeeds, but in general parsing may // fail (for example, an invalid post of json), so diff --git a/examples/params.rs b/examples/params.rs --- a/examples/params.rs +++ b/examples/params.rs @@ -98,9 +98,11 @@ fn main() { pretty_env_logger::init(); let addr = "127.0.0.1:1337".parse().unwrap(); - tokio::run(lazy(move || { + tokio::runtime::run2(lazy(move |_| { let server = Http::new().bind(&addr, || Ok(ParamExample)).unwrap(); - println!("Listening on http://{} with 1 thread.", server.local_addr().unwrap()); - server.run().map_err(|err| eprintln!("Server error {}", err)) + println!("Listening on http://{}", server.local_addr().unwrap()); + server.run().recover(|err| { + eprintln!("Server error {}", err) + }) })); } diff --git a/examples/send_file.rs b/examples/send_file.rs --- a/examples/send_file.rs +++ b/examples/send_file.rs @@ -4,9 +4,9 @@ extern crate hyper; extern crate pretty_env_logger; extern crate tokio; -use futures::{Future/*, Sink*/}; +use futures::{Future, FutureExt}; use futures::future::lazy; -use futures::sync::oneshot; +use futures::channel::oneshot; use hyper::{Body, /*Chunk,*/ Method, Request, Response, StatusCode}; use hyper::error::Error; diff --git a/examples/send_file.rs b/examples/send_file.rs --- a/examples/send_file.rs +++ b/examples/send_file.rs @@ -141,9 +141,9 @@ fn main() { pretty_env_logger::init(); let addr = "127.0.0.1:1337".parse().unwrap(); - tokio::run(lazy(move || { + tokio::runtime::run2(lazy(move |_| { let server = Http::new().bind(&addr, || Ok(ResponseExamples)).unwrap(); - println!("Listening on http://{} with 1 thread.", server.local_addr().unwrap()); - server.run().map_err(|err| eprintln!("Server error {}", err)) + println!("Listening on http://{}", server.local_addr().unwrap()); + server.run().map_err(|err| panic!("Server error {}", err)) })); } diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -4,7 +4,7 @@ extern crate hyper; extern crate pretty_env_logger; extern crate tokio; -use futures::Future; +use futures::FutureExt; use futures::future::{FutureResult, lazy}; use hyper::{Body, Method, Request, Response, StatusCode}; diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -43,9 +43,11 @@ fn main() { pretty_env_logger::init(); let addr = "127.0.0.1:1337".parse().unwrap(); - tokio::run(lazy(move || { + tokio::runtime::run2(lazy(move |_| { let server = Http::new().bind(&addr, || Ok(Echo)).unwrap(); - println!("Listening on http://{} with 1 thread.", server.local_addr().unwrap()); - server.run().map_err(|err| eprintln!("Server error {}", err)) + println!("Listening on http://{}", server.local_addr().unwrap()); + server.run().recover(|err| { + eprintln!("Server error {}", err) + }) })); } diff --git a/examples/web_api.rs b/examples/web_api.rs --- a/examples/web_api.rs +++ b/examples/web_api.rs @@ -4,14 +4,15 @@ extern crate hyper; extern crate pretty_env_logger; extern crate tokio; -use futures::{Future, Stream}; +use futures::{Future, FutureExt, StreamExt}; +use futures::executor::spawn; use futures::future::lazy; use tokio::reactor::Handle; use hyper::{Body, Chunk, Client, Method, Request, Response, StatusCode}; use hyper::server::{Http, Service}; -#[allow(unused)] +#[allow(unused, deprecated)] use std::ascii::AsciiExt; static NOTFOUND: &[u8] = b"Not Found"; diff --git a/examples/web_api.rs b/examples/web_api.rs --- a/examples/web_api.rs +++ b/examples/web_api.rs @@ -78,13 +79,15 @@ fn main() { pretty_env_logger::init(); let addr = "127.0.0.1:1337".parse().unwrap(); - tokio::run(lazy(move || { + tokio::runtime::run2(lazy(move |_| { let handle = Handle::current(); let serve = Http::new().serve_addr(&addr, move || Ok(ResponseExamples(handle.clone()))).unwrap(); - println!("Listening on http://{} with 1 thread.", serve.incoming_ref().local_addr()); + println!("Listening on http://{}", serve.incoming_ref().local_addr()); - serve.map_err(|_| ()).for_each(move |conn| { - tokio::spawn(conn.map(|_| ()).map_err(|err| println!("serve error: {:?}", err))) - }) + serve.map_err(|err| panic!("server error {:?}", err)).for_each(move |conn| { + spawn(conn.recover(|err| { + println!("connection error: {:?}", err); + })) + }).map(|_| ()) })); } diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -11,9 +11,10 @@ use std::fmt; use std::marker::PhantomData; use bytes::Bytes; -use futures::{Async, Future, Poll}; +use futures::{Async, Future, FutureExt, Poll}; use futures::future::{self, Either}; -use tokio_io::{AsyncRead, AsyncWrite}; +use futures::task; +use futures::io::{AsyncRead, AsyncWrite}; use proto; use proto::body::Entity; diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -123,8 +124,8 @@ impl<B> SendRequest<B> /// Polls to determine whether this sender can be used yet for a request. /// /// If the associated connection is closed, this returns an Error. - pub fn poll_ready(&mut self) -> Poll<(), ::Error> { - self.dispatch.poll_ready() + pub fn poll_ready(&mut self, cx: &mut task::Context) -> Poll<(), ::Error> { + self.dispatch.poll_ready(cx) } pub(super) fn is_closed(&self) -> bool { diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -162,7 +163,7 @@ where /// # use http::header::HOST; /// # use hyper::client::conn::SendRequest; /// # use hyper::Body; - /// use futures::Future; + /// use futures::FutureExt; /// use hyper::Request; /// /// # fn doc(mut tx: SendRequest<Body>) { diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -186,19 +187,19 @@ where pub fn send_request(&mut self, req: Request<B>) -> ResponseFuture { let inner = match self.dispatch.send(req) { Ok(rx) => { - Either::A(rx.then(move |res| { + rx.then(move |res| { match res { Ok(Ok(res)) => Ok(res), Ok(Err(err)) => Err(err), // this is definite bug if it happens, but it shouldn't happen! Err(_) => panic!("dispatch dropped without returning error"), } - })) + }).left() }, Err(_req) => { debug!("connection was not ready"); let err = ::Error::new_canceled(Some("connection was not ready")); - Either::B(future::err(err)) + future::err(err).right() } }; diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -214,7 +215,7 @@ where { let inner = match self.dispatch.try_send(req) { Ok(rx) => { - Either::A(rx.then(move |res| { + Either::Left(rx.then(move |res| { match res { Ok(Ok(res)) => Ok(res), Ok(Err(err)) => Err(err), diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -226,7 +227,7 @@ where Err(req) => { debug!("connection was not ready"); let err = ::Error::new_canceled(Some("connection was not ready")); - Either::B(future::err((err, Some(req)))) + Either::Right(future::err((err, Some(req)))) } }; Box::new(inner) diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -277,8 +278,8 @@ where /// upgrade. Once the upgrade is completed, the connection would be "done", /// but it is not desired to actally shutdown the IO object. Instead you /// would take it back using `into_parts`. - pub fn poll_without_shutdown(&mut self) -> Poll<(), ::Error> { - self.inner.poll_without_shutdown() + pub fn poll_without_shutdown(&mut self, cx: &mut task::Context) -> Poll<(), ::Error> { + self.inner.poll_without_shutdown(cx) } } diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -290,8 +291,8 @@ where type Item = (); type Error = ::Error; - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - self.inner.poll() + fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> { + self.inner.poll(cx) } } diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -363,8 +364,8 @@ where type Item = (SendRequest<B>, Connection<T, B>); type Error = ::Error; - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - self.inner.poll() + fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> { + self.inner.poll(cx) .map(|async| { async.map(|(tx, dispatch)| { (tx, Connection { inner: dispatch }) diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -394,8 +395,8 @@ where >); type Error = ::Error; - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - self.inner.poll() + fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> { + self.inner.poll(cx) } } diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -417,7 +418,7 @@ where >); type Error = ::Error; - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + fn poll(&mut self, _cx: &mut task::Context) -> Poll<Self::Item, Self::Error> { let io = self.io.take().expect("polled more than once"); let (tx, rx) = dispatch::channel(); let mut conn = proto::Conn::new(io); diff --git a/src/client/conn.rs b/src/client/conn.rs --- a/src/client/conn.rs +++ b/src/client/conn.rs @@ -441,8 +442,8 @@ impl Future for ResponseFuture { type Error = ::Error; #[inline] - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - self.inner.poll() + fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> { + self.inner.poll(cx) } } diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -8,24 +8,21 @@ use std::error::Error as StdError; use std::fmt; use std::io; -use std::mem; use std::net::SocketAddr; -use std::sync::Arc; use std::time::Duration; -use futures::{Future, Poll, Async}; -use futures::future::{Executor, ExecuteError}; -use futures::sync::oneshot; -use futures_cpupool::{Builder as CpuPoolBuilder}; +use futures::{Future, Never, Poll, Async}; +use futures::executor::{Executor, SpawnError, ThreadPoolBuilder}; +use futures::task; +use futures::io::{AsyncRead, AsyncWrite}; use http::Uri; use http::uri::Scheme; use net2::TcpBuilder; -use tokio_io::{AsyncRead, AsyncWrite}; use tokio::reactor::Handle; use tokio::net::{TcpStream, ConnectFuture}; +use executor::CloneBoxedExecutor; use super::dns; -use self::http_connector::HttpConnectorBlockingTask; /// Connect to a destination, returning an IO transport. /// diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -174,7 +171,7 @@ impl HttpConnector { /// Takes number of DNS worker threads. #[inline] pub fn new(threads: usize, handle: &Handle) -> HttpConnector { - let pool = CpuPoolBuilder::new() + let pool = ThreadPoolBuilder::new() .name_prefix("hyper-dns") .pool_size(threads) .create(); diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -186,10 +183,10 @@ impl HttpConnector { /// Takes an executor to run blocking tasks on. #[inline] pub fn new_with_executor<E: 'static>(executor: E, handle: &Handle) -> HttpConnector - where E: Executor<HttpConnectorBlockingTask> + Send + Sync + where E: Executor + Clone + Send + Sync { HttpConnector { - executor: HttpConnectExecutor(Arc::new(executor)), + executor: HttpConnectExecutor(Box::new(executor)), enforce_http: true, handle: handle.clone(), keep_alive_timeout: None, diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -298,7 +295,7 @@ pub struct HttpConnecting { enum State { Lazy(HttpConnectExecutor, String, u16), - Resolving(oneshot::SpawnHandle<dns::IpAddrs, io::Error>), + Resolving(dns::Resolving), Connecting(ConnectingTcp), Error(Option<io::Error>), } diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -307,11 +304,11 @@ impl Future for HttpConnecting { type Item = (TcpStream, Connected); type Error = io::Error; - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> { loop { let state; match self.state { - State::Lazy(ref executor, ref mut host, port) => { + State::Lazy(ref mut executor, ref mut host, port) => { // If the host is already an IP addr (v4 or v6), // skip resolving the dns and start connecting right away. if let Some(addrs) = dns::IpAddrs::try_parse(host, port) { diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -320,24 +317,19 @@ impl Future for HttpConnecting { current: None }) } else { - let host = mem::replace(host, String::new()); - let work = dns::Work::new(host, port); - state = State::Resolving(oneshot::spawn(work, executor)); + let host = ::std::mem::replace(host, String::new()); + state = State::Resolving(dns::Resolving::spawn(host, port, executor)); } }, State::Resolving(ref mut future) => { - match try!(future.poll()) { - Async::NotReady => return Ok(Async::NotReady), - Async::Ready(addrs) => { - state = State::Connecting(ConnectingTcp { - addrs: addrs, - current: None, - }) - } - }; + let addrs = try_ready!(future.poll(cx)); + state = State::Connecting(ConnectingTcp { + addrs: addrs, + current: None, + }); }, State::Connecting(ref mut c) => { - let sock = try_ready!(c.poll(&self.handle)); + let sock = try_ready!(c.poll(cx, &self.handle)); if let Some(dur) = self.keep_alive_timeout { sock.set_keepalive(Some(dur))?; diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -365,11 +357,11 @@ struct ConnectingTcp { impl ConnectingTcp { // not a Future, since passing a &Handle to poll - fn poll(&mut self, handle: &Handle) -> Poll<TcpStream, io::Error> { + fn poll(&mut self, cx: &mut task::Context, handle: &Handle) -> Poll<TcpStream, io::Error> { let mut err = None; loop { if let Some(ref mut current) = self.current { - match current.poll() { + match current.poll(cx) { Ok(ok) => return Ok(ok), Err(e) => { trace!("connect error {:?}", e); diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -392,37 +384,19 @@ impl ConnectingTcp { } } -// Make this Future unnameable outside of this crate. -mod http_connector { - use super::*; - // Blocking task to be executed on a thread pool. - pub struct HttpConnectorBlockingTask { - pub(super) work: oneshot::Execute<dns::Work> - } - - impl fmt::Debug for HttpConnectorBlockingTask { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad("HttpConnectorBlockingTask") - } - } - - impl Future for HttpConnectorBlockingTask { - type Item = (); - type Error = (); - - fn poll(&mut self) -> Poll<(), ()> { - self.work.poll() - } - } -} - #[derive(Clone)] -struct HttpConnectExecutor(Arc<Executor<HttpConnectorBlockingTask> + Send + Sync>); +struct HttpConnectExecutor(Box<CloneBoxedExecutor>); + +impl Executor for HttpConnectExecutor { + fn spawn( + &mut self, + f: Box<Future<Item = (), Error = Never> + 'static + Send> + ) -> Result<(), SpawnError> { + self.0.spawn(f) + } -impl Executor<oneshot::Execute<dns::Work>> for HttpConnectExecutor { - fn execute(&self, future: oneshot::Execute<dns::Work>) -> Result<(), ExecuteError<oneshot::Execute<dns::Work>>> { - self.0.execute(HttpConnectorBlockingTask { work: future }) - .map_err(|err| ExecuteError::new(err.kind(), err.into_future().work)) + fn status(&self) -> Result<(), SpawnError> { + self.0.status() } } diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -1,9 +1,8 @@ -use futures::{Async, Poll, Stream}; -use futures::sync::{mpsc, oneshot}; +use futures::{Async, Never, Poll, Stream}; +use futures::channel::{mpsc, oneshot}; +use futures::task; use want; -use common::Never; - //pub type Callback<T, U> = oneshot::Sender<Result<U, (::Error, Option<T>)>>; pub type RetryPromise<T, U> = oneshot::Receiver<Result<U, (::Error, Option<T>)>>; pub type Promise<T> = oneshot::Receiver<Result<T, ::Error>>; diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -33,15 +32,15 @@ pub struct Sender<T, U> { } impl<T, U> Sender<T, U> { - pub fn poll_ready(&mut self) -> Poll<(), ::Error> { - match self.inner.poll_ready() { + pub fn poll_ready(&mut self, cx: &mut task::Context) -> Poll<(), ::Error> { + match self.inner.poll_ready(cx) { Ok(Async::Ready(())) => { // there's room in the queue, but does the Connection // want a message yet? - self.giver.poll_want() + self.giver.poll_want(cx) .map_err(|_| ::Error::Closed) }, - Ok(Async::NotReady) => Ok(Async::NotReady), + Ok(Async::Pending) => Ok(Async::Pending), Err(_) => Err(::Error::Closed), } } diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -75,16 +74,15 @@ impl<T, U> Stream for Receiver<T, U> { type Item = (T, Callback<T, U>); type Error = Never; - fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { - match self.inner.poll() { - Ok(Async::Ready(item)) => Ok(Async::Ready(item.map(|mut env| { + fn poll_next(&mut self, cx: &mut task::Context) -> Poll<Option<Self::Item>, Self::Error> { + match self.inner.poll_next(cx)? { + Async::Ready(item) => Ok(Async::Ready(item.map(|mut env| { env.0.take().expect("envelope not dropped") }))), - Ok(Async::NotReady) => { + Async::Pending => { self.taker.want(); - Ok(Async::NotReady) + Ok(Async::Pending) } - Err(()) => unreachable!("mpsc never errors"), } } } diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -107,11 +105,11 @@ impl<T, U> Drop for Receiver<T, U> { // This poll() is safe to call in `Drop`, because we've // called, `close`, which promises that no new messages // will arrive, and thus, once we reach the end, we won't - // see a `NotReady` (and try to park), but a Ready(None). + // see a `Pending` (and try to park), but a Ready(None). // // All other variants: // - Ready(None): the end. we want to stop looping - // - NotReady: unreachable + // - Pending: unreachable // - Err: unreachable while let Ok(Async::Ready(Some((val, cb)))) = self.inner.poll() { let _ = cb.send(Err((::Error::new_canceled(None::<::Error>), Some(val)))); diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -137,10 +135,10 @@ pub enum Callback<T, U> { } impl<T, U> Callback<T, U> { - pub fn poll_cancel(&mut self) -> Poll<(), ()> { + pub fn poll_cancel(&mut self, cx: &mut task::Context) -> Poll<(), Never> { match *self { - Callback::Retry(ref mut tx) => tx.poll_cancel(), - Callback::NoRetry(ref mut tx) => tx.poll_cancel(), + Callback::Retry(ref mut tx) => tx.poll_cancel(cx), + Callback::NoRetry(ref mut tx) => tx.poll_cancel(cx), } } diff --git a/src/client/dns.rs b/src/client/dns.rs --- a/src/client/dns.rs +++ b/src/client/dns.rs @@ -6,27 +6,44 @@ use std::net::{ }; use std::vec; -use ::futures::{Async, Future, Poll}; +use futures::{Async, Future, Poll}; +use futures::task; +use futures::future::lazy; +use futures::executor::Executor; +use futures::channel::oneshot; -pub struct Work { - host: String, - port: u16 +pub struct Resolving { + receiver: oneshot::Receiver<Result<IpAddrs, io::Error>> } -impl Work { - pub fn new(host: String, port: u16) -> Work { - Work { host: host, port: port } +impl Resolving { + pub fn spawn(host: String, port: u16, executor: &mut Executor) -> Resolving { + let (sender, receiver) = oneshot::channel(); + // The `Resolving` future will return an error when the sender is dropped, + // so we can just ignore the spawn error here + executor.spawn(Box::new(lazy(move |_| { + debug!("resolving host={:?}, port={:?}", host, port); + let result = (host.as_ref(), port).to_socket_addrs() + .map(|i| IpAddrs { iter: i }); + sender.send(result).ok(); + Ok(()) + }))).ok(); + Resolving { receiver } } } -impl Future for Work { +impl Future for Resolving { type Item = IpAddrs; type Error = io::Error; - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - debug!("resolving host={:?}, port={:?}", self.host, self.port); - (&*self.host, self.port).to_socket_addrs() - .map(|i| Async::Ready(IpAddrs { iter: i })) + fn poll(&mut self, cx: &mut task::Context) -> Poll<IpAddrs, io::Error> { + match self.receiver.poll(cx) { + Ok(Async::Pending) => Ok(Async::Pending), + Ok(Async::Ready(Ok(ips))) => Ok(Async::Ready(ips)), + Ok(Async::Ready(Err(err))) => Err(err), + Err(_) => + Err(io::Error::new(io::ErrorKind::Other, "dns task was cancelled")) + } } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -6,22 +6,21 @@ use std::marker::PhantomData; use std::sync::Arc; use std::time::Duration; -use futures::{Async, Future, Poll}; -use futures::future::{self, Executor}; +use futures::{Async, Future, FutureExt, Never, Poll}; +use futures::future; +use futures::task; use http::{Method, Request, Response, Uri, Version}; use http::header::{Entry, HeaderValue, HOST}; use http::uri::Scheme; use tokio::reactor::Handle; -use tokio_executor::spawn; -pub use tokio_service::Service; +pub use service::Service; use proto::body::{Body, Entity}; use proto; use self::pool::Pool; pub use self::connect::{Connect, HttpConnector}; -use self::background::{bg, Background}; use self::connect::Destination; pub mod conn; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -82,10 +80,9 @@ impl Client<HttpConnector, proto::Body> { impl<C, B> Client<C, B> { #[inline] - fn configured(config: Config<C, B>, exec: Exec) -> Client<C, B> { + fn configured(config: Config<C, B>) -> Client<C, B> { Client { connector: Arc::new(config.connector), - executor: exec, h1_writev: config.h1_writev, pool: Pool::new(config.keep_alive, config.keep_alive_timeout), retry_canceled_requests: config.retry_canceled_requests, diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -125,14 +122,6 @@ where C: Connect<Error=io::Error> + Sync + 'static, /// Send a constructed Request using this Client. pub fn request(&self, mut req: Request<B>) -> FutureResponse { - // TODO(0.12): do this at construction time. - // - // It cannot be done in the constructor because the Client::configured - // does not have `B: 'static` bounds, which are required to spawn - // the interval. In 0.12, add a static bounds to the constructor, - // and move this. - self.schedule_pool_timer(); - match req.version() { Version::HTTP_10 | Version::HTTP_11 => (), diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -175,7 +164,6 @@ where C: Connect<Error=io::Error> + Sync + 'static, } } - let client = self.clone(); let uri = req.uri().clone(); let fut = RetryableSendRequest { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -192,7 +180,6 @@ where C: Connect<Error=io::Error> + Sync + 'static, let url = req.uri().clone(); let checkout = self.pool.checkout(domain); let connect = { - let executor = self.executor.clone(); let pool = self.pool.clone(); let pool_key = Arc::new(domain.to_string()); let h1_writev = self.h1_writev; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -200,36 +187,39 @@ where C: Connect<Error=io::Error> + Sync + 'static, let dst = Destination { uri: url, }; - future::lazy(move || { + future::lazy(move |_| { connector.connect(dst) - .from_err() + .err_into() .and_then(move |(io, connected)| { conn::Builder::new() .h1_writev(h1_writev) .handshake_no_upgrades(io) .and_then(move |(tx, conn)| { - executor.execute(conn.map_err(|e| debug!("client connection error: {}", e)))?; - Ok(pool.pooled(pool_key, PoolClient { - is_proxied: connected.is_proxied, - tx: tx, - })) + future::lazy(move |cx| { + execute(conn.recover(|e| { + debug!("client connection error: {}", e); + }), cx)?; + Ok(pool.pooled(pool_key, PoolClient { + is_proxied: connected.is_proxied, + tx: tx, + })) + }) }) }) }) }; - let race = checkout.select(connect) - .map(|(pooled, _work)| pooled) - .map_err(|(e, _checkout)| { - // the Pool Checkout cannot error, so the only error - // is from the Connector - // XXX: should wait on the Checkout? Problem is - // that if the connector is failing, it may be that we - // never had a pooled stream at all - ClientError::Normal(e) - }); - - let executor = self.executor.clone(); + let race = checkout.select(connect).map(|either| { + either.either(|(pooled, _)| pooled, |(pooled, _)| pooled) + }).map_err(|either| { + // the Pool Checkout cannot error, so the only error + // is from the Connector + // XXX: should wait on the Checkout? Problem is + // that if the connector is failing, it may be that we + // never had a pooled stream at all + ClientError::Normal(either.either(|(e, _)| e, |(e, _)| e)) + }); + let resp = race.and_then(move |mut pooled| { let conn_reused = pooled.is_reused(); set_relative_uri(req.uri_mut(), pooled.is_proxied); diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -245,24 +235,26 @@ where C: Connect<Error=io::Error> + Sync + 'static, ClientError::Normal(err) } }) - .map(move |res| { - // when pooled is dropped, it will try to insert back into the - // pool. To delay that, spawn a future that completes once the - // sender is ready again. - // - // This *should* only be once the related `Connection` has polled - // for a new request to start. - // - // It won't be ready if there is a body to stream. - if let Ok(Async::NotReady) = pooled.tx.poll_ready() { - // If the executor doesn't have room, oh well. Things will likely - // be blowing up soon, but this specific task isn't required. - let _ = executor.execute(future::poll_fn(move || { - pooled.tx.poll_ready().map_err(|_| ()) - })); - } + .and_then(move |res| { + future::lazy(move |cx| { + // when pooled is dropped, it will try to insert back into the + // pool. To delay that, spawn a future that completes once the + // sender is ready again. + // + // This *should* only be once the related `Connection` has polled + // for a new request to start. + // + // It won't be ready if there is a body to stream. + if let Ok(Async::Pending) = pooled.tx.poll_ready(cx) { + // If the executor doesn't have room, oh well. Things will likely + // be blowing up soon, but this specific task isn't required. + execute(future::poll_fn(move |cx| { + pooled.tx.poll_ready(cx).or(Ok(Async::Ready(()))) + }), cx).ok(); + } - res + Ok(res) + }) }); diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -271,10 +263,6 @@ where C: Connect<Error=io::Error> + Sync + 'static, Box::new(resp) } - - fn schedule_pool_timer(&self) { - self.pool.spawn_expired_interval(&self.executor); - } } impl<C, B> Service for Client<C, B> diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -297,7 +285,6 @@ impl<C, B> Clone for Client<C, B> { fn clone(&self) -> Client<C, B> { Client { connector: self.connector.clone(), - executor: self.executor.clone(), h1_writev: self.h1_writev, pool: self.pool.clone(), retry_canceled_requests: self.retry_canceled_requests, diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -327,8 +314,8 @@ impl Future for FutureResponse { type Item = Response<Body>; type Error = ::Error; - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - self.0.poll() + fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> { + self.0.poll(cx) } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -349,11 +336,11 @@ where type Item = Response<Body>; type Error = ::Error; - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> { loop { - match self.future.poll() { + match self.future.poll(cx) { Ok(Async::Ready(resp)) => return Ok(Async::Ready(resp)), - Ok(Async::NotReady) => return Ok(Async::NotReady), + Ok(Async::Pending) => return Ok(Async::Pending), Err(ClientError::Normal(err)) => return Err(err), Err(ClientError::Canceled { connection_reused, diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -561,18 +548,7 @@ where C: Connect<Error=io::Error>, /// Construct the Client with this configuration. #[inline] pub fn build(self) -> Client<C, B> { - Client::configured(self, Exec::Default) - } - - /// Construct a Client with this configuration and an executor. - /// - /// The executor will be used to spawn "background" connection tasks - /// to drive requests and responses. - pub fn executor<E>(self, executor: E) -> Client<C, B> - where - E: Executor<Background> + Send + Sync + 'static, - { - Client::configured(self, Exec::new(executor)) + Client::configured(self) } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -590,21 +566,6 @@ where } self.connector(connector).build() } - - /// Construct a Client with this configuration and an executor. - /// - /// The executor will be used to spawn "background" connection tasks - /// to drive requests and responses. - pub fn build_with_executor<E>(self, handle: &Handle, executor: E) -> Client<HttpConnector, B> - where - E: Executor<Background> + Send + Sync + 'static, - { - let mut connector = HttpConnector::new(4, handle); - if self.keep_alive { - connector.set_keepalive(self.keep_alive_timeout); - } - self.connector(connector).executor(executor) - } } impl<C, B> fmt::Debug for Config<C, B> { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -629,68 +590,15 @@ impl<C: Clone, B> Clone for Config<C, B> { } -// ===== impl Exec ===== - -#[derive(Clone)] -enum Exec { - Default, - Executor(Arc<Executor<Background> + Send + Sync>), -} - - -impl Exec { - pub(crate) fn new<E: Executor<Background> + Send + Sync + 'static>(executor: E) -> Exec { - Exec::Executor(Arc::new(executor)) - } - - fn execute<F>(&self, fut: F) -> io::Result<()> - where - F: Future<Item=(), Error=()> + Send + 'static, - { - match *self { - Exec::Default => spawn(fut), - Exec::Executor(ref e) => { - e.execute(bg(Box::new(fut))) - .map_err(|err| { - debug!("executor error: {:?}", err.kind()); - io::Error::new( - io::ErrorKind::Other, - "executor error", - ) - })? - }, - } - Ok(()) - } -} - -// ===== impl Background ===== - -// The types inside this module are not exported out of the crate, -// so they are in essence un-nameable. -mod background { - use futures::{Future, Poll}; - - // This is basically `impl Future`, since the type is un-nameable, - // and only implementeds `Future`. - #[allow(missing_debug_implementations)] - pub struct Background { - inner: Box<Future<Item=(), Error=()> + Send>, - } - - pub fn bg(fut: Box<Future<Item=(), Error=()> + Send>) -> Background { - Background { - inner: fut, - } - } - - impl Future for Background { - type Item = (); - type Error = (); - - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - self.inner.poll() - } +fn execute<F>(fut: F, cx: &mut task::Context) -> Result<(), ::Error> + where F: Future<Item=(), Error=Never> + Send + 'static, +{ + if let Some(executor) = cx.executor() { + executor.spawn(Box::new(fut)).map_err(|err| { + debug!("executor error: {:?}", err); + ::Error::Executor + }) + } else { + Err(::Error::Executor) } } - diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -4,14 +4,13 @@ use std::ops::{Deref, DerefMut}; use std::sync::{Arc, Mutex, Weak}; use std::time::{Duration, Instant}; -use futures::{Future, Async, Poll, Stream}; -use futures::sync::oneshot; +use futures::{Future, Async, Never, Poll, Stream}; +use futures::channel::oneshot; +use futures::task; use futures_timer::Interval; -use super::Exec; - -pub struct Pool<T> { - inner: Arc<Mutex<PoolInner<T>>>, +pub(super) struct Pool<T> { + inner: Arc<Mutex<PoolInner<T>>> } // Before using a pooled connection, make sure the sender is not dead. diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -48,7 +47,7 @@ struct PoolInner<T> { } impl<T> Pool<T> { - pub fn new(enabled: bool, timeout: Option<Duration>) -> Pool<T> { + pub(super) fn new(enabled: bool, timeout: Option<Duration>) -> Pool<T> { Pool { inner: Arc::new(Mutex::new(PoolInner { enabled: enabled, diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -56,7 +55,7 @@ impl<T> Pool<T> { parked: HashMap::new(), timeout: timeout, expired_timer_spawned: false, - })), + })) } } } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -67,6 +66,7 @@ impl<T: Closed> Pool<T> { key: Arc::new(key.to_owned()), pool: self.clone(), parked: None, + spawned_expired_interval: false } } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -221,38 +221,38 @@ impl<T: Closed> PoolInner<T> { impl<T: Closed + Send + 'static> Pool<T> { - pub(super) fn spawn_expired_interval(&self, exec: &Exec) { + fn spawn_expired_interval(&mut self, cx: &mut task::Context) -> Result<(), ::Error> { let dur = { let mut inner = self.inner.lock().unwrap(); if !inner.enabled { - return; + return Ok(()); } if inner.expired_timer_spawned { - return; + return Ok(()); } inner.expired_timer_spawned = true; if let Some(dur) = inner.timeout { dur } else { - return + return Ok(()); } }; let interval = Interval::new(dur); - exec.execute(IdleInterval { + super::execute(IdleInterval { interval: interval, pool: Arc::downgrade(&self.inner), - }).unwrap(); + }, cx) } } impl<T> Clone for Pool<T> { fn clone(&self) -> Pool<T> { Pool { - inner: self.inner.clone(), + inner: self.inner.clone() } } } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -322,22 +322,23 @@ pub struct Checkout<T> { key: Arc<String>, pool: Pool<T>, parked: Option<oneshot::Receiver<T>>, + spawned_expired_interval: bool } struct NotParked; impl<T: Closed> Checkout<T> { - fn poll_parked(&mut self) -> Poll<Pooled<T>, NotParked> { + fn poll_parked(&mut self, cx: &mut task::Context) -> Poll<Pooled<T>, NotParked> { let mut drop_parked = false; if let Some(ref mut rx) = self.parked { - match rx.poll() { + match rx.poll(cx) { Ok(Async::Ready(value)) => { if !value.is_closed() { return Ok(Async::Ready(self.pool.reuse(&self.key, value))); } drop_parked = true; }, - Ok(Async::NotReady) => return Ok(Async::NotReady), + Ok(Async::Pending) => return Ok(Async::Pending), Err(_canceled) => drop_parked = true, } } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -347,22 +348,27 @@ impl<T: Closed> Checkout<T> { Err(NotParked) } - fn park(&mut self) { + fn park(&mut self, cx: &mut task::Context) { if self.parked.is_none() { let (tx, mut rx) = oneshot::channel(); - let _ = rx.poll(); // park this task + let _ = rx.poll(cx); // park this task self.pool.park(self.key.clone(), tx); self.parked = Some(rx); } } } -impl<T: Closed> Future for Checkout<T> { +impl<T: Closed + Send + 'static> Future for Checkout<T> { type Item = Pooled<T>; type Error = ::Error; - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - match self.poll_parked() { + fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> { + if !self.spawned_expired_interval { + self.pool.spawn_expired_interval(cx)?; + self.spawned_expired_interval = true; + } + + match self.poll_parked(cx) { Ok(async) => return Ok(async), Err(_not_parked) => (), } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -372,8 +378,8 @@ impl<T: Closed> Future for Checkout<T> { if let Some(pooled) = entry { Ok(Async::Ready(pooled)) } else { - self.park(); - Ok(Async::NotReady) + self.park(cx); + Ok(Async::Pending) } } } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -409,11 +415,11 @@ struct IdleInterval<T> { impl<T: Closed + 'static> Future for IdleInterval<T> { type Item = (); - type Error = (); + type Error = Never; - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> { loop { - try_ready!(self.interval.poll().map_err(|_| unreachable!("interval cannot error"))); + try_ready!(self.interval.poll_next(cx).map_err(|_| unreachable!("interval cannot error"))); if let Some(inner) = self.pool.upgrade() { if let Ok(mut inner) = inner.lock() { diff --git a/src/common/mod.rs /dev/null --- a/src/common/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -#[derive(Debug)] -pub enum Never {} diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -21,7 +21,8 @@ use self::Error::{ Io, TooLarge, Incomplete, - Utf8 + Utf8, + Executor }; /// Result type often returned from methods that can have hyper `Error`s. diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -56,6 +57,8 @@ pub enum Error { Io(IoError), /// Parsing a field as string failed Utf8(Utf8Error), + /// Executing a future failed + Executor, #[doc(hidden)] __Nonexhaustive(Void) diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -127,6 +130,7 @@ impl StdError for Error { Cancel(ref e) => e.description(), Io(ref e) => e.description(), Utf8(ref e) => e.description(), + Executor => "executor is missing or failed to spawn", Error::__Nonexhaustive(..) => unreachable!(), } } diff --git /dev/null b/src/executor.rs new file mode 100644 --- /dev/null +++ b/src/executor.rs @@ -0,0 +1,17 @@ +use futures::executor::Executor; + +pub(crate) trait CloneBoxedExecutor: Executor + Send + Sync { + fn clone_boxed(&self) -> Box<CloneBoxedExecutor + Send + Sync>; +} + +impl<E: Executor + Clone + Send + Sync + 'static> CloneBoxedExecutor for E { + fn clone_boxed(&self) -> Box<CloneBoxedExecutor + Send + Sync> { + Box::new(self.clone()) + } +} + +impl Clone for Box<CloneBoxedExecutor> { + fn clone(&self) -> Self { + self.clone_boxed() + } +} diff --git a/src/headers.rs b/src/headers.rs --- a/src/headers.rs +++ b/src/headers.rs @@ -129,7 +129,7 @@ fn eq_ascii(left: &str, right: &str) -> bool { // compiler says this trait is unused. // // Once our minimum Rust compiler version is >=1.23, this can be removed. - #[allow(unused)] + #[allow(unused, deprecated)] use std::ascii::AsciiExt; left.eq_ignore_ascii_case(right) diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -18,7 +18,6 @@ extern crate bytes; #[macro_use] extern crate futures; -extern crate futures_cpupool; extern crate futures_timer; extern crate http; extern crate httparse; diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -3,10 +3,10 @@ use std::cmp; use std::io::{self, Read, Write}; use std::sync::{Arc, Mutex}; -use bytes::Buf; use futures::{Async, Poll}; -use futures::task::{self, Task}; -use tokio_io::{AsyncRead, AsyncWrite}; +use futures::task; +use futures::io::{AsyncRead, AsyncWrite}; +use iovec::IoVec; use ::client::connect::{Connect, Connected, Destination}; diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -77,7 +77,7 @@ pub struct AsyncIo<T> { max_read_vecs: usize, num_writes: usize, park_tasks: bool, - task: Option<Task>, + task: Option<task::Waker>, } impl<T> AsyncIo<T> { diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -99,7 +99,7 @@ impl<T> AsyncIo<T> { self.bytes_until_block = bytes; if let Some(task) = self.task.take() { - task.notify(); + task.wake(); } } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -130,12 +130,12 @@ impl<T> AsyncIo<T> { self.num_writes } - fn would_block(&mut self) -> io::Error { + fn would_block<X, E>(&mut self, cx: &mut task::Context) -> Poll<X, E> { self.blocked = true; if self.park_tasks { - self.task = Some(task::current()); + self.task = Some(cx.waker().clone()); } - io::ErrorKind::WouldBlock.into() + Ok(Async::Pending) } } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -159,118 +159,101 @@ impl AsyncIo<MockCursor> { } } -impl<T: Read + Write> AsyncIo<T> { - fn write_no_vecs<B: Buf>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { - if !buf.has_remaining() { - return Ok(Async::Ready(0)); - } - - let n = try_nb!(self.write(buf.bytes())); - buf.advance(n); - Ok(Async::Ready(n)) - } -} - impl<S: AsRef<[u8]>, T: AsRef<[u8]>> PartialEq<S> for AsyncIo<T> { fn eq(&self, other: &S) -> bool { self.inner.as_ref() == other.as_ref() } } - -impl<T: Read> Read for AsyncIo<T> { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { +impl<T: Read> AsyncRead for AsyncIo<T> { + fn poll_read(&mut self, cx: &mut task::Context, buf: &mut [u8]) -> Poll<usize, io::Error> { self.blocked = false; if let Some(err) = self.error.take() { Err(err) } else if self.bytes_until_block == 0 { - Err(self.would_block()) + self.would_block(cx) } else { let n = cmp::min(self.bytes_until_block, buf.len()); let n = try!(self.inner.read(&mut buf[..n])); self.bytes_until_block -= n; - Ok(n) + Ok(Async::Ready(n)) } } } -impl<T: Write> Write for AsyncIo<T> { - fn write(&mut self, data: &[u8]) -> io::Result<usize> { +impl<T: Read + Write> AsyncIo<T> { + fn write_no_vecs(&mut self, cx: &mut task::Context, buf: &[u8]) -> Poll<usize, io::Error> { + if buf.len() == 0 { + return Ok(Async::Ready(0)); + } + + self.poll_write(cx, buf) + } +} + +impl<T: Read + Write> AsyncWrite for AsyncIo<T> { + fn poll_write(&mut self, cx: &mut task::Context, buf: &[u8]) -> Poll<usize, io::Error> { self.num_writes += 1; if let Some(err) = self.error.take() { trace!("AsyncIo::write error"); Err(err) } else if self.bytes_until_block == 0 { trace!("AsyncIo::write would block"); - Err(self.would_block()) + self.would_block(cx) } else { - trace!("AsyncIo::write; {} bytes", data.len()); + trace!("AsyncIo::write; {} bytes", buf.len()); self.flushed = false; - let n = cmp::min(self.bytes_until_block, data.len()); - let n = try!(self.inner.write(&data[..n])); + let n = cmp::min(self.bytes_until_block, buf.len()); + let n = try!(self.inner.write(&buf[..n])); self.bytes_until_block -= n; - Ok(n) + Ok(Async::Ready(n)) } } - fn flush(&mut self) -> io::Result<()> { + fn poll_flush(&mut self, _cx: &mut task::Context) -> Poll<(), io::Error> { self.flushed = true; - self.inner.flush() + try!(self.inner.flush()); + Ok(Async::Ready(())) } -} - -impl<T: Read + Write> AsyncRead for AsyncIo<T> { -} -impl<T: Read + Write> AsyncWrite for AsyncIo<T> { - fn shutdown(&mut self) -> Poll<(), io::Error> { + fn poll_close(&mut self, _cx: &mut task::Context) -> Poll<(), io::Error> { Ok(().into()) } - fn write_buf<B: Buf>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { + fn poll_vectored_write(&mut self, cx: &mut task::Context, vec: &[&IoVec]) -> Poll<usize, io::Error> { if self.max_read_vecs == 0 { - return self.write_no_vecs(buf); + if let Some(ref first_iovec) = vec.get(0) { + return self.write_no_vecs(cx, &*first_iovec) + } else { + return Ok(Async::Ready(0)); + } } - let r = { - static DUMMY: &[u8] = &[0]; - let mut bufs = [From::from(DUMMY); READ_VECS_CNT]; - let i = Buf::bytes_vec(&buf, &mut bufs[..self.max_read_vecs]); - let mut n = 0; - let mut ret = Ok(0); - // each call to write() will increase our count, but we assume - // that if iovecs are used, its really only 1 write call. - let num_writes = self.num_writes; - for iovec in &bufs[..i] { - match self.write(iovec) { - Ok(num) => { - n += num; - ret = Ok(n); - }, - Err(e) => { - if e.kind() == io::ErrorKind::WouldBlock { - if let Ok(0) = ret { - ret = Err(e); - } - } else { - ret = Err(e); - } - break; + + let mut n = 0; + let mut ret = Ok(Async::Ready(0)); + // each call to poll_write() will increase our count, but we assume + // that if iovecs are used, its really only 1 write call. + let num_writes = self.num_writes; + for buf in vec { + match self.poll_write(cx, &buf) { + Ok(Async::Ready(num)) => { + n += num; + ret = Ok(Async::Ready(n)); + }, + Ok(Async::Pending) => { + if let Ok(Async::Ready(0)) = ret { + ret = Ok(Async::Pending); } + break; + }, + Err(err) => { + ret = Err(err); + break; } } - self.num_writes = num_writes + 1; - ret - }; - match r { - Ok(n) => { - Buf::advance(buf, n); - Ok(Async::Ready(n)) - } - Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { - Ok(Async::NotReady) - } - Err(e) => Err(e), } + self.num_writes = num_writes + 1; + ret } } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -287,48 +270,34 @@ pub struct Duplex { } struct DuplexInner { - handle_read_task: Option<Task>, + handle_read_task: Option<task::Waker>, read: AsyncIo<MockCursor>, write: AsyncIo<MockCursor>, } -impl Read for Duplex { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.inner.lock().unwrap().read.read(buf) +impl AsyncRead for Duplex { + fn poll_read(&mut self, cx: &mut task::Context, buf: &mut [u8]) -> Poll<usize, io::Error> { + self.inner.lock().unwrap().read.poll_read(cx, buf) } } -impl Write for Duplex { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { +impl AsyncWrite for Duplex { + fn poll_write(&mut self, cx: &mut task::Context, buf: &[u8]) -> Poll<usize, io::Error> { let mut inner = self.inner.lock().unwrap(); if let Some(task) = inner.handle_read_task.take() { trace!("waking DuplexHandle read"); - task.notify(); + task.wake(); } - inner.write.write(buf) + inner.write.poll_write(cx, buf) } - fn flush(&mut self) -> io::Result<()> { - self.inner.lock().unwrap().write.flush() + fn poll_flush(&mut self, cx: &mut task::Context) -> Poll<(), io::Error> { + self.inner.lock().unwrap().write.poll_flush(cx) } -} - -impl AsyncRead for Duplex { -} - -impl AsyncWrite for Duplex { - fn shutdown(&mut self) -> Poll<(), io::Error> { + fn poll_close(&mut self, _cx: &mut task::Context) -> Poll<(), io::Error> { Ok(().into()) } - - fn write_buf<B: Buf>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { - let mut inner = self.inner.lock().unwrap(); - if let Some(task) = inner.handle_read_task.take() { - task.notify(); - } - inner.write.write_buf(buf) - } } pub struct DuplexHandle { diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -336,13 +305,13 @@ pub struct DuplexHandle { } impl DuplexHandle { - pub fn read(&self, buf: &mut [u8]) -> Poll<usize, io::Error> { + pub fn read(&self, cx: &mut task::Context, buf: &mut [u8]) -> Poll<usize, io::Error> { let mut inner = self.inner.lock().unwrap(); assert!(buf.len() >= inner.write.inner.len()); if inner.write.inner.is_empty() { trace!("DuplexHandle read parking"); - inner.handle_read_task = Some(task::current()); - return Ok(Async::NotReady); + inner.handle_read_task = Some(cx.waker().clone()); + return Ok(Async::Pending); } inner.write.inner.vec.truncate(0); Ok(Async::Ready(inner.write.inner.len())) diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -3,8 +3,9 @@ use std::borrow::Cow; use std::fmt; use bytes::Bytes; -use futures::{Async, Future, Poll, Stream}; -use futures::sync::{mpsc, oneshot}; +use futures::{Async, Future, Poll, Stream, StreamExt}; +use futures::task; +use futures::channel::{mpsc, oneshot}; use http::HeaderMap; use super::Chunk; diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -24,14 +25,14 @@ pub trait Entity { /// /// Similar to `Stream::poll_next`, this yields `Some(Data)` until /// the body ends, when it yields `None`. - fn poll_data(&mut self) -> Poll<Option<Self::Data>, Self::Error>; + fn poll_data(&mut self, cx: &mut task::Context) -> Poll<Option<Self::Data>, Self::Error>; /// Poll for an optional **single** `HeaderMap` of trailers. /// /// This should **only** be called after `poll_data` has ended. /// /// Note: Trailers aren't currently used for HTTP/1, only for HTTP/2. - fn poll_trailers(&mut self) -> Poll<Option<HeaderMap>, Self::Error> { + fn poll_trailers(&mut self, _cx: &mut task::Context) -> Poll<Option<HeaderMap>, Self::Error> { Ok(Async::Ready(None)) } diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -67,12 +68,12 @@ impl<E: Entity> Entity for Box<E> { type Data = E::Data; type Error = E::Error; - fn poll_data(&mut self) -> Poll<Option<Self::Data>, Self::Error> { - (**self).poll_data() + fn poll_data(&mut self, cx: &mut task::Context) -> Poll<Option<Self::Data>, Self::Error> { + (**self).poll_data(cx) } - fn poll_trailers(&mut self) -> Poll<Option<HeaderMap>, Self::Error> { - (**self).poll_trailers() + fn poll_trailers(&mut self, cx: &mut task::Context) -> Poll<Option<HeaderMap>, Self::Error> { + (**self).poll_trailers(cx) } fn is_end_stream(&self) -> bool { diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -96,10 +97,10 @@ impl<E: Entity> Stream for EntityStream<E> { type Item = E::Data; type Error = E::Error; - fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { + fn poll_next(&mut self, cx: &mut task::Context) -> Poll<Option<Self::Item>, Self::Error> { loop { if self.is_data_eof { - return self.entity.poll_trailers() + return self.entity.poll_trailers(cx) .map(|async| { async.map(|_opt| { // drop the trailers and return that Stream is done diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -108,7 +109,7 @@ impl<E: Entity> Stream for EntityStream<E> { }); } - let opt = try_ready!(self.entity.poll_data()); + let opt = try_ready!(self.entity.poll_data(cx)); if let Some(data) = opt { return Ok(Async::Ready(Some(data))); } else { diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -211,14 +212,14 @@ impl Body { /// ``` /// # extern crate futures; /// # extern crate hyper; - /// # use futures::{Future, Stream}; + /// # use futures::{FutureExt, StreamExt}; /// # use hyper::{Body, Request}; /// # fn request_concat(some_req: Request<Body>) { /// let req: Request<Body> = some_req; /// let body = req.into_body(); /// /// let stream = body.into_stream(); - /// stream.concat2() + /// stream.concat() /// .map(|buf| { /// println!("body length: {}", buf.len()); /// }); diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -267,15 +268,15 @@ impl Entity for Body { type Data = Chunk; type Error = ::Error; - fn poll_data(&mut self) -> Poll<Option<Self::Data>, Self::Error> { + fn poll_data(&mut self, cx: &mut task::Context) -> Poll<Option<Self::Data>, Self::Error> { match self.kind { - Kind::Chan { ref mut rx, .. } => match rx.poll().expect("mpsc cannot error") { + Kind::Chan { ref mut rx, .. } => match rx.poll_next(cx).expect("mpsc cannot error") { Async::Ready(Some(Ok(chunk))) => Ok(Async::Ready(Some(chunk))), Async::Ready(Some(Err(err))) => Err(err), Async::Ready(None) => Ok(Async::Ready(None)), - Async::NotReady => Ok(Async::NotReady), + Async::Pending => Ok(Async::Pending), }, - Kind::Wrapped(ref mut s) => s.poll(), + Kind::Wrapped(ref mut s) => s.poll_next(cx), Kind::Once(ref mut val) => Ok(Async::Ready(val.take())), Kind::Empty => Ok(Async::Ready(None)), } diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -310,13 +311,13 @@ impl fmt::Debug for Body { impl Sender { /// Check to see if this `Sender` can send more data. - pub fn poll_ready(&mut self) -> Poll<(), ()> { - match self.close_rx.poll() { + pub fn poll_ready(&mut self, cx: &mut task::Context) -> Poll<(), ()> { + match self.close_rx.poll(cx) { Ok(Async::Ready(())) | Err(_) => return Err(()), - Ok(Async::NotReady) => (), + Ok(Async::Pending) => (), } - self.tx.poll_ready().map_err(|_| ()) + self.tx.poll_ready(cx).map_err(|_| ()) } /// Sends data on this channel. diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -3,10 +3,10 @@ use std::io::{self}; use std::marker::PhantomData; use bytes::Bytes; -use futures::{Async, AsyncSink, Poll, StartSend}; -use futures::task::Task; +use futures::{Async, Poll}; +use futures::task; +use futures::io::{AsyncRead, AsyncWrite}; use http::{Method, Version}; -use tokio_io::{AsyncRead, AsyncWrite}; use proto::{BodyLength, Chunk, Decode, Http1Transaction, MessageHead}; use super::io::{Cursor, Buffered}; diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -113,14 +113,14 @@ where I: AsyncRead + AsyncWrite, T::should_error_on_parse_eof() && !self.state.is_idle() } - pub fn read_head(&mut self) -> Poll<Option<(MessageHead<T::Incoming>, bool)>, ::Error> { + pub fn read_head(&mut self, cx: &mut task::Context) -> Poll<Option<(MessageHead<T::Incoming>, bool)>, ::Error> { debug_assert!(self.can_read_head()); trace!("Conn::read_head"); loop { - let (version, head) = match self.io.parse::<T>() { + let (version, head) = match self.io.parse::<T>(cx) { Ok(Async::Ready(head)) => (head.version, head), - Ok(Async::NotReady) => return Ok(Async::NotReady), + Ok(Async::Pending) => return Ok(Async::Pending), Err(e) => { // If we are currently waiting on a message, then an empty // message should be reported as an error. If not, it is just diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -132,7 +132,7 @@ where I: AsyncRead + AsyncWrite, return if was_mid_parse || must_error { debug!("parse error ({}) with {} bytes", e, self.io.read_buf().len()); self.on_parse_error(e) - .map(|()| Async::NotReady) + .map(|()| Async::Pending) } else { debug!("read eof"); Ok(Async::Ready(None)) diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -169,7 +169,7 @@ where I: AsyncRead + AsyncWrite, debug!("decoder error = {:?}", e); self.state.close_read(); return self.on_parse_error(e) - .map(|()| Async::NotReady); + .map(|()| Async::Pending); } }; diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -193,20 +193,20 @@ where I: AsyncRead + AsyncWrite, self.state.reading = reading; } if !body { - self.try_keep_alive(); + self.try_keep_alive(cx); } return Ok(Async::Ready(Some((head, body)))); } } - pub fn read_body(&mut self) -> Poll<Option<Chunk>, io::Error> { + pub fn read_body(&mut self, cx: &mut task::Context) -> Poll<Option<Chunk>, io::Error> { debug_assert!(self.can_read_body()); trace!("Conn::read_body"); let (reading, ret) = match self.state.reading { Reading::Body(ref mut decoder) => { - match decoder.decode(&mut self.io) { + match decoder.decode(&mut self.io, cx) { Ok(Async::Ready(slice)) => { let (reading, chunk) = if !slice.is_empty() { return Ok(Async::Ready(Some(Chunk::from(slice)))); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -222,7 +222,7 @@ where I: AsyncRead + AsyncWrite, }; (reading, Ok(Async::Ready(chunk))) }, - Ok(Async::NotReady) => return Ok(Async::NotReady), + Ok(Async::Pending) => return Ok(Async::Pending), Err(e) => { trace!("decode stream error: {}", e); (Reading::Closed, Err(e)) diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -233,19 +233,19 @@ where I: AsyncRead + AsyncWrite, }; self.state.reading = reading; - self.try_keep_alive(); + self.try_keep_alive(cx); ret } - pub fn read_keep_alive(&mut self) -> Result<(), ::Error> { + pub fn read_keep_alive(&mut self, cx: &mut task::Context) -> Result<(), ::Error> { debug_assert!(!self.can_read_head() && !self.can_read_body()); trace!("read_keep_alive; is_mid_message={}", self.is_mid_message()); if self.is_mid_message() { - self.maybe_park_read(); + self.maybe_park_read(cx); } else { - self.require_empty_read()?; + self.require_empty_read(cx)?; } Ok(()) } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -257,18 +257,19 @@ where I: AsyncRead + AsyncWrite, } } - fn maybe_park_read(&mut self) { + fn maybe_park_read(&mut self, cx: &mut task::Context) { if !self.io.is_read_blocked() { // the Io object is ready to read, which means it will never alert // us that it is ready until we drain it. However, we're currently // finished reading, so we need to park the task to be able to // wake back up later when more reading should happen. + let current_waker = cx.waker(); let park = self.state.read_task.as_ref() - .map(|t| !t.will_notify_current()) + .map(|t| !t.will_wake(current_waker)) .unwrap_or(true); if park { trace!("parking current task"); - self.state.read_task = Some(::futures::task::current()); + self.state.read_task = Some(current_waker.clone()); } } } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -277,14 +278,14 @@ where I: AsyncRead + AsyncWrite, // // This should only be called for Clients wanting to enter the idle // state. - fn require_empty_read(&mut self) -> io::Result<()> { + fn require_empty_read(&mut self, cx: &mut task::Context) -> io::Result<()> { assert!(!self.can_read_head() && !self.can_read_body()); if !self.io.read_buf().is_empty() { debug!("received an unexpected {} bytes", self.io.read_buf().len()); Err(io::Error::new(io::ErrorKind::InvalidData, "unexpected bytes after message ended")) } else { - match self.try_io_read()? { + match self.try_io_read(cx)? { Async::Ready(0) => { // case handled in try_io_read Ok(()) diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -298,15 +299,15 @@ where I: AsyncRead + AsyncWrite, }; Err(io::Error::new(io::ErrorKind::InvalidData, desc)) }, - Async::NotReady => { + Async::Pending => { Ok(()) }, } } } - fn try_io_read(&mut self) -> Poll<usize, io::Error> { - match self.io.read_from_io() { + fn try_io_read(&mut self, cx: &mut task::Context) -> Poll<usize, io::Error> { + match self.io.read_from_io(cx) { Ok(Async::Ready(0)) => { trace!("try_io_read; found EOF on connection: {:?}", self.state); let must_error = self.should_error_on_eof(); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -328,8 +329,8 @@ where I: AsyncRead + AsyncWrite, Ok(Async::Ready(n)) => { Ok(Async::Ready(n)) }, - Ok(Async::NotReady) => { - Ok(Async::NotReady) + Ok(Async::Pending) => { + Ok(Async::Pending) }, Err(e) => { self.state.close(); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -339,8 +340,8 @@ where I: AsyncRead + AsyncWrite, } - fn maybe_notify(&mut self) { - // its possible that we returned NotReady from poll() without having + fn maybe_notify(&mut self, cx: &mut task::Context) { + // its possible that we returned Pending from poll() without having // exhausted the underlying Io. We would have done this when we // determined we couldn't keep reading until we knew how writing // would finish. diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -366,9 +367,9 @@ where I: AsyncRead + AsyncWrite, if !self.io.is_read_blocked() { if wants_read && self.io.read_buf().is_empty() { - match self.io.read_from_io() { + match self.io.read_from_io(cx) { Ok(Async::Ready(_)) => (), - Ok(Async::NotReady) => { + Ok(Async::Pending) => { trace!("maybe_notify; read_from_io blocked"); return }, diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -380,16 +381,16 @@ where I: AsyncRead + AsyncWrite, } if let Some(ref task) = self.state.read_task { trace!("maybe_notify; notifying task"); - task.notify(); + task.wake(); } else { trace!("maybe_notify; no task to notify"); } } } - fn try_keep_alive(&mut self) { + fn try_keep_alive(&mut self, cx: &mut task::Context) { self.state.try_keep_alive(); - self.maybe_notify(); + self.maybe_notify(cx); } pub fn can_write_head(&self) -> bool { diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -475,17 +476,15 @@ where I: AsyncRead + AsyncWrite, } } - pub fn write_body(&mut self, chunk: Option<B>) -> StartSend<Option<B>, io::Error> { + pub fn write_body(&mut self, _cx: &mut task::Context, chunk: Option<B>) -> Poll<(), io::Error> { debug_assert!(self.can_write_body()); if !self.can_buffer_body() { - if let Async::NotReady = self.flush()? { - // if chunk is Some(&[]), aka empty, whatever, just skip it - if chunk.as_ref().map(|c| c.as_ref().is_empty()).unwrap_or(false) { - return Ok(AsyncSink::Ready); - } else { - return Ok(AsyncSink::NotReady(chunk)); - } + // if chunk is Some(&[]), aka empty, whatever, just skip it + if chunk.as_ref().map(|c| c.as_ref().is_empty()).unwrap_or(true) { + return Ok(Async::Ready(())); + } else { + return Err(io::Error::new(io::ErrorKind::Other, "tried to write chunk when body can't buffer")); } } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -493,7 +492,7 @@ where I: AsyncRead + AsyncWrite, Writing::Body(ref mut encoder) => { if let Some(chunk) = chunk { if chunk.as_ref().is_empty() { - return Ok(AsyncSink::Ready); + return Ok(Async::Ready(())); } let encoded = encoder.encode(Cursor::new(chunk)); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -506,7 +505,7 @@ where I: AsyncRead + AsyncWrite, Writing::KeepAlive } } else { - return Ok(AsyncSink::Ready); + return Ok(Async::Ready(())); } } else { // end of stream, that means we should try to eof diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -529,7 +528,7 @@ where I: AsyncRead + AsyncWrite, }; self.state.writing = state; - Ok(AsyncSink::Ready) + Ok(Async::Ready(())) } // When we get a parse error, depending on what side we are, we might be able diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -553,16 +552,16 @@ where I: AsyncRead + AsyncWrite, Err(err) } - pub fn flush(&mut self) -> Poll<(), io::Error> { - try_ready!(self.io.flush()); - self.try_keep_alive(); + pub fn flush(&mut self, cx: &mut task::Context) -> Poll<(), io::Error> { + try_ready!(self.io.flush(cx)); + self.try_keep_alive(cx); trace!("flushed {:?}", self.state); Ok(Async::Ready(())) } - pub fn shutdown(&mut self) -> Poll<(), io::Error> { - match self.io.io_mut().shutdown() { - Ok(Async::NotReady) => Ok(Async::NotReady), + pub fn shutdown(&mut self, cx: &mut task::Context) -> Poll<(), io::Error> { + match self.io.io_mut().poll_close(cx) { + Ok(Async::Pending) => Ok(Async::Pending), Ok(Async::Ready(())) => { trace!("shut down IO"); Ok(Async::Ready(())) diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -612,7 +611,7 @@ struct State { error: Option<::Error>, keep_alive: KA, method: Option<Method>, - read_task: Option<Task>, + read_task: Option<task::Waker>, reading: Reading, writing: Writing, version: Version, diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -4,6 +4,7 @@ use std::usize; use std::io; use futures::{Async, Poll}; +use futures::task; use bytes::Bytes; use super::io::MemRead; diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -84,7 +85,7 @@ impl Decoder { } } - pub fn decode<R: MemRead>(&mut self, body: &mut R) -> Poll<Bytes, io::Error> { + pub fn decode<R: MemRead>(&mut self, body: &mut R, cx: &mut task::Context) -> Poll<Bytes, io::Error> { trace!("decode; state={:?}", self.kind); match self.kind { Length(ref mut remaining) => { diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -92,7 +93,7 @@ impl Decoder { Ok(Async::Ready(Bytes::new())) } else { let to_read = *remaining as usize; - let buf = try_ready!(body.read_mem(to_read)); + let buf = try_ready!(body.read_mem(cx, to_read)); let num = buf.as_ref().len() as u64; if num > *remaining { *remaining = 0; diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -108,7 +109,7 @@ impl Decoder { loop { let mut buf = None; // advances the chunked state - *state = try_ready!(state.step(body, size, &mut buf)); + *state = try_ready!(state.step(body, cx, size, &mut buf)); if *state == ChunkedState::End { trace!("end of chunked"); return Ok(Async::Ready(Bytes::new())); diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -125,7 +126,7 @@ impl Decoder { // 8192 chosen because its about 2 packets, there probably // won't be that much available, so don't have MemReaders // allocate buffers to big - let slice = try_ready!(body.read_mem(8192)); + let slice = try_ready!(body.read_mem(cx, 8192)); *is_eof = slice.is_empty(); Ok(Async::Ready(slice)) } diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -152,8 +153,8 @@ impl fmt::Display for Decoder { } macro_rules! byte ( - ($rdr:ident) => ({ - let buf = try_ready!($rdr.read_mem(1)); + ($rdr:ident, $cx:ident) => ({ + let buf = try_ready!($rdr.read_mem($cx, 1)); if !buf.is_empty() { buf[0] } else { diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -166,27 +167,28 @@ macro_rules! byte ( impl ChunkedState { fn step<R: MemRead>(&self, body: &mut R, + cx: &mut task::Context, size: &mut u64, buf: &mut Option<Bytes>) -> Poll<ChunkedState, io::Error> { use self::ChunkedState::*; match *self { - Size => ChunkedState::read_size(body, size), - SizeLws => ChunkedState::read_size_lws(body), - Extension => ChunkedState::read_extension(body), - SizeLf => ChunkedState::read_size_lf(body, *size), - Body => ChunkedState::read_body(body, size, buf), - BodyCr => ChunkedState::read_body_cr(body), - BodyLf => ChunkedState::read_body_lf(body), - EndCr => ChunkedState::read_end_cr(body), - EndLf => ChunkedState::read_end_lf(body), + Size => ChunkedState::read_size(body, cx, size), + SizeLws => ChunkedState::read_size_lws(body, cx), + Extension => ChunkedState::read_extension(body, cx), + SizeLf => ChunkedState::read_size_lf(body, cx, *size), + Body => ChunkedState::read_body(body, cx, size, buf), + BodyCr => ChunkedState::read_body_cr(body, cx), + BodyLf => ChunkedState::read_body_lf(body, cx), + EndCr => ChunkedState::read_end_cr(body, cx), + EndLf => ChunkedState::read_end_lf(body, cx), End => Ok(Async::Ready(ChunkedState::End)), } } - fn read_size<R: MemRead>(rdr: &mut R, size: &mut u64) -> Poll<ChunkedState, io::Error> { + fn read_size<R: MemRead>(rdr: &mut R, cx: &mut task::Context, size: &mut u64) -> Poll<ChunkedState, io::Error> { trace!("Read chunk hex size"); let radix = 16; - match byte!(rdr) { + match byte!(rdr, cx) { b @ b'0'...b'9' => { *size *= radix; *size += (b - b'0') as u64; diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -209,9 +211,9 @@ impl ChunkedState { } Ok(Async::Ready(ChunkedState::Size)) } - fn read_size_lws<R: MemRead>(rdr: &mut R) -> Poll<ChunkedState, io::Error> { + fn read_size_lws<R: MemRead>(rdr: &mut R, cx: &mut task::Context) -> Poll<ChunkedState, io::Error> { trace!("read_size_lws"); - match byte!(rdr) { + match byte!(rdr, cx) { // LWS can follow the chunk size, but no more digits can come b'\t' | b' ' => Ok(Async::Ready(ChunkedState::SizeLws)), b';' => Ok(Async::Ready(ChunkedState::Extension)), diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -222,16 +224,16 @@ impl ChunkedState { } } } - fn read_extension<R: MemRead>(rdr: &mut R) -> Poll<ChunkedState, io::Error> { + fn read_extension<R: MemRead>(rdr: &mut R, cx: &mut task::Context) -> Poll<ChunkedState, io::Error> { trace!("read_extension"); - match byte!(rdr) { + match byte!(rdr, cx) { b'\r' => Ok(Async::Ready(ChunkedState::SizeLf)), _ => Ok(Async::Ready(ChunkedState::Extension)), // no supported extensions } } - fn read_size_lf<R: MemRead>(rdr: &mut R, size: u64) -> Poll<ChunkedState, io::Error> { + fn read_size_lf<R: MemRead>(rdr: &mut R, cx: &mut task::Context, size: u64) -> Poll<ChunkedState, io::Error> { trace!("Chunk size is {:?}", size); - match byte!(rdr) { + match byte!(rdr, cx) { b'\n' => { if size == 0 { Ok(Async::Ready(ChunkedState::EndCr)) diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -244,7 +246,7 @@ impl ChunkedState { } } - fn read_body<R: MemRead>(rdr: &mut R, + fn read_body<R: MemRead>(rdr: &mut R, cx: &mut task::Context, rem: &mut u64, buf: &mut Option<Bytes>) -> Poll<ChunkedState, io::Error> { diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -257,7 +259,7 @@ impl ChunkedState { }; let to_read = rem_cap; - let slice = try_ready!(rdr.read_mem(to_read)); + let slice = try_ready!(rdr.read_mem(cx, to_read)); let count = slice.len(); if count == 0 { diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -273,27 +275,27 @@ impl ChunkedState { Ok(Async::Ready(ChunkedState::BodyCr)) } } - fn read_body_cr<R: MemRead>(rdr: &mut R) -> Poll<ChunkedState, io::Error> { - match byte!(rdr) { + fn read_body_cr<R: MemRead>(rdr: &mut R, cx: &mut task::Context) -> Poll<ChunkedState, io::Error> { + match byte!(rdr, cx) { b'\r' => Ok(Async::Ready(ChunkedState::BodyLf)), _ => Err(io::Error::new(io::ErrorKind::InvalidInput, "Invalid chunk body CR")), } } - fn read_body_lf<R: MemRead>(rdr: &mut R) -> Poll<ChunkedState, io::Error> { - match byte!(rdr) { + fn read_body_lf<R: MemRead>(rdr: &mut R, cx: &mut task::Context) -> Poll<ChunkedState, io::Error> { + match byte!(rdr, cx) { b'\n' => Ok(Async::Ready(ChunkedState::Size)), _ => Err(io::Error::new(io::ErrorKind::InvalidInput, "Invalid chunk body LF")), } } - fn read_end_cr<R: MemRead>(rdr: &mut R) -> Poll<ChunkedState, io::Error> { - match byte!(rdr) { + fn read_end_cr<R: MemRead>(rdr: &mut R, cx: &mut task::Context) -> Poll<ChunkedState, io::Error> { + match byte!(rdr, cx) { b'\r' => Ok(Async::Ready(ChunkedState::EndLf)), _ => Err(io::Error::new(io::ErrorKind::InvalidInput, "Invalid chunk end CR")), } } - fn read_end_lf<R: MemRead>(rdr: &mut R) -> Poll<ChunkedState, io::Error> { - match byte!(rdr) { + fn read_end_lf<R: MemRead>(rdr: &mut R, cx: &mut task::Context) -> Poll<ChunkedState, io::Error> { + match byte!(rdr, cx) { b'\n' => Ok(Async::Ready(ChunkedState::End)), _ => Err(io::Error::new(io::ErrorKind::InvalidInput, "Invalid chunk end LF")), } diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -2,13 +2,15 @@ use std::io; use bytes::Bytes; use futures::{Async, Future, Poll, Stream}; +use futures::task; +use futures::io::{AsyncRead, AsyncWrite}; use http::{Request, Response, StatusCode}; -use tokio_io::{AsyncRead, AsyncWrite}; -use tokio_service::Service; use proto::body::Entity; use proto::{Body, BodyLength, Conn, Http1Transaction, MessageHead, RequestHead, RequestLine, ResponseHead}; +use ::service::Service; + pub struct Dispatcher<D, Bs, I, B, T> { conn: Conn<I, B, T>, dispatch: D, diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -21,9 +23,9 @@ pub trait Dispatch { type PollItem; type PollBody; type RecvItem; - fn poll_msg(&mut self) -> Poll<Option<(Self::PollItem, Option<Self::PollBody>)>, ::Error>; - fn recv_msg(&mut self, msg: ::Result<(Self::RecvItem, Body)>) -> ::Result<()>; - fn poll_ready(&mut self) -> Poll<(), ()>; + fn poll_msg(&mut self, cx: &mut task::Context) -> Poll<Option<(Self::PollItem, Option<Self::PollBody>)>, ::Error>; + fn recv_msg(&mut self, cx: &mut task::Context, msg: ::Result<(Self::RecvItem, Body)>) -> ::Result<()>; + fn poll_ready(&mut self, cx: &mut task::Context) -> Poll<(), ()>; fn should_poll(&self) -> bool; } diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -69,57 +71,57 @@ where /// The "Future" poll function. Runs this dispatcher until the /// connection is shutdown, or an error occurs. - pub fn poll_until_shutdown(&mut self) -> Poll<(), ::Error> { - self.poll_catch(true) + pub fn poll_until_shutdown(&mut self, cx: &mut task::Context) -> Poll<(), ::Error> { + self.poll_catch(cx, true) } /// Run this dispatcher until HTTP says this connection is done, /// but don't call `AsyncWrite::shutdown` on the underlying IO. /// /// This is useful for HTTP upgrades. - pub fn poll_without_shutdown(&mut self) -> Poll<(), ::Error> { - self.poll_catch(false) + pub fn poll_without_shutdown(&mut self, cx: &mut task::Context) -> Poll<(), ::Error> { + self.poll_catch(cx, false) } - fn poll_catch(&mut self, should_shutdown: bool) -> Poll<(), ::Error> { - self.poll_inner(should_shutdown).or_else(|e| { + fn poll_catch(&mut self, cx: &mut task::Context, should_shutdown: bool) -> Poll<(), ::Error> { + self.poll_inner(cx, should_shutdown).or_else(|e| { // An error means we're shutting down either way. // We just try to give the error to the user, // and close the connection with an Ok. If we // cannot give it to the user, then return the Err. - self.dispatch.recv_msg(Err(e)).map(Async::Ready) + self.dispatch.recv_msg(cx, Err(e)).map(Async::Ready) }) } - fn poll_inner(&mut self, should_shutdown: bool) -> Poll<(), ::Error> { - self.poll_read()?; - self.poll_write()?; - self.poll_flush()?; + fn poll_inner(&mut self, cx: &mut task::Context, should_shutdown: bool) -> Poll<(), ::Error> { + self.poll_read(cx)?; + self.poll_write(cx)?; + self.poll_flush(cx)?; if self.is_done() { if should_shutdown { - try_ready!(self.conn.shutdown()); + try_ready!(self.conn.shutdown(cx)); } self.conn.take_error()?; Ok(Async::Ready(())) } else { - Ok(Async::NotReady) + Ok(Async::Pending) } } - fn poll_read(&mut self) -> Poll<(), ::Error> { + fn poll_read(&mut self, cx: &mut task::Context) -> Poll<(), ::Error> { loop { if self.is_closing { return Ok(Async::Ready(())); } else if self.conn.can_read_head() { - try_ready!(self.poll_read_head()); + try_ready!(self.poll_read_head(cx)); } else if let Some(mut body) = self.body_tx.take() { if self.conn.can_read_body() { - match body.poll_ready() { + match body.poll_ready(cx) { Ok(Async::Ready(())) => (), - Ok(Async::NotReady) => { + Ok(Async::Pending) => { self.body_tx = Some(body); - return Ok(Async::NotReady); + return Ok(Async::Pending); }, Err(_canceled) => { // user doesn't care about the body diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -129,7 +131,7 @@ where return Ok(Async::Ready(())); } } - match self.conn.read_body() { + match self.conn.read_body(cx) { Ok(Async::Ready(Some(chunk))) => { match body.send_data(chunk) { Ok(()) => { diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -147,9 +149,9 @@ where Ok(Async::Ready(None)) => { // just drop, the body will close automatically }, - Ok(Async::NotReady) => { + Ok(Async::Pending) => { self.body_tx = Some(body); - return Ok(Async::NotReady); + return Ok(Async::Pending); } Err(e) => { body.send_error(::Error::Io(e)); diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -159,16 +161,16 @@ where // just drop, the body will close automatically } } else { - return self.conn.read_keep_alive().map(Async::Ready); + return self.conn.read_keep_alive(cx).map(Async::Ready); } } } - fn poll_read_head(&mut self) -> Poll<(), ::Error> { + fn poll_read_head(&mut self, cx: &mut task::Context) -> Poll<(), ::Error> { // can dispatch receive, or does it still care about, an incoming message? - match self.dispatch.poll_ready() { + match self.dispatch.poll_ready(cx) { Ok(Async::Ready(())) => (), - Ok(Async::NotReady) => unreachable!("dispatch not ready when conn is"), + Ok(Async::Pending) => unreachable!("dispatch not ready when conn is"), Err(()) => { trace!("dispatch no longer receiving messages"); self.close(); diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -176,27 +178,27 @@ where } } // dispatch is ready for a message, try to read one - match self.conn.read_head() { + match self.conn.read_head(cx) { Ok(Async::Ready(Some((head, has_body)))) => { let body = if has_body { let (mut tx, rx) = Body::channel(); - let _ = tx.poll_ready(); // register this task if rx is dropped + let _ = tx.poll_ready(cx); // register this task if rx is dropped self.body_tx = Some(tx); rx } else { Body::empty() }; - self.dispatch.recv_msg(Ok((head, body)))?; + self.dispatch.recv_msg(cx, Ok((head, body)))?; Ok(Async::Ready(())) }, Ok(Async::Ready(None)) => { // read eof, conn will start to shutdown automatically Ok(Async::Ready(())) } - Ok(Async::NotReady) => Ok(Async::NotReady), + Ok(Async::Pending) => Ok(Async::Pending), Err(err) => { debug!("read_head error: {}", err); - self.dispatch.recv_msg(Err(err))?; + self.dispatch.recv_msg(cx, Err(err))?; // if here, the dispatcher gave the user the error // somewhere else. we still need to shutdown, but // not as a second error. diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -205,12 +207,12 @@ where } } - fn poll_write(&mut self) -> Poll<(), ::Error> { + fn poll_write(&mut self, cx: &mut task::Context) -> Poll<(), ::Error> { loop { if self.is_closing { return Ok(Async::Ready(())); } else if self.body_rx.is_none() && self.conn.can_write_head() && self.dispatch.should_poll() { - if let Some((head, body)) = try_ready!(self.dispatch.poll_msg()) { + if let Some((head, body)) = try_ready!(self.dispatch.poll_msg(cx)) { let body_type = body.as_ref().map(|body| { body.content_length() .map(BodyLength::Known) diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -223,27 +225,27 @@ where return Ok(Async::Ready(())); } } else if !self.conn.can_buffer_body() { - try_ready!(self.poll_flush()); + try_ready!(self.poll_flush(cx)); } else if let Some(mut body) = self.body_rx.take() { - let chunk = match body.poll_data()? { + let chunk = match body.poll_data(cx)? { Async::Ready(Some(chunk)) => { self.body_rx = Some(body); chunk }, Async::Ready(None) => { if self.conn.can_write_body() { - self.conn.write_body(None)?; + self.conn.write_body(cx, None)?; } continue; }, - Async::NotReady => { + Async::Pending => { self.body_rx = Some(body); - return Ok(Async::NotReady); + return Ok(Async::Pending); } }; if self.conn.can_write_body() { - assert!(self.conn.write_body(Some(chunk))?.is_ready()); + self.conn.write_body(cx, Some(chunk))?; // This allows when chunk is `None`, or `Some([])`. } else if chunk.as_ref().len() == 0 { // ok diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -251,13 +253,13 @@ where warn!("unexpected chunk when body cannot write"); } } else { - return Ok(Async::NotReady); + return Ok(Async::Pending); } } } - fn poll_flush(&mut self) -> Poll<(), ::Error> { - self.conn.flush().map_err(|err| { + fn poll_flush(&mut self, cx: &mut task::Context) -> Poll<(), ::Error> { + self.conn.flush(cx).map_err(|err| { debug!("error writing: {}", err); err.into() }) diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -300,8 +302,8 @@ where type Error = ::Error; #[inline] - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - self.poll_until_shutdown() + fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> { + self.poll_until_shutdown(cx) } } diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -325,13 +327,13 @@ where type PollBody = Bs; type RecvItem = RequestHead; - fn poll_msg(&mut self) -> Poll<Option<(Self::PollItem, Option<Self::PollBody>)>, ::Error> { + fn poll_msg(&mut self, cx: &mut task::Context) -> Poll<Option<(Self::PollItem, Option<Self::PollBody>)>, ::Error> { if let Some(mut fut) = self.in_flight.take() { - let resp = match fut.poll()? { + let resp = match fut.poll(cx)? { Async::Ready(res) => res, - Async::NotReady => { + Async::Pending => { self.in_flight = Some(fut); - return Ok(Async::NotReady); + return Ok(Async::Pending); } }; let (parts, body) = resp.into_parts(); diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -351,7 +353,7 @@ where } } - fn recv_msg(&mut self, msg: ::Result<(Self::RecvItem, Body)>) -> ::Result<()> { + fn recv_msg(&mut self, _cx: &mut task::Context, msg: ::Result<(Self::RecvItem, Body)>) -> ::Result<()> { let (msg, body) = msg?; let mut req = Request::new(body); *req.method_mut() = msg.subject.0; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -362,9 +364,9 @@ where Ok(()) } - fn poll_ready(&mut self) -> Poll<(), ()> { + fn poll_ready(&mut self, _cx: &mut task::Context) -> Poll<(), ()> { if self.in_flight.is_some() { - Ok(Async::NotReady) + Ok(Async::Pending) } else { Ok(Async::Ready(())) } diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -395,16 +397,16 @@ where type PollBody = B; type RecvItem = ResponseHead; - fn poll_msg(&mut self) -> Poll<Option<(Self::PollItem, Option<Self::PollBody>)>, ::Error> { - match self.rx.poll() { + fn poll_msg(&mut self, cx: &mut task::Context) -> Poll<Option<(Self::PollItem, Option<Self::PollBody>)>, ::Error> { + match self.rx.poll_next(cx) { Ok(Async::Ready(Some((req, mut cb)))) => { // check that future hasn't been canceled already - match cb.poll_cancel().expect("poll_cancel cannot error") { + match cb.poll_cancel(cx).expect("poll_cancel cannot error") { Async::Ready(()) => { trace!("request canceled"); Ok(Async::Ready(None)) }, - Async::NotReady => { + Async::Pending => { let (parts, body) = req.into_parts(); let head = RequestHead { version: parts.version, diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -427,12 +429,12 @@ where // user has dropped sender handle Ok(Async::Ready(None)) }, - Ok(Async::NotReady) => return Ok(Async::NotReady), + Ok(Async::Pending) => return Ok(Async::Pending), Err(_) => unreachable!("receiver cannot error"), } } - fn recv_msg(&mut self, msg: ::Result<(Self::RecvItem, Body)>) -> ::Result<()> { + fn recv_msg(&mut self, cx: &mut task::Context, msg: ::Result<(Self::RecvItem, Body)>) -> ::Result<()> { match msg { Ok((msg, body)) => { if let Some(cb) = self.callback.take() { diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -450,7 +452,7 @@ where if let Some(cb) = self.callback.take() { let _ = cb.send(Err((err, None))); Ok(()) - } else if let Ok(Async::Ready(Some((req, cb)))) = self.rx.poll() { + } else if let Ok(Async::Ready(Some((req, cb)))) = self.rx.poll_next(cx) { trace!("canceling queued request with connection error: {}", err); // in this case, the message was never even started, so it's safe to tell // the user that the request was completely canceled diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -463,14 +465,14 @@ where } } - fn poll_ready(&mut self) -> Poll<(), ()> { + fn poll_ready(&mut self, cx: &mut task::Context) -> Poll<(), ()> { match self.callback { - Some(ref mut cb) => match cb.poll_cancel() { + Some(ref mut cb) => match cb.poll_cancel(cx) { Ok(Async::Ready(())) => { trace!("callback receiver has dropped"); Err(()) }, - Ok(Async::NotReady) => Ok(Async::Ready(())), + Ok(Async::Pending) => Ok(Async::Ready(())), Err(_) => unreachable!("oneshot poll_cancel cannot error"), }, None => Err(()), diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -1,12 +1,12 @@ -use std::cell::Cell; use std::collections::VecDeque; use std::fmt; use std::io; use bytes::{Buf, BufMut, Bytes, BytesMut}; use futures::{Async, Poll}; +use futures::task; +use futures::io::{AsyncRead, AsyncWrite}; use iovec::IoVec; -use tokio_io::{AsyncRead, AsyncWrite}; use proto::{Http1Transaction, MessageHead}; diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -108,7 +108,7 @@ where } } - pub fn parse<S: Http1Transaction>(&mut self) -> Poll<MessageHead<S::Incoming>, ::Error> { + pub fn parse<S: Http1Transaction>(&mut self, cx: &mut task::Context) -> Poll<MessageHead<S::Incoming>, ::Error> { loop { match try!(S::parse(&mut self.read_buf)) { Some((head, len)) => { diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -122,7 +122,7 @@ where } }, } - match try_ready!(self.read_from_io()) { + match try_ready!(self.read_from_io(cx)) { 0 => { trace!("parse eof"); return Err(::Error::Incomplete); diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -132,21 +132,21 @@ where } } - pub fn read_from_io(&mut self) -> Poll<usize, io::Error> { + pub fn read_from_io(&mut self, cx: &mut task::Context) -> Poll<usize, io::Error> { use bytes::BufMut; self.read_blocked = false; if self.read_buf.remaining_mut() < INIT_BUFFER_SIZE { self.read_buf.reserve(INIT_BUFFER_SIZE); } - self.io.read_buf(&mut self.read_buf).map(|ok| { + read_buf(&mut self.io, cx, &mut self.read_buf).map(|ok| { match ok { Async::Ready(n) => { debug!("read {} bytes", n); Async::Ready(n) }, - Async::NotReady => { + Async::Pending => { self.read_blocked = true; - Async::NotReady + Async::Pending } } }) diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -164,14 +164,14 @@ where self.read_blocked } - pub fn flush(&mut self) -> Poll<(), io::Error> { + pub fn flush(&mut self, cx: &mut task::Context) -> Poll<(), io::Error> { if self.flush_pipeline && !self.read_buf.is_empty() { //Ok(()) } else if self.write_buf.remaining() == 0 { - try_nb!(self.io.flush()); + try_ready!(self.io.poll_flush(cx)); } else { loop { - let n = try_ready!(self.io.write_buf(&mut self.write_buf.auto())); + let n = try_ready!(self.write_buf.poll_flush_into(&mut self.io, cx)); debug!("flushed {} bytes", n); if self.write_buf.remaining() == 0 { break; diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -180,14 +180,33 @@ where return Err(io::ErrorKind::WriteZero.into()) } } - try_nb!(self.io.flush()) + try_ready!(self.io.poll_flush(cx)) } Ok(Async::Ready(())) } } +fn read_buf<I: AsyncRead, B: BufMut>(io: &mut I, cx: &mut task::Context, buf: &mut B) -> Poll<usize, io::Error> { + if !buf.has_remaining_mut() { + return Ok(Async::Ready(0)); + } + + unsafe { + let n = { + let b = buf.bytes_mut(); + + io.initializer().initialize(b); + + try_ready!(io.poll_read(cx, b)) + }; + + buf.advance_mut(n); + Ok(Async::Ready(n)) + } +} + pub trait MemRead { - fn read_mem(&mut self, len: usize) -> Poll<Bytes, io::Error>; + fn read_mem(&mut self, cx: &mut task::Context, len: usize) -> Poll<Bytes, io::Error>; } impl<T, B> MemRead for Buffered<T, B> diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -195,12 +214,12 @@ where T: AsyncRead + AsyncWrite, B: Buf, { - fn read_mem(&mut self, len: usize) -> Poll<Bytes, io::Error> { + fn read_mem(&mut self, cx: &mut task::Context, len: usize) -> Poll<Bytes, io::Error> { if !self.read_buf.is_empty() { let n = ::std::cmp::min(len, self.read_buf.len()); Ok(Async::Ready(self.read_buf.split_to(n).freeze())) } else { - let n = try_ready!(self.read_from_io()); + let n = try_ready!(self.read_from_io(cx)); Ok(Async::Ready(self.read_buf.split_to(::std::cmp::min(len, n)).freeze())) } } diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -294,11 +313,6 @@ where self.strategy = strategy; } - #[inline] - fn auto(&mut self) -> WriteBufAuto<B> { - WriteBufAuto::new(self) - } - fn buffer(&mut self, buf: B) { match self.strategy { Strategy::Flatten => { diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -343,6 +357,48 @@ where unreachable!("head_buf just pushed on back"); } } + + fn poll_flush_into<I: AsyncWrite>(&mut self, io: &mut I, cx: &mut task::Context) -> Poll<usize, io::Error> { + if !self.has_remaining() { + return Ok(Async::Ready(0)); + } + + let (num_bufs_avail, num_bytes_written, len_first_buf) = { + static PLACEHOLDER: &[u8] = &[0]; + let mut bufs = [From::from(PLACEHOLDER); 64]; + let num_bufs_avail = self.bytes_vec(&mut bufs[..]); + let num_bytes_written = try_ready!(io.poll_vectored_write(cx, &bufs[..num_bufs_avail])); + (num_bufs_avail, num_bytes_written, bufs[0].len()) + }; + self.advance(num_bytes_written); + + if let Strategy::Auto = self.strategy { + if num_bufs_avail > 1 { + // If there's more than one IoVec available, attempt to + // determine the best buffering strategy based on whether + // the underlying AsyncWrite object supports vectored I/O. + if num_bytes_written == len_first_buf { + // If only the first of many IoVec was written, we can assume + // with some certainty that vectored I/O _is not_ supported. + // + // Switch to a flattening strategy for buffering data. + trace!("detected no usage of vectored write, flattening"); + let mut vec = Vec::new(); + vec.put(&mut self.buf); + self.buf.bufs.push_back(VecOrBuf::Vec(Cursor::new(vec))); + self.strategy = Strategy::Flatten; + } else if num_bytes_written > len_first_buf { + // If more than the first IoVec was written, we can assume + // with some certainty that vectored I/O _is_ supported. + // + // Switch to a queuing strategy for buffering data. + self.strategy = Strategy::Queue; + } + } + } + + Ok(Async::Ready(num_bytes_written)) + } } impl<B: Buf> fmt::Debug for WriteBuf<B> { diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -376,65 +432,6 @@ impl<B: Buf> Buf for WriteBuf<B> { } } -/// Detects when wrapped `WriteBuf` is used for vectored IO, and -/// adjusts the `WriteBuf` strategy if not. -struct WriteBufAuto<'a, B: Buf + 'a> { - bytes_called: Cell<bool>, - bytes_vec_called: Cell<bool>, - inner: &'a mut WriteBuf<B>, -} - -impl<'a, B: Buf> WriteBufAuto<'a, B> { - fn new(inner: &'a mut WriteBuf<B>) -> WriteBufAuto<'a, B> { - WriteBufAuto { - bytes_called: Cell::new(false), - bytes_vec_called: Cell::new(false), - inner: inner, - } - } -} - -impl<'a, B: Buf> Buf for WriteBufAuto<'a, B> { - #[inline] - fn remaining(&self) -> usize { - self.inner.remaining() - } - - #[inline] - fn bytes(&self) -> &[u8] { - self.bytes_called.set(true); - self.inner.bytes() - } - - #[inline] - fn advance(&mut self, cnt: usize) { - self.inner.advance(cnt) - } - - #[inline] - fn bytes_vec<'t>(&'t self, dst: &mut [&'t IoVec]) -> usize { - self.bytes_vec_called.set(true); - self.inner.bytes_vec(dst) - } -} - -impl<'a, B: Buf + 'a> Drop for WriteBufAuto<'a, B> { - fn drop(&mut self) { - if let Strategy::Auto = self.inner.strategy { - if self.bytes_vec_called.get() { - self.inner.strategy = Strategy::Queue; - } else if self.bytes_called.get() { - trace!("detected no usage of vectored write, flattening"); - self.inner.strategy = Strategy::Flatten; - let mut vec = Vec::new(); - vec.put(&mut self.inner.buf); - self.inner.buf.bufs.push_back(VecOrBuf::Vec(Cursor::new(vec))); - } - } - } -} - - #[derive(Debug)] enum Strategy { Auto, diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -12,7 +12,8 @@ use std::fmt; use bytes::Bytes; use futures::{Future, Poll}; -use tokio_io::{AsyncRead, AsyncWrite}; +use futures::task; +use futures::io::{AsyncRead, AsyncWrite}; use proto; use proto::body::{Body, Entity}; diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -89,8 +90,8 @@ where S: Service<Request = Request<Body>, Response = Response<B>, Error = ::Erro /// upgrade. Once the upgrade is completed, the connection would be "done", /// but it is not desired to actally shutdown the IO object. Instead you /// would take it back using `into_parts`. - pub fn poll_without_shutdown(&mut self) -> Poll<(), ::Error> { - try_ready!(self.conn.poll_without_shutdown()); + pub fn poll_without_shutdown(&mut self, cx: &mut task::Context) -> Poll<(), ::Error> { + try_ready!(self.conn.poll_without_shutdown(cx)); Ok(().into()) } } diff --git a/src/server/conn.rs b/src/server/conn.rs --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -103,8 +104,8 @@ where S: Service<Request = Request<Body>, Response = Response<B>, Error = ::Erro type Item = (); type Error = ::Error; - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - self.conn.poll() + fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> { + self.conn.poll(cx) } } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -4,7 +4,6 @@ //! them off to a `Service`. pub mod conn; -mod service; use std::fmt; use std::io; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -13,16 +12,15 @@ use std::net::{SocketAddr, TcpListener as StdTcpListener}; use std::sync::{Arc, Mutex, Weak}; use std::time::Duration; -use futures::task::{self, Task}; +use futures::task::{self, Waker}; use futures::future::{self}; -use futures::{Future, Stream, Poll, Async}; +use futures::{Future, FutureExt, Stream, StreamExt, Poll, Async}; +use futures::io::{AsyncRead, AsyncWrite}; +use futures::executor::spawn; use futures_timer::Delay; use http::{Request, Response}; -use tokio_io::{AsyncRead, AsyncWrite}; -use tokio::spawn; use tokio::reactor::Handle; use tokio::net::TcpListener; -pub use tokio_service::{NewService, Service}; use proto::body::{Body, Entity}; use proto; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -30,7 +28,8 @@ use self::addr_stream::AddrStream; use self::hyper_service::HyperService; pub use self::conn::Connection; -pub use self::service::{const_service, service_fn}; +pub use super::service::{NewService, Service}; +pub use super::service::{const_service, service_fn}; /// A configuration of the HTTP protocol. /// diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -255,11 +254,10 @@ impl<B: AsRef<[u8]> + 'static> Http<B> { /// # extern crate futures; /// # extern crate hyper; /// # extern crate tokio; - /// # extern crate tokio_io; - /// # use futures::Future; + /// # use futures::FutureExt; + /// # use futures::io::{AsyncRead, AsyncWrite}; /// # use hyper::{Body, Request, Response}; /// # use hyper::server::{Http, Service}; - /// # use tokio_io::{AsyncRead, AsyncWrite}; /// # use tokio::reactor::Handle; /// # fn run<I, S>(some_io: I, some_service: S) /// # where diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -272,9 +270,9 @@ impl<B: AsRef<[u8]> + 'static> Http<B> { /// /// let fut = conn /// .map(|_| ()) - /// .map_err(|e| eprintln!("server connection error: {}", e)); + /// .map_err(|e| panic!("server connection error: {}", e)); /// - /// tokio::spawn(fut); + /// tokio::spawn2(fut); /// # } /// # fn main() {} /// ``` diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -334,8 +332,8 @@ impl Future for Run { type Item = (); type Error = ::Error; - fn poll(&mut self) -> Poll<(), ::Error> { - self.0.poll() + fn poll(&mut self, cx: &mut task::Context) -> Poll<(), ::Error> { + self.0.poll(cx) } } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -412,17 +410,21 @@ impl<S, B> Server<S, B> let addr = socket.remote_addr; debug!("accepted new connection ({})", addr); - let service = new_service.new_service()?; + let service = match new_service.new_service() { + Ok(service) => service, + Err(err) => return future::err(err).left() + }; + let s = NotifyService { inner: service, info: Arc::downgrade(&info_cloned), }; info_cloned.lock().unwrap().active += 1; - let fut = protocol.serve_connection(socket, s) - .map(|_| ()) - .map_err(move |err| error!("server connection error: ({}) {}", addr, err)); - spawn(fut); - Ok(()) + let fut = protocol.serve_connection(socket, s).recover(move |err| { + error!("server connection error: ({}) {}", addr, err); + }); + + spawn(fut).map_err(|err| err.never_into()).right() }); // for now, we don't care if the shutdown signal succeeds or errors diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -438,8 +440,11 @@ impl<S, B> Server<S, B> // stop accepting incoming connections. let main_execution = shutdown_signal.select(srv).then(move |result| { match result { - Ok(((), _incoming)) => {}, - Err((e, _other)) => return future::Either::A(future::err(e.into())) + Ok(_) => {}, + Err(future::Either::Left((e, _other))) => + return future::Either::Left(future::err(e)), + Err(future::Either::Right((e, _other))) => + return future::Either::Left(future::err(e.into())), } // Ok we've stopped accepting new connections at this point, but we want diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -451,10 +456,11 @@ impl<S, B> Server<S, B> // here have been destroyed. let timeout = Delay::new(shutdown_timeout); let wait = WaitUntilZero { info: info.clone() }; - future::Either::B(wait.select(timeout).then(|result| { + future::Either::Right(wait.select(timeout).then(|result| { match result { Ok(_) => Ok(()), - Err((e, _)) => Err(e.into()) + Err(future::Either::Left((e, _))) => Err(e.into()), + Err(future::Either::Right((e, _))) => Err(e.into()) } })) }); diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -505,8 +511,8 @@ where type Item = Connection<I::Item, S::Instance>; type Error = ::Error; - fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { - if let Some(io) = try_ready!(self.incoming.poll()) { + fn poll_next(&mut self, cx: &mut task::Context) -> Poll<Option<Self::Item>, Self::Error> { + if let Some(io) = try_ready!(self.incoming.poll_next(cx)) { let service = self.new_service.new_service()?; Ok(Async::Ready(Some(self.protocol.serve_connection(io, service)))) } else { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -586,17 +592,17 @@ impl Stream for AddrIncoming { type Item = AddrStream; type Error = ::std::io::Error; - fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { + fn poll_next(&mut self, cx: &mut task::Context) -> Poll<Option<Self::Item>, Self::Error> { // Check if a previous timeout is active that was set by IO errors. if let Some(ref mut to) = self.timeout { - match to.poll().expect("timeout never fails") { + match to.poll(cx).expect("timeout never fails") { Async::Ready(_) => {} - Async::NotReady => return Ok(Async::NotReady), + Async::Pending => return Ok(Async::Pending), } } self.timeout = None; loop { - match self.listener.poll_accept() { + match self.listener.poll_accept2(cx) { Ok(Async::Ready((socket, addr))) => { if let Some(dur) = self.keep_alive_timeout { if let Err(e) = socket.set_keepalive(Some(dur)) { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -605,7 +611,7 @@ impl Stream for AddrIncoming { } return Ok(Async::Ready(Some(AddrStream::new(socket, addr)))); }, - Ok(Async::NotReady) => return Ok(Async::NotReady), + Ok(Async::Pending) => return Ok(Async::Pending), Err(ref e) if self.sleep_on_errors => { // Connection errors can be ignored directly, continue by // accepting the next request. diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -617,13 +623,13 @@ impl Stream for AddrIncoming { debug!("accept error: {}; sleeping {:?}", e, delay); let mut timeout = Delay::new(delay); - let result = timeout.poll() + let result = timeout.poll(cx) .expect("timeout never fails"); match result { Async::Ready(()) => continue, - Async::NotReady => { + Async::Pending => { self.timeout = Some(timeout); - return Ok(Async::NotReady); + return Ok(Async::Pending); } } }, diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -647,12 +653,13 @@ fn connection_error(e: &io::Error) -> bool { } mod addr_stream { - use std::io::{self, Read, Write}; + use std::io; use std::net::SocketAddr; - use bytes::{Buf, BufMut}; use futures::Poll; + use futures::task; + use futures::io::{AsyncRead, AsyncWrite, Initializer}; + use iovec::IoVec; use tokio::net::TcpStream; - use tokio_io::{AsyncRead, AsyncWrite}; #[derive(Debug)] diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -670,46 +677,42 @@ mod addr_stream { } } - impl Read for AddrStream { + impl AsyncRead for AddrStream { #[inline] - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.inner.read(buf) + fn poll_read(&mut self, cx: &mut task::Context, buf: &mut [u8]) -> Poll<usize, io::Error> { + self.inner.poll_read(cx, buf) } - } - impl Write for AddrStream { #[inline] - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.inner.write(buf) + unsafe fn initializer(&self) -> Initializer { + AsyncRead::initializer(&self.inner) } #[inline] - fn flush(&mut self ) -> io::Result<()> { - self.inner.flush() + fn poll_vectored_read(&mut self, cx: &mut task::Context, vec: &mut [&mut IoVec]) -> Poll<usize, io::Error> { + self.inner.poll_vectored_read(cx, vec) } } - impl AsyncRead for AddrStream { + impl AsyncWrite for AddrStream { #[inline] - unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool { - self.inner.prepare_uninitialized_buffer(buf) + fn poll_write(&mut self, cx: &mut task::Context, buf: &[u8]) -> Poll<usize, io::Error> { + self.inner.poll_write(cx, buf) } #[inline] - fn read_buf<B: BufMut>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { - self.inner.read_buf(buf) + fn poll_flush(&mut self, cx: &mut task::Context) -> Poll<(), io::Error> { + self.inner.poll_flush(cx) } - } - impl AsyncWrite for AddrStream { #[inline] - fn shutdown(&mut self) -> Poll<(), io::Error> { - AsyncWrite::shutdown(&mut self.inner) + fn poll_close(&mut self, cx: &mut task::Context) -> Poll<(), io::Error> { + self.inner.poll_close(cx) } #[inline] - fn write_buf<B: Buf>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { - self.inner.write_buf(buf) + fn poll_vectored_write(&mut self, cx: &mut task::Context, vec: &[&IoVec]) -> Poll<usize, io::Error> { + self.inner.poll_vectored_write(cx, vec) } } } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -727,7 +730,7 @@ struct WaitUntilZero { struct Info { active: usize, - blocker: Option<Task>, + blocker: Option<Waker>, } impl<S: Service> Service for NotifyService<S> { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -750,8 +753,8 @@ impl<S> Drop for NotifyService<S> { let mut info = info.lock().unwrap(); info.active -= 1; if info.active == 0 { - if let Some(task) = info.blocker.take() { - task.notify(); + if let Some(waker) = info.blocker.take() { + waker.wake(); } } } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -761,13 +764,13 @@ impl Future for WaitUntilZero { type Item = (); type Error = io::Error; - fn poll(&mut self) -> Poll<(), io::Error> { + fn poll(&mut self, cx: &mut task::Context) -> Poll<(), io::Error> { let mut info = self.info.lock().unwrap(); if info.active == 0 { Ok(().into()) } else { - info.blocker = Some(task::current()); - Ok(Async::NotReady) + info.blocker = Some(cx.waker().clone()); + Ok(Async::Pending) } } } diff --git a/src/server/service.rs /dev/null --- a/src/server/service.rs +++ /dev/null @@ -1,64 +0,0 @@ -use std::marker::PhantomData; -use std::sync::Arc; - -use futures::IntoFuture; -use tokio_service::{NewService, Service}; - -/// Create a `Service` from a function. -pub fn service_fn<F, R, S>(f: F) -> ServiceFn<F, R> -where - F: Fn(R) -> S, - S: IntoFuture, -{ - ServiceFn { - f: f, - _req: PhantomData, - } -} - -/// Create a `NewService` by sharing references of `service. -pub fn const_service<S>(service: S) -> ConstService<S> { - ConstService { - svc: Arc::new(service), - } -} - -#[derive(Debug)] -pub struct ServiceFn<F, R> { - f: F, - _req: PhantomData<fn() -> R>, -} - -impl<F, R, S> Service for ServiceFn<F, R> -where - F: Fn(R) -> S, - S: IntoFuture, -{ - type Request = R; - type Response = S::Item; - type Error = S::Error; - type Future = S::Future; - - fn call(&self, req: Self::Request) -> Self::Future { - (self.f)(req).into_future() - } -} - -#[derive(Debug)] -pub struct ConstService<S> { - svc: Arc<S>, -} - -impl<S> NewService for ConstService<S> -where - S: Service, -{ - type Request = S::Request; - type Response = S::Response; - type Error = S::Error; - type Instance = Arc<S>; - - fn new_service(&self) -> ::std::io::Result<Self::Instance> { - Ok(self.svc.clone()) - } -} diff --git /dev/null b/src/service.rs new file mode 100644 --- /dev/null +++ b/src/service.rs @@ -0,0 +1,116 @@ +use std::marker::PhantomData; +use std::sync::Arc; + +use futures::{Future, IntoFuture}; + +/// An asynchronous function from `Request` to a `Response`. +pub trait Service { + /// Requests handled by the service. + type Request; + /// Responses given by the service. + type Response; + /// Errors produced by the service. + type Error; + /// The future response value. + type Future: Future<Item = Self::Response, Error = Self::Error>; + /// Process the request and return the response asynchronously. + fn call(&self, req: Self::Request) -> Self::Future; +} + +impl<S: Service + ?Sized> Service for Arc<S> { + type Request = S::Request; + type Response = S::Response; + type Error = S::Error; + type Future = S::Future; + + fn call(&self, request: S::Request) -> S::Future { + (**self).call(request) + } +} + +/// Creates new `Service` values. +pub trait NewService { + /// Requests handled by the service. + type Request; + /// Responses given by the service. + type Response; + /// Errors produced by the service. + type Error; + /// The `Service` value created by this factory. + type Instance: Service<Request = Self::Request, Response = Self::Response, Error = Self::Error>; + /// Create and return a new service value. + fn new_service(&self) -> ::std::io::Result<Self::Instance>; +} + +impl<F, R> NewService for F + where F: Fn() -> ::std::io::Result<R>, + R: Service, +{ + type Request = R::Request; + type Response = R::Response; + type Error = R::Error; + type Instance = R; + + fn new_service(&self) -> ::std::io::Result<R> { + (*self)() + } +} + +/// Create a `Service` from a function. +pub fn service_fn<F, R, S>(f: F) -> ServiceFn<F, R> +where + F: Fn(R) -> S, + S: IntoFuture, +{ + ServiceFn { + f: f, + _req: PhantomData, + } +} + +/// Create a `NewService` by sharing references of `service. +pub fn const_service<S>(service: S) -> ConstService<S> { + ConstService { + svc: Arc::new(service), + } +} + +#[derive(Debug)] +pub struct ServiceFn<F, R> { + f: F, + _req: PhantomData<fn() -> R>, +} + +impl<F, R, S> Service for ServiceFn<F, R> +where + F: Fn(R) -> S, + S: IntoFuture, +{ + type Request = R; + type Response = S::Item; + type Error = S::Error; + type Future = S::Future; + + fn call(&self, req: Self::Request) -> Self::Future { + (self.f)(req).into_future() + } +} + +#[derive(Debug)] +pub struct ConstService<S> { + svc: Arc<S>, +} + +impl<S> NewService for ConstService<S> +where + S: Service, +{ + type Request = S::Request; + type Response = S::Response; + type Error = S::Error; + type Instance = Arc<S>; + + fn new_service(&self) -> ::std::io::Result<Self::Instance> { + Ok(self.svc.clone()) + } +}
diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -22,19 +23,20 @@ fn get_one_at_a_time(b: &mut test::Bencher) { let addr = spawn_hello(&mut rt); let client = hyper::Client::configure() - .build_with_executor(&rt.handle(), rt.executor()); + .build(&rt.handle()); let url: hyper::Uri = format!("http://{}/get", addr).parse().unwrap(); b.bytes = 160 * 2 + PHRASE.len() as u64; b.iter(move || { - client.get(url.clone()) + block_on(client.get(url.clone()) + .with_executor(rt.executor()) .and_then(|res| { res.into_body().into_stream().for_each(|_chunk| { Ok(()) - }) + }).map(|_| ()) }) - .wait().expect("client wait"); + ).expect("client wait"); }); } diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -44,7 +46,7 @@ fn post_one_at_a_time(b: &mut test::Bencher) { let addr = spawn_hello(&mut rt); let client = hyper::Client::configure() - .build_with_executor(&rt.handle(), rt.executor()); + .build(&rt.handle()); let url: hyper::Uri = format!("http://{}/post", addr).parse().unwrap(); diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -54,11 +56,14 @@ fn post_one_at_a_time(b: &mut test::Bencher) { let mut req = Request::new(post.into()); *req.method_mut() = Method::POST; *req.uri_mut() = url.clone(); - client.request(req).and_then(|res| { - res.into_body().into_stream().for_each(|_chunk| { - Ok(()) + block_on(client.request(req) + .with_executor(rt.executor()) + .and_then(|res| { + res.into_body().into_stream().for_each(|_chunk| { + Ok(()) + }).map(|_| ()) }) - }).wait().expect("client wait"); + ).expect("client wait"); }); } diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -430,7 +404,7 @@ impl Executor<oneshot::Execute<dns::Work>> for HttpConnectExecutor { mod tests { #![allow(deprecated)] use std::io; - use futures::Future; + use futures::executor::block_on; use tokio::runtime::Runtime; use super::{Connect, Destination, HttpConnector}; diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -443,7 +417,7 @@ mod tests { }; let connector = HttpConnector::new(1, runtime.handle()); - assert_eq!(connector.connect(dst).wait().unwrap_err().kind(), io::ErrorKind::InvalidInput); + assert_eq!(block_on(connector.connect(dst)).unwrap_err().kind(), io::ErrorKind::InvalidInput); } #[test] diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -455,7 +429,7 @@ mod tests { }; let connector = HttpConnector::new(1, runtime.handle()); - assert_eq!(connector.connect(dst).wait().unwrap_err().kind(), io::ErrorKind::InvalidInput); + assert_eq!(block_on(connector.connect(dst)).unwrap_err().kind(), io::ErrorKind::InvalidInput); } diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -468,6 +442,6 @@ mod tests { }; let connector = HttpConnector::new(1, runtime.handle()); - assert_eq!(connector.connect(dst).wait().unwrap_err().kind(), io::ErrorKind::InvalidInput); + assert_eq!(block_on(connector.connect(dst)).unwrap_err().kind(), io::ErrorKind::InvalidInput); } } diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -162,7 +160,8 @@ mod tests { #[cfg(feature = "nightly")] extern crate test; - use futures::{future, Future}; + use futures::{future, FutureExt}; + use futures::executor::block_on; #[cfg(feature = "nightly")] use futures::{Stream}; diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -171,7 +170,7 @@ mod tests { fn drop_receiver_sends_cancel_errors() { let _ = pretty_env_logger::try_init(); - future::lazy(|| { + block_on(future::lazy(|_| { #[derive(Debug)] struct Custom(i32); let (mut tx, rx) = super::channel::<Custom, ()>(); diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -188,7 +187,7 @@ mod tests { Ok::<(), ()>(()) }) - }).wait().unwrap(); + })).unwrap(); } #[cfg(feature = "nightly")] diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -197,18 +196,18 @@ mod tests { let (mut tx, mut rx) = super::channel::<i32, ()>(); b.iter(move || { - ::futures::future::lazy(|| { + block_on(future::lazy(|cx| { let _ = tx.send(1).unwrap(); loop { - let async = rx.poll().unwrap(); - if async.is_not_ready() { + let async = rx.poll_next(cx).unwrap(); + if async.is_pending() { break; } } Ok::<(), ()>(()) - }).wait().unwrap(); + })).unwrap(); }) } diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -218,11 +217,11 @@ mod tests { let (_tx, mut rx) = super::channel::<i32, ()>(); b.iter(move || { - ::futures::future::lazy(|| { - assert!(rx.poll().unwrap().is_not_ready()); + block_on(future::lazy(|cx| { + assert!(rx.poll_next(cx).unwrap().is_pending()); Ok::<(), ()>(()) - }).wait().unwrap(); + })).unwrap(); }) } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -35,7 +34,6 @@ mod tests; /// A Client to make outgoing HTTP requests. pub struct Client<C, B = proto::Body> { connector: Arc<C>, - executor: Exec, h1_writev: bool, pool: Pool<PoolClient<B>>, retry_canceled_requests: bool, diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -430,9 +436,10 @@ impl<T: Closed + 'static> Future for IdleInterval<T> { mod tests { use std::sync::Arc; use std::time::Duration; - use futures::{Async, Future}; + use futures::{Async, Future, FutureExt}; use futures::future; - use super::{Closed, Pool, Exec}; + use futures::executor::block_on; + use super::{Closed, Pool}; impl Closed for i32 { fn is_closed(&self) -> bool { diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -442,34 +449,37 @@ mod tests { #[test] fn test_pool_checkout_smoke() { - let pool = Pool::new(true, Some(Duration::from_secs(5))); - let key = Arc::new("foo".to_string()); - let pooled = pool.pooled(key.clone(), 41); + block_on(future::lazy(|cx| { + let pool = Pool::new(true, Some(Duration::from_secs(5))); + let key = Arc::new("foo".to_string()); + let pooled = pool.pooled(key.clone(), 41); - drop(pooled); + drop(pooled); - match pool.checkout(&key).poll().unwrap() { - Async::Ready(pooled) => assert_eq!(*pooled, 41), - _ => panic!("not ready"), - } + match pool.checkout(&key).poll(cx).unwrap() { + Async::Ready(pooled) => assert_eq!(*pooled, 41), + _ => panic!("not ready"), + } + Ok::<_, ()>(()) + })).unwrap(); } #[test] fn test_pool_checkout_returns_none_if_expired() { - future::lazy(|| { + block_on(future::lazy(|cx| { let pool = Pool::new(true, Some(Duration::from_millis(100))); let key = Arc::new("foo".to_string()); let pooled = pool.pooled(key.clone(), 41); drop(pooled); ::std::thread::sleep(pool.inner.lock().unwrap().timeout.unwrap()); - assert!(pool.checkout(&key).poll().unwrap().is_not_ready()); - ::futures::future::ok::<(), ()>(()) - }).wait().unwrap(); + assert!(pool.checkout(&key).poll(cx).unwrap().is_pending()); + Ok::<_, ()>(()) + })).unwrap(); } #[test] fn test_pool_checkout_removes_expired() { - future::lazy(|| { + block_on(future::lazy(|cx| { let pool = Pool::new(true, Some(Duration::from_millis(100))); let key = Arc::new("foo".to_string()); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -481,20 +491,20 @@ mod tests { ::std::thread::sleep(pool.inner.lock().unwrap().timeout.unwrap()); // checkout.poll() should clean out the expired - pool.checkout(&key).poll().unwrap(); + pool.checkout(&key).poll(cx).unwrap(); assert!(pool.inner.lock().unwrap().idle.get(&key).is_none()); - Ok::<(), ()>(()) - }).wait().unwrap(); + Ok::<_, ()>(()) + })).unwrap(); } #[test] fn test_pool_timer_removes_expired() { - let runtime = ::tokio::runtime::Runtime::new().unwrap(); - let pool = Pool::new(true, Some(Duration::from_millis(100))); + let mut pool = Pool::new(true, Some(Duration::from_millis(100))); - let executor = runtime.executor(); - pool.spawn_expired_interval(&Exec::new(executor)); + block_on(future::lazy(|cx| { + pool.spawn_expired_interval(cx) + })).unwrap(); let key = Arc::new("foo".to_string()); pool.pooled(key.clone(), 41); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -503,9 +513,9 @@ mod tests { assert_eq!(pool.inner.lock().unwrap().idle.get(&key).map(|entries| entries.len()), Some(3)); - ::futures_timer::Delay::new( + block_on(::futures_timer::Delay::new( Duration::from_millis(400) // allow for too-good resolution - ).wait().unwrap(); + )).unwrap(); assert!(pool.inner.lock().unwrap().idle.get(&key).is_none()); } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -516,7 +526,7 @@ mod tests { let key = Arc::new("foo".to_string()); let pooled = pool.pooled(key.clone(), 41); - let checkout = pool.checkout(&key).join(future::lazy(move || { + let checkout = pool.checkout(&key).join(future::lazy(move |_| { // the checkout future will park first, // and then this lazy future will be polled, which will insert // the pooled back into the pool diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -525,12 +535,12 @@ mod tests { drop(pooled); Ok(()) })).map(|(entry, _)| entry); - assert_eq!(*checkout.wait().unwrap(), 41); + assert_eq!(*block_on(checkout).unwrap(), 41); } #[test] fn test_pool_checkout_drop_cleans_up_parked() { - future::lazy(|| { + block_on(future::lazy(|cx| { let pool = Pool::<i32>::new(true, Some(Duration::from_secs(10))); let key = Arc::new("localhost:12345".to_string()); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -538,9 +548,9 @@ mod tests { let mut checkout2 = pool.checkout(&key); // first poll needed to get into Pool's parked - checkout1.poll().unwrap(); + checkout1.poll(cx).unwrap(); assert_eq!(pool.inner.lock().unwrap().parked.get(&key).unwrap().len(), 1); - checkout2.poll().unwrap(); + checkout2.poll(cx).unwrap(); assert_eq!(pool.inner.lock().unwrap().parked.get(&key).unwrap().len(), 2); // on drop, clean up Pool diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -550,7 +560,7 @@ mod tests { drop(checkout2); assert!(pool.inner.lock().unwrap().parked.get(&key).is_none()); - ::futures::future::ok::<(), ()>(()) - }).wait().unwrap(); + Ok::<_, ()>(()) + })).unwrap(); } } diff --git a/src/client/tests.rs b/src/client/tests.rs --- a/src/client/tests.rs +++ b/src/client/tests.rs @@ -5,6 +5,7 @@ use std::time::Duration; use futures::Async; use futures::future::poll_fn; +use futures::executor::block_on; use tokio::executor::thread_pool::{Builder as ThreadPoolBuilder}; use mock::MockConnector; diff --git a/src/client/tests.rs b/src/client/tests.rs --- a/src/client/tests.rs +++ b/src/client/tests.rs @@ -22,7 +23,7 @@ fn retryable_request() { let client = Client::configure() .connector(connector) - .executor(executor.sender().clone()); + .build(); { diff --git a/src/client/tests.rs b/src/client/tests.rs --- a/src/client/tests.rs +++ b/src/client/tests.rs @@ -30,13 +31,13 @@ fn retryable_request() { .uri("http://mock.local/a") .body(Default::default()) .unwrap(); - let res1 = client.request(req); - let srv1 = poll_fn(|| { - try_ready!(sock1.read(&mut [0u8; 512])); + let res1 = client.request(req).with_executor(executor.sender().clone()); + let srv1 = poll_fn(|cx| { + try_ready!(sock1.read(cx, &mut [0u8; 512])); try_ready!(sock1.write(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")); Ok(Async::Ready(())) }); - res1.join(srv1).wait().expect("res1"); + block_on(res1.join(srv1)).expect("res1"); } drop(sock1); diff --git a/src/client/tests.rs b/src/client/tests.rs --- a/src/client/tests.rs +++ b/src/client/tests.rs @@ -44,17 +45,17 @@ fn retryable_request() { .uri("http://mock.local/b") .body(Default::default()) .unwrap(); - let res2 = client.request(req) + let res2 = client.request(req).with_executor(executor.sender().clone()) .map(|res| { assert_eq!(res.status().as_u16(), 222); }); - let srv2 = poll_fn(|| { - try_ready!(sock2.read(&mut [0u8; 512])); + let srv2 = poll_fn(|cx| { + try_ready!(sock2.read(cx, &mut [0u8; 512])); try_ready!(sock2.write(b"HTTP/1.1 222 OK\r\nContent-Length: 0\r\n\r\n")); Ok(Async::Ready(())) }); - res2.join(srv2).wait().expect("res2"); + block_on(res2.join(srv2)).expect("res2"); } #[test] diff --git a/src/client/tests.rs b/src/client/tests.rs --- a/src/client/tests.rs +++ b/src/client/tests.rs @@ -68,7 +69,7 @@ fn conn_reset_after_write() { let client = Client::configure() .connector(connector) - .executor(executor.sender().clone()); + .build(); { let req = Request::builder() diff --git a/src/client/tests.rs b/src/client/tests.rs --- a/src/client/tests.rs +++ b/src/client/tests.rs @@ -77,13 +78,13 @@ fn conn_reset_after_write() { .header("content-length", "0") .body(Default::default()) .unwrap(); - let res1 = client.request(req); - let srv1 = poll_fn(|| { - try_ready!(sock1.read(&mut [0u8; 512])); + let res1 = client.request(req).with_executor(executor.sender().clone()); + let srv1 = poll_fn(|cx| { + try_ready!(sock1.read(cx, &mut [0u8; 512])); try_ready!(sock1.write(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")); Ok(Async::Ready(())) }); - res1.join(srv1).wait().expect("res1"); + block_on(res1.join(srv1)).expect("res1"); } // sleep to allow some time for the connection to return to the pool diff --git a/src/client/tests.rs b/src/client/tests.rs --- a/src/client/tests.rs +++ b/src/client/tests.rs @@ -93,20 +94,20 @@ fn conn_reset_after_write() { .uri("http://mock.local/a") .body(Default::default()) .unwrap(); - let res2 = client.request(req); + let res2 = client.request(req).with_executor(executor.sender().clone()); let mut sock1 = Some(sock1); - let srv2 = poll_fn(|| { + let srv2 = poll_fn(|cx| { // We purposefully keep the socket open until the client // has written the second request, and THEN disconnect. // // Not because we expect servers to be jerks, but to trigger // state where we write on an assumedly good connetion, and // only reset the close AFTER we wrote bytes. - try_ready!(sock1.as_mut().unwrap().read(&mut [0u8; 512])); + try_ready!(sock1.as_mut().unwrap().read(cx, &mut [0u8; 512])); sock1.take(); Ok(Async::Ready(())) }); - let err = res2.join(srv2).wait().expect_err("res2"); + let err = block_on(res2.join(srv2)).expect_err("res2"); match err { ::Error::Incomplete => (), other => panic!("expected Incomplete, found {:?}", other) diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -28,8 +27,6 @@ extern crate net2; extern crate time; extern crate tokio; extern crate tokio_executor; -#[macro_use] extern crate tokio_io; -extern crate tokio_service; extern crate want; #[cfg(all(test, feature = "nightly"))] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -49,7 +46,8 @@ pub use error::{Result, Error}; pub use proto::{body, Body, Chunk}; pub use server::Server; -mod common; +mod executor; +mod service; #[cfg(test)] mod mock; pub mod client; diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -413,13 +414,11 @@ fn _assert_send_sync() { #[test] fn test_body_stream_concat() { - use futures::{Stream, Future}; + use futures::{StreamExt}; let body = Body::from("hello world"); - let total = body.into_stream() - .concat2() - .wait() + let total = ::futures::executor::block_on(body.into_stream().concat()) .unwrap(); assert_eq!(total.as_ref(), b"hello world"); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -964,7 +963,7 @@ mod tests { } match conn.poll() { - Ok(Async::NotReady) => (), + Ok(Async::Pending) => (), other => panic!("unexpected frame: {:?}", other) } Ok(()) diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -323,11 +325,14 @@ mod tests { use super::ChunkedState; use super::super::io::MemRead; use futures::{Async, Poll}; + use futures::task; + use futures::future::lazy; + use futures::executor::block_on; use bytes::{BytesMut, Bytes}; use mock::AsyncIo; impl<'a> MemRead for &'a [u8] { - fn read_mem(&mut self, len: usize) -> Poll<Bytes, io::Error> { + fn read_mem(&mut self, _cx: &mut task::Context, len: usize) -> Poll<Bytes, io::Error> { let n = ::std::cmp::min(len, self.len()); if n > 0 { let (a, b) = self.split_at(n); diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -347,7 +352,7 @@ mod tests { fn unwrap(self) -> Bytes { match self { Async::Ready(bytes) => bytes, - Async::NotReady => panic!(), + Async::Pending => panic!(), } } } diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -355,7 +360,7 @@ mod tests { fn unwrap(self) -> ChunkedState { match self { Async::Ready(state) => state, - Async::NotReady => panic!(), + Async::Pending => panic!(), } } } diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -364,12 +369,12 @@ mod tests { fn test_read_chunk_size() { use std::io::ErrorKind::{UnexpectedEof, InvalidInput}; - fn read(s: &str) -> u64 { + fn read(cx: &mut task::Context, s: &str) -> u64 { let mut state = ChunkedState::Size; let rdr = &mut s.as_bytes(); let mut size = 0; loop { - let result = state.step(rdr, &mut size, &mut None); + let result = state.step(rdr, cx, &mut size, &mut None); let desc = format!("read_size failed for {:?}", s); state = result.expect(desc.as_str()).unwrap(); if state == ChunkedState::Body || state == ChunkedState::EndCr { diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -379,12 +384,12 @@ mod tests { size } - fn read_err(s: &str, expected_err: io::ErrorKind) { + fn read_err(cx: &mut task::Context, s: &str, expected_err: io::ErrorKind) { let mut state = ChunkedState::Size; let rdr = &mut s.as_bytes(); let mut size = 0; loop { - let result = state.step(rdr, &mut size, &mut None); + let result = state.step(rdr, cx, &mut size, &mut None); state = match result { Ok(s) => s.unwrap(), Err(e) => { diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -399,90 +404,111 @@ mod tests { } } - assert_eq!(1, read("1\r\n")); - assert_eq!(1, read("01\r\n")); - assert_eq!(0, read("0\r\n")); - assert_eq!(0, read("00\r\n")); - assert_eq!(10, read("A\r\n")); - assert_eq!(10, read("a\r\n")); - assert_eq!(255, read("Ff\r\n")); - assert_eq!(255, read("Ff \r\n")); - // Missing LF or CRLF - read_err("F\rF", InvalidInput); - read_err("F", UnexpectedEof); - // Invalid hex digit - read_err("X\r\n", InvalidInput); - read_err("1X\r\n", InvalidInput); - read_err("-\r\n", InvalidInput); - read_err("-1\r\n", InvalidInput); - // Acceptable (if not fully valid) extensions do not influence the size - assert_eq!(1, read("1;extension\r\n")); - assert_eq!(10, read("a;ext name=value\r\n")); - assert_eq!(1, read("1;extension;extension2\r\n")); - assert_eq!(1, read("1;;; ;\r\n")); - assert_eq!(2, read("2; extension...\r\n")); - assert_eq!(3, read("3 ; extension=123\r\n")); - assert_eq!(3, read("3 ;\r\n")); - assert_eq!(3, read("3 ; \r\n")); - // Invalid extensions cause an error - read_err("1 invalid extension\r\n", InvalidInput); - read_err("1 A\r\n", InvalidInput); - read_err("1;no CRLF", UnexpectedEof); + block_on(lazy(|cx| { + assert_eq!(1, read(cx, "1\r\n")); + assert_eq!(1, read(cx, "01\r\n")); + assert_eq!(0, read(cx, "0\r\n")); + assert_eq!(0, read(cx, "00\r\n")); + assert_eq!(10, read(cx, "A\r\n")); + assert_eq!(10, read(cx, "a\r\n")); + assert_eq!(255, read(cx, "Ff\r\n")); + assert_eq!(255, read(cx, "Ff \r\n")); + // Missing LF or CRLF + read_err(cx, "F\rF", InvalidInput); + read_err(cx, "F", UnexpectedEof); + // Invalid hex digit + read_err(cx, "X\r\n", InvalidInput); + read_err(cx, "1X\r\n", InvalidInput); + read_err(cx, "-\r\n", InvalidInput); + read_err(cx, "-1\r\n", InvalidInput); + // Acceptable (if not fully valid) extensions do not influence the size + assert_eq!(1, read(cx, "1;extension\r\n")); + assert_eq!(10, read(cx, "a;ext name=value\r\n")); + assert_eq!(1, read(cx, "1;extension;extension2\r\n")); + assert_eq!(1, read(cx, "1;;; ;\r\n")); + assert_eq!(2, read(cx, "2; extension...\r\n")); + assert_eq!(3, read(cx, "3 ; extension=123\r\n")); + assert_eq!(3, read(cx, "3 ;\r\n")); + assert_eq!(3, read(cx, "3 ; \r\n")); + // Invalid extensions cause an error + read_err(cx, "1 invalid extension\r\n", InvalidInput); + read_err(cx, "1 A\r\n", InvalidInput); + read_err(cx, "1;no CRLF", UnexpectedEof); + + Ok::<_, ()>(()) + })).unwrap() } #[test] fn test_read_sized_early_eof() { - let mut bytes = &b"foo bar"[..]; - let mut decoder = Decoder::length(10); - assert_eq!(decoder.decode(&mut bytes).unwrap().unwrap().len(), 7); - let e = decoder.decode(&mut bytes).unwrap_err(); - assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof); + block_on(lazy(|cx| { + let mut bytes = &b"foo bar"[..]; + let mut decoder = Decoder::length(10); + assert_eq!(decoder.decode(&mut bytes, cx).unwrap().unwrap().len(), 7); + let e = decoder.decode(&mut bytes, cx).unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof); + + Ok::<_, ()>(()) + })).unwrap() } #[test] fn test_read_chunked_early_eof() { - let mut bytes = &b"\ - 9\r\n\ - foo bar\ - "[..]; - let mut decoder = Decoder::chunked(); - assert_eq!(decoder.decode(&mut bytes).unwrap().unwrap().len(), 7); - let e = decoder.decode(&mut bytes).unwrap_err(); - assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof); + block_on(lazy(|cx| { + let mut bytes = &b"\ + 9\r\n\ + foo bar\ + "[..]; + let mut decoder = Decoder::chunked(); + assert_eq!(decoder.decode(&mut bytes, cx).unwrap().unwrap().len(), 7); + let e = decoder.decode(&mut bytes, cx).unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof); + + Ok::<_, ()>(()) + })).unwrap() } #[test] fn test_read_chunked_single_read() { - let mut mock_buf = &b"10\r\n1234567890abcdef\r\n0\r\n"[..]; - let buf = Decoder::chunked().decode(&mut mock_buf).expect("decode").unwrap(); - assert_eq!(16, buf.len()); - let result = String::from_utf8(buf.as_ref().to_vec()).expect("decode String"); - assert_eq!("1234567890abcdef", &result); + block_on(lazy(|cx| { + let mut mock_buf = &b"10\r\n1234567890abcdef\r\n0\r\n"[..]; + let buf = Decoder::chunked().decode(&mut mock_buf, cx).expect("decode").unwrap(); + assert_eq!(16, buf.len()); + let result = String::from_utf8(buf.as_ref().to_vec()).expect("decode String"); + assert_eq!("1234567890abcdef", &result); + + Ok::<_, ()>(()) + })).unwrap() } #[test] fn test_read_chunked_after_eof() { - let mut mock_buf = &b"10\r\n1234567890abcdef\r\n0\r\n\r\n"[..]; - let mut decoder = Decoder::chunked(); + block_on(lazy(|cx| { + let mut mock_buf = &b"10\r\n1234567890abcdef\r\n0\r\n\r\n"[..]; + let mut decoder = Decoder::chunked(); + + // normal read + let buf = decoder.decode(&mut mock_buf, cx).expect("decode").unwrap(); + assert_eq!(16, buf.len()); + let result = String::from_utf8(buf.as_ref().to_vec()).expect("decode String"); + assert_eq!("1234567890abcdef", &result); - // normal read - let buf = decoder.decode(&mut mock_buf).expect("decode").unwrap(); - assert_eq!(16, buf.len()); - let result = String::from_utf8(buf.as_ref().to_vec()).expect("decode String"); - assert_eq!("1234567890abcdef", &result); + // eof read + let buf = decoder.decode(&mut mock_buf, cx).expect("decode").unwrap(); + assert_eq!(0, buf.len()); - // eof read - let buf = decoder.decode(&mut mock_buf).expect("decode").unwrap(); - assert_eq!(0, buf.len()); + // ensure read after eof also returns eof + let buf = decoder.decode(&mut mock_buf, cx).expect("decode").unwrap(); + assert_eq!(0, buf.len()); - // ensure read after eof also returns eof - let buf = decoder.decode(&mut mock_buf).expect("decode").unwrap(); - assert_eq!(0, buf.len()); + Ok::<_, ()>(()) + })).unwrap() } // perform an async read using a custom buffer size and causing a blocking // read at the specified byte fn read_async(mut decoder: Decoder, + cx: &mut task::Context, content: &[u8], block_at: usize) -> String { diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -490,14 +516,14 @@ mod tests { let mut ins = AsyncIo::new(content, block_at); let mut outs = Vec::new(); loop { - match decoder.decode(&mut ins).expect("unexpected decode error: {}") { + match decoder.decode(&mut ins, cx).expect("unexpected decode error: {}") { Async::Ready(buf) => { if buf.is_empty() { break; // eof } outs.write(buf.as_ref()).expect("write buffer"); }, - Async::NotReady => { + Async::Pending => { ins.block_in(content_len); // we only block once } }; diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -508,11 +534,14 @@ mod tests { // iterate over the different ways that this async read could go. // tests blocking a read at each byte along the content - The shotgun approach fn all_async_cases(content: &str, expected: &str, decoder: Decoder) { - let content_len = content.len(); - for block_at in 0..content_len { - let actual = read_async(decoder.clone(), content.as_bytes(), block_at); - assert_eq!(expected, &actual) //, "Failed async. Blocking at {}", block_at); - } + block_on(lazy(|cx| { + let content_len = content.len(); + for block_at in 0..content_len { + let actual = read_async(decoder.clone(), cx, content.as_bytes(), block_at); + assert_eq!(expected, &actual) //, "Failed async. Blocking at {}", block_at); + } + Ok::<_, ()>(()) + })).unwrap() } #[test] diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -487,31 +489,32 @@ mod tests { extern crate pretty_env_logger; use super::*; + use futures::executor::block_on; + use futures::future::lazy; use mock::AsyncIo; use proto::ClientTransaction; #[test] fn client_read_bytes_before_writing_request() { let _ = pretty_env_logger::try_init(); - ::futures::lazy(|| { + block_on(lazy(|cx| { let io = AsyncIo::new_buf(b"HTTP/1.1 200 OK\r\n\r\n".to_vec(), 100); let (mut tx, rx) = ::client::dispatch::channel(); let conn = Conn::<_, ::Chunk, ClientTransaction>::new(io); let mut dispatcher = Dispatcher::new(Client::new(rx), conn); - let res_rx = tx.try_send(::Request::new(::Body::empty())).unwrap(); + let mut res_rx = tx.try_send(::Request::new(::Body::empty())).unwrap(); - let a1 = dispatcher.poll().expect("error should be sent on channel"); + let a1 = dispatcher.poll(cx).expect("error should be sent on channel"); assert!(a1.is_ready(), "dispatcher should be closed"); - let err = res_rx.wait() - .expect("callback poll") - .expect_err("callback response"); + let result = res_rx.poll(cx) + .expect("callback poll"); - match err { - (::Error::Cancel(_), Some(_)) => (), - other => panic!("expected Canceled, got {:?}", other), + match result { + Async::Ready(Err((::Error::Cancel(_), Some(_)))) => (), + other => panic!("expected Err(Canceled), got {:?}", other), } - Ok::<(), ()>(()) - }).wait().unwrap(); + Ok::<_, ()>(()) + })).unwrap(); } } diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -568,51 +565,68 @@ impl<T: Buf> Buf for BufDeque<T> { mod tests { use super::*; use std::io::Read; + use futures::task; + use futures::future; + use futures::executor::block_on; + use futures::io::AsyncRead; use mock::AsyncIo; #[cfg(test)] impl<T: Read> MemRead for ::mock::AsyncIo<T> { - fn read_mem(&mut self, len: usize) -> Poll<Bytes, io::Error> { + fn read_mem(&mut self, cx: &mut task::Context, len: usize) -> Poll<Bytes, io::Error> { let mut v = vec![0; len]; - let n = try_nb!(self.read(v.as_mut_slice())); + let n = try_ready!(self.poll_read(cx, v.as_mut_slice())); Ok(Async::Ready(BytesMut::from(&v[..n]).freeze())) } } #[test] fn iobuf_write_empty_slice() { - let mut mock = AsyncIo::new_buf(vec![], 256); - mock.error(io::Error::new(io::ErrorKind::Other, "logic error")); + block_on(future::lazy(|cx| { + let mut mock = AsyncIo::new_buf(vec![], 256); + mock.error(io::Error::new(io::ErrorKind::Other, "logic error")); + + let mut io_buf = Buffered::<_, Cursor<Vec<u8>>>::new(mock); - let mut io_buf = Buffered::<_, Cursor<Vec<u8>>>::new(mock); + // underlying io will return the logic error upon write, + // so we are testing that the io_buf does not trigger a write + // when there is nothing to flush + io_buf.flush(cx).expect("should short-circuit flush"); - // underlying io will return the logic error upon write, - // so we are testing that the io_buf does not trigger a write - // when there is nothing to flush - io_buf.flush().expect("should short-circuit flush"); + Ok::<_, ()>(()) + })).unwrap() } #[test] fn parse_reads_until_blocked() { - // missing last line ending - let raw = "HTTP/1.1 200 OK\r\n"; + block_on(future::lazy(|cx| { + // missing last line ending + let raw = "HTTP/1.1 200 OK\r\n"; - let mock = AsyncIo::new_buf(raw, raw.len()); - let mut buffered = Buffered::<_, Cursor<Vec<u8>>>::new(mock); - assert_eq!(buffered.parse::<::proto::ClientTransaction>().unwrap(), Async::NotReady); - assert!(buffered.io.blocked()); + let mock = AsyncIo::new_buf(raw, raw.len()); + let mut buffered = Buffered::<_, Cursor<Vec<u8>>>::new(mock); + + assert_eq!(buffered.parse::<::proto::ClientTransaction>(cx).unwrap(), Async::Pending); + assert!(buffered.io.blocked()); + + Ok::<_, ()>(()) + })).unwrap() } #[test] fn write_buf_skips_empty_bufs() { - let mut mock = AsyncIo::new_buf(vec![], 1024); - mock.max_read_vecs(0); // disable vectored IO - let mut buffered = Buffered::<_, Cursor<Vec<u8>>>::new(mock); + block_on(future::lazy(|cx| { + let mut mock = AsyncIo::new_buf(vec![], 1024); + mock.max_read_vecs(0); // disable vectored IO + let mut buffered = Buffered::<_, Cursor<Vec<u8>>>::new(mock); - buffered.buffer(Cursor::new(Vec::new())); - buffered.buffer(Cursor::new(b"hello".to_vec())); - buffered.flush().unwrap(); - assert_eq!(buffered.io, b"hello"); + buffered.buffer(Cursor::new(Vec::new())); + buffered.buffer(Cursor::new(b"hello".to_vec())); + buffered.flush(cx).unwrap(); + assert_eq!(buffered.io, b"hello"); + + Ok::<_, ()>(()) + })).unwrap() } #[test] diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -620,17 +634,22 @@ mod tests { extern crate pretty_env_logger; let _ = pretty_env_logger::try_init(); - let mock = AsyncIo::new_buf(vec![], 1024); - let mut buffered = Buffered::<_, Cursor<Vec<u8>>>::new(mock); + block_on(future::lazy(|cx| { + let mock = AsyncIo::new_buf(vec![], 1024); + let mut buffered = Buffered::<_, Cursor<Vec<u8>>>::new(mock); + + buffered.write_buf_mut().extend(b"hello "); + buffered.buffer(Cursor::new(b"world, ".to_vec())); + buffered.write_buf_mut().extend(b"it's "); + buffered.buffer(Cursor::new(b"hyper!".to_vec())); + assert_eq!(buffered.io.num_writes(), 0); + buffered.flush(cx).unwrap(); - buffered.write_buf_mut().extend(b"hello "); - buffered.buffer(Cursor::new(b"world, ".to_vec())); - buffered.write_buf_mut().extend(b"it's "); - buffered.buffer(Cursor::new(b"hyper!".to_vec())); - buffered.flush().unwrap(); + assert_eq!(buffered.io, b"hello world, it's hyper!"); + assert_eq!(buffered.io.num_writes(), 1); - assert_eq!(buffered.io, b"hello world, it's hyper!"); - assert_eq!(buffered.io.num_writes(), 1); + Ok::<_, ()>(()) + })).unwrap() } #[test] diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -638,27 +657,31 @@ mod tests { extern crate pretty_env_logger; let _ = pretty_env_logger::try_init(); - let mock = AsyncIo::new_buf(vec![], 1024); - let mut buffered = Buffered::<_, Cursor<Vec<u8>>>::new(mock); + block_on(future::lazy(|cx| { + let mock = AsyncIo::new_buf(vec![], 1024); + let mut buffered = Buffered::<_, Cursor<Vec<u8>>>::new(mock); - buffered.write_buf_mut().extend(b"hello "); - assert_eq!(buffered.write_buf.buf.bufs.len(), 1); - buffered.write_buf_mut().extend(b"world, "); - assert_eq!(buffered.write_buf.buf.bufs.len(), 1); + buffered.write_buf_mut().extend(b"hello "); + assert_eq!(buffered.write_buf.buf.bufs.len(), 1); + buffered.write_buf_mut().extend(b"world, "); + assert_eq!(buffered.write_buf.buf.bufs.len(), 1); - // after flushing, reclaim the Vec - buffered.flush().unwrap(); - assert_eq!(buffered.write_buf.remaining(), 0); - assert_eq!(buffered.write_buf.buf.bufs.len(), 1); + // after flushing, reclaim the Vec + buffered.flush(cx).unwrap(); + assert_eq!(buffered.write_buf.remaining(), 0); + assert_eq!(buffered.write_buf.buf.bufs.len(), 1); - // add a user buf in the way - buffered.buffer(Cursor::new(b"it's ".to_vec())); - // and then add more hyper bytes - buffered.write_buf_mut().extend(b"hyper!"); - buffered.flush().unwrap(); - assert_eq!(buffered.write_buf.buf.bufs.len(), 1); + // add a user buf in the way + buffered.buffer(Cursor::new(b"it's ".to_vec())); + // and then add more hyper bytes + buffered.write_buf_mut().extend(b"hyper!"); + buffered.flush(cx).unwrap(); + assert_eq!(buffered.write_buf.buf.bufs.len(), 1); - assert_eq!(buffered.io, b"hello world, it's hyper!"); + assert_eq!(buffered.io, b"hello world, it's hyper!"); + + Ok::<_, ()>(()) + })).unwrap() } #[test] diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -666,21 +689,25 @@ mod tests { extern crate pretty_env_logger; let _ = pretty_env_logger::try_init(); - let mock = AsyncIo::new_buf(vec![], 1024); - let mut buffered = Buffered::<_, Cursor<Vec<u8>>>::new(mock); - buffered.write_buf.set_strategy(Strategy::Flatten); + block_on(future::lazy(|cx| { + let mock = AsyncIo::new_buf(vec![], 1024); + let mut buffered = Buffered::<_, Cursor<Vec<u8>>>::new(mock); + buffered.write_buf.set_strategy(Strategy::Flatten); + + buffered.write_buf_mut().extend(b"hello "); + buffered.buffer(Cursor::new(b"world, ".to_vec())); + buffered.write_buf_mut().extend(b"it's "); + buffered.buffer(Cursor::new(b"hyper!".to_vec())); + assert_eq!(buffered.write_buf.buf.bufs.len(), 1); - buffered.write_buf_mut().extend(b"hello "); - buffered.buffer(Cursor::new(b"world, ".to_vec())); - buffered.write_buf_mut().extend(b"it's "); - buffered.buffer(Cursor::new(b"hyper!".to_vec())); - assert_eq!(buffered.write_buf.buf.bufs.len(), 1); + buffered.flush(cx).unwrap(); - buffered.flush().unwrap(); + assert_eq!(buffered.io, b"hello world, it's hyper!"); + assert_eq!(buffered.io.num_writes(), 1); + assert_eq!(buffered.write_buf.buf.bufs.len(), 1); - assert_eq!(buffered.io, b"hello world, it's hyper!"); - assert_eq!(buffered.io.num_writes(), 1); - assert_eq!(buffered.write_buf.buf.bufs.len(), 1); + Ok::<_, ()>(()) + })).unwrap() } #[test] diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -688,22 +715,26 @@ mod tests { extern crate pretty_env_logger; let _ = pretty_env_logger::try_init(); - let mut mock = AsyncIo::new_buf(vec![], 1024); - mock.max_read_vecs(0); // disable vectored IO - let mut buffered = Buffered::<_, Cursor<Vec<u8>>>::new(mock); + block_on(future::lazy(|cx| { + let mut mock = AsyncIo::new_buf(vec![], 1024); + mock.max_read_vecs(0); // disable vectored IO + let mut buffered = Buffered::<_, Cursor<Vec<u8>>>::new(mock); + + // we have 4 buffers, but hope to detect that vectored IO isn't + // being used, and switch to flattening automatically, + // resulting in only 2 writes + buffered.write_buf_mut().extend(b"hello "); + buffered.buffer(Cursor::new(b"world, ".to_vec())); + buffered.write_buf_mut().extend(b"it's hyper!"); + //buffered.buffer(Cursor::new(b"hyper!".to_vec())); + buffered.flush(cx).unwrap(); - // we have 4 buffers, but hope to detect that vectored IO isn't - // being used, and switch to flattening automatically, - // resulting in only 2 writes - buffered.write_buf_mut().extend(b"hello "); - buffered.buffer(Cursor::new(b"world, ".to_vec())); - buffered.write_buf_mut().extend(b"it's hyper!"); - //buffered.buffer(Cursor::new(b"hyper!".to_vec())); - buffered.flush().unwrap(); + assert_eq!(buffered.io, b"hello world, it's hyper!"); + assert_eq!(buffered.io.num_writes(), 2); + assert_eq!(buffered.write_buf.buf.bufs.len(), 1); - assert_eq!(buffered.io, b"hello world, it's hyper!"); - assert_eq!(buffered.io.num_writes(), 2); - assert_eq!(buffered.write_buf.buf.bufs.len(), 1); + Ok::<_, ()>(()) + })).unwrap() } #[test] diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -711,20 +742,24 @@ mod tests { extern crate pretty_env_logger; let _ = pretty_env_logger::try_init(); - let mut mock = AsyncIo::new_buf(vec![], 1024); - mock.max_read_vecs(0); // disable vectored IO - let mut buffered = Buffered::<_, Cursor<Vec<u8>>>::new(mock); - buffered.write_buf.set_strategy(Strategy::Queue); - - // we have 4 buffers, and vec IO disabled, but explicitly said - // don't try to auto detect (via setting strategy above) - buffered.write_buf_mut().extend(b"hello "); - buffered.buffer(Cursor::new(b"world, ".to_vec())); - buffered.write_buf_mut().extend(b"it's "); - buffered.buffer(Cursor::new(b"hyper!".to_vec())); - buffered.flush().unwrap(); - - assert_eq!(buffered.io, b"hello world, it's hyper!"); - assert_eq!(buffered.io.num_writes(), 4); + block_on(future::lazy(move |cx| { + let mut mock = AsyncIo::new_buf(vec![], 1024); + mock.max_read_vecs(0); // disable vectored IO + let mut buffered = Buffered::<_, Cursor<Vec<u8>>>::new(mock); + buffered.write_buf.set_strategy(Strategy::Queue); + + // we have 4 buffers, and vec IO disabled, but explicitly said + // don't try to auto detect (via setting strategy above) + buffered.write_buf_mut().extend(b"hello "); + buffered.buffer(Cursor::new(b"world, ".to_vec())); + buffered.write_buf_mut().extend(b"it's "); + buffered.buffer(Cursor::new(b"hyper!".to_vec())); + buffered.flush(cx).unwrap(); + + assert_eq!(buffered.io, b"hello world, it's hyper!"); + assert_eq!(buffered.io.num_writes(), 4); + + Ok::<_, ()>(()) + })).unwrap() } } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -5,7 +5,6 @@ extern crate futures; extern crate futures_timer; extern crate net2; extern crate tokio; -extern crate tokio_io; extern crate pretty_env_logger; use std::io::{self, Read, Write}; diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -15,8 +14,9 @@ use std::time::Duration; use hyper::{Body, Client, Method, Request, StatusCode}; -use futures::{Future, Stream}; -use futures::sync::oneshot; +use futures::{FutureExt, StreamExt}; +use futures::channel::oneshot; +use futures::executor::block_on; use tokio::reactor::Handle; use tokio::runtime::Runtime; use tokio::net::{ConnectFuture, TcpStream}; diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -111,11 +111,7 @@ macro_rules! test { assert_eq!(res.headers()[$response_header_name], $response_header_val); )* - let body = res - .into_body() - .into_stream() - .concat2() - .wait() + let body = block_on(res.into_body().into_stream().concat()) .expect("body concat wait"); let expected_res_body = Option::<&[u8]>::from($response_body) diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -186,7 +182,7 @@ macro_rules! test { if !$set_host { config = config.set_host(false); } - let client = config.build_with_executor(&runtime.handle(), runtime.executor()); + let client = config.build(&runtime.handle()); let body = if let Some(body) = $request_body { let body: &'static str = body; diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -203,7 +199,7 @@ macro_rules! test { .body(body) .expect("request builder"); - let res = client.request(req); + let res = client.request(req).with_executor(runtime.executor()); let (tx, rx) = oneshot::channel(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -230,7 +226,7 @@ macro_rules! test { let rx = rx.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); - res.join(rx).map(|r| r.0).wait() + block_on(res.join(rx).map(|r| r.0)) }); } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -642,12 +638,15 @@ mod dispatch_impl { use std::thread; use std::time::Duration; - use futures::{self, Future}; - use futures::sync::{mpsc, oneshot}; + use futures::{self, Future, FutureExt, Stream, StreamExt}; + use futures::channel::{mpsc, oneshot}; + use futures::io::{AsyncRead, AsyncWrite}; + use futures::future::lazy; + use futures::executor::block_on; + use futures::task; use futures_timer::Delay; use tokio::net::TcpStream; use tokio::runtime::Runtime; - use tokio_io::{AsyncRead, AsyncWrite}; use hyper::client::connect::{Connect, Connected, Destination, HttpConnector}; use hyper::Client; diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -666,7 +665,7 @@ mod dispatch_impl { let (closes_tx, closes) = mpsc::channel(10); let client = Client::configure() .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &runtime.handle()), closes_tx)) - .executor(runtime.executor()); + .build(); let (tx1, rx1) = oneshot::channel(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -686,15 +685,15 @@ mod dispatch_impl { .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); - let res = client.request(req).and_then(move |res| { + let res = client.request(req).with_executor(runtime.executor()).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); Delay::new(Duration::from_secs(1)) - .from_err() + .err_into() }); let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); - res.join(rx).map(|r| r.0).wait().unwrap(); + block_on(res.join(rx).map(|r| r.0)).unwrap(); - closes.into_future().wait().unwrap().0.expect("closes"); + block_on(closes.next()).unwrap().0.expect("closes"); } #[test] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -725,25 +724,25 @@ mod dispatch_impl { let res = { let client = Client::configure() .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes_tx)) - .executor(runtime.executor()); + .build(); let req = Request::builder() .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); - client.request(req).and_then(move |res| { + client.request(req).with_executor(runtime.executor()).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); - res.into_body().into_stream().concat2() + res.into_body().into_stream().concat() }).and_then(|_| { Delay::new(Duration::from_secs(1)) - .from_err() + .err_into() }) }; // client is dropped let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); - res.join(rx).map(|r| r.0).wait().unwrap(); + block_on(res.join(rx).map(|r| r.0)).unwrap(); - closes.into_future().wait().unwrap().0.expect("closes"); + block_on(closes.next()).unwrap().0.expect("closes"); } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -773,41 +772,41 @@ mod dispatch_impl { // prevent this thread from closing until end of test, so the connection // stays open and idle until Client is dropped - let _ = client_drop_rx.wait(); + let _ = block_on(client_drop_rx); }); let client = Client::configure() .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes_tx)) - .executor(runtime.executor()); + .build(); let req = Request::builder() .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); - let res = client.request(req).and_then(move |res| { + let res = client.request(req).with_executor(runtime.executor()).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); - res.into_body().into_stream().concat2() + res.into_body().into_stream().concat() }); let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); - res.join(rx).map(|r| r.0).wait().unwrap(); + block_on(res.join(rx).map(|r| r.0)).unwrap(); // not closed yet, just idle { - futures::future::poll_fn(|| { - assert!(closes.poll()?.is_not_ready()); - Ok::<_, ()>(().into()) - }).wait().unwrap(); + block_on(lazy(|cx| { + assert!(closes.poll_next(cx).unwrap().is_pending()); + Ok::<_, ()>(()) + })).unwrap(); } drop(client); let t = Delay::new(Duration::from_millis(100)) .map(|_| panic!("time out")); - let close = closes.into_future() + let close = closes.next() .map(|(opt, _)| { opt.expect("closes"); }) .map_err(|_| panic!("closes dropped")); - let _ = t.select(close).wait(); + let _ = block_on(t.select(close)); } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -836,32 +835,32 @@ mod dispatch_impl { // prevent this thread from closing until end of test, so the connection // stays open and idle until Client is dropped - let _ = client_drop_rx.wait(); + let _ = block_on(client_drop_rx); }); let res = { let client = Client::configure() .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes_tx)) - .executor(runtime.executor()); + .build(); let req = Request::builder() .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); - client.request(req) + client.request(req).with_executor(runtime.executor()) }; //let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); - res.select2(rx1).wait().unwrap(); + block_on(res.select(rx1)).unwrap(); // res now dropped let t = Delay::new(Duration::from_millis(100)) .map(|_| panic!("time out")); - let close = closes.into_future() + let close = closes.next() .map(|(opt, _)| { opt.expect("closes"); }) .map_err(|_| panic!("closes dropped")); - let _ = t.select(close).wait(); + let _ = block_on(t.select(close)); } #[test] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -888,33 +887,33 @@ mod dispatch_impl { // prevent this thread from closing until end of test, so the connection // stays open and idle until Client is dropped - let _ = client_drop_rx.wait(); + let _ = block_on(client_drop_rx); }); let res = { let client = Client::configure() .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes_tx)) - .executor(runtime.executor()); + .build(); let req = Request::builder() .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); // notably, havent read body yet - client.request(req) + client.request(req).with_executor(runtime.executor()) }; let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); - res.join(rx).map(|r| r.0).wait().unwrap(); + block_on(res.join(rx).map(|r| r.0)).unwrap(); let t = Delay::new(Duration::from_millis(100)) .map(|_| panic!("time out")); - let close = closes.into_future() + let close = closes.next() .map(|(opt, _)| { opt.expect("closes"); }) .map_err(|_| panic!("closes dropped")); - let _ = t.select(close).wait(); + let _ = block_on(t.select(close)); } #[test] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -939,33 +938,33 @@ mod dispatch_impl { sock.read(&mut buf).expect("read 1"); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap(); let _ = tx1.send(()); - let _ = rx2.wait(); + let _ = block_on(rx2); }); let client = Client::configure() .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes_tx)) .keep_alive(false) - .executor(runtime.executor()); + .build(); let req = Request::builder() .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); - let res = client.request(req).and_then(move |res| { + let res = client.request(req).with_executor(runtime.executor()).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); - res.into_body().into_stream().concat2() + res.into_body().into_stream().concat() }); let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); - res.join(rx).map(|r| r.0).wait().unwrap(); + block_on(res.join(rx).map(|r| r.0)).unwrap(); let t = Delay::new(Duration::from_millis(100)) .map(|_| panic!("time out")); - let close = closes.into_future() + let close = closes.next() .map(|(opt, _)| { opt.expect("closes"); }) .map_err(|_| panic!("closes dropped")); - let _ = t.select(close).wait(); + let _ = block_on(t.select(close)); } #[test] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -993,28 +992,28 @@ mod dispatch_impl { let client = Client::configure() .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes_tx)) - .executor(runtime.executor()); + .build(); let req = Request::builder() .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); - let res = client.request(req).and_then(move |res| { + let res = client.request(req).with_executor(runtime.executor()).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); - res.into_body().into_stream().concat2() + res.into_body().into_stream().concat() }); let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); - res.join(rx).map(|r| r.0).wait().unwrap(); + block_on(res.join(rx).map(|r| r.0)).unwrap(); let t = Delay::new(Duration::from_millis(100)) .map(|_| panic!("time out")); - let close = closes.into_future() + let close = closes.next() .map(|(opt, _)| { opt.expect("closes"); }) .map_err(|_| panic!("closes dropped")); - let _ = t.select(close).wait(); + let _ = block_on(t.select(close)); } #[test] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1026,11 +1025,13 @@ mod dispatch_impl { // See https://github.com/hyperium/hyper/issues/1429 use std::error::Error; + use tokio::prelude::Future; let _ = pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let runtime = Runtime::new().unwrap(); + let executor = runtime.executor(); let handle = runtime.handle().clone(); let (tx1, rx1) = oneshot::channel(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1042,27 +1043,27 @@ mod dispatch_impl { let mut buf = [0; 4096]; sock.read(&mut buf).expect("read 1"); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap(); - sock.read(&mut buf).expect("read 2"); + //sock.read(&mut buf).expect("read 2"); let _ = tx1.send(()); }); let uri = format!("http://{}/a", addr).parse::<hyper::Uri>().unwrap(); - let client = Client::configure().build_with_executor(&handle, runtime.executor()); + let client = Client::configure().build(&handle); let req = Request::builder() .uri(uri.clone()) .body(Body::empty()) .unwrap(); - let res = client.request(req).and_then(move |res| { + let res = client.request(req).with_executor(executor.clone()).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); - res.into_body().into_stream().concat2() + res.into_body().into_stream().concat() }); - res.wait().unwrap(); + block_on(res).unwrap(); - // drop previous runtime - drop(runtime); + // shut down runtime + runtime.shutdown_now().wait().unwrap(); let timeout = Delay::new(Duration::from_millis(200)); let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1071,10 +1072,10 @@ mod dispatch_impl { .uri(uri) .body(Body::empty()) .unwrap(); - let res = client.request(req); + let res = client.request(req).with_executor(executor); // this does trigger an 'event loop gone' error, but before, it would // panic internally on a `SendError`, which is what we're testing against. - let err = res.join(rx).map(|r| r.0).wait().unwrap_err(); + let err = block_on(res.join(rx).map(|r| r.0)).unwrap_err(); assert_eq!(err.description(), "event loop gone"); } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1100,31 +1101,31 @@ mod dispatch_impl { let client = Client::configure() .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes_tx)) - .executor(runtime.executor()); + .build(); let req = Request::builder() .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); - let res = client.request(req).and_then(move |res| { + let res = client.request(req).with_executor(runtime.executor()).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); - res.into_body().into_stream().concat2() + res.into_body().into_stream().concat() }); let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); let timeout = Delay::new(Duration::from_millis(200)); let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); - res.join(rx).map(|r| r.0).wait().unwrap(); + block_on(res.join(rx).map(|r| r.0)).unwrap(); let t = Delay::new(Duration::from_millis(100)) .map(|_| panic!("time out")); - let close = closes.into_future() + let close = closes.next() .map(|(opt, _)| { opt.expect("closes"); }) .map_err(|_| panic!("closes dropped")); - let _ = t.select(close).wait(); + let _ = block_on(t.select(close)); } #[test] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1140,14 +1141,14 @@ mod dispatch_impl { let client = Client::configure() .connector(connector) - .executor(runtime.executor()); + .build(); assert_eq!(connects.load(Ordering::Relaxed), 0); let req = Request::builder() .uri("http://hyper.local/a") .body(Default::default()) .unwrap(); - let _fut = client.request(req); + let _fut = client.request(req).with_executor(runtime.executor()); // internal Connect::connect should have been lazy, and not // triggered an actual connect yet. assert_eq!(connects.load(Ordering::Relaxed), 0); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1165,7 +1166,7 @@ mod dispatch_impl { let client = Client::configure() .connector(connector) - .executor(runtime.executor()); + .build(); let (tx1, rx1) = oneshot::channel(); let (tx2, rx2) = oneshot::channel(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1195,8 +1196,8 @@ mod dispatch_impl { .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); - let res = client.request(req); - res.join(rx).map(|r| r.0).wait().unwrap(); + let res = client.request(req).with_executor(runtime.executor()); + block_on(res.join(rx).map(|r| r.0)).unwrap(); assert_eq!(connects.load(Ordering::SeqCst), 1); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1209,8 +1210,8 @@ mod dispatch_impl { .uri(&*format!("http://{}/b", addr)) .body(Body::empty()) .unwrap(); - let res = client.request(req); - res.join(rx).map(|r| r.0).wait().unwrap(); + let res = client.request(req).with_executor(runtime.executor()); + block_on(res.join(rx).map(|r| r.0)).unwrap(); assert_eq!(connects.load(Ordering::SeqCst), 1, "second request should still only have 1 connect"); } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1228,7 +1229,7 @@ mod dispatch_impl { let client = Client::configure() .connector(connector) - .executor(runtime.executor()); + .build(); let (tx1, rx1) = oneshot::channel(); let (tx2, rx2) = oneshot::channel(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1261,8 +1262,8 @@ mod dispatch_impl { .uri(&*format!("http://{}/a", addr)) .body(Body::empty()) .unwrap(); - let res = client.request(req); - res.join(rx).map(|r| r.0).wait().unwrap(); + let res = client.request(req).with_executor(runtime.executor()); + block_on(res.join(rx).map(|r| r.0)).unwrap(); assert_eq!(connects.load(Ordering::Relaxed), 1); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1271,8 +1272,8 @@ mod dispatch_impl { .uri(&*format!("http://{}/b", addr)) .body(Body::empty()) .unwrap(); - let res = client.request(req); - res.join(rx).map(|r| r.0).wait().unwrap(); + let res = client.request(req).with_executor(runtime.executor()); + block_on(res.join(rx).map(|r| r.0)).unwrap(); assert_eq!(connects.load(Ordering::Relaxed), 2); } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1289,7 +1290,7 @@ mod dispatch_impl { let client = Client::configure() .connector(connector) - .executor(runtime.executor()); + .build(); let (tx1, rx1) = oneshot::channel(); thread::spawn(move || { diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1312,8 +1313,8 @@ mod dispatch_impl { .uri(&*format!("http://{}/foo/bar", addr)) .body(Body::empty()) .unwrap(); - let res = client.request(req); - res.join(rx).map(|r| r.0).wait().unwrap(); + let res = client.request(req).with_executor(runtime.executor()); + block_on(res.join(rx).map(|r| r.0)).unwrap(); } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1369,33 +1370,25 @@ mod dispatch_impl { } } - impl Write for DebugStream { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.0.write(buf) + impl AsyncWrite for DebugStream { + fn poll_write(&mut self, cx: &mut task::Context, buf: &[u8]) -> futures::Poll<usize, io::Error> { + self.0.poll_write(cx, buf) } - fn flush(&mut self) -> io::Result<()> { - self.0.flush() - } - } - - impl AsyncWrite for DebugStream { - fn shutdown(&mut self) -> futures::Poll<(), io::Error> { - AsyncWrite::shutdown(&mut self.0) + fn poll_flush(&mut self, cx: &mut task::Context) -> futures::Poll<(), io::Error> { + self.0.poll_flush(cx) } - fn write_buf<B: ::bytes::Buf>(&mut self, buf: &mut B) -> futures::Poll<usize, io::Error> { - self.0.write_buf(buf) + fn poll_close(&mut self, cx: &mut task::Context) -> futures::Poll<(), io::Error> { + self.0.poll_close(cx) } } - impl Read for DebugStream { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.0.read(buf) + impl AsyncRead for DebugStream { + fn poll_read(&mut self, cx: &mut task::Context, buf: &mut [u8]) -> futures::Poll<usize, io::Error> { + self.0.poll_read(cx, buf) } } - - impl AsyncRead for DebugStream {} } mod conn { diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1404,13 +1397,15 @@ mod conn { use std::thread; use std::time::Duration; - use futures::{Async, Future, Poll, Stream}; - use futures::future::poll_fn; - use futures::sync::oneshot; + use futures::{FutureExt, Poll, StreamExt}; + use futures::future::{poll_fn, lazy}; + use futures::channel::oneshot; + use futures::task; + use futures::io::{AsyncRead, AsyncWrite}; + use futures::executor::block_on; use futures_timer::Delay; use tokio::runtime::Runtime; use tokio::net::TcpStream; - use tokio_io::{AsyncRead, AsyncWrite}; use hyper::{self, Request}; use hyper::client::conn; diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1442,11 +1437,11 @@ mod conn { let _ = tx1.send(()); }); - let tcp = tcp_connect(&addr).wait().unwrap(); + let tcp = block_on(tcp_connect(&addr)).unwrap(); - let (mut client, conn) = conn::handshake(tcp).wait().unwrap(); + let (mut client, conn) = block_on(conn::handshake(tcp)).unwrap(); - runtime.spawn(conn.map(|_| ()).map_err(|e| panic!("conn error: {}", e))); + runtime.spawn2(conn.map(|_| ()).map_err(|e| panic!("conn error: {}", e))); let req = Request::builder() .uri("/a") diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1454,13 +1449,13 @@ mod conn { .unwrap(); let res = client.send_request(req).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); - res.into_body().into_stream().concat2() + res.into_body().into_stream().concat() }); let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); let timeout = Delay::new(Duration::from_millis(200)); let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); - res.join(rx).map(|r| r.0).wait().unwrap(); + block_on(res.join(rx).map(|r| r.0)).unwrap(); } #[test] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1487,11 +1482,11 @@ mod conn { let _ = tx1.send(()); }); - let tcp = tcp_connect(&addr).wait().unwrap(); + let tcp = block_on(tcp_connect(&addr)).unwrap(); - let (mut client, conn) = conn::handshake(tcp).wait().unwrap(); + let (mut client, conn) = block_on(conn::handshake(tcp)).unwrap(); - runtime.spawn(conn.map(|_| ()).map_err(|e| panic!("conn error: {}", e))); + runtime.spawn2(conn.map(|_| ()).map_err(|e| panic!("conn error: {}", e))); let req = Request::builder() .uri("http://hyper.local/a") diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1500,13 +1495,13 @@ mod conn { let res = client.send_request(req).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); - res.into_body().into_stream().concat2() + res.into_body().into_stream().concat() }); let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); let timeout = Delay::new(Duration::from_millis(200)); let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); - res.join(rx).map(|r| r.0).wait().unwrap(); + block_on(res.join(rx).map(|r| r.0)).unwrap(); } #[test] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1528,11 +1523,11 @@ mod conn { let _ = tx1.send(()); }); - let tcp = tcp_connect(&addr).wait().unwrap(); + let tcp = block_on(tcp_connect(&addr)).unwrap(); - let (mut client, conn) = conn::handshake(tcp).wait().unwrap(); + let (mut client, conn) = block_on(conn::handshake(tcp)).unwrap(); - runtime.spawn(conn.map(|_| ()).map_err(|e| panic!("conn error: {}", e))); + runtime.spawn2(conn.map(|_| ()).map_err(|e| panic!("conn error: {}", e))); let req = Request::builder() .uri("/a") diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1540,10 +1535,10 @@ mod conn { .unwrap(); let res1 = client.send_request(req).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); - res.into_body().into_stream().concat2() + res.into_body().into_stream().concat() }); - // pipelined request will hit NotReady, and thus should return an Error::Cancel + // pipelined request will hit Pending, and thus should return an Error::Cancel let req = Request::builder() .uri("/b") .body(Default::default()) diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1562,12 +1557,12 @@ mod conn { let timeout = Delay::new(Duration::from_millis(200)); let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); - res1.join(res2).join(rx).map(|r| r.0).wait().unwrap(); + block_on(res1.join(res2).join(rx).map(|r| r.0)).unwrap(); } #[test] fn upgrade() { - use tokio_io::io::{read_to_end, write_all}; + use futures::io::{AsyncReadExt, AsyncWriteExt}; let _ = ::pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1595,18 +1590,18 @@ mod conn { sock.write_all(b"bar=foo").expect("write 2"); }); - let tcp = tcp_connect(&addr).wait().unwrap(); + let tcp = block_on(tcp_connect(&addr)).unwrap(); let io = DebugStream { tcp: tcp, shutdown_called: false, }; - let (mut client, mut conn) = conn::handshake(io).wait().unwrap(); + let (mut client, mut conn) = block_on(conn::handshake(io)).unwrap(); { - let until_upgrade = poll_fn(|| { - conn.poll_without_shutdown() + let until_upgrade = poll_fn(|cx| { + conn.poll_without_shutdown(cx) }); let req = Request::builder() diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1616,20 +1611,20 @@ mod conn { let res = client.send_request(req).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::SWITCHING_PROTOCOLS); assert_eq!(res.headers()["Upgrade"], "foobar"); - res.into_body().into_stream().concat2() + res.into_body().into_stream().concat() }); let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); let timeout = Delay::new(Duration::from_millis(200)); let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); - until_upgrade.join(res).join(rx).map(|r| r.0).wait().unwrap(); + block_on(until_upgrade.join(res).join(rx).map(|r| r.0)).unwrap(); // should not be ready now - poll_fn(|| { - assert!(client.poll_ready().unwrap().is_not_ready()); - Ok::<_, ()>(Async::Ready(())) - }).wait().unwrap(); + block_on(lazy(|cx| { + assert!(client.poll_ready(cx).unwrap().is_pending()); + Ok::<_, ()>(()) + })).unwrap(); } let parts = conn.into_parts(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1638,16 +1633,16 @@ mod conn { assert_eq!(buf, b"foobar=ready"[..]); assert!(!io.shutdown_called, "upgrade shouldn't shutdown AsyncWrite"); - assert!(client.poll_ready().is_err()); + assert!(block_on(poll_fn(|cx| client.poll_ready(cx))).is_err()); - let io = write_all(io, b"foo=bar").wait().unwrap().0; - let vec = read_to_end(io, vec![]).wait().unwrap().1; + let io = block_on(io.write_all(b"foo=bar")).unwrap().0; + let vec = block_on(io.read_to_end(vec![])).unwrap().1; assert_eq!(vec, b"bar=foo"); } #[test] fn connect_method() { - use tokio_io::io::{read_to_end, write_all}; + use futures::io::{AsyncReadExt, AsyncWriteExt}; let _ = ::pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1674,18 +1669,18 @@ mod conn { sock.write_all(b"bar=foo").expect("write 2"); }); - let tcp = tcp_connect(&addr).wait().unwrap(); + let tcp = block_on(tcp_connect(&addr)).unwrap(); let io = DebugStream { tcp: tcp, shutdown_called: false, }; - let (mut client, mut conn) = conn::handshake(io).wait().unwrap(); + let (mut client, mut conn) = block_on(conn::handshake(io)).unwrap(); { - let until_tunneled = poll_fn(|| { - conn.poll_without_shutdown() + let until_tunneled = poll_fn(|cx| { + conn.poll_without_shutdown(cx) }); let req = Request::builder() diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1696,7 +1691,7 @@ mod conn { let res = client.send_request(req) .and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::OK); - res.into_body().into_stream().concat2() + res.into_body().into_stream().concat() }) .map(|body| { assert_eq!(body.as_ref(), b""); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1706,13 +1701,13 @@ mod conn { let timeout = Delay::new(Duration::from_millis(200)); let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); - until_tunneled.join(res).join(rx).map(|r| r.0).wait().unwrap(); + block_on(until_tunneled.join(res).join(rx).map(|r| r.0)).unwrap(); // should not be ready now - poll_fn(|| { - assert!(client.poll_ready().unwrap().is_not_ready()); - Ok::<_, ()>(Async::Ready(())) - }).wait().unwrap(); + block_on(lazy(|cx| { + assert!(client.poll_ready(cx).unwrap().is_pending()); + Ok::<_, ()>(()) + })).unwrap(); } let parts = conn.into_parts(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1721,10 +1716,10 @@ mod conn { assert_eq!(buf, b"foobar=ready"[..]); assert!(!io.shutdown_called, "tunnel shouldn't shutdown AsyncWrite"); - assert!(client.poll_ready().is_err()); + assert!(block_on(poll_fn(|cx| client.poll_ready(cx))).is_err()); - let io = write_all(io, b"foo=bar").wait().unwrap().0; - let vec = read_to_end(io, vec![]).wait().unwrap().1; + let io = block_on(io.write_all(b"foo=bar")).unwrap().0; + let vec = block_on(io.read_to_end(vec![])).unwrap().1; assert_eq!(vec, b"bar=foo"); } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1733,28 +1728,24 @@ mod conn { shutdown_called: bool, } - impl Write for DebugStream { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.tcp.write(buf) + impl AsyncWrite for DebugStream { + fn poll_write(&mut self, cx: &mut task::Context, buf: &[u8]) -> Poll<usize, io::Error> { + self.tcp.poll_write(cx, buf) } - fn flush(&mut self) -> io::Result<()> { - self.tcp.flush() + fn poll_flush(&mut self, cx: &mut task::Context) -> Poll<(), io::Error> { + self.tcp.poll_flush(cx) } - } - impl AsyncWrite for DebugStream { - fn shutdown(&mut self) -> Poll<(), io::Error> { + fn poll_close(&mut self, cx: &mut task::Context) -> Poll<(), io::Error> { self.shutdown_called = true; - AsyncWrite::shutdown(&mut self.tcp) + self.tcp.poll_close(cx) } } - impl Read for DebugStream { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.tcp.read(buf) + impl AsyncRead for DebugStream { + fn poll_read(&mut self, cx: &mut task::Context, buf: &mut [u8]) -> Poll<usize, io::Error> { + self.tcp.poll_read(cx, buf) } } - - impl AsyncRead for DebugStream {} } diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -8,7 +8,6 @@ extern crate net2; extern crate spmc; extern crate pretty_env_logger; extern crate tokio; -extern crate tokio_io; use std::net::{TcpStream, Shutdown, SocketAddr}; use std::io::{self, Read, Write}; diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -19,16 +18,18 @@ use std::net::{TcpListener as StdTcpListener}; use std::thread; use std::time::Duration; -use futures::{Future, Stream}; +use futures::{Future, FutureExt, StreamExt}; use futures::future::{self, FutureResult, Either}; -use futures::sync::oneshot; +use futures::channel::oneshot; +use futures::executor::block_on; +use futures::task; +use futures::io::{AsyncRead, AsyncWrite}; use futures_timer::Delay; use http::header::{HeaderName, HeaderValue}; //use net2::TcpBuilder; use tokio::net::TcpListener; use tokio::runtime::Runtime; use tokio::reactor::Handle; -use tokio_io::{AsyncRead, AsyncWrite}; use hyper::{Body, Request, Response, StatusCode}; diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -91,14 +92,14 @@ fn get_implicitly_empty() { }); let fut = listener.incoming() - .into_future() + .next() .map_err(|_| unreachable!()) .and_then(|(item, _incoming)| { let socket = item.unwrap(); Http::<hyper::Chunk>::new().serve_connection(socket, GetImplicitlyEmpty) }); - fut.wait().unwrap(); + block_on(fut).unwrap(); struct GetImplicitlyEmpty; diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -111,7 +112,7 @@ fn get_implicitly_empty() { fn call(&self, req: Request<Body>) -> Self::Future { Box::new(req.into_body() .into_stream() - .concat2() + .concat() .map(|buf| { assert!(buf.is_empty()); Response::new(Body::empty()) diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -765,34 +766,34 @@ fn disable_keep_alive_mid_request() { let mut req = connect(&addr); req.write_all(b"GET / HTTP/1.1\r\n").unwrap(); tx1.send(()).unwrap(); - rx2.wait().unwrap(); + block_on(rx2).unwrap(); req.write_all(b"Host: localhost\r\n\r\n").unwrap(); let mut buf = vec![]; req.read_to_end(&mut buf).unwrap(); }); let fut = listener.incoming() - .into_future() + .next() .map_err(|_| unreachable!()) .and_then(|(item, _incoming)| { let socket = item.unwrap(); Http::<hyper::Chunk>::new().serve_connection(socket, HelloWorld) - .select2(rx1) + .select(rx1) .then(|r| { match r { - Ok(Either::A(_)) => panic!("expected rx first"), - Ok(Either::B(((), mut conn))) => { + Ok(Either::Left(_)) => panic!("expected rx first"), + Ok(Either::Right(((), mut conn))) => { conn.disable_keep_alive(); tx2.send(()).unwrap(); conn } - Err(Either::A((e, _))) => panic!("unexpected error {}", e), - Err(Either::B((e, _))) => panic!("unexpected error {}", e), + Err(Either::Left((e, _))) => panic!("unexpected error {}", e), + Err(Either::Right((e, _))) => panic!("unexpected error {}", e), } }) }); - fut.wait().unwrap(); + block_on(fut).unwrap(); child.join().unwrap(); } diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -833,7 +834,7 @@ fn disable_keep_alive_post_request() { let dropped = Dropped::new(); let dropped2 = dropped.clone(); let fut = listener.incoming() - .into_future() + .next() .map_err(|_| unreachable!()) .and_then(|(item, _incoming)| { let socket = item.expect("accepted socket"); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -842,28 +843,28 @@ fn disable_keep_alive_post_request() { _debug: dropped2, }; Http::<hyper::Chunk>::new().serve_connection(transport, HelloWorld) - .select2(rx1) + .select(rx1) .then(|r| { match r { - Ok(Either::A(_)) => panic!("expected rx first"), - Ok(Either::B(((), mut conn))) => { + Ok(Either::Left(_)) => panic!("expected rx first"), + Ok(Either::Right(((), mut conn))) => { conn.disable_keep_alive(); conn } - Err(Either::A((e, _))) => panic!("unexpected error {}", e), - Err(Either::B((e, _))) => panic!("unexpected error {}", e), + Err(Either::Left((e, _))) => panic!("unexpected error {}", e), + Err(Either::Right((e, _))) => panic!("unexpected error {}", e), } }) }); assert!(!dropped.load()); - fut.wait().unwrap(); + block_on(fut).unwrap(); // we must poll the Core one more time in order for Windows to drop // the read-blocked socket. // // See https://github.com/carllerche/mio/issues/776 let timeout = Delay::new(Duration::from_millis(10)); - timeout.wait().unwrap(); + block_on(timeout).unwrap(); assert!(dropped.load()); child.join().unwrap(); } diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -879,14 +880,14 @@ fn empty_parse_eof_does_not_return_error() { }); let fut = listener.incoming() - .into_future() + .next() .map_err(|_| unreachable!()) .and_then(|(item, _incoming)| { let socket = item.unwrap(); Http::<hyper::Chunk>::new().serve_connection(socket, HelloWorld) }); - fut.wait().unwrap(); + block_on(fut).unwrap(); } #[test] diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -901,7 +902,7 @@ fn nonempty_parse_eof_returns_error() { }); let fut = listener.incoming() - .into_future() + .next() .map_err(|_| unreachable!()) .and_then(|(item, _incoming)| { let socket = item.unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -909,7 +910,7 @@ fn nonempty_parse_eof_returns_error() { .map(|_| ()) }); - fut.wait().unwrap_err(); + block_on(fut).unwrap_err(); } #[test] diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -929,7 +930,7 @@ fn returning_1xx_response_is_error() { }); let fut = listener.incoming() - .into_future() + .next() .map_err(|_| unreachable!()) .and_then(|(item, _incoming)| { let socket = item.unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -943,12 +944,12 @@ fn returning_1xx_response_is_error() { .map(|_| ()) }); - fut.wait().unwrap_err(); + block_on(fut).unwrap_err(); } #[test] fn upgrades() { - use tokio_io::io::{read_to_end, write_all}; + use futures::io::{AsyncReadExt, AsyncWriteExt}; let _ = pretty_env_logger::try_init(); let runtime = Runtime::new().unwrap(); let listener = tcp_bind(&"127.0.0.1:0".parse().unwrap(), &runtime.handle()).unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -977,7 +978,7 @@ fn upgrades() { }); let fut = listener.incoming() - .into_future() + .next() .map_err(|_| -> hyper::Error { unreachable!() }) .and_then(|(item, _incoming)| { let socket = item.unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -992,24 +993,24 @@ fn upgrades() { })); let mut conn_opt = Some(conn); - future::poll_fn(move || { - try_ready!(conn_opt.as_mut().unwrap().poll_without_shutdown()); + future::poll_fn(move |cx| { + try_ready!(conn_opt.as_mut().unwrap().poll_without_shutdown(cx)); // conn is done with HTTP now Ok(conn_opt.take().unwrap().into()) }) }); - let conn = fut.wait().unwrap(); + let conn = block_on(fut).unwrap(); // wait so that we don't write until other side saw 101 response - rx.wait().unwrap(); + block_on(rx).unwrap(); let parts = conn.into_parts(); let io = parts.io; assert_eq!(parts.read_buf, "eagerly optimistic"); - let io = write_all(io, b"foo=bar").wait().unwrap().0; - let vec = read_to_end(io, vec![]).wait().unwrap().1; + let io = block_on(io.write_all(b"foo=bar")).unwrap().0; + let vec = block_on(io.read_to_end(vec![])).unwrap().1; assert_eq!(vec, b"bar=foo"); } diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1030,7 +1031,7 @@ fn parse_errors_send_4xx_response() { }); let fut = listener.incoming() - .into_future() + .next() .map_err(|_| unreachable!()) .and_then(|(item, _incoming)| { let socket = item.unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1039,7 +1040,7 @@ fn parse_errors_send_4xx_response() { .map(|_| ()) }); - fut.wait().unwrap_err(); + block_on(fut).unwrap_err(); } #[test] diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1059,7 +1060,7 @@ fn illegal_request_length_returns_400_response() { }); let fut = listener.incoming() - .into_future() + .next() .map_err(|_| unreachable!()) .and_then(|(item, _incoming)| { let socket = item.unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1068,7 +1069,7 @@ fn illegal_request_length_returns_400_response() { .map(|_| ()) }); - fut.wait().unwrap_err(); + block_on(fut).unwrap_err(); } #[test] diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1092,7 +1093,7 @@ fn max_buf_size() { }); let fut = listener.incoming() - .into_future() + .next() .map_err(|_| unreachable!()) .and_then(|(item, _incoming)| { let socket = item.unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1102,7 +1103,7 @@ fn max_buf_size() { .map(|_| ()) }); - fut.wait().unwrap_err(); + block_on(fut).unwrap_err(); } #[test] diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1136,7 +1137,7 @@ fn streaming_body() { let rx = rx.map_err(|_| panic!("thread panicked")); let fut = listener.incoming() - .into_future() + .next() .map_err(|_| unreachable!()) .and_then(|(item, _incoming)| { let socket = item.unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1152,7 +1153,7 @@ fn streaming_body() { .map(|_| ()) }); - fut.join(rx).wait().unwrap(); + block_on(fut.join(rx)).unwrap(); } // ------------------------------------------------- diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1292,7 +1293,7 @@ impl Service for TestService { Ok(()) }).then(move |result| { let msg = match result { - Ok(()) => Msg::End, + Ok(_) => Msg::End, Err(e) => Msg::Error(e), }; tx2.lock().unwrap().send(msg).unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1379,7 +1380,7 @@ fn serve_with_options(options: ServeOptions) -> Serve { let thread_name = format!("test-server-{:?}", dur); let thread = thread::Builder::new().name(thread_name).spawn(move || { - tokio::run(::futures::future::lazy(move || { + tokio::runtime::run2(::futures::future::lazy(move |_| { let srv = Http::new() .keep_alive(keep_alive) .pipeline(pipeline) diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1390,7 +1391,7 @@ fn serve_with_options(options: ServeOptions) -> Serve { }).unwrap(); addr_tx.send(srv.local_addr().unwrap()).unwrap(); srv.run_until(shutdown_rx.then(|_| Ok(()))) - .map_err(|err| println!("error {}", err)) + .map_err(|err| panic!("error {}", err)) })) }).unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1420,32 +1421,27 @@ struct DebugStream<T, D> { _debug: D, } -impl<T: Read, D> Read for DebugStream<T, D> { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.stream.read(buf) +impl<T: AsyncWrite, D> AsyncWrite for DebugStream<T, D> { + fn poll_write(&mut self, cx: &mut task::Context, buf: &[u8]) -> futures::Poll<usize, io::Error> { + self.stream.poll_write(cx, buf) } -} -impl<T: Write, D> Write for DebugStream<T, D> { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.stream.write(buf) + fn poll_flush(&mut self, cx: &mut task::Context) -> futures::Poll<(), io::Error> { + self.stream.poll_flush(cx) } - fn flush(&mut self) -> io::Result<()> { - self.stream.flush() + fn poll_close(&mut self, cx: &mut task::Context) -> futures::Poll<(), io::Error> { + self.stream.poll_close(cx) } } -impl<T: AsyncWrite, D> AsyncWrite for DebugStream<T, D> { - fn shutdown(&mut self) -> futures::Poll<(), io::Error> { - self.stream.shutdown() +impl<T: AsyncRead, D> AsyncRead for DebugStream<T, D> { + fn poll_read(&mut self, cx: &mut task::Context, buf: &mut [u8]) -> futures::Poll<usize, io::Error> { + self.stream.poll_read(cx, buf) } } - -impl<T: AsyncRead, D> AsyncRead for DebugStream<T, D> {} - #[derive(Clone)] struct Dropped(Arc<AtomicBool>);
Update to futures 0.2 It's not released yet, but this is just tracking that it needs to happen and is part of 0.12.
I'm super excited for this and would be interested in helping out! futures-0.2 is nearly code-complete, so we could probably get started soon. Do you have a branch you'd like PRs submitted to? There's a 0.12.x branch now on the repo where I've been trying to add new breaking changes to. Now that tokio 0.1 has landed in the 0.12.x branch, we should be able to attempt this. Is anyone working on this yet? Otherwise I'd have some time tomorrow to take a stab!
2018-03-20T09:55:12Z
0.12
a1609fbb332fccffbeb85d16f1cc0bf98c6ede21
hyperium/hyper
1,459
hyperium__hyper-1459
[ "1323" ]
eb15c660c106a2be08afd07e6cdfce162272d6cc
diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -500,6 +500,8 @@ where I: AsyncRead + AsyncWrite, Ok(encoder) => { if !encoder.is_eof() { Writing::Body(encoder) + } else if encoder.is_last() { + Writing::Closed } else { Writing::KeepAlive } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -566,7 +568,11 @@ where I: AsyncRead + AsyncWrite, self.io.buffer(encoded); if encoder.is_eof() { - Writing::KeepAlive + if encoder.is_last() { + Writing::Closed + } else { + Writing::KeepAlive + } } else { return Ok(AsyncSink::Ready); } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -577,7 +583,11 @@ where I: AsyncRead + AsyncWrite, if let Some(end) = end { self.io.buffer(end); } - Writing::KeepAlive + if encoder.is_last() { + Writing::Closed + } else { + Writing::KeepAlive + } }, Err(_not_eof) => Writing::Closed, } diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -9,6 +9,7 @@ use iovec::IoVec; #[derive(Debug, Clone)] pub struct Encoder { kind: Kind, + is_last: bool, } #[derive(Debug)] diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -43,22 +44,22 @@ enum BufKind<B> { } impl Encoder { - pub fn chunked() -> Encoder { + fn new(kind: Kind) -> Encoder { Encoder { - kind: Kind::Chunked, + kind: kind, + is_last: false, } } + pub fn chunked() -> Encoder { + Encoder::new(Kind::Chunked) + } pub fn length(len: u64) -> Encoder { - Encoder { - kind: Kind::Length(len), - } + Encoder::new(Kind::Length(len)) } pub fn eof() -> Encoder { - Encoder { - kind: Kind::Eof, - } + Encoder::new(Kind::Eof) } pub fn is_eof(&self) -> bool { diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -68,6 +69,14 @@ impl Encoder { } } + pub fn set_last(&mut self) { + self.is_last = true; + } + + pub fn is_last(&self) -> bool { + self.is_last + } + pub fn end<B>(&self) -> Result<Option<EncodedBuf<B>>, NotEof> { match self.kind { Kind::Length(0) => Ok(None), diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -132,7 +132,11 @@ where // replying with the latter status code response. let ret = if ::StatusCode::SwitchingProtocols == head.subject { T::on_encode_upgrade(&mut head) - .map(|_| Server::set_length(&mut head, has_body, method.as_ref())) + .map(|_| { + let mut enc = Server::set_length(&mut head, has_body, method.as_ref()); + enc.set_last(); + enc + }) } else if head.subject.is_informational() { error!("response with 1xx status code not supported"); head = MessageHead::default(); diff --git a/src/proto/mod.rs b/src/proto/mod.rs --- a/src/proto/mod.rs +++ b/src/proto/mod.rs @@ -134,7 +134,9 @@ pub fn expecting_continue(version: HttpVersion, headers: &Headers) -> bool { ret } -pub type ServerTransaction = h1::role::Server<h1::role::NoUpgrades>; +pub type ServerTransaction = h1::role::Server<h1::role::YesUpgrades>; +//pub type ServerTransaction = h1::role::Server<h1::role::NoUpgrades>; +//pub type ServerUpgradeTransaction = h1::role::Server<h1::role::YesUpgrades>; pub type ClientTransaction = h1::role::Client<h1::role::NoUpgrades>; pub type ClientUpgradeTransaction = h1::role::Client<h1::role::YesUpgrades>; diff --git /dev/null b/src/server/conn.rs new file mode 100644 --- /dev/null +++ b/src/server/conn.rs @@ -0,0 +1,124 @@ +//! Lower-level Server connection API. +//! +//! The types in thie module are to provide a lower-level API based around a +//! single connection. Accepting a connection and binding it with a service +//! are not handled at this level. This module provides the building blocks to +//! customize those things externally. +//! +//! If don't have need to manage connections yourself, consider using the +//! higher-level [Server](super) API. + +use std::fmt; + +use bytes::Bytes; +use futures::{Future, Poll, Stream}; +use tokio_io::{AsyncRead, AsyncWrite}; + +use proto; +use super::{HyperService, Request, Response, Service}; + +/// A future binding a connection with a Service. +/// +/// Polling this future will drive HTTP forward. +#[must_use = "futures do nothing unless polled"] +pub struct Connection<I, S> +where + S: HyperService, + S::ResponseBody: Stream<Error=::Error>, + <S::ResponseBody as Stream>::Item: AsRef<[u8]>, +{ + pub(super) conn: proto::dispatch::Dispatcher< + proto::dispatch::Server<S>, + S::ResponseBody, + I, + <S::ResponseBody as Stream>::Item, + proto::ServerTransaction, + >, +} + +/// Deconstructed parts of a `Connection`. +/// +/// This allows taking apart a `Connection` at a later time, in order to +/// reclaim the IO object, and additional related pieces. +#[derive(Debug)] +pub struct Parts<T> { + /// The original IO object used in the handshake. + pub io: T, + /// A buffer of bytes that have been read but not processed as HTTP. + /// + /// If the client sent additional bytes after its last request, and + /// this connection "ended" with an upgrade, the read buffer will contain + /// those bytes. + /// + /// You will want to check for any existing bytes if you plan to continue + /// communicating on the IO object. + pub read_buf: Bytes, + _inner: (), +} + +// ===== impl Connection ===== + +impl<I, B, S> Connection<I, S> +where S: Service<Request = Request, Response = Response<B>, Error = ::Error> + 'static, + I: AsyncRead + AsyncWrite + 'static, + B: Stream<Error=::Error> + 'static, + B::Item: AsRef<[u8]>, +{ + /// Disables keep-alive for this connection. + pub fn disable_keep_alive(&mut self) { + self.conn.disable_keep_alive() + } + + /// Return the inner IO object, and additional information. + /// + /// This should only be called after `poll_without_shutdown` signals + /// that the connection is "done". Otherwise, it may not have finished + /// flushing all necessary HTTP bytes. + pub fn into_parts(self) -> Parts<I> { + let (io, read_buf) = self.conn.into_inner(); + Parts { + io: io, + read_buf: read_buf, + _inner: (), + } + } + + /// Poll the connection for completion, but without calling `shutdown` + /// on the underlying IO. + /// + /// This is useful to allow running a connection while doing an HTTP + /// upgrade. Once the upgrade is completed, the connection would be "done", + /// but it is not desired to actally shutdown the IO object. Instead you + /// would take it back using `into_parts`. + pub fn poll_without_shutdown(&mut self) -> Poll<(), ::Error> { + try_ready!(self.conn.poll_without_shutdown()); + Ok(().into()) + } +} + +impl<I, B, S> Future for Connection<I, S> +where S: Service<Request = Request, Response = Response<B>, Error = ::Error> + 'static, + I: AsyncRead + AsyncWrite + 'static, + B: Stream<Error=::Error> + 'static, + B::Item: AsRef<[u8]>, +{ + type Item = (); + type Error = ::Error; + + fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + self.conn.poll() + } +} + +impl<I, S> fmt::Debug for Connection<I, S> +where + S: HyperService, + S::ResponseBody: Stream<Error=::Error>, + <S::ResponseBody as Stream>::Item: AsRef<[u8]>, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Connection") + .finish() + } +} + diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -5,6 +5,7 @@ #[cfg(feature = "compat")] pub mod compat; +pub mod conn; mod service; use std::cell::RefCell; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -46,6 +47,7 @@ feat_server_proto! { }; } +pub use self::conn::Connection; pub use self::service::{const_service, service_fn}; /// A configuration of the HTTP protocol. diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -108,34 +110,6 @@ pub struct AddrIncoming { timeout: Option<Timeout>, } -/// A future binding a connection with a Service. -/// -/// Polling this future will drive HTTP forward. -/// -/// # Note -/// -/// This will currently yield an unnameable (`Opaque`) value -/// on success. The purpose of this is that nothing can be assumed about -/// the type, not even it's name. It's probable that in a later release, -/// this future yields the underlying IO object, which could be done without -/// a breaking change. -/// -/// It is likely best to just map the value to `()`, for now. -#[must_use = "futures do nothing unless polled"] -pub struct Connection<I, S> -where - S: HyperService, - S::ResponseBody: Stream<Error=::Error>, - <S::ResponseBody as Stream>::Item: AsRef<[u8]>, -{ - conn: proto::dispatch::Dispatcher< - proto::dispatch::Server<S>, - S::ResponseBody, - I, - <S::ResponseBody as Stream>::Item, - proto::ServerTransaction, - >, -} // ===== impl Http ===== diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -567,70 +541,6 @@ where } */ -// ===== impl Connection ===== - -impl<I, B, S> Future for Connection<I, S> -where S: Service<Request = Request, Response = Response<B>, Error = ::Error> + 'static, - I: AsyncRead + AsyncWrite + 'static, - B: Stream<Error=::Error> + 'static, - B::Item: AsRef<[u8]>, -{ - type Item = self::unnameable::Opaque; - type Error = ::Error; - - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - try_ready!(self.conn.poll()); - Ok(self::unnameable::opaque().into()) - } -} - -impl<I, S> fmt::Debug for Connection<I, S> -where - S: HyperService, - S::ResponseBody: Stream<Error=::Error>, - <S::ResponseBody as Stream>::Item: AsRef<[u8]>, -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("Connection") - .finish() - } -} - -impl<I, B, S> Connection<I, S> -where S: Service<Request = Request, Response = Response<B>, Error = ::Error> + 'static, - I: AsyncRead + AsyncWrite + 'static, - B: Stream<Error=::Error> + 'static, - B::Item: AsRef<[u8]>, -{ - /// Disables keep-alive for this connection. - pub fn disable_keep_alive(&mut self) { - self.conn.disable_keep_alive() - } -} - -mod unnameable { - // This type is specifically not exported outside the crate, - // so no one can actually name the type. With no methods, we make no - // promises about this type. - // - // All of that to say we can eventually replace the type returned - // to something else, and it would not be a breaking change. - // - // We may want to eventually yield the `T: AsyncRead + AsyncWrite`, which - // doesn't have a `Debug` bound. So, this type can't implement `Debug` - // either, so the type change doesn't break people. - #[allow(missing_debug_implementations)] - pub struct Opaque { - _inner: (), - } - - pub fn opaque() -> Opaque { - Opaque { - _inner: (), - } - } -} - // ===== impl AddrIncoming ===== impl AddrIncoming {
diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1,5 +1,6 @@ #![deny(warnings)] extern crate hyper; +#[macro_use] extern crate futures; extern crate spmc; extern crate pretty_env_logger; diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -930,6 +931,71 @@ fn returning_1xx_response_is_error() { core.run(fut).unwrap_err(); } +#[test] +fn upgrades() { + use tokio_io::io::{read_to_end, write_all}; + let _ = pretty_env_logger::try_init(); + let mut core = Core::new().unwrap(); + let listener = TcpListener::bind(&"127.0.0.1:0".parse().unwrap(), &core.handle()).unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = oneshot::channel(); + + thread::spawn(move || { + let mut tcp = connect(&addr); + tcp.write_all(b"\ + GET / HTTP/1.1\r\n\ + Upgrade: foobar\r\n\ + Connection: upgrade\r\n\ + \r\n\ + eagerly optimistic\ + ").expect("write 1"); + let mut buf = [0; 256]; + tcp.read(&mut buf).expect("read 1"); + + let expected = "HTTP/1.1 101 Switching Protocols\r\n"; + assert_eq!(s(&buf[..expected.len()]), expected); + let _ = tx.send(()); + + let n = tcp.read(&mut buf).expect("read 2"); + assert_eq!(s(&buf[..n]), "foo=bar"); + tcp.write_all(b"bar=foo").expect("write 2"); + }); + + let fut = listener.incoming() + .into_future() + .map_err(|_| -> hyper::Error { unreachable!() }) + .and_then(|(item, _incoming)| { + let (socket, _) = item.unwrap(); + let conn = Http::<hyper::Chunk>::new() + .serve_connection(socket, service_fn(|_| { + let mut res = Response::<hyper::Body>::new() + .with_status(StatusCode::SwitchingProtocols); + res.headers_mut().set_raw("Upgrade", "foobar"); + Ok(res) + })); + + let mut conn_opt = Some(conn); + future::poll_fn(move || { + try_ready!(conn_opt.as_mut().unwrap().poll_without_shutdown()); + // conn is done with HTTP now + Ok(conn_opt.take().unwrap().into()) + }) + }); + + let conn = core.run(fut).unwrap(); + + // wait so that we don't write until other side saw 101 response + core.run(rx).unwrap(); + + let parts = conn.into_parts(); + let io = parts.io; + assert_eq!(parts.read_buf, "eagerly optimistic"); + + let io = core.run(write_all(io, b"foo=bar")).unwrap().0; + let vec = core.run(read_to_end(io, vec![])).unwrap().1; + assert_eq!(vec, b"bar=foo"); +} + #[test] fn parse_errors_send_4xx_response() { let mut core = Core::new().unwrap();
Server Protocol Upgrades Add support for servers to receive requests that wish to upgrade to a different protocol, such as websockets. A proposed API follows: ## Proposal - `Response` - `pub fn upgrade(proto: header::Upgrade) -> (Response, server::Upgrade)` This sets the `StatusCode::SwitchingProtocols`, and the `Upgrade` header provided. It returns the `Response`, in case other headers need to be added, and a `server::Upgrade` type, explained next. - `server::Upgrade` - `impl Future for server::Upgrade` - This type is a `Future` that resolves to the underlying IO object that is being upgraded. ## Usage ```rust // inside a `Service` fn call(&self, req: Request) -> Self::Future { if wants_ws_upgrade(&req) { let (res, upgrade) = Response::upgrade(Upgrade::ws()); self.ws_queue.send(res); future::ok(res) } else { self.handle_http(req) } } ``` A theoretical websocket server would also exist, and a channel, the `ws_queue`, would be used to give the socket to the websocket server. ## Implementation The `server::Upgrade` could wrap a `futures::sync::oneshot::Receiver`. The purpose for wrapping one is to hide the implementation details. When upgrading protocols, the response is only supposed to send headers. A blank newline after a header block with a `101` response code is supposed to be for the already upgraded protocol. That means sending a body with an upgrade response is an error. If it is possible with some `Into` impls to allow `Response::upgrade` to return a `Response<()>`, that would probably be ideal. I imagine it might not be doable, in which case, it will need to be enforced at runtime. This will still work, as the `server::Upgrade` can be sent a `hyper::Error` noting that a body was illegal. It would be nice if the type could be `server::Upgrade<T>`, where `T` is the specific IO type being used internally. However, that might not be possible either, as the `Service` may not have a way to know what type is being used (it might be possible for a user to have encoded the type in their `new_service`, and thus `Service`, and be able to statically guarantee the type, though!). If not, then the return type will need to be a `Box<AsyncRead + AsyncWrite>`. Any buffered bytes internally associated with the socket should be returned as well, as a `Chunk`.
This is a great idea, but what about handling CONNECT method at the server side (like in a HTTP proxy server)? I think the upgrade function should only provide the underlying I/O object, and it is the user's responsibility to return a proper HTTP response. @lqf96 I would definitely like to also offer a way of handling `CONNECT` requests. However, it's not quite the same, as HTTP/2 defines `CONNECT` a little differently. The original socket does not get upgraded out of h2, it just sends and receives `DATA` frames on the same stream, and it should be forwarded to the target host. So, when hyper gains HTTP/2 support, it would be wrong to pull the socket out because some stream sent a `CONNECT`. It would need to continue to just stream bytes back and forth. As for handling the response yourself, the thing is that you need to return a `Response` anyways, so it seems useful to be able to fill in the status code and headers, and let hyper write that to the socket. Yes, that is indeed a problem. Maybe for HTTP/2 we need two kinds of upgrade, one for the TCP connection and another one for the H2 stream containing the HTTP request. The former one can be used to upgrade from HTTP/2 to something else, and the latter one can be used for CONNECT or (possibly) running WebSocket over H2 stream. > The former one can be used to upgrade from HTTP/2 to something else HTTP/2 does not define a way to upgrade to another protocol. You cannot upgrade from HTTP/2 to websockets. Just want to note that the [websocket crate](https://crates.io/crates/websocket) already [supported upgrading](http://cyderize.github.io/rust-websocket/doc/websocket/server/upgrade/sync/struct.HyperRequest.html) with old sync Hyper. It could do it because the old `Request` [exposed the underlying IO stream](https://docs.rs/hyper/0.10.6/hyper/server/request/struct.Request.html#method.deconstruct). The new async version [doesn't](https://docs.rs/hyper/0.11.6/hyper/server/struct.Request.html#method.deconstruct). @seanmonstar it all sounds reasonable. I'm not sure I get the part about returning Chunk of buffered bytes at the end though. I'd expect any buffered bytes be "put back" and made available through reading from returned IO object. I.e. return implementation that first depletes buffered bytes, then proxies calls to actual underlying IO object.
2018-03-08T21:45:47Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,454
hyperium__hyper-1454
[ "1449" ]
0786ea1f871de9e007295238f20512825720853e
diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -8,14 +8,13 @@ extern crate tokio_core; use std::net::SocketAddr; -use futures::{future, Future, Stream}; +use futures::{Future, Stream}; use tokio_core::reactor::{Core, Handle}; use tokio_core::net::TcpListener; use hyper::client; use hyper::header::{ContentLength, ContentType}; use hyper::Method; -use hyper::server::{self, Service}; #[bench] diff --git a/src/client/cancel.rs /dev/null --- a/src/client/cancel.rs +++ /dev/null @@ -1,154 +0,0 @@ -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; - -use futures::{Async, Future, Poll}; -use futures::task::{self, Task}; - -use common::Never; - -use self::lock::Lock; - -#[derive(Clone)] -pub struct Cancel { - inner: Arc<Inner>, -} - -pub struct Canceled { - inner: Arc<Inner>, -} - -struct Inner { - is_canceled: AtomicBool, - task: Lock<Option<Task>>, -} - -impl Cancel { - pub fn new() -> (Cancel, Canceled) { - let inner = Arc::new(Inner { - is_canceled: AtomicBool::new(false), - task: Lock::new(None), - }); - let inner2 = inner.clone(); - ( - Cancel { - inner: inner, - }, - Canceled { - inner: inner2, - }, - ) - } - - pub fn cancel(&self) { - if !self.inner.is_canceled.swap(true, Ordering::SeqCst) { - if let Some(mut locked) = self.inner.task.try_lock() { - if let Some(task) = locked.take() { - task.notify(); - } - } - // if we couldn't take the lock, Canceled was trying to park. - // After parking, it will check is_canceled one last time, - // so we can just stop here. - } - } - - pub fn is_canceled(&self) -> bool { - self.inner.is_canceled.load(Ordering::SeqCst) - } -} - -impl Canceled { - pub fn cancel(&self) { - self.inner.is_canceled.store(true, Ordering::SeqCst); - } -} - -impl Future for Canceled { - type Item = (); - type Error = Never; - - fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - if self.inner.is_canceled.load(Ordering::SeqCst) { - Ok(Async::Ready(())) - } else { - if let Some(mut locked) = self.inner.task.try_lock() { - if locked.is_none() { - // it's possible a Cancel just tried to cancel on another thread, - // and we just missed it. Once we have the lock, we should check - // one more time before parking this task and going away. - if self.inner.is_canceled.load(Ordering::SeqCst) { - return Ok(Async::Ready(())); - } - *locked = Some(task::current()); - } - Ok(Async::NotReady) - } else { - // if we couldn't take the lock, then a Cancel taken has it. - // The *ONLY* reason is because it is in the process of canceling. - Ok(Async::Ready(())) - } - } - } -} - -impl Drop for Canceled { - fn drop(&mut self) { - self.cancel(); - } -} - - -// a sub module just to protect unsafety -mod lock { - use std::cell::UnsafeCell; - use std::ops::{Deref, DerefMut}; - use std::sync::atomic::{AtomicBool, Ordering}; - - pub struct Lock<T> { - is_locked: AtomicBool, - value: UnsafeCell<T>, - } - - impl<T> Lock<T> { - pub fn new(val: T) -> Lock<T> { - Lock { - is_locked: AtomicBool::new(false), - value: UnsafeCell::new(val), - } - } - - pub fn try_lock(&self) -> Option<Locked<T>> { - if !self.is_locked.swap(true, Ordering::SeqCst) { - Some(Locked { lock: self }) - } else { - None - } - } - } - - unsafe impl<T: Send> Send for Lock<T> {} - unsafe impl<T: Send> Sync for Lock<T> {} - - pub struct Locked<'a, T: 'a> { - lock: &'a Lock<T>, - } - - impl<'a, T> Deref for Locked<'a, T> { - type Target = T; - fn deref(&self) -> &T { - unsafe { &*self.lock.value.get() } - } - } - - impl<'a, T> DerefMut for Locked<'a, T> { - fn deref_mut(&mut self) -> &mut T { - unsafe { &mut *self.lock.value.get() } - } - } - - impl<'a, T> Drop for Locked<'a, T> { - fn drop(&mut self) { - self.lock.is_locked.store(false, Ordering::SeqCst); - } - } -} diff --git /dev/null b/src/client/conn.rs new file mode 100644 --- /dev/null +++ b/src/client/conn.rs @@ -0,0 +1,487 @@ +//! Lower-level client connection API. +//! +//! The types in thie module are to provide a lower-level API based around a +//! single connection. Connecting to a host, pooling connections, and the like +//! are not handled at this level. This module provides the building blocks to +//! customize those things externally. +//! +//! If don't have need to manage connections yourself, consider using the +//! higher-level [Client](super) API. +use std::fmt; +use std::marker::PhantomData; + +use bytes::Bytes; +use futures::{Async, Future, Poll, Stream}; +use futures::future::{self, Either}; +use tokio_io::{AsyncRead, AsyncWrite}; + +use proto; +use super::{dispatch, Request, Response}; + +/// Returns a `Handshake` future over some IO. +/// +/// This is a shortcut for `Builder::new().handshake(io)`. +pub fn handshake<T>(io: T) -> Handshake<T, ::Body> +where + T: AsyncRead + AsyncWrite, +{ + Builder::new() + .handshake(io) +} + +/// The sender side of an established connection. +pub struct SendRequest<B> { + dispatch: dispatch::Sender<proto::dispatch::ClientMsg<B>, ::Response>, + +} + +/// A future that processes all HTTP state for the IO object. +/// +/// In most cases, this should just be spawned into an executor, so that it +/// can process incoming and outgoing messages, notice hangups, and the like. +#[must_use = "futures do nothing unless polled"] +pub struct Connection<T, B> +where + T: AsyncRead + AsyncWrite, + B: Stream<Error=::Error> + 'static, + B::Item: AsRef<[u8]>, +{ + inner: proto::dispatch::Dispatcher< + proto::dispatch::Client<B>, + B, + T, + B::Item, + proto::ClientUpgradeTransaction, + >, +} + + +/// A builder to configure an HTTP connection. +/// +/// After setting options, the builder is used to create a `Handshake` future. +#[derive(Clone, Debug)] +pub struct Builder { + h1_writev: bool, +} + +/// A future setting up HTTP over an IO object. +/// +/// If successful, yields a `(SendRequest, Connection)` pair. +#[must_use = "futures do nothing unless polled"] +pub struct Handshake<T, B> { + inner: HandshakeInner<T, B, proto::ClientUpgradeTransaction>, +} + +/// A future returned by `SendRequest::send_request`. +/// +/// Yields a `Response` if successful. +#[must_use = "futures do nothing unless polled"] +pub struct ResponseFuture { + // for now, a Box is used to hide away the internal `B` + // that can be returned if canceled + inner: Box<Future<Item=Response, Error=::Error>>, +} + +/// Deconstructed parts of a `Connection`. +/// +/// This allows taking apart a `Connection` at a later time, in order to +/// reclaim the IO object, and additional related pieces. +#[derive(Debug)] +pub struct Parts<T> { + /// The original IO object used in the handshake. + pub io: T, + /// A buffer of bytes that have been read but not processed as HTTP. + /// + /// For instance, if the `Connection` is used for an HTTP upgrade request, + /// it is possible the server sent back the first bytes of the new protocol + /// along with the response upgrade. + /// + /// You will want to check for any existing bytes if you plan to continue + /// communicating on the IO object. + pub read_buf: Bytes, + _inner: (), +} + +// internal client api + +#[must_use = "futures do nothing unless polled"] +pub(super) struct HandshakeNoUpgrades<T, B> { + inner: HandshakeInner<T, B, proto::ClientTransaction>, +} + +struct HandshakeInner<T, B, R> { + builder: Builder, + io: Option<T>, + _marker: PhantomData<(B, R)>, +} + +// ===== impl SendRequest + +impl<B> SendRequest<B> +{ + /// Polls to determine whether this sender can be used yet for a request. + /// + /// If the associated connection is closed, this returns an Error. + pub fn poll_ready(&mut self) -> Poll<(), ::Error> { + self.dispatch.poll_ready() + } + + pub(super) fn is_closed(&self) -> bool { + self.dispatch.is_closed() + } +} + +impl<B> SendRequest<B> +where + B: Stream<Error=::Error> + 'static, + B::Item: AsRef<[u8]>, +{ + /// Sends a `Request` on the associated connection. + /// + /// Returns a future that if successful, yields the `Response`. + /// + /// # Note + /// + /// There are some key differences in what automatic things the `Client` + /// does for you that will not be done here: + /// + /// - `Client` requires absolute-form `Uri`s, since the scheme and + /// authority are need to connect. They aren't required here. + /// - Since the `Client` requires absolute-form `Uri`s, it can add + /// the `Host` header based on it. You must add a `Host` header yourself + /// before calling this method. + /// - Since absolute-form `Uri`s are not required, if received, they will + /// be serialized as-is, irregardless of calling `Request::set_proxy`. + /// + /// # Example + /// + /// ``` + /// # extern crate futures; + /// # extern crate hyper; + /// # use hyper::client::conn::SendRequest; + /// # use hyper::Body; + /// use futures::Future; + /// use hyper::{Method, Request}; + /// use hyper::header::Host; + /// + /// # fn doc(mut tx: SendRequest<Body>) { + /// // build a Request + /// let path = "/foo/bar".parse().expect("valid path"); + /// let mut req = Request::new(Method::Get, path); + /// req.headers_mut().set(Host::new("hyper.rs", None)); + /// + /// // send it and get a future back + /// let fut = tx.send_request(req) + /// .map(|res| { + /// // got the Response + /// assert!(res.status().is_success()); + /// }); + /// # drop(fut); + /// # } + /// # fn main() {} + /// ``` + pub fn send_request(&mut self, mut req: Request<B>) -> ResponseFuture { + // The Connection API does less things automatically than the Client + // API does. For instance, right here, we always assume set_proxy, so + // that if an absolute-form URI is provided, it is serialized as-is. + // + // Part of the reason for this is to prepare for the change to `http` + // types, where there is no more set_proxy. + // + // It's important that this method isn't called directly from the + // `Client`, so that `set_proxy` there is still respected. + req.set_proxy(true); + let inner = self.send_request_retryable(req).map_err(|e| { + let (err, _orig_req) = e; + err + }); + ResponseFuture { + inner: Box::new(inner), + } + } + + //TODO: replace with `impl Future` when stable + pub(crate) fn send_request_retryable(&mut self, req: Request<B>) -> Box<Future<Item=Response, Error=(::Error, Option<(::proto::RequestHead, Option<B>)>)>> { + let (head, body) = proto::request::split(req); + let inner = match self.dispatch.send((head, body)) { + Ok(rx) => { + Either::A(rx.then(move |res| { + match res { + Ok(Ok(res)) => Ok(res), + Ok(Err(err)) => Err(err), + // this is definite bug if it happens, but it shouldn't happen! + Err(_) => panic!("dispatch dropped without returning error"), + } + })) + }, + Err(req) => { + debug!("connection was not ready"); + let err = ::Error::new_canceled(Some("connection was not ready")); + Either::B(future::err((err, Some(req)))) + } + }; + Box::new(inner) + } +} + +/* TODO(0.12.0): when we change from tokio-service to tower. +impl<T, B> Service for SendRequest<T, B> { + type Request = Request<B>; + type Response = Response; + type Error = ::Error; + type Future = ResponseFuture; + + fn call(&self, req: Self::Request) -> Self::Future { + + } +} +*/ + +impl<B> fmt::Debug for SendRequest<B> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("SendRequest") + .finish() + } +} + +// ===== impl Connection + +impl<T, B> Connection<T, B> +where + T: AsyncRead + AsyncWrite, + B: Stream<Error=::Error> + 'static, + B::Item: AsRef<[u8]>, +{ + /// Return the inner IO object, and additional information. + pub fn into_parts(self) -> Parts<T> { + let (io, read_buf) = self.inner.into_inner(); + Parts { + io: io, + read_buf: read_buf, + _inner: (), + } + } + + /// Poll the connection for completion, but without calling `shutdown` + /// on the underlying IO. + /// + /// This is useful to allow running a connection while doing an HTTP + /// upgrade. Once the upgrade is completed, the connection would be "done", + /// but it is not desired to actally shutdown the IO object. Instead you + /// would take it back using `into_parts`. + pub fn poll_without_shutdown(&mut self) -> Poll<(), ::Error> { + self.inner.poll_without_shutdown() + } +} + +impl<T, B> Future for Connection<T, B> +where + T: AsyncRead + AsyncWrite, + B: Stream<Error=::Error> + 'static, + B::Item: AsRef<[u8]>, +{ + type Item = (); + type Error = ::Error; + + fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + self.inner.poll() + } +} + +impl<T, B> fmt::Debug for Connection<T, B> +where + T: AsyncRead + AsyncWrite + fmt::Debug, + B: Stream<Error=::Error> + 'static, + B::Item: AsRef<[u8]>, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Connection") + .finish() + } +} + +// ===== impl Builder + +impl Builder { + /// Creates a new connection builder. + #[inline] + pub fn new() -> Builder { + Builder { + h1_writev: true, + } + } + + pub(super) fn h1_writev(&mut self, enabled: bool) -> &mut Builder { + self.h1_writev = enabled; + self + } + + /// Constructs a connection with the configured options and IO. + #[inline] + pub fn handshake<T, B>(&self, io: T) -> Handshake<T, B> + where + T: AsyncRead + AsyncWrite, + B: Stream<Error=::Error> + 'static, + B::Item: AsRef<[u8]>, + { + Handshake { + inner: HandshakeInner { + builder: self.clone(), + io: Some(io), + _marker: PhantomData, + } + } + } + + pub(super) fn handshake_no_upgrades<T, B>(&self, io: T) -> HandshakeNoUpgrades<T, B> + where + T: AsyncRead + AsyncWrite, + B: Stream<Error=::Error> + 'static, + B::Item: AsRef<[u8]>, + { + HandshakeNoUpgrades { + inner: HandshakeInner { + builder: self.clone(), + io: Some(io), + _marker: PhantomData, + } + } + } +} + +// ===== impl Handshake + +impl<T, B> Future for Handshake<T, B> +where + T: AsyncRead + AsyncWrite, + B: Stream<Error=::Error> + 'static, + B::Item: AsRef<[u8]>, +{ + type Item = (SendRequest<B>, Connection<T, B>); + type Error = ::Error; + + fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + self.inner.poll() + .map(|async| { + async.map(|(tx, dispatch)| { + (tx, Connection { inner: dispatch }) + }) + }) + } +} + +impl<T, B> fmt::Debug for Handshake<T, B> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Handshake") + .finish() + } +} + +impl<T, B> Future for HandshakeNoUpgrades<T, B> +where + T: AsyncRead + AsyncWrite, + B: Stream<Error=::Error> + 'static, + B::Item: AsRef<[u8]>, +{ + type Item = (SendRequest<B>, proto::dispatch::Dispatcher< + proto::dispatch::Client<B>, + B, + T, + B::Item, + proto::ClientTransaction, + >); + type Error = ::Error; + + fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + self.inner.poll() + } +} + +impl<T, B, R> Future for HandshakeInner<T, B, R> +where + T: AsyncRead + AsyncWrite, + B: Stream<Error=::Error> + 'static, + B::Item: AsRef<[u8]>, + R: proto::Http1Transaction< + Incoming=proto::RawStatus, + Outgoing=proto::RequestLine, + >, +{ + type Item = (SendRequest<B>, proto::dispatch::Dispatcher< + proto::dispatch::Client<B>, + B, + T, + B::Item, + R, + >); + type Error = ::Error; + + fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + let io = self.io.take().expect("polled more than once"); + let (tx, rx) = dispatch::channel(); + let mut conn = proto::Conn::new(io); + if !self.builder.h1_writev { + conn.set_write_strategy_flatten(); + } + let dispatch = proto::dispatch::Dispatcher::new(proto::dispatch::Client::new(rx), conn); + Ok(Async::Ready(( + SendRequest { + dispatch: tx, + }, + dispatch, + ))) + } +} + +// ===== impl ResponseFuture + +impl Future for ResponseFuture { + type Item = Response; + type Error = ::Error; + + #[inline] + fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + self.inner.poll() + } +} + +impl fmt::Debug for ResponseFuture { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("ResponseFuture") + .finish() + } +} + +// assert trait markers + +trait AssertSend: Send {} +trait AssertSendSync: Send + Sync {} + + +#[doc(hidden)] +impl<B: Send> AssertSendSync for SendRequest<B> {} + +#[doc(hidden)] +impl<T: Send, B: Send> AssertSend for Connection<T, B> +where + T: AsyncRead + AsyncWrite, + B: Stream<Error=::Error>, + B::Item: AsRef<[u8]> + Send, +{} + +#[doc(hidden)] +impl<T: Send + Sync, B: Send + Sync> AssertSendSync for Connection<T, B> +where + T: AsyncRead + AsyncWrite, + B: Stream<Error=::Error>, + B::Item: AsRef<[u8]> + Send + Sync, +{} + +#[doc(hidden)] +impl AssertSendSync for Builder {} + +// TODO: This could be done by using a dispatch channel that doesn't +// return the `B` on Error, removing the possibility of contains some !Send +// thing. +//#[doc(hidden)] +//impl AssertSend for ResponseFuture {} diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -1,60 +1,64 @@ -use futures::{Async, Future, Poll, Stream}; +use futures::{Async, Poll, Stream}; use futures::sync::{mpsc, oneshot}; use common::Never; -use super::cancel::{Cancel, Canceled}; +use super::signal; pub type Callback<T, U> = oneshot::Sender<Result<U, (::Error, Option<T>)>>; pub type Promise<T, U> = oneshot::Receiver<Result<U, (::Error, Option<T>)>>; pub fn channel<T, U>() -> (Sender<T, U>, Receiver<T, U>) { - let (tx, rx) = mpsc::unbounded(); - let (cancel, canceled) = Cancel::new(); + let (tx, rx) = mpsc::channel(0); + let (giver, taker) = signal::new(); let tx = Sender { - cancel: cancel, + giver: giver, inner: tx, }; let rx = Receiver { - canceled: canceled, inner: rx, + taker: taker, }; (tx, rx) } pub struct Sender<T, U> { - cancel: Cancel, - inner: mpsc::UnboundedSender<(T, Callback<T, U>)>, + // The Giver helps watch that the the Receiver side has been polled + // when the queue is empty. This helps us know when a request and + // response have been fully processed, and a connection is ready + // for more. + giver: signal::Giver, + inner: mpsc::Sender<(T, Callback<T, U>)>, } impl<T, U> Sender<T, U> { - pub fn is_closed(&self) -> bool { - self.cancel.is_canceled() + pub fn poll_ready(&mut self) -> Poll<(), ::Error> { + match self.inner.poll_ready() { + Ok(Async::Ready(())) => { + // there's room in the queue, but does the Connection + // want a message yet? + self.giver.poll_want() + .map_err(|_| ::Error::Closed) + }, + Ok(Async::NotReady) => Ok(Async::NotReady), + Err(_) => Err(::Error::Closed), + } } - pub fn cancel(&self) { - self.cancel.cancel(); + pub fn is_closed(&self) -> bool { + self.giver.is_canceled() } - pub fn send(&self, val: T) -> Result<Promise<T, U>, T> { + pub fn send(&mut self, val: T) -> Result<Promise<T, U>, T> { let (tx, rx) = oneshot::channel(); - self.inner.unbounded_send((val, tx)) + self.inner.try_send((val, tx)) .map(move |_| rx) .map_err(|e| e.into_inner().0) } } -impl<T, U> Clone for Sender<T, U> { - fn clone(&self) -> Sender<T, U> { - Sender { - cancel: self.cancel.clone(), - inner: self.inner.clone(), - } - } -} - pub struct Receiver<T, U> { - canceled: Canceled, - inner: mpsc::UnboundedReceiver<(T, Callback<T, U>)>, + inner: mpsc::Receiver<(T, Callback<T, U>)>, + taker: signal::Taker, } impl<T, U> Stream for Receiver<T, U> { diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -62,16 +66,20 @@ impl<T, U> Stream for Receiver<T, U> { type Error = Never; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { - if let Async::Ready(()) = self.canceled.poll()? { - return Ok(Async::Ready(None)); + match self.inner.poll() { + Ok(Async::Ready(item)) => Ok(Async::Ready(item)), + Ok(Async::NotReady) => { + self.taker.want(); + Ok(Async::NotReady) + } + Err(()) => unreachable!("mpsc never errors"), } - self.inner.poll().map_err(|()| unreachable!("mpsc never errors")) } } impl<T, U> Drop for Receiver<T, U> { fn drop(&mut self) { - self.canceled.cancel(); + self.taker.cancel(); self.inner.close(); // This poll() is safe to call in `Drop`, because we've diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -84,8 +92,7 @@ impl<T, U> Drop for Receiver<T, U> { // - NotReady: unreachable // - Err: unreachable while let Ok(Async::Ready(Some((val, cb)))) = self.inner.poll() { - // maybe in future, we pass the value along with the error? - let _ = cb.send(Err((::Error::new_canceled(None), Some(val)))); + let _ = cb.send(Err((::Error::new_canceled(None::<::Error>), Some(val)))); } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -1,14 +1,14 @@ //! HTTP Client -use std::cell::Cell; use std::fmt; use std::io; use std::marker::PhantomData; use std::rc::Rc; +use std::sync::Arc; use std::time::Duration; use futures::{Async, Future, Poll, Stream}; -use futures::future::{self, Either, Executor}; +use futures::future::{self, Executor}; #[cfg(feature = "compat")] use http; use tokio::reactor::Handle; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -28,7 +28,7 @@ pub use self::connect::{HttpConnector, Connect}; use self::background::{bg, Background}; -mod cancel; +pub mod conn; mod connect; //TODO(easy): move cancel and dispatch into common instead pub(crate) mod dispatch; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -44,7 +45,7 @@ pub struct Client<C, B = proto::Body> { connector: Rc<C>, executor: Exec, h1_writev: bool, - pool: Pool<HyperClient<B>>, + pool: Pool<PoolClient<B>>, retry_canceled_requests: bool, set_host: bool, } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -191,77 +192,73 @@ where C: Connect, //TODO: replace with `impl Future` when stable fn send_request(&self, req: Request<B>, domain: &Uri) -> Box<Future<Item=Response, Error=ClientError<B>>> { + //fn send_request(&self, req: Request<B>, domain: &Uri) -> Box<Future<Item=Response, Error=::Error>> { let url = req.uri().clone(); - let (head, body) = request::split(req); let checkout = self.pool.checkout(domain.as_ref()); let connect = { let executor = self.executor.clone(); let pool = self.pool.clone(); - let pool_key = Rc::new(domain.to_string()); + let pool_key = Arc::new(domain.to_string()); let h1_writev = self.h1_writev; let connector = self.connector.clone(); future::lazy(move || { connector.connect(url) + .from_err() .and_then(move |io| { - let (tx, rx) = dispatch::channel(); - let tx = HyperClient { + conn::Builder::new() + .h1_writev(h1_writev) + .handshake_no_upgrades(io) + }).and_then(move |(tx, conn)| { + executor.execute(conn.map_err(|e| debug!("client connection error: {}", e)))?; + Ok(pool.pooled(pool_key, PoolClient { tx: tx, - should_close: Cell::new(true), - }; - let pooled = pool.pooled(pool_key, tx); - let mut conn = proto::Conn::<_, _, proto::ClientTransaction, _>::new(io, pooled.clone()); - if !h1_writev { - conn.set_write_strategy_flatten(); - } - let dispatch = proto::dispatch::Dispatcher::new(proto::dispatch::Client::new(rx), conn); - executor.execute(dispatch.map_err(|e| debug!("client connection error: {}", e)))?; - Ok(pooled) + })) }) }) }; let race = checkout.select(connect) - .map(|(client, _work)| client) + .map(|(pooled, _work)| pooled) .map_err(|(e, _checkout)| { // the Pool Checkout cannot error, so the only error // is from the Connector // XXX: should wait on the Checkout? Problem is // that if the connector is failing, it may be that we // never had a pooled stream at all - ClientError::Normal(e.into()) + ClientError::Normal(e) }); - let resp = race.and_then(move |client| { - let conn_reused = client.is_reused(); - match client.tx.send((head, body)) { - Ok(rx) => { - client.should_close.set(false); - Either::A(rx.then(move |res| { - match res { - Ok(Ok(res)) => Ok(res), - Ok(Err((err, orig_req))) => Err(match orig_req { - Some(req) => ClientError::Canceled { - connection_reused: conn_reused, - reason: err, - req: req, - }, - None => ClientError::Normal(err), - }), - // this is definite bug if it happens, but it shouldn't happen! - Err(_) => panic!("dispatch dropped without returning error"), + + let executor = self.executor.clone(); + let resp = race.and_then(move |mut pooled| { + let conn_reused = pooled.is_reused(); + let fut = pooled.tx.send_request_retryable(req) + .map_err(move |(err, orig_req)| { + if let Some(req) = orig_req { + ClientError::Canceled { + connection_reused: conn_reused, + reason: err, + req: req, } - })) - }, - Err(req) => { - debug!("pooled connection was not ready"); - let err = ClientError::Canceled { - connection_reused: conn_reused, - reason: ::Error::new_canceled(None), - req: req, - }; - Either::B(future::err(err)) - } - } + } else { + ClientError::Normal(err) + } + }); + + // when pooled is dropped, it will try to insert back into the + // pool. To delay that, spawn a future that completes once the + // sender is ready again. + // + // This *should* only be once the related `Connection` has polled + // for a new request to start. + // + // If the executor doesn't have room, oh well. Things will likely + // be blowing up soon, but this specific task isn't required. + let _ = executor.execute(future::poll_fn(move || { + pooled.tx.poll_ready().map_err(|_| ()) + })); + + fut }); Box::new(resp) diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -373,35 +370,19 @@ where } } -struct HyperClient<B> { - should_close: Cell<bool>, - tx: dispatch::Sender<proto::dispatch::ClientMsg<B>, ::Response>, +struct PoolClient<B> { + tx: conn::SendRequest<B>, } -impl<B> Clone for HyperClient<B> { - fn clone(&self) -> HyperClient<B> { - HyperClient { - tx: self.tx.clone(), - should_close: self.should_close.clone(), - } - } -} - -impl<B> self::pool::Closed for HyperClient<B> { +impl<B> self::pool::Closed for PoolClient<B> +where + B: 'static, +{ fn is_closed(&self) -> bool { self.tx.is_closed() } } -impl<B> Drop for HyperClient<B> { - fn drop(&mut self) { - if self.should_close.get() { - self.should_close.set(false); - self.tx.cancel(); - } - } -} - pub(crate) enum ClientError<B> { Normal(::Error), Canceled { diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -1,19 +1,15 @@ -use std::cell::{Cell, RefCell}; use std::collections::{HashMap, VecDeque}; use std::fmt; -use std::io; -use std::ops::{Deref, DerefMut, BitAndAssign}; -use std::rc::{Rc, Weak}; +use std::ops::{Deref, DerefMut}; +use std::sync::{Arc, Mutex, Weak}; use std::time::{Duration, Instant}; use futures::{Future, Async, Poll, Stream}; +use futures::sync::oneshot; use tokio::reactor::{Handle, Interval}; -use relay; - -use proto::{KeepAlive, KA}; pub struct Pool<T> { - inner: Rc<RefCell<PoolInner<T>>>, + inner: Arc<Mutex<PoolInner<T>>>, } // Before using a pooled connection, make sure the sender is not dead. diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -29,7 +25,7 @@ struct PoolInner<T> { enabled: bool, // These are internal Conns sitting in the event loop in the KeepAlive // state, waiting to receive a new Request to send on the socket. - idle: HashMap<Rc<String>, Vec<Entry<T>>>, + idle: HashMap<Arc<String>, Vec<Idle<T>>>, // These are outstanding Checkouts that are waiting for a socket to be // able to send a Request one. This is used when "racing" for a new // connection. diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -39,7 +35,7 @@ struct PoolInner<T> { // this list is checked for any parked Checkouts, and tries to notify // them that the Conn could be used instead of waiting for a brand new // connection. - parked: HashMap<Rc<String>, VecDeque<relay::Sender<Entry<T>>>>, + parked: HashMap<Arc<String>, VecDeque<oneshot::Sender<T>>>, timeout: Option<Duration>, // Used to prevent multiple intervals from being spawned to clear // expired connections. diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -49,10 +45,10 @@ struct PoolInner<T> { expired_timer_spawned: bool, } -impl<T: Clone + Closed> Pool<T> { +impl<T> Pool<T> { pub fn new(enabled: bool, timeout: Option<Duration>) -> Pool<T> { Pool { - inner: Rc::new(RefCell::new(PoolInner { + inner: Arc::new(Mutex::new(PoolInner { enabled: enabled, idle: HashMap::new(), parked: HashMap::new(), diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -61,74 +57,33 @@ impl<T: Clone + Closed> Pool<T> { })), } } +} +impl<T: Closed> Pool<T> { pub fn checkout(&self, key: &str) -> Checkout<T> { Checkout { - key: Rc::new(key.to_owned()), + key: Arc::new(key.to_owned()), pool: self.clone(), parked: None, } } - fn put(&mut self, key: Rc<String>, entry: Entry<T>) { - trace!("Pool::put {:?}", key); - let mut inner = self.inner.borrow_mut(); - let mut remove_parked = false; - let mut entry = Some(entry); - if let Some(parked) = inner.parked.get_mut(&key) { - while let Some(tx) = parked.pop_front() { - if tx.is_canceled() { - trace!("Pool::put removing canceled parked {:?}", key); - } else { - tx.complete(entry.take().unwrap()); - break; - } - /* - match tx.send(entry.take().unwrap()) { - Ok(()) => break, - Err(e) => { - trace!("Pool::put removing canceled parked {:?}", key); - entry = Some(e); - } - } - */ - } - remove_parked = parked.is_empty(); - } - if remove_parked { - inner.parked.remove(&key); - } - - match entry { - Some(entry) => { - debug!("pooling idle connection for {:?}", key); - inner.idle.entry(key) - .or_insert(Vec::new()) - .push(entry); - } - None => trace!("Pool::put found parked {:?}", key), - } - } - - fn take(&self, key: &Rc<String>) -> Option<Pooled<T>> { + fn take(&self, key: &Arc<String>) -> Option<Pooled<T>> { let entry = { - let mut inner = self.inner.borrow_mut(); + let mut inner = self.inner.lock().unwrap(); let expiration = Expiration::new(inner.timeout); let mut should_remove = false; let entry = inner.idle.get_mut(key).and_then(|list| { trace!("take; url = {:?}, expiration = {:?}", key, expiration.0); while let Some(entry) = list.pop() { - match entry.status.get() { - TimedKA::Idle(idle_at) if !expiration.expires(idle_at) => { - if !entry.value.is_closed() { - should_remove = list.is_empty(); - return Some(entry); - } - }, - _ => {}, + if !expiration.expires(entry.idle_at) { + if !entry.value.is_closed() { + should_remove = list.is_empty(); + return Some(entry); + } } trace!("removing unacceptable pooled {:?}", key); - // every other case the Entry should just be dropped + // every other case the Idle should just be dropped // 1. Idle but expired // 2. Busy (something else somehow took it?) // 3. Disabled don't reuse of course diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -143,72 +98,102 @@ impl<T: Clone + Closed> Pool<T> { entry }; - entry.map(|e| self.reuse(key, e)) + entry.map(|e| self.reuse(key, e.value)) } - pub fn pooled(&self, key: Rc<String>, value: T) -> Pooled<T> { + pub fn pooled(&self, key: Arc<String>, value: T) -> Pooled<T> { Pooled { - entry: Entry { - value: value, - is_reused: false, - status: Rc::new(Cell::new(TimedKA::Busy)), - }, + is_reused: false, key: key, - pool: Rc::downgrade(&self.inner), + pool: Arc::downgrade(&self.inner), + value: Some(value) } } - fn is_enabled(&self) -> bool { - self.inner.borrow().enabled - } - - fn reuse(&self, key: &Rc<String>, mut entry: Entry<T>) -> Pooled<T> { + fn reuse(&self, key: &Arc<String>, value: T) -> Pooled<T> { debug!("reuse idle connection for {:?}", key); - entry.is_reused = true; - entry.status.set(TimedKA::Busy); Pooled { - entry: entry, + is_reused: true, key: key.clone(), - pool: Rc::downgrade(&self.inner), + pool: Arc::downgrade(&self.inner), + value: Some(value), } } - fn park(&mut self, key: Rc<String>, tx: relay::Sender<Entry<T>>) { + fn park(&mut self, key: Arc<String>, tx: oneshot::Sender<T>) { trace!("park; waiting for idle connection: {:?}", key); - self.inner.borrow_mut() + self.inner.lock().unwrap() .parked.entry(key) .or_insert(VecDeque::new()) .push_back(tx); } } -impl<T> Pool<T> { +impl<T: Closed> PoolInner<T> { + fn put(&mut self, key: Arc<String>, value: T) { + if !self.enabled { + return; + } + trace!("Pool::put {:?}", key); + let mut remove_parked = false; + let mut value = Some(value); + if let Some(parked) = self.parked.get_mut(&key) { + while let Some(tx) = parked.pop_front() { + if !tx.is_canceled() { + match tx.send(value.take().unwrap()) { + Ok(()) => break, + Err(e) => { + value = Some(e); + } + } + } + + trace!("Pool::put removing canceled parked {:?}", key); + } + remove_parked = parked.is_empty(); + } + if remove_parked { + self.parked.remove(&key); + } + + match value { + Some(value) => { + debug!("pooling idle connection for {:?}", key); + self.idle.entry(key) + .or_insert(Vec::new()) + .push(Idle { + value: value, + idle_at: Instant::now(), + }); + } + None => trace!("Pool::put found parked {:?}", key), + } + } +} + +impl<T> PoolInner<T> { /// Any `FutureResponse`s that were created will have made a `Checkout`, /// and possibly inserted into the pool that it is waiting for an idle /// connection. If a user ever dropped that future, we need to clean out /// those parked senders. - fn clean_parked(&mut self, key: &Rc<String>) { - let mut inner = self.inner.borrow_mut(); - + fn clean_parked(&mut self, key: &Arc<String>) { let mut remove_parked = false; - if let Some(parked) = inner.parked.get_mut(key) { + if let Some(parked) = self.parked.get_mut(key) { parked.retain(|tx| { !tx.is_canceled() }); remove_parked = parked.is_empty(); } if remove_parked { - inner.parked.remove(key); + self.parked.remove(key); } } } -impl<T: Closed> Pool<T> { - fn clear_expired(&self) { - let mut inner = self.inner.borrow_mut(); - - let dur = if let Some(dur) = inner.timeout { +impl<T: Closed> PoolInner<T> { + fn clear_expired(&mut self) { + let dur = if let Some(dur) = self.timeout { dur } else { return diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -217,19 +202,13 @@ impl<T: Closed> Pool<T> { let now = Instant::now(); //self.last_idle_check_at = now; - inner.idle.retain(|_key, values| { + self.idle.retain(|_key, values| { - values.retain(|val| { - if val.value.is_closed() { + values.retain(|entry| { + if entry.value.is_closed() { return false; } - match val.status.get() { - TimedKA::Idle(idle_at) if now - idle_at < dur => { - true - }, - _ => false, - } - //now - val.idle_at < dur + now - entry.idle_at < dur }); // returning false evicts this key/val diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -241,28 +220,30 @@ impl<T: Closed> Pool<T> { impl<T: Closed + 'static> Pool<T> { pub(super) fn spawn_expired_interval(&self, handle: &Handle) { - let mut inner = self.inner.borrow_mut(); + let dur = { + let mut inner = self.inner.lock().unwrap(); - if !inner.enabled { - return; - } + if !inner.enabled { + return; + } - if inner.expired_timer_spawned { - return; - } - inner.expired_timer_spawned = true; + if inner.expired_timer_spawned { + return; + } + inner.expired_timer_spawned = true; - let dur = if let Some(dur) = inner.timeout { - dur - } else { - return + if let Some(dur) = inner.timeout { + dur + } else { + return + } }; let interval = Interval::new(dur, handle) .expect("reactor is gone"); handle.spawn(IdleInterval { interval: interval, - pool: Rc::downgrade(&self.inner), + pool: Arc::downgrade(&self.inner), }); } } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -275,121 +256,83 @@ impl<T> Clone for Pool<T> { } } -#[derive(Clone)] -pub struct Pooled<T> { - entry: Entry<T>, - key: Rc<String>, - pool: Weak<RefCell<PoolInner<T>>>, +pub struct Pooled<T: Closed> { + value: Option<T>, + is_reused: bool, + key: Arc<String>, + pool: Weak<Mutex<PoolInner<T>>>, } -impl<T> Pooled<T> { +impl<T: Closed> Pooled<T> { pub fn is_reused(&self) -> bool { - self.entry.is_reused + self.is_reused + } + + fn as_ref(&self) -> &T { + self.value.as_ref().expect("not dropped") + } + + fn as_mut(&mut self) -> &mut T { + self.value.as_mut().expect("not dropped") } } -impl<T> Deref for Pooled<T> { +impl<T: Closed> Deref for Pooled<T> { type Target = T; fn deref(&self) -> &T { - &self.entry.value + self.as_ref() } } -impl<T> DerefMut for Pooled<T> { +impl<T: Closed> DerefMut for Pooled<T> { fn deref_mut(&mut self) -> &mut T { - &mut self.entry.value + self.as_mut() } } -impl<T: Clone + Closed> KeepAlive for Pooled<T> { - fn busy(&mut self) { - self.entry.status.set(TimedKA::Busy); - } - - fn disable(&mut self) { - self.entry.status.set(TimedKA::Disabled); - } - - fn idle(&mut self) { - let previous = self.status(); - self.entry.status.set(TimedKA::Idle(Instant::now())); - if let KA::Idle = previous { - trace!("Pooled::idle already idle"); - return; - } - self.entry.is_reused = true; - if let Some(inner) = self.pool.upgrade() { - let mut pool = Pool { - inner: inner, - }; - if pool.is_enabled() { - pool.put(self.key.clone(), self.entry.clone()); +impl<T: Closed> Drop for Pooled<T> { + fn drop(&mut self) { + if let Some(value) = self.value.take() { + if let Some(inner) = self.pool.upgrade() { + if let Ok(mut inner) = inner.lock() { + inner.put(self.key.clone(), value); + } } else { - trace!("keepalive disabled, dropping pooled ({:?})", self.key); - self.disable(); + trace!("pool dropped, dropping pooled ({:?})", self.key); } - } else { - trace!("pool dropped, dropping pooled ({:?})", self.key); - self.disable(); - } - } - - fn status(&self) -> KA { - match self.entry.status.get() { - TimedKA::Idle(_) => KA::Idle, - TimedKA::Busy => KA::Busy, - TimedKA::Disabled => KA::Disabled, } } } -impl<T> fmt::Debug for Pooled<T> { +impl<T: Closed> fmt::Debug for Pooled<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Pooled") - .field("status", &self.entry.status.get()) .field("key", &self.key) .finish() } } -impl<T: Clone + Closed> BitAndAssign<bool> for Pooled<T> { - fn bitand_assign(&mut self, enabled: bool) { - if !enabled { - self.disable(); - } - } -} - -#[derive(Clone)] -struct Entry<T> { +struct Idle<T> { + idle_at: Instant, value: T, - is_reused: bool, - status: Rc<Cell<TimedKA>>, -} - -#[derive(Clone, Copy, Debug)] -enum TimedKA { - Idle(Instant), - Busy, - Disabled, } pub struct Checkout<T> { - key: Rc<String>, + key: Arc<String>, pool: Pool<T>, - parked: Option<relay::Receiver<Entry<T>>>, + parked: Option<oneshot::Receiver<T>>, } struct NotParked; -impl<T: Clone + Closed> Checkout<T> { +impl<T: Closed> Checkout<T> { fn poll_parked(&mut self) -> Poll<Pooled<T>, NotParked> { let mut drop_parked = false; if let Some(ref mut rx) = self.parked { match rx.poll() { - Ok(Async::Ready(entry)) => { - if !entry.value.is_closed() { - return Ok(Async::Ready(self.pool.reuse(&self.key, entry))); + Ok(Async::Ready(value)) => { + if !value.is_closed() { + return Ok(Async::Ready(self.pool.reuse(&self.key, value))); } drop_parked = true; }, diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -405,7 +348,7 @@ impl<T: Clone + Closed> Checkout<T> { fn park(&mut self) { if self.parked.is_none() { - let (tx, mut rx) = relay::channel(); + let (tx, mut rx) = oneshot::channel(); let _ = rx.poll(); // park this task self.pool.park(self.key.clone(), tx); self.parked = Some(rx); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -413,9 +356,9 @@ impl<T: Clone + Closed> Checkout<T> { } } -impl<T: Clone + Closed> Future for Checkout<T> { +impl<T: Closed> Future for Checkout<T> { type Item = Pooled<T>; - type Error = io::Error; + type Error = ::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { match self.poll_parked() { diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -437,7 +380,9 @@ impl<T: Clone + Closed> Future for Checkout<T> { impl<T> Drop for Checkout<T> { fn drop(&mut self) { self.parked.take(); - self.pool.clean_parked(&self.key); + if let Ok(mut inner) = self.pool.inner.lock() { + inner.clean_parked(&self.key); + } } } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -458,7 +403,7 @@ impl Expiration { struct IdleInterval<T> { interval: Interval, - pool: Weak<RefCell<PoolInner<T>>>, + pool: Weak<Mutex<PoolInner<T>>>, } impl<T: Closed + 'static> Future for IdleInterval<T> { diff --git /dev/null b/src/client/signal.rs new file mode 100644 --- /dev/null +++ b/src/client/signal.rs @@ -0,0 +1,188 @@ +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use futures::{Async, Poll}; +use futures::task::{self, Task}; + +use self::lock::Lock; + +pub fn new() -> (Giver, Taker) { + let inner = Arc::new(Inner { + state: AtomicUsize::new(STATE_IDLE), + task: Lock::new(None), + }); + let inner2 = inner.clone(); + ( + Giver { + inner: inner, + }, + Taker { + inner: inner2, + }, + ) +} + +#[derive(Clone)] +pub struct Giver { + inner: Arc<Inner>, +} + +pub struct Taker { + inner: Arc<Inner>, +} + +const STATE_IDLE: usize = 0; +const STATE_WANT: usize = 1; +const STATE_GIVE: usize = 2; +const STATE_CLOSED: usize = 3; + +struct Inner { + state: AtomicUsize, + task: Lock<Option<Task>>, +} + +impl Giver { + pub fn poll_want(&mut self) -> Poll<(), ()> { + loop { + let state = self.inner.state.load(Ordering::SeqCst); + match state { + STATE_WANT => { + // only set to IDLE if it is still Want + self.inner.state.compare_and_swap( + STATE_WANT, + STATE_IDLE, + Ordering::SeqCst, + ); + return Ok(Async::Ready(())) + }, + STATE_GIVE => { + // we're already waiting, return + return Ok(Async::NotReady) + } + STATE_CLOSED => return Err(()), + // Taker doesn't want anything yet, so park. + _ => { + if let Some(mut locked) = self.inner.task.try_lock() { + + // While we have the lock, try to set to GIVE. + let old = self.inner.state.compare_and_swap( + STATE_IDLE, + STATE_GIVE, + Ordering::SeqCst, + ); + // If it's not still IDLE, something happened! + // Go around the loop again. + if old == STATE_IDLE { + *locked = Some(task::current()); + return Ok(Async::NotReady) + } + } else { + // if we couldn't take the lock, then a Taker has it. + // The *ONLY* reason is because it is in the process of notifying us + // of its want. + // + // We need to loop again to see what state it was changed to. + } + }, + } + } + } + + pub fn is_canceled(&self) -> bool { + self.inner.state.load(Ordering::SeqCst) == STATE_CLOSED + } +} + +impl Taker { + pub fn cancel(&self) { + self.signal(STATE_CLOSED) + } + + pub fn want(&self) { + self.signal(STATE_WANT) + } + + fn signal(&self, state: usize) { + let old_state = self.inner.state.swap(state, Ordering::SeqCst); + match old_state { + STATE_WANT | STATE_CLOSED | STATE_IDLE => (), + _ => { + loop { + if let Some(mut locked) = self.inner.task.try_lock() { + if let Some(task) = locked.take() { + task.notify(); + } + return; + } else { + // if we couldn't take the lock, then a Giver has it. + // The *ONLY* reason is because it is in the process of parking. + // + // We need to loop and take the lock so we can notify this task. + } + } + }, + } + } +} + +impl Drop for Taker { + fn drop(&mut self) { + self.cancel(); + } +} + + +// a sub module just to protect unsafety +mod lock { + use std::cell::UnsafeCell; + use std::ops::{Deref, DerefMut}; + use std::sync::atomic::{AtomicBool, Ordering}; + + pub struct Lock<T> { + is_locked: AtomicBool, + value: UnsafeCell<T>, + } + + impl<T> Lock<T> { + pub fn new(val: T) -> Lock<T> { + Lock { + is_locked: AtomicBool::new(false), + value: UnsafeCell::new(val), + } + } + + pub fn try_lock(&self) -> Option<Locked<T>> { + if !self.is_locked.swap(true, Ordering::SeqCst) { + Some(Locked { lock: self }) + } else { + None + } + } + } + + unsafe impl<T: Send> Send for Lock<T> {} + unsafe impl<T: Send> Sync for Lock<T> {} + + pub struct Locked<'a, T: 'a> { + lock: &'a Lock<T>, + } + + impl<'a, T> Deref for Locked<'a, T> { + type Target = T; + fn deref(&self) -> &T { + unsafe { &*self.lock.value.get() } + } + } + + impl<'a, T> DerefMut for Locked<'a, T> { + fn deref_mut(&mut self) -> &mut T { + unsafe { &mut *self.lock.value.get() } + } + } + + impl<'a, T> Drop for Locked<'a, T> { + fn drop(&mut self) { + self.lock.is_locked.store(false, Ordering::SeqCst); + } + } +} diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -17,6 +17,7 @@ use self::Error::{ Status, Timeout, Upgrade, + Closed, Cancel, Io, TooLarge, diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -50,6 +51,8 @@ pub enum Error { Upgrade, /// A pending item was dropped before ever being processed. Cancel(Canceled), + /// Indicates a connection is closed. + Closed, /// An `io::Error` that occurred while trying to read or write to a network stream. Io(IoError), /// Parsing a field as string failed diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -60,9 +63,9 @@ pub enum Error { } impl Error { - pub(crate) fn new_canceled(cause: Option<Error>) -> Error { + pub(crate) fn new_canceled<E: Into<Box<StdError + Send + Sync>>>(cause: Option<E>) -> Error { Error::Cancel(Canceled { - cause: cause.map(Box::new), + cause: cause.map(Into::into), }) } } diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -75,7 +78,7 @@ impl Error { /// fulfilled with this error, signaling the `Request` was never started. #[derive(Debug)] pub struct Canceled { - cause: Option<Box<Error>>, + cause: Option<Box<StdError + Send + Sync>>, } impl Canceled { diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -121,6 +124,7 @@ impl StdError for Error { Incomplete => "message is incomplete", Timeout => "timeout", Upgrade => "unsupported protocol upgrade", + Closed => "connection is closed", Cancel(ref e) => e.description(), Uri(ref e) => e.description(), Io(ref e) => e.description(), diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -1,3 +1,5 @@ +use std::fmt; + use bytes::Bytes; use futures::{Async, AsyncSink, Future, Poll, Sink, StartSend, Stream}; use futures::sync::{mpsc, oneshot}; diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -13,11 +15,12 @@ pub type BodySender = mpsc::Sender<Result<Chunk, ::Error>>; /// A `Stream` for `Chunk`s used in requests and responses. #[must_use = "streams do nothing unless polled"] -#[derive(Debug)] -pub struct Body(Inner); +pub struct Body { + kind: Kind, +} #[derive(Debug)] -enum Inner { +enum Kind { #[cfg(feature = "tokio-proto")] Tokio(TokioBody), Chan { diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -40,7 +43,7 @@ impl Body { /// Return an empty body stream #[inline] pub fn empty() -> Body { - Body(Inner::Empty) + Body::new(Kind::Empty) } /// Return a body stream with an associated sender half diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -60,11 +63,32 @@ impl Body { /// there are more chunks immediately. #[inline] pub fn is_empty(&self) -> bool { - match self.0 { - Inner::Empty => true, + match self.kind { + Kind::Empty => true, _ => false, } } + + fn new(kind: Kind) -> Body { + Body { + kind: kind, + } + } + + fn poll_inner(&mut self) -> Poll<Option<Chunk>, ::Error> { + match self.kind { + #[cfg(feature = "tokio-proto")] + Kind::Tokio(ref mut rx) => rx.poll(), + Kind::Chan { ref mut rx, .. } => match rx.poll().expect("mpsc cannot error") { + Async::Ready(Some(Ok(chunk))) => Ok(Async::Ready(Some(chunk))), + Async::Ready(Some(Err(err))) => Err(err), + Async::Ready(None) => Ok(Async::Ready(None)), + Async::NotReady => Ok(Async::NotReady), + }, + Kind::Once(ref mut val) => Ok(Async::Ready(val.take())), + Kind::Empty => Ok(Async::Ready(None)), + } + } } impl Default for Body { diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -80,18 +104,15 @@ impl Stream for Body { #[inline] fn poll(&mut self) -> Poll<Option<Chunk>, ::Error> { - match self.0 { - #[cfg(feature = "tokio-proto")] - Inner::Tokio(ref mut rx) => rx.poll(), - Inner::Chan { ref mut rx, .. } => match rx.poll().expect("mpsc cannot error") { - Async::Ready(Some(Ok(chunk))) => Ok(Async::Ready(Some(chunk))), - Async::Ready(Some(Err(err))) => Err(err), - Async::Ready(None) => Ok(Async::Ready(None)), - Async::NotReady => Ok(Async::NotReady), - }, - Inner::Once(ref mut val) => Ok(Async::Ready(val.take())), - Inner::Empty => Ok(Async::Ready(None)), - } + self.poll_inner() + } +} + +impl fmt::Debug for Body { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_tuple("Body") + .field(&self.kind) + .finish() } } diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -105,7 +126,7 @@ pub fn channel() -> (ChunkSender, Body) { close_rx_check: true, tx: tx, }; - let rx = Body(Inner::Chan { + let rx = Body::new(Kind::Chan { close_tx: close_tx, rx: rx, }); diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -142,24 +163,24 @@ impl ChunkSender { feat_server_proto! { impl From<Body> for tokio_proto::streaming::Body<Chunk, ::Error> { fn from(b: Body) -> tokio_proto::streaming::Body<Chunk, ::Error> { - match b.0 { - Inner::Tokio(b) => b, - Inner::Chan { close_tx, rx } => { + match b.kind { + Kind::Tokio(b) => b, + Kind::Chan { close_tx, rx } => { // disable knowing if the Rx gets dropped, since we cannot // pass this tx along. let _ = close_tx.send(false); rx.into() }, - Inner::Once(Some(chunk)) => TokioBody::from(chunk), - Inner::Once(None) | - Inner::Empty => TokioBody::empty(), + Kind::Once(Some(chunk)) => TokioBody::from(chunk), + Kind::Once(None) | + Kind::Empty => TokioBody::empty(), } } } impl From<tokio_proto::streaming::Body<Chunk, ::Error>> for Body { fn from(tokio_body: tokio_proto::streaming::Body<Chunk, ::Error>) -> Body { - Body(Inner::Tokio(tokio_body)) + Body::new(Kind::Tokio(tokio_body)) } } } diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -168,7 +189,7 @@ impl From<mpsc::Receiver<Result<Chunk, ::Error>>> for Body { #[inline] fn from(src: mpsc::Receiver<Result<Chunk, ::Error>>) -> Body { let (tx, _) = oneshot::channel(); - Body(Inner::Chan { + Body::new(Kind::Chan { close_tx: tx, rx: src, }) diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -178,7 +199,7 @@ impl From<mpsc::Receiver<Result<Chunk, ::Error>>> for Body { impl From<Chunk> for Body { #[inline] fn from (chunk: Chunk) -> Body { - Body(Inner::Once(Some(chunk))) + Body::new(Kind::Once(Some(chunk))) } } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -2,6 +2,7 @@ use std::fmt; use std::io::{self}; use std::marker::PhantomData; +use bytes::Bytes; use futures::{Async, AsyncSink, Poll, StartSend}; #[cfg(feature = "tokio-proto")] use futures::{Sink, Stream}; diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -10,7 +11,7 @@ use tokio_io::{AsyncRead, AsyncWrite}; #[cfg(feature = "tokio-proto")] use tokio_proto::streaming::pipeline::{Frame, Transport}; -use proto::{Chunk, Http1Transaction, MessageHead}; +use proto::{Chunk, Decode, Http1Transaction, MessageHead}; use super::io::{Cursor, Buffered}; use super::{EncodedBuf, Encoder, Decoder}; use method::Method; diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -24,24 +25,34 @@ use version::HttpVersion; /// The connection will determine when a message begins and ends as well as /// determine if this connection can be kept alive after the message, /// or if it is complete. -pub struct Conn<I, B, T, K = KA> { +pub struct Conn<I, B, T> { io: Buffered<I, EncodedBuf<Cursor<B>>>, - state: State<K>, + state: State, _marker: PhantomData<T> } -impl<I, B, T, K> Conn<I, B, T, K> +/* +impl<I, B> Conn<I, B, ClientTransaction> +where I: AsyncRead + AsyncWrite, + B: AsRef<[u8]>, +{ + pub fn new_client(io: I) -> Conn<I, B, ClientTransaction> { + Conn::new(io) + } +} +*/ + +impl<I, B, T> Conn<I, B, T> where I: AsyncRead + AsyncWrite, B: AsRef<[u8]>, T: Http1Transaction, - K: KeepAlive { - pub fn new(io: I, keep_alive: K) -> Conn<I, B, T, K> { + pub fn new(io: I) -> Conn<I, B, T> { Conn { io: Buffered::new(io), state: State { error: None, - keep_alive: keep_alive, + keep_alive: KA::Busy, method: None, read_task: None, reading: Reading::Init, diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -66,6 +77,10 @@ where I: AsyncRead + AsyncWrite, self.io.set_write_strategy_flatten(); } + pub fn into_inner(self) -> (I, Bytes) { + self.io.into_inner() + } + #[cfg(feature = "tokio-proto")] fn poll_incoming(&mut self) -> Poll<Option<Frame<MessageHead<T::Incoming>, Chunk, ::Error>>, io::Error> { trace!("Conn::poll_incoming()"); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -205,8 +220,16 @@ where I: AsyncRead + AsyncWrite, }; let decoder = match T::decoder(&head, &mut self.state.method) { - Ok(Some(d)) => d, - Ok(None) => { + Ok(Decode::Normal(d)) => { + d + }, + Ok(Decode::Final(d)) => { + trace!("final decoder, HTTP ending"); + debug_assert!(d.is_eof()); + self.state.close_read(); + d + }, + Ok(Decode::Ignore) => { // likely a 1xx message that we can ignore continue; } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -232,7 +255,11 @@ where I: AsyncRead + AsyncWrite, } else { (true, Reading::Body(decoder)) }; - self.state.reading = reading; + if let Reading::Closed = self.state.reading { + // actually want an `if not let ...` + } else { + self.state.reading = reading; + } if !body { self.try_keep_alive(); } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -434,6 +461,12 @@ where I: AsyncRead + AsyncWrite, } pub fn can_write_head(&self) -> bool { + if !T::should_read_first() { + match self.state.reading { + Reading::Closed => return false, + _ => {}, + } + } match self.state.writing { Writing::Init => true, _ => false diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -456,6 +489,10 @@ where I: AsyncRead + AsyncWrite, pub fn write_head(&mut self, mut head: MessageHead<T::Outgoing>, body: bool) { debug_assert!(self.can_write_head()); + if !T::should_read_first() { + self.state.busy(); + } + self.enforce_version(&mut head); let buf = self.io.write_buf_mut(); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -623,11 +660,10 @@ where I: AsyncRead + AsyncWrite, // ==== tokio_proto impl ==== #[cfg(feature = "tokio-proto")] -impl<I, B, T, K> Stream for Conn<I, B, T, K> +impl<I, B, T> Stream for Conn<I, B, T> where I: AsyncRead + AsyncWrite, B: AsRef<[u8]>, T: Http1Transaction, - K: KeepAlive, T::Outgoing: fmt::Debug { type Item = Frame<MessageHead<T::Incoming>, Chunk, ::Error>; type Error = io::Error; diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -642,11 +678,10 @@ where I: AsyncRead + AsyncWrite, } #[cfg(feature = "tokio-proto")] -impl<I, B, T, K> Sink for Conn<I, B, T, K> +impl<I, B, T> Sink for Conn<I, B, T> where I: AsyncRead + AsyncWrite, B: AsRef<[u8]>, T: Http1Transaction, - K: KeepAlive, T::Outgoing: fmt::Debug { type SinkItem = Frame<MessageHead<T::Outgoing>, B, ::Error>; type SinkError = io::Error; diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -711,14 +746,13 @@ where I: AsyncRead + AsyncWrite, } #[cfg(feature = "tokio-proto")] -impl<I, B, T, K> Transport for Conn<I, B, T, K> +impl<I, B, T> Transport for Conn<I, B, T> where I: AsyncRead + AsyncWrite + 'static, B: AsRef<[u8]> + 'static, T: Http1Transaction + 'static, - K: KeepAlive + 'static, T::Outgoing: fmt::Debug {} -impl<I, B: AsRef<[u8]>, T, K: KeepAlive> fmt::Debug for Conn<I, B, T, K> { +impl<I, B: AsRef<[u8]>, T> fmt::Debug for Conn<I, B, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Conn") .field("state", &self.state) diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -727,9 +761,9 @@ impl<I, B: AsRef<[u8]>, T, K: KeepAlive> fmt::Debug for Conn<I, B, T, K> { } } -struct State<K> { +struct State { error: Option<::Error>, - keep_alive: K, + keep_alive: KA, method: Option<Method>, read_task: Option<Task>, reading: Reading, diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -752,12 +786,12 @@ enum Writing { Closed, } -impl<K: KeepAlive> fmt::Debug for State<K> { +impl fmt::Debug for State { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("State") .field("reading", &self.reading) .field("writing", &self.writing) - .field("keep_alive", &self.keep_alive.status()) + .field("keep_alive", &self.keep_alive) .field("error", &self.error) //.field("method", &self.method) .field("read_task", &self.read_task) diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -786,15 +820,8 @@ impl ::std::ops::BitAndAssign<bool> for KA { } } -pub trait KeepAlive: fmt::Debug + ::std::ops::BitAndAssign<bool> { - fn busy(&mut self); - fn disable(&mut self); - fn idle(&mut self); - fn status(&self) -> KA; -} - #[derive(Clone, Copy, Debug)] -pub enum KA { +enum KA { Idle, Busy, Disabled, diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -806,7 +833,7 @@ impl Default for KA { } } -impl KeepAlive for KA { +impl KA { fn idle(&mut self) { *self = KA::Idle; } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -824,7 +851,7 @@ impl KeepAlive for KA { } } -impl<K: KeepAlive> State<K> { +impl State { fn close(&mut self) { trace!("State::close()"); self.reading = Reading::Closed; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -1,15 +1,16 @@ use std::io; +use bytes::Bytes; use futures::{Async, AsyncSink, Future, Poll, Stream}; use futures::sync::oneshot; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_service::Service; -use proto::{Body, Conn, KeepAlive, Http1Transaction, MessageHead, RequestHead, ResponseHead}; +use proto::{Body, Conn, Http1Transaction, MessageHead, RequestHead, ResponseHead}; use ::StatusCode; -pub struct Dispatcher<D, Bs, I, B, T, K> { - conn: Conn<I, B, T, K>, +pub struct Dispatcher<D, Bs, I, B, T> { + conn: Conn<I, B, T>, dispatch: D, body_tx: Option<::proto::body::ChunkSender>, body_rx: Option<Bs>, diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -40,16 +41,15 @@ pub type ClientMsg<B> = (RequestHead, Option<B>); type ClientRx<B> = ::client::dispatch::Receiver<ClientMsg<B>, ::Response>; -impl<D, Bs, I, B, T, K> Dispatcher<D, Bs, I, B, T, K> +impl<D, Bs, I, B, T> Dispatcher<D, Bs, I, B, T> where D: Dispatch<PollItem=MessageHead<T::Outgoing>, PollBody=Bs, RecvItem=MessageHead<T::Incoming>>, I: AsyncRead + AsyncWrite, B: AsRef<[u8]>, T: Http1Transaction, - K: KeepAlive, Bs: Stream<Item=B, Error=::Error>, { - pub fn new(dispatch: D, conn: Conn<I, B, T, K>) -> Self { + pub fn new(dispatch: D, conn: Conn<I, B, T>) -> Self { Dispatcher { conn: conn, dispatch: dispatch, diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -63,15 +63,44 @@ where self.conn.disable_keep_alive() } - fn poll2(&mut self) -> Poll<(), ::Error> { + pub fn into_inner(self) -> (I, Bytes) { + self.conn.into_inner() + } + + /// The "Future" poll function. Runs this dispatcher until the + /// connection is shutdown, or an error occurs. + pub fn poll_until_shutdown(&mut self) -> Poll<(), ::Error> { + self.poll_catch(true) + } + + /// Run this dispatcher until HTTP says this connection is done, + /// but don't call `AsyncWrite::shutdown` on the underlying IO. + /// + /// This is useful for HTTP upgrades. + pub fn poll_without_shutdown(&mut self) -> Poll<(), ::Error> { + self.poll_catch(false) + } + + fn poll_catch(&mut self, should_shutdown: bool) -> Poll<(), ::Error> { + self.poll_inner(should_shutdown).or_else(|e| { + // An error means we're shutting down either way. + // We just try to give the error to the user, + // and close the connection with an Ok. If we + // cannot give it to the user, then return the Err. + self.dispatch.recv_msg(Err(e)).map(Async::Ready) + }) + } + + fn poll_inner(&mut self, should_shutdown: bool) -> Poll<(), ::Error> { self.poll_read()?; self.poll_write()?; self.poll_flush()?; if self.is_done() { - try_ready!(self.conn.shutdown()); + if should_shutdown { + try_ready!(self.conn.shutdown()); + } self.conn.take_error()?; - trace!("Dispatch::poll done"); Ok(Async::Ready(())) } else { Ok(Async::NotReady) diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -183,7 +212,7 @@ where loop { if self.is_closing { return Ok(Async::Ready(())); - } else if self.body_rx.is_none() && self.dispatch.should_poll() { + } else if self.body_rx.is_none() && self.conn.can_write_head() && self.dispatch.should_poll() { if let Some((head, body)) = try_ready!(self.dispatch.poll_msg()) { self.conn.write_head(head, body.is_some()); self.body_rx = body; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -257,13 +286,12 @@ where } -impl<D, Bs, I, B, T, K> Future for Dispatcher<D, Bs, I, B, T, K> +impl<D, Bs, I, B, T> Future for Dispatcher<D, Bs, I, B, T> where D: Dispatch<PollItem=MessageHead<T::Outgoing>, PollBody=Bs, RecvItem=MessageHead<T::Incoming>>, I: AsyncRead + AsyncWrite, B: AsRef<[u8]>, T: Http1Transaction, - K: KeepAlive, Bs: Stream<Item=B, Error=::Error>, { type Item = (); diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -271,14 +299,7 @@ where #[inline] fn poll(&mut self) -> Poll<Self::Item, Self::Error> { - trace!("Dispatcher::poll"); - self.poll2().or_else(|e| { - // An error means we're shutting down either way. - // We just try to give the error to the user, - // and close the connection with an Ok. If we - // cannot give it to the user, then return the Err. - self.dispatch.recv_msg(Err(e)).map(Async::Ready) - }) + self.poll_until_shutdown() } } diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -152,6 +152,10 @@ where }) } + pub fn into_inner(self) -> (T, Bytes) { + (self.io, self.read_buf.freeze()) + } + pub fn io_mut(&mut self) -> &mut T { &mut self.io } diff --git a/src/proto/h1/mod.rs b/src/proto/h1/mod.rs --- a/src/proto/h1/mod.rs +++ b/src/proto/h1/mod.rs @@ -1,4 +1,4 @@ -pub use self::conn::{Conn, KeepAlive, KA}; +pub use self::conn::Conn; pub use self::decode::Decoder; pub use self::encode::{EncodedBuf, Encoder}; diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -5,8 +5,8 @@ use httparse; use bytes::{BytesMut, Bytes}; use header::{self, Headers, ContentLength, TransferEncoding}; -use proto::{MessageHead, RawStatus, Http1Transaction, ParseResult, - ServerTransaction, ClientTransaction, RequestLine, RequestHead}; +use proto::{Decode, MessageHead, RawStatus, Http1Transaction, ParseResult, + RequestLine, RequestHead}; use proto::h1::{Encoder, Decoder, date}; use method::Method; use status::StatusCode; diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -15,7 +15,19 @@ use version::HttpVersion::{Http10, Http11}; const MAX_HEADERS: usize = 100; const AVERAGE_HEADER_SIZE: usize = 30; // totally scientific -impl Http1Transaction for ServerTransaction { +// There are 2 main roles, Client and Server. +// +// There is 1 modifier, OnUpgrade, which can wrap Client and Server, +// to signal that HTTP upgrades are not supported. + +pub struct Client<T>(T); + +pub struct Server<T>(T); + +impl<T> Http1Transaction for Server<T> +where + T: OnUpgrade, +{ type Incoming = RequestLine; type Outgoing = StatusCode; diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -72,7 +84,7 @@ impl Http1Transaction for ServerTransaction { }, len))) } - fn decoder(head: &MessageHead<Self::Incoming>, method: &mut Option<Method>) -> ::Result<Option<Decoder>> { + fn decoder(head: &MessageHead<Self::Incoming>, method: &mut Option<Method>) -> ::Result<Decode> { use ::header; *method = Some(head.subject.0.clone()); diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -95,37 +107,40 @@ impl Http1Transaction for ServerTransaction { debug!("HTTP/1.0 has Transfer-Encoding header"); Err(::Error::Header) } else if encodings.last() == Some(&header::Encoding::Chunked) { - Ok(Some(Decoder::chunked())) + Ok(Decode::Normal(Decoder::chunked())) } else { debug!("request with transfer-encoding header, but not chunked, bad request"); Err(::Error::Header) } } else if let Some(&header::ContentLength(len)) = head.headers.get() { - Ok(Some(Decoder::length(len))) + Ok(Decode::Normal(Decoder::length(len))) } else if head.headers.has::<header::ContentLength>() { debug!("illegal Content-Length: {:?}", head.headers.get_raw("Content-Length")); Err(::Error::Header) } else { - Ok(Some(Decoder::length(0))) + Ok(Decode::Normal(Decoder::length(0))) } } fn encode(mut head: MessageHead<Self::Outgoing>, has_body: bool, method: &mut Option<Method>, dst: &mut Vec<u8>) -> ::Result<Encoder> { - trace!("ServerTransaction::encode has_body={}, method={:?}", has_body, method); + trace!("Server::encode has_body={}, method={:?}", has_body, method); // hyper currently doesn't support returning 1xx status codes as a Response // This is because Service only allows returning a single Response, and // so if you try to reply with a e.g. 100 Continue, you have no way of // replying with the latter status code response. - let ret = if head.subject.is_informational() { + let ret = if ::StatusCode::SwitchingProtocols == head.subject { + T::on_encode_upgrade(&mut head) + .map(|_| Server::set_length(&mut head, has_body, method.as_ref())) + } else if head.subject.is_informational() { error!("response with 1xx status code not supported"); head = MessageHead::default(); head.subject = ::StatusCode::InternalServerError; head.headers.set(ContentLength(0)); Err(::Error::Status) } else { - Ok(ServerTransaction::set_length(&mut head, has_body, method.as_ref())) + Ok(Server::set_length(&mut head, has_body, method.as_ref())) }; diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -179,7 +194,7 @@ impl Http1Transaction for ServerTransaction { } } -impl ServerTransaction { +impl Server<()> { fn set_length(head: &mut MessageHead<StatusCode>, has_body: bool, method: Option<&Method>) -> Encoder { // these are here thanks to borrowck // `if method == Some(&Method::Get)` says the RHS doesn't live long enough diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -214,7 +229,10 @@ impl ServerTransaction { } } -impl Http1Transaction for ClientTransaction { +impl<T> Http1Transaction for Client<T> +where + T: OnUpgrade, +{ type Incoming = RawStatus; type Outgoing = RequestLine; diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -262,7 +280,7 @@ impl Http1Transaction for ClientTransaction { }, len))) } - fn decoder(inc: &MessageHead<Self::Incoming>, method: &mut Option<Method>) -> ::Result<Option<Decoder>> { + fn decoder(inc: &MessageHead<Self::Incoming>, method: &mut Option<Method>) -> ::Result<Decode> { // According to https://tools.ietf.org/html/rfc7230#section-3.3.3 // 1. HEAD responses, and Status 1xx, 204, and 304 cannot have a body. // 2. Status 2xx to a CONNECT cannot have a body. diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -274,30 +292,29 @@ impl Http1Transaction for ClientTransaction { match inc.subject.0 { 101 => { - debug!("received 101 upgrade response, not supported"); - return Err(::Error::Upgrade); + return T::on_decode_upgrade().map(Decode::Final); }, 100...199 => { trace!("ignoring informational response: {}", inc.subject.0); - return Ok(None); + return Ok(Decode::Ignore); }, 204 | - 304 => return Ok(Some(Decoder::length(0))), + 304 => return Ok(Decode::Normal(Decoder::length(0))), _ => (), } match *method { Some(Method::Head) => { - return Ok(Some(Decoder::length(0))); + return Ok(Decode::Normal(Decoder::length(0))); } Some(Method::Connect) => match inc.subject.0 { 200...299 => { - return Ok(Some(Decoder::length(0))); + return Ok(Decode::Final(Decoder::length(0))); }, _ => {}, }, Some(_) => {}, None => { - trace!("ClientTransaction::decoder is missing the Method"); + trace!("Client::decoder is missing the Method"); } } diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -307,28 +324,28 @@ impl Http1Transaction for ClientTransaction { debug!("HTTP/1.0 has Transfer-Encoding header"); Err(::Error::Header) } else if codings.last() == Some(&header::Encoding::Chunked) { - Ok(Some(Decoder::chunked())) + Ok(Decode::Normal(Decoder::chunked())) } else { trace!("not chunked. read till eof"); - Ok(Some(Decoder::eof())) + Ok(Decode::Normal(Decoder::eof())) } } else if let Some(&header::ContentLength(len)) = inc.headers.get() { - Ok(Some(Decoder::length(len))) + Ok(Decode::Normal(Decoder::length(len))) } else if inc.headers.has::<header::ContentLength>() { debug!("illegal Content-Length: {:?}", inc.headers.get_raw("Content-Length")); Err(::Error::Header) } else { trace!("neither Transfer-Encoding nor Content-Length"); - Ok(Some(Decoder::eof())) + Ok(Decode::Normal(Decoder::eof())) } } fn encode(mut head: MessageHead<Self::Outgoing>, has_body: bool, method: &mut Option<Method>, dst: &mut Vec<u8>) -> ::Result<Encoder> { - trace!("ClientTransaction::encode has_body={}, method={:?}", has_body, method); + trace!("Client::encode has_body={}, method={:?}", has_body, method); *method = Some(head.subject.0.clone()); - let body = ClientTransaction::set_length(&mut head, has_body); + let body = Client::set_length(&mut head, has_body); let init_cap = 30 + head.headers.len() * AVERAGE_HEADER_SIZE; dst.reserve(init_cap); diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -351,7 +368,7 @@ impl Http1Transaction for ClientTransaction { } } -impl ClientTransaction { +impl Client<()> { fn set_length(head: &mut RequestHead, has_body: bool) -> Encoder { if has_body { let can_chunked = head.version == Http11 diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -393,6 +410,42 @@ fn set_length(headers: &mut Headers, can_chunked: bool) -> Encoder { } } +pub trait OnUpgrade { + fn on_encode_upgrade(head: &mut MessageHead<StatusCode>) -> ::Result<()>; + fn on_decode_upgrade() -> ::Result<Decoder>; +} + +pub enum YesUpgrades {} + +pub enum NoUpgrades {} + +impl OnUpgrade for YesUpgrades { + fn on_encode_upgrade(_head: &mut MessageHead<StatusCode>) -> ::Result<()> { + Ok(()) + } + + fn on_decode_upgrade() -> ::Result<Decoder> { + debug!("101 response received, upgrading"); + // 101 upgrades always have no body + Ok(Decoder::length(0)) + } +} + +impl OnUpgrade for NoUpgrades { + fn on_encode_upgrade(head: &mut MessageHead<StatusCode>) -> ::Result<()> { + error!("response with 101 status code not supported"); + *head = MessageHead::default(); + head.subject = ::StatusCode::InternalServerError; + head.headers.set(ContentLength(0)); + Err(::Error::Status) + } + + fn on_decode_upgrade() -> ::Result<Decoder> { + debug!("received 101 upgrade response, not supported"); + return Err(::Error::Upgrade); + } +} + #[derive(Clone, Copy)] struct HeaderIndices { name: (usize, usize), diff --git a/src/proto/mod.rs b/src/proto/mod.rs --- a/src/proto/mod.rs +++ b/src/proto/mod.rs @@ -16,7 +16,7 @@ pub use self::body::Body; #[cfg(feature = "tokio-proto")] pub use self::body::TokioBody; pub use self::chunk::Chunk; -pub use self::h1::{dispatch, Conn, KeepAlive, KA}; +pub use self::h1::{dispatch, Conn}; mod body; mod chunk; diff --git a/src/proto/mod.rs b/src/proto/mod.rs --- a/src/proto/mod.rs +++ b/src/proto/mod.rs @@ -134,17 +134,16 @@ pub fn expecting_continue(version: HttpVersion, headers: &Headers) -> bool { ret } -#[derive(Debug)] -pub enum ServerTransaction {} +pub type ServerTransaction = h1::role::Server<h1::role::NoUpgrades>; -#[derive(Debug)] -pub enum ClientTransaction {} +pub type ClientTransaction = h1::role::Client<h1::role::NoUpgrades>; +pub type ClientUpgradeTransaction = h1::role::Client<h1::role::YesUpgrades>; pub trait Http1Transaction { type Incoming; type Outgoing: Default; fn parse(bytes: &mut BytesMut) -> ParseResult<Self::Incoming>; - fn decoder(head: &MessageHead<Self::Incoming>, method: &mut Option<::Method>) -> ::Result<Option<h1::Decoder>>; + fn decoder(head: &MessageHead<Self::Incoming>, method: &mut Option<::Method>) -> ::Result<Decode>; fn encode(head: MessageHead<Self::Outgoing>, has_body: bool, method: &mut Option<Method>, dst: &mut Vec<u8>) -> ::Result<h1::Encoder>; fn on_error(err: &::Error) -> Option<MessageHead<Self::Outgoing>>; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -134,7 +134,6 @@ where I, <S::ResponseBody as Stream>::Item, proto::ServerTransaction, - proto::KA, >, } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -310,12 +309,10 @@ impl<B: AsRef<[u8]> + 'static> Http<B> { I: AsyncRead + AsyncWrite, { - let ka = if self.keep_alive { - proto::KA::Busy - } else { - proto::KA::Disabled - }; - let mut conn = proto::Conn::new(io, ka); + let mut conn = proto::Conn::new(io); + if !self.keep_alive { + conn.disable_keep_alive(); + } conn.set_flush_pipeline(self.pipeline); if let Some(max) = self.max_buf_size { conn.set_max_buf_size(max); diff --git a/src/server/server_proto.rs b/src/server/server_proto.rs --- a/src/server/server_proto.rs +++ b/src/server/server_proto.rs @@ -99,12 +99,10 @@ impl<T, B> ServerProto<T> for Http<B> #[inline] fn bind_transport(&self, io: T) -> Self::BindTransport { - let ka = if self.keep_alive { - proto::KA::Busy - } else { - proto::KA::Disabled - }; - let mut conn = proto::Conn::new(io, ka); + let mut conn = proto::Conn::new(io); + if !self.keep_alive { + conn.disable_keep_alive(); + } conn.set_flush_pipeline(self.pipeline); if let Some(max) = self.max_buf_size { conn.set_max_buf_size(max);
diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -42,13 +41,15 @@ fn get_one_at_a_time(b: &mut test::Bencher) { #[bench] fn post_one_at_a_time(b: &mut test::Bencher) { + extern crate pretty_env_logger; + let _ = pretty_env_logger::try_init(); let mut core = Core::new().unwrap(); let handle = core.handle(); let addr = spawn_hello(&handle); let client = hyper::Client::new(&handle); - let url: hyper::Uri = format!("http://{}/get", addr).parse().unwrap(); + let url: hyper::Uri = format!("http://{}/post", addr).parse().unwrap(); let post = "foo bar baz quux"; b.bytes = 180 * 2 + post.len() as u64 + PHRASE.len() as u64; diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -69,35 +70,32 @@ fn post_one_at_a_time(b: &mut test::Bencher) { static PHRASE: &'static [u8] = include_bytes!("../CHANGELOG.md"); //b"Hello, World!"; -#[derive(Clone, Copy)] -struct Hello; - -impl Service for Hello { - type Request = server::Request; - type Response = server::Response; - type Error = hyper::Error; - type Future = future::FutureResult<Self::Response, hyper::Error>; - fn call(&self, _req: Self::Request) -> Self::Future { - future::ok( - server::Response::new() - .with_header(ContentLength(PHRASE.len() as u64)) - .with_header(ContentType::plaintext()) - .with_body(PHRASE) - ) - } - -} - fn spawn_hello(handle: &Handle) -> SocketAddr { + use hyper::server::{const_service, service_fn, NewService, Request, Response}; let addr = "127.0.0.1:0".parse().unwrap(); let listener = TcpListener::bind(&addr, handle).unwrap(); let addr = listener.local_addr().unwrap(); let handle2 = handle.clone(); let http = hyper::server::Http::<hyper::Chunk>::new(); + + let service = const_service(service_fn(|req: Request| { + req.body() + .concat2() + .map(|_| { + Response::<hyper::Body>::new() + .with_header(ContentLength(PHRASE.len() as u64)) + .with_header(ContentType::plaintext()) + .with_body(PHRASE) + }) + })); + + let mut conns = 0; handle.spawn(listener.incoming().for_each(move |(socket, _addr)| { + conns += 1; + assert_eq!(conns, 1, "should only need 1 connection"); handle2.spawn( - http.serve_connection(socket, Hello) + http.serve_connection(socket, service.new_service()?) .map(|_| ()) .map_err(|_| ()) ); diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -109,7 +116,7 @@ mod tests { future::lazy(|| { #[derive(Debug)] struct Custom(i32); - let (tx, rx) = super::channel::<Custom, ()>(); + let (mut tx, rx) = super::channel::<Custom, ()>(); let promise = tx.send(Custom(43)).unwrap(); drop(rx); diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -128,8 +135,8 @@ mod tests { #[cfg(feature = "nightly")] #[bench] - fn cancelable_queue_throughput(b: &mut test::Bencher) { - let (tx, mut rx) = super::channel::<i32, ()>(); + fn giver_queue_throughput(b: &mut test::Bencher) { + let (mut tx, mut rx) = super::channel::<i32, ()>(); b.iter(move || { ::futures::future::lazy(|| { diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -149,7 +156,7 @@ mod tests { #[cfg(feature = "nightly")] #[bench] - fn cancelable_queue_not_ready(b: &mut test::Bencher) { + fn giver_queue_not_ready(b: &mut test::Bencher) { let (_tx, mut rx) = super::channel::<i32, ()>(); b.iter(move || { diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -163,11 +170,11 @@ mod tests { #[cfg(feature = "nightly")] #[bench] - fn cancelable_queue_cancel(b: &mut test::Bencher) { - let (tx, _rx) = super::channel::<i32, ()>(); + fn giver_queue_cancel(b: &mut test::Bencher) { + let (_tx, rx) = super::channel::<i32, ()>(); b.iter(move || { - tx.cancel(); + rx.taker.cancel(); }) } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -36,6 +36,7 @@ mod dns; mod pool; #[cfg(feature = "compat")] pub mod compat; +mod signal; #[cfg(test)] mod tests; diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -470,22 +415,22 @@ impl<T: Closed + 'static> Future for IdleInterval<T> { try_ready!(self.interval.poll().map_err(|_| unreachable!("interval cannot error"))); if let Some(inner) = self.pool.upgrade() { - let pool = Pool { inner: inner }; - pool.clear_expired(); - } else { - return Ok(Async::Ready(())); + if let Ok(mut inner) = inner.lock() { + inner.clear_expired(); + continue; + } } + return Ok(Async::Ready(())); } } } #[cfg(test)] mod tests { - use std::rc::Rc; + use std::sync::Arc; use std::time::Duration; use futures::{Async, Future}; use futures::future; - use proto::KeepAlive; use super::{Closed, Pool}; impl Closed for i32 { diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -497,9 +442,10 @@ mod tests { #[test] fn test_pool_checkout_smoke() { let pool = Pool::new(true, Some(Duration::from_secs(5))); - let key = Rc::new("foo".to_string()); - let mut pooled = pool.pooled(key.clone(), 41); - pooled.idle(); + let key = Arc::new("foo".to_string()); + let pooled = pool.pooled(key.clone(), 41); + + drop(pooled); match pool.checkout(&key).poll().unwrap() { Async::Ready(pooled) => assert_eq!(*pooled, 41), diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -510,11 +456,11 @@ mod tests { #[test] fn test_pool_checkout_returns_none_if_expired() { future::lazy(|| { - let pool = Pool::new(true, Some(Duration::from_secs(1))); - let key = Rc::new("foo".to_string()); - let mut pooled = pool.pooled(key.clone(), 41); - pooled.idle(); - ::std::thread::sleep(pool.inner.borrow().timeout.unwrap()); + let pool = Pool::new(true, Some(Duration::from_millis(100))); + let key = Arc::new("foo".to_string()); + let pooled = pool.pooled(key.clone(), 41); + drop(pooled); + ::std::thread::sleep(pool.inner.lock().unwrap().timeout.unwrap()); assert!(pool.checkout(&key).poll().unwrap().is_not_ready()); ::futures::future::ok::<(), ()>(()) }).wait().unwrap(); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -522,26 +468,23 @@ mod tests { #[test] fn test_pool_checkout_removes_expired() { - let pool = Pool::new(true, Some(Duration::from_secs(1))); - let key = Rc::new("foo".to_string()); + future::lazy(|| { + let pool = Pool::new(true, Some(Duration::from_millis(100))); + let key = Arc::new("foo".to_string()); - let mut pooled1 = pool.pooled(key.clone(), 41); - pooled1.idle(); - let mut pooled2 = pool.pooled(key.clone(), 5); - pooled2.idle(); - let mut pooled3 = pool.pooled(key.clone(), 99); - pooled3.idle(); + pool.pooled(key.clone(), 41); + pool.pooled(key.clone(), 5); + pool.pooled(key.clone(), 99); + assert_eq!(pool.inner.lock().unwrap().idle.get(&key).map(|entries| entries.len()), Some(3)); + ::std::thread::sleep(pool.inner.lock().unwrap().timeout.unwrap()); - assert_eq!(pool.inner.borrow().idle.get(&key).map(|entries| entries.len()), Some(3)); - ::std::thread::sleep(pool.inner.borrow().timeout.unwrap()); + // checkout.poll() should clean out the expired + pool.checkout(&key).poll().unwrap(); + assert!(pool.inner.lock().unwrap().idle.get(&key).is_none()); - pooled1.idle(); - pooled2.idle(); // idle after sleep, not expired - pool.checkout(&key).poll().unwrap(); - assert_eq!(pool.inner.borrow().idle.get(&key).map(|entries| entries.len()), Some(1)); - pool.checkout(&key).poll().unwrap(); - assert!(pool.inner.borrow().idle.get(&key).is_none()); + Ok::<(), ()>(()) + }).wait().unwrap(); } #[test] diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -549,16 +492,13 @@ mod tests { let mut core = ::tokio::reactor::Core::new().unwrap(); let pool = Pool::new(true, Some(Duration::from_millis(100))); pool.spawn_expired_interval(&core.handle()); - let key = Rc::new("foo".to_string()); + let key = Arc::new("foo".to_string()); - let mut pooled1 = pool.pooled(key.clone(), 41); - pooled1.idle(); - let mut pooled2 = pool.pooled(key.clone(), 5); - pooled2.idle(); - let mut pooled3 = pool.pooled(key.clone(), 99); - pooled3.idle(); + pool.pooled(key.clone(), 41); + pool.pooled(key.clone(), 5); + pool.pooled(key.clone(), 99); - assert_eq!(pool.inner.borrow().idle.get(&key).map(|entries| entries.len()), Some(3)); + assert_eq!(pool.inner.lock().unwrap().idle.get(&key).map(|entries| entries.len()), Some(3)); let timeout = ::tokio::reactor::Timeout::new( Duration::from_millis(400), // allow for too-good resolution diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -566,49 +506,48 @@ mod tests { ).unwrap(); core.run(timeout).unwrap(); - assert!(pool.inner.borrow().idle.get(&key).is_none()); + assert!(pool.inner.lock().unwrap().idle.get(&key).is_none()); } #[test] fn test_pool_checkout_task_unparked() { let pool = Pool::new(true, Some(Duration::from_secs(10))); - let key = Rc::new("foo".to_string()); - let pooled1 = pool.pooled(key.clone(), 41); + let key = Arc::new("foo".to_string()); + let pooled = pool.pooled(key.clone(), 41); - let mut pooled = pooled1.clone(); let checkout = pool.checkout(&key).join(future::lazy(move || { // the checkout future will park first, // and then this lazy future will be polled, which will insert // the pooled back into the pool // // this test makes sure that doing so will unpark the checkout - pooled.idle(); + drop(pooled); Ok(()) })).map(|(entry, _)| entry); - assert_eq!(*checkout.wait().unwrap(), *pooled1); + assert_eq!(*checkout.wait().unwrap(), 41); } #[test] fn test_pool_checkout_drop_cleans_up_parked() { future::lazy(|| { - let pool = Pool::new(true, Some(Duration::from_secs(10))); - let key = Rc::new("localhost:12345".to_string()); - let _pooled1 = pool.pooled(key.clone(), 41); + let pool = Pool::<i32>::new(true, Some(Duration::from_secs(10))); + let key = Arc::new("localhost:12345".to_string()); + let mut checkout1 = pool.checkout(&key); let mut checkout2 = pool.checkout(&key); // first poll needed to get into Pool's parked checkout1.poll().unwrap(); - assert_eq!(pool.inner.borrow().parked.get(&key).unwrap().len(), 1); + assert_eq!(pool.inner.lock().unwrap().parked.get(&key).unwrap().len(), 1); checkout2.poll().unwrap(); - assert_eq!(pool.inner.borrow().parked.get(&key).unwrap().len(), 2); + assert_eq!(pool.inner.lock().unwrap().parked.get(&key).unwrap().len(), 2); // on drop, clean up Pool drop(checkout1); - assert_eq!(pool.inner.borrow().parked.get(&key).unwrap().len(), 1); + assert_eq!(pool.inner.lock().unwrap().parked.get(&key).unwrap().len(), 1); drop(checkout2); - assert!(pool.inner.borrow().parked.get(&key).is_none()); + assert!(pool.inner.lock().unwrap().parked.get(&key).is_none()); ::futures::future::ok::<(), ()>(()) }).wait().unwrap(); diff --git a/src/client/tests.rs b/src/client/tests.rs --- a/src/client/tests.rs +++ b/src/client/tests.rs @@ -45,3 +45,47 @@ fn retryable_request() { core.run(res2.join(srv2)).expect("res2"); } + +#[test] +fn conn_reset_after_write() { + let _ = pretty_env_logger::try_init(); + let mut core = Core::new().unwrap(); + + let mut connector = MockConnector::new(); + + let sock1 = connector.mock("http://mock.local/a"); + + let client = Client::configure() + .connector(connector) + .build(&core.handle()); + + + { + let res1 = client.get("http://mock.local/a".parse().unwrap()); + let srv1 = poll_fn(|| { + try_ready!(sock1.read(&mut [0u8; 512])); + try_ready!(sock1.write(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")); + Ok(Async::Ready(())) + }); + core.run(res1.join(srv1)).expect("res1"); + } + + let res2 = client.get("http://mock.local/a".parse().unwrap()); + let mut sock1 = Some(sock1); + let srv2 = poll_fn(|| { + // We purposefully keep the socket open until the client + // has written the second request, and THEN disconnect. + // + // Not because we expect servers to be jerks, but to trigger + // state where we write on an assumedly good connetion, and + // only reset the close AFTER we wrote bytes. + try_ready!(sock1.as_mut().unwrap().read(&mut [0u8; 512])); + sock1.take(); + Ok(Async::Ready(())) + }); + let err = core.run(res2.join(srv2)).expect_err("res2"); + match err { + ::Error::Incomplete => (), + other => panic!("expected Incomplete, found {:?}", other) + } +} diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -976,7 +1003,7 @@ mod tests { let good_message = b"GET / HTTP/1.1\r\n\r\n".to_vec(); let len = good_message.len(); let io = AsyncIo::new_buf(good_message, len); - let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io); match conn.poll().unwrap() { Async::Ready(Some(Frame::Message { message, body: false })) => { diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -994,7 +1021,7 @@ mod tests { let _: Result<(), ()> = future::lazy(|| { let good_message = b"GET / HTTP/1.1\r\nHost: foo.bar\r\n\r\n".to_vec(); let io = AsyncIo::new_buf(good_message, 10); - let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io); assert!(conn.poll().unwrap().is_not_ready()); conn.io.io_mut().block_in(50); let async = conn.poll().unwrap(); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1010,7 +1037,7 @@ mod tests { #[test] fn test_conn_init_read_eof_idle() { let io = AsyncIo::new_buf(vec![], 1); - let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io); conn.state.idle(); match conn.poll().unwrap() { diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1022,7 +1049,7 @@ mod tests { #[test] fn test_conn_init_read_eof_idle_partial_parse() { let io = AsyncIo::new_buf(b"GET / HTTP/1.1".to_vec(), 100); - let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io); conn.state.idle(); match conn.poll() { diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1036,7 +1063,7 @@ mod tests { let _: Result<(), ()> = future::lazy(|| { // server ignores let io = AsyncIo::new_eof(); - let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io); conn.state.busy(); match conn.poll().unwrap() { diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1046,7 +1073,7 @@ mod tests { // client let io = AsyncIo::new_eof(); - let mut conn = Conn::<_, proto::Chunk, ClientTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ClientTransaction>::new(io); conn.state.busy(); match conn.poll() { diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1061,7 +1088,7 @@ mod tests { fn test_conn_body_finish_read_eof() { let _: Result<(), ()> = future::lazy(|| { let io = AsyncIo::new_eof(); - let mut conn = Conn::<_, proto::Chunk, ClientTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ClientTransaction>::new(io); conn.state.busy(); conn.state.writing = Writing::KeepAlive; conn.state.reading = Reading::Body(Decoder::length(0)); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1086,7 +1113,7 @@ mod tests { fn test_conn_message_empty_body_read_eof() { let _: Result<(), ()> = future::lazy(|| { let io = AsyncIo::new_buf(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n".to_vec(), 1024); - let mut conn = Conn::<_, proto::Chunk, ClientTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ClientTransaction>::new(io); conn.state.busy(); conn.state.writing = Writing::KeepAlive; diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1110,7 +1137,7 @@ mod tests { fn test_conn_read_body_end() { let _: Result<(), ()> = future::lazy(|| { let io = AsyncIo::new_buf(b"POST / HTTP/1.1\r\nContent-Length: 5\r\n\r\n12345".to_vec(), 1024); - let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io); conn.state.busy(); match conn.poll() { diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1140,7 +1167,7 @@ mod tests { #[test] fn test_conn_closed_read() { let io = AsyncIo::new_buf(vec![], 0); - let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io); conn.state.close(); match conn.poll().unwrap() { diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1155,7 +1182,7 @@ mod tests { let _ = pretty_env_logger::try_init(); let _: Result<(), ()> = future::lazy(|| { let io = AsyncIo::new_buf(vec![], 0); - let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io); let max = super::super::io::DEFAULT_MAX_BUFFER_SIZE + 4096; conn.state.writing = Writing::Body(Encoder::length((max * 2) as u64)); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1180,7 +1207,7 @@ mod tests { fn test_conn_body_write_chunked() { let _: Result<(), ()> = future::lazy(|| { let io = AsyncIo::new_buf(vec![], 4096); - let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io); conn.state.writing = Writing::Body(Encoder::chunked()); assert!(conn.start_send(Frame::Body { chunk: Some("headers".into()) }).unwrap().is_ready()); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1193,7 +1220,7 @@ mod tests { fn test_conn_body_flush() { let _: Result<(), ()> = future::lazy(|| { let io = AsyncIo::new_buf(vec![], 1024 * 1024 * 5); - let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io); conn.state.writing = Writing::Body(Encoder::length(1024 * 1024)); assert!(conn.start_send(Frame::Body { chunk: Some(vec![b'a'; 1024 * 1024].into()) }).unwrap().is_ready()); assert!(!conn.can_buffer_body()); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1230,7 +1257,7 @@ mod tests { // test that once writing is done, unparks let f = future::lazy(|| { let io = AsyncIo::new_buf(vec![], 4096); - let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io); conn.state.reading = Reading::KeepAlive; assert!(conn.poll().unwrap().is_not_ready()); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1244,7 +1271,7 @@ mod tests { // test that flushing when not waiting on read doesn't unpark let f = future::lazy(|| { let io = AsyncIo::new_buf(vec![], 4096); - let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io); conn.state.writing = Writing::KeepAlive; assert!(conn.poll_complete().unwrap().is_ready()); Ok::<(), ()>(()) diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1255,7 +1282,7 @@ mod tests { // test that flushing and writing isn't done doesn't unpark let f = future::lazy(|| { let io = AsyncIo::new_buf(vec![], 4096); - let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io); conn.state.reading = Reading::KeepAlive; assert!(conn.poll().unwrap().is_not_ready()); conn.state.writing = Writing::Body(Encoder::length(5_000)); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1268,7 +1295,7 @@ mod tests { #[test] fn test_conn_closed_write() { let io = AsyncIo::new_buf(vec![], 0); - let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io); conn.state.close(); match conn.start_send(Frame::Body { chunk: Some(b"foobar".to_vec().into()) }) { diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1282,7 +1309,7 @@ mod tests { #[test] fn test_conn_write_empty_chunk() { let io = AsyncIo::new_buf(vec![], 0); - let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); + let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io); conn.state.writing = Writing::KeepAlive; assert!(conn.start_send(Frame::Body { chunk: None }).unwrap().is_ready()); diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -445,8 +466,8 @@ mod tests { let _ = pretty_env_logger::try_init(); ::futures::lazy(|| { let io = AsyncIo::new_buf(b"HTTP/1.1 200 OK\r\n\r\n".to_vec(), 100); - let (tx, rx) = ::client::dispatch::channel(); - let conn = Conn::<_, ::Chunk, ClientTransaction>::new(io, Default::default()); + let (mut tx, rx) = ::client::dispatch::channel(); + let conn = Conn::<_, ::Chunk, ClientTransaction>::new(io); let mut dispatcher = Dispatcher::new(Client::new(rx), conn); let req = RequestHead { diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -456,16 +509,43 @@ fn extend(dst: &mut Vec<u8>, data: &[u8]) { mod tests { use bytes::BytesMut; - use proto::{MessageHead, ServerTransaction, ClientTransaction, Http1Transaction}; + use proto::{Decode, MessageHead}; + use super::{Decoder, Server as S, Client as C, NoUpgrades, Http1Transaction}; use header::{ContentLength, TransferEncoding}; + type Server = S<NoUpgrades>; + type Client = C<NoUpgrades>; + + impl Decode { + fn final_(self) -> Decoder { + match self { + Decode::Final(d) => d, + other => panic!("expected Final, found {:?}", other), + } + } + + fn normal(self) -> Decoder { + match self { + Decode::Normal(d) => d, + other => panic!("expected Normal, found {:?}", other), + } + } + + fn ignore(self) { + match self { + Decode::Ignore => {}, + other => panic!("expected Ignore, found {:?}", other), + } + } + } + #[test] fn test_parse_request() { extern crate pretty_env_logger; let _ = pretty_env_logger::try_init(); let mut raw = BytesMut::from(b"GET /echo HTTP/1.1\r\nHost: hyper.rs\r\n\r\n".to_vec()); let expected_len = raw.len(); - let (req, len) = ServerTransaction::parse(&mut raw).unwrap().unwrap(); + let (req, len) = Server::parse(&mut raw).unwrap().unwrap(); assert_eq!(len, expected_len); assert_eq!(req.subject.0, ::Method::Get); assert_eq!(req.subject.1, "/echo"); diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -481,7 +561,7 @@ mod tests { let _ = pretty_env_logger::try_init(); let mut raw = BytesMut::from(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n".to_vec()); let expected_len = raw.len(); - let (req, len) = ClientTransaction::parse(&mut raw).unwrap().unwrap(); + let (req, len) = Client::parse(&mut raw).unwrap().unwrap(); assert_eq!(len, expected_len); assert_eq!(req.subject.0, 200); assert_eq!(req.subject.1, "OK"); diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -493,17 +573,17 @@ mod tests { #[test] fn test_parse_request_errors() { let mut raw = BytesMut::from(b"GET htt:p// HTTP/1.1\r\nHost: hyper.rs\r\n\r\n".to_vec()); - ServerTransaction::parse(&mut raw).unwrap_err(); + Server::parse(&mut raw).unwrap_err(); } #[test] fn test_parse_raw_status() { let mut raw = BytesMut::from(b"HTTP/1.1 200 OK\r\n\r\n".to_vec()); - let (res, _) = ClientTransaction::parse(&mut raw).unwrap().unwrap(); + let (res, _) = Client::parse(&mut raw).unwrap().unwrap(); assert_eq!(res.subject.1, "OK"); let mut raw = BytesMut::from(b"HTTP/1.1 200 Howdy\r\n\r\n".to_vec()); - let (res, _) = ClientTransaction::parse(&mut raw).unwrap().unwrap(); + let (res, _) = Client::parse(&mut raw).unwrap().unwrap(); assert_eq!(res.subject.1, "Howdy"); } diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -516,32 +596,32 @@ mod tests { let mut head = MessageHead::<::proto::RequestLine>::default(); head.subject.0 = ::Method::Get; - assert_eq!(Decoder::length(0), ServerTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::length(0), Server::decoder(&head, method).unwrap().normal()); assert_eq!(*method, Some(::Method::Get)); head.subject.0 = ::Method::Post; - assert_eq!(Decoder::length(0), ServerTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::length(0), Server::decoder(&head, method).unwrap().normal()); assert_eq!(*method, Some(::Method::Post)); head.headers.set(TransferEncoding::chunked()); - assert_eq!(Decoder::chunked(), ServerTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::chunked(), Server::decoder(&head, method).unwrap().normal()); // transfer-encoding and content-length = chunked head.headers.set(ContentLength(10)); - assert_eq!(Decoder::chunked(), ServerTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::chunked(), Server::decoder(&head, method).unwrap().normal()); head.headers.remove::<TransferEncoding>(); - assert_eq!(Decoder::length(10), ServerTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::length(10), Server::decoder(&head, method).unwrap().normal()); head.headers.set_raw("Content-Length", vec![b"5".to_vec(), b"5".to_vec()]); - assert_eq!(Decoder::length(5), ServerTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::length(5), Server::decoder(&head, method).unwrap().normal()); head.headers.set_raw("Content-Length", vec![b"10".to_vec(), b"11".to_vec()]); - ServerTransaction::decoder(&head, method).unwrap_err(); + Server::decoder(&head, method).unwrap_err(); head.headers.remove::<ContentLength>(); head.headers.set_raw("Transfer-Encoding", "gzip"); - ServerTransaction::decoder(&head, method).unwrap_err(); + Server::decoder(&head, method).unwrap_err(); // http/1.0 diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -549,14 +629,14 @@ mod tests { head.headers.clear(); // 1.0 requests can only have bodies if content-length is set - assert_eq!(Decoder::length(0), ServerTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::length(0), Server::decoder(&head, method).unwrap().normal()); head.headers.set(TransferEncoding::chunked()); - ServerTransaction::decoder(&head, method).unwrap_err(); + Server::decoder(&head, method).unwrap_err(); head.headers.remove::<TransferEncoding>(); head.headers.set(ContentLength(15)); - assert_eq!(Decoder::length(15), ServerTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::length(15), Server::decoder(&head, method).unwrap().normal()); } #[test] diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -567,64 +647,64 @@ mod tests { let mut head = MessageHead::<::proto::RawStatus>::default(); head.subject.0 = 204; - assert_eq!(Decoder::length(0), ClientTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::length(0), Client::decoder(&head, method).unwrap().normal()); head.subject.0 = 304; - assert_eq!(Decoder::length(0), ClientTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::length(0), Client::decoder(&head, method).unwrap().normal()); head.subject.0 = 200; - assert_eq!(Decoder::eof(), ClientTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::eof(), Client::decoder(&head, method).unwrap().normal()); *method = Some(::Method::Head); - assert_eq!(Decoder::length(0), ClientTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::length(0), Client::decoder(&head, method).unwrap().normal()); *method = Some(::Method::Connect); - assert_eq!(Decoder::length(0), ClientTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::length(0), Client::decoder(&head, method).unwrap().final_()); // CONNECT receiving non 200 can have a body head.subject.0 = 404; head.headers.set(ContentLength(10)); - assert_eq!(Decoder::length(10), ClientTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::length(10), Client::decoder(&head, method).unwrap().normal()); head.headers.remove::<ContentLength>(); *method = Some(::Method::Get); head.headers.set(TransferEncoding::chunked()); - assert_eq!(Decoder::chunked(), ClientTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::chunked(), Client::decoder(&head, method).unwrap().normal()); // transfer-encoding and content-length = chunked head.headers.set(ContentLength(10)); - assert_eq!(Decoder::chunked(), ClientTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::chunked(), Client::decoder(&head, method).unwrap().normal()); head.headers.remove::<TransferEncoding>(); - assert_eq!(Decoder::length(10), ClientTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::length(10), Client::decoder(&head, method).unwrap().normal()); head.headers.set_raw("Content-Length", vec![b"5".to_vec(), b"5".to_vec()]); - assert_eq!(Decoder::length(5), ClientTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::length(5), Client::decoder(&head, method).unwrap().normal()); head.headers.set_raw("Content-Length", vec![b"10".to_vec(), b"11".to_vec()]); - ClientTransaction::decoder(&head, method).unwrap_err(); + Client::decoder(&head, method).unwrap_err(); head.headers.clear(); // 1xx status codes head.subject.0 = 100; - assert!(ClientTransaction::decoder(&head, method).unwrap().is_none()); + Client::decoder(&head, method).unwrap().ignore(); head.subject.0 = 103; - assert!(ClientTransaction::decoder(&head, method).unwrap().is_none()); + Client::decoder(&head, method).unwrap().ignore(); // 101 upgrade not supported yet head.subject.0 = 101; - ClientTransaction::decoder(&head, method).unwrap_err(); + Client::decoder(&head, method).unwrap_err(); head.subject.0 = 200; // http/1.0 head.version = ::HttpVersion::Http10; - assert_eq!(Decoder::eof(), ClientTransaction::decoder(&head, method).unwrap().unwrap()); + assert_eq!(Decoder::eof(), Client::decoder(&head, method).unwrap().normal()); head.headers.set(TransferEncoding::chunked()); - ClientTransaction::decoder(&head, method).unwrap_err(); + Client::decoder(&head, method).unwrap_err(); } #[cfg(feature = "nightly")] diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -656,7 +736,7 @@ mod tests { b.bytes = len as u64; b.iter(|| { - ServerTransaction::parse(&mut raw).unwrap(); + Server::parse(&mut raw).unwrap(); restart(&mut raw, len); }); diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -688,7 +768,7 @@ mod tests { b.iter(|| { let mut vec = Vec::new(); - ServerTransaction::encode(head.clone(), true, &mut None, &mut vec).unwrap(); + Server::encode(head.clone(), true, &mut None, &mut vec).unwrap(); assert_eq!(vec.len(), len); ::test::black_box(vec); }) diff --git a/src/proto/mod.rs b/src/proto/mod.rs --- a/src/proto/mod.rs +++ b/src/proto/mod.rs @@ -154,6 +153,16 @@ pub trait Http1Transaction { pub type ParseResult<T> = ::Result<Option<(MessageHead<T>, usize)>>; +#[derive(Debug)] +pub enum Decode { + /// Decode normally. + Normal(h1::Decoder), + /// After this decoder is done, HTTP is done. + Final(h1::Decoder), + /// A header block that should be ignored, like unknown 1xx responses. + Ignore, +} + #[test] fn test_should_keep_alive() { let mut headers = Headers::new(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -737,7 +737,7 @@ mod dispatch_impl { use std::time::Duration; use futures::{self, Future}; - use futures::sync::oneshot; + use futures::sync::{mpsc, oneshot}; use tokio_core::reactor::{Timeout}; use tokio_core::net::TcpStream; use tokio_io::{AsyncRead, AsyncWrite}; diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -758,9 +758,9 @@ mod dispatch_impl { let addr = server.local_addr().unwrap(); let mut core = Core::new().unwrap(); let handle = core.handle(); - let closes = Arc::new(AtomicUsize::new(0)); + let (closes_tx, closes) = mpsc::channel(10); let client = Client::configure() - .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &core.handle()), closes.clone())) + .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &core.handle()), closes_tx)) .build(&handle); let (tx1, rx1) = oneshot::channel(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -787,7 +787,7 @@ mod dispatch_impl { let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); core.run(res.join(rx).map(|r| r.0)).unwrap(); - assert_eq!(closes.load(Ordering::Relaxed), 1); + core.run(closes.into_future()).unwrap().0.expect("closes"); } #[test] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -799,7 +799,7 @@ mod dispatch_impl { let addr = server.local_addr().unwrap(); let mut core = Core::new().unwrap(); let handle = core.handle(); - let closes = Arc::new(AtomicUsize::new(0)); + let (closes_tx, closes) = mpsc::channel(10); let (tx1, rx1) = oneshot::channel(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -819,7 +819,7 @@ mod dispatch_impl { let res = { let client = Client::configure() - .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes.clone())) + .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes_tx)) .build(&handle); client.get(uri).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::Ok); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -833,7 +833,7 @@ mod dispatch_impl { let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); core.run(res.join(rx).map(|r| r.0)).unwrap(); - assert_eq!(closes.load(Ordering::Relaxed), 1); + core.run(closes.into_future()).unwrap().0.expect("closes"); } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -845,7 +845,7 @@ mod dispatch_impl { let addr = server.local_addr().unwrap(); let mut core = Core::new().unwrap(); let handle = core.handle(); - let closes = Arc::new(AtomicUsize::new(0)); + let (closes_tx, mut closes) = mpsc::channel(10); let (tx1, rx1) = oneshot::channel(); let (_client_drop_tx, client_drop_rx) = oneshot::channel::<()>(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -869,7 +869,7 @@ mod dispatch_impl { let uri = format!("http://{}/a", addr).parse().unwrap(); let client = Client::configure() - .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes.clone())) + .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes_tx)) .build(&handle); let res = client.get(uri).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::Ok); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -879,13 +879,25 @@ mod dispatch_impl { core.run(res.join(rx).map(|r| r.0)).unwrap(); // not closed yet, just idle - assert_eq!(closes.load(Ordering::Relaxed), 0); + { + futures::future::poll_fn(|| { + assert!(closes.poll()?.is_not_ready()); + Ok::<_, ()>(().into()) + }).wait().unwrap(); + } drop(client); - core.run(Timeout::new(Duration::from_millis(100), &handle).unwrap()).unwrap(); - assert_eq!(closes.load(Ordering::Relaxed), 1); + let t = Timeout::new(Duration::from_millis(100), &handle).unwrap() + .map(|_| panic!("time out")); + let close = closes.into_future() + .map(|(opt, _)| { + opt.expect("closes"); + }) + .map_err(|_| panic!("closes dropped")); + let _ = core.run(t.select(close)); } + #[test] fn drop_response_future_closes_in_progress_connection() { let _ = pretty_env_logger::try_init(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -894,7 +906,7 @@ mod dispatch_impl { let addr = server.local_addr().unwrap(); let mut core = Core::new().unwrap(); let handle = core.handle(); - let closes = Arc::new(AtomicUsize::new(0)); + let (closes_tx, closes) = mpsc::channel(10); let (tx1, rx1) = oneshot::channel(); let (_client_drop_tx, client_drop_rx) = oneshot::channel::<()>(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -918,7 +930,7 @@ mod dispatch_impl { let res = { let client = Client::configure() - .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes.clone())) + .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes_tx)) .build(&handle); client.get(uri) }; diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -926,9 +938,14 @@ mod dispatch_impl { //let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); core.run(res.select2(rx1)).unwrap(); // res now dropped - core.run(Timeout::new(Duration::from_millis(100), &handle).unwrap()).unwrap(); - - assert_eq!(closes.load(Ordering::Relaxed), 1); + let t = Timeout::new(Duration::from_millis(100), &handle).unwrap() + .map(|_| panic!("time out")); + let close = closes.into_future() + .map(|(opt, _)| { + opt.expect("closes"); + }) + .map_err(|_| panic!("closes dropped")); + let _ = core.run(t.select(close)); } #[test] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -939,7 +956,7 @@ mod dispatch_impl { let addr = server.local_addr().unwrap(); let mut core = Core::new().unwrap(); let handle = core.handle(); - let closes = Arc::new(AtomicUsize::new(0)); + let (closes_tx, closes) = mpsc::channel(10); let (tx1, rx1) = oneshot::channel(); let (_client_drop_tx, client_drop_rx) = oneshot::channel::<()>(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -962,7 +979,7 @@ mod dispatch_impl { let res = { let client = Client::configure() - .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes.clone())) + .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes_tx)) .build(&handle); // notably, havent read body yet client.get(uri) diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -970,9 +987,15 @@ mod dispatch_impl { let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); core.run(res.join(rx).map(|r| r.0)).unwrap(); - core.run(Timeout::new(Duration::from_millis(100), &handle).unwrap()).unwrap(); - assert_eq!(closes.load(Ordering::Relaxed), 1); + let t = Timeout::new(Duration::from_millis(100), &handle).unwrap() + .map(|_| panic!("time out")); + let close = closes.into_future() + .map(|(opt, _)| { + opt.expect("closes"); + }) + .map_err(|_| panic!("closes dropped")); + let _ = core.run(t.select(close)); } #[test] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -984,7 +1007,7 @@ mod dispatch_impl { let addr = server.local_addr().unwrap(); let mut core = Core::new().unwrap(); let handle = core.handle(); - let closes = Arc::new(AtomicUsize::new(0)); + let (closes_tx, closes) = mpsc::channel(10); let (tx1, rx1) = oneshot::channel(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1001,7 +1024,7 @@ mod dispatch_impl { let uri = format!("http://{}/a", addr).parse().unwrap(); let client = Client::configure() - .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes.clone())) + .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes_tx)) .keep_alive(false) .build(&handle); let res = client.get(uri).and_then(move |res| { diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1011,7 +1034,14 @@ mod dispatch_impl { let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); core.run(res.join(rx).map(|r| r.0)).unwrap(); - assert_eq!(closes.load(Ordering::Relaxed), 1); + let t = Timeout::new(Duration::from_millis(100), &handle).unwrap() + .map(|_| panic!("time out")); + let close = closes.into_future() + .map(|(opt, _)| { + opt.expect("closes"); + }) + .map_err(|_| panic!("closes dropped")); + let _ = core.run(t.select(close)); } #[test] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1023,7 +1053,7 @@ mod dispatch_impl { let addr = server.local_addr().unwrap(); let mut core = Core::new().unwrap(); let handle = core.handle(); - let closes = Arc::new(AtomicUsize::new(0)); + let (closes_tx, closes) = mpsc::channel(10); let (tx1, rx1) = oneshot::channel(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1040,19 +1070,24 @@ mod dispatch_impl { let uri = format!("http://{}/a", addr).parse().unwrap(); let client = Client::configure() - .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes.clone())) + .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes_tx)) .build(&handle); let res = client.get(uri).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::Ok); res.body().concat2() }); let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); - - let timeout = Timeout::new(Duration::from_millis(200), &handle).unwrap(); - let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); core.run(res.join(rx).map(|r| r.0)).unwrap(); - assert_eq!(closes.load(Ordering::Relaxed), 1); + + let t = Timeout::new(Duration::from_millis(100), &handle).unwrap() + .map(|_| panic!("time out")); + let close = closes.into_future() + .map(|(opt, _)| { + opt.expect("closes"); + }) + .map_err(|_| panic!("closes dropped")); + let _ = core.run(t.select(close)); } #[test] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1113,7 +1148,7 @@ mod dispatch_impl { let addr = server.local_addr().unwrap(); let mut core = Core::new().unwrap(); let handle = core.handle(); - let closes = Arc::new(AtomicUsize::new(0)); + let (closes_tx, closes) = mpsc::channel(10); let (tx1, rx1) = oneshot::channel(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1130,7 +1165,7 @@ mod dispatch_impl { let uri = format!("http://{}/a", addr).parse().unwrap(); let client = Client::configure() - .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes.clone())) + .connector(DebugConnector::with_http_and_closes(HttpConnector::new(1, &handle), closes_tx)) .executor(handle.clone()); let res = client.get(uri).and_then(move |res| { assert_eq!(res.status(), hyper::StatusCode::Ok); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1142,75 +1177,58 @@ mod dispatch_impl { let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); core.run(res.join(rx).map(|r| r.0)).unwrap(); - assert_eq!(closes.load(Ordering::Relaxed), 1); + + let t = Timeout::new(Duration::from_millis(100), &handle).unwrap() + .map(|_| panic!("time out")); + let close = closes.into_future() + .map(|(opt, _)| { + opt.expect("closes"); + }) + .map_err(|_| panic!("closes dropped")); + let _ = core.run(t.select(close)); } #[test] - fn idle_conn_prevents_connect_call() { + fn connect_call_is_lazy() { + // We especially don't want connects() triggered if there's + // idle connections that the Checkout would have found let _ = pretty_env_logger::try_init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); - let mut core = Core::new().unwrap(); + let core = Core::new().unwrap(); let handle = core.handle(); let connector = DebugConnector::new(&handle); let connects = connector.connects.clone(); - let (tx1, rx1) = oneshot::channel(); - let (tx2, rx2) = oneshot::channel(); - - thread::spawn(move || { - let mut sock = server.accept().unwrap().0; - sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); - sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); - let mut buf = [0; 4096]; - sock.read(&mut buf).expect("read 1"); - sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap(); - let _ = tx1.send(()); - - sock.read(&mut buf).expect("read 2"); - sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap(); - let _ = tx2.send(()); - }); - let uri: hyper::Uri = format!("http://{}/a", addr).parse().unwrap(); let client = Client::configure() .connector(connector) .build(&handle); - let res = client.get(uri.clone()).and_then(move |res| { - assert_eq!(res.status(), hyper::StatusCode::Ok); - res.body().concat2() - }); - let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); - core.run(res.join(rx).map(|r| r.0)).unwrap(); - assert_eq!(connects.load(Ordering::Relaxed), 1); - - let res2 = client.get(uri).and_then(move |res| { - assert_eq!(res.status(), hyper::StatusCode::Ok); - res.body().concat2() - }); - let rx = rx2.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); - core.run(res2.join(rx).map(|r| r.0)).unwrap(); - - assert_eq!(connects.load(Ordering::Relaxed), 1); + assert_eq!(connects.load(Ordering::Relaxed), 0); + let _fut = client.get(uri); + // internal Connect::connect should have been lazy, and not + // triggered an actual connect yet. + assert_eq!(connects.load(Ordering::Relaxed), 0); } struct DebugConnector { http: HttpConnector, - closes: Arc<AtomicUsize>, + closes: mpsc::Sender<()>, connects: Arc<AtomicUsize>, } impl DebugConnector { fn new(handle: &Handle) -> DebugConnector { let http = HttpConnector::new(1, handle); - DebugConnector::with_http_and_closes(http, Arc::new(AtomicUsize::new(0))) + let (tx, _) = mpsc::channel(10); + DebugConnector::with_http_and_closes(http, tx) } - fn with_http_and_closes(http: HttpConnector, closes: Arc<AtomicUsize>) -> DebugConnector { + fn with_http_and_closes(http: HttpConnector, closes: mpsc::Sender<()>) -> DebugConnector { DebugConnector { http: http, closes: closes, diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1234,11 +1252,11 @@ mod dispatch_impl { } } - struct DebugStream(TcpStream, Arc<AtomicUsize>); + struct DebugStream(TcpStream, mpsc::Sender<()>); impl Drop for DebugStream { fn drop(&mut self) { - self.1.fetch_add(1, Ordering::SeqCst); + let _ = self.1.try_send(()); } } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1266,3 +1284,356 @@ mod dispatch_impl { impl AsyncRead for DebugStream {} } + +mod conn { + use std::io::{self, Read, Write}; + use std::net::TcpListener; + use std::thread; + use std::time::Duration; + + use futures::{Async, Future, Poll, Stream}; + use futures::future::poll_fn; + use futures::sync::oneshot; + use tokio_core::reactor::{Core, Timeout}; + use tokio_core::net::TcpStream; + use tokio_io::{AsyncRead, AsyncWrite}; + + use hyper::{self, Method, Request}; + use hyper::client::conn; + + use super::s; + + #[test] + fn get() { + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = server.local_addr().unwrap(); + let mut core = Core::new().unwrap(); + let handle = core.handle(); + + let (tx1, rx1) = oneshot::channel(); + + thread::spawn(move || { + let mut sock = server.accept().unwrap().0; + sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut buf = [0; 4096]; + let n = sock.read(&mut buf).expect("read 1"); + + // Notably: + // - Just a path, since just a path was set + // - No host, since no host was set + let expected = "GET /a HTTP/1.1\r\n\r\n"; + assert_eq!(s(&buf[..n]), expected); + + sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap(); + let _ = tx1.send(()); + }); + + let tcp = core.run(TcpStream::connect(&addr, &handle)).unwrap(); + + let (mut client, conn) = core.run(conn::handshake(tcp)).unwrap(); + + handle.spawn(conn.map(|_| ()).map_err(|e| panic!("conn error: {}", e))); + + let uri = "/a".parse().unwrap(); + let req = Request::new(Method::Get, uri); + + let res = client.send_request(req).and_then(move |res| { + assert_eq!(res.status(), hyper::StatusCode::Ok); + res.body().concat2() + }); + let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + + let timeout = Timeout::new(Duration::from_millis(200), &handle).unwrap(); + let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); + core.run(res.join(rx).map(|r| r.0)).unwrap(); + } + + #[test] + fn uri_absolute_form() { + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = server.local_addr().unwrap(); + let mut core = Core::new().unwrap(); + let handle = core.handle(); + + let (tx1, rx1) = oneshot::channel(); + + thread::spawn(move || { + let mut sock = server.accept().unwrap().0; + sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut buf = [0; 4096]; + let n = sock.read(&mut buf).expect("read 1"); + + // Notably: + // - Still no Host header, since it wasn't set + let expected = "GET http://hyper.local/a HTTP/1.1\r\n\r\n"; + assert_eq!(s(&buf[..n]), expected); + + sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap(); + let _ = tx1.send(()); + }); + + let tcp = core.run(TcpStream::connect(&addr, &handle)).unwrap(); + + let (mut client, conn) = core.run(conn::handshake(tcp)).unwrap(); + + handle.spawn(conn.map(|_| ()).map_err(|e| panic!("conn error: {}", e))); + + let uri = "http://hyper.local/a".parse().unwrap(); + let req = Request::new(Method::Get, uri); + + let res = client.send_request(req).and_then(move |res| { + assert_eq!(res.status(), hyper::StatusCode::Ok); + res.body().concat2() + }); + let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + + let timeout = Timeout::new(Duration::from_millis(200), &handle).unwrap(); + let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); + core.run(res.join(rx).map(|r| r.0)).unwrap(); + } + + + #[test] + fn pipeline() { + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = server.local_addr().unwrap(); + let mut core = Core::new().unwrap(); + let handle = core.handle(); + + let (tx1, rx1) = oneshot::channel(); + + thread::spawn(move || { + let mut sock = server.accept().unwrap().0; + sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut buf = [0; 4096]; + sock.read(&mut buf).expect("read 1"); + sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap(); + let _ = tx1.send(()); + }); + + let tcp = core.run(TcpStream::connect(&addr, &handle)).unwrap(); + + let (mut client, conn) = core.run(conn::handshake(tcp)).unwrap(); + + handle.spawn(conn.map(|_| ()).map_err(|e| panic!("conn error: {}", e))); + + let uri = "/a".parse().unwrap(); + let req = Request::new(Method::Get, uri); + let res1 = client.send_request(req).and_then(move |res| { + assert_eq!(res.status(), hyper::StatusCode::Ok); + res.body().concat2() + }); + + // pipelined request will hit NotReady, and thus should return an Error::Cancel + let uri = "/b".parse().unwrap(); + let req = Request::new(Method::Get, uri); + let res2 = client.send_request(req) + .then(|result| { + let err = result.expect_err("res2"); + match err { + hyper::Error::Cancel(..) => (), + other => panic!("expected Cancel, found {:?}", other), + } + Ok(()) + }); + + let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + + let timeout = Timeout::new(Duration::from_millis(200), &handle).unwrap(); + let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); + core.run(res1.join(res2).join(rx).map(|r| r.0)).unwrap(); + } + + #[test] + fn upgrade() { + use tokio_io::io::{read_to_end, write_all}; + let _ = ::pretty_env_logger::try_init(); + + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = server.local_addr().unwrap(); + let mut core = Core::new().unwrap(); + let handle = core.handle(); + + let (tx1, rx1) = oneshot::channel(); + + thread::spawn(move || { + let mut sock = server.accept().unwrap().0; + sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut buf = [0; 4096]; + sock.read(&mut buf).expect("read 1"); + sock.write_all(b"\ + HTTP/1.1 101 Switching Protocols\r\n\ + Upgrade: foobar\r\n\ + \r\n\ + foobar=ready\ + ").unwrap(); + let _ = tx1.send(()); + + let n = sock.read(&mut buf).expect("read 2"); + assert_eq!(&buf[..n], b"foo=bar"); + sock.write_all(b"bar=foo").expect("write 2"); + }); + + let tcp = core.run(TcpStream::connect(&addr, &handle)).unwrap(); + + let io = DebugStream { + tcp: tcp, + shutdown_called: false, + }; + + let (mut client, mut conn) = core.run(conn::handshake(io)).unwrap(); + + { + let until_upgrade = poll_fn(|| { + conn.poll_without_shutdown() + }); + + let uri = "/a".parse().unwrap(); + let req = Request::new(Method::Get, uri); + let res = client.send_request(req).and_then(move |res| { + assert_eq!(res.status(), hyper::StatusCode::SwitchingProtocols); + assert_eq!(res.headers().get_raw("Upgrade").unwrap(), "foobar"); + res.body().concat2() + }); + + let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + + let timeout = Timeout::new(Duration::from_millis(200), &handle).unwrap(); + let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); + core.run(until_upgrade.join(res).join(rx).map(|r| r.0)).unwrap(); + + // should not be ready now + core.run(poll_fn(|| { + assert!(client.poll_ready().unwrap().is_not_ready()); + Ok::<_, ()>(Async::Ready(())) + })).unwrap(); + } + + let parts = conn.into_parts(); + let io = parts.io; + let buf = parts.read_buf; + + assert_eq!(buf, b"foobar=ready"[..]); + assert!(!io.shutdown_called, "upgrade shouldn't shutdown AsyncWrite"); + assert!(client.poll_ready().is_err()); + + let io = core.run(write_all(io, b"foo=bar")).unwrap().0; + let vec = core.run(read_to_end(io, vec![])).unwrap().1; + assert_eq!(vec, b"bar=foo"); + } + + #[test] + fn connect_method() { + use tokio_io::io::{read_to_end, write_all}; + let _ = ::pretty_env_logger::try_init(); + + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = server.local_addr().unwrap(); + let mut core = Core::new().unwrap(); + let handle = core.handle(); + + let (tx1, rx1) = oneshot::channel(); + + thread::spawn(move || { + let mut sock = server.accept().unwrap().0; + sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut buf = [0; 4096]; + sock.read(&mut buf).expect("read 1"); + sock.write_all(b"\ + HTTP/1.1 200 OK\r\n\ + \r\n\ + foobar=ready\ + ").unwrap(); + let _ = tx1.send(()); + + let n = sock.read(&mut buf).expect("read 2"); + assert_eq!(&buf[..n], b"foo=bar", "sock read 2 bytes"); + sock.write_all(b"bar=foo").expect("write 2"); + }); + + let tcp = core.run(TcpStream::connect(&addr, &handle)).unwrap(); + + let io = DebugStream { + tcp: tcp, + shutdown_called: false, + }; + + let (mut client, mut conn) = core.run(conn::handshake(io)).unwrap(); + + { + let until_tunneled = poll_fn(|| { + conn.poll_without_shutdown() + }); + + let uri = format!("http://{}", addr).parse().unwrap(); + let req = Request::new(Method::Connect, uri); + let res = client.send_request(req) + .and_then(move |res| { + assert_eq!(res.status(), hyper::StatusCode::Ok); + res.body().concat2() + }) + .map(|body| { + assert_eq!(body.as_ref(), b""); + }); + + let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + + let timeout = Timeout::new(Duration::from_millis(200), &handle).unwrap(); + let rx = rx.and_then(move |_| timeout.map_err(|e| e.into())); + core.run(until_tunneled.join(res).join(rx).map(|r| r.0)).unwrap(); + + // should not be ready now + core.run(poll_fn(|| { + assert!(client.poll_ready().unwrap().is_not_ready()); + Ok::<_, ()>(Async::Ready(())) + })).unwrap(); + } + + let parts = conn.into_parts(); + let io = parts.io; + let buf = parts.read_buf; + + assert_eq!(buf, b"foobar=ready"[..]); + assert!(!io.shutdown_called, "tunnel shouldn't shutdown AsyncWrite"); + assert!(client.poll_ready().is_err()); + + let io = core.run(write_all(io, b"foo=bar")).unwrap().0; + let vec = core.run(read_to_end(io, vec![])).unwrap().1; + assert_eq!(vec, b"bar=foo"); + } + + struct DebugStream { + tcp: TcpStream, + shutdown_called: bool, + } + + impl Write for DebugStream { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.tcp.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.tcp.flush() + } + } + + impl AsyncWrite for DebugStream { + fn shutdown(&mut self) -> Poll<(), io::Error> { + self.shutdown_called = true; + AsyncWrite::shutdown(&mut self.tcp) + } + } + + impl Read for DebugStream { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.tcp.read(buf) + } + } + + impl AsyncRead for DebugStream {} +}
A lower level Connection API for the Client The `Client` is a higher level API that, among other things, provides a connection pool. Similar to how the server has higher and lower level APIs (`Server` vs `Serve`/`Connection`), the client should gain a lower level connection based API. This would allow finer grained control over when connections are made, and would allow external pool implementations (cc #1253). ### Implementation There would be a new `hyper::client::Connection` type, which implements `Service`. It would represent a single connection bound to HTTP. It would not reconnect itself when it is closed, someone managing the connection would handle that.
This would be great! The API I've been prototyping has a similar look to the [h2 client](https://docs.rs/h2/0.1.*/h2/client/index.html), where you provide an already connected `io`, and get back a sender (`SendRequest`?) and `Connection` pair. You probably want to just spawn the `Connection` into an executor, and then use the sender to send requests, but there are methods on `Connection` to allow finer control. At this level, the internals can be configured to allow HTTP upgrades and CONNECTs (where as the higher level `Client` and `Server` treat them as errors, since there's no exposed API to handle them yet). After a user sends a request wanting an upgrade, and gets a `101` response back, they could coordinate to get the original `io` back out of the `Connection`. There's a few parts of this that may be tricky. Details next. ## `SendRequest` - This has a `poll_ready` method, allowing you to know if the related `Connection` is still usable. - There is a `send_request(&mut self, req: Request<B>)` method, similar to `Client::request(req)`. **Questions:** - What should this be called? `SendRequest`? `Sender`? - What should the `send_request` method be called? `send_request`? `request`? `send`? - Should this type be `Clone`? ## `Connection` - The easiest thing is to just have `Connection::into_inner(self) -> Io`, however, servers can send the 101 upgrade response and the first part of the new protocol in the same packet. If they do that, the internal state will likely have those bytes in its read buffer. So, just calling `conn.into_inner()` would mean losing data. For that reason, I'm wondering if it is better to just remove this possible footgun. - The next thing that could be done is have `Connection::into_parts(self) -> Parts<Io>`. This is kind of like [http's into_parts](https://docs.rs/http/0.1.*/http/request/struct.Request.html#method.into_parts), which returns a struct with public fields, and a private one, allowing the possibility of adding new fields, while also allowing a user to take ownership of multiple things at once. ```rust pub struct Parts<T> { pub io: T, pub read_buf: Bytes, _non_exhaustive: (), } ``` - By default, the `impl Future for Connection` assumes it should manage the socket until completion, and then call `AsyncWrite::shutdown()`. However, if you're wanting to do an upgrade, you don't want `shutdown` to be called, but you do want to know when the `Connection` is otherwise "done" with HTTP. So, there probably needs to be another `poll_*` method to do that. **Questions:** - Should there be an `into_inner()` that could possibly lose data? - If you were to call `into_inner` or `into_parts` at some arbitrary time, even if there wasn't an upgrade, there could be unfinished state internally. Should it be an error to do that? Or should that extra state be available the `Parts` struct? - What should `Parts` be called? Is `Parts` too vague (`hyper::client::conn::Parts`)? I didn't want to say specifically `Upgrade`, since you might use it without an upgrade... - What buffer should be returned in `Parts`? It is internally a `BytesMut`, but we may not want to expose that directly. It's not hard to convert almost anything into a `Bytes`, so I started with that... - Should `Parts` include both the `read_buf` and `write_buf`? - What should the secondary `poll_` method be called, that resolves when HTTP is finished but without calling `shutdown`? `Connection::poll_upgrade()`? What should it return? Should it return an `Error` if the connection is closed without a successful upgrade? Or should that be an `Ok` result, just with an additional `enum`? ## Example Here's an example that I'm currently using in tests (with `await` inserted for terseness): ```rust use hyper::client::conn; // connect a tcpstream somehow, and then... let (mut tx, mut conn) = await conn::handshake(io)?; let until_upgrade = future::poll_fn(|| conn.poll_upgrade()); // using `http` crate let req = Request::builder() .uri(uri) .header("upgrade", "foobar") .header("connection", "upgrade") .body(Body::empty()) .unwrap(); let upgrade = tx.send_request(req) .map(|res| { assert_eq!(res.status(), StatusCode::SWITCHING_PROTOCOLS); assert_eq!(res.headers()["upgrade"], "foobar"); }); await upgrade.join(until_upgrade)?; let tcp = conn.into_parts().io; // use tcp over 'foobar' protocol ``` If we made `Parts` implement Read/Write that could be a decent way of handling upgrades in a non-footgunny way. You could manually grab the existing buffered data and stream out separately or just use the type itself as the stream for the upgraded protocol. > If we made Parts implement Read/Write That's a definite possibility!
2018-03-01T01:43:41Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,434
hyperium__hyper-1434
[ "1433" ]
8fb84d29a1c0ff848ff1c921f4c5bb7493939b97
diff --git /dev/null b/src/client/cancel.rs new file mode 100644 --- /dev/null +++ b/src/client/cancel.rs @@ -0,0 +1,148 @@ +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use futures::{Async, Future, Poll}; +use futures::task::{self, Task}; + +use common::Never; + +use self::lock::Lock; + +#[derive(Clone)] +pub struct Cancel { + inner: Arc<Inner>, +} + +pub struct Canceled { + inner: Arc<Inner>, +} + +struct Inner { + is_canceled: AtomicBool, + task: Lock<Option<Task>>, +} + +impl Cancel { + pub fn new() -> (Cancel, Canceled) { + let inner = Arc::new(Inner { + is_canceled: AtomicBool::new(false), + task: Lock::new(None), + }); + let inner2 = inner.clone(); + ( + Cancel { + inner: inner, + }, + Canceled { + inner: inner2, + }, + ) + } + + pub fn cancel(&self) { + if !self.inner.is_canceled.swap(true, Ordering::SeqCst) { + if let Some(mut locked) = self.inner.task.try_lock() { + if let Some(task) = locked.take() { + task.notify(); + } + } + // if we couldn't take the lock, Canceled was trying to park. + // After parking, it will check is_canceled one last time, + // so we can just stop here. + } + } + + pub fn is_canceled(&self) -> bool { + self.inner.is_canceled.load(Ordering::SeqCst) + } +} + +impl Future for Canceled { + type Item = (); + type Error = Never; + + fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + if self.inner.is_canceled.load(Ordering::SeqCst) { + Ok(Async::Ready(())) + } else { + if let Some(mut locked) = self.inner.task.try_lock() { + if locked.is_none() { + // it's possible a Cancel just tried to cancel on another thread, + // and we just missed it. Once we have the lock, we should check + // one more time before parking this task and going away. + if self.inner.is_canceled.load(Ordering::SeqCst) { + return Ok(Async::Ready(())); + } + *locked = Some(task::current()); + } + Ok(Async::NotReady) + } else { + // if we couldn't take the lock, then a Cancel taken has it. + // The *ONLY* reason is because it is in the process of canceling. + Ok(Async::Ready(())) + } + } + } +} + +impl Drop for Canceled { + fn drop(&mut self) { + self.inner.is_canceled.store(true, Ordering::SeqCst); + } +} + + +// a sub module just to protect unsafety +mod lock { + use std::cell::UnsafeCell; + use std::ops::{Deref, DerefMut}; + use std::sync::atomic::{AtomicBool, Ordering}; + + pub struct Lock<T> { + is_locked: AtomicBool, + value: UnsafeCell<T>, + } + + impl<T> Lock<T> { + pub fn new(val: T) -> Lock<T> { + Lock { + is_locked: AtomicBool::new(false), + value: UnsafeCell::new(val), + } + } + + pub fn try_lock(&self) -> Option<Locked<T>> { + if !self.is_locked.swap(true, Ordering::SeqCst) { + Some(Locked { lock: self }) + } else { + None + } + } + } + + unsafe impl<T: Send> Send for Lock<T> {} + unsafe impl<T: Send> Sync for Lock<T> {} + + pub struct Locked<'a, T: 'a> { + lock: &'a Lock<T>, + } + + impl<'a, T> Deref for Locked<'a, T> { + type Target = T; + fn deref(&self) -> &T { + unsafe { &*self.lock.value.get() } + } + } + + impl<'a, T> DerefMut for Locked<'a, T> { + fn deref_mut(&mut self) -> &mut T { + unsafe { &mut *self.lock.value.get() } + } + } + + impl<'a, T> Drop for Locked<'a, T> { + fn drop(&mut self) { + self.lock.is_locked.store(false, Ordering::SeqCst); + } + } +} diff --git /dev/null b/src/client/dispatch.rs new file mode 100644 --- /dev/null +++ b/src/client/dispatch.rs @@ -0,0 +1,73 @@ +use futures::{Async, Future, Poll, Stream}; +use futures::sync::{mpsc, oneshot}; + +use common::Never; +use super::cancel::{Cancel, Canceled}; + +pub type Callback<U> = oneshot::Sender<::Result<U>>; +pub type Promise<U> = oneshot::Receiver<::Result<U>>; + +pub fn channel<T, U>() -> (Sender<T, U>, Receiver<T, U>) { + let (tx, rx) = mpsc::unbounded(); + let (cancel, canceled) = Cancel::new(); + let tx = Sender { + cancel: cancel, + inner: tx, + }; + let rx = Receiver { + canceled: canceled, + inner: rx, + }; + (tx, rx) +} + +pub struct Sender<T, U> { + cancel: Cancel, + inner: mpsc::UnboundedSender<(T, Callback<U>)>, +} + +impl<T, U> Sender<T, U> { + pub fn is_closed(&self) -> bool { + self.cancel.is_canceled() + } + + pub fn cancel(&self) { + self.cancel.cancel(); + } + + pub fn send(&self, val: T) -> Result<Promise<U>, T> { + let (tx, rx) = oneshot::channel(); + self.inner.unbounded_send((val, tx)) + .map(move |_| rx) + .map_err(|e| e.into_inner().0) + } +} + +impl<T, U> Clone for Sender<T, U> { + fn clone(&self) -> Sender<T, U> { + Sender { + cancel: self.cancel.clone(), + inner: self.inner.clone(), + } + } +} + +pub struct Receiver<T, U> { + canceled: Canceled, + inner: mpsc::UnboundedReceiver<(T, Callback<U>)>, +} + +impl<T, U> Stream for Receiver<T, U> { + type Item = (T, Callback<U>); + type Error = Never; + + fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { + if let Async::Ready(()) = self.canceled.poll()? { + return Ok(Async::Ready(None)); + } + self.inner.poll() + .map_err(|()| unreachable!("mpsc never errors")) + } +} + +//TODO: Drop for Receiver should consume inner diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -1,14 +1,14 @@ //! HTTP Client -use std::cell::{Cell, RefCell}; +use std::cell::Cell; use std::fmt; use std::io; use std::marker::PhantomData; use std::rc::Rc; use std::time::Duration; -use futures::{Future, Poll, Stream}; -use futures::future::{self, Executor}; +use futures::{Async, Future, Poll, Stream}; +use futures::future::{self, Either, Executor}; #[cfg(feature = "compat")] use http; use tokio::reactor::Handle; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -28,7 +28,10 @@ pub use self::connect::{HttpConnector, Connect}; use self::background::{bg, Background}; +mod cancel; mod connect; +//TODO(easy): move cancel and dispatch into common instead +pub(crate) mod dispatch; mod dns; mod pool; #[cfg(feature = "compat")] diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -189,9 +192,6 @@ where C: Connect, head.headers.set_pos(0, host); } - use futures::Sink; - use futures::sync::{mpsc, oneshot}; - let checkout = self.pool.checkout(domain.as_ref()); let connect = { let executor = self.executor.clone(); diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -199,10 +199,9 @@ where C: Connect, let pool_key = Rc::new(domain.to_string()); self.connector.connect(url) .and_then(move |io| { - // 1 extra slot for possible Close message - let (tx, rx) = mpsc::channel(1); + let (tx, rx) = dispatch::channel(); let tx = HyperClient { - tx: RefCell::new(tx), + tx: tx, should_close: Cell::new(true), }; let pooled = pool.pooled(pool_key, tx); diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -225,33 +224,26 @@ where C: Connect, }); let resp = race.and_then(move |client| { - use proto::dispatch::ClientMsg; - - let (callback, rx) = oneshot::channel(); - client.should_close.set(false); - - match client.tx.borrow_mut().start_send(ClientMsg::Request(head, body, callback)) { - Ok(_) => (), - Err(e) => match e.into_inner() { - ClientMsg::Request(_, _, callback) => { - error!("pooled connection was not ready, this is a hyper bug"); - let err = io::Error::new( - io::ErrorKind::BrokenPipe, - "pool selected dead connection", - ); - let _ = callback.send(Err(::Error::Io(err))); - }, - _ => unreachable!("ClientMsg::Request was just sent"), + match client.tx.send((head, body)) { + Ok(rx) => { + client.should_close.set(false); + Either::A(rx.then(|res| { + match res { + Ok(Ok(res)) => Ok(res), + Ok(Err(err)) => Err(err), + Err(_) => panic!("dispatch dropped without returning error"), + } + })) + }, + Err(_) => { + error!("pooled connection was not ready, this is a hyper bug"); + let err = io::Error::new( + io::ErrorKind::BrokenPipe, + "pool selected dead connection", + ); + Either::B(future::err(::Error::Io(err))) } } - - rx.then(|res| { - match res { - Ok(Ok(res)) => Ok(res), - Ok(Err(err)) => Err(err), - Err(_) => panic!("dispatch dropped without returning error"), - } - }) }); FutureResponse(Box::new(resp)) diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -276,13 +268,8 @@ impl<C, B> fmt::Debug for Client<C, B> { } struct HyperClient<B> { - // A sentinel that is usually always true. If this is dropped - // while true, this will try to shutdown the dispatcher task. - // - // This should be set to false whenever it is checked out of the - // pool and successfully used to send a request. should_close: Cell<bool>, - tx: RefCell<::futures::sync::mpsc::Sender<proto::dispatch::ClientMsg<B>>>, + tx: dispatch::Sender<proto::dispatch::ClientMsg<B>, ::Response>, } impl<B> Clone for HyperClient<B> { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -296,10 +283,11 @@ impl<B> Clone for HyperClient<B> { impl<B> self::pool::Ready for HyperClient<B> { fn poll_ready(&mut self) -> Poll<(), ()> { - self.tx - .borrow_mut() - .poll_ready() - .map_err(|_| ()) + if self.tx.is_closed() { + Err(()) + } else { + Ok(Async::Ready(())) + } } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -307,7 +295,7 @@ impl<B> Drop for HyperClient<B> { fn drop(&mut self) { if self.should_close.get() { self.should_close.set(false); - let _ = self.tx.borrow_mut().try_send(proto::dispatch::ClientMsg::Close); + self.tx.cancel(); } } } diff --git a/src/common/mod.rs b/src/common/mod.rs --- a/src/common/mod.rs +++ b/src/common/mod.rs @@ -1,3 +1,5 @@ pub use self::str::ByteStr; mod str; + +pub enum Never {} diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -1,7 +1,7 @@ use std::io; use futures::{Async, AsyncSink, Future, Poll, Stream}; -use futures::sync::{mpsc, oneshot}; +use futures::sync::oneshot; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_service::Service; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -36,12 +36,9 @@ pub struct Client<B> { rx: ClientRx<B>, } -pub enum ClientMsg<B> { - Request(RequestHead, Option<B>, oneshot::Sender<::Result<::Response>>), - Close, -} +pub type ClientMsg<B> = (RequestHead, Option<B>); -type ClientRx<B> = mpsc::Receiver<ClientMsg<B>>; +type ClientRx<B> = ::client::dispatch::Receiver<ClientMsg<B>, ::Response>; impl<D, Bs, I, B, T, K> Dispatcher<D, Bs, I, B, T, K> where diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -365,7 +362,7 @@ where fn poll_msg(&mut self) -> Poll<Option<(Self::PollItem, Option<Self::PollBody>)>, ::Error> { match self.rx.poll() { - Ok(Async::Ready(Some(ClientMsg::Request(head, body, mut cb)))) => { + Ok(Async::Ready(Some(((head, body), mut cb)))) => { // check that future hasn't been canceled already match cb.poll_cancel().expect("poll_cancel cannot error") { Async::Ready(()) => { diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -378,14 +375,13 @@ where } } }, - Ok(Async::Ready(Some(ClientMsg::Close))) | Ok(Async::Ready(None)) => { trace!("client tx closed"); // user has dropped sender handle Ok(Async::Ready(None)) }, Ok(Async::NotReady) => return Ok(Async::NotReady), - Err(()) => unreachable!("mpsc receiver cannot error"), + Err(_) => unreachable!("receiver cannot error"), } } diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -404,7 +400,7 @@ where if let Some(cb) = self.callback.take() { let _ = cb.send(Err(err)); Ok(()) - } else if let Ok(Async::Ready(Some(ClientMsg::Request(_, _, cb)))) = self.rx.poll() { + } else if let Ok(Async::Ready(Some((_, cb)))) = self.rx.poll() { let _ = cb.send(Err(err)); Ok(()) } else {
diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -435,8 +431,6 @@ where #[cfg(test)] mod tests { - use futures::Sink; - use super::*; use mock::AsyncIo; use proto::ClientTransaction; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -447,7 +441,7 @@ mod tests { let _ = pretty_env_logger::try_init(); ::futures::lazy(|| { let io = AsyncIo::new_buf(b"HTTP/1.1 200 OK\r\n\r\n".to_vec(), 100); - let (mut tx, rx) = mpsc::channel(0); + let (tx, rx) = ::client::dispatch::channel(); let conn = Conn::<_, ::Chunk, ClientTransaction>::new(io, Default::default()); let mut dispatcher = Dispatcher::new(Client::new(rx), conn); diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -456,8 +450,7 @@ mod tests { subject: ::proto::RequestLine::default(), headers: Default::default(), }; - let (res_tx, res_rx) = oneshot::channel(); - tx.start_send(ClientMsg::Request(req, None::<::Body>, res_tx)).unwrap(); + let res_rx = tx.send((req, None::<::Body>)).unwrap(); dispatcher.poll().expect("dispatcher poll 1"); dispatcher.poll().expect("dispatcher poll 2");
Connection pool returns connections which are not ready I am running a high number of concurrent requests (~1000) to the AWS Kinesis service and I am getting an error log from the hyper connection pool: ``` root@doit-1800981089-sz6zt:~/kinesis-hyper-bug# cargo build --release && RUST_LOG=error RUST_BACKTRACE=full ./target/release/kinesis-hyper-bug Finished release [optimized + debuginfo] target(s) in 0.0 secs ERROR 2018-01-31T17:10:32Z: hyper::client: pooled connection was not ready, this is a hyper bug ERROR 2018-01-31T17:11:49Z: hyper::client: pooled connection was not ready, this is a hyper bug ERROR 2018-01-31T17:15:16Z: hyper::client: pooled connection was not ready, this is a hyper bug ERROR 2018-01-31T17:15:58Z: hyper::client: pooled connection was not ready, this is a hyper bug ERROR 2018-01-31T17:16:00Z: hyper::client: pooled connection was not ready, this is a hyper bug ```
2018-02-03T00:03:56Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,390
hyperium__hyper-1390
[ "1365" ]
cecef9d402b76af12e6415519deb2b604f77b195
diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -453,6 +453,14 @@ where I: AsyncRead + AsyncWrite, pub fn close_write(&mut self) { self.state.close_write(); } + + pub fn disable_keep_alive(&mut self) { + if self.state.is_idle() { + self.state.close_read(); + } else { + self.state.disable_keep_alive(); + } + } } // ==== tokio_proto impl ==== diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -700,6 +708,10 @@ impl<B, K: KeepAlive> State<B, K> { } } + fn disable_keep_alive(&mut self) { + self.keep_alive.disable() + } + fn busy(&mut self) { if let KA::Disabled = self.keep_alive.status() { return; diff --git a/src/proto/dispatch.rs b/src/proto/dispatch.rs --- a/src/proto/dispatch.rs +++ b/src/proto/dispatch.rs @@ -54,6 +54,10 @@ where } } + pub fn disable_keep_alive(&mut self) { + self.conn.disable_keep_alive() + } + fn poll_read(&mut self) -> Poll<(), ::Error> { loop { if self.conn.can_read_head() { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -536,6 +536,18 @@ where } } +impl<I, B, S> Connection<I, S> +where S: Service<Request = Request, Response = Response<B>, Error = ::Error> + 'static, + I: AsyncRead + AsyncWrite + 'static, + B: Stream<Error=::Error> + 'static, + B::Item: AsRef<[u8]>, +{ + /// Disables keep-alive for this connection. + pub fn disable_keep_alive(&mut self) { + self.conn.disable_keep_alive() + } +} + mod unnameable { // This type is specifically not exported outside the crate, // so no one can actually name the type. With no methods, we make no
diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -869,7 +881,7 @@ mod tests { other => panic!("unexpected frame: {:?}", other) } - // client + // client let io = AsyncIo::new_buf(vec![], 1); let mut conn = Conn::<_, proto::Chunk, ClientTransaction>::new(io, Default::default()); conn.state.busy(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -6,7 +6,7 @@ extern crate pretty_env_logger; extern crate tokio_core; use futures::{Future, Stream}; -use futures::future::{self, FutureResult}; +use futures::future::{self, FutureResult, Either}; use futures::sync::oneshot; use tokio_core::net::TcpListener; diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -551,6 +551,106 @@ fn pipeline_enabled() { assert_eq!(n, 0); } +#[test] +fn disable_keep_alive_mid_request() { + let mut core = Core::new().unwrap(); + let listener = TcpListener::bind(&"127.0.0.1:0".parse().unwrap(), &core.handle()).unwrap(); + let addr = listener.local_addr().unwrap(); + + let (tx1, rx1) = oneshot::channel(); + let (tx2, rx2) = oneshot::channel(); + + let child = thread::spawn(move || { + let mut req = connect(&addr); + req.write_all(b"GET / HTTP/1.1\r\n").unwrap(); + tx1.send(()).unwrap(); + rx2.wait().unwrap(); + req.write_all(b"Host: localhost\r\n\r\n").unwrap(); + let mut buf = vec![]; + req.read_to_end(&mut buf).unwrap(); + }); + + let fut = listener.incoming() + .into_future() + .map_err(|_| unreachable!()) + .and_then(|(item, _incoming)| { + let (socket, _) = item.unwrap(); + Http::<hyper::Chunk>::new().serve_connection(socket, HelloWorld) + .select2(rx1) + .then(|r| { + match r { + Ok(Either::A(_)) => panic!("expected rx first"), + Ok(Either::B(((), mut conn))) => { + conn.disable_keep_alive(); + tx2.send(()).unwrap(); + conn + } + Err(Either::A((e, _))) => panic!("unexpected error {}", e), + Err(Either::B((e, _))) => panic!("unexpected error {}", e), + } + }) + }); + + core.run(fut).unwrap(); + child.join().unwrap(); +} + +#[test] +fn disable_keep_alive_post_request() { + let mut core = Core::new().unwrap(); + let listener = TcpListener::bind(&"127.0.0.1:0".parse().unwrap(), &core.handle()).unwrap(); + let addr = listener.local_addr().unwrap(); + + let (tx1, rx1) = oneshot::channel(); + + let child = thread::spawn(move || { + let mut req = connect(&addr); + req.write_all(b"\ + GET / HTTP/1.1\r\n\ + Host: localhost\r\n\ + \r\n\ + ").unwrap(); + + let mut buf = [0; 1024 * 8]; + loop { + let n = req.read(&mut buf).expect("reading 1"); + if n < buf.len() { + if &buf[n - HELLO.len()..n] == HELLO.as_bytes() { + break; + } + } + } + + tx1.send(()).unwrap(); + + let nread = req.read(&mut buf).unwrap(); + assert_eq!(nread, 0); + }); + + let fut = listener.incoming() + .into_future() + .map_err(|_| unreachable!()) + .and_then(|(item, _incoming)| { + let (socket, _) = item.unwrap(); + Http::<hyper::Chunk>::new().serve_connection(socket, HelloWorld) + .select2(rx1) + .then(|r| { + match r { + Ok(Either::A(_)) => panic!("expected rx first"), + Ok(Either::B(((), mut conn))) => { + conn.disable_keep_alive(); + conn + } + Err(Either::A((e, _))) => panic!("unexpected error {}", e), + Err(Either::B((e, _))) => panic!("unexpected error {}", e), + } + }) + }); + + core.run(fut).unwrap(); + child.join().unwrap(); +} + #[test] fn no_proto_empty_parse_eof_does_not_return_error() { let mut core = Core::new().unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -719,6 +819,8 @@ impl Service for TestService { } +const HELLO: &'static str = "hello"; + struct HelloWorld; impl Service for HelloWorld { diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -728,7 +830,10 @@ impl Service for HelloWorld { type Future = FutureResult<Self::Response, Self::Error>; fn call(&self, _req: Request) -> Self::Future { - future::ok(Response::new()) + let mut response = Response::new(); + response.headers_mut().set(hyper::header::ContentLength(HELLO.len() as u64)); + response.set_body(HELLO); + future::ok(response) } }
Make graceful shutdown work at request rather than connection granularity The graceful shutdown logic currently waits until all `Service`s have dropped (i.e. all connections have closed). However, with keep-alive this is overconservative - what we'd really like is to wait until pending requests have finished. This can't be correctly modeled with the current API, however. The last point in a request/response pair that user code is aware of is when it sends the last bit of the response body through the body channel. It will still take some amount of time for that bit to be written out over the network, so we can't immediately shut down after that's done.
@seanmonstar pointed out that a simple way of doing this is to add a method to disable keep-alive on Connections. Then, `Service::drop`-based tracking will be accurate.
2017-11-29T07:06:16Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,387
hyperium__hyper-1387
[ "1383" ]
e4864a2bea59b40fb07e6d18329f75817803a3f3
diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -200,10 +200,13 @@ impl<T: Clone> KeepAlive for Pooled<T> { }; if pool.is_enabled() { pool.put(self.key.clone(), self.entry.clone()); + } else { + trace!("keepalive disabled, dropping pooled ({:?})", self.key); + self.disable(); } } else { trace!("pool dropped, dropping pooled ({:?})", self.key); - self.entry.status.set(TimedKA::Disabled); + self.disable(); } }
diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -654,6 +654,46 @@ mod dispatch_impl { } + #[test] + fn no_keep_alive_closes_connection() { + // https://github.com/hyperium/hyper/issues/1383 + let _ = pretty_env_logger::init(); + + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = server.local_addr().unwrap(); + let mut core = Core::new().unwrap(); + let handle = core.handle(); + let closes = Arc::new(AtomicUsize::new(0)); + + let (tx1, rx1) = oneshot::channel(); + + thread::spawn(move || { + let mut sock = server.accept().unwrap().0; + sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut buf = [0; 4096]; + sock.read(&mut buf).expect("read 1"); + sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap(); + let _ = tx1.send(()); + }); + + let uri = format!("http://{}/a", addr).parse().unwrap(); + + let client = Client::configure() + .connector(DebugConnector(HttpConnector::new(1, &handle), closes.clone())) + .no_proto() + .keep_alive(false) + .build(&handle); + let res = client.get(uri).and_then(move |res| { + assert_eq!(res.status(), hyper::StatusCode::Ok); + res.body().concat2() + }); + let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + core.run(res.join(rx).map(|r| r.0)).unwrap(); + + assert_eq!(closes.load(Ordering::Relaxed), 1); + } + struct DebugConnector(HttpConnector, Arc<AtomicUsize>);
All client connections are leaked when keep_alive(false) ```rust extern crate hyper; extern crate tokio_core; extern crate tokio_io; extern crate futures; extern crate env_logger; use tokio_core::reactor::{Core, Timeout}; use tokio_core::net::TcpStream; use tokio_io::{AsyncRead, AsyncWrite}; use hyper::{Client, Uri}; use hyper::client::HttpConnector; use hyper::server::Service; use std::time::Duration; use std::cell::Cell; use futures::{Future, Stream, stream}; use std::io::{self, Read, Write}; fn main() { env_logger::init().unwrap(); let mut core = Core::new().unwrap(); let handle = core.handle(); let client = Client::configure() .connector(DebugConnector(HttpConnector::new(1, &handle), Cell::new(0))) .no_proto() .keep_alive(false) .build(&handle); let fut = stream::repeat(()).for_each(|()| { client.get("http://www.google.com".parse().unwrap()) .and_then(|resp| { resp.body().collect() }) .and_then(|_| { let timeout = Timeout::new(Duration::from_secs(1), &handle).unwrap(); timeout.map_err(|e| e.into()) }) .map_err(|e| println!("error {}", e)) }); core.run(fut).unwrap(); } struct DebugConnector(HttpConnector, Cell<u32>); impl Service for DebugConnector { type Request = Uri; type Response = DebugStream; type Error = io::Error; type Future = Box<Future<Item = DebugStream, Error = io::Error>>; fn call(&self, uri: Uri) -> Self::Future { let id = self.1.get(); self.1.set(id + 1); println!("new connection {}", id); Box::new(self.0.call(uri).map(move |s| DebugStream(s, id))) } } struct DebugStream(TcpStream, u32); impl Drop for DebugStream { fn drop(&mut self) { println!("socket {} dropping", self.1); } } impl Write for DebugStream { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } fn flush(&mut self) -> io::Result<()> { self.0.flush() } } impl AsyncWrite for DebugStream { fn shutdown(&mut self) -> futures::Poll<(), io::Error> { AsyncWrite::shutdown(&mut self.0) } } impl Read for DebugStream { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } } impl AsyncRead for DebugStream {} ``` ``` ~/foo ❯ cargo run [foo/master +%] Compiling foo v0.1.0 (file:///Users/sfackler/foo) Finished dev [unoptimized + debuginfo] target(s) in 5.28 secs Running `target/debug/foo` new connection 0 new connection 1 new connection 2 new connection 3 new connection 4 new connection 5 new connection 6 new connection 7 new connection 8 new connection 9 new connection 10 new connection 11 new connection 12 new connection 13 new connection 14 ... ``` This happens both with and without no_proto
2017-11-28T05:44:01Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,362
hyperium__hyper-1362
[ "1353" ]
8153cfaebf65779c279dc089767dece508d3359c
diff --git a/.travis.yml b/.travis.yml --- a/.travis.yml +++ b/.travis.yml @@ -8,6 +8,8 @@ matrix: env: FEATURES="--features nightly" - rust: beta - rust: stable + - rust: stable + env: HYPER_NO_PROTO=1 - rust: stable env: FEATURES="--features compat" - rust: 1.17.0 diff --git a/examples/client.rs b/examples/client.rs --- a/examples/client.rs +++ b/examples/client.rs @@ -1,4 +1,4 @@ -#![deny(warnings)] +//#![deny(warnings)] extern crate futures; extern crate hyper; extern crate tokio_core; diff --git a/examples/client.rs b/examples/client.rs --- a/examples/client.rs +++ b/examples/client.rs @@ -32,7 +32,9 @@ fn main() { let mut core = tokio_core::reactor::Core::new().unwrap(); let handle = core.handle(); - let client = Client::new(&handle); + let client = Client::configure() + .no_proto() + .build(&handle); let work = client.get(url).and_then(|res| { println!("Response: {}", res.status()); diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -31,7 +31,8 @@ impl Service for Hello { fn main() { pretty_env_logger::init().unwrap(); let addr = "127.0.0.1:3000".parse().unwrap(); - let server = Http::new().bind(&addr, || Ok(Hello)).unwrap(); + let mut server = Http::new().bind(&addr, || Ok(Hello)).unwrap(); + server.no_proto(); println!("Listening on http://{} with 1 thread.", server.local_addr().unwrap()); server.run().unwrap(); } diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -47,7 +47,8 @@ fn main() { pretty_env_logger::init().unwrap(); let addr = "127.0.0.1:1337".parse().unwrap(); - let server = Http::new().bind(&addr, || Ok(Echo)).unwrap(); + let mut server = Http::new().bind(&addr, || Ok(Echo)).unwrap(); + server.no_proto(); println!("Listening on http://{} with 1 thread.", server.local_addr().unwrap()); server.run().unwrap(); } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -20,7 +20,7 @@ use tokio_proto::util::client_proxy::ClientProxy; pub use tokio_service::Service; use header::{Headers, Host}; -use proto::{self, TokioBody}; +use proto::{self, RequestHead, TokioBody}; use proto::response; use proto::request; use method::Method; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -45,7 +45,7 @@ pub mod compat; pub struct Client<C, B = proto::Body> { connector: C, handle: Handle, - pool: Pool<TokioClient<B>>, + pool: Dispatch<B>, } impl Client<HttpConnector, proto::Body> { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -93,7 +93,11 @@ impl<C, B> Client<C, B> { Client { connector: config.connector, handle: handle.clone(), - pool: Pool::new(config.keep_alive, config.keep_alive_timeout), + pool: if config.no_proto { + Dispatch::Hyper(Pool::new(config.keep_alive, config.keep_alive_timeout)) + } else { + Dispatch::Proto(Pool::new(config.keep_alive, config.keep_alive_timeout)) + } } } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -187,48 +191,100 @@ where C: Connect, headers.extend(head.headers.iter()); head.headers = headers; - let checkout = self.pool.checkout(domain.as_ref()); - let connect = { - let handle = self.handle.clone(); - let pool = self.pool.clone(); - let pool_key = Rc::new(domain.to_string()); - self.connector.connect(url) - .map(move |io| { - let (tx, rx) = oneshot::channel(); - let client = HttpClient { - client_rx: RefCell::new(Some(rx)), - }.bind_client(&handle, io); - let pooled = pool.pooled(pool_key, client); - drop(tx.send(pooled.clone())); - pooled - }) - }; + match self.pool { + Dispatch::Proto(ref pool) => { + trace!("proto_dispatch"); + let checkout = pool.checkout(domain.as_ref()); + let connect = { + let handle = self.handle.clone(); + let pool = pool.clone(); + let pool_key = Rc::new(domain.to_string()); + self.connector.connect(url) + .map(move |io| { + let (tx, rx) = oneshot::channel(); + let client = HttpClient { + client_rx: RefCell::new(Some(rx)), + }.bind_client(&handle, io); + let pooled = pool.pooled(pool_key, client); + drop(tx.send(pooled.clone())); + pooled + }) + }; + + let race = checkout.select(connect) + .map(|(client, _work)| client) + .map_err(|(e, _work)| { + // the Pool Checkout cannot error, so the only error + // is from the Connector + // XXX: should wait on the Checkout? Problem is + // that if the connector is failing, it may be that we + // never had a pooled stream at all + e.into() + }); + let resp = race.and_then(move |client| { + let msg = match body { + Some(body) => { + Message::WithBody(head, body.into()) + }, + None => Message::WithoutBody(head), + }; + client.call(msg) + }); + FutureResponse(Box::new(resp.map(|msg| { + match msg { + Message::WithoutBody(head) => response::from_wire(head, None), + Message::WithBody(head, body) => response::from_wire(head, Some(body.into())), + } + }))) + }, + Dispatch::Hyper(ref pool) => { + trace!("no_proto dispatch"); + use futures::Sink; + use futures::sync::{mpsc, oneshot}; + + let checkout = pool.checkout(domain.as_ref()); + let connect = { + let handle = self.handle.clone(); + let pool = pool.clone(); + let pool_key = Rc::new(domain.to_string()); + self.connector.connect(url) + .map(move |io| { + let (tx, rx) = mpsc::channel(1); + let pooled = pool.pooled(pool_key, RefCell::new(tx)); + let conn = proto::Conn::<_, _, proto::ClientTransaction, _>::new(io, pooled.clone()); + let dispatch = proto::dispatch::Dispatcher::new(proto::dispatch::Client::new(rx), conn); + handle.spawn(dispatch.map_err(|err| error!("no_proto error: {}", err))); + pooled + }) + }; + + let race = checkout.select(connect) + .map(|(client, _work)| client) + .map_err(|(e, _work)| { + // the Pool Checkout cannot error, so the only error + // is from the Connector + // XXX: should wait on the Checkout? Problem is + // that if the connector is failing, it may be that we + // never had a pooled stream at all + e.into() + }); + + let resp = race.and_then(move |client| { + let (callback, rx) = oneshot::channel(); + client.borrow_mut().start_send((head, body, callback)).unwrap(); + rx.then(|res| { + match res { + Ok(Ok(res)) => Ok(res), + Ok(Err(err)) => Err(err), + Err(_) => panic!("dispatch dropped without returning error"), + } + }) + }); + + FutureResponse(Box::new(resp)) - let race = checkout.select(connect) - .map(|(client, _work)| client) - .map_err(|(e, _work)| { - // the Pool Checkout cannot error, so the only error - // is from the Connector - // XXX: should wait on the Checkout? Problem is - // that if the connector is failing, it may be that we - // never had a pooled stream at all - e.into() - }); - let resp = race.and_then(move |client| { - let msg = match body { - Some(body) => { - Message::WithBody(head, body.into()) - }, - None => Message::WithoutBody(head), - }; - client.call(msg) - }); - FutureResponse(Box::new(resp.map(|msg| { - match msg { - Message::WithoutBody(head) => response::from_wire(head, None), - Message::WithBody(head, body) => response::from_wire(head, Some(body.into())), } - }))) + } } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -238,7 +294,10 @@ impl<C: Clone, B> Clone for Client<C, B> { Client { connector: self.connector.clone(), handle: self.handle.clone(), - pool: self.pool.clone(), + pool: match self.pool { + Dispatch::Proto(ref pool) => Dispatch::Proto(pool.clone()), + Dispatch::Hyper(ref pool) => Dispatch::Hyper(pool.clone()), + } } } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -249,10 +308,16 @@ impl<C, B> fmt::Debug for Client<C, B> { } } -type TokioClient<B> = ClientProxy<Message<proto::RequestHead, B>, Message<proto::ResponseHead, TokioBody>, ::Error>; +type ProtoClient<B> = ClientProxy<Message<RequestHead, B>, Message<proto::ResponseHead, TokioBody>, ::Error>; +type HyperClient<B> = RefCell<::futures::sync::mpsc::Sender<(RequestHead, Option<B>, ::futures::sync::oneshot::Sender<::Result<::Response>>)>>; + +enum Dispatch<B> { + Proto(Pool<ProtoClient<B>>), + Hyper(Pool<HyperClient<B>>), +} struct HttpClient<B> { - client_rx: RefCell<Option<oneshot::Receiver<Pooled<TokioClient<B>>>>>, + client_rx: RefCell<Option<oneshot::Receiver<Pooled<ProtoClient<B>>>>>, } impl<T, B> ClientProto<T> for HttpClient<B> diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -265,7 +330,7 @@ where T: AsyncRead + AsyncWrite + 'static, type Response = proto::ResponseHead; type ResponseBody = proto::Chunk; type Error = ::Error; - type Transport = proto::Conn<T, B::Item, proto::ClientTransaction, Pooled<TokioClient<B>>>; + type Transport = proto::Conn<T, B::Item, proto::ClientTransaction, Pooled<ProtoClient<B>>>; type BindTransport = BindingClient<T, B>; fn bind_transport(&self, io: T) -> Self::BindTransport { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -277,7 +342,7 @@ where T: AsyncRead + AsyncWrite + 'static, } struct BindingClient<T, B> { - rx: oneshot::Receiver<Pooled<TokioClient<B>>>, + rx: oneshot::Receiver<Pooled<ProtoClient<B>>>, io: Option<T>, } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -286,7 +351,7 @@ where T: AsyncRead + AsyncWrite + 'static, B: Stream<Error=::Error>, B::Item: AsRef<[u8]>, { - type Item = proto::Conn<T, B::Item, proto::ClientTransaction, Pooled<TokioClient<B>>>; + type Item = proto::Conn<T, B::Item, proto::ClientTransaction, Pooled<ProtoClient<B>>>; type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -309,6 +374,7 @@ pub struct Config<C, B> { keep_alive_timeout: Option<Duration>, //TODO: make use of max_idle config max_idle: usize, + no_proto: bool, } /// Phantom type used to signal that `Config` should create a `HttpConnector`. diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -324,6 +390,7 @@ impl Default for Config<UseDefaultConnector, proto::Body> { keep_alive: true, keep_alive_timeout: Some(Duration::from_secs(90)), max_idle: 5, + no_proto: false, } } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -347,6 +414,7 @@ impl<C, B> Config<C, B> { keep_alive: self.keep_alive, keep_alive_timeout: self.keep_alive_timeout, max_idle: self.max_idle, + no_proto: self.no_proto, } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -360,6 +428,7 @@ impl<C, B> Config<C, B> { keep_alive: self.keep_alive, keep_alive_timeout: self.keep_alive_timeout, max_idle: self.max_idle, + no_proto: self.no_proto, } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -393,6 +462,13 @@ impl<C, B> Config<C, B> { self } */ + + /// Disable tokio-proto internal usage. + #[inline] + pub fn no_proto(mut self) -> Config<C, B> { + self.no_proto = true; + self + } } impl<C, B> Config<C, B> diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -431,11 +507,8 @@ impl<C, B> fmt::Debug for Config<C, B> { impl<C: Clone, B> Clone for Config<C, B> { fn clone(&self) -> Config<C, B> { Config { - _body_type: PhantomData::<B>, connector: self.connector.clone(), - keep_alive: self.keep_alive, - keep_alive_timeout: self.keep_alive_timeout, - max_idle: self.max_idle, + .. *self } } } diff --git a/src/proto/body.rs b/src/proto/body.rs --- a/src/proto/body.rs +++ b/src/proto/body.rs @@ -7,6 +7,7 @@ use std::borrow::Cow; use super::Chunk; pub type TokioBody = tokio_proto::streaming::Body<Chunk, ::Error>; +pub type BodySender = mpsc::Sender<Result<Chunk, ::Error>>; /// A `Stream` for `Chunk`s used in requests and responses. #[must_use = "streams do nothing unless polled"] diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -7,7 +7,7 @@ use futures::task::Task; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_proto::streaming::pipeline::{Frame, Transport}; -use proto::{Http1Transaction}; +use proto::Http1Transaction; use super::io::{Cursor, Buffered}; use super::h1::{Encoder, Decoder}; use method::Method; diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -51,15 +51,28 @@ where I: AsyncRead + AsyncWrite, self.io.set_flush_pipeline(enabled); } - fn poll2(&mut self) -> Poll<Option<Frame<super::MessageHead<T::Incoming>, super::Chunk, ::Error>>, io::Error> { - trace!("Conn::poll()"); + fn poll_incoming(&mut self) -> Poll<Option<Frame<super::MessageHead<T::Incoming>, super::Chunk, ::Error>>, io::Error> { + trace!("Conn::poll_incoming()"); loop { if self.is_read_closed() { trace!("Conn::poll when closed"); return Ok(Async::Ready(None)); } else if self.can_read_head() { - return self.read_head(); + return match self.read_head() { + Ok(Async::Ready(Some((head, body)))) => { + Ok(Async::Ready(Some(Frame::Message { + message: head, + body: body, + }))) + }, + Ok(Async::Ready(None)) => Ok(Async::Ready(None)), + Ok(Async::NotReady) => Ok(Async::NotReady), + Err(::Error::Io(err)) => Err(err), + Err(err) => Ok(Async::Ready(Some(Frame::Error { + error: err, + }))), + }; } else if self.can_write_continue() { try_nb!(self.flush()); } else if self.can_read_body() { diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -79,18 +92,26 @@ where I: AsyncRead + AsyncWrite, } } - fn is_read_closed(&self) -> bool { + pub fn is_read_closed(&self) -> bool { self.state.is_read_closed() } - #[allow(unused)] - fn is_write_closed(&self) -> bool { + pub fn is_write_closed(&self) -> bool { self.state.is_write_closed() } - fn can_read_head(&self) -> bool { + pub fn can_read_head(&self) -> bool { match self.state.reading { - Reading::Init => true, + Reading::Init => { + if T::should_read_first() { + true + } else { + match self.state.writing { + Writing::Init => false, + _ => true, + } + } + } _ => false, } } diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -102,14 +123,14 @@ where I: AsyncRead + AsyncWrite, } } - fn can_read_body(&self) -> bool { + pub fn can_read_body(&self) -> bool { match self.state.reading { Reading::Body(..) => true, _ => false, } } - fn read_head(&mut self) -> Poll<Option<Frame<super::MessageHead<T::Incoming>, super::Chunk, ::Error>>, io::Error> { + pub fn read_head(&mut self) -> Poll<Option<(super::MessageHead<T::Incoming>, bool)>, ::Error> { debug_assert!(self.can_read_head()); trace!("Conn::read_head"); diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -117,13 +138,16 @@ where I: AsyncRead + AsyncWrite, Ok(Async::Ready(head)) => (head.version, head), Ok(Async::NotReady) => return Ok(Async::NotReady), Err(e) => { - let must_respond_with_error = !self.state.is_idle(); + // If we are currently waiting on a message, then an empty + // message should be reported as an error. If not, it is just + // the connection closing gracefully. + let must_error = !self.state.is_idle() && T::should_error_on_parse_eof(); self.state.close_read(); self.io.consume_leading_lines(); let was_mid_parse = !self.io.read_buf().is_empty(); - return if was_mid_parse || must_respond_with_error { + return if was_mid_parse || must_error { debug!("parse error ({}) with {} bytes", e, self.io.read_buf().len()); - Ok(Async::Ready(Some(Frame::Error { error: e }))) + Err(e) } else { debug!("read eof"); Ok(Async::Ready(None)) diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -138,7 +162,7 @@ where I: AsyncRead + AsyncWrite, Err(e) => { debug!("decoder error = {:?}", e); self.state.close_read(); - return Ok(Async::Ready(Some(Frame::Error { error: e }))); + return Err(e); } }; self.state.busy(); diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -154,17 +178,17 @@ where I: AsyncRead + AsyncWrite, (true, Reading::Body(decoder)) }; self.state.reading = reading; - Ok(Async::Ready(Some(Frame::Message { message: head, body: body }))) + Ok(Async::Ready(Some((head, body)))) }, _ => { error!("unimplemented HTTP Version = {:?}", version); self.state.close_read(); - Ok(Async::Ready(Some(Frame::Error { error: ::Error::Version }))) + Err(::Error::Version) } } } - fn read_body(&mut self) -> Poll<Option<super::Chunk>, io::Error> { + pub fn read_body(&mut self) -> Poll<Option<super::Chunk>, io::Error> { debug_assert!(self.can_read_body()); trace!("Conn::read_body"); diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -187,7 +211,7 @@ where I: AsyncRead + AsyncWrite, ret } - fn maybe_park_read(&mut self) { + pub fn maybe_park_read(&mut self) { if !self.io.is_read_blocked() { // the Io object is ready to read, which means it will never alert // us that it is ready until we drain it. However, we're currently diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -236,13 +260,16 @@ where I: AsyncRead + AsyncWrite, return }, Err(e) => { - trace!("maybe_notify read_from_io error: {}", e); + trace!("maybe_notify; read_from_io error: {}", e); self.state.close(); } } } if let Some(ref task) = self.state.read_task { + trace!("maybe_notify; notifying task"); task.notify(); + } else { + trace!("maybe_notify; no task to notify"); } } } diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -252,14 +279,14 @@ where I: AsyncRead + AsyncWrite, self.maybe_notify(); } - fn can_write_head(&self) -> bool { + pub fn can_write_head(&self) -> bool { match self.state.writing { Writing::Continue(..) | Writing::Init => true, _ => false } } - fn can_write_body(&self) -> bool { + pub fn can_write_body(&self) -> bool { match self.state.writing { Writing::Body(..) => true, Writing::Continue(..) | diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -277,7 +304,7 @@ where I: AsyncRead + AsyncWrite, } } - fn write_head(&mut self, head: super::MessageHead<T::Outgoing>, body: bool) { + pub fn write_head(&mut self, head: super::MessageHead<T::Outgoing>, body: bool) { debug_assert!(self.can_write_head()); let wants_keep_alive = head.should_keep_alive(); diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -298,7 +325,7 @@ where I: AsyncRead + AsyncWrite, }; } - fn write_body(&mut self, chunk: Option<B>) -> StartSend<Option<B>, io::Error> { + pub fn write_body(&mut self, chunk: Option<B>) -> StartSend<Option<B>, io::Error> { debug_assert!(self.can_write_body()); if self.has_queued_body() { diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -397,7 +424,7 @@ where I: AsyncRead + AsyncWrite, Ok(Async::Ready(())) } - fn flush(&mut self) -> Poll<(), io::Error> { + pub fn flush(&mut self) -> Poll<(), io::Error> { loop { let queue_finished = try!(self.write_queued()).is_ready(); try_nb!(self.io.flush()); diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -410,8 +437,18 @@ where I: AsyncRead + AsyncWrite, Ok(Async::Ready(())) } + + pub fn close_read(&mut self) { + self.state.close_read(); + } + + pub fn close_write(&mut self) { + self.state.close_write(); + } } +// ==== tokio_proto impl ==== + impl<I, B, T, K> Stream for Conn<I, B, T, K> where I: AsyncRead + AsyncWrite, B: AsRef<[u8]>, diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -423,7 +460,7 @@ where I: AsyncRead + AsyncWrite, #[inline] fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { - self.poll2().map_err(|err| { + self.poll_incoming().map_err(|err| { debug!("poll error: {}", err); err }) diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -635,6 +672,12 @@ impl<B, K: KeepAlive> State<B, K> { self.keep_alive.disable(); } + fn close_write(&mut self) { + trace!("State::close_write()"); + self.writing = Writing::Closed; + self.keep_alive.disable(); + } + fn try_keep_alive(&mut self) { match (&self.reading, &self.writing) { (&Reading::KeepAlive, &Writing::KeepAlive) => { diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -652,14 +695,6 @@ impl<B, K: KeepAlive> State<B, K> { } } - fn is_idle(&self) -> bool { - if let KA::Idle = self.keep_alive.status() { - true - } else { - false - } - } - fn busy(&mut self) { if let KA::Disabled = self.keep_alive.status() { return; diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -674,6 +709,14 @@ impl<B, K: KeepAlive> State<B, K> { self.keep_alive.idle(); } + fn is_idle(&self) -> bool { + if let KA::Idle = self.keep_alive.status() { + true + } else { + false + } + } + fn is_read_closed(&self) -> bool { match self.reading { Reading::Closed => true, diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -681,7 +724,6 @@ impl<B, K: KeepAlive> State<B, K> { } } - #[allow(unused)] fn is_write_closed(&self) -> bool { match self.writing { Writing::Closed => true, diff --git /dev/null b/src/proto/dispatch.rs new file mode 100644 --- /dev/null +++ b/src/proto/dispatch.rs @@ -0,0 +1,325 @@ +use futures::{Async, AsyncSink, Future, Poll, Sink, Stream}; +use futures::sync::{mpsc, oneshot}; +use tokio_io::{AsyncRead, AsyncWrite}; +use tokio_service::Service; + +use super::{Body, Conn, KeepAlive, Http1Transaction, MessageHead, RequestHead, ResponseHead}; +use ::StatusCode; + +pub struct Dispatcher<D, Bs, I, B, T, K> { + conn: Conn<I, B, T, K>, + dispatch: D, + body_tx: Option<super::body::BodySender>, + body_rx: Option<Bs>, +} + +pub trait Dispatch { + type PollItem; + type PollBody; + type RecvItem; + fn poll_msg(&mut self) -> Poll<Option<(Self::PollItem, Option<Self::PollBody>)>, ::Error>; + fn recv_msg(&mut self, msg: ::Result<(Self::RecvItem, Body)>) -> ::Result<()>; + fn should_poll(&self) -> bool; +} + +pub struct Server<S: Service> { + in_flight: Option<S::Future>, + service: S, +} + +pub struct Client<B> { + callback: Option<oneshot::Sender<::Result<::Response>>>, + rx: ClientRx<B>, +} + +type ClientRx<B> = mpsc::Receiver<(RequestHead, Option<B>, oneshot::Sender<::Result<::Response>>)>; + +impl<D, Bs, I, B, T, K> Dispatcher<D, Bs, I, B, T, K> +where + D: Dispatch<PollItem=MessageHead<T::Outgoing>, PollBody=Bs, RecvItem=MessageHead<T::Incoming>>, + I: AsyncRead + AsyncWrite, + B: AsRef<[u8]>, + T: Http1Transaction, + K: KeepAlive, + Bs: Stream<Item=B, Error=::Error>, +{ + pub fn new(dispatch: D, conn: Conn<I, B, T, K>) -> Self { + Dispatcher { + conn: conn, + dispatch: dispatch, + body_tx: None, + body_rx: None, + } + } + + fn poll_read(&mut self) -> Poll<(), ::Error> { + loop { + if self.conn.can_read_head() { + match self.conn.read_head() { + Ok(Async::Ready(Some((head, has_body)))) => { + let body = if has_body { + let (tx, rx) = super::Body::pair(); + self.body_tx = Some(tx); + rx + } else { + Body::empty() + }; + self.dispatch.recv_msg(Ok((head, body))).expect("recv_msg with Ok shouldn't error"); + }, + Ok(Async::Ready(None)) => { + // read eof, conn will start to shutdown automatically + return Ok(Async::Ready(())); + } + Ok(Async::NotReady) => return Ok(Async::NotReady), + Err(err) => { + debug!("read_head error: {}", err); + self.dispatch.recv_msg(Err(err))?; + // if here, the dispatcher gave the user the error + // somewhere else. we still need to shutdown, but + // not as a second error. + return Ok(Async::Ready(())); + } + } + } else if let Some(mut body) = self.body_tx.take() { + let can_read_body = self.conn.can_read_body(); + match body.poll_ready() { + Ok(Async::Ready(())) => (), + Ok(Async::NotReady) => { + self.body_tx = Some(body); + return Ok(Async::NotReady); + }, + Err(_canceled) => { + // user doesn't care about the body + // so we should stop reading + if can_read_body { + trace!("body receiver dropped before eof, closing"); + self.conn.close_read(); + return Ok(Async::Ready(())); + } + } + } + if can_read_body { + match self.conn.read_body() { + Ok(Async::Ready(Some(chunk))) => { + match body.start_send(Ok(chunk)) { + Ok(AsyncSink::Ready) => { + self.body_tx = Some(body); + }, + Ok(AsyncSink::NotReady(_chunk)) => { + unreachable!("mpsc poll_ready was ready, start_send was not"); + } + Err(_canceled) => { + if self.conn.can_read_body() { + trace!("body receiver dropped before eof, closing"); + self.conn.close_read(); + } + } + + } + }, + Ok(Async::Ready(None)) => { + let _ = body.close(); + }, + Ok(Async::NotReady) => { + self.body_tx = Some(body); + return Ok(Async::NotReady); + } + Err(e) => { + let _ = body.start_send(Err(::Error::Io(e))); + } + } + } else { + let _ = body.close(); + } + } else { + self.conn.maybe_park_read(); + return Ok(Async::Ready(())); + } + } + } + + fn poll_write(&mut self) -> Poll<(), ::Error> { + loop { + if self.body_rx.is_none() && self.dispatch.should_poll() { + if let Some((head, body)) = try_ready!(self.dispatch.poll_msg()) { + self.conn.write_head(head, body.is_some()); + self.body_rx = body; + } else { + self.conn.close_write(); + return Ok(Async::Ready(())); + } + } else if let Some(mut body) = self.body_rx.take() { + let chunk = match body.poll()? { + Async::Ready(Some(chunk)) => { + self.body_rx = Some(body); + chunk + }, + Async::Ready(None) => { + if self.conn.can_write_body() { + self.conn.write_body(None)?; + } + continue; + }, + Async::NotReady => { + self.body_rx = Some(body); + return Ok(Async::NotReady); + } + }; + self.conn.write_body(Some(chunk))?; + } else { + return Ok(Async::NotReady); + } + } + } + + fn poll_flush(&mut self) -> Poll<(), ::Error> { + self.conn.flush().map_err(|err| { + debug!("error writing: {}", err); + err.into() + }) + } + + fn is_done(&self) -> bool { + let read_done = self.conn.is_read_closed(); + let write_done = self.conn.is_write_closed() || + (!self.dispatch.should_poll() && self.body_rx.is_none()); + + read_done && write_done + } +} + + +impl<D, Bs, I, B, T, K> Future for Dispatcher<D, Bs, I, B, T, K> +where + D: Dispatch<PollItem=MessageHead<T::Outgoing>, PollBody=Bs, RecvItem=MessageHead<T::Incoming>>, + I: AsyncRead + AsyncWrite, + B: AsRef<[u8]>, + T: Http1Transaction, + K: KeepAlive, + Bs: Stream<Item=B, Error=::Error>, +{ + type Item = (); + type Error = ::Error; + + #[inline] + fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + self.poll_read()?; + self.poll_write()?; + self.poll_flush()?; + + if self.is_done() { + trace!("Dispatch::poll done"); + Ok(Async::Ready(())) + } else { + Ok(Async::NotReady) + } + } +} + +// ===== impl Server ===== + +impl<S> Server<S> where S: Service { + pub fn new(service: S) -> Server<S> { + Server { + in_flight: None, + service: service, + } + } +} + +impl<S, Bs> Dispatch for Server<S> +where + S: Service<Request=::Request, Response=::Response<Bs>, Error=::Error>, + Bs: Stream<Error=::Error>, + Bs::Item: AsRef<[u8]>, +{ + type PollItem = MessageHead<StatusCode>; + type PollBody = Bs; + type RecvItem = RequestHead; + + fn poll_msg(&mut self) -> Poll<Option<(Self::PollItem, Option<Self::PollBody>)>, ::Error> { + if let Some(mut fut) = self.in_flight.take() { + let resp = match fut.poll()? { + Async::Ready(res) => res, + Async::NotReady => { + self.in_flight = Some(fut); + return Ok(Async::NotReady); + } + }; + let (head, body) = super::response::split(resp); + Ok(Async::Ready(Some((head.into(), body)))) + } else { + unreachable!("poll_msg shouldn't be called if no inflight"); + } + } + + fn recv_msg(&mut self, msg: ::Result<(Self::RecvItem, Body)>) -> ::Result<()> { + let (msg, body) = msg?; + let req = super::request::from_wire(None, msg, body); + self.in_flight = Some(self.service.call(req)); + Ok(()) + } + + fn should_poll(&self) -> bool { + self.in_flight.is_some() + } +} + +// ===== impl Client ===== + +impl<B> Client<B> { + pub fn new(rx: ClientRx<B>) -> Client<B> { + Client { + callback: None, + rx: rx, + } + } +} + +impl<B> Dispatch for Client<B> +where + B: Stream<Error=::Error>, + B::Item: AsRef<[u8]>, +{ + type PollItem = RequestHead; + type PollBody = B; + type RecvItem = ResponseHead; + + fn poll_msg(&mut self) -> Poll<Option<(Self::PollItem, Option<Self::PollBody>)>, ::Error> { + match self.rx.poll() { + Ok(Async::Ready(Some((head, body, cb)))) => { + self.callback = Some(cb); + Ok(Async::Ready(Some((head, body)))) + }, + Ok(Async::Ready(None)) => { + // user has dropped sender handle + Ok(Async::Ready(None)) + }, + Ok(Async::NotReady) => return Ok(Async::NotReady), + Err(()) => unreachable!("mpsc receiver cannot error"), + } + } + + fn recv_msg(&mut self, msg: ::Result<(Self::RecvItem, Body)>) -> ::Result<()> { + match msg { + Ok((msg, body)) => { + let res = super::response::from_wire(msg, Some(body)); + let cb = self.callback.take().expect("recv_msg without callback"); + let _ = cb.send(Ok(res)); + Ok(()) + }, + Err(err) => { + if let Some(cb) = self.callback.take() { + let _ = cb.send(Err(err)); + Ok(()) + } else { + Err(err) + } + } + } + } + + fn should_poll(&self) -> bool { + self.callback.is_none() + } +} diff --git a/src/proto/h1/parse.rs b/src/proto/h1/parse.rs --- a/src/proto/h1/parse.rs +++ b/src/proto/h1/parse.rs @@ -132,6 +132,14 @@ impl Http1Transaction for ServerTransaction { extend(dst, b"\r\n"); body } + + fn should_error_on_parse_eof() -> bool { + false + } + + fn should_read_first() -> bool { + true + } } impl ServerTransaction { diff --git a/src/proto/h1/parse.rs b/src/proto/h1/parse.rs --- a/src/proto/h1/parse.rs +++ b/src/proto/h1/parse.rs @@ -281,6 +289,14 @@ impl Http1Transaction for ClientTransaction { body } + + fn should_error_on_parse_eof() -> bool { + true + } + + fn should_read_first() -> bool { + false + } } impl ClientTransaction { diff --git a/src/proto/io.rs b/src/proto/io.rs --- a/src/proto/io.rs +++ b/src/proto/io.rs @@ -84,7 +84,7 @@ impl<T: AsyncRead + AsyncWrite> Buffered<T> { match try_ready!(self.read_from_io()) { 0 => { trace!("parse eof"); - //TODO: With Rust 1.14, this can be Error::from(ErrorKind) + //TODO: utilize Error::Incomplete when Error type is redesigned return Err(io::Error::new(io::ErrorKind::UnexpectedEof, ParseEof).into()); } _ => {}, diff --git a/src/proto/io.rs b/src/proto/io.rs --- a/src/proto/io.rs +++ b/src/proto/io.rs @@ -335,13 +335,13 @@ struct ParseEof; impl fmt::Display for ParseEof { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_str("parse eof") + f.write_str(::std::error::Error::description(self)) } } impl ::std::error::Error for ParseEof { fn description(&self) -> &str { - "parse eof" + "end of file reached before parsing could complete" } } diff --git a/src/proto/mod.rs b/src/proto/mod.rs --- a/src/proto/mod.rs +++ b/src/proto/mod.rs @@ -19,6 +19,7 @@ pub use self::chunk::Chunk; mod body; mod chunk; mod conn; +pub mod dispatch; mod io; mod h1; //mod h2; diff --git a/src/proto/mod.rs b/src/proto/mod.rs --- a/src/proto/mod.rs +++ b/src/proto/mod.rs @@ -146,6 +147,9 @@ pub trait Http1Transaction { fn parse(bytes: &mut BytesMut) -> ParseResult<Self::Incoming>; fn decoder(head: &MessageHead<Self::Incoming>, method: &mut Option<::Method>) -> ::Result<h1::Decoder>; fn encode(head: MessageHead<Self::Outgoing>, has_body: bool, method: &mut Option<Method>, dst: &mut Vec<u8>) -> h1::Encoder; + + fn should_error_on_parse_eof() -> bool; + fn should_read_first() -> bool; } pub type ParseResult<T> = ::Result<Option<(MessageHead<T>, usize)>>; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -66,6 +66,7 @@ where B: Stream<Error=::Error>, core: Core, listener: TcpListener, shutdown_timeout: Duration, + no_proto: bool, } impl<B: AsRef<[u8]> + 'static> Http<B> { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -121,6 +122,7 @@ impl<B: AsRef<[u8]> + 'static> Http<B> { listener: listener, protocol: self.clone(), shutdown_timeout: Duration::new(1, 0), + no_proto: false, }) } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -165,6 +167,30 @@ impl<B: AsRef<[u8]> + 'static> Http<B> { }) } + /// Bind a connection together with a Service. + /// + /// This returns a Future that must be polled in order for HTTP to be + /// driven on the connection. + /// + /// This additionally skips the tokio-proto infrastructure internally. + pub fn no_proto<S, I, Bd>(&self, io: I, service: S) -> Connection<I, Bd, S> + where S: Service<Request = Request, Response = Response<Bd>, Error = ::Error> + 'static, + Bd: Stream<Item=B, Error=::Error> + 'static, + I: AsyncRead + AsyncWrite + 'static, + + { + let ka = if self.keep_alive { + proto::KA::Busy + } else { + proto::KA::Disabled + }; + let mut conn = proto::Conn::new(io, ka); + conn.set_flush_pipeline(self.pipeline); + Connection { + conn: proto::dispatch::Dispatcher::new(proto::dispatch::Server::new(service), conn), + } + } + /// Bind a `Service` using types from the `http` crate. /// /// See `Http::bind_connection`. diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -185,6 +211,67 @@ impl<B: AsRef<[u8]> + 'static> Http<B> { } } +/// A future binding a connection with a Service. +/// +/// Polling this future will drive HTTP forward. +#[must_use = "futures do nothing unless polled"] +pub struct Connection<I, B, S> +where S: Service, + B: Stream<Error=::Error>, + B::Item: AsRef<[u8]>, +{ + conn: proto::dispatch::Dispatcher<proto::dispatch::Server<S>, B, I, B::Item, proto::ServerTransaction, proto::KA>, +} + +impl<I, B, S> Future for Connection<I, B, S> +where S: Service<Request = Request, Response = Response<B>, Error = ::Error> + 'static, + I: AsyncRead + AsyncWrite + 'static, + B: Stream<Error=::Error> + 'static, + B::Item: AsRef<[u8]>, +{ + type Item = self::unnameable::Opaque; + type Error = ::Error; + + fn poll(&mut self) -> Poll<Self::Item, Self::Error> { + try_ready!(self.conn.poll()); + Ok(self::unnameable::opaque().into()) + } +} + +impl<I, B, S> fmt::Debug for Connection<I, B, S> +where S: Service, + B: Stream<Error=::Error>, + B::Item: AsRef<[u8]>, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Connection") + .finish() + } +} + +mod unnameable { + // This type is specifically not exported outside the crate, + // so no one can actually name the type. With no methods, we make no + // promises about this type. + // + // All of that to say we can eventually replace the type returned + // to something else, and it would not be a breaking change. + // + // We may want to eventually yield the `T: AsyncRead + AsyncWrite`, which + // doesn't have a `Debug` bound. So, this type can't implement `Debug` + // either, so the type change doesn't break people. + #[allow(missing_debug_implementations)] + pub struct Opaque { + _inner: (), + } + + pub fn opaque() -> Opaque { + Opaque { + _inner: (), + } + } +} + impl<B> Clone for Http<B> { fn clone(&self) -> Http<B> { Http { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -207,7 +294,7 @@ impl<B> fmt::Debug for Http<B> { pub struct __ProtoRequest(proto::RequestHead); #[doc(hidden)] #[allow(missing_debug_implementations)] -pub struct __ProtoResponse(ResponseHead); +pub struct __ProtoResponse(proto::MessageHead<::StatusCode>); #[doc(hidden)] #[allow(missing_debug_implementations)] pub struct __ProtoTransport<T, B>(proto::Conn<T, B, proto::ServerTransaction>); diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -368,8 +455,6 @@ struct HttpService<T> { remote_addr: SocketAddr, } -type ResponseHead = proto::MessageHead<::StatusCode>; - impl<T, B> Service for HttpService<T> where T: Service<Request=Request, Response=Response<B>, Error=::Error>, B: Stream<Error=::Error>, diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -420,6 +505,12 @@ impl<S, B> Server<S, B> self } + /// Configure this server to not use tokio-proto infrastructure internally. + pub fn no_proto(&mut self) -> &mut Self { + self.no_proto = true; + self + } + /// Execute this server infinitely. /// /// This method does not currently return, but it will return an error if diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -444,7 +535,7 @@ impl<S, B> Server<S, B> pub fn run_until<F>(self, shutdown_signal: F) -> ::Result<()> where F: Future<Item = (), Error = ()>, { - let Server { protocol, new_service, mut core, listener, shutdown_timeout } = self; + let Server { protocol, new_service, mut core, listener, shutdown_timeout, no_proto } = self; let handle = core.handle(); // Mini future to track the number of active services diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -460,7 +551,14 @@ impl<S, B> Server<S, B> info: Rc::downgrade(&info), }; info.borrow_mut().active += 1; - protocol.bind_connection(&handle, socket, addr, s); + if no_proto { + let fut = protocol.no_proto(socket, s) + .map(|_| ()) + .map_err(|err| error!("no_proto error: {}", err)); + handle.spawn(fut); + } else { + protocol.bind_connection(&handle, socket, addr, s); + } Ok(()) });
diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -727,7 +769,7 @@ mod tests { use futures::future; use tokio_proto::streaming::pipeline::Frame; - use proto::{self, MessageHead, ServerTransaction}; + use proto::{self, ClientTransaction, MessageHead, ServerTransaction}; use super::super::h1::Encoder; use mock::AsyncIo; diff --git a/src/proto/conn.rs b/src/proto/conn.rs --- a/src/proto/conn.rs +++ b/src/proto/conn.rs @@ -799,22 +841,43 @@ mod tests { let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); conn.state.idle(); - match conn.poll().unwrap() { - Async::Ready(Some(Frame::Error { .. })) => {}, - other => panic!("frame is not Error: {:?}", other) + match conn.poll() { + Err(ref err) if err.kind() == ::std::io::ErrorKind::UnexpectedEof => {}, + other => panic!("unexpected frame: {:?}", other) } } #[test] fn test_conn_init_read_eof_busy() { - let io = AsyncIo::new_buf(vec![], 1); - let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); - conn.state.busy(); + let _: Result<(), ()> = future::lazy(|| { + // server ignores + let io = AsyncIo::new_buf(vec![], 1); + let mut conn = Conn::<_, proto::Chunk, ServerTransaction>::new(io, Default::default()); + conn.state.busy(); - match conn.poll().unwrap() { - Async::Ready(Some(Frame::Error { .. })) => {}, - other => panic!("frame is not Error: {:?}", other) - } + match conn.poll().unwrap() { + Async::Ready(None) => {}, + other => panic!("unexpected frame: {:?}", other) + } + + // client + let io = AsyncIo::new_buf(vec![], 1); + let mut conn = Conn::<_, proto::Chunk, ClientTransaction>::new(io, Default::default()); + conn.state.busy(); + + match conn.poll() { + Ok(Async::NotReady) => {}, + other => panic!("unexpected frame: {:?}", other) + } + + // once mid-request, returns the error + conn.state.writing = super::Writing::KeepAlive; + match conn.poll() { + Err(ref err) if err.kind() == ::std::io::ErrorKind::UnexpectedEof => {}, + other => panic!("unexpected frame: {:?}", other) + } + Ok(()) + }).wait(); } #[test] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -2,6 +2,7 @@ extern crate hyper; extern crate futures; extern crate tokio_core; +extern crate tokio_io; extern crate pretty_env_logger; use std::io::{self, Read, Write}; diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -18,13 +19,24 @@ use futures::sync::oneshot; use tokio_core::reactor::{Core, Handle}; fn client(handle: &Handle) -> Client<HttpConnector> { - Client::new(handle) + let mut config = Client::configure(); + if env("HYPER_NO_PROTO", "1") { + config = config.no_proto(); + } + config.build(handle) } fn s(buf: &[u8]) -> &str { ::std::str::from_utf8(buf).unwrap() } +fn env(name: &str, val: &str) -> bool { + match ::std::env::var(name) { + Ok(var) => var == val, + Err(_) => false, + } +} + macro_rules! test { ( name: $name:ident, diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -49,51 +61,24 @@ macro_rules! test { #![allow(unused)] use hyper::header::*; let _ = pretty_env_logger::init(); - let server = TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = server.local_addr().unwrap(); let mut core = Core::new().unwrap(); - let client = client(&core.handle()); - let mut req = Request::new(Method::$client_method, format!($client_url, addr=addr).parse().unwrap()); - $( - req.headers_mut().set($request_headers); - )* - if let Some(body) = $request_body { - let body: &'static str = body; - req.set_body(body); - } - req.set_proxy($request_proxy); - - let res = client.request(req); - - let (tx, rx) = oneshot::channel(); - - let thread = thread::Builder::new() - .name(format!("tcp-server<{}>", stringify!($name))); - thread.spawn(move || { - let mut inc = server.accept().unwrap().0; - inc.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); - inc.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); - let expected = format!($server_expected, addr=addr); - let mut buf = [0; 4096]; - let mut n = 0; - while n < buf.len() && n < expected.len() { - n += match inc.read(&mut buf[n..]) { - Ok(n) => n, - Err(e) => panic!("failed to read request, partially read = {:?}, error: {}", s(&buf[..n]), e), - }; - } - assert_eq!(s(&buf[..n]), expected); - - inc.write_all($server_reply.as_ref()).unwrap(); - let _ = tx.send(()); - }).unwrap(); - - let rx = rx.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); - - let work = res.join(rx).map(|r| r.0); - - let res = core.run(work).unwrap(); + let res = test! { + INNER; + core: &mut core, + server: + expected: $server_expected, + reply: $server_reply, + client: + request: + method: $client_method, + url: $client_url, + headers: [ $($request_headers,)* ], + body: $request_body, + proxy: $request_proxy, + }.unwrap(); + + assert_eq!(res.status(), StatusCode::$client_status); $( assert_eq!(res.headers().get(), Some(&$response_headers)); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -106,6 +91,108 @@ macro_rules! test { assert_eq!(body.as_ref(), expected_res_body); } ); + ( + name: $name:ident, + server: + expected: $server_expected:expr, + reply: $server_reply:expr, + client: + request: + method: $client_method:ident, + url: $client_url:expr, + headers: [ $($request_headers:expr,)* ], + body: $request_body:expr, + proxy: $request_proxy:expr, + + error: $err:expr, + ) => ( + #[test] + fn $name() { + #![allow(unused)] + use hyper::header::*; + let _ = pretty_env_logger::init(); + let mut core = Core::new().unwrap(); + + let err = test! { + INNER; + core: &mut core, + server: + expected: $server_expected, + reply: $server_reply, + client: + request: + method: $client_method, + url: $client_url, + headers: [ $($request_headers,)* ], + body: $request_body, + proxy: $request_proxy, + }.unwrap_err(); + if !$err(&err) { + panic!("unexpected error: {:?}", err) + } + } + ); + + ( + INNER; + core: $core:expr, + server: + expected: $server_expected:expr, + reply: $server_reply:expr, + client: + request: + method: $client_method:ident, + url: $client_url:expr, + headers: [ $($request_headers:expr,)* ], + body: $request_body:expr, + proxy: $request_proxy:expr, + ) => ({ + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = server.local_addr().unwrap(); + let mut core = $core; + let client = client(&core.handle()); + let mut req = Request::new(Method::$client_method, format!($client_url, addr=addr).parse().unwrap()); + $( + req.headers_mut().set($request_headers); + )* + + if let Some(body) = $request_body { + let body: &'static str = body; + req.set_body(body); + } + req.set_proxy($request_proxy); + + let res = client.request(req); + + let (tx, rx) = oneshot::channel(); + + let thread = thread::Builder::new() + .name(format!("tcp-server<{}>", stringify!($name))); + thread.spawn(move || { + let mut inc = server.accept().unwrap().0; + inc.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + inc.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + let expected = format!($server_expected, addr=addr); + let mut buf = [0; 4096]; + let mut n = 0; + while n < buf.len() && n < expected.len() { + n += match inc.read(&mut buf[n..]) { + Ok(n) => n, + Err(e) => panic!("failed to read request, partially read = {:?}, error: {}", s(&buf[..n]), e), + }; + } + assert_eq!(s(&buf[..n]), expected); + + inc.write_all($server_reply.as_ref()).unwrap(); + let _ = tx.send(()); + }).unwrap(); + + let rx = rx.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + + let work = res.join(rx).map(|r| r.0); + + core.run(work) + }); } static REPLY_OK: &'static str = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"; diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -266,6 +353,93 @@ test! { body: None, } +test! { + name: client_pipeline_responses_extra, + + server: + expected: "\ + GET /pipe HTTP/1.1\r\n\ + Host: {addr}\r\n\ + \r\n\ + ", + reply: "\ + HTTP/1.1 200 OK\r\n\ + Content-Length: 0\r\n\ + \r\n\ + HTTP/1.1 200 OK\r\n\ + Content-Length: 0\r\n\ + \r\n\ + ", + + client: + request: + method: Get, + url: "http://{addr}/pipe", + headers: [], + body: None, + proxy: false, + response: + status: Ok, + headers: [], + body: None, +} + + +test! { + name: client_error_unexpected_eof, + + server: + expected: "\ + GET /err HTTP/1.1\r\n\ + Host: {addr}\r\n\ + \r\n\ + ", + reply: "\ + HTTP/1.1 200 OK\r\n\ + ", // unexpected eof before double CRLF + + client: + request: + method: Get, + url: "http://{addr}/err", + headers: [], + body: None, + proxy: false, + error: |err| match err { + &hyper::Error::Io(_) => true, + _ => false, + }, +} + +test! { + name: client_error_parse_version, + + server: + expected: "\ + GET /err HTTP/1.1\r\n\ + Host: {addr}\r\n\ + \r\n\ + ", + reply: "\ + HEAT/1.1 200 OK\r\n\ + \r\n\ + ", + + client: + request: + method: Get, + url: "http://{addr}/err", + headers: [], + body: None, + proxy: false, + error: |err| match err { + &hyper::Error::Version if env("HYPER_NO_PROTO", "1") => true, + &hyper::Error::Io(_) if !env("HYPER_NO_PROTO", "1") => true, + _ => false, + }, + +} + #[test] fn client_keep_alive() { let server = TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -285,9 +459,10 @@ fn client_keep_alive() { sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").expect("write 1"); let _ = tx1.send(()); - sock.read(&mut buf).expect("read 2"); - let second_get = b"GET /b HTTP/1.1\r\n"; - assert_eq!(&buf[..second_get.len()], second_get); + let n2 = sock.read(&mut buf).expect("read 2"); + assert_ne!(n2, 0); + let second_get = "GET /b HTTP/1.1\r\n"; + assert_eq!(s(&buf[..second_get.len()]), second_get); sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").expect("write 2"); let _ = tx2.send(()); }); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -367,3 +542,104 @@ fn client_pooled_socket_disconnected() { assert_ne!(addr1, addr2); } */ + +#[test] +fn drop_body_before_eof_closes_connection() { + // https://github.com/hyperium/hyper/issues/1353 + use std::io::{self, Read, Write}; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Duration; + use tokio_core::reactor::{Timeout}; + use tokio_core::net::TcpStream; + use tokio_io::{AsyncRead, AsyncWrite}; + use hyper::client::HttpConnector; + use hyper::server::Service; + use hyper::Uri; + + let _ = pretty_env_logger::init(); + + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = server.local_addr().unwrap(); + let mut core = Core::new().unwrap(); + let handle = core.handle(); + let closes = Arc::new(AtomicUsize::new(0)); + let client = Client::configure() + .connector(DebugConnector(HttpConnector::new(1, &core.handle()), closes.clone())) + .no_proto() + .build(&handle); + + let (tx1, rx1) = oneshot::channel(); + + thread::spawn(move || { + let mut sock = server.accept().unwrap().0; + sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut buf = [0; 4096]; + sock.read(&mut buf).expect("read 1"); + let body = vec![b'x'; 1024 * 128]; + write!(sock, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body.len()).expect("write head"); + let _ = sock.write_all(&body); + let _ = tx1.send(()); + }); + + let uri = format!("http://{}/a", addr).parse().unwrap(); + + let res = client.get(uri).and_then(move |res| { + assert_eq!(res.status(), hyper::StatusCode::Ok); + Timeout::new(Duration::from_secs(1), &handle).unwrap() + .from_err() + }); + let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked"))); + core.run(res.join(rx).map(|r| r.0)).unwrap(); + + assert_eq!(closes.load(Ordering::Relaxed), 1); + + + + struct DebugConnector(HttpConnector, Arc<AtomicUsize>); + + impl Service for DebugConnector { + type Request = Uri; + type Response = DebugStream; + type Error = io::Error; + type Future = Box<Future<Item = DebugStream, Error = io::Error>>; + + fn call(&self, uri: Uri) -> Self::Future { + let counter = self.1.clone(); + Box::new(self.0.call(uri).map(move |s| DebugStream(s, counter))) + } + } + + struct DebugStream(TcpStream, Arc<AtomicUsize>); + + impl Drop for DebugStream { + fn drop(&mut self) { + self.1.fetch_add(1, Ordering::SeqCst); + } + } + + impl Write for DebugStream { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.0.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.0.flush() + } + } + + impl AsyncWrite for DebugStream { + fn shutdown(&mut self) -> futures::Poll<(), io::Error> { + AsyncWrite::shutdown(&mut self.0) + } + } + + impl Read for DebugStream { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.0.read(buf) + } + } + + impl AsyncRead for DebugStream {} +} diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -3,10 +3,15 @@ extern crate hyper; extern crate futures; extern crate spmc; extern crate pretty_env_logger; +extern crate tokio_core; use futures::{Future, Stream}; +use futures::future::{self, FutureResult}; use futures::sync::oneshot; +use tokio_core::net::TcpListener; +use tokio_core::reactor::Core; + use std::net::{TcpStream, SocketAddr}; use std::io::{Read, Write}; use std::sync::mpsc; diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -387,6 +392,7 @@ fn disable_keep_alive() { .header(hyper::header::ContentLength(quux.len() as u64)) .body(quux); + // the write can possibly succeed, since it fills the kernel buffer on the first write let _ = req.write_all(b"\ GET /quux HTTP/1.1\r\n\ Host: example.domain\r\n\ diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -394,7 +400,6 @@ fn disable_keep_alive() { \r\n\ "); - // the write can possibly succeed, since it fills the kernel buffer on the first write let mut buf = [0; 1024 * 8]; match req.read(&mut buf[..]) { // Ok(0) means EOF, so a proper shutdown diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -504,6 +509,50 @@ fn pipeline_enabled() { assert_eq!(n, 0); } +#[test] +fn no_proto_empty_parse_eof_does_not_return_error() { + let mut core = Core::new().unwrap(); + let listener = TcpListener::bind(&"127.0.0.1:0".parse().unwrap(), &core.handle()).unwrap(); + let addr = listener.local_addr().unwrap(); + + thread::spawn(move || { + let _tcp = connect(&addr); + }); + + let fut = listener.incoming() + .into_future() + .map_err(|_| unreachable!()) + .and_then(|(item, _incoming)| { + let (socket, _) = item.unwrap(); + Http::new().no_proto(socket, HelloWorld) + }); + + core.run(fut).unwrap(); +} + +#[test] +fn no_proto_nonempty_parse_eof_returns_error() { + let mut core = Core::new().unwrap(); + let listener = TcpListener::bind(&"127.0.0.1:0".parse().unwrap(), &core.handle()).unwrap(); + let addr = listener.local_addr().unwrap(); + + thread::spawn(move || { + let mut tcp = connect(&addr); + tcp.write_all(b"GET / HTTP/1.1").unwrap(); + }); + + let fut = listener.incoming() + .into_future() + .map_err(|_| unreachable!()) + .and_then(|(item, _incoming)| { + let (socket, _) = item.unwrap(); + Http::new().no_proto(socket, HelloWorld) + .map(|_| ()) + }); + + core.run(fut).unwrap_err(); +} + // ------------------------------------------------- // the Server that is used to run all the tests with // ------------------------------------------------- diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -628,6 +677,20 @@ impl Service for TestService { } +struct HelloWorld; + +impl Service for HelloWorld { + type Request = Request; + type Response = Response; + type Error = hyper::Error; + type Future = FutureResult<Self::Response, Self::Error>; + + fn call(&self, _req: Request) -> Self::Future { + future::ok(Response::new()) + } +} + + fn connect(addr: &SocketAddr) -> TcpStream { let req = TcpStream::connect(addr).unwrap(); req.set_read_timeout(Some(Duration::from_secs(1))).unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -639,13 +702,31 @@ fn serve() -> Serve { serve_with_options(Default::default()) } -#[derive(Default)] struct ServeOptions { keep_alive_disabled: bool, + no_proto: bool, pipeline: bool, timeout: Option<Duration>, } +impl Default for ServeOptions { + fn default() -> Self { + ServeOptions { + keep_alive_disabled: false, + no_proto: env("HYPER_NO_PROTO", "1"), + pipeline: false, + timeout: None, + } + } +} + +fn env(name: &str, val: &str) -> bool { + match ::std::env::var(name) { + Ok(var) => var == val, + Err(_) => false, + } +} + fn serve_with_options(options: ServeOptions) -> Serve { let _ = pretty_env_logger::init(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -657,12 +738,13 @@ fn serve_with_options(options: ServeOptions) -> Serve { let addr = "127.0.0.1:0".parse().unwrap(); let keep_alive = !options.keep_alive_disabled; + let no_proto = !options.no_proto; let pipeline = options.pipeline; let dur = options.timeout; let thread_name = format!("test-server-{:?}", dur); let thread = thread::Builder::new().name(thread_name).spawn(move || { - let srv = Http::new() + let mut srv = Http::new() .keep_alive(keep_alive) .pipeline(pipeline) .bind(&addr, TestService { diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -670,6 +752,9 @@ fn serve_with_options(options: ServeOptions) -> Serve { _timeout: dur, reply: reply_rx, }).unwrap(); + if no_proto { + srv.no_proto(); + } addr_tx.send(srv.local_addr().unwrap()).unwrap(); srv.run_until(shutdown_rx.then(|_| Ok(()))).unwrap(); }).unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -684,5 +769,3 @@ fn serve_with_options(options: ServeOptions) -> Serve { thread: Some(thread), } } - -
Not reading the entire response body leaks the connection on the client side This program continually creates new connections without ever closing old ones: ```rust extern crate hyper; extern crate tokio_core; extern crate tokio_io; extern crate futures; extern crate env_logger; use tokio_core::reactor::{Core, Timeout}; use tokio_core::net::TcpStream; use tokio_io::{AsyncRead, AsyncWrite}; use hyper::{Client, Uri}; use hyper::client::HttpConnector; use hyper::server::Service; use std::time::Duration; use std::cell::Cell; use futures::{Future, Stream, stream}; use std::io::{self, Read, Write}; fn main() { env_logger::init().unwrap(); let mut core = Core::new().unwrap(); let handle = core.handle(); let client = Client::configure() .connector(DebugConnector(HttpConnector::new(1, &handle), Cell::new(0))) .keep_alive_timeout(Some(Duration::from_secs(5))) .build(&handle); let fut = stream::repeat(()).for_each(|()| { client.get("http://www.google.com".parse().unwrap()) .and_then(|_| { println!("ignoring body"); let timeout = Timeout::new(Duration::from_secs(1), &handle).unwrap(); timeout.map_err(|e| e.into()) }) .map_err(|e| println!("error {}", e)) }); core.run(fut).unwrap(); } struct DebugConnector(HttpConnector, Cell<u32>); impl Service for DebugConnector { type Request = Uri; type Response = DebugStream; type Error = io::Error; type Future = Box<Future<Item = DebugStream, Error = io::Error>>; fn call(&self, uri: Uri) -> Self::Future { let id = self.1.get(); self.1.set(id + 1); println!("new connection {}", id); Box::new(self.0.call(uri).map(move |s| DebugStream(s, id))) } } struct DebugStream(TcpStream, u32); impl Drop for DebugStream { fn drop(&mut self) { println!("socket {} dropping", self.1); } } impl Write for DebugStream { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } fn flush(&mut self) -> io::Result<()> { self.0.flush() } } impl AsyncWrite for DebugStream { fn shutdown(&mut self) -> futures::Poll<(), io::Error> { AsyncWrite::shutdown(&mut self.0) } } impl Read for DebugStream { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } } impl AsyncRead for DebugStream {} ``` ``` new connection 0 ignoring body new connection 1 ignoring body new connection 2 ignoring body new connection 3 ignoring body new connection 4 ignoring body new connection 5 ignoring body new connection 6 ignoring body new connection 7 ignoring body new connection 8 ignoring body new connection 9 ignoring body new connection 10 ignoring body new connection 11 ignoring body new connection 12 ignoring body new connection 13 ignoring body new connection 14 ignoring body new connection 15 ignoring body new connection 16 ignoring body new connection 17 ignoring body new connection 18 ignoring body new connection 19 ignoring body new connection 20 ignoring body new connection 21 ignoring body new connection 22 ignoring body new connection 23 ignoring body new connection 24 ignoring body new connection 25 ... ```
2017-10-27T06:25:54Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,325
hyperium__hyper-1325
[ "1315" ]
971864c424495e9dd4cafe6c7fb4c7504a01e03d
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,7 @@ language-tags = "0.2" log = "0.3" mime = "0.3.2" percent-encoding = "1.0" +relay = "0.1" time = "0.1" tokio-core = "0.1.6" tokio-proto = "0.1" diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -7,7 +7,7 @@ use std::rc::Rc; use std::time::{Duration, Instant}; use futures::{Future, Async, Poll}; -use futures::unsync::oneshot; +use relay; use http::{KeepAlive, KA}; diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -17,8 +17,19 @@ pub struct Pool<T> { struct PoolInner<T> { enabled: bool, + // These are internal Conns sitting in the event loop in the KeepAlive + // state, waiting to receive a new Request to send on the socket. idle: HashMap<Rc<String>, Vec<Entry<T>>>, - parked: HashMap<Rc<String>, VecDeque<oneshot::Sender<Entry<T>>>>, + // These are outstanding Checkouts that are waiting for a socket to be + // able to send a Request one. This is used when "racing" for a new + // connection. + // + // The Client starts 2 tasks, 1 to connect a new socket, and 1 to wait + // for the Pool to receive an idle Conn. When a Conn becomes idle, + // this list is checked for any parked Checkouts, and tries to notify + // them that the Conn could be used instead of waiting for a brand new + // connection. + parked: HashMap<Rc<String>, VecDeque<relay::Sender<Entry<T>>>>, timeout: Option<Duration>, } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -50,6 +61,12 @@ impl<T: Clone> Pool<T> { let mut entry = Some(entry); if let Some(parked) = inner.parked.get_mut(&key) { while let Some(tx) = parked.pop_front() { + if tx.is_canceled() { + trace!("Pool::put removing canceled parked {:?}", key); + } else { + tx.complete(entry.take().unwrap()); + } + /* match tx.send(entry.take().unwrap()) { Ok(()) => break, Err(e) => { diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -57,6 +74,7 @@ impl<T: Clone> Pool<T> { entry = Some(e); } } + */ } remove_parked = parked.is_empty(); } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -74,6 +92,7 @@ impl<T: Clone> Pool<T> { } } + pub fn pooled(&self, key: Rc<String>, value: T) -> Pooled<T> { trace!("Pool::pooled {:?}", key); Pooled { diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -102,7 +121,7 @@ impl<T: Clone> Pool<T> { } } - fn park(&mut self, key: Rc<String>, tx: oneshot::Sender<Entry<T>>) { + fn park(&mut self, key: Rc<String>, tx: relay::Sender<Entry<T>>) { trace!("Pool::park {:?}", key); self.inner.borrow_mut() .parked.entry(key) diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -111,6 +130,24 @@ impl<T: Clone> Pool<T> { } } +impl<T> Pool<T> { + fn clean_parked(&mut self, key: &Rc<String>) { + trace!("Pool::clean_parked {:?}", key); + let mut inner = self.inner.borrow_mut(); + + let mut remove_parked = false; + if let Some(parked) = inner.parked.get_mut(key) { + parked.retain(|tx| { + !tx.is_canceled() + }); + remove_parked = parked.is_empty(); + } + if remove_parked { + inner.parked.remove(key); + } + } +} + impl<T> Clone for Pool<T> { fn clone(&self) -> Pool<T> { Pool { diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -204,7 +241,7 @@ enum TimedKA { pub struct Checkout<T> { key: Rc<String>, pool: Pool<T>, - parked: Option<oneshot::Receiver<Entry<T>>>, + parked: Option<relay::Receiver<Entry<T>>>, } impl<T: Clone> Future for Checkout<T> { diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -260,7 +297,7 @@ impl<T: Clone> Future for Checkout<T> { Some(entry) => Ok(Async::Ready(self.pool.reuse(self.key.clone(), entry))), None => { if self.parked.is_none() { - let (tx, mut rx) = oneshot::channel(); + let (tx, mut rx) = relay::channel(); let _ = rx.poll(); // park this task self.pool.park(self.key.clone(), tx); self.parked = Some(rx); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -271,6 +308,13 @@ impl<T: Clone> Future for Checkout<T> { } } +impl<T> Drop for Checkout<T> { + fn drop(&mut self) { + self.parked.take(); + self.pool.clean_parked(&self.key); + } +} + struct Expiration(Option<Duration>); impl Expiration { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -26,6 +26,7 @@ extern crate language_tags; #[macro_use] extern crate log; pub extern crate mime; #[macro_use] extern crate percent_encoding; +extern crate relay; extern crate time; extern crate tokio_core as tokio; #[macro_use] extern crate tokio_io;
diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -364,4 +408,30 @@ mod tests { })).map(|(entry, _)| entry); assert_eq!(*checkout.wait().unwrap(), *pooled1); } + + #[test] + fn test_pool_checkout_drop_cleans_up_parked() { + future::lazy(|| { + let pool = Pool::new(true, Some(Duration::from_secs(10))); + let key = Rc::new("localhost:12345".to_string()); + let _pooled1 = pool.pooled(key.clone(), 41); + let mut checkout1 = pool.checkout(&key); + let mut checkout2 = pool.checkout(&key); + + // first poll needed to get into Pool's parked + checkout1.poll().unwrap(); + assert_eq!(pool.inner.borrow().parked.get(&key).unwrap().len(), 1); + checkout2.poll().unwrap(); + assert_eq!(pool.inner.borrow().parked.get(&key).unwrap().len(), 2); + + // on drop, clean up Pool + drop(checkout1); + assert_eq!(pool.inner.borrow().parked.get(&key).unwrap().len(), 1); + + drop(checkout2); + assert!(pool.inner.borrow().parked.get(&key).is_none()); + + ::futures::future::ok::<(), ()>(()) + }).wait().unwrap(); + } }
Memory leak when using client.clone() for server (proxy) I'm writing a reverse proxy and use the HTTP client to connect to any upstream server. Code is in https://github.com/klausi/rustnish/blob/goal-06/src/lib.rs#L150 . The server is leaking memory so I must be doing something wrong. Steps to reproduce: 1. Make sure you have any upstream HTTP service running locally on port 80, for example the default Apache install on Ubuntu which will give you a dummy page at http://localhost/ ``` sudo apt install apache2 ``` 2. Run rustnish reverse proxy on port 9090: ``` git clone --branch goal-06 git@github.com:klausi/rustnish.git cd rustnish cargo run --release ``` 3. Get PID of rustnish process and memory usage: ``` ps aux | grep rustnish ``` The 6th column is the memory usage of the process, something like 20124 (~20MB) 4. Fire 1 million requests at the reverse proxy with Apache Bench: ``` ab -c 4 -n 1000000 http://localhost:9090/ ``` (This takes ~130 seconds on my computer) 5. Check memory usage again: ``` ps aux | grep rustnish ``` The 6th column should show something like 284920, which is ~280MB! So although we do not cache any requests or keep them around otherwise memory usage is growing without freeing up anymore. One solution to the problem is this patch: ``` diff --git a/src/lib.rs b/src/lib.rs index 520dd24..a591b99 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -170,7 +170,6 @@ pub fn start_server_background( let http = Http::new(); let listener = TcpListener::bind(&address, &handle) .chain_err(|| format!("Failed to bind server to address {}", address))?; - let client = Client::new(&handle); let server = listener.incoming().for_each(move |(sock, addr)| { http.bind_connection( @@ -180,7 +179,7 @@ pub fn start_server_background( Proxy { port: port, upstream_port: upstream_port, - client: client.clone(), + client: Client::new(&handle), }, ); Ok(()) ``` Avoiding the client.clone() call fixes the memory leak but degrades the runtime performance. Apache Bench with 1 million requests took 220 seconds instead of 130 seconds before. So the client_clone() call seems to be the right thing to do, but the clones are not dropped correctly when one request handling is done?
The `Client` contains a pool of connections internally. Are the requests to different hosts? The pool is lazy about ejecting expired connections, so that could be part of it... The requests are always to the same host, http://localhost/ in this example. I will try to find out what happens on a cloned client and what exactly is growing in memory. After spending half an hour of adding `where T: Debug,` to all the things in pool.rs I was able to debug log the pool after 20 requests: ``` Pool { inner: RefCell { value: PoolInner { enabled: true, idle: {}, parked: {"http://localhost:80": [Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }, Sender { inner: (Weak) }]}, timeout: Some(Duration { secs: 90, nanos: 0 }) } } } ``` The hashmap of parked things is growing linearly with the requests performed. The only call to remove() entries form the parked HashMap is in the put() function of Pool, but it is never called. So maybe we need to clean up the parked HashMap in other places as well? Great work investigating this! Thanks! The "parked" senders are `Checkout`s that are "racing" for either a newly connected socket, or an existing socket to become idle, whichever comes first. Your PR is definitely going in the right direction, it just needs to be a little more targeted to only remove the relevant sender, I'll look into it.
2017-09-18T20:30:32Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,259
hyperium__hyper-1259
[ "1257" ]
5f47d72347231c60a953c228abec75b077e99f8d
diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -7,10 +7,10 @@ use futures::task::Task; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_proto::streaming::pipeline::{Frame, Transport}; -use header::{ContentLength, TransferEncoding}; use http::{self, Http1Transaction, DebugTruncate}; use http::io::{Cursor, Buffered}; use http::h1::{Encoder, Decoder}; +use method::Method; use version::HttpVersion; diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -37,10 +37,11 @@ where I: AsyncRead + AsyncWrite, Conn { io: Buffered::new(io), state: State { + keep_alive: keep_alive, + method: None, + read_task: None, reading: Reading::Init, writing: Writing::Init, - read_task: None, - keep_alive: keep_alive, }, _marker: PhantomData, } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -103,7 +104,7 @@ where I: AsyncRead + AsyncWrite, match version { HttpVersion::Http10 | HttpVersion::Http11 => { - let decoder = match T::decoder(&head) { + let decoder = match T::decoder(&head, &mut self.state.method) { Ok(d) => d, Err(e) => { debug!("decoder error = {:?}", e); diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -234,17 +235,8 @@ where I: AsyncRead + AsyncWrite, } } - fn write_head(&mut self, mut head: http::MessageHead<T::Outgoing>, body: bool) { + fn write_head(&mut self, head: http::MessageHead<T::Outgoing>, body: bool) { debug_assert!(self.can_write_head()); - if !body { - head.headers.remove::<TransferEncoding>(); - //TODO: check that this isn't a response to a HEAD - //request, which could include the content-length - //even if no body is to be written - if T::should_set_length(&head) { - head.headers.set(ContentLength(0)); - } - } let wants_keep_alive = head.should_keep_alive(); self.state.keep_alive &= wants_keep_alive; diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -256,8 +248,8 @@ where I: AsyncRead + AsyncWrite, buf.extend_from_slice(pending.buf()); } } - let encoder = T::encode(head, buf); - self.state.writing = if body { + let encoder = T::encode(head, body, &mut self.state.method, buf); + self.state.writing = if !encoder.is_eof() { Writing::Body(encoder, None) } else { Writing::KeepAlive diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -493,10 +485,11 @@ impl<I, B: AsRef<[u8]>, T, K: fmt::Debug> fmt::Debug for Conn<I, B, T, K> { } struct State<B, K> { + keep_alive: K, + method: Option<Method>, + read_task: Option<Task>, reading: Reading, writing: Writing<B>, - read_task: Option<Task>, - keep_alive: K, } #[derive(Debug)] diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -522,6 +515,7 @@ impl<B: AsRef<[u8]>, K: fmt::Debug> fmt::Debug for State<B, K> { .field("reading", &self.reading) .field("writing", &self.writing) .field("keep_alive", &self.keep_alive) + .field("method", &self.method) .field("read_task", &self.read_task) .finish() } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -641,6 +635,7 @@ impl<B, K: KeepAlive> State<B, K> { } fn idle(&mut self) { + self.method = None; self.reading = Reading::Init; self.writing = Writing::Init; self.keep_alive.idle(); diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -5,7 +5,8 @@ use httparse; use bytes::{BytesMut, Bytes}; use header::{self, Headers, ContentLength, TransferEncoding}; -use http::{MessageHead, RawStatus, Http1Transaction, ParseResult, ServerTransaction, ClientTransaction, RequestLine}; +use http::{MessageHead, RawStatus, Http1Transaction, ParseResult, + ServerTransaction, ClientTransaction, RequestLine, RequestHead}; use http::h1::{Encoder, Decoder, date}; use method::Method; use status::StatusCode; diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -72,8 +73,11 @@ impl Http1Transaction for ServerTransaction { }, len))) } - fn decoder(head: &MessageHead<Self::Incoming>) -> ::Result<Decoder> { + fn decoder(head: &MessageHead<Self::Incoming>, method: &mut Option<Method>) -> ::Result<Decoder> { use ::header; + + *method = Some(head.subject.0.clone()); + // According to https://tools.ietf.org/html/rfc7230#section-3.3.3 // 1. (irrelevant to Request) // 2. (irrelevant to Request) diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -105,30 +109,11 @@ impl Http1Transaction for ServerTransaction { } - fn encode(mut head: MessageHead<Self::Outgoing>, dst: &mut Vec<u8>) -> Encoder { - use ::header; - trace!("writing head: {:?}", head); - - let len = head.headers.get::<header::ContentLength>().map(|n| **n); - - let body = if let Some(len) = len { - Encoder::length(len) - } else { - let encodings = match head.headers.get_mut::<header::TransferEncoding>() { - Some(&mut header::TransferEncoding(ref mut encodings)) => { - if encodings.last() != Some(&header::Encoding::Chunked) { - encodings.push(header::Encoding::Chunked); - } - false - }, - None => true - }; + fn encode(mut head: MessageHead<Self::Outgoing>, has_body: bool, method: &mut Option<Method>, dst: &mut Vec<u8>) -> Encoder { + trace!("ServerTransaction::encode head={:?}, has_body={}, method={:?}", + head, has_body, method); - if encodings { - head.headers.set(header::TransferEncoding(vec![header::Encoding::Chunked])); - } - Encoder::chunked() - }; + let body = ServerTransaction::set_length(&mut head, has_body, method.as_ref()); debug!("encode headers = {:?}", head.headers); let init_cap = 30 + head.headers.len() * AVERAGE_HEADER_SIZE; diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -150,16 +135,39 @@ impl Http1Transaction for ServerTransaction { extend(dst, b"\r\n"); body } +} - fn should_set_length(head: &MessageHead<Self::Outgoing>) -> bool { - //TODO: pass method, check if method == HEAD +impl ServerTransaction { + fn set_length(head: &mut MessageHead<StatusCode>, has_body: bool, method: Option<&Method>) -> Encoder { + // these are here thanks to borrowck + // `if method == Some(&Method::Get)` says the RHS doesnt live long enough + const HEAD: Option<&'static Method> = Some(&Method::Head); + const CONNECT: Option<&'static Method> = Some(&Method::Connect); + + let can_have_body = { + if method == HEAD { + false + } else if method == CONNECT && head.subject.is_success() { + false + } else { + match head.subject { + // TODO: support for 1xx codes needs improvement everywhere + // would be 100...199 => false + StatusCode::NoContent | + StatusCode::NotModified => false, + _ => true, + } + } + }; - match head.subject { - // TODO: support for 1xx codes needs improvement everywhere - // would be 100...199 => false - StatusCode::NoContent | - StatusCode::NotModified => false, - _ => true, + if has_body && can_have_body { + set_length(&mut head.headers) + } else { + head.headers.remove::<TransferEncoding>(); + if can_have_body { + head.headers.set(ContentLength(0)); + } + Encoder::length(0) } } } diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -213,8 +221,7 @@ impl Http1Transaction for ClientTransaction { }, len))) } - fn decoder(inc: &MessageHead<Self::Incoming>) -> ::Result<Decoder> { - use ::header; + fn decoder(inc: &MessageHead<Self::Incoming>, method: &mut Option<Method>) -> ::Result<Decoder> { // According to https://tools.ietf.org/html/rfc7230#section-3.3.3 // 1. HEAD responses, and Status 1xx, 204, and 304 cannot have a body. // 2. Status 2xx to a CONNECT cannot have a body. diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -224,7 +231,21 @@ impl Http1Transaction for ClientTransaction { // 6. (irrelevant to Response) // 7. Read till EOF. - //TODO: need a way to pass the Method that caused this Response + match *method { + Some(Method::Head) => { + return Ok(Decoder::length(0)); + } + Some(Method::Connect) => match inc.subject.0 { + 200...299 => { + return Ok(Decoder::length(0)); + }, + _ => {}, + }, + Some(_) => {}, + None => { + trace!("ClientTransaction::decoder is missing the Method"); + } + } match inc.subject.0 { 100...199 | diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -251,39 +272,14 @@ impl Http1Transaction for ClientTransaction { } } - fn encode(mut head: MessageHead<Self::Outgoing>, dst: &mut Vec<u8>) -> Encoder { - trace!("writing head: {:?}", head); - - - let mut body = Encoder::length(0); - let expects_no_body = match head.subject.0 { - Method::Head | Method::Get | Method::Connect => true, - _ => false - }; - let mut chunked = false; + fn encode(mut head: MessageHead<Self::Outgoing>, has_body: bool, method: &mut Option<Method>, dst: &mut Vec<u8>) -> Encoder { + trace!("ClientTransaction::encode head={:?}, has_body={}, method={:?}", + head, has_body, method); - if let Some(con_len) = head.headers.get::<ContentLength>() { - body = Encoder::length(**con_len); - } else { - chunked = !expects_no_body; - } - if chunked { - body = Encoder::chunked(); - let encodings = match head.headers.get_mut::<TransferEncoding>() { - Some(encodings) => { - if !encodings.contains(&header::Encoding::Chunked) { - encodings.push(header::Encoding::Chunked); - } - true - }, - None => false - }; + *method = Some(head.subject.0.clone()); - if !encodings { - head.headers.set(TransferEncoding(vec![header::Encoding::Chunked])); - } - } + let body = ClientTransaction::set_length(&mut head, has_body); debug!("encode headers = {:?}", head.headers); let init_cap = 30 + head.headers.len() * AVERAGE_HEADER_SIZE; diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -292,13 +288,40 @@ impl Http1Transaction for ClientTransaction { body } +} + +impl ClientTransaction { + fn set_length(head: &mut RequestHead, has_body: bool) -> Encoder { + if has_body { + set_length(&mut head.headers) + } else { + head.headers.remove::<ContentLength>(); + head.headers.remove::<TransferEncoding>(); + Encoder::length(0) + } + } +} + +fn set_length(headers: &mut Headers) -> Encoder { + let len = headers.get::<header::ContentLength>().map(|n| **n); + if let Some(len) = len { + Encoder::length(len) + } else { + let encodings = match headers.get_mut::<header::TransferEncoding>() { + Some(&mut header::TransferEncoding(ref mut encodings)) => { + if encodings.last() != Some(&header::Encoding::Chunked) { + encodings.push(header::Encoding::Chunked); + } + false + }, + None => true + }; - fn should_set_length(head: &MessageHead<Self::Outgoing>) -> bool { - match &head.subject.0 { - &Method::Get | &Method::Head => false, - _ => true + if encodings { + headers.set(header::TransferEncoding(vec![header::Encoding::Chunked])); } + Encoder::chunked() } } diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -144,9 +144,8 @@ pub trait Http1Transaction { type Incoming; type Outgoing: Default; fn parse(bytes: &mut BytesMut) -> ParseResult<Self::Incoming>; - fn decoder(head: &MessageHead<Self::Incoming>) -> ::Result<h1::Decoder>; - fn encode(head: MessageHead<Self::Outgoing>, dst: &mut Vec<u8>) -> h1::Encoder; - fn should_set_length(head: &MessageHead<Self::Outgoing>) -> bool; + fn decoder(head: &MessageHead<Self::Incoming>, method: &mut Option<::Method>) -> ::Result<h1::Decoder>; + fn encode(head: MessageHead<Self::Outgoing>, has_body: bool, method: &mut Option<Method>, dst: &mut Vec<u8>) -> h1::Encoder; } pub type ParseResult<T> = ::Result<Option<(MessageHead<T>, usize)>>;
diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -421,63 +444,83 @@ mod tests { fn test_decoder_request() { use super::Decoder; + let method = &mut None; let mut head = MessageHead::<::http::RequestLine>::default(); head.subject.0 = ::Method::Get; - assert_eq!(Decoder::length(0), ServerTransaction::decoder(&head).unwrap()); + assert_eq!(Decoder::length(0), ServerTransaction::decoder(&head, method).unwrap()); + assert_eq!(*method, Some(::Method::Get)); + head.subject.0 = ::Method::Post; - assert_eq!(Decoder::length(0), ServerTransaction::decoder(&head).unwrap()); + assert_eq!(Decoder::length(0), ServerTransaction::decoder(&head, method).unwrap()); + assert_eq!(*method, Some(::Method::Post)); head.headers.set(TransferEncoding::chunked()); - assert_eq!(Decoder::chunked(), ServerTransaction::decoder(&head).unwrap()); + assert_eq!(Decoder::chunked(), ServerTransaction::decoder(&head, method).unwrap()); // transfer-encoding and content-length = chunked head.headers.set(ContentLength(10)); - assert_eq!(Decoder::chunked(), ServerTransaction::decoder(&head).unwrap()); + assert_eq!(Decoder::chunked(), ServerTransaction::decoder(&head, method).unwrap()); head.headers.remove::<TransferEncoding>(); - assert_eq!(Decoder::length(10), ServerTransaction::decoder(&head).unwrap()); + assert_eq!(Decoder::length(10), ServerTransaction::decoder(&head, method).unwrap()); head.headers.set_raw("Content-Length", vec![b"5".to_vec(), b"5".to_vec()]); - assert_eq!(Decoder::length(5), ServerTransaction::decoder(&head).unwrap()); + assert_eq!(Decoder::length(5), ServerTransaction::decoder(&head, method).unwrap()); head.headers.set_raw("Content-Length", vec![b"10".to_vec(), b"11".to_vec()]); - ServerTransaction::decoder(&head).unwrap_err(); + ServerTransaction::decoder(&head, method).unwrap_err(); head.headers.remove::<ContentLength>(); head.headers.set_raw("Transfer-Encoding", "gzip"); - ServerTransaction::decoder(&head).unwrap_err(); + ServerTransaction::decoder(&head, method).unwrap_err(); } #[test] fn test_decoder_response() { use super::Decoder; + let method = &mut Some(::Method::Get); let mut head = MessageHead::<::http::RawStatus>::default(); head.subject.0 = 204; - assert_eq!(Decoder::length(0), ClientTransaction::decoder(&head).unwrap()); + assert_eq!(Decoder::length(0), ClientTransaction::decoder(&head, method).unwrap()); head.subject.0 = 304; - assert_eq!(Decoder::length(0), ClientTransaction::decoder(&head).unwrap()); + assert_eq!(Decoder::length(0), ClientTransaction::decoder(&head, method).unwrap()); head.subject.0 = 200; - assert_eq!(Decoder::eof(), ClientTransaction::decoder(&head).unwrap()); + assert_eq!(Decoder::eof(), ClientTransaction::decoder(&head, method).unwrap()); + + *method = Some(::Method::Head); + assert_eq!(Decoder::length(0), ClientTransaction::decoder(&head, method).unwrap()); + + *method = Some(::Method::Connect); + assert_eq!(Decoder::length(0), ClientTransaction::decoder(&head, method).unwrap()); + + + // CONNECT receiving non 200 can have a body + head.subject.0 = 404; + head.headers.set(ContentLength(10)); + assert_eq!(Decoder::length(10), ClientTransaction::decoder(&head, method).unwrap()); + head.headers.remove::<ContentLength>(); + + *method = Some(::Method::Get); head.headers.set(TransferEncoding::chunked()); - assert_eq!(Decoder::chunked(), ClientTransaction::decoder(&head).unwrap()); + assert_eq!(Decoder::chunked(), ClientTransaction::decoder(&head, method).unwrap()); // transfer-encoding and content-length = chunked head.headers.set(ContentLength(10)); - assert_eq!(Decoder::chunked(), ClientTransaction::decoder(&head).unwrap()); + assert_eq!(Decoder::chunked(), ClientTransaction::decoder(&head, method).unwrap()); head.headers.remove::<TransferEncoding>(); - assert_eq!(Decoder::length(10), ClientTransaction::decoder(&head).unwrap()); + assert_eq!(Decoder::length(10), ClientTransaction::decoder(&head, method).unwrap()); head.headers.set_raw("Content-Length", vec![b"5".to_vec(), b"5".to_vec()]); - assert_eq!(Decoder::length(5), ClientTransaction::decoder(&head).unwrap()); + assert_eq!(Decoder::length(5), ClientTransaction::decoder(&head, method).unwrap()); head.headers.set_raw("Content-Length", vec![b"10".to_vec(), b"11".to_vec()]); - ClientTransaction::decoder(&head).unwrap_err(); + ClientTransaction::decoder(&head, method).unwrap_err(); } #[cfg(feature = "nightly")] diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -541,7 +584,7 @@ mod tests { b.iter(|| { let mut vec = Vec::new(); - ServerTransaction::encode(head.clone(), &mut vec); + ServerTransaction::encode(head.clone(), true, &mut None, &mut vec); assert_eq!(vec.len(), len); ::test::black_box(vec); }) diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,6 @@ #![doc(html_root_url = "https://docs.rs/hyper/0.11.1")] #![deny(missing_docs)] -#![deny(warnings)] +//#![deny(warnings)] #![deny(missing_debug_implementations)] #![cfg_attr(all(test, feature = "nightly"), feature(test))] diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -12,7 +12,7 @@ use std::time::Duration; use hyper::client::{Client, Request, HttpConnector}; use hyper::{Method, StatusCode}; -use futures::Future; +use futures::{Future, Stream}; use futures::sync::oneshot; use tokio_core::reactor::{Core, Handle}; diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -93,6 +93,12 @@ macro_rules! test { $( assert_eq!(res.headers().get(), Some(&$response_headers)); )* + + let body = core.run(res.body().concat2()).unwrap(); + + let expected_res_body = Option::<&[u8]>::from($response_body) + .unwrap_or_default(); + assert_eq!(body.as_ref(), expected_res_body); } ); } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -225,6 +231,36 @@ test! { body: None, } + +test! { + name: client_head_ignores_body, + + server: + expected: "\ + HEAD /head HTTP/1.1\r\n\ + Host: {addr}\r\n\ + \r\n\ + ", + reply: "\ + HTTP/1.1 200 OK\r\n\ + Content-Length: 11\r\n\ + \r\n\ + Hello World\ + ", + + client: + request: + method: Head, + url: "http://{addr}/head", + headers: [], + body: None, + proxy: false, + response: + status: Ok, + headers: [], + body: None, +} + #[test] fn client_keep_alive() { let server = TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -16,182 +16,8 @@ use std::time::Duration; use hyper::server::{Http, Request, Response, Service, NewService}; -struct Serve { - addr: SocketAddr, - msg_rx: mpsc::Receiver<Msg>, - reply_tx: spmc::Sender<Reply>, - shutdown_signal: Option<oneshot::Sender<()>>, - thread: Option<thread::JoinHandle<()>>, -} - -impl Serve { - fn addr(&self) -> &SocketAddr { - &self.addr - } - - fn body(&self) -> Vec<u8> { - let mut buf = vec![]; - while let Ok(Msg::Chunk(msg)) = self.msg_rx.try_recv() { - buf.extend(&msg); - } - buf - } - - fn reply(&self) -> ReplyBuilder { - ReplyBuilder { - tx: &self.reply_tx - } - } -} - -struct ReplyBuilder<'a> { - tx: &'a spmc::Sender<Reply>, -} - -impl<'a> ReplyBuilder<'a> { - fn status(self, status: hyper::StatusCode) -> Self { - self.tx.send(Reply::Status(status)).unwrap(); - self - } - - fn header<H: hyper::header::Header>(self, header: H) -> Self { - let mut headers = hyper::Headers::new(); - headers.set(header); - self.tx.send(Reply::Headers(headers)).unwrap(); - self - } - - fn body<T: AsRef<[u8]>>(self, body: T) { - self.tx.send(Reply::Body(body.as_ref().into())).unwrap(); - } -} - -impl Drop for Serve { - fn drop(&mut self) { - drop(self.shutdown_signal.take()); - self.thread.take().unwrap().join().unwrap(); - } -} - -#[derive(Clone)] -struct TestService { - tx: Arc<Mutex<mpsc::Sender<Msg>>>, - reply: spmc::Receiver<Reply>, - _timeout: Option<Duration>, -} - -#[derive(Clone, Debug)] -enum Reply { - Status(hyper::StatusCode), - Headers(hyper::Headers), - Body(Vec<u8>), -} - -enum Msg { - //Head(Request), - Chunk(Vec<u8>), -} - -impl NewService for TestService { - type Request = Request; - type Response = Response; - type Error = hyper::Error; - - type Instance = TestService; - - fn new_service(&self) -> std::io::Result<TestService> { - Ok(self.clone()) - } - - -} - -impl Service for TestService { - type Request = Request; - type Response = Response; - type Error = hyper::Error; - type Future = Box<Future<Item=Response, Error=hyper::Error>>; - fn call(&self, req: Request) -> Self::Future { - let tx = self.tx.clone(); - let replies = self.reply.clone(); - req.body().for_each(move |chunk| { - tx.lock().unwrap().send(Msg::Chunk(chunk.to_vec())).unwrap(); - Ok(()) - }).map(move |_| { - let mut res = Response::new(); - while let Ok(reply) = replies.try_recv() { - match reply { - Reply::Status(s) => { - res.set_status(s); - }, - Reply::Headers(headers) => { - *res.headers_mut() = headers; - }, - Reply::Body(body) => { - res.set_body(body); - }, - } - } - res - }).boxed() - } - -} - -fn connect(addr: &SocketAddr) -> TcpStream { - let req = TcpStream::connect(addr).unwrap(); - req.set_read_timeout(Some(Duration::from_secs(1))).unwrap(); - req.set_write_timeout(Some(Duration::from_secs(1))).unwrap(); - req -} - -fn serve() -> Serve { - serve_with_options(Default::default()) -} - -#[derive(Default)] -struct ServeOptions { - keep_alive_disabled: bool, - timeout: Option<Duration>, -} - -fn serve_with_options(options: ServeOptions) -> Serve { - let _ = pretty_env_logger::init(); - - let (addr_tx, addr_rx) = mpsc::channel(); - let (msg_tx, msg_rx) = mpsc::channel(); - let (reply_tx, reply_rx) = spmc::channel(); - let (shutdown_tx, shutdown_rx) = oneshot::channel(); - - let addr = "127.0.0.1:0".parse().unwrap(); - - let keep_alive = !options.keep_alive_disabled; - let dur = options.timeout; - - let thread_name = format!("test-server-{:?}", dur); - let thread = thread::Builder::new().name(thread_name).spawn(move || { - let srv = Http::new().keep_alive(keep_alive).bind(&addr, TestService { - tx: Arc::new(Mutex::new(msg_tx.clone())), - _timeout: dur, - reply: reply_rx, - }).unwrap(); - addr_tx.send(srv.local_addr().unwrap()).unwrap(); - srv.run_until(shutdown_rx.then(|_| Ok(()))).unwrap(); - }).unwrap(); - - let addr = addr_rx.recv().unwrap(); - - Serve { - msg_rx: msg_rx, - reply_tx: reply_tx, - addr: addr, - shutdown_signal: Some(shutdown_tx), - thread: Some(thread), - } -} - #[test] -fn server_get_should_ignore_body() { +fn get_should_ignore_body() { let server = serve(); let mut req = connect(server.addr()); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -209,7 +35,7 @@ fn server_get_should_ignore_body() { } #[test] -fn server_get_with_body() { +fn get_with_body() { let server = serve(); let mut req = connect(server.addr()); req.write_all(b"\ diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -226,7 +52,7 @@ fn server_get_with_body() { } #[test] -fn server_get_fixed_response() { +fn get_fixed_response() { let foo_bar = b"foo bar baz"; let server = serve(); server.reply() diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -248,7 +74,7 @@ fn server_get_fixed_response() { } #[test] -fn server_get_chunked_response() { +fn get_chunked_response() { let foo_bar = b"foo bar baz"; let server = serve(); server.reply() diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -270,7 +96,7 @@ fn server_get_chunked_response() { } #[test] -fn server_get_chunked_response_with_ka() { +fn get_chunked_response_with_ka() { let foo_bar = b"foo bar baz"; let foo_bar_chunk = b"\r\nfoo bar baz\r\n0\r\n\r\n"; let server = serve(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -324,10 +150,8 @@ fn server_get_chunked_response_with_ka() { } } - - #[test] -fn server_post_with_chunked_body() { +fn post_with_chunked_body() { let server = serve(); let mut req = connect(server.addr()); req.write_all(b"\ diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -350,7 +174,7 @@ fn server_post_with_chunked_body() { } #[test] -fn server_empty_response_chunked() { +fn empty_response_chunked() { let server = serve(); server.reply() diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -384,7 +208,7 @@ fn server_empty_response_chunked() { } #[test] -fn server_empty_response_chunked_without_body_should_set_content_length() { +fn empty_response_chunked_without_body_should_set_content_length() { extern crate pretty_env_logger; let _ = pretty_env_logger::init(); let server = serve(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -414,7 +238,66 @@ fn server_empty_response_chunked_without_body_should_set_content_length() { } #[test] -fn server_keep_alive() { +fn head_response_can_send_content_length() { + extern crate pretty_env_logger; + let _ = pretty_env_logger::init(); + let server = serve(); + server.reply() + .status(hyper::Ok) + .header(hyper::header::ContentLength(1024)); + let mut req = connect(server.addr()); + req.write_all(b"\ + HEAD / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Connection: close\r\n\ + \r\n\ + ").unwrap(); + + let mut response = String::new(); + req.read_to_string(&mut response).unwrap(); + + assert!(response.contains("Content-Length: 1024\r\n")); + + let mut lines = response.lines(); + assert_eq!(lines.next(), Some("HTTP/1.1 200 OK")); + + let mut lines = lines.skip_while(|line| !line.is_empty()); + assert_eq!(lines.next(), Some("")); + assert_eq!(lines.next(), None); +} + +#[test] +fn response_does_not_set_chunked_if_body_not_allowed() { + extern crate pretty_env_logger; + let _ = pretty_env_logger::init(); + let server = serve(); + server.reply() + .status(hyper::StatusCode::NotModified) + .header(hyper::header::TransferEncoding::chunked()); + let mut req = connect(server.addr()); + req.write_all(b"\ + GET / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Connection: close\r\n\ + \r\n\ + ").unwrap(); + + let mut response = String::new(); + req.read_to_string(&mut response).unwrap(); + + assert!(!response.contains("Transfer-Encoding")); + + let mut lines = response.lines(); + assert_eq!(lines.next(), Some("HTTP/1.1 304 Not Modified")); + + // no body or 0\r\n\r\n + let mut lines = lines.skip_while(|line| !line.is_empty()); + assert_eq!(lines.next(), Some("")); + assert_eq!(lines.next(), None); +} + +#[test] +fn keep_alive() { let foo_bar = b"foo bar baz"; let server = serve(); server.reply() diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -467,8 +350,8 @@ fn server_keep_alive() { } #[test] -fn test_server_disable_keep_alive() { - let foo_bar = b"foo bar baz"; +fn disable_keep_alive() { + let foo_bar = b"foo bar baz"; let server = serve_with_options(ServeOptions { keep_alive_disabled: true, .. Default::default() diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -553,3 +436,183 @@ fn expect_continue() { let body = server.body(); assert_eq!(body, msg); } + +// ------------------------------------------------- +// the Server that is used to run all the tests with +// ------------------------------------------------- + +struct Serve { + addr: SocketAddr, + msg_rx: mpsc::Receiver<Msg>, + reply_tx: spmc::Sender<Reply>, + shutdown_signal: Option<oneshot::Sender<()>>, + thread: Option<thread::JoinHandle<()>>, +} + +impl Serve { + fn addr(&self) -> &SocketAddr { + &self.addr + } + + fn body(&self) -> Vec<u8> { + let mut buf = vec![]; + while let Ok(Msg::Chunk(msg)) = self.msg_rx.try_recv() { + buf.extend(&msg); + } + buf + } + + fn reply(&self) -> ReplyBuilder { + ReplyBuilder { + tx: &self.reply_tx + } + } +} + +struct ReplyBuilder<'a> { + tx: &'a spmc::Sender<Reply>, +} + +impl<'a> ReplyBuilder<'a> { + fn status(self, status: hyper::StatusCode) -> Self { + self.tx.send(Reply::Status(status)).unwrap(); + self + } + + fn header<H: hyper::header::Header>(self, header: H) -> Self { + let mut headers = hyper::Headers::new(); + headers.set(header); + self.tx.send(Reply::Headers(headers)).unwrap(); + self + } + + fn body<T: AsRef<[u8]>>(self, body: T) { + self.tx.send(Reply::Body(body.as_ref().into())).unwrap(); + } +} + +impl Drop for Serve { + fn drop(&mut self) { + drop(self.shutdown_signal.take()); + self.thread.take().unwrap().join().unwrap(); + } +} + +#[derive(Clone)] +struct TestService { + tx: Arc<Mutex<mpsc::Sender<Msg>>>, + reply: spmc::Receiver<Reply>, + _timeout: Option<Duration>, +} + +#[derive(Clone, Debug)] +enum Reply { + Status(hyper::StatusCode), + Headers(hyper::Headers), + Body(Vec<u8>), +} + +enum Msg { + //Head(Request), + Chunk(Vec<u8>), +} + +impl NewService for TestService { + type Request = Request; + type Response = Response; + type Error = hyper::Error; + + type Instance = TestService; + + fn new_service(&self) -> std::io::Result<TestService> { + Ok(self.clone()) + } + + +} + +impl Service for TestService { + type Request = Request; + type Response = Response; + type Error = hyper::Error; + type Future = Box<Future<Item=Response, Error=hyper::Error>>; + fn call(&self, req: Request) -> Self::Future { + let tx = self.tx.clone(); + let replies = self.reply.clone(); + req.body().for_each(move |chunk| { + tx.lock().unwrap().send(Msg::Chunk(chunk.to_vec())).unwrap(); + Ok(()) + }).map(move |_| { + let mut res = Response::new(); + while let Ok(reply) = replies.try_recv() { + match reply { + Reply::Status(s) => { + res.set_status(s); + }, + Reply::Headers(headers) => { + *res.headers_mut() = headers; + }, + Reply::Body(body) => { + res.set_body(body); + }, + } + } + res + }).boxed() + } + +} + +fn connect(addr: &SocketAddr) -> TcpStream { + let req = TcpStream::connect(addr).unwrap(); + req.set_read_timeout(Some(Duration::from_secs(1))).unwrap(); + req.set_write_timeout(Some(Duration::from_secs(1))).unwrap(); + req +} + +fn serve() -> Serve { + serve_with_options(Default::default()) +} + +#[derive(Default)] +struct ServeOptions { + keep_alive_disabled: bool, + timeout: Option<Duration>, +} + +fn serve_with_options(options: ServeOptions) -> Serve { + let _ = pretty_env_logger::init(); + + let (addr_tx, addr_rx) = mpsc::channel(); + let (msg_tx, msg_rx) = mpsc::channel(); + let (reply_tx, reply_rx) = spmc::channel(); + let (shutdown_tx, shutdown_rx) = oneshot::channel(); + + let addr = "127.0.0.1:0".parse().unwrap(); + + let keep_alive = !options.keep_alive_disabled; + let dur = options.timeout; + + let thread_name = format!("test-server-{:?}", dur); + let thread = thread::Builder::new().name(thread_name).spawn(move || { + let srv = Http::new().keep_alive(keep_alive).bind(&addr, TestService { + tx: Arc::new(Mutex::new(msg_tx.clone())), + _timeout: dur, + reply: reply_rx, + }).unwrap(); + addr_tx.send(srv.local_addr().unwrap()).unwrap(); + srv.run_until(shutdown_rx.then(|_| Ok(()))).unwrap(); + }).unwrap(); + + let addr = addr_rx.recv().unwrap(); + + Serve { + msg_rx: msg_rx, + reply_tx: reply_tx, + addr: addr, + shutdown_signal: Some(shutdown_tx), + thread: Some(thread), + } +} + +
Response without a body receives `Transfer-Encoding: chunked` I want a server to make a `304 Not Modified` response like this: ```rust Response::new() .with_status(StatusCode::NotModified) .with_header(ETag(etag)) .with_header(LastModified(last_modified)) ``` My problem is *hyper* sees the response without body (or without `Content-Length`) and adds a `Transfer-Encoding: chunked` to the headers ([here's the culprit](https://github.com/hyperium/hyper/blob/master/src/http/h1/parse.rs#L117-L130)). Am I using the API wrong or is this an error on hyper's side?
It's a bug in hyper. I've been working on this week actually, to better handle when message shouldn't have bodies. Besides 304, also 204, and also when the request verb would not allow a response body, like `HEAD` or `CONNECT`.
2017-07-13T19:19:31Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,182
hyperium__hyper-1182
[ "650" ]
97abb81b3cc271a6dd258da86559bc25ab77c652
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -57,6 +57,7 @@ pub use self::transfer_encoding::TransferEncoding; pub use self::upgrade::{Upgrade, Protocol, ProtocolName}; pub use self::user_agent::UserAgent; pub use self::vary::Vary; +pub use self::link::{Link, LinkValue, RelationType, MediaDesc}; #[doc(hidden)] #[macro_export] diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -391,3 +392,4 @@ mod transfer_encoding; mod upgrade; mod user_agent; mod vary; +mod link;
diff --git /dev/null b/src/header/common/link.rs new file mode 100644 --- /dev/null +++ b/src/header/common/link.rs @@ -0,0 +1,1110 @@ +use std::fmt; +use std::borrow::Cow; +use std::str::FromStr; +use std::ascii::AsciiExt; + +use mime::Mime; +use language_tags::LanguageTag; + +use header::parsing; +use header::{Header, HeaderFormat}; + +/// The `Link` header, defined in +/// [RFC5988](http://tools.ietf.org/html/rfc5988#section-5) +/// +/// # ABNF +/// ```plain +/// Link = "Link" ":" #link-value +/// link-value = "<" URI-Reference ">" *( ";" link-param ) +/// link-param = ( ( "rel" "=" relation-types ) +/// | ( "anchor" "=" <"> URI-Reference <"> ) +/// | ( "rev" "=" relation-types ) +/// | ( "hreflang" "=" Language-Tag ) +/// | ( "media" "=" ( MediaDesc | ( <"> MediaDesc <"> ) ) ) +/// | ( "title" "=" quoted-string ) +/// | ( "title*" "=" ext-value ) +/// | ( "type" "=" ( media-type | quoted-mt ) ) +/// | ( link-extension ) ) +/// link-extension = ( parmname [ "=" ( ptoken | quoted-string ) ] ) +/// | ( ext-name-star "=" ext-value ) +/// ext-name-star = parmname "*" ; reserved for RFC2231-profiled +/// ; extensions. Whitespace NOT +/// ; allowed in between. +/// ptoken = 1*ptokenchar +/// ptokenchar = "!" | "#" | "$" | "%" | "&" | "'" | "(" +/// | ")" | "*" | "+" | "-" | "." | "/" | DIGIT +/// | ":" | "<" | "=" | ">" | "?" | "@" | ALPHA +/// | "[" | "]" | "^" | "_" | "`" | "{" | "|" +/// | "}" | "~" +/// media-type = type-name "/" subtype-name +/// quoted-mt = <"> media-type <"> +/// relation-types = relation-type +/// | <"> relation-type *( 1*SP relation-type ) <"> +/// relation-type = reg-rel-type | ext-rel-type +/// reg-rel-type = LOALPHA *( LOALPHA | DIGIT | "." | "-" ) +/// ext-rel-type = URI +/// ``` +/// +/// # Example values +/// +/// `Link: <http://example.com/TheBook/chapter2>; rel="previous"; +/// title="previous chapter"` +/// +/// `Link: </TheBook/chapter2>; rel="previous"; title*=UTF-8'de'letztes%20Kapitel, +/// </TheBook/chapter4>; rel="next"; title*=UTF-8'de'n%c3%a4chstes%20Kapitel` +/// +/// # Examples +/// ``` +/// use hyper::header::{Headers, Link, LinkValue, RelationType}; +/// +/// let link_value = LinkValue::new("http://example.com/TheBook/chapter2") +/// .push_rel(RelationType::Previous) +/// .set_title("previous chapter"); +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// Link::new(vec![link_value]) +/// ); +/// ``` +#[derive(Clone, PartialEq, Debug)] +pub struct Link { + /// A list of the `link-value`s of the Link entity-header. + values: Vec<LinkValue> +} + +/// A single `link-value` of a `Link` header, based on: +/// [RFC5988](http://tools.ietf.org/html/rfc5988#section-5) +#[derive(Clone, PartialEq, Debug)] +pub struct LinkValue { + /// Target IRI: `link-value`. + link: Cow<'static, str>, + + /// Forward Relation Types: `rel`. + rel: Option<Vec<RelationType>>, + + /// Context IRI: `anchor`. + anchor: Option<String>, + + /// Reverse Relation Types: `rev`. + rev: Option<Vec<RelationType>>, + + /// Hint on the language of the result of dereferencing + /// the link: `hreflang`. + href_lang: Option<Vec<LanguageTag>>, + + /// Destination medium or media: `media`. + media_desc: Option<Vec<MediaDesc>>, + + /// Label of the destination of a Link: `title`. + title: Option<String>, + + /// The `title` encoded in a different charset: `title*`. + title_star: Option<String>, + + /// Hint on the media type of the result of dereferencing + /// the link: `type`. + media_type: Option<Mime>, +} + +/// A Media Descriptors Enum based on: +/// https://www.w3.org/TR/html401/types.html#h-6.13 +#[derive(Clone, PartialEq, Debug)] +pub enum MediaDesc { + /// screen. + Screen, + /// tty. + Tty, + /// tv. + Tv, + /// projection. + Projection, + /// handheld. + Handheld, + /// print. + Print, + /// braille. + Braille, + /// aural. + Aural, + /// all. + All, + /// Unrecognized media descriptor extension. + Extension(String) +} + +/// A Link Relation Type Enum based on: +/// [RFC5988](https://tools.ietf.org/html/rfc5988#section-6.2.2) +#[derive(Clone, PartialEq, Debug)] +pub enum RelationType { + /// alternate. + Alternate, + /// appendix. + Appendix, + /// bookmark. + Bookmark, + /// chapter. + Chapter, + /// contents. + Contents, + /// copyright. + Copyright, + /// current. + Current, + /// describedby. + DescribedBy, + /// edit. + Edit, + /// edit-media. + EditMedia, + /// enclosure. + Enclosure, + /// first. + First, + /// glossary. + Glossary, + /// help. + Help, + /// hub. + Hub, + /// index. + Index, + /// last. + Last, + /// latest-version. + LatestVersion, + /// license. + License, + /// next. + Next, + /// next-archive. + NextArchive, + /// payment. + Payment, + /// prev. + Prev, + /// predecessor-version. + PredecessorVersion, + /// previous. + Previous, + /// prev-archive. + PrevArchive, + /// related. + Related, + /// replies. + Replies, + /// section. + Section, + /// self. + RelationTypeSelf, + /// service. + Service, + /// start. + Start, + /// stylesheet. + Stylesheet, + /// subsection. + Subsection, + /// successor-version. + SuccessorVersion, + /// up. + Up, + /// versionHistory. + VersionHistory, + /// via. + Via, + /// working-copy. + WorkingCopy, + /// working-copy-of. + WorkingCopyOf, + /// ext-rel-type. + ExtRelType(String) +} + +//////////////////////////////////////////////////////////////////////////////// +// Struct methods +//////////////////////////////////////////////////////////////////////////////// + +impl Link { + /// Create `Link` from a `Vec<LinkValue>`. + pub fn new(link_values: Vec<LinkValue>) -> Link { + Link { values: link_values } + } + + /// Get the `Link` header's `LinkValue`s. + pub fn values(&self) -> &[LinkValue] { + self.values.as_ref() + } + + /// Add a `LinkValue` instance to the `Link` header's values. + pub fn push_value(&mut self, link_value: LinkValue) { + self.values.push(link_value); + } +} + +impl LinkValue { + /// Create `LinkValue` from URI-Reference. + pub fn new<T>(uri: T) -> LinkValue + where T: Into<Cow<'static, str>> { + LinkValue { + link: uri.into(), + rel: None, + anchor: None, + rev: None, + href_lang: None, + media_desc: None, + title: None, + title_star: None, + media_type: None, + } + } + + /// Get the `LinkValue`'s value. + pub fn link(&self) -> &str { + self.link.as_ref() + } + + /// Get the `LinkValue`'s `rel` parameter(s). + pub fn rel(&self) -> Option<&[RelationType]> { + self.rel.as_ref().map(AsRef::as_ref) + } + + /// Get the `LinkValue`'s `anchor` parameter. + pub fn anchor(&self) -> Option<&str> { + self.anchor.as_ref().map(AsRef::as_ref) + } + + /// Get the `LinkValue`'s `rev` parameter(s). + pub fn rev(&self) -> Option<&[RelationType]> { + self.rev.as_ref().map(AsRef::as_ref) + } + + /// Get the `LinkValue`'s `hreflang` parameter(s). + pub fn href_lang(&self) -> Option<&[LanguageTag]> { + self.href_lang.as_ref().map(AsRef::as_ref) + } + + /// Get the `LinkValue`'s `media` parameter(s). + pub fn media_desc(&self) -> Option<&[MediaDesc]> { + self.media_desc.as_ref().map(AsRef::as_ref) + } + + /// Get the `LinkValue`'s `title` parameter. + pub fn title(&self) -> Option<&str> { + self.title.as_ref().map(AsRef::as_ref) + } + + /// Get the `LinkValue`'s `title*` parameter. + pub fn title_star(&self) -> Option<&str> { + self.title_star.as_ref().map(AsRef::as_ref) + } + + /// Get the `LinkValue`'s `type` parameter. + pub fn media_type(&self) -> Option<&Mime> { + self.media_type.as_ref() + } + + /// Add a `RelationType` to the `LinkValue`'s `rel` parameter. + pub fn push_rel(mut self, rel: RelationType) -> LinkValue { + let mut v = self.rel.take().unwrap_or(Vec::new()); + + v.push(rel); + + self.rel = Some(v); + + self + } + + /// Set `LinkValue`'s `anchor` parameter. + pub fn set_anchor<T: Into<String>>(mut self, anchor: T) -> LinkValue { + self.anchor = Some(anchor.into()); + + self + } + + /// Add a `RelationType` to the `LinkValue`'s `rev` parameter. + pub fn push_rev(mut self, rev: RelationType) -> LinkValue { + let mut v = self.rev.take().unwrap_or(Vec::new()); + + v.push(rev); + + self.rev = Some(v); + + self + } + + /// Add a `LanguageTag` to the `LinkValue`'s `hreflang` parameter. + pub fn push_href_lang(mut self, language_tag: LanguageTag) -> LinkValue { + let mut v = self.href_lang.take().unwrap_or(Vec::new()); + + v.push(language_tag); + + self.href_lang = Some(v); + + self + } + + /// Add a `MediaDesc` to the `LinkValue`'s `media_desc` parameter. + pub fn push_media_desc(mut self, media_desc: MediaDesc) -> LinkValue { + let mut v = self.media_desc.take().unwrap_or(Vec::new()); + + v.push(media_desc); + + self.media_desc = Some(v); + + self + } + + /// Set `LinkValue`'s `title` parameter. + pub fn set_title<T: Into<String>>(mut self, title: T) -> LinkValue { + self.title = Some(title.into()); + + self + } + + /// Set `LinkValue`'s `title*` parameter. + pub fn set_title_star<T: Into<String>>(mut self, title_star: T) -> LinkValue { + self.title_star = Some(title_star.into()); + + self + } + + /// Set `LinkValue`'s `type` parameter. + pub fn set_media_type(mut self, media_type: Mime) -> LinkValue { + self.media_type = Some(media_type); + + self + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Trait implementations +//////////////////////////////////////////////////////////////////////////////// + +impl Header for Link { + fn header_name() -> &'static str { + static NAME: &'static str = "Link"; + NAME + } + + fn parse_header(raw: &[Vec<u8>]) -> ::Result<Link> { + // If more that one `Link` headers are present in a request's + // headers they are combined in a single `Link` header containing + // all the `link-value`s present in each of those `Link` headers. + raw.iter() + .map(|v| parsing::from_raw_str::<Link>(&v)) + .fold(None, |p, c| match (p, c) { + (None, c) => Some(c), + (e @ Some(Err(_)), _) => e, + (Some(Ok(mut p)), Ok(c)) => { + p.values.extend(c.values); + + Some(Ok(p)) + } + _ => Some(Err(::Error::Header)), + }) + .unwrap_or(Err(::Error::Header)) + } +} +impl HeaderFormat for Link { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt_delimited(f, self.values.as_slice(), ", ", ("", "")) + } +} + +impl fmt::Display for Link { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.fmt_header(f) + } +} + +impl fmt::Display for LinkValue { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(write!(f, "<{}>", self.link)); + + if let Some(ref rel) = self.rel { + try!(fmt_delimited(f, rel.as_slice(), " ", ("; rel=\"", "\""))); + } + if let Some(ref anchor) = self.anchor { + try!(write!(f, "; anchor=\"{}\"", anchor)); + } + if let Some(ref rev) = self.rev { + try!(fmt_delimited(f, rev.as_slice(), " ", ("; rev=\"", "\""))); + } + if let Some(ref href_lang) = self.href_lang { + for tag in href_lang { + try!(write!(f, "; hreflang={}", tag)); + } + } + if let Some(ref media_desc) = self.media_desc { + try!(fmt_delimited(f, media_desc.as_slice(), ", ", ("; media=\"", "\""))); + } + if let Some(ref title) = self.title { + try!(write!(f, "; title=\"{}\"", title)); + } + if let Some(ref title_star) = self.title_star { + try!(write!(f, "; title*={}", title_star)); + } + if let Some(ref media_type) = self.media_type { + try!(write!(f, "; type=\"{}\"", media_type)); + } + + Ok(()) + } +} + +impl FromStr for Link { + type Err = ::Error; + + fn from_str(s: &str) -> ::Result<Link> { + // Create a split iterator with delimiters: `;`, `,` + let link_split = SplitAsciiUnquoted::new(s, ";,"); + + let mut link_values: Vec<LinkValue> = Vec::new(); + + // Loop over the splits parsing the Link header into + // a `Vec<LinkValue>` + for segment in link_split { + // Parse the `Target IRI` + // https://tools.ietf.org/html/rfc5988#section-5.1 + if segment.trim().starts_with('<') { + link_values.push( + match verify_and_trim(segment.trim(), (b'<', b'>')) { + Err(_) => return Err(::Error::Header), + Ok(s) => { + LinkValue { + link: s.to_owned().into(), + rel: None, + anchor: None, + rev: None, + href_lang: None, + media_desc: None, + title: None, + title_star: None, + media_type: None, + } + }, + } + ); + } else { + // Parse the current link-value's parameters + let mut link_param_split = segment.splitn(2, '='); + + let link_param_name = match link_param_split.next() { + None => return Err(::Error::Header), + Some(p) => p.trim(), + }; + + let mut link_header = match link_values.last_mut() { + None => return Err(::Error::Header), + Some(l) => l, + }; + + if "rel".eq_ignore_ascii_case(link_param_name) { + // Parse relation type: `rel`. + // https://tools.ietf.org/html/rfc5988#section-5.3 + if link_header.rel.is_none() { + link_header.rel = match link_param_split.next() { + None => return Err(::Error::Header), + Some("") => return Err(::Error::Header), + Some(s) => { + s.trim_matches(|c: char| c == '"' || c.is_whitespace()) + .split(' ') + .map(|t| t.trim().parse()) + .collect::<Result<Vec<RelationType>, _>>() + .or_else(|_| return Err(::Error::Header)) + .ok() + }, + }; + } + } else if "anchor".eq_ignore_ascii_case(link_param_name) { + // Parse the `Context IRI`. + // https://tools.ietf.org/html/rfc5988#section-5.2 + link_header.anchor = match link_param_split.next() { + None => return Err(::Error::Header), + Some("") => return Err(::Error::Header), + Some(s) => match verify_and_trim(s.trim(), (b'"', b'"')) { + Err(_) => return Err(::Error::Header), + Ok(a) => Some(String::from(a)), + }, + }; + } else if "rev".eq_ignore_ascii_case(link_param_name) { + // Parse relation type: `rev`. + // https://tools.ietf.org/html/rfc5988#section-5.3 + if link_header.rev.is_none() { + link_header.rev = match link_param_split.next() { + None => return Err(::Error::Header), + Some("") => return Err(::Error::Header), + Some(s) => { + s.trim_matches(|c: char| c == '"' || c.is_whitespace()) + .split(' ') + .map(|t| t.trim().parse()) + .collect::<Result<Vec<RelationType>, _>>() + .or_else(|_| return Err(::Error::Header)) + .ok() + }, + } + } + } else if "hreflang".eq_ignore_ascii_case(link_param_name) { + // Parse target attribute: `hreflang`. + // https://tools.ietf.org/html/rfc5988#section-5.4 + let mut v = link_header.href_lang.take().unwrap_or(Vec::new()); + + v.push( + match link_param_split.next() { + None => return Err(::Error::Header), + Some("") => return Err(::Error::Header), + Some(s) => match s.trim().parse() { + Err(_) => return Err(::Error::Header), + Ok(t) => t, + }, + } + ); + + link_header.href_lang = Some(v); + } else if "media".eq_ignore_ascii_case(link_param_name) { + // Parse target attribute: `media`. + // https://tools.ietf.org/html/rfc5988#section-5.4 + if link_header.media_desc.is_none() { + link_header.media_desc = match link_param_split.next() { + None => return Err(::Error::Header), + Some("") => return Err(::Error::Header), + Some(s) => { + s.trim_matches(|c: char| c == '"' || c.is_whitespace()) + .split(',') + .map(|t| t.trim().parse()) + .collect::<Result<Vec<MediaDesc>, _>>() + .or_else(|_| return Err(::Error::Header)) + .ok() + }, + }; + } + } else if "title".eq_ignore_ascii_case(link_param_name) { + // Parse target attribute: `title`. + // https://tools.ietf.org/html/rfc5988#section-5.4 + if link_header.title.is_none() { + link_header.title = match link_param_split.next() { + None => return Err(::Error::Header), + Some("") => return Err(::Error::Header), + Some(s) => match verify_and_trim(s.trim(), (b'"', b'"')) { + Err(_) => return Err(::Error::Header), + Ok(t) => Some(String::from(t)), + }, + }; + } + } else if "title*".eq_ignore_ascii_case(link_param_name) { + // Parse target attribute: `title*`. + // https://tools.ietf.org/html/rfc5988#section-5.4 + // + // Definition of `ext-value`: + // https://tools.ietf.org/html/rfc5987#section-3.2.1 + if link_header.title_star.is_none() { + link_header.title_star = match link_param_split.next() { + None => return Err(::Error::Header), + Some("") => return Err(::Error::Header), + Some(s) => Some(String::from(s.trim())), + }; + } + } else if "type".eq_ignore_ascii_case(link_param_name) { + // Parse target attribute: `type`. + // https://tools.ietf.org/html/rfc5988#section-5.4 + if link_header.media_type.is_none() { + link_header.media_type = match link_param_split.next() { + None => return Err(::Error::Header), + Some("") => return Err(::Error::Header), + Some(s) => match verify_and_trim(s.trim(), (b'"', b'"')) { + Err(_) => return Err(::Error::Header), + Ok(t) => match t.parse() { + Err(_) => return Err(::Error::Header), + Ok(m) => Some(m), + }, + }, + + }; + } + } else { + return Err(::Error::Header); + } + } + } + + Ok(Link::new(link_values)) + } +} + +impl fmt::Display for MediaDesc { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + MediaDesc::Screen => write!(f, "screen"), + MediaDesc::Tty => write!(f, "tty"), + MediaDesc::Tv => write!(f, "tv"), + MediaDesc::Projection => write!(f, "projection"), + MediaDesc::Handheld => write!(f, "handheld"), + MediaDesc::Print => write!(f, "print"), + MediaDesc::Braille => write!(f, "braille"), + MediaDesc::Aural => write!(f, "aural"), + MediaDesc::All => write!(f, "all"), + MediaDesc::Extension(ref other) => write!(f, "{}", other), + } + } +} + +impl FromStr for MediaDesc { + type Err = ::Error; + + fn from_str(s: &str) -> ::Result<MediaDesc> { + match s { + "screen" => Ok(MediaDesc::Screen), + "tty" => Ok(MediaDesc::Tty), + "tv" => Ok(MediaDesc::Tv), + "projection" => Ok(MediaDesc::Projection), + "handheld" => Ok(MediaDesc::Handheld), + "print" => Ok(MediaDesc::Print), + "braille" => Ok(MediaDesc::Braille), + "aural" => Ok(MediaDesc::Aural), + "all" => Ok(MediaDesc::All), + _ => Ok(MediaDesc::Extension(String::from(s))), + } + } +} + +impl fmt::Display for RelationType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + RelationType::Alternate => write!(f, "alternate"), + RelationType::Appendix => write!(f, "appendix"), + RelationType::Bookmark => write!(f, "bookmark"), + RelationType::Chapter => write!(f, "chapter"), + RelationType::Contents => write!(f, "contents"), + RelationType::Copyright => write!(f, "copyright"), + RelationType::Current => write!(f, "current"), + RelationType::DescribedBy => write!(f, "describedby"), + RelationType::Edit => write!(f, "edit"), + RelationType::EditMedia => write!(f, "edit-media"), + RelationType::Enclosure => write!(f, "enclosure"), + RelationType::First => write!(f, "first"), + RelationType::Glossary => write!(f, "glossary"), + RelationType::Help => write!(f, "help"), + RelationType::Hub => write!(f, "hub"), + RelationType::Index => write!(f, "index"), + RelationType::Last => write!(f, "last"), + RelationType::LatestVersion => write!(f, "latest-version"), + RelationType::License => write!(f, "license"), + RelationType::Next => write!(f, "next"), + RelationType::NextArchive => write!(f, "next-archive"), + RelationType::Payment => write!(f, "payment"), + RelationType::Prev => write!(f, "prev"), + RelationType::PredecessorVersion => write!(f, "predecessor-version"), + RelationType::Previous => write!(f, "previous"), + RelationType::PrevArchive => write!(f, "prev-archive"), + RelationType::Related => write!(f, "related"), + RelationType::Replies => write!(f, "replies"), + RelationType::Section => write!(f, "section"), + RelationType::RelationTypeSelf => write!(f, "self"), + RelationType::Service => write!(f, "service"), + RelationType::Start => write!(f, "start"), + RelationType::Stylesheet => write!(f, "stylesheet"), + RelationType::Subsection => write!(f, "subsection"), + RelationType::SuccessorVersion => write!(f, "successor-version"), + RelationType::Up => write!(f, "up"), + RelationType::VersionHistory => write!(f, "version-history"), + RelationType::Via => write!(f, "via"), + RelationType::WorkingCopy => write!(f, "working-copy"), + RelationType::WorkingCopyOf => write!(f, "working-copy-of"), + RelationType::ExtRelType(ref uri) => write!(f, "{}", uri), + } + } +} + +impl FromStr for RelationType { + type Err = ::Error; + + fn from_str(s: &str) -> ::Result<RelationType> { + if "alternate".eq_ignore_ascii_case(s) { + Ok(RelationType::Alternate) + } else if "appendix".eq_ignore_ascii_case(s) { + Ok(RelationType::Appendix) + } else if "bookmark".eq_ignore_ascii_case(s) { + Ok(RelationType::Bookmark) + } else if "chapter".eq_ignore_ascii_case(s) { + Ok(RelationType::Chapter) + } else if "contents".eq_ignore_ascii_case(s) { + Ok(RelationType::Contents) + } else if "copyright".eq_ignore_ascii_case(s) { + Ok(RelationType::Copyright) + } else if "current".eq_ignore_ascii_case(s) { + Ok(RelationType::Current) + } else if "describedby".eq_ignore_ascii_case(s) { + Ok(RelationType::DescribedBy) + } else if "edit".eq_ignore_ascii_case(s) { + Ok(RelationType::Edit) + } else if "edit-media".eq_ignore_ascii_case(s) { + Ok(RelationType::EditMedia) + } else if "enclosure".eq_ignore_ascii_case(s) { + Ok(RelationType::Enclosure) + } else if "first".eq_ignore_ascii_case(s) { + Ok(RelationType::First) + } else if "glossary".eq_ignore_ascii_case(s) { + Ok(RelationType::Glossary) + } else if "help".eq_ignore_ascii_case(s) { + Ok(RelationType::Help) + } else if "hub".eq_ignore_ascii_case(s) { + Ok(RelationType::Hub) + } else if "index".eq_ignore_ascii_case(s) { + Ok(RelationType::Index) + } else if "last".eq_ignore_ascii_case(s) { + Ok(RelationType::Last) + } else if "latest-version".eq_ignore_ascii_case(s) { + Ok(RelationType::LatestVersion) + } else if "license".eq_ignore_ascii_case(s) { + Ok(RelationType::License) + } else if "next".eq_ignore_ascii_case(s) { + Ok(RelationType::Next) + } else if "next-archive".eq_ignore_ascii_case(s) { + Ok(RelationType::NextArchive) + } else if "payment".eq_ignore_ascii_case(s) { + Ok(RelationType::Payment) + } else if "prev".eq_ignore_ascii_case(s) { + Ok(RelationType::Prev) + } else if "predecessor-version".eq_ignore_ascii_case(s) { + Ok(RelationType::PredecessorVersion) + } else if "previous".eq_ignore_ascii_case(s) { + Ok(RelationType::Previous) + } else if "prev-archive".eq_ignore_ascii_case(s) { + Ok(RelationType::PrevArchive) + } else if "related".eq_ignore_ascii_case(s) { + Ok(RelationType::Related) + } else if "replies".eq_ignore_ascii_case(s) { + Ok(RelationType::Replies) + } else if "section".eq_ignore_ascii_case(s) { + Ok(RelationType::Section) + } else if "self".eq_ignore_ascii_case(s) { + Ok(RelationType::RelationTypeSelf) + } else if "service".eq_ignore_ascii_case(s) { + Ok(RelationType::Service) + } else if "start".eq_ignore_ascii_case(s) { + Ok(RelationType::Start) + } else if "stylesheet".eq_ignore_ascii_case(s) { + Ok(RelationType::Stylesheet) + } else if "subsection".eq_ignore_ascii_case(s) { + Ok(RelationType::Subsection) + } else if "successor-version".eq_ignore_ascii_case(s) { + Ok(RelationType::SuccessorVersion) + } else if "up".eq_ignore_ascii_case(s) { + Ok(RelationType::Up) + } else if "version-history".eq_ignore_ascii_case(s) { + Ok(RelationType::VersionHistory) + } else if "via".eq_ignore_ascii_case(s) { + Ok(RelationType::Via) + } else if "working-copy".eq_ignore_ascii_case(s) { + Ok(RelationType::WorkingCopy) + } else if "working-copy-of".eq_ignore_ascii_case(s) { + Ok(RelationType::WorkingCopyOf) + } else { + Ok(RelationType::ExtRelType(String::from(s))) + } + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Utilities +//////////////////////////////////////////////////////////////////////////////// + +struct SplitAsciiUnquoted<'a> { + src: &'a str, + pos: usize, + del: &'a str +} + +impl<'a> SplitAsciiUnquoted<'a> { + fn new(s: &'a str, d: &'a str) -> SplitAsciiUnquoted<'a> { + SplitAsciiUnquoted{ + src: s, + pos: 0, + del: d, + } + } +} + +impl<'a> Iterator for SplitAsciiUnquoted<'a> { + type Item = &'a str; + + fn next(&mut self) -> Option<&'a str> { + if self.pos < self.src.len() { + let prev_pos = self.pos; + let mut pos = self.pos; + + let mut in_quotes = false; + + for c in self.src[prev_pos..].as_bytes().iter() { + in_quotes ^= *c == b'"'; + + // Ignore `c` if we're `in_quotes`. + if !in_quotes && self.del.as_bytes().contains(c) { + break; + } + + pos += 1; + } + + self.pos = pos + 1; + + Some(&self.src[prev_pos..pos]) + } else { + None + } + } +} + +fn fmt_delimited<T: fmt::Display>(f: &mut fmt::Formatter, p: &[T], d: &str, b: (&str, &str)) -> fmt::Result { + if p.len() != 0 { + // Write a starting string `b.0` before the first element + try!(write!(f, "{}{}", b.0, p[0])); + + for i in &p[1..] { + // Write the next element preceded by the delimiter `d` + try!(write!(f, "{}{}", d, i)); + } + + // Write a ending string `b.1` before the first element + try!(write!(f, "{}", b.1)); + } + + Ok(()) +} + +fn verify_and_trim(s: &str, b: (u8, u8)) -> ::Result<&str> { + let length = s.len(); + let byte_array = s.as_bytes(); + + // Verify that `s` starts with `b.0` and ends with `b.1` and return + // the contained substring after triming whitespace. + if length > 1 && b.0 == byte_array[0] && b.1 == byte_array[length - 1] { + Ok(s.trim_matches( + |c: char| c == b.0 as char || c == b.1 as char || c.is_whitespace()) + ) + } else { + Err(::Error::Header) + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Tests +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(test)] +mod tests { + use std::fmt; + use std::fmt::Write; + + use super::{Link, LinkValue, MediaDesc, RelationType, SplitAsciiUnquoted}; + use super::{fmt_delimited, verify_and_trim}; + + use header::Header; + + use buffer::BufReader; + use mock::MockStream; + use http::h1::parse_request; + + use mime::Mime; + use mime::TopLevel::Text; + use mime::SubLevel::Plain; + + #[test] + fn test_link() { + let link_value = LinkValue::new("http://example.com/TheBook/chapter2") + .push_rel(RelationType::Previous) + .push_rev(RelationType::Next) + .set_title("previous chapter"); + + let link_header = b"<http://example.com/TheBook/chapter2>; \ + rel=\"previous\"; rev=next; title=\"previous chapter\""; + + let expected_link = Link::new(vec![link_value]); + + let link = Header::parse_header(&vec![link_header.to_vec()]); + assert_eq!(link.ok(), Some(expected_link)); + } + + #[test] + fn test_link_multiple_values() { + let first_link = LinkValue::new("/TheBook/chapter2") + .push_rel(RelationType::Previous) + .set_title_star("UTF-8'de'letztes%20Kapitel"); + + let second_link = LinkValue::new("/TheBook/chapter4") + .push_rel(RelationType::Next) + .set_title_star("UTF-8'de'n%c3%a4chstes%20Kapitel"); + + let link_header = b"</TheBook/chapter2>; \ + rel=\"previous\"; title*=UTF-8'de'letztes%20Kapitel, \ + </TheBook/chapter4>; \ + rel=\"next\"; title*=UTF-8'de'n%c3%a4chstes%20Kapitel"; + + let expected_link = Link::new(vec![first_link, second_link]); + + let link = Header::parse_header(&vec![link_header.to_vec()]); + assert_eq!(link.ok(), Some(expected_link)); + } + + #[test] + fn test_link_all_attributes() { + let link_value = LinkValue::new("http://example.com/TheBook/chapter2") + .push_rel(RelationType::Previous) + .set_anchor("../anchor/example/") + .push_rev(RelationType::Next) + .push_href_lang(langtag!(de)) + .push_media_desc(MediaDesc::Screen) + .set_title("previous chapter") + .set_title_star("title* unparsed") + .set_media_type(Mime(Text, Plain, vec![])); + + let link_header = b"<http://example.com/TheBook/chapter2>; \ + rel=\"previous\"; anchor=\"../anchor/example/\"; \ + rev=\"next\"; hreflang=de; media=\"screen\"; \ + title=\"previous chapter\"; title*=title* unparsed; \ + type=\"text/plain\""; + + let expected_link = Link::new(vec![link_value]); + + let link = Header::parse_header(&vec![link_header.to_vec()]); + assert_eq!(link.ok(), Some(expected_link)); + } + + #[test] + fn test_link_multiple_link_headers() { + let first_link = LinkValue::new("/TheBook/chapter2") + .push_rel(RelationType::Previous) + .set_title_star("UTF-8'de'letztes%20Kapitel"); + + let second_link = LinkValue::new("/TheBook/chapter4") + .push_rel(RelationType::Next) + .set_title_star("UTF-8'de'n%c3%a4chstes%20Kapitel"); + + let third_link = LinkValue::new("http://example.com/TheBook/chapter2") + .push_rel(RelationType::Previous) + .push_rev(RelationType::Next) + .set_title("previous chapter"); + + let expected_link = Link::new(vec![first_link, second_link, third_link]); + + let mut raw = MockStream::with_input(b"GET /super_short_uri/and_whatever HTTP/1.1\r\nHost: \ + hyper.rs\r\nAccept: a lot of things\r\nAccept-Charset: \ + utf8\r\nAccept-Encoding: *\r\nLink: </TheBook/chapter2>; \ + rel=\"previous\"; title*=UTF-8'de'letztes%20Kapitel, \ + </TheBook/chapter4>; rel=\"next\"; title*=\ + UTF-8'de'n%c3%a4chstes%20Kapitel\r\n\ + Access-Control-Allow-Credentials: None\r\nLink: \ + <http://example.com/TheBook/chapter2>; \ + rel=\"previous\"; rev=next; title=\"previous chapter\"\ + \r\n\r\n"); + + let mut buf = BufReader::new(&mut raw); + let res = parse_request(&mut buf).unwrap(); + + let link = res.headers.get::<Link>().unwrap(); + + assert_eq!(*link, expected_link); + } + + #[test] + fn test_link_display() { + let link_value = LinkValue::new("http://example.com/TheBook/chapter2") + .push_rel(RelationType::Previous) + .set_anchor("/anchor/example/") + .push_rev(RelationType::Next) + .push_href_lang(langtag!(de)) + .push_media_desc(MediaDesc::Screen) + .set_title("previous chapter") + .set_title_star("title* unparsed") + .set_media_type(Mime(Text, Plain, vec![])); + + let link = Link::new(vec![link_value]); + + let mut link_header = String::new(); + write!(&mut link_header, "{}", link).unwrap(); + + let expected_link_header = "<http://example.com/TheBook/chapter2>; \ + rel=\"previous\"; anchor=\"/anchor/example/\"; \ + rev=\"next\"; hreflang=de; media=\"screen\"; \ + title=\"previous chapter\"; title*=title* unparsed; \ + type=\"text/plain\""; + + assert_eq!(link_header, expected_link_header); + } + + #[test] + fn test_link_parsing_errors() { + let link_a = b"http://example.com/TheBook/chapter2; \ + rel=\"previous\"; rev=next; title=\"previous chapter\""; + + let mut err: Result<Link, _> = Header::parse_header(&vec![link_a.to_vec()]); + assert_eq!(err.is_err(), true); + + let link_b = b"<http://example.com/TheBook/chapter2>; \ + =\"previous\"; rev=next; title=\"previous chapter\""; + + err = Header::parse_header(&vec![link_b.to_vec()]); + assert_eq!(err.is_err(), true); + + let link_c = b"<http://example.com/TheBook/chapter2>; \ + rel=; rev=next; title=\"previous chapter\""; + + err = Header::parse_header(&vec![link_c.to_vec()]); + assert_eq!(err.is_err(), true); + + let link_d = b"<http://example.com/TheBook/chapter2>; \ + rel=\"previous\"; rev=next; title="; + + err = Header::parse_header(&vec![link_d.to_vec()]); + assert_eq!(err.is_err(), true); + + let link_e = b"<http://example.com/TheBook/chapter2>; \ + rel=\"previous\"; rev=next; attr=unknown"; + + err = Header::parse_header(&vec![link_e.to_vec()]); + assert_eq!(err.is_err(), true); + } + + #[test] + fn test_link_split_ascii_unquoted_iterator() { + let string = "some, text; \"and, more; in quotes\", or not"; + let mut string_split = SplitAsciiUnquoted::new(string, ";,"); + + assert_eq!(Some("some"), string_split.next()); + assert_eq!(Some(" text"), string_split.next()); + assert_eq!(Some(" \"and, more; in quotes\""), string_split.next()); + assert_eq!(Some(" or not"), string_split.next()); + assert_eq!(None, string_split.next()); + } + + #[test] + fn test_link_fmt_delimited() { + struct TestFormatterStruct<'a> { v: Vec<&'a str> }; + + impl<'a> fmt::Display for TestFormatterStruct<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt_delimited(f, self.v.as_slice(), ", ", (">>", "<<")) + } + } + + let test_formatter = TestFormatterStruct { v: vec!["first", "second"] }; + + let mut string = String::new(); + write!(&mut string, "{}", test_formatter).unwrap(); + + let expected_string = ">>first, second<<"; + + assert_eq!(string, expected_string); + } + + #[test] + fn test_link_verify_and_trim() { + let string = verify_and_trim("> some string <", (b'>', b'<')); + assert_eq!(string.ok(), Some("some string")); + + let err = verify_and_trim(" > some string <", (b'>', b'<')); + assert_eq!(err.is_err(), true); + } +} + +bench_header!(bench_link, Link, { vec![b"<http://example.com/TheBook/chapter2>; rel=\"previous\"; rev=next; title=\"previous chapter\"; type=\"text/html\"; media=\"screen, tty\"".to_vec()] });
Link header Currently, as far as I know there's no facility to parse and generate Link headers, It would be very useful if we had one, many APIs (including github) uses it to navigate. Do we plan to add support for it? http://www.w3.org/wiki/LinkHeader http://www.rfc-editor.org/rfc/rfc5988.txt
Sounds fine to me. It seems like this header is more complicated than others, just by judging it's ABNF: ``` ABNF Link = "Link" ":" #link-value link-value = "<" URI-Reference ">" *( ";" link-param ) link-param = ( ( "rel" "=" relation-types ) | ( "anchor" "=" <"> URI-Reference <"> ) | ( "rev" "=" relation-types ) | ( "hreflang" "=" Language-Tag ) | ( "media" "=" ( MediaDesc | ( <"> MediaDesc <"> ) ) ) | ( "title" "=" quoted-string ) | ( "title*" "=" ext-value ) | ( "type" "=" ( media-type | quoted-mt ) ) | ( link-extension ) ) link-extension = ( parmname [ "=" ( ptoken | quoted-string ) ] ) | ( ext-name-star "=" ext-value ) ext-name-star = parmname "*" ; reserved for RFC2231-profiled ; extensions. Whitespace NOT ; allowed in between. ptoken = 1*ptokenchar ptokenchar = "!" | "#" | "$" | "%" | "&" | "'" | "(" | ")" | "*" | "+" | "-" | "." | "/" | DIGIT | ":" | "<" | "=" | ">" | "?" | "@" | ALPHA | "[" | "]" | "^" | "_" | "`" | "{" | "|" | "}" | "~" media-type = type-name "/" subtype-name quoted-mt = <"> media-type <"> relation-types = relation-type | <"> relation-type *( 1*SP relation-type ) <"> relation-type = reg-rel-type | ext-rel-type reg-rel-type = LOALPHA *( LOALPHA | DIGIT | "." | "-" ) ext-rel-type = URI ``` @seanmonstar Hi, I'd like to give this a try if you're OK, we still want this right? @tabac sure!
2017-05-18T22:47:39Z
0.10
97abb81b3cc271a6dd258da86559bc25ab77c652
hyperium/hyper
1,178
hyperium__hyper-1178
[ "1176" ]
33eb8f95a3537cfd02aa4956a69dedd0c840a604
diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -213,9 +213,8 @@ fn parse_scheme(s: &str) -> Option<usize> { fn parse_authority(s: &str) -> usize { let i = s.find("://").map(|p| p + 3).unwrap_or(0); - s[i..].find('/') - .or_else(|| s[i..].find('?')) - .or_else(|| s[i..].find('#')) + s[i..] + .find(|ch| ch == '/' || ch == '?' || ch == '#') .map(|end| end + i) .unwrap_or(s.len()) }
diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -537,6 +536,28 @@ test_parse! { port = None, } +test_parse! { + test_uri_parse_absolute_form_with_empty_path_and_fragment_with_slash, + "http://127.0.0.1#foo/bar", + scheme = Some("http"), + authority = Some("127.0.0.1"), + path = "/", + query = None, + fragment = Some("foo/bar"), + port = None, +} + +test_parse! { + test_uri_parse_absolute_form_with_empty_path_and_fragment_with_questionmark, + "http://127.0.0.1#foo?bar", + scheme = Some("http"), + authority = Some("127.0.0.1"), + path = "/", + query = None, + fragment = Some("foo?bar"), + port = None, +} + #[test] fn test_uri_parse_error() { fn err(s: &str) {
hyper::Uri doesn't parse Uris with empty path well Problem: Latest master hyper::Uri thinks `https://google.com#ab/cd` has a host `google.com#ab`, while it should have a host `google.com`. hyper::Uri is okay with `https://google.com/#ab/cd`.
2017-05-17T11:42:58Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,162
hyperium__hyper-1162
[ "1155" ]
df1095dfe79e199128bd605777dd0f3e58487e46
diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -22,19 +22,19 @@ pub use tokio_service::Service; use header::{Headers, Host}; use http::{self, TokioBody}; +use http::response; +use http::request; use method::Method; use self::pool::{Pool, Pooled}; use uri::{self, Uri}; +pub use http::response::Response; +pub use http::request::Request; pub use self::connect::{HttpConnector, Connect}; -pub use self::request::Request; -pub use self::response::Response; mod connect; mod dns; mod pool; -mod request; -mod response; /// A Client to make outgoing HTTP requests. // If the Connector is clone, then the Client can be clone easily. diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -198,8 +198,8 @@ where C: Connect, }); FutureResponse(Box::new(req.map(|msg| { match msg { - Message::WithoutBody(head) => response::new(head, None), - Message::WithBody(head, body) => response::new(head, Some(body.into())), + Message::WithoutBody(head) => response::from_wire(head, None), + Message::WithBody(head, body) => response::from_wire(head, Some(body.into())), } }))) } diff --git a/src/client/response.rs /dev/null --- a/src/client/response.rs +++ /dev/null @@ -1,65 +0,0 @@ -use std::fmt; - -use header; -use http::{self, RawStatus, Body}; -use status; -use version; - -pub fn new(incoming: http::ResponseHead, body: Option<Body>) -> Response { - trace!("Response::new"); - let status = status::StatusCode::from_u16(incoming.subject.0); - debug!("version={:?}, status={:?}", incoming.version, status); - debug!("headers={:?}", incoming.headers); - - Response { - status: status, - version: incoming.version, - headers: incoming.headers, - status_raw: incoming.subject, - body: body, - } - -} - -/// A response for a client request to a remote server. -pub struct Response { - status: status::StatusCode, - headers: header::Headers, - version: version::HttpVersion, - status_raw: RawStatus, - body: Option<Body>, -} - -impl Response { - /// Get the headers from the server. - #[inline] - pub fn headers(&self) -> &header::Headers { &self.headers } - - /// Get the status from the server. - #[inline] - pub fn status(&self) -> status::StatusCode { self.status } - - /// Get the raw status code and reason. - #[inline] - pub fn status_raw(&self) -> &RawStatus { &self.status_raw } - - /// Get the HTTP version of this response from the server. - #[inline] - pub fn version(&self) -> version::HttpVersion { self.version } - - /// Take the `Body` of this response. - #[inline] - pub fn body(mut self) -> Body { - self.body.take().unwrap_or(Body::empty()) - } -} - -impl fmt::Debug for Response { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("Response") - .field("status", &self.status) - .field("version", &self.version) - .field("headers", &self.headers) - .finish() - } -} diff --git a/src/http/body.rs b/src/http/body.rs --- a/src/http/body.rs +++ b/src/http/body.rs @@ -107,6 +107,13 @@ impl From<&'static str> for Body { } } +impl From<Option<Body>> for Body { + #[inline] + fn from (body: Option<Body>) -> Body { + body.unwrap_or_default() + } +} + fn _assert_send_sync() { fn _assert_send<T: Send>() {} fn _assert_sync<T: Sync>() {} diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -24,6 +24,8 @@ mod io; mod h1; //mod h2; mod str; +pub mod request; +pub mod response; /* macro_rules! nonblocking { diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -71,10 +73,26 @@ impl<S> MessageHead<S> { } } +impl ResponseHead { + /// Converts this head's RawStatus into a StatusCode. + #[inline] + pub fn status(&self) -> StatusCode { + self.subject.status() + } +} + /// The raw status code and reason-phrase. #[derive(Clone, PartialEq, Debug)] pub struct RawStatus(pub u16, pub Cow<'static, str>); +impl RawStatus { + /// Converts this into a StatusCode. + #[inline] + pub fn status(&self) -> StatusCode { + StatusCode::from_u16(self.0) + } +} + impl fmt::Display for RawStatus { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {}", self.0, self.1) diff --git a/src/client/request.rs b/src/http/request.rs --- a/src/client/request.rs +++ b/src/http/request.rs @@ -1,10 +1,11 @@ use std::fmt; use header::Headers; -use http::{Body, RequestHead}; +use http::{Body, MessageHead, RequestHead, RequestLine}; use method::Method; use uri::{self, Uri}; use version::HttpVersion; +use std::net::SocketAddr; /// A client request to a remote server. pub struct Request<B = Body> { diff --git a/src/client/request.rs b/src/http/request.rs --- a/src/client/request.rs +++ b/src/http/request.rs @@ -14,6 +15,7 @@ pub struct Request<B = Body> { headers: Headers, body: Option<B>, is_proxy: bool, + remote_addr: Option<SocketAddr>, } impl<B> Request<B> { diff --git a/src/client/request.rs b/src/http/request.rs --- a/src/client/request.rs +++ b/src/http/request.rs @@ -27,13 +29,14 @@ impl<B> Request<B> { headers: Headers::new(), body: None, is_proxy: false, + remote_addr: None, } } /// Read the Request Uri. #[inline] pub fn uri(&self) -> &Uri { &self.uri } - + /// Read the Request Version. #[inline] pub fn version(&self) -> HttpVersion { self.version } diff --git a/src/client/request.rs b/src/http/request.rs --- a/src/client/request.rs +++ b/src/http/request.rs @@ -48,8 +51,29 @@ impl<B> Request<B> { /// Read the Request body. #[inline] - pub fn body(&self) -> Option<&B> { self.body.as_ref() } - + pub fn body_ref(&self) -> Option<&B> { self.body.as_ref() } + + /// The remote socket address of this request + /// + /// This is an `Option`, because some underlying transports may not have + /// a socket address, such as Unix Sockets. + /// + /// This field is not used for outgoing requests. + #[inline] + pub fn remote_addr(&self) -> Option<SocketAddr> { self.remote_addr } + + /// The target path of this Request. + #[inline] + pub fn path(&self) -> &str { + self.uri.path() + } + + /// The query string of this Request. + #[inline] + pub fn query(&self) -> Option<&str> { + self.uri.query() + } + /// Set the Method of this request. #[inline] pub fn set_method(&mut self, method: Method) { self.method = method; } diff --git a/src/client/request.rs b/src/http/request.rs --- a/src/client/request.rs +++ b/src/http/request.rs @@ -78,17 +102,60 @@ impl<B> Request<B> { pub fn set_proxy(&mut self, is_proxy: bool) { self.is_proxy = is_proxy; } } +impl Request<Body> { + /// Deconstruct this Request into its pieces. + /// + /// Modifying these pieces will have no effect on how hyper behaves. + #[inline] + pub fn deconstruct(self) -> (Method, Uri, HttpVersion, Headers, Body) { + (self.method, self.uri, self.version, self.headers, self.body.unwrap_or_default()) + } + + /// Take the Request body. + #[inline] + pub fn body(self) -> Body { self.body.unwrap_or_default() } +} + impl<B> fmt::Debug for Request<B> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Request") .field("method", &self.method) .field("uri", &self.uri) .field("version", &self.version) + .field("remote_addr", &self.remote_addr) .field("headers", &self.headers) .finish() } } +struct MaybeAddr<'a>(&'a Option<SocketAddr>); + +impl<'a> fmt::Display for MaybeAddr<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self.0 { + Some(ref addr) => fmt::Display::fmt(addr, f), + None => f.write_str("None"), + } + } +} + +/// Constructs a request using a received ResponseHead and optional body +pub fn from_wire<B>(addr: Option<SocketAddr>, incoming: RequestHead, body: B) -> Request<B> { + let MessageHead { version, subject: RequestLine(method, uri), headers } = incoming; + debug!("Request::new: addr={}, req=\"{} {} {}\"", MaybeAddr(&addr), method, uri, version); + debug!("Request::new: headers={:?}", headers); + + Request::<B> { + method: method, + uri: uri, + headers: headers, + version: version, + remote_addr: addr, + body: Some(body), + is_proxy: false, + } +} + pub fn split<B>(req: Request<B>) -> (RequestHead, Option<B>) { let uri = if req.is_proxy { req.uri diff --git /dev/null b/src/http/response.rs new file mode 100644 --- /dev/null +++ b/src/http/response.rs @@ -0,0 +1,152 @@ +use std::fmt; + +use header::{Header, Headers}; +use http::{MessageHead, ResponseHead, Body, RawStatus}; +use status::StatusCode; +use version::HttpVersion; + +/// A response for a client request to a remote server. +pub struct Response<B = Body> { + version: HttpVersion, + headers: Headers, + status: StatusCode, + raw_status: RawStatus, + body: Option<B>, +} + +impl<B> Response<B> { + /// Constructs a default response + #[inline] + pub fn new() -> Response<B> { + Response::default() + } + + /// Get the HTTP version of this response. + #[inline] + pub fn version(&self) -> HttpVersion { self.version } + + /// Get the headers from the response. + #[inline] + pub fn headers(&self) -> &Headers { &self.headers } + + /// Get a mutable reference to the headers. + #[inline] + pub fn headers_mut(&mut self) -> &mut Headers { &mut self.headers } + + /// Get the status from the server. + #[inline] + pub fn status(&self) -> StatusCode { self.status } + + /// Get the raw status code and reason. + /// + /// This method is only useful when inspecting the raw subject line from + /// a received response. + #[inline] + pub fn status_raw(&self) -> &RawStatus { &self.raw_status } + + /// Set the `StatusCode` for this response. + #[inline] + pub fn set_status(&mut self, status: StatusCode) { + self.status = status; + } + + /// Set the status and move the Response. + /// + /// Useful for the "builder-style" pattern. + #[inline] + pub fn with_status(mut self, status: StatusCode) -> Self { + self.set_status(status); + self + } + + /// Set a header and move the Response. + /// + /// Useful for the "builder-style" pattern. + #[inline] + pub fn with_header<H: Header>(mut self, header: H) -> Self { + self.headers.set(header); + self + } + + /// Set the headers and move the Response. + /// + /// Useful for the "builder-style" pattern. + #[inline] + pub fn with_headers(mut self, headers: Headers) -> Self { + self.headers = headers; + self + } + + /// Set the body. + #[inline] + pub fn set_body<T: Into<B>>(&mut self, body: T) { + self.body = Some(body.into()); + } + + /// Set the body and move the Response. + /// + /// Useful for the "builder-style" pattern. + #[inline] + pub fn with_body<T: Into<B>>(mut self, body: T) -> Self { + self.set_body(body); + self + } +} + +impl Response<Body> { + /// Take the `Body` of this response. + #[inline] + pub fn body(self) -> Body { + self.body.unwrap_or_default() + } +} + +impl<B> Default for Response<B> { + fn default() -> Response<B> { + Response::<B> { + version: Default::default(), + headers: Default::default(), + status: Default::default(), + raw_status: Default::default(), + body: None, + } + } +} + +impl fmt::Debug for Response { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Response") + .field("status", &self.status) + .field("version", &self.version) + .field("headers", &self.headers) + .finish() + } +} + +/// Constructs a response using a received ResponseHead and optional body +#[inline] +pub fn from_wire<B>(incoming: ResponseHead, body: Option<B>) -> Response<B> { + let status = incoming.status(); + trace!("Response::new"); + debug!("version={:?}, status={:?}", incoming.version, status); + debug!("headers={:?}", incoming.headers); + + Response::<B> { + status: status, + version: incoming.version, + headers: incoming.headers, + raw_status: incoming.subject, + body: body, + } +} + +/// Splits this response into a MessageHead<StatusCode> and its body +#[inline] +pub fn split<B>(res: Response<B>) -> (MessageHead<StatusCode>, Option<B>) { + let head = MessageHead::<StatusCode> { + version: res.version, + headers: res.headers, + subject: res.status + }; + (head, res.body) +} diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -39,6 +39,8 @@ pub use client::Client; pub use error::{Result, Error}; pub use header::Headers; pub use http::{Body, Chunk}; +pub use http::request::Request; +pub use http::response::Response; pub use method::Method::{self, Get, Head, Post, Put, Delete}; pub use status::StatusCode::{self, Ok, BadRequest, NotFound}; pub use server::Server; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -24,13 +24,12 @@ use tokio_proto::streaming::Message; use tokio_proto::streaming::pipeline::{Transport, Frame, ServerProto}; pub use tokio_service::{NewService, Service}; -pub use self::request::Request; -pub use self::response::Response; - use http; +use http::response; +use http::request; -mod request; -mod response; +pub use http::response::Response; +pub use http::request::Request; /// An instance of the HTTP protocol, and implementation of tokio-proto's /// `ServerProto` trait. diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -284,7 +283,7 @@ impl From<Message<__ProtoRequest, http::TokioBody>> for Request { Message::WithoutBody(head) => (head.0, http::Body::empty()), Message::WithBody(head, body) => (head.0, body.into()), }; - request::new(None, head, body) + request::from_wire(None, head, body) } } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -321,7 +320,7 @@ impl<T, B> Service for HttpService<T> Message::WithoutBody(head) => (head.0, http::Body::empty()), Message::WithBody(head, body) => (head.0, body.into()), }; - let req = request::new(Some(self.remote_addr), head, body); + let req = request::from_wire(Some(self.remote_addr), head, body); self.inner.call(req).map(Into::into) } } diff --git a/src/server/request.rs /dev/null --- a/src/server/request.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! Server Requests -//! -//! These are requests that a `hyper::Server` receives, and include its method, -//! target URI, headers, and message body. - -use std::fmt; -use std::net::SocketAddr; - -use version::HttpVersion; -use method::Method; -use header::Headers; -use http::{RequestHead, MessageHead, RequestLine, Body}; -use uri::Uri; - -/// A request bundles several parts of an incoming `NetworkStream`, given to a `Handler`. -pub struct Request { - method: Method, - uri: Uri, - version: HttpVersion, - headers: Headers, - remote_addr: Option<SocketAddr>, - body: Body, -} - -impl Request { - /// The `Method`, such as `Get`, `Post`, etc. - #[inline] - pub fn method(&self) -> &Method { &self.method } - - /// The headers of the incoming request. - #[inline] - pub fn headers(&self) -> &Headers { &self.headers } - - /// The target request-uri for this request. - #[inline] - pub fn uri(&self) -> &Uri { &self.uri } - - /// The version of HTTP for this request. - #[inline] - pub fn version(&self) -> HttpVersion { self.version } - - /// The remote socket address of this request - /// - /// This is an `Option`, because some underlying transports may not have - /// a socket address, such as Unix Sockets. - #[inline] - pub fn remote_addr(&self) -> Option<SocketAddr> { self.remote_addr } - - /// The target path of this Request. - #[inline] - pub fn path(&self) -> &str { - self.uri.path() - } - - /// The query string of this Request. - #[inline] - pub fn query(&self) -> Option<&str> { - self.uri.query() - } - - /// Take the `Body` of this `Request`. - #[inline] - pub fn body(self) -> Body { - self.body - } - - /// Deconstruct this Request into its pieces. - /// - /// Modifying these pieces will have no effect on how hyper behaves. - #[inline] - pub fn deconstruct(self) -> (Method, Uri, HttpVersion, Headers, Body) { - (self.method, self.uri, self.version, self.headers, self.body) - } -} - -impl fmt::Debug for Request { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("Request") - .field("method", &self.method) - .field("uri", &self.uri) - .field("version", &self.version) - .field("remote_addr", &self.remote_addr) - .field("headers", &self.headers) - .finish() - } -} - -pub fn new(addr: Option<SocketAddr>, incoming: RequestHead, body: Body) -> Request { - let MessageHead { version, subject: RequestLine(method, uri), headers } = incoming; - debug!("Request::new: addr={}, req=\"{} {} {}\"", MaybeAddr(&addr), method, uri, version); - debug!("Request::new: headers={:?}", headers); - - Request { - method: method, - uri: uri, - headers: headers, - version: version, - remote_addr: addr, - body: body, - } -} - -struct MaybeAddr<'a>(&'a Option<SocketAddr>); - -impl<'a> fmt::Display for MaybeAddr<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self.0 { - Some(ref addr) => fmt::Display::fmt(addr, f), - None => f.write_str("None"), - } - } -} - diff --git a/src/server/response.rs /dev/null --- a/src/server/response.rs +++ /dev/null @@ -1,111 +0,0 @@ -use std::fmt; - -use header; -use http::{self, Body}; -use status::StatusCode; -use version; - -/// The Response sent to a client after receiving a Request in a Service. -/// -/// The default `StatusCode` for a `Response` is `200 OK`. -pub struct Response<B = Body> { - head: http::MessageHead<StatusCode>, - body: Option<B>, -} - -impl<B> Response<B> { - /// Create a new Response. - #[inline] - pub fn new() -> Response<B> { - Response::default() - } - - /// The headers of this response. - #[inline] - pub fn headers(&self) -> &header::Headers { &self.head.headers } - - /// The status of this response. - #[inline] - pub fn status(&self) -> StatusCode { - self.head.subject - } - - /// The HTTP version of this response. - #[inline] - pub fn version(&self) -> version::HttpVersion { self.head.version } - - /// Get a mutable reference to the Headers. - #[inline] - pub fn headers_mut(&mut self) -> &mut header::Headers { &mut self.head.headers } - - /// Set the `StatusCode` for this response. - #[inline] - pub fn set_status(&mut self, status: StatusCode) { - self.head.subject = status; - } - - /// Set the body. - #[inline] - pub fn set_body<T: Into<B>>(&mut self, body: T) { - self.body = Some(body.into()); - } - - /// Set the status and move the Response. - /// - /// Useful for the "builder-style" pattern. - #[inline] - pub fn with_status(mut self, status: StatusCode) -> Self { - self.set_status(status); - self - } - - /// Set a header and move the Response. - /// - /// Useful for the "builder-style" pattern. - #[inline] - pub fn with_header<H: header::Header>(mut self, header: H) -> Self { - self.head.headers.set(header); - self - } - - /// Set the headers and move the Response. - /// - /// Useful for the "builder-style" pattern. - #[inline] - pub fn with_headers(mut self, headers: header::Headers) -> Self { - self.head.headers = headers; - self - } - - /// Set the body and move the Response. - /// - /// Useful for the "builder-style" pattern. - #[inline] - pub fn with_body<T: Into<B>>(mut self, body: T) -> Self { - self.set_body(body); - self - } -} - -impl<B> Default for Response<B> { - fn default() -> Response<B> { - Response { - head: Default::default(), - body: None, - } - } -} - -impl<B> fmt::Debug for Response<B> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("Response") - .field("status", &self.head.subject) - .field("version", &self.head.version) - .field("headers", &self.head.headers) - .finish() - } -} - -pub fn split<B>(res: Response<B>) -> (http::MessageHead<StatusCode>, Option<B>) { - (res.head, res.body) -}
diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -503,7 +503,7 @@ fn test_server_disable_keep_alive() { .status(hyper::Ok) .header(hyper::header::ContentLength(quux.len() as u64)) .body(quux); - + let _ = req.write_all(b"\ GET /quux HTTP/1.1\r\n\ Host: example.domain\r\n\ diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -522,4 +522,4 @@ fn test_server_disable_keep_alive() { panic!("read {} bytes on a disabled keep-alive socket", n); } } -} \ No newline at end of file +}
Unite Request and Response types Currently, `client::Request` is a different type from `server::Request`, and `client::Response` is different from `server::Response`. We want to unite them into the same type. That dramatically improves generic middleware that could apply on both a server and a client, and makes things like proxies far simpler as well, since a received `client::Response` can just become the `server::Response` for free.
2017-05-01T18:43:59Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,152
hyperium__hyper-1152
[ "1145" ]
c3466bedf8bd634c9c1aba25a3790bf8ae5e89d7
diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -1,7 +1,10 @@ -use header::{Header, Raw}; -use std::fmt::{self, Display}; +use std::borrow::Cow; +use std::fmt; use std::str::from_utf8; +use header::{Header, Raw}; +use header::internals::VecMap; + /// `Cookie` header, defined in [RFC6265](http://tools.ietf.org/html/rfc6265#section-5.4) /// /// If the user agent does attach a Cookie header field to an HTTP diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -20,17 +23,69 @@ use std::str::from_utf8; /// use hyper::header::{Headers, Cookie}; /// /// let mut headers = Headers::new(); +/// let mut cookie = Cookie::new(); +/// cookie.append("foo", "bar"); /// -/// headers.set( -/// Cookie(vec![ -/// String::from("foo=bar") -/// ]) -/// ); +/// assert_eq!(cookie.get("foo"), Some("bar")); +/// +/// headers.set(cookie); /// ``` -#[derive(Clone, PartialEq, Debug)] -pub struct Cookie(pub Vec<String>); +#[derive(Clone)] +pub struct Cookie(VecMap<Cow<'static, str>, Cow<'static, str>>); + +impl Cookie { + /// Creates a new `Cookie` header. + pub fn new() -> Cookie { + Cookie(VecMap::with_capacity(0)) + } -__hyper__deref!(Cookie => Vec<String>); + /// Sets a name and value for the `Cookie`. + /// + /// # Note + /// + /// This will remove all other instances with the same name, + /// and insert the new value. + pub fn set<K, V>(&mut self, key: K, value: V) + where K: Into<Cow<'static, str>>, + V: Into<Cow<'static, str>>, + { + let key = key.into(); + let value = value.into(); + self.0.remove_all(&key); + self.0.append(key, value); + } + + /// Append a name and value for the `Cookie`. + /// + /// # Note + /// + /// Cookies are allowed to set a name with a + /// a value multiple times. For example: + /// + /// ``` + /// use hyper::header::Cookie; + /// let mut cookie = Cookie::new(); + /// cookie.append("foo", "bar"); + /// cookie.append("foo", "quux"); + /// assert_eq!(cookie.to_string(), "foo=bar; foo=quux"); + pub fn append<K, V>(&mut self, key: K, value: V) + where K: Into<Cow<'static, str>>, + V: Into<Cow<'static, str>>, + { + self.0.append(key.into(), value.into()); + } + + /// Get a value for the name, if it exists. + /// + /// # Note + /// + /// Only returns the first instance found. To access + /// any other values associated with the name, parse + /// the `str` representation. + pub fn get(&self, key: &str) -> Option<&str> { + self.0.get(key).map(AsRef::as_ref) + } +} impl Header for Cookie { fn header_name() -> &'static str { diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -39,16 +94,22 @@ impl Header for Cookie { } fn parse_header(raw: &Raw) -> ::Result<Cookie> { - let mut cookies = Vec::with_capacity(raw.len()); + let mut vec_map = VecMap::with_capacity(raw.len()); for cookies_raw in raw.iter() { let cookies_str = try!(from_utf8(&cookies_raw[..])); for cookie_str in cookies_str.split(';') { - cookies.push(cookie_str.trim().to_owned()) + let mut key_val = cookie_str.splitn(2, '='); + let key_val = (key_val.next(), key_val.next()); + if let (Some(key), Some(val)) = key_val { + vec_map.insert(key.trim().to_owned().into(), val.trim().to_owned().into()); + } else { + return Err(::Error::Header); + } } } - if !cookies.is_empty() { - Ok(Cookie(cookies)) + if vec_map.len() != 0 { + Ok(Cookie(vec_map)) } else { Err(::Error::Header) } diff --git a/src/header/internals/vec_map.rs b/src/header/internals/vec_map.rs --- a/src/header/internals/vec_map.rs +++ b/src/header/internals/vec_map.rs @@ -19,6 +19,11 @@ impl<K: PartialEq, V> VecMap<K, V> { } } + #[inline] + pub fn append(&mut self, key: K, value: V) { + self.vec.push((key, value)); + } + #[inline] pub fn entry(&mut self, key: K) -> Entry<K, V> { match self.find(&key) { diff --git a/src/header/internals/vec_map.rs b/src/header/internals/vec_map.rs --- a/src/header/internals/vec_map.rs +++ b/src/header/internals/vec_map.rs @@ -55,10 +60,23 @@ impl<K: PartialEq, V> VecMap<K, V> { pub fn iter(&self) -> ::std::slice::Iter<(K, V)> { self.vec.iter() } + #[inline] pub fn remove<K2: PartialEq<K> + ?Sized>(&mut self, key: &K2) -> Option<V> { self.find(key).map(|pos| self.vec.remove(pos)).map(|(_, v)| v) } + + #[inline] + pub fn remove_all<K2: PartialEq<K> + ?Sized>(&mut self, key: &K2) { + let len = self.vec.len(); + for i in (0..len).rev() { + if key == &self.vec[i].0 { + self.vec.remove(i); + } + } + } + + #[inline] pub fn clear(&mut self) { self.vec.clear();
diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -59,16 +120,110 @@ impl Header for Cookie { } } +impl PartialEq for Cookie { + fn eq(&self, other: &Cookie) -> bool { + if self.0.len() == other.0.len() { + for &(ref k, ref v) in self.0.iter() { + if other.get(k) != Some(v) { + return false; + } + } + true + } else { + false + } + } +} + +impl fmt::Debug for Cookie { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_map() + .entries(self.0.iter().map(|&(ref k, ref v)| (k, v))) + .finish() + } +} + impl fmt::Display for Cookie { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let cookies = &self.0; - for (i, cookie) in cookies.iter().enumerate() { - if i != 0 { - try!(f.write_str("; ")); - } - try!(Display::fmt(&cookie, f)); + let mut iter = self.0.iter(); + if let Some(&(ref key, ref val)) = iter.next() { + try!(write!(f, "{}={}", key, val)); + } + for &(ref key, ref val) in iter { + try!(write!(f, "; {}={}", key, val)); } Ok(()) + } +} + +#[cfg(test)] +mod tests { + use ::header::Header; + use super::Cookie; + + #[test] + fn test_set_and_get() { + let mut cookie = Cookie::new(); + cookie.append("foo", "bar"); + cookie.append(String::from("dyn"), String::from("amic")); + + assert_eq!(cookie.get("foo"), Some("bar")); + assert_eq!(cookie.get("dyn"), Some("amic")); + assert!(cookie.get("nope").is_none()); + + cookie.append("foo", "notbar"); + assert_eq!(cookie.get("foo"), Some("bar")); + + cookie.set("foo", "hi"); + assert_eq!(cookie.get("foo"), Some("hi")); + assert_eq!(cookie.get("dyn"), Some("amic")); + } + + #[test] + fn test_eq() { + let mut cookie = Cookie::new(); + let mut cookie2 = Cookie::new(); + + // empty is equal + assert_eq!(cookie, cookie2); + + // left has more params + cookie.append("foo", "bar"); + assert!(cookie != cookie2); + + // same len, different params + cookie2.append("bar", "foo"); + assert!(cookie != cookie2); + + + // right has more params, and matching KV + cookie2.append("foo", "bar"); + assert!(cookie != cookie2); + + // same params, different order + cookie.append("bar", "foo"); + assert_eq!(cookie, cookie2); + } + + #[test] + fn test_parse() { + let mut cookie = Cookie::new(); + + let parsed = Cookie::parse_header(&b"foo=bar".to_vec().into()).unwrap(); + cookie.append("foo", "bar"); + assert_eq!(cookie, parsed); + + let parsed = Cookie::parse_header(&b"foo=bar; baz=quux".to_vec().into()).unwrap(); + cookie.append("baz", "quux"); + assert_eq!(cookie, parsed); + + let parsed = Cookie::parse_header(&b" foo = bar;baz= quux ".to_vec().into()).unwrap(); + assert_eq!(cookie, parsed); + + let parsed = Cookie::parse_header(&vec![b"foo = bar".to_vec(),b"baz= quux ".to_vec()].into()).unwrap(); + assert_eq!(cookie, parsed); + + Cookie::parse_header(&b"foo;bar=baz;quux".to_vec().into()).unwrap_err(); } }
Cookie Header should be Map-like We only ever receive headers like this: `Cookie: foo=bar; session=sean; hello=world`, and having that be a vector of `["foo=bar", "session=sean", "hello=world"]` doesn't really help anyone. Instead, anyone needing to accept cookies would only be looking for a certain name anyways, so this code would be more appropriate: ```rust let maybe_session = req.headers().get::<Cookie>().map(|cookie| cookie.get("session")); ``` Being a map also helps deal with a common mistake naïve users could make: duplicate names should just be dropped. Creation of a `Cookie` header should likewise use a map-like interface. ```rust let mut cookie = Cookie::new(); cookie.set("session", "sean"); // maybe an extend API also? Though we could easily defer to a later release let pairs = [("foo", "bar"), ("hello", "world")]; cookie.extend(&pairs); ```
For implementation, something like the `VecMap` inside `Headers` would probably be best, since it performs faster and with less memory than a `HashMap` when the number of items is small. I can't imagine the `Cookie` header, in the common case, having that many key-value pairs. So, it could look like: ```rust pub struct Cookie(VecMap<Cow<'static, str>, Cow<'static, str>>); impl Cookie { pub fn new() -> Cookie; pub fn get(&self, name: &str) -> Option<&str>; pub fn set<K: Into<Cow<'static, str>>, V: Into<Cow<'static, str>>>(&mut self, name: K, value: V); } ``` 1. We need to drop duplicate cookies, but in a very specific order. I believe the RFC does not specify the order, but most servers (all?) accept the first instance of each key only due to the way clients send them (higher scope first). 1. I was originally going to replace the vec of string by a HashMaps, but decided against it as this would break backwards compatibility, but totally agree that this is the way to go. As explained in #1142, I feel that the current implementation of the Cookie header is not a good implementation of what a Cookie header is. What is the process to inject a breaking change? Well, a breaking change would require a version bump (since we're before 1.0, that means the minor version). Good news is that we're about to do that anyways, with the async changes, to 0.11. So, if done quickly, it can ride that breakage together. Regarding duplicate cookie names, I just did some more searching. The situation is worse than I thought. The spec explicitly leaves it undefined when there are multiple cookies with the same name. "[...] servers SHOULD NOT rely upon the order in which these cookies appear in the header." Thanks, RFC. It seems many libraries in many languages just grab the first one. That may not be the behavior determined in the spec, but it seems like it has become the de-facto behavior. The internet is fun... My understanding is that servers should not rely on it, but because all clients send cookies the same way (narrower, more pertinent scope first), accepting the first key of a series of duplicate is what all servers do, and not doing so could create security issues. Should I take a first stab at implement a new struct for the "Cookie" header, something along the method in #1142, but as the struct instead? That should be fine. And anyone really needing the duplicate headers can always check `headers.get_raw`. I'd suggest starting with an implementation following https://github.com/hyperium/hyper/issues/1145#issuecomment-295810782.
2017-04-26T20:25:54Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,147
hyperium__hyper-1147
[ "1065" ]
1cd8ea36f33486c352b53cbbf92bba889077e85a
diff --git a/src/header/common/origin.rs b/src/header/common/origin.rs --- a/src/header/common/origin.rs +++ b/src/header/common/origin.rs @@ -31,20 +31,39 @@ use header::parsing::from_one_raw_str; /// ); /// ``` -#[derive(Clone, Debug)] -pub struct Origin { - /// The scheme, such as http or https - scheme: Cow<'static,str>, - /// The host, such as Host{hostname: "hyper.rs".to_owned(), port: None} - host: Host, +#[derive(PartialEq, Clone, Debug)] +pub struct Origin(OriginOrNull); + +#[derive(PartialEq, Clone, Debug)] +enum OriginOrNull { + Origin { + /// The scheme, such as http or https + scheme: Cow<'static,str>, + /// The host, such as Host{hostname: "hyper.rs".to_owned(), port: None} + host: Host, + }, + Null, } impl Origin { /// Creates a new `Origin` header. pub fn new<S: Into<Cow<'static,str>>, H: Into<Cow<'static,str>>>(scheme: S, hostname: H, port: Option<u16>) -> Origin{ - Origin { + Origin(OriginOrNull::Origin { scheme: scheme.into(), host: Host::new(hostname, port), + }) + } + + /// Creates a `Null` `Origin` header. + pub fn null() -> Origin { + Origin(OriginOrNull::Null) + } + + /// Checks if `Origin` is `Null`. + pub fn is_null(&self) -> bool { + match self { + &Origin(OriginOrNull::Null) => true, + _ => false, } } diff --git a/src/header/common/origin.rs b/src/header/common/origin.rs --- a/src/header/common/origin.rs +++ b/src/header/common/origin.rs @@ -52,20 +71,26 @@ impl Origin { /// ``` /// use hyper::header::Origin; /// let origin = Origin::new("https", "foo.com", Some(443)); - /// assert_eq!(origin.scheme(), "https"); + /// assert_eq!(origin.scheme(), Some("https")); /// ``` - pub fn scheme(&self) -> &str { - &(self.scheme) + pub fn scheme(&self) -> Option<&str> { + match self { + &Origin(OriginOrNull::Origin { ref scheme, .. }) => Some(&scheme), + _ => None, + } } /// The host, such as Host{hostname: "hyper.rs".to_owned(), port: None} /// ``` /// use hyper::header::{Origin,Host}; /// let origin = Origin::new("https", "foo.com", Some(443)); - /// assert_eq!(origin.host(), &Host::new("foo.com", Some(443))); + /// assert_eq!(origin.host(), Some(&Host::new("foo.com", Some(443)))); /// ``` - pub fn host(&self) -> &Host { - &(self.host) + pub fn host(&self) -> Option<&Host> { + match self { + &Origin(OriginOrNull::Origin { ref host, .. }) => Some(&host), + _ => None, + } } }
diff --git a/src/header/common/origin.rs b/src/header/common/origin.rs --- a/src/header/common/origin.rs +++ b/src/header/common/origin.rs @@ -104,26 +129,24 @@ impl FromStr for Origin { s => Cow::Owned(s.to_owned()) }; - Ok(Origin{ + Ok(Origin(OriginOrNull::Origin { scheme: scheme, host: host - }) + })) } } impl fmt::Display for Origin { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}://{}", self.scheme, self.host) - } -} - -impl PartialEq for Origin { - fn eq(&self, other: &Origin) -> bool { - self.scheme == other.scheme && self.host == other.host + match self { + &Origin(OriginOrNull::Origin { ref scheme, ref host }) => write!(f, "{}://{}", scheme, host), + /// Serialized as "null" per ASCII serialization of an origin + /// https://html.spec.whatwg.org/multipage/browsers.html#ascii-serialisation-of-an-origin + _ => write!(f, "null") + } } } - #[cfg(test)] mod tests { use super::Origin; diff --git a/src/header/common/origin.rs b/src/header/common/origin.rs --- a/src/header/common/origin.rs +++ b/src/header/common/origin.rs @@ -143,11 +166,11 @@ mod tests { fn test_origin() { let origin : Origin = Header::parse_header(&vec![b"http://foo.com".to_vec()].into()).unwrap(); assert_eq!(&origin, &Origin::new("http", "foo.com", None)); - assert_borrowed!(origin.scheme); + assert_borrowed!(origin.scheme().unwrap().into()); let origin : Origin = Header::parse_header(&vec![b"https://foo.com:443".to_vec()].into()).unwrap(); assert_eq!(&origin, &Origin::new("https", "foo.com", Some(443))); - assert_borrowed!(origin.scheme); + assert_borrowed!(origin.scheme().unwrap().into()); } }
Support Opaque origin headers, serializing it to `null` Support Opaque origins: > An internal value, with no serialization it can be recreated from (it is serialized as "null" per ASCII serialization of an origin), for which the only meaningful operation is testing for equality. https://html.spec.whatwg.org/multipage/browsers.html#concept-origin
Sorry, in what context? The url? The `Origin` header? The origin header. I see. So it can either be `null`, or the full origin. It seems like any way to make this work with hyper's `Origin` header would require a breaking change. Since that's the case, my thinking is something like this, for inclusion in v0.11: ```rust pub struct Origin(OriginOrNull); enum OriginOrNull { Origin { scheme: String, host: Host, }, Null, } impl Origin { pub fn new<S: Into<String>, H: Into<String>>(scheme: S, hostname: H, port: Option<u16>) -> Origin{ Origin(OriginOrNull::Origin { scheme: scheme.into(), host: Host::new(hostname.into(), port), }) } pub fn null() -> Origin { Origin(OriginOrNull::Null) } pub fn is_null(&self) -> bool; pub fn scheme(&self) -> Option<&str>; pub fn hostname(&self) -> Option<&str>; pub fn port(&self) -> Option<u16>; } ``` Whatcha think? For servo, if you wish to make use of this right away while keeping to hyper 0.10, you could implement an `Origin` header in Servo. @seanmonstar That looks real similar to the `url` crate's `Origin` implementation, since it's a dependency, could we rely on the serialization algorithms implemented there? Ah, I might implement `Header` for `url::Origin`, would be a nice intermediate solution. Oh I remember this conversation again. We didn't use `url::Origin` because it requires the port. The header has the port optional. Thanks to work in #1121, the breaking change required here is done. This would be pretty easy to implement using an internal private enum, as described in https://github.com/hyperium/hyper/issues/1065#issuecomment-280116120, keeping our use of `Cow` instead of `String. Hi there! I'd like to try implementing this.
2017-04-20T20:27:31Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,136
hyperium__hyper-1136
[ "1124" ]
574ded90dd5bf52b2ea10420fe34379636b094bd
diff --git a/src/header/common/origin.rs b/src/header/common/origin.rs --- a/src/header/common/origin.rs +++ b/src/header/common/origin.rs @@ -84,6 +84,9 @@ impl Header for Origin { } } +static HTTP : &'static str = "http"; +static HTTPS : &'static str = "https"; + impl FromStr for Origin { type Err = ::Error; diff --git a/src/header/common/origin.rs b/src/header/common/origin.rs --- a/src/header/common/origin.rs +++ b/src/header/common/origin.rs @@ -95,10 +98,14 @@ impl FromStr for Origin { // idx + 3 because that's how long "://" is let (scheme, etc) = (&s[..idx], &s[idx + 3..]); let host = try!(Host::from_str(etc)); - + let scheme = match scheme { + "http" => Cow::Borrowed(HTTP), + "https" => Cow::Borrowed(HTTPS), + s => Cow::Owned(s.to_owned()) + }; Ok(Origin{ - scheme: scheme.to_owned().into(), + scheme: scheme, host: host }) }
diff --git a/src/header/common/origin.rs b/src/header/common/origin.rs --- a/src/header/common/origin.rs +++ b/src/header/common/origin.rs @@ -121,14 +128,26 @@ impl PartialEq for Origin { mod tests { use super::Origin; use header::Header; + use std::borrow::Cow; + + macro_rules! assert_borrowed{ + ($expr : expr) => { + match $expr { + Cow::Owned(ref v) => panic!("assertion failed: `{}` owns {:?}", stringify!($expr), v), + _ => {} + } + } + } #[test] fn test_origin() { - let origin = Header::parse_header(&vec![b"http://foo.com".to_vec()].into()); - assert_eq!(origin.ok(), Some(Origin::new("http", "foo.com", None))); + let origin : Origin = Header::parse_header(&vec![b"http://foo.com".to_vec()].into()).unwrap(); + assert_eq!(&origin, &Origin::new("http", "foo.com", None)); + assert_borrowed!(origin.scheme); - let origin = Header::parse_header(&vec![b"https://foo.com:443".to_vec()].into()); - assert_eq!(origin.ok(), Some(Origin::new("https", "foo.com", Some(443)))); + let origin : Origin = Header::parse_header(&vec![b"https://foo.com:443".to_vec()].into()).unwrap(); + assert_eq!(&origin, &Origin::new("https", "foo.com", Some(443))); + assert_borrowed!(origin.scheme); } }
Reduce to_owned of scheme in Origin header Now that the `scheme` propertry is a `Cow<'static, str>`, and the scheme is pretty much always only ever "http" or "https", we should compare for those and then store a `Cow::Borrowed("http")` etc, instead of calling `scheme.to_owned()`.
2017-04-13T22:20:32Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,135
hyperium__hyper-1135
[ "1134" ]
f05a58a1b2288d30a601b0466bc08a38c5a76054
diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -610,6 +610,9 @@ impl<B, K: KeepAlive> State<B, K> { } fn busy(&mut self) { + if let KA::Disabled = self.keep_alive.status() { + return; + } self.keep_alive.busy(); }
diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -146,10 +146,16 @@ fn connect(addr: &SocketAddr) -> TcpStream { } fn serve() -> Serve { - serve_with_timeout(None) + serve_with_options(Default::default()) } -fn serve_with_timeout(dur: Option<Duration>) -> Serve { +#[derive(Default)] +struct ServeOptions { + keep_alive_disabled: bool, + timeout: Option<Duration>, +} + +fn serve_with_options(options: ServeOptions) -> Serve { let _ = pretty_env_logger::init(); let (addr_tx, addr_rx) = mpsc::channel(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -159,9 +165,12 @@ fn serve_with_timeout(dur: Option<Duration>) -> Serve { let addr = "127.0.0.1:0".parse().unwrap(); + let keep_alive = !options.keep_alive_disabled; + let dur = options.timeout; + let thread_name = format!("test-server-{:?}", dur); let thread = thread::Builder::new().name(thread_name).spawn(move || { - let srv = Http::new().bind(&addr, TestService { + let srv = Http::new().keep_alive(keep_alive).bind(&addr, TestService { tx: Arc::new(Mutex::new(msg_tx.clone())), _timeout: dur, reply: reply_rx, diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -456,3 +465,61 @@ fn server_keep_alive() { } } } + +#[test] +fn test_server_disable_keep_alive() { + let foo_bar = b"foo bar baz"; + let server = serve_with_options(ServeOptions { + keep_alive_disabled: true, + .. Default::default() + }); + server.reply() + .status(hyper::Ok) + .header(hyper::header::ContentLength(foo_bar.len() as u64)) + .body(foo_bar); + let mut req = connect(server.addr()); + req.write_all(b"\ + GET / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Connection: keep-alive\r\n\ + \r\n\ + ").expect("writing 1"); + + let mut buf = [0; 1024 * 8]; + loop { + let n = req.read(&mut buf[..]).expect("reading 1"); + if n < buf.len() { + if &buf[n - foo_bar.len()..n] == foo_bar { + break; + } else { + } + } + } + + // try again! + + let quux = b"zar quux"; + server.reply() + .status(hyper::Ok) + .header(hyper::header::ContentLength(quux.len() as u64)) + .body(quux); + + let _ = req.write_all(b"\ + GET /quux HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Connection: close\r\n\ + \r\n\ + "); + + // the write can possibly succeed, since it fills the kernel buffer on the first write + let mut buf = [0; 1024 * 8]; + match req.read(&mut buf[..]) { + // Ok(0) means EOF, so a proper shutdown + // Err(_) could mean ConnReset or something, also fine + Ok(0) | + Err(_) => {} + Ok(n) => { + panic!("read {} bytes on a disabled keep-alive socket", n); + } + } +} \ No newline at end of file
Connection Keepalive Hi, I'm currently using the hyper master branch. I have written a Service and want that the connection is dropped after each request. I thought that using "Http::keep_alive(false)" should close the connection? But that does not work. Is this a bug or do I use the wrong functionality?
2017-04-13T00:05:44Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,116
hyperium__hyper-1116
[ "1111" ]
6e55fbe75d0ac98b162b4f44f746df76d71a778a
diff --git a/src/http/io.rs b/src/http/io.rs --- a/src/http/io.rs +++ b/src/http/io.rs @@ -55,31 +55,33 @@ impl<T: AsyncRead + AsyncWrite> Buffered<T> { } pub fn parse<S: Http1Transaction>(&mut self) -> ::Result<Option<MessageHead<S::Incoming>>> { - self.reserve_read_buf(); - match self.read_from_io() { - Ok(0) => { - trace!("parse eof"); - return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "parse eof").into()); - } - Ok(_) => {}, - Err(e) => match e.kind() { - io::ErrorKind::WouldBlock => {}, - _ => return Err(e.into()) + loop { + match try!(parse::<S, _>(&mut self.read_buf)) { + Some(head) => { + //trace!("parsed {} bytes out of {}", len, self.read_buf.len()); + return Ok(Some(head.0)) + }, + None => { + if self.read_buf.capacity() >= MAX_BUFFER_SIZE { + debug!("MAX_BUFFER_SIZE reached, closing"); + return Err(::Error::TooLarge); + } + }, } - } - match try!(parse::<S, _>(&mut self.read_buf)) { - Some(head) => { - //trace!("parsed {} bytes out of {}", len, self.read_buf.len()); - Ok(Some(head.0)) - }, - None => { - if self.read_buf.capacity() >= MAX_BUFFER_SIZE { - debug!("MAX_BUFFER_SIZE reached, closing"); - Err(::Error::TooLarge) - } else { - Ok(None) + self.reserve_read_buf(); + match self.read_from_io() { + Ok(0) => { + trace!("parse eof"); + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "parse eof").into()); + } + Ok(_) => {}, + Err(e) => match e.kind() { + io::ErrorKind::WouldBlock => { + return Ok(None); + }, + _ => return Err(e.into()) } - }, + } } } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -62,6 +62,7 @@ pub struct AsyncIo<T> { inner: T, bytes_until_block: usize, error: Option<io::Error>, + blocked: bool, flushed: bool, } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -72,6 +73,7 @@ impl<T> AsyncIo<T> { bytes_until_block: bytes, error: None, flushed: false, + blocked: false, } } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -92,13 +94,19 @@ impl AsyncIo<Buf> { pub fn flushed(&self) -> bool { self.flushed } + + pub fn blocked(&self) -> bool { + self.blocked + } } impl<T: Read> Read for AsyncIo<T> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.blocked = false; if let Some(err) = self.error.take() { Err(err) } else if self.bytes_until_block == 0 { + self.blocked = true; Err(io::Error::new(io::ErrorKind::WouldBlock, "mock block")) } else { let n = cmp::min(self.bytes_until_block, buf.len());
diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -745,7 +745,6 @@ mod tests { let mut conn = Conn::<_, http::Chunk, ServerTransaction>::new(io, Default::default()); conn.state.idle(); - assert!(conn.poll().unwrap().is_not_ready()); match conn.poll().unwrap() { Async::Ready(Some(Frame::Error { .. })) => {}, other => panic!("frame is not Error: {:?}", other) diff --git a/src/http/io.rs b/src/http/io.rs --- a/src/http/io.rs +++ b/src/http/io.rs @@ -340,3 +342,15 @@ fn test_iobuf_write_empty_slice() { // when there is nothing to flush io_buf.flush().expect("should short-circuit flush"); } + +#[test] +fn test_parse_reads_until_blocked() { + use mock::{AsyncIo, Buf as MockBuf}; + // missing last line ending + let raw = "HTTP/1.1 200 OK\r\n"; + + let mock = AsyncIo::new(MockBuf::wrap(raw.into()), raw.len()); + let mut buffered = Buffered::new(mock); + assert_eq!(buffered.parse::<super::ClientTransaction>().unwrap(), None); + assert!(buffered.io.blocked()); +}
Example tokio client hangs when HTTP Response code is in its own packet Steps to reproduce: - Run nc -l -p 8081 - Run hyper/examples/client.rs http://localhost:8081/ - In the nc terminal, paste: ``` HTTP/1.1 200 OK Hello World ``` - Press ^C - This works fine. Now repeat, but: - Run nc -l -p 8081 - Run hyper/examples/client.rs http://localhost:8081/ - In the nc terminal, paste: ``` HTTP/1.1 200 OK ``` - Wait one second. Then paste ``` Hello World ``` - Press ^C - The hyper example is hung Expected result: the packet timing should not cause the example hyper client to hang (this works fine with curl).
2017-04-05T22:23:25Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,115
hyperium__hyper-1115
[ "1112" ]
66ad619d6ece49a2325bf22f85fdecc9e3eda3c4
diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -3,6 +3,7 @@ use std::fmt::{Display, self}; use std::str::{self, FromStr}; use http::ByteStr; +use bytes::{BufMut, BytesMut}; /// The Request-URI of a Request's StartLine. /// diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -32,8 +33,8 @@ pub struct Uri { source: ByteStr, scheme_end: Option<usize>, authority_end: Option<usize>, - query: Option<usize>, - fragment: Option<usize>, + query_start: Option<usize>, + fragment_start: Option<usize>, } impl Uri { diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -43,13 +44,7 @@ impl Uri { Err(UriError(ErrorKind::Empty)) } else if s.as_bytes() == b"*" { // asterisk-form - Ok(Uri { - source: ByteStr::from_static("*"), - scheme_end: None, - authority_end: None, - query: None, - fragment: None, - }) + Ok(asterisk_form()) } else if s.as_bytes() == b"/" { // shortcut for '/' Ok(Uri::default()) diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -61,13 +56,13 @@ impl Uri { source: s, scheme_end: None, authority_end: None, - query: query, - fragment: fragment, + query_start: query, + fragment_start: fragment, }) } else if s.contains("://") { // absolute-form let scheme = parse_scheme(&s); - let auth = parse_authority(&s); + let auth = Some(parse_authority(&s)); let scheme_end = scheme.expect("just checked for ':' above"); let auth_end = auth.expect("just checked for ://"); if scheme_end + 3 == auth_end { diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -80,8 +75,8 @@ impl Uri { source: s, scheme_end: scheme, authority_end: auth, - query: query, - fragment: fragment, + query_start: query, + fragment_start: fragment, }) } else if (s.contains("/") || s.contains("?")) && !s.contains("://") { // last possibility is authority-form, above are illegal characters diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -93,19 +88,16 @@ impl Uri { source: s, scheme_end: None, authority_end: Some(len), - query: None, - fragment: None, + query_start: None, + fragment_start: None, }) } } /// Get the path of this `Uri`. pub fn path(&self) -> &str { - let index = self.authority_end.unwrap_or(self.scheme_end.unwrap_or(0)); - let query_len = self.query.unwrap_or(0); - let fragment_len = self.fragment.unwrap_or(0); - let end = self.source.len() - if query_len > 0 { query_len + 1 } else { 0 } - - if fragment_len > 0 { fragment_len + 1 } else { 0 }; + let index = self.path_start(); + let end = self.path_end(); if index >= end { if self.scheme().is_some() { "/" // absolute-form MUST have path diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -117,6 +109,31 @@ impl Uri { } } + #[inline] + fn path_start(&self) -> usize { + self.authority_end.unwrap_or(self.scheme_end.unwrap_or(0)) + } + + #[inline] + fn path_end(&self) -> usize { + if let Some(query) = self.query_start { + query + } else if let Some(fragment) = self.fragment_start { + fragment + } else { + self.source.len() + } + } + + #[inline] + fn origin_form_end(&self) -> usize { + if let Some(fragment) = self.fragment_start { + fragment + } else { + self.source.len() + } + } + /// Get the scheme of this `Uri`. pub fn scheme(&self) -> Option<&str> { if let Some(end) = self.scheme_end { diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -180,35 +197,31 @@ fn parse_scheme(s: &str) -> Option<usize> { s.find(':') } -fn parse_authority(s: &str) -> Option<usize> { - let i = s.find("://").and_then(|p| Some(p + 3)).unwrap_or(0); - - Some(&s[i..].split("/") - .next() - .unwrap_or(s) - .len() + i) +fn parse_authority(s: &str) -> usize { + let i = s.find("://").map(|p| p + 3).unwrap_or(0); + s[i..].find('/') + .or_else(|| s[i..].find('?')) + .or_else(|| s[i..].find('#')) + .map(|end| end + i) + .unwrap_or(s.len()) } fn parse_query(s: &str) -> Option<usize> { - match s.find('?') { - Some(i) => { - let frag_pos = s.find('#').unwrap_or(s.len()); - - if frag_pos < i + 1 { + s.find('?').and_then(|i| { + if let Some(frag) = s.find('#') { + if frag < i { None } else { - Some(frag_pos - i - 1) + Some(i) } - }, - None => None, - } + } else { + Some(i) + } + }) } fn parse_fragment(s: &str) -> Option<usize> { - match s.find('#') { - Some(i) => Some(s.len() - i - 1), - None => None, - } + s.find('#') } impl FromStr for Uri { diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -227,6 +240,18 @@ impl PartialEq for Uri { } } +impl<'a> PartialEq<&'a str> for Uri { + fn eq(&self, other: & &'a str) -> bool { + self.source.as_str() == *other + } +} + +impl<'a> PartialEq<Uri> for &'a str{ + fn eq(&self, other: &Uri) -> bool { + *self == other.source.as_str() + } +} + impl Eq for Uri {} impl AsRef<str> for Uri { diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -241,8 +266,8 @@ impl Default for Uri { source: ByteStr::from_static("/"), scheme_end: None, authority_end: None, - query: None, - fragment: None, + query_start: None, + fragment_start: None, } } } diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -269,27 +294,58 @@ pub fn scheme_and_authority(uri: &Uri) -> Option<Uri> { source: uri.source.slice_to(uri.authority_end.expect("scheme without authority")), scheme_end: uri.scheme_end, authority_end: uri.authority_end, - query: None, - fragment: None, + query_start: None, + fragment_start: None, }) } else { None } } +#[inline] +fn asterisk_form() -> Uri { + Uri { + source: ByteStr::from_static("*"), + scheme_end: None, + authority_end: None, + query_start: None, + fragment_start: None, + } +} + pub fn origin_form(uri: &Uri) -> Uri { - let start = uri.authority_end.unwrap_or(uri.scheme_end.unwrap_or(0)); - let end = if let Some(f) = uri.fragment { - uri.source.len() - f - 1 + let range = Range(uri.path_start(), uri.origin_form_end()); + + let clone = if range.len() == 0 { + ByteStr::from_static("/") + } else if uri.source.as_bytes()[range.0] == b'*' { + return asterisk_form(); + } else if uri.source.as_bytes()[range.0] != b'/' { + let mut new = BytesMut::with_capacity(range.1 - range.0 + 1); + new.put_u8(b'/'); + new.put_slice(&uri.source.as_bytes()[range.0..range.1]); + // safety: the bytes are '/' + previous utf8 str + unsafe { ByteStr::from_utf8_unchecked(new.freeze()) } + } else if range.0 == 0 && range.1 == uri.source.len() { + uri.source.clone() } else { - uri.source.len() + uri.source.slice(range.0, range.1) }; + Uri { - source: uri.source.slice(start, end), + source: clone, scheme_end: None, authority_end: None, - query: uri.query, - fragment: None, + query_start: uri.query_start, + fragment_start: None, + } +} + +struct Range(usize, usize); + +impl Range { + fn len(&self) -> usize { + self.1 - self.0 } }
diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -344,7 +344,7 @@ mod tests { let (req, len) = parse::<http::ServerTransaction, _>(&mut raw).unwrap().unwrap(); assert_eq!(len, expected_len); assert_eq!(req.subject.0, ::Method::Get); - assert_eq!(req.subject.1, "/echo".parse().unwrap()); + assert_eq!(req.subject.1, "/echo"); assert_eq!(req.version, ::HttpVersion::Http11); assert_eq!(req.headers.len(), 1); assert_eq!(req.headers.get_raw("Host").map(|raw| &raw[0]), Some(b"hyper.rs".as_ref())); diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -156,23 +173,23 @@ impl Uri { /// Get the query string of this `Uri`, starting after the `?`. pub fn query(&self) -> Option<&str> { - let fragment_len = self.fragment.unwrap_or(0); - let fragment_len = if fragment_len > 0 { fragment_len + 1 } else { 0 }; - if let Some(len) = self.query { - Some(&self.source[self.source.len() - len - fragment_len.. - self.source.len() - fragment_len]) - } else { - None - } + self.query_start.map(|start| { + // +1 to remove '?' + let start = start + 1; + if let Some(end) = self.fragment_start { + &self.source[start..end] + } else { + &self.source[start..] + } + }) } #[cfg(test)] fn fragment(&self) -> Option<&str> { - if let Some(len) = self.fragment { - Some(&self.source[self.source.len() - len..self.source.len()]) - } else { - None - } + self.fragment_start.map(|start| { + // +1 to remove the '#' + &self.source[start + 1..] + }) } } diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -329,6 +385,7 @@ macro_rules! test_parse { #[test] fn $test_name() { let uri = Uri::from_str($str).unwrap(); + println!("{:?} = {:#?}", $str, uri); $( assert_eq!(uri.$method(), $value); )+ diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -442,6 +499,30 @@ test_parse! { port = None, } +test_parse! { + test_uri_parse_path_with_terminating_questionmark, + "http://127.0.0.1/path?", + + scheme = Some("http"), + authority = Some("127.0.0.1"), + path = "/path", + query = Some(""), + fragment = None, + port = None, +} + +test_parse! { + test_uri_parse_absolute_form_with_empty_path_and_nonempty_query, + "http://127.0.0.1?foo=bar", + + scheme = Some("http"), + authority = Some("127.0.0.1"), + path = "/", + query = Some("foo=bar"), + fragment = None, + port = None, +} + #[test] fn test_uri_parse_error() { fn err(s: &str) { diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -452,6 +533,26 @@ fn test_uri_parse_error() { err("htt:p//host"); err("hyper.rs/"); err("hyper.rs?key=val"); + err("?key=val"); err("localhost/"); err("localhost?key=val"); } + +#[test] +fn test_uri_to_origin_form() { + let cases = vec![ + ("/", "/"), + ("/foo?bar", "/foo?bar"), + ("/foo?bar#nope", "/foo?bar"), + ("http://hyper.rs", "/"), + ("http://hyper.rs/", "/"), + ("http://hyper.rs/path", "/path"), + ("http://hyper.rs?query", "/?query"), + ("*", "*"), + ]; + + for case in cases { + let uri = Uri::from_str(case.0).unwrap(); + assert_eq!(origin_form(&uri), case.1, "{:?}", case); + } +}
Send invalid request line when there's no trailing slash in url If url is requested without trailing slash like "http://www.google.com", '404 not found' is returned because Request line doesn't have Request URI like "GET HTTP/1.1". It is ok if url is requested like "http://www.google.com/"
2017-04-05T21:26:06Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,110
hyperium__hyper-1110
[ "1108" ]
d63b7de44f813696f8ec595d2f8f901526c1720e
diff --git a/src/http/io.rs b/src/http/io.rs --- a/src/http/io.rs +++ b/src/http/io.rs @@ -134,15 +134,16 @@ impl<T: Write> Write for Buffered<T> { fn flush(&mut self) -> io::Result<()> { if self.write_buf.remaining() == 0 { - Ok(()) + self.io.flush() } else { loop { let n = try!(self.write_buf.write_into(&mut self.io)); debug!("flushed {} bytes", n); if self.write_buf.remaining() == 0 { - return Ok(()) + break; } } + self.io.flush() } } } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -62,6 +62,7 @@ pub struct AsyncIo<T> { inner: T, bytes_until_block: usize, error: Option<io::Error>, + flushed: bool, } impl<T> AsyncIo<T> { diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -70,6 +71,7 @@ impl<T> AsyncIo<T> { inner: inner, bytes_until_block: bytes, error: None, + flushed: false, } } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -86,6 +88,10 @@ impl AsyncIo<Buf> { pub fn new_buf<T: Into<Vec<u8>>>(buf: T, bytes: usize) -> AsyncIo<Buf> { AsyncIo::new(Buf::wrap(buf.into()), bytes) } + + pub fn flushed(&self) -> bool { + self.flushed + } } impl<T: Read> Read for AsyncIo<T> { diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -111,6 +117,7 @@ impl<T: Write> Write for AsyncIo<T> { Err(io::Error::new(io::ErrorKind::WouldBlock, "mock block")) } else { trace!("AsyncIo::write() block_in = {}, data.len() = {}", self.bytes_until_block, data.len()); + self.flushed = false; let n = cmp::min(self.bytes_until_block, data.len()); let n = try!(self.inner.write(&data[..n])); self.bytes_until_block -= n; diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -119,6 +126,7 @@ impl<T: Write> Write for AsyncIo<T> { } fn flush(&mut self) -> io::Result<()> { + self.flushed = true; self.inner.flush() } }
diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -827,6 +827,7 @@ mod tests { assert!(conn.state.writing.is_queued()); assert!(conn.poll_complete().unwrap().is_ready()); assert!(!conn.state.writing.is_queued()); + assert!(conn.io.io_mut().flushed()); Ok(()) }).wait();
Client doesn't appear to flush when waiting to read a response I was implementing a custom I/O stream to send requests over and I saw that the request was never actually written when it was waiting for a response. Turns out I was accidentally enabling buffering on the abstraction I was using and so none of the data was being flushed out. I wonder if perhaps the client could flush the underlying I/O stream once it starts needing to read a request? I do realize though that buffering at that layer isn't a great idea (and I've since disabled it), but I figured this'd be a semi-relevant issue regardless.
Interesting! As `conn.poll_complete()` is called, we take that to mean to flush `Conn`s `write_buf` into the `io`, but then we don't actually call `io.flush()`. I assume that's the missing piece? I think so yeah, that'd make sense. This came up w/ a custom `AsyncRead + AsyncWrite` implementation so a call to `io.flush()` in `poll_complete` would do the trick.
2017-04-03T17:08:03Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,100
hyperium__hyper-1100
[ "1089" ]
e81184e53c5c59a6262201e212a04a772f089079
diff --git a/examples/client.rs b/examples/client.rs --- a/examples/client.rs +++ b/examples/client.rs @@ -24,8 +24,8 @@ fn main() { } }; - let url = hyper::Url::parse(&url).unwrap(); - if url.scheme() != "http" { + let url = url.parse::<hyper::Uri>().unwrap(); + if url.scheme() != Some("http") { println!("This example only works with 'http' URLs."); return; } diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -7,7 +7,7 @@ use tokio_io::{AsyncRead, AsyncWrite}; use tokio::reactor::Handle; use tokio::net::{TcpStream, TcpStreamNew}; use tokio_service::Service; -use Url; +use Uri; use super::dns; diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -15,25 +15,25 @@ use super::dns; /// /// This trait is not implemented directly, and only exists to make /// the intent clearer. A connector should implement `Service` with -/// `Request=Url` and `Response: Io` instead. -pub trait Connect: Service<Request=Url, Error=io::Error> + 'static { +/// `Request=Uri` and `Response: Io` instead. +pub trait Connect: Service<Request=Uri, Error=io::Error> + 'static { /// The connected Io Stream. type Output: AsyncRead + AsyncWrite + 'static; /// A Future that will resolve to the connected Stream. type Future: Future<Item=Self::Output, Error=io::Error> + 'static; /// Connect to a remote address. - fn connect(&self, Url) -> <Self as Connect>::Future; + fn connect(&self, Uri) -> <Self as Connect>::Future; } impl<T> Connect for T -where T: Service<Request=Url, Error=io::Error> + 'static, +where T: Service<Request=Uri, Error=io::Error> + 'static, T::Response: AsyncRead + AsyncWrite, T::Future: Future<Error=io::Error>, { type Output = T::Response; type Future = T::Future; - fn connect(&self, url: Url) -> <Self as Connect>::Future { + fn connect(&self, url: Uri) -> <Self as Connect>::Future { self.call(url) } } diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -66,21 +66,21 @@ impl fmt::Debug for HttpConnector { } impl Service for HttpConnector { - type Request = Url; + type Request = Uri; type Response = TcpStream; type Error = io::Error; type Future = HttpConnecting; - fn call(&self, url: Url) -> Self::Future { + fn call(&self, url: Uri) -> Self::Future { debug!("Http::connect({:?})", url); - let host = match url.host_str() { + let host = match url.host() { Some(s) => s, None => return HttpConnecting { state: State::Error(Some(io::Error::new(io::ErrorKind::InvalidInput, "invalid url"))), handle: self.handle.clone(), }, }; - let port = url.port_or_known_default().unwrap_or(80); + let port = url.port().unwrap_or(80); HttpConnecting { state: State::Resolving(self.dns.resolve(host.into(), port)), diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -10,7 +10,7 @@ use std::marker::PhantomData; use std::rc::Rc; use std::time::Duration; -use futures::{Poll, Async, Future, Stream}; +use futures::{future, Poll, Async, Future, Stream}; use futures::unsync::oneshot; use tokio_io::{AsyncRead, AsyncWrite}; use tokio::reactor::Handle; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -24,7 +24,7 @@ use header::{Headers, Host}; use http::{self, TokioBody}; use method::Method; use self::pool::{Pool, Pooled}; -use Url; +use uri::{self, Uri}; pub use self::connect::{HttpConnector, Connect}; pub use self::request::Request; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -95,7 +95,7 @@ where C: Connect, { /// Send a GET Request using this Client. #[inline] - pub fn get(&self, url: Url) -> FutureResponse { + pub fn get(&self, url: Uri) -> FutureResponse { self.request(Request::new(Method::Get, url)) } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -135,18 +135,30 @@ where C: Connect, type Future = FutureResponse; fn call(&self, req: Self::Request) -> Self::Future { - let url = req.url().clone(); + let url = req.uri().clone(); + let domain = match uri::scheme_and_authority(&url) { + Some(uri) => uri, + None => { + return FutureResponse(Box::new(future::err(::Error::Io( + io::Error::new( + io::ErrorKind::InvalidInput, + "invalid URI for Client Request" + ) + )))); + } + }; + let host = Host::new(domain.host().expect("authority implies host").to_owned(), domain.port()); let (mut head, body) = request::split(req); let mut headers = Headers::new(); - headers.set(Host::new(url.host_str().unwrap().to_owned(), url.port())); + headers.set(host); headers.extend(head.headers.iter()); head.headers = headers; - let checkout = self.pool.checkout(&url[..::url::Position::BeforePath]); + let checkout = self.pool.checkout(domain.as_ref()); let connect = { let handle = self.handle.clone(); let pool = self.pool.clone(); - let pool_key = Rc::new(url[..::url::Position::BeforePath].to_owned()); + let pool_key = Rc::new(domain.to_string()); self.connector.connect(url) .map(move |io| { let (tx, rx) = oneshot::channel(); diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -1,18 +1,15 @@ use std::fmt; -use Url; - use header::Headers; use http::{Body, RequestHead}; use method::Method; -use uri::Uri; +use uri::{self, Uri}; use version::HttpVersion; -use std::str::FromStr; /// A client request to a remote server. pub struct Request<B = Body> { method: Method, - url: Url, + uri: Uri, version: HttpVersion, headers: Headers, body: Option<B>, diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -22,10 +19,10 @@ pub struct Request<B = Body> { impl<B> Request<B> { /// Construct a new Request. #[inline] - pub fn new(method: Method, url: Url) -> Request<B> { + pub fn new(method: Method, uri: Uri) -> Request<B> { Request { method: method, - url: url, + uri: uri, version: HttpVersion::default(), headers: Headers::new(), body: None, diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -33,9 +30,9 @@ impl<B> Request<B> { } } - /// Read the Request Url. + /// Read the Request Uri. #[inline] - pub fn url(&self) -> &Url { &self.url } + pub fn uri(&self) -> &Uri { &self.uri } /// Read the Request Version. #[inline] diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -57,9 +54,9 @@ impl<B> Request<B> { #[inline] pub fn headers_mut(&mut self) -> &mut Headers { &mut self.headers } - /// Set the `Url` of this request. + /// Set the `Uri` of this request. #[inline] - pub fn set_url(&mut self, url: Url) { self.url = url; } + pub fn set_uri(&mut self, uri: Uri) { self.uri = uri; } /// Set the `HttpVersion` of this request. #[inline] diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -81,7 +78,7 @@ impl<B> fmt::Debug for Request<B> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Request") .field("method", &self.method) - .field("url", &self.url) + .field("uri", &self.uri) .field("version", &self.version) .field("headers", &self.headers) .finish() diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -90,9 +87,9 @@ impl<B> fmt::Debug for Request<B> { pub fn split<B>(req: Request<B>) -> (RequestHead, Option<B>) { let uri = if req.is_proxy { - Uri::from(req.url) + req.uri } else { - Uri::from_str(&req.url[::url::Position::BeforePath..::url::Position::AfterQuery]).expect("url is not uri") + uri::origin_form(&req.uri) }; let head = RequestHead { subject: ::http::RequestLine(req.method, uri), diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -6,7 +6,8 @@ use std::str::Utf8Error; use std::string::FromUtf8Error; use httparse; -use url; + +pub use uri::UriError; use self::Error::{ Method, diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -21,8 +22,6 @@ use self::Error::{ Utf8 }; -pub use url::ParseError; - /// Result type often returned from methods that can have hyper `Error`s. pub type Result<T> = ::std::result::Result<T, Error>; diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -32,7 +31,7 @@ pub enum Error { /// An invalid `Method`, such as `GE,T`. Method, /// An invalid `Uri`, such as `exam ple.domain`. - Uri(url::ParseError), + Uri(UriError), /// An invalid `HttpVersion`, such as `HTP/1.1` Version, /// An invalid `Header`. diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -102,15 +101,15 @@ impl StdError for Error { } } -impl From<IoError> for Error { - fn from(err: IoError) -> Error { - Io(err) +impl From<UriError> for Error { + fn from(err: UriError) -> Error { + Uri(err) } } -impl From<url::ParseError> for Error { - fn from(err: url::ParseError) -> Error { - Uri(err) +impl From<IoError> for Error { + fn from(err: IoError) -> Error { + Io(err) } } diff --git a/src/header/common/content_disposition.rs b/src/header/common/content_disposition.rs --- a/src/header/common/content_disposition.rs +++ b/src/header/common/content_disposition.rs @@ -9,10 +9,9 @@ use language_tags::LanguageTag; use std::fmt; use unicase::UniCase; -use url::percent_encoding; use header::{Header, Raw, parsing}; -use header::parsing::{parse_extended_value, HTTP_VALUE}; +use header::parsing::{parse_extended_value, http_percent_encode}; use header::shared::Charset; /// The implied disposition of the content of the HTTP body diff --git a/src/header/common/content_disposition.rs b/src/header/common/content_disposition.rs --- a/src/header/common/content_disposition.rs +++ b/src/header/common/content_disposition.rs @@ -182,8 +181,7 @@ impl fmt::Display for ContentDisposition { try!(write!(f, "{}", lang)); }; try!(write!(f, "'")); - try!(f.write_str( - &percent_encoding::percent_encode(bytes, HTTP_VALUE).to_string())) + try!(http_percent_encode(f, bytes)) } }, DispositionParam::Ext(ref k, ref v) => try!(write!(f, "; {}=\"{}\"", k, v)), diff --git a/src/header/parsing.rs b/src/header/parsing.rs --- a/src/header/parsing.rs +++ b/src/header/parsing.rs @@ -9,6 +9,7 @@ use url::percent_encoding; use header::Raw; use header::shared::Charset; + /// Reads a single raw string when parsing a header. pub fn from_one_raw_str<T: str::FromStr>(raw: &Raw) -> ::Result<T> { if let Some(line) = raw.one() { diff --git a/src/header/parsing.rs b/src/header/parsing.rs --- a/src/header/parsing.rs +++ b/src/header/parsing.rs @@ -132,25 +133,11 @@ pub fn parse_extended_value(val: &str) -> ::Result<ExtendedValue> { }) } -define_encode_set! { - /// This encode set is used for HTTP header values and is defined at - /// https://tools.ietf.org/html/rfc5987#section-3.2 - pub HTTP_VALUE = [percent_encoding::SIMPLE_ENCODE_SET] | { - ' ', '"', '%', '\'', '(', ')', '*', ',', '/', ':', ';', '<', '-', '>', '?', - '[', '\\', ']', '{', '}' - } -} - -impl fmt::Debug for HTTP_VALUE { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad("HTTP_VALUE") - } -} impl Display for ExtendedValue { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let encoded_value = - percent_encoding::percent_encode(&self.value[..], HTTP_VALUE); + percent_encoding::percent_encode(&self.value[..], self::percent_encoding_http::HTTP_VALUE); if let Some(ref lang) = self.language_tag { write!(f, "{}'{}'{}", self.charset, lang, encoded_value) } else { diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -61,7 +61,7 @@ impl Http1Transaction for ServerTransaction { let path = unsafe { ByteStr::from_utf8_unchecked(path) }; let subject = RequestLine( method, - try!(::uri::from_mem_str(path)), + try!(::uri::from_byte_str(path)), ); headers.extend(HeadersAsBytesIter { diff --git a/src/http/str.rs b/src/http/str.rs --- a/src/http/str.rs +++ b/src/http/str.rs @@ -1,8 +1,9 @@ +use std::ops::Deref; use std::str; use bytes::Bytes; -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct ByteStr(Bytes); impl ByteStr { diff --git a/src/http/str.rs b/src/http/str.rs --- a/src/http/str.rs +++ b/src/http/str.rs @@ -10,7 +11,35 @@ impl ByteStr { ByteStr(slice) } + pub fn from_static(s: &'static str) -> ByteStr { + ByteStr(Bytes::from_static(s.as_bytes())) + } + + pub fn slice(&self, from: usize, to: usize) -> ByteStr { + assert!(self.as_str().is_char_boundary(from)); + assert!(self.as_str().is_char_boundary(to)); + ByteStr(self.0.slice(from, to)) + } + + pub fn slice_to(&self, idx: usize) -> ByteStr { + assert!(self.as_str().is_char_boundary(idx)); + ByteStr(self.0.slice_to(idx)) + } + pub fn as_str(&self) -> &str { unsafe { str::from_utf8_unchecked(self.0.as_ref()) } } } + +impl Deref for ByteStr { + type Target = str; + fn deref(&self) -> &str { + self.as_str() + } +} + +impl<'a> From<&'a str> for ByteStr { + fn from(s: &'a str) -> ByteStr { + ByteStr(Bytes::from(s)) + } +} diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -1,13 +1,8 @@ -use std::borrow::Cow; +use std::error::Error as StdError; use std::fmt::{Display, self}; -use std::ops::Deref; use std::str::{self, FromStr}; use http::ByteStr; -use Url; -use url::ParseError as UrlError; - -use Error; /// The Request-URI of a Request's StartLine. /// diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -32,9 +27,9 @@ use Error; /// | | | | | /// scheme authority path query fragment /// ``` -#[derive(Clone)] +#[derive(Clone, Hash)] pub struct Uri { - source: InternalUri, + source: ByteStr, scheme_end: Option<usize>, authority_end: Option<usize>, query: Option<usize>, diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -43,20 +38,23 @@ pub struct Uri { impl Uri { /// Parse a string into a `Uri`. - fn new(s: InternalUri) -> Result<Uri, Error> { + fn new(s: ByteStr) -> Result<Uri, UriError> { if s.len() == 0 { - Err(Error::Uri(UrlError::RelativeUrlWithoutBase)) + Err(UriError(ErrorKind::Empty)) } else if s.as_bytes() == b"*" { + // asterisk-form Ok(Uri { - source: InternalUri::Cow("*".into()), + source: ByteStr::from_static("*"), scheme_end: None, authority_end: None, query: None, fragment: None, }) } else if s.as_bytes() == b"/" { + // shortcut for '/' Ok(Uri::default()) } else if s.as_bytes()[0] == b'/' { + // origin-form let query = parse_query(&s); let fragment = parse_fragment(&s); Ok(Uri { diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -67,22 +65,14 @@ impl Uri { fragment: fragment, }) } else if s.contains("://") { + // absolute-form let scheme = parse_scheme(&s); let auth = parse_authority(&s); - if let Some(end) = scheme { - match &s[..end] { - "ftp" | "gopher" | "http" | "https" | "ws" | "wss" => {}, - "blob" | "file" => return Err(Error::Method), - _ => return Err(Error::Method), - } - match auth { - Some(a) => { - if (end + 3) == a { - return Err(Error::Method); - } - }, - None => return Err(Error::Method), - } + let scheme_end = scheme.expect("just checked for ':' above"); + let auth_end = auth.expect("just checked for ://"); + if scheme_end + 3 == auth_end { + // authority was empty + return Err(UriError(ErrorKind::MissingAuthority)); } let query = parse_query(&s); let fragment = parse_fragment(&s); diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -94,8 +84,10 @@ impl Uri { fragment: fragment, }) } else if (s.contains("/") || s.contains("?")) && !s.contains("://") { - return Err(Error::Method) + // last possibility is authority-form, above are illegal characters + return Err(UriError(ErrorKind::Malformed)) } else { + // authority-form let len = s.len(); Ok(Uri { source: s, diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -220,25 +212,12 @@ fn parse_fragment(s: &str) -> Option<usize> { } impl FromStr for Uri { - type Err = Error; + type Err = UriError; - fn from_str(s: &str) -> Result<Uri, Error> { + fn from_str(s: &str) -> Result<Uri, UriError> { //TODO: refactor such that the to_owned() is only required at the end //of successful parsing, so an Err doesn't needlessly clone the string. - Uri::new(InternalUri::Cow(Cow::Owned(s.to_owned()))) - } -} - -impl From<Url> for Uri { - fn from(url: Url) -> Uri { - let s = InternalUri::Cow(Cow::Owned(url.into_string())); - // TODO: we could build the indices with some simple subtraction, - // instead of re-parsing an already parsed string. - // For example: - // let scheme_end = url[..url::Position::AfterScheme].as_ptr() as usize - // - url.as_str().as_ptr() as usize; - // etc - Uri::new(s).expect("Uri::From<Url> failed") + Uri::new(ByteStr::from(s)) } } diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -259,7 +238,7 @@ impl AsRef<str> for Uri { impl Default for Uri { fn default() -> Uri { Uri { - source: InternalUri::Cow("/".into()), + source: ByteStr::from_static("/"), scheme_end: None, authority_end: None, query: None,
diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -28,7 +28,7 @@ fn get_one_at_a_time(b: &mut test::Bencher) { let client = hyper::Client::new(&handle); - let url: hyper::Url = format!("http://{}/get", addr).parse().unwrap(); + let url: hyper::Uri = format!("http://{}/get", addr).parse().unwrap(); b.bytes = 160 * 2 + PHRASE.len() as u64; b.iter(move || { diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -51,7 +51,7 @@ fn post_one_at_a_time(b: &mut test::Bencher) { let client = hyper::Client::new(&handle); - let url: hyper::Url = format!("http://{}/get", addr).parse().unwrap(); + let url: hyper::Uri = format!("http://{}/get", addr).parse().unwrap(); let post = "foo bar baz quux"; b.bytes = 180 * 2 + post.len() as u64 + PHRASE.len() as u64; diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -185,13 +185,12 @@ impl<S: SslClient> HttpsConnector<S> { mod tests { use std::io; use tokio::reactor::Core; - use Url; use super::{Connect, HttpConnector}; #[test] fn test_non_http_url() { let mut core = Core::new().unwrap(); - let url = Url::parse("file:///home/sean/foo.txt").unwrap(); + let url = "/foo/bar?baz".parse().unwrap(); let connector = HttpConnector::new(1, &core.handle()); assert_eq!(core.run(connector.connect(url)).unwrap_err().kind(), io::ErrorKind::InvalidInput); diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -145,7 +144,6 @@ mod tests { use std::error::Error as StdError; use std::io; use httparse; - use url; use super::Error; use super::Error::*; diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -185,7 +183,6 @@ mod tests { fn test_from() { from_and_cause!(io::Error::new(io::ErrorKind::Other, "other") => Io(..)); - from_and_cause!(url::ParseError::EmptyHost => Uri(..)); from!(httparse::Error::HeaderName => Header); from!(httparse::Error::HeaderName => Header); diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -196,14 +193,4 @@ mod tests { from!(httparse::Error::TooManyHeaders => TooLarge); from!(httparse::Error::Version => Version); } - - #[cfg(feature = "openssl")] - #[test] - fn test_from_ssl() { - use openssl::ssl::error::SslError; - - from!(SslError::StreamError( - io::Error::new(io::ErrorKind::Other, "ssl negotiation")) => Io(..)); - from_and_cause!(SslError::SslSessionClosed => Ssl(..)); - } } diff --git a/src/header/parsing.rs b/src/header/parsing.rs --- a/src/header/parsing.rs +++ b/src/header/parsing.rs @@ -159,6 +146,33 @@ impl Display for ExtendedValue { } } +/// Percent encode a sequence of bytes with a character set defined in +/// https://tools.ietf.org/html/rfc5987#section-3.2 +pub fn http_percent_encode(f: &mut fmt::Formatter, bytes: &[u8]) -> fmt::Result { + let encoded = percent_encoding::percent_encode(bytes, self::percent_encoding_http::HTTP_VALUE); + fmt::Display::fmt(&encoded, f) +} + +mod percent_encoding_http { + use std::fmt; + use url::percent_encoding; + + define_encode_set! { + /// This encode set is used for HTTP header values and is defined at + /// https://tools.ietf.org/html/rfc5987#section-3.2 + pub HTTP_VALUE = [percent_encoding::SIMPLE_ENCODE_SET] | { + ' ', '"', '%', '\'', '(', ')', '*', ',', '/', ':', ';', '<', '-', '>', '?', + '[', '\\', ']', '{', '}' + } + } + + impl fmt::Debug for HTTP_VALUE { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad("HTTP_VALUE") + } + } +} + #[cfg(test)] mod tests { use header::shared::Charset; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,6 @@ #![doc(html_root_url = "https://hyperium.github.io/hyper/")] #![deny(missing_docs)] -//#![deny(warnings)] +#![deny(warnings)] #![deny(missing_debug_implementations)] #![cfg_attr(all(test, feature = "nightly"), feature(test))] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -35,7 +35,6 @@ extern crate test; pub use uri::Uri; -pub use url::Url; pub use client::Client; pub use error::{Result, Error}; pub use header::Headers; diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -280,33 +259,66 @@ impl Display for Uri { } } -pub fn from_mem_str(s: ByteStr) -> Result<Uri, Error> { - Uri::new(InternalUri::Shared(s)) +pub fn from_byte_str(s: ByteStr) -> Result<Uri, UriError> { + Uri::new(s) } -#[derive(Clone)] -enum InternalUri { - Cow(Cow<'static, str>), - Shared(ByteStr), +pub fn scheme_and_authority(uri: &Uri) -> Option<Uri> { + if uri.scheme_end.is_some() { + Some(Uri { + source: uri.source.slice_to(uri.authority_end.expect("scheme without authority")), + scheme_end: uri.scheme_end, + authority_end: uri.authority_end, + query: None, + fragment: None, + }) + } else { + None + } } -impl InternalUri { - fn as_str(&self) -> &str { - match *self { - InternalUri::Cow(ref s) => s.as_ref(), - InternalUri::Shared(ref m) => m.as_str(), - } +pub fn origin_form(uri: &Uri) -> Uri { + let start = uri.authority_end.unwrap_or(uri.scheme_end.unwrap_or(0)); + let end = if let Some(f) = uri.fragment { + uri.source.len() - f - 1 + } else { + uri.source.len() + }; + Uri { + source: uri.source.slice(start, end), + scheme_end: None, + authority_end: None, + query: uri.query, + fragment: None, } } -impl Deref for InternalUri { - type Target = str; +/// An error parsing a `Uri`. +#[derive(Clone, Debug)] +pub struct UriError(ErrorKind); - fn deref(&self) -> &str { - self.as_str() +#[derive(Clone, Debug)] +enum ErrorKind { + Empty, + Malformed, + MissingAuthority, +} + +impl fmt::Display for UriError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad(self.description()) } } +impl StdError for UriError { + fn description(&self) -> &str { + match self.0 { + ErrorKind::Empty => "empty Uri string", + ErrorKind::Malformed => "invalid character in Uri authority", + ErrorKind::MissingAuthority => "absolute Uri missing authority segment", + } + } +} macro_rules! test_parse { ( diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -443,13 +455,3 @@ fn test_uri_parse_error() { err("localhost/"); err("localhost?key=val"); } - -#[test] -fn test_uri_from_url() { - let uri = Uri::from(Url::parse("http://test.com/nazghul?test=3").unwrap()); - assert_eq!(uri.path(), "/nazghul"); - assert_eq!(uri.authority(), Some("test.com")); - assert_eq!(uri.scheme(), Some("http")); - assert_eq!(uri.query(), Some("test=3")); - assert_eq!(uri.as_ref(), "http://test.com/nazghul?test=3"); -}
Remove Url depedency Now that `hyper::Uri` has sufficient parsing capability, and can represent any URI for the server or client, does it make sense to still also use the `Url` type? When looking at the rustdocs generated, it certainly looks confusing that there is both `Url` and `Uri` at the crate root. And issues like #1087 and others sometimes appear because people assume hyper controls the `Url` type. Some options I'm considering: - Remove any direct usage of `Url`, but implement `From<Url> for Uri`, so people can easily do `Request::new(Get, url.into())`. - Remove the `url` crate dependency entirely. This would probably be the ideal option, so that the crate is only included in projects that explicitly ask for it. However, it does make it slightly more annoying to create client requests. /cc @frewsxcv @nox (@alexcrichton for sccache experience)
At least for me in how I've worked with libs in the past it's pretty rare for me to have a parsed `Url` on hand. Typically I manage it via a string and then just pass it to a library (there's also typically very little manipulation of the URL as well). I could go either way, but in some sense reducing the suite of public dependencies is always a nice win! (if necessary though I'd definitely still use it for internal usage if the need arose) hyper no longer makes use the of the `Url` type internally anywhere. It's only usage at this point is in `client::Request`, for setting the target of the `Request`, and in the generic `Connect` type that `Client` uses. The `Connect` trait is basically an alias for `Server<Request=Url, Response=T> where T: Io`. ---- So, hyper could remove the public re-export, and change `Client` and `client::Request` to make use of `hyper::Uri`. That looks like the right direction to go. My last remaining question is whether there is value in implementing `From<Url> for Uri`, since it'd be a near-free conversion, and people who do have a `Url` could then do `client.get(url.into())`.
2017-03-21T18:03:13Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,074
hyperium__hyper-1074
[ "1073" ]
dc97dd77f45486d9cb9a22a1859809c5af5579e2
diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -4,6 +4,7 @@ use std::marker::PhantomData; use std::time::Instant; use futures::{Poll, Async, AsyncSink, Stream, Sink, StartSend}; +use futures::task::Task; use tokio::io::Io; use tokio_proto::streaming::pipeline::{Frame, Transport}; diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -39,6 +40,7 @@ where I: Io, state: State { reading: Reading::Init, writing: Writing::Init, + read_task: None, keep_alive: keep_alive, }, _marker: PhantomData, diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -49,13 +51,6 @@ where I: Io, self.io.parse::<T>() } - fn is_read_ready(&mut self) -> bool { - match self.state.reading { - Reading::Init | - Reading::Body(..) => self.io.poll_read().is_ready(), - Reading::KeepAlive | Reading::Closed => true, - } - } fn is_read_closed(&self) -> bool { self.state.is_read_closed() diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -91,7 +86,7 @@ where I: Io, self.state.close_read(); self.io.consume_leading_lines(); let was_mid_parse = !self.io.read_buf().is_empty(); - let must_respond_with_error = !self.state.was_idle(); + let must_respond_with_error = !self.state.is_idle(); return if was_mid_parse { debug!("parse error ({}) with bytes: {:?}", e, self.io.read_buf()); Ok(Async::Ready(Some(Frame::Error { error: e }))) diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -159,6 +154,43 @@ where I: Io, ret } + fn maybe_park_read(&mut self) { + if self.io.poll_read().is_ready() { + // the Io object is ready to read, which means it will never alert + // us that it is ready until we drain it. However, we're currently + // finished reading, so we need to park the task to be able to + // wake back up later when more reading should happen. + self.state.read_task = Some(::futures::task::park()); + } + } + + fn maybe_unpark(&mut self) { + // its possible that we returned NotReady from poll() without having + // exhausted the underlying Io. We would have done this when we + // determined we couldn't keep reading until we knew how writing + // would finish. + // + // When writing finishes, we need to wake the task up in case there + // is more reading that can be done, to start a new message. + match self.state.reading { + Reading::Body(..) => return, + Reading::Init | + Reading::KeepAlive | Reading::Closed => (), + } + + match self.state.writing { + Writing::Body(..) | + Writing::Ending(..) => return, + Writing::Init | + Writing::KeepAlive | + Writing::Closed => (), + } + + if let Some(task) = self.state.read_task.take() { + task.unpark(); + } + } + fn can_write_head(&self) -> bool { match self.state.writing { Writing::Init => true, diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -290,9 +322,7 @@ where I: Io, try_nb!(self.io.flush()); self.state.try_keep_alive(); trace!("flushed {:?}", self.state); - if self.is_read_ready() { - ::futures::task::park().unpark(); - } + self.maybe_unpark(); Ok(ret) } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -309,6 +339,7 @@ where I: Io, fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { trace!("Conn::poll()"); + self.state.read_task.take(); if self.is_read_closed() { trace!("Conn::poll when closed"); diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -326,6 +357,7 @@ where I: Io, }) } else { trace!("poll when on keep-alive"); + self.maybe_park_read(); Ok(Async::NotReady) } } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -418,6 +450,7 @@ impl<I, B: AsRef<[u8]>, T, K: fmt::Debug> fmt::Debug for Conn<I, B, T, K> { struct State<B, K> { reading: Reading, writing: Writing<B>, + read_task: Option<Task>, keep_alive: K, } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -443,6 +476,7 @@ impl<B: AsRef<[u8]>, K: fmt::Debug> fmt::Debug for State<B, K> { .field("reading", &self.reading) .field("writing", &self.writing) .field("keep_alive", &self.keep_alive) + .field("read_task", &self.read_task) .finish() } } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -543,7 +577,7 @@ impl<B, K: KeepAlive> State<B, K> { } } - fn was_idle(&self) -> bool { + fn is_idle(&self) -> bool { if let KA::Idle(..) = self.keep_alive.status() { true } else {
diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -605,14 +639,14 @@ impl<'a, T: fmt::Debug + 'a, B: AsRef<[u8]> + 'a> fmt::Debug for DebugFrame<'a, #[cfg(test)] mod tests { - use futures::{Async, Stream, Sink}; + use futures::{Async, Future, Stream, Sink}; use tokio_proto::streaming::pipeline::Frame; use http::{self, MessageHead, ServerTransaction}; use http::h1::Encoder; use mock::AsyncIo; - use super::{Conn, Writing}; + use super::{Conn, Reading, Writing}; use ::uri::Uri; use std::str::FromStr; diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -637,17 +671,20 @@ mod tests { #[test] fn test_conn_parse_partial() { - let good_message = b"GET / HTTP/1.1\r\nHost: foo.bar\r\n\r\n".to_vec(); - let io = AsyncIo::new_buf(good_message, 10); - let mut conn = Conn::<_, http::Chunk, ServerTransaction>::new(io, Default::default()); - assert!(conn.poll().unwrap().is_not_ready()); - conn.io.io_mut().block_in(50); - let async = conn.poll().unwrap(); - assert!(async.is_ready()); - match async { - Async::Ready(Some(Frame::Message { .. })) => (), - f => panic!("frame is not Message: {:?}", f), - } + let _: Result<(), ()> = ::futures::lazy(|| { + let good_message = b"GET / HTTP/1.1\r\nHost: foo.bar\r\n\r\n".to_vec(); + let io = AsyncIo::new_buf(good_message, 10); + let mut conn = Conn::<_, http::Chunk, ServerTransaction>::new(io, Default::default()); + assert!(conn.poll().unwrap().is_not_ready()); + conn.io.io_mut().block_in(50); + let async = conn.poll().unwrap(); + assert!(async.is_ready()); + match async { + Async::Ready(Some(Frame::Message { .. })) => (), + f => panic!("frame is not Message: {:?}", f), + } + Ok(()) + }).wait(); } #[test] diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -664,9 +701,6 @@ mod tests { #[test] fn test_conn_body_write_length() { - extern crate pretty_env_logger; - use ::futures::Future; - let _ = pretty_env_logger::init(); let _: Result<(), ()> = ::futures::lazy(|| { let io = AsyncIo::new_buf(vec![], 0); let mut conn = Conn::<_, http::Chunk, ServerTransaction>::new(io, Default::default()); diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -703,7 +737,6 @@ mod tests { #[test] fn test_conn_body_write_chunked() { - use ::futures::Future; let _: Result<(), ()> = ::futures::lazy(|| { let io = AsyncIo::new_buf(vec![], 4096); let mut conn = Conn::<_, http::Chunk, ServerTransaction>::new(io, Default::default()); diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -714,6 +747,65 @@ mod tests { Ok(()) }).wait(); } + + #[test] + fn test_conn_parking() { + use std::sync::Arc; + use futures::task::Unpark; + + struct Car { + permit: bool, + } + impl Unpark for Car { + fn unpark(&self) { + assert!(self.permit, "unparked without permit"); + } + } + + fn car(permit: bool) -> Arc<Unpark> { + Arc::new(Car { + permit: permit, + }) + } + + // test that once writing is done, unparks + let f = ::futures::lazy(|| { + let io = AsyncIo::new_buf(vec![], 4096); + let mut conn = Conn::<_, http::Chunk, ServerTransaction>::new(io, Default::default()); + conn.state.reading = Reading::KeepAlive; + assert!(conn.poll().unwrap().is_not_ready()); + + conn.state.writing = Writing::KeepAlive; + assert!(conn.poll_complete().unwrap().is_ready()); + Ok::<(), ()>(()) + }); + ::futures::executor::spawn(f).poll_future(car(true)).unwrap(); + + + // test that flushing when not waiting on read doesn't unpark + let f = ::futures::lazy(|| { + let io = AsyncIo::new_buf(vec![], 4096); + let mut conn = Conn::<_, http::Chunk, ServerTransaction>::new(io, Default::default()); + conn.state.writing = Writing::KeepAlive; + assert!(conn.poll_complete().unwrap().is_ready()); + Ok::<(), ()>(()) + }); + ::futures::executor::spawn(f).poll_future(car(false)).unwrap(); + + + // test that flushing and writing isn't done doesn't unpark + let f = ::futures::lazy(|| { + let io = AsyncIo::new_buf(vec![], 4096); + let mut conn = Conn::<_, http::Chunk, ServerTransaction>::new(io, Default::default()); + conn.state.reading = Reading::KeepAlive; + assert!(conn.poll().unwrap().is_not_ready()); + conn.state.writing = Writing::Body(Encoder::length(5_000), None); + assert!(conn.poll_complete().unwrap().is_ready()); + Ok::<(), ()>(()) + }); + ::futures::executor::spawn(f).poll_future(car(false)).unwrap(); + } + #[test] fn test_conn_closed_write() { let io = AsyncIo::new_buf(vec![], 0);
Infinite loop if body sender is dropped Originally [reported here](https://github.com/tokio-rs/tokio-core/issues/177#issuecomment-281574226) it looks like this code: ```rust extern crate env_logger; extern crate futures; extern crate hyper; use hyper::{Body, Error}; use hyper::server::{Request, Response}; use futures::future; struct MyService; impl hyper::server::Service for MyService { type Request = Request; type Response = Response; type Error = Error; type Future = future::FutureResult<Self::Response, Self::Error>; fn call(&self, _req: Request) -> Self::Future { let (snd, rcv) = Body::pair(); // Leak the sender, so rcv never gets chunks and is never closed. ::std::mem::forget(snd); future::ok(Response::new().with_body(rcv)) } } fn main() { env_logger::init().unwrap(); let addr = "127.0.0.1:1337".parse().unwrap(); let server = hyper::server::Http::new().bind(&addr, || Ok(MyService)).unwrap(); println!("Running on http://{}", server.local_addr().unwrap()); server.run().unwrap(); } ``` sends hyper into an infinite loop [here](https://github.com/hyperium/hyper/blob/435fe84bf52fbbf819068402d6c8e902aa7a6685/src/http/conn.rs#L294).
I've been looking in to trying to park and unpark a little less, but one thing here strikes me as odd: if the Sender hasn't sent anything, why would tokio try to flush again, especially if the previous flush already said it was complete? IIRC "flush" in this case basically just happens pretty commonly, but @carllerche would know for sure There are potentially some extra calls to flush that were added before the park / unpack semantics were figured out. They can probably be removed at some point though I am a bit worried about breaking existing code that happens to rely on it (hyper might be relying on them)
2017-02-23T00:36:01Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,054
hyperium__hyper-1054
[ "1041" ]
04f169034a4bf34927a65408cf418dcfacfe15f0
diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -7,6 +7,7 @@ use http::{Body, RequestHead}; use method::Method; use uri::Uri; use version::HttpVersion; +use std::str::FromStr; /// A client request to a remote server. pub struct Request { diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -79,7 +80,7 @@ impl fmt::Debug for Request { } pub fn split(req: Request) -> (RequestHead, Option<Body>) { - let uri = Uri::new(&req.url[::url::Position::BeforePath..::url::Position::AfterQuery]).expect("url is uri"); + let uri = Uri::from_str(&req.url[::url::Position::BeforePath..::url::Position::AfterQuery]).expect("url is uri"); let head = RequestHead { subject: ::http::RequestLine(req.method, uri), headers: req.headers, diff --git a/src/http/buf.rs b/src/http/buf.rs --- a/src/http/buf.rs +++ b/src/http/buf.rs @@ -4,6 +4,7 @@ use std::fmt; use std::io::{self, Read}; use std::ops::{Index, Range, RangeFrom, RangeTo, RangeFull}; use std::ptr; +use std::str; use std::sync::Arc; pub struct MemBuf { diff --git a/src/http/buf.rs b/src/http/buf.rs --- a/src/http/buf.rs +++ b/src/http/buf.rs @@ -49,8 +50,8 @@ impl MemBuf { } pub fn slice(&self, len: usize) -> MemSlice { - assert!(self.end - self.start.get() >= len); let start = self.start.get(); + assert!(!(self.end - start < len)); let end = start + len; self.start.set(end); MemSlice { diff --git a/src/http/buf.rs b/src/http/buf.rs --- a/src/http/buf.rs +++ b/src/http/buf.rs @@ -196,6 +197,19 @@ impl From<Vec<u8>> for MemBuf { } } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MemStr(MemSlice); + +impl MemStr { + pub unsafe fn from_utf8_unchecked(slice: MemSlice) -> MemStr { + MemStr(slice) + } + + pub fn as_str(&self) -> &str { + unsafe { str::from_utf8_unchecked(self.0.as_ref()) } + } +} + pub struct MemSlice { buf: Arc<UnsafeCell<Vec<u8>>>, start: usize, diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -6,7 +6,7 @@ use httparse; use header::{self, Headers, ContentLength, TransferEncoding}; use http::{MessageHead, RawStatus, Http1Transaction, ParseResult, ServerTransaction, ClientTransaction, RequestLine}; use http::h1::{Encoder, Decoder}; -use http::buf::{MemBuf, MemSlice}; +use http::buf::{MemBuf, MemSlice, MemStr}; use method::Method; use status::StatusCode; use version::HttpVersion::{Http10, Http11}; diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -33,18 +33,26 @@ impl Http1Transaction for ServerTransaction { Ok(match try!(req.parse(buf.bytes())) { httparse::Status::Complete(len) => { trace!("Request.parse Complete({})", len); - let mut headers = Headers::with_capacity(req.headers.len()); let slice = buf.slice(len); + let path = req.path.unwrap(); + let path_start = path.as_ptr() as usize - slice.as_ref().as_ptr() as usize; + let path_end = path_start + path.len(); + let path = slice.slice(path_start..path_end); + // path was found to be utf8 by httparse + let path = unsafe { MemStr::from_utf8_unchecked(path) }; + let subject = RequestLine( + try!(req.method.unwrap().parse()), + try!(::uri::from_mem_str(path)), + ); + let mut headers = Headers::with_capacity(req.headers.len()); headers.extend(HeadersAsMemSliceIter { headers: req.headers.iter(), slice: slice, }); + Some((MessageHead { version: if req.version.unwrap() == 1 { Http11 } else { Http10 }, - subject: RequestLine( - try!(req.method.unwrap().parse()), - try!(req.path.unwrap().parse()) - ), + subject: subject, headers: headers, }, len)) } diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -143,7 +151,7 @@ impl Http1Transaction for ClientTransaction { headers: headers, }, len)) }, - httparse::Status::Partial => None + httparse::Status::Partial => None, }) } diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -1,6 +1,8 @@ use std::borrow::Cow; use std::fmt::{Display, self}; -use std::str::FromStr; +use std::ops::Deref; +use std::str::{self, FromStr}; +use http::buf::MemStr; use Url; use url::ParseError as UrlError; diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -30,7 +32,7 @@ use Error; /// scheme authority path query fragment #[derive(Clone)] pub struct Uri { - source: Cow<'static, str>, + source: InternalUri, scheme_end: Option<usize>, authority_end: Option<usize>, query: Option<usize>, diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -39,31 +41,32 @@ pub struct Uri { impl Uri { /// Parse a string into a `Uri`. - pub fn new(s: &str) -> Result<Uri, Error> { - let bytes = s.as_bytes(); - if bytes.len() == 0 { + fn new(s: InternalUri) -> Result<Uri, Error> { + if s.len() == 0 { Err(Error::Uri(UrlError::RelativeUrlWithoutBase)) - } else if bytes == b"*" { + } else if s.as_bytes() == b"*" { Ok(Uri { - source: "*".into(), + source: InternalUri::Cow("*".into()), scheme_end: None, authority_end: None, query: None, fragment: None, }) - } else if bytes == b"/" { + } else if s.as_bytes() == b"/" { Ok(Uri::default()) - } else if bytes.starts_with(b"/") { + } else if s.as_bytes()[0] == b'/' { + let query = parse_query(&s); + let fragment = parse_fragment(&s); Ok(Uri { - source: s.to_owned().into(), + source: s, scheme_end: None, authority_end: None, - query: parse_query(s), - fragment: parse_fragment(s), + query: query, + fragment: fragment, }) } else if s.contains("://") { - let scheme = parse_scheme(s); - let auth = parse_authority(s); + let scheme = parse_scheme(&s); + let auth = parse_authority(&s); if let Some(end) = scheme { match &s[..end] { "ftp" | "gopher" | "http" | "https" | "ws" | "wss" => {}, diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -79,20 +82,23 @@ impl Uri { None => return Err(Error::Method), } } + let query = parse_query(&s); + let fragment = parse_fragment(&s); Ok(Uri { - source: s.to_owned().into(), + source: s, scheme_end: scheme, authority_end: auth, - query: parse_query(s), - fragment: parse_fragment(s), + query: query, + fragment: fragment, }) } else if (s.contains("/") || s.contains("?")) && !s.contains("://") { return Err(Error::Method) } else { + let len = s.len(); Ok(Uri { - source: s.to_owned().into(), + source: s, scheme_end: None, - authority_end: Some(s.len()), + authority_end: Some(len), query: None, fragment: None, }) diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -108,9 +114,10 @@ impl Uri { if fragment_len > 0 { fragment_len + 1 } else { 0 }; if index >= end { if self.scheme().is_some() { - return "/" // absolute-form MUST have path + "/" // absolute-form MUST have path + } else { + "" } - "" } else { &self.source[index..end] } diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -158,7 +165,8 @@ impl Uri { let fragment_len = self.fragment.unwrap_or(0); let fragment_len = if fragment_len > 0 { fragment_len + 1 } else { 0 }; if let Some(len) = self.query { - Some(&self.source[self.source.len() - len - fragment_len..self.source.len() - fragment_len]) + Some(&self.source[self.source.len() - len - fragment_len.. + self.source.len() - fragment_len]) } else { None } diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -180,7 +188,7 @@ fn parse_scheme(s: &str) -> Option<usize> { fn parse_authority(s: &str) -> Option<usize> { let i = s.find("://").and_then(|p| Some(p + 3)).unwrap_or(0); - + Some(&s[i..].split("/") .next() .unwrap_or(s) diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -209,32 +217,43 @@ impl FromStr for Uri { type Err = Error; fn from_str(s: &str) -> Result<Uri, Error> { - Uri::new(s) + //TODO: refactor such that the to_owned() is only required at the end + //of successful parsing, so an Err doesn't needlessly clone the string. + Uri::new(InternalUri::Cow(Cow::Owned(s.to_owned()))) } } impl From<Url> for Uri { fn from(url: Url) -> Uri { - Uri::new(url.as_str()).expect("Uri::From<Url> failed") + let s = InternalUri::Cow(Cow::Owned(url.into_string())); + // TODO: we could build the indices with some simple subtraction, + // instead of re-parsing an already parsed string. + // For example: + // let scheme_end = url[..url::Position::AfterScheme].as_ptr() as usize + // - url.as_str().as_ptr() as usize; + // etc + Uri::new(s).expect("Uri::From<Url> failed") } } impl PartialEq for Uri { fn eq(&self, other: &Uri) -> bool { - self.source == other.source + self.source.as_str() == other.source.as_str() } } +impl Eq for Uri {} + impl AsRef<str> for Uri { fn as_ref(&self) -> &str { - &self.source + self.source.as_str() } } impl Default for Uri { fn default() -> Uri { Uri { - source: "/".into(), + source: InternalUri::Cow("/".into()), scheme_end: None, authority_end: None, query: None,
diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -577,6 +577,8 @@ mod tests { use super::{Conn, Writing}; use ::uri::Uri; + use std::str::FromStr; + #[test] fn test_conn_init_read() { let good_message = b"GET / HTTP/1.1\r\n\r\n".to_vec(); diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -587,7 +589,7 @@ mod tests { match conn.poll().unwrap() { Async::Ready(Some(Frame::Message { message, body: false })) => { assert_eq!(message, MessageHead { - subject: ::http::RequestLine(::Get, Uri::new("/").unwrap()), + subject: ::http::RequestLine(::Get, Uri::from_str("/").unwrap()), .. MessageHead::default() }) }, diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -326,5 +334,4 @@ mod tests { raw.restart(); }); } - } diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -167,7 +175,7 @@ impl Uri { #[cfg(test)] fn fragment(&self) -> Option<&str> { if let Some(len) = self.fragment { - Some(&self.source[self.source.len() - len..]) + Some(&self.source[self.source.len() - len..self.source.len()]) } else { None } diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -245,16 +264,44 @@ impl Default for Uri { impl fmt::Debug for Uri { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Debug::fmt(&self.source.as_ref(), f) + fmt::Debug::fmt(self.as_ref(), f) } } impl Display for Uri { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_str(&self.source) + f.write_str(self.as_ref()) + } +} + +pub fn from_mem_str(s: MemStr) -> Result<Uri, Error> { + Uri::new(InternalUri::Shared(s)) +} + +#[derive(Clone)] +enum InternalUri { + Cow(Cow<'static, str>), + Shared(MemStr), +} + +impl InternalUri { + fn as_str(&self) -> &str { + match *self { + InternalUri::Cow(ref s) => s.as_ref(), + InternalUri::Shared(ref m) => m.as_str(), + } + } +} + +impl Deref for InternalUri { + type Target = str; + + fn deref(&self) -> &str { + self.as_str() } } + macro_rules! test_parse { ( $test_name:ident, diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -263,7 +310,7 @@ macro_rules! test_parse { ) => ( #[test] fn $test_name() { - let uri = Uri::new($str).unwrap(); + let uri = Uri::from_str($str).unwrap(); $( assert_eq!(uri.$method(), $value); )+ diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -368,7 +415,7 @@ test_parse! { #[test] fn test_uri_parse_error() { fn err(s: &str) { - Uri::new(s).unwrap_err(); + Uri::from_str(s).unwrap_err(); } err("http://");
Make Uri use MemSlice internally
New version with internal enum. There would also need to be a change in `http/h1/parse`, instead of using `req.path.unwrap().parse()`. Instead, we want to create a `Uri` using the related `MemSlice`. It could look like this: ```rust let path = slice.slice(path_start..path_end); // path was found to be utf8 by httparse let path = unsafe { MemStr::from_utf8_unchecked(path) }; let uri = try!(::uri::from_mem_str(path)); ``` Updated. @seanmonstar: Updated: anything else to change? New benches: ``` running 2 tests test get_one_at_a_time ... bench: 128,290 ns/iter (+/- 11,401) = 402 MB/s test post_one_at_a_time ... bench: 127,876 ns/iter (+/- 12,776) = 403 MB/s test result: ok. 0 passed; 0 failed; 0 ignored; 2 measured Running target/release/deps/hyper-d8f89bd3a96bdf05 running 361 tests test header::common::accept::bench::bench_format ... bench: 583 ns/iter (+/- 191) test header::common::accept::bench::bench_parse ... bench: 586 ns/iter (+/- 29) test header::common::accept_language::bench::bench_format ... bench: 794 ns/iter (+/- 385) test header::common::accept_language::bench::bench_parse ... bench: 1,154 ns/iter (+/- 53) test header::common::allow::bench::bench_format ... bench: 371 ns/iter (+/- 189) test header::common::allow::bench::bench_parse ... bench: 633 ns/iter (+/- 53) test header::common::authorization::basic::bench_format ... bench: 339 ns/iter (+/- 143) test header::common::authorization::basic::bench_parse ... bench: 193 ns/iter (+/- 52) test header::common::authorization::bearer::bench_format ... bench: 183 ns/iter (+/- 42) test header::common::authorization::bearer::bench_parse ... bench: 45 ns/iter (+/- 6) test header::common::authorization::raw::bench_format ... bench: 52 ns/iter (+/- 14) test header::common::authorization::raw::bench_parse ... bench: 38 ns/iter (+/- 12) test header::common::cache_control::normal::bench_format ... bench: 198 ns/iter (+/- 18) test header::common::cache_control::normal::bench_parse ... bench: 275 ns/iter (+/- 47) test header::common::connection::close::bench_format ... bench: 60 ns/iter (+/- 9) test header::common::connection::close::bench_parse ... bench: 66 ns/iter (+/- 18) test header::common::connection::header::bench_format ... bench: 54 ns/iter (+/- 8) test header::common::connection::header::bench_parse ... bench: 104 ns/iter (+/- 40) test header::common::connection::keep_alive::bench_format ... bench: 54 ns/iter (+/- 21) test header::common::connection::keep_alive::bench_parse ... bench: 80 ns/iter (+/- 30) test header::common::content_encoding::multiple::bench_format ... bench: 138 ns/iter (+/- 17) test header::common::content_encoding::multiple::bench_parse ... bench: 159 ns/iter (+/- 40) test header::common::content_encoding::single::bench_format ... bench: 56 ns/iter (+/- 25) test header::common::content_encoding::single::bench_parse ... bench: 59 ns/iter (+/- 12) test header::common::content_length::bench::bench_format ... bench: 60 ns/iter (+/- 21) test header::common::content_length::bench::bench_parse ... bench: 37 ns/iter (+/- 6) test header::common::content_type::bench::bench_format ... bench: 219 ns/iter (+/- 29) test header::common::content_type::bench::bench_parse ... bench: 269 ns/iter (+/- 35) test header::common::cookie::bench::bench_format ... bench: 150 ns/iter (+/- 24) test header::common::cookie::bench::bench_parse ... bench: 168 ns/iter (+/- 4) test header::common::date::asctime::bench_format ... bench: 897 ns/iter (+/- 137) test header::common::date::asctime::bench_parse ... bench: 288 ns/iter (+/- 197) test header::common::date::imf_fixdate::bench_format ... bench: 812 ns/iter (+/- 484) test header::common::date::imf_fixdate::bench_parse ... bench: 214 ns/iter (+/- 67) test header::common::date::rfc_850::bench_format ... bench: 815 ns/iter (+/- 144) test header::common::date::rfc_850::bench_parse ... bench: 234 ns/iter (+/- 149) test header::common::etag::bench::bench_format ... bench: 154 ns/iter (+/- 20) test header::common::etag::bench::bench_parse ... bench: 71 ns/iter (+/- 32) test header::common::expires::asctime::bench_format ... bench: 809 ns/iter (+/- 445) test header::common::expires::asctime::bench_parse ... bench: 284 ns/iter (+/- 141) test header::common::expires::imf_fixdate::bench_format ... bench: 793 ns/iter (+/- 120) test header::common::expires::imf_fixdate::bench_parse ... bench: 213 ns/iter (+/- 28) test header::common::expires::rfc_850::bench_format ... bench: 789 ns/iter (+/- 80) test header::common::expires::rfc_850::bench_parse ... bench: 230 ns/iter (+/- 99) test header::common::host::bench::bench_format ... bench: 140 ns/iter (+/- 36) test header::common::host::bench::bench_parse ... bench: 64 ns/iter (+/- 13) test header::common::if_match::multi::bench_format ... bench: 303 ns/iter (+/- 37) test header::common::if_match::multi::bench_parse ... bench: 347 ns/iter (+/- 44) test header::common::if_match::single::bench_format ... bench: 148 ns/iter (+/- 42) test header::common::if_match::single::bench_parse ... bench: 108 ns/iter (+/- 34) test header::common::if_match::star::bench_format ... bench: 52 ns/iter (+/- 5) test header::common::if_match::star::bench_parse ... bench: 2 ns/iter (+/- 0) test header::common::if_modified_since::asctime::bench_format ... bench: 784 ns/iter (+/- 54) test header::common::if_modified_since::asctime::bench_parse ... bench: 290 ns/iter (+/- 39) test header::common::if_modified_since::imf_fixdate::bench_format ... bench: 790 ns/iter (+/- 127) test header::common::if_modified_since::imf_fixdate::bench_parse ... bench: 211 ns/iter (+/- 16) test header::common::if_modified_since::rfc_850::bench_format ... bench: 789 ns/iter (+/- 291) test header::common::if_modified_since::rfc_850::bench_parse ... bench: 227 ns/iter (+/- 43) test header::common::if_none_match::bench::bench_format ... bench: 154 ns/iter (+/- 20) test header::common::if_none_match::bench::bench_parse ... bench: 129 ns/iter (+/- 50) test header::common::if_unmodified_since::asctime::bench_format ... bench: 801 ns/iter (+/- 238) test header::common::if_unmodified_since::asctime::bench_parse ... bench: 279 ns/iter (+/- 44) test header::common::if_unmodified_since::imf_fixdate::bench_format ... bench: 794 ns/iter (+/- 346) test header::common::if_unmodified_since::imf_fixdate::bench_parse ... bench: 213 ns/iter (+/- 40) test header::common::if_unmodified_since::rfc_850::bench_format ... bench: 791 ns/iter (+/- 287) test header::common::if_unmodified_since::rfc_850::bench_parse ... bench: 231 ns/iter (+/- 56) test header::common::last_modified::asctime::bench_format ... bench: 796 ns/iter (+/- 100) test header::common::last_modified::asctime::bench_parse ... bench: 280 ns/iter (+/- 35) test header::common::last_modified::imf_fixdate::bench_format ... bench: 800 ns/iter (+/- 273) test header::common::last_modified::imf_fixdate::bench_parse ... bench: 230 ns/iter (+/- 119) test header::common::last_modified::rfc_850::bench_format ... bench: 792 ns/iter (+/- 157) test header::common::last_modified::rfc_850::bench_parse ... bench: 229 ns/iter (+/- 26) test header::common::location::bench::bench_format ... bench: 52 ns/iter (+/- 11) test header::common::location::bench::bench_parse ... bench: 46 ns/iter (+/- 18) test header::common::origin::bench::bench_format ... bench: 166 ns/iter (+/- 36) test header::common::origin::bench::bench_parse ... bench: 128 ns/iter (+/- 15) test header::common::prefer::normal::bench_format ... bench: 201 ns/iter (+/- 50) test header::common::prefer::normal::bench_parse ... bench: 609 ns/iter (+/- 146) test header::common::preference_applied::normal::bench_format ... bench: 252 ns/iter (+/- 37) test header::common::preference_applied::normal::bench_parse ... bench: 600 ns/iter (+/- 42) test header::common::range::bytes_multi::bench_format ... bench: 351 ns/iter (+/- 10) test header::common::range::bytes_multi::bench_parse ... bench: 334 ns/iter (+/- 36) test header::common::range::custom_unit::bench_format ... bench: 167 ns/iter (+/- 23) test header::common::range::custom_unit::bench_parse ... bench: 90 ns/iter (+/- 29) test header::common::referer::bench::bench_format ... bench: 52 ns/iter (+/- 10) test header::common::referer::bench::bench_parse ... bench: 46 ns/iter (+/- 11) test header::common::server::bench::bench_format ... bench: 52 ns/iter (+/- 2) test header::common::server::bench::bench_parse ... bench: 45 ns/iter (+/- 1) test header::common::strict_transport_security::bench::bench_format ... bench: 159 ns/iter (+/- 25) test header::common::strict_transport_security::bench::bench_parse ... bench: 162 ns/iter (+/- 3) test header::common::transfer_encoding::ext::bench_format ... bench: 53 ns/iter (+/- 3) test header::common::transfer_encoding::ext::bench_parse ... bench: 79 ns/iter (+/- 3) test header::common::transfer_encoding::normal::bench_format ... bench: 111 ns/iter (+/- 25) test header::common::transfer_encoding::normal::bench_parse ... bench: 150 ns/iter (+/- 32) test header::common::upgrade::bench::bench_format ... bench: 242 ns/iter (+/- 59) test header::common::upgrade::bench::bench_parse ... bench: 429 ns/iter (+/- 66) test header::tests::bench_headers_fmt ... bench: 171 ns/iter (+/- 108) test header::tests::bench_headers_get ... bench: 12 ns/iter (+/- 5) test header::tests::bench_headers_get_miss ... bench: 3 ns/iter (+/- 1) test header::tests::bench_headers_has ... bench: 5 ns/iter (+/- 2) test header::tests::bench_headers_new ... bench: 91 ns/iter (+/- 13) test header::tests::bench_headers_set ... bench: 58 ns/iter (+/- 23) test header::tests::bench_headers_view_is ... bench: 1 ns/iter (+/- 0) test http::h1::parse::tests::bench_parse_incoming ... bench: 3,194 ns/iter (+/- 516) test result: ok. 0 passed; 0 failed; 257 ignored; 104 measured ``` Seems like global performances improved quite a bit! :D Updated.
2017-02-09T19:49:24Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,038
hyperium__hyper-1038
[ "1026" ]
5c890321ee2da727a814c18d4ee2df5eddd6720e
diff --git a/src/header/common/content_length.rs b/src/header/common/content_length.rs --- a/src/header/common/content_length.rs +++ b/src/header/common/content_length.rs @@ -40,6 +40,7 @@ impl Header for ContentLength { static NAME: &'static str = "Content-Length"; NAME } + fn parse_header(raw: &Raw) -> ::Result<ContentLength> { // If multiple Content-Length headers were sent, everything can still // be alright if they all contain the same value, and all parse diff --git a/src/header/common/content_length.rs b/src/header/common/content_length.rs --- a/src/header/common/content_length.rs +++ b/src/header/common/content_length.rs @@ -49,9 +50,9 @@ impl Header for ContentLength { .fold(None, |prev, x| { match (prev, x) { (None, x) => Some(x), - (e@Some(Err(_)), _ ) => e, + (e @ Some(Err(_)), _ ) => e, (Some(Ok(prev)), Ok(x)) if prev == x => Some(Ok(prev)), - _ => Some(Err(::Error::Header)) + _ => Some(Err(::Error::Header)), } }) .unwrap_or(Err(::Error::Header)) diff --git a/src/header/internals/vec_map.rs b/src/header/internals/vec_map.rs --- a/src/header/internals/vec_map.rs +++ b/src/header/internals/vec_map.rs @@ -4,9 +4,9 @@ pub struct VecMap<K, V> { } impl<K: PartialEq, V> VecMap<K, V> { - pub fn new() -> VecMap<K, V> { + pub fn with_capacity(cap: usize) -> VecMap<K, V> { VecMap { - vec: Vec::new() + vec: Vec::with_capacity(cap) } } diff --git a/src/header/internals/vec_map.rs b/src/header/internals/vec_map.rs --- a/src/header/internals/vec_map.rs +++ b/src/header/internals/vec_map.rs @@ -43,6 +43,7 @@ impl<K: PartialEq, V> VecMap<K, V> { } pub fn len(&self) -> usize { self.vec.len() } + pub fn iter(&self) -> ::std::slice::Iter<(K, V)> { self.vec.iter() } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -80,7 +80,6 @@ use std::borrow::{Cow, ToOwned}; use std::iter::{FromIterator, IntoIterator}; use std::{mem, fmt}; -use httparse; use unicase::UniCase; use self::internals::{Item, VecMap, Entry}; diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -88,6 +87,7 @@ use self::internals::{Item, VecMap, Entry}; pub use self::shared::*; pub use self::common::*; pub use self::raw::Raw; +use http::buf::MemSlice; mod common; mod internals; diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -346,31 +346,17 @@ literals! { impl Headers { /// Creates a new, empty headers map. + #[inline] pub fn new() -> Headers { - Headers { - data: VecMap::new() - } + Headers::with_capacity(0) } - #[doc(hidden)] - pub fn from_raw(raw: &[httparse::Header]) -> ::Result<Headers> { - let mut headers = Headers::new(); - for header in raw { - trace!("raw header: {:?}={:?}", header.name, &header.value[..]); - let name = HeaderName(UniCase(maybe_literal(header.name))); - let trim = header.value.iter().rev().take_while(|&&x| x == b' ').count(); - let value = &header.value[.. header.value.len() - trim]; - - match headers.data.entry(name) { - Entry::Vacant(entry) => { - entry.insert(Item::new_raw(self::raw::parsed(value))); - } - Entry::Occupied(entry) => { - entry.into_mut().mut_raw().push(value); - } - }; + /// Creates a new `Headers` struct with space reserved for `len` headers. + #[inline] + pub fn with_capacity(len: usize) -> Headers { + Headers { + data: VecMap::with_capacity(len) } - Ok(headers) } /// Set a header field to the corresponding value. diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -586,6 +572,24 @@ impl<'a> Extend<HeaderView<'a>> for Headers { } } +impl<'a> Extend<(&'a str, MemSlice)> for Headers { + fn extend<I: IntoIterator<Item=(&'a str, MemSlice)>>(&mut self, iter: I) { + for (name, value) in iter { + let name = HeaderName(UniCase(maybe_literal(name))); + //let trim = header.value.iter().rev().take_while(|&&x| x == b' ').count(); + + match self.data.entry(name) { + Entry::Vacant(entry) => { + entry.insert(Item::new_raw(self::raw::parsed(value))); + } + Entry::Occupied(entry) => { + self::raw::push(entry.into_mut().mut_raw(), value); + } + }; + } + } +} + impl<'a> FromIterator<HeaderView<'a>> for Headers { fn from_iter<I: IntoIterator<Item=HeaderView<'a>>>(iter: I) -> Headers { let mut headers = Headers::new(); diff --git a/src/header/parsing.rs b/src/header/parsing.rs --- a/src/header/parsing.rs +++ b/src/header/parsing.rs @@ -21,7 +21,7 @@ pub fn from_one_raw_str<T: str::FromStr>(raw: &Raw) -> ::Result<T> { /// Reads a raw string into a value. pub fn from_raw_str<T: str::FromStr>(raw: &[u8]) -> ::Result<T> { - let s = try!(str::from_utf8(raw)); + let s = try!(str::from_utf8(raw)).trim(); T::from_str(s).or(Err(::Error::Header)) } diff --git a/src/header/parsing.rs b/src/header/parsing.rs --- a/src/header/parsing.rs +++ b/src/header/parsing.rs @@ -36,7 +36,7 @@ pub fn from_comma_delimited<T: str::FromStr>(raw: &Raw) -> ::Result<Vec<T>> { "" => None, y => Some(y) }) - .filter_map(|x| x.parse().ok())) + .filter_map(|x| x.trim().parse().ok())) } Ok(result) } diff --git a/src/header/raw.rs b/src/header/raw.rs --- a/src/header/raw.rs +++ b/src/header/raw.rs @@ -1,5 +1,6 @@ use std::borrow::Cow; use std::fmt; +use http::buf::MemSlice; /// A raw header value. #[derive(Clone, PartialEq, Eq)] diff --git a/src/header/raw.rs b/src/header/raw.rs --- a/src/header/raw.rs +++ b/src/header/raw.rs @@ -19,8 +20,8 @@ impl Raw { #[inline] pub fn one(&self) -> Option<&[u8]> { match self.0 { - Lines::One(ref line) => Some(line), - Lines::Many(ref lines) if lines.len() == 1 => Some(&lines[0]), + Lines::One(ref line) => Some(line.as_ref()), + Lines::Many(ref lines) if lines.len() == 1 => Some(lines[0].as_ref()), _ => None } } diff --git a/src/header/raw.rs b/src/header/raw.rs --- a/src/header/raw.rs +++ b/src/header/raw.rs @@ -29,37 +30,42 @@ impl Raw { #[inline] pub fn iter(&self) -> RawLines { RawLines { - inner: match self.0 { - Lines::One(ref line) => unsafe { - ::std::slice::from_raw_parts(line, 1) - }.iter(), - Lines::Many(ref lines) => lines.iter() - } + inner: &self.0, + pos: 0, } } /// Append a line to this `Raw` header value. pub fn push(&mut self, val: &[u8]) { + self.push_line(maybe_literal(val.into())); + } + + fn push_line(&mut self, line: Line) { let lines = ::std::mem::replace(&mut self.0, Lines::Many(Vec::new())); match lines { - Lines::One(line) => { - self.0 = Lines::Many(vec![line, maybe_literal(val.into())]); + Lines::One(one) => { + self.0 = Lines::Many(vec![one, line]); } Lines::Many(mut lines) => { - lines.push(maybe_literal(val.into())); + lines.push(line); self.0 = Lines::Many(lines); } } } } -#[derive(Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] enum Lines { One(Line), - Many(Vec<Line>) + Many(Vec<Line>), } -type Line = Cow<'static, [u8]>; +#[derive(Debug, Clone, PartialEq, Eq)] +enum Line { + Static(&'static [u8]), + Owned(Vec<u8>), + Shared(MemSlice), +} fn eq<A: AsRef<[u8]>, B: AsRef<[u8]>>(a: &[A], b: &[B]) -> bool { if a.len() != b.len() { diff --git a/src/header/raw.rs b/src/header/raw.rs --- a/src/header/raw.rs +++ b/src/header/raw.rs @@ -123,24 +129,59 @@ impl From<String> for Raw { impl From<Vec<u8>> for Raw { #[inline] fn from(val: Vec<u8>) -> Raw { - Raw(Lines::One(Cow::Owned(val))) + Raw(Lines::One(Line::from(val))) } } impl From<&'static str> for Raw { fn from(val: &'static str) -> Raw { - Raw(Lines::One(Cow::Borrowed(val.as_bytes()))) + Raw(Lines::One(Line::Static(val.as_bytes()))) } } impl From<&'static [u8]> for Raw { fn from(val: &'static [u8]) -> Raw { - Raw(Lines::One(Cow::Borrowed(val))) + Raw(Lines::One(Line::Static(val))) + } +} + +impl From<MemSlice> for Raw { + #[inline] + fn from(val: MemSlice) -> Raw { + Raw(Lines::One(Line::Shared(val))) + } +} + +impl From<Vec<u8>> for Line { + #[inline] + fn from(val: Vec<u8>) -> Line { + Line::Owned(val) } } -pub fn parsed(val: &[u8]) -> Raw { - Raw(Lines::One(maybe_literal(val.into()))) +impl From<MemSlice> for Line { + #[inline] + fn from(val: MemSlice) -> Line { + Line::Shared(val) + } +} + +impl AsRef<[u8]> for Line { + fn as_ref(&self) -> &[u8] { + match *self { + Line::Static(ref s) => s, + Line::Owned(ref v) => v.as_ref(), + Line::Shared(ref m) => m.as_ref(), + } + } +} + +pub fn parsed(val: MemSlice) -> Raw { + Raw(Lines::One(From::from(val))) +} + +pub fn push(raw: &mut Raw, val: MemSlice) { + raw.push_line(Line::from(val)); } impl fmt::Debug for Raw { diff --git a/src/header/raw.rs b/src/header/raw.rs --- a/src/header/raw.rs +++ b/src/header/raw.rs @@ -154,6 +195,7 @@ impl fmt::Debug for Raw { impl ::std::ops::Index<usize> for Raw { type Output = [u8]; + fn index(&self, idx: usize) -> &[u8] { match self.0 { Lines::One(ref line) => if idx == 0 { diff --git a/src/header/raw.rs b/src/header/raw.rs --- a/src/header/raw.rs +++ b/src/header/raw.rs @@ -168,12 +210,12 @@ impl ::std::ops::Index<usize> for Raw { macro_rules! literals { ($($len:expr => $($value:expr),+;)+) => ( - fn maybe_literal<'a>(s: Cow<'a, [u8]>) -> Cow<'static, [u8]> { + fn maybe_literal<'a>(s: Cow<'a, [u8]>) -> Line { match s.len() { $($len => { $( if s.as_ref() == $value { - return Cow::Borrowed($value); + return Line::Static($value); } )+ })+ diff --git a/src/header/raw.rs b/src/header/raw.rs --- a/src/header/raw.rs +++ b/src/header/raw.rs @@ -216,7 +258,8 @@ impl<'a> IntoIterator for &'a Raw { #[derive(Debug)] pub struct RawLines<'a> { - inner: ::std::slice::Iter<'a, Cow<'static, [u8]>> + inner: &'a Lines, + pos: usize, } impl<'a> Iterator for RawLines<'a> { diff --git a/src/header/raw.rs b/src/header/raw.rs --- a/src/header/raw.rs +++ b/src/header/raw.rs @@ -224,6 +267,17 @@ impl<'a> Iterator for RawLines<'a> { #[inline] fn next(&mut self) -> Option<&'a [u8]> { - self.inner.next().map(AsRef::as_ref) + let current_pos = self.pos; + self.pos += 1; + match *self.inner { + Lines::One(ref line) => { + if current_pos == 0 { + Some(line.as_ref()) + } else { + None + } + } + Lines::Many(ref lines) => lines.get(current_pos).map(|l| l.as_ref()), + } } } diff --git a/src/http/buf.rs b/src/http/buf.rs --- a/src/http/buf.rs +++ b/src/http/buf.rs @@ -1,13 +1,14 @@ -use std::cell::UnsafeCell; +use std::borrow::Cow; +use std::cell::{Cell, UnsafeCell}; use std::fmt; use std::io::{self, Read}; -use std::ops::{Deref, Range, RangeFrom, RangeTo, RangeFull}; +use std::ops::{Index, Range, RangeFrom, RangeTo, RangeFull}; use std::ptr; use std::sync::Arc; pub struct MemBuf { buf: Arc<UnsafeCell<Vec<u8>>>, - start: usize, + start: Cell<usize>, end: usize, } diff --git a/src/http/buf.rs b/src/http/buf.rs --- a/src/http/buf.rs +++ b/src/http/buf.rs @@ -19,13 +20,13 @@ impl MemBuf { pub fn with_capacity(cap: usize) -> MemBuf { MemBuf { buf: Arc::new(UnsafeCell::new(vec![0; cap])), - start: 0, + start: Cell::new(0), end: 0, } } pub fn bytes(&self) -> &[u8] { - &self.buf()[self.start..self.end] + &self.buf()[self.start.get()..self.end] } pub fn is_empty(&self) -> bool { diff --git a/src/http/buf.rs b/src/http/buf.rs --- a/src/http/buf.rs +++ b/src/http/buf.rs @@ -33,7 +34,7 @@ impl MemBuf { } pub fn len(&self) -> usize { - self.end - self.start + self.end - self.start.get() } pub fn capacity(&self) -> usize { diff --git a/src/http/buf.rs b/src/http/buf.rs --- a/src/http/buf.rs +++ b/src/http/buf.rs @@ -41,20 +42,21 @@ impl MemBuf { } pub fn read_from<R: Read>(&mut self, io: &mut R) -> io::Result<usize> { - let start = self.end - self.start; + let start = self.end - self.start.get(); let n = try!(io.read(&mut self.buf_mut()[start..])); self.end += n; Ok(n) } - pub fn slice(&mut self, len: usize) -> MemSlice { - assert!(self.end - self.start >= len); - let start = self.start; - self.start += len; + pub fn slice(&self, len: usize) -> MemSlice { + assert!(self.end - self.start.get() >= len); + let start = self.start.get(); + let end = start + len; + self.start.set(end); MemSlice { buf: self.buf.clone(), start: start, - end: self.start, + end: end, } } diff --git a/src/http/buf.rs b/src/http/buf.rs --- a/src/http/buf.rs +++ b/src/http/buf.rs @@ -67,18 +69,18 @@ impl MemBuf { } let is_unique = Arc::get_mut(&mut self.buf).is_some(); trace!("MemBuf::reserve {} access", if is_unique { "unique" } else { "shared" }); - if is_unique && remaining + self.start >= needed { + if is_unique && remaining + self.start.get() >= needed { // we have unique access, we can mutate this vector trace!("MemBuf::reserve unique access, shifting"); unsafe { let mut buf = &mut *self.buf.get(); let len = self.len(); ptr::copy( - buf.as_ptr().offset(self.start as isize), + buf.as_ptr().offset(self.start.get() as isize), buf.as_mut_ptr(), len ); - self.start = 0; + self.start.set(0); self.end = len; } } else if is_unique { diff --git a/src/http/buf.rs b/src/http/buf.rs --- a/src/http/buf.rs +++ b/src/http/buf.rs @@ -109,7 +111,7 @@ impl MemBuf { match Arc::get_mut(&mut self.buf) { Some(_) => { trace!("MemBuf::reset was unique, re-using"); - self.start = 0; + self.start.set(0); self.end = 0; }, None => { diff --git a/src/http/buf.rs b/src/http/buf.rs --- a/src/http/buf.rs +++ b/src/http/buf.rs @@ -182,7 +190,7 @@ impl From<Vec<u8>> for MemBuf { vec.shrink_to_fit(); MemBuf { buf: Arc::new(UnsafeCell::new(vec)), - start: 0, + start: Cell::new(0), end: end, } } diff --git a/src/http/buf.rs b/src/http/buf.rs --- a/src/http/buf.rs +++ b/src/http/buf.rs @@ -203,23 +211,118 @@ impl MemSlice { } } + pub fn len(&self) -> usize { + self.get().len() + } + + pub fn is_empty(&self) -> bool { + self.get().is_empty() + } + pub fn slice<S: Slice>(&self, range: S) -> MemSlice { range.slice(self) } + + fn get(&self) -> &[u8] { + unsafe { &(*self.buf.get())[self.start..self.end] } + } } +impl AsRef<[u8]> for MemSlice { + fn as_ref(&self) -> &[u8] { + self.get() + } +} impl fmt::Debug for MemSlice { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Debug::fmt(&**self, f) + fmt::Debug::fmt(&self.get(), f) } } -impl Deref for MemSlice { - type Target = [u8]; - fn deref(&self) -> &[u8] { - unsafe { - &(*self.buf.get())[self.start..self.end] +impl Index<usize> for MemSlice { + type Output = u8; + fn index(&self, i: usize) -> &u8 { + &self.get()[i] + } +} + +impl<'a> From<&'a [u8]> for MemSlice { + fn from(v: &'a [u8]) -> MemSlice { + MemSlice { + buf: Arc::new(UnsafeCell::new(v.to_vec())), + start: 0, + end: v.len(), + } + } +} + +impl From<Vec<u8>> for MemSlice { + fn from(v: Vec<u8>) -> MemSlice { + let len = v.len(); + MemSlice { + buf: Arc::new(UnsafeCell::new(v)), + start: 0, + end: len, + } + } +} + +impl<'a> From<&'a str> for MemSlice { + fn from(v: &'a str) -> MemSlice { + let v = v.as_bytes(); + MemSlice { + buf: Arc::new(UnsafeCell::new(v.to_vec())), + start: 0, + end: v.len(), + } + } +} + +impl<'a> From<Cow<'a, [u8]>> for MemSlice { + fn from(v: Cow<'a, [u8]>) -> MemSlice { + let v = v.into_owned(); + let len = v.len(); + MemSlice { + buf: Arc::new(UnsafeCell::new(v)), + start: 0, + end: len, + } + } +} + +impl PartialEq for MemSlice { + fn eq(&self, other: &MemSlice) -> bool { + self.get() == other.get() + } +} + +impl PartialEq<[u8]> for MemSlice { + fn eq(&self, other: &[u8]) -> bool { + self.get() == other + } +} + +impl PartialEq<str> for MemSlice { + fn eq(&self, other: &str) -> bool { + self.get() == other.as_bytes() + } +} + +impl PartialEq<Vec<u8>> for MemSlice { + fn eq(&self, other: &Vec<u8>) -> bool { + self.get() == other.as_slice() + } +} + +impl Eq for MemSlice {} + +impl Clone for MemSlice { + fn clone(&self) -> MemSlice { + MemSlice { + buf: self.buf.clone(), + start: self.start, + end: self.end, } } } diff --git a/src/http/chunk.rs b/src/http/chunk.rs --- a/src/http/chunk.rs +++ b/src/http/chunk.rs @@ -69,7 +69,7 @@ impl AsRef<[u8]> for Chunk { match self.0 { Inner::Owned(ref vec) => vec, Inner::Referenced(ref vec) => vec, - Inner::Mem(ref slice) => slice, + Inner::Mem(ref slice) => slice.as_ref(), Inner::Static(slice) => slice, } } diff --git a/src/http/h1/decode.rs b/src/http/h1/decode.rs --- a/src/http/h1/decode.rs +++ b/src/http/h1/decode.rs @@ -88,7 +88,7 @@ impl Decoder { } else { let to_read = *remaining as usize; let buf = try!(body.read_mem(to_read)); - let num = buf.len() as u64; + let num = buf.as_ref().len() as u64; trace!("Length read: {}", num); if num > *remaining { *remaining = 0; diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -6,6 +6,7 @@ use httparse; use header::{self, Headers, ContentLength, TransferEncoding}; use http::{MessageHead, RawStatus, Http1Transaction, ParseResult, ServerTransaction, ClientTransaction, RequestLine}; use http::h1::{Encoder, Decoder}; +use http::buf::{MemBuf, MemSlice}; use method::Method; use status::StatusCode; use version::HttpVersion::{Http10, Http11}; diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -13,7 +14,7 @@ use version::HttpVersion::{Http10, Http11}; const MAX_HEADERS: usize = 100; const AVERAGE_HEADER_SIZE: usize = 30; // totally scientific -pub fn parse<T: Http1Transaction<Incoming=I>, I>(buf: &[u8]) -> ParseResult<I> { +pub fn parse<T: Http1Transaction<Incoming=I>, I>(buf: &MemBuf) -> ParseResult<I> { if buf.len() == 0 { return Ok(None); } diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -25,23 +26,29 @@ impl Http1Transaction for ServerTransaction { type Incoming = RequestLine; type Outgoing = StatusCode; - fn parse(buf: &[u8]) -> ParseResult<RequestLine> { + fn parse(buf: &MemBuf) -> ParseResult<RequestLine> { let mut headers = [httparse::EMPTY_HEADER; MAX_HEADERS]; trace!("Request.parse([Header; {}], [u8; {}])", headers.len(), buf.len()); let mut req = httparse::Request::new(&mut headers); - Ok(match try!(req.parse(buf)) { + Ok(match try!(req.parse(buf.bytes())) { httparse::Status::Complete(len) => { trace!("Request.parse Complete({})", len); + let mut headers = Headers::with_capacity(req.headers.len()); + let slice = buf.slice(len); + headers.extend(HeadersAsMemSliceIter { + headers: req.headers.iter(), + slice: slice, + }); Some((MessageHead { version: if req.version.unwrap() == 1 { Http11 } else { Http10 }, subject: RequestLine( try!(req.method.unwrap().parse()), try!(req.path.unwrap().parse()) ), - headers: try!(Headers::from_raw(req.headers)) + headers: headers, }, len)) - }, - httparse::Status::Partial => None + } + httparse::Status::Partial => None, }) } diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -112,11 +119,11 @@ impl Http1Transaction for ClientTransaction { type Incoming = RawStatus; type Outgoing = RequestLine; - fn parse(buf: &[u8]) -> ParseResult<RawStatus> { + fn parse(buf: &MemBuf) -> ParseResult<RawStatus> { let mut headers = [httparse::EMPTY_HEADER; MAX_HEADERS]; trace!("Response.parse([Header; {}], [u8; {}])", headers.len(), buf.len()); let mut res = httparse::Response::new(&mut headers); - Ok(match try!(res.parse(buf)) { + Ok(match try!(res.parse(buf.bytes())) { httparse::Status::Complete(len) => { trace!("Response.try_parse Complete({})", len); let code = res.code.unwrap(); diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -124,10 +131,16 @@ impl Http1Transaction for ClientTransaction { Some(reason) if reason == res.reason.unwrap() => Cow::Borrowed(reason), _ => Cow::Owned(res.reason.unwrap().to_owned()) }; + let mut headers = Headers::with_capacity(res.headers.len()); + let slice = buf.slice(len); + headers.extend(HeadersAsMemSliceIter { + headers: res.headers.iter(), + slice: slice, + }); Some((MessageHead { version: if res.version.unwrap() == 1 { Http11 } else { Http10 }, subject: RawStatus(code, reason), - headers: try!(Headers::from_raw(res.headers)) + headers: headers, }, len)) }, httparse::Status::Partial => None diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -216,6 +229,22 @@ impl Http1Transaction for ClientTransaction { } } +struct HeadersAsMemSliceIter<'a> { + headers: ::std::slice::Iter<'a, httparse::Header<'a>>, + slice: MemSlice, +} + +impl<'a> Iterator for HeadersAsMemSliceIter<'a> { + type Item = (&'a str, MemSlice); + fn next(&mut self) -> Option<Self::Item> { + self.headers.next().map(|header| { + let value_start = header.value.as_ptr() as usize - self.slice.as_ref().as_ptr() as usize; + let value_end = value_start + header.value.len(); + (header.name, self.slice.slice(value_start..value_end)) + }) + } +} + struct FastWrite<'a>(&'a mut Vec<u8>); impl<'a> fmt::Write for FastWrite<'a> { diff --git a/src/http/io.rs b/src/http/io.rs --- a/src/http/io.rs +++ b/src/http/io.rs @@ -70,11 +70,11 @@ impl<T: Io> Buffered<T> { _ => return Err(e.into()) } } - match try!(parse::<S, _>(self.read_buf.bytes())) { - Some((head, len)) => { - trace!("parsed {} bytes out of {}", len, self.read_buf.len()); - self.read_buf.slice(len); - Ok(Some(head)) + match try!(parse::<S, _>(&self.read_buf)) { + Some(head) => { + //trace!("parsed {} bytes out of {}", len, self.read_buf.len()); + //self.read_buf.slice(len); + Ok(Some(head.0)) }, None => { if self.read_buf.capacity() >= MAX_BUFFER_SIZE { diff --git a/src/http/io.rs b/src/http/io.rs --- a/src/http/io.rs +++ b/src/http/io.rs @@ -140,7 +140,7 @@ impl<T: Write> Write for Buffered<T> { } } -fn parse<T: Http1Transaction<Incoming=I>, I>(rdr: &[u8]) -> ParseResult<I> { +fn parse<T: Http1Transaction<Incoming=I>, I>(rdr: &MemBuf) -> ParseResult<I> { h1::parse::<T, I>(rdr) } diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -13,9 +13,11 @@ use version::HttpVersion::{Http10, Http11}; pub use self::conn::{Conn, KeepAlive, KA}; pub use self::body::{Body, TokioBody}; pub use self::chunk::Chunk; +use self::buf::MemBuf; mod body; -mod buf; +#[doc(hidden)] +pub mod buf; mod chunk; mod conn; mod io; diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -123,7 +125,7 @@ pub trait Http1Transaction { type Incoming; type Outgoing: Default; //type KeepAlive: KeepAlive; - fn parse(bytes: &[u8]) -> ParseResult<Self::Incoming>; + fn parse(bytes: &MemBuf) -> ParseResult<Self::Incoming>; fn decoder(head: &MessageHead<Self::Incoming>) -> ::Result<h1::Decoder>; fn encode(head: &mut MessageHead<Self::Outgoing>, dst: &mut Vec<u8>) -> h1::Encoder; fn should_set_length(head: &MessageHead<Self::Outgoing>) -> bool; diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -6,7 +6,8 @@ use tokio::io::Io; #[derive(Debug)] pub struct Buf { - vec: Vec<u8> + vec: Vec<u8>, + pos: usize, } impl Buf { diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -17,6 +18,7 @@ impl Buf { pub fn wrap(vec: Vec<u8>) -> Buf { Buf { vec: vec, + pos: 0, } } } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -48,7 +50,10 @@ impl Write for Buf { impl Read for Buf { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - (&*self.vec).read(buf) + (&self.vec[self.pos..]).read(buf).map(|n| { + self.pos += n; + n + }) } }
diff --git a/src/header/common/retry_after.rs b/src/header/common/retry_after.rs --- a/src/header/common/retry_after.rs +++ b/src/header/common/retry_after.rs @@ -141,9 +141,7 @@ impl Header for RetryAfter { #[cfg(test)] mod tests { - extern crate httparse; - - use header::{Header, Headers}; + use header::Header; use header::shared::HttpDate; use time::{Duration}; diff --git a/src/header/common/retry_after.rs b/src/header/common/retry_after.rs --- a/src/header/common/retry_after.rs +++ b/src/header/common/retry_after.rs @@ -179,17 +177,15 @@ mod tests { #[test] fn hyper_headers_from_raw_delay() { - let headers = Headers::from_raw(&[httparse::Header { name: "Retry-After", value: b"300" }]).unwrap(); - let retry_after = headers.get::<RetryAfter>().unwrap(); - assert_eq!(retry_after, &RetryAfter::Delay(Duration::seconds(300))); + let retry_after = RetryAfter::parse_header(&b"300".to_vec().into()).unwrap(); + assert_eq!(retry_after, RetryAfter::Delay(Duration::seconds(300))); } #[test] fn hyper_headers_from_raw_datetime() { - let headers = Headers::from_raw(&[httparse::Header { name: "Retry-After", value: b"Sun, 06 Nov 1994 08:49:37 GMT" }]).unwrap(); - let retry_after = headers.get::<RetryAfter>().unwrap(); + let retry_after = RetryAfter::parse_header(&b"Sun, 06 Nov 1994 08:49:37 GMT".to_vec().into()).unwrap(); let expected = "Sun, 06 Nov 1994 08:49:37 GMT".parse::<HttpDate>().unwrap(); - assert_eq!(retry_after, &RetryAfter::DateTime(expected.0)); + assert_eq!(retry_after, RetryAfter::DateTime(expected.0)); } } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -658,37 +662,25 @@ mod tests { use mime::SubLevel::Plain; use super::{Headers, Header, Raw, ContentLength, ContentType, Accept, Host, qitem}; - use httparse; #[cfg(feature = "nightly")] use test::Bencher; - // Slice.position_elem was unstable - fn index_of(slice: &[u8], byte: u8) -> Option<usize> { - for (index, &b) in slice.iter().enumerate() { - if b == byte { - return Some(index); - } - } - None - } - - macro_rules! raw { - ($($line:expr),*) => ({ - [$({ - let line = $line; - let pos = index_of(line, b':').expect("raw splits on ':', not found"); - httparse::Header { - name: ::std::str::from_utf8(&line[..pos]).unwrap(), - value: &line[pos + 2..] - } - }),*] + macro_rules! make_header { + ($name:expr, $value:expr) => ({ + let mut headers = Headers::new(); + headers.set_raw(String::from_utf8($name.to_vec()).unwrap(), $value.to_vec()); + headers + }); + ($text:expr) => ({ + let bytes = $text; + let colon = bytes.iter().position(|&x| x == b':').unwrap(); + make_header!(&bytes[..colon], &bytes[colon + 2..]) }) } - #[test] fn test_from_raw() { - let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); + let headers = make_header!(b"Content-Length", b"10"); assert_eq!(headers.get(), Some(&ContentLength(10))); } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -738,20 +730,20 @@ mod tests { #[test] fn test_different_structs_for_same_header() { - let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); + let headers = make_header!(b"Content-Length: 10"); assert_eq!(headers.get::<ContentLength>(), Some(&ContentLength(10))); assert_eq!(headers.get::<CrazyLength>(), Some(&CrazyLength(Some(false), 10))); } #[test] fn test_trailing_whitespace() { - let headers = Headers::from_raw(&raw!(b"Content-Length: 10 ")).unwrap(); + let headers = make_header!(b"Content-Length: 10 "); assert_eq!(headers.get::<ContentLength>(), Some(&ContentLength(10))); } #[test] fn test_multiple_reads() { - let headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); + let headers = make_header!(b"Content-Length: 10"); let ContentLength(one) = *headers.get::<ContentLength>().unwrap(); let ContentLength(two) = *headers.get::<ContentLength>().unwrap(); assert_eq!(one, two); diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -759,15 +751,16 @@ mod tests { #[test] fn test_different_reads() { - let headers = Headers::from_raw( - &raw!(b"Content-Length: 10", b"Content-Type: text/plain")).unwrap(); + let mut headers = Headers::new(); + headers.set_raw("Content-Length", "10"); + headers.set_raw("Content-Type", "text/plain"); let ContentLength(_) = *headers.get::<ContentLength>().unwrap(); let ContentType(_) = *headers.get::<ContentType>().unwrap(); } #[test] fn test_get_mutable() { - let mut headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); + let mut headers = make_header!(b"Content-Length: 10"); *headers.get_mut::<ContentLength>().unwrap() = ContentLength(20); assert_eq!(headers.get_raw("content-length").unwrap(), &[b"20".to_vec()][..]); assert_eq!(*headers.get::<ContentLength>().unwrap(), ContentLength(20)); diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -786,7 +779,7 @@ mod tests { #[test] fn test_headers_to_string_raw() { - let mut headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); + let mut headers = make_header!(b"Content-Length: 10"); headers.set_raw("x-foo", vec![b"foo".to_vec(), b"bar".to_vec()]); let s = headers.to_string(); assert_eq!(s, "Content-Length: 10\r\nx-foo: foo\r\nx-foo: bar\r\n"); diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -900,13 +893,6 @@ mod tests { }) } - #[cfg(feature = "nightly")] - #[bench] - fn bench_headers_from_raw(b: &mut Bencher) { - let raw = raw!(b"Content-Length: 10"); - b.iter(|| Headers::from_raw(&raw).unwrap()) - } - #[cfg(feature = "nightly")] #[bench] fn bench_headers_get(b: &mut Bencher) { diff --git a/src/header/raw.rs b/src/header/raw.rs --- a/src/header/raw.rs +++ b/src/header/raw.rs @@ -181,7 +223,7 @@ macro_rules! literals { _ => () } - Cow::Owned(s.into_owned()) + Line::from(s.into_owned()) } #[test] diff --git a/src/http/buf.rs b/src/http/buf.rs --- a/src/http/buf.rs +++ b/src/http/buf.rs @@ -119,13 +121,19 @@ impl MemBuf { } } + #[cfg(all(feature = "nightly", test))] + pub fn restart(&mut self) { + Arc::get_mut(&mut self.buf).unwrap(); + self.start.set(0); + } + fn buf_mut(&mut self) -> &mut [u8] { // The contract here is that we NEVER have a MemSlice that exists // with slice.end > self.start. // In other words, we should *ALWAYS* be the only instance that can // look at the bytes on the right side of self.start. unsafe { - &mut (*self.buf.get())[self.start..] + &mut (*self.buf.get())[self.start.get()..] } } diff --git a/src/http/buf.rs b/src/http/buf.rs --- a/src/http/buf.rs +++ b/src/http/buf.rs @@ -169,9 +177,9 @@ fn test_grow_zerofill() { impl fmt::Debug for MemBuf { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("MemBuf") - .field("start", &self.start) + .field("start", &self.start.get()) .field("end", &self.end) - .field("buf", &&self.buf()[self.start..self.end]) + .field("buf", &&self.buf()[self.start.get()..self.end]) .finish() } } diff --git a/src/http/buf.rs b/src/http/buf.rs --- a/src/http/buf.rs +++ b/src/http/buf.rs @@ -296,18 +399,18 @@ mod tests { #[test] fn test_mem_slice_slice() { - let mut buf = MemBuf::from(b"Hello World".to_vec()); + let buf = MemBuf::from(b"Hello World".to_vec()); let len = buf.len(); let full = buf.slice(len); - assert_eq!(&*full, b"Hello World"); - assert_eq!(&*full.slice(6..), b"World"); - assert_eq!(&*full.slice(..5), b"Hello"); - assert_eq!(&*full.slice(..), b"Hello World"); + assert_eq!(full.as_ref(), b"Hello World"); + assert_eq!(full.slice(6..).as_ref(), b"World"); + assert_eq!(full.slice(..5).as_ref(), b"Hello"); + assert_eq!(full.slice(..).as_ref(), b"Hello World"); for a in 0..len { for b in a..len { - assert_eq!(&*full.slice(a..b), &b"Hello World"[a..b], "{}..{}", a, b); + assert_eq!(full.slice(a..b).as_ref(), &b"Hello World"[a..b], "{}..{}", a, b); } } } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -595,6 +595,21 @@ mod tests { } } + #[test] + fn test_conn_parse_partial() { + let good_message = b"GET / HTTP/1.1\r\nHost: foo.bar\r\n\r\n".to_vec(); + let io = AsyncIo::new_buf(good_message, 10); + let mut conn = Conn::<_, ServerTransaction>::new(io, Default::default()); + assert!(conn.poll().unwrap().is_not_ready()); + conn.io.io_mut().block_in(50); + let async = conn.poll().unwrap(); + assert!(async.is_ready()); + match async { + Async::Ready(Some(Frame::Message { .. })) => (), + f => panic!("frame is not Message: {:?}", f), + } + } + #[test] fn test_conn_closed_read() { let io = AsyncIo::new_buf(vec![], 0); diff --git a/src/http/h1/decode.rs b/src/http/h1/decode.rs --- a/src/http/h1/decode.rs +++ b/src/http/h1/decode.rs @@ -399,7 +399,7 @@ mod tests { let mut mock_buf = &b"10\r\n1234567890abcdef\r\n0\r\n"[..]; let buf = Decoder::chunked().decode(&mut mock_buf).expect("decode"); assert_eq!(16, buf.len()); - let result = String::from_utf8(buf.to_vec()).expect("decode String"); + let result = String::from_utf8(buf.as_ref().to_vec()).expect("decode String"); assert_eq!("1234567890abcdef", &result); } diff --git a/src/http/h1/decode.rs b/src/http/h1/decode.rs --- a/src/http/h1/decode.rs +++ b/src/http/h1/decode.rs @@ -411,7 +411,7 @@ mod tests { // normal read let buf = decoder.decode(&mut mock_buf).expect("decode"); assert_eq!(16, buf.len()); - let result = String::from_utf8(buf.to_vec()).expect("decode String"); + let result = String::from_utf8(buf.as_ref().to_vec()).expect("decode String"); assert_eq!("1234567890abcdef", &result); // eof read diff --git a/src/http/h1/decode.rs b/src/http/h1/decode.rs --- a/src/http/h1/decode.rs +++ b/src/http/h1/decode.rs @@ -438,7 +438,7 @@ mod tests { if buf.is_empty() { break; // eof } - outs.write(&buf).expect("write buffer"); + outs.write(buf.as_ref()).expect("write buffer"); } Err(e) => match e.kind() { io::ErrorKind::WouldBlock => { diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -244,22 +273,23 @@ fn extend(dst: &mut Vec<u8>, data: &[u8]) { #[cfg(test)] mod tests { use http; + use http::buf::MemBuf; use super::{parse}; #[test] fn test_parse_request() { - let raw = b"GET /echo HTTP/1.1\r\nHost: hyper.rs\r\n\r\n"; - parse::<http::ServerTransaction, _>(raw).unwrap(); + let raw = MemBuf::from(b"GET /echo HTTP/1.1\r\nHost: hyper.rs\r\n\r\n".to_vec()); + parse::<http::ServerTransaction, _>(&raw).unwrap(); } #[test] fn test_parse_raw_status() { - let raw = b"HTTP/1.1 200 OK\r\n\r\n"; - let (res, _) = parse::<http::ClientTransaction, _>(raw).unwrap().unwrap(); + let raw = MemBuf::from(b"HTTP/1.1 200 OK\r\n\r\n".to_vec()); + let (res, _) = parse::<http::ClientTransaction, _>(&raw).unwrap().unwrap(); assert_eq!(res.subject.1, "OK"); - let raw = b"HTTP/1.1 200 Howdy\r\n\r\n"; - let (res, _) = parse::<http::ClientTransaction, _>(raw).unwrap().unwrap(); + let raw = MemBuf::from(b"HTTP/1.1 200 Howdy\r\n\r\n".to_vec()); + let (res, _) = parse::<http::ClientTransaction, _>(&raw).unwrap().unwrap(); assert_eq!(res.subject.1, "Howdy"); } diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -269,9 +299,26 @@ mod tests { #[cfg(feature = "nightly")] #[bench] fn bench_parse_incoming(b: &mut Bencher) { - let raw = b"GET /echo HTTP/1.1\r\nHost: hyper.rs\r\n\r\n"; + let mut raw = MemBuf::from(b"GET /super_long_uri/and_whatever?what_should_we_talk_about/\ + I_wonder/Hard_to_write_in_an_uri_after_all/you_have_to_make\ + _up_the_punctuation_yourself/how_fun_is_that?test=foo&test1=\ + foo1&test2=foo2&test3=foo3&test4=foo4 HTTP/1.1\r\nHost: \ + hyper.rs\r\nAccept: a lot of things\r\nAccept-Charset: \ + utf8\r\nAccept-Encoding: *\r\nAccess-Control-Allow-\ + Credentials: None\r\nAccess-Control-Allow-Origin: None\r\n\ + Access-Control-Allow-Methods: None\r\nAccess-Control-Allow-\ + Headers: None\r\nContent-Encoding: utf8\r\nContent-Security-\ + Policy: None\r\nContent-Type: text/html\r\nOrigin: hyper\ + \r\nSec-Websocket-Extensions: It looks super important!\r\n\ + Sec-Websocket-Origin: hyper\r\nSec-Websocket-Version: 4.3\r\ + \nStrict-Transport-Security: None\r\nUser-Agent: hyper\r\n\ + X-Content-Duration: None\r\nX-Content-Security-Policy: None\ + \r\nX-DNSPrefetch-Control: None\r\nX-Frame-Options: \ + Something important obviously\r\nX-Requested-With: Nothing\ + \r\n\r\n".to_vec()); b.iter(|| { - parse::<http::ServerTransaction, _>(raw).unwrap() + parse::<http::ServerTransaction, _>(&raw).unwrap(); + raw.restart(); }); }
Raw is now using Memslice Fixes #1024. I still need to find where I made a mistake to fix the tests. (And add some tests as well)
2017-01-27T19:09:33Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
1,014
hyperium__hyper-1014
[ "1000" ]
b64665635ff3a5dc7f47a2ed847d7a98e1f1eb67
diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -23,12 +23,12 @@ impl Service for Echo { fn call(&self, req: Request) -> Self::Future { ::futures::finished(match (req.method(), req.path()) { - (&Get, Some("/")) | (&Get, Some("/echo")) => { + (&Get, "/") | (&Get, "/echo") => { Response::new() .with_header(ContentLength(INDEX.len() as u64)) .with_body(INDEX) }, - (&Post, Some("/echo")) => { + (&Post, "/echo") => { let mut res = Response::new(); if let Some(len) = req.headers().get::<ContentLength>() { res.headers_mut().set(len.clone()); diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -23,7 +23,6 @@ use header::{Headers, Host}; use http::{self, TokioBody}; use method::Method; use self::pool::{Pool, Pooled}; -use uri::RequestUri; use {Url}; pub use self::connect::{HttpConnector, Connect}; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -120,15 +119,10 @@ impl<C: Connect> Service for Client<C> { fn call(&self, req: Request) -> Self::Future { let url = req.url().clone(); - let (mut head, body) = request::split(req); let mut headers = Headers::new(); headers.set(Host::new(url.host_str().unwrap().to_owned(), url.port())); headers.extend(head.headers.iter()); - head.subject.1 = RequestUri::AbsolutePath { - path: url.path().to_owned(), - query: url.query().map(ToOwned::to_owned), - }; head.headers = headers; let checkout = self.pool.checkout(&url[..::url::Position::BeforePath]); diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -5,7 +5,7 @@ use Url; use header::Headers; use http::{Body, RequestHead}; use method::Method; -use uri::RequestUri; +use uri::Uri; use version::HttpVersion; /// A client request to a remote server. diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -79,8 +79,9 @@ impl fmt::Debug for Request { } pub fn split(req: Request) -> (RequestHead, Option<Body>) { + let uri = Uri::new(&req.url[::url::Position::BeforePath..::url::Position::AfterQuery]).expect("url is uri"); let head = RequestHead { - subject: ::http::RequestLine(req.method, RequestUri::AbsoluteUri(req.url)), + subject: ::http::RequestLine(req.method, uri), headers: req.headers, version: req.version, }; diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -31,7 +31,7 @@ pub type Result<T> = ::std::result::Result<T, Error>; pub enum Error { /// An invalid `Method`, such as `GE,T`. Method, - /// An invalid `RequestUri`, such as `exam ple.domain`. + /// An invalid `Uri`, such as `exam ple.domain`. Uri(url::ParseError), /// An invalid `HttpVersion`, such as `HTP/1.1` Version, diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -6,7 +6,7 @@ use header::{Connection, ConnectionOption}; use header::Headers; use method::Method; use status::StatusCode; -use uri::RequestUri; +use uri::Uri; use version::HttpVersion; use version::HttpVersion::{Http10, Http11}; diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -51,7 +51,7 @@ pub struct MessageHead<S> { pub type RequestHead = MessageHead<RequestLine>; #[derive(Debug, Default, PartialEq)] -pub struct RequestLine(pub Method, pub RequestUri); +pub struct RequestLine(pub Method, pub Uri); impl fmt::Display for RequestLine { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -41,7 +41,6 @@ pub use http::{Body, Chunk}; pub use method::Method::{self, Get, Head, Post, Delete}; pub use status::StatusCode::{self, Ok, BadRequest, NotFound}; pub use server::Server; -pub use uri::RequestUri; pub use version::HttpVersion; macro_rules! unimplemented { diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -10,12 +10,12 @@ use version::HttpVersion; use method::Method; use header::Headers; use http::{RequestHead, MessageHead, RequestLine, Body}; -use uri::RequestUri; +use uri::Uri; /// A request bundles several parts of an incoming `NetworkStream`, given to a `Handler`. pub struct Request { method: Method, - uri: RequestUri, + uri: Uri, version: HttpVersion, headers: Headers, remote_addr: SocketAddr, diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -33,7 +33,7 @@ impl Request { /// The target request-uri for this request. #[inline] - pub fn uri(&self) -> &RequestUri { &self.uri } + pub fn uri(&self) -> &Uri { &self.uri } /// The version of HTTP for this request. #[inline] diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -45,22 +45,14 @@ impl Request { /// The target path of this Request. #[inline] - pub fn path(&self) -> Option<&str> { - match self.uri { - RequestUri::AbsolutePath { path: ref p, .. } => Some(p.as_str()), - RequestUri::AbsoluteUri(ref url) => Some(url.path()), - _ => None, - } + pub fn path(&self) -> &str { + self.uri.path() } /// The query string of this Request. #[inline] pub fn query(&self) -> Option<&str> { - match self.uri { - RequestUri::AbsolutePath { query: ref q, .. } => q.as_ref().map(|x| x.as_str()), - RequestUri::AbsoluteUri(ref url) => url.query(), - _ => None, - } + self.uri.query() } /// Take the `Body` of this `Request`. diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -73,7 +65,7 @@ impl Request { /// /// Modifying these pieces will have no effect on how hyper behaves. #[inline] - pub fn deconstruct(self) -> (Method, RequestUri, HttpVersion, Headers, Body) { + pub fn deconstruct(self) -> (Method, Uri, HttpVersion, Headers, Body) { (self.method, self.uri, self.version, self.headers, self.body) } } diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -1,7 +1,7 @@ -//! HTTP RequestUris +use std::borrow::Cow; use std::fmt::{Display, self}; use std::str::FromStr; -use url::Url; +use url::{self, Url}; use url::ParseError as UrlError; use Error;
diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -574,6 +574,7 @@ mod tests { use mock::AsyncIo; use super::{Conn, Writing}; + use ::uri::Uri; #[test] fn test_conn_init_read() { diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -585,10 +586,7 @@ mod tests { match conn.poll().unwrap() { Async::Ready(Some(Frame::Message { message, body: false })) => { assert_eq!(message, MessageHead { - subject: ::http::RequestLine(::Get, ::RequestUri::AbsolutePath { - path: "/".to_string(), - query: None, - }), + subject: ::http::RequestLine(::Get, Uri::new("/").unwrap()), .. MessageHead::default() }) }, diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -21,125 +21,301 @@ use Error; /// > / authority-form /// > / asterisk-form /// > ``` -#[derive(Debug, PartialEq, Eq, Hash, Clone)] -pub enum RequestUri { - /// The most common request target, an absolute path and optional query. - /// - /// For example, the line `GET /where?q=now HTTP/1.1` would parse the URI - /// as `AbsolutePath { path: "/where".to_string(), query: Some("q=now".to_string()) }`. - AbsolutePath { - /// The path part of the request uri. - path: String, - /// The query part of the request uri. - query: Option<String>, - }, - - /// An absolute URI. Used in conjunction with proxies. - /// - /// > When making a request to a proxy, other than a CONNECT or server-wide - /// > OPTIONS request (as detailed below), a client MUST send the target - /// > URI in absolute-form as the request-target. - /// - /// An example StartLine with an `AbsoluteUri` would be - /// `GET http://www.example.org/pub/WWW/TheProject.html HTTP/1.1`. - AbsoluteUri(Url), - - /// The authority form is only for use with `CONNECT` requests. - /// - /// An example StartLine: `CONNECT www.example.com:80 HTTP/1.1`. - Authority(String), - - /// The star is used to target the entire server, instead of a specific resource. - /// - /// This is only used for a server-wide `OPTIONS` request. - Star, -} - -impl Default for RequestUri { - fn default() -> RequestUri { - RequestUri::Star - } -} - -impl FromStr for RequestUri { - type Err = Error; +/// +/// # Uri explanations +/// +/// abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1 +/// |-| |-------------------------------||--------| |-------------------| |-----| +/// | | | | | +/// scheme authority path query fragment +#[derive(Clone)] +pub struct Uri { + source: Cow<'static, str>, + scheme_end: Option<usize>, + authority_end: Option<usize>, + query: Option<usize>, + fragment: Option<usize>, +} - fn from_str(s: &str) -> Result<RequestUri, Error> { +impl Uri { + /// Parse a string into a `Uri`. + pub fn new(s: &str) -> Result<Uri, Error> { let bytes = s.as_bytes(); if bytes.len() == 0 { Err(Error::Uri(UrlError::RelativeUrlWithoutBase)) } else if bytes == b"*" { - Ok(RequestUri::Star) + Ok(Uri { + source: "*".into(), + scheme_end: None, + authority_end: None, + query: None, + fragment: None, + }) + } else if bytes == b"/" { + Ok(Uri::default()) } else if bytes.starts_with(b"/") { let mut temp = "http://example.com".to_owned(); temp.push_str(s); let url = try!(Url::parse(&temp)); - Ok(RequestUri::AbsolutePath { - path: url.path().to_owned(), - query: url.query().map(|q| q.to_owned()), + let query_len = url.query().unwrap_or("").len(); + let fragment_len = url.fragment().unwrap_or("").len(); + Ok(Uri { + source: s.to_owned().into(), + scheme_end: None, + authority_end: None, + query: if query_len > 0 { Some(query_len) } else { None }, + fragment: if fragment_len > 0 { Some(fragment_len) } else { None }, }) - } else if bytes.contains(&b'/') { - Ok(RequestUri::AbsoluteUri(try!(Url::parse(s)))) + } else if s.contains("://") { + let url = try!(Url::parse(s)); + let query_len = url.query().unwrap_or("").len(); + let v: Vec<&str> = s.split("://").collect(); + let authority_end = v.last().unwrap() + .split(url.path()) + .next() + .unwrap_or(s) + .len() + if v.len() == 2 { v[0].len() + 3 } else { 0 }; + let fragment_len = url.fragment().unwrap_or("").len(); + match url.origin() { + url::Origin::Opaque(_) => Err(Error::Method), + url::Origin::Tuple(scheme, _, _) => { + Ok(Uri { + source: url.to_string().into(), + scheme_end: Some(scheme.len()), + authority_end: if authority_end > 0 { Some(authority_end) } else { None }, + query: if query_len > 0 { Some(query_len) } else { None }, + fragment: if fragment_len > 0 { Some(fragment_len) } else { None }, + }) + } + } } else { - let mut temp = "http://".to_owned(); - temp.push_str(s); - let url = try!(Url::parse(&temp)); - if url.query().is_some() { - return Err(Error::Uri(UrlError::RelativeUrlWithoutBase)); + Ok(Uri { + source: s.to_owned().into(), + scheme_end: None, + authority_end: Some(s.len()), + query: None, + fragment: None, + }) + } + } + + /// Get the path of this `Uri`. + pub fn path(&self) -> &str { + let index = self.authority_end.unwrap_or(self.scheme_end.unwrap_or(0)); + let query_len = self.query.unwrap_or(0); + let fragment_len = self.fragment.unwrap_or(0); + let end = self.source.len() - if query_len > 0 { query_len + 1 } else { 0 } - + if fragment_len > 0 { fragment_len + 1 } else { 0 }; + if index >= end { + "" + } else { + &self.source[index..end] + } + } + + /// Get the scheme of this `Uri`. + pub fn scheme(&self) -> Option<&str> { + if let Some(end) = self.scheme_end { + Some(&self.source[..end]) + } else { + None + } + } + + /// Get the authority of this `Uri`. + pub fn authority(&self) -> Option<&str> { + if let Some(end) = self.authority_end { + let index = self.scheme_end.map(|i| i + 3).unwrap_or(0); + Some(&self.source[index..end]) + } else { + None + } + } + + /// Get the host of this `Uri`. + pub fn host(&self) -> Option<&str> { + if let Some(auth) = self.authority() { + auth.split(":").next() + } else { + None + } + } + + /// Get the port of this `Uri. + pub fn port(&self) -> Option<u16> { + if let Some(auth) = self.authority() { + let v: Vec<&str> = auth.split(":").collect(); + if v.len() == 2 { + u16::from_str(v[1]).ok() + } else { + None } - //TODO: compare vs u.authority()? - Ok(RequestUri::Authority(s.to_owned())) + } else { + None + } + } + + /// Get the query string of this `Uri`, starting after the `?`. + pub fn query(&self) -> Option<&str> { + let fragment_len = self.fragment.unwrap_or(0); + let fragment_len = if fragment_len > 0 { fragment_len + 1 } else { 0 }; + if let Some(len) = self.query { + Some(&self.source[self.source.len() - len - fragment_len..self.source.len() - fragment_len]) + } else { + None + } + } + + #[cfg(test)] + fn fragment(&self) -> Option<&str> { + if let Some(len) = self.fragment { + Some(&self.source[self.source.len() - len..]) + } else { + None } } } -impl Display for RequestUri { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - RequestUri::AbsolutePath { ref path, ref query } => { - try!(f.write_str(path)); - match *query { - Some(ref q) => write!(f, "?{}", q), - None => Ok(()), - } - } - RequestUri::AbsoluteUri(ref url) => write!(f, "{}", url), - RequestUri::Authority(ref path) => f.write_str(path), - RequestUri::Star => f.write_str("*") +impl FromStr for Uri { + type Err = Error; + + fn from_str(s: &str) -> Result<Uri, Error> { + Uri::new(s) + } +} + +impl From<Url> for Uri { + fn from(url: Url) -> Uri { + Uri::new(url.as_str()).expect("Uri::From<Url> failed") + } +} + +impl PartialEq for Uri { + fn eq(&self, other: &Uri) -> bool { + self.source == other.source + } +} + +impl AsRef<str> for Uri { + fn as_ref(&self) -> &str { + &self.source + } +} + +impl Default for Uri { + fn default() -> Uri { + Uri { + source: "/".into(), + scheme_end: None, + authority_end: None, + query: None, + fragment: None, } } } -#[test] -fn test_uri_fromstr() { - fn parse(s: &str, result: RequestUri) { - assert_eq!(s.parse::<RequestUri>().unwrap(), result); +impl fmt::Debug for Uri { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self.source.as_ref(), f) } - fn parse_err(s: &str) { - assert!(s.parse::<RequestUri>().is_err()); +} + +impl Display for Uri { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(&self.source) + } +} + +macro_rules! test_parse { + ( + $test_name:ident, + $str:expr, + $($method:ident = $value:expr,)* + ) => ( + #[test] + fn $test_name() { + let uri = Uri::new($str).unwrap(); + $( + assert_eq!(uri.$method(), $value); + )+ + } + ); +} + +test_parse! { + test_uri_parse_origin_form, + "/some/path/here?and=then&hello#and-bye", + + scheme = None, + authority = None, + path = "/some/path/here", + query = Some("and=then&hello"), + fragment = Some("and-bye"), +} + +test_parse! { + test_uri_parse_absolute_form, + "http://127.0.0.1:61761/chunks", + + scheme = Some("http"), + authority = Some("127.0.0.1:61761"), + path = "/chunks", + query = None, + fragment = None, +} + +test_parse! { + test_uri_parse_absolute_form_without_path, + "https://127.0.0.1:61761", + + scheme = Some("https"), + authority = Some("127.0.0.1:61761"), + path = "/", + query = None, + fragment = None, +} + +test_parse! { + test_uri_parse_asterisk_form, + "*", + + scheme = None, + authority = None, + path = "*", + query = None, + fragment = None, +} + +test_parse! { + test_uri_parse_authority_form, + "localhost:3000", + + scheme = None, + authority = Some("localhost:3000"), + path = "", + query = None, + fragment = None, +} + +#[test] +fn test_uri_parse_error() { + fn err(s: &str) { + Uri::new(s).unwrap_err(); } - parse("*", RequestUri::Star); - parse("**", RequestUri::Authority("**".to_owned())); - parse("http://hyper.rs/", RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap())); - parse("hyper.rs", RequestUri::Authority("hyper.rs".to_owned())); - parse_err("hyper.rs?key=value"); - parse_err("hyper.rs/"); - parse("/", RequestUri::AbsolutePath { path: "/".to_owned(), query: None }); + err("http://"); + //TODO: these should error + //err("htt:p//host"); + //err("hyper.rs/"); + //err("hyper.rs?key=val"); } #[test] -fn test_uri_display() { - fn assert_display(expected_string: &str, request_uri: RequestUri) { - assert_eq!(expected_string, format!("{}", request_uri)); - } - - assert_display("*", RequestUri::Star); - assert_display("http://hyper.rs/", RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap())); - assert_display("hyper.rs", RequestUri::Authority("hyper.rs".to_owned())); - assert_display("/", RequestUri::AbsolutePath { path: "/".to_owned(), query: None }); - assert_display("/where?key=value", RequestUri::AbsolutePath { - path: "/where".to_owned(), - query: Some("key=value".to_owned()), - }); +fn test_uri_from_url() { + let uri = Uri::from(Url::parse("http://test.com/nazghul?test=3").unwrap()); + assert_eq!(uri.path(), "/nazghul"); + assert_eq!(uri.authority(), Some("test.com")); + assert_eq!(uri.scheme(), Some("http")); + assert_eq!(uri.query(), Some("test=3")); + assert_eq!(uri.as_ref(), "http://test.com/nazghul?test=3"); } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -47,6 +47,7 @@ macro_rules! test { fn $name() { #![allow(unused)] use hyper::header::*; + let _ = pretty_env_logger::init(); let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let mut core = Core::new().unwrap(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -74,7 +75,7 @@ macro_rules! test { while n < buf.len() && n < expected.len() { n += inc.read(&mut buf[n..]).unwrap(); } - assert_eq!(s(&buf[..n]), expected); + assert_eq!(s(&buf[..n]), expected, "expected is invalid"); inc.write_all($server_reply.as_ref()).unwrap(); tx.complete(()); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -85,9 +86,9 @@ macro_rules! test { let work = res.join(rx).map(|r| r.0); let res = core.run(work).unwrap(); - assert_eq!(res.status(), &StatusCode::$client_status); + assert_eq!(res.status(), &StatusCode::$client_status, "status is invalid"); $( - assert_eq!(res.headers().get(), Some(&$response_headers)); + assert_eq!(res.headers().get(), Some(&$response_headers), "headers are invalid"); )* } );
Redesign the Uri type There are a couple of things that a redesign could help with: - Making it an opaque struct instead of an enum means fiddling with internals is no longer a breaking change - It'd be best if we could create less copies when parsing out a URI - To future-proof for when hyper supports HTTP2 We want to optimize for the most common case, which is the [`origin-form`](https://tools.ietf.org/html/rfc7230#section-5.3.1), (currently `RequestUri::AbsolutePath`). We can start with keeping a single `String`, and then keeping indices into it to know where the `path` and `query` are. In HTTP2, the URI would gain additional fields, `scheme` and `authority` (what is in HTTP1 the `Host` header), and the `asterisk-form` request target is defined as `path = *`. We could eventually change the internal source representation to be a `MemSlice` or whatever it is at that point, to reduce a further copy. Some quick code describing what it could look like: ```rust pub struct Uri { source: String, scheme_end: Option<usize>, authority_end: Option<usize>, query: Option<usize>, } impl Uri { pub fn path(&self) -> &str { let index = self.scheme_end.unwrap_or(0) + self.authority_end.unwrap_or(0); let end = self.query.unwrap_or(self.source.len()); &self.source[index..end] } // .. and other accessors } let star = Uri::from_str("*").unwrap(); assert_eq!(Uri { source: String::from("*"), scheme_end: None, authority_end: None, query: None, }, star); assert_eq!(star.path(), "*"); let common = Uri::from_str("/p?foo=bar").unwrap(); assert_eq!(Uri { source: String::from("/p?foo=bar"), scheme_end: None, authority_end: None, query: Some(2), }, common); assert_eq!(common.path(), "/p"); assert_eq!(common.query(), "?foo=bar"); ``` cc @GuillaumeGomez
2017-01-18T00:48:46Z
0.11
eb15c660c106a2be08afd07e6cdfce162272d6cc
hyperium/hyper
994
hyperium__hyper-994
[ "993" ]
bef05bf2075cc0569213f8cad4cd1bf22cc4e736
diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -17,7 +17,7 @@ impl Service for Hello { type Response = Response; type Error = hyper::Error; type Future = ::futures::Finished<Response, hyper::Error>; - fn call(&mut self, _req: Request) -> Self::Future { + fn call(&self, _req: Request) -> Self::Future { ::futures::finished( Response::new() .with_header(ContentLength(PHRASE.len() as u64)) diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -21,7 +21,7 @@ impl Service for Echo { type Error = hyper::Error; type Future = ::futures::Finished<Response, hyper::Error>; - fn call(&mut self, req: Request) -> Self::Future { + fn call(&self, req: Request) -> Self::Future { ::futures::finished(match (req.method(), req.path()) { (&Get, Some("/")) | (&Get, Some("/echo")) => { Response::new() diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -29,7 +29,7 @@ pub trait Connect: Service<Request=Url, Error=io::Error> + 'static { /// A Future that will resolve to the connected Stream. type Future: Future<Item=Self::Output, Error=io::Error> + 'static; /// Connect to a remote address. - fn connect(&mut self, Url) -> <Self as Connect>::Future; + fn connect(&self, Url) -> <Self as Connect>::Future; } impl<T> Connect for T diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -40,7 +40,7 @@ where T: Service<Request=Url, Error=io::Error> + 'static, type Output = T::Response; type Future = T::Future; - fn connect(&mut self, url: Url) -> <Self as Connect>::Future { + fn connect(&self, url: Url) -> <Self as Connect>::Future { self.call(url) } } diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -78,7 +78,7 @@ impl Service for HttpConnector { type Error = io::Error; type Future = HttpConnecting; - fn call(&mut self, url: Url) -> Self::Future { + fn call(&self, url: Url) -> Self::Future { debug!("Http::connect({:?})", url); let host = match url.host_str() { Some(s) => s, diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -130,7 +130,7 @@ impl Service for HttpsConnector { type Error = io::Error; type Future = HttpsConnecting; - fn call(&mut self, url: Url) -> Self::Future { + fn call(&self, url: Url) -> Self::Future { debug!("Https::connect({:?})", url); let is_https = url.scheme() == "https"; let host = match url.host_str() { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -118,7 +118,7 @@ impl<C: Connect> Service for Client<C> { type Error = ::Error; type Future = FutureResponse; - fn call(&mut self, req: Request) -> Self::Future { + fn call(&self, req: Request) -> Self::Future { let url = match req.uri() { &::RequestUri::AbsoluteUri(ref u) => u.clone(), _ => unimplemented!("RequestUri::*") diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -164,7 +164,7 @@ impl<C: Connect> Service for Client<C> { // never had a pooled stream at all e.into() }); - let req = race.and_then(move |mut client| { + let req = race.and_then(move |client| { let msg = match body { Some(body) => { Message::WithBody(head, body.into()) diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -34,7 +34,7 @@ impl<T: Clone> Pool<T> { } } - pub fn checkout(&mut self, key: &str) -> Checkout<T> { + pub fn checkout(&self, key: &str) -> Checkout<T> { Checkout { key: Rc::new(key.to_owned()), pool: self.clone(), diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -267,7 +267,7 @@ impl<T> Service for HttpService<T> type Error = ::Error; type Future = Map<T::Future, fn(Response) -> Message<ResponseHead, http::TokioBody>>; - fn call(&mut self, message: Self::Request) -> Self::Future { + fn call(&self, message: Self::Request) -> Self::Future { let (head, body) = match message { Message::WithoutBody(head) => (head, http::Body::empty()), Message::WithBody(head, body) => (head, body.into()),
diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -344,7 +344,7 @@ mod tests { fn test_non_http_url() { let mut core = Core::new().unwrap(); let url = Url::parse("file:///home/sean/foo.txt").unwrap(); - let mut connector = HttpConnector::new(1, &core.handle()); + let connector = HttpConnector::new(1, &core.handle()); assert_eq!(core.run(connector.connect(url)).unwrap_err().kind(), io::ErrorKind::InvalidInput); } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -284,7 +284,7 @@ mod tests { #[test] fn test_pool_checkout_smoke() { - let mut pool = Pool::new(true, Some(Duration::from_secs(5))); + let pool = Pool::new(true, Some(Duration::from_secs(5))); let key = Rc::new("foo".to_string()); let mut pooled = pool.pooled(key.clone(), 41); pooled.idle(); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -298,7 +298,7 @@ mod tests { #[test] fn test_pool_checkout_returns_none_if_expired() { ::futures::lazy(|| { - let mut pool = Pool::new(true, Some(Duration::from_secs(1))); + let pool = Pool::new(true, Some(Duration::from_secs(1))); let key = Rc::new("foo".to_string()); let mut pooled = pool.pooled(key.clone(), 41); pooled.idle(); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -310,7 +310,7 @@ mod tests { #[test] fn test_pool_removes_expired() { - let mut pool = Pool::new(true, Some(Duration::from_secs(1))); + let pool = Pool::new(true, Some(Duration::from_secs(1))); let key = Rc::new("foo".to_string()); let mut pooled1 = pool.pooled(key.clone(), 41); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -334,7 +334,7 @@ mod tests { #[test] fn test_pool_checkout_task_unparked() { - let mut pool = Pool::new(true, Some(Duration::from_secs(10))); + let pool = Pool::new(true, Some(Duration::from_secs(10))); let key = Rc::new("foo".to_string()); let pooled1 = pool.pooled(key.clone(), 41); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -113,7 +113,7 @@ impl Service for TestService { type Response = Response; type Error = hyper::Error; type Future = Box<Future<Item=Response, Error=hyper::Error>>; - fn call(&mut self, req: Request) -> Self::Future { + fn call(&self, req: Request) -> Self::Future { let tx = self.tx.clone(); let replies = self.reply.clone(); req.body().for_each(move |chunk| {
tokio branch does not compile after tokio_service mutability change i am gonna try to write a PR to fix this! here's the error for posterity. ``` error[E0053]: method `call` has an incompatible type for trait --> src/client/connect.rs:81:5 | 81 | fn call(&mut self, url: Url) -> Self::Future { | ^ types differ in mutability | = note: expected type `fn(&client::connect::HttpConnector, url::Url) -> client::connect::HttpConnecting` = note: found type `fn(&mut client::connect::HttpConnector, url::Url) -> client::connect::HttpConnecting` error[E0053]: method `call` has an incompatible type for trait --> src/client/connect.rs:133:5 | 133 | fn call(&mut self, url: Url) -> Self::Future { | ^ types differ in mutability | = note: expected type `fn(&client::connect::HttpsConnector, url::Url) -> client::connect::HttpsConnecting` = note: found type `fn(&mut client::connect::HttpsConnector, url::Url) -> client::connect::HttpsConnecting` error[E0053]: method `call` has an incompatible type for trait --> src/client/mod.rs:121:5 | 121 | fn call(&mut self, req: Request) -> Self::Future { | ^ types differ in mutability | = note: expected type `fn(&client::Client<C>, client::request::Request) -> client::FutureResponse` = note: found type `fn(&mut client::Client<C>, client::request::Request) -> client::FutureResponse` error[E0053]: method `call` has an incompatible type for trait --> src/server/mod.rs:270:5 | 270 | fn call(&mut self, message: Self::Request) -> Self::Future { | _____^ starting here... 271 | | let (head, body) = match message { 272 | | Message::WithoutBody(head) => (head, http::Body::empty()), 273 | | Message::WithBody(head, body) => (head, body.into()), 274 | | }; 275 | | let req = request::new(self.remote_addr, head, body); 276 | | self.inner.call(req).map(map_response_to_message) 277 | | } | |_____^ ...ending here: types differ in mutability | = note: expected type `fn(&server::HttpService<T>, tokio_proto::streaming::Message<http::MessageHead<http::RequestLine>, tokio_proto::streaming::Body<http::chunk::Chunk, error::Error>>) -> futures::Map<<T as tokio_service::Service>::Future, fn(server::response::Response) -> tokio_proto::streaming::Message<http::MessageHead<status::StatusCode>, tokio_proto::streaming::Body<http::chunk::Chunk, error::Error>>>` = note: found type `fn(&mut server::HttpService<T>, tokio_proto::streaming::Message<http::MessageHead<http::RequestLine>, tokio_proto::streaming::Body<http::chunk::Chunk, error::Error>>) -> futures::Map<<T as tokio_service::Service>::Future, fn(server::response::Response) -> tokio_proto::streaming::Message<http::MessageHead<status::StatusCode>, tokio_proto::streaming::Body<http::chunk::Chunk, error::Error>>>` error: aborting due to 4 previous errors error: Could not compile `hyper`. Caused by: process didn't exit successfully: `rustc --crate-name hyper src/lib.rs --crate-type lib -g --cfg feature="default" -C metadata=d4a40b29437ca96f -C extra-filename=-d4a40b29437ca96f --out-dir /Users/ag_dubs/rust/hyper/target/debug/deps --emit=dep-info,link -L dependency=/Users/ag_dubs/rust/hyper/target/debug/deps --extern tokio_tls=/Users/ag_dubs/rust/hyper/target/debug/deps/libtokio_tls-f3e5968fda14b2c3.rlib --extern httparse=/Users/ag_dubs/rust/hyper/target/debug/deps/libhttparse-996fc9116d9dcf83.rlib --extern url=/Users/ag_dubs/rust/hyper/target/debug/deps/liburl-8aa0752fa6071745.rlib --extern vecio=/Users/ag_dubs/rust/hyper/target/debug/deps/libvecio-b90c1aba84926426.rlib --extern mime=/Users/ag_dubs/rust/hyper/target/debug/deps/libmime-c64500266507952e.rlib --extern tokio_core=/Users/ag_dubs/rust/hyper/target/debug/deps/libtokio_core-a0dfb4e4436a27df.rlib --extern unicase=/Users/ag_dubs/rust/hyper/target/debug/deps/libunicase-ceb43341bcf99e15.rlib --extern native_tls=/Users/ag_dubs/rust/hyper/target/debug/deps/libnative_tls-2758c2463fafa3da.rlib --extern time=/Users/ag_dubs/rust/hyper/target/debug/deps/libtime-02018c58facc89ee.rlib --extern tokio_service=/Users/ag_dubs/rust/hyper/target/debug/deps/libtokio_service-94bffe2000aad1d6.rlib --extern futures_cpupool=/Users/ag_dubs/rust/hyper/target/debug/deps/libfutures_cpupool-0057d211711ed4da.rlib --extern rustc_serialize=/Users/ag_dubs/rust/hyper/target/debug/deps/librustc_serialize-03b62901d97343ea.rlib --extern language_tags=/Users/ag_dubs/rust/hyper/target/debug/deps/liblanguage_tags-69c1ab0d09b59b1d.rlib --extern log=/Users/ag_dubs/rust/hyper/target/debug/deps/liblog-1ce22d3a92f37841.rlib --extern cookie=/Users/ag_dubs/rust/hyper/target/debug/deps/libcookie-a1e4ecdfdab40c7f.rlib --extern tokio_proto=/Users/ag_dubs/rust/hyper/target/debug/deps/libtokio_proto-872bc602f52ffd09.rlib --extern relay=/Users/ag_dubs/rust/hyper/target/debug/deps/librelay-3c2ac943d6a43c65.rlib --extern mio=/Users/ag_dubs/rust/hyper/target/debug/deps/libmio-9b8eb2d3b7c024fa.rlib --extern futures=/Users/ag_dubs/rust/hyper/target/debug/deps/libfutures-986bba8c0d767260.rlib` (exit code: 101) ```
2017-01-10T00:05:57Z
0.10
97abb81b3cc271a6dd258da86559bc25ab77c652
hyperium/hyper
971
hyperium__hyper-971
[ "969" ]
17a7e2b0514d3cf8f0f072b7ebc972223a338dad
diff --git /dev/null b/src/body.rs new file mode 100644 --- /dev/null +++ b/src/body.rs @@ -0,0 +1,81 @@ +//! The Hyper Body, which is a wrapper around the tokio_proto Body. +//! This is used as the Body for a Server Request, Server Response, +//! and also for a Client Request and Client Response. +//! It is based on a tokio_proto::streaming::Body for now, but will be +//! changed to tokio_proto::multiplex::Body int the future for SSL support. + +use std::convert::From; + +use tokio_proto; +use http::Chunk; +use futures::{Poll, Stream, Sink}; +use futures::sync::mpsc; +use futures::StartSend; + +pub type TokioBody = tokio_proto::streaming::Body<Chunk, ::Error>; + +#[derive(Debug)] +pub struct Body(TokioBody); + +impl Body { + /// Return an empty body stream + pub fn empty() -> Body { + Body(TokioBody::empty()) + } + + /// Return a body stream with an associated sender half + pub fn pair() -> (mpsc::Sender<Result<Chunk, ::Error>>, Body) { + let (tx, rx) = TokioBody::pair(); + let rx = Body(rx); + (tx, rx) + } +} + +impl Stream for Body { + type Item = Chunk; + type Error = ::Error; + + fn poll(&mut self) -> Poll<Option<Chunk>, ::Error> { + self.0.poll() + } +} + +impl From<Body> for tokio_proto::streaming::Body<Chunk, ::Error> { + fn from(b: Body) -> tokio_proto::streaming::Body<Chunk, ::Error> { + b.0 + } +} +impl From<tokio_proto::streaming::Body<Chunk, ::Error>> for Body { + fn from(tokio_body: tokio_proto::streaming::Body<Chunk, ::Error>) -> Body { + Body(tokio_body) + } +} + +impl From<mpsc::Receiver<Result<Chunk, ::Error>>> for Body { + fn from(src: mpsc::Receiver<Result<Chunk, ::Error>>) -> Body { + Body(src.into()) + } +} + +impl From<Vec<u8>> for Body { + fn from (vec: Vec<u8>) -> Body { + let (mut tx, rx) = Body::pair(); + tx.start_send(Ok(Chunk::from(vec))); + tx.poll_complete(); + rx + } +} + +impl From<&'static [u8]> for Body { + fn from (static_u8: &'static [u8]) -> Body { + let vec = static_u8.to_vec(); + Into::<Body>::into(vec) + } +} + +impl From<&'static str> for Body { + fn from (static_str: &'static str) -> Body { + let vec = static_str.as_bytes().to_vec(); + Into::<Body>::into(vec) + } +} \ No newline at end of file diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -17,11 +17,12 @@ use tokio::io::Io; use tokio::net::TcpStream; use tokio::reactor::Handle; use tokio_proto::BindClient; -use tokio_proto::streaming::{Body, Message}; +use tokio_proto::streaming::Message; use tokio_proto::streaming::pipeline::ClientProto; use tokio_proto::util::client_proxy::ClientProxy; pub use tokio_service::Service; +use body::{Body, TokioBody}; use header::{Headers, Host}; use http::{self, Conn, RequestHead, ClientTransaction}; use method::Method; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -38,7 +39,7 @@ mod dns; mod request; mod response; -type ClientBody = Body<http::Chunk, ::Error>; +type ClientBody = Body; /// A Client to make outgoing HTTP requests. pub struct Client<C> { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -133,7 +134,10 @@ impl Service for Client<DefaultConnector> { .map_err(|e| e.into()); let req = client.and_then(move |client| { let msg = match body { - Some(body) => Message::WithBody(head, body), + Some(body) => { + let body: TokioBody = body.into(); + Message::WithBody(head, body) + }, None => Message::WithoutBody(head), }; client.call(msg) diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -141,7 +145,7 @@ impl Service for Client<DefaultConnector> { FutureResponse(Box::new(req.map(|msg| { match msg { Message::WithoutBody(head) => response::new(head, None), - Message::WithBody(head, body) => response::new(head, Some(body)), + Message::WithBody(head, body) => response::new(head, Some(body.into())), } }))) } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -151,7 +155,7 @@ impl Service for Client<DefaultConnector> { struct HttpClient; struct Pool<C> { connector: C, - connections: RefCell<Vec<ClientProxy<Message<http::RequestHead, ClientBody>, Message<http::ResponseHead, ClientBody>, ::Error>>>, + connections: RefCell<Vec<ClientProxy<Message<http::RequestHead, TokioBody>, Message<http::ResponseHead, TokioBody>, ::Error>>>, } impl<T: Io + 'static> ClientProto<T> for HttpClient { diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -1,15 +1,15 @@ //! Client Requests -use futures::{Future, Sink}; use Url; +use body::Body; use header::Headers; use http::{RequestHead, Chunk}; use method::Method; use uri::RequestUri; use version::HttpVersion; -type Body = ::tokio_proto::streaming::Body<Chunk, ::Error>; +type RequestBody = Body; /// A client request to a remote server. #[derive(Debug)] diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -65,7 +65,7 @@ impl Request { /// Set the body of the request. #[inline] - pub fn set_body<T: IntoBody>(&mut self, body: T) { self.body = Some(body.into()); } + pub fn set_body<T: Into<Body>>(&mut self, body: T) { self.body = Some(body.into()); } } diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -1,13 +1,12 @@ //! Client Responses -use tokio_proto::streaming::Body; - +use body::Body; use header; use http::{self, Chunk, RawStatus}; use status; use version; -pub fn new(incoming: http::ResponseHead, body: Option<Body<Chunk, ::Error>>) -> Response { +pub fn new(incoming: http::ResponseHead, body: Option<Body>) -> Response { trace!("Response::new"); let status = status::StatusCode::from_u16(incoming.subject.0); debug!("version={:?}, status={:?}", incoming.version, status); diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -30,7 +29,7 @@ pub struct Response { headers: header::Headers, version: version::HttpVersion, status_raw: RawStatus, - body: Option<Body<Chunk, ::Error>>, + body: Option<Body>, } impl Response { diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -54,7 +53,7 @@ impl Response { #[inline] pub fn version(&self) -> &version::HttpVersion { &self.version } - pub fn body(mut self) -> Body<::http::Chunk, ::Error> { + pub fn body(mut self) -> Body { self.body.take().unwrap_or(Body::empty()) } } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -19,7 +19,7 @@ use tokio::io::Io; use tokio::net::TcpListener; use tokio::reactor::{Core, Handle}; use tokio_proto::BindServer; -use tokio_proto::streaming::{Message, Body}; +use tokio_proto::streaming::Message; use tokio_proto::streaming::pipeline::ServerProto; pub use tokio_service::{NewService, Service}; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -28,6 +28,7 @@ pub use self::response::Response; //use self::conn::Conn; +use body::{Body, TokioBody}; use http; pub use net::{Accept, HttpListener}; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -41,6 +42,8 @@ use net::{SslServer, Transport}; mod request; mod response; +type ServerBody = Body; + /// A Server that can accept incoming network requests. #[derive(Debug)] pub struct Server<A> { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -245,10 +248,10 @@ struct HttpService<T> { inner: T, } -fn map_response_to_message(res: Response) -> Message<ResponseHead, Body<http::Chunk, ::Error>> { +fn map_response_to_message(res: Response) -> Message<ResponseHead, TokioBody> { let (head, body) = response::split(res); if let Some(body) = body { - Message::WithBody(head, body) + Message::WithBody(head, body.into()) } else { Message::WithoutBody(head) } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -259,15 +262,15 @@ type ResponseHead = http::MessageHead<::StatusCode>; impl<T> Service for HttpService<T> where T: Service<Request=Request, Response=Response, Error=::Error>, { - type Request = Message<http::RequestHead, Body<http::Chunk, ::Error>>; - type Response = Message<ResponseHead, Body<http::Chunk, ::Error>>; + type Request = Message<http::RequestHead, TokioBody>; + type Response = Message<ResponseHead, TokioBody>; type Error = ::Error; - type Future = Map<T::Future, fn(Response) -> Message<ResponseHead, Body<http::Chunk, ::Error>>>; + type Future = Map<T::Future, fn(Response) -> Message<ResponseHead, TokioBody>>; fn call(&self, message: Self::Request) -> Self::Future { let req = match message { Message::WithoutBody(head) => Request::new(head, None), - Message::WithBody(head, body) => Request::new(head, Some(body)), + Message::WithBody(head, body) => Request::new(head, Some(body.into())), }; self.inner.call(req).map(map_response_to_message) } diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -5,14 +5,13 @@ use std::fmt; +use body::Body; use version::HttpVersion; use method::Method; use header::Headers; use http::{RequestHead, MessageHead, RequestLine, Chunk}; use uri::RequestUri; -type Body = ::tokio_proto::streaming::Body<Chunk, ::Error>; - /// A request bundles several parts of an incoming `NetworkStream`, given to a `Handler`. pub struct Request { method: Method, diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -3,15 +3,12 @@ //! These are responses sent by a `hyper::Server` to clients, after //! receiving a request. -use futures::{Future, Sink}; - +use body::Body; use header; use http; use status::StatusCode; use version; -type Body = ::tokio_proto::streaming::Body<http::Chunk, ::Error>; - /// The outgoing half for a Tcp connection, created by a `Server` and given to a `Handler`. /// /// The default `StatusCode` for a `Response` is `200 OK`. diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -54,7 +51,7 @@ impl Response { /// Set the body. #[inline] - pub fn set_body<T: IntoBody>(&mut self, body: T) { + pub fn set_body<T: Into<Body>>(&mut self, body: T) { self.body = Some(body.into()); } diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -89,7 +86,7 @@ impl Response { /// /// Useful for the "builder-style" pattern. #[inline] - pub fn with_body<T: IntoBody>(mut self, body: T) -> Self { + pub fn with_body<T: Into<Body>>(mut self, body: T) -> Self { self.set_body(body); self } diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -98,29 +95,3 @@ impl Response { pub fn split(res: Response) -> (http::MessageHead<StatusCode>, Option<Body>) { (res.head, res.body) } - -pub trait IntoBody { - fn into(self) -> Body; -} - -impl IntoBody for Body { - fn into(self) -> Self { - self - } -} - -impl IntoBody for Vec<u8> { - fn into(self) -> Body { - let (mut tx, rx) = Body::pair(); - tx.start_send(Ok(http::Chunk::from(self))); - tx.poll_complete(); - rx - } -} - -impl IntoBody for &'static [u8] { - fn into(self) -> Body { - let vec = self.to_vec(); - IntoBody::into(vec) - } -}
diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -73,38 +73,6 @@ pub fn split(req: Request) -> (RequestHead, Option<Body>) { (req.head, req.body) } -pub trait IntoBody { - fn into(self) -> Body; -} - -impl IntoBody for Body { - fn into(self) -> Self { - self - } -} - -impl IntoBody for Vec<u8> { - fn into(self) -> Body { - let (mut tx, rx) = Body::pair(); - ::futures::lazy(move || tx.start_send(Ok(Chunk::from(self)))).wait().unwrap(); - rx - } -} - -impl IntoBody for &'static [u8] { - fn into(self) -> Body { - let vec = self.to_vec(); - IntoBody::into(vec) - } -} - -impl IntoBody for &'static str { - fn into(self) -> Body { - let vec = self.as_bytes().to_vec(); - IntoBody::into(vec) - } -} - #[cfg(test)] mod tests { /* diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -42,6 +42,7 @@ extern crate test; pub use url::Url; +pub use body::Body; pub use client::Client; pub use error::{Result, Error}; pub use header::Headers; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -67,6 +68,7 @@ macro_rules! unimplemented { #[cfg(test)] mod mock; +pub mod body; pub mod client; pub mod error; mod method;
[Tokio Branch] hyper::server::response::{ Body and IntoBody } are private, propose to expose publically Currently, you can call `response.set_body()` with anything that implements `hyper::server::response::IntoBody`, and right now that is just `Body` itself, `Vec<u8>` and `&'static [u8]`. In my application, I have my own ResponseBody struct, that I would like implement `IntoBody`, (to pass to `response.set_body()` but I cannot because `IntoBody` is private. Additionally, I would like to be able to use the `hyper::server::response::Body` type, so that I can do the `Body::pair()` and `tx.start_send()` within my application, then pass that result to `response.set_body()`. Is that potentially breaking any Hyper conventions? Are they private for a reason, and is there a better way of doing what I want to do? (Other than simply converting my ResponseBody to `Vec<u8>` and passing that in.)
In general things are private because I'm being much more conservative with what is made public, so internal optimizations can be made without breaking people. In this particular case, I didn't really like the idea of a `IntoBody` trait, but instead wanted `Into<Body>`. The `IntoBody` trait currently exists because I cannot `impl Into<Body> for Vec<u8>`, since neither `Body` nor `Vec<u8>` are defined in hyper. I think what is probably the best to do is to create `hyper::Body`, which may just wrap around `tokio_proto::streaming::pipeline::Body`, and so I can also kill the trait. A reason for hyper to have its own `Body` is because once hyper supports HTTP2, it would need to use `tokio_proto::streaming::multiplex::Body`, and I'd rather take care of those details internally. I hadn't done all this yet because, well, I've forgotten, and I also wasn't certain if it was the right thing to do, but it currently feels like it. Oh, yes, creating a `hyper::Body` that is just a wrapper around the `tokio_proto` `Body` is a good idea, so that you can implement `Into<Body>` on that. Then if that `hyper::Body` was exposed publicly, I could do `impl Into<hyper::Body> for MyResponseBody` and be able to pass `MyResponseBody` directly into `set_body()`. That way I don't need to add a dependency on `tokio_proto` into my application, and can simply use `hyper::Body`. Another point to make. Currently `hyper::server::response::Body` and `hyper::client::response::Body` are both separately defined to `tokio_proto::streaming::pipeline::Body`. Would a `hyper::Body` replace both of those? Will `server::response::Body` always be the same as `server::client::Body`, regardless of what `tokio_proto` `Body` it is using? They should probably be the same type, and they should be made to work regardless of whether 1 side is HTTP1 and the other is HTTP2, and the type is really just meant to describe something that implements `Future<Item=hyper::Chunk, Error=hyper::Error>`.
2016-12-14T02:03:34Z
0.10
97abb81b3cc271a6dd258da86559bc25ab77c652
hyperium/hyper
920
hyperium__hyper-920
[ "882" ]
588ef9d25242f6154294c0c9cc5966d886c0a0f3
diff --git a/src/header/common/referrer_policy.rs b/src/header/common/referrer_policy.rs --- a/src/header/common/referrer_policy.rs +++ b/src/header/common/referrer_policy.rs @@ -54,19 +54,23 @@ impl Header for ReferrerPolicy { fn parse_header(raw: &Raw) -> ::Result<ReferrerPolicy> { use self::ReferrerPolicy::*; - parsing::from_one_raw_str(raw).and_then(|s: String| { - let slice = &s.to_ascii_lowercase()[..]; - // See https://www.w3.org/TR/referrer-policy/#determine-policy-for-token + // See https://www.w3.org/TR/referrer-policy/#determine-policy-for-token + let headers: Vec<String> = try!(parsing::from_comma_delimited(raw)); + + for h in headers.iter().rev() { + let slice = &h.to_ascii_lowercase()[..]; match slice { - "no-referrer" | "never" => Ok(NoReferrer), - "no-referrer-when-downgrade" | "default" => Ok(NoReferrerWhenDowngrade), - "same-origin" => Ok(SameOrigin), - "origin" => Ok(Origin), - "origin-when-cross-origin" => Ok(OriginWhenCrossOrigin), - "unsafe-url" | "always" => Ok(UnsafeUrl), - _ => Err(::Error::Header), + "no-referrer" | "never" => return Ok(NoReferrer), + "no-referrer-when-downgrade" | "default" => return Ok(NoReferrerWhenDowngrade), + "same-origin" => return Ok(SameOrigin), + "origin" => return Ok(Origin), + "origin-when-cross-origin" => return Ok(OriginWhenCrossOrigin), + "unsafe-url" | "always" => return Ok(UnsafeUrl), + _ => continue, } - }) + } + + Err(::Error::Header) } fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
diff --git a/src/header/common/referrer_policy.rs b/src/header/common/referrer_policy.rs --- a/src/header/common/referrer_policy.rs +++ b/src/header/common/referrer_policy.rs @@ -90,3 +94,10 @@ fn test_parse_header() { let e: ::Result<ReferrerPolicy> = Header::parse_header(&"foobar".into()); assert!(e.is_err()); } + +#[test] +fn test_rightmost_header() { + let a: ReferrerPolicy = Header::parse_header(&"same-origin, origin, foobar".into()).unwrap(); + let b = ReferrerPolicy::Origin; + assert_eq!(a, b); +}
Referrer-Policy header should support multiple values In order to support fallback policies when a subset of the full policies is supported (such as when a new policy is introduced in the specification), hyper's Referrer-Policy header should store the most recent value that is successfully parsed from the list of potential multiple values, per https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header .
2016-10-06T20:21:50Z
0.10
97abb81b3cc271a6dd258da86559bc25ab77c652
hyperium/hyper
910
hyperium__hyper-910
[ "883" ]
8b3c1206846cb96be780923952eafe0dde7850bf
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -58,6 +58,7 @@ pub use self::transfer_encoding::TransferEncoding; pub use self::upgrade::{Upgrade, Protocol, ProtocolName}; pub use self::user_agent::UserAgent; pub use self::vary::Vary; +pub use self::warning::Warning; #[doc(hidden)] #[macro_export] diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -420,3 +421,4 @@ mod transfer_encoding; mod upgrade; mod user_agent; mod vary; +mod warning; \ No newline at end of file
diff --git /dev/null b/src/header/common/warning.rs new file mode 100644 --- /dev/null +++ b/src/header/common/warning.rs @@ -0,0 +1,174 @@ +use std::fmt; +use std::str::{FromStr}; +use header::{Header, HttpDate, Raw}; +use header::parsing::from_one_raw_str; + +/// `Warning` header, defined in [RFC7234](https://tools.ietf.org/html/rfc7234#section-5.5) +/// +/// The `Warning` header field can be be used to carry additional information +/// about the status or transformation of a message that might not be reflected +/// in the status code. This header is sometimes used as backwards +/// compatible way to notify of a deprecated API. +/// +/// # ABNF +/// ```plain +/// Warning = 1#warning-value +/// warning-value = warn-code SP warn-agent SP warn-text +/// [ SP warn-date ] +/// warn-code = 3DIGIT +/// warn-agent = ( uri-host [ ":" port ] ) / pseudonym +/// ; the name or pseudonym of the server adding +/// ; the Warning header field, for use in debugging +/// ; a single "-" is recommended when agent unknown +/// warn-text = quoted-string +/// warn-date = DQUOTE HTTP-date DQUOTE +/// ``` +/// +/// # Example values +/// * `Warning: 112 - "network down" "Sat, 25 Aug 2012 23:34:45 GMT"` +/// * `Warning: 299 - "Deprecated API " "Tue, 15 Nov 1994 08:12:31 GMT"` +/// * `Warning: 299 api.hyper.rs:8080 "Deprecated API : use newapi.hyper.rs instead."` +/// * `Warning: 299 api.hyper.rs:8080 "Deprecated API : use newapi.hyper.rs instead." "Tue, 15 Nov 1994 08:12:31 GMT"` +/// +/// # Examples +/// ``` +/// use hyper::header::{Headers, Warning}; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// Warning{ +/// code: 299, +/// agent: "api.hyper.rs".to_owned(), +/// text: "Deprecated".to_owned(), +/// date: None +/// } +/// ); +/// ``` +/// ``` +/// use hyper::header::{Headers, HttpDate, Warning}; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// Warning{ +/// code: 299, +/// agent: "api.hyper.rs".to_owned(), +/// text: "Deprecated".to_owned(), +/// date: "Tue, 15 Nov 1994 08:12:31 GMT".parse::<HttpDate>().ok() +/// } +/// ); +/// ``` +/// ``` +/// # extern crate hyper; +/// # extern crate time; +/// # fn main() { +/// use hyper::header::{Headers, HttpDate, Warning}; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// Warning{ +/// code: 199, +/// agent: "api.hyper.rs".to_owned(), +/// text: "Deprecated".to_owned(), +/// date: Some(HttpDate(time::now())) +/// } +/// ); +/// # } +/// ``` +#[derive(PartialEq, Clone, Debug)] +pub struct Warning { + /// The 3 digit warn code. + pub code: u16, + /// The name or pseudonym of the server adding this header. + pub agent: String, + /// The warning message describing the error. + pub text: String, + /// An optional warning date. + pub date: Option<HttpDate> +} + +impl Header for Warning { + fn header_name() -> &'static str { + static NAME: &'static str = "Warning"; + NAME + } + + fn parse_header(raw: &Raw) -> ::Result<Warning> { + from_one_raw_str(raw) + } + + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self.date { + Some(date) => write!(f, "{:03} {} \"{}\" \"{}\"", self.code, self.agent, self.text, date), + None => write!(f, "{:03} {} \"{}\"", self.code, self.agent, self.text) + } + } +} + +impl FromStr for Warning { + type Err = ::Error; + + fn from_str(s: &str) -> ::Result<Warning> { + let mut warning_split = s.split_whitespace(); + let code = match warning_split.next() { + Some(c) => match c.parse::<u16>() { + Ok(c) => c, + Err(..) => return Err(::Error::Header) + }, + None => return Err(::Error::Header) + }; + let agent = match warning_split.next() { + Some(a) => a.to_string(), + None => return Err(::Error::Header) + }; + + let mut warning_split = s.split('"').skip(1); + let text = match warning_split.next() { + Some(t) => t.to_string(), + None => return Err(::Error::Header) + }; + let date = match warning_split.skip(1).next() { + Some(d) => d.parse::<HttpDate>().ok(), + None => None // Optional + }; + + Ok(Warning { + code: code, + agent: agent, + text: text, + date: date + }) + } +} + +#[cfg(test)] +mod tests { + use super::Warning; + use header::{Header, HttpDate}; + + #[test] + fn test_parsing() { + let warning = Header::parse_header(&vec![b"112 - \"network down\" \"Sat, 25 Aug 2012 23:34:45 GMT\"".to_vec()].into()); + assert_eq!(warning.ok(), Some(Warning { + code: 112, + agent: "-".to_owned(), + text: "network down".to_owned(), + date: "Sat, 25 Aug 2012 23:34:45 GMT".parse::<HttpDate>().ok() + })); + + let warning = Header::parse_header(&vec![b"299 api.hyper.rs:8080 \"Deprecated API : use newapi.hyper.rs instead.\"".to_vec()].into()); + assert_eq!(warning.ok(), Some(Warning { + code: 299, + agent: "api.hyper.rs:8080".to_owned(), + text: "Deprecated API : use newapi.hyper.rs instead.".to_owned(), + date: None + })); + + let warning = Header::parse_header(&vec![b"299 api.hyper.rs:8080 \"Deprecated API : use newapi.hyper.rs instead.\" \"Tue, 15 Nov 1994 08:12:31 GMT\"".to_vec()].into()); + assert_eq!(warning.ok(), Some(Warning { + code: 299, + agent: "api.hyper.rs:8080".to_owned(), + text: "Deprecated API : use newapi.hyper.rs instead.".to_owned(), + date: "Tue, 15 Nov 1994 08:12:31 GMT".parse::<HttpDate>().ok() + })); + } +}
add Warning header I would like to use the `Warning` header to warn users of deprecated API routes as proposed in this SO answer: http://stackoverflow.com/a/29623798. Spec: https://tools.ietf.org/html/rfc7234#section-5.5
2016-09-05T17:55:06Z
0.10
97abb81b3cc271a6dd258da86559bc25ab77c652
hyperium/hyper
899
hyperium__hyper-899
[ "896" ]
a228486a85d88eb10b03509228bd11937ad57261
diff --git a/doc/guide/server.md b/doc/guide/server.md --- a/doc/guide/server.md +++ b/doc/guide/server.md @@ -165,7 +165,7 @@ impl Handler<Http> for Text { fn on_request(&mut self, req: Request<Http>) -> Next { use hyper::RequestUri; let path = match *req.uri() { - RequestUri::AbsolutePath(ref p) => p, + RequestUri::AbsolutePath { path: ref p, .. } => p, RequestUri::AbsoluteUri(ref url) => url.path(), // other 2 forms are for CONNECT and OPTIONS methods _ => "" diff --git a/doc/guide/server.md b/doc/guide/server.md --- a/doc/guide/server.md +++ b/doc/guide/server.md @@ -299,7 +299,7 @@ impl Handler<Http> for Text { fn on_request(&mut self, req: Request<Http>) -> Next { use hyper::RequestUri; let path = match *req.uri() { - RequestUri::AbsolutePath(ref p) => p, + RequestUri::AbsolutePath { path: ref p, .. } => p, RequestUri::AbsoluteUri(ref url) => url.path(), _ => "" }; diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -45,7 +45,7 @@ impl Echo { impl Handler<HttpStream> for Echo { fn on_request(&mut self, req: Request<HttpStream>) -> Next { match *req.uri() { - RequestUri::AbsolutePath(ref path) => match (req.method(), &path[..]) { + RequestUri::AbsolutePath { ref path, .. } => match (req.method(), &path[..]) { (&Get, "/") | (&Get, "/echo") => { info!("GET Index"); self.route = Route::Index; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -290,7 +290,6 @@ impl<H: Handler<T>, T: Transport> http::MessageHandler<T> for Message<H, T> { type Message = http::ClientMessage; fn on_outgoing(&mut self, head: &mut RequestHead) -> Next { - use ::url::Position; let url = self.url.take().expect("Message.url is missing"); if let Some(host) = url.host_str() { head.headers.set(Host { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -298,7 +297,10 @@ impl<H: Handler<T>, T: Transport> http::MessageHandler<T> for Message<H, T> { port: url.port(), }); } - head.subject.1 = RequestUri::AbsolutePath(url[Position::BeforePath..Position::AfterQuery].to_owned()); + head.subject.1 = RequestUri::AbsolutePath { + path: url.path().to_owned(), + query: url.query().map(|q| q.to_owned()), + }; let mut req = self::request::new(head); self.handler.on_request(&mut req) } diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -66,17 +66,25 @@ impl<'a, T> Request<'a, T> { #[inline] pub fn version(&self) -> &HttpVersion { &self.version } - /* /// The target path of this Request. #[inline] pub fn path(&self) -> Option<&str> { - match *self.uri { - RequestUri::AbsolutePath(ref s) => Some(s), - RequestUri::AbsoluteUri(ref url) => Some(&url[::url::Position::BeforePath..]), - _ => None + match self.uri { + RequestUri::AbsolutePath { path: ref p, .. } => Some(p.as_str()), + RequestUri::AbsoluteUri(ref url) => Some(url.path()), + _ => None, + } + } + + /// The query string of this Request. + #[inline] + pub fn query(&self) -> Option<&str> { + match self.uri { + RequestUri::AbsolutePath { query: ref q, .. } => q.as_ref().map(|x| x.as_str()), + RequestUri::AbsoluteUri(ref url) => url.query(), + _ => None, } } - */ /// Deconstruct this Request into its pieces. /// diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -26,8 +26,13 @@ pub enum RequestUri { /// The most common request target, an absolute path and optional query. /// /// For example, the line `GET /where?q=now HTTP/1.1` would parse the URI - /// as `AbsolutePath("/where?q=now".to_string())`. - AbsolutePath(String), + /// as `AbsolutePath { path: "/where".to_string(), query: Some("q=now".to_string()) }`. + AbsolutePath { + /// The path part of the request uri. + path: String, + /// The query part of the request uri. + query: Option<String>, + }, /// An absolute URI. Used in conjunction with proxies. /// diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -66,13 +71,22 @@ impl FromStr for RequestUri { } else if bytes == b"*" { Ok(RequestUri::Star) } else if bytes.starts_with(b"/") { - Ok(RequestUri::AbsolutePath(s.to_owned())) + let mut temp = "http://example.com".to_owned(); + temp.push_str(s); + let url = try!(Url::parse(&temp)); + Ok(RequestUri::AbsolutePath { + path: url.path().to_owned(), + query: url.query().map(|q| q.to_owned()), + }) } else if bytes.contains(&b'/') { Ok(RequestUri::AbsoluteUri(try!(Url::parse(s)))) } else { let mut temp = "http://".to_owned(); temp.push_str(s); - try!(Url::parse(&temp[..])); + let url = try!(Url::parse(&temp)); + if url.query().is_some() { + return Err(Error::Uri(UrlError::RelativeUrlWithoutBase)); + } //TODO: compare vs u.authority()? Ok(RequestUri::Authority(s.to_owned())) } diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -82,7 +96,13 @@ impl FromStr for RequestUri { impl Display for RequestUri { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - RequestUri::AbsolutePath(ref path) => f.write_str(path), + RequestUri::AbsolutePath { ref path, ref query } => { + try!(f.write_str(path)); + match *query { + Some(ref q) => write!(f, "?{}", q), + None => Ok(()), + } + } RequestUri::AbsoluteUri(ref url) => write!(f, "{}", url), RequestUri::Authority(ref path) => f.write_str(path), RequestUri::Star => f.write_str("*")
diff --git a/.travis.yml b/.travis.yml --- a/.travis.yml +++ b/.travis.yml @@ -22,7 +22,7 @@ script: - ./.travis/readme.py - cargo build --verbose $FEATURES - cargo test --verbose $FEATURES - - 'for f in ./doc/**/*.md; do rustdoc -L ./target/debug -L ./target/debug/deps --test $f; done' + - 'for f in ./doc/**/*.md; do echo "Running rustdoc on $f"; rustdoc -L ./target/debug -L ./target/debug/deps --test $f; done' addons: apt: diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -92,14 +112,20 @@ impl Display for RequestUri { #[test] fn test_uri_fromstr() { - fn read(s: &str, result: RequestUri) { + fn parse(s: &str, result: RequestUri) { assert_eq!(s.parse::<RequestUri>().unwrap(), result); } + fn parse_err(s: &str) { + assert!(s.parse::<RequestUri>().is_err()); + } - read("*", RequestUri::Star); - read("http://hyper.rs/", RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap())); - read("hyper.rs", RequestUri::Authority("hyper.rs".to_owned())); - read("/", RequestUri::AbsolutePath("/".to_owned())); + parse("*", RequestUri::Star); + parse("**", RequestUri::Authority("**".to_owned())); + parse("http://hyper.rs/", RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap())); + parse("hyper.rs", RequestUri::Authority("hyper.rs".to_owned())); + parse_err("hyper.rs?key=value"); + parse_err("hyper.rs/"); + parse("/", RequestUri::AbsolutePath { path: "/".to_owned(), query: None }); } #[test] diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -111,6 +137,9 @@ fn test_uri_display() { assert_display("*", RequestUri::Star); assert_display("http://hyper.rs/", RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap())); assert_display("hyper.rs", RequestUri::Authority("hyper.rs".to_owned())); - assert_display("/", RequestUri::AbsolutePath("/".to_owned())); - + assert_display("/", RequestUri::AbsolutePath { path: "/".to_owned(), query: None }); + assert_display("/where?key=value", RequestUri::AbsolutePath { + path: "/where".to_owned(), + query: Some("key=value".to_owned()), + }); }
Add `path()` method to `server::Request` ``` rust fn path(&self) -> Option<&str> ``` It'd need to check for a query string in the `AbsolutePath` variant.
2016-08-23T02:47:00Z
0.10
97abb81b3cc271a6dd258da86559bc25ab77c652
hyperium/hyper
898
hyperium__hyper-898
[ "891" ]
74136de9609e9e272e3fc2de1b6b939e629df093
diff --git a/src/header/internals/cell.rs b/src/header/internals/cell.rs --- a/src/header/internals/cell.rs +++ b/src/header/internals/cell.rs @@ -86,6 +86,20 @@ impl<V: ?Sized + Any + 'static> PtrMapCell<V> { }.map(|val| &mut **val) } + #[inline] + pub fn into_value(self, key: TypeId) -> Option<Box<V>> { + let map = unsafe { self.0.into_inner() }; + match map { + PtrMap::Empty => None, + PtrMap::One(id, v) => if id == key { + Some(v) + } else { + None + }, + PtrMap::Many(mut hm) => hm.remove(&key) + } + } + #[inline] pub unsafe fn insert(&self, key: TypeId, val: Box<V>) { let mut map = &mut *self.0.get(); diff --git a/src/header/internals/item.rs b/src/header/internals/item.rs --- a/src/header/internals/item.rs +++ b/src/header/internals/item.rs @@ -82,6 +82,14 @@ impl Item { } self.typed.get_mut(tid).map(|typed| unsafe { typed.downcast_mut_unchecked() }) } + + pub fn into_typed<H: Header>(self) -> Option<H> { + let tid = TypeId::of::<H>(); + match self.typed.into_value(tid) { + Some(val) => Some(val), + None => parse::<H>(self.raw.as_ref().expect("item.raw must exist")).ok() + }.map(|typed| unsafe { typed.downcast_unchecked() }) + } } #[inline] diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -182,6 +182,11 @@ impl Header + Send + Sync { unsafe fn downcast_mut_unchecked<T: 'static>(&mut self) -> &mut T { &mut *(mem::transmute::<*mut _, (*mut (), *mut ())>(self).0 as *mut T) } + + #[inline] + unsafe fn downcast_unchecked<T: 'static>(self: Box<Self>) -> T { + *Box::from_raw(mem::transmute::<*mut _, (*mut (), *mut ())>(Box::into_raw(self)).0 as *mut T) + } } impl Clone for Box<Header + Send + Sync> { diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -320,10 +325,14 @@ impl Headers { } /// Removes a header from the map, if one existed. - /// Returns true if a header has been removed. - pub fn remove<H: Header>(&mut self) -> bool { + /// Returns the header, if one has been removed and could be parsed. + /// + /// Note that this function may return `None` even though a header was removed. If you want to + /// know whether a header exists, rather rely on `has`. + pub fn remove<H: Header>(&mut self) -> Option<H> { trace!("Headers.remove( {:?} )", header_name::<H>()); - self.data.remove(&HeaderName(UniCase(Cow::Borrowed(header_name::<H>())))).is_some() + self.data.remove(&HeaderName(UniCase(Cow::Borrowed(header_name::<H>())))) + .and_then(Item::into_typed::<H>) } /// Returns an iterator over the header fields.
diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -751,6 +760,13 @@ mod tests { assert_eq!(headers.get_raw("Content-length"), None); } + #[test] + fn test_remove() { + let mut headers = Headers::new(); + headers.set(ContentLength(10)); + assert_eq!(headers.remove(), Some(ContentLength(10))); + } + #[test] fn test_len() { let mut headers = Headers::new();
Headers should offer method to remove and return header If I take a `Headers` by value (moving it into my function), I want to avoid copying them. For that reason it would be useful if either `Headers::remove` would return the popped item (as `HashMap::remove` does), or if a new method was added.
(I'm willing to write a PR for this) Hm, I agree with this entirely, 👍 . This would be a breaking change, since `remove` currently returns a `bool`, but it seems like the right one to make. As such, I'd aim it for master and not for the 0.9.x branch. Basically: ``` rust fn remove<H: Header>(&mut self) -> Option<H>; ``` Great, I will write a PR as soon as possible.
2016-08-22T19:54:17Z
0.10
97abb81b3cc271a6dd258da86559bc25ab77c652
hyperium/hyper
875
hyperium__hyper-875
[ "870" ]
e5841365dd82ff7f594f24309b48ae692cb09cc5
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -27,6 +27,7 @@ pub use self::content_disposition::{ContentDisposition, DispositionType, Disposi pub use self::content_length::ContentLength; pub use self::content_encoding::ContentEncoding; pub use self::content_language::ContentLanguage; +pub use self::content_location::ContentLocation; pub use self::content_range::{ContentRange, ContentRangeSpec}; pub use self::content_type::ContentType; pub use self::cookie::Cookie; diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -389,6 +390,7 @@ mod content_disposition; mod content_encoding; mod content_language; mod content_length; +mod content_location; mod content_range; mod content_type; mod date;
diff --git /dev/null b/src/header/common/content_location.rs new file mode 100644 --- /dev/null +++ b/src/header/common/content_location.rs @@ -0,0 +1,44 @@ +header! { + /// `Content-Location` header, defined in + /// [RFC7231](https://tools.ietf.org/html/rfc7231#section-3.1.4.2) + /// + /// The header can be used by both the client in requests and the server + /// in resposes with different semantics. Client sets `Content-Location` + /// to refer to the URI where original representation of the body was + /// obtained. + /// + /// In responses `Content-Location` represents URI for the representation + /// that was content negotiated, created or for the response payload. + /// + /// # ABNF + /// ```plain + /// Content-Location = absolute-URI / partial-URI + /// ``` + /// + /// # Example values + /// * `/hypertext/Overview.html` + /// * `http://www.example.org/hypertext/Overview.html` + /// + /// # Examples + /// + /// ``` + /// use hyper::header::{Headers, ContentLocation}; + /// + /// let mut headers = Headers::new(); + /// headers.set(ContentLocation("/hypertext/Overview.html".to_owned())); + /// ``` + /// ``` + /// use hyper::header::{Headers, ContentLocation}; + /// + /// let mut headers = Headers::new(); + /// headers.set(ContentLocation("http://www.example.org/hypertext/Overview.html".to_owned())); + /// ``` + // TODO: use URL + (ContentLocation, "Content-Location") => [String] + + test_content_location { + test_header!(partial_query, vec![b"/hypertext/Overview.html?q=tim"]); + + test_header!(absolute, vec![b"http://www.example.org/hypertext/Overview.html"]); + } +}
Add Content-Location header See https://tools.ietf.org/html/rfc7231#section-3.1.4.2
I'd like to take a shot at this. ABNF from RFC here is: ``` Content-Location = absolute-URI / partial-URI ``` ABNF is exactly same as with `Referer` which is implemented as ``` header! { // TODO Use URL (Referer, "Referer") => [String] // testcase } ``` `/TODO:? Use URL/` is mentioned for `Location` and `Referer` headers, so I guess it'd be best to implement `Content-Location` as simple `(ContentLocation, "Content-Location") => [String]` for consistency?
2016-07-27T09:58:01Z
0.10
97abb81b3cc271a6dd258da86559bc25ab77c652
hyperium/hyper
873
hyperium__hyper-873
[ "806" ]
50ccdaa7e7db574ec9890c220765ffd2da5e493b
diff --git a/doc/guide/server.md b/doc/guide/server.md --- a/doc/guide/server.md +++ b/doc/guide/server.md @@ -1,30 +1,384 @@ % Server Guide -# The `Handler` +# Hello, World -```ignore,no_run -extern crate hyper; -use hyper::server::{Handler, Request, Response, Decoder, Encoder, Next, HttpStream as Http}; +Let's start off by creating a simple server to just serve a text response +of "Hello, World!" to every request. -struct Hello; +```no_run +extern crate hyper; +use hyper::{Decoder, Encoder, HttpStream as Http, Next}; +use hyper::server::{Server, Handler, Request, Response}; -impl Handler<Http> for Hello { - fn on_request(&mut self, req: Request<Http>) -> Next { +struct Text(&'static [u8]); +impl Handler<Http> for Text { + fn on_request(&mut self, _req: Request<Http>) -> Next { + Next::write() } - fn on_request_readable(&mut self, decoder: &mut Decoder<Http>) -> Next { - + fn on_request_readable(&mut self, _decoder: &mut Decoder<Http>) -> Next { + Next::write() } fn on_response(&mut self, res: &mut Response) -> Next { + use hyper::header::ContentLength; + res.headers_mut().set(ContentLength(self.0.len() as u64)); + Next::write() + } + fn on_response_writable(&mut self, encoder: &mut Encoder<Http>) -> Next { + encoder.write(self.0).unwrap(); // for now + Next::end() } +} + +fn main() { + let addr = "127.0.0.1:0".parse().unwrap(); + let (listening, server) = Server::http(&addr).unwrap() + .handle(|_| Text(b"Hello, World")).unwrap(); + + println!("Listening on http://{}", listening); + server.run() +} +``` + +There is quite a few concepts here, so let's tackle them one by one. + +## Handler + +The [`Handler`][Handler] is how you define what should happen during the lifetime +of an HTTP message. + +## Next + +Every event in the [`Handler`][Handler] returns a [`Next`][Next]. This signals +to hyper what the `Handler` would wishes to do next, and hyper will call the +appropriate method of the `Handler` when the action is ready again. + +So, in our "Hello World" server, you'll notice that when a request comes in, we +have no interest in the `Request` or its body. We immediately just wish to write +"Hello, World!", and be done. So, in `on_request`, we return `Next::write()`, +which tells hyper we wish to write the response. + +After `on_response` is called, we ask for `Next::write()` again, because we +still need to write the response body. hyper knows that the next time the +transport is ready to be written, since it already called `on_response`, it +will call `on_response_writable`, which is where we can write the text body. + +Once we're all done with the response, we can tell hyper to finish by returning +`Next::end()`. hyper will try to finish flushing all the output, and if the +conditions are met, it may try to use the underlying transport for another +request. This is also known as "keep-alive". + +## Server + +In the `main` function, a [`Server`][Server] is created that will utilize our +`Hello` handler. We use the default options, though you may wish to peruse +them, especially the `max_sockets` option, as it is conservative by default. + +We pass a constructor closure to `Server.handle`, which constructs a `Handler` +to be used for each incoming request. +# Non-blocking IO + +## Don't Panic + +There is actually a very bad practice in the "Hello, World" example. The usage +of `decoder.write(x).unwrap()` will panic if the write operation fails. A panic +will take down the whole thread, which means the event loop and all other +in-progress requests. So don't do it. It's bad. + +What makes it worse, is that the write operation is much more likely to fail +when using non-blocking IO. If the write would block the thread, instead of +doing so, it will return an `io::Error` with the `kind` of `WouldBlock`. These +are expected errors. + +## WouldBlock + +Instead, we should inspect when there is a read or write error to see if the +`kind` was a `WouldBlock` error. Since `WouldBlock` is so common when using +non-blocking IO, the `Encoder` and `Decoder` provide `try_` methods that will +special case `WouldBlock`, allowing you to treat all `Err` cases as actual +errors. + +Additionally, it's possible there was a partial write of the response body, so +we should probably change the example to keep track of it's progress. Can you +see how we should change the example to better handle these conditions? + +This will just show the updated `on_response_writable` method, the rest stays +the same: + +```no_run +# extern crate hyper; +# use hyper::{Encoder, HttpStream as Http, Next}; + +# struct Text(&'static [u8]); + +# impl Text { fn on_response_writable(&mut self, encoder: &mut Encoder<Http>) -> Next { + match encoder.try_write(self.0) { + Ok(Some(n)) => { + if n == self.0.len() { + // all done! + Next::end() + } else { + // a partial write! + // with a static array, we can just move our pointer + // another option could be to store a separate index field + self.0 = &self.0[n..]; + // there's still more to write, so ask to write again + Next::write() + } + }, + Ok(None) => { + // would block, ask to write again + Next::write() + }, + Err(e) => { + println!("oh noes, we cannot say hello! {}", e); + // remove (kill) this transport + Next::remove() + } + } + } +# } + +# fn main() {} +``` + +# Routing + +What if we wanted to serve different messages depending on the URL of the +request? Say, we wanted to respond with "Hello, World!" to `/hello`, but +"Good-bye" with `/bye`. Let's adjust our example to do that. + +```no_run +extern crate hyper; +use hyper::{Decoder, Encoder, HttpStream as Http, Next, StatusCode}; +use hyper::server::{Server, Handler, Request, Response}; + +struct Text(StatusCode, &'static [u8]); + +impl Handler<Http> for Text { + fn on_request(&mut self, req: Request<Http>) -> Next { + use hyper::RequestUri; + let path = match *req.uri() { + RequestUri::AbsolutePath(ref p) => p, + RequestUri::AbsoluteUri(ref url) => url.path(), + // other 2 forms are for CONNECT and OPTIONS methods + _ => "" + }; + + match path { + "/hello" => { + self.1 = b"Hello, World!"; + }, + "/bye" => { + self.1 = b"Good-bye"; + }, + _ => { + self.0 = StatusCode::NotFound; + self.1 = b"Not Found"; + } + } + Next::write() + } + +# fn on_request_readable(&mut self, _decoder: &mut Decoder<Http>) -> Next { +# Next::write() +# } + fn on_response(&mut self, res: &mut Response) -> Next { + use hyper::header::ContentLength; + // we send an HTTP Status Code, 200 OK, or 404 Not Found + res.set_status(self.0); + res.headers_mut().set(ContentLength(self.1.len() as u64)); + Next::write() } + +# fn on_response_writable(&mut self, encoder: &mut Encoder<Http>) -> Next { +# match encoder.try_write(self.1) { +# Ok(Some(n)) => { +# if n == self.1.len() { +# Next::end() +# } else { +# self.1 = &self.1[n..]; +# Next::write() +# } +# }, +# Ok(None) => { +# Next::write() +# }, +# Err(e) => { +# println!("oh noes, we cannot say hello! {}", e); +# Next::remove() +# } +# } +# } +} + +fn main() { + let addr = "127.0.0.1:0".parse().unwrap(); + let (listening, server) = Server::http(&addr).unwrap() + .handle(|_| Text(StatusCode::Ok, b"")).unwrap(); + + println!("Listening on http://{}", listening); + server.run() +} +``` + +# Waiting + +More often than not, a server needs to something "expensive" before it can +provide a response to a request. This may be talking to a database, reading +a file, processing an image, sending its own HTTP request to another server, +or anything else that would impede the event loop thread. These sorts of actions +should be done off the event loop thread, when complete, should notify hyper +that it can now proceed. This is done by combining `Next::wait()` and the +[`Control`][Control]. + +## Control + +The `Control` is provided to the `Handler` constructor; it is the argument we +have so far been ignoring. It's not needed if we don't ever need to wait a +transport. The `Control` is usually sent to a queue, or another thread, or +wherever makes sense to be able to use it when the "blocking" operations are +complete. + +To focus on hyper instead of obscure blocking operations, we'll use this useless +sleeping thread to show it works. + +```no_run +extern crate hyper; + +use std::sync::mpsc; +use std::thread; +use std::time::Duration; + +use hyper::{Control, Next}; + +fn calculate_ultimate_question(rx: mpsc::Receiver<(Control, mpsc::Sender<&'static [u8]>)>) { + thread::spawn(move || { + while let Ok((ctrl, tx)) = rx.recv() { + thread::sleep(Duration::from_millis(500)); + tx.send(b"42").unwrap(); + ctrl.ready(Next::write()).unwrap(); + } + }); } # fn main() {} ``` + +Our worker will spawn a thread that waits on messages. When receiving a message, +after a short nap, it will send back the "result" of the work, and wake up the +waiting transport with a `Next::write()` desire. + +## Wait + +Finally, let's tie in our worker thread into our `Text` handler: + +```no_run +extern crate hyper; +use hyper::{Control, Decoder, Encoder, HttpStream as Http, Next, StatusCode}; +use hyper::server::{Server, Handler, Request, Response}; + +use std::sync::mpsc; + +struct Text { + status: StatusCode, + text: &'static [u8], + control: Option<Control>, + worker_tx: mpsc::Sender<(Control, mpsc::Sender<&'static [u8]>)>, + worker_rx: Option<mpsc::Receiver<&'static [u8]>>, +} + +impl Handler<Http> for Text { + fn on_request(&mut self, req: Request<Http>) -> Next { + use hyper::RequestUri; + let path = match *req.uri() { + RequestUri::AbsolutePath(ref p) => p, + RequestUri::AbsoluteUri(ref url) => url.path(), + _ => "" + }; + + match path { + "/hello" => { + self.text = b"Hello, World!"; + }, + "/bye" => { + self.text = b"Good-bye"; + }, + "/question" => { + let (tx, rx) = mpsc::channel(); + // queue work on our worker + self.worker_tx.send((self.control.take().unwrap(), tx)); + // tell hyper we need to wait until we can continue + return Next::wait(); + } + _ => { + self.status = StatusCode::NotFound; + self.text = b"Not Found"; + } + } + Next::write() + } + +# fn on_request_readable(&mut self, _decoder: &mut Decoder<Http>) -> Next { +# Next::write() +# } +# + + fn on_response(&mut self, res: &mut Response) -> Next { + use hyper::header::ContentLength; + res.set_status(self.status); + if let Some(rx) = self.worker_rx.take() { + self.text = rx.recv().unwrap(); + } + res.headers_mut().set(ContentLength(self.text.len() as u64)); + Next::write() + } +# +# fn on_response_writable(&mut self, encoder: &mut Encoder<Http>) -> Next { +# unimplemented!() +# } +} + +# fn calculate_ultimate_question(rx: mpsc::Receiver<(Control, mpsc::Sender<&'static [u8]>)>) { +# use std::sync::mpsc; +# use std::thread; +# use std::time::Duration; +# thread::spawn(move || { +# while let Ok((ctrl, tx)) = rx.recv() { +# thread::sleep(Duration::from_millis(500)); +# tx.send(b"42").unwrap(); +# ctrl.ready(Next::write()).unwrap(); +# } +# }); +# } + +fn main() { + let (tx, rx) = mpsc::channel(); + calculate_ultimate_question(rx); + let addr = "127.0.0.1:0".parse().unwrap(); + let (listening, server) = Server::http(&addr).unwrap() + .handle(move |ctrl| Text { + status: StatusCode::Ok, + text: b"", + control: Some(ctrl), + worker_tx: tx.clone(), + worker_rx: None, + }).unwrap(); + + println!("Listening on http://{}", listening); + server.run() +} +``` + + + +[Control]: ../hyper/struct.Control.html +[Handler]: ../hyper/server/trait.Handler.html +[Next]: ../hyper/struct.Next.html +[Server]: ../hyper/server/struct.Server.html diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -13,6 +13,8 @@ //! Hyper provides both a [Client](client/index.html) and a //! [Server](server/index.html), along with a //! [typed Headers system](header/index.html). +//! +//! If just getting started, consider looking over the [Server Guide](./guide/server.html). extern crate rustc_serialize as serialize; extern crate time; #[macro_use] extern crate url;
diff --git a/.travis.yml b/.travis.yml --- a/.travis.yml +++ b/.travis.yml @@ -22,7 +22,7 @@ script: - ./.travis/readme.py - cargo build --verbose $FEATURES - cargo test --verbose $FEATURES - - 'for f in ./doc/**/*.md; do rustdoc --test $f; done' + - 'for f in ./doc/**/*.md; do rustdoc -L ./target/debug -L ./target/debug/deps --test $f; done' addons: apt:
Add a Server Guide Add a guide on how to do more and more complicated things with the Server/Handler in `docs/guide/server.md`.
So what sort of spec would you hold for this guide? like what points should it cover? I could imagine the guide going in steps: - Introduce the `Handler` trait. Such as show how to make a simple "Hello World" handler, like from the `examples/hello.rs`. - Explain `WouldBlock`, and/or `try_read`/`try_write`, and repeating with `Next` until the IO is done. - Introduce some routing, using `req.uri()`. - Add an additional blocking service, like a worker pool. This would show off how to use `Next::wait()` and `Control.ready()`. Somewhere in there, sometimes it makes sense to skip explaining all the pieces, and then eventually explain "So remember `Handler<HttpStream>`? That's actually a `Transport`, go read about the Transport docs." or something. --- I'm currently fiddling with the docs script, to try to pull in any `.md` file in the `doc` directory, so that the guides will be part of the docs at http://hyper.rs/hyper, and can even be versioned.
2016-07-26T00:44:05Z
0.10
97abb81b3cc271a6dd258da86559bc25ab77c652
hyperium/hyper
867
hyperium__hyper-867
[ "859" ]
a22ae26cecf56b1a97b3d15bc57ac05a6231c8e6
diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -1,6 +1,7 @@ //! A collection of traits abstracting over Listeners and Streams. use std::io::{self, Read, Write}; use std::net::{SocketAddr}; +use std::option; use rotor::mio::tcp::{TcpStream, TcpListener}; use rotor::mio::{Selector, Token, Evented, EventSet, PollOpt, TryAccept}; diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -168,6 +169,15 @@ impl Evented for HttpListener { } } +impl IntoIterator for HttpListener { + type Item = Self; + type IntoIter = option::IntoIter<Self>; + + fn into_iter(self) -> Self::IntoIter { + Some(self).into_iter() + } +} + /// Deprecated /// /// Use `SslClient` and `SslServer` instead. diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -390,6 +400,15 @@ impl<S: SslServer> Evented for HttpsListener<S> { } } +impl<S: SslServer> IntoIterator for HttpsListener<S> { + type Item = Self; + type IntoIter = option::IntoIter<Self>; + + fn into_iter(self) -> Self::IntoIter { + Some(self).into_iter() + } +} + fn _assert_transport() { fn _assert<T: Transport>() {} _assert::<HttpsStream<HttpStream>>(); diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -37,19 +37,26 @@ impl<A: Accept, H: HandlerFactory<A::Output>> fmt::Debug for ServerLoop<A, H> { /// A Server that can accept incoming network requests. #[derive(Debug)] -pub struct Server<T: Accept> { - listener: T, +pub struct Server<A> { + lead_listener: A, + other_listeners: Vec<A>, keep_alive: bool, idle_timeout: Option<Duration>, max_sockets: usize, } -impl<T> Server<T> where T: Accept, T::Output: Transport { - /// Creates a new server with the provided Listener. - #[inline] - pub fn new(listener: T) -> Server<T> { +impl<A: Accept> Server<A> { + /// Creates a new Server from one or more Listeners. + /// + /// Panics if listeners is an empty iterator. + pub fn new<I: IntoIterator<Item = A>>(listeners: I) -> Server<A> { + let mut listeners = listeners.into_iter(); + let lead_listener = listeners.next().expect("Server::new requires at least 1 listener"); + let other_listeners = listeners.collect::<Vec<_>>(); + Server { - listener: listener, + lead_listener: lead_listener, + other_listeners: other_listeners, keep_alive: true, idle_timeout: Some(Duration::from_secs(10)), max_sockets: 4096, diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -59,7 +66,7 @@ impl<T> Server<T> where T: Accept, T::Output: Transport { /// Enables or disables HTTP keep-alive. /// /// Default is true. - pub fn keep_alive(mut self, val: bool) -> Server<T> { + pub fn keep_alive(mut self, val: bool) -> Server<A> { self.keep_alive = val; self } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -67,7 +74,7 @@ impl<T> Server<T> where T: Accept, T::Output: Transport { /// Sets how long an idle connection will be kept before closing. /// /// Default is 10 seconds. - pub fn idle_timeout(mut self, val: Option<Duration>) -> Server<T> { + pub fn idle_timeout(mut self, val: Option<Duration>) -> Server<A> { self.idle_timeout = val; self } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -75,7 +82,7 @@ impl<T> Server<T> where T: Accept, T::Output: Transport { /// Sets the maximum open sockets for this Server. /// /// Default is 4096, but most servers can handle much more than this. - pub fn max_sockets(mut self, val: usize) -> Server<T> { + pub fn max_sockets(mut self, val: usize) -> Server<A> { self.max_sockets = val; self } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -105,33 +112,48 @@ impl<S: SslServer> Server<HttpsListener<S>> { } -impl<A: Accept> Server<A> where A::Output: Transport { +impl<A: Accept> Server<A> { /// Binds to a socket and starts handling connections. pub fn handle<H>(self, factory: H) -> ::Result<(Listening, ServerLoop<A, H>)> where H: HandlerFactory<A::Output> { - let addr = try!(self.listener.local_addr()); let shutdown = Arc::new(AtomicBool::new(false)); - let shutdown_rx = shutdown.clone(); - + let mut config = rotor::Config::new(); config.slab_capacity(self.max_sockets); config.mio().notify_capacity(self.max_sockets); let keep_alive = self.keep_alive; let idle_timeout = self.idle_timeout; let mut loop_ = rotor::Loop::new(&config).unwrap(); + + let mut addrs = Vec::with_capacity(1 + self.other_listeners.len()); + + // Add the lead listener. This one handles shutdown messages. let mut notifier = None; { let notifier = &mut notifier; + let listener = self.lead_listener; + addrs.push(try!(listener.local_addr())); + let shutdown_rx = shutdown.clone(); loop_.add_machine_with(move |scope| { *notifier = Some(scope.notifier()); - rotor_try!(scope.register(&self.listener, EventSet::readable(), PollOpt::level())); - rotor::Response::ok(ServerFsm::Listener::<A, H>(self.listener, shutdown_rx)) + rotor_try!(scope.register(&listener, EventSet::readable(), PollOpt::level())); + rotor::Response::ok(ServerFsm::Listener(listener, shutdown_rx)) }).unwrap(); } let notifier = notifier.expect("loop.add_machine failed"); + // Add the other listeners. + for listener in self.other_listeners { + addrs.push(try!(listener.local_addr())); + let shutdown_rx = shutdown.clone(); + loop_.add_machine_with(move |scope| { + rotor_try!(scope.register(&listener, EventSet::readable(), PollOpt::level())); + rotor::Response::ok(ServerFsm::Listener(listener, shutdown_rx)) + }).unwrap(); + } + let listening = Listening { - addr: addr, + addrs: addrs, shutdown: (shutdown, notifier), }; let server = ServerLoop { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -299,14 +321,14 @@ where A: Accept, /// A handle of the running server. pub struct Listening { - addr: SocketAddr, + addrs: Vec<SocketAddr>, shutdown: (Arc<AtomicBool>, rotor::Notifier), } impl fmt::Debug for Listening { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Listening") - .field("addr", &self.addr) + .field("addrs", &self.addrs) .field("closed", &self.shutdown.0.load(Ordering::Relaxed)) .finish() } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -314,14 +336,20 @@ impl fmt::Debug for Listening { impl fmt::Display for Listening { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(&self.addr, f) + for (i, addr) in self.addrs().iter().enumerate() { + if i > 1 { + try!(f.write_str(", ")); + } + try!(fmt::Display::fmt(addr, f)); + } + Ok(()) } } impl Listening { - /// The address this server is listening on. - pub fn addr(&self) -> &SocketAddr { - &self.addr + /// The addresses this server is listening on. + pub fn addrs(&self) -> &[SocketAddr] { + &self.addrs } /// Stop the server from listening to its socket address.
diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -375,8 +403,3 @@ where F: FnMut(http::Control) -> H, H: Handler<T>, T: Transport { self(ctrl) } } - -#[cfg(test)] -mod tests { - -} diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -7,7 +7,7 @@ use std::sync::mpsc; use std::time::Duration; use hyper::{Next, Encoder, Decoder}; -use hyper::net::HttpStream; +use hyper::net::{HttpListener, HttpStream}; use hyper::server::{Server, Handler, Request, Response}; struct Serve { diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -17,8 +17,14 @@ struct Serve { } impl Serve { + fn addrs(&self) -> &[SocketAddr] { + self.listening.as_ref().unwrap().addrs() + } + fn addr(&self) -> &SocketAddr { - self.listening.as_ref().unwrap().addr() + let addrs = self.addrs(); + assert!(addrs.len() == 1); + &addrs[0] } /* diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -161,11 +167,22 @@ fn serve() -> Serve { } fn serve_with_timeout(dur: Option<Duration>) -> Serve { + serve_n_with_timeout(1, dur) +} + +fn serve_n(n: u32) -> Serve { + serve_n_with_timeout(n, None) +} + +fn serve_n_with_timeout(n: u32, dur: Option<Duration>) -> Serve { use std::thread; let (msg_tx, msg_rx) = mpsc::channel(); let (reply_tx, reply_rx) = mpsc::channel(); - let (listening, server) = Server::http(&"127.0.0.1:0".parse().unwrap()).unwrap() + + let addr = "127.0.0.1:0".parse().unwrap(); + let listeners = (0..n).map(|_| HttpListener::bind(&addr).unwrap()); + let (listening, server) = Server::new(listeners) .handle(move |_| { let mut replies = Vec::new(); while let Ok(reply) = reply_rx.try_recv() { diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -180,7 +197,7 @@ fn serve_with_timeout(dur: Option<Duration>) -> Serve { }).unwrap(); - let thread_name = format!("test-server-{}: {:?}", listening.addr(), dur); + let thread_name = format!("test-server-{}: {:?}", listening, dur); thread::Builder::new().name(thread_name).spawn(move || { server.run(); }).unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -439,3 +456,26 @@ fn server_keep_alive() { } } } + +#[test] +fn server_get_with_body_three_listeners() { + let server = serve_n(3); + let addrs = server.addrs(); + assert_eq!(addrs.len(), 3); + + for (i, addr) in addrs.iter().enumerate() { + let mut req = TcpStream::connect(addr).unwrap(); + write!(req, "\ + GET / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Content-Length: 17\r\n\ + \r\n\ + I'm sending to {}.\r\n\ + ", i).unwrap(); + req.read(&mut [0; 256]).unwrap(); + + // note: doesnt include trailing \r\n, cause Content-Length wasn't 19 + let comparison = format!("I'm sending to {}.", i).into_bytes(); + assert_eq!(server.body(), comparison); + } +}
Listen on multiple addresses in async hyper Given that hyper is now async it would be great to be able to easily have a single server listen on multiple addresses. It's already possible to get the local address of a connection via `Request::transport`. It's not possible to implement your own `Transport` to do this as `Evented::register` is only passed one `Token`. If you agree with this I'm happy to implement it. I think the easiest way is to let `Server` take multiple `Accept`s of the same type e.g (but with more traits so you could pass a bare HttpListener as before). ``` rust impl<I> Server<I> where I: IntoIterator, I::Item: Accept, <I::Item as Accept>::Output: Transport { ... } ``` Then you could have something like this in a different crate. ``` rust enum HttpOrHttpsListener { Http(HttpListener), Https(HttpsListener), } impl Accept for HttpOrHttpsListener { ... } ```
Interesting. Your proposed use case is to listen on port 80 and 443 in the same event loop? At the moment I just want to listen for http on multiple IPV4 and 6 addresses. That just seemed like a natural extension. While I have personal feelings on having an app run on both 80 and 443 together (I'd be that the http listener simply shoot out redirects to the 443 listener), I do believe this in general is a good thing to add. --- This would require either modifying `Server::new` to accept 1 or more `Accept`, or add a second constructor, something like `fn listeners(listeners: Vec<T>)` (or generic over an Iterator? I dunno.) And then internally, this would just add each of the listeners to the event loop. The only tweak would be that `scope.notifier()` piece that is used to signal the server should shutdown should only exist for 1 of these listeners, and not on all of them. It should be fine to keep it `T: Accept`, since the common case would be an array of TcpListeners listening on different ports. Anyone who wanted different types can compose using an enum. Everything's working. Just one last difficulty. What should the behaviour be if the constructor is passed no listeners? **It could return an error.** e.g. `fn listeners<I: IntoIterator<...>>(listeners: I) -> Result<Server, NoListenersError>` (I'm reluctant to add another variant to `Error` just for this case.) **It could panic.** I don't like panics. **`ServerLoop::run` dies immediately.** **`ServerLoop::run` runs normally (with no listeners)!** --- I'm a fan of option 4. We wouldn't need a second constructor - `Server::new` would do :thumbsup:. It makes sense if we add (at some point) the ability to add and remove listeners while the server is running. This is useful from a `service apache2 reload` point of view and if you want to do a graceful shutdown (i.e. kill the listener then wait a bit before killing all the open sockets). It's pretty easy to check if you've got no listeners and just before starting your server maybe isn't the best place to do it. Hm. So, you start a server with no listeners, and so you have an event loop running, essentially doing nothing? I get all the points of being able to kill the listener without killing the server, for shutdowns or restarts. I just don't know what you would do with _creating_ a Server that has no listeners (until there is a definitive API to add in some listeners). So, without that API, I'd lean towards providing zero listeners is a programmer error. That would mean a panic. I'm not for promoting panicking on everything, but this actually does seem like the right thing to do, since until there is a way to add listeners, a `Server` with no listener will only cause head scratches.
2016-07-18T07:04:45Z
0.10
97abb81b3cc271a6dd258da86559bc25ab77c652
hyperium/hyper
857
hyperium__hyper-857
[ "848" ]
220d09fc3a68cdd9a10589b2b454b54312518bb3
diff --git a/examples/client.rs b/examples/client.rs --- a/examples/client.rs +++ b/examples/client.rs @@ -48,7 +48,7 @@ impl hyper::client::Handler<HttpStream> for Dump { Err(e) => match e.kind() { io::ErrorKind::WouldBlock => Next::read(), _ => { - println!("ERROR: {}", e); + println!("ERROR:example: {}", e); Next::end() } } diff --git a/examples/client.rs b/examples/client.rs --- a/examples/client.rs +++ b/examples/client.rs @@ -56,7 +56,7 @@ impl hyper::client::Handler<HttpStream> for Dump { } fn on_error(&mut self, err: hyper::Error) -> Next { - println!("ERROR: {}", err); + println!("ERROR:example: {}", err); Next::remove() } } diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -16,7 +16,7 @@ pub trait Connect { /// Type of Transport to create type Output: Transport; /// The key used to determine if an existing socket can be used. - type Key: Eq + Hash + Clone; + type Key: Eq + Hash + Clone + fmt::Debug; /// Returns the key based off the Url. fn key(&self, &Url) -> Option<Self::Key>; /// Connect to a remote address. diff --git a/src/client/connect.rs b/src/client/connect.rs --- a/src/client/connect.rs +++ b/src/client/connect.rs @@ -96,10 +96,12 @@ impl Connect for HttpConnector { } fn connected(&mut self) -> Option<(Self::Key, io::Result<HttpStream>)> { - let (host, addr) = match self.dns.as_ref().expect("dns workers lost").resolved() { + let (host, addrs) = match self.dns.as_ref().expect("dns workers lost").resolved() { Ok(res) => res, Err(_) => return None }; + //TODO: try all addrs + let addr = addrs.and_then(|mut addrs| Ok(addrs.next().unwrap())); debug!("Http::resolved <- ({:?}, {:?})", host, addr); if let Entry::Occupied(mut entry) = self.resolving.entry(host) { let resolved = entry.get_mut().remove(0); diff --git a/src/client/dns.rs b/src/client/dns.rs --- a/src/client/dns.rs +++ b/src/client/dns.rs @@ -1,6 +1,7 @@ use std::io; -use std::net::{IpAddr, ToSocketAddrs}; +use std::net::{IpAddr, SocketAddr, ToSocketAddrs}; use std::thread; +use std::vec; use ::spmc; diff --git a/src/client/dns.rs b/src/client/dns.rs --- a/src/client/dns.rs +++ b/src/client/dns.rs @@ -11,7 +12,19 @@ pub struct Dns { rx: channel::Receiver<Answer>, } -pub type Answer = (String, io::Result<IpAddr>); +pub type Answer = (String, io::Result<IpAddrs>); + +pub struct IpAddrs { + iter: vec::IntoIter<SocketAddr>, +} + +impl Iterator for IpAddrs { + type Item = IpAddr; + #[inline] + fn next(&mut self) -> Option<IpAddr> { + self.iter.next().map(|addr| addr.ip()) + } +} impl Dns { pub fn new(notify: (channel::Sender<Answer>, channel::Receiver<Answer>), threads: usize) -> Dns { diff --git a/src/client/dns.rs b/src/client/dns.rs --- a/src/client/dns.rs +++ b/src/client/dns.rs @@ -26,7 +39,7 @@ impl Dns { } pub fn resolve<T: Into<String>>(&self, hostname: T) { - self.tx.send(hostname.into()).expect("Workers all died horribly"); + self.tx.send(hostname.into()).expect("DNS workers all died unexpectedly"); } pub fn resolved(&self) -> Result<Answer, channel::TryRecvError> { diff --git a/src/client/dns.rs b/src/client/dns.rs --- a/src/client/dns.rs +++ b/src/client/dns.rs @@ -41,9 +54,8 @@ fn work(rx: spmc::Receiver<String>, notify: channel::Sender<Answer>) { let notify = worker.notify.as_ref().expect("Worker lost notify"); while let Ok(host) = rx.recv() { debug!("resolve {:?}", host); - let res = match (&*host, 80).to_socket_addrs().map(|mut i| i.next()) { - Ok(Some(addr)) => (host, Ok(addr.ip())), - Ok(None) => (host, Err(io::Error::new(io::ErrorKind::Other, "no addresses found"))), + let res = match (&*host, 80).to_socket_addrs().map(|i| IpAddrs{ iter: i }) { + Ok(addrs) => (host, Ok(addrs)), Err(e) => (host, Err(e)) }; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -30,7 +30,6 @@ mod response; /// A Client to make outgoing HTTP requests. pub struct Client<H> { - //handle: Option<thread::JoinHandle<()>>, tx: http::channel::Sender<Notify<H>>, } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -64,16 +63,6 @@ impl<H> Client<H> { pub fn configure() -> Config<DefaultConnector> { Config::default() } - - /*TODO - pub fn http() -> Config<HttpConnector> { - - } - - pub fn https() -> Config<HttpsConnector> { - - } - */ } impl<H: Handler<<DefaultConnector as Connect>::Output>> Client<H> { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -243,14 +232,6 @@ impl<H> fmt::Display for ClientError<H> { } } -/* -impl Drop for Client { - fn drop(&mut self) { - self.handle.take().map(|handle| handle.join()); - } -} -*/ - /// A trait to react to client events that happen for each message. /// /// Each event handler returns it's desired `Next` action. diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -338,15 +319,16 @@ struct Context<K, H> { } impl<K: http::Key, H> Context<K, H> { - fn pop_queue(&mut self, key: &K) -> Queued<H> { + fn pop_queue(&mut self, key: &K) -> Option<Queued<H>> { let mut should_remove = false; let queued = { - let mut vec = self.queue.get_mut(key).expect("handler not in queue for key"); - let queued = vec.remove(0); - if vec.is_empty() { - should_remove = true; - } - queued + self.queue.get_mut(key).map(|vec| { + let queued = vec.remove(0); + if vec.is_empty() { + should_remove = true; + } + queued + }) }; if should_remove { self.queue.remove(key); diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -379,16 +361,22 @@ impl<K: http::Key, H> Context<K, H> { impl<K: http::Key, H: Handler<T>, T: Transport> http::MessageHandlerFactory<K, T> for Context<K, H> { type Output = Message<H, T>; - fn create(&mut self, seed: http::Seed<K>) -> Self::Output { + fn create(&mut self, seed: http::Seed<K>) -> Option<Self::Output> { let key = seed.key(); - let queued = self.pop_queue(key); - let (url, mut handler) = (queued.url, queued.handler); - handler.on_control(seed.control()); - Message { - handler: handler, - url: Some(url), - _marker: PhantomData, - } + self.pop_queue(key).map(|queued| { + let (url, mut handler) = (queued.url, queued.handler); + handler.on_control(seed.control()); + + Message { + handler: handler, + url: Some(url), + _marker: PhantomData, + } + }) + } + + fn keep_alive_interest(&self) -> Next { + Next::wait() } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -402,6 +390,7 @@ where C: Connect, C::Output: Transport, H: Handler<C::Output> { Connector(C, http::channel::Receiver<Notify<H>>), + Connecting((C::Key, C::Output)), Socket(http::Conn<C::Key, C::Output, Message<H, C::Output>>) } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -415,6 +404,7 @@ where impl<C, H> rotor::Machine for ClientFsm<C, H> where C: Connect, + C::Key: fmt::Debug, C::Output: Transport, H: Handler<C::Output> { type Context = Context<C::Key, H>; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -422,24 +412,47 @@ where C: Connect, fn create(seed: Self::Seed, scope: &mut Scope<Self::Context>) -> rotor::Response<Self, rotor::Void> { rotor_try!(scope.register(&seed.1, EventSet::writable(), PollOpt::level())); - rotor::Response::ok( - ClientFsm::Socket( - http::Conn::new(seed.0, seed.1, scope.notifier()) - .keep_alive(scope.keep_alive) - ) - ) + rotor::Response::ok(ClientFsm::Connecting(seed)) } fn ready(self, events: EventSet, scope: &mut Scope<Self::Context>) -> rotor::Response<Self, Self::Seed> { match self { - ClientFsm::Connector(..) => { - unreachable!("Connector can never be ready") - }, ClientFsm::Socket(conn) => { let res = conn.ready(events, scope); let now = scope.now(); scope.conn_response(res, now) + }, + ClientFsm::Connecting(mut seed) => { + if events.is_error() || events.is_hup() { + if let Some(err) = seed.1.take_socket_error().err() { + debug!("error while connecting: {:?}", err); + scope.pop_queue(&seed.0).map(move |mut queued| queued.handler.on_error(::Error::Io(err))); + rotor::Response::done() + } else { + trace!("connecting is_error, but no socket error"); + rotor::Response::ok(ClientFsm::Connecting(seed)) + } + } else if events.is_writable() { + if scope.queue.contains_key(&seed.0) { + trace!("connected and writable {:?}", seed.0); + rotor::Response::ok( + ClientFsm::Socket( + http::Conn::new(seed.0, seed.1, Next::write().timeout(scope.connect_timeout), scope.notifier()) + .keep_alive(scope.keep_alive) + ) + ) + } else { + trace!("connected, but queued handler is gone: {:?}", seed.0); // probably took too long connecting + rotor::Response::done() + } + } else { + // spurious? + rotor::Response::ok(ClientFsm::Connecting(seed)) + } } + ClientFsm::Connector(..) => { + unreachable!("Connector can never be ready") + }, } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -477,6 +490,7 @@ where C: Connect, None => rotor::Response::ok(self) } } + ClientFsm::Connecting(..) => unreachable!(), ClientFsm::Socket(conn) => { let res = conn.timeout(scope); let now = scope.now(); diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -494,13 +508,15 @@ where C: Connect, let res = conn.wakeup(scope); let now = scope.now(); scope.conn_response(res, now) - } + }, + ClientFsm::Connecting(..) => unreachable!("connecting sockets should not be woken up") } } } impl<C, H> ClientFsm<C, H> where C: Connect, + C::Key: fmt::Debug, C::Output: Transport, H: Handler<C::Output> { fn connect(self, scope: &mut rotor::Scope<<Self as rotor::Machine>::Context>) -> rotor::Response<Self, <Self as rotor::Machine>::Seed> { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -509,13 +525,12 @@ where C: Connect, if let Some((key, res)) = connector.connected() { match res { Ok(socket) => { - trace!("connected"); + trace!("connecting {:?}", key); return rotor::Response::spawn(ClientFsm::Connector(connector, rx), (key, socket)); }, Err(e) => { - trace!("connected error = {:?}", e); - let mut queued = scope.pop_queue(&key); - let _ = queued.handler.on_error(::Error::Io(e)); + trace!("connect error = {:?}", e); + scope.pop_queue(&key).map(|mut queued| queued.handler.on_error(::Error::Io(e))); } } } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -163,7 +163,10 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { Ok(decoder) => { trace!("decoder = {:?}", decoder); let keep_alive = self.keep_alive_enabled && head.should_keep_alive(); - let mut handler = scope.create(Seed(&self.key, &self.ctrl.0)); + let mut handler = match scope.create(Seed(&self.key, &self.ctrl.0)) { + Some(handler) => handler, + None => unreachable!() + }; let next = handler.on_incoming(head, &self.transport); trace!("handler.on_incoming() -> {:?}", next); diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -276,7 +279,7 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { }; let mut s = State::Http1(http1); if let Some(next) = next { - s.update(next); + s.update(next, &**scope); } trace!("Conn.on_readable State::Http1 completed, new state = State::{:?}", s); diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -304,7 +307,13 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { // this could be a Client request, which writes first, so pay // attention to the version written here, which will adjust // our internal state to Http1 or Http2 - let mut handler = scope.create(Seed(&self.key, &self.ctrl.0)); + let mut handler = match scope.create(Seed(&self.key, &self.ctrl.0)) { + Some(handler) => handler, + None => { + trace!("could not create handler {:?}", self.key); + return State::Closed; + } + }; let mut head = http::MessageHead::default(); let interest = handler.on_outgoing(&mut head); if head.version == HttpVersion::Http11 { diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -427,7 +436,7 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { }; if let Some(next) = next { - state.update(next); + state.update(next, &**scope); } state } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -439,7 +448,7 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { } } - fn on_error(&mut self, err: ::Error) { + fn on_error<F>(&mut self, err: ::Error, factory: &F) where F: MessageHandlerFactory<K, T> { debug!("on_error err = {:?}", err); trace!("on_error state = {:?}", self.state); let next = match self.state { diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -447,7 +456,7 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { State::Http1(ref mut http1) => http1.handler.on_error(err), State::Closed => Next::remove(), }; - self.state.update(next); + self.state.update(next, factory); } fn on_readable<F>(&mut self, scope: &mut Scope<F>) diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -477,15 +486,15 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { } impl<K: Key, T: Transport, H: MessageHandler<T>> Conn<K, T, H> { - pub fn new(key: K, transport: T, notify: rotor::Notifier) -> Conn<K, T, H> { + pub fn new(key: K, transport: T, next: Next, notify: rotor::Notifier) -> Conn<K, T, H> { Conn(Box::new(ConnInner { buf: Buffer::new(), ctrl: channel::new(notify), keep_alive_enabled: true, key: key, state: State::Init { - interest: H::Message::initial_interest().interest, - timeout: None, + interest: next.interest, + timeout: next.timeout, }, transport: transport, })) diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -506,7 +515,7 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> Conn<K, T, H> { trace!("is_error, but not socket error"); // spurious? }, - Err(e) => self.0.on_error(e.into()) + Err(e) => self.0.on_error(e.into(), &**scope) } } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -570,7 +579,7 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> Conn<K, T, H> { }, Err(e) => { trace!("error reregistering: {:?}", e); - self.0.on_error(e.into()); + self.0.on_error(e.into(), &**scope); None } } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -580,7 +589,7 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> Conn<K, T, H> { where F: MessageHandlerFactory<K, T, Output=H> { while let Ok(next) = self.0.ctrl.1.try_recv() { trace!("woke up with {:?}", next); - self.0.state.update(next); + self.0.state.update(next, &**scope); } self.ready(EventSet::readable() | EventSet::writable(), scope) } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -588,7 +597,7 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> Conn<K, T, H> { pub fn timeout<F>(mut self, scope: &mut Scope<F>) -> Option<(Self, Option<Duration>)> where F: MessageHandlerFactory<K, T, Output=H> { //TODO: check if this was a spurious timeout? - self.0.on_error(::Error::Timeout); + self.0.on_error(::Error::Timeout, &**scope); self.ready(EventSet::none(), scope) } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -660,7 +669,7 @@ impl<H: MessageHandler<T>, T: Transport> fmt::Debug for State<H, T> { } impl<H: MessageHandler<T>, T: Transport> State<H, T> { - fn update(&mut self, next: Next) { + fn update<F, K>(&mut self, next: Next, factory: &F) where F: MessageHandlerFactory<K, T>, K: Key { let timeout = next.timeout; let state = mem::replace(self, State::Closed); let new_state = match (state, next.interest) { diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -730,10 +739,10 @@ impl<H: MessageHandler<T>, T: Transport> State<H, T> { }; match (reading, writing) { (Reading::KeepAlive, Writing::KeepAlive) => { - //XXX keepalive + let next = factory.keep_alive_interest(); State::Init { - interest: H::Message::keep_alive_interest().interest, - timeout: None, + interest: next.interest, + timeout: next.timeout, } }, (reading, Writing::Chunk(chunk)) => { diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -848,6 +857,10 @@ impl<H: MessageHandler<T>, T: Transport> State<H, T> { } }; let new_state = match new_state { + State::Init { interest, .. } => State::Init { + timeout: timeout, + interest: interest, + }, State::Http1(mut http1) => { http1.timeout = timeout; State::Http1(http1) diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -4,7 +4,7 @@ use std::io::Write; use httparse; use header::{self, Headers, ContentLength, TransferEncoding}; -use http::{MessageHead, RawStatus, Http1Message, ParseResult, Next, ServerMessage, ClientMessage, Next_, RequestLine}; +use http::{MessageHead, RawStatus, Http1Message, ParseResult, ServerMessage, ClientMessage, RequestLine}; use http::h1::{Encoder, Decoder}; use method::Method; use status::StatusCode; diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -27,14 +27,6 @@ impl Http1Message for ServerMessage { type Incoming = RequestLine; type Outgoing = StatusCode; - fn initial_interest() -> Next { - Next::new(Next_::Read) - } - - fn keep_alive_interest() -> Next { - Next::new(Next_::Read) - } - fn parse(buf: &[u8]) -> ParseResult<RequestLine> { let mut headers = [httparse::EMPTY_HEADER; MAX_HEADERS]; trace!("Request.parse([Header; {}], [u8; {}])", headers.len(), buf.len()); diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -113,15 +105,6 @@ impl Http1Message for ClientMessage { type Incoming = RawStatus; type Outgoing = RequestLine; - - fn initial_interest() -> Next { - Next::new(Next_::Write) - } - - fn keep_alive_interest() -> Next { - Next::new(Next_::Wait) - } - fn parse(buf: &[u8]) -> ParseResult<RawStatus> { let mut headers = [httparse::EMPTY_HEADER; MAX_HEADERS]; trace!("Response.parse([Header; {}], [u8; {}])", headers.len(), buf.len()); diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -280,13 +280,9 @@ pub enum ClientMessage {} pub trait Http1Message { type Incoming; type Outgoing: Default; - //TODO: replace with associated const when stable - fn initial_interest() -> Next; - fn keep_alive_interest() -> Next; fn parse(bytes: &[u8]) -> ParseResult<Self::Incoming>; fn decoder(head: &MessageHead<Self::Incoming>) -> ::Result<h1::Decoder>; fn encode(head: MessageHead<Self::Outgoing>, dst: &mut Vec<u8>) -> h1::Encoder; - } /// Used to signal desired events when working with asynchronous IO. diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -167,8 +167,12 @@ struct Context<F> { impl<F: HandlerFactory<T>, T: Transport> http::MessageHandlerFactory<(), T> for Context<F> { type Output = message::Message<F::Output, T>; - fn create(&mut self, seed: http::Seed<()>) -> Self::Output { - message::Message::new(self.factory.create(seed.control())) + fn create(&mut self, seed: http::Seed<()>) -> Option<Self::Output> { + Some(message::Message::new(self.factory.create(seed.control()))) + } + + fn keep_alive_interest(&self) -> Next { + Next::read() } } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -191,7 +195,7 @@ where A: Accept, rotor_try!(scope.register(&seed, EventSet::readable(), PollOpt::level())); rotor::Response::ok( ServerFsm::Conn( - http::Conn::new((), seed, scope.notifier()) + http::Conn::new((), seed, Next::read(), scope.notifier()) .keep_alive(scope.keep_alive) ) )
diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -943,22 +956,13 @@ impl<'a, K: Key + 'a> Seed<'a, K> { pub trait MessageHandlerFactory<K: Key, T: Transport> { type Output: MessageHandler<T>; - fn create(&mut self, seed: Seed<K>) -> Self::Output; -} + fn create(&mut self, seed: Seed<K>) -> Option<Self::Output>; -impl<F, K, H, T> MessageHandlerFactory<K, T> for F -where F: FnMut(Seed<K>) -> H, - K: Key, - H: MessageHandler<T>, - T: Transport { - type Output = H; - fn create(&mut self, seed: Seed<K>) -> H { - self(seed) - } + fn keep_alive_interest(&self) -> Next; } -pub trait Key: Eq + Hash + Clone {} -impl<T: Eq + Hash + Clone> Key for T {} +pub trait Key: Eq + Hash + Clone + fmt::Debug {} +impl<T: Eq + Hash + Clone + fmt::Debug> Key for T {} #[cfg(test)] mod tests {
Client panics with 'handler not in queue for key' Using latest master. I have a `Client` that sends HTTP POST requests to the same URL from multiple threads and sometime this happens: ``` 2016-06-29 19:39:49 TRACE:hyper::client: on_incoming MessageHead { version: Http11, subject: RawStatus(200, "OK"), headers: Headers { Date: Wed, 29 Jun 2016 17:39:49 GMT, Content-Type: text/html; charset=utf-8, Transfer-Encoding: chunked, Connection: keep-alive, Set-Cookie: __cfduid=d7fc357ba132c654f5d1ff011ddf8f45c1467221989; expires=Thu, 29-Jun-17 17:39:49 GMT; path=/; domain=.requestb.in; HttpOnly, Sponsored-By: https://www.runscope.com, Via: 1.1 vegur, Server: cloudflare-nginx, CF-RAY: 2bab28f85afc2696-FRA, } } 2016-06-29 19:39:49 TRACE:hyper::client::response: Response::new 2016-06-29 19:39:49 DEBUG:hyper::client::response: version=Http11, status=Ok 2016-06-29 19:39:49 DEBUG:hyper::client::response: headers=Headers { Date: Wed, 29 Jun 2016 17:39:49 GMT, Content-Type: text/html; charset=utf-8, Transfer-Encoding: chunked, Connection: keep-alive, Set-Cookie: __cfduid=d7fc357ba132c654f5d1ff011ddf8f45c1467221989; expires=Thu, 29-Jun-17 17:39:49 GMT; path=/; domain=.requestb.in; HttpOnly, Sponsored-By: https://www.runscope.com, Via: 1.1 vegur, Server: cloudflare-nginx, CF-RAY: 2bab28f85afc2696-FRA, } 2016-06-29 19:39:49 TRACE:hyper::http::conn: handler.on_incoming() -> Next::End 2016-06-29 19:39:49 TRACE:hyper::http::conn: Conn.on_readable State::Http1 completed, new state = Closed 2016-06-29 19:39:49 TRACE:hyper::http::conn: on_readable <- Closed 2016-06-29 19:39:49 TRACE:hyper::http::conn: removing transport 2016-06-29 19:39:49 DEBUG:hyper::http::conn: on_remove 2016-06-29 19:39:49 TRACE:hyper::http::conn: Conn::ready events='Writable', blocked=None 2016-06-29 19:39:49 TRACE:hyper::http::conn: on_writable -> Init thread 'hyper-client' panicked at 'handler not in queue for key', ../src/libcore/option.rs:700 stack backtrace: 1: 0x10df189a8 - std::sys::backtrace::tracing::imp::write::h4c73fcd3363076f5 2: 0x10df1d695 - std::panicking::default_hook::_$u7b$$u7b$closure$u7d$$u7d$::h0422dbb3077e6747 3: 0x10df1d2ce - std::panicking::default_hook::haac48fa641db8fa2 4: 0x10df042a6 - std::sys_common::unwind::begin_unwind_inner::h39d40f52add53ef7 5: 0x10df0512e - std::sys_common::unwind::begin_unwind_fmt::h64c0ff793199cc1b 6: 0x10df17c77 - rust_begin_unwind 7: 0x10df44650 - core::panicking::panic_fmt::h73bf9d7e8e891a73 8: 0x10df4ba05 - core::option::expect_failed::h076bf2c39f982c10 9: 0x10d15bff7 - _<std..option..Option<T>>::expect::h4d371225682cdf33 10: 0x10d15bde8 - _<hyper..client..Context<K, H>>::pop_queue::h9f1ca6f87b02e137 11: 0x10d17f2c8 - _<hyper..client..Context<K, H> as hyper..http..conn..MessageHandlerFactory<K, T>>::create::h72fe55a18cf094e1 12: 0x10d1838d1 - _<hyper..http..conn..ConnInner<K, T, H>>::write::h27233c439f264973 13: 0x10d1833e7 - _<hyper..http..conn..ConnInner<K, T, H>>::on_writable::hf0fc8b494309b678 14: 0x10d16a117 - _<hyper..http..conn..Conn<K, T, H>>::ready::hcd9a5057a4a978bb 15: 0x10d168d34 - _<hyper..client..ClientFsm<C, H> as rotor..machine..Machine>::ready::h18d7b4b8c2b1d861 16: 0x10d156a2a - _<rotor..handler..Handler<M> as mio..handler..Handler>::ready::_$u7b$$u7b$closure$u7d$$u7d$::hd97c848ac2d5a15f 17: 0x10d154829 - rotor::handler::machine_loop::_$u7b$$u7b$closure$u7d$$u7d$::hc30baa823bb27586 18: 0x10d153bdf - _<slab..Slab<T, I>>::replace_with::h33450c53ecf92861 19: 0x10d153373 - rotor::handler::machine_loop::h9cb7d33db670d5d7 20: 0x10d153267 - _<rotor..handler..Handler<M> as mio..handler..Handler>::ready::h710fa45b2de72561 21: 0x10d15320f - _<mio..event_loop..EventLoop<H>>::io_event::h03b152c8f8e13717 22: 0x10d153138 - _<mio..event_loop..EventLoop<H>>::io_process::h181871cbb835ee55 23: 0x10d152720 - _<mio..event_loop..EventLoop<H>>::run_once::h3d9fc897d97966a0 24: 0x10d151f6b - _<mio..event_loop..EventLoop<H>>::run::hb65bd25c79b9dbbf 25: 0x10d151e87 - _<rotor..creator..LoopInstance<M>>::run::he20d485afc7f963f 26: 0x10d151da8 - _<rotor..creator..LoopCreator<M>>::run::h0cc8a75bbdd8303c 27: 0x10d151819 - _<hyper..Client<H>>::configured::_$u7b$$u7b$closure$u7d$$u7d$::h8f30494177b18b6d 28: 0x10d1511d3 - std::thread::Builder::spawn::_$u7b$$u7b$closure$u7d$$u7d$::_$u7b$$u7b$closure$u7d$$u7d$::h4b89e9fded2ad991 29: 0x10d151148 - std::sys_common::unwind::try::try_fn::h4a08d65f9221d375 30: 0x10df17c0b - __rust_try 31: 0x10df17b93 - std::sys_common::unwind::inner_try::h9eebd8dc83f388a6 32: 0x10d151085 - std::sys_common::unwind::try::h3a06944618b15d43 33: 0x10d150eb1 - std::thread::Builder::spawn::_$u7b$$u7b$closure$u7d$$u7d$::hcec021c16765064b 34: 0x10d151a57 - _<F as std..boxed..FnBox<A>>::call_box::h861041a9a27a885d 35: 0x10df1c828 - std::sys::thread::Thread::new::thread_start::h471ad90789353b5b 36: 0x7fff9549f99c - _pthread_body 37: 0x7fff9549f919 - _pthread_start ``` OS X 10.11.5
I'm still getting this error on 220d09f: ``` thread 'hyper-client' panicked at 'handler not in queue for key', ../src/libcore/option.rs:699 stack backtrace: 1: 0x101062fab - std::sys::backtrace::tracing::imp::write::h3800f45f421043b8 2: 0x101065135 - std::panicking::default_hook::_$u7b$$u7b$closure$u7d$$u7d$::h0ef6c8db532f55dc 3: 0x101064d6e - std::panicking::default_hook::hf3839060ccbb8764 4: 0x101058d57 - std::panicking::rust_panic_with_hook::h5dd7da6bb3d06020 5: 0x1010656f6 - std::panicking::begin_panic::h9bf160aee246b9f6 6: 0x101059ba8 - std::panicking::begin_panic_fmt::haf08a9a70a097ee1 7: 0x10106534f - rust_begin_unwind 8: 0x10108b260 - core::panicking::panic_fmt::h93df64e7370b5253 9: 0x10108cb95 - core::option::expect_failed::h03c4c03f58c1633f 10: 0x100e6be37 - _<std..option..Option<T>>::expect::h904cc49f34fb7126 11: 0x100e6bc28 - _<hyper..client..Context<K, H>>::pop_queue::ha385db4d7e271633 12: 0x100e94848 - _<hyper..client..Context<K, H> as hyper..http..conn..MessageHandlerFactory<K, T>>::create::hdab9d8df17821a8b 13: 0x100e99731 - _<hyper..http..conn..ConnInner<K, T, H>>::write::h8bf0793167db4de5 14: 0x100e991e7 - _<hyper..http..conn..ConnInner<K, T, H>>::on_writable::h23c7a4038164366b 15: 0x100e838a3 - _<hyper..http..conn..Conn<K, T, H>>::ready::ha7943110f672e530 16: 0x100e826bb - _<hyper..client..ClientFsm<C, H> as rotor..machine..Machine>::ready::h12d8e10694517c93 17: 0x100e64172 - _<rotor..handler..Handler<M> as mio..handler..Handler>::ready::_$u7b$$u7b$closure$u7d$$u7d$::h23e72b149b40a114 18: 0x100e61f39 - rotor::handler::machine_loop::_$u7b$$u7b$closure$u7d$$u7d$::h236e9fcf74f8593f 19: 0x100e612d3 - _<slab..Slab<T, I>>::replace_with::h360746f6793e2f7f 20: 0x100e60ab7 - rotor::handler::machine_loop::h95bcdc235462b1b1 21: 0x100e6098f - _<rotor..handler..Handler<M> as mio..handler..Handler>::ready::h63fa883c90431441 22: 0x100e6092f - _<mio..event_loop..EventLoop<H>>::io_event::h134e5ea52ae4ecee 23: 0x100e60838 - _<mio..event_loop..EventLoop<H>>::io_process::h0b3c112a870fd570 24: 0x100e5fc50 - _<mio..event_loop..EventLoop<H>>::run_once::h2c2a794cc3a3077f 25: 0x100e5f49b - _<mio..event_loop..EventLoop<H>>::run::h28c2d6d411bbd2f1 26: 0x100e5f3ba - _<rotor..creator..LoopInstance<M>>::run::h10df6fe28ea10bfb 27: 0x100e5f2e0 - _<rotor..creator..LoopCreator<M>>::run::hd70222702ee8783e 28: 0x100e5e550 - _<hyper..Client<H>>::configured::_$u7b$$u7b$closure$u7d$$u7d$::hf7f94e2f06fe4a88 29: 0x100e5e407 - _<std..panic..AssertUnwindSafe<F> as std..ops..FnOnce<()>>::call_once::h02b88cb629f75f13 30: 0x100e5e35e - std::panicking::try::_$u7b$$u7b$closure$u7d$$u7d$::_$u7b$$u7b$closure$u7d$$u7d$::hd5b87ecaef035883 31: 0x100e5eb24 - std::panicking::try::call::h7ab4dd542e8f0d6d 32: 0x101067ceb - __rust_try 33: 0x101067c85 - __rust_maybe_catch_panic 34: 0x100e5dfed - std::panicking::try::_$u7b$$u7b$closure$u7d$$u7d$::h8e4abf05d797c710 35: 0x100e5debf - _<std..thread..LocalKey<T>>::with::h2d2e8e9c5ad81465 36: 0x100e5dcef - std::panicking::try::h174a46106ff9d681 37: 0x100e5dbce - std::panic::catch_unwind::h1e31bf21058af93e 38: 0x100e5da41 - std::thread::Builder::spawn::_$u7b$$u7b$closure$u7d$$u7d$::hc9a714b59d9b1d07 39: 0x100e5ed77 - _<F as std..boxed..FnBox<A>>::call_box::hede04a1363ea441c 40: 0x101064398 - std::sys::thread::Thread::new::thread_start::h9e5bde00f3b3e2e2 41: 0x7fff91d5999c - _pthread_body 42: 0x7fff91d59919 - _pthread_start ``` I can provide a simple script to reproduce the error (based on client example). @lopuhin yea, I'd really appreciate an example. I've altered the client example locally to spawn several threads and make a bunch of requests to the same web page, and I don't get any panics... Thanks for looking into it! Here is an example that reliably reproduces the crash for me: ``` git clone https://github.com/lopuhin/rust-broad-crawl.git cd rust-broad-crawl git checkout 069c7e0aaa8efeb92bd9c81585614d21b4cba4e6 cargo run top-1k.txt ``` Note that this will make about 1000 requests to top 1000 sites from Alexa 1m (I hope there is nothing scary there). It will be making requests for about 10 seconds printing headers, then timeouts will arrive, and then the crash, so the end of the output looks like this: ``` ERROR: Timeout ERROR: Timeout ERROR: Timeout Received () thread 'hyper-client' panicked at 'handler not in queue for key', ../src/libcore/option.rs:699 note: Run with `RUST_BACKTRACE=1` for a backtrace. ``` Rust version `rustc 1.10.0 (cfcb716cf 2016-07-03)` on OS X (I can try to reproduce on ubuntu too). @lopuhin oh! its not a race condition in this case, it's incorrect handling of a connect timeout. Resolving the DNS took longer than the timeout allowed, which removed the handler, but the DNS did eventually resolve, and tried to continue where a handler no longer exists.
2016-07-13T19:24:29Z
0.9
220d09fc3a68cdd9a10589b2b454b54312518bb3
hyperium/hyper
856
hyperium__hyper-856
[ "848" ]
5f273ef646a9e7b7154ecd52b1f65388b77ea422
diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -5,6 +5,7 @@ use std::collections::HashMap; use std::fmt; +use std::io; use std::marker::PhantomData; use std::sync::mpsc; use std::thread; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -24,7 +25,6 @@ pub use self::response::Response; mod connect; mod dns; -//mod pool; mod request; mod response; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -116,6 +116,7 @@ impl<H: Send> Client<H> { loop_.run(Context { connect_timeout: connect_timeout, keep_alive: keep_alive, + idle_conns: HashMap::new(), queue: HashMap::new(), }).unwrap() })); diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -332,7 +333,7 @@ impl<H: Handler<T>, T: Transport> http::MessageHandler<T> for Message<H, T> { struct Context<K, H> { connect_timeout: Duration, keep_alive: bool, - // idle: HashMap<K, Vec<Notify>>, + idle_conns: HashMap<K, Vec<http::Control>>, queue: HashMap<K, Vec<Queued<H>>>, } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -352,6 +353,27 @@ impl<K: http::Key, H> Context<K, H> { } queued } + + fn conn_response<C>(&mut self, conn: Option<(http::Conn<K, C::Output, Message<H, C::Output>>, Option<Duration>)>, time: rotor::Time) + -> rotor::Response<ClientFsm<C, H>, (C::Key, C::Output)> + where C: Connect<Key=K>, H: Handler<C::Output> { + match conn { + Some((conn, timeout)) => { + //TODO: HTTP2: a connection doesn't need to be idle to be used for a second stream + if conn.is_idle() { + self.idle_conns.entry(conn.key().clone()).or_insert_with(Vec::new) + .push(conn.control()); + } + match timeout { + Some(dur) => rotor::Response::ok(ClientFsm::Socket(conn)) + .deadline(time + dur), + None => rotor::Response::ok(ClientFsm::Socket(conn)), + } + + } + None => rotor::Response::done() + } + } } impl<K: http::Key, H: Handler<T>, T: Transport> http::MessageHandlerFactory<K, T> for Context<K, H> { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -414,14 +436,9 @@ where C: Connect, unreachable!("Connector can never be ready") }, ClientFsm::Socket(conn) => { - match conn.ready(events, scope) { - Some((conn, None)) => rotor::Response::ok(ClientFsm::Socket(conn)), - Some((conn, Some(dur))) => { - rotor::Response::ok(ClientFsm::Socket(conn)) - .deadline(scope.now() + dur) - } - None => rotor::Response::done() - } + let res = conn.ready(events, scope); + let now = scope.now(); + scope.conn_response(res, now) } } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -461,14 +478,9 @@ where C: Connect, } } ClientFsm::Socket(conn) => { - match conn.timeout(scope) { - Some((conn, None)) => rotor::Response::ok(ClientFsm::Socket(conn)), - Some((conn, Some(dur))) => { - rotor::Response::ok(ClientFsm::Socket(conn)) - .deadline(scope.now() + dur) - } - None => rotor::Response::done() - } + let res = conn.timeout(scope); + let now = scope.now(); + scope.conn_response(res, now) } } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -478,13 +490,10 @@ where C: Connect, ClientFsm::Connector(..) => { self.connect(scope) }, - ClientFsm::Socket(conn) => match conn.wakeup(scope) { - Some((conn, None)) => rotor::Response::ok(ClientFsm::Socket(conn)), - Some((conn, Some(dur))) => { - rotor::Response::ok(ClientFsm::Socket(conn)) - .deadline(scope.now() + dur) - } - None => rotor::Response::done() + ClientFsm::Socket(conn) => { + let res = conn.wakeup(scope); + let now = scope.now(); + scope.conn_response(res, now) } } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -513,7 +522,41 @@ where C: Connect, loop { match rx.try_recv() { Ok(Notify::Connect(url, mut handler)) => { - // TODO: check pool for sockets to this domain + // check pool for sockets to this domain + if let Some(key) = connector.key(&url) { + let mut remove_idle = false; + let mut woke_up = false; + if let Some(mut idle) = scope.idle_conns.get_mut(&key) { + while !idle.is_empty() { + let ctrl = idle.remove(0); + // err means the socket has since died + if ctrl.ready(Next::write()).is_ok() { + woke_up = true; + break; + } + } + remove_idle = idle.is_empty(); + } + if remove_idle { + scope.idle_conns.remove(&key); + } + + if woke_up { + trace!("woke up idle conn for '{}'", url); + let deadline = scope.now() + scope.connect_timeout; + scope.queue.entry(key).or_insert_with(Vec::new).push(Queued { + deadline: deadline, + handler: handler, + url: url + }); + continue; + } + } else { + // this connector cannot handle this url anyways + let _ = handler.on_error(io::Error::new(io::ErrorKind::InvalidInput, "invalid url for connector").into()); + continue; + } + // no exist connection, call connector match connector.connect(&url) { Ok(key) => { let deadline = scope.now() + scope.connect_timeout; diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -63,8 +63,8 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { fn interest(&self) -> Reg { match self.state { State::Closed => Reg::Remove, - State::Init => { - <H as MessageHandler>::Message::initial_interest().interest() + State::Init { interest, .. } => { + interest.register() } State::Http1(Http1 { reading: Reading::Closed, writing: Writing::Closed, .. }) => { Reg::Remove diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -142,12 +142,12 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { fn read<F: MessageHandlerFactory<K, T, Output=H>>(&mut self, scope: &mut Scope<F>, state: State<H, T>) -> State<H, T> { match state { - State::Init => { + State::Init { interest: Next_::Read, .. } => { let head = match self.parse() { Ok(head) => head, Err(::Error::Io(e)) => match e.kind() { io::ErrorKind::WouldBlock | - io::ErrorKind::Interrupted => return State::Init, + io::ErrorKind::Interrupted => return state, _ => { debug!("io error trying to parse {:?}", e); return State::Closed; diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -219,6 +219,10 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { } } }, + State::Init { .. } => { + trace!("on_readable State::{:?}", state); + state + }, State::Http1(mut http1) => { let next = match http1.reading { Reading::Init => None, diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -274,7 +278,7 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { if let Some(next) = next { s.update(next); } - trace!("Conn.on_readable State::Http1 completed, new state = {:?}", s); + trace!("Conn.on_readable State::Http1 completed, new state = State::{:?}", s); let again = match s { State::Http1(Http1 { reading: Reading::Body(ref encoder), .. }) => encoder.is_eof(), diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -296,7 +300,7 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { fn write<F: MessageHandlerFactory<K, T, Output=H>>(&mut self, scope: &mut Scope<F>, mut state: State<H, T>) -> State<H, T> { let next = match state { - State::Init => { + State::Init { interest: Next_::Write, .. } => { // this could be a Client request, which writes first, so pay // attention to the version written here, which will adjust // our internal state to Http1 or Http2 diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -336,6 +340,10 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { } Some(interest) } + State::Init { .. } => { + trace!("Conn.on_writable State::{:?}", state); + None + } State::Http1(Http1 { ref mut handler, ref mut writing, ref mut keep_alive, .. }) => { match *writing { Writing::Init => { diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -426,7 +434,7 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { fn can_read_more(&self) -> bool { match self.state { - State::Init => false, + State::Init { .. } => false, _ => !self.buf.is_empty() } } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -435,7 +443,7 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { debug!("on_error err = {:?}", err); trace!("on_error state = {:?}", self.state); let next = match self.state { - State::Init => Next::remove(), + State::Init { .. } => Next::remove(), State::Http1(ref mut http1) => http1.handler.on_error(err), State::Closed => Next::remove(), }; diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -461,7 +469,7 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { fn on_remove(self) { debug!("on_remove"); match self.state { - State::Init | State::Closed => (), + State::Init { .. } | State::Closed => (), State::Http1(http1) => http1.handler.on_remove(self.transport), } } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -475,7 +483,10 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> Conn<K, T, H> { ctrl: channel::new(notify), keep_alive_enabled: true, key: key, - state: State::Init, + state: State::Init { + interest: H::Message::initial_interest().interest, + timeout: None, + }, transport: transport, })) } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -585,10 +596,30 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> Conn<K, T, H> { self.0.on_remove() } + pub fn key(&self) -> &K { + &self.0.key + } + + pub fn control(&self) -> Control { + Control { + tx: self.0.ctrl.0.clone(), + } + } + + pub fn is_idle(&self) -> bool { + if let State::Init { interest: Next_::Wait, .. } = self.0.state { + true + } else { + false + } + } } enum State<H: MessageHandler<T>, T: Transport> { - Init, + Init { + interest: Next_, + timeout: Option<Duration>, + }, /// Http1 will only ever use a connection to send and receive a single /// message at a time. Once a H1 status has been determined, we will either /// be reading or writing an H1 message, and optionally multiple if diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -606,7 +637,7 @@ enum State<H: MessageHandler<T>, T: Transport> { impl<H: MessageHandler<T>, T: Transport> State<H, T> { fn timeout(&self) -> Option<Duration> { match *self { - State::Init => None, + State::Init { timeout, .. } => timeout, State::Http1(ref http1) => http1.timeout, State::Closed => None, } diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -616,7 +647,10 @@ impl<H: MessageHandler<T>, T: Transport> State<H, T> { impl<H: MessageHandler<T>, T: Transport> fmt::Debug for State<H, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - State::Init => f.write_str("Init"), + State::Init { interest, timeout } => f.debug_struct("Init") + .field("interest", &interest) + .field("timeout", &timeout) + .finish(), State::Http1(ref h1) => f.debug_tuple("Http1") .field(h1) .finish(), diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -632,10 +666,14 @@ impl<H: MessageHandler<T>, T: Transport> State<H, T> { let new_state = match (state, next.interest) { (_, Next_::Remove) => State::Closed, (State::Closed, _) => State::Closed, - (State::Init, _) => State::Init, + (State::Init { timeout, .. }, e) => State::Init { + interest: e, + timeout: timeout, + }, (State::Http1(http1), Next_::End) => { let reading = match http1.reading { - Reading::Body(ref decoder) if decoder.is_eof() => { + Reading::Body(ref decoder) | + Reading::Wait(ref decoder) if decoder.is_eof() => { if http1.keep_alive { Reading::KeepAlive } else { diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -646,6 +684,7 @@ impl<H: MessageHandler<T>, T: Transport> State<H, T> { _ => Reading::Closed, }; let writing = match http1.writing { + Writing::Wait(encoder) | Writing::Ready(encoder) => { if encoder.is_eof() { if http1.keep_alive { diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -691,8 +730,11 @@ impl<H: MessageHandler<T>, T: Transport> State<H, T> { }; match (reading, writing) { (Reading::KeepAlive, Writing::KeepAlive) => { - //http1.handler.on_keep_alive(); - State::Init + //XXX keepalive + State::Init { + interest: H::Message::keep_alive_interest().interest, + timeout: None, + } }, (reading, Writing::Chunk(chunk)) => { State::Http1(Http1 { diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -31,6 +31,10 @@ impl Http1Message for ServerMessage { Next::new(Next_::Read) } + fn keep_alive_interest() -> Next { + Next::new(Next_::Read) + } + fn parse(buf: &[u8]) -> ParseResult<RequestLine> { let mut headers = [httparse::EMPTY_HEADER; MAX_HEADERS]; trace!("Request.parse([Header; {}], [u8; {}])", headers.len(), buf.len()); diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -114,6 +118,10 @@ impl Http1Message for ClientMessage { Next::new(Next_::Write) } + fn keep_alive_interest() -> Next { + Next::new(Next_::Wait) + } + fn parse(buf: &[u8]) -> ParseResult<RawStatus> { let mut headers = [httparse::EMPTY_HEADER; MAX_HEADERS]; trace!("Response.parse([Header; {}], [u8; {}])", headers.len(), buf.len()); diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -249,14 +249,16 @@ impl Deserialize for RawStatus { /// Checks if a connection should be kept alive. #[inline] pub fn should_keep_alive(version: HttpVersion, headers: &Headers) -> bool { - trace!("should_keep_alive( {:?}, {:?} )", version, headers.get::<Connection>()); - match (version, headers.get::<Connection>()) { + let ret = match (version, headers.get::<Connection>()) { (Http10, None) => false, (Http10, Some(conn)) if !conn.contains(&KeepAlive) => false, (Http11, Some(conn)) if conn.contains(&Close) => false, _ => true - } + }; + trace!("should_keep_alive(version={:?}, header={:?}) = {:?}", version, headers.get::<Connection>(), ret); + ret } + pub type ParseResult<T> = ::Result<Option<(MessageHead<T>, usize)>>; pub fn parse<T: Http1Message<Incoming=I>, I>(rdr: &[u8]) -> ParseResult<I> { diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -280,6 +282,7 @@ pub trait Http1Message { type Outgoing: Default; //TODO: replace with associated const when stable fn initial_interest() -> Next; + fn keep_alive_interest() -> Next; fn parse(bytes: &[u8]) -> ParseResult<Self::Incoming>; fn decoder(head: &MessageHead<Self::Incoming>) -> ::Result<h1::Decoder>; fn encode(head: MessageHead<Self::Outgoing>, dst: &mut Vec<u8>) -> h1::Encoder; diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -304,6 +307,7 @@ impl fmt::Debug for Next { } } +// Internal enum for `Next` #[derive(Debug, Clone, Copy)] enum Next_ { Read, diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -314,6 +318,8 @@ enum Next_ { Remove, } +// An enum representing all the possible actions to taken when registering +// with the event loop. #[derive(Debug, Clone, Copy)] enum Reg { Read, diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -361,16 +367,11 @@ impl Next { } } - fn interest(&self) -> Reg { - match self.interest { - Next_::Read => Reg::Read, - Next_::Write => Reg::Write, - Next_::ReadWrite => Reg::ReadWrite, - Next_::Wait => Reg::Wait, - Next_::End => Reg::Remove, - Next_::Remove => Reg::Remove, - } + /* + fn reg(&self) -> Reg { + self.interest.register() } + */ /// Signals the desire to read from the transport. pub fn read() -> Next {
diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -410,6 +411,19 @@ impl Next { } } +impl Next_ { + fn register(&self) -> Reg { + match *self { + Next_::Read => Reg::Read, + Next_::Write => Reg::Write, + Next_::ReadWrite => Reg::ReadWrite, + Next_::Wait => Reg::Wait, + Next_::End => Reg::Remove, + Next_::Remove => Reg::Remove, + } + } +} + #[test] fn test_should_keep_alive() { let mut headers = Headers::new(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -363,3 +363,28 @@ fn client_read_timeout() { other => panic!("expected timeout, actual: {:?}", other) } } + +#[test] +fn client_keep_alive() { + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = server.local_addr().unwrap(); + let client = client(); + let res = client.request(format!("http://{}/a", addr), opts()); + + let mut sock = server.accept().unwrap().0; + sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut buf = [0; 4096]; + sock.read(&mut buf).expect("read 1"); + sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").expect("write 1"); + + while let Ok(_) = res.recv() {} + + let res = client.request(format!("http://{}/b", addr), opts()); + sock.read(&mut buf).expect("read 2"); + let second_get = b"GET /b HTTP/1.1\r\n"; + assert_eq!(&buf[..second_get.len()], second_get); + sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").expect("write 2"); + + while let Ok(_) = res.recv() {} +} diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -72,7 +72,7 @@ impl Drop for Serve { struct TestHandler { tx: mpsc::Sender<Msg>, - rx: mpsc::Receiver<Reply>, + reply: Vec<Reply>, peeked: Option<Vec<u8>>, timeout: Option<Duration>, } diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -123,28 +123,26 @@ impl Handler<HttpStream> for TestHandler { } fn on_response(&mut self, res: &mut Response) -> Next { - loop { - match self.rx.try_recv() { - Ok(Reply::Status(s)) => { + for reply in self.reply.drain(..) { + match reply { + Reply::Status(s) => { res.set_status(s); }, - Ok(Reply::Headers(headers)) => { + Reply::Headers(headers) => { use std::iter::Extend; res.headers_mut().extend(headers.iter()); }, - Ok(Reply::Body(body)) => { + Reply::Body(body) => { self.peeked = Some(body); }, - Err(..) => { - return if self.peeked.is_some() { - self.next(Next::write()) - } else { - self.next(Next::end()) - }; - }, } } + if self.peeked.is_some() { + self.next(Next::write()) + } else { + self.next(Next::end()) + } } fn on_response_writable(&mut self, encoder: &mut Encoder<HttpStream>) -> Next { diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -167,13 +165,18 @@ fn serve_with_timeout(dur: Option<Duration>) -> Serve { let (msg_tx, msg_rx) = mpsc::channel(); let (reply_tx, reply_rx) = mpsc::channel(); - let mut reply_rx = Some(reply_rx); let (listening, server) = Server::http(&"127.0.0.1:0".parse().unwrap()).unwrap() - .handle(move |_| TestHandler { - tx: msg_tx.clone(), - timeout: dur, - rx: reply_rx.take().unwrap(), - peeked: None, + .handle(move |_| { + let mut replies = Vec::new(); + while let Ok(reply) = reply_rx.try_recv() { + replies.push(reply); + } + TestHandler { + tx: msg_tx.clone(), + timeout: dur, + reply: replies, + peeked: None, + } }).unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -377,3 +380,62 @@ fn server_empty_response_chunked_without_calling_write() { assert_eq!(lines.next(), Some("")); assert_eq!(lines.next(), None); } + +#[test] +fn server_keep_alive() { + extern crate env_logger; + env_logger::init().unwrap(); + + let foo_bar = b"foo bar baz"; + let server = serve(); + server.reply() + .status(hyper::Ok) + .header(hyper::header::ContentLength(foo_bar.len() as u64)) + .body(foo_bar); + let mut req = TcpStream::connect(server.addr()).unwrap(); + req.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + req.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + req.write_all(b"\ + GET / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Connection: keep-alive\r\n\ + \r\n\ + ").expect("writing 1"); + + let mut buf = [0; 1024 * 8]; + loop { + let n = req.read(&mut buf[..]).expect("reading 1"); + if n < buf.len() { + if &buf[n - foo_bar.len()..n] == foo_bar { + break; + } else { + println!("{:?}", ::std::str::from_utf8(&buf[..n])); + } + } + } + + // try again! + + let quux = b"zar quux"; + server.reply() + .status(hyper::Ok) + .header(hyper::header::ContentLength(quux.len() as u64)) + .body(quux); + req.write_all(b"\ + GET /quux HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Connection: close\r\n\ + \r\n\ + ").expect("writing 2"); + + let mut buf = [0; 1024 * 8]; + loop { + let n = req.read(&mut buf[..]).expect("reading 2"); + assert!(n > 0, "n = {}", n); + if n < buf.len() { + if &buf[n - quux.len()..n] == quux { + break; + } + } + } +}
Client panics with 'handler not in queue for key' Using latest master. I have a `Client` that sends HTTP POST requests to the same URL from multiple threads and sometime this happens: ``` 2016-06-29 19:39:49 TRACE:hyper::client: on_incoming MessageHead { version: Http11, subject: RawStatus(200, "OK"), headers: Headers { Date: Wed, 29 Jun 2016 17:39:49 GMT, Content-Type: text/html; charset=utf-8, Transfer-Encoding: chunked, Connection: keep-alive, Set-Cookie: __cfduid=d7fc357ba132c654f5d1ff011ddf8f45c1467221989; expires=Thu, 29-Jun-17 17:39:49 GMT; path=/; domain=.requestb.in; HttpOnly, Sponsored-By: https://www.runscope.com, Via: 1.1 vegur, Server: cloudflare-nginx, CF-RAY: 2bab28f85afc2696-FRA, } } 2016-06-29 19:39:49 TRACE:hyper::client::response: Response::new 2016-06-29 19:39:49 DEBUG:hyper::client::response: version=Http11, status=Ok 2016-06-29 19:39:49 DEBUG:hyper::client::response: headers=Headers { Date: Wed, 29 Jun 2016 17:39:49 GMT, Content-Type: text/html; charset=utf-8, Transfer-Encoding: chunked, Connection: keep-alive, Set-Cookie: __cfduid=d7fc357ba132c654f5d1ff011ddf8f45c1467221989; expires=Thu, 29-Jun-17 17:39:49 GMT; path=/; domain=.requestb.in; HttpOnly, Sponsored-By: https://www.runscope.com, Via: 1.1 vegur, Server: cloudflare-nginx, CF-RAY: 2bab28f85afc2696-FRA, } 2016-06-29 19:39:49 TRACE:hyper::http::conn: handler.on_incoming() -> Next::End 2016-06-29 19:39:49 TRACE:hyper::http::conn: Conn.on_readable State::Http1 completed, new state = Closed 2016-06-29 19:39:49 TRACE:hyper::http::conn: on_readable <- Closed 2016-06-29 19:39:49 TRACE:hyper::http::conn: removing transport 2016-06-29 19:39:49 DEBUG:hyper::http::conn: on_remove 2016-06-29 19:39:49 TRACE:hyper::http::conn: Conn::ready events='Writable', blocked=None 2016-06-29 19:39:49 TRACE:hyper::http::conn: on_writable -> Init thread 'hyper-client' panicked at 'handler not in queue for key', ../src/libcore/option.rs:700 stack backtrace: 1: 0x10df189a8 - std::sys::backtrace::tracing::imp::write::h4c73fcd3363076f5 2: 0x10df1d695 - std::panicking::default_hook::_$u7b$$u7b$closure$u7d$$u7d$::h0422dbb3077e6747 3: 0x10df1d2ce - std::panicking::default_hook::haac48fa641db8fa2 4: 0x10df042a6 - std::sys_common::unwind::begin_unwind_inner::h39d40f52add53ef7 5: 0x10df0512e - std::sys_common::unwind::begin_unwind_fmt::h64c0ff793199cc1b 6: 0x10df17c77 - rust_begin_unwind 7: 0x10df44650 - core::panicking::panic_fmt::h73bf9d7e8e891a73 8: 0x10df4ba05 - core::option::expect_failed::h076bf2c39f982c10 9: 0x10d15bff7 - _<std..option..Option<T>>::expect::h4d371225682cdf33 10: 0x10d15bde8 - _<hyper..client..Context<K, H>>::pop_queue::h9f1ca6f87b02e137 11: 0x10d17f2c8 - _<hyper..client..Context<K, H> as hyper..http..conn..MessageHandlerFactory<K, T>>::create::h72fe55a18cf094e1 12: 0x10d1838d1 - _<hyper..http..conn..ConnInner<K, T, H>>::write::h27233c439f264973 13: 0x10d1833e7 - _<hyper..http..conn..ConnInner<K, T, H>>::on_writable::hf0fc8b494309b678 14: 0x10d16a117 - _<hyper..http..conn..Conn<K, T, H>>::ready::hcd9a5057a4a978bb 15: 0x10d168d34 - _<hyper..client..ClientFsm<C, H> as rotor..machine..Machine>::ready::h18d7b4b8c2b1d861 16: 0x10d156a2a - _<rotor..handler..Handler<M> as mio..handler..Handler>::ready::_$u7b$$u7b$closure$u7d$$u7d$::hd97c848ac2d5a15f 17: 0x10d154829 - rotor::handler::machine_loop::_$u7b$$u7b$closure$u7d$$u7d$::hc30baa823bb27586 18: 0x10d153bdf - _<slab..Slab<T, I>>::replace_with::h33450c53ecf92861 19: 0x10d153373 - rotor::handler::machine_loop::h9cb7d33db670d5d7 20: 0x10d153267 - _<rotor..handler..Handler<M> as mio..handler..Handler>::ready::h710fa45b2de72561 21: 0x10d15320f - _<mio..event_loop..EventLoop<H>>::io_event::h03b152c8f8e13717 22: 0x10d153138 - _<mio..event_loop..EventLoop<H>>::io_process::h181871cbb835ee55 23: 0x10d152720 - _<mio..event_loop..EventLoop<H>>::run_once::h3d9fc897d97966a0 24: 0x10d151f6b - _<mio..event_loop..EventLoop<H>>::run::hb65bd25c79b9dbbf 25: 0x10d151e87 - _<rotor..creator..LoopInstance<M>>::run::he20d485afc7f963f 26: 0x10d151da8 - _<rotor..creator..LoopCreator<M>>::run::h0cc8a75bbdd8303c 27: 0x10d151819 - _<hyper..Client<H>>::configured::_$u7b$$u7b$closure$u7d$$u7d$::h8f30494177b18b6d 28: 0x10d1511d3 - std::thread::Builder::spawn::_$u7b$$u7b$closure$u7d$$u7d$::_$u7b$$u7b$closure$u7d$$u7d$::h4b89e9fded2ad991 29: 0x10d151148 - std::sys_common::unwind::try::try_fn::h4a08d65f9221d375 30: 0x10df17c0b - __rust_try 31: 0x10df17b93 - std::sys_common::unwind::inner_try::h9eebd8dc83f388a6 32: 0x10d151085 - std::sys_common::unwind::try::h3a06944618b15d43 33: 0x10d150eb1 - std::thread::Builder::spawn::_$u7b$$u7b$closure$u7d$$u7d$::hcec021c16765064b 34: 0x10d151a57 - _<F as std..boxed..FnBox<A>>::call_box::h861041a9a27a885d 35: 0x10df1c828 - std::sys::thread::Thread::new::thread_start::h471ad90789353b5b 36: 0x7fff9549f99c - _pthread_body 37: 0x7fff9549f919 - _pthread_start ``` OS X 10.11.5
2016-07-08T17:16:53Z
0.9
220d09fc3a68cdd9a10589b2b454b54312518bb3
hyperium/hyper
853
hyperium__hyper-853
[ "651" ]
b47affd94b1ca53d04642202728f194a1ceec04d
diff --git a/src/header/common/host.rs b/src/header/common/host.rs --- a/src/header/common/host.rs +++ b/src/header/common/host.rs @@ -1,6 +1,8 @@ use header::{Header, HeaderFormat}; use std::fmt; +use std::str::FromStr; use header::parsing::from_one_raw_str; +use url::idna::domain_to_unicode; /// The `Host` header. /// diff --git a/src/header/common/host.rs b/src/header/common/host.rs --- a/src/header/common/host.rs +++ b/src/header/common/host.rs @@ -47,44 +49,7 @@ impl Header for Host { } fn parse_header(raw: &[Vec<u8>]) -> ::Result<Host> { - from_one_raw_str(raw).and_then(|mut s: String| { - // FIXME: use rust-url to parse this - // https://github.com/servo/rust-url/issues/42 - let idx = { - let slice = &s[..]; - let mut chars = slice.chars(); - chars.next(); - if chars.next().unwrap() == '[' { - match slice.rfind(']') { - Some(idx) => { - if slice.len() > idx + 2 { - Some(idx + 1) - } else { - None - } - } - None => return Err(::Error::Header) // this is a bad ipv6 address... - } - } else { - slice.rfind(':') - } - }; - - let port = match idx { - Some(idx) => s[idx + 1..].parse().ok(), - None => None - }; - - match idx { - Some(idx) => s.truncate(idx), - None => () - } - - Ok(Host { - hostname: s, - port: port - }) - }) + from_one_raw_str(raw) } } diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -43,6 +43,7 @@ pub use self::if_unmodified_since::IfUnmodifiedSince; pub use self::if_range::IfRange; pub use self::last_modified::LastModified; pub use self::location::Location; +pub use self::origin::Origin; pub use self::pragma::Pragma; pub use self::prefer::{Prefer, Preference}; pub use self::preference_applied::PreferenceApplied; diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -406,6 +407,7 @@ mod if_range; mod if_unmodified_since; mod last_modified; mod location; +mod origin; mod pragma; mod prefer; mod preference_applied;
diff --git a/src/header/common/host.rs b/src/header/common/host.rs --- a/src/header/common/host.rs +++ b/src/header/common/host.rs @@ -97,6 +62,35 @@ impl HeaderFormat for Host { } } +impl fmt::Display for Host { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.fmt_header(f) + } +} + +impl FromStr for Host { + type Err = ::Error; + + fn from_str(s: &str) -> ::Result<Host> { + let (host_port, res) = domain_to_unicode(s); + if res.is_err() { + return Err(::Error::Header) + } + let idx = host_port.rfind(':'); + let port = idx.and_then( + |idx| s[idx + 1..].parse().ok() + ); + let hostname = match idx { + None => host_port, + Some(idx) => host_port[..idx].to_owned() + }; + Ok(Host { + hostname: hostname, + port: port + }) + } +} + #[cfg(test)] mod tests { use super::Host; diff --git /dev/null b/src/header/common/origin.rs new file mode 100644 --- /dev/null +++ b/src/header/common/origin.rs @@ -0,0 +1,112 @@ +use header::{Header, Host, HeaderFormat}; +use std::fmt; +use std::str::FromStr; +use header::parsing::from_one_raw_str; + +/// The `Origin` header. +/// +/// The `Origin` header is a version of the `Referer` header that is used for all HTTP fetches and `POST`s whose CORS flag is set. +/// This header is often used to inform recipients of the security context of where the request was initiated. +/// +/// +/// Following the spec, https://fetch.spec.whatwg.org/#origin-header, the value of this header is composed of +/// a String (scheme), header::Host (host/port) +/// +/// # Examples +/// ``` +/// use hyper::header::{Headers, Origin}; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// Origin::new("http", "hyper.rs", None) +/// ); +/// ``` +/// ``` +/// use hyper::header::{Headers, Origin}; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// Origin::new("https", "wikipedia.org", Some(443)) +/// ); +/// ``` + +#[derive(Clone, Debug)] +pub struct Origin { + /// The scheme, such as http or https + pub scheme: String, + /// The host, such as Host{hostname: "hyper.rs".to_owned(), port: None} + pub host: Host, +} + +impl Origin { + pub fn new<S: Into<String>, H: Into<String>>(scheme: S, hostname: H, port: Option<u16>) -> Origin{ + Origin { + scheme: scheme.into(), + host: Host { + hostname: hostname.into(), + port: port + } + } + } +} + +impl Header for Origin { + fn header_name() -> &'static str { + static NAME: &'static str = "Origin"; + NAME + } + + fn parse_header(raw: &[Vec<u8>]) -> ::Result<Origin> { + from_one_raw_str(raw) + } +} + +impl FromStr for Origin { + type Err = ::Error; + + fn from_str(s: &str) -> ::Result<Origin> { + let idx = match s.find("://") { + Some(idx) => idx, + None => return Err(::Error::Header) + }; + // idx + 3 because thats how long "://" is + let (scheme, etc) = (&s[..idx], &s[idx + 3..]); + let host = try!(Host::from_str(etc)); + + + Ok(Origin{ + scheme: scheme.to_owned(), + host: host + }) + } +} + +impl HeaderFormat for Origin { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}://{}", self.scheme, self.host) + } +} + +impl PartialEq for Origin { + fn eq(&self, other: &Origin) -> bool { + self.scheme == other.scheme && self.host == other.host + } +} + + +#[cfg(test)] +mod tests { + use super::Origin; + use header::Header; + + #[test] + fn test_origin() { + let origin = Header::parse_header([b"http://foo.com".to_vec()].as_ref()); + assert_eq!(origin.ok(), Some(Origin::new("http", "foo.com", None))); + + let origin = Header::parse_header([b"https://foo.com:443".to_vec()].as_ref()); + assert_eq!(origin.ok(), Some(Origin::new("https", "foo.com", Some(443)))); + } +} + +bench_header!(bench, Origin, { vec![b"https://foo.com".to_vec()] });
Origin Header It seems like the "Origin" header is missing [here](http://hyper.rs/hyper/hyper/header/index.html) http://tools.ietf.org/id/draft-abarth-origin-03.html
Is this in common use? I've never used it myself, and when checking the dev consoles, I notice neither Firefox nor Chrome set that header while browsing. The Origin header is set for CORS requests. On 15 October 2015 01:36:27 CEST, Sean McArthur notifications@github.com wrote: > Is this in common use? I've never used it myself, and when checking the > dev consoles, I notice neither Firefox nor Chrome set that header while > browsing. > > --- > > Reply to this email directly or view it on GitHub: > https://github.com/hyperium/hyper/issues/651#issuecomment-148233353 ## Sent from my phone. Please excuse my brevity. Ah yes, quite true. I had forgotten. @seanmonstar Is anyone working on this? If not I'd be interested in giving it a go Go for it! On Thu, Nov 19, 2015 at 4:56 AM Martin Feckie notifications@github.com wrote: > @seanmonstar https://github.com/seanmonstar Is anyone working on this? > If not I'd be interested in giving it a go > > — > Reply to this email directly or view it on GitHub > https://github.com/hyperium/hyper/issues/651#issuecomment-158049297. I don't think anybody is working on this. On Thu, Nov 19, 2015 at 04:56:13AM -0800, Martin Feckie wrote: > @seanmonstar Is anyone working on this? If not I'd be interested in giving it a go > > --- > > Reply to this email directly or view it on GitHub: > https://github.com/hyperium/hyper/issues/651#issuecomment-158049297 Would love to get newly-rusty hands wet; what's going on here? A variety of PRs have been closed, and one (to another project?) I think the main discussion is under https://github.com/hyperium/hyper/pull/691, basically we waited until rust-url was 1.0 (where its Origin type was rewritten) and then forgot about it. On 5 July 2016 01:21:00 EEST, Michael Perez notifications@github.com wrote: > Would love to get newly-rusty hands wet; what's going on here? > > A variety of PRs have been closed, and one (to another project?) > > --- > > You are receiving this because you are subscribed to this thread. > Reply to this email directly or view it on GitHub: > https://github.com/hyperium/hyper/issues/651#issuecomment-230359643 ## Sent from my Android device with K-9 Mail. Please excuse my brevity. The current type in rust-url is an enum with an `OpaqueOrigin` variant, which is not needed in the header. So, I'm thinking we do something like this: ``` rust pub struct Origin(String, String, Option<u16>); // support default ports impl PartialEq for Origin { fn eq(&self, other: &Origin) -> bool { if self.0 == other.0 && self.1 == other.1 { self.2.or_else(|| default_port(&self.0)) == other.2.or_else(|| default_port(&other.0)) } false } } fn default_port(scheme: &str) -> Option<u16> { match scheme { "http" => Some(80), "https" => Some(443), _ => None, } } ``` @seanmonstar that seems good for a single "serialized-origin". I'm not very familiar with things (in general) but according to the [spec](https://tools.ietf.org/html/rfc6454#section-7) the value of an Origin header may actually be a vec of this implementation of Origin. Aside from that in order to parse/generate, after having read [the docs](http://hyper.rs/hyper/v0.9.9/hyper/header/index.html) the `Origin` struct also needs to implement `Header` and `HeaderFormat` right? also aside: y use `u16` when there are no negative ports? @puhrez since the Origin header only makes in CORS requests, may as well use the definition from the most up-to-date spec governing them: https://fetch.spec.whatwg.org/#origin-header In that spec, the `Origin` is only ever 1 value. Yes, a header needs to implement `Header` (and `HeaderFormat` in the 0.9x branch. If possible, the `header!` macro handles this merge of traits). A `u16` means unsigned, so a bit isn't dedicated to the sign. This means it's range is 0-65535, which is the full range of possible ports.
2016-07-06T20:03:14Z
0.9
220d09fc3a68cdd9a10589b2b454b54312518bb3
hyperium/hyper
845
hyperium__hyper-845
[ "843" ]
e682844431f9d3e83f9dfc8bd5f7ef873b8a9b16
diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -14,7 +14,7 @@ static PHRASE: &'static [u8] = b"Hello World!"; struct Hello; impl Handler<HttpStream> for Hello { - fn on_request(&mut self, _: Request) -> Next { + fn on_request(&mut self, _: Request<HttpStream>) -> Next { Next::write() } fn on_request_readable(&mut self, _: &mut Decoder<HttpStream>) -> Next { diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -46,7 +46,7 @@ impl Echo { } impl Handler<HttpStream> for Echo { - fn on_request(&mut self, req: Request) -> Next { + fn on_request(&mut self, req: Request<HttpStream>) -> Next { match *req.uri() { RequestUri::AbsolutePath(ref path) => match (req.method(), &path[..]) { (&Get, "/") | (&Get, "/echo") => { diff --git a/examples/sync.rs /dev/null --- a/examples/sync.rs +++ /dev/null @@ -1,278 +0,0 @@ -extern crate hyper; -extern crate env_logger; -extern crate time; - -use std::io::{self, Read, Write}; -use std::marker::PhantomData; -use std::thread; -use std::sync::{Arc, mpsc}; - -pub struct Server { - listening: hyper::server::Listening, -} - -pub struct Request<'a> { - #[allow(dead_code)] - inner: hyper::server::Request, - tx: &'a mpsc::Sender<Action>, - rx: &'a mpsc::Receiver<io::Result<usize>>, - ctrl: &'a hyper::Control, -} - -impl<'a> Request<'a> { - fn new(inner: hyper::server::Request, tx: &'a mpsc::Sender<Action>, rx: &'a mpsc::Receiver<io::Result<usize>>, ctrl: &'a hyper::Control) -> Request<'a> { - Request { - inner: inner, - tx: tx, - rx: rx, - ctrl: ctrl, - } - } -} - -impl<'a> io::Read for Request<'a> { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.tx.send(Action::Read(buf.as_mut_ptr(), buf.len())).unwrap(); - self.ctrl.ready(hyper::Next::read()).unwrap(); - self.rx.recv().unwrap() - } -} - -pub enum Fresh {} -pub enum Streaming {} - -pub struct Response<'a, W = Fresh> { - status: hyper::StatusCode, - headers: hyper::Headers, - version: hyper::HttpVersion, - tx: &'a mpsc::Sender<Action>, - rx: &'a mpsc::Receiver<io::Result<usize>>, - ctrl: &'a hyper::Control, - _marker: PhantomData<W>, -} - -impl<'a> Response<'a, Fresh> { - fn new(tx: &'a mpsc::Sender<Action>, rx: &'a mpsc::Receiver<io::Result<usize>>, ctrl: &'a hyper::Control) -> Response<'a, Fresh> { - Response { - status: hyper::Ok, - headers: hyper::Headers::new(), - version: hyper::HttpVersion::Http11, - tx: tx, - rx: rx, - ctrl: ctrl, - _marker: PhantomData, - } - } - - pub fn start(self) -> io::Result<Response<'a, Streaming>> { - self.tx.send(Action::Respond(self.version.clone(), self.status.clone(), self.headers.clone())).unwrap(); - self.ctrl.ready(hyper::Next::write()).unwrap(); - let res = self.rx.recv().unwrap(); - res.map(move |_| Response { - status: self.status, - headers: self.headers, - version: self.version, - tx: self.tx, - rx: self.rx, - ctrl: self.ctrl, - _marker: PhantomData, - }) - } - - pub fn send(mut self, msg: &[u8]) -> io::Result<()> { - self.headers.set(hyper::header::ContentLength(msg.len() as u64)); - self.start().and_then(|mut res| res.write_all(msg)).map(|_| ()) - } -} - -impl<'a> Write for Response<'a, Streaming> { - fn write(&mut self, msg: &[u8]) -> io::Result<usize> { - self.tx.send(Action::Write(msg.as_ptr(), msg.len())).unwrap(); - self.ctrl.ready(hyper::Next::write()).unwrap(); - let res = self.rx.recv().unwrap(); - res - } - - fn flush(&mut self) -> io::Result<()> { - panic!("Response.flush() not impemented") - } -} - -struct SynchronousHandler { - req_tx: mpsc::Sender<hyper::server::Request>, - tx: mpsc::Sender<io::Result<usize>>, - rx: mpsc::Receiver<Action>, - reading: Option<(*mut u8, usize)>, - writing: Option<(*const u8, usize)>, - respond: Option<(hyper::HttpVersion, hyper::StatusCode, hyper::Headers)> -} - -unsafe impl Send for SynchronousHandler {} - -impl SynchronousHandler { - fn next(&mut self) -> hyper::Next { - match self.rx.try_recv() { - Ok(Action::Read(ptr, len)) => { - self.reading = Some((ptr, len)); - hyper::Next::read() - }, - Ok(Action::Respond(ver, status, headers)) => { - self.respond = Some((ver, status, headers)); - hyper::Next::write() - }, - Ok(Action::Write(ptr, len)) => { - self.writing = Some((ptr, len)); - hyper::Next::write() - } - Err(mpsc::TryRecvError::Empty) => { - // we're too fast, the other thread hasn't had a chance to respond - hyper::Next::wait() - } - Err(mpsc::TryRecvError::Disconnected) => { - // they dropped it - // TODO: should finish up sending response, whatever it was - hyper::Next::end() - } - } - } - - fn reading(&mut self) -> Option<(*mut u8, usize)> { - self.reading.take().or_else(|| { - match self.rx.try_recv() { - Ok(Action::Read(ptr, len)) => { - Some((ptr, len)) - }, - _ => None - } - }) - } - - fn writing(&mut self) -> Option<(*const u8, usize)> { - self.writing.take().or_else(|| { - match self.rx.try_recv() { - Ok(Action::Write(ptr, len)) => { - Some((ptr, len)) - }, - _ => None - } - }) - } - fn respond(&mut self) -> Option<(hyper::HttpVersion, hyper::StatusCode, hyper::Headers)> { - self.respond.take().or_else(|| { - match self.rx.try_recv() { - Ok(Action::Respond(ver, status, headers)) => { - Some((ver, status, headers)) - }, - _ => None - } - }) - } -} - -impl hyper::server::Handler<hyper::net::HttpStream> for SynchronousHandler { - fn on_request(&mut self, req: hyper::server::Request) -> hyper::Next { - if let Err(_) = self.req_tx.send(req) { - return hyper::Next::end(); - } - - self.next() - } - - fn on_request_readable(&mut self, decoder: &mut hyper::Decoder<hyper::net::HttpStream>) -> hyper::Next { - if let Some(raw) = self.reading() { - let slice = unsafe { ::std::slice::from_raw_parts_mut(raw.0, raw.1) }; - if self.tx.send(decoder.read(slice)).is_err() { - return hyper::Next::end(); - } - } - self.next() - } - - fn on_response(&mut self, req: &mut hyper::server::Response) -> hyper::Next { - use std::iter::Extend; - if let Some(head) = self.respond() { - req.set_status(head.1); - req.headers_mut().extend(head.2.iter()); - if self.tx.send(Ok(0)).is_err() { - return hyper::Next::end(); - } - } else { - // wtf happened? - panic!("no head to respond with"); - } - self.next() - } - - fn on_response_writable(&mut self, encoder: &mut hyper::Encoder<hyper::net::HttpStream>) -> hyper::Next { - if let Some(raw) = self.writing() { - let slice = unsafe { ::std::slice::from_raw_parts(raw.0, raw.1) }; - if self.tx.send(encoder.write(slice)).is_err() { - return hyper::Next::end(); - } - } - self.next() - } -} - -enum Action { - Read(*mut u8, usize), - Write(*const u8, usize), - Respond(hyper::HttpVersion, hyper::StatusCode, hyper::Headers), -} - -unsafe impl Send for Action {} - -trait Handler: Send + Sync + 'static { - fn handle(&self, req: Request, res: Response); -} - -impl<F> Handler for F where F: Fn(Request, Response) + Send + Sync + 'static { - fn handle(&self, req: Request, res: Response) { - (self)(req, res) - } -} - -impl Server { - fn handle<H: Handler>(addr: &str, handler: H) -> Server { - let handler = Arc::new(handler); - let (listening, server) = hyper::Server::http(&addr.parse().unwrap()).unwrap() - .handle(move |ctrl| { - let (req_tx, req_rx) = mpsc::channel(); - let (blocking_tx, blocking_rx) = mpsc::channel(); - let (async_tx, async_rx) = mpsc::channel(); - let handler = handler.clone(); - thread::Builder::new().name("handler-thread".into()).spawn(move || { - let req = Request::new(req_rx.recv().unwrap(), &blocking_tx, &async_rx, &ctrl); - let res = Response::new(&blocking_tx, &async_rx, &ctrl); - handler.handle(req, res); - }).unwrap(); - - SynchronousHandler { - req_tx: req_tx, - tx: async_tx, - rx: blocking_rx, - reading: None, - writing: None, - respond: None, - } - }).unwrap(); - thread::spawn(move || { - server.run(); - }); - Server { - listening: listening - } - } -} - -fn main() { - env_logger::init().unwrap(); - let s = Server::handle("127.0.0.1:0", |mut req: Request, res: Response| { - let mut body = [0; 256]; - let n = req.read(&mut body).unwrap(); - println!("!!!: received: {:?}", ::std::str::from_utf8(&body[..n]).unwrap()); - - res.send(b"Hello World!").unwrap(); - }); - println!("listening on {}", s.listening.addr()); -} diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -310,7 +310,7 @@ impl<H: Handler<T>, T: Transport> http::MessageHandler<T> for Message<H, T> { self.handler.on_request_writable(transport) } - fn on_incoming(&mut self, head: http::ResponseHead) -> Next { + fn on_incoming(&mut self, head: http::ResponseHead, _: &T) -> Next { trace!("on_incoming {:?}", head); let resp = response::new(head); self.handler.on_response(resp) diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -164,7 +164,7 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { trace!("decoder = {:?}", decoder); let keep_alive = self.keep_alive_enabled && head.should_keep_alive(); let mut handler = scope.create(Seed(&self.key, &self.ctrl.0)); - let next = handler.on_incoming(head); + let next = handler.on_incoming(head, &self.transport); trace!("handler.on_incoming() -> {:?}", next); match next.interest { diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -231,7 +231,7 @@ impl<K: Key, T: Transport, H: MessageHandler<T>> ConnInner<K, T, H> { if http1.keep_alive { http1.keep_alive = head.should_keep_alive(); } - let next = http1.handler.on_incoming(head); + let next = http1.handler.on_incoming(head, &self.transport); http1.reading = Reading::Wait(decoder); trace!("handler.on_incoming() -> {:?}", next); Some(next) diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -874,7 +874,7 @@ impl Chunk { pub trait MessageHandler<T: Transport> { type Message: Http1Message; - fn on_incoming(&mut self, head: http::MessageHead<<Self::Message as Http1Message>::Incoming>) -> Next; + fn on_incoming(&mut self, head: http::MessageHead<<Self::Message as Http1Message>::Incoming>, transport: &T) -> Next; fn on_outgoing(&mut self, head: &mut http::MessageHead<<Self::Message as Http1Message>::Outgoing>) -> Next; fn on_decode(&mut self, &mut http::Decoder<T>) -> Next; fn on_encode(&mut self, &mut http::Encoder<T>) -> Next; diff --git a/src/server/message.rs b/src/server/message.rs --- a/src/server/message.rs +++ b/src/server/message.rs @@ -28,9 +28,9 @@ impl<H: Handler<T>, T: Transport> Message<H, T> { impl<H: Handler<T>, T: Transport> http::MessageHandler<T> for Message<H, T> { type Message = http::ServerMessage; - fn on_incoming(&mut self, head: http::RequestHead) -> Next { + fn on_incoming(&mut self, head: http::RequestHead, transport: &T) -> Next { trace!("on_incoming {:?}", head); - let req = request::new(head); + let req = request::new(head, transport); self.handler.on_request(req) } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -324,7 +324,7 @@ impl Listening { /// Each event handler returns it's desired `Next` action. pub trait Handler<T: Transport> { /// This event occurs first, triggering when a `Request` has been parsed. - fn on_request(&mut self, request: Request) -> Next; + fn on_request(&mut self, request: Request<T>) -> Next; /// This event occurs each time the `Request` is ready to be read from. fn on_request_readable(&mut self, request: &mut http::Decoder<T>) -> Next; /// This event occurs after the first time this handled signals `Next::write()`. diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -3,13 +3,15 @@ //! These are requests that a `hyper::Server` receives, and include its method, //! target URI, headers, and message body. +use std::fmt; + use version::HttpVersion; use method::Method; use header::Headers; use http::{RequestHead, MessageHead, RequestLine}; use uri::RequestUri; -pub fn new(incoming: RequestHead) -> Request { +pub fn new<'a, T>(incoming: RequestHead, transport: &'a T) -> Request<'a, T> { let MessageHead { version, subject: RequestLine(method, uri), headers } = incoming; debug!("Request Line: {:?} {:?} {:?}", method, uri, version); debug!("{:#?}", headers); diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -19,22 +21,31 @@ pub fn new(incoming: RequestHead) -> Request { uri: uri, headers: headers, version: version, + transport: transport, } } /// A request bundles several parts of an incoming `NetworkStream`, given to a `Handler`. -#[derive(Debug)] -pub struct Request { - // The IP address of the remote connection. - //remote_addr: SocketAddr, +pub struct Request<'a, T: 'a> { method: Method, - headers: Headers, uri: RequestUri, version: HttpVersion, + headers: Headers, + transport: &'a T, } +impl<'a, T> fmt::Debug for Request<'a, T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Request") + .field("method", &self.method) + .field("uri", &self.uri) + .field("version", &self.version) + .field("headers", &self.headers) + .finish() + } +} -impl Request { +impl<'a, T> Request<'a, T> { /// The `Method`, such as `Get`, `Post`, etc. #[inline] pub fn method(&self) -> &Method { &self.method } diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -43,6 +54,10 @@ impl Request { #[inline] pub fn headers(&self) -> &Headers { &self.headers } + /// The underlying `Transport` of this request. + #[inline] + pub fn transport(&self) -> &'a T { self.transport } + /// The target request-uri for this request. #[inline] pub fn uri(&self) -> &RequestUri { &self.uri }
diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -99,7 +99,7 @@ impl TestHandler { } impl Handler<HttpStream> for TestHandler { - fn on_request(&mut self, _req: Request) -> Next { + fn on_request(&mut self, _req: Request<HttpStream>) -> Next { //self.tx.send(Msg::Head(req)).unwrap(); self.next(Next::read()) }
Remote Address Might Not Always Available So looking more carefully at how hyper does its thing it looks like the remote address (from the transport) might not always be available. In the case of a GET request there likely won't be a body and it looks like https://github.com/hyperium/hyper/blob/master/src/server/mod.rs#L329 won't be called then. If thats the case then the remote address is never available for certain request types which would seem to be a bug.
I've also simply felt that it'd be better to have access to the `Transport` in the `on_request` event. So to do this, I've been thinking of adding a `&'a T` field to the `Request` struct. ``` rust fn on_request<'a>(&mut self, req: Request<'a>) -> Next { let addr = req.transport().peer_addr().unwrap(); } ``` I wonder if lifetime elision can remove the need for those `'a`s... @Ogeon @Ryman would this hurt ergonomics for frameworks much that you could no longer hold on to the `Request` object? You could still get the underlying fields with `req.deconstruct()`... I don't think it will be a problem. I'm consuming the request in `on_request`, so it won't leave the scope. I'm quite sure the `'a`s will be elided, as well. It's the same for the `Handler` trait in Rustful. I haven't spent enough time with the new api to know if it'll be a problem, but I imagine if `deconstruct` is available it'll probably be fine :)
2016-06-23T22:29:49Z
0.9
220d09fc3a68cdd9a10589b2b454b54312518bb3
hyperium/hyper
841
hyperium__hyper-841
[ "833", "821" ]
6dab63fbac546fee78dadad20ec2617c7396f15a
diff --git a/src/header/internals/item.rs b/src/header/internals/item.rs --- a/src/header/internals/item.rs +++ b/src/header/internals/item.rs @@ -78,6 +78,9 @@ impl Item { Err(_) => () } } + if self.raw.is_some() && self.typed.get_mut(tid).is_some() { + self.raw = OptCell::new(None); + } self.typed.get_mut(tid).map(|typed| unsafe { typed.downcast_mut_unchecked() }) } }
diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -670,6 +670,7 @@ mod tests { fn test_get_mutable() { let mut headers = Headers::from_raw(&raw!(b"Content-Length: 10")).unwrap(); *headers.get_mut::<ContentLength>().unwrap() = ContentLength(20); + assert_eq!(headers.get_raw("content-length").unwrap(), &[b"20".to_vec()][..]); assert_eq!(*headers.get::<ContentLength>().unwrap(), ContentLength(20)); }
Kill raw part when getting mutable reference to typed header Fixes #821. get_mut doesn't seem to work I'm not sure what happened here: ``` rust extern crate hyper; use hyper::header::Headers; use hyper::header::{ContentLength, ContentType}; use hyper::http::RawStatus; use hyper::method::Method; use hyper::mime::{Attr as MimeAttr, Value}; fn main() { let mut x = Headers::new(); x.set_raw("Content-Type", vec!["text/plain;charset=shift-jis".bytes().collect()]); println!("old: {:?}", x); // charset is shift-jis if let Some(old_ct) = x.get_mut::<ContentType>() { println!("old old_ct: {:?}", old_ct); // still shift-jis let mut new_ct = old_ct.clone(); for param in (new_ct.0).2.iter_mut() { if param.0 == MimeAttr::Charset { println!("old param {:?}", param); // shift-jis *param = (MimeAttr::Charset, Value::Ext("hi".into())); println!("new param {:?}", param); // hi } } *old_ct = new_ct; println!("new old_ct: {:?}", old_ct); // hi } // at this stage I'd expect the header to have changed. But it hasn't. println!("new get: {:?}", x.get::<ContentType>()); // hi println!("new get raw: {:?}", x.get_raw("content-type")); // shift-jis again?? println!("new: {:?}", x); // shift-jis again?? } ```
I guess the mixture of raw and non-raw methods is breaking it, but I'm not sure. Does set_raw create two copies of the thing -- one typed, one untyped? I guess the issue is that typed_mut doesn't remove the header from the raw headers when inserting a typed one. Ah, this is a bug. The invariants I've been enforcing are: if you get an immutable view (raw or typed), and it doesn't exist, it will generate it and then give it to you (either serializing a typed, or parsing a raw). However, if you get a mutable reference, because you can cause them to be out of sync, it should obliterate the other stored value. So, `get_mut` should kill the raw part. I believe it does this correctly when you do `headers.set(Foo)`, so it's a hole in `get_mut`.
2016-06-20T22:13:45Z
0.9
220d09fc3a68cdd9a10589b2b454b54312518bb3
hyperium/hyper
834
hyperium__hyper-834
[ "831" ]
43ac0dd09569f80625f7875ff27543bfaf339b99
diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -646,13 +646,6 @@ impl<H: MessageHandler<T>, T: Transport> State<H, T> { _ => Reading::Closed, }; let writing = match http1.writing { - Writing::Ready(ref encoder) if encoder.is_eof() => { - if http1.keep_alive { - Writing::KeepAlive - } else { - Writing::Closed - } - }, Writing::Ready(encoder) => { if encoder.is_eof() { if http1.keep_alive { diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -660,7 +653,7 @@ impl<H: MessageHandler<T>, T: Transport> State<H, T> { } else { Writing::Closed } - } else if let Some(buf) = encoder.end() { + } else if let Some(buf) = encoder.finish() { Writing::Chunk(Chunk { buf: buf.bytes, pos: buf.pos, diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -680,7 +673,7 @@ impl<H: MessageHandler<T>, T: Transport> State<H, T> { } else { Writing::Closed } - } else if let Some(buf) = encoder.end() { + } else if let Some(buf) = encoder.finish() { Writing::Chunk(Chunk { buf: buf.bytes, pos: buf.pos, diff --git a/src/http/conn.rs b/src/http/conn.rs --- a/src/http/conn.rs +++ b/src/http/conn.rs @@ -719,14 +712,26 @@ impl<H: MessageHandler<T>, T: Transport> State<H, T> { }; http1.writing = match http1.writing { - Writing::Ready(encoder) => if encoder.is_eof() { - if http1.keep_alive { - Writing::KeepAlive + Writing::Ready(encoder) => { + if encoder.is_eof() { + if http1.keep_alive { + Writing::KeepAlive + } else { + Writing::Closed + } + } else if encoder.is_closed() { + if let Some(buf) = encoder.finish() { + Writing::Chunk(Chunk { + buf: buf.bytes, + pos: buf.pos, + next: (h1::Encoder::length(0), Next::wait()) + }) + } else { + Writing::Closed + } } else { - Writing::Closed + Writing::Wait(encoder) } - } else { - Writing::Wait(encoder) }, Writing::Chunk(chunk) => if chunk.is_written() { Writing::Wait(chunk.next.0) diff --git a/src/http/h1/encode.rs b/src/http/h1/encode.rs --- a/src/http/h1/encode.rs +++ b/src/http/h1/encode.rs @@ -8,7 +8,8 @@ use http::internal::{AtomicWrite, WriteBuf}; #[derive(Debug, Clone)] pub struct Encoder { kind: Kind, - prefix: Prefix, //Option<WriteBuf<Vec<u8>>> + prefix: Prefix, + is_closed: bool, } #[derive(Debug, PartialEq, Clone)] diff --git a/src/http/h1/encode.rs b/src/http/h1/encode.rs --- a/src/http/h1/encode.rs +++ b/src/http/h1/encode.rs @@ -25,14 +26,16 @@ impl Encoder { pub fn chunked() -> Encoder { Encoder { kind: Kind::Chunked(Chunked::Init), - prefix: Prefix(None) + prefix: Prefix(None), + is_closed: false, } } pub fn length(len: u64) -> Encoder { Encoder { kind: Kind::Length(len), - prefix: Prefix(None) + prefix: Prefix(None), + is_closed: false, } } diff --git a/src/http/h1/encode.rs b/src/http/h1/encode.rs --- a/src/http/h1/encode.rs +++ b/src/http/h1/encode.rs @@ -51,7 +54,16 @@ impl Encoder { } } - pub fn end(self) -> Option<WriteBuf<Cow<'static, [u8]>>> { + /// User has called `encoder.close()` in a `Handler`. + pub fn is_closed(&self) -> bool { + self.is_closed + } + + pub fn close(&mut self) { + self.is_closed = true; + } + + pub fn finish(self) -> Option<WriteBuf<Cow<'static, [u8]>>> { let trailer = self.trailer(); let buf = self.prefix.0; diff --git a/src/http/h1/parse.rs b/src/http/h1/parse.rs --- a/src/http/h1/parse.rs +++ b/src/http/h1/parse.rs @@ -188,8 +188,9 @@ impl Http1Message for ClientMessage { body = Encoder::chunked(); let encodings = match head.headers.get_mut::<TransferEncoding>() { Some(encodings) => { - //TODO: check if Chunked already exists - encodings.push(header::Encoding::Chunked); + if !encodings.contains(&header::Encoding::Chunked) { + encodings.push(header::Encoding::Chunked); + } true }, None => false diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -72,6 +72,7 @@ impl<'a, T: Read> Decoder<'a, T> { Decoder(DecoderImpl::H1(decoder, transport)) } + /// Get a reference to the transport. pub fn get_ref(&self) -> &T { match self.0 { diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -85,6 +86,17 @@ impl<'a, T: Transport> Encoder<'a, T> { Encoder(EncoderImpl::H1(encoder, transport)) } + /// Closes an encoder, signaling that no more writing will occur. + /// + /// This is needed for encodings that don't know length of the content + /// beforehand. Most common instance would be usage of + /// `Transfer-Enciding: chunked`. You would call `close()` to signal + /// the `Encoder` should write the end chunk, or `0\r\n\r\n`. + pub fn close(&mut self) { + match self.0 { + EncoderImpl::H1(ref mut encoder, _) => encoder.close() + } + } /// Get a reference to the transport. pub fn get_ref(&self) -> &T { diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -113,7 +125,11 @@ impl<'a, T: Transport> Write for Encoder<'a, T> { } match self.0 { EncoderImpl::H1(ref mut encoder, ref mut transport) => { - encoder.encode(*transport, data) + if encoder.is_closed() { + Ok(0) + } else { + encoder.encode(*transport, data) + } } } }
diff --git a/src/http/h1/encode.rs b/src/http/h1/encode.rs --- a/src/http/h1/encode.rs +++ b/src/http/h1/encode.rs @@ -335,7 +347,7 @@ mod tests { use mock::{Async, Buf}; #[test] - fn test_write_chunked_sync() { + fn test_chunked_encode_sync() { let mut dst = Buf::new(); let mut encoder = Encoder::chunked(); diff --git a/src/http/h1/encode.rs b/src/http/h1/encode.rs --- a/src/http/h1/encode.rs +++ b/src/http/h1/encode.rs @@ -346,7 +358,7 @@ mod tests { } #[test] - fn test_write_chunked_async() { + fn test_chunked_encode_async() { let mut dst = Async::new(Buf::new(), 7); let mut encoder = Encoder::chunked(); diff --git a/src/http/h1/encode.rs b/src/http/h1/encode.rs --- a/src/http/h1/encode.rs +++ b/src/http/h1/encode.rs @@ -360,7 +372,7 @@ mod tests { } #[test] - fn test_write_sized() { + fn test_sized_encode() { let mut dst = Buf::new(); let mut encoder = Encoder::length(8); encoder.encode(&mut dst, b"foo bar").unwrap(); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -8,6 +8,7 @@ use std::time::Duration; use hyper::client::{Handler, Request, Response, HttpConnector}; use hyper::{Method, StatusCode, Next, Encoder, Decoder}; +use hyper::header::Headers; use hyper::net::HttpStream; fn s(bytes: &[u8]) -> &str { diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -48,10 +49,24 @@ fn read(opts: &Opts) -> Next { impl Handler<HttpStream> for TestHandler { fn on_request(&mut self, req: &mut Request) -> Next { req.set_method(self.opts.method.clone()); - read(&self.opts) + req.headers_mut().extend(self.opts.headers.iter()); + if self.opts.body.is_some() { + Next::write() + } else { + read(&self.opts) + } } - fn on_request_writable(&mut self, _encoder: &mut Encoder<HttpStream>) -> Next { + fn on_request_writable(&mut self, encoder: &mut Encoder<HttpStream>) -> Next { + if let Some(ref mut body) = self.opts.body { + let n = encoder.write(body).unwrap(); + *body = &body[n..]; + + if !body.is_empty() { + return Next::write() + } + } + encoder.close(); read(&self.opts) } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -103,14 +118,18 @@ struct Client { #[derive(Debug)] struct Opts { + body: Option<&'static [u8]>, method: Method, + headers: Headers, read_timeout: Option<Duration>, } impl Default for Opts { fn default() -> Opts { Opts { + body: None, method: Method::Get, + headers: Headers::new(), read_timeout: None, } } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -126,6 +145,16 @@ impl Opts { self } + fn header<H: ::hyper::header::Header>(mut self, header: H) -> Opts { + self.headers.set(header); + self + } + + fn body(mut self, body: Option<&'static [u8]>) -> Opts { + self.body = body; + self + } + fn read_timeout(mut self, timeout: Duration) -> Opts { self.read_timeout = Some(timeout); self diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -167,33 +196,46 @@ macro_rules! test { request: method: $client_method:ident, url: $client_url:expr, + headers: [ $($request_headers:expr,)* ], + body: $request_body:expr, + response: status: $client_status:ident, - headers: [ $($client_headers:expr,)* ], - body: $client_body:expr + headers: [ $($response_headers:expr,)* ], + body: $response_body:expr, ) => ( #[test] fn $name() { + #[allow(unused)] + use hyper::header::*; let server = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = server.local_addr().unwrap(); let client = client(); - let res = client.request(format!($client_url, addr=addr), opts().method(Method::$client_method)); + let opts = opts() + .method(Method::$client_method) + .body($request_body); + $( + let opts = opts.header($request_headers); + )* + let res = client.request(format!($client_url, addr=addr), opts); let mut inc = server.accept().unwrap().0; inc.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); inc.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); - let mut buf = [0; 4096]; - let n = inc.read(&mut buf).unwrap(); let expected = format!($server_expected, addr=addr); + let mut buf = [0; 4096]; + let mut n = 0; + while n < buf.len() && n < expected.len() { + n += inc.read(&mut buf[n..]).unwrap(); + } assert_eq!(s(&buf[..n]), expected); inc.write_all($server_reply.as_ref()).unwrap(); if let Msg::Head(head) = res.recv().unwrap() { - use hyper::header::*; assert_eq!(head.status(), &StatusCode::$client_status); $( - assert_eq!(head.headers().get(), Some(&$client_headers)); + assert_eq!(head.headers().get(), Some(&$response_headers)); )* } else { panic!("we lost the head!"); diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -205,23 +247,27 @@ macro_rules! test { ); } +static REPLY_OK: &'static str = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"; + test! { name: client_get, server: expected: "GET / HTTP/1.1\r\nHost: {addr}\r\n\r\n", - reply: "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", + reply: REPLY_OK, client: request: method: Get, url: "http://{addr}/", + headers: [], + body: None, response: status: Ok, headers: [ ContentLength(0), ], - body: None + body: None, } test! { diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -229,19 +275,76 @@ test! { server: expected: "GET /foo?key=val HTTP/1.1\r\nHost: {addr}\r\n\r\n", - reply: "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", + reply: REPLY_OK, client: request: method: Get, url: "http://{addr}/foo?key=val#dont_send_me", + headers: [], + body: None, response: status: Ok, headers: [ ContentLength(0), ], - body: None + body: None, +} + +test! { + name: client_post_sized, + server: + expected: "\ + POST /length HTTP/1.1\r\n\ + Host: {addr}\r\n\ + Content-Length: 7\r\n\ + \r\n\ + foo bar\ + ", + reply: REPLY_OK, + + client: + request: + method: Post, + url: "http://{addr}/length", + headers: [ + ContentLength(7), + ], + body: Some(b"foo bar"), + response: + status: Ok, + headers: [], + body: None, +} + +test! { + name: client_post_chunked, + + server: + expected: "\ + POST /chunks HTTP/1.1\r\n\ + Host: {addr}\r\n\ + Transfer-Encoding: chunked\r\n\ + \r\n\ + B\r\n\ + foo bar baz\r\n\ + 0\r\n\r\n\ + ", + reply: REPLY_OK, + + client: + request: + method: Post, + url: "http://{addr}/chunks", + headers: [ + TransferEncoding::chunked(), + ], + body: Some(b"foo bar baz"), + response: + status: Ok, + headers: [], + body: None, } #[test]
Client needs a way to "end" writing chunked requests
This cannot be `Next::end()`, as that signals the entire message is complete. There is need to signal "writing is done, but I still want to read from the server". Some options I've thought of: - Make the Handler write with zero bytes if chunked, ie `encoder.write(b"")` - Add a method to `Encoder<T>`, such that the handler calls `encoder.end()` - Add a variant to `Next`, such as `Next::response()` or `Next::read_only()` or something else horrid :cry:
2016-06-17T11:08:53Z
0.9
220d09fc3a68cdd9a10589b2b454b54312518bb3
hyperium/hyper
827
hyperium__hyper-827
[ "804" ]
f20d5953c775868a139f3f55e7774cbbd6425dbf
diff --git a/src/http/buffer.rs b/src/http/buffer.rs --- a/src/http/buffer.rs +++ b/src/http/buffer.rs @@ -98,6 +98,12 @@ pub struct BufReader<'a, R: io::Read + 'a> { reader: &'a mut R } +impl<'a, R: io::Read + 'a> BufReader<'a, R> { + pub fn get_ref(&self) -> &R { + self.reader + } +} + impl<'a, R: io::Read> Read for BufReader<'a, R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { trace!("BufReader.read self={}, buf={}", self.buf.len(), buf.len()); diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -44,6 +44,15 @@ enum Trans<'a, T: Read + 'a> { Buf(self::buffer::BufReader<'a, T>) } +impl<'a, T: Read + 'a> Trans<'a, T> { + fn get_ref(&self) -> &T { + match *self { + Trans::Port(ref t) => &*t, + Trans::Buf(ref buf) => buf.get_ref() + } + } +} + impl<'a, T: Read + 'a> Read for Trans<'a, T> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match *self { diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -62,12 +71,27 @@ impl<'a, T: Read> Decoder<'a, T> { fn h1(decoder: &'a mut h1::Decoder, transport: Trans<'a, T>) -> Decoder<'a, T> { Decoder(DecoderImpl::H1(decoder, transport)) } + + /// Get a reference to the transport. + pub fn get_ref(&self) -> &T { + match self.0 { + DecoderImpl::H1(_, ref transport) => transport.get_ref() + } + } } impl<'a, T: Transport> Encoder<'a, T> { fn h1(encoder: &'a mut h1::Encoder, transport: &'a mut T) -> Encoder<'a, T> { Encoder(EncoderImpl::H1(encoder, transport)) } + + + /// Get a reference to the transport. + pub fn get_ref(&self) -> &T { + match self.0 { + EncoderImpl::H1(_, ref transport) => &*transport + } + } } impl<'a, T: Read> Read for Decoder<'a, T> { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -53,11 +53,6 @@ pub enum Blocked { Write, } -impl Transport for HttpStream { - fn take_socket_error(&mut self) -> io::Result<()> { - self.0.take_socket_error() - } -} /// Accepts sockets asynchronously. pub trait Accept: Evented { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -73,6 +68,12 @@ pub trait Accept: Evented { #[derive(Debug)] pub struct HttpStream(pub TcpStream); +impl Transport for HttpStream { + fn take_socket_error(&mut self) -> io::Result<()> { + self.0.take_socket_error() + } +} + impl Read for HttpStream { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -2,7 +2,6 @@ //! //! These are requests that a `hyper::Server` receives, and include its method, //! target URI, headers, and message body. -//use std::net::SocketAddr; use version::HttpVersion; use method::Method; diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -16,7 +15,6 @@ pub fn new(incoming: RequestHead) -> Request { debug!("{:#?}", headers); Request { - //remote_addr: addr, method: method, uri: uri, headers: headers,
diff --git a/src/client/pool.rs /dev/null --- a/src/client/pool.rs +++ /dev/null @@ -1,291 +0,0 @@ -//! Client Connection Pooling -use std::borrow::ToOwned; -use std::collections::HashMap; -use std::io::{self, Read, Write}; -use std::net::{SocketAddr, Shutdown}; -use std::sync::{Arc, Mutex}; - -use std::time::Duration; - -use net::{NetworkConnector, NetworkStream, DefaultConnector}; - -/// The `NetworkConnector` that behaves as a connection pool used by hyper's `Client`. -pub struct Pool<C: NetworkConnector> { - connector: C, - inner: Arc<Mutex<PoolImpl<<C as NetworkConnector>::Stream>>> -} - -/// Config options for the `Pool`. -#[derive(Debug)] -pub struct Config { - /// The maximum idle connections *per host*. - pub max_idle: usize, -} - -impl Default for Config { - #[inline] - fn default() -> Config { - Config { - max_idle: 5, - } - } -} - -#[derive(Debug)] -struct PoolImpl<S> { - conns: HashMap<Key, Vec<PooledStreamInner<S>>>, - config: Config, -} - -type Key = (String, u16, Scheme); - -fn key<T: Into<Scheme>>(host: &str, port: u16, scheme: T) -> Key { - (host.to_owned(), port, scheme.into()) -} - -#[derive(Clone, PartialEq, Eq, Debug, Hash)] -enum Scheme { - Http, - Https, - Other(String) -} - -impl<'a> From<&'a str> for Scheme { - fn from(s: &'a str) -> Scheme { - match s { - "http" => Scheme::Http, - "https" => Scheme::Https, - s => Scheme::Other(String::from(s)) - } - } -} - -impl Pool<DefaultConnector> { - /// Creates a `Pool` with a `DefaultConnector`. - #[inline] - pub fn new(config: Config) -> Pool<DefaultConnector> { - Pool::with_connector(config, DefaultConnector::default()) - } -} - -impl<C: NetworkConnector> Pool<C> { - /// Creates a `Pool` with a specified `NetworkConnector`. - #[inline] - pub fn with_connector(config: Config, connector: C) -> Pool<C> { - Pool { - connector: connector, - inner: Arc::new(Mutex::new(PoolImpl { - conns: HashMap::new(), - config: config, - })) - } - } - - /// Clear all idle connections from the Pool, closing them. - #[inline] - pub fn clear_idle(&mut self) { - self.inner.lock().unwrap().conns.clear(); - } -} - -impl<S> PoolImpl<S> { - fn reuse(&mut self, key: Key, conn: PooledStreamInner<S>) { - trace!("reuse {:?}", key); - let conns = self.conns.entry(key).or_insert(vec![]); - if conns.len() < self.config.max_idle { - conns.push(conn); - } - } -} - -impl<C: NetworkConnector<Stream=S>, S: NetworkStream + Send> NetworkConnector for Pool<C> { - type Stream = PooledStream<S>; - fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<PooledStream<S>> { - let key = key(host, port, scheme); - - let inner = { - // keep the mutex locked only in this block - let mut locked = self.inner.lock().unwrap(); - let mut should_remove = false; - let inner = locked.conns.get_mut(&key).map(|vec| { - trace!("Pool had connection, using"); - should_remove = vec.len() == 1; - vec.pop().unwrap() - }); - if should_remove { - locked.conns.remove(&key); - } - inner - }; - - let inner = match inner { - Some(inner) => inner, - None => PooledStreamInner { - key: key.clone(), - stream: try!(self.connector.connect(host, port, scheme)), - previous_response_expected_no_content: false, - } - - }; - Ok(PooledStream { - inner: Some(inner), - is_closed: false, - pool: self.inner.clone(), - }) - } -} - -/// A Stream that will try to be returned to the Pool when dropped. -#[derive(Debug)] -pub struct PooledStream<S> { - inner: Option<PooledStreamInner<S>>, - is_closed: bool, - pool: Arc<Mutex<PoolImpl<S>>>, -} - -impl<S: NetworkStream> PooledStream<S> { - /// Take the wrapped stream out of the pool completely. - pub fn into_inner(mut self) -> S { - self.inner.take().expect("PooledStream lost its inner stream").stream - } -} - -#[derive(Debug)] -struct PooledStreamInner<S> { - key: Key, - stream: S, - previous_response_expected_no_content: bool, -} - -impl<S: NetworkStream> Read for PooledStream<S> { - #[inline] - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - match self.inner.as_mut().unwrap().stream.read(buf) { - Ok(0) => { - // if the wrapped stream returns EOF (Ok(0)), that means the - // server has closed the stream. we must be sure this stream - // is dropped and not put back into the pool. - self.is_closed = true; - Ok(0) - }, - r => r - } - } -} - -impl<S: NetworkStream> Write for PooledStream<S> { - #[inline] - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.inner.as_mut().unwrap().stream.write(buf) - } - - #[inline] - fn flush(&mut self) -> io::Result<()> { - self.inner.as_mut().unwrap().stream.flush() - } -} - -impl<S: NetworkStream> NetworkStream for PooledStream<S> { - #[inline] - fn peer_addr(&mut self) -> io::Result<SocketAddr> { - self.inner.as_mut().unwrap().stream.peer_addr() - } - - #[inline] - fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.inner.as_ref().unwrap().stream.set_read_timeout(dur) - } - - #[inline] - fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.inner.as_ref().unwrap().stream.set_write_timeout(dur) - } - - #[inline] - fn close(&mut self, how: Shutdown) -> io::Result<()> { - self.is_closed = true; - self.inner.as_mut().unwrap().stream.close(how) - } - - #[inline] - fn set_previous_response_expected_no_content(&mut self, expected: bool) { - trace!("set_previous_response_expected_no_content {}", expected); - self.inner.as_mut().unwrap().previous_response_expected_no_content = expected; - } - - #[inline] - fn previous_response_expected_no_content(&self) -> bool { - let answer = self.inner.as_ref().unwrap().previous_response_expected_no_content; - trace!("previous_response_expected_no_content {}", answer); - answer - } -} - -impl<S> Drop for PooledStream<S> { - fn drop(&mut self) { - trace!("PooledStream.drop, is_closed={}", self.is_closed); - if !self.is_closed { - self.inner.take().map(|inner| { - if let Ok(mut pool) = self.pool.lock() { - pool.reuse(inner.key.clone(), inner); - } - // else poisoned, give up - }); - } - } -} - -#[cfg(test)] -mod tests { - use std::net::Shutdown; - use std::io::Read; - use mock::{MockConnector}; - use net::{NetworkConnector, NetworkStream}; - - use super::{Pool, key}; - - macro_rules! mocked { - () => ({ - Pool::with_connector(Default::default(), MockConnector) - }) - } - - #[test] - fn test_connect_and_drop() { - let pool = mocked!(); - let key = key("127.0.0.1", 3000, "http"); - pool.connect("127.0.0.1", 3000, "http").unwrap(); - { - let locked = pool.inner.lock().unwrap(); - assert_eq!(locked.conns.len(), 1); - assert_eq!(locked.conns.get(&key).unwrap().len(), 1); - } - pool.connect("127.0.0.1", 3000, "http").unwrap(); //reused - { - let locked = pool.inner.lock().unwrap(); - assert_eq!(locked.conns.len(), 1); - assert_eq!(locked.conns.get(&key).unwrap().len(), 1); - } - } - - #[test] - fn test_closed() { - let pool = mocked!(); - let mut stream = pool.connect("127.0.0.1", 3000, "http").unwrap(); - stream.close(Shutdown::Both).unwrap(); - drop(stream); - let locked = pool.inner.lock().unwrap(); - assert_eq!(locked.conns.len(), 0); - } - - #[test] - fn test_eof_closes() { - let pool = mocked!(); - - let mut stream = pool.connect("127.0.0.1", 3000, "http").unwrap(); - assert_eq!(stream.read(&mut [0]).unwrap(), 0); - drop(stream); - let locked = pool.inner.lock().unwrap(); - assert_eq!(locked.conns.len(), 0); - } -}
Remote Address not set in Request The remote_addr member of hyper::server::Request is commented out and not yet set on each request. Presumably https://github.com/hyperium/hyper/blob/master/src/server/request.rs#L19 is commented out as a placeholder to be done for 0.10. Just making an issue so its not forgotten :+1:
2016-06-14T15:04:58Z
0.9
220d09fc3a68cdd9a10589b2b454b54312518bb3
hyperium/hyper
778
hyperium__hyper-778
[ "395" ]
1ec56fe6b68ecf74213cf7e285f80c3a4ee70ce9
diff --git a/.travis.yml b/.travis.yml --- a/.travis.yml +++ b/.travis.yml @@ -3,6 +3,8 @@ matrix: fast_finish: true include: - os: osx + rust: stable + env: FEATURES="--no-default-features --features security-framework" - rust: nightly env: FEATURES="--features nightly" - rust: beta diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -16,13 +16,15 @@ httparse = "1.0" language-tags = "0.2" log = "0.3" mime = "0.2" -num_cpus = "0.2" +rotor = "0.6" rustc-serialize = "0.3" +spmc = "0.2" time = "0.1" traitobject = "0.0.1" typeable = "0.1" unicase = "1.0" url = "1.0" +vecio = "0.1" [dependencies.cookie] version = "0.2" diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -40,16 +42,13 @@ optional = true version = "0.1.4" optional = true -[dependencies.solicit] -version = "0.4" -default-features = false - [dependencies.serde] version = "0.7" optional = true [dev-dependencies] env_logger = "0.3" +num_cpus = "0.2" [features] default = ["ssl"] diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -10,12 +10,12 @@ A Modern HTTP library for Rust. ### Documentation -- [Stable](http://hyperium.github.io/hyper) +- [Released](http://hyperium.github.io/hyper) - [Master](http://hyperium.github.io/hyper/master) ## Overview -Hyper is a fast, modern HTTP implementation written in and for Rust. It +hyper is a fast, modern HTTP implementation written in and for Rust. It is a low-level typesafe abstraction over raw HTTP, providing an elegant layer over "stringly-typed" HTTP. diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -23,53 +23,3 @@ Hyper offers both an HTTP client and server which can be used to drive complex web applications written entirely in Rust. The documentation is located at [http://hyperium.github.io/hyper](http://hyperium.github.io/hyper). - -## Example - -### Hello World Server: - -```rust -extern crate hyper; - -use hyper::Server; -use hyper::server::Request; -use hyper::server::Response; - -fn hello(_: Request, res: Response) { - res.send(b"Hello World!").unwrap(); -} - -fn main() { - Server::http("127.0.0.1:3000").unwrap() - .handle(hello).unwrap(); -} -``` - -### Client: - -```rust -extern crate hyper; - -use std::io::Read; - -use hyper::Client; -use hyper::header::Connection; - -fn main() { - // Create a client. - let client = Client::new(); - - // Creating an outgoing request. - let mut res = client.get("http://rust-lang.org/") - // set a header - .header(Connection::close()) - // let 'er go! - .send().unwrap(); - - // Read the Response. - let mut body = String::new(); - res.read_to_string(&mut body).unwrap(); - - println!("Response: {}", body); -} -``` diff --git a/examples/client.rs b/examples/client.rs --- a/examples/client.rs +++ b/examples/client.rs @@ -5,9 +5,61 @@ extern crate env_logger; use std::env; use std::io; +use std::sync::mpsc; +use std::time::Duration; -use hyper::Client; +use hyper::client::{Client, Request, Response, DefaultTransport as HttpStream}; use hyper::header::Connection; +use hyper::{Decoder, Encoder, Next}; + +#[derive(Debug)] +struct Dump(mpsc::Sender<()>); + +impl Drop for Dump { + fn drop(&mut self) { + let _ = self.0.send(()); + } +} + +fn read() -> Next { + Next::read().timeout(Duration::from_secs(10)) +} + +impl hyper::client::Handler<HttpStream> for Dump { + fn on_request(&mut self, req: &mut Request) -> Next { + req.headers_mut().set(Connection::close()); + read() + } + + fn on_request_writable(&mut self, _encoder: &mut Encoder<HttpStream>) -> Next { + read() + } + + fn on_response(&mut self, res: Response) -> Next { + println!("Response: {}", res.status()); + println!("Headers:\n{}", res.headers()); + read() + } + + fn on_response_readable(&mut self, decoder: &mut Decoder<HttpStream>) -> Next { + match io::copy(decoder, &mut io::stdout()) { + Ok(0) => Next::end(), + Ok(_) => read(), + Err(e) => match e.kind() { + io::ErrorKind::WouldBlock => Next::read(), + _ => { + println!("ERROR: {}", e); + Next::end() + } + } + } + } + + fn on_error(&mut self, err: hyper::Error) -> Next { + println!("ERROR: {}", err); + Next::remove() + } +} fn main() { env_logger::init().unwrap(); diff --git a/examples/client.rs b/examples/client.rs --- a/examples/client.rs +++ b/examples/client.rs @@ -20,26 +72,11 @@ fn main() { } }; - let client = match env::var("HTTP_PROXY") { - Ok(mut proxy) => { - // parse the proxy, message if it doesn't make sense - let mut port = 80; - if let Some(colon) = proxy.rfind(':') { - port = proxy[colon + 1..].parse().unwrap_or_else(|e| { - panic!("HTTP_PROXY is malformed: {:?}, port parse error: {}", proxy, e); - }); - proxy.truncate(colon); - } - Client::with_http_proxy(proxy, port) - }, - _ => Client::new() - }; - - let mut res = client.get(&*url) - .header(Connection::close()) - .send().unwrap(); + let (tx, rx) = mpsc::channel(); + let client = Client::new().expect("Failed to create a Client"); + client.request(url.parse().unwrap(), Dump(tx)).unwrap(); - println!("Response: {}", res.status); - println!("Headers:\n{}", res.headers); - io::copy(&mut res, &mut io::stdout()).unwrap(); + // wait till done + let _ = rx.recv(); + client.close(); } diff --git a/examples/client_http2.rs /dev/null --- a/examples/client_http2.rs +++ /dev/null @@ -1,34 +0,0 @@ -#![deny(warnings)] -extern crate hyper; - -extern crate env_logger; - -use std::env; -use std::io; - -use hyper::Client; -use hyper::header::Connection; -use hyper::http::h2; - -fn main() { - env_logger::init().unwrap(); - - let url = match env::args().nth(1) { - Some(url) => url, - None => { - println!("Usage: client <url>"); - return; - } - }; - - let client = Client::with_protocol(h2::new_protocol()); - - // `Connection: Close` is not a valid header for HTTP/2, but the client handles it gracefully. - let mut res = client.get(&*url) - .header(Connection::close()) - .send().unwrap(); - - println!("Response: {}", res.status); - println!("Headers:\n{}", res.headers); - io::copy(&mut res, &mut io::stdout()).unwrap(); -} diff --git a/examples/headers.rs /dev/null --- a/examples/headers.rs +++ /dev/null @@ -1,16 +0,0 @@ -#![deny(warnings)] - -#[macro_use] -// TODO: only import header!, blocked by https://github.com/rust-lang/rust/issues/25003 -extern crate hyper; - -#[cfg(feature = "serde-serialization")] -extern crate serde; - -// A header in the form of `X-Foo: some random string` -header! { - (Foo, "X-Foo") => [String] -} - -fn main() { -} diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -1,18 +1,53 @@ #![deny(warnings)] extern crate hyper; extern crate env_logger; +extern crate num_cpus; -use hyper::server::{Request, Response}; +use std::io::Write; + +use hyper::{Decoder, Encoder, Next}; +use hyper::net::{HttpStream, HttpListener}; +use hyper::server::{Server, Handler, Request, Response}; static PHRASE: &'static [u8] = b"Hello World!"; -fn hello(_: Request, res: Response) { - res.send(PHRASE).unwrap(); +struct Hello; + +impl Handler<HttpStream> for Hello { + fn on_request(&mut self, _: Request) -> Next { + Next::write() + } + fn on_request_readable(&mut self, _: &mut Decoder<HttpStream>) -> Next { + Next::write() + } + fn on_response(&mut self, response: &mut Response) -> Next { + use hyper::header::ContentLength; + response.headers_mut().set(ContentLength(PHRASE.len() as u64)); + Next::write() + } + fn on_response_writable(&mut self, encoder: &mut Encoder<HttpStream>) -> Next { + let n = encoder.write(PHRASE).unwrap(); + debug_assert_eq!(n, PHRASE.len()); + Next::end() + } } fn main() { env_logger::init().unwrap(); - let _listening = hyper::Server::http("127.0.0.1:3000").unwrap() - .handle(hello); + + let listener = HttpListener::bind(&"127.0.0.1:3000".parse().unwrap()).unwrap(); + let mut handles = Vec::new(); + + for _ in 0..num_cpus::get() { + let listener = listener.try_clone().unwrap(); + handles.push(::std::thread::spawn(move || { + Server::new(listener) + .handle(|_| Hello).unwrap() + })); + } println!("Listening on http://127.0.0.1:3000"); + + for handle in handles { + handle.join().unwrap(); + } } diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -1,47 +1,171 @@ #![deny(warnings)] extern crate hyper; extern crate env_logger; +#[macro_use] +extern crate log; -use std::io::copy; +use std::io::{self, Read, Write}; -use hyper::{Get, Post}; -use hyper::server::{Server, Request, Response}; -use hyper::uri::RequestUri::AbsolutePath; +use hyper::{Get, Post, StatusCode, RequestUri, Decoder, Encoder, Next}; +use hyper::header::ContentLength; +use hyper::net::HttpStream; +use hyper::server::{Server, Handler, Request, Response}; -macro_rules! try_return( - ($e:expr) => {{ - match $e { - Ok(v) => v, - Err(e) => { println!("Error: {}", e); return; } +struct Echo { + buf: Vec<u8>, + read_pos: usize, + write_pos: usize, + eof: bool, + route: Route, +} + +enum Route { + NotFound, + Index, + Echo(Body), +} + +#[derive(Clone, Copy)] +enum Body { + Len(u64), + Chunked +} + +static INDEX: &'static [u8] = b"Try POST /echo"; + +impl Echo { + fn new() -> Echo { + Echo { + buf: vec![0; 4096], + read_pos: 0, + write_pos: 0, + eof: false, + route: Route::NotFound, } - }} -); - -fn echo(mut req: Request, mut res: Response) { - match req.uri { - AbsolutePath(ref path) => match (&req.method, &path[..]) { - (&Get, "/") | (&Get, "/echo") => { - try_return!(res.send(b"Try POST /echo")); - return; + } +} + +impl Handler<HttpStream> for Echo { + fn on_request(&mut self, req: Request) -> Next { + match *req.uri() { + RequestUri::AbsolutePath(ref path) => match (req.method(), &path[..]) { + (&Get, "/") | (&Get, "/echo") => { + info!("GET Index"); + self.route = Route::Index; + Next::write() + } + (&Post, "/echo") => { + info!("POST Echo"); + let mut is_more = true; + self.route = if let Some(len) = req.headers().get::<ContentLength>() { + is_more = **len > 0; + Route::Echo(Body::Len(**len)) + } else { + Route::Echo(Body::Chunked) + }; + if is_more { + Next::read_and_write() + } else { + Next::write() + } + } + _ => Next::write(), }, - (&Post, "/echo") => (), // fall through, fighting mutable borrows - _ => { - *res.status_mut() = hyper::NotFound; - return; + _ => Next::write() + } + } + fn on_request_readable(&mut self, transport: &mut Decoder<HttpStream>) -> Next { + match self.route { + Route::Echo(ref body) => { + if self.read_pos < self.buf.len() { + match transport.read(&mut self.buf[self.read_pos..]) { + Ok(0) => { + debug!("Read 0, eof"); + self.eof = true; + Next::write() + }, + Ok(n) => { + self.read_pos += n; + match *body { + Body::Len(max) if max <= self.read_pos as u64 => { + self.eof = true; + Next::write() + }, + _ => Next::read_and_write() + } + } + Err(e) => match e.kind() { + io::ErrorKind::WouldBlock => Next::read_and_write(), + _ => { + println!("read error {:?}", e); + Next::end() + } + } + } + } else { + Next::write() + } } - }, - _ => { - return; + _ => unreachable!() } - }; + } - let mut res = try_return!(res.start()); - try_return!(copy(&mut req, &mut res)); + fn on_response(&mut self, res: &mut Response) -> Next { + match self.route { + Route::NotFound => { + res.set_status(StatusCode::NotFound); + Next::end() + } + Route::Index => { + res.headers_mut().set(ContentLength(INDEX.len() as u64)); + Next::write() + } + Route::Echo(body) => { + if let Body::Len(len) = body { + res.headers_mut().set(ContentLength(len)); + } + Next::read_and_write() + } + } + } + + fn on_response_writable(&mut self, transport: &mut Encoder<HttpStream>) -> Next { + match self.route { + Route::Index => { + transport.write(INDEX).unwrap(); + Next::end() + } + Route::Echo(..) => { + if self.write_pos < self.read_pos { + match transport.write(&self.buf[self.write_pos..self.read_pos]) { + Ok(0) => panic!("write ZERO"), + Ok(n) => { + self.write_pos += n; + Next::write() + } + Err(e) => match e.kind() { + io::ErrorKind::WouldBlock => Next::write(), + _ => { + println!("write error {:?}", e); + Next::end() + } + } + } + } else if !self.eof { + Next::read() + } else { + Next::end() + } + } + _ => unreachable!() + } + } } fn main() { env_logger::init().unwrap(); - let server = Server::http("127.0.0.1:1337").unwrap(); - let _guard = server.handle(echo); - println!("Listening on http://127.0.0.1:1337"); + let server = Server::http(&"127.0.0.1:1337".parse().unwrap()).unwrap(); + let (listening, server) = server.handle(|_| Echo::new()).unwrap(); + println!("Listening on http://{}", listening); + server.run(); } diff --git /dev/null b/examples/sync.rs new file mode 100644 --- /dev/null +++ b/examples/sync.rs @@ -0,0 +1,278 @@ +extern crate hyper; +extern crate env_logger; +extern crate time; + +use std::io::{self, Read, Write}; +use std::marker::PhantomData; +use std::thread; +use std::sync::{Arc, mpsc}; + +pub struct Server { + listening: hyper::server::Listening, +} + +pub struct Request<'a> { + #[allow(dead_code)] + inner: hyper::server::Request, + tx: &'a mpsc::Sender<Action>, + rx: &'a mpsc::Receiver<io::Result<usize>>, + ctrl: &'a hyper::Control, +} + +impl<'a> Request<'a> { + fn new(inner: hyper::server::Request, tx: &'a mpsc::Sender<Action>, rx: &'a mpsc::Receiver<io::Result<usize>>, ctrl: &'a hyper::Control) -> Request<'a> { + Request { + inner: inner, + tx: tx, + rx: rx, + ctrl: ctrl, + } + } +} + +impl<'a> io::Read for Request<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.tx.send(Action::Read(buf.as_mut_ptr(), buf.len())).unwrap(); + self.ctrl.ready(hyper::Next::read()).unwrap(); + self.rx.recv().unwrap() + } +} + +pub enum Fresh {} +pub enum Streaming {} + +pub struct Response<'a, W = Fresh> { + status: hyper::StatusCode, + headers: hyper::Headers, + version: hyper::HttpVersion, + tx: &'a mpsc::Sender<Action>, + rx: &'a mpsc::Receiver<io::Result<usize>>, + ctrl: &'a hyper::Control, + _marker: PhantomData<W>, +} + +impl<'a> Response<'a, Fresh> { + fn new(tx: &'a mpsc::Sender<Action>, rx: &'a mpsc::Receiver<io::Result<usize>>, ctrl: &'a hyper::Control) -> Response<'a, Fresh> { + Response { + status: hyper::Ok, + headers: hyper::Headers::new(), + version: hyper::HttpVersion::Http11, + tx: tx, + rx: rx, + ctrl: ctrl, + _marker: PhantomData, + } + } + + pub fn start(self) -> io::Result<Response<'a, Streaming>> { + self.tx.send(Action::Respond(self.version.clone(), self.status.clone(), self.headers.clone())).unwrap(); + self.ctrl.ready(hyper::Next::write()).unwrap(); + let res = self.rx.recv().unwrap(); + res.map(move |_| Response { + status: self.status, + headers: self.headers, + version: self.version, + tx: self.tx, + rx: self.rx, + ctrl: self.ctrl, + _marker: PhantomData, + }) + } + + pub fn send(mut self, msg: &[u8]) -> io::Result<()> { + self.headers.set(hyper::header::ContentLength(msg.len() as u64)); + self.start().and_then(|mut res| res.write_all(msg)).map(|_| ()) + } +} + +impl<'a> Write for Response<'a, Streaming> { + fn write(&mut self, msg: &[u8]) -> io::Result<usize> { + self.tx.send(Action::Write(msg.as_ptr(), msg.len())).unwrap(); + self.ctrl.ready(hyper::Next::write()).unwrap(); + let res = self.rx.recv().unwrap(); + res + } + + fn flush(&mut self) -> io::Result<()> { + panic!("Response.flush() not impemented") + } +} + +struct SynchronousHandler { + req_tx: mpsc::Sender<hyper::server::Request>, + tx: mpsc::Sender<io::Result<usize>>, + rx: mpsc::Receiver<Action>, + reading: Option<(*mut u8, usize)>, + writing: Option<(*const u8, usize)>, + respond: Option<(hyper::HttpVersion, hyper::StatusCode, hyper::Headers)> +} + +unsafe impl Send for SynchronousHandler {} + +impl SynchronousHandler { + fn next(&mut self) -> hyper::Next { + match self.rx.try_recv() { + Ok(Action::Read(ptr, len)) => { + self.reading = Some((ptr, len)); + hyper::Next::read() + }, + Ok(Action::Respond(ver, status, headers)) => { + self.respond = Some((ver, status, headers)); + hyper::Next::write() + }, + Ok(Action::Write(ptr, len)) => { + self.writing = Some((ptr, len)); + hyper::Next::write() + } + Err(mpsc::TryRecvError::Empty) => { + // we're too fast, the other thread hasn't had a chance to respond + hyper::Next::wait() + } + Err(mpsc::TryRecvError::Disconnected) => { + // they dropped it + // TODO: should finish up sending response, whatever it was + hyper::Next::end() + } + } + } + + fn reading(&mut self) -> Option<(*mut u8, usize)> { + self.reading.take().or_else(|| { + match self.rx.try_recv() { + Ok(Action::Read(ptr, len)) => { + Some((ptr, len)) + }, + _ => None + } + }) + } + + fn writing(&mut self) -> Option<(*const u8, usize)> { + self.writing.take().or_else(|| { + match self.rx.try_recv() { + Ok(Action::Write(ptr, len)) => { + Some((ptr, len)) + }, + _ => None + } + }) + } + fn respond(&mut self) -> Option<(hyper::HttpVersion, hyper::StatusCode, hyper::Headers)> { + self.respond.take().or_else(|| { + match self.rx.try_recv() { + Ok(Action::Respond(ver, status, headers)) => { + Some((ver, status, headers)) + }, + _ => None + } + }) + } +} + +impl hyper::server::Handler<hyper::net::HttpStream> for SynchronousHandler { + fn on_request(&mut self, req: hyper::server::Request) -> hyper::Next { + if let Err(_) = self.req_tx.send(req) { + return hyper::Next::end(); + } + + self.next() + } + + fn on_request_readable(&mut self, decoder: &mut hyper::Decoder<hyper::net::HttpStream>) -> hyper::Next { + if let Some(raw) = self.reading() { + let slice = unsafe { ::std::slice::from_raw_parts_mut(raw.0, raw.1) }; + if self.tx.send(decoder.read(slice)).is_err() { + return hyper::Next::end(); + } + } + self.next() + } + + fn on_response(&mut self, req: &mut hyper::server::Response) -> hyper::Next { + use std::iter::Extend; + if let Some(head) = self.respond() { + req.set_status(head.1); + req.headers_mut().extend(head.2.iter()); + if self.tx.send(Ok(0)).is_err() { + return hyper::Next::end(); + } + } else { + // wtf happened? + panic!("no head to respond with"); + } + self.next() + } + + fn on_response_writable(&mut self, encoder: &mut hyper::Encoder<hyper::net::HttpStream>) -> hyper::Next { + if let Some(raw) = self.writing() { + let slice = unsafe { ::std::slice::from_raw_parts(raw.0, raw.1) }; + if self.tx.send(encoder.write(slice)).is_err() { + return hyper::Next::end(); + } + } + self.next() + } +} + +enum Action { + Read(*mut u8, usize), + Write(*const u8, usize), + Respond(hyper::HttpVersion, hyper::StatusCode, hyper::Headers), +} + +unsafe impl Send for Action {} + +trait Handler: Send + Sync + 'static { + fn handle(&self, req: Request, res: Response); +} + +impl<F> Handler for F where F: Fn(Request, Response) + Send + Sync + 'static { + fn handle(&self, req: Request, res: Response) { + (self)(req, res) + } +} + +impl Server { + fn handle<H: Handler>(addr: &str, handler: H) -> Server { + let handler = Arc::new(handler); + let (listening, server) = hyper::Server::http(&addr.parse().unwrap()).unwrap() + .handle(move |ctrl| { + let (req_tx, req_rx) = mpsc::channel(); + let (blocking_tx, blocking_rx) = mpsc::channel(); + let (async_tx, async_rx) = mpsc::channel(); + let handler = handler.clone(); + thread::Builder::new().name("handler-thread".into()).spawn(move || { + let req = Request::new(req_rx.recv().unwrap(), &blocking_tx, &async_rx, &ctrl); + let res = Response::new(&blocking_tx, &async_rx, &ctrl); + handler.handle(req, res); + }).unwrap(); + + SynchronousHandler { + req_tx: req_tx, + tx: async_tx, + rx: blocking_rx, + reading: None, + writing: None, + respond: None, + } + }).unwrap(); + thread::spawn(move || { + server.run(); + }); + Server { + listening: listening + } + } +} + +fn main() { + env_logger::init().unwrap(); + let s = Server::handle("127.0.0.1:0", |mut req: Request, res: Response| { + let mut body = [0; 256]; + let n = req.read(&mut body).unwrap(); + println!("!!!: received: {:?}", ::std::str::from_utf8(&body[..n]).unwrap()); + + res.send(b"Hello World!").unwrap(); + }); + println!("listening on {}", s.listening.addr()); +} diff --git /dev/null b/src/client/connect.rs new file mode 100644 --- /dev/null +++ b/src/client/connect.rs @@ -0,0 +1,219 @@ +use std::collections::hash_map::{HashMap, Entry}; +use std::hash::Hash; +use std::fmt; +use std::io; +use std::net::SocketAddr; + +use rotor::mio::tcp::TcpStream; +use url::Url; + +use net::{HttpStream, HttpsStream, Transport, SslClient}; +use super::dns::Dns; +use super::Registration; + +/// A connector creates a Transport to a remote address.. +pub trait Connect { + /// Type of Transport to create + type Output: Transport; + /// The key used to determine if an existing socket can be used. + type Key: Eq + Hash + Clone; + /// Returns the key based off the Url. + fn key(&self, &Url) -> Option<Self::Key>; + /// Connect to a remote address. + fn connect(&mut self, &Url) -> io::Result<Self::Key>; + /// Returns a connected socket and associated host. + fn connected(&mut self) -> Option<(Self::Key, io::Result<Self::Output>)>; + #[doc(hidden)] + fn register(&mut self, Registration); +} + +type Scheme = String; +type Port = u16; + +/// A connector for the `http` scheme. +pub struct HttpConnector { + dns: Option<Dns>, + threads: usize, + resolving: HashMap<String, Vec<(&'static str, String, u16)>>, +} + +impl HttpConnector { + /// Set the number of resolver threads. + /// + /// Default is 4. + pub fn threads(mut self, threads: usize) -> HttpConnector { + debug_assert!(self.dns.is_none(), "setting threads after Dns is created does nothing"); + self.threads = threads; + self + } +} + +impl Default for HttpConnector { + fn default() -> HttpConnector { + HttpConnector { + dns: None, + threads: 4, + resolving: HashMap::new(), + } + } +} + +impl fmt::Debug for HttpConnector { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("HttpConnector") + .field("threads", &self.threads) + .field("resolving", &self.resolving) + .finish() + } +} + +impl Connect for HttpConnector { + type Output = HttpStream; + type Key = (&'static str, String, u16); + + fn key(&self, url: &Url) -> Option<Self::Key> { + if url.scheme() == "http" { + Some(( + "http", + url.host_str().expect("http scheme must have host").to_owned(), + url.port().unwrap_or(80), + )) + } else { + None + } + } + + fn connect(&mut self, url: &Url) -> io::Result<Self::Key> { + debug!("Http::connect({:?})", url); + if let Some(key) = self.key(url) { + let host = url.host_str().expect("http scheme must have a host"); + self.dns.as_ref().expect("dns workers lost").resolve(host); + self.resolving.entry(host.to_owned()).or_insert(Vec::new()).push(key.clone()); + Ok(key) + } else { + Err(io::Error::new(io::ErrorKind::InvalidInput, "scheme must be http")) + } + } + + fn connected(&mut self) -> Option<(Self::Key, io::Result<HttpStream>)> { + let (host, addr) = match self.dns.as_ref().expect("dns workers lost").resolved() { + Ok(res) => res, + Err(_) => return None + }; + debug!("Http::resolved <- ({:?}, {:?})", host, addr); + match self.resolving.entry(host) { + Entry::Occupied(mut entry) => { + let resolved = entry.get_mut().remove(0); + if entry.get().is_empty() { + entry.remove(); + } + let port = resolved.2; + match addr { + Ok(addr) => { + Some((resolved, TcpStream::connect(&SocketAddr::new(addr, port)) + .map(HttpStream))) + }, + Err(e) => Some((resolved, Err(e))) + } + } + _ => { + trace!("^-- resolved but not in hashmap?"); + return None + } + } + } + + fn register(&mut self, reg: Registration) { + self.dns = Some(Dns::new(reg.notify, 4)); + } +} + +/// A connector that can protect HTTP streams using SSL. +#[derive(Debug, Default)] +pub struct HttpsConnector<S: SslClient> { + http: HttpConnector, + ssl: S +} + +impl<S: SslClient> HttpsConnector<S> { + /// Create a new connector using the provided SSL implementation. + pub fn new(s: S) -> HttpsConnector<S> { + HttpsConnector { + http: HttpConnector::default(), + ssl: s, + } + } +} + +impl<S: SslClient> Connect for HttpsConnector<S> { + type Output = HttpsStream<S::Stream>; + type Key = (&'static str, String, u16); + + fn key(&self, url: &Url) -> Option<Self::Key> { + let scheme = match url.scheme() { + "http" => "http", + "https" => "https", + _ => return None + }; + Some(( + scheme, + url.host_str().expect("http scheme must have host").to_owned(), + url.port_or_known_default().expect("http scheme must have a port"), + )) + } + + fn connect(&mut self, url: &Url) -> io::Result<Self::Key> { + debug!("Https::connect({:?})", url); + if let Some(key) = self.key(url) { + let host = url.host_str().expect("http scheme must have a host"); + self.http.dns.as_ref().expect("dns workers lost").resolve(host); + self.http.resolving.entry(host.to_owned()).or_insert(Vec::new()).push(key.clone()); + Ok(key) + } else { + Err(io::Error::new(io::ErrorKind::InvalidInput, "scheme must be http or https")) + } + } + + fn connected(&mut self) -> Option<(Self::Key, io::Result<Self::Output>)> { + self.http.connected().map(|(key, res)| { + let res = res.and_then(|http| { + if key.0 == "https" { + self.ssl.wrap_client(http, &key.1) + .map(HttpsStream::Https) + .map_err(|e| match e { + ::Error::Io(e) => e, + e => io::Error::new(io::ErrorKind::Other, e) + }) + } else { + Ok(HttpsStream::Http(http)) + } + }); + (key, res) + }) + } + + fn register(&mut self, reg: Registration) { + self.http.register(reg); + } +} + +#[cfg(not(any(feature = "openssl", feature = "security-framework")))] +#[doc(hidden)] +pub type DefaultConnector = HttpConnector; + +#[cfg(all(feature = "openssl", not(feature = "security-framework")))] +#[doc(hidden)] +pub type DefaultConnector = HttpsConnector<::net::Openssl>; + +#[cfg(feature = "security-framework")] +#[doc(hidden)] +pub type DefaultConnector = HttpsConnector<::net::SecureTransportClient>; + +#[doc(hidden)] +pub type DefaultTransport = <DefaultConnector as Connect>::Output; + +fn _assert_defaults() { + fn _assert<T, U>() where T: Connect<Output=U>, U: Transport {} + + _assert::<DefaultConnector, DefaultTransport>(); +} diff --git /dev/null b/src/client/dns.rs new file mode 100644 --- /dev/null +++ b/src/client/dns.rs @@ -0,0 +1,84 @@ +use std::io; +use std::net::{IpAddr, ToSocketAddrs}; +use std::thread; + +use ::spmc; + +use http::channel; + +pub struct Dns { + tx: spmc::Sender<String>, + rx: channel::Receiver<Answer>, +} + +pub type Answer = (String, io::Result<IpAddr>); + +impl Dns { + pub fn new(notify: (channel::Sender<Answer>, channel::Receiver<Answer>), threads: usize) -> Dns { + let (tx, rx) = spmc::channel(); + for _ in 0..threads { + work(rx.clone(), notify.0.clone()); + } + Dns { + tx: tx, + rx: notify.1, + } + } + + pub fn resolve<T: Into<String>>(&self, hostname: T) { + self.tx.send(hostname.into()).expect("Workers all died horribly"); + } + + pub fn resolved(&self) -> Result<Answer, channel::TryRecvError> { + self.rx.try_recv() + } +} + +fn work(rx: spmc::Receiver<String>, notify: channel::Sender<Answer>) { + thread::spawn(move || { + let mut worker = Worker::new(rx, notify); + let rx = worker.rx.as_ref().expect("Worker lost rx"); + let notify = worker.notify.as_ref().expect("Worker lost notify"); + while let Ok(host) = rx.recv() { + debug!("resolve {:?}", host); + let res = match (&*host, 80).to_socket_addrs().map(|mut i| i.next()) { + Ok(Some(addr)) => (host, Ok(addr.ip())), + Ok(None) => (host, Err(io::Error::new(io::ErrorKind::Other, "no addresses found"))), + Err(e) => (host, Err(e)) + }; + + if let Err(_) = notify.send(res) { + break; + } + } + worker.shutdown = true; + }); +} + +struct Worker { + rx: Option<spmc::Receiver<String>>, + notify: Option<channel::Sender<Answer>>, + shutdown: bool, +} + +impl Worker { + fn new(rx: spmc::Receiver<String>, notify: channel::Sender<Answer>) -> Worker { + Worker { + rx: Some(rx), + notify: Some(notify), + shutdown: false, + } + } +} + +impl Drop for Worker { + fn drop(&mut self) { + if !self.shutdown { + trace!("Worker.drop panicked, restarting"); + work(self.rx.take().expect("Worker lost rx"), + self.notify.take().expect("Worker lost notify")); + } else { + trace!("Worker.drop shutdown, closing"); + } + } +} diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -1,82 +1,57 @@ //! Client Responses -use std::io::{self, Read}; - -use url::Url; - use header; -use net::NetworkStream; -use http::{self, RawStatus, ResponseHead, HttpMessage}; -use http::h1::Http11Message; +//use net::NetworkStream; +use http::{self, RawStatus}; use status; use version; +pub fn new(incoming: http::ResponseHead) -> Response { + trace!("Response::new"); + let status = status::StatusCode::from_u16(incoming.subject.0); + debug!("version={:?}, status={:?}", incoming.version, status); + debug!("headers={:?}", incoming.headers); + + Response { + status: status, + version: incoming.version, + headers: incoming.headers, + status_raw: incoming.subject, + } + +} + /// A response for a client request to a remote server. #[derive(Debug)] pub struct Response { - /// The status from the server. - pub status: status::StatusCode, - /// The headers from the server. - pub headers: header::Headers, - /// The HTTP version of this response from the server. - pub version: version::HttpVersion, - /// The final URL of this response. - pub url: Url, + status: status::StatusCode, + headers: header::Headers, + version: version::HttpVersion, status_raw: RawStatus, - message: Box<HttpMessage>, } impl Response { + /// Get the headers from the server. + #[inline] + pub fn headers(&self) -> &header::Headers { &self.headers } - /// Creates a new response from a server. - pub fn new(url: Url, stream: Box<NetworkStream + Send>) -> ::Result<Response> { - trace!("Response::new"); - Response::with_message(url, Box::new(Http11Message::with_stream(stream))) - } - - /// Creates a new response received from the server on the given `HttpMessage`. - pub fn with_message(url: Url, mut message: Box<HttpMessage>) -> ::Result<Response> { - trace!("Response::with_message"); - let ResponseHead { headers, raw_status, version } = match message.get_incoming() { - Ok(head) => head, - Err(e) => { - let _ = message.close_connection(); - return Err(From::from(e)); - } - }; - let status = status::StatusCode::from_u16(raw_status.0); - debug!("version={:?}, status={:?}", version, status); - debug!("headers={:?}", headers); - - Ok(Response { - status: status, - version: version, - headers: headers, - url: url, - status_raw: raw_status, - message: message, - }) - } + /// Get the status from the server. + #[inline] + pub fn status(&self) -> &status::StatusCode { &self.status } /// Get the raw status code and reason. #[inline] - pub fn status_raw(&self) -> &RawStatus { - &self.status_raw - } -} + pub fn status_raw(&self) -> &RawStatus { &self.status_raw } -impl Read for Response { + /// Get the final URL of this response. #[inline] - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - match self.message.read(buf) { - Err(e) => { - let _ = self.message.close_connection(); - Err(e) - } - r => r - } - } + //pub fn url(&self) -> &Url { &self.url } + + /// Get the HTTP version of this response from the server. + #[inline] + pub fn version(&self) -> &version::HttpVersion { &self.version } } +/* impl Drop for Response { fn drop(&mut self) { // if not drained, theres old bits in the Reader. we can't reuse this, diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -7,7 +7,6 @@ use std::string::FromUtf8Error; use httparse; use url; -use solicit::http::HttpError as Http2Error; #[cfg(feature = "openssl")] use openssl::ssl::error::SslError; diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -18,10 +17,11 @@ use self::Error::{ Version, Header, Status, + Timeout, Io, Ssl, TooLarge, - Http2, + Incomplete, Utf8 }; diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -42,14 +42,16 @@ pub enum Error { Header, /// A message head is too large to be reasonable. TooLarge, + /// A message reached EOF before being a complete message. + Incomplete, /// An invalid `Status`, such as `1337 ELITE`. Status, + /// A timeout occurred waiting for an IO event. + Timeout, /// An `io::Error` that occurred while trying to read or write to a network stream. Io(IoError), /// An error from a SSL library. Ssl(Box<StdError + Send + Sync>), - /// An HTTP/2-specific error, coming from the `solicit` library. - Http2(Http2Error), /// Parsing a field as string failed Utf8(Utf8Error), diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -80,10 +82,11 @@ impl StdError for Error { Header => "Invalid Header provided", TooLarge => "Message head is too large", Status => "Invalid Status provided", + Incomplete => "Message is incomplete", + Timeout => "Timeout", Uri(ref e) => e.description(), Io(ref e) => e.description(), Ssl(ref e) => e.description(), - Http2(ref e) => e.description(), Utf8(ref e) => e.description(), Error::__Nonexhaustive(ref void) => match *void {} } diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -94,7 +97,6 @@ impl StdError for Error { Io(ref error) => Some(error), Ssl(ref error) => Some(&**error), Uri(ref error) => Some(error), - Http2(ref error) => Some(error), _ => None, } } diff --git a/src/header/common/access_control_allow_credentials.rs b/src/header/common/access_control_allow_credentials.rs --- a/src/header/common/access_control_allow_credentials.rs +++ b/src/header/common/access_control_allow_credentials.rs @@ -1,7 +1,7 @@ use std::fmt::{self, Display}; use std::str; use unicase::UniCase; -use header::{Header, HeaderFormat}; +use header::{Header}; /// `Access-Control-Allow-Credentials` header, part of /// [CORS](http://www.w3.org/TR/cors/#access-control-allow-headers-response-header) diff --git a/src/header/common/access_control_allow_credentials.rs b/src/header/common/access_control_allow_credentials.rs --- a/src/header/common/access_control_allow_credentials.rs +++ b/src/header/common/access_control_allow_credentials.rs @@ -62,9 +62,7 @@ impl Header for AccessControlAllowCredentials { } Err(::Error::Header) } -} -impl HeaderFormat for AccessControlAllowCredentials { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("true") } diff --git a/src/header/common/access_control_allow_origin.rs b/src/header/common/access_control_allow_origin.rs --- a/src/header/common/access_control_allow_origin.rs +++ b/src/header/common/access_control_allow_origin.rs @@ -1,6 +1,6 @@ use std::fmt::{self, Display}; -use header::{Header, HeaderFormat}; +use header::{Header}; /// The `Access-Control-Allow-Origin` response header, /// part of [CORS](http://www.w3.org/TR/cors/#access-control-allow-origin-response-header) diff --git a/src/header/common/access_control_allow_origin.rs b/src/header/common/access_control_allow_origin.rs --- a/src/header/common/access_control_allow_origin.rs +++ b/src/header/common/access_control_allow_origin.rs @@ -70,9 +70,7 @@ impl Header for AccessControlAllowOrigin { _ => AccessControlAllowOrigin::Value(try!(String::from_utf8(value.clone()))) }) } -} -impl HeaderFormat for AccessControlAllowOrigin { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { AccessControlAllowOrigin::Any => f.write_str("*"), diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -3,7 +3,7 @@ use std::fmt::{self, Display}; use std::str::{FromStr, from_utf8}; use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; -use header::{Header, HeaderFormat}; +use header::{Header}; /// `Authorization` header, defined in [RFC7235](https://tools.ietf.org/html/rfc7235#section-4.2) /// diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -97,9 +97,7 @@ impl<S: Scheme + Any> Header for Authorization<S> where <S as FromStr>::Err: 'st } } } -} -impl<S: Scheme + Any> HeaderFormat for Authorization<S> where <S as FromStr>::Err: 'static { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(scheme) = <S as Scheme>::scheme() { try!(write!(f, "{} ", scheme)) diff --git a/src/header/common/cache_control.rs b/src/header/common/cache_control.rs --- a/src/header/common/cache_control.rs +++ b/src/header/common/cache_control.rs @@ -1,6 +1,6 @@ use std::fmt; use std::str::FromStr; -use header::{Header, HeaderFormat}; +use header::Header; use header::parsing::{from_comma_delimited, fmt_comma_delimited}; /// `Cache-Control` header, defined in [RFC7234](https://tools.ietf.org/html/rfc7234#section-5.2) diff --git a/src/header/common/cache_control.rs b/src/header/common/cache_control.rs --- a/src/header/common/cache_control.rs +++ b/src/header/common/cache_control.rs @@ -62,9 +62,7 @@ impl Header for CacheControl { Err(::Error::Header) } } -} -impl HeaderFormat for CacheControl { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt_comma_delimited(f, &self[..]) } diff --git a/src/header/common/content_disposition.rs b/src/header/common/content_disposition.rs --- a/src/header/common/content_disposition.rs +++ b/src/header/common/content_disposition.rs @@ -11,7 +11,7 @@ use std::fmt; use unicase::UniCase; use url::percent_encoding; -use header::{Header, HeaderFormat, parsing}; +use header::{Header, parsing}; use header::parsing::{parse_extended_value, HTTP_VALUE}; use header::shared::Charset; diff --git a/src/header/common/content_disposition.rs b/src/header/common/content_disposition.rs --- a/src/header/common/content_disposition.rs +++ b/src/header/common/content_disposition.rs @@ -144,9 +144,7 @@ impl Header for ContentDisposition { Ok(cd) }) } -} -impl HeaderFormat for ContentDisposition { #[inline] fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self, f) diff --git a/src/header/common/content_length.rs b/src/header/common/content_length.rs --- a/src/header/common/content_length.rs +++ b/src/header/common/content_length.rs @@ -1,6 +1,6 @@ use std::fmt; -use header::{HeaderFormat, Header, parsing}; +use header::{Header, parsing}; /// `Content-Length` header, defined in /// [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2) diff --git a/src/header/common/content_length.rs b/src/header/common/content_length.rs --- a/src/header/common/content_length.rs +++ b/src/header/common/content_length.rs @@ -55,9 +55,7 @@ impl Header for ContentLength { .unwrap_or(Err(::Error::Header)) .map(ContentLength) } -} -impl HeaderFormat for ContentLength { #[inline] fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -1,4 +1,4 @@ -use header::{Header, HeaderFormat, CookiePair, CookieJar}; +use header::{Header, CookiePair, CookieJar}; use std::fmt::{self, Display}; use std::str::from_utf8; diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -61,9 +61,7 @@ impl Header for Cookie { Err(::Error::Header) } } -} -impl HeaderFormat for Cookie { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { let cookies = &self.0; for (i, cookie) in cookies.iter().enumerate() { diff --git a/src/header/common/expect.rs b/src/header/common/expect.rs --- a/src/header/common/expect.rs +++ b/src/header/common/expect.rs @@ -3,7 +3,7 @@ use std::str; use unicase::UniCase; -use header::{Header, HeaderFormat}; +use header::{Header}; /// The `Expect` header. /// diff --git a/src/header/common/expect.rs b/src/header/common/expect.rs --- a/src/header/common/expect.rs +++ b/src/header/common/expect.rs @@ -53,9 +53,7 @@ impl Header for Expect { Err(::Error::Header) } } -} -impl HeaderFormat for Expect { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("100-continue") } diff --git a/src/header/common/host.rs b/src/header/common/host.rs --- a/src/header/common/host.rs +++ b/src/header/common/host.rs @@ -1,4 +1,4 @@ -use header::{Header, HeaderFormat}; +use header::{Header}; use std::fmt; use header::parsing::from_one_raw_str; diff --git a/src/header/common/host.rs b/src/header/common/host.rs --- a/src/header/common/host.rs +++ b/src/header/common/host.rs @@ -52,9 +52,7 @@ impl Header for Host { // https://github.com/servo/rust-url/issues/42 let idx = { let slice = &s[..]; - let mut chars = slice.chars(); - chars.next(); - if chars.next().unwrap() == '[' { + if slice.starts_with('[') { match slice.rfind(']') { Some(idx) => { if slice.len() > idx + 2 { diff --git a/src/header/common/host.rs b/src/header/common/host.rs --- a/src/header/common/host.rs +++ b/src/header/common/host.rs @@ -86,9 +84,7 @@ impl Header for Host { }) }) } -} -impl HeaderFormat for Host { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.port { None | Some(80) | Some(443) => f.write_str(&self.hostname[..]), diff --git a/src/header/common/if_range.rs b/src/header/common/if_range.rs --- a/src/header/common/if_range.rs +++ b/src/header/common/if_range.rs @@ -1,5 +1,5 @@ use std::fmt::{self, Display}; -use header::{self, Header, HeaderFormat, EntityTag, HttpDate}; +use header::{self, Header, EntityTag, HttpDate}; /// `If-Range` header, defined in [RFC7233](http://tools.ietf.org/html/rfc7233#section-3.2) /// diff --git a/src/header/common/if_range.rs b/src/header/common/if_range.rs --- a/src/header/common/if_range.rs +++ b/src/header/common/if_range.rs @@ -59,18 +59,16 @@ impl Header for IfRange { } fn parse_header(raw: &[Vec<u8>]) -> ::Result<IfRange> { let etag: ::Result<EntityTag> = header::parsing::from_one_raw_str(raw); - if etag.is_ok() { - return Ok(IfRange::EntityTag(etag.unwrap())); + if let Ok(etag) = etag { + return Ok(IfRange::EntityTag(etag)); } let date: ::Result<HttpDate> = header::parsing::from_one_raw_str(raw); - if date.is_ok() { - return Ok(IfRange::Date(date.unwrap())); + if let Ok(date) = date { + return Ok(IfRange::Date(date)); } Err(::Error::Header) } -} -impl HeaderFormat for IfRange { fn fmt_header(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { IfRange::EntityTag(ref x) => Display::fmt(x, f), diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -79,7 +79,7 @@ macro_rules! bench_header( #[bench] fn bench_format(b: &mut Bencher) { let val: $ty = Header::parse_header(&$value[..]).unwrap(); - let fmt = HeaderFormatter(&val); + let fmt = ::header::HeaderFormatter(&val); b.iter(|| { format!("{}", fmt); }); diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -222,15 +222,13 @@ macro_rules! header { fn parse_header(raw: &[Vec<u8>]) -> $crate::Result<Self> { $crate::header::parsing::from_comma_delimited(raw).map($id) } - } - impl $crate::header::HeaderFormat for $id { fn fmt_header(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { $crate::header::parsing::fmt_comma_delimited(f, &self.0[..]) } } impl ::std::fmt::Display for $id { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - use $crate::header::HeaderFormat; + use $crate::header::Header; self.fmt_header(f) } } diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -250,15 +248,13 @@ macro_rules! header { fn parse_header(raw: &[Vec<u8>]) -> $crate::Result<Self> { $crate::header::parsing::from_comma_delimited(raw).map($id) } - } - impl $crate::header::HeaderFormat for $id { fn fmt_header(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { $crate::header::parsing::fmt_comma_delimited(f, &self.0[..]) } } impl ::std::fmt::Display for $id { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - use $crate::header::HeaderFormat; + use $crate::header::Header; self.fmt_header(f) } } diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -277,8 +273,6 @@ macro_rules! header { fn parse_header(raw: &[Vec<u8>]) -> $crate::Result<Self> { $crate::header::parsing::from_one_raw_str(raw).map($id) } - } - impl $crate::header::HeaderFormat for $id { fn fmt_header(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { ::std::fmt::Display::fmt(&**self, f) } diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -313,8 +307,6 @@ macro_rules! header { } $crate::header::parsing::from_comma_delimited(raw).map($id::Items) } - } - impl $crate::header::HeaderFormat for $id { fn fmt_header(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { $id::Any => f.write_str("*"), diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -325,7 +317,7 @@ macro_rules! header { } impl ::std::fmt::Display for $id { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - use $crate::header::HeaderFormat; + use $crate::header::Header; self.fmt_header(f) } } diff --git a/src/header/common/pragma.rs b/src/header/common/pragma.rs --- a/src/header/common/pragma.rs +++ b/src/header/common/pragma.rs @@ -1,7 +1,7 @@ use std::fmt; use std::ascii::AsciiExt; -use header::{Header, HeaderFormat, parsing}; +use header::{Header, parsing}; /// The `Pragma` header defined by HTTP/1.0. /// diff --git a/src/header/common/pragma.rs b/src/header/common/pragma.rs --- a/src/header/common/pragma.rs +++ b/src/header/common/pragma.rs @@ -52,9 +52,7 @@ impl Header for Pragma { } }) } -} -impl HeaderFormat for Pragma { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { Pragma::NoCache => "no-cache", diff --git a/src/header/common/prefer.rs b/src/header/common/prefer.rs --- a/src/header/common/prefer.rs +++ b/src/header/common/prefer.rs @@ -1,6 +1,6 @@ use std::fmt; use std::str::FromStr; -use header::{Header, HeaderFormat}; +use header::{Header}; use header::parsing::{from_comma_delimited, fmt_comma_delimited}; /// `Prefer` header, defined in [RFC7240](http://tools.ietf.org/html/rfc7240) diff --git a/src/header/common/prefer.rs b/src/header/common/prefer.rs --- a/src/header/common/prefer.rs +++ b/src/header/common/prefer.rs @@ -64,9 +64,7 @@ impl Header for Prefer { Err(::Error::Header) } } -} -impl HeaderFormat for Prefer { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt_comma_delimited(f, &self[..]) } diff --git a/src/header/common/preference_applied.rs b/src/header/common/preference_applied.rs --- a/src/header/common/preference_applied.rs +++ b/src/header/common/preference_applied.rs @@ -1,5 +1,5 @@ use std::fmt; -use header::{Header, HeaderFormat, Preference}; +use header::{Header, Preference}; use header::parsing::{from_comma_delimited, fmt_comma_delimited}; /// `Preference-Applied` header, defined in [RFC7240](http://tools.ietf.org/html/rfc7240) diff --git a/src/header/common/preference_applied.rs b/src/header/common/preference_applied.rs --- a/src/header/common/preference_applied.rs +++ b/src/header/common/preference_applied.rs @@ -61,9 +61,7 @@ impl Header for PreferenceApplied { Err(::Error::Header) } } -} -impl HeaderFormat for PreferenceApplied { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { let preferences: Vec<_> = self.0.iter().map(|pref| match pref { // The spec ignores parameters in `Preferences-Applied` diff --git a/src/header/common/range.rs b/src/header/common/range.rs --- a/src/header/common/range.rs +++ b/src/header/common/range.rs @@ -1,7 +1,7 @@ use std::fmt::{self, Display}; use std::str::FromStr; -use header::{Header, HeaderFormat}; +use header::Header; use header::parsing::{from_one_raw_str, from_comma_delimited}; /// `Range` header, defined in [RFC7233](https://tools.ietf.org/html/rfc7233#section-3.1) diff --git a/src/header/common/range.rs b/src/header/common/range.rs --- a/src/header/common/range.rs +++ b/src/header/common/range.rs @@ -182,9 +182,6 @@ impl Header for Range { fn parse_header(raw: &[Vec<u8>]) -> ::Result<Range> { from_one_raw_str(raw) } -} - -impl HeaderFormat for Range { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { Display::fmt(self, f) diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs --- a/src/header/common/set_cookie.rs +++ b/src/header/common/set_cookie.rs @@ -1,4 +1,4 @@ -use header::{Header, HeaderFormat, CookiePair, CookieJar}; +use header::{Header, CookiePair, CookieJar}; use std::fmt::{self, Display}; use std::str::from_utf8; diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs --- a/src/header/common/set_cookie.rs +++ b/src/header/common/set_cookie.rs @@ -104,10 +104,6 @@ impl Header for SetCookie { } } -} - -impl HeaderFormat for SetCookie { - fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { for (i, cookie) in self.0.iter().enumerate() { if i != 0 { diff --git a/src/header/common/strict_transport_security.rs b/src/header/common/strict_transport_security.rs --- a/src/header/common/strict_transport_security.rs +++ b/src/header/common/strict_transport_security.rs @@ -3,7 +3,7 @@ use std::str::{self, FromStr}; use unicase::UniCase; -use header::{Header, HeaderFormat, parsing}; +use header::{Header, parsing}; /// `StrictTransportSecurity` header, defined in [RFC6797](https://tools.ietf.org/html/rfc6797) /// diff --git a/src/header/common/strict_transport_security.rs b/src/header/common/strict_transport_security.rs --- a/src/header/common/strict_transport_security.rs +++ b/src/header/common/strict_transport_security.rs @@ -127,9 +127,7 @@ impl Header for StrictTransportSecurity { fn parse_header(raw: &[Vec<u8>]) -> ::Result<StrictTransportSecurity> { parsing::from_one_raw_str(raw) } -} -impl HeaderFormat for StrictTransportSecurity { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.include_subdomains { write!(f, "max-age={}; includeSubdomains", self.max_age) diff --git a/src/header/common/transfer_encoding.rs b/src/header/common/transfer_encoding.rs --- a/src/header/common/transfer_encoding.rs +++ b/src/header/common/transfer_encoding.rs @@ -49,5 +49,12 @@ header! { } } +impl TransferEncoding { + /// Constructor for the most common Transfer-Encoding, `chunked`. + pub fn chunked() -> TransferEncoding { + TransferEncoding(vec![Encoding::Chunked]) + } +} + bench_header!(normal, TransferEncoding, { vec![b"chunked, gzip".to_vec()] }); bench_header!(ext, TransferEncoding, { vec![b"ext".to_vec()] }); diff --git a/src/header/internals/cell.rs b/src/header/internals/cell.rs --- a/src/header/internals/cell.rs +++ b/src/header/internals/cell.rs @@ -1,7 +1,6 @@ use std::any::{Any, TypeId}; use std::cell::UnsafeCell; use std::collections::HashMap; -use std::fmt; use std::mem; use std::ops::Deref; diff --git a/src/header/internals/cell.rs b/src/header/internals/cell.rs --- a/src/header/internals/cell.rs +++ b/src/header/internals/cell.rs @@ -53,7 +52,7 @@ enum PtrMap<T> { Many(HashMap<TypeId, T>) } -impl<V: ?Sized + fmt::Debug + Any + 'static> PtrMapCell<V> { +impl<V: ?Sized + Any + 'static> PtrMapCell<V> { #[inline] pub fn new() -> PtrMapCell<V> { PtrMapCell(UnsafeCell::new(PtrMap::Empty)) diff --git a/src/header/internals/cell.rs b/src/header/internals/cell.rs --- a/src/header/internals/cell.rs +++ b/src/header/internals/cell.rs @@ -114,12 +113,12 @@ impl<V: ?Sized + fmt::Debug + Any + 'static> PtrMapCell<V> { let map = &*self.0.get(); match *map { PtrMap::One(_, ref one) => one, - _ => panic!("not PtrMap::One value, {:?}", *map) + _ => panic!("not PtrMap::One value") } } } -impl<V: ?Sized + fmt::Debug + Any + 'static> Clone for PtrMapCell<V> where Box<V>: Clone { +impl<V: ?Sized + Any + 'static> Clone for PtrMapCell<V> where Box<V>: Clone { #[inline] fn clone(&self) -> PtrMapCell<V> { let cell = PtrMapCell::new(); diff --git a/src/header/internals/item.rs b/src/header/internals/item.rs --- a/src/header/internals/item.rs +++ b/src/header/internals/item.rs @@ -4,13 +4,13 @@ use std::fmt; use std::str::from_utf8; use super::cell::{OptCell, PtrMapCell}; -use header::{Header, HeaderFormat}; +use header::{Header}; #[derive(Clone)] pub struct Item { raw: OptCell<Vec<Vec<u8>>>, - typed: PtrMapCell<HeaderFormat + Send + Sync> + typed: PtrMapCell<Header + Send + Sync> } impl Item { diff --git a/src/header/internals/item.rs b/src/header/internals/item.rs --- a/src/header/internals/item.rs +++ b/src/header/internals/item.rs @@ -23,7 +23,7 @@ impl Item { } #[inline] - pub fn new_typed(ty: Box<HeaderFormat + Send + Sync>) -> Item { + pub fn new_typed(ty: Box<Header + Send + Sync>) -> Item { let map = PtrMapCell::new(); unsafe { map.insert((*ty).get_type(), ty); } Item { diff --git a/src/header/internals/item.rs b/src/header/internals/item.rs --- a/src/header/internals/item.rs +++ b/src/header/internals/item.rs @@ -52,7 +52,7 @@ impl Item { &raw[..] } - pub fn typed<H: Header + HeaderFormat + Any>(&self) -> Option<&H> { + pub fn typed<H: Header + Any>(&self) -> Option<&H> { let tid = TypeId::of::<H>(); match self.typed.get(tid) { Some(val) => Some(val), diff --git a/src/header/internals/item.rs b/src/header/internals/item.rs --- a/src/header/internals/item.rs +++ b/src/header/internals/item.rs @@ -68,7 +68,7 @@ impl Item { }.map(|typed| unsafe { typed.downcast_ref_unchecked() }) } - pub fn typed_mut<H: Header + HeaderFormat>(&mut self) -> Option<&mut H> { + pub fn typed_mut<H: Header>(&mut self) -> Option<&mut H> { let tid = TypeId::of::<H>(); if self.typed.get_mut(tid).is_none() { match parse::<H>(self.raw.as_ref().expect("item.raw must exist")) { diff --git a/src/header/internals/item.rs b/src/header/internals/item.rs --- a/src/header/internals/item.rs +++ b/src/header/internals/item.rs @@ -83,11 +83,11 @@ impl Item { } #[inline] -fn parse<H: Header + HeaderFormat>(raw: &Vec<Vec<u8>>) -> - ::Result<Box<HeaderFormat + Send + Sync>> { +fn parse<H: Header>(raw: &Vec<Vec<u8>>) -> + ::Result<Box<Header + Send + Sync>> { Header::parse_header(&raw[..]).map(|h: H| { // FIXME: Use Type ascription - let h: Box<HeaderFormat + Send + Sync> = Box::new(h); + let h: Box<Header + Send + Sync> = Box::new(h); h }) } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -31,18 +31,17 @@ //! } //! ``` //! -//! This works well for simple "string" headers. But the header system -//! actually involves 2 parts: parsing, and formatting. If you need to -//! customize either part, you can do so. +//! This works well for simple "string" headers. If you need more control, +//! you can implement the trait directly. //! -//! ## `Header` and `HeaderFormat` +//! ## Implementing the `Header` trait //! //! Consider a Do Not Track header. It can be true or false, but it represents //! that via the numerals `1` and `0`. //! //! ``` //! use std::fmt; -//! use hyper::header::{Header, HeaderFormat}; +//! use hyper::header::Header; //! //! #[derive(Debug, Clone, Copy)] //! struct Dnt(bool); diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -66,9 +65,7 @@ //! } //! Err(hyper::Error::Header) //! } -//! } //! -//! impl HeaderFormat for Dnt { //! fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { //! if self.0 { //! f.write_str("1") diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -113,11 +110,11 @@ type HeaderName = UniCase<CowStr>; /// /// This trait represents the construction and identification of headers, /// and contains trait-object unsafe methods. -pub trait Header: Clone + Any + Send + Sync { +pub trait Header: HeaderClone + Any + Typeable + Send + Sync { /// Returns the name of the header field this belongs to. /// /// This will become an associated constant once available. - fn header_name() -> &'static str; + fn header_name() -> &'static str where Self: Sized; /// Parse a header from a raw stream of bytes. /// /// It's possible that a request can include a header field more than once, diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -125,35 +122,27 @@ pub trait Header: Clone + Any + Send + Sync { /// it's not necessarily the case that a Header is *allowed* to have more /// than one field value. If that's the case, you **should** return `None` /// if `raw.len() > 1`. - fn parse_header(raw: &[Vec<u8>]) -> ::Result<Self>; - -} - -/// A trait for any object that will represent a header field and value. -/// -/// This trait represents the formatting of a `Header` for output to a TcpStream. -pub trait HeaderFormat: fmt::Debug + HeaderClone + Any + Typeable + Send + Sync { + fn parse_header(raw: &[Vec<u8>]) -> ::Result<Self> where Self: Sized; /// Format a header to be output into a TcpStream. /// /// This method is not allowed to introduce an Err not produced /// by the passed-in Formatter. fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result; - } #[doc(hidden)] pub trait HeaderClone { - fn clone_box(&self) -> Box<HeaderFormat + Send + Sync>; + fn clone_box(&self) -> Box<Header + Send + Sync>; } -impl<T: HeaderFormat + Clone> HeaderClone for T { +impl<T: Header + Clone> HeaderClone for T { #[inline] - fn clone_box(&self) -> Box<HeaderFormat + Send + Sync> { + fn clone_box(&self) -> Box<Header + Send + Sync> { Box::new(self.clone()) } } -impl HeaderFormat + Send + Sync { +impl Header + Send + Sync { #[inline] unsafe fn downcast_ref_unchecked<T: 'static>(&self) -> &T { mem::transmute(traitobject::data(self)) diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -165,9 +154,9 @@ impl HeaderFormat + Send + Sync { } } -impl Clone for Box<HeaderFormat + Send + Sync> { +impl Clone for Box<Header + Send + Sync> { #[inline] - fn clone(&self) -> Box<HeaderFormat + Send + Sync> { + fn clone(&self) -> Box<Header + Send + Sync> { self.clone_box() } } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -183,6 +172,12 @@ pub struct Headers { data: HashMap<HeaderName, Item> } +impl Default for Headers { + fn default() -> Headers { + Headers::new() + } +} + impl Headers { /// Creates a new, empty headers map. diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -212,8 +207,8 @@ impl Headers { /// Set a header field to the corresponding value. /// /// The field is determined by the type of the value being set. - pub fn set<H: Header + HeaderFormat>(&mut self, value: H) { - trace!("Headers.set( {:?}, {:?} )", header_name::<H>(), value); + pub fn set<H: Header>(&mut self, value: H) { + trace!("Headers.set( {:?}, {:?} )", header_name::<H>(), HeaderFormatter(&value)); self.data.insert(UniCase(CowStr(Cow::Borrowed(header_name::<H>()))), Item::new_typed(Box::new(value))); } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -259,13 +254,13 @@ impl Headers { } /// Get a reference to the header field's value, if it exists. - pub fn get<H: Header + HeaderFormat>(&self) -> Option<&H> { + pub fn get<H: Header>(&self) -> Option<&H> { self.data.get(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))) .and_then(Item::typed::<H>) } /// Get a mutable reference to the header field's value, if it exists. - pub fn get_mut<H: Header + HeaderFormat>(&mut self) -> Option<&mut H> { + pub fn get_mut<H: Header>(&mut self) -> Option<&mut H> { self.data.get_mut(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))) .and_then(Item::typed_mut::<H>) } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -280,13 +275,13 @@ impl Headers { /// # let mut headers = Headers::new(); /// let has_type = headers.has::<ContentType>(); /// ``` - pub fn has<H: Header + HeaderFormat>(&self) -> bool { + pub fn has<H: Header>(&self) -> bool { self.data.contains_key(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))) } /// Removes a header from the map, if one existed. /// Returns true if a header has been removed. - pub fn remove<H: Header + HeaderFormat>(&mut self) -> bool { + pub fn remove<H: Header>(&mut self) -> bool { trace!("Headers.remove( {:?} )", header_name::<H>()); self.data.remove(&UniCase(CowStr(Cow::Borrowed(header_name::<H>())))).is_some() } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -380,6 +375,7 @@ impl Deserialize for Headers { } /// An `Iterator` over the fields in a `Headers` map. +#[allow(missing_debug_implementations)] pub struct HeadersItems<'a> { inner: Iter<'a, HeaderName, Item> } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -410,7 +406,7 @@ impl<'a> HeaderView<'a> { /// Cast the value to a certain Header type. #[inline] - pub fn value<H: Header + HeaderFormat>(&self) -> Option<&'a H> { + pub fn value<H: Header>(&self) -> Option<&'a H> { self.1.typed::<H>() } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -449,7 +445,7 @@ impl<'a> FromIterator<HeaderView<'a>> for Headers { } } -impl<'a> fmt::Display for &'a (HeaderFormat + Send + Sync) { +impl<'a> fmt::Display for &'a (Header + Send + Sync) { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt_header(f) diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -461,16 +457,16 @@ impl<'a> fmt::Display for &'a (HeaderFormat + Send + Sync) { /// This can be used like so: `format!("{}", HeaderFormatter(&header))` to /// get the representation of a Header which will be written to an /// outgoing `TcpStream`. -pub struct HeaderFormatter<'a, H: HeaderFormat>(pub &'a H); +pub struct HeaderFormatter<'a, H: Header>(pub &'a H); -impl<'a, H: HeaderFormat> fmt::Display for HeaderFormatter<'a, H> { +impl<'a, H: Header> fmt::Display for HeaderFormatter<'a, H> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt_header(f) } } -impl<'a, H: HeaderFormat> fmt::Debug for HeaderFormatter<'a, H> { +impl<'a, H: Header> fmt::Debug for HeaderFormatter<'a, H> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt_header(f) diff --git a/src/header/parsing.rs b/src/header/parsing.rs --- a/src/header/parsing.rs +++ b/src/header/parsing.rs @@ -137,6 +137,12 @@ define_encode_set! { } } +impl fmt::Debug for HTTP_VALUE { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad("HTTP_VALUE") + } +} + impl Display for ExtendedValue { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let encoded_value = diff --git /dev/null b/src/http/buffer.rs new file mode 100644 --- /dev/null +++ b/src/http/buffer.rs @@ -0,0 +1,120 @@ +use std::cmp; +use std::io::{self, Read}; +use std::ptr; + + +const INIT_BUFFER_SIZE: usize = 4096; +const MAX_BUFFER_SIZE: usize = 8192 + 4096 * 100; + +#[derive(Debug)] +pub struct Buffer { + vec: Vec<u8>, + read_pos: usize, + write_pos: usize, +} + +impl Buffer { + pub fn new() -> Buffer { + Buffer { + vec: Vec::new(), + read_pos: 0, + write_pos: 0, + } + } + + pub fn reset(&mut self) { + *self = Buffer::new() + } + + #[inline] + pub fn len(&self) -> usize { + self.read_pos - self.write_pos + } + + #[inline] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + #[inline] + pub fn bytes(&self) -> &[u8] { + &self.vec[self.write_pos..self.read_pos] + } + + #[inline] + pub fn consume(&mut self, pos: usize) { + debug_assert!(self.read_pos >= self.write_pos + pos); + self.write_pos += pos; + if self.write_pos == self.read_pos { + self.write_pos = 0; + self.read_pos = 0; + } + } + + pub fn read_from<R: Read>(&mut self, r: &mut R) -> io::Result<usize> { + self.maybe_reserve(); + let n = try!(r.read(&mut self.vec[self.read_pos..])); + self.read_pos += n; + Ok(n) + } + + #[inline] + fn maybe_reserve(&mut self) { + let cap = self.vec.len(); + if cap == 0 { + trace!("reserving initial {}", INIT_BUFFER_SIZE); + self.vec = vec![0; INIT_BUFFER_SIZE]; + } else if self.write_pos > 0 && self.read_pos == cap { + let count = self.read_pos - self.write_pos; + trace!("moving buffer bytes over by {}", count); + unsafe { + ptr::copy( + self.vec.as_ptr().offset(self.write_pos as isize), + self.vec.as_mut_ptr(), + count + ); + } + self.read_pos -= count; + self.write_pos = 0; + } else if self.read_pos == cap && cap < MAX_BUFFER_SIZE { + self.vec.reserve(cmp::min(cap * 4, MAX_BUFFER_SIZE) - cap); + let new = self.vec.capacity() - cap; + trace!("reserved {}", new); + unsafe { grow_zerofill(&mut self.vec, new) } + } + } + + pub fn wrap<'a, 'b: 'a, R: io::Read>(&'a mut self, reader: &'b mut R) -> BufReader<'a, R> { + BufReader { + buf: self, + reader: reader + } + } +} + +#[derive(Debug)] +pub struct BufReader<'a, R: io::Read + 'a> { + buf: &'a mut Buffer, + reader: &'a mut R +} + +impl<'a, R: io::Read> Read for BufReader<'a, R> { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + trace!("BufReader.read self={}, buf={}", self.buf.len(), buf.len()); + let n = try!(self.buf.bytes().read(buf)); + self.buf.consume(n); + if n == 0 { + self.buf.reset(); + self.reader.read(&mut buf[n..]) + } else { + Ok(n) + } + } +} + +#[inline] +unsafe fn grow_zerofill(buf: &mut Vec<u8>, additional: usize) { + let len = buf.len(); + buf.set_len(len + additional); + ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()); +} diff --git /dev/null b/src/http/channel.rs new file mode 100644 --- /dev/null +++ b/src/http/channel.rs @@ -0,0 +1,96 @@ +use std::fmt; +use std::sync::{Arc, mpsc}; +use std::sync::atomic::{AtomicBool, Ordering}; +use ::rotor; + +pub use std::sync::mpsc::TryRecvError; + +pub fn new<T>(notify: rotor::Notifier) -> (Sender<T>, Receiver<T>) { + let b = Arc::new(AtomicBool::new(false)); + let (tx, rx) = mpsc::channel(); + (Sender { + awake: b.clone(), + notify: notify, + tx: tx, + }, + Receiver { + awake: b, + rx: rx, + }) +} + +pub fn share<T, U>(other: &Sender<U>) -> (Sender<T>, Receiver<T>) { + let (tx, rx) = mpsc::channel(); + let notify = other.notify.clone(); + let b = other.awake.clone(); + (Sender { + awake: b.clone(), + notify: notify, + tx: tx, + }, + Receiver { + awake: b, + rx: rx, + }) +} + +pub struct Sender<T> { + awake: Arc<AtomicBool>, + notify: rotor::Notifier, + tx: mpsc::Sender<T>, +} + +impl<T: Send> Sender<T> { + pub fn send(&self, val: T) -> Result<(), SendError<T>> { + try!(self.tx.send(val)); + if !self.awake.swap(true, Ordering::SeqCst) { + try!(self.notify.wakeup()); + } + Ok(()) + } +} + +impl<T> Clone for Sender<T> { + fn clone(&self) -> Sender<T> { + Sender { + awake: self.awake.clone(), + notify: self.notify.clone(), + tx: self.tx.clone(), + } + } +} + +impl<T> fmt::Debug for Sender<T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Sender") + .field("notify", &self.notify) + .finish() + } +} + +#[derive(Debug)] +pub struct SendError<T>(pub Option<T>); + +impl<T> From<mpsc::SendError<T>> for SendError<T> { + fn from(e: mpsc::SendError<T>) -> SendError<T> { + SendError(Some(e.0)) + } +} + +impl<T> From<rotor::WakeupError> for SendError<T> { + fn from(_e: rotor::WakeupError) -> SendError<T> { + SendError(None) + } +} + +pub struct Receiver<T> { + awake: Arc<AtomicBool>, + rx: mpsc::Receiver<T>, +} + +impl<T: Send> Receiver<T> { + pub fn try_recv(&self) -> Result<T, mpsc::TryRecvError> { + self.awake.store(false, Ordering::Relaxed); + self.rx.try_recv() + } +} diff --git /dev/null b/src/http/h1/mod.rs new file mode 100644 --- /dev/null +++ b/src/http/h1/mod.rs @@ -0,0 +1,136 @@ +/* +use std::fmt; +use std::io::{self, Write}; +use std::marker::PhantomData; +use std::sync::mpsc; + +use url::Url; +use tick; +use time::now_utc; + +use header::{self, Headers}; +use http::{self, conn}; +use method::Method; +use net::{Fresh, Streaming}; +use status::StatusCode; +use version::HttpVersion; +*/ + +pub use self::decode::Decoder; +pub use self::encode::Encoder; + +pub use self::parse::parse; + +mod decode; +mod encode; +mod parse; + +/* +fn should_have_response_body(method: &Method, status: u16) -> bool { + trace!("should_have_response_body({:?}, {})", method, status); + match (method, status) { + (&Method::Head, _) | + (_, 100...199) | + (_, 204) | + (_, 304) | + (&Method::Connect, 200...299) => false, + _ => true + } +} +*/ +/* +const MAX_INVALID_RESPONSE_BYTES: usize = 1024 * 128; +impl HttpMessage for Http11Message { + + fn get_incoming(&mut self) -> ::Result<ResponseHead> { + unimplemented!(); + /* + try!(self.flush_outgoing()); + let stream = match self.stream.take() { + Some(stream) => stream, + None => { + // The message was already in the reading state... + // TODO Decide what happens in case we try to get a new incoming at that point + return Err(From::from( + io::Error::new(io::ErrorKind::Other, + "Read already in progress"))); + } + }; + + let expected_no_content = stream.previous_response_expected_no_content(); + trace!("previous_response_expected_no_content = {}", expected_no_content); + + let mut stream = BufReader::new(stream); + + let mut invalid_bytes_read = 0; + let head; + loop { + head = match parse_response(&mut stream) { + Ok(head) => head, + Err(::Error::Version) + if expected_no_content && invalid_bytes_read < MAX_INVALID_RESPONSE_BYTES => { + trace!("expected_no_content, found content"); + invalid_bytes_read += 1; + stream.consume(1); + continue; + } + Err(e) => { + self.stream = Some(stream.into_inner()); + return Err(e); + } + }; + break; + } + + let raw_status = head.subject; + let headers = head.headers; + + let method = self.method.take().unwrap_or(Method::Get); + + let is_empty = !should_have_response_body(&method, raw_status.0); + stream.get_mut().set_previous_response_expected_no_content(is_empty); + // According to https://tools.ietf.org/html/rfc7230#section-3.3.3 + // 1. HEAD reponses, and Status 1xx, 204, and 304 cannot have a body. + // 2. Status 2xx to a CONNECT cannot have a body. + // 3. Transfer-Encoding: chunked has a chunked body. + // 4. If multiple differing Content-Length headers or invalid, close connection. + // 5. Content-Length header has a sized body. + // 6. Not Client. + // 7. Read till EOF. + self.reader = Some(if is_empty { + SizedReader(stream, 0) + } else { + if let Some(&TransferEncoding(ref codings)) = headers.get() { + if codings.last() == Some(&Chunked) { + ChunkedReader(stream, None) + } else { + trace!("not chuncked. read till eof"); + EofReader(stream) + } + } else if let Some(&ContentLength(len)) = headers.get() { + SizedReader(stream, len) + } else if headers.has::<ContentLength>() { + trace!("illegal Content-Length: {:?}", headers.get_raw("Content-Length")); + return Err(Error::Header); + } else { + trace!("neither Transfer-Encoding nor Content-Length"); + EofReader(stream) + } + }); + + trace!("Http11Message.reader = {:?}", self.reader); + + + Ok(ResponseHead { + headers: headers, + raw_status: raw_status, + version: head.version, + }) + */ + } +} + + +*/ + + diff --git a/src/http/message.rs /dev/null --- a/src/http/message.rs +++ /dev/null @@ -1,133 +0,0 @@ -//! Defines the `HttpMessage` trait that serves to encapsulate the operations of a single -//! request-response cycle on any HTTP connection. - -use std::any::{Any, TypeId}; -use std::fmt::Debug; -use std::io::{Read, Write}; -use std::mem; - -use std::io; -use std::time::Duration; - -use typeable::Typeable; - -use header::Headers; -use http::RawStatus; -use url::Url; - -use method; -use version; -use traitobject; - -/// The trait provides an API for creating new `HttpMessage`s depending on the underlying HTTP -/// protocol. -pub trait Protocol { - /// Creates a fresh `HttpMessage` bound to the given host, based on the given protocol scheme. - fn new_message(&self, host: &str, port: u16, scheme: &str) -> ::Result<Box<HttpMessage>>; -} - -/// Describes a request. -#[derive(Clone, Debug)] -pub struct RequestHead { - /// The headers of the request - pub headers: Headers, - /// The method of the request - pub method: method::Method, - /// The URL of the request - pub url: Url, -} - -/// Describes a response. -#[derive(Clone, Debug)] -pub struct ResponseHead { - /// The headers of the reponse - pub headers: Headers, - /// The raw status line of the response - pub raw_status: RawStatus, - /// The HTTP/2 version which generated the response - pub version: version::HttpVersion, -} - -/// The trait provides an API for sending an receiving HTTP messages. -pub trait HttpMessage: Write + Read + Send + Any + Typeable + Debug { - /// Initiates a new outgoing request. - /// - /// Only the request's head is provided (in terms of the `RequestHead` struct). - /// - /// After this, the `HttpMessage` instance can be used as an `io::Write` in order to write the - /// body of the request. - fn set_outgoing(&mut self, head: RequestHead) -> ::Result<RequestHead>; - /// Obtains the incoming response and returns its head (i.e. the `ResponseHead` struct) - /// - /// After this, the `HttpMessage` instance can be used as an `io::Read` in order to read out - /// the response body. - fn get_incoming(&mut self) -> ::Result<ResponseHead>; - /// Set the read timeout duration for this message. - fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()>; - /// Set the write timeout duration for this message. - fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()>; - /// Closes the underlying HTTP connection. - fn close_connection(&mut self) -> ::Result<()>; - /// Returns whether the incoming message has a body. - fn has_body(&self) -> bool; - /// Called when the Client wishes to use a Proxy. - fn set_proxied(&mut self, val: bool) { - // default implementation so as to not be a breaking change. - warn!("default set_proxied({:?})", val); - } -} - -impl HttpMessage { - unsafe fn downcast_ref_unchecked<T: 'static>(&self) -> &T { - mem::transmute(traitobject::data(self)) - } - - unsafe fn downcast_mut_unchecked<T: 'static>(&mut self) -> &mut T { - mem::transmute(traitobject::data_mut(self)) - } - - unsafe fn downcast_unchecked<T: 'static>(self: Box<HttpMessage>) -> Box<T> { - let raw: *mut HttpMessage = mem::transmute(self); - mem::transmute(traitobject::data_mut(raw)) - } -} - -impl HttpMessage { - /// Is the underlying type in this trait object a T? - #[inline] - pub fn is<T: Any>(&self) -> bool { - (*self).get_type() == TypeId::of::<T>() - } - - /// If the underlying type is T, get a reference to the contained data. - #[inline] - pub fn downcast_ref<T: Any>(&self) -> Option<&T> { - if self.is::<T>() { - Some(unsafe { self.downcast_ref_unchecked() }) - } else { - None - } - } - - /// If the underlying type is T, get a mutable reference to the contained - /// data. - #[inline] - pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> { - if self.is::<T>() { - Some(unsafe { self.downcast_mut_unchecked() }) - } else { - None - } - } - - /// If the underlying type is T, extract it. - #[inline] - pub fn downcast<T: Any>(self: Box<HttpMessage>) - -> Result<Box<T>, Box<HttpMessage>> { - if self.is::<T>() { - Ok(unsafe { self.downcast_unchecked() }) - } else { - Err(self) - } - } -} diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -1,25 +1,196 @@ //! Pieces pertaining to the HTTP message protocol. use std::borrow::Cow; +use std::fmt; +use std::io::{self, Read, Write}; +use std::time::Duration; use header::Connection; use header::ConnectionOption::{KeepAlive, Close}; use header::Headers; +use method::Method; +use net::Transport; +use status::StatusCode; +use uri::RequestUri; use version::HttpVersion; use version::HttpVersion::{Http10, Http11}; #[cfg(feature = "serde-serialization")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; -pub use self::message::{HttpMessage, RequestHead, ResponseHead, Protocol}; +pub use self::conn::{Conn, MessageHandler, MessageHandlerFactory, Seed, Key}; -pub mod h1; -pub mod h2; -pub mod message; +mod buffer; +pub mod channel; +mod conn; +mod h1; +//mod h2; + +/// Wraps a `Transport` to provide HTTP decoding when reading. +#[derive(Debug)] +pub struct Decoder<'a, T: Read + 'a>(DecoderImpl<'a, T>); + +/// Wraps a `Transport` to provide HTTP encoding when writing. +#[derive(Debug)] +pub struct Encoder<'a, T: Transport + 'a>(EncoderImpl<'a, T>); + +#[derive(Debug)] +enum DecoderImpl<'a, T: Read + 'a> { + H1(&'a mut h1::Decoder, Trans<'a, T>), +} + +#[derive(Debug)] +enum Trans<'a, T: Read + 'a> { + Port(&'a mut T), + Buf(self::buffer::BufReader<'a, T>) +} + +impl<'a, T: Read + 'a> Read for Trans<'a, T> { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + match *self { + Trans::Port(ref mut t) => t.read(buf), + Trans::Buf(ref mut b) => b.read(buf) + } + } +} + +#[derive(Debug)] +enum EncoderImpl<'a, T: Transport + 'a> { + H1(&'a mut h1::Encoder, &'a mut T), +} + +impl<'a, T: Read> Decoder<'a, T> { + fn h1(decoder: &'a mut h1::Decoder, transport: Trans<'a, T>) -> Decoder<'a, T> { + Decoder(DecoderImpl::H1(decoder, transport)) + } +} + +impl<'a, T: Transport> Encoder<'a, T> { + fn h1(encoder: &'a mut h1::Encoder, transport: &'a mut T) -> Encoder<'a, T> { + Encoder(EncoderImpl::H1(encoder, transport)) + } +} + +impl<'a, T: Read> Read for Decoder<'a, T> { + #[inline] + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + match self.0 { + DecoderImpl::H1(ref mut decoder, ref mut transport) => { + decoder.decode(transport, buf) + } + } + } +} + +impl<'a, T: Transport> Write for Encoder<'a, T> { + #[inline] + fn write(&mut self, data: &[u8]) -> io::Result<usize> { + if data.is_empty() { + return Ok(0); + } + match self.0 { + EncoderImpl::H1(ref mut encoder, ref mut transport) => { + encoder.encode(*transport, data) + } + } + } + + #[inline] + fn flush(&mut self) -> io::Result<()> { + match self.0 { + EncoderImpl::H1(_, ref mut transport) => { + transport.flush() + } + } + } +} + +/// Because privacy rules. Reasons. +/// https://github.com/rust-lang/rust/issues/30905 +mod internal { + use std::io::{self, Write}; + + #[derive(Debug, Clone)] + pub struct WriteBuf<T: AsRef<[u8]>> { + pub bytes: T, + pub pos: usize, + } + + pub trait AtomicWrite { + fn write_atomic(&mut self, data: &[&[u8]]) -> io::Result<usize>; + } + + #[cfg(not(windows))] + impl<T: Write + ::vecio::Writev> AtomicWrite for T { + + fn write_atomic(&mut self, bufs: &[&[u8]]) -> io::Result<usize> { + self.writev(bufs) + } + + } + + #[cfg(windows)] + impl<T: Write> AtomicWrite for T { + fn write_atomic(&mut self, bufs: &[&[u8]]) -> io::Result<usize> { + let vec = bufs.concat(); + self.write(&vec) + } + } +} + +/// An Incoming Message head. Includes request/status line, and headers. +#[derive(Debug, Default)] +pub struct MessageHead<S> { + /// HTTP version of the message. + pub version: HttpVersion, + /// Subject (request line or status line) of Incoming message. + pub subject: S, + /// Headers of the Incoming message. + pub headers: Headers +} + +/// An incoming request message. +pub type RequestHead = MessageHead<RequestLine>; + +#[derive(Debug, Default)] +pub struct RequestLine(pub Method, pub RequestUri); + +impl fmt::Display for RequestLine { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{} {}", self.0, self.1) + } +} + +/// An incoming response message. +pub type ResponseHead = MessageHead<RawStatus>; + +impl<S> MessageHead<S> { + pub fn should_keep_alive(&self) -> bool { + should_keep_alive(self.version, &self.headers) + } +} /// The raw status code and reason-phrase. #[derive(Clone, PartialEq, Debug)] pub struct RawStatus(pub u16, pub Cow<'static, str>); +impl fmt::Display for RawStatus { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{} {}", self.0, self.1) + } +} + +impl From<StatusCode> for RawStatus { + fn from(status: StatusCode) -> RawStatus { + RawStatus(status.to_u16(), Cow::Borrowed(status.canonical_reason().unwrap_or(""))) + } +} + +impl Default for RawStatus { + fn default() -> RawStatus { + RawStatus(200, Cow::Borrowed("OK")) + } +} + #[cfg(feature = "serde-serialization")] impl Serialize for RawStatus { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -9,125 +10,9 @@ //! is a low-level typesafe abstraction over raw HTTP, providing an elegant //! layer over "stringly-typed" HTTP. //! -//! Hyper offers both a [Client](client/index.html) and a -//! [Server](server/index.html) which can be used to drive complex web -//! applications written entirely in Rust. -//! -//! ## Internal Design -//! -//! Hyper is designed as a relatively low-level wrapper over raw HTTP. It should -//! allow the implementation of higher-level abstractions with as little pain as -//! possible, and should not irrevocably hide any information from its users. -//! -//! ### Common Functionality -//! -//! Functionality and code shared between the Server and Client implementations -//! can be found in `src` directly - this includes `NetworkStream`s, `Method`s, -//! `StatusCode`, and so on. -//! -//! #### Methods -//! -//! Methods are represented as a single `enum` to remain as simple as possible. -//! Extension Methods are represented as raw `String`s. A method's safety and -//! idempotence can be accessed using the `safe` and `idempotent` methods. -//! -//! #### StatusCode -//! -//! Status codes are also represented as a single, exhaustive, `enum`. This -//! representation is efficient, typesafe, and ergonomic as it allows the use of -//! `match` to disambiguate known status codes. -//! -//! #### Headers -//! -//! Hyper's [header](header/index.html) representation is likely the most -//! complex API exposed by Hyper. -//! -//! Hyper's headers are an abstraction over an internal `HashMap` and provides a -//! typesafe API for interacting with headers that does not rely on the use of -//! "string-typing." -//! -//! Each HTTP header in Hyper has an associated type and implementation of the -//! `Header` trait, which defines an HTTP headers name as a string, how to parse -//! that header, and how to format that header. -//! -//! Headers are then parsed from the string representation lazily when the typed -//! representation of a header is requested and formatted back into their string -//! representation when headers are written back to the client. -//! -//! #### NetworkStream and NetworkAcceptor -//! -//! These are found in `src/net.rs` and define the interface that acceptors and -//! streams must fulfill for them to be used within Hyper. They are by and large -//! internal tools and you should only need to mess around with them if you want to -//! mock or replace `TcpStream` and `TcpAcceptor`. -//! -//! ### Server -//! -//! Server-specific functionality, such as `Request` and `Response` -//! representations, are found in in `src/server`. -//! -//! #### Handler + Server -//! -//! A `Handler` in Hyper accepts a `Request` and `Response`. This is where -//! user-code can handle each connection. The server accepts connections in a -//! task pool with a customizable number of threads, and passes the Request / -//! Response to the handler. -//! -//! #### Request -//! -//! An incoming HTTP Request is represented as a struct containing -//! a `Reader` over a `NetworkStream`, which represents the body, headers, a remote -//! address, an HTTP version, and a `Method` - relatively standard stuff. -//! -//! `Request` implements `Reader` itself, meaning that you can ergonomically get -//! the body out of a `Request` using standard `Reader` methods and helpers. -//! -//! #### Response -//! -//! An outgoing HTTP Response is also represented as a struct containing a `Writer` -//! over a `NetworkStream` which represents the Response body in addition to -//! standard items such as the `StatusCode` and HTTP version. `Response`'s `Writer` -//! implementation provides a streaming interface for sending data over to the -//! client. -//! -//! One of the traditional problems with representing outgoing HTTP Responses is -//! tracking the write-status of the Response - have we written the status-line, -//! the headers, the body, etc.? Hyper tracks this information statically using the -//! type system and prevents you, using the type system, from writing headers after -//! you have started writing to the body or vice versa. -//! -//! Hyper does this through a phantom type parameter in the definition of Response, -//! which tracks whether you are allowed to write to the headers or the body. This -//! phantom type can have two values `Fresh` or `Streaming`, with `Fresh` -//! indicating that you can write the headers and `Streaming` indicating that you -//! may write to the body, but not the headers. -//! -//! ### Client -//! -//! Client-specific functionality, such as `Request` and `Response` -//! representations, are found in `src/client`. -//! -//! #### Request -//! -//! An outgoing HTTP Request is represented as a struct containing a `Writer` over -//! a `NetworkStream` which represents the Request body in addition to the standard -//! information such as headers and the request method. -//! -//! Outgoing Requests track their write-status in almost exactly the same way as -//! outgoing HTTP Responses do on the Server, so we will defer to the explanation -//! in the documentation for server Response. -//! -//! Requests expose an efficient streaming interface instead of a builder pattern, -//! but they also provide the needed interface for creating a builder pattern over -//! the API exposed by core Hyper. -//! -//! #### Response -//! -//! Incoming HTTP Responses are represented as a struct containing a `Reader` over -//! a `NetworkStream` and contain headers, a status, and an http version. They -//! implement `Reader` and can be read to get the data out of a `Response`. -//! - +//! Hyper provides both a [Client](client/index.html) and a +//! [Server](server/index.html), along with a +//! [typed Headers system](header/index.html). extern crate rustc_serialize as serialize; extern crate time; #[macro_use] extern crate url; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -142,10 +27,11 @@ extern crate serde; extern crate cookie; extern crate unicase; extern crate httparse; -extern crate num_cpus; +extern crate rotor; +extern crate spmc; extern crate traitobject; extern crate typeable; -extern crate solicit; +extern crate vecio; #[macro_use] extern crate language_tags; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -203,6 +85,7 @@ pub mod mime { pub use mime_crate::*; } +/* #[allow(unconditional_recursion)] fn _assert_send<T: Send>() { _assert_send::<Client>(); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -216,3 +99,4 @@ fn _assert_sync<T: Sync>() { _assert_sync::<Client>(); _assert_sync::<error::Error>(); } +*/ diff --git a/src/method.rs b/src/method.rs --- a/src/method.rs +++ b/src/method.rs @@ -128,6 +128,12 @@ impl fmt::Display for Method { } } +impl Default for Method { + fn default() -> Method { + Method::Get + } +} + #[cfg(feature = "serde-serialization")] impl Serialize for Method { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer { diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -1,327 +1,127 @@ -use std::ascii::AsciiExt; -use std::io::{self, Read, Write, Cursor}; -use std::cell::RefCell; -use std::net::{SocketAddr, Shutdown}; -use std::sync::{Arc, Mutex}; -use std::time::Duration; -use std::cell::Cell; +use std::cmp; +use std::io::{self, Read, Write}; -use solicit::http::HttpScheme; -use solicit::http::transport::TransportStream; -use solicit::http::frame::{SettingsFrame, Frame}; -use solicit::http::connection::{HttpConnection, EndStream, DataChunk}; - -use header::Headers; -use net::{NetworkStream, NetworkConnector, SslClient}; - -#[derive(Clone, Debug)] -pub struct MockStream { - pub read: Cursor<Vec<u8>>, - next_reads: Vec<Vec<u8>>, - pub write: Vec<u8>, - pub is_closed: bool, - pub error_on_write: bool, - pub error_on_read: bool, - pub read_timeout: Cell<Option<Duration>>, - pub write_timeout: Cell<Option<Duration>>, -} - -impl PartialEq for MockStream { - fn eq(&self, other: &MockStream) -> bool { - self.read.get_ref() == other.read.get_ref() && self.write == other.write - } +#[derive(Debug)] +pub struct Buf { + vec: Vec<u8> } -impl MockStream { - pub fn new() -> MockStream { - MockStream::with_input(b"") - } - - pub fn with_input(input: &[u8]) -> MockStream { - MockStream::with_responses(vec![input]) - } - - pub fn with_responses(mut responses: Vec<&[u8]>) -> MockStream { - MockStream { - read: Cursor::new(responses.remove(0).to_vec()), - next_reads: responses.into_iter().map(|arr| arr.to_vec()).collect(), - write: vec![], - is_closed: false, - error_on_write: false, - error_on_read: false, - read_timeout: Cell::new(None), - write_timeout: Cell::new(None), +impl Buf { + pub fn new() -> Buf { + Buf { + vec: vec![] } } } -impl Read for MockStream { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - if self.error_on_read { - Err(io::Error::new(io::ErrorKind::Other, "mock error")) - } else { - match self.read.read(buf) { - Ok(n) => { - if self.read.position() as usize == self.read.get_ref().len() { - if self.next_reads.len() > 0 { - self.read = Cursor::new(self.next_reads.remove(0)); - } - } - Ok(n) - }, - r => r - } - } - } -} +impl ::std::ops::Deref for Buf { + type Target = [u8]; -impl Write for MockStream { - fn write(&mut self, msg: &[u8]) -> io::Result<usize> { - if self.error_on_write { - Err(io::Error::new(io::ErrorKind::Other, "mock error")) - } else { - Write::write(&mut self.write, msg) - } - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) + fn deref(&self) -> &[u8] { + &self.vec } } -impl NetworkStream for MockStream { - fn peer_addr(&mut self) -> io::Result<SocketAddr> { - Ok("127.0.0.1:1337".parse().unwrap()) - } - - fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.read_timeout.set(dur); - Ok(()) - } - - fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.write_timeout.set(dur); - Ok(()) - } - - fn close(&mut self, _how: Shutdown) -> io::Result<()> { - self.is_closed = true; - Ok(()) +impl<S: AsRef<[u8]>> PartialEq<S> for Buf { + fn eq(&self, other: &S) -> bool { + self.vec == other.as_ref() } } -/// A wrapper around a `MockStream` that allows one to clone it and keep an independent copy to the -/// same underlying stream. -#[derive(Clone)] -pub struct CloneableMockStream { - pub inner: Arc<Mutex<MockStream>>, -} - -impl Write for CloneableMockStream { - fn write(&mut self, msg: &[u8]) -> io::Result<usize> { - self.inner.lock().unwrap().write(msg) +impl Write for Buf { + fn write(&mut self, data: &[u8]) -> io::Result<usize> { + self.vec.extend(data); + Ok(data.len()) } fn flush(&mut self) -> io::Result<()> { - self.inner.lock().unwrap().flush() + Ok(()) } } -impl Read for CloneableMockStream { +impl Read for Buf { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.inner.lock().unwrap().read(buf) + (&*self.vec).read(buf) } } -impl TransportStream for CloneableMockStream { - fn try_split(&self) -> Result<CloneableMockStream, io::Error> { - Ok(self.clone()) - } +impl ::vecio::Writev for Buf { + fn writev(&mut self, bufs: &[&[u8]]) -> io::Result<usize> { + let cap = bufs.iter().map(|buf| buf.len()).fold(0, |total, next| total + next); + let mut vec = Vec::with_capacity(cap); + for &buf in bufs { + vec.extend(buf); + } - fn close(&mut self) -> Result<(), io::Error> { - Ok(()) + self.write(&vec) } } -impl NetworkStream for CloneableMockStream { - fn peer_addr(&mut self) -> io::Result<SocketAddr> { - self.inner.lock().unwrap().peer_addr() - } - - fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.inner.lock().unwrap().set_read_timeout(dur) - } - - fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.inner.lock().unwrap().set_write_timeout(dur) - } - - fn close(&mut self, how: Shutdown) -> io::Result<()> { - NetworkStream::close(&mut *self.inner.lock().unwrap(), how) - } +#[derive(Debug)] +pub struct Async<T> { + inner: T, + bytes_until_block: usize, } -impl CloneableMockStream { - pub fn with_stream(stream: MockStream) -> CloneableMockStream { - CloneableMockStream { - inner: Arc::new(Mutex::new(stream)), +impl<T> Async<T> { + pub fn new(inner: T, bytes: usize) -> Async<T> { + Async { + inner: inner, + bytes_until_block: bytes } } -} -pub struct MockConnector; - -impl NetworkConnector for MockConnector { - type Stream = MockStream; - - fn connect(&self, _host: &str, _port: u16, _scheme: &str) -> ::Result<MockStream> { - Ok(MockStream::new()) + pub fn block_in(&mut self, bytes: usize) { + self.bytes_until_block = bytes; } } -/// new connectors must be created if you wish to intercept requests. -macro_rules! mock_connector ( - ($name:ident { - $($url:expr => $res:expr)* - }) => ( - - struct $name; - - impl $crate::net::NetworkConnector for $name { - type Stream = ::mock::MockStream; - fn connect(&self, host: &str, port: u16, scheme: &str) - -> $crate::Result<::mock::MockStream> { - use std::collections::HashMap; - debug!("MockStream::connect({:?}, {:?}, {:?})", host, port, scheme); - let mut map = HashMap::new(); - $(map.insert($url, $res);)* - - - let key = format!("{}://{}", scheme, host); - // ignore port for now - match map.get(&*key) { - Some(&res) => Ok($crate::mock::MockStream::with_input(res.as_bytes())), - None => panic!("{:?} doesn't know url {}", stringify!($name), key) - } - } - } - - ); - - ($name:ident { $($response:expr),+ }) => ( - struct $name; - - impl $crate::net::NetworkConnector for $name { - type Stream = $crate::mock::MockStream; - fn connect(&self, _: &str, _: u16, _: &str) - -> $crate::Result<$crate::mock::MockStream> { - Ok($crate::mock::MockStream::with_responses(vec![ - $($response),+ - ])) - } +impl<T: Read> Read for Async<T> { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + if self.bytes_until_block == 0 { + Err(io::Error::new(io::ErrorKind::WouldBlock, "mock block")) + } else { + let n = cmp::min(self.bytes_until_block, buf.len()); + let n = try!(self.inner.read(&mut buf[..n])); + self.bytes_until_block -= n; + Ok(n) } - ); -); - -impl TransportStream for MockStream { - fn try_split(&self) -> Result<MockStream, io::Error> { - Ok(self.clone()) - } - - fn close(&mut self) -> Result<(), io::Error> { - Ok(()) } } -impl MockStream { - /// Creates a new `MockStream` that will return the response described by the parameters as an - /// HTTP/2 response. This will also include the correct server preface. - pub fn new_http2_response(status: &[u8], headers: &Headers, body: Option<Vec<u8>>) - -> MockStream { - let resp_bytes = build_http2_response(status, headers, body); - MockStream::with_input(&resp_bytes) +impl<T: Write> Write for Async<T> { + fn write(&mut self, data: &[u8]) -> io::Result<usize> { + if self.bytes_until_block == 0 { + Err(io::Error::new(io::ErrorKind::WouldBlock, "mock block")) + } else { + let n = cmp::min(self.bytes_until_block, data.len()); + let n = try!(self.inner.write(&data[..n])); + self.bytes_until_block -= n; + Ok(n) + } } -} -/// Builds up a sequence of bytes that represent a server's response based on the given parameters. -pub fn build_http2_response(status: &[u8], headers: &Headers, body: Option<Vec<u8>>) -> Vec<u8> { - let mut conn = HttpConnection::new(MockStream::new(), MockStream::new(), HttpScheme::Http); - // Server preface first - conn.sender.write(&SettingsFrame::new().serialize()).unwrap(); - - let mut resp_headers: Vec<_> = headers.iter().map(|h| { - (h.name().to_ascii_lowercase().into_bytes(), h.value_string().into_bytes()) - }).collect(); - resp_headers.insert(0, (b":status".to_vec(), status.into())); - - let end = if body.is_none() { - EndStream::Yes - } else { - EndStream::No - }; - conn.send_headers(resp_headers, 1, end).unwrap(); - if body.is_some() { - let chunk = DataChunk::new_borrowed(&body.as_ref().unwrap()[..], 1, EndStream::Yes); - conn.send_data(chunk).unwrap(); + fn flush(&mut self) -> io::Result<()> { + self.inner.flush() } - - conn.sender.write } -/// A mock connector that produces `MockStream`s that are set to return HTTP/2 responses. -/// -/// This means that the streams' payloads are fairly opaque byte sequences (as HTTP/2 is a binary -/// protocol), which can be understood only be HTTP/2 clients. -pub struct MockHttp2Connector { - /// The list of streams that the connector returns, in the given order. - pub streams: RefCell<Vec<CloneableMockStream>>, -} - -impl MockHttp2Connector { - /// Creates a new `MockHttp2Connector` with no streams. - pub fn new() -> MockHttp2Connector { - MockHttp2Connector { - streams: RefCell::new(Vec::new()), +impl<T: Write> ::vecio::Writev for Async<T> { + fn writev(&mut self, bufs: &[&[u8]]) -> io::Result<usize> { + let cap = bufs.iter().map(|buf| buf.len()).fold(0, |total, next| total + next); + let mut vec = Vec::with_capacity(cap); + for &buf in bufs { + vec.extend(buf); } - } - - /// Adds a new `CloneableMockStream` to the end of the connector's stream queue. - /// - /// Streams are returned in a FIFO manner. - pub fn add_stream(&mut self, stream: CloneableMockStream) { - self.streams.borrow_mut().push(stream); - } - - /// Adds a new response stream that will be placed to the end of the connector's stream queue. - /// - /// Returns a separate `CloneableMockStream` that allows the user to inspect what is written - /// into the original stream. - pub fn new_response_stream(&mut self, status: &[u8], headers: &Headers, body: Option<Vec<u8>>) - -> CloneableMockStream { - let stream = MockStream::new_http2_response(status, headers, body); - let stream = CloneableMockStream::with_stream(stream); - let ret = stream.clone(); - self.add_stream(stream); - - ret - } -} -impl NetworkConnector for MockHttp2Connector { - type Stream = CloneableMockStream; - #[inline] - fn connect(&self, _host: &str, _port: u16, _scheme: &str) - -> ::Result<CloneableMockStream> { - Ok(self.streams.borrow_mut().remove(0)) + self.write(&vec) } } -#[derive(Debug, Default)] -pub struct MockSsl; +impl ::std::ops::Deref for Async<Buf> { + type Target = [u8]; -impl<T: NetworkStream + Send + Clone> SslClient<T> for MockSsl { - type Stream = T; - fn wrap_client(&self, stream: T, _host: &str) -> ::Result<T> { - Ok(stream) + fn deref(&self) -> &[u8] { + &self.inner } } diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -1,412 +1,169 @@ //! A collection of traits abstracting over Listeners and Streams. -use std::any::{Any, TypeId}; -use std::fmt; -use std::io::{self, ErrorKind, Read, Write}; -use std::net::{SocketAddr, ToSocketAddrs, TcpStream, TcpListener, Shutdown}; -use std::mem; +use std::io::{self, Read, Write}; +use std::net::{SocketAddr}; -#[cfg(feature = "openssl")] -pub use self::openssl::{Openssl, OpensslClient}; - -use std::time::Duration; - -use typeable::Typeable; -use traitobject; - -/// The write-status indicating headers have not been written. -pub enum Fresh {} +use rotor::mio::tcp::{TcpStream, TcpListener}; +use rotor::mio::{Selector, Token, Evented, EventSet, PollOpt, TryAccept}; -/// The write-status indicating headers have been written. -pub enum Streaming {} - -/// An abstraction to listen for connections on a certain port. -pub trait NetworkListener: Clone { - /// The stream produced for each connection. - type Stream: NetworkStream + Send + Clone; - - /// Returns an iterator of streams. - fn accept(&mut self) -> ::Result<Self::Stream>; - - /// Get the address this Listener ended up listening on. - fn local_addr(&mut self) -> io::Result<SocketAddr>; +#[cfg(feature = "openssl")] +pub use self::openssl::{Openssl, OpensslStream}; - /// Returns an iterator over incoming connections. - fn incoming(&mut self) -> NetworkConnections<Self> { - NetworkConnections(self) - } -} +#[cfg(feature = "security-framework")] +pub use self::security_framework::{SecureTransport, SecureTransportClient, SecureTransportServer}; -/// An iterator wrapper over a `NetworkAcceptor`. -pub struct NetworkConnections<'a, N: NetworkListener + 'a>(&'a mut N); +/// A trait representing a socket transport that can be used in a Client or Server. +#[cfg(not(windows))] +pub trait Transport: Read + Write + Evented + ::vecio::Writev { + /// Takes a socket error when event polling notices an `events.is_error()`. + fn take_socket_error(&mut self) -> io::Result<()>; -impl<'a, N: NetworkListener + 'a> Iterator for NetworkConnections<'a, N> { - type Item = ::Result<N::Stream>; - fn next(&mut self) -> Option<::Result<N::Stream>> { - Some(self.0.accept()) + /// Returns if the this transport is blocked on read or write. + /// + /// By default, the user will declare whether they wish to wait on read + /// or write events. However, some transports, such as those protected by + /// TLS, may be blocked on reading before it can write, or vice versa. + fn blocked(&self) -> Option<Blocked> { + None } } -/// An abstraction over streams that a `Server` can utilize. -pub trait NetworkStream: Read + Write + Any + Send + Typeable { - /// Get the remote address of the underlying connection. - fn peer_addr(&mut self) -> io::Result<SocketAddr>; - - /// Set the maximum time to wait for a read to complete. - fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()>; - - /// Set the maximum time to wait for a write to complete. - fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()>; - - /// This will be called when Stream should no longer be kept alive. - #[inline] - fn close(&mut self, _how: Shutdown) -> io::Result<()> { - Ok(()) - } - - // Unsure about name and implementation... - - #[doc(hidden)] - fn set_previous_response_expected_no_content(&mut self, _expected: bool) { } +/// A trait representing a socket transport that can be used in a Client or Server. +#[cfg(windows)] +pub trait Transport: Read + Write + Evented { + /// Takes a socket error when event polling notices an `events.is_error()`. + fn take_socket_error(&mut self) -> io::Result<()>; - #[doc(hidden)] - fn previous_response_expected_no_content(&self) -> bool { - false + /// Returns if the this transport is blocked on read or write. + /// + /// By default, the user will declare whether they wish to wait on read + /// or write events. However, some transports, such as those protected by + /// TLS, may be blocked on reading before it can write, or vice versa. + fn blocked(&self) -> Option<Blocked> { + None } } -/// A connector creates a NetworkStream. -pub trait NetworkConnector { - /// Type of `Stream` to create - type Stream: Into<Box<NetworkStream + Send>>; - - /// Connect to a remote address. - fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<Self::Stream>; -} - -impl<T: NetworkStream + Send> From<T> for Box<NetworkStream + Send> { - fn from(s: T) -> Box<NetworkStream + Send> { - Box::new(s) - } +/// Declares when a transport is blocked from any further action, until the +/// corresponding event has occured. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Blocked { + /// Blocked on reading + Read, + /// blocked on writing + Write, } -impl fmt::Debug for Box<NetworkStream + Send> { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.pad("Box<NetworkStream>") +impl Transport for HttpStream { + fn take_socket_error(&mut self) -> io::Result<()> { + self.0.take_socket_error() } } -impl NetworkStream { - unsafe fn downcast_ref_unchecked<T: 'static>(&self) -> &T { - mem::transmute(traitobject::data(self)) - } - - unsafe fn downcast_mut_unchecked<T: 'static>(&mut self) -> &mut T { - mem::transmute(traitobject::data_mut(self)) - } - - unsafe fn downcast_unchecked<T: 'static>(self: Box<NetworkStream>) -> Box<T> { - let raw: *mut NetworkStream = mem::transmute(self); - mem::transmute(traitobject::data_mut(raw)) - } +/// Accepts sockets asynchronously. +pub trait Accept: Evented { + /// The transport type that is accepted. + type Output: Transport; + /// Accept a socket from the listener, if it doesn not block. + fn accept(&self) -> io::Result<Option<Self::Output>>; + /// Return the local `SocketAddr` of this listener. + fn local_addr(&self) -> io::Result<SocketAddr>; } -impl NetworkStream { - /// Is the underlying type in this trait object a `T`? - #[inline] - pub fn is<T: Any>(&self) -> bool { - (*self).get_type() == TypeId::of::<T>() - } +/// An alias to `mio::tcp::TcpStream`. +#[derive(Debug)] +pub struct HttpStream(pub TcpStream); - /// If the underlying type is `T`, get a reference to the contained data. +impl Read for HttpStream { #[inline] - pub fn downcast_ref<T: Any>(&self) -> Option<&T> { - if self.is::<T>() { - Some(unsafe { self.downcast_ref_unchecked() }) - } else { - None - } + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.0.read(buf) } +} - /// If the underlying type is `T`, get a mutable reference to the contained - /// data. +impl Write for HttpStream { #[inline] - pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> { - if self.is::<T>() { - Some(unsafe { self.downcast_mut_unchecked() }) - } else { - None - } + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.0.write(buf) } - /// If the underlying type is `T`, extract it. #[inline] - pub fn downcast<T: Any>(self: Box<NetworkStream>) - -> Result<Box<T>, Box<NetworkStream>> { - if self.is::<T>() { - Ok(unsafe { self.downcast_unchecked() }) - } else { - Err(self) - } - } -} - -impl NetworkStream + Send { - unsafe fn downcast_ref_unchecked<T: 'static>(&self) -> &T { - mem::transmute(traitobject::data(self)) - } - - unsafe fn downcast_mut_unchecked<T: 'static>(&mut self) -> &mut T { - mem::transmute(traitobject::data_mut(self)) - } - - unsafe fn downcast_unchecked<T: 'static>(self: Box<NetworkStream + Send>) -> Box<T> { - let raw: *mut NetworkStream = mem::transmute(self); - mem::transmute(traitobject::data_mut(raw)) + fn flush(&mut self) -> io::Result<()> { + self.0.flush() } } -impl NetworkStream + Send { - /// Is the underlying type in this trait object a `T`? - #[inline] - pub fn is<T: Any>(&self) -> bool { - (*self).get_type() == TypeId::of::<T>() - } - - /// If the underlying type is `T`, get a reference to the contained data. +impl Evented for HttpStream { #[inline] - pub fn downcast_ref<T: Any>(&self) -> Option<&T> { - if self.is::<T>() { - Some(unsafe { self.downcast_ref_unchecked() }) - } else { - None - } + fn register(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> { + self.0.register(selector, token, interest, opts) } - /// If the underlying type is `T`, get a mutable reference to the contained - /// data. #[inline] - pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> { - if self.is::<T>() { - Some(unsafe { self.downcast_mut_unchecked() }) - } else { - None - } + fn reregister(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> { + self.0.reregister(selector, token, interest, opts) } - /// If the underlying type is `T`, extract it. #[inline] - pub fn downcast<T: Any>(self: Box<NetworkStream + Send>) - -> Result<Box<T>, Box<NetworkStream + Send>> { - if self.is::<T>() { - Ok(unsafe { self.downcast_unchecked() }) - } else { - Err(self) - } + fn deregister(&self, selector: &mut Selector) -> io::Result<()> { + self.0.deregister(selector) } } -/// A `NetworkListener` for `HttpStream`s. -pub struct HttpListener(TcpListener); - -impl Clone for HttpListener { +#[cfg(not(windows))] +impl ::vecio::Writev for HttpStream { #[inline] - fn clone(&self) -> HttpListener { - HttpListener(self.0.try_clone().unwrap()) + fn writev(&mut self, bufs: &[&[u8]]) -> io::Result<usize> { + use ::vecio::Rawv; + self.0.writev(bufs) } } -impl From<TcpListener> for HttpListener { - fn from(listener: TcpListener) -> HttpListener { - HttpListener(listener) - } -} +/// An alias to `mio::tcp::TcpListener`. +#[derive(Debug)] +pub struct HttpListener(pub TcpListener); impl HttpListener { - /// Start listening to an address over HTTP. - pub fn new<To: ToSocketAddrs>(addr: To) -> ::Result<HttpListener> { - Ok(HttpListener(try!(TcpListener::bind(addr)))) - } -} - -impl NetworkListener for HttpListener { - type Stream = HttpStream; - - #[inline] - fn accept(&mut self) -> ::Result<HttpStream> { - Ok(HttpStream(try!(self.0.accept()).0)) - } - - #[inline] - fn local_addr(&mut self) -> io::Result<SocketAddr> { - self.0.local_addr() - } -} - -#[cfg(windows)] -impl ::std::os::windows::io::AsRawSocket for HttpListener { - fn as_raw_socket(&self) -> ::std::os::windows::io::RawSocket { - self.0.as_raw_socket() - } -} - -#[cfg(windows)] -impl ::std::os::windows::io::FromRawSocket for HttpListener { - unsafe fn from_raw_socket(sock: ::std::os::windows::io::RawSocket) -> HttpListener { - HttpListener(TcpListener::from_raw_socket(sock)) + /// Bind to a socket address. + pub fn bind(addr: &SocketAddr) -> io::Result<HttpListener> { + TcpListener::bind(addr) + .map(HttpListener) } -} -#[cfg(unix)] -impl ::std::os::unix::io::AsRawFd for HttpListener { - fn as_raw_fd(&self) -> ::std::os::unix::io::RawFd { - self.0.as_raw_fd() + /// Try to duplicate the underlying listening socket. + pub fn try_clone(&self) -> io::Result<HttpListener> { + self.0.try_clone().map(HttpListener) } } -#[cfg(unix)] -impl ::std::os::unix::io::FromRawFd for HttpListener { - unsafe fn from_raw_fd(fd: ::std::os::unix::io::RawFd) -> HttpListener { - HttpListener(TcpListener::from_raw_fd(fd)) - } -} -/// A wrapper around a `TcpStream`. -pub struct HttpStream(pub TcpStream); +impl Accept for HttpListener { + type Output = HttpStream; -impl Clone for HttpStream { #[inline] - fn clone(&self) -> HttpStream { - HttpStream(self.0.try_clone().unwrap()) - } -} - -impl fmt::Debug for HttpStream { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_str("HttpStream(_)") + fn accept(&self) -> io::Result<Option<HttpStream>> { + TryAccept::accept(&self.0).map(|ok| ok.map(HttpStream)) } -} -impl Read for HttpStream { #[inline] - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.0.read(buf) - } -} - -impl Write for HttpStream { - #[inline] - fn write(&mut self, msg: &[u8]) -> io::Result<usize> { - self.0.write(msg) - } - #[inline] - fn flush(&mut self) -> io::Result<()> { - self.0.flush() - } -} - -#[cfg(windows)] -impl ::std::os::windows::io::AsRawSocket for HttpStream { - fn as_raw_socket(&self) -> ::std::os::windows::io::RawSocket { - self.0.as_raw_socket() - } -} - -#[cfg(windows)] -impl ::std::os::windows::io::FromRawSocket for HttpStream { - unsafe fn from_raw_socket(sock: ::std::os::windows::io::RawSocket) -> HttpStream { - HttpStream(TcpStream::from_raw_socket(sock)) - } -} - -#[cfg(unix)] -impl ::std::os::unix::io::AsRawFd for HttpStream { - fn as_raw_fd(&self) -> ::std::os::unix::io::RawFd { - self.0.as_raw_fd() - } -} - -#[cfg(unix)] -impl ::std::os::unix::io::FromRawFd for HttpStream { - unsafe fn from_raw_fd(fd: ::std::os::unix::io::RawFd) -> HttpStream { - HttpStream(TcpStream::from_raw_fd(fd)) + fn local_addr(&self) -> io::Result<SocketAddr> { + self.0.local_addr() } } -impl NetworkStream for HttpStream { +impl Evented for HttpListener { #[inline] - fn peer_addr(&mut self) -> io::Result<SocketAddr> { - self.0.peer_addr() + fn register(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> { + self.0.register(selector, token, interest, opts) } #[inline] - fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.0.set_read_timeout(dur) + fn reregister(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> { + self.0.reregister(selector, token, interest, opts) } #[inline] - fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.0.set_write_timeout(dur) - } - - #[inline] - fn close(&mut self, how: Shutdown) -> io::Result<()> { - match self.0.shutdown(how) { - Ok(_) => Ok(()), - // see https://github.com/hyperium/hyper/issues/508 - Err(ref e) if e.kind() == ErrorKind::NotConnected => Ok(()), - err => err - } - } -} - -/// A connector that will produce HttpStreams. -#[derive(Debug, Clone, Default)] -pub struct HttpConnector; - -impl NetworkConnector for HttpConnector { - type Stream = HttpStream; - - fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<HttpStream> { - let addr = &(host, port); - Ok(try!(match scheme { - "http" => { - debug!("http scheme"); - Ok(HttpStream(try!(TcpStream::connect(addr)))) - }, - _ => { - Err(io::Error::new(io::ErrorKind::InvalidInput, - "Invalid scheme for Http")) - } - })) - } -} - -/// A closure as a connector used to generate `TcpStream`s per request -/// -/// # Example -/// -/// Basic example: -/// -/// ```norun -/// Client::with_connector(|addr: &str, port: u16, scheme: &str| { -/// TcpStream::connect(&(addr, port)) -/// }); -/// ``` -/// -/// Example using `TcpBuilder` from the net2 crate if you want to configure your source socket: -/// -/// ```norun -/// Client::with_connector(|addr: &str, port: u16, scheme: &str| { -/// let b = try!(TcpBuilder::new_v4()); -/// try!(b.bind("127.0.0.1:0")); -/// b.connect(&(addr, port)) -/// }); -/// ``` -impl<F> NetworkConnector for F where F: Fn(&str, u16, &str) -> io::Result<TcpStream> { - type Stream = HttpStream; - - fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<HttpStream> { - Ok(HttpStream(try!((*self)(host, port, scheme)))) + fn deregister(&self, selector: &mut Selector) -> io::Result<()> { + self.0.deregister(selector) } } diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -415,7 +172,7 @@ impl<F> NetworkConnector for F where F: Fn(&str, u16, &str) -> io::Result<TcpStr /// Use `SslClient` and `SslServer` instead. pub trait Ssl { /// The protected stream. - type Stream: NetworkStream + Send + Clone; + type Stream: Transport; /// Wrap a client stream with SSL. fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream>; /// Wrap a server stream with SSL. diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -423,22 +180,22 @@ pub trait Ssl { } /// An abstraction to allow any SSL implementation to be used with client-side HttpsStreams. -pub trait SslClient<T: NetworkStream + Send + Clone = HttpStream> { +pub trait SslClient { /// The protected stream. - type Stream: NetworkStream + Send + Clone; + type Stream: Transport; /// Wrap a client stream with SSL. - fn wrap_client(&self, stream: T, host: &str) -> ::Result<Self::Stream>; + fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream>; } /// An abstraction to allow any SSL implementation to be used with server-side HttpsStreams. -pub trait SslServer<T: NetworkStream + Send + Clone = HttpStream> { +pub trait SslServer { /// The protected stream. - type Stream: NetworkStream + Send + Clone; + type Stream: Transport; /// Wrap a server stream with SSL. - fn wrap_server(&self, stream: T) -> ::Result<Self::Stream>; + fn wrap_server(&self, stream: HttpStream) -> ::Result<Self::Stream>; } -impl<S: Ssl> SslClient<HttpStream> for S { +impl<S: Ssl> SslClient for S { type Stream = <S as Ssl>::Stream; fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream> { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -446,7 +203,7 @@ impl<S: Ssl> SslClient<HttpStream> for S { } } -impl<S: Ssl> SslServer<HttpStream> for S { +impl<S: Ssl> SslServer for S { type Stream = <S as Ssl>::Stream; fn wrap_server(&self, stream: HttpStream) -> ::Result<Self::Stream> { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -454,16 +211,16 @@ impl<S: Ssl> SslServer<HttpStream> for S { } } -/// A stream over the HTTP protocol, possibly protected by SSL. -#[derive(Debug, Clone)] -pub enum HttpsStream<S: NetworkStream> { +/// A stream over the HTTP protocol, possibly protected by TLS. +#[derive(Debug)] +pub enum HttpsStream<S: Transport> { /// A plain text stream. Http(HttpStream), - /// A stream protected by SSL. + /// A stream protected by TLS. Https(S) } -impl<S: NetworkStream> Read for HttpsStream<S> { +impl<S: Transport> Read for HttpsStream<S> { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match *self { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -473,7 +230,7 @@ impl<S: NetworkStream> Read for HttpsStream<S> { } } -impl<S: NetworkStream> Write for HttpsStream<S> { +impl<S: Transport> Write for HttpsStream<S> { #[inline] fn write(&mut self, msg: &[u8]) -> io::Result<usize> { match *self { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -491,58 +248,100 @@ impl<S: NetworkStream> Write for HttpsStream<S> { } } -impl<S: NetworkStream> NetworkStream for HttpsStream<S> { +#[cfg(not(windows))] +impl<S: Transport> ::vecio::Writev for HttpsStream<S> { #[inline] - fn peer_addr(&mut self) -> io::Result<SocketAddr> { + fn writev(&mut self, bufs: &[&[u8]]) -> io::Result<usize> { match *self { - HttpsStream::Http(ref mut s) => s.peer_addr(), - HttpsStream::Https(ref mut s) => s.peer_addr() + HttpsStream::Http(ref mut s) => s.writev(bufs), + HttpsStream::Https(ref mut s) => s.writev(bufs) } } +} + + +#[cfg(unix)] +impl ::std::os::unix::io::AsRawFd for HttpStream { + #[inline] + fn as_raw_fd(&self) -> ::std::os::unix::io::RawFd { + self.0.as_raw_fd() + } +} +#[cfg(unix)] +impl<S: Transport + ::std::os::unix::io::AsRawFd> ::std::os::unix::io::AsRawFd for HttpsStream<S> { #[inline] - fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + fn as_raw_fd(&self) -> ::std::os::unix::io::RawFd { match *self { - HttpsStream::Http(ref inner) => inner.0.set_read_timeout(dur), - HttpsStream::Https(ref inner) => inner.set_read_timeout(dur) + HttpsStream::Http(ref s) => s.as_raw_fd(), + HttpsStream::Https(ref s) => s.as_raw_fd(), } } +} +impl<S: Transport> Evented for HttpsStream<S> { #[inline] - fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + fn register(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> { match *self { - HttpsStream::Http(ref inner) => inner.0.set_write_timeout(dur), - HttpsStream::Https(ref inner) => inner.set_write_timeout(dur) + HttpsStream::Http(ref s) => s.register(selector, token, interest, opts), + HttpsStream::Https(ref s) => s.register(selector, token, interest, opts), } } #[inline] - fn close(&mut self, how: Shutdown) -> io::Result<()> { + fn reregister(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> { match *self { - HttpsStream::Http(ref mut s) => s.close(how), - HttpsStream::Https(ref mut s) => s.close(how) + HttpsStream::Http(ref s) => s.reregister(selector, token, interest, opts), + HttpsStream::Https(ref s) => s.reregister(selector, token, interest, opts), + } + } + + #[inline] + fn deregister(&self, selector: &mut Selector) -> io::Result<()> { + match *self { + HttpsStream::Http(ref s) => s.deregister(selector), + HttpsStream::Https(ref s) => s.deregister(selector), + } + } +} + +impl<S: Transport> Transport for HttpsStream<S> { + #[inline] + fn take_socket_error(&mut self) -> io::Result<()> { + match *self { + HttpsStream::Http(ref mut s) => s.take_socket_error(), + HttpsStream::Https(ref mut s) => s.take_socket_error(), + } + } + + #[inline] + fn blocked(&self) -> Option<Blocked> { + match *self { + HttpsStream::Http(ref s) => s.blocked(), + HttpsStream::Https(ref s) => s.blocked(), } } } /// A Http Listener over SSL. -#[derive(Clone)] +#[derive(Debug)] pub struct HttpsListener<S: SslServer> { - listener: HttpListener, + listener: TcpListener, ssl: S, } -impl<S: Ssl> HttpsListener<S> { +impl<S: SslServer> HttpsListener<S> { /// Start listening to an address over HTTPS. - pub fn new<To: ToSocketAddrs>(addr: To, ssl: S) -> ::Result<HttpsListener<S>> { - HttpListener::new(addr).map(|l| HttpsListener { + #[inline] + pub fn new(addr: &SocketAddr, ssl: S) -> io::Result<HttpsListener<S>> { + TcpListener::bind(addr).map(|l| HttpsListener { listener: l, ssl: ssl }) } /// Construct an HttpsListener from a bound `TcpListener`. - pub fn with_listener(listener: HttpListener, ssl: S) -> HttpsListener<S> { + pub fn with_listener(listener: TcpListener, ssl: S) -> HttpsListener<S> { HttpsListener { listener: listener, ssl: ssl diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -550,56 +349,52 @@ impl<S: Ssl> HttpsListener<S> { } } -impl<S: SslServer + Clone> NetworkListener for HttpsListener<S> { - type Stream = S::Stream; +impl<S: SslServer> Accept for HttpsListener<S> { + type Output = S::Stream; #[inline] - fn accept(&mut self) -> ::Result<S::Stream> { - self.listener.accept().and_then(|s| self.ssl.wrap_server(s)) + fn accept(&self) -> io::Result<Option<S::Stream>> { + self.listener.accept().and_then(|s| match s { + Some((s, _)) => self.ssl.wrap_server(HttpStream(s)).map(Some).map_err(|e| { + match e { + ::Error::Io(e) => e, + _ => io::Error::new(io::ErrorKind::Other, e), + + } + }), + None => Ok(None), + }) } #[inline] - fn local_addr(&mut self) -> io::Result<SocketAddr> { + fn local_addr(&self) -> io::Result<SocketAddr> { self.listener.local_addr() } } -/// A connector that can protect HTTP streams using SSL. -#[derive(Debug, Default)] -pub struct HttpsConnector<S: SslClient, C: NetworkConnector = HttpConnector> { - ssl: S, - connector: C, -} - -impl<S: SslClient> HttpsConnector<S, HttpConnector> { - /// Create a new connector using the provided SSL implementation. - pub fn new(s: S) -> HttpsConnector<S, HttpConnector> { - HttpsConnector::with_connector(s, HttpConnector) +impl<S: SslServer> Evented for HttpsListener<S> { + #[inline] + fn register(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> { + self.listener.register(selector, token, interest, opts) } -} -impl<S: SslClient, C: NetworkConnector> HttpsConnector<S, C> { - /// Create a new connector using the provided SSL implementation. - pub fn with_connector(s: S, connector: C) -> HttpsConnector<S, C> { - HttpsConnector { ssl: s, connector: connector } + #[inline] + fn reregister(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> { + self.listener.reregister(selector, token, interest, opts) } -} -impl<S: SslClient, C: NetworkConnector<Stream=HttpStream>> NetworkConnector for HttpsConnector<S, C> { - type Stream = HttpsStream<S::Stream>; - - fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<Self::Stream> { - let stream = try!(self.connector.connect(host, port, "http")); - if scheme == "https" { - debug!("https scheme"); - self.ssl.wrap_client(stream, host).map(HttpsStream::Https) - } else { - Ok(HttpsStream::Http(stream)) - } + #[inline] + fn deregister(&self, selector: &mut Selector) -> io::Result<()> { + self.listener.deregister(selector) } } +fn _assert_transport() { + fn _assert<T: Transport>() {} + _assert::<HttpsStream<HttpStream>>(); +} +/* #[cfg(all(not(feature = "openssl"), not(feature = "security-framework")))] #[doc(hidden)] pub type DefaultConnector = HttpConnector; diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -611,19 +406,24 @@ pub type DefaultConnector = HttpsConnector<self::openssl::OpensslClient>; #[cfg(all(feature = "security-framework", not(feature = "openssl")))] pub type DefaultConnector = HttpsConnector<self::security_framework::ClientWrapper>; +#[doc(hidden)] +pub type DefaultTransport = <DefaultConnector as Connect>::Output; +*/ + #[cfg(feature = "openssl")] mod openssl { - use std::io; - use std::net::{SocketAddr, Shutdown}; + use std::io::{self, Write}; use std::path::Path; - use std::sync::Arc; - use std::time::Duration; - use openssl::ssl::{Ssl, SslContext, SslStream, SslMethod, SSL_VERIFY_NONE, SSL_VERIFY_PEER, SSL_OP_NO_SSLV2, SSL_OP_NO_SSLV3, SSL_OP_NO_COMPRESSION}; + use rotor::mio::{Selector, Token, Evented, EventSet, PollOpt}; + + use openssl::ssl::{Ssl, SslContext, SslStream, SslMethod, SSL_VERIFY_PEER, SSL_OP_NO_SSLV2, SSL_OP_NO_SSLV3, SSL_OP_NO_COMPRESSION}; use openssl::ssl::error::StreamError as SslIoError; use openssl::ssl::error::SslError; + use openssl::ssl::error::Error as OpensslError; use openssl::x509::X509FileType; - use super::{NetworkStream, HttpStream}; + + use super::{HttpStream, Blocked}; /// An implementation of `Ssl` for OpenSSL. /// diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -634,7 +434,7 @@ mod openssl { /// use hyper::net::Openssl; /// /// let ssl = Openssl::with_cert_and_key("/home/foo/cert", "/home/foo/key").unwrap(); - /// Server::https("0.0.0.0:443", ssl).unwrap(); + /// Server::https(&"0.0.0.0:443".parse().unwrap(), ssl).unwrap(); /// ``` /// /// For complete control, create a `SslContext` with the options you desire diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -642,7 +442,7 @@ mod openssl { #[derive(Debug, Clone)] pub struct Openssl { /// The `SslContext` from openssl crate. - pub context: Arc<SslContext> + pub context: SslContext } /// A client-specific implementation of OpenSSL. diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -662,26 +462,28 @@ mod openssl { } - impl<T: NetworkStream + Send + Clone> super::SslClient<T> for OpensslClient { - type Stream = SslStream<T>; + impl super::SslClient for OpensslClient { + type Stream = OpensslStream<HttpStream>; - fn wrap_client(&self, stream: T, host: &str) -> ::Result<Self::Stream> { + fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream> { let mut ssl = try!(Ssl::new(&self.0)); try!(ssl.set_hostname(host)); let host = host.to_owned(); ssl.set_verify_callback(SSL_VERIFY_PEER, move |p, x| ::openssl_verify::verify_callback(&host, p, x)); - SslStream::connect(ssl, stream).map_err(From::from) + SslStream::connect(ssl, stream) + .map(openssl_stream) + .map_err(From::from) } } impl Default for Openssl { fn default() -> Openssl { Openssl { - context: Arc::new(SslContext::new(SslMethod::Sslv23).unwrap_or_else(|e| { + context: SslContext::new(SslMethod::Sslv23).unwrap_or_else(|e| { // if we cannot create a SslContext, that's because of a // serious problem. just crash. panic!("{}", e) - })) + }) } } } diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -691,26 +493,27 @@ mod openssl { pub fn with_cert_and_key<C, K>(cert: C, key: K) -> Result<Openssl, SslError> where C: AsRef<Path>, K: AsRef<Path> { let mut ctx = try!(SslContext::new(SslMethod::Sslv23)); - try!(ctx.set_cipher_list("DEFAULT")); + try!(ctx.set_cipher_list("ALL!EXPORT!EXPORT40!EXPORT56!aNULL!LOW!RC4@STRENGTH")); try!(ctx.set_certificate_file(cert.as_ref(), X509FileType::PEM)); try!(ctx.set_private_key_file(key.as_ref(), X509FileType::PEM)); - ctx.set_verify(SSL_VERIFY_NONE, None); - Ok(Openssl { context: Arc::new(ctx) }) + Ok(Openssl { context: ctx }) } } impl super::Ssl for Openssl { - type Stream = SslStream<HttpStream>; + type Stream = OpensslStream<HttpStream>; fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream> { let ssl = try!(Ssl::new(&self.context)); try!(ssl.set_hostname(host)); - SslStream::connect(ssl, stream).map_err(From::from) + SslStream::connect(ssl, stream) + .map(openssl_stream) + .map_err(From::from) } fn wrap_server(&self, stream: HttpStream) -> ::Result<Self::Stream> { - match SslStream::accept(&*self.context, stream) { - Ok(ssl_stream) => Ok(ssl_stream), + match SslStream::accept(&self.context, stream) { + Ok(ssl_stream) => Ok(openssl_stream(ssl_stream)), Err(SslIoError(e)) => { Err(io::Error::new(io::ErrorKind::ConnectionAborted, e).into()) }, diff --git a/src/server/listener.rs /dev/null --- a/src/server/listener.rs +++ /dev/null @@ -1,79 +0,0 @@ -use std::sync::{Arc, mpsc}; -use std::thread; - -use net::NetworkListener; - -pub struct ListenerPool<A: NetworkListener> { - acceptor: A -} - -impl<A: NetworkListener + Send + 'static> ListenerPool<A> { - /// Create a thread pool to manage the acceptor. - pub fn new(acceptor: A) -> ListenerPool<A> { - ListenerPool { acceptor: acceptor } - } - - /// Runs the acceptor pool. Blocks until the acceptors are closed. - /// - /// ## Panics - /// - /// Panics if threads == 0. - pub fn accept<F>(self, work: F, threads: usize) - where F: Fn(A::Stream) + Send + Sync + 'static { - assert!(threads != 0, "Can't accept on 0 threads."); - - let (super_tx, supervisor_rx) = mpsc::channel(); - - let work = Arc::new(work); - - // Begin work. - for _ in 0..threads { - spawn_with(super_tx.clone(), work.clone(), self.acceptor.clone()) - } - - // Monitor for panics. - // FIXME(reem): This won't ever exit since we still have a super_tx handle. - for _ in supervisor_rx.iter() { - spawn_with(super_tx.clone(), work.clone(), self.acceptor.clone()); - } - } -} - -fn spawn_with<A, F>(supervisor: mpsc::Sender<()>, work: Arc<F>, mut acceptor: A) -where A: NetworkListener + Send + 'static, - F: Fn(<A as NetworkListener>::Stream) + Send + Sync + 'static { - thread::spawn(move || { - let _sentinel = Sentinel::new(supervisor, ()); - - loop { - match acceptor.accept() { - Ok(stream) => work(stream), - Err(e) => { - error!("Connection failed: {}", e); - } - } - } - }); -} - -struct Sentinel<T: Send + 'static> { - value: Option<T>, - supervisor: mpsc::Sender<T>, -} - -impl<T: Send + 'static> Sentinel<T> { - fn new(channel: mpsc::Sender<T>, data: T) -> Sentinel<T> { - Sentinel { - value: Some(data), - supervisor: channel, - } - } -} - -impl<T: Send + 'static> Drop for Sentinel<T> { - fn drop(&mut self) { - // Respawn ourselves - let _ = self.supervisor.send(self.value.take().unwrap()); - } -} - diff --git /dev/null b/src/server/message.rs new file mode 100644 --- /dev/null +++ b/src/server/message.rs @@ -0,0 +1,58 @@ +use std::marker::PhantomData; + + +use http::{self, Next}; +use net::Transport; + +use super::{Handler, request, response}; + +/// A MessageHandler for a Server. +/// +/// This should be really thin glue between http::MessageHandler and +/// server::Handler, but largely just providing the proper types one +/// would expect in a Server Handler. +pub struct Message<H: Handler<T>, T: Transport> { + handler: H, + _marker: PhantomData<T> +} + +impl<H: Handler<T>, T: Transport> Message<H, T> { + pub fn new(handler: H) -> Message<H, T> { + Message { + handler: handler, + _marker: PhantomData, + } + } +} + +impl<H: Handler<T>, T: Transport> http::MessageHandler<T> for Message<H, T> { + type Message = http::ServerMessage; + + fn on_incoming(&mut self, head: http::RequestHead) -> Next { + trace!("on_incoming {:?}", head); + let req = request::new(head); + self.handler.on_request(req) + } + + fn on_decode(&mut self, transport: &mut http::Decoder<T>) -> Next { + self.handler.on_request_readable(transport) + } + + fn on_outgoing(&mut self, head: &mut http::MessageHead<::status::StatusCode>) -> Next { + let mut res = response::new(head); + self.handler.on_response(&mut res) + } + + fn on_encode(&mut self, transport: &mut http::Encoder<T>) -> Next { + self.handler.on_response_writable(transport) + } + + fn on_error(&mut self, error: ::Error) -> Next { + self.handler.on_error(error) + } + + fn on_remove(self, transport: T) { + self.handler.on_remove(transport); + } +} + diff --git a/src/status.rs b/src/status.rs --- a/src/status.rs +++ b/src/status.rs @@ -547,6 +547,12 @@ impl Ord for StatusCode { } } +impl Default for StatusCode { + fn default() -> StatusCode { + StatusCode::Ok + } +} + /// The class of an HTTP `status-code`. /// /// [RFC 7231, section 6 (Response Status Codes)](https://tools.ietf.org/html/rfc7231#section-6): diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -21,7 +21,7 @@ use Error; /// > / authority-form /// > / asterisk-form /// > ``` -#[derive(Debug, PartialEq, Clone)] +#[derive(Debug, PartialEq, Eq, Hash, Clone)] pub enum RequestUri { /// The most common request target, an absolute path and optional query. /// diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -50,6 +50,12 @@ pub enum RequestUri { Star, } +impl Default for RequestUri { + fn default() -> RequestUri { + RequestUri::Star + } +} + impl FromStr for RequestUri { type Err = Error; diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -67,7 +73,7 @@ impl FromStr for RequestUri { let mut temp = "http://".to_owned(); temp.push_str(s); try!(Url::parse(&temp[..])); - todo!("compare vs u.authority()"); + //TODO: compare vs u.authority()? Ok(RequestUri::Authority(s.to_owned())) } } diff --git a/src/version.rs b/src/version.rs --- a/src/version.rs +++ b/src/version.rs @@ -4,7 +4,7 @@ //! the `HttpVersion` enum. use std::fmt; -use self::HttpVersion::{Http09, Http10, Http11, Http20}; +use self::HttpVersion::{Http09, Http10, Http11, H2, H2c}; /// Represents a version of the HTTP spec. #[derive(PartialEq, PartialOrd, Copy, Clone, Eq, Ord, Hash, Debug)] diff --git a/src/version.rs b/src/version.rs --- a/src/version.rs +++ b/src/version.rs @@ -15,8 +15,10 @@ pub enum HttpVersion { Http10, /// `HTTP/1.1` Http11, - /// `HTTP/2.0` - Http20 + /// `HTTP/2.0` over TLS + H2, + /// `HTTP/2.0` over cleartext + H2c, } impl fmt::Display for HttpVersion { diff --git a/src/version.rs b/src/version.rs --- a/src/version.rs +++ b/src/version.rs @@ -25,7 +27,14 @@ impl fmt::Display for HttpVersion { Http09 => "HTTP/0.9", Http10 => "HTTP/1.0", Http11 => "HTTP/1.1", - Http20 => "HTTP/2.0", + H2 => "h2", + H2c => "h2c", }) } } + +impl Default for HttpVersion { + fn default() -> HttpVersion { + Http11 + } +}
diff --git a/benches/client.rs /dev/null --- a/benches/client.rs +++ /dev/null @@ -1,111 +0,0 @@ -#![deny(warnings)] -#![feature(test)] -extern crate hyper; - -extern crate test; - -use std::fmt; -use std::io::{self, Read, Write, Cursor}; -use std::net::SocketAddr; -use std::time::Duration; - -use hyper::net; - -static README: &'static [u8] = include_bytes!("../README.md"); - -struct MockStream { - read: Cursor<Vec<u8>> -} - -impl MockStream { - fn new() -> MockStream { - let head = b"HTTP/1.1 200 OK\r\nServer: Mock\r\n\r\n"; - let mut res = head.to_vec(); - res.extend_from_slice(README); - MockStream { - read: Cursor::new(res) - } - } -} - -impl Clone for MockStream { - fn clone(&self) -> MockStream { - MockStream { - read: Cursor::new(self.read.get_ref().clone()) - } - } -} - -impl Read for MockStream { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.read.read(buf) - } -} - -impl Write for MockStream { - fn write(&mut self, msg: &[u8]) -> io::Result<usize> { - // we're mocking, what do we care. - Ok(msg.len()) - } - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -#[derive(Clone, Debug)] -struct Foo; - -impl hyper::header::Header for Foo { - fn header_name() -> &'static str { - "x-foo" - } - fn parse_header(_: &[Vec<u8>]) -> hyper::Result<Foo> { - Err(hyper::Error::Header) - } -} - -impl hyper::header::HeaderFormat for Foo { - fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.write_str("Bar") - } -} - -impl net::NetworkStream for MockStream { - fn peer_addr(&mut self) -> io::Result<SocketAddr> { - Ok("127.0.0.1:1337".parse().unwrap()) - } - fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> { - // can't time out - Ok(()) - } - fn set_write_timeout(&self, _: Option<Duration>) -> io::Result<()> { - // can't time out - Ok(()) - } -} - -struct MockConnector; - -impl net::NetworkConnector for MockConnector { - type Stream = MockStream; - fn connect(&self, _: &str, _: u16, _: &str) -> hyper::Result<MockStream> { - Ok(MockStream::new()) - } -} - -#[bench] -fn bench_mock_hyper(b: &mut test::Bencher) { - let url = "http://127.0.0.1:1337/"; - b.iter(|| { - let mut req = hyper::client::Request::with_connector( - hyper::Get, hyper::Url::parse(url).unwrap(), &MockConnector - ).unwrap(); - req.headers_mut().set(Foo); - - let mut s = String::new(); - req - .start().unwrap() - .send().unwrap() - .read_to_string(&mut s).unwrap() - }); -} diff --git a/src/buffer.rs /dev/null --- a/src/buffer.rs +++ /dev/null @@ -1,164 +0,0 @@ -use std::cmp; -use std::io::{self, Read, BufRead}; - -pub struct BufReader<R> { - inner: R, - buf: Vec<u8>, - pos: usize, - cap: usize, -} - -const INIT_BUFFER_SIZE: usize = 4096; -const MAX_BUFFER_SIZE: usize = 8192 + 4096 * 100; - -impl<R: Read> BufReader<R> { - #[inline] - pub fn new(rdr: R) -> BufReader<R> { - BufReader::with_capacity(rdr, INIT_BUFFER_SIZE) - } - - #[inline] - pub fn with_capacity(rdr: R, cap: usize) -> BufReader<R> { - BufReader { - inner: rdr, - buf: vec![0; cap], - pos: 0, - cap: 0, - } - } - - #[inline] - pub fn get_ref(&self) -> &R { &self.inner } - - #[inline] - pub fn get_mut(&mut self) -> &mut R { &mut self.inner } - - #[inline] - pub fn get_buf(&self) -> &[u8] { - if self.pos < self.cap { - trace!("get_buf [u8; {}][{}..{}]", self.buf.len(), self.pos, self.cap); - &self.buf[self.pos..self.cap] - } else { - trace!("get_buf []"); - &[] - } - } - - #[inline] - pub fn into_inner(self) -> R { self.inner } - - #[inline] - pub fn read_into_buf(&mut self) -> io::Result<usize> { - self.maybe_reserve(); - let v = &mut self.buf; - trace!("read_into_buf buf[{}..{}]", self.cap, v.len()); - if self.cap < v.capacity() { - let nread = try!(self.inner.read(&mut v[self.cap..])); - self.cap += nread; - Ok(nread) - } else { - trace!("read_into_buf at full capacity"); - Ok(0) - } - } - - #[inline] - fn maybe_reserve(&mut self) { - let cap = self.buf.capacity(); - if self.cap == cap && cap < MAX_BUFFER_SIZE { - self.buf.reserve(cmp::min(cap * 4, MAX_BUFFER_SIZE) - cap); - let new = self.buf.capacity() - self.buf.len(); - trace!("reserved {}", new); - unsafe { grow_zerofill(&mut self.buf, new) } - } - } -} - -#[inline] -unsafe fn grow_zerofill(buf: &mut Vec<u8>, additional: usize) { - use std::ptr; - let len = buf.len(); - buf.set_len(len + additional); - ptr::write_bytes(buf.as_mut_ptr().offset(len as isize), 0, additional); -} - -impl<R: Read> Read for BufReader<R> { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - if self.cap == self.pos && buf.len() >= self.buf.len() { - return self.inner.read(buf); - } - let nread = { - let mut rem = try!(self.fill_buf()); - try!(rem.read(buf)) - }; - self.consume(nread); - Ok(nread) - } -} - -impl<R: Read> BufRead for BufReader<R> { - fn fill_buf(&mut self) -> io::Result<&[u8]> { - if self.pos == self.cap { - self.cap = try!(self.inner.read(&mut self.buf)); - self.pos = 0; - } - Ok(&self.buf[self.pos..self.cap]) - } - - #[inline] - fn consume(&mut self, amt: usize) { - self.pos = cmp::min(self.pos + amt, self.cap); - if self.pos == self.cap { - self.pos = 0; - self.cap = 0; - } - } -} - -#[cfg(test)] -mod tests { - - use std::io::{self, Read, BufRead}; - use super::BufReader; - - struct SlowRead(u8); - - impl Read for SlowRead { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - let state = self.0; - self.0 += 1; - (&match state % 3 { - 0 => b"foo", - 1 => b"bar", - _ => b"baz", - }[..]).read(buf) - } - } - - #[test] - fn test_consume_and_get_buf() { - let mut rdr = BufReader::new(SlowRead(0)); - rdr.read_into_buf().unwrap(); - rdr.consume(1); - assert_eq!(rdr.get_buf(), b"oo"); - rdr.read_into_buf().unwrap(); - rdr.read_into_buf().unwrap(); - assert_eq!(rdr.get_buf(), b"oobarbaz"); - rdr.consume(5); - assert_eq!(rdr.get_buf(), b"baz"); - rdr.consume(3); - assert_eq!(rdr.get_buf(), b""); - assert_eq!(rdr.pos, 0); - assert_eq!(rdr.cap, 0); - } - - #[test] - fn test_resize() { - let raw = b"hello world"; - let mut rdr = BufReader::with_capacity(&raw[..], 5); - rdr.read_into_buf().unwrap(); - assert_eq!(rdr.get_buf(), b"hello"); - rdr.read_into_buf().unwrap(); - assert_eq!(rdr.get_buf(), b"hello world"); - } -} diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -1,600 +1,607 @@ //! HTTP Client //! -//! # Usage -//! -//! The `Client` API is designed for most people to make HTTP requests. -//! It utilizes the lower level `Request` API. -//! -//! ## GET -//! -//! ```no_run -//! # use hyper::Client; -//! let client = Client::new(); -//! -//! let res = client.get("http://example.domain").send().unwrap(); -//! assert_eq!(res.status, hyper::Ok); -//! ``` -//! -//! The returned value is a `Response`, which provides easy access to -//! the `status`, the `headers`, and the response body via the `Read` -//! trait. -//! -//! ## POST -//! -//! ```no_run -//! # use hyper::Client; -//! let client = Client::new(); -//! -//! let res = client.post("http://example.domain") -//! .body("foo=bar") -//! .send() -//! .unwrap(); -//! assert_eq!(res.status, hyper::Ok); -//! ``` -//! -//! # Sync -//! -//! The `Client` implements `Sync`, so you can share it among multiple threads -//! and make multiple requests simultaneously. -//! -//! ```no_run -//! # use hyper::Client; -//! use std::sync::Arc; -//! use std::thread; -//! -//! // Note: an Arc is used here because `thread::spawn` creates threads that -//! // can outlive the main thread, so we must use reference counting to keep -//! // the Client alive long enough. Scoped threads could skip the Arc. -//! let client = Arc::new(Client::new()); -//! let clone1 = client.clone(); -//! let clone2 = client.clone(); -//! thread::spawn(move || { -//! clone1.get("http://example.domain").send().unwrap(); -//! }); -//! thread::spawn(move || { -//! clone2.post("http://example.domain/post").body("foo=bar").send().unwrap(); -//! }); -//! ``` -use std::borrow::Cow; -use std::default::Default; -use std::io::{self, copy, Read}; -use std::fmt; +//! The HTTP `Client` uses asynchronous IO, and utilizes the `Handler` trait +//! to convey when IO events are available for a given request. +use std::collections::HashMap; +use std::fmt; +use std::marker::PhantomData; +use std::sync::mpsc; +use std::thread; use std::time::Duration; -use url::Url; -use url::ParseError as UrlError; +use rotor::{self, Scope, EventSet, PollOpt}; -use header::{Headers, Header, HeaderFormat}; -use header::{ContentLength, Host, Location}; -use method::Method; -use net::{NetworkConnector, NetworkStream}; -use Error; +use header::Host; +use http::{self, Next, RequestHead}; +use net::Transport; +use uri::RequestUri; +use {Url}; -use self::proxy::tunnel; -pub use self::pool::Pool; +pub use self::connect::{Connect, DefaultConnector, HttpConnector, HttpsConnector, DefaultTransport}; pub use self::request::Request; pub use self::response::Response; -mod proxy; -pub mod pool; -pub mod request; -pub mod response; +mod connect; +mod dns; +//mod pool; +mod request; +mod response; -use http::Protocol; -use http::h1::Http11Protocol; - -/// A Client to use additional features with Requests. -/// -/// Clients can handle things such as: redirect policy, connection pooling. -pub struct Client { - protocol: Box<Protocol + Send + Sync>, - redirect_policy: RedirectPolicy, - read_timeout: Option<Duration>, - write_timeout: Option<Duration>, - proxy: Option<(Cow<'static, str>, u16)> +/// A Client to make outgoing HTTP requests. +pub struct Client<H> { + //handle: Option<thread::JoinHandle<()>>, + tx: http::channel::Sender<Notify<H>>, } -impl fmt::Debug for Client { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("Client") - .field("redirect_policy", &self.redirect_policy) - .field("read_timeout", &self.read_timeout) - .field("write_timeout", &self.write_timeout) - .field("proxy", &self.proxy) - .finish() +impl<H> Clone for Client<H> { + fn clone(&self) -> Client<H> { + Client { + tx: self.tx.clone() + } } } -impl Client { +impl<H> fmt::Debug for Client<H> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad("Client") + } +} - /// Create a new Client. - pub fn new() -> Client { - Client::with_pool_config(Default::default()) +impl<H> Client<H> { + /// Configure a Client. + /// + /// # Example + /// + /// ```dont_run + /// # use hyper::Client; + /// let client = Client::configure() + /// .keep_alive(true) + /// .max_sockets(10_000) + /// .build().unwrap(); + /// ``` + #[inline] + pub fn configure() -> Config<DefaultConnector> { + Config::default() } - /// Create a new Client with a configured Pool Config. - pub fn with_pool_config(config: pool::Config) -> Client { - Client::with_connector(Pool::new(config)) + /*TODO + pub fn http() -> Config<HttpConnector> { + } - pub fn with_http_proxy<H>(host: H, port: u16) -> Client - where H: Into<Cow<'static, str>> { - let host = host.into(); - let proxy = tunnel((host.clone(), port)); - let mut client = Client::with_connector(Pool::with_connector(Default::default(), proxy)); - client.proxy = Some((host, port)); - client + pub fn https() -> Config<HttpsConnector> { + } + */ +} - /// Create a new client with a specific connector. - pub fn with_connector<C, S>(connector: C) -> Client - where C: NetworkConnector<Stream=S> + Send + Sync + 'static, S: NetworkStream + Send { - Client::with_protocol(Http11Protocol::with_connector(connector)) +impl<H: Handler<<DefaultConnector as Connect>::Output>> Client<H> { + /// Create a new Client with the default config. + #[inline] + pub fn new() -> ::Result<Client<H>> { + Client::<H>::configure().build() } +} - /// Create a new client with a specific `Protocol`. - pub fn with_protocol<P: Protocol + Send + Sync + 'static>(protocol: P) -> Client { - Client { - protocol: Box::new(protocol), - redirect_policy: Default::default(), - read_timeout: None, - write_timeout: None, - proxy: None, +impl<H: Send> Client<H> { + /// Create a new client with a specific connector. + fn configured<T, C>(config: Config<C>) -> ::Result<Client<H>> + where H: Handler<T>, + T: Transport, + C: Connect<Output=T> + Send + 'static { + let mut rotor_config = rotor::Config::new(); + rotor_config.slab_capacity(config.max_sockets); + rotor_config.mio().notify_capacity(config.max_sockets); + let keep_alive = config.keep_alive; + let connect_timeout = config.connect_timeout; + let mut loop_ = try!(rotor::Loop::new(&rotor_config)); + let mut notifier = None; + let mut connector = config.connector; + { + let not = &mut notifier; + loop_.add_machine_with(move |scope| { + let (tx, rx) = http::channel::new(scope.notifier()); + let (dns_tx, dns_rx) = http::channel::share(&tx); + *not = Some(tx); + connector.register(Registration { + notify: (dns_tx, dns_rx), + }); + rotor::Response::ok(ClientFsm::Connector(connector, rx)) + }).unwrap(); } - } - /// Set the RedirectPolicy. - pub fn set_redirect_policy(&mut self, policy: RedirectPolicy) { - self.redirect_policy = policy; - } + let notifier = notifier.expect("loop.add_machine_with failed"); + let _handle = try!(thread::Builder::new().name("hyper-client".to_owned()).spawn(move || { + loop_.run(Context { + connect_timeout: connect_timeout, + keep_alive: keep_alive, + queue: HashMap::new(), + }).unwrap() + })); - /// Set the read timeout value for all requests. - pub fn set_read_timeout(&mut self, dur: Option<Duration>) { - self.read_timeout = dur; + Ok(Client { + //handle: Some(handle), + tx: notifier, + }) } - /// Set the write timeout value for all requests. - pub fn set_write_timeout(&mut self, dur: Option<Duration>) { - self.write_timeout = dur; + /// Build a new request using this Client. + /// + /// ## Error + /// + /// If the event loop thread has died, or the queue is full, a `ClientError` + /// will be returned. + pub fn request(&self, url: Url, handler: H) -> Result<(), ClientError<H>> { + self.tx.send(Notify::Connect(url, handler)).map_err(|e| { + match e.0 { + Some(Notify::Connect(url, handler)) => ClientError(Some((url, handler))), + _ => ClientError(None) + } + }) } - /// Build a Get request. - pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder { - self.request(Method::Get, url) + /// Close the Client loop. + pub fn close(self) { + // Most errors mean that the Receivers are already dead, which would + // imply the EventLoop panicked. + let _ = self.tx.send(Notify::Shutdown); } +} - /// Build a Head request. - pub fn head<U: IntoUrl>(&self, url: U) -> RequestBuilder { - self.request(Method::Head, url) - } +/// Configuration for a Client +#[derive(Debug, Clone)] +pub struct Config<C> { + connect_timeout: Duration, + connector: C, + keep_alive: bool, + max_idle: usize, + max_sockets: usize, +} - /// Build a Patch request. - pub fn patch<U: IntoUrl>(&self, url: U) -> RequestBuilder { - self.request(Method::Patch, url) +impl<C> Config<C> where C: Connect + Send + 'static { + /// Set the `Connect` type to be used. + #[inline] + pub fn connector<CC: Connect>(self, val: CC) -> Config<CC> { + Config { + connect_timeout: self.connect_timeout, + connector: val, + keep_alive: self.keep_alive, + max_idle: self.max_idle, + max_sockets: self.max_sockets, + } } - /// Build a Post request. - pub fn post<U: IntoUrl>(&self, url: U) -> RequestBuilder { - self.request(Method::Post, url) + /// Enable or disable keep-alive mechanics. + /// + /// Default is enabled. + #[inline] + pub fn keep_alive(mut self, val: bool) -> Config<C> { + self.keep_alive = val; + self } - /// Build a Put request. - pub fn put<U: IntoUrl>(&self, url: U) -> RequestBuilder { - self.request(Method::Put, url) + /// Set the max table size allocated for holding on to live sockets. + /// + /// Default is 1024. + #[inline] + pub fn max_sockets(mut self, val: usize) -> Config<C> { + self.max_sockets = val; + self } - /// Build a Delete request. - pub fn delete<U: IntoUrl>(&self, url: U) -> RequestBuilder { - self.request(Method::Delete, url) + /// Set the timeout for connecting to a URL. + /// + /// Default is 10 seconds. + #[inline] + pub fn connect_timeout(mut self, val: Duration) -> Config<C> { + self.connect_timeout = val; + self } + /// Construct the Client with this configuration. + #[inline] + pub fn build<H: Handler<C::Output>>(self) -> ::Result<Client<H>> { + Client::configured(self) + } +} - /// Build a new request using this Client. - pub fn request<U: IntoUrl>(&self, method: Method, url: U) -> RequestBuilder { - RequestBuilder { - client: self, - method: method, - url: url.into_url(), - body: None, - headers: None, +impl Default for Config<DefaultConnector> { + fn default() -> Config<DefaultConnector> { + Config { + connect_timeout: Duration::from_secs(10), + connector: DefaultConnector::default(), + keep_alive: true, + max_idle: 5, + max_sockets: 1024, } } } -impl Default for Client { - fn default() -> Client { Client::new() } +/// An error that can occur when trying to queue a request. +#[derive(Debug)] +pub struct ClientError<H>(Option<(Url, H)>); + +impl<H> ClientError<H> { + /// If the event loop was down, the `Url` and `Handler` can be recovered + /// from this method. + pub fn recover(self) -> Option<(Url, H)> { + self.0 + } } -/// Options for an individual Request. -/// -/// One of these will be built for you if you use one of the convenience -/// methods, such as `get()`, `post()`, etc. -pub struct RequestBuilder<'a> { - client: &'a Client, - // We store a result here because it's good to keep RequestBuilder - // from being generic, but it is a nicer API to report the error - // from `send` (when other errors may be happening, so it already - // returns a `Result`). Why's it good to keep it non-generic? It - // stops downstream crates having to remonomorphise and recompile - // the code, which can take a while, since `send` is fairly large. - // (For an extreme example, a tiny crate containing - // `hyper::Client::new().get("x").send().unwrap();` took ~4s to - // compile with a generic RequestBuilder, but 2s with this scheme,) - url: Result<Url, UrlError>, - headers: Option<Headers>, - method: Method, - body: Option<Body<'a>>, +impl<H: fmt::Debug + ::std::any::Any> ::std::error::Error for ClientError<H> { + fn description(&self) -> &str { + "Cannot queue request" + } } -impl<'a> RequestBuilder<'a> { +impl<H> fmt::Display for ClientError<H> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("Cannot queue request") + } +} - /// Set a request body to be sent. - pub fn body<B: Into<Body<'a>>>(mut self, body: B) -> RequestBuilder<'a> { - self.body = Some(body.into()); - self +/* +impl Drop for Client { + fn drop(&mut self) { + self.handle.take().map(|handle| handle.join()); } +} +*/ - /// Add additional headers to the request. - pub fn headers(mut self, headers: Headers) -> RequestBuilder<'a> { - self.headers = Some(headers); - self +/// A trait to react to client events that happen for each message. +/// +/// Each event handler returns it's desired `Next` action. +pub trait Handler<T: Transport>: Send + 'static { + /// This event occurs first, triggering when a `Request` head can be written.. + fn on_request(&mut self, request: &mut Request) -> http::Next; + /// This event occurs each time the `Request` is ready to be written to. + fn on_request_writable(&mut self, request: &mut http::Encoder<T>) -> http::Next; + /// This event occurs after the first time this handler signals `Next::read()`, + /// and a Response has been parsed. + fn on_response(&mut self, response: Response) -> http::Next; + /// This event occurs each time the `Response` is ready to be read from. + fn on_response_readable(&mut self, response: &mut http::Decoder<T>) -> http::Next; + + /// This event occurs whenever an `Error` occurs outside of the other events. + /// + /// This could IO errors while waiting for events, or a timeout, etc. + fn on_error(&mut self, err: ::Error) -> http::Next { + debug!("default Handler.on_error({:?})", err); + http::Next::remove() + } + + /// This event occurs when this Handler has requested to remove the Transport. + fn on_remove(self, _transport: T) where Self: Sized { + debug!("default Handler.on_remove"); + } + + /// Receive a `Control` to manage waiting for this request. + fn on_control(&mut self, _: http::Control) { + debug!("default Handler.on_control()"); } +} - /// Add an individual new header to the request. - pub fn header<H: Header + HeaderFormat>(mut self, header: H) -> RequestBuilder<'a> { - { - let mut headers = match self.headers { - Some(ref mut h) => h, - None => { - self.headers = Some(Headers::new()); - self.headers.as_mut().unwrap() - } - }; +struct Message<H: Handler<T>, T: Transport> { + handler: H, + url: Option<Url>, + _marker: PhantomData<T>, +} + +impl<H: Handler<T>, T: Transport> http::MessageHandler<T> for Message<H, T> { + type Message = http::ClientMessage; - headers.set(header); + fn on_outgoing(&mut self, head: &mut RequestHead) -> Next { + let url = self.url.take().expect("Message.url is missing"); + if let Some(host) = url.host_str() { + head.headers.set(Host { + hostname: host.to_owned(), + port: url.port(), + }); } - self + head.subject.1 = RequestUri::AbsolutePath(url.path().to_owned()); + let mut req = self::request::new(head); + self.handler.on_request(&mut req) } - /// Execute this request and receive a Response back. - pub fn send(self) -> ::Result<Response> { - let RequestBuilder { client, method, url, headers, body } = self; - let mut url = try!(url); - trace!("send method={:?}, url={:?}, client={:?}", method, url, client); - - let can_have_body = match method { - Method::Get | Method::Head => false, - _ => true - }; + fn on_encode(&mut self, transport: &mut http::Encoder<T>) -> Next { + self.handler.on_request_writable(transport) + } - let mut body = if can_have_body { - body - } else { - None - }; + fn on_incoming(&mut self, head: http::ResponseHead) -> Next { + trace!("on_incoming {:?}", head); + let resp = response::new(head); + self.handler.on_response(resp) + } - loop { - let mut req = { - let (host, port) = try!(get_host_and_port(&url)); - let mut message = try!(client.protocol.new_message(&host, port, url.scheme())); - if url.scheme() == "http" && client.proxy.is_some() { - message.set_proxied(true); - } + fn on_decode(&mut self, transport: &mut http::Decoder<T>) -> Next { + self.handler.on_response_readable(transport) + } - let mut headers = match headers { - Some(ref headers) => headers.clone(), - None => Headers::new(), - }; - headers.set(Host { - hostname: host.to_owned(), - port: Some(port), - }); - Request::with_headers_and_message(method.clone(), url.clone(), headers, message) - }; - - try!(req.set_write_timeout(client.write_timeout)); - try!(req.set_read_timeout(client.read_timeout)); - - match (can_have_body, body.as_ref()) { - (true, Some(body)) => match body.size() { - Some(size) => req.headers_mut().set(ContentLength(size)), - None => (), // chunked, Request will add it automatically - }, - (true, None) => req.headers_mut().set(ContentLength(0)), - _ => () // neither - } - let mut streaming = try!(req.start()); - body.take().map(|mut rdr| copy(&mut rdr, &mut streaming)); - let res = try!(streaming.send()); - if !res.status.is_redirection() { - return Ok(res) - } - debug!("redirect code {:?} for {}", res.status, url); + fn on_error(&mut self, error: ::Error) -> Next { + self.handler.on_error(error) + } - let loc = { - // punching borrowck here - let loc = match res.headers.get::<Location>() { - Some(&Location(ref loc)) => { - Some(url.join(loc)) - } - None => { - debug!("no Location header"); - // could be 304 Not Modified? - None - } - }; - match loc { - Some(r) => r, - None => return Ok(res) - } - }; - url = match loc { - Ok(u) => u, - Err(e) => { - debug!("Location header had invalid URI: {:?}", e); - return Ok(res); - } - }; - match client.redirect_policy { - // separate branches because they can't be one - RedirectPolicy::FollowAll => (), //continue - RedirectPolicy::FollowIf(cond) if cond(&url) => (), //continue - _ => return Ok(res), - } - } + fn on_remove(self, transport: T) { + self.handler.on_remove(transport); } } -/// An enum of possible body types for a Request. -pub enum Body<'a> { - /// A Reader does not necessarily know it's size, so it is chunked. - ChunkedBody(&'a mut (Read + 'a)), - /// For Readers that can know their size, like a `File`. - SizedBody(&'a mut (Read + 'a), u64), - /// A String has a size, and uses Content-Length. - BufBody(&'a [u8] , usize), +struct Context<K, H> { + connect_timeout: Duration, + keep_alive: bool, + // idle: HashMap<K, Vec<Notify>>, + queue: HashMap<K, Vec<Queued<H>>>, } -impl<'a> Body<'a> { - fn size(&self) -> Option<u64> { - match *self { - Body::SizedBody(_, len) => Some(len), - Body::BufBody(_, len) => Some(len as u64), - _ => None +impl<K: http::Key, H> Context<K, H> { + fn pop_queue(&mut self, key: &K) -> Queued<H> { + let mut should_remove = false; + let queued = { + let mut vec = self.queue.get_mut(key).expect("handler not in queue for key"); + let queued = vec.remove(0); + if vec.is_empty() { + should_remove = true; + } + queued + }; + if should_remove { + self.queue.remove(key); } + queued } } -impl<'a> Read for Body<'a> { - #[inline] - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - match *self { - Body::ChunkedBody(ref mut r) => r.read(buf), - Body::SizedBody(ref mut r, _) => r.read(buf), - Body::BufBody(ref mut r, _) => Read::read(r, buf), +impl<K: http::Key, H: Handler<T>, T: Transport> http::MessageHandlerFactory<K, T> for Context<K, H> { + type Output = Message<H, T>; + + fn create(&mut self, seed: http::Seed<K>) -> Self::Output { + let key = seed.key(); + let queued = self.pop_queue(key); + let (url, mut handler) = (queued.url, queued.handler); + handler.on_control(seed.control()); + Message { + handler: handler, + url: Some(url), + _marker: PhantomData, } } } -impl<'a> Into<Body<'a>> for &'a [u8] { - #[inline] - fn into(self) -> Body<'a> { - Body::BufBody(self, self.len()) - } +enum Notify<T> { + Connect(Url, T), + Shutdown, } -impl<'a> Into<Body<'a>> for &'a str { - #[inline] - fn into(self) -> Body<'a> { - self.as_bytes().into() - } +enum ClientFsm<C, H> +where C: Connect, + C::Output: Transport, + H: Handler<C::Output> { + Connector(C, http::channel::Receiver<Notify<H>>), + Socket(http::Conn<C::Key, C::Output, Message<H, C::Output>>) } -impl<'a> Into<Body<'a>> for &'a String { - #[inline] - fn into(self) -> Body<'a> { - self.as_bytes().into() +unsafe impl<C, H> Send for ClientFsm<C, H> +where + C: Connect + Send, + //C::Key, // Key doesn't need to be Send + C::Output: Transport, // Tranport doesn't need to be Send + H: Handler<C::Output> + Send +{} + +impl<C, H> rotor::Machine for ClientFsm<C, H> +where C: Connect, + C::Output: Transport, + H: Handler<C::Output> { + type Context = Context<C::Key, H>; + type Seed = (C::Key, C::Output); + + fn create(seed: Self::Seed, scope: &mut Scope<Self::Context>) -> rotor::Response<Self, rotor::Void> { + rotor_try!(scope.register(&seed.1, EventSet::writable(), PollOpt::level())); + rotor::Response::ok( + ClientFsm::Socket( + http::Conn::new(seed.0, seed.1, scope.notifier()) + .keep_alive(scope.keep_alive) + ) + ) + } + + fn ready(self, events: EventSet, scope: &mut Scope<Self::Context>) -> rotor::Response<Self, Self::Seed> { + match self { + ClientFsm::Connector(..) => { + unreachable!("Connector can never be ready") + }, + ClientFsm::Socket(conn) => { + match conn.ready(events, scope) { + Some((conn, None)) => rotor::Response::ok(ClientFsm::Socket(conn)), + Some((conn, Some(dur))) => { + rotor::Response::ok(ClientFsm::Socket(conn)) + .deadline(scope.now() + dur) + } + None => rotor::Response::done() + } + } + } } -} -impl<'a, R: Read> From<&'a mut R> for Body<'a> { - #[inline] - fn from(r: &'a mut R) -> Body<'a> { - Body::ChunkedBody(r) + fn spawned(self, scope: &mut Scope<Self::Context>) -> rotor::Response<Self, Self::Seed> { + match self { + ClientFsm::Connector(..) => self.connect(scope), + other => rotor::Response::ok(other) + } } -} - -/// A helper trait to convert common objects into a Url. -pub trait IntoUrl { - /// Consumes the object, trying to return a Url. - fn into_url(self) -> Result<Url, UrlError>; -} -impl IntoUrl for Url { - fn into_url(self) -> Result<Url, UrlError> { - Ok(self) + fn timeout(self, scope: &mut Scope<Self::Context>) -> rotor::Response<Self, Self::Seed> { + trace!("timeout now = {:?}", scope.now()); + match self { + ClientFsm::Connector(..) => { + let now = scope.now(); + let mut empty_keys = Vec::new(); + { + for (key, mut vec) in scope.queue.iter_mut() { + while !vec.is_empty() && vec[0].deadline <= now { + let mut queued = vec.remove(0); + let _ = queued.handler.on_error(::Error::Timeout); + } + if vec.is_empty() { + empty_keys.push(key.clone()); + } + } + } + for key in &empty_keys { + scope.queue.remove(key); + } + match self.deadline(scope) { + Some(deadline) => { + rotor::Response::ok(self).deadline(deadline) + }, + None => rotor::Response::ok(self) + } + } + ClientFsm::Socket(conn) => { + match conn.timeout(scope) { + Some((conn, None)) => rotor::Response::ok(ClientFsm::Socket(conn)), + Some((conn, Some(dur))) => { + rotor::Response::ok(ClientFsm::Socket(conn)) + .deadline(scope.now() + dur) + } + None => rotor::Response::done() + } + } + } } -} -impl<'a> IntoUrl for &'a str { - fn into_url(self) -> Result<Url, UrlError> { - Url::parse(self) + fn wakeup(self, scope: &mut Scope<Self::Context>) -> rotor::Response<Self, Self::Seed> { + match self { + ClientFsm::Connector(..) => { + self.connect(scope) + }, + ClientFsm::Socket(conn) => match conn.wakeup(scope) { + Some((conn, None)) => rotor::Response::ok(ClientFsm::Socket(conn)), + Some((conn, Some(dur))) => { + rotor::Response::ok(ClientFsm::Socket(conn)) + .deadline(scope.now() + dur) + } + None => rotor::Response::done() + } + } } } -impl<'a> IntoUrl for &'a String { - fn into_url(self) -> Result<Url, UrlError> { - Url::parse(self) +impl<C, H> ClientFsm<C, H> +where C: Connect, + C::Output: Transport, + H: Handler<C::Output> { + fn connect(self, scope: &mut rotor::Scope<<Self as rotor::Machine>::Context>) -> rotor::Response<Self, <Self as rotor::Machine>::Seed> { + match self { + ClientFsm::Connector(mut connector, rx) => { + if let Some((key, res)) = connector.connected() { + match res { + Ok(socket) => { + trace!("connected"); + return rotor::Response::spawn(ClientFsm::Connector(connector, rx), (key, socket)); + }, + Err(e) => { + trace!("connected error = {:?}", e); + let mut queued = scope.pop_queue(&key); + let _ = queued.handler.on_error(::Error::Io(e)); + } + } + } + loop { + match rx.try_recv() { + Ok(Notify::Connect(url, mut handler)) => { + // TODO: check pool for sockets to this domain + match connector.connect(&url) { + Ok(key) => { + let deadline = scope.now() + scope.connect_timeout; + scope.queue.entry(key).or_insert(Vec::new()).push(Queued { + deadline: deadline, + handler: handler, + url: url + }); + } + Err(e) => { + let _todo = handler.on_error(e.into()); + trace!("Connect error, next={:?}", _todo); + continue; + } + } + } + Ok(Notify::Shutdown) => { + scope.shutdown_loop(); + return rotor::Response::done() + }, + Err(mpsc::TryRecvError::Disconnected) => { + // if there is no way to send additional requests, + // what more can the loop do? i suppose we should + // shutdown. + scope.shutdown_loop(); + return rotor::Response::done() + } + Err(mpsc::TryRecvError::Empty) => { + // spurious wakeup or loop is done + let fsm = ClientFsm::Connector(connector, rx); + return match fsm.deadline(scope) { + Some(deadline) => { + rotor::Response::ok(fsm).deadline(deadline) + }, + None => rotor::Response::ok(fsm) + }; + } + } + } + }, + other => rotor::Response::ok(other) + } } -} -/// Behavior regarding how to handle redirects within a Client. -#[derive(Copy)] -pub enum RedirectPolicy { - /// Don't follow any redirects. - FollowNone, - /// Follow all redirects. - FollowAll, - /// Follow a redirect if the contained function returns true. - FollowIf(fn(&Url) -> bool), -} - -impl fmt::Debug for RedirectPolicy { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn deadline(&self, scope: &mut rotor::Scope<<Self as rotor::Machine>::Context>) -> Option<rotor::Time> { match *self { - RedirectPolicy::FollowNone => fmt.write_str("FollowNone"), - RedirectPolicy::FollowAll => fmt.write_str("FollowAll"), - RedirectPolicy::FollowIf(_) => fmt.write_str("FollowIf"), + ClientFsm::Connector(..) => { + let mut earliest = None; + for vec in scope.queue.values() { + for queued in vec { + match earliest { + Some(ref mut earliest) => { + if queued.deadline < *earliest { + *earliest = queued.deadline; + } + } + None => earliest = Some(queued.deadline) + } + } + } + trace!("deadline = {:?}, now = {:?}", earliest, scope.now()); + earliest + } + _ => None } } } -// This is a hack because of upstream typesystem issues. -impl Clone for RedirectPolicy { - fn clone(&self) -> RedirectPolicy { - *self - } -} - -impl Default for RedirectPolicy { - fn default() -> RedirectPolicy { - RedirectPolicy::FollowAll - } +struct Queued<H> { + deadline: rotor::Time, + handler: H, + url: Url, } - -fn get_host_and_port(url: &Url) -> ::Result<(&str, u16)> { - let host = match url.host_str() { - Some(host) => host, - None => return Err(Error::Uri(UrlError::EmptyHost)) - }; - trace!("host={:?}", host); - let port = match url.port_or_known_default() { - Some(port) => port, - None => return Err(Error::Uri(UrlError::InvalidPort)) - }; - trace!("port={:?}", port); - Ok((host, port)) +#[doc(hidden)] +#[allow(missing_debug_implementations)] +pub struct Registration { + notify: (http::channel::Sender<self::dns::Answer>, http::channel::Receiver<self::dns::Answer>), } #[cfg(test)] mod tests { + /* use std::io::Read; use header::Server; - use http::h1::Http11Message; - use mock::{MockStream, MockSsl}; - use super::{Client, RedirectPolicy}; - use super::proxy::Proxy; + use super::{Client}; use super::pool::Pool; use url::Url; - mock_connector!(MockRedirectPolicy { - "http://127.0.0.1" => "HTTP/1.1 301 Redirect\r\n\ - Location: http://127.0.0.2\r\n\ - Server: mock1\r\n\ - \r\n\ - " - "http://127.0.0.2" => "HTTP/1.1 302 Found\r\n\ - Location: https://127.0.0.3\r\n\ - Server: mock2\r\n\ - \r\n\ - " - "https://127.0.0.3" => "HTTP/1.1 200 OK\r\n\ - Server: mock3\r\n\ - \r\n\ - " - }); - - - #[test] - fn test_proxy() { - use super::pool::PooledStream; - type MessageStream = PooledStream<super::proxy::Proxied<MockStream, MockStream>>; - mock_connector!(ProxyConnector { - b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" - }); - let tunnel = Proxy { - connector: ProxyConnector, - proxy: ("example.proxy".into(), 8008), - ssl: MockSsl, - }; - let mut client = Client::with_connector(Pool::with_connector(Default::default(), tunnel)); - client.proxy = Some(("example.proxy".into(), 8008)); - let mut dump = vec![]; - client.get("http://127.0.0.1/foo/bar").send().unwrap().read_to_end(&mut dump).unwrap(); - - let box_message = client.protocol.new_message("127.0.0.1", 80, "http").unwrap(); - let message = box_message.downcast::<Http11Message>().unwrap(); - let stream = message.into_inner().downcast::<MessageStream>().unwrap().into_inner().into_normal().unwrap();; - - let s = ::std::str::from_utf8(&stream.write).unwrap(); - let request_line = "GET http://127.0.0.1/foo/bar HTTP/1.1\r\n"; - assert!(s.starts_with(request_line), "{:?} doesn't start with {:?}", s, request_line); - assert!(s.contains("Host: 127.0.0.1\r\n")); - } - - #[test] - fn test_proxy_tunnel() { - use super::pool::PooledStream; - type MessageStream = PooledStream<super::proxy::Proxied<MockStream, MockStream>>; - - mock_connector!(ProxyConnector { - b"HTTP/1.1 200 OK\r\n\r\n", - b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" - }); - let tunnel = Proxy { - connector: ProxyConnector, - proxy: ("example.proxy".into(), 8008), - ssl: MockSsl, - }; - let mut client = Client::with_connector(Pool::with_connector(Default::default(), tunnel)); - client.proxy = Some(("example.proxy".into(), 8008)); - let mut dump = vec![]; - client.get("https://127.0.0.1/foo/bar").send().unwrap().read_to_end(&mut dump).unwrap(); - - let box_message = client.protocol.new_message("127.0.0.1", 443, "https").unwrap(); - let message = box_message.downcast::<Http11Message>().unwrap(); - let stream = message.into_inner().downcast::<MessageStream>().unwrap().into_inner().into_tunneled().unwrap(); - - let s = ::std::str::from_utf8(&stream.write).unwrap(); - let connect_line = "CONNECT 127.0.0.1:443 HTTP/1.1\r\nHost: 127.0.0.1:443\r\n\r\n"; - assert_eq!(&s[..connect_line.len()], connect_line); - - let s = &s[connect_line.len()..]; - let request_line = "GET /foo/bar HTTP/1.1\r\n"; - assert_eq!(&s[..request_line.len()], request_line); - assert!(s.contains("Host: 127.0.0.1\r\n")); - } - - #[test] - fn test_redirect_followall() { - let mut client = Client::with_connector(MockRedirectPolicy); - client.set_redirect_policy(RedirectPolicy::FollowAll); - - let res = client.get("http://127.0.0.1").send().unwrap(); - assert_eq!(res.headers.get(), Some(&Server("mock3".to_owned()))); - } - - #[test] - fn test_redirect_dontfollow() { - let mut client = Client::with_connector(MockRedirectPolicy); - client.set_redirect_policy(RedirectPolicy::FollowNone); - let res = client.get("http://127.0.0.1").send().unwrap(); - assert_eq!(res.headers.get(), Some(&Server("mock1".to_owned()))); - } - - #[test] - fn test_redirect_followif() { - fn follow_if(url: &Url) -> bool { - !url.as_str().contains("127.0.0.3") - } - let mut client = Client::with_connector(MockRedirectPolicy); - client.set_redirect_policy(RedirectPolicy::FollowIf(follow_if)); - let res = client.get("http://127.0.0.1").send().unwrap(); - assert_eq!(res.headers.get(), Some(&Server("mock2".to_owned()))); - } - mock_connector!(Issue640Connector { b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\n", b"GET", diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -621,4 +628,5 @@ mod tests { client.post("http://127.0.0.1").send().unwrap().read_to_string(&mut s).unwrap(); assert_eq!(s, "POST"); } + */ } diff --git a/src/client/proxy.rs /dev/null --- a/src/client/proxy.rs +++ /dev/null @@ -1,240 +0,0 @@ -use std::borrow::Cow; -use std::io; -use std::net::{SocketAddr, Shutdown}; -use std::time::Duration; - -use method::Method; -use net::{NetworkConnector, HttpConnector, NetworkStream, SslClient}; - -#[cfg(all(feature = "openssl", not(feature = "security-framework")))] -pub fn tunnel(proxy: (Cow<'static, str>, u16)) -> Proxy<HttpConnector, ::net::Openssl> { - Proxy { - connector: HttpConnector, - proxy: proxy, - ssl: Default::default() - } -} - -#[cfg(feature = "security-framework")] -pub fn tunnel(proxy: (Cow<'static, str>, u16)) -> Proxy<HttpConnector, ::net::Openssl> { - Proxy { - connector: HttpConnector, - proxy: proxy, - ssl: Default::default() - } -} - -#[cfg(not(any(feature = "openssl", feature = "security-framework")))] -pub fn tunnel(proxy: (Cow<'static, str>, u16)) -> Proxy<HttpConnector, self::no_ssl::Plaintext> { - Proxy { - connector: HttpConnector, - proxy: proxy, - ssl: self::no_ssl::Plaintext, - } - -} - -pub struct Proxy<C, S> -where C: NetworkConnector + Send + Sync + 'static, - C::Stream: NetworkStream + Send + Clone, - S: SslClient<C::Stream> { - pub connector: C, - pub proxy: (Cow<'static, str>, u16), - pub ssl: S, -} - - -impl<C, S> NetworkConnector for Proxy<C, S> -where C: NetworkConnector + Send + Sync + 'static, - C::Stream: NetworkStream + Send + Clone, - S: SslClient<C::Stream> { - type Stream = Proxied<C::Stream, S::Stream>; - - fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<Self::Stream> { - use httparse; - use std::io::{Read, Write}; - use ::version::HttpVersion::Http11; - trace!("{:?} proxy for '{}://{}:{}'", self.proxy, scheme, host, port); - match scheme { - "http" => { - self.connector.connect(self.proxy.0.as_ref(), self.proxy.1, "http") - .map(Proxied::Normal) - }, - "https" => { - let mut stream = try!(self.connector.connect(self.proxy.0.as_ref(), self.proxy.1, "http")); - trace!("{:?} CONNECT {}:{}", self.proxy, host, port); - try!(write!(&mut stream, "{method} {host}:{port} {version}\r\nHost: {host}:{port}\r\n\r\n", - method=Method::Connect, host=host, port=port, version=Http11)); - try!(stream.flush()); - let mut buf = [0; 1024]; - let mut n = 0; - while n < buf.len() { - n += try!(stream.read(&mut buf[n..])); - let mut headers = [httparse::EMPTY_HEADER; 10]; - let mut res = httparse::Response::new(&mut headers); - if try!(res.parse(&buf[..n])).is_complete() { - let code = res.code.expect("complete parsing lost code"); - if code >= 200 && code < 300 { - trace!("CONNECT success = {:?}", code); - return self.ssl.wrap_client(stream, host) - .map(Proxied::Tunneled) - } else { - trace!("CONNECT response = {:?}", code); - return Err(::Error::Status); - } - } - } - Err(::Error::TooLarge) - }, - _ => Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid scheme").into()) - } - } -} - -#[derive(Debug)] -pub enum Proxied<T1, T2> { - Normal(T1), - Tunneled(T2) -} - -#[cfg(test)] -impl<T1, T2> Proxied<T1, T2> { - pub fn into_normal(self) -> Result<T1, Self> { - match self { - Proxied::Normal(t1) => Ok(t1), - _ => Err(self) - } - } - - pub fn into_tunneled(self) -> Result<T2, Self> { - match self { - Proxied::Tunneled(t2) => Ok(t2), - _ => Err(self) - } - } -} - -impl<T1: NetworkStream, T2: NetworkStream> io::Read for Proxied<T1, T2> { - #[inline] - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - match *self { - Proxied::Normal(ref mut t) => io::Read::read(t, buf), - Proxied::Tunneled(ref mut t) => io::Read::read(t, buf), - } - } -} - -impl<T1: NetworkStream, T2: NetworkStream> io::Write for Proxied<T1, T2> { - #[inline] - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - match *self { - Proxied::Normal(ref mut t) => io::Write::write(t, buf), - Proxied::Tunneled(ref mut t) => io::Write::write(t, buf), - } - } - - #[inline] - fn flush(&mut self) -> io::Result<()> { - match *self { - Proxied::Normal(ref mut t) => io::Write::flush(t), - Proxied::Tunneled(ref mut t) => io::Write::flush(t), - } - } -} - -impl<T1: NetworkStream, T2: NetworkStream> NetworkStream for Proxied<T1, T2> { - #[inline] - fn peer_addr(&mut self) -> io::Result<SocketAddr> { - match *self { - Proxied::Normal(ref mut s) => s.peer_addr(), - Proxied::Tunneled(ref mut s) => s.peer_addr() - } - } - - #[inline] - fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - match *self { - Proxied::Normal(ref inner) => inner.set_read_timeout(dur), - Proxied::Tunneled(ref inner) => inner.set_read_timeout(dur) - } - } - - #[inline] - fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - match *self { - Proxied::Normal(ref inner) => inner.set_write_timeout(dur), - Proxied::Tunneled(ref inner) => inner.set_write_timeout(dur) - } - } - - #[inline] - fn close(&mut self, how: Shutdown) -> io::Result<()> { - match *self { - Proxied::Normal(ref mut s) => s.close(how), - Proxied::Tunneled(ref mut s) => s.close(how) - } - } -} - -#[cfg(not(any(feature = "openssl", feature = "security-framework")))] -mod no_ssl { - use std::io; - use std::net::{Shutdown, SocketAddr}; - use std::time::Duration; - - use net::{SslClient, NetworkStream}; - - pub struct Plaintext; - - #[derive(Clone)] - pub enum Void {} - - impl io::Read for Void { - #[inline] - fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { - match *self {} - } - } - - impl io::Write for Void { - #[inline] - fn write(&mut self, _buf: &[u8]) -> io::Result<usize> { - match *self {} - } - - #[inline] - fn flush(&mut self) -> io::Result<()> { - match *self {} - } - } - - impl NetworkStream for Void { - #[inline] - fn peer_addr(&mut self) -> io::Result<SocketAddr> { - match *self {} - } - - #[inline] - fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> { - match *self {} - } - - #[inline] - fn set_write_timeout(&self, _dur: Option<Duration>) -> io::Result<()> { - match *self {} - } - - #[inline] - fn close(&mut self, _how: Shutdown) -> io::Result<()> { - match *self {} - } - } - - impl<T: NetworkStream + Send + Clone> SslClient<T> for Plaintext { - type Stream = Void; - - fn wrap_client(&self, _stream: T, _host: &str) -> ::Result<Self::Stream> { - Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid scheme").into()) - } - } -} diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -1,177 +1,52 @@ //! Client Requests -use std::marker::PhantomData; -use std::io::{self, Write}; -use std::time::Duration; - -use url::Url; - -use method::Method; use header::Headers; -use header::Host; -use net::{NetworkStream, NetworkConnector, DefaultConnector, Fresh, Streaming}; -use version; -use client::{Response, get_host_and_port}; +use http::RequestHead; +use method::Method; +use uri::RequestUri; +use version::HttpVersion; -use http::{HttpMessage, RequestHead}; -use http::h1::Http11Message; /// A client request to a remote server. -/// The W type tracks the state of the request, Fresh vs Streaming. -pub struct Request<W> { - /// The target URI for this request. - pub url: Url, - - /// The HTTP version of this request. - pub version: version::HttpVersion, - - message: Box<HttpMessage>, - headers: Headers, - method: Method, - - _marker: PhantomData<W>, +#[derive(Debug)] +pub struct Request<'a> { + head: &'a mut RequestHead } -impl<W> Request<W> { - /// Read the Request headers. +impl<'a> Request<'a> { + /// Read the Request Url. #[inline] - pub fn headers(&self) -> &Headers { &self.headers } + pub fn uri(&self) -> &RequestUri { &self.head.subject.1 } - /// Read the Request method. + /// Readthe Request Version. #[inline] - pub fn method(&self) -> Method { self.method.clone() } + pub fn version(&self) -> &HttpVersion { &self.head.version } - /// Set the write timeout. + /// Read the Request headers. #[inline] - pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.message.set_write_timeout(dur) - } + pub fn headers(&self) -> &Headers { &self.head.headers } - /// Set the read timeout. + /// Read the Request method. #[inline] - pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.message.set_read_timeout(dur) - } -} - -impl Request<Fresh> { - /// Create a new `Request<Fresh>` that will use the given `HttpMessage` for its communication - /// with the server. This implies that the given `HttpMessage` instance has already been - /// properly initialized by the caller (e.g. a TCP connection's already established). - pub fn with_message(method: Method, url: Url, message: Box<HttpMessage>) - -> ::Result<Request<Fresh>> { - let mut headers = Headers::new(); - { - let (host, port) = try!(get_host_and_port(&url)); - headers.set(Host { - hostname: host.to_owned(), - port: Some(port), - }); - } - - Ok(Request::with_headers_and_message(method, url, headers, message)) - } - - #[doc(hidden)] - pub fn with_headers_and_message(method: Method, url: Url, headers: Headers, message: Box<HttpMessage>) - -> Request<Fresh> { - Request { - method: method, - headers: headers, - url: url, - version: version::HttpVersion::Http11, - message: message, - _marker: PhantomData, - } - } + pub fn method(&self) -> &Method { &self.head.subject.0 } - /// Create a new client request. - pub fn new(method: Method, url: Url) -> ::Result<Request<Fresh>> { - let conn = DefaultConnector::default(); - Request::with_connector(method, url, &conn) - } - - /// Create a new client request with a specific underlying NetworkStream. - pub fn with_connector<C, S>(method: Method, url: Url, connector: &C) - -> ::Result<Request<Fresh>> where - C: NetworkConnector<Stream=S>, - S: Into<Box<NetworkStream + Send>> { - let stream = { - let (host, port) = try!(get_host_and_port(&url)); - try!(connector.connect(host, port, url.scheme())).into() - }; - - Request::with_message(method, url, Box::new(Http11Message::with_stream(stream))) - } - - /// Consume a Fresh Request, writing the headers and method, - /// returning a Streaming Request. - pub fn start(mut self) -> ::Result<Request<Streaming>> { - let head = match self.message.set_outgoing(RequestHead { - headers: self.headers, - method: self.method, - url: self.url, - }) { - Ok(head) => head, - Err(e) => { - let _ = self.message.close_connection(); - return Err(From::from(e)); - } - }; - - Ok(Request { - method: head.method, - headers: head.headers, - url: head.url, - version: self.version, - message: self.message, - _marker: PhantomData, - }) - } + /// Set the Method of this request. + #[inline] + pub fn set_method(&mut self, method: Method) { self.head.subject.0 = method; } /// Get a mutable reference to the Request headers. #[inline] - pub fn headers_mut(&mut self) -> &mut Headers { &mut self.headers } -} - - - -impl Request<Streaming> { - /// Completes writing the request, and returns a response to read from. - /// - /// Consumes the Request. - pub fn send(self) -> ::Result<Response> { - Response::with_message(self.url, self.message) - } + pub fn headers_mut(&mut self) -> &mut Headers { &mut self.head.headers } } -impl Write for Request<Streaming> { - #[inline] - fn write(&mut self, msg: &[u8]) -> io::Result<usize> { - match self.message.write(msg) { - Ok(n) => Ok(n), - Err(e) => { - let _ = self.message.close_connection(); - Err(e) - } - } - } - - #[inline] - fn flush(&mut self) -> io::Result<()> { - match self.message.flush() { - Ok(r) => Ok(r), - Err(e) => { - let _ = self.message.close_connection(); - Err(e) - } - } - } +pub fn new(head: &mut RequestHead) -> Request { + Request { head: head } } #[cfg(test)] mod tests { + /* use std::io::Write; use std::str::from_utf8; use url::Url; diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -311,4 +186,5 @@ mod tests { .get_ref().downcast_ref::<MockStream>().unwrap() .is_closed); } + */ } diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -94,9 +69,11 @@ impl Drop for Response { } } } +*/ #[cfg(test)] mod tests { + /* use std::io::{self, Read}; use url::Url; diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -230,4 +207,5 @@ mod tests { assert!(Response::new(url, Box::new(stream)).is_err()); } + */ } diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -148,18 +150,11 @@ impl From<httparse::Error> for Error { } } -impl From<Http2Error> for Error { - fn from(err: Http2Error) -> Error { - Error::Http2(err) - } -} - #[cfg(test)] mod tests { use std::error::Error as StdError; use std::io; use httparse; - use solicit::http::HttpError as Http2Error; use url; use super::Error; use super::Error::*; diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -201,7 +196,6 @@ mod tests { from_and_cause!(io::Error::new(io::ErrorKind::Other, "other") => Io(..)); from_and_cause!(url::ParseError::EmptyHost => Uri(..)); - from_and_cause!(Http2Error::UnknownStreamId => Http2(..)); from!(httparse::Error::HeaderName => Header); from!(httparse::Error::HeaderName => Header); diff --git a/src/header/common/access_control_allow_credentials.rs b/src/header/common/access_control_allow_credentials.rs --- a/src/header/common/access_control_allow_credentials.rs +++ b/src/header/common/access_control_allow_credentials.rs @@ -86,4 +84,4 @@ mod test_access_control_allow_credentials { test_header!(not_bool, vec![b"false"], None); test_header!(only_single, vec![b"true", b"true"], None); test_header!(no_gibberish, vec!["\u{645}\u{631}\u{62d}\u{628}\u{627}".as_bytes()], None); -} \ No newline at end of file +} diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -66,7 +66,7 @@ macro_rules! bench_header( use test::Bencher; use super::*; - use header::{Header, HeaderFormatter}; + use header::{Header}; #[bench] fn bench_parse(b: &mut Bencher) { diff --git a/src/header/common/preference_applied.rs b/src/header/common/preference_applied.rs --- a/src/header/common/preference_applied.rs +++ b/src/header/common/preference_applied.rs @@ -80,7 +78,7 @@ impl HeaderFormat for PreferenceApplied { #[cfg(test)] mod tests { - use header::{HeaderFormat, Preference}; + use header::{Header, Preference}; use super::*; #[test] diff --git a/src/header/common/preference_applied.rs b/src/header/common/preference_applied.rs --- a/src/header/common/preference_applied.rs +++ b/src/header/common/preference_applied.rs @@ -90,7 +88,7 @@ mod tests { "foo".to_owned(), "bar".to_owned(), vec![("bar".to_owned(), "foo".to_owned()), ("buz".to_owned(), "".to_owned())] - )]) as &(HeaderFormat + Send + Sync)), + )]) as &(Header + Send + Sync)), "foo=bar".to_owned() ); } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -519,7 +515,7 @@ mod tests { use mime::Mime; use mime::TopLevel::Text; use mime::SubLevel::Plain; - use super::{Headers, Header, HeaderFormat, ContentLength, ContentType, + use super::{Headers, Header, ContentLength, ContentType, Accept, Host, qitem}; use httparse; diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -597,9 +593,7 @@ mod tests { None => Err(::Error::Header), } } - } - impl HeaderFormat for CrazyLength { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { let CrazyLength(ref opt, ref value) = *self; write!(f, "{:?}, {:?}", opt, value) diff --git /dev/null b/src/http/conn.rs new file mode 100644 --- /dev/null +++ b/src/http/conn.rs @@ -0,0 +1,915 @@ +use std::borrow::Cow; +use std::fmt; +use std::hash::Hash; +use std::io; +use std::marker::PhantomData; +use std::mem; +use std::time::Duration; + +use rotor::{self, EventSet, PollOpt, Scope}; + +use http::{self, h1, Http1Message, Encoder, Decoder, Next, Next_, Reg, Control}; +use http::channel; +use http::internal::WriteBuf; +use http::buffer::Buffer; +use net::{Transport, Blocked}; +use version::HttpVersion; + +const MAX_BUFFER_SIZE: usize = 8192 + 4096 * 100; + +/// This handles a connection, which will have been established over a +/// Transport (like a socket), and will likely include multiple +/// `Message`s over HTTP. +/// +/// The connection will determine when a message begins and ends, creating +/// a new message `MessageHandler` for each one, as well as determine if this +/// connection can be kept alive after the message, or if it is complete. +pub struct Conn<K: Key, T: Transport, H: MessageHandler<T>> { + buf: Buffer, + ctrl: (channel::Sender<Next>, channel::Receiver<Next>), + keep_alive_enabled: bool, + key: K, + state: State<H, T>, + transport: T, +} + +impl<K: Key, T: Transport, H: MessageHandler<T>> fmt::Debug for Conn<K, T, H> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Conn") + .field("keep_alive_enabled", &self.keep_alive_enabled) + .field("state", &self.state) + .field("buf", &self.buf) + .finish() + } +} + +impl<K: Key, T: Transport, H: MessageHandler<T>> Conn<K, T, H> { + pub fn new(key: K, transport: T, notify: rotor::Notifier) -> Conn<K, T, H> { + Conn { + buf: Buffer::new(), + ctrl: channel::new(notify), + keep_alive_enabled: true, + key: key, + state: State::Init, + transport: transport, + } + } + + pub fn keep_alive(mut self, val: bool) -> Conn<K, T, H> { + self.keep_alive_enabled = val; + self + } + + /// Desired Register interest based on state of current connection. + /// + /// This includes the user interest, such as when they return `Next::read()`. + fn interest(&self) -> Reg { + match self.state { + State::Closed => Reg::Remove, + State::Init => { + <H as MessageHandler>::Message::initial_interest().interest() + } + State::Http1(Http1 { reading: Reading::Closed, writing: Writing::Closed, .. }) => { + Reg::Remove + } + State::Http1(Http1 { ref reading, ref writing, .. }) => { + let read = match *reading { + Reading::Parse | + Reading::Body(..) => Reg::Read, + Reading::Init | + Reading::Wait(..) | + Reading::KeepAlive | + Reading::Closed => Reg::Wait + }; + + let write = match *writing { + Writing::Head | + Writing::Chunk(..) | + Writing::Ready(..) => Reg::Write, + Writing::Init | + Writing::Wait(..) | + Writing::KeepAlive => Reg::Wait, + Writing::Closed => Reg::Wait, + }; + + match (read, write) { + (Reg::Read, Reg::Write) => Reg::ReadWrite, + (Reg::Read, Reg::Wait) => Reg::Read, + (Reg::Wait, Reg::Write) => Reg::Write, + (Reg::Wait, Reg::Wait) => Reg::Wait, + _ => unreachable!("bad read/write reg combo") + } + } + } + } + + /// Actual register action. + /// + /// Considers the user interest(), but also compares if the underlying + /// transport is blocked(), and adjusts accordingly. + fn register(&self) -> Reg { + let reg = self.interest(); + match (reg, self.transport.blocked()) { + (Reg::Remove, _) | + (Reg::Wait, _) | + (_, None) => reg, + + (_, Some(Blocked::Read)) => Reg::Read, + (_, Some(Blocked::Write)) => Reg::Write, + } + } + + fn parse(&mut self) -> ::Result<http::MessageHead<<<H as MessageHandler<T>>::Message as Http1Message>::Incoming>> { + let n = try!(self.buf.read_from(&mut self.transport)); + if n == 0 { + trace!("parse eof"); + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "parse eof").into()); + } + match try!(http::parse::<<H as MessageHandler<T>>::Message, _>(self.buf.bytes())) { + Some((head, len)) => { + trace!("parsed {} bytes out of {}", len, self.buf.len()); + self.buf.consume(len); + Ok(head) + }, + None => { + if self.buf.len() >= MAX_BUFFER_SIZE { + //TODO: Handler.on_too_large_error() + debug!("MAX_BUFFER_SIZE reached, closing"); + Err(::Error::TooLarge) + } else { + Err(io::Error::new(io::ErrorKind::WouldBlock, "incomplete parse").into()) + } + }, + } + } + + fn read<F: MessageHandlerFactory<K, T, Output=H>>(&mut self, scope: &mut Scope<F>, state: State<H, T>) -> State<H, T> { + match state { + State::Init => { + let head = match self.parse() { + Ok(head) => head, + Err(::Error::Io(e)) => match e.kind() { + io::ErrorKind::WouldBlock | + io::ErrorKind::Interrupted => return State::Init, + _ => { + debug!("io error trying to parse {:?}", e); + return State::Closed; + } + }, + Err(e) => { + //TODO: send proper error codes depending on error + trace!("parse eror: {:?}", e); + return State::Closed; + } + }; + match <<H as MessageHandler<T>>::Message as Http1Message>::decoder(&head) { + Ok(decoder) => { + trace!("decoder = {:?}", decoder); + let keep_alive = self.keep_alive_enabled && head.should_keep_alive(); + let mut handler = scope.create(Seed(&self.key, &self.ctrl.0)); + let next = handler.on_incoming(head); + trace!("handler.on_incoming() -> {:?}", next); + + match next.interest { + Next_::Read => self.read(scope, State::Http1(Http1 { + handler: handler, + reading: Reading::Body(decoder), + writing: Writing::Init, + keep_alive: keep_alive, + timeout: next.timeout, + _marker: PhantomData, + })), + Next_::Write => State::Http1(Http1 { + handler: handler, + reading: if decoder.is_eof() { + if keep_alive { + Reading::KeepAlive + } else { + Reading::Closed + } + } else { + Reading::Wait(decoder) + }, + writing: Writing::Head, + keep_alive: keep_alive, + timeout: next.timeout, + _marker: PhantomData, + }), + Next_::ReadWrite => self.read(scope, State::Http1(Http1 { + handler: handler, + reading: Reading::Body(decoder), + writing: Writing::Head, + keep_alive: keep_alive, + timeout: next.timeout, + _marker: PhantomData, + })), + Next_::Wait => State::Http1(Http1 { + handler: handler, + reading: Reading::Wait(decoder), + writing: Writing::Init, + keep_alive: keep_alive, + timeout: next.timeout, + _marker: PhantomData, + }), + Next_::End | + Next_::Remove => State::Closed, + } + }, + Err(e) => { + debug!("error creating decoder: {:?}", e); + //TODO: respond with 400 + State::Closed + } + } + }, + State::Http1(mut http1) => { + let next = match http1.reading { + Reading::Init => None, + Reading::Parse => match self.parse() { + Ok(head) => match <<H as MessageHandler<T>>::Message as Http1Message>::decoder(&head) { + Ok(decoder) => { + trace!("decoder = {:?}", decoder); + // if client request asked for keep alive, + // then it depends entirely on if the server agreed + if http1.keep_alive { + http1.keep_alive = head.should_keep_alive(); + } + let next = http1.handler.on_incoming(head); + http1.reading = Reading::Wait(decoder); + trace!("handler.on_incoming() -> {:?}", next); + Some(next) + }, + Err(e) => { + debug!("error creating decoder: {:?}", e); + //TODO: respond with 400 + return State::Closed; + } + }, + Err(::Error::Io(e)) => match e.kind() { + io::ErrorKind::WouldBlock | + io::ErrorKind::Interrupted => None, + _ => { + debug!("io error trying to parse {:?}", e); + return State::Closed; + } + }, + Err(e) => { + //TODO: send proper error codes depending on error + trace!("parse eror: {:?}", e); + return State::Closed; + } + }, + Reading::Body(ref mut decoder) => { + let wrapped = if !self.buf.is_empty() { + super::Trans::Buf(self.buf.wrap(&mut self.transport)) + } else { + super::Trans::Port(&mut self.transport) + }; + + Some(http1.handler.on_decode(&mut Decoder::h1(decoder, wrapped))) + }, + _ => { + trace!("Conn.on_readable State::Http1(reading = {:?})", http1.reading); + None + } + }; + let mut s = State::Http1(http1); + trace!("h1 read completed, next = {:?}", next); + if let Some(next) = next { + s.update(next); + } + trace!("h1 read completed, state = {:?}", s); + + let again = match s { + State::Http1(Http1 { reading: Reading::Body(ref encoder), .. }) => encoder.is_eof(), + _ => false + }; + + if again { + self.read(scope, s) + } else { + s + } + }, + State::Closed => { + error!("on_readable State::Closed"); + State::Closed + } + + } + } + + fn write<F: MessageHandlerFactory<K, T, Output=H>>(&mut self, scope: &mut Scope<F>, mut state: State<H, T>) -> State<H, T> { + let next = match state { + State::Init => { + // this could be a Client request, which writes first, so pay + // attention to the version written here, which will adjust + // our internal state to Http1 or Http2 + let mut handler = scope.create(Seed(&self.key, &self.ctrl.0)); + let mut head = http::MessageHead::default(); + let interest = handler.on_outgoing(&mut head); + if head.version == HttpVersion::Http11 { + let mut buf = Vec::new(); + let keep_alive = self.keep_alive_enabled && head.should_keep_alive(); + let mut encoder = H::Message::encode(head, &mut buf); + let writing = match interest.interest { + // user wants to write some data right away + // try to write the headers and the first chunk + // together, so they are in the same packet + Next_::Write | + Next_::ReadWrite => { + encoder.prefix(WriteBuf { + bytes: buf, + pos: 0 + }); + Writing::Ready(encoder) + }, + _ => Writing::Chunk(Chunk { + buf: Cow::Owned(buf), + pos: 0, + next: (encoder, interest.clone()) + }) + }; + state = State::Http1(Http1 { + reading: Reading::Init, + writing: writing, + handler: handler, + keep_alive: keep_alive, + timeout: interest.timeout, + _marker: PhantomData, + }) + } + Some(interest) + } + State::Http1(Http1 { ref mut handler, ref mut writing, ref mut keep_alive, .. }) => { + match *writing { + Writing::Init => { + trace!("Conn.on_writable Http1::Writing::Init"); + None + } + Writing::Head => { + let mut head = http::MessageHead::default(); + let interest = handler.on_outgoing(&mut head); + // if the request wants to close, server cannot stop it + if *keep_alive { + // if the request wants to stay alive, then it depends + // on the server to agree + *keep_alive = head.should_keep_alive(); + } + let mut buf = Vec::new(); + let mut encoder = <<H as MessageHandler<T>>::Message as Http1Message>::encode(head, &mut buf); + *writing = match interest.interest { + // user wants to write some data right away + // try to write the headers and the first chunk + // together, so they are in the same packet + Next_::Write | + Next_::ReadWrite => { + encoder.prefix(WriteBuf { + bytes: buf, + pos: 0 + }); + Writing::Ready(encoder) + }, + _ => Writing::Chunk(Chunk { + buf: Cow::Owned(buf), + pos: 0, + next: (encoder, interest.clone()) + }) + }; + Some(interest) + }, + Writing::Chunk(ref mut chunk) => { + trace!("Http1.Chunk on_writable"); + match self.transport.write(&chunk.buf.as_ref()[chunk.pos..]) { + Ok(n) => { + chunk.pos += n; + trace!("Http1.Chunk wrote={}, done={}", n, chunk.is_written()); + if chunk.is_written() { + Some(chunk.next.1.clone()) + } else { + None + } + }, + Err(e) => match e.kind() { + io::ErrorKind::WouldBlock | + io::ErrorKind::Interrupted => None, + _ => { + Some(handler.on_error(e.into())) + } + } + } + }, + Writing::Ready(ref mut encoder) => { + trace!("Http1.Ready on_writable"); + Some(handler.on_encode(&mut Encoder::h1(encoder, &mut self.transport))) + }, + Writing::Wait(..) => { + trace!("Conn.on_writable Http1::Writing::Wait"); + None + } + Writing::KeepAlive => { + trace!("Conn.on_writable Http1::Writing::KeepAlive"); + None + } + Writing::Closed => { + trace!("on_writable Http1::Writing::Closed"); + None + } + } + }, + State::Closed => { + trace!("on_writable State::Closed"); + None + } + }; + + if let Some(next) = next { + state.update(next); + } + state + } + + fn can_read_more(&self) -> bool { + match self.state { + State::Init => false, + _ => !self.buf.is_empty() + } + } + + pub fn ready<F>(mut self, events: EventSet, scope: &mut Scope<F>) -> Option<(Self, Option<Duration>)> + where F: MessageHandlerFactory<K, T, Output=H> { + trace!("Conn::ready events='{:?}', blocked={:?}", events, self.transport.blocked()); + + if events.is_error() { + match self.transport.take_socket_error() { + Ok(_) => { + trace!("is_error, but not socket error"); + // spurious? + }, + Err(e) => self.on_error(e.into()) + } + } + + // if the user had an io interest, but the transport was blocked differently, + // the event needs to be translated to what the user was actually expecting. + // + // Example: + // - User asks for `Next::write(). + // - But transport is in the middle of renegotiating TLS, and is blocked on reading. + // - hyper should not wait on the `write` event, since epoll already + // knows it is writable. We would just loop a whole bunch, and slow down. + // - So instead, hyper waits on the event needed to unblock the transport, `read`. + // - Once epoll detects the transport is readable, it will alert hyper + // with a `readable` event. + // - hyper needs to translate that `readable` event back into a `write`, + // since that is actually what the Handler wants. + + let events = if let Some(blocked) = self.transport.blocked() { + let interest = self.interest(); + trace!("translating blocked={:?}, interest={:?}", blocked, interest); + match (blocked, interest) { + (Blocked::Read, Reg::Write) => EventSet::writable(), + (Blocked::Write, Reg::Read) => EventSet::readable(), + // otherwise, the transport was blocked on the same thing the user wanted + _ => events + } + } else { + events + }; + + if events.is_readable() { + self.on_readable(scope); + } + + if events.is_writable() { + self.on_writable(scope); + } + + let events = match self.register() { + Reg::Read => EventSet::readable(), + Reg::Write => EventSet::writable(), + Reg::ReadWrite => EventSet::readable() | EventSet::writable(), + Reg::Wait => EventSet::none(), + Reg::Remove => { + trace!("removing transport"); + let _ = scope.deregister(&self.transport); + self.on_remove(); + return None; + }, + }; + + if events.is_readable() && self.can_read_more() { + return self.ready(events, scope); + } + + trace!("scope.reregister({:?})", events); + match scope.reregister(&self.transport, events, PollOpt::level()) { + Ok(..) => { + let timeout = self.state.timeout(); + Some((self, timeout)) + }, + Err(e) => { + error!("error reregistering: {:?}", e); + None + } + } + } + + pub fn wakeup<F>(mut self, scope: &mut Scope<F>) -> Option<(Self, Option<Duration>)> + where F: MessageHandlerFactory<K, T, Output=H> { + loop { + match self.ctrl.1.try_recv() { + Ok(next) => { + trace!("woke up with {:?}", next); + self.state.update(next); + }, + Err(_) => break + } + } + self.ready(EventSet::readable() | EventSet::writable(), scope) + } + + pub fn timeout<F>(mut self, scope: &mut Scope<F>) -> Option<(Self, Option<Duration>)> + where F: MessageHandlerFactory<K, T, Output=H> { + //TODO: check if this was a spurious timeout? + self.on_error(::Error::Timeout); + self.ready(EventSet::none(), scope) + } + + fn on_error(&mut self, err: ::Error) { + debug!("on_error err = {:?}", err); + trace!("on_error state = {:?}", self.state); + let next = match self.state { + State::Init => Next::remove(), + State::Http1(ref mut http1) => http1.handler.on_error(err), + State::Closed => Next::remove(), + }; + self.state.update(next); + } + + fn on_remove(self) { + debug!("on_remove"); + match self.state { + State::Init | State::Closed => (), + State::Http1(http1) => http1.handler.on_remove(self.transport), + } + } + + fn on_readable<F>(&mut self, scope: &mut Scope<F>) + where F: MessageHandlerFactory<K, T, Output=H> { + trace!("on_readable -> {:?}", self.state); + let state = mem::replace(&mut self.state, State::Closed); + self.state = self.read(scope, state); + trace!("on_readable <- {:?}", self.state); + } + + fn on_writable<F>(&mut self, scope: &mut Scope<F>) + where F: MessageHandlerFactory<K, T, Output=H> { + trace!("on_writable -> {:?}", self.state); + let state = mem::replace(&mut self.state, State::Closed); + self.state = self.write(scope, state); + trace!("on_writable <- {:?}", self.state); + } +} + +enum State<H: MessageHandler<T>, T: Transport> { + Init, + /// Http1 will only ever use a connection to send and receive a single + /// message at a time. Once a H1 status has been determined, we will either + /// be reading or writing an H1 message, and optionally multiple if + /// keep-alive is true. + Http1(Http1<H, T>), + /// Http2 allows multiplexing streams over a single connection. So even + /// when we've identified a certain message, we must always parse frame + /// head to determine if the incoming frame is part of a current message, + /// or a new one. This also means we could have multiple messages at once. + //Http2 {}, + Closed, +} + + +impl<H: MessageHandler<T>, T: Transport> State<H, T> { + fn timeout(&self) -> Option<Duration> { + match *self { + State::Init => None, + State::Http1(ref http1) => http1.timeout, + State::Closed => None, + } + } +} + +impl<H: MessageHandler<T>, T: Transport> fmt::Debug for State<H, T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + State::Init => f.write_str("Init"), + State::Http1(ref h1) => f.debug_tuple("Http1") + .field(h1) + .finish(), + State::Closed => f.write_str("Closed") + } + } +} + +impl<H: MessageHandler<T>, T: Transport> State<H, T> { + fn update(&mut self, next: Next) { + let timeout = next.timeout; + let state = mem::replace(self, State::Closed); + let new_state = match (state, next.interest) { + (_, Next_::Remove) => State::Closed, + (State::Closed, _) => State::Closed, + (State::Init, _) => State::Init, + (State::Http1(http1), Next_::End) => { + let reading = match http1.reading { + Reading::Body(ref decoder) if decoder.is_eof() => { + if http1.keep_alive { + Reading::KeepAlive + } else { + Reading::Closed + } + }, + Reading::KeepAlive => http1.reading, + _ => Reading::Closed, + }; + let writing = match http1.writing { + Writing::Ready(ref encoder) if encoder.is_eof() => { + if http1.keep_alive { + Writing::KeepAlive + } else { + Writing::Closed + } + }, + Writing::Ready(encoder) => { + if encoder.is_eof() { + if http1.keep_alive { + Writing::KeepAlive + } else { + Writing::Closed + } + } else if let Some(buf) = encoder.end() { + Writing::Chunk(Chunk { + buf: buf.bytes, + pos: buf.pos, + next: (h1::Encoder::length(0), Next::end()) + }) + } else { + Writing::Closed + } + } + Writing::Chunk(mut chunk) => { + if chunk.is_written() { + let encoder = chunk.next.0; + //TODO: de-dupe this code and from Writing::Ready + if encoder.is_eof() { + if http1.keep_alive { + Writing::KeepAlive + } else { + Writing::Closed + } + } else if let Some(buf) = encoder.end() { + Writing::Chunk(Chunk { + buf: buf.bytes, + pos: buf.pos, + next: (h1::Encoder::length(0), Next::end()) + }) + } else { + Writing::Closed + } + } else { + chunk.next.1 = next; + Writing::Chunk(chunk) + } + }, + _ => Writing::Closed, + }; + match (reading, writing) { + (Reading::KeepAlive, Writing::KeepAlive) => State::Init, + (reading, Writing::Chunk(chunk)) => { + State::Http1(Http1 { + reading: reading, + writing: Writing::Chunk(chunk), + .. http1 + }) + } + _ => State::Closed + } + }, + (State::Http1(mut http1), Next_::Read) => { + http1.reading = match http1.reading { + Reading::Init => Reading::Parse, + Reading::Wait(decoder) => Reading::Body(decoder), + same => same + }; + + http1.writing = match http1.writing { + Writing::Ready(encoder) => if encoder.is_eof() { + if http1.keep_alive { + Writing::KeepAlive + } else { + Writing::Closed + } + } else { + Writing::Wait(encoder) + }, + Writing::Chunk(chunk) => if chunk.is_written() { + Writing::Wait(chunk.next.0) + } else { + Writing::Chunk(chunk) + }, + same => same + }; + + State::Http1(http1) + }, + (State::Http1(mut http1), Next_::Write) => { + http1.writing = match http1.writing { + Writing::Wait(encoder) => Writing::Ready(encoder), + Writing::Init => Writing::Head, + Writing::Chunk(chunk) => if chunk.is_written() { + Writing::Ready(chunk.next.0) + } else { + Writing::Chunk(chunk) + }, + same => same + }; + + http1.reading = match http1.reading { + Reading::Body(decoder) => if decoder.is_eof() { + if http1.keep_alive { + Reading::KeepAlive + } else { + Reading::Closed + } + } else { + Reading::Wait(decoder) + }, + same => same + }; + State::Http1(http1) + }, + (State::Http1(mut http1), Next_::ReadWrite) => { + http1.reading = match http1.reading { + Reading::Init => Reading::Parse, + Reading::Wait(decoder) => Reading::Body(decoder), + same => same + }; + http1.writing = match http1.writing { + Writing::Wait(encoder) => Writing::Ready(encoder), + Writing::Init => Writing::Head, + Writing::Chunk(chunk) => if chunk.is_written() { + Writing::Ready(chunk.next.0) + } else { + Writing::Chunk(chunk) + }, + same => same + }; + State::Http1(http1) + }, + (State::Http1(mut http1), Next_::Wait) => { + http1.reading = match http1.reading { + Reading::Body(decoder) => Reading::Wait(decoder), + same => same + }; + + http1.writing = match http1.writing { + Writing::Ready(encoder) => Writing::Wait(encoder), + Writing::Chunk(chunk) => if chunk.is_written() { + Writing::Wait(chunk.next.0) + } else { + Writing::Chunk(chunk) + }, + same => same + }; + State::Http1(http1) + } + }; + let new_state = match new_state { + State::Http1(mut http1) => { + http1.timeout = timeout; + State::Http1(http1) + } + other => other + }; + mem::replace(self, new_state); + } +} + +// These Reading and Writing stuff should probably get moved into h1/message.rs + +struct Http1<H, T> { + handler: H, + reading: Reading, + writing: Writing, + keep_alive: bool, + timeout: Option<Duration>, + _marker: PhantomData<T>, +} + +impl<H, T> fmt::Debug for Http1<H, T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Http1") + .field("reading", &self.reading) + .field("writing", &self.writing) + .field("keep_alive", &self.keep_alive) + .field("timeout", &self.timeout) + .finish() + } +} + +#[derive(Debug)] +enum Reading { + Init, + Parse, + Body(h1::Decoder), + Wait(h1::Decoder), + KeepAlive, + Closed +} + +#[derive(Debug)] +enum Writing { + Init, + Head, + Chunk(Chunk) , + Ready(h1::Encoder), + Wait(h1::Encoder), + KeepAlive, + Closed +} + +#[derive(Debug)] +struct Chunk { + buf: Cow<'static, [u8]>, + pos: usize, + next: (h1::Encoder, Next), +} + +impl Chunk { + fn is_written(&self) -> bool { + self.pos >= self.buf.len() + } +} + +pub trait MessageHandler<T: Transport> { + type Message: Http1Message; + fn on_incoming(&mut self, head: http::MessageHead<<Self::Message as Http1Message>::Incoming>) -> Next; + fn on_outgoing(&mut self, head: &mut http::MessageHead<<Self::Message as Http1Message>::Outgoing>) -> Next; + fn on_decode(&mut self, &mut http::Decoder<T>) -> Next; + fn on_encode(&mut self, &mut http::Encoder<T>) -> Next; + fn on_error(&mut self, err: ::Error) -> Next; + + fn on_remove(self, T) where Self: Sized; +} + +pub struct Seed<'a, K: Key + 'a>(&'a K, &'a channel::Sender<Next>); + +impl<'a, K: Key + 'a> Seed<'a, K> { + pub fn control(&self) -> Control { + Control { + tx: self.1.clone(), + } + } + + pub fn key(&self) -> &K { + &self.0 + } +} + + +pub trait MessageHandlerFactory<K: Key, T: Transport> { + type Output: MessageHandler<T>; + + fn create(&mut self, seed: Seed<K>) -> Self::Output; +} + +impl<F, K, H, T> MessageHandlerFactory<K, T> for F +where F: FnMut(Seed<K>) -> H, + K: Key, + H: MessageHandler<T>, + T: Transport { + type Output = H; + fn create(&mut self, seed: Seed<K>) -> H { + self(seed) + } +} + +pub trait Key: Eq + Hash + Clone {} +impl<T: Eq + Hash + Clone> Key for T {} + +#[cfg(test)] +mod tests { + /* TODO: + test when the underlying Transport of a Conn is blocked on an action that + differs from the desired interest(). + + Ex: + transport.blocked() == Some(Blocked::Read) + self.interest() == Reg::Write + + Should call `scope.register(EventSet::read())`, not with write + + #[test] + fn test_conn_register_when_transport_blocked() { + + } + */ +} diff --git a/src/http/h1.rs /dev/null --- a/src/http/h1.rs +++ /dev/null @@ -1,1137 +0,0 @@ -//! Adapts the HTTP/1.1 implementation into the `HttpMessage` API. -use std::borrow::Cow; -use std::cmp::min; -use std::fmt; -use std::io::{self, Write, BufWriter, BufRead, Read}; -use std::net::Shutdown; -use std::time::Duration; - -use httparse; -use url::Position as UrlPosition; - -use buffer::BufReader; -use Error; -use header::{Headers, ContentLength, TransferEncoding}; -use header::Encoding::Chunked; -use method::{Method}; -use net::{NetworkConnector, NetworkStream}; -use status::StatusCode; -use version::HttpVersion; -use version::HttpVersion::{Http10, Http11}; -use uri::RequestUri; - -use self::HttpReader::{SizedReader, ChunkedReader, EofReader, EmptyReader}; -use self::HttpWriter::{ChunkedWriter, SizedWriter, EmptyWriter, ThroughWriter}; - -use http::{ - RawStatus, - Protocol, - HttpMessage, - RequestHead, - ResponseHead, -}; -use header; -use version; - -const MAX_INVALID_RESPONSE_BYTES: usize = 1024 * 128; - -#[derive(Debug)] -struct Wrapper<T> { - obj: Option<T>, -} - -impl<T> Wrapper<T> { - pub fn new(obj: T) -> Wrapper<T> { - Wrapper { obj: Some(obj) } - } - - pub fn map_in_place<F>(&mut self, f: F) where F: FnOnce(T) -> T { - let obj = self.obj.take().unwrap(); - let res = f(obj); - self.obj = Some(res); - } - - pub fn into_inner(self) -> T { self.obj.unwrap() } - pub fn as_mut(&mut self) -> &mut T { self.obj.as_mut().unwrap() } - pub fn as_ref(&self) -> &T { self.obj.as_ref().unwrap() } -} - -#[derive(Debug)] -enum Stream { - Idle(Box<NetworkStream + Send>), - Writing(HttpWriter<BufWriter<Box<NetworkStream + Send>>>), - Reading(HttpReader<BufReader<Box<NetworkStream + Send>>>), -} - -impl Stream { - fn writer_mut(&mut self) -> Option<&mut HttpWriter<BufWriter<Box<NetworkStream + Send>>>> { - match *self { - Stream::Writing(ref mut writer) => Some(writer), - _ => None, - } - } - fn reader_mut(&mut self) -> Option<&mut HttpReader<BufReader<Box<NetworkStream + Send>>>> { - match *self { - Stream::Reading(ref mut reader) => Some(reader), - _ => None, - } - } - fn reader_ref(&self) -> Option<&HttpReader<BufReader<Box<NetworkStream + Send>>>> { - match *self { - Stream::Reading(ref reader) => Some(reader), - _ => None, - } - } - - fn new(stream: Box<NetworkStream + Send>) -> Stream { - Stream::Idle(stream) - } -} - -/// An implementation of the `HttpMessage` trait for HTTP/1.1. -#[derive(Debug)] -pub struct Http11Message { - is_proxied: bool, - method: Option<Method>, - stream: Wrapper<Stream>, -} - -impl Write for Http11Message { - #[inline] - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - match self.stream.as_mut().writer_mut() { - None => Err(io::Error::new(io::ErrorKind::Other, - "Not in a writable state")), - Some(ref mut writer) => writer.write(buf), - } - } - #[inline] - fn flush(&mut self) -> io::Result<()> { - match self.stream.as_mut().writer_mut() { - None => Err(io::Error::new(io::ErrorKind::Other, - "Not in a writable state")), - Some(ref mut writer) => writer.flush(), - } - } -} - -impl Read for Http11Message { - #[inline] - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - match self.stream.as_mut().reader_mut() { - None => Err(io::Error::new(io::ErrorKind::Other, - "Not in a readable state")), - Some(ref mut reader) => reader.read(buf), - } - } -} - -impl HttpMessage for Http11Message { - fn set_outgoing(&mut self, mut head: RequestHead) -> ::Result<RequestHead> { - let mut res = Err(Error::from(io::Error::new( - io::ErrorKind::Other, - ""))); - let mut method = None; - let is_proxied = self.is_proxied; - self.stream.map_in_place(|stream: Stream| -> Stream { - let stream = match stream { - Stream::Idle(stream) => stream, - _ => { - res = Err(Error::from(io::Error::new( - io::ErrorKind::Other, - "Message not idle, cannot start new outgoing"))); - return stream; - }, - }; - let mut stream = BufWriter::new(stream); - - { - let uri = if is_proxied { - head.url.as_ref() - } else { - &head.url[UrlPosition::BeforePath..UrlPosition::AfterQuery] - }; - - let version = version::HttpVersion::Http11; - debug!("request line: {:?} {:?} {:?}", head.method, uri, version); - match write!(&mut stream, "{} {} {}{}", - head.method, uri, version, LINE_ENDING) { - Err(e) => { - res = Err(From::from(e)); - // TODO What should we do if the BufWriter doesn't wanna - // relinquish the stream? - return Stream::Idle(stream.into_inner().ok().unwrap()); - }, - Ok(_) => {}, - }; - } - - let stream = { - let write_headers = |mut stream: BufWriter<Box<NetworkStream + Send>>, head: &RequestHead| { - debug!("headers={:?}", head.headers); - match write!(&mut stream, "{}{}", head.headers, LINE_ENDING) { - Ok(_) => Ok(stream), - Err(e) => { - Err((e, stream.into_inner().unwrap())) - } - } - }; - match head.method { - Method::Get | Method::Head => { - let writer = match write_headers(stream, &head) { - Ok(w) => w, - Err(e) => { - res = Err(From::from(e.0)); - return Stream::Idle(e.1); - } - }; - EmptyWriter(writer) - }, - _ => { - let mut chunked = true; - let mut len = 0; - - match head.headers.get::<header::ContentLength>() { - Some(cl) => { - chunked = false; - len = **cl; - }, - None => () - }; - - // can't do in match above, thanks borrowck - if chunked { - let encodings = match head.headers.get_mut::<header::TransferEncoding>() { - Some(encodings) => { - //TODO: check if chunked is already in encodings. use HashSet? - encodings.push(header::Encoding::Chunked); - false - }, - None => true - }; - - if encodings { - head.headers.set( - header::TransferEncoding(vec![header::Encoding::Chunked])) - } - } - - let stream = match write_headers(stream, &head) { - Ok(s) => s, - Err(e) => { - res = Err(From::from(e.0)); - return Stream::Idle(e.1); - }, - }; - - if chunked { - ChunkedWriter(stream) - } else { - SizedWriter(stream, len) - } - } - } - }; - - method = Some(head.method.clone()); - res = Ok(head); - Stream::Writing(stream) - }); - - self.method = method; - res - } - - fn get_incoming(&mut self) -> ::Result<ResponseHead> { - try!(self.flush_outgoing()); - let method = self.method.take().unwrap_or(Method::Get); - let mut res = Err(From::from( - io::Error::new(io::ErrorKind::Other, - "Read already in progress"))); - self.stream.map_in_place(|stream| { - let stream = match stream { - Stream::Idle(stream) => stream, - _ => { - // The message was already in the reading state... - // TODO Decide what happens in case we try to get a new incoming at that point - res = Err(From::from( - io::Error::new(io::ErrorKind::Other, - "Read already in progress"))); - return stream; - } - }; - - let expected_no_content = stream.previous_response_expected_no_content(); - trace!("previous_response_expected_no_content = {}", expected_no_content); - - let mut stream = BufReader::new(stream); - - let mut invalid_bytes_read = 0; - let head; - loop { - head = match parse_response(&mut stream) { - Ok(head) => head, - Err(::Error::Version) - if expected_no_content && invalid_bytes_read < MAX_INVALID_RESPONSE_BYTES => { - trace!("expected_no_content, found content"); - invalid_bytes_read += 1; - stream.consume(1); - continue; - } - Err(e) => { - res = Err(e); - return Stream::Idle(stream.into_inner()); - } - }; - break; - } - - let raw_status = head.subject; - let headers = head.headers; - - let is_empty = !should_have_response_body(&method, raw_status.0); - stream.get_mut().set_previous_response_expected_no_content(is_empty); - // According to https://tools.ietf.org/html/rfc7230#section-3.3.3 - // 1. HEAD reponses, and Status 1xx, 204, and 304 cannot have a body. - // 2. Status 2xx to a CONNECT cannot have a body. - // 3. Transfer-Encoding: chunked has a chunked body. - // 4. If multiple differing Content-Length headers or invalid, close connection. - // 5. Content-Length header has a sized body. - // 6. Not Client. - // 7. Read till EOF. - let reader = if is_empty { - EmptyReader(stream) - } else { - if let Some(&TransferEncoding(ref codings)) = headers.get() { - if codings.last() == Some(&Chunked) { - ChunkedReader(stream, None) - } else { - trace!("not chuncked. read till eof"); - EofReader(stream) - } - } else if let Some(&ContentLength(len)) = headers.get() { - SizedReader(stream, len) - } else if headers.has::<ContentLength>() { - trace!("illegal Content-Length: {:?}", headers.get_raw("Content-Length")); - res = Err(Error::Header); - return Stream::Idle(stream.into_inner()); - } else { - trace!("neither Transfer-Encoding nor Content-Length"); - EofReader(stream) - } - }; - - trace!("Http11Message.reader = {:?}", reader); - - - res = Ok(ResponseHead { - headers: headers, - raw_status: raw_status, - version: head.version, - }); - - Stream::Reading(reader) - }); - res - } - - fn has_body(&self) -> bool { - match self.stream.as_ref().reader_ref() { - Some(&EmptyReader(..)) | - Some(&SizedReader(_, 0)) | - Some(&ChunkedReader(_, Some(0))) => false, - // specifically EofReader is always true - _ => true - } - } - - #[inline] - fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.get_ref().set_read_timeout(dur) - } - - #[inline] - fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.get_ref().set_write_timeout(dur) - } - - #[inline] - fn close_connection(&mut self) -> ::Result<()> { - try!(self.get_mut().close(Shutdown::Both)); - Ok(()) - } - - #[inline] - fn set_proxied(&mut self, val: bool) { - self.is_proxied = val; - } -} - -impl Http11Message { - /// Consumes the `Http11Message` and returns the underlying `NetworkStream`. - pub fn into_inner(self) -> Box<NetworkStream + Send> { - match self.stream.into_inner() { - Stream::Idle(stream) => stream, - Stream::Writing(stream) => stream.into_inner().into_inner().unwrap(), - Stream::Reading(stream) => stream.into_inner().into_inner(), - } - } - - /// Gets a mutable reference to the underlying `NetworkStream`, regardless of the state of the - /// `Http11Message`. - pub fn get_ref(&self) -> &(NetworkStream + Send) { - match *self.stream.as_ref() { - Stream::Idle(ref stream) => &**stream, - Stream::Writing(ref stream) => &**stream.get_ref().get_ref(), - Stream::Reading(ref stream) => &**stream.get_ref().get_ref() - } - } - - /// Gets a mutable reference to the underlying `NetworkStream`, regardless of the state of the - /// `Http11Message`. - pub fn get_mut(&mut self) -> &mut (NetworkStream + Send) { - match *self.stream.as_mut() { - Stream::Idle(ref mut stream) => &mut **stream, - Stream::Writing(ref mut stream) => &mut **stream.get_mut().get_mut(), - Stream::Reading(ref mut stream) => &mut **stream.get_mut().get_mut() - } - } - - /// Creates a new `Http11Message` that will use the given `NetworkStream` for communicating to - /// the peer. - pub fn with_stream(stream: Box<NetworkStream + Send>) -> Http11Message { - Http11Message { - is_proxied: false, - method: None, - stream: Wrapper::new(Stream::new(stream)), - } - } - - /// Flushes the current outgoing content and moves the stream into the `stream` property. - /// - /// TODO It might be sensible to lift this up to the `HttpMessage` trait itself... - pub fn flush_outgoing(&mut self) -> ::Result<()> { - let mut res = Ok(()); - self.stream.map_in_place(|stream| { - let writer = match stream { - Stream::Writing(writer) => writer, - _ => { - res = Ok(()); - return stream; - }, - }; - // end() already flushes - let raw = match writer.end() { - Ok(buf) => buf.into_inner().unwrap(), - Err(e) => { - res = Err(From::from(e.0)); - return Stream::Writing(e.1); - } - }; - Stream::Idle(raw) - }); - res - } -} - -/// The `Protocol` implementation provides HTTP/1.1 messages. -pub struct Http11Protocol { - connector: Connector, -} - -impl Protocol for Http11Protocol { - fn new_message(&self, host: &str, port: u16, scheme: &str) -> ::Result<Box<HttpMessage>> { - let stream = try!(self.connector.connect(host, port, scheme)).into(); - - Ok(Box::new(Http11Message::with_stream(stream))) - } -} - -impl Http11Protocol { - /// Creates a new `Http11Protocol` instance that will use the given `NetworkConnector` for - /// establishing HTTP connections. - pub fn with_connector<C, S>(c: C) -> Http11Protocol - where C: NetworkConnector<Stream=S> + Send + Sync + 'static, - S: NetworkStream + Send { - Http11Protocol { - connector: Connector(Box::new(ConnAdapter(c))), - } - } -} - -struct ConnAdapter<C: NetworkConnector + Send + Sync>(C); - -impl<C: NetworkConnector<Stream=S> + Send + Sync, S: NetworkStream + Send> - NetworkConnector for ConnAdapter<C> { - type Stream = Box<NetworkStream + Send>; - #[inline] - fn connect(&self, host: &str, port: u16, scheme: &str) - -> ::Result<Box<NetworkStream + Send>> { - Ok(try!(self.0.connect(host, port, scheme)).into()) - } -} - -struct Connector(Box<NetworkConnector<Stream=Box<NetworkStream + Send>> + Send + Sync>); - -impl NetworkConnector for Connector { - type Stream = Box<NetworkStream + Send>; - #[inline] - fn connect(&self, host: &str, port: u16, scheme: &str) - -> ::Result<Box<NetworkStream + Send>> { - Ok(try!(self.0.connect(host, port, scheme)).into()) - } -} - - -/// Readers to handle different Transfer-Encodings. -/// -/// If a message body does not include a Transfer-Encoding, it *should* -/// include a Content-Length header. -pub enum HttpReader<R> { - /// A Reader used when a Content-Length header is passed with a positive integer. - SizedReader(R, u64), - /// A Reader used when Transfer-Encoding is `chunked`. - ChunkedReader(R, Option<u64>), - /// A Reader used for responses that don't indicate a length or chunked. - /// - /// Note: This should only used for `Response`s. It is illegal for a - /// `Request` to be made with both `Content-Length` and - /// `Transfer-Encoding: chunked` missing, as explained from the spec: - /// - /// > If a Transfer-Encoding header field is present in a response and - /// > the chunked transfer coding is not the final encoding, the - /// > message body length is determined by reading the connection until - /// > it is closed by the server. If a Transfer-Encoding header field - /// > is present in a request and the chunked transfer coding is not - /// > the final encoding, the message body length cannot be determined - /// > reliably; the server MUST respond with the 400 (Bad Request) - /// > status code and then close the connection. - EofReader(R), - /// A Reader used for messages that should never have a body. - /// - /// See https://tools.ietf.org/html/rfc7230#section-3.3.3 - EmptyReader(R), -} - -impl<R: Read> HttpReader<R> { - - /// Unwraps this HttpReader and returns the underlying Reader. - pub fn into_inner(self) -> R { - match self { - SizedReader(r, _) => r, - ChunkedReader(r, _) => r, - EofReader(r) => r, - EmptyReader(r) => r, - } - } - - /// Gets a borrowed reference to the underlying Reader. - pub fn get_ref(&self) -> &R { - match *self { - SizedReader(ref r, _) => r, - ChunkedReader(ref r, _) => r, - EofReader(ref r) => r, - EmptyReader(ref r) => r, - } - } - - /// Gets a mutable reference to the underlying Reader. - pub fn get_mut(&mut self) -> &mut R { - match *self { - SizedReader(ref mut r, _) => r, - ChunkedReader(ref mut r, _) => r, - EofReader(ref mut r) => r, - EmptyReader(ref mut r) => r, - } - } -} - -impl<R> fmt::Debug for HttpReader<R> { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - match *self { - SizedReader(_,rem) => write!(fmt, "SizedReader(remaining={:?})", rem), - ChunkedReader(_, None) => write!(fmt, "ChunkedReader(chunk_remaining=unknown)"), - ChunkedReader(_, Some(rem)) => write!(fmt, "ChunkedReader(chunk_remaining={:?})", rem), - EofReader(_) => write!(fmt, "EofReader"), - EmptyReader(_) => write!(fmt, "EmptyReader"), - } - } -} - -impl<R: Read> Read for HttpReader<R> { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - match *self { - SizedReader(ref mut body, ref mut remaining) => { - trace!("Sized read, remaining={:?}", remaining); - if *remaining == 0 { - Ok(0) - } else { - let to_read = min(*remaining as usize, buf.len()); - let num = try!(body.read(&mut buf[..to_read])) as u64; - trace!("Sized read: {}", num); - if num > *remaining { - *remaining = 0; - } else if num == 0 { - return Err(io::Error::new(io::ErrorKind::Other, "early eof")); - } else { - *remaining -= num; - } - Ok(num as usize) - } - }, - ChunkedReader(ref mut body, ref mut opt_remaining) => { - let mut rem = match *opt_remaining { - Some(ref rem) => *rem, - // None means we don't know the size of the next chunk - None => try!(read_chunk_size(body)) - }; - trace!("Chunked read, remaining={:?}", rem); - - if rem == 0 { - *opt_remaining = Some(0); - - // chunk of size 0 signals the end of the chunked stream - // if the 0 digit was missing from the stream, it would - // be an InvalidInput error instead. - trace!("end of chunked"); - return Ok(0) - } - - let to_read = min(rem as usize, buf.len()); - let count = try!(body.read(&mut buf[..to_read])) as u64; - - if count == 0 { - *opt_remaining = Some(0); - return Err(io::Error::new(io::ErrorKind::Other, "early eof")); - } - - rem -= count; - *opt_remaining = if rem > 0 { - Some(rem) - } else { - try!(eat(body, LINE_ENDING.as_bytes())); - None - }; - Ok(count as usize) - }, - EofReader(ref mut body) => { - let r = body.read(buf); - trace!("eofread: {:?}", r); - r - }, - EmptyReader(_) => Ok(0) - } - } -} - -fn eat<R: Read>(rdr: &mut R, bytes: &[u8]) -> io::Result<()> { - let mut buf = [0]; - for &b in bytes.iter() { - match try!(rdr.read(&mut buf)) { - 1 if buf[0] == b => (), - _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, - "Invalid characters found")), - } - } - Ok(()) -} - -/// Chunked chunks start with 1*HEXDIGIT, indicating the size of the chunk. -fn read_chunk_size<R: Read>(rdr: &mut R) -> io::Result<u64> { - macro_rules! byte ( - ($rdr:ident) => ({ - let mut buf = [0]; - match try!($rdr.read(&mut buf)) { - 1 => buf[0], - _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, - "Invalid chunk size line")), - - } - }) - ); - let mut size = 0u64; - let radix = 16; - let mut in_ext = false; - let mut in_chunk_size = true; - loop { - match byte!(rdr) { - b@b'0'...b'9' if in_chunk_size => { - size *= radix; - size += (b - b'0') as u64; - }, - b@b'a'...b'f' if in_chunk_size => { - size *= radix; - size += (b + 10 - b'a') as u64; - }, - b@b'A'...b'F' if in_chunk_size => { - size *= radix; - size += (b + 10 - b'A') as u64; - }, - CR => { - match byte!(rdr) { - LF => break, - _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, - "Invalid chunk size line")) - - } - }, - // If we weren't in the extension yet, the ";" signals its start - b';' if !in_ext => { - in_ext = true; - in_chunk_size = false; - }, - // "Linear white space" is ignored between the chunk size and the - // extension separator token (";") due to the "implied *LWS rule". - b'\t' | b' ' if !in_ext & !in_chunk_size => {}, - // LWS can follow the chunk size, but no more digits can come - b'\t' | b' ' if in_chunk_size => in_chunk_size = false, - // We allow any arbitrary octet once we are in the extension, since - // they all get ignored anyway. According to the HTTP spec, valid - // extensions would have a more strict syntax: - // (token ["=" (token | quoted-string)]) - // but we gain nothing by rejecting an otherwise valid chunk size. - ext if in_ext => { - todo!("chunk extension byte={}", ext); - }, - // Finally, if we aren't in the extension and we're reading any - // other octet, the chunk size line is invalid! - _ => { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "Invalid chunk size line")); - } - } - } - trace!("chunk size={:?}", size); - Ok(size) -} - -fn should_have_response_body(method: &Method, status: u16) -> bool { - trace!("should_have_response_body({:?}, {})", method, status); - match (method, status) { - (&Method::Head, _) | - (_, 100...199) | - (_, 204) | - (_, 304) | - (&Method::Connect, 200...299) => false, - _ => true - } -} - -/// Writers to handle different Transfer-Encodings. -pub enum HttpWriter<W: Write> { - /// A no-op Writer, used initially before Transfer-Encoding is determined. - ThroughWriter(W), - /// A Writer for when Transfer-Encoding includes `chunked`. - ChunkedWriter(W), - /// A Writer for when Content-Length is set. - /// - /// Enforces that the body is not longer than the Content-Length header. - SizedWriter(W, u64), - /// A writer that should not write any body. - EmptyWriter(W), -} - -impl<W: Write> HttpWriter<W> { - /// Unwraps the HttpWriter and returns the underlying Writer. - #[inline] - pub fn into_inner(self) -> W { - match self { - ThroughWriter(w) => w, - ChunkedWriter(w) => w, - SizedWriter(w, _) => w, - EmptyWriter(w) => w, - } - } - - /// Access the inner Writer. - #[inline] - pub fn get_ref(&self) -> &W { - match *self { - ThroughWriter(ref w) => w, - ChunkedWriter(ref w) => w, - SizedWriter(ref w, _) => w, - EmptyWriter(ref w) => w, - } - } - - /// Access the inner Writer mutably. - /// - /// Warning: You should not write to this directly, as you can corrupt - /// the state. - #[inline] - pub fn get_mut(&mut self) -> &mut W { - match *self { - ThroughWriter(ref mut w) => w, - ChunkedWriter(ref mut w) => w, - SizedWriter(ref mut w, _) => w, - EmptyWriter(ref mut w) => w, - } - } - - /// Ends the HttpWriter, and returns the underlying Writer. - /// - /// A final `write_all()` is called with an empty message, and then flushed. - /// The ChunkedWriter variant will use this to write the 0-sized last-chunk. - #[inline] - pub fn end(mut self) -> Result<W, EndError<W>> { - fn inner<W: Write>(w: &mut W) -> io::Result<()> { - try!(w.write(&[])); - w.flush() - } - - match inner(&mut self) { - Ok(..) => Ok(self.into_inner()), - Err(e) => Err(EndError(e, self)) - } - } -} - -#[derive(Debug)] -pub struct EndError<W: Write>(io::Error, HttpWriter<W>); - -impl<W: Write> From<EndError<W>> for io::Error { - fn from(e: EndError<W>) -> io::Error { - e.0 - } -} - -impl<W: Write> Write for HttpWriter<W> { - #[inline] - fn write(&mut self, msg: &[u8]) -> io::Result<usize> { - match *self { - ThroughWriter(ref mut w) => w.write(msg), - ChunkedWriter(ref mut w) => { - let chunk_size = msg.len(); - trace!("chunked write, size = {:?}", chunk_size); - try!(write!(w, "{:X}{}", chunk_size, LINE_ENDING)); - try!(w.write_all(msg)); - try!(w.write_all(LINE_ENDING.as_bytes())); - Ok(msg.len()) - }, - SizedWriter(ref mut w, ref mut remaining) => { - let len = msg.len() as u64; - if len > *remaining { - let len = *remaining; - *remaining = 0; - try!(w.write_all(&msg[..len as usize])); - Ok(len as usize) - } else { - *remaining -= len; - try!(w.write_all(msg)); - Ok(len as usize) - } - }, - EmptyWriter(..) => { - if !msg.is_empty() { - error!("Cannot include a body with this kind of message"); - } - Ok(0) - } - } - } - - #[inline] - fn flush(&mut self) -> io::Result<()> { - match *self { - ThroughWriter(ref mut w) => w.flush(), - ChunkedWriter(ref mut w) => w.flush(), - SizedWriter(ref mut w, _) => w.flush(), - EmptyWriter(ref mut w) => w.flush(), - } - } -} - -impl<W: Write> fmt::Debug for HttpWriter<W> { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - match *self { - ThroughWriter(_) => write!(fmt, "ThroughWriter"), - ChunkedWriter(_) => write!(fmt, "ChunkedWriter"), - SizedWriter(_, rem) => write!(fmt, "SizedWriter(remaining={:?})", rem), - EmptyWriter(_) => write!(fmt, "EmptyWriter"), - } - } -} - -const MAX_HEADERS: usize = 100; - -/// Parses a request into an Incoming message head. -#[inline] -pub fn parse_request<R: Read>(buf: &mut BufReader<R>) -> ::Result<Incoming<(Method, RequestUri)>> { - parse::<R, httparse::Request, (Method, RequestUri)>(buf) -} - -/// Parses a response into an Incoming message head. -#[inline] -pub fn parse_response<R: Read>(buf: &mut BufReader<R>) -> ::Result<Incoming<RawStatus>> { - parse::<R, httparse::Response, RawStatus>(buf) -} - -fn parse<R: Read, T: TryParse<Subject=I>, I>(rdr: &mut BufReader<R>) -> ::Result<Incoming<I>> { - loop { - match try!(try_parse::<R, T, I>(rdr)) { - httparse::Status::Complete((inc, len)) => { - rdr.consume(len); - return Ok(inc); - }, - _partial => () - } - match try!(rdr.read_into_buf()) { - 0 if rdr.get_buf().is_empty() => { - return Err(Error::Io(io::Error::new( - io::ErrorKind::ConnectionAborted, - "Connection closed" - ))) - }, - 0 => return Err(Error::TooLarge), - _ => () - } - } -} - -fn try_parse<R: Read, T: TryParse<Subject=I>, I>(rdr: &mut BufReader<R>) -> TryParseResult<I> { - let mut headers = [httparse::EMPTY_HEADER; MAX_HEADERS]; - let buf = rdr.get_buf(); - if buf.len() == 0 { - return Ok(httparse::Status::Partial); - } - trace!("try_parse({:?})", buf); - <T as TryParse>::try_parse(&mut headers, buf) -} - -#[doc(hidden)] -trait TryParse { - type Subject; - fn try_parse<'a>(headers: &'a mut [httparse::Header<'a>], buf: &'a [u8]) -> - TryParseResult<Self::Subject>; -} - -type TryParseResult<T> = Result<httparse::Status<(Incoming<T>, usize)>, Error>; - -impl<'a> TryParse for httparse::Request<'a, 'a> { - type Subject = (Method, RequestUri); - - fn try_parse<'b>(headers: &'b mut [httparse::Header<'b>], buf: &'b [u8]) -> - TryParseResult<(Method, RequestUri)> { - trace!("Request.try_parse([Header; {}], [u8; {}])", headers.len(), buf.len()); - let mut req = httparse::Request::new(headers); - Ok(match try!(req.parse(buf)) { - httparse::Status::Complete(len) => { - trace!("Request.try_parse Complete({})", len); - httparse::Status::Complete((Incoming { - version: if req.version.unwrap() == 1 { Http11 } else { Http10 }, - subject: ( - try!(req.method.unwrap().parse()), - try!(req.path.unwrap().parse()) - ), - headers: try!(Headers::from_raw(req.headers)) - }, len)) - }, - httparse::Status::Partial => httparse::Status::Partial - }) - } -} - -impl<'a> TryParse for httparse::Response<'a, 'a> { - type Subject = RawStatus; - - fn try_parse<'b>(headers: &'b mut [httparse::Header<'b>], buf: &'b [u8]) -> - TryParseResult<RawStatus> { - trace!("Response.try_parse([Header; {}], [u8; {}])", headers.len(), buf.len()); - let mut res = httparse::Response::new(headers); - Ok(match try!(res.parse(buf)) { - httparse::Status::Complete(len) => { - trace!("Response.try_parse Complete({})", len); - let code = res.code.unwrap(); - let reason = match StatusCode::from_u16(code).canonical_reason() { - Some(reason) if reason == res.reason.unwrap() => Cow::Borrowed(reason), - _ => Cow::Owned(res.reason.unwrap().to_owned()) - }; - httparse::Status::Complete((Incoming { - version: if res.version.unwrap() == 1 { Http11 } else { Http10 }, - subject: RawStatus(code, reason), - headers: try!(Headers::from_raw(res.headers)) - }, len)) - }, - httparse::Status::Partial => httparse::Status::Partial - }) - } -} - -/// An Incoming Message head. Includes request/status line, and headers. -#[derive(Debug)] -pub struct Incoming<S> { - /// HTTP version of the message. - pub version: HttpVersion, - /// Subject (request line or status line) of Incoming message. - pub subject: S, - /// Headers of the Incoming message. - pub headers: Headers -} - -/// The `\r` byte. -pub const CR: u8 = b'\r'; -/// The `\n` byte. -pub const LF: u8 = b'\n'; -/// The bytes `\r\n`. -pub const LINE_ENDING: &'static str = "\r\n"; - -#[cfg(test)] -mod tests { - use std::error::Error; - use std::io::{self, Read, Write}; - - - use buffer::BufReader; - use mock::MockStream; - use http::HttpMessage; - - use super::{read_chunk_size, parse_request, parse_response, Http11Message}; - - #[test] - fn test_write_chunked() { - use std::str::from_utf8; - let mut w = super::HttpWriter::ChunkedWriter(Vec::new()); - w.write_all(b"foo bar").unwrap(); - w.write_all(b"baz quux herp").unwrap(); - let buf = w.end().unwrap(); - let s = from_utf8(buf.as_ref()).unwrap(); - assert_eq!(s, "7\r\nfoo bar\r\nD\r\nbaz quux herp\r\n0\r\n\r\n"); - } - - #[test] - fn test_write_sized() { - use std::str::from_utf8; - let mut w = super::HttpWriter::SizedWriter(Vec::new(), 8); - w.write_all(b"foo bar").unwrap(); - assert_eq!(w.write(b"baz").unwrap(), 1); - - let buf = w.end().unwrap(); - let s = from_utf8(buf.as_ref()).unwrap(); - assert_eq!(s, "foo barb"); - } - - #[test] - fn test_read_chunk_size() { - fn read(s: &str, result: u64) { - assert_eq!(read_chunk_size(&mut s.as_bytes()).unwrap(), result); - } - - fn read_err(s: &str) { - assert_eq!(read_chunk_size(&mut s.as_bytes()).unwrap_err().kind(), - io::ErrorKind::InvalidInput); - } - - read("1\r\n", 1); - read("01\r\n", 1); - read("0\r\n", 0); - read("00\r\n", 0); - read("A\r\n", 10); - read("a\r\n", 10); - read("Ff\r\n", 255); - read("Ff \r\n", 255); - // Missing LF or CRLF - read_err("F\rF"); - read_err("F"); - // Invalid hex digit - read_err("X\r\n"); - read_err("1X\r\n"); - read_err("-\r\n"); - read_err("-1\r\n"); - // Acceptable (if not fully valid) extensions do not influence the size - read("1;extension\r\n", 1); - read("a;ext name=value\r\n", 10); - read("1;extension;extension2\r\n", 1); - read("1;;; ;\r\n", 1); - read("2; extension...\r\n", 2); - read("3 ; extension=123\r\n", 3); - read("3 ;\r\n", 3); - read("3 ; \r\n", 3); - // Invalid extensions cause an error - read_err("1 invalid extension\r\n"); - read_err("1 A\r\n"); - read_err("1;no CRLF"); - } - - #[test] - fn test_read_sized_early_eof() { - let mut r = super::HttpReader::SizedReader(MockStream::with_input(b"foo bar"), 10); - let mut buf = [0u8; 10]; - assert_eq!(r.read(&mut buf).unwrap(), 7); - let e = r.read(&mut buf).unwrap_err(); - assert_eq!(e.kind(), io::ErrorKind::Other); - assert_eq!(e.description(), "early eof"); - } - - #[test] - fn test_read_chunked_early_eof() { - let mut r = super::HttpReader::ChunkedReader(MockStream::with_input(b"\ - 9\r\n\ - foo bar\ - "), None); - - let mut buf = [0u8; 10]; - assert_eq!(r.read(&mut buf).unwrap(), 7); - let e = r.read(&mut buf).unwrap_err(); - assert_eq!(e.kind(), io::ErrorKind::Other); - assert_eq!(e.description(), "early eof"); - } - - #[test] - fn test_message_get_incoming_invalid_content_length() { - let raw = MockStream::with_input( - b"HTTP/1.1 200 OK\r\nContent-Length: asdf\r\n\r\n"); - let mut msg = Http11Message::with_stream(Box::new(raw)); - assert!(msg.get_incoming().is_err()); - assert!(msg.close_connection().is_ok()); - } - - #[test] - fn test_parse_incoming() { - let mut raw = MockStream::with_input(b"GET /echo HTTP/1.1\r\nHost: hyper.rs\r\n\r\n"); - let mut buf = BufReader::new(&mut raw); - parse_request(&mut buf).unwrap(); - } - - #[test] - fn test_parse_raw_status() { - let mut raw = MockStream::with_input(b"HTTP/1.1 200 OK\r\n\r\n"); - let mut buf = BufReader::new(&mut raw); - let res = parse_response(&mut buf).unwrap(); - - assert_eq!(res.subject.1, "OK"); - - let mut raw = MockStream::with_input(b"HTTP/1.1 200 Howdy\r\n\r\n"); - let mut buf = BufReader::new(&mut raw); - let res = parse_response(&mut buf).unwrap(); - - assert_eq!(res.subject.1, "Howdy"); - } - - - #[test] - fn test_parse_tcp_closed() { - use std::io::ErrorKind; - use error::Error; - - let mut empty = MockStream::new(); - let mut buf = BufReader::new(&mut empty); - match parse_request(&mut buf) { - Err(Error::Io(ref e)) if e.kind() == ErrorKind::ConnectionAborted => (), - other => panic!("unexpected result: {:?}", other) - } - } - - #[cfg(feature = "nightly")] - use test::Bencher; - - #[cfg(feature = "nightly")] - #[bench] - fn bench_parse_incoming(b: &mut Bencher) { - let mut raw = MockStream::with_input(b"GET /echo HTTP/1.1\r\nHost: hyper.rs\r\n\r\n"); - let mut buf = BufReader::new(&mut raw); - b.iter(|| { - parse_request(&mut buf).unwrap(); - buf.get_mut().read.set_position(0); - }); - } -} diff --git /dev/null b/src/http/h1/decode.rs new file mode 100644 --- /dev/null +++ b/src/http/h1/decode.rs @@ -0,0 +1,293 @@ +use std::cmp; +use std::io::{self, Read}; + +use self::Kind::{Length, Chunked, Eof}; + +/// Decoders to handle different Transfer-Encodings. +/// +/// If a message body does not include a Transfer-Encoding, it *should* +/// include a Content-Length header. +#[derive(Debug, Clone)] +pub struct Decoder { + kind: Kind, +} + +impl Decoder { + pub fn length(x: u64) -> Decoder { + Decoder { + kind: Kind::Length(x) + } + } + + pub fn chunked() -> Decoder { + Decoder { + kind: Kind::Chunked(None) + } + } + + pub fn eof() -> Decoder { + Decoder { + kind: Kind::Eof(false) + } + } +} + +#[derive(Debug, Clone)] +enum Kind { + /// A Reader used when a Content-Length header is passed with a positive integer. + Length(u64), + /// A Reader used when Transfer-Encoding is `chunked`. + Chunked(Option<u64>), + /// A Reader used for responses that don't indicate a length or chunked. + /// + /// Note: This should only used for `Response`s. It is illegal for a + /// `Request` to be made with both `Content-Length` and + /// `Transfer-Encoding: chunked` missing, as explained from the spec: + /// + /// > If a Transfer-Encoding header field is present in a response and + /// > the chunked transfer coding is not the final encoding, the + /// > message body length is determined by reading the connection until + /// > it is closed by the server. If a Transfer-Encoding header field + /// > is present in a request and the chunked transfer coding is not + /// > the final encoding, the message body length cannot be determined + /// > reliably; the server MUST respond with the 400 (Bad Request) + /// > status code and then close the connection. + Eof(bool), +} + +impl Decoder { + pub fn is_eof(&self) -> bool { + trace!("is_eof? {:?}", self); + match self.kind { + Length(0) | + Chunked(Some(0)) | + Eof(true) => true, + _ => false + } + } +} + +impl Decoder { + pub fn decode<R: Read>(&mut self, body: &mut R, buf: &mut [u8]) -> io::Result<usize> { + match self.kind { + Length(ref mut remaining) => { + trace!("Sized read, remaining={:?}", remaining); + if *remaining == 0 { + Ok(0) + } else { + let to_read = cmp::min(*remaining as usize, buf.len()); + let num = try!(body.read(&mut buf[..to_read])) as u64; + trace!("Length read: {}", num); + if num > *remaining { + *remaining = 0; + } else if num == 0 { + return Err(io::Error::new(io::ErrorKind::Other, "early eof")); + } else { + *remaining -= num; + } + Ok(num as usize) + } + }, + Chunked(ref mut opt_remaining) => { + let mut rem = match *opt_remaining { + Some(ref rem) => *rem, + // None means we don't know the size of the next chunk + None => try!(read_chunk_size(body)) + }; + trace!("Chunked read, remaining={:?}", rem); + + if rem == 0 { + *opt_remaining = Some(0); + + // chunk of size 0 signals the end of the chunked stream + // if the 0 digit was missing from the stream, it would + // be an InvalidInput error instead. + trace!("end of chunked"); + return Ok(0) + } + + let to_read = cmp::min(rem as usize, buf.len()); + let count = try!(body.read(&mut buf[..to_read])) as u64; + + if count == 0 { + *opt_remaining = Some(0); + return Err(io::Error::new(io::ErrorKind::Other, "early eof")); + } + + rem -= count; + *opt_remaining = if rem > 0 { + Some(rem) + } else { + try!(eat(body, b"\r\n")); + None + }; + Ok(count as usize) + }, + Eof(ref mut is_eof) => { + match body.read(buf) { + Ok(0) => { + *is_eof = true; + Ok(0) + } + other => other + } + }, + } + } +} + +fn eat<R: Read>(rdr: &mut R, bytes: &[u8]) -> io::Result<()> { + let mut buf = [0]; + for &b in bytes.iter() { + match try!(rdr.read(&mut buf)) { + 1 if buf[0] == b => (), + _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, + "Invalid characters found")), + } + } + Ok(()) +} + +/// Chunked chunks start with 1*HEXDIGIT, indicating the size of the chunk. +fn read_chunk_size<R: Read>(rdr: &mut R) -> io::Result<u64> { + macro_rules! byte ( + ($rdr:ident) => ({ + let mut buf = [0]; + match try!($rdr.read(&mut buf)) { + 1 => buf[0], + _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, + "Invalid chunk size line")), + + } + }) + ); + let mut size = 0u64; + let radix = 16; + let mut in_ext = false; + let mut in_chunk_size = true; + loop { + match byte!(rdr) { + b@b'0'...b'9' if in_chunk_size => { + size *= radix; + size += (b - b'0') as u64; + }, + b@b'a'...b'f' if in_chunk_size => { + size *= radix; + size += (b + 10 - b'a') as u64; + }, + b@b'A'...b'F' if in_chunk_size => { + size *= radix; + size += (b + 10 - b'A') as u64; + }, + b'\r' => { + match byte!(rdr) { + b'\n' => break, + _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, + "Invalid chunk size line")) + + } + }, + // If we weren't in the extension yet, the ";" signals its start + b';' if !in_ext => { + in_ext = true; + in_chunk_size = false; + }, + // "Linear white space" is ignored between the chunk size and the + // extension separator token (";") due to the "implied *LWS rule". + b'\t' | b' ' if !in_ext & !in_chunk_size => {}, + // LWS can follow the chunk size, but no more digits can come + b'\t' | b' ' if in_chunk_size => in_chunk_size = false, + // We allow any arbitrary octet once we are in the extension, since + // they all get ignored anyway. According to the HTTP spec, valid + // extensions would have a more strict syntax: + // (token ["=" (token | quoted-string)]) + // but we gain nothing by rejecting an otherwise valid chunk size. + _ext if in_ext => { + //TODO: chunk extension byte; + }, + // Finally, if we aren't in the extension and we're reading any + // other octet, the chunk size line is invalid! + _ => { + return Err(io::Error::new(io::ErrorKind::InvalidInput, + "Invalid chunk size line")); + } + } + } + trace!("chunk size={:?}", size); + Ok(size) +} + + +#[cfg(test)] +mod tests { + use std::error::Error; + use std::io; + use super::{Decoder, read_chunk_size}; + + #[test] + fn test_read_chunk_size() { + fn read(s: &str, result: u64) { + assert_eq!(read_chunk_size(&mut s.as_bytes()).unwrap(), result); + } + + fn read_err(s: &str) { + assert_eq!(read_chunk_size(&mut s.as_bytes()).unwrap_err().kind(), + io::ErrorKind::InvalidInput); + } + + read("1\r\n", 1); + read("01\r\n", 1); + read("0\r\n", 0); + read("00\r\n", 0); + read("A\r\n", 10); + read("a\r\n", 10); + read("Ff\r\n", 255); + read("Ff \r\n", 255); + // Missing LF or CRLF + read_err("F\rF"); + read_err("F"); + // Invalid hex digit + read_err("X\r\n"); + read_err("1X\r\n"); + read_err("-\r\n"); + read_err("-1\r\n"); + // Acceptable (if not fully valid) extensions do not influence the size + read("1;extension\r\n", 1); + read("a;ext name=value\r\n", 10); + read("1;extension;extension2\r\n", 1); + read("1;;; ;\r\n", 1); + read("2; extension...\r\n", 2); + read("3 ; extension=123\r\n", 3); + read("3 ;\r\n", 3); + read("3 ; \r\n", 3); + // Invalid extensions cause an error + read_err("1 invalid extension\r\n"); + read_err("1 A\r\n"); + read_err("1;no CRLF"); + } + + #[test] + fn test_read_sized_early_eof() { + let mut bytes = &b"foo bar"[..]; + let mut decoder = Decoder::length(10); + let mut buf = [0u8; 10]; + assert_eq!(decoder.decode(&mut bytes, &mut buf).unwrap(), 7); + let e = decoder.decode(&mut bytes, &mut buf).unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::Other); + assert_eq!(e.description(), "early eof"); + } + + #[test] + fn test_read_chunked_early_eof() { + let mut bytes = &b"\ + 9\r\n\ + foo bar\ + "[..]; + let mut decoder = Decoder::chunked(); + let mut buf = [0u8; 10]; + assert_eq!(decoder.decode(&mut bytes, &mut buf).unwrap(), 7); + let e = decoder.decode(&mut bytes, &mut buf).unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::Other); + assert_eq!(e.description(), "early eof"); + } +} diff --git /dev/null b/src/http/h1/encode.rs new file mode 100644 --- /dev/null +++ b/src/http/h1/encode.rs @@ -0,0 +1,371 @@ +use std::borrow::Cow; +use std::cmp; +use std::io::{self, Write}; + +use http::internal::{AtomicWrite, WriteBuf}; + +/// Encoders to handle different Transfer-Encodings. +#[derive(Debug, Clone)] +pub struct Encoder { + kind: Kind, + prefix: Prefix, //Option<WriteBuf<Vec<u8>>> +} + +#[derive(Debug, PartialEq, Clone)] +enum Kind { + /// An Encoder for when Transfer-Encoding includes `chunked`. + Chunked(Chunked), + /// An Encoder for when Content-Length is set. + /// + /// Enforces that the body is not longer than the Content-Length header. + Length(u64), +} + +impl Encoder { + pub fn chunked() -> Encoder { + Encoder { + kind: Kind::Chunked(Chunked::Init), + prefix: Prefix(None) + } + } + + pub fn length(len: u64) -> Encoder { + Encoder { + kind: Kind::Length(len), + prefix: Prefix(None) + } + } + + pub fn prefix(&mut self, prefix: WriteBuf<Vec<u8>>) { + self.prefix.0 = Some(prefix); + } + + pub fn is_eof(&self) -> bool { + if self.prefix.0.is_some() { + return false; + } + match self.kind { + Kind::Length(0) | + Kind::Chunked(Chunked::End) => true, + _ => false + } + } + + pub fn end(self) -> Option<WriteBuf<Cow<'static, [u8]>>> { + let trailer = self.trailer(); + let buf = self.prefix.0; + + match (buf, trailer) { + (Some(mut buf), Some(trailer)) => { + buf.bytes.extend_from_slice(trailer); + Some(WriteBuf { + bytes: Cow::Owned(buf.bytes), + pos: buf.pos, + }) + }, + (Some(buf), None) => Some(WriteBuf { + bytes: Cow::Owned(buf.bytes), + pos: buf.pos + }), + (None, Some(trailer)) => { + Some(WriteBuf { + bytes: Cow::Borrowed(trailer), + pos: 0, + }) + }, + (None, None) => None + } + } + + fn trailer(&self) -> Option<&'static [u8]> { + match self.kind { + Kind::Chunked(Chunked::Init) => { + Some(b"0\r\n\r\n") + } + _ => None + } + } + + pub fn encode<W: AtomicWrite>(&mut self, w: &mut W, msg: &[u8]) -> io::Result<usize> { + match self.kind { + Kind::Chunked(ref mut chunked) => { + chunked.encode(w, &mut self.prefix, msg) + }, + Kind::Length(ref mut remaining) => { + let mut n = { + let max = cmp::min(*remaining as usize, msg.len()); + let slice = &msg[..max]; + + let prefix = self.prefix.0.as_ref().map(|buf| &buf.bytes[buf.pos..]).unwrap_or(b""); + + try!(w.write_atomic(&[prefix, slice])) + }; + + n = self.prefix.update(n); + if n == 0 { + return Err(io::Error::new(io::ErrorKind::WouldBlock, "would block")); + } + + *remaining -= n as u64; + Ok(n) + }, + } + } +} + +#[derive(Debug, PartialEq, Clone)] +enum Chunked { + Init, + Size(ChunkSize), + SizeCr, + SizeLf, + Body(usize), + BodyCr, + BodyLf, + End, +} + +impl Chunked { + fn encode<W: AtomicWrite>(&mut self, w: &mut W, prefix: &mut Prefix, msg: &[u8]) -> io::Result<usize> { + match *self { + Chunked::Init => { + let mut size = ChunkSize { + bytes: [0; CHUNK_SIZE_MAX_BYTES], + pos: 0, + len: 0, + }; + trace!("chunked write, size = {:?}", msg.len()); + write!(&mut size, "{:X}", msg.len()) + .expect("CHUNK_SIZE_MAX_BYTES should fit any usize"); + *self = Chunked::Size(size); + } + Chunked::End => return Ok(0), + _ => {} + } + let mut n = { + let pieces = match *self { + Chunked::Init => unreachable!("Chunked::Init should have become Chunked::Size"), + Chunked::Size(ref size) => [ + prefix.0.as_ref().map(|buf| &buf.bytes[buf.pos..]).unwrap_or(b""), + &size.bytes[size.pos.into() .. size.len.into()], + &b"\r\n"[..], + msg, + &b"\r\n"[..], + ], + Chunked::SizeCr => [ + &b""[..], + &b""[..], + &b"\r\n"[..], + msg, + &b"\r\n"[..], + ], + Chunked::SizeLf => [ + &b""[..], + &b""[..], + &b"\n"[..], + msg, + &b"\r\n"[..], + ], + Chunked::Body(pos) => [ + &b""[..], + &b""[..], + &b""[..], + &msg[pos..], + &b"\r\n"[..], + ], + Chunked::BodyCr => [ + &b""[..], + &b""[..], + &b""[..], + &b""[..], + &b"\r\n"[..], + ], + Chunked::BodyLf => [ + &b""[..], + &b""[..], + &b""[..], + &b""[..], + &b"\n"[..], + ], + Chunked::End => unreachable!("Chunked::End shouldn't write more") + }; + try!(w.write_atomic(&pieces)) + }; + + if n > 0 { + n = prefix.update(n); + } + while n > 0 { + match *self { + Chunked::Init => unreachable!("Chunked::Init should have become Chunked::Size"), + Chunked::Size(mut size) => { + n = size.update(n); + if size.len == 0 { + *self = Chunked::SizeCr; + } else { + *self = Chunked::Size(size); + } + }, + Chunked::SizeCr => { + *self = Chunked::SizeLf; + n -= 1; + } + Chunked::SizeLf => { + *self = Chunked::Body(0); + n -= 1; + } + Chunked::Body(pos) => { + let left = msg.len() - pos; + if n >= left { + *self = Chunked::BodyCr; + n -= left; + } else { + *self = Chunked::Body(pos + n); + n = 0; + } + } + Chunked::BodyCr => { + *self = Chunked::BodyLf; + n -= 1; + } + Chunked::BodyLf => { + assert!(n == 1); + *self = if msg.len() == 0 { + Chunked::End + } else { + Chunked::Init + }; + n = 0; + }, + Chunked::End => unreachable!("Chunked::End shouldn't have any to write") + } + } + + match *self { + Chunked::Init | + Chunked::End => Ok(msg.len()), + _ => Err(io::Error::new(io::ErrorKind::WouldBlock, "chunked incomplete")) + } + } +} + +#[cfg(target_pointer_width = "32")] +const USIZE_BYTES: usize = 4; + +#[cfg(target_pointer_width = "64")] +const USIZE_BYTES: usize = 8; + +// each byte will become 2 hex +const CHUNK_SIZE_MAX_BYTES: usize = USIZE_BYTES * 2; + +#[derive(Clone, Copy)] +struct ChunkSize { + bytes: [u8; CHUNK_SIZE_MAX_BYTES], + pos: u8, + len: u8, +} + +impl ChunkSize { + fn update(&mut self, n: usize) -> usize { + let diff = (self.len - self.pos).into(); + if n >= diff { + self.pos = 0; + self.len = 0; + n - diff + } else { + self.pos += n as u8; // just verified it was a small usize + 0 + } + } +} + +impl ::std::fmt::Debug for ChunkSize { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + f.debug_struct("ChunkSize") + .field("bytes", &&self.bytes[..self.len.into()]) + .field("pos", &self.pos) + .finish() + } +} + +impl ::std::cmp::PartialEq for ChunkSize { + fn eq(&self, other: &ChunkSize) -> bool { + self.len == other.len && + self.pos == other.pos && + (&self.bytes[..]) == (&other.bytes[..]) + } +} + +impl io::Write for ChunkSize { + fn write(&mut self, msg: &[u8]) -> io::Result<usize> { + let n = (&mut self.bytes[self.len.into() ..]).write(msg) + .expect("&mut [u8].write() cannot error"); + self.len += n as u8; // safe because bytes is never bigger than 256 + Ok(n) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[derive(Debug, Clone)] +struct Prefix(Option<WriteBuf<Vec<u8>>>); + +impl Prefix { + fn update(&mut self, n: usize) -> usize { + if let Some(mut buf) = self.0.take() { + if buf.bytes.len() - buf.pos > n { + buf.pos += n; + self.0 = Some(buf); + 0 + } else { + let nbuf = buf.bytes.len() - buf.pos; + n - nbuf + } + } else { + n + } + } +} + +#[cfg(test)] +mod tests { + use super::Encoder; + use mock::{Async, Buf}; + + #[test] + fn test_write_chunked_sync() { + let mut dst = Buf::new(); + let mut encoder = Encoder::chunked(); + + encoder.encode(&mut dst, b"foo bar").unwrap(); + encoder.encode(&mut dst, b"baz quux herp").unwrap(); + encoder.encode(&mut dst, b"").unwrap(); + assert_eq!(&dst[..], &b"7\r\nfoo bar\r\nD\r\nbaz quux herp\r\n0\r\n\r\n"[..]); + } + + #[test] + fn test_write_chunked_async() { + let mut dst = Async::new(Buf::new(), 7); + let mut encoder = Encoder::chunked(); + + assert!(encoder.encode(&mut dst, b"foo bar").is_err()); + dst.block_in(6); + assert_eq!(7, encoder.encode(&mut dst, b"foo bar").unwrap()); + dst.block_in(30); + assert_eq!(13, encoder.encode(&mut dst, b"baz quux herp").unwrap()); + encoder.encode(&mut dst, b"").unwrap(); + assert_eq!(&dst[..], &b"7\r\nfoo bar\r\nD\r\nbaz quux herp\r\n0\r\n\r\n"[..]); + } + + #[test] + fn test_write_sized() { + let mut dst = Buf::new(); + let mut encoder = Encoder::length(8); + encoder.encode(&mut dst, b"foo bar").unwrap(); + assert_eq!(encoder.encode(&mut dst, b"baz").unwrap(), 1); + + assert_eq!(dst, b"foo barb"); + } +} diff --git /dev/null b/src/http/h1/parse.rs new file mode 100644 --- /dev/null +++ b/src/http/h1/parse.rs @@ -0,0 +1,246 @@ +use std::borrow::Cow; +use std::io::Write; + +use httparse; + +use header::{self, Headers, ContentLength, TransferEncoding}; +use http::{MessageHead, RawStatus, Http1Message, ParseResult, Next, ServerMessage, ClientMessage, Next_, RequestLine}; +use http::h1::{Encoder, Decoder}; +use method::Method; +use status::StatusCode; +use version::HttpVersion::{Http10, Http11}; + +const MAX_HEADERS: usize = 100; +const AVERAGE_HEADER_SIZE: usize = 30; // totally scientific + +pub fn parse<T: Http1Message<Incoming=I>, I>(buf: &[u8]) -> ParseResult<I> { + if buf.len() == 0 { + return Ok(None); + } + trace!("parse({:?})", buf); + <T as Http1Message>::parse(buf) +} + + + +impl Http1Message for ServerMessage { + type Incoming = RequestLine; + type Outgoing = StatusCode; + + fn initial_interest() -> Next { + Next::new(Next_::Read) + } + + fn parse(buf: &[u8]) -> ParseResult<RequestLine> { + let mut headers = [httparse::EMPTY_HEADER; MAX_HEADERS]; + trace!("Request.parse([Header; {}], [u8; {}])", headers.len(), buf.len()); + let mut req = httparse::Request::new(&mut headers); + Ok(match try!(req.parse(buf)) { + httparse::Status::Complete(len) => { + trace!("Request.parse Complete({})", len); + Some((MessageHead { + version: if req.version.unwrap() == 1 { Http11 } else { Http10 }, + subject: RequestLine( + try!(req.method.unwrap().parse()), + try!(req.path.unwrap().parse()) + ), + headers: try!(Headers::from_raw(req.headers)) + }, len)) + }, + httparse::Status::Partial => None + }) + } + + fn decoder(head: &MessageHead<Self::Incoming>) -> ::Result<Decoder> { + use ::header; + if let Some(&header::ContentLength(len)) = head.headers.get() { + Ok(Decoder::length(len)) + } else if head.headers.has::<header::TransferEncoding>() { + //TODO: check for Transfer-Encoding: chunked + Ok(Decoder::chunked()) + } else { + Ok(Decoder::length(0)) + } + } + + + fn encode(mut head: MessageHead<Self::Outgoing>, dst: &mut Vec<u8>) -> Encoder { + use ::header; + trace!("writing head: {:?}", head); + + if !head.headers.has::<header::Date>() { + head.headers.set(header::Date(header::HttpDate(::time::now_utc()))); + } + + let mut is_chunked = true; + let mut body = Encoder::chunked(); + if let Some(cl) = head.headers.get::<header::ContentLength>() { + body = Encoder::length(**cl); + is_chunked = false + } + + if is_chunked { + let encodings = match head.headers.get_mut::<header::TransferEncoding>() { + Some(&mut header::TransferEncoding(ref mut encodings)) => { + if encodings.last() != Some(&header::Encoding::Chunked) { + encodings.push(header::Encoding::Chunked); + } + false + }, + None => true + }; + + if encodings { + head.headers.set(header::TransferEncoding(vec![header::Encoding::Chunked])); + } + } + + + let init_cap = 30 + head.headers.len() * AVERAGE_HEADER_SIZE; + dst.reserve(init_cap); + debug!("writing {:#?}", head.headers); + let _ = write!(dst, "{} {}\r\n{}\r\n", head.version, head.subject, head.headers); + + body + } +} + +impl Http1Message for ClientMessage { + type Incoming = RawStatus; + type Outgoing = RequestLine; + + + fn initial_interest() -> Next { + Next::new(Next_::Write) + } + + fn parse(buf: &[u8]) -> ParseResult<RawStatus> { + let mut headers = [httparse::EMPTY_HEADER; MAX_HEADERS]; + trace!("Response.parse([Header; {}], [u8; {}])", headers.len(), buf.len()); + let mut res = httparse::Response::new(&mut headers); + Ok(match try!(res.parse(buf)) { + httparse::Status::Complete(len) => { + trace!("Response.try_parse Complete({})", len); + let code = res.code.unwrap(); + let reason = match StatusCode::from_u16(code).canonical_reason() { + Some(reason) if reason == res.reason.unwrap() => Cow::Borrowed(reason), + _ => Cow::Owned(res.reason.unwrap().to_owned()) + }; + Some((MessageHead { + version: if res.version.unwrap() == 1 { Http11 } else { Http10 }, + subject: RawStatus(code, reason), + headers: try!(Headers::from_raw(res.headers)) + }, len)) + }, + httparse::Status::Partial => None + }) + } + + fn decoder(inc: &MessageHead<Self::Incoming>) -> ::Result<Decoder> { + use ::header; + // According to https://tools.ietf.org/html/rfc7230#section-3.3.3 + // 1. HEAD reponses, and Status 1xx, 204, and 304 cannot have a body. + // 2. Status 2xx to a CONNECT cannot have a body. + // + // First two steps taken care of before this method. + // + // 3. Transfer-Encoding: chunked has a chunked body. + // 4. If multiple differing Content-Length headers or invalid, close connection. + // 5. Content-Length header has a sized body. + // 6. Not Client. + // 7. Read till EOF. + if let Some(&header::TransferEncoding(ref codings)) = inc.headers.get() { + if codings.last() == Some(&header::Encoding::Chunked) { + Ok(Decoder::chunked()) + } else { + trace!("not chuncked. read till eof"); + Ok(Decoder::eof()) + } + } else if let Some(&header::ContentLength(len)) = inc.headers.get() { + Ok(Decoder::length(len)) + } else if inc.headers.has::<header::ContentLength>() { + trace!("illegal Content-Length: {:?}", inc.headers.get_raw("Content-Length")); + Err(::Error::Header) + } else { + trace!("neither Transfer-Encoding nor Content-Length"); + Ok(Decoder::eof()) + } + } + + fn encode(mut head: MessageHead<Self::Outgoing>, dst: &mut Vec<u8>) -> Encoder { + trace!("writing head: {:?}", head); + + + let mut body = Encoder::length(0); + let expects_no_body = match head.subject.0 { + Method::Head | Method::Get | Method::Connect => true, + _ => false + }; + let mut chunked = false; + + if let Some(con_len) = head.headers.get::<ContentLength>() { + body = Encoder::length(**con_len); + } else { + chunked = !expects_no_body; + } + + if chunked { + body = Encoder::chunked(); + let encodings = match head.headers.get_mut::<TransferEncoding>() { + Some(encodings) => { + //TODO: check if Chunked already exists + encodings.push(header::Encoding::Chunked); + true + }, + None => false + }; + + if !encodings { + head.headers.set(TransferEncoding(vec![header::Encoding::Chunked])); + } + } + + let init_cap = 30 + head.headers.len() * AVERAGE_HEADER_SIZE; + dst.reserve(init_cap); + debug!("writing {:#?}", head.headers); + let _ = write!(dst, "{} {}\r\n{}\r\n", head.subject, head.version, head.headers); + + body + } +} + +#[cfg(test)] +mod tests { + use http; + use super::{parse}; + + #[test] + fn test_parse_request() { + let raw = b"GET /echo HTTP/1.1\r\nHost: hyper.rs\r\n\r\n"; + parse::<http::ServerMessage, _>(raw).unwrap(); + } + + #[test] + fn test_parse_raw_status() { + let raw = b"HTTP/1.1 200 OK\r\n\r\n"; + let (res, _) = parse::<http::ClientMessage, _>(raw).unwrap().unwrap(); + assert_eq!(res.subject.1, "OK"); + + let raw = b"HTTP/1.1 200 Howdy\r\n\r\n"; + let (res, _) = parse::<http::ClientMessage, _>(raw).unwrap().unwrap(); + assert_eq!(res.subject.1, "Howdy"); + } + + #[cfg(feature = "nightly")] + use test::Bencher; + + #[cfg(feature = "nightly")] + #[bench] + fn bench_parse_incoming(b: &mut Bencher) { + let raw = b"GET /echo HTTP/1.1\r\nHost: hyper.rs\r\n\r\n"; + b.iter(|| { + parse::<http::ServerMessage, _>(raw).unwrap() + }); + } + +} diff --git a/src/http/mod.rs b/src/http/mod.rs --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -46,6 +217,158 @@ pub fn should_keep_alive(version: HttpVersion, headers: &Headers) -> bool { _ => true } } +pub type ParseResult<T> = ::Result<Option<(MessageHead<T>, usize)>>; + +pub fn parse<T: Http1Message<Incoming=I>, I>(rdr: &[u8]) -> ParseResult<I> { + h1::parse::<T, I>(rdr) +} + +// These 2 enums are not actually dead_code. They are used in the server and +// and client modules, respectively. However, their being used as associated +// types doesn't mark them as used, so the dead_code linter complains. + +#[allow(dead_code)] +#[derive(Debug)] +pub enum ServerMessage {} + +#[allow(dead_code)] +#[derive(Debug)] +pub enum ClientMessage {} + +pub trait Http1Message { + type Incoming; + type Outgoing: Default; + //TODO: replace with associated const when stable + fn initial_interest() -> Next; + fn parse(bytes: &[u8]) -> ParseResult<Self::Incoming>; + fn decoder(head: &MessageHead<Self::Incoming>) -> ::Result<h1::Decoder>; + fn encode(head: MessageHead<Self::Outgoing>, dst: &mut Vec<u8>) -> h1::Encoder; + +} + +/// Used to signal desired events when working with asynchronous IO. +#[must_use] +#[derive(Clone)] +pub struct Next { + interest: Next_, + timeout: Option<Duration>, +} + +impl fmt::Debug for Next { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(write!(f, "Next::{:?}", &self.interest)); + match self.timeout { + Some(ref d) => write!(f, "({:?})", d), + None => Ok(()) + } + } +} + +#[derive(Debug, Clone, Copy)] +enum Next_ { + Read, + Write, + ReadWrite, + Wait, + End, + Remove, +} + +#[derive(Debug, Clone, Copy)] +enum Reg { + Read, + Write, + ReadWrite, + Wait, + Remove +} + +/// A notifier to wakeup a socket after having used `Next::wait()` +#[derive(Debug, Clone)] +pub struct Control { + tx: self::channel::Sender<Next>, +} + +impl Control { + /// Wakeup a waiting socket to listen for a certain event. + pub fn ready(&self, next: Next) -> Result<(), ControlError> { + //TODO: assert!( next.interest != Next_::Wait ) ? + self.tx.send(next).map_err(|_| ControlError(())) + } +} + +/// An error occured trying to tell a Control it is ready. +#[derive(Debug)] +pub struct ControlError(()); + +impl ::std::error::Error for ControlError { + fn description(&self) -> &str { + "Cannot wakeup event loop: loop is closed" + } +} + +impl fmt::Display for ControlError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(::std::error::Error::description(self)) + } +} + +impl Next { + fn new(interest: Next_) -> Next { + Next { + interest: interest, + timeout: None, + } + } + + fn interest(&self) -> Reg { + match self.interest { + Next_::Read => Reg::Read, + Next_::Write => Reg::Write, + Next_::ReadWrite => Reg::ReadWrite, + Next_::Wait => Reg::Wait, + Next_::End => Reg::Remove, + Next_::Remove => Reg::Remove, + } + } + + /// Signals the desire to read from the transport. + pub fn read() -> Next { + Next::new(Next_::Read) + } + + /// Signals the desire to write to the transport. + pub fn write() -> Next { + Next::new(Next_::Write) + } + + /// Signals the desire to read and write to the transport. + pub fn read_and_write() -> Next { + Next::new(Next_::ReadWrite) + } + + /// Signals the desire to end the current HTTP message. + pub fn end() -> Next { + Next::new(Next_::End) + } + + /// Signals the desire to abruptly remove the current transport from the + /// event loop. + pub fn remove() -> Next { + Next::new(Next_::Remove) + } + + /// Signals the desire to wait until some future time before acting again. + pub fn wait() -> Next { + Next::new(Next_::Wait) + } + + /// Signals a maximum duration to be waited for the desired event. + pub fn timeout(mut self, dur: Duration) -> Next { + self.timeout = Some(dur); + self + } +} #[test] fn test_should_keep_alive() { diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ #![doc(html_root_url = "https://hyperium.github.io/hyper/")] -#![cfg_attr(test, deny(missing_docs))] -#![cfg_attr(test, deny(warnings))] +#![deny(missing_docs)] +#![deny(warnings)] +#![deny(missing_debug_implementations)] #![cfg_attr(all(test, feature = "nightly"), feature(test))] //! # Hyper diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -163,35 +49,31 @@ extern crate test; pub use url::Url; pub use client::Client; pub use error::{Result, Error}; -pub use method::Method::{Get, Head, Post, Delete}; -pub use status::StatusCode::{Ok, BadRequest, NotFound}; +pub use http::{Next, Encoder, Decoder, Control}; +pub use header::Headers; +pub use method::Method::{self, Get, Head, Post, Delete}; +pub use status::StatusCode::{self, Ok, BadRequest, NotFound}; pub use server::Server; +pub use uri::RequestUri; +pub use version::HttpVersion; pub use language_tags::LanguageTag; -macro_rules! todo( - ($($arg:tt)*) => (if cfg!(not(ndebug)) { - trace!("TODO: {:?}", format_args!($($arg)*)) - }) -); - -macro_rules! inspect( - ($name:expr, $value:expr) => ({ - let v = $value; - trace!("inspect: {:?} = {:?}", $name, v); - v - }) -); +macro_rules! rotor_try { + ($e:expr) => ({ + match $e { + Ok(v) => v, + Err(e) => return ::rotor::Response::error(e.into()) + } + }); +} #[cfg(test)] -#[macro_use] mod mock; -#[doc(hidden)] -pub mod buffer; pub mod client; pub mod error; pub mod method; pub mod header; -pub mod http; +mod http; pub mod net; pub mod server; pub mod status; diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -719,159 +522,220 @@ mod openssl { } } - impl<S: NetworkStream> NetworkStream for SslStream<S> { + /// A transport protected by OpenSSL. + #[derive(Debug)] + pub struct OpensslStream<T> { + stream: SslStream<T>, + blocked: Option<Blocked>, + } + + fn openssl_stream<T>(inner: SslStream<T>) -> OpensslStream<T> { + OpensslStream { + stream: inner, + blocked: None, + } + } + + impl<T: super::Transport> io::Read for OpensslStream<T> { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.blocked = None; + self.stream.ssl_read(buf).or_else(|e| match e { + OpensslError::ZeroReturn => Ok(0), + OpensslError::WantWrite(e) => { + self.blocked = Some(Blocked::Write); + Err(e) + }, + OpensslError::WantRead(e) | OpensslError::Stream(e) => Err(e), + e => Err(io::Error::new(io::ErrorKind::Other, e)) + }) + } + } + + impl<T: super::Transport> io::Write for OpensslStream<T> { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.blocked = None; + self.stream.ssl_write(buf).or_else(|e| match e { + OpensslError::ZeroReturn => Ok(0), + OpensslError::WantRead(e) => { + self.blocked = Some(Blocked::Read); + Err(e) + }, + OpensslError::WantWrite(e) | OpensslError::Stream(e) => Err(e), + e => Err(io::Error::new(io::ErrorKind::Other, e)) + }) + } + + fn flush(&mut self) -> io::Result<()> { + self.stream.flush() + } + } + + + impl<T: super::Transport> Evented for OpensslStream<T> { #[inline] - fn peer_addr(&mut self) -> io::Result<SocketAddr> { - self.get_mut().peer_addr() + fn register(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> { + self.stream.get_ref().register(selector, token, interest, opts) } #[inline] - fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.get_ref().set_read_timeout(dur) + fn reregister(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> { + self.stream.get_ref().reregister(selector, token, interest, opts) } #[inline] - fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.get_ref().set_write_timeout(dur) + fn deregister(&self, selector: &mut Selector) -> io::Result<()> { + self.stream.get_ref().deregister(selector) + } + } + + impl<T: super::Transport> ::vecio::Writev for OpensslStream<T> { + fn writev(&mut self, bufs: &[&[u8]]) -> io::Result<usize> { + let vec = bufs.concat(); + self.write(&vec) } + } - fn close(&mut self, how: Shutdown) -> io::Result<()> { - self.get_mut().close(how) + impl<T: super::Transport> super::Transport for OpensslStream<T> { + fn take_socket_error(&mut self) -> io::Result<()> { + self.stream.get_mut().take_socket_error() } } } #[cfg(feature = "security-framework")] -pub mod security_framework { - use std::io; - use std::fmt; - use std::sync::{Arc, Mutex}; - use std::net::{Shutdown, SocketAddr}; - use std::time::Duration; - use security_framework::secure_transport::{SslStream, ClientBuilder, ServerBuilder}; +mod security_framework { + use std::io::{self, Read, Write}; use error::Error; - use net::{SslClient, SslServer, HttpStream, NetworkStream}; + use net::{SslClient, SslServer, HttpStream, Transport, Blocked}; + + use security_framework::secure_transport::SslStream; + pub use security_framework::secure_transport::{ClientBuilder as SecureTransportClient, ServerBuilder as SecureTransportServer}; + use rotor::mio::{Selector, Token, Evented, EventSet, PollOpt}; - #[derive(Default)] - pub struct ClientWrapper(ClientBuilder); + impl SslClient for SecureTransportClient { + type Stream = SecureTransport<HttpStream>; - impl ClientWrapper { - pub fn new(builder: ClientBuilder) -> ClientWrapper { - ClientWrapper(builder) + fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream> { + match self.handshake(host, journal(stream)) { + Ok(s) => Ok(SecureTransport(s)), + Err(e) => Err(Error::Ssl(e.into())), + } } } - impl SslClient for ClientWrapper { - type Stream = Stream; + impl SslServer for SecureTransportServer { + type Stream = SecureTransport<HttpStream>; - fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Stream> { - match self.0.handshake(host, stream) { - Ok(s) => Ok(Stream(Arc::new(Mutex::new(s)))), + fn wrap_server(&self, stream: HttpStream) -> ::Result<Self::Stream> { + match self.handshake(journal(stream)) { + Ok(s) => Ok(SecureTransport(s)), Err(e) => Err(Error::Ssl(e.into())), } } } - #[derive(Clone)] - pub struct ServerWrapper(Arc<ServerBuilder>); + /// A transport protected by Security Framework. + #[derive(Debug)] + pub struct SecureTransport<T>(SslStream<Journal<T>>); - impl ServerWrapper { - pub fn new(builder: ServerBuilder) -> ServerWrapper { - ServerWrapper(Arc::new(builder)) + impl<T: Transport> io::Read for SecureTransport<T> { + #[inline] + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.0.read(buf) } } - impl SslServer for ServerWrapper { - type Stream = Stream; + impl<T: Transport> io::Write for SecureTransport<T> { + #[inline] + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.0.write(buf) + } - fn wrap_server(&self, stream: HttpStream) -> ::Result<Stream> { - match self.0.handshake(stream) { - Ok(s) => Ok(Stream(Arc::new(Mutex::new(s)))), - Err(e) => Err(Error::Ssl(e.into())), - } + #[inline] + fn flush(&mut self) -> io::Result<()> { + self.0.flush() } } - #[derive(Clone)] - pub struct Stream(Arc<Mutex<SslStream<HttpStream>>>); - impl io::Read for Stream { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.0.lock().unwrap_or_else(|e| e.into_inner()).read(buf) + impl<T: Transport> Evented for SecureTransport<T> { + #[inline] + fn register(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> { + self.0.get_ref().inner.register(selector, token, interest, opts) } - fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { - self.0.lock().unwrap_or_else(|e| e.into_inner()).read_to_end(buf) + #[inline] + fn reregister(&self, selector: &mut Selector, token: Token, interest: EventSet, opts: PollOpt) -> io::Result<()> { + self.0.get_ref().inner.reregister(selector, token, interest, opts) } - fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> { - self.0.lock().unwrap_or_else(|e| e.into_inner()).read_to_string(buf) + #[inline] + fn deregister(&self, selector: &mut Selector) -> io::Result<()> { + self.0.get_ref().inner.deregister(selector) } + } - fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { - self.0.lock().unwrap_or_else(|e| e.into_inner()).read_exact(buf) + impl<T: Transport> ::vecio::Writev for SecureTransport<T> { + fn writev(&mut self, bufs: &[&[u8]]) -> io::Result<usize> { + let vec = bufs.concat(); + self.write(&vec) } } - impl io::Write for Stream { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.0.lock().unwrap_or_else(|e| e.into_inner()).write(buf) + impl<T: Transport> Transport for SecureTransport<T> { + fn take_socket_error(&mut self) -> io::Result<()> { + self.0.get_mut().inner.take_socket_error() } - fn flush(&mut self) -> io::Result<()> { - self.0.lock().unwrap_or_else(|e| e.into_inner()).flush() + fn blocked(&self) -> Option<super::Blocked> { + self.0.get_ref().blocked } + } - fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - self.0.lock().unwrap_or_else(|e| e.into_inner()).write_all(buf) - } - fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> { - self.0.lock().unwrap_or_else(|e| e.into_inner()).write_fmt(fmt) - } + // Records if this object was blocked on reading or writing. + #[derive(Debug)] + struct Journal<T> { + inner: T, + blocked: Option<Blocked>, } - impl NetworkStream for Stream { - fn peer_addr(&mut self) -> io::Result<SocketAddr> { - self.0.lock().unwrap_or_else(|e| e.into_inner()).get_mut().peer_addr() + fn journal<T: Read + Write>(inner: T) -> Journal<T> { + Journal { + inner: inner, + blocked: None, } + } - fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.0.lock().unwrap_or_else(|e| e.into_inner()).get_mut().set_read_timeout(dur) + impl<T: Read> Read for Journal<T> { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.blocked = None; + self.inner.read(buf).map_err(|e| match e.kind() { + io::ErrorKind::WouldBlock => { + self.blocked = Some(Blocked::Read); + e + }, + _ => e + }) } + } - fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.0.lock().unwrap_or_else(|e| e.into_inner()).get_mut().set_write_timeout(dur) + impl<T: Write> Write for Journal<T> { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.blocked = None; + self.inner.write(buf).map_err(|e| match e.kind() { + io::ErrorKind::WouldBlock => { + self.blocked = Some(Blocked::Write); + e + }, + _ => e + }) } - fn close(&mut self, how: Shutdown) -> io::Result<()> { - self.0.lock().unwrap_or_else(|e| e.into_inner()).get_mut().close(how) + fn flush(&mut self) -> io::Result<()> { + self.inner.flush() } } -} -#[cfg(test)] -mod tests { - use mock::MockStream; - use super::{NetworkStream}; - - #[test] - fn test_downcast_box_stream() { - // FIXME: Use Type ascription - let stream: Box<NetworkStream + Send> = Box::new(MockStream::new()); - - let mock = stream.downcast::<MockStream>().ok().unwrap(); - assert_eq!(mock, Box::new(MockStream::new())); - } - - #[test] - fn test_downcast_unchecked_box_stream() { - // FIXME: Use Type ascription - let stream: Box<NetworkStream + Send> = Box::new(MockStream::new()); - - let mock = unsafe { stream.downcast_unchecked::<MockStream>() }; - assert_eq!(mock, Box::new(MockStream::new())); - } } - diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -1,510 +1,369 @@ //! HTTP Server //! -//! # Server -//! //! A `Server` is created to listen on port, parse HTTP requests, and hand -//! them off to a `Handler`. By default, the Server will listen across multiple -//! threads, but that can be configured to a single thread if preferred. -//! -//! # Handling requests -//! -//! You must pass a `Handler` to the Server that will handle requests. There is -//! a default implementation for `fn`s and closures, allowing you pass one of -//! those easily. -//! -//! -//! ```no_run -//! use hyper::server::{Server, Request, Response}; -//! -//! fn hello(req: Request, res: Response) { -//! // handle things here -//! } -//! -//! Server::http("0.0.0.0:0").unwrap().handle(hello).unwrap(); -//! ``` -//! -//! As with any trait, you can also define a struct and implement `Handler` -//! directly on your own type, and pass that to the `Server` instead. -//! -//! ```no_run -//! use std::sync::Mutex; -//! use std::sync::mpsc::{channel, Sender}; -//! use hyper::server::{Handler, Server, Request, Response}; -//! -//! struct SenderHandler { -//! sender: Mutex<Sender<&'static str>> -//! } -//! -//! impl Handler for SenderHandler { -//! fn handle(&self, req: Request, res: Response) { -//! self.sender.lock().unwrap().send("start").unwrap(); -//! } -//! } -//! -//! -//! let (tx, rx) = channel(); -//! Server::http("0.0.0.0:0").unwrap().handle(SenderHandler { -//! sender: Mutex::new(tx) -//! }).unwrap(); -//! ``` -//! -//! Since the `Server` will be listening on multiple threads, the `Handler` -//! must implement `Sync`: any mutable state must be synchronized. -//! -//! ```no_run -//! use std::sync::atomic::{AtomicUsize, Ordering}; -//! use hyper::server::{Server, Request, Response}; -//! -//! let counter = AtomicUsize::new(0); -//! Server::http("0.0.0.0:0").unwrap().handle(move |req: Request, res: Response| { -//! counter.fetch_add(1, Ordering::Relaxed); -//! }).unwrap(); -//! ``` -//! -//! # The `Request` and `Response` pair -//! -//! A `Handler` receives a pair of arguments, a `Request` and a `Response`. The -//! `Request` includes access to the `method`, `uri`, and `headers` of the -//! incoming HTTP request. It also implements `std::io::Read`, in order to -//! read any body, such as with `POST` or `PUT` messages. -//! -//! Likewise, the `Response` includes ways to set the `status` and `headers`, -//! and implements `std::io::Write` to allow writing the response body. -//! -//! ```no_run -//! use std::io; -//! use hyper::server::{Server, Request, Response}; -//! use hyper::status::StatusCode; -//! -//! Server::http("0.0.0.0:0").unwrap().handle(|mut req: Request, mut res: Response| { -//! match req.method { -//! hyper::Post => { -//! io::copy(&mut req, &mut res.start().unwrap()).unwrap(); -//! }, -//! _ => *res.status_mut() = StatusCode::MethodNotAllowed -//! } -//! }).unwrap(); -//! ``` -//! -//! ## An aside: Write Status -//! -//! The `Response` uses a phantom type parameter to determine its write status. -//! What does that mean? In short, it ensures you never write a body before -//! adding all headers, and never add a header after writing some of the body. -//! -//! This is often done in most implementations by include a boolean property -//! on the response, such as `headers_written`, checking that each time the -//! body has something to write, so as to make sure the headers are sent once, -//! and only once. But this has 2 downsides: -//! -//! 1. You are typically never notified that your late header is doing nothing. -//! 2. There's a runtime cost to checking on every write. -//! -//! Instead, hyper handles this statically, or at compile-time. A -//! `Response<Fresh>` includes a `headers_mut()` method, allowing you add more -//! headers. It also does not implement `Write`, so you can't accidentally -//! write early. Once the "head" of the response is correct, you can "send" it -//! out by calling `start` on the `Response<Fresh>`. This will return a new -//! `Response<Streaming>` object, that no longer has `headers_mut()`, but does -//! implement `Write`. +//! them off to a `Handler`. use std::fmt; -use std::io::{self, ErrorKind, BufWriter, Write}; -use std::net::{SocketAddr, ToSocketAddrs}; -use std::thread::{self, JoinHandle}; +use std::net::SocketAddr; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; -use num_cpus; +use rotor::mio::{EventSet, PollOpt}; +use rotor::{self, Scope}; pub use self::request::Request; pub use self::response::Response; -pub use net::{Fresh, Streaming}; - -use Error; -use buffer::BufReader; -use header::{Headers, Expect, Connection}; -use http; -use method::Method; -use net::{NetworkListener, NetworkStream, HttpListener, HttpsListener, Ssl}; -use status::StatusCode; -use uri::RequestUri; -use version::HttpVersion::Http11; - -use self::listener::ListenerPool; +use http::{self, Next}; +use net::{Accept, HttpListener, HttpsListener, SslServer, Transport}; -pub mod request; -pub mod response; -mod listener; +mod request; +mod response; +mod message; -/// A server can listen on a TCP socket. -/// -/// Once listening, it will create a `Request`/`Response` pair for each -/// incoming connection, and hand them to the provided handler. -#[derive(Debug)] -pub struct Server<L = HttpListener> { - listener: L, - timeouts: Timeouts, -} - -#[derive(Clone, Copy, Debug)] -struct Timeouts { - read: Option<Duration>, - write: Option<Duration>, - keep_alive: Option<Duration>, +/// A configured `Server` ready to run. +pub struct ServerLoop<A, H> where A: Accept, H: HandlerFactory<A::Output> { + inner: Option<(rotor::Loop<ServerFsm<A, H>>, Context<H>)>, } -impl Default for Timeouts { - fn default() -> Timeouts { - Timeouts { - read: None, - write: None, - keep_alive: Some(Duration::from_secs(5)) - } +impl<A: Accept, H: HandlerFactory<A::Output>> fmt::Debug for ServerLoop<A, H> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad("ServerLoop") } } -macro_rules! try_option( - ($e:expr) => {{ - match $e { - Some(v) => v, - None => return None - } - }} -); +/// A Server that can accept incoming network requests. +#[derive(Debug)] +pub struct Server<T: Accept> { + listener: T, + keep_alive: bool, + idle_timeout: Duration, + max_sockets: usize, +} -impl<L: NetworkListener> Server<L> { - /// Creates a new server with the provided handler. +impl<T> Server<T> where T: Accept, T::Output: Transport { + /// Creates a new server with the provided Listener. #[inline] - pub fn new(listener: L) -> Server<L> { + pub fn new(listener: T) -> Server<T> { Server { listener: listener, - timeouts: Timeouts::default() + keep_alive: true, + idle_timeout: Duration::from_secs(10), + max_sockets: 4096, } } - /// Controls keep-alive for this server. - /// - /// The timeout duration passed will be used to determine how long - /// to keep the connection alive before dropping it. - /// - /// Passing `None` will disable keep-alive. + /// Enables or disables HTTP keep-alive. /// - /// Default is enabled with a 5 second timeout. - #[inline] - pub fn keep_alive(&mut self, timeout: Option<Duration>) { - self.timeouts.keep_alive = timeout; + /// Default is true. + pub fn keep_alive(mut self, val: bool) -> Server<T> { + self.keep_alive = val; + self } - /// Sets the read timeout for all Request reads. - pub fn set_read_timeout(&mut self, dur: Option<Duration>) { - self.timeouts.read = dur; + /// Sets how long an idle connection will be kept before closing. + /// + /// Default is 10 seconds. + pub fn idle_timeout(mut self, val: Duration) -> Server<T> { + self.idle_timeout = val; + self } - /// Sets the write timeout for all Response writes. - pub fn set_write_timeout(&mut self, dur: Option<Duration>) { - self.timeouts.write = dur; + /// Sets the maximum open sockets for this Server. + /// + /// Default is 4096, but most servers can handle much more than this. + pub fn max_sockets(mut self, val: usize) -> Server<T> { + self.max_sockets = val; + self } } -impl Server<HttpListener> { - /// Creates a new server that will handle `HttpStream`s. - pub fn http<To: ToSocketAddrs>(addr: To) -> ::Result<Server<HttpListener>> { - HttpListener::new(addr).map(Server::new) +impl Server<HttpListener> { //<H: HandlerFactory<<HttpListener as Accept>::Output>> Server<HttpListener, H> { + /// Creates a new HTTP server config listening on the provided address. + pub fn http(addr: &SocketAddr) -> ::Result<Server<HttpListener>> { + use ::rotor::mio::tcp::TcpListener; + TcpListener::bind(addr) + .map(HttpListener) + .map(Server::new) + .map_err(From::from) } } -impl<S: Ssl + Clone + Send> Server<HttpsListener<S>> { - /// Creates a new server that will handle `HttpStream`s over SSL. + +impl<S: SslServer> Server<HttpsListener<S>> { + /// Creates a new server config that will handle `HttpStream`s over SSL. /// /// You can use any SSL implementation, as long as implements `hyper::net::Ssl`. - pub fn https<A: ToSocketAddrs>(addr: A, ssl: S) -> ::Result<Server<HttpsListener<S>>> { - HttpsListener::new(addr, ssl).map(Server::new) + pub fn https(addr: &SocketAddr, ssl: S) -> ::Result<Server<HttpsListener<S>>> { + HttpsListener::new(addr, ssl) + .map(Server::new) + .map_err(From::from) } } -impl<L: NetworkListener + Send + 'static> Server<L> { + +impl<A: Accept> Server<A> where A::Output: Transport { /// Binds to a socket and starts handling connections. - pub fn handle<H: Handler + 'static>(self, handler: H) -> ::Result<Listening> { - self.handle_threads(handler, num_cpus::get() * 5 / 4) - } + pub fn handle<H>(self, factory: H) -> ::Result<(Listening, ServerLoop<A, H>)> + where H: HandlerFactory<A::Output> { + let addr = try!(self.listener.local_addr()); + let shutdown = Arc::new(AtomicBool::new(false)); + let shutdown_rx = shutdown.clone(); + + let mut config = rotor::Config::new(); + config.slab_capacity(self.max_sockets); + config.mio().notify_capacity(self.max_sockets); + let keep_alive = self.keep_alive; + let mut loop_ = rotor::Loop::new(&config).unwrap(); + let mut notifier = None; + { + let notifier = &mut notifier; + loop_.add_machine_with(move |scope| { + *notifier = Some(scope.notifier()); + rotor_try!(scope.register(&self.listener, EventSet::readable(), PollOpt::level())); + rotor::Response::ok(ServerFsm::Listener::<A, H>(self.listener, shutdown_rx)) + }).unwrap(); + } + let notifier = notifier.expect("loop.add_machine failed"); - /// Binds to a socket and starts handling connections with the provided - /// number of threads. - pub fn handle_threads<H: Handler + 'static>(self, handler: H, - threads: usize) -> ::Result<Listening> { - handle(self, handler, threads) + let listening = Listening { + addr: addr, + shutdown: (shutdown, notifier), + }; + let server = ServerLoop { + inner: Some((loop_, Context { + keep_alive: keep_alive, + factory: factory + })) + }; + Ok((listening, server)) } } -fn handle<H, L>(mut server: Server<L>, handler: H, threads: usize) -> ::Result<Listening> -where H: Handler + 'static, L: NetworkListener + Send + 'static { - let socket = try!(server.listener.local_addr()); - debug!("threads = {:?}", threads); - let pool = ListenerPool::new(server.listener); - let worker = Worker::new(handler, server.timeouts); - let work = move |mut stream| worker.handle_connection(&mut stream); - - let guard = thread::spawn(move || pool.accept(work, threads)); - - Ok(Listening { - _guard: Some(guard), - socket: socket, - }) -} - -struct Worker<H: Handler + 'static> { - handler: H, - timeouts: Timeouts, +impl<A: Accept, H: HandlerFactory<A::Output>> ServerLoop<A, H> { + /// Runs the server forever in this loop. + /// + /// This will block the current thread. + pub fn run(self) { + // drop will take care of it. + } } -impl<H: Handler + 'static> Worker<H> { - fn new(handler: H, timeouts: Timeouts) -> Worker<H> { - Worker { - handler: handler, - timeouts: timeouts, - } +impl<A: Accept, H: HandlerFactory<A::Output>> Drop for ServerLoop<A, H> { + fn drop(&mut self) { + self.inner.take().map(|(loop_, ctx)| { + let _ = loop_.run(ctx); + }); } +} - fn handle_connection<S>(&self, mut stream: &mut S) where S: NetworkStream + Clone { - debug!("Incoming stream"); - - self.handler.on_connection_start(); - - if let Err(e) = self.set_timeouts(&*stream) { - error!("set_timeouts error: {:?}", e); - return; - } - - let addr = match stream.peer_addr() { - Ok(addr) => addr, - Err(e) => { - error!("Peer Name error: {:?}", e); - return; - } - }; - - // FIXME: Use Type ascription - let stream_clone: &mut NetworkStream = &mut stream.clone(); - let mut rdr = BufReader::new(stream_clone); - let mut wrt = BufWriter::new(stream); - - while self.keep_alive_loop(&mut rdr, &mut wrt, addr) { - if let Err(e) = self.set_read_timeout(*rdr.get_ref(), self.timeouts.keep_alive) { - error!("set_read_timeout keep_alive {:?}", e); - break; - } - } - - self.handler.on_connection_end(); +struct Context<F> { + keep_alive: bool, + factory: F, +} - debug!("keep_alive loop ending for {}", addr); - } +impl<F: HandlerFactory<T>, T: Transport> http::MessageHandlerFactory<(), T> for Context<F> { + type Output = message::Message<F::Output, T>; - fn set_timeouts(&self, s: &NetworkStream) -> io::Result<()> { - try!(self.set_read_timeout(s, self.timeouts.read)); - self.set_write_timeout(s, self.timeouts.write) + fn create(&mut self, seed: http::Seed<()>) -> Self::Output { + message::Message::new(self.factory.create(seed.control())) } +} - fn set_write_timeout(&self, s: &NetworkStream, timeout: Option<Duration>) -> io::Result<()> { - s.set_write_timeout(timeout) - } +enum ServerFsm<A, H> +where A: Accept, + A::Output: Transport, + H: HandlerFactory<A::Output> { + Listener(A, Arc<AtomicBool>), + Conn(http::Conn<(), A::Output, message::Message<H::Output, A::Output>>) +} - fn set_read_timeout(&self, s: &NetworkStream, timeout: Option<Duration>) -> io::Result<()> { - s.set_read_timeout(timeout) +impl<A, H> rotor::Machine for ServerFsm<A, H> +where A: Accept, + A::Output: Transport, + H: HandlerFactory<A::Output> { + type Context = Context<H>; + type Seed = A::Output; + + fn create(seed: Self::Seed, scope: &mut Scope<Self::Context>) -> rotor::Response<Self, rotor::Void> { + rotor_try!(scope.register(&seed, EventSet::readable(), PollOpt::level())); + rotor::Response::ok( + ServerFsm::Conn( + http::Conn::new((), seed, scope.notifier()) + .keep_alive(scope.keep_alive) + ) + ) } - fn keep_alive_loop<W: Write>(&self, mut rdr: &mut BufReader<&mut NetworkStream>, - wrt: &mut W, addr: SocketAddr) -> bool { - let req = match Request::new(rdr, addr) { - Ok(req) => req, - Err(Error::Io(ref e)) if e.kind() == ErrorKind::ConnectionAborted => { - trace!("tcp closed, cancelling keep-alive loop"); - return false; - } - Err(Error::Io(e)) => { - debug!("ioerror in keepalive loop = {:?}", e); - return false; - } - Err(e) => { - //TODO: send a 400 response - error!("request error = {:?}", e); - return false; + fn ready(self, events: EventSet, scope: &mut Scope<Self::Context>) -> rotor::Response<Self, Self::Seed> { + match self { + ServerFsm::Listener(listener, rx) => { + match listener.accept() { + Ok(Some(conn)) => { + rotor::Response::spawn(ServerFsm::Listener(listener, rx), conn) + }, + Ok(None) => rotor::Response::ok(ServerFsm::Listener(listener, rx)), + Err(e) => { + error!("listener accept error {}", e); + // usually fine, just keep listening + rotor::Response::ok(ServerFsm::Listener(listener, rx)) + } + } + }, + ServerFsm::Conn(conn) => { + match conn.ready(events, scope) { + Some((conn, None)) => rotor::Response::ok(ServerFsm::Conn(conn)), + Some((conn, Some(dur))) => { + rotor::Response::ok(ServerFsm::Conn(conn)) + .deadline(scope.now() + dur) + } + None => rotor::Response::done() + } } - }; - - if !self.handle_expect(&req, wrt) { - return false; - } - - if let Err(e) = req.set_read_timeout(self.timeouts.read) { - error!("set_read_timeout {:?}", e); - return false; - } - - let mut keep_alive = self.timeouts.keep_alive.is_some() && - http::should_keep_alive(req.version, &req.headers); - let version = req.version; - let mut res_headers = Headers::new(); - if !keep_alive { - res_headers.set(Connection::close()); - } - { - let mut res = Response::new(wrt, &mut res_headers); - res.version = version; - self.handler.handle(req, res); } + } - // if the request was keep-alive, we need to check that the server agrees - // if it wasn't, then the server cannot force it to be true anyways - if keep_alive { - keep_alive = http::should_keep_alive(version, &res_headers); + fn spawned(self, _scope: &mut Scope<Self::Context>) -> rotor::Response<Self, Self::Seed> { + match self { + ServerFsm::Listener(listener, rx) => { + match listener.accept() { + Ok(Some(conn)) => { + rotor::Response::spawn(ServerFsm::Listener(listener, rx), conn) + }, + Ok(None) => rotor::Response::ok(ServerFsm::Listener(listener, rx)), + Err(e) => { + error!("listener accept error {}", e); + // usually fine, just keep listening + rotor::Response::ok(ServerFsm::Listener(listener, rx)) + } + } + }, + sock => rotor::Response::ok(sock) } - debug!("keep_alive = {:?} for {}", keep_alive, addr); - keep_alive } - fn handle_expect<W: Write>(&self, req: &Request, wrt: &mut W) -> bool { - if req.version == Http11 && req.headers.get() == Some(&Expect::Continue) { - let status = self.handler.check_continue((&req.method, &req.uri, &req.headers)); - match write!(wrt, "{} {}\r\n\r\n", Http11, status).and_then(|_| wrt.flush()) { - Ok(..) => (), - Err(e) => { - error!("error writing 100-continue: {:?}", e); - return false; + fn timeout(self, scope: &mut Scope<Self::Context>) -> rotor::Response<Self, Self::Seed> { + match self { + ServerFsm::Listener(..) => unreachable!("Listener cannot timeout"), + ServerFsm::Conn(conn) => { + match conn.timeout(scope) { + Some((conn, None)) => rotor::Response::ok(ServerFsm::Conn(conn)), + Some((conn, Some(dur))) => { + rotor::Response::ok(ServerFsm::Conn(conn)) + .deadline(scope.now() + dur) + } + None => rotor::Response::done() } } + } + } - if status != StatusCode::Continue { - debug!("non-100 status ({}) for Expect 100 request", status); - return false; + fn wakeup(self, scope: &mut Scope<Self::Context>) -> rotor::Response<Self, Self::Seed> { + match self { + ServerFsm::Listener(lst, shutdown) => { + if shutdown.load(Ordering::Acquire) { + let _ = scope.deregister(&lst); + scope.shutdown_loop(); + rotor::Response::done() + } else { + rotor::Response::ok(ServerFsm::Listener(lst, shutdown)) + } + }, + ServerFsm::Conn(conn) => match conn.wakeup(scope) { + Some((conn, None)) => rotor::Response::ok(ServerFsm::Conn(conn)), + Some((conn, Some(dur))) => { + rotor::Response::ok(ServerFsm::Conn(conn)) + .deadline(scope.now() + dur) + } + None => rotor::Response::done() } } - - true } } -/// A listening server, which can later be closed. +/// A handle of the running server. pub struct Listening { - _guard: Option<JoinHandle<()>>, - /// The socket addresses that the server is bound to. - pub socket: SocketAddr, + addr: SocketAddr, + shutdown: (Arc<AtomicBool>, rotor::Notifier), } impl fmt::Debug for Listening { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Listening {{ socket: {:?} }}", self.socket) + f.debug_struct("Listening") + .field("addr", &self.addr) + .field("closed", &self.shutdown.0.load(Ordering::Relaxed)) + .finish() } } -impl Drop for Listening { - fn drop(&mut self) { - let _ = self._guard.take().map(|g| g.join()); +impl fmt::Display for Listening { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&self.addr, f) } } impl Listening { - /// Warning: This function doesn't work. The server remains listening after you called - /// it. See https://github.com/hyperium/hyper/issues/338 for more details. - /// + /// The address this server is listening on. + pub fn addr(&self) -> &SocketAddr { + &self.addr + } + /// Stop the server from listening to its socket address. - pub fn close(&mut self) -> ::Result<()> { - let _ = self._guard.take(); - debug!("closing server"); - Ok(()) + pub fn close(self) { + debug!("closing server {}", self); + self.shutdown.0.store(true, Ordering::Release); + self.shutdown.1.wakeup().unwrap(); } } -/// A handler that can handle incoming requests for a server. -pub trait Handler: Sync + Send { - /// Receives a `Request`/`Response` pair, and should perform some action on them. +/// A trait to react to server events that happen for each message. +/// +/// Each event handler returns it's desired `Next` action. +pub trait Handler<T: Transport> { + /// This event occurs first, triggering when a `Request` has been parsed. + fn on_request(&mut self, request: Request) -> Next; + /// This event occurs each time the `Request` is ready to be read from. + fn on_request_readable(&mut self, request: &mut http::Decoder<T>) -> Next; + /// This event occurs after the first time this handled signals `Next::write()`. + fn on_response(&mut self, response: &mut Response) -> Next; + /// This event occurs each time the `Response` is ready to be written to. + fn on_response_writable(&mut self, response: &mut http::Encoder<T>) -> Next; + + /// This event occurs whenever an `Error` occurs outside of the other events. /// - /// This could reading from the request, and writing to the response. - fn handle<'a, 'k>(&'a self, Request<'a, 'k>, Response<'a, Fresh>); + /// This could IO errors while waiting for events, or a timeout, etc. + fn on_error(&mut self, err: ::Error) -> Next where Self: Sized { + debug!("default Handler.on_error({:?})", err); + http::Next::remove() + } - /// Called when a Request includes a `Expect: 100-continue` header. - /// - /// By default, this will always immediately response with a `StatusCode::Continue`, - /// but can be overridden with custom behavior. - fn check_continue(&self, _: (&Method, &RequestUri, &Headers)) -> StatusCode { - StatusCode::Continue + /// This event occurs when this Handler has requested to remove the Transport. + fn on_remove(self, _transport: T) where Self: Sized { + debug!("default Handler.on_remove"); } +} - /// This is run after a connection is received, on a per-connection basis (not a - /// per-request basis, as a connection with keep-alive may handle multiple - /// requests) - fn on_connection_start(&self) { } - /// This is run before a connection is closed, on a per-connection basis (not a - /// per-request basis, as a connection with keep-alive may handle multiple - /// requests) - fn on_connection_end(&self) { } +/// Used to create a `Handler` when a new message is received by the server. +pub trait HandlerFactory<T: Transport> { + /// The `Handler` to use for the incoming message. + type Output: Handler<T>; + /// Creates the associated `Handler`. + fn create(&mut self, ctrl: http::Control) -> Self::Output; } -impl<F> Handler for F where F: Fn(Request, Response<Fresh>), F: Sync + Send { - fn handle<'a, 'k>(&'a self, req: Request<'a, 'k>, res: Response<'a, Fresh>) { - self(req, res) +impl<F, H, T> HandlerFactory<T> for F +where F: FnMut(http::Control) -> H, H: Handler<T>, T: Transport { + type Output = H; + fn create(&mut self, ctrl: http::Control) -> H { + self(ctrl) } } #[cfg(test)] mod tests { - use header::Headers; - use method::Method; - use mock::MockStream; - use status::StatusCode; - use uri::RequestUri; - - use super::{Request, Response, Fresh, Handler, Worker}; - - #[test] - fn test_check_continue_default() { - let mut mock = MockStream::with_input(b"\ - POST /upload HTTP/1.1\r\n\ - Host: example.domain\r\n\ - Expect: 100-continue\r\n\ - Content-Length: 10\r\n\ - \r\n\ - 1234567890\ - "); - - fn handle(_: Request, res: Response<Fresh>) { - res.start().unwrap().end().unwrap(); - } - - Worker::new(handle, Default::default()).handle_connection(&mut mock); - let cont = b"HTTP/1.1 100 Continue\r\n\r\n"; - assert_eq!(&mock.write[..cont.len()], cont); - let res = b"HTTP/1.1 200 OK\r\n"; - assert_eq!(&mock.write[cont.len()..cont.len() + res.len()], res); - } - #[test] - fn test_check_continue_reject() { - struct Reject; - impl Handler for Reject { - fn handle<'a, 'k>(&'a self, _: Request<'a, 'k>, res: Response<'a, Fresh>) { - res.start().unwrap().end().unwrap(); - } - - fn check_continue(&self, _: (&Method, &RequestUri, &Headers)) -> StatusCode { - StatusCode::ExpectationFailed - } - } - - let mut mock = MockStream::with_input(b"\ - POST /upload HTTP/1.1\r\n\ - Host: example.domain\r\n\ - Expect: 100-continue\r\n\ - Content-Length: 10\r\n\ - \r\n\ - 1234567890\ - "); - - Worker::new(Reject, Default::default()).handle_connection(&mut mock); - assert_eq!(mock.write, &b"HTTP/1.1 417 Expectation Failed\r\n\r\n"[..]); - } } diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -2,324 +2,75 @@ //! //! These are requests that a `hyper::Server` receives, and include its method, //! target URI, headers, and message body. -use std::io::{self, Read}; -use std::net::SocketAddr; -use std::time::Duration; +//use std::net::SocketAddr; -use buffer::BufReader; -use net::NetworkStream; -use version::{HttpVersion}; +use version::HttpVersion; use method::Method; -use header::{Headers, ContentLength, TransferEncoding}; -use http::h1::{self, Incoming, HttpReader}; -use http::h1::HttpReader::{SizedReader, ChunkedReader, EmptyReader}; +use header::Headers; +use http::{RequestHead, MessageHead, RequestLine}; use uri::RequestUri; -/// A request bundles several parts of an incoming `NetworkStream`, given to a `Handler`. -pub struct Request<'a, 'b: 'a> { - /// The IP address of the remote connection. - pub remote_addr: SocketAddr, - /// The `Method`, such as `Get`, `Post`, etc. - pub method: Method, - /// The headers of the incoming request. - pub headers: Headers, - /// The target request-uri for this request. - pub uri: RequestUri, - /// The version of HTTP for this request. - pub version: HttpVersion, - body: HttpReader<&'a mut BufReader<&'b mut NetworkStream>> -} +pub fn new(incoming: RequestHead) -> Request { + let MessageHead { version, subject: RequestLine(method, uri), headers } = incoming; + debug!("Request Line: {:?} {:?} {:?}", method, uri, version); + debug!("{:#?}", headers); + Request { + //remote_addr: addr, + method: method, + uri: uri, + headers: headers, + version: version, + } +} -impl<'a, 'b: 'a> Request<'a, 'b> { - /// Create a new Request, reading the StartLine and Headers so they are - /// immediately useful. - pub fn new(mut stream: &'a mut BufReader<&'b mut NetworkStream>, addr: SocketAddr) - -> ::Result<Request<'a, 'b>> { +/// A request bundles several parts of an incoming `NetworkStream`, given to a `Handler`. +#[derive(Debug)] +pub struct Request { + // The IP address of the remote connection. + //remote_addr: SocketAddr, + method: Method, + headers: Headers, + uri: RequestUri, + version: HttpVersion, +} - let Incoming { version, subject: (method, uri), headers } = try!(h1::parse_request(stream)); - debug!("Request Line: {:?} {:?} {:?}", method, uri, version); - debug!("{:?}", headers); - let body = if headers.has::<ContentLength>() { - match headers.get::<ContentLength>() { - Some(&ContentLength(len)) => SizedReader(stream, len), - None => unreachable!() - } - } else if headers.has::<TransferEncoding>() { - todo!("check for Transfer-Encoding: chunked"); - ChunkedReader(stream, None) - } else { - EmptyReader(stream) - }; +impl Request { + /// The `Method`, such as `Get`, `Post`, etc. + #[inline] + pub fn method(&self) -> &Method { &self.method } - Ok(Request { - remote_addr: addr, - method: method, - uri: uri, - headers: headers, - version: version, - body: body - }) - } + /// The headers of the incoming request. + #[inline] + pub fn headers(&self) -> &Headers { &self.headers } - /// Set the read timeout of the underlying NetworkStream. + /// The target request-uri for this request. #[inline] - pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> { - self.body.get_ref().get_ref().set_read_timeout(timeout) - } + pub fn uri(&self) -> &RequestUri { &self.uri } - /// Get a reference to the underlying `NetworkStream`. + /// The version of HTTP for this request. #[inline] - pub fn downcast_ref<T: NetworkStream>(&self) -> Option<&T> { - self.body.get_ref().get_ref().downcast_ref() - } + pub fn version(&self) -> &HttpVersion { &self.version } - /// Get a reference to the underlying Ssl stream, if connected - /// over HTTPS. - /// - /// # Example - /// - /// ```rust - /// # extern crate hyper; - /// # #[cfg(feature = "openssl")] - /// extern crate openssl; - /// # #[cfg(feature = "openssl")] - /// use openssl::ssl::SslStream; - /// use hyper::net::HttpStream; - /// # fn main() {} - /// # #[cfg(feature = "openssl")] - /// # fn doc_ssl(req: hyper::server::Request) { - /// let maybe_ssl = req.ssl::<SslStream<HttpStream>>(); - /// # } - /// ``` + /* + /// The target path of this Request. #[inline] - pub fn ssl<T: NetworkStream>(&self) -> Option<&T> { - use ::net::HttpsStream; - match self.downcast_ref() { - Some(&HttpsStream::Https(ref s)) => Some(s), + pub fn path(&self) -> Option<&str> { + match *self.uri { + RequestUri::AbsolutePath(ref s) => Some(s), + RequestUri::AbsoluteUri(ref url) => Some(&url[::url::Position::BeforePath..]), _ => None } } + */ - /// Deconstruct a Request into its constituent parts. - #[inline] - pub fn deconstruct(self) -> (SocketAddr, Method, Headers, - RequestUri, HttpVersion, - HttpReader<&'a mut BufReader<&'b mut NetworkStream>>) { - (self.remote_addr, self.method, self.headers, - self.uri, self.version, self.body) - } -} - -impl<'a, 'b> Read for Request<'a, 'b> { + /// Deconstruct this Request into its pieces. + /// + /// Modifying these pieces will have no effect on how hyper behaves. #[inline] - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.body.read(buf) - } -} - -#[cfg(test)] -mod tests { - use buffer::BufReader; - use header::{Host, TransferEncoding, Encoding}; - use net::NetworkStream; - use mock::MockStream; - use super::Request; - - use std::io::{self, Read}; - use std::net::SocketAddr; - - fn sock(s: &str) -> SocketAddr { - s.parse().unwrap() - } - - fn read_to_string(mut req: Request) -> io::Result<String> { - let mut s = String::new(); - try!(req.read_to_string(&mut s)); - Ok(s) - } - - #[test] - fn test_get_empty_body() { - let mut mock = MockStream::with_input(b"\ - GET / HTTP/1.1\r\n\ - Host: example.domain\r\n\ - \r\n\ - I'm a bad request.\r\n\ - "); - - // FIXME: Use Type ascription - let mock: &mut NetworkStream = &mut mock; - let mut stream = BufReader::new(mock); - - let req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); - assert_eq!(read_to_string(req).unwrap(), "".to_owned()); - } - - #[test] - fn test_get_with_body() { - let mut mock = MockStream::with_input(b"\ - GET / HTTP/1.1\r\n\ - Host: example.domain\r\n\ - Content-Length: 19\r\n\ - \r\n\ - I'm a good request.\r\n\ - "); - - // FIXME: Use Type ascription - let mock: &mut NetworkStream = &mut mock; - let mut stream = BufReader::new(mock); - - let req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); - assert_eq!(read_to_string(req).unwrap(), "I'm a good request.".to_owned()); - } - - #[test] - fn test_head_empty_body() { - let mut mock = MockStream::with_input(b"\ - HEAD / HTTP/1.1\r\n\ - Host: example.domain\r\n\ - \r\n\ - I'm a bad request.\r\n\ - "); - - // FIXME: Use Type ascription - let mock: &mut NetworkStream = &mut mock; - let mut stream = BufReader::new(mock); - - let req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); - assert_eq!(read_to_string(req).unwrap(), "".to_owned()); - } - - #[test] - fn test_post_empty_body() { - let mut mock = MockStream::with_input(b"\ - POST / HTTP/1.1\r\n\ - Host: example.domain\r\n\ - \r\n\ - I'm a bad request.\r\n\ - "); - - // FIXME: Use Type ascription - let mock: &mut NetworkStream = &mut mock; - let mut stream = BufReader::new(mock); - - let req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); - assert_eq!(read_to_string(req).unwrap(), "".to_owned()); - } - - #[test] - fn test_parse_chunked_request() { - let mut mock = MockStream::with_input(b"\ - POST / HTTP/1.1\r\n\ - Host: example.domain\r\n\ - Transfer-Encoding: chunked\r\n\ - \r\n\ - 1\r\n\ - q\r\n\ - 2\r\n\ - we\r\n\ - 2\r\n\ - rt\r\n\ - 0\r\n\ - \r\n" - ); - - // FIXME: Use Type ascription - let mock: &mut NetworkStream = &mut mock; - let mut stream = BufReader::new(mock); - - let req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); - - // The headers are correct? - match req.headers.get::<Host>() { - Some(host) => { - assert_eq!("example.domain", host.hostname); - }, - None => panic!("Host header expected!"), - }; - match req.headers.get::<TransferEncoding>() { - Some(encodings) => { - assert_eq!(1, encodings.len()); - assert_eq!(Encoding::Chunked, encodings[0]); - } - None => panic!("Transfer-Encoding: chunked expected!"), - }; - // The content is correctly read? - assert_eq!(read_to_string(req).unwrap(), "qwert".to_owned()); - } - - /// Tests that when a chunk size is not a valid radix-16 number, an error - /// is returned. - #[test] - fn test_invalid_chunk_size_not_hex_digit() { - let mut mock = MockStream::with_input(b"\ - POST / HTTP/1.1\r\n\ - Host: example.domain\r\n\ - Transfer-Encoding: chunked\r\n\ - \r\n\ - X\r\n\ - 1\r\n\ - 0\r\n\ - \r\n" - ); - - // FIXME: Use Type ascription - let mock: &mut NetworkStream = &mut mock; - let mut stream = BufReader::new(mock); - - let req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); - - assert!(read_to_string(req).is_err()); - } - - /// Tests that when a chunk size contains an invalid extension, an error is - /// returned. - #[test] - fn test_invalid_chunk_size_extension() { - let mut mock = MockStream::with_input(b"\ - POST / HTTP/1.1\r\n\ - Host: example.domain\r\n\ - Transfer-Encoding: chunked\r\n\ - \r\n\ - 1 this is an invalid extension\r\n\ - 1\r\n\ - 0\r\n\ - \r\n" - ); - - // FIXME: Use Type ascription - let mock: &mut NetworkStream = &mut mock; - let mut stream = BufReader::new(mock); - - let req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); - - assert!(read_to_string(req).is_err()); - } - - /// Tests that when a valid extension that contains a digit is appended to - /// the chunk size, the chunk is correctly read. - #[test] - fn test_chunk_size_with_extension() { - let mut mock = MockStream::with_input(b"\ - POST / HTTP/1.1\r\n\ - Host: example.domain\r\n\ - Transfer-Encoding: chunked\r\n\ - \r\n\ - 1;this is an extension with a digit 1\r\n\ - 1\r\n\ - 0\r\n\ - \r\n" - ); - - // FIXME: Use Type ascription - let mock: &mut NetworkStream = &mut mock; - let mut stream = BufReader::new(mock); - - let req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); - - assert_eq!(read_to_string(req).unwrap(), "1".to_owned()); + pub fn deconstruct(self) -> (Method, RequestUri, HttpVersion, Headers) { + (self.method, self.uri, self.version, self.headers) } } diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -2,431 +2,49 @@ //! //! These are responses sent by a `hyper::Server` to clients, after //! receiving a request. -use std::any::{Any, TypeId}; -use std::marker::PhantomData; -use std::mem; -use std::io::{self, Write}; -use std::ptr; -use std::thread; - -use time::now_utc; - use header; -use http::h1::{LINE_ENDING, HttpWriter}; -use http::h1::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter}; -use status; -use net::{Fresh, Streaming}; +use http; +use status::StatusCode; use version; /// The outgoing half for a Tcp connection, created by a `Server` and given to a `Handler`. /// /// The default `StatusCode` for a `Response` is `200 OK`. -/// -/// There is a `Drop` implementation for `Response` that will automatically -/// write the head and flush the body, if the handler has not already done so, -/// so that the server doesn't accidentally leave dangling requests. #[derive(Debug)] -pub struct Response<'a, W: Any = Fresh> { - /// The HTTP version of this response. - pub version: version::HttpVersion, - // Stream the Response is writing to, not accessible through UnwrittenResponse - body: HttpWriter<&'a mut (Write + 'a)>, - // The status code for the request. - status: status::StatusCode, - // The outgoing headers on this response. - headers: &'a mut header::Headers, - - _writing: PhantomData<W> +pub struct Response<'a> { + head: &'a mut http::MessageHead<StatusCode>, } -impl<'a, W: Any> Response<'a, W> { - /// The status of this response. - #[inline] - pub fn status(&self) -> status::StatusCode { self.status } - +impl<'a> Response<'a> { /// The headers of this response. #[inline] - pub fn headers(&self) -> &header::Headers { &*self.headers } - - /// Construct a Response from its constituent parts. - #[inline] - pub fn construct(version: version::HttpVersion, - body: HttpWriter<&'a mut (Write + 'a)>, - status: status::StatusCode, - headers: &'a mut header::Headers) -> Response<'a, Fresh> { - Response { - status: status, - version: version, - body: body, - headers: headers, - _writing: PhantomData, - } - } - - /// Deconstruct this Response into its constituent parts. - #[inline] - pub fn deconstruct(self) -> (version::HttpVersion, HttpWriter<&'a mut (Write + 'a)>, - status::StatusCode, &'a mut header::Headers) { - unsafe { - let parts = ( - self.version, - ptr::read(&self.body), - self.status, - ptr::read(&self.headers) - ); - mem::forget(self); - parts - } - } - - fn write_head(&mut self) -> io::Result<Body> { - debug!("writing head: {:?} {:?}", self.version, self.status); - try!(write!(&mut self.body, "{} {}\r\n", self.version, self.status)); - - if !self.headers.has::<header::Date>() { - self.headers.set(header::Date(header::HttpDate(now_utc()))); - } - - let body_type = match self.status { - status::StatusCode::NoContent | status::StatusCode::NotModified => Body::Empty, - c if c.class() == status::StatusClass::Informational => Body::Empty, - _ => if let Some(cl) = self.headers.get::<header::ContentLength>() { - Body::Sized(**cl) - } else { - Body::Chunked - } - }; - - // can't do in match above, thanks borrowck - if body_type == Body::Chunked { - let encodings = match self.headers.get_mut::<header::TransferEncoding>() { - Some(&mut header::TransferEncoding(ref mut encodings)) => { - //TODO: check if chunked is already in encodings. use HashSet? - encodings.push(header::Encoding::Chunked); - false - }, - None => true - }; - - if encodings { - self.headers.set::<header::TransferEncoding>( - header::TransferEncoding(vec![header::Encoding::Chunked])) - } - } - + pub fn headers(&self) -> &header::Headers { &self.head.headers } - debug!("headers [\n{:?}]", self.headers); - try!(write!(&mut self.body, "{}", self.headers)); - try!(write!(&mut self.body, "{}", LINE_ENDING)); - - Ok(body_type) - } -} - -impl<'a> Response<'a, Fresh> { - /// Creates a new Response that can be used to write to a network stream. - #[inline] - pub fn new(stream: &'a mut (Write + 'a), headers: &'a mut header::Headers) -> - Response<'a, Fresh> { - Response { - status: status::StatusCode::Ok, - version: version::HttpVersion::Http11, - headers: headers, - body: ThroughWriter(stream), - _writing: PhantomData, - } - } - - /// Writes the body and ends the response. - /// - /// This is a shortcut method for when you have a response with a fixed - /// size, and would only need a single `write` call normally. - /// - /// # Example - /// - /// ``` - /// # use hyper::server::Response; - /// fn handler(res: Response) { - /// res.send(b"Hello World!").unwrap(); - /// } - /// ``` - /// - /// The above is the same, but shorter, than the longer: - /// - /// ``` - /// # use hyper::server::Response; - /// use std::io::Write; - /// use hyper::header::ContentLength; - /// fn handler(mut res: Response) { - /// let body = b"Hello World!"; - /// res.headers_mut().set(ContentLength(body.len() as u64)); - /// let mut res = res.start().unwrap(); - /// res.write_all(body).unwrap(); - /// } - /// ``` + /// The status of this response. #[inline] - pub fn send(mut self, body: &[u8]) -> io::Result<()> { - self.headers.set(header::ContentLength(body.len() as u64)); - let mut stream = try!(self.start()); - try!(stream.write_all(body)); - stream.end() + pub fn status(&self) -> &StatusCode { + &self.head.subject } - /// Consume this Response<Fresh>, writing the Headers and Status and - /// creating a Response<Streaming> - pub fn start(mut self) -> io::Result<Response<'a, Streaming>> { - let body_type = try!(self.write_head()); - let (version, body, status, headers) = self.deconstruct(); - let stream = match body_type { - Body::Chunked => ChunkedWriter(body.into_inner()), - Body::Sized(len) => SizedWriter(body.into_inner(), len), - Body::Empty => EmptyWriter(body.into_inner()), - }; - - // "copy" to change the phantom type - Ok(Response { - version: version, - body: stream, - status: status, - headers: headers, - _writing: PhantomData, - }) - } - /// Get a mutable reference to the status. + /// The HTTP version of this response. #[inline] - pub fn status_mut(&mut self) -> &mut status::StatusCode { &mut self.status } + pub fn version(&self) -> &version::HttpVersion { &self.head.version } /// Get a mutable reference to the Headers. #[inline] - pub fn headers_mut(&mut self) -> &mut header::Headers { self.headers } -} - - -impl<'a> Response<'a, Streaming> { - /// Flushes all writing of a response to the client. - #[inline] - pub fn end(self) -> io::Result<()> { - trace!("ending"); - let (_, body, _, _) = self.deconstruct(); - try!(body.end()); - Ok(()) - } -} - -impl<'a> Write for Response<'a, Streaming> { - #[inline] - fn write(&mut self, msg: &[u8]) -> io::Result<usize> { - debug!("write {:?} bytes", msg.len()); - self.body.write(msg) - } + pub fn headers_mut(&mut self) -> &mut header::Headers { &mut self.head.headers } + /// Get a mutable reference to the status. #[inline] - fn flush(&mut self) -> io::Result<()> { - self.body.flush() + pub fn set_status(&mut self, status: StatusCode) { + self.head.subject = status; } } -#[derive(PartialEq)] -enum Body { - Chunked, - Sized(u64), - Empty, -} - -impl<'a, T: Any> Drop for Response<'a, T> { - fn drop(&mut self) { - if TypeId::of::<T>() == TypeId::of::<Fresh>() { - if thread::panicking() { - self.status = status::StatusCode::InternalServerError; - } - - let mut body = match self.write_head() { - Ok(Body::Chunked) => ChunkedWriter(self.body.get_mut()), - Ok(Body::Sized(len)) => SizedWriter(self.body.get_mut(), len), - Ok(Body::Empty) => EmptyWriter(self.body.get_mut()), - Err(e) => { - debug!("error dropping request: {:?}", e); - return; - } - }; - end(&mut body); - } else { - end(&mut self.body); - }; - - - #[inline] - fn end<W: Write>(w: &mut W) { - match w.write(&[]) { - Ok(_) => match w.flush() { - Ok(_) => debug!("drop successful"), - Err(e) => debug!("error dropping request: {:?}", e) - }, - Err(e) => debug!("error dropping request: {:?}", e) - } - } - } -} - -#[cfg(test)] -mod tests { - use header::Headers; - use mock::MockStream; - use super::Response; - - macro_rules! lines { - ($s:ident = $($line:pat),+) => ({ - let s = String::from_utf8($s.write).unwrap(); - let mut lines = s.split_terminator("\r\n"); - - $( - match lines.next() { - Some($line) => (), - other => panic!("line mismatch: {:?} != {:?}", other, stringify!($line)) - } - )+ - - assert_eq!(lines.next(), None); - }) - } - - #[test] - fn test_fresh_start() { - let mut headers = Headers::new(); - let mut stream = MockStream::new(); - { - let res = Response::new(&mut stream, &mut headers); - res.start().unwrap().deconstruct(); - } - - lines! { stream = - "HTTP/1.1 200 OK", - _date, - _transfer_encoding, - "" - } - } - - #[test] - fn test_streaming_end() { - let mut headers = Headers::new(); - let mut stream = MockStream::new(); - { - let res = Response::new(&mut stream, &mut headers); - res.start().unwrap().end().unwrap(); - } - - lines! { stream = - "HTTP/1.1 200 OK", - _date, - _transfer_encoding, - "", - "0", - "" // empty zero body - } - } - - #[test] - fn test_fresh_drop() { - use status::StatusCode; - let mut headers = Headers::new(); - let mut stream = MockStream::new(); - { - let mut res = Response::new(&mut stream, &mut headers); - *res.status_mut() = StatusCode::NotFound; - } - - lines! { stream = - "HTTP/1.1 404 Not Found", - _date, - _transfer_encoding, - "", - "0", - "" // empty zero body - } - } - - // x86 windows msvc does not support unwinding - // See https://github.com/rust-lang/rust/issues/25869 - #[cfg(not(all(windows, target_arch="x86", target_env="msvc")))] - #[test] - fn test_fresh_drop_panicing() { - use std::thread; - use std::sync::{Arc, Mutex}; - - use status::StatusCode; - - let stream = MockStream::new(); - let stream = Arc::new(Mutex::new(stream)); - let inner_stream = stream.clone(); - let join_handle = thread::spawn(move || { - let mut headers = Headers::new(); - let mut stream = inner_stream.lock().unwrap(); - let mut res = Response::new(&mut *stream, &mut headers); - *res.status_mut() = StatusCode::NotFound; - - panic!("inside") - }); - - assert!(join_handle.join().is_err()); - - let stream = match stream.lock() { - Err(poisoned) => poisoned.into_inner().clone(), - Ok(_) => unreachable!() - }; - - lines! { stream = - "HTTP/1.1 500 Internal Server Error", - _date, - _transfer_encoding, - "", - "0", - "" // empty zero body - } - } - - - #[test] - fn test_streaming_drop() { - use std::io::Write; - use status::StatusCode; - let mut headers = Headers::new(); - let mut stream = MockStream::new(); - { - let mut res = Response::new(&mut stream, &mut headers); - *res.status_mut() = StatusCode::NotFound; - let mut stream = res.start().unwrap(); - stream.write_all(b"foo").unwrap(); - } - - lines! { stream = - "HTTP/1.1 404 Not Found", - _date, - _transfer_encoding, - "", - "3", - "foo", - "0", - "" // empty zero body - } - } - - #[test] - fn test_no_content() { - use status::StatusCode; - let mut headers = Headers::new(); - let mut stream = MockStream::new(); - { - let mut res = Response::new(&mut stream, &mut headers); - *res.status_mut() = StatusCode::NoContent; - res.start().unwrap(); - } - - lines! { stream = - "HTTP/1.1 204 No Content", - _date, - "" - } +/// Creates a new Response that can be used to write to a network stream. +pub fn new<'a>(head: &'a mut http::MessageHead<StatusCode>) -> Response<'a> { + Response { + head: head } } diff --git /dev/null b/tests/client.rs new file mode 100644 --- /dev/null +++ b/tests/client.rs @@ -0,0 +1,205 @@ +#![deny(warnings)] +extern crate hyper; + +use std::io::{self, Read, Write}; +use std::net::TcpListener; +use std::sync::mpsc; +use std::time::Duration; + +use hyper::client::{Handler, Request, Response, HttpConnector}; +use hyper::header; +use hyper::{Method, StatusCode, Next, Encoder, Decoder}; +use hyper::net::HttpStream; + +fn s(bytes: &[u8]) -> &str { + ::std::str::from_utf8(bytes.as_ref()).unwrap() +} + +#[derive(Debug)] +struct TestHandler { + opts: Opts, + tx: mpsc::Sender<Msg> +} + +impl TestHandler { + fn new(opts: Opts) -> (TestHandler, mpsc::Receiver<Msg>) { + let (tx, rx) = mpsc::channel(); + (TestHandler { + opts: opts, + tx: tx + }, rx) + } +} + +#[derive(Debug)] +enum Msg { + Head(Response), + Chunk(Vec<u8>), + Error(hyper::Error), +} + +fn read(opts: &Opts) -> Next { + if let Some(timeout) = opts.read_timeout { + Next::read().timeout(timeout) + } else { + Next::read() + } +} + +impl Handler<HttpStream> for TestHandler { + fn on_request(&mut self, req: &mut Request) -> Next { + req.set_method(self.opts.method.clone()); + read(&self.opts) + } + + fn on_request_writable(&mut self, _encoder: &mut Encoder<HttpStream>) -> Next { + read(&self.opts) + } + + fn on_response(&mut self, res: Response) -> Next { + use hyper::header; + // server responses can include a body until eof, if not size is specified + let mut has_body = true; + if let Some(len) = res.headers().get::<header::ContentLength>() { + if **len == 0 { + has_body = false; + } + } + self.tx.send(Msg::Head(res)).unwrap(); + if has_body { + read(&self.opts) + } else { + Next::end() + } + } + + fn on_response_readable(&mut self, decoder: &mut Decoder<HttpStream>) -> Next { + let mut v = vec![0; 512]; + match decoder.read(&mut v) { + Ok(n) => { + v.truncate(n); + self.tx.send(Msg::Chunk(v)).unwrap(); + if n == 0 { + Next::end() + } else { + read(&self.opts) + } + }, + Err(e) => match e.kind() { + io::ErrorKind::WouldBlock => read(&self.opts), + _ => panic!("io read error: {:?}", e) + } + } + } + + fn on_error(&mut self, err: hyper::Error) -> Next { + self.tx.send(Msg::Error(err)).unwrap(); + Next::remove() + } +} + +struct Client { + client: Option<hyper::Client<TestHandler>>, +} + +#[derive(Debug)] +struct Opts { + method: Method, + read_timeout: Option<Duration>, +} + +impl Default for Opts { + fn default() -> Opts { + Opts { + method: Method::Get, + read_timeout: None, + } + } +} + +fn opts() -> Opts { + Opts::default() +} + +impl Opts { + fn method(mut self, method: Method) -> Opts { + self.method = method; + self + } + + fn read_timeout(mut self, timeout: Duration) -> Opts { + self.read_timeout = Some(timeout); + self + } +} + +impl Client { + fn request<U>(&self, url: U, opts: Opts) -> mpsc::Receiver<Msg> + where U: AsRef<str> { + let (handler, rx) = TestHandler::new(opts); + self.client.as_ref().unwrap() + .request(url.as_ref().parse().unwrap(), handler).unwrap(); + rx + } +} + +impl Drop for Client { + fn drop(&mut self) { + self.client.take().map(|c| c.close()); + } +} + +fn client() -> Client { + let c = hyper::Client::<TestHandler>::configure() + .connector(HttpConnector::default()) + .build().unwrap(); + Client { + client: Some(c), + } +} + + +#[test] +fn client_get() { + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = server.local_addr().unwrap(); + let client = client(); + let res = client.request(format!("http://{}/", addr), opts().method(Method::Get)); + + let mut inc = server.accept().unwrap().0; + inc.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + inc.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut buf = [0; 4096]; + let n = inc.read(&mut buf).unwrap(); + let expected = format!("GET / HTTP/1.1\r\nHost: {}\r\n\r\n", addr); + assert_eq!(s(&buf[..n]), expected); + + inc.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap(); + + if let Msg::Head(head) = res.recv().unwrap() { + assert_eq!(head.status(), &StatusCode::Ok); + assert_eq!(head.headers().get(), Some(&header::ContentLength(0))); + } else { + panic!("we lost the head!"); + } + //drop(inc); + + assert!(res.recv().is_err()); +} + +#[test] +fn client_read_timeout() { + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = server.local_addr().unwrap(); + let client = client(); + let res = client.request(format!("http://{}/", addr), opts().read_timeout(Duration::from_secs(3))); + + let mut inc = server.accept().unwrap().0; + let mut buf = [0; 4096]; + inc.read(&mut buf).unwrap(); + + match res.recv() { + Ok(Msg::Error(hyper::Error::Timeout)) => (), + other => panic!("expected timeout, actual: {:?}", other) + } +} diff --git /dev/null b/tests/server.rs new file mode 100644 --- /dev/null +++ b/tests/server.rs @@ -0,0 +1,379 @@ +#![deny(warnings)] +extern crate hyper; + +use std::net::{TcpStream, SocketAddr}; +use std::io::{self, Read, Write}; +use std::sync::mpsc; +use std::time::Duration; + +use hyper::{Next, Encoder, Decoder}; +use hyper::net::HttpStream; +use hyper::server::{Server, Handler, Request, Response}; + +struct Serve { + listening: Option<hyper::server::Listening>, + msg_rx: mpsc::Receiver<Msg>, + reply_tx: mpsc::Sender<Reply>, +} + +impl Serve { + fn addr(&self) -> &SocketAddr { + self.listening.as_ref().unwrap().addr() + } + + /* + fn head(&self) -> Request { + unimplemented!() + } + */ + + fn body(&self) -> Vec<u8> { + let mut buf = vec![]; + while let Ok(Msg::Chunk(msg)) = self.msg_rx.try_recv() { + buf.extend(&msg); + } + buf + } + + fn reply(&self) -> ReplyBuilder { + ReplyBuilder { + tx: &self.reply_tx + } + } +} + +struct ReplyBuilder<'a> { + tx: &'a mpsc::Sender<Reply>, +} + +impl<'a> ReplyBuilder<'a> { + fn status(self, status: hyper::StatusCode) -> Self { + self.tx.send(Reply::Status(status)).unwrap(); + self + } + + fn header<H: hyper::header::Header>(self, header: H) -> Self { + let mut headers = hyper::Headers::new(); + headers.set(header); + self.tx.send(Reply::Headers(headers)).unwrap(); + self + } + + fn body<T: AsRef<[u8]>>(self, body: T) { + self.tx.send(Reply::Body(body.as_ref().into())).unwrap(); + } +} + +impl Drop for Serve { + fn drop(&mut self) { + self.listening.take().unwrap().close(); + } +} + +struct TestHandler { + tx: mpsc::Sender<Msg>, + rx: mpsc::Receiver<Reply>, + peeked: Option<Vec<u8>>, + timeout: Option<Duration>, +} + +enum Reply { + Status(hyper::StatusCode), + Headers(hyper::Headers), + Body(Vec<u8>), +} + +enum Msg { + //Head(Request), + Chunk(Vec<u8>), +} + +impl TestHandler { + fn next(&self, next: Next) -> Next { + if let Some(dur) = self.timeout { + next.timeout(dur) + } else { + next + } + } +} + +impl Handler<HttpStream> for TestHandler { + fn on_request(&mut self, _req: Request) -> Next { + //self.tx.send(Msg::Head(req)).unwrap(); + self.next(Next::read()) + } + + fn on_request_readable(&mut self, decoder: &mut Decoder<HttpStream>) -> Next { + let mut vec = vec![0; 1024]; + match decoder.read(&mut vec) { + Ok(0) => { + self.next(Next::write()) + } + Ok(n) => { + vec.truncate(n); + self.tx.send(Msg::Chunk(vec)).unwrap(); + self.next(Next::read()) + } + Err(e) => match e.kind() { + io::ErrorKind::WouldBlock => self.next(Next::read()), + _ => panic!("test error: {}", e) + } + } + } + + fn on_response(&mut self, res: &mut Response) -> Next { + loop { + match self.rx.try_recv() { + Ok(Reply::Status(s)) => { + res.set_status(s); + }, + Ok(Reply::Headers(headers)) => { + use std::iter::Extend; + res.headers_mut().extend(headers.iter()); + }, + Ok(Reply::Body(body)) => { + self.peeked = Some(body); + }, + Err(..) => { + return if self.peeked.is_some() { + self.next(Next::write()) + } else { + self.next(Next::end()) + }; + }, + } + } + + } + + fn on_response_writable(&mut self, encoder: &mut Encoder<HttpStream>) -> Next { + match self.peeked { + Some(ref body) => { + encoder.write(body).unwrap(); + self.next(Next::end()) + }, + None => self.next(Next::end()) + } + } +} + +fn serve() -> Serve { + serve_with_timeout(None) +} + +fn serve_with_timeout(dur: Option<Duration>) -> Serve { + use std::thread; + + let (msg_tx, msg_rx) = mpsc::channel(); + let (reply_tx, reply_rx) = mpsc::channel(); + let mut reply_rx = Some(reply_rx); + let (listening, server) = Server::http(&"127.0.0.1:0".parse().unwrap()).unwrap() + .handle(move |_| TestHandler { + tx: msg_tx.clone(), + timeout: dur, + rx: reply_rx.take().unwrap(), + peeked: None, + }).unwrap(); + + + let thread_name = format!("test-server-{}: {:?}", listening.addr(), dur); + thread::Builder::new().name(thread_name).spawn(move || { + server.run(); + }).unwrap(); + + Serve { + listening: Some(listening), + msg_rx: msg_rx, + reply_tx: reply_tx, + } +} + +#[test] +fn server_get_should_ignore_body() { + let server = serve(); + + let mut req = TcpStream::connect(server.addr()).unwrap(); + req.write_all(b"\ + GET / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + \r\n\ + I shouldn't be read.\r\n\ + ").unwrap(); + req.read(&mut [0; 256]).unwrap(); + + assert_eq!(server.body(), b""); +} + +#[test] +fn server_get_with_body() { + let server = serve(); + let mut req = TcpStream::connect(server.addr()).unwrap(); + req.write_all(b"\ + GET / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Content-Length: 19\r\n\ + \r\n\ + I'm a good request.\r\n\ + ").unwrap(); + req.read(&mut [0; 256]).unwrap(); + + // note: doesnt include trailing \r\n, cause Content-Length wasn't 21 + assert_eq!(server.body(), b"I'm a good request."); +} + +#[test] +fn server_get_fixed_response() { + let foo_bar = b"foo bar baz"; + let server = serve(); + server.reply() + .status(hyper::Ok) + .header(hyper::header::ContentLength(foo_bar.len() as u64)) + .body(foo_bar); + let mut req = TcpStream::connect(server.addr()).unwrap(); + req.write_all(b"\ + GET / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Connection: close\r\n + \r\n\ + ").unwrap(); + let mut body = String::new(); + req.read_to_string(&mut body).unwrap(); + let n = body.find("\r\n\r\n").unwrap() + 4; + + assert_eq!(&body[n..], "foo bar baz"); +} + +#[test] +fn server_get_chunked_response() { + let foo_bar = b"foo bar baz"; + let server = serve(); + server.reply() + .status(hyper::Ok) + .header(hyper::header::TransferEncoding::chunked()) + .body(foo_bar); + let mut req = TcpStream::connect(server.addr()).unwrap(); + req.write_all(b"\ + GET / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Connection: close\r\n + \r\n\ + ").unwrap(); + let mut body = String::new(); + req.read_to_string(&mut body).unwrap(); + let n = body.find("\r\n\r\n").unwrap() + 4; + + assert_eq!(&body[n..], "B\r\nfoo bar baz\r\n0\r\n\r\n"); +} + +#[test] +fn server_post_with_chunked_body() { + let server = serve(); + let mut req = TcpStream::connect(server.addr()).unwrap(); + req.write_all(b"\ + POST / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Transfer-Encoding: chunked\r\n\ + \r\n\ + 1\r\n\ + q\r\n\ + 2\r\n\ + we\r\n\ + 2\r\n\ + rt\r\n\ + 0\r\n\ + \r\n + ").unwrap(); + req.read(&mut [0; 256]).unwrap(); + + assert_eq!(server.body(), b"qwert"); +} + +/* +#[test] +fn server_empty_response() { + let server = serve(); + server.reply() + .status(hyper::Ok); + let mut req = TcpStream::connect(server.addr()).unwrap(); + req.write_all(b"\ + GET / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Connection: close\r\n + \r\n\ + ").unwrap(); + + let mut response = String::new(); + req.read_to_string(&mut response).unwrap(); + + assert_eq!(response, "foo"); + assert!(!response.contains("Transfer-Encoding: chunked\r\n")); + + let mut lines = response.lines(); + assert_eq!(lines.next(), Some("HTTP/1.1 200 OK")); + + let mut lines = lines.skip_while(|line| !line.is_empty()); + assert_eq!(lines.next(), Some("")); + assert_eq!(lines.next(), None); +} +*/ + +#[test] +fn server_empty_response_chunked() { + let server = serve(); + server.reply() + .status(hyper::Ok) + .body(""); + let mut req = TcpStream::connect(server.addr()).unwrap(); + req.write_all(b"\ + GET / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Connection: close\r\n + \r\n\ + ").unwrap(); + + let mut response = String::new(); + req.read_to_string(&mut response).unwrap(); + + assert!(response.contains("Transfer-Encoding: chunked\r\n")); + + let mut lines = response.lines(); + assert_eq!(lines.next(), Some("HTTP/1.1 200 OK")); + + let mut lines = lines.skip_while(|line| !line.is_empty()); + assert_eq!(lines.next(), Some("")); + // 0\r\n\r\n + assert_eq!(lines.next(), Some("0")); + assert_eq!(lines.next(), Some("")); + assert_eq!(lines.next(), None); +} + +#[test] +fn server_empty_response_chunked_without_calling_write() { + let server = serve(); + server.reply() + .status(hyper::Ok) + .header(hyper::header::TransferEncoding::chunked()); + let mut req = TcpStream::connect(server.addr()).unwrap(); + req.write_all(b"\ + GET / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Connection: close\r\n + \r\n\ + ").unwrap(); + + let mut response = String::new(); + req.read_to_string(&mut response).unwrap(); + + assert!(response.contains("Transfer-Encoding: chunked\r\n")); + + let mut lines = response.lines(); + assert_eq!(lines.next(), Some("HTTP/1.1 200 OK")); + + let mut lines = lines.skip_while(|line| !line.is_empty()); + assert_eq!(lines.next(), Some("")); + // 0\r\n\r\n + assert_eq!(lines.next(), Some("0")); + assert_eq!(lines.next(), Some("")); + assert_eq!(lines.next(), None); +}
Non-blocking/Evented I/O Hyper would be far more powerful of a client & server if it was based on traditional event-oriented I/O, single-threaded or multi-threaded. You should look into https://github.com/carllerche/mio or a wrapper around libuv or something of that sort. Another option is to split hyper up into multiple crates, and refactor the client & server to abstract the HTTP protocol handling (reading & writing requests/responses onto a Stream) so that someone can use the client and/or server logic on top of their own sockets/streams that are polled in an event loop. Think, libcurl's multi interface + libuv's uv_poll_t.
We agree. We're actively looking into it. Mio looks promising. We also need a Windows library, and a wrapper combining the two. On Tue, Mar 24, 2015, 6:06 AM Jarred Nicholls notifications@github.com wrote: > Hyper would be far more powerful of a client & server if it was based on > traditional event-oriented I/O, single-threaded or multi-threaded. You > should look into https://github.com/carllerche/mio or a wrapper around > libuv or something of that sort. > > — > Reply to this email directly or view it on GitHub > https://github.com/hyperium/hyper/issues/395. Do you already have a vision how to embed mio into hyper? I'm very interested in async client and have enough time to contribute some code. I don't have a vision; I haven't looked that hard into how mio works. I'd love to hear suggestions. mio will be adding Windows support in the near future, so depending upon it should be a safe bet. The API surface of hyper's server will not have to change much if at all, but the client will need an async interface, either in the form of closure callbacks, a trait handler, something like a Future or Promise return value, etc. +1 for prioritizing a trait handler. Futures have some amount of overhead, and closure callbacks have even more overhead and can lead to callback hell. If the goal is maximum performance, an async handler interface would be a natural starting point. Yeah honestly a trait handler with monomorphization/static dispatch is the only way to go. +1 for the async handler Trait http://hermanradtke.com/2015/07/12/my-basic-understanding-of-mio-and-async-io.html awesome introduction to mio This is very much premature, but figured any activity to this thread is a positive! I have been playing around with what it would look like to write an asynchronous hyper client. here it goes: https://github.com/talevy/tengas. this has many things hardcoded, and is not "usable" by any means. Currently it does just enough to get an event loop going and allows to do basic `GET` requests and handle the response within a callback function. I tried to re-use as many components of hyper as possible. Seems to work! I had to re-implement HttpStream to use `mio`'s TcpStream instead of the standard one. I plan on making this more generic and slowly match the original hyper client capabilities. Any feedback is welcome! Code is a slight mess because it is the first pass at this to make it work. I've been investigating mio support, and fitting it in was actually pretty simple (in a branch). I may continue the branch and include the support with a cargo feature flag, but I can't switch over completely until Windows support exists. A feature flag makes great sense in this case then. There are plenty of people who would be able to take advantage of hyper + mio on *nix systems; probably the vast majority of hyper users in fact. On Sun, Jul 26, 2015 at 5:22 PM, Sean McArthur notifications@github.com wrote: > I've been investigating mio support, and fitting it in was actually pretty > simple (in a branch). I may continue the branch and include the support > with a cargo feature flag, but I can't switch over completely until Windows > support exists. > > — > Reply to this email directly or view it on GitHub > https://github.com/hyperium/hyper/issues/395#issuecomment-125041688. Servo would be super interested in hyper + mio to reduce the thread bloat :) hyper + mio looks very promising =) :+1: I would assume there would be some number of threads with event loops handling http requests rather than one thread with one event loop? @seanmonstar is this branch public somewhere? Not yet. It doesn't use an event loop yet, I simply switched out usage of std::net with mio::tcp. Which works fine for small requests that don't block... On Mon, Jul 27, 2015, 8:56 AM Tal Levy notifications@github.com wrote: > @seanmonstar https://github.com/seanmonstar is this branch public > somewhere? > > — > Reply to this email directly or view it on GitHub > https://github.com/hyperium/hyper/issues/395#issuecomment-125253301. If hyper can add that feature I'd basically consider it usable for myself in production, otherwise it would probably cause a great deal of thread context switching for my use case (lots and lots and lots of short lived connections) By my own benchmarks with lots of http connections, rust will be fastest way, if it will have async io: <image src="https://s3.amazonaws.com/f.cl.ly/items/0T201o0S3l2F3e1I3f1x/%D0%A1%D0%BD%D0%B8%D0%BC%D0%BE%D0%BA%20%D1%8D%D0%BA%D1%80%D0%B0%D0%BD%D0%B0%202015-08-06%20%D0%B2%2012.32.56.png"/> It is interesting how stable express, vanilla, and spray are in terms of response times over time. I'm surprised nickel and iron are not equally as stable; interestingly enough they both have the same shape, so my guess is it's identical behavior on their primary dependency: hyper :) On Thu, Aug 6, 2015 at 5:33 AM, Sergey Kamardin notifications@github.com wrote: > By my own benchmarks with lots of http connections, rust will be fastest > way, if it will have async io: > > https://camo.githubusercontent.com/698a9884f2e7734d4fd27b8af45a4b79ef06c3bd/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f662e636c2e6c792f6974656d732f30543230316f3053336c324633653149336631782f254430254131254430254244254430254238254430254243254430254245254430254241253230254431253844254430254241254431253830254430254230254430254244254430254230253230323031352d30382d303625323025443025423225323031322e33322e35362e706e67 > > — > Reply to this email directly or view it on GitHub > https://github.com/hyperium/hyper/issues/395#issuecomment-128308700. @jnicholls fair enough :beers: @seanmonstar > I don't have a vision; I haven't looked that hard into how mio works. I'd love to hear suggestions. I have a vision. In short it boils down to splitting hyper into three logical parts: 1. Types (Headers, Status, Version..., may be some generic version of Request) 2. Logic. For example the function determining what HTTPReader is used, should be decoupled from real streams. I.e. there should be enum like HTTPReaderKind which then is turned into current HTTPReader with a simple method like `kind.with_stream(stream)` 3. And code handling real streams, with convenience Request objects implementing Read, buffering an so on. The first item is basically ok, except maybe put types into separate crates. But logic is too coupled with streams. Decoupling it should also simplify testing AFAIU. Then we can do competing experimental asychronous I/O implementations without rewriting too much of hyper. (I will publish my implementation soon). The biggest question on mio right now is how to make things composable. I.e. you can't mix multiple applications in same async loop, until some better abstractions are implemented, so I'm currently experimenting with it. How does this sound? What I need to start contributing these changes into hyper? I agree that hyper should decouple the logic of composing and parsing HTTP requests/responses from the actual I/O. This is what I alluded to in my original request. Such a change would make it possible to run any kind of I/O model (in-memory, blocking I/O, non-blocking I/O, etc.) and any sub-variants thereof (unix readiness model, windows callback/IOCP model) with any stack that a user would prefer to use (mio, curl multi-interface + libuv, etc.) That's a lot of freedom offered by simply splitting up the composition and parsing logic from the I/O logic. I agree with Paul. On Fri, Aug 7, 2015 at 8:14 PM, Paul Colomiets notifications@github.com wrote: > @seanmonstar https://github.com/seanmonstar > > I don't have a vision; I haven't looked that hard into how mio works. I'd > love to hear suggestions. > > I have a vision. In short it boils down to splitting hyper into three > logical parts: > 1. Types (Headers, Status, Version..., may be some generic version of > Request) > 2. Logic. For example the function determining what HTTPReader is used, > should be decoupled from real streams. I.e. there should be enum like > HTTPReaderKind which then is turned into current HTTPReader with a simple > method like kind.with_stream(stream) > 3. And code handling real streams, with convenience Request objects > implementing Read, buffering an so on. > > The first item is basically ok, except maybe put types into separate > crates. But logic is too coupled with streams. Decoupling it should also > simplify testing AFAIU. > > Then we can do competing experimental asychronous I/O implementations > without rewriting too much of hyper. (I will publish my implementation > soon). The biggest question on mio right now is how to make things > composable. I.e. you can't mix multiple applications in same async loop, > until some better abstractions are implemented, so I'm currently > experimenting with it. > > How does this sound? What I need to start contributing these changes into > hyper? > > — > Reply to this email directly or view it on GitHub > https://github.com/hyperium/hyper/issues/395#issuecomment-128866149. That actually sounds quite feasible. I'll think more on the relationship between the 2nd and 3rd crates. But the first crate sounds simple enough: method, uri, status, version, and headers. Need a proper name, and to figure out the least annoying way to publish multiple crates at a time. If you do separate crates instead of modules, I would group #1 and #2 into a crate, and #3 in a separate crate (http_proto & hyper, for example, where hyper is the actual client/server I/O logic). node.js put their http_parse into a separate project from the node.js project in a similar fashion. On Saturday, August 8, 2015, Sean McArthur notifications@github.com wrote: > That actually sounds quite feasible. I'll think more on the relationship > between the 2nd and 3rd crates. But the first crate sounds simple enough: > method, uri, status, and headers. Need a proper name, and to figure out the > least annoying way to publish multiple crates at a time. > > — > Reply to this email directly or view it on GitHub > https://github.com/hyperium/hyper/issues/395#issuecomment-129058122. ## Sent from Gmail Mobile Okay, I've just put some code of async HTTP handling online: https://github.com/tailhook/rotor-http It's not generally usable, just put here to encourage you to split the hyper. It uses Headers from hyper. And I would probably better help to refactor hyper rather than rewriting whole logic myself. The "http_proto" name is probably good for crate that contains types and abstract HTTP protocol logic (like determining length of request body). I'd like to push a branch up with a `mio` feature. To start, I think hyper should be agnostic to what sort of IO abstraction is used, whether it's with callbacks, promises, streams, or whatever. To do that, I imagine this list is what I need to implement (still reading mio docs, so help would be appreciated): - `Evented` for `server::{Request, Response, Server}` - `Evented` for `client::{Request, Response}` - `trait NetworkStream: Evented (+ others) {}` --- Hyper does do some reading and writing uncontrolled by the user, such as parsing the a request head, before handing it to `server::Handler`. So perhaps internally hyper will need to pick a way to handle async reads/writes. To be truly agnostic, we'd need to move the request head parsing logic into the public API, and have those reads only execute when the user asks for them. Otherwise, the user won't be able to use whatever event notification mechanism they want. Also, @seanmonstar I have some experience with mio, so if you have questions please ask. I second @reem opinion. You can't just implement Evented, it will not work. Also it's expected that there will be IOCP-based library for windows that has very different interface than mio. The secondary issue is ensuring that we don't do things like: ``` rust let buf = get_buf(); try!(req.read(&mut buf)); // process part of buf but don't save progress anywhere outside this call try!(req.read(&mut buf)); // could yield wouldblock, and we would lose the info from the first read ``` The adventurous can try out the [mio branch](https://github.com/hyperium/hyper/tree/mio). The 2 server examples work, but a ton is missing. Also, just to get things moving, I chose to use eventual to provide the asynchronous patterns. Missing: - Keep alive - timeouts - the entire Client Cool stuff! I may feel adventurous enough to try this in a branch of Rustful. :smile: I have really been looking forwards to this, so I would be happy to give it a spin. By the way, I see that mio still doesn't seem to support Windows. Can Hyper still support Windows, without mio doing it? @Ogeon no, but alexcrichton has been working on windows support in mio, so it's coming. https://github.com/carllerche/mio/commits/master?author=alexcrichton That's great! I'll probably not be able to stop myself from trying this within the coming days... I'll be in touch if I bump into any problems. @Ogeon I'm sure you will (bump into problems). :) @seanmonstar, few questions: 1. From quick skimming, it looks like you made the mio-only version, rather than making mio support optional, right? Is it generally accepted strategy? 2. Quick benchmarking of hello.rs shows that it's much slower (<1k against 40K sync version), whereas my version and coroutine-based version does same order of magnitude requests per second. Any ideas? @tailhook 1. The strategies of using blocking io and an event loop are quite different, and so supported both is complicated. It's a whole lot easier to implement a sync API using the event loop, by just blocking on the `Future`. Also, I'm currently just trying to get it _working_, and worrying about the rest after. 2. How are you benchmarking? Also, so far, this version of the Server is only using 1 thread, whereas the Server in 0.6 uses threads that scale to your cores. Using more threads (and more event loops) could probably help. However, my super simple `ab` checking hasn't showed such a slow down (though my test machine has 1 core, so it doesn't use multiple threads in the sync version). Update: current mio branch no longer using futures, and seeing a significant performance improvement. My linux box has horrible specs, so I won't post benchmarks from it. I see an error when compiling the latest mio branch with rustc 1.3 ``` ~/s/hyper git:mio ❯❯❯ git rev-parse HEAD c60cc831269d023b77f0013e6c919dbfefaf031d ~/s/hyper git:mio ❯❯❯ cargo build Compiling hyper v0.7.0-mio (file:///home/tburdick/src/hyper) src/http/conn.rs:6:21: 6:23 error: expected `,`, found `as` src/http/conn.rs:6 use http::h1::{self as http, Incoming, TryParse}; ^~ Could not compile `hyper`. To learn more, run the command again with --verbose. ~/s/hyper git:mio ❯❯❯ ``` Ah, woops. I've been doing all this work on nightly, and that syntax is allowed on nightly, but not stable yet. I'll try to push soon such that it builds on stable. > Update: current mio branch no longer using futures, and seeing a significant performance improvement. My linux box has horrible specs, so I won't post benchmarks from it. I can confirm that benchmarks are fine now. I'm curious why the difference is so drastic without futures? Is it because of inlining, or because of the different structure of the code? Is it just overhead of lambdas? By the way code looks super-similar to what I've [written about](https://medium.com/@paulcolomiets/asynchronous-io-in-rust-36b623e7b965) and [working on](https://github.com/tailhook/rotor-http). And it would be nice to join the effort. So have you seen that? Does you see any inherent flaws in what I'm doing? Or does the absence of documentation is the main cause that stopped you from using my library? @tailhook > I'm curious why the difference is so drastic without futures? Is it because of inlining, or because of the different structure of the code? Is it just overhead of lambdas? I never profiled, so I can't say for certain. Some things I can guess about: `eventual::Future` has to store the callbacks as `Box<Fn>` internally, which means allocations (likely tiny), and dynamic dispatch (likely medium). Additionally, the core of the `Future` uses atomics to keep it in sync, which makes sense, but just wasn't necessary in the event loop, where it was all on a single thread. This isn't to say Futures are bad, just that they aren't a cost-free abstraction, and the abstraction wasn't worth the cost in this case. I'm still considering exposing higher-level methods on `Request` and `Response` that use a Future, such as `req.read(1024).and_then(|bytes| { ... })`, which would have the Future tying into the events in the event loop. > By the way code looks super-similar to what I've written about and working on. And it would be nice to join the effort. So have you seen that? Does you see any inherent flaws in what I'm doing? Or does the absence of documentation is the main cause that stopped you from using my library? My main inspiration when writing the `tick` crate was [Python's asyncio](https://docs.python.org/3/library/asyncio.html). I did see that rotor seemed to in a similar vein, but I wrote `tick` for these reasons: - This branch has been all about fast prototypes to test ideas, and so I wanted to be able to tweak the event loop design as needed. - I wanted the ability to pause transports, which I see is a `TODO` in greedy_stream :) - The amount of generics I saw trying to read rotor's source left me often confused. I'm sure our efforts could be combined in this area. My main reason here was to be able to prototype while understanding what's going on internally, instead of needing to ask on IRC. > I wanted the ability to pause transports, which I see is a TODO in greedy_stream :) Yes. It was done to keep the scope of the protocol smaller for quick experiments. Easy to fix. I need to get messaging between unrelated connections right; then I will make a non-greedy stream that is pausable and has an idle timeout. > The amount of generics I saw trying to read rotor's source left me often confused. Well, yes, I'm trying to build a library that allows you to combine multiple independent things to create an app (One of the things will be an HTTP library). So the problem is not an easy one, and require some amount of generics. But it's not that much in _user_ code. I'm also looking forward to moving some of the generics to associated types, to make code simpler. > I'm sure our efforts could be combined in this area. My main reason here was to be able to prototype while understanding what's going on internally, instead of needing to ask on IRC. Yes, that sounds reasonable. Let me know if I could be of any help. @seanmonstar I've also been following how the `mio` branch has been unfolding and thinking about how it interacts with supporting HTTP/2, as well. From the aspect of HTTP/2 support, the new approach in `tick` is definitely better than the previous future-based one. It boils down to the fact that now it is more or less explicit that a single event loop owns the connection and that all events on a single connection (be it writes or reads) will, therefore, be necessarily serialized (as opposed to concurrent). --- I would like to throw in just a remark on something that would need to be supported in some way by any async IO implementation that we end up going with here if it is to also back HTTP/2 connections efficiently. Something that seems to be missing in both `tick`, as well as `rotor`, is the option to send messages to the protocol/event machine. For example, in HTTP/2 we would like to be able to issue new requests on existing connections. This is, after all, one of the main selling points of HTTP/2! In order for a new request to be issued, we require unique access to the state of the connection. This is because issuing a new request always needs to update the state (as well as read it). Examples are deciding on the new stream's ID (and updating the next available ID), possibly modifying the flow control windows... Therefore, issuing the request must execute on the same event loop and by the `Protocol`/`EventMachine`, as that is what effectively owns the connection state. Another example would be sending request body/data. This cannot be simply written out directly onto the socket like in the case of HTTP/1.1 for multiple reasons (flow control, framing, priority, etc.), all of which come down to the fact that writing a data chunk requires unique/mutable access to the state. Thus, each request should notify the protocol (which owns the HTTP/2 connection) that it has data to be written and then the protocol itself should decide when exactly to perform the write onto the underlying async socket... This actually goes for writing out responses on the server side, as well, since from HTTP/2's point of view, the difference is quite negligible (both are considered outbound streams). Basically, the `AsyncWriter` that is there currently is insufficient to support HTTP/2. As far as I can tell, the best way to do this would be to be able to dispatch a protocol-specific message onto the event loop, which when received and processed by the loop ends up notifying the `Protocol` (and passing the message onto it). The type of the message would ideally be an associated type of the `Protocol` to allow for different protocols having different custom-defined messages. Of course, there might be a different way to achieve this, but for now I can't see what would be more efficient, given that there are operations in HTTP/2 which necessarily need unique/mutable access to the connection state, which would be owned by the event loop... I made a minimal prototype of this, just to verify that it would work, as well as to see what kind of changes would be required in `solicit` [1]. I don't want to get too involved in the exact specifics of the async IO implementation that we end up going with here (avoid the whole "too many cooks..." situation), but it'd be good if these requirements could be considered already to minimize any churn or duplication required to also support HTTP/2. [1] It out turns that by only adding a couple of helper methods it all works out quite nicely already, given that `solicit` was not coupled to any concrete IO implementation. I'll put in the work to adapt the part in `hyper` once the async IO approach is closer to being decided on and finalized... > As far as I can tell, the best way to do this would be to be able to dispatch a protocol-specific message onto the event loop, which when received and processed by the loop ends up notifying the Protocol (and passing the message onto it). Yes. All the same issues with websockets. This is a thing that I'm going to support in `rotor` because the library is basically useless without the functionality (I. e. you can't implement a proxy). As I've said, it's my next priority. However, flow control may be done another way. You could just have a `Vec<Handler>` and/or `Vec<OutputStream>` in connection state. So readiness handler can supply data chunk to any handler and can choose the stream to send data from for writing. It's easy to group state machines in `rotor` as long as they all share the same connection (and same thread of execution). I'd like to just note that having a way for direct, 2-way communication along the callback chain is very important for efficiency reasons. The additional overhead of enqueueing events in the event loop rather than executing them directly on a parent has been a performance bottleneck in the past for async webserver code I've written in C++. Unfortunately, I haven't yet seen a way to do this safely in Rust. On Wed, Sep 23, 2015 at 11:09 AM, Paul Colomiets notifications@github.com wrote: > As far as I can tell, the best way to do this would be to be able to > dispatch a protocol-specific message onto the event loop, which when > received and processed by the loop ends up notifying the Protocol (and > passing the message onto it). > > Yes. All the same issues with websockets. This is a thing that I'm going > to support in rotor because the library is basically useless without the > functionality (I. e. you can't implement a proxy). As I've said, it's my > next priority. > > However, flow control may be done another way. You could just have a > Vec<Handler> and/or Vec<OutputStream> in connection state. So readiness > handler can supply data chunk to any handler and can choose the stream to > send data from for writing. It's easy to group state machines in rotor as > long as they all share the same connection (and same thread of execution). > > — > Reply to this email directly or view it on GitHub > https://github.com/hyperium/hyper/issues/395#issuecomment-142683795. @dcsommer > I'd like to just note that having a way for direct, 2-way communication > along the callback chain is very important for efficiency reasons. > [ .. snip .. ] > Unfortunately, I haven't yet seen a way to do this safely in Rust. If I understand you right, then there is a way in `rotor`. In [the article](https://medium.com/@paulcolomiets/asynchronous-io-in-rust-36b623e7b965) there are are two cases of communication: 1. From parent to child, you just pass value as an argument to callback 2. From child to parent either you return a value (like in `body_finished` callback), or a `Option<State>` like in almost every other example there (the latter is a form of communication too). But in fact you may return a tuple if you need two things: ``` struct StreamSettings { pause_stream: bool } trait RequestHandler { fn process_request(self) -> (StreamSettings, Option<Self>); } ``` Or you might pass a mutable object: ``` trait RequestHandler { fn process_request(self, s: &mut StreamSettings) -> Option<Self>; } ``` (the latter is used for `Transport` object in `rotor`) @tailhook yeah, I read the article. It was really good, and I'm excited to see people take async IO seriously in Rust. My issue with point 2 is for the case where you aren't yet ready to perform a state transition. How can the child inform the parent of state transitions that don't originate with a call from the parent? For instance, what if your request handler has to perform some async operation to calculate the response? @dcsommer, basically the parent need to be prepared for the situation. And it's communicated either by return value (i.e. turn `Some/None` into `NewState/Wait/Stop`) or by `transport.pause()`. Which way to choose depends on which layer this is (or, in other words, is the `transport` passed down here or is it hidden in the layers below). I'll put an example in `rotor` soon. Overall, I feel it's a little bit offtopic here. Feel free to open an issue in `rotor` itself. @tailhook actually, I think there could be some performance gains if some reading and writing directly to the stream could be overridden. (From tick's perspective). ``` rust trait On<T: Read + Write> { fn on_readable(&mut self, socket: &mut T) -> io::Result<bool>; fn on_writable(&mut self, socket: &mut T) -> io::Result<()>; } ``` I know in hyper, implementing this instead of `Protocol::on_data` would prevent a copy, since hyper still needs to parse the data as possibly chunked, and could skip the intermediary buffer that `Protocol` provides. Likewise when writing, since hyper may need to wrap the data in "chunks". The cool part about all this stuff, is that I believe it can be contained in the event loop and hyper's `http` module, without affecting user-facing API in `Request`/`Response`. It would just get faster. > @tailhook actually, I think there could be some performance gains if some reading and writing directly to the stream could be overridden I have few thoughts about that. It's not my top priority, but let me share some brain-dump: 1. I think that it's possible to have InfiniBand or userspace TCP stack buffers in Transport (by changing transport and event loop, but keeping Protocol same). But in your example it's not. (However, this thesis should be confirmed). 2. It's might be interesting to just move `chunked` encoding to lower layer, i.e. to transport itself. Just like we usually do that for encryption (which interacts with chunked encoding in some subtle ways too). 3. The write optimization is probably useless without `writev` (i.e. sending multiple buffers at once to the kernel space) I'm also only getting basics in `rotor`. So I'm trying to make protocol writer's life easier for now. For protocols that need last bits of performance, it's possible to "squash" two layers of abstraction. This is inherent to how `rotor` is designed. Any updates? I'm really looking forward to this! @yazaddaruvala, I've just published a [follow-up article](https://medium.com/@paulcolomiets/async-io-for-rust-part-ii-33b9a7274e67) and fundamental update to the rotor. I'm going to build few small applications with it and HTTP. Overall, it's not very solved problem in rust so it will take some time. On the other hand we haven't agreed on any kind of collaboration with hyper. So I'm not sure if we will duplicate the work. @tailhook great post, did it show up in HN and /r/rust already? @arthurprs, no not yet, according to Medium stats. @tailhook I'll help with the second one them. Also, I'm curious, what kind of performance do you get w/ Golang in the same machine? Quick update that mio 0.5 is out and supports windows. Yea! I'll be meeting with @carllerche tomorrow to discuss my WIP integration, and hope to have usable versions soon after. Can't wait! Looking forward to hearing more about your integration @seanmonstar. Hi, I have a quick status update: 1. Current master [rotor-http](https://github.com/tailhook/rotor-http) has most features of the HTTP implemented (server-side). Of course, they are largely untested, but it hope to make tests shortly. 2. It uses only `hyper::{version,status,method,header}` from hyper. It would be great if those tools be a separate library. 3. The [rotor](http://github.com/tailhook/rotor)-library itself is now super-small. It would be nice if we agree on the interface and start building apps that can co-exist in the same main loop. 4. Another article and more docs will be done soon. I just put it here in case anyone want's to take an early look. P.S.: I've noticed that `wrk` may behave very slow in case you're closing connection which should not be closed (e.g. has no `Connection: close` header). I've not rechecked but it may be the reason of slowness of the test in the branch of hyper that was based on eventual io. Sounds good! Are there plans for client side? I'd be interested to see what an evented model for outgoing requests will look like. @KodrAus there is an [example in rotor-stream](https://github.com/tailhook/rotor-stream/blob/master/examples/fetch.rs). The full implementation of HTTP client will eventually be in rotor-http too. But DNS resolver is a prerequisite. Awesome news! Speaking of benchmarks, what kind of numbers are you seeing compared to the current hyper master? @tailhook are you planning another article to sum up the whole thing now that you are happy with it? Interested in benchmark comparisons for hyper and rotor master branches as well @tailhook very cool! The rotor-http state machines look very similar to what I'm developing for hyper. One difference I have is giving direct read and write access to the underlying socket, since that's a requirement another use case has for eeking out as much control as possible. --- For hyper, I'd settled on an internal state machine, with callback-style Request and Response APIs to interact with it. You can see it in the current [mio branch](https://github.com/hyperium/hyper/tree/84f36250d9057d3f5280a78589c879858c3c325c). The `examples/hello.rs` fairs much better in benchmarks than master. However, on my machine, it was still performing at around 60% of my ideal target ([a super simple state machine that ignores https semantics](https://github.com/seanmonstar/tick/blob/master/examples/http.rs)). I want hyper to be a low level HTTP library for Rust. People shouldn't be skipping hyper because it's not fast enough. At a recent Mozilla work week, others expressed interest in building a reverse proxy that could actually compete with nginx. If hyper cannot help to do that, then someone will just have to re-implement HTTP all over again, but with less costs. This does mean the ergonomic API for Request and Response will have to become a little less ergonomic, but don't fret! I've prototyped similar APIs on top of this state machine approach, and it wasn't hard at all to do. Even blocking IO was quite simple to emulate, using threads and channels. Okay here is [the third article](https://medium.com/@paulcolomiets/async-io-in-rust-part-iii-cbfd10f17203), including some benchmark vs golang, nginx and hyper. Hopefully, it will answer some questions here. --- @seanmonstar > One difference I have is giving direct read and write access to the underlying socket, since that's a requirement another use case has for eeking out as much control as possible. Current rotor core library gives direct access to the socket. You can build on top of that. I'm not sure what is the reason because the performance of rotor-http that is build on top of rotor-stream (the latter does buffering and higher level abstractions, including hiding away the sockets) is decent. The benchmarks are in the article. Could you give some insight on a use case you are talking about? I'm looking forward to integrating `sendfile()` and memory mapped files with rotor-stream. But I think this use case is quite niche (although, it is probably required to compete with nginx) > However, on my machine, it was still performing at around 60% of my ideal target (a super simple state machine that ignores https semantics). Well, that script linked gives 600k requests per second on my laptop, comparing to 65k for nginx. I don't think it's much useful to compete with something that pushes lots of responses as fast as a connection is opened. Or do you say that you can get 60% of that performance on normal http request parsing? > At a recent Mozilla work week, others expressed interest in building a reverse proxy that could actually compete with nginx. Sure, writing a HTTP implementation that has competitive performance comparing with nginx is my goal too. > Even blocking IO was quite simple to emulate, using threads and channels. Well, I think it's possible to write blocking client implementation that wraps mio loop without threads and channels. And I doubt that blocking IO for servers is something useful. Although, offloading work to the thread pool is simple indeed. @tailhook > Current rotor core library gives direct access to the socket. Oh neat! I hadn't really noticed you split the code into rotor and rotor-stream. I'll have to take a look at the split. I had mostly looked through rotor-http when writing my last comment. > Could you give some insight on a use case you are talking about? Yep. The WebPush team at Mozilla has to run servers where every single instance of Firefox must keep an open socket to the Push server. They want to reduce cost, and are thinking Rust can help do that. They want as little memory usage as possible for every connection, so that means controlling every allocation, including buffers used to read and write. > Well, that script linked gives 600k requests per second on my laptop, comparing to 65k for nginx. Ha, well then I'm sure part of it is the terrible machine I'm running these benchmarks on. I'm using a small Linode VM with 1 core and 1GB of RAM. When running the Tick example, i get around 18,000 requests per second. The hello server in hyper's mio branch gets me around 12,000. I'd love to bench on my desktop with all its cores, but I use Windows, and wrk won't run on that... > I doubt that blocking IO for servers is something useful. I agree. Blocking servers is almost never useful. I've just seen people beg that the option still be there. And I meant also that it's not hard for a callback API, or Futures, or whatever to be built on top. > Yep. The WebPush team at Mozilla has to run servers where every single instance of Firefox must keep an open socket to the Push server. They want to reduce cost, and are thinking Rust can help do that. They want as little memory usage as possible for every connection, so that means controlling every allocation, including buffers used to read and write. Sure, keeping keep-alive connections with minimum overhead is my goal too. This is how netbuf (the buffer object that rotor-stream uses) is designed: it deallocates the buffer when there are no bytes. This was doubtful trade-off. But it looks like okay in the bencharks. AFAICS in rotor-http there are no heap-allocated stuff per state machine, except buffers. The size of state machine in hello-world is 288 bytes which is probably not the smallest possible (you may probably get as small as 8 or 16 bytes), but is perhaps less than most current servers have. You also have an overhead of Slab and timer slab, and probably larger message queue, all of that are currently fixed-size in mio. Anyway according to quick test a hello world example configured for 1M connections takes about 350M RSS (379M of virtual memory, in case you doubt that something is non-initialized yet). I haven't done real connections, though. I believe there is much more overhead in the kernel space. Thanks for the rough benchmark numbers. If I understand correctly, the requests carry out synchronous workloads, i.e. they don't yield back to the event queue. I would love to see a benchmark where each request 'sleeps' for some amount of time (1 or 10ms, mocking a network request) and only then sends its response. No hurry though, just curious :) @alubbe You can sorta do this by making flamegraphs: - http://carol-nichols.com/2015/12/09/rust-profiling-on-osx-cpu-time/ - http://www.brendangregg.com/flamegraphs.html @seanmonstar any ideas about schedule for this feature? Would love to know which pieces are still missing and if there are any opportunities to contribute. Thanks! @tailhook Could you please also benchmark against [Facebook's Proxygen](https://github.com/facebook/proxygen)? [Here](https://gist.github.com/seanmonstar/a08d0bd6d25ad4251915) is the current `hello.rs` and `server.rs` examples in the wip branch. It doesn't look as elegeant as a blocking, synchronous API, but it does give the performance. On my terrible build server, a wrk bench shows ~9% more requests per second than the branch using callbacks. And again, it's possible to build higher level APIs on top of this. This just gives the performance to those who need it. Awesome stuff. It looks like what you'd expect working with mio at a lower level to me. Do you have plans for an evented client sample? > This just gives the performance to those who need it. Most of people and organisations who want to move to Rust-lang have only one goal - improve the performance :) I've (force) pushed to the mio branch, which has the server examples working. I've also been following rotor's development, and feel like it and my current branch are at a point that I could switch out the internal use of 'tick' to 'rotor', with basically no change to the exposed API. This would just reduce duplicate effort in state machine development. Thanks for the update, I was able to get the examples to work. One of the things I noticed was that server cannot utilize more than one cpu core now. I assume this is because of mio. Are there any plans to build a master/cluster process on top to run multiple, isolated event queues for the new hyper? > my current branch are at a point that I could switch out the internal use of 'tick' to 'rotor', with basically no change to the exposed API. This would just reduce duplicate effort in state machine development. Great. Should I cut a new release of rotor? I mean do you have any outstanding questions/issues with API, so I can release all API changes in one bulk. > One of the things I noticed was that server cannot utilize more than one cpu core now. I assume this is because of mio. Are there any plans to build a master/cluster process on top to run multiple, isolated event queues for the new hyper? You can easily run multiple event loops, each in it's own thread. Here is an example in rotor: https://github.com/tailhook/rotor-http/blob/7a24c516e30cdb6773584f465d4a8cccd8435fdc/examples/threaded.rs#L132 That's not hyper, but I believe you can do the same with @seanmonstar's branch. That's pretty cool. So you would leave the implementation of how to distribute the load (e.g. round-robin) to the library consumer? > That's pretty cool. So you would leave the implementation of how to distribute the load (e.g. round-robin) to the library consumer? I'm not sure I understand question well. But you have several options for load distribution: 1. In the example OS distributes sockets somehow by letting each thread accept on it's own. It works well for tiny asynchronous tasks 2. Another option is to use SO_REUSEPORT in linux. AFAIU linux distributes connections equally (by a hash ring) between sockets (which are equal to threads in [the example](https://github.com/tailhook/rotor-http/blob/7a24c516e30cdb6773584f465d4a8cccd8435fdc/examples/threaded_reuse_port.rs#L140)) 3. For more complex processing you probably want to read the request in one of the IO threads which are distributed by option (1) or (2) and send job to worker threads which are running some [MPMC queue](http://aturon.github.io/crossbeam-doc/crossbeam/sync/struct.MsQueue.html) (just an example) @alubbe yes, hyper is probably going to stop guessing at how many threads to use, and instead let the user decide to run servers in as many threads as they'd like. I could add that to the `hello.rs` server example, I suppose. --- Swapping in rotor was actually pretty quick work (besides the time I've spent reading the source of rotor to understand it's concepts). As I said, it didn't change the Server api at all. One thing that I noticed, but it could be just my terrible test machine: the swap to rotor meant my benchmark lost ~1-2% in requests per second. Maybe a proper production machine wouldn't notice this. If it did, I imagine the difference is that perhaps some function didn't get inlined, or something else minor that I'm sure we can fix. If you wish to look yourself, you can compare the current `mio` branch with the current `mio-rotor` branch. @seanmonstar the common usage of a state machine framework like rotor is a nice touch Excited for the day I can put this to work! :beers: Okay, I've done some quick tests https://gist.github.com/tailhook/f1174e1a3e8b340d1e1f Shortly: - hyper-mio: 63450.68/63454.14/65230.27 - hyper-rotor: 66627.13/65829.25/67861.90 - rotor-http: 65600.74/66425.12/64309.17/69134.65 It's on i5-3230M CPU @ 2.60GHz / Linux 4.3.3, versions of the libraries are in gist The tests were run for each of the version once, then next round. Also I've discarded some outliers with much lower RPS (all examples generated 61-62k sometimes).At the end of the day, I would say that variablility of the value is more than the difference, and I'm not sure I've captured fastest samples. Anyway. it doesn't look like slower. May be I'll try to find some time to make non-laptop test (test on laptops are always wrong because of powersaving). In the meantime I've published rotor 0.5.0 on crates.io. > besides the time I've spent reading the source of rotor to understand it's concepts Any hints to start with? I know I need a lot more for documentation, but maybe some quick pointers. Like should I better make a tutorial or fill in more comprehensive coverage of API. Are standalone examples good enough? @lilianmoraru I've seen your request to test proxygen, but I can't find time to get it. It may help, if you create a vagga.yaml so it would be easy for me to test. @tailhook A state diagram to visualize the rotor API might be a good start. On earlier iterations of rotor, I had to draw out state diagrams to grok the API. Excellent. Like I said, it's probably that my test Linux box is complete junk. Well, I couldn't find the docs hosted, so I had to resort to the source. But, even with docs, I like reading source. I'm a weirdo who likes to pick modules from the rust repo for some good-night reading in bed. On Mon, Feb 1, 2016, 4:41 PM Alberto Leal notifications@github.com wrote: > @tailhook https://github.com/tailhook A state diagram to visualize the > rotor API might be a good start. On earlier iterations of rotor, I had to > draw out state diagrams to grok the API. > > — > Reply to this email directly or view it on GitHub > https://github.com/hyperium/hyper/issues/395#issuecomment-178274584. @tailhook Here is a "basic" configuration: [gist](https://gist.github.com/lilianmoraru/10cb8fd12b3f582f5d79). It compiles `proxygen` and `rotor` but the examples of course need to be modified because they do not do the same thing logic-wise. Thanks @lilianmoraru . So here is a test having a response with similar number of bytes (more details https://git.io/vgIpo): - rotor-http: 57k (requests per second) - proxygen: 28k From quick skimming it looks like proxygen accepts a connection by one thread and hands it off to another thread for processing (is it even async?), this explains why performance is 2x slower **on this microbenchmark** (i.e. 2 thread wake-ups instead of one). The proxygen compiled with default options, which includes `-O3` as far as I can see. Hey @seanmonstar, good read: http://seanmonstar.com/post/141495445652/async-hyper. Thanks for the update, and all the hard work! `Next::end()` covers the situation where the server wants to end the connection. However, one thing that isn't explicitly obvious is how the server handles a connection that gets closed prematurely from the client's side? Would this be handleable in `on_request_readable` during `match transport.read(...)`? or would(should) `Handler` need an `on_request_closed`? @yazaddaruvala there's 2 ways that may appear. If it occurs while waiting for readable or writable, then the event loop will notice. hyper will call `Handler::on_error(Error::Io(e))`. If the socket has already triggered a readable or writable event, and thus the handler is trying to read or write, then that will likely trigger an `io::Error` during `read` or `write`. Cool! Looks like it's time to give this another try. Just one question: Is there a reason for making the `Request` components private, besides preventing accidental changes? Are there any side effects from them being changed? I ask because this prevents me from repackaging them in the Rustful `Context` type without making references (which may prevent even more things), and it makes it makes it impossible to write pre-routing that actually modifies the request. I'm somewhat prepared to lessen the power of the pre-routing filters, since I'm not even sure how useful the are, but I'm still not much of a fan of doing it. The filters would then only be able to observe and abort. The request problem could be worked around by including it as it is, instead of splitting it, and maybe add accessors as shortcuts. The [host name+port injection](https://github.com/Ogeon/rustful/blob/68ab5972db2685229e1705163752530d895aace3/src/server/instance.rs#L190) would also have to change. I may have missed it by I don't think Hyper does this, and it's sometimes a useful header. It could, of course, live outside the `Request`, but that would be a bit awkward. All I would need is a way to destructure the `Request`, and it doesn't matter if it's a method. That worked fine for the previous version of `Response`. Second best would be mutable accessors, but that would somewhat defeat the purpose of keeping everything immutable. Anyway, nice to see that this is almost complete. :+1: @Ogeon there were no side effects to them being changed, I've just seen people in IRC make changes to the `Request` when they meant to change the `Response`, and were left confused why nothing happened. The change to making the fields private was to prevent people from doing things that did nothing. I'm surprised you need to inject the `Host` header into requests. HTTP/1.1 is pretty clear that clients [must include the Host header](https://tools.ietf.org/html/rfc7230#section-5.4). Perhaps a `deconstruct` method would be warranted, that would return a tuple of the internal fields. That should be clear that modifying it won't do anything, but still allow you to do so if you really want? @seanmonstar Yeah, I think the decision to make them immutable was a good idea from that perspective. A `deconstruct` method is all I need and it would be great if it was added. The critical part is the `Headers` struct, which may become expensive to clone. The URI is parsed, and is cloned at the same time, and the method should be cheap enough to clone in the most common situation. The best would be if I didn't have to clone anything. :smile: I have, by the way, started to port everything to the new system and it's working quite well, so far. I have just managed to make the main functionality work, and the simplest examples are compiling. The only thing I really haven't figured out a good solution for, at the moment, is file uploading. I'm not yet sure how to coordinate the file reading and sending in a good way that doesn't clog everything up. I'll probably figure something out after some sleep. > I'm surprised you need to inject the Host header into requests. HTTP/1.1 is pretty clear that clients must include the Host header. I should look into that again. I don't remember why I added that part (I rediscovered it when I wrote that comment), so it may actually be unnecessary. Does Hyper check that the `Host` header exist? Oh, and another quick question: What happens with the request body if the handler decides to return `Next::end()` before reading it? Will Hyper take care of it automatically? @Ogeon hyper does not check for the `Host` header. > What happens with the request body if the handler decides to return Next::end() before reading it? Will Hyper take care of it automatically? If the Handler ends, no more reading is done. (Reading only happens when the handle calls `decoder.read()` anyways). If there is still bytes waiting (determined by whether there was a Content-Length header, or if chunked, if there was a `0\r\n\r\n` sequence already read), then the socket will not be used for keep-alive. @seanmonstar Alright, so I take it that I have to read the body to make sure the socket is reused for keep-alive. That's good to know :+1: Thanks! It seems to me that this is the same behavior with the current (blocking), at least that's what I observed empirically: if your server handles a POST request but does not read it's body, the method field of the subsequent POST request is "body_of_previous_requestPOST". Not sure if this should be considered a bug or not, so I implemented Drop for my Request so it reads the body in case it has not been read before. I got the impression that it was done automatically in 0.8.x and earlier, but I may be wrong. It would be nice if the responsibilities of the handler were documented, to make it more clear what's automatic and what's not. I asked because some of the examples skips the body. @Ogeon hyper has not automatically read the body. The problem with that is what to do when someone POSTs a 4GB file to your server. If hyper were to automatically read the whole body, that'd block the server for a while, and waste bandwidth. Deciding on a proper maximum size to automatically read is difficult, so hyper has so far chosen that all reading must be done by the user. @seanmonstar Looks like I misunderstood it, then :smile: Probably a leftover assumption from rust-http, which used to include the body in the request. @seanmonstar I have bumped into a problem with zero sized response bodies. I don't know if it's intentional, but it seems like I have to call `encoder.write(...)` at least once for the response to be properly sent. It will otherwise result in "empty response" errors. Do you want me to file separate issues for things like this? Have you updated recently? I hit a similar error this morning, and fixed it (at least in my case), and pushed. On Sat, Mar 26, 2016, 12:51 PM Erik Hedvall notifications@github.com wrote: > @seanmonstar https://github.com/seanmonstar I have bumped into a > problem with zero sized response bodies. I don't know if it's intentional, > but it seems like I have to call encoder.write(...) at least once for the > response to be properly sent. It will otherwise result in "empty response" > errors. > > — > You are receiving this because you were mentioned. > > Reply to this email directly or view it on GitHub > https://github.com/hyperium/hyper/issues/395#issuecomment-201919390 I hadn't and did now. Part of problem is still there. The general state flow is as follows: 1. In `on_request` -> `Next::wait`, 2. immediately wake up and go into `write`, 3. in `on_response` -> `Next::write`, 4. do nothing in `on_response_writable`, since body length is 0, and -> `Next::end` Skipping step 4 and calling `Next::end` in 3 seems to work after the update. Calling `encoder.write` with an empty slice in 4 causes the headers to be sent and the returned value from `write` is `WouldBlock`. @Ogeon I believe I've not fixed this on the branch. Yeah, it's still there. Another thing I've noticed is that `wrk` reports read errors. I haven't done any deeper investigations into those, though, but I guess you have seen them as well. @Ogeon As I should have done, I've added a test in the server tests for that exact instance, and I can now say it is fixed. As for read errors, you mean errors printed by env_logger from hyper (that the socket closed?), or the read errors reported directly from wrk? The former, I've fixed (it was a useful error log when first working on the branch). The latter, I haven't seen in a long time. > @Ogeon As I should have done, I've added a test in the server tests for that exact instance, and I can now say it is fixed. Ah, nice! I can confirm that it works now. > As for read errors, you mean errors printed by env_logger from hyper (that the socket closed?), or the read errors reported directly from wrk? The former, I've fixed (it was a useful error log when first working on the branch). The latter, I haven't seen in a long time. It's directly reported from `wrk`. It can look like this for my `hello_world` example, after a run with 456888 requests: ``` text Socket errors: connect 0, read 456873, write 0, timeout 0 ``` It looks like it's not one for each request, so I'm not really sure what would trigger them. Could it be something I have missed, when implementing it? Hm, read errors from wrk are reported each time 'read(fd)' returns -1. Does that mean the sockets may be closing before having written the end of the response? I don't see this in the hello world server example in hyper. What response are you writing? Headers and body? On Thu, Mar 31, 2016, 3:54 AM Erik Hedvall notifications@github.com wrote: > @Ogeon https://github.com/Ogeon As I should have done, I've added a > test in the server tests for that exact instance, and I can now say it is > fixed. > > Ah, nice! I can confirm that it works now. > > As for read errors, you mean errors printed by env_logger from hyper (that > the socket closed?), or the read errors reported directly from wrk? The > former, I've fixed (it was a useful error log when first working on the > branch). The latter, I haven't seen in a long time. > > It's directly reported from wrk. It can look like this for my hello_world > example, after a run with 456888 requests: > > Socket errors: connect 0, read 456873, write 0, timeout 0 > > It looks like it's not one for each request, so I'm not really sure what > would trigger them. Could it be something I have missed, when? > > — > You are receiving this because you were mentioned. > > Reply to this email directly or view it on GitHub > https://github.com/hyperium/hyper/issues/395#issuecomment-203876959 It's the [hello_world example from Rustful](https://github.com/Ogeon/rustful/blob/master/examples/hello_world.rs), and it's the same for other examples there, as well. It should just write "Hello, stranger!" and the headers should just be date, content length, content type, and server name. It looks fine in the browser, so that's why I'm a bit confused. I tried some of the Hyper examples and they didn't generate the errors, so there must be something with how I'm doing it. I'll investigate more later, and see what I can find. Ok, I found something. The "simplified" handler goes into wait mode if no body should be read, and waits for a signal that tells it that it's time to start the writing the response. Changing this to make it immediately go into write mode (which will mess with the flow, but should work for `hello_world`) makes the errors disappear. I tried to replicate the `hello` example from Hyper, using the more advanced handler method. It did not call `Next::wait` and it did not cause any errors. I changed it to call `Next::wait`, and made it call `control.ready(Next::write())` from a thread, and that made the errors appear again. What do you think? @Ogeon hm, I am able to reproduce if I `wait()` and spawn a thread to call `ready()`, as you say. When I make a tiny Rust program to open a tcp stream, write a request, and read a response, I don't get any io errors, or reads of 0. Can you see something else here that would make wrk goto error: https://github.com/wg/wrk/blob/master/src/wrk.c#L426-L448 Hard to say. The error conditions seems to be either a network error (return -1), a 0 read before finishing the response, or some failure in `http_parser_execute`. There shouldn't be anything to read (unless the errors appears when data is finally received), so the only logical failures would be the network error or the 0 read, given that `http_parser_execute` returns the number of parsed bytes. [It's quite complex](https://github.com/wg/wrk/blob/master/src/http_parser.c#L627), though, so it's hard to say exactly what happens. Either way, 0 reads will still cause problems. If it does read something, then the problem should be caused by something in `http_parser_execute`. It's huge and has many jumps to [`error`](https://github.com/wg/wrk/blob/master/src/http_parser.c#L2069), but it looks like it would report those errors to the user. I tried to pass the `--timeout 10s` option, but that didn't make a difference. That should show up in the timeout counter, instead, so I didn't really expect anything. It looks like they forgot to check errno in sock_read to return RETRY, and so the EAGAIN error is being reported as a read error. On Sat, Apr 2, 2016, 4:03 AM Erik Hedvall notifications@github.com wrote: > Hard to say. The error conditions seems to be either a network error > (return -1), a 0 read before finishing the response, or some failure in > http_parser_execute. There shouldn't be anything to read (unless the > errors appears when data is finally received), so the only logical failures > would be the network error or the 0 read, given that http_parser_execute > returns the number of parsed bytes. It's quite complex > https://github.com/wg/wrk/blob/master/src/http_parser.c#L627, though, > so it's hard to say exactly what happens. Either way, 0 reads will still > cause problems. > > If it does read something, then the problem should be caused by something > in http_parser_execute. It's huge and has many jumps to error > https://github.com/wg/wrk/blob/master/src/http_parser.c#L2069, but it > looks like it would report those errors to the user. > > I tried to pass the --timeout 10s option, but that didn't make a > difference. That should show up in the timeout counter, instead, so I > didn't really expect anything. > > — > You are receiving this because you were mentioned. > > Reply to this email directly or view it on GitHub > https://github.com/hyperium/hyper/issues/395#issuecomment-204694576 Hmm, yeah, looks like that's the case. It's also static, so I guess it won't be replaced by an other function. I've noticed that the latency, and variation of latency with the mio branch is much higher and seems to have a larger spread than whats currently on master. I ran cargo --release --example server in each branch then ran wrk against it. Mio ``` Running 30s test @ http://127.0.0.1:1337/ 10 threads and 1000 connections Thread Stats Avg Stdev Max +/- Stdev Latency 22.23ms 34.30ms 1.03s 99.67% Req/Sec 4.76k 693.41 8.08k 88.07% 1421686 requests in 30.06s, 122.02MB read Requests/sec: 47290.16 Transfer/sec: 4.06MB wrk -c 1000 -t 10 -d 30s "http://127.0.0.1:1337/" 2.80s user 11.56s system 47% cpu 30.111 total ``` Master ``` Running 30s test @ http://127.0.0.1:1337/ 10 threads and 1000 connections Thread Stats Avg Stdev Max +/- Stdev Latency 54.80us 93.95us 22.16ms 98.91% Req/Sec 84.24k 15.81k 97.11k 78.33% 2512893 requests in 30.07s, 215.68MB read Requests/sec: 83560.27 Transfer/sec: 7.17MB wrk -c 1000 -t 10 -d 30s "http://127.0.0.1:1337/" 5.07s user 22.54s system 91% cpu 30.122 total ``` Can anyone else confirm this? Is this a known issue? The mio branch cpu usage is like half of the threaded. That might be related It may help to edit the async example to spawn a server in several threads, so as to compare to the master example which is using 1.25 threads per cpus. I just noticed that the way `Control::ready` behaves has changed. It's no longer possible to call it from `on_request` and then make `on_request` return `Next::wait()` ([small example](https://gist.github.com/Ogeon/5b9de0f2cb5e744841f75ffee75a798b)). It won't wake up after `on_request`. Is this a bug? @Ogeon It was indeed a bug. I added the use of an `AtomicBool` to reduce the amount of usage on the mio's bounded queue (to reduce errors from it being full), and had an incorrect `if` check. Fixed. Alright, nice! :smile: It works just as before, now. I've been trying to re-enable OpenSSL support in Rustful today, and it went alright, except when it came to dealing with the different `Transport` types. The fact that many parts of the API depends on it gives me three alternatives: 1. Make almost everything in Rustful generic over `Transport`. This would work if it didn't cause a bunch of coherence problems in some important parts. 2. Make `Http/Https` enums for `Encoder` and `Decoder`. This would work if the `Transport` type for HTTPS was public. I tried with `<Openssl as Ssl>::Stream`, as well, but it looks like it counts as a type parameter and caused conflicting implementations of `From`. 3. Mask `Encoder<T>` and `Decoder<T>` as `Read` and `Write`. My current solution is a variant of this, but it's not so nice, and won't work well if more than simple read/write functionality is ever expected. It would be nice if the `Transport` type could be made public for the OpenSSL case, allowing solution 2, or if both HTTP and HTTPS used the same type (I saw `HttpsStream` in there, but I guess that's something else), allowing simple `type` aliases for `Encoder` and `Decoder`. A completely different solution is, of course, also welcome. @Ogeon ah, I hadn't noticed that the `OpensslStream` type wasn't being exported. Just doing that should be enough, right? Then for https, (if you wish to utilize only openssl), you could use `HttpsStream<OpensslStream<HttpStream>>`. That should do it, as far as I could tell. It did look like it was just `OpensslStream<HttpStream>`, though, but it could also have been some misleading error messages. Ignore me if you've already done this, but if you're using non-blocking sockets with OpenSSL you can't just use the `io::{Read, Write}` traits, you need to port the code to use `ssl_read` and `ssl_write` [1] instead. This is because OpenSSL can return special error codes that indicate that the code must call `read` if they're currently writing or `write` if they're currently reading. (Or at least that's my understanding). If you don't, it will work most of the time and then occasionally fail. [1] http://sfackler.github.io/rust-openssl/doc/v0.7.9/openssl/ssl/struct.SslStream.html#method.ssl_read @erikjohnston yep, I know about it. I haven't handled it yet, as I slowed down trying to design a generic way for the `Transport` trait to report it, and moved on to other pieces that were missing. I won't ship the version without getting that in place, however. --- Basically, my initial thoughts were something like this: ``` rust trait Transport { // ... fn blocked(&self) -> Option<Blocked> { // default implementations assume nothing special None } } enum Blocked { Read, Write, } ``` The `blocked` method could be checked by the event loop when deciding what events to listen for. If the result is `Some`, the event will be added to the event list. So an implementation for openssl could do something like this: ``` rust struct OpensslStream { stream: openssl::SslStream<HttpStream>, blocked: Option<Blocked>, } impl Read for OpensslStream { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match self.stream.ssl_read(buf) { Ok(n) => Ok(n), Err(openssl::Error::WantWrite(io)) => { self.blocked = Some(Blocked::Write); return Err(io); }, // ... } } } ``` Does this seem like it would work for any other transport implementation, like schannel or security-framework? @sfackler @frewsxcv That should work, yeah, but it's unfortunate that there's that out of band signaling of what you're blocked on. Maybe there should be a tweaked Read trait that could return the proper information? @sfackler well, the stream is present to the `Handler` as `T: Read` or `T: Write`, so user code would be using those traits. This design was to hopefully remove the need for a `Handler` to notice if the underlying stream protocol needed to read, even if the user just wants `Next::write()` a bunch. @seanmonstar I could implement the nicer solution nr. 2 now, when `OpensslStream` is public, so all is well. :smile: It's an ok solution. Also, I had to use `Encoder<OpensslStream<HttpStream>>` and `Encoder<OpensslStream<HttpStream>>`, as I vaguely mentioned before. I'm not sure if that was what you actually meant.
2016-05-04T19:40:53Z
0.9
220d09fc3a68cdd9a10589b2b454b54312518bb3
hyperium/hyper
775
hyperium__hyper-775
[ "774" ]
3a3e08687b9711edcc2d08e1f307805322ff68bb
diff --git a/examples/client.rs b/examples/client.rs --- a/examples/client.rs +++ b/examples/client.rs @@ -20,7 +20,20 @@ fn main() { } }; - let client = Client::new(); + let client = match env::var("HTTP_PROXY") { + Ok(mut proxy) => { + // parse the proxy, message if it doesn't make sense + let mut port = 80; + if let Some(colon) = proxy.rfind(':') { + port = proxy[colon + 1..].parse().unwrap_or_else(|e| { + panic!("HTTP_PROXY is malformed: {:?}, port parse error: {}", proxy, e); + }); + proxy.truncate(colon); + } + Client::with_http_proxy(proxy, port) + }, + _ => Client::new() + }; let mut res = client.get(&*url) .header(Connection::close()) diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -71,10 +71,12 @@ use method::Method; use net::{NetworkConnector, NetworkStream}; use Error; +use self::proxy::tunnel; pub use self::pool::Pool; pub use self::request::Request; pub use self::response::Response; +mod proxy; pub mod pool; pub mod request; pub mod response; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -90,7 +92,7 @@ pub struct Client { redirect_policy: RedirectPolicy, read_timeout: Option<Duration>, write_timeout: Option<Duration>, - proxy: Option<(Cow<'static, str>, Cow<'static, str>, u16)> + proxy: Option<(Cow<'static, str>, u16)> } impl fmt::Debug for Client { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -116,6 +118,15 @@ impl Client { Client::with_connector(Pool::new(config)) } + pub fn with_http_proxy<H>(host: H, port: u16) -> Client + where H: Into<Cow<'static, str>> { + let host = host.into(); + let proxy = tunnel((host.clone(), port)); + let mut client = Client::with_connector(Pool::with_connector(Default::default(), proxy)); + client.proxy = Some((host, port)); + client + } + /// Create a new client with a specific connector. pub fn with_connector<C, S>(connector: C) -> Client where C: NetworkConnector<Stream=S> + Send + Sync + 'static, S: NetworkStream + Send { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -148,12 +159,6 @@ impl Client { self.write_timeout = dur; } - /// Set a proxy for requests of this Client. - pub fn set_proxy<S, H>(&mut self, scheme: S, host: H, port: u16) - where S: Into<Cow<'static, str>>, H: Into<Cow<'static, str>> { - self.proxy = Some((scheme.into(), host.into(), port)); - } - /// Build a Get request. pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder { self.request(Method::Get, url) diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -271,13 +276,12 @@ impl<'a> RequestBuilder<'a> { loop { let mut req = { - let (scheme, host, port) = match client.proxy { - Some(ref proxy) => (proxy.0.as_ref(), proxy.1.as_ref(), proxy.2), - None => { - let hp = try!(get_host_and_port(&url)); - (url.scheme(), hp.0, hp.1) - } - }; + let (host, port) = try!(get_host_and_port(&url)); + let mut message = try!(client.protocol.new_message(&host, port, url.scheme())); + if url.scheme() == "http" && client.proxy.is_some() { + message.set_proxied(true); + } + let mut headers = match headers { Some(ref headers) => headers.clone(), None => Headers::new(), diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -286,7 +290,6 @@ impl<'a> RequestBuilder<'a> { hostname: host.to_owned(), port: Some(port), }); - let message = try!(client.protocol.new_message(&host, port, scheme)); Request::with_headers_and_message(method.clone(), url.clone(), headers, message) }; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -460,6 +463,7 @@ impl Default for RedirectPolicy { } } + fn get_host_and_port(url: &Url) -> ::Result<(&str, u16)> { let host = match url.host_str() { Some(host) => host, diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -127,6 +127,7 @@ impl<C: NetworkConnector<Stream=S>, S: NetworkStream + Send> NetworkConnector fo } /// A Stream that will try to be returned to the Pool when dropped. +#[derive(Debug)] pub struct PooledStream<S> { inner: Option<PooledStreamInner<S>>, is_closed: bool, diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -11,7 +11,7 @@ use url::Position as UrlPosition; use buffer::BufReader; use Error; -use header::{Headers, Host, ContentLength, TransferEncoding}; +use header::{Headers, ContentLength, TransferEncoding}; use header::Encoding::Chunked; use method::{Method}; use net::{NetworkConnector, NetworkStream}; diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -91,6 +91,7 @@ impl Stream { /// An implementation of the `HttpMessage` trait for HTTP/1.1. #[derive(Debug)] pub struct Http11Message { + is_proxied: bool, method: Option<Method>, stream: Wrapper<Stream>, } diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -131,6 +132,7 @@ impl HttpMessage for Http11Message { io::ErrorKind::Other, ""))); let mut method = None; + let is_proxied = self.is_proxied; self.stream.map_in_place(|stream: Stream| -> Stream { let stream = match stream { Stream::Idle(stream) => stream, diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -144,17 +146,10 @@ impl HttpMessage for Http11Message { let mut stream = BufWriter::new(stream); { - let uri = match head.headers.get::<Host>() { - Some(host) - if Some(&*host.hostname) == head.url.host_str() - && host.port == head.url.port_or_known_default() => { - &head.url[UrlPosition::BeforePath..UrlPosition::AfterQuery] - }, - _ => { - trace!("url and host header dont match, using absolute uri form"); - head.url.as_ref() - } - + let uri = if is_proxied { + head.url.as_ref() + } else { + &head.url[UrlPosition::BeforePath..UrlPosition::AfterQuery] }; let version = version::HttpVersion::Http11; diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -365,6 +360,11 @@ impl HttpMessage for Http11Message { try!(self.get_mut().close(Shutdown::Both)); Ok(()) } + + #[inline] + fn set_proxied(&mut self, val: bool) { + self.is_proxied = val; + } } impl Http11Message { diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -401,6 +401,7 @@ impl Http11Message { /// the peer. pub fn with_stream(stream: Box<NetworkStream + Send>) -> Http11Message { Http11Message { + is_proxied: false, method: None, stream: Wrapper::new(Stream::new(stream)), } diff --git a/src/http/message.rs b/src/http/message.rs --- a/src/http/message.rs +++ b/src/http/message.rs @@ -70,6 +70,11 @@ pub trait HttpMessage: Write + Read + Send + Any + Typeable + Debug { fn close_connection(&mut self) -> ::Result<()>; /// Returns whether the incoming message has a body. fn has_body(&self) -> bool; + /// Called when the Client wishes to use a Proxy. + fn set_proxied(&mut self, val: bool) { + // default implementation so as to not be a breaking change. + warn!("default set_proxied({:?})", val); + } } impl HttpMessage { diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -12,7 +12,7 @@ use solicit::http::frame::{SettingsFrame, Frame}; use solicit::http::connection::{HttpConnection, EndStream, DataChunk}; use header::Headers; -use net::{NetworkStream, NetworkConnector}; +use net::{NetworkStream, NetworkConnector, SslClient}; #[derive(Clone, Debug)] pub struct MockStream { diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -315,3 +315,13 @@ impl NetworkConnector for MockHttp2Connector { Ok(self.streams.borrow_mut().remove(0)) } } + +#[derive(Debug, Default)] +pub struct MockSsl; + +impl<T: NetworkStream + Send + Clone> SslClient<T> for MockSsl { + type Stream = T; + fn wrap_client(&self, stream: T, _host: &str) -> ::Result<T> { + Ok(stream) + } +} diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -6,7 +6,7 @@ use std::net::{SocketAddr, ToSocketAddrs, TcpStream, TcpListener, Shutdown}; use std::mem; #[cfg(feature = "openssl")] -pub use self::openssl::Openssl; +pub use self::openssl::{Openssl, OpensslClient}; use std::time::Duration; diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -423,22 +423,22 @@ pub trait Ssl { } /// An abstraction to allow any SSL implementation to be used with client-side HttpsStreams. -pub trait SslClient { +pub trait SslClient<T: NetworkStream + Send + Clone = HttpStream> { /// The protected stream. type Stream: NetworkStream + Send + Clone; /// Wrap a client stream with SSL. - fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream>; + fn wrap_client(&self, stream: T, host: &str) -> ::Result<Self::Stream>; } /// An abstraction to allow any SSL implementation to be used with server-side HttpsStreams. -pub trait SslServer { +pub trait SslServer<T: NetworkStream + Send + Clone = HttpStream> { /// The protected stream. type Stream: NetworkStream + Send + Clone; /// Wrap a server stream with SSL. - fn wrap_server(&self, stream: HttpStream) -> ::Result<Self::Stream>; + fn wrap_server(&self, stream: T) -> ::Result<Self::Stream>; } -impl<S: Ssl> SslClient for S { +impl<S: Ssl> SslClient<HttpStream> for S { type Stream = <S as Ssl>::Stream; fn wrap_client(&self, stream: HttpStream, host: &str) -> ::Result<Self::Stream> { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -446,7 +446,7 @@ impl<S: Ssl> SslClient for S { } } -impl<S: Ssl> SslServer for S { +impl<S: Ssl> SslServer<HttpStream> for S { type Stream = <S as Ssl>::Stream; fn wrap_server(&self, stream: HttpStream) -> ::Result<Self::Stream> { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -566,28 +566,35 @@ impl<S: SslServer + Clone> NetworkListener for HttpsListener<S> { /// A connector that can protect HTTP streams using SSL. #[derive(Debug, Default)] -pub struct HttpsConnector<S: SslClient> { - ssl: S +pub struct HttpsConnector<S: SslClient, C: NetworkConnector = HttpConnector> { + ssl: S, + connector: C, +} + +impl<S: SslClient> HttpsConnector<S, HttpConnector> { + /// Create a new connector using the provided SSL implementation. + pub fn new(s: S) -> HttpsConnector<S, HttpConnector> { + HttpsConnector::with_connector(s, HttpConnector) + } } -impl<S: SslClient> HttpsConnector<S> { +impl<S: SslClient, C: NetworkConnector> HttpsConnector<S, C> { /// Create a new connector using the provided SSL implementation. - pub fn new(s: S) -> HttpsConnector<S> { - HttpsConnector { ssl: s } + pub fn with_connector(s: S, connector: C) -> HttpsConnector<S, C> { + HttpsConnector { ssl: s, connector: connector } } } -impl<S: SslClient> NetworkConnector for HttpsConnector<S> { +impl<S: SslClient, C: NetworkConnector<Stream=HttpStream>> NetworkConnector for HttpsConnector<S, C> { type Stream = HttpsStream<S::Stream>; fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<Self::Stream> { - let addr = &(host, port); + let stream = try!(self.connector.connect(host, port, "http")); if scheme == "https" { debug!("https scheme"); - let stream = HttpStream(try!(TcpStream::connect(addr))); self.ssl.wrap_client(stream, host).map(HttpsStream::Https) } else { - HttpConnector.connect(host, port, scheme).map(HttpsStream::Http) + Ok(HttpsStream::Http(stream)) } } } diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -638,6 +645,31 @@ mod openssl { pub context: Arc<SslContext> } + /// A client-specific implementation of OpenSSL. + #[derive(Debug, Clone)] + pub struct OpensslClient(SslContext); + + impl Default for OpensslClient { + fn default() -> OpensslClient { + OpensslClient(SslContext::new(SslMethod::Sslv23).unwrap_or_else(|e| { + // if we cannot create a SslContext, that's because of a + // serious problem. just crash. + panic!("{}", e) + })) + } + } + + + impl<T: NetworkStream + Send + Clone> super::SslClient<T> for OpensslClient { + type Stream = SslStream<T>; + + fn wrap_client(&self, stream: T, host: &str) -> ::Result<Self::Stream> { + let ssl = try!(Ssl::new(&self.0)); + try!(ssl.set_hostname(host)); + SslStream::connect(ssl, stream).map_err(From::from) + } + } + impl Default for Openssl { fn default() -> Openssl { Openssl { diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -12,7 +12,7 @@ use std::thread; use time::now_utc; use header; -use http::h1::{CR, LF, LINE_ENDING, HttpWriter}; +use http::h1::{LINE_ENDING, HttpWriter}; use http::h1::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter}; use status; use net::{Fresh, Streaming}; diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -82,8 +82,7 @@ impl<'a, W: Any> Response<'a, W> { fn write_head(&mut self) -> io::Result<Body> { debug!("writing head: {:?} {:?}", self.version, self.status); - try!(write!(&mut self.body, "{} {}{}{}", self.version, self.status, - CR as char, LF as char)); + try!(write!(&mut self.body, "{} {}\r\n", self.version, self.status)); if !self.headers.has::<header::Date>() { self.headers.set(header::Date(header::HttpDate(now_utc())));
diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -479,8 +483,9 @@ mod tests { use std::io::Read; use header::Server; use http::h1::Http11Message; - use mock::{MockStream}; + use mock::{MockStream, MockSsl}; use super::{Client, RedirectPolicy}; + use super::proxy::Proxy; use super::pool::Pool; use url::Url; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -505,24 +510,61 @@ mod tests { #[test] fn test_proxy() { use super::pool::PooledStream; + type MessageStream = PooledStream<super::proxy::Proxied<MockStream, MockStream>>; mock_connector!(ProxyConnector { b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" }); - let mut client = Client::with_connector(Pool::with_connector(Default::default(), ProxyConnector)); - client.set_proxy("http", "example.proxy", 8008); + let tunnel = Proxy { + connector: ProxyConnector, + proxy: ("example.proxy".into(), 8008), + ssl: MockSsl, + }; + let mut client = Client::with_connector(Pool::with_connector(Default::default(), tunnel)); + client.proxy = Some(("example.proxy".into(), 8008)); let mut dump = vec![]; client.get("http://127.0.0.1/foo/bar").send().unwrap().read_to_end(&mut dump).unwrap(); - { - let box_message = client.protocol.new_message("example.proxy", 8008, "http").unwrap(); - let message = box_message.downcast::<Http11Message>().unwrap(); - let stream = message.into_inner().downcast::<PooledStream<MockStream>>().unwrap().into_inner(); - let s = ::std::str::from_utf8(&stream.write).unwrap(); - let request_line = "GET http://127.0.0.1/foo/bar HTTP/1.1\r\n"; - assert_eq!(&s[..request_line.len()], request_line); - assert!(s.contains("Host: example.proxy:8008\r\n")); - } + let box_message = client.protocol.new_message("127.0.0.1", 80, "http").unwrap(); + let message = box_message.downcast::<Http11Message>().unwrap(); + let stream = message.into_inner().downcast::<MessageStream>().unwrap().into_inner().into_normal().unwrap();; + + let s = ::std::str::from_utf8(&stream.write).unwrap(); + let request_line = "GET http://127.0.0.1/foo/bar HTTP/1.1\r\n"; + assert!(s.starts_with(request_line), "{:?} doesn't start with {:?}", s, request_line); + assert!(s.contains("Host: 127.0.0.1\r\n")); + } + + #[test] + fn test_proxy_tunnel() { + use super::pool::PooledStream; + type MessageStream = PooledStream<super::proxy::Proxied<MockStream, MockStream>>; + + mock_connector!(ProxyConnector { + b"HTTP/1.1 200 OK\r\n\r\n", + b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" + }); + let tunnel = Proxy { + connector: ProxyConnector, + proxy: ("example.proxy".into(), 8008), + ssl: MockSsl, + }; + let mut client = Client::with_connector(Pool::with_connector(Default::default(), tunnel)); + client.proxy = Some(("example.proxy".into(), 8008)); + let mut dump = vec![]; + client.get("https://127.0.0.1/foo/bar").send().unwrap().read_to_end(&mut dump).unwrap(); + + let box_message = client.protocol.new_message("127.0.0.1", 443, "https").unwrap(); + let message = box_message.downcast::<Http11Message>().unwrap(); + let stream = message.into_inner().downcast::<MessageStream>().unwrap().into_inner().into_tunneled().unwrap(); + + let s = ::std::str::from_utf8(&stream.write).unwrap(); + let connect_line = "CONNECT 127.0.0.1:443 HTTP/1.1\r\nHost: 127.0.0.1:443\r\n\r\n"; + assert_eq!(&s[..connect_line.len()], connect_line); + let s = &s[connect_line.len()..]; + let request_line = "GET /foo/bar HTTP/1.1\r\n"; + assert_eq!(&s[..request_line.len()], request_line); + assert!(s.contains("Host: 127.0.0.1\r\n")); } #[test] diff --git /dev/null b/src/client/proxy.rs new file mode 100644 --- /dev/null +++ b/src/client/proxy.rs @@ -0,0 +1,240 @@ +use std::borrow::Cow; +use std::io; +use std::net::{SocketAddr, Shutdown}; +use std::time::Duration; + +use method::Method; +use net::{NetworkConnector, HttpConnector, NetworkStream, SslClient}; + +#[cfg(all(feature = "openssl", not(feature = "security-framework")))] +pub fn tunnel(proxy: (Cow<'static, str>, u16)) -> Proxy<HttpConnector, ::net::Openssl> { + Proxy { + connector: HttpConnector, + proxy: proxy, + ssl: Default::default() + } +} + +#[cfg(feature = "security-framework")] +pub fn tunnel(proxy: (Cow<'static, str>, u16)) -> Proxy<HttpConnector, ::net::Openssl> { + Proxy { + connector: HttpConnector, + proxy: proxy, + ssl: Default::default() + } +} + +#[cfg(not(any(feature = "openssl", feature = "security-framework")))] +pub fn tunnel(proxy: (Cow<'static, str>, u16)) -> Proxy<HttpConnector, self::no_ssl::Plaintext> { + Proxy { + connector: HttpConnector, + proxy: proxy, + ssl: self::no_ssl::Plaintext, + } + +} + +pub struct Proxy<C, S> +where C: NetworkConnector + Send + Sync + 'static, + C::Stream: NetworkStream + Send + Clone, + S: SslClient<C::Stream> { + pub connector: C, + pub proxy: (Cow<'static, str>, u16), + pub ssl: S, +} + + +impl<C, S> NetworkConnector for Proxy<C, S> +where C: NetworkConnector + Send + Sync + 'static, + C::Stream: NetworkStream + Send + Clone, + S: SslClient<C::Stream> { + type Stream = Proxied<C::Stream, S::Stream>; + + fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<Self::Stream> { + use httparse; + use std::io::{Read, Write}; + use ::version::HttpVersion::Http11; + trace!("{:?} proxy for '{}://{}:{}'", self.proxy, scheme, host, port); + match scheme { + "http" => { + self.connector.connect(self.proxy.0.as_ref(), self.proxy.1, "http") + .map(Proxied::Normal) + }, + "https" => { + let mut stream = try!(self.connector.connect(self.proxy.0.as_ref(), self.proxy.1, "http")); + trace!("{:?} CONNECT {}:{}", self.proxy, host, port); + try!(write!(&mut stream, "{method} {host}:{port} {version}\r\nHost: {host}:{port}\r\n\r\n", + method=Method::Connect, host=host, port=port, version=Http11)); + try!(stream.flush()); + let mut buf = [0; 1024]; + let mut n = 0; + while n < buf.len() { + n += try!(stream.read(&mut buf[n..])); + let mut headers = [httparse::EMPTY_HEADER; 10]; + let mut res = httparse::Response::new(&mut headers); + if try!(res.parse(&buf[..n])).is_complete() { + let code = res.code.expect("complete parsing lost code"); + if code >= 200 && code < 300 { + trace!("CONNECT success = {:?}", code); + return self.ssl.wrap_client(stream, host) + .map(Proxied::Tunneled) + } else { + trace!("CONNECT response = {:?}", code); + return Err(::Error::Status); + } + } + } + Err(::Error::TooLarge) + }, + _ => Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid scheme").into()) + } + } +} + +#[derive(Debug)] +pub enum Proxied<T1, T2> { + Normal(T1), + Tunneled(T2) +} + +#[cfg(test)] +impl<T1, T2> Proxied<T1, T2> { + pub fn into_normal(self) -> Result<T1, Self> { + match self { + Proxied::Normal(t1) => Ok(t1), + _ => Err(self) + } + } + + pub fn into_tunneled(self) -> Result<T2, Self> { + match self { + Proxied::Tunneled(t2) => Ok(t2), + _ => Err(self) + } + } +} + +impl<T1: NetworkStream, T2: NetworkStream> io::Read for Proxied<T1, T2> { + #[inline] + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + match *self { + Proxied::Normal(ref mut t) => io::Read::read(t, buf), + Proxied::Tunneled(ref mut t) => io::Read::read(t, buf), + } + } +} + +impl<T1: NetworkStream, T2: NetworkStream> io::Write for Proxied<T1, T2> { + #[inline] + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + match *self { + Proxied::Normal(ref mut t) => io::Write::write(t, buf), + Proxied::Tunneled(ref mut t) => io::Write::write(t, buf), + } + } + + #[inline] + fn flush(&mut self) -> io::Result<()> { + match *self { + Proxied::Normal(ref mut t) => io::Write::flush(t), + Proxied::Tunneled(ref mut t) => io::Write::flush(t), + } + } +} + +impl<T1: NetworkStream, T2: NetworkStream> NetworkStream for Proxied<T1, T2> { + #[inline] + fn peer_addr(&mut self) -> io::Result<SocketAddr> { + match *self { + Proxied::Normal(ref mut s) => s.peer_addr(), + Proxied::Tunneled(ref mut s) => s.peer_addr() + } + } + + #[inline] + fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + match *self { + Proxied::Normal(ref inner) => inner.set_read_timeout(dur), + Proxied::Tunneled(ref inner) => inner.set_read_timeout(dur) + } + } + + #[inline] + fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + match *self { + Proxied::Normal(ref inner) => inner.set_write_timeout(dur), + Proxied::Tunneled(ref inner) => inner.set_write_timeout(dur) + } + } + + #[inline] + fn close(&mut self, how: Shutdown) -> io::Result<()> { + match *self { + Proxied::Normal(ref mut s) => s.close(how), + Proxied::Tunneled(ref mut s) => s.close(how) + } + } +} + +#[cfg(not(any(feature = "openssl", feature = "security-framework")))] +mod no_ssl { + use std::io; + use std::net::{Shutdown, SocketAddr}; + use std::time::Duration; + + use net::{SslClient, NetworkStream}; + + pub struct Plaintext; + + #[derive(Clone)] + pub enum Void {} + + impl io::Read for Void { + #[inline] + fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { + match *self {} + } + } + + impl io::Write for Void { + #[inline] + fn write(&mut self, _buf: &[u8]) -> io::Result<usize> { + match *self {} + } + + #[inline] + fn flush(&mut self) -> io::Result<()> { + match *self {} + } + } + + impl NetworkStream for Void { + #[inline] + fn peer_addr(&mut self) -> io::Result<SocketAddr> { + match *self {} + } + + #[inline] + fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> { + match *self {} + } + + #[inline] + fn set_write_timeout(&self, _dur: Option<Duration>) -> io::Result<()> { + match *self {} + } + + #[inline] + fn close(&mut self, _how: Shutdown) -> io::Result<()> { + match *self {} + } + } + + impl<T: NetworkStream + Send + Clone> SslClient<T> for Plaintext { + type Stream = Void; + + fn wrap_client(&self, _stream: T, _host: &str) -> ::Result<Self::Stream> { + Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid scheme").into()) + } + } +} diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -268,16 +268,15 @@ mod tests { #[test] fn test_proxy() { let url = Url::parse("http://example.dom").unwrap(); - let proxy_url = Url::parse("http://pro.xy").unwrap(); let mut req = Request::with_connector( - Get, proxy_url, &mut MockConnector + Get, url, &mut MockConnector ).unwrap(); - req.url = url; + req.message.set_proxied(true); let bytes = run_request(req); let s = from_utf8(&bytes[..]).unwrap(); let request_line = "GET http://example.dom/ HTTP/1.1"; assert_eq!(&s[..request_line.len()], request_line); - assert!(s.contains("Host: pro.xy")); + assert!(s.contains("Host: example.dom")); } #[test]
Proxy handling does not properly set destination Host header Here is a script transcript of a working proxy session ``` Script started on Wed 27 Apr 2016 09:32:58 AM PDT [~/repos/rust/hyper-upstream] ~$ telnet my-proxy 8080 Trying x.x.x.x... Connected to my-proxy. Escape character is '^]'. GET http://xkcd.com http/1.1 host: xkcd.com:80 HTTP/1.1 200 OK Cache-Control: public, max-age=300 Expires: Wed, 27 Apr 2016 16:23:15 GMT Content-Type: text/html; charset=utf-8 ETag: "1703862119" Last-Modified: Wed, 27 Apr 2016 05:16:40 GMT Server: lighttpd/1.4.28 Content-Length: 6196 Accept-Ranges: bytes Date: Wed, 27 Apr 2016 16:18:15 GMT Via: 1.1 varnish X-Served-By: cache-dfw1838-DFW X-Cache: HIT X-Cache-Hits: 1 X-Timer: S1461772234.306036,VS0,VE0 Vary: Accept-Encoding Proxy-Connection: Keep-Alive Connection: Keep-Alive Age: 971 ``` Note the destination is specified TWICE. Once on the GET and once again in the Host line. The current client code does not set the Host correctly. Here is the diff needed to fix it: ``` diff --git a/src/client/mod.rs b/src/client/mod.rs index 4ad5c2d..ad0b14d 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -271,10 +271,10 @@ impl<'a> RequestBuilder<'a> { loop { let mut req = { + let hp = try!(get_host_and_port(&url)); let (scheme, host, port) = match client.proxy { Some(ref proxy) => (proxy.0.as_ref(), proxy.1.as_ref(), proxy.2), None => { - let hp = try!(get_host_and_port(&url)); (url.scheme(), hp.0, hp.1) } }; @@ -282,11 +282,14 @@ impl<'a> RequestBuilder<'a> { Some(ref headers) => headers.clone(), None => Headers::new(), }; + // Host needs to be the destination host not the proxy headers.set(Host { - hostname: host.to_owned(), - port: Some(port), + hostname: hp.0.to_owned(), + port: Some(hp.1), }); + // now connect to the proxy let message = try!(client.protocol.new_message(&host, port, scheme)); + // and make a request for the destination Request::with_headers_and_message(method.clone(), url.clone(), headers, messag\ ``` e) };
I see, I misunderstood the spec. I understood that the `Host` header is the host of the proxy server, with the absolute-uri in the request line aimed at the target host. Re-reading the spec, it seems I am indeed incorrect, as HTTP/1.0 proxies may just forward the `Host` header directly. It may be that the proxy you are using is indeed using version HTTP/1.0, or otherwise has a bug itself as I noticed this is also [in the spec](https://tools.ietf.org/html/rfc7230#section-5.4): > When a proxy receives a request with an absolute-form of > request-target, the proxy MUST ignore the received Host header field > (if any) and instead replace it with the host information of the > request-target. A proxy that forwards such a request MUST generate a > new Host field-value based on the received request-target rather than > forward the received Host field-value. That would not surprise me. yay corp IT.
2016-04-27T18:21:16Z
0.9
220d09fc3a68cdd9a10589b2b454b54312518bb3
hyperium/hyper
771
hyperium__hyper-771
[ "531" ]
4828437551c7f5ed3f54acb1c1bf1fd50a6a3516
diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -55,9 +55,9 @@ //! clone2.post("http://example.domain/post").body("foo=bar").send().unwrap(); //! }); //! ``` +use std::borrow::Cow; use std::default::Default; use std::io::{self, copy, Read}; -use std::iter::Extend; use std::fmt; use std::time::Duration; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -66,7 +66,7 @@ use url::Url; use url::ParseError as UrlError; use header::{Headers, Header, HeaderFormat}; -use header::{ContentLength, Location}; +use header::{ContentLength, Host, Location}; use method::Method; use net::{NetworkConnector, NetworkStream}; use Error; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -90,6 +90,7 @@ pub struct Client { redirect_policy: RedirectPolicy, read_timeout: Option<Duration>, write_timeout: Option<Duration>, + proxy: Option<(Cow<'static, str>, Cow<'static, str>, u16)> } impl fmt::Debug for Client { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -98,6 +99,7 @@ impl fmt::Debug for Client { .field("redirect_policy", &self.redirect_policy) .field("read_timeout", &self.read_timeout) .field("write_timeout", &self.write_timeout) + .field("proxy", &self.proxy) .finish() } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -127,6 +129,7 @@ impl Client { redirect_policy: Default::default(), read_timeout: None, write_timeout: None, + proxy: None, } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -145,6 +148,12 @@ impl Client { self.write_timeout = dur; } + /// Set a proxy for requests of this Client. + pub fn set_proxy<S, H>(&mut self, scheme: S, host: H, port: u16) + where S: Into<Cow<'static, str>>, H: Into<Cow<'static, str>> { + self.proxy = Some((scheme.into(), host.into(), port)); + } + /// Build a Get request. pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder { self.request(Method::Get, url) diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -247,7 +256,7 @@ impl<'a> RequestBuilder<'a> { pub fn send(self) -> ::Result<Response> { let RequestBuilder { client, method, url, headers, body } = self; let mut url = try!(url); - trace!("send {:?} {:?}", method, url); + trace!("send method={:?}, url={:?}, client={:?}", method, url, client); let can_have_body = match method { Method::Get | Method::Head => false, diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -261,12 +270,25 @@ impl<'a> RequestBuilder<'a> { }; loop { - let message = { - let (host, port) = try!(get_host_and_port(&url)); - try!(client.protocol.new_message(&host, port, url.scheme())) + let mut req = { + let (scheme, host, port) = match client.proxy { + Some(ref proxy) => (proxy.0.as_ref(), proxy.1.as_ref(), proxy.2), + None => { + let hp = try!(get_host_and_port(&url)); + (url.scheme(), hp.0, hp.1) + } + }; + let mut headers = match headers { + Some(ref headers) => headers.clone(), + None => Headers::new(), + }; + headers.set(Host { + hostname: host.to_owned(), + port: Some(port), + }); + let message = try!(client.protocol.new_message(&host, port, scheme)); + Request::with_headers_and_message(method.clone(), url.clone(), headers, message) }; - let mut req = try!(Request::with_message(method.clone(), url.clone(), message)); - headers.as_ref().map(|headers| req.headers_mut().extend(headers.iter())); try!(req.set_write_timeout(client.write_timeout)); try!(req.set_read_timeout(client.read_timeout)); diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -102,22 +102,21 @@ impl<C: NetworkConnector<Stream=S>, S: NetworkStream + Send> NetworkConnector fo type Stream = PooledStream<S>; fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<PooledStream<S>> { let key = key(host, port, scheme); - let mut locked = self.inner.lock().unwrap(); let mut should_remove = false; - let inner = match locked.conns.get_mut(&key) { + let inner = match self.inner.lock().unwrap().conns.get_mut(&key) { Some(ref mut vec) => { trace!("Pool had connection, using"); should_remove = vec.len() == 1; vec.pop().unwrap() } - _ => PooledStreamInner { + None => PooledStreamInner { key: key.clone(), stream: try!(self.connector.connect(host, port, scheme)), previous_response_expected_no_content: false, } }; if should_remove { - locked.conns.remove(&key); + self.inner.lock().unwrap().conns.remove(&key); } Ok(PooledStream { inner: Some(inner), diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -134,6 +133,13 @@ pub struct PooledStream<S> { pool: Arc<Mutex<PoolImpl<S>>>, } +impl<S: NetworkStream> PooledStream<S> { + /// Take the wrapped stream out of the pool completely. + pub fn into_inner(mut self) -> S { + self.inner.take().expect("PooledStream lost its inner stream").stream + } +} + #[derive(Debug)] struct PooledStreamInner<S> { key: Key, diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -70,14 +70,20 @@ impl Request<Fresh> { }); } - Ok(Request { + Ok(Request::with_headers_and_message(method, url, headers, message)) + } + + #[doc(hidden)] + pub fn with_headers_and_message(method: Method, url: Url, headers: Headers, message: Box<HttpMessage>) + -> Request<Fresh> { + Request { method: method, headers: headers, url: url, version: version::HttpVersion::Http11, message: message, _marker: PhantomData, - }) + } } /// Create a new client request. diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -129,6 +135,8 @@ impl Request<Fresh> { pub fn headers_mut(&mut self) -> &mut Headers { &mut self.headers } } + + impl Request<Streaming> { /// Completes writing the request, and returns a response to read from. /// diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -11,7 +11,7 @@ use url::Position as UrlPosition; use buffer::BufReader; use Error; -use header::{Headers, ContentLength, TransferEncoding}; +use header::{Headers, Host, ContentLength, TransferEncoding}; use header::Encoding::Chunked; use method::{Method}; use net::{NetworkConnector, NetworkStream}; diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -144,7 +144,18 @@ impl HttpMessage for Http11Message { let mut stream = BufWriter::new(stream); { - let uri = &head.url[UrlPosition::BeforePath..UrlPosition::AfterQuery]; + let uri = match head.headers.get::<Host>() { + Some(host) + if Some(&*host.hostname) == head.url.host_str() + && host.port == head.url.port_or_known_default() => { + &head.url[UrlPosition::BeforePath..UrlPosition::AfterQuery] + }, + _ => { + trace!("url and host header dont match, using absolute uri form"); + head.url.as_ref() + } + + }; let version = version::HttpVersion::Http11; debug!("request line: {:?} {:?} {:?}", head.method, uri, version);
diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -456,6 +478,8 @@ fn get_host_and_port(url: &Url) -> ::Result<(&str, u16)> { mod tests { use std::io::Read; use header::Server; + use http::h1::Http11Message; + use mock::{MockStream}; use super::{Client, RedirectPolicy}; use super::pool::Pool; use url::Url; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -477,6 +501,30 @@ mod tests { " }); + + #[test] + fn test_proxy() { + use super::pool::PooledStream; + mock_connector!(ProxyConnector { + b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" + }); + let mut client = Client::with_connector(Pool::with_connector(Default::default(), ProxyConnector)); + client.set_proxy("http", "example.proxy", 8008); + let mut dump = vec![]; + client.get("http://127.0.0.1/foo/bar").send().unwrap().read_to_end(&mut dump).unwrap(); + + { + let box_message = client.protocol.new_message("example.proxy", 8008, "http").unwrap(); + let message = box_message.downcast::<Http11Message>().unwrap(); + let stream = message.into_inner().downcast::<PooledStream<MockStream>>().unwrap().into_inner(); + let s = ::std::str::from_utf8(&stream.write).unwrap(); + let request_line = "GET http://127.0.0.1/foo/bar HTTP/1.1\r\n"; + assert_eq!(&s[..request_line.len()], request_line); + assert!(s.contains("Host: example.proxy:8008\r\n")); + } + + } + #[test] fn test_redirect_followall() { let mut client = Client::with_connector(MockRedirectPolicy); diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -246,6 +254,32 @@ mod tests { assert!(!s.contains("Content-Length:")); } + #[test] + fn test_host_header() { + let url = Url::parse("http://example.dom").unwrap(); + let req = Request::with_connector( + Get, url, &mut MockConnector + ).unwrap(); + let bytes = run_request(req); + let s = from_utf8(&bytes[..]).unwrap(); + assert!(s.contains("Host: example.dom")); + } + + #[test] + fn test_proxy() { + let url = Url::parse("http://example.dom").unwrap(); + let proxy_url = Url::parse("http://pro.xy").unwrap(); + let mut req = Request::with_connector( + Get, proxy_url, &mut MockConnector + ).unwrap(); + req.url = url; + let bytes = run_request(req); + let s = from_utf8(&bytes[..]).unwrap(); + let request_line = "GET http://example.dom/ HTTP/1.1"; + assert_eq!(&s[..request_line.len()], request_line); + assert!(s.contains("Host: pro.xy")); + } + #[test] fn test_post_chunked_with_encoding() { let url = Url::parse("http://example.dom").unwrap();
Add Proxy support to Client I imagine some sort of `Proxy` type being added a property of `Client`, with a corresponding `set_proxy(Option<Proxy>)` method. Use of a proxy can have different requirements: all requests, only https requests, only http... So it would probably mean `Proxy` would be an enum... and the proxy would be consulted in the `RequestBuilder.send` method.
It would be awesome to have this feature! Yes please. Some of us need this to use Rust at work. Something like: ``` let mut client = Client::new(); // after checking config, env for HTTP_PROXY, whatever let proxy = Proxy::new(server, port, scheme); // AuthProxy::new for the more complicated cases client.add_proxy(proxy); // set_proxy, which ever. Bike shed as needed // now a request using 'scheme' will be proxied client.get(....) ``` I would like to give this a try. @seanmonstar Could you give more information on how you think this should be implemented? @mattnenterprise an api suggested by @shaleh looks fine. It'd likely require adding a method to `Request` to change the `RequestUri`, since the full url is needed instead of just the path. Note the requirement for a list of proxies. When the final HTTP call is made it should check the request's scheme against defined proxies for a matching scheme. Since Rust does not support optional arguments I used `AuthProxy` in my example for the case where the proxy needs authentication. If this is too cumbersome using `Option` for the credentials is probably OK. I think using a container for the proxies avoids the need for `Option<Proxy>`. Just walk it and compare schemes. Since the list will only every be a few items long it is sane to walk it. No need for a hash or other lookup table. There's a PR for this at #639, if others interested in this feature could help looking it over. Hello everybody, I have been working on the proxy implementation for a while (on and off) but I missed this conversation :-) I will evolve my PR based on this feedback. Hi All, I've just been tracking down the reason why multirust-rs is not able to work behind a proxy, It seems like the Http Client used in multirust is the Hyper one which leads me to this discussion and the associated PR. Do you have an ETA on this one ? it seems like it hasn't evolved since October. Any chance to see this merged or is it still not mature enough. I see a lot of value in having this functionality built-in Hyper as it serves a lot of tools/libs in the ecosystem and could clearly help to drive Enterprise adoption. Thanks ! I'm in the same boat. I really need proxy support. Is there any chance I can help out with this? Any updates on this? My focus is entirely on the async branch, which makes this easy: ``` rust struct ProxiedHandler(hyper::Method, &'static str); impl Handler for ProxiedHandler { fn on_request(&mut self, req: &mut Request) -> Next { req.set_method(self.0); req.set_uri(RequestUri::AbsoluteUri(self.1.parse().unwrap()); Next::read() } // ... } client.request("http://proxy.server", ProxiedHandler(GET, "http://target.domain/path")); ``` I can try to add in some support to the sync branch, such that if the `Request.url` does not match the `Host` header, then assume it is a proxied request and send the full URI...
2016-04-25T22:51:19Z
0.9
220d09fc3a68cdd9a10589b2b454b54312518bb3
hyperium/hyper
750
hyperium__hyper-750
[ "747" ]
c85b056cabd1bbe62340af03696810c7e155fe17
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -44,6 +44,8 @@ pub use self::if_range::IfRange; pub use self::last_modified::LastModified; pub use self::location::Location; pub use self::pragma::Pragma; +pub use self::prefer::{Prefer, Preference}; +pub use self::preference_applied::PreferenceApplied; pub use self::range::{Range, ByteRangeSpec}; pub use self::referer::Referer; pub use self::server::Server; diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -392,6 +394,8 @@ mod if_unmodified_since; mod last_modified; mod location; mod pragma; +mod prefer; +mod preference_applied; mod range; mod referer; mod server;
diff --git /dev/null b/src/header/common/prefer.rs new file mode 100644 --- /dev/null +++ b/src/header/common/prefer.rs @@ -0,0 +1,203 @@ +use std::fmt; +use std::str::FromStr; +use header::{Header, HeaderFormat}; +use header::parsing::{from_comma_delimited, fmt_comma_delimited}; + +/// `Prefer` header, defined in [RFC7240](http://tools.ietf.org/html/rfc7240) +/// +/// The `Prefer` header field is HTTP header field that can be used by a +/// client to request that certain behaviors be employed by a server +/// while processing a request. +/// +/// # ABNF +/// ```plain +/// Prefer = "Prefer" ":" 1#preference +/// preference = token [ BWS "=" BWS word ] +/// *( OWS ";" [ OWS parameter ] ) +/// parameter = token [ BWS "=" BWS word ] +/// ``` +/// +/// # Example values +/// * `respond-async` +/// * `return=minimal` +/// * `wait=30` +/// +/// # Examples +/// ``` +/// use hyper::header::{Headers, Prefer, Preference}; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// Prefer(vec![Preference::RespondAsync]) +/// ); +/// ``` +/// ``` +/// use hyper::header::{Headers, Prefer, Preference}; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// Prefer(vec![ +/// Preference::RespondAsync, +/// Preference::ReturnRepresentation, +/// Preference::Wait(10u32), +/// Preference::Extension("foo".to_owned(), +/// "bar".to_owned(), +/// vec![]), +/// ]) +/// ); +/// ``` +#[derive(PartialEq, Clone, Debug)] +pub struct Prefer(pub Vec<Preference>); + +__hyper__deref!(Prefer => Vec<Preference>); + +impl Header for Prefer { + fn header_name() -> &'static str { + "Prefer" + } + + fn parse_header(raw: &[Vec<u8>]) -> ::Result<Prefer> { + let preferences = try!(from_comma_delimited(raw)); + if !preferences.is_empty() { + Ok(Prefer(preferences)) + } else { + Err(::Error::Header) + } + } +} + +impl HeaderFormat for Prefer { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt_comma_delimited(f, &self[..]) + } +} + +/// Prefer contains a list of these preferences. +#[derive(PartialEq, Clone, Debug)] +pub enum Preference { + /// "respond-async" + RespondAsync, + /// "return=representation" + ReturnRepresentation, + /// "return=minimal" + ReturnMinimal, + /// "handling=strict" + HandlingStrict, + /// "handling=leniant" + HandlingLeniant, + /// "wait=delta" + Wait(u32), + + /// Extension preferences. Always has a value, if none is specified it is + /// just "". A preference can also have a list of parameters. + Extension(String, String, Vec<(String, String)>) +} + +impl fmt::Display for Preference { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Preference::*; + fmt::Display::fmt(match *self { + RespondAsync => "respond-async", + ReturnRepresentation => "return=representation", + ReturnMinimal => "return=minimal", + HandlingStrict => "handling=strict", + HandlingLeniant => "handling=leniant", + + Wait(secs) => return write!(f, "wait={}", secs), + + Extension(ref name, ref value, ref params) => { + try!(write!(f, "{}", name)); + if value != "" { try!(write!(f, "={}", value)); } + if params.len() > 0 { + for &(ref name, ref value) in params { + try!(write!(f, "; {}", name)); + if value != "" { try!(write!(f, "={}", value)); } + } + } + return Ok(()); + } + }, f) + } +} + +impl FromStr for Preference { + type Err = Option<<u32 as FromStr>::Err>; + fn from_str(s: &str) -> Result<Preference, Option<<u32 as FromStr>::Err>> { + use self::Preference::*; + let mut params = s.split(';').map(|p| { + let mut param = p.splitn(2, '='); + match (param.next(), param.next()) { + (Some(name), Some(value)) => (name.trim(), value.trim().trim_matches('"')), + (Some(name), None) => (name.trim(), ""), + // This can safely be unreachable because the [`splitn`][1] + // function (used above) will always have at least one value. + // + // [1]: http://doc.rust-lang.org/std/primitive.str.html#method.splitn + _ => { unreachable!(); } + } + }); + match params.nth(0) { + Some(param) => { + let rest: Vec<(String, String)> = params.map(|(l, r)| (l.to_owned(), r.to_owned())).collect(); + match param { + ("respond-async", "") => if rest.len() == 0 { Ok(RespondAsync) } else { Err(None) }, + ("return", "representation") => if rest.len() == 0 { Ok(ReturnRepresentation) } else { Err(None) }, + ("return", "minimal") => if rest.len() == 0 { Ok(ReturnMinimal) } else { Err(None) }, + ("handling", "strict") => if rest.len() == 0 { Ok(HandlingStrict) } else { Err(None) }, + ("handling", "leniant") => if rest.len() == 0 { Ok(HandlingLeniant) } else { Err(None) }, + ("wait", secs) => if rest.len() == 0 { secs.parse().map(Wait).map_err(Some) } else { Err(None) }, + (left, right) => Ok(Extension(left.to_owned(), right.to_owned(), rest)) + } + }, + None => Err(None) + } + } +} + +#[cfg(test)] +mod tests { + use header::Header; + use super::*; + + #[test] + fn test_parse_multiple_headers() { + let prefer = Header::parse_header(&[b"respond-async, return=representation".to_vec()]); + assert_eq!(prefer.ok(), Some(Prefer(vec![Preference::RespondAsync, + Preference::ReturnRepresentation]))) + } + + #[test] + fn test_parse_argument() { + let prefer = Header::parse_header(&[b"wait=100, handling=leniant, respond-async".to_vec()]); + assert_eq!(prefer.ok(), Some(Prefer(vec![Preference::Wait(100), + Preference::HandlingLeniant, + Preference::RespondAsync]))) + } + + #[test] + fn test_parse_quote_form() { + let prefer = Header::parse_header(&[b"wait=\"200\", handling=\"strict\"".to_vec()]); + assert_eq!(prefer.ok(), Some(Prefer(vec![Preference::Wait(200), + Preference::HandlingStrict]))) + } + + #[test] + fn test_parse_extension() { + let prefer = Header::parse_header(&[b"foo, bar=baz, baz; foo; bar=baz, bux=\"\"; foo=\"\", buz=\"some parameter\"".to_vec()]); + assert_eq!(prefer.ok(), Some(Prefer(vec![ + Preference::Extension("foo".to_owned(), "".to_owned(), vec![]), + Preference::Extension("bar".to_owned(), "baz".to_owned(), vec![]), + Preference::Extension("baz".to_owned(), "".to_owned(), vec![("foo".to_owned(), "".to_owned()), ("bar".to_owned(), "baz".to_owned())]), + Preference::Extension("bux".to_owned(), "".to_owned(), vec![("foo".to_owned(), "".to_owned())]), + Preference::Extension("buz".to_owned(), "some parameter".to_owned(), vec![])]))) + } + + #[test] + fn test_fail_with_args() { + let prefer: ::Result<Prefer> = Header::parse_header(&[b"respond-async; foo=bar".to_vec()]); + assert_eq!(prefer.ok(), None); + } +} + +bench_header!(normal, + Prefer, { vec![b"respond-async, return=representation".to_vec(), b"wait=100".to_vec()] }); diff --git /dev/null b/src/header/common/preference_applied.rs new file mode 100644 --- /dev/null +++ b/src/header/common/preference_applied.rs @@ -0,0 +1,100 @@ +use std::fmt; +use header::{Header, HeaderFormat, Preference}; +use header::parsing::{from_comma_delimited, fmt_comma_delimited}; + +/// `Preference-Applied` header, defined in [RFC7240](http://tools.ietf.org/html/rfc7240) +/// +/// The `Preference-Applied` response header may be included within a +/// response message as an indication as to which `Prefer` header tokens were +/// honored by the server and applied to the processing of a request. +/// +/// # ABNF +/// ```plain +/// Preference-Applied = "Preference-Applied" ":" 1#applied-pref +/// applied-pref = token [ BWS "=" BWS word ] +/// ``` +/// +/// # Example values +/// * `respond-async` +/// * `return=minimal` +/// * `wait=30` +/// +/// # Examples +/// ``` +/// use hyper::header::{Headers, PreferenceApplied, Preference}; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// PreferenceApplied(vec![Preference::RespondAsync]) +/// ); +/// ``` +/// ``` +/// use hyper::header::{Headers, PreferenceApplied, Preference}; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// PreferenceApplied(vec![ +/// Preference::RespondAsync, +/// Preference::ReturnRepresentation, +/// Preference::Wait(10u32), +/// Preference::Extension("foo".to_owned(), +/// "bar".to_owned(), +/// vec![]), +/// ]) +/// ); +/// ``` +#[derive(PartialEq, Clone, Debug)] +pub struct PreferenceApplied(pub Vec<Preference>); + +__hyper__deref!(PreferenceApplied => Vec<Preference>); + +impl Header for PreferenceApplied { + fn header_name() -> &'static str { + "Preference-Applied" + } + + fn parse_header(raw: &[Vec<u8>]) -> ::Result<PreferenceApplied> { + let preferences = try!(from_comma_delimited(raw)); + if !preferences.is_empty() { + Ok(PreferenceApplied(preferences)) + } else { + Err(::Error::Header) + } + } +} + +impl HeaderFormat for PreferenceApplied { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + let preferences: Vec<_> = self.0.iter().map(|pref| match pref { + // The spec ignores parameters in `Preferences-Applied` + &Preference::Extension(ref name, ref value, _) => Preference::Extension( + name.to_owned(), + value.to_owned(), + vec![] + ), + preference @ _ => preference.clone() + }).collect(); + fmt_comma_delimited(f, &preferences) + } +} + +#[cfg(test)] +mod tests { + use header::{HeaderFormat, Preference}; + use super::*; + + #[test] + fn test_format_ignore_parameters() { + assert_eq!( + format!("{}", &PreferenceApplied(vec![Preference::Extension( + "foo".to_owned(), + "bar".to_owned(), + vec![("bar".to_owned(), "foo".to_owned()), ("buz".to_owned(), "".to_owned())] + )]) as &(HeaderFormat + Send + Sync)), + "foo=bar".to_owned() + ); + } +} + +bench_header!(normal, + PreferenceApplied, { vec![b"respond-async, return=representation".to_vec(), b"wait=100".to_vec()] });
Add prefer header I'd like to use the [`Prefer`](http://tools.ietf.org/html/rfc7240) header, could types for this header be added?
This is the first I've heard of this header. Is there a situation where its usage is common? If you look at the [PostgREST](http://postgrest.com/api/reading/) project you'll see it's being used to suppress counts and in a few other cases. The [spec](http://tools.ietf.org/html/rfc7240#section-2.1) also gives some interesting examples. For my usage I'd like to explore the header for styling a response. For example: `Prefer: case=camel` or `Prefer: envelope`. To me, the `Prefer` header represents the configuration of some niche behaviors. Basically it's an optional `Expect`.
2016-03-24T18:12:17Z
0.8
c85b056cabd1bbe62340af03696810c7e155fe17
hyperium/hyper
743
hyperium__hyper-743
[ "683" ]
028f5864324f95d4d9007c304358b6e7b91743fc
diff --git a/src/header/common/cache_control.rs b/src/header/common/cache_control.rs --- a/src/header/common/cache_control.rs +++ b/src/header/common/cache_control.rs @@ -1,7 +1,7 @@ use std::fmt; use std::str::FromStr; use header::{Header, HeaderFormat}; -use header::parsing::{from_one_comma_delimited, fmt_comma_delimited}; +use header::parsing::{from_comma_delimited, fmt_comma_delimited}; /// `Cache-Control` header, defined in [RFC7234](https://tools.ietf.org/html/rfc7234#section-5.2) /// diff --git a/src/header/common/cache_control.rs b/src/header/common/cache_control.rs --- a/src/header/common/cache_control.rs +++ b/src/header/common/cache_control.rs @@ -55,10 +55,7 @@ impl Header for CacheControl { } fn parse_header(raw: &[Vec<u8>]) -> ::Result<CacheControl> { - let directives = raw.iter() - .filter_map(|line| from_one_comma_delimited(&line[..]).ok()) - .collect::<Vec<Vec<CacheDirective>>>() - .concat(); + let directives = try!(from_comma_delimited(raw)); if !directives.is_empty() { Ok(CacheControl(directives)) } else { diff --git a/src/header/common/range.rs b/src/header/common/range.rs --- a/src/header/common/range.rs +++ b/src/header/common/range.rs @@ -2,7 +2,7 @@ use std::fmt::{self, Display}; use std::str::FromStr; use header::{Header, HeaderFormat}; -use header::parsing::{from_one_raw_str, from_one_comma_delimited}; +use header::parsing::{from_one_raw_str, from_comma_delimited}; /// `Range` header, defined in [RFC7233](https://tools.ietf.org/html/rfc7233#section-3.1) /// diff --git a/src/header/common/range.rs b/src/header/common/range.rs --- a/src/header/common/range.rs +++ b/src/header/common/range.rs @@ -130,7 +130,7 @@ impl FromStr for Range { match (iter.next(), iter.next()) { (Some("bytes"), Some(ranges)) => { - match from_one_comma_delimited(ranges.as_bytes()) { + match from_comma_delimited(&[ranges]) { Ok(ranges) => { if ranges.is_empty() { return Err(::Error::Header); diff --git a/src/header/parsing.rs b/src/header/parsing.rs --- a/src/header/parsing.rs +++ b/src/header/parsing.rs @@ -23,24 +23,18 @@ pub fn from_raw_str<T: str::FromStr>(raw: &[u8]) -> ::Result<T> { /// Reads a comma-delimited raw header into a Vec. #[inline] -pub fn from_comma_delimited<T: str::FromStr>(raw: &[Vec<u8>]) -> ::Result<Vec<T>> { - if raw.len() != 1 { - return Err(::Error::Header); +pub fn from_comma_delimited<T: str::FromStr, S: AsRef<[u8]>>(raw: &[S]) -> ::Result<Vec<T>> { + let mut result = Vec::new(); + for s in raw { + let s = try!(str::from_utf8(s.as_ref())); + result.extend(s.split(',') + .filter_map(|x| match x.trim() { + "" => None, + y => Some(y) + }) + .filter_map(|x| x.parse().ok())) } - // we JUST checked that raw.len() == 1, so raw[0] WILL exist. - from_one_comma_delimited(& unsafe { raw.get_unchecked(0) }[..]) -} - -/// Reads a comma-delimited raw string into a Vec. -pub fn from_one_comma_delimited<T: str::FromStr>(raw: &[u8]) -> ::Result<Vec<T>> { - let s = try!(str::from_utf8(raw)); - Ok(s.split(',') - .filter_map(|x| match x.trim() { - "" => None, - y => Some(y) - }) - .filter_map(|x| x.parse().ok()) - .collect()) + Ok(result) } /// Format an array into a comma-delimited string.
diff --git a/src/header/common/content_length.rs b/src/header/common/content_length.rs --- a/src/header/common/content_length.rs +++ b/src/header/common/content_length.rs @@ -79,7 +79,16 @@ __hyper__tm!(ContentLength, tests { test_header!(test1, vec![b"3495"], Some(HeaderField(3495))); test_header!(test_invalid, vec![b"34v95"], None); - test_header!(test_duplicates, vec![b"5", b"5"], Some(HeaderField(5))); + + // Can't use the test_header macro because "5, 5" gets cleaned to "5". + #[test] + fn test_duplicates() { + let parsed = HeaderField::parse_header(&[b"5"[..].into(), + b"5"[..].into()]).unwrap(); + assert_eq!(parsed, HeaderField(5)); + assert_eq!(format!("{}", parsed), "5"); + } + test_header!(test_duplicates_vary, vec![b"5", b"6", b"5"], None); }); diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -156,8 +156,15 @@ macro_rules! test_header { assert_eq!(val.ok(), typed); // Test formatting if typed.is_some() { - let res: &str = str::from_utf8($raw[0]).unwrap(); - assert_eq!(format!("{}", typed.unwrap()), res); + let raw = &($raw)[..]; + let mut iter = raw.iter().map(|b|str::from_utf8(&b[..]).unwrap()); + let mut joined = String::new(); + joined.push_str(iter.next().unwrap()); + for s in iter { + joined.push_str(", "); + joined.push_str(s); + } + assert_eq!(format!("{}", typed.unwrap()), joined); } } } diff --git a/src/header/common/transfer_encoding.rs b/src/header/common/transfer_encoding.rs --- a/src/header/common/transfer_encoding.rs +++ b/src/header/common/transfer_encoding.rs @@ -38,6 +38,13 @@ header! { Some(HeaderField( vec![Encoding::Gzip, Encoding::Chunked] ))); + // Issue: #683 + test_header!( + test2, + vec![b"chunked", b"chunked"], + Some(HeaderField( + vec![Encoding::Chunked, Encoding::Chunked] + ))); } }
Response with multiple `Transfer-Encoding: chunked` header fields not parsed as chunk I've adapted this code from `client/response.rs`: ``` rust fn main() { let stream = MockStream::with_input(b"\ HTTP/1.1 200 OK\r\n\ Transfer-Encoding: chunked\r\n\ Transfer-Encoding: chunked\r\n\ \r\n\ 1\r\n\ q\r\n\ 2\r\n\ we\r\n\ 2\r\n\ rt\r\n\ 0\r\n\ \r\n" ); let url = Url::parse("http://hyper.rs").unwrap(); let mut res = Response::new(url, Box::new(stream)).unwrap(); let mut s = String::new(); res.read_to_string(&mut s).unwrap(); println!("{:?}", s); } ``` The result is: `"1\r\nq\r\n2\r\nwe\r\n2\r\nrt\r\n0\r\n\r\n"` Unless I'm misreading the HTTP spec, it seems ``` HTTP/1.1 200 OK\r\n Transfer-Encoding: chunked\r\n Transfer-Encoding: chunked\r\n ``` should be the same as ``` HTTP/1.1 200 OK\r\n Transfer-Encoding: chunked, chunked\r\n ``` The latter correctly results in `"qwert"` being printed out.
Indeed, it would seem the bug is in the parsing of the `TransferEncoding` header. It should handle more than 1 field occurrence. @seanmonstar I'm running into this issue myself, but I'm not sure how/where to best fix it. Any pointers where I should start looking? This occurs in the parsing. `TransferEncoding` uses [`parsing::from_comma_delimited()`](https://github.com/hyperium/hyper/blob/master/src/header/parsing.rs#L27), which currently only allows 1 line of a header. I cannot recall if there are any headers that are comma separated but should be rejected if there is more than one line. If not, then the fix would be in the `from_comma_delimited` method to check all the lines, not just the first. I have written a parser for comma-delimited headers that should catch all cases like multiline headers, too much whitespace and superfluos commas. https://github.com/pyfisch/kinglet/blob/master/src/headers.rs#L54-L100
2016-03-11T20:08:29Z
0.8
c85b056cabd1bbe62340af03696810c7e155fe17
hyperium/hyper
718
hyperium__hyper-718
[ "715" ]
a4230eb510224b3a52e0f2d616fade8f0e8313b9
diff --git a/src/buffer.rs b/src/buffer.rs --- a/src/buffer.rs +++ b/src/buffer.rs @@ -79,7 +79,7 @@ unsafe fn grow_zerofill(buf: &mut Vec<u8>, additional: usize) { use std::ptr; let len = buf.len(); buf.set_len(len + additional); - ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()); + ptr::write_bytes(buf.as_mut_ptr().offset(len as isize), 0, buf.len()); } impl<R: Read> Read for BufReader<R> {
diff --git a/src/buffer.rs b/src/buffer.rs --- a/src/buffer.rs +++ b/src/buffer.rs @@ -151,4 +151,14 @@ mod tests { assert_eq!(rdr.pos, 0); assert_eq!(rdr.cap, 0); } + + #[test] + fn test_resize() { + let raw = b"hello world"; + let mut rdr = BufReader::with_capacity(&raw[..], 5); + rdr.read_into_buf().unwrap(); + assert_eq!(rdr.get_buf(), b"hello"); + rdr.read_into_buf().unwrap(); + assert_eq!(rdr.get_buf(), b"hello world"); + } }
Odd error when unwrapping a response I'm getting a weird error when trying to get data from this API. Any help would be appreciated. ``` rust let client = Client::new(); let mut res = client.get(&"https://data.medicare.gov/resource/pqp8-xrjv.json?$limit=1".to_string()) .send().unwrap(); ``` ``` thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value: Version', ../src/libcore/result.rs:738 ```
Hm, what version of hyper? I just tried that URL using https://github.com/hyperium/hyper/blob/master/examples/client.rs and it worked for me. Was on 0.6 when I posted the issue. Updated to 0.7 and still getting the same thing. Here's the log incase it helps ``` TRACE:hyper::header: Headers.set( "Connection", Connection([Close]) ) TRACE:hyper::client: send Get Url { scheme: "https", scheme_data: Relative(RelativeSchemeData { username: "", password: None, host: Domain("data.medicare.gov"), port: None, default_port: Some(443), path: ["resource", "pqp8-xrjv.json"] }), query: Some("$limit=1"), fragment: None } TRACE:hyper::client: host="data.medicare.gov" TRACE:hyper::client: port=443 DEBUG:hyper::net: https scheme TRACE:hyper::client: host="data.medicare.gov" TRACE:hyper::client: port=443 TRACE:hyper::header: Headers.set( "Host", Host { hostname: "data.medicare.gov", port: Some(443) } ) DEBUG:hyper::http::h1: request line: Get "/resource/pqp8-xrjv.json?$limit=1" Http11 DEBUG:hyper::http::h1: headers=Headers { Host: data.medicare.gov, Connection: close, } TRACE:hyper::client::response: Response::with_message TRACE:hyper::client::pool: previous_response_expected_no_content false TRACE:hyper::http::h1: previous_response_expected_no_content = false TRACE:hyper::buffer: get_buf [] TRACE:hyper::buffer: read_into_buf buf[0..4096] TRACE:hyper::buffer: get_buf [u8; 4096][0..4096] TRACE:hyper::http::h1: try_parse([72, 84, 84, 80, 47, 49, 46, 49, 32, 50, 48, 48, 32, 79, 75, 13, 10, 83, 101, 114, 118, 101, 114, 58, 32, 110, 103, 105, 110, 120, 13, 10, 68, 97, 116, 101, 58, 32, 77, 111, 110, 44, 32, 48, 52, 32, 74, 97, 110, 32, 50, 48, 49, 54, 32, 50, 50, 58, 50, 54, 58, 52, 50, 32, 71, 77, 84, 13, 10, 67, 111, 110, 116, 101, 110, 116, 45, 84, 121, 112, 101, 58, 32, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 47, 106, 115, 111, 110, 59, 32, 99, 104, 97, 114, 115, 101, 116, 61, 117, 116, 102, 45, 56, 13, 10, 84, 114, 97, 110, 115, 102, 101, 114, 45, 69, 110, 99, 111, 100, 105, 110, 103, 58, 32, 99, 104, 117, 110, 107, 101, 100, 13, 10, 67, 111, 110, 110, 101, 99, 116, 105, 111, 110, 58, 32, 99, 108, 111, 115, 101, 13, 10, 65, 99, 99, 101, 115, 115, 45, 67, 111, 110, 116, 114, 111, 108, 45, 65, 108, 108, 111, 119, 45, 79, 114, 105, 103, 105, 110, 58, 32, 42, 13, 10, 69, 84, 97, 103, 58, 32, 34, 50, 52, 49, 48, 51, 56, 99, 97, 49, 57, 102, 55, 52, 50, 48, 52, 55, 97, 101, 98, 100, 48, 48, 55, 57, 54, 98, 57, 55, 98, 57, 48, 34, 13, 10, 76, 97, 115, 116, 45, 77, 111, 100, 105, 102, 105, 101, 100, 58, 32, 84, 104, 117, 44, 32, 51, 49, 32, 68, 101, 99, 32, 50, 48, 49, 53, 32, 49, 49, 58, 49, 50, 58, 51, 54, 32, 80, 83, 84, 13, 10, 88, 45, 83, 79, 68, 65, 50, 45, 87, 97, 114, 110, 105, 110, 103, 58, 32, 88, 45, 83, 79, 68, 65, 50, 45, 70, 105, 101, 108, 100, 115, 44, 32, 88, 45, 83, 79, 68, 65, 50, 45, 84, 121, 112, 101, 115, 44, 32, 97, 110, 100, 32, 88, 45, 83, 79, 68, 65, 50, 45, 76, 101, 103, 97, 99, 121, 45, 84, 121, 112, 101, 115, 32, 97, 114, 101, 32, 100, 101, 112, 114, 101, 99, 97, 116, 101, 100, 13, 10, 88, 45, 83, 79, 68, 65, 50, 45, 70, 105, 101, 108, 100, 115, 58, 32, 91, 34, 105, 115, 95, 115, 117, 112, 112, 108, 105, 101, 114, 95, 112, 97, 114, 116, 105, 99, 105, 112, 97, 116, 105, 110, 103, 34, 44, 34, 117, 108, 116, 114, 97, 118, 105, 111, 108, 101, 116, 95, 108, 105, 103, 104, 116, 95, 100, 101, 118, 105, 99, 101, 115, 34, 44, 34, 118, 111, 105, 99, 101, 95, 112, 114, 111, 115, 116, 104, 101, 116, 105, 99, 115, 34, 44, 34, 99, 105, 116, 121, 34, 44, 34, 101, 120, 116, 101, 114, 110, 97, 108, 95, 105, 110, 102, 117, 115, 105, 111, 110, 95, 112, 117, 109, 112, 115, 95, 97, 110, 100, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 44, 34, 99, 111, 109, 109, 111, 100, 101, 115, 95, 117, 114, 105, 110, 97, 108, 115, 95, 98, 101, 100, 112, 97, 110, 115, 34, 44, 34, 115, 116, 97, 110, 100, 97, 114, 100, 95, 109, 111, 98, 105, 108, 105, 116, 121, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 97, 110, 100, 95, 114, 101, 108, 97, 116, 101, 100, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 44, 34, 104, 111, 115, 112, 105, 116, 97, 108, 95, 98, 101, 100, 115, 95, 97, 110, 100, 95, 114, 101, 108, 97, 116, 101, 100, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 44, 34, 99, 97, 110, 101, 115, 95, 99, 114, 117, 116, 99, 104, 101, 115, 34, 44, 34, 111, 114, 116, 104, 111, 115, 101, 115, 95, 111, 102, 102, 95, 116, 104, 101, 95, 115, 104, 101, 108, 102, 34, 44, 34, 100, 121, 110, 97, 109, 105, 99, 95, 115, 112, 108, 105, 110, 116, 115, 34, 44, 34, 112, 114, 111, 115, 116, 104, 101, 116, 105, 99, 95, 108, 101, 110, 115, 101, 115, 95, 99, 111, 110, 118, 101, 110, 116, 105, 111, 110, 97, 108, 95, 99, 111, 110, 116, 97, 99, 116, 95, 108, 101, 110, 115, 101, 115, 34, 44, 34, 105, 110, 102, 114, 97, 114, 101, 100, 95, 104, 101, 97, 116, 105, 110, 103, 95, 112, 97, 100, 95, 115, 121, 115, 116, 101, 109, 115, 34, 44, 34, 104, 111, 115, 112, 105, 116, 97, 108, 95, 98, 101, 100, 115, 95, 109, 97, 110, 117, 97, 108, 34, 44, 34, 99, 112, 97, 112, 95, 100, 101, 118, 105, 99, 101, 115, 95, 114, 101, 115, 112, 105, 114, 97, 116, 111, 114, 121, 95, 97, 115, 115, 105, 115, 116, 95, 100, 101, 118, 105, 99, 101, 115, 95, 97, 110, 100, 95, 114, 101, 108, 97, 116, 101, 100, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 97, 110, 100, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 44, 34, 111, 115, 116, 101, 111, 103, 101, 110, 101, 115, 105, 115, 95, 115, 116, 105, 109, 117, 108, 97, 116, 111, 114, 115, 34, 44, 34, 112, 97, 114, 101, 110, 116, 101, 114, 97, 108, 95, 110, 117, 116, 114, 105, 101, 110, 116, 115, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 44, 34, 98, 108, 111, 111, 100, 95, 103, 108, 117, 99, 111, 115, 101, 95, 109, 111, 110, 105, 116, 111, 114, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 110, 111, 110, 95, 109, 97, 105, 108, 95, 111, 114, 100, 101, 114, 34, 44, 34, 115, 117, 112, 112, 111, 114, 116, 95, 115, 117, 114, 102, 97, 99, 101, 115, 95, 103, 114, 111, 117, 112, 95, 50, 95, 109, 97, 116, 116, 114, 101, 115, 115, 101, 115, 95, 97, 110, 100, 95, 111, 118, 101, 114, 108, 97, 121, 115, 34, 44, 34, 97, 100, 100, 114, 101, 115, 115, 95, 50, 34, 44, 34, 112, 97, 116, 105, 101, 110, 116, 95, 108, 105, 102, 116, 115, 34, 44, 34, 100, 98, 97, 95, 110, 97, 109, 101, 34, 44, 34, 111, 114, 116, 104, 111, 115, 101, 115, 95, 112, 114, 101, 102, 97, 98, 114, 105, 99, 97, 116, 101, 100, 34, 44, 34, 100, 105, 97, 98, 101, 116, 105, 99, 95, 115, 104, 111, 101, 115, 95, 105, 110, 115, 101, 114, 116, 115, 95, 99, 117, 115, 116, 111, 109, 95, 102, 97, 98, 114, 105, 99, 97, 116, 101, 100, 34, 44, 34, 115, 101, 97, 116, 95, 108, 105, 102, 116, 95, 109, 101, 99, 104, 97, 110, 105, 115, 109, 115, 34, 44, 34, 99, 111, 109, 112, 101, 116, 105, 116, 105, 118, 101, 95, 98, 105, 100, 95, 115, 101, 114, 118, 105, 99, 101, 95, 97, 114, 101, 97, 34, 44, 34, 112, 111, 119, 101, 114, 95, 111, 112, 101, 114, 97, 116, 101, 100, 95, 118, 101, 104, 105, 99, 108, 101, 115, 95, 115, 99, 111, 111, 116, 101, 114, 115, 34, 44, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 95, 115, 116, 97, 110, 100, 97, 114, 100, 95, 109, 97, 110, 117, 97, 108, 95, 112, 101, 100, 105, 97, 116, 114, 105, 99, 115, 34, 44, 34, 115, 117, 112, 112, 111, 114, 116, 95, 115, 117, 114, 102, 97, 99, 101, 115, 95, 112, 114, 101, 115, 115, 117, 114, 101, 95, 114, 101, 100, 117, 99, 105, 110, 103, 95, 98, 101, 100, 115, 95, 109, 97, 116, 116, 114, 101, 115, 115, 101, 115, 95, 111, 118, 101, 114, 108, 97, 121, 115, 95, 112, 97, 100, 115, 34, 44, 34, 122, 105, 112, 95, 112, 108, 117, 115, 95, 52, 34, 44, 34, 103, 97, 115, 116, 114, 105, 99, 95, 115, 117, 99, 116, 105, 111, 110, 95, 112, 117, 109, 112, 115, 34, 44, 34, 105, 110, 102, 117, 115, 105, 111, 110, 95, 112, 117, 109, 112, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 105, 110, 115, 117, 108, 105, 110, 95, 105, 110, 102, 117, 115, 105, 111, 110, 34, 44, 34, 58, 99, 114, 101, 97, 116, 101, 100, 95, 97, 116, 34, 44, 34, 105, 110, 102, 117, 115, 105, 111, 110, 95, 112, 117, 109, 112, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 105, 109, 112, 108, 97, 110, 116, 101, 100, 95, 105, 110, 102, 117, 115, 105, 111, 110, 34, 44, 34, 110, 101, 117, 114, 111, 115, 116, 105, 109, 117, 108, 97, 116, 111, 114, 115, 34, 44, 34, 105, 110, 102, 117, 115, 105, 111, 110, 95, 112, 117, 109, 112, 115, 95, 105, 109, 112, 108, 97, 110, 116, 97, 98, 108, 101, 95, 97, 110, 100, 95, 117, 110, 105, 110, 116, 101, 114, 114, 117, 112, 116, 101, 100, 34, 44, 34, 104, 101, 109, 111, 100, 105, 97, 108, 121, 115, 105, 115, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 44, 34, 116, 114, 97, 110, 115, 99, 117, 116, 97, 110, 101, 111, 117, 115, 95, 101, 108, 101, 99, 116, 114, 105, 99, 97, 108, 95, 110, 101, 114, 118, 101, 95, 115, 116, 105, 109, 117, 108, 97, 116, 111, 114, 115, 95, 116, 101, 110, 115, 95, 117, 110, 105, 116, 115, 34, 44, 34, 108, 105, 109, 98, 95, 112, 114, 111, 115, 116, 104, 101, 115, 101, 115, 34, 44, 34, 109, 101, 99, 104, 97, 110, 105, 99, 97, 108, 95, 105, 110, 95, 101, 120, 115, 117, 102, 102, 108, 97, 116, 105, 111, 110, 95, 100, 101, 118, 105, 99, 101, 115, 34, 44, 34, 105, 110, 116, 114, 97, 112, 117, 108, 109, 111, 110, 97, 114, 121, 95, 112, 101, 114, 99, 117, 115, 115, 105, 118, 101, 95, 118, 101, 110, 116, 105, 108, 97, 116, 105, 111, 110, 95, 100, 101, 118, 105, 99, 101, 115, 34, 44, 34, 104, 105, 103, 104, 95, 102, 114, 101, 113, 117, 101, 110, 99, 121, 95, 99, 104, 101, 115, 116, 95, 119, 97, 108, 108, 95, 111, 115, 99, 105, 108, 108, 97, 116, 105, 111, 110, 95, 104, 102, 99, 119, 111, 95, 100, 101, 118, 105, 99, 101, 115, 34, 44, 34, 105, 110, 102, 117, 115, 105, 111, 110, 95, 112, 117, 109, 112, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 101, 120, 116, 101, 114, 110, 97, 108, 95, 105, 110, 102, 117, 115, 105, 111, 110, 34, 44, 34, 101, 110, 116, 101, 114, 97, 108, 95, 110, 117, 116, 114, 105, 101, 110, 116, 115, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 97, 110, 100, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 44, 34, 112, 110, 101, 117, 109, 97, 116, 105, 99, 95, 99, 111, 109, 112, 114, 101, 115, 115, 105, 111, 110, 95, 100, 101, 118, 105, 99, 101, 115, 34, 44, 34, 104, 111, 109, 101, 95, 100, 105, 97, 108, 121, 115, 105, 115, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 44, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 95, 115, 116, 97, 110, 100, 97, 114, 100, 95, 109, 97, 110, 117, 97, 108, 34, 44, 34, 102, 97, 99, 105, 97, 108, 95, 112, 114, 111, 115, 116, 104, 101, 115, 101, 115, 34, 44, 34, 101, 121, 101, 95, 112, 114, 111, 115, 116, 104, 101, 115, 101, 115, 34, 44, 34, 58, 105, 100, 34, 44, 34, 97, 117, 116, 111, 109, 97, 116, 105, 99, 95, 101, 120, 116, 101, 114, 110, 97, 108, 95, 100, 101, 102, 105, 98, 114, 105, 108, 108, 97, 116, 111, 114, 115, 95, 97, 101, 100, 115, 34, 44, 34, 98, 108, 111, 111, 100, 95, 103, 108, 117, 99, 111, 115, 101, 95, 109, 111, 110, 105, 116, 111, 114, 115, 95, 109, 97, 105, 108, 95, 111, 114, 100, 101, 114, 34, 44, 34, 112, 104, 111, 110, 101, 34, 44, 34, 119, 97, 108, 107, 101, 114, 115, 95, 97, 110, 100, 95, 114, 101, 108, 97, 116, 101, 100, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 44, 34, 111, 120, 121, 103, 101, 110, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 97, 110, 100, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 34, 44, 34, 101, 110, 116, 101, 114, 97, 108, 95, 110, 117, 116, 114, 105, 101, 110, 116, 115, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 44, 34, 110, 101, 98, 117, 108, 105, 122, 101, 114, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 117, 108, 116, 114, 97, 115, 111, 110, 105, 99, 95, 97, 110, 100, 95, 99, 111, 110, 116, 114, 111, 108, 108, 101, 100, 95, 100, 111, 115, 101, 34, 44, 34, 99, 111, 109, 112, 97, 110, 121, 95, 110, 97, 109, 101, 34, 44, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 95, 99, 111, 109, 112, 108, 101, 120, 95, 114, 101, 104, 97, 98, 105, 108, 105, 116, 97, 116, 105, 118, 101, 95, 109, 97, 110, 117, 97, 108, 34, 44, 34, 112, 114, 111, 115, 116, 104, 101, 116, 105, 99, 95, 108, 101, 110, 115, 101, 115, 95, 112, 114, 111, 115, 116, 104, 101, 116, 105, 99, 95, 99, 97, 116, 97, 114, 97, 99, 116, 95, 108, 101, 110, 115, 101, 115, 34, 44, 34, 114, 101, 115, 112, 105, 114, 97, 116, 111, 114, 121, 95, 115, 117, 99, 116, 105, 111, 110, 95, 112, 117, 109, 112, 115, 34, 44, 34, 110, 101, 117, 114, 111, 109, 117, 115, 99, 117, 108, 97, 114, 95, 101, 108, 101, 99, 116, 114, 105, 99, 97, 108, 95, 115, 116, 105, 109, 117, 108, 97, 116, 111, 114, 115, 95, 110, 109, 101, 115, 34, 44, 34, 119, 97, 108, 107, 101, 114, 115, 34, 44, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 95, 115, 116, 97, 110, 100, 97, 114, 100, 95, 112, 111, 119, 101, 114, 95, 112, 101, 100, 105, 97, 116, 114, 105, 99, 115, 34, 44, 34, 114, 101, 115, 112, 105, 114, 97, 116, 111, 114, 121, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 114, 101, 108, 97, 116, 101, 100, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 97, 110, 100, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 44, 34, 110, 101, 98, 117, 108, 105, 122, 101, 114, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 44, 34, 110, 101, 103, 97, 116, 105, 118, 101, 95, 112, 114, 101, 115, 115, 117, 114, 101, 95, 119, 111, 117, 110, 100, 95, 116, 104, 101, 114, 97, 112, 121, 95, 112, 117, 109, 112, 115, 95, 97, 110, 100, 95, 114, 101, 108, 97, 116, 101, 100, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 97, 110, 100, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 44, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 95, 115, 101, 97, 116, 105, 110, 103, 95, 99, 117, 115, 104, 105, 111, 110, 115, 95, 115, 107, 105, 110, 95, 112, 114, 111, 116, 101, 99, 116, 105, 110, 103, 34, 44, 34, 118, 101, 110, 116, 105, 108, 97, 116, 111, 114, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 44, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 95, 115, 101, 97, 116, 105, 110, 103, 95, 99, 117, 115, 104, 105, 111, 110, 115, 34, 44, 34, 99, 112, 97, 112, 95, 97, 110, 100, 95, 114, 97, 100, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 101, 95, 103, 95, 99, 111, 109, 98, 105, 110, 97, 116, 105, 111, 110, 95, 109, 97, 115, 107, 115, 34, 44, 34, 99, 112, 97, 112, 95, 114, 97, 100, 115, 95, 114, 101, 108, 97, 116, 101, 100, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 44, 34, 117, 114, 111, 108, 111, 103, 105, 99, 97, 108, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 44, 34, 98, 108, 111, 111, 100, 95, 103, 108, 117, 99, 111, 115, 101, 95, 109, 111, 110, 105, 116, 111, 114, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 109, 97, 105, 108, 95, 111, 114, 100, 101, 114, 34, 44, 34, 116, 114, 97, 99, 116, 105, 111, 110, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 34, 44, 34, 105, 110, 116, 101, 114, 109, 105, 116, 116, 101, 110, 116, 95, 112, 111, 115, 105, 116, 105, 118, 101, 95, 112, 114, 101, 115, 115, 117, 114, 101, 95, 98, 114, 101, 97, 116, 104, 105, 110, 103, 95, 105, 112, 112, 98, 95, 100, 101, 118, 105, 99, 101, 115, 34, 44, 34, 110, 101, 103, 97, 116, 105, 118, 101, 95, 112, 114, 101, 115, 115, 117, 114, 101, 95, 119, 111, 117, 110, 100, 95, 116, 104, 101, 114, 97, 112, 121, 95, 112, 117, 109, 112, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 44, 34, 115, 116, 97, 116, 101, 34, 44, 34, 103, 101, 110, 101, 114, 97, 108, 95, 104, 111, 109, 101, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 97, 110, 100, 95, 114, 101, 108, 97, 116, 101, 100, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 97, 110, 100, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 44, 34, 111, 114, 116, 104, 111, 115, 101, 115, 95, 99, 117, 115, 116, 111, 109, 95, 102, 97, 98, 114, 105, 99, 97, 116, 101, 100, 34, 44, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 95, 99, 111, 109, 112, 108, 101, 120, 95, 114, 101, 104, 97, 98, 105, 108, 105, 116, 97, 116, 105, 118, 101, 95, 112, 111, 119, 101, 114, 34, 44, 34, 111, 115, 116, 111, 109, 121, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 44, 34, 104, 111, 115, 112, 105, 116, 97, 108, 95, 98, 101, 100, 115, 95, 109, 97, 110, 117, 97, 108, 95, 112, 101, 100, 105, 97, 116, 114, 105, 99, 34, 44, 34, 104, 111, 115, 112, 105, 116, 97, 108, 95, 98, 101, 100, 115, 95, 101, 108, 101, 99, 116, 114, 105, 99, 34, 44, 34, 99, 111, 110, 116, 105, 110, 117, 111, 117, 115, 95, 112, 97, 115, 115, 105, 118, 101, 95, 109, 111, 116, 105, 111, 110, 95, 99, 112, 109, 95, 100, 101, 118, 105, 99, 101, 115, 34, 44, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 95, 115, 116, 97, 110, 100, 97, 114, 100, 95, 112, 111, 119, 101, 114, 34, 44, 34, 98, 114, 101, 97, 115, 116, 95, 112, 114, 111, 115, 116, 104, 101, 115, 101, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 44, 34, 122, 105, 112, 34, 44, 34, 115, 116, 97, 110, 100, 97, 114, 100, 95, 112, 111, 119, 101, 114, 95, 109, 97, 110, 117, 97, 108, 95, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 115, 95, 115, 99, 111, 111, 116, 101, 114, 115, 95, 97, 110, 100, 95, 114, 101, 108, 97, 116, 101, 100, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 44, 34, 115, 117, 112, 112, 111, 114, 116, 95, 115, 117, 114, 102, 97, 99, 101, 115, 34, 44, 34, 58, 117, 112, 100, 97, 116, 101, 100, 95, 97, 116, 34, 44, 34, 116, 114, 97, 99, 104, 101, 111, 115, 116, 111, 109, 121, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 44, 34, 111, 120, 121, 103, 101, 110, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 44, 34, 111, 99, 117, 108, 97, 114, 95, 112, 114, 111, 115, 116, 104, 101, 115, 101, 115, 34, 44, 34, 109, 97, 105, 108, 95, 111, 114, 100, 101, 114, 95, 100, 105, 97, 98, 101, 116, 105, 99, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 44, 34, 115, 117, 114, 103, 105, 99, 97, 108, 95, 100, 114, 101, 115, 115, 105, 110, 103, 115, 34, 44, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 95, 99, 111, 109, 112, 108, 101, 120, 95, 114, 101, 104, 97, 98, 105, 108, 105, 116, 97, 116, 105, 118, 101, 95, 112, 111, 119, 101, 114, 95, 101, 95, 103, 95, 103, 114, 111, 117, 112, 95, 51, 95, 103, 114, 111, 117, 112, 95, 52, 95, 103, 114, 111, 117, 112, 95, 53, 34, 44, 34, 115, 111, 109, 97, 116, 105, 99, 95, 112, 114, 111, 115, 116, 104, 101, 115, 101, 115, 34, 44, 34, 104, 111, 115, 112, 105, 116, 97, 108, 95, 98, 101, 100, 115, 95, 116, 111, 116, 97, 108, 95, 101, 108, 101, 99, 116, 114, 105, 99, 95, 112, 101, 100, 105, 97, 116, 114, 105, 99, 34, 44, 34, 104, 101, 97, 116, 95, 99, 111, 108, 100, 95, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 115, 34, 44, 34, 97, 100, 100, 114, 101, 115, 115, 34, 44, 34, 101, 110, 116, 101, 114, 97, 108, 95, 110, 117, 116, 114, 105, 101, 110, 116, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 102, 111, 114, 95, 115, 112, 101, 99, 105, 97, 108, 95, 109, 101, 116, 97, 98, 111, 108, 105, 99, 95, 110, 101, 101, 100, 115, 95, 97, 110, 100, 95, 112, 101, 100, 105, 97, 116, 114, 105, 99, 115, 34, 44, 34, 105, 110, 118, 97, 115, 105, 118, 101, 95, 109, 101, 99, 104, 97, 110, 105, 99, 97, 108, 95, 118, 101, 110, 116, 105, 108, 97, 116, 105, 111, 110, 34, 44, 34, 112, 114, 111, 115, 116, 104, 101, 116, 105, 99, 95, 108, 101, 110, 115, 101, 115, 95, 99, 111, 110, 118, 101, 110, 116, 105, 111, 110, 97, 108, 95, 101, 121, 101, 103, 108, 97, 115, 115, 101, 115, 34, 44, 34, 99, 111, 99, 104, 108, 101, 97, 114, 95, 105, 109, 112, 108, 97, 110, 116, 115, 34, 44, 34, 100, 105, 97, 98, 101, 116, 105, 99, 95, 115, 104, 111, 101, 115, 95, 105, 110, 115, 101, 114, 116, 115, 95, 112, 114, 101, 102, 97, 98, 114, 105, 99, 97, 116, 101, 100, 34, 44, 34, 115, 112, 101, 101, 99, 104, 95, 103, 101, 110, 101, 114, 97, 116, 105, 110, 103, 95, 100, 101, 118, 105, 99, 101, 115, 34, 93, 13, 10]) TRACE:hyper::http::h1: Response.try_parse([Header; 100], [u8; 4096]) TRACE:hyper::buffer: reserved 28672 TRACE:hyper::buffer: read_into_buf buf[4096..32768] TRACE:hyper::buffer: get_buf [u8; 32768][0..10335] TRACE:hyper::http::h1: try_parse([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 88, 45, 83, 79, 68, 65, 50, 45, 84, 121, 112, 101, 115, 58, 32, 91, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 116, 101, 120, 116, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 116, 101, 120, 116, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 116, 101, 120, 116, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 116, 101, 120, 116, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 110, 117, 109, 98, 101, 114, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 109, 101, 116, 97, 95, 100, 97, 116, 97, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 109, 101, 116, 97, 95, 100, 97, 116, 97, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 116, 101, 120, 116, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 116, 101, 120, 116, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 116, 101, 120, 116, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 116, 101, 120, 116, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 109, 101, 116, 97, 95, 100, 97, 116, 97, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 116, 101, 120, 116, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 44, 34, 99, 104, 101, 99, 107, 98, 111, 120, 34, 93, 13, 10, 88, 45, 83, 79, 68, 65, 50, 45, 76, 101, 103, 97, 99, 121, 45, 84, 121, 112, 101, 115, 58, 32, 116, 114, 117, 101, 13, 10, 88, 45, 83, 111, 99, 114, 97, 116, 97, 45, 82, 101, 103, 105, 111, 110, 58, 32, 112, 114, 111, 100, 117, 99, 116, 105, 111, 110, 13, 10, 65, 103, 101, 58, 32, 48, 13, 10, 13, 10, 49, 51, 56, 54, 13, 10, 91, 32, 123, 10, 32, 32, 34, 105, 115, 95, 115, 117, 112, 112, 108, 105, 101, 114, 95, 112, 97, 114, 116, 105, 99, 105, 112, 97, 116, 105, 110, 103, 34, 32, 58, 32, 116, 114, 117, 101, 44, 10, 32, 32, 34, 117, 108, 116, 114, 97, 118, 105, 111, 108, 101, 116, 95, 108, 105, 103, 104, 116, 95, 100, 101, 118, 105, 99, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 118, 111, 105, 99, 101, 95, 112, 114, 111, 115, 116, 104, 101, 116, 105, 99, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 99, 105, 116, 121, 34, 32, 58, 32, 34, 65, 78, 67, 72, 79, 82, 65, 71, 69, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 44, 10, 32, 32, 34, 101, 120, 116, 101, 114, 110, 97, 108, 95, 105, 110, 102, 117, 115, 105, 111, 110, 95, 112, 117, 109, 112, 115, 95, 97, 110, 100, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 99, 111, 109, 109, 111, 100, 101, 115, 95, 117, 114, 105, 110, 97, 108, 115, 95, 98, 101, 100, 112, 97, 110, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 104, 111, 115, 112, 105, 116, 97, 108, 95, 98, 101, 100, 115, 95, 97, 110, 100, 95, 114, 101, 108, 97, 116, 101, 100, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 115, 116, 97, 110, 100, 97, 114, 100, 95, 109, 111, 98, 105, 108, 105, 116, 121, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 97, 110, 100, 95, 114, 101, 108, 97, 116, 101, 100, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 99, 97, 110, 101, 115, 95, 99, 114, 117, 116, 99, 104, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 111, 114, 116, 104, 111, 115, 101, 115, 95, 111, 102, 102, 95, 116, 104, 101, 95, 115, 104, 101, 108, 102, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 100, 121, 110, 97, 109, 105, 99, 95, 115, 112, 108, 105, 110, 116, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 112, 114, 111, 115, 116, 104, 101, 116, 105, 99, 95, 108, 101, 110, 115, 101, 115, 95, 99, 111, 110, 118, 101, 110, 116, 105, 111, 110, 97, 108, 95, 99, 111, 110, 116, 97, 99, 116, 95, 108, 101, 110, 115, 101, 115, 34, 32, 58, 32, 116, 114, 117, 101, 44, 10, 32, 32, 34, 105, 110, 102, 114, 97, 114, 101, 100, 95, 104, 101, 97, 116, 105, 110, 103, 95, 112, 97, 100, 95, 115, 121, 115, 116, 101, 109, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 104, 111, 115, 112, 105, 116, 97, 108, 95, 98, 101, 100, 115, 95, 109, 97, 110, 117, 97, 108, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 99, 112, 97, 112, 95, 100, 101, 118, 105, 99, 101, 115, 95, 114, 101, 115, 112, 105, 114, 97, 116, 111, 114, 121, 95, 97, 115, 115, 105, 115, 116, 95, 100, 101, 118, 105, 99, 101, 115, 95, 97, 110, 100, 95, 114, 101, 108, 97, 116, 101, 100, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 97, 110, 100, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 111, 115, 116, 101, 111, 103, 101, 110, 101, 115, 105, 115, 95, 115, 116, 105, 109, 117, 108, 97, 116, 111, 114, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 112, 97, 114, 101, 110, 116, 101, 114, 97, 108, 95, 110, 117, 116, 114, 105, 101, 110, 116, 115, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 98, 108, 111, 111, 100, 95, 103, 108, 117, 99, 111, 115, 101, 95, 109, 111, 110, 105, 116, 111, 114, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 110, 111, 110, 95, 109, 97, 105, 108, 95, 111, 114, 100, 101, 114, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 115, 117, 112, 112, 111, 114, 116, 95, 115, 117, 114, 102, 97, 99, 101, 115, 95, 103, 114, 111, 117, 112, 95, 50, 95, 109, 97, 116, 116, 114, 101, 115, 115, 101, 115, 95, 97, 110, 100, 95, 111, 118, 101, 114, 108, 97, 121, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 97, 100, 100, 114, 101, 115, 115, 95, 50, 34, 32, 58, 32, 34, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 44, 10, 32, 32, 34, 112, 97, 116, 105, 101, 110, 116, 95, 108, 105, 102, 116, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 100, 98, 97, 95, 110, 97, 109, 101, 34, 32, 58, 32, 34, 65, 76, 65, 83, 75, 65, 32, 69, 89, 69, 32, 67, 65, 82, 69, 32, 67, 69, 78, 84, 69, 82, 83, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 44, 10, 32, 32, 34, 111, 114, 116, 104, 111, 115, 101, 115, 95, 112, 114, 101, 102, 97, 98, 114, 105, 99, 97, 116, 101, 100, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 100, 105, 97, 98, 101, 116, 105, 99, 95, 115, 104, 111, 101, 115, 95, 105, 110, 115, 101, 114, 116, 115, 95, 99, 117, 115, 116, 111, 109, 95, 102, 97, 98, 114, 105, 99, 97, 116, 101, 100, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 115, 101, 97, 116, 95, 108, 105, 102, 116, 95, 109, 101, 99, 104, 97, 110, 105, 115, 109, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 112, 111, 119, 101, 114, 95, 111, 112, 101, 114, 97, 116, 101, 100, 95, 118, 101, 104, 105, 99, 108, 101, 115, 95, 115, 99, 111, 111, 116, 101, 114, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 95, 115, 116, 97, 110, 100, 97, 114, 100, 95, 109, 97, 110, 117, 97, 108, 95, 112, 101, 100, 105, 97, 116, 114, 105, 99, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 115, 117, 112, 112, 111, 114, 116, 95, 115, 117, 114, 102, 97, 99, 101, 115, 95, 112, 114, 101, 115, 115, 117, 114, 101, 95, 114, 101, 100, 117, 99, 105, 110, 103, 95, 98, 101, 100, 115, 95, 109, 97, 116, 116, 114, 101, 115, 115, 101, 115, 95, 111, 118, 101, 114, 108, 97, 121, 115, 95, 112, 97, 100, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 103, 97, 115, 116, 114, 105, 99, 95, 115, 117, 99, 116, 105, 111, 110, 95, 112, 117, 109, 112, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 105, 110, 102, 117, 115, 105, 111, 110, 95, 112, 117, 109, 112, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 105, 110, 115, 117, 108, 105, 110, 95, 105, 110, 102, 117, 115, 105, 111, 110, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 105, 110, 102, 117, 115, 105, 111, 110, 95, 112, 117, 109, 112, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 105, 109, 112, 108, 97, 110, 116, 101, 100, 95, 105, 110, 102, 117, 115, 105, 111, 110, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 110, 101, 117, 114, 111, 115, 116, 105, 109, 117, 108, 97, 116, 111, 114, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 105, 110, 102, 117, 115, 105, 111, 110, 95, 112, 117, 109, 112, 115, 95, 105, 109, 112, 108, 97, 110, 116, 97, 98, 108, 101, 95, 97, 110, 100, 95, 117, 110, 105, 110, 116, 101, 114, 114, 117, 112, 116, 101, 100, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 104, 101, 109, 111, 100, 105, 97, 108, 121, 115, 105, 115, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 116, 114, 97, 110, 115, 99, 117, 116, 97, 110, 101, 111, 117, 115, 95, 101, 108, 101, 99, 116, 114, 105, 99, 97, 108, 95, 110, 101, 114, 118, 101, 95, 115, 116, 105, 109, 117, 108, 97, 116, 111, 114, 115, 95, 116, 101, 110, 115, 95, 117, 110, 105, 116, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 108, 105, 109, 98, 95, 112, 114, 111, 115, 116, 104, 101, 115, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 109, 101, 99, 104, 97, 110, 105, 99, 97, 108, 95, 105, 110, 95, 101, 120, 115, 117, 102, 102, 108, 97, 116, 105, 111, 110, 95, 100, 101, 118, 105, 99, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 105, 110, 116, 114, 97, 112, 117, 108, 109, 111, 110, 97, 114, 121, 95, 112, 101, 114, 99, 117, 115, 115, 105, 118, 101, 95, 118, 101, 110, 116, 105, 108, 97, 116, 105, 111, 110, 95, 100, 101, 118, 105, 99, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 104, 105, 103, 104, 95, 102, 114, 101, 113, 117, 101, 110, 99, 121, 95, 99, 104, 101, 115, 116, 95, 119, 97, 108, 108, 95, 111, 115, 99, 105, 108, 108, 97, 116, 105, 111, 110, 95, 104, 102, 99, 119, 111, 95, 100, 101, 118, 105, 99, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 105, 110, 102, 117, 115, 105, 111, 110, 95, 112, 117, 109, 112, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 101, 120, 116, 101, 114, 110, 97, 108, 95, 105, 110, 102, 117, 115, 105, 111, 110, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 101, 110, 116, 101, 114, 97, 108, 95, 110, 117, 116, 114, 105, 101, 110, 116, 115, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 97, 110, 100, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 112, 110, 101, 117, 109, 97, 116, 105, 99, 95, 99, 111, 109, 112, 114, 101, 115, 115, 105, 111, 110, 95, 100, 101, 118, 105, 99, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 104, 111, 109, 101, 95, 100, 105, 97, 108, 121, 115, 105, 115, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 95, 115, 116, 97, 110, 100, 97, 114, 100, 95, 109, 97, 110, 117, 97, 108, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 102, 97, 99, 105, 97, 108, 95, 112, 114, 111, 115, 116, 104, 101, 115, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 101, 121, 101, 95, 112, 114, 111, 115, 116, 104, 101, 115, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 97, 117, 116, 111, 109, 97, 116, 105, 99, 95, 101, 120, 116, 101, 114, 110, 97, 108, 95, 100, 101, 102, 105, 98, 114, 105, 108, 108, 97, 116, 111, 114, 115, 95, 97, 101, 100, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 98, 108, 111, 111, 100, 95, 103, 108, 117, 99, 111, 115, 101, 95, 109, 111, 110, 105, 116, 111, 114, 115, 95, 109, 97, 105, 108, 95, 111, 114, 100, 101, 114, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 112, 104, 111, 110, 101, 34, 32, 58, 32, 34, 40, 57, 48, 55, 41, 50, 55, 50, 45, 50, 53, 53, 55, 34, 44, 10, 32, 32, 34, 119, 97, 108, 107, 101, 114, 115, 95, 97, 110, 100, 95, 114, 101, 108, 97, 116, 101, 100, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 111, 120, 121, 103, 101, 110, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 97, 110, 100, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 101, 110, 116, 101, 114, 97, 108, 95, 110, 117, 116, 114, 105, 101, 110, 116, 115, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 110, 101, 98, 117, 108, 105, 122, 101, 114, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 117, 108, 116, 114, 97, 115, 111, 110, 105, 99, 95, 97, 110, 100, 95, 99, 111, 110, 116, 114, 111, 108, 108, 101, 100, 95, 100, 111, 115, 101, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 99, 111, 109, 112, 97, 110, 121, 95, 110, 97, 109, 101, 34, 32, 58, 32, 34, 65, 76, 65, 83, 75, 65, 32, 69, 89, 69, 32, 67, 65, 82, 69, 32, 67, 69, 78, 84, 69, 82, 83, 32, 65, 32, 80, 82, 79, 70, 69, 83, 83, 73, 79, 78, 65, 76, 32, 67, 79, 82, 80, 79, 82, 65, 84, 73, 79, 78, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 44, 10, 32, 32, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 95, 99, 111, 109, 112, 108, 101, 120, 95, 114, 101, 104, 97, 98, 105, 108, 105, 116, 97, 116, 105, 118, 101, 95, 109, 97, 110, 117, 97, 108, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 112, 114, 111, 115, 116, 104, 101, 116, 105, 99, 95, 108, 101, 110, 115, 101, 115, 95, 112, 114, 111, 115, 116, 104, 101, 116, 105, 99, 95, 99, 97, 116, 97, 114, 97, 99, 116, 95, 108, 101, 110, 115, 101, 115, 34, 32, 58, 32, 116, 114, 117, 101, 44, 10, 32, 32, 34, 114, 101, 115, 112, 105, 114, 97, 116, 111, 114, 121, 95, 115, 117, 99, 116, 105, 111, 110, 95, 112, 117, 109, 112, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 110, 101, 117, 114, 111, 109, 117, 115, 99, 117, 108, 97, 114, 95, 101, 108, 101, 99, 116, 114, 105, 99, 97, 108, 95, 115, 116, 105, 109, 117, 108, 97, 116, 111, 114, 115, 95, 110, 109, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 119, 97, 108, 107, 101, 114, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 95, 115, 116, 97, 110, 100, 97, 114, 100, 95, 112, 111, 119, 101, 114, 95, 112, 101, 100, 105, 97, 116, 114, 105, 99, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 114, 101, 115, 112, 105, 114, 97, 116, 111, 114, 121, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 114, 101, 108, 97, 116, 101, 100, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 97, 110, 100, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 110, 101, 98, 117, 108, 105, 122, 101, 114, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 110, 101, 103, 97, 116, 105, 118, 101, 95, 112, 114, 101, 115, 115, 117, 114, 101, 95, 119, 111, 117, 110, 100, 95, 116, 104, 101, 114, 97, 112, 121, 95, 112, 117, 109, 112, 115, 95, 97, 110, 100, 95, 114, 101, 108, 97, 116, 101, 100, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 97, 110, 100, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 95, 115, 101, 97, 116, 105, 110, 103, 95, 99, 117, 115, 104, 105, 111, 110, 115, 95, 115, 107, 105, 110, 95, 112, 114, 111, 116, 101, 99, 116, 105, 110, 103, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 118, 101, 110, 116, 105, 108, 97, 116, 111, 114, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 95, 115, 101, 97, 116, 105, 110, 103, 95, 99, 117, 115, 104, 105, 111, 110, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 99, 112, 97, 112, 95, 97, 110, 100, 95, 114, 97, 100, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 101, 95, 103, 95, 99, 111, 109, 98, 105, 110, 97, 116, 105, 111, 110, 95, 109, 97, 115, 107, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 99, 112, 97, 112, 95, 114, 97, 100, 115, 95, 114, 101, 108, 97, 116, 101, 100, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 117, 114, 111, 108, 111, 103, 105, 99, 97, 108, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 98, 108, 111, 111, 100, 95, 103, 108, 117, 99, 111, 115, 101, 95, 109, 111, 110, 105, 116, 111, 114, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 109, 97, 105, 108, 95, 111, 114, 100, 101, 114, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 116, 114, 97, 99, 116, 105, 111, 110, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 105, 110, 116, 101, 114, 109, 105, 116, 116, 101, 110, 116, 95, 112, 111, 115, 105, 116, 105, 118, 101, 95, 112, 114, 101, 115, 115, 117, 114, 101, 95, 98, 114, 101, 97, 116, 104, 105, 110, 103, 95, 105, 112, 112, 98, 95, 100, 101, 118, 105, 99, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 110, 101, 103, 97, 116, 105, 118, 101, 95, 112, 114, 101, 115, 115, 117, 114, 101, 95, 119, 111, 117, 110, 100, 95, 116, 104, 101, 114, 97, 112, 121, 95, 112, 117, 109, 112, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 115, 116, 97, 116, 101, 34, 32, 58, 32, 34, 65, 75, 34, 44, 10, 32, 32, 34, 103, 101, 110, 101, 114, 97, 108, 95, 104, 111, 109, 101, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 97, 110, 100, 95, 114, 101, 108, 97, 116, 101, 100, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 97, 110, 100, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 111, 114, 116, 104, 111, 115, 101, 115, 95, 99, 117, 115, 116, 111, 109, 95, 102, 97, 98, 114, 105, 99, 97, 116, 101, 100, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 95, 99, 111, 109, 112, 108, 101, 120, 95, 114, 101, 104, 97, 98, 105, 108, 105, 116, 97, 116, 105, 118, 101, 95, 112, 111, 119, 101, 114, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 111, 115, 116, 111, 109, 121, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 104, 111, 115, 112, 105, 116, 97, 108, 95, 98, 101, 100, 115, 95, 109, 97, 110, 117, 97, 108, 95, 112, 101, 100, 105, 97, 116, 114, 105, 99, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 104, 111, 115, 112, 105, 116, 97, 108, 95, 98, 101, 100, 115, 95, 101, 108, 101, 99, 116, 114, 105, 99, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 99, 111, 110, 116, 105, 110, 117, 111, 117, 115, 95, 112, 97, 115, 115, 105, 118, 101, 95, 109, 111, 116, 105, 111, 110, 95, 99, 112, 109, 95, 100, 101, 118, 105, 99, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 95, 115, 116, 97, 110, 100, 97, 114, 100, 95, 112, 111, 119, 101, 114, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 98, 114, 101, 97, 115, 116, 95, 112, 114, 111, 115, 116, 104, 101, 115, 101, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 122, 105, 112, 34, 32, 58, 32, 34, 57, 57, 53, 48, 49, 34, 44, 10, 32, 32, 34, 115, 116, 97, 110, 100, 97, 114, 100, 95, 112, 111, 119, 101, 114, 95, 109, 97, 110, 117, 97, 108, 95, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 115, 95, 115, 99, 111, 111, 116, 101, 114, 115, 95, 97, 110, 100, 95, 114, 101, 108, 97, 116, 101, 100, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 115, 117, 112, 112, 111, 114, 116, 95, 115, 117, 114, 102, 97, 99, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 116, 114, 97, 99, 104, 101, 111, 115, 116, 111, 109, 121, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 111, 120, 121, 103, 101, 110, 95, 101, 113, 117, 105, 112, 109, 101, 110, 116, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 111, 99, 117, 108, 97, 114, 95, 112, 114, 111, 115, 116, 104, 101, 115, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 109, 97, 105, 108, 95, 111, 114, 100, 101, 114, 95, 100, 105, 97, 98, 101, 116, 105, 99, 95, 115, 117, 112, 112, 108, 105, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 115, 117, 114, 103, 105, 99, 97, 108, 95, 100, 114, 101, 115, 115, 105, 110, 103, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 119, 104, 101, 101, 108, 99, 104, 97, 105, 114, 115, 95, 97, 99, 99, 101, 115, 115, 111, 114, 105, 101, 115, 95, 99, 111, 109, 112, 108, 101, 120, 95, 114, 101, 104, 97, 98, 105, 108, 105, 116, 97, 116, 105, 118, 101, 95, 112, 111, 119, 101, 114, 95, 101, 95, 103, 95, 103, 114, 111, 117, 112, 95, 51, 95, 103, 114, 111, 117, 112, 95, 52, 95, 103, 114, 111, 117, 112, 95, 53, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 115, 111, 109, 97, 116, 105, 99, 95, 112, 114, 111, 115, 116, 104, 101, 115, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 104, 111, 115, 112, 105, 116, 97, 108, 95, 98, 101, 100, 115, 95, 116, 111, 116, 97, 108, 95, 101, 108, 101, 99, 116, 114, 105, 99, 95, 112, 101, 100, 105, 97, 116, 114, 105, 99, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 104, 101, 97, 116, 95, 99, 111, 108, 100, 95, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 97, 100, 100, 114, 101, 115, 115, 34, 32, 58, 32, 34, 49, 51, 52, 53, 32, 87, 32, 57, 84, 72, 32, 65, 86, 69, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 44, 10, 32, 32, 34, 101, 110, 116, 101, 114, 97, 108, 95, 110, 117, 116, 114, 105, 101, 110, 116, 115, 95, 115, 117, 112, 112, 108, 105, 101, 115, 95, 102, 111, 114, 95, 115, 112, 101, 99, 105, 97, 108, 95, 109, 101, 116, 97, 98, 111, 108, 105, 99, 95, 110, 101, 101, 100, 115, 95, 97, 110, 100, 95, 112, 101, 100, 105, 97, 116, 114, 105, 99, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 105, 110, 118, 97, 115, 105, 118, 101, 95, 109, 101, 99, 104, 97, 110, 105, 99, 97, 108, 95, 118, 101, 110, 116, 105, 108, 97, 116, 105, 111, 110, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 112, 114, 111, 115, 116, 104, 101, 116, 105, 99, 95, 108, 101, 110, 115, 101, 115, 95, 99, 111, 110, 118, 101, 110, 116, 105, 111, 110, 97, 108, 95, 101, 121, 101, 103, 108, 97, 115, 115, 101, 115, 34, 32, 58, 32, 116, 114, 117, 101, 44, 10, 32, 32, 34, 99, 111, 99, 104, 108, 101, 97, 114, 95, 105, 109, 112, 108, 97, 110, 116, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 100, 105, 97, 98, 101, 116, 105, 99, 95, 115, 104, 111, 101, 115, 95, 105, 110, 115, 101, 114, 116, 115, 95, 112, 114, 101, 102, 97, 98, 114, 105, 99, 97, 116, 101, 100, 34, 32, 58, 32, 102, 97, 108, 115, 101, 44, 10, 32, 32, 34, 115, 112, 101, 101, 99, 104, 95, 103, 101, 110, 101, 114, 97, 116, 105, 110, 103, 95, 100, 101, 118, 105, 99, 101, 115, 34, 32, 58, 32, 102, 97, 108, 115, 101, 10, 125, 10, 32, 93, 13, 10, 48, 13, 10, 13, 10]) TRACE:hyper::http::h1: Response.try_parse([Header; 100], [u8; 10335]) TRACE:hyper::client::pool: PooledStream.drop, is_closed=true thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value: Version', ../src/libcore/result.rs:738 ``` To add to the weirdness of the error if I copy paste the client code and use the command line argument URL the response works but if the URL is a string in the code then I get the error. This works ``` fn main() { env_logger::init().unwrap(); let url = match env::args().nth(1) { Some(url) => url, None => { println!("Usage: client <url>"); return; } }; let client = Client::new(); let mut res = client.get(&*url) .header(Connection::close()) .send().unwrap(); println!("Response: {}", res.status); println!("Headers:\n{}", res.headers); io::copy(&mut res, &mut io::stdout()).unwrap(); } ``` This doesn't ``` fn main() { env_logger::init().unwrap(); let url = "https://data.medicare.gov/resource/pqp8-xrjv.json?$limit=1"; let client = Client::new(); let mut res = client.get(url) .header(Connection::close()) .send().unwrap(); println!("Response: {}", res.status); println!("Headers:\n{}", res.headers); io::copy(&mut res, &mut io::stdout()).unwrap(); } ``` I believe this is a bug in the resizing of the buffer. It seems to zero the entire thing, not just the new part.
2016-01-04T23:01:42Z
0.7
a4230eb510224b3a52e0f2d616fade8f0e8313b9
hyperium/hyper
699
hyperium__hyper-699
[ "698" ]
3f1b13c72d925b80601ab5468dbe36273622b451
diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -9,7 +9,7 @@ use std::time::Duration; use buffer::BufReader; use net::NetworkStream; use version::{HttpVersion}; -use method::Method::{self, Get, Head}; +use method::Method; use header::{Headers, ContentLength, TransferEncoding}; use http::h1::{self, Incoming, HttpReader}; use http::h1::HttpReader::{SizedReader, ChunkedReader, EmptyReader}; diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -41,9 +41,7 @@ impl<'a, 'b: 'a> Request<'a, 'b> { debug!("Request Line: {:?} {:?} {:?}", method, uri, version); debug!("{:?}", headers); - let body = if method == Get || method == Head { - EmptyReader(stream) - } else if headers.has::<ContentLength>() { + let body = if headers.has::<ContentLength>() { match headers.get::<ContentLength>() { Some(&ContentLength(len)) => SizedReader(stream, len), None => unreachable!()
diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -159,6 +157,24 @@ mod tests { assert_eq!(read_to_string(req).unwrap(), "".to_owned()); } + #[test] + fn test_get_with_body() { + let mut mock = MockStream::with_input(b"\ + GET / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Content-Length: 19\r\n\ + \r\n\ + I'm a good request.\r\n\ + "); + + // FIXME: Use Type ascription + let mock: &mut NetworkStream = &mut mock; + let mut stream = BufReader::new(mock); + + let req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); + assert_eq!(read_to_string(req).unwrap(), "I'm a good request.".to_owned()); + } + #[test] fn test_head_empty_body() { let mut mock = MockStream::with_input(b"\
Request body should be allowed with GET/HEAD requests Currently, the body is ignored when the request method is either GET or HEAD. I had a look through the HTTP 1.1 spec and didn't find any mention of restricting request bodies to certian methods (http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3). I have also seen this behaviour used in the wild. For example, Elasticsearch uses it for passing the search query when performing a search request (https://www.elastic.co/guide/en/elasticsearch/reference/1.4/search-request-body.html). Relevant code: https://github.com/hyperium/hyper/blob/master/src/server/request.rs#L44-L45 Introduced in: https://github.com/hyperium/hyper/commit/a60a67cd1e0a67c3348c34b4e3bd933557c07671
2616 has been [superseded](https://www.mnot.net/blog/2014/06/07/rfc2616_is_dead). See http://tools.ietf.org/html/rfc7231#section-4.3.2 for the relevant MUST NOT.
2015-11-29T17:10:41Z
0.7
a4230eb510224b3a52e0f2d616fade8f0e8313b9
hyperium/hyper
693
hyperium__hyper-693
[ "655" ]
072d4fe36af21e1551316242ba5ebb5a011d38ca
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -7,6 +7,7 @@ //! is used, such as `ContentType(pub Mime)`. pub use self::accept::Accept; +pub use self::access_control_allow_credentials::AccessControlAllowCredentials; pub use self::access_control_allow_headers::AccessControlAllowHeaders; pub use self::access_control_allow_methods::AccessControlAllowMethods; pub use self::access_control_allow_origin::AccessControlAllowOrigin; diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -353,6 +354,7 @@ macro_rules! header { mod accept; +mod access_control_allow_credentials; mod access_control_allow_headers; mod access_control_allow_methods; mod access_control_allow_origin;
diff --git /dev/null b/src/header/common/access_control_allow_credentials.rs new file mode 100644 --- /dev/null +++ b/src/header/common/access_control_allow_credentials.rs @@ -0,0 +1,89 @@ +use std::fmt::{self, Display}; +use std::str; +use unicase::UniCase; +use header::{Header, HeaderFormat}; + +/// `Access-Control-Allow-Credentials` header, part of +/// [CORS](http://www.w3.org/TR/cors/#access-control-allow-headers-response-header) +/// +/// > The Access-Control-Allow-Credentials HTTP response header indicates whether the +/// > response to request can be exposed when the credentials flag is true. When part +/// > of the response to an preflight request it indicates that the actual request can +/// > be made with credentials. The Access-Control-Allow-Credentials HTTP header must +/// > match the following ABNF: +/// +/// # ABNF +/// ```plain +/// Access-Control-Allow-Credentials: "Access-Control-Allow-Credentials" ":" "true" +/// ``` +/// +/// Since there is only one acceptable field value, the header struct does not accept +/// any values at all. Setting an empty `AccessControlAllowCredentials` header is +/// sufficient. See the examples below. +/// +/// # Example values +/// * "true" +/// +/// # Examples +/// ``` +/// # extern crate hyper; +/// # fn main() { +/// +/// use hyper::header::{Headers, AccessControlAllowCredentials}; +/// +/// let mut headers = Headers::new(); +/// headers.set(AccessControlAllowCredentials); +/// # } +/// ``` +#[derive(Clone, PartialEq, Debug)] +pub struct AccessControlAllowCredentials; + +const ACCESS_CONTROL_ALLOW_CREDENTIALS_TRUE: UniCase<&'static str> = UniCase("true"); + +impl Header for AccessControlAllowCredentials { + fn header_name() -> &'static str { + "Access-Control-Allow-Credentials" + } + + fn parse_header(raw: &[Vec<u8>]) -> ::Result<AccessControlAllowCredentials> { + if raw.len() == 1 { + let text = unsafe { + // safe because: + // 1. we just checked raw.len == 1 + // 2. we don't actually care if it's utf8, we just want to + // compare the bytes with the "case" normalized. If it's not + // utf8, then the byte comparison will fail, and we'll return + // None. No big deal. + str::from_utf8_unchecked(raw.get_unchecked(0)) + }; + if UniCase(text) == ACCESS_CONTROL_ALLOW_CREDENTIALS_TRUE { + return Ok(AccessControlAllowCredentials); + } + } + Err(::Error::Header) + } +} + +impl HeaderFormat for AccessControlAllowCredentials { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("true") + } +} + +impl Display for AccessControlAllowCredentials { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + self.fmt_header(f) + } +} + +#[cfg(test)] +mod test_access_control_allow_credentials { + use std::str; + use header::*; + use super::AccessControlAllowCredentials as HeaderField; + test_header!(works, vec![b"true"], Some(HeaderField)); + test_header!(ignores_case, vec![b"True"]); + test_header!(not_bool, vec![b"false"], None); + test_header!(only_single, vec![b"true", b"true"], None); + test_header!(no_gibberish, vec!["\u{645}\u{631}\u{62d}\u{628}\u{627}".as_bytes()], None); +} \ No newline at end of file
Access-Control-Allow-Credentials header the Access-Control-Allow-Credentials header is missing http://www.w3.org/TR/2008/WD-access-control-20080912/#access-control-allow-credentials ABNF: ``` Access-Control-Allow-Credentials: "Access-Control-Allow-Credentials" ":" "true" ```
2015-11-22T08:55:39Z
0.6
072d4fe36af21e1551316242ba5ebb5a011d38ca
hyperium/hyper
687
hyperium__hyper-687
[ "686" ]
d44ee5980f744b34bc33ad34b1ae2cafcf7ad6e7
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -25,11 +25,11 @@ unicase = "1.0" url = "0.2" [dependencies.cookie] -version = "0.1" +version = "0.2" default-features = false [dependencies.openssl] -version = "0.6.4" +version = "0.7" optional = true [dependencies.solicit] diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -1,10 +1,7 @@ -use header::{Header, HeaderFormat}; +use header::{Header, HeaderFormat, CookiePair, CookieJar}; use std::fmt::{self, Display}; use std::str::from_utf8; -use cookie::Cookie as CookiePair; -use cookie::CookieJar; - /// `Cookie` header, defined in [RFC6265](http://tools.ietf.org/html/rfc6265#section-5.4) /// /// If the user agent does attach a Cookie header field to an HTTP diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs --- a/src/header/common/set_cookie.rs +++ b/src/header/common/set_cookie.rs @@ -1,9 +1,7 @@ -use header::{Header, HeaderFormat}; +use header::{Header, HeaderFormat, CookiePair, CookieJar}; use std::fmt::{self, Display}; use std::str::from_utf8; -use cookie::Cookie; -use cookie::CookieJar; /// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1) /// diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs --- a/src/header/common/set_cookie.rs +++ b/src/header/common/set_cookie.rs @@ -80,9 +78,9 @@ use cookie::CookieJar; /// # } /// ``` #[derive(Clone, PartialEq, Debug)] -pub struct SetCookie(pub Vec<Cookie>); +pub struct SetCookie(pub Vec<CookiePair>); -__hyper__deref!(SetCookie => Vec<Cookie>); +__hyper__deref!(SetCookie => Vec<CookiePair>); impl Header for SetCookie { fn header_name() -> &'static str { diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs --- a/src/header/common/set_cookie.rs +++ b/src/header/common/set_cookie.rs @@ -176,5 +174,5 @@ fn cookie_jar() { cookies.apply_to_cookie_jar(&mut new_jar); assert_eq!(jar.find("foo"), new_jar.find("foo")); - assert_eq!(jar.iter().collect::<Vec<Cookie>>(), new_jar.iter().collect::<Vec<Cookie>>()); + assert_eq!(jar.iter().collect::<Vec<CookiePair>>(), new_jar.iter().collect::<Vec<CookiePair>>()); } diff --git a/src/header/shared/mod.rs b/src/header/shared/mod.rs --- a/src/header/shared/mod.rs +++ b/src/header/shared/mod.rs @@ -1,4 +1,6 @@ pub use self::charset::Charset; +pub use cookie::Cookie as CookiePair; +pub use cookie::CookieJar; pub use self::encoding::Encoding; pub use self::entity::EntityTag; pub use self::httpdate::HttpDate;
diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs --- a/src/header/common/set_cookie.rs +++ b/src/header/common/set_cookie.rs @@ -142,7 +140,7 @@ impl SetCookie { #[test] fn test_parse() { let h = Header::parse_header(&[b"foo=bar; HttpOnly".to_vec()][..]); - let mut c1 = Cookie::new("foo".to_owned(), "bar".to_owned()); + let mut c1 = CookiePair::new("foo".to_owned(), "bar".to_owned()); c1.httponly = true; assert_eq!(h.ok(), Some(SetCookie(vec![c1]))); diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs --- a/src/header/common/set_cookie.rs +++ b/src/header/common/set_cookie.rs @@ -152,22 +150,22 @@ fn test_parse() { fn test_fmt() { use header::Headers; - let mut cookie = Cookie::new("foo".to_owned(), "bar".to_owned()); + let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned()); cookie.httponly = true; cookie.path = Some("/p".to_owned()); - let cookies = SetCookie(vec![cookie, Cookie::new("baz".to_owned(), "quux".to_owned())]); + let cookies = SetCookie(vec![cookie, CookiePair::new("baz".to_owned(), "quux".to_owned())]); let mut headers = Headers::new(); headers.set(cookies); assert_eq!( &headers.to_string()[..], - "Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux; Path=/\r\n"); + "Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux\r\n"); } #[test] fn cookie_jar() { let jar = CookieJar::new(b"secret"); - let cookie = Cookie::new("foo".to_owned(), "bar".to_owned()); + let cookie = CookiePair::new("foo".to_owned(), "bar".to_owned()); jar.add(cookie); let cookies = SetCookie::from_cookie_jar(&jar); diff --git a/src/http/h2.rs b/src/http/h2.rs --- a/src/http/h2.rs +++ b/src/http/h2.rs @@ -661,8 +661,8 @@ mod tests { let h2headers = prepare_headers(headers); assert_eq!(vec![ - (b"set-cookie".to_vec(), b"foo=bar; Path=/".to_vec()), - (b"set-cookie".to_vec(), b"baz=quux; Path=/".to_vec()), + (b"set-cookie".to_vec(), b"foo=bar".to_vec()), + (b"set-cookie".to_vec(), b"baz=quux".to_vec()), ], h2headers); } diff --git a/src/http/h2.rs b/src/http/h2.rs --- a/src/http/h2.rs +++ b/src/http/h2.rs @@ -700,8 +700,8 @@ mod tests { #[test] fn test_http2_parse_headers_with_set_cookie() { let h2headers = vec![ - (b"set-cookie".to_vec(), b"foo=bar; Path=/".to_vec()), - (b"set-cookie".to_vec(), b"baz=quux; Path=/".to_vec()), + (b"set-cookie".to_vec(), b"foo=bar".to_vec()), + (b"set-cookie".to_vec(), b"baz=quux".to_vec()), ]; let expected = header::SetCookie(vec![ cookie::Cookie::new("foo".to_owned(), "bar".to_owned()),
Can we bump the version of the cookie crate from 0.1 to 0.2? I'm trying to build https://github.com/cyderize/rust-websocket. Now that fails (see https://github.com/cyderize/rust-websocket/issues/54) because websocket wants a newer version of openssl than hyper/cookie does, which causes a conflict. Websocket could of course require an older version of ssl, to match hyper. However, in the long run, I'm guessing that hyper will move to new version of cookie though (with already uses the newer version) sooner or later, so I'm suggesting we bump it now. I tried to do it locally, unfortunately 3 tests failed for me then, so some work is required. If I can work out what that is, I'll put up a PR, but I'm guessing that it's above my level of knowledge.
2015-11-20T19:15:49Z
0.6
072d4fe36af21e1551316242ba5ebb5a011d38ca
hyperium/hyper
680
hyperium__hyper-680
[ "561" ]
b4a9227204e1c08b047643b0c2f655fbf49e30b0
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -23,6 +23,7 @@ pub use self::allow::Allow; pub use self::authorization::{Authorization, Scheme, Basic, Bearer}; pub use self::cache_control::{CacheControl, CacheDirective}; pub use self::connection::{Connection, ConnectionOption}; +pub use self::content_disposition::{ContentDisposition, DispositionType, DispositionParam}; pub use self::content_length::ContentLength; pub use self::content_encoding::ContentEncoding; pub use self::content_language::ContentLanguage; diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -371,6 +372,7 @@ mod authorization; mod cache_control; mod cookie; mod connection; +mod content_disposition; mod content_encoding; mod content_language; mod content_length;
diff --git /dev/null b/src/header/common/content_disposition.rs new file mode 100644 --- /dev/null +++ b/src/header/common/content_disposition.rs @@ -0,0 +1,328 @@ +// # References +// +// "The Content-Disposition Header Field" https://www.ietf.org/rfc/rfc2183.txt +// "The Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)" https://www.ietf.org/rfc/rfc6266.txt +// "Returning Values from Forms: multipart/form-data" https://www.ietf.org/rfc/rfc2388.txt +// Browser conformance tests at: http://greenbytes.de/tech/tc2231/ +// IANA assignment: http://www.iana.org/assignments/cont-disp/cont-disp.xhtml + +use language_tags::LanguageTag; +use std::fmt; +use std::str::FromStr; +use unicase::UniCase; +use url::percent_encoding; + +use header::{Header, HeaderFormat, parsing}; +use header::shared::Charset; + +/// The implied disposition of the content of the HTTP body +#[derive(Clone, Debug, PartialEq)] +pub enum DispositionType { + /// Inline implies default processing + Inline, + /// Attachment implies that the recipient should prompt the user to save the response locally, + /// rather than process it normally (as per its media type). + Attachment, + /// Extension type. Should be handled by recipients the same way as Attachment + Ext(String) +} + +/// A parameter to the disposition type +#[derive(Clone, Debug, PartialEq)] +pub enum DispositionParam { + /// A Filename consisting of a Charset, an optional LanguageTag, and finally a sequence of + /// bytes representing the filename + Filename(Charset, Option<LanguageTag>, Vec<u8>), + /// Extension type consisting of token and value. Recipients should ignore unrecognized + /// parameters. + Ext(String, String) +} + +/// A `Content-Disposition` header, (re)defined in [RFC6266](https://tools.ietf.org/html/rfc6266) +/// +/// The Content-Disposition response header field is used to convey +/// additional information about how to process the response payload, and +/// also can be used to attach additional metadata, such as the filename +/// to use when saving the response payload locally. +/// +/// # ABNF +/// ```plain +/// content-disposition = "Content-Disposition" ":" +/// disposition-type *( ";" disposition-parm ) +/// +/// disposition-type = "inline" | "attachment" | disp-ext-type +/// ; case-insensitive +/// +/// disp-ext-type = token +/// +/// disposition-parm = filename-parm | disp-ext-parm +/// +/// filename-parm = "filename" "=" value +/// | "filename*" "=" ext-value +/// +/// disp-ext-parm = token "=" value +/// | ext-token "=" ext-value +/// +/// ext-token = <the characters in token, followed by "*"> +/// ``` +/// +/// # Example +/// ``` +/// use hyper::header::{Headers, ContentDisposition, DispositionType, DispositionParam, Charset}; +/// +/// let mut headers = Headers::new(); +/// headers.set(ContentDisposition { +/// disposition: DispositionType::Attachment, +/// parameters: vec![DispositionParam::Filename( +/// Charset::Iso_8859_1, // The character set for the bytes of the filename +/// None, // The optional language tag (see `language-tag` crate) +/// b"\xa9 Copyright 1989.txt".to_vec() // the actual bytes of the filename +/// )] +/// }); +/// ``` +#[derive(Clone, Debug, PartialEq)] +pub struct ContentDisposition { + /// The disposition + pub disposition: DispositionType, + /// Disposition parameters + pub parameters: Vec<DispositionParam>, +} + +impl Header for ContentDisposition { + fn header_name() -> &'static str { + "Content-Disposition" + } + + fn parse_header(raw: &[Vec<u8>]) -> ::Result<ContentDisposition> { + parsing::from_one_raw_str(raw).and_then(|s: String| { + let mut sections = s.split(';'); + let disposition = match sections.next() { + Some(s) => s.trim(), + None => return Err(::Error::Header), + }; + + let mut cd = ContentDisposition { + disposition: if UniCase(&*disposition) == UniCase("inline") { + DispositionType::Inline + } else if UniCase(&*disposition) == UniCase("attachment") { + DispositionType::Attachment + } else { + DispositionType::Ext(disposition.to_owned()) + }, + parameters: Vec::new(), + }; + + for section in sections { + let mut parts = section.splitn(2, '='); + + let key = if let Some(key) = parts.next() { + key.trim() + } else { + return Err(::Error::Header); + }; + + let val = if let Some(val) = parts.next() { + val.trim() + } else { + return Err(::Error::Header); + }; + + cd.parameters.push( + if UniCase(&*key) == UniCase("filename") { + DispositionParam::Filename( + Charset::Ext("UTF-8".to_owned()), None, + val.trim_matches('"').as_bytes().to_owned()) + } else if UniCase(&*key) == UniCase("filename*") { + let (charset, opt_language, value) = try!(parse_ext_value(val)); + DispositionParam::Filename(charset, opt_language, value) + } else { + DispositionParam::Ext(key.to_owned(), val.trim_matches('"').to_owned()) + } + ); + } + + Ok(cd) + }) + } +} + +impl HeaderFormat for ContentDisposition { + #[inline] + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&self, f) + } +} + +impl fmt::Display for ContentDisposition { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self.disposition { + DispositionType::Inline => try!(write!(f, "inline")), + DispositionType::Attachment => try!(write!(f, "attachment")), + DispositionType::Ext(ref s) => try!(write!(f, "{}", s)), + } + for param in self.parameters.iter() { + match param { + &DispositionParam::Filename(ref charset, ref opt_lang, ref bytes) => { + let mut use_simple_format: bool = false; + if opt_lang.is_none() { + if let Charset::Ext(ref ext) = *charset { + if UniCase(&**ext) == UniCase("utf-8") { + use_simple_format = true; + } + } + } + if use_simple_format { + try!(write!(f, "; filename=\"{}\"", + match String::from_utf8(bytes.clone()) { + Ok(s) => s, + Err(_) => return Err(fmt::Error), + })); + } else { + try!(write!(f, "; filename*={}'", charset)); + if let Some(ref lang) = *opt_lang { + try!(write!(f, "{}", lang)); + }; + try!(write!(f, "'")); + try!(f.write_str( + &*percent_encoding::percent_encode( + bytes, percent_encoding::HTTP_VALUE_ENCODE_SET))) + } + }, + &DispositionParam::Ext(ref k, ref v) => try!(write!(f, "; {}=\"{}\"", k, v)), + } + } + Ok(()) + } +} + +/// Parsing of `ext-value` +/// https://tools.ietf.org/html/rfc5987#section-3.2 +/// +/// # ABNF +/// ```plain +/// ext-value = charset "'" [ language ] "'" value-chars +/// ; like RFC 2231's <extended-initial-value> +/// ; (see [RFC2231], Section 7) +/// +/// charset = "UTF-8" / "ISO-8859-1" / mime-charset +/// +/// mime-charset = 1*mime-charsetc +/// mime-charsetc = ALPHA / DIGIT +/// / "!" / "#" / "$" / "%" / "&" +/// / "+" / "-" / "^" / "_" / "`" +/// / "{" / "}" / "~" +/// ; as <mime-charset> in Section 2.3 of [RFC2978] +/// ; except that the single quote is not included +/// ; SHOULD be registered in the IANA charset registry +/// +/// language = <Language-Tag, defined in [RFC5646], Section 2.1> +/// +/// value-chars = *( pct-encoded / attr-char ) +/// +/// pct-encoded = "%" HEXDIG HEXDIG +/// ; see [RFC3986], Section 2.1 +/// +/// attr-char = ALPHA / DIGIT +/// / "!" / "#" / "$" / "&" / "+" / "-" / "." +/// / "^" / "_" / "`" / "|" / "~" +/// ; token except ( "*" / "'" / "%" ) +/// ``` +fn parse_ext_value(val: &str) -> ::Result<(Charset, Option<LanguageTag>, Vec<u8>)> { + + // Break into three pieces separated by the single-quote character + let mut parts = val.splitn(3,'\''); + + // Interpret the first piece as a Charset + let charset: Charset = match parts.next() { + None => return Err(::Error::Header), + Some(n) => try!(FromStr::from_str(n)), + }; + + // Interpret the second piece as a language tag + let lang: Option<LanguageTag> = match parts.next() { + None => return Err(::Error::Header), + Some("") => None, + Some(s) => match s.parse() { + Ok(lt) => Some(lt), + Err(_) => return Err(::Error::Header), + } + }; + + // Interpret the third piece as a sequence of value characters + let value: Vec<u8> = match parts.next() { + None => return Err(::Error::Header), + Some(v) => percent_encoding::percent_decode(v.as_bytes()), + }; + + Ok( (charset, lang, value) ) +} + +#[cfg(test)] +mod tests { + use super::{ContentDisposition,DispositionType,DispositionParam}; + use ::header::Header; + use ::header::shared::Charset; + + #[test] + fn test_parse_header() { + assert!(ContentDisposition::parse_header([b"".to_vec()].as_ref()).is_err()); + + let a = [b"form-data; dummy=3; name=upload;\r\n filename=\"sample.png\"".to_vec()]; + let a: ContentDisposition = ContentDisposition::parse_header(a.as_ref()).unwrap(); + let b = ContentDisposition { + disposition: DispositionType::Ext("form-data".to_owned()), + parameters: vec![ + DispositionParam::Ext("dummy".to_owned(), "3".to_owned()), + DispositionParam::Ext("name".to_owned(), "upload".to_owned()), + DispositionParam::Filename( + Charset::Ext("UTF-8".to_owned()), + None, + "sample.png".bytes().collect()) ] + }; + assert_eq!(a, b); + + let a = [b"attachment; filename=\"image.jpg\"".to_vec()]; + let a: ContentDisposition = ContentDisposition::parse_header(a.as_ref()).unwrap(); + let b = ContentDisposition { + disposition: DispositionType::Attachment, + parameters: vec![ + DispositionParam::Filename( + Charset::Ext("UTF-8".to_owned()), + None, + "image.jpg".bytes().collect()) ] + }; + assert_eq!(a, b); + + let a = [b"attachment; filename*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates".to_vec()]; + let a: ContentDisposition = ContentDisposition::parse_header(a.as_ref()).unwrap(); + let b = ContentDisposition { + disposition: DispositionType::Attachment, + parameters: vec![ + DispositionParam::Filename( + Charset::Ext("UTF-8".to_owned()), + None, + vec![0xc2, 0xa3, 0x20, b'a', b'n', b'd', 0x20, + 0xe2, 0x82, 0xac, 0x20, b'r', b'a', b't', b'e', b's']) ] + }; + assert_eq!(a, b); + } + + #[test] + fn test_display() { + let a = [b"attachment; filename*=UTF-8'en'%C2%A3%20and%20%E2%82%AC%20rates".to_vec()]; + let as_string = ::std::str::from_utf8(&(a[0])).unwrap(); + let a: ContentDisposition = ContentDisposition::parse_header(a.as_ref()).unwrap(); + let display_rendered = format!("{}",a); + assert_eq!(as_string, display_rendered); + + let a = [b"attachment; filename*=UTF-8''black%20and%20white.csv".to_vec()]; + let a: ContentDisposition = ContentDisposition::parse_header(a.as_ref()).unwrap(); + let display_rendered = format!("{}",a); + assert_eq!("attachment; filename=\"black and white.csv\"".to_owned(), display_rendered); + + let a = [b"attachment; filename=colourful.csv".to_vec()]; + let a: ContentDisposition = ContentDisposition::parse_header(a.as_ref()).unwrap(); + let display_rendered = format!("{}",a); + assert_eq!("attachment; filename=\"colourful.csv\"".to_owned(), display_rendered); + } +}
Content-Disposition header Not strictly part of HTTP/1.1 but comes up in common usage. See: - RFC 6266 - Browser conformance tests at: http://greenbytes.de/tech/tc2231/ - IANA assignment at: http://www.iana.org/assignments/cont-disp/cont-disp.xhtml (I'm just documenting this. I'm creating a heavily stripped down variant for my multipart/form-data parsing, and don't need a proper one at present).
If anyone takes this on, you might want to start with the one at https://github.com/mikedilger/formdata/blob/master/src/headers.rs and then extend it to comply with the standards listed above.
2015-11-11T20:06:56Z
0.6
072d4fe36af21e1551316242ba5ebb5a011d38ca
hyperium/hyper
677
hyperium__hyper-677
[ "673" ]
becced4ef293d131ae2ca245621e6ac65bb32c29
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -10,6 +10,7 @@ pub use self::accept::Accept; pub use self::access_control_allow_headers::AccessControlAllowHeaders; pub use self::access_control_allow_methods::AccessControlAllowMethods; pub use self::access_control_allow_origin::AccessControlAllowOrigin; +pub use self::access_control_expose_headers::AccessControlExposeHeaders; pub use self::access_control_max_age::AccessControlMaxAge; pub use self::access_control_request_headers::AccessControlRequestHeaders; pub use self::access_control_request_method::AccessControlRequestMethod; diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -355,6 +356,7 @@ mod accept; mod access_control_allow_headers; mod access_control_allow_methods; mod access_control_allow_origin; +mod access_control_expose_headers; mod access_control_max_age; mod access_control_request_headers; mod access_control_request_method;
diff --git /dev/null b/src/header/common/access_control_expose_headers.rs new file mode 100644 --- /dev/null +++ b/src/header/common/access_control_expose_headers.rs @@ -0,0 +1,60 @@ +use unicase::UniCase; + +header! { + /// `Access-Control-Expose-Headers` header, part of + /// [CORS](http://www.w3.org/TR/cors/#access-control-expose-headers-response-header) + /// + /// The Access-Control-Expose-Headers header indicates which headers are safe to expose to the + /// API of a CORS API specification. + /// + /// # ABNF + /// ```plain + /// Access-Control-Expose-Headers = "Access-Control-Expose-Headers" ":" #field-name + /// ``` + /// + /// # Example values + /// * `ETag, Content-Length` + /// + /// # Examples + /// ``` + /// # extern crate hyper; + /// # extern crate unicase; + /// # fn main() { + /// // extern crate unicase; + /// + /// use hyper::header::{Headers, AccessControlExposeHeaders}; + /// use unicase::UniCase; + /// + /// let mut headers = Headers::new(); + /// headers.set( + /// AccessControlExposeHeaders(vec![ + /// UniCase("etag".to_owned()), + /// UniCase("content-length".to_owned()) + /// ]) + /// ); + /// # } + /// ``` + /// ``` + /// # extern crate hyper; + /// # extern crate unicase; + /// # fn main() { + /// // extern crate unicase; + /// + /// use hyper::header::{Headers, AccessControlExposeHeaders}; + /// use unicase::UniCase; + /// + /// let mut headers = Headers::new(); + /// headers.set( + /// AccessControlExposeHeaders(vec![ + /// UniCase("etag".to_owned()), + /// UniCase("content-length".to_owned()) + /// ]) + /// ); + /// # } + /// ``` + (AccessControlExposeHeaders, "Access-Control-Expose-Headers") => (UniCase<String>)* + + test_access_control_expose_headers { + test_header!(test1, vec![b"etag, content-length"]); + } +}
Header request: Access-Control-Expose-Headers http://www.w3.org/TR/cors/#access-control-expose-headers-response-header
2015-11-02T21:04:17Z
0.6
072d4fe36af21e1551316242ba5ebb5a011d38ca
hyperium/hyper
647
hyperium__hyper-647
[ "646" ]
32e09a04292b0247456a8fb9003a75a6abaa998e
diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -225,6 +225,7 @@ impl HttpMessage for Http11Message { SizedReader(stream, len) } else if headers.has::<ContentLength>() { trace!("illegal Content-Length: {:?}", headers.get_raw("Content-Length")); + self.stream = Some(stream.into_inner()); return Err(Error::Header); } else { trace!("neither Transfer-Encoding nor Content-Length");
diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -893,10 +894,12 @@ mod tests { use std::error::Error; use std::io::{self, Read, Write}; + use buffer::BufReader; use mock::MockStream; + use http::HttpMessage; - use super::{read_chunk_size, parse_request, parse_response}; + use super::{read_chunk_size, parse_request, parse_response, Http11Message}; #[test] fn test_write_chunked() { diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -987,6 +990,15 @@ mod tests { assert_eq!(e.description(), "early eof"); } + #[test] + fn test_message_get_incoming_invalid_content_length() { + let raw = MockStream::with_input( + b"HTTP/1.1 200 OK\r\nContent-Length: asdf\r\n\r\n"); + let mut msg = Http11Message::with_stream(Box::new(raw)); + assert!(msg.get_incoming().is_err()); + assert!(msg.close_connection().is_ok()); + } + #[test] fn test_parse_incoming() { let mut raw = MockStream::with_input(b"GET /echo HTTP/1.1\r\nHost: hyper.rs\r\n\r\n");
Panic when getting empty response from server As noted in this other (closed) issue: https://github.com/hyperium/hyper/issues/365 When receiving empty response data, hyper consistently panics with: ``` thread '<unnamed>' panicked at 'thread '<unnamed>Http11Message lost its underlying stream somehow.', /home/jneves/.cargo/registry/src/github.com-0a35038f75765ae4/hyper-0.6.10/src/http/h1.rs:270 ```
Yep, try updating hyper, this was fixed in a patch. On Fri, Sep 4, 2015, 12:26 AM João Neves notifications@github.com wrote: > As noted in this other (closed) issue: #365 > https://github.com/hyperium/hyper/issues/365 > > When receiving empty response data, hyper consistently panics with: > > thread '<unnamed>' panicked at 'thread '<unnamed>Http11Message lost its underlying stream somehow.', /home/jneves/.cargo/registry/src/github.com-0a35038f75765ae4/hyper-0.6.10/src/http/h1.rs:270 > > — > Reply to this email directly or view it on GitHub > https://github.com/hyperium/hyper/issues/646. Actually, I think this can happen, but not because the response is empty, but because the `Content-Length` header is invalid. For example, try accessing a server that gives `Content-Length: asdf` or even `Content-Length:` (i.e. empty) and you'll reproduce this. It's because the `get_incoming` method definitely drops the stream [here](https://github.com/hyperium/hyper/blob/32e09a04292b0247456a8fb9003a75a6abaa998e/src/http/h1.rs#L227-L228) and returns an `Err`, but then `Response` tries closing it in the error match arm [here](https://github.com/hyperium/hyper/blob/32e09a04292b0247456a8fb9003a75a6abaa998e/src/client/response.rs#L42). Adding a line to save the stream before returning the `Err` in `get_incoming` fixes it, though...
2015-09-04T23:13:55Z
0.6
072d4fe36af21e1551316242ba5ebb5a011d38ca
hyperium/hyper
645
hyperium__hyper-645
[ "640" ]
8dbc38c75acfc93557f7acdba58edeb8d27dfa2d
diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -34,7 +34,7 @@ impl Default for Config { #[derive(Debug)] struct PoolImpl<S> { - conns: HashMap<Key, Vec<S>>, + conns: HashMap<Key, Vec<PooledStreamInner<S>>>, config: Config, } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -90,7 +90,7 @@ impl<C: NetworkConnector> Pool<C> { } impl<S> PoolImpl<S> { - fn reuse(&mut self, key: Key, conn: S) { + fn reuse(&mut self, key: Key, conn: PooledStreamInner<S>) { trace!("reuse {:?}", key); let conns = self.conns.entry(key).or_insert(vec![]); if conns.len() < self.config.max_idle { diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -105,73 +105,97 @@ impl<C: NetworkConnector<Stream=S>, S: NetworkStream + Send> NetworkConnector fo let key = key(host, port, scheme); let mut locked = self.inner.lock().unwrap(); let mut should_remove = false; - let conn = match locked.conns.get_mut(&key) { + let inner = match locked.conns.get_mut(&key) { Some(ref mut vec) => { trace!("Pool had connection, using"); should_remove = vec.len() == 1; vec.pop().unwrap() } - _ => try!(self.connector.connect(host, port, scheme)) + _ => PooledStreamInner { + key: key.clone(), + stream: try!(self.connector.connect(host, port, scheme)), + previous_response_expected_no_content: false, + } }; if should_remove { locked.conns.remove(&key); } Ok(PooledStream { - inner: Some((key, conn)), + inner: Some(inner), is_closed: false, - pool: self.inner.clone() + pool: self.inner.clone(), }) } } /// A Stream that will try to be returned to the Pool when dropped. pub struct PooledStream<S> { - inner: Option<(Key, S)>, + inner: Option<PooledStreamInner<S>>, is_closed: bool, - pool: Arc<Mutex<PoolImpl<S>>> + pool: Arc<Mutex<PoolImpl<S>>>, +} + +#[derive(Debug)] +struct PooledStreamInner<S> { + key: Key, + stream: S, + previous_response_expected_no_content: bool, } impl<S: NetworkStream> Read for PooledStream<S> { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.inner.as_mut().unwrap().1.read(buf) + self.inner.as_mut().unwrap().stream.read(buf) } } impl<S: NetworkStream> Write for PooledStream<S> { #[inline] fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.inner.as_mut().unwrap().1.write(buf) + self.inner.as_mut().unwrap().stream.write(buf) } #[inline] fn flush(&mut self) -> io::Result<()> { - self.inner.as_mut().unwrap().1.flush() + self.inner.as_mut().unwrap().stream.flush() } } impl<S: NetworkStream> NetworkStream for PooledStream<S> { #[inline] fn peer_addr(&mut self) -> io::Result<SocketAddr> { - self.inner.as_mut().unwrap().1.peer_addr() + self.inner.as_mut().unwrap().stream.peer_addr() } #[cfg(feature = "timeouts")] #[inline] fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.inner.as_ref().unwrap().1.set_read_timeout(dur) + self.inner.as_ref().unwrap().stream.set_read_timeout(dur) } #[cfg(feature = "timeouts")] #[inline] fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.inner.as_ref().unwrap().1.set_write_timeout(dur) + self.inner.as_ref().unwrap().stream.set_write_timeout(dur) } #[inline] fn close(&mut self, how: Shutdown) -> io::Result<()> { self.is_closed = true; - self.inner.as_mut().unwrap().1.close(how) + self.inner.as_mut().unwrap().stream.close(how) + } + + #[inline] + fn set_previous_response_expected_no_content(&mut self, expected: bool) { + trace!("set_previous_response_expected_no_content {}", expected); + self.inner.as_mut().unwrap().previous_response_expected_no_content = expected; + } + + #[inline] + fn previous_response_expected_no_content(&self) -> bool { + let answer = self.inner.as_ref().unwrap().previous_response_expected_no_content; + trace!("previous_response_expected_no_content {}", answer); + answer } } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -179,9 +203,9 @@ impl<S> Drop for PooledStream<S> { fn drop(&mut self) { trace!("PooledStream.drop, is_closed={}", self.is_closed); if !self.is_closed { - self.inner.take().map(|(key, conn)| { + self.inner.take().map(|inner| { if let Ok(mut pool) = self.pool.lock() { - pool.reuse(key, conn); + pool.reuse(inner.key.clone(), inner); } // else poisoned, give up }); diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -64,7 +64,6 @@ impl Response { pub fn status_raw(&self) -> &RawStatus { &self.status_raw } - } impl Read for Response { diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -91,11 +90,11 @@ impl Drop for Response { // // otherwise, the response has been drained. we should check that the // server has agreed to keep the connection open - trace!("Response.is_drained = {:?}", self.is_drained); + trace!("Response.drop is_drained={}", self.is_drained); if !(self.is_drained && http::should_keep_alive(self.version, &self.headers)) { - trace!("closing connection"); + trace!("Response.drop closing connection"); if let Err(e) = self.message.close_connection() { - error!("error closing connection: {}", e); + error!("Response.drop error closing connection: {}", e); } } } diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -33,6 +33,8 @@ use http::{ use header; use version; +const MAX_INVALID_RESPONSE_BYTES: usize = 1024 * 128; + /// An implementation of the `HttpMessage` trait for HTTP/1.1. #[derive(Debug)] pub struct Http11Message { diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -169,19 +171,38 @@ impl HttpMessage for Http11Message { } }; + let expected_no_content = stream.previous_response_expected_no_content(); + trace!("previous_response_expected_no_content = {}", expected_no_content); + let mut stream = BufReader::new(stream); - let head = match parse_response(&mut stream) { - Ok(head) => head, - Err(e) => { - self.stream = Some(stream.into_inner()); - return Err(e); - } - }; + let mut invalid_bytes_read = 0; + let head; + loop { + head = match parse_response(&mut stream) { + Ok(head) => head, + Err(::Error::Version) + if expected_no_content && invalid_bytes_read < MAX_INVALID_RESPONSE_BYTES => { + trace!("expected_no_content, found content"); + invalid_bytes_read += 1; + stream.consume(1); + continue; + } + Err(e) => { + self.stream = Some(stream.into_inner()); + return Err(e); + } + }; + break; + } + let raw_status = head.subject; let headers = head.headers; let method = self.method.take().unwrap_or(Method::Get); + + let is_empty = !should_have_response_body(&method, raw_status.0); + stream.get_mut().set_previous_response_expected_no_content(is_empty); // According to https://tools.ietf.org/html/rfc7230#section-3.3.3 // 1. HEAD reponses, and Status 1xx, 204, and 304 cannot have a body. // 2. Status 2xx to a CONNECT cannot have a body. diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -190,27 +211,24 @@ impl HttpMessage for Http11Message { // 5. Content-Length header has a sized body. // 6. Not Client. // 7. Read till EOF. - self.reader = Some(match (method, raw_status.0) { - (Method::Head, _) => EmptyReader(stream), - (_, 100...199) | (_, 204) | (_, 304) => EmptyReader(stream), - (Method::Connect, 200...299) => EmptyReader(stream), - _ => { - if let Some(&TransferEncoding(ref codings)) = headers.get() { - if codings.last() == Some(&Chunked) { - ChunkedReader(stream, None) - } else { - trace!("not chuncked. read till eof"); - EofReader(stream) - } - } else if let Some(&ContentLength(len)) = headers.get() { - SizedReader(stream, len) - } else if headers.has::<ContentLength>() { - trace!("illegal Content-Length: {:?}", headers.get_raw("Content-Length")); - return Err(Error::Header); + self.reader = Some(if is_empty { + EmptyReader(stream) + } else { + if let Some(&TransferEncoding(ref codings)) = headers.get() { + if codings.last() == Some(&Chunked) { + ChunkedReader(stream, None) } else { - trace!("neither Transfer-Encoding nor Content-Length"); + trace!("not chuncked. read till eof"); EofReader(stream) } + } else if let Some(&ContentLength(len)) = headers.get() { + SizedReader(stream, len) + } else if headers.has::<ContentLength>() { + trace!("illegal Content-Length: {:?}", headers.get_raw("Content-Length")); + return Err(Error::Header); + } else { + trace!("neither Transfer-Encoding nor Content-Length"); + EofReader(stream) } }); diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -226,7 +244,9 @@ impl HttpMessage for Http11Message { fn has_body(&self) -> bool { match self.reader { - Some(EmptyReader(..)) => false, + Some(EmptyReader(..)) | + Some(SizedReader(_, 0)) | + Some(ChunkedReader(_, Some(0))) => false, _ => true } } diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -597,6 +617,18 @@ fn read_chunk_size<R: Read>(rdr: &mut R) -> io::Result<u64> { Ok(size) } +fn should_have_response_body(method: &Method, status: u16) -> bool { + trace!("should_have_response_body({:?}, {})", method, status); + match (method, status) { + (&Method::Head, _) | + (_, 100...199) | + (_, 204) | + (_, 304) | + (&Method::Connect, 200...299) => false, + _ => true + } +} + /// Writers to handle different Transfer-Encodings. pub enum HttpWriter<W: Write> { /// A no-op Writer, used initially before Transfer-Encoding is determined. diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -19,6 +19,7 @@ use net::{NetworkStream, NetworkConnector}; #[derive(Clone, Debug)] pub struct MockStream { pub read: Cursor<Vec<u8>>, + next_reads: Vec<Vec<u8>>, pub write: Vec<u8>, pub is_closed: bool, pub error_on_write: bool, diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -40,27 +41,33 @@ impl MockStream { MockStream::with_input(b"") } - #[cfg(not(feature = "timeouts"))] pub fn with_input(input: &[u8]) -> MockStream { + MockStream::with_responses(vec![input]) + } + + #[cfg(feature = "timeouts")] + pub fn with_responses(mut responses: Vec<&[u8]>) -> MockStream { MockStream { - read: Cursor::new(input.to_vec()), + read: Cursor::new(responses.remove(0).to_vec()), + next_reads: responses.into_iter().map(|arr| arr.to_vec()).collect(), write: vec![], is_closed: false, error_on_write: false, error_on_read: false, + read_timeout: Cell::new(None), + write_timeout: Cell::new(None), } } - #[cfg(feature = "timeouts")] - pub fn with_input(input: &[u8]) -> MockStream { + #[cfg(not(feature = "timeouts"))] + pub fn with_responses(mut responses: Vec<&[u8]>) -> MockStream { MockStream { - read: Cursor::new(input.to_vec()), + read: Cursor::new(responses.remove(0).to_vec()), + next_reads: responses.into_iter().map(|arr| arr.to_vec()).collect(), write: vec![], is_closed: false, error_on_write: false, error_on_read: false, - read_timeout: Cell::new(None), - write_timeout: Cell::new(None), } } } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -70,7 +77,17 @@ impl Read for MockStream { if self.error_on_read { Err(io::Error::new(io::ErrorKind::Other, "mock error")) } else { - self.read.read(buf) + match self.read.read(buf) { + Ok(n) => { + if self.read.position() as usize == self.read.get_ref().len() { + if self.next_reads.len() > 0 { + self.read = Cursor::new(self.next_reads.remove(0)); + } + } + Ok(n) + }, + r => r + } } } } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -191,7 +208,7 @@ macro_rules! mock_connector ( struct $name; - impl ::net::NetworkConnector for $name { + impl $crate::net::NetworkConnector for $name { type Stream = ::mock::MockStream; fn connect(&self, host: &str, port: u16, scheme: &str) -> $crate::Result<::mock::MockStream> { diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -210,7 +227,21 @@ macro_rules! mock_connector ( } } - ) + ); + + ($name:ident { $($response:expr),+ }) => ( + struct $name; + + impl $crate::net::NetworkConnector for $name { + type Stream = $crate::mock::MockStream; + fn connect(&self, _: &str, _: u16, _: &str) + -> $crate::Result<$crate::mock::MockStream> { + Ok($crate::mock::MockStream::with_responses(vec![ + $($response),+ + ])) + } + } + ); ); impl TransportStream for MockStream { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -62,6 +62,17 @@ pub trait NetworkStream: Read + Write + Any + Send + Typeable { fn close(&mut self, _how: Shutdown) -> io::Result<()> { Ok(()) } + + // Unsure about name and implementation... + + #[doc(hidden)] + fn set_previous_response_expected_no_content(&mut self, _expected: bool) { + + } + #[doc(hidden)] + fn previous_response_expected_no_content(&self) -> bool { + false + } } /// A connector creates a NetworkStream.
diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -446,8 +446,10 @@ fn get_host_and_port(url: &Url) -> ::Result<(String, u16)> { #[cfg(test)] mod tests { + use std::io::Read; use header::Server; use super::{Client, RedirectPolicy}; + use super::pool::Pool; use url::Url; mock_connector!(MockRedirectPolicy { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -494,4 +496,31 @@ mod tests { let res = client.get("http://127.0.0.1").send().unwrap(); assert_eq!(res.headers.get(), Some(&Server("mock2".to_owned()))); } + + mock_connector!(Issue640Connector { + b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\n", + b"GET", + b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\n", + b"HEAD", + b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\n", + b"POST" + }); + + // see issue #640 + #[test] + fn test_head_response_body_keep_alive() { + let client = Client::with_connector(Pool::with_connector(Default::default(), Issue640Connector)); + + let mut s = String::new(); + client.get("http://127.0.0.1").send().unwrap().read_to_string(&mut s).unwrap(); + assert_eq!(s, "GET"); + + let mut s = String::new(); + client.head("http://127.0.0.1").send().unwrap().read_to_string(&mut s).unwrap(); + assert_eq!(s, ""); + + let mut s = String::new(); + client.post("http://127.0.0.1").send().unwrap().read_to_string(&mut s).unwrap(); + assert_eq!(s, "POST"); + } }
Client Connection Pool wrongly handles HEAD response with body
2015-09-01T23:49:03Z
0.6
072d4fe36af21e1551316242ba5ebb5a011d38ca
hyperium/hyper
636
hyperium__hyper-636
[ "635" ]
44a4010537dd9abbdf803061226505b56a053bc8
diff --git a/src/header/common/connection.rs b/src/header/common/connection.rs --- a/src/header/common/connection.rs +++ b/src/header/common/connection.rs @@ -4,6 +4,9 @@ use unicase::UniCase; pub use self::ConnectionOption::{KeepAlive, Close, ConnectionHeader}; +const KEEP_ALIVE: UniCase<&'static str> = UniCase("keep-alive"); +const CLOSE: UniCase<&'static str> = UniCase("close"); + /// Values that can be in the `Connection` header. #[derive(Clone, PartialEq, Debug)] pub enum ConnectionOption { diff --git a/src/header/common/connection.rs b/src/header/common/connection.rs --- a/src/header/common/connection.rs +++ b/src/header/common/connection.rs @@ -25,10 +28,12 @@ pub enum ConnectionOption { impl FromStr for ConnectionOption { type Err = (); fn from_str(s: &str) -> Result<ConnectionOption, ()> { - match s { - "keep-alive" => Ok(KeepAlive), - "close" => Ok(Close), - s => Ok(ConnectionHeader(UniCase(s.to_owned()))) + if UniCase(s) == KEEP_ALIVE { + Ok(KeepAlive) + } else if UniCase(s) == CLOSE { + Ok(Close) + } else { + Ok(ConnectionHeader(UniCase(s.to_owned()))) } } }
diff --git a/src/header/common/connection.rs b/src/header/common/connection.rs --- a/src/header/common/connection.rs +++ b/src/header/common/connection.rs @@ -131,6 +136,7 @@ mod tests { fn test_parse() { assert_eq!(Connection::close(),parse_option(b"close".to_vec())); assert_eq!(Connection::keep_alive(),parse_option(b"keep-alive".to_vec())); + assert_eq!(Connection::keep_alive(),parse_option(b"Keep-Alive".to_vec())); assert_eq!(Connection(vec![ConnectionHeader(UniCase("upgrade".to_owned()))]), parse_option(b"upgrade".to_vec())); }
Connection Header case insensitivity http://tools.ietf.org/html/rfc7230#section-6.1: ``` ... "Connection options are case-insensitive." ... ``` I noticed that Apache Bench sends "Keep-Alive" and hyper misinterprets it ``` DEBUG:hyper::server::request: Headers { Connection: Keep-Alive, Host: 192.168.66.62:8881, Accept: */*, User-Agent: ApacheBench/2.3, } TRACE:hyper::http: should_keep_alive( Http10, Some(Connection([ConnectionHeader(UniCase("Keep-Alive"))])) ) ``` I think this may also apply to most other headers
2015-08-27T22:39:32Z
0.6
072d4fe36af21e1551316242ba5ebb5a011d38ca
hyperium/hyper
632
hyperium__hyper-632
[ "629" ]
da2d29309a986ba25c5af6e95c71d033c48e4b2c
diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -1,4 +1,5 @@ //! HTTP RequestUris +use std::fmt::{Display, self}; use std::str::FromStr; use url::Url; use url::ParseError as UrlError;
diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -72,6 +73,17 @@ impl FromStr for RequestUri { } } +impl Display for RequestUri { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + RequestUri::AbsolutePath(ref path) => f.write_str(path), + RequestUri::AbsoluteUri(ref url) => write!(f, "{}", url), + RequestUri::Authority(ref path) => f.write_str(path), + RequestUri::Star => f.write_str("*") + } + } +} + #[test] fn test_uri_fromstr() { fn read(s: &str, result: RequestUri) { diff --git a/src/uri.rs b/src/uri.rs --- a/src/uri.rs +++ b/src/uri.rs @@ -83,3 +95,16 @@ fn test_uri_fromstr() { read("hyper.rs", RequestUri::Authority("hyper.rs".to_owned())); read("/", RequestUri::AbsolutePath("/".to_owned())); } + +#[test] +fn test_uri_display() { + fn assert_display(expected_string: &str, request_uri: RequestUri) { + assert_eq!(expected_string, format!("{}", request_uri)); + } + + assert_display("*", RequestUri::Star); + assert_display("http://hyper.rs/", RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap())); + assert_display("hyper.rs", RequestUri::Authority("hyper.rs".to_owned())); + assert_display("/", RequestUri::AbsolutePath("/".to_owned())); + +}
implement fmt::Display for RequestUri
2015-08-18T20:29:29Z
0.6
072d4fe36af21e1551316242ba5ebb5a011d38ca
hyperium/hyper
625
hyperium__hyper-625
[ "436" ]
af062ac954d5b90275138880ce2f5013d6664b5a
diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -47,9 +47,9 @@ impl Response { version: version, headers: headers, url: url, - message: message, status_raw: raw_status, - is_drained: false, + is_drained: !message.has_body(), + message: message, }) } diff --git a/src/header/parsing.rs b/src/header/parsing.rs --- a/src/header/parsing.rs +++ b/src/header/parsing.rs @@ -3,16 +3,17 @@ use std::str; use std::fmt::{self, Display}; -/// Reads a single raw string when parsing a header +/// Reads a single raw string when parsing a header. pub fn from_one_raw_str<T: str::FromStr>(raw: &[Vec<u8>]) -> ::Result<T> { if raw.len() != 1 || unsafe { raw.get_unchecked(0) } == b"" { return Err(::Error::Header) } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. - let s: &str = try!(str::from_utf8(& unsafe { raw.get_unchecked(0) }[..])); - if let Ok(x) = str::FromStr::from_str(s) { - Ok(x) - } else { - Err(::Error::Header) - } + from_raw_str(& unsafe { raw.get_unchecked(0) }) +} + +/// Reads a raw string into a value. +pub fn from_raw_str<T: str::FromStr>(raw: &[u8]) -> ::Result<T> { + let s = try!(str::from_utf8(raw)); + T::from_str(s).or(Err(::Error::Header)) } /// Reads a comma-delimited raw header into a Vec. diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -36,6 +36,7 @@ use version; /// An implementation of the `HttpMessage` trait for HTTP/1.1. #[derive(Debug)] pub struct Http11Message { + method: Option<Method>, stream: Option<Box<NetworkStream + Send>>, writer: Option<HttpWriter<BufWriter<Box<NetworkStream + Send>>>>, reader: Option<HttpReader<BufReader<Box<NetworkStream + Send>>>>, diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -91,8 +92,8 @@ impl HttpMessage for Http11Message { try!(write!(&mut stream, "{} {} {}{}", head.method, uri, version, LINE_ENDING)); - let stream = match head.method { - Method::Get | Method::Head => { + let stream = match &head.method { + &Method::Get | &Method::Head => { debug!("headers={:?}", head.headers); try!(write!(&mut stream, "{}{}", head.headers, LINE_ENDING)); EmptyWriter(stream) diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -137,6 +138,7 @@ impl HttpMessage for Http11Message { } }; + self.method = Some(head.method.clone()); self.writer = Some(stream); Ok(head) diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -159,30 +161,37 @@ impl HttpMessage for Http11Message { let raw_status = head.subject; let headers = head.headers; - let body = if headers.has::<TransferEncoding>() { - match headers.get::<TransferEncoding>() { - Some(&TransferEncoding(ref codings)) => { - if codings.len() > 1 { - trace!("TODO: #2 handle other codings: {:?}", codings); - }; - - if codings.contains(&Chunked) { + let method = self.method.take().unwrap_or(Method::Get); + // According to https://tools.ietf.org/html/rfc7230#section-3.3.3 + // 1. HEAD reponses, and Status 1xx, 204, and 304 cannot have a body. + // 2. Status 2xx to a CONNECT cannot have a body. + // 3. Transfer-Encoding: chunked has a chunked body. + // 4. If multiple differing Content-Length headers or invalid, close connection. + // 5. Content-Length header has a sized body. + // 6. Not Client. + // 7. Read till EOF. + let body = match (method, raw_status.0) { + (Method::Head, _) => EmptyReader(stream), + (_, 100...199) | (_, 204) | (_, 304) => EmptyReader(stream), + (Method::Connect, 200...299) => EmptyReader(stream), + _ => { + if let Some(&TransferEncoding(ref codings)) = headers.get() { + if codings.last() == Some(&Chunked) { ChunkedReader(stream, None) } else { trace!("not chuncked. read till eof"); EofReader(stream) } + } else if let Some(&ContentLength(len)) = headers.get() { + SizedReader(stream, len) + } else if headers.has::<ContentLength>() { + trace!("illegal Content-Length: {:?}", headers.get_raw("Content-Length")); + return Err(Error::Header); + } else { + trace!("neither Transfer-Encoding nor Content-Length"); + EofReader(stream) } - None => unreachable!() - } - } else if headers.has::<ContentLength>() { - match headers.get::<ContentLength>() { - Some(&ContentLength(len)) => SizedReader(stream, len), - None => unreachable!() } - } else { - trace!("neither Transfer-Encoding nor Content-Length"); - EofReader(stream) }; self.reader = Some(body); diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -194,6 +203,13 @@ impl HttpMessage for Http11Message { }) } + fn has_body(&self) -> bool { + match self.reader { + Some(EmptyReader(..)) => false, + _ => true + } + } + #[cfg(feature = "timeouts")] #[inline] fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -259,6 +275,7 @@ impl Http11Message { /// the peer. pub fn with_stream(stream: Box<NetworkStream + Send>) -> Http11Message { Http11Message { + method: None, stream: Some(stream), writer: None, reader: None, diff --git a/src/http/h2.rs b/src/http/h2.rs --- a/src/http/h2.rs +++ b/src/http/h2.rs @@ -400,6 +400,10 @@ impl<S> HttpMessage for Http2Message<S> where S: CloneableStream { Ok(head) } + fn has_body(&self) -> bool { + true + } + #[cfg(feature = "timeouts")] #[inline] fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> { diff --git a/src/http/message.rs b/src/http/message.rs --- a/src/http/message.rs +++ b/src/http/message.rs @@ -72,6 +72,8 @@ pub trait HttpMessage: Write + Read + Send + Any + Typeable + Debug { fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()>; /// Closes the underlying HTTP connection. fn close_connection(&mut self) -> ::Result<()>; + /// Returns whether the incoming message has a body. + fn has_body(&self) -> bool; } impl HttpMessage {
diff --git a/src/header/common/content_length.rs b/src/header/common/content_length.rs --- a/src/header/common/content_length.rs +++ b/src/header/common/content_length.rs @@ -1,37 +1,86 @@ -header! { - #[doc="`Content-Length` header, defined in"] - #[doc="[RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2)"] - #[doc=""] - #[doc="When a message does not have a `Transfer-Encoding` header field, a"] - #[doc="Content-Length header field can provide the anticipated size, as a"] - #[doc="decimal number of octets, for a potential payload body. For messages"] - #[doc="that do include a payload body, the Content-Length field-value"] - #[doc="provides the framing information necessary for determining where the"] - #[doc="body (and message) ends. For messages that do not include a payload"] - #[doc="body, the Content-Length indicates the size of the selected"] - #[doc="representation."] - #[doc=""] - #[doc="# ABNF"] - #[doc="```plain"] - #[doc="Content-Length = 1*DIGIT"] - #[doc="```"] - #[doc=""] - #[doc="# Example values"] - #[doc="* `3495`"] - #[doc=""] - #[doc="# Example"] - #[doc="```"] - #[doc="use hyper::header::{Headers, ContentLength};"] - #[doc=""] - #[doc="let mut headers = Headers::new();"] - #[doc="headers.set(ContentLength(1024u64));"] - #[doc="```"] - (ContentLength, "Content-Length") => [u64] - - test_content_length { - // Testcase from RFC - test_header!(test1, vec![b"3495"], Some(HeaderField(3495))); +use std::fmt; + +use header::{HeaderFormat, Header, parsing}; + +#[doc="`Content-Length` header, defined in"] +#[doc="[RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2)"] +#[doc=""] +#[doc="When a message does not have a `Transfer-Encoding` header field, a"] +#[doc="Content-Length header field can provide the anticipated size, as a"] +#[doc="decimal number of octets, for a potential payload body. For messages"] +#[doc="that do include a payload body, the Content-Length field-value"] +#[doc="provides the framing information necessary for determining where the"] +#[doc="body (and message) ends. For messages that do not include a payload"] +#[doc="body, the Content-Length indicates the size of the selected"] +#[doc="representation."] +#[doc=""] +#[doc="# ABNF"] +#[doc="```plain"] +#[doc="Content-Length = 1*DIGIT"] +#[doc="```"] +#[doc=""] +#[doc="# Example values"] +#[doc="* `3495`"] +#[doc=""] +#[doc="# Example"] +#[doc="```"] +#[doc="use hyper::header::{Headers, ContentLength};"] +#[doc=""] +#[doc="let mut headers = Headers::new();"] +#[doc="headers.set(ContentLength(1024u64));"] +#[doc="```"] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ContentLength(pub u64); + +impl Header for ContentLength { + #[inline] + fn header_name() -> &'static str { + "Content-Length" + } + fn parse_header(raw: &[Vec<u8>]) -> ::Result<ContentLength> { + // If multiple Content-Length headers were sent, everything can still + // be alright if they all contain the same value, and all parse + // correctly. If not, then it's an error. + raw.iter() + .map(::std::ops::Deref::deref) + .map(parsing::from_raw_str) + .fold(None, |prev, x| { + match (prev, x) { + (None, x) => Some(x), + (e@Some(Err(_)), _ ) => e, + (Some(Ok(prev)), Ok(x)) if prev == x => Some(Ok(prev)), + _ => Some(Err(::Error::Header)) + } + }) + .unwrap_or(Err(::Error::Header)) + .map(ContentLength) + } +} + +impl HeaderFormat for ContentLength { + #[inline] + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&self.0, f) } } +impl fmt::Display for ContentLength { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&self.0, f) + } +} + +__hyper__deref!(ContentLength => u64); +__hyper_generate_header_serialization!(ContentLength); + +__hyper__tm!(ContentLength, tests { + // Testcase from RFC + test_header!(test1, vec![b"3495"], Some(HeaderField(3495))); + + test_header!(test_invalid, vec![b"34v95"], None); + test_header!(test_duplicates, vec![b"5", b"5"], Some(HeaderField(5))); + test_header!(test_duplicates_vary, vec![b"5", b"6", b"5"], None); +}); + bench_header!(bench, ContentLength, { vec![b"42349984".to_vec()] }); diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -148,12 +148,13 @@ macro_rules! test_header { fn $id() { let a: Vec<Vec<u8>> = $raw.iter().map(|x| x.to_vec()).collect(); let val = HeaderField::parse_header(&a[..]); + let typed: Option<HeaderField> = $typed; // Test parsing - assert_eq!(val.ok(), $typed); + assert_eq!(val.ok(), typed); // Test formatting - if $typed != None { + if typed.is_some() { let res: &str = str::from_utf8($raw[0]).unwrap(); - assert_eq!(format!("{}", $typed.unwrap()), res); + assert_eq!(format!("{}", typed.unwrap()), res); } } }
When a server returns NoContent, reading the response should not hang When a client makes a request that results in a `NoContent` status code, the read methods on the repsonse should return an immediate EOF status, rather than blocking.
2015-08-05T23:47:36Z
0.6
072d4fe36af21e1551316242ba5ebb5a011d38ca
hyperium/hyper
621
hyperium__hyper-621
[ "315" ]
421422b620206c43bc85e05b973042da1b20f130
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -47,5 +47,5 @@ env_logger = "*" default = ["ssl"] ssl = ["openssl", "cookie/secure"] serde-serialization = ["serde"] -nightly = [] - +timeouts = [] +nightly = ["timeouts"] diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -59,13 +59,16 @@ use std::default::Default; use std::io::{self, copy, Read}; use std::iter::Extend; +#[cfg(feature = "timeouts")] +use std::time::Duration; + use url::UrlParser; use url::ParseError as UrlError; use header::{Headers, Header, HeaderFormat}; use header::{ContentLength, Location}; use method::Method; -use net::{NetworkConnector, NetworkStream}; +use net::{NetworkConnector, NetworkStream, Fresh}; use {Url}; use Error; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -87,7 +90,9 @@ pub struct Client { protocol: Box<Protocol + Send + Sync>, redirect_policy: RedirectPolicy, #[cfg(feature = "timeouts")] - read_timeout: Option<Duration> + read_timeout: Option<Duration>, + #[cfg(feature = "timeouts")] + write_timeout: Option<Duration>, } impl Client { diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -108,11 +113,23 @@ impl Client { Client::with_protocol(Http11Protocol::with_connector(connector)) } + #[cfg(not(feature = "timeouts"))] + /// Create a new client with a specific `Protocol`. + pub fn with_protocol<P: Protocol + Send + Sync + 'static>(protocol: P) -> Client { + Client { + protocol: Box::new(protocol), + redirect_policy: Default::default(), + } + } + + #[cfg(feature = "timeouts")] /// Create a new client with a specific `Protocol`. pub fn with_protocol<P: Protocol + Send + Sync + 'static>(protocol: P) -> Client { Client { protocol: Box::new(protocol), - redirect_policy: Default::default() + redirect_policy: Default::default(), + read_timeout: None, + write_timeout: None, } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -127,6 +144,12 @@ impl Client { self.read_timeout = dur; } + /// Set the write timeout value for all requests. + #[cfg(feature = "timeouts")] + pub fn set_write_timeout(&mut self, dur: Option<Duration>) { + self.write_timeout = dur; + } + /// Build a Get request. pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder<U> { self.request(Method::Get, url) diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -236,6 +259,20 @@ impl<'a, U: IntoUrl> RequestBuilder<'a, U> { let mut req = try!(Request::with_message(method.clone(), url.clone(), message)); headers.as_ref().map(|headers| req.headers_mut().extend(headers.iter())); + #[cfg(not(feature = "timeouts"))] + fn set_timeouts(_req: &mut Request<Fresh>, _client: &Client) -> ::Result<()> { + Ok(()) + } + + #[cfg(feature = "timeouts")] + fn set_timeouts(req: &mut Request<Fresh>, client: &Client) -> ::Result<()> { + try!(req.set_write_timeout(client.write_timeout)); + try!(req.set_read_timeout(client.read_timeout)); + Ok(()) + } + + try!(set_timeouts(&mut req, &client)); + match (can_have_body, body.as_ref()) { (true, Some(body)) => match body.size() { Some(size) => req.headers_mut().set(ContentLength(size)), diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -5,6 +5,9 @@ use std::io::{self, Read, Write}; use std::net::{SocketAddr, Shutdown}; use std::sync::{Arc, Mutex}; +#[cfg(feature = "timeouts")] +use std::time::Duration; + use net::{NetworkConnector, NetworkStream, DefaultConnector}; /// The `NetworkConnector` that behaves as a connection pool used by hyper's `Client`. diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -153,6 +156,18 @@ impl<S: NetworkStream> NetworkStream for PooledStream<S> { self.inner.as_mut().unwrap().1.peer_addr() } + #[cfg(feature = "timeouts")] + #[inline] + fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + self.inner.as_ref().unwrap().1.set_read_timeout(dur) + } + + #[cfg(feature = "timeouts")] + #[inline] + fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + self.inner.as_ref().unwrap().1.set_write_timeout(dur) + } + #[inline] fn close(&mut self, how: Shutdown) -> io::Result<()> { self.is_closed = true; diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -2,6 +2,9 @@ use std::marker::PhantomData; use std::io::{self, Write}; +#[cfg(feature = "timeouts")] +use std::time::Duration; + use url::Url; use method::{self, Method}; diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -39,6 +42,20 @@ impl<W> Request<W> { /// Read the Request method. #[inline] pub fn method(&self) -> method::Method { self.method.clone() } + + /// Set the write timeout. + #[cfg(feature = "timeouts")] + #[inline] + pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + self.message.set_write_timeout(dur) + } + + /// Set the read timeout. + #[cfg(feature = "timeouts")] + #[inline] + pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + self.message.set_read_timeout(dur) + } } impl Request<Fresh> { diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -4,6 +4,8 @@ use std::cmp::min; use std::fmt; use std::io::{self, Write, BufWriter, BufRead, Read}; use std::net::Shutdown; +#[cfg(feature = "timeouts")] +use std::time::Duration; use httparse; diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -192,6 +194,19 @@ impl HttpMessage for Http11Message { }) } + #[cfg(feature = "timeouts")] + #[inline] + fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + self.get_ref().set_read_timeout(dur) + } + + #[cfg(feature = "timeouts")] + #[inline] + fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + self.get_ref().set_write_timeout(dur) + } + + #[inline] fn close_connection(&mut self) -> ::Result<()> { try!(self.get_mut().close(Shutdown::Both)); Ok(()) diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -214,13 +229,27 @@ impl Http11Message { /// Gets a mutable reference to the underlying `NetworkStream`, regardless of the state of the /// `Http11Message`. - pub fn get_mut(&mut self) -> &mut Box<NetworkStream + Send> { + pub fn get_ref(&self) -> &(NetworkStream + Send) { if self.stream.is_some() { - self.stream.as_mut().unwrap() + &**self.stream.as_ref().unwrap() } else if self.writer.is_some() { - self.writer.as_mut().unwrap().get_mut().get_mut() + &**self.writer.as_ref().unwrap().get_ref().get_ref() } else if self.reader.is_some() { - self.reader.as_mut().unwrap().get_mut().get_mut() + &**self.reader.as_ref().unwrap().get_ref().get_ref() + } else { + panic!("Http11Message lost its underlying stream somehow"); + } + } + + /// Gets a mutable reference to the underlying `NetworkStream`, regardless of the state of the + /// `Http11Message`. + pub fn get_mut(&mut self) -> &mut (NetworkStream + Send) { + if self.stream.is_some() { + &mut **self.stream.as_mut().unwrap() + } else if self.writer.is_some() { + &mut **self.writer.as_mut().unwrap().get_mut().get_mut() + } else if self.reader.is_some() { + &mut **self.reader.as_mut().unwrap().get_mut().get_mut() } else { panic!("Http11Message lost its underlying stream somehow"); } diff --git a/src/http/h1.rs b/src/http/h1.rs --- a/src/http/h1.rs +++ b/src/http/h1.rs @@ -344,6 +373,16 @@ impl<R: Read> HttpReader<R> { } } + /// Gets a borrowed reference to the underlying Reader. + pub fn get_ref(&self) -> &R { + match *self { + SizedReader(ref r, _) => r, + ChunkedReader(ref r, _) => r, + EofReader(ref r) => r, + EmptyReader(ref r) => r, + } + } + /// Gets a mutable reference to the underlying Reader. pub fn get_mut(&mut self) -> &mut R { match *self { diff --git a/src/http/h2.rs b/src/http/h2.rs --- a/src/http/h2.rs +++ b/src/http/h2.rs @@ -4,6 +4,8 @@ use std::io::{self, Write, Read, Cursor}; use std::net::Shutdown; use std::ascii::AsciiExt; use std::mem; +#[cfg(feature = "timeouts")] +use std::time::Duration; use http::{ Protocol, diff --git a/src/http/h2.rs b/src/http/h2.rs --- a/src/http/h2.rs +++ b/src/http/h2.rs @@ -398,6 +400,19 @@ impl<S> HttpMessage for Http2Message<S> where S: CloneableStream { Ok(head) } + #[cfg(feature = "timeouts")] + #[inline] + fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> { + Ok(()) + } + + #[cfg(feature = "timeouts")] + #[inline] + fn set_write_timeout(&self, _dur: Option<Duration>) -> io::Result<()> { + Ok(()) + } + + #[inline] fn close_connection(&mut self) -> ::Result<()> { Ok(()) } diff --git a/src/http/message.rs b/src/http/message.rs --- a/src/http/message.rs +++ b/src/http/message.rs @@ -1,12 +1,16 @@ //! Defines the `HttpMessage` trait that serves to encapsulate the operations of a single //! request-response cycle on any HTTP connection. -use std::fmt::Debug; use std::any::{Any, TypeId}; +use std::fmt::Debug; use std::io::{Read, Write}; - use std::mem; +#[cfg(feature = "timeouts")] +use std::io; +#[cfg(feature = "timeouts")] +use std::time::Duration; + use typeable::Typeable; use header::Headers; diff --git a/src/http/message.rs b/src/http/message.rs --- a/src/http/message.rs +++ b/src/http/message.rs @@ -62,7 +66,10 @@ pub trait HttpMessage: Write + Read + Send + Any + Typeable + Debug { fn get_incoming(&mut self) -> ::Result<ResponseHead>; /// Set the read timeout duration for this message. #[cfg(feature = "timeouts")] - fn set_read_timeout(&self, dur: Option<Duration>) -> ::Result<()>; + fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()>; + /// Set the write timeout duration for this message. + #[cfg(feature = "timeouts")] + fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()>; /// Closes the underlying HTTP connection. fn close_connection(&mut self) -> ::Result<()>; } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -4,6 +4,10 @@ use std::io::{self, Read, Write, Cursor}; use std::cell::RefCell; use std::net::SocketAddr; use std::sync::{Arc, Mutex}; +#[cfg(feature = "timeouts")] +use std::time::Duration; +#[cfg(feature = "timeouts")] +use std::cell::Cell; use solicit::http::HttpScheme; use solicit::http::transport::TransportStream; diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -13,18 +17,14 @@ use solicit::http::connection::{HttpConnection, EndStream, DataChunk}; use header::Headers; use net::{NetworkStream, NetworkConnector}; +#[derive(Clone)] pub struct MockStream { pub read: Cursor<Vec<u8>>, pub write: Vec<u8>, -} - -impl Clone for MockStream { - fn clone(&self) -> MockStream { - MockStream { - read: Cursor::new(self.read.get_ref().clone()), - write: self.write.clone() - } - } + #[cfg(feature = "timeouts")] + pub read_timeout: Cell<Option<Duration>>, + #[cfg(feature = "timeouts")] + pub write_timeout: Cell<Option<Duration>> } impl fmt::Debug for MockStream { diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -41,16 +41,24 @@ impl PartialEq for MockStream { impl MockStream { pub fn new() -> MockStream { + MockStream::with_input(b"") + } + + #[cfg(not(feature = "timeouts"))] + pub fn with_input(input: &[u8]) -> MockStream { MockStream { - read: Cursor::new(vec![]), - write: vec![], + read: Cursor::new(input.to_vec()), + write: vec![] } } + #[cfg(feature = "timeouts")] pub fn with_input(input: &[u8]) -> MockStream { MockStream { read: Cursor::new(input.to_vec()), - write: vec![] + write: vec![], + read_timeout: Cell::new(None), + write_timeout: Cell::new(None), } } } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -75,6 +83,18 @@ impl NetworkStream for MockStream { fn peer_addr(&mut self) -> io::Result<SocketAddr> { Ok("127.0.0.1:1337".parse().unwrap()) } + + #[cfg(feature = "timeouts")] + fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + self.read_timeout.set(dur); + Ok(()) + } + + #[cfg(feature = "timeouts")] + fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + self.write_timeout.set(dur); + Ok(()) + } } /// A wrapper around a `MockStream` that allows one to clone it and keep an independent copy to the diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -114,6 +134,16 @@ impl NetworkStream for CloneableMockStream { fn peer_addr(&mut self) -> io::Result<SocketAddr> { self.inner.lock().unwrap().peer_addr() } + + #[cfg(feature = "timeouts")] + fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + self.inner.lock().unwrap().set_read_timeout(dur) + } + + #[cfg(feature = "timeouts")] + fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + self.inner.lock().unwrap().set_write_timeout(dur) + } } impl CloneableMockStream { diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -147,7 +177,6 @@ macro_rules! mock_connector ( fn connect(&self, host: &str, port: u16, scheme: &str) -> $crate::Result<::mock::MockStream> { use std::collections::HashMap; - use std::io::Cursor; debug!("MockStream::connect({:?}, {:?}, {:?})", host, port, scheme); let mut map = HashMap::new(); $(map.insert($url, $res);)* diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -156,10 +185,7 @@ macro_rules! mock_connector ( let key = format!("{}://{}", scheme, host); // ignore port for now match map.get(&*key) { - Some(&res) => Ok($crate::mock::MockStream { - write: vec![], - read: Cursor::new(res.to_owned().into_bytes()), - }), + Some(&res) => Ok($crate::mock::MockStream::with_input(res.as_bytes())), None => panic!("{:?} doesn't know url {}", stringify!($name), key) } } diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -8,6 +8,9 @@ use std::mem; #[cfg(feature = "openssl")] pub use self::openssl::Openssl; +#[cfg(feature = "timeouts")] +use std::time::Duration; + use typeable::Typeable; use traitobject; diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -21,8 +24,6 @@ pub enum Streaming {} pub trait NetworkListener: Clone { /// The stream produced for each connection. type Stream: NetworkStream + Send + Clone; - /// Listens on a socket. - //fn listen<To: ToSocketAddrs>(&mut self, addr: To) -> io::Result<Self::Acceptor>; /// Returns an iterator of streams. fn accept(&mut self) -> ::Result<Self::Stream>; diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -30,9 +31,6 @@ pub trait NetworkListener: Clone { /// Get the address this Listener ended up listening on. fn local_addr(&mut self) -> io::Result<SocketAddr>; - /// Closes the Acceptor, so no more incoming connections will be handled. -// fn close(&mut self) -> io::Result<()>; - /// Returns an iterator over incoming connections. fn incoming(&mut self) -> NetworkConnections<Self> { NetworkConnections(self) diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -53,6 +51,12 @@ impl<'a, N: NetworkListener + 'a> Iterator for NetworkConnections<'a, N> { pub trait NetworkStream: Read + Write + Any + Send + Typeable { /// Get the remote address of the underlying connection. fn peer_addr(&mut self) -> io::Result<SocketAddr>; + /// Set the maximum time to wait for a read to complete. + #[cfg(feature = "timeouts")] + fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()>; + /// Set the maximum time to wait for a write to complete. + #[cfg(feature = "timeouts")] + fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()>; /// This will be called when Stream should no longer be kept alive. #[inline] fn close(&mut self, _how: Shutdown) -> io::Result<()> { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -222,6 +226,18 @@ impl NetworkStream for HttpStream { self.0.peer_addr() } + #[cfg(feature = "timeouts")] + #[inline] + fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + self.0.set_read_timeout(dur) + } + + #[cfg(feature = "timeouts")] + #[inline] + fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + self.0.set_write_timeout(dur) + } + #[inline] fn close(&mut self, how: Shutdown) -> io::Result<()> { match self.0.shutdown(how) { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -312,6 +328,24 @@ impl<S: NetworkStream> NetworkStream for HttpsStream<S> { } } + #[cfg(feature = "timeouts")] + #[inline] + fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + match *self { + HttpsStream::Http(ref inner) => inner.0.set_read_timeout(dur), + HttpsStream::Https(ref inner) => inner.set_read_timeout(dur) + } + } + + #[cfg(feature = "timeouts")] + #[inline] + fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + match *self { + HttpsStream::Http(ref inner) => inner.0.set_read_timeout(dur), + HttpsStream::Https(ref inner) => inner.set_read_timeout(dur) + } + } + #[inline] fn close(&mut self, how: Shutdown) -> io::Result<()> { match *self { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -397,6 +431,9 @@ mod openssl { use std::net::{SocketAddr, Shutdown}; use std::path::Path; use std::sync::Arc; + #[cfg(feature = "timeouts")] + use std::time::Duration; + use openssl::ssl::{Ssl, SslContext, SslStream, SslMethod, SSL_VERIFY_NONE}; use openssl::ssl::error::StreamError as SslIoError; use openssl::ssl::error::SslError; diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -475,6 +512,18 @@ mod openssl { self.get_mut().peer_addr() } + #[cfg(feature = "timeouts")] + #[inline] + fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + self.get_ref().set_read_timeout(dur) + } + + #[cfg(feature = "timeouts")] + #[inline] + fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + self.get_ref().set_write_timeout(dur) + } + fn close(&mut self, how: Shutdown) -> io::Result<()> { self.get_mut().close(how) } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -108,10 +108,13 @@ //! `Request<Streaming>` object, that no longer has `headers_mut()`, but does //! implement `Write`. use std::fmt; -use std::io::{ErrorKind, BufWriter, Write}; +use std::io::{self, ErrorKind, BufWriter, Write}; use std::net::{SocketAddr, ToSocketAddrs}; use std::thread::{self, JoinHandle}; +#[cfg(feature = "timeouts")] +use std::time::Duration; + use num_cpus; pub use self::request::Request; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -143,8 +146,20 @@ mod listener; #[derive(Debug)] pub struct Server<L = HttpListener> { listener: L, + _timeouts: Timeouts, +} + +#[cfg(feature = "timeouts")] +#[derive(Clone, Copy, Default, Debug)] +struct Timeouts { + read: Option<Duration>, + write: Option<Duration>, } +#[cfg(not(feature = "timeouts"))] +#[derive(Clone, Copy, Default, Debug)] +struct Timeouts; + macro_rules! try_option( ($e:expr) => {{ match $e { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -159,9 +174,22 @@ impl<L: NetworkListener> Server<L> { #[inline] pub fn new(listener: L) -> Server<L> { Server { - listener: listener + listener: listener, + _timeouts: Timeouts::default(), } } + + #[cfg(feature = "timeouts")] + pub fn set_read_timeout(&mut self, dur: Option<Duration>) { + self._timeouts.read = dur; + } + + #[cfg(feature = "timeouts")] + pub fn set_write_timeout(&mut self, dur: Option<Duration>) { + self._timeouts.write = dur; + } + + } impl Server<HttpListener> { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -183,24 +211,25 @@ impl<S: Ssl + Clone + Send> Server<HttpsListener<S>> { impl<L: NetworkListener + Send + 'static> Server<L> { /// Binds to a socket and starts handling connections. pub fn handle<H: Handler + 'static>(self, handler: H) -> ::Result<Listening> { - with_listener(handler, self.listener, num_cpus::get() * 5 / 4) + self.handle_threads(handler, num_cpus::get() * 5 / 4) } /// Binds to a socket and starts handling connections with the provided /// number of threads. pub fn handle_threads<H: Handler + 'static>(self, handler: H, threads: usize) -> ::Result<Listening> { - with_listener(handler, self.listener, threads) + handle(self, handler, threads) } } -fn with_listener<H, L>(handler: H, mut listener: L, threads: usize) -> ::Result<Listening> +fn handle<H, L>(mut server: Server<L>, handler: H, threads: usize) -> ::Result<Listening> where H: Handler + 'static, L: NetworkListener + Send + 'static { - let socket = try!(listener.local_addr()); + let socket = try!(server.listener.local_addr()); debug!("threads = {:?}", threads); - let pool = ListenerPool::new(listener); - let work = move |mut stream| Worker(&handler).handle_connection(&mut stream); + let pool = ListenerPool::new(server.listener); + let worker = Worker::new(handler, server._timeouts); + let work = move |mut stream| worker.handle_connection(&mut stream); let guard = thread::spawn(move || pool.accept(work, threads)); diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -210,12 +239,28 @@ L: NetworkListener + Send + 'static { }) } -struct Worker<'a, H: Handler + 'static>(&'a H); +struct Worker<H: Handler + 'static> { + handler: H, + _timeouts: Timeouts, +} + +impl<H: Handler + 'static> Worker<H> { -impl<'a, H: Handler + 'static> Worker<'a, H> { + fn new(handler: H, timeouts: Timeouts) -> Worker<H> { + Worker { + handler: handler, + _timeouts: timeouts, + } + } fn handle_connection<S>(&self, mut stream: &mut S) where S: NetworkStream + Clone { debug!("Incoming stream"); + + if let Err(e) = self.set_timeouts(stream) { + error!("set_timeouts error: {:?}", e); + return; + } + let addr = match stream.peer_addr() { Ok(addr) => addr, Err(e) => { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -233,6 +278,17 @@ impl<'a, H: Handler + 'static> Worker<'a, H> { debug!("keep_alive loop ending for {}", addr); } + #[cfg(not(feature = "timeouts"))] + fn set_timeouts<S>(&self, _: &mut S) -> io::Result<()> where S: NetworkStream { + Ok(()) + } + + #[cfg(feature = "timeouts")] + fn set_timeouts<S>(&self, s: &mut S) -> io::Result<()> where S: NetworkStream { + try!(s.set_read_timeout(self._timeouts.read)); + s.set_write_timeout(self._timeouts.write) + } + fn keep_alive_loop<W: Write>(&self, mut rdr: BufReader<&mut NetworkStream>, mut wrt: W, addr: SocketAddr) { let mut keep_alive = true; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -268,7 +324,7 @@ impl<'a, H: Handler + 'static> Worker<'a, H> { { let mut res = Response::new(&mut wrt, &mut res_headers); res.version = version; - self.0.handle(req, res); + self.handler.handle(req, res); } // if the request was keep-alive, we need to check that the server agrees diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -284,7 +340,7 @@ impl<'a, H: Handler + 'static> Worker<'a, H> { fn handle_expect<W: Write>(&self, req: &Request, wrt: &mut W) -> bool { if req.version == Http11 && req.headers.get() == Some(&Expect::Continue) { - let status = self.0.check_continue((&req.method, &req.uri, &req.headers)); + let status = self.handler.check_continue((&req.method, &req.uri, &req.headers)); match write!(wrt, "{} {}\r\n\r\n", Http11, status) { Ok(..) => (), Err(e) => { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -327,7 +383,6 @@ impl Listening { pub fn close(&mut self) -> ::Result<()> { let _ = self._guard.take(); debug!("closing server"); - //try!(self.acceptor.close()); Ok(()) } }
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,7 @@ #![cfg_attr(test, deny(missing_docs))] #![cfg_attr(test, deny(warnings))] #![cfg_attr(all(test, feature = "nightly"), feature(test))] +#![cfg_attr(feature = "timeouts", feature(duration, socket_timeout))] //! # Hyper //! diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -379,7 +434,7 @@ mod tests { res.start().unwrap().end().unwrap(); } - Worker(&handle).handle_connection(&mut mock); + Worker::new(handle, Default::default()).handle_connection(&mut mock); let cont = b"HTTP/1.1 100 Continue\r\n\r\n"; assert_eq!(&mock.write[..cont.len()], cont); let res = b"HTTP/1.1 200 OK\r\n"; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -408,7 +463,7 @@ mod tests { 1234567890\ "); - Worker(&Reject).handle_connection(&mut mock); + Worker::new(Reject, Default::default()).handle_connection(&mut mock); assert_eq!(mock.write, &b"HTTP/1.1 417 Expectation Failed\r\n\r\n"[..]); } }
Support for pervasive timeouts We need to provide timeouts for all of our blocking APIs and ways to set timeouts for all internal blocking actions.
Indeed, and we had a PR offering timeouts, but the IO reform currently means there is no API to do so for TcpStreams. There is now going to be a stable way to timeout on condition variables, so we could implement _something_. Link? On Wed, Apr 1, 2015, 2:13 PM Jonathan Reem notifications@github.com wrote: > There is now going to be a stable way to timeout on condition variables, > so we could implement _something_. > > — > Reply to this email directly or view it on GitHub > https://github.com/hyperium/hyper/issues/315#issuecomment-88633538. https://github.com/rust-lang/rust/pull/23949 I see. So, to support a timeout using those, I imagine having to kick off 2 threads, one that is parked for X ms, the other that tries to `read()`, and we use a `select! {}` on the 2 receivers. Doesn't sound cheap... If you're not happy using `select!` in hyper itself, how about adding an example to the README? It took me a little fiddling to get it working, so having an example would have helped me.
2015-07-27T16:58:37Z
0.6
072d4fe36af21e1551316242ba5ebb5a011d38ca
hyperium/hyper
567
hyperium__hyper-567
[ "468" ]
c37d85728f67997cef4887736c5228322c8967ec
diff --git a/src/header/common/accept.rs b/src/header/common/accept.rs --- a/src/header/common/accept.rs +++ b/src/header/common/accept.rs @@ -27,6 +27,51 @@ header! { #[doc="* `audio/*; q=0.2, audio/basic` (`*` value won't parse correctly)"] #[doc="* `text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c`"] #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, Accept, qitem};"] + #[doc="use hyper::mime::{Mime, TopLevel, SubLevel};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc=""] + #[doc="headers.set("] + #[doc=" Accept(vec!["] + #[doc=" qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])),"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, Accept, qitem};"] + #[doc="use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" Accept(vec!["] + #[doc=" qitem(Mime(TopLevel::Application, SubLevel::Json,"] + #[doc=" vec![(Attr::Charset, Value::Utf8)])),"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, Accept, QualityItem, Quality, qitem};"] + #[doc="use hyper::mime::{Mime, TopLevel, SubLevel};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc=""] + #[doc="headers.set("] + #[doc=" Accept(vec!["] + #[doc=" qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])),"] + #[doc=" qitem(Mime(TopLevel::Application, SubLevel::Ext(\"xhtml+xml\".to_owned()), vec![])),"] + #[doc=" QualityItem::new(Mime(TopLevel::Application, SubLevel::Xml, vec![]),"] + #[doc=" Quality(900)),"] + #[doc=" qitem(Mime(TopLevel::Image, SubLevel::Ext(\"webp\".to_owned()), vec![])), +"] + #[doc=" QualityItem::new(Mime(TopLevel::Star, SubLevel::Star, vec![]),"] + #[doc=" Quality(800))"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] + #[doc=""] #[doc="# Notes"] #[doc="* Using always Mime types to represent `media-range` differs from the ABNF."] #[doc="* **FIXME**: `accept-ext` is not supported."] diff --git a/src/header/common/access_control_allow_origin.rs b/src/header/common/access_control_allow_origin.rs --- a/src/header/common/access_control_allow_origin.rs +++ b/src/header/common/access_control_allow_origin.rs @@ -20,6 +20,33 @@ use header::{Header, HeaderFormat}; /// * `null` /// * `*` /// * `http://google.com/` +/// +/// # Examples +/// ``` +/// use hyper::header::{Headers, AccessControlAllowOrigin}; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// AccessControlAllowOrigin::Any +/// ); +/// ``` +/// ``` +/// use hyper::header::{Headers, AccessControlAllowOrigin}; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// AccessControlAllowOrigin::Null, +/// ); +/// ``` +/// ``` +/// use hyper::header::{Headers, AccessControlAllowOrigin}; +/// use hyper::Url; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// AccessControlAllowOrigin::Value(Url::parse("http://hyper.rs").unwrap()) +/// ); +/// ``` #[derive(Clone, PartialEq, Debug)] pub enum AccessControlAllowOrigin { /// Allow all origins diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -20,6 +20,27 @@ use header::{Header, HeaderFormat}; /// /// # Example values /// * `Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==` +/// +/// # Examples +/// ``` +/// use hyper::header::{Headers, Authorization}; +/// +/// let mut headers = Headers::new(); +/// headers.set(Authorization("let me in".to_owned())); +/// ``` +/// ``` +/// use hyper::header::{Headers, Authorization, Basic}; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// Authorization( +/// Basic { +/// username: "Aladdin".to_owned(), +/// password: Some("open sesame".to_owned()) +/// } +/// ) +/// ); +/// ``` #[derive(Clone, PartialEq, Debug)] pub struct Authorization<S: Scheme>(pub S); diff --git a/src/header/common/cache_control.rs b/src/header/common/cache_control.rs --- a/src/header/common/cache_control.rs +++ b/src/header/common/cache_control.rs @@ -20,6 +20,30 @@ use header::parsing::{from_one_comma_delimited, fmt_comma_delimited}; /// * `no-cache` /// * `private, community="UCI"` /// * `max-age=30` +/// +/// # Examples +/// ``` +/// use hyper::header::{Headers, CacheControl, CacheDirective}; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// CacheControl(vec![CacheDirective::MaxAge(86400u32)]) +/// ); +/// ``` +/// ``` +/// use hyper::header::{Headers, CacheControl, CacheDirective}; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// CacheControl(vec![ +/// CacheDirective::NoCache, +/// CacheDirective::Private, +/// CacheDirective::MaxAge(360u32), +/// CacheDirective::Extension("foo".to_owned(), +/// Some("bar".to_owned())), +/// ]) +/// ); +/// ``` #[derive(PartialEq, Clone, Debug)] pub struct CacheControl(pub Vec<CacheDirective>); diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -17,6 +17,24 @@ use cookie::CookieJar; /// # Example values /// * `SID=31d4d96e407aad42` /// * `SID=31d4d96e407aad42; lang=en-US` +/// +/// # Example +/// ``` +/// # extern crate hyper; +/// # extern crate cookie; +/// # fn main() { +/// use hyper::header::{Headers, Cookie}; +/// use cookie::Cookie as CookiePair; +/// +/// let mut headers = Headers::new(); +/// +/// headers.set( +/// Cookie(vec![ +/// CookiePair::new("foo".to_owned(), "bar".to_owned()) +/// ]) +/// ); +/// # } +/// ``` #[derive(Clone, PartialEq, Debug)] pub struct Cookie(pub Vec<CookiePair>); diff --git a/src/header/common/expect.rs b/src/header/common/expect.rs --- a/src/header/common/expect.rs +++ b/src/header/common/expect.rs @@ -13,6 +13,13 @@ use header::{Header, HeaderFormat}; /// > defined by this specification is 100-continue. /// > /// > Expect = "100-continue" +/// +/// # Example +/// ``` +/// use hyper::header::{Headers, Expect}; +/// let mut headers = Headers::new(); +/// headers.set(Expect::Continue); +/// ``` #[derive(Copy, Clone, PartialEq, Debug)] pub enum Expect { /// The value `100-continue`. diff --git a/src/header/common/from.rs b/src/header/common/from.rs --- a/src/header/common/from.rs +++ b/src/header/common/from.rs @@ -9,6 +9,14 @@ header! { #[doc="From = mailbox"] #[doc="mailbox = <mailbox, see [RFC5322], Section 3.4>"] #[doc="```"] + #[doc=""] + #[doc="# Example"] + #[doc="```"] + #[doc="use hyper::header::{Headers, From};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(From(\"webmaster@example.org\".to_owned()));"] + #[doc="```"] // FIXME: Maybe use mailbox? (From, "From") => [String] diff --git a/src/header/common/host.rs b/src/header/common/host.rs --- a/src/header/common/host.rs +++ b/src/header/common/host.rs @@ -9,6 +9,30 @@ use header::parsing::from_one_raw_str; /// /// Currently is just a String, but it should probably become a better type, /// like url::Host or something. +/// +/// # Examples +/// ``` +/// use hyper::header::{Headers, Host}; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// Host{ +/// hostname: "hyper.rs".to_owned(), +/// port: None, +/// } +/// ); +/// ``` +/// ``` +/// use hyper::header::{Headers, Host}; +/// +/// let mut headers = Headers::new(); +/// headers.set( +/// Host{ +/// hostname: "hyper.rs".to_owned(), +/// port: Some(8080), +/// } +/// ); +/// ``` #[derive(Clone, PartialEq, Debug)] pub struct Host { /// The hostname, such a example.domain. diff --git a/src/header/common/if_range.rs b/src/header/common/if_range.rs --- a/src/header/common/if_range.rs +++ b/src/header/common/if_range.rs @@ -24,6 +24,27 @@ use header::{self, Header, HeaderFormat, EntityTag, HttpDate}; /// # Example values /// * `Sat, 29 Oct 1994 19:43:31 GMT` /// * `\"xyzzy\"` +/// +/// # Examples +/// ``` +/// use hyper::header::{Headers, IfRange, EntityTag}; +/// +/// let mut headers = Headers::new(); +/// headers.set(IfRange::EntityTag(EntityTag::new(false, "xyzzy".to_owned()))); +/// ``` +/// ``` +/// # extern crate hyper; +/// # extern crate time; +/// # fn main() { +/// // extern crate time; +/// +/// use hyper::header::{Headers, IfRange, HttpDate}; +/// use time::{self, Duration}; +/// +/// let mut headers = Headers::new(); +/// headers.set(IfRange::Date(HttpDate(time::now() - Duration::days(1)))); +/// # } +/// ``` #[derive(Clone, Debug, PartialEq)] pub enum IfRange { /// The entity-tag the client has of the resource diff --git a/src/header/common/location.rs b/src/header/common/location.rs --- a/src/header/common/location.rs +++ b/src/header/common/location.rs @@ -15,6 +15,20 @@ header! { #[doc="# Example values"] #[doc="* `/People.html#tim`"] #[doc="* `http://www.example.net/index.html`"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, Location};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(Location(\"/People.html#tim\".to_owned()));"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, Location};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(Location(\"http://www.example.com/index.html\".to_owned()));"] + #[doc="```"] // TODO: Use URL (Location, "Location") => [String] diff --git a/src/header/common/pragma.rs b/src/header/common/pragma.rs --- a/src/header/common/pragma.rs +++ b/src/header/common/pragma.rs @@ -16,6 +16,20 @@ use header::{Header, HeaderFormat, parsing}; /// > specification deprecates such extensions to improve interoperability. /// /// Spec: https://tools.ietf.org/html/rfc7234#section-5.4 +/// +/// # Examples +/// ``` +/// use hyper::header::{Headers, Pragma}; +/// +/// let mut headers = Headers::new(); +/// headers.set(Pragma::NoCache); +/// ``` +/// ``` +/// use hyper::header::{Headers, Pragma}; +/// +/// let mut headers = Headers::new(); +/// headers.set(Pragma::Ext("foobar".to_owned())); +/// ``` #[derive(Clone, PartialEq, Debug)] pub enum Pragma { /// Corresponds to the `no-cache` value. diff --git a/src/header/common/referer.rs b/src/header/common/referer.rs --- a/src/header/common/referer.rs +++ b/src/header/common/referer.rs @@ -15,6 +15,20 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `http://www.example.org/hypertext/Overview.html`"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, Referer};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(Referer(\"/People.html#tim\".to_owned()));"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, Referer};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(Referer(\"http://www.example.com/index.html\".to_owned()));"] + #[doc="```"] // TODO: Use URL (Referer, "Referer") => [String] diff --git a/src/header/common/server.rs b/src/header/common/server.rs --- a/src/header/common/server.rs +++ b/src/header/common/server.rs @@ -16,6 +16,14 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `CERN/3.0 libwww/2.17`"] + #[doc=""] + #[doc="# Example"] + #[doc="```"] + #[doc="use hyper::header::{Headers, Server};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(Server(\"hyper/0.5.2\".to_owned()));"] + #[doc="```"] // TODO: Maybe parse as defined in the spec? (Server, "Server") => [String] diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs --- a/src/header/common/set_cookie.rs +++ b/src/header/common/set_cookie.rs @@ -54,6 +54,31 @@ use cookie::CookieJar; /// * `lang=en-US; Expires=Wed, 09 Jun 2021 10:18:14 GMT` /// * `lang=; Expires=Sun, 06 Nov 1994 08:49:37 GMT` /// * `lang=en-US; Path=/; Domain=example.com` +/// +/// # Example +/// ``` +/// # extern crate hyper; +/// # extern crate cookie; +/// # fn main() { +/// // extern crate cookie; +/// +/// use hyper::header::{Headers, SetCookie}; +/// use cookie::Cookie as CookiePair; +/// +/// let mut headers = Headers::new(); +/// let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned()); +/// +/// cookie.path = Some("/path".to_owned()); +/// cookie.domain = Some("example.com".to_owned()); +/// +/// headers.set( +/// SetCookie(vec![ +/// cookie, +/// CookiePair::new("baz".to_owned(), "quux".to_owned()), +/// ]) +/// ); +/// # } +/// ``` #[derive(Clone, PartialEq, Debug)] pub struct SetCookie(pub Vec<Cookie>); diff --git a/src/header/common/transfer_encoding.rs b/src/header/common/transfer_encoding.rs --- a/src/header/common/transfer_encoding.rs +++ b/src/header/common/transfer_encoding.rs @@ -16,6 +16,19 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `gzip, chunked`"] + #[doc=""] + #[doc="# Example"] + #[doc="```"] + #[doc="use hyper::header::{Headers, TransferEncoding, Encoding};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" TransferEncoding(vec!["] + #[doc=" Encoding::Gzip,"] + #[doc=" Encoding::Chunked,"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] (TransferEncoding, "Transfer-Encoding") => (Encoding)+ transfer_encoding {
diff --git a/src/header/common/accept_charset.rs b/src/header/common/accept_charset.rs --- a/src/header/common/accept_charset.rs +++ b/src/header/common/accept_charset.rs @@ -18,6 +18,35 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `iso-8859-5, unicode-1-1;q=0.8`"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, AcceptCharset, Charset, qitem};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" AcceptCharset(vec![qitem(Charset::Us_Ascii)])"] + #[doc=");"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, AcceptCharset, Charset, Quality, QualityItem};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" AcceptCharset(vec!["] + #[doc=" QualityItem::new(Charset::Us_Ascii, Quality(900)),"] + #[doc=" QualityItem::new(Charset::Iso_8859_10, Quality(200)),"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, AcceptCharset, Charset, qitem};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" AcceptCharset(vec![qitem(Charset::Ext(\"utf-8\".to_owned()))])"] + #[doc=");"] + #[doc="```"] (AcceptCharset, "Accept-Charset") => (QualityItem<Charset>)+ test_accept_charset { diff --git a/src/header/common/accept_encoding.rs b/src/header/common/accept_encoding.rs --- a/src/header/common/accept_encoding.rs +++ b/src/header/common/accept_encoding.rs @@ -22,6 +22,40 @@ header! { #[doc="* `*`"] #[doc="* `compress;q=0.5, gzip;q=1`"] #[doc="* `gzip;q=1.0, identity; q=0.5, *;q=0`"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, AcceptEncoding, Encoding, qitem};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" AcceptEncoding(vec![qitem(Encoding::Chunked)])"] + #[doc=");"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, AcceptEncoding, Encoding, qitem};"] + #[doc=" "] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" AcceptEncoding(vec!["] + #[doc=" qitem(Encoding::Chunked),"] + #[doc=" qitem(Encoding::Gzip),"] + #[doc=" qitem(Encoding::Deflate),"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, AcceptEncoding, Encoding, QualityItem, Quality, qitem};"] + #[doc=" "] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" AcceptEncoding(vec!["] + #[doc=" qitem(Encoding::Chunked),"] + #[doc=" QualityItem::new(Encoding::Gzip, Quality(600)),"] + #[doc=" QualityItem::new(Encoding::EncodingExt(\"*\".to_owned()), Quality(0)),"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] (AcceptEncoding, "Accept-Encoding") => (QualityItem<Encoding>)* test_accept_encoding { diff --git a/src/header/common/accept_language.rs b/src/header/common/accept_language.rs --- a/src/header/common/accept_language.rs +++ b/src/header/common/accept_language.rs @@ -17,6 +17,52 @@ header! { #[doc="# Example values"] #[doc="* `da, en-gb;q=0.8, en;q=0.7`"] #[doc="* `en-us;q=1.0, en;q=0.5, fr`"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, AcceptLanguage, Language, qitem};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" AcceptLanguage(vec!["] + #[doc=" qitem("] + #[doc=" Language {"] + #[doc=" primary: \"en\".to_owned(),"] + #[doc=" sub: Some(\"us\".to_owned()),"] + #[doc=" }"] + #[doc=" ),"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, AcceptLanguage, Language, QualityItem, Quality, qitem};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" AcceptLanguage(vec!["] + #[doc=" qitem("] + #[doc=" Language {"] + #[doc=" primary: \"da\".to_owned(),"] + #[doc=" sub: None,"] + #[doc=" }"] + #[doc=" ),"] + #[doc=" QualityItem::new("] + #[doc=" Language {"] + #[doc=" primary: \"en\".to_owned(),"] + #[doc=" sub: Some(\"gb\".to_owned()),"] + #[doc=" },"] + #[doc=" Quality(800),"] + #[doc=" ),"] + #[doc=" QualityItem::new("] + #[doc=" Language {"] + #[doc=" primary: \"en\".to_owned(),"] + #[doc=" sub: None,"] + #[doc=" },"] + #[doc=" Quality(700),"] + #[doc=" ),"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] (AcceptLanguage, "Accept-Language") => (QualityItem<Language>)+ test_accept_language { diff --git a/src/header/common/accept_ranges.rs b/src/header/common/accept_ranges.rs --- a/src/header/common/accept_ranges.rs +++ b/src/header/common/accept_ranges.rs @@ -18,6 +18,33 @@ header! { #[doc="* `none`"] #[doc="* `unknown-unit`"] #[doc="```"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(AcceptRanges(vec![RangeUnit::Bytes]));"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(AcceptRanges(vec![RangeUnit::None]));"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" AcceptRanges(vec!["] + #[doc=" RangeUnit::Unregistered(\"nibbles\".to_owned()),"] + #[doc=" RangeUnit::Bytes,"] + #[doc=" RangeUnit::Unregistered(\"doublets\".to_owned()),"] + #[doc=" RangeUnit::Unregistered(\"quadlets\".to_owned()),"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] (AcceptRanges, "Accept-Ranges") => (RangeUnit)+ test_acccept_ranges { diff --git a/src/header/common/access_control_allow_headers.rs b/src/header/common/access_control_allow_headers.rs --- a/src/header/common/access_control_allow_headers.rs +++ b/src/header/common/access_control_allow_headers.rs @@ -15,6 +15,41 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `accept-language, date`"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="# extern crate hyper;"] + #[doc="# extern crate unicase;"] + #[doc="# fn main() {"] + #[doc="// extern crate unicase;"] + #[doc=""] + #[doc="use hyper::header::{Headers, AccessControlAllowHeaders};"] + #[doc="use unicase::UniCase;"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" AccessControlAllowHeaders(vec![UniCase(\"date\".to_owned())])"] + #[doc=");"] + #[doc="# }"] + #[doc="```"] + #[doc="```"] + #[doc="# extern crate hyper;"] + #[doc="# extern crate unicase;"] + #[doc="# fn main() {"] + #[doc="// extern crate unicase;"] + #[doc=""] + #[doc="use hyper::header::{Headers, AccessControlAllowHeaders};"] + #[doc="use unicase::UniCase;"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" AccessControlAllowHeaders(vec!["] + #[doc=" UniCase(\"accept-language\".to_owned()),"] + #[doc=" UniCase(\"date\".to_owned()),"] + #[doc=" ])"] + #[doc=");"] + #[doc="# }"] + #[doc="```"] (AccessControlAllowHeaders, "Access-Control-Allow-Headers") => (UniCase<String>)* test_access_control_allow_headers { diff --git a/src/header/common/access_control_allow_methods.rs b/src/header/common/access_control_allow_methods.rs --- a/src/header/common/access_control_allow_methods.rs +++ b/src/header/common/access_control_allow_methods.rs @@ -15,6 +15,31 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `PUT, DELETE, XMODIFY`"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, AccessControlAllowMethods};"] + #[doc="use hyper::method::Method;"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" AccessControlAllowMethods(vec![Method::Get])"] + #[doc=");"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, AccessControlAllowMethods};"] + #[doc="use hyper::method::Method;"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" AccessControlAllowMethods(vec!["] + #[doc=" Method::Get,"] + #[doc=" Method::Post,"] + #[doc=" Method::Patch,"] + #[doc=" Method::Extension(\"COPY\".to_owned()),"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] (AccessControlAllowMethods, "Access-Control-Allow-Methods") => (Method)* test_access_control_allow_methods { diff --git a/src/header/common/access_control_max_age.rs b/src/header/common/access_control_max_age.rs --- a/src/header/common/access_control_max_age.rs +++ b/src/header/common/access_control_max_age.rs @@ -12,6 +12,14 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `531`"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, AccessControlMaxAge};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(AccessControlMaxAge(1728000u32));"] + #[doc="```"] (AccessControlMaxAge, "Access-Control-Max-Age") => [u32] test_access_control_max_age { diff --git a/src/header/common/access_control_request_headers.rs b/src/header/common/access_control_request_headers.rs --- a/src/header/common/access_control_request_headers.rs +++ b/src/header/common/access_control_request_headers.rs @@ -15,6 +15,41 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `accept-language, date`"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="# extern crate hyper;"] + #[doc="# extern crate unicase;"] + #[doc="# fn main() {"] + #[doc="// extern crate unicase;"] + #[doc=""] + #[doc="use hyper::header::{Headers, AccessControlRequestHeaders};"] + #[doc="use unicase::UniCase;"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" AccessControlRequestHeaders(vec![UniCase(\"date\".to_owned())])"] + #[doc=");"] + #[doc="# }"] + #[doc="```"] + #[doc="```"] + #[doc="# extern crate hyper;"] + #[doc="# extern crate unicase;"] + #[doc="# fn main() {"] + #[doc="// extern crate unicase;"] + #[doc=""] + #[doc="use hyper::header::{Headers, AccessControlRequestHeaders};"] + #[doc="use unicase::UniCase;"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" AccessControlRequestHeaders(vec!["] + #[doc=" UniCase(\"accept-language\".to_owned()),"] + #[doc=" UniCase(\"date\".to_owned()),"] + #[doc=" ])"] + #[doc=");"] + #[doc="# }"] + #[doc="```"] (AccessControlRequestHeaders, "Access-Control-Request-Headers") => (UniCase<String>)* test_access_control_request_headers { diff --git a/src/header/common/access_control_request_method.rs b/src/header/common/access_control_request_method.rs --- a/src/header/common/access_control_request_method.rs +++ b/src/header/common/access_control_request_method.rs @@ -13,6 +13,15 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `GET`"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, AccessControlRequestMethod};"] + #[doc="use hyper::method::Method;"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(AccessControlRequestMethod(Method::Get));"] + #[doc="```"] (AccessControlRequestMethod, "Access-Control-Request-Method") => [Method] test_access_control_request_method { diff --git a/src/header/common/allow.rs b/src/header/common/allow.rs --- a/src/header/common/allow.rs +++ b/src/header/common/allow.rs @@ -17,6 +17,31 @@ header! { #[doc="* `GET, HEAD, PUT`"] #[doc="* `OPTIONS, GET, PUT, POST, DELETE, HEAD, TRACE, CONNECT, PATCH, fOObAr`"] #[doc="* ``"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, Allow};"] + #[doc="use hyper::method::Method;"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" Allow(vec![Method::Get])"] + #[doc=");"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, Allow};"] + #[doc="use hyper::method::Method;"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" Allow(vec!["] + #[doc=" Method::Get,"] + #[doc=" Method::Post,"] + #[doc=" Method::Patch,"] + #[doc=" Method::Extension(\"COPY\".to_owned()),"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] (Allow, "Allow") => (Method)* test_allow { diff --git a/src/header/common/connection.rs b/src/header/common/connection.rs --- a/src/header/common/connection.rs +++ b/src/header/common/connection.rs @@ -62,6 +62,32 @@ header! { #[doc="* `close`"] #[doc="* `keep-alive`"] #[doc="* `upgrade`"] + #[doc="```"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, Connection};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(Connection::keep_alive());"] + #[doc="```"] + #[doc="```"] + #[doc="# extern crate hyper;"] + #[doc="# extern crate unicase;"] + #[doc="# fn main() {"] + #[doc="// extern crate unicase;"] + #[doc=""] + #[doc="use hyper::header::{Headers, Connection, ConnectionOption};"] + #[doc="use unicase::UniCase;"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" Connection(vec!["] + #[doc=" ConnectionOption::ConnectionHeader(UniCase(\"upgrade\".to_owned())),"] + #[doc=" ])"] + #[doc=");"] + #[doc="# }"] + #[doc="```"] (Connection, "Connection") => (ConnectionOption)+ test_connection { diff --git a/src/header/common/content_encoding.rs b/src/header/common/content_encoding.rs --- a/src/header/common/content_encoding.rs +++ b/src/header/common/content_encoding.rs @@ -19,6 +19,25 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `gzip`"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, ContentEncoding, Encoding};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(ContentEncoding(vec![Encoding::Chunked]));"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, ContentEncoding, Encoding};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" ContentEncoding(vec!["] + #[doc=" Encoding::Gzip,"] + #[doc=" Encoding::Chunked,"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] (ContentEncoding, "Content-Encoding") => (Encoding)+ test_content_encoding { diff --git a/src/header/common/content_language.rs b/src/header/common/content_language.rs --- a/src/header/common/content_language.rs +++ b/src/header/common/content_language.rs @@ -17,6 +17,44 @@ header! { #[doc="# Example values"] #[doc="* `da`"] #[doc="* `mi, en`"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, ContentLanguage, Language, qitem};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" ContentLanguage(vec!["] + #[doc=" qitem("] + #[doc=" Language { "] + #[doc=" primary: \"en\".to_owned(),"] + #[doc=" sub: None,"] + #[doc=" }"] + #[doc=" ),"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, ContentLanguage, Language, qitem};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" ContentLanguage(vec!["] + #[doc=" qitem("] + #[doc=" Language {"] + #[doc=" primary: \"da\".to_owned(),"] + #[doc=" sub: None,"] + #[doc=" }"] + #[doc=" ),"] + #[doc=" qitem("] + #[doc=" Language {"] + #[doc=" primary: \"en\".to_owned(),"] + #[doc=" sub: Some(\"gb\".to_owned()),"] + #[doc=" }"] + #[doc=" ),"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] (ContentLanguage, "Content-Language") => (QualityItem<Language>)+ test_content_language { diff --git a/src/header/common/content_length.rs b/src/header/common/content_length.rs --- a/src/header/common/content_length.rs +++ b/src/header/common/content_length.rs @@ -18,6 +18,14 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `3495`"] + #[doc=""] + #[doc="# Example"] + #[doc="```"] + #[doc="use hyper::header::{Headers, ContentLength};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(ContentLength(1024u64));"] + #[doc="```"] (ContentLength, "Content-Length") => [u64] test_content_length { diff --git a/src/header/common/content_type.rs b/src/header/common/content_type.rs --- a/src/header/common/content_type.rs +++ b/src/header/common/content_type.rs @@ -19,6 +19,29 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `text/html; charset=ISO-8859-4`"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, ContentType};"] + #[doc="use hyper::mime::{Mime, TopLevel, SubLevel};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc=""] + #[doc="headers.set("] + #[doc=" ContentType(Mime(TopLevel::Text, SubLevel::Html, vec![]))"] + #[doc=");"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, ContentType};"] + #[doc="use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" ContentType(Mime(TopLevel::Application, SubLevel::Json,"] + #[doc=" vec![(Attr::Charset, Value::Utf8)]))"] + #[doc=""] + #[doc=");"] + #[doc="```"] (ContentType, "Content-Type") => [Mime] test_content_type { diff --git a/src/header/common/date.rs b/src/header/common/date.rs --- a/src/header/common/date.rs +++ b/src/header/common/date.rs @@ -13,6 +13,21 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `Tue, 15 Nov 1994 08:12:31 GMT`"] + #[doc=""] + #[doc="# Example"] + #[doc="```"] + #[doc="# extern crate time;"] + #[doc="# extern crate hyper;"] + #[doc="# fn main() {"] + #[doc="// extern crate time;"] + #[doc=""] + #[doc="use hyper::header::{Headers, Date, HttpDate};"] + #[doc="use time;"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(Date(HttpDate(time::now())));"] + #[doc="# }"] + #[doc="```"] (Date, "Date") => [HttpDate] test_date { diff --git a/src/header/common/etag.rs b/src/header/common/etag.rs --- a/src/header/common/etag.rs +++ b/src/header/common/etag.rs @@ -22,6 +22,20 @@ header! { #[doc="* `\"xyzzy\"`"] #[doc="* `W/\"xyzzy\"`"] #[doc="* `\"\"`"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, ETag, EntityTag};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(ETag(EntityTag::new(false, \"xyzzy\".to_owned())));"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, ETag, EntityTag};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(ETag(EntityTag::new(true, \"xyzzy\".to_owned())));"] + #[doc="```"] (ETag, "ETag") => [EntityTag] test_etag { diff --git a/src/header/common/expires.rs b/src/header/common/expires.rs --- a/src/header/common/expires.rs +++ b/src/header/common/expires.rs @@ -17,6 +17,21 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `Thu, 01 Dec 1994 16:00:00 GMT`"] + #[doc=""] + #[doc="# Example"] + #[doc="```"] + #[doc="# extern crate hyper;"] + #[doc="# extern crate time;"] + #[doc="# fn main() {"] + #[doc="// extern crate time;"] + #[doc=""] + #[doc="use hyper::header::{Headers, Expires, HttpDate};"] + #[doc="use time::{self, Duration};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(Expires(HttpDate(time::now() + Duration::days(1))));"] + #[doc="# }"] + #[doc="```"] (Expires, "Expires") => [HttpDate] test_expires { diff --git a/src/header/common/if_match.rs b/src/header/common/if_match.rs --- a/src/header/common/if_match.rs +++ b/src/header/common/if_match.rs @@ -24,6 +24,26 @@ header! { #[doc="# Example values"] #[doc="* `\"xyzzy\"`"] #[doc="* \"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, IfMatch};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(IfMatch::Any);"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, IfMatch, EntityTag};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" IfMatch::Items(vec!["] + #[doc=" EntityTag::new(false, \"xyzzy\".to_owned()),"] + #[doc=" EntityTag::new(false, \"foobar\".to_owned()),"] + #[doc=" EntityTag::new(false, \"bazquux\".to_owned()),"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] (IfMatch, "If-Match") => {Any / (EntityTag)+} test_if_match { diff --git a/src/header/common/if_modified_since.rs b/src/header/common/if_modified_since.rs --- a/src/header/common/if_modified_since.rs +++ b/src/header/common/if_modified_since.rs @@ -17,6 +17,21 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `Sat, 29 Oct 1994 19:43:31 GMT`"] + #[doc=""] + #[doc="# Example"] + #[doc="```"] + #[doc="# extern crate hyper;"] + #[doc="# extern crate time;"] + #[doc="# fn main() {"] + #[doc="// extern crate time;"] + #[doc=""] + #[doc="use hyper::header::{Headers, IfModifiedSince, HttpDate};"] + #[doc="use time::{self, Duration};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(IfModifiedSince(HttpDate(time::now() - Duration::days(1))));"] + #[doc="# }"] + #[doc="```"] (IfModifiedSince, "If-Modified-Since") => [HttpDate] test_if_modified_since { diff --git a/src/header/common/if_none_match.rs b/src/header/common/if_none_match.rs --- a/src/header/common/if_none_match.rs +++ b/src/header/common/if_none_match.rs @@ -26,6 +26,26 @@ header! { #[doc="* `\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\"`"] #[doc="* `W/\"xyzzy\", W/\"r2d2xxxx\", W/\"c3piozzzz\"`"] #[doc="* `*`"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, IfNoneMatch};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(IfNoneMatch::Any);"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, IfNoneMatch, EntityTag};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" IfNoneMatch::Items(vec!["] + #[doc=" EntityTag::new(false, \"xyzzy\".to_owned()),"] + #[doc=" EntityTag::new(false, \"foobar\".to_owned()),"] + #[doc=" EntityTag::new(false, \"bazquux\".to_owned()),"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] (IfNoneMatch, "If-None-Match") => {Any / (EntityTag)+} test_if_none_match { diff --git a/src/header/common/if_unmodified_since.rs b/src/header/common/if_unmodified_since.rs --- a/src/header/common/if_unmodified_since.rs +++ b/src/header/common/if_unmodified_since.rs @@ -17,6 +17,21 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `Sat, 29 Oct 1994 19:43:31 GMT`"] + #[doc=""] + #[doc="# Example"] + #[doc="```"] + #[doc="# extern crate hyper;"] + #[doc="# extern crate time;"] + #[doc="# fn main() {"] + #[doc="// extern crate time;"] + #[doc=""] + #[doc="use hyper::header::{Headers, IfUnmodifiedSince, HttpDate};"] + #[doc="use time::{self, Duration};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(IfUnmodifiedSince(HttpDate(time::now() - Duration::days(1))));"] + #[doc="# }"] + #[doc="```"] (IfUnmodifiedSince, "If-Unmodified-Since") => [HttpDate] test_if_unmodified_since { diff --git a/src/header/common/last_modified.rs b/src/header/common/last_modified.rs --- a/src/header/common/last_modified.rs +++ b/src/header/common/last_modified.rs @@ -16,6 +16,21 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `Sat, 29 Oct 1994 19:43:31 GMT`"] + #[doc=""] + #[doc="# Example"] + #[doc="```"] + #[doc="# extern crate hyper;"] + #[doc="# extern crate time;"] + #[doc="# fn main() {"] + #[doc="// extern crate time;"] + #[doc=""] + #[doc="use hyper::header::{Headers, LastModified, HttpDate};"] + #[doc="use time::{self, Duration};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(LastModified(HttpDate(time::now() - Duration::days(1))));"] + #[doc="# }"] + #[doc="```"] (LastModified, "Last-Modified") => [HttpDate] test_last_modified { diff --git a/src/header/common/upgrade.rs b/src/header/common/upgrade.rs --- a/src/header/common/upgrade.rs +++ b/src/header/common/upgrade.rs @@ -26,6 +26,27 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11`"] + #[doc=""] + #[doc="# Examples"] + #[doc="```"] + #[doc="use hyper::header::{Headers, Upgrade, Protocol, ProtocolName};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(Upgrade(vec![Protocol::new(ProtocolName::WebSocket, None)]));"] + #[doc="```"] + #[doc="```"] + #[doc="use hyper::header::{Headers, Upgrade, Protocol, ProtocolName};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" Upgrade(vec!["] + #[doc=" Protocol::new(ProtocolName::Http, Some(\"2.0\".to_owned())),"] + #[doc=" Protocol::new(ProtocolName::Unregistered(\"SHTTP\".to_owned()), Some(\"1.3\".to_owned())),"] + #[doc=" Protocol::new(ProtocolName::Unregistered(\"IRC\".to_owned()), Some(\"6.9\".to_owned())),"] + #[doc=" Protocol::new(ProtocolName::Unregistered(\"RTA\".to_owned()), Some(\"x11\".to_owned())),"] + #[doc=" ])"] + #[doc=");"] + #[doc="```"] (Upgrade, "Upgrade") => (Protocol)+ test_upgrade { diff --git a/src/header/common/user_agent.rs b/src/header/common/user_agent.rs --- a/src/header/common/user_agent.rs +++ b/src/header/common/user_agent.rs @@ -23,6 +23,14 @@ header! { #[doc=""] #[doc="# Notes"] #[doc="* The parser does not split the value"] + #[doc=""] + #[doc="# Example"] + #[doc="```"] + #[doc="use hyper::header::{Headers, UserAgent};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(UserAgent(\"hyper/0.5.2\".to_owned()));"] + #[doc="```"] (UserAgent, "User-Agent") => [String] test_user_agent { diff --git a/src/header/common/vary.rs b/src/header/common/vary.rs --- a/src/header/common/vary.rs +++ b/src/header/common/vary.rs @@ -17,6 +17,34 @@ header! { #[doc=""] #[doc="# Example values"] #[doc="* `accept-encoding, accept-language`"] + #[doc=""] + #[doc="# Example"] + #[doc="```"] + #[doc="use hyper::header::{Headers, Vary};"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set(Vary::Any);"] + #[doc="```"] + #[doc=""] + #[doc="# Example"] + #[doc="```"] + #[doc="# extern crate hyper;"] + #[doc="# extern crate unicase;"] + #[doc="# fn main() {"] + #[doc="// extern crate unicase;"] + #[doc=""] + #[doc="use hyper::header::{Headers, Vary};"] + #[doc="use unicase::UniCase;"] + #[doc=""] + #[doc="let mut headers = Headers::new();"] + #[doc="headers.set("] + #[doc=" Vary::Items(vec!["] + #[doc=" UniCase(\"accept-encoding\".to_owned()),"] + #[doc=" UniCase(\"accept-language\".to_owned()),"] + #[doc=" ])"] + #[doc=");"] + #[doc="# }"] + #[doc="```"] (Vary, "Vary") => {Any / (UniCase<String>)+} test_vary {
Add example usage for each Header The header types docs could show an example usage on each of their respective pages.
This is solved by #503 Ah, when I meant example usage, I meant showing in a rust code fench how to create a header to to send in a Request/Response.
2015-06-15T03:44:31Z
0.5
c37d85728f67997cef4887736c5228322c8967ec
hyperium/hyper
518
hyperium__hyper-518
[ "495" ]
38f40c7f6a17bd33951bbab1adddf542cbb96de6
diff --git a/benches/client.rs b/benches/client.rs --- a/benches/client.rs +++ b/benches/client.rs @@ -8,7 +8,7 @@ use std::fmt; use std::io::{self, Read, Write, Cursor}; use std::net::SocketAddr; -use hyper::net; +use hyper::net::{self, ContextVerifier}; static README: &'static [u8] = include_bytes!("../README.md"); diff --git a/benches/client.rs b/benches/client.rs --- a/benches/client.rs +++ b/benches/client.rs @@ -83,6 +83,9 @@ impl net::NetworkConnector for MockConnector { Ok(MockStream::new()) } + fn set_ssl_verifier(&mut self, _verifier: ContextVerifier) { + // pass + } } #[bench] diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -41,7 +41,7 @@ use url::ParseError as UrlError; use header::{Headers, Header, HeaderFormat}; use header::{ContentLength, Location}; use method::Method; -use net::{NetworkConnector, NetworkStream, HttpConnector, ContextVerifier}; +use net::{NetworkConnector, NetworkStream, ContextVerifier}; use status::StatusClass::Redirection; use {Url}; use Error; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -85,10 +85,7 @@ impl Client { /// Set the SSL verifier callback for use with OpenSSL. pub fn set_ssl_verifier(&mut self, verifier: ContextVerifier) { - self.connector = with_connector(Pool::with_connector( - Default::default(), - HttpConnector(Some(verifier)) - )); + self.connector.set_ssl_verifier(verifier); } /// Set the RedirectPolicy. diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -147,6 +144,10 @@ impl<C: NetworkConnector<Stream=S> + Send, S: NetworkStream + Send> NetworkConne -> ::Result<Box<NetworkStream + Send>> { Ok(try!(self.0.connect(host, port, scheme)).into()) } + #[inline] + fn set_ssl_verifier(&mut self, verifier: ContextVerifier) { + self.0.set_ssl_verifier(verifier); + } } struct Connector(Box<NetworkConnector<Stream=Box<NetworkStream + Send>> + Send>); diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -158,6 +159,10 @@ impl NetworkConnector for Connector { -> ::Result<Box<NetworkStream + Send>> { Ok(try!(self.0.connect(host, port, scheme)).into()) } + #[inline] + fn set_ssl_verifier(&mut self, verifier: ContextVerifier) { + self.0.set_ssl_verifier(verifier); + } } /// Options for an individual Request. diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -5,7 +5,7 @@ use std::io::{self, Read, Write}; use std::net::{SocketAddr, Shutdown}; use std::sync::{Arc, Mutex}; -use net::{NetworkConnector, NetworkStream, HttpConnector}; +use net::{NetworkConnector, NetworkStream, HttpConnector, ContextVerifier}; /// The `NetworkConnector` that behaves as a connection pool used by hyper's `Client`. pub struct Pool<C: NetworkConnector> { diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -119,6 +119,10 @@ impl<C: NetworkConnector<Stream=S>, S: NetworkStream + Send> NetworkConnector fo pool: self.inner.clone() }) } + #[inline] + fn set_ssl_verifier(&mut self, verifier: ContextVerifier) { + self.connector.set_ssl_verifier(verifier); + } } /// A Stream that will try to be returned to the Pool when dropped. diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -1,8 +1,9 @@ use std::fmt; use std::io::{self, Read, Write, Cursor}; use std::net::SocketAddr; +use std::sync::mpsc::Sender; -use net::{NetworkStream, NetworkConnector}; +use net::{NetworkStream, NetworkConnector, ContextVerifier}; pub struct MockStream { pub read: Cursor<Vec<u8>>, diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -76,6 +77,39 @@ impl NetworkConnector for MockConnector { fn connect(&mut self, _host: &str, _port: u16, _scheme: &str) -> ::Result<MockStream> { Ok(MockStream::new()) } + + fn set_ssl_verifier(&mut self, _verifier: ContextVerifier) { + // pass + } +} + +/// A mock implementation of the `NetworkConnector` trait that keeps track of all calls to its +/// methods by sending corresponding messages onto a channel. +/// +/// Otherwise, it behaves the same as `MockConnector`. +pub struct ChannelMockConnector { + calls: Sender<String>, +} + +impl ChannelMockConnector { + pub fn new(calls: Sender<String>) -> ChannelMockConnector { + ChannelMockConnector { calls: calls } + } +} + +impl NetworkConnector for ChannelMockConnector { + type Stream = MockStream; + #[inline] + fn connect(&mut self, _host: &str, _port: u16, _scheme: &str) + -> ::Result<MockStream> { + self.calls.send("connect".into()).unwrap(); + Ok(MockStream::new()) + } + + #[inline] + fn set_ssl_verifier(&mut self, _verifier: ContextVerifier) { + self.calls.send("set_ssl_verifier".into()).unwrap(); + } } /// new connectors must be created if you wish to intercept requests. diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -107,6 +141,9 @@ macro_rules! mock_connector ( } } + fn set_ssl_verifier(&mut self, _verifier: ::net::ContextVerifier) { + // pass + } } ) diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -70,6 +70,9 @@ pub trait NetworkConnector { type Stream: Into<Box<NetworkStream + Send>>; /// Connect to a remote address. fn connect(&mut self, host: &str, port: u16, scheme: &str) -> ::Result<Self::Stream>; + /// Sets the given `ContextVerifier` to be used when verifying the SSL context + /// on the establishment of a new connection. + fn set_ssl_verifier(&mut self, verifier: ContextVerifier); } impl<T: NetworkStream + Send> From<T> for Box<NetworkStream + Send> {
diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -401,6 +406,8 @@ mod tests { use header::Server; use super::{Client, RedirectPolicy}; use url::Url; + use mock::ChannelMockConnector; + use std::sync::mpsc::{self, TryRecvError}; mock_connector!(MockRedirectPolicy { "http://127.0.0.1" => "HTTP/1.1 301 Redirect\r\n\ diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -447,4 +454,30 @@ mod tests { assert_eq!(res.headers.get(), Some(&Server("mock2".to_string()))); } + /// Tests that the `Client::set_ssl_verifier` method does not drop the + /// old connector, but rather delegates the change to the connector itself. + #[test] + fn test_client_set_ssl_verifer() { + let (tx, rx) = mpsc::channel(); + let mut client = Client::with_connector(ChannelMockConnector::new(tx)); + + client.set_ssl_verifier(Box::new(|_| {})); + + // Make sure that the client called the `set_ssl_verifier` method + match rx.try_recv() { + Ok(meth) => { + assert_eq!(meth, "set_ssl_verifier"); + }, + _ => panic!("Expected a call to `set_ssl_verifier`"), + }; + // Now make sure that no other method was called, as well as that + // the connector is still alive (i.e. wasn't dropped by the client). + match rx.try_recv() { + Err(TryRecvError::Empty) => {}, + Err(TryRecvError::Disconnected) => { + panic!("Expected the connector to still be alive."); + }, + Ok(_) => panic!("Did not expect any more method calls."), + }; + } } diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -184,8 +188,9 @@ impl<S> Drop for PooledStream<S> { #[cfg(test)] mod tests { use std::net::Shutdown; - use mock::MockConnector; + use mock::{MockConnector, ChannelMockConnector}; use net::{NetworkConnector, NetworkStream}; + use std::sync::mpsc; use super::{Pool, key}; diff --git a/src/client/pool.rs b/src/client/pool.rs --- a/src/client/pool.rs +++ b/src/client/pool.rs @@ -223,5 +228,19 @@ mod tests { assert_eq!(locked.conns.len(), 0); } + /// Tests that the `Pool::set_ssl_verifier` method sets the SSL verifier of + /// the underlying `Connector` instance that it uses. + #[test] + fn test_set_ssl_verifier_delegates_to_connector() { + let (tx, rx) = mpsc::channel(); + let mut pool = Pool::with_connector( + Default::default(), ChannelMockConnector::new(tx)); + + pool.set_ssl_verifier(Box::new(|_| { })); + match rx.try_recv() { + Ok(meth) => assert_eq!(meth, "set_ssl_verifier"), + _ => panic!("Expected a call to `set_ssl_verifier`"), + }; + } } diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -344,12 +347,15 @@ impl NetworkConnector for HttpConnector { } })) } + fn set_ssl_verifier(&mut self, verifier: ContextVerifier) { + self.0 = Some(verifier); + } } #[cfg(test)] mod tests { use mock::MockStream; - use super::NetworkStream; + use super::{NetworkStream, HttpConnector, NetworkConnector}; #[test] fn test_downcast_box_stream() { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -371,4 +377,12 @@ mod tests { } + #[test] + fn test_http_connector_set_ssl_verifier() { + let mut connector = HttpConnector(None); + + connector.set_ssl_verifier(Box::new(|_| {})); + + assert!(connector.0.is_some()); + } }
Client: Setting a custom SSL verifier discards previous Connector When the `Client::set_ssl_verifier` method is called, it will discard any previously existing `Connector` instance that the `Client` was instantiated to use. This wasn't a problem before, when the connectors were largely stateless, but with the introduction of a `Pool` connector, this means that the pool's config will be dropped (replaced with the default one) and the client will use a brand new set of connections, instead of the originally intended ones.
This is true. Before, it was possible when `Client` was generic over the NetworkConnector. Perhaps such a method `set_ssl_verifier` should be added to the `NetworkConnector` trait...
2015-05-09T18:02:10Z
0.4
38f40c7f6a17bd33951bbab1adddf542cbb96de6
hyperium/hyper
499
hyperium__hyper-499
[ "480" ]
b916a7b18cdbbecc872dba8f4ed12d5697cc531c
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -42,7 +42,7 @@ pub use self::referer::Referer; pub use self::server::Server; pub use self::set_cookie::SetCookie; pub use self::transfer_encoding::TransferEncoding; -pub use self::upgrade::{Upgrade, Protocol}; +pub use self::upgrade::{Upgrade, Protocol, ProtocolName}; pub use self::user_agent::UserAgent; pub use self::vary::Vary; diff --git a/src/header/common/upgrade.rs b/src/header/common/upgrade.rs --- a/src/header/common/upgrade.rs +++ b/src/header/common/upgrade.rs @@ -1,9 +1,7 @@ -use std::fmt; +use std::fmt::{self, Display}; use std::str::FromStr; use unicase::UniCase; -use self::Protocol::{WebSocket, ProtocolExt}; - header! { #[doc="`Upgrade` header, defined in [RFC7230](http://tools.ietf.org/html/rfc7230#section-6.7)"] #[doc=""]
diff --git a/src/header/common/upgrade.rs b/src/header/common/upgrade.rs --- a/src/header/common/upgrade.rs +++ b/src/header/common/upgrade.rs @@ -31,47 +29,107 @@ header! { (Upgrade, "Upgrade") => (Protocol)+ test_upgrade { + // Testcase from the RFC test_header!( test1, vec![b"HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11"], - Some(HeaderField(vec![ - Protocol::ProtocolExt("HTTP/2.0".to_string()), - Protocol::ProtocolExt("SHTTP/1.3".to_string()), - Protocol::ProtocolExt("IRC/6.9".to_string()), - Protocol::ProtocolExt("RTA/x11".to_string()), + Some(Upgrade(vec![ + Protocol::new(ProtocolName::Http, Some("2.0".to_string())), + Protocol::new(ProtocolName::Unregistered("SHTTP".to_string()), Some("1.3".to_string())), + Protocol::new(ProtocolName::Unregistered("IRC".to_string()), Some("6.9".to_string())), + Protocol::new(ProtocolName::Unregistered("RTA".to_string()), Some("x11".to_string())), ]))); + // Own tests + test_header!( + test2, vec![b"websocket"], + Some(Upgrade(vec![Protocol::new(ProtocolName::WebSocket, None)]))); + #[test] + fn test3() { + let x: Option<Upgrade> = Header::parse_header(&[b"WEbSOCKet".to_vec()]); + assert_eq!(x, Some(Upgrade(vec![Protocol::new(ProtocolName::WebSocket, None)]))); + } } } -/// Protocol values that can appear in the Upgrade header. -// TODO: Parse version part seperately -#[derive(Clone, PartialEq, Debug)] -pub enum Protocol { - /// The websocket protocol. +/// A protocol name used to identify a spefic protocol. Names are case-sensitive +/// except for the `WebSocket` value. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ProtocolName { + /// `HTTP` value, Hypertext Transfer Protocol + Http, + /// `TLS` value, Transport Layer Security [RFC2817](http://tools.ietf.org/html/rfc2817) + Tls, + /// `WebSocket` value, matched case insensitively,Web Socket Protocol + /// [RFC6455](http://tools.ietf.org/html/rfc6455) WebSocket, - /// Some other less common protocol. - ProtocolExt(String), + /// `h2c` value, HTTP/2 over cleartext TCP + H2c, + /// Any other protocol name not known to hyper + Unregistered(String), } -impl FromStr for Protocol { +impl FromStr for ProtocolName { type Err = (); - fn from_str(s: &str) -> Result<Protocol, ()> { - if UniCase(s) == UniCase("websocket") { - Ok(WebSocket) - } - else { - Ok(ProtocolExt(s.to_string())) - } + fn from_str(s: &str) -> Result<ProtocolName, ()> { + Ok(match s { + "HTTP" => ProtocolName::Http, + "TLS" => ProtocolName::Tls, + "h2c" => ProtocolName::H2c, + _ => { + if UniCase(s) == UniCase("websocket") { + ProtocolName::WebSocket + } else { + ProtocolName::Unregistered(s.to_string()) + } + } + }) } } -impl fmt::Display for Protocol { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - write!(fmt, "{}", match *self { - WebSocket => "websocket", - ProtocolExt(ref s) => s.as_ref() +impl Display for ProtocolName { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(match *self { + ProtocolName::Http => "HTTP", + ProtocolName::Tls => "TLS", + ProtocolName::WebSocket => "websocket", + ProtocolName::H2c => "h2c", + ProtocolName::Unregistered(ref s) => s, }) } } +/// Protocols that appear in the `Upgrade` header field +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Protocol { + /// The protocol identifier + pub name: ProtocolName, + /// The optional version of the protocol, often in the format "DIGIT.DIGIT" (e.g.. "1.2") + pub version: Option<String>, +} + +impl Protocol { + /// Creates a new Protocol with the given name and version + pub fn new(name: ProtocolName, version: Option<String>) -> Protocol { + Protocol { name: name, version: version } + } +} + +impl FromStr for Protocol { + type Err =(); + fn from_str(s: &str) -> Result<Protocol, ()> { + let mut parts = s.splitn(2, '/'); + Ok(Protocol::new(try!(parts.next().unwrap().parse()), parts.next().map(|x| x.to_string()))) + } +} + +impl Display for Protocol { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(fmt::Display::fmt(&self.name, f)); + if let Some(ref version) = self.version { + try!(write!(f, "/{}", version)); + } + Ok(()) + } +} + bench_header!(bench, Upgrade, { vec![b"HTTP/2.0, RTA/x11, websocket".to_vec()] });
Reminder: Upgrade header Protocols should support version As defined in http://tools.ietf.org/html/rfc7230#section-6.7 a protocol consists of a name and an optional version token.
I don't understand what the action is for this issue. Does the `Upgrade` header need to be changed? Yes we need to change `Upgrade` header field. (What means "need" we can also keep it but do not implement the RFC) The RFC says: ``` Upgrade = 1#protocol protocol = protocol-name ["/" protocol-version] protocol-name = token protocol-version = token ``` We do: ``` Upgrade = 1#protocol protocol = text ```
2015-05-02T17:30:05Z
0.3
b916a7b18cdbbecc872dba8f4ed12d5697cc531c
hyperium/hyper
498
hyperium__hyper-498
[ "497" ]
6d7ae81e36096947b28ce5a5414df3c75d1fbae9
diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -409,8 +409,8 @@ impl<'a> TryParse for httparse::Response<'a, 'a> { httparse::Status::Complete(len) => { let code = res.code.unwrap(); let reason = match StatusCode::from_u16(code).canonical_reason() { - Some(reason) => Cow::Borrowed(reason), - None => Cow::Owned(res.reason.unwrap().to_owned()) + Some(reason) if reason == res.reason.unwrap() => Cow::Borrowed(reason), + _ => Cow::Owned(res.reason.unwrap().to_owned()) }; httparse::Status::Complete((Incoming { version: if res.version.unwrap() == 1 { Http11 } else { Http10 },
diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -460,7 +460,7 @@ mod tests { use buffer::BufReader; use mock::MockStream; - use super::{read_chunk_size, parse_request}; + use super::{read_chunk_size, parse_request, parse_response}; #[test] fn test_write_chunked() { diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -533,6 +533,22 @@ mod tests { parse_request(&mut buf).unwrap(); } + #[test] + fn test_parse_raw_status() { + let mut raw = MockStream::with_input(b"HTTP/1.1 200 OK\r\n\r\n"); + let mut buf = BufReader::new(&mut raw); + let res = parse_response(&mut buf).unwrap(); + + assert_eq!(res.subject.1, "OK"); + + let mut raw = MockStream::with_input(b"HTTP/1.1 200 Howdy\r\n\r\n"); + let mut buf = BufReader::new(&mut raw); + let res = parse_response(&mut buf).unwrap(); + + assert_eq!(res.subject.1, "Howdy"); + } + + #[test] fn test_parse_tcp_closed() { use std::io::ErrorKind;
Real status text gets lost This is blocking the Servo rustup. Code went from ``` rust let reason = match str::from_utf8(cursor.into_inner()) { Ok(s) => s.trim(), Err(_) => return Err(HttpStatusError) }; let reason = match from_u16::<StatusCode>(code) { Some(status) => match status.canonical_reason() { Some(phrase) => { if phrase == reason { Borrowed(phrase) } else { Owned(reason.to_string()) } } _ => Owned(reason.to_string()) }, None => return Err(HttpStatusError) }; ``` to ``` rust let code = res.code.unwrap(); let reason = match StatusCode::from_u16(code).canonical_reason() { Some(reason) => Cow::Borrowed(reason), None => Cow::Owned(res.reason.unwrap().to_owned()) }; ```
For what is the reason phrase needed in servo? https://xhr.spec.whatwg.org/#the-statustext-attribute
2015-05-01T22:09:54Z
0.3
b916a7b18cdbbecc872dba8f4ed12d5697cc531c
hyperium/hyper
492
hyperium__hyper-492
[ "490" ]
1426a4ce343bb4533234ac51e7f10d110ec701a6
diff --git /dev/null b/examples/headers.rs new file mode 100644 --- /dev/null +++ b/examples/headers.rs @@ -0,0 +1,13 @@ +#![deny(warnings)] + +#[macro_use] +// TODO: only import header!, blocked by https://github.com/rust-lang/rust/issues/25003 +extern crate hyper; + +// A header in the form of `X-Foo: some random string` +header! { + (Foo, "X-Foo") => [String] +} + +fn main() { +} diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -135,7 +150,7 @@ macro_rules! header { // $nn:expr: Nice name of the header // List header, zero or more items - ($(#[$a:meta])*($id:ident, $n:expr) => ($item:ty)* $tm:ident{$($tf:item)*}) => { + ($(#[$a:meta])*($id:ident, $n:expr) => ($item:ty)*) => { $(#[$a])* #[derive(Clone, Debug, PartialEq)] pub struct $id(pub Vec<$item>); diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -159,19 +174,9 @@ macro_rules! header { self.fmt_header(f) } } - #[allow(unused_imports)] - mod $tm{ - use std::str; - use $crate::header::*; - use $crate::mime::*; - use $crate::method::Method; - use super::$id as HeaderField; - $($tf)* - } - }; // List header, one or more items - ($(#[$a:meta])*($id:ident, $n:expr) => ($item:ty)+ $tm:ident{$($tf:item)*}) => { + ($(#[$a:meta])*($id:ident, $n:expr) => ($item:ty)+) => { $(#[$a])* #[derive(Clone, Debug, PartialEq)] pub struct $id(pub Vec<$item>); diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -195,18 +200,9 @@ macro_rules! header { self.fmt_header(f) } } - #[allow(unused_imports)] - mod $tm{ - use std::str; - use $crate::header::*; - use $crate::mime::*; - use $crate::method::Method; - use super::$id as HeaderField; - $($tf)* - } }; // Single value header - ($(#[$a:meta])*($id:ident, $n:expr) => [$value:ty] $tm:ident{$($tf:item)*}) => { + ($(#[$a:meta])*($id:ident, $n:expr) => [$value:ty]) => { $(#[$a])* #[derive(Clone, Debug, PartialEq)] pub struct $id(pub $value); diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -229,18 +225,9 @@ macro_rules! header { ::std::fmt::Display::fmt(&**self, f) } } - #[allow(unused_imports)] - mod $tm{ - use std::str; - use $crate::header::*; - use $crate::mime::*; - use $crate::method::Method; - use super::$id as HeaderField; - $($tf)* - } }; // List header, one or more items with "*" option - ($(#[$a:meta])*($id:ident, $n:expr) => {Any / ($item:ty)+} $tm:ident{$($tf:item)*}) => { + ($(#[$a:meta])*($id:ident, $n:expr) => {Any / ($item:ty)+}) => { $(#[$a])* #[derive(Clone, Debug, PartialEq)] pub enum $id {
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -95,6 +95,21 @@ macro_rules! deref( } ); +macro_rules! tm { + ($id:ident, $tm:ident{$($tf:item)*}) => { + #[allow(unused_imports)] + mod $tm{ + use std::str; + use $crate::header::*; + use $crate::mime::*; + use $crate::method::Method; + use super::$id as HeaderField; + $($tf)* + } + + } +} + #[macro_export] macro_rules! test_header { ($id:ident, $raw:expr) => { diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -279,18 +266,44 @@ macro_rules! header { self.fmt_header(f) } } - #[allow(unused_imports)] - mod $tm{ - use std::str; - use $crate::header::*; - use $crate::mime::*; - use $crate::method::Method; - use super::$id as HeaderField; - $($tf)* + }; + + // optional test module + ($(#[$a:meta])*($id:ident, $n:expr) => ($item:ty)* $tm:ident{$($tf:item)*}) => { + header! { + $(#[$a])* + ($id, $n) => ($item)* } + + tm! { $id, $tm { $($tf)* }} + }; + ($(#[$a:meta])*($id:ident, $n:expr) => ($item:ty)+ $tm:ident{$($tf:item)*}) => { + header! { + $(#[$a])* + ($id, $n) => ($item)+ + } + + tm! { $id, $tm { $($tf)* }} + }; + ($(#[$a:meta])*($id:ident, $n:expr) => [$item:ty] $tm:ident{$($tf:item)*}) => { + header! { + $(#[$a])* + ($id, $n) => [$item] + } + + tm! { $id, $tm { $($tf)* }} + }; + ($(#[$a:meta])*($id:ident, $n:expr) => {Any / ($item:ty)+} $tm:ident{$($tf:item)*}) => { + header! { + $(#[$a])* + ($id, $n) => {Any / ($item)+} + } + + tm! { $id, $tm { $($tf)* }} }; } + mod accept; mod access_control_allow_headers; mod access_control_allow_methods;
Breaking change in the header! macro not documented I updated to 0.3.15 and my code is now failing due to changes in `header!` macro: ``` src/lib.rs:250:43: 250:44 error: unexpected end of macro invocation src/lib.rs:250 header!{ (TenantId, "TenantId") => [String] } ``` This is most likely due to commits https://github.com/hyperium/hyper/commit/efd6c96a3cf152b49b672ac87e225e45ab87a477 and https://github.com/hyperium/hyper/commit/a27e6812b9db98fd8f375f2b4b497e4bafc1871e which are not listed as breaking changes. With the new `header!` implementation It seems I must also add a dummy test function when implementing the header which is, IMHO, an unnecessary complication and makes the `header!` macro harder to use. E.g. for my example above: ``` header!{ (TenantId, "TenantId") => [String] test1 {} } ``` Is this the intended behaviour?
cc @pyfisch as he is the one which added the commits mentioned above I'd say this was an oversight. We shouldn't have made a breaking change. A reason making it easier to miss is that all of our internal uses _do_ include a test function. I think part of a fix so as to make sure we don't break the exported `header!` macro in the future is to use it in the `examples/` directory. Sorry, I forgot to add BREAKING CHANGE warnings to the commits. The current behaviour is the intended behaviour. It is impossible (I think so) to add optional parts to a macro without duplicating the definition, since every header should have tests this is no problem for the core of hyper. I think also external headers should have tests, they have been proven useful to discover bugs in header parsing and formatting inside hyper. Using the `test_header!` macro makes it really easy to test headers but it requires to be inside the `header!` macro. #489 will allow external code to use it in tests, but you can also write your own test functions inside the `header!` macro test section. @pyfisch can't the macro be written such that without the test pattern, a dummy empty one is created? ``` rust macro_rules! header { ( $foo:ty $bar:ty ) => ( header! { $foo $bar test_dummy {} } ) } ``` @seanmonstar yes this will probably work. There is one problem: you can't have multiple headers with no tests in one module, because there will be multiple `test_dummy` modules. I guess you can append the `ident`to the name of the test function as the `ident` has to be unique anyhow. Joining identifiers like function or module names does not work.
2015-04-30T22:05:09Z
0.3
b916a7b18cdbbecc872dba8f4ed12d5697cc531c
hyperium/hyper
491
hyperium__hyper-491
[ "388" ]
92ee51acdbf9ac1e2f2d3770f5566196c13b20bd
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -34,6 +34,7 @@ pub use self::if_match::IfMatch; pub use self::if_modified_since::IfModifiedSince; pub use self::if_none_match::IfNoneMatch; pub use self::if_unmodified_since::IfUnmodifiedSince; +pub use self::if_range::IfRange; pub use self::last_modified::LastModified; pub use self::location::Location; pub use self::pragma::Pragma; diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -313,10 +316,11 @@ mod expect; mod expires; mod host; mod if_match; -mod last_modified; mod if_modified_since; mod if_none_match; +mod if_range; mod if_unmodified_since; +mod last_modified; mod location; mod pragma; mod referer;
diff --git /dev/null b/src/header/common/if_range.rs new file mode 100644 --- /dev/null +++ b/src/header/common/if_range.rs @@ -0,0 +1,73 @@ +use header::{self, EntityTag, HttpDate}; + +/// `If-Range` header, defined in [RFC7233](http://tools.ietf.org/html/rfc7233#section-3.2) +/// +/// If a client has a partial copy of a representation and wishes to have +/// an up-to-date copy of the entire representation, it could use the +/// Range header field with a conditional GET (using either or both of +/// If-Unmodified-Since and If-Match.) However, if the precondition +/// fails because the representation has been modified, the client would +/// then have to make a second request to obtain the entire current +/// representation. +/// +/// The `If-Range` header field allows a client to \"short-circuit\" the +/// second request. Informally, its meaning is as follows: if the +/// representation is unchanged, send me the part(s) that I am requesting +/// in Range; otherwise, send me the entire representation. +/// +/// # ABNF +/// ```plain +/// If-Range = entity-tag / HTTP-date +/// ``` +/// +/// # Example values +/// * `Sat, 29 Oct 1994 19:43:31 GMT` +/// * `\"xyzzy\"` +#[derive(Clone, Debug, PartialEq)] +pub enum IfRange { + /// The entity-tag the client has of the resource + EntityTag(EntityTag), + /// The date when the client retrieved the resource + Date(HttpDate), +} + +impl header::Header for IfRange { + fn header_name() -> &'static str { + "If-Range" + } + fn parse_header(raw: &[Vec<u8>]) -> Option<IfRange> { + let etag: Option<EntityTag> = header::parsing::from_one_raw_str(raw); + if etag != None { + return Some(IfRange::EntityTag(etag.unwrap())); + } + let date: Option<HttpDate> = header::parsing::from_one_raw_str(raw); + if date != None { + return Some(IfRange::Date(date.unwrap())); + } + None + } +} + +impl header::HeaderFormat for IfRange { + fn fmt_header(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + match self { + &IfRange::EntityTag(ref x) => write!(f, "{}", x), + &IfRange::Date(ref x) => write!(f, "{}", x), + } + } +} + +impl ::std::fmt::Display for IfRange { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + use header::HeaderFormat; + self.fmt_header(f) + } +} + +#[cfg(test)] +mod test_range { + use header::*; + use super::IfRange as HeaderField; + test_header!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]); + test_header!(test2, vec![b"\"xyzzy\""]); +} diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -118,8 +119,10 @@ macro_rules! test_header { // Test parsing assert_eq!(val, $typed); // Test formatting - let res: &str = str::from_utf8($raw[0]).unwrap(); - assert_eq!(format!("{}", $typed.unwrap()), res); + if $typed != None { + let res: &str = str::from_utf8($raw[0]).unwrap(); + assert_eq!(format!("{}", $typed.unwrap()), res); + } } } }
Implement If-Range header parsing Spec: `http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.27`
RFC2616 is obsolte. New and better spec: https://tools.ietf.org/html/rfc7233#section-3.2 I will do this.
2015-04-30T17:51:04Z
0.3
b916a7b18cdbbecc872dba8f4ed12d5697cc531c
hyperium/hyper
486
hyperium__hyper-486
[ "41" ]
362044c32c2e6a5dcb701c48339d0dddde27effc
diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -46,15 +46,17 @@ use status::StatusClass::Redirection; use {Url, HttpResult}; use HttpError::HttpUriError; +pub use self::pool::Pool; pub use self::request::Request; pub use self::response::Response; +pub mod pool; pub mod request; pub mod response; /// A Client to use additional features with Requests. /// -/// Clients can handle things such as: redirect policy. +/// Clients can handle things such as: redirect policy, connection pooling. pub struct Client { connector: Connector, redirect_policy: RedirectPolicy, diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -64,7 +66,12 @@ impl Client { /// Create a new Client. pub fn new() -> Client { - Client::with_connector(HttpConnector(None)) + Client::with_pool_config(Default::default()) + } + + /// Create a new Client with a configured Pool Config. + pub fn with_pool_config(config: pool::Config) -> Client { + Client::with_connector(Pool::new(config)) } /// Create a new client with a specific connector. diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -78,7 +85,10 @@ impl Client { /// Set the SSL verifier callback for use with OpenSSL. pub fn set_ssl_verifier(&mut self, verifier: ContextVerifier) { - self.connector = with_connector(HttpConnector(Some(verifier))); + self.connector = with_connector(Pool::with_connector( + Default::default(), + HttpConnector(Some(verifier)) + )); } /// Set the RedirectPolicy. diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -1,6 +1,7 @@ //! Client Requests use std::marker::PhantomData; use std::io::{self, Write, BufWriter}; +use std::net::Shutdown; use url::Url; diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -8,7 +9,7 @@ use method::{self, Method}; use header::Headers; use header::{self, Host}; use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming}; -use http::{HttpWriter, LINE_ENDING}; +use http::{self, HttpWriter, LINE_ENDING}; use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter}; use version; use HttpResult; diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -154,7 +155,10 @@ impl Request<Streaming> { /// /// Consumes the Request. pub fn send(self) -> HttpResult<Response> { - let raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes + let mut raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes + if !http::should_keep_alive(self.version, &self.headers) { + try!(raw.close(Shutdown::Write)); + } Response::new(raw) } } diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -1,6 +1,7 @@ //! Client Responses use std::io::{self, Read}; use std::marker::PhantomData; +use std::net::Shutdown; use buffer::BufReader; use header; diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -42,6 +43,10 @@ impl Response { debug!("version={:?}, status={:?}", head.version, status); debug!("headers={:?}", headers); + if !http::should_keep_alive(head.version, &headers) { + try!(stream.get_mut().close(Shutdown::Write)); + } + let body = if headers.has::<TransferEncoding>() { match headers.get::<TransferEncoding>() { Some(&TransferEncoding(ref codings)) => { diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -7,7 +7,8 @@ use std::fmt; use httparse; use buffer::BufReader; -use header::Headers; +use header::{Headers, Connection}; +use header::ConnectionOption::{Close, KeepAlive}; use method::Method; use status::StatusCode; use uri::RequestUri; diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -2,7 +2,7 @@ use std::any::{Any, TypeId}; use std::fmt; use std::io::{self, Read, Write}; -use std::net::{SocketAddr, ToSocketAddrs, TcpStream, TcpListener}; +use std::net::{SocketAddr, ToSocketAddrs, TcpStream, TcpListener, Shutdown}; use std::mem; use std::path::Path; use std::sync::Arc; diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -57,6 +57,10 @@ impl<'a, N: NetworkListener + 'a> Iterator for NetworkConnections<'a, N> { pub trait NetworkStream: Read + Write + Any + Send + Typeable { /// Get the remote address of the underlying connection. fn peer_addr(&mut self) -> io::Result<SocketAddr>; + /// This will be called when Stream should no longer be kept alive. + fn close(&mut self, _how: Shutdown) -> io::Result<()> { + Ok(()) + } } /// A connector creates a NetworkStream. diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -123,6 +127,7 @@ impl NetworkStream + Send { } /// If the underlying type is T, extract it. + #[inline] pub fn downcast<T: Any>(self: Box<NetworkStream + Send>) -> Result<Box<T>, Box<NetworkStream + Send>> { if self.is::<T>() { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -277,12 +282,21 @@ impl Write for HttpStream { } impl NetworkStream for HttpStream { + #[inline] fn peer_addr(&mut self) -> io::Result<SocketAddr> { match *self { HttpStream::Http(ref mut inner) => inner.0.peer_addr(), HttpStream::Https(ref mut inner) => inner.get_mut().0.peer_addr() } } + + #[inline] + fn close(&mut self, how: Shutdown) -> io::Result<()> { + match *self { + HttpStream::Http(ref mut inner) => inner.0.shutdown(how), + HttpStream::Https(ref mut inner) => inner.get_mut().0.shutdown(how) + } + } } /// A connector that will produce HttpStreams. diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -36,13 +36,13 @@ pub use net::{Fresh, Streaming}; use HttpError::HttpIoError; use {HttpResult}; use buffer::BufReader; -use header::{Headers, Connection, Expect}; -use header::ConnectionOption::{Close, KeepAlive}; +use header::{Headers, Expect}; +use http; use method::Method; use net::{NetworkListener, NetworkStream, HttpListener}; use status::StatusCode; use uri::RequestUri; -use version::HttpVersion::{Http10, Http11}; +use version::HttpVersion::Http11; use self::listener::ListenerPool; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -206,11 +206,7 @@ where S: NetworkStream + Clone, H: Handler { } } - keep_alive = match (req.version, req.headers.get::<Connection>()) { - (Http10, Some(conn)) if !conn.contains(&KeepAlive) => false, - (Http11, Some(conn)) if conn.contains(&Close) => false, - _ => true - }; + keep_alive = http::should_keep_alive(req.version, &req.headers); let mut res = Response::new(&mut wrt); res.version = req.version; handler.handle(req, res);
diff --git /dev/null b/src/client/pool.rs new file mode 100644 --- /dev/null +++ b/src/client/pool.rs @@ -0,0 +1,227 @@ +//! Client Connection Pooling +use std::borrow::ToOwned; +use std::collections::HashMap; +use std::io::{self, Read, Write}; +use std::net::{SocketAddr, Shutdown}; +use std::sync::{Arc, Mutex}; + +use net::{NetworkConnector, NetworkStream, HttpConnector}; + +/// The `NetworkConnector` that behaves as a connection pool used by hyper's `Client`. +pub struct Pool<C: NetworkConnector> { + connector: C, + inner: Arc<Mutex<PoolImpl<<C as NetworkConnector>::Stream>>> +} + +/// Config options for the `Pool`. +#[derive(Debug)] +pub struct Config { + /// The maximum idle connections *per host*. + pub max_idle: usize, +} + +impl Default for Config { + #[inline] + fn default() -> Config { + Config { + max_idle: 5, + } + } +} + +#[derive(Debug)] +struct PoolImpl<S> { + conns: HashMap<Key, Vec<S>>, + config: Config, +} + +type Key = (String, u16, Scheme); + +fn key<T: Into<Scheme>>(host: &str, port: u16, scheme: T) -> Key { + (host.to_owned(), port, scheme.into()) +} + +#[derive(Clone, PartialEq, Eq, Debug, Hash)] +enum Scheme { + Http, + Https, + Other(String) +} + +impl<'a> From<&'a str> for Scheme { + fn from(s: &'a str) -> Scheme { + match s { + "http" => Scheme::Http, + "https" => Scheme::Https, + s => Scheme::Other(String::from(s)) + } + } +} + +impl Pool<HttpConnector> { + /// Creates a `Pool` with an `HttpConnector`. + #[inline] + pub fn new(config: Config) -> Pool<HttpConnector> { + Pool::with_connector(config, HttpConnector(None)) + } +} + +impl<C: NetworkConnector> Pool<C> { + /// Creates a `Pool` with a specified `NetworkConnector`. + #[inline] + pub fn with_connector(config: Config, connector: C) -> Pool<C> { + Pool { + connector: connector, + inner: Arc::new(Mutex::new(PoolImpl { + conns: HashMap::new(), + config: config, + })) + } + } + + /// Clear all idle connections from the Pool, closing them. + #[inline] + pub fn clear_idle(&mut self) { + self.inner.lock().unwrap().conns.clear(); + } +} + +impl<S> PoolImpl<S> { + fn reuse(&mut self, key: Key, conn: S) { + trace!("reuse {:?}", key); + let conns = self.conns.entry(key).or_insert(vec![]); + if conns.len() < self.config.max_idle { + conns.push(conn); + } + } +} + +impl<C: NetworkConnector<Stream=S>, S: NetworkStream + Send> NetworkConnector for Pool<C> { + type Stream = PooledStream<S>; + fn connect(&mut self, host: &str, port: u16, scheme: &str) -> io::Result<PooledStream<S>> { + let key = key(host, port, scheme); + let mut locked = self.inner.lock().unwrap(); + let mut should_remove = false; + let conn = match locked.conns.get_mut(&key) { + Some(ref mut vec) => { + should_remove = vec.len() == 1; + vec.pop().unwrap() + } + _ => try!(self.connector.connect(host, port, scheme)) + }; + if should_remove { + locked.conns.remove(&key); + } + Ok(PooledStream { + inner: Some((key, conn)), + is_closed: false, + is_drained: false, + pool: self.inner.clone() + }) + } +} + +/// A Stream that will try to be returned to the Pool when dropped. +pub struct PooledStream<S> { + inner: Option<(Key, S)>, + is_closed: bool, + is_drained: bool, + pool: Arc<Mutex<PoolImpl<S>>> +} + +impl<S: NetworkStream> Read for PooledStream<S> { + #[inline] + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + match self.inner.as_mut().unwrap().1.read(buf) { + Ok(0) => { + self.is_drained = true; + Ok(0) + } + r => r + } + } +} + +impl<S: NetworkStream> Write for PooledStream<S> { + #[inline] + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.inner.as_mut().unwrap().1.write(buf) + } + + #[inline] + fn flush(&mut self) -> io::Result<()> { + self.inner.as_mut().unwrap().1.flush() + } +} + +impl<S: NetworkStream> NetworkStream for PooledStream<S> { + #[inline] + fn peer_addr(&mut self) -> io::Result<SocketAddr> { + self.inner.as_mut().unwrap().1.peer_addr() + } + + #[inline] + fn close(&mut self, how: Shutdown) -> io::Result<()> { + self.is_closed = true; + self.inner.as_mut().unwrap().1.close(how) + } +} + +impl<S> Drop for PooledStream<S> { + fn drop(&mut self) { + trace!("PooledStream.drop, is_closed={}, is_drained={}", self.is_closed, self.is_drained); + if !self.is_closed && self.is_drained { + self.inner.take().map(|(key, conn)| { + if let Ok(mut pool) = self.pool.lock() { + pool.reuse(key, conn); + } + // else poisoned, give up + }); + } + } +} + +#[cfg(test)] +mod tests { + use std::net::Shutdown; + use mock::MockConnector; + use net::{NetworkConnector, NetworkStream}; + + use super::{Pool, key}; + + macro_rules! mocked { + () => ({ + Pool::with_connector(Default::default(), MockConnector) + }) + } + + #[test] + fn test_connect_and_drop() { + let mut pool = mocked!(); + let key = key("127.0.0.1", 3000, "http"); + pool.connect("127.0.0.1", 3000, "http").unwrap().is_drained = true; + { + let locked = pool.inner.lock().unwrap(); + assert_eq!(locked.conns.len(), 1); + assert_eq!(locked.conns.get(&key).unwrap().len(), 1); + } + pool.connect("127.0.0.1", 3000, "http").unwrap().is_drained = true; //reused + { + let locked = pool.inner.lock().unwrap(); + assert_eq!(locked.conns.len(), 1); + assert_eq!(locked.conns.get(&key).unwrap().len(), 1); + } + } + + #[test] + fn test_closed() { + let mut pool = mocked!(); + let mut stream = pool.connect("127.0.0.1", 3000, "http").unwrap(); + stream.close(Shutdown::Both).unwrap(); + drop(stream); + let locked = pool.inner.lock().unwrap(); + assert_eq!(locked.conns.len(), 0); + } + + +} diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -443,6 +444,15 @@ pub const LINE_ENDING: &'static str = "\r\n"; #[derive(Clone, PartialEq, Debug)] pub struct RawStatus(pub u16, pub Cow<'static, str>); +/// Checks if a connection should be kept alive. +pub fn should_keep_alive(version: HttpVersion, headers: &Headers) -> bool { + match (version, headers.get::<Connection>()) { + (Http10, Some(conn)) if !conn.contains(&KeepAlive) => false, + (Http11, Some(conn)) if conn.contains(&Close) => false, + _ => true + } +} + #[cfg(test)] mod tests { use std::io::{self, Write};
Implement keep-alive
This is really important for SSL requests. server side is done
2015-04-28T01:26:13Z
0.3
b916a7b18cdbbecc872dba8f4ed12d5697cc531c
hyperium/hyper
485
hyperium__hyper-485
[ "475" ]
f7f0361626a808293e52cbe3fc07bc89490a7c03
diff --git a/src/header/common/accept_language.rs b/src/header/common/accept_language.rs --- a/src/header/common/accept_language.rs +++ b/src/header/common/accept_language.rs @@ -1,39 +1,4 @@ -use header::QualityItem; -use std::str::FromStr; -use std::fmt; - -/// A language tag. -/// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.10 -#[derive(Clone, PartialEq, Debug)] -pub struct Language{ - primary: String, - sub: Option<String> -} - -impl FromStr for Language { - type Err = (); - fn from_str(s: &str) -> Result<Language, ()> { - let mut i = s.split("-"); - let p = i.next(); - let s = i.next(); - match (p, s) { - (Some(p),Some(s)) => Ok(Language{primary: p.to_string(), - sub: Some(s.to_string())}), - (Some(p),_) => Ok(Language{primary: p.to_string(), sub: None}), - _ => Err(()) - } - } -} - -impl fmt::Display for Language { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{}", self.primary)); - match self.sub { - Some(ref s) => write!(f, "-{}", s), - None => Ok(()) - } - } -} +use header::{Language, QualityItem}; header! { #[doc="`Accept-Language` header, defined in"] diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -22,6 +22,7 @@ pub use self::cache_control::{CacheControl, CacheDirective}; pub use self::connection::{Connection, ConnectionOption}; pub use self::content_length::ContentLength; pub use self::content_encoding::ContentEncoding; +pub use self::content_language::ContentLanguage; pub use self::content_type::ContentType; pub use self::cookie::Cookie; pub use self::date::Date; diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -303,6 +304,7 @@ mod cache_control; mod cookie; mod connection; mod content_encoding; +mod content_language; mod content_length; mod content_type; mod date; diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -19,7 +19,7 @@ use unicase::UniCase; use self::internals::Item; use error::HttpResult; -pub use self::shared::{Charset, Encoding, EntityTag, HttpDate, Quality, QualityItem, qitem, q}; +pub use self::shared::*; pub use self::common::*; mod common; diff --git /dev/null b/src/header/shared/language.rs new file mode 100644 --- /dev/null +++ b/src/header/shared/language.rs @@ -0,0 +1,45 @@ +use std::str::FromStr; +use std::fmt; + +/// A language tag. +/// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.10 +/// +/// Note: This is no complete language tag implementation, it should be replaced with +/// github.com/pyfisch/rust-language-tag once it is ready. +#[derive(Clone, PartialEq, Debug)] +pub struct Language { + /// The language tag + pub primary: String, + /// A language subtag or country code + pub sub: Option<String> +} + +impl FromStr for Language { + type Err = (); + fn from_str(s: &str) -> Result<Language, ()> { + let mut i = s.split("-"); + let p = i.next(); + let s = i.next(); + match (p, s) { + (Some(p), Some(s)) => Ok(Language { + primary: p.to_string(), + sub: Some(s.to_string()) + }), + (Some(p), _) => Ok(Language { + primary: p.to_string(), + sub: None + }), + _ => Err(()) + } + } +} + +impl fmt::Display for Language { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(write!(f, "{}", self.primary)); + match self.sub { + Some(ref s) => write!(f, "-{}", s), + None => Ok(()) + } + } +} diff --git a/src/header/shared/mod.rs b/src/header/shared/mod.rs --- a/src/header/shared/mod.rs +++ b/src/header/shared/mod.rs @@ -2,10 +2,12 @@ pub use self::charset::Charset; pub use self::encoding::Encoding; pub use self::entity::EntityTag; pub use self::httpdate::HttpDate; +pub use self::language::Language; pub use self::quality_item::{Quality, QualityItem, qitem, q}; mod charset; mod encoding; mod entity; mod httpdate; +mod language; mod quality_item;
diff --git a/src/header/common/accept_language.rs b/src/header/common/accept_language.rs --- a/src/header/common/accept_language.rs +++ b/src/header/common/accept_language.rs @@ -57,7 +22,7 @@ header! { #[cfg(test)] mod tests { - use header::{Header, qitem, Quality, QualityItem}; + use header::{Header, Language, qitem, Quality, QualityItem}; use super::*; #[test] diff --git /dev/null b/src/header/common/content_language.rs new file mode 100644 --- /dev/null +++ b/src/header/common/content_language.rs @@ -0,0 +1,22 @@ +use header::{Language, QualityItem}; + +header! { + #[doc="`Content-Language` header, defined in"] + #[doc="[RFC7231](https://tools.ietf.org/html/rfc7231#section-3.1.3.2)"] + #[doc=""] + #[doc="The `Content-Language` header field describes the natural language(s)"] + #[doc="of the intended audience for the representation. Note that this"] + #[doc="might not be equivalent to all the languages used within the"] + #[doc="representation."] + #[doc=""] + #[doc="# ABNF"] + #[doc="```plain"] + #[doc="Content-Language = 1#language-tag"] + #[doc="```"] + (ContentLanguage, "Content-Language") => (QualityItem<Language>)+ + + test_content_language { + test_header!(test1, vec![b"da"]); + test_header!(test2, vec![b"mi, en"]); + } +}
Implement Content-Language header https://tools.ietf.org/html/rfc7231#section-3.1.3.2 This will be useful for Servo.
2015-04-27T19:12:52Z
0.3
b916a7b18cdbbecc872dba8f4ed12d5697cc531c
hyperium/hyper
455
hyperium__hyper-455
[ "437" ]
dac2f4db8ac4cd3e529a8a8333a575dbb5b37839
diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -12,7 +12,7 @@ use method::Method; use status::StatusCode; use uri::RequestUri; use version::HttpVersion::{self, Http10, Http11}; -use HttpError:: HttpTooLargeError; +use HttpError::{HttpIoError, HttpTooLargeError}; use {HttpError, HttpResult}; use self::HttpReader::{SizedReader, ChunkedReader, EofReader, EmptyReader}; diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -353,6 +353,12 @@ fn parse<R: Read, T: TryParse<Subject=I>, I>(rdr: &mut BufReader<R>) -> HttpResu _partial => () } match try!(rdr.read_into_buf()) { + 0 if rdr.get_buf().len() == 0 => { + return Err(HttpIoError(io::Error::new( + io::ErrorKind::ConnectionAborted, + "Connection closed" + ))) + }, 0 => return Err(HttpTooLargeError), _ => () } diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -417,6 +423,7 @@ impl<'a> TryParse for httparse::Response<'a> { } /// An Incoming Message head. Includes request/status line, and headers. +#[derive(Debug)] pub struct Incoming<S> { /// HTTP version of the message. pub version: HttpVersion, diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -1,5 +1,5 @@ //! HTTP Server -use std::io::{BufWriter, Write}; +use std::io::{ErrorKind, BufWriter, Write}; use std::marker::PhantomData; use std::net::{SocketAddr, ToSocketAddrs}; use std::path::Path; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -134,7 +134,11 @@ where S: NetworkStream + Clone, H: Handler { while keep_alive { let req = match Request::new(&mut rdr, addr) { Ok(req) => req, - Err(e@HttpIoError(_)) => { + Err(HttpIoError(ref e)) if e.kind() == ErrorKind::ConnectionAborted => { + trace!("tcp closed, cancelling keep-alive loop"); + break; + } + Err(HttpIoError(e)) => { debug!("ioerror in keepalive loop = {:?}", e); break; }
diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -440,8 +447,10 @@ pub struct RawStatus(pub u16, pub Cow<'static, str>); mod tests { use std::io::{self, Write}; - use super::{read_chunk_size}; + use buffer::BufReader; + use mock::MockStream; + use super::{read_chunk_size, parse_request}; #[test] fn test_write_chunked() { diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -509,25 +518,30 @@ mod tests { #[test] fn test_parse_incoming() { - use buffer::BufReader; - use mock::MockStream; - - use super::parse_request; let mut raw = MockStream::with_input(b"GET /echo HTTP/1.1\r\nHost: hyper.rs\r\n\r\n"); let mut buf = BufReader::new(&mut raw); parse_request(&mut buf).unwrap(); } + #[test] + fn test_parse_tcp_closed() { + use std::io::ErrorKind; + use error::HttpError::HttpIoError; + + let mut empty = MockStream::new(); + let mut buf = BufReader::new(&mut empty); + match parse_request(&mut buf) { + Err(HttpIoError(ref e)) if e.kind() == ErrorKind::ConnectionAborted => (), + other => panic!("unexpected result: {:?}", other) + } + } + #[cfg(feature = "nightly")] use test::Bencher; #[cfg(feature = "nightly")] #[bench] fn bench_parse_incoming(b: &mut Bencher) { - use buffer::BufReader; - use mock::MockStream; - - use super::parse_request; let mut raw = MockStream::with_input(b"GET /echo HTTP/1.1\r\nHost: hyper.rs\r\n\r\n"); let mut buf = BufReader::new(&mut raw); b.iter(|| {
HttpTooLargeError after the response Ever since the new buffering code, I get `HttpTooLargeError`s after almost every response. It is after the handler returns and the response has been sent, and so the site continues to function. But clearly something is amiss. The requests are rather normal small requests, nothing large, nothing fancy. ``` ERROR:hyper::server: request error = HttpTooLargeError ``` in `server/mod.rs` `handle_connection()` `while keep_alive` loop, the `Request::new()` calls `http::parse_request()` which fails with HttpTooLargeError at some point around this keep_alive loop, which means that `read_into_buf()` must have returned `Ok(0)` which means that `self.cap < v.capacity()`, but I haven't looked further as to why that is for small requests that are only handled once.
I maked a pull request: https://github.com/hyperium/hyper/pull/454
2015-04-15T18:20:52Z
0.3
b916a7b18cdbbecc872dba8f4ed12d5697cc531c
hyperium/hyper
407
hyperium__hyper-407
[ "406" ]
ce5231508e615276333dc2dff7c8c27a6716a93d
diff --git a/src/buffer.rs b/src/buffer.rs --- a/src/buffer.rs +++ b/src/buffer.rs @@ -27,7 +27,12 @@ impl<R: Read> BufReader<R> { pub fn get_mut(&mut self) -> &mut R { &mut self.inner } pub fn get_buf(&self) -> &[u8] { - self.buf.get_ref() + let pos = self.buf.position() as usize; + if pos < self.buf.get_ref().len() { + &self.buf.get_ref()[pos..] + } else { + &[] + } } pub fn into_inner(self) -> R { self.inner }
diff --git a/src/buffer.rs b/src/buffer.rs --- a/src/buffer.rs +++ b/src/buffer.rs @@ -93,3 +98,18 @@ fn reserve(v: &mut Vec<u8>) { v.reserve(cmp::min(cap * 4, MAX_BUFFER_SIZE) - cap); } } + +#[cfg(test)] +mod tests { + + use std::io::BufRead; + use super::BufReader; + + #[test] + fn test_consume_and_get_buf() { + let mut rdr = BufReader::new(&b"foo bar baz"[..]); + rdr.read_into_buf().unwrap(); + rdr.consume(8); + assert_eq!(rdr.get_buf(), b"baz"); + } +} diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -228,7 +228,6 @@ mod tests { Host: example.domain\r\n\ Expect: 100-continue\r\n\ Content-Length: 10\r\n\ - Connection: close\r\n\ \r\n\ 1234567890\ ");
hyper 0.3.5 is looping handle() is being called repeatedly on just 1 request until some resource becomes exhausted and response.start() fails. 0.3.4 worked fine. I'll post more details once I look into the code.
This commit is the culprit: cb59f609c61a097d5d9fa728b9df33d79922573b fix(http): read more before triggering TooLargeError I wont try to fix, I'll leave it for you Sean as you're more familiar with what you just did. To test, the client that makes the server loop is a GET request via this firefox extension: http://www.restclient.net/
2015-03-30T04:21:21Z
0.3
b916a7b18cdbbecc872dba8f4ed12d5697cc531c
hyperium/hyper
401
hyperium__hyper-401
[ "389" ]
b04f6d8e7ad9550588bceadcc0e21f1434ab244a
diff --git /dev/null b/src/buffer.rs new file mode 100644 --- /dev/null +++ b/src/buffer.rs @@ -0,0 +1,95 @@ +use std::cmp; +use std::iter; +use std::io::{self, Read, BufRead, Cursor}; + +pub struct BufReader<R> { + buf: Cursor<Vec<u8>>, + inner: R +} + +const INIT_BUFFER_SIZE: usize = 4096; +const MAX_BUFFER_SIZE: usize = 8192 + 4096 * 100; + +impl<R: Read> BufReader<R> { + pub fn new(rdr: R) -> BufReader<R> { + BufReader::with_capacity(rdr, INIT_BUFFER_SIZE) + } + + pub fn with_capacity(rdr: R, cap: usize) -> BufReader<R> { + BufReader { + buf: Cursor::new(Vec::with_capacity(cap)), + inner: rdr + } + } + + pub fn get_ref(&self) -> &R { &self.inner } + + pub fn get_mut(&mut self) -> &mut R { &mut self.inner } + + pub fn get_buf(&self) -> &[u8] { + self.buf.get_ref() + } + + pub fn into_inner(self) -> R { self.inner } + + pub fn read_into_buf(&mut self) -> io::Result<usize> { + let v = self.buf.get_mut(); + reserve(v); + let inner = &mut self.inner; + with_end_to_cap(v, |b| inner.read(b)) + } +} + +impl<R: Read> Read for BufReader<R> { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + if self.buf.get_ref().len() == self.buf.position() as usize && + buf.len() >= self.buf.get_ref().capacity() { + return self.inner.read(buf); + } + try!(self.fill_buf()); + self.buf.read(buf) + } +} + +impl<R: Read> BufRead for BufReader<R> { + fn fill_buf(&mut self) -> io::Result<&[u8]> { + if self.buf.position() as usize == self.buf.get_ref().len() { + self.buf.set_position(0); + let v = self.buf.get_mut(); + v.truncate(0); + let inner = &mut self.inner; + try!(with_end_to_cap(v, |b| inner.read(b))); + } + self.buf.fill_buf() + } + + fn consume(&mut self, amt: usize) { + self.buf.consume(amt) + } +} + +fn with_end_to_cap<F>(v: &mut Vec<u8>, f: F) -> io::Result<usize> + where F: FnOnce(&mut [u8]) -> io::Result<usize> +{ + let len = v.len(); + let new_area = v.capacity() - len; + v.extend(iter::repeat(0).take(new_area)); + match f(&mut v[len..]) { + Ok(n) => { + v.truncate(len + n); + Ok(n) + } + Err(e) => { + v.truncate(len); + Err(e) + } + } +} + +#[inline] +fn reserve(v: &mut Vec<u8>) { + let cap = v.capacity(); + if v.len() == cap { + v.reserve(cmp::min(cap * 4, MAX_BUFFER_SIZE) - cap); + } +} diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -1,8 +1,9 @@ //! Client Responses -use std::io::{self, Read, BufReader}; +use std::io::{self, Read}; use std::num::FromPrimitive; use std::marker::PhantomData; +use buffer::BufReader; use header; use header::{ContentLength, TransferEncoding}; use header::Encoding::Chunked; diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -5,12 +5,13 @@ use std::io::{self, Read, Write, BufRead}; use httparse; +use buffer::BufReader; use header::Headers; use method::Method; use uri::RequestUri; use version::HttpVersion::{self, Http10, Http11}; use HttpError:: HttpTooLargeError; -use HttpResult; +use {HttpError, HttpResult}; use self::HttpReader::{SizedReader, ChunkedReader, EofReader, EmptyReader}; use self::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter}; diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -307,56 +308,88 @@ impl<W: Write> Write for HttpWriter<W> { } } +const MAX_HEADERS: usize = 100; + /// Parses a request into an Incoming message head. -pub fn parse_request<T: BufRead>(buf: &mut T) -> HttpResult<Incoming<(Method, RequestUri)>> { - let (inc, len) = { - let slice = try!(buf.fill_buf()); - let mut headers = [httparse::Header { name: "", value: b"" }; 64]; - let mut req = httparse::Request::new(&mut headers); - match try!(req.parse(slice)) { +#[inline] +pub fn parse_request<R: Read>(buf: &mut BufReader<R>) -> HttpResult<Incoming<(Method, RequestUri)>> { + parse::<R, httparse::Request, (Method, RequestUri)>(buf) +} + +/// Parses a response into an Incoming message head. +#[inline] +pub fn parse_response<R: Read>(buf: &mut BufReader<R>) -> HttpResult<Incoming<RawStatus>> { + parse::<R, httparse::Response, RawStatus>(buf) +} + +fn parse<R: Read, T: TryParse<Subject=I>, I>(rdr: &mut BufReader<R>) -> HttpResult<Incoming<I>> { + loop { + match try!(try_parse::<R, T, I>(rdr)) { + httparse::Status::Complete((inc, len)) => { + rdr.consume(len); + return Ok(inc); + }, + _partial => () + } + match try!(rdr.read_into_buf()) { + 0 => return Err(HttpTooLargeError), + _ => () + } + } +} + +fn try_parse<R: Read, T: TryParse<Subject=I>, I>(rdr: &mut BufReader<R>) -> TryParseResult<I> { + let mut headers = [httparse::EMPTY_HEADER; MAX_HEADERS]; + <T as TryParse>::try_parse(&mut headers, rdr.get_buf()) +} + +#[doc(hidden)] +trait TryParse { + type Subject; + fn try_parse<'a>(headers: &'a mut [httparse::Header<'a>], buf: &'a [u8]) -> TryParseResult<Self::Subject>; +} + +type TryParseResult<T> = Result<httparse::Status<(Incoming<T>, usize)>, HttpError>; + +impl<'a> TryParse for httparse::Request<'a> { + type Subject = (Method, RequestUri); + + fn try_parse<'b>(headers: &'b mut [httparse::Header<'b>], buf: &'b [u8]) -> TryParseResult<(Method, RequestUri)> { + let mut req = httparse::Request::new(headers); + Ok(match try!(req.parse(buf)) { httparse::Status::Complete(len) => { - (Incoming { + httparse::Status::Complete((Incoming { version: if req.version.unwrap() == 1 { Http11 } else { Http10 }, subject: ( try!(req.method.unwrap().parse()), try!(req.path.unwrap().parse()) ), headers: try!(Headers::from_raw(req.headers)) - }, len) + }, len)) }, - _ => { - // request head is bigger than a BufRead's buffer? 400 that! - return Err(HttpTooLargeError) - } - } - }; - buf.consume(len); - Ok(inc) + httparse::Status::Partial => httparse::Status::Partial + }) + } } -/// Parses a response into an Incoming message head. -pub fn parse_response<T: BufRead>(buf: &mut T) -> HttpResult<Incoming<RawStatus>> { - let (inc, len) = { - let mut headers = [httparse::Header { name: "", value: b"" }; 64]; - let mut res = httparse::Response::new(&mut headers); - match try!(res.parse(try!(buf.fill_buf()))) { +impl<'a> TryParse for httparse::Response<'a> { + type Subject = RawStatus; + + fn try_parse<'b>(headers: &'b mut [httparse::Header<'b>], buf: &'b [u8]) -> TryParseResult<RawStatus> { + let mut res = httparse::Response::new(headers); + Ok(match try!(res.parse(buf)) { httparse::Status::Complete(len) => { - (Incoming { + httparse::Status::Complete((Incoming { version: if res.version.unwrap() == 1 { Http11 } else { Http10 }, subject: RawStatus( res.code.unwrap(), res.reason.unwrap().to_owned().into_cow() ), headers: try!(Headers::from_raw(res.headers)) - }, len) + }, len)) }, - _ => { - // response head is bigger than a BufRead's buffer? - return Err(HttpTooLargeError) - } - } - }; - buf.consume(len); - Ok(inc) + httparse::Status::Partial => httparse::Status::Partial + }) + } } /// An Incoming Message head. Includes request/status line, and headers. diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -1,5 +1,5 @@ //! HTTP Server -use std::io::{BufReader, BufWriter, Write}; +use std::io::{BufWriter, Write}; use std::marker::PhantomData; use std::net::{SocketAddr, ToSocketAddrs}; use std::path::Path; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -14,6 +14,7 @@ pub use net::{Fresh, Streaming}; use HttpError::HttpIoError; use {HttpResult}; +use buffer::BufReader; use header::{Headers, Connection, Expect}; use header::ConnectionOption::{Close, KeepAlive}; use method::Method; diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -2,10 +2,11 @@ //! //! These are requests that a `hyper::Server` receives, and include its method, //! target URI, headers, and message body. -use std::io::{self, Read, BufReader}; +use std::io::{self, Read}; use std::net::SocketAddr; use {HttpResult}; +use buffer::BufReader; use net::NetworkStream; use version::{HttpVersion}; use method::Method::{self, Get, Head};
diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -103,9 +104,10 @@ impl Read for Response { mod tests { use std::borrow::Cow::Borrowed; use std::boxed::BoxAny; - use std::io::{self, Read, BufReader}; + use std::io::{self, Read}; use std::marker::PhantomData; + use buffer::BufReader; use header::Headers; use header::TransferEncoding; use header::Encoding; diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -456,19 +489,30 @@ mod tests { read_err("1;no CRLF"); } + #[test] + fn test_parse_incoming() { + use buffer::BufReader; + use mock::MockStream; + + use super::parse_request; + let mut raw = MockStream::with_input(b"GET /echo HTTP/1.1\r\nHost: hyper.rs\r\n\r\n"); + let mut buf = BufReader::new(&mut raw); + parse_request(&mut buf).unwrap(); + } + use test::Bencher; #[bench] fn bench_parse_incoming(b: &mut Bencher) { - use std::io::BufReader; + use buffer::BufReader; use mock::MockStream; use super::parse_request; + let mut raw = MockStream::with_input(b"GET /echo HTTP/1.1\r\nHost: hyper.rs\r\n\r\n"); + let mut buf = BufReader::new(&mut raw); b.iter(|| { - let mut raw = MockStream::with_input(b"GET /echo HTTP/1.1\r\nHost: hyper.rs\r\n\r\n"); - let mut buf = BufReader::new(&mut raw); - parse_request(&mut buf).unwrap(); + buf.get_mut().read.set_position(0); }); } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -168,7 +168,8 @@ macro_rules! inspect( #[cfg(test)] #[macro_use] mod mock; - +#[doc(hidden)] +pub mod buffer; pub mod client; pub mod error; pub mod method; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -227,6 +228,7 @@ mod tests { Host: example.domain\r\n\ Expect: 100-continue\r\n\ Content-Length: 10\r\n\ + Connection: close\r\n\ \r\n\ 1234567890\ "); diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -81,12 +82,13 @@ impl<'a, 'b> Read for Request<'a, 'b> { #[cfg(test)] mod tests { + use buffer::BufReader; use header::{Host, TransferEncoding, Encoding}; use net::NetworkStream; use mock::MockStream; use super::Request; - use std::io::{self, Read, BufReader}; + use std::io::{self, Read}; use std::net::SocketAddr; fn sock(s: &str) -> SocketAddr {
Hyper client fails if the header isn't fully received in the first read Some HTTP servers do not send the entire HTTP header in a single chunk. Hyper assumes that the entire header is received when calling fill_buf, which isn't always the case. Running the client example in the documentation against a [Flask test server](http://flask.pocoo.org/) causes it to panic: thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value: HttpTooLargeError'
True, I was hoping that the BufReader would fill it's entire buffer before yielding, which [by default is 64kb](https://github.com/rust-lang/rust/blob/master/src/libstd/io/mod.rs#L50). Is the test server head bigger than this? Or BufReader is yielding earlier? The head is a few bytes long. By looking at Wireshark I could see that the different lines of the head are spread among multiple TCP packets, which causes BufReader to yield the first received packet, which contains only the first head line.
2015-03-27T18:02:42Z
0.3
b916a7b18cdbbecc872dba8f4ed12d5697cc531c
hyperium/hyper
383
hyperium__hyper-383
[ "381" ]
7469e62d1e54d9b6f51e9435306e0455de05e1d0
diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ Hello World Server: extern crate hyper; use std::io::Write; -use std::net::IpAddr; +use std::net::Ipv4Addr; use hyper::Server; use hyper::server::Request; diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ fn hello(_: Request, mut res: Response<Fresh>) { } fn main() { - Server::http(hello).listen(IpAddr::new_v4(127, 0, 0, 1), 3000).unwrap(); + Server::http(hello).listen(Ipv4Addr::new(127, 0, 0, 1), 3000).unwrap(); } ``` diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -27,7 +27,7 @@ fn hyper_handle(_: Request, res: Response) { #[bench] fn bench_hyper(b: &mut Bencher) { let server = hyper::Server::http(hyper_handle); - let mut listener = server.listen(IpAddr::new_v4(127, 0, 0, 1), 0).unwrap(); + let mut listener = server.listen(Ipv4Addr::new(127, 0, 0, 1), 0).unwrap(); let url = hyper::Url::parse(&*format!("http://{}", listener.socket)).unwrap(); b.iter(|| request(url.clone())); diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -1,10 +1,9 @@ #![deny(warnings)] -#![feature(net)] extern crate hyper; extern crate env_logger; use std::io::Write; -use std::net::IpAddr; +use std::net::Ipv4Addr; use hyper::server::{Request, Response}; static PHRASE: &'static [u8] = b"Hello World!"; diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -18,6 +17,6 @@ fn hello(_: Request, res: Response) { fn main() { env_logger::init().unwrap(); let _listening = hyper::Server::http(hello) - .listen(IpAddr::new_v4(127, 0, 0, 1), 3000).unwrap(); + .listen(Ipv4Addr::new(127, 0, 0, 1), 3000).unwrap(); println!("Listening on http://127.0.0.1:3000"); } diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -1,10 +1,9 @@ #![deny(warnings)] -#![feature(net)] extern crate hyper; extern crate env_logger; use std::io::{Write, copy}; -use std::net::IpAddr; +use std::net::Ipv4Addr; use hyper::{Get, Post}; use hyper::header::ContentLength; diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -53,6 +52,6 @@ fn echo(mut req: Request, mut res: Response) { fn main() { env_logger::init().unwrap(); let server = Server::http(echo); - let _guard = server.listen(IpAddr::new_v4(127, 0, 0, 1), 1337).unwrap(); + let _guard = server.listen(Ipv4Addr::new(127, 0, 0, 1), 1337).unwrap(); println!("Listening on http://127.0.0.1:1337"); } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -75,7 +75,7 @@ impl<T: HeaderFormat + Send + Sync + Clone> HeaderClone for T { } } -impl HeaderFormat { +impl HeaderFormat + Send + Sync { #[inline] unsafe fn downcast_ref_unchecked<T: 'static>(&self) -> &T { mem::transmute(mem::transmute::<&HeaderFormat, raw::TraitObject>(self).data) diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -97,7 +97,7 @@ impl Clone for Box<NetworkStream + Send> { fn clone(&self) -> Box<NetworkStream + Send> { self.clone_box() } } -impl NetworkStream { +impl NetworkStream + Send { unsafe fn downcast_ref_unchecked<T: 'static>(&self) -> &T { mem::transmute(mem::transmute::<&NetworkStream, raw::TraitObject>(self).data) diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -108,13 +108,13 @@ impl NetworkStream { raw::TraitObject>(self).data) } - unsafe fn downcast_unchecked<T: 'static>(self: Box<NetworkStream>) -> Box<T> { - mem::transmute(mem::transmute::<Box<NetworkStream>, + unsafe fn downcast_unchecked<T: 'static>(self: Box<NetworkStream + Send>) -> Box<T> { + mem::transmute(mem::transmute::<Box<NetworkStream + Send>, raw::TraitObject>(self).data) } } -impl NetworkStream { +impl NetworkStream + Send { /// Is the underlying type in this trait object a T? #[inline] pub fn is<T: 'static>(&self) -> bool { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -143,8 +143,8 @@ impl NetworkStream { } /// If the underlying type is T, extract it. - pub fn downcast<T: 'static>(self: Box<NetworkStream>) - -> Result<Box<T>, Box<NetworkStream>> { + pub fn downcast<T: 'static>(self: Box<NetworkStream + Send>) + -> Result<Box<T>, Box<NetworkStream + Send>> { if self.is::<T>() { Ok(unsafe { self.downcast_unchecked() }) } else { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -215,8 +215,8 @@ impl NetworkListener for HttpListener { #[inline] fn socket_addr(&mut self) -> io::Result<SocketAddr> { match *self { - HttpListener::Http(ref mut tcp) => tcp.socket_addr(), - HttpListener::Https(ref mut tcp, _) => tcp.socket_addr(), + HttpListener::Http(ref mut tcp) => tcp.local_addr(), + HttpListener::Https(ref mut tcp, _) => tcp.local_addr(), } } } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -1,7 +1,7 @@ //! HTTP Server use std::io::{BufReader, BufWriter, Write}; use std::marker::PhantomData; -use std::net::{IpAddr, SocketAddr}; +use std::net::{Ipv4Addr, SocketAddr}; use std::path::Path; use std::thread::{self, JoinGuard}; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -76,7 +76,7 @@ impl<'a, H: Handler + 'static> Server<'a, H, HttpListener> { impl<'a, H: Handler + 'static> Server<'a, H, HttpListener> { /// Binds to a socket, and starts handling connections using a task pool. - pub fn listen_threads(self, ip: IpAddr, port: u16, threads: usize) -> HttpResult<Listening> { + pub fn listen_threads(self, ip: Ipv4Addr, port: u16, threads: usize) -> HttpResult<Listening> { let addr = &(ip, port); let listener = try!(match self.ssl { Some((cert, key)) => HttpListener::https(addr, cert, key), diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -86,7 +86,7 @@ impl<'a, H: Handler + 'static> Server<'a, H, HttpListener> { } /// Binds to a socket and starts handling connections. - pub fn listen(self, ip: IpAddr, port: u16) -> HttpResult<Listening> { + pub fn listen(self, ip: Ipv4Addr, port: u16) -> HttpResult<Listening> { self.listen_threads(ip, port, num_cpus::get() * 5 / 4) } }
diff --git a/benches/client.rs b/benches/client.rs --- a/benches/client.rs +++ b/benches/client.rs @@ -1,5 +1,5 @@ #![deny(warnings)] -#![feature(collections, io, net, test)] +#![feature(collections, test)] extern crate hyper; extern crate test; diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -1,11 +1,11 @@ #![deny(warnings)] -#![feature(net, test)] +#![feature(test)] extern crate hyper; extern crate test; use test::Bencher; use std::io::{Read, Write}; -use std::net::IpAddr; +use std::net::Ipv4Addr; use hyper::method::Method::Get; use hyper::server::{Request, Response}; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,4 @@ -#![feature(core, collections, io, net, +#![feature(core, collections, io, std_misc, box_syntax, unsafe_destructor)] #![deny(missing_docs)] #![cfg_attr(test, deny(warnings))]
hyper doesn't built with new rustc. `IpAddr` was splitted to `Ipv4Addr` and `Ipv6Addr` ``` src\server/mod.rs:4:16: 4:22 error: unresolved import `std::net::IpAddr`. There is no `IpAddr` in `std::net` src\server/mod.rs:4 use std::net::{IpAddr, SocketAddr}; ``` rustc 1.0.0-dev (c10918905 2015-03-18) (built 2015-03-18)
2015-03-20T09:32:33Z
0.3
b916a7b18cdbbecc872dba8f4ed12d5697cc531c
hyperium/hyper
382
hyperium__hyper-382
[ "381", "381" ]
7469e62d1e54d9b6f51e9435306e0455de05e1d0
diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ Hello World Server: extern crate hyper; use std::io::Write; -use std::net::IpAddr; +use std::net::Ipv4Addr; use hyper::Server; use hyper::server::Request; diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ fn hello(_: Request, mut res: Response<Fresh>) { } fn main() { - Server::http(hello).listen(IpAddr::new_v4(127, 0, 0, 1), 3000).unwrap(); + Server::http(hello).listen(Ipv4Addr::new(127, 0, 0, 1), 3000).unwrap(); } ``` diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -27,7 +27,7 @@ fn hyper_handle(_: Request, res: Response) { #[bench] fn bench_hyper(b: &mut Bencher) { let server = hyper::Server::http(hyper_handle); - let mut listener = server.listen(IpAddr::new_v4(127, 0, 0, 1), 0).unwrap(); + let mut listener = server.listen(Ipv4Addr::new(127, 0, 0, 1), 0).unwrap(); let url = hyper::Url::parse(&*format!("http://{}", listener.socket)).unwrap(); b.iter(|| request(url.clone())); diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -1,10 +1,9 @@ #![deny(warnings)] -#![feature(net)] extern crate hyper; extern crate env_logger; use std::io::Write; -use std::net::IpAddr; +use std::net::Ipv4Addr; use hyper::server::{Request, Response}; static PHRASE: &'static [u8] = b"Hello World!"; diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -18,6 +17,6 @@ fn hello(_: Request, res: Response) { fn main() { env_logger::init().unwrap(); let _listening = hyper::Server::http(hello) - .listen(IpAddr::new_v4(127, 0, 0, 1), 3000).unwrap(); + .listen(Ipv4Addr::new(127, 0, 0, 1), 3000).unwrap(); println!("Listening on http://127.0.0.1:3000"); } diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -1,10 +1,9 @@ #![deny(warnings)] -#![feature(net)] extern crate hyper; extern crate env_logger; use std::io::{Write, copy}; -use std::net::IpAddr; +use std::net::Ipv4Addr; use hyper::{Get, Post}; use hyper::header::ContentLength; diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -53,6 +52,6 @@ fn echo(mut req: Request, mut res: Response) { fn main() { env_logger::init().unwrap(); let server = Server::http(echo); - let _guard = server.listen(IpAddr::new_v4(127, 0, 0, 1), 1337).unwrap(); + let _guard = server.listen(Ipv4Addr::new(127, 0, 0, 1), 1337).unwrap(); println!("Listening on http://127.0.0.1:1337"); } diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -215,8 +215,8 @@ impl NetworkListener for HttpListener { #[inline] fn socket_addr(&mut self) -> io::Result<SocketAddr> { match *self { - HttpListener::Http(ref mut tcp) => tcp.socket_addr(), - HttpListener::Https(ref mut tcp, _) => tcp.socket_addr(), + HttpListener::Http(ref mut tcp) => tcp.local_addr(), + HttpListener::Https(ref mut tcp, _) => tcp.local_addr(), } } } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -1,7 +1,7 @@ //! HTTP Server use std::io::{BufReader, BufWriter, Write}; use std::marker::PhantomData; -use std::net::{IpAddr, SocketAddr}; +use std::net::{Ipv4Addr, SocketAddr}; use std::path::Path; use std::thread::{self, JoinGuard}; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -76,7 +76,7 @@ impl<'a, H: Handler + 'static> Server<'a, H, HttpListener> { impl<'a, H: Handler + 'static> Server<'a, H, HttpListener> { /// Binds to a socket, and starts handling connections using a task pool. - pub fn listen_threads(self, ip: IpAddr, port: u16, threads: usize) -> HttpResult<Listening> { + pub fn listen_threads(self, ip: Ipv4Addr, port: u16, threads: usize) -> HttpResult<Listening> { let addr = &(ip, port); let listener = try!(match self.ssl { Some((cert, key)) => HttpListener::https(addr, cert, key), diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -86,7 +86,7 @@ impl<'a, H: Handler + 'static> Server<'a, H, HttpListener> { } /// Binds to a socket and starts handling connections. - pub fn listen(self, ip: IpAddr, port: u16) -> HttpResult<Listening> { + pub fn listen(self, ip: Ipv4Addr, port: u16) -> HttpResult<Listening> { self.listen_threads(ip, port, num_cpus::get() * 5 / 4) } }
diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -5,7 +5,7 @@ extern crate test; use test::Bencher; use std::io::{Read, Write}; -use std::net::IpAddr; +use std::net::Ipv4Addr; use hyper::method::Method::Get; use hyper::server::{Request, Response}; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,4 @@ -#![feature(core, collections, io, net, +#![feature(core, collections, io, std_misc, box_syntax, unsafe_destructor)] #![deny(missing_docs)] #![cfg_attr(test, deny(warnings))]
hyper doesn't built with new rustc. `IpAddr` was splitted to `Ipv4Addr` and `Ipv6Addr` ``` src\server/mod.rs:4:16: 4:22 error: unresolved import `std::net::IpAddr`. There is no `IpAddr` in `std::net` src\server/mod.rs:4 use std::net::{IpAddr, SocketAddr}; ``` rustc 1.0.0-dev (c10918905 2015-03-18) (built 2015-03-18) hyper doesn't built with new rustc. `IpAddr` was splitted to `Ipv4Addr` and `Ipv6Addr` ``` src\server/mod.rs:4:16: 4:22 error: unresolved import `std::net::IpAddr`. There is no `IpAddr` in `std::net` src\server/mod.rs:4 use std::net::{IpAddr, SocketAddr}; ``` rustc 1.0.0-dev (c10918905 2015-03-18) (built 2015-03-18)
2015-03-19T08:16:38Z
0.3
b916a7b18cdbbecc872dba8f4ed12d5697cc531c
hyperium/hyper
377
hyperium__hyper-377
[ "369" ]
fe8c6d9914b7c213edd97fefeddc0ef831e02d4b
diff --git /dev/null b/src/header/common/expect.rs new file mode 100644 --- /dev/null +++ b/src/header/common/expect.rs @@ -0,0 +1,37 @@ +use std::fmt; + +use header::{Header, HeaderFormat}; + +/// The `Expect` header. +/// +/// > The "Expect" header field in a request indicates a certain set of +/// > behaviors (expectations) that need to be supported by the server in +/// > order to properly handle this request. The only such expectation +/// > defined by this specification is 100-continue. +/// > +/// > Expect = "100-continue" +#[derive(Copy, Clone, PartialEq, Debug)] +pub enum Expect { + /// The value `100-continue`. + Continue +} + +impl Header for Expect { + fn header_name() -> &'static str { + "Expect" + } + + fn parse_header(raw: &[Vec<u8>]) -> Option<Expect> { + if &[b"100-continue"] == raw { + Some(Expect::Continue) + } else { + None + } + } +} + +impl HeaderFormat for Expect { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("100-continue") + } +} diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -20,6 +20,7 @@ pub use self::content_type::ContentType; pub use self::cookie::Cookie; pub use self::date::Date; pub use self::etag::Etag; +pub use self::expect::Expect; pub use self::expires::Expires; pub use self::host::Host; pub use self::if_match::IfMatch; diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -160,6 +161,7 @@ mod content_length; mod content_type; mod date; mod etag; +mod expect; mod expires; mod host; mod if_match; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -1,5 +1,5 @@ //! HTTP Server -use std::io::{BufReader, BufWriter}; +use std::io::{BufReader, BufWriter, Write}; use std::marker::PhantomData; use std::net::{IpAddr, SocketAddr}; use std::path::Path; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -14,9 +14,12 @@ pub use net::{Fresh, Streaming}; use HttpError::HttpIoError; use {HttpResult}; -use header::Connection; +use header::{Headers, Connection, Expect}; use header::ConnectionOption::{Close, KeepAlive}; +use method::Method; use net::{NetworkListener, NetworkStream, HttpListener}; +use status::StatusCode; +use uri::RequestUri; use version::HttpVersion::{Http10, Http11}; use self::listener::ListenerPool; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -99,7 +102,7 @@ S: NetworkStream + Clone + Send> Server<'a, H, L> { debug!("threads = {:?}", threads); let pool = ListenerPool::new(listener.clone()); - let work = move |stream| keep_alive_loop(stream, &handler); + let work = move |mut stream| handle_connection(&mut stream, &handler); let guard = thread::scoped(move || pool.accept(work, threads)); diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -111,7 +114,7 @@ S: NetworkStream + Clone + Send> Server<'a, H, L> { } -fn keep_alive_loop<'h, S, H>(mut stream: S, handler: &'h H) +fn handle_connection<'h, S, H>(mut stream: &mut S, handler: &'h H) where S: NetworkStream + Clone, H: Handler { debug!("Incoming stream"); let addr = match stream.peer_addr() { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -128,39 +131,45 @@ where S: NetworkStream + Clone, H: Handler { let mut keep_alive = true; while keep_alive { - keep_alive = handle_connection(addr, &mut rdr, &mut wrt, handler); - debug!("keep_alive = {:?}", keep_alive); - } -} + let req = match Request::new(&mut rdr, addr) { + Ok(req) => req, + Err(e@HttpIoError(_)) => { + debug!("ioerror in keepalive loop = {:?}", e); + break; + } + Err(e) => { + //TODO: send a 400 response + error!("request error = {:?}", e); + break; + } + }; -fn handle_connection<'a, 'aa, 'h, S, H>( - addr: SocketAddr, - rdr: &'a mut BufReader<&'aa mut NetworkStream>, - wrt: &mut BufWriter<S>, - handler: &'h H -) -> bool where 'aa: 'a, S: NetworkStream, H: Handler { - let mut res = Response::new(wrt); - let req = match Request::<'a, 'aa>::new(rdr, addr) { - Ok(req) => req, - Err(e@HttpIoError(_)) => { - debug!("ioerror in keepalive loop = {:?}", e); - return false; - } - Err(e) => { - //TODO: send a 400 response - error!("request error = {:?}", e); - return false; + if req.version == Http11 && req.headers.get() == Some(&Expect::Continue) { + let status = handler.check_continue((&req.method, &req.uri, &req.headers)); + match write!(&mut wrt, "{} {}\r\n\r\n", Http11, status) { + Ok(..) => (), + Err(e) => { + error!("error writing 100-continue: {:?}", e); + break; + } + } + + if status != StatusCode::Continue { + debug!("non-100 status ({}) for Expect 100 request", status); + break; + } } - }; - let keep_alive = match (req.version, req.headers.get::<Connection>()) { - (Http10, Some(conn)) if !conn.contains(&KeepAlive) => false, - (Http11, Some(conn)) if conn.contains(&Close) => false, - _ => true - }; - res.version = req.version; - handler.handle(req, res); - keep_alive + keep_alive = match (req.version, req.headers.get::<Connection>()) { + (Http10, Some(conn)) if !conn.contains(&KeepAlive) => false, + (Http11, Some(conn)) if conn.contains(&Close) => false, + _ => true + }; + let mut res = Response::new(&mut wrt); + res.version = req.version; + handler.handle(req, res); + debug!("keep_alive = {:?}", keep_alive); + } } /// A listening server, which can later be closed.
diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -184,11 +193,78 @@ pub trait Handler: Sync + Send { /// Receives a `Request`/`Response` pair, and should perform some action on them. /// /// This could reading from the request, and writing to the response. - fn handle<'a, 'aa, 'b, 's>(&'s self, Request<'aa, 'a>, Response<'b, Fresh>); + fn handle<'a, 'k>(&'a self, Request<'a, 'k>, Response<'a, Fresh>); + + /// Called when a Request includes a `Expect: 100-continue` header. + /// + /// By default, this will always immediately response with a `StatusCode::Continue`, + /// but can be overridden with custom behavior. + fn check_continue(&self, _: (&Method, &RequestUri, &Headers)) -> StatusCode { + StatusCode::Continue + } } impl<F> Handler for F where F: Fn(Request, Response<Fresh>), F: Sync + Send { - fn handle<'a, 'aa, 'b, 's>(&'s self, req: Request<'a, 'aa>, res: Response<'b, Fresh>) { + fn handle<'a, 'k>(&'a self, req: Request<'a, 'k>, res: Response<'a, Fresh>) { self(req, res) } } + +#[cfg(test)] +mod tests { + use header::Headers; + use method::Method; + use mock::MockStream; + use status::StatusCode; + use uri::RequestUri; + + use super::{Request, Response, Fresh, Handler, handle_connection}; + + #[test] + fn test_check_continue_default() { + let mut mock = MockStream::with_input(b"\ + POST /upload HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Expect: 100-continue\r\n\ + Content-Length: 10\r\n\ + \r\n\ + 1234567890\ + "); + + fn handle(_: Request, res: Response<Fresh>) { + res.start().unwrap().end().unwrap(); + } + + handle_connection(&mut mock, &handle); + let cont = b"HTTP/1.1 100 Continue\r\n\r\n"; + assert_eq!(&mock.write[..cont.len()], cont); + let res = b"HTTP/1.1 200 OK\r\n"; + assert_eq!(&mock.write[cont.len()..cont.len() + res.len()], res); + } + + #[test] + fn test_check_continue_reject() { + struct Reject; + impl Handler for Reject { + fn handle<'a, 'k>(&'a self, _: Request<'a, 'k>, res: Response<'a, Fresh>) { + res.start().unwrap().end().unwrap(); + } + + fn check_continue(&self, _: (&Method, &RequestUri, &Headers)) -> StatusCode { + StatusCode::ExpectationFailed + } + } + + let mut mock = MockStream::with_input(b"\ + POST /upload HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Expect: 100-continue\r\n\ + Content-Length: 10\r\n\ + \r\n\ + 1234567890\ + "); + + handle_connection(&mut mock, &Reject); + assert_eq!(mock.write, b"HTTP/1.1 417 Expectation Failed\r\n\r\n"); + } +}
hyper does not comply with `Expect: 100-continue` statement I'm using hyper to receive githook commit messages and when the payload is longer than 1024 bytes, `request.read_to_string()` is much much slower than it probably should be (something like a factor 100 on localhost)... I have created a very simple test case in https://github.com/octplane/githook-client-rust/tree/slow_read_hyper . It's a simple POST upload that triggers the behavior. I suspect this might be due to the network packets but I'm not sure and I'm certain somebody here will have a much better idea on how to identify the issue :) Thanks for your time !
Hmm. Hyper is using a BufReader, which by [default uses 64kbs](https://github.com/rust-lang/rust/blob/master/src/libstd/io/mod.rs#L55). Is it significantly bigger than that? It is much smaller: 1024 bytes (as indicated by the title of the Issue :wink: ). And the issue starts getting visible at precisely this value. Could you try using `String::with_capacity(1024)` or whichever the size is, and see if that affects things. i'm trying to think where in hyper it might be doing something. It makes strictly no difference. @octplane Could you try to profile the code? Also, would be neat to see actual time values. 1000 bytes can be the size of packet in some cases, so it could just be doing an additional sys call to read the end. @reem , @seanmonstar I have no idea on how to profile rust code... I'm on OSX, FWIW... Ok, after some investigation (read the wget logs), I found out that hyper does not conform to some expected parf of the HTTP specification: ``` time curl -vvv -X POST -d @broken.json http://127.0.0.1:5000/hook/ * Hostname was NOT found in DNS cache * Trying 127.0.0.1... * Connected to 127.0.0.1 (127.0.0.1) port 5000 (#0) > POST /hook/ HTTP/1.1 > User-Agent: curl/7.37.1 > Host: 127.0.0.1:5000 > Accept: */* > Content-Length: 1025 > Content-Type: application/x-www-form-urlencoded > Expect: 100-continue > * Done waiting for 100-continue < HTTP/1.1 200 OK < Transfer-Encoding: chunked < Date: Wed, 11 Mar 2015 20:41:28 GMT < * Connection #0 to host 127.0.0.1 left intact OK.curl -vvv -X POST -d @broken.json http://127.0.0.1:5000/hook/ 0,00s user 0,00s system 0% cpu 1,011 total ``` Because the payload is bigger than 1024 bytes, `curl` attempts a two step posts using the `Expect: 100-continue` instruction. After 1s, curl gives up and send the payload: ` set->expect_100_timeout = 1000L; /* Wait for a second by default. */ ` https://github.com/bagder/curl/blob/df5578a7a304a23f9aa3670daff8573ec3ef416f/lib/transfer.c#L1103 Hyper happily receives the payload and call the handler. Thanks for finding out the real issue! To fix this, I'd imagine adding a `check_continue` method to the `Handler` trait, with a default implementation of just writing continue, and checking for an `Expect` header in the server loop. This allows it to just work, and allows someone to override the behavior if they need to. @seanmonstar I'm not convinced that hyper should actually handle this vs. downstream users/libraries adding features like this. @reem according to [RFC7231](https://tools.ietf.org/html/rfc7231#section-5.1.1): > An origin server MUST, upon receiving an HTTP/1.1 (or later) > request-line and a complete header section that contains a > 100-continue expectation and indicates a request message body will > follow, either send an immediate response with a final status code, > if that status can be determined by examining just the request-line > and header fields, or send an immediate 100 (Continue) response to > encourage the client to send the request's message body. The origin > server MUST NOT wait for the message body before sending the 100 > (Continue) response. I'm convinced.
2015-03-16T23:00:08Z
0.3
b916a7b18cdbbecc872dba8f4ed12d5697cc531c
hyperium/hyper
354
hyperium__hyper-354
[ "347" ]
7235d3f74a6f058a9bedc840519be80384e292da
diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -27,12 +27,13 @@ Hello World Server: ```rust extern crate hyper; -use hyper::status::StatusCode; -use hyper::server::Server; -use hyper::server::request::Request; -use hyper::server::response::Response; +use std::io::Write; +use std::net::IpAddr; + +use hyper::Server; +use hyper::server::Request; +use hyper::server::Response; use hyper::net::Fresh; -use hyper::IpAddr::Ipv4Addr; fn hello(_: Request, mut res: Response<Fresh>) { let mut res = res.start().unwrap(); diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -41,8 +42,7 @@ fn hello(_: Request, mut res: Response<Fresh>) { } fn main() { - let server = Server::http(Ipv4Addr(127, 0, 0, 1), 1337); - server.listen(hello).unwrap(); + Server::http(hello).listen(IpAddr::new_v4(127, 0, 0, 1), 3000).unwrap(); } ``` diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -51,7 +51,9 @@ Client: ```rust extern crate hyper; -use hyper::client::Client; +use std::io::Read; + +use hyper::Client; use hyper::header::Connection; use hyper::header::ConnectionOption; diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -67,7 +69,8 @@ fn main() { .send().unwrap(); // Read the Response. - let body = res.read_to_string().unwrap(); + let mut body = String::new(); + res.read_to_string(&mut body).unwrap(); println!("Response: {}", body); } diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -12,7 +13,8 @@ static PHRASE: &'static [u8] = b"Benchmarking hyper vs others!"; fn request(url: hyper::Url) { let req = hyper::client::Request::new(Get, url).unwrap(); - req.start().unwrap().send().unwrap().read_to_string().unwrap(); + let mut s = String::new(); + req.start().unwrap().send().unwrap().read_to_string(&mut s).unwrap(); } fn hyper_handle(_: Request, res: Response) { diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -23,8 +25,8 @@ fn hyper_handle(_: Request, res: Response) { #[bench] fn bench_hyper(b: &mut Bencher) { - let server = hyper::Server::http(Ipv4Addr(127, 0, 0, 1), 0); - let mut listener = server.listen(hyper_handle).unwrap(); + let server = hyper::Server::http(hyper_handle); + let mut listener = server.listen(IpAddr::new_v4(127, 0, 0, 1), 0).unwrap(); let url = hyper::Url::parse(&*format!("http://{}", listener.socket)).unwrap(); b.iter(|| request(url.clone())); diff --git a/examples/client.rs b/examples/client.rs --- a/examples/client.rs +++ b/examples/client.rs @@ -1,9 +1,7 @@ -#![feature(env, old_io)] +#![feature(env)] extern crate hyper; use std::env; -use std::old_io::stdout; -use std::old_io::util::copy; use hyper::Client; diff --git a/examples/client.rs b/examples/client.rs --- a/examples/client.rs +++ b/examples/client.rs @@ -18,16 +16,12 @@ fn main() { let mut client = Client::new(); - let mut res = match client.get(&*url).send() { + let res = match client.get(&*url).send() { Ok(res) => res, Err(err) => panic!("Failed to connect: {:?}", err) }; println!("Response: {}", res.status); println!("Headers:\n{}", res.headers); - match copy(&mut res, &mut stdout()) { - Ok(..) => (), - Err(e) => panic!("Stream failure: {:?}", e) - }; - + //TODO: add copy back when std::stdio impls std::io::Write. } diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -1,7 +1,8 @@ -#![feature(old_io)] +#![feature(io, net)] extern crate hyper; -use std::old_io::net::ip::Ipv4Addr; +use std::io::Write; +use std::net::IpAddr; use hyper::server::{Request, Response}; static PHRASE: &'static [u8] = b"Hello World!"; diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -13,7 +14,7 @@ fn hello(_: Request, res: Response) { } fn main() { - let _listening = hyper::Server::http(Ipv4Addr(127, 0, 0, 1), 3000) - .listen(hello).unwrap(); + let _listening = hyper::Server::http(hello) + .listen(IpAddr::new_v4(127, 0, 0, 1), 3000).unwrap(); println!("Listening on http://127.0.0.1:3000"); } diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -1,9 +1,9 @@ -#![feature(old_io)] +#![feature(io, net)] extern crate hyper; #[macro_use] extern crate log; -use std::old_io::util::copy; -use std::old_io::net::ip::Ipv4Addr; +use std::io::{Write, copy}; +use std::net::IpAddr; use hyper::{Get, Post}; use hyper::header::ContentLength; diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -50,7 +50,7 @@ fn echo(mut req: Request, mut res: Response) { } fn main() { - let server = Server::http(Ipv4Addr(127, 0, 0, 1), 1337); - let _guard = server.listen(echo).unwrap(); + let server = Server::http(echo); + let _guard = server.listen(IpAddr::new_v4(127, 0, 0, 1), 1337).unwrap(); println!("Listening on http://127.0.0.1:1337"); } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -18,8 +18,7 @@ //! to the `status`, the `headers`, and the response body via the `Writer` //! trait. use std::default::Default; -use std::old_io::IoResult; -use std::old_io::util::copy; +use std::io::{self, copy, Read}; use std::iter::Extend; use url::UrlParser; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -30,7 +29,7 @@ use header::{ContentLength, Location}; use method::Method; use net::{NetworkConnector, HttpConnector, ContextVerifier}; use status::StatusClass::Redirection; -use {Url, Port, HttpResult}; +use {Url, HttpResult}; use HttpError::HttpUriError; pub use self::request::Request; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -238,9 +237,9 @@ pub trait IntoBody<'a> { /// The target enum for the IntoBody trait. pub enum Body<'a> { /// A Reader does not necessarily know it's size, so it is chunked. - ChunkedBody(&'a mut (Reader + 'a)), + ChunkedBody(&'a mut (Read + 'a)), /// For Readers that can know their size, like a `File`. - SizedBody(&'a mut (Reader + 'a), u64), + SizedBody(&'a mut (Read + 'a), u64), /// A String has a size, and uses Content-Length. BufBody(&'a [u8] , usize), } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -255,13 +254,13 @@ impl<'a> Body<'a> { } } -impl<'a> Reader for Body<'a> { +impl<'a> Read for Body<'a> { #[inline] - fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match *self { Body::ChunkedBody(ref mut r) => r.read(buf), Body::SizedBody(ref mut r, _) => r.read(buf), - Body::BufBody(ref mut r, _) => r.read(buf), + Body::BufBody(ref mut r, _) => Read::read(r, buf), } } } diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -288,7 +287,7 @@ impl<'a> IntoBody<'a> for &'a str { } } -impl<'a, R: Reader> IntoBody<'a> for &'a mut R { +impl<'a, R: Read> IntoBody<'a> for &'a mut R { #[inline] fn into_body(self) -> Body<'a> { Body::ChunkedBody(self) diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -337,7 +336,7 @@ impl Default for RedirectPolicy { } } -fn get_host_and_port(url: &Url) -> HttpResult<(String, Port)> { +fn get_host_and_port(url: &Url) -> HttpResult<(String, u16)> { let host = match url.serialize_host() { Some(host) => host, None => return Err(HttpUriError(UrlError::EmptyHost)) diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -1,6 +1,6 @@ //! Client Requests -use std::old_io::{BufferedWriter, IoResult}; use std::marker::PhantomData; +use std::io::{self, Write, BufWriter}; use url::Url; diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -23,7 +23,7 @@ pub struct Request<W> { /// The HTTP version of this request. pub version: version::HttpVersion, - body: HttpWriter<BufferedWriter<Box<NetworkStream + Send>>>, + body: HttpWriter<BufWriter<Box<NetworkStream + Send>>>, headers: Headers, method: method::Method, diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -59,7 +59,7 @@ impl Request<Fresh> { let (host, port) = try!(get_host_and_port(&url)); let stream = try!(connector.connect(&*host, port, &*url.scheme)); - let stream = ThroughWriter(BufferedWriter::new(box stream as Box<NetworkStream + Send>)); + let stream = ThroughWriter(BufWriter::new(box stream as Box<NetworkStream + Send>)); let mut headers = Headers::new(); headers.set(Host { diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -96,7 +96,7 @@ impl Request<Fresh> { Method::Get | Method::Head => { debug!("headers [\n{:?}]", self.headers); try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING)); - EmptyWriter(self.body.unwrap()) + EmptyWriter(self.body.into_inner()) }, _ => { let mut chunked = true; diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -131,9 +131,9 @@ impl Request<Fresh> { try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING)); if chunked { - ChunkedWriter(self.body.unwrap()) + ChunkedWriter(self.body.into_inner()) } else { - SizedWriter(self.body.unwrap(), len) + SizedWriter(self.body.into_inner(), len) } } }; diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -158,19 +158,19 @@ impl Request<Streaming> { /// /// Consumes the Request. pub fn send(self) -> HttpResult<Response> { - let raw = try!(self.body.end()).into_inner(); + let raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes Response::new(raw) } } -impl Writer for Request<Streaming> { +impl Write for Request<Streaming> { #[inline] - fn write_all(&mut self, msg: &[u8]) -> IoResult<()> { - self.body.write_all(msg) + fn write(&mut self, msg: &[u8]) -> io::Result<usize> { + self.body.write(msg) } #[inline] - fn flush(&mut self) -> IoResult<()> { + fn flush(&mut self) -> io::Result<()> { self.body.flush() } } diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -1,6 +1,6 @@ //! Client Responses +use std::io::{self, Read, BufReader}; use std::num::FromPrimitive; -use std::old_io::{BufferedReader, IoResult}; use std::marker::PhantomData; use header; diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -23,7 +23,7 @@ pub struct Response<S = HttpStream> { /// The HTTP version of this response from the server. pub version: version::HttpVersion, status_raw: RawStatus, - body: HttpReader<BufferedReader<Box<NetworkStream + Send>>>, + body: HttpReader<BufReader<Box<NetworkStream + Send>>>, _marker: PhantomData<S>, } diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -35,7 +35,7 @@ impl Response { /// Creates a new response from a server. pub fn new(stream: Box<NetworkStream + Send>) -> HttpResult<Response> { - let mut stream = BufferedReader::new(stream); + let mut stream = BufReader::new(stream); let (version, raw_status) = try!(read_status_line(&mut stream)); let status = match FromPrimitive::from_u16(raw_status.0) { Some(status) => status, diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -89,13 +89,13 @@ impl Response { /// Consumes the Request to return the NetworkStream underneath. pub fn into_inner(self) -> Box<NetworkStream + Send> { - self.body.unwrap().into_inner() + self.body.into_inner().into_inner() } } -impl Reader for Response { +impl Read for Response { #[inline] - fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.body.read(buf) } } diff --git a/src/header/common/accept_language.rs b/src/header/common/accept_language.rs --- a/src/header/common/accept_language.rs +++ b/src/header/common/accept_language.rs @@ -1,4 +1,4 @@ -use header::{self, QualityItem}; +use header::QualityItem; use std::str::FromStr; use std::fmt; diff --git a/src/header/common/host.rs b/src/header/common/host.rs --- a/src/header/common/host.rs +++ b/src/header/common/host.rs @@ -1,5 +1,4 @@ use header::{Header, HeaderFormat}; -use Port; use std::fmt; use header::parsing::from_one_raw_str; diff --git a/src/header/common/host.rs b/src/header/common/host.rs --- a/src/header/common/host.rs +++ b/src/header/common/host.rs @@ -15,7 +14,7 @@ pub struct Host { /// The hostname, such a example.domain. pub hostname: String, /// An optional port number. - pub port: Option<Port> + pub port: Option<u16> } impl Header for Host { diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -7,6 +7,7 @@ use std::any::{Any, TypeId}; use std::borrow::Cow::{Borrowed, Owned}; use std::fmt; +use std::io::Read; use std::raw::TraitObject; use std::str::from_utf8; use std::collections::HashMap; diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -132,7 +133,7 @@ impl Headers { } #[doc(hidden)] - pub fn from_raw<R: Reader>(rdr: &mut R) -> HttpResult<Headers> { + pub fn from_raw<R: Read>(rdr: &mut R) -> HttpResult<Headers> { let mut headers = Headers::new(); let mut count = 0u32; loop { diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -2,7 +2,7 @@ use std::borrow::Cow::{self, Borrowed, Owned}; use std::borrow::IntoCow; use std::cmp::min; -use std::old_io::{self, Reader, IoResult, BufWriter}; +use std::io::{self, Read, Write, Cursor}; use std::num::from_u16; use std::str; diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -14,8 +14,8 @@ use status::StatusCode; use uri; use uri::RequestUri::{AbsolutePath, AbsoluteUri, Authority, Star}; use version::HttpVersion; -use version::HttpVersion::{Http09, Http10, Http11, Http20}; -use HttpError::{HttpHeaderError, HttpIoError, HttpMethodError, HttpStatusError, +use version::HttpVersion::{Http09, Http10, Http11}; +use HttpError::{HttpHeaderError, HttpMethodError, HttpStatusError, HttpUriError, HttpVersionError}; use HttpResult; diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -52,10 +52,10 @@ pub enum HttpReader<R> { EmptyReader(R), } -impl<R: Reader> HttpReader<R> { +impl<R: Read> HttpReader<R> { /// Unwraps this HttpReader and returns the underlying Reader. - pub fn unwrap(self) -> R { + pub fn into_inner(self) -> R { match self { SizedReader(r, _) => r, ChunkedReader(r, _) => r, diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -65,13 +65,13 @@ impl<R: Reader> HttpReader<R> { } } -impl<R: Reader> Reader for HttpReader<R> { - fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { +impl<R: Read> Read for HttpReader<R> { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match *self { SizedReader(ref mut body, ref mut remaining) => { debug!("Sized read, remaining={:?}", remaining); if *remaining == 0 { - Err(old_io::standard_error(old_io::EndOfFile)) + Ok(0) } else { let num = try!(body.read(buf)) as u64; if num > *remaining { diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -97,7 +97,7 @@ impl<R: Reader> Reader for HttpReader<R> { // if the 0 digit was missing from the stream, it would // be an InvalidInput error instead. debug!("end of chunked"); - return Err(old_io::standard_error(old_io::EndOfFile)); + return Ok(0) } let to_read = min(rem as usize, buf.len()); diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -115,29 +115,44 @@ impl<R: Reader> Reader for HttpReader<R> { EofReader(ref mut body) => { body.read(buf) }, - EmptyReader(_) => Err(old_io::standard_error(old_io::EndOfFile)) + EmptyReader(_) => Ok(0) } } } -fn eat<R: Reader>(rdr: &mut R, bytes: &[u8]) -> IoResult<()> { +fn eat<R: Read>(rdr: &mut R, bytes: &[u8]) -> io::Result<()> { + let mut buf = [0]; for &b in bytes.iter() { - match try!(rdr.read_byte()) { - byte if byte == b => (), - _ => return Err(old_io::standard_error(old_io::InvalidInput)) + match try!(rdr.read(&mut buf)) { + 1 if buf[0] == b => (), + _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, + "Invalid characters found", + None)) } } Ok(()) } /// Chunked chunks start with 1*HEXDIGIT, indicating the size of the chunk. -fn read_chunk_size<R: Reader>(rdr: &mut R) -> IoResult<u64> { +fn read_chunk_size<R: Read>(rdr: &mut R) -> io::Result<u64> { + macro_rules! byte ( + ($rdr:ident) => ({ + let mut buf = [0]; + match try!($rdr.read(&mut buf)) { + 1 => buf[0], + _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, + "Invalid chunk size line", + None)), + + } + }) + ); let mut size = 0u64; let radix = 16; let mut in_ext = false; let mut in_chunk_size = true; loop { - match try!(rdr.read_byte()) { + match byte!(rdr) { b@b'0'...b'9' if in_chunk_size => { size *= radix; size += (b - b'0') as u64; diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -151,9 +166,12 @@ fn read_chunk_size<R: Reader>(rdr: &mut R) -> IoResult<u64> { size += (b + 10 - b'A') as u64; }, CR => { - match try!(rdr.read_byte()) { + match byte!(rdr) { LF => break, - _ => return Err(old_io::standard_error(old_io::InvalidInput)) + _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, + "Invalid chunk size line", + None)) + } }, // If we weren't in the extension yet, the ";" signals its start diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -177,7 +195,9 @@ fn read_chunk_size<R: Reader>(rdr: &mut R) -> IoResult<u64> { // Finally, if we aren't in the extension and we're reading any // other octet, the chunk size line is invalid! _ => { - return Err(old_io::standard_error(old_io::InvalidInput)); + return Err(io::Error::new(io::ErrorKind::InvalidInput, + "Invalid chunk size line", + None)) } } } diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -186,7 +206,7 @@ fn read_chunk_size<R: Reader>(rdr: &mut R) -> IoResult<u64> { } /// Writers to handle different Transfer-Encodings. -pub enum HttpWriter<W: Writer> { +pub enum HttpWriter<W: Write> { /// A no-op Writer, used initially before Transfer-Encoding is determined. ThroughWriter(W), /// A Writer for when Transfer-Encoding includes `chunked`. diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -199,10 +219,10 @@ pub enum HttpWriter<W: Writer> { EmptyWriter(W), } -impl<W: Writer> HttpWriter<W> { +impl<W: Write> HttpWriter<W> { /// Unwraps the HttpWriter and returns the underlying Writer. #[inline] - pub fn unwrap(self) -> W { + pub fn into_inner(self) -> W { match self { ThroughWriter(w) => w, ChunkedWriter(w) => w, diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -241,24 +261,25 @@ impl<W: Writer> HttpWriter<W> { /// A final `write_all()` is called with an empty message, and then flushed. /// The ChunkedWriter variant will use this to write the 0-sized last-chunk. #[inline] - pub fn end(mut self) -> IoResult<W> { - try!(self.write_all(&[])); + pub fn end(mut self) -> io::Result<W> { + try!(self.write(&[])); try!(self.flush()); - Ok(self.unwrap()) + Ok(self.into_inner()) } } -impl<W: Writer> Writer for HttpWriter<W> { +impl<W: Write> Write for HttpWriter<W> { #[inline] - fn write_all(&mut self, msg: &[u8]) -> IoResult<()> { + fn write(&mut self, msg: &[u8]) -> io::Result<usize> { match *self { - ThroughWriter(ref mut w) => w.write_all(msg), + ThroughWriter(ref mut w) => w.write(msg), ChunkedWriter(ref mut w) => { let chunk_size = msg.len(); debug!("chunked write, size = {:?}", chunk_size); try!(write!(w, "{:X}{}", chunk_size, LINE_ENDING)); try!(w.write_all(msg)); - w.write_str(LINE_ENDING) + try!(w.write_all(LINE_ENDING.as_bytes())); + Ok(msg.len()) }, SizedWriter(ref mut w, ref mut remaining) => { let len = msg.len() as u64; diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -266,29 +287,24 @@ impl<W: Writer> Writer for HttpWriter<W> { let len = *remaining; *remaining = 0; try!(w.write_all(&msg[..len as usize])); - Err(old_io::standard_error(old_io::ShortWrite(len as usize))) + Ok(len as usize) } else { *remaining -= len; - w.write_all(msg) + try!(w.write_all(msg)); + Ok(len as usize) } }, EmptyWriter(..) => { - let bytes = msg.len(); - if bytes == 0 { - Ok(()) - } else { - Err(old_io::IoError { - kind: old_io::ShortWrite(bytes), - desc: "EmptyWriter cannot write any bytes", - detail: Some("Cannot include a body with this kind of message".to_string()) - }) + if msg.len() != 0 { + error!("Cannot include a body with this kind of message"); } + Ok(0) } } } #[inline] - fn flush(&mut self) -> IoResult<()> { + fn flush(&mut self) -> io::Result<()> { match *self { ThroughWriter(ref mut w) => w.flush(), ChunkedWriter(ref mut w) => w.flush(), diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -345,24 +361,36 @@ pub fn is_token(b: u8) -> bool { /// otherwise returns any error encountered reading the stream. /// /// The remaining contents of `buf` are left untouched. -fn read_token_until_space<R: Reader>(stream: &mut R, buf: &mut [u8]) -> HttpResult<bool> { - use std::old_io::BufWriter; - let mut bufwrt = BufWriter::new(buf); +fn read_method_token_until_space<R: Read>(stream: &mut R, buf: &mut [u8]) -> HttpResult<bool> { + macro_rules! byte ( + ($rdr:ident) => ({ + let mut slot = [0]; + match try!($rdr.read(&mut slot)) { + 1 => slot[0], + _ => return Err(HttpMethodError), + } + }) + ); + + let mut cursor = Cursor::new(buf); loop { - let byte = try!(stream.read_byte()); + let b = byte!(stream); - if byte == SP { + if b == SP { break; - } else if !is_token(byte) { + } else if !is_token(b) { return Err(HttpMethodError); // Read to end but there's still more - } else if bufwrt.write_u8(byte).is_err() { - return Ok(false); + } else { + match cursor.write(&[b]) { + Ok(1) => (), + _ => return Ok(false) + } } } - if bufwrt.tell().unwrap() == 0 { + if cursor.position() == 0 { return Err(HttpMethodError); } diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -372,10 +400,10 @@ fn read_token_until_space<R: Reader>(stream: &mut R, buf: &mut [u8]) -> HttpResu /// Read a `Method` from a raw stream, such as `GET`. /// ### Note: /// Extension methods are only parsed to 16 characters. -pub fn read_method<R: Reader>(stream: &mut R) -> HttpResult<method::Method> { +pub fn read_method<R: Read>(stream: &mut R) -> HttpResult<method::Method> { let mut buf = [SP; 16]; - if !try!(read_token_until_space(stream, &mut buf)) { + if !try!(read_method_token_until_space(stream, &mut buf)) { return Err(HttpMethodError); } diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -404,20 +432,29 @@ pub fn read_method<R: Reader>(stream: &mut R) -> HttpResult<method::Method> { } /// Read a `RequestUri` from a raw stream. -pub fn read_uri<R: Reader>(stream: &mut R) -> HttpResult<uri::RequestUri> { - let mut b = try!(stream.read_byte()); +pub fn read_uri<R: Read>(stream: &mut R) -> HttpResult<uri::RequestUri> { + macro_rules! byte ( + ($rdr:ident) => ({ + let mut buf = [0]; + match try!($rdr.read(&mut buf)) { + 1 => buf[0], + _ => return Err(HttpUriError(UrlError::InvalidCharacter)), + } + }) + ); + let mut b = byte!(stream); while b == SP { - b = try!(stream.read_byte()); + b = byte!(stream); } let mut s = String::new(); if b == STAR { - try!(expect(stream.read_byte(), SP)); + try!(expect(byte!(stream), SP)); return Ok(Star) } else { s.push(b as char); loop { - match try!(stream.read_byte()) { + match byte!(stream) { SP => { break; }, diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -448,32 +485,37 @@ pub fn read_uri<R: Reader>(stream: &mut R) -> HttpResult<uri::RequestUri> { /// Read the `HttpVersion` from a raw stream, such as `HTTP/1.1`. -pub fn read_http_version<R: Reader>(stream: &mut R) -> HttpResult<HttpVersion> { - try!(expect(stream.read_byte(), b'H')); - try!(expect(stream.read_byte(), b'T')); - try!(expect(stream.read_byte(), b'T')); - try!(expect(stream.read_byte(), b'P')); - try!(expect(stream.read_byte(), b'/')); - - match try!(stream.read_byte()) { +pub fn read_http_version<R: Read>(stream: &mut R) -> HttpResult<HttpVersion> { + macro_rules! byte ( + ($rdr:ident) => ({ + let mut buf = [0]; + match try!($rdr.read(&mut buf)) { + 1 => buf[0], + _ => return Err(HttpVersionError), + } + }) + ); + + try!(expect(byte!(stream), b'H')); + try!(expect(byte!(stream), b'T')); + try!(expect(byte!(stream), b'T')); + try!(expect(byte!(stream), b'P')); + try!(expect(byte!(stream), b'/')); + + match byte!(stream) { b'0' => { - try!(expect(stream.read_byte(), b'.')); - try!(expect(stream.read_byte(), b'9')); + try!(expect(byte!(stream), b'.')); + try!(expect(byte!(stream), b'9')); Ok(Http09) }, b'1' => { - try!(expect(stream.read_byte(), b'.')); - match try!(stream.read_byte()) { + try!(expect(byte!(stream), b'.')); + match byte!(stream) { b'0' => Ok(Http10), b'1' => Ok(Http11), _ => Err(HttpVersionError) } }, - b'2' => { - try!(expect(stream.read_byte(), b'.')); - try!(expect(stream.read_byte(), b'0')); - Ok(Http20) - }, _ => Err(HttpVersionError) } } diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -507,14 +549,24 @@ pub type RawHeaderLine = (String, Vec<u8>); /// > ; obsolete line folding /// > ; see Section 3.2.4 /// > ``` -pub fn read_header<R: Reader>(stream: &mut R) -> HttpResult<Option<RawHeaderLine>> { +pub fn read_header<R: Read>(stream: &mut R) -> HttpResult<Option<RawHeaderLine>> { + macro_rules! byte ( + ($rdr:ident) => ({ + let mut buf = [0]; + match try!($rdr.read(&mut buf)) { + 1 => buf[0], + _ => return Err(HttpHeaderError), + } + }) + ); + let mut name = String::new(); let mut value = vec![]; loop { - match try!(stream.read_byte()) { + match byte!(stream) { CR if name.len() == 0 => { - match try!(stream.read_byte()) { + match byte!(stream) { LF => return Ok(None), _ => return Err(HttpHeaderError) } diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -534,7 +586,7 @@ pub fn read_header<R: Reader>(stream: &mut R) -> HttpResult<Option<RawHeaderLine todo!("handle obs-folding (gross!)"); loop { - match try!(stream.read_byte()) { + match byte!(stream) { CR => break, LF => return Err(HttpHeaderError), b' ' if ows => {}, diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -549,7 +601,7 @@ pub fn read_header<R: Reader>(stream: &mut R) -> HttpResult<Option<RawHeaderLine let real_len = value.len() - value.iter().rev().take_while(|&&x| b' ' == x).count(); value.truncate(real_len); - match try!(stream.read_byte()) { + match byte!(stream) { LF => Ok(Some((name, value))), _ => Err(HttpHeaderError) } diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -560,7 +612,17 @@ pub fn read_header<R: Reader>(stream: &mut R) -> HttpResult<Option<RawHeaderLine pub type RequestLine = (method::Method, uri::RequestUri, HttpVersion); /// Read the `RequestLine`, such as `GET / HTTP/1.1`. -pub fn read_request_line<R: Reader>(stream: &mut R) -> HttpResult<RequestLine> { +pub fn read_request_line<R: Read>(stream: &mut R) -> HttpResult<RequestLine> { + macro_rules! byte ( + ($rdr:ident) => ({ + let mut buf = [0]; + match try!($rdr.read(&mut buf)) { + 1 => buf[0], + _ => return Err(HttpVersionError), + } + }) + ); + debug!("read request line"); let method = try!(read_method(stream)); debug!("method = {:?}", method); diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -569,10 +631,10 @@ pub fn read_request_line<R: Reader>(stream: &mut R) -> HttpResult<RequestLine> { let version = try!(read_http_version(stream)); debug!("version = {:?}", version); - if try!(stream.read_byte()) != CR { + if byte!(stream) != CR { return Err(HttpVersionError); } - if try!(stream.read_byte()) != LF { + if byte!(stream) != LF { return Err(HttpVersionError); } diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -606,9 +668,19 @@ impl Clone for RawStatus { /// > status-code = 3DIGIT /// > reason-phrase = *( HTAB / SP / VCHAR / obs-text ) /// >``` -pub fn read_status_line<R: Reader>(stream: &mut R) -> HttpResult<StatusLine> { +pub fn read_status_line<R: Read>(stream: &mut R) -> HttpResult<StatusLine> { + macro_rules! byte ( + ($rdr:ident) => ({ + let mut buf = [0]; + match try!($rdr.read(&mut buf)) { + 1 => buf[0], + _ => return Err(HttpVersionError), + } + }) + ); + let version = try!(read_http_version(stream)); - if try!(stream.read_byte()) != SP { + if byte!(stream) != SP { return Err(HttpVersionError); } let code = try!(read_status(stream)); diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -617,11 +689,21 @@ pub fn read_status_line<R: Reader>(stream: &mut R) -> HttpResult<StatusLine> { } /// Read the StatusCode from a stream. -pub fn read_status<R: Reader>(stream: &mut R) -> HttpResult<RawStatus> { +pub fn read_status<R: Read>(stream: &mut R) -> HttpResult<RawStatus> { + macro_rules! byte ( + ($rdr:ident) => ({ + let mut buf = [0]; + match try!($rdr.read(&mut buf)) { + 1 => buf[0], + _ => return Err(HttpStatusError), + } + }) + ); + let code = [ - try!(stream.read_byte()), - try!(stream.read_byte()), - try!(stream.read_byte()), + byte!(stream), + byte!(stream), + byte!(stream), ]; let code = match str::from_utf8(code.as_slice()).ok().and_then(|x| x.parse().ok()) { diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -629,27 +711,25 @@ pub fn read_status<R: Reader>(stream: &mut R) -> HttpResult<RawStatus> { None => return Err(HttpStatusError) }; - match try!(stream.read_byte()) { + match byte!(stream) { b' ' => (), _ => return Err(HttpStatusError) } - let mut buf = [b' '; 32]; - + let mut buf = [SP; 32]; + let mut cursor = Cursor::new(&mut buf[..]); { - let mut bufwrt = BufWriter::new(&mut buf); 'read: loop { - match try!(stream.read_byte()) { - CR => match try!(stream.read_byte()) { + match byte!(stream) { + CR => match byte!(stream) { LF => break, _ => return Err(HttpStatusError) }, - b => match bufwrt.write_u8(b) { - Ok(_) => (), - Err(_) => { + b => match cursor.write(&[b]) { + Ok(0) | Err(_) => { for _ in 0u8..128 { - match try!(stream.read_byte()) { - CR => match try!(stream.read_byte()) { + match byte!(stream) { + CR => match byte!(stream) { LF => break 'read, _ => return Err(HttpStatusError) }, diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -658,12 +738,13 @@ pub fn read_status<R: Reader>(stream: &mut R) -> HttpResult<RawStatus> { } return Err(HttpStatusError) } + Ok(_) => (), } } } } - let reason = match str::from_utf8(&buf[..]) { + let reason = match str::from_utf8(cursor.into_inner()) { Ok(s) => s.trim(), Err(_) => return Err(HttpStatusError) }; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -150,7 +150,7 @@ pub use server::Server; use std::error::{Error, FromError}; use std::fmt; -use std::old_io::IoError; +use std::io::Error as IoError; use self::HttpError::{HttpMethodError, HttpUriError, HttpVersionError, HttpHeaderError, HttpStatusError, HttpIoError}; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -164,7 +164,7 @@ macro_rules! todo( macro_rules! inspect( ($name:expr, $value:expr) => ({ let v = $value; - debug!("inspect: {:?} = {:?}", $name, v); + trace!("inspect: {:?} = {:?}", $name, v); v }) ); diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -1,67 +1,69 @@ use std::fmt; -use std::old_io::{IoResult, MemReader, MemWriter}; -use std::old_io::net::ip::SocketAddr; +use std::io::{self, Read, Write, Cursor}; +use std::net::SocketAddr; use net::{NetworkStream, NetworkConnector}; pub struct MockStream { - pub read: MemReader, - pub write: MemWriter, + pub read: Cursor<Vec<u8>>, + pub write: Vec<u8>, } impl Clone for MockStream { fn clone(&self) -> MockStream { MockStream { - read: MemReader::new(self.read.get_ref().to_vec()), - write: MemWriter::from_vec(self.write.get_ref().to_vec()), + read: Cursor::new(self.read.get_ref().clone()), + write: self.write.clone() } } } -impl PartialEq for MockStream { - fn eq(&self, other: &MockStream) -> bool { - self.read.get_ref() == other.read.get_ref() && - self.write.get_ref() == other.write.get_ref() - } -} - impl fmt::Debug for MockStream { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "MockStream {{ read: {:?}, write: {:?} }}", - self.read.get_ref(), self.write.get_ref()) + write!(f, "MockStream {{ read: {:?}, write: {:?} }}", self.read.get_ref(), self.write) } +} +impl PartialEq for MockStream { + fn eq(&self, other: &MockStream) -> bool { + self.read.get_ref() == other.read.get_ref() && self.write == other.write + } } impl MockStream { pub fn new() -> MockStream { MockStream { - read: MemReader::new(vec![]), - write: MemWriter::new(), + read: Cursor::new(vec![]), + write: vec![], } } pub fn with_input(input: &[u8]) -> MockStream { MockStream { - read: MemReader::new(input.to_vec()), - write: MemWriter::new(), + read: Cursor::new(input.to_vec()), + write: vec![] } } } -impl Reader for MockStream { - fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { + +impl Read for MockStream { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.read.read(buf) } } -impl Writer for MockStream { - fn write_all(&mut self, msg: &[u8]) -> IoResult<()> { - self.write.write_all(msg) +impl Write for MockStream { + fn write(&mut self, msg: &[u8]) -> io::Result<usize> { + Write::write(&mut self.write, msg) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) } } impl NetworkStream for MockStream { - fn peer_name(&mut self) -> IoResult<SocketAddr> { + fn peer_addr(&mut self) -> io::Result<SocketAddr> { Ok("127.0.0.1:1337".parse().unwrap()) } } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -71,7 +73,7 @@ pub struct MockConnector; impl NetworkConnector for MockConnector { type Stream = MockStream; - fn connect(&mut self, _host: &str, _port: u16, _scheme: &str) -> IoResult<MockStream> { + fn connect(&mut self, _host: &str, _port: u16, _scheme: &str) -> io::Result<MockStream> { Ok(MockStream::new()) } } diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -86,8 +88,9 @@ macro_rules! mock_connector ( impl ::net::NetworkConnector for $name { type Stream = ::mock::MockStream; - fn connect(&mut self, host: &str, port: u16, scheme: &str) -> ::std::old_io::IoResult<::mock::MockStream> { + fn connect(&mut self, host: &str, port: u16, scheme: &str) -> ::std::io::Result<::mock::MockStream> { use std::collections::HashMap; + use std::io::Cursor; debug!("MockStream::connect({:?}, {:?}, {:?})", host, port, scheme); let mut map = HashMap::new(); $(map.insert($url, $res);)* diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -97,8 +100,8 @@ macro_rules! mock_connector ( // ignore port for now match map.get(&*key) { Some(res) => Ok(::mock::MockStream { - write: ::std::old_io::MemWriter::new(), - read: ::std::old_io::MemReader::new(res.to_string().into_bytes()) + write: vec![], + read: Cursor::new(res.to_string().into_bytes()), }), None => panic!("{:?} doesn't know url {}", stringify!($name), key) } diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -1,11 +1,10 @@ //! A collection of traits abstracting over Listeners and Streams. use std::any::{Any, TypeId}; use std::fmt; -use std::old_io::{IoResult, IoError, ConnectionAborted, InvalidInput, OtherIoError, - Stream, Listener, Acceptor}; -use std::old_io::net::ip::{SocketAddr, ToSocketAddr, Port}; -use std::old_io::net::tcp::{TcpStream, TcpListener, TcpAcceptor}; +use std::io::{self, Read, Write}; +use std::net::{SocketAddr, ToSocketAddrs, TcpStream, TcpListener}; use std::mem; +use std::path::Path; use std::raw::{self, TraitObject}; use std::sync::Arc; diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -24,34 +23,26 @@ macro_rules! try_some { } /// The write-status indicating headers have not been written. -#[allow(missing_copy_implementations)] -pub struct Fresh; +pub enum Fresh {} /// The write-status indicating headers have been written. -#[allow(missing_copy_implementations)] -pub struct Streaming; +pub enum Streaming {} /// An abstraction to listen for connections on a certain port. -pub trait NetworkListener { - /// Type of Acceptor - type Acceptor: NetworkAcceptor; - /// Listens on a socket. - fn listen<To: ToSocketAddr>(&mut self, addr: To) -> IoResult<Self::Acceptor>; -} - -/// An abstraction to receive `NetworkStream`s. -pub trait NetworkAcceptor: Clone + Send { - /// Type of Stream to receive +pub trait NetworkListener: Clone { + /// The stream produced for each connection. type Stream: NetworkStream + Send + Clone; + /// Listens on a socket. + //fn listen<To: ToSocketAddrs>(&mut self, addr: To) -> io::Result<Self::Acceptor>; /// Returns an iterator of streams. - fn accept(&mut self) -> IoResult<Self::Stream>; + fn accept(&mut self) -> io::Result<Self::Stream>; /// Get the address this Listener ended up listening on. - fn socket_name(&self) -> IoResult<SocketAddr>; + fn socket_addr(&mut self) -> io::Result<SocketAddr>; /// Closes the Acceptor, so no more incoming connections will be handled. - fn close(&mut self) -> IoResult<()>; +// fn close(&mut self) -> io::Result<()>; /// Returns an iterator over incoming connections. fn incoming(&mut self) -> NetworkConnections<Self> { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -60,20 +51,20 @@ pub trait NetworkAcceptor: Clone + Send { } /// An iterator wrapper over a NetworkAcceptor. -pub struct NetworkConnections<'a, N: NetworkAcceptor + 'a>(&'a mut N); +pub struct NetworkConnections<'a, N: NetworkListener + 'a>(&'a mut N); -impl<'a, N: NetworkAcceptor> Iterator for NetworkConnections<'a, N> { - type Item = IoResult<N::Stream>; - fn next(&mut self) -> Option<IoResult<N::Stream>> { +impl<'a, N: NetworkListener + 'a> Iterator for NetworkConnections<'a, N> { + type Item = io::Result<N::Stream>; + fn next(&mut self) -> Option<io::Result<N::Stream>> { Some(self.0.accept()) } } /// An abstraction over streams that a Server can utilize. -pub trait NetworkStream: Stream + Any + StreamClone + Send { +pub trait NetworkStream: Read + Write + Any + StreamClone + Send { /// Get the remote address of the underlying connection. - fn peer_name(&mut self) -> IoResult<SocketAddr>; + fn peer_addr(&mut self) -> io::Result<SocketAddr>; } diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -94,7 +85,7 @@ pub trait NetworkConnector { /// Type of Stream to create type Stream: NetworkStream + Send; /// Connect to a remote address. - fn connect(&mut self, host: &str, port: Port, scheme: &str) -> IoResult<Self::Stream>; + fn connect(&mut self, host: &str, port: u16, scheme: &str) -> io::Result<Self::Stream>; } impl fmt::Debug for Box<NetworkStream + Send> { diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -108,32 +99,6 @@ impl Clone for Box<NetworkStream + Send> { fn clone(&self) -> Box<NetworkStream + Send> { self.clone_box() } } -impl Reader for Box<NetworkStream + Send> { - #[inline] - fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { (**self).read(buf) } -} - -impl Writer for Box<NetworkStream + Send> { - #[inline] - fn write_all(&mut self, msg: &[u8]) -> IoResult<()> { (**self).write_all(msg) } - - #[inline] - fn flush(&mut self) -> IoResult<()> { (**self).flush() } -} - -impl<'a> Reader for &'a mut NetworkStream { - #[inline] - fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { (**self).read(buf) } -} - -impl<'a> Writer for &'a mut NetworkStream { - #[inline] - fn write_all(&mut self, msg: &[u8]) -> IoResult<()> { (**self).write_all(msg) } - - #[inline] - fn flush(&mut self) -> IoResult<()> { (**self).flush() } -} - impl UnsafeAnyExt for NetworkStream { unsafe fn downcast_ref_unchecked<T: 'static>(&self) -> &T { mem::transmute(mem::transmute::<&NetworkStream, diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -191,63 +156,57 @@ impl NetworkStream { } /// A `NetworkListener` for `HttpStream`s. -#[allow(missing_copy_implementations)] pub enum HttpListener { /// Http variant. - Http, + Http(TcpListener), /// Https variant. The two paths point to the certificate and key PEM files, in that order. - Https(Path, Path), + Https(TcpListener, Arc<SslContext>) } -impl NetworkListener for HttpListener { - type Acceptor = HttpAcceptor; - - #[inline] - fn listen<To: ToSocketAddr>(&mut self, addr: To) -> IoResult<HttpAcceptor> { - let mut tcp = try!(TcpListener::bind(addr)); - let addr = try!(tcp.socket_name()); - Ok(match *self { - HttpListener::Http => HttpAcceptor::Http(try!(tcp.listen()), addr), - HttpListener::Https(ref cert, ref key) => { - let mut ssl_context = try!(SslContext::new(Sslv23).map_err(lift_ssl_error)); - try_some!(ssl_context.set_cipher_list("DEFAULT").map(lift_ssl_error)); - try_some!(ssl_context.set_certificate_file( - cert, X509FileType::PEM).map(lift_ssl_error)); - try_some!(ssl_context.set_private_key_file( - key, X509FileType::PEM).map(lift_ssl_error)); - ssl_context.set_verify(SslVerifyNone, None); - HttpAcceptor::Https(try!(tcp.listen()), addr, Arc::new(ssl_context)) - } - }) +impl Clone for HttpListener { + fn clone(&self) -> HttpListener { + match *self { + HttpListener::Http(ref tcp) => HttpListener::Http(tcp.try_clone().unwrap()), + HttpListener::Https(ref tcp, ref ssl) => HttpListener::Https(tcp.try_clone().unwrap(), ssl.clone()), + } } } -/// A `NetworkAcceptor` for `HttpStream`s. -#[derive(Clone)] -pub enum HttpAcceptor { - /// Http variant. - Http(TcpAcceptor, SocketAddr), - /// Https variant. - Https(TcpAcceptor, SocketAddr, Arc<SslContext>), +impl HttpListener { + + /// Start listening to an address over HTTP. + pub fn http<To: ToSocketAddrs>(addr: &To) -> io::Result<HttpListener> { + Ok(HttpListener::Http(try!(TcpListener::bind(addr)))) + } + + /// Start listening to an address over HTTPS. + pub fn https<To: ToSocketAddrs>(addr: &To, cert: &Path, key: &Path) -> io::Result<HttpListener> { + let mut ssl_context = try!(SslContext::new(Sslv23).map_err(lift_ssl_error)); + try_some!(ssl_context.set_cipher_list("DEFAULT").map(lift_ssl_error)); + try_some!(ssl_context.set_certificate_file( + cert, X509FileType::PEM).map(lift_ssl_error)); + try_some!(ssl_context.set_private_key_file( + key, X509FileType::PEM).map(lift_ssl_error)); + ssl_context.set_verify(SslVerifyNone, None); + Ok(HttpListener::Https(try!(TcpListener::bind(addr)), Arc::new(ssl_context))) + } } -impl NetworkAcceptor for HttpAcceptor { +impl NetworkListener for HttpListener { type Stream = HttpStream; #[inline] - fn accept(&mut self) -> IoResult<HttpStream> { + fn accept(&mut self) -> io::Result<HttpStream> { Ok(match *self { - HttpAcceptor::Http(ref mut tcp, _) => HttpStream::Http(try!(tcp.accept())), - HttpAcceptor::Https(ref mut tcp, _, ref ssl_context) => { - let stream = try!(tcp.accept()); - match SslStream::<TcpStream>::new_server(&**ssl_context, stream) { + HttpListener::Http(ref mut tcp) => HttpStream::Http(CloneTcpStream(try!(tcp.accept()).0)), + HttpListener::Https(ref mut tcp, ref ssl_context) => { + let stream = CloneTcpStream(try!(tcp.accept()).0); + match SslStream::new_server(&**ssl_context, stream) { Ok(ssl_stream) => HttpStream::Https(ssl_stream), Err(StreamError(ref e)) => { - return Err(IoError { - kind: ConnectionAborted, - desc: "SSL Handshake Interrupted", - detail: Some(e.desc.to_string()) - }); + return Err(io::Error::new(io::ErrorKind::ConnectionAborted, + "SSL Handshake Interrupted", + Some(e.to_string()))); }, Err(e) => return Err(lift_ssl_error(e)) } diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -256,19 +215,39 @@ impl NetworkAcceptor for HttpAcceptor { } #[inline] - fn close(&mut self) -> IoResult<()> { + fn socket_addr(&mut self) -> io::Result<SocketAddr> { match *self { - HttpAcceptor::Http(ref mut tcp, _) => tcp.close_accept(), - HttpAcceptor::Https(ref mut tcp, _, _) => tcp.close_accept(), + HttpListener::Http(ref mut tcp) => tcp.socket_addr(), + HttpListener::Https(ref mut tcp, _) => tcp.socket_addr(), } } +} + +#[doc(hidden)] +pub struct CloneTcpStream(TcpStream); +impl Clone for CloneTcpStream{ #[inline] - fn socket_name(&self) -> IoResult<SocketAddr> { - match *self { - HttpAcceptor::Http(_, addr) => Ok(addr), - HttpAcceptor::Https(_, addr, _) => Ok(addr), - } + fn clone(&self) -> CloneTcpStream { + CloneTcpStream(self.0.try_clone().unwrap()) + } +} + +impl Read for CloneTcpStream { + #[inline] + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.0.read(buf) + } +} + +impl Write for CloneTcpStream { + #[inline] + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.0.write(buf) + } + #[inline] + fn flush(&mut self) -> io::Result<()> { + self.0.flush() } } diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -276,14 +255,14 @@ impl NetworkAcceptor for HttpAcceptor { #[derive(Clone)] pub enum HttpStream { /// A stream over the HTTP protocol. - Http(TcpStream), + Http(CloneTcpStream), /// A stream over the HTTP protocol, protected by SSL. - Https(SslStream<TcpStream>), + Https(SslStream<CloneTcpStream>), } -impl Reader for HttpStream { +impl Read for HttpStream { #[inline] - fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match *self { HttpStream::Http(ref mut inner) => inner.read(buf), HttpStream::Https(ref mut inner) => inner.read(buf) diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -291,16 +270,16 @@ impl Reader for HttpStream { } } -impl Writer for HttpStream { +impl Write for HttpStream { #[inline] - fn write_all(&mut self, msg: &[u8]) -> IoResult<()> { + fn write(&mut self, msg: &[u8]) -> io::Result<usize> { match *self { - HttpStream::Http(ref mut inner) => inner.write_all(msg), - HttpStream::Https(ref mut inner) => inner.write_all(msg) + HttpStream::Http(ref mut inner) => inner.write(msg), + HttpStream::Https(ref mut inner) => inner.write(msg) } } #[inline] - fn flush(&mut self) -> IoResult<()> { + fn flush(&mut self) -> io::Result<()> { match *self { HttpStream::Http(ref mut inner) => inner.flush(), HttpStream::Https(ref mut inner) => inner.flush(), diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -309,10 +288,10 @@ impl Writer for HttpStream { } impl NetworkStream for HttpStream { - fn peer_name(&mut self) -> IoResult<SocketAddr> { + fn peer_addr(&mut self) -> io::Result<SocketAddr> { match *self { - HttpStream::Http(ref mut inner) => inner.peer_name(), - HttpStream::Https(ref mut inner) => inner.get_mut().peer_name() + HttpStream::Http(ref mut inner) => inner.0.peer_addr(), + HttpStream::Https(ref mut inner) => inner.get_mut().0.peer_addr() } } } diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -327,16 +306,16 @@ pub type ContextVerifier<'v> = Box<FnMut(&mut SslContext) -> ()+'v>; impl<'v> NetworkConnector for HttpConnector<'v> { type Stream = HttpStream; - fn connect(&mut self, host: &str, port: Port, scheme: &str) -> IoResult<HttpStream> { - let addr = (host, port); + fn connect(&mut self, host: &str, port: u16, scheme: &str) -> io::Result<HttpStream> { + let addr = &(host, port); match scheme { "http" => { debug!("http scheme"); - Ok(HttpStream::Http(try!(TcpStream::connect(addr)))) + Ok(HttpStream::Http(CloneTcpStream(try!(TcpStream::connect(addr))))) }, "https" => { debug!("https scheme"); - let stream = try!(TcpStream::connect(addr)); + let stream = CloneTcpStream(try!(TcpStream::connect(addr))); let mut context = try!(SslContext::new(Sslv23).map_err(lift_ssl_error)); if let Some(ref mut verifier) = self.0 { verifier(&mut context); diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -347,32 +326,26 @@ impl<'v> NetworkConnector for HttpConnector<'v> { Ok(HttpStream::Https(stream)) }, _ => { - Err(IoError { - kind: InvalidInput, - desc: "Invalid scheme for Http", - detail: None - }) + Err(io::Error::new(io::ErrorKind::InvalidInput, + "Invalid scheme for Http", + None)) } } } } -fn lift_ssl_error(ssl: SslError) -> IoError { +fn lift_ssl_error(ssl: SslError) -> io::Error { debug!("lift_ssl_error: {:?}", ssl); match ssl { StreamError(err) => err, - SslSessionClosed => IoError { - kind: ConnectionAborted, - desc: "SSL Connection Closed", - detail: None - }, + SslSessionClosed => io::Error::new(io::ErrorKind::ConnectionAborted, + "SSL Connection Closed", + None), // Unfortunately throw this away. No way to support this // detail without a better Error abstraction. - OpenSslErrors(errs) => IoError { - kind: OtherIoError, - desc: "Error in OpenSSL", - detail: Some(format!("{:?}", errs)) - } + OpenSslErrors(errs) => io::Error::new(io::ErrorKind::Other, + "Error in OpenSSL", + Some(format!("{:?}", errs))) } } diff --git a/src/server/acceptor.rs b/src/server/listener.rs --- a/src/server/acceptor.rs +++ b/src/server/listener.rs @@ -1,16 +1,16 @@ use std::thread::{self, JoinGuard}; use std::sync::mpsc; use std::collections::VecMap; -use net::NetworkAcceptor; +use net::NetworkListener; -pub struct AcceptorPool<A: NetworkAcceptor> { +pub struct ListenerPool<A: NetworkListener> { acceptor: A } -impl<'a, A: NetworkAcceptor + 'a> AcceptorPool<A> { +impl<'a, A: NetworkListener + Send + 'a> ListenerPool<A> { /// Create a thread pool to manage the acceptor. - pub fn new(acceptor: A) -> AcceptorPool<A> { - AcceptorPool { acceptor: acceptor } + pub fn new(acceptor: A) -> ListenerPool<A> { + ListenerPool { acceptor: acceptor } } /// Runs the acceptor pool. Blocks until the acceptors are closed. diff --git a/src/server/acceptor.rs b/src/server/listener.rs --- a/src/server/acceptor.rs +++ b/src/server/listener.rs @@ -44,23 +44,16 @@ impl<'a, A: NetworkAcceptor + 'a> AcceptorPool<A> { } } -fn spawn_with<'a, A, F>(supervisor: mpsc::Sender<usize>, work: &'a F, mut acceptor: A, id: usize) -> JoinGuard<'a, ()> -where A: NetworkAcceptor + 'a, - F: Fn(<A as NetworkAcceptor>::Stream) + Send + Sync + 'a { - use std::old_io::EndOfFile; +fn spawn_with<'a, A, F>(supervisor: mpsc::Sender<usize>, work: &'a F, mut acceptor: A, id: usize) -> thread::JoinGuard<'a, ()> +where A: NetworkListener + Send + 'a, + F: Fn(<A as NetworkListener>::Stream) + Send + Sync + 'a { thread::scoped(move || { - let sentinel = Sentinel::new(supervisor, id); + let _sentinel = Sentinel::new(supervisor, id); loop { match acceptor.accept() { Ok(stream) => work(stream), - Err(ref e) if e.kind == EndOfFile => { - debug!("Server closed."); - sentinel.cancel(); - return; - }, - Err(e) => { error!("Connection failed: {}", e); } diff --git a/src/server/acceptor.rs b/src/server/listener.rs --- a/src/server/acceptor.rs +++ b/src/server/listener.rs @@ -72,7 +65,7 @@ where A: NetworkAcceptor + 'a, struct Sentinel<T: Send> { value: Option<T>, supervisor: mpsc::Sender<T>, - active: bool + //active: bool } impl<T: Send> Sentinel<T> { diff --git a/src/server/acceptor.rs b/src/server/listener.rs --- a/src/server/acceptor.rs +++ b/src/server/listener.rs @@ -80,18 +73,18 @@ impl<T: Send> Sentinel<T> { Sentinel { value: Some(data), supervisor: channel, - active: true + //active: true } } - fn cancel(mut self) { self.active = false; } + //fn cancel(mut self) { self.active = false; } } #[unsafe_destructor] impl<T: Send + 'static> Drop for Sentinel<T> { fn drop(&mut self) { // If we were cancelled, get out of here. - if !self.active { return; } + //if !self.active { return; } // Respawn ourselves let _ = self.supervisor.send(self.value.take().unwrap()); diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -1,7 +1,9 @@ //! HTTP Server -use std::old_io::{Listener, BufferedReader, BufferedWriter}; -use std::old_io::net::ip::{IpAddr, Port, SocketAddr}; +use std::io::{BufReader, BufWriter}; +use std::marker::PhantomData; +use std::net::{IpAddr, SocketAddr}; use std::os; +use std::path::Path; use std::thread::{self, JoinGuard}; pub use self::request::Request; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -13,25 +15,24 @@ use HttpError::HttpIoError; use {HttpResult}; use header::Connection; use header::ConnectionOption::{Close, KeepAlive}; -use net::{NetworkListener, NetworkStream, NetworkAcceptor, - HttpAcceptor, HttpListener}; +use net::{NetworkListener, NetworkStream, HttpListener}; use version::HttpVersion::{Http10, Http11}; -use self::acceptor::AcceptorPool; +use self::listener::ListenerPool; pub mod request; pub mod response; -mod acceptor; +mod listener; /// A server can listen on a TCP socket. /// /// Once listening, it will create a `Request`/`Response` pair for each /// incoming connection, and hand them to the provided handler. -pub struct Server<L = HttpListener> { - ip: IpAddr, - port: Port, - listener: L, +pub struct Server<'a, H: Handler, L = HttpListener> { + handler: H, + ssl: Option<(&'a Path, &'a Path)>, + _marker: PhantomData<L> } macro_rules! try_option( diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -43,38 +44,59 @@ macro_rules! try_option( }} ); -impl Server<HttpListener> { - /// Creates a new server that will handle `HttpStream`s. - pub fn http(ip: IpAddr, port: Port) -> Server { - Server::with_listener(ip, port, HttpListener::Http) - } - /// Creates a new server that will handler `HttpStreams`s using a TLS connection. - pub fn https(ip: IpAddr, port: Port, cert: Path, key: Path) -> Server { - Server::with_listener(ip, port, HttpListener::Https(cert, key)) +impl<'a, H: Handler, L: NetworkListener> Server<'a, H, L> { + pub fn new(handler: H) -> Server<'a, H, L> { + Server { + handler: handler, + ssl: None, + _marker: PhantomData + } } } -impl< -L: NetworkListener<Acceptor=A> + Send, -A: NetworkAcceptor<Stream=S> + Send + 'static, -S: NetworkStream + Clone + Send> Server<L> { +impl<'a, H: Handler + 'static> Server<'a, H, HttpListener> { /// Creates a new server that will handle `HttpStream`s. - pub fn with_listener(ip: IpAddr, port: Port, listener: L) -> Server<L> { + pub fn http(handler: H) -> Server<'a, H, HttpListener> { + Server::new(handler) + } + /// Creates a new server that will handler `HttpStreams`s using a TLS connection. + pub fn https(handler: H, cert: &'a Path, key: &'a Path) -> Server<'a, H, HttpListener> { Server { - ip: ip, - port: port, - listener: listener, + handler: handler, + ssl: Some((cert, key)), + _marker: PhantomData } } +} +impl<'a, H: Handler + 'static> Server<'a, H, HttpListener> { /// Binds to a socket, and starts handling connections using a task pool. - pub fn listen_threads<H: Handler + 'static>(mut self, handler: H, threads: usize) -> HttpResult<Listening<L::Acceptor>> { - debug!("binding to {:?}:{:?}", self.ip, self.port); - let acceptor = try!(self.listener.listen((self.ip, self.port))); - let socket = try!(acceptor.socket_name()); + pub fn listen_threads(self, ip: IpAddr, port: u16, threads: usize) -> HttpResult<Listening> { + let addr = &(ip, port); + let listener = try!(match self.ssl { + Some((cert, key)) => HttpListener::https(addr, cert, key), + None => HttpListener::http(addr) + }); + self.with_listener(listener, threads) + } + + /// Binds to a socket and starts handling connections. + pub fn listen(self, ip: IpAddr, port: u16) -> HttpResult<Listening> { + self.listen_threads(ip, port, os::num_cpus() * 5 / 4) + } +} +impl< +'a, +H: Handler + 'static, +L: NetworkListener<Stream=S> + Send + 'static, +S: NetworkStream + Clone + Send> Server<'a, H, L> { + /// Creates a new server that will handle `HttpStream`s. + pub fn with_listener(self, mut listener: L, threads: usize) -> HttpResult<Listening> { + let socket = try!(listener.socket_addr()); + let handler = self.handler; debug!("threads = {:?}", threads); - let pool = AcceptorPool::new(acceptor.clone()); + let pool = ListenerPool::new(listener.clone()); let work = move |stream| handle_connection(stream, &handler); let guard = thread::scoped(move || pool.accept(work, threads)); diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -82,21 +104,15 @@ S: NetworkStream + Clone + Send> Server<L> { Ok(Listening { _guard: guard, socket: socket, - acceptor: acceptor }) } - - /// Binds to a socket and starts handling connections. - pub fn listen<H: Handler + 'static>(self, handler: H) -> HttpResult<Listening<L::Acceptor>> { - self.listen_threads(handler, os::num_cpus() * 5 / 4) - } - } + fn handle_connection<S, H>(mut stream: S, handler: &H) where S: NetworkStream + Clone, H: Handler { debug!("Incoming stream"); - let addr = match stream.peer_name() { + let addr = match stream.peer_addr() { Ok(addr) => addr, Err(e) => { error!("Peer Name error: {:?}", e); diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -104,8 +120,8 @@ where S: NetworkStream + Clone, H: Handler { } }; - let mut rdr = BufferedReader::new(stream.clone()); - let mut wrt = BufferedWriter::new(stream); + let mut rdr = BufReader::new(stream.clone()); + let mut wrt = BufWriter::new(stream); let mut keep_alive = true; while keep_alive { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -135,18 +151,17 @@ where S: NetworkStream + Clone, H: Handler { } /// A listening server, which can later be closed. -pub struct Listening<A = HttpAcceptor> { - acceptor: A, +pub struct Listening { _guard: JoinGuard<'static, ()>, /// The socket addresses that the server is bound to. pub socket: SocketAddr, } -impl<A: NetworkAcceptor> Listening<A> { +impl Listening { /// Stop the server from listening to its socket address. pub fn close(&mut self) -> HttpResult<()> { debug!("closing server"); - try!(self.acceptor.close()); + //try!(self.acceptor.close()); Ok(()) } } diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -2,8 +2,8 @@ //! //! These are requests that a `hyper::Server` receives, and include its method, //! target URI, headers, and message body. -use std::old_io::IoResult; -use std::old_io::net::ip::SocketAddr; +use std::io::{self, Read}; +use std::net::SocketAddr; use {HttpResult}; use version::{HttpVersion}; diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -26,14 +26,14 @@ pub struct Request<'a> { pub uri: RequestUri, /// The version of HTTP for this request. pub version: HttpVersion, - body: HttpReader<&'a mut (Reader + 'a)> + body: HttpReader<&'a mut (Read + 'a)> } impl<'a> Request<'a> { /// Create a new Request, reading the StartLine and Headers so they are /// immediately useful. - pub fn new(mut stream: &'a mut (Reader + 'a), addr: SocketAddr) -> HttpResult<Request<'a>> { + pub fn new(mut stream: &'a mut (Read + 'a), addr: SocketAddr) -> HttpResult<Request<'a>> { let (method, uri, version) = try!(read_request_line(&mut stream)); debug!("Request Line: {:?} {:?} {:?}", method, uri, version); let headers = try!(Headers::from_raw(&mut stream)); diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -66,14 +66,14 @@ impl<'a> Request<'a> { /// Deconstruct a Request into its constituent parts. pub fn deconstruct(self) -> (SocketAddr, Method, Headers, RequestUri, HttpVersion, - HttpReader<&'a mut (Reader + 'a)>,) { + HttpReader<&'a mut (Read + 'a)>,) { (self.remote_addr, self.method, self.headers, self.uri, self.version, self.body) } } -impl<'a> Reader for Request<'a> { - fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { +impl<'a> Read for Request<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.body.read(buf) } } diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -2,8 +2,8 @@ //! //! These are responses sent by a `hyper::Server` to clients, after //! receiving a request. -use std::old_io::IoResult; use std::marker::PhantomData; +use std::io::{self, Write}; use time::now_utc; diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -19,7 +19,7 @@ pub struct Response<'a, W = Fresh> { /// The HTTP version of this response. pub version: version::HttpVersion, // Stream the Response is writing to, not accessible through UnwrittenResponse - body: HttpWriter<&'a mut (Writer + 'a)>, + body: HttpWriter<&'a mut (Write + 'a)>, // The status code for the request. status: status::StatusCode, // The outgoing headers on this response. diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -38,7 +38,7 @@ impl<'a, W> Response<'a, W> { /// Construct a Response from its constituent parts. pub fn construct(version: version::HttpVersion, - body: HttpWriter<&'a mut (Writer + 'a)>, + body: HttpWriter<&'a mut (Write + 'a)>, status: status::StatusCode, headers: header::Headers) -> Response<'a, Fresh> { Response { diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -51,7 +51,7 @@ impl<'a, W> Response<'a, W> { } /// Deconstruct this Response into its constituent parts. - pub fn deconstruct(self) -> (version::HttpVersion, HttpWriter<&'a mut (Writer + 'a)>, + pub fn deconstruct(self) -> (version::HttpVersion, HttpWriter<&'a mut (Write + 'a)>, status::StatusCode, header::Headers) { (self.version, self.body, self.status, self.headers) } diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -59,7 +59,7 @@ impl<'a, W> Response<'a, W> { impl<'a> Response<'a, Fresh> { /// Creates a new Response that can be used to write to a network stream. - pub fn new(stream: &'a mut (Writer + 'a)) -> Response<'a, Fresh> { + pub fn new(stream: &'a mut (Write + 'a)) -> Response<'a, Fresh> { Response { status: status::StatusCode::Ok, version: version::HttpVersion::Http11, diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -70,7 +70,7 @@ impl<'a> Response<'a, Fresh> { } /// Consume this Response<Fresh>, writing the Headers and Status and creating a Response<Streaming> - pub fn start(mut self) -> IoResult<Response<'a, Streaming>> { + pub fn start(mut self) -> io::Result<Response<'a, Streaming>> { debug!("writing head: {:?} {:?}", self.version, self.status); try!(write!(&mut self.body, "{} {}{}{}", self.version, self.status, CR as char, LF as char)); diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -110,13 +110,12 @@ impl<'a> Response<'a, Fresh> { debug!("headers [\n{:?}]", self.headers); try!(write!(&mut self.body, "{}", self.headers)); - - try!(self.body.write_str(LINE_ENDING)); + try!(write!(&mut self.body, "{}", LINE_ENDING)); let stream = if chunked { - ChunkedWriter(self.body.unwrap()) + ChunkedWriter(self.body.into_inner()) } else { - SizedWriter(self.body.unwrap(), len) + SizedWriter(self.body.into_inner(), len) }; // "copy" to change the phantom type diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -139,20 +138,20 @@ impl<'a> Response<'a, Fresh> { impl<'a> Response<'a, Streaming> { /// Flushes all writing of a response to the client. - pub fn end(self) -> IoResult<()> { + pub fn end(self) -> io::Result<()> { debug!("ending"); try!(self.body.end()); Ok(()) } } -impl<'a> Writer for Response<'a, Streaming> { - fn write_all(&mut self, msg: &[u8]) -> IoResult<()> { +impl<'a> Write for Response<'a, Streaming> { + fn write(&mut self, msg: &[u8]) -> io::Result<usize> { debug!("write {:?} bytes", msg.len()); - self.body.write_all(msg) + self.body.write(msg) } - fn flush(&mut self) -> IoResult<()> { + fn flush(&mut self) -> io::Result<()> { self.body.flush() } }
diff --git a/benches/client.rs b/benches/client.rs --- a/benches/client.rs +++ b/benches/client.rs @@ -1,33 +1,53 @@ -#![feature(core, old_io, test)] +#![feature(collections, io, net, test)] extern crate hyper; extern crate test; use std::fmt; -use std::old_io::net::ip::Ipv4Addr; -use hyper::server::{Request, Response, Server}; -use hyper::header::Headers; -use hyper::Client; - -fn listen() -> hyper::server::Listening { - let server = Server::http(Ipv4Addr(127, 0, 0, 1), 0); - server.listen(handle).unwrap() +use std::io::{self, Read, Write, Cursor}; +use std::net::SocketAddr; + +use hyper::net; + +static README: &'static [u8] = include_bytes!("../README.md"); + +struct MockStream { + read: Cursor<Vec<u8>> +} + +impl MockStream { + fn new() -> MockStream { + let head = b"HTTP/1.1 200 OK\r\nServer: Mock\r\n\r\n"; + let mut res = head.to_vec(); + res.push_all(README); + MockStream { + read: Cursor::new(res) + } + } } -macro_rules! try_return( - ($e:expr) => {{ - match $e { - Ok(v) => v, - Err(..) => return +impl Clone for MockStream { + fn clone(&self) -> MockStream { + MockStream { + read: Cursor::new(self.read.get_ref().clone()) } - }} -); - -fn handle(_r: Request, res: Response) { - static BODY: &'static [u8] = b"Benchmarking hyper vs others!"; - let mut res = try_return!(res.start()); - try_return!(res.write_all(BODY)); - try_return!(res.end()); + } +} + +impl Read for MockStream { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.read.read(buf) + } +} + +impl Write for MockStream { + fn write(&mut self, msg: &[u8]) -> io::Result<usize> { + // we're mocking, what do we care. + Ok(msg.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } } #[derive(Clone)] diff --git a/benches/client.rs b/benches/client.rs --- a/benches/client.rs +++ b/benches/client.rs @@ -48,17 +68,36 @@ impl hyper::header::HeaderFormat for Foo { } } +impl net::NetworkStream for MockStream { + fn peer_addr(&mut self) -> io::Result<SocketAddr> { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + +struct MockConnector; + +impl net::NetworkConnector for MockConnector { + type Stream = MockStream; + fn connect(&mut self, _: &str, _: u16, _: &str) -> io::Result<MockStream> { + Ok(MockStream::new()) + } + +} + #[bench] -fn bench_hyper(b: &mut test::Bencher) { - let mut listening = listen(); - let s = format!("http://{}/", listening.socket); - let url = s.as_slice(); - let mut client = Client::new(); - let mut headers = Headers::new(); - headers.set(Foo); +fn bench_mock_hyper(b: &mut test::Bencher) { + let url = "http://127.0.0.1:1337/"; b.iter(|| { - client.get(url).header(Foo).send().unwrap().read_to_string().unwrap(); + let mut req = hyper::client::Request::with_connector( + hyper::Get, hyper::Url::parse(url).unwrap(), &mut MockConnector + ).unwrap(); + req.headers_mut().set(Foo); + + let mut s = String::new(); + req + .start().unwrap() + .send().unwrap() + .read_to_string(&mut s).unwrap() }); - listening.close().unwrap() } diff --git a/benches/client_mock_tcp.rs /dev/null --- a/benches/client_mock_tcp.rs +++ /dev/null @@ -1,98 +0,0 @@ -#![feature(collections, old_io, test)] -extern crate hyper; - -extern crate test; - -use std::fmt; -use std::old_io::{IoResult, MemReader}; -use std::old_io::net::ip::SocketAddr; - -use hyper::net; - -static README: &'static [u8] = include_bytes!("../README.md"); - - -struct MockStream { - read: MemReader, -} - -impl Clone for MockStream { - fn clone(&self) -> MockStream { - MockStream::new() - } -} - -impl MockStream { - fn new() -> MockStream { - let head = b"HTTP/1.1 200 OK\r\nServer: Mock\r\n\r\n"; - let mut res = head.to_vec(); - res.push_all(README); - MockStream { - read: MemReader::new(res), - } - } -} - -impl Reader for MockStream { - fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { - self.read.read(buf) - } -} - -impl Writer for MockStream { - fn write_all(&mut self, _msg: &[u8]) -> IoResult<()> { - // we're mocking, what do we care. - Ok(()) - } -} - -#[derive(Clone)] -struct Foo; - -impl hyper::header::Header for Foo { - fn header_name() -> &'static str { - "x-foo" - } - fn parse_header(_: &[Vec<u8>]) -> Option<Foo> { - None - } -} - -impl hyper::header::HeaderFormat for Foo { - fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.write_str("Bar") - } -} - -impl net::NetworkStream for MockStream { - fn peer_name(&mut self) -> IoResult<SocketAddr> { - Ok("127.0.0.1:1337".parse().unwrap()) - } -} - -struct MockConnector; - -impl net::NetworkConnector for MockConnector { - type Stream = MockStream; - fn connect(&mut self, _: &str, _: u16, _: &str) -> IoResult<MockStream> { - Ok(MockStream::new()) - } - -} - -#[bench] -fn bench_mock_hyper(b: &mut test::Bencher) { - let url = "http://127.0.0.1:1337/"; - b.iter(|| { - let mut req = hyper::client::Request::with_connector( - hyper::Get, hyper::Url::parse(url).unwrap(), &mut MockConnector - ).unwrap(); - req.headers_mut().set(Foo); - - req - .start().unwrap() - .send().unwrap() - .read_to_string().unwrap() - }); -} - diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -1,9 +1,10 @@ -#![feature(old_io, test)] +#![feature(io, net, test)] extern crate hyper; extern crate test; use test::Bencher; -use std::old_io::net::ip::Ipv4Addr; +use std::io::{Read, Write}; +use std::net::IpAddr; use hyper::method::Method::Get; use hyper::server::{Request, Response}; diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -191,8 +191,8 @@ mod tests { ).unwrap(); let req = req.start().unwrap(); let stream = *req.body.end().unwrap() - .into_inner().downcast::<MockStream>().ok().unwrap(); - let bytes = stream.write.into_inner(); + .into_inner().unwrap().downcast::<MockStream>().ok().unwrap(); + let bytes = stream.write; let s = from_utf8(&bytes[..]).unwrap(); assert!(!s.contains("Content-Length:")); assert!(!s.contains("Transfer-Encoding:")); diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -205,8 +205,8 @@ mod tests { ).unwrap(); let req = req.start().unwrap(); let stream = *req.body.end().unwrap() - .into_inner().downcast::<MockStream>().ok().unwrap(); - let bytes = stream.write.into_inner(); + .into_inner().unwrap().downcast::<MockStream>().ok().unwrap(); + let bytes = stream.write; let s = from_utf8(&bytes[..]).unwrap(); assert!(!s.contains("Content-Length:")); assert!(!s.contains("Transfer-Encoding:")); diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -104,7 +104,7 @@ impl Reader for Response { mod tests { use std::borrow::Cow::Borrowed; use std::boxed::BoxAny; - use std::old_io::BufferedReader; + use std::io::{self, Read, BufReader}; use std::marker::PhantomData; use header::Headers; diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -119,14 +119,20 @@ mod tests { use super::Response; + fn read_to_string(mut r: Response) -> io::Result<String> { + let mut s = String::new(); + try!(r.read_to_string(&mut s)); + Ok(s) + } + #[test] - fn test_unwrap() { + fn test_into_inner() { let res = Response { status: status::StatusCode::Ok, headers: Headers::new(), version: version::HttpVersion::Http11, - body: EofReader(BufferedReader::new(box MockStream::new() as Box<NetworkStream + Send>)), + body: EofReader(BufReader::new(box MockStream::new() as Box<NetworkStream + Send>)), status_raw: RawStatus(200, Borrowed("OK")), _marker: PhantomData, }; diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -152,7 +158,7 @@ mod tests { \r\n" ); - let mut res = Response::new(box stream).unwrap(); + let res = Response::new(box stream).unwrap(); // The status line is correct? assert_eq!(res.status, status::StatusCode::Ok); diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -166,8 +172,7 @@ mod tests { None => panic!("Transfer-Encoding: chunked expected!"), }; // The body is correct? - let body = res.read_to_string().unwrap(); - assert_eq!("qwert", body); + assert_eq!(read_to_string(res), Ok("qwert".to_string())); } /// Tests that when a chunk size is not a valid radix-16 number, an error diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -184,9 +189,9 @@ mod tests { \r\n" ); - let mut res = Response::new(box stream).unwrap(); + let res = Response::new(box stream).unwrap(); - assert!(res.read_to_string().is_err()); + assert!(read_to_string(res).is_err()); } /// Tests that when a chunk size contains an invalid extension, an error is diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -203,9 +208,9 @@ mod tests { \r\n" ); - let mut res = Response::new(box stream).unwrap(); + let res = Response::new(box stream).unwrap(); - assert!(res.read_to_string().is_err()); + assert!(read_to_string(res).is_err()); } /// Tests that when a valid extension that contains a digit is appended to diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -222,8 +227,8 @@ mod tests { \r\n" ); - let mut res = Response::new(box stream).unwrap(); + let res = Response::new(box stream).unwrap(); - assert_eq!("1", res.read_to_string().unwrap()) + assert_eq!(read_to_string(res), Ok("1".to_string())); } } diff --git a/src/header/common/accept_language.rs b/src/header/common/accept_language.rs --- a/src/header/common/accept_language.rs +++ b/src/header/common/accept_language.rs @@ -49,7 +49,6 @@ impl_list_header!(AcceptLanguage, #[cfg(test)] mod tests { use header::{Header, qitem, Quality, QualityItem}; - use super::*; #[test] diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -142,14 +142,9 @@ impl FromStr for Basic { #[cfg(test)] mod tests { - use std::old_io::MemReader; use super::{Authorization, Basic}; use super::super::super::{Headers}; - fn mem(s: &str) -> MemReader { - MemReader::new(s.as_bytes().to_vec()) - } - #[test] fn test_raw_auth() { let mut headers = Headers::new(); diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -159,7 +154,7 @@ mod tests { #[test] fn test_raw_auth_parse() { - let headers = Headers::from_raw(&mut mem("Authorization: foo bar baz\r\n\r\n")).unwrap(); + let headers = Headers::from_raw(&mut b"Authorization: foo bar baz\r\n\r\n").unwrap(); assert_eq!(&headers.get::<Authorization<String>>().unwrap().0[..], "foo bar baz"); } diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -179,7 +174,7 @@ mod tests { #[test] fn test_basic_auth_parse() { - let headers = Headers::from_raw(&mut mem("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n\r\n")).unwrap(); + let headers = Headers::from_raw(&mut b"Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n\r\n").unwrap(); let auth = headers.get::<Authorization<Basic>>().unwrap(); assert_eq!(&auth.0.username[..], "Aladdin"); assert_eq!(auth.0.password, Some("open sesame".to_string())); diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -187,7 +182,7 @@ mod tests { #[test] fn test_basic_auth_parse_no_password() { - let headers = Headers::from_raw(&mut mem("Authorization: Basic QWxhZGRpbjo=\r\n\r\n")).unwrap(); + let headers = Headers::from_raw(&mut b"Authorization: Basic QWxhZGRpbjo=\r\n\r\n").unwrap(); let auth = headers.get::<Authorization<Basic>>().unwrap(); assert_eq!(auth.0.username.as_slice(), "Aladdin"); assert_eq!(auth.0.password, Some("".to_string())); diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -534,7 +535,6 @@ impl<'a, H: HeaderFormat> fmt::Debug for HeaderFormatter<'a, H> { #[cfg(test)] mod tests { - use std::old_io::MemReader; use std::fmt; use mime::Mime; use mime::TopLevel::Text; diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -544,13 +544,9 @@ mod tests { use test::Bencher; - fn mem(s: &str) -> MemReader { - MemReader::new(s.as_bytes().to_vec()) - } - #[test] fn test_from_raw() { - let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap(); + let headers = Headers::from_raw(&mut b"Content-Length: 10\r\n\r\n").unwrap(); assert_eq!(headers.get(), Some(&ContentLength(10))); } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -603,21 +599,21 @@ mod tests { #[test] fn test_different_structs_for_same_header() { - let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap(); + let headers = Headers::from_raw(&mut b"Content-Length: 10\r\n\r\n").unwrap(); let ContentLength(_) = *headers.get::<ContentLength>().unwrap(); assert!(headers.get::<CrazyLength>().is_none()); } #[test] fn test_trailing_whitespace() { - let headers = Headers::from_raw(&mut mem("Content-Length: 10 \r\n\r\n")).unwrap(); + let headers = Headers::from_raw(&mut b"Content-Length: 10 \r\n\r\n").unwrap(); let ContentLength(_) = *headers.get::<ContentLength>().unwrap(); assert!(headers.get::<CrazyLength>().is_none()); } #[test] fn test_multiple_reads() { - let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap(); + let headers = Headers::from_raw(&mut b"Content-Length: 10\r\n\r\n").unwrap(); let ContentLength(one) = *headers.get::<ContentLength>().unwrap(); let ContentLength(two) = *headers.get::<ContentLength>().unwrap(); assert_eq!(one, two); diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -625,14 +621,14 @@ mod tests { #[test] fn test_different_reads() { - let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\nContent-Type: text/plain\r\n\r\n")).unwrap(); + let headers = Headers::from_raw(&mut b"Content-Length: 10\r\nContent-Type: text/plain\r\n\r\n").unwrap(); let ContentLength(_) = *headers.get::<ContentLength>().unwrap(); let ContentType(_) = *headers.get::<ContentType>().unwrap(); } #[test] fn test_get_mutable() { - let mut headers = Headers::from_raw(&mut mem("Content-Length: 10\r\nContent-Type: text/plain\r\n\r\n")).unwrap(); + let mut headers = Headers::from_raw(&mut b"Content-Length: 10\r\nContent-Type: text/plain\r\n\r\n").unwrap(); *headers.get_mut::<ContentLength>().unwrap() = ContentLength(20); assert_eq!(*headers.get::<ContentLength>().unwrap(), ContentLength(20)); } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -653,7 +649,7 @@ mod tests { #[test] fn test_headers_show_raw() { - let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap(); + let headers = Headers::from_raw(&mut b"Content-Length: 10\r\n\r\n").unwrap(); let s = headers.to_string(); assert_eq!(s, "Content-Length: 10\r\n"); } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -720,7 +716,7 @@ mod tests { #[bench] fn bench_headers_from_raw(b: &mut Bencher) { - b.iter(|| Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap()) + b.iter(|| Headers::from_raw(&mut b"Content-Length: 10\r\n\r\n").unwrap()) } #[bench] diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -686,39 +767,34 @@ pub fn read_status<R: Reader>(stream: &mut R) -> HttpResult<RawStatus> { } #[inline] -fn expect(r: IoResult<u8>, expected: u8) -> HttpResult<()> { - match r { - Ok(b) if b == expected => Ok(()), - Ok(_) => Err(HttpVersionError), - Err(e) => Err(HttpIoError(e)) +fn expect(actual: u8, expected: u8) -> HttpResult<()> { + if actual == expected { + Ok(()) + } else { + Err(HttpVersionError) } } #[cfg(test)] mod tests { - use std::old_io::{self, MemReader, MemWriter, IoResult}; + use std::io::{self, Write}; use std::borrow::Cow::{Borrowed, Owned}; use test::Bencher; use uri::RequestUri; use uri::RequestUri::{Star, AbsoluteUri, AbsolutePath, Authority}; use method; use version::HttpVersion; - use version::HttpVersion::{Http10, Http11, Http20}; + use version::HttpVersion::{Http10, Http11}; use HttpError::{HttpVersionError, HttpMethodError}; use HttpResult; use url::Url; use super::{read_method, read_uri, read_http_version, read_header, RawHeaderLine, read_status, RawStatus, read_chunk_size}; - - fn mem(s: &str) -> MemReader { - MemReader::new(s.as_bytes().to_vec()) - } - #[test] fn test_read_method() { fn read(s: &str, result: HttpResult<method::Method>) { - assert_eq!(read_method(&mut mem(s)), result); + assert_eq!(read_method(&mut s.as_bytes()), result); } read("GET /", Ok(method::Method::Get)); diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -737,7 +813,7 @@ mod tests { #[test] fn test_read_uri() { fn read(s: &str, result: HttpResult<RequestUri>) { - assert_eq!(read_uri(&mut mem(s)), result); + assert_eq!(read_uri(&mut s.as_bytes()), result); } read("* ", Ok(Star)); diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -749,12 +825,11 @@ mod tests { #[test] fn test_read_http_version() { fn read(s: &str, result: HttpResult<HttpVersion>) { - assert_eq!(read_http_version(&mut mem(s)), result); + assert_eq!(read_http_version(&mut s.as_bytes()), result); } read("HTTP/1.0", Ok(Http10)); read("HTTP/1.1", Ok(Http11)); - read("HTTP/2.0", Ok(Http20)); read("HTP/2.0", Err(HttpVersionError)); read("HTTP.2.0", Err(HttpVersionError)); read("HTTP 2.0", Err(HttpVersionError)); diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -764,11 +839,11 @@ mod tests { #[test] fn test_read_status() { fn read(s: &str, result: HttpResult<RawStatus>) { - assert_eq!(read_status(&mut mem(s)), result); + assert_eq!(read_status(&mut s.as_bytes()), result); } fn read_ignore_string(s: &str, result: HttpResult<RawStatus>) { - match (read_status(&mut mem(s)), result) { + match (read_status(&mut s.as_bytes()), result) { (Ok(RawStatus(ref c1, _)), Ok(RawStatus(ref c2, _))) => { assert_eq!(c1, c2); }, diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -788,7 +863,7 @@ mod tests { #[test] fn test_read_header() { fn read(s: &str, result: HttpResult<Option<RawHeaderLine>>) { - assert_eq!(read_header(&mut mem(s)), result); + assert_eq!(read_header(&mut s.as_bytes()), result); } read("Host: rust-lang.org\r\n", Ok(Some(("Host".to_string(), diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -798,10 +873,10 @@ mod tests { #[test] fn test_write_chunked() { use std::str::from_utf8; - let mut w = super::HttpWriter::ChunkedWriter(MemWriter::new()); + let mut w = super::HttpWriter::ChunkedWriter(Vec::new()); w.write_all(b"foo bar").unwrap(); w.write_all(b"baz quux herp").unwrap(); - let buf = w.end().unwrap().into_inner(); + let buf = w.end().unwrap(); let s = from_utf8(buf.as_slice()).unwrap(); assert_eq!(s, "7\r\nfoo bar\r\nD\r\nbaz quux herp\r\n0\r\n\r\n"); } diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -809,19 +884,23 @@ mod tests { #[test] fn test_write_sized() { use std::str::from_utf8; - let mut w = super::HttpWriter::SizedWriter(MemWriter::new(), 8); + let mut w = super::HttpWriter::SizedWriter(Vec::new(), 8); w.write_all(b"foo bar").unwrap(); - assert_eq!(w.write_all(b"baz"), Err(old_io::standard_error(old_io::ShortWrite(1)))); + assert_eq!(w.write(b"baz"), Ok(1)); - let buf = w.end().unwrap().into_inner(); + let buf = w.end().unwrap(); let s = from_utf8(buf.as_slice()).unwrap(); assert_eq!(s, "foo barb"); } #[test] fn test_read_chunk_size() { - fn read(s: &str, result: IoResult<u64>) { - assert_eq!(read_chunk_size(&mut mem(s)), result); + fn read(s: &str, result: io::Result<u64>) { + assert_eq!(read_chunk_size(&mut s.as_bytes()), result); + } + + fn read_err(s: &str) { + assert_eq!(read_chunk_size(&mut s.as_bytes()).unwrap_err().kind(), io::ErrorKind::InvalidInput); } read("1\r\n", Ok(1)); diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -833,13 +912,13 @@ mod tests { read("Ff\r\n", Ok(255)); read("Ff \r\n", Ok(255)); // Missing LF or CRLF - read("F\rF", Err(old_io::standard_error(old_io::InvalidInput))); - read("F", Err(old_io::standard_error(old_io::EndOfFile))); + read_err("F\rF"); + read_err("F"); // Invalid hex digit - read("X\r\n", Err(old_io::standard_error(old_io::InvalidInput))); - read("1X\r\n", Err(old_io::standard_error(old_io::InvalidInput))); - read("-\r\n", Err(old_io::standard_error(old_io::InvalidInput))); - read("-1\r\n", Err(old_io::standard_error(old_io::InvalidInput))); + read_err("X\r\n"); + read_err("1X\r\n"); + read_err("-\r\n"); + read_err("-1\r\n"); // Acceptable (if not fully valid) extensions do not influence the size read("1;extension\r\n", Ok(1)); read("a;ext name=value\r\n", Ok(10)); diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -850,21 +929,21 @@ mod tests { read("3 ;\r\n", Ok(3)); read("3 ; \r\n", Ok(3)); // Invalid extensions cause an error - read("1 invalid extension\r\n", Err(old_io::standard_error(old_io::InvalidInput))); - read("1 A\r\n", Err(old_io::standard_error(old_io::InvalidInput))); - read("1;no CRLF", Err(old_io::standard_error(old_io::EndOfFile))); + read_err("1 invalid extension\r\n"); + read_err("1 A\r\n"); + read_err("1;no CRLF"); } #[bench] fn bench_read_method(b: &mut Bencher) { b.bytes = b"CONNECT ".len() as u64; - b.iter(|| assert_eq!(read_method(&mut mem("CONNECT ")), Ok(method::Method::Connect))); + b.iter(|| assert_eq!(read_method(&mut b"CONNECT "), Ok(method::Method::Connect))); } #[bench] fn bench_read_status(b: &mut Bencher) { b.bytes = b"404 Not Found\r\n".len() as u64; - b.iter(|| assert_eq!(read_status(&mut mem("404 Not Found\r\n")), Ok(RawStatus(404, Borrowed("Not Found"))))); + b.iter(|| assert_eq!(read_status(&mut b"404 Not Found\r\n"), Ok(RawStatus(404, Borrowed("Not Found"))))); } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,6 @@ -#![feature(core, collections, io, old_io, os, old_path, +#![feature(core, collections, io, net, os, path, std_misc, box_syntax, unsafe_destructor)] -#![deny(missing_docs)] +#![cfg_attr(test, deny(missing_docs))] #![cfg_attr(test, deny(warnings))] #![cfg_attr(test, feature(alloc, test))] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -140,7 +140,7 @@ extern crate log; #[cfg(test)] extern crate test; -pub use std::old_io::net::ip::{SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr, Port}; + pub use mimewrapper::mime; pub use url::Url; pub use client::Client; diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -84,12 +84,19 @@ mod tests { use mock::MockStream; use super::Request; - use std::old_io::net::ip::SocketAddr; + use std::io::{self, Read}; + use std::net::SocketAddr; fn sock(s: &str) -> SocketAddr { s.parse().unwrap() } + fn read_to_string(mut req: Request) -> io::Result<String> { + let mut s = String::new(); + try!(req.read_to_string(&mut s)); + Ok(s) + } + #[test] fn test_get_empty_body() { let mut stream = MockStream::with_input(b"\ diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -99,8 +106,8 @@ mod tests { I'm a bad request.\r\n\ "); - let mut req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); - assert_eq!(req.read_to_string(), Ok("".to_string())); + let req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); + assert_eq!(read_to_string(req), Ok("".to_string())); } #[test] diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -112,8 +119,8 @@ mod tests { I'm a bad request.\r\n\ "); - let mut req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); - assert_eq!(req.read_to_string(), Ok("".to_string())); + let req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); + assert_eq!(read_to_string(req), Ok("".to_string())); } #[test] diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -125,8 +132,8 @@ mod tests { I'm a bad request.\r\n\ "); - let mut req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); - assert_eq!(req.read_to_string(), Ok("".to_string())); + let req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); + assert_eq!(read_to_string(req), Ok("".to_string())); } #[test] diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -146,7 +153,7 @@ mod tests { \r\n" ); - let mut req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); + let req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); // The headers are correct? match req.headers.get::<Host>() { diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -163,8 +170,7 @@ mod tests { None => panic!("Transfer-Encoding: chunked expected!"), }; // The content is correctly read? - let body = req.read_to_string().unwrap(); - assert_eq!("qwert", body); + assert_eq!(read_to_string(req), Ok("qwert".to_string())); } /// Tests that when a chunk size is not a valid radix-16 number, an error diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -182,9 +188,9 @@ mod tests { \r\n" ); - let mut req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); + let req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); - assert!(req.read_to_string().is_err()); + assert!(read_to_string(req).is_err()); } /// Tests that when a chunk size contains an invalid extension, an error is diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -202,9 +208,9 @@ mod tests { \r\n" ); - let mut req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); + let req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); - assert!(req.read_to_string().is_err()); + assert!(read_to_string(req).is_err()); } /// Tests that when a valid extension that contains a digit is appended to diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -222,9 +228,9 @@ mod tests { \r\n" ); - let mut req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); + let req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); - assert_eq!("1", req.read_to_string().unwrap()) + assert_eq!(read_to_string(req), Ok("1".to_string())); } }
Switch to new std::io Installed Rust nightly build, after not using Rust for 3 weeks. Hyper won't compile any more. The I/O libraries changed. Again. Not your fault. Sigh. ``` Compiling hyper v0.2.1 /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:215:25: 215:29 error: mismatched types: expected `&std::path::Path`, found `&std::old_path::posix::Path` (expected struct `std::path::Path`, found struct `std::old_path::posix::Path`) [E0308] /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:215 cert, X509FileType::PEM).map(lift_ssl_error)); ^~~~ /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:19:1: 24:2 note: in expansion of try_some! /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:214:17: 215:71 note: expansion site /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:217:25: 217:28 error: mismatched types: expected `&std::path::Path`, found `&std::old_path::posix::Path` (expected struct `std::path::Path`, found struct `std::old_path::posix::Path`) [E0308] /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:217 key, X509FileType::PEM).map(lift_ssl_error)); ^~~ /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:19:1: 24:2 note: in expansion of try_some! /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:216:17: 217:70 note: expansion site /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:243:23: 243:57 error: the trait `std::io::Read` is not implemented for the type `std::old_io::net::tcp::TcpStream` [E0277] /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:243 match SslStream::<TcpStream>::new_server(&**ssl_context, stream) { ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:243:23: 243:57 error: the trait `std::io::Write` is not implemented for the type `std::old_io::net::tcp::TcpStream` [E0277] /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:243 match SslStream::<TcpStream>::new_server(&**ssl_context, stream) { ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:249:42: 249:48 error: attempted access of field `desc` on type `&std::io::error::Error`, but no field with that name was found /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:249 detail: Some(e.desc.to_string()) ^~~~~~ /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:289:55: 289:64 error: type `&mut openssl::ssl::SslStream<std::old_io::net::tcp::TcpStream>` does not implement any method in scope named `read` /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:289 HttpStream::Https(ref mut inner) => inner.read(buf) ^~~~~~~~~ /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:299:55: 299:69 error: type `&mut openssl::ssl::SslStream<std::old_io::net::tcp::TcpStream>` does not implement any method in scope named `write_all` /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:299 HttpStream::Https(ref mut inner) => inner.write_all(msg) ^~~~~~~~~~~~~~ /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:306:55: 306:62 error: type `&mut openssl::ssl::SslStream<std::old_io::net::tcp::TcpStream>` does not implement any method in scope named `flush` /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:306 HttpStream::Https(ref mut inner) => inner.flush(), ^~~~~~~ /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:315:55: 315:64 error: type `&mut openssl::ssl::SslStream<std::old_io::net::tcp::TcpStream>` does not implement any method in scope named `get_mut` /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:315 HttpStream::Https(ref mut inner) => inner.get_mut().peer_name() ^~~~~~~~~ /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:346:35: 346:49 error: the trait `std::io::Read` is not implemented for the type `std::old_io::net::tcp::TcpStream` [E0277] /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:346 let stream = try!(SslStream::new(&context, stream).map_err(lift_ssl_error)); ^~~~~~~~~~~~~~ <std macros>:1:1: 6:57 note: in expansion of try! /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:346:30: 346:93 note: expansion site /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:346:35: 346:49 error: the trait `std::io::Write` is not implemented for the type `std::old_io::net::tcp::TcpStream` [E0277] /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:346 let stream = try!(SslStream::new(&context, stream).map_err(lift_ssl_error)); ^~~~~~~~~~~~~~ <std macros>:1:1: 6:57 note: in expansion of try! /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:346:30: 346:93 note: expansion site /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:363:29: 363:32 error: mismatched types: expected `std::old_io::IoError`, found `std::io::error::Error` (expected struct `std::old_io::IoError`, found struct `std::io::error::Error`) [E0308] /home/john/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.2.1/src/net.rs:363 StreamError(err) => err, ^~~ error: aborting due to 12 previous errors Could not compile `hyper`. ```
2015-03-01T03:23:46Z
0.2
7235d3f74a6f058a9bedc840519be80384e292da
hyperium/hyper
331
hyperium__hyper-331
[ "326" ]
41fd8de243dc1183b994d46a9624b1ee6c2dcdd2
diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -206,6 +206,11 @@ impl Headers { self.data.insert(UniCase(name.into_cow()), Item::new_raw(value)); } + /// Remove a header set by set_raw + pub fn remove_raw(&mut self, name: &str) { + self.data.remove(&UniCase(name.into_cow())); + } + /// Get a reference to the header field's value, if it exists. pub fn get<H: Header + HeaderFormat>(&self) -> Option<&H> { self.get_or_parse::<H>().map(|item| {
diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -662,6 +667,14 @@ mod tests { assert_eq!(headers.get(), Some(&ContentLength(20))); } + #[test] + fn test_remove_raw() { + let mut headers = Headers::new(); + headers.set_raw("content-LENGTH", vec![b"20".to_vec()]); + headers.remove_raw("content-LENGTH"); + assert_eq!(headers.get_raw("Content-length"), None); + } + #[test] fn test_len() { let mut headers = Headers::new();
Removing a raw header Currently, I can insert or overwrite a header by doing, for example: ``` request_headers.set_raw("Accept-Encoding", vec![b"gzip, deflate".to_vec()]); ``` But apparently, I cannot remove it, only set it to a different value. Wouldn't it be useful to add a remove_raw() method to Headers? Raw headers are very useful if you don't know what headers to send at compile time, for example, or for quick prototyping.
Good call, this would be needed to support XHR's `removeHeader` method.
2015-02-22T12:24:43Z
0.2
7235d3f74a6f058a9bedc840519be80384e292da
hyperium/hyper
329
hyperium__hyper-329
[ "328" ]
e8833c0c894a2b87b5d9b48b07858ec7fc890b7a
diff --git a/examples/client.rs b/examples/client.rs --- a/examples/client.rs +++ b/examples/client.rs @@ -1,4 +1,4 @@ -#![feature(env, io)] +#![feature(env, old_io)] extern crate hyper; use std::env; diff --git a/examples/hello.rs b/examples/hello.rs --- a/examples/hello.rs +++ b/examples/hello.rs @@ -1,4 +1,4 @@ -#![feature(io)] +#![feature(old_io)] extern crate hyper; use std::old_io::net::ip::Ipv4Addr; diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -1,4 +1,4 @@ -#![feature(io)] +#![feature(old_io)] extern crate hyper; #[macro_use] extern crate log; diff --git a/examples/server.rs b/examples/server.rs --- a/examples/server.rs +++ b/examples/server.rs @@ -21,7 +21,7 @@ macro_rules! try_return( fn echo(mut req: Request, mut res: Response) { match req.uri { - AbsolutePath(ref path) => match (&req.method, &path[]) { + AbsolutePath(ref path) => match (&req.method, &path[..]) { (&Get, "/") | (&Get, "/echo") => { let out = b"Try POST /echo"; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -197,7 +197,7 @@ impl<'a, U: IntoUrl, C: NetworkConnector> RequestBuilder<'a, U, C> { // punching borrowck here let loc = match res.headers.get::<Location>() { Some(&Location(ref loc)) => { - Some(UrlParser::new().base_url(&url).parse(&loc[])) + Some(UrlParser::new().base_url(&url).parse(&loc[..])) } None => { debug!("no Location header"); diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -1,5 +1,6 @@ //! Client Requests use std::old_io::{BufferedWriter, IoResult}; +use std::marker::PhantomData; use url::Url; diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -25,8 +26,13 @@ pub struct Request<W> { body: HttpWriter<BufferedWriter<Box<NetworkStream + Send>>>, headers: Headers, method: method::Method, + + _marker: PhantomData<W>, } +//FIXME: remove once https://github.com/rust-lang/issues/22629 is fixed +unsafe impl<W> Send for Request<W> {} + impl<W> Request<W> { /// Read the Request headers. #[inline] diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -66,7 +72,8 @@ impl Request<Fresh> { headers: headers, url: url, version: version::HttpVersion::Http11, - body: stream + body: stream, + _marker: PhantomData, }) } diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -136,7 +143,8 @@ impl Request<Fresh> { headers: self.headers, url: self.url, version: self.version, - body: stream + body: stream, + _marker: PhantomData, }) } diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -1,6 +1,7 @@ //! Client Responses use std::num::FromPrimitive; use std::old_io::{BufferedReader, IoResult}; +use std::marker::PhantomData; use header; use header::{ContentLength, TransferEncoding}; diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -23,8 +24,13 @@ pub struct Response<S = HttpStream> { pub version: version::HttpVersion, status_raw: RawStatus, body: HttpReader<BufferedReader<Box<NetworkStream + Send>>>, + + _marker: PhantomData<S>, } +//FIXME: remove once https://github.com/rust-lang/issues/22629 is fixed +unsafe impl<S: Send> Send for Response<S> {} + impl Response { /// Creates a new response from a server. diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -72,6 +78,7 @@ impl Response { headers: headers, body: body, status_raw: raw_status, + _marker: PhantomData, }) } diff --git a/src/header/common/access_control/allow_origin.rs b/src/header/common/access_control/allow_origin.rs --- a/src/header/common/access_control/allow_origin.rs +++ b/src/header/common/access_control/allow_origin.rs @@ -29,7 +29,7 @@ impl header::Header for AccessControlAllowOrigin { fn parse_header(raw: &[Vec<u8>]) -> Option<AccessControlAllowOrigin> { if raw.len() == 1 { - match str::from_utf8(unsafe { &raw[].get_unchecked(0)[] }) { + match str::from_utf8(unsafe { &raw.get_unchecked(0)[..] }) { Ok(s) => { if s == "*" { Some(AccessControlAllowOrigin::AllowStar) diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -22,14 +22,14 @@ impl<S: Scheme> DerefMut for Authorization<S> { } } -impl<S: Scheme> Header for Authorization<S> { +impl<S: Scheme + 'static> Header for Authorization<S> where <S as FromStr>::Err: 'static { fn header_name() -> &'static str { "Authorization" } fn parse_header(raw: &[Vec<u8>]) -> Option<Authorization<S>> { if raw.len() == 1 { - match (from_utf8(unsafe { &raw[].get_unchecked(0)[] }), Scheme::scheme(None::<S>)) { + match (from_utf8(unsafe { &raw.get_unchecked(0)[..] }), Scheme::scheme(None::<S>)) { (Ok(header), Some(scheme)) if header.starts_with(scheme) && header.len() > scheme.len() + 1 => { header[scheme.len() + 1..].parse::<S>().map(|s| Authorization(s)).ok() diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -43,7 +43,7 @@ impl<S: Scheme> Header for Authorization<S> { } } -impl<S: Scheme> HeaderFormat for Authorization<S> { +impl<S: Scheme + 'static> HeaderFormat for Authorization<S> where <S as FromStr>::Err: 'static { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match Scheme::scheme(None::<S>) { Some(scheme) => try!(write!(fmt, "{} ", scheme)), diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -96,7 +96,7 @@ impl Scheme for Basic { let mut text = self.username.clone(); text.push(':'); if let Some(ref pass) = self.password { - text.push_str(&pass[]); + text.push_str(&pass[..]); } write!(f, "{}", text.as_bytes().to_base64(Config { char_set: Standard, diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -113,7 +113,7 @@ impl FromStr for Basic { match s.from_base64() { Ok(decoded) => match String::from_utf8(decoded) { Ok(text) => { - let mut parts = &mut text[].split(':'); + let mut parts = &mut text.split(':'); let user = match parts.next() { Some(part) => part.to_string(), None => return Err(()) diff --git a/src/header/common/cache_control.rs b/src/header/common/cache_control.rs --- a/src/header/common/cache_control.rs +++ b/src/header/common/cache_control.rs @@ -16,7 +16,7 @@ impl Header for CacheControl { fn parse_header(raw: &[Vec<u8>]) -> Option<CacheControl> { let directives = raw.iter() - .filter_map(|line| from_one_comma_delimited(&line[])) + .filter_map(|line| from_one_comma_delimited(&line[..])) .collect::<Vec<Vec<CacheDirective>>>() .concat(); if directives.len() > 0 { diff --git a/src/header/common/cache_control.rs b/src/header/common/cache_control.rs --- a/src/header/common/cache_control.rs +++ b/src/header/common/cache_control.rs @@ -29,7 +29,7 @@ impl Header for CacheControl { impl HeaderFormat for CacheControl { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt_comma_delimited(fmt, &self[]) + fmt_comma_delimited(fmt, &self[..]) } } diff --git a/src/header/common/cache_control.rs b/src/header/common/cache_control.rs --- a/src/header/common/cache_control.rs +++ b/src/header/common/cache_control.rs @@ -88,7 +88,7 @@ impl fmt::Display for CacheDirective { ProxyRevalidate => "proxy-revalidate", SMaxAge(secs) => return write!(f, "s-maxage={}", secs), - Extension(ref name, None) => &name[], + Extension(ref name, None) => &name[..], Extension(ref name, Some(ref arg)) => return write!(f, "{}={}", name, arg), }, f) diff --git a/src/header/common/connection.rs b/src/header/common/connection.rs --- a/src/header/common/connection.rs +++ b/src/header/common/connection.rs @@ -64,7 +64,7 @@ impl Header for Connection { impl HeaderFormat for Connection { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let Connection(ref parts) = *self; - fmt_comma_delimited(fmt, &parts[]) + fmt_comma_delimited(fmt, &parts[..]) } } diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -26,7 +26,7 @@ impl Header for Cookie { fn parse_header(raw: &[Vec<u8>]) -> Option<Cookie> { let mut cookies = Vec::with_capacity(raw.len()); for cookies_raw in raw.iter() { - match from_utf8(&cookies_raw[]) { + match from_utf8(&cookies_raw[..]) { Ok(cookies_str) => { for cookie_str in cookies_str.split(';') { match cookie_str.trim().parse() { diff --git a/src/header/common/host.rs b/src/header/common/host.rs --- a/src/header/common/host.rs +++ b/src/header/common/host.rs @@ -28,7 +28,7 @@ impl Header for Host { // FIXME: use rust-url to parse this // https://github.com/servo/rust-url/issues/42 let idx = { - let slice = &s[]; + let slice = &s[..]; if slice.char_at(1) == '[' { match slice.rfind(']') { Some(idx) => { diff --git a/src/header/common/if_match.rs b/src/header/common/if_match.rs --- a/src/header/common/if_match.rs +++ b/src/header/common/if_match.rs @@ -25,7 +25,7 @@ impl Header for IfMatch { fn parse_header(raw: &[Vec<u8>]) -> Option<IfMatch> { from_one_raw_str(raw).and_then(|s: String| { - let slice = &s[]; + let slice = &s[..]; match slice { "" => None, "*" => Some(IfMatch::Any), diff --git a/src/header/common/if_match.rs b/src/header/common/if_match.rs --- a/src/header/common/if_match.rs +++ b/src/header/common/if_match.rs @@ -39,7 +39,7 @@ impl HeaderFormat for IfMatch { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { IfMatch::Any => write!(fmt, "*"), - IfMatch::EntityTags(ref fields) => fmt_comma_delimited(fmt, &fields[]) + IfMatch::EntityTags(ref fields) => fmt_comma_delimited(fmt, &fields[..]) } } } diff --git a/src/header/common/if_none_match.rs b/src/header/common/if_none_match.rs --- a/src/header/common/if_none_match.rs +++ b/src/header/common/if_none_match.rs @@ -33,7 +33,7 @@ impl Header for IfNoneMatch { fn parse_header(raw: &[Vec<u8>]) -> Option<IfNoneMatch> { from_one_raw_str(raw).and_then(|s: String| { - let slice = &s[]; + let slice = &s[..]; match slice { "" => None, "*" => Some(IfNoneMatch::Any), diff --git a/src/header/common/if_none_match.rs b/src/header/common/if_none_match.rs --- a/src/header/common/if_none_match.rs +++ b/src/header/common/if_none_match.rs @@ -47,7 +47,7 @@ impl HeaderFormat for IfNoneMatch { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { IfNoneMatch::Any => { write!(fmt, "*") } - IfNoneMatch::EntityTags(ref fields) => { fmt_comma_delimited(fmt, &fields[]) } + IfNoneMatch::EntityTags(ref fields) => { fmt_comma_delimited(fmt, &fields[..]) } } } } diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -50,13 +50,13 @@ macro_rules! bench_header( fn bench_parse(b: &mut Bencher) { let val = $value; b.iter(|| { - let _: $ty = Header::parse_header(&val[]).unwrap(); + let _: $ty = Header::parse_header(&val[..]).unwrap(); }); } #[bench] fn bench_format(b: &mut Bencher) { - let val: $ty = Header::parse_header(&$value[]).unwrap(); + let val: $ty = Header::parse_header(&$value[..]).unwrap(); let fmt = HeaderFormatter(&val); b.iter(|| { format!("{}", fmt); diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -102,7 +102,7 @@ macro_rules! impl_list_header( impl $crate::header::HeaderFormat for $from { fn fmt_header(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - $crate::header::parsing::fmt_comma_delimited(fmt, &self[]) + $crate::header::parsing::fmt_comma_delimited(fmt, &self[..]) } } diff --git a/src/header/common/pragma.rs b/src/header/common/pragma.rs --- a/src/header/common/pragma.rs +++ b/src/header/common/pragma.rs @@ -31,7 +31,7 @@ impl Header for Pragma { fn parse_header(raw: &[Vec<u8>]) -> Option<Pragma> { parsing::from_one_raw_str(raw).and_then(|s: String| { - let slice = &s.to_ascii_lowercase()[]; + let slice = &s.to_ascii_lowercase()[..]; match slice { "" => None, "no-cache" => Some(Pragma::NoCache), diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs --- a/src/header/common/set_cookie.rs +++ b/src/header/common/set_cookie.rs @@ -23,7 +23,7 @@ impl Header for SetCookie { fn parse_header(raw: &[Vec<u8>]) -> Option<SetCookie> { let mut set_cookies = Vec::with_capacity(raw.len()); for set_cookies_raw in raw.iter() { - match from_utf8(&set_cookies_raw[]) { + match from_utf8(&set_cookies_raw[..]) { Ok(s) if !s.is_empty() => { match s.parse() { Ok(cookie) => set_cookies.push(cookie), diff --git a/src/header/common/upgrade.rs b/src/header/common/upgrade.rs --- a/src/header/common/upgrade.rs +++ b/src/header/common/upgrade.rs @@ -55,7 +55,7 @@ impl Header for Upgrade { impl HeaderFormat for Upgrade { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let Upgrade(ref parts) = *self; - fmt_comma_delimited(fmt, &parts[]) + fmt_comma_delimited(fmt, &parts[..]) } } diff --git a/src/header/common/vary.rs b/src/header/common/vary.rs --- a/src/header/common/vary.rs +++ b/src/header/common/vary.rs @@ -21,7 +21,7 @@ impl Header for Vary { fn parse_header(raw: &[Vec<u8>]) -> Option<Vary> { from_one_raw_str(raw).and_then(|s: String| { - let slice = &s[]; + let slice = &s[..]; match slice { "" => None, "*" => Some(Vary::Any), diff --git a/src/header/common/vary.rs b/src/header/common/vary.rs --- a/src/header/common/vary.rs +++ b/src/header/common/vary.rs @@ -35,7 +35,7 @@ impl HeaderFormat for Vary { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { Vary::Any => { write!(fmt, "*") } - Vary::Headers(ref fields) => { fmt_comma_delimited(fmt, &fields[]) } + Vary::Headers(ref fields) => { fmt_comma_delimited(fmt, &fields[..]) } } } } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -9,11 +9,10 @@ use std::borrow::Cow::{Borrowed, Owned}; use std::fmt; use std::raw::TraitObject; use std::str::from_utf8; -use std::string::CowString; use std::collections::HashMap; use std::collections::hash_map::{Iter, Entry}; -use std::iter::FromIterator; -use std::borrow::IntoCow; +use std::iter::{FromIterator, IntoIterator}; +use std::borrow::{Cow, IntoCow}; use std::{mem, raw}; use uany::{UnsafeAnyExt}; diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -30,7 +29,7 @@ mod common; mod shared; pub mod parsing; -type HeaderName = UniCase<CowString<'static>>; +type HeaderName = UniCase<Cow<'static, str>>; /// A trait for any object that will represent a header field and value. /// diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -139,7 +138,7 @@ impl Headers { loop { match try!(http::read_header(rdr)) { Some((name, value)) => { - debug!("raw header: {:?}={:?}", name, &value[]); + debug!("raw header: {:?}={:?}", name, &value[..]); count += (name.len() + value.len()) as u32; if count > MAX_HEADERS_LENGTH { debug!("Max header size reached, aborting"); diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -183,14 +182,14 @@ impl Headers { .get(&UniCase(Borrowed(unsafe { mem::transmute::<&str, &str>(name) }))) .and_then(|item| { if let Some(ref raw) = *item.raw { - return Some(&raw[]); + return Some(&raw[..]); } let raw = vec![item.typed.as_ref().unwrap().to_string().into_bytes()]; item.raw.set(raw); let raw = item.raw.as_ref().unwrap(); - Some(&raw[]) + Some(&raw[..]) }) } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -203,7 +202,7 @@ impl Headers { /// # let mut headers = Headers::new(); /// headers.set_raw("content-length", vec![b"5".to_vec()]); /// ``` - pub fn set_raw<K: IntoCow<'static, String, str>>(&mut self, name: K, value: Vec<Vec<u8>>) { + pub fn set_raw<K: IntoCow<'static, str>>(&mut self, name: K, value: Vec<Vec<u8>>) { self.data.insert(UniCase(name.into_cow()), Item::new_raw(value)); } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -351,7 +350,7 @@ impl<'a> fmt::Debug for HeaderView<'a> { } impl<'a> Extend<HeaderView<'a>> for Headers { - fn extend<I: Iterator<Item=HeaderView<'a>>>(&mut self, iter: I) { + fn extend<I: IntoIterator<Item=HeaderView<'a>>>(&mut self, iter: I) { for header in iter { self.data.insert((*header.0).clone(), (*header.1).clone()); } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -359,7 +358,7 @@ impl<'a> Extend<HeaderView<'a>> for Headers { } impl<'a> FromIterator<HeaderView<'a>> for Headers { - fn from_iter<I: Iterator<Item=HeaderView<'a>>>(iter: I) -> Headers { + fn from_iter<I: IntoIterator<Item=HeaderView<'a>>>(iter: I) -> Headers { let mut headers = Headers::new(); headers.extend(iter); headers diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -451,7 +450,7 @@ fn get_or_parse_mut<H: Header + HeaderFormat>(item: &mut Item) -> Option<&mut It fn parse<H: Header + HeaderFormat>(item: &Item) { match *item.raw { - Some(ref raw) => match Header::parse_header(&raw[]) { + Some(ref raw) => match Header::parse_header(&raw[..]) { Some::<H>(h) => item.typed.set(box h as Box<HeaderFormat + Send + Sync>), None => () }, diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -476,7 +475,7 @@ impl fmt::Display for Item { None => match *self.raw { Some(ref raw) => { for part in raw.iter() { - match from_utf8(&part[]) { + match from_utf8(&part[..]) { Ok(s) => try!(fmt.write_str(s)), Err(e) => { error!("raw header value is not utf8. header={:?}, error={:?}", part, e); diff --git a/src/header/parsing.rs b/src/header/parsing.rs --- a/src/header/parsing.rs +++ b/src/header/parsing.rs @@ -11,7 +11,7 @@ pub fn from_one_raw_str<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<T> { return None; } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. - match str::from_utf8(&raw[0][]) { + match str::from_utf8(&raw[0][..]) { Ok(s) => str::FromStr::from_str(s).ok(), Err(_) => None } diff --git a/src/header/parsing.rs b/src/header/parsing.rs --- a/src/header/parsing.rs +++ b/src/header/parsing.rs @@ -24,7 +24,7 @@ pub fn from_comma_delimited<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<Vec<T>> return None; } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. - from_one_comma_delimited(&raw[0][]) + from_one_comma_delimited(&raw[0][..]) } /// Reads a comma-delimited raw string into a Vec. diff --git a/src/header/shared/entity.rs b/src/header/shared/entity.rs --- a/src/header/shared/entity.rs +++ b/src/header/shared/entity.rs @@ -42,7 +42,7 @@ impl FromStr for EntityTag { type Err = (); fn from_str(s: &str) -> Result<EntityTag, ()> { let length: usize = s.len(); - let slice = &s[]; + let slice = &s[..]; // Early exits: // 1. The string is empty, or, diff --git a/src/header/shared/quality_item.rs b/src/header/shared/quality_item.rs --- a/src/header/shared/quality_item.rs +++ b/src/header/shared/quality_item.rs @@ -39,7 +39,7 @@ impl<T: fmt::Display> fmt::Display for QualityItem<T> { write!(f, "{}", self.item) } else { write!(f, "{}; q={}", self.item, - format!("{:.3}", self.quality).trim_right_matches(&['0', '.'][])) + format!("{:.3}", self.quality).trim_right_matches(&['0', '.'][..])) } } } diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -1,11 +1,10 @@ //! Pieces pertaining to the HTTP message protocol. -use std::borrow::Cow::{Borrowed, Owned}; +use std::borrow::Cow::{self, Borrowed, Owned}; use std::borrow::IntoCow; use std::cmp::min; use std::old_io::{self, Reader, IoResult, BufWriter}; use std::num::from_u16; use std::str; -use std::string::CowString; use url::Url; use url::ParseError as UrlError; diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -395,7 +394,7 @@ pub fn read_method<R: Reader>(stream: &mut R) -> HttpResult<method::Method> { debug!("maybe_method = {:?}", maybe_method); - match (maybe_method, &buf[]) { + match (maybe_method, &buf[..]) { (Some(method), _) => Ok(method), (None, ext) => { // We already checked that the buffer is ASCII diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -587,7 +586,7 @@ pub type StatusLine = (HttpVersion, RawStatus); /// The raw status code and reason-phrase. #[derive(PartialEq, Debug)] -pub struct RawStatus(pub u16, pub CowString<'static>); +pub struct RawStatus(pub u16, pub Cow<'static, str>); impl Clone for RawStatus { fn clone(&self) -> RawStatus { diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -664,7 +663,7 @@ pub fn read_status<R: Reader>(stream: &mut R) -> HttpResult<RawStatus> { } } - let reason = match str::from_utf8(&buf[]) { + let reason = match str::from_utf8(&buf[..]) { Ok(s) => s.trim(), Err(_) => return Err(HttpStatusError) }; diff --git a/src/net.rs b/src/net.rs --- a/src/net.rs +++ b/src/net.rs @@ -58,7 +58,7 @@ pub trait NetworkAcceptor: Clone + Send { } /// An iterator wrapper over a NetworkAcceptor. -pub struct NetworkConnections<'a, N: NetworkAcceptor>(&'a mut N); +pub struct NetworkConnections<'a, N: NetworkAcceptor + 'a>(&'a mut N); impl<'a, N: NetworkAcceptor> Iterator for NetworkConnections<'a, N> { type Item = IoResult<N::Stream>; diff --git a/src/server/acceptor.rs b/src/server/acceptor.rs --- a/src/server/acceptor.rs +++ b/src/server/acceptor.rs @@ -1,13 +1,13 @@ -use std::thread::{Thread, JoinGuard}; -use std::sync::Arc; +use std::thread::{self, JoinGuard}; use std::sync::mpsc; +use std::collections::VecMap; use net::NetworkAcceptor; pub struct AcceptorPool<A: NetworkAcceptor> { acceptor: A } -impl<A: NetworkAcceptor> AcceptorPool<A> { +impl<'a, A: NetworkAcceptor + 'a> AcceptorPool<A> { /// Create a thread pool to manage the acceptor. pub fn new(acceptor: A) -> AcceptorPool<A> { AcceptorPool { acceptor: acceptor } diff --git a/src/server/acceptor.rs b/src/server/acceptor.rs --- a/src/server/acceptor.rs +++ b/src/server/acceptor.rs @@ -18,34 +18,39 @@ impl<A: NetworkAcceptor> AcceptorPool<A> { /// ## Panics /// /// Panics if threads == 0. - pub fn accept<F: Fn(A::Stream) + Send + Sync>(self, - work: F, - threads: usize) -> JoinGuard<'static, ()> { + pub fn accept<F>(self, work: F, threads: usize) + where F: Fn(A::Stream) + Send + Sync + 'a { assert!(threads != 0, "Can't accept on 0 threads."); - // Replace with &F when Send changes land. - let work = Arc::new(work); - let (super_tx, supervisor_rx) = mpsc::channel(); - let spawn = - move || spawn_with(super_tx.clone(), work.clone(), self.acceptor.clone()); + let counter = &mut 0; + let work = &work; + let mut spawn = move || { + let id = *counter; + let guard = spawn_with(super_tx.clone(), work, self.acceptor.clone(), id); + *counter += 1; + (id, guard) + }; // Go - for _ in 0..threads { spawn() } + let mut guards: VecMap<_> = (0..threads).map(|_| spawn()).collect(); - // Spawn the supervisor - Thread::scoped(move || for () in supervisor_rx.iter() { spawn() }) + for id in supervisor_rx.iter() { + guards.remove(&id); + let (id, guard) = spawn(); + guards.insert(id, guard); + } } } -fn spawn_with<A, F>(supervisor: mpsc::Sender<()>, work: Arc<F>, mut acceptor: A) -where A: NetworkAcceptor, - F: Fn(<A as NetworkAcceptor>::Stream) + Send + Sync { +fn spawn_with<'a, A, F>(supervisor: mpsc::Sender<usize>, work: &'a F, mut acceptor: A, id: usize) -> JoinGuard<'a, ()> +where A: NetworkAcceptor + 'a, + F: Fn(<A as NetworkAcceptor>::Stream) + Send + Sync + 'a { use std::old_io::EndOfFile; - Thread::spawn(move || { - let sentinel = Sentinel::new(supervisor, ()); + thread::scoped(move || { + let sentinel = Sentinel::new(supervisor, id); loop { match acceptor.accept() { diff --git a/src/server/acceptor.rs b/src/server/acceptor.rs --- a/src/server/acceptor.rs +++ b/src/server/acceptor.rs @@ -61,7 +66,7 @@ where A: NetworkAcceptor, } } } - }); + }) } struct Sentinel<T: Send> { diff --git a/src/server/acceptor.rs b/src/server/acceptor.rs --- a/src/server/acceptor.rs +++ b/src/server/acceptor.rs @@ -83,7 +88,7 @@ impl<T: Send> Sentinel<T> { } #[unsafe_destructor] -impl<T: Send> Drop for Sentinel<T> { +impl<T: Send + 'static> Drop for Sentinel<T> { fn drop(&mut self) { // If we were cancelled, get out of here. if !self.active { return; } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -2,7 +2,7 @@ use std::old_io::{Listener, BufferedReader, BufferedWriter}; use std::old_io::net::ip::{IpAddr, Port, SocketAddr}; use std::os; -use std::thread::JoinGuard; +use std::thread::{self, JoinGuard}; pub use self::request::Request; pub use self::response::Response; diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -56,7 +56,7 @@ impl Server<HttpListener> { impl< L: NetworkListener<Acceptor=A> + Send, -A: NetworkAcceptor<Stream=S> + Send, +A: NetworkAcceptor<Stream=S> + Send + 'static, S: NetworkStream + Clone + Send> Server<L> { /// Creates a new server that will handle `HttpStream`s. pub fn with_listener(ip: IpAddr, port: Port, listener: L) -> Server<L> { diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -68,7 +68,7 @@ S: NetworkStream + Clone + Send> Server<L> { } /// Binds to a socket, and starts handling connections using a task pool. - pub fn listen_threads<H: Handler>(mut self, handler: H, threads: usize) -> HttpResult<Listening<L::Acceptor>> { + pub fn listen_threads<H: Handler + 'static>(mut self, handler: H, threads: usize) -> HttpResult<Listening<L::Acceptor>> { debug!("binding to {:?}:{:?}", self.ip, self.port); let acceptor = try!(self.listener.listen((self.ip, self.port))); let socket = try!(acceptor.socket_name()); diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -77,15 +77,17 @@ S: NetworkStream + Clone + Send> Server<L> { let pool = AcceptorPool::new(acceptor.clone()); let work = move |stream| handle_connection(stream, &handler); + let guard = thread::scoped(move || pool.accept(work, threads)); + Ok(Listening { - _guard: pool.accept(work, threads), + _guard: guard, socket: socket, acceptor: acceptor }) } /// Binds to a socket and starts handling connections. - pub fn listen<H: Handler>(self, handler: H) -> HttpResult<Listening<L::Acceptor>> { + pub fn listen<H: Handler + 'static>(self, handler: H) -> HttpResult<Listening<L::Acceptor>> { self.listen_threads(handler, os::num_cpus() * 5 / 4) } diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -3,6 +3,7 @@ //! These are responses sent by a `hyper::Server` to clients, after //! receiving a request. use std::old_io::IoResult; +use std::marker::PhantomData; use time::now_utc; diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -22,7 +23,9 @@ pub struct Response<'a, W = Fresh> { // The status code for the request. status: status::StatusCode, // The outgoing headers on this response. - headers: header::Headers + headers: header::Headers, + + _marker: PhantomData<W> } impl<'a, W> Response<'a, W> { diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -42,7 +45,8 @@ impl<'a, W> Response<'a, W> { status: status, version: version, body: body, - headers: headers + headers: headers, + _marker: PhantomData, } } diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -60,7 +64,8 @@ impl<'a> Response<'a, Fresh> { status: status::StatusCode::Ok, version: version::HttpVersion::Http11, headers: header::Headers::new(), - body: ThroughWriter(stream) + body: ThroughWriter(stream), + _marker: PhantomData, } } diff --git a/src/server/response.rs b/src/server/response.rs --- a/src/server/response.rs +++ b/src/server/response.rs @@ -119,7 +124,8 @@ impl<'a> Response<'a, Fresh> { version: self.version, body: stream, status: self.status, - headers: self.headers + headers: self.headers, + _marker: PhantomData, }) }
diff --git a/benches/client.rs b/benches/client.rs --- a/benches/client.rs +++ b/benches/client.rs @@ -1,4 +1,4 @@ -#![feature(core, io, test)] +#![feature(core, old_io, test)] extern crate hyper; extern crate test; diff --git a/benches/client_mock_tcp.rs b/benches/client_mock_tcp.rs --- a/benches/client_mock_tcp.rs +++ b/benches/client_mock_tcp.rs @@ -1,4 +1,4 @@ -#![feature(collections, io, test)] +#![feature(collections, old_io, test)] extern crate hyper; extern crate test; diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -1,4 +1,4 @@ -#![feature(io, test)] +#![feature(old_io, test)] extern crate hyper; extern crate test; diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -394,7 +394,7 @@ mod tests { #[test] fn test_redirect_followif() { fn follow_if(url: &Url) -> bool { - !url.serialize()[].contains("127.0.0.3") + !url.serialize().contains("127.0.0.3") } let mut client = Client::with_connector(MockRedirectPolicy); client.set_redirect_policy(RedirectPolicy::FollowIf(follow_if)); diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -77,7 +84,7 @@ impl Request<Fresh> { //TODO: this needs a test if let Some(ref q) = self.url.query { uri.push('?'); - uri.push_str(&q[]); + uri.push_str(&q[..]); } debug!("writing head: {:?} {:?} {:?}", self.method, uri, self.version); diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -185,7 +193,7 @@ mod tests { let stream = *req.body.end().unwrap() .into_inner().downcast::<MockStream>().ok().unwrap(); let bytes = stream.write.into_inner(); - let s = from_utf8(&bytes[]).unwrap(); + let s = from_utf8(&bytes[..]).unwrap(); assert!(!s.contains("Content-Length:")); assert!(!s.contains("Transfer-Encoding:")); } diff --git a/src/client/request.rs b/src/client/request.rs --- a/src/client/request.rs +++ b/src/client/request.rs @@ -199,7 +207,7 @@ mod tests { let stream = *req.body.end().unwrap() .into_inner().downcast::<MockStream>().ok().unwrap(); let bytes = stream.write.into_inner(); - let s = from_utf8(&bytes[]).unwrap(); + let s = from_utf8(&bytes[..]).unwrap(); assert!(!s.contains("Content-Length:")); assert!(!s.contains("Transfer-Encoding:")); } diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -98,6 +105,7 @@ mod tests { use std::borrow::Cow::Borrowed; use std::boxed::BoxAny; use std::old_io::BufferedReader; + use std::marker::PhantomData; use header::Headers; use header::TransferEncoding; diff --git a/src/client/response.rs b/src/client/response.rs --- a/src/client/response.rs +++ b/src/client/response.rs @@ -119,7 +127,8 @@ mod tests { headers: Headers::new(), version: version::HttpVersion::Http11, body: EofReader(BufferedReader::new(box MockStream::new() as Box<NetworkStream + Send>)), - status_raw: RawStatus(200, Borrowed("OK")) + status_raw: RawStatus(200, Borrowed("OK")), + _marker: PhantomData, }; let b = res.into_inner().downcast::<MockStream>().ok().unwrap(); diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -160,7 +160,7 @@ mod tests { #[test] fn test_raw_auth_parse() { let headers = Headers::from_raw(&mut mem("Authorization: foo bar baz\r\n\r\n")).unwrap(); - assert_eq!(&headers.get::<Authorization<String>>().unwrap().0[], "foo bar baz"); + assert_eq!(&headers.get::<Authorization<String>>().unwrap().0[..], "foo bar baz"); } #[test] diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -181,7 +181,7 @@ mod tests { fn test_basic_auth_parse() { let headers = Headers::from_raw(&mut mem("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n\r\n")).unwrap(); let auth = headers.get::<Authorization<Basic>>().unwrap(); - assert_eq!(&auth.0.username[], "Aladdin"); + assert_eq!(&auth.0.username[..], "Aladdin"); assert_eq!(auth.0.password, Some("open sesame".to_string())); } diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -82,7 +82,7 @@ impl Cookie { #[test] fn test_parse() { - let h = Header::parse_header(&[b"foo=bar; baz=quux".to_vec()][]); + let h = Header::parse_header(&[b"foo=bar; baz=quux".to_vec()][..]); let c1 = CookiePair::new("foo".to_string(), "bar".to_string()); let c2 = CookiePair::new("baz".to_string(), "quux".to_string()); assert_eq!(h, Some(Cookie(vec![c1, c2]))); diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -99,7 +99,7 @@ fn test_fmt() { let mut headers = Headers::new(); headers.set(cookie_header); - assert_eq!(&headers.to_string()[], "Cookie: foo=bar; baz=quux\r\n"); + assert_eq!(&headers.to_string()[..], "Cookie: foo=bar; baz=quux\r\n"); } #[test] diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs --- a/src/header/common/set_cookie.rs +++ b/src/header/common/set_cookie.rs @@ -76,7 +76,7 @@ impl SetCookie { #[test] fn test_parse() { - let h = Header::parse_header(&[b"foo=bar; HttpOnly".to_vec()][]); + let h = Header::parse_header(&[b"foo=bar; HttpOnly".to_vec()][..]); let mut c1 = Cookie::new("foo".to_string(), "bar".to_string()); c1.httponly = true; diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs --- a/src/header/common/set_cookie.rs +++ b/src/header/common/set_cookie.rs @@ -94,7 +94,7 @@ fn test_fmt() { let mut headers = Headers::new(); headers.set(cookies); - assert_eq!(&headers.to_string()[], "Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux; Path=/\r\n"); + assert_eq!(&headers.to_string()[..], "Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux; Path=/\r\n"); } #[test] diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -532,12 +531,9 @@ impl<'a, H: HeaderFormat> fmt::Debug for HeaderFormatter<'a, H> { mod tests { use std::old_io::MemReader; use std::fmt; - use std::borrow::Cow::Borrowed; - use std::hash::{SipHasher, hash}; use mime::Mime; use mime::TopLevel::Text; use mime::SubLevel::Plain; - use unicase::UniCase; use super::{Headers, Header, HeaderFormat, ContentLength, ContentType, Accept, Host, QualityItem}; diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -547,15 +543,6 @@ mod tests { MemReader::new(s.as_bytes().to_vec()) } - #[test] - fn test_case_insensitive() { - let a = UniCase(Borrowed("foobar")); - let b = UniCase(Borrowed("FOOBAR")); - - assert_eq!(a, b); - assert_eq!(hash::<_, SipHasher>(&a), hash::<_, SipHasher>(&b)); - } - #[test] fn test_from_raw() { let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap(); diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -595,7 +582,7 @@ mod tests { return None; } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. - match from_utf8(unsafe { &raw[].get_unchecked(0)[] }) { + match from_utf8(unsafe { &raw.get_unchecked(0)[..] }) { Ok(s) => FromStr::from_str(s).ok(), Err(_) => None }.map(|u| CrazyLength(Some(false), u)) diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -671,7 +658,7 @@ mod tests { let mut headers = Headers::new(); headers.set(ContentLength(10)); headers.set_raw("content-LENGTH", vec![b"20".to_vec()]); - assert_eq!(headers.get_raw("Content-length").unwrap(), &[b"20".to_vec()][]); + assert_eq!(headers.get_raw("Content-length").unwrap(), &[b"20".to_vec()][..]); assert_eq!(headers.get(), Some(&ContentLength(20))); } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,5 @@ -#![feature(core, collections, hash, io, os, path, std_misc, - slicing_syntax, box_syntax, unsafe_destructor)] +#![feature(core, collections, io, old_io, os, old_path, + std_misc, box_syntax, unsafe_destructor)] #![deny(missing_docs)] #![cfg_attr(test, deny(warnings))] #![cfg_attr(test, feature(alloc, test))]
Build failure with rust nightly Hi, I'm not sure what this error means, or why there are so many of these "note: write `[...]` instead" lines without any souce file and line number information... ``` $ cargo build Compiling hyper v0.1.13 note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead note: write `[..]` instead /home/x/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.1.13/src/header/mod.rs:206:23: 206:52 error: wrong number of type arguments: expected 1, found 2 [E0244] /home/x/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.1.13/src/header/mod.rs:206 pub fn set_raw<K: IntoCow<'static, String, str>>(&mut self, name: K, value: Vec<Vec<u8>>) { ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: aborting due to previous error Could not compile `hyper`. ```
2015-02-21T23:07:22Z
0.1
e8833c0c894a2b87b5d9b48b07858ec7fc890b7a
hyperium/hyper
319
hyperium__hyper-319
[ "314" ]
f8776f4c241e6c064b7cdcaa62e4eab180784c69
diff --git a/src/header/shared/quality_item.rs b/src/header/shared/quality_item.rs --- a/src/header/shared/quality_item.rs +++ b/src/header/shared/quality_item.rs @@ -26,6 +27,12 @@ impl<T> QualityItem<T> { } } +impl<T: PartialEq> cmp::PartialOrd for QualityItem<T> { + fn partial_cmp(&self, other: &QualityItem<T>) -> Option<cmp::Ordering> { + self.quality.partial_cmp(&other.quality) + } +} + impl<T: fmt::Display> fmt::Display for QualityItem<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.quality == 1.0 {
diff --git a/src/header/shared/quality_item.rs b/src/header/shared/quality_item.rs --- a/src/header/shared/quality_item.rs +++ b/src/header/shared/quality_item.rs @@ -5,6 +5,7 @@ use std::fmt; use std::str; +use std::cmp; #[cfg(test)] use super::encoding::*; /// Represents an item with a quality value as defined in diff --git a/src/header/shared/quality_item.rs b/src/header/shared/quality_item.rs --- a/src/header/shared/quality_item.rs +++ b/src/header/shared/quality_item.rs @@ -127,3 +134,10 @@ fn test_quality_item_from_str5() { let x: Result<QualityItem<Encoding>, ()> = "gzip; q=0.2739999".parse(); assert_eq!(x, Err(())); } +#[test] +fn test_quality_item_ordering() { + let x: QualityItem<Encoding> = "gzip; q=0.5".parse().ok().unwrap(); + let y: QualityItem<Encoding> = "gzip; q=0.273".parse().ok().unwrap(); + let comparision_result: bool = x.gt(&y); + assert_eq!(comparision_result, true) +}
Implement `PartialOrd` for `QualityItem` Sort `QualityItems` according to their `q` value. This is useful for comparison and to sort `QualityItems`. It makes it easier to find the preferred item, that matches the provided items.
2015-02-15T17:04:29Z
0.1
e8833c0c894a2b87b5d9b48b07858ec7fc890b7a
hyperium/hyper
313
hyperium__hyper-313
[ "301" ]
f554c09e12da805a219675fe7eceeffca4e41fec
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -20,6 +20,7 @@ pub use self::date::Date; pub use self::etag::Etag; pub use self::expires::Expires; pub use self::host::Host; +pub use self::if_match::IfMatch; pub use self::if_modified_since::IfModifiedSince; pub use self::if_none_match::IfNoneMatch; pub use self::if_unmodified_since::IfUnmodifiedSince; diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -157,6 +158,7 @@ mod date; mod etag; mod expires; mod host; +mod if_match; mod last_modified; mod if_modified_since; mod if_none_match;
diff --git /dev/null b/src/header/common/if_match.rs new file mode 100644 --- /dev/null +++ b/src/header/common/if_match.rs @@ -0,0 +1,68 @@ +use header::{EntityTag, Header, HeaderFormat}; +use header::parsing::{from_comma_delimited, fmt_comma_delimited, from_one_raw_str}; +use std::fmt; + +/// The `If-Match` header +/// +/// The `If-Match` request-header field is used with a method to make +/// it conditional. The client provides a list of entity tags, and +/// the request is only executed if one of those tags matches the +/// current entity. +/// +/// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24 +#[derive(Clone, PartialEq, Debug)] +pub enum IfMatch { + /// This corresponds to '*'. + Any, + /// The header field names which will influence the response representation. + EntityTags(Vec<EntityTag>) +} + +impl Header for IfMatch { + fn header_name() -> &'static str { + "If-Match" + } + + fn parse_header(raw: &[Vec<u8>]) -> Option<IfMatch> { + from_one_raw_str(raw).and_then(|s: String| { + let slice = &s[]; + match slice { + "" => None, + "*" => Some(IfMatch::Any), + _ => from_comma_delimited(raw).map(IfMatch::EntityTags), + } + }) + } +} + +impl HeaderFormat for IfMatch { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + match *self { + IfMatch::Any => write!(fmt, "*"), + IfMatch::EntityTags(ref fields) => fmt_comma_delimited(fmt, &fields[]) + } + } +} + +#[test] +fn test_parse_header() { + { + let a: IfMatch = Header::parse_header( + [b"*".to_vec()].as_slice()).unwrap(); + assert_eq!(a, IfMatch::Any); + } + { + let a: IfMatch = Header::parse_header( + [b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\"".to_vec()].as_slice()).unwrap(); + let b = IfMatch::EntityTags( + vec![EntityTag{weak:false, tag: "xyzzy".to_string()}, + EntityTag{weak:false, tag: "r2d2xxxx".to_string()}, + EntityTag{weak:false, tag: "c3piozzzz".to_string()}]); + assert_eq!(a, b); + } +} + +bench_header!(star, IfMatch, { vec![b"*".to_vec()] }); +bench_header!(single , IfMatch, { vec![b"\"xyzzy\"".to_vec()] }); +bench_header!(multi, IfMatch, + { vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\"".to_vec()] });
feat(headers): add IfMatch header Add support for the If-Match http header.
2015-02-14T20:00:41Z
0.1
e8833c0c894a2b87b5d9b48b07858ec7fc890b7a
hyperium/hyper
310
hyperium__hyper-310
[ "309" ]
f554c09e12da805a219675fe7eceeffca4e41fec
diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -3,7 +3,10 @@ use std::borrow::Cow::{Borrowed, Owned}; use std::borrow::IntoCow; use std::cmp::min; use std::old_io::{self, Reader, IoResult, BufWriter}; +use std::old_io::util as io_util; +use std::mem; use std::num::from_u16; +use std::ptr; use std::str; use std::string::CowString; diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -20,7 +23,7 @@ use HttpError::{HttpHeaderError, HttpIoError, HttpMethodError, HttpStatusError, HttpUriError, HttpVersionError}; use HttpResult; -use self::HttpReader::{SizedReader, ChunkedReader, EofReader, EmptyReader}; +use self::HttpReader::{SizedReader, ChunkedReader, EofReader}; use self::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter}; /// Readers to handle different Transfer-Encodings. diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -47,22 +50,30 @@ pub enum HttpReader<R> { /// > reliably; the server MUST respond with the 400 (Bad Request) /// > status code and then close the connection. EofReader(R), - /// A Reader used for messages that should never have a body. - /// - /// See https://tools.ietf.org/html/rfc7230#section-3.3.3 - EmptyReader(R), } impl<R: Reader> HttpReader<R> { /// Unwraps this HttpReader and returns the underlying Reader. + #[inline] pub fn unwrap(self) -> R { - match self { - SizedReader(r, _) => r, - ChunkedReader(r, _) => r, - EofReader(r) => r, - EmptyReader(r) => r, - } + let r = unsafe { + ptr::read(match self { + SizedReader(ref r, _) => r, + ChunkedReader(ref r, _) => r, + EofReader(ref r) => r, + }) + }; + unsafe { mem::forget(self); } + r + } +} + +#[unsafe_destructor] +impl<R: Reader> Drop for HttpReader<R> { + #[inline] + fn drop(&mut self) { + let _cant_use = io_util::copy(self, &mut io_util::NullWriter); } } diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -116,7 +127,6 @@ impl<R: Reader> Reader for HttpReader<R> { EofReader(ref mut body) => { body.read(buf) }, - EmptyReader(_) => Err(old_io::standard_error(old_io::EndOfFile)) } } } diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -2,7 +2,7 @@ //! //! These are requests that a `hyper::Server` receives, and include its method, //! target URI, headers, and message body. -use std::old_io::IoResult; +use std::old_io::{self, IoResult}; use std::old_io::net::ip::SocketAddr; use {HttpResult}; diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -11,7 +11,7 @@ use method::Method::{self, Get, Head}; use header::{Headers, ContentLength, TransferEncoding}; use http::{read_request_line}; use http::HttpReader; -use http::HttpReader::{SizedReader, ChunkedReader, EmptyReader}; +use http::HttpReader::{SizedReader, ChunkedReader}; use uri::RequestUri; /// A request bundles several parts of an incoming `NetworkStream`, given to a `Handler`. diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -26,7 +26,7 @@ pub struct Request<'a> { pub uri: RequestUri, /// The version of HTTP for this request. pub version: HttpVersion, - body: HttpReader<&'a mut (Reader + 'a)> + body: Body<HttpReader<&'a mut (Reader + 'a)>> } diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -39,18 +39,19 @@ impl<'a> Request<'a> { let headers = try!(Headers::from_raw(&mut stream)); debug!("{:?}", headers); - let body = if method == Get || method == Head { - EmptyReader(stream) - } else if headers.has::<ContentLength>() { - match headers.get::<ContentLength>() { - Some(&ContentLength(len)) => SizedReader(stream, len), - None => unreachable!() - } + let body = if let Some(len) = headers.get::<ContentLength>() { + SizedReader(stream, **len) } else if headers.has::<TransferEncoding>() { todo!("check for Transfer-Encoding: chunked"); ChunkedReader(stream, None) } else { - EmptyReader(stream) + SizedReader(stream, 0) + }; + + let body = if method == Get || method == Head { + Body::Empty(body) + } else { + Body::NonEmpty(body) }; Ok(Request { diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -68,13 +69,31 @@ impl<'a> Request<'a> { RequestUri, HttpVersion, HttpReader<&'a mut (Reader + 'a)>,) { (self.remote_addr, self.method, self.headers, - self.uri, self.version, self.body) + self.uri, self.version, self.body.into_inner()) } } impl<'a> Reader for Request<'a> { + #[inline] fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { - self.body.read(buf) + match self.body { + Body::Empty(..) => Err(old_io::standard_error(old_io::EndOfFile)), + Body::NonEmpty(ref mut r) => r.read(buf) + } + } +} + +enum Body<R> { + Empty(R), + NonEmpty(R), +} + +impl<R> Body<R> { + fn into_inner(self) -> R { + match self { + Body::Empty(r) => r, + Body::NonEmpty(r) => r + } } }
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,5 @@ #![feature(core, collections, hash, io, os, path, std_misc, - slicing_syntax, box_syntax)] + slicing_syntax, box_syntax, unsafe_destructor)] #![deny(missing_docs)] #![cfg_attr(test, deny(warnings))] #![cfg_attr(test, feature(alloc, test))] diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -95,8 +114,9 @@ mod tests { let mut stream = MockStream::with_input(b"\ GET / HTTP/1.1\r\n\ Host: example.domain\r\n\ + Content-Length: 18\r\n\ \r\n\ - I'm a bad request.\r\n\ + I'm a bad request.\ "); let mut req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -108,8 +128,9 @@ mod tests { let mut stream = MockStream::with_input(b"\ HEAD / HTTP/1.1\r\n\ Host: example.domain\r\n\ + Content-Length: 18\r\n\ \r\n\ - I'm a bad request.\r\n\ + I'm a bad request.\ "); let mut req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -117,7 +138,7 @@ mod tests { } #[test] - fn test_post_empty_body() { + fn test_post_body_with_no_content_length() { let mut stream = MockStream::with_input(b"\ POST / HTTP/1.1\r\n\ Host: example.domain\r\n\ diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -129,6 +150,20 @@ mod tests { assert_eq!(req.read_to_string(), Ok("".to_string())); } + #[test] + fn test_unexpected_body_drains_upon_drop() { + let mut stream = MockStream::with_input(b"\ + GET / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Content-Length: 18\r\n\ + \r\n\ + I'm a bad request.\ + "); + + Request::new(&mut stream, sock("127.0.0.1:80")).unwrap().read_to_string().unwrap(); + assert!(stream.read.eof()); + } + #[test] fn test_parse_chunked_request() { let mut stream = MockStream::with_input(b"\
Read body for all requests with a Content-Length header The framing of a HTTP request doesn't depend on the method [1], so any request with a non-zero Content-Length has a corresponding body. This does not change in the case of idempotent methods like GET; what is different is that for such methods it is incorrect for the server's response to depend on the content of this body. At the moment GET and HEAD are incorrectly special cased in hyper [2] leading to problems if you send a GET request with a body (the unread body bleeds into the following request unless the connection is closed). In these cases the body data, if any, must be read from the network but could be discarded and not made avaliable through the request API. [1] https://tools.ietf.org/html/rfc7230#section-3.3 [2] https://github.com/hyperium/hyper/blob/master/src/server/request.rs#L42
Good catch. I've also noticed that for requests that should have a body, such as POST, and the user doesn't read it out, it bleeds into the next request also. We could write a Drop impl for Request that tries to read out the remainder of the body.
2015-02-14T02:39:22Z
0.1
e8833c0c894a2b87b5d9b48b07858ec7fc890b7a
hyperium/hyper
302
hyperium__hyper-302
[ "238" ]
f836ee89c13e6afa44429d3da2517530175bad25
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -21,6 +21,7 @@ pub use self::etag::Etag; pub use self::expires::Expires; pub use self::host::Host; pub use self::if_modified_since::IfModifiedSince; +pub use self::if_none_match::IfNoneMatch; pub use self::if_unmodified_since::IfUnmodifiedSince; pub use self::last_modified::LastModified; pub use self::location::Location; diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -158,6 +159,7 @@ mod expires; mod host; mod last_modified; mod if_modified_since; +mod if_none_match; mod if_unmodified_since; mod location; mod pragma;
diff --git /dev/null b/src/header/common/if_none_match.rs new file mode 100644 --- /dev/null +++ b/src/header/common/if_none_match.rs @@ -0,0 +1,84 @@ +use header::{Header, HeaderFormat, EntityTag}; +use header::parsing::{from_comma_delimited, fmt_comma_delimited, from_one_raw_str}; +use std::fmt::{self}; + +/// The `If-None-Match` header defined by HTTP/1.1. +/// +/// The "If-None-Match" header field makes the request method conditional +/// on a recipient cache or origin server either not having any current +/// representation of the target resource, when the field-value is "*", +/// or having a selected representation with an entity-tag that does not +/// match any of those listed in the field-value. +/// +/// A recipient MUST use the weak comparison function when comparing +/// entity-tags for If-None-Match (Section 2.3.2), since weak entity-tags +/// can be used for cache validation even if there have been changes to +/// the representation data. +/// +/// Spec: https://tools.ietf.org/html/rfc7232#section-3.2 + +/// The `If-None-Match` header field. +#[derive(Clone, PartialEq, Debug)] +pub enum IfNoneMatch { + /// This corresponds to '*'. + Any, + /// The header field names which will influence the response representation. + EntityTags(Vec<EntityTag>) +} + +impl Header for IfNoneMatch { + fn header_name() -> &'static str { + "If-None-Match" + } + + fn parse_header(raw: &[Vec<u8>]) -> Option<IfNoneMatch> { + from_one_raw_str(raw).and_then(|s: String| { + let slice = &s[]; + match slice { + "" => None, + "*" => Some(IfNoneMatch::Any), + _ => from_comma_delimited(raw).map(|vec| IfNoneMatch::EntityTags(vec)), + } + }) + } +} + +impl HeaderFormat for IfNoneMatch { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + match *self { + IfNoneMatch::Any => { write!(fmt, "*") } + IfNoneMatch::EntityTags(ref fields) => { fmt_comma_delimited(fmt, &fields[]) } + } + } +} + +#[cfg(test)] +mod tests { + use super::IfNoneMatch; + use header::Header; + use header::EntityTag; + + #[test] + fn test_if_none_match() { + let mut if_none_match: Option<IfNoneMatch>; + + if_none_match = Header::parse_header([b"*".to_vec()].as_slice()); + assert_eq!(if_none_match, Some(IfNoneMatch::Any)); + + if_none_match = Header::parse_header([b"\"foobar\", W/\"weak-etag\"".to_vec()].as_slice()); + let mut entities: Vec<EntityTag> = Vec::new(); + let foobar_etag = EntityTag { + weak: false, + tag: "foobar".to_string() + }; + let weak_etag = EntityTag { + weak: true, + tag: "weak-etag".to_string() + }; + entities.push(foobar_etag); + entities.push(weak_etag); + assert_eq!(if_none_match, Some(IfNoneMatch::EntityTags(entities))); + } +} + +bench_header!(bench, IfNoneMatch, { vec![b"W/\"nonemptytag\"".to_vec()] });
add If-None-Match header This is needed for https://github.com/servo/servo/pull/4117/. Spec: https://tools.ietf.org/html/rfc7232#section-3.2
2015-02-07T20:57:28Z
0.1
e8833c0c894a2b87b5d9b48b07858ec7fc890b7a
hyperium/hyper
292
hyperium__hyper-292
[ "291" ]
eee462568657ac54b1cf44d473f5227979241255
diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -32,9 +32,9 @@ impl<S: Scheme> Header for Authorization<S> { match (from_utf8(unsafe { &raw[].get_unchecked(0)[] }), Scheme::scheme(None::<S>)) { (Ok(header), Some(scheme)) if header.starts_with(scheme) && header.len() > scheme.len() + 1 => { - header[scheme.len() + 1..].parse::<S>().map(|s| Authorization(s)) + header[scheme.len() + 1..].parse::<S>().map(|s| Authorization(s)).ok() }, - (Ok(header), None) => header.parse::<S>().map(|s| Authorization(s)), + (Ok(header), None) => header.parse::<S>().map(|s| Authorization(s)).ok(), _ => None } } else { diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -108,32 +108,33 @@ impl Scheme for Basic { } impl FromStr for Basic { - fn from_str(s: &str) -> Option<Basic> { + type Err = (); + fn from_str(s: &str) -> Result<Basic, ()> { match s.from_base64() { Ok(decoded) => match String::from_utf8(decoded) { Ok(text) => { let mut parts = &mut text[].split(':'); let user = match parts.next() { Some(part) => part.to_string(), - None => return None + None => return Err(()) }; let password = match parts.next() { Some(part) => Some(part.to_string()), None => None }; - Some(Basic { + Ok(Basic { username: user, password: password }) }, Err(e) => { debug!("Basic::from_utf8 error={:?}", e); - None + Err(()) } }, Err(e) => { debug!("Basic::from_base64 error={:?}", e); - None + Err(()) } } } diff --git a/src/header/common/cache_control.rs b/src/header/common/cache_control.rs --- a/src/header/common/cache_control.rs +++ b/src/header/common/cache_control.rs @@ -96,28 +96,29 @@ impl fmt::Display for CacheDirective { } impl FromStr for CacheDirective { - fn from_str(s: &str) -> Option<CacheDirective> { + type Err = Option<<u32 as FromStr>::Err>; + fn from_str(s: &str) -> Result<CacheDirective, Option<<u32 as FromStr>::Err>> { use self::CacheDirective::*; match s { - "no-cache" => Some(NoCache), - "no-store" => Some(NoStore), - "no-transform" => Some(NoTransform), - "only-if-cached" => Some(OnlyIfCached), - "must-revalidate" => Some(MustRevalidate), - "public" => Some(Public), - "private" => Some(Private), - "proxy-revalidate" => Some(ProxyRevalidate), - "" => None, + "no-cache" => Ok(NoCache), + "no-store" => Ok(NoStore), + "no-transform" => Ok(NoTransform), + "only-if-cached" => Ok(OnlyIfCached), + "must-revalidate" => Ok(MustRevalidate), + "public" => Ok(Public), + "private" => Ok(Private), + "proxy-revalidate" => Ok(ProxyRevalidate), + "" => Err(None), _ => match s.find('=') { Some(idx) if idx+1 < s.len() => match (&s[..idx], &s[idx+1..].trim_matches('"')) { - ("max-age" , secs) => secs.parse().map(MaxAge), - ("max-stale", secs) => secs.parse().map(MaxStale), - ("min-fresh", secs) => secs.parse().map(MinFresh), - ("s-maxage", secs) => secs.parse().map(SMaxAge), - (left, right) => Some(Extension(left.to_string(), Some(right.to_string()))) + ("max-age" , secs) => secs.parse().map(MaxAge).map_err(|x| Some(x)), + ("max-stale", secs) => secs.parse().map(MaxStale).map_err(|x| Some(x)), + ("min-fresh", secs) => secs.parse().map(MinFresh).map_err(|x| Some(x)), + ("s-maxage", secs) => secs.parse().map(SMaxAge).map_err(|x| Some(x)), + (left, right) => Ok(Extension(left.to_string(), Some(right.to_string()))) }, - Some(_) => None, - None => Some(Extension(s.to_string(), None)) + Some(_) => Err(None), + None => Ok(Extension(s.to_string(), None)) } } } diff --git a/src/header/common/connection.rs b/src/header/common/connection.rs --- a/src/header/common/connection.rs +++ b/src/header/common/connection.rs @@ -31,11 +31,12 @@ pub enum ConnectionOption { } impl FromStr for ConnectionOption { - fn from_str(s: &str) -> Option<ConnectionOption> { + type Err = (); + fn from_str(s: &str) -> Result<ConnectionOption, ()> { match s { - "keep-alive" => Some(KeepAlive), - "close" => Some(Close), - s => Some(ConnectionHeader(UniCase(s.to_string()))) + "keep-alive" => Ok(KeepAlive), + "close" => Ok(Close), + s => Ok(ConnectionHeader(UniCase(s.to_string()))) } } } diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -30,8 +30,8 @@ impl Header for Cookie { Ok(cookies_str) => { for cookie_str in cookies_str.split(';') { match cookie_str.trim().parse() { - Some(cookie) => cookies.push(cookie), - None => return None + Ok(cookie) => cookies.push(cookie), + Err(_) => return None } } }, diff --git a/src/header/common/date.rs b/src/header/common/date.rs --- a/src/header/common/date.rs +++ b/src/header/common/date.rs @@ -35,8 +35,9 @@ impl HeaderFormat for Date { } impl FromStr for Date { - fn from_str(s: &str) -> Option<Date> { - tm_from_str(s).map(Date) + type Err = (); + fn from_str(s: &str) -> Result<Date, ()> { + tm_from_str(s).map(Date).ok_or(()) } } diff --git a/src/header/common/expires.rs b/src/header/common/expires.rs --- a/src/header/common/expires.rs +++ b/src/header/common/expires.rs @@ -34,8 +34,9 @@ impl HeaderFormat for Expires { } impl FromStr for Expires { - fn from_str(s: &str) -> Option<Expires> { - tm_from_str(s).map(Expires) + type Err = (); + fn from_str(s: &str) -> Result<Expires, ()> { + tm_from_str(s).map(Expires).ok_or(()) } } diff --git a/src/header/common/host.rs b/src/header/common/host.rs --- a/src/header/common/host.rs +++ b/src/header/common/host.rs @@ -46,7 +46,7 @@ impl Header for Host { }; let port = match idx { - Some(idx) => s[idx + 1..].parse(), + Some(idx) => s[idx + 1..].parse().ok(), None => None }; diff --git a/src/header/common/if_modified_since.rs b/src/header/common/if_modified_since.rs --- a/src/header/common/if_modified_since.rs +++ b/src/header/common/if_modified_since.rs @@ -34,8 +34,9 @@ impl HeaderFormat for IfModifiedSince { } impl FromStr for IfModifiedSince { - fn from_str(s: &str) -> Option<IfModifiedSince> { - tm_from_str(s).map(IfModifiedSince) + type Err = (); + fn from_str(s: &str) -> Result<IfModifiedSince, ()> { + tm_from_str(s).map(IfModifiedSince).ok_or(()) } } diff --git a/src/header/common/last_modified.rs b/src/header/common/last_modified.rs --- a/src/header/common/last_modified.rs +++ b/src/header/common/last_modified.rs @@ -34,8 +34,9 @@ impl HeaderFormat for LastModified { } impl FromStr for LastModified { - fn from_str(s: &str) -> Option<LastModified> { - tm_from_str(s).map(LastModified) + type Err = (); + fn from_str(s: &str) -> Result<LastModified, ()> { + tm_from_str(s).map(LastModified).ok_or(()) } } diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs --- a/src/header/common/set_cookie.rs +++ b/src/header/common/set_cookie.rs @@ -26,8 +26,8 @@ impl Header for SetCookie { match from_utf8(&set_cookies_raw[]) { Ok(s) if !s.is_empty() => { match s.parse() { - Some(cookie) => set_cookies.push(cookie), - None => () + Ok(cookie) => set_cookies.push(cookie), + Err(_) => () } }, _ => () diff --git a/src/header/common/upgrade.rs b/src/header/common/upgrade.rs --- a/src/header/common/upgrade.rs +++ b/src/header/common/upgrade.rs @@ -22,12 +22,13 @@ pub enum Protocol { } impl FromStr for Protocol { - fn from_str(s: &str) -> Option<Protocol> { + type Err = (); + fn from_str(s: &str) -> Result<Protocol, ()> { if UniCase(s) == UniCase("websocket") { - Some(WebSocket) + Ok(WebSocket) } else { - Some(ProtocolExt(s.to_string())) + Ok(ProtocolExt(s.to_string())) } } } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -349,7 +349,7 @@ impl<'a> fmt::Debug for HeaderView<'a> { } impl<'a> Extend<HeaderView<'a>> for Headers { - fn extend<I: Iterator<Item=HeaderView<'a>>>(&mut self, mut iter: I) { + fn extend<I: Iterator<Item=HeaderView<'a>>>(&mut self, iter: I) { for header in iter { self.data.insert((*header.0).clone(), (*header.1).clone()); } diff --git a/src/header/parsing.rs b/src/header/parsing.rs --- a/src/header/parsing.rs +++ b/src/header/parsing.rs @@ -12,7 +12,7 @@ pub fn from_one_raw_str<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<T> { } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. match str::from_utf8(&raw[0][]) { - Ok(s) => str::FromStr::from_str(s), + Ok(s) => str::FromStr::from_str(s).ok(), Err(_) => None } } diff --git a/src/header/parsing.rs b/src/header/parsing.rs --- a/src/header/parsing.rs +++ b/src/header/parsing.rs @@ -34,7 +34,7 @@ pub fn from_one_comma_delimited<T: str::FromStr>(raw: &[u8]) -> Option<Vec<T>> { Some(s.as_slice() .split(',') .map(|x| x.trim()) - .filter_map(str::FromStr::from_str) + .filter_map(|x| x.parse().ok()) .collect()) } Err(_) => None diff --git a/src/header/shared/encoding.rs b/src/header/shared/encoding.rs --- a/src/header/shared/encoding.rs +++ b/src/header/shared/encoding.rs @@ -37,14 +37,15 @@ impl fmt::Display for Encoding { } impl str::FromStr for Encoding { - fn from_str(s: &str) -> Option<Encoding> { + type Err = (); + fn from_str(s: &str) -> Result<Encoding, ()> { match s { - "chunked" => Some(Chunked), - "deflate" => Some(Deflate), - "gzip" => Some(Gzip), - "compress" => Some(Compress), - "identity" => Some(Identity), - _ => Some(EncodingExt(s.to_string())) + "chunked" => Ok(Chunked), + "deflate" => Ok(Deflate), + "gzip" => Ok(Gzip), + "compress" => Ok(Compress), + "identity" => Ok(Identity), + _ => Ok(EncodingExt(s.to_string())) } } } diff --git a/src/header/shared/quality_item.rs b/src/header/shared/quality_item.rs --- a/src/header/shared/quality_item.rs +++ b/src/header/shared/quality_item.rs @@ -38,7 +38,8 @@ impl<T: fmt::Display> fmt::Display for QualityItem<T> { } impl<T: str::FromStr> str::FromStr for QualityItem<T> { - fn from_str(s: &str) -> Option<Self> { + type Err = (); + fn from_str(s: &str) -> Result<Self, ()> { // Set defaults used if parsing fails. let mut raw_item = s; let mut quality = 1f32; diff --git a/src/header/shared/quality_item.rs b/src/header/shared/quality_item.rs --- a/src/header/shared/quality_item.rs +++ b/src/header/shared/quality_item.rs @@ -49,28 +50,28 @@ impl<T: str::FromStr> str::FromStr for QualityItem<T> { if start == "q=" || start == "Q=" { let q_part = &parts[0][2..parts[0].len()]; if q_part.len() > 5 { - return None; + return Err(()); } - let x: Option<f32> = q_part.parse(); + let x: Result<f32, _> = q_part.parse(); match x { - Some(q_value) => { + Ok(q_value) => { if 0f32 <= q_value && q_value <= 1f32 { quality = q_value; raw_item = parts[1]; } else { - return None; + return Err(()); } }, - None => return None, + Err(_) => return Err(()), } } } - let x: Option<T> = raw_item.parse(); + let x: Result<T, _> = raw_item.parse(); match x { - Some(item) => { - Some(QualityItem{ item: item, quality: quality, }) + Ok(item) => { + Ok(QualityItem{ item: item, quality: quality, }) }, - None => return None, + Err(_) => return Err(()), } } } diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -4,7 +4,7 @@ use std::borrow::IntoCow; use std::cmp::min; use std::old_io::{self, Reader, IoResult, BufWriter}; use std::num::from_u16; -use std::str::{self, FromStr}; +use std::str; use std::string::CowString; use url::Url; diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -625,7 +625,7 @@ pub fn read_status<R: Reader>(stream: &mut R) -> HttpResult<RawStatus> { try!(stream.read_byte()), ]; - let code = match str::from_utf8(code.as_slice()).ok().and_then(FromStr::from_str) { + let code = match str::from_utf8(code.as_slice()).ok().and_then(|x| x.parse().ok()) { Some(num) => num, None => return Err(HttpStatusError) }; diff --git a/src/method.rs b/src/method.rs --- a/src/method.rs +++ b/src/method.rs @@ -68,11 +68,12 @@ impl Method { } impl FromStr for Method { - fn from_str(s: &str) -> Option<Method> { + type Err = (); + fn from_str(s: &str) -> Result<Method, ()> { if s == "" { - None + Err(()) } else { - Some(match s { + Ok(match s { "OPTIONS" => Options, "GET" => Get, "POST" => Post,
diff --git a/benches/client_mock_tcp.rs b/benches/client_mock_tcp.rs --- a/benches/client_mock_tcp.rs +++ b/benches/client_mock_tcp.rs @@ -1,4 +1,4 @@ -#![feature(core, collections, io, test)] +#![feature(collections, io, test)] extern crate hyper; extern crate test; diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -571,7 +571,7 @@ mod tests { } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. match from_utf8(unsafe { &raw[].get_unchecked(0)[] }) { - Ok(s) => FromStr::from_str(s), + Ok(s) => FromStr::from_str(s).ok(), Err(_) => None }.map(|u| CrazyLength(Some(false), u)) } diff --git a/src/header/shared/quality_item.rs b/src/header/shared/quality_item.rs --- a/src/header/shared/quality_item.rs +++ b/src/header/shared/quality_item.rs @@ -103,26 +104,26 @@ fn test_quality_item_show3() { #[test] fn test_quality_item_from_str1() { - let x: Option<QualityItem<Encoding>> = "chunked".parse(); + let x: Result<QualityItem<Encoding>, ()> = "chunked".parse(); assert_eq!(x.unwrap(), QualityItem{ item: Chunked, quality: 1f32, }); } #[test] fn test_quality_item_from_str2() { - let x: Option<QualityItem<Encoding>> = "chunked; q=1".parse(); + let x: Result<QualityItem<Encoding>, ()> = "chunked; q=1".parse(); assert_eq!(x.unwrap(), QualityItem{ item: Chunked, quality: 1f32, }); } #[test] fn test_quality_item_from_str3() { - let x: Option<QualityItem<Encoding>> = "gzip; q=0.5".parse(); + let x: Result<QualityItem<Encoding>, ()> = "gzip; q=0.5".parse(); assert_eq!(x.unwrap(), QualityItem{ item: Gzip, quality: 0.5f32, }); } #[test] fn test_quality_item_from_str4() { - let x: Option<QualityItem<Encoding>> = "gzip; q=0.273".parse(); + let x: Result<QualityItem<Encoding>, ()> = "gzip; q=0.273".parse(); assert_eq!(x.unwrap(), QualityItem{ item: Gzip, quality: 0.273f32, }); } #[test] fn test_quality_item_from_str5() { - let x: Option<QualityItem<Encoding>> = "gzip; q=0.2739999".parse(); - assert_eq!(x, None); + let x: Result<QualityItem<Encoding>, ()> = "gzip; q=0.2739999".parse(); + assert_eq!(x, Err(())); } diff --git a/src/method.rs b/src/method.rs --- a/src/method.rs +++ b/src/method.rs @@ -127,8 +128,8 @@ mod tests { #[test] fn test_from_str() { - assert_eq!(Some(Get), FromStr::from_str("GET")); - assert_eq!(Some(Extension("MOVE".to_string())), + assert_eq!(Ok(Get), FromStr::from_str("GET")); + assert_eq!(Ok(Extension("MOVE".to_string())), FromStr::from_str("MOVE")); }
fix(rustup): update FromStr
There were the following issues with your Pull Request - Commit: 12746b6076b62dd8167af2670ac345dc2497c36f - Commits must be in the following format: **%{type}(%{scope}): %{description}** Guidelines are available at https://github.com/hyperium/hyper/blob/master/CONTRIBUTING.md --- This message was auto-generated by https://gitcop.com
2015-02-04T02:58:09Z
0.1
e8833c0c894a2b87b5d9b48b07858ec7fc890b7a
hyperium/hyper
289
hyperium__hyper-289
[ "252" ]
e9af13c3a6b1de4cc1f0774c085bd20ded4d41d6
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,6 @@ keywords = ["http", "hyper", "hyperium"] cookie = "*" log = ">= 0.2.0" mime = "*" -mucell = "*" openssl = "*" rustc-serialize = "*" time = "*" diff --git /dev/null b/src/header/cell.rs new file mode 100644 --- /dev/null +++ b/src/header/cell.rs @@ -0,0 +1,41 @@ +use std::cell::UnsafeCell; +use std::ops::Deref; + +pub struct OptCell<T>(UnsafeCell<Option<T>>); + +impl<T> OptCell<T> { + #[inline] + pub fn new(val: Option<T>) -> OptCell<T> { + OptCell(UnsafeCell::new(val)) + } + + #[inline] + pub fn set(&self, val: T) { + unsafe { + let opt = self.0.get(); + debug_assert!((*opt).is_none()); + *opt = Some(val) + } + } + + #[inline] + pub unsafe fn get_mut(&mut self) -> &mut T { + let opt = &mut *self.0.get(); + opt.as_mut().unwrap() + } +} + +impl<T> Deref for OptCell<T> { + type Target = Option<T>; + #[inline] + fn deref<'a>(&'a self) -> &'a Option<T> { + unsafe { &*self.0.get() } + } +} + +impl<T: Clone> Clone for OptCell<T> { + #[inline] + fn clone(&self) -> OptCell<T> { + OptCell::new((**self).clone()) + } +} diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -16,15 +16,16 @@ use std::iter::FromIterator; use std::borrow::IntoCow; use std::{mem, raw}; -use mucell::MuCell; use uany::{UnsafeAnyExt}; use unicase::UniCase; +use self::cell::OptCell; use {http, HttpResult, HttpError}; pub use self::shared::{Encoding, QualityItem, qitem}; pub use self::common::*; +mod cell; mod common; mod shared; pub mod parsing; diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -115,7 +116,7 @@ fn header_name<T: Header>() -> &'static str { /// A map of header fields on requests and responses. #[derive(Clone)] pub struct Headers { - data: HashMap<HeaderName, MuCell<Item>> + data: HashMap<HeaderName, Item> } // To prevent DOS from a server sending a never ending header. diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -146,15 +147,10 @@ impl Headers { } let name = UniCase(Owned(name)); let mut item = match headers.data.entry(name) { - Entry::Vacant(entry) => entry.insert(MuCell::new(Item::raw(vec![]))), + Entry::Vacant(entry) => entry.insert(Item::new_raw(vec![])), Entry::Occupied(entry) => entry.into_mut() }; - - match &mut item.borrow_mut().raw { - &mut Some(ref mut raw) => raw.push(value), - // Unreachable - _ => {} - }; + item.mut_raw().push(value); }, None => break, } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -167,7 +163,7 @@ impl Headers { /// The field is determined by the type of the value being set. pub fn set<H: Header + HeaderFormat>(&mut self, value: H) { self.data.insert(UniCase(Borrowed(header_name::<H>())), - MuCell::new(Item::typed(Box::new(value)))); + Item::new_typed(Box::new(value))); } /// Access the raw value of a header. diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -186,19 +182,15 @@ impl Headers { // FIXME(reem): Find a better way to do this lookup without find_equiv. .get(&UniCase(Borrowed(unsafe { mem::transmute::<&str, &str>(name) }))) .and_then(|item| { - if let Some(ref raw) = item.borrow().raw { - return unsafe { mem::transmute(Some(&raw[])) }; + if let Some(ref raw) = *item.raw { + return Some(&raw[]); } - let worked = item.try_mutate(|item| { - let raw = vec![item.typed.as_ref().unwrap().to_string().into_bytes()]; - item.raw = Some(raw); - }); - debug_assert!(worked, "item.try_mutate should return true"); + let raw = vec![item.typed.as_ref().unwrap().to_string().into_bytes()]; + item.raw.set(raw); - let item = item.borrow(); let raw = item.raw.as_ref().unwrap(); - unsafe { mem::transmute(Some(&raw[])) } + Some(&raw[]) }) } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -212,14 +204,14 @@ impl Headers { /// headers.set_raw("content-length", vec![b"5".to_vec()]); /// ``` pub fn set_raw<K: IntoCow<'static, String, str>>(&mut self, name: K, value: Vec<Vec<u8>>) { - self.data.insert(UniCase(name.into_cow()), MuCell::new(Item::raw(value))); + self.data.insert(UniCase(name.into_cow()), Item::new_raw(value)); } /// Get a reference to the header field's value, if it exists. pub fn get<H: Header + HeaderFormat>(&self) -> Option<&H> { self.get_or_parse::<H>().map(|item| { unsafe { - mem::transmute::<&H, &H>(downcast(&*item.borrow())) + downcast(&*item) } }) } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -227,15 +219,15 @@ impl Headers { /// Get a mutable reference to the header field's value, if it exists. pub fn get_mut<H: Header + HeaderFormat>(&mut self) -> Option<&mut H> { self.get_or_parse_mut::<H>().map(|item| { - unsafe { downcast_mut(item.borrow_mut()) } + unsafe { downcast_mut(item) } }) } - fn get_or_parse<H: Header + HeaderFormat>(&self) -> Option<&MuCell<Item>> { + fn get_or_parse<H: Header + HeaderFormat>(&self) -> Option<&Item> { self.data.get(&UniCase(Borrowed(header_name::<H>()))).and_then(get_or_parse::<H>) } - fn get_or_parse_mut<H: Header + HeaderFormat>(&mut self) -> Option<&mut MuCell<Item>> { + fn get_or_parse_mut<H: Header + HeaderFormat>(&mut self) -> Option<&mut Item> { self.data.get_mut(&UniCase(Borrowed(header_name::<H>()))).and_then(get_or_parse_mut::<H>) } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -299,7 +291,7 @@ impl fmt::Debug for Headers { /// An `Iterator` over the fields in a `Headers` map. pub struct HeadersItems<'a> { - inner: Iter<'a, HeaderName, MuCell<Item>> + inner: Iter<'a, HeaderName, Item> } impl<'a> Iterator for HeadersItems<'a> { diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -314,7 +306,7 @@ impl<'a> Iterator for HeadersItems<'a> { } /// Returned with the `HeadersItems` iterator. -pub struct HeaderView<'a>(&'a HeaderName, &'a MuCell<Item>); +pub struct HeaderView<'a>(&'a HeaderName, &'a Item); impl<'a> HeaderView<'a> { /// Check if a HeaderView is a certain Header. diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -334,7 +326,7 @@ impl<'a> HeaderView<'a> { pub fn value<H: Header + HeaderFormat>(&self) -> Option<&'a H> { get_or_parse::<H>(self.1).map(|item| { unsafe { - mem::transmute::<&H, &H>(downcast(&*item.borrow())) + downcast(&*item) } }) } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -342,13 +334,13 @@ impl<'a> HeaderView<'a> { /// Get just the header value as a String. #[inline] pub fn value_string(&self) -> String { - (*self.1.borrow()).to_string() + (*self.1).to_string() } } impl<'a> fmt::Display for HeaderView<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}: {}", self.0, *self.1.borrow()) + write!(f, "{}: {}", self.0, *self.1) } } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -376,29 +368,47 @@ impl<'a> FromIterator<HeaderView<'a>> for Headers { #[derive(Clone)] struct Item { - raw: Option<Vec<Vec<u8>>>, - typed: Option<Box<HeaderFormat + Send + Sync>> + raw: OptCell<Vec<Vec<u8>>>, + typed: OptCell<Box<HeaderFormat + Send + Sync>> } impl Item { - fn raw(data: Vec<Vec<u8>>) -> Item { + #[inline] + fn new_raw(data: Vec<Vec<u8>>) -> Item { Item { - raw: Some(data), - typed: None, + raw: OptCell::new(Some(data)), + typed: OptCell::new(None), } } - fn typed(ty: Box<HeaderFormat + Send + Sync>) -> Item { + #[inline] + fn new_typed(ty: Box<HeaderFormat + Send + Sync>) -> Item { Item { - raw: None, - typed: Some(ty), + raw: OptCell::new(None), + typed: OptCell::new(Some(ty)), } } + #[inline] + fn mut_raw(&mut self) -> &mut Vec<Vec<u8>> { + self.typed = OptCell::new(None); + unsafe { + self.raw.get_mut() + } + } + + #[inline] + fn mut_typed(&mut self) -> &mut Box<HeaderFormat + Send + Sync> { + self.raw = OptCell::new(None); + unsafe { + self.typed.get_mut() + } + } } -fn get_or_parse<H: Header + HeaderFormat>(item: &MuCell<Item>) -> Option<&MuCell<Item>> { - match item.borrow().typed { + +fn get_or_parse<H: Header + HeaderFormat>(item: &Item) -> Option<&Item> { + match *item.typed { Some(ref typed) if typed.is::<H>() => return Some(item), Some(ref typed) => { warn!("attempted to access {:?} as wrong type", typed); diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -407,17 +417,16 @@ fn get_or_parse<H: Header + HeaderFormat>(item: &MuCell<Item>) -> Option<&MuCell _ => () } - let worked = item.try_mutate(parse::<H>); - debug_assert!(worked, "item.try_mutate should return true"); - if item.borrow().typed.is_some() { + parse::<H>(item); + if item.typed.is_some() { Some(item) } else { None } } -fn get_or_parse_mut<H: Header + HeaderFormat>(item: &mut MuCell<Item>) -> Option<&mut MuCell<Item>> { - let is_correct_type = match item.borrow().typed { +fn get_or_parse_mut<H: Header + HeaderFormat>(item: &mut Item) -> Option<&mut Item> { + let is_correct_type = match *item.typed { Some(ref typed) if typed.is::<H>() => Some(true), Some(ref typed) => { warn!("attempted to access {:?} as wrong type", typed); diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -432,37 +441,39 @@ fn get_or_parse_mut<H: Header + HeaderFormat>(item: &mut MuCell<Item>) -> Option None => () } - parse::<H>(item.borrow_mut()); - if item.borrow().typed.is_some() { + parse::<H>(&item); + if item.typed.is_some() { Some(item) } else { None } } -fn parse<H: Header + HeaderFormat>(item: &mut Item) { - item.typed = match item.raw { +fn parse<H: Header + HeaderFormat>(item: &Item) { + match *item.raw { Some(ref raw) => match Header::parse_header(&raw[]) { - Some::<H>(h) => Some(box h as Box<HeaderFormat + Send + Sync>), - None => None + Some::<H>(h) => item.typed.set(box h as Box<HeaderFormat + Send + Sync>), + None => () }, None => unreachable!() - }; + } } +#[inline] unsafe fn downcast<H: Header + HeaderFormat>(item: &Item) -> &H { item.typed.as_ref().expect("item.typed must be set").downcast_ref_unchecked() } +#[inline] unsafe fn downcast_mut<H: Header + HeaderFormat>(item: &mut Item) -> &mut H { - item.typed.as_mut().expect("item.typed must be set").downcast_mut_unchecked() + item.mut_typed().downcast_mut_unchecked() } impl fmt::Display for Item { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - match self.typed { + match *self.typed { Some(ref h) => h.fmt_header(fmt), - None => match self.raw { + None => match *self.raw { Some(ref raw) => { for part in raw.iter() { match from_utf8(&part[]) { diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -483,12 +494,14 @@ impl fmt::Display for Item { impl fmt::Debug for Box<HeaderFormat + Send + Sync> { + #[inline] fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { (**self).fmt_header(fmt) } } impl fmt::Display for Box<HeaderFormat + Send + Sync> { + #[inline] fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { (**self).fmt_header(fmt) } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -502,12 +515,14 @@ impl fmt::Display for Box<HeaderFormat + Send + Sync> { pub struct HeaderFormatter<'a, H: HeaderFormat>(pub &'a H); impl<'a, H: HeaderFormat> fmt::Display for HeaderFormatter<'a, H> { + #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt_header(f) } } impl<'a, H: HeaderFormat> fmt::Debug for HeaderFormatter<'a, H> { + #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt_header(f) }
diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -695,37 +710,58 @@ mod tests { } #[bench] - fn bench_header_get(b: &mut Bencher) { + fn bench_headers_new(b: &mut Bencher) { + b.iter(|| { + let mut h = Headers::new(); + h.set(ContentLength(11)); + h + }) + } + + #[bench] + fn bench_headers_from_raw(b: &mut Bencher) { + b.iter(|| Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap()) + } + + #[bench] + fn bench_headers_get(b: &mut Bencher) { let mut headers = Headers::new(); headers.set(ContentLength(11)); b.iter(|| assert_eq!(headers.get::<ContentLength>(), Some(&ContentLength(11)))) } #[bench] - fn bench_header_get_miss(b: &mut Bencher) { + fn bench_headers_get_miss(b: &mut Bencher) { let headers = Headers::new(); b.iter(|| assert!(headers.get::<ContentLength>().is_none())) } #[bench] - fn bench_header_set(b: &mut Bencher) { + fn bench_headers_set(b: &mut Bencher) { let mut headers = Headers::new(); b.iter(|| headers.set(ContentLength(12))) } #[bench] - fn bench_header_has(b: &mut Bencher) { + fn bench_headers_has(b: &mut Bencher) { let mut headers = Headers::new(); headers.set(ContentLength(11)); b.iter(|| assert!(headers.has::<ContentLength>())) } #[bench] - fn bench_header_view_is(b: &mut Bencher) { + fn bench_headers_view_is(b: &mut Bencher) { let mut headers = Headers::new(); headers.set(ContentLength(11)); let mut iter = headers.iter(); let view = iter.next().unwrap(); b.iter(|| assert!(view.is::<ContentLength>())) } + + #[bench] + fn bench_headers_fmt(b: &mut Bencher) { + let mut headers = Headers::new(); + headers.set(ContentLength(11)); + b.iter(|| headers.to_string()) + } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -134,7 +134,6 @@ extern crate openssl; #[cfg(test)] extern crate test; extern crate "unsafe-any" as uany; extern crate cookie; -extern crate mucell; extern crate unicase; pub use std::old_io::net::ip::{SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr, Port};
Mucell often breaks Hyper Mucell breaks Hyper really often. Like for example just now: https://travis-ci.org/hyperium/hyper/builds/47357537 I do not really know what mucell makes it superior to the standard library types, but for me it looks like it only provides a minor speed increasement. So do we really need it or could we switch to another builtin type?
@pyfisch it's fixed now, but I do see your concern. I guess a benchmark (of hyper) using both mucell and refcell would be useful to know if it's worth using something outside of std.
2015-02-02T20:16:36Z
0.1
e8833c0c894a2b87b5d9b48b07858ec7fc890b7a
hyperium/hyper
283
hyperium__hyper-283
[ "281" ]
93821fc731fe00295dad13b488b8e4b4097d15a8
diff --git a/src/header/shared/quality_item.rs b/src/header/shared/quality_item.rs --- a/src/header/shared/quality_item.rs +++ b/src/header/shared/quality_item.rs @@ -28,7 +28,12 @@ impl<T> QualityItem<T> { impl<T: fmt::Display> fmt::Display for QualityItem<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}; q={}", self.item, format!("{:.3}", self.quality).trim_right_matches(['0', '.'].as_slice())) + if self.quality == 1.0 { + write!(f, "{}", self.item) + } else { + write!(f, "{}; q={}", self.item, + format!("{:.3}", self.quality).trim_right_matches(&['0', '.'][])) + } } }
diff --git a/src/header/shared/quality_item.rs b/src/header/shared/quality_item.rs --- a/src/header/shared/quality_item.rs +++ b/src/header/shared/quality_item.rs @@ -79,7 +84,7 @@ pub fn qitem<T>(item: T) -> QualityItem<T> { #[test] fn test_quality_item_show1() { let x = qitem(Chunked); - assert_eq!(format!("{}", x), "chunked; q=1"); + assert_eq!(format!("{}", x), "chunked"); } #[test] fn test_quality_item_show2() {
Don't print "; q=1" when QualityItem is set to 1 See https://github.com/servo/servo/issues/4734
2015-01-28T05:53:47Z
0.1
e8833c0c894a2b87b5d9b48b07858ec7fc890b7a
hyperium/hyper
267
hyperium__hyper-267
[ "237" ]
fb92a260c0506f9d1764504527648a7bd7be3560
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -23,6 +23,7 @@ pub use self::host::Host; pub use self::if_modified_since::IfModifiedSince; pub use self::last_modified::LastModified; pub use self::location::Location; +pub use self::pragma::Pragma; pub use self::referer::Referer; pub use self::server::Server; pub use self::set_cookie::SetCookie; diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -157,6 +158,7 @@ mod host; mod last_modified; mod if_modified_since; mod location; +mod pragma; mod referer; mod server; mod set_cookie; diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -164,4 +166,3 @@ mod transfer_encoding; mod upgrade; mod user_agent; mod vary; -
diff --git /dev/null b/src/header/common/pragma.rs new file mode 100644 --- /dev/null +++ b/src/header/common/pragma.rs @@ -0,0 +1,61 @@ +use std::fmt; +use std::ascii::AsciiExt; + +use header::{Header, HeaderFormat, parsing}; + +/// The `Pragma` header defined by HTTP/1.0. +/// +/// > The "Pragma" header field allows backwards compatibility with +/// > HTTP/1.0 caches, so that clients can specify a "no-cache" request +/// > that they will understand (as Cache-Control was not defined until +/// > HTTP/1.1). When the Cache-Control header field is also present and +/// > understood in a request, Pragma is ignored. + +/// > In HTTP/1.0, Pragma was defined as an extensible field for +/// > implementation-specified directives for recipients. This +/// > specification deprecates such extensions to improve interoperability. +/// +/// Spec: https://tools.ietf.org/html/rfc7234#section-5.4 +#[derive(Clone, PartialEq, Debug)] +pub enum Pragma { + /// Corresponds to the `no-cache` value. + NoCache, + /// Every value other than `no-cache`. + Ext(String), +} + +impl Header for Pragma { + fn header_name() -> &'static str { + "Pragma" + } + + fn parse_header(raw: &[Vec<u8>]) -> Option<Pragma> { + parsing::from_one_raw_str(raw).and_then(|s: String| { + let slice = &s.to_ascii_lowercase()[]; + match slice { + "" => None, + "no-cache" => Some(Pragma::NoCache), + _ => Some(Pragma::Ext(s)), + } + }) + } +} + +impl HeaderFormat for Pragma { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Pragma::NoCache => write!(f, "no-cache"), + Pragma::Ext(ref string) => write!(f, "{}", string), + } + } +} + +#[test] +fn test_parse_header() { + let a: Pragma = Header::parse_header([b"no-cache".to_vec()].as_slice()).unwrap(); + let b = Pragma::NoCache; + assert_eq!(a, b); + let c: Pragma = Header::parse_header([b"FoObar".to_vec()].as_slice()).unwrap(); + let d = Pragma::Ext("FoObar".to_string()); + assert_eq!(c, d); +}
add Pragma header This is needed for https://github.com/servo/servo/pull/4117/. Spec: https://tools.ietf.org/html/rfc7234#section-5.4
2015-01-22T21:12:20Z
0.1
e8833c0c894a2b87b5d9b48b07858ec7fc890b7a
hyperium/hyper
213
hyperium__hyper-213
[ "211", "211" ]
27b262c22678ed785ed269da4f4a4ddc154526d1
diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -544,6 +544,9 @@ pub fn read_header<R: Reader>(stream: &mut R) -> HttpResult<Option<RawHeaderLine } }; } + // Remove optional trailing whitespace + let real_len = value.len() - value.iter().rev().take_while(|&&x| b' ' == x).count(); + value.truncate(real_len); debug!("header value = {}", value[].to_ascii());
diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -594,6 +594,13 @@ mod tests { assert!(headers.get::<CrazyLength>().is_none()); } + #[test] + fn test_trailing_whitespace() { + let headers = Headers::from_raw(&mut mem("Content-Length: 10 \r\n\r\n")).unwrap(); + let ContentLength(_) = *headers.get::<ContentLength>().unwrap(); + assert!(headers.get::<CrazyLength>().is_none()); + } + #[test] fn test_multiple_reads() { let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap();
Whitespace trailing header values causes incorrect parsing of header field [RFC7230](https://tools.ietf.org/html/rfc7230#section-3.2) allows optional trailing whitespace for header fields. So `Content-Length: 10 \r\nContent-Type: text/plain\r\n\r\n` is a valid header. It causes the parser to fail, it thinks the value of `Content-Length` is invalid. Whitespace trailing header values causes incorrect parsing of header field [RFC7230](https://tools.ietf.org/html/rfc7230#section-3.2) allows optional trailing whitespace for header fields. So `Content-Length: 10 \r\nContent-Type: text/plain\r\n\r\n` is a valid header. It causes the parser to fail, it thinks the value of `Content-Length` is invalid.
True! It seems like in [read_header](https://github.com/hyperium/hyper/blob/master/src/http.rs#L509) should trim the OWS. True! It seems like in [read_header](https://github.com/hyperium/hyper/blob/master/src/http.rs#L509) should trim the OWS.
2014-12-29T11:18:29Z
0.0
27b262c22678ed785ed269da4f4a4ddc154526d1
hyperium/hyper
206
hyperium__hyper-206
[ "205" ]
33f61213ce9d58722647a03f2f04514c1c14ade9
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,8 @@ typeable = "*" cookie = "*" time = "*" mucell = "*" +log = "*" +rustc-serialize = "*" [dev-dependencies] curl = "*" diff --git a/src/header/common/accept.rs b/src/header/common/accept.rs --- a/src/header/common/accept.rs +++ b/src/header/common/accept.rs @@ -34,15 +34,15 @@ impl Header for Accept { let mut mimes: Vec<Mime> = vec![]; for mimes_raw in raw.iter() { match from_utf8(mimes_raw.as_slice()) { - Some(mimes_str) => { + Ok(mimes_str) => { for mime_str in mimes_str.split(',') { - match from_str(mime_str.trim()) { + match mime_str.trim().parse() { Some(mime) => mimes.push(mime), None => return None } } }, - None => return None + Err(_) => return None }; } diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -27,11 +27,11 @@ impl<S: Scheme> Header for Authorization<S> { fn parse_header(raw: &[Vec<u8>]) -> Option<Authorization<S>> { if raw.len() == 1 { match (from_utf8(unsafe { raw[].unsafe_get(0)[] }), Scheme::scheme(None::<S>)) { - (Some(header), Some(scheme)) + (Ok(header), Some(scheme)) if header.starts_with(scheme) && header.len() > scheme.len() + 1 => { - from_str::<S>(header[scheme.len() + 1..]).map(|s| Authorization(s)) + header[scheme.len() + 1..].parse::<S>().map(|s| Authorization(s)) }, - (Some(header), None) => from_str::<S>(header).map(|s| Authorization(s)), + (Ok(header), None) => header.parse::<S>().map(|s| Authorization(s)), _ => None } } else { diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -111,11 +111,11 @@ impl FromStr for Basic { Ok(text) => { let mut parts = text[].split(':'); let user = match parts.next() { - Some(part) => part.into_string(), + Some(part) => part.to_string(), None => return None }; let password = match parts.next() { - Some(part) => Some(part.into_string()), + Some(part) => Some(part.to_string()), None => None }; Some(Basic { diff --git a/src/header/common/cache_control.rs b/src/header/common/cache_control.rs --- a/src/header/common/cache_control.rs +++ b/src/header/common/cache_control.rs @@ -110,14 +110,14 @@ impl FromStr for CacheDirective { "" => None, _ => match s.find('=') { Some(idx) if idx+1 < s.len() => match (s[..idx], s[idx+1..].trim_chars('"')) { - ("max-age" , secs) => from_str::<uint>(secs).map(MaxAge), - ("max-stale", secs) => from_str::<uint>(secs).map(MaxStale), - ("min-fresh", secs) => from_str::<uint>(secs).map(MinFresh), - ("s-maxage", secs) => from_str::<uint>(secs).map(SMaxAge), - (left, right) => Some(Extension(left.into_string(), Some(right.into_string()))) + ("max-age" , secs) => secs.parse().map(MaxAge), + ("max-stale", secs) => secs.parse().map(MaxStale), + ("min-fresh", secs) => secs.parse().map(MinFresh), + ("s-maxage", secs) => secs.parse().map(SMaxAge), + (left, right) => Some(Extension(left.to_string(), Some(right.to_string()))) }, Some(_) => None, - None => Some(Extension(s.into_string(), None)) + None => Some(Extension(s.to_string(), None)) } } } diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -1,6 +1,6 @@ use header::{Header, HeaderFormat}; use std::fmt::{mod, Show}; -use std::str::{from_utf8, from_str}; +use std::str::from_utf8; use cookie::Cookie; use cookie::CookieJar; diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -27,15 +27,15 @@ impl Header for Cookies { let mut cookies = Vec::with_capacity(raw.len()); for cookies_raw in raw.iter() { match from_utf8(cookies_raw[]) { - Some(cookies_str) => { + Ok(cookies_str) => { for cookie_str in cookies_str.split(';') { - match from_str(cookie_str.trim()) { + match cookie_str.trim().parse() { Some(cookie) => cookies.push(cookie), None => return None } } }, - None => return None + Err(_) => return None }; } diff --git a/src/header/common/etag.rs b/src/header/common/etag.rs --- a/src/header/common/etag.rs +++ b/src/header/common/etag.rs @@ -55,7 +55,7 @@ impl Header for Etag { if check_slice_validity(slice.slice_chars(1, length-1)) { return Some(Etag { weak: false, - tag: slice.slice_chars(1, length-1).into_string() + tag: slice.slice_chars(1, length-1).to_string() }); } else { return None; diff --git a/src/header/common/etag.rs b/src/header/common/etag.rs --- a/src/header/common/etag.rs +++ b/src/header/common/etag.rs @@ -66,7 +66,7 @@ impl Header for Etag { if check_slice_validity(slice.slice_chars(3, length-1)) { return Some(Etag { weak: true, - tag: slice.slice_chars(3, length-1).into_string() + tag: slice.slice_chars(3, length-1).to_string() }); } else { return None; diff --git a/src/header/common/host.rs b/src/header/common/host.rs --- a/src/header/common/host.rs +++ b/src/header/common/host.rs @@ -46,7 +46,7 @@ impl Header for Host { }; let port = match idx { - Some(idx) => from_str::<u16>(s[].slice_from(idx + 1)), + Some(idx) => s[].slice_from(idx + 1).parse(), None => None }; diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs --- a/src/header/common/set_cookie.rs +++ b/src/header/common/set_cookie.rs @@ -24,8 +24,8 @@ impl Header for SetCookie { let mut set_cookies = Vec::with_capacity(raw.len()); for set_cookies_raw in raw.iter() { match from_utf8(set_cookies_raw[]) { - Some(s) if !s.is_empty() => { - match from_str(s) { + Ok(s) if !s.is_empty() => { + match s.parse() { Some(cookie) => set_cookies.push(cookie), None => () } diff --git a/src/header/common/util.rs b/src/header/common/util.rs --- a/src/header/common/util.rs +++ b/src/header/common/util.rs @@ -11,8 +11,8 @@ pub fn from_one_raw_str<T: FromStr>(raw: &[Vec<u8>]) -> Option<T> { } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. match from_utf8(unsafe { raw[].unsafe_get(0)[] }) { - Some(s) => FromStr::from_str(s), - None => None + Ok(s) => FromStr::from_str(s), + Err(_) => None } } diff --git a/src/header/common/util.rs b/src/header/common/util.rs --- a/src/header/common/util.rs +++ b/src/header/common/util.rs @@ -29,13 +29,13 @@ pub fn from_comma_delimited<T: FromStr>(raw: &[Vec<u8>]) -> Option<Vec<T>> { /// Reads a comma-delimited raw string into a Vec. pub fn from_one_comma_delimited<T: FromStr>(raw: &[u8]) -> Option<Vec<T>> { match from_utf8(raw) { - Some(s) => { + Ok(s) => { Some(s.as_slice() .split([',', ' '].as_slice()) - .filter_map(from_str) + .filter_map(FromStr::from_str) .collect()) } - None => None + Err(_) => None } } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -12,7 +12,7 @@ use std::intrinsics::TypeId; use std::raw::TraitObject; use std::str::{SendStr, FromStr}; use std::collections::HashMap; -use std::collections::hash_map::{Entries, Occupied, Vacant}; +use std::collections::hash_map::{Entries, Entry}; use std::{hash, mem}; use mucell::MuCell; diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -130,8 +130,8 @@ impl Headers { debug!("raw header: {}={}", name, value[].to_ascii()); let name = CaseInsensitive(Owned(name)); let mut item = match headers.data.entry(name) { - Vacant(entry) => entry.set(MuCell::new(Item::raw(vec![]))), - Occupied(entry) => entry.into_mut() + Entry::Vacant(entry) => entry.set(MuCell::new(Item::raw(vec![]))), + Entry::Occupied(entry) => entry.into_mut() }; match &mut item.borrow_mut().raw { diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -4,7 +4,7 @@ use std::cmp::min; use std::fmt; use std::io::{mod, Reader, IoResult, BufWriter}; use std::num::from_u16; -use std::str::{mod, SendStr}; +use std::str::{mod, SendStr, FromStr}; use url::Url; use url::ParseError as UrlError; diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -260,7 +260,7 @@ impl<W: Writer> Writer for HttpWriter<W> { Err(io::IoError { kind: io::ShortWrite(bytes), desc: "EmptyWriter cannot write any bytes", - detail: Some("Cannot include a body with this kind of message".into_string()) + detail: Some("Cannot include a body with this kind of message".to_string()) }) } } diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -397,7 +397,7 @@ pub fn read_method<R: Reader>(stream: &mut R) -> HttpResult<method::Method> { (Some(method), _) => Ok(method), (None, ext) => { // We already checked that the buffer is ASCII - Ok(method::Method::Extension(unsafe { str::from_utf8_unchecked(ext) }.trim().into_string())) + Ok(method::Method::Extension(unsafe { str::from_utf8_unchecked(ext) }.trim().to_string())) }, } } diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -622,7 +622,7 @@ pub fn read_status<R: Reader>(stream: &mut R) -> HttpResult<RawStatus> { try!(stream.read_byte()), ]; - let code = match str::from_utf8(code.as_slice()).and_then(from_str::<u16>) { + let code = match str::from_utf8(code.as_slice()).ok().and_then(FromStr::from_str) { Some(num) => num, None => return Err(HttpStatusError) }; diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -662,8 +662,8 @@ pub fn read_status<R: Reader>(stream: &mut R) -> HttpResult<RawStatus> { } let reason = match str::from_utf8(buf[]) { - Some(s) => s.trim(), - None => return Err(HttpStatusError) + Ok(s) => s.trim(), + Err(_) => return Err(HttpStatusError) }; let reason = match from_u16::<StatusCode>(code) { diff --git a/src/http.rs b/src/http.rs --- a/src/http.rs +++ b/src/http.rs @@ -672,10 +672,10 @@ pub fn read_status<R: Reader>(stream: &mut R) -> HttpResult<RawStatus> { if phrase == reason { Borrowed(phrase) } else { - Owned(reason.into_string()) + Owned(reason.to_string()) } } - _ => Owned(reason.into_string()) + _ => Owned(reason.to_string()) }, None => return Err(HttpStatusError) }; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -125,7 +125,7 @@ //! implement `Reader` and can be read to get the data out of a `Response`. //! -extern crate serialize; +extern crate "rustc-serialize" as serialize; extern crate time; extern crate url; extern crate openssl; diff --git a/src/mock.rs b/src/mock.rs --- a/src/mock.rs +++ b/src/mock.rs @@ -62,7 +62,7 @@ impl Writer for MockStream { impl NetworkStream for MockStream { fn peer_name(&mut self) -> IoResult<SocketAddr> { - Ok(from_str("127.0.0.1:1337").unwrap()) + Ok("127.0.0.1:1337".parse().unwrap()) } } diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -68,7 +68,7 @@ impl<L: NetworkListener<S, A>, S: NetworkStream, A: NetworkAcceptor<S>> Server<L let acceptor = try!(listener.listen()); let mut captured = acceptor.clone(); - let guard = Builder::new().name("hyper acceptor".into_string()).spawn(move || { + let guard = Builder::new().name("hyper acceptor".to_string()).spawn(move || { let handler = Arc::new(handler); debug!("threads = {}", threads); let pool = TaskPool::new(threads); diff --git a/src/server/mod.rs b/src/server/mod.rs --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -179,7 +179,7 @@ pub trait Handler: Sync + Send { fn handle(&self, Request, Response<Fresh>); } -impl Handler for fn(Request, Response<Fresh>) { +impl<F> Handler for F where F: Fn(Request, Response<Fresh>), F: Sync + Send { fn handle(&self, req: Request, res: Response<Fresh>) { (*self)(req, res) }
diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -381,7 +381,7 @@ mod tests { client.set_redirect_policy(RedirectPolicy::FollowAll); let res = client.get("http://127.0.0.1").send().unwrap(); - assert_eq!(res.headers.get(), Some(&Server("mock3".into_string()))); + assert_eq!(res.headers.get(), Some(&Server("mock3".to_string()))); } #[test] diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -389,7 +389,7 @@ mod tests { let mut client = Client::with_connector(MockRedirectPolicy); client.set_redirect_policy(RedirectPolicy::FollowNone); let res = client.get("http://127.0.0.1").send().unwrap(); - assert_eq!(res.headers.get(), Some(&Server("mock1".into_string()))); + assert_eq!(res.headers.get(), Some(&Server("mock1".to_string()))); } #[test] diff --git a/src/client/mod.rs b/src/client/mod.rs --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -400,7 +400,7 @@ mod tests { let mut client = Client::with_connector(MockRedirectPolicy); client.set_redirect_policy(RedirectPolicy::FollowIf(follow_if)); let res = client.get("http://127.0.0.1").send().unwrap(); - assert_eq!(res.headers.get(), Some(&Server("mock2".into_string()))); + assert_eq!(res.headers.get(), Some(&Server("mock2".to_string()))); } } diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -149,7 +149,7 @@ mod tests { #[test] fn test_raw_auth() { let mut headers = Headers::new(); - headers.set(Authorization("foo bar baz".into_string())); + headers.set(Authorization("foo bar baz".to_string())); assert_eq!(headers.to_string(), "Authorization: foo bar baz\r\n".to_string()); } diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -162,8 +162,8 @@ mod tests { #[test] fn test_basic_auth() { let mut headers = Headers::new(); - headers.set(Authorization(Basic { username: "Aladdin".into_string(), password: Some("open sesame".into_string()) })); - assert_eq!(headers.to_string(), "Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n".into_string()); + headers.set(Authorization(Basic { username: "Aladdin".to_string(), password: Some("open sesame".to_string()) })); + assert_eq!(headers.to_string(), "Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n".to_string()); } #[test] diff --git a/src/header/common/etag.rs b/src/header/common/etag.rs --- a/src/header/common/etag.rs +++ b/src/header/common/etag.rs @@ -100,31 +100,31 @@ mod tests { etag = Header::parse_header([b"\"foobar\"".to_vec()].as_slice()); assert_eq!(etag, Some(Etag { weak: false, - tag: "foobar".into_string() + tag: "foobar".to_string() })); etag = Header::parse_header([b"\"\"".to_vec()].as_slice()); assert_eq!(etag, Some(Etag { weak: false, - tag: "".into_string() + tag: "".to_string() })); etag = Header::parse_header([b"W/\"weak-etag\"".to_vec()].as_slice()); assert_eq!(etag, Some(Etag { weak: true, - tag: "weak-etag".into_string() + tag: "weak-etag".to_string() })); etag = Header::parse_header([b"W/\"\x65\x62\"".to_vec()].as_slice()); assert_eq!(etag, Some(Etag { weak: true, - tag: "\u{0065}\u{0062}".into_string() + tag: "\u{0065}\u{0062}".to_string() })); etag = Header::parse_header([b"W/\"\"".to_vec()].as_slice()); assert_eq!(etag, Some(Etag { weak: true, - tag: "".into_string() + tag: "".to_string() })); } diff --git a/src/header/common/host.rs b/src/header/common/host.rs --- a/src/header/common/host.rs +++ b/src/header/common/host.rs @@ -82,14 +82,14 @@ mod tests { fn test_host() { let host = Header::parse_header([b"foo.com".to_vec()].as_slice()); assert_eq!(host, Some(Host { - hostname: "foo.com".into_string(), + hostname: "foo.com".to_string(), port: None })); let host = Header::parse_header([b"foo.com:8080".to_vec()].as_slice()); assert_eq!(host, Some(Host { - hostname: "foo.com".into_string(), + hostname: "foo.com".to_string(), port: Some(8080) })); } diff --git a/src/header/common/vary.rs b/src/header/common/vary.rs --- a/src/header/common/vary.rs +++ b/src/header/common/vary.rs @@ -42,7 +42,7 @@ impl HeaderFormat for Vary { #[cfg(test)] mod tests { use super::Vary; - use header::{Header, CaseInsensitive}; + use header::Header; #[test] fn test_vary() { diff --git a/src/header/common/vary.rs b/src/header/common/vary.rs --- a/src/header/common/vary.rs +++ b/src/header/common/vary.rs @@ -52,8 +52,8 @@ mod tests { assert_eq!(vary, Some(Vary::Any)); vary = Header::parse_header([b"etag,cookie,allow".to_vec()].as_slice()); - assert_eq!(vary, Some(Vary::Headers(vec![from_str::<CaseInsensitive>("eTag").unwrap(), - from_str::<CaseInsensitive>("cookIE").unwrap(), - from_str::<CaseInsensitive>("AlLOw").unwrap(),]))); + assert_eq!(vary, Some(Vary::Headers(vec!["eTag".parse().unwrap(), + "cookIE".parse().unwrap(), + "AlLOw".parse().unwrap(),]))); } } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -549,7 +549,7 @@ mod tests { #[test] fn test_accept() { let text_plain = Mime(Text, Plain, vec![]); - let application_vendor = from_str("application/vnd.github.v3.full+json; q=0.5").unwrap(); + let application_vendor = "application/vnd.github.v3.full+json; q=0.5".parse().unwrap(); let accept = Header::parse_header([b"text/plain".to_vec()].as_slice()); assert_eq!(accept, Some(Accept(vec![text_plain.clone()]))); diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -574,8 +574,8 @@ mod tests { } // we JUST checked that raw.len() == 1, so raw[0] WILL exist. match from_utf8(unsafe { raw.as_slice().unsafe_get(0).as_slice() }) { - Some(s) => FromStr::from_str(s), - None => None + Ok(s) => FromStr::from_str(s), + Err(_) => None }.map(|u| CrazyLength(Some(false), u)) } } diff --git a/src/header/mod.rs b/src/header/mod.rs --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -620,7 +620,7 @@ mod tests { fn test_headers_show() { let mut headers = Headers::new(); headers.set(ContentLength(15)); - headers.set(Host { hostname: "foo.bar".into_string(), port: None }); + headers.set(Host { hostname: "foo.bar".to_string(), port: None }); let s = headers.to_string(); // hashmap's iterators have arbitrary order, so we must sort first diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -92,7 +92,7 @@ mod tests { "); let mut req = Request::new(&mut stream, sock!("127.0.0.1:80")).unwrap(); - assert_eq!(req.read_to_string(), Ok("".into_string())); + assert_eq!(req.read_to_string(), Ok("".to_string())); } #[test] diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -105,7 +105,7 @@ mod tests { "); let mut req = Request::new(&mut stream, sock!("127.0.0.1:80")).unwrap(); - assert_eq!(req.read_to_string(), Ok("".into_string())); + assert_eq!(req.read_to_string(), Ok("".to_string())); } #[test] diff --git a/src/server/request.rs b/src/server/request.rs --- a/src/server/request.rs +++ b/src/server/request.rs @@ -118,6 +118,6 @@ mod tests { "); let mut req = Request::new(&mut stream, sock!("127.0.0.1:80")).unwrap(); - assert_eq!(req.read_to_string(), Ok("".into_string())); + assert_eq!(req.read_to_string(), Ok("".to_string())); } }
Multiple matching crates for log I'm not sure if this is a cargo bug, but a rust project that has a log dependency causes hyper to not be compiled. Cargo confuses liblog in rustlib with the liblog that cargo provided. ``` ~/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.0.16/src/lib.rs:132:23: 132:40 error: multiple matching crates for `log` ~/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.0.16/src/lib.rs:132 #[phase(plugin,link)] extern crate log; ^~~~~~~~~~~~~~~~~ note: candidates: note: path: /xxx/target/deps/liblog-58f1f5901694db31.rlib note: crate name: log note: path: /usr/local/lib/rustlib/x86_64-apple-darwin/lib/liblog-4e7c5e5c.dylib note: path: /usr/local/lib/rustlib/x86_64-apple-darwin/lib/liblog-4e7c5e5c.rlib note: crate name: log ``` I think liblog from rustc is deprecated in favor of the one from cargo, so maybe that one should just be used instead?
Same issue here. I've simply made a hello world application which depends on hyper. My Cargo's dependencies looks like this: ``` hyper = "0.0.16" ``` Yep, things moved around. I'm fixing for latest nightly currently.
2014-12-23T21:10:33Z
0.0
27b262c22678ed785ed269da4f4a4ddc154526d1