Skip to content

Commit 04361b7

Browse files
davidpdrsnjplatte
andauthored
Upgrade to http-body 1.0 (#348)
* punt on examples for now * remove dependency on hyper * port to http-body 1.0 * note which types from http_body_util is in our public api * wrap body types * fix some warnings * comment out compression stuff for now * validate-request docs * trace * timeout * set_status * set_header * serve_dir * redirect * follow_redirect * sensitive_headers * request_id * propagate_header * normalize_path * in_flight_requests * map_response_body * map_request_body * limit * lib * cors * classify * add_extension * catch_panic * add_authorization * require_authorization + async_require_authorization * builder * format * fixes * fix docs * fix cargo hack * is this breaking patches in Cargo.toml? * update to 1.0 of dependencies * porting compression like this seems to work \o/ * use `BodyExt::collect` in tests * compression is back! * and thats decompression! * remove hyper specific test * Update examples/axum-key-value-store/src/main.rs Co-authored-by: Jonas Platte <jplatte+git@posteo.de> * bring back client examples * fix doc tests * forgot ServiceBuilderExt * changelog * Fix potential ordering issues with `BodyIntoStream` * don't delegate `is_end_stream` * fix typos * use std::task::ready * uncomment CompressionLayer in examples * Derive default * format * bring back hyper compat test * remove lint. Lets just add this back later. Wanna merge now --------- Co-authored-by: Jonas Platte <jplatte+git@posteo.de>
1 parent d2eadcb commit 04361b7

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

60 files changed

+1135
-939
lines changed

Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
[workspace]
2+
resolver = "2"
23
members = [
34
"tower-http",
45
"examples/*",

examples/axum-key-value-store/src/main.rs

+6
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
fn main() {
2+
eprintln!("this example has not yet been updated to hyper 1.0");
3+
}
4+
5+
/*
16
use axum::{
27
body::Bytes,
38
extract::{Path, State},
@@ -108,3 +113,4 @@ async fn set_key(Path(path): Path<String>, state: State<AppState>, value: Bytes)
108113
109114
// See https://github.com/tokio-rs/axum/blob/main/examples/testing/src/main.rs for an example of
110115
// how to test axum apps
116+
*/

examples/tonic-key-value-store/src/main.rs

+6
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
fn main() {
2+
eprint!("this example has not yet been updated to hyper 1.0");
3+
}
4+
5+
/*
16
use bytes::Bytes;
27
use clap::Parser;
38
use futures::StreamExt;
@@ -370,3 +375,4 @@ mod tests {
370375
addr
371376
}
372377
}
378+
*/

examples/warp-key-value-store/src/main.rs

+6
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
fn main() {
2+
eprint!("this example has not yet been updated to hyper 1.0");
3+
}
4+
5+
/*
16
use bytes::Bytes;
27
use clap::Parser;
38
use hyper::{
@@ -222,3 +227,4 @@ mod tests {
222227
addr
223228
}
224229
}
230+
*/

tower-http/CHANGELOG.md

+3
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1414
## Changed
1515

1616
- Bump Minimum Supported Rust Version to 1.66 ([#433])
17+
- Update to http-body 1.0 ([#348])
18+
- Update to http 1.0 ([#348])
1719
- Preserve service error type in RequestDecompression ([#368])
1820

1921
## Removed
@@ -27,6 +29,7 @@ http-range-header to `0.4`
2729

2830
[#418]: https://github.com/tower-rs/tower-http/pull/418
2931
[#433]: https://github.com/tower-rs/tower-http/pull/433
32+
[#348]: https://github.com/tower-rs/tower-http/pull/348
3033
[#368]: https://github.com/tower-rs/tower-http/pull/368
3134

3235
# 0.4.2 (July 19, 2023)

tower-http/Cargo.toml

+10-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
[package]
22
name = "tower-http"
33
description = "Tower middleware and utilities for HTTP clients and servers"
4-
version = "0.4.2"
4+
version = "0.4.4"
55
authors = ["Tower Maintainers <team@tower-rs.com>"]
66
edition = "2018"
77
license = "MIT"
@@ -15,8 +15,9 @@ rust-version = "1.66"
1515
[dependencies]
1616
bitflags = "2.0.2"
1717
bytes = "1"
18-
http = "0.2.7"
19-
http-body = "0.4.5"
18+
http = "1.0"
19+
http-body = "1.0.0"
20+
http-body-util = "0.1.0"
2021
pin-project-lite = "0.2.7"
2122
tower-layer = "0.3"
2223
tower-service = "0.3"
@@ -38,16 +39,19 @@ httpdate = { version = "1.0", optional = true }
3839
uuid = { version = "1.0", features = ["v4"], optional = true }
3940

4041
[dev-dependencies]
42+
async-trait = "0.1"
43+
brotli = "3"
4144
bytes = "1"
4245
flate2 = "1.0"
43-
brotli = "3"
44-
hyper = { version = "0.14", features = ["full"] }
46+
futures-util = "0.3.14"
47+
hyper-util = { version = "0.1", features = ["client-legacy", "http1", "tokio"] }
4548
once_cell = "1"
49+
serde_json = "1.0"
50+
sync_wrapper = "0.1.1"
4651
tokio = { version = "1", features = ["full"] }
4752
tower = { version = "0.4.10", features = ["buffer", "util", "retry", "make", "timeout"] }
4853
tracing-subscriber = "0.3"
4954
uuid = { version = "1.0", features = ["v4"] }
50-
serde_json = "1.0"
5155
zstd = "0.12"
5256

5357
[features]

tower-http/src/add_extension.rs

+6-5
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
//! use tower_http::add_extension::AddExtensionLayer;
99
//! use tower::{Service, ServiceExt, ServiceBuilder, service_fn};
1010
//! use http::{Request, Response};
11-
//! use hyper::Body;
11+
//! use bytes::Bytes;
12+
//! use http_body_util::Full;
1213
//! use std::{sync::Arc, convert::Infallible};
1314
//!
1415
//! # struct DatabaseConnectionPool;
@@ -21,11 +22,11 @@
2122
//! pool: DatabaseConnectionPool,
2223
//! }
2324
//!
24-
//! async fn handle(req: Request<Body>) -> Result<Response<Body>, Infallible> {
25+
//! async fn handle(req: Request<Full<Bytes>>) -> Result<Response<Full<Bytes>>, Infallible> {
2526
//! // Grab the state from the request extensions.
2627
//! let state = req.extensions().get::<Arc<State>>().unwrap();
2728
//!
28-
//! Ok(Response::new(Body::empty()))
29+
//! Ok(Response::new(Full::default()))
2930
//! }
3031
//!
3132
//! # #[tokio::main]
@@ -44,7 +45,7 @@
4445
//! let response = service
4546
//! .ready()
4647
//! .await?
47-
//! .call(Request::new(Body::empty()))
48+
//! .call(Request::new(Full::default()))
4849
//! .await?;
4950
//! # Ok(())
5051
//! # }
@@ -137,8 +138,8 @@ where
137138
mod tests {
138139
#[allow(unused_imports)]
139140
use super::*;
141+
use crate::test_helpers::Body;
140142
use http::Response;
141-
use hyper::Body;
142143
use std::{convert::Infallible, sync::Arc};
143144
use tower::{service_fn, ServiceBuilder, ServiceExt};
144145

tower-http/src/auth/add_authorization.rs

+14-14
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,16 @@
77
//! ```
88
//! use tower_http::validate_request::{ValidateRequestHeader, ValidateRequestHeaderLayer};
99
//! use tower_http::auth::AddAuthorizationLayer;
10-
//! use hyper::{Request, Response, Body, Error};
11-
//! use http::{StatusCode, header::AUTHORIZATION};
12-
//! use tower::{Service, ServiceExt, ServiceBuilder, service_fn};
13-
//! # async fn handle(request: Request<Body>) -> Result<Response<Body>, Error> {
14-
//! # Ok(Response::new(Body::empty()))
10+
//! use http::{Request, Response, StatusCode, header::AUTHORIZATION};
11+
//! use tower::{Service, ServiceExt, ServiceBuilder, service_fn, BoxError};
12+
//! use http_body_util::Full;
13+
//! use bytes::Bytes;
14+
//! # async fn handle(request: Request<Full<Bytes>>) -> Result<Response<Full<Bytes>>, BoxError> {
15+
//! # Ok(Response::new(Full::default()))
1516
//! # }
1617
//!
1718
//! # #[tokio::main]
18-
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
19+
//! # async fn main() -> Result<(), BoxError> {
1920
//! # let service_that_requires_auth = ValidateRequestHeader::basic(
2021
//! # tower::service_fn(handle),
2122
//! # "username",
@@ -30,7 +31,7 @@
3031
//! let response = client
3132
//! .ready()
3233
//! .await?
33-
//! .call(Request::new(Body::empty()))
34+
//! .call(Request::new(Full::default()))
3435
//! .await?;
3536
//!
3637
//! assert_eq!(StatusCode::OK, response.status());
@@ -84,7 +85,7 @@ impl AddAuthorizationLayer {
8485
///
8586
/// # Panics
8687
///
87-
/// Panics if the token is not a valid [`HeaderValue`](http::header::HeaderValue).
88+
/// Panics if the token is not a valid [`HeaderValue`].
8889
pub fn bearer(token: &str) -> Self {
8990
let value =
9091
HeaderValue::try_from(format!("Bearer {}", token)).expect("token is not valid header");
@@ -147,7 +148,7 @@ impl<S> AddAuthorization<S> {
147148
///
148149
/// # Panics
149150
///
150-
/// Panics if the token is not a valid [`HeaderValue`](http::header::HeaderValue).
151+
/// Panics if the token is not a valid [`HeaderValue`].
151152
pub fn bearer(inner: S, token: &str) -> Self {
152153
AddAuthorizationLayer::bearer(token).layer(inner)
153154
}
@@ -187,12 +188,11 @@ where
187188

188189
#[cfg(test)]
189190
mod tests {
190-
use crate::validate_request::ValidateRequestHeaderLayer;
191-
192-
#[allow(unused_imports)]
193191
use super::*;
192+
use crate::test_helpers::Body;
193+
use crate::validate_request::ValidateRequestHeaderLayer;
194194
use http::{Response, StatusCode};
195-
use hyper::Body;
195+
use std::convert::Infallible;
196196
use tower::{BoxError, Service, ServiceBuilder, ServiceExt};
197197

198198
#[tokio::test]
@@ -245,7 +245,7 @@ mod tests {
245245
let auth = request.headers().get(http::header::AUTHORIZATION).unwrap();
246246
assert!(auth.is_sensitive());
247247

248-
Ok::<_, hyper::Error>(Response::new(Body::empty()))
248+
Ok::<_, Infallible>(Response::new(Body::empty()))
249249
});
250250

251251
let mut client = AddAuthorization::bearer(svc, "foo").as_sensitive(true);

tower-http/src/auth/async_require_authorization.rs

+20-18
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@
66
//!
77
//! ```
88
//! use tower_http::auth::{AsyncRequireAuthorizationLayer, AsyncAuthorizeRequest};
9-
//! use hyper::{Request, Response, Body, Error};
10-
//! use http::{StatusCode, header::AUTHORIZATION};
11-
//! use tower::{Service, ServiceExt, ServiceBuilder, service_fn};
9+
//! use http::{Request, Response, StatusCode, header::AUTHORIZATION};
10+
//! use tower::{Service, ServiceExt, ServiceBuilder, service_fn, BoxError};
1211
//! use futures_util::future::BoxFuture;
12+
//! use bytes::Bytes;
13+
//! use http_body_util::Full;
1314
//!
1415
//! #[derive(Clone, Copy)]
1516
//! struct MyAuth;
@@ -19,7 +20,7 @@
1920
//! B: Send + Sync + 'static,
2021
//! {
2122
//! type RequestBody = B;
22-
//! type ResponseBody = Body;
23+
//! type ResponseBody = Full<Bytes>;
2324
//! type Future = BoxFuture<'static, Result<Request<B>, Response<Self::ResponseBody>>>;
2425
//!
2526
//! fn authorize(&mut self, mut request: Request<B>) -> Self::Future {
@@ -33,7 +34,7 @@
3334
//! } else {
3435
//! let unauthorized_response = Response::builder()
3536
//! .status(StatusCode::UNAUTHORIZED)
36-
//! .body(Body::empty())
37+
//! .body(Full::<Bytes>::default())
3738
//! .unwrap();
3839
//!
3940
//! Err(unauthorized_response)
@@ -47,10 +48,10 @@
4748
//! # None
4849
//! }
4950
//!
50-
//! #[derive(Debug)]
51+
//! #[derive(Debug, Clone)]
5152
//! struct UserId(String);
5253
//!
53-
//! async fn handle(request: Request<Body>) -> Result<Response<Body>, Error> {
54+
//! async fn handle(request: Request<Full<Bytes>>) -> Result<Response<Full<Bytes>>, BoxError> {
5455
//! // Access the `UserId` that was set in `on_authorized`. If `handle` gets called the
5556
//! // request was authorized and `UserId` will be present.
5657
//! let user_id = request
@@ -60,11 +61,11 @@
6061
//!
6162
//! println!("request from {:?}", user_id);
6263
//!
63-
//! Ok(Response::new(Body::empty()))
64+
//! Ok(Response::new(Full::default()))
6465
//! }
6566
//!
6667
//! # #[tokio::main]
67-
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
68+
//! # async fn main() -> Result<(), BoxError> {
6869
//! let service = ServiceBuilder::new()
6970
//! // Authorize requests using `MyAuth`
7071
//! .layer(AsyncRequireAuthorizationLayer::new(MyAuth))
@@ -77,10 +78,11 @@
7778
//!
7879
//! ```
7980
//! use tower_http::auth::{AsyncRequireAuthorizationLayer, AsyncAuthorizeRequest};
80-
//! use hyper::{Request, Response, Body, Error};
81-
//! use http::StatusCode;
82-
//! use tower::{Service, ServiceExt, ServiceBuilder};
81+
//! use http::{Request, Response, StatusCode};
82+
//! use tower::{Service, ServiceExt, ServiceBuilder, BoxError};
8383
//! use futures_util::future::BoxFuture;
84+
//! use http_body_util::Full;
85+
//! use bytes::Bytes;
8486
//!
8587
//! async fn check_auth<B>(request: &Request<B>) -> Option<UserId> {
8688
//! // ...
@@ -90,21 +92,21 @@
9092
//! #[derive(Debug)]
9193
//! struct UserId(String);
9294
//!
93-
//! async fn handle(request: Request<Body>) -> Result<Response<Body>, Error> {
95+
//! async fn handle(request: Request<Full<Bytes>>) -> Result<Response<Full<Bytes>>, BoxError> {
9496
//! # todo!();
9597
//! // ...
9698
//! }
9799
//!
98100
//! # #[tokio::main]
99-
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
101+
//! # async fn main() -> Result<(), BoxError> {
100102
//! let service = ServiceBuilder::new()
101-
//! .layer(AsyncRequireAuthorizationLayer::new(|request: Request<Body>| async move {
103+
//! .layer(AsyncRequireAuthorizationLayer::new(|request: Request<Full<Bytes>>| async move {
102104
//! if let Some(user_id) = check_auth(&request).await {
103105
//! Ok(request)
104106
//! } else {
105107
//! let unauthorized_response = Response::builder()
106108
//! .status(StatusCode::UNAUTHORIZED)
107-
//! .body(Body::empty())
109+
//! .body(Full::<Bytes>::default())
108110
//! .unwrap();
109111
//!
110112
//! Err(unauthorized_response)
@@ -306,9 +308,9 @@ where
306308
mod tests {
307309
#[allow(unused_imports)]
308310
use super::*;
311+
use crate::test_helpers::Body;
309312
use futures_util::future::BoxFuture;
310313
use http::{header, StatusCode};
311-
use hyper::Body;
312314
use tower::{BoxError, ServiceBuilder, ServiceExt};
313315

314316
#[derive(Clone, Copy)]
@@ -346,7 +348,7 @@ mod tests {
346348
}
347349
}
348350

349-
#[derive(Debug)]
351+
#[derive(Clone, Debug)]
350352
struct UserId(String);
351353

352354
#[tokio::test]

0 commit comments

Comments
 (0)