Files
axum/src/lib.rs
T

250 lines
6.3 KiB
Rust
Raw Normal View History

2021-05-30 13:24:03 +02:00
use self::{
2021-05-31 10:20:07 +02:00
body::Body,
2021-05-31 16:28:26 +02:00
routing::{AlwaysNotFound, RouteAt},
2021-05-30 13:24:03 +02:00
};
use body::BoxBody;
2021-05-29 21:13:06 +02:00
use bytes::Bytes;
2021-05-31 10:20:07 +02:00
use futures_util::ready;
use http::{Request, Response};
2021-05-30 01:11:18 +02:00
use pin_project::pin_project;
2021-06-01 17:17:10 +02:00
use response::IntoResponse;
2021-05-29 21:13:06 +02:00
use std::{
2021-06-01 00:34:09 +02:00
convert::Infallible,
fmt,
2021-05-29 21:13:06 +02:00
future::Future,
2021-05-30 01:11:18 +02:00
pin::Pin,
2021-05-29 21:13:06 +02:00
task::{Context, Poll},
};
use tower::{BoxError, Service};
2021-05-29 21:13:06 +02:00
2021-05-30 13:24:03 +02:00
pub mod body;
pub mod extract;
pub mod handler;
pub mod response;
pub mod routing;
2021-06-01 14:52:18 +02:00
pub use async_trait::async_trait;
2021-06-01 17:17:10 +02:00
pub use tower_http::add_extension::{AddExtension, AddExtensionLayer};
2021-06-01 14:52:18 +02:00
2021-05-31 12:22:16 +02:00
#[cfg(test)]
mod tests;
2021-05-31 16:28:26 +02:00
pub fn app() -> App<AlwaysNotFound> {
2021-05-29 21:13:06 +02:00
App {
2021-05-31 16:28:26 +02:00
service_tree: AlwaysNotFound(()),
2021-05-29 21:13:06 +02:00
}
}
2021-05-30 00:52:04 +02:00
#[derive(Debug, Clone)]
2021-05-29 21:13:06 +02:00
pub struct App<R> {
2021-05-31 16:28:26 +02:00
service_tree: R,
2021-05-29 21:13:06 +02:00
}
impl<R> App<R> {
2021-06-01 21:15:48 +02:00
fn new(service_tree: R) -> Self {
Self { service_tree }
}
2021-05-30 00:52:04 +02:00
pub fn at(self, route_spec: &str) -> RouteAt<R> {
self.at_bytes(Bytes::copy_from_slice(route_spec.as_bytes()))
}
fn at_bytes(self, route_spec: Bytes) -> RouteAt<R> {
RouteAt {
2021-05-29 21:13:06 +02:00
app: self,
2021-05-30 00:52:04 +02:00
route_spec,
2021-05-29 21:13:06 +02:00
}
}
}
2021-06-01 21:15:48 +02:00
#[derive(Clone)]
2021-05-30 04:28:24 +02:00
pub struct IntoService<R> {
2021-06-01 21:15:48 +02:00
service_tree: R
2021-05-30 04:28:24 +02:00
}
impl<R, B, T> Service<T> for IntoService<R>
where
2021-06-01 00:34:09 +02:00
R: Service<T, Response = Response<B>, Error = Infallible>,
2021-05-30 04:28:24 +02:00
B: Default,
2021-05-29 21:13:06 +02:00
{
2021-05-30 04:28:24 +02:00
type Response = Response<B>;
2021-06-01 00:34:09 +02:00
type Error = Infallible;
type Future = R::Future;
2021-05-29 21:13:06 +02:00
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
2021-06-01 21:15:48 +02:00
match ready!(self.service_tree.poll_ready(cx)) {
2021-06-01 00:34:09 +02:00
Ok(_) => Poll::Ready(Ok(())),
Err(err) => match err {},
2021-05-30 13:24:03 +02:00
}
2021-05-29 21:13:06 +02:00
}
2021-05-30 00:52:04 +02:00
fn call(&mut self, req: T) -> Self::Future {
2021-06-01 21:15:48 +02:00
self.service_tree.call(req)
2021-06-01 00:34:09 +02:00
}
}
pub(crate) trait ResultExt<T> {
fn unwrap_infallible(self) -> T;
}
impl<T> ResultExt<T> for Result<T, Infallible> {
fn unwrap_infallible(self) -> T {
match self {
Ok(value) => value,
Err(err) => match err {},
2021-05-30 04:28:24 +02:00
}
2021-05-30 00:52:04 +02:00
}
2021-05-30 04:28:24 +02:00
}
2021-06-01 00:34:09 +02:00
// work around for `BoxError` not implementing `std::error::Error`
//
// This is currently required since tower-http's Compression middleware's body type's
// error only implements error when the inner error type does:
// https://github.com/tower-rs/tower-http/blob/master/tower-http/src/lib.rs#L310
//
// Fixing that is a breaking change to tower-http so we should wait a bit, but should
// totally fix it at some point.
#[derive(Debug, thiserror::Error)]
#[error("{0}")]
pub struct BoxStdError(#[source] pub(crate) tower::BoxError);
pub trait ServiceExt<B>: Service<Request<Body>, Response = Response<B>> {
2021-06-01 17:17:10 +02:00
fn handle_error<F, Res>(self, f: F) -> HandleError<Self, F, Self::Error>
where
Self: Sized,
2021-06-01 17:17:10 +02:00
F: FnOnce(Self::Error) -> Res,
Res: IntoResponse<Body>,
B: http_body::Body<Data = Bytes> + Send + Sync + 'static,
B::Error: Into<BoxError> + Send + Sync + 'static,
{
2021-06-01 17:17:10 +02:00
HandleError::new(self, f)
}
}
impl<S, B> ServiceExt<B> for S where S: Service<Request<Body>, Response = Response<B>> {}
pub struct HandleError<S, F, E> {
inner: S,
f: F,
poll_ready_error: Option<E>,
}
2021-06-01 17:17:10 +02:00
impl<S, F, E> HandleError<S, F, E> {
pub(crate) fn new(inner: S, f: F) -> Self {
Self {
inner,
f,
poll_ready_error: None,
}
}
}
impl<S, F, E> fmt::Debug for HandleError<S, F, E>
where
S: fmt::Debug,
E: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HandleError")
.field("inner", &self.inner)
.field("f", &format_args!("{}", std::any::type_name::<F>()))
.field("poll_ready_error", &self.poll_ready_error)
.finish()
}
}
impl<S, F, E> Clone for HandleError<S, F, E>
where
S: Clone,
F: Clone,
{
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
f: self.f.clone(),
poll_ready_error: None,
}
}
}
2021-06-01 17:17:10 +02:00
impl<S, F, B, Res> Service<Request<Body>> for HandleError<S, F, S::Error>
where
S: Service<Request<Body>, Response = Response<B>>,
2021-06-01 17:17:10 +02:00
F: FnOnce(S::Error) -> Res + Clone,
Res: IntoResponse<Body>,
B: http_body::Body<Data = Bytes> + Send + Sync + 'static,
B::Error: Into<BoxError> + Send + Sync + 'static,
{
type Response = Response<BoxBody>;
type Error = Infallible;
type Future = HandleErrorFuture<S::Future, F, S::Error>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
match ready!(self.inner.poll_ready(cx)) {
Ok(_) => Poll::Ready(Ok(())),
Err(err) => {
self.poll_ready_error = Some(err);
Poll::Ready(Ok(()))
}
}
}
fn call(&mut self, req: Request<Body>) -> Self::Future {
if let Some(err) = self.poll_ready_error.take() {
return HandleErrorFuture {
f: Some(self.f.clone()),
kind: Kind::Error(Some(err)),
};
}
HandleErrorFuture {
f: Some(self.f.clone()),
kind: Kind::Future(self.inner.call(req)),
}
}
}
#[pin_project]
pub struct HandleErrorFuture<Fut, F, E> {
#[pin]
kind: Kind<Fut, E>,
f: Option<F>,
}
#[pin_project(project = KindProj)]
enum Kind<Fut, E> {
Future(#[pin] Fut),
Error(Option<E>),
}
2021-06-01 17:17:10 +02:00
impl<Fut, F, E, B, Res> Future for HandleErrorFuture<Fut, F, E>
where
Fut: Future<Output = Result<Response<B>, E>>,
2021-06-01 17:17:10 +02:00
F: FnOnce(E) -> Res,
Res: IntoResponse<Body>,
B: http_body::Body<Data = Bytes> + Send + Sync + 'static,
B::Error: Into<BoxError> + Send + Sync + 'static,
{
type Output = Result<Response<BoxBody>, Infallible>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
match this.kind.project() {
KindProj::Future(future) => match ready!(future.poll(cx)) {
Ok(res) => Ok(res.map(BoxBody::new)).into(),
Err(err) => {
let f = this.f.take().unwrap();
2021-06-01 17:17:10 +02:00
let res = f(err).into_response();
Ok(res.map(BoxBody::new)).into()
}
},
KindProj::Error(err) => {
let f = this.f.take().unwrap();
2021-06-01 17:17:10 +02:00
let res = f(err.take().unwrap()).into_response();
Ok(res.map(BoxBody::new)).into()
}
}
}
}