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, OnceLock};
6use std::task::{Context, Poll, Waker};
7use std::thread::ThreadId;
8
9use mln_util::error::Error;
10use parking_lot::{Condvar, Mutex};
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    /// `None` for a completion whose result is discarded, which acts as one
61    /// whose result was taken.
62    shared: Option<Arc<Shared<T>>>,
63}
64
65/// The sending side of a [`Completion`]. Dropping it unresolved cancels the
66/// completion.
67pub(crate) struct Resolver<T> {
68    target: Target<T>,
69}
70
71enum Target<T> {
72    Completion(Arc<Shared<T>>),
73    /// The result is discarded, except for a failure, which goes here.
74    Discard(fn(Error)),
75    Resolved,
76}
77
78fn taken() -> Error {
79    Error::invalid_state("the completion's result was already taken")
80}
81
82impl<T: Send + 'static> Completion<T> {
83    /// A completion that a resolver on the thread `home` resolves.
84    pub(crate) fn new(home: Option<ThreadId>) -> (Completion<T>, Resolver<T>) {
85        Completion::at(home.map_or(Home::Anywhere, Home::Thread))
86    }
87
88    /// A completion that a resolver on the thread `home` resolves.
89    pub(crate) fn at(home: Home) -> (Completion<T>, Resolver<T>) {
90        let shared = Arc::new(Shared {
91            state: Mutex::new(State::Pending { waker: None, callback: None }),
92            ready: Condvar::new(),
93            home,
94        });
95        (Completion { shared: Some(Arc::clone(&shared)) }, Resolver { target: Target::Completion(shared) })
96    }
97
98    /// A completion whose result is discarded: the completion acts as one
99    /// whose result was taken, and the resolver passes a failure,
100    /// cancellations included, to `on_failure` on the thread that resolves
101    /// it. It allocates nothing.
102    pub(crate) fn discarded(on_failure: fn(Error)) -> (Completion<T>, Resolver<T>) {
103        (Completion { shared: None }, Resolver { target: Target::Discard(on_failure) })
104    }
105
106    /// A completion that already has its result.
107    pub fn ready(result: Result<T, Error>) -> Completion<T> {
108        let (completion, resolver) = Completion::new(None);
109        resolver.resolve(result);
110        completion
111    }
112
113    /// Whether the result has arrived.
114    #[must_use]
115    pub fn is_complete(&self) -> bool {
116        self.shared.as_ref().is_none_or(|shared| !matches!(*shared.state.lock(), State::Pending { .. }))
117    }
118
119    /// Blocks until the result arrives, and returns it.
120    ///
121    /// A wait on the thread that resolves the completion would never end,
122    /// such as the runtime's own thread, or the thread that runs a render
123    /// session's [`DriverWork`](crate::DriverWork). A render session's
124    /// completions wait for its map's runtime too, as a resize or a detach
125    /// does, so their wait on the runtime's thread would never end either.
126    /// Such a wait fails with
127    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind::InvalidState) instead,
128    /// unless the result is already there, and so does every wait in the
129    /// browser, whose instance has one thread: await the completion there,
130    /// or pass it a callback.
131    pub fn wait(self) -> Result<T, Error> {
132        let Some(shared) = &self.shared else { return Err(taken()) };
133        let mut state = shared.state.lock();
134        loop {
135            match std::mem::replace(&mut *state, State::Taken) {
136                State::Ready(result) => return result,
137                pending @ State::Pending { .. } => {
138                    *state = pending;
139                    // The browser's one thread runs everything that would
140                    // resolve it, after this returns.
141                    if shared.home.is_current() || cfg!(target_family = "wasm") {
142                        return Err(Error::invalid_state(
143                            "a completion can't be waited for on the thread that resolves it",
144                        ));
145                    }
146                    shared.ready.wait(&mut state);
147                }
148                State::Taken => return Err(taken()),
149            }
150        }
151    }
152
153    /// Calls `callback` with the result once it arrives: on the thread that
154    /// resolves the completion, or at once on this thread when the result is
155    /// already there.
156    pub fn on_complete(self, callback: impl FnOnce(Result<T, Error>) + Send + 'static) {
157        if let Some((callback, result)) = self.on_complete_unless_ready(callback) {
158            callback(result);
159        }
160    }
161
162    /// As [`on_complete`](Self::on_complete), except that a result that is
163    /// already there comes back with the callback, for the caller to run.
164    pub(crate) fn on_complete_unless_ready<F: FnOnce(Result<T, Error>) + Send + 'static>(
165        self,
166        callback: F,
167    ) -> Option<(F, Result<T, Error>)> {
168        let Some(shared) = &self.shared else { return Some((callback, Err(taken()))) };
169        let mut state = shared.state.lock();
170        match std::mem::replace(&mut *state, State::Taken) {
171            State::Ready(result) => Some((callback, result)),
172            State::Pending { waker, .. } => {
173                *state = State::Pending { waker, callback: Some(Box::new(callback)) };
174                None
175            }
176            State::Taken => Some((callback, Err(taken()))),
177        }
178    }
179}
180
181impl<T> Future for Completion<T> {
182    type Output = Result<T, Error>;
183
184    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
185        let Some(shared) = &self.shared else { return Poll::Ready(Err(taken())) };
186        let mut state = shared.state.lock();
187        match std::mem::replace(&mut *state, State::Taken) {
188            State::Ready(result) => Poll::Ready(result),
189            State::Pending { callback, .. } => {
190                *state = State::Pending { waker: Some(cx.waker().clone()), callback };
191                Poll::Pending
192            }
193            State::Taken => Poll::Ready(Err(taken())),
194        }
195    }
196}
197
198impl<T> std::fmt::Debug for Completion<T> {
199    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200        let complete = self.shared.as_ref().is_none_or(|shared| !matches!(*shared.state.lock(), State::Pending { .. }));
201        f.debug_struct("Completion").field("complete", &complete).finish()
202    }
203}
204
205impl<T> Resolver<T> {
206    /// Delivers `result`: to the callback, if one is waiting, or to the
207    /// receiver. Nothing is locked while the callback or waker runs.
208    pub(crate) fn resolve(mut self, result: Result<T, Error>) {
209        self.deliver(result);
210    }
211
212    /// Whether the result is discarded, so that a success has nowhere to go.
213    pub(crate) fn discards(&self) -> bool {
214        matches!(self.target, Target::Discard(_))
215    }
216
217    fn deliver(&mut self, result: Result<T, Error>) {
218        match std::mem::replace(&mut self.target, Target::Resolved) {
219            Target::Completion(shared) => Self::deliver_to(&shared, result),
220            Target::Discard(on_failure) => {
221                if let Err(error) = result {
222                    on_failure(error);
223                }
224            }
225            Target::Resolved => {}
226        }
227    }
228
229    fn deliver_to(shared: &Shared<T>, result: Result<T, Error>) {
230        let (callback, waker) = {
231            let mut state = shared.state.lock();
232            match std::mem::replace(&mut *state, State::Taken) {
233                State::Pending { callback: Some(callback), .. } => (Some((callback, result)), None),
234                State::Pending { waker, callback: None } => {
235                    *state = State::Ready(result);
236                    shared.ready.notify_all();
237                    (None, waker)
238                }
239                done => {
240                    *state = done;
241                    (None, None)
242                }
243            }
244        };
245        if let Some((callback, result)) = callback {
246            callback(result);
247        }
248        if let Some(waker) = waker {
249            waker.wake();
250        }
251    }
252}
253
254impl<T> Drop for Resolver<T> {
255    fn drop(&mut self) {
256        if !matches!(self.target, Target::Resolved) {
257            self.deliver(Err(Error::cancelled("the command was dropped before it ran")));
258        }
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use std::sync::atomic::{AtomicBool, Ordering};
265    use std::task::Wake;
266
267    use mln_util::ErrorKind;
268
269    use super::*;
270
271    #[test]
272    fn wait_receives_a_result_from_another_thread() {
273        let (completion, resolver) = Completion::new(None);
274        let thread = std::thread::spawn(move || resolver.resolve(Ok(7)));
275        assert_eq!(Ok(7), completion.wait());
276        thread.join().unwrap();
277    }
278
279    #[test]
280    fn a_callback_runs_once_with_the_result() {
281        let (completion, resolver) = Completion::<u32>::new(None);
282        let (tx, rx) = std::sync::mpsc::channel();
283        completion.on_complete(move |result| tx.send(result).unwrap());
284        assert!(rx.try_recv().is_err());
285        resolver.resolve(Ok(3));
286        assert_eq!(Ok(3), rx.recv().unwrap());
287        assert!(rx.try_recv().is_err());
288    }
289
290    #[test]
291    fn a_callback_on_a_ready_completion_runs_at_once() {
292        let (tx, rx) = std::sync::mpsc::channel();
293        Completion::ready(Ok("done")).on_complete(move |result| tx.send(result).unwrap());
294        assert_eq!(Ok("done"), rx.try_recv().unwrap());
295    }
296
297    #[test]
298    fn a_dropped_resolver_cancels() {
299        let (completion, resolver) = Completion::<()>::new(None);
300        drop(resolver);
301        assert_eq!(ErrorKind::Cancelled, completion.wait().unwrap_err().kind);
302    }
303
304    #[test]
305    fn waiting_on_the_resolving_thread_fails_instead_of_hanging() {
306        let (completion, resolver) = Completion::<()>::new(Some(std::thread::current().id()));
307        assert_eq!(ErrorKind::InvalidState, completion.wait().unwrap_err().kind);
308        drop(resolver);
309    }
310
311    #[test]
312    fn a_discarded_completion_passes_on_only_failures() {
313        thread_local! {
314            static FAILURES: std::cell::RefCell<Vec<ErrorKind>> = const { std::cell::RefCell::new(Vec::new()) };
315        }
316        let on_failure: fn(Error) = |error| FAILURES.with_borrow_mut(|failures| failures.push(error.kind));
317        let (completion, resolver) = Completion::<u32>::discarded(on_failure);
318        assert!(completion.is_complete());
319        assert_eq!(ErrorKind::InvalidState, completion.wait().unwrap_err().kind);
320        resolver.resolve(Ok(1));
321        let (_, resolver) = Completion::<u32>::discarded(on_failure);
322        resolver.resolve(Err(Error::invalid_argument("bad")));
323        let (_, resolver) = Completion::<u32>::discarded(on_failure);
324        drop(resolver);
325        assert_eq!(vec![ErrorKind::InvalidArgument, ErrorKind::Cancelled], FAILURES.take());
326    }
327
328    struct Flag(AtomicBool);
329
330    impl Wake for Flag {
331        fn wake(self: Arc<Self>) {
332            self.0.store(true, Ordering::SeqCst);
333        }
334    }
335
336    #[test]
337    fn polling_wakes_when_the_result_arrives() {
338        let (mut completion, resolver) = Completion::new(None);
339        let flag = Arc::new(Flag(AtomicBool::new(false)));
340        let waker = Waker::from(Arc::clone(&flag));
341        let mut cx = Context::from_waker(&waker);
342        assert!(Pin::new(&mut completion).poll(&mut cx).is_pending());
343        resolver.resolve(Ok(1));
344        assert!(flag.0.load(Ordering::SeqCst));
345        assert_eq!(Poll::Ready(Ok(1)), Pin::new(&mut completion).poll(&mut cx));
346    }
347}