Skip to main content

mln_runtime/
completion.rs

1//! The result of a command that runs on a runtime's thread.
2
3use std::future::Future;
4use std::pin::Pin;
5use std::sync::{Arc, Condvar, Mutex, OnceLock};
6use std::task::{Context, Poll, Waker};
7use std::thread::ThreadId;
8
9use mln_util::error::Error;
10use mln_util::sync::{CondvarExt, MutexExt};
11
12type Callback<T> = Box<dyn FnOnce(Result<T, Error>) + Send>;
13
14enum State<T> {
15    Pending {
16        waker: Option<Waker>,
17        callback: Option<Callback<T>>,
18    },
19    Ready(Result<T, Error>),
20    /// The result went to its receiver.
21    Taken,
22}
23
24/// The thread that resolves a completion, where waiting for it would never
25/// end.
26pub(crate) enum Home {
27    Anywhere,
28    Thread(ThreadId),
29    /// The thread that the cell names once it is set, and a thread whose
30    /// work the result waits for on the way.
31    Later(Arc<OnceLock<ThreadId>>, ThreadId),
32}
33
34impl Home {
35    fn is_current(&self) -> bool {
36        let current = std::thread::current().id();
37        match self {
38            Home::Anywhere => false,
39            Home::Thread(thread) => *thread == current,
40            Home::Later(thread, via) => thread.get() == Some(&current) || *via == current,
41        }
42    }
43}
44
45struct Shared<T> {
46    state: Mutex<State<T>>,
47    ready: Condvar,
48    home: Home,
49}
50
51/// The result of a command, which arrives once the command has run.
52///
53/// Receive it in one of three ways: await it (it is a [`Future`], with no
54/// executor of its own), block on it with [`wait`](Self::wait), or pass a
55/// callback to [`on_complete`](Self::on_complete). A command whose runtime
56/// or map goes away before it runs completes with
57/// [`ErrorKind::Cancelled`](mln_util::ErrorKind::Cancelled).
58#[must_use = "a completion does nothing unless it is received"]
59pub struct Completion<T> {
60    shared: Arc<Shared<T>>,
61}
62
63/// The sending side of a [`Completion`]. Dropping it unresolved cancels the
64/// completion.
65pub(crate) struct Resolver<T> {
66    shared: Option<Arc<Shared<T>>>,
67}
68
69impl<T: Send + 'static> Completion<T> {
70    /// A completion that a resolver on the thread `home` resolves.
71    pub(crate) fn new(home: Option<ThreadId>) -> (Completion<T>, Resolver<T>) {
72        Completion::at(home.map_or(Home::Anywhere, Home::Thread))
73    }
74
75    /// A completion that a resolver on the thread `home` resolves.
76    pub(crate) fn at(home: Home) -> (Completion<T>, Resolver<T>) {
77        let shared = Arc::new(Shared {
78            state: Mutex::new(State::Pending { waker: None, callback: None }),
79            ready: Condvar::new(),
80            home,
81        });
82        (Completion { shared: shared.clone() }, Resolver { shared: Some(shared) })
83    }
84
85    /// A completion that already has its result.
86    pub fn ready(result: Result<T, Error>) -> Completion<T> {
87        let (completion, resolver) = Completion::new(None);
88        resolver.resolve(result);
89        completion
90    }
91
92    /// Whether the result has arrived.
93    #[must_use]
94    pub fn is_complete(&self) -> bool {
95        !matches!(*self.shared.state.lock_unpoisoned(), State::Pending { .. })
96    }
97
98    /// Blocks until the result arrives, and returns it.
99    ///
100    /// A wait on the thread that resolves the completion would never end,
101    /// such as the runtime's own thread, or the thread that runs a render
102    /// session's [`DriverWork`](crate::DriverWork). A render session's
103    /// completions wait for its map's runtime too, as a resize or a detach
104    /// does, so their wait on the runtime's thread would never end either.
105    /// Such a wait fails with
106    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind::InvalidState) instead,
107    /// unless the result is already there.
108    pub fn wait(self) -> Result<T, Error> {
109        let mut state = self.shared.state.lock_unpoisoned();
110        loop {
111            match std::mem::replace(&mut *state, State::Taken) {
112                State::Ready(result) => return result,
113                pending @ State::Pending { .. } => {
114                    *state = pending;
115                    if self.shared.home.is_current() {
116                        return Err(Error::invalid_state(
117                            "a completion can't be waited for on the thread that resolves it",
118                        ));
119                    }
120                    state = self.shared.ready.wait_unpoisoned(state);
121                }
122                State::Taken => return Err(Error::invalid_state("the completion's result was already taken")),
123            }
124        }
125    }
126
127    /// Calls `callback` with the result once it arrives: on the thread that
128    /// resolves the completion, or at once on this thread when the result is
129    /// already there.
130    pub fn on_complete(self, callback: impl FnOnce(Result<T, Error>) + Send + 'static) {
131        let result = {
132            let mut state = self.shared.state.lock_unpoisoned();
133            match std::mem::replace(&mut *state, State::Taken) {
134                State::Ready(result) => result,
135                State::Pending { waker, .. } => {
136                    *state = State::Pending { waker, callback: Some(Box::new(callback)) };
137                    return;
138                }
139                State::Taken => Err(Error::invalid_state("the completion's result was already taken")),
140            }
141        };
142        callback(result);
143    }
144}
145
146impl<T> Future for Completion<T> {
147    type Output = Result<T, Error>;
148
149    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
150        let mut state = self.shared.state.lock_unpoisoned();
151        match std::mem::replace(&mut *state, State::Taken) {
152            State::Ready(result) => Poll::Ready(result),
153            State::Pending { callback, .. } => {
154                *state = State::Pending { waker: Some(cx.waker().clone()), callback };
155                Poll::Pending
156            }
157            State::Taken => Poll::Ready(Err(Error::invalid_state("the completion's result was already taken"))),
158        }
159    }
160}
161
162impl<T> std::fmt::Debug for Completion<T> {
163    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
164        let complete = !matches!(*self.shared.state.lock_unpoisoned(), State::Pending { .. });
165        f.debug_struct("Completion").field("complete", &complete).finish()
166    }
167}
168
169impl<T> Resolver<T> {
170    /// Delivers `result`: to the callback, if one is waiting, or to the
171    /// receiver. Nothing is locked while the callback or waker runs.
172    pub(crate) fn resolve(mut self, result: Result<T, Error>) {
173        if let Some(shared) = self.shared.take() {
174            Self::deliver(&shared, result);
175        }
176    }
177
178    fn deliver(shared: &Shared<T>, result: Result<T, Error>) {
179        let (callback, waker) = {
180            let mut state = shared.state.lock_unpoisoned();
181            match std::mem::replace(&mut *state, State::Taken) {
182                State::Pending { callback: Some(callback), .. } => (Some((callback, result)), None),
183                State::Pending { waker, callback: None } => {
184                    *state = State::Ready(result);
185                    shared.ready.notify_all();
186                    (None, waker)
187                }
188                done => {
189                    *state = done;
190                    (None, None)
191                }
192            }
193        };
194        if let Some((callback, result)) = callback {
195            callback(result);
196        }
197        if let Some(waker) = waker {
198            waker.wake();
199        }
200    }
201}
202
203impl<T> Drop for Resolver<T> {
204    fn drop(&mut self) {
205        if let Some(shared) = self.shared.take() {
206            Self::deliver(&shared, Err(Error::cancelled("the command was dropped before it ran")));
207        }
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use std::sync::atomic::{AtomicBool, Ordering};
214    use std::task::Wake;
215
216    use mln_util::ErrorKind;
217
218    use super::*;
219
220    #[test]
221    fn wait_receives_a_result_from_another_thread() {
222        let (completion, resolver) = Completion::new(None);
223        let thread = std::thread::spawn(move || resolver.resolve(Ok(7)));
224        assert_eq!(Ok(7), completion.wait());
225        thread.join().unwrap();
226    }
227
228    #[test]
229    fn a_callback_runs_once_with_the_result() {
230        let (completion, resolver) = Completion::<u32>::new(None);
231        let (tx, rx) = std::sync::mpsc::channel();
232        completion.on_complete(move |result| tx.send(result).unwrap());
233        assert!(rx.try_recv().is_err());
234        resolver.resolve(Ok(3));
235        assert_eq!(Ok(3), rx.recv().unwrap());
236        assert!(rx.try_recv().is_err());
237    }
238
239    #[test]
240    fn a_callback_on_a_ready_completion_runs_at_once() {
241        let (tx, rx) = std::sync::mpsc::channel();
242        Completion::ready(Ok("done")).on_complete(move |result| tx.send(result).unwrap());
243        assert_eq!(Ok("done"), rx.try_recv().unwrap());
244    }
245
246    #[test]
247    fn a_dropped_resolver_cancels() {
248        let (completion, resolver) = Completion::<()>::new(None);
249        drop(resolver);
250        assert_eq!(ErrorKind::Cancelled, completion.wait().unwrap_err().kind);
251    }
252
253    #[test]
254    fn waiting_on_the_resolving_thread_fails_instead_of_hanging() {
255        let (completion, resolver) = Completion::<()>::new(Some(std::thread::current().id()));
256        assert_eq!(ErrorKind::InvalidState, completion.wait().unwrap_err().kind);
257        drop(resolver);
258    }
259
260    struct Flag(AtomicBool);
261
262    impl Wake for Flag {
263        fn wake(self: Arc<Self>) {
264            self.0.store(true, Ordering::SeqCst);
265        }
266    }
267
268    #[test]
269    fn polling_wakes_when_the_result_arrives() {
270        let (mut completion, resolver) = Completion::new(None);
271        let flag = Arc::new(Flag(AtomicBool::new(false)));
272        let waker = Waker::from(flag.clone());
273        let mut cx = Context::from_waker(&waker);
274        assert!(Pin::new(&mut completion).poll(&mut cx).is_pending());
275        resolver.resolve(Ok(1));
276        assert!(flag.0.load(Ordering::SeqCst));
277        assert_eq!(Poll::Ready(Ok(1)), Pin::new(&mut completion).poll(&mut cx));
278    }
279}