Files
axum/src/handler.rs
T

239 lines
5.9 KiB
Rust
Raw Normal View History

2021-06-06 11:37:08 +02:00
use crate::{
body::Body,
extract::FromRequest,
response::IntoResponse,
routing::{EmptyRouter, MethodFilter, OnMethod},
service::{self, HandleError},
};
2021-05-30 13:24:03 +02:00
use async_trait::async_trait;
2021-06-01 17:17:10 +02:00
use bytes::Bytes;
2021-05-30 13:24:03 +02:00
use futures_util::future;
use http::{Request, Response};
use std::{
2021-05-31 22:54:21 +02:00
convert::Infallible,
2021-05-30 13:24:03 +02:00
future::Future,
marker::PhantomData,
task::{Context, Poll},
};
2021-06-06 11:37:08 +02:00
use tower::{BoxError, Layer, Service, ServiceExt};
pub fn get<H, B, T>(handler: H) -> OnMethod<IntoService<H, B, T>, EmptyRouter>
where
H: Handler<B, T>,
{
on(MethodFilter::Get, handler)
}
pub fn post<H, B, T>(handler: H) -> OnMethod<IntoService<H, B, T>, EmptyRouter>
where
H: Handler<B, T>,
{
on(MethodFilter::Post, handler)
}
pub fn on<H, B, T>(method: MethodFilter, handler: H) -> OnMethod<IntoService<H, B, T>, EmptyRouter>
where
H: Handler<B, T>,
{
service::on(method, handler.into_service())
}
2021-05-30 13:24:03 +02:00
mod sealed {
2021-06-06 11:37:08 +02:00
#![allow(unreachable_pub)]
2021-05-30 13:24:03 +02:00
pub trait HiddentTrait {}
pub struct Hidden;
impl HiddentTrait for Hidden {}
}
#[async_trait]
pub trait Handler<B, In>: Sized {
type Response: IntoResponse<B>;
// This seals the trait. We cannot use the regular "sealed super trait" approach
// due to coherence.
#[doc(hidden)]
type Sealed: sealed::HiddentTrait;
2021-05-31 22:54:21 +02:00
async fn call(self, req: Request<Body>) -> Response<B>;
2021-05-30 13:24:03 +02:00
fn layer<L>(self, layer: L) -> Layered<L::Service, In>
where
2021-06-06 11:37:08 +02:00
L: Layer<IntoService<Self, B, In>>,
2021-05-30 13:24:03 +02:00
{
2021-06-06 11:37:08 +02:00
Layered::new(layer.layer(IntoService::new(self)))
}
fn into_service(self) -> IntoService<Self, B, In> {
IntoService::new(self)
2021-05-30 13:24:03 +02:00
}
}
#[async_trait]
impl<F, Fut, B, Res> Handler<B, ()> for F
where
2021-06-01 08:32:58 +02:00
F: FnOnce(Request<Body>) -> Fut + Send + Sync,
2021-05-31 20:42:57 +02:00
Fut: Future<Output = Res> + Send,
2021-05-30 13:24:03 +02:00
Res: IntoResponse<B>,
{
type Response = Res;
type Sealed = sealed::Hidden;
2021-05-31 22:54:21 +02:00
async fn call(self, req: Request<Body>) -> Response<B> {
2021-05-31 20:42:57 +02:00
self(req).await.into_response()
2021-05-30 13:24:03 +02:00
}
}
macro_rules! impl_handler {
2021-05-30 16:53:27 +02:00
() => {};
2021-05-30 13:24:03 +02:00
( $head:ident, $($tail:ident),* $(,)? ) => {
#[async_trait]
#[allow(non_snake_case)]
impl<F, Fut, B, Res, $head, $($tail,)*> Handler<B, ($head, $($tail,)*)> for F
where
2021-06-01 08:32:58 +02:00
F: FnOnce(Request<Body>, $head, $($tail,)*) -> Fut + Send + Sync,
2021-05-31 20:42:57 +02:00
Fut: Future<Output = Res> + Send,
2021-05-30 13:24:03 +02:00
Res: IntoResponse<B>,
2021-05-31 22:54:21 +02:00
$head: FromRequest<B> + Send,
$( $tail: FromRequest<B> + Send, )*
2021-05-30 13:24:03 +02:00
{
type Response = Res;
type Sealed = sealed::Hidden;
2021-05-31 22:54:21 +02:00
async fn call(self, mut req: Request<Body>) -> Response<B> {
let $head = match $head::from_request(&mut req).await {
Ok(value) => value,
Err(rejection) => return rejection.into_response(),
};
2021-05-30 13:24:03 +02:00
$(
2021-05-31 22:54:21 +02:00
let $tail = match $tail::from_request(&mut req).await {
Ok(value) => value,
Err(rejection) => return rejection.into_response(),
};
2021-05-30 13:24:03 +02:00
)*
2021-05-31 22:54:21 +02:00
2021-05-31 20:42:57 +02:00
let res = self(req, $head, $($tail,)*).await;
2021-05-31 22:54:21 +02:00
2021-05-31 20:42:57 +02:00
res.into_response()
2021-05-30 13:24:03 +02:00
}
}
impl_handler!($($tail,)*);
};
}
impl_handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16);
pub struct Layered<S, T> {
svc: S,
_input: PhantomData<fn() -> T>,
}
impl<S, T> Clone for Layered<S, T>
where
S: Clone,
{
fn clone(&self) -> Self {
Self::new(self.svc.clone())
}
}
#[async_trait]
impl<S, B, T> Handler<B, T> for Layered<S, T>
where
S: Service<Request<Body>, Response = Response<B>> + Send,
2021-05-31 22:54:21 +02:00
S::Error: IntoResponse<B>,
S::Response: IntoResponse<B>,
2021-05-30 13:24:03 +02:00
S::Future: Send,
{
type Response = S::Response;
type Sealed = sealed::Hidden;
2021-05-31 22:54:21 +02:00
async fn call(self, req: Request<Body>) -> Self::Response {
// TODO(david): add tests for nesting services
match self
.svc
2021-05-30 13:24:03 +02:00
.oneshot(req)
.await
2021-05-31 22:54:21 +02:00
.map_err(IntoResponse::into_response)
{
Ok(res) => res,
Err(res) => res,
}
2021-05-30 13:24:03 +02:00
}
}
impl<S, T> Layered<S, T> {
pub(crate) fn new(svc: S) -> Self {
Self {
svc,
_input: PhantomData,
}
}
2021-06-01 17:17:10 +02:00
2021-06-04 01:00:48 +02:00
pub fn handle_error<F, B, Res>(self, f: F) -> Layered<HandleError<S, F>, T>
2021-06-01 17:17:10 +02:00
where
S: Service<Request<Body>, Response = Response<B>>,
F: FnOnce(S::Error) -> Res,
2021-06-04 01:00:48 +02:00
Res: IntoResponse<B>,
2021-06-01 17:17:10 +02:00
B: http_body::Body<Data = Bytes> + Send + Sync + 'static,
B::Error: Into<BoxError> + Send + Sync + 'static,
{
let svc = HandleError::new(self.svc, f);
Layered::new(svc)
}
2021-05-30 13:24:03 +02:00
}
2021-06-06 11:37:08 +02:00
pub struct IntoService<H, B, T> {
2021-05-30 13:24:03 +02:00
handler: H,
2021-06-06 11:37:08 +02:00
_marker: PhantomData<fn() -> (B, T)>,
2021-05-30 13:24:03 +02:00
}
2021-06-06 11:37:08 +02:00
impl<H, B, T> IntoService<H, B, T> {
fn new(handler: H) -> Self {
2021-05-30 13:24:03 +02:00
Self {
handler,
2021-06-06 11:37:08 +02:00
_marker: PhantomData,
2021-05-30 13:24:03 +02:00
}
}
}
2021-06-06 11:37:08 +02:00
impl<H, B, T> Clone for IntoService<H, B, T>
2021-05-30 13:24:03 +02:00
where
H: Clone,
{
fn clone(&self) -> Self {
Self {
handler: self.handler.clone(),
2021-06-06 11:37:08 +02:00
_marker: PhantomData,
2021-05-30 13:24:03 +02:00
}
}
}
2021-06-06 11:37:08 +02:00
impl<H, B, T> Service<Request<Body>> for IntoService<H, B, T>
2021-05-30 13:24:03 +02:00
where
H: Handler<B, T> + Clone + Send + 'static,
H::Response: 'static,
{
type Response = Response<B>;
2021-05-31 22:54:21 +02:00
type Error = Infallible;
2021-05-30 13:24:03 +02:00
type Future = future::BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
2021-06-06 11:37:08 +02:00
// `IntoService` can only be constructed from async functions which are always ready, or from
2021-05-30 13:24:03 +02:00
// `Layered` which bufferes in `<Layered as Handler>::call` and is therefore also always
// ready.
Poll::Ready(Ok(()))
}
fn call(&mut self, req: Request<Body>) -> Self::Future {
let handler = self.handler.clone();
2021-05-31 22:54:21 +02:00
Box::pin(async move { Ok(Handler::call(handler, req).await) })
2021-05-30 13:24:03 +02:00
}
}