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:
Sean McArthur
2018-04-17 13:03:59 -07:00
parent 71a15c25f5
commit 2dc6202fe7
24 changed files with 749 additions and 582 deletions

View File

@@ -31,8 +31,8 @@ use tokio_io::{AsyncRead, AsyncWrite};
use hyper::{Body, Request, Response, StatusCode};
use hyper::server::{Service, NewService, service_fn};
use hyper::server::conn::Http;
use hyper::service::{service_fn, Service};
fn tcp_bind(addr: &SocketAddr, handle: &Handle) -> ::tokio::io::Result<TcpListener> {
let std_listener = StdTcpListener::bind(addr).unwrap();
@@ -95,28 +95,17 @@ fn get_implicitly_empty() {
.map_err(|_| unreachable!())
.and_then(|(item, _incoming)| {
let socket = item.unwrap();
Http::new().serve_connection(socket, GetImplicitlyEmpty)
Http::new().serve_connection(socket, service_fn(|req: Request<Body>| {
req.into_body()
.concat2()
.map(|buf| {
assert!(buf.is_empty());
Response::new(Body::empty())
})
}))
});
fut.wait().unwrap();
struct GetImplicitlyEmpty;
impl Service for GetImplicitlyEmpty {
type Request = Request<Body>;
type Response = Response<Body>;
type Error = hyper::Error;
type Future = Box<Future<Item=Self::Response, Error=Self::Error> + Send>;
fn call(&self, req: Request<Body>) -> Self::Future {
Box::new(req.into_body()
.concat2()
.map(|buf| {
assert!(buf.is_empty());
Response::new(Body::empty())
}))
}
}
}
mod response_body_lengths {
@@ -1258,24 +1247,9 @@ enum Msg {
End,
}
impl NewService for TestService {
type Request = Request<Body>;
type Response = Response<Body>;
type Error = hyper::Error;
type Instance = TestService;
fn new_service(&self) -> std::io::Result<TestService> {
Ok(self.clone())
}
}
impl Service for TestService {
type Request = Request<Body>;
type Response = Response<Body>;
type Error = hyper::Error;
type Future = Box<Future<Item=Response<Body>, Error=hyper::Error> + Send>;
fn call(&self, req: Request<Body>) -> Self::Future {
impl TestService {
// Box is needed until we can return `impl Future` from a fn
fn call(&self, req: Request<Body>) -> Box<Future<Item=Response<Body>, Error=hyper::Error> + Send> {
let tx1 = self.tx.clone();
let tx2 = self.tx.clone();
@@ -1309,7 +1283,6 @@ impl Service for TestService {
res
}))
}
}
const HELLO: &'static str = "hello";
@@ -1317,12 +1290,12 @@ const HELLO: &'static str = "hello";
struct HelloWorld;
impl Service for HelloWorld {
type Request = Request<Body>;
type Response = Response<Body>;
type ReqBody = Body;
type ResBody = Body;
type Error = hyper::Error;
type Future = FutureResult<Self::Response, Self::Error>;
type Future = FutureResult<Response<Body>, Self::Error>;
fn call(&self, _req: Request<Body>) -> Self::Future {
fn call(&mut self, _req: Request<Body>) -> Self::Future {
let response = Response::new(HELLO.into());
future::ok(response)
}
@@ -1376,10 +1349,13 @@ fn serve_with_options(options: ServeOptions) -> Serve {
let serve = Http::new()
.keep_alive(keep_alive)
.pipeline_flush(pipeline)
.serve_addr(&addr, TestService {
tx: Arc::new(Mutex::new(msg_tx.clone())),
_timeout: dur,
reply: reply_rx,
.serve_addr(&addr, move || {
let ts = TestService {
tx: Arc::new(Mutex::new(msg_tx.clone())),
_timeout: dur,
reply: reply_rx.clone(),
};
service_fn(move |req| ts.call(req))
})
.expect("bind to address");
@@ -1390,10 +1366,12 @@ fn serve_with_options(options: ServeOptions) -> Serve {
).expect("server addr tx");
// spawn_all() is private for now, so just duplicate it here
let spawn_all = serve.for_each(|conn| {
tokio::spawn(conn.map_err(|e| {
println!("server error: {}", e);
}));
let spawn_all = serve.for_each(|connecting| {
let fut = connecting
.map_err(|never| -> hyper::Error { match never {} })
.flatten()
.map_err(|e| println!("server error: {}", e));
tokio::spawn(fut);
Ok(())
}).map_err(|e| {
println!("accept error: {}", e)

View File

@@ -187,7 +187,7 @@ pub fn __run_test(cfg: __TestConfig) {
extern crate pretty_env_logger;
use hyper::{Body, Client, Request, Response};
use hyper::client::HttpConnector;
use std::sync::Arc;
use std::sync::{Arc, Mutex};
let _ = pretty_env_logger::try_init();
let rt = Runtime::new().expect("new rt");
let handle = rt.reactor().clone();
@@ -198,37 +198,40 @@ pub fn __run_test(cfg: __TestConfig) {
.executor(rt.executor())
.build::<_, Body>(connector);
let serve_handles = ::std::sync::Mutex::new(
let serve_handles = Arc::new(Mutex::new(
cfg.server_msgs
);
let service = hyper::server::service_fn(move |req: Request<Body>| -> Box<Future<Item=Response<Body>, Error=hyper::Error> + Send> {
let (sreq, sres) = serve_handles.lock()
.unwrap()
.remove(0);
));
let new_service = move || {
// Move a clone into the service_fn
let serve_handles = serve_handles.clone();
hyper::service::service_fn(move |req: Request<Body>| {
let (sreq, sres) = serve_handles.lock()
.unwrap()
.remove(0);
assert_eq!(req.uri().path(), sreq.uri);
assert_eq!(req.method(), &sreq.method);
for (name, value) in &sreq.headers {
assert_eq!(
req.headers()[name],
value
);
}
let sbody = sreq.body;
Box::new(req.into_body()
.concat2()
.map(move |body| {
assert_eq!(body.as_ref(), sbody.as_slice());
assert_eq!(req.uri().path(), sreq.uri);
assert_eq!(req.method(), &sreq.method);
for (name, value) in &sreq.headers {
assert_eq!(
req.headers()[name],
value
);
}
let sbody = sreq.body;
req.into_body()
.concat2()
.map(move |body| {
assert_eq!(body.as_ref(), sbody.as_slice());
let mut res = Response::builder()
.status(sres.status)
.body(sres.body.into())
.expect("Response::build");
*res.headers_mut() = sres.headers;
res
}))
});
let new_service = hyper::server::const_service(service);
let mut res = Response::builder()
.status(sres.status)
.body(Body::from(sres.body))
.expect("Response::build");
*res.headers_mut() = sres.headers;
res
})
})
};
let serve = hyper::server::conn::Http::new()
.http2_only(cfg.server_version == 2)
@@ -246,8 +249,12 @@ pub fn __run_test(cfg: __TestConfig) {
let (success_tx, success_rx) = oneshot::channel();
let expected_connections = cfg.connections;
let server = serve
.fold(0, move |cnt, conn| {
exe.spawn(conn.map_err(|e| panic!("server connection error: {}", e)));
.fold(0, move |cnt, connecting| {
let fut = connecting
.map_err(|never| -> hyper::Error { match never {} })
.flatten()
.map_err(|e| panic!("server connection error: {}", e));
exe.spawn(fut);
Ok::<_, hyper::Error>(cnt + 1)
})
.map(move |cnt| {