|
80 | 80 | //! [`AsyncWrite`]: tokio::io::AsyncWrite
|
81 | 81 | //! [`Connection`]: Connection
|
82 | 82 | use std::fmt;
|
| 83 | +use std::ops::Deref; |
| 84 | +use std::sync::Arc; |
83 | 85 |
|
84 | 86 | use ::http::Extensions;
|
| 87 | +use tokio::sync::watch; |
85 | 88 |
|
86 | 89 | cfg_feature! {
|
87 | 90 | #![feature = "tcp"]
|
@@ -115,6 +118,114 @@ pub struct Connected {
|
115 | 118 | pub(super) extra: Option<Extra>,
|
116 | 119 | }
|
117 | 120 |
|
| 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 | + |
118 | 229 | pub(super) struct Extra(Box<dyn ExtraInner>);
|
119 | 230 |
|
120 | 231 | #[derive(Clone, Copy, Debug, PartialEq)]
|
@@ -191,7 +302,6 @@ impl Connected {
|
191 | 302 |
|
192 | 303 | // Don't public expose that `Connected` is `Clone`, unsure if we want to
|
193 | 304 | // keep that contract...
|
194 |
| - #[cfg(feature = "http2")] |
195 | 305 | pub(super) fn clone(&self) -> Connected {
|
196 | 306 | Connected {
|
197 | 307 | alpn: self.alpn.clone(),
|
@@ -351,6 +461,7 @@ pub(super) mod sealed {
|
351 | 461 | #[cfg(test)]
|
352 | 462 | mod tests {
|
353 | 463 | use super::Connected;
|
| 464 | + use crate::client::connect::CaptureConnection; |
354 | 465 |
|
355 | 466 | #[derive(Clone, Debug, PartialEq)]
|
356 | 467 | struct Ex1(usize);
|
@@ -409,4 +520,72 @@ mod tests {
|
409 | 520 | assert_eq!(ex2.get::<Ex1>(), Some(&Ex1(99)));
|
410 | 521 | assert_eq!(ex2.get::<Ex2>(), Some(&Ex2("hiccup")));
|
411 | 522 | }
|
| 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 | + } |
412 | 591 | }
|
0 commit comments