Skip to main content

webbluetooth_wasm/
exec.rs

1//! A single-threaded executor, because a browser has no other kind.
2//!
3//! The rest of this crate is written in `async fn`, which needs something to
4//! poll it. On every other platform that is the caller's runtime, and on
5//! several of them a blocking `block_on` is a reasonable answer. In a browser
6//! it is not: blocking the only thread stops the event loop, so the callback
7//! that would have completed the future can never run. Blocking there does not
8//! wait, it deadlocks.
9//!
10//! So a task is handed here, polled once, and then polled again whenever
11//! something wakes it — which in practice means when the shim settles a
12//! request or delivers an event. There is no thread and no queue drain on a
13//! timer; waking *is* the schedule.
14
15use std::cell::RefCell;
16use std::collections::HashMap;
17use std::future::Future;
18use std::pin::Pin;
19use std::rc::Rc;
20use std::sync::atomic::{AtomicU64, Ordering};
21use std::sync::Arc;
22use std::task::{Context, Poll, Wake, Waker};
23
24type BoxFuture = Pin<Box<dyn Future<Output = ()> + 'static>>;
25
26thread_local! {
27    /// Tasks that have not finished.
28    static TASKS: RefCell<HashMap<u64, BoxFuture>> = RefCell::new(HashMap::new());
29    /// Tasks woken while a poll was already in progress.
30    ///
31    /// Polling a task can wake it again — synchronously, from inside its own
32    /// poll. Re-entering the map at that moment would be a double borrow, so
33    /// the wake is recorded and drained once the current poll returns.
34    static READY: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
35    /// Whether a drain is already running, so a nested wake does not start a
36    /// second one underneath the first.
37    static DRAINING: RefCell<bool> = const { RefCell::new(false) };
38}
39
40static NEXT_TASK: AtomicU64 = AtomicU64::new(1);
41
42/// Identifies a spawned task.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44pub struct TaskId(u64);
45
46/// Wakes one task by putting it back in the ready list.
47struct TaskWaker(u64);
48
49impl Wake for TaskWaker {
50    fn wake(self: Arc<Self>) {
51        self.wake_by_ref();
52    }
53
54    fn wake_by_ref(self: &Arc<Self>) {
55        let id = self.0;
56        READY.with(|r| r.borrow_mut().push(id));
57        drain();
58    }
59}
60
61/// Run `future` to completion, polling it as it is woken.
62///
63/// Returns immediately; the future continues on the browser's event loop. This
64/// is the entry point every asynchronous operation ultimately needs, and the
65/// reason a page does not have to supply a runtime.
66pub fn spawn(future: impl Future<Output = ()> + 'static) -> TaskId {
67    let id = NEXT_TASK.fetch_add(1, Ordering::Relaxed);
68    TASKS.with(|t| t.borrow_mut().insert(id, Box::pin(future)));
69    READY.with(|r| r.borrow_mut().push(id));
70    drain();
71    TaskId(id)
72}
73
74/// Poll every task that has been woken, until none are left.
75fn drain() {
76    // A poll can wake something, which calls `drain` again. The outermost call
77    // owns the loop; an inner one returns and lets it pick the work up.
78    if DRAINING.with(|d| std::mem::replace(&mut *d.borrow_mut(), true)) {
79        return;
80    }
81
82    loop {
83        let Some(id) = READY.with(|r| r.borrow_mut().pop()) else {
84            break;
85        };
86        // Taken out of the map for the duration of the poll, so that waking
87        // this same task from inside its own poll does not need the map.
88        let Some(mut future) = TASKS.with(|t| t.borrow_mut().remove(&id)) else {
89            continue; // Already finished.
90        };
91
92        let waker: Waker = Arc::new(TaskWaker(id)).into();
93        let mut context = Context::from_waker(&waker);
94        match future.as_mut().poll(&mut context) {
95            Poll::Ready(()) => {}
96            Poll::Pending => {
97                TASKS.with(|t| t.borrow_mut().insert(id, future));
98            }
99        }
100    }
101
102    DRAINING.with(|d| *d.borrow_mut() = false);
103}
104
105/// How many tasks are alive. For tests, and for noticing a leak.
106pub fn task_count() -> usize {
107    TASKS.with(|t| t.borrow().len())
108}
109
110/// A future whose result is delivered once, from somewhere else.
111///
112/// The standard library has no single-threaded oneshot and this crate has no
113/// dependencies, so here is one. `Rc<RefCell<..>>` rather than a channel:
114/// there is one thread, so there is nothing to synchronise.
115pub struct Oneshot<T> {
116    slot: Rc<RefCell<OneshotState<T>>>,
117}
118
119struct OneshotState<T> {
120    value: Option<T>,
121    waker: Option<Waker>,
122    /// Set when the sending half goes away without sending.
123    dropped: bool,
124}
125
126/// Delivers a value to its [`Oneshot`].
127pub struct Sender<T> {
128    slot: Rc<RefCell<OneshotState<T>>>,
129}
130
131/// A pair to hand a value across an await point.
132pub fn oneshot<T>() -> (Sender<T>, Oneshot<T>) {
133    let slot = Rc::new(RefCell::new(OneshotState {
134        value: None,
135        waker: None,
136        dropped: false,
137    }));
138    (Sender { slot: slot.clone() }, Oneshot { slot })
139}
140
141impl<T> Sender<T> {
142    /// Deliver the value and wake whoever is waiting.
143    pub fn send(self, value: T) {
144        let waker = {
145            let mut state = self.slot.borrow_mut();
146            state.value = Some(value);
147            state.waker.take()
148        };
149        // Outside the borrow: waking may poll the receiver, which borrows.
150        if let Some(waker) = waker {
151            waker.wake();
152        }
153    }
154}
155
156impl<T> Drop for Sender<T> {
157    fn drop(&mut self) {
158        let waker = {
159            let mut state = self.slot.borrow_mut();
160            if state.value.is_some() {
161                return; // Already sent.
162            }
163            state.dropped = true;
164            state.waker.take()
165        };
166        // A receiver waiting on a sender that is gone would wait forever, so
167        // it is woken to find out.
168        if let Some(waker) = waker {
169            waker.wake();
170        }
171    }
172}
173
174impl<T> Future for Oneshot<T> {
175    /// `None` if the sender was dropped without sending.
176    type Output = Option<T>;
177
178    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
179        let mut state = self.slot.borrow_mut();
180        if let Some(value) = state.value.take() {
181            return Poll::Ready(Some(value));
182        }
183        if state.dropped {
184            return Poll::Ready(None);
185        }
186        state.waker = Some(context.waker().clone());
187        Poll::Pending
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194    use std::cell::Cell;
195
196    #[test]
197    fn a_task_that_never_waits_finishes_immediately() {
198        let ran = Rc::new(Cell::new(false));
199        let flag = ran.clone();
200        spawn(async move { flag.set(true) });
201        assert!(ran.get());
202        assert_eq!(task_count(), 0, "a finished task is not kept");
203    }
204
205    #[test]
206    fn a_task_resumes_when_its_value_arrives() {
207        let got = Rc::new(Cell::new(0u32));
208        let out = got.clone();
209        let (tx, rx) = oneshot::<u32>();
210
211        spawn(async move {
212            if let Some(v) = rx.await {
213                out.set(v);
214            }
215        });
216        assert_eq!(got.get(), 0, "still waiting");
217        assert_eq!(task_count(), 1);
218
219        tx.send(42);
220        assert_eq!(got.get(), 42, "sending should have resumed the task");
221        assert_eq!(task_count(), 0);
222    }
223
224    /// A sender that goes away has to wake the receiver, or the task waits for
225    /// a value that can never come — which in a browser is a leak with no
226    /// thread to show for it.
227    #[test]
228    fn dropping_the_sender_wakes_the_waiter() {
229        let finished = Rc::new(Cell::new(false));
230        let flag = finished.clone();
231        let (tx, rx) = oneshot::<u32>();
232
233        spawn(async move {
234            let value = rx.await;
235            assert!(value.is_none(), "no value was ever sent");
236            flag.set(true);
237        });
238        assert!(!finished.get());
239
240        drop(tx);
241        assert!(finished.get());
242        assert_eq!(task_count(), 0);
243    }
244
245    /// Waking from inside a poll must not re-enter the task map. This is the
246    /// case that deadlocks a naive implementation.
247    #[test]
248    fn waking_during_a_poll_does_not_re_enter() {
249        struct WakeThenReady(bool);
250        impl Future for WakeThenReady {
251            type Output = ();
252            fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
253                if self.0 {
254                    return Poll::Ready(());
255                }
256                self.0 = true;
257                // Wake ourselves from inside our own poll.
258                cx.waker().wake_by_ref();
259                Poll::Pending
260            }
261        }
262
263        let done = Rc::new(Cell::new(false));
264        let flag = done.clone();
265        spawn(async move {
266            WakeThenReady(false).await;
267            flag.set(true);
268        });
269        assert!(done.get(), "the task should have been polled again");
270        assert_eq!(task_count(), 0);
271    }
272
273    #[test]
274    fn many_tasks_run_independently() {
275        let count = Rc::new(Cell::new(0u32));
276        let mut senders = Vec::new();
277        for _ in 0..5 {
278            let (tx, rx) = oneshot::<u32>();
279            senders.push(tx);
280            let c = count.clone();
281            spawn(async move {
282                if rx.await.is_some() {
283                    c.set(c.get() + 1);
284                }
285            });
286        }
287        assert_eq!(task_count(), 5);
288        for (i, tx) in senders.into_iter().enumerate() {
289            tx.send(i as u32);
290        }
291        assert_eq!(count.get(), 5);
292        assert_eq!(task_count(), 0);
293    }
294
295    #[test]
296    fn a_value_sent_before_the_first_poll_is_not_lost() {
297        let (tx, rx) = oneshot::<u32>();
298        tx.send(7);
299        let got = Rc::new(Cell::new(0u32));
300        let out = got.clone();
301        spawn(async move {
302            out.set(rx.await.unwrap_or(0));
303        });
304        assert_eq!(got.get(), 7);
305    }
306}