Remove RequestParts::take_extensions (#699)

* 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 <[email protected]>

* Remove macro only used once

Co-authored-by: Jonas Platte <[email protected]>
This commit is contained in:
David Pedersen
2022-01-23 18:01:52 +01:00
co-authored by Jonas Platte
parent 184ea656c0
commit b1ef0be1a7
14 changed files with 98 additions and 228 deletions
+14
View File
@@ -21,8 +21,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `RequestAlreadyExtracted` - `RequestAlreadyExtracted`
- `RequestPartsAlreadyExtracted` - `RequestPartsAlreadyExtracted`
- `<HeaderMap as FromRequest<_>>::Error` has been changed to `std::convert::Infallible`. - `<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 [#698]: https://github.com/tokio-rs/axum/pull/698
[#699]: https://github.com/tokio-rs/axum/pull/699
# 0.1.1 (06. December, 2021) # 0.1.1 (06. December, 2021)
+12 -35
View File
@@ -78,7 +78,7 @@ pub struct RequestParts<B> {
uri: Uri, uri: Uri,
version: Version, version: Version,
headers: HeaderMap, headers: HeaderMap,
extensions: Option<Extensions>, extensions: Extensions,
body: Option<B>, body: Option<B>,
} }
@@ -108,52 +108,38 @@ impl<B> RequestParts<B> {
uri, uri,
version, version,
headers, headers,
extensions: Some(extensions), extensions,
body: Some(body), body: Some(body),
} }
} }
/// Convert this `RequestParts` back into a [`Request`]. /// 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 /// [`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 { let Self {
method, method,
uri, uri,
version, version,
headers, headers,
mut extensions, extensions,
mut body, mut body,
} = self; } = self;
let mut req = if let Some(body) = body.take() { let mut req = if let Some(body) = body.take() {
Request::new(body) Request::new(body)
} else { } else {
return Err(RequestAlreadyExtracted::BodyAlreadyExtracted( return Err(BodyAlreadyExtracted);
BodyAlreadyExtracted,
));
}; };
*req.method_mut() = method; *req.method_mut() = method;
*req.uri_mut() = uri; *req.uri_mut() = uri;
*req.version_mut() = version; *req.version_mut() = version;
*req.headers_mut() = headers; *req.headers_mut() = headers;
*req.extensions_mut() = extensions;
if let Some(extensions) = extensions.take() {
*req.extensions_mut() = extensions;
} else {
return Err(RequestAlreadyExtracted::ExtensionsAlreadyExtracted(
ExtensionsAlreadyExtracted,
));
}
Ok(req) Ok(req)
} }
@@ -199,22 +185,13 @@ impl<B> RequestParts<B> {
} }
/// Gets a reference to the request extensions. /// Gets a reference to the request extensions.
/// pub fn extensions(&self) -> &Extensions {
/// Returns `None` if the extensions has been taken by another extractor. &self.extensions
pub fn extensions(&self) -> Option<&Extensions> {
self.extensions.as_ref()
} }
/// Gets a mutable reference to the request extensions. /// Gets a mutable reference to the request extensions.
/// pub fn extensions_mut(&mut self) -> &mut Extensions {
/// Returns `None` if the extensions has been taken by another extractor. &mut self.extensions
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()
} }
/// Gets a reference to the request body. /// Gets a reference to the request body.
+27 -33
View File
@@ -1,21 +1,36 @@
//! Rejection response types. //! Rejection response types.
define_rejection! { use crate::body;
#[status = INTERNAL_SERVER_ERROR] use http::{Response, StatusCode};
#[body = "Cannot have two request body extractors for a single handler"] use http_body::Full;
/// Rejection type used if you try and extract the request body more than use std::fmt;
/// once.
pub struct BodyAlreadyExtracted; /// 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! { impl crate::response::IntoResponse for BodyAlreadyExtracted {
#[status = INTERNAL_SERVER_ERROR] fn into_response(self) -> crate::response::Response {
#[body = "Extensions taken by other extractor"] let mut res = Response::new(body::boxed(Full::from(Self::BODY)));
/// Rejection used if the request extension has been taken by another *res.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
/// extractor. res
pub struct ExtensionsAlreadyExtracted; }
} }
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! { define_rejection! {
#[status = BAD_REQUEST] #[status = BAD_REQUEST]
#[body = "Failed to buffer the request body"] #[body = "Failed to buffer the request body"]
@@ -32,18 +47,6 @@ define_rejection! {
pub struct InvalidUtf8(Error); 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! { composite_rejection! {
/// Rejection used for [`Bytes`](bytes::Bytes). /// Rejection used for [`Bytes`](bytes::Bytes).
/// ///
@@ -65,12 +68,3 @@ composite_rejection! {
InvalidUtf8, 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,
}
}
+5 -20
View File
@@ -10,7 +10,7 @@ impl<B> FromRequest<B> for Request<B>
where where
B: Send, B: Send,
{ {
type Rejection = RequestAlreadyExtracted; type Rejection = BodyAlreadyExtracted;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let req = std::mem::replace( let req = std::mem::replace(
@@ -20,7 +20,7 @@ where
version: req.version, version: req.version,
uri: req.uri.clone(), uri: req.uri.clone(),
headers: HeaderMap::new(), headers: HeaderMap::new(),
extensions: None, extensions: Extensions::default(),
body: None, body: None,
}, },
); );
@@ -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] #[async_trait]
impl<B> FromRequest<B> for Bytes impl<B> FromRequest<B> for Bytes
where where
@@ -142,17 +130,14 @@ impl<B> FromRequest<B> for http::request::Parts
where where
B: Send, B: Send,
{ {
type Rejection = RequestPartsAlreadyExtracted; type Rejection = Infallible;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let method = unwrap_infallible(Method::from_request(req).await); let method = unwrap_infallible(Method::from_request(req).await);
let uri = unwrap_infallible(Uri::from_request(req).await); let uri = unwrap_infallible(Uri::from_request(req).await);
let version = unwrap_infallible(Version::from_request(req).await); let version = unwrap_infallible(Version::from_request(req).await);
let headers = match HeaderMap::from_request(req).await { let headers = unwrap_infallible(HeaderMap::from_request(req).await);
Ok(headers) => headers, let extensions = std::mem::take(req.extensions_mut());
Err(err) => match err {},
};
let extensions = Extensions::from_request(req).await?;
let mut temp_request = Request::new(()); let mut temp_request = Request::new(());
*temp_request.method_mut() = method; *temp_request.method_mut() = method;
-35
View File
@@ -1,39 +1,4 @@
macro_rules! define_rejection { 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] #[status = $status:ident]
#[body = $body:expr] #[body = $body:expr]
+3
View File
@@ -12,8 +12,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
# 0.1.2 (13. January, 2021) # 0.1.2 (13. January, 2021)
- **fix:** Depend on tower with `default_features = false` ([#666]) - **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 [#666]: https://github.com/tokio-rs/axum/pull/666
[#699]: https://github.com/tokio-rs/axum/pull/699
# 0.1.1 (27. December, 2021) # 0.1.1 (27. December, 2021)
+5 -71
View File
@@ -1,15 +1,8 @@
use axum::{ use axum::{
async_trait, async_trait,
extract::{ extract::{Extension, FromRequest, RequestParts},
rejection::{ExtensionRejection, ExtensionsAlreadyExtracted},
Extension, FromRequest, RequestParts,
},
response::{IntoResponse, Response},
};
use std::{
fmt,
ops::{Deref, DerefMut},
}; };
use std::ops::{Deref, DerefMut};
/// Cache results of other extractors. /// Cache results of other extractors.
/// ///
@@ -100,25 +93,14 @@ where
B: Send, B: Send,
T: FromRequest<B> + Clone + Send + Sync + 'static, T: FromRequest<B> + Clone + Send + Sync + 'static,
{ {
type Rejection = CachedRejection<T::Rejection>; type Rejection = T::Rejection;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
match Extension::<CachedEntry<T>>::from_request(req).await { match Extension::<CachedEntry<T>>::from_request(req).await {
Ok(Extension(CachedEntry(value))) => Ok(Self(value)), Ok(Extension(CachedEntry(value))) => Ok(Self(value)),
Err(ExtensionRejection::ExtensionsAlreadyExtracted(err)) => {
Err(CachedRejection::ExtensionsAlreadyExtracted(err))
}
Err(_) => { Err(_) => {
let value = T::from_request(req).await.map_err(CachedRejection::Inner)?; let value = T::from_request(req).await?;
req.extensions_mut().insert(CachedEntry(value.clone()));
req.extensions_mut()
.ok_or_else(|| {
CachedRejection::ExtensionsAlreadyExtracted(
ExtensionsAlreadyExtracted::default(),
)
})?
.insert(CachedEntry(value.clone()));
Ok(Self(value)) Ok(Self(value))
} }
} }
@@ -139,54 +121,6 @@ impl<T> DerefMut for Cached<T> {
} }
} }
/// Rejection used for [`Cached`].
///
/// Contains one variant for each way the [`Cached`] extractor can fail.
#[derive(Debug)]
#[non_exhaustive]
pub enum CachedRejection<R> {
#[allow(missing_docs)]
ExtensionsAlreadyExtracted(ExtensionsAlreadyExtracted),
#[allow(missing_docs)]
Inner(R),
}
impl<R> IntoResponse for CachedRejection<R>
where
R: IntoResponse,
{
fn into_response(self) -> Response {
match self {
Self::ExtensionsAlreadyExtracted(inner) => inner.into_response(),
Self::Inner(inner) => inner.into_response(),
}
}
}
impl<R> fmt::Display for CachedRejection<R>
where
R: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ExtensionsAlreadyExtracted(inner) => write!(f, "{}", inner),
Self::Inner(inner) => write!(f, "{}", inner),
}
}
}
impl<R> std::error::Error for CachedRejection<R>
where
R: std::error::Error + 'static,
{
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::ExtensionsAlreadyExtracted(inner) => Some(inner),
Self::Inner(inner) => Some(inner),
}
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
-6
View File
@@ -3,9 +3,3 @@
mod cached; mod cached;
pub use self::cached::Cached; pub use self::cached::Cached;
pub mod rejection {
//! Rejection response types.
pub use super::cached::CachedRejection;
}
+19
View File
@@ -31,10 +31,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `ContentLengthLimitRejection` - `ContentLengthLimitRejection`
- `WebSocketUpgradeRejection` - `WebSocketUpgradeRejection`
- `<HeaderMap as FromRequest<_>>::Error` has been changed to `std::convert::Infallible`. - `<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.
- The `ExtensionsAlreadyExtracted` removed variant has been removed from these rejections:
- `ExtensionRejection`
- `PathRejection`
- `MatchedPathRejection`
- `WebSocketUpgradeRejection`
[#644]: https://github.com/tokio-rs/axum/pull/644 [#644]: https://github.com/tokio-rs/axum/pull/644
[#665]: https://github.com/tokio-rs/axum/pull/665 [#665]: https://github.com/tokio-rs/axum/pull/665
[#698]: https://github.com/tokio-rs/axum/pull/698 [#698]: https://github.com/tokio-rs/axum/pull/698
[#699]: https://github.com/tokio-rs/axum/pull/699
# 0.4.4 (13. January, 2021) # 0.4.4 (13. January, 2021)
-1
View File
@@ -53,7 +53,6 @@ where
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let value = req let value = req
.extensions() .extensions()
.ok_or_else(ExtensionsAlreadyExtracted::default)?
.get::<T>() .get::<T>()
.ok_or_else(|| { .ok_or_else(|| {
MissingExtension::from_err(format!( MissingExtension::from_err(format!(
+2 -5
View File
@@ -70,11 +70,8 @@ where
type Rejection = MatchedPathRejection; type Rejection = MatchedPathRejection;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let extensions = req.extensions().ok_or_else(|| { let matched_path = req
MatchedPathRejection::ExtensionsAlreadyExtracted(ExtensionsAlreadyExtracted::default()) .extensions()
})?;
let matched_path = extensions
.get::<Self>() .get::<Self>()
.ok_or(MatchedPathRejection::MatchedPathMissing(MatchedPathMissing))? .ok_or(MatchedPathRejection::MatchedPathMissing(MatchedPathMissing))?
.clone(); .clone();
+5 -7
View File
@@ -3,7 +3,6 @@
mod de; mod de;
use super::rejection::ExtensionsAlreadyExtracted;
use crate::{ use crate::{
body::{boxed, Full}, body::{boxed, Full},
extract::{rejection::*, FromRequest, RequestParts}, extract::{rejection::*, FromRequest, RequestParts},
@@ -164,11 +163,7 @@ where
type Rejection = PathRejection; type Rejection = PathRejection;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let ext = req let params = match req.extensions_mut().get::<Option<UrlParams>>() {
.extensions_mut()
.ok_or_else::<Self::Rejection, _>(|| ExtensionsAlreadyExtracted::default().into())?;
let params = match ext.get::<Option<UrlParams>>() {
Some(Some(UrlParams(Ok(params)))) => Cow::Borrowed(params), Some(Some(UrlParams(Ok(params)))) => Cow::Borrowed(params),
Some(Some(UrlParams(Err(InvalidUtf8InPathParam { key })))) => { Some(Some(UrlParams(Err(InvalidUtf8InPathParam { key })))) => {
let err = PathDeserializationError { let err = PathDeserializationError {
@@ -519,6 +514,9 @@ mod tests {
let res = client.get("/foo").send().await; let res = client.get("/foo").send().await;
assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR); assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(res.text().await, "Extensions taken by other extractor"); assert_eq!(
res.text().await,
"No paths parameters found for matched route. Are you also extracting `Request<_>`?"
);
} }
} }
+4 -6
View File
@@ -52,9 +52,10 @@ define_rejection! {
define_rejection! { define_rejection! {
#[status = INTERNAL_SERVER_ERROR] #[status = INTERNAL_SERVER_ERROR]
#[body = "No paths parameters found for matched route. This is a bug in axum. Please open an issue"] #[body = "No paths parameters found for matched route. Are you also extracting `Request<_>`?"]
/// Rejection type used if axum's internal representation of path parameters is missing. This /// Rejection type used if axum's internal representation of path parameters
/// should never happen and is a bug in axum if it does. /// is missing. This is commonly caused by extracting `Request<_>`. `Path`
/// must be extracted first.
pub struct MissingPathParams; pub struct MissingPathParams;
} }
@@ -148,7 +149,6 @@ composite_rejection! {
/// can fail. /// can fail.
pub enum ExtensionRejection { pub enum ExtensionRejection {
MissingExtension, MissingExtension,
ExtensionsAlreadyExtracted,
} }
} }
@@ -160,7 +160,6 @@ composite_rejection! {
pub enum PathRejection { pub enum PathRejection {
FailedToDeserializePathParams, FailedToDeserializePathParams,
MissingPathParams, MissingPathParams,
ExtensionsAlreadyExtracted,
} }
} }
@@ -176,7 +175,6 @@ define_rejection! {
composite_rejection! { composite_rejection! {
/// Rejection used for [`MatchedPath`](super::MatchedPath). /// Rejection used for [`MatchedPath`](super::MatchedPath).
pub enum MatchedPathRejection { pub enum MatchedPathRejection {
ExtensionsAlreadyExtracted,
MatchedPathMissing, MatchedPathMissing,
} }
} }
+2 -9
View File
@@ -64,7 +64,7 @@
//! [`StreamExt::split`]: https://docs.rs/futures/0.3.17/futures/stream/trait.StreamExt.html#method.split //! [`StreamExt::split`]: https://docs.rs/futures/0.3.17/futures/stream/trait.StreamExt.html#method.split
use self::rejection::*; use self::rejection::*;
use super::{rejection::*, FromRequest, RequestParts}; use super::{FromRequest, RequestParts};
use crate::{ use crate::{
body::{self, Bytes}, body::{self, Bytes},
response::Response, response::Response,
@@ -268,11 +268,7 @@ where
return Err(WebSocketKeyHeaderMissing.into()); return Err(WebSocketKeyHeaderMissing.into());
}; };
let on_upgrade = req let on_upgrade = req.extensions_mut().remove::<OnUpgrade>().unwrap();
.extensions_mut()
.ok_or_else(ExtensionsAlreadyExtracted::default)?
.remove::<OnUpgrade>()
.unwrap();
let sec_websocket_protocol = req.headers().get(header::SEC_WEBSOCKET_PROTOCOL).cloned(); let sec_websocket_protocol = req.headers().get(header::SEC_WEBSOCKET_PROTOCOL).cloned();
@@ -514,8 +510,6 @@ fn sign(key: &[u8]) -> HeaderValue {
pub mod rejection { pub mod rejection {
//! WebSocket specific rejections. //! WebSocket specific rejections.
use crate::extract::rejection::*;
define_rejection! { define_rejection! {
#[status = METHOD_NOT_ALLOWED] #[status = METHOD_NOT_ALLOWED]
#[body = "Request method must be `GET`"] #[body = "Request method must be `GET`"]
@@ -562,7 +556,6 @@ pub mod rejection {
InvalidUpgradeHeader, InvalidUpgradeHeader,
InvalidWebSocketVersionHeader, InvalidWebSocketVersionHeader,
WebSocketKeyHeaderMissing, WebSocketKeyHeaderMissing,
ExtensionsAlreadyExtracted,
} }
} }
} }