|
| 1 | +use std::{future::Future, pin::Pin}; |
| 2 | + |
| 3 | +use tokio::sync::{Mutex, MutexGuard, Notify, futures::Notified}; |
| 4 | + |
| 5 | +#[derive(Default)] |
| 6 | +pub(super) struct ProbeControl { |
| 7 | + running: Mutex<()>, |
| 8 | + cancelled: Notify, |
| 9 | +} |
| 10 | + |
| 11 | +impl ProbeControl { |
| 12 | + pub(super) fn try_start(&self) -> Option<ActiveProbe<'_>> { |
| 13 | + let running = self.running.try_lock().ok()?; |
| 14 | + let mut cancelled = Box::pin(self.cancelled.notified()); |
| 15 | + cancelled.as_mut().enable(); |
| 16 | + Some(ActiveProbe { |
| 17 | + _running: running, |
| 18 | + cancelled, |
| 19 | + }) |
| 20 | + } |
| 21 | + |
| 22 | + pub(super) fn cancel(&self) { |
| 23 | + self.cancelled.notify_waiters(); |
| 24 | + } |
| 25 | + |
| 26 | + pub(super) async fn cancel_and_wait(&self) { |
| 27 | + self.cancel(); |
| 28 | + drop(self.running.lock().await); |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +pub(super) struct ActiveProbe<'a> { |
| 33 | + _running: MutexGuard<'a, ()>, |
| 34 | + cancelled: Pin<Box<Notified<'a>>>, |
| 35 | +} |
| 36 | + |
| 37 | +impl ActiveProbe<'_> { |
| 38 | + pub(super) async fn run<Probe: Future>(&mut self, probe: Probe) -> Option<Probe::Output> { |
| 39 | + tokio::select! { |
| 40 | + biased; |
| 41 | + () = &mut self.cancelled => None, |
| 42 | + result = probe => Some(result), |
| 43 | + } |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +#[cfg(test)] |
| 48 | +mod tests { |
| 49 | + use std::{ |
| 50 | + future::{pending, ready}, |
| 51 | + sync::{ |
| 52 | + Arc, |
| 53 | + atomic::{AtomicBool, Ordering}, |
| 54 | + }, |
| 55 | + }; |
| 56 | + |
| 57 | + use tokio::{io::AsyncReadExt, net::TcpListener, sync::oneshot}; |
| 58 | + |
| 59 | + use super::*; |
| 60 | + |
| 61 | + #[tokio::test] |
| 62 | + async fn cancellation_before_first_poll_does_not_start_the_request() { |
| 63 | + let control = ProbeControl::default(); |
| 64 | + let mut active = control.try_start().expect("probe should start"); |
| 65 | + control.cancel(); |
| 66 | + |
| 67 | + let result = active |
| 68 | + .run(async { panic!("a cancelled probe must not send an HTTP request") }) |
| 69 | + .await; |
| 70 | + |
| 71 | + assert_eq!(result, None); |
| 72 | + } |
| 73 | + |
| 74 | + #[tokio::test] |
| 75 | + async fn only_one_probe_can_run_at_a_time() { |
| 76 | + let control = ProbeControl::default(); |
| 77 | + let mut active = control.try_start().expect("probe should start"); |
| 78 | + assert!(control.try_start().is_none()); |
| 79 | + assert_eq!(active.run(ready(42)).await, Some(42)); |
| 80 | + assert!(control.try_start().is_none()); |
| 81 | + drop(active); |
| 82 | + assert!(control.try_start().is_some()); |
| 83 | + } |
| 84 | + |
| 85 | + struct DropFlag(Arc<AtomicBool>); |
| 86 | + |
| 87 | + impl Drop for DropFlag { |
| 88 | + fn drop(&mut self) { |
| 89 | + self.0.store(true, Ordering::SeqCst); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + #[tokio::test] |
| 94 | + async fn recording_waits_until_in_flight_request_is_dropped() { |
| 95 | + let control = Arc::new(ProbeControl::default()); |
| 96 | + let request_dropped = Arc::new(AtomicBool::new(false)); |
| 97 | + let (started_tx, started_rx) = oneshot::channel(); |
| 98 | + let probe_control = Arc::clone(&control); |
| 99 | + let dropped = Arc::clone(&request_dropped); |
| 100 | + let task = tokio::spawn(async move { |
| 101 | + let mut active = probe_control.try_start().expect("probe should start"); |
| 102 | + active |
| 103 | + .run(async move { |
| 104 | + let _drop_flag = DropFlag(dropped); |
| 105 | + started_tx.send(()).expect("receiver should be waiting"); |
| 106 | + pending::<()>().await; |
| 107 | + }) |
| 108 | + .await |
| 109 | + }); |
| 110 | + |
| 111 | + started_rx |
| 112 | + .await |
| 113 | + .expect("probe should enter the upload POST"); |
| 114 | + control.cancel_and_wait().await; |
| 115 | + |
| 116 | + assert!(request_dropped.load(Ordering::SeqCst)); |
| 117 | + assert_eq!(task.await.expect("probe task should not panic"), None); |
| 118 | + assert!(control.try_start().is_some()); |
| 119 | + } |
| 120 | + |
| 121 | + #[tokio::test] |
| 122 | + async fn cancels_a_real_http_request_waiting_for_its_response() { |
| 123 | + let listener = TcpListener::bind(("127.0.0.1", 0)) |
| 124 | + .await |
| 125 | + .expect("test listener should bind"); |
| 126 | + let url = format!("http://{}/upload-health", listener.local_addr().unwrap()); |
| 127 | + let (request_tx, request_rx) = oneshot::channel(); |
| 128 | + let (stop_tx, stop_rx) = oneshot::channel(); |
| 129 | + let server = tokio::spawn(async move { |
| 130 | + let (mut socket, _) = listener.accept().await.unwrap(); |
| 131 | + let mut method = [0; 5]; |
| 132 | + socket.read_exact(&mut method).await.unwrap(); |
| 133 | + assert_eq!(&method, b"POST "); |
| 134 | + request_tx.send(()).unwrap(); |
| 135 | + stop_rx.await.unwrap(); |
| 136 | + }); |
| 137 | + let control = Arc::new(ProbeControl::default()); |
| 138 | + let probe_control = Arc::clone(&control); |
| 139 | + let request = tokio::spawn(async move { |
| 140 | + let mut active = probe_control.try_start().expect("probe should start"); |
| 141 | + active |
| 142 | + .run(async { |
| 143 | + reqwest::Client::builder() |
| 144 | + .no_proxy() |
| 145 | + .build() |
| 146 | + .unwrap() |
| 147 | + .post(url) |
| 148 | + .body(vec![0; 256 * 1024]) |
| 149 | + .send() |
| 150 | + .await |
| 151 | + }) |
| 152 | + .await |
| 153 | + }); |
| 154 | + |
| 155 | + tokio::time::timeout(std::time::Duration::from_secs(5), async { |
| 156 | + request_rx.await.unwrap(); |
| 157 | + control.cancel_and_wait().await; |
| 158 | + assert!(request.await.unwrap().is_none()); |
| 159 | + stop_tx.send(()).unwrap(); |
| 160 | + server.await.unwrap(); |
| 161 | + }) |
| 162 | + .await |
| 163 | + .expect("cancellation should not wait for the HTTP response"); |
| 164 | + } |
| 165 | + |
| 166 | + #[tokio::test] |
| 167 | + async fn previous_cancellation_does_not_cancel_a_later_probe() { |
| 168 | + let control = ProbeControl::default(); |
| 169 | + let mut active = control.try_start().expect("probe should start"); |
| 170 | + control.cancel(); |
| 171 | + assert_eq!(active.run(ready(1)).await, None); |
| 172 | + drop(active); |
| 173 | + |
| 174 | + control.cancel_and_wait().await; |
| 175 | + let mut next = control.try_start().expect("next probe should start"); |
| 176 | + assert_eq!(next.run(ready(2)).await, Some(2)); |
| 177 | + } |
| 178 | +} |
0 commit comments