Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove B type param #1751

Merged
merged 26 commits into from
Mar 12, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
4596c3c
Start working on v0.7.0
davidpdrsn Nov 25, 2022
8685796
Add `axum_core::body::Body` (#1584)
davidpdrsn Nov 27, 2022
97d3258
FromRequest
davidpdrsn Feb 12, 2023
b7f0dcd
Handler
davidpdrsn Feb 12, 2023
3b64f85
Router
davidpdrsn Feb 12, 2023
beeb567
MethodRouter
davidpdrsn Feb 12, 2023
a95da74
Remove `B` type param: axum-core (#1772)
davidpdrsn Feb 20, 2023
dea73f8
Remove `B` type param: axum-extra (#1775)
davidpdrsn Feb 21, 2023
69e8b04
Remove `B` type param: `Router`, `MethodRouter`, `Handler` (#1774)
davidpdrsn Feb 21, 2023
92722fc
Remove `B` type param: rest of axum (#1776)
davidpdrsn Feb 21, 2023
412f388
Start working on v0.7.0
davidpdrsn Nov 25, 2022
d9de5ec
Add `axum_core::body::Body` (#1584)
davidpdrsn Nov 27, 2022
d81effb
Change `sse::Event::json_data` to use `axum_core::Error` as its error…
davidpdrsn Feb 16, 2023
813dbac
Fix typo in extract::ws (#1664)
mscofield0 Feb 24, 2023
b9e0c0c
Remove `B` type param: the rest (#1778)
davidpdrsn Feb 28, 2023
161bb60
Merge branch 'v0.7.0' into remove-generic-b-type-prep
davidpdrsn Mar 1, 2023
d039c35
Add workaround for inference errors after removing `B` type param (#1…
davidpdrsn Mar 12, 2023
02eb3a6
Merge branch 'v0.7.0' into remove-generic-b-type-prep
davidpdrsn Mar 12, 2023
dd0d5e5
Merge remote-tracking branch 'origin/remove-generic-b-type-prep' into…
davidpdrsn Mar 12, 2023
4eb9bf6
try again
davidpdrsn Mar 12, 2023
2de724e
Add `Router::into_service`
davidpdrsn Mar 12, 2023
d8a504c
changelog
davidpdrsn Mar 12, 2023
8496c85
format
davidpdrsn Mar 12, 2023
ee7f6ef
fix ui tests
davidpdrsn Mar 12, 2023
72f90b4
spa.rs committed by accident
davidpdrsn Mar 12, 2023
9b69d39
changelog
davidpdrsn Mar 12, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 92 additions & 2 deletions axum-core/src/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
use crate::{BoxError, Error};
use bytes::Bytes;
use bytes::{Buf, BufMut};
use http_body::Body;
use futures_util::stream::Stream;
use http::HeaderMap;
use http_body::Body as _;
use std::pin::Pin;
use std::task::{Context, Poll};

/// A boxed [`Body`] trait object.
///
Expand Down Expand Up @@ -55,7 +59,7 @@ where
// THE SOFTWARE.
pub(crate) async fn to_bytes<T>(body: T) -> Result<Bytes, T::Error>
where
T: Body,
T: http_body::Body,
{
futures_util::pin_mut!(body);

Expand Down Expand Up @@ -85,6 +89,92 @@ where
Ok(vec.into())
}

/// The body type used in axum requests and responses.
#[derive(Debug)]
pub struct Body(BoxBody);

impl Body {
/// Create a new `Body` that wraps another [`http_body::Body`].
pub fn new<B>(body: B) -> Self
where
B: http_body::Body<Data = Bytes> + Send + 'static,
B::Error: Into<BoxError>,
{
try_downcast(body).unwrap_or_else(|body| Self(boxed(body)))
}

/// Create an empty body.
pub fn empty() -> Self {
Self::new(http_body::Empty::new())
}
}

impl Default for Body {
fn default() -> Self {
Self::empty()
}
}

macro_rules! body_from_impl {
($ty:ty) => {
impl From<$ty> for Body {
fn from(buf: $ty) -> Self {
Self::new(http_body::Full::from(buf))
}
}
};
}

body_from_impl!(&'static [u8]);
body_from_impl!(std::borrow::Cow<'static, [u8]>);
body_from_impl!(Vec<u8>);

body_from_impl!(&'static str);
body_from_impl!(std::borrow::Cow<'static, str>);
body_from_impl!(String);

body_from_impl!(Bytes);

impl http_body::Body for Body {
type Data = Bytes;
type Error = Error;

#[inline]
fn poll_data(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> std::task::Poll<Option<Result<Self::Data, Self::Error>>> {
Pin::new(&mut self.0).poll_data(cx)
}

#[inline]
fn poll_trailers(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> std::task::Poll<Result<Option<HeaderMap>, Self::Error>> {
Pin::new(&mut self.0).poll_trailers(cx)
}

#[inline]
fn size_hint(&self) -> http_body::SizeHint {
self.0.size_hint()
}

#[inline]
fn is_end_stream(&self) -> bool {
self.0.is_end_stream()
}
}

impl Stream for Body {
type Item = Result<Bytes, Error>;

#[inline]
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.poll_data(cx)
}
}

#[test]
fn test_try_downcast() {
assert_eq!(try_downcast::<i32, _>(5_u32), Err(5_u32));
Expand Down
4 changes: 2 additions & 2 deletions axum-core/src/extract/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,13 +114,13 @@ pub trait FromRequestParts<S>: Sized {
note = "Function argument is not a valid axum extractor. \nSee `https://docs.rs/axum/latest/axum/extract/index.html` for details",
)
)]
pub trait FromRequest<S, B, M = private::ViaRequest>: Sized {
pub trait FromRequest<S, M = private::ViaRequest>: Sized {
/// If the extractor fails it'll use this "rejection" type. A rejection is
/// a kind of error that can be converted into a response.
type Rejection: IntoResponse;

/// Perform the extraction.
async fn from_request(req: Request<B>, state: &S) -> Result<Self, Self::Rejection>;
async fn from_request(req: Request<Body>, state: &S) -> Result<Self, Self::Rejection>;
}

#[async_trait]
Expand Down
24 changes: 11 additions & 13 deletions axum/src/handler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,12 +99,12 @@ pub use self::service::HandlerService;
note = "Consider using `#[axum::debug_handler]` to improve the error message"
)
)]
pub trait Handler<T, S, B = Body>: Clone + Send + Sized + 'static {
pub trait Handler<T, S>: Clone + Send + Sized + 'static {
/// The type of future calling this handler returns.
type Future: Future<Output = Response> + Send + 'static;

/// Call the handler with the given request.
fn call(self, req: Request<B>, state: S) -> Self::Future;
fn call(self, req: Request<Body>, state: S) -> Self::Future;

/// Apply a [`tower::Layer`] to the handler.
///
Expand Down Expand Up @@ -142,10 +142,10 @@ pub trait Handler<T, S, B = Body>: Clone + Send + Sized + 'static {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
fn layer<L, NewReqBody>(self, layer: L) -> Layered<L, Self, T, S, B, NewReqBody>
fn layer<L>(self, layer: L) -> Layered<L, Self, T, S>
where
L: Layer<HandlerService<Self, T, S, B>> + Clone,
L::Service: Service<Request<NewReqBody>>,
L: Layer<HandlerService<Self, T, S>> + Clone,
L::Service: Service<Request<Body>>,
{
Layered {
layer,
Expand All @@ -155,21 +155,20 @@ pub trait Handler<T, S, B = Body>: Clone + Send + Sized + 'static {
}

/// Convert the handler into a [`Service`] by providing the state
fn with_state(self, state: S) -> HandlerService<Self, T, S, B> {
fn with_state(self, state: S) -> HandlerService<Self, T, S> {
HandlerService::new(self, state)
}
}

impl<F, Fut, Res, S, B> Handler<((),), S, B> for F
impl<F, Fut, Res, S> Handler<((),), S> for F
where
F: FnOnce() -> Fut + Clone + Send + 'static,
Fut: Future<Output = Res> + Send,
Res: IntoResponse,
B: Send + 'static,
{
type Future = Pin<Box<dyn Future<Output = Response> + Send>>;

fn call(self, _req: Request<B>, _state: S) -> Self::Future {
fn call(self, _req: Request<Body>, _state: S) -> Self::Future {
Box::pin(async move { self().await.into_response() })
}
}
Expand All @@ -179,19 +178,18 @@ macro_rules! impl_handler {
[$($ty:ident),*], $last:ident
) => {
#[allow(non_snake_case, unused_mut)]
impl<F, Fut, S, B, Res, M, $($ty,)* $last> Handler<(M, $($ty,)* $last,), S, B> for F
impl<F, Fut, S, Res, M, $($ty,)* $last> Handler<(M, $($ty,)* $last,), S> for F
where
F: FnOnce($($ty,)* $last,) -> Fut + Clone + Send + 'static,
Fut: Future<Output = Res> + Send,
B: Send + 'static,
S: Send + Sync + 'static,
Res: IntoResponse,
$( $ty: FromRequestParts<S> + Send, )*
$last: FromRequest<S, B, M> + Send,
$last: FromRequest<S, M> + Send,
{
type Future = Pin<Box<dyn Future<Output = Response> + Send>>;

fn call(self, req: Request<B>, state: S) -> Self::Future {
fn call(self, req: Request<Body>, state: S) -> Self::Future {
Box::pin(async move {
let (mut parts, body) = req.into_parts();
let state = &state;
Expand Down
27 changes: 14 additions & 13 deletions axum/src/routing/method_routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -513,16 +513,16 @@ where
/// S: Service<Request<Body>>,
/// {}
/// ```
pub struct MethodRouter<S = (), B = Body, E = Infallible> {
get: MethodEndpoint<S, B, E>,
head: MethodEndpoint<S, B, E>,
delete: MethodEndpoint<S, B, E>,
options: MethodEndpoint<S, B, E>,
patch: MethodEndpoint<S, B, E>,
post: MethodEndpoint<S, B, E>,
put: MethodEndpoint<S, B, E>,
trace: MethodEndpoint<S, B, E>,
fallback: Fallback<S, B, E>,
pub struct MethodRouter<S = (), E = Infallible> {
get: MethodEndpoint<S, E>,
head: MethodEndpoint<S, E>,
delete: MethodEndpoint<S, E>,
options: MethodEndpoint<S, E>,
patch: MethodEndpoint<S, E>,
post: MethodEndpoint<S, E>,
put: MethodEndpoint<S, E>,
trace: MethodEndpoint<S, E>,
fallback: Fallback<S, E>,
allow_header: AllowHeader,
}

Expand Down Expand Up @@ -1248,13 +1248,14 @@ impl<S, B, E> fmt::Debug for MethodEndpoint<S, B, E> {
}
}

impl<B, E> Service<Request<B>> for MethodRouter<(), B, E>
impl<B, E> Service<Request<B>> for MethodRouter<(), E>
where
B: HttpBody + Send + 'static,
B: HttpBody<Data = Bytes> + Send + 'static,
B::Error: Into<BoxError>,
{
type Response = Response;
type Error = E;
type Future = RouteFuture<B, E>;
type Future = RouteFuture<E>;

#[inline]
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Expand Down
14 changes: 8 additions & 6 deletions axum/src/routing/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,10 @@ impl RouteId {
}

/// The router type for composing handlers and services.
pub struct Router<S = (), B = Body> {
routes: HashMap<RouteId, Endpoint<S, B>>,
pub struct Router<S = ()> {
routes: HashMap<RouteId, Endpoint<S>>,
node: Arc<Node>,
fallback: Fallback<S, B>,
fallback: Fallback<S>,
}

impl<S, B> Clone for Router<S, B> {
Expand Down Expand Up @@ -550,13 +550,14 @@ where
}
}

impl<B> Service<Request<B>> for Router<(), B>
impl<B> Service<Request<B>> for Router<()>
where
B: HttpBody + Send + 'static,
B: HttpBody<Data = bytes::Bytes> + Send + 'static,
B::Error: Into<axum_core::BoxError>,
{
type Response = Response;
type Error = Infallible;
type Future = RouteFuture<B, Infallible>;
type Future = RouteFuture<Infallible>;

#[inline]
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Expand All @@ -565,6 +566,7 @@ where

#[inline]
fn call(&mut self, req: Request<B>) -> Self::Future {
let req = req.map(Body::new);
self.call_with_state(req, ())
}
}
Expand Down