Skip to main content

mtorrent_utils/
task_watcher.rs

1use futures_util::Stream;
2use futures_util::stream::FusedStream;
3use pin_project_lite::pin_project;
4use std::pin::Pin;
5use std::task::{Context, Poll, ready};
6use tokio::sync::mpsc;
7
8/// Tracks a set of futures and reports when each of them exits, i.e. completes or is dropped.
9///
10/// Every future wrapped via [`watch`](Self::watch) reports its exit exactly once: either when it
11/// completes or when it is dropped before completion, whichever happens first. Note that when a
12/// future is dropped before completion, the exit is reported before the inner future itself is
13/// dropped.
14///
15/// Once all futures have been wrapped, call [`into_exits`](Self::into_exits) to get a stream
16/// of [`Exit`]s. The stream ends after every watched future has exited.
17#[derive(Debug)]
18pub struct TaskWatcher<T> {
19    tx: mpsc::UnboundedSender<Exit<T>>,
20    rx: mpsc::UnboundedReceiver<Exit<T>>,
21}
22
23impl<T> TaskWatcher<T> {
24    /// Create a watcher with no watched futures.
25    pub fn new() -> Self {
26        let (tx, rx) = mpsc::unbounded_channel();
27        Self { tx, rx }
28    }
29
30    /// Wrap `future` so that its exit is reported with `tag`.
31    pub fn watch<F: Future>(&self, tag: T, future: F) -> Watched<F, T> {
32        Watched {
33            future,
34            notifier: Some(Notifier {
35                tx: self.tx.clone(),
36                tag,
37            }),
38        }
39    }
40
41    /// Stop watching new futures and return a stream of exits of the watched futures.
42    /// The stream ends once all of them have exited.
43    pub fn into_exits(self) -> Exits<T> {
44        Exits { rx: self.rx }
45    }
46}
47
48impl<T> Default for TaskWatcher<T> {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54/// How a watched future exited, together with its tag.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Exit<T> {
57    /// The future ran to completion.
58    Completed(T),
59    /// The future was dropped before completion, e.g. because it was aborted or panicked.
60    Dropped(T),
61}
62
63impl<T> Exit<T> {
64    /// Tag of the exited future.
65    pub fn tag(&self) -> &T {
66        match self {
67            Self::Completed(tag) | Self::Dropped(tag) => tag,
68        }
69    }
70
71    /// Consume the exit and return the tag of the exited future.
72    pub fn into_tag(self) -> T {
73        match self {
74            Self::Completed(tag) | Self::Dropped(tag) => tag,
75        }
76    }
77
78    /// Whether the future ran to completion.
79    pub fn is_completed(&self) -> bool {
80        matches!(self, Self::Completed(_))
81    }
82}
83
84/// Stream of exits of watched futures, returned by [`TaskWatcher::into_exits`].
85///
86/// If a future completes, [`Exit::Completed`] is reported immediately, even if the [`Watched`]
87/// future is dropped later. [`Exit::Dropped`] is only reported for futures dropped before
88/// completion.
89#[derive(Debug)]
90pub struct Exits<T> {
91    rx: mpsc::UnboundedReceiver<Exit<T>>,
92}
93
94impl<T> Stream for Exits<T> {
95    type Item = Exit<T>;
96
97    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
98        self.rx.poll_recv(cx)
99    }
100}
101
102impl<T> FusedStream for Exits<T> {
103    fn is_terminated(&self) -> bool {
104        self.rx.is_closed() && self.rx.is_empty()
105    }
106}
107
108pin_project! {
109    /// Future returned by [`TaskWatcher::watch`].
110    #[derive(Debug)]
111    pub struct Watched<F, T> {
112        #[pin]
113        future: F,
114        notifier: Option<Notifier<T>>,
115    }
116
117    impl<F, T> PinnedDrop for Watched<F, T> {
118        fn drop(this: Pin<&mut Self>) {
119            let this = this.project();
120            if let Some(notifier) = this.notifier.take() {
121                notifier.fire(Exit::Dropped);
122            }
123        }
124    }
125}
126
127impl<F, T> Future for Watched<F, T>
128where
129    F: Future,
130{
131    type Output = <F as Future>::Output;
132
133    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
134        let this = self.project();
135        let ret = ready!(this.future.poll(cx));
136        if let Some(notifier) = this.notifier.take() {
137            notifier.fire(Exit::Completed);
138        }
139        Poll::Ready(ret)
140    }
141}
142
143#[derive(Debug)]
144struct Notifier<T> {
145    tx: mpsc::UnboundedSender<Exit<T>>,
146    tag: T,
147}
148
149impl<T> Notifier<T> {
150    fn fire(self, exit: fn(T) -> Exit<T>) {
151        _ = self.tx.send(exit(self.tag));
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158    use std::future::{pending, ready};
159    use tokio::sync::oneshot;
160    use tokio_test::{assert_pending, assert_ready, assert_ready_eq, task};
161
162    #[test]
163    fn test_no_watched_futures() {
164        let watcher = TaskWatcher::<u32>::new();
165        let mut exits = task::spawn(watcher.into_exits());
166        assert_ready_eq!(exits.poll_next(), None);
167    }
168
169    #[test]
170    fn test_pending_while_future_alive() {
171        let watcher = TaskWatcher::new();
172        let watched = watcher.watch(1, pending::<()>());
173        let mut exits = task::spawn(watcher.into_exits());
174        assert_pending!(exits.poll_next());
175
176        drop(watched);
177        assert!(exits.is_woken());
178        assert_ready_eq!(exits.poll_next(), Some(Exit::Dropped(1)));
179        assert_ready_eq!(exits.poll_next(), None);
180    }
181
182    #[test]
183    fn test_reports_completion_before_drop() {
184        let watcher = TaskWatcher::new();
185        let mut watched = task::spawn(watcher.watch(1, ready(42)));
186        let mut exits = task::spawn(watcher.into_exits());
187        assert_pending!(exits.poll_next());
188
189        assert_ready_eq!(watched.poll(), 42);
190        assert!(exits.is_woken());
191        assert_ready_eq!(exits.poll_next(), Some(Exit::Completed(1)));
192        // The sender is released on completion, so the stream ends without dropping `watched`.
193        assert_ready_eq!(exits.poll_next(), None);
194        drop(watched);
195    }
196
197    #[test]
198    fn test_reports_drop_without_completion() {
199        let watcher = TaskWatcher::new();
200        let watched = watcher.watch(7, pending::<()>());
201        drop(watched);
202        let mut exits = task::spawn(watcher.into_exits());
203        assert_ready_eq!(exits.poll_next(), Some(Exit::Dropped(7)));
204        assert_ready_eq!(exits.poll_next(), None);
205    }
206
207    #[test]
208    fn test_drains_all_exits_in_order() {
209        let watcher = TaskWatcher::new();
210        let a = watcher.watch(1, pending::<()>());
211        let b = watcher.watch(2, pending::<()>());
212        let c = watcher.watch(3, pending::<()>());
213        let mut exits = task::spawn(watcher.into_exits());
214        drop(b);
215        drop(c);
216        drop(a);
217        for expected in [2, 3, 1] {
218            assert_ready_eq!(exits.poll_next(), Some(Exit::Dropped(expected)));
219        }
220        assert_ready_eq!(exits.poll_next(), None);
221    }
222
223    #[test]
224    fn test_is_terminated() {
225        let watcher = TaskWatcher::new();
226        let a = watcher.watch(1, pending::<()>());
227        let b = watcher.watch(2, pending::<()>());
228        let mut exits = task::spawn(watcher.into_exits());
229        assert!(!exits.is_terminated());
230
231        drop(a);
232        assert!(!exits.is_terminated());
233        assert_ready_eq!(exits.poll_next(), Some(Exit::Dropped(1)));
234        assert!(!exits.is_terminated());
235
236        // All senders are gone, but an exit is still queued.
237        drop(b);
238        assert!(!exits.is_terminated());
239        assert_ready_eq!(exits.poll_next(), Some(Exit::Dropped(2)));
240        assert!(exits.is_terminated());
241        assert_ready_eq!(exits.poll_next(), None);
242        assert!(exits.is_terminated());
243    }
244
245    #[test]
246    fn test_is_terminated_without_watched_futures() {
247        let exits = TaskWatcher::<u32>::new().into_exits();
248        assert!(exits.is_terminated());
249    }
250
251    #[test]
252    fn test_waiting_stream_is_woken_on_completion() {
253        let watcher = TaskWatcher::new();
254        let (tx, rx) = oneshot::channel::<()>();
255        let mut watched = task::spawn(watcher.watch(5, rx));
256        let mut exits = task::spawn(watcher.into_exits());
257
258        assert_pending!(exits.poll_next());
259        assert_pending!(watched.poll());
260
261        tx.send(()).unwrap();
262        assert!(watched.is_woken());
263        assert_ready!(watched.poll()).unwrap();
264        assert!(exits.is_woken());
265        assert_ready_eq!(exits.poll_next(), Some(Exit::Completed(5)));
266        assert_ready_eq!(exits.poll_next(), None);
267        drop(watched);
268    }
269
270    #[test]
271    fn test_reports_mixed_exits() {
272        let watcher = TaskWatcher::new();
273        let mut completing = task::spawn(watcher.watch("completing", ready(())));
274        let dropped = watcher.watch("dropped", pending::<()>());
275        let mut exits = task::spawn(watcher.into_exits());
276
277        drop(dropped);
278        assert_ready!(completing.poll());
279        drop(completing);
280        assert_ready_eq!(exits.poll_next(), Some(Exit::Dropped("dropped")));
281        assert_ready_eq!(exits.poll_next(), Some(Exit::Completed("completing")));
282        assert_ready_eq!(exits.poll_next(), None);
283    }
284
285    #[test]
286    fn test_exit_accessors() {
287        let completed = Exit::Completed(1);
288        assert!(completed.is_completed());
289        assert_eq!(completed.tag(), &1);
290        assert_eq!(completed.into_tag(), 1);
291
292        let dropped = Exit::Dropped(2);
293        assert!(!dropped.is_completed());
294        assert_eq!(dropped.tag(), &2);
295        assert_eq!(dropped.into_tag(), 2);
296    }
297
298    #[test]
299    fn test_polled_between_send_and_sender_drop() {
300        // Tries to hit the window where a watched future dropped on another thread has already
301        // sent its exit but not yet dropped its sender, while the stream yields the exit and is
302        // immediately polled again. That poll must be woken once the sender is dropped, instead
303        // of staying pending forever.
304        const ITERATIONS: usize = 10_000;
305        let mut window_hits = 0;
306        for _ in 0..ITERATIONS {
307            let watcher = TaskWatcher::new();
308            let watched = watcher.watch(1, pending::<()>());
309            let mut exits = task::spawn(watcher.into_exits());
310            let dropper = std::thread::spawn(move || drop(watched));
311
312            loop {
313                match exits.poll_next() {
314                    Poll::Ready(exit) => {
315                        assert_eq!(exit, Some(Exit::Dropped(1)));
316                        break;
317                    }
318                    Poll::Pending => std::hint::spin_loop(),
319                }
320            }
321
322            let first_poll = exits.poll_next();
323            dropper.join().unwrap();
324            match first_poll {
325                Poll::Ready(exit) => assert_eq!(exit, None),
326                Poll::Pending => {
327                    window_hits += 1;
328                    assert!(exits.is_woken(), "stream not woken after the last sender dropped");
329                    assert_ready_eq!(exits.poll_next(), None);
330                }
331            }
332        }
333        println!("race window hit {window_hits}/{ITERATIONS} times");
334    }
335
336    #[test]
337    fn test_no_premature_end_across_threads() {
338        const TASKS: usize = 16;
339        let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
340
341        for _ in 0..200 {
342            let watcher = TaskWatcher::new();
343            let watched: Vec<_> = (0..TASKS).map(|i| watcher.watch(i, pending::<()>())).collect();
344            let mut exits = watcher.into_exits();
345            let threads: Vec<_> = watched
346                .into_iter()
347                .map(|watched| std::thread::spawn(move || drop(watched)))
348                .collect();
349            let received: Vec<_> = rt.block_on(async {
350                use futures_util::StreamExt;
351                let mut received = Vec::with_capacity(TASKS);
352                while let Some(exit) = exits.next().await {
353                    assert!(!exit.is_completed());
354                    received.push(exit.into_tag());
355                }
356                received
357            });
358            threads.into_iter().for_each(|t| t.join().unwrap());
359            let mut received = received;
360            received.sort_unstable();
361            assert_eq!(received, (0..TASKS).collect::<Vec<_>>());
362        }
363    }
364}