mirror of https://github.com/fafhrd91/actix-web
Merge branch 'master' into default_error_handler
This commit is contained in:
commit
61f142c4e8
|
@ -1,8 +1,14 @@
|
||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2022-xx-xx
|
## Unreleased - 2022-xx-xx
|
||||||
|
|
||||||
|
|
||||||
|
## 0.6.2 - 2022-07-23
|
||||||
|
- Allow partial range responses for video content to start streaming sooner. [#2817]
|
||||||
- Minimum supported Rust version (MSRV) is now 1.57 due to transitive `time` dependency.
|
- Minimum supported Rust version (MSRV) is now 1.57 due to transitive `time` dependency.
|
||||||
|
|
||||||
|
[#2817]: https://github.com/actix/actix-web/pull/2817
|
||||||
|
|
||||||
|
|
||||||
## 0.6.1 - 2022-06-11
|
## 0.6.1 - 2022-06-11
|
||||||
- Add `NamedFile::{modified, metadata, content_type, content_disposition, encoding}()` getters. [#2021]
|
- Add `NamedFile::{modified, metadata, content_type, content_disposition, encoding}()` getters. [#2021]
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
[package]
|
[package]
|
||||||
name = "actix-files"
|
name = "actix-files"
|
||||||
version = "0.6.1"
|
version = "0.6.2"
|
||||||
authors = [
|
authors = [
|
||||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||||
"fakeshadow <24548779@qq.com>",
|
"fakeshadow <24548779@qq.com>",
|
||||||
|
@ -46,6 +46,6 @@ actix-server = { version = "2.1", optional = true } # ensure matching tokio-urin
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "2.7"
|
actix-rt = "2.7"
|
||||||
actix-test = "0.1.0-beta.13"
|
actix-test = "0.1"
|
||||||
actix-web = "4"
|
actix-web = "4"
|
||||||
tempfile = "3.2"
|
tempfile = "3.2"
|
||||||
|
|
|
@ -3,11 +3,11 @@
|
||||||
> Static file serving for Actix Web
|
> Static file serving for Actix Web
|
||||||
|
|
||||||
[](https://crates.io/crates/actix-files)
|
[](https://crates.io/crates/actix-files)
|
||||||
[](https://docs.rs/actix-files/0.6.1)
|
[](https://docs.rs/actix-files/0.6.2)
|
||||||

|

|
||||||

|

|
||||||
<br />
|
<br />
|
||||||
[](https://deps.rs/crate/actix-files/0.6.1)
|
[](https://deps.rs/crate/actix-files/0.6.2)
|
||||||
[](https://crates.io/crates/actix-files)
|
[](https://crates.io/crates/actix-files)
|
||||||
[](https://discord.gg/NWpN5mmg3x)
|
[](https://discord.gg/NWpN5mmg3x)
|
||||||
|
|
||||||
|
|
|
@ -2,7 +2,7 @@ use actix_web::{http::StatusCode, ResponseError};
|
||||||
use derive_more::Display;
|
use derive_more::Display;
|
||||||
|
|
||||||
/// Errors which can occur when serving static files.
|
/// Errors which can occur when serving static files.
|
||||||
#[derive(Display, Debug, PartialEq)]
|
#[derive(Debug, PartialEq, Eq, Display)]
|
||||||
pub enum FilesError {
|
pub enum FilesError {
|
||||||
/// Path is not a directory
|
/// Path is not a directory
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
|
@ -22,7 +22,7 @@ impl ResponseError for FilesError {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::enum_variant_names)]
|
#[allow(clippy::enum_variant_names)]
|
||||||
#[derive(Display, Debug, PartialEq)]
|
#[derive(Debug, PartialEq, Eq, Display)]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
pub enum UriSegmentError {
|
pub enum UriSegmentError {
|
||||||
/// The segment started with the wrapped invalid character.
|
/// The segment started with the wrapped invalid character.
|
||||||
|
|
|
@ -528,11 +528,26 @@ impl NamedFile {
|
||||||
length = ranges[0].length;
|
length = ranges[0].length;
|
||||||
offset = ranges[0].start;
|
offset = ranges[0].start;
|
||||||
|
|
||||||
// don't allow compression middleware to modify partial content
|
// When a Content-Encoding header is present in a 206 partial content response
|
||||||
res.insert_header((
|
// for video content, it prevents browser video players from starting playback
|
||||||
header::CONTENT_ENCODING,
|
// before loading the whole video and also prevents seeking.
|
||||||
HeaderValue::from_static("identity"),
|
//
|
||||||
));
|
// See: https://github.com/actix/actix-web/issues/2815
|
||||||
|
//
|
||||||
|
// The assumption of this fix is that the video player knows to not send an
|
||||||
|
// Accept-Encoding header for this request and that downstream middleware will
|
||||||
|
// not attempt compression for requests without it.
|
||||||
|
//
|
||||||
|
// TODO: Solve question around what to do if self.encoding is set and partial
|
||||||
|
// range is requested. Reject request? Ignoring self.encoding seems wrong, too.
|
||||||
|
// In practice, it should not come up.
|
||||||
|
if req.headers().contains_key(&header::ACCEPT_ENCODING) {
|
||||||
|
// don't allow compression middleware to modify partial content
|
||||||
|
res.insert_header((
|
||||||
|
header::CONTENT_ENCODING,
|
||||||
|
HeaderValue::from_static("identity"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
res.insert_header((
|
res.insert_header((
|
||||||
header::CONTENT_RANGE,
|
header::CONTENT_RANGE,
|
||||||
|
|
|
@ -1,11 +1,11 @@
|
||||||
use actix_files::Files;
|
use actix_files::{Files, NamedFile};
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
http::{
|
http::{
|
||||||
header::{self, HeaderValue},
|
header::{self, HeaderValue},
|
||||||
StatusCode,
|
StatusCode,
|
||||||
},
|
},
|
||||||
test::{self, TestRequest},
|
test::{self, TestRequest},
|
||||||
App,
|
web, App,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[actix_web::test]
|
#[actix_web::test]
|
||||||
|
@ -36,3 +36,31 @@ async fn test_utf8_file_contents() {
|
||||||
Some(&HeaderValue::from_static("text/plain")),
|
Some(&HeaderValue::from_static("text/plain")),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn partial_range_response_encoding() {
|
||||||
|
let srv = test::init_service(App::new().default_service(web::to(|| async {
|
||||||
|
NamedFile::open_async("./tests/test.binary").await.unwrap()
|
||||||
|
})))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// range request without accept-encoding returns no content-encoding header
|
||||||
|
let req = TestRequest::with_uri("/")
|
||||||
|
.append_header((header::RANGE, "bytes=10-20"))
|
||||||
|
.to_request();
|
||||||
|
let res = test::call_service(&srv, req).await;
|
||||||
|
assert_eq!(res.status(), StatusCode::PARTIAL_CONTENT);
|
||||||
|
assert!(!res.headers().contains_key(header::CONTENT_ENCODING));
|
||||||
|
|
||||||
|
// range request with accept-encoding returns a content-encoding header
|
||||||
|
let req = TestRequest::with_uri("/")
|
||||||
|
.append_header((header::RANGE, "bytes=10-20"))
|
||||||
|
.append_header((header::ACCEPT_ENCODING, "identity"))
|
||||||
|
.to_request();
|
||||||
|
let res = test::call_service(&srv, req).await;
|
||||||
|
assert_eq!(res.status(), StatusCode::PARTIAL_CONTENT);
|
||||||
|
assert_eq!(
|
||||||
|
res.headers().get(header::CONTENT_ENCODING).unwrap(),
|
||||||
|
"identity"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
|
@ -1,9 +1,24 @@
|
||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2022-xx-xx
|
## Unreleased - 2022-xx-xx
|
||||||
- Minimum supported Rust version (MSRV) is now 1.57 due to transitive `time` dependency.
|
|
||||||
|
|
||||||
|
|
||||||
|
## 3.0.0 - 2022-07-24
|
||||||
|
- `TestServer::stop` is now async and will wait for the server and system to shutdown. [#2442]
|
||||||
|
- Added `TestServer::client_headers` method. [#2097]
|
||||||
|
- Update `actix-server` dependency to `2`.
|
||||||
|
- Update `actix-tls` dependency to `3`.
|
||||||
|
- Update `bytes` to `1.0`. [#1813]
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.57.
|
||||||
|
|
||||||
|
[#2442]: https://github.com/actix/actix-web/pull/2442
|
||||||
|
[#2097]: https://github.com/actix/actix-web/pull/2097
|
||||||
|
[#1813]: https://github.com/actix/actix-web/pull/1813
|
||||||
|
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>3.0.0 Pre-Releases</summary>
|
||||||
|
|
||||||
## 3.0.0-beta.13 - 2022-02-16
|
## 3.0.0-beta.13 - 2022-02-16
|
||||||
- No significant changes since `3.0.0-beta.12`.
|
- No significant changes since `3.0.0-beta.12`.
|
||||||
|
|
||||||
|
@ -69,6 +84,7 @@
|
||||||
|
|
||||||
[#1813]: https://github.com/actix/actix-web/pull/1813
|
[#1813]: https://github.com/actix/actix-web/pull/1813
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
## 2.1.0 - 2020-11-25
|
## 2.1.0 - 2020-11-25
|
||||||
- Add ability to set address for `TestServer`. [#1645]
|
- Add ability to set address for `TestServer`. [#1645]
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
[package]
|
[package]
|
||||||
name = "actix-http-test"
|
name = "actix-http-test"
|
||||||
version = "3.0.0-beta.13"
|
version = "3.0.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Various helpers for Actix applications to use during testing"
|
description = "Various helpers for Actix applications to use during testing"
|
||||||
keywords = ["http", "web", "framework", "async", "futures"]
|
keywords = ["http", "web", "framework", "async", "futures"]
|
||||||
|
|
|
@ -3,11 +3,11 @@
|
||||||
> Various helpers for Actix applications to use during testing.
|
> Various helpers for Actix applications to use during testing.
|
||||||
|
|
||||||
[](https://crates.io/crates/actix-http-test)
|
[](https://crates.io/crates/actix-http-test)
|
||||||
[](https://docs.rs/actix-http-test/3.0.0-beta.13)
|
[](https://docs.rs/actix-http-test/3.0.0)
|
||||||

|

|
||||||

|

|
||||||
<br>
|
<br>
|
||||||
[](https://deps.rs/crate/actix-http-test/3.0.0-beta.13)
|
[](https://deps.rs/crate/actix-http-test/3.0.0)
|
||||||
[](https://crates.io/crates/actix-http-test)
|
[](https://crates.io/crates/actix-http-test)
|
||||||
[](https://discord.gg/NWpN5mmg3x)
|
[](https://discord.gg/NWpN5mmg3x)
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,10 @@
|
||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2022-xx-xx
|
## Unreleased - 2022-xx-xx
|
||||||
|
### Fixed
|
||||||
|
- Avoid possibility of dispatcher getting stuck while back-pressuring I/O. [#2369]
|
||||||
|
|
||||||
|
[#2369]: https://github.com/actix/actix-web/pull/2369
|
||||||
|
|
||||||
|
|
||||||
## 3.2.1 - 2022-07-02
|
## 3.2.1 - 2022-07-02
|
||||||
|
@ -29,9 +33,9 @@
|
||||||
### Fixed
|
### Fixed
|
||||||
- Revert broken fix in [#2624] that caused erroneous 500 error responses. Temporarily re-introduces [#2357] bug. [#2779]
|
- Revert broken fix in [#2624] that caused erroneous 500 error responses. Temporarily re-introduces [#2357] bug. [#2779]
|
||||||
|
|
||||||
|
[#2624]: https://github.com/actix/actix-web/pull/2624
|
||||||
[#2357]: https://github.com/actix/actix-web/issues/2357
|
[#2357]: https://github.com/actix/actix-web/issues/2357
|
||||||
[#2624]: https://github.com/actix/actix-web/issues/2624
|
[#2779]: https://github.com/actix/actix-web/pull/2779
|
||||||
[#2779]: https://github.com/actix/actix-web/issues/2779
|
|
||||||
|
|
||||||
|
|
||||||
## 3.0.4 - 2022-03-09
|
## 3.0.4 - 2022-03-09
|
||||||
|
@ -43,14 +47,14 @@
|
||||||
### Fixed
|
### Fixed
|
||||||
- Allow spaces between header name and colon when parsing responses. [#2684]
|
- Allow spaces between header name and colon when parsing responses. [#2684]
|
||||||
|
|
||||||
[#2684]: https://github.com/actix/actix-web/issues/2684
|
[#2684]: https://github.com/actix/actix-web/pull/2684
|
||||||
|
|
||||||
|
|
||||||
## 3.0.2 - 2022-03-05
|
## 3.0.2 - 2022-03-05
|
||||||
### Fixed
|
### Fixed
|
||||||
- Fix encoding camel-case header names with more than one hyphen. [#2683]
|
- Fix encoding camel-case header names with more than one hyphen. [#2683]
|
||||||
|
|
||||||
[#2683]: https://github.com/actix/actix-web/issues/2683
|
[#2683]: https://github.com/actix/actix-web/pull/2683
|
||||||
|
|
||||||
|
|
||||||
## 3.0.1 - 2022-03-04
|
## 3.0.1 - 2022-03-04
|
||||||
|
|
|
@ -97,7 +97,7 @@ flate2 = { version = "1.0.13", optional = true }
|
||||||
zstd = { version = "0.11", optional = true }
|
zstd = { version = "0.11", optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-http-test = { version = "3.0.0-beta.13", features = ["openssl"] }
|
actix-http-test = { version = "3", features = ["openssl"] }
|
||||||
actix-server = "2"
|
actix-server = "2"
|
||||||
actix-tls = { version = "3", features = ["openssl"] }
|
actix-tls = { version = "3", features = ["openssl"] }
|
||||||
actix-web = "4"
|
actix-web = "4"
|
||||||
|
|
|
@ -211,6 +211,7 @@ 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.
|
||||||
#[cfg(feature = "http2")]
|
#[cfg(feature = "http2")]
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
|
||||||
pub fn h2<F, B>(self, service: F) -> crate::h2::H2Service<T, S, B>
|
pub fn h2<F, B>(self, service: F) -> crate::h2::H2Service<T, S, B>
|
||||||
where
|
where
|
||||||
F: IntoServiceFactory<S, Request>,
|
F: IntoServiceFactory<S, Request>,
|
||||||
|
|
|
@ -35,7 +35,7 @@ impl Default for ServiceConfig {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ServiceConfig {
|
impl ServiceConfig {
|
||||||
/// Create instance of `ServiceConfig`
|
/// Create instance of `ServiceConfig`.
|
||||||
pub fn new(
|
pub fn new(
|
||||||
keep_alive: KeepAlive,
|
keep_alive: KeepAlive,
|
||||||
client_request_timeout: Duration,
|
client_request_timeout: Duration,
|
||||||
|
|
|
@ -294,6 +294,7 @@ impl std::error::Error for PayloadError {
|
||||||
PayloadError::Overflow => None,
|
PayloadError::Overflow => None,
|
||||||
PayloadError::UnknownLength => None,
|
PayloadError::UnknownLength => None,
|
||||||
#[cfg(feature = "http2")]
|
#[cfg(feature = "http2")]
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
|
||||||
PayloadError::Http2Payload(err) => Some(err),
|
PayloadError::Http2Payload(err) => Some(err),
|
||||||
PayloadError::Io(err) => Some(err),
|
PayloadError::Io(err) => Some(err),
|
||||||
}
|
}
|
||||||
|
@ -351,6 +352,7 @@ pub enum DispatchError {
|
||||||
/// HTTP/2 error.
|
/// HTTP/2 error.
|
||||||
#[display(fmt = "{}", _0)]
|
#[display(fmt = "{}", _0)]
|
||||||
#[cfg(feature = "http2")]
|
#[cfg(feature = "http2")]
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
|
||||||
H2(h2::Error),
|
H2(h2::Error),
|
||||||
|
|
||||||
/// The first request did not complete within the specified timeout.
|
/// The first request did not complete within the specified timeout.
|
||||||
|
@ -388,7 +390,7 @@ impl StdError for DispatchError {
|
||||||
|
|
||||||
/// A set of error that can occur during parsing content type.
|
/// A set of error that can occur during parsing content type.
|
||||||
#[derive(Debug, Display, Error)]
|
#[derive(Debug, Display, Error)]
|
||||||
#[cfg_attr(test, derive(PartialEq))]
|
#[cfg_attr(test, derive(PartialEq, Eq))]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
pub enum ContentTypeError {
|
pub enum ContentTypeError {
|
||||||
/// Can not parse content type
|
/// Can not parse content type
|
||||||
|
|
|
@ -15,7 +15,7 @@ macro_rules! byte (
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Clone)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub(super) enum ChunkedState {
|
pub(super) enum ChunkedState {
|
||||||
Size,
|
Size,
|
||||||
SizeLws,
|
SizeLws,
|
||||||
|
|
|
@ -440,7 +440,7 @@ impl HeaderIndex {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
/// Chunk type yielded while decoding a payload.
|
/// Chunk type yielded while decoding a payload.
|
||||||
pub enum PayloadItem {
|
pub enum PayloadItem {
|
||||||
Chunk(Bytes),
|
Chunk(Bytes),
|
||||||
|
@ -450,7 +450,7 @@ pub enum PayloadItem {
|
||||||
/// Decoder that can handle different payload types.
|
/// Decoder that can handle different payload types.
|
||||||
///
|
///
|
||||||
/// If a message body does not use `Transfer-Encoding`, it should include a `Content-Length`.
|
/// If a message body does not use `Transfer-Encoding`, it should include a `Content-Length`.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct PayloadDecoder {
|
pub struct PayloadDecoder {
|
||||||
kind: Kind,
|
kind: Kind,
|
||||||
}
|
}
|
||||||
|
@ -476,7 +476,7 @@ impl PayloadDecoder {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
enum Kind {
|
enum Kind {
|
||||||
/// A reader used when a `Content-Length` header is passed with a positive integer.
|
/// A reader used when a `Content-Length` header is passed with a positive integer.
|
||||||
Length(u64),
|
Length(u64),
|
||||||
|
|
|
@ -976,9 +976,11 @@ where
|
||||||
//
|
//
|
||||||
// A Request head too large to parse is only checked on `httparse::Status::Partial`.
|
// A Request head too large to parse is only checked on `httparse::Status::Partial`.
|
||||||
|
|
||||||
if this.payload.is_none() {
|
match this.payload {
|
||||||
// When dispatcher has a payload the responsibility of wake up it would be shift
|
// When dispatcher has a payload the responsibility of wake ups is shifted to
|
||||||
// to h1::payload::Payload.
|
// `h1::payload::Payload` unless the payload is needing a read, in which case it
|
||||||
|
// might not have access to the waker and could result in the dispatcher
|
||||||
|
// getting stuck until timeout.
|
||||||
//
|
//
|
||||||
// Reason:
|
// Reason:
|
||||||
// Self wake up when there is payload would waste poll and/or result in
|
// Self wake up when there is payload would waste poll and/or result in
|
||||||
|
@ -989,7 +991,8 @@ where
|
||||||
// read anymore. At this case read_buf could always remain beyond
|
// read anymore. At this case read_buf could always remain beyond
|
||||||
// MAX_BUFFER_SIZE and self wake up would be busy poll dispatcher and
|
// MAX_BUFFER_SIZE and self wake up would be busy poll dispatcher and
|
||||||
// waste resources.
|
// waste resources.
|
||||||
cx.waker().wake_by_ref();
|
Some(ref p) if p.need_read(cx) != PayloadStatus::Read => {}
|
||||||
|
_ => cx.waker().wake_by_ref(),
|
||||||
}
|
}
|
||||||
|
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
|
|
|
@ -16,7 +16,7 @@ use crate::error::PayloadError;
|
||||||
/// max buffer size 32k
|
/// max buffer size 32k
|
||||||
pub(crate) const MAX_BUFFER_SIZE: usize = 32_768;
|
pub(crate) const MAX_BUFFER_SIZE: usize = 32_768;
|
||||||
|
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
pub enum PayloadStatus {
|
pub enum PayloadStatus {
|
||||||
Read,
|
Read,
|
||||||
Pause,
|
Pause,
|
||||||
|
@ -252,19 +252,15 @@ impl Inner {
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::panic::{RefUnwindSafe, UnwindSafe};
|
|
||||||
|
|
||||||
use actix_utils::future::poll_fn;
|
use actix_utils::future::poll_fn;
|
||||||
use static_assertions::{assert_impl_all, assert_not_impl_any};
|
use static_assertions::{assert_impl_all, assert_not_impl_any};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
assert_impl_all!(Payload: Unpin);
|
assert_impl_all!(Payload: Unpin);
|
||||||
assert_not_impl_any!(Payload: Send, Sync, UnwindSafe, RefUnwindSafe);
|
assert_not_impl_any!(Payload: Send, Sync);
|
||||||
|
|
||||||
assert_impl_all!(Inner: Unpin, Send, Sync);
|
assert_impl_all!(Inner: Unpin, Send, Sync);
|
||||||
// assertion not stable wrt rustc versions yet
|
|
||||||
// assert_impl_all!(Inner: UnwindSafe, RefUnwindSafe);
|
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_unread_data() {
|
async fn test_unread_data() {
|
||||||
|
|
|
@ -134,6 +134,7 @@ mod openssl {
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
/// Create OpenSSL based service.
|
/// Create OpenSSL based service.
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "openssl")))]
|
||||||
pub fn openssl(
|
pub fn openssl(
|
||||||
self,
|
self,
|
||||||
acceptor: SslAcceptor,
|
acceptor: SslAcceptor,
|
||||||
|
@ -196,6 +197,7 @@ mod rustls {
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
/// Create Rustls based service.
|
/// Create Rustls based service.
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "rustls")))]
|
||||||
pub fn rustls(
|
pub fn rustls(
|
||||||
self,
|
self,
|
||||||
config: ServerConfig,
|
config: ServerConfig,
|
||||||
|
|
|
@ -67,7 +67,7 @@ where
|
||||||
timer
|
timer
|
||||||
})
|
})
|
||||||
.unwrap_or_else(|| Box::pin(sleep(dur))),
|
.unwrap_or_else(|| Box::pin(sleep(dur))),
|
||||||
on_flight: false,
|
in_flight: false,
|
||||||
ping_pong: conn.ping_pong().unwrap(),
|
ping_pong: conn.ping_pong().unwrap(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -84,9 +84,14 @@ where
|
||||||
}
|
}
|
||||||
|
|
||||||
struct H2PingPong {
|
struct H2PingPong {
|
||||||
timer: Pin<Box<Sleep>>,
|
/// Handle to send ping frames from the peer.
|
||||||
on_flight: bool,
|
|
||||||
ping_pong: PingPong,
|
ping_pong: PingPong,
|
||||||
|
|
||||||
|
/// True when a ping has been sent and is waiting for a reply.
|
||||||
|
in_flight: bool,
|
||||||
|
|
||||||
|
/// Timeout for pong response.
|
||||||
|
timer: Pin<Box<Sleep>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
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>
|
||||||
|
@ -152,26 +157,28 @@ where
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Poll::Ready(None) => return Poll::Ready(Ok(())),
|
Poll::Ready(None) => return Poll::Ready(Ok(())),
|
||||||
|
|
||||||
Poll::Pending => match this.ping_pong.as_mut() {
|
Poll::Pending => match this.ping_pong.as_mut() {
|
||||||
Some(ping_pong) => loop {
|
Some(ping_pong) => loop {
|
||||||
if ping_pong.on_flight {
|
if ping_pong.in_flight {
|
||||||
// When have on flight ping pong. poll pong and and keep alive timer.
|
// When there is an in-flight ping-pong, poll pong and and keep-alive
|
||||||
// on success pong received update keep alive timer to determine the next timing of
|
// timer. On successful pong received, update keep-alive timer to
|
||||||
// ping pong.
|
// determine the next timing of ping pong.
|
||||||
match ping_pong.ping_pong.poll_pong(cx)? {
|
match ping_pong.ping_pong.poll_pong(cx)? {
|
||||||
Poll::Ready(_) => {
|
Poll::Ready(_) => {
|
||||||
ping_pong.on_flight = false;
|
ping_pong.in_flight = false;
|
||||||
|
|
||||||
let dead_line = this.config.keep_alive_deadline().unwrap();
|
let dead_line = this.config.keep_alive_deadline().unwrap();
|
||||||
ping_pong.timer.as_mut().reset(dead_line.into());
|
ping_pong.timer.as_mut().reset(dead_line.into());
|
||||||
}
|
}
|
||||||
Poll::Pending => {
|
Poll::Pending => {
|
||||||
return ping_pong.timer.as_mut().poll(cx).map(|_| Ok(()))
|
return ping_pong.timer.as_mut().poll(cx).map(|_| Ok(()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// When there is no on flight ping pong. keep alive timer is used to wait for next
|
// When there is no in-flight ping-pong, keep-alive timer is used to
|
||||||
// timing of ping pong. Therefore at this point it serves as an interval instead.
|
// wait for next timing of ping-pong. Therefore, at this point it serves
|
||||||
|
// as an interval instead.
|
||||||
ready!(ping_pong.timer.as_mut().poll(cx));
|
ready!(ping_pong.timer.as_mut().poll(cx));
|
||||||
|
|
||||||
ping_pong.ping_pong.send_ping(Ping::opaque())?;
|
ping_pong.ping_pong.send_ping(Ping::opaque())?;
|
||||||
|
@ -179,7 +186,7 @@ where
|
||||||
let dead_line = this.config.keep_alive_deadline().unwrap();
|
let dead_line = this.config.keep_alive_deadline().unwrap();
|
||||||
ping_pong.timer.as_mut().reset(dead_line.into());
|
ping_pong.timer.as_mut().reset(dead_line.into());
|
||||||
|
|
||||||
ping_pong.on_flight = true;
|
ping_pong.in_flight = true;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
None => return Poll::Pending,
|
None => return Poll::Pending,
|
||||||
|
@ -287,13 +294,13 @@ fn prepare_response(
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
let _ = match size {
|
match size {
|
||||||
BodySize::None | BodySize::Stream => None,
|
BodySize::None | BodySize::Stream => {}
|
||||||
|
|
||||||
BodySize::Sized(0) => {
|
BodySize::Sized(0) => {
|
||||||
#[allow(clippy::declare_interior_mutable_const)]
|
#[allow(clippy::declare_interior_mutable_const)]
|
||||||
const HV_ZERO: HeaderValue = HeaderValue::from_static("0");
|
const HV_ZERO: HeaderValue = HeaderValue::from_static("0");
|
||||||
res.headers_mut().insert(CONTENT_LENGTH, HV_ZERO)
|
res.headers_mut().insert(CONTENT_LENGTH, HV_ZERO);
|
||||||
}
|
}
|
||||||
|
|
||||||
BodySize::Sized(len) => {
|
BodySize::Sized(len) => {
|
||||||
|
@ -302,7 +309,7 @@ fn prepare_response(
|
||||||
res.headers_mut().insert(
|
res.headers_mut().insert(
|
||||||
CONTENT_LENGTH,
|
CONTENT_LENGTH,
|
||||||
HeaderValue::from_str(buf.format(*len)).unwrap(),
|
HeaderValue::from_str(buf.format(*len)).unwrap(),
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -103,11 +103,9 @@ where
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::panic::{RefUnwindSafe, UnwindSafe};
|
|
||||||
|
|
||||||
use static_assertions::assert_impl_all;
|
use static_assertions::assert_impl_all;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
assert_impl_all!(Payload: Unpin, Send, Sync, UnwindSafe, RefUnwindSafe);
|
assert_impl_all!(Payload: Unpin, Send, Sync);
|
||||||
}
|
}
|
||||||
|
|
|
@ -117,6 +117,7 @@ mod openssl {
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
{
|
{
|
||||||
/// Create OpenSSL based service.
|
/// Create OpenSSL based service.
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "openssl")))]
|
||||||
pub fn openssl(
|
pub fn openssl(
|
||||||
self,
|
self,
|
||||||
acceptor: SslAcceptor,
|
acceptor: SslAcceptor,
|
||||||
|
@ -164,6 +165,7 @@ mod rustls {
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
{
|
{
|
||||||
/// Create Rustls based service.
|
/// Create Rustls based service.
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "rustls")))]
|
||||||
pub fn rustls(
|
pub fn rustls(
|
||||||
self,
|
self,
|
||||||
mut config: ServerConfig,
|
mut config: ServerConfig,
|
||||||
|
|
|
@ -12,7 +12,7 @@ use crate::header::{Charset, HTTP_VALUE};
|
||||||
/// - A character sequence representing the actual value (`value`), separated by single quotes.
|
/// - A character sequence representing the actual value (`value`), separated by single quotes.
|
||||||
///
|
///
|
||||||
/// It is defined in [RFC 5987 §3.2](https://datatracker.ietf.org/doc/html/rfc5987#section-3.2).
|
/// It is defined in [RFC 5987 §3.2](https://datatracker.ietf.org/doc/html/rfc5987#section-3.2).
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct ExtendedValue {
|
pub struct ExtendedValue {
|
||||||
/// The character set that is used to encode the `value` to a string.
|
/// The character set that is used to encode the `value` to a string.
|
||||||
pub charset: Charset,
|
pub charset: Charset,
|
||||||
|
|
|
@ -147,7 +147,7 @@ mod tests {
|
||||||
|
|
||||||
// copy of encoding from actix-web headers
|
// copy of encoding from actix-web headers
|
||||||
#[allow(clippy::enum_variant_names)] // allow Encoding prefix on EncodingExt
|
#[allow(clippy::enum_variant_names)] // allow Encoding prefix on EncodingExt
|
||||||
#[derive(Clone, PartialEq, Debug)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum Encoding {
|
pub enum Encoding {
|
||||||
Chunked,
|
Chunked,
|
||||||
Brotli,
|
Brotli,
|
||||||
|
|
|
@ -40,6 +40,7 @@ pub mod error;
|
||||||
mod extensions;
|
mod extensions;
|
||||||
pub mod h1;
|
pub mod h1;
|
||||||
#[cfg(feature = "http2")]
|
#[cfg(feature = "http2")]
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
|
||||||
pub mod h2;
|
pub mod h2;
|
||||||
pub mod header;
|
pub mod header;
|
||||||
mod helpers;
|
mod helpers;
|
||||||
|
@ -54,6 +55,7 @@ mod responses;
|
||||||
mod service;
|
mod service;
|
||||||
pub mod test;
|
pub mod test;
|
||||||
#[cfg(feature = "ws")]
|
#[cfg(feature = "ws")]
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
|
||||||
pub mod ws;
|
pub mod ws;
|
||||||
|
|
||||||
pub use self::builder::HttpServiceBuilder;
|
pub use self::builder::HttpServiceBuilder;
|
||||||
|
@ -71,6 +73,7 @@ pub use self::requests::{Request, RequestHead, RequestHeadType};
|
||||||
pub use self::responses::{Response, ResponseBuilder, ResponseHead};
|
pub use self::responses::{Response, ResponseBuilder, ResponseHead};
|
||||||
pub use self::service::HttpService;
|
pub use self::service::HttpService;
|
||||||
#[cfg(any(feature = "openssl", feature = "rustls"))]
|
#[cfg(any(feature = "openssl", feature = "rustls"))]
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(any(feature = "openssl", feature = "rustls"))))]
|
||||||
pub use self::service::TlsAcceptorConfig;
|
pub use self::service::TlsAcceptorConfig;
|
||||||
|
|
||||||
/// A major HTTP protocol version.
|
/// A major HTTP protocol version.
|
||||||
|
|
|
@ -3,7 +3,7 @@ use std::{cell::RefCell, ops, rc::Rc};
|
||||||
use bitflags::bitflags;
|
use bitflags::bitflags;
|
||||||
|
|
||||||
/// Represents various types of connection
|
/// Represents various types of connection
|
||||||
#[derive(Copy, Clone, PartialEq, Debug)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum ConnectionType {
|
pub enum ConnectionType {
|
||||||
/// Close connection after response.
|
/// Close connection after response.
|
||||||
Close,
|
Close,
|
||||||
|
|
|
@ -97,12 +97,10 @@ where
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::panic::{RefUnwindSafe, UnwindSafe};
|
|
||||||
|
|
||||||
use static_assertions::{assert_impl_all, assert_not_impl_any};
|
use static_assertions::{assert_impl_all, assert_not_impl_any};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
assert_impl_all!(Payload: Unpin);
|
assert_impl_all!(Payload: Unpin);
|
||||||
assert_not_impl_any!(Payload: Send, Sync, UnwindSafe, RefUnwindSafe);
|
assert_not_impl_any!(Payload: Send, Sync);
|
||||||
}
|
}
|
||||||
|
|
|
@ -239,6 +239,7 @@ mod openssl {
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
/// Create OpenSSL based service.
|
/// Create OpenSSL based service.
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "openssl")))]
|
||||||
pub fn openssl(
|
pub fn openssl(
|
||||||
self,
|
self,
|
||||||
acceptor: SslAcceptor,
|
acceptor: SslAcceptor,
|
||||||
|
@ -253,6 +254,7 @@ mod openssl {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create OpenSSL based service with custom TLS acceptor configuration.
|
/// Create OpenSSL based service with custom TLS acceptor configuration.
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "openssl")))]
|
||||||
pub fn openssl_with_config(
|
pub fn openssl_with_config(
|
||||||
self,
|
self,
|
||||||
acceptor: SslAcceptor,
|
acceptor: SslAcceptor,
|
||||||
|
@ -332,6 +334,7 @@ mod rustls {
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
/// Create Rustls based service.
|
/// Create Rustls based service.
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "rustls")))]
|
||||||
pub fn rustls(
|
pub fn rustls(
|
||||||
self,
|
self,
|
||||||
config: ServerConfig,
|
config: ServerConfig,
|
||||||
|
@ -346,6 +349,7 @@ mod rustls {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create Rustls based service with custom TLS acceptor configuration.
|
/// Create Rustls based service with custom TLS acceptor configuration.
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "rustls")))]
|
||||||
pub fn rustls_with_config(
|
pub fn rustls_with_config(
|
||||||
self,
|
self,
|
||||||
mut config: ServerConfig,
|
mut config: ServerConfig,
|
||||||
|
|
|
@ -11,7 +11,7 @@ use super::{
|
||||||
};
|
};
|
||||||
|
|
||||||
/// A WebSocket message.
|
/// A WebSocket message.
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
pub enum Message {
|
pub enum Message {
|
||||||
/// Text message.
|
/// Text message.
|
||||||
Text(ByteString),
|
Text(ByteString),
|
||||||
|
@ -36,7 +36,7 @@ pub enum Message {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A WebSocket frame.
|
/// A WebSocket frame.
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
pub enum Frame {
|
pub enum Frame {
|
||||||
/// Text frame. Note that the codec does not validate UTF-8 encoding.
|
/// Text frame. Note that the codec does not validate UTF-8 encoding.
|
||||||
Text(Bytes),
|
Text(Bytes),
|
||||||
|
@ -58,7 +58,7 @@ pub enum Frame {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A WebSocket continuation item.
|
/// A WebSocket continuation item.
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
pub enum Item {
|
pub enum Item {
|
||||||
FirstText(Bytes),
|
FirstText(Bytes),
|
||||||
FirstBinary(Bytes),
|
FirstBinary(Bytes),
|
||||||
|
|
|
@ -67,7 +67,7 @@ pub enum ProtocolError {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// WebSocket handshake errors
|
/// WebSocket handshake errors
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Display, Error)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Display, Error)]
|
||||||
pub enum HandshakeError {
|
pub enum HandshakeError {
|
||||||
/// Only get method is allowed.
|
/// Only get method is allowed.
|
||||||
#[display(fmt = "Method not allowed.")]
|
#[display(fmt = "Method not allowed.")]
|
||||||
|
|
|
@ -21,7 +21,7 @@ default = ["http"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
bytestring = ">=0.1.5, <2"
|
bytestring = ">=0.1.5, <2"
|
||||||
http = { version = "0.2.3", optional = true }
|
http = { version = "0.2.5", optional = true }
|
||||||
regex = "1.5"
|
regex = "1.5"
|
||||||
serde = "1"
|
serde = "1"
|
||||||
tracing = { version = "0.1.30", default-features = false, features = ["log"] }
|
tracing = { version = "0.1.30", default-features = false, features = ["log"] }
|
||||||
|
|
|
@ -27,7 +27,7 @@ impl<'a> ResourcePath for &'a str {
|
||||||
|
|
||||||
impl ResourcePath for bytestring::ByteString {
|
impl ResourcePath for bytestring::ByteString {
|
||||||
fn path(&self) -> &str {
|
fn path(&self) -> &str {
|
||||||
&*self
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
use crate::{IntoPatterns, Resource, ResourceDef};
|
use crate::{IntoPatterns, Resource, ResourceDef};
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
pub struct ResourceId(pub u16);
|
pub struct ResourceId(pub u16);
|
||||||
|
|
||||||
/// Resource router.
|
/// Resource router.
|
||||||
|
|
|
@ -1,6 +1,9 @@
|
||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2022-xx-xx
|
## Unreleased - 2022-xx-xx
|
||||||
|
|
||||||
|
|
||||||
|
## 0.1.0 - 2022-07-24
|
||||||
- Minimum supported Rust version (MSRV) is now 1.57 due to transitive `time` dependency.
|
- Minimum supported Rust version (MSRV) is now 1.57 due to transitive `time` dependency.
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
[package]
|
[package]
|
||||||
name = "actix-test"
|
name = "actix-test"
|
||||||
version = "0.1.0-beta.13"
|
version = "0.1.0"
|
||||||
authors = [
|
authors = [
|
||||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||||
"Rob Ede <robjtede@icloud.com>",
|
"Rob Ede <robjtede@icloud.com>",
|
||||||
|
@ -30,7 +30,7 @@ openssl = ["tls-openssl", "actix-http/openssl", "awc/openssl"]
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.5"
|
actix-codec = "0.5"
|
||||||
actix-http = "3"
|
actix-http = "3"
|
||||||
actix-http-test = "3.0.0-beta.13"
|
actix-http-test = "3"
|
||||||
actix-rt = "2.1"
|
actix-rt = "2.1"
|
||||||
actix-service = "2"
|
actix-service = "2"
|
||||||
actix-utils = "3"
|
actix-utils = "3"
|
||||||
|
|
|
@ -27,7 +27,7 @@ tokio = { version = "1.13.1", features = ["sync"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "2.2"
|
actix-rt = "2.2"
|
||||||
actix-test = "0.1.0-beta.13"
|
actix-test = "0.1"
|
||||||
awc = { version = "3", default-features = false }
|
awc = { version = "3", default-features = false }
|
||||||
actix-web = { version = "4", features = ["macros"] }
|
actix-web = { version = "4", features = ["macros"] }
|
||||||
|
|
||||||
|
|
|
@ -23,7 +23,7 @@ syn = { version = "1", features = ["full", "extra-traits"] }
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-macros = "0.2.3"
|
actix-macros = "0.2.3"
|
||||||
actix-rt = "2.2"
|
actix-rt = "2.2"
|
||||||
actix-test = "0.1.0-beta.13"
|
actix-test = "0.1"
|
||||||
actix-utils = "3.0.0"
|
actix-utils = "3.0.0"
|
||||||
actix-web = "4.0.0"
|
actix-web = "4.0.0"
|
||||||
|
|
||||||
|
|
|
@ -84,11 +84,12 @@ derive_more = "0.99.5"
|
||||||
encoding_rs = "0.8"
|
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 }
|
||||||
|
http = "0.2.8"
|
||||||
itoa = "1"
|
itoa = "1"
|
||||||
language-tags = "0.3"
|
language-tags = "0.3"
|
||||||
once_cell = "1.5"
|
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
mime = "0.3"
|
mime = "0.3"
|
||||||
|
once_cell = "1.5"
|
||||||
pin-project-lite = "0.2.7"
|
pin-project-lite = "0.2.7"
|
||||||
regex = "1.5.5"
|
regex = "1.5.5"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
|
@ -101,7 +102,7 @@ url = "2.1"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-files = "0.6"
|
actix-files = "0.6"
|
||||||
actix-test = { version = "0.1.0-beta.13", features = ["openssl", "rustls"] }
|
actix-test = { version = "0.1", features = ["openssl", "rustls"] }
|
||||||
awc = { version = "3", features = ["openssl"] }
|
awc = { version = "3", features = ["openssl"] }
|
||||||
|
|
||||||
brotli = "3.3.3"
|
brotli = "3.3.3"
|
||||||
|
|
|
@ -118,7 +118,7 @@ impl<T: ?Sized> Deref for Data<T> {
|
||||||
|
|
||||||
impl<T: ?Sized> Clone for Data<T> {
|
impl<T: ?Sized> Clone for Data<T> {
|
||||||
fn clone(&self) -> Data<T> {
|
fn clone(&self) -> Data<T> {
|
||||||
Data(self.0.clone())
|
Data(Arc::clone(&self.0))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -42,7 +42,7 @@ pub struct BlockingError;
|
||||||
impl ResponseError for crate::error::BlockingError {}
|
impl ResponseError for crate::error::BlockingError {}
|
||||||
|
|
||||||
/// Errors which can occur when attempting to generate resource uri.
|
/// Errors which can occur when attempting to generate resource uri.
|
||||||
#[derive(Debug, PartialEq, Display, Error, From)]
|
#[derive(Debug, PartialEq, Eq, Display, Error, From)]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
pub enum UrlGenerationError {
|
pub enum UrlGenerationError {
|
||||||
/// Resource not found.
|
/// Resource not found.
|
||||||
|
|
|
@ -10,9 +10,10 @@
|
||||||
//! - Browser conformance tests at: <http://greenbytes.de/tech/tc2231/>
|
//! - Browser conformance tests at: <http://greenbytes.de/tech/tc2231/>
|
||||||
//! - IANA assignment: <http://www.iana.org/assignments/cont-disp/cont-disp.xhtml>
|
//! - IANA assignment: <http://www.iana.org/assignments/cont-disp/cont-disp.xhtml>
|
||||||
|
|
||||||
|
use std::fmt::{self, Write};
|
||||||
|
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use std::fmt::{self, Write};
|
|
||||||
|
|
||||||
use super::{ExtendedValue, Header, TryIntoHeaderValue, Writer};
|
use super::{ExtendedValue, Header, TryIntoHeaderValue, Writer};
|
||||||
use crate::http::header;
|
use crate::http::header;
|
||||||
|
@ -36,7 +37,7 @@ fn split_once_and_trim(haystack: &str, needle: char) -> (&str, &str) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The implied disposition of the content of the HTTP body.
|
/// The implied disposition of the content of the HTTP body.
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum DispositionType {
|
pub enum DispositionType {
|
||||||
/// Inline implies default processing.
|
/// Inline implies default processing.
|
||||||
Inline,
|
Inline,
|
||||||
|
@ -78,7 +79,7 @@ impl<'a> From<&'a str> for DispositionType {
|
||||||
/// assert!(param.is_filename());
|
/// assert!(param.is_filename());
|
||||||
/// assert_eq!(param.as_filename().unwrap(), "sample.txt");
|
/// assert_eq!(param.as_filename().unwrap(), "sample.txt");
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
#[allow(clippy::large_enum_variant)]
|
#[allow(clippy::large_enum_variant)]
|
||||||
pub enum DispositionParam {
|
pub enum DispositionParam {
|
||||||
/// For [`DispositionType::FormData`] (i.e. *multipart/form-data*), the name of an field from
|
/// For [`DispositionType::FormData`] (i.e. *multipart/form-data*), the name of an field from
|
||||||
|
@ -301,7 +302,7 @@ impl DispositionParam {
|
||||||
/// change to match local file system conventions if applicable, and do not use directory path
|
/// change to match local file system conventions if applicable, and do not use directory path
|
||||||
/// information that may be present.
|
/// information that may be present.
|
||||||
/// See [RFC 2183 §2.3](https://datatracker.ietf.org/doc/html/rfc2183#section-2.3).
|
/// See [RFC 2183 §2.3](https://datatracker.ietf.org/doc/html/rfc2183#section-2.3).
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct ContentDisposition {
|
pub struct ContentDisposition {
|
||||||
/// The disposition type
|
/// The disposition type
|
||||||
pub disposition: DispositionType,
|
pub disposition: DispositionType,
|
||||||
|
|
|
@ -57,7 +57,7 @@ use crate::HttpMessage;
|
||||||
/// IfRange::Date(fetched.into())
|
/// IfRange::Date(fetched.into())
|
||||||
/// );
|
/// );
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub enum IfRange {
|
pub enum IfRange {
|
||||||
/// The entity-tag the client has of the resource.
|
/// The entity-tag the client has of the resource.
|
||||||
EntityTag(EntityTag),
|
EntityTag(EntityTag),
|
||||||
|
|
|
@ -224,10 +224,11 @@ macro_rules! common_header {
|
||||||
// List header, one or more items with "*" option
|
// List header, one or more items with "*" option
|
||||||
($(#[$attrs:meta])*($id:ident, $name:expr) => {Any / ($item:ty)+}) => {
|
($(#[$attrs:meta])*($id:ident, $name:expr) => {Any / ($item:ty)+}) => {
|
||||||
$(#[$attrs])*
|
$(#[$attrs])*
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub enum $id {
|
pub enum $id {
|
||||||
/// Any value is a match
|
/// Any value is a match
|
||||||
Any,
|
Any,
|
||||||
|
|
||||||
/// Only the listed items are a match
|
/// Only the listed items are a match
|
||||||
Items(Vec<$item>),
|
Items(Vec<$item>),
|
||||||
}
|
}
|
||||||
|
|
|
@ -53,7 +53,7 @@ use super::{Header, HeaderName, HeaderValue, InvalidHeaderValue, TryIntoHeaderVa
|
||||||
/// builder.insert_header(Range::bytes(1, 100));
|
/// builder.insert_header(Range::bytes(1, 100));
|
||||||
/// builder.insert_header(Range::bytes_multi(vec![(1, 100), (200, 300)]));
|
/// builder.insert_header(Range::bytes_multi(vec![(1, 100), (200, 300)]));
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(PartialEq, Clone, Debug)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum Range {
|
pub enum Range {
|
||||||
/// Byte range.
|
/// Byte range.
|
||||||
Bytes(Vec<ByteRangeSpec>),
|
Bytes(Vec<ByteRangeSpec>),
|
||||||
|
|
|
@ -2,7 +2,6 @@ use std::{convert::Infallible, net::SocketAddr};
|
||||||
|
|
||||||
use actix_utils::future::{err, ok, Ready};
|
use actix_utils::future::{err, ok, Ready};
|
||||||
use derive_more::{Display, Error};
|
use derive_more::{Display, Error};
|
||||||
use once_cell::sync::Lazy;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
dev::{AppConfig, Payload, RequestHead},
|
dev::{AppConfig, Payload, RequestHead},
|
||||||
|
@ -13,12 +12,9 @@ use crate::{
|
||||||
FromRequest, HttpRequest, ResponseError,
|
FromRequest, HttpRequest, ResponseError,
|
||||||
};
|
};
|
||||||
|
|
||||||
static X_FORWARDED_FOR: Lazy<HeaderName> =
|
static X_FORWARDED_FOR: HeaderName = HeaderName::from_static("x-forwarded-for");
|
||||||
Lazy::new(|| HeaderName::from_static("x-forwarded-for"));
|
static X_FORWARDED_HOST: HeaderName = HeaderName::from_static("x-forwarded-host");
|
||||||
static X_FORWARDED_HOST: Lazy<HeaderName> =
|
static X_FORWARDED_PROTO: HeaderName = HeaderName::from_static("x-forwarded-proto");
|
||||||
Lazy::new(|| HeaderName::from_static("x-forwarded-host"));
|
|
||||||
static X_FORWARDED_PROTO: Lazy<HeaderName> =
|
|
||||||
Lazy::new(|| HeaderName::from_static("x-forwarded-proto"));
|
|
||||||
|
|
||||||
/// Trim whitespace then any quote marks.
|
/// Trim whitespace then any quote marks.
|
||||||
fn unquote(val: &str) -> &str {
|
fn unquote(val: &str) -> &str {
|
||||||
|
@ -117,21 +113,21 @@ impl ConnectionInfo {
|
||||||
}
|
}
|
||||||
|
|
||||||
let scheme = scheme
|
let scheme = scheme
|
||||||
.or_else(|| first_header_value(req, &*X_FORWARDED_PROTO))
|
.or_else(|| first_header_value(req, &X_FORWARDED_PROTO))
|
||||||
.or_else(|| req.uri.scheme().map(Scheme::as_str))
|
.or_else(|| req.uri.scheme().map(Scheme::as_str))
|
||||||
.or_else(|| Some("https").filter(|_| cfg.secure()))
|
.or_else(|| Some("https").filter(|_| cfg.secure()))
|
||||||
.unwrap_or("http")
|
.unwrap_or("http")
|
||||||
.to_owned();
|
.to_owned();
|
||||||
|
|
||||||
let host = host
|
let host = host
|
||||||
.or_else(|| first_header_value(req, &*X_FORWARDED_HOST))
|
.or_else(|| first_header_value(req, &X_FORWARDED_HOST))
|
||||||
.or_else(|| req.headers.get(&header::HOST)?.to_str().ok())
|
.or_else(|| req.headers.get(&header::HOST)?.to_str().ok())
|
||||||
.or_else(|| req.uri.authority().map(Authority::as_str))
|
.or_else(|| req.uri.authority().map(Authority::as_str))
|
||||||
.unwrap_or_else(|| cfg.host())
|
.unwrap_or_else(|| cfg.host())
|
||||||
.to_owned();
|
.to_owned();
|
||||||
|
|
||||||
let realip_remote_addr = realip_remote_addr
|
let realip_remote_addr = realip_remote_addr
|
||||||
.or_else(|| first_header_value(req, &*X_FORWARDED_FOR))
|
.or_else(|| first_header_value(req, &X_FORWARDED_FOR))
|
||||||
.map(str::to_owned);
|
.map(str::to_owned);
|
||||||
|
|
||||||
let peer_addr = req.peer_addr.map(|addr| addr.ip().to_string());
|
let peer_addr = req.peer_addr.map(|addr| addr.ip().to_string());
|
||||||
|
|
|
@ -220,32 +220,25 @@ static SUPPORTED_ENCODINGS_STRING: Lazy<String> = Lazy::new(|| {
|
||||||
encoding.join(", ")
|
encoding.join(", ")
|
||||||
});
|
});
|
||||||
|
|
||||||
static SUPPORTED_ENCODINGS: Lazy<Vec<Encoding>> = Lazy::new(|| {
|
static SUPPORTED_ENCODINGS: &[Encoding] = &[
|
||||||
let mut encodings = vec![Encoding::identity()];
|
Encoding::identity(),
|
||||||
|
|
||||||
#[cfg(feature = "compress-brotli")]
|
#[cfg(feature = "compress-brotli")]
|
||||||
{
|
{
|
||||||
encodings.push(Encoding::brotli());
|
Encoding::brotli()
|
||||||
}
|
},
|
||||||
|
|
||||||
#[cfg(feature = "compress-gzip")]
|
#[cfg(feature = "compress-gzip")]
|
||||||
{
|
{
|
||||||
encodings.push(Encoding::gzip());
|
Encoding::gzip()
|
||||||
encodings.push(Encoding::deflate());
|
},
|
||||||
}
|
#[cfg(feature = "compress-gzip")]
|
||||||
|
{
|
||||||
|
Encoding::deflate()
|
||||||
|
},
|
||||||
#[cfg(feature = "compress-zstd")]
|
#[cfg(feature = "compress-zstd")]
|
||||||
{
|
{
|
||||||
encodings.push(Encoding::zstd());
|
Encoding::zstd()
|
||||||
}
|
},
|
||||||
|
];
|
||||||
assert!(
|
|
||||||
!encodings.is_empty(),
|
|
||||||
"encodings can not be empty unless __compress feature has been explicitly enabled by itself"
|
|
||||||
);
|
|
||||||
|
|
||||||
encodings
|
|
||||||
});
|
|
||||||
|
|
||||||
// move cfg(feature) to prevents_double_compressing if more tests are added
|
// move cfg(feature) to prevents_double_compressing if more tests are added
|
||||||
#[cfg(feature = "compress-gzip")]
|
#[cfg(feature = "compress-gzip")]
|
||||||
|
@ -326,6 +319,7 @@ mod tests {
|
||||||
.to_request();
|
.to_request();
|
||||||
let res = test::call_service(&app, req).await;
|
let res = test::call_service(&app, req).await;
|
||||||
assert_eq!(res.status(), StatusCode::OK);
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
|
#[allow(clippy::mutable_key_type)]
|
||||||
let vary_headers = res.headers().get_all(header::VARY).collect::<HashSet<_>>();
|
let vary_headers = res.headers().get_all(header::VARY).collect::<HashSet<_>>();
|
||||||
assert!(vary_headers.contains(&HeaderValue::from_static("x-test")));
|
assert!(vary_headers.contains(&HeaderValue::from_static("x-test")));
|
||||||
assert!(vary_headers.contains(&HeaderValue::from_static("accept-encoding")));
|
assert!(vary_headers.contains(&HeaderValue::from_static("accept-encoding")));
|
||||||
|
|
|
@ -253,7 +253,7 @@ impl HttpRequest {
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn connection_info(&self) -> Ref<'_, ConnectionInfo> {
|
pub fn connection_info(&self) -> Ref<'_, ConnectionInfo> {
|
||||||
if !self.extensions().contains::<ConnectionInfo>() {
|
if !self.extensions().contains::<ConnectionInfo>() {
|
||||||
let info = ConnectionInfo::new(self.head(), &*self.app_config());
|
let info = ConnectionInfo::new(self.head(), self.app_config());
|
||||||
self.extensions_mut().insert(info);
|
self.extensions_mut().insert(info);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -311,6 +311,7 @@ impl HttpRequest {
|
||||||
|
|
||||||
/// Load request cookies.
|
/// Load request cookies.
|
||||||
#[cfg(feature = "cookies")]
|
#[cfg(feature = "cookies")]
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "cookies")))]
|
||||||
pub fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
|
pub fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
|
||||||
use actix_http::header::COOKIE;
|
use actix_http::header::COOKIE;
|
||||||
|
|
||||||
|
@ -334,6 +335,7 @@ impl HttpRequest {
|
||||||
|
|
||||||
/// Return request cookie.
|
/// Return request cookie.
|
||||||
#[cfg(feature = "cookies")]
|
#[cfg(feature = "cookies")]
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "cookies")))]
|
||||||
pub fn cookie(&self, name: &str) -> Option<Cookie<'static>> {
|
pub fn cookie(&self, name: &str) -> Option<Cookie<'static>> {
|
||||||
if let Ok(cookies) = self.cookies() {
|
if let Ok(cookies) = self.cookies() {
|
||||||
for cookie in cookies.iter() {
|
for cookie in cookies.iter() {
|
||||||
|
|
|
@ -41,17 +41,22 @@ struct Config {
|
||||||
///
|
///
|
||||||
/// Create new HTTP server with application factory.
|
/// Create new HTTP server with application factory.
|
||||||
///
|
///
|
||||||
|
/// # HTTP/2
|
||||||
|
/// Currently, HTTP/2 is only supported when using TLS (HTTPS). See `bind_rustls` or `bind_openssl`.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
/// ```no_run
|
/// ```no_run
|
||||||
/// use actix_web::{web, App, HttpResponse, HttpServer};
|
/// use actix_web::{web, App, HttpResponse, HttpServer};
|
||||||
///
|
///
|
||||||
/// #[actix_rt::main]
|
/// #[actix_web::main]
|
||||||
/// async fn main() -> std::io::Result<()> {
|
/// async fn main() -> std::io::Result<()> {
|
||||||
/// HttpServer::new(
|
/// HttpServer::new(|| {
|
||||||
/// || App::new()
|
/// App::new()
|
||||||
/// .service(web::resource("/").to(|| HttpResponse::Ok())))
|
/// .service(web::resource("/").to(|| async { "hello world" }))
|
||||||
/// .bind("127.0.0.1:59090")?
|
/// })
|
||||||
/// .run()
|
/// .bind(("127.0.0.1", 8080))?
|
||||||
/// .await
|
/// .run()
|
||||||
|
/// .await
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub struct HttpServer<F, I, S, B>
|
pub struct HttpServer<F, I, S, B>
|
||||||
|
@ -108,32 +113,7 @@ where
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets function that will be called once before each connection is handled.
|
/// Sets number of workers to start (per bind address).
|
||||||
/// It will receive a `&std::any::Any`, which contains underlying connection type and an
|
|
||||||
/// [Extensions] container so that connection data can be accessed in middleware and handlers.
|
|
||||||
///
|
|
||||||
/// # Connection Types
|
|
||||||
/// - `actix_tls::accept::openssl::TlsStream<actix_web::rt::net::TcpStream>` when using openssl.
|
|
||||||
/// - `actix_tls::accept::rustls::TlsStream<actix_web::rt::net::TcpStream>` when using rustls.
|
|
||||||
/// - `actix_web::rt::net::TcpStream` when no encryption is used.
|
|
||||||
///
|
|
||||||
/// See the `on_connect` example for additional details.
|
|
||||||
pub fn on_connect<CB>(self, f: CB) -> HttpServer<F, I, S, B>
|
|
||||||
where
|
|
||||||
CB: Fn(&dyn Any, &mut Extensions) + Send + Sync + 'static,
|
|
||||||
{
|
|
||||||
HttpServer {
|
|
||||||
factory: self.factory,
|
|
||||||
config: self.config,
|
|
||||||
backlog: self.backlog,
|
|
||||||
sockets: self.sockets,
|
|
||||||
builder: self.builder,
|
|
||||||
on_connect_fn: Some(Arc::new(f)),
|
|
||||||
_phantom: PhantomData,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set number of workers to start.
|
|
||||||
///
|
///
|
||||||
/// By default, the number of available physical CPUs is used as the worker count.
|
/// By default, the number of available physical CPUs is used as the worker count.
|
||||||
pub fn workers(mut self, num: usize) -> Self {
|
pub fn workers(mut self, num: usize) -> Self {
|
||||||
|
@ -141,23 +121,30 @@ where
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set the maximum number of pending connections.
|
/// Sets server keep-alive preference.
|
||||||
///
|
///
|
||||||
/// This refers to the number of clients that can be waiting to be served.
|
/// By default keep-alive is set to 5 seconds.
|
||||||
/// Exceeding this number results in the client getting an error when
|
pub fn keep_alive<T: Into<KeepAlive>>(self, val: T) -> Self {
|
||||||
/// attempting to connect. It should only affect servers under significant
|
self.config.lock().unwrap().keep_alive = val.into();
|
||||||
/// load.
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the maximum number of pending connections.
|
||||||
///
|
///
|
||||||
/// Generally set in the 64-2048 range. Default value is 2048.
|
/// This refers to the number of clients that can be waiting to be served. Exceeding this number
|
||||||
|
/// results in the client getting an error when attempting to connect. It should only affect
|
||||||
|
/// servers under significant load.
|
||||||
///
|
///
|
||||||
/// This method should be called before `bind()` method call.
|
/// Generally set in the 64–2048 range. Default value is 2048.
|
||||||
|
///
|
||||||
|
/// This method will have no effect if called after a `bind()`.
|
||||||
pub fn backlog(mut self, backlog: u32) -> Self {
|
pub fn backlog(mut self, backlog: u32) -> Self {
|
||||||
self.backlog = backlog;
|
self.backlog = backlog;
|
||||||
self.builder = self.builder.backlog(backlog);
|
self.builder = self.builder.backlog(backlog);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets the maximum per-worker number of concurrent connections.
|
/// Sets the per-worker maximum number of concurrent connections.
|
||||||
///
|
///
|
||||||
/// All socket listeners will stop accepting connections when this limit is reached for
|
/// All socket listeners will stop accepting connections when this limit is reached for
|
||||||
/// each worker.
|
/// each worker.
|
||||||
|
@ -168,7 +155,7 @@ where
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets the maximum per-worker concurrent connection establish process.
|
/// Sets the per-worker maximum concurrent TLS connection limit.
|
||||||
///
|
///
|
||||||
/// All listeners will stop accepting connections when this limit is reached. It can be used to
|
/// All listeners will stop accepting connections when this limit is reached. It can be used to
|
||||||
/// limit the global TLS CPU usage.
|
/// limit the global TLS CPU usage.
|
||||||
|
@ -181,7 +168,7 @@ where
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set max number of threads for each worker's blocking task thread pool.
|
/// Sets max number of threads for each worker's blocking task thread pool.
|
||||||
///
|
///
|
||||||
/// One thread pool is set up **per worker**; not shared across workers.
|
/// One thread pool is set up **per worker**; not shared across workers.
|
||||||
///
|
///
|
||||||
|
@ -191,19 +178,10 @@ where
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set server keep-alive setting.
|
/// Sets server client timeout for first request.
|
||||||
///
|
///
|
||||||
/// By default keep alive is set to a 5 seconds.
|
/// Defines a timeout for reading client request head. If a client does not transmit the entire
|
||||||
pub fn keep_alive<T: Into<KeepAlive>>(self, val: T) -> Self {
|
/// set headers within this time, the request is terminated with a 408 (Request Timeout) error.
|
||||||
self.config.lock().unwrap().keep_alive = val.into();
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set server client timeout in milliseconds for first request.
|
|
||||||
///
|
|
||||||
/// Defines a timeout for reading client request header. If a client does not transmit
|
|
||||||
/// the entire set headers within this time, the request is terminated with
|
|
||||||
/// the 408 (Request Time-out) error.
|
|
||||||
///
|
///
|
||||||
/// To disable timeout set value to 0.
|
/// To disable timeout set value to 0.
|
||||||
///
|
///
|
||||||
|
@ -219,10 +197,10 @@ where
|
||||||
self.client_request_timeout(dur)
|
self.client_request_timeout(dur)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set server connection shutdown timeout in milliseconds.
|
/// Sets server connection shutdown timeout.
|
||||||
///
|
///
|
||||||
/// Defines a timeout for shutdown connection. If a shutdown procedure does not complete
|
/// Defines a timeout for connection shutdown. If a shutdown procedure does not complete within
|
||||||
/// within this time, the request is dropped.
|
/// this time, the request is dropped.
|
||||||
///
|
///
|
||||||
/// To disable timeout set value to 0.
|
/// To disable timeout set value to 0.
|
||||||
///
|
///
|
||||||
|
@ -232,10 +210,10 @@ where
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set TLS handshake timeout.
|
/// Sets TLS handshake timeout.
|
||||||
///
|
///
|
||||||
/// Defines a timeout for TLS handshake. If the TLS handshake does not complete
|
/// Defines a timeout for TLS handshake. If the TLS handshake does not complete within this
|
||||||
/// within this time, the connection is closed.
|
/// time, the connection is closed.
|
||||||
///
|
///
|
||||||
/// By default handshake timeout is set to 3000 milliseconds.
|
/// By default handshake timeout is set to 3000 milliseconds.
|
||||||
#[cfg(any(feature = "openssl", feature = "rustls"))]
|
#[cfg(any(feature = "openssl", feature = "rustls"))]
|
||||||
|
@ -256,35 +234,61 @@ where
|
||||||
self.client_disconnect_timeout(Duration::from_millis(dur))
|
self.client_disconnect_timeout(Duration::from_millis(dur))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set server host name.
|
/// Sets function that will be called once before each connection is handled.
|
||||||
///
|
///
|
||||||
/// Host name is used by application router as a hostname for url generation.
|
/// It will receive a `&std::any::Any`, which contains underlying connection type and an
|
||||||
/// Check [ConnectionInfo](super::dev::ConnectionInfo::host())
|
/// [Extensions] container so that connection data can be accessed in middleware and handlers.
|
||||||
/// documentation for more information.
|
|
||||||
///
|
///
|
||||||
/// By default host name is set to a "localhost" value.
|
/// # Connection Types
|
||||||
|
/// - `actix_tls::accept::openssl::TlsStream<actix_web::rt::net::TcpStream>` when using OpenSSL.
|
||||||
|
/// - `actix_tls::accept::rustls::TlsStream<actix_web::rt::net::TcpStream>` when using Rustls.
|
||||||
|
/// - `actix_web::rt::net::TcpStream` when no encryption is used.
|
||||||
|
///
|
||||||
|
/// See the `on_connect` example for additional details.
|
||||||
|
pub fn on_connect<CB>(self, f: CB) -> HttpServer<F, I, S, B>
|
||||||
|
where
|
||||||
|
CB: Fn(&dyn Any, &mut Extensions) + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
HttpServer {
|
||||||
|
factory: self.factory,
|
||||||
|
config: self.config,
|
||||||
|
backlog: self.backlog,
|
||||||
|
sockets: self.sockets,
|
||||||
|
builder: self.builder,
|
||||||
|
on_connect_fn: Some(Arc::new(f)),
|
||||||
|
_phantom: PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets server host name.
|
||||||
|
///
|
||||||
|
/// Host name is used by application router as a hostname for url generation. Check
|
||||||
|
/// [`ConnectionInfo`](crate::dev::ConnectionInfo::host()) docs for more info.
|
||||||
|
///
|
||||||
|
/// By default, hostname is set to "localhost".
|
||||||
pub fn server_hostname<T: AsRef<str>>(self, val: T) -> Self {
|
pub fn server_hostname<T: AsRef<str>>(self, val: T) -> Self {
|
||||||
self.config.lock().unwrap().host = Some(val.as_ref().to_owned());
|
self.config.lock().unwrap().host = Some(val.as_ref().to_owned());
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stop Actix `System` after server shutdown.
|
/// Flags the `System` to exit after server shutdown.
|
||||||
|
///
|
||||||
|
/// Does nothing when running under `#[tokio::main]` runtime.
|
||||||
pub fn system_exit(mut self) -> Self {
|
pub fn system_exit(mut self) -> Self {
|
||||||
self.builder = self.builder.system_exit();
|
self.builder = self.builder.system_exit();
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Disable signal handling
|
/// Disables signal handling.
|
||||||
pub fn disable_signals(mut self) -> Self {
|
pub fn disable_signals(mut self) -> Self {
|
||||||
self.builder = self.builder.disable_signals();
|
self.builder = self.builder.disable_signals();
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Timeout for graceful workers shutdown.
|
/// Sets timeout for graceful worker shutdown of workers.
|
||||||
///
|
///
|
||||||
/// After receiving a stop signal, workers have this much time to finish
|
/// After receiving a stop signal, workers have this much time to finish serving requests.
|
||||||
/// serving requests. Workers still alive after the timeout are force
|
/// Workers still alive after the timeout are force dropped.
|
||||||
/// dropped.
|
|
||||||
///
|
///
|
||||||
/// By default shutdown timeout sets to 30 seconds.
|
/// By default shutdown timeout sets to 30 seconds.
|
||||||
pub fn shutdown_timeout(mut self, sec: u64) -> Self {
|
pub fn shutdown_timeout(mut self, sec: u64) -> Self {
|
||||||
|
@ -292,33 +296,141 @@ where
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get addresses of bound sockets.
|
/// Returns addresses of bound sockets.
|
||||||
pub fn addrs(&self) -> Vec<net::SocketAddr> {
|
pub fn addrs(&self) -> Vec<net::SocketAddr> {
|
||||||
self.sockets.iter().map(|s| s.addr).collect()
|
self.sockets.iter().map(|s| s.addr).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get addresses of bound sockets and the scheme for it.
|
/// Returns addresses of bound sockets and the scheme for it.
|
||||||
///
|
///
|
||||||
/// This is useful when the server is bound from different sources
|
/// This is useful when the server is bound from different sources with some sockets listening
|
||||||
/// with some sockets listening on HTTP and some listening on HTTPS
|
/// on HTTP and some listening on HTTPS and the user should be presented with an enumeration of
|
||||||
/// and the user should be presented with an enumeration of which
|
/// which socket requires which protocol.
|
||||||
/// socket requires which protocol.
|
|
||||||
pub fn addrs_with_scheme(&self) -> Vec<(net::SocketAddr, &str)> {
|
pub fn addrs_with_scheme(&self) -> Vec<(net::SocketAddr, &str)> {
|
||||||
self.sockets.iter().map(|s| (s.addr, s.scheme)).collect()
|
self.sockets.iter().map(|s| (s.addr, s.scheme)).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Use listener for accepting incoming connection requests
|
/// Resolves socket address(es) and binds server to created listener(s).
|
||||||
///
|
///
|
||||||
/// HttpServer does not change any configuration for TcpListener,
|
/// # Hostname Resolution
|
||||||
/// it needs to be configured before passing it to listen() method.
|
/// When `addr` includes a hostname, it is possible for this method to bind to both the IPv4 and
|
||||||
|
/// IPv6 addresses that result from a DNS lookup. You can test this by passing `localhost:8080`
|
||||||
|
/// and noting that the server binds to `127.0.0.1:8080` _and_ `[::1]:8080`. To bind additional
|
||||||
|
/// addresses, call this method multiple times.
|
||||||
|
///
|
||||||
|
/// Note that, if a DNS lookup is required, resolving hostnames is a blocking operation.
|
||||||
|
///
|
||||||
|
/// # Typical Usage
|
||||||
|
/// In general, use `127.0.0.1:<port>` when testing locally and `0.0.0.0:<port>` when deploying
|
||||||
|
/// (with or without a reverse proxy or load balancer) so that the server is accessible.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// Returns an `io::Error` if:
|
||||||
|
/// - `addrs` cannot be resolved into one or more socket addresses;
|
||||||
|
/// - all the resolved socket addresses are already bound.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
/// ```
|
||||||
|
/// # use actix_web::{App, HttpServer};
|
||||||
|
/// # fn inner() -> std::io::Result<()> {
|
||||||
|
/// HttpServer::new(|| App::new())
|
||||||
|
/// .bind(("127.0.0.1", 8080))?
|
||||||
|
/// .bind("[::1]:9000")?
|
||||||
|
/// # ; Ok(()) }
|
||||||
|
/// ```
|
||||||
|
pub fn bind<A: net::ToSocketAddrs>(mut self, addrs: A) -> io::Result<Self> {
|
||||||
|
let sockets = self.bind2(addrs)?;
|
||||||
|
|
||||||
|
for lst in sockets {
|
||||||
|
self = self.listen(lst)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bind2<A: net::ToSocketAddrs>(&self, addrs: A) -> io::Result<Vec<net::TcpListener>> {
|
||||||
|
let mut err = None;
|
||||||
|
let mut success = false;
|
||||||
|
let mut sockets = Vec::new();
|
||||||
|
|
||||||
|
for addr in addrs.to_socket_addrs()? {
|
||||||
|
match create_tcp_listener(addr, self.backlog) {
|
||||||
|
Ok(lst) => {
|
||||||
|
success = true;
|
||||||
|
sockets.push(lst);
|
||||||
|
}
|
||||||
|
Err(e) => err = Some(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if success {
|
||||||
|
Ok(sockets)
|
||||||
|
} else if let Some(e) = err.take() {
|
||||||
|
Err(e)
|
||||||
|
} else {
|
||||||
|
Err(io::Error::new(
|
||||||
|
io::ErrorKind::Other,
|
||||||
|
"Can not bind to address.",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves socket address(es) and binds server to created listener(s) for TLS connections
|
||||||
|
/// using Rustls.
|
||||||
|
///
|
||||||
|
/// See [`bind()`](Self::bind) for more details on `addrs` argument.
|
||||||
|
///
|
||||||
|
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
|
||||||
|
#[cfg(feature = "rustls")]
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "rustls")))]
|
||||||
|
pub fn bind_rustls<A: net::ToSocketAddrs>(
|
||||||
|
mut self,
|
||||||
|
addrs: A,
|
||||||
|
config: RustlsServerConfig,
|
||||||
|
) -> io::Result<Self> {
|
||||||
|
let sockets = self.bind2(addrs)?;
|
||||||
|
for lst in sockets {
|
||||||
|
self = self.listen_rustls_inner(lst, config.clone())?;
|
||||||
|
}
|
||||||
|
Ok(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves socket address(es) and binds server to created listener(s) for TLS connections
|
||||||
|
/// using OpenSSL.
|
||||||
|
///
|
||||||
|
/// See [`bind()`](Self::bind) for more details on `addrs` argument.
|
||||||
|
///
|
||||||
|
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
|
||||||
|
#[cfg(feature = "openssl")]
|
||||||
|
#[cfg_attr(docsrs, doc(cfg(feature = "openssl")))]
|
||||||
|
pub fn bind_openssl<A>(mut self, addrs: A, builder: SslAcceptorBuilder) -> io::Result<Self>
|
||||||
|
where
|
||||||
|
A: net::ToSocketAddrs,
|
||||||
|
{
|
||||||
|
let sockets = self.bind2(addrs)?;
|
||||||
|
let acceptor = openssl_acceptor(builder)?;
|
||||||
|
|
||||||
|
for lst in sockets {
|
||||||
|
self = self.listen_openssl_inner(lst, acceptor.clone())?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Binds to existing listener for accepting incoming connection requests.
|
||||||
|
///
|
||||||
|
/// No changes are made to `lst`'s configuration. Ensure it is configured properly before
|
||||||
|
/// passing ownership to `listen()`.
|
||||||
pub fn listen(mut self, lst: net::TcpListener) -> io::Result<Self> {
|
pub fn listen(mut self, lst: net::TcpListener) -> io::Result<Self> {
|
||||||
let cfg = self.config.clone();
|
let cfg = self.config.clone();
|
||||||
let factory = self.factory.clone();
|
let factory = self.factory.clone();
|
||||||
let addr = lst.local_addr().unwrap();
|
let addr = lst.local_addr().unwrap();
|
||||||
|
|
||||||
self.sockets.push(Socket {
|
self.sockets.push(Socket {
|
||||||
addr,
|
addr,
|
||||||
scheme: "http",
|
scheme: "http",
|
||||||
});
|
});
|
||||||
|
|
||||||
let on_connect_fn = self.on_connect_fn.clone();
|
let on_connect_fn = self.on_connect_fn.clone();
|
||||||
|
|
||||||
self.builder =
|
self.builder =
|
||||||
|
@ -351,74 +463,13 @@ where
|
||||||
Ok(self)
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "openssl")]
|
/// Binds to existing listener for accepting incoming TLS connection requests using Rustls.
|
||||||
/// Use listener for accepting incoming tls connection requests
|
|
||||||
///
|
///
|
||||||
/// This method sets alpn protocols to "h2" and "http/1.1"
|
/// See [`listen()`](Self::listen) for more details on the `lst` argument.
|
||||||
pub fn listen_openssl(
|
///
|
||||||
self,
|
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
|
||||||
lst: net::TcpListener,
|
|
||||||
builder: SslAcceptorBuilder,
|
|
||||||
) -> io::Result<Self> {
|
|
||||||
self.listen_ssl_inner(lst, openssl_acceptor(builder)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "openssl")]
|
|
||||||
fn listen_ssl_inner(
|
|
||||||
mut self,
|
|
||||||
lst: net::TcpListener,
|
|
||||||
acceptor: SslAcceptor,
|
|
||||||
) -> io::Result<Self> {
|
|
||||||
let factory = self.factory.clone();
|
|
||||||
let cfg = self.config.clone();
|
|
||||||
let addr = lst.local_addr().unwrap();
|
|
||||||
self.sockets.push(Socket {
|
|
||||||
addr,
|
|
||||||
scheme: "https",
|
|
||||||
});
|
|
||||||
|
|
||||||
let on_connect_fn = self.on_connect_fn.clone();
|
|
||||||
|
|
||||||
self.builder =
|
|
||||||
self.builder
|
|
||||||
.listen(format!("actix-web-service-{}", addr), lst, move || {
|
|
||||||
let c = cfg.lock().unwrap();
|
|
||||||
let host = c.host.clone().unwrap_or_else(|| format!("{}", addr));
|
|
||||||
|
|
||||||
let svc = HttpService::build()
|
|
||||||
.keep_alive(c.keep_alive)
|
|
||||||
.client_request_timeout(c.client_request_timeout)
|
|
||||||
.client_disconnect_timeout(c.client_disconnect_timeout)
|
|
||||||
.local_addr(addr);
|
|
||||||
|
|
||||||
let svc = if let Some(handler) = on_connect_fn.clone() {
|
|
||||||
svc.on_connect_ext(move |io: &_, ext: _| (handler)(io as &dyn Any, ext))
|
|
||||||
} else {
|
|
||||||
svc
|
|
||||||
};
|
|
||||||
|
|
||||||
let fac = factory()
|
|
||||||
.into_factory()
|
|
||||||
.map_err(|err| err.into().error_response());
|
|
||||||
|
|
||||||
let acceptor_config = match c.tls_handshake_timeout {
|
|
||||||
Some(dur) => TlsAcceptorConfig::default().handshake_timeout(dur),
|
|
||||||
None => TlsAcceptorConfig::default(),
|
|
||||||
};
|
|
||||||
|
|
||||||
svc.finish(map_config(fac, move |_| {
|
|
||||||
AppConfig::new(true, host.clone(), addr)
|
|
||||||
}))
|
|
||||||
.openssl_with_config(acceptor.clone(), acceptor_config)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "rustls")]
|
#[cfg(feature = "rustls")]
|
||||||
/// Use listener for accepting incoming tls connection requests
|
#[cfg_attr(docsrs, doc(cfg(feature = "rustls")))]
|
||||||
///
|
|
||||||
/// This method prepends alpn protocols "h2" and "http/1.1" to configured ones
|
|
||||||
pub fn listen_rustls(
|
pub fn listen_rustls(
|
||||||
self,
|
self,
|
||||||
lst: net::TcpListener,
|
lst: net::TcpListener,
|
||||||
|
@ -478,82 +529,125 @@ where
|
||||||
Ok(self)
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The socket address to bind
|
/// Binds to existing listener for accepting incoming TLS connection requests using OpenSSL.
|
||||||
///
|
///
|
||||||
/// To bind multiple addresses this method can be called multiple times.
|
/// See [`listen()`](Self::listen) for more details on the `lst` argument.
|
||||||
pub fn bind<A: net::ToSocketAddrs>(mut self, addr: A) -> io::Result<Self> {
|
///
|
||||||
let sockets = self.bind2(addr)?;
|
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
|
||||||
|
#[cfg(feature = "openssl")]
|
||||||
for lst in sockets {
|
#[cfg_attr(docsrs, doc(cfg(feature = "openssl")))]
|
||||||
self = self.listen(lst)?;
|
pub fn listen_openssl(
|
||||||
}
|
self,
|
||||||
|
lst: net::TcpListener,
|
||||||
Ok(self)
|
builder: SslAcceptorBuilder,
|
||||||
}
|
) -> io::Result<Self> {
|
||||||
|
self.listen_openssl_inner(lst, openssl_acceptor(builder)?)
|
||||||
fn bind2<A: net::ToSocketAddrs>(&self, addr: A) -> io::Result<Vec<net::TcpListener>> {
|
|
||||||
let mut err = None;
|
|
||||||
let mut success = false;
|
|
||||||
let mut sockets = Vec::new();
|
|
||||||
|
|
||||||
for addr in addr.to_socket_addrs()? {
|
|
||||||
match create_tcp_listener(addr, self.backlog) {
|
|
||||||
Ok(lst) => {
|
|
||||||
success = true;
|
|
||||||
sockets.push(lst);
|
|
||||||
}
|
|
||||||
Err(e) => err = Some(e),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if success {
|
|
||||||
Ok(sockets)
|
|
||||||
} else if let Some(e) = err.take() {
|
|
||||||
Err(e)
|
|
||||||
} else {
|
|
||||||
Err(io::Error::new(
|
|
||||||
io::ErrorKind::Other,
|
|
||||||
"Can not bind to address.",
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "openssl")]
|
#[cfg(feature = "openssl")]
|
||||||
/// Start listening for incoming tls connections.
|
fn listen_openssl_inner(
|
||||||
///
|
|
||||||
/// This method sets alpn protocols to "h2" and "http/1.1"
|
|
||||||
pub fn bind_openssl<A>(mut self, addr: A, builder: SslAcceptorBuilder) -> io::Result<Self>
|
|
||||||
where
|
|
||||||
A: net::ToSocketAddrs,
|
|
||||||
{
|
|
||||||
let sockets = self.bind2(addr)?;
|
|
||||||
let acceptor = openssl_acceptor(builder)?;
|
|
||||||
|
|
||||||
for lst in sockets {
|
|
||||||
self = self.listen_ssl_inner(lst, acceptor.clone())?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "rustls")]
|
|
||||||
/// Start listening for incoming tls connections.
|
|
||||||
///
|
|
||||||
/// This method prepends alpn protocols "h2" and "http/1.1" to configured ones
|
|
||||||
pub fn bind_rustls<A: net::ToSocketAddrs>(
|
|
||||||
mut self,
|
mut self,
|
||||||
addr: A,
|
lst: net::TcpListener,
|
||||||
config: RustlsServerConfig,
|
acceptor: SslAcceptor,
|
||||||
) -> io::Result<Self> {
|
) -> io::Result<Self> {
|
||||||
let sockets = self.bind2(addr)?;
|
let factory = self.factory.clone();
|
||||||
for lst in sockets {
|
let cfg = self.config.clone();
|
||||||
self = self.listen_rustls_inner(lst, config.clone())?;
|
let addr = lst.local_addr().unwrap();
|
||||||
}
|
self.sockets.push(Socket {
|
||||||
|
addr,
|
||||||
|
scheme: "https",
|
||||||
|
});
|
||||||
|
|
||||||
|
let on_connect_fn = self.on_connect_fn.clone();
|
||||||
|
|
||||||
|
self.builder =
|
||||||
|
self.builder
|
||||||
|
.listen(format!("actix-web-service-{}", addr), lst, move || {
|
||||||
|
let c = cfg.lock().unwrap();
|
||||||
|
let host = c.host.clone().unwrap_or_else(|| format!("{}", addr));
|
||||||
|
|
||||||
|
let svc = HttpService::build()
|
||||||
|
.keep_alive(c.keep_alive)
|
||||||
|
.client_request_timeout(c.client_request_timeout)
|
||||||
|
.client_disconnect_timeout(c.client_disconnect_timeout)
|
||||||
|
.local_addr(addr);
|
||||||
|
|
||||||
|
let svc = if let Some(handler) = on_connect_fn.clone() {
|
||||||
|
svc.on_connect_ext(move |io: &_, ext: _| (handler)(io as &dyn Any, ext))
|
||||||
|
} else {
|
||||||
|
svc
|
||||||
|
};
|
||||||
|
|
||||||
|
let fac = factory()
|
||||||
|
.into_factory()
|
||||||
|
.map_err(|err| err.into().error_response());
|
||||||
|
|
||||||
|
// false positive lint (?)
|
||||||
|
#[allow(clippy::significant_drop_in_scrutinee)]
|
||||||
|
let acceptor_config = match c.tls_handshake_timeout {
|
||||||
|
Some(dur) => TlsAcceptorConfig::default().handshake_timeout(dur),
|
||||||
|
None => TlsAcceptorConfig::default(),
|
||||||
|
};
|
||||||
|
|
||||||
|
svc.finish(map_config(fac, move |_| {
|
||||||
|
AppConfig::new(true, host.clone(), addr)
|
||||||
|
}))
|
||||||
|
.openssl_with_config(acceptor.clone(), acceptor_config)
|
||||||
|
})?;
|
||||||
|
|
||||||
Ok(self)
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Opens Unix Domain Socket (UDS) from `uds` path and binds server to created listener.
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub fn bind_uds<A>(mut self, uds_path: A) -> io::Result<Self>
|
||||||
|
where
|
||||||
|
A: AsRef<std::path::Path>,
|
||||||
|
{
|
||||||
|
use actix_http::Protocol;
|
||||||
|
use actix_rt::net::UnixStream;
|
||||||
|
use actix_service::{fn_service, ServiceFactoryExt as _};
|
||||||
|
|
||||||
|
let cfg = self.config.clone();
|
||||||
|
let factory = self.factory.clone();
|
||||||
|
let socket_addr =
|
||||||
|
net::SocketAddr::new(net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)), 8080);
|
||||||
|
|
||||||
|
self.sockets.push(Socket {
|
||||||
|
scheme: "http",
|
||||||
|
addr: socket_addr,
|
||||||
|
});
|
||||||
|
|
||||||
|
self.builder = self.builder.bind_uds(
|
||||||
|
format!("actix-web-service-{:?}", uds_path.as_ref()),
|
||||||
|
uds_path,
|
||||||
|
move || {
|
||||||
|
let c = cfg.lock().unwrap();
|
||||||
|
let config = AppConfig::new(
|
||||||
|
false,
|
||||||
|
c.host.clone().unwrap_or_else(|| format!("{}", socket_addr)),
|
||||||
|
socket_addr,
|
||||||
|
);
|
||||||
|
|
||||||
|
let fac = factory()
|
||||||
|
.into_factory()
|
||||||
|
.map_err(|err| err.into().error_response());
|
||||||
|
|
||||||
|
fn_service(|io: UnixStream| async { Ok((io, Protocol::Http1, None)) }).and_then(
|
||||||
|
HttpService::build()
|
||||||
|
.keep_alive(c.keep_alive)
|
||||||
|
.client_request_timeout(c.client_request_timeout)
|
||||||
|
.client_disconnect_timeout(c.client_disconnect_timeout)
|
||||||
|
.finish(map_config(fac, move |_| config.clone())),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
|
||||||
|
Ok(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Binds to existing Unix Domain Socket (UDS) listener.
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
/// Start listening for unix domain (UDS) connections on existing listener.
|
|
||||||
pub fn listen_uds(mut self, lst: std::os::unix::net::UnixListener) -> io::Result<Self> {
|
pub fn listen_uds(mut self, lst: std::os::unix::net::UnixListener) -> io::Result<Self> {
|
||||||
use actix_http::Protocol;
|
use actix_http::Protocol;
|
||||||
use actix_rt::net::UnixStream;
|
use actix_rt::net::UnixStream;
|
||||||
|
@ -600,54 +694,6 @@ where
|
||||||
})?;
|
})?;
|
||||||
Ok(self)
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Start listening for incoming unix domain connections.
|
|
||||||
#[cfg(unix)]
|
|
||||||
pub fn bind_uds<A>(mut self, addr: A) -> io::Result<Self>
|
|
||||||
where
|
|
||||||
A: AsRef<std::path::Path>,
|
|
||||||
{
|
|
||||||
use actix_http::Protocol;
|
|
||||||
use actix_rt::net::UnixStream;
|
|
||||||
use actix_service::{fn_service, ServiceFactoryExt as _};
|
|
||||||
|
|
||||||
let cfg = self.config.clone();
|
|
||||||
let factory = self.factory.clone();
|
|
||||||
let socket_addr =
|
|
||||||
net::SocketAddr::new(net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)), 8080);
|
|
||||||
|
|
||||||
self.sockets.push(Socket {
|
|
||||||
scheme: "http",
|
|
||||||
addr: socket_addr,
|
|
||||||
});
|
|
||||||
|
|
||||||
self.builder = self.builder.bind_uds(
|
|
||||||
format!("actix-web-service-{:?}", addr.as_ref()),
|
|
||||||
addr,
|
|
||||||
move || {
|
|
||||||
let c = cfg.lock().unwrap();
|
|
||||||
let config = AppConfig::new(
|
|
||||||
false,
|
|
||||||
c.host.clone().unwrap_or_else(|| format!("{}", socket_addr)),
|
|
||||||
socket_addr,
|
|
||||||
);
|
|
||||||
|
|
||||||
let fac = factory()
|
|
||||||
.into_factory()
|
|
||||||
.map_err(|err| err.into().error_response());
|
|
||||||
|
|
||||||
fn_service(|io: UnixStream| async { Ok((io, Protocol::Http1, None)) }).and_then(
|
|
||||||
HttpService::build()
|
|
||||||
.keep_alive(c.keep_alive)
|
|
||||||
.client_request_timeout(c.client_request_timeout)
|
|
||||||
.client_disconnect_timeout(c.client_disconnect_timeout)
|
|
||||||
.finish(map_config(fac, move |_| config.clone())),
|
|
||||||
)
|
|
||||||
},
|
|
||||||
)?;
|
|
||||||
|
|
||||||
Ok(self)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<F, I, S, B> HttpServer<F, I, S, B>
|
impl<F, I, S, B> HttpServer<F, I, S, B>
|
||||||
|
@ -663,25 +709,16 @@ where
|
||||||
{
|
{
|
||||||
/// Start listening for incoming connections.
|
/// Start listening for incoming connections.
|
||||||
///
|
///
|
||||||
/// This method starts number of HTTP workers in separate threads.
|
/// # Workers
|
||||||
/// For each address this method starts separate thread which does
|
/// This method starts a number of HTTP workers in separate threads. The number of workers in a
|
||||||
/// `accept()` in a loop.
|
/// set is defined by [`workers()`](Self::workers) or, by default, the number of the machine's
|
||||||
|
/// physical cores. One worker set is created for each socket address to be bound. For example,
|
||||||
|
/// if workers is set to 4, and there are 2 addresses to bind, then 8 worker threads will be
|
||||||
|
/// spawned.
|
||||||
///
|
///
|
||||||
/// This methods panics if no socket address can be bound or an `Actix` system is not yet
|
/// # Panics
|
||||||
/// configured.
|
/// This methods panics if no socket addresses were successfully bound or if no Tokio runtime
|
||||||
///
|
/// is set up.
|
||||||
/// ```no_run
|
|
||||||
/// use std::io;
|
|
||||||
/// use actix_web::{web, App, HttpResponse, HttpServer};
|
|
||||||
///
|
|
||||||
/// #[actix_rt::main]
|
|
||||||
/// async fn main() -> io::Result<()> {
|
|
||||||
/// HttpServer::new(|| App::new().service(web::resource("/").to(|| HttpResponse::Ok())))
|
|
||||||
/// .bind("127.0.0.1:0")?
|
|
||||||
/// .run()
|
|
||||||
/// .await
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
pub fn run(self) -> Server {
|
pub fn run(self) -> Server {
|
||||||
self.builder.run()
|
self.builder.run()
|
||||||
}
|
}
|
||||||
|
|
|
@ -73,7 +73,7 @@ use crate::{
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
pub enum Either<L, R> {
|
pub enum Either<L, R> {
|
||||||
/// A value of type `L`.
|
/// A value of type `L`.
|
||||||
Left(L),
|
Left(L),
|
||||||
|
|
|
@ -134,6 +134,7 @@ where
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Clone, Default)]
|
#[derive(Clone, Default)]
|
||||||
pub struct PathConfig {
|
pub struct PathConfig {
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
err_handler: Option<Arc<dyn Fn(PathError, &HttpRequest) -> Error + Send + Sync>>,
|
err_handler: Option<Arc<dyn Fn(PathError, &HttpRequest) -> Error + Send + Sync>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -169,6 +169,7 @@ impl<T: DeserializeOwned> FromRequest for Query<T> {
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Clone, Default)]
|
#[derive(Clone, Default)]
|
||||||
pub struct QueryConfig {
|
pub struct QueryConfig {
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
err_handler: Option<Arc<dyn Fn(QueryPayloadError, &HttpRequest) -> Error + Send + Sync>>,
|
err_handler: Option<Arc<dyn Fn(QueryPayloadError, &HttpRequest) -> Error + Send + Sync>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -94,9 +94,9 @@ trust-dns-resolver = { version = "0.21", optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-http = { version = "3", features = ["openssl"] }
|
actix-http = { version = "3", features = ["openssl"] }
|
||||||
actix-http-test = { version = "3.0.0-beta.13", features = ["openssl"] }
|
actix-http-test = { version = "3", features = ["openssl"] }
|
||||||
actix-server = "2"
|
actix-server = "2"
|
||||||
actix-test = { version = "0.1.0-beta.13", features = ["openssl", "rustls"] }
|
actix-test = { version = "0.1", features = ["openssl", "rustls"] }
|
||||||
actix-tls = { version = "3", features = ["openssl", "rustls"] }
|
actix-tls = { version = "3", features = ["openssl", "rustls"] }
|
||||||
actix-utils = "3"
|
actix-utils = "3"
|
||||||
actix-web = { version = "4", features = ["openssl"] }
|
actix-web = { version = "4", features = ["openssl"] }
|
||||||
|
|
|
@ -98,7 +98,7 @@ rm -f $README_FILE.bak
|
||||||
echo "manifest, changelog, and readme updated"
|
echo "manifest, changelog, and readme updated"
|
||||||
echo
|
echo
|
||||||
echo "check other references:"
|
echo "check other references:"
|
||||||
rg --glob='**/Cargo.toml' "\
|
rg --glob='**/{Cargo.toml,README.md}' "\
|
||||||
${PACKAGE_NAME} ?= ?\"[^\"]+\"\
|
${PACKAGE_NAME} ?= ?\"[^\"]+\"\
|
||||||
|${PACKAGE_NAME} ?=.*version ?= ?\"([^\"]+)\"\
|
|${PACKAGE_NAME} ?=.*version ?= ?\"([^\"]+)\"\
|
||||||
|package ?= ?\"${PACKAGE_NAME}\".*version ?= ?\"([^\"]+)\"\
|
|package ?= ?\"${PACKAGE_NAME}\".*version ?= ?\"([^\"]+)\"\
|
||||||
|
|
Loading…
Reference in New Issue