feat(service): introduce hyper-specific Service
This introduces the `hyper::service` module, which replaces `tokio-service`. Since the trait is specific to hyper, its associated types have been adjusted. It didn't make sense to need to define `Service<Request=http::Request>`, since we already know the context is HTTP. Instead, the request and response bodies are associated types now, and slightly stricter bounds have been placed on `Error`. The helpers `service_fn` and `service_fn_ok` should be sufficient for now to ease creating `Service`s. The `NewService` trait now allows service creation to also be asynchronous. These traits are similar to `tower` in nature, and possibly will be replaced completely by it in the future. For now, hyper defining its own allows the traits to have better context, and prevents breaking changes in `tower` from affecting hyper. Closes #1461 BREAKING CHANGE: The `Service` trait has changed: it has some changed associated types, and `call` is now bound to `&mut self`. The `NewService` trait has changed: it has some changed associated types, and `new_service` now returns a `Future`. `Client` no longer implements `Service` for now. `hyper::server::conn::Serve` now returns `Connecting` instead of `Connection`s, since `new_service` can now return a `Future`. The `Connecting` is a future wrapping the new service future, returning a `Connection` afterwards. In many cases, `Future::flatten` can be used.
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -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> {
|
||||
@@ -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> {
|
||||
@@ -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,
|
||||
>,
|
||||
>,
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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();
|
||||
@@ -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,
|
||||
@@ -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,
|
||||
{
|
||||
@@ -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,
|
||||
{
|
||||
@@ -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,
|
||||
{
|
||||
@@ -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,
|
||||
@@ -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,
|
||||
@@ -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")
|
||||
@@ -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> {
|
||||
@@ -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 = ();
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
@@ -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
|
||||
@@ -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 = ();
|
||||
@@ -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);
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user