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:
		| @@ -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; | ||||
| @@ -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 { | ||||
|   | ||||
| @@ -1,6 +1,5 @@ | ||||
| mod exec; | ||||
| mod never; | ||||
|  | ||||
| pub(crate) use self::exec::Exec; | ||||
|  | ||||
| #[derive(Debug)] | ||||
| pub enum Never {} | ||||
| pub use self::never::Never; | ||||
|   | ||||
							
								
								
									
										22
									
								
								src/common/never.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										22
									
								
								src/common/never.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -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 {} | ||||
|     } | ||||
| } | ||||
|  | ||||
| @@ -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 { | ||||
|   | ||||
| @@ -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"))] | ||||
| @@ -62,3 +61,4 @@ pub mod error; | ||||
| mod headers; | ||||
| mod proto; | ||||
| pub mod server; | ||||
| pub mod service; | ||||
|   | ||||
| @@ -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>, | ||||
| @@ -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, | ||||
| { | ||||
|   | ||||
| @@ -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 | ||||
| @@ -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, | ||||
| @@ -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, | ||||
| @@ -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, | ||||
|   | ||||
| @@ -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()) | ||||
|     } | ||||
| } | ||||
							
								
								
									
										35
									
								
								src/service/mod.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										35
									
								
								src/service/mod.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -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}; | ||||
							
								
								
									
										55
									
								
								src/service/new_service.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										55
									
								
								src/service/new_service.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -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() | ||||
|     } | ||||
| } | ||||
|  | ||||
							
								
								
									
										165
									
								
								src/service/service.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										165
									
								
								src/service/service.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -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() | ||||
|     } | ||||
| } | ||||
		Reference in New Issue
	
	Block a user