Skip to content

Commit a8b5029

Browse files
committed
feat(client): add capture_connection
Add `capture_connection` functionality. This allows callers to retrieve the `Connected` struct of the connection that was used internally by Hyper. This is in service of #2605. Although this uses `http::Extensions` under the hood, the API exposed explicitly hides that detail.
1 parent 40c01df commit a8b5029

File tree

3 files changed

+226
-6
lines changed

3 files changed

+226
-6
lines changed

src/client/client.rs

+11-4
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,21 @@ use http::uri::{Port, Scheme};
1010
use http::{Method, Request, Response, Uri, Version};
1111
use tracing::{debug, trace, warn};
1212

13+
use crate::body::{Body, HttpBody};
14+
use crate::client::connect::CaptureConnectionExtension;
15+
use crate::common::{
16+
exec::BoxSendFuture, lazy as hyper_lazy, sync_wrapper::SyncWrapper, task, Future, Lazy, Pin,
17+
Poll,
18+
};
19+
use crate::rt::Executor;
20+
1321
use super::conn;
1422
use super::connect::{self, sealed::Connect, Alpn, Connected, Connection};
1523
use super::pool::{
1624
self, CheckoutIsClosedError, Key as PoolKey, Pool, Poolable, Pooled, Reservation,
1725
};
1826
#[cfg(feature = "tcp")]
1927
use super::HttpConnector;
20-
use crate::body::{Body, HttpBody};
21-
use crate::common::{exec::BoxSendFuture, sync_wrapper::SyncWrapper, lazy as hyper_lazy, task, Future, Lazy, Pin, Poll};
22-
use crate::rt::Executor;
2328

2429
/// A Client to make outgoing HTTP requests.
2530
///
@@ -238,7 +243,9 @@ where
238243
})
239244
}
240245
};
241-
246+
req.extensions_mut()
247+
.get_mut::<CaptureConnectionExtension>()
248+
.map(|conn| conn.set(&pooled.conn_info));
242249
if pooled.is_http1() {
243250
if req.version() == Version::HTTP_2 {
244251
warn!("Connection is HTTP/1, but request requires HTTP/2");

src/client/connect/mod.rs

+180-1
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,11 @@
8080
//! [`AsyncWrite`]: tokio::io::AsyncWrite
8181
//! [`Connection`]: Connection
8282
use std::fmt;
83+
use std::ops::Deref;
84+
use std::sync::Arc;
8385

8486
use ::http::Extensions;
87+
use tokio::sync::watch;
8588

8689
cfg_feature! {
8790
#![feature = "tcp"]
@@ -115,6 +118,114 @@ pub struct Connected {
115118
pub(super) extra: Option<Extra>,
116119
}
117120

121+
/// [`CaptureConnection`] allows callers to capture [`Connected`] information
122+
///
123+
/// To capture a connection for a request, use [`capture_connection`].
124+
#[derive(Debug, Clone)]
125+
pub struct CaptureConnection {
126+
rx: watch::Receiver<Option<Connected>>,
127+
}
128+
129+
/// Capture the connection for a given request
130+
///
131+
/// When making a request with Hyper, the underlying connection must implement the [`Connection`] trait.
132+
/// [`capture_connection`] allows a caller to capture the returned [`Connected`] structure as soon
133+
/// as the connection is established.
134+
///
135+
/// *Note*: If establishing a connection fails, [`CaptureConnection::connection_metadata`] will always return none.
136+
///
137+
/// # Examples
138+
///
139+
/// **Synchronous access**:
140+
/// The [`CaptureConnection::connection_metadata`] method allows callers to check if a connection has been
141+
/// established. This is ideal for situations where you are certain the connection has already
142+
/// been established (e.g. after the response future has already completed).
143+
/// ```rust
144+
/// use hyper::client::connect::{capture_connection, CaptureConnection};
145+
/// let mut request = http::Request::builder()
146+
/// .uri("http://foo.com")
147+
/// .body(())
148+
/// .unwrap();
149+
///
150+
/// let captured_connection = capture_connection(&mut request);
151+
/// // some time later after the request has been sent...
152+
/// let connection_info = captured_connection.connection_metadata();
153+
/// println!("we are connected! {:?}", connection_info.as_ref());
154+
/// ```
155+
///
156+
/// **Asynchronous access**:
157+
/// The [`CaptureConnection::wait_for_connection_metadata`] method returns a future resolves as soon as the
158+
/// connection is available.
159+
///
160+
/// ```rust
161+
/// # #[cfg(feature = "runtime")]
162+
/// # async fn example() {
163+
/// use hyper::client::connect::{capture_connection, CaptureConnection};
164+
/// let mut request = http::Request::builder()
165+
/// .uri("http://foo.com")
166+
/// .body(hyper::Body::empty())
167+
/// .unwrap();
168+
///
169+
/// let mut captured = capture_connection(&mut request);
170+
/// tokio::task::spawn(async move {
171+
/// let connection_info = captured.wait_for_connection_metadata().await;
172+
/// println!("we are connected! {:?}", connection_info.as_ref());
173+
/// });
174+
///
175+
/// let client = hyper::Client::new();
176+
/// client.request(request).await.expect("request failed");
177+
/// # }
178+
/// ```
179+
pub fn capture_connection<B>(request: &mut crate::http::Request<B>) -> CaptureConnection {
180+
let (tx, rx) = CaptureConnection::new();
181+
request.extensions_mut().insert(tx);
182+
rx
183+
}
184+
185+
/// TxSide for [`CaptureConnection`]
186+
///
187+
/// This is inserted into `Extensions` to allow Hyper to back channel connection info
188+
#[derive(Clone)]
189+
pub(crate) struct CaptureConnectionExtension {
190+
tx: Arc<watch::Sender<Option<Connected>>>,
191+
}
192+
193+
impl CaptureConnectionExtension {
194+
pub(crate) fn set(&self, connected: &Connected) {
195+
self.tx.send_replace(Some(connected.clone()));
196+
}
197+
}
198+
199+
impl CaptureConnection {
200+
/// Internal API to create the tx and rx half of [`CaptureConnection`]
201+
pub(crate) fn new() -> (CaptureConnectionExtension, Self) {
202+
let (tx, rx) = watch::channel(None);
203+
(
204+
CaptureConnectionExtension { tx: Arc::new(tx) },
205+
CaptureConnection { rx },
206+
)
207+
}
208+
209+
/// Retrieve the connection metadata, if available
210+
pub fn connection_metadata(&self) -> impl Deref<Target = Option<Connected>> + '_ {
211+
self.rx.borrow()
212+
}
213+
214+
/// Wait for the connection to be established
215+
///
216+
/// If a connection was established, this will always return `Some(...)`. If the request never
217+
/// successfully connected (e.g. DNS resolution failure), this method will never return.
218+
pub async fn wait_for_connection_metadata(
219+
&mut self,
220+
) -> impl Deref<Target = Option<Connected>> + '_ {
221+
if self.rx.borrow().is_some() {
222+
return self.rx.borrow();
223+
}
224+
let _ = self.rx.changed().await;
225+
self.rx.borrow()
226+
}
227+
}
228+
118229
pub(super) struct Extra(Box<dyn ExtraInner>);
119230

120231
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -191,7 +302,6 @@ impl Connected {
191302

192303
// Don't public expose that `Connected` is `Clone`, unsure if we want to
193304
// keep that contract...
194-
#[cfg(feature = "http2")]
195305
pub(super) fn clone(&self) -> Connected {
196306
Connected {
197307
alpn: self.alpn.clone(),
@@ -351,6 +461,7 @@ pub(super) mod sealed {
351461
#[cfg(test)]
352462
mod tests {
353463
use super::Connected;
464+
use crate::client::connect::CaptureConnection;
354465

355466
#[derive(Clone, Debug, PartialEq)]
356467
struct Ex1(usize);
@@ -409,4 +520,72 @@ mod tests {
409520
assert_eq!(ex2.get::<Ex1>(), Some(&Ex1(99)));
410521
assert_eq!(ex2.get::<Ex2>(), Some(&Ex2("hiccup")));
411522
}
523+
524+
#[test]
525+
fn test_sync_capture_connection() {
526+
let (tx, rx) = CaptureConnection::new();
527+
assert!(
528+
rx.connection_metadata().is_none(),
529+
"connection has not been set"
530+
);
531+
tx.set(&Connected::new().proxy(true));
532+
assert_eq!(
533+
rx.connection_metadata()
534+
.as_ref()
535+
.expect("connected should be set")
536+
.is_proxied(),
537+
true
538+
);
539+
540+
// ensure it can be called multiple times
541+
assert_eq!(
542+
rx.connection_metadata()
543+
.as_ref()
544+
.expect("connected should be set")
545+
.is_proxied(),
546+
true
547+
);
548+
}
549+
550+
#[tokio::test]
551+
async fn async_capture_connection() {
552+
let (tx, mut rx) = CaptureConnection::new();
553+
assert!(
554+
rx.connection_metadata().is_none(),
555+
"connection has not been set"
556+
);
557+
let test_task = tokio::spawn(async move {
558+
assert_eq!(
559+
rx.wait_for_connection_metadata()
560+
.await
561+
.as_ref()
562+
.expect("connection should be set")
563+
.is_proxied(),
564+
true
565+
);
566+
// can be awaited multiple times
567+
assert!(
568+
rx.wait_for_connection_metadata().await.is_some(),
569+
"should be awaitable multiple times"
570+
);
571+
572+
assert_eq!(rx.connection_metadata().is_some(), true);
573+
});
574+
// can't be finished, we haven't set the connection yet
575+
assert_eq!(test_task.is_finished(), false);
576+
tx.set(&Connected::new().proxy(true));
577+
578+
assert!(test_task.await.is_ok());
579+
}
580+
581+
#[tokio::test]
582+
async fn capture_connection_sender_side_dropped() {
583+
let (tx, mut rx) = CaptureConnection::new();
584+
assert!(
585+
rx.connection_metadata().is_none(),
586+
"connection has not been set"
587+
);
588+
drop(tx);
589+
assert!(rx.wait_for_connection_metadata().await.is_none());
590+
}
412591
}

tests/client.rs

+35-1
Original file line numberDiff line numberDiff line change
@@ -1121,10 +1121,11 @@ mod dispatch_impl {
11211121
use http::Uri;
11221122
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
11231123
use tokio::net::TcpStream;
1124+
use tokio_test::block_on;
11241125

11251126
use super::support;
11261127
use hyper::body::HttpBody;
1127-
use hyper::client::connect::{Connected, Connection, HttpConnector};
1128+
use hyper::client::connect::{capture_connection, Connected, Connection, HttpConnector};
11281129
use hyper::Client;
11291130

11301131
#[test]
@@ -1533,6 +1534,39 @@ mod dispatch_impl {
15331534
assert_eq!(connects.load(Ordering::Relaxed), 0);
15341535
}
15351536

1537+
#[test]
1538+
fn capture_connection_on_client() {
1539+
// We especially don't want connects() triggered if there's
1540+
// idle connections that the Checkout would have found
1541+
let _ = pretty_env_logger::try_init();
1542+
1543+
let _rt = support::runtime();
1544+
let connector = DebugConnector::new();
1545+
1546+
let client = Client::builder().build(connector);
1547+
1548+
let server = TcpListener::bind("127.0.0.1:0").unwrap();
1549+
let addr = server.local_addr().unwrap();
1550+
thread::spawn(move || {
1551+
let mut sock = server.accept().unwrap().0;
1552+
//drop(server);
1553+
sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
1554+
sock.set_write_timeout(Some(Duration::from_secs(5)))
1555+
.unwrap();
1556+
let mut buf = [0; 4096];
1557+
sock.read(&mut buf).expect("read 1");
1558+
sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
1559+
.expect("write 1");
1560+
});
1561+
let mut req = Request::builder()
1562+
.uri(&*format!("http://{}/a", addr))
1563+
.body(Body::empty())
1564+
.unwrap();
1565+
let captured_conn = capture_connection(&mut req);
1566+
block_on(client.request(req)).expect("200 OK");
1567+
assert!(captured_conn.connection_metadata().is_some());
1568+
}
1569+
15361570
#[test]
15371571
fn client_keep_alive_0() {
15381572
let _ = pretty_env_logger::try_init();

0 commit comments

Comments
 (0)