navree_http/fallible.rs
1//! [`FallibleLayer`]: a tower layer whose service can fail, made into one the
2//! app can mount, and [`FallibleService`], what it makes.
3
4use std::convert::Infallible;
5use std::task::{Context, Poll};
6
7use bytes::Bytes;
8use navree_kernel::{BoxError, BoxFuture};
9use tower::{Layer, Service, ServiceExt};
10
11use crate::body::{Body, HttpBody};
12use crate::error::AppError;
13use crate::extract::Request;
14use crate::response::{IntoResponse, Response};
15
16/// A tower layer whose service can fail, made into one the app can mount
17/// ([`AppRouter::layer`](crate::AppRouter::layer),
18/// [`Endpoint::layer`](crate::handler::Endpoint::layer),
19/// [`Router::route_layer`](crate::routing::Router::route_layer)): the
20/// service's error becomes a 500 [`AppError`] with the error as its source,
21/// so the app's error mapping
22/// ([`m.map_error`](crate::ModuleBuilderHttpExt::map_error)) and JSON error
23/// shape apply; its response body is taken as the app's body.
24///
25/// The service is cloned for each request and asked first whether it is
26/// ready: an error there (a load shedder's, say) answers like an error of
27/// the call. Without a mapping the client sees `"Internal server error"`,
28/// and the error is logged, never sent. That holds in every
29/// [`LayerSlot`](crate::LayerSlot) but `Edge`, which sits outside the app's
30/// error rendering: there the error answers as a 500 in the JSON error
31/// shape, neither mapped nor logged.
32///
33/// ```
34/// use std::time::Duration;
35///
36/// use navree_http::{AppError, FallibleLayer, GlobalLayer, LayerSlot, ModuleBuilderHttpExt};
37/// use navree_kernel::{Module, ModuleBuilder};
38///
39/// struct LedgerModule;
40///
41/// impl Module for LedgerModule {
42/// fn register(&self, m: &mut ModuleBuilder) {
43/// m.http_layer(GlobalLayer::new(LayerSlot::Context, "timeout", |_, router| {
44/// Ok(router.layer(FallibleLayer::new(tower::timeout::TimeoutLayer::new(
45/// Duration::from_secs(10),
46/// ))))
47/// }))
48/// // The timeout's error answers 503 instead of 500.
49/// .map_error::<tower::timeout::error::Elapsed>(|_| {
50/// Some(AppError::service_unavailable("The khata took too long."))
51/// });
52/// }
53/// }
54/// ```
55#[derive(Clone, Debug)]
56pub struct FallibleLayer<L> {
57 /// The layer whose service can fail.
58 layer: L,
59}
60
61impl<L> FallibleLayer<L> {
62 /// Wraps `layer`, whose service may answer with an error.
63 pub fn new(layer: L) -> FallibleLayer<L> {
64 FallibleLayer { layer }
65 }
66}
67
68impl<S, L, B> Layer<S> for FallibleLayer<L>
69where
70 L: Layer<S>,
71 L::Service: Service<Request, Response = http::Response<B>> + Clone + Send + Sync + 'static,
72 <L::Service as Service<Request>>::Error: Into<BoxError>,
73 <L::Service as Service<Request>>::Future: Send + 'static,
74 B: HttpBody<Data = Bytes> + Send + 'static,
75 B::Error: Into<BoxError>,
76{
77 type Service = FallibleService<L::Service>;
78
79 fn layer(&self, inner: S) -> Self::Service {
80 FallibleService {
81 inner: self.layer.layer(inner),
82 }
83 }
84}
85
86/// What [`FallibleLayer`] makes: a service with `Error = Infallible` and
87/// `Response = navree_http::response::Response`. An error of the wrapped
88/// service, at its readiness or its call, answers as
89/// [`AppError::internal`] of that error.
90///
91/// ```
92/// # #[tokio::main(flavor = "current_thread")]
93/// # async fn main() {
94/// use http::StatusCode;
95/// use navree_http::FallibleLayer;
96/// use navree_http::body::Body;
97/// use navree_http::extract::Request;
98/// use tower::{Layer, ServiceExt};
99///
100/// // A service of another crate that fails.
101/// let lost = tower::service_fn(|_request: Request| async {
102/// Err::<http::Response<Body>, _>(std::io::Error::other("the khata of Jaipur is lost"))
103/// });
104/// let service = FallibleLayer::new(tower::layer::util::Identity::new()).layer(lost);
105/// let response = service.oneshot(Request::new(Body::empty())).await.unwrap();
106/// assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
107/// # }
108/// ```
109#[derive(Clone, Debug)]
110pub struct FallibleService<S> {
111 /// The service whose errors become 500s.
112 inner: S,
113}
114
115impl<S, B> Service<Request> for FallibleService<S>
116where
117 S: Service<Request, Response = http::Response<B>> + Clone + Send + Sync + 'static,
118 S::Error: Into<BoxError>,
119 S::Future: Send + 'static,
120 B: HttpBody<Data = Bytes> + Send + 'static,
121 B::Error: Into<BoxError>,
122{
123 type Response = Response;
124 type Error = Infallible;
125 type Future = BoxFuture<'static, Result<Response, Infallible>>;
126
127 /// Always ready: the inner service's readiness is asked for each call.
128 #[inline]
129 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
130 Poll::Ready(Ok(()))
131 }
132
133 fn call(&mut self, request: Request) -> Self::Future {
134 let service = self.inner.clone();
135 Box::pin(async move {
136 Ok(match service.oneshot(request).await {
137 Ok(response) => response.map(Body::new),
138 Err(error) => AppError::internal(error).into_response(),
139 })
140 })
141 }
142}