mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-03 17:41:30 +02:00
Compare commits
137 Commits
http-v0.1.
...
web-v1.0.2
Author | SHA1 | Date | |
---|---|---|---|
ad0e6f73b3 | |||
546a8a58db | |||
acda1c075a | |||
686e5f1595 | |||
d2b6502c7a | |||
7c0f570845 | |||
eaa371db8b | |||
d293ae2a69 | |||
d7ec241fd0 | |||
cd323f2ff1 | |||
bf48798bce | |||
c8118e8411 | |||
e7ba67e1a8 | |||
13e618b128 | |||
36e6f0cb4b | |||
7450ae37a7 | |||
2ffda29f9b | |||
ff724e239d | |||
ee769832cf | |||
c4b7980b4f | |||
bfbac4f875 | |||
53e2f8090f | |||
e399e01a22 | |||
d9a62c4bbf | |||
a548b69679 | |||
ae64475d98 | |||
a342b1289d | |||
38f04b75a7 | |||
a771540b16 | |||
cf217d35a8 | |||
0e138e111f | |||
1fce4876f3 | |||
4a179d1ae1 | |||
a780ea10e9 | |||
6d2e190c8e | |||
b1cfbdcf7a | |||
24180f9014 | |||
15cdc680f6 | |||
666756bfbe | |||
a1b40f4314 | |||
29a0fe76d5 | |||
7753b9da6d | |||
f1764bba43 | |||
c2d7db7e06 | |||
21418c7414 | |||
fe781345d5 | |||
a614be7cb5 | |||
1eb89b8375 | |||
aa626a1e72 | |||
7f12b754e9 | |||
3f196f469d | |||
35eb378585 | |||
6db625f55b | |||
801cc2ed5d | |||
ded1e86e7e | |||
babf48c550 | |||
d3e807f6e9 | |||
7746e785c1 | |||
4e141d7f5d | |||
12842871fe | |||
fc85ae4014 | |||
5826f39dbe | |||
8ff56d7cd5 | |||
0843bce7ba | |||
dea0e0a721 | |||
e857ab1f81 | |||
0dda4b06ea | |||
cbe0226177 | |||
e8c8626878 | |||
4b215e0839 | |||
e1ff3bf8fa | |||
80f4ef9aac | |||
bba90d7f22 | |||
f8af3b86e5 | |||
6c3d8b8738 | |||
5a90e33bcc | |||
86b569e320 | |||
2350a2dc68 | |||
36d017dcc6 | |||
3bb081852c | |||
1ca58e876b | |||
e9cbcbaf03 | |||
07c9eec803 | |||
beae9ca0f7 | |||
07b9707ca1 | |||
45c05978b0 | |||
df08baf67f | |||
4066375737 | |||
a77b0b054a | |||
a17ff492a1 | |||
33b4c05557 | |||
005c055a7f | |||
3d1af19080 | |||
fa78da8156 | |||
01cfcf3b75 | |||
7ef4f5ac0b | |||
fc19ce41c4 | |||
6e00eef63a | |||
337c2febe3 | |||
f27beab016 | |||
4f1c6d1bb7 | |||
6b34909537 | |||
87284f0951 | |||
24bd5b1344 | |||
94a0d1a6bc | |||
f4e1205cbb | |||
d2c1791067 | |||
f4b4875cb1 | |||
29a841529f | |||
b51b5b763c | |||
8db6b48a76 | |||
ffd2c04cd3 | |||
70a4c36496 | |||
cba78e06ae | |||
3b3dbb4f40 | |||
7300002226 | |||
5426413cb6 | |||
2bc937f6c3 | |||
60fa0d5427 | |||
f429d3319f | |||
2e19f572ee | |||
64f603b076 | |||
679d1cd513 | |||
42644dac3f | |||
898ef57080 | |||
9702b2d88e | |||
d2b0afd859 | |||
5f6a1a8249 | |||
5d531989e7 | |||
3532602299 | |||
48bee55087 | |||
d00c9bb844 | |||
895e409d57 | |||
f0789aad05 | |||
7e480ab2f7 | |||
891f857547 | |||
01b1350dcc |
140
CHANGES.md
140
CHANGES.md
@ -1,6 +1,142 @@
|
||||
# Changes
|
||||
|
||||
## [1.0.0-beta.1] - 2019-04-xx
|
||||
## [1.0.2] - 2019-06-17
|
||||
|
||||
### Changes
|
||||
|
||||
* Move cors middleware to `actix-cors` crate.
|
||||
|
||||
* Move identity middleware to `actix-identity` crate.
|
||||
|
||||
|
||||
## [1.0.1] - 2019-06-17
|
||||
|
||||
### Add
|
||||
|
||||
* Add support for PathConfig #903
|
||||
|
||||
* Add `middleware::identity::RequestIdentity` trait to `get_identity` from `HttpMessage`.
|
||||
|
||||
### Changes
|
||||
|
||||
* Move cors middleware to `actix-cors` crate.
|
||||
|
||||
* Move identity middleware to `actix-identity` crate.
|
||||
|
||||
* Disable default feature `secure-cookies`.
|
||||
|
||||
* Allow to test an app that uses async actors #897
|
||||
|
||||
* Re-apply patch from #637 #894
|
||||
|
||||
### Fixed
|
||||
|
||||
* HttpRequest::url_for is broken with nested scopes #915
|
||||
|
||||
|
||||
## [1.0.0] - 2019-06-05
|
||||
|
||||
### Add
|
||||
|
||||
* Add `Scope::configure()` method.
|
||||
|
||||
* Add `ServiceRequest::set_payload()` method.
|
||||
|
||||
* Add `test::TestRequest::set_json()` convenience method to automatically
|
||||
serialize data and set header in test requests.
|
||||
|
||||
* Add macros for head, options, trace, connect and patch http methods
|
||||
|
||||
### Changes
|
||||
|
||||
* Drop an unnecessary `Option<_>` indirection around `ServerBuilder` from `HttpServer`. #863
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix Logger request time format, and use rfc3339. #867
|
||||
|
||||
* Clear http requests pool on app service drop #860
|
||||
|
||||
|
||||
## [1.0.0-rc] - 2019-05-18
|
||||
|
||||
### Add
|
||||
|
||||
* Add `Query<T>::from_query()` to extract parameters from a query string. #846
|
||||
* `QueryConfig`, similar to `JsonConfig` for customizing error handling of query extractors.
|
||||
|
||||
### Changes
|
||||
|
||||
* `JsonConfig` is now `Send + Sync`, this implies that `error_handler` must be `Send + Sync` too.
|
||||
|
||||
### Fixed
|
||||
|
||||
* Codegen with parameters in the path only resolves the first registered endpoint #841
|
||||
|
||||
|
||||
## [1.0.0-beta.4] - 2019-05-12
|
||||
|
||||
### Add
|
||||
|
||||
* Allow to set/override app data on scope level
|
||||
|
||||
### Changes
|
||||
|
||||
* `App::configure` take an `FnOnce` instead of `Fn`
|
||||
* Upgrade actix-net crates
|
||||
|
||||
|
||||
## [1.0.0-beta.3] - 2019-05-04
|
||||
|
||||
### Added
|
||||
|
||||
* Add helper function for executing futures `test::block_fn()`
|
||||
|
||||
### Changed
|
||||
|
||||
* Extractor configuration could be registered with `App::data()`
|
||||
or with `Resource::data()` #775
|
||||
|
||||
* Route data is unified with app data, `Route::data()` moved to resource
|
||||
level to `Resource::data()`
|
||||
|
||||
* CORS handling without headers #702
|
||||
|
||||
* Allow to construct `Data` instances to avoid double `Arc` for `Send + Sync` types.
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix `NormalizePath` middleware impl #806
|
||||
|
||||
### Deleted
|
||||
|
||||
* `App::data_factory()` is deleted.
|
||||
|
||||
|
||||
## [1.0.0-beta.2] - 2019-04-24
|
||||
|
||||
### Added
|
||||
|
||||
* Add raw services support via `web::service()`
|
||||
|
||||
* Add helper functions for reading response body `test::read_body()`
|
||||
|
||||
* Add support for `remainder match` (i.e "/path/{tail}*")
|
||||
|
||||
* Extend `Responder` trait, allow to override status code and headers.
|
||||
|
||||
* Store visit and login timestamp in the identity cookie #502
|
||||
|
||||
### Changed
|
||||
|
||||
* `.to_async()` handler can return `Responder` type #792
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix async web::Data factory handling
|
||||
|
||||
|
||||
## [1.0.0-beta.1] - 2019-04-20
|
||||
|
||||
### Added
|
||||
|
||||
@ -9,6 +145,8 @@
|
||||
|
||||
* Add `.peer_addr()` #744
|
||||
|
||||
* Add `NormalizePath` middleware
|
||||
|
||||
### Changed
|
||||
|
||||
* Rename `RouterConfig` to `ServiceConfig`
|
||||
|
41
Cargo.toml
41
Cargo.toml
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web"
|
||||
version = "1.0.0-beta.1"
|
||||
version = "1.0.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
|
||||
readme = "README.md"
|
||||
@ -31,9 +31,11 @@ members = [
|
||||
".",
|
||||
"awc",
|
||||
"actix-http",
|
||||
"actix-cors",
|
||||
"actix-files",
|
||||
"actix-framed",
|
||||
"actix-session",
|
||||
"actix-identity",
|
||||
"actix-multipart",
|
||||
"actix-web-actors",
|
||||
"actix-web-codegen",
|
||||
@ -41,7 +43,7 @@ members = [
|
||||
]
|
||||
|
||||
[features]
|
||||
default = ["brotli", "flate2-zlib", "secure-cookies", "client"]
|
||||
default = ["brotli", "flate2-zlib", "client", "fail"]
|
||||
|
||||
# http client
|
||||
client = ["awc"]
|
||||
@ -58,6 +60,8 @@ flate2-rust = ["actix-http/flate2-rust"]
|
||||
# sessions feature, session require "ring" crate and c compiler
|
||||
secure-cookies = ["actix-http/secure-cookies"]
|
||||
|
||||
fail = ["actix-http/fail"]
|
||||
|
||||
# openssl
|
||||
ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
|
||||
|
||||
@ -66,26 +70,26 @@ rust-tls = ["rustls", "actix-server/rust-tls"]
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-service = "0.3.6"
|
||||
actix-utils = "0.3.4"
|
||||
actix-router = "0.1.2"
|
||||
actix-service = "0.4.1"
|
||||
actix-utils = "0.4.1"
|
||||
actix-router = "0.1.5"
|
||||
actix-rt = "0.2.2"
|
||||
actix-web-codegen = "0.1.0-alpha.6"
|
||||
actix-http = { version = "0.1.0", features=["fail"] }
|
||||
actix-server = "0.4.3"
|
||||
actix-web-codegen = "0.1.2"
|
||||
actix-http = "0.2.4"
|
||||
actix-server = "0.5.1"
|
||||
actix-server-config = "0.1.1"
|
||||
actix-threadpool = "0.1.0"
|
||||
awc = { version = "0.1.0", optional = true }
|
||||
actix-threadpool = "0.1.1"
|
||||
awc = { version = "0.2.1", optional = true }
|
||||
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
derive_more = "0.15.0"
|
||||
encoding = "0.2"
|
||||
futures = "0.1"
|
||||
hashbrown = "0.2.2"
|
||||
futures = "0.1.25"
|
||||
hashbrown = "0.5.0"
|
||||
log = "0.4"
|
||||
mime = "0.3"
|
||||
net2 = "0.2.33"
|
||||
parking_lot = "0.7"
|
||||
parking_lot = "0.8"
|
||||
regex = "1.0"
|
||||
serde = { version = "1.0", features=["derive"] }
|
||||
serde_json = "1.0"
|
||||
@ -95,12 +99,12 @@ url = { version="1.7", features=["query_encoding"] }
|
||||
|
||||
# ssl support
|
||||
openssl = { version="0.10", optional = true }
|
||||
rustls = { version = "^0.15", optional = true }
|
||||
rustls = { version = "0.15", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-http = { version = "0.1.0", features=["ssl", "brotli", "flate2-zlib"] }
|
||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||
actix-files = { version = "0.1.0-alpha.6" }
|
||||
actix = { version = "0.8.3" }
|
||||
actix-http = { version = "0.2.4", features=["ssl", "brotli", "flate2-zlib"] }
|
||||
actix-http-test = { version = "0.2.2", features=["ssl"] }
|
||||
rand = "0.6"
|
||||
env_logger = "0.6"
|
||||
serde_derive = "1.0"
|
||||
@ -121,4 +125,5 @@ actix-web-codegen = { path = "actix-web-codegen" }
|
||||
actix-web-actors = { path = "actix-web-actors" }
|
||||
actix-session = { path = "actix-session" }
|
||||
actix-files = { path = "actix-files" }
|
||||
actix-multipart = { path = "actix-multipart" }
|
||||
awc = { path = "awc" }
|
||||
|
77
MIGRATION.md
77
MIGRATION.md
@ -1,4 +1,35 @@
|
||||
## 1.0
|
||||
## 1.0.1
|
||||
|
||||
* Cors middleware has been moved to `actix-cors` crate
|
||||
|
||||
instead of
|
||||
|
||||
```rust
|
||||
use actix_web::middleware::cors::Cors;
|
||||
```
|
||||
|
||||
use
|
||||
|
||||
```rust
|
||||
use actix_cors::Cors;
|
||||
```
|
||||
|
||||
* Identity middleware has been moved to `actix-identity` crate
|
||||
|
||||
instead of
|
||||
|
||||
```rust
|
||||
use actix_web::middleware::identity::{Identity, CookieIdentityPolicy, IdentityService};
|
||||
```
|
||||
|
||||
use
|
||||
|
||||
```rust
|
||||
use actix_identity::{Identity, CookieIdentityPolicy, IdentityService};
|
||||
```
|
||||
|
||||
|
||||
## 1.0.0
|
||||
|
||||
* Resource registration. 1.0 version uses generalized resource
|
||||
registration via `.service()` method.
|
||||
@ -92,6 +123,36 @@
|
||||
App.new().service(web::resource("/welcome").to(welcome))
|
||||
```
|
||||
|
||||
* `HttpRequest` does not provide access to request's payload stream.
|
||||
|
||||
instead of
|
||||
|
||||
```rust
|
||||
fn index(req: &HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
|
||||
req
|
||||
.payload()
|
||||
.from_err()
|
||||
.fold((), |_, chunk| {
|
||||
...
|
||||
})
|
||||
.map(|_| HttpResponse::Ok().finish())
|
||||
.responder()
|
||||
}
|
||||
```
|
||||
|
||||
use `Payload` extractor
|
||||
|
||||
```rust
|
||||
fn index(stream: web::Payload) -> impl Future<Item=HttpResponse, Error=Error> {
|
||||
stream
|
||||
.from_err()
|
||||
.fold((), |_, chunk| {
|
||||
...
|
||||
})
|
||||
.map(|_| HttpResponse::Ok().finish())
|
||||
}
|
||||
```
|
||||
|
||||
* `State` is now `Data`. You register Data during the App initialization process
|
||||
and then access it from handlers either using a Data extractor or using
|
||||
HttpRequest's api.
|
||||
@ -164,7 +225,7 @@
|
||||
* `HttpRequest::body()`, `HttpRequest::urlencoded()`, `HttpRequest::json()`, `HttpRequest::multipart()`
|
||||
method have been removed. Use `Bytes`, `String`, `Form`, `Json`, `Multipart` extractors instead.
|
||||
|
||||
instead if
|
||||
instead of
|
||||
|
||||
```rust
|
||||
fn index(req: &HttpRequest) -> Responder {
|
||||
@ -173,6 +234,7 @@
|
||||
...
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
use
|
||||
|
||||
@ -207,6 +269,17 @@
|
||||
|
||||
* Actors support have been moved to `actix-web-actors` crate
|
||||
|
||||
* Custom Error
|
||||
|
||||
Instead of error_response method alone, ResponseError now provides two methods: error_response and render_response respectively. Where, error_response creates the error response and render_response returns the error response to the caller.
|
||||
|
||||
Simplest migration from 0.7 to 1.0 shall include below method to the custom implementation of ResponseError:
|
||||
|
||||
```rust
|
||||
fn render_response(&self) -> HttpResponse {
|
||||
self.error_response()
|
||||
}
|
||||
```
|
||||
|
||||
## 0.7.15
|
||||
|
||||
|
@ -11,7 +11,7 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
|
||||
* Multipart streams
|
||||
* Static assets
|
||||
* SSL support with OpenSSL or Rustls
|
||||
* Middlewares ([Logger, Session, CORS, CSRF, etc](https://actix.rs/docs/middleware/))
|
||||
* Middlewares ([Logger, Session, CORS, etc](https://actix.rs/docs/middleware/))
|
||||
* Includes an asynchronous [HTTP client](https://actix.rs/actix-web/actix_web/client/index.html)
|
||||
* Supports [Actix actor framework](https://github.com/actix/actix)
|
||||
|
||||
@ -22,7 +22,7 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
|
||||
* [API Documentation (0.7)](https://docs.rs/actix-web/0.7.19/actix_web/)
|
||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||
* Cargo package: [actix-web](https://crates.io/crates/actix-web)
|
||||
* Minimum supported Rust version: 1.32 or later
|
||||
* Minimum supported Rust version: 1.34 or later
|
||||
|
||||
## Example
|
||||
|
||||
|
5
actix-cors/CHANGES.md
Normal file
5
actix-cors/CHANGES.md
Normal file
@ -0,0 +1,5 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.0] - 2019-06-15
|
||||
|
||||
* Move cors middleware to separate crate
|
23
actix-cors/Cargo.toml
Normal file
23
actix-cors/Cargo.toml
Normal file
@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "actix-cors"
|
||||
version = "0.1.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Cross-origin resource sharing (CORS) for Actix applications."
|
||||
readme = "README.md"
|
||||
keywords = ["web", "framework"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-web.git"
|
||||
documentation = "https://docs.rs/actix-cors/"
|
||||
license = "MIT/Apache-2.0"
|
||||
edition = "2018"
|
||||
#workspace = ".."
|
||||
|
||||
[lib]
|
||||
name = "actix_cors"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.0"
|
||||
actix-service = "0.4.0"
|
||||
derive_more = "0.14.1"
|
||||
futures = "0.1.25"
|
1
actix-cors/LICENSE-APACHE
Symbolic link
1
actix-cors/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-cors/LICENSE-MIT
Symbolic link
1
actix-cors/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
9
actix-cors/README.md
Normal file
9
actix-cors/README.md
Normal file
@ -0,0 +1,9 @@
|
||||
# Identity service for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-identity) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
## Documentation & community resources
|
||||
|
||||
* [User Guide](https://actix.rs/docs/)
|
||||
* [API Documentation](https://docs.rs/actix-identity/)
|
||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||
* Cargo package: [actix-session](https://crates.io/crates/actix-identity)
|
||||
* Minimum supported Rust version: 1.34 or later
|
@ -7,7 +7,7 @@
|
||||
//! # Example
|
||||
//!
|
||||
//! ```rust
|
||||
//! use actix_web::middleware::cors::Cors;
|
||||
//! use actix_cors::Cors;
|
||||
//! use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer};
|
||||
//!
|
||||
//! fn index(req: HttpRequest) -> &'static str {
|
||||
@ -42,17 +42,15 @@ use std::iter::FromIterator;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_service::{IntoTransform, Service, Transform};
|
||||
use actix_web::dev::{RequestHead, ServiceRequest, ServiceResponse};
|
||||
use actix_web::error::{Error, ResponseError, Result};
|
||||
use actix_web::http::header::{self, HeaderName, HeaderValue};
|
||||
use actix_web::http::{self, HttpTryFrom, Method, StatusCode, Uri};
|
||||
use actix_web::HttpResponse;
|
||||
use derive_more::Display;
|
||||
use futures::future::{ok, Either, Future, FutureResult};
|
||||
use futures::Poll;
|
||||
|
||||
use crate::dev::RequestHead;
|
||||
use crate::error::{ResponseError, Result};
|
||||
use crate::http::header::{self, HeaderName, HeaderValue};
|
||||
use crate::http::{self, HttpTryFrom, Method, StatusCode, Uri};
|
||||
use crate::service::{ServiceRequest, ServiceResponse};
|
||||
use crate::HttpResponse;
|
||||
|
||||
/// A set of errors that can occur during processing CORS
|
||||
#[derive(Debug, Display)]
|
||||
pub enum CorsError {
|
||||
@ -81,13 +79,6 @@ pub enum CorsError {
|
||||
fmt = "The request header `Access-Control-Request-Headers` has an invalid value"
|
||||
)]
|
||||
BadRequestHeaders,
|
||||
/// The request header `Access-Control-Request-Headers` is required but is
|
||||
/// missing.
|
||||
#[display(
|
||||
fmt = "The request header `Access-Control-Request-Headers` is required but is
|
||||
missing"
|
||||
)]
|
||||
MissingRequestHeaders,
|
||||
/// Origin is not allowed to make this request
|
||||
#[display(fmt = "Origin is not allowed to make this request")]
|
||||
OriginNotAllowed,
|
||||
@ -159,11 +150,11 @@ impl<T> AllOrSome<T> {
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_cors::Cors;
|
||||
/// use actix_web::http::header;
|
||||
/// use actix_web::middleware::cors;
|
||||
///
|
||||
/// # fn main() {
|
||||
/// let cors = cors::Cors::new()
|
||||
/// let cors = Cors::new()
|
||||
/// .allowed_origin("https://www.rust-lang.org/")
|
||||
/// .allowed_methods(vec!["GET", "POST"])
|
||||
/// .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
|
||||
@ -477,9 +468,8 @@ fn cors<'a>(
|
||||
|
||||
impl<S, B> IntoTransform<CorsFactory, S> for Cors
|
||||
where
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
B: 'static,
|
||||
{
|
||||
fn into_transform(self) -> CorsFactory {
|
||||
@ -539,14 +529,13 @@ pub struct CorsFactory {
|
||||
|
||||
impl<S, B> Transform<S> for CorsFactory
|
||||
where
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
B: 'static,
|
||||
{
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = S::Error;
|
||||
type Error = Error;
|
||||
type InitError = ();
|
||||
type Transform = CorsMiddleware<S>;
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
@ -663,15 +652,18 @@ impl Inner {
|
||||
Err(_) => return Err(CorsError::BadRequestHeaders),
|
||||
};
|
||||
}
|
||||
|
||||
if !hdrs.is_empty() && !hdrs.is_subset(allowed_headers) {
|
||||
// `Access-Control-Request-Headers` must contain 1 or more
|
||||
// `field-name`.
|
||||
if !hdrs.is_empty() {
|
||||
if !hdrs.is_subset(allowed_headers) {
|
||||
return Err(CorsError::HeadersNotAllowed);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(CorsError::BadRequestHeaders)
|
||||
} else {
|
||||
Err(CorsError::MissingRequestHeaders)
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -680,17 +672,16 @@ impl Inner {
|
||||
|
||||
impl<S, B> Service for CorsMiddleware<S>
|
||||
where
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
B: 'static,
|
||||
{
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = S::Error;
|
||||
type Error = Error;
|
||||
type Future = Either<
|
||||
FutureResult<Self::Response, Self::Error>,
|
||||
Either<S::Future, Box<Future<Item = Self::Response, Error = Self::Error>>>,
|
||||
FutureResult<Self::Response, Error>,
|
||||
Either<S::Future, Box<Future<Item = Self::Response, Error = Error>>>,
|
||||
>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
@ -812,22 +803,26 @@ where
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_service::{FnService, Transform};
|
||||
use actix_service::{IntoService, Transform};
|
||||
use actix_web::test::{self, block_on, TestRequest};
|
||||
|
||||
use super::*;
|
||||
use crate::test::{self, block_on, TestRequest};
|
||||
|
||||
impl Cors {
|
||||
fn finish<S, B>(self, srv: S) -> CorsMiddleware<S>
|
||||
fn finish<F, S, B>(self, srv: F) -> CorsMiddleware<S>
|
||||
where
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>
|
||||
+ 'static,
|
||||
F: IntoService<S>,
|
||||
S: Service<
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse<B>,
|
||||
Error = Error,
|
||||
> + 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
B: 'static,
|
||||
{
|
||||
block_on(
|
||||
IntoTransform::<CorsFactory, S>::into_transform(self).new_transform(srv),
|
||||
IntoTransform::<CorsFactory, S>::into_transform(self)
|
||||
.new_transform(srv.into_service()),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
@ -875,6 +870,7 @@ mod tests {
|
||||
|
||||
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
||||
.method(Method::OPTIONS)
|
||||
.header(header::ACCESS_CONTROL_REQUEST_HEADERS, "X-Not-Allowed")
|
||||
.to_srv_request();
|
||||
|
||||
assert!(cors.inner.validate_allowed_method(req.head()).is_err());
|
||||
@ -888,7 +884,7 @@ mod tests {
|
||||
.to_srv_request();
|
||||
|
||||
assert!(cors.inner.validate_allowed_method(req.head()).is_err());
|
||||
assert!(cors.inner.validate_allowed_headers(req.head()).is_err());
|
||||
assert!(cors.inner.validate_allowed_headers(req.head()).is_ok());
|
||||
|
||||
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
||||
.header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
|
||||
@ -1067,11 +1063,11 @@ mod tests {
|
||||
.allowed_headers(exposed_headers.clone())
|
||||
.expose_headers(exposed_headers.clone())
|
||||
.allowed_header(header::CONTENT_TYPE)
|
||||
.finish(FnService::new(move |req: ServiceRequest| {
|
||||
.finish(|req: ServiceRequest| {
|
||||
req.into_response(
|
||||
HttpResponse::Ok().header(header::VARY, "Accept").finish(),
|
||||
)
|
||||
}));
|
||||
});
|
||||
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
||||
.method(Method::OPTIONS)
|
||||
.to_srv_request();
|
@ -1,5 +1,28 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.2] - 2019-06-13
|
||||
|
||||
* Content-Length is 0 for NamedFile HEAD request #914
|
||||
|
||||
* Fix ring dependency from actix-web default features for #741
|
||||
|
||||
## [0.1.1] - 2019-06-01
|
||||
|
||||
* Static files are incorrectly served as both chunked and with length #812
|
||||
|
||||
## [0.1.0] - 2019-05-25
|
||||
|
||||
* NamedFile last-modified check always fails due to nano-seconds
|
||||
in file modified date #820
|
||||
|
||||
## [0.1.0-beta.4] - 2019-05-12
|
||||
|
||||
* Update actix-web to beta.4
|
||||
|
||||
## [0.1.0-beta.1] - 2019-04-20
|
||||
|
||||
* Update actix-web to beta.1
|
||||
|
||||
## [0.1.0-alpha.6] - 2019-04-14
|
||||
|
||||
* Update actix-web to alpha6
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-files"
|
||||
version = "0.1.0-alpha.6"
|
||||
version = "0.1.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Static files support for actix web."
|
||||
readme = "README.md"
|
||||
@ -18,12 +18,13 @@ name = "actix_files"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.0-alpha.6"
|
||||
actix-service = "0.3.4"
|
||||
actix-web = { version = "1.0.0", default-features = false }
|
||||
actix-http = "0.2.4"
|
||||
actix-service = "0.4.1"
|
||||
bitflags = "1"
|
||||
bytes = "0.4"
|
||||
futures = "0.1.25"
|
||||
derive_more = "0.14"
|
||||
derive_more = "0.15.0"
|
||||
log = "0.4"
|
||||
mime = "0.3"
|
||||
mime_guess = "2.0.0-alpha"
|
||||
@ -31,4 +32,4 @@ percent-encoding = "1.0"
|
||||
v_htmlescape = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = { version = "1.0.0-alpha.6", features=["ssl"] }
|
||||
actix-web = { version = "1.0.0", features=["ssl"] }
|
||||
|
1
actix-files/LICENSE-APACHE
Symbolic link
1
actix-files/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-files/LICENSE-MIT
Symbolic link
1
actix-files/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -1 +1,9 @@
|
||||
# Static files support for actix web [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-files) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
## Documentation & community resources
|
||||
|
||||
* [User Guide](https://actix.rs/docs/)
|
||||
* [API Documentation](https://docs.rs/actix-files/)
|
||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||
* Cargo package: [actix-files](https://crates.io/crates/actix-files)
|
||||
* Minimum supported Rust version: 1.33 or later
|
||||
|
@ -334,6 +334,7 @@ impl Files {
|
||||
where
|
||||
F: IntoNewService<U>,
|
||||
U: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -363,6 +364,7 @@ impl HttpServiceFactory for Files {
|
||||
}
|
||||
|
||||
impl NewService for Files {
|
||||
type Config = ();
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse;
|
||||
type Error = Error;
|
||||
@ -924,6 +926,29 @@ mod tests {
|
||||
assert_eq!(bytes.freeze(), data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_head_content_length_headers() {
|
||||
let mut srv = test::init_service(
|
||||
App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
|
||||
);
|
||||
|
||||
// Valid range header
|
||||
let request = TestRequest::default()
|
||||
.method(Method::HEAD)
|
||||
.uri("/t%65st/tests/test.binary")
|
||||
.to_request();
|
||||
let response = test::call_service(&mut srv, request);
|
||||
|
||||
let contentlength = response
|
||||
.headers()
|
||||
.get(header::CONTENT_LENGTH)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(contentlength, "100");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_static_files_with_spaces() {
|
||||
let mut srv = test::init_service(
|
||||
|
@ -11,6 +11,7 @@ use bitflags::bitflags;
|
||||
use mime;
|
||||
use mime_guess::guess_mime_type;
|
||||
|
||||
use actix_http::body::SizedStream;
|
||||
use actix_web::http::header::{
|
||||
self, ContentDisposition, DispositionParam, DispositionType,
|
||||
};
|
||||
@ -66,6 +67,7 @@ impl NamedFile {
|
||||
/// let mut file = File::create("foo.txt")?;
|
||||
/// file.write_all(b"Hello, world!")?;
|
||||
/// let named_file = NamedFile::from_file(file, "bar.txt")?;
|
||||
/// # std::fs::remove_file("foo.txt");
|
||||
/// Ok(())
|
||||
/// }
|
||||
/// ```
|
||||
@ -336,7 +338,12 @@ impl Responder for NamedFile {
|
||||
} else if let (Some(ref m), Some(header::IfUnmodifiedSince(ref since))) =
|
||||
(last_modified, req.get_header())
|
||||
{
|
||||
m > since
|
||||
let t1: SystemTime = m.clone().into();
|
||||
let t2: SystemTime = since.clone().into();
|
||||
match (t1.duration_since(UNIX_EPOCH), t2.duration_since(UNIX_EPOCH)) {
|
||||
(Ok(t1), Ok(t2)) => t1 > t2,
|
||||
_ => false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
@ -349,7 +356,12 @@ impl Responder for NamedFile {
|
||||
} else if let (Some(ref m), Some(header::IfModifiedSince(ref since))) =
|
||||
(last_modified, req.get_header())
|
||||
{
|
||||
m <= since
|
||||
let t1: SystemTime = m.clone().into();
|
||||
let t2: SystemTime = since.clone().into();
|
||||
match (t1.duration_since(UNIX_EPOCH), t2.duration_since(UNIX_EPOCH)) {
|
||||
(Ok(t1), Ok(t2)) => t1 <= t2,
|
||||
_ => false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
@ -410,9 +422,6 @@ impl Responder for NamedFile {
|
||||
return Ok(resp.status(StatusCode::NOT_MODIFIED).finish());
|
||||
}
|
||||
|
||||
if *req.method() == Method::HEAD {
|
||||
Ok(resp.finish())
|
||||
} else {
|
||||
let reader = ChunkedReadFile {
|
||||
offset,
|
||||
size: length,
|
||||
@ -423,7 +432,6 @@ impl Responder for NamedFile {
|
||||
if offset != 0 || length != self.md.len() {
|
||||
return Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader));
|
||||
};
|
||||
Ok(resp.streaming(reader))
|
||||
}
|
||||
Ok(resp.body(SizedStream::new(length, reader)))
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-framed"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix framed app server"
|
||||
readme = "README.md"
|
||||
@ -21,17 +21,18 @@ path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-service = "0.3.6"
|
||||
actix-utils = "0.3.4"
|
||||
actix-service = "0.4.0"
|
||||
actix-utils = "0.4.0"
|
||||
actix-router = "0.1.2"
|
||||
actix-rt = "0.2.2"
|
||||
actix-http = "0.1.0"
|
||||
actix-http = "0.2.0"
|
||||
actix-server-config = "0.1.1"
|
||||
|
||||
bytes = "0.4"
|
||||
futures = "0.1.25"
|
||||
log = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-server = { version = "0.4.3", features=["ssl"] }
|
||||
actix-connect = { version = "0.1.4", features=["ssl"] }
|
||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||
actix-server = { version = "0.5.0", features=["ssl"] }
|
||||
actix-connect = { version = "0.2.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
|
@ -1 +1,8 @@
|
||||
# Framed app for actix web [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-framed) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
## Documentation & community resources
|
||||
|
||||
* [API Documentation](https://docs.rs/actix-framed/)
|
||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||
* Cargo package: [actix-framed](https://crates.io/crates/actix-framed)
|
||||
* Minimum supported Rust version: 1.33 or later
|
||||
|
@ -1,5 +1,10 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.0] - 2019-05-12
|
||||
|
||||
* Update dependencies
|
||||
|
||||
|
||||
## [0.1.0] - 2019-04-16
|
||||
|
||||
* Update tests
|
||||
|
@ -4,6 +4,7 @@ use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||
use actix_http::h1::{Codec, SendResponse};
|
||||
use actix_http::{Error, Request, Response};
|
||||
use actix_router::{Path, Router, Url};
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{IntoNewService, NewService, Service};
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use futures::{Async, Future, Poll};
|
||||
@ -49,6 +50,7 @@ impl<T: 'static, S: 'static> FramedApp<T, S> {
|
||||
where
|
||||
U: HttpServiceFactory,
|
||||
U::Factory: NewService<
|
||||
Config = (),
|
||||
Request = FramedRequest<T, S>,
|
||||
Response = (),
|
||||
Error = Error,
|
||||
@ -88,11 +90,12 @@ pub struct FramedAppFactory<T, S> {
|
||||
services: Rc<Vec<(String, BoxedHttpNewService<FramedRequest<T, S>>)>>,
|
||||
}
|
||||
|
||||
impl<T, S, C> NewService<C> for FramedAppFactory<T, S>
|
||||
impl<T, S> NewService for FramedAppFactory<T, S>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + 'static,
|
||||
S: 'static,
|
||||
{
|
||||
type Config = ServerConfig;
|
||||
type Request = (Request, Framed<T, Codec>);
|
||||
type Response = ();
|
||||
type Error = Error;
|
||||
@ -100,7 +103,7 @@ where
|
||||
type Service = CloneableService<FramedAppService<T, S>>;
|
||||
type Future = CreateService<T, S>;
|
||||
|
||||
fn new_service(&self, _: &C) -> Self::Future {
|
||||
fn new_service(&self, _: &ServerConfig) -> Self::Future {
|
||||
CreateService {
|
||||
fut: self
|
||||
.services
|
||||
|
@ -13,6 +13,7 @@ pub(crate) type BoxedHttpService<Req> = Box<
|
||||
|
||||
pub(crate) type BoxedHttpNewService<Req> = Box<
|
||||
NewService<
|
||||
Config = (),
|
||||
Request = Req,
|
||||
Response = (),
|
||||
Error = Error,
|
||||
@ -39,12 +40,13 @@ where
|
||||
|
||||
impl<T> NewService for HttpNewService<T>
|
||||
where
|
||||
T: NewService<Response = (), Error = Error>,
|
||||
T: NewService<Config = (), Response = (), Error = Error>,
|
||||
T::Request: 'static,
|
||||
T::Future: 'static,
|
||||
T::Service: Service<Future = Box<Future<Item = (), Error = Error>>> + 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
{
|
||||
type Config = ();
|
||||
type Request = T::Request;
|
||||
type Response = ();
|
||||
type Error = Error;
|
||||
|
@ -106,6 +106,7 @@ where
|
||||
R::Future: 'static,
|
||||
R::Error: fmt::Display,
|
||||
{
|
||||
type Config = ();
|
||||
type Request = FramedRequest<Io, S>;
|
||||
type Response = ();
|
||||
type Error = Error;
|
||||
|
@ -12,22 +12,23 @@ use futures::{Async, Future, IntoFuture, Poll, Sink};
|
||||
|
||||
/// Service that verifies incoming request if it is valid websocket
|
||||
/// upgrade request. In case of error returns `HandshakeError`
|
||||
pub struct VerifyWebSockets<T> {
|
||||
_t: PhantomData<T>,
|
||||
pub struct VerifyWebSockets<T, C> {
|
||||
_t: PhantomData<(T, C)>,
|
||||
}
|
||||
|
||||
impl<T> Default for VerifyWebSockets<T> {
|
||||
impl<T, C> Default for VerifyWebSockets<T, C> {
|
||||
fn default() -> Self {
|
||||
VerifyWebSockets { _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, C> NewService<C> for VerifyWebSockets<T> {
|
||||
impl<T, C> NewService for VerifyWebSockets<T, C> {
|
||||
type Config = C;
|
||||
type Request = (Request, Framed<T, Codec>);
|
||||
type Response = (Request, Framed<T, Codec>);
|
||||
type Error = (HandshakeError, Framed<T, Codec>);
|
||||
type InitError = ();
|
||||
type Service = VerifyWebSockets<T>;
|
||||
type Service = VerifyWebSockets<T, C>;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &C) -> Self::Future {
|
||||
@ -35,7 +36,7 @@ impl<T, C> NewService<C> for VerifyWebSockets<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Service for VerifyWebSockets<T> {
|
||||
impl<T, C> Service for VerifyWebSockets<T, C> {
|
||||
type Request = (Request, Framed<T, Codec>);
|
||||
type Response = (Request, Framed<T, Codec>);
|
||||
type Error = (HandshakeError, Framed<T, Codec>);
|
||||
@ -54,9 +55,9 @@ impl<T> Service for VerifyWebSockets<T> {
|
||||
}
|
||||
|
||||
/// Send http/1 error response
|
||||
pub struct SendError<T, R, E>(PhantomData<(T, R, E)>);
|
||||
pub struct SendError<T, R, E, C>(PhantomData<(T, R, E, C)>);
|
||||
|
||||
impl<T, R, E> Default for SendError<T, R, E>
|
||||
impl<T, R, E, C> Default for SendError<T, R, E, C>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
E: ResponseError,
|
||||
@ -66,17 +67,18 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, R, E, C> NewService<C> for SendError<T, R, E>
|
||||
impl<T, R, E, C> NewService for SendError<T, R, E, C>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + 'static,
|
||||
R: 'static,
|
||||
E: ResponseError + 'static,
|
||||
{
|
||||
type Config = C;
|
||||
type Request = Result<R, (E, Framed<T, Codec>)>;
|
||||
type Response = R;
|
||||
type Error = (E, Framed<T, Codec>);
|
||||
type InitError = ();
|
||||
type Service = SendError<T, R, E>;
|
||||
type Service = SendError<T, R, E, C>;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &C) -> Self::Future {
|
||||
@ -84,7 +86,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, R, E> Service for SendError<T, R, E>
|
||||
impl<T, R, E, C> Service for SendError<T, R, E, C>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + 'static,
|
||||
R: 'static,
|
||||
|
@ -1,5 +1,86 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.4] - 2019-06-16
|
||||
|
||||
### Fixed
|
||||
|
||||
* Do not compress NoContent (204) responses #918
|
||||
|
||||
|
||||
## [0.2.3] - 2019-06-02
|
||||
|
||||
### Added
|
||||
|
||||
* Debug impl for ResponseBuilder
|
||||
|
||||
* From SizedStream and BodyStream for Body
|
||||
|
||||
### Changed
|
||||
|
||||
* SizedStream uses u64
|
||||
|
||||
|
||||
## [0.2.2] - 2019-05-29
|
||||
|
||||
### Fixed
|
||||
|
||||
* Parse incoming stream before closing stream on disconnect #868
|
||||
|
||||
|
||||
## [0.2.1] - 2019-05-25
|
||||
|
||||
### Fixed
|
||||
|
||||
* Handle socket read disconnect
|
||||
|
||||
|
||||
## [0.2.0] - 2019-05-12
|
||||
|
||||
### Changed
|
||||
|
||||
* Update actix-service to 0.4
|
||||
|
||||
* Expect and upgrade services accept `ServerConfig` config.
|
||||
|
||||
### Deleted
|
||||
|
||||
* `OneRequest` service
|
||||
|
||||
|
||||
## [0.1.5] - 2019-05-04
|
||||
|
||||
### Fixed
|
||||
|
||||
* Clean up response extensions in response pool #817
|
||||
|
||||
|
||||
## [0.1.4] - 2019-04-24
|
||||
|
||||
### Added
|
||||
|
||||
* Allow to render h1 request headers in `Camel-Case`
|
||||
|
||||
### Fixed
|
||||
|
||||
* Read until eof for http/1.0 responses #771
|
||||
|
||||
|
||||
## [0.1.3] - 2019-04-23
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix http client pool management
|
||||
|
||||
* Fix http client wait queue management #794
|
||||
|
||||
|
||||
## [0.1.2] - 2019-04-23
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix BorrowMutError panic in client connector #793
|
||||
|
||||
|
||||
## [0.1.1] - 2019-04-19
|
||||
|
||||
### Changes
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-http"
|
||||
version = "0.1.1"
|
||||
version = "0.2.4"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http primitives"
|
||||
readme = "README.md"
|
||||
@ -44,10 +44,10 @@ fail = ["failure"]
|
||||
secure-cookies = ["ring"]
|
||||
|
||||
[dependencies]
|
||||
actix-service = "0.3.6"
|
||||
actix-service = "0.4.0"
|
||||
actix-codec = "0.1.2"
|
||||
actix-connect = "0.1.5"
|
||||
actix-utils = "0.3.5"
|
||||
actix-connect = "0.2.0"
|
||||
actix-utils = "0.4.1"
|
||||
actix-server-config = "0.1.1"
|
||||
actix-threadpool = "0.1.0"
|
||||
|
||||
@ -56,11 +56,11 @@ bitflags = "1.0"
|
||||
bytes = "0.4"
|
||||
byteorder = "1.2"
|
||||
copyless = "0.1.2"
|
||||
derive_more = "0.14"
|
||||
derive_more = "0.15.0"
|
||||
either = "1.5.2"
|
||||
encoding = "0.2"
|
||||
futures = "0.1"
|
||||
hashbrown = "0.2.2"
|
||||
futures = "0.1.25"
|
||||
hashbrown = "0.5.0"
|
||||
h2 = "0.1.16"
|
||||
http = "0.1.17"
|
||||
httparse = "1.3"
|
||||
@ -81,7 +81,7 @@ time = "0.1.42"
|
||||
tokio-tcp = "0.1.3"
|
||||
tokio-timer = "0.2.8"
|
||||
tokio-current-thread = "0.1"
|
||||
trust-dns-resolver = { version="0.11.0", default-features = false }
|
||||
trust-dns-resolver = { version="0.11.1", default-features = false }
|
||||
|
||||
# for secure cookie
|
||||
ring = { version = "0.14.6", optional = true }
|
||||
@ -97,9 +97,9 @@ chrono = "0.4.6"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
actix-server = { version = "0.4.3", features=["ssl"] }
|
||||
actix-connect = { version = "0.1.4", features=["ssl"] }
|
||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||
actix-server = { version = "0.5.0", features=["ssl"] }
|
||||
actix-connect = { version = "0.2.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
env_logger = "0.6"
|
||||
serde_derive = "1.0"
|
||||
openssl = { version="0.10" }
|
||||
|
@ -234,6 +234,25 @@ impl From<BytesMut> for Body {
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> From<SizedStream<S>> for Body
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = Error> + 'static,
|
||||
{
|
||||
fn from(s: SizedStream<S>) -> Body {
|
||||
Body::from_message(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, E> From<BodyStream<S, E>> for Body
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = E> + 'static,
|
||||
E: Into<Error> + 'static,
|
||||
{
|
||||
fn from(s: BodyStream<S, E>) -> Body {
|
||||
Body::from_message(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl MessageBody for Bytes {
|
||||
fn size(&self) -> BodySize {
|
||||
BodySize::Sized(self.len())
|
||||
@ -366,7 +385,7 @@ where
|
||||
/// Type represent streaming body. This body implementation should be used
|
||||
/// if total size of stream is known. Data get sent as is without using transfer encoding.
|
||||
pub struct SizedStream<S> {
|
||||
size: usize,
|
||||
size: u64,
|
||||
stream: S,
|
||||
}
|
||||
|
||||
@ -374,7 +393,7 @@ impl<S> SizedStream<S>
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = Error>,
|
||||
{
|
||||
pub fn new(size: usize, stream: S) -> Self {
|
||||
pub fn new(size: u64, stream: S) -> Self {
|
||||
SizedStream { size, stream }
|
||||
}
|
||||
}
|
||||
@ -384,7 +403,7 @@ where
|
||||
S: Stream<Item = Bytes, Error = Error>,
|
||||
{
|
||||
fn size(&self) -> BodySize {
|
||||
BodySize::Sized(self.size)
|
||||
BodySize::Sized64(self.size)
|
||||
}
|
||||
|
||||
fn poll_next(&mut self) -> Poll<Option<Bytes>, Error> {
|
||||
|
@ -29,7 +29,7 @@ pub struct HttpServiceBuilder<T, S, X = ExpectHandler, U = UpgradeHandler<T>> {
|
||||
|
||||
impl<T, S> HttpServiceBuilder<T, S, ExpectHandler, UpgradeHandler<T>>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
{
|
||||
@ -48,13 +48,17 @@ where
|
||||
|
||||
impl<T, S, X, U> HttpServiceBuilder<T, S, X, U>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
X: NewService<Request = Request, Response = Request>,
|
||||
X: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
X::InitError: fmt::Debug,
|
||||
U: NewService<Request = (Request, Framed<T, Codec>), Response = ()>,
|
||||
U: NewService<
|
||||
Config = SrvConfig,
|
||||
Request = (Request, Framed<T, Codec>),
|
||||
Response = (),
|
||||
>,
|
||||
U::Error: fmt::Display,
|
||||
U::InitError: fmt::Debug,
|
||||
{
|
||||
@ -101,7 +105,7 @@ where
|
||||
pub fn expect<F, X1>(self, expect: F) -> HttpServiceBuilder<T, S, X1, U>
|
||||
where
|
||||
F: IntoNewService<X1>,
|
||||
X1: NewService<Request = Request, Response = Request>,
|
||||
X1: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||
X1::Error: Into<Error>,
|
||||
X1::InitError: fmt::Debug,
|
||||
{
|
||||
@ -122,7 +126,11 @@ where
|
||||
pub fn upgrade<F, U1>(self, upgrade: F) -> HttpServiceBuilder<T, S, X, U1>
|
||||
where
|
||||
F: IntoNewService<U1>,
|
||||
U1: NewService<Request = (Request, Framed<T, Codec>), Response = ()>,
|
||||
U1: NewService<
|
||||
Config = SrvConfig,
|
||||
Request = (Request, Framed<T, Codec>),
|
||||
Response = (),
|
||||
>,
|
||||
U1::Error: fmt::Display,
|
||||
U1::InitError: fmt::Debug,
|
||||
{
|
||||
@ -140,7 +148,7 @@ where
|
||||
pub fn h1<F, P, B>(self, service: F) -> H1Service<T, P, S, B, X, U>
|
||||
where
|
||||
B: MessageBody + 'static,
|
||||
F: IntoNewService<S, SrvConfig>,
|
||||
F: IntoNewService<S>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
@ -159,7 +167,7 @@ where
|
||||
pub fn h2<F, P, B>(self, service: F) -> H2Service<T, P, S, B>
|
||||
where
|
||||
B: MessageBody + 'static,
|
||||
F: IntoNewService<S, SrvConfig>,
|
||||
F: IntoNewService<S>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
@ -177,7 +185,7 @@ where
|
||||
pub fn finish<F, P, B>(self, service: F) -> HttpService<T, P, S, B, X, U>
|
||||
where
|
||||
B: MessageBody + 'static,
|
||||
F: IntoNewService<S, SrvConfig>,
|
||||
F: IntoNewService<S>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
|
@ -114,7 +114,8 @@ where
|
||||
Request = TcpConnect<Uri>,
|
||||
Response = TcpConnection<Uri, U>,
|
||||
Error = actix_connect::ConnectError,
|
||||
> + Clone,
|
||||
> + Clone
|
||||
+ 'static,
|
||||
{
|
||||
/// Connection timeout, i.e. max time to connect to remote host including dns name resolution.
|
||||
/// Set to 1 second by default.
|
||||
@ -284,7 +285,9 @@ mod connect_impl {
|
||||
pub(crate) struct InnerConnector<T, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>,
|
||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
pub(crate) tcp_pool: ConnectionPool<T, Io>,
|
||||
}
|
||||
@ -293,7 +296,8 @@ mod connect_impl {
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||
+ Clone,
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
InnerConnector {
|
||||
@ -305,7 +309,9 @@ mod connect_impl {
|
||||
impl<T, Io> Service for InnerConnector<T, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>,
|
||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
type Request = Connect;
|
||||
type Response = IoConnection<Io>;
|
||||
@ -356,9 +362,11 @@ mod connect_impl {
|
||||
Io1: AsyncRead + AsyncWrite + 'static,
|
||||
Io2: AsyncRead + AsyncWrite + 'static,
|
||||
T1: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||
+ Clone,
|
||||
+ Clone
|
||||
+ 'static,
|
||||
T2: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
||||
+ Clone,
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
InnerConnector {
|
||||
@ -372,8 +380,12 @@ mod connect_impl {
|
||||
where
|
||||
Io1: AsyncRead + AsyncWrite + 'static,
|
||||
Io2: AsyncRead + AsyncWrite + 'static,
|
||||
T1: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>,
|
||||
T2: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>,
|
||||
T1: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
T2: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
type Request = Connect;
|
||||
type Response = EitherConnection<Io1, Io2>;
|
||||
@ -409,7 +421,9 @@ mod connect_impl {
|
||||
pub(crate) struct InnerConnectorResponseA<T, Io1, Io2>
|
||||
where
|
||||
Io1: AsyncRead + AsyncWrite + 'static,
|
||||
T: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>,
|
||||
T: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
fut: <ConnectionPool<T, Io1> as Service>::Future,
|
||||
_t: PhantomData<Io2>,
|
||||
@ -417,7 +431,9 @@ mod connect_impl {
|
||||
|
||||
impl<T, Io1, Io2> Future for InnerConnectorResponseA<T, Io1, Io2>
|
||||
where
|
||||
T: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>,
|
||||
T: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
Io1: AsyncRead + AsyncWrite + 'static,
|
||||
Io2: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
@ -435,7 +451,9 @@ mod connect_impl {
|
||||
pub(crate) struct InnerConnectorResponseB<T, Io1, Io2>
|
||||
where
|
||||
Io2: AsyncRead + AsyncWrite + 'static,
|
||||
T: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>,
|
||||
T: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
fut: <ConnectionPool<T, Io2> as Service>::Future,
|
||||
_t: PhantomData<Io1>,
|
||||
@ -443,7 +461,9 @@ mod connect_impl {
|
||||
|
||||
impl<T, Io1, Io2> Future for InnerConnectorResponseB<T, Io1, Io2>
|
||||
where
|
||||
T: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>,
|
||||
T: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
Io1: AsyncRead + AsyncWrite + 'static,
|
||||
Io2: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
|
@ -274,7 +274,7 @@ impl<Io: ConnectionLifetime> Stream for PlStream<Io> {
|
||||
Ok(Async::Ready(Some(chunk)))
|
||||
} else {
|
||||
let framed = self.framed.take().unwrap();
|
||||
let force_close = framed.get_codec().keepalive();
|
||||
let force_close = !framed.get_codec().keepalive();
|
||||
release_connection(framed, force_close);
|
||||
Ok(Async::Ready(None))
|
||||
}
|
||||
|
@ -49,7 +49,9 @@ pub(crate) struct ConnectionPool<T, Io: AsyncRead + AsyncWrite + 'static>(
|
||||
impl<T, Io> ConnectionPool<T, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>,
|
||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
pub(crate) fn new(
|
||||
connector: T,
|
||||
@ -69,7 +71,7 @@ where
|
||||
waiters: Slab::new(),
|
||||
waiters_queue: IndexSet::new(),
|
||||
available: HashMap::new(),
|
||||
task: AtomicTask::new(),
|
||||
task: None,
|
||||
})),
|
||||
)
|
||||
}
|
||||
@ -88,7 +90,9 @@ where
|
||||
impl<T, Io> Service for ConnectionPool<T, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>,
|
||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
type Request = Connect;
|
||||
type Response = IoConnection<Io>;
|
||||
@ -113,15 +117,35 @@ where
|
||||
match self.1.as_ref().borrow_mut().acquire(&key) {
|
||||
Acquire::Acquired(io, created) => {
|
||||
// use existing connection
|
||||
Either::A(ok(IoConnection::new(
|
||||
return Either::A(ok(IoConnection::new(
|
||||
io,
|
||||
created,
|
||||
Some(Acquired(key, Some(self.1.clone()))),
|
||||
)))
|
||||
)));
|
||||
}
|
||||
Acquire::NotAvailable => {
|
||||
Acquire::Available => {
|
||||
// open new connection
|
||||
return Either::B(Either::B(OpenConnection::new(
|
||||
key,
|
||||
self.1.clone(),
|
||||
self.0.call(req),
|
||||
)));
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
|
||||
// connection is not available, wait
|
||||
let (rx, token) = self.1.as_ref().borrow_mut().wait_for(req);
|
||||
let (rx, token, support) = self.1.as_ref().borrow_mut().wait_for(req);
|
||||
|
||||
// start support future
|
||||
if !support {
|
||||
self.1.as_ref().borrow_mut().task = Some(AtomicTask::new());
|
||||
tokio_current_thread::spawn(ConnectorPoolSupport {
|
||||
connector: self.0.clone(),
|
||||
inner: self.1.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
Either::B(Either::A(WaitForConnection {
|
||||
rx,
|
||||
key,
|
||||
@ -129,16 +153,6 @@ where
|
||||
inner: Some(self.1.clone()),
|
||||
}))
|
||||
}
|
||||
Acquire::Available => {
|
||||
// open new connection
|
||||
Either::B(Either::B(OpenConnection::new(
|
||||
key,
|
||||
self.1.clone(),
|
||||
self.0.call(req),
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
@ -245,7 +259,7 @@ where
|
||||
Ok(Async::Ready(IoConnection::new(
|
||||
ConnectionType::H2(snd),
|
||||
Instant::now(),
|
||||
Some(Acquired(self.key.clone(), self.inner.clone())),
|
||||
Some(Acquired(self.key.clone(), self.inner.take())),
|
||||
)))
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
@ -256,12 +270,11 @@ where
|
||||
match self.fut.poll() {
|
||||
Err(err) => Err(err),
|
||||
Ok(Async::Ready((io, proto))) => {
|
||||
let _ = self.inner.take();
|
||||
if proto == Protocol::Http1 {
|
||||
Ok(Async::Ready(IoConnection::new(
|
||||
ConnectionType::H1(io),
|
||||
Instant::now(),
|
||||
Some(Acquired(self.key.clone(), self.inner.clone())),
|
||||
Some(Acquired(self.key.clone(), self.inner.take())),
|
||||
)))
|
||||
} else {
|
||||
self.h2 = Some(handshake(io));
|
||||
@ -279,7 +292,6 @@ enum Acquire<T> {
|
||||
NotAvailable,
|
||||
}
|
||||
|
||||
// #[derive(Debug)]
|
||||
struct AvailableConnection<Io> {
|
||||
io: ConnectionType<Io>,
|
||||
used: Instant,
|
||||
@ -298,7 +310,7 @@ pub(crate) struct Inner<Io> {
|
||||
oneshot::Sender<Result<IoConnection<Io>, ConnectError>>,
|
||||
)>,
|
||||
waiters_queue: IndexSet<(Key, usize)>,
|
||||
task: AtomicTask,
|
||||
task: Option<AtomicTask>,
|
||||
}
|
||||
|
||||
impl<Io> Inner<Io> {
|
||||
@ -314,18 +326,6 @@ impl<Io> Inner<Io> {
|
||||
self.waiters.remove(token);
|
||||
self.waiters_queue.remove(&(key.clone(), token));
|
||||
}
|
||||
|
||||
fn release_conn(&mut self, key: &Key, io: ConnectionType<Io>, created: Instant) {
|
||||
self.acquired -= 1;
|
||||
self.available
|
||||
.entry(key.clone())
|
||||
.or_insert_with(VecDeque::new)
|
||||
.push_back(AvailableConnection {
|
||||
io,
|
||||
created,
|
||||
used: Instant::now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl<Io> Inner<Io>
|
||||
@ -339,6 +339,7 @@ where
|
||||
) -> (
|
||||
oneshot::Receiver<Result<IoConnection<Io>, ConnectError>>,
|
||||
usize,
|
||||
bool,
|
||||
) {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
|
||||
@ -346,8 +347,9 @@ where
|
||||
let entry = self.waiters.vacant_entry();
|
||||
let token = entry.key();
|
||||
entry.insert((connect, tx));
|
||||
assert!(!self.waiters_queue.insert((key, token)));
|
||||
(rx, token)
|
||||
assert!(self.waiters_queue.insert((key, token)));
|
||||
|
||||
(rx, token, self.task.is_some())
|
||||
}
|
||||
|
||||
fn acquire(&mut self, key: &Key) -> Acquire<Io> {
|
||||
@ -400,6 +402,19 @@ where
|
||||
Acquire::Available
|
||||
}
|
||||
|
||||
fn release_conn(&mut self, key: &Key, io: ConnectionType<Io>, created: Instant) {
|
||||
self.acquired -= 1;
|
||||
self.available
|
||||
.entry(key.clone())
|
||||
.or_insert_with(VecDeque::new)
|
||||
.push_back(AvailableConnection {
|
||||
io,
|
||||
created,
|
||||
used: Instant::now(),
|
||||
});
|
||||
self.check_availibility();
|
||||
}
|
||||
|
||||
fn release_close(&mut self, io: ConnectionType<Io>) {
|
||||
self.acquired -= 1;
|
||||
if let Some(timeout) = self.disconnect_timeout {
|
||||
@ -407,11 +422,12 @@ where
|
||||
tokio_current_thread::spawn(CloseConnection::new(io, timeout))
|
||||
}
|
||||
}
|
||||
self.check_availibility();
|
||||
}
|
||||
|
||||
fn check_availibility(&self) {
|
||||
if !self.waiters_queue.is_empty() && self.acquired < self.limit {
|
||||
self.task.notify()
|
||||
self.task.as_ref().map(|t| t.notify());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -451,6 +467,147 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
struct ConnectorPoolSupport<T, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
connector: T,
|
||||
inner: Rc<RefCell<Inner<Io>>>,
|
||||
}
|
||||
|
||||
impl<T, Io> Future for ConnectorPoolSupport<T, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>,
|
||||
T::Future: 'static,
|
||||
{
|
||||
type Item = ();
|
||||
type Error = ();
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
let mut inner = self.inner.as_ref().borrow_mut();
|
||||
inner.task.as_ref().unwrap().register();
|
||||
|
||||
// check waiters
|
||||
loop {
|
||||
let (key, token) = {
|
||||
if let Some((key, token)) = inner.waiters_queue.get_index(0) {
|
||||
(key.clone(), *token)
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
};
|
||||
match inner.acquire(&key) {
|
||||
Acquire::NotAvailable => break,
|
||||
Acquire::Acquired(io, created) => {
|
||||
let (_, tx) = inner.waiters.remove(token);
|
||||
if let Err(conn) = tx.send(Ok(IoConnection::new(
|
||||
io,
|
||||
created,
|
||||
Some(Acquired(key.clone(), Some(self.inner.clone()))),
|
||||
))) {
|
||||
let (io, created) = conn.unwrap().into_inner();
|
||||
inner.release_conn(&key, io, created);
|
||||
}
|
||||
}
|
||||
Acquire::Available => {
|
||||
let (connect, tx) = inner.waiters.remove(token);
|
||||
OpenWaitingConnection::spawn(
|
||||
key.clone(),
|
||||
tx,
|
||||
self.inner.clone(),
|
||||
self.connector.call(connect),
|
||||
);
|
||||
}
|
||||
}
|
||||
let _ = inner.waiters_queue.swap_remove_index(0);
|
||||
}
|
||||
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
|
||||
struct OpenWaitingConnection<F, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
fut: F,
|
||||
key: Key,
|
||||
h2: Option<Handshake<Io, Bytes>>,
|
||||
rx: Option<oneshot::Sender<Result<IoConnection<Io>, ConnectError>>>,
|
||||
inner: Option<Rc<RefCell<Inner<Io>>>>,
|
||||
}
|
||||
|
||||
impl<F, Io> OpenWaitingConnection<F, Io>
|
||||
where
|
||||
F: Future<Item = (Io, Protocol), Error = ConnectError> + 'static,
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
fn spawn(
|
||||
key: Key,
|
||||
rx: oneshot::Sender<Result<IoConnection<Io>, ConnectError>>,
|
||||
inner: Rc<RefCell<Inner<Io>>>,
|
||||
fut: F,
|
||||
) {
|
||||
tokio_current_thread::spawn(OpenWaitingConnection {
|
||||
key,
|
||||
fut,
|
||||
h2: None,
|
||||
rx: Some(rx),
|
||||
inner: Some(inner),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Io> Drop for OpenWaitingConnection<F, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
if let Some(inner) = self.inner.take() {
|
||||
let mut inner = inner.as_ref().borrow_mut();
|
||||
inner.release();
|
||||
inner.check_availibility();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Io> Future for OpenWaitingConnection<F, Io>
|
||||
where
|
||||
F: Future<Item = (Io, Protocol), Error = ConnectError>,
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
{
|
||||
type Item = ();
|
||||
type Error = ();
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self.fut.poll() {
|
||||
Err(err) => {
|
||||
let _ = self.inner.take();
|
||||
if let Some(rx) = self.rx.take() {
|
||||
let _ = rx.send(Err(err));
|
||||
}
|
||||
Err(())
|
||||
}
|
||||
Ok(Async::Ready((io, proto))) => {
|
||||
if proto == Protocol::Http1 {
|
||||
let rx = self.rx.take().unwrap();
|
||||
let _ = rx.send(Ok(IoConnection::new(
|
||||
ConnectionType::H1(io),
|
||||
Instant::now(),
|
||||
Some(Acquired(self.key.clone(), self.inner.take())),
|
||||
)));
|
||||
Ok(Async::Ready(()))
|
||||
} else {
|
||||
self.h2 = Some(handshake(io));
|
||||
self.poll()
|
||||
}
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Acquired<T>(Key, Option<Rc<RefCell<Inner<T>>>>);
|
||||
|
||||
impl<T> Acquired<T>
|
||||
|
@ -158,7 +158,8 @@ impl ServiceConfig {
|
||||
self.0.timer.now()
|
||||
}
|
||||
|
||||
pub(crate) fn set_date(&self, dst: &mut BytesMut) {
|
||||
#[doc(hidden)]
|
||||
pub fn set_date(&self, dst: &mut BytesMut) {
|
||||
let mut buf: [u8; 39] = [0; 39];
|
||||
buf[..6].copy_from_slice(b"date: ");
|
||||
buf[6..35].copy_from_slice(&self.0.timer.date().bytes);
|
||||
|
@ -33,6 +33,7 @@ impl<B: MessageBody> Encoder<B> {
|
||||
) -> ResponseBody<Encoder<B>> {
|
||||
let can_encode = !(head.headers().contains_key(&CONTENT_ENCODING)
|
||||
|| head.status == StatusCode::SWITCHING_PROTOCOLS
|
||||
|| head.status == StatusCode::NO_CONTENT
|
||||
|| encoding == ContentEncoding::Identity
|
||||
|| encoding == ContentEncoding::Auto);
|
||||
|
||||
|
@ -137,7 +137,7 @@ impl<E: ResponseError> ResponseError for TimeoutError<E> {
|
||||
#[display(fmt = "UnknownError")]
|
||||
struct UnitError;
|
||||
|
||||
/// `InternalServerError` for `JsonError`
|
||||
/// `InternalServerError` for `UnitError`
|
||||
impl ResponseError for UnitError {}
|
||||
|
||||
/// `InternalServerError` for `JsonError`
|
||||
@ -150,11 +150,11 @@ impl ResponseError for FormError {}
|
||||
impl ResponseError for TimerError {}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
/// `InternalServerError` for `SslError`
|
||||
/// `InternalServerError` for `openssl::ssl::Error`
|
||||
impl ResponseError for openssl::ssl::Error {}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
/// `InternalServerError` for `SslError`
|
||||
/// `InternalServerError` for `openssl::ssl::HandshakeError`
|
||||
impl ResponseError for openssl::ssl::HandshakeError<tokio_tcp::TcpStream> {}
|
||||
|
||||
/// Return `BAD_REQUEST` for `de::value::Error`
|
||||
|
@ -31,7 +31,7 @@ const AVERAGE_HEADER_SIZE: usize = 30;
|
||||
|
||||
/// HTTP/1 Codec
|
||||
pub struct Codec {
|
||||
pub(crate) config: ServiceConfig,
|
||||
config: ServiceConfig,
|
||||
decoder: decoder::MessageDecoder<Request>,
|
||||
payload: Option<PayloadDecoder>,
|
||||
version: Version,
|
||||
@ -104,6 +104,11 @@ impl Codec {
|
||||
MessageType::Payload
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn config(&self) -> &ServiceConfig {
|
||||
&self.config
|
||||
}
|
||||
}
|
||||
|
||||
impl Decoder for Codec {
|
||||
|
@ -299,8 +299,14 @@ impl MessageType for ResponseHead {
|
||||
} else if src.len() >= MAX_BUFFER_SIZE {
|
||||
error!("MAX_BUFFER_SIZE unprocessed data reached, closing");
|
||||
return Err(ParseError::TooLarge);
|
||||
} else {
|
||||
// for HTTP/1.0 read to eof and close connection
|
||||
if msg.version == Version::HTTP_10 {
|
||||
msg.set_connection_type(ConnectionType::Close);
|
||||
PayloadType::Payload(PayloadDecoder::eof())
|
||||
} else {
|
||||
PayloadType::None
|
||||
}
|
||||
};
|
||||
|
||||
Ok(Some((msg, decoder)))
|
||||
@ -331,7 +337,7 @@ impl HeaderIndex {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
/// Http payload item
|
||||
pub enum PayloadItem {
|
||||
Chunk(Bytes),
|
||||
@ -1191,4 +1197,16 @@ mod tests {
|
||||
let msg = pl.decode(&mut buf).unwrap().unwrap();
|
||||
assert!(msg.eof());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_response_http10_read_until_eof() {
|
||||
let mut buf = BytesMut::from(&"HTTP/1.0 200 Ok\r\n\r\ntest data"[..]);
|
||||
|
||||
let mut reader = MessageDecoder::<ResponseHead>::default();
|
||||
let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap();
|
||||
let mut pl = pl.unwrap();
|
||||
|
||||
let chunk = pl.decode(&mut buf).unwrap().unwrap();
|
||||
assert_eq!(chunk, PayloadItem::Chunk(Bytes::from_static(b"test data")));
|
||||
}
|
||||
}
|
||||
|
@ -567,7 +567,7 @@ where
|
||||
}
|
||||
|
||||
if updated && self.ka_timer.is_some() {
|
||||
if let Some(expire) = self.codec.config.keep_alive_expire() {
|
||||
if let Some(expire) = self.codec.config().keep_alive_expire() {
|
||||
self.ka_expire = expire;
|
||||
}
|
||||
}
|
||||
@ -579,10 +579,13 @@ where
|
||||
if self.ka_timer.is_none() {
|
||||
// shutdown timeout
|
||||
if self.flags.contains(Flags::SHUTDOWN) {
|
||||
if let Some(interval) = self.codec.config.client_disconnect_timer() {
|
||||
if let Some(interval) = self.codec.config().client_disconnect_timer() {
|
||||
self.ka_timer = Some(Delay::new(interval));
|
||||
} else {
|
||||
self.flags.insert(Flags::READ_DISCONNECT);
|
||||
if let Some(mut payload) = self.payload.take() {
|
||||
payload.set_error(PayloadError::Incomplete(None));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
} else {
|
||||
@ -607,7 +610,7 @@ where
|
||||
|
||||
// start shutdown timer
|
||||
if let Some(deadline) =
|
||||
self.codec.config.client_disconnect_timer()
|
||||
self.codec.config().client_disconnect_timer()
|
||||
{
|
||||
if let Some(timer) = self.ka_timer.as_mut() {
|
||||
timer.reset(deadline);
|
||||
@ -632,7 +635,8 @@ where
|
||||
self.flags.insert(Flags::STARTED | Flags::SHUTDOWN);
|
||||
self.state = State::None;
|
||||
}
|
||||
} else if let Some(deadline) = self.codec.config.keep_alive_expire()
|
||||
} else if let Some(deadline) =
|
||||
self.codec.config().keep_alive_expire()
|
||||
{
|
||||
if let Some(timer) = self.ka_timer.as_mut() {
|
||||
timer.reset(deadline);
|
||||
@ -689,15 +693,21 @@ where
|
||||
}
|
||||
} else {
|
||||
// read socket into a buf
|
||||
let should_disconnect =
|
||||
if !inner.flags.contains(Flags::READ_DISCONNECT) {
|
||||
if let Some(true) =
|
||||
read_available(&mut inner.io, &mut inner.read_buf)?
|
||||
{
|
||||
inner.flags.insert(Flags::READ_DISCONNECT)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
inner.poll_request()?;
|
||||
if let Some(true) = should_disconnect {
|
||||
inner.flags.insert(Flags::READ_DISCONNECT);
|
||||
if let Some(mut payload) = inner.payload.take() {
|
||||
payload.feed_eof();
|
||||
}
|
||||
};
|
||||
|
||||
loop {
|
||||
if inner.write_buf.remaining_mut() < LW_BUFFER_SIZE {
|
||||
inner.write_buf.reserve(HW_BUFFER_SIZE);
|
||||
|
@ -43,6 +43,10 @@ pub(crate) trait MessageType: Sized {
|
||||
|
||||
fn headers(&self) -> &HeaderMap;
|
||||
|
||||
fn camel_case(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn chunked(&self) -> bool;
|
||||
|
||||
fn encode_status(&mut self, dst: &mut BytesMut) -> io::Result<()>;
|
||||
@ -57,6 +61,7 @@ pub(crate) trait MessageType: Sized {
|
||||
) -> io::Result<()> {
|
||||
let chunked = self.chunked();
|
||||
let mut skip_len = length != BodySize::Stream;
|
||||
let camel_case = self.camel_case();
|
||||
|
||||
// Content length
|
||||
if let Some(status) = self.status() {
|
||||
@ -74,18 +79,30 @@ pub(crate) trait MessageType: Sized {
|
||||
match length {
|
||||
BodySize::Stream => {
|
||||
if chunked {
|
||||
if camel_case {
|
||||
dst.put_slice(b"\r\nTransfer-Encoding: chunked\r\n")
|
||||
} else {
|
||||
dst.put_slice(b"\r\ntransfer-encoding: chunked\r\n")
|
||||
}
|
||||
} else {
|
||||
skip_len = false;
|
||||
dst.put_slice(b"\r\n");
|
||||
}
|
||||
}
|
||||
BodySize::Empty => {
|
||||
if camel_case {
|
||||
dst.put_slice(b"\r\nContent-Length: 0\r\n");
|
||||
} else {
|
||||
dst.put_slice(b"\r\ncontent-length: 0\r\n");
|
||||
}
|
||||
}
|
||||
BodySize::Sized(len) => helpers::write_content_length(len, dst),
|
||||
BodySize::Sized64(len) => {
|
||||
if camel_case {
|
||||
dst.put_slice(b"\r\nContent-Length: ");
|
||||
} else {
|
||||
dst.put_slice(b"\r\ncontent-length: ");
|
||||
}
|
||||
write!(dst.writer(), "{}\r\n", len)?;
|
||||
}
|
||||
BodySize::None => dst.put_slice(b"\r\n"),
|
||||
@ -95,11 +112,19 @@ pub(crate) trait MessageType: Sized {
|
||||
match ctype {
|
||||
ConnectionType::Upgrade => dst.put_slice(b"connection: upgrade\r\n"),
|
||||
ConnectionType::KeepAlive if version < Version::HTTP_11 => {
|
||||
if camel_case {
|
||||
dst.put_slice(b"Connection: keep-alive\r\n")
|
||||
} else {
|
||||
dst.put_slice(b"connection: keep-alive\r\n")
|
||||
}
|
||||
}
|
||||
ConnectionType::Close if version >= Version::HTTP_11 => {
|
||||
if camel_case {
|
||||
dst.put_slice(b"Connection: close\r\n")
|
||||
} else {
|
||||
dst.put_slice(b"connection: close\r\n")
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
|
||||
@ -133,7 +158,12 @@ pub(crate) trait MessageType: Sized {
|
||||
buf = &mut *(dst.bytes_mut() as *mut _);
|
||||
}
|
||||
}
|
||||
// use upper Camel-Case
|
||||
if camel_case {
|
||||
write_camel_case(k, &mut buf[pos..pos + k.len()]);
|
||||
} else {
|
||||
buf[pos..pos + k.len()].copy_from_slice(k);
|
||||
}
|
||||
pos += k.len();
|
||||
buf[pos..pos + 2].copy_from_slice(b": ");
|
||||
pos += 2;
|
||||
@ -158,7 +188,12 @@ pub(crate) trait MessageType: Sized {
|
||||
buf = &mut *(dst.bytes_mut() as *mut _);
|
||||
}
|
||||
}
|
||||
// use upper Camel-Case
|
||||
if camel_case {
|
||||
write_camel_case(k, &mut buf[pos..pos + k.len()]);
|
||||
} else {
|
||||
buf[pos..pos + k.len()].copy_from_slice(k);
|
||||
}
|
||||
pos += k.len();
|
||||
buf[pos..pos + 2].copy_from_slice(b": ");
|
||||
pos += 2;
|
||||
@ -221,6 +256,10 @@ impl MessageType for RequestHead {
|
||||
self.chunked()
|
||||
}
|
||||
|
||||
fn camel_case(&self) -> bool {
|
||||
RequestHead::camel_case_headers(self)
|
||||
}
|
||||
|
||||
fn headers(&self) -> &HeaderMap {
|
||||
&self.headers
|
||||
}
|
||||
@ -418,11 +457,41 @@ impl<'a> io::Write for Writer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn write_camel_case(value: &[u8], buffer: &mut [u8]) {
|
||||
let mut index = 0;
|
||||
let key = value;
|
||||
let mut key_iter = key.iter();
|
||||
|
||||
if let Some(c) = key_iter.next() {
|
||||
if *c >= b'a' && *c <= b'z' {
|
||||
buffer[index] = *c ^ b' ';
|
||||
index += 1;
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
while let Some(c) = key_iter.next() {
|
||||
buffer[index] = *c;
|
||||
index += 1;
|
||||
if *c == b'-' {
|
||||
if let Some(c) = key_iter.next() {
|
||||
if *c >= b'a' && *c <= b'z' {
|
||||
buffer[index] = *c ^ b' ';
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use bytes::Bytes;
|
||||
|
||||
use super::*;
|
||||
use crate::http::header::{HeaderValue, CONTENT_TYPE};
|
||||
|
||||
#[test]
|
||||
fn test_chunked_te() {
|
||||
let mut bytes = BytesMut::new();
|
||||
@ -436,4 +505,77 @@ mod tests {
|
||||
Bytes::from_static(b"4\r\ntest\r\n0\r\n\r\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_camel_case() {
|
||||
let mut bytes = BytesMut::with_capacity(2048);
|
||||
let mut head = RequestHead::default();
|
||||
head.set_camel_case_headers(true);
|
||||
head.headers.insert(DATE, HeaderValue::from_static("date"));
|
||||
head.headers
|
||||
.insert(CONTENT_TYPE, HeaderValue::from_static("plain/text"));
|
||||
|
||||
let _ = head.encode_headers(
|
||||
&mut bytes,
|
||||
Version::HTTP_11,
|
||||
BodySize::Empty,
|
||||
ConnectionType::Close,
|
||||
&ServiceConfig::default(),
|
||||
);
|
||||
assert_eq!(
|
||||
bytes.take().freeze(),
|
||||
Bytes::from_static(b"\r\nContent-Length: 0\r\nConnection: close\r\nDate: date\r\nContent-Type: plain/text\r\n\r\n")
|
||||
);
|
||||
|
||||
let _ = head.encode_headers(
|
||||
&mut bytes,
|
||||
Version::HTTP_11,
|
||||
BodySize::Stream,
|
||||
ConnectionType::KeepAlive,
|
||||
&ServiceConfig::default(),
|
||||
);
|
||||
assert_eq!(
|
||||
bytes.take().freeze(),
|
||||
Bytes::from_static(b"\r\nTransfer-Encoding: chunked\r\nDate: date\r\nContent-Type: plain/text\r\n\r\n")
|
||||
);
|
||||
|
||||
let _ = head.encode_headers(
|
||||
&mut bytes,
|
||||
Version::HTTP_11,
|
||||
BodySize::Sized64(100),
|
||||
ConnectionType::KeepAlive,
|
||||
&ServiceConfig::default(),
|
||||
);
|
||||
assert_eq!(
|
||||
bytes.take().freeze(),
|
||||
Bytes::from_static(b"\r\nContent-Length: 100\r\nDate: date\r\nContent-Type: plain/text\r\n\r\n")
|
||||
);
|
||||
|
||||
head.headers
|
||||
.append(CONTENT_TYPE, HeaderValue::from_static("xml"));
|
||||
let _ = head.encode_headers(
|
||||
&mut bytes,
|
||||
Version::HTTP_11,
|
||||
BodySize::Stream,
|
||||
ConnectionType::KeepAlive,
|
||||
&ServiceConfig::default(),
|
||||
);
|
||||
assert_eq!(
|
||||
bytes.take().freeze(),
|
||||
Bytes::from_static(b"\r\nTransfer-Encoding: chunked\r\nDate: date\r\nContent-Type: xml\r\nContent-Type: plain/text\r\n\r\n")
|
||||
);
|
||||
|
||||
head.set_camel_case_headers(false);
|
||||
let _ = head.encode_headers(
|
||||
&mut bytes,
|
||||
Version::HTTP_11,
|
||||
BodySize::Stream,
|
||||
ConnectionType::KeepAlive,
|
||||
&ServiceConfig::default(),
|
||||
);
|
||||
assert_eq!(
|
||||
bytes.take().freeze(),
|
||||
Bytes::from_static(b"\r\ntransfer-encoding: chunked\r\ndate: date\r\ncontent-type: xml\r\ncontent-type: plain/text\r\n\r\n")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,4 @@
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Poll};
|
||||
@ -8,6 +9,7 @@ use crate::request::Request;
|
||||
pub struct ExpectHandler;
|
||||
|
||||
impl NewService for ExpectHandler {
|
||||
type Config = ServerConfig;
|
||||
type Request = Request;
|
||||
type Response = Request;
|
||||
type Error = Error;
|
||||
@ -15,7 +17,7 @@ impl NewService for ExpectHandler {
|
||||
type InitError = Error;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
fn new_service(&self, _: &ServerConfig) -> Self::Future {
|
||||
ok(ExpectHandler)
|
||||
}
|
||||
}
|
||||
|
@ -29,14 +29,14 @@ pub struct H1Service<T, P, S, B, X = ExpectHandler, U = UpgradeHandler<T>> {
|
||||
|
||||
impl<T, P, S, B> H1Service<T, P, S, B>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
B: MessageBody,
|
||||
{
|
||||
/// Create new `HttpService` instance with default config.
|
||||
pub fn new<F: IntoNewService<S, SrvConfig>>(service: F) -> Self {
|
||||
pub fn new<F: IntoNewService<S>>(service: F) -> Self {
|
||||
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
||||
|
||||
H1Service {
|
||||
@ -49,10 +49,7 @@ where
|
||||
}
|
||||
|
||||
/// Create new `HttpService` instance with config.
|
||||
pub fn with_config<F: IntoNewService<S, SrvConfig>>(
|
||||
cfg: ServiceConfig,
|
||||
service: F,
|
||||
) -> Self {
|
||||
pub fn with_config<F: IntoNewService<S>>(cfg: ServiceConfig, service: F) -> Self {
|
||||
H1Service {
|
||||
cfg,
|
||||
srv: service.into_new_service(),
|
||||
@ -65,7 +62,7 @@ where
|
||||
|
||||
impl<T, P, S, B, X, U> H1Service<T, P, S, B, X, U>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
S::InitError: fmt::Debug,
|
||||
@ -102,21 +99,26 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, P, S, B, X, U> NewService<SrvConfig> for H1Service<T, P, S, B, X, U>
|
||||
impl<T, P, S, B, X, U> NewService for H1Service<T, P, S, B, X, U>
|
||||
where
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
S::InitError: fmt::Debug,
|
||||
B: MessageBody,
|
||||
X: NewService<Request = Request, Response = Request>,
|
||||
X: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
X::InitError: fmt::Debug,
|
||||
U: NewService<Request = (Request, Framed<T, Codec>), Response = ()>,
|
||||
U: NewService<
|
||||
Config = SrvConfig,
|
||||
Request = (Request, Framed<T, Codec>),
|
||||
Response = (),
|
||||
>,
|
||||
U::Error: fmt::Display,
|
||||
U::InitError: fmt::Debug,
|
||||
{
|
||||
type Config = SrvConfig;
|
||||
type Request = Io<T, P>;
|
||||
type Response = ();
|
||||
type Error = DispatchError;
|
||||
@ -127,8 +129,8 @@ where
|
||||
fn new_service(&self, cfg: &SrvConfig) -> Self::Future {
|
||||
H1ServiceResponse {
|
||||
fut: self.srv.new_service(cfg).into_future(),
|
||||
fut_ex: Some(self.expect.new_service(&())),
|
||||
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(&())),
|
||||
fut_ex: Some(self.expect.new_service(cfg)),
|
||||
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(cfg)),
|
||||
expect: None,
|
||||
upgrade: None,
|
||||
cfg: Some(self.cfg.clone()),
|
||||
@ -140,7 +142,7 @@ where
|
||||
#[doc(hidden)]
|
||||
pub struct H1ServiceResponse<T, P, S, B, X, U>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
X: NewService<Request = Request, Response = Request>,
|
||||
@ -162,7 +164,7 @@ where
|
||||
impl<T, P, S, B, X, U> Future for H1ServiceResponse<T, P, S, B, X, U>
|
||||
where
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
S::InitError: fmt::Debug,
|
||||
@ -320,10 +322,11 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, P> NewService<SrvConfig> for OneRequest<T, P>
|
||||
impl<T, P> NewService for OneRequest<T, P>
|
||||
where
|
||||
T: IoStream,
|
||||
{
|
||||
type Config = SrvConfig;
|
||||
type Request = Io<T, P>;
|
||||
type Response = (Request, Framed<T, Codec>);
|
||||
type Error = ParseError;
|
||||
|
@ -1,6 +1,7 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use actix_codec::Framed;
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::future::FutureResult;
|
||||
use futures::{Async, Poll};
|
||||
@ -12,6 +13,7 @@ use crate::request::Request;
|
||||
pub struct UpgradeHandler<T>(PhantomData<T>);
|
||||
|
||||
impl<T> NewService for UpgradeHandler<T> {
|
||||
type Config = ServerConfig;
|
||||
type Request = (Request, Framed<T, Codec>);
|
||||
type Response = ();
|
||||
type Error = Error;
|
||||
@ -19,7 +21,7 @@ impl<T> NewService for UpgradeHandler<T> {
|
||||
type InitError = Error;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
fn new_service(&self, _: &ServerConfig) -> Self::Future {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
@ -31,14 +31,14 @@ pub struct H2Service<T, P, S, B> {
|
||||
|
||||
impl<T, P, S, B> H2Service<T, P, S, B>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
B: MessageBody + 'static,
|
||||
{
|
||||
/// Create new `HttpService` instance.
|
||||
pub fn new<F: IntoNewService<S, SrvConfig>>(service: F) -> Self {
|
||||
pub fn new<F: IntoNewService<S>>(service: F) -> Self {
|
||||
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
||||
|
||||
H2Service {
|
||||
@ -49,10 +49,7 @@ where
|
||||
}
|
||||
|
||||
/// Create new `HttpService` instance with config.
|
||||
pub fn with_config<F: IntoNewService<S, SrvConfig>>(
|
||||
cfg: ServiceConfig,
|
||||
service: F,
|
||||
) -> Self {
|
||||
pub fn with_config<F: IntoNewService<S>>(cfg: ServiceConfig, service: F) -> Self {
|
||||
H2Service {
|
||||
cfg,
|
||||
srv: service.into_new_service(),
|
||||
@ -61,15 +58,16 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, P, S, B> NewService<SrvConfig> for H2Service<T, P, S, B>
|
||||
impl<T, P, S, B> NewService for H2Service<T, P, S, B>
|
||||
where
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
B: MessageBody + 'static,
|
||||
{
|
||||
type Config = SrvConfig;
|
||||
type Request = Io<T, P>;
|
||||
type Response = ();
|
||||
type Error = DispatchError;
|
||||
@ -87,7 +85,7 @@ where
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct H2ServiceResponse<T, P, S: NewService<SrvConfig, Request = Request>, B> {
|
||||
pub struct H2ServiceResponse<T, P, S: NewService, B> {
|
||||
fut: <S::Future as IntoFuture>::Future,
|
||||
cfg: Option<ServiceConfig>,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
@ -96,7 +94,7 @@ pub struct H2ServiceResponse<T, P, S: NewService<SrvConfig, Request = Request>,
|
||||
impl<T, P, S, B> Future for H2ServiceResponse<T, P, S, B>
|
||||
where
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
|
@ -27,6 +27,7 @@ bitflags! {
|
||||
const UPGRADE = 0b0000_0100;
|
||||
const EXPECT = 0b0000_1000;
|
||||
const NO_CHUNKING = 0b0001_0000;
|
||||
const CAMEL_CASE = 0b0010_0000;
|
||||
}
|
||||
}
|
||||
|
||||
@ -97,6 +98,23 @@ impl RequestHead {
|
||||
&mut self.headers
|
||||
}
|
||||
|
||||
/// Is to uppercase headers with Camel-Case.
|
||||
/// Befault is `false`
|
||||
#[inline]
|
||||
pub fn camel_case_headers(&self) -> bool {
|
||||
self.flags.contains(Flags::CAMEL_CASE)
|
||||
}
|
||||
|
||||
/// Set `true` to send headers which are uppercased with Camel-Case.
|
||||
#[inline]
|
||||
pub fn set_camel_case_headers(&mut self, val: bool) {
|
||||
if val {
|
||||
self.flags.insert(Flags::CAMEL_CASE);
|
||||
} else {
|
||||
self.flags.remove(Flags::CAMEL_CASE);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Set connection type of the message
|
||||
pub fn set_connection_type(&mut self, ctype: ConnectionType) {
|
||||
@ -431,6 +449,7 @@ impl BoxedResponsePool {
|
||||
fn release(&self, msg: Box<ResponseHead>) {
|
||||
let v = &mut self.0.borrow_mut();
|
||||
if v.len() < 128 {
|
||||
msg.extensions.borrow_mut().clear();
|
||||
v.push(msg);
|
||||
}
|
||||
}
|
||||
|
@ -764,6 +764,25 @@ impl IntoFuture for ResponseBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ResponseBuilder {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
let head = self.head.as_ref().unwrap();
|
||||
|
||||
let res = writeln!(
|
||||
f,
|
||||
"\nResponseBuilder {:?} {}{}",
|
||||
head.version,
|
||||
head.status,
|
||||
head.reason.unwrap_or(""),
|
||||
);
|
||||
let _ = writeln!(f, " headers:");
|
||||
for (key, val) in head.headers.iter() {
|
||||
let _ = writeln!(f, " {:?}: {:?}", key, val);
|
||||
}
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper converters
|
||||
impl<I: Into<Response>, E: Into<Error>> From<Result<I, E>> for Response {
|
||||
fn from(res: Result<I, E>) -> Self {
|
||||
|
@ -30,7 +30,7 @@ pub struct HttpService<T, P, S, B, X = h1::ExpectHandler, U = h1::UpgradeHandler
|
||||
|
||||
impl<T, S, B> HttpService<T, (), S, B>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
@ -45,7 +45,7 @@ where
|
||||
|
||||
impl<T, P, S, B> HttpService<T, P, S, B>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
@ -53,7 +53,7 @@ where
|
||||
B: MessageBody + 'static,
|
||||
{
|
||||
/// Create new `HttpService` instance.
|
||||
pub fn new<F: IntoNewService<S, SrvConfig>>(service: F) -> Self {
|
||||
pub fn new<F: IntoNewService<S>>(service: F) -> Self {
|
||||
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
||||
|
||||
HttpService {
|
||||
@ -66,7 +66,7 @@ where
|
||||
}
|
||||
|
||||
/// Create new `HttpService` instance with config.
|
||||
pub(crate) fn with_config<F: IntoNewService<S, SrvConfig>>(
|
||||
pub(crate) fn with_config<F: IntoNewService<S>>(
|
||||
cfg: ServiceConfig,
|
||||
service: F,
|
||||
) -> Self {
|
||||
@ -82,7 +82,7 @@ where
|
||||
|
||||
impl<T, P, S, B, X, U> HttpService<T, P, S, B, X, U>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
@ -95,7 +95,7 @@ where
|
||||
/// request will be forwarded to main service.
|
||||
pub fn expect<X1>(self, expect: X1) -> HttpService<T, P, S, B, X1, U>
|
||||
where
|
||||
X1: NewService<Request = Request, Response = Request>,
|
||||
X1: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||
X1::Error: Into<Error>,
|
||||
X1::InitError: fmt::Debug,
|
||||
{
|
||||
@ -114,7 +114,11 @@ where
|
||||
/// and this service get called with original request and framed object.
|
||||
pub fn upgrade<U1>(self, upgrade: Option<U1>) -> HttpService<T, P, S, B, X, U1>
|
||||
where
|
||||
U1: NewService<Request = (Request, Framed<T, h1::Codec>), Response = ()>,
|
||||
U1: NewService<
|
||||
Config = SrvConfig,
|
||||
Request = (Request, Framed<T, h1::Codec>),
|
||||
Response = (),
|
||||
>,
|
||||
U1::Error: fmt::Display,
|
||||
U1::InitError: fmt::Debug,
|
||||
{
|
||||
@ -128,22 +132,27 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, P, S, B, X, U> NewService<SrvConfig> for HttpService<T, P, S, B, X, U>
|
||||
impl<T, P, S, B, X, U> NewService for HttpService<T, P, S, B, X, U>
|
||||
where
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
B: MessageBody + 'static,
|
||||
X: NewService<Request = Request, Response = Request>,
|
||||
X: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
X::InitError: fmt::Debug,
|
||||
U: NewService<Request = (Request, Framed<T, h1::Codec>), Response = ()>,
|
||||
U: NewService<
|
||||
Config = SrvConfig,
|
||||
Request = (Request, Framed<T, h1::Codec>),
|
||||
Response = (),
|
||||
>,
|
||||
U::Error: fmt::Display,
|
||||
U::InitError: fmt::Debug,
|
||||
{
|
||||
type Config = SrvConfig;
|
||||
type Request = ServerIo<T, P>;
|
||||
type Response = ();
|
||||
type Error = DispatchError;
|
||||
@ -154,8 +163,8 @@ where
|
||||
fn new_service(&self, cfg: &SrvConfig) -> Self::Future {
|
||||
HttpServiceResponse {
|
||||
fut: self.srv.new_service(cfg).into_future(),
|
||||
fut_ex: Some(self.expect.new_service(&())),
|
||||
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(&())),
|
||||
fut_ex: Some(self.expect.new_service(cfg)),
|
||||
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(cfg)),
|
||||
expect: None,
|
||||
upgrade: None,
|
||||
cfg: Some(self.cfg.clone()),
|
||||
@ -165,14 +174,7 @@ where
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct HttpServiceResponse<
|
||||
T,
|
||||
P,
|
||||
S: NewService<SrvConfig>,
|
||||
B,
|
||||
X: NewService,
|
||||
U: NewService,
|
||||
> {
|
||||
pub struct HttpServiceResponse<T, P, S: NewService, B, X: NewService, U: NewService> {
|
||||
fut: S::Future,
|
||||
fut_ex: Option<X::Future>,
|
||||
fut_upg: Option<U::Future>,
|
||||
@ -185,7 +187,7 @@ pub struct HttpServiceResponse<
|
||||
impl<T, P, S, B, X, U> Future for HttpServiceResponse<T, P, S, B, X, U>
|
||||
where
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
|
@ -59,9 +59,7 @@ fn test_connection_close() {
|
||||
.finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.map(|_| ())
|
||||
});
|
||||
println!("REQ: {:?}", srv.get("/").force_close());
|
||||
let response = srv.block_on(srv.get("/").force_close().send()).unwrap();
|
||||
println!("RES: {:?}", response);
|
||||
assert!(response.status().is_success());
|
||||
}
|
||||
|
||||
|
@ -5,13 +5,13 @@ use std::{net, thread};
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_http_test::TestServer;
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{fn_cfg_factory, fn_service, NewService};
|
||||
use actix_service::{new_service_cfg, service_fn, NewService};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures::future::{self, ok, Future};
|
||||
use futures::stream::{once, Stream};
|
||||
use regex::Regex;
|
||||
use tokio_timer::sleep;
|
||||
|
||||
use actix_http::body::Body;
|
||||
use actix_http::error::PayloadError;
|
||||
use actix_http::{
|
||||
body, error, http, http::header, Error, HttpService, KeepAlive, Request, Response,
|
||||
@ -163,7 +163,7 @@ fn test_h2_body() -> std::io::Result<()> {
|
||||
fn test_expect_continue() {
|
||||
let srv = TestServer::new(|| {
|
||||
HttpService::build()
|
||||
.expect(fn_service(|req: Request| {
|
||||
.expect(service_fn(|req: Request| {
|
||||
if req.head().uri.query() == Some("yes=") {
|
||||
Ok(req)
|
||||
} else {
|
||||
@ -190,7 +190,7 @@ fn test_expect_continue() {
|
||||
fn test_expect_continue_h1() {
|
||||
let srv = TestServer::new(|| {
|
||||
HttpService::build()
|
||||
.expect(fn_service(|req: Request| {
|
||||
.expect(service_fn(|req: Request| {
|
||||
sleep(Duration::from_millis(20)).then(move |_| {
|
||||
if req.head().uri.query() == Some("yes=") {
|
||||
Ok(req)
|
||||
@ -215,6 +215,54 @@ fn test_expect_continue_h1() {
|
||||
assert!(data.starts_with("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_chunked_payload() {
|
||||
let chunk_sizes = vec![32768, 32, 32768];
|
||||
let total_size: usize = chunk_sizes.iter().sum();
|
||||
|
||||
let srv = TestServer::new(|| {
|
||||
HttpService::build().h1(|mut request: Request| {
|
||||
request
|
||||
.take_payload()
|
||||
.map_err(|e| panic!(format!("Error reading payload: {}", e)))
|
||||
.fold(0usize, |acc, chunk| future::ok::<_, ()>(acc + chunk.len()))
|
||||
.map(|req_size| Response::Ok().body(format!("size={}", req_size)))
|
||||
})
|
||||
});
|
||||
|
||||
let returned_size = {
|
||||
let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
|
||||
let _ = stream
|
||||
.write_all(b"POST /test HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n");
|
||||
|
||||
for chunk_size in chunk_sizes.iter() {
|
||||
let mut bytes = Vec::new();
|
||||
let random_bytes: Vec<u8> =
|
||||
(0..*chunk_size).map(|_| rand::random::<u8>()).collect();
|
||||
|
||||
bytes.extend(format!("{:X}\r\n", chunk_size).as_bytes());
|
||||
bytes.extend(&random_bytes[..]);
|
||||
bytes.extend(b"\r\n");
|
||||
let _ = stream.write_all(&bytes);
|
||||
}
|
||||
|
||||
let _ = stream.write_all(b"0\r\n\r\n");
|
||||
stream.shutdown(net::Shutdown::Write).unwrap();
|
||||
|
||||
let mut data = String::new();
|
||||
let _ = stream.read_to_string(&mut data);
|
||||
|
||||
let re = Regex::new(r"size=(\d+)").unwrap();
|
||||
let size: usize = match re.captures(&data) {
|
||||
Some(caps) => caps.get(1).unwrap().as_str().parse().unwrap(),
|
||||
None => panic!(format!("Failed to find size in HTTP Response: {}", data)),
|
||||
};
|
||||
size
|
||||
};
|
||||
|
||||
assert_eq!(returned_size, total_size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_slow_request() {
|
||||
let srv = TestServer::new(|| {
|
||||
@ -775,8 +823,7 @@ fn test_h1_body_length() {
|
||||
HttpService::build().h1(|_| {
|
||||
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.body(Body::from_message(body::SizedStream::new(STR.len(), body))),
|
||||
Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)),
|
||||
)
|
||||
})
|
||||
});
|
||||
@ -801,9 +848,10 @@ fn test_h2_body_length() {
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(Response::Ok().body(Body::from_message(
|
||||
body::SizedStream::new(STR.len(), body),
|
||||
)))
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.body(body::SizedStream::new(STR.len() as u64, body)),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
@ -912,7 +960,7 @@ fn test_h1_body_chunked_implicit() {
|
||||
#[test]
|
||||
fn test_h1_response_http_error_handling() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
HttpService::build().h1(fn_cfg_factory(|_: &ServerConfig| {
|
||||
HttpService::build().h1(new_service_cfg(|_: &ServerConfig| {
|
||||
Ok::<_, ()>(|_| {
|
||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||
ok::<_, ()>(
|
||||
@ -943,7 +991,7 @@ fn test_h2_response_http_error_handling() {
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(fn_cfg_factory(|_: &ServerConfig| {
|
||||
.h2(new_service_cfg(|_: &ServerConfig| {
|
||||
Ok::<_, ()>(|_| {
|
||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||
ok::<_, ()>(
|
||||
|
5
actix-identity/CHANGES.md
Normal file
5
actix-identity/CHANGES.md
Normal file
@ -0,0 +1,5 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.0] - 2019-06-xx
|
||||
|
||||
* Move identity middleware to separate crate
|
30
actix-identity/Cargo.toml
Normal file
30
actix-identity/Cargo.toml
Normal file
@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "actix-identity"
|
||||
version = "0.1.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Identity service for actix web framework."
|
||||
readme = "README.md"
|
||||
keywords = ["http", "web", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-web.git"
|
||||
documentation = "https://docs.rs/actix-identity/"
|
||||
license = "MIT/Apache-2.0"
|
||||
edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
[lib]
|
||||
name = "actix_identity"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = { version = "1.0.0", default-features = false, features = ["secure-cookies"] }
|
||||
actix-service = "0.4.0"
|
||||
futures = "0.1.25"
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
time = "0.1.42"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
actix-http = "0.2.3"
|
||||
bytes = "0.4"
|
1
actix-identity/LICENSE-APACHE
Symbolic link
1
actix-identity/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-identity/LICENSE-MIT
Symbolic link
1
actix-identity/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
9
actix-identity/README.md
Normal file
9
actix-identity/README.md
Normal file
@ -0,0 +1,9 @@
|
||||
# Identity service for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-identity) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
## Documentation & community resources
|
||||
|
||||
* [User Guide](https://actix.rs/docs/)
|
||||
* [API Documentation](https://docs.rs/actix-identity/)
|
||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||
* Cargo package: [actix-session](https://crates.io/crates/actix-identity)
|
||||
* Minimum supported Rust version: 1.34 or later
|
1056
actix-identity/src/lib.rs
Normal file
1056
actix-identity/src/lib.rs
Normal file
File diff suppressed because it is too large
Load Diff
@ -1,7 +1,31 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.0-alpha.1] - 2019-04-xx
|
||||
## [0.1.3] - 2019-06-06
|
||||
|
||||
* Fix ring dependency from actix-web default features for #741.
|
||||
|
||||
## [0.1.2] - 2019-06-02
|
||||
|
||||
* Fix boundary parsing #876
|
||||
|
||||
## [0.1.1] - 2019-05-25
|
||||
|
||||
* Fix disconnect handling #834
|
||||
|
||||
## [0.1.0] - 2019-05-18
|
||||
|
||||
* Release
|
||||
|
||||
## [0.1.0-beta.4] - 2019-05-12
|
||||
|
||||
* Handle cancellation of uploads #736
|
||||
|
||||
* Upgrade to actix-web 1.0.0-beta.4
|
||||
|
||||
## [0.1.0-beta.1] - 2019-04-21
|
||||
|
||||
* Do not support nested multipart
|
||||
|
||||
* Split multipart support to separate crate
|
||||
|
||||
* Optimize multipart handling #634, #769
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-multipart"
|
||||
version = "0.1.0-alpha.1"
|
||||
version = "0.1.3"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Multipart support for actix web framework."
|
||||
readme = "README.md"
|
||||
@ -18,10 +18,10 @@ name = "actix_multipart"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.0-alpha.6"
|
||||
actix-service = "0.3.4"
|
||||
actix-web = { version = "1.0.0", default-features = false }
|
||||
actix-service = "0.4.1"
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
derive_more = "0.15.0"
|
||||
httparse = "1.3"
|
||||
futures = "0.1.25"
|
||||
log = "0.4"
|
||||
@ -31,4 +31,4 @@ twoway = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
actix-http = "0.1.0"
|
||||
actix-http = "0.2.4"
|
1
actix-multipart/LICENSE-APACHE
Symbolic link
1
actix-multipart/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-multipart/LICENSE-MIT
Symbolic link
1
actix-multipart/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -1 +1,8 @@
|
||||
# Multipart support for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-multipart) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
## Documentation & community resources
|
||||
|
||||
* [API Documentation](https://docs.rs/actix-multipart/)
|
||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||
* Cargo package: [actix-multipart](https://crates.io/crates/actix-multipart)
|
||||
* Minimum supported Rust version: 1.33 or later
|
||||
|
@ -28,6 +28,9 @@ pub enum MultipartError {
|
||||
/// Payload error
|
||||
#[display(fmt = "{}", _0)]
|
||||
Payload(PayloadError),
|
||||
/// Not consumed
|
||||
#[display(fmt = "Multipart stream is not consumed")]
|
||||
NotConsumed,
|
||||
}
|
||||
|
||||
/// Return `BadRequest` for `MultipartError`
|
||||
|
@ -1,5 +1,5 @@
|
||||
//! Multipart payload support
|
||||
use std::cell::{RefCell, UnsafeCell};
|
||||
use std::cell::{Cell, RefCell, UnsafeCell};
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
use std::{cmp, fmt};
|
||||
@ -116,6 +116,8 @@ impl Stream for Multipart {
|
||||
payload.poll_stream()?;
|
||||
}
|
||||
inner.poll(&self.safety)
|
||||
} else if !self.safety.is_clean() {
|
||||
Err(MultipartError::NotConsumed)
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
@ -126,7 +128,7 @@ impl InnerMultipart {
|
||||
fn read_headers(
|
||||
payload: &mut PayloadBuffer,
|
||||
) -> Result<Option<HeaderMap>, MultipartError> {
|
||||
match payload.read_until(b"\r\n\r\n") {
|
||||
match payload.read_until(b"\r\n\r\n")? {
|
||||
None => {
|
||||
if payload.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
@ -165,10 +167,10 @@ impl InnerMultipart {
|
||||
boundary: &str,
|
||||
) -> Result<Option<bool>, MultipartError> {
|
||||
// TODO: need to read epilogue
|
||||
match payload.readline() {
|
||||
match payload.readline()? {
|
||||
None => {
|
||||
if payload.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
Ok(Some(true))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
@ -198,11 +200,10 @@ impl InnerMultipart {
|
||||
) -> Result<Option<bool>, MultipartError> {
|
||||
let mut eof = false;
|
||||
loop {
|
||||
match payload.readline() {
|
||||
match payload.readline()? {
|
||||
Some(chunk) => {
|
||||
if chunk.is_empty() {
|
||||
//ValueError("Could not find starting boundary %r"
|
||||
//% (self._boundary))
|
||||
return Err(MultipartError::Boundary);
|
||||
}
|
||||
if chunk.len() < boundary.len() {
|
||||
continue;
|
||||
@ -416,6 +417,8 @@ impl Stream for Field {
|
||||
}
|
||||
|
||||
inner.poll(&self.safety)
|
||||
} else if !self.safety.is_clean() {
|
||||
return Err(MultipartError::NotConsumed);
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
@ -478,7 +481,7 @@ impl InnerField {
|
||||
if *size == 0 {
|
||||
Ok(Async::Ready(None))
|
||||
} else {
|
||||
match payload.read_max(*size) {
|
||||
match payload.read_max(*size)? {
|
||||
Some(mut chunk) => {
|
||||
let len = cmp::min(chunk.len() as u64, *size);
|
||||
*size -= len;
|
||||
@ -505,47 +508,74 @@ impl InnerField {
|
||||
payload: &mut PayloadBuffer,
|
||||
boundary: &str,
|
||||
) -> Poll<Option<Bytes>, MultipartError> {
|
||||
match payload.read_until(b"\r") {
|
||||
None => {
|
||||
if payload.eof {
|
||||
let mut pos = 0;
|
||||
|
||||
let len = payload.buf.len();
|
||||
if len == 0 {
|
||||
return if payload.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
};
|
||||
}
|
||||
|
||||
// check boundary
|
||||
if len > 4 && payload.buf[0] == b'\r' {
|
||||
let b_len = if &payload.buf[..2] == b"\r\n" && &payload.buf[2..4] == b"--" {
|
||||
Some(4)
|
||||
} else if &payload.buf[1..3] == b"--" {
|
||||
Some(3)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(b_len) = b_len {
|
||||
let b_size = boundary.len() + b_len;
|
||||
if len < b_size {
|
||||
return Ok(Async::NotReady);
|
||||
} else {
|
||||
if &payload.buf[b_len..b_size] == boundary.as_bytes() {
|
||||
// found boundary
|
||||
return Ok(Async::Ready(None));
|
||||
}
|
||||
}
|
||||
Some(mut chunk) => {
|
||||
if chunk.len() == 1 {
|
||||
payload.unprocessed(chunk);
|
||||
match payload.read_exact(boundary.len() + 4) {
|
||||
None => {
|
||||
if payload.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
}
|
||||
}
|
||||
|
||||
loop {
|
||||
return if let Some(idx) = twoway::find_bytes(&payload.buf[pos..], b"\r") {
|
||||
let cur = pos + idx;
|
||||
|
||||
// check if we have enough data for boundary detection
|
||||
if cur + 4 > len {
|
||||
if cur > 0 {
|
||||
Ok(Async::Ready(Some(payload.buf.split_to(cur).freeze())))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
Some(mut chunk) => {
|
||||
if &chunk[..2] == b"\r\n"
|
||||
&& &chunk[2..4] == b"--"
|
||||
&& &chunk[4..] == boundary.as_bytes()
|
||||
} else {
|
||||
// check boundary
|
||||
if (&payload.buf[cur..cur + 2] == b"\r\n"
|
||||
&& &payload.buf[cur + 2..cur + 4] == b"--")
|
||||
|| (&payload.buf[cur..cur + 1] == b"\r"
|
||||
&& &payload.buf[cur + 1..cur + 3] == b"--")
|
||||
{
|
||||
payload.unprocessed(chunk);
|
||||
Ok(Async::Ready(None))
|
||||
if cur != 0 {
|
||||
// return buffer
|
||||
Ok(Async::Ready(Some(payload.buf.split_to(cur).freeze())))
|
||||
} else {
|
||||
// \r might be part of data stream
|
||||
let ch = chunk.split_to(1);
|
||||
payload.unprocessed(chunk);
|
||||
Ok(Async::Ready(Some(ch)))
|
||||
pos = cur + 1;
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
// not boundary
|
||||
pos = cur + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let to = chunk.len() - 1;
|
||||
let ch = chunk.split_to(to);
|
||||
payload.unprocessed(chunk);
|
||||
Ok(Async::Ready(Some(ch)))
|
||||
}
|
||||
}
|
||||
Ok(Async::Ready(Some(payload.buf.take().freeze())))
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ -555,6 +585,7 @@ impl InnerField {
|
||||
}
|
||||
|
||||
let result = if let Some(payload) = self.payload.as_ref().unwrap().get_mut(s) {
|
||||
if !self.eof {
|
||||
let res = if let Some(ref mut len) = self.length {
|
||||
InnerField::read_len(payload, len)?
|
||||
} else {
|
||||
@ -562,11 +593,13 @@ impl InnerField {
|
||||
};
|
||||
|
||||
match res {
|
||||
Async::NotReady => Async::NotReady,
|
||||
Async::Ready(Some(bytes)) => Async::Ready(Some(bytes)),
|
||||
Async::Ready(None) => {
|
||||
self.eof = true;
|
||||
match payload.readline() {
|
||||
Async::NotReady => return Ok(Async::NotReady),
|
||||
Async::Ready(Some(bytes)) => return Ok(Async::Ready(Some(bytes))),
|
||||
Async::Ready(None) => self.eof = true,
|
||||
}
|
||||
}
|
||||
|
||||
match payload.readline()? {
|
||||
None => Async::Ready(None),
|
||||
Some(line) => {
|
||||
if line.as_ref() != b"\r\n" {
|
||||
@ -575,8 +608,6 @@ impl InnerField {
|
||||
Async::Ready(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Async::NotReady
|
||||
};
|
||||
@ -630,6 +661,7 @@ struct Safety {
|
||||
task: Option<Task>,
|
||||
level: usize,
|
||||
payload: Rc<PhantomData<bool>>,
|
||||
clean: Rc<Cell<bool>>,
|
||||
}
|
||||
|
||||
impl Safety {
|
||||
@ -638,12 +670,17 @@ impl Safety {
|
||||
Safety {
|
||||
task: None,
|
||||
level: Rc::strong_count(&payload),
|
||||
clean: Rc::new(Cell::new(true)),
|
||||
payload,
|
||||
}
|
||||
}
|
||||
|
||||
fn current(&self) -> bool {
|
||||
Rc::strong_count(&self.payload) == self.level
|
||||
Rc::strong_count(&self.payload) == self.level && self.clean.get()
|
||||
}
|
||||
|
||||
fn is_clean(&self) -> bool {
|
||||
self.clean.get()
|
||||
}
|
||||
}
|
||||
|
||||
@ -653,6 +690,7 @@ impl Clone for Safety {
|
||||
Safety {
|
||||
task: Some(current_task()),
|
||||
level: Rc::strong_count(&payload),
|
||||
clean: self.clean.clone(),
|
||||
payload,
|
||||
}
|
||||
}
|
||||
@ -662,7 +700,7 @@ impl Drop for Safety {
|
||||
fn drop(&mut self) {
|
||||
// parent task is dead
|
||||
if Rc::strong_count(&self.payload) != self.level {
|
||||
panic!("Safety get dropped but it is not from top-most task");
|
||||
self.clean.set(true);
|
||||
}
|
||||
if let Some(task) = self.task.take() {
|
||||
task.notify()
|
||||
@ -704,7 +742,7 @@ impl PayloadBuffer {
|
||||
}
|
||||
|
||||
/// Read exact number of bytes
|
||||
#[inline]
|
||||
#[cfg(test)]
|
||||
fn read_exact(&mut self, size: usize) -> Option<Bytes> {
|
||||
if size <= self.buf.len() {
|
||||
Some(self.buf.split_to(size).freeze())
|
||||
@ -713,23 +751,31 @@ impl PayloadBuffer {
|
||||
}
|
||||
}
|
||||
|
||||
fn read_max(&mut self, size: u64) -> Option<Bytes> {
|
||||
fn read_max(&mut self, size: u64) -> Result<Option<Bytes>, MultipartError> {
|
||||
if !self.buf.is_empty() {
|
||||
let size = std::cmp::min(self.buf.len() as u64, size) as usize;
|
||||
Some(self.buf.split_to(size).freeze())
|
||||
Ok(Some(self.buf.split_to(size).freeze()))
|
||||
} else if self.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
} else {
|
||||
None
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Read until specified ending
|
||||
pub fn read_until(&mut self, line: &[u8]) -> Option<Bytes> {
|
||||
twoway::find_bytes(&self.buf, line)
|
||||
.map(|idx| self.buf.split_to(idx + line.len()).freeze())
|
||||
pub fn read_until(&mut self, line: &[u8]) -> Result<Option<Bytes>, MultipartError> {
|
||||
let res = twoway::find_bytes(&self.buf, line)
|
||||
.map(|idx| self.buf.split_to(idx + line.len()).freeze());
|
||||
|
||||
if res.is_none() && self.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
} else {
|
||||
Ok(res)
|
||||
}
|
||||
}
|
||||
|
||||
/// Read bytes until new line delimiter
|
||||
pub fn readline(&mut self) -> Option<Bytes> {
|
||||
pub fn readline(&mut self) -> Result<Option<Bytes>, MultipartError> {
|
||||
self.read_until(b"\n")
|
||||
}
|
||||
|
||||
@ -875,6 +921,78 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stream() {
|
||||
run_on(|| {
|
||||
let (sender, payload) = create_stream();
|
||||
|
||||
let bytes = Bytes::from(
|
||||
"testasdadsad\r\n\
|
||||
--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
|
||||
Content-Disposition: form-data; name=\"file\"; filename=\"fn.txt\"\r\n\
|
||||
Content-Type: text/plain; charset=utf-8\r\n\r\n\
|
||||
test\r\n\
|
||||
--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
|
||||
Content-Type: text/plain; charset=utf-8\r\n\r\n\
|
||||
data\r\n\
|
||||
--abbc761f78ff4d7cb7573b5a23f96ef0--\r\n",
|
||||
);
|
||||
sender.unbounded_send(Ok(bytes)).unwrap();
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
header::HeaderValue::from_static(
|
||||
"multipart/mixed; boundary=\"abbc761f78ff4d7cb7573b5a23f96ef0\"",
|
||||
),
|
||||
);
|
||||
|
||||
let mut multipart = Multipart::new(&headers, payload);
|
||||
match multipart.poll().unwrap() {
|
||||
Async::Ready(Some(mut field)) => {
|
||||
let cd = field.content_disposition().unwrap();
|
||||
assert_eq!(cd.disposition, DispositionType::FormData);
|
||||
assert_eq!(cd.parameters[0], DispositionParam::Name("file".into()));
|
||||
|
||||
assert_eq!(field.content_type().type_(), mime::TEXT);
|
||||
assert_eq!(field.content_type().subtype(), mime::PLAIN);
|
||||
|
||||
match field.poll().unwrap() {
|
||||
Async::Ready(Some(chunk)) => assert_eq!(chunk, "test"),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
match field.poll().unwrap() {
|
||||
Async::Ready(None) => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
|
||||
match multipart.poll().unwrap() {
|
||||
Async::Ready(Some(mut field)) => {
|
||||
assert_eq!(field.content_type().type_(), mime::TEXT);
|
||||
assert_eq!(field.content_type().subtype(), mime::PLAIN);
|
||||
|
||||
match field.poll() {
|
||||
Ok(Async::Ready(Some(chunk))) => assert_eq!(chunk, "data"),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
match field.poll() {
|
||||
Ok(Async::Ready(None)) => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
|
||||
match multipart.poll().unwrap() {
|
||||
Async::Ready(None) => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_basic() {
|
||||
run_on(|| {
|
||||
@ -883,7 +1001,7 @@ mod tests {
|
||||
|
||||
assert_eq!(payload.buf.len(), 0);
|
||||
payload.poll_stream().unwrap();
|
||||
assert_eq!(None, payload.read_max(1));
|
||||
assert_eq!(None, payload.read_max(1).unwrap());
|
||||
})
|
||||
}
|
||||
|
||||
@ -893,14 +1011,14 @@ mod tests {
|
||||
let (mut sender, payload) = Payload::create(false);
|
||||
let mut payload = PayloadBuffer::new(payload);
|
||||
|
||||
assert_eq!(None, payload.read_max(4));
|
||||
assert_eq!(None, payload.read_max(4).unwrap());
|
||||
sender.feed_data(Bytes::from("data"));
|
||||
sender.feed_eof();
|
||||
payload.poll_stream().unwrap();
|
||||
|
||||
assert_eq!(Some(Bytes::from("data")), payload.read_max(4));
|
||||
assert_eq!(Some(Bytes::from("data")), payload.read_max(4).unwrap());
|
||||
assert_eq!(payload.buf.len(), 0);
|
||||
assert_eq!(None, payload.read_max(1));
|
||||
assert!(payload.read_max(1).is_err());
|
||||
assert!(payload.eof);
|
||||
})
|
||||
}
|
||||
@ -910,7 +1028,7 @@ mod tests {
|
||||
run_on(|| {
|
||||
let (mut sender, payload) = Payload::create(false);
|
||||
let mut payload = PayloadBuffer::new(payload);
|
||||
assert_eq!(None, payload.read_max(1));
|
||||
assert_eq!(None, payload.read_max(1).unwrap());
|
||||
sender.set_error(PayloadError::Incomplete(None));
|
||||
payload.poll_stream().err().unwrap();
|
||||
})
|
||||
@ -927,10 +1045,10 @@ mod tests {
|
||||
payload.poll_stream().unwrap();
|
||||
assert_eq!(payload.buf.len(), 10);
|
||||
|
||||
assert_eq!(Some(Bytes::from("line1")), payload.read_max(5));
|
||||
assert_eq!(Some(Bytes::from("line1")), payload.read_max(5).unwrap());
|
||||
assert_eq!(payload.buf.len(), 5);
|
||||
|
||||
assert_eq!(Some(Bytes::from("line2")), payload.read_max(5));
|
||||
assert_eq!(Some(Bytes::from("line2")), payload.read_max(5).unwrap());
|
||||
assert_eq!(payload.buf.len(), 0);
|
||||
})
|
||||
}
|
||||
@ -961,16 +1079,22 @@ mod tests {
|
||||
let (mut sender, payload) = Payload::create(false);
|
||||
let mut payload = PayloadBuffer::new(payload);
|
||||
|
||||
assert_eq!(None, payload.read_until(b"ne"));
|
||||
assert_eq!(None, payload.read_until(b"ne").unwrap());
|
||||
|
||||
sender.feed_data(Bytes::from("line1"));
|
||||
sender.feed_data(Bytes::from("line2"));
|
||||
payload.poll_stream().unwrap();
|
||||
|
||||
assert_eq!(Some(Bytes::from("line")), payload.read_until(b"ne"));
|
||||
assert_eq!(
|
||||
Some(Bytes::from("line")),
|
||||
payload.read_until(b"ne").unwrap()
|
||||
);
|
||||
assert_eq!(payload.buf.len(), 6);
|
||||
|
||||
assert_eq!(Some(Bytes::from("1line2")), payload.read_until(b"2"));
|
||||
assert_eq!(
|
||||
Some(Bytes::from("1line2")),
|
||||
payload.read_until(b"2").unwrap()
|
||||
);
|
||||
assert_eq!(payload.buf.len(), 0);
|
||||
})
|
||||
}
|
||||
|
@ -1,5 +1,24 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.1] - 2019-06-03
|
||||
|
||||
* Fix optional cookie session support
|
||||
|
||||
## [0.1.0] - 2019-05-18
|
||||
|
||||
* Use actix-web 1.0.0-rc
|
||||
|
||||
## [0.1.0-beta.4] - 2019-05-12
|
||||
|
||||
* Use actix-web 1.0.0-beta.4
|
||||
|
||||
## [0.1.0-beta.2] - 2019-04-28
|
||||
|
||||
* Add helper trait `UserSession` which allows to get session for ServiceRequest and HttpRequest
|
||||
|
||||
## [0.1.0-beta.1] - 2019-04-20
|
||||
|
||||
* Update actix-web to beta.1
|
||||
|
||||
* `CookieSession::max_age()` accepts value in seconds
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-session"
|
||||
version = "0.1.0-alpha.6"
|
||||
version = "0.1.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Session for actix web framework."
|
||||
readme = "README.md"
|
||||
@ -24,12 +24,12 @@ default = ["cookie-session"]
|
||||
cookie-session = ["actix-web/secure-cookies"]
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.0-alpha.6"
|
||||
actix-service = "0.3.4"
|
||||
actix-web = "1.0.0"
|
||||
actix-service = "0.4.1"
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
derive_more = "0.15.0"
|
||||
futures = "0.1.25"
|
||||
hashbrown = "0.2.0"
|
||||
hashbrown = "0.5.0"
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
time = "0.1.42"
|
||||
|
1
actix-session/LICENSE-APACHE
Symbolic link
1
actix-session/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-session/LICENSE-MIT
Symbolic link
1
actix-session/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -1 +1,9 @@
|
||||
# Session for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-session) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
## Documentation & community resources
|
||||
|
||||
* [User Guide](https://actix.rs/docs/)
|
||||
* [API Documentation](https://docs.rs/actix-session/)
|
||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||
* Cargo package: [actix-session](https://crates.io/crates/actix-session)
|
||||
* Minimum supported Rust version: 1.33 or later
|
||||
|
@ -52,7 +52,9 @@ use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
use serde_json;
|
||||
|
||||
#[cfg(feature = "cookie-session")]
|
||||
mod cookie;
|
||||
#[cfg(feature = "cookie-session")]
|
||||
pub use crate::cookie::CookieSession;
|
||||
|
||||
/// The high-level interface you use to modify session data.
|
||||
@ -79,6 +81,23 @@ pub use crate::cookie::CookieSession;
|
||||
/// ```
|
||||
pub struct Session(Rc<RefCell<SessionInner>>);
|
||||
|
||||
/// Helper trait that allows to get session
|
||||
pub trait UserSession {
|
||||
fn get_session(&mut self) -> Session;
|
||||
}
|
||||
|
||||
impl UserSession for HttpRequest {
|
||||
fn get_session(&mut self) -> Session {
|
||||
Session::get_session(&mut *self.extensions_mut())
|
||||
}
|
||||
}
|
||||
|
||||
impl UserSession for ServiceRequest {
|
||||
fn get_session(&mut self) -> Session {
|
||||
Session::get_session(&mut *self.extensions_mut())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SessionInner {
|
||||
state: HashMap<String, String>,
|
||||
@ -208,4 +227,18 @@ mod tests {
|
||||
let changes: Vec<_> = Session::get_changes(&mut res).unwrap().collect();
|
||||
assert_eq!(changes, [("key2".to_string(), "\"value2\"".to_string())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_session() {
|
||||
let mut req = test::TestRequest::default().to_srv_request();
|
||||
|
||||
Session::set_session(
|
||||
vec![("key".to_string(), "\"value\"".to_string())].into_iter(),
|
||||
&mut req,
|
||||
);
|
||||
|
||||
let session = req.get_session();
|
||||
let res = session.get::<String>("key").unwrap();
|
||||
assert_eq!(res, Some("value".to_string()));
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,9 @@
|
||||
# Changes
|
||||
|
||||
## [1.0.0] - 2019-05-29
|
||||
|
||||
* Update actix-http and actix-web
|
||||
|
||||
## [0.1.0-alpha.3] - 2019-04-02
|
||||
|
||||
* Update actix-http and actix-web
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web-actors"
|
||||
version = "1.0.0-alpha.3"
|
||||
version = "1.0.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix actors support for actix web framework."
|
||||
readme = "README.md"
|
||||
@ -18,13 +18,13 @@ name = "actix_web_actors"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix = "0.8.0"
|
||||
actix-web = "1.0.0-alpha.5"
|
||||
actix-http = "0.1.0"
|
||||
actix = "0.8.3"
|
||||
actix-web = "1.0.0"
|
||||
actix-http = "0.2.4"
|
||||
actix-codec = "0.1.2"
|
||||
bytes = "0.4"
|
||||
futures = "0.1.25"
|
||||
|
||||
[dev-dependencies]
|
||||
env_logger = "0.6"
|
||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
|
1
actix-web-actors/LICENSE-APACHE
Symbolic link
1
actix-web-actors/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-web-actors/LICENSE-MIT
Symbolic link
1
actix-web-actors/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -1 +1,8 @@
|
||||
Actix actors support for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-web-actors) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
## Documentation & community resources
|
||||
|
||||
* [API Documentation](https://docs.rs/actix-web-actors/)
|
||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||
* Cargo package: [actix-web-actors](https://crates.io/crates/actix-web-actors)
|
||||
* Minimum supported Rust version: 1.33 or later
|
||||
|
@ -1,5 +1,21 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.2] - 2019-06-04
|
||||
|
||||
* Add macros for head, options, trace, connect and patch http methods
|
||||
|
||||
## [0.1.1] - 2019-06-01
|
||||
|
||||
* Add syn "extra-traits" feature
|
||||
|
||||
## [0.1.0] - 2019-05-18
|
||||
|
||||
* Release
|
||||
|
||||
## [0.1.0-beta.1] - 2019-04-20
|
||||
|
||||
* Gen code for actix-web 1.0.0-beta.1
|
||||
|
||||
## [0.1.0-alpha.6] - 2019-04-14
|
||||
|
||||
* Gen code for actix-web 1.0.0-alpha.6
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web-codegen"
|
||||
version = "0.1.0-alpha.6"
|
||||
version = "0.1.2"
|
||||
description = "Actix web proc macros"
|
||||
readme = "README.md"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
@ -12,11 +12,11 @@ workspace = ".."
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
quote = "0.6"
|
||||
syn = { version = "0.15", features = ["full", "parsing"] }
|
||||
quote = "0.6.12"
|
||||
syn = { version = "0.15.34", features = ["full", "parsing", "extra-traits"] }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = { version = "1.0.0-alpha.6" }
|
||||
actix-http = { version = "0.1.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||
actix-web = { version = "1.0.0" }
|
||||
actix-http = { version = "0.2.4", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
futures = { version = "0.1" }
|
||||
|
1
actix-web-codegen/LICENSE-APACHE
Symbolic link
1
actix-web-codegen/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-web-codegen/LICENSE-MIT
Symbolic link
1
actix-web-codegen/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -11,6 +11,11 @@
|
||||
//! - [post](attr.post.html)
|
||||
//! - [put](attr.put.html)
|
||||
//! - [delete](attr.delete.html)
|
||||
//! - [head](attr.head.html)
|
||||
//! - [connect](attr.connect.html)
|
||||
//! - [options](attr.options.html)
|
||||
//! - [trace](attr.trace.html)
|
||||
//! - [patch](attr.patch.html)
|
||||
//!
|
||||
//! ### Attributes:
|
||||
//!
|
||||
@ -92,3 +97,63 @@ pub fn delete(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Delete);
|
||||
gen.generate()
|
||||
}
|
||||
|
||||
/// Creates route handler with `HEAD` method guard.
|
||||
///
|
||||
/// Syntax: `#[head("path"[, attributes])]`
|
||||
///
|
||||
/// Attributes are the same as in [head](attr.head.html)
|
||||
#[proc_macro_attribute]
|
||||
pub fn head(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Head);
|
||||
gen.generate()
|
||||
}
|
||||
|
||||
/// Creates route handler with `CONNECT` method guard.
|
||||
///
|
||||
/// Syntax: `#[connect("path"[, attributes])]`
|
||||
///
|
||||
/// Attributes are the same as in [connect](attr.connect.html)
|
||||
#[proc_macro_attribute]
|
||||
pub fn connect(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Connect);
|
||||
gen.generate()
|
||||
}
|
||||
|
||||
/// Creates route handler with `OPTIONS` method guard.
|
||||
///
|
||||
/// Syntax: `#[options("path"[, attributes])]`
|
||||
///
|
||||
/// Attributes are the same as in [options](attr.options.html)
|
||||
#[proc_macro_attribute]
|
||||
pub fn options(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Options);
|
||||
gen.generate()
|
||||
}
|
||||
|
||||
/// Creates route handler with `TRACE` method guard.
|
||||
///
|
||||
/// Syntax: `#[trace("path"[, attributes])]`
|
||||
///
|
||||
/// Attributes are the same as in [trace](attr.trace.html)
|
||||
#[proc_macro_attribute]
|
||||
pub fn trace(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Trace);
|
||||
gen.generate()
|
||||
}
|
||||
|
||||
/// Creates route handler with `PATCH` method guard.
|
||||
///
|
||||
/// Syntax: `#[patch("path"[, attributes])]`
|
||||
///
|
||||
/// Attributes are the same as in [patch](attr.patch.html)
|
||||
#[proc_macro_attribute]
|
||||
pub fn patch(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Patch);
|
||||
gen.generate()
|
||||
}
|
||||
|
@ -25,6 +25,11 @@ pub enum GuardType {
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Head,
|
||||
Connect,
|
||||
Options,
|
||||
Trace,
|
||||
Patch,
|
||||
}
|
||||
|
||||
impl fmt::Display for GuardType {
|
||||
@ -34,6 +39,11 @@ impl fmt::Display for GuardType {
|
||||
&GuardType::Post => write!(f, "Post"),
|
||||
&GuardType::Put => write!(f, "Put"),
|
||||
&GuardType::Delete => write!(f, "Delete"),
|
||||
&GuardType::Head => write!(f, "Head"),
|
||||
&GuardType::Connect => write!(f, "Connect"),
|
||||
&GuardType::Options => write!(f, "Options"),
|
||||
&GuardType::Trace => write!(f, "Trace"),
|
||||
&GuardType::Patch => write!(f, "Patch"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
use actix_http::HttpService;
|
||||
use actix_http_test::TestServer;
|
||||
use actix_web::{http, App, HttpResponse, Responder};
|
||||
use actix_web_codegen::get;
|
||||
use actix_web::{http, web::Path, App, HttpResponse, Responder};
|
||||
use actix_web_codegen::{connect, delete, get, head, options, patch, post, put, trace};
|
||||
use futures::{future, Future};
|
||||
|
||||
#[get("/test")]
|
||||
@ -9,6 +9,41 @@ fn test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[put("/test")]
|
||||
fn put_test() -> impl Responder {
|
||||
HttpResponse::Created()
|
||||
}
|
||||
|
||||
#[patch("/test")]
|
||||
fn patch_test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[post("/test")]
|
||||
fn post_test() -> impl Responder {
|
||||
HttpResponse::NoContent()
|
||||
}
|
||||
|
||||
#[head("/test")]
|
||||
fn head_test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[connect("/test")]
|
||||
fn connect_test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[options("/test")]
|
||||
fn options_test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[trace("/test")]
|
||||
fn trace_test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[get("/test")]
|
||||
fn auto_async() -> impl Future<Item = HttpResponse, Error = actix_web::Error> {
|
||||
future::ok(HttpResponse::Ok().finish())
|
||||
@ -19,13 +54,94 @@ fn auto_sync() -> impl Future<Item = HttpResponse, Error = actix_web::Error> {
|
||||
future::ok(HttpResponse::Ok().finish())
|
||||
}
|
||||
|
||||
#[put("/test/{param}")]
|
||||
fn put_param_test(_: Path<String>) -> impl Responder {
|
||||
HttpResponse::Created()
|
||||
}
|
||||
|
||||
#[delete("/test/{param}")]
|
||||
fn delete_param_test(_: Path<String>) -> impl Responder {
|
||||
HttpResponse::NoContent()
|
||||
}
|
||||
|
||||
#[get("/test/{param}")]
|
||||
fn get_param_test(_: Path<String>) -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_params() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
HttpService::new(
|
||||
App::new()
|
||||
.service(get_param_test)
|
||||
.service(put_param_test)
|
||||
.service(delete_param_test),
|
||||
)
|
||||
});
|
||||
|
||||
let request = srv.request(http::Method::GET, srv.url("/test/it"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert_eq!(response.status(), http::StatusCode::OK);
|
||||
|
||||
let request = srv.request(http::Method::PUT, srv.url("/test/it"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert_eq!(response.status(), http::StatusCode::CREATED);
|
||||
|
||||
let request = srv.request(http::Method::DELETE, srv.url("/test/it"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_body() {
|
||||
let mut srv = TestServer::new(|| HttpService::new(App::new().service(test)));
|
||||
let mut srv = TestServer::new(|| {
|
||||
HttpService::new(
|
||||
App::new()
|
||||
.service(post_test)
|
||||
.service(put_test)
|
||||
.service(head_test)
|
||||
.service(connect_test)
|
||||
.service(options_test)
|
||||
.service(trace_test)
|
||||
.service(patch_test)
|
||||
.service(test),
|
||||
)
|
||||
});
|
||||
let request = srv.request(http::Method::GET, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::HEAD, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::CONNECT, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::OPTIONS, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::TRACE, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::PATCH, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::PUT, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert_eq!(response.status(), http::StatusCode::CREATED);
|
||||
|
||||
let request = srv.request(http::Method::POST, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
|
||||
|
||||
let mut srv = TestServer::new(|| HttpService::new(App::new().service(auto_sync)));
|
||||
let request = srv.request(http::Method::GET, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
|
@ -1,5 +1,22 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.1] - 2019-06-05
|
||||
|
||||
### Added
|
||||
|
||||
* Add license files
|
||||
|
||||
## [0.2.0] - 2019-05-12
|
||||
|
||||
### Added
|
||||
|
||||
* Allow to send headers in `Camel-Case` form.
|
||||
|
||||
### Changed
|
||||
|
||||
* Upgrade actix-http dependency.
|
||||
|
||||
|
||||
## [0.1.1] - 2019-04-19
|
||||
|
||||
### Added
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "awc"
|
||||
version = "0.1.1"
|
||||
version = "0.2.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http client."
|
||||
readme = "README.md"
|
||||
@ -8,10 +8,13 @@ keywords = ["actix", "http", "framework", "async", "web"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-web.git"
|
||||
documentation = "https://docs.rs/awc/"
|
||||
categories = ["network-programming", "asynchronous",
|
||||
"web-programming::http-client",
|
||||
"web-programming::websocket"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
workspace = ".."
|
||||
edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
[lib]
|
||||
name = "awc"
|
||||
@ -37,11 +40,11 @@ flate2-rust = ["actix-http/flate2-rust"]
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-service = "0.3.6"
|
||||
actix-http = "0.1.1"
|
||||
actix-service = "0.4.1"
|
||||
actix-http = "0.2.4"
|
||||
base64 = "0.10.1"
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
derive_more = "0.15.0"
|
||||
futures = "0.1.25"
|
||||
log =" 0.4"
|
||||
mime = "0.3"
|
||||
@ -55,11 +58,11 @@ openssl = { version="0.10", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
actix-web = { version = "1.0.0-alpha.6", features=["ssl"] }
|
||||
actix-http = { version = "0.1.1", features=["ssl"] }
|
||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||
actix-utils = "0.3.4"
|
||||
actix-server = { version = "0.4.3", features=["ssl"] }
|
||||
actix-web = { version = "1.0.0", features=["ssl"] }
|
||||
actix-http = { version = "0.2.4", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
actix-utils = "0.4.1"
|
||||
actix-server = { version = "0.5.1", features=["ssl"] }
|
||||
brotli2 = { version="0.3.2" }
|
||||
flate2 = { version="1.0.2" }
|
||||
env_logger = "0.6"
|
||||
|
1
awc/LICENSE-APACHE
Symbolic link
1
awc/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
awc/LICENSE-MIT
Symbolic link
1
awc/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -140,11 +140,9 @@ impl ClientBuilder {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test;
|
||||
|
||||
#[test]
|
||||
fn client_basic_auth() {
|
||||
test::run_on(|| {
|
||||
let client = ClientBuilder::new().basic_auth("username", Some("password"));
|
||||
assert_eq!(
|
||||
client
|
||||
@ -168,12 +166,10 @@ mod tests {
|
||||
.unwrap(),
|
||||
"Basic dXNlcm5hbWU="
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_bearer_auth() {
|
||||
test::run_on(|| {
|
||||
let client = ClientBuilder::new().bearer_auth("someS3cr3tAutht0k3n");
|
||||
assert_eq!(
|
||||
client
|
||||
@ -185,6 +181,5 @@ mod tests {
|
||||
.unwrap(),
|
||||
"Bearer someS3cr3tAutht0k3n"
|
||||
);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -65,7 +65,7 @@ pub enum JsonPayloadError {
|
||||
Payload(PayloadError),
|
||||
}
|
||||
|
||||
/// Return `InternlaServerError` for `JsonPayloadError`
|
||||
/// Return `InternalServerError` for `JsonPayloadError`
|
||||
impl ResponseError for JsonPayloadError {
|
||||
fn error_response(&self) -> Response {
|
||||
Response::new(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
|
@ -38,6 +38,7 @@ pub mod test;
|
||||
pub mod ws;
|
||||
|
||||
pub use self::builder::ClientBuilder;
|
||||
pub use self::connect::BoxedSocket;
|
||||
pub use self::request::ClientRequest;
|
||||
pub use self::response::{ClientResponse, JsonBody, MessageBody};
|
||||
|
||||
|
@ -235,6 +235,13 @@ impl ClientRequest {
|
||||
self
|
||||
}
|
||||
|
||||
/// Send headers in `Camel-Case` form.
|
||||
#[inline]
|
||||
pub fn camel_case(mut self) -> Self {
|
||||
self.head.set_camel_case_headers(true);
|
||||
self
|
||||
}
|
||||
|
||||
/// Force close connection instead of returning it back to connections pool.
|
||||
/// This setting affect only http/1 connections.
|
||||
#[inline]
|
||||
|
@ -347,10 +347,11 @@ where
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use actix_http_test::block_on;
|
||||
use futures::Async;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{http::header, test::block_on, test::TestResponse};
|
||||
use crate::{http::header, test::TestResponse};
|
||||
|
||||
#[test]
|
||||
fn test_body() {
|
||||
|
@ -6,39 +6,10 @@ use actix_http::http::header::{self, Header, HeaderValue, IntoHeaderValue};
|
||||
use actix_http::http::{HeaderName, HttpTryFrom, StatusCode, Version};
|
||||
use actix_http::{h1, Payload, ResponseHead};
|
||||
use bytes::Bytes;
|
||||
#[cfg(test)]
|
||||
use futures::Future;
|
||||
use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
|
||||
|
||||
use crate::ClientResponse;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static RT: std::cell::RefCell<actix_rt::Runtime> = {
|
||||
std::cell::RefCell::new(actix_rt::Runtime::new().unwrap())
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn run_on<F, R>(f: F) -> R
|
||||
where
|
||||
F: Fn() -> R,
|
||||
{
|
||||
RT.with(move |rt| {
|
||||
rt.borrow_mut()
|
||||
.block_on(futures::future::lazy(|| Ok::<_, ()>(f())))
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn block_on<F>(f: F) -> Result<F::Item, F::Error>
|
||||
where
|
||||
F: Future,
|
||||
{
|
||||
RT.with(move |rt| rt.borrow_mut().block_on(f))
|
||||
}
|
||||
|
||||
/// Test `ClientResponse` builder
|
||||
pub struct TestResponse {
|
||||
head: ResponseHead,
|
||||
|
@ -318,7 +318,9 @@ impl WebsocketsRequest {
|
||||
}
|
||||
} else {
|
||||
log::trace!("Invalid connection header: {:?}", conn);
|
||||
return Err(WsClientError::InvalidConnectionHeader(conn.clone()));
|
||||
return Err(WsClientError::InvalidConnectionHeader(
|
||||
conn.clone(),
|
||||
));
|
||||
}
|
||||
} else {
|
||||
log::trace!("Missing connection header");
|
||||
@ -462,7 +464,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn basics() {
|
||||
actix_http_test::run_on(|| {
|
||||
let req = Client::new()
|
||||
.ws("http://localhost/")
|
||||
.origin("test-origin")
|
||||
@ -483,8 +484,8 @@ mod tests {
|
||||
req.head.headers.get(header::CONTENT_TYPE).unwrap(),
|
||||
header::HeaderValue::from_static("json")
|
||||
);
|
||||
let _ = req.connect();
|
||||
});
|
||||
|
||||
let _ = actix_http_test::block_fn(move || req.connect());
|
||||
|
||||
assert!(Client::new().ws("/").connect().poll().is_err());
|
||||
assert!(Client::new().ws("http:///test").connect().poll().is_err());
|
||||
|
@ -1,5 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use brotli2::write::BrotliEncoder;
|
||||
@ -7,12 +9,14 @@ use bytes::Bytes;
|
||||
use flate2::read::GzDecoder;
|
||||
use flate2::write::GzEncoder;
|
||||
use flate2::Compression;
|
||||
use futures::future::Future;
|
||||
use futures::Future;
|
||||
use rand::Rng;
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_http::HttpService;
|
||||
use actix_http_test::TestServer;
|
||||
use actix_web::http::Cookie;
|
||||
use actix_service::{service_fn, NewService};
|
||||
use actix_web::http::{Cookie, Version};
|
||||
use actix_web::middleware::{BodyEncoding, Compress};
|
||||
use actix_web::{http::header, web, App, Error, HttpMessage, HttpRequest, HttpResponse};
|
||||
use awc::error::SendRequestError;
|
||||
@ -39,6 +43,30 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World";
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
fn ssl_acceptor<T: AsyncRead + AsyncWrite>(
|
||||
) -> std::io::Result<actix_server::ssl::OpensslAcceptor<T, ()>> {
|
||||
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
|
||||
// load ssl keys
|
||||
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
|
||||
builder
|
||||
.set_private_key_file("../tests/key.pem", SslFiletype::PEM)
|
||||
.unwrap();
|
||||
builder
|
||||
.set_certificate_chain_file("../tests/cert.pem")
|
||||
.unwrap();
|
||||
builder.set_alpn_select_callback(|_, protos| {
|
||||
const H2: &[u8] = b"\x02h2";
|
||||
if protos.windows(3).any(|window| window == H2) {
|
||||
Ok(b"h2")
|
||||
} else {
|
||||
Err(openssl::ssl::AlpnError::NOACK)
|
||||
}
|
||||
});
|
||||
builder.set_alpn_protos(b"\x02h2")?;
|
||||
Ok(actix_server::ssl::OpensslAcceptor::new(builder.build()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_simple() {
|
||||
let mut srv =
|
||||
@ -62,6 +90,10 @@ fn test_simple() {
|
||||
// read response
|
||||
let bytes = srv.block_on(response.body()).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
|
||||
// camel case
|
||||
let response = srv.block_on(srv.post("/").camel_case().send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -144,17 +176,249 @@ fn test_timeout_override() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connection_close() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
HttpService::new(
|
||||
App::new().service(web::resource("/").to(|| HttpResponse::Ok())),
|
||||
fn test_connection_reuse() {
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
service_fn(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
.and_then(HttpService::new(
|
||||
App::new().service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
|
||||
))
|
||||
});
|
||||
|
||||
let client = awc::Client::default();
|
||||
|
||||
// req 1
|
||||
let request = client.get(srv.url("/")).send();
|
||||
let response = srv.block_on(request).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// req 2
|
||||
let req = client.post(srv.url("/"));
|
||||
let response = srv.block_on_fn(move || req.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// one connection
|
||||
assert_eq!(num.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_connection_reuse_h2() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
service_fn(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
.and_then(
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e)),
|
||||
)
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(App::new()
|
||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let res = srv
|
||||
.block_on(awc::Client::new().get(srv.url("/")).force_close().send())
|
||||
.unwrap();
|
||||
assert!(res.status().is_success());
|
||||
// disable ssl verification
|
||||
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
|
||||
|
||||
let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
|
||||
builder.set_verify(SslVerifyMode::NONE);
|
||||
let _ = builder
|
||||
.set_alpn_protos(b"\x02h2\x08http/1.1")
|
||||
.map_err(|e| log::error!("Can not set alpn protocol: {:?}", e));
|
||||
|
||||
let client = awc::Client::build()
|
||||
.connector(awc::Connector::new().ssl(builder.build()).finish())
|
||||
.finish();
|
||||
|
||||
// req 1
|
||||
let request = client.get(srv.surl("/")).send();
|
||||
let response = srv.block_on(request).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// req 2
|
||||
let req = client.post(srv.surl("/"));
|
||||
let response = srv.block_on_fn(move || req.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert_eq!(response.version(), Version::HTTP_2);
|
||||
|
||||
// one connection
|
||||
assert_eq!(num.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connection_force_close() {
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
service_fn(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
.and_then(HttpService::new(
|
||||
App::new().service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
|
||||
))
|
||||
});
|
||||
|
||||
let client = awc::Client::default();
|
||||
|
||||
// req 1
|
||||
let request = client.get(srv.url("/")).force_close().send();
|
||||
let response = srv.block_on(request).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// req 2
|
||||
let req = client.post(srv.url("/")).force_close();
|
||||
let response = srv.block_on_fn(move || req.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// two connection
|
||||
assert_eq!(num.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connection_server_close() {
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
service_fn(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
.and_then(HttpService::new(
|
||||
App::new().service(
|
||||
web::resource("/")
|
||||
.route(web::to(|| HttpResponse::Ok().force_close().finish())),
|
||||
),
|
||||
))
|
||||
});
|
||||
|
||||
let client = awc::Client::default();
|
||||
|
||||
// req 1
|
||||
let request = client.get(srv.url("/")).send();
|
||||
let response = srv.block_on(request).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// req 2
|
||||
let req = client.post(srv.url("/"));
|
||||
let response = srv.block_on_fn(move || req.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// two connection
|
||||
assert_eq!(num.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connection_wait_queue() {
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
service_fn(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
.and_then(HttpService::new(App::new().service(
|
||||
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
|
||||
)))
|
||||
});
|
||||
|
||||
let client = awc::Client::build()
|
||||
.connector(awc::Connector::new().limit(1).finish())
|
||||
.finish();
|
||||
|
||||
// req 1
|
||||
let request = client.get(srv.url("/")).send();
|
||||
let mut response = srv.block_on(request).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// req 2
|
||||
let req2 = client.post(srv.url("/"));
|
||||
let req2_fut = srv.execute(move || {
|
||||
let mut fut = req2.send();
|
||||
assert!(fut.poll().unwrap().is_not_ready());
|
||||
fut
|
||||
});
|
||||
|
||||
// read response 1
|
||||
let bytes = srv.block_on(response.body()).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
|
||||
// req 2
|
||||
let response = srv.block_on(req2_fut).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// two connection
|
||||
assert_eq!(num.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connection_wait_queue_force_close() {
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
service_fn(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
.and_then(HttpService::new(
|
||||
App::new().service(
|
||||
web::resource("/")
|
||||
.route(web::to(|| HttpResponse::Ok().force_close().body(STR))),
|
||||
),
|
||||
))
|
||||
});
|
||||
|
||||
let client = awc::Client::build()
|
||||
.connector(awc::Connector::new().limit(1).finish())
|
||||
.finish();
|
||||
|
||||
// req 1
|
||||
let request = client.get(srv.url("/")).send();
|
||||
let mut response = srv.block_on(request).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// req 2
|
||||
let req2 = client.post(srv.url("/"));
|
||||
let req2_fut = srv.execute(move || {
|
||||
let mut fut = req2.send();
|
||||
assert!(fut.poll().unwrap().is_not_ready());
|
||||
fut
|
||||
});
|
||||
|
||||
// read response 1
|
||||
let bytes = srv.block_on(response.body()).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
|
||||
// req 2
|
||||
let response = srv.block_on(req2_fut).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// two connection
|
||||
assert_eq!(num.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -1,17 +1,11 @@
|
||||
use std::io;
|
||||
|
||||
use actix_codec::Framed;
|
||||
use actix_http::{body::BodySize, h1, ws, Error, HttpService, Request, Response};
|
||||
use actix_http_test::TestServer;
|
||||
use actix_server::Io;
|
||||
use actix_service::{fn_service, NewService};
|
||||
use actix_utils::framed::IntoFramed;
|
||||
use actix_utils::stream::TakeItem;
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures::future::{ok, Either};
|
||||
use futures::future::ok;
|
||||
use futures::{Future, Sink, Stream};
|
||||
use tokio_tcp::TcpStream;
|
||||
|
||||
use actix_http::{body::BodySize, h1, ws, Request, ResponseError, ServiceConfig};
|
||||
|
||||
fn ws_service(req: ws::Frame) -> impl Future<Item = ws::Message, Error = io::Error> {
|
||||
match req {
|
||||
@ -37,52 +31,20 @@ fn ws_service(req: ws::Frame) -> impl Future<Item = ws::Message, Error = io::Err
|
||||
#[test]
|
||||
fn test_simple() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
fn_service(|io: Io<TcpStream>| Ok(io.into_parts().0))
|
||||
.and_then(IntoFramed::new(|| h1::Codec::new(ServiceConfig::default())))
|
||||
.and_then(TakeItem::new().map_err(|_| ()))
|
||||
.and_then(
|
||||
|(req, framed): (Option<h1::Message<Request>>, Framed<_, _>)| {
|
||||
// validate request
|
||||
if let Some(h1::Message::Item(req)) = req {
|
||||
match ws::verify_handshake(req.head()) {
|
||||
Err(e) => {
|
||||
// validation failed
|
||||
let res = e.error_response();
|
||||
Either::A(
|
||||
framed
|
||||
.send(h1::Message::Item((
|
||||
res.drop_body(),
|
||||
BodySize::Empty,
|
||||
)))
|
||||
.map_err(|_| ())
|
||||
.map(|_| ()),
|
||||
)
|
||||
}
|
||||
Ok(_) => {
|
||||
HttpService::build()
|
||||
.upgrade(|(req, framed): (Request, Framed<_, _>)| {
|
||||
let res = ws::handshake_response(req.head()).finish();
|
||||
Either::B(
|
||||
// send handshake response
|
||||
framed
|
||||
.send(h1::Message::Item((
|
||||
res.drop_body(),
|
||||
BodySize::None,
|
||||
)))
|
||||
.map_err(|_| ())
|
||||
.send(h1::Message::Item((res.drop_body(), BodySize::None)))
|
||||
.map_err(|e: io::Error| e.into())
|
||||
.and_then(|framed| {
|
||||
// start websocket service
|
||||
let framed =
|
||||
framed.into_framed(ws::Codec::new());
|
||||
let framed = framed.into_framed(ws::Codec::new());
|
||||
ws::Transport::with(framed, ws_service)
|
||||
.map_err(|_| ())
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
panic!()
|
||||
}
|
||||
},
|
||||
)
|
||||
})
|
||||
})
|
||||
.finish(|_| ok::<_, Error>(Response::NotFound()))
|
||||
});
|
||||
|
||||
// client service
|
||||
|
106
src/app.rs
106
src/app.rs
@ -4,7 +4,6 @@ use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_http::body::{Body, MessageBody};
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::boxed::{self, BoxedNewService};
|
||||
use actix_service::{
|
||||
apply_transform, IntoNewService, IntoTransform, NewService, Transform,
|
||||
@ -59,6 +58,7 @@ impl<T, B> App<T, B>
|
||||
where
|
||||
B: MessageBody,
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse<B>,
|
||||
Error = Error,
|
||||
@ -95,20 +95,14 @@ where
|
||||
/// web::get().to(index)));
|
||||
/// }
|
||||
/// ```
|
||||
pub fn data<S: 'static>(mut self, data: S) -> Self {
|
||||
pub fn data<U: 'static>(mut self, data: U) -> Self {
|
||||
self.data.push(Box::new(Data::new(data)));
|
||||
self
|
||||
}
|
||||
|
||||
/// Set application data factory. This function is
|
||||
/// similar to `.data()` but it accepts data factory. Data object get
|
||||
/// constructed asynchronously during application initialization.
|
||||
pub fn data_factory<F, R>(mut self, data: F) -> Self
|
||||
where
|
||||
F: Fn() -> R + 'static,
|
||||
R: IntoFuture + 'static,
|
||||
R::Error: std::fmt::Debug,
|
||||
{
|
||||
/// Set application data. Application data could be accessed
|
||||
/// by using `Data<T>` extractor where `T` is data type.
|
||||
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
|
||||
self.data.push(Box::new(data));
|
||||
self
|
||||
}
|
||||
@ -141,7 +135,7 @@ where
|
||||
/// ```
|
||||
pub fn configure<F>(mut self, f: F) -> Self
|
||||
where
|
||||
F: Fn(&mut ServiceConfig),
|
||||
F: FnOnce(&mut ServiceConfig),
|
||||
{
|
||||
let mut cfg = ServiceConfig::new();
|
||||
f(&mut cfg);
|
||||
@ -231,7 +225,6 @@ where
|
||||
/// It is also possible to use static files as default service.
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_files::Files;
|
||||
/// use actix_web::{web, App, HttpResponse};
|
||||
///
|
||||
/// fn main() {
|
||||
@ -239,7 +232,7 @@ where
|
||||
/// .service(
|
||||
/// web::resource("/index.html").to(|| HttpResponse::Ok()))
|
||||
/// .default_service(
|
||||
/// Files::new("", "./static")
|
||||
/// web::to(|| HttpResponse::NotFound())
|
||||
/// );
|
||||
/// }
|
||||
/// ```
|
||||
@ -247,6 +240,7 @@ where
|
||||
where
|
||||
F: IntoNewService<U>,
|
||||
U: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -301,7 +295,15 @@ where
|
||||
/// lifecycle (request -> response), modifying request/response as
|
||||
/// necessary, across all requests managed by the *Application*.
|
||||
///
|
||||
/// Use middleware when you need to read or modify *every* request or response in some way.
|
||||
/// Use middleware when you need to read or modify *every* request or
|
||||
/// response in some way.
|
||||
///
|
||||
/// Notice that the keyword for registering middleware is `wrap`. As you
|
||||
/// register middleware using `wrap` in the App builder, imagine wrapping
|
||||
/// layers around an inner App. The first middleware layer exposed to a
|
||||
/// Request is the outermost layer-- the *last* registered in
|
||||
/// the builder chain. Consequently, the *first* middleware registered
|
||||
/// in the builder chain is the *last* to execute during request processing.
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_service::Service;
|
||||
@ -324,6 +326,7 @@ where
|
||||
mw: F,
|
||||
) -> App<
|
||||
impl NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse<B1>,
|
||||
Error = Error,
|
||||
@ -389,6 +392,7 @@ where
|
||||
mw: F,
|
||||
) -> App<
|
||||
impl NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse<B1>,
|
||||
Error = Error,
|
||||
@ -405,10 +409,11 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, B> IntoNewService<AppInit<T, B>, ServerConfig> for App<T, B>
|
||||
impl<T, B> IntoNewService<AppInit<T, B>> for App<T, B>
|
||||
where
|
||||
B: MessageBody,
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse<B>,
|
||||
Error = Error,
|
||||
@ -417,9 +422,9 @@ where
|
||||
{
|
||||
fn into_new_service(self) -> AppInit<T, B> {
|
||||
AppInit {
|
||||
data: self.data,
|
||||
data: Rc::new(self.data),
|
||||
endpoint: self.endpoint,
|
||||
services: RefCell::new(self.services),
|
||||
services: Rc::new(RefCell::new(self.services)),
|
||||
external: RefCell::new(self.external),
|
||||
default: self.default,
|
||||
factory_ref: self.factory_ref,
|
||||
@ -431,13 +436,16 @@ where
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_service::Service;
|
||||
use bytes::Bytes;
|
||||
use futures::{Future, IntoFuture};
|
||||
|
||||
use super::*;
|
||||
use crate::http::{header, HeaderValue, Method, StatusCode};
|
||||
use crate::service::{ServiceRequest, ServiceResponse};
|
||||
use crate::test::{block_on, call_service, init_service, TestRequest};
|
||||
use crate::{web, Error, HttpResponse};
|
||||
use crate::test::{
|
||||
block_fn, block_on, call_service, init_service, read_body, TestRequest,
|
||||
};
|
||||
use crate::{web, Error, HttpRequest, HttpResponse};
|
||||
|
||||
#[test]
|
||||
fn test_default_resource() {
|
||||
@ -445,7 +453,7 @@ mod tests {
|
||||
App::new().service(web::resource("/test").to(|| HttpResponse::Ok())),
|
||||
);
|
||||
let req = TestRequest::with_uri("/test").to_request();
|
||||
let resp = block_on(srv.call(req)).unwrap();
|
||||
let resp = block_fn(|| srv.call(req)).unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let req = TestRequest::with_uri("/blah").to_request();
|
||||
@ -482,24 +490,24 @@ mod tests {
|
||||
assert_eq!(resp.status(), StatusCode::CREATED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_data_factory() {
|
||||
let mut srv =
|
||||
init_service(App::new().data_factory(|| Ok::<_, ()>(10usize)).service(
|
||||
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||
));
|
||||
let req = TestRequest::default().to_request();
|
||||
let resp = block_on(srv.call(req)).unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
// #[test]
|
||||
// fn test_data_factory() {
|
||||
// let mut srv =
|
||||
// init_service(App::new().data_factory(|| Ok::<_, ()>(10usize)).service(
|
||||
// web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||
// ));
|
||||
// let req = TestRequest::default().to_request();
|
||||
// let resp = block_on(srv.call(req)).unwrap();
|
||||
// assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let mut srv =
|
||||
init_service(App::new().data_factory(|| Ok::<_, ()>(10u32)).service(
|
||||
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||
));
|
||||
let req = TestRequest::default().to_request();
|
||||
let resp = block_on(srv.call(req)).unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
// let mut srv =
|
||||
// init_service(App::new().data_factory(|| Ok::<_, ()>(10u32)).service(
|
||||
// web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||
// ));
|
||||
// let req = TestRequest::default().to_request();
|
||||
// let resp = block_on(srv.call(req)).unwrap();
|
||||
// assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
// }
|
||||
|
||||
fn md<S, B>(
|
||||
req: ServiceRequest,
|
||||
@ -598,4 +606,26 @@ mod tests {
|
||||
HeaderValue::from_static("0001")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_external_resource() {
|
||||
let mut srv = init_service(
|
||||
App::new()
|
||||
.external_resource("youtube", "https://youtube.com/watch/{video_id}")
|
||||
.route(
|
||||
"/test",
|
||||
web::get().to(|req: HttpRequest| {
|
||||
HttpResponse::Ok().body(format!(
|
||||
"{}",
|
||||
req.url_for("youtube", &["12345"]).unwrap()
|
||||
))
|
||||
}),
|
||||
),
|
||||
);
|
||||
let req = TestRequest::with_uri("/test").to_request();
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let body = read_body(resp);
|
||||
assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345"));
|
||||
}
|
||||
}
|
||||
|
@ -2,16 +2,16 @@ use std::cell::RefCell;
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_http::{Request, Response};
|
||||
use actix_http::{Extensions, Request, Response};
|
||||
use actix_router::{Path, ResourceDef, ResourceInfo, Router, Url};
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::boxed::{self, BoxedNewService, BoxedService};
|
||||
use actix_service::{fn_service, NewService, Service};
|
||||
use actix_service::{service_fn, NewService, Service};
|
||||
use futures::future::{ok, Either, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use crate::config::{AppConfig, AppService};
|
||||
use crate::data::{DataFactory, DataFactoryResult};
|
||||
use crate::data::DataFactory;
|
||||
use crate::error::Error;
|
||||
use crate::guard::Guard;
|
||||
use crate::request::{HttpRequest, HttpRequestPool};
|
||||
@ -31,6 +31,7 @@ type BoxedResponse = Either<
|
||||
pub struct AppInit<T, B>
|
||||
where
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse<B>,
|
||||
Error = Error,
|
||||
@ -38,23 +39,25 @@ where
|
||||
>,
|
||||
{
|
||||
pub(crate) endpoint: T,
|
||||
pub(crate) data: Vec<Box<DataFactory>>,
|
||||
pub(crate) data: Rc<Vec<Box<DataFactory>>>,
|
||||
pub(crate) config: RefCell<AppConfig>,
|
||||
pub(crate) services: RefCell<Vec<Box<ServiceFactory>>>,
|
||||
pub(crate) services: Rc<RefCell<Vec<Box<ServiceFactory>>>>,
|
||||
pub(crate) default: Option<Rc<HttpNewService>>,
|
||||
pub(crate) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
|
||||
pub(crate) external: RefCell<Vec<ResourceDef>>,
|
||||
}
|
||||
|
||||
impl<T, B> NewService<ServerConfig> for AppInit<T, B>
|
||||
impl<T, B> NewService for AppInit<T, B>
|
||||
where
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse<B>,
|
||||
Error = Error,
|
||||
InitError = (),
|
||||
>,
|
||||
{
|
||||
type Config = ServerConfig;
|
||||
type Request = Request;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = T::Error;
|
||||
@ -65,11 +68,12 @@ where
|
||||
fn new_service(&self, cfg: &ServerConfig) -> Self::Future {
|
||||
// update resource default service
|
||||
let default = self.default.clone().unwrap_or_else(|| {
|
||||
Rc::new(boxed::new_service(fn_service(|req: ServiceRequest| {
|
||||
Rc::new(boxed::new_service(service_fn(|req: ServiceRequest| {
|
||||
Ok(req.into_response(Response::NotFound().finish()))
|
||||
})))
|
||||
});
|
||||
|
||||
// App config
|
||||
{
|
||||
let mut c = self.config.borrow_mut();
|
||||
let loc_cfg = Rc::get_mut(&mut c.0).unwrap();
|
||||
@ -77,7 +81,11 @@ where
|
||||
loc_cfg.addr = cfg.local_addr();
|
||||
}
|
||||
|
||||
let mut config = AppService::new(self.config.borrow().clone(), default.clone());
|
||||
let mut config = AppService::new(
|
||||
self.config.borrow().clone(),
|
||||
default.clone(),
|
||||
self.data.clone(),
|
||||
);
|
||||
|
||||
// register services
|
||||
std::mem::replace(&mut *self.services.borrow_mut(), Vec::new())
|
||||
@ -86,12 +94,13 @@ where
|
||||
|
||||
let mut rmap = ResourceMap::new(ResourceDef::new(""));
|
||||
|
||||
let (config, services) = config.into_services();
|
||||
|
||||
// complete pipeline creation
|
||||
*self.factory_ref.borrow_mut() = Some(AppRoutingFactory {
|
||||
default,
|
||||
services: Rc::new(
|
||||
config
|
||||
.into_services()
|
||||
services
|
||||
.into_iter()
|
||||
.map(|(mut rdef, srv, guards, nested)| {
|
||||
rmap.add(&mut rdef, nested);
|
||||
@ -110,11 +119,17 @@ where
|
||||
let rmap = Rc::new(rmap);
|
||||
rmap.finish(rmap.clone());
|
||||
|
||||
// create app data container
|
||||
let mut data = Extensions::new();
|
||||
for f in self.data.iter() {
|
||||
f.create(&mut data);
|
||||
}
|
||||
|
||||
AppInitResult {
|
||||
endpoint: None,
|
||||
endpoint_fut: self.endpoint.new_service(&()),
|
||||
data: self.data.iter().map(|s| s.construct()).collect(),
|
||||
config: self.config.borrow().clone(),
|
||||
data: Rc::new(data),
|
||||
config,
|
||||
rmap,
|
||||
_t: PhantomData,
|
||||
}
|
||||
@ -128,14 +143,15 @@ where
|
||||
endpoint: Option<T::Service>,
|
||||
endpoint_fut: T::Future,
|
||||
rmap: Rc<ResourceMap>,
|
||||
data: Vec<Box<DataFactoryResult>>,
|
||||
config: AppConfig,
|
||||
data: Rc<Extensions>,
|
||||
_t: PhantomData<B>,
|
||||
}
|
||||
|
||||
impl<T, B> Future for AppInitResult<T, B>
|
||||
where
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse<B>,
|
||||
Error = Error,
|
||||
@ -146,16 +162,6 @@ where
|
||||
type Error = T::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
let mut idx = 0;
|
||||
let mut extensions = self.config.0.extensions.borrow_mut();
|
||||
while idx < self.data.len() {
|
||||
if let Async::Ready(_) = self.data[idx].poll_result(&mut extensions)? {
|
||||
self.data.remove(idx);
|
||||
} else {
|
||||
idx += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if self.endpoint.is_none() {
|
||||
if let Async::Ready(srv) = self.endpoint_fut.poll()? {
|
||||
self.endpoint = Some(srv);
|
||||
@ -167,6 +173,7 @@ where
|
||||
service: self.endpoint.take().unwrap(),
|
||||
rmap: self.rmap.clone(),
|
||||
config: self.config.clone(),
|
||||
data: self.data.clone(),
|
||||
pool: HttpRequestPool::create(),
|
||||
}))
|
||||
} else {
|
||||
@ -176,13 +183,14 @@ where
|
||||
}
|
||||
|
||||
/// Service to convert `Request` to a `ServiceRequest<S>`
|
||||
pub struct AppInitService<T: Service, B>
|
||||
pub struct AppInitService<T, B>
|
||||
where
|
||||
T: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
{
|
||||
service: T,
|
||||
rmap: Rc<ResourceMap>,
|
||||
config: AppConfig,
|
||||
data: Rc<Extensions>,
|
||||
pool: &'static HttpRequestPool,
|
||||
}
|
||||
|
||||
@ -207,17 +215,30 @@ where
|
||||
inner.path.get_mut().update(&head.uri);
|
||||
inner.path.reset();
|
||||
inner.head = head;
|
||||
inner.payload = payload;
|
||||
inner.app_data = self.data.clone();
|
||||
req
|
||||
} else {
|
||||
HttpRequest::new(
|
||||
Path::new(Url::new(head.uri.clone())),
|
||||
head,
|
||||
payload,
|
||||
self.rmap.clone(),
|
||||
self.config.clone(),
|
||||
self.data.clone(),
|
||||
self.pool,
|
||||
)
|
||||
};
|
||||
self.service.call(ServiceRequest::from_parts(req, payload))
|
||||
self.service.call(ServiceRequest::new(req))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, B> Drop for AppInitService<T, B>
|
||||
where
|
||||
T: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
self.pool.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@ -227,6 +248,7 @@ pub struct AppRoutingFactory {
|
||||
}
|
||||
|
||||
impl NewService for AppRoutingFactory {
|
||||
type Config = ();
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse;
|
||||
type Error = Error;
|
||||
@ -385,6 +407,7 @@ impl AppEntry {
|
||||
}
|
||||
|
||||
impl NewService for AppEntry {
|
||||
type Config = ();
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse;
|
||||
type Error = Error;
|
||||
@ -396,3 +419,37 @@ impl NewService for AppEntry {
|
||||
self.factory.borrow_mut().as_mut().unwrap().new_service(&())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_service::Service;
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
use crate::{test, web, App, HttpResponse};
|
||||
|
||||
struct DropData(Arc<AtomicBool>);
|
||||
|
||||
impl Drop for DropData {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_data() {
|
||||
let data = Arc::new(AtomicBool::new(false));
|
||||
{
|
||||
let mut app = test::init_service(
|
||||
App::new()
|
||||
.data(DropData(data.clone()))
|
||||
.service(web::resource("/test").to(|| HttpResponse::Ok())),
|
||||
);
|
||||
let req = test::TestRequest::with_uri("/test").to_request();
|
||||
let _ = test::block_on(app.call(req)).unwrap();
|
||||
}
|
||||
assert!(data.load(Ordering::Relaxed));
|
||||
}
|
||||
}
|
||||
|
140
src/config.rs
140
src/config.rs
@ -1,11 +1,9 @@
|
||||
use std::cell::{Ref, RefCell};
|
||||
use std::net::SocketAddr;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_http::Extensions;
|
||||
use actix_router::ResourceDef;
|
||||
use actix_service::{boxed, IntoNewService, NewService};
|
||||
use futures::IntoFuture;
|
||||
|
||||
use crate::data::{Data, DataFactory};
|
||||
use crate::error::Error;
|
||||
@ -33,14 +31,20 @@ pub struct AppService {
|
||||
Option<Guards>,
|
||||
Option<Rc<ResourceMap>>,
|
||||
)>,
|
||||
service_data: Rc<Vec<Box<DataFactory>>>,
|
||||
}
|
||||
|
||||
impl AppService {
|
||||
/// Crate server settings instance
|
||||
pub(crate) fn new(config: AppConfig, default: Rc<HttpNewService>) -> Self {
|
||||
pub(crate) fn new(
|
||||
config: AppConfig,
|
||||
default: Rc<HttpNewService>,
|
||||
service_data: Rc<Vec<Box<DataFactory>>>,
|
||||
) -> Self {
|
||||
AppService {
|
||||
config,
|
||||
default,
|
||||
service_data,
|
||||
root: true,
|
||||
services: Vec::new(),
|
||||
}
|
||||
@ -53,13 +57,16 @@ impl AppService {
|
||||
|
||||
pub(crate) fn into_services(
|
||||
self,
|
||||
) -> Vec<(
|
||||
) -> (
|
||||
AppConfig,
|
||||
Vec<(
|
||||
ResourceDef,
|
||||
HttpNewService,
|
||||
Option<Guards>,
|
||||
Option<Rc<ResourceMap>>,
|
||||
)> {
|
||||
self.services
|
||||
)>,
|
||||
) {
|
||||
(self.config, self.services)
|
||||
}
|
||||
|
||||
pub(crate) fn clone_config(&self) -> Self {
|
||||
@ -68,6 +75,7 @@ impl AppService {
|
||||
default: self.default.clone(),
|
||||
services: Vec::new(),
|
||||
root: false,
|
||||
service_data: self.service_data.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@ -81,6 +89,15 @@ impl AppService {
|
||||
self.default.clone()
|
||||
}
|
||||
|
||||
/// Set global route data
|
||||
pub fn set_service_data(&self, extensions: &mut Extensions) -> bool {
|
||||
for f in self.service_data.iter() {
|
||||
f.create(extensions);
|
||||
}
|
||||
!self.service_data.is_empty()
|
||||
}
|
||||
|
||||
/// Register http service
|
||||
pub fn register_service<F, S>(
|
||||
&mut self,
|
||||
rdef: ResourceDef,
|
||||
@ -90,6 +107,7 @@ impl AppService {
|
||||
) where
|
||||
F: IntoNewService<S>,
|
||||
S: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -133,24 +151,12 @@ impl AppConfig {
|
||||
pub fn local_addr(&self) -> SocketAddr {
|
||||
self.0.addr
|
||||
}
|
||||
|
||||
/// Resource map
|
||||
pub fn rmap(&self) -> &ResourceMap {
|
||||
&self.0.rmap
|
||||
}
|
||||
|
||||
/// Application extensions
|
||||
pub fn extensions(&self) -> Ref<Extensions> {
|
||||
self.0.extensions.borrow()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct AppConfigInner {
|
||||
pub(crate) secure: bool,
|
||||
pub(crate) host: String,
|
||||
pub(crate) addr: SocketAddr,
|
||||
pub(crate) rmap: ResourceMap,
|
||||
pub(crate) extensions: RefCell<Extensions>,
|
||||
}
|
||||
|
||||
impl Default for AppConfigInner {
|
||||
@ -159,8 +165,6 @@ impl Default for AppConfigInner {
|
||||
secure: false,
|
||||
addr: "127.0.0.1:8080".parse().unwrap(),
|
||||
host: "localhost:8080".to_owned(),
|
||||
rmap: ResourceMap::new(ResourceDef::new("")),
|
||||
extensions: RefCell::new(Extensions::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -184,7 +188,7 @@ impl ServiceConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Set application data. Applicatin data could be accessed
|
||||
/// Set application data. Application data could be accessed
|
||||
/// by using `Data<T>` extractor where `T` is data type.
|
||||
///
|
||||
/// This is same as `App::data()` method.
|
||||
@ -193,21 +197,6 @@ impl ServiceConfig {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set application data factory. This function is
|
||||
/// similar to `.data()` but it accepts data factory. Data object get
|
||||
/// constructed asynchronously during application initialization.
|
||||
///
|
||||
/// This is same as `App::data_dactory()` method.
|
||||
pub fn data_factory<F, R>(&mut self, data: F) -> &mut Self
|
||||
where
|
||||
F: Fn() -> R + 'static,
|
||||
R: IntoFuture + 'static,
|
||||
R::Error: std::fmt::Debug,
|
||||
{
|
||||
self.data.push(Box::new(data));
|
||||
self
|
||||
}
|
||||
|
||||
/// Configure route for a specific path.
|
||||
///
|
||||
/// This is same as `App::route()` method.
|
||||
@ -253,11 +242,12 @@ impl ServiceConfig {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_service::Service;
|
||||
use bytes::Bytes;
|
||||
|
||||
use super::*;
|
||||
use crate::http::{Method, StatusCode};
|
||||
use crate::test::{block_on, call_service, init_service, TestRequest};
|
||||
use crate::{web, App, HttpResponse};
|
||||
use crate::test::{block_on, call_service, init_service, read_body, TestRequest};
|
||||
use crate::{web, App, HttpRequest, HttpResponse};
|
||||
|
||||
#[test]
|
||||
fn test_data() {
|
||||
@ -274,31 +264,63 @@ mod tests {
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
// #[test]
|
||||
// fn test_data_factory() {
|
||||
// let cfg = |cfg: &mut ServiceConfig| {
|
||||
// cfg.data_factory(|| {
|
||||
// sleep(std::time::Duration::from_millis(50)).then(|_| {
|
||||
// println!("READY");
|
||||
// Ok::<_, ()>(10usize)
|
||||
// })
|
||||
// });
|
||||
// };
|
||||
|
||||
// let mut srv =
|
||||
// init_service(App::new().configure(cfg).service(
|
||||
// web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||
// ));
|
||||
// let req = TestRequest::default().to_request();
|
||||
// let resp = block_on(srv.call(req)).unwrap();
|
||||
// assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
// let cfg2 = |cfg: &mut ServiceConfig| {
|
||||
// cfg.data_factory(|| Ok::<_, ()>(10u32));
|
||||
// };
|
||||
// let mut srv = init_service(
|
||||
// App::new()
|
||||
// .service(web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()))
|
||||
// .configure(cfg2),
|
||||
// );
|
||||
// let req = TestRequest::default().to_request();
|
||||
// let resp = block_on(srv.call(req)).unwrap();
|
||||
// assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
// }
|
||||
|
||||
#[test]
|
||||
fn test_data_factory() {
|
||||
let cfg = |cfg: &mut ServiceConfig| {
|
||||
cfg.data_factory(|| Ok::<_, ()>(10usize));
|
||||
};
|
||||
|
||||
let mut srv =
|
||||
init_service(App::new().configure(cfg).service(
|
||||
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||
));
|
||||
let req = TestRequest::default().to_request();
|
||||
let resp = block_on(srv.call(req)).unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let cfg2 = |cfg: &mut ServiceConfig| {
|
||||
cfg.data_factory(|| Ok::<_, ()>(10u32));
|
||||
};
|
||||
fn test_external_resource() {
|
||||
let mut srv = init_service(
|
||||
App::new()
|
||||
.service(web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()))
|
||||
.configure(cfg2),
|
||||
.configure(|cfg| {
|
||||
cfg.external_resource(
|
||||
"youtube",
|
||||
"https://youtube.com/watch/{video_id}",
|
||||
);
|
||||
let req = TestRequest::default().to_request();
|
||||
let resp = block_on(srv.call(req)).unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
})
|
||||
.route(
|
||||
"/test",
|
||||
web::get().to(|req: HttpRequest| {
|
||||
HttpResponse::Ok().body(format!(
|
||||
"{}",
|
||||
req.url_for("youtube", &["12345"]).unwrap()
|
||||
))
|
||||
}),
|
||||
),
|
||||
);
|
||||
let req = TestRequest::with_uri("/test").to_request();
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let body = read_body(resp);
|
||||
assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
225
src/data.rs
225
src/data.rs
@ -3,7 +3,6 @@ use std::sync::Arc;
|
||||
|
||||
use actix_http::error::{Error, ErrorInternalServerError};
|
||||
use actix_http::Extensions;
|
||||
use futures::{Async, Future, IntoFuture, Poll};
|
||||
|
||||
use crate::dev::Payload;
|
||||
use crate::extract::FromRequest;
|
||||
@ -11,11 +10,7 @@ use crate::request::HttpRequest;
|
||||
|
||||
/// Application data factory
|
||||
pub(crate) trait DataFactory {
|
||||
fn construct(&self) -> Box<DataFactoryResult>;
|
||||
}
|
||||
|
||||
pub(crate) trait DataFactoryResult {
|
||||
fn poll_result(&mut self, extensions: &mut Extensions) -> Poll<(), ()>;
|
||||
fn create(&self, extensions: &mut Extensions) -> bool;
|
||||
}
|
||||
|
||||
/// Application data.
|
||||
@ -33,29 +28,33 @@ pub(crate) trait DataFactoryResult {
|
||||
/// instance for each thread, thus application data must be constructed
|
||||
/// multiple times. If you want to share data between different
|
||||
/// threads, a shareable object should be used, e.g. `Send + Sync`. Application
|
||||
/// data does not need to be `Send` or `Sync`. Internally `Data` instance
|
||||
/// uses `Arc`.
|
||||
/// data does not need to be `Send` or `Sync`. Internally `Data` type
|
||||
/// uses `Arc`. if your data implements `Send` + `Sync` traits you can
|
||||
/// use `web::Data::new()` and avoid double `Arc`.
|
||||
///
|
||||
/// If route data is not set for a handler, using `Data<T>` extractor would
|
||||
/// cause *Internal Server Error* response.
|
||||
///
|
||||
/// ```rust
|
||||
/// use std::cell::Cell;
|
||||
/// use std::sync::Mutex;
|
||||
/// use actix_web::{web, App};
|
||||
///
|
||||
/// struct MyData {
|
||||
/// counter: Cell<usize>,
|
||||
/// counter: usize,
|
||||
/// }
|
||||
///
|
||||
/// /// Use `Data<T>` extractor to access data in handler.
|
||||
/// fn index(data: web::Data<MyData>) {
|
||||
/// data.counter.set(data.counter.get() + 1);
|
||||
/// fn index(data: web::Data<Mutex<MyData>>) {
|
||||
/// let mut data = data.lock().unwrap();
|
||||
/// data.counter += 1;
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let data = web::Data::new(Mutex::new(MyData{ counter: 0 }));
|
||||
///
|
||||
/// let app = App::new()
|
||||
/// // Store `MyData` in application storage.
|
||||
/// .data(MyData{ counter: Cell::new(0) })
|
||||
/// .register_data(data.clone())
|
||||
/// .service(
|
||||
/// web::resource("/index.html").route(
|
||||
/// web::get().to(index)));
|
||||
@ -65,7 +64,12 @@ pub(crate) trait DataFactoryResult {
|
||||
pub struct Data<T>(Arc<T>);
|
||||
|
||||
impl<T> Data<T> {
|
||||
pub(crate) fn new(state: T) -> Data<T> {
|
||||
/// Create new `Data` instance.
|
||||
///
|
||||
/// Internally `Data` type uses `Arc`. if your data implements
|
||||
/// `Send` + `Sync` traits you can use `web::Data::new()` and
|
||||
/// avoid double `Arc`.
|
||||
pub fn new(state: T) -> Data<T> {
|
||||
Data(Arc::new(state))
|
||||
}
|
||||
|
||||
@ -96,8 +100,8 @@ impl<T: 'static> FromRequest for Data<T> {
|
||||
|
||||
#[inline]
|
||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||
if let Some(st) = req.app_config().extensions().get::<Data<T>>() {
|
||||
Ok(st.clone())
|
||||
if let Some(st) = req.get_app_data::<T>() {
|
||||
Ok(st)
|
||||
} else {
|
||||
log::debug!(
|
||||
"Failed to construct App-level Data extractor. \
|
||||
@ -112,142 +116,12 @@ impl<T: 'static> FromRequest for Data<T> {
|
||||
}
|
||||
|
||||
impl<T: 'static> DataFactory for Data<T> {
|
||||
fn construct(&self) -> Box<DataFactoryResult> {
|
||||
Box::new(DataFut { st: self.clone() })
|
||||
}
|
||||
}
|
||||
|
||||
struct DataFut<T> {
|
||||
st: Data<T>,
|
||||
}
|
||||
|
||||
impl<T: 'static> DataFactoryResult for DataFut<T> {
|
||||
fn poll_result(&mut self, extensions: &mut Extensions) -> Poll<(), ()> {
|
||||
extensions.insert(self.st.clone());
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Out> DataFactory for F
|
||||
where
|
||||
F: Fn() -> Out + 'static,
|
||||
Out: IntoFuture + 'static,
|
||||
Out::Error: std::fmt::Debug,
|
||||
{
|
||||
fn construct(&self) -> Box<DataFactoryResult> {
|
||||
Box::new(DataFactoryFut {
|
||||
fut: (*self)().into_future(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct DataFactoryFut<T, F>
|
||||
where
|
||||
F: Future<Item = T>,
|
||||
F::Error: std::fmt::Debug,
|
||||
{
|
||||
fut: F,
|
||||
}
|
||||
|
||||
impl<T: 'static, F> DataFactoryResult for DataFactoryFut<T, F>
|
||||
where
|
||||
F: Future<Item = T>,
|
||||
F::Error: std::fmt::Debug,
|
||||
{
|
||||
fn poll_result(&mut self, extensions: &mut Extensions) -> Poll<(), ()> {
|
||||
match self.fut.poll() {
|
||||
Ok(Async::Ready(s)) => {
|
||||
extensions.insert(Data::new(s));
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Err(e) => {
|
||||
log::error!("Can not construct application state: {:?}", e);
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Route data.
|
||||
///
|
||||
/// Route data is an arbitrary data attached to specific route.
|
||||
/// Route data could be added to route during route configuration process
|
||||
/// with `Route::data()` method. Route data is also used as an extractor
|
||||
/// configuration storage. Route data could be accessed in handler
|
||||
/// via `RouteData<T>` extractor.
|
||||
///
|
||||
/// If route data is not set for a handler, using `RouteData` extractor
|
||||
/// would cause *Internal Server Error* response.
|
||||
///
|
||||
/// ```rust
|
||||
/// # use std::cell::Cell;
|
||||
/// use actix_web::{web, App};
|
||||
///
|
||||
/// struct MyData {
|
||||
/// counter: Cell<usize>,
|
||||
/// }
|
||||
///
|
||||
/// /// Use `RouteData<T>` extractor to access data in handler.
|
||||
/// fn index(data: web::RouteData<MyData>) {
|
||||
/// data.counter.set(data.counter.get() + 1);
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().service(
|
||||
/// web::resource("/index.html").route(
|
||||
/// web::get()
|
||||
/// // Store `MyData` in route storage
|
||||
/// .data(MyData{ counter: Cell::new(0) })
|
||||
/// // Route data could be used as extractor configuration storage,
|
||||
/// // limit size of the payload
|
||||
/// .data(web::PayloadConfig::new(4096))
|
||||
/// // register handler
|
||||
/// .to(index)
|
||||
/// ));
|
||||
/// }
|
||||
/// ```
|
||||
pub struct RouteData<T>(Arc<T>);
|
||||
|
||||
impl<T> RouteData<T> {
|
||||
pub(crate) fn new(state: T) -> RouteData<T> {
|
||||
RouteData(Arc::new(state))
|
||||
}
|
||||
|
||||
/// Get referecnce to inner data object.
|
||||
pub fn get_ref(&self) -> &T {
|
||||
self.0.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for RouteData<T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &T {
|
||||
self.0.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for RouteData<T> {
|
||||
fn clone(&self) -> RouteData<T> {
|
||||
RouteData(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> FromRequest for RouteData<T> {
|
||||
type Config = ();
|
||||
type Error = Error;
|
||||
type Future = Result<Self, Error>;
|
||||
|
||||
#[inline]
|
||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||
if let Some(st) = req.route_data::<T>() {
|
||||
Ok(st.clone())
|
||||
fn create(&self, extensions: &mut Extensions) -> bool {
|
||||
if !extensions.contains::<Data<T>>() {
|
||||
let _ = extensions.insert(Data(self.0.clone()));
|
||||
true
|
||||
} else {
|
||||
log::debug!("Failed to construct Route-level Data extractor");
|
||||
Err(ErrorInternalServerError(
|
||||
"Route data is not configured, to configure use Route::data()",
|
||||
))
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -256,6 +130,7 @@ impl<T: 'static> FromRequest for RouteData<T> {
|
||||
mod tests {
|
||||
use actix_service::Service;
|
||||
|
||||
use super::*;
|
||||
use crate::http::StatusCode;
|
||||
use crate::test::{block_on, init_service, TestRequest};
|
||||
use crate::{web, App, HttpResponse};
|
||||
@ -280,10 +155,31 @@ mod tests {
|
||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_register_data_extractor() {
|
||||
let mut srv =
|
||||
init_service(App::new().register_data(Data::new(10usize)).service(
|
||||
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||
));
|
||||
|
||||
let req = TestRequest::default().to_request();
|
||||
let resp = block_on(srv.call(req)).unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let mut srv =
|
||||
init_service(App::new().register_data(Data::new(10u32)).service(
|
||||
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||
));
|
||||
let req = TestRequest::default().to_request();
|
||||
let resp = block_on(srv.call(req)).unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_route_data_extractor() {
|
||||
let mut srv = init_service(App::new().service(web::resource("/").route(
|
||||
web::get().data(10usize).to(|data: web::RouteData<usize>| {
|
||||
let mut srv =
|
||||
init_service(App::new().service(web::resource("/").data(10usize).route(
|
||||
web::get().to(|data: web::Data<usize>| {
|
||||
let _ = data.clone();
|
||||
HttpResponse::Ok()
|
||||
}),
|
||||
@ -296,15 +192,30 @@ mod tests {
|
||||
// different type
|
||||
let mut srv = init_service(
|
||||
App::new().service(
|
||||
web::resource("/").route(
|
||||
web::get()
|
||||
web::resource("/")
|
||||
.data(10u32)
|
||||
.to(|_: web::RouteData<usize>| HttpResponse::Ok()),
|
||||
),
|
||||
.route(web::get().to(|_: web::Data<usize>| HttpResponse::Ok())),
|
||||
),
|
||||
);
|
||||
let req = TestRequest::default().to_request();
|
||||
let resp = block_on(srv.call(req)).unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_override_data() {
|
||||
let mut srv = init_service(App::new().data(1usize).service(
|
||||
web::resource("/").data(10usize).route(web::get().to(
|
||||
|data: web::Data<usize>| {
|
||||
assert_eq!(*data, 10);
|
||||
let _ = data.clone();
|
||||
HttpResponse::Ok()
|
||||
},
|
||||
)),
|
||||
));
|
||||
|
||||
let req = TestRequest::default().to_request();
|
||||
let resp = block_on(srv.call(req)).unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
}
|
||||
|
46
src/error.rs
46
src/error.rs
@ -6,6 +6,7 @@ use url::ParseError as UrlParseError;
|
||||
|
||||
use crate::http::StatusCode;
|
||||
use crate::HttpResponse;
|
||||
use serde_urlencoded::de;
|
||||
|
||||
/// Errors which can occur when attempting to generate resource uri.
|
||||
#[derive(Debug, PartialEq, Display, From)]
|
||||
@ -91,6 +92,42 @@ impl ResponseError for JsonPayloadError {
|
||||
}
|
||||
}
|
||||
|
||||
/// A set of errors that can occur during parsing request paths
|
||||
#[derive(Debug, Display, From)]
|
||||
pub enum PathError {
|
||||
/// Deserialize error
|
||||
#[display(fmt = "Path deserialize error: {}", _0)]
|
||||
Deserialize(de::Error),
|
||||
}
|
||||
|
||||
/// Return `BadRequest` for `PathError`
|
||||
impl ResponseError for PathError {
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
match *self {
|
||||
PathError::Deserialize(_) => HttpResponse::new(StatusCode::BAD_REQUEST),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A set of errors that can occur during parsing query strings
|
||||
#[derive(Debug, Display, From)]
|
||||
pub enum QueryPayloadError {
|
||||
/// Deserialize error
|
||||
#[display(fmt = "Query deserialize error: {}", _0)]
|
||||
Deserialize(de::Error),
|
||||
}
|
||||
|
||||
/// Return `BadRequest` for `QueryPayloadError`
|
||||
impl ResponseError for QueryPayloadError {
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
match *self {
|
||||
QueryPayloadError::Deserialize(_) => {
|
||||
HttpResponse::new(StatusCode::BAD_REQUEST)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Error type returned when reading body as lines.
|
||||
#[derive(From, Display, Debug)]
|
||||
pub enum ReadlinesError {
|
||||
@ -143,6 +180,15 @@ mod tests {
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_query_payload_error() {
|
||||
let resp: HttpResponse = QueryPayloadError::Deserialize(
|
||||
serde_urlencoded::from_str::<i32>("bad query").unwrap_err(),
|
||||
)
|
||||
.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_readlines_error() {
|
||||
let resp: HttpResponse = ReadlinesError::LimitOverflow.error_response();
|
||||
|
@ -283,7 +283,7 @@ mod tests {
|
||||
header::CONTENT_TYPE,
|
||||
"application/x-www-form-urlencoded",
|
||||
)
|
||||
.route_data(FormConfig::default().limit(4096))
|
||||
.data(FormConfig::default().limit(4096))
|
||||
.to_http_parts();
|
||||
|
||||
let r = block_on(Option::<Form<Info>>::from_request(&req, &mut pl)).unwrap();
|
||||
|
100
src/handler.rs
100
src/handler.rs
@ -1,9 +1,8 @@
|
||||
use std::cell::RefCell;
|
||||
use std::convert::Infallible;
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_http::{Error, Extensions, Payload, Response};
|
||||
use actix_service::{NewService, Service, Void};
|
||||
use actix_http::{Error, Response};
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{try_ready, Async, Future, IntoFuture, Poll};
|
||||
|
||||
@ -73,7 +72,7 @@ where
|
||||
{
|
||||
type Request = (T, HttpRequest);
|
||||
type Response = ServiceResponse;
|
||||
type Error = Void;
|
||||
type Error = Infallible;
|
||||
type Future = HandlerServiceResponse<<R::Future as IntoFuture>::Future>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
@ -100,7 +99,7 @@ where
|
||||
T::Error: Into<Error>,
|
||||
{
|
||||
type Item = ServiceResponse;
|
||||
type Error = Void;
|
||||
type Error = Infallible;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self.fut.poll() {
|
||||
@ -124,7 +123,7 @@ where
|
||||
pub trait AsyncFactory<T, R>: Clone + 'static
|
||||
where
|
||||
R: IntoFuture,
|
||||
R::Item: Into<Response>,
|
||||
R::Item: Responder,
|
||||
R::Error: Into<Error>,
|
||||
{
|
||||
fn call(&self, param: T) -> R;
|
||||
@ -134,7 +133,7 @@ impl<F, R> AsyncFactory<(), R> for F
|
||||
where
|
||||
F: Fn() -> R + Clone + 'static,
|
||||
R: IntoFuture,
|
||||
R::Item: Into<Response>,
|
||||
R::Item: Responder,
|
||||
R::Error: Into<Error>,
|
||||
{
|
||||
fn call(&self, _: ()) -> R {
|
||||
@ -147,7 +146,7 @@ pub struct AsyncHandler<F, T, R>
|
||||
where
|
||||
F: AsyncFactory<T, R>,
|
||||
R: IntoFuture,
|
||||
R::Item: Into<Response>,
|
||||
R::Item: Responder,
|
||||
R::Error: Into<Error>,
|
||||
{
|
||||
hnd: F,
|
||||
@ -158,7 +157,7 @@ impl<F, T, R> AsyncHandler<F, T, R>
|
||||
where
|
||||
F: AsyncFactory<T, R>,
|
||||
R: IntoFuture,
|
||||
R::Item: Into<Response>,
|
||||
R::Item: Responder,
|
||||
R::Error: Into<Error>,
|
||||
{
|
||||
pub fn new(hnd: F) -> Self {
|
||||
@ -173,7 +172,7 @@ impl<F, T, R> Clone for AsyncHandler<F, T, R>
|
||||
where
|
||||
F: AsyncFactory<T, R>,
|
||||
R: IntoFuture,
|
||||
R::Item: Into<Response>,
|
||||
R::Item: Responder,
|
||||
R::Error: Into<Error>,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
@ -188,12 +187,12 @@ impl<F, T, R> Service for AsyncHandler<F, T, R>
|
||||
where
|
||||
F: AsyncFactory<T, R>,
|
||||
R: IntoFuture,
|
||||
R::Item: Into<Response>,
|
||||
R::Item: Responder,
|
||||
R::Error: Into<Error>,
|
||||
{
|
||||
type Request = (T, HttpRequest);
|
||||
type Response = ServiceResponse;
|
||||
type Error = Void;
|
||||
type Error = Infallible;
|
||||
type Future = AsyncHandlerServiceResponse<R::Future>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
@ -203,31 +202,38 @@ where
|
||||
fn call(&mut self, (param, req): (T, HttpRequest)) -> Self::Future {
|
||||
AsyncHandlerServiceResponse {
|
||||
fut: self.hnd.call(param).into_future(),
|
||||
fut2: None,
|
||||
req: Some(req),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct AsyncHandlerServiceResponse<T> {
|
||||
pub struct AsyncHandlerServiceResponse<T>
|
||||
where
|
||||
T: Future,
|
||||
T::Item: Responder,
|
||||
{
|
||||
fut: T,
|
||||
fut2: Option<<<T::Item as Responder>::Future as IntoFuture>::Future>,
|
||||
req: Option<HttpRequest>,
|
||||
}
|
||||
|
||||
impl<T> Future for AsyncHandlerServiceResponse<T>
|
||||
where
|
||||
T: Future,
|
||||
T::Item: Into<Response>,
|
||||
T::Item: Responder,
|
||||
T::Error: Into<Error>,
|
||||
{
|
||||
type Item = ServiceResponse;
|
||||
type Error = Void;
|
||||
type Error = Infallible;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self.fut.poll() {
|
||||
if let Some(ref mut fut) = self.fut2 {
|
||||
return match fut.poll() {
|
||||
Ok(Async::Ready(res)) => Ok(Async::Ready(ServiceResponse::new(
|
||||
self.req.take().unwrap(),
|
||||
res.into(),
|
||||
res,
|
||||
))),
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Err(e) => {
|
||||
@ -237,21 +243,36 @@ where
|
||||
res,
|
||||
)))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
match self.fut.poll() {
|
||||
Ok(Async::Ready(res)) => {
|
||||
self.fut2 =
|
||||
Some(res.respond_to(self.req.as_ref().unwrap()).into_future());
|
||||
return self.poll();
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Err(e) => {
|
||||
let res: Response = e.into().into();
|
||||
Ok(Async::Ready(ServiceResponse::new(
|
||||
self.req.take().unwrap(),
|
||||
res,
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract arguments from request
|
||||
pub struct Extract<T: FromRequest, S> {
|
||||
config: Rc<RefCell<Option<Rc<Extensions>>>>,
|
||||
service: S,
|
||||
_t: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T: FromRequest, S> Extract<T, S> {
|
||||
pub fn new(config: Rc<RefCell<Option<Rc<Extensions>>>>, service: S) -> Self {
|
||||
pub fn new(service: S) -> Self {
|
||||
Extract {
|
||||
config,
|
||||
service,
|
||||
_t: PhantomData,
|
||||
}
|
||||
@ -260,9 +281,13 @@ impl<T: FromRequest, S> Extract<T, S> {
|
||||
|
||||
impl<T: FromRequest, S> NewService for Extract<T, S>
|
||||
where
|
||||
S: Service<Request = (T, HttpRequest), Response = ServiceResponse, Error = Void>
|
||||
+ Clone,
|
||||
S: Service<
|
||||
Request = (T, HttpRequest),
|
||||
Response = ServiceResponse,
|
||||
Error = Infallible,
|
||||
> + Clone,
|
||||
{
|
||||
type Config = ();
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse;
|
||||
type Error = (Error, ServiceRequest);
|
||||
@ -273,22 +298,23 @@ where
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(ExtractService {
|
||||
_t: PhantomData,
|
||||
config: self.config.borrow().clone(),
|
||||
service: self.service.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ExtractService<T: FromRequest, S> {
|
||||
config: Option<Rc<Extensions>>,
|
||||
service: S,
|
||||
_t: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T: FromRequest, S> Service for ExtractService<T, S>
|
||||
where
|
||||
S: Service<Request = (T, HttpRequest), Response = ServiceResponse, Error = Void>
|
||||
+ Clone,
|
||||
S: Service<
|
||||
Request = (T, HttpRequest),
|
||||
Response = ServiceResponse,
|
||||
Error = Infallible,
|
||||
> + Clone,
|
||||
{
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse;
|
||||
@ -300,21 +326,20 @@ where
|
||||
}
|
||||
|
||||
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
||||
let (mut req, mut payload) = req.into_parts();
|
||||
req.set_route_data(self.config.clone());
|
||||
let (req, mut payload) = req.into_parts();
|
||||
let fut = T::from_request(&req, &mut payload).into_future();
|
||||
|
||||
ExtractResponse {
|
||||
fut,
|
||||
req,
|
||||
fut_s: None,
|
||||
req: Some((req, payload)),
|
||||
service: self.service.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ExtractResponse<T: FromRequest, S: Service> {
|
||||
req: Option<(HttpRequest, Payload)>,
|
||||
req: HttpRequest,
|
||||
service: S,
|
||||
fut: <T::Future as IntoFuture>::Future,
|
||||
fut_s: Option<S::Future>,
|
||||
@ -322,7 +347,11 @@ pub struct ExtractResponse<T: FromRequest, S: Service> {
|
||||
|
||||
impl<T: FromRequest, S> Future for ExtractResponse<T, S>
|
||||
where
|
||||
S: Service<Request = (T, HttpRequest), Response = ServiceResponse, Error = Void>,
|
||||
S: Service<
|
||||
Request = (T, HttpRequest),
|
||||
Response = ServiceResponse,
|
||||
Error = Infallible,
|
||||
>,
|
||||
{
|
||||
type Item = ServiceResponse;
|
||||
type Error = (Error, ServiceRequest);
|
||||
@ -333,12 +362,11 @@ where
|
||||
}
|
||||
|
||||
let item = try_ready!(self.fut.poll().map_err(|e| {
|
||||
let (req, payload) = self.req.take().unwrap();
|
||||
let req = ServiceRequest::from_parts(req, payload);
|
||||
let req = ServiceRequest::new(self.req.clone());
|
||||
(e.into(), req)
|
||||
}));
|
||||
|
||||
self.fut_s = Some(self.service.call((item, self.req.take().unwrap().0)));
|
||||
self.fut_s = Some(self.service.call((item, self.req.clone())));
|
||||
self.poll()
|
||||
}
|
||||
}
|
||||
@ -357,7 +385,7 @@ macro_rules! factory_tuple ({ $(($n:tt, $T:ident)),+} => {
|
||||
impl<Func, $($T,)+ Res> AsyncFactory<($($T,)+), Res> for Func
|
||||
where Func: Fn($($T,)+) -> Res + Clone + 'static,
|
||||
Res: IntoFuture,
|
||||
Res::Item: Into<Response>,
|
||||
Res::Item: Responder,
|
||||
Res::Error: Into<Error>,
|
||||
{
|
||||
fn call(&self, param: ($($T,)+)) -> Res {
|
||||
|
15
src/lib.rs
15
src/lib.rs
@ -66,15 +66,15 @@
|
||||
//!
|
||||
//! ## Package feature
|
||||
//!
|
||||
//! * `client` - enables http client
|
||||
//! * `client` - enables http client (default enabled)
|
||||
//! * `ssl` - enables ssl support via `openssl` crate, supports `http/2`
|
||||
//! * `rust-tls` - enables ssl support via `rustls` crate, supports `http/2`
|
||||
//! * `secure-cookies` - enables secure cookies support, includes `ring` crate as
|
||||
//! dependency
|
||||
//! * `brotli` - enables `brotli` compression support, requires `c`
|
||||
//! compiler
|
||||
//! compiler (default enabled)
|
||||
//! * `flate2-zlib` - enables `gzip`, `deflate` compression support, requires
|
||||
//! `c` compiler
|
||||
//! `c` compiler (default enabled)
|
||||
//! * `flate2-rust` - experimental rust based implementation for
|
||||
//! `gzip`, `deflate` compression.
|
||||
//!
|
||||
@ -111,7 +111,7 @@ pub use actix_web_codegen::*;
|
||||
|
||||
// re-export for convenience
|
||||
pub use actix_http::Response as HttpResponse;
|
||||
pub use actix_http::{cookie, http, Error, HttpMessage, ResponseError, Result};
|
||||
pub use actix_http::{body, cookie, http, Error, HttpMessage, ResponseError, Result};
|
||||
|
||||
pub use crate::app::App;
|
||||
pub use crate::extract::FromRequest;
|
||||
@ -136,12 +136,14 @@ pub mod dev {
|
||||
pub use crate::config::{AppConfig, AppService};
|
||||
pub use crate::info::ConnectionInfo;
|
||||
pub use crate::rmap::ResourceMap;
|
||||
pub use crate::service::{HttpServiceFactory, ServiceRequest, ServiceResponse};
|
||||
pub use crate::service::{
|
||||
HttpServiceFactory, ServiceRequest, ServiceResponse, WebService,
|
||||
};
|
||||
pub use crate::types::form::UrlEncoded;
|
||||
pub use crate::types::json::JsonBody;
|
||||
pub use crate::types::readlines::Readlines;
|
||||
|
||||
pub use actix_http::body::{Body, BodySize, MessageBody, ResponseBody};
|
||||
pub use actix_http::body::{Body, BodySize, MessageBody, ResponseBody, SizedStream};
|
||||
pub use actix_http::encoding::Decoder as Decompress;
|
||||
pub use actix_http::ResponseBuilder as HttpResponseBuilder;
|
||||
pub use actix_http::{
|
||||
@ -149,6 +151,7 @@ pub mod dev {
|
||||
};
|
||||
pub use actix_router::{Path, ResourceDef, ResourcePath, Url};
|
||||
pub use actix_server::Server;
|
||||
pub use actix_service::{Service, Transform};
|
||||
|
||||
pub(crate) fn insert_slash(path: &str) -> String {
|
||||
let mut path = path.to_owned();
|
||||
|
@ -6,7 +6,7 @@ use std::str::FromStr;
|
||||
use actix_http::body::MessageBody;
|
||||
use actix_http::encoding::Encoder;
|
||||
use actix_http::http::header::{ContentEncoding, ACCEPT_ENCODING};
|
||||
use actix_http::{Response, ResponseBuilder};
|
||||
use actix_http::{Error, Response, ResponseBuilder};
|
||||
use actix_service::{Service, Transform};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
@ -71,11 +71,11 @@ impl Default for Compress {
|
||||
impl<S, B> Transform<S> for Compress
|
||||
where
|
||||
B: MessageBody,
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
{
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse<Encoder<B>>;
|
||||
type Error = S::Error;
|
||||
type Error = Error;
|
||||
type InitError = ();
|
||||
type Transform = CompressMiddleware<S>;
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
@ -96,11 +96,11 @@ pub struct CompressMiddleware<S> {
|
||||
impl<S, B> Service for CompressMiddleware<S>
|
||||
where
|
||||
B: MessageBody,
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
{
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse<Encoder<B>>;
|
||||
type Error = S::Error;
|
||||
type Error = Error;
|
||||
type Future = CompressResponse<S, B>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
@ -141,10 +141,10 @@ where
|
||||
impl<S, B> Future for CompressResponse<S, B>
|
||||
where
|
||||
B: MessageBody,
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
{
|
||||
type Item = ServiceResponse<Encoder<B>>;
|
||||
type Error = S::Error;
|
||||
type Error = Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
let resp = futures::try_ready!(self.fut.poll());
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user