diff --git a/Cargo.toml b/Cargo.toml index 803003dd..1fa21c0b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,7 @@ serde = "1.0" serde_json = "1.0" serde_urlencoded = "0.7" tokio = { version = "1", features = ["time"] } +tokio-util = "0.6" tower = { version = "0.4", features = ["util", "buffer", "make"] } tower-http = { version = "0.1", features = ["add-extension", "map-response-body"] } diff --git a/examples/key_value_store.rs b/examples/key_value_store.rs index d05446eb..3f685a50 100644 --- a/examples/key_value_store.rs +++ b/examples/key_value_store.rs @@ -11,6 +11,7 @@ use awebframework::{ prelude::*, response::IntoResponse, routing::BoxRoute, + service::ServiceExt, }; use bytes::Bytes; use http::StatusCode; @@ -53,7 +54,8 @@ async fn main() { .into_inner(), ) // Handle errors from middleware - .handle_error(handle_error); + .handle_error(handle_error) + .check_infallible(); // Run our app with hyper let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); diff --git a/src/buffer.rs b/src/buffer.rs new file mode 100644 index 00000000..21697c12 --- /dev/null +++ b/src/buffer.rs @@ -0,0 +1,190 @@ +use futures_util::ready; +use pin_project::pin_project; +use std::{ + future::Future, + pin::Pin, + sync::Arc, + task::{Context, Poll}, +}; +use tokio::sync::{mpsc, oneshot, OwnedSemaphorePermit, Semaphore}; +use tokio_util::sync::PollSemaphore; +use tower::{Service, ServiceExt}; + +/// A version of [`tower::buffer::Buffer`] which panicks on channel related errors, thus keeping +/// the error type of the service. +pub(crate) struct MpscBuffer +where + S: Service, +{ + tx: mpsc::UnboundedSender>, + semaphore: PollSemaphore, + permit: Option, +} + +impl Clone for MpscBuffer +where + S: Service, +{ + fn clone(&self) -> Self { + Self { + tx: self.tx.clone(), + semaphore: self.semaphore.clone(), + permit: None, + } + } +} + +impl MpscBuffer +where + S: Service, +{ + pub(crate) fn new(svc: S) -> Self + where + S: Send + 'static, + R: Send + 'static, + S::Error: Send + 'static, + S::Future: Send + 'static, + { + let (tx, rx) = mpsc::unbounded_channel::>(); + let semaphore = PollSemaphore::new(Arc::new(Semaphore::new(1024))); + + tokio::spawn(run_worker(svc, rx)); + + Self { + tx, + semaphore, + permit: None, + } + } +} + +async fn run_worker(mut svc: S, mut rx: mpsc::UnboundedReceiver>) +where + S: Service, +{ + while let Some((req, reply_tx)) = rx.recv().await { + match svc.ready().await { + Ok(svc) => { + let future = svc.call(req); + let _ = reply_tx.send(WorkerReply::Future(future)); + } + Err(err) => { + let _ = reply_tx.send(WorkerReply::Error(err)); + } + } + } +} + +type Msg = ( + R, + oneshot::Sender>::Future, >::Error>>, +); + +enum WorkerReply { + Future(F), + Error(E), +} + +impl Service for MpscBuffer +where + S: Service, +{ + type Response = S::Response; + type Error = S::Error; + type Future = ResponseFuture; + + fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + if self.permit.is_some() { + return Poll::Ready(Ok(())); + } + + let permit = ready!(self.semaphore.poll_acquire(cx)) + .expect("buffer semaphore closed. This is a bug in awebframework and should never happen. Please file an issue"); + + self.permit = Some(permit); + + Poll::Ready(Ok(())) + } + + fn call(&mut self, req: R) -> Self::Future { + let permit = self + .permit + .take() + .expect("semaphore permit missing. Did you forget to call `poll_ready`?"); + + let (reply_tx, reply_rx) = oneshot::channel::>(); + + self.tx.send((req, reply_tx)).unwrap_or_else(|_| { + panic!("buffer worker not running. This is a bug in awebframework and should never happen. Please file an issue") + }); + + ResponseFuture { + state: State::Channel(reply_rx), + permit, + } + } +} + +#[pin_project] +pub(crate) struct ResponseFuture { + #[pin] + state: State, + permit: OwnedSemaphorePermit, +} + +#[pin_project(project = StateProj)] +enum State { + Channel(oneshot::Receiver>), + Future(#[pin] F), +} + +impl Future for ResponseFuture +where + F: Future>, +{ + type Output = Result; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + loop { + let mut this = self.as_mut().project(); + + let new_state = match this.state.as_mut().project() { + StateProj::Channel(reply_rx) => { + let msg = ready!(Pin::new(reply_rx).poll(cx)) + .expect("buffer worker not running. This is a bug in awebframework and should never happen. Please file an issue"); + + match msg { + WorkerReply::Future(future) => State::Future(future), + WorkerReply::Error(err) => return Poll::Ready(Err(err)), + } + } + StateProj::Future(future) => { + return future.poll(cx); + } + }; + + this.state.set(new_state); + } + } +} + +#[cfg(test)] +mod tests { + #[allow(unused_imports)] + use super::*; + use tower::ServiceExt; + + #[tokio::test] + async fn test_buffer() { + let mut svc = MpscBuffer::new(tower::service_fn(handle)); + + let res = svc.ready().await.unwrap().call(42).await.unwrap(); + + assert_eq!(res, "foo"); + } + + async fn handle(req: i32) -> Result<&'static str, std::convert::Infallible> { + assert_eq!(req, 42); + Ok("foo") + } +} diff --git a/src/handler/mod.rs b/src/handler/mod.rs index e1ea5d41..c015672a 100644 --- a/src/handler/mod.rs +++ b/src/handler/mod.rs @@ -263,7 +263,7 @@ pub trait Handler: Sized { /// # }; /// ``` /// - /// When adding middleware that might fail its required to handle those + /// When adding middleware that might fail its recommended to handle those /// errors. See [`Layered::handle_error`] for more details. fn layer(self, layer: L) -> Layered where @@ -397,11 +397,10 @@ impl Layered { /// Create a new [`Layered`] handler where errors will be handled using the /// given closure. /// - /// awebframework requires that services gracefully handles all errors. That - /// means when you apply a Tower middleware that adds a new failure - /// condition you have to handle that as well. + /// This is used to convert errors to responses rather than simply + /// terminating the connection. /// - /// That can be done using `handle_error` like so: + /// `handle_error` can be used like so: /// /// ```rust /// use awebframework::prelude::*; @@ -415,7 +414,7 @@ impl Layered { /// let layered_handler = handler /// .layer(TimeoutLayer::new(Duration::from_secs(30))); /// - /// // ...so we must handle that error + /// // ...so we should handle that error /// let layered_handler = layered_handler.handle_error(|error: BoxError| { /// if error.is::() { /// ( diff --git a/src/lib.rs b/src/lib.rs index e3d4670e..592abbd6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -304,17 +304,17 @@ //! //! ## Error handling //! -//! awebframework requires all errors to be handled. That is done by using -//! [`std::convert::Infallible`] as the error type in all its [`Service`] -//! implementations. +//! Handlers created from async functions must always produce a response, even +//! when returning a `Result` the error type must implement +//! [`IntoResponse`]. In practice this makes error handling very perdictable and +//! easier to reason about. //! -//! For handlers created from async functions this is works automatically since -//! handlers must return something that implements -//! [`IntoResponse`](response::IntoResponse), even if its a `Result`. -//! -//! However middleware might add new failure cases that has to be handled. For -//! that awebframework provides a [`handle_error`](handler::Layered::handle_error) -//! combinator: +//! However when applying middleware, or embedding other tower services, errors +//! might happen. For example [`Timeout`] will return an error if the timeout +//! elapses. By default these errors will be propagated all the way up to hyper +//! where the connection will be closed. If that isn't desireable you can call +//! [`handle_error`](handler::Layered::handle_error) to handle errors from +//! adding a middleware to a handler: //! //! ```rust,no_run //! use awebframework::prelude::*; @@ -488,7 +488,6 @@ //! "/static/Cargo.toml", //! service::get( //! ServeFile::new("Cargo.toml") -//! // Errors must be handled //! .handle_error(|error: std::io::Error| { /* ... */ }) //! ) //! ); @@ -508,7 +507,6 @@ //! use awebframework::{prelude::*, routing::BoxRoute, body::{Body, BoxBody}}; //! use tower_http::services::ServeFile; //! use http::Response; -//! use std::convert::Infallible; //! //! fn api_routes() -> BoxRoute { //! route("/users", get(|_: Request| async { /* ... */ })).boxed() @@ -527,7 +525,6 @@ //! use awebframework::{prelude::*, service::ServiceExt, routing::nest}; //! use tower_http::services::ServeDir; //! use http::Response; -//! use std::convert::Infallible; //! use tower::{service_fn, BoxError}; //! //! let app = nest( @@ -558,6 +555,8 @@ //! [tokio]: http://crates.io/crates/tokio //! [hyper]: http://crates.io/crates/hyper //! [feature flags]: https://doc.rust-lang.org/cargo/reference/features.html#the-features-section +//! [`IntoResponse`]: crate::response::IntoResponse +//! [`Timeout`]: tower::timeout::Timeout #![doc(html_root_url = "https://docs.rs/tower-http/0.1.0")] #![warn( @@ -609,12 +608,12 @@ use self::body::Body; use http::Request; use routing::{EmptyRouter, Route}; -use std::convert::Infallible; use tower::Service; #[macro_use] pub(crate) mod macros; +mod buffer; mod util; pub mod body; @@ -661,12 +660,6 @@ pub mod prelude { /// `service` is the [`Service`] that should receive the request if the path /// matches `description`. /// -/// Note that `service`'s error type must be [`Infallible`] meaning you must -/// handle all errors. If you're creating handlers from async functions that is -/// handled automatically but if you're routing to some other [`Service`] you -/// might need to use [`handle_error`](service::ServiceExt::handle_error) to map -/// errors into responses. -/// /// # Examples /// /// ```rust @@ -688,7 +681,7 @@ pub mod prelude { /// Panics if `description` doesn't start with `/`. pub fn route(description: &str, service: S) -> Route where - S: Service, Error = Infallible> + Clone, + S: Service> + Clone, { use routing::RoutingDsl; diff --git a/src/routing.rs b/src/routing.rs index 288b8500..fee6274f 100644 --- a/src/routing.rs +++ b/src/routing.rs @@ -1,11 +1,10 @@ //! Routing between [`Service`]s. -use crate::{body::BoxBody, response::IntoResponse, util::ByteStr}; +use crate::{body::BoxBody, buffer::MpscBuffer, response::IntoResponse, util::ByteStr}; use async_trait::async_trait; use bytes::Bytes; -use futures_util::{future, ready}; +use futures_util::future; use http::{Method, Request, Response, StatusCode, Uri}; -use http_body::Full; use pin_project::pin_project; use regex::Regex; use std::{ @@ -18,7 +17,6 @@ use std::{ task::{Context, Poll}, }; use tower::{ - buffer::Buffer, util::{BoxService, Oneshot, ServiceExt}, BoxError, Layer, Service, ServiceBuilder, }; @@ -106,7 +104,7 @@ pub trait RoutingDsl: crate::sealed::Sealed + Sized { /// ``` fn route(self, description: &str, svc: T) -> Route where - T: Service, Error = Infallible> + Clone, + T: Service> + Clone, { Route { pattern: PathPattern::new(description), @@ -120,7 +118,7 @@ pub trait RoutingDsl: crate::sealed::Sealed + Sized { /// See [`nest`] for more details. fn nest(self, description: &str, svc: T) -> Nested where - T: Service, Error = Infallible> + Clone, + T: Service> + Clone, { Nested { pattern: PathPattern::new(description), @@ -152,11 +150,10 @@ pub trait RoutingDsl: crate::sealed::Sealed + Sized { /// /// It also helps with compile times when you have a very large number of /// routes. - fn boxed(self) -> BoxRoute + fn boxed(self) -> BoxRoute where - Self: Service, Response = Response, Error = Infallible> - + Send - + 'static, + Self: Service, Response = Response> + Send + 'static, + >>::Error: Into + Send + Sync, >>::Future: Send, ReqBody: http_body::Body + Send + Sync + 'static, ReqBody::Error: Into + Send + Sync + 'static, @@ -165,7 +162,7 @@ pub trait RoutingDsl: crate::sealed::Sealed + Sized { { ServiceBuilder::new() .layer_fn(BoxRoute) - .buffer(1024) + .layer_fn(MpscBuffer::new) .layer(BoxService::layer()) .layer(MapResponseBodyLayer::new(BoxBody::new)) .service(self) @@ -231,9 +228,6 @@ pub trait RoutingDsl: crate::sealed::Sealed + Sized { /// # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); /// # }; /// ``` - /// - /// When adding middleware that might fail its required to handle those - /// errors. See [`Layered::handle_error`] for more details. fn layer(self, layer: L) -> Layered where L: Layer, @@ -275,11 +269,11 @@ impl crate::sealed::Sealed for Route {} impl Service> for Route where - S: Service, Response = Response, Error = Infallible> + Clone, - F: Service, Response = Response, Error = Infallible> + Clone, + S: Service, Response = Response> + Clone, + F: Service, Response = Response, Error = S::Error> + Clone, { type Response = Response; - type Error = Infallible; + type Error = S::Error; type Future = RouteFuture; fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { @@ -333,10 +327,10 @@ where impl Future for RouteFuture where - S: Service, Response = Response, Error = Infallible>, - F: Service, Response = Response, Error = Infallible>, + S: Service, Response = Response>, + F: Service, Response = Response, Error = S::Error>, { - type Output = Result, Infallible>; + type Output = Result, S::Error>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { match self.project().0.project() { @@ -491,28 +485,33 @@ type Captures = Vec<(String, String)>; /// A boxed route trait object. /// /// See [`RoutingDsl::boxed`] for more details. -pub struct BoxRoute(Buffer, Response, Infallible>, Request>); +pub struct BoxRoute( + MpscBuffer, Response, E>, Request>, +); -impl Clone for BoxRoute { +impl Clone for BoxRoute { fn clone(&self) -> Self { Self(self.0.clone()) } } -impl fmt::Debug for BoxRoute { +impl fmt::Debug for BoxRoute { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("BoxRoute").finish() } } -impl RoutingDsl for BoxRoute {} +impl RoutingDsl for BoxRoute {} -impl crate::sealed::Sealed for BoxRoute {} +impl crate::sealed::Sealed for BoxRoute {} -impl Service> for BoxRoute { +impl Service> for BoxRoute +where + E: Into, +{ type Response = Response; - type Error = Infallible; - type Future = BoxRouteFuture; + type Error = E; + type Future = BoxRouteFuture; #[inline] fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { @@ -521,66 +520,43 @@ impl Service> for BoxRoute { #[inline] fn call(&mut self, req: Request) -> Self::Future { - BoxRouteFuture(self.0.clone().oneshot(req)) + BoxRouteFuture { + inner: self.0.clone().oneshot(req), + } } } /// The response future for [`BoxRoute`]. #[pin_project] -pub struct BoxRouteFuture(#[pin] InnerFuture); +pub struct BoxRouteFuture +where + E: Into, +{ + #[pin] + inner: + Oneshot, Response, E>, Request>, Request>, +} -type InnerFuture = - Oneshot, Response, Infallible>, Request>, Request>; +impl Future for BoxRouteFuture +where + E: Into, +{ + type Output = Result, E>; -impl fmt::Debug for BoxRouteFuture { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + self.project().inner.poll(cx) + } +} + +impl fmt::Debug for BoxRouteFuture +where + E: Into, +{ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("BoxRouteFuture").finish() } } -impl Future for BoxRouteFuture { - type Output = Result, Infallible>; - - fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - match ready!(self.project().0.poll(cx)) { - Ok(res) => Poll::Ready(Ok(res)), - Err(err) => Poll::Ready(Ok(handle_buffer_error(err))), - } - } -} - -fn handle_buffer_error(error: BoxError) -> Response { - use tower::buffer::error::{Closed, ServiceError}; - - let error = match error.downcast::() { - Ok(closed) => { - return Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(BoxBody::new(Full::from(closed.to_string()))) - .unwrap(); - } - Err(e) => e, - }; - - let error = match error.downcast::() { - Ok(service_error) => { - return Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(BoxBody::new(Full::from(format!("Service error: {}. This is a bug in awebframework. All inner services should be infallible. Please file an issue", service_error)))) - .unwrap(); - } - Err(e) => e, - }; - - Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(BoxBody::new(Full::from(format!( - "Uncountered an unknown error: {}. This should never happen. Please file an issue", - error - )))) - .unwrap() -} - /// A [`Service`] created from a router by applying a Tower middleware. /// /// Created with [`RoutingDsl::layer`]. See that method for more details. @@ -622,9 +598,8 @@ impl Layered { /// Create a new [`Layered`] service where errors will be handled using the /// given closure. /// - /// awebframework requires that services gracefully handles all errors. That - /// means when you apply a Tower middleware that adds a new failure - /// condition you have to handle that as well. + /// This is used to convert errors to responses rather than simply + /// terminating the connection. /// /// That can be done using `handle_error` like so: /// @@ -640,7 +615,7 @@ impl Layered { /// let layered_app = route("/", get(handler)) /// .layer(TimeoutLayer::new(Duration::from_secs(30))); /// - /// // ...so we must handle that error + /// // ...so we should handle that error /// let with_errors_handled = layered_app.handle_error(|error: BoxError| { /// if error.is::() { /// ( @@ -771,7 +746,7 @@ where /// `nest`. pub fn nest(description: &str, svc: S) -> Nested where - S: Service, Error = Infallible> + Clone, + S: Service> + Clone, { Nested { pattern: PathPattern::new(description), @@ -796,11 +771,11 @@ impl crate::sealed::Sealed for Nested {} impl Service> for Nested where - S: Service, Response = Response, Error = Infallible> + Clone, - F: Service, Response = Response, Error = Infallible> + Clone, + S: Service, Response = Response> + Clone, + F: Service, Response = Response, Error = S::Error> + Clone, { type Response = Response; - type Error = Infallible; + type Error = S::Error; type Future = RouteFuture; fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { diff --git a/src/service/mod.rs b/src/service/mod.rs index 4e9da348..52c9c4d1 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -111,7 +111,7 @@ pub mod future; /// See [`get`] for an example. pub fn any(svc: S) -> OnMethod, EmptyRouter> where - S: Service, Error = Infallible> + Clone, + S: Service> + Clone, { on(MethodFilter::Any, svc) } @@ -121,7 +121,7 @@ where /// See [`get`] for an example. pub fn connect(svc: S) -> OnMethod, EmptyRouter> where - S: Service, Error = Infallible> + Clone, + S: Service> + Clone, { on(MethodFilter::Connect, svc) } @@ -131,7 +131,7 @@ where /// See [`get`] for an example. pub fn delete(svc: S) -> OnMethod, EmptyRouter> where - S: Service, Error = Infallible> + Clone, + S: Service> + Clone, { on(MethodFilter::Delete, svc) } @@ -156,12 +156,9 @@ where /// # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); /// # }; /// ``` -/// -/// You can only add services who cannot fail (their error type must be -/// [`Infallible`]). To gracefully handle errors see [`ServiceExt::handle_error`]. pub fn get(svc: S) -> OnMethod, EmptyRouter> where - S: Service, Error = Infallible> + Clone, + S: Service> + Clone, { on(MethodFilter::Get, svc) } @@ -171,7 +168,7 @@ where /// See [`get`] for an example. pub fn head(svc: S) -> OnMethod, EmptyRouter> where - S: Service, Error = Infallible> + Clone, + S: Service> + Clone, { on(MethodFilter::Head, svc) } @@ -181,7 +178,7 @@ where /// See [`get`] for an example. pub fn options(svc: S) -> OnMethod, EmptyRouter> where - S: Service, Error = Infallible> + Clone, + S: Service> + Clone, { on(MethodFilter::Options, svc) } @@ -191,7 +188,7 @@ where /// See [`get`] for an example. pub fn patch(svc: S) -> OnMethod, EmptyRouter> where - S: Service, Error = Infallible> + Clone, + S: Service> + Clone, { on(MethodFilter::Patch, svc) } @@ -201,7 +198,7 @@ where /// See [`get`] for an example. pub fn post(svc: S) -> OnMethod, EmptyRouter> where - S: Service, Error = Infallible> + Clone, + S: Service> + Clone, { on(MethodFilter::Post, svc) } @@ -211,7 +208,7 @@ where /// See [`get`] for an example. pub fn put(svc: S) -> OnMethod, EmptyRouter> where - S: Service, Error = Infallible> + Clone, + S: Service> + Clone, { on(MethodFilter::Put, svc) } @@ -221,7 +218,7 @@ where /// See [`get`] for an example. pub fn trace(svc: S) -> OnMethod, EmptyRouter> where - S: Service, Error = Infallible> + Clone, + S: Service> + Clone, { on(MethodFilter::Trace, svc) } @@ -248,7 +245,7 @@ where /// ``` pub fn on(method: MethodFilter, svc: S) -> OnMethod, EmptyRouter> where - S: Service, Error = Infallible> + Clone, + S: Service> + Clone, { OnMethod { method, @@ -276,7 +273,7 @@ impl OnMethod { /// See [`OnMethod::get`] for an example. pub fn any(self, svc: T) -> OnMethod, Self> where - T: Service, Error = Infallible> + Clone, + T: Service> + Clone, { self.on(MethodFilter::Any, svc) } @@ -286,7 +283,7 @@ impl OnMethod { /// See [`OnMethod::get`] for an example. pub fn connect(self, svc: T) -> OnMethod, Self> where - T: Service, Error = Infallible> + Clone, + T: Service> + Clone, { self.on(MethodFilter::Connect, svc) } @@ -296,7 +293,7 @@ impl OnMethod { /// See [`OnMethod::get`] for an example. pub fn delete(self, svc: T) -> OnMethod, Self> where - T: Service, Error = Infallible> + Clone, + T: Service> + Clone, { self.on(MethodFilter::Delete, svc) } @@ -326,13 +323,9 @@ impl OnMethod { /// # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); /// # }; /// ``` - /// - /// You can only add services who cannot fail (their error type must be - /// [`Infallible`]). To gracefully handle errors see - /// [`ServiceExt::handle_error`]. pub fn get(self, svc: T) -> OnMethod, Self> where - T: Service, Error = Infallible> + Clone, + T: Service> + Clone, { self.on(MethodFilter::Get, svc) } @@ -342,7 +335,7 @@ impl OnMethod { /// See [`OnMethod::get`] for an example. pub fn head(self, svc: T) -> OnMethod, Self> where - T: Service, Error = Infallible> + Clone, + T: Service> + Clone, { self.on(MethodFilter::Head, svc) } @@ -352,7 +345,7 @@ impl OnMethod { /// See [`OnMethod::get`] for an example. pub fn options(self, svc: T) -> OnMethod, Self> where - T: Service, Error = Infallible> + Clone, + T: Service> + Clone, { self.on(MethodFilter::Options, svc) } @@ -362,7 +355,7 @@ impl OnMethod { /// See [`OnMethod::get`] for an example. pub fn patch(self, svc: T) -> OnMethod, Self> where - T: Service, Error = Infallible> + Clone, + T: Service> + Clone, { self.on(MethodFilter::Patch, svc) } @@ -372,7 +365,7 @@ impl OnMethod { /// See [`OnMethod::get`] for an example. pub fn post(self, svc: T) -> OnMethod, Self> where - T: Service, Error = Infallible> + Clone, + T: Service> + Clone, { self.on(MethodFilter::Post, svc) } @@ -382,7 +375,7 @@ impl OnMethod { /// See [`OnMethod::get`] for an example. pub fn put(self, svc: T) -> OnMethod, Self> where - T: Service, Error = Infallible> + Clone, + T: Service> + Clone, { self.on(MethodFilter::Put, svc) } @@ -392,7 +385,7 @@ impl OnMethod { /// See [`OnMethod::get`] for an example. pub fn trace(self, svc: T) -> OnMethod, Self> where - T: Service, Error = Infallible> + Clone, + T: Service> + Clone, { self.on(MethodFilter::Trace, svc) } @@ -424,7 +417,7 @@ impl OnMethod { /// ``` pub fn on(self, method: MethodFilter, svc: T) -> OnMethod, Self> where - T: Service, Error = Infallible> + Clone, + T: Service> + Clone, { OnMethod { method, @@ -441,11 +434,11 @@ impl OnMethod { // that up, but not sure its possible. impl Service> for OnMethod where - S: Service, Response = Response, Error = Infallible> + Clone, - F: Service, Response = Response, Error = Infallible> + Clone, + S: Service, Response = Response> + Clone, + F: Service, Response = Response, Error = S::Error> + Clone, { type Response = Response; - type Error = Infallible; + type Error = S::Error; type Future = RouteFuture; fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { @@ -541,11 +534,6 @@ pub trait ServiceExt: { /// Handle errors from a service. /// - /// awebframework requires all handlers and services, that are part of the - /// router, to never return errors. If you route to [`Service`], not created - /// by awebframework, who's error isn't `Infallible` you can use this combinator - /// to handle the error. - /// /// `handle_error` takes a closure that will map errors from the service /// into responses. The closure's return type must implement /// [`IntoResponse`]. @@ -584,6 +572,16 @@ pub trait ServiceExt: { HandleError::new(self, f) } + + /// Check that your service cannot fail. + /// + /// That is its error type is [`Infallible`]. + fn check_infallible(self) -> Self + where + Self: Service, Response = Response, Error = Infallible> + Sized, + { + self + } } impl ServiceExt for S where @@ -622,12 +620,12 @@ where impl Service> for BoxResponseBody where - S: Service, Response = Response, Error = Infallible> + Clone, + S: Service, Response = Response> + Clone, ResBody: http_body::Body + Send + Sync + 'static, ResBody::Error: Into + Send + Sync + 'static, { type Response = Response; - type Error = Infallible; + type Error = S::Error; type Future = BoxResponseBodyFuture>>; fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { @@ -645,13 +643,13 @@ where #[derive(Debug)] pub struct BoxResponseBodyFuture(#[pin] F); -impl Future for BoxResponseBodyFuture +impl Future for BoxResponseBodyFuture where - F: Future, Infallible>>, + F: Future, E>>, B: http_body::Body + Send + Sync + 'static, B::Error: Into + Send + Sync + 'static, { - type Output = Result, Infallible>; + type Output = Result, E>; fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let res = ready!(self.project().0.poll(cx))?;