feat(body): rename Entity to Payload

Closes #1464
This commit is contained in:
Sean McArthur
2018-04-10 15:55:13 -07:00
parent 313f82d971
commit dfdca25c00
18 changed files with 105 additions and 160 deletions

View File

@@ -30,7 +30,7 @@ fn get_one_at_a_time(b: &mut test::Bencher) {
b.iter(move || { b.iter(move || {
client.get(url.clone()) client.get(url.clone())
.and_then(|res| { .and_then(|res| {
res.into_body().into_stream().for_each(|_chunk| { res.into_body().for_each(|_chunk| {
Ok(()) Ok(())
}) })
}) })
@@ -55,7 +55,7 @@ fn post_one_at_a_time(b: &mut test::Bencher) {
*req.method_mut() = Method::POST; *req.method_mut() = Method::POST;
*req.uri_mut() = url.clone(); *req.uri_mut() = url.clone();
client.request(req).and_then(|res| { client.request(req).and_then(|res| {
res.into_body().into_stream().for_each(|_chunk| { res.into_body().for_each(|_chunk| {
Ok(()) Ok(())
}) })
}).wait().expect("client wait"); }).wait().expect("client wait");
@@ -75,7 +75,6 @@ fn spawn_hello(rt: &mut Runtime) -> SocketAddr {
let service = const_service(service_fn(|req: Request<Body>| { let service = const_service(service_fn(|req: Request<Body>| {
req.into_body() req.into_body()
.into_stream()
.concat2() .concat2()
.map(|_| { .map(|_| {
Response::new(Body::from(PHRASE)) Response::new(Body::from(PHRASE))

View File

@@ -40,7 +40,7 @@ fn main() {
println!("Response: {}", res.status()); println!("Response: {}", res.status());
println!("Headers: {:#?}", res.headers()); println!("Headers: {:#?}", res.headers());
res.into_body().into_stream().for_each(|chunk| { res.into_body().for_each(|chunk| {
io::stdout().write_all(&chunk) io::stdout().write_all(&chunk)
.map_err(|e| panic!("example expects stdout is open, error={}", e)) .map_err(|e| panic!("example expects stdout is open, error={}", e))
}) })

View File

@@ -32,7 +32,7 @@ impl Service for ParamExample {
Box::new(futures::future::ok(Response::new(INDEX.into()))) Box::new(futures::future::ok(Response::new(INDEX.into())))
}, },
(&Method::POST, "/post") => { (&Method::POST, "/post") => {
Box::new(req.into_parts().1.into_stream().concat2().map(|b| { Box::new(req.into_body().concat2().map(|b| {
// Parse the request body. form_urlencoded::parse // Parse the request body. form_urlencoded::parse
// always succeeds, but in general parsing may // always succeeds, but in general parsing may
// fail (for example, an invalid post of json), so // fail (for example, an invalid post of json), so

View File

@@ -44,7 +44,7 @@ impl Service for ResponseExamples {
let web_res_future = client.request(req); let web_res_future = client.request(req);
Box::new(web_res_future.map(|web_res| { Box::new(web_res_future.map(|web_res| {
let body = Body::wrap_stream(web_res.into_body().into_stream().map(|b| { let body = Body::wrap_stream(web_res.into_body().map(|b| {
Chunk::from(format!("before: '{:?}'<br>after: '{:?}'", Chunk::from(format!("before: '{:?}'<br>after: '{:?}'",
std::str::from_utf8(LOWERCASE).unwrap(), std::str::from_utf8(LOWERCASE).unwrap(),
std::str::from_utf8(&b).unwrap())) std::str::from_utf8(&b).unwrap()))
@@ -54,7 +54,7 @@ impl Service for ResponseExamples {
}, },
(&Method::POST, "/web_api") => { (&Method::POST, "/web_api") => {
// A web api to run against. Simple upcasing of the body. // A web api to run against. Simple upcasing of the body.
let body = Body::wrap_stream(req.into_body().into_stream().map(|chunk| { let body = Body::wrap_stream(req.into_body().map(|chunk| {
let upper = chunk.iter().map(|byte| byte.to_ascii_uppercase()) let upper = chunk.iter().map(|byte| byte.to_ascii_uppercase())
.collect::<Vec<u8>>(); .collect::<Vec<u8>>();
Chunk::from(upper) Chunk::from(upper)

View File

@@ -13,7 +13,7 @@ use super::Chunk;
type BodySender = mpsc::Sender<Result<Chunk, ::Error>>; type BodySender = mpsc::Sender<Result<Chunk, ::Error>>;
/// This trait represents a streaming body of a `Request` or `Response`. /// This trait represents a streaming body of a `Request` or `Response`.
pub trait Entity { pub trait Payload {
/// A buffer of bytes representing a single chunk of a body. /// A buffer of bytes representing a single chunk of a body.
type Data: AsRef<[u8]>; type Data: AsRef<[u8]>;
@@ -63,7 +63,7 @@ pub trait Entity {
} }
} }
impl<E: Entity> Entity for Box<E> { impl<E: Payload> Payload for Box<E> {
type Data = E::Data; type Data = E::Data;
type Error = E::Error; type Error = E::Error;
@@ -84,43 +84,10 @@ impl<E: Entity> Entity for Box<E> {
} }
} }
/// A wrapper to consume an `Entity` as a futures `Stream`.
#[must_use = "streams do nothing unless polled"]
#[derive(Debug)]
pub struct EntityStream<E> {
is_data_eof: bool,
entity: E,
}
impl<E: Entity> Stream for EntityStream<E> { /// A `Payload` of `Chunk`s, used when receiving bodies.
type Item = E::Data;
type Error = E::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
loop {
if self.is_data_eof {
return self.entity.poll_trailers()
.map(|async| {
async.map(|_opt| {
// drop the trailers and return that Stream is done
None
})
});
}
let opt = try_ready!(self.entity.poll_data());
if let Some(data) = opt {
return Ok(Async::Ready(Some(data)));
} else {
self.is_data_eof = true;
}
}
}
}
/// An `Entity` of `Chunk`s, used when receiving bodies.
/// ///
/// Also a good default `Entity` to use in many applications. /// Also a good default `Payload` to use in many applications.
#[must_use = "streams do nothing unless polled"] #[must_use = "streams do nothing unless polled"]
pub struct Body { pub struct Body {
kind: Kind, kind: Kind,
@@ -229,35 +196,6 @@ impl Body {
Body::new(Kind::Wrapped(Box::new(mapped))) Body::new(Kind::Wrapped(Box::new(mapped)))
} }
/// Convert this `Body` into a `Stream<Item=Chunk, Error=hyper::Error>`.
///
/// # Example
///
/// ```
/// # extern crate futures;
/// # extern crate hyper;
/// # use futures::{Future, Stream};
/// # 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()
/// .map(|buf| {
/// println!("body length: {}", buf.len());
/// });
/// # }
/// # fn main() {}
/// ```
#[inline]
pub fn into_stream(self) -> EntityStream<Body> {
EntityStream {
is_data_eof: false,
entity: self,
}
}
/// Returns if this body was constructed via `Body::empty()`. /// Returns if this body was constructed via `Body::empty()`.
/// ///
/// # Note /// # Note
@@ -345,7 +283,7 @@ impl Default for Body {
} }
} }
impl Entity for Body { impl Payload for Body {
type Data = Chunk; type Data = Chunk;
type Error = ::Error; type Error = ::Error;
@@ -373,6 +311,15 @@ impl Entity for Body {
} }
} }
impl Stream for Body {
type Item = Chunk;
type Error = ::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
self.poll_data()
}
}
impl fmt::Debug for Body { impl fmt::Debug for Body {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Body") f.debug_struct("Body")
@@ -489,10 +436,10 @@ fn test_body_stream_concat() {
let body = Body::from("hello world"); let body = Body::from("hello world");
let total = body.into_stream() let total = body
.concat2() .concat2()
.wait() .wait()
.unwrap(); .unwrap();
assert_eq!(total.as_ref(), b"hello world"); assert_eq!(total.as_ref(), b"hello world");
} }

View File

@@ -15,8 +15,8 @@ use futures::{Async, Future, Poll};
use futures::future::{self, Either}; use futures::future::{self, Either};
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
use body::Payload;
use proto; use proto;
use proto::body::Entity;
use super::dispatch; use super::dispatch;
use {Body, Request, Response, StatusCode}; use {Body, Request, Response, StatusCode};
@@ -45,7 +45,7 @@ pub struct SendRequest<B> {
pub struct Connection<T, B> pub struct Connection<T, B>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
B: Entity + 'static, B: Payload + 'static,
{ {
inner: proto::dispatch::Dispatcher< inner: proto::dispatch::Dispatcher<
proto::dispatch::Client<B>, proto::dispatch::Client<B>,
@@ -138,7 +138,7 @@ impl<B> SendRequest<B>
impl<B> SendRequest<B> impl<B> SendRequest<B>
where where
B: Entity + 'static, B: Payload + 'static,
{ {
/// Sends a `Request` on the associated connection. /// Sends a `Request` on the associated connection.
/// ///
@@ -262,7 +262,7 @@ impl<B> fmt::Debug for SendRequest<B> {
impl<T, B> Connection<T, B> impl<T, B> Connection<T, B>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
B: Entity + 'static, B: Payload + 'static,
{ {
/// Return the inner IO object, and additional information. /// Return the inner IO object, and additional information.
pub fn into_parts(self) -> Parts<T> { pub fn into_parts(self) -> Parts<T> {
@@ -289,7 +289,7 @@ where
impl<T, B> Future for Connection<T, B> impl<T, B> Future for Connection<T, B>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
B: Entity + 'static, B: Payload + 'static,
{ {
type Item = (); type Item = ();
type Error = ::Error; type Error = ::Error;
@@ -302,7 +302,7 @@ where
impl<T, B> fmt::Debug for Connection<T, B> impl<T, B> fmt::Debug for Connection<T, B>
where where
T: AsyncRead + AsyncWrite + fmt::Debug, T: AsyncRead + AsyncWrite + fmt::Debug,
B: Entity + 'static, B: Payload + 'static,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Connection") f.debug_struct("Connection")
@@ -331,7 +331,7 @@ impl Builder {
pub fn handshake<T, B>(&self, io: T) -> Handshake<T, B> pub fn handshake<T, B>(&self, io: T) -> Handshake<T, B>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
B: Entity + 'static, B: Payload + 'static,
{ {
Handshake { Handshake {
inner: HandshakeInner { inner: HandshakeInner {
@@ -345,7 +345,7 @@ impl Builder {
pub(super) fn handshake_no_upgrades<T, B>(&self, io: T) -> HandshakeNoUpgrades<T, B> pub(super) fn handshake_no_upgrades<T, B>(&self, io: T) -> HandshakeNoUpgrades<T, B>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
B: Entity + 'static, B: Payload + 'static,
{ {
HandshakeNoUpgrades { HandshakeNoUpgrades {
inner: HandshakeInner { inner: HandshakeInner {
@@ -362,7 +362,7 @@ impl Builder {
impl<T, B> Future for Handshake<T, B> impl<T, B> Future for Handshake<T, B>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
B: Entity + 'static, B: Payload + 'static,
{ {
type Item = (SendRequest<B>, Connection<T, B>); type Item = (SendRequest<B>, Connection<T, B>);
type Error = ::Error; type Error = ::Error;
@@ -387,7 +387,7 @@ impl<T, B> fmt::Debug for Handshake<T, B> {
impl<T, B> Future for HandshakeNoUpgrades<T, B> impl<T, B> Future for HandshakeNoUpgrades<T, B>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
B: Entity + 'static, B: Payload + 'static,
{ {
type Item = (SendRequest<B>, proto::dispatch::Dispatcher< type Item = (SendRequest<B>, proto::dispatch::Dispatcher<
proto::dispatch::Client<B>, proto::dispatch::Client<B>,
@@ -406,7 +406,7 @@ where
impl<T, B, R> Future for HandshakeInner<T, B, R> impl<T, B, R> Future for HandshakeInner<T, B, R>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
B: Entity + 'static, B: Payload + 'static,
R: proto::Http1Transaction< R: proto::Http1Transaction<
Incoming=StatusCode, Incoming=StatusCode,
Outgoing=proto::RequestLine, Outgoing=proto::RequestLine,
@@ -470,7 +470,7 @@ impl<B: Send> AssertSendSync for SendRequest<B> {}
impl<T: Send, B: Send> AssertSend for Connection<T, B> impl<T: Send, B: Send> AssertSend for Connection<T, B>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
B: Entity + 'static, B: Payload + 'static,
B::Data: Send + 'static, B::Data: Send + 'static,
{} {}
@@ -478,7 +478,7 @@ where
impl<T: Send + Sync, B: Send + Sync> AssertSendSync for Connection<T, B> impl<T: Send + Sync, B: Send + Sync> AssertSendSync for Connection<T, B>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
B: Entity + 'static, B: Payload + 'static,
B::Data: Send + Sync + 'static, B::Data: Send + Sync + 'static,
{} {}

View File

@@ -16,8 +16,7 @@ use tokio::reactor::Handle;
use tokio_executor::spawn; use tokio_executor::spawn;
pub use tokio_service::Service; pub use tokio_service::Service;
use proto::body::{Body, Entity}; use body::{Body, Payload};
use proto;
use self::pool::Pool; use self::pool::Pool;
pub use self::connect::{Connect, HttpConnector}; pub use self::connect::{Connect, HttpConnector};
@@ -34,7 +33,7 @@ mod pool;
mod tests; mod tests;
/// A Client to make outgoing HTTP requests. /// A Client to make outgoing HTTP requests.
pub struct Client<C, B = proto::Body> { pub struct Client<C, B = Body> {
connector: Arc<C>, connector: Arc<C>,
executor: Exec, executor: Exec,
h1_writev: bool, h1_writev: bool,
@@ -43,21 +42,21 @@ pub struct Client<C, B = proto::Body> {
set_host: bool, set_host: bool,
} }
impl Client<HttpConnector, proto::Body> { impl Client<HttpConnector, Body> {
/// Create a new Client with the default config. /// Create a new Client with the default config.
#[inline] #[inline]
pub fn new(handle: &Handle) -> Client<HttpConnector, proto::Body> { pub fn new(handle: &Handle) -> Client<HttpConnector, Body> {
Config::default().build(handle) Config::default().build(handle)
} }
} }
impl Default for Client<HttpConnector, proto::Body> { impl Default for Client<HttpConnector, Body> {
fn default() -> Client<HttpConnector, proto::Body> { fn default() -> Client<HttpConnector, Body> {
Client::new(&Handle::current()) Client::new(&Handle::current())
} }
} }
impl Client<HttpConnector, proto::Body> { impl Client<HttpConnector, Body> {
/// Configure a Client. /// Configure a Client.
/// ///
/// # Example /// # Example
@@ -76,7 +75,7 @@ impl Client<HttpConnector, proto::Body> {
/// # } /// # }
/// ``` /// ```
#[inline] #[inline]
pub fn configure() -> Config<UseDefaultConnector, proto::Body> { pub fn configure() -> Config<UseDefaultConnector, Body> {
Config::default() Config::default()
} }
} }
@@ -99,7 +98,7 @@ impl<C, B> Client<C, B>
where C: Connect + Sync + 'static, where C: Connect + Sync + 'static,
C::Transport: 'static, C::Transport: 'static,
C::Future: 'static, C::Future: 'static,
B: Entity + Send + 'static, B: Payload + Send + 'static,
B::Data: Send, B::Data: Send,
{ {
@@ -107,16 +106,16 @@ where C: Connect + Sync + 'static,
/// ///
/// # Note /// # Note
/// ///
/// This requires that the `Entity` type have a `Default` implementation. /// This requires that the `Payload` type have a `Default` implementation.
/// It *should* return an "empty" version of itself, such that /// It *should* return an "empty" version of itself, such that
/// `Entity::is_end_stream` is `true`. /// `Payload::is_end_stream` is `true`.
pub fn get(&self, uri: Uri) -> FutureResponse pub fn get(&self, uri: Uri) -> FutureResponse
where where
B: Default, B: Default,
{ {
let body = B::default(); let body = B::default();
if !body.is_end_stream() { if !body.is_end_stream() {
warn!("default Entity used for get() does not return true for is_end_stream"); warn!("default Payload used for get() does not return true for is_end_stream");
} }
let mut req = Request::new(body); let mut req = Request::new(body);
@@ -291,7 +290,7 @@ where C: Connect + Sync + 'static,
impl<C, B> Service for Client<C, B> impl<C, B> Service for Client<C, B>
where C: Connect + 'static, where C: Connect + 'static,
C::Future: 'static, C::Future: 'static,
B: Entity + Send + 'static, B: Payload + Send + 'static,
B::Data: Send, B::Data: Send,
{ {
type Request = Request<B>; type Request = Request<B>;
@@ -354,7 +353,7 @@ impl<C, B> Future for RetryableSendRequest<C, B>
where where
C: Connect + 'static, C: Connect + 'static,
C::Future: 'static, C::Future: 'static,
B: Entity + Send + 'static, B: Payload + Send + 'static,
B::Data: Send, B::Data: Send,
{ {
type Item = Response<Body>; type Item = Response<Body>;
@@ -444,10 +443,10 @@ pub struct Config<C, B> {
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub struct UseDefaultConnector(()); pub struct UseDefaultConnector(());
impl Default for Config<UseDefaultConnector, proto::Body> { impl Default for Config<UseDefaultConnector, Body> {
fn default() -> Config<UseDefaultConnector, proto::Body> { fn default() -> Config<UseDefaultConnector, Body> {
Config { Config {
_body_type: PhantomData::<proto::Body>, _body_type: PhantomData::<Body>,
connector: UseDefaultConnector(()), connector: UseDefaultConnector(()),
keep_alive: true, keep_alive: true,
keep_alive_timeout: Some(Duration::from_secs(90)), keep_alive_timeout: Some(Duration::from_secs(90)),
@@ -566,7 +565,7 @@ impl<C, B> Config<C, B>
where C: Connect, where C: Connect,
C::Transport: 'static, C::Transport: 'static,
C::Future: 'static, C::Future: 'static,
B: Entity + Send, B: Payload + Send,
B::Data: Send, B::Data: Send,
{ {
/// Construct the Client with this configuration. /// Construct the Client with this configuration.
@@ -589,7 +588,7 @@ where C: Connect,
impl<B> Config<UseDefaultConnector, B> impl<B> Config<UseDefaultConnector, B>
where where
B: Entity + Send, B: Payload + Send,
B::Data: Send, B::Data: Send,
{ {
/// Construct the Client with this configuration. /// Construct the Client with this configuration.

View File

@@ -50,7 +50,7 @@ pub(crate) enum Kind {
Body, Body,
/// Error while writing a body to connection. /// Error while writing a body to connection.
BodyWrite, BodyWrite,
/// Error calling user's Entity::poll_data(). /// Error calling user's Payload::poll_data().
BodyUser, BodyUser,
/// Error calling AsyncWrite::shutdown() /// Error calling AsyncWrite::shutdown()
Shutdown, Shutdown,
@@ -257,7 +257,7 @@ impl StdError for Error {
Kind::Service => "error from user's server service", Kind::Service => "error from user's server service",
Kind::Body => "error reading a body from connection", Kind::Body => "error reading a body from connection",
Kind::BodyWrite => "error write a body to connection", Kind::BodyWrite => "error write a body to connection",
Kind::BodyUser => "error from user's Entity stream", Kind::BodyUser => "error from user's Payload stream",
Kind::Shutdown => "error shutting down connection", Kind::Shutdown => "error shutting down connection",
Kind::UnsupportedVersion => "request has unsupported HTTP version", Kind::UnsupportedVersion => "request has unsupported HTTP version",
Kind::UnsupportedRequestMethod => "request has unsupported HTTP method", Kind::UnsupportedRequestMethod => "request has unsupported HTTP method",

View File

@@ -46,12 +46,15 @@ pub use http::{
pub use client::Client; pub use client::Client;
pub use error::{Result, Error}; pub use error::{Result, Error};
pub use proto::{body, Body, Chunk}; pub use body::{Body};
pub use chunk::Chunk;
pub use server::Server; pub use server::Server;
mod common; mod common;
#[cfg(test)] #[cfg(test)]
mod mock; mod mock;
pub mod body;
mod chunk;
pub mod client; pub mod client;
pub mod error; pub mod error;
mod headers; mod headers;

View File

@@ -8,7 +8,8 @@ use futures::task::Task;
use http::{Method, Version}; use http::{Method, Version};
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
use proto::{BodyLength, Chunk, Decode, Http1Transaction, MessageHead}; use ::Chunk;
use proto::{BodyLength, Decode, Http1Transaction, MessageHead};
use super::io::{Cursor, Buffered}; use super::io::{Cursor, Buffered};
use super::{EncodedBuf, Encoder, Decoder}; use super::{EncodedBuf, Encoder, Decoder};

View File

@@ -4,13 +4,13 @@ use http::{Request, Response, StatusCode};
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
use tokio_service::Service; use tokio_service::Service;
use proto::body::Entity; use body::{Body, Payload};
use proto::{Body, BodyLength, Conn, Http1Transaction, MessageHead, RequestHead, RequestLine, ResponseHead}; use proto::{BodyLength, Conn, Http1Transaction, MessageHead, RequestHead, RequestLine, ResponseHead};
pub(crate) struct Dispatcher<D, Bs, I, B, T> { pub(crate) struct Dispatcher<D, Bs, I, B, T> {
conn: Conn<I, B, T>, conn: Conn<I, B, T>,
dispatch: D, dispatch: D,
body_tx: Option<::proto::body::Sender>, body_tx: Option<::body::Sender>,
body_rx: Option<Bs>, body_rx: Option<Bs>,
is_closing: bool, is_closing: bool,
} }
@@ -45,7 +45,7 @@ where
I: AsyncRead + AsyncWrite, I: AsyncRead + AsyncWrite,
B: AsRef<[u8]>, B: AsRef<[u8]>,
T: Http1Transaction, T: Http1Transaction,
Bs: Entity<Data=B>, Bs: Payload<Data=B>,
{ {
pub fn new(dispatch: D, conn: Conn<I, B, T>) -> Self { pub fn new(dispatch: D, conn: Conn<I, B, T>) -> Self {
Dispatcher { Dispatcher {
@@ -292,7 +292,7 @@ where
I: AsyncRead + AsyncWrite, I: AsyncRead + AsyncWrite,
B: AsRef<[u8]>, B: AsRef<[u8]>,
T: Http1Transaction, T: Http1Transaction,
Bs: Entity<Data=B>, Bs: Payload<Data=B>,
{ {
type Item = (); type Item = ();
type Error = ::Error; type Error = ::Error;
@@ -318,7 +318,7 @@ impl<S, Bs> Dispatch for Server<S>
where where
S: Service<Request=Request<Body>, Response=Response<Bs>>, S: Service<Request=Request<Body>, Response=Response<Bs>>,
S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Error: Into<Box<::std::error::Error + Send + Sync>>,
Bs: Entity, Bs: Payload,
{ {
type PollItem = MessageHead<StatusCode>; type PollItem = MessageHead<StatusCode>;
type PollBody = Bs; type PollBody = Bs;
@@ -388,7 +388,7 @@ impl<B> Client<B> {
impl<B> Dispatch for Client<B> impl<B> Dispatch for Client<B>
where where
B: Entity, B: Payload,
{ {
type PollItem = RequestHead; type PollItem = RequestHead;
type PollBody = B; type PollBody = B;

View File

@@ -428,7 +428,7 @@ impl Client<()> {
fn set_length(headers: &mut HeaderMap, body: BodyLength, can_chunked: bool) -> Encoder { fn set_length(headers: &mut HeaderMap, body: BodyLength, can_chunked: bool) -> Encoder {
// If the user already set specific headers, we should respect them, regardless // If the user already set specific headers, we should respect them, regardless
// of what the Entity knows about itself. They set them for a reason. // of what the Payload knows about itself. They set them for a reason.
// Because of the borrow checker, we can't check the for an existing // Because of the borrow checker, we can't check the for an existing
// Content-Length header while holding an `Entry` for the Transfer-Encoding // Content-Length header while holding an `Entry` for the Transfer-Encoding

View File

@@ -4,12 +4,8 @@ use http::{HeaderMap, Method, StatusCode, Uri, Version};
use headers; use headers;
pub use self::body::Body;
pub use self::chunk::Chunk;
pub(crate) use self::h1::{dispatch, Conn}; pub(crate) use self::h1::{dispatch, Conn};
pub mod body;
mod chunk;
mod h1; mod h1;
//mod h2; //mod h2;

View File

@@ -15,7 +15,7 @@ use futures::{Future, Poll};
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
use proto; use proto;
use proto::body::{Body, Entity}; use body::{Body, Payload};
use super::{HyperService, Request, Response, Service}; use super::{HyperService, Request, Response, Service};
/// A future binding a connection with a Service. /// A future binding a connection with a Service.
@@ -25,13 +25,13 @@ use super::{HyperService, Request, Response, Service};
pub struct Connection<I, S> pub struct Connection<I, S>
where where
S: HyperService, S: HyperService,
S::ResponseBody: Entity, S::ResponseBody: Payload,
{ {
pub(super) conn: proto::dispatch::Dispatcher< pub(super) conn: proto::dispatch::Dispatcher<
proto::dispatch::Server<S>, proto::dispatch::Server<S>,
S::ResponseBody, S::ResponseBody,
I, I,
<S::ResponseBody as Entity>::Data, <S::ResponseBody as Payload>::Data,
proto::ServerTransaction, proto::ServerTransaction,
>, >,
} }
@@ -63,7 +63,7 @@ where
S: Service<Request=Request<Body>, Response=Response<B>> + 'static, S: Service<Request=Request<Body>, Response=Response<B>> + 'static,
S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Error: Into<Box<::std::error::Error + Send + Sync>>,
I: AsyncRead + AsyncWrite + 'static, I: AsyncRead + AsyncWrite + 'static,
B: Entity + 'static, B: Payload + 'static,
{ {
/// Disables keep-alive for this connection. /// Disables keep-alive for this connection.
pub fn disable_keep_alive(&mut self) { pub fn disable_keep_alive(&mut self) {
@@ -102,7 +102,7 @@ where
S: Service<Request=Request<Body>, Response=Response<B>> + 'static, S: Service<Request=Request<Body>, Response=Response<B>> + 'static,
S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Error: Into<Box<::std::error::Error + Send + Sync>>,
I: AsyncRead + AsyncWrite + 'static, I: AsyncRead + AsyncWrite + 'static,
B: Entity + 'static, B: Payload + 'static,
{ {
type Item = (); type Item = ();
type Error = ::Error; type Error = ::Error;
@@ -115,7 +115,7 @@ where
impl<I, S> fmt::Debug for Connection<I, S> impl<I, S> fmt::Debug for Connection<I, S>
where where
S: HyperService, S: HyperService,
S::ResponseBody: Entity, S::ResponseBody: Payload,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Connection") f.debug_struct("Connection")

View File

@@ -24,7 +24,7 @@ use tokio::reactor::Handle;
use tokio::net::TcpListener; use tokio::net::TcpListener;
pub use tokio_service::{NewService, Service}; pub use tokio_service::{NewService, Service};
use proto::body::{Body, Entity}; use body::{Body, Payload};
use proto; use proto;
use self::addr_stream::AddrStream; use self::addr_stream::AddrStream;
use self::hyper_service::HyperService; use self::hyper_service::HyperService;
@@ -51,7 +51,7 @@ pub struct Http<B = ::Chunk> {
/// address and then serving TCP connections accepted with the service provided. /// address and then serving TCP connections accepted with the service provided.
pub struct Server<S, B> pub struct Server<S, B>
where where
B: Entity, B: Payload,
{ {
protocol: Http<B::Data>, protocol: Http<B::Data>,
new_service: S, new_service: S,
@@ -168,7 +168,7 @@ impl<B: AsRef<[u8]> + 'static> Http<B> {
where where
S: NewService<Request=Request<Body>, Response=Response<Bd>> + 'static, S: NewService<Request=Request<Body>, Response=Response<Bd>> + 'static,
S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Error: Into<Box<::std::error::Error + Send + Sync>>,
Bd: Entity<Data=B>, Bd: Payload<Data=B>,
{ {
let handle = Handle::current(); let handle = Handle::current();
let std_listener = StdTcpListener::bind(addr).map_err(::Error::new_listen)?; let std_listener = StdTcpListener::bind(addr).map_err(::Error::new_listen)?;
@@ -193,7 +193,7 @@ impl<B: AsRef<[u8]> + 'static> Http<B> {
where where
S: NewService<Request=Request<Body>, Response=Response<Bd>>, S: NewService<Request=Request<Body>, Response=Response<Bd>>,
S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Error: Into<Box<::std::error::Error + Send + Sync>>,
Bd: Entity<Data=B>, Bd: Payload<Data=B>,
{ {
let handle = Handle::current(); let handle = Handle::current();
let std_listener = StdTcpListener::bind(addr).map_err(::Error::new_listen)?; let std_listener = StdTcpListener::bind(addr).map_err(::Error::new_listen)?;
@@ -217,7 +217,7 @@ impl<B: AsRef<[u8]> + 'static> Http<B> {
where where
S: NewService<Request = Request<Body>, Response = Response<Bd>>, S: NewService<Request = Request<Body>, Response = Response<Bd>>,
S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Error: Into<Box<::std::error::Error + Send + Sync>>,
Bd: Entity<Data=B>, Bd: Payload<Data=B>,
{ {
let std_listener = StdTcpListener::bind(addr).map_err(::Error::new_listen)?; 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 listener = TcpListener::from_std(std_listener, &handle).map_err(::Error::new_listen)?;
@@ -238,7 +238,7 @@ impl<B: AsRef<[u8]> + 'static> Http<B> {
I::Item: AsyncRead + AsyncWrite, I::Item: AsyncRead + AsyncWrite,
S: NewService<Request = Request<Body>, Response = Response<Bd>>, S: NewService<Request = Request<Body>, Response = Response<Bd>>,
S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Error: Into<Box<::std::error::Error + Send + Sync>>,
Bd: Entity<Data=B>, Bd: Payload<Data=B>,
{ {
Serve { Serve {
incoming: incoming, incoming: incoming,
@@ -291,7 +291,7 @@ impl<B: AsRef<[u8]> + 'static> Http<B> {
where where
S: Service<Request = Request<Body>, Response = Response<Bd>>, S: Service<Request = Request<Body>, Response = Response<Bd>>,
S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Error: Into<Box<::std::error::Error + Send + Sync>>,
Bd: Entity, Bd: Payload,
I: AsyncRead + AsyncWrite, I: AsyncRead + AsyncWrite,
{ {
let mut conn = proto::Conn::new(io); let mut conn = proto::Conn::new(io);
@@ -357,7 +357,7 @@ where
S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Error: Into<Box<::std::error::Error + Send + Sync>>,
<S as NewService>::Instance: Send, <S as NewService>::Instance: Send,
<<S as NewService>::Instance as Service>::Future: Send, <<S as NewService>::Instance as Service>::Future: Send,
B: Entity + Send + 'static, B: Payload + Send + 'static,
B::Data: Send, B::Data: Send,
{ {
/// Returns the local address that this server is bound to. /// Returns the local address that this server is bound to.
@@ -479,7 +479,7 @@ where
} }
} }
impl<S: fmt::Debug, B: Entity> fmt::Debug for Server<S, B> impl<S: fmt::Debug, B: Payload> fmt::Debug for Server<S, B>
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Server") f.debug_struct("Server")
@@ -516,7 +516,7 @@ where
I::Item: AsyncRead + AsyncWrite, I::Item: AsyncRead + AsyncWrite,
S: NewService<Request=Request<Body>, Response=Response<B>>, S: NewService<Request=Request<Body>, Response=Response<B>>,
S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Error: Into<Box<::std::error::Error + Send + Sync>>,
B: Entity, B: Payload,
{ {
type Item = Connection<I::Item, S::Instance>; type Item = Connection<I::Item, S::Instance>;
type Error = ::Error; type Error = ::Error;
@@ -795,7 +795,7 @@ impl Future for WaitUntilZero {
} }
mod hyper_service { mod hyper_service {
use super::{Body, Entity, Request, Response, Service}; use super::{Body, Payload, Request, Response, Service};
/// A "trait alias" for any type that implements `Service` with hyper's /// A "trait alias" for any type that implements `Service` with hyper's
/// Request, Response, and Error types, and a streaming body. /// Request, Response, and Error types, and a streaming body.
/// ///
@@ -826,7 +826,7 @@ mod hyper_service {
Response=Response<B>, Response=Response<B>,
>, >,
S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Error: Into<Box<::std::error::Error + Send + Sync>>,
B: Entity, B: Payload,
{} {}
impl<S, B> HyperService for S impl<S, B> HyperService for S
@@ -837,7 +837,7 @@ mod hyper_service {
>, >,
S::Error: Into<Box<::std::error::Error + Send + Sync>>, S::Error: Into<Box<::std::error::Error + Send + Sync>>,
S: Sealed, S: Sealed,
B: Entity, B: Payload,
{ {
type ResponseBody = B; type ResponseBody = B;
type Sealed = Opaque; type Sealed = Opaque;

View File

@@ -113,7 +113,7 @@ macro_rules! test {
let body = res let body = res
.into_body() .into_body()
.into_stream()
.concat2() .concat2()
.wait() .wait()
.expect("body concat wait"); .expect("body concat wait");
@@ -726,7 +726,7 @@ mod dispatch_impl {
.unwrap(); .unwrap();
client.request(req).and_then(move |res| { client.request(req).and_then(move |res| {
assert_eq!(res.status(), hyper::StatusCode::OK); assert_eq!(res.status(), hyper::StatusCode::OK);
res.into_body().into_stream().concat2() res.into_body().concat2()
}).and_then(|_| { }).and_then(|_| {
Delay::new(Duration::from_secs(1)) Delay::new(Duration::from_secs(1))
.expect("timeout") .expect("timeout")
@@ -779,7 +779,7 @@ mod dispatch_impl {
.unwrap(); .unwrap();
let res = client.request(req).and_then(move |res| { let res = client.request(req).and_then(move |res| {
assert_eq!(res.status(), hyper::StatusCode::OK); assert_eq!(res.status(), hyper::StatusCode::OK);
res.into_body().into_stream().concat2() res.into_body().concat2()
}); });
let rx = rx1.expect("thread panicked"); let rx = rx1.expect("thread panicked");
res.join(rx).map(|r| r.0).wait().unwrap(); res.join(rx).map(|r| r.0).wait().unwrap();
@@ -946,7 +946,7 @@ mod dispatch_impl {
.unwrap(); .unwrap();
let res = client.request(req).and_then(move |res| { let res = client.request(req).and_then(move |res| {
assert_eq!(res.status(), hyper::StatusCode::OK); assert_eq!(res.status(), hyper::StatusCode::OK);
res.into_body().into_stream().concat2() res.into_body().concat2()
}); });
let rx = rx1.expect("thread panicked"); let rx = rx1.expect("thread panicked");
res.join(rx).map(|r| r.0).wait().unwrap(); res.join(rx).map(|r| r.0).wait().unwrap();
@@ -994,7 +994,7 @@ mod dispatch_impl {
.unwrap(); .unwrap();
let res = client.request(req).and_then(move |res| { let res = client.request(req).and_then(move |res| {
assert_eq!(res.status(), hyper::StatusCode::OK); assert_eq!(res.status(), hyper::StatusCode::OK);
res.into_body().into_stream().concat2() res.into_body().concat2()
}); });
let rx = rx1.expect("thread panicked"); let rx = rx1.expect("thread panicked");
res.join(rx).map(|r| r.0).wait().unwrap(); res.join(rx).map(|r| r.0).wait().unwrap();
@@ -1039,7 +1039,7 @@ mod dispatch_impl {
.unwrap(); .unwrap();
let res = client.request(req).and_then(move |res| { let res = client.request(req).and_then(move |res| {
assert_eq!(res.status(), hyper::StatusCode::OK); assert_eq!(res.status(), hyper::StatusCode::OK);
res.into_body().into_stream().concat2() res.into_body().concat2()
}); });
let rx = rx1.expect("thread panicked"); let rx = rx1.expect("thread panicked");
@@ -1384,7 +1384,7 @@ mod conn {
.unwrap(); .unwrap();
let res = client.send_request(req).and_then(move |res| { let res = client.send_request(req).and_then(move |res| {
assert_eq!(res.status(), hyper::StatusCode::OK); assert_eq!(res.status(), hyper::StatusCode::OK);
res.into_body().into_stream().concat2() res.into_body().concat2()
}); });
let rx = rx1.expect("thread panicked"); let rx = rx1.expect("thread panicked");
@@ -1430,7 +1430,7 @@ mod conn {
let res = client.send_request(req).and_then(move |res| { let res = client.send_request(req).and_then(move |res| {
assert_eq!(res.status(), hyper::StatusCode::OK); assert_eq!(res.status(), hyper::StatusCode::OK);
res.into_body().into_stream().concat2() res.into_body().concat2()
}); });
let rx = rx1.expect("thread panicked"); let rx = rx1.expect("thread panicked");
@@ -1470,7 +1470,7 @@ mod conn {
.unwrap(); .unwrap();
let res1 = client.send_request(req).and_then(move |res| { let res1 = client.send_request(req).and_then(move |res| {
assert_eq!(res.status(), hyper::StatusCode::OK); assert_eq!(res.status(), hyper::StatusCode::OK);
res.into_body().into_stream().concat2() res.into_body().concat2()
}); });
// pipelined request will hit NotReady, and thus should return an Error::Cancel // pipelined request will hit NotReady, and thus should return an Error::Cancel
@@ -1543,7 +1543,7 @@ mod conn {
let res = client.send_request(req).and_then(move |res| { let res = client.send_request(req).and_then(move |res| {
assert_eq!(res.status(), hyper::StatusCode::SWITCHING_PROTOCOLS); assert_eq!(res.status(), hyper::StatusCode::SWITCHING_PROTOCOLS);
assert_eq!(res.headers()["Upgrade"], "foobar"); assert_eq!(res.headers()["Upgrade"], "foobar");
res.into_body().into_stream().concat2() res.into_body().concat2()
}); });
let rx = rx1.expect("thread panicked"); let rx = rx1.expect("thread panicked");
@@ -1623,7 +1623,7 @@ mod conn {
let res = client.send_request(req) let res = client.send_request(req)
.and_then(move |res| { .and_then(move |res| {
assert_eq!(res.status(), hyper::StatusCode::OK); assert_eq!(res.status(), hyper::StatusCode::OK);
res.into_body().into_stream().concat2() res.into_body().concat2()
}) })
.map(|body| { .map(|body| {
assert_eq!(body.as_ref(), b""); assert_eq!(body.as_ref(), b"");

View File

@@ -110,7 +110,7 @@ fn get_implicitly_empty() {
fn call(&self, req: Request<Body>) -> Self::Future { fn call(&self, req: Request<Body>) -> Self::Future {
Box::new(req.into_body() Box::new(req.into_body()
.into_stream()
.concat2() .concat2()
.map(|buf| { .map(|buf| {
assert!(buf.is_empty()); assert!(buf.is_empty());
@@ -256,7 +256,7 @@ mod response_body_lengths {
fn get_auto_response_with_entity_unknown_length() { fn get_auto_response_with_entity_unknown_length() {
run_test(TestCase { run_test(TestCase {
version: 1, version: 1,
// no headers means trying to guess from Entity // no headers means trying to guess from Payload
headers: &[], headers: &[],
body: Bd::Unknown("foo bar baz"), body: Bd::Unknown("foo bar baz"),
expects_chunked: true, expects_chunked: true,
@@ -268,7 +268,7 @@ mod response_body_lengths {
fn get_auto_response_with_entity_known_length() { fn get_auto_response_with_entity_known_length() {
run_test(TestCase { run_test(TestCase {
version: 1, version: 1,
// no headers means trying to guess from Entity // no headers means trying to guess from Payload
headers: &[], headers: &[],
body: Bd::Known("foo bar baz"), body: Bd::Known("foo bar baz"),
expects_chunked: false, expects_chunked: false,
@@ -281,7 +281,7 @@ mod response_body_lengths {
fn http_10_get_auto_response_with_entity_unknown_length() { fn http_10_get_auto_response_with_entity_unknown_length() {
run_test(TestCase { run_test(TestCase {
version: 0, version: 0,
// no headers means trying to guess from Entity // no headers means trying to guess from Payload
headers: &[], headers: &[],
body: Bd::Unknown("foo bar baz"), body: Bd::Unknown("foo bar baz"),
expects_chunked: false, expects_chunked: false,
@@ -1287,7 +1287,7 @@ impl Service for TestService {
let tx2 = self.tx.clone(); let tx2 = self.tx.clone();
let replies = self.reply.clone(); let replies = self.reply.clone();
Box::new(req.into_body().into_stream().for_each(move |chunk| { Box::new(req.into_body().for_each(move |chunk| {
tx1.lock().unwrap().send(Msg::Chunk(chunk.to_vec())).unwrap(); tx1.lock().unwrap().send(Msg::Chunk(chunk.to_vec())).unwrap();
Ok(()) Ok(())
}).then(move |result| { }).then(move |result| {