remove body reexports from dev

This commit is contained in:
Rob Ede 2021-12-04 04:05:37 +00:00
parent d1552235da
commit eb9a6125fb
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933
13 changed files with 69 additions and 24 deletions

View File

@ -13,6 +13,7 @@
### Fixed ### Fixed
* Accept wildcard `*` items in `AcceptLanguage`. [#2480] * Accept wildcard `*` items in `AcceptLanguage`. [#2480]
* Re-exports `dev::{BodySize, MessageBody, SizedStream}`. They are exposed through the `body` module. [#2468]
* Typed headers containing lists that require one or more items now enforce this minimum. [#2482] * Typed headers containing lists that require one or more items now enforce this minimum. [#2482]
[#2468]: https://github.com/actix/actix-web/pull/2468 [#2468]: https://github.com/actix/actix-web/pull/2468

View File

@ -46,8 +46,8 @@ pub trait Head: Default + 'static {
#[derive(Debug)] #[derive(Debug)]
pub struct RequestHead { pub struct RequestHead {
pub uri: Uri,
pub method: Method, pub method: Method,
pub uri: Uri,
pub version: Version, pub version: Version,
pub headers: HeaderMap, pub headers: HeaderMap,
pub extensions: RefCell<Extensions>, pub extensions: RefCell<Extensions>,
@ -58,13 +58,13 @@ pub struct RequestHead {
impl Default for RequestHead { impl Default for RequestHead {
fn default() -> RequestHead { fn default() -> RequestHead {
RequestHead { RequestHead {
uri: Uri::default(),
method: Method::default(), method: Method::default(),
uri: Uri::default(),
version: Version::HTTP_11, version: Version::HTTP_11,
headers: HeaderMap::with_capacity(16), headers: HeaderMap::with_capacity(16),
flags: Flags::empty(),
peer_addr: None,
extensions: RefCell::new(Extensions::new()), extensions: RefCell::new(Extensions::new()),
peer_addr: None,
flags: Flags::empty(),
} }
} }
} }
@ -192,6 +192,7 @@ impl RequestHead {
} }
#[derive(Debug)] #[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub enum RequestHeadType { pub enum RequestHeadType {
Owned(RequestHead), Owned(RequestHead),
Rc(Rc<RequestHead>, Option<HeaderMap>), Rc(Rc<RequestHead>, Option<HeaderMap>),

View File

@ -41,7 +41,8 @@ use actix_http::{
}; };
use actix_service::{map_config, IntoServiceFactory, ServiceFactory, ServiceFactoryExt as _}; use actix_service::{map_config, IntoServiceFactory, ServiceFactory, ServiceFactoryExt as _};
use actix_web::{ use actix_web::{
dev::{AppConfig, MessageBody, Server, ServerHandle, Service}, body::MessageBody,
dev::{AppConfig, Server, ServerHandle, Service},
rt::{self, System}, rt::{self, System},
web, Error, web, Error,
}; };

View File

@ -14,9 +14,6 @@ pub use crate::types::form::UrlEncoded;
pub use crate::types::json::JsonBody; pub use crate::types::json::JsonBody;
pub use crate::types::readlines::Readlines; pub use crate::types::readlines::Readlines;
#[allow(deprecated)]
pub use actix_http::body::{BodySize, MessageBody, SizedStream};
pub use actix_http::{Extensions, Payload, PayloadStream, RequestHead, Response, ResponseHead}; pub use actix_http::{Extensions, Payload, PayloadStream, RequestHead, Response, ResponseHead};
pub use actix_router::{Path, ResourceDef, ResourcePath, Url}; pub use actix_router::{Path, ResourceDef, ResourcePath, Url};
pub use actix_server::{Server, ServerHandle}; pub use actix_server::{Server, ServerHandle};
@ -105,3 +102,40 @@ impl<B> BodyEncoding for crate::HttpResponse<B> {
self self
} }
} }
// pin_project_lite::pin_project! {
#[derive(Debug)]
pub enum AnyBody {
None,
Full { body: crate::web::Bytes },
Boxed { body: actix_http::body::BoxBody },
}
// }
impl crate::body::MessageBody for AnyBody {
type Error = crate::BoxError;
/// Body size hint.
fn size(&self) -> crate::body::BodySize {
match self {
AnyBody::None => crate::body::BodySize::None,
AnyBody::Full { body } => body.size(),
AnyBody::Boxed { body } => body.size(),
}
}
/// Attempt to pull out the next chunk of body bytes.
fn poll_next(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Result<crate::web::Bytes, Self::Error>>> {
match self.get_mut() {
AnyBody::None => std::task::Poll::Ready(None),
AnyBody::Full { body } => {
let bytes = std::mem::take(body);
std::task::Poll::Ready(Some(Ok(bytes)))
}
AnyBody::Boxed { body } => body.as_pin_mut().poll_next(cx),
}
}
}

View File

@ -9,11 +9,13 @@ use crate::{
}; };
/// A request handler is an async function that accepts zero or more parameters that can be /// A request handler is an async function that accepts zero or more parameters that can be
/// extracted from a request (i.e., [`impl FromRequest`](crate::FromRequest)) and returns a type /// extracted from a request (i.e., [`impl FromRequest`]) and returns a type that can be converted
/// that can be converted into an [`HttpResponse`] (that is, it impls the [`Responder`] trait). /// into an [`HttpResponse`] (that is, it impls the [`Responder`] trait).
/// ///
/// If you got the error `the trait Handler<_, _, _> is not implemented`, then your function is not /// If you got the error `the trait Handler<_, _, _> is not implemented`, then your function is not
/// a valid handler. See [Request Handlers](https://actix.rs/docs/handlers/) for more information. /// a valid handler. See <https://actix.rs/docs/handlers> for more information.
///
/// [`impl FromRequest`]: crate::FromRequest
pub trait Handler<T, R>: Clone + 'static pub trait Handler<T, R>: Clone + 'static
where where
R: Future, R: Future,
@ -22,7 +24,7 @@ where
fn call(&self, param: T) -> R; fn call(&self, param: T) -> R;
} }
pub fn handler_service<F, T, R>(handler: F) -> BoxedHttpServiceFactory pub(crate) fn handler_service<F, T, R>(handler: F) -> BoxedHttpServiceFactory
where where
F: Handler<T, R>, F: Handler<T, R>,
T: FromRequest, T: FromRequest,
@ -36,8 +38,9 @@ where
async move { async move {
let (req, mut payload) = req.into_parts(); let (req, mut payload) = req.into_parts();
let res = match T::from_request(&req, &mut payload).await { let res = match T::from_request(&req, &mut payload).await {
Err(err) => HttpResponse::from_error(err).map_into_boxed_body(), Err(err) => HttpResponse::from_error(err),
Ok(data) => handler Ok(data) => handler
.call(data) .call(data)
@ -51,7 +54,14 @@ where
})) }))
} }
/// FromRequest trait impl for tuples /// Generates a [`Handler`] trait impl for N-ary functions where N is specified with a sequence of
/// space separated type parameters.
///
/// # Examples
/// ```ignore
/// factory_tuple! {} // implements Handler for types: fn() -> Res
/// factory_tuple! { A B C } // implements Handler for types: fn(A, B, C) -> Res
/// ```
macro_rules! factory_tuple ({ $($param:ident)* } => { macro_rules! factory_tuple ({ $($param:ident)* } => {
impl<Func, $($param,)* Res> Handler<($($param,)*), Res> for Func impl<Func, $($param,)* Res> Handler<($($param,)*), Res> for Func
where Func: Fn($($param),*) -> Res + Clone + 'static, where Func: Fn($($param),*) -> Res + Clone + 'static,

View File

@ -208,7 +208,7 @@ impl Accept {
/// If no q-factors are provided, the first mime type is chosen. Note that items without /// If no q-factors are provided, the first mime type is chosen. Note that items without
/// q-factors are given the maximum preference value. /// q-factors are given the maximum preference value.
/// ///
/// As per the spec, will return [`Mime::STAR_STAR`] (indicating no preference) if the contained /// As per the spec, will return [`mime::STAR_STAR`] (indicating no preference) if the contained
/// list is empty. /// list is empty.
/// ///
/// [q-factor weighting]: https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.2 /// [q-factor weighting]: https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.2

View File

@ -22,7 +22,7 @@ use regex::{Regex, RegexSet};
use time::{format_description::well_known::Rfc3339, OffsetDateTime}; use time::{format_description::well_known::Rfc3339, OffsetDateTime};
use crate::{ use crate::{
dev::{BodySize, MessageBody}, body::{BodySize, MessageBody},
http::HeaderName, http::HeaderName,
service::{ServiceRequest, ServiceResponse}, service::{ServiceRequest, ServiceResponse},
Error, HttpResponse, Result, Error, HttpResponse, Result,

View File

@ -1,7 +1,6 @@
use std::{ use std::{
cell::{Ref, RefMut}, cell::{Ref, RefMut},
convert::TryInto, convert::TryInto,
error::Error as StdError,
future::Future, future::Future,
pin::Pin, pin::Pin,
task::{Context, Poll}, task::{Context, Poll},

View File

@ -241,6 +241,7 @@ impl<B> HttpResponse<B> {
where where
B: MessageBody + 'static, B: MessageBody + 'static,
{ {
// TODO: avoid double boxing with down-casting, if it improves perf
self.map_body(|_, body| BoxBody::new(body)) self.map_body(|_, body| BoxBody::new(body))
} }

View File

@ -1,5 +1,3 @@
#![allow(clippy::rc_buffer)] // inner value is mutated before being shared (`Rc::get_mut`)
use std::{future::Future, mem, rc::Rc}; use std::{future::Future, mem, rc::Rc};
use actix_http::http::Method; use actix_http::http::Method;

View File

@ -90,7 +90,7 @@ impl<T: fmt::Display> fmt::Display for Path<T> {
} }
} }
/// See [here](#usage) for example of usage as an extractor. /// See [here](#Examples) for example of usage as an extractor.
impl<T> FromRequest for Path<T> impl<T> FromRequest for Path<T>
where where
T: de::DeserializeOwned, T: de::DeserializeOwned,

View File

@ -43,12 +43,12 @@ use crate::{
/// Ok(format!("Request Body Bytes:\n{:?}", bytes)) /// Ok(format!("Request Body Bytes:\n{:?}", bytes))
/// } /// }
/// ``` /// ```
pub struct Payload(crate::dev::Payload); pub struct Payload(dev::Payload);
impl Payload { impl Payload {
/// Unwrap to inner Payload type. /// Unwrap to inner Payload type.
#[inline] #[inline]
pub fn into_inner(self) -> crate::dev::Payload { pub fn into_inner(self) -> dev::Payload {
self.0 self.0
} }
} }
@ -62,7 +62,7 @@ impl Stream for Payload {
} }
} }
/// See [here](#usage) for example of usage as an extractor. /// See [here](#Examples) for example of usage as an extractor.
impl FromRequest for Payload { impl FromRequest for Payload {
type Error = Error; type Error = Error;
type Future = Ready<Result<Payload, Error>>; type Future = Ready<Result<Payload, Error>>;

View File

@ -105,7 +105,7 @@ impl<T: fmt::Display> fmt::Display for Query<T> {
} }
} }
/// See [here](#usage) for example of usage as an extractor. /// See [here](#Examples) for example of usage as an extractor.
impl<T: DeserializeOwned> FromRequest for Query<T> { impl<T: DeserializeOwned> FromRequest for Query<T> {
type Error = Error; type Error = Error;
type Future = Ready<Result<Self, Error>>; type Future = Ready<Result<Self, Error>>;