Skip to main content

mln_runtime/
completion.rs

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