Skip to content

Commit

Permalink
Remove RequestParts::take_extensions (#699)
Browse files Browse the repository at this point in the history
* Remove `RequestParts::take_extensions`

* fix out of date docs

* Remove RequestAlreadyExtracted and replace it with BodyAlreadyExtracted

* fix docs

* fix test

* Update axum-core/src/extract/mod.rs

Co-authored-by: Jonas Platte <jplatte@users.noreply.github.com>

* Remove macro only used once

Co-authored-by: Jonas Platte <jplatte@users.noreply.github.com>
  • Loading branch information
davidpdrsn and jplatte committed Jan 23, 2022
1 parent 184ea65 commit b1ef0be
Show file tree
Hide file tree
Showing 14 changed files with 98 additions and 228 deletions.
14 changes: 14 additions & 0 deletions axum-core/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `RequestAlreadyExtracted`
- `RequestPartsAlreadyExtracted`
- `<HeaderMap as FromRequest<_>>::Error` has been changed to `std::convert::Infallible`.
- **breaking:** `axum::http::Extensions` is no longer an extractor (ie it
doesn't implement `FromRequest`). The `axum::extract::Extension` extractor is
_not_ impacted by this and works the same. This change makes it harder to
accidentally remove all extensions which would result in confusing errors
elsewhere ([#699])
This includes these breaking changes:
- `RequestParts::take_extensions` has been removed.
- `RequestParts::extensions` returns `&Extensions`.
- `RequestParts::extensions_mut` returns `&mut Extensions`.
- `RequestAlreadyExtracted` has been removed.
- `<Request as FromRequest>::Error` is now `BodyAlreadyExtracted`.
- `<http::request::Parts as FromRequest>::Error` is now `Infallible`.
- `ExtensionsAlreadyExtracted` has been removed.

[#698]: https://github.com/tokio-rs/axum/pull/698
[#699]: https://github.com/tokio-rs/axum/pull/699

# 0.1.1 (06. December, 2021)

Expand Down
47 changes: 12 additions & 35 deletions axum-core/src/extract/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ pub struct RequestParts<B> {
uri: Uri,
version: Version,
headers: HeaderMap,
extensions: Option<Extensions>,
extensions: Extensions,
body: Option<B>,
}

Expand Down Expand Up @@ -108,52 +108,38 @@ impl<B> RequestParts<B> {
uri,
version,
headers,
extensions: Some(extensions),
extensions,
body: Some(body),
}
}

/// Convert this `RequestParts` back into a [`Request`].
///
/// Fails if
/// Fails if The request body has been extracted, that is [`take_body`] has
/// been called.
///
/// - The full [`Extensions`] has been extracted, that is
/// [`take_extensions`] have been called.
/// - The request body has been extracted, that is [`take_body`] have been
/// called.
///
/// [`take_extensions`]: RequestParts::take_extensions
/// [`take_body`]: RequestParts::take_body
pub fn try_into_request(self) -> Result<Request<B>, RequestAlreadyExtracted> {
pub fn try_into_request(self) -> Result<Request<B>, BodyAlreadyExtracted> {
let Self {
method,
uri,
version,
headers,
mut extensions,
extensions,
mut body,
} = self;

let mut req = if let Some(body) = body.take() {
Request::new(body)
} else {
return Err(RequestAlreadyExtracted::BodyAlreadyExtracted(
BodyAlreadyExtracted,
));
return Err(BodyAlreadyExtracted);
};

*req.method_mut() = method;
*req.uri_mut() = uri;
*req.version_mut() = version;
*req.headers_mut() = headers;

if let Some(extensions) = extensions.take() {
*req.extensions_mut() = extensions;
} else {
return Err(RequestAlreadyExtracted::ExtensionsAlreadyExtracted(
ExtensionsAlreadyExtracted,
));
}
*req.extensions_mut() = extensions;

Ok(req)
}
Expand Down Expand Up @@ -199,22 +185,13 @@ impl<B> RequestParts<B> {
}

/// Gets a reference to the request extensions.
///
/// Returns `None` if the extensions has been taken by another extractor.
pub fn extensions(&self) -> Option<&Extensions> {
self.extensions.as_ref()
pub fn extensions(&self) -> &Extensions {
&self.extensions
}

/// Gets a mutable reference to the request extensions.
///
/// Returns `None` if the extensions has been taken by another extractor.
pub fn extensions_mut(&mut self) -> Option<&mut Extensions> {
self.extensions.as_mut()
}

/// Takes the extensions out of the request, leaving a `None` in its place.
pub fn take_extensions(&mut self) -> Option<Extensions> {
self.extensions.take()
pub fn extensions_mut(&mut self) -> &mut Extensions {
&mut self.extensions
}

/// Gets a reference to the request body.
Expand Down
60 changes: 27 additions & 33 deletions axum-core/src/extract/rejection.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,36 @@
//! Rejection response types.
define_rejection! {
#[status = INTERNAL_SERVER_ERROR]
#[body = "Cannot have two request body extractors for a single handler"]
/// Rejection type used if you try and extract the request body more than
/// once.
pub struct BodyAlreadyExtracted;
use crate::body;
use http::{Response, StatusCode};
use http_body::Full;
use std::fmt;

/// Rejection type used if you try and extract the request body more than
/// once.
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct BodyAlreadyExtracted;

impl BodyAlreadyExtracted {
const BODY: &'static str = "Cannot have two request body extractors for a single handler";
}

define_rejection! {
#[status = INTERNAL_SERVER_ERROR]
#[body = "Extensions taken by other extractor"]
/// Rejection used if the request extension has been taken by another
/// extractor.
pub struct ExtensionsAlreadyExtracted;
impl crate::response::IntoResponse for BodyAlreadyExtracted {
fn into_response(self) -> crate::response::Response {
let mut res = Response::new(body::boxed(Full::from(Self::BODY)));
*res.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
res
}
}

impl fmt::Display for BodyAlreadyExtracted {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", Self::BODY)
}
}

impl std::error::Error for BodyAlreadyExtracted {}

define_rejection! {
#[status = BAD_REQUEST]
#[body = "Failed to buffer the request body"]
Expand All @@ -32,18 +47,6 @@ define_rejection! {
pub struct InvalidUtf8(Error);
}

composite_rejection! {
/// Rejection used for [`Request<_>`].
///
/// Contains one variant for each way the [`Request<_>`] extractor can fail.
///
/// [`Request<_>`]: http::Request
pub enum RequestAlreadyExtracted {
BodyAlreadyExtracted,
ExtensionsAlreadyExtracted,
}
}

composite_rejection! {
/// Rejection used for [`Bytes`](bytes::Bytes).
///
Expand All @@ -65,12 +68,3 @@ composite_rejection! {
InvalidUtf8,
}
}

composite_rejection! {
/// Rejection used for [`http::request::Parts`].
///
/// Contains one variant for each way the [`http::request::Parts`] extractor can fail.
pub enum RequestPartsAlreadyExtracted {
ExtensionsAlreadyExtracted,
}
}
25 changes: 5 additions & 20 deletions axum-core/src/extract/request_parts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ impl<B> FromRequest<B> for Request<B>
where
B: Send,
{
type Rejection = RequestAlreadyExtracted;
type Rejection = BodyAlreadyExtracted;

async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let req = std::mem::replace(
Expand All @@ -20,7 +20,7 @@ where
version: req.version,
uri: req.uri.clone(),
headers: HeaderMap::new(),
extensions: None,
extensions: Extensions::default(),
body: None,
},
);
Expand Down Expand Up @@ -82,18 +82,6 @@ where
}
}

#[async_trait]
impl<B> FromRequest<B> for Extensions
where
B: Send,
{
type Rejection = ExtensionsAlreadyExtracted;

async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
req.take_extensions().ok_or(ExtensionsAlreadyExtracted)
}
}

#[async_trait]
impl<B> FromRequest<B> for Bytes
where
Expand Down Expand Up @@ -142,17 +130,14 @@ impl<B> FromRequest<B> for http::request::Parts
where
B: Send,
{
type Rejection = RequestPartsAlreadyExtracted;
type Rejection = Infallible;

async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let method = unwrap_infallible(Method::from_request(req).await);
let uri = unwrap_infallible(Uri::from_request(req).await);
let version = unwrap_infallible(Version::from_request(req).await);
let headers = match HeaderMap::from_request(req).await {
Ok(headers) => headers,
Err(err) => match err {},
};
let extensions = Extensions::from_request(req).await?;
let headers = unwrap_infallible(HeaderMap::from_request(req).await);
let extensions = std::mem::take(req.extensions_mut());

let mut temp_request = Request::new(());
*temp_request.method_mut() = method;
Expand Down
35 changes: 0 additions & 35 deletions axum-core/src/macros.rs
Original file line number Diff line number Diff line change
@@ -1,39 +1,4 @@
macro_rules! define_rejection {
(
#[status = $status:ident]
#[body = $body:expr]
$(#[$m:meta])*
pub struct $name:ident;
) => {
$(#[$m])*
#[derive(Debug)]
#[non_exhaustive]
pub struct $name;

#[allow(deprecated)]
impl $crate::response::IntoResponse for $name {
fn into_response(self) -> $crate::response::Response {
let mut res = http::Response::new($crate::body::boxed(http_body::Full::from($body)));
*res.status_mut() = http::StatusCode::$status;
res
}
}

impl std::fmt::Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", $body)
}
}

impl std::error::Error for $name {}

impl Default for $name {
fn default() -> Self {
Self
}
}
};

(
#[status = $status:ident]
#[body = $body:expr]
Expand Down
3 changes: 3 additions & 0 deletions axum-extra/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
# 0.1.2 (13. January, 2021)

- **fix:** Depend on tower with `default_features = false` ([#666])
- **breaking:** `CachedRejection` has been removed ([#699])
- **breaking:** `<Cached<T> as FromRequest>::Error` is now `T::Rejection`. ([#699])

[#666]: https://github.com/tokio-rs/axum/pull/666
[#699]: https://github.com/tokio-rs/axum/pull/699

# 0.1.1 (27. December, 2021)

Expand Down
Loading

0 comments on commit b1ef0be

Please sign in to comment.