├── .gitignore ├── Cargo.toml ├── LICENSE-MIT ├── .github └── workflows │ └── ci.yml ├── examples └── client.rs ├── README.md ├── tests └── client_upload.rs ├── src ├── lib.rs └── stream.rs └── LICENSE-APACHE /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hyper-timeout" 3 | version = "0.5.2" 4 | authors = ["Herman J. Radtke III "] 5 | edition = "2018" 6 | description = "A connect, read and write timeout aware connector to be used with hyper Client." 7 | license = "MIT OR Apache-2.0" 8 | documentation = "https://github.com/hjr3/hyper-timeout" 9 | homepage = "https://github.com/hjr3/hyper-timeout" 10 | repository = "https://github.com/hjr3/hyper-timeout" 11 | readme = "README.md" 12 | 13 | [dependencies] 14 | hyper = "1.1" 15 | hyper-util = { version = "0.1.10", features = ["client-legacy", "http1"] } 16 | pin-project-lite = "0.2" 17 | tokio = "1.35" 18 | tower-service = "0.3" 19 | 20 | [dev-dependencies] 21 | tokio = { version = "1.35", features = ["io-std", "io-util", "macros"] } 22 | hyper = { version = "1.1", features = ["http1"] } 23 | hyper-tls = "0.6" 24 | http-body-util = "0.1" 25 | hyper-util = { version = "0.1.10", features = ["client-legacy", "http1", "server", "server-graceful"] } 26 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 The weldr Project Developers 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: 4 | - master 5 | pull_request: {} 6 | 7 | name: Continuous integration 8 | 9 | jobs: 10 | check: 11 | name: Check 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | - uses: actions-rs/toolchain@v1 16 | with: 17 | profile: minimal 18 | toolchain: stable 19 | override: true 20 | - uses: actions-rs/cargo@v1 21 | with: 22 | command: check 23 | 24 | test: 25 | name: Test Suite 26 | runs-on: ubuntu-latest 27 | steps: 28 | - uses: actions/checkout@v2 29 | - uses: actions-rs/toolchain@v1 30 | with: 31 | profile: minimal 32 | toolchain: stable 33 | override: true 34 | - uses: actions-rs/cargo@v1 35 | with: 36 | command: test 37 | 38 | fmt: 39 | name: Rustfmt 40 | runs-on: ubuntu-latest 41 | steps: 42 | - uses: actions/checkout@v2 43 | - uses: actions-rs/toolchain@v1 44 | with: 45 | profile: minimal 46 | toolchain: stable 47 | override: true 48 | - run: rustup component add rustfmt 49 | - uses: actions-rs/cargo@v1 50 | with: 51 | command: fmt 52 | args: --all -- --check 53 | 54 | clippy: 55 | name: Clippy 56 | runs-on: ubuntu-latest 57 | steps: 58 | - uses: actions/checkout@v2 59 | - uses: actions-rs/toolchain@v1 60 | with: 61 | profile: minimal 62 | toolchain: stable 63 | override: true 64 | - run: rustup component add clippy 65 | - uses: actions-rs/cargo@v1 66 | with: 67 | command: clippy 68 | args: -- -D warnings 69 | -------------------------------------------------------------------------------- /examples/client.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::time::Duration; 3 | 4 | use http_body_util::{BodyExt, Empty}; 5 | use hyper::body::Bytes; 6 | use hyper_util::{client::legacy::Client, rt::TokioExecutor}; 7 | use tokio::io::{self, AsyncWriteExt}; 8 | 9 | use hyper_tls::HttpsConnector; 10 | 11 | use hyper_timeout::TimeoutConnector; 12 | 13 | #[tokio::main(flavor = "current_thread")] 14 | async fn main() -> Result<(), Box> { 15 | let url = match env::args().nth(1) { 16 | Some(url) => url, 17 | None => { 18 | println!("Usage: client "); 19 | println!("Example: client https://example.com"); 20 | return Ok(()); 21 | } 22 | }; 23 | 24 | let url = url.parse::().unwrap(); 25 | 26 | // This example uses `HttpsConnector`, but you can also use hyper `HttpConnector` 27 | //let h = hyper_util::client::legacy::connect::HttpConnector::new(); 28 | let h = HttpsConnector::new(); 29 | let mut connector = TimeoutConnector::new(h); 30 | connector.set_connect_timeout(Some(Duration::from_secs(5))); 31 | connector.set_read_timeout(Some(Duration::from_secs(5))); 32 | connector.set_write_timeout(Some(Duration::from_secs(5))); 33 | let client = Client::builder(TokioExecutor::new()).build::<_, Empty>(connector); 34 | 35 | let mut res = client.get(url).await?; 36 | 37 | println!("Status: {}", res.status()); 38 | println!("Headers:\n{:#?}", res.headers()); 39 | 40 | while let Some(frame) = res.body_mut().frame().await { 41 | let bytes = frame? 42 | .into_data() 43 | .map_err(|_| io::Error::new(io::ErrorKind::Other, "Error when consuming frame"))?; 44 | io::stdout().write_all(&bytes).await?; 45 | } 46 | 47 | Ok(()) 48 | } 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![crates.io](https://img.shields.io/crates/v/hyper-timeout.svg)](https://crates.io/crates/hyper-timeout) 2 | 3 | # hyper-timeout 4 | 5 | A connect, read and write timeout aware connector to be used with hyper `Client`. 6 | 7 | ## Problem 8 | 9 | At the time this crate was created, hyper did not support timeouts. There is a way to do general timeouts, but no easy way to get connect, read and write specific timeouts. 10 | 11 | ## Solution 12 | 13 | There is a `TimeoutConnector` that implements the `hyper::Connect` trait. This connector wraps around `HttpConnector` or `HttpsConnector` values and provides timeouts. 14 | 15 | > [!IMPORTANT] 16 | > The timeouts are on the underlying stream and _not_ the request. 17 | 18 | - The read timeout will start when the underlying stream is first polled for read. 19 | - The write timeout will start when the underlying stream is first polled for write. 20 | 21 | Tokio often interleaves poll_read and poll_write calls to handle this bi-directional communication efficiently. Due to this behavior, both the read and write timeouts start at the same time. This means your read timeout can expire while the client is still writing the request to the server. If you are writing large bodies, consider using `set_reset_reader_on_write` to avoid this behavior. 22 | 23 | ## Usage 24 | 25 | Hyper version compatibility: 26 | 27 | - The `master` branch will track on going development for hyper. 28 | - The `0.5` release supports hyper 1.0. 29 | - The `0.4` release supports hyper 0.14. 30 | - The `0.3` release supports hyper 0.13. 31 | - The `0.2` release supports hyper 0.12. 32 | - The `0.1` release supports hyper 0.11. 33 | - **Note:** In hyper 0.11, a read or write timeout will return a _broken pipe_ error because of the way `tokio_proto::ClientProto` works 34 | 35 | 36 | Assuming you are using hyper 1.0, add this to your `Cargo.toml`: 37 | 38 | ```toml 39 | [dependencies] 40 | hyper-timeout = "0.5" 41 | ``` 42 | 43 | See the [client example](./examples/client.rs) for a working example. 44 | 45 | ## License 46 | 47 | Licensed under either of 48 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 49 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 50 | at your option. 51 | 52 | ### Contribution 53 | 54 | Unless you explicitly state otherwise, any contribution intentionally submitted 55 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any 56 | additional terms or conditions. 57 | -------------------------------------------------------------------------------- /tests/client_upload.rs: -------------------------------------------------------------------------------- 1 | use http_body_util::{combinators::BoxBody, BodyExt, Full}; 2 | use hyper::body::Bytes; 3 | use hyper::server::conn::http1; 4 | use hyper::service::service_fn; 5 | use hyper::{Request, Response}; 6 | use hyper_util::{client::legacy::Client, rt::TokioIo}; 7 | use std::{net::SocketAddr, time::Duration}; 8 | use tokio::io; 9 | use tokio::net::TcpListener; 10 | use tokio::sync::oneshot; 11 | use tokio::task; 12 | 13 | use hyper_timeout::TimeoutConnector; 14 | 15 | async fn spawn_test_server(listener: TcpListener, shutdown_rx: oneshot::Receiver<()>) { 16 | let http = http1::Builder::new(); 17 | let graceful = hyper_util::server::graceful::GracefulShutdown::new(); 18 | let mut signal = std::pin::pin!(shutdown_rx); 19 | 20 | loop { 21 | tokio::select! { 22 | Ok((stream, _addr)) = listener.accept() => { 23 | let io = TokioIo::new(stream); 24 | let conn = http.serve_connection(io, service_fn(handle_request)); 25 | // watch this connection 26 | let fut = graceful.watch(conn); 27 | tokio::spawn(async move { 28 | if let Err(e) = fut.await { 29 | eprintln!("Error serving connection: {:?}", e); 30 | } 31 | }); 32 | }, 33 | 34 | _ = &mut signal => { 35 | eprintln!("graceful shutdown signal received"); 36 | break; 37 | } 38 | } 39 | } 40 | 41 | tokio::select! { 42 | _ = graceful.shutdown() => { 43 | eprintln!("all connections gracefully closed"); 44 | }, 45 | _ = tokio::time::sleep(std::time::Duration::from_millis(100)) => { 46 | eprintln!("timed out wait for all connections to close"); 47 | } 48 | } 49 | } 50 | 51 | async fn handle_request( 52 | req: Request, 53 | ) -> Result>, hyper::Error> { 54 | let body = req.collect().await.expect("Failed to read body").to_bytes(); 55 | assert!(!body.is_empty(), "empty body"); 56 | 57 | Ok(Response::new(full("finished"))) 58 | } 59 | 60 | fn full>(chunk: T) -> BoxBody { 61 | Full::new(chunk.into()) 62 | .map_err(|never| match never {}) 63 | .boxed() 64 | } 65 | 66 | #[tokio::test] 67 | async fn test_upload_timeout() { 68 | let addr = SocketAddr::from(([127, 0, 0, 1], 0)); 69 | let listener = TcpListener::bind(addr) 70 | .await 71 | .expect("Failed to bind listener"); 72 | let (shutdown_tx, shutdown_rx) = oneshot::channel(); 73 | 74 | let server_addr = listener.local_addr().unwrap(); 75 | 76 | let server_handle = task::spawn(spawn_test_server(listener, shutdown_rx)); 77 | 78 | let h = hyper_util::client::legacy::connect::HttpConnector::new(); 79 | let mut connector = TimeoutConnector::new(h); 80 | connector.set_read_timeout(Some(Duration::from_millis(5))); 81 | 82 | // comment this out and the test will fail 83 | connector.set_reset_reader_on_write(true); 84 | 85 | let client = Client::builder(hyper_util::rt::TokioExecutor::new()).build(connector); 86 | 87 | let body = vec![0; 10 * 1024 * 1024]; // 10MB 88 | let req = Request::post(format!("http://{}/", server_addr)) 89 | .body(full(body)) 90 | .expect("request builder"); 91 | 92 | let mut res = client.request(req).await.expect("request failed"); 93 | 94 | let mut resp_body = Vec::new(); 95 | while let Some(frame) = res.body_mut().frame().await { 96 | let bytes = frame 97 | .expect("frame error") 98 | .into_data() 99 | .map_err(|_| io::Error::new(io::ErrorKind::Other, "Error when consuming frame")) 100 | .expect("data error"); 101 | resp_body.extend_from_slice(&bytes); 102 | } 103 | 104 | assert_eq!(res.status(), 200); 105 | assert_eq!(resp_body, b"finished"); 106 | 107 | let _ = shutdown_tx.send(()); 108 | let _ = server_handle.await; 109 | } 110 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::future::Future; 2 | use std::io; 3 | use std::pin::Pin; 4 | use std::task::{Context, Poll}; 5 | use std::time::Duration; 6 | 7 | use hyper::rt::{Read, Write}; 8 | use tokio::time::timeout; 9 | 10 | use hyper::Uri; 11 | use hyper_util::client::legacy::connect::{Connected, Connection}; 12 | use tower_service::Service; 13 | 14 | mod stream; 15 | use stream::TimeoutStream; 16 | 17 | type BoxError = Box; 18 | 19 | /// A connector that enforces a connection timeout 20 | #[derive(Debug, Clone)] 21 | pub struct TimeoutConnector { 22 | /// A connector implementing the `Connect` trait 23 | connector: T, 24 | /// Amount of time to wait connecting 25 | connect_timeout: Option, 26 | /// Amount of time to wait reading response 27 | read_timeout: Option, 28 | /// Amount of time to wait writing request 29 | write_timeout: Option, 30 | /// If true, resets the reader timeout whenever a write occures 31 | reset_reader_on_write: bool, 32 | } 33 | 34 | impl TimeoutConnector 35 | where 36 | T: Service + Send, 37 | T::Response: Read + Write + Send + Unpin, 38 | T::Future: Send + 'static, 39 | T::Error: Into, 40 | { 41 | /// Construct a new TimeoutConnector with a given connector implementing the `Connect` trait 42 | pub fn new(connector: T) -> Self { 43 | TimeoutConnector { 44 | connector, 45 | connect_timeout: None, 46 | read_timeout: None, 47 | write_timeout: None, 48 | reset_reader_on_write: false, 49 | } 50 | } 51 | } 52 | 53 | impl Service for TimeoutConnector 54 | where 55 | T: Service + Send, 56 | T::Response: Read + Write + Connection + Send + Unpin, 57 | T::Future: Send + 'static, 58 | T::Error: Into, 59 | { 60 | type Response = Pin>>; 61 | type Error = BoxError; 62 | #[allow(clippy::type_complexity)] 63 | type Future = Pin> + Send>>; 64 | 65 | fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { 66 | self.connector.poll_ready(cx).map_err(Into::into) 67 | } 68 | 69 | fn call(&mut self, dst: Uri) -> Self::Future { 70 | let connect_timeout = self.connect_timeout; 71 | let read_timeout = self.read_timeout; 72 | let write_timeout = self.write_timeout; 73 | let reset_reader_on_write = self.reset_reader_on_write; 74 | let connecting = self.connector.call(dst); 75 | 76 | let fut = async move { 77 | let mut stream = match connect_timeout { 78 | None => { 79 | let io = connecting.await.map_err(Into::into)?; 80 | TimeoutStream::new(io) 81 | } 82 | Some(connect_timeout) => { 83 | let timeout = timeout(connect_timeout, connecting); 84 | let connecting = timeout 85 | .await 86 | .map_err(|e| io::Error::new(io::ErrorKind::TimedOut, e))?; 87 | let io = connecting.map_err(Into::into)?; 88 | TimeoutStream::new(io) 89 | } 90 | }; 91 | stream.set_read_timeout(read_timeout); 92 | stream.set_write_timeout(write_timeout); 93 | stream.set_reset_reader_on_write(reset_reader_on_write); 94 | Ok(Box::pin(stream)) 95 | }; 96 | 97 | Box::pin(fut) 98 | } 99 | } 100 | 101 | impl TimeoutConnector { 102 | /// Set the timeout for connecting to a URL. 103 | /// 104 | /// Default is no timeout. 105 | #[inline] 106 | pub fn set_connect_timeout(&mut self, val: Option) { 107 | self.connect_timeout = val; 108 | } 109 | 110 | /// Set the timeout for the response. 111 | /// 112 | /// Default is no timeout. 113 | #[inline] 114 | pub fn set_read_timeout(&mut self, val: Option) { 115 | self.read_timeout = val; 116 | } 117 | 118 | /// Set the timeout for the request. 119 | /// 120 | /// Default is no timeout. 121 | #[inline] 122 | pub fn set_write_timeout(&mut self, val: Option) { 123 | self.write_timeout = val; 124 | } 125 | 126 | /// Reset on the reader timeout on write 127 | /// 128 | /// This will reset the reader timeout when a write is done through the 129 | /// the TimeoutReader. This is useful when you don't want to trigger 130 | /// a reader timeout while writes are still be accepted. 131 | pub fn set_reset_reader_on_write(&mut self, reset: bool) { 132 | self.reset_reader_on_write = reset; 133 | } 134 | } 135 | 136 | impl Connection for TimeoutConnector 137 | where 138 | T: Read + Write + Connection + Service + Send + Unpin, 139 | T::Response: Read + Write + Send + Unpin, 140 | T::Future: Send + 'static, 141 | T::Error: Into, 142 | { 143 | fn connected(&self) -> Connected { 144 | self.connector.connected() 145 | } 146 | } 147 | 148 | #[cfg(test)] 149 | mod tests { 150 | use std::time::Duration; 151 | use std::{error::Error, io}; 152 | 153 | use http_body_util::Empty; 154 | use hyper::body::Bytes; 155 | use hyper_util::{ 156 | client::legacy::{connect::HttpConnector, Client}, 157 | rt::TokioExecutor, 158 | }; 159 | 160 | use super::TimeoutConnector; 161 | 162 | #[tokio::test] 163 | async fn test_timeout_connector() { 164 | // 10.255.255.1 is a not a routable IP address 165 | let url = "http://10.255.255.1".parse().unwrap(); 166 | 167 | let http = HttpConnector::new(); 168 | let mut connector = TimeoutConnector::new(http); 169 | connector.set_connect_timeout(Some(Duration::from_millis(1))); 170 | 171 | let client = Client::builder(TokioExecutor::new()).build::<_, Empty>(connector); 172 | 173 | let res = client.get(url).await; 174 | 175 | match res { 176 | Ok(_) => panic!("Expected a timeout"), 177 | Err(e) => { 178 | if let Some(io_e) = e.source().unwrap().downcast_ref::() { 179 | assert_eq!(io_e.kind(), io::ErrorKind::TimedOut); 180 | } else { 181 | panic!("Expected timeout error"); 182 | } 183 | } 184 | } 185 | } 186 | 187 | #[tokio::test] 188 | async fn test_read_timeout() { 189 | let url = "http://example.com".parse().unwrap(); 190 | 191 | let http = HttpConnector::new(); 192 | let mut connector = TimeoutConnector::new(http); 193 | // A 1 ms read timeout should be so short that we trigger a timeout error 194 | connector.set_read_timeout(Some(Duration::from_millis(1))); 195 | 196 | let client = Client::builder(TokioExecutor::new()).build::<_, Empty>(connector); 197 | 198 | let res = client.get(url).await; 199 | 200 | if let Err(client_e) = res { 201 | if let Some(hyper_e) = client_e.source() { 202 | if let Some(io_e) = hyper_e.source().unwrap().downcast_ref::() { 203 | return assert_eq!(io_e.kind(), io::ErrorKind::TimedOut); 204 | } 205 | } 206 | } 207 | panic!("Expected timeout error"); 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/stream.rs: -------------------------------------------------------------------------------- 1 | //! Wrappers for applying timeouts to IO operations. 2 | //! 3 | //! This used to depend on [tokio-io-timeout]. After Hyper 1.0 introduced hyper-specific IO traits, this was rewritten to use hyper IO traits instead of tokio IO traits. 4 | //! 5 | //! These timeouts are analogous to the read and write timeouts on traditional blocking sockets. A timeout countdown is 6 | //! initiated when a read/write operation returns [`Poll::Pending`]. If a read/write does not return successfully before 7 | //! the countdown expires, an [`io::Error`] with a kind of [`TimedOut`](io::ErrorKind::TimedOut) is returned. 8 | #![warn(missing_docs)] 9 | 10 | use hyper::rt::{Read, ReadBuf, ReadBufCursor, Write}; 11 | use hyper_util::client::legacy::connect::{Connected, Connection}; 12 | use pin_project_lite::pin_project; 13 | use std::future::Future; 14 | use std::io; 15 | use std::pin::Pin; 16 | use std::task::{ready, Context, Poll}; 17 | use std::time::Duration; 18 | use tokio::time::{sleep_until, Instant, Sleep}; 19 | 20 | pin_project! { 21 | #[derive(Debug)] 22 | struct TimeoutState { 23 | timeout: Option, 24 | #[pin] 25 | cur: Sleep, 26 | active: bool, 27 | } 28 | } 29 | 30 | impl TimeoutState { 31 | #[inline] 32 | fn new() -> TimeoutState { 33 | TimeoutState { 34 | timeout: None, 35 | cur: sleep_until(Instant::now()), 36 | active: false, 37 | } 38 | } 39 | 40 | #[inline] 41 | fn timeout(&self) -> Option { 42 | self.timeout 43 | } 44 | 45 | #[inline] 46 | fn set_timeout(&mut self, timeout: Option) { 47 | // since this takes &mut self, we can't yet be active 48 | self.timeout = timeout; 49 | } 50 | 51 | #[inline] 52 | fn set_timeout_pinned(mut self: Pin<&mut Self>, timeout: Option) { 53 | *self.as_mut().project().timeout = timeout; 54 | self.reset(); 55 | } 56 | 57 | #[inline] 58 | fn reset(self: Pin<&mut Self>) { 59 | let this = self.project(); 60 | 61 | if *this.active { 62 | *this.active = false; 63 | this.cur.reset(Instant::now()); 64 | } 65 | } 66 | 67 | #[inline] 68 | fn restart(self: Pin<&mut Self>) { 69 | let this = self.project(); 70 | 71 | if *this.active { 72 | let timeout = match this.timeout { 73 | Some(timeout) => *timeout, 74 | None => return, 75 | }; 76 | 77 | this.cur.reset(Instant::now() + timeout); 78 | } 79 | } 80 | 81 | #[inline] 82 | fn poll_check(self: Pin<&mut Self>, cx: &mut Context) -> io::Result<()> { 83 | let mut this = self.project(); 84 | 85 | let timeout = match this.timeout { 86 | Some(timeout) => *timeout, 87 | None => return Ok(()), 88 | }; 89 | 90 | if !*this.active { 91 | this.cur.as_mut().reset(Instant::now() + timeout); 92 | *this.active = true; 93 | } 94 | 95 | match this.cur.poll(cx) { 96 | Poll::Ready(()) => Err(io::Error::from(io::ErrorKind::TimedOut)), 97 | Poll::Pending => Ok(()), 98 | } 99 | } 100 | } 101 | 102 | pin_project! { 103 | /// An `hyper::rt::Read`er which applies a timeout to read operations. 104 | #[derive(Debug)] 105 | pub struct TimeoutReader { 106 | #[pin] 107 | reader: R, 108 | #[pin] 109 | state: TimeoutState, 110 | reset_on_write: bool, 111 | } 112 | } 113 | 114 | impl TimeoutReader 115 | where 116 | R: Read, 117 | { 118 | /// Returns a new `TimeoutReader` wrapping the specified reader. 119 | /// 120 | /// There is initially no timeout. 121 | pub fn new(reader: R) -> TimeoutReader { 122 | TimeoutReader { 123 | reader, 124 | state: TimeoutState::new(), 125 | reset_on_write: false, 126 | } 127 | } 128 | 129 | /// Returns the current read timeout. 130 | pub fn timeout(&self) -> Option { 131 | self.state.timeout() 132 | } 133 | 134 | /// Sets the read timeout. 135 | /// 136 | /// This can only be used before the reader is pinned; use [`set_timeout_pinned`](Self::set_timeout_pinned) 137 | /// otherwise. 138 | pub fn set_timeout(&mut self, timeout: Option) { 139 | self.state.set_timeout(timeout); 140 | } 141 | 142 | /// Sets the read timeout. 143 | /// 144 | /// This will reset any pending timeout. Use [`set_timeout`](Self::set_timeout) instead if the reader is not yet 145 | /// pinned. 146 | pub fn set_timeout_pinned(self: Pin<&mut Self>, timeout: Option) { 147 | self.project().state.set_timeout_pinned(timeout); 148 | } 149 | 150 | /// Returns a shared reference to the inner reader. 151 | pub fn get_ref(&self) -> &R { 152 | &self.reader 153 | } 154 | 155 | /// Returns a mutable reference to the inner reader. 156 | pub fn get_mut(&mut self) -> &mut R { 157 | &mut self.reader 158 | } 159 | 160 | /// Returns a pinned mutable reference to the inner reader. 161 | pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut R> { 162 | self.project().reader 163 | } 164 | 165 | /// Consumes the `TimeoutReader`, returning the inner reader. 166 | pub fn into_inner(self) -> R { 167 | self.reader 168 | } 169 | } 170 | 171 | impl TimeoutReader 172 | where 173 | R: Read + Write, 174 | { 175 | /// Reset on the reader timeout on write 176 | /// 177 | /// This will reset the reader timeout when a write is done through the 178 | /// the TimeoutReader. This is useful when you don't want to trigger 179 | /// a reader timeout while writes are still be accepted. 180 | pub fn set_reset_on_write(&mut self, reset: bool) { 181 | self.reset_on_write = reset 182 | } 183 | } 184 | 185 | impl Read for TimeoutReader 186 | where 187 | R: Read, 188 | { 189 | fn poll_read( 190 | self: Pin<&mut Self>, 191 | cx: &mut Context, 192 | buf: ReadBufCursor, 193 | ) -> Poll> { 194 | let this = self.project(); 195 | let r = this.reader.poll_read(cx, buf); 196 | match r { 197 | Poll::Pending => this.state.poll_check(cx)?, 198 | _ => this.state.reset(), 199 | } 200 | r 201 | } 202 | } 203 | 204 | impl Write for TimeoutReader 205 | where 206 | R: Write, 207 | { 208 | fn poll_write( 209 | self: Pin<&mut Self>, 210 | cx: &mut Context, 211 | buf: &[u8], 212 | ) -> Poll> { 213 | let this = self.project(); 214 | let r = this.reader.poll_write(cx, buf); 215 | if *this.reset_on_write && r.is_ready() { 216 | this.state.restart(); 217 | } 218 | r 219 | } 220 | 221 | fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { 222 | let this = self.project(); 223 | let r = this.reader.poll_flush(cx); 224 | if *this.reset_on_write && r.is_ready() { 225 | this.state.restart(); 226 | } 227 | r 228 | } 229 | 230 | fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { 231 | let this = self.project(); 232 | let r = this.reader.poll_shutdown(cx); 233 | if *this.reset_on_write && r.is_ready() { 234 | this.state.restart(); 235 | } 236 | r 237 | } 238 | 239 | fn poll_write_vectored( 240 | self: Pin<&mut Self>, 241 | cx: &mut Context, 242 | bufs: &[io::IoSlice], 243 | ) -> Poll> { 244 | let this = self.project(); 245 | let r = this.reader.poll_write_vectored(cx, bufs); 246 | if *this.reset_on_write && r.is_ready() { 247 | this.state.restart(); 248 | } 249 | r 250 | } 251 | 252 | fn is_write_vectored(&self) -> bool { 253 | self.reader.is_write_vectored() 254 | } 255 | } 256 | 257 | pin_project! { 258 | /// An `hyper::rt::Write`er which applies a timeout to write operations. 259 | #[derive(Debug)] 260 | pub struct TimeoutWriter { 261 | #[pin] 262 | writer: W, 263 | #[pin] 264 | state: TimeoutState, 265 | } 266 | } 267 | 268 | impl TimeoutWriter 269 | where 270 | W: Write, 271 | { 272 | /// Returns a new `TimeoutReader` wrapping the specified reader. 273 | /// 274 | /// There is initially no timeout. 275 | pub fn new(writer: W) -> TimeoutWriter { 276 | TimeoutWriter { 277 | writer, 278 | state: TimeoutState::new(), 279 | } 280 | } 281 | 282 | /// Returns the current write timeout. 283 | pub fn timeout(&self) -> Option { 284 | self.state.timeout() 285 | } 286 | 287 | /// Sets the write timeout. 288 | /// 289 | /// This can only be used before the writer is pinned; use [`set_timeout_pinned`](Self::set_timeout_pinned) 290 | /// otherwise. 291 | pub fn set_timeout(&mut self, timeout: Option) { 292 | self.state.set_timeout(timeout); 293 | } 294 | 295 | /// Sets the write timeout. 296 | /// 297 | /// This will reset any pending timeout. Use [`set_timeout`](Self::set_timeout) instead if the reader is not yet 298 | /// pinned. 299 | pub fn set_timeout_pinned(self: Pin<&mut Self>, timeout: Option) { 300 | self.project().state.set_timeout_pinned(timeout); 301 | } 302 | 303 | /// Returns a shared reference to the inner writer. 304 | pub fn get_ref(&self) -> &W { 305 | &self.writer 306 | } 307 | 308 | /// Returns a mutable reference to the inner writer. 309 | pub fn get_mut(&mut self) -> &mut W { 310 | &mut self.writer 311 | } 312 | 313 | /// Returns a pinned mutable reference to the inner writer. 314 | pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut W> { 315 | self.project().writer 316 | } 317 | 318 | /// Consumes the `TimeoutWriter`, returning the inner writer. 319 | pub fn into_inner(self) -> W { 320 | self.writer 321 | } 322 | } 323 | 324 | impl Write for TimeoutWriter 325 | where 326 | W: Write, 327 | { 328 | fn poll_write( 329 | self: Pin<&mut Self>, 330 | cx: &mut Context, 331 | buf: &[u8], 332 | ) -> Poll> { 333 | let this = self.project(); 334 | let r = this.writer.poll_write(cx, buf); 335 | match r { 336 | Poll::Pending => this.state.poll_check(cx)?, 337 | _ => this.state.reset(), 338 | } 339 | r 340 | } 341 | 342 | fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { 343 | let this = self.project(); 344 | let r = this.writer.poll_flush(cx); 345 | match r { 346 | Poll::Pending => this.state.poll_check(cx)?, 347 | _ => this.state.reset(), 348 | } 349 | r 350 | } 351 | 352 | fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { 353 | let this = self.project(); 354 | let r = this.writer.poll_shutdown(cx); 355 | match r { 356 | Poll::Pending => this.state.poll_check(cx)?, 357 | _ => this.state.reset(), 358 | } 359 | r 360 | } 361 | 362 | fn poll_write_vectored( 363 | self: Pin<&mut Self>, 364 | cx: &mut Context, 365 | bufs: &[io::IoSlice], 366 | ) -> Poll> { 367 | let this = self.project(); 368 | let r = this.writer.poll_write_vectored(cx, bufs); 369 | match r { 370 | Poll::Pending => this.state.poll_check(cx)?, 371 | _ => this.state.reset(), 372 | } 373 | r 374 | } 375 | 376 | fn is_write_vectored(&self) -> bool { 377 | self.writer.is_write_vectored() 378 | } 379 | } 380 | 381 | impl Read for TimeoutWriter 382 | where 383 | W: Read, 384 | { 385 | fn poll_read( 386 | self: Pin<&mut Self>, 387 | cx: &mut Context, 388 | buf: ReadBufCursor, 389 | ) -> Poll> { 390 | self.project().writer.poll_read(cx, buf) 391 | } 392 | } 393 | 394 | pin_project! { 395 | /// A stream which applies read and write timeouts to an inner stream. 396 | #[derive(Debug)] 397 | pub struct TimeoutStream { 398 | #[pin] 399 | stream: TimeoutReader> 400 | } 401 | } 402 | 403 | impl TimeoutStream 404 | where 405 | S: Read + Write, 406 | { 407 | /// Returns a new `TimeoutStream` wrapping the specified stream. 408 | /// 409 | /// There is initially no read or write timeout. 410 | pub fn new(stream: S) -> TimeoutStream { 411 | let writer = TimeoutWriter::new(stream); 412 | let stream = TimeoutReader::new(writer); 413 | TimeoutStream { stream } 414 | } 415 | 416 | /// Returns the current read timeout. 417 | pub fn read_timeout(&self) -> Option { 418 | self.stream.timeout() 419 | } 420 | 421 | /// Sets the read timeout. 422 | /// 423 | /// This can only be used before the stream is pinned; use 424 | /// [`set_read_timeout_pinned`](Self::set_read_timeout_pinned) otherwise. 425 | pub fn set_read_timeout(&mut self, timeout: Option) { 426 | self.stream.set_timeout(timeout) 427 | } 428 | 429 | /// Sets the read timeout. 430 | /// 431 | /// This will reset any pending read timeout. Use [`set_read_timeout`](Self::set_read_timeout) instead if the stream 432 | /// has not yet been pinned. 433 | pub fn set_read_timeout_pinned(self: Pin<&mut Self>, timeout: Option) { 434 | self.project().stream.set_timeout_pinned(timeout) 435 | } 436 | 437 | /// Returns the current write timeout. 438 | pub fn write_timeout(&self) -> Option { 439 | self.stream.get_ref().timeout() 440 | } 441 | 442 | /// Sets the write timeout. 443 | /// 444 | /// This can only be used before the stream is pinned; use 445 | /// [`set_write_timeout_pinned`](Self::set_write_timeout_pinned) otherwise. 446 | pub fn set_write_timeout(&mut self, timeout: Option) { 447 | self.stream.get_mut().set_timeout(timeout) 448 | } 449 | 450 | /// Sets the write timeout. 451 | /// 452 | /// This will reset any pending write timeout. Use [`set_write_timeout`](Self::set_write_timeout) instead if the 453 | /// stream has not yet been pinned. 454 | pub fn set_write_timeout_pinned(self: Pin<&mut Self>, timeout: Option) { 455 | self.project() 456 | .stream 457 | .get_pin_mut() 458 | .set_timeout_pinned(timeout) 459 | } 460 | 461 | /// Reset on the reader timeout on write 462 | /// 463 | /// This will reset the reader timeout when a write is done through the 464 | /// the TimeoutReader. This is useful when you don't want to trigger 465 | /// a reader timeout while writes are still be accepted. 466 | pub fn set_reset_reader_on_write(&mut self, reset: bool) { 467 | self.stream.set_reset_on_write(reset); 468 | } 469 | 470 | /// Returns a shared reference to the inner stream. 471 | pub fn get_ref(&self) -> &S { 472 | self.stream.get_ref().get_ref() 473 | } 474 | 475 | /// Returns a mutable reference to the inner stream. 476 | pub fn get_mut(&mut self) -> &mut S { 477 | self.stream.get_mut().get_mut() 478 | } 479 | 480 | /// Returns a pinned mutable reference to the inner stream. 481 | pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut S> { 482 | self.project().stream.get_pin_mut().get_pin_mut() 483 | } 484 | 485 | /// Consumes the stream, returning the inner stream. 486 | pub fn into_inner(self) -> S { 487 | self.stream.into_inner().into_inner() 488 | } 489 | } 490 | 491 | impl Read for TimeoutStream 492 | where 493 | S: Read + Write, 494 | { 495 | fn poll_read( 496 | self: Pin<&mut Self>, 497 | cx: &mut Context, 498 | buf: ReadBufCursor, 499 | ) -> Poll> { 500 | self.project().stream.poll_read(cx, buf) 501 | } 502 | } 503 | 504 | impl Write for TimeoutStream 505 | where 506 | S: Read + Write, 507 | { 508 | fn poll_write( 509 | self: Pin<&mut Self>, 510 | cx: &mut Context, 511 | buf: &[u8], 512 | ) -> Poll> { 513 | self.project().stream.poll_write(cx, buf) 514 | } 515 | 516 | fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { 517 | self.project().stream.poll_flush(cx) 518 | } 519 | 520 | fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { 521 | self.project().stream.poll_shutdown(cx) 522 | } 523 | 524 | fn poll_write_vectored( 525 | self: Pin<&mut Self>, 526 | cx: &mut Context, 527 | bufs: &[io::IoSlice], 528 | ) -> Poll> { 529 | self.project().stream.poll_write_vectored(cx, bufs) 530 | } 531 | 532 | fn is_write_vectored(&self) -> bool { 533 | self.stream.is_write_vectored() 534 | } 535 | } 536 | 537 | impl Connection for TimeoutStream 538 | where 539 | S: Read + Write + Connection + Unpin, 540 | { 541 | fn connected(&self) -> Connected { 542 | self.get_ref().connected() 543 | } 544 | } 545 | 546 | impl Connection for Pin>> 547 | where 548 | S: Read + Write + Connection + Unpin, 549 | { 550 | fn connected(&self) -> Connected { 551 | self.get_ref().connected() 552 | } 553 | } 554 | 555 | pin_project! { 556 | /// A future which can be used to easily read available number of bytes to fill 557 | /// a buffer. Based on the internal [tokio::io::util::read::Read] 558 | struct ReadFut<'a, R: ?Sized> { 559 | reader: &'a mut R, 560 | buf: &'a mut [u8], 561 | } 562 | } 563 | 564 | /// Tries to read some bytes directly into the given `buf` in asynchronous 565 | /// manner, returning a future type. 566 | /// 567 | /// The returned future will resolve to both the I/O stream and the buffer 568 | /// as well as the number of bytes read once the read operation is completed. 569 | #[cfg(test)] 570 | fn read<'a, R>(reader: &'a mut R, buf: &'a mut [u8]) -> ReadFut<'a, R> 571 | where 572 | R: Read + Unpin + ?Sized, 573 | { 574 | ReadFut { reader, buf } 575 | } 576 | 577 | impl Future for ReadFut<'_, R> 578 | where 579 | R: Read + Unpin + ?Sized, 580 | { 581 | type Output = io::Result; 582 | 583 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 584 | let me = self.project(); 585 | let mut buf = ReadBuf::new(me.buf); 586 | ready!(Pin::new(me.reader).poll_read(cx, buf.unfilled()))?; 587 | Poll::Ready(Ok(buf.filled().len())) 588 | } 589 | } 590 | 591 | #[cfg(test)] 592 | trait ReadExt: Read { 593 | /// Pulls some bytes from this source into the specified buffer, 594 | /// returning how many bytes were read. 595 | fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadFut<'a, Self> 596 | where 597 | Self: Unpin, 598 | { 599 | read(self, buf) 600 | } 601 | } 602 | 603 | pin_project! { 604 | /// A future to write some of the buffer to an `AsyncWrite`.- 605 | struct WriteFut<'a, W: ?Sized> { 606 | writer: &'a mut W, 607 | buf: &'a [u8], 608 | } 609 | } 610 | 611 | /// Tries to write some bytes from the given `buf` to the writer in an 612 | /// asynchronous manner, returning a future. 613 | #[cfg(test)] 614 | fn write<'a, W>(writer: &'a mut W, buf: &'a [u8]) -> WriteFut<'a, W> 615 | where 616 | W: Write + Unpin + ?Sized, 617 | { 618 | WriteFut { writer, buf } 619 | } 620 | 621 | impl Future for WriteFut<'_, W> 622 | where 623 | W: Write + Unpin + ?Sized, 624 | { 625 | type Output = io::Result; 626 | 627 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 628 | let me = self.project(); 629 | Pin::new(&mut *me.writer).poll_write(cx, me.buf) 630 | } 631 | } 632 | 633 | #[cfg(test)] 634 | trait WriteExt: Write { 635 | /// Writes a buffer into this writer, returning how many bytes were 636 | /// written. 637 | fn write<'a>(&'a mut self, src: &'a [u8]) -> WriteFut<'a, Self> 638 | where 639 | Self: Unpin, 640 | { 641 | write(self, src) 642 | } 643 | } 644 | 645 | #[cfg(test)] 646 | impl ReadExt for Pin<&mut TimeoutReader> 647 | where 648 | R: Read, 649 | { 650 | fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadFut<'a, Self> { 651 | read(self, buf) 652 | } 653 | } 654 | 655 | #[cfg(test)] 656 | impl WriteExt for Pin<&mut TimeoutWriter> 657 | where 658 | W: Write, 659 | { 660 | fn write<'a>(&'a mut self, src: &'a [u8]) -> WriteFut<'a, Self> { 661 | write(self, src) 662 | } 663 | } 664 | 665 | #[cfg(test)] 666 | impl ReadExt for Pin<&mut TimeoutStream> 667 | where 668 | S: Read + Write, 669 | { 670 | fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadFut<'a, Self> { 671 | read(self, buf) 672 | } 673 | } 674 | 675 | #[cfg(test)] 676 | impl WriteExt for Pin<&mut TimeoutStream> 677 | where 678 | S: Read + Write, 679 | { 680 | fn write<'a>(&'a mut self, src: &'a [u8]) -> WriteFut<'a, Self> { 681 | write(self, src) 682 | } 683 | } 684 | 685 | #[cfg(test)] 686 | mod test { 687 | use super::*; 688 | use hyper_util::rt::TokioIo; 689 | use std::io::Write; 690 | use std::net::TcpListener; 691 | use std::thread; 692 | use tokio::net::TcpStream; 693 | use tokio::pin; 694 | 695 | pin_project! { 696 | struct DelayStream { 697 | #[pin] 698 | sleep: Sleep, 699 | } 700 | } 701 | 702 | impl DelayStream { 703 | fn new(until: Instant) -> Self { 704 | DelayStream { 705 | sleep: sleep_until(until), 706 | } 707 | } 708 | } 709 | 710 | impl Read for DelayStream { 711 | fn poll_read( 712 | self: Pin<&mut Self>, 713 | cx: &mut Context, 714 | _buf: ReadBufCursor, 715 | ) -> Poll> { 716 | match self.project().sleep.poll(cx) { 717 | Poll::Ready(()) => Poll::Ready(Ok(())), 718 | Poll::Pending => Poll::Pending, 719 | } 720 | } 721 | } 722 | 723 | impl hyper::rt::Write for DelayStream { 724 | fn poll_write( 725 | self: Pin<&mut Self>, 726 | cx: &mut Context, 727 | buf: &[u8], 728 | ) -> Poll> { 729 | match self.project().sleep.poll(cx) { 730 | Poll::Ready(()) => Poll::Ready(Ok(buf.len())), 731 | Poll::Pending => Poll::Pending, 732 | } 733 | } 734 | 735 | fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context) -> Poll> { 736 | Poll::Ready(Ok(())) 737 | } 738 | 739 | fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context) -> Poll> { 740 | Poll::Ready(Ok(())) 741 | } 742 | } 743 | 744 | #[tokio::test] 745 | async fn read_timeout() { 746 | let reader = DelayStream::new(Instant::now() + Duration::from_millis(500)); 747 | let mut reader = TimeoutReader::new(reader); 748 | reader.set_timeout(Some(Duration::from_millis(100))); 749 | pin!(reader); 750 | 751 | let r = reader.read(&mut [0, 1, 2]).await; 752 | assert_eq!(r.err().unwrap().kind(), io::ErrorKind::TimedOut); 753 | } 754 | 755 | #[tokio::test] 756 | async fn read_ok() { 757 | let reader = DelayStream::new(Instant::now() + Duration::from_millis(100)); 758 | let mut reader = TimeoutReader::new(reader); 759 | reader.set_timeout(Some(Duration::from_millis(500))); 760 | pin!(reader); 761 | 762 | reader.read(&mut [0]).await.unwrap(); 763 | } 764 | 765 | #[tokio::test] 766 | async fn write_timeout() { 767 | let writer = DelayStream::new(Instant::now() + Duration::from_millis(500)); 768 | let mut writer = TimeoutWriter::new(writer); 769 | writer.set_timeout(Some(Duration::from_millis(100))); 770 | pin!(writer); 771 | 772 | let r = writer.write(&[0]).await; 773 | assert_eq!(r.err().unwrap().kind(), io::ErrorKind::TimedOut); 774 | } 775 | 776 | #[tokio::test] 777 | async fn write_ok() { 778 | let writer = DelayStream::new(Instant::now() + Duration::from_millis(100)); 779 | let mut writer = TimeoutWriter::new(writer); 780 | writer.set_timeout(Some(Duration::from_millis(500))); 781 | pin!(writer); 782 | 783 | writer.write(&[0]).await.unwrap(); 784 | } 785 | 786 | #[tokio::test] 787 | async fn tcp_read() { 788 | let listener = TcpListener::bind("127.0.0.1:0").unwrap(); 789 | let addr = listener.local_addr().unwrap(); 790 | 791 | thread::spawn(move || { 792 | let mut socket = listener.accept().unwrap().0; 793 | thread::sleep(Duration::from_millis(10)); 794 | socket.write_all(b"f").unwrap(); 795 | thread::sleep(Duration::from_millis(500)); 796 | let _ = socket.write_all(b"f"); // this may hit an eof 797 | }); 798 | 799 | let s = TcpStream::connect(&addr).await.unwrap(); 800 | let s = TokioIo::new(s); 801 | let mut s = TimeoutStream::new(s); 802 | s.set_read_timeout(Some(Duration::from_millis(100))); 803 | pin!(s); 804 | s.read(&mut [0]).await.unwrap(); 805 | let r = s.read(&mut [0]).await; 806 | 807 | match r { 808 | Ok(_) => panic!("unexpected success"), 809 | Err(ref e) if e.kind() == io::ErrorKind::TimedOut => (), 810 | Err(e) => panic!("{:?}", e), 811 | } 812 | } 813 | } 814 | --------------------------------------------------------------------------------