1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-02 13:29:24 +00:00

add associated error type to MessageBody (#2183)

This commit is contained in:
Rob Ede 2021-05-05 18:36:02 +01:00 committed by GitHub
parent dd1a3e7675
commit ddaf8c3e43
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
27 changed files with 447 additions and 74 deletions

View file

@ -2,11 +2,13 @@
## Unreleased - 2021-xx-xx
### Added
* `BoxAnyBody`: a boxed message body with boxed errors. [#2183]
* Re-export `http` crate's `Error` type as `error::HttpError`. [#2171]
* Re-export `StatusCode`, `Method`, `Version` and `Uri` at the crate root. [#2171]
* Re-export `ContentEncoding` and `ConnectionType` at the crate root. [#2171]
### Changed
* The `MessageBody` trait now has an associated `Error` type. [#2183]
* `header` mod is now public. [#2171]
* `uri` mod is now public. [#2171]
* Update `language-tags` to `0.3`.
@ -14,8 +16,10 @@
### Removed
* Stop re-exporting `http` crate's `HeaderMap` types in addition to ours. [#2171]
* Down-casting for `MessageBody` types. [#2183]
[#2171]: https://github.com/actix/actix-web/pull/2171
[#2183]: https://github.com/actix/actix-web/pull/2183
[#2196]: https://github.com/actix/actix-web/pull/2196

View file

@ -1,16 +1,17 @@
use std::{
borrow::Cow,
error::Error as StdError,
fmt, mem,
pin::Pin,
task::{Context, Poll},
};
use bytes::{Bytes, BytesMut};
use futures_core::Stream;
use futures_core::{ready, Stream};
use crate::error::Error;
use super::{BodySize, BodyStream, MessageBody, SizedStream};
use super::{BodySize, BodyStream, MessageBody, MessageBodyMapErr, SizedStream};
/// Represents various types of HTTP message body.
// #[deprecated(since = "4.0.0", note = "Use body types directly.")]
@ -25,7 +26,7 @@ pub enum Body {
Bytes(Bytes),
/// Generic message body.
Message(Pin<Box<dyn MessageBody>>),
Message(BoxAnyBody),
}
impl Body {
@ -35,12 +36,18 @@ impl Body {
}
/// Create body from generic message body.
pub fn from_message<B: MessageBody + 'static>(body: B) -> Body {
Body::Message(Box::pin(body))
pub fn from_message<B>(body: B) -> Body
where
B: MessageBody + 'static,
B::Error: Into<Box<dyn StdError + 'static>>,
{
Self::Message(BoxAnyBody::from_body(body))
}
}
impl MessageBody for Body {
type Error = Error;
fn size(&self) -> BodySize {
match self {
Body::None => BodySize::None,
@ -53,7 +60,7 @@ impl MessageBody for Body {
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> {
) -> Poll<Option<Result<Bytes, Self::Error>>> {
match self.get_mut() {
Body::None => Poll::Ready(None),
Body::Empty => Poll::Ready(None),
@ -65,7 +72,13 @@ impl MessageBody for Body {
Poll::Ready(Some(Ok(mem::take(bin))))
}
}
Body::Message(body) => body.as_mut().poll_next(cx),
// TODO: MSRV 1.51: poll_map_err
Body::Message(body) => match ready!(body.as_pin_mut().poll_next(cx)) {
Some(Err(err)) => Poll::Ready(Some(Err(err.into()))),
Some(Ok(val)) => Poll::Ready(Some(Ok(val))),
None => Poll::Ready(None),
},
}
}
}
@ -166,3 +179,51 @@ where
Body::from_message(s)
}
}
/// A boxed message body with boxed errors.
pub struct BoxAnyBody(Pin<Box<dyn MessageBody<Error = Box<dyn StdError + 'static>>>>);
impl BoxAnyBody {
/// Boxes a `MessageBody` and any errors it generates.
pub fn from_body<B>(body: B) -> Self
where
B: MessageBody + 'static,
B::Error: Into<Box<dyn StdError + 'static>>,
{
let body = MessageBodyMapErr::new(body, Into::into);
Self(Box::pin(body))
}
/// Returns a mutable pinned reference to the inner message body type.
pub fn as_pin_mut(
&mut self,
) -> Pin<&mut (dyn MessageBody<Error = Box<dyn StdError + 'static>>)> {
self.0.as_mut()
}
}
impl fmt::Debug for BoxAnyBody {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("BoxAnyBody(dyn MessageBody)")
}
}
impl MessageBody for BoxAnyBody {
type Error = Error;
fn size(&self) -> BodySize {
self.0.size()
}
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Self::Error>>> {
// TODO: MSRV 1.51: poll_map_err
match ready!(self.0.as_mut().poll_next(cx)) {
Some(Err(err)) => Poll::Ready(Some(Err(err.into()))),
Some(Ok(val)) => Poll::Ready(Some(Ok(val))),
None => Poll::Ready(None),
}
}
}

View file

@ -36,6 +36,8 @@ where
S: Stream<Item = Result<Bytes, E>>,
E: Into<Error>,
{
type Error = Error;
fn size(&self) -> BodySize {
BodySize::Stream
}
@ -48,7 +50,7 @@ where
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> {
) -> Poll<Option<Result<Bytes, Self::Error>>> {
loop {
let stream = self.as_mut().project().stream;

View file

@ -1,12 +1,15 @@
//! [`MessageBody`] trait and foreign implementations.
use std::{
convert::Infallible,
mem,
pin::Pin,
task::{Context, Poll},
};
use bytes::{Bytes, BytesMut};
use futures_core::ready;
use pin_project_lite::pin_project;
use crate::error::Error;
@ -14,6 +17,8 @@ use super::BodySize;
/// An interface for response bodies.
pub trait MessageBody {
type Error;
/// Body size hint.
fn size(&self) -> BodySize;
@ -21,14 +26,12 @@ pub trait MessageBody {
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>>;
downcast_get_type_id!();
) -> Poll<Option<Result<Bytes, Self::Error>>>;
}
downcast!(MessageBody);
impl MessageBody for () {
type Error = Infallible;
fn size(&self) -> BodySize {
BodySize::Empty
}
@ -36,12 +39,18 @@ impl MessageBody for () {
fn poll_next(
self: Pin<&mut Self>,
_: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> {
) -> Poll<Option<Result<Bytes, Self::Error>>> {
Poll::Ready(None)
}
}
impl<T: MessageBody + Unpin> MessageBody for Box<T> {
impl<B> MessageBody for Box<B>
where
B: MessageBody + Unpin,
B::Error: Into<Error>,
{
type Error = B::Error;
fn size(&self) -> BodySize {
self.as_ref().size()
}
@ -49,12 +58,18 @@ impl<T: MessageBody + Unpin> MessageBody for Box<T> {
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> {
) -> Poll<Option<Result<Bytes, Self::Error>>> {
Pin::new(self.get_mut().as_mut()).poll_next(cx)
}
}
impl<T: MessageBody> MessageBody for Pin<Box<T>> {
impl<B> MessageBody for Pin<Box<B>>
where
B: MessageBody,
B::Error: Into<Error>,
{
type Error = B::Error;
fn size(&self) -> BodySize {
self.as_ref().size()
}
@ -62,12 +77,14 @@ impl<T: MessageBody> MessageBody for Pin<Box<T>> {
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> {
) -> Poll<Option<Result<Bytes, Self::Error>>> {
self.as_mut().poll_next(cx)
}
}
impl MessageBody for Bytes {
type Error = Infallible;
fn size(&self) -> BodySize {
BodySize::Sized(self.len() as u64)
}
@ -75,7 +92,7 @@ impl MessageBody for Bytes {
fn poll_next(
self: Pin<&mut Self>,
_: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> {
) -> Poll<Option<Result<Bytes, Self::Error>>> {
if self.is_empty() {
Poll::Ready(None)
} else {
@ -85,6 +102,8 @@ impl MessageBody for Bytes {
}
impl MessageBody for BytesMut {
type Error = Infallible;
fn size(&self) -> BodySize {
BodySize::Sized(self.len() as u64)
}
@ -92,7 +111,7 @@ impl MessageBody for BytesMut {
fn poll_next(
self: Pin<&mut Self>,
_: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> {
) -> Poll<Option<Result<Bytes, Self::Error>>> {
if self.is_empty() {
Poll::Ready(None)
} else {
@ -102,6 +121,8 @@ impl MessageBody for BytesMut {
}
impl MessageBody for &'static str {
type Error = Infallible;
fn size(&self) -> BodySize {
BodySize::Sized(self.len() as u64)
}
@ -109,7 +130,7 @@ impl MessageBody for &'static str {
fn poll_next(
self: Pin<&mut Self>,
_: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> {
) -> Poll<Option<Result<Bytes, Self::Error>>> {
if self.is_empty() {
Poll::Ready(None)
} else {
@ -121,6 +142,8 @@ impl MessageBody for &'static str {
}
impl MessageBody for Vec<u8> {
type Error = Infallible;
fn size(&self) -> BodySize {
BodySize::Sized(self.len() as u64)
}
@ -128,7 +151,7 @@ impl MessageBody for Vec<u8> {
fn poll_next(
self: Pin<&mut Self>,
_: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> {
) -> Poll<Option<Result<Bytes, Self::Error>>> {
if self.is_empty() {
Poll::Ready(None)
} else {
@ -138,6 +161,8 @@ impl MessageBody for Vec<u8> {
}
impl MessageBody for String {
type Error = Infallible;
fn size(&self) -> BodySize {
BodySize::Sized(self.len() as u64)
}
@ -145,7 +170,7 @@ impl MessageBody for String {
fn poll_next(
self: Pin<&mut Self>,
_: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> {
) -> Poll<Option<Result<Bytes, Self::Error>>> {
if self.is_empty() {
Poll::Ready(None)
} else {
@ -155,3 +180,53 @@ impl MessageBody for String {
}
}
}
pin_project! {
pub(crate) struct MessageBodyMapErr<B, F> {
#[pin]
body: B,
mapper: Option<F>,
}
}
impl<B, F, E> MessageBodyMapErr<B, F>
where
B: MessageBody,
F: FnOnce(B::Error) -> E,
{
pub(crate) fn new(body: B, mapper: F) -> Self {
Self {
body,
mapper: Some(mapper),
}
}
}
impl<B, F, E> MessageBody for MessageBodyMapErr<B, F>
where
B: MessageBody,
F: FnOnce(B::Error) -> E,
{
type Error = E;
fn size(&self) -> BodySize {
self.body.size()
}
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Self::Error>>> {
let this = self.as_mut().project();
match ready!(this.body.poll_next(cx)) {
Some(Err(err)) => {
let f = self.as_mut().project().mapper.take().unwrap();
let mapped_err = (f)(err);
Poll::Ready(Some(Err(mapped_err)))
}
Some(Ok(val)) => Poll::Ready(Some(Ok(val))),
None => Poll::Ready(None),
}
}
}

View file

@ -15,9 +15,10 @@ mod response_body;
mod size;
mod sized_stream;
pub use self::body::Body;
pub use self::body::{Body, BoxAnyBody};
pub use self::body_stream::BodyStream;
pub use self::message_body::MessageBody;
pub(crate) use self::message_body::MessageBodyMapErr;
pub use self::response_body::ResponseBody;
pub use self::size::BodySize;
pub use self::sized_stream::SizedStream;
@ -41,7 +42,7 @@ pub use self::sized_stream::SizedStream;
/// assert_eq!(bytes, b"123"[..]);
/// # }
/// ```
pub async fn to_bytes(body: impl MessageBody) -> Result<Bytes, crate::Error> {
pub async fn to_bytes<B: MessageBody>(body: B) -> Result<Bytes, B::Error> {
let cap = match body.size() {
BodySize::None | BodySize::Empty | BodySize::Sized(0) => return Ok(Bytes::new()),
BodySize::Sized(size) => size as usize,
@ -237,10 +238,13 @@ mod tests {
);
}
// down-casting used to be done with a method on MessageBody trait
// test is kept to demonstrate equivalence of Any trait
#[actix_rt::test]
async fn test_body_casting() {
let mut body = String::from("hello cast");
let resp_body: &mut dyn MessageBody = &mut body;
// let mut resp_body: &mut dyn MessageBody<Error = Error> = &mut body;
let resp_body: &mut dyn std::any::Any = &mut body;
let body = resp_body.downcast_ref::<String>().unwrap();
assert_eq!(body, "hello cast");
let body = &mut resp_body.downcast_mut::<String>().unwrap();

View file

@ -5,7 +5,7 @@ use std::{
};
use bytes::Bytes;
use futures_core::Stream;
use futures_core::{ready, Stream};
use pin_project::pin_project;
use crate::error::Error;
@ -43,7 +43,13 @@ impl<B: MessageBody> ResponseBody<B> {
}
}
impl<B: MessageBody> MessageBody for ResponseBody<B> {
impl<B> MessageBody for ResponseBody<B>
where
B: MessageBody,
B::Error: Into<Error>,
{
type Error = Error;
fn size(&self) -> BodySize {
match self {
ResponseBody::Body(ref body) => body.size(),
@ -54,12 +60,16 @@ impl<B: MessageBody> MessageBody for ResponseBody<B> {
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> {
) -> Poll<Option<Result<Bytes, Self::Error>>> {
Stream::poll_next(self, cx)
}
}
impl<B: MessageBody> Stream for ResponseBody<B> {
impl<B> Stream for ResponseBody<B>
where
B: MessageBody,
B::Error: Into<Error>,
{
type Item = Result<Bytes, Error>;
fn poll_next(
@ -67,7 +77,12 @@ impl<B: MessageBody> Stream for ResponseBody<B> {
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
match self.project() {
ResponseBodyProj::Body(body) => body.poll_next(cx),
// TODO: MSRV 1.51: poll_map_err
ResponseBodyProj::Body(body) => match ready!(body.poll_next(cx)) {
Some(Err(err)) => Poll::Ready(Some(Err(err.into()))),
Some(Ok(val)) => Poll::Ready(Some(Ok(val))),
None => Poll::Ready(None),
},
ResponseBodyProj::Other(body) => Pin::new(body).poll_next(cx),
}
}

View file

@ -36,6 +36,8 @@ impl<S> MessageBody for SizedStream<S>
where
S: Stream<Item = Result<Bytes, Error>>,
{
type Error = Error;
fn size(&self) -> BodySize {
BodySize::Sized(self.size as u64)
}
@ -48,7 +50,7 @@ where
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> {
) -> Poll<Option<Result<Bytes, Self::Error>>> {
loop {
let stream = self.as_mut().project().stream;

View file

@ -202,11 +202,13 @@ where
/// Finish service configuration and create a HTTP service for HTTP/2 protocol.
pub fn h2<F, B>(self, service: F) -> H2Service<T, S, B>
where
B: MessageBody + 'static,
F: IntoServiceFactory<S, Request>,
S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>> + 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
{
let cfg = ServiceConfig::new(
self.keep_alive,
@ -223,11 +225,13 @@ where
/// Finish service configuration and create `HttpService` instance.
pub fn finish<F, B>(self, service: F) -> HttpService<T, S, B, X, U>
where
B: MessageBody + 'static,
F: IntoServiceFactory<S, Request>,
S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>> + 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
{
let cfg = ServiceConfig::new(
self.keep_alive,

View file

@ -12,10 +12,10 @@ use bytes::Bytes;
use futures_core::future::LocalBoxFuture;
use h2::client::SendRequest;
use crate::body::MessageBody;
use crate::h1::ClientCodec;
use crate::message::{RequestHeadType, ResponseHead};
use crate::payload::Payload;
use crate::{body::MessageBody, Error};
use super::error::SendRequestError;
use super::pool::Acquired;
@ -256,8 +256,9 @@ where
body: RB,
) -> LocalBoxFuture<'static, Result<(ResponseHead, Payload), SendRequestError>>
where
RB: MessageBody + 'static,
H: Into<RequestHeadType> + 'static,
RB: MessageBody + 'static,
RB::Error: Into<Error>,
{
Box::pin(async move {
match self {

View file

@ -11,7 +11,6 @@ use bytes::{Bytes, BytesMut};
use futures_core::{ready, Stream};
use futures_util::SinkExt as _;
use crate::error::PayloadError;
use crate::h1;
use crate::http::{
header::{HeaderMap, IntoHeaderValue, EXPECT, HOST},
@ -19,6 +18,7 @@ use crate::http::{
};
use crate::message::{RequestHeadType, ResponseHead};
use crate::payload::Payload;
use crate::{error::PayloadError, Error};
use super::connection::{ConnectionIo, H1Connection};
use super::error::{ConnectError, SendRequestError};
@ -32,6 +32,7 @@ pub(crate) async fn send_request<Io, B>(
where
Io: ConnectionIo,
B: MessageBody,
B::Error: Into<Error>,
{
// set request host header
if !head.as_ref().headers.contains_key(HOST)
@ -154,6 +155,7 @@ pub(crate) async fn send_body<Io, B>(
where
Io: ConnectionIo,
B: MessageBody,
B::Error: Into<Error>,
{
actix_rt::pin!(body);
@ -161,9 +163,10 @@ where
while !eof {
while !eof && !framed.as_ref().is_write_buf_full() {
match poll_fn(|cx| body.as_mut().poll_next(cx)).await {
Some(result) => {
framed.as_mut().write(h1::Message::Chunk(Some(result?)))?;
Some(Ok(chunk)) => {
framed.as_mut().write(h1::Message::Chunk(Some(chunk)))?;
}
Some(Err(err)) => return Err(err.into().into()),
None => {
eof = true;
framed.as_mut().write(h1::Message::Chunk(None))?;

View file

@ -9,14 +9,19 @@ use h2::{
use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, TRANSFER_ENCODING};
use http::{request::Request, Method, Version};
use crate::body::{BodySize, MessageBody};
use crate::header::HeaderMap;
use crate::message::{RequestHeadType, ResponseHead};
use crate::payload::Payload;
use crate::{
body::{BodySize, MessageBody},
header::HeaderMap,
message::{RequestHeadType, ResponseHead},
payload::Payload,
Error,
};
use super::config::ConnectorConfig;
use super::connection::{ConnectionIo, H2Connection};
use super::error::SendRequestError;
use super::{
config::ConnectorConfig,
connection::{ConnectionIo, H2Connection},
error::SendRequestError,
};
pub(crate) async fn send_request<Io, B>(
mut io: H2Connection<Io>,
@ -26,6 +31,7 @@ pub(crate) async fn send_request<Io, B>(
where
Io: ConnectionIo,
B: MessageBody,
B::Error: Into<Error>,
{
trace!("Sending client request: {:?} {:?}", head, body.size());
@ -125,10 +131,14 @@ where
Ok((head, payload))
}
async fn send_body<B: MessageBody>(
async fn send_body<B>(
body: B,
mut send: SendStream<Bytes>,
) -> Result<(), SendRequestError> {
) -> Result<(), SendRequestError>
where
B: MessageBody,
B::Error: Into<Error>,
{
let mut buf = None;
actix_rt::pin!(body);
loop {
@ -138,7 +148,7 @@ async fn send_body<B: MessageBody>(
send.reserve_capacity(b.len());
buf = Some(b);
}
Some(Err(e)) => return Err(e.into()),
Some(Err(e)) => return Err(e.into().into()),
None => {
if let Err(e) = send.send_data(Bytes::new(), true) {
return Err(e.into());

View file

@ -1,6 +1,7 @@
//! Stream encoders.
use std::{
error::Error as StdError,
future::Future,
io::{self, Write as _},
pin::Pin,
@ -10,12 +11,13 @@ use std::{
use actix_rt::task::{spawn_blocking, JoinHandle};
use brotli2::write::BrotliEncoder;
use bytes::Bytes;
use derive_more::Display;
use flate2::write::{GzEncoder, ZlibEncoder};
use futures_core::ready;
use pin_project::pin_project;
use crate::{
body::{Body, BodySize, MessageBody, ResponseBody},
body::{Body, BodySize, BoxAnyBody, MessageBody, ResponseBody},
http::{
header::{ContentEncoding, CONTENT_ENCODING},
HeaderValue, StatusCode,
@ -92,10 +94,16 @@ impl<B: MessageBody> Encoder<B> {
enum EncoderBody<B> {
Bytes(Bytes),
Stream(#[pin] B),
BoxedStream(Pin<Box<dyn MessageBody>>),
BoxedStream(BoxAnyBody),
}
impl<B: MessageBody> MessageBody for EncoderBody<B> {
impl<B> MessageBody for EncoderBody<B>
where
B: MessageBody,
B::Error: Into<Error>,
{
type Error = EncoderError<B::Error>;
fn size(&self) -> BodySize {
match self {
EncoderBody::Bytes(ref b) => b.size(),
@ -107,7 +115,7 @@ impl<B: MessageBody> MessageBody for EncoderBody<B> {
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> {
) -> Poll<Option<Result<Bytes, Self::Error>>> {
match self.project() {
EncoderBodyProj::Bytes(b) => {
if b.is_empty() {
@ -116,13 +124,32 @@ impl<B: MessageBody> MessageBody for EncoderBody<B> {
Poll::Ready(Some(Ok(std::mem::take(b))))
}
}
EncoderBodyProj::Stream(b) => b.poll_next(cx),
EncoderBodyProj::BoxedStream(ref mut b) => b.as_mut().poll_next(cx),
// TODO: MSRV 1.51: poll_map_err
EncoderBodyProj::Stream(b) => match ready!(b.poll_next(cx)) {
Some(Err(err)) => Poll::Ready(Some(Err(EncoderError::Body(err)))),
Some(Ok(val)) => Poll::Ready(Some(Ok(val))),
None => Poll::Ready(None),
},
EncoderBodyProj::BoxedStream(ref mut b) => {
match ready!(b.as_pin_mut().poll_next(cx)) {
Some(Err(err)) => {
Poll::Ready(Some(Err(EncoderError::Boxed(err.into()))))
}
Some(Ok(val)) => Poll::Ready(Some(Ok(val))),
None => Poll::Ready(None),
}
}
}
}
}
impl<B: MessageBody> MessageBody for Encoder<B> {
impl<B> MessageBody for Encoder<B>
where
B: MessageBody,
B::Error: Into<Error>,
{
type Error = EncoderError<B::Error>;
fn size(&self) -> BodySize {
if self.encoder.is_none() {
self.body.size()
@ -134,7 +161,7 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> {
) -> Poll<Option<Result<Bytes, Self::Error>>> {
let mut this = self.project();
loop {
if *this.eof {
@ -142,8 +169,9 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
}
if let Some(ref mut fut) = this.fut {
let mut encoder =
ready!(Pin::new(fut).poll(cx)).map_err(|_| BlockingError)??;
let mut encoder = ready!(Pin::new(fut).poll(cx))
.map_err(|_| EncoderError::Blocking(BlockingError))?
.map_err(EncoderError::Io)?;
let chunk = encoder.take();
*this.encoder = Some(encoder);
@ -162,7 +190,7 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
Some(Ok(chunk)) => {
if let Some(mut encoder) = this.encoder.take() {
if chunk.len() < MAX_CHUNK_SIZE_ENCODE_IN_PLACE {
encoder.write(&chunk)?;
encoder.write(&chunk).map_err(EncoderError::Io)?;
let chunk = encoder.take();
*this.encoder = Some(encoder);
@ -182,7 +210,7 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
None => {
if let Some(encoder) = this.encoder.take() {
let chunk = encoder.finish()?;
let chunk = encoder.finish().map_err(EncoderError::Io)?;
if chunk.is_empty() {
return Poll::Ready(None);
} else {
@ -281,3 +309,36 @@ impl ContentEncoder {
}
}
}
#[derive(Debug, Display)]
#[non_exhaustive]
pub enum EncoderError<E> {
#[display(fmt = "body")]
Body(E),
#[display(fmt = "boxed")]
Boxed(Error),
#[display(fmt = "blocking")]
Blocking(BlockingError),
#[display(fmt = "io")]
Io(io::Error),
}
impl<E: StdError> StdError for EncoderError<E> {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
None
}
}
impl<E: Into<Error>> From<EncoderError<E>> for Error {
fn from(err: EncoderError<E>) -> Self {
match err {
EncoderError::Body(err) => err.into(),
EncoderError::Boxed(err) => err,
EncoderError::Blocking(err) => err.into(),
EncoderError::Io(err) => err.into(),
}
}
}

View file

@ -2,6 +2,7 @@
use std::{
cell::RefCell,
error::Error as StdError,
fmt,
io::{self, Write as _},
str::Utf8Error,
@ -105,8 +106,7 @@ impl From<()> for Error {
impl From<std::convert::Infallible> for Error {
fn from(_: std::convert::Infallible) -> Self {
// `std::convert::Infallible` indicates an error
// that will never happen
// hint that an error that will never happen
unreachable!()
}
}
@ -145,6 +145,8 @@ impl From<ResponseBuilder> for Error {
#[display(fmt = "Unknown Error")]
struct UnitError;
impl ResponseError for Box<dyn StdError + 'static> {}
/// Returns [`StatusCode::INTERNAL_SERVER_ERROR`] for [`UnitError`].
impl ResponseError for UnitError {}

View file

@ -51,9 +51,13 @@ pub struct Dispatcher<T, S, B, X, U>
where
S: Service<Request>,
S::Error: Into<Error>,
B: MessageBody,
B::Error: Into<Error>,
X: Service<Request, Response = Request>,
X::Error: Into<Error>,
U: Service<(Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display,
{
@ -69,9 +73,13 @@ enum DispatcherState<T, S, B, X, U>
where
S: Service<Request>,
S::Error: Into<Error>,
B: MessageBody,
B::Error: Into<Error>,
X: Service<Request, Response = Request>,
X::Error: Into<Error>,
U: Service<(Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display,
{
@ -84,9 +92,13 @@ struct InnerDispatcher<T, S, B, X, U>
where
S: Service<Request>,
S::Error: Into<Error>,
B: MessageBody,
B::Error: Into<Error>,
X: Service<Request, Response = Request>,
X::Error: Into<Error>,
U: Service<(Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display,
{
@ -122,7 +134,9 @@ enum State<S, B, X>
where
S: Service<Request>,
X: Service<Request, Response = Request>,
B: MessageBody,
B::Error: Into<Error>,
{
None,
ExpectCall(#[pin] X::Future),
@ -133,8 +147,11 @@ where
impl<S, B, X> State<S, B, X>
where
S: Service<Request>,
X: Service<Request, Response = Request>,
B: MessageBody,
B::Error: Into<Error>,
{
fn is_empty(&self) -> bool {
matches!(self, State::None)
@ -150,12 +167,17 @@ enum PollResponse {
impl<T, S, B, X, U> Dispatcher<T, S, B, X, U>
where
T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request>,
S::Error: Into<Error>,
S::Response: Into<Response<B>>,
B: MessageBody,
B::Error: Into<Error>,
X: Service<Request, Response = Request>,
X::Error: Into<Error>,
U: Service<(Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display,
{
@ -206,12 +228,17 @@ where
impl<T, S, B, X, U> InnerDispatcher<T, S, B, X, U>
where
T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request>,
S::Error: Into<Error>,
S::Response: Into<Response<B>>,
B: MessageBody,
B::Error: Into<Error>,
X: Service<Request, Response = Request>,
X::Error: Into<Error>,
U: Service<(Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display,
{
@ -817,12 +844,17 @@ where
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
where
T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request>,
S::Error: Into<Error>,
S::Response: Into<Response<B>>,
B: MessageBody,
B::Error: Into<Error>,
X: Service<Request, Response = Request>,
X::Error: Into<Error>,
U: Service<(Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display,
{

View file

@ -64,11 +64,15 @@ where
S::Error: Into<Error>,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>>,
B: MessageBody,
B::Error: Into<Error>,
X: ServiceFactory<Request, Config = (), Response = Request>,
X::Future: 'static,
X::Error: Into<Error>,
X::InitError: fmt::Debug,
U: ServiceFactory<(Request, Framed<TcpStream, Codec>), Config = (), Response = ()>,
U::Future: 'static,
U::Error: fmt::Display + Into<Error>,
@ -109,11 +113,15 @@ mod openssl {
S::Error: Into<Error>,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>>,
B: MessageBody,
B::Error: Into<Error>,
X: ServiceFactory<Request, Config = (), Response = Request>,
X::Future: 'static,
X::Error: Into<Error>,
X::InitError: fmt::Debug,
U: ServiceFactory<
(Request, Framed<TlsStream<TcpStream>, Codec>),
Config = (),
@ -165,11 +173,15 @@ mod rustls {
S::Error: Into<Error>,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>>,
B: MessageBody,
B::Error: Into<Error>,
X: ServiceFactory<Request, Config = (), Response = Request>,
X::Future: 'static,
X::Error: Into<Error>,
X::InitError: fmt::Debug,
U: ServiceFactory<
(Request, Framed<TlsStream<TcpStream>, Codec>),
Config = (),
@ -253,16 +265,21 @@ impl<T, S, B, X, U> ServiceFactory<(T, Option<net::SocketAddr>)>
for H1Service<T, S, B, X, U>
where
T: AsyncRead + AsyncWrite + Unpin + 'static,
S: ServiceFactory<Request, Config = ()>,
S::Future: 'static,
S::Error: Into<Error>,
S::Response: Into<Response<B>>,
S::InitError: fmt::Debug,
B: MessageBody,
B::Error: Into<Error>,
X: ServiceFactory<Request, Config = (), Response = Request>,
X::Future: 'static,
X::Error: Into<Error>,
X::InitError: fmt::Debug,
U: ServiceFactory<(Request, Framed<T, Codec>), Config = (), Response = ()>,
U::Future: 'static,
U::Error: fmt::Display + Into<Error>,
@ -319,12 +336,17 @@ impl<T, S, B, X, U> Service<(T, Option<net::SocketAddr>)>
for HttpServiceHandler<T, S, B, X, U>
where
T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request>,
S::Error: Into<Error>,
S::Response: Into<Response<B>>,
B: MessageBody,
B::Error: Into<Error>,
X: Service<Request, Response = Request>,
X::Error: Into<Error>,
U: Service<(Request, Framed<T, Codec>), Response = ()>,
U::Error: fmt::Display + Into<Error>,
{

View file

@ -22,6 +22,7 @@ pub struct SendResponse<T, B> {
impl<T, B> SendResponse<T, B>
where
B: MessageBody,
B::Error: Into<Error>,
{
pub fn new(framed: Framed<T, Codec>, response: Response<B>) -> Self {
let (res, body) = response.into_parts();
@ -38,6 +39,7 @@ impl<T, B> Future for SendResponse<T, B>
where
T: AsyncRead + AsyncWrite + Unpin,
B: MessageBody + Unpin,
B::Error: Into<Error>,
{
type Output = Result<Framed<T, Codec>, Error>;

View file

@ -69,11 +69,14 @@ where
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
where
T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request>,
S::Error: Into<Error> + 'static,
S::Future: 'static,
S::Response: Into<Response<B>> + 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
{
type Output = Result<(), DispatchError>;
@ -140,7 +143,9 @@ where
F: Future<Output = Result<I, E>>,
E: Into<Error>,
I: Into<Response<B>>,
B: MessageBody,
B::Error: Into<Error>,
{
fn prepare_response(
&self,
@ -216,7 +221,9 @@ where
F: Future<Output = Result<I, E>>,
E: Into<Error>,
I: Into<Response<B>>,
B: MessageBody,
B::Error: Into<Error>,
{
type Output = ();

View file

@ -40,7 +40,9 @@ where
S::Error: Into<Error> + 'static,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
{
/// Create new `H2Service` instance with config.
pub(crate) fn with_config<F: IntoServiceFactory<S, Request>>(
@ -69,7 +71,9 @@ where
S::Error: Into<Error> + 'static,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
{
/// Create plain TCP based service
pub fn tcp(
@ -106,7 +110,9 @@ mod openssl {
S::Error: Into<Error> + 'static,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
{
/// Create OpenSSL based service
pub fn openssl(
@ -150,7 +156,9 @@ mod rustls {
S::Error: Into<Error> + 'static,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
{
/// Create Rustls based service
pub fn rustls(
@ -185,12 +193,15 @@ mod rustls {
impl<T, S, B> ServiceFactory<(T, Option<net::SocketAddr>)> for H2Service<T, S, B>
where
T: AsyncRead + AsyncWrite + Unpin + 'static,
S: ServiceFactory<Request, Config = ()>,
S::Future: 'static,
S::Error: Into<Error> + 'static,
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
{
type Response = ();
type Error = DispatchError;
@ -252,6 +263,7 @@ where
S::Future: 'static,
S::Response: Into<Response<B>> + 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
{
type Response = ();
type Error = DispatchError;
@ -316,6 +328,7 @@ where
S::Future: 'static,
S::Response: Into<Response<B>> + 'static,
B: MessageBody,
B::Error: Into<Error>,
{
type Output = Result<(), DispatchError>;

View file

@ -242,7 +242,11 @@ impl<B> Response<B> {
}
}
impl<B: MessageBody> fmt::Debug for Response<B> {
impl<B> fmt::Debug for Response<B>
where
B: MessageBody,
B::Error: Into<Error>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let res = writeln!(
f,

View file

@ -59,6 +59,7 @@ where
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
{
/// Create new `HttpService` instance.
pub fn new<F: IntoServiceFactory<S, Request>>(service: F) -> Self {
@ -157,6 +158,7 @@ where
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
X: ServiceFactory<Request, Config = (), Response = Request>,
X::Future: 'static,
@ -208,6 +210,7 @@ mod openssl {
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
X: ServiceFactory<Request, Config = (), Response = Request>,
X::Future: 'static,
@ -275,6 +278,7 @@ mod rustls {
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
X: ServiceFactory<Request, Config = (), Response = Request>,
X::Future: 'static,
@ -339,6 +343,7 @@ where
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
X: ServiceFactory<Request, Config = (), Response = Request>,
X::Future: 'static,
@ -465,13 +470,18 @@ impl<T, S, B, X, U> Service<(T, Protocol, Option<net::SocketAddr>)>
for HttpServiceHandler<T, S, B, X, U>
where
T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request>,
S::Error: Into<Error> + 'static,
S::Future: 'static,
S::Response: Into<Response<B>> + 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
X: Service<Request, Response = Request>,
X::Error: Into<Error>,
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
U::Error: fmt::Display + Into<Error>,
{
@ -522,13 +532,18 @@ where
#[pin_project(project = StateProj)]
enum State<T, S, B, X, U>
where
T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request>,
S::Future: 'static,
S::Error: Into<Error>,
T: AsyncRead + AsyncWrite + Unpin,
B: MessageBody,
B::Error: Into<Error>,
X: Service<Request, Response = Request>,
X::Error: Into<Error>,
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
U::Error: fmt::Display,
{
@ -549,13 +564,18 @@ where
pub struct HttpServiceHandlerResponse<T, S, B, X, U>
where
T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request>,
S::Error: Into<Error> + 'static,
S::Future: 'static,
S::Response: Into<Response<B>> + 'static,
B: MessageBody + 'static,
B: MessageBody,
B::Error: Into<Error>,
X: Service<Request, Response = Request>,
X::Error: Into<Error>,
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
U::Error: fmt::Display,
{
@ -566,13 +586,18 @@ where
impl<T, S, B, X, U> Future for HttpServiceHandlerResponse<T, S, B, X, U>
where
T: AsyncRead + AsyncWrite + Unpin,
S: Service<Request>,
S::Error: Into<Error> + 'static,
S::Future: 'static,
S::Response: Into<Response<B>> + 'static,
B: MessageBody,
B: MessageBody + 'static,
B::Error: Into<Error>,
X: Service<Request, Response = Request>,
X::Error: Into<Error>,
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
U::Error: fmt::Display,
{

View file

@ -86,6 +86,7 @@ where
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
{
start_with(TestServerConfig::default(), factory)
}
@ -125,6 +126,7 @@ where
S::Response: Into<Response<B>> + 'static,
<S::Service as Service<Request>>::Future: 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
{
let (tx, rx) = mpsc::channel();

View file

@ -113,7 +113,11 @@ pub trait MapServiceResponseBody {
fn map_body(self) -> ServiceResponse;
}
impl<B: MessageBody + Unpin + 'static> MapServiceResponseBody for ServiceResponse<B> {
impl<B> MapServiceResponseBody for ServiceResponse<B>
where
B: MessageBody + Unpin + 'static,
B::Error: Into<Error>,
{
fn map_body(self) -> ServiceResponse {
self.map_body(|_, body| ResponseBody::Other(Body::from_message(body)))
}

View file

@ -22,10 +22,9 @@ use time::OffsetDateTime;
use crate::{
dev::{BodySize, MessageBody, ResponseBody},
error::{Error, Result},
http::{HeaderName, StatusCode},
service::{ServiceRequest, ServiceResponse},
HttpResponse,
Error, HttpResponse, Result,
};
/// Middleware for logging request and response summaries to the terminal.
@ -327,7 +326,13 @@ impl<B> PinnedDrop for StreamLog<B> {
}
}
impl<B: MessageBody> MessageBody for StreamLog<B> {
impl<B> MessageBody for StreamLog<B>
where
B: MessageBody,
B::Error: Into<Error>,
{
type Error = Error;
fn size(&self) -> BodySize {
self.body.size()
}
@ -335,7 +340,7 @@ impl<B: MessageBody> MessageBody for StreamLog<B> {
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> {
) -> Poll<Option<Result<Bytes, Self::Error>>> {
let this = self.project();
match this.body.poll_next(cx) {
Poll::Ready(Some(Ok(chunk))) => {

View file

@ -243,7 +243,11 @@ impl<B> HttpResponse<B> {
}
}
impl<B: MessageBody> fmt::Debug for HttpResponse<B> {
impl<B> fmt::Debug for HttpResponse<B>
where
B: MessageBody,
B::Error: Into<Error>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HttpResponse")
.field("error", &self.error)

View file

@ -81,6 +81,7 @@ where
S::Service: 'static,
// S::Service: 'static,
B: MessageBody + 'static,
B::Error: Into<Error>,
{
/// Create new HTTP server with application factory
pub fn new(factory: F) -> Self {

View file

@ -443,7 +443,11 @@ impl<B> From<ServiceResponse<B>> for Response<B> {
}
}
impl<B: MessageBody> fmt::Debug for ServiceResponse<B> {
impl<B> fmt::Debug for ServiceResponse<B>
where
B: MessageBody,
B::Error: Into<Error>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let res = writeln!(
f,

View file

@ -151,6 +151,7 @@ pub async fn read_response<S, B>(app: &S, req: Request) -> Bytes
where
S: Service<Request, Response = ServiceResponse<B>, Error = Error>,
B: MessageBody + Unpin,
B::Error: Into<Error>,
{
let mut resp = app
.call(req)
@ -196,6 +197,7 @@ where
pub async fn read_body<B>(mut res: ServiceResponse<B>) -> Bytes
where
B: MessageBody + Unpin,
B::Error: Into<Error>,
{
let mut body = res.take_body();
let mut bytes = BytesMut::new();
@ -245,6 +247,7 @@ where
pub async fn read_body_json<T, B>(res: ServiceResponse<B>) -> T
where
B: MessageBody + Unpin,
B::Error: Into<Error>,
T: DeserializeOwned,
{
let body = read_body(res).await;
@ -306,6 +309,7 @@ pub async fn read_response_json<S, B, T>(app: &S, req: Request) -> T
where
S: Service<Request, Response = ServiceResponse<B>, Error = Error>,
B: MessageBody + Unpin,
B::Error: Into<Error>,
T: DeserializeOwned,
{
let body = read_response(app, req).await;