mirror of https://github.com/fafhrd91/actix-web
Merge branch 'master' into feature/h1_pending_timer
This commit is contained in:
commit
e6967b66df
|
@ -1,6 +1,8 @@
|
||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
|
### Changed
|
||||||
|
* Update `language-tags` to `0.3`.
|
||||||
|
|
||||||
|
|
||||||
## 4.0.0-beta.6 - 2021-04-17
|
## 4.0.0-beta.6 - 2021-04-17
|
||||||
|
|
|
@ -78,7 +78,7 @@ encoding_rs = "0.8"
|
||||||
futures-core = { version = "0.3.7", default-features = false }
|
futures-core = { version = "0.3.7", default-features = false }
|
||||||
futures-util = { version = "0.3.7", default-features = false }
|
futures-util = { version = "0.3.7", default-features = false }
|
||||||
itoa = "0.4"
|
itoa = "0.4"
|
||||||
language-tags = "0.2"
|
language-tags = "0.3"
|
||||||
once_cell = "1.5"
|
once_cell = "1.5"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
mime = "0.3"
|
mime = "0.3"
|
||||||
|
|
|
@ -11,6 +11,9 @@
|
||||||
## 0.6.0-beta.4 - 2021-04-02
|
## 0.6.0-beta.4 - 2021-04-02
|
||||||
* No notable changes.
|
* No notable changes.
|
||||||
|
|
||||||
|
* Add support for `.guard` in `Files` to selectively filter `Files` services. [#2046]
|
||||||
|
|
||||||
|
[#2046]: https://github.com/actix/actix-web/pull/2046
|
||||||
|
|
||||||
## 0.6.0-beta.3 - 2021-03-09
|
## 0.6.0-beta.3 - 2021-03-09
|
||||||
* No notable changes.
|
* No notable changes.
|
||||||
|
|
|
@ -37,7 +37,8 @@ pub struct Files {
|
||||||
renderer: Rc<DirectoryRenderer>,
|
renderer: Rc<DirectoryRenderer>,
|
||||||
mime_override: Option<Rc<MimeOverride>>,
|
mime_override: Option<Rc<MimeOverride>>,
|
||||||
file_flags: named::Flags,
|
file_flags: named::Flags,
|
||||||
guards: Option<Rc<dyn Guard>>,
|
use_guards: Option<Rc<dyn Guard>>,
|
||||||
|
guards: Vec<Box<Rc<dyn Guard>>>,
|
||||||
hidden_files: bool,
|
hidden_files: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -59,12 +60,12 @@ impl Clone for Files {
|
||||||
file_flags: self.file_flags,
|
file_flags: self.file_flags,
|
||||||
path: self.path.clone(),
|
path: self.path.clone(),
|
||||||
mime_override: self.mime_override.clone(),
|
mime_override: self.mime_override.clone(),
|
||||||
|
use_guards: self.use_guards.clone(),
|
||||||
guards: self.guards.clone(),
|
guards: self.guards.clone(),
|
||||||
hidden_files: self.hidden_files,
|
hidden_files: self.hidden_files,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Files {
|
impl Files {
|
||||||
/// Create new `Files` instance for a specified base directory.
|
/// Create new `Files` instance for a specified base directory.
|
||||||
///
|
///
|
||||||
|
@ -80,10 +81,9 @@ impl Files {
|
||||||
/// If the mount path is set as the root path `/`, services registered after this one will
|
/// If the mount path is set as the root path `/`, services registered after this one will
|
||||||
/// be inaccessible. Register more specific handlers and services first.
|
/// be inaccessible. Register more specific handlers and services first.
|
||||||
///
|
///
|
||||||
/// `Files` uses a threadpool for blocking filesystem operations. By default, the pool uses a
|
/// `Files` utilizes the existing Tokio thread-pool for blocking filesystem operations.
|
||||||
/// max number of threads equal to `512 * HttpServer::worker`. Real time thread count are
|
/// The number of running threads is adjusted over time as needed, up to a maximum of 512 times
|
||||||
/// adjusted with work load. More threads would spawn when need and threads goes idle for a
|
/// the number of server [workers](HttpServer::workers), by default.
|
||||||
/// period of time would be de-spawned.
|
|
||||||
pub fn new<T: Into<PathBuf>>(mount_path: &str, serve_from: T) -> Files {
|
pub fn new<T: Into<PathBuf>>(mount_path: &str, serve_from: T) -> Files {
|
||||||
let orig_dir = serve_from.into();
|
let orig_dir = serve_from.into();
|
||||||
let dir = match orig_dir.canonicalize() {
|
let dir = match orig_dir.canonicalize() {
|
||||||
|
@ -104,7 +104,8 @@ impl Files {
|
||||||
renderer: Rc::new(directory_listing),
|
renderer: Rc::new(directory_listing),
|
||||||
mime_override: None,
|
mime_override: None,
|
||||||
file_flags: named::Flags::default(),
|
file_flags: named::Flags::default(),
|
||||||
guards: None,
|
use_guards: None,
|
||||||
|
guards: Vec::new(),
|
||||||
hidden_files: false,
|
hidden_files: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -156,7 +157,6 @@ impl Files {
|
||||||
/// Specifies whether to use ETag or not.
|
/// Specifies whether to use ETag or not.
|
||||||
///
|
///
|
||||||
/// Default is true.
|
/// Default is true.
|
||||||
#[inline]
|
|
||||||
pub fn use_etag(mut self, value: bool) -> Self {
|
pub fn use_etag(mut self, value: bool) -> Self {
|
||||||
self.file_flags.set(named::Flags::ETAG, value);
|
self.file_flags.set(named::Flags::ETAG, value);
|
||||||
self
|
self
|
||||||
|
@ -165,7 +165,6 @@ impl Files {
|
||||||
/// Specifies whether to use Last-Modified or not.
|
/// Specifies whether to use Last-Modified or not.
|
||||||
///
|
///
|
||||||
/// Default is true.
|
/// Default is true.
|
||||||
#[inline]
|
|
||||||
pub fn use_last_modified(mut self, value: bool) -> Self {
|
pub fn use_last_modified(mut self, value: bool) -> Self {
|
||||||
self.file_flags.set(named::Flags::LAST_MD, value);
|
self.file_flags.set(named::Flags::LAST_MD, value);
|
||||||
self
|
self
|
||||||
|
@ -174,25 +173,55 @@ impl Files {
|
||||||
/// Specifies whether text responses should signal a UTF-8 encoding.
|
/// Specifies whether text responses should signal a UTF-8 encoding.
|
||||||
///
|
///
|
||||||
/// Default is false (but will default to true in a future version).
|
/// Default is false (but will default to true in a future version).
|
||||||
#[inline]
|
|
||||||
pub fn prefer_utf8(mut self, value: bool) -> Self {
|
pub fn prefer_utf8(mut self, value: bool) -> Self {
|
||||||
self.file_flags.set(named::Flags::PREFER_UTF8, value);
|
self.file_flags.set(named::Flags::PREFER_UTF8, value);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Specifies custom guards to use for directory listings and files.
|
/// Adds a routing guard.
|
||||||
///
|
///
|
||||||
/// Default behaviour allows GET and HEAD.
|
/// Use this to allow multiple chained file services that respond to strictly different
|
||||||
#[inline]
|
/// properties of a request. Due to the way routing works, if a guard check returns true and the
|
||||||
pub fn use_guards<G: Guard + 'static>(mut self, guards: G) -> Self {
|
/// request starts being handled by the file service, it will not be able to back-out and try
|
||||||
self.guards = Some(Rc::new(guards));
|
/// the next service, you will simply get a 404 (or 405) error response.
|
||||||
|
///
|
||||||
|
/// To allow `POST` requests to retrieve files, see [`Files::use_guards`].
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// use actix_web::{guard::Header, App};
|
||||||
|
/// use actix_files::Files;
|
||||||
|
///
|
||||||
|
/// App::new().service(
|
||||||
|
/// Files::new("/","/my/site/files")
|
||||||
|
/// .guard(Header("Host", "example.com"))
|
||||||
|
/// );
|
||||||
|
/// ```
|
||||||
|
pub fn guard<G: Guard + 'static>(mut self, guard: G) -> Self {
|
||||||
|
self.guards.push(Box::new(Rc::new(guard)));
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Specifies guard to check before fetching directory listings or files.
|
||||||
|
///
|
||||||
|
/// Note that this guard has no effect on routing; it's main use is to guard on the request's
|
||||||
|
/// method just before serving the file, only allowing `GET` and `HEAD` requests by default.
|
||||||
|
/// See [`Files::guard`] for routing guards.
|
||||||
|
pub fn method_guard<G: Guard + 'static>(mut self, guard: G) -> Self {
|
||||||
|
self.use_guards = Some(Rc::new(guard));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[doc(hidden)]
|
||||||
|
#[deprecated(since = "0.6.0", note = "Renamed to `method_guard`.")]
|
||||||
|
/// See [`Files::method_guard`].
|
||||||
|
pub fn use_guards<G: Guard + 'static>(self, guard: G) -> Self {
|
||||||
|
self.method_guard(guard)
|
||||||
|
}
|
||||||
|
|
||||||
/// Disable `Content-Disposition` header.
|
/// Disable `Content-Disposition` header.
|
||||||
///
|
///
|
||||||
/// By default Content-Disposition` header is enabled.
|
/// By default Content-Disposition` header is enabled.
|
||||||
#[inline]
|
|
||||||
pub fn disable_content_disposition(mut self) -> Self {
|
pub fn disable_content_disposition(mut self) -> Self {
|
||||||
self.file_flags.remove(named::Flags::CONTENT_DISPOSITION);
|
self.file_flags.remove(named::Flags::CONTENT_DISPOSITION);
|
||||||
self
|
self
|
||||||
|
@ -200,8 +229,9 @@ impl Files {
|
||||||
|
|
||||||
/// Sets default handler which is used when no matched file could be found.
|
/// Sets default handler which is used when no matched file could be found.
|
||||||
///
|
///
|
||||||
/// For example, you could set a fall back static file handler:
|
/// # Examples
|
||||||
/// ```rust
|
/// Setting a fallback static file handler:
|
||||||
|
/// ```
|
||||||
/// use actix_files::{Files, NamedFile};
|
/// use actix_files::{Files, NamedFile};
|
||||||
///
|
///
|
||||||
/// # fn run() -> Result<(), actix_web::Error> {
|
/// # fn run() -> Result<(), actix_web::Error> {
|
||||||
|
@ -230,7 +260,6 @@ impl Files {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Enables serving hidden files and directories, allowing a leading dots in url fragments.
|
/// Enables serving hidden files and directories, allowing a leading dots in url fragments.
|
||||||
#[inline]
|
|
||||||
pub fn use_hidden_files(mut self) -> Self {
|
pub fn use_hidden_files(mut self) -> Self {
|
||||||
self.hidden_files = true;
|
self.hidden_files = true;
|
||||||
self
|
self
|
||||||
|
@ -238,7 +267,19 @@ impl Files {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HttpServiceFactory for Files {
|
impl HttpServiceFactory for Files {
|
||||||
fn register(self, config: &mut AppService) {
|
fn register(mut self, config: &mut AppService) {
|
||||||
|
let guards = if self.guards.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
let guards = std::mem::take(&mut self.guards);
|
||||||
|
Some(
|
||||||
|
guards
|
||||||
|
.into_iter()
|
||||||
|
.map(|guard| -> Box<dyn Guard> { guard })
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
if self.default.borrow().is_none() {
|
if self.default.borrow().is_none() {
|
||||||
*self.default.borrow_mut() = Some(config.default_service());
|
*self.default.borrow_mut() = Some(config.default_service());
|
||||||
}
|
}
|
||||||
|
@ -249,7 +290,7 @@ impl HttpServiceFactory for Files {
|
||||||
ResourceDef::prefix(&self.path)
|
ResourceDef::prefix(&self.path)
|
||||||
};
|
};
|
||||||
|
|
||||||
config.register_service(rdef, None, self, None)
|
config.register_service(rdef, guards, self, None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -271,7 +312,7 @@ impl ServiceFactory<ServiceRequest> for Files {
|
||||||
renderer: self.renderer.clone(),
|
renderer: self.renderer.clone(),
|
||||||
mime_override: self.mime_override.clone(),
|
mime_override: self.mime_override.clone(),
|
||||||
file_flags: self.file_flags,
|
file_flags: self.file_flags,
|
||||||
guards: self.guards.clone(),
|
guards: self.use_guards.clone(),
|
||||||
hidden_files: self.hidden_files,
|
hidden_files: self.hidden_files,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -532,7 +532,7 @@ mod tests {
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_files_guards() {
|
async fn test_files_guards() {
|
||||||
let srv = test::init_service(
|
let srv = test::init_service(
|
||||||
App::new().service(Files::new("/", ".").use_guards(guard::Post())),
|
App::new().service(Files::new("/", ".").method_guard(guard::Post())),
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
first
|
|
@ -0,0 +1 @@
|
||||||
|
second
|
|
@ -0,0 +1,36 @@
|
||||||
|
use actix_files::Files;
|
||||||
|
use actix_web::{
|
||||||
|
guard::Host,
|
||||||
|
http::StatusCode,
|
||||||
|
test::{self, TestRequest},
|
||||||
|
App,
|
||||||
|
};
|
||||||
|
use bytes::Bytes;
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_guard_filter() {
|
||||||
|
let srv = test::init_service(
|
||||||
|
App::new()
|
||||||
|
.service(Files::new("/", "./tests/fixtures/guards/first").guard(Host("first.com")))
|
||||||
|
.service(
|
||||||
|
Files::new("/", "./tests/fixtures/guards/second").guard(Host("second.com")),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let req = TestRequest::with_uri("/index.txt")
|
||||||
|
.append_header(("Host", "first.com"))
|
||||||
|
.to_request();
|
||||||
|
let res = test::call_service(&srv, req).await;
|
||||||
|
|
||||||
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
|
assert_eq!(test::read_body(res).await, Bytes::from("first"));
|
||||||
|
|
||||||
|
let req = TestRequest::with_uri("/index.txt")
|
||||||
|
.append_header(("Host", "second.com"))
|
||||||
|
.to_request();
|
||||||
|
let res = test::call_service(&srv, req).await;
|
||||||
|
|
||||||
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
|
assert_eq!(test::read_body(res).await, Bytes::from("second"));
|
||||||
|
}
|
|
@ -2,18 +2,25 @@
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
### Added
|
### Added
|
||||||
|
* `BoxAnyBody`: a boxed message body with boxed errors. [#2183]
|
||||||
* Re-export `http` crate's `Error` type as `error::HttpError`. [#2171]
|
* 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 `StatusCode`, `Method`, `Version` and `Uri` at the crate root. [#2171]
|
||||||
* Re-export `ContentEncoding` and `ConnectionType` at the crate root. [#2171]
|
* Re-export `ContentEncoding` and `ConnectionType` at the crate root. [#2171]
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
* The `MessageBody` trait now has an associated `Error` type. [#2183]
|
||||||
* `header` mod is now public. [#2171]
|
* `header` mod is now public. [#2171]
|
||||||
* `uri` mod is now public. [#2171]
|
* `uri` mod is now public. [#2171]
|
||||||
|
* Update `language-tags` to `0.3`.
|
||||||
|
* Reduce the level from `error` to `debug` for the log line that is emitted when a `500 Internal Server Error` is built using `HttpResponse::from_error`. [#2196]
|
||||||
|
|
||||||
### Removed
|
### Removed
|
||||||
* Stop re-exporting `http` crate's `HeaderMap` types in addition to ours. [#2171]
|
* 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
|
[#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
|
||||||
|
|
||||||
|
|
||||||
## 3.0.0-beta.6 - 2021-04-17
|
## 3.0.0-beta.6 - 2021-04-17
|
||||||
|
|
|
@ -57,7 +57,7 @@ h2 = "0.3.1"
|
||||||
http = "0.2.2"
|
http = "0.2.2"
|
||||||
httparse = "1.3"
|
httparse = "1.3"
|
||||||
itoa = "0.4"
|
itoa = "0.4"
|
||||||
language-tags = "0.2"
|
language-tags = "0.3"
|
||||||
local-channel = "0.1"
|
local-channel = "0.1"
|
||||||
once_cell = "1.5"
|
once_cell = "1.5"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
|
|
|
@ -1,16 +1,17 @@
|
||||||
use std::{
|
use std::{
|
||||||
borrow::Cow,
|
borrow::Cow,
|
||||||
|
error::Error as StdError,
|
||||||
fmt, mem,
|
fmt, mem,
|
||||||
pin::Pin,
|
pin::Pin,
|
||||||
task::{Context, Poll},
|
task::{Context, Poll},
|
||||||
};
|
};
|
||||||
|
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use futures_core::Stream;
|
use futures_core::{ready, Stream};
|
||||||
|
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
|
|
||||||
use super::{BodySize, BodyStream, MessageBody, SizedStream};
|
use super::{BodySize, BodyStream, MessageBody, MessageBodyMapErr, SizedStream};
|
||||||
|
|
||||||
/// Represents various types of HTTP message body.
|
/// Represents various types of HTTP message body.
|
||||||
// #[deprecated(since = "4.0.0", note = "Use body types directly.")]
|
// #[deprecated(since = "4.0.0", note = "Use body types directly.")]
|
||||||
|
@ -25,7 +26,7 @@ pub enum Body {
|
||||||
Bytes(Bytes),
|
Bytes(Bytes),
|
||||||
|
|
||||||
/// Generic message body.
|
/// Generic message body.
|
||||||
Message(Pin<Box<dyn MessageBody>>),
|
Message(BoxAnyBody),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Body {
|
impl Body {
|
||||||
|
@ -35,12 +36,18 @@ impl Body {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create body from generic message body.
|
/// Create body from generic message body.
|
||||||
pub fn from_message<B: MessageBody + 'static>(body: B) -> Body {
|
pub fn from_message<B>(body: B) -> Body
|
||||||
Body::Message(Box::pin(body))
|
where
|
||||||
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Box<dyn StdError + 'static>>,
|
||||||
|
{
|
||||||
|
Self::Message(BoxAnyBody::from_body(body))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MessageBody for Body {
|
impl MessageBody for Body {
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
match self {
|
match self {
|
||||||
Body::None => BodySize::None,
|
Body::None => BodySize::None,
|
||||||
|
@ -53,7 +60,7 @@ impl MessageBody for Body {
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
match self.get_mut() {
|
match self.get_mut() {
|
||||||
Body::None => Poll::Ready(None),
|
Body::None => Poll::Ready(None),
|
||||||
Body::Empty => Poll::Ready(None),
|
Body::Empty => Poll::Ready(None),
|
||||||
|
@ -65,7 +72,13 @@ impl MessageBody for Body {
|
||||||
Poll::Ready(Some(Ok(mem::take(bin))))
|
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)
|
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),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -36,6 +36,8 @@ where
|
||||||
S: Stream<Item = Result<Bytes, E>>,
|
S: Stream<Item = Result<Bytes, E>>,
|
||||||
E: Into<Error>,
|
E: Into<Error>,
|
||||||
{
|
{
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Stream
|
BodySize::Stream
|
||||||
}
|
}
|
||||||
|
@ -48,7 +50,7 @@ where
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
mut self: Pin<&mut Self>,
|
mut self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
loop {
|
loop {
|
||||||
let stream = self.as_mut().project().stream;
|
let stream = self.as_mut().project().stream;
|
||||||
|
|
||||||
|
|
|
@ -1,12 +1,15 @@
|
||||||
//! [`MessageBody`] trait and foreign implementations.
|
//! [`MessageBody`] trait and foreign implementations.
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
|
convert::Infallible,
|
||||||
mem,
|
mem,
|
||||||
pin::Pin,
|
pin::Pin,
|
||||||
task::{Context, Poll},
|
task::{Context, Poll},
|
||||||
};
|
};
|
||||||
|
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
|
use futures_core::ready;
|
||||||
|
use pin_project_lite::pin_project;
|
||||||
|
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
|
|
||||||
|
@ -14,6 +17,8 @@ use super::BodySize;
|
||||||
|
|
||||||
/// An interface for response bodies.
|
/// An interface for response bodies.
|
||||||
pub trait MessageBody {
|
pub trait MessageBody {
|
||||||
|
type Error;
|
||||||
|
|
||||||
/// Body size hint.
|
/// Body size hint.
|
||||||
fn size(&self) -> BodySize;
|
fn size(&self) -> BodySize;
|
||||||
|
|
||||||
|
@ -21,14 +26,12 @@ pub trait MessageBody {
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>>;
|
) -> Poll<Option<Result<Bytes, Self::Error>>>;
|
||||||
|
|
||||||
downcast_get_type_id!();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
downcast!(MessageBody);
|
|
||||||
|
|
||||||
impl MessageBody for () {
|
impl MessageBody for () {
|
||||||
|
type Error = Infallible;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Empty
|
BodySize::Empty
|
||||||
}
|
}
|
||||||
|
@ -36,12 +39,18 @@ impl MessageBody for () {
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
_: &mut Context<'_>,
|
_: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
Poll::Ready(None)
|
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 {
|
fn size(&self) -> BodySize {
|
||||||
self.as_ref().size()
|
self.as_ref().size()
|
||||||
}
|
}
|
||||||
|
@ -49,12 +58,18 @@ impl<T: MessageBody + Unpin> MessageBody for Box<T> {
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
Pin::new(self.get_mut().as_mut()).poll_next(cx)
|
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 {
|
fn size(&self) -> BodySize {
|
||||||
self.as_ref().size()
|
self.as_ref().size()
|
||||||
}
|
}
|
||||||
|
@ -62,12 +77,14 @@ impl<T: MessageBody> MessageBody for Pin<Box<T>> {
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
mut self: Pin<&mut Self>,
|
mut self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
self.as_mut().poll_next(cx)
|
self.as_mut().poll_next(cx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MessageBody for Bytes {
|
impl MessageBody for Bytes {
|
||||||
|
type Error = Infallible;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Sized(self.len() as u64)
|
BodySize::Sized(self.len() as u64)
|
||||||
}
|
}
|
||||||
|
@ -75,7 +92,7 @@ impl MessageBody for Bytes {
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
_: &mut Context<'_>,
|
_: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
if self.is_empty() {
|
if self.is_empty() {
|
||||||
Poll::Ready(None)
|
Poll::Ready(None)
|
||||||
} else {
|
} else {
|
||||||
|
@ -85,6 +102,8 @@ impl MessageBody for Bytes {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MessageBody for BytesMut {
|
impl MessageBody for BytesMut {
|
||||||
|
type Error = Infallible;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Sized(self.len() as u64)
|
BodySize::Sized(self.len() as u64)
|
||||||
}
|
}
|
||||||
|
@ -92,7 +111,7 @@ impl MessageBody for BytesMut {
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
_: &mut Context<'_>,
|
_: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
if self.is_empty() {
|
if self.is_empty() {
|
||||||
Poll::Ready(None)
|
Poll::Ready(None)
|
||||||
} else {
|
} else {
|
||||||
|
@ -102,6 +121,8 @@ impl MessageBody for BytesMut {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MessageBody for &'static str {
|
impl MessageBody for &'static str {
|
||||||
|
type Error = Infallible;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Sized(self.len() as u64)
|
BodySize::Sized(self.len() as u64)
|
||||||
}
|
}
|
||||||
|
@ -109,7 +130,7 @@ impl MessageBody for &'static str {
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
_: &mut Context<'_>,
|
_: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
if self.is_empty() {
|
if self.is_empty() {
|
||||||
Poll::Ready(None)
|
Poll::Ready(None)
|
||||||
} else {
|
} else {
|
||||||
|
@ -121,6 +142,8 @@ impl MessageBody for &'static str {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MessageBody for Vec<u8> {
|
impl MessageBody for Vec<u8> {
|
||||||
|
type Error = Infallible;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Sized(self.len() as u64)
|
BodySize::Sized(self.len() as u64)
|
||||||
}
|
}
|
||||||
|
@ -128,7 +151,7 @@ impl MessageBody for Vec<u8> {
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
_: &mut Context<'_>,
|
_: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
if self.is_empty() {
|
if self.is_empty() {
|
||||||
Poll::Ready(None)
|
Poll::Ready(None)
|
||||||
} else {
|
} else {
|
||||||
|
@ -138,6 +161,8 @@ impl MessageBody for Vec<u8> {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MessageBody for String {
|
impl MessageBody for String {
|
||||||
|
type Error = Infallible;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Sized(self.len() as u64)
|
BodySize::Sized(self.len() as u64)
|
||||||
}
|
}
|
||||||
|
@ -145,7 +170,7 @@ impl MessageBody for String {
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
_: &mut Context<'_>,
|
_: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
if self.is_empty() {
|
if self.is_empty() {
|
||||||
Poll::Ready(None)
|
Poll::Ready(None)
|
||||||
} else {
|
} 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),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -15,9 +15,10 @@ mod response_body;
|
||||||
mod size;
|
mod size;
|
||||||
mod sized_stream;
|
mod sized_stream;
|
||||||
|
|
||||||
pub use self::body::Body;
|
pub use self::body::{Body, BoxAnyBody};
|
||||||
pub use self::body_stream::BodyStream;
|
pub use self::body_stream::BodyStream;
|
||||||
pub use self::message_body::MessageBody;
|
pub use self::message_body::MessageBody;
|
||||||
|
pub(crate) use self::message_body::MessageBodyMapErr;
|
||||||
pub use self::response_body::ResponseBody;
|
pub use self::response_body::ResponseBody;
|
||||||
pub use self::size::BodySize;
|
pub use self::size::BodySize;
|
||||||
pub use self::sized_stream::SizedStream;
|
pub use self::sized_stream::SizedStream;
|
||||||
|
@ -41,7 +42,7 @@ pub use self::sized_stream::SizedStream;
|
||||||
/// assert_eq!(bytes, b"123"[..]);
|
/// 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() {
|
let cap = match body.size() {
|
||||||
BodySize::None | BodySize::Empty | BodySize::Sized(0) => return Ok(Bytes::new()),
|
BodySize::None | BodySize::Empty | BodySize::Sized(0) => return Ok(Bytes::new()),
|
||||||
BodySize::Sized(size) => size as usize,
|
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]
|
#[actix_rt::test]
|
||||||
async fn test_body_casting() {
|
async fn test_body_casting() {
|
||||||
let mut body = String::from("hello cast");
|
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();
|
let body = resp_body.downcast_ref::<String>().unwrap();
|
||||||
assert_eq!(body, "hello cast");
|
assert_eq!(body, "hello cast");
|
||||||
let body = &mut resp_body.downcast_mut::<String>().unwrap();
|
let body = &mut resp_body.downcast_mut::<String>().unwrap();
|
||||||
|
|
|
@ -5,7 +5,7 @@ use std::{
|
||||||
};
|
};
|
||||||
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures_core::Stream;
|
use futures_core::{ready, Stream};
|
||||||
use pin_project::pin_project;
|
use pin_project::pin_project;
|
||||||
|
|
||||||
use crate::error::Error;
|
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 {
|
fn size(&self) -> BodySize {
|
||||||
match self {
|
match self {
|
||||||
ResponseBody::Body(ref body) => body.size(),
|
ResponseBody::Body(ref body) => body.size(),
|
||||||
|
@ -54,12 +60,16 @@ impl<B: MessageBody> MessageBody for ResponseBody<B> {
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
Stream::poll_next(self, cx)
|
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>;
|
type Item = Result<Bytes, Error>;
|
||||||
|
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
|
@ -67,7 +77,12 @@ impl<B: MessageBody> Stream for ResponseBody<B> {
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Self::Item>> {
|
) -> Poll<Option<Self::Item>> {
|
||||||
match self.project() {
|
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),
|
ResponseBodyProj::Other(body) => Pin::new(body).poll_next(cx),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -36,6 +36,8 @@ impl<S> MessageBody for SizedStream<S>
|
||||||
where
|
where
|
||||||
S: Stream<Item = Result<Bytes, Error>>,
|
S: Stream<Item = Result<Bytes, Error>>,
|
||||||
{
|
{
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Sized(self.size as u64)
|
BodySize::Sized(self.size as u64)
|
||||||
}
|
}
|
||||||
|
@ -48,7 +50,7 @@ where
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
mut self: Pin<&mut Self>,
|
mut self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
loop {
|
loop {
|
||||||
let stream = self.as_mut().project().stream;
|
let stream = self.as_mut().project().stream;
|
||||||
|
|
||||||
|
|
|
@ -202,11 +202,13 @@ where
|
||||||
/// Finish service configuration and create a HTTP service for HTTP/2 protocol.
|
/// Finish service configuration and create a HTTP service for HTTP/2 protocol.
|
||||||
pub fn h2<F, B>(self, service: F) -> H2Service<T, S, B>
|
pub fn h2<F, B>(self, service: F) -> H2Service<T, S, B>
|
||||||
where
|
where
|
||||||
B: MessageBody + 'static,
|
|
||||||
F: IntoServiceFactory<S, Request>,
|
F: IntoServiceFactory<S, Request>,
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
|
|
||||||
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
let cfg = ServiceConfig::new(
|
let cfg = ServiceConfig::new(
|
||||||
self.keep_alive,
|
self.keep_alive,
|
||||||
|
@ -223,11 +225,13 @@ where
|
||||||
/// Finish service configuration and create `HttpService` instance.
|
/// Finish service configuration and create `HttpService` instance.
|
||||||
pub fn finish<F, B>(self, service: F) -> HttpService<T, S, B, X, U>
|
pub fn finish<F, B>(self, service: F) -> HttpService<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
B: MessageBody + 'static,
|
|
||||||
F: IntoServiceFactory<S, Request>,
|
F: IntoServiceFactory<S, Request>,
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
|
|
||||||
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
let cfg = ServiceConfig::new(
|
let cfg = ServiceConfig::new(
|
||||||
self.keep_alive,
|
self.keep_alive,
|
||||||
|
|
|
@ -12,10 +12,10 @@ use bytes::Bytes;
|
||||||
use futures_core::future::LocalBoxFuture;
|
use futures_core::future::LocalBoxFuture;
|
||||||
use h2::client::SendRequest;
|
use h2::client::SendRequest;
|
||||||
|
|
||||||
use crate::body::MessageBody;
|
|
||||||
use crate::h1::ClientCodec;
|
use crate::h1::ClientCodec;
|
||||||
use crate::message::{RequestHeadType, ResponseHead};
|
use crate::message::{RequestHeadType, ResponseHead};
|
||||||
use crate::payload::Payload;
|
use crate::payload::Payload;
|
||||||
|
use crate::{body::MessageBody, Error};
|
||||||
|
|
||||||
use super::error::SendRequestError;
|
use super::error::SendRequestError;
|
||||||
use super::pool::Acquired;
|
use super::pool::Acquired;
|
||||||
|
@ -256,8 +256,9 @@ where
|
||||||
body: RB,
|
body: RB,
|
||||||
) -> LocalBoxFuture<'static, Result<(ResponseHead, Payload), SendRequestError>>
|
) -> LocalBoxFuture<'static, Result<(ResponseHead, Payload), SendRequestError>>
|
||||||
where
|
where
|
||||||
RB: MessageBody + 'static,
|
|
||||||
H: Into<RequestHeadType> + 'static,
|
H: Into<RequestHeadType> + 'static,
|
||||||
|
RB: MessageBody + 'static,
|
||||||
|
RB::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
match self {
|
match self {
|
||||||
|
|
|
@ -11,7 +11,6 @@ use bytes::{Bytes, BytesMut};
|
||||||
use futures_core::{ready, Stream};
|
use futures_core::{ready, Stream};
|
||||||
use futures_util::SinkExt as _;
|
use futures_util::SinkExt as _;
|
||||||
|
|
||||||
use crate::error::PayloadError;
|
|
||||||
use crate::h1;
|
use crate::h1;
|
||||||
use crate::http::{
|
use crate::http::{
|
||||||
header::{HeaderMap, IntoHeaderValue, EXPECT, HOST},
|
header::{HeaderMap, IntoHeaderValue, EXPECT, HOST},
|
||||||
|
@ -19,6 +18,7 @@ use crate::http::{
|
||||||
};
|
};
|
||||||
use crate::message::{RequestHeadType, ResponseHead};
|
use crate::message::{RequestHeadType, ResponseHead};
|
||||||
use crate::payload::Payload;
|
use crate::payload::Payload;
|
||||||
|
use crate::{error::PayloadError, Error};
|
||||||
|
|
||||||
use super::connection::{ConnectionIo, H1Connection};
|
use super::connection::{ConnectionIo, H1Connection};
|
||||||
use super::error::{ConnectError, SendRequestError};
|
use super::error::{ConnectError, SendRequestError};
|
||||||
|
@ -32,6 +32,7 @@ pub(crate) async fn send_request<Io, B>(
|
||||||
where
|
where
|
||||||
Io: ConnectionIo,
|
Io: ConnectionIo,
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
// set request host header
|
// set request host header
|
||||||
if !head.as_ref().headers.contains_key(HOST)
|
if !head.as_ref().headers.contains_key(HOST)
|
||||||
|
@ -154,6 +155,7 @@ pub(crate) async fn send_body<Io, B>(
|
||||||
where
|
where
|
||||||
Io: ConnectionIo,
|
Io: ConnectionIo,
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
actix_rt::pin!(body);
|
actix_rt::pin!(body);
|
||||||
|
|
||||||
|
@ -161,9 +163,10 @@ where
|
||||||
while !eof {
|
while !eof {
|
||||||
while !eof && !framed.as_ref().is_write_buf_full() {
|
while !eof && !framed.as_ref().is_write_buf_full() {
|
||||||
match poll_fn(|cx| body.as_mut().poll_next(cx)).await {
|
match poll_fn(|cx| body.as_mut().poll_next(cx)).await {
|
||||||
Some(result) => {
|
Some(Ok(chunk)) => {
|
||||||
framed.as_mut().write(h1::Message::Chunk(Some(result?)))?;
|
framed.as_mut().write(h1::Message::Chunk(Some(chunk)))?;
|
||||||
}
|
}
|
||||||
|
Some(Err(err)) => return Err(err.into().into()),
|
||||||
None => {
|
None => {
|
||||||
eof = true;
|
eof = true;
|
||||||
framed.as_mut().write(h1::Message::Chunk(None))?;
|
framed.as_mut().write(h1::Message::Chunk(None))?;
|
||||||
|
|
|
@ -9,14 +9,19 @@ use h2::{
|
||||||
use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, TRANSFER_ENCODING};
|
use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, TRANSFER_ENCODING};
|
||||||
use http::{request::Request, Method, Version};
|
use http::{request::Request, Method, Version};
|
||||||
|
|
||||||
use crate::body::{BodySize, MessageBody};
|
use crate::{
|
||||||
use crate::header::HeaderMap;
|
body::{BodySize, MessageBody},
|
||||||
use crate::message::{RequestHeadType, ResponseHead};
|
header::HeaderMap,
|
||||||
use crate::payload::Payload;
|
message::{RequestHeadType, ResponseHead},
|
||||||
|
payload::Payload,
|
||||||
|
Error,
|
||||||
|
};
|
||||||
|
|
||||||
use super::config::ConnectorConfig;
|
use super::{
|
||||||
use super::connection::{ConnectionIo, H2Connection};
|
config::ConnectorConfig,
|
||||||
use super::error::SendRequestError;
|
connection::{ConnectionIo, H2Connection},
|
||||||
|
error::SendRequestError,
|
||||||
|
};
|
||||||
|
|
||||||
pub(crate) async fn send_request<Io, B>(
|
pub(crate) async fn send_request<Io, B>(
|
||||||
mut io: H2Connection<Io>,
|
mut io: H2Connection<Io>,
|
||||||
|
@ -26,6 +31,7 @@ pub(crate) async fn send_request<Io, B>(
|
||||||
where
|
where
|
||||||
Io: ConnectionIo,
|
Io: ConnectionIo,
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
trace!("Sending client request: {:?} {:?}", head, body.size());
|
trace!("Sending client request: {:?} {:?}", head, body.size());
|
||||||
|
|
||||||
|
@ -125,10 +131,14 @@ where
|
||||||
Ok((head, payload))
|
Ok((head, payload))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_body<B: MessageBody>(
|
async fn send_body<B>(
|
||||||
body: B,
|
body: B,
|
||||||
mut send: SendStream<Bytes>,
|
mut send: SendStream<Bytes>,
|
||||||
) -> Result<(), SendRequestError> {
|
) -> Result<(), SendRequestError>
|
||||||
|
where
|
||||||
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
{
|
||||||
let mut buf = None;
|
let mut buf = None;
|
||||||
actix_rt::pin!(body);
|
actix_rt::pin!(body);
|
||||||
loop {
|
loop {
|
||||||
|
@ -138,7 +148,7 @@ async fn send_body<B: MessageBody>(
|
||||||
send.reserve_capacity(b.len());
|
send.reserve_capacity(b.len());
|
||||||
buf = Some(b);
|
buf = Some(b);
|
||||||
}
|
}
|
||||||
Some(Err(e)) => return Err(e.into()),
|
Some(Err(e)) => return Err(e.into().into()),
|
||||||
None => {
|
None => {
|
||||||
if let Err(e) = send.send_data(Bytes::new(), true) {
|
if let Err(e) = send.send_data(Bytes::new(), true) {
|
||||||
return Err(e.into());
|
return Err(e.into());
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
//! Stream encoders.
|
//! Stream encoders.
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
|
error::Error as StdError,
|
||||||
future::Future,
|
future::Future,
|
||||||
io::{self, Write as _},
|
io::{self, Write as _},
|
||||||
pin::Pin,
|
pin::Pin,
|
||||||
|
@ -10,12 +11,13 @@ use std::{
|
||||||
use actix_rt::task::{spawn_blocking, JoinHandle};
|
use actix_rt::task::{spawn_blocking, JoinHandle};
|
||||||
use brotli2::write::BrotliEncoder;
|
use brotli2::write::BrotliEncoder;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
|
use derive_more::Display;
|
||||||
use flate2::write::{GzEncoder, ZlibEncoder};
|
use flate2::write::{GzEncoder, ZlibEncoder};
|
||||||
use futures_core::ready;
|
use futures_core::ready;
|
||||||
use pin_project::pin_project;
|
use pin_project::pin_project;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
body::{Body, BodySize, MessageBody, ResponseBody},
|
body::{Body, BodySize, BoxAnyBody, MessageBody, ResponseBody},
|
||||||
http::{
|
http::{
|
||||||
header::{ContentEncoding, CONTENT_ENCODING},
|
header::{ContentEncoding, CONTENT_ENCODING},
|
||||||
HeaderValue, StatusCode,
|
HeaderValue, StatusCode,
|
||||||
|
@ -92,10 +94,16 @@ impl<B: MessageBody> Encoder<B> {
|
||||||
enum EncoderBody<B> {
|
enum EncoderBody<B> {
|
||||||
Bytes(Bytes),
|
Bytes(Bytes),
|
||||||
Stream(#[pin] B),
|
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 {
|
fn size(&self) -> BodySize {
|
||||||
match self {
|
match self {
|
||||||
EncoderBody::Bytes(ref b) => b.size(),
|
EncoderBody::Bytes(ref b) => b.size(),
|
||||||
|
@ -107,7 +115,7 @@ impl<B: MessageBody> MessageBody for EncoderBody<B> {
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
match self.project() {
|
match self.project() {
|
||||||
EncoderBodyProj::Bytes(b) => {
|
EncoderBodyProj::Bytes(b) => {
|
||||||
if b.is_empty() {
|
if b.is_empty() {
|
||||||
|
@ -116,13 +124,32 @@ impl<B: MessageBody> MessageBody for EncoderBody<B> {
|
||||||
Poll::Ready(Some(Ok(std::mem::take(b))))
|
Poll::Ready(Some(Ok(std::mem::take(b))))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
EncoderBodyProj::Stream(b) => b.poll_next(cx),
|
// TODO: MSRV 1.51: poll_map_err
|
||||||
EncoderBodyProj::BoxedStream(ref mut b) => b.as_mut().poll_next(cx),
|
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 {
|
fn size(&self) -> BodySize {
|
||||||
if self.encoder.is_none() {
|
if self.encoder.is_none() {
|
||||||
self.body.size()
|
self.body.size()
|
||||||
|
@ -134,7 +161,7 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
let mut this = self.project();
|
let mut this = self.project();
|
||||||
loop {
|
loop {
|
||||||
if *this.eof {
|
if *this.eof {
|
||||||
|
@ -142,8 +169,9 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(ref mut fut) = this.fut {
|
if let Some(ref mut fut) = this.fut {
|
||||||
let mut encoder =
|
let mut encoder = ready!(Pin::new(fut).poll(cx))
|
||||||
ready!(Pin::new(fut).poll(cx)).map_err(|_| BlockingError)??;
|
.map_err(|_| EncoderError::Blocking(BlockingError))?
|
||||||
|
.map_err(EncoderError::Io)?;
|
||||||
|
|
||||||
let chunk = encoder.take();
|
let chunk = encoder.take();
|
||||||
*this.encoder = Some(encoder);
|
*this.encoder = Some(encoder);
|
||||||
|
@ -162,7 +190,7 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
|
||||||
Some(Ok(chunk)) => {
|
Some(Ok(chunk)) => {
|
||||||
if let Some(mut encoder) = this.encoder.take() {
|
if let Some(mut encoder) = this.encoder.take() {
|
||||||
if chunk.len() < MAX_CHUNK_SIZE_ENCODE_IN_PLACE {
|
if chunk.len() < MAX_CHUNK_SIZE_ENCODE_IN_PLACE {
|
||||||
encoder.write(&chunk)?;
|
encoder.write(&chunk).map_err(EncoderError::Io)?;
|
||||||
let chunk = encoder.take();
|
let chunk = encoder.take();
|
||||||
*this.encoder = Some(encoder);
|
*this.encoder = Some(encoder);
|
||||||
|
|
||||||
|
@ -182,7 +210,7 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
|
||||||
|
|
||||||
None => {
|
None => {
|
||||||
if let Some(encoder) = this.encoder.take() {
|
if let Some(encoder) = this.encoder.take() {
|
||||||
let chunk = encoder.finish()?;
|
let chunk = encoder.finish().map_err(EncoderError::Io)?;
|
||||||
if chunk.is_empty() {
|
if chunk.is_empty() {
|
||||||
return Poll::Ready(None);
|
return Poll::Ready(None);
|
||||||
} else {
|
} 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(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
cell::RefCell,
|
cell::RefCell,
|
||||||
|
error::Error as StdError,
|
||||||
fmt,
|
fmt,
|
||||||
io::{self, Write as _},
|
io::{self, Write as _},
|
||||||
str::Utf8Error,
|
str::Utf8Error,
|
||||||
|
@ -105,8 +106,7 @@ impl From<()> for Error {
|
||||||
|
|
||||||
impl From<std::convert::Infallible> for Error {
|
impl From<std::convert::Infallible> for Error {
|
||||||
fn from(_: std::convert::Infallible) -> Self {
|
fn from(_: std::convert::Infallible) -> Self {
|
||||||
// `std::convert::Infallible` indicates an error
|
// hint that an error that will never happen
|
||||||
// that will never happen
|
|
||||||
unreachable!()
|
unreachable!()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -145,6 +145,8 @@ impl From<ResponseBuilder> for Error {
|
||||||
#[display(fmt = "Unknown Error")]
|
#[display(fmt = "Unknown Error")]
|
||||||
struct UnitError;
|
struct UnitError;
|
||||||
|
|
||||||
|
impl ResponseError for Box<dyn StdError + 'static> {}
|
||||||
|
|
||||||
/// Returns [`StatusCode::INTERNAL_SERVER_ERROR`] for [`UnitError`].
|
/// Returns [`StatusCode::INTERNAL_SERVER_ERROR`] for [`UnitError`].
|
||||||
impl ResponseError for UnitError {}
|
impl ResponseError for UnitError {}
|
||||||
|
|
||||||
|
|
|
@ -56,9 +56,13 @@ pub struct Dispatcher<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
|
@ -74,9 +78,13 @@ enum DispatcherState<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
|
@ -89,9 +97,13 @@ struct InnerDispatcher<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
|
@ -127,7 +139,9 @@ enum State<S, B, X>
|
||||||
where
|
where
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
None,
|
None,
|
||||||
ExpectCall(#[pin] X::Future),
|
ExpectCall(#[pin] X::Future),
|
||||||
|
@ -138,8 +152,11 @@ where
|
||||||
impl<S, B, X> State<S, B, X>
|
impl<S, B, X> State<S, B, X>
|
||||||
where
|
where
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
fn is_empty(&self) -> bool {
|
fn is_empty(&self) -> bool {
|
||||||
matches!(self, State::None)
|
matches!(self, State::None)
|
||||||
|
@ -155,12 +172,17 @@ enum PollResponse {
|
||||||
impl<T, S, B, X, U> Dispatcher<T, S, B, X, U>
|
impl<T, S, B, X, U> Dispatcher<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: ActixStream,
|
T: ActixStream,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
|
@ -211,12 +233,17 @@ where
|
||||||
impl<T, S, B, X, U> InnerDispatcher<T, S, B, X, U>
|
impl<T, S, B, X, U> InnerDispatcher<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: ActixStream,
|
T: ActixStream,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
|
@ -868,12 +895,17 @@ where
|
||||||
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
|
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: ActixStream,
|
T: ActixStream,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
|
|
|
@ -64,11 +64,15 @@ where
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||||
X::Future: 'static,
|
X::Future: 'static,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
X::InitError: fmt::Debug,
|
X::InitError: fmt::Debug,
|
||||||
|
|
||||||
U: ServiceFactory<(Request, Framed<TcpStream, Codec>), Config = (), Response = ()>,
|
U: ServiceFactory<(Request, Framed<TcpStream, Codec>), Config = (), Response = ()>,
|
||||||
U::Future: 'static,
|
U::Future: 'static,
|
||||||
U::Error: fmt::Display + Into<Error>,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
|
@ -109,11 +113,15 @@ mod openssl {
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||||
X::Future: 'static,
|
X::Future: 'static,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
X::InitError: fmt::Debug,
|
X::InitError: fmt::Debug,
|
||||||
|
|
||||||
U: ServiceFactory<
|
U: ServiceFactory<
|
||||||
(Request, Framed<TlsStream<TcpStream>, Codec>),
|
(Request, Framed<TlsStream<TcpStream>, Codec>),
|
||||||
Config = (),
|
Config = (),
|
||||||
|
@ -165,11 +173,15 @@ mod rustls {
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||||
X::Future: 'static,
|
X::Future: 'static,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
X::InitError: fmt::Debug,
|
X::InitError: fmt::Debug,
|
||||||
|
|
||||||
U: ServiceFactory<
|
U: ServiceFactory<
|
||||||
(Request, Framed<TlsStream<TcpStream>, Codec>),
|
(Request, Framed<TlsStream<TcpStream>, Codec>),
|
||||||
Config = (),
|
Config = (),
|
||||||
|
@ -253,16 +265,21 @@ impl<T, S, B, X, U> ServiceFactory<(T, Option<net::SocketAddr>)>
|
||||||
for H1Service<T, S, B, X, U>
|
for H1Service<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: ActixStream + 'static,
|
T: ActixStream + 'static,
|
||||||
|
|
||||||
S: ServiceFactory<Request, Config = ()>,
|
S: ServiceFactory<Request, Config = ()>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||||
X::Future: 'static,
|
X::Future: 'static,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
X::InitError: fmt::Debug,
|
X::InitError: fmt::Debug,
|
||||||
|
|
||||||
U: ServiceFactory<(Request, Framed<T, Codec>), Config = (), Response = ()>,
|
U: ServiceFactory<(Request, Framed<T, Codec>), Config = (), Response = ()>,
|
||||||
U::Future: 'static,
|
U::Future: 'static,
|
||||||
U::Error: fmt::Display + Into<Error>,
|
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>
|
for HttpServiceHandler<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: ActixStream,
|
T: ActixStream,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display + Into<Error>,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
{
|
{
|
||||||
|
|
|
@ -22,6 +22,7 @@ pub struct SendResponse<T, B> {
|
||||||
impl<T, B> SendResponse<T, B>
|
impl<T, B> SendResponse<T, B>
|
||||||
where
|
where
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
pub fn new(framed: Framed<T, Codec>, response: Response<B>) -> Self {
|
pub fn new(framed: Framed<T, Codec>, response: Response<B>) -> Self {
|
||||||
let (res, body) = response.into_parts();
|
let (res, body) = response.into_parts();
|
||||||
|
@ -38,6 +39,7 @@ impl<T, B> Future for SendResponse<T, B>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
T: AsyncRead + AsyncWrite + Unpin,
|
||||||
B: MessageBody + Unpin,
|
B: MessageBody + Unpin,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
type Output = Result<Framed<T, Codec>, Error>;
|
type Output = Result<Framed<T, Codec>, Error>;
|
||||||
|
|
||||||
|
|
|
@ -69,11 +69,14 @@ where
|
||||||
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
|
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
T: AsyncRead + AsyncWrite + Unpin,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
type Output = Result<(), DispatchError>;
|
type Output = Result<(), DispatchError>;
|
||||||
|
|
||||||
|
@ -140,7 +143,9 @@ where
|
||||||
F: Future<Output = Result<I, E>>,
|
F: Future<Output = Result<I, E>>,
|
||||||
E: Into<Error>,
|
E: Into<Error>,
|
||||||
I: Into<Response<B>>,
|
I: Into<Response<B>>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
fn prepare_response(
|
fn prepare_response(
|
||||||
&self,
|
&self,
|
||||||
|
@ -216,7 +221,9 @@ where
|
||||||
F: Future<Output = Result<I, E>>,
|
F: Future<Output = Result<I, E>>,
|
||||||
E: Into<Error>,
|
E: Into<Error>,
|
||||||
I: Into<Response<B>>,
|
I: Into<Response<B>>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
type Output = ();
|
type Output = ();
|
||||||
|
|
||||||
|
|
|
@ -40,7 +40,9 @@ where
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
/// Create new `H2Service` instance with config.
|
/// Create new `H2Service` instance with config.
|
||||||
pub(crate) fn with_config<F: IntoServiceFactory<S, Request>>(
|
pub(crate) fn with_config<F: IntoServiceFactory<S, Request>>(
|
||||||
|
@ -69,7 +71,9 @@ where
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
/// Create plain TCP based service
|
/// Create plain TCP based service
|
||||||
pub fn tcp(
|
pub fn tcp(
|
||||||
|
@ -106,7 +110,9 @@ mod openssl {
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
/// Create OpenSSL based service
|
/// Create OpenSSL based service
|
||||||
pub fn openssl(
|
pub fn openssl(
|
||||||
|
@ -150,7 +156,9 @@ mod rustls {
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
/// Create Rustls based service
|
/// Create Rustls based service
|
||||||
pub fn rustls(
|
pub fn rustls(
|
||||||
|
@ -185,12 +193,15 @@ mod rustls {
|
||||||
impl<T, S, B> ServiceFactory<(T, Option<net::SocketAddr>)> for H2Service<T, S, B>
|
impl<T, S, B> ServiceFactory<(T, Option<net::SocketAddr>)> for H2Service<T, S, B>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
||||||
|
|
||||||
S: ServiceFactory<Request, Config = ()>,
|
S: ServiceFactory<Request, Config = ()>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = DispatchError;
|
type Error = DispatchError;
|
||||||
|
@ -252,6 +263,7 @@ where
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = DispatchError;
|
type Error = DispatchError;
|
||||||
|
@ -316,6 +328,7 @@ where
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
type Output = Result<(), DispatchError>;
|
type Output = Result<(), DispatchError>;
|
||||||
|
|
||||||
|
|
|
@ -15,8 +15,15 @@ macro_rules! downcast_get_type_id {
|
||||||
/// making it impossible for safe code to construct outside of
|
/// making it impossible for safe code to construct outside of
|
||||||
/// this module. This ensures that safe code cannot violate
|
/// this module. This ensures that safe code cannot violate
|
||||||
/// type-safety by implementing this method.
|
/// type-safety by implementing this method.
|
||||||
|
///
|
||||||
|
/// We also take `PrivateHelper` as a parameter, to ensure that
|
||||||
|
/// safe code cannot obtain a `PrivateHelper` instance by
|
||||||
|
/// delegating to an existing implementation of `__private_get_type_id__`
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
fn __private_get_type_id__(&self) -> (std::any::TypeId, PrivateHelper)
|
fn __private_get_type_id__(
|
||||||
|
&self,
|
||||||
|
_: PrivateHelper,
|
||||||
|
) -> (std::any::TypeId, PrivateHelper)
|
||||||
where
|
where
|
||||||
Self: 'static,
|
Self: 'static,
|
||||||
{
|
{
|
||||||
|
@ -39,7 +46,9 @@ macro_rules! downcast {
|
||||||
impl dyn $name + 'static {
|
impl dyn $name + 'static {
|
||||||
/// Downcasts generic body to a specific type.
|
/// Downcasts generic body to a specific type.
|
||||||
pub fn downcast_ref<T: $name + 'static>(&self) -> Option<&T> {
|
pub fn downcast_ref<T: $name + 'static>(&self) -> Option<&T> {
|
||||||
if self.__private_get_type_id__().0 == std::any::TypeId::of::<T>() {
|
if self.__private_get_type_id__(PrivateHelper(())).0
|
||||||
|
== std::any::TypeId::of::<T>()
|
||||||
|
{
|
||||||
// SAFETY: external crates cannot override the default
|
// SAFETY: external crates cannot override the default
|
||||||
// implementation of `__private_get_type_id__`, since
|
// implementation of `__private_get_type_id__`, since
|
||||||
// it requires returning a private type. We can therefore
|
// it requires returning a private type. We can therefore
|
||||||
|
@ -53,7 +62,9 @@ macro_rules! downcast {
|
||||||
|
|
||||||
/// Downcasts a generic body to a mutable specific type.
|
/// Downcasts a generic body to a mutable specific type.
|
||||||
pub fn downcast_mut<T: $name + 'static>(&mut self) -> Option<&mut T> {
|
pub fn downcast_mut<T: $name + 'static>(&mut self) -> Option<&mut T> {
|
||||||
if self.__private_get_type_id__().0 == std::any::TypeId::of::<T>() {
|
if self.__private_get_type_id__(PrivateHelper(())).0
|
||||||
|
== std::any::TypeId::of::<T>()
|
||||||
|
{
|
||||||
// SAFETY: external crates cannot override the default
|
// SAFETY: external crates cannot override the default
|
||||||
// implementation of `__private_get_type_id__`, since
|
// implementation of `__private_get_type_id__`, since
|
||||||
// it requires returning a private type. We can therefore
|
// it requires returning a private type. We can therefore
|
||||||
|
|
|
@ -78,7 +78,7 @@ impl Response<Body> {
|
||||||
pub fn from_error(error: Error) -> Response<Body> {
|
pub fn from_error(error: Error) -> Response<Body> {
|
||||||
let mut resp = error.as_response_error().error_response();
|
let mut resp = error.as_response_error().error_response();
|
||||||
if resp.head.status == StatusCode::INTERNAL_SERVER_ERROR {
|
if resp.head.status == StatusCode::INTERNAL_SERVER_ERROR {
|
||||||
error!("Internal Server Error: {:?}", error);
|
debug!("Internal Server Error: {:?}", error);
|
||||||
}
|
}
|
||||||
resp.error = Some(error);
|
resp.error = Some(error);
|
||||||
resp
|
resp
|
||||||
|
@ -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 {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
let res = writeln!(
|
let res = writeln!(
|
||||||
f,
|
f,
|
||||||
|
|
|
@ -59,6 +59,7 @@ where
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
/// Create new `HttpService` instance.
|
/// Create new `HttpService` instance.
|
||||||
pub fn new<F: IntoServiceFactory<S, Request>>(service: F) -> Self {
|
pub fn new<F: IntoServiceFactory<S, Request>>(service: F) -> Self {
|
||||||
|
@ -157,6 +158,7 @@ where
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||||
X::Future: 'static,
|
X::Future: 'static,
|
||||||
|
@ -208,6 +210,7 @@ mod openssl {
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||||
X::Future: 'static,
|
X::Future: 'static,
|
||||||
|
@ -275,6 +278,7 @@ mod rustls {
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||||
X::Future: 'static,
|
X::Future: 'static,
|
||||||
|
@ -338,6 +342,7 @@ where
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||||
X::Future: 'static,
|
X::Future: 'static,
|
||||||
|
@ -464,13 +469,18 @@ impl<T, S, B, X, U> Service<(T, Protocol, Option<net::SocketAddr>)>
|
||||||
for HttpServiceHandler<T, S, B, X, U>
|
for HttpServiceHandler<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: ActixStream,
|
T: ActixStream,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display + Into<Error>,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
{
|
{
|
||||||
|
@ -521,13 +531,18 @@ where
|
||||||
#[pin_project(project = StateProj)]
|
#[pin_project(project = StateProj)]
|
||||||
enum State<T, S, B, X, U>
|
enum State<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
|
T: ActixStream,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
T: ActixStream,
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
|
@ -548,13 +563,18 @@ where
|
||||||
pub struct HttpServiceHandlerResponse<T, S, B, X, U>
|
pub struct HttpServiceHandlerResponse<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: ActixStream,
|
T: ActixStream,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
B: MessageBody + 'static,
|
|
||||||
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
|
@ -565,13 +585,18 @@ where
|
||||||
impl<T, S, B, X, U> Future for HttpServiceHandlerResponse<T, S, B, X, U>
|
impl<T, S, B, X, U> Future for HttpServiceHandlerResponse<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: ActixStream,
|
T: ActixStream,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
B: MessageBody,
|
|
||||||
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
|
|
|
@ -86,6 +86,7 @@ where
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
start_with(TestServerConfig::default(), factory)
|
start_with(TestServerConfig::default(), factory)
|
||||||
}
|
}
|
||||||
|
@ -125,6 +126,7 @@ where
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
let (tx, rx) = mpsc::channel();
|
let (tx, rx) = mpsc::channel();
|
||||||
|
|
||||||
|
|
|
@ -26,6 +26,8 @@
|
||||||
//! ```
|
//! ```
|
||||||
#![allow(non_snake_case)]
|
#![allow(non_snake_case)]
|
||||||
use std::convert::TryFrom;
|
use std::convert::TryFrom;
|
||||||
|
use std::ops::Deref;
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_http::http::{self, header, uri::Uri};
|
use actix_http::http::{self, header, uri::Uri};
|
||||||
use actix_http::RequestHead;
|
use actix_http::RequestHead;
|
||||||
|
@ -40,6 +42,12 @@ pub trait Guard {
|
||||||
fn check(&self, request: &RequestHead) -> bool;
|
fn check(&self, request: &RequestHead) -> bool;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Guard for Rc<dyn Guard> {
|
||||||
|
fn check(&self, request: &RequestHead) -> bool {
|
||||||
|
self.deref().check(request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Create guard object for supplied function.
|
/// Create guard object for supplied function.
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
|
|
|
@ -24,14 +24,11 @@ crate::__define_common_header! {
|
||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// use language_tags::langtag;
|
|
||||||
/// use actix_web::HttpResponse;
|
/// use actix_web::HttpResponse;
|
||||||
/// use actix_web::http::header::{AcceptLanguage, LanguageTag, qitem};
|
/// use actix_web::http::header::{AcceptLanguage, LanguageTag, qitem};
|
||||||
///
|
///
|
||||||
/// let mut builder = HttpResponse::Ok();
|
/// let mut builder = HttpResponse::Ok();
|
||||||
/// let mut langtag: LanguageTag = Default::default();
|
/// let langtag = LanguageTag::parse("en-US").unwrap();
|
||||||
/// langtag.language = Some("en".to_owned());
|
|
||||||
/// langtag.region = Some("US".to_owned());
|
|
||||||
/// builder.insert_header(
|
/// builder.insert_header(
|
||||||
/// AcceptLanguage(vec![
|
/// AcceptLanguage(vec![
|
||||||
/// qitem(langtag),
|
/// qitem(langtag),
|
||||||
|
@ -40,16 +37,15 @@ crate::__define_common_header! {
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// use language_tags::langtag;
|
|
||||||
/// use actix_web::HttpResponse;
|
/// use actix_web::HttpResponse;
|
||||||
/// use actix_web::http::header::{AcceptLanguage, QualityItem, q, qitem};
|
/// use actix_web::http::header::{AcceptLanguage, LanguageTag, QualityItem, q, qitem};
|
||||||
///
|
///
|
||||||
/// let mut builder = HttpResponse::Ok();
|
/// let mut builder = HttpResponse::Ok();
|
||||||
/// builder.insert_header(
|
/// builder.insert_header(
|
||||||
/// AcceptLanguage(vec![
|
/// AcceptLanguage(vec![
|
||||||
/// qitem(langtag!(da)),
|
/// qitem(LanguageTag::parse("da").unwrap()),
|
||||||
/// QualityItem::new(langtag!(en;;;GB), q(800)),
|
/// QualityItem::new(LanguageTag::parse("en-GB").unwrap(), q(800)),
|
||||||
/// QualityItem::new(langtag!(en), q(700)),
|
/// QualityItem::new(LanguageTag::parse("en").unwrap(), q(700)),
|
||||||
/// ])
|
/// ])
|
||||||
/// );
|
/// );
|
||||||
/// ```
|
/// ```
|
||||||
|
|
|
@ -24,28 +24,26 @@ crate::__define_common_header! {
|
||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// use language_tags::langtag;
|
|
||||||
/// use actix_web::HttpResponse;
|
/// use actix_web::HttpResponse;
|
||||||
/// use actix_web::http::header::{ContentLanguage, qitem};
|
/// use actix_web::http::header::{ContentLanguage, LanguageTag, qitem};
|
||||||
///
|
///
|
||||||
/// let mut builder = HttpResponse::Ok();
|
/// let mut builder = HttpResponse::Ok();
|
||||||
/// builder.insert_header(
|
/// builder.insert_header(
|
||||||
/// ContentLanguage(vec![
|
/// ContentLanguage(vec![
|
||||||
/// qitem(langtag!(en)),
|
/// qitem(LanguageTag::parse("en").unwrap()),
|
||||||
/// ])
|
/// ])
|
||||||
/// );
|
/// );
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// use language_tags::langtag;
|
|
||||||
/// use actix_web::HttpResponse;
|
/// use actix_web::HttpResponse;
|
||||||
/// use actix_web::http::header::{ContentLanguage, qitem};
|
/// use actix_web::http::header::{ContentLanguage, LanguageTag, qitem};
|
||||||
///
|
///
|
||||||
/// let mut builder = HttpResponse::Ok();
|
/// let mut builder = HttpResponse::Ok();
|
||||||
/// builder.insert_header(
|
/// builder.insert_header(
|
||||||
/// ContentLanguage(vec![
|
/// ContentLanguage(vec![
|
||||||
/// qitem(langtag!(da)),
|
/// qitem(LanguageTag::parse("da").unwrap()),
|
||||||
/// qitem(langtag!(en;;;GB)),
|
/// qitem(LanguageTag::parse("en-GB").unwrap()),
|
||||||
/// ])
|
/// ])
|
||||||
/// );
|
/// );
|
||||||
/// ```
|
/// ```
|
||||||
|
|
|
@ -113,7 +113,11 @@ pub trait MapServiceResponseBody {
|
||||||
fn map_body(self) -> ServiceResponse;
|
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 {
|
fn map_body(self) -> ServiceResponse {
|
||||||
self.map_body(|_, body| ResponseBody::Other(Body::from_message(body)))
|
self.map_body(|_, body| ResponseBody::Other(Body::from_message(body)))
|
||||||
}
|
}
|
||||||
|
|
|
@ -22,10 +22,9 @@ use time::OffsetDateTime;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
dev::{BodySize, MessageBody, ResponseBody},
|
dev::{BodySize, MessageBody, ResponseBody},
|
||||||
error::{Error, Result},
|
|
||||||
http::{HeaderName, StatusCode},
|
http::{HeaderName, StatusCode},
|
||||||
service::{ServiceRequest, ServiceResponse},
|
service::{ServiceRequest, ServiceResponse},
|
||||||
HttpResponse,
|
Error, HttpResponse, Result,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Middleware for logging request and response summaries to the terminal.
|
/// 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 {
|
fn size(&self) -> BodySize {
|
||||||
self.body.size()
|
self.body.size()
|
||||||
}
|
}
|
||||||
|
@ -335,7 +340,7 @@ impl<B: MessageBody> MessageBody for StreamLog<B> {
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
let this = self.project();
|
let this = self.project();
|
||||||
match this.body.poll_next(cx) {
|
match this.body.poll_next(cx) {
|
||||||
Poll::Ready(Some(Ok(chunk))) => {
|
Poll::Ready(Some(Ok(chunk))) => {
|
||||||
|
|
|
@ -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 {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
f.debug_struct("HttpResponse")
|
f.debug_struct("HttpResponse")
|
||||||
.field("error", &self.error)
|
.field("error", &self.error)
|
||||||
|
|
|
@ -81,6 +81,7 @@ where
|
||||||
S::Service: 'static,
|
S::Service: 'static,
|
||||||
// S::Service: 'static,
|
// S::Service: 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
/// Create new HTTP server with application factory
|
/// Create new HTTP server with application factory
|
||||||
pub fn new(factory: F) -> Self {
|
pub fn new(factory: F) -> Self {
|
||||||
|
|
|
@ -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 {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
let res = writeln!(
|
let res = writeln!(
|
||||||
f,
|
f,
|
||||||
|
|
|
@ -151,6 +151,7 @@ pub async fn read_response<S, B>(app: &S, req: Request) -> Bytes
|
||||||
where
|
where
|
||||||
S: Service<Request, Response = ServiceResponse<B>, Error = Error>,
|
S: Service<Request, Response = ServiceResponse<B>, Error = Error>,
|
||||||
B: MessageBody + Unpin,
|
B: MessageBody + Unpin,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
let mut resp = app
|
let mut resp = app
|
||||||
.call(req)
|
.call(req)
|
||||||
|
@ -196,6 +197,7 @@ where
|
||||||
pub async fn read_body<B>(mut res: ServiceResponse<B>) -> Bytes
|
pub async fn read_body<B>(mut res: ServiceResponse<B>) -> Bytes
|
||||||
where
|
where
|
||||||
B: MessageBody + Unpin,
|
B: MessageBody + Unpin,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
let mut body = res.take_body();
|
let mut body = res.take_body();
|
||||||
let mut bytes = BytesMut::new();
|
let mut bytes = BytesMut::new();
|
||||||
|
@ -245,6 +247,7 @@ where
|
||||||
pub async fn read_body_json<T, B>(res: ServiceResponse<B>) -> T
|
pub async fn read_body_json<T, B>(res: ServiceResponse<B>) -> T
|
||||||
where
|
where
|
||||||
B: MessageBody + Unpin,
|
B: MessageBody + Unpin,
|
||||||
|
B::Error: Into<Error>,
|
||||||
T: DeserializeOwned,
|
T: DeserializeOwned,
|
||||||
{
|
{
|
||||||
let body = read_body(res).await;
|
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
|
where
|
||||||
S: Service<Request, Response = ServiceResponse<B>, Error = Error>,
|
S: Service<Request, Response = ServiceResponse<B>, Error = Error>,
|
||||||
B: MessageBody + Unpin,
|
B: MessageBody + Unpin,
|
||||||
|
B::Error: Into<Error>,
|
||||||
T: DeserializeOwned,
|
T: DeserializeOwned,
|
||||||
{
|
{
|
||||||
let body = read_response(app, req).await;
|
let body = read_response(app, req).await;
|
||||||
|
|
|
@ -1,8 +1,14 @@
|
||||||
//! For either helper, see [`Either`].
|
//! For either helper, see [`Either`].
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
future::Future,
|
||||||
|
mem,
|
||||||
|
pin::Pin,
|
||||||
|
task::{Context, Poll},
|
||||||
|
};
|
||||||
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures_core::future::LocalBoxFuture;
|
use futures_core::ready;
|
||||||
use futures_util::{FutureExt as _, TryFutureExt as _};
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
dev,
|
dev,
|
||||||
|
@ -180,41 +186,111 @@ where
|
||||||
R: FromRequest + 'static,
|
R: FromRequest + 'static,
|
||||||
{
|
{
|
||||||
type Error = EitherExtractError<L::Error, R::Error>;
|
type Error = EitherExtractError<L::Error, R::Error>;
|
||||||
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
|
type Future = EitherExtractFut<L, R>;
|
||||||
type Config = ();
|
type Config = ();
|
||||||
|
|
||||||
fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
|
fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
|
||||||
let req2 = req.clone();
|
EitherExtractFut {
|
||||||
|
req: req.clone(),
|
||||||
Bytes::from_request(req, payload)
|
state: EitherExtractState::Bytes {
|
||||||
.map_err(EitherExtractError::Bytes)
|
bytes: Bytes::from_request(req, payload),
|
||||||
.and_then(|bytes| bytes_to_l_or_r(req2, bytes))
|
},
|
||||||
.boxed_local()
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn bytes_to_l_or_r<L, R>(
|
#[pin_project::pin_project]
|
||||||
req: HttpRequest,
|
pub struct EitherExtractFut<L, R>
|
||||||
bytes: Bytes,
|
|
||||||
) -> Result<Either<L, R>, EitherExtractError<L::Error, R::Error>>
|
|
||||||
where
|
where
|
||||||
L: FromRequest + 'static,
|
R: FromRequest,
|
||||||
R: FromRequest + 'static,
|
L: FromRequest,
|
||||||
{
|
{
|
||||||
let fallback = bytes.clone();
|
req: HttpRequest,
|
||||||
let a_err;
|
#[pin]
|
||||||
|
state: EitherExtractState<L, R>,
|
||||||
|
}
|
||||||
|
|
||||||
let mut pl = payload_from_bytes(bytes);
|
#[pin_project::pin_project(project = EitherExtractProj)]
|
||||||
match L::from_request(&req, &mut pl).await {
|
pub enum EitherExtractState<L, R>
|
||||||
Ok(a_data) => return Ok(Either::Left(a_data)),
|
where
|
||||||
// store A's error for returning if B also fails
|
L: FromRequest,
|
||||||
Err(err) => a_err = err,
|
R: FromRequest,
|
||||||
};
|
{
|
||||||
|
Bytes {
|
||||||
|
#[pin]
|
||||||
|
bytes: <Bytes as FromRequest>::Future,
|
||||||
|
},
|
||||||
|
Left {
|
||||||
|
#[pin]
|
||||||
|
left: L::Future,
|
||||||
|
fallback: Bytes,
|
||||||
|
},
|
||||||
|
Right {
|
||||||
|
#[pin]
|
||||||
|
right: R::Future,
|
||||||
|
left_err: Option<L::Error>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
let mut pl = payload_from_bytes(fallback);
|
impl<R, RF, RE, L, LF, LE> Future for EitherExtractFut<L, R>
|
||||||
match R::from_request(&req, &mut pl).await {
|
where
|
||||||
Ok(b_data) => return Ok(Either::Right(b_data)),
|
L: FromRequest<Future = LF, Error = LE>,
|
||||||
Err(b_err) => Err(EitherExtractError::Extract(a_err, b_err)),
|
R: FromRequest<Future = RF, Error = RE>,
|
||||||
|
LF: Future<Output = Result<L, LE>> + 'static,
|
||||||
|
RF: Future<Output = Result<R, RE>> + 'static,
|
||||||
|
LE: Into<Error>,
|
||||||
|
RE: Into<Error>,
|
||||||
|
{
|
||||||
|
type Output = Result<Either<L, R>, EitherExtractError<LE, RE>>;
|
||||||
|
|
||||||
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
let mut this = self.project();
|
||||||
|
let ready = loop {
|
||||||
|
let next = match this.state.as_mut().project() {
|
||||||
|
EitherExtractProj::Bytes { bytes } => {
|
||||||
|
let res = ready!(bytes.poll(cx));
|
||||||
|
match res {
|
||||||
|
Ok(bytes) => {
|
||||||
|
let fallback = bytes.clone();
|
||||||
|
let left =
|
||||||
|
L::from_request(&this.req, &mut payload_from_bytes(bytes));
|
||||||
|
EitherExtractState::Left { left, fallback }
|
||||||
|
}
|
||||||
|
Err(err) => break Err(EitherExtractError::Bytes(err)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EitherExtractProj::Left { left, fallback } => {
|
||||||
|
let res = ready!(left.poll(cx));
|
||||||
|
match res {
|
||||||
|
Ok(extracted) => break Ok(Either::Left(extracted)),
|
||||||
|
Err(left_err) => {
|
||||||
|
let right = R::from_request(
|
||||||
|
&this.req,
|
||||||
|
&mut payload_from_bytes(mem::take(fallback)),
|
||||||
|
);
|
||||||
|
EitherExtractState::Right {
|
||||||
|
left_err: Some(left_err),
|
||||||
|
right,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EitherExtractProj::Right { right, left_err } => {
|
||||||
|
let res = ready!(right.poll(cx));
|
||||||
|
match res {
|
||||||
|
Ok(data) => break Ok(Either::Right(data)),
|
||||||
|
Err(err) => {
|
||||||
|
break Err(EitherExtractError::Extract(
|
||||||
|
left_err.take().unwrap(),
|
||||||
|
err,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
this.state.set(next);
|
||||||
|
};
|
||||||
|
Poll::Ready(ready)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -12,7 +12,7 @@ use std::{
|
||||||
use actix_http::Payload;
|
use actix_http::Payload;
|
||||||
use bytes::BytesMut;
|
use bytes::BytesMut;
|
||||||
use encoding_rs::{Encoding, UTF_8};
|
use encoding_rs::{Encoding, UTF_8};
|
||||||
use futures_core::future::LocalBoxFuture;
|
use futures_core::{future::LocalBoxFuture, ready};
|
||||||
use futures_util::{FutureExt as _, StreamExt as _};
|
use futures_util::{FutureExt as _, StreamExt as _};
|
||||||
use serde::{de::DeserializeOwned, Serialize};
|
use serde::{de::DeserializeOwned, Serialize};
|
||||||
|
|
||||||
|
@ -123,11 +123,10 @@ where
|
||||||
{
|
{
|
||||||
type Config = FormConfig;
|
type Config = FormConfig;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Future = LocalBoxFuture<'static, Result<Self, Error>>;
|
type Future = FormExtractFut<T>;
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
||||||
let req2 = req.clone();
|
|
||||||
let (limit, err_handler) = req
|
let (limit, err_handler) = req
|
||||||
.app_data::<Self::Config>()
|
.app_data::<Self::Config>()
|
||||||
.or_else(|| {
|
.or_else(|| {
|
||||||
|
@ -137,16 +136,42 @@ where
|
||||||
.map(|c| (c.limit, c.err_handler.clone()))
|
.map(|c| (c.limit, c.err_handler.clone()))
|
||||||
.unwrap_or((16384, None));
|
.unwrap_or((16384, None));
|
||||||
|
|
||||||
UrlEncoded::new(req, payload)
|
FormExtractFut {
|
||||||
.limit(limit)
|
fut: UrlEncoded::new(req, payload).limit(limit),
|
||||||
.map(move |res| match res {
|
req: req.clone(),
|
||||||
Err(err) => match err_handler {
|
err_handler,
|
||||||
Some(err_handler) => Err((err_handler)(err, &req2)),
|
}
|
||||||
None => Err(err.into()),
|
}
|
||||||
},
|
}
|
||||||
Ok(item) => Ok(Form(item)),
|
|
||||||
})
|
type FormErrHandler = Option<Rc<dyn Fn(UrlencodedError, &HttpRequest) -> Error>>;
|
||||||
.boxed_local()
|
|
||||||
|
pub struct FormExtractFut<T> {
|
||||||
|
fut: UrlEncoded<T>,
|
||||||
|
err_handler: FormErrHandler,
|
||||||
|
req: HttpRequest,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Future for FormExtractFut<T>
|
||||||
|
where
|
||||||
|
T: DeserializeOwned + 'static,
|
||||||
|
{
|
||||||
|
type Output = Result<Form<T>, Error>;
|
||||||
|
|
||||||
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
let this = self.get_mut();
|
||||||
|
|
||||||
|
let res = ready!(Pin::new(&mut this.fut).poll(cx));
|
||||||
|
|
||||||
|
let res = match res {
|
||||||
|
Err(err) => match &this.err_handler {
|
||||||
|
Some(err_handler) => Err((err_handler)(err, &this.req)),
|
||||||
|
None => Err(err.into()),
|
||||||
|
},
|
||||||
|
Ok(item) => Ok(Form(item)),
|
||||||
|
};
|
||||||
|
|
||||||
|
Poll::Ready(res)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -193,7 +218,7 @@ impl<T: Serialize> Responder for Form<T> {
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct FormConfig {
|
pub struct FormConfig {
|
||||||
limit: usize,
|
limit: usize,
|
||||||
err_handler: Option<Rc<dyn Fn(UrlencodedError, &HttpRequest) -> Error>>,
|
err_handler: FormErrHandler,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FormConfig {
|
impl FormConfig {
|
||||||
|
|
Loading…
Reference in New Issue