| 1 | use std::future::Future; |
| 2 | use std::pin::Pin; |
| 3 | use std::task::{Context, Poll}; |
| 4 | use tokio::sync::watch; |
| 5 | |
| 6 | /// Completion of one observed engine run, not a durable save or child-task drain. |
| 7 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 8 | pub enum EngineRunCompletion { |
| 9 | NormalReturn, |
| 10 | AbnormalTermination, |
| 11 | /// The handle was constructed without an observed background run. |
| 12 | NotObserved, |
| 13 | } |
| 14 | |
| 15 | pub(super) struct ObservedRun<F> { |
| 16 | future: Option<Pin<Box<F>>>, |
| 17 | completion: Option<watch::Sender<Option<EngineRunCompletion>>>, |
| 18 | } |
| 19 | |
| 20 | pub(super) fn observe<F: Future<Output = ()>>( |
| 21 | future: Pin<Box<F>>, |
| 22 | ) -> (ObservedRun<F>, watch::Receiver<Option<EngineRunCompletion>>) { |
| 23 | let (completion, receiver) = watch::channel(None); |
| 24 | ( |
| 25 | ObservedRun { |
| 26 | future: Some(future), |
| 27 | completion: Some(completion), |
| 28 | }, |
| 29 | receiver, |
| 30 | ) |
| 31 | } |
| 32 | |
| 33 | impl<F> ObservedRun<F> { |
| 34 | fn finish(&mut self, outcome: EngineRunCompletion) { |
| 35 | drop(self.future.take()); |
| 36 | if let Some(completion) = self.completion.take() { |
| 37 | let _ = completion.send_replace(Some(outcome)); |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | impl<F: Future<Output = ()>> Future for ObservedRun<F> { |
| 43 | type Output = (); |
| 44 | |
| 45 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { |
| 46 | let this = self.get_mut(); |
| 47 | match this |
| 48 | .future |
| 49 | .as_mut() |
| 50 | .expect("run already completed") |
| 51 | .as_mut() |
| 52 | .poll(cx) |
| 53 | { |
| 54 | Poll::Pending => Poll::Pending, |
| 55 | Poll::Ready(()) => { |
| 56 | this.finish(EngineRunCompletion::NormalReturn); |
| 57 | Poll::Ready(()) |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | impl<F> Drop for ObservedRun<F> { |
| 64 | fn drop(&mut self) { |
| 65 | self.finish(EngineRunCompletion::AbnormalTermination); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | #[cfg(test)] |
| 70 | mod tests { |
| 71 | use super::*; |
| 72 | use crate::core::engine::mock_engine_handle; |
| 73 | use std::sync::{ |
| 74 | Arc, |
| 75 | atomic::{AtomicBool, Ordering}, |
| 76 | }; |
| 77 | use tokio::sync::oneshot; |
| 78 | |
| 79 | struct Run { |
| 80 | release: oneshot::Receiver<()>, |
| 81 | dropped: Arc<AtomicBool>, |
| 82 | panic: bool, |
| 83 | completion: Option<watch::Receiver<Option<EngineRunCompletion>>>, |
| 84 | } |
| 85 | |
| 86 | impl Future for Run { |
| 87 | type Output = (); |
| 88 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { |
| 89 | assert!(!self.panic, "controlled run panic"); |
| 90 | Pin::new(&mut self.release).poll(cx).map(|_| ()) |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | impl Drop for Run { |
| 95 | fn drop(&mut self) { |
| 96 | if let Some(completion) = &self.completion { |
| 97 | assert!( |
| 98 | completion.borrow().is_none(), |
| 99 | "completion published before run drop" |
| 100 | ); |
| 101 | } |
| 102 | self.dropped.store(true, Ordering::Release); |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | fn fixture( |
| 107 | panic: bool, |
| 108 | ) -> ( |
| 109 | ObservedRun<Run>, |
| 110 | crate::core::engine::EngineHandle, |
| 111 | oneshot::Sender<()>, |
| 112 | Arc<AtomicBool>, |
| 113 | ) { |
| 114 | let (release, receiver) = oneshot::channel(); |
| 115 | let dropped = Arc::new(AtomicBool::new(false)); |
| 116 | let (mut run, completion) = observe(Box::pin(Run { |
| 117 | release: receiver, |
| 118 | dropped: Arc::clone(&dropped), |
| 119 | panic, |
| 120 | completion: None, |
| 121 | })); |
| 122 | run.future.as_mut().unwrap().as_mut().get_mut().completion = Some(completion.clone()); |
| 123 | let mut handle = mock_engine_handle().handle; |
| 124 | handle.run_completion = Some(completion); |
| 125 | (run, handle, release, dropped) |
| 126 | } |
| 127 | |
| 128 | #[tokio::test] |
| 129 | async fn run_completion_drops_future_before_notifying_all_waiters() { |
| 130 | let (run, handle, release, dropped) = fixture(false); |
| 131 | let task = tokio::spawn(run); |
| 132 | let mut cancelled = Box::pin(handle.wait_run_completion()); |
| 133 | std::future::poll_fn(|cx| { |
| 134 | assert!(cancelled.as_mut().poll(cx).is_pending()); |
| 135 | Poll::Ready(()) |
| 136 | }) |
| 137 | .await; |
| 138 | drop(cancelled); |
| 139 | release.send(()).unwrap(); |
| 140 | let clone = handle.clone(); |
| 141 | let (first, second) = |
| 142 | tokio::join!(handle.wait_run_completion(), clone.wait_run_completion()); |
| 143 | assert_eq!(first, EngineRunCompletion::NormalReturn); |
| 144 | assert_eq!(second, first); |
| 145 | assert!(dropped.load(Ordering::Acquire)); |
| 146 | task.await.unwrap(); |
| 147 | assert_eq!(handle.wait_run_completion().await, first); |
| 148 | } |
| 149 | |
| 150 | #[test] |
| 151 | fn run_completion_supervised_panic_is_abnormal_after_future_drop() { |
| 152 | let _env = crate::test_support::lock_test_env(); |
| 153 | let home = tempfile::tempdir().unwrap(); |
| 154 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 155 | let runtime = tokio::runtime::Builder::new_current_thread() |
| 156 | .enable_all() |
| 157 | .build() |
| 158 | .unwrap(); |
| 159 | runtime.block_on(async { |
| 160 | let (run, handle, _release, dropped) = fixture(true); |
| 161 | let task = codewhale_util::utils::spawn_supervised( |
| 162 | "completion-test", |
| 163 | std::panic::Location::caller(), |
| 164 | run, |
| 165 | ); |
| 166 | task.await.expect("existing supervisor catches the panic"); |
| 167 | assert_eq!( |
| 168 | handle.wait_run_completion().await, |
| 169 | EngineRunCompletion::AbnormalTermination |
| 170 | ); |
| 171 | assert!(dropped.load(Ordering::Acquire)); |
| 172 | }); |
| 173 | } |
| 174 | |
| 175 | #[tokio::test] |
| 176 | async fn run_completion_unpolled_abort_drops_future_before_notification() { |
| 177 | let (run, handle, _release, dropped) = fixture(false); |
| 178 | let task = tokio::spawn(run); |
| 179 | task.abort(); |
| 180 | assert!(task.await.unwrap_err().is_cancelled()); |
| 181 | assert_eq!( |
| 182 | handle.wait_run_completion().await, |
| 183 | EngineRunCompletion::AbnormalTermination |
| 184 | ); |
| 185 | assert!(dropped.load(Ordering::Acquire)); |
| 186 | } |
| 187 | |
| 188 | #[tokio::test] |
| 189 | async fn run_completion_polled_abort_drops_future_before_notification() { |
| 190 | let (mut run, handle, _release, dropped) = fixture(false); |
| 191 | std::future::poll_fn(|cx| { |
| 192 | assert!(Pin::new(&mut run).poll(cx).is_pending()); |
| 193 | Poll::Ready(()) |
| 194 | }) |
| 195 | .await; |
| 196 | let task = tokio::spawn(run); |
| 197 | task.abort(); |
| 198 | assert!(task.await.unwrap_err().is_cancelled()); |
| 199 | assert_eq!( |
| 200 | handle.wait_run_completion().await, |
| 201 | EngineRunCompletion::AbnormalTermination |
| 202 | ); |
| 203 | assert!(dropped.load(Ordering::Acquire)); |
| 204 | } |
| 205 | |
| 206 | #[test] |
| 207 | fn run_completion_runtime_drop_is_abnormal() { |
| 208 | let runtime = tokio::runtime::Builder::new_current_thread() |
| 209 | .enable_all() |
| 210 | .build() |
| 211 | .unwrap(); |
| 212 | let (run, handle, _release, dropped) = fixture(false); |
| 213 | runtime.spawn(run); |
| 214 | drop(runtime); |
| 215 | assert!(dropped.load(Ordering::Acquire)); |
| 216 | let runtime = tokio::runtime::Builder::new_current_thread() |
| 217 | .enable_all() |
| 218 | .build() |
| 219 | .unwrap(); |
| 220 | assert_eq!( |
| 221 | runtime.block_on(handle.wait_run_completion()), |
| 222 | EngineRunCompletion::AbnormalTermination |
| 223 | ); |
| 224 | } |
| 225 | |
| 226 | #[tokio::test] |
| 227 | async fn run_completion_old_run_cannot_complete_another_run() { |
| 228 | let (old, old_handle, release, _) = fixture(false); |
| 229 | let (_new, new_handle, _new_release, _) = fixture(false); |
| 230 | release.send(()).unwrap(); |
| 231 | old.await; |
| 232 | assert_eq!( |
| 233 | old_handle.wait_run_completion().await, |
| 234 | EngineRunCompletion::NormalReturn |
| 235 | ); |
| 236 | let mut pending = Box::pin(new_handle.wait_run_completion()); |
| 237 | std::future::poll_fn(|cx| { |
| 238 | assert!(pending.as_mut().poll(cx).is_pending()); |
| 239 | Poll::Ready(()) |
| 240 | }) |
| 241 | .await; |
| 242 | } |
| 243 | } |
| 244 |