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

@@ -6,8 +6,8 @@ extern crate tokio;
use futures::Future;
use hyper::{Body, Response};
use hyper::server::{Server, const_service, service_fn};
use hyper::{Body, Response, Server};
use hyper::service::service_fn_ok;
static PHRASE: &'static [u8] = b"Hello World!";
@@ -16,10 +16,16 @@ fn main() {
let addr = ([127, 0, 0, 1], 3000).into();
let new_service = const_service(service_fn(|_| {
//TODO: when `!` is stable, replace error type
Ok::<_, hyper::Error>(Response::new(Body::from(PHRASE)))
}));
// new_service is run for each connection, creating a 'service'
// to handle requests for that specific connection.
let new_service = || {
// This is the `Service` that will handle the connection.
// `service_fn_ok` is a helper to convert a function that
// returns a Response into a `Service`.
service_fn_ok(|_| {
Response::new(Body::from(PHRASE))
})
};
let server = Server::bind(&addr)
.serve(new_service)

View File

@@ -5,39 +5,14 @@ extern crate pretty_env_logger;
extern crate tokio;
use futures::{Future};
use futures::future::{FutureResult, lazy};
use futures::future::{lazy};
use hyper::{Body, Method, Request, Response, StatusCode};
use hyper::server::{Server, Service};
use hyper::{Body, Response, Server};
use hyper::service::service_fn_ok;
static INDEX1: &'static [u8] = b"The 1st service!";
static INDEX2: &'static [u8] = b"The 2nd service!";
struct Srv(&'static [u8]);
impl Service for Srv {
type Request = Request<Body>;
type Response = Response<Body>;
type Error = hyper::Error;
type Future = FutureResult<Response<Body>, hyper::Error>;
fn call(&self, req: Request<Body>) -> Self::Future {
futures::future::ok(match (req.method(), req.uri().path()) {
(&Method::GET, "/") => {
Response::new(self.0.into())
},
_ => {
Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::empty())
.unwrap()
}
})
}
}
fn main() {
pretty_env_logger::init();
@@ -46,11 +21,11 @@ fn main() {
tokio::run(lazy(move || {
let srv1 = Server::bind(&addr1)
.serve(|| Ok(Srv(INDEX1)))
.serve(|| service_fn_ok(|_| Response::new(Body::from(INDEX1))))
.map_err(|e| eprintln!("server 1 error: {}", e));
let srv2 = Server::bind(&addr2)
.serve(|| Ok(Srv(INDEX2)))
.serve(|| service_fn_ok(|_| Response::new(Body::from(INDEX2))))
.map_err(|e| eprintln!("server 2 error: {}", e));
println!("Listening on http://{} and http://{}", addr1, addr2);

View File

@@ -5,10 +5,10 @@ extern crate pretty_env_logger;
extern crate tokio;
extern crate url;
use futures::{Future, Stream};
use futures::{future, Future, Stream};
use hyper::{Body, Method, Request, Response, StatusCode};
use hyper::server::{Server, Service};
use hyper::{Body, Method, Request, Response, Server, StatusCode};
use hyper::service::service_fn;
use std::collections::HashMap;
use url::form_urlencoded;
@@ -17,89 +17,80 @@ static INDEX: &[u8] = b"<html><body><form action=\"post\" method=\"post\">Name:
static MISSING: &[u8] = b"Missing field";
static NOTNUMERIC: &[u8] = b"Number field is not numeric";
struct ParamExample;
// Using service_fn, we can turn this function into a `Service`.
fn param_example(req: Request<Body>) -> Box<Future<Item=Response<Body>, Error=hyper::Error> + Send> {
match (req.method(), req.uri().path()) {
(&Method::GET, "/") | (&Method::GET, "/post") => {
Box::new(future::ok(Response::new(INDEX.into())))
},
(&Method::POST, "/post") => {
Box::new(req.into_body().concat2().map(|b| {
// Parse the request body. form_urlencoded::parse
// always succeeds, but in general parsing may
// fail (for example, an invalid post of json), so
// returning early with BadRequest may be
// necessary.
//
// Warning: this is a simplified use case. In
// principle names can appear multiple times in a
// form, and the values should be rolled up into a
// HashMap<String, Vec<String>>. However in this
// example the simpler approach is sufficient.
let params = form_urlencoded::parse(b.as_ref()).into_owned().collect::<HashMap<String, String>>();
impl Service for ParamExample {
type Request = Request<Body>;
type Response = Response<Body>;
type Error = hyper::Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error> + Send>;
fn call(&self, req: Request<Body>) -> Self::Future {
match (req.method(), req.uri().path()) {
(&Method::GET, "/") | (&Method::GET, "/post") => {
Box::new(futures::future::ok(Response::new(INDEX.into())))
},
(&Method::POST, "/post") => {
Box::new(req.into_body().concat2().map(|b| {
// Parse the request body. form_urlencoded::parse
// always succeeds, but in general parsing may
// fail (for example, an invalid post of json), so
// returning early with BadRequest may be
// necessary.
//
// Warning: this is a simplified use case. In
// principle names can appear multiple times in a
// form, and the values should be rolled up into a
// HashMap<String, Vec<String>>. However in this
// example the simpler approach is sufficient.
let params = form_urlencoded::parse(b.as_ref()).into_owned().collect::<HashMap<String, String>>();
// Validate the request parameters, returning
// early if an invalid input is detected.
let name = if let Some(n) = params.get("name") {
n
// Validate the request parameters, returning
// early if an invalid input is detected.
let name = if let Some(n) = params.get("name") {
n
} else {
return Response::builder()
.status(StatusCode::UNPROCESSABLE_ENTITY)
.body(MISSING.into())
.unwrap();
};
let number = if let Some(n) = params.get("number") {
if let Ok(v) = n.parse::<f64>() {
v
} else {
return Response::builder()
.status(StatusCode::UNPROCESSABLE_ENTITY)
.body(MISSING.into())
.body(NOTNUMERIC.into())
.unwrap();
};
let number = if let Some(n) = params.get("number") {
if let Ok(v) = n.parse::<f64>() {
v
} else {
return Response::builder()
.status(StatusCode::UNPROCESSABLE_ENTITY)
.body(NOTNUMERIC.into())
.unwrap();
}
} else {
return Response::builder()
.status(StatusCode::UNPROCESSABLE_ENTITY)
.body(MISSING.into())
.unwrap();
};
}
} else {
return Response::builder()
.status(StatusCode::UNPROCESSABLE_ENTITY)
.body(MISSING.into())
.unwrap();
};
// Render the response. This will often involve
// calls to a database or web service, which will
// require creating a new stream for the response
// body. Since those may fail, other error
// responses such as InternalServiceError may be
// needed here, too.
let body = format!("Hello {}, your number is {}", name, number);
Response::new(body.into())
}))
},
_ => {
Box::new(futures::future::ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::empty())
.unwrap()))
}
// Render the response. This will often involve
// calls to a database or web service, which will
// require creating a new stream for the response
// body. Since those may fail, other error
// responses such as InternalServiceError may be
// needed here, too.
let body = format!("Hello {}, your number is {}", name, number);
Response::new(body.into())
}))
},
_ => {
Box::new(future::ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::empty())
.unwrap()))
}
}
}
fn main() {
pretty_env_logger::init();
let addr = ([127, 0, 0, 1], 1337).into();
let server = Server::bind(&addr)
.serve(|| Ok(ParamExample))
.serve(|| service_fn(param_example))
.map_err(|e| eprintln!("server error: {}", e));
tokio::run(server);

View File

@@ -4,11 +4,11 @@ extern crate hyper;
extern crate pretty_env_logger;
extern crate tokio;
use futures::{Future/*, Sink*/};
use futures::{future, Future};
use futures::sync::oneshot;
use hyper::{Body, /*Chunk,*/ Method, Request, Response, StatusCode};
use hyper::server::{Server, Service};
use hyper::{Body, Method, Request, Response, Server, StatusCode};
use hyper::service::service_fn;
use std::fs::File;
use std::io::{self, copy/*, Read*/};
@@ -17,7 +17,92 @@ use std::thread;
static NOTFOUND: &[u8] = b"Not Found";
static INDEX: &str = "examples/send_file_index.html";
fn simple_file_send(f: &str) -> Box<Future<Item = Response<Body>, Error = io::Error> + Send> {
fn main() {
pretty_env_logger::init();
let addr = "127.0.0.1:1337".parse().unwrap();
let server = Server::bind(&addr)
.serve(|| service_fn(response_examples))
.map_err(|e| eprintln!("server error: {}", e));
println!("Listening on http://{}", addr);
tokio::run(server);
}
type ResponseFuture = Box<Future<Item=Response<Body>, Error=io::Error> + Send>;
fn response_examples(req: Request<Body>) -> ResponseFuture {
match (req.method(), req.uri().path()) {
(&Method::GET, "/") | (&Method::GET, "/index.html") => {
simple_file_send(INDEX)
},
(&Method::GET, "/big_file.html") => {
// Stream a large file in chunks. This requires a
// little more overhead with two channels, (one for
// the response future, and a second for the response
// body), but can handle arbitrarily large files.
//
// We use an artificially small buffer, since we have
// a small test file.
let (tx, rx) = oneshot::channel();
thread::spawn(move || {
let _file = match File::open(INDEX) {
Ok(f) => f,
Err(_) => {
tx.send(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(NOTFOUND.into())
.unwrap())
.expect("Send error on open");
return;
},
};
let (_tx_body, rx_body) = Body::channel();
let res = Response::new(rx_body.into());
tx.send(res).expect("Send error on successful file read");
/* TODO: fix once we have futures 0.2 Sink working
let mut buf = [0u8; 16];
loop {
match file.read(&mut buf) {
Ok(n) => {
if n == 0 {
// eof
tx_body.close().expect("panic closing");
break;
} else {
let chunk: Chunk = buf[0..n].to_vec().into();
match tx_body.send_data(chunk).wait() {
Ok(t) => { tx_body = t; },
Err(_) => { break; }
};
}
},
Err(_) => { break; }
}
}
*/
});
Box::new(rx.map_err(|e| io::Error::new(io::ErrorKind::Other, e)))
},
(&Method::GET, "/no_file.html") => {
// Test what happens when file cannot be be found
simple_file_send("this_file_should_not_exist.html")
},
_ => {
Box::new(future::ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::empty())
.unwrap()))
}
}
}
fn simple_file_send(f: &str) -> ResponseFuture {
// Serve a file by reading it entirely into memory. As a result
// this is limited to serving small files, but it is somewhat
// simpler with a little less overhead.
@@ -57,94 +142,3 @@ fn simple_file_send(f: &str) -> Box<Future<Item = Response<Body>, Error = io::Er
Box::new(rx.map_err(|e| io::Error::new(io::ErrorKind::Other, e)))
}
struct ResponseExamples;
impl Service for ResponseExamples {
type Request = Request<Body>;
type Response = Response<Body>;
type Error = io::Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error> + Send>;
fn call(&self, req: Request<Body>) -> Self::Future {
match (req.method(), req.uri().path()) {
(&Method::GET, "/") | (&Method::GET, "/index.html") => {
simple_file_send(INDEX)
},
(&Method::GET, "/big_file.html") => {
// Stream a large file in chunks. This requires a
// little more overhead with two channels, (one for
// the response future, and a second for the response
// body), but can handle arbitrarily large files.
//
// We use an artificially small buffer, since we have
// a small test file.
let (tx, rx) = oneshot::channel();
thread::spawn(move || {
let _file = match File::open(INDEX) {
Ok(f) => f,
Err(_) => {
tx.send(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(NOTFOUND.into())
.unwrap())
.expect("Send error on open");
return;
},
};
let (_tx_body, rx_body) = Body::channel();
let res = Response::new(rx_body.into());
tx.send(res).expect("Send error on successful file read");
/* TODO: fix once we have futures 0.2 Sink working
let mut buf = [0u8; 16];
loop {
match file.read(&mut buf) {
Ok(n) => {
if n == 0 {
// eof
tx_body.close().expect("panic closing");
break;
} else {
let chunk: Chunk = buf[0..n].to_vec().into();
match tx_body.send_data(chunk).wait() {
Ok(t) => { tx_body = t; },
Err(_) => { break; }
};
}
},
Err(_) => { break; }
}
}
*/
});
Box::new(rx.map_err(|e| io::Error::new(io::ErrorKind::Other, e)))
},
(&Method::GET, "/no_file.html") => {
// Test what happens when file cannot be be found
simple_file_send("this_file_should_not_exist.html")
},
_ => {
Box::new(futures::future::ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::empty())
.unwrap()))
}
}
}
}
fn main() {
pretty_env_logger::init();
let addr = "127.0.0.1:1337".parse().unwrap();
let server = Server::bind(&addr)
.serve(|| Ok(ResponseExamples))
.map_err(|e| eprintln!("server error: {}", e));
println!("Listening on http://{}", addr);
tokio::run(server);
}

View File

@@ -5,37 +5,27 @@ extern crate pretty_env_logger;
extern crate tokio;
use futures::Future;
use futures::future::{FutureResult};
use hyper::{Body, Method, Request, Response, StatusCode};
use hyper::server::{Server, Service};
use hyper::{Body, Method, Request, Response, Server, StatusCode};
use hyper::service::service_fn_ok;
static INDEX: &'static [u8] = b"Try POST /echo";
struct Echo;
impl Service for Echo {
type Request = Request<Body>;
type Response = Response<Body>;
type Error = hyper::Error;
type Future = FutureResult<Self::Response, Self::Error>;
fn call(&self, req: Self::Request) -> Self::Future {
futures::future::ok(match (req.method(), req.uri().path()) {
(&Method::GET, "/") | (&Method::POST, "/") => {
Response::new(INDEX.into())
},
(&Method::POST, "/echo") => {
Response::new(req.into_body())
},
_ => {
let mut res = Response::new(Body::empty());
*res.status_mut() = StatusCode::NOT_FOUND;
res
}
})
// Using service_fn_ok, we can convert this function into a `Service`.
fn echo(req: Request<Body>) -> Response<Body> {
match (req.method(), req.uri().path()) {
(&Method::GET, "/") | (&Method::POST, "/") => {
Response::new(INDEX.into())
},
(&Method::POST, "/echo") => {
Response::new(req.into_body())
},
_ => {
let mut res = Response::new(Body::empty());
*res.status_mut() = StatusCode::NOT_FOUND;
res
}
}
}
@@ -45,7 +35,7 @@ fn main() {
let addr = ([127, 0, 0, 1], 1337).into();
let server = Server::bind(&addr)
.serve(|| Ok(Echo))
.serve(|| service_fn_ok(echo))
.map_err(|e| eprintln!("server error: {}", e));
println!("Listening on http://{}", addr);

View File

@@ -4,12 +4,11 @@ extern crate hyper;
extern crate pretty_env_logger;
extern crate tokio;
use futures::{Future, Stream};
use futures::future::lazy;
use futures::{future, Future, Stream};
use hyper::{Body, Chunk, Client, Method, Request, Response, StatusCode};
use hyper::{Body, Chunk, Client, Method, Request, Response, Server, StatusCode};
use hyper::client::HttpConnector;
use hyper::server::{Server, Service};
use hyper::service::service_fn;
#[allow(unused, deprecated)]
use std::ascii::AsciiExt;
@@ -19,69 +18,70 @@ static URL: &str = "http://127.0.0.1:1337/web_api";
static INDEX: &[u8] = b"<a href=\"test.html\">test.html</a>";
static LOWERCASE: &[u8] = b"i am a lower case string";
struct ResponseExamples(Client<HttpConnector>);
fn response_examples(req: Request<Body>, client: &Client<HttpConnector>)
-> Box<Future<Item=Response<Body>, Error=hyper::Error> + Send>
{
match (req.method(), req.uri().path()) {
(&Method::GET, "/") | (&Method::GET, "/index.html") => {
let body = Body::from(INDEX);
Box::new(future::ok(Response::new(body)))
},
(&Method::GET, "/test.html") => {
// Run a web query against the web api below
let req = Request::builder()
.method(Method::POST)
.uri(URL)
.body(LOWERCASE.into())
.unwrap();
let web_res_future = client.request(req);
impl Service for ResponseExamples {
type Request = Request<Body>;
type Response = Response<Body>;
type Error = hyper::Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error> + Send>;
fn call(&self, req: Self::Request) -> Self::Future {
match (req.method(), req.uri().path()) {
(&Method::GET, "/") | (&Method::GET, "/index.html") => {
let body = Body::from(INDEX);
Box::new(futures::future::ok(Response::new(body)))
},
(&Method::GET, "/test.html") => {
// Run a web query against the web api below
let req = Request::builder()
.method(Method::POST)
.uri(URL)
.body(LOWERCASE.into())
.unwrap();
let web_res_future = self.0.request(req);
Box::new(web_res_future.map(|web_res| {
let body = Body::wrap_stream(web_res.into_body().map(|b| {
Chunk::from(format!("before: '{:?}'<br>after: '{:?}'",
std::str::from_utf8(LOWERCASE).unwrap(),
std::str::from_utf8(&b).unwrap()))
}));
Response::new(body)
}))
},
(&Method::POST, "/web_api") => {
// A web api to run against. Simple upcasing of the body.
let body = Body::wrap_stream(req.into_body().map(|chunk| {
let upper = chunk.iter().map(|byte| byte.to_ascii_uppercase())
.collect::<Vec<u8>>();
Chunk::from(upper)
Box::new(web_res_future.map(|web_res| {
let body = Body::wrap_stream(web_res.into_body().map(|b| {
Chunk::from(format!("before: '{:?}'<br>after: '{:?}'",
std::str::from_utf8(LOWERCASE).unwrap(),
std::str::from_utf8(&b).unwrap()))
}));
Box::new(futures::future::ok(Response::new(body)))
},
_ => {
let body = Body::from(NOTFOUND);
Box::new(futures::future::ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(body)
.unwrap()))
}
Response::new(body)
}))
},
(&Method::POST, "/web_api") => {
// A web api to run against. Simple upcasing of the body.
let body = Body::wrap_stream(req.into_body().map(|chunk| {
let upper = chunk.iter().map(|byte| byte.to_ascii_uppercase())
.collect::<Vec<u8>>();
Chunk::from(upper)
}));
Box::new(future::ok(Response::new(body)))
},
_ => {
let body = Body::from(NOTFOUND);
Box::new(future::ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(body)
.unwrap()))
}
}
}
fn main() {
pretty_env_logger::init();
let addr = "127.0.0.1:1337".parse().unwrap();
tokio::run(lazy(move || {
tokio::run(future::lazy(move || {
// Share a `Client` with all `Service`s
let client = Client::new();
let new_service = move || {
// Move a clone of `client` into the `service_fn`.
let client = client.clone();
service_fn(move |req| {
response_examples(req, &client)
})
};
let server = Server::bind(&addr)
.serve(move || Ok(ResponseExamples(client.clone())))
.serve(new_service)
.map_err(|e| eprintln!("server error: {}", e));
println!("Listening on http://{}", addr);
@@ -89,3 +89,4 @@ fn main() {
server
}));
}