Skip to content

Commit

Permalink
switch encoder/compress to use AnyBody
Browse files Browse the repository at this point in the history
  • Loading branch information
robjtede committed Nov 16, 2021
1 parent 5167bf1 commit 0b13d27
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 46 deletions.
5 changes: 4 additions & 1 deletion CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# Changes

## Unreleased - 2021-xx-xx
### Changed
* Compress middleware's response type is now `AnyBody<Encoder<B>>`. [#2448]

### Fixed
* Relax `Unpin` bound on `S` (stream) parameter of `HttpResponseBuilder::streaming`. [#????]
* Relax `Unpin` bound on `S` (stream) parameter of `HttpResponseBuilder::streaming`. [#2448]

[#2423]: https://github.com/actix/actix-web/pull/2423

Expand Down
14 changes: 8 additions & 6 deletions actix-http/CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,21 @@
## Unreleased - 2021-xx-xx
### Added
* `AnyBody::empty` for quickly creating an empty body. [#2446]
* `impl Clone` for `AnyBody<S> where S: Clone`. [#????]
* `AnyBody::into_boxed` for quickly converting to a type-erased, boxed body type. [#????]
* `impl Clone` for `AnyBody<S> where S: Clone`. [#2448]
* `AnyBody::into_boxed` for quickly converting to a type-erased, boxed body type. [#2448]

### Changed
* Rename `AnyBody::{Message => Body}`. [#2446]
* Rename `AnyBody::{from_message => new_boxed}`. [#????]
* Rename `AnyBody::{from_slice => copy_from_slice}`. [#????]
* Rename `BoxAnyBody` to `BoxBody` [#????]
* Change representation of `AnyBody` to include a type parameter in `Body` variant. Defaults to `BoxBody`. [#????]
* Rename `AnyBody::{from_message => new_boxed}`. [#2448]
* Rename `AnyBody::{from_slice => copy_from_slice}`. [#2448]
* Rename `BoxAnyBody` to `BoxBody` [#2448]
* Change representation of `AnyBody` to include a type parameter in `Body` variant. Defaults to `BoxBody`. [#2448]
* `Encoder::response` now returns `AnyBody<Encoder<B>>`. [#2448]

### Removed
* `AnyBody::Empty`; an empty body can now only be represented as a zero-length `Bytes` variant. [#2446]
* `BodySize::Empty`; an empty body can now only be represented as a `Sized(0)` variant. [#2446]
* `EncoderError::Boxed`; it is no longer required. [#2446]

[#2446]: https://github.com/actix/actix-web/pull/2446

Expand Down
39 changes: 14 additions & 25 deletions actix-http/src/encoding/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use flate2::write::{GzEncoder, ZlibEncoder};
use zstd::stream::write::Encoder as ZstdEncoder;

use crate::{
body::{Body, BodySize, BoxBody, MessageBody, ResponseBody},
body::{AnyBody, BodySize, MessageBody},
http::{
header::{ContentEncoding, CONTENT_ENCODING},
HeaderValue, StatusCode,
Expand All @@ -50,35 +50,33 @@ impl<B: MessageBody> Encoder<B> {
pub fn response(
encoding: ContentEncoding,
head: &mut ResponseHead,
body: ResponseBody<B>,
) -> ResponseBody<Encoder<B>> {
body: AnyBody<B>,
) -> AnyBody<Encoder<B>> {
let can_encode = !(head.headers().contains_key(&CONTENT_ENCODING)
|| head.status == StatusCode::SWITCHING_PROTOCOLS
|| head.status == StatusCode::NO_CONTENT
|| encoding == ContentEncoding::Identity
|| encoding == ContentEncoding::Auto);

let body = match body {
ResponseBody::Other(b) => match b {
Body::None => return ResponseBody::Other(Body::None),
Body::Bytes(buf) => {
if can_encode {
EncoderBody::Bytes(buf)
} else {
return ResponseBody::Other(Body::Bytes(buf));
}
AnyBody::None => return AnyBody::None,
AnyBody::Bytes(buf) => {
if can_encode {
EncoderBody::Bytes(buf)
} else {
return AnyBody::Bytes(buf);
}
Body::Body(stream) => EncoderBody::BoxedStream(stream),
},
ResponseBody::Body(stream) => EncoderBody::Stream(stream),
}
AnyBody::Body(body) => EncoderBody::Stream(body),
};

if can_encode {
// Modify response body only if encoder is not None
if let Some(enc) = ContentEncoder::encoder(encoding) {
update_head(encoding, head);
head.no_chunking(false);
return ResponseBody::Body(Encoder {

return AnyBody::Body(Encoder {
body,
eof: false,
fut: None,
Expand All @@ -87,7 +85,7 @@ impl<B: MessageBody> Encoder<B> {
}
}

ResponseBody::Body(Encoder {
AnyBody::Body(Encoder {
body,
eof: false,
fut: None,
Expand All @@ -100,7 +98,6 @@ impl<B: MessageBody> Encoder<B> {
enum EncoderBody<B> {
Bytes(Bytes),
Stream(#[pin] B),
BoxedStream(BoxBody),
}

impl<B> MessageBody for EncoderBody<B>
Expand All @@ -113,7 +110,6 @@ where
match self {
EncoderBody::Bytes(ref b) => b.size(),
EncoderBody::Stream(ref b) => b.size(),
EncoderBody::BoxedStream(ref b) => b.size(),
}
}

Expand All @@ -130,9 +126,6 @@ where
}
}
EncoderBodyProj::Stream(b) => b.poll_next(cx).map_err(EncoderError::Body),
EncoderBodyProj::BoxedStream(ref mut b) => {
b.as_pin_mut().poll_next(cx).map_err(EncoderError::Boxed)
}
}
}
}
Expand Down Expand Up @@ -348,9 +341,6 @@ pub enum EncoderError<E> {
#[display(fmt = "body")]
Body(E),

#[display(fmt = "boxed")]
Boxed(Box<dyn StdError>),

#[display(fmt = "blocking")]
Blocking(BlockingError),

Expand All @@ -362,7 +352,6 @@ impl<E: StdError + 'static> StdError for EncoderError<E> {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match self {
EncoderError::Body(err) => Some(err),
EncoderError::Boxed(err) => Some(&**err),
EncoderError::Blocking(err) => Some(err),
EncoderError::Io(err) => Some(err),
}
Expand Down
33 changes: 19 additions & 14 deletions src/middleware/compress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@ use std::{
};

use actix_http::{
body::{MessageBody, ResponseBody},
body::{AnyBody, MessageBody},
encoding::Encoder,
http::header::{ContentEncoding, ACCEPT_ENCODING},
StatusCode,
};
use actix_service::{Service, Transform};
use actix_utils::future::{ok, Either, Ready};
use bytes::Bytes;
use futures_core::ready;
use once_cell::sync::Lazy;
use pin_project::pin_project;
Expand Down Expand Up @@ -61,7 +62,7 @@ where
B: MessageBody,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{
type Response = ServiceResponse<ResponseBody<Encoder<B>>>;
type Response = ServiceResponse<AnyBody<Encoder<B>>>;
type Error = Error;
type Transform = CompressMiddleware<S>;
type InitError = ();
Expand Down Expand Up @@ -110,7 +111,7 @@ where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
B: MessageBody,
{
type Response = ServiceResponse<ResponseBody<Encoder<B>>>;
type Response = ServiceResponse<AnyBody<Encoder<B>>>;
type Error = Error;
type Future = Either<CompressResponse<S, B>, Ready<Result<Self::Response, Self::Error>>>;

Expand Down Expand Up @@ -142,15 +143,19 @@ where

// There is an HTTP header but we cannot match what client as asked for
Some(Err(_)) => {
let res = HttpResponse::with_body(
StatusCode::NOT_ACCEPTABLE,
SUPPORTED_ALGORITHM_NAMES.as_str(),
);
let enc = ContentEncoding::Identity;

Either::right(ok(req.into_response(res.map_body(move |head, body| {
Encoder::response(enc, head, ResponseBody::Other(body.into()))
}))))
let res = HttpResponse::new(StatusCode::NOT_ACCEPTABLE);

let res: HttpResponse<AnyBody<Encoder<B>>> = res.map_body(move |head, _| {
let body_bytes = Bytes::from(SUPPORTED_ALGORITHM_NAMES.as_bytes());

Encoder::response(
ContentEncoding::Identity,
head,
AnyBody::Bytes(body_bytes),
)
});

Either::right(ok(req.into_response(res)))
}
}
}
Expand All @@ -172,7 +177,7 @@ where
B: MessageBody,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{
type Output = Result<ServiceResponse<ResponseBody<Encoder<B>>>, Error>;
type Output = Result<ServiceResponse<AnyBody<Encoder<B>>>, Error>;

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
Expand All @@ -186,7 +191,7 @@ where
};

Poll::Ready(Ok(resp.map_body(move |head, body| {
Encoder::response(enc, head, ResponseBody::Body(body))
Encoder::response(enc, head, AnyBody::Body(body))
})))
}
Err(e) => Poll::Ready(Err(e)),
Expand Down
3 changes: 3 additions & 0 deletions src/response/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,9 @@ impl<B> HttpResponse<B> {
}
}

// TODO: into_body equivalent
// TODO: into_boxed_body

/// Extract response body
pub fn into_body(self) -> B {
self.res.into_body()
Expand Down

0 comments on commit 0b13d27

Please sign in to comment.