Skip to main content

wackasm_opencomputers/
task.rs

1//! A small single-threaded async executor driven by OpenComputers: tasks
2//! wait on component calls, signals and timers, and the computer sleeps until
3//! one of them is ready. Enable the crate's `async` feature to use it.
4//!
5//! ```no_run
6//! use std::time::Duration;
7//! use wackasm_opencomputers::{prelude::*, task};
8//!
9//! task::run(async {
10//!     // A background task: blink a cursor in the corner every half second.
11//!     task::spawn(async {
12//!         let gpu = Gpu::first().expect("no GPU");
13//!         let mut on = false;
14//!         loop {
15//!             on = !on;
16//!             let _ = gpu.set_async(1, 1, if on { "_" } else { " " }, None).await;
17//!             task::sleep(Duration::from_millis(500)).await;
18//!         }
19//!     });
20//!
21//!     // Meanwhile: two component calls in flight at once, then wait for a key.
22//!     let gpu = Gpu::first().expect("no GPU");
23//!     let (resolution, depth) = task::join(gpu.get_resolution_async(), gpu.get_depth_async()).await;
24//!     println!("{resolution:?} at depth {depth:?}");
25//!     let key = task::signal(|s| matches!(s, Signal::KeyDown { .. })).await;
26//!     println!("pressed {key:?}");
27//! });
28//! ```
29//!
30//! # How it works
31//!
32//! The `_async` methods queue their component call with the architecture and
33//! return a future at once; the call runs on the server while the program
34//! keeps going, and the future completes when the result comes back. Calls
35//! run in the order they were made. A direct call runs as soon as the program
36//! next waits; indirect calls run on the server tick, as many per tick as the
37//! server's `asyncCallsPerTick` allows (1 by default, like Lua).
38//!
39//! [`run`] polls every task that is ready, then waits for whatever comes
40//! first: a completed call, a signal, or the next timer. Signals go to the
41//! first task waiting for one that matches ([`signal`]); signals nobody is
42//! waiting for are kept (up to 256) for later.
43//!
44//! Everything blocking still works inside tasks: `std::fs`, `println!`,
45//! reading stdin, the blocking component methods and [`crate::process`].
46//! While one runs, though, no other task does, so prefer the `_async`
47//! versions in code that has other tasks to keep going. Don't call
48//! [`crate::signal::pull`] inside [`run`]: it would take signals other tasks
49//! are waiting for. Use [`signal`].
50
51use std::{
52    cell::RefCell,
53    collections::{BTreeMap, HashMap, VecDeque},
54    future::Future,
55    pin::Pin,
56    rc::Rc,
57    sync::{Arc, Mutex},
58    task::{Context, Poll, Wake, Waker},
59    time::Duration,
60};
61
62use crate::{
63    component,
64    error::{Error, Result},
65    signal::Signal,
66    sys,
67    value::Value,
68};
69
70/// Signals kept for later when no task is waiting for them.
71const MAX_BUFFERED_SIGNALS: usize = 256;
72
73type BoxedTask = Pin<Box<dyn Future<Output = ()>>>;
74
75enum Slot {
76    Empty,
77    /// Taken out while being polled.
78    Polling,
79    Ready(BoxedTask),
80}
81
82struct TaskWaker {
83    id: usize,
84    ready: Arc<Mutex<VecDeque<usize>>>,
85}
86
87impl Wake for TaskWaker {
88    fn wake(self: Arc<Self>) {
89        self.wake_by_ref();
90    }
91
92    fn wake_by_ref(self: &Arc<Self>) {
93        if let Ok(mut ready) = self.ready.lock() {
94            ready.push_back(self.id);
95        }
96    }
97}
98
99enum CallSlot {
100    Waiting(Option<Waker>),
101    Done(Result<Vec<Value>>),
102}
103
104struct SignalWaiter {
105    id: u64,
106    filter: Box<dyn Fn(&Signal) -> bool>,
107    waker: Option<Waker>,
108}
109
110#[derive(Default)]
111struct Reactor {
112    calls: HashMap<i64, CallSlot>,
113    /// By (deadline in ms of uptime, id).
114    timers: BTreeMap<(u64, u64), Waker>,
115    signal_waiters: Vec<SignalWaiter>,
116    /// Signals delivered to a waiter, by waiter id.
117    delivered: HashMap<u64, Signal>,
118    /// Signals nobody was waiting for.
119    unclaimed: VecDeque<Signal>,
120    next_id: u64,
121}
122
123impl Reactor {
124    fn next_id(&mut self) -> u64 {
125        self.next_id += 1;
126        self.next_id
127    }
128
129    fn deliver(&mut self, signal: Signal) {
130        match self.signal_waiters.iter().position(|w| (w.filter)(&signal)) {
131            Some(i) => {
132                let waiter = self.signal_waiters.remove(i);
133                self.delivered.insert(waiter.id, signal);
134                if let Some(waker) = waiter.waker {
135                    waker.wake();
136                }
137            }
138            None => {
139                if self.unclaimed.len() == MAX_BUFFERED_SIGNALS {
140                    self.unclaimed.pop_front();
141                }
142                self.unclaimed.push_back(signal);
143            }
144        }
145    }
146
147    fn fire_timers(&mut self, now: u64) {
148        while let Some(entry) = self.timers.first_entry() {
149            if entry.key().0 > now {
150                break;
151            }
152            entry.remove().wake();
153        }
154    }
155
156    /// Anything that could wake a task.
157    fn has_waiters(&self) -> bool {
158        !self.calls.is_empty() || !self.timers.is_empty() || !self.signal_waiters.is_empty()
159    }
160}
161
162struct Runtime {
163    tasks: RefCell<Vec<Slot>>,
164    ready: Arc<Mutex<VecDeque<usize>>>,
165    reactor: RefCell<Reactor>,
166}
167
168thread_local! {
169    static RUNTIME: RefCell<Option<Rc<Runtime>>> = const { RefCell::new(None) };
170}
171
172fn runtime() -> Rc<Runtime> {
173    RUNTIME
174        .with(|r| r.borrow().clone())
175        .expect("wackasm_opencomputers async calls, timers and signals must run inside task::run")
176}
177
178fn with_reactor<T>(f: impl FnOnce(&mut Reactor) -> T) -> T {
179    let rt = runtime();
180    let mut reactor = rt.reactor.borrow_mut();
181    f(&mut reactor)
182}
183
184fn now_ms() -> u64 {
185    unsafe { sys::uptime_ms() }.max(0) as u64
186}
187
188impl Runtime {
189    fn spawn(&self, task: BoxedTask) {
190        let mut tasks = self.tasks.borrow_mut();
191        let id = match tasks.iter().position(|s| matches!(s, Slot::Empty)) {
192            Some(id) => {
193                tasks[id] = Slot::Ready(task);
194                id
195            }
196            None => {
197                tasks.push(Slot::Ready(task));
198                tasks.len() - 1
199            }
200        };
201        drop(tasks);
202        if let Ok(mut ready) = self.ready.lock() {
203            ready.push_back(id);
204        }
205    }
206
207    /// Polls every task that is ready. `true` if any was.
208    fn poll_ready(&self) -> bool {
209        let mut polled = false;
210        loop {
211            let next = self.ready.lock().ok().and_then(|mut r| r.pop_front());
212            let Some(id) = next else { return polled };
213            let task = {
214                let mut tasks = self.tasks.borrow_mut();
215                match tasks.get_mut(id).map(|s| std::mem::replace(s, Slot::Polling)) {
216                    Some(Slot::Ready(task)) => Some(task),
217                    Some(other) => {
218                        tasks[id] = other; // finished, or a duplicate wake
219                        None
220                    }
221                    None => None,
222                }
223            };
224            let Some(mut task) = task else { continue };
225            polled = true;
226            let waker = Waker::from(Arc::new(TaskWaker { id, ready: self.ready.clone() }));
227            let done = task.as_mut().poll(&mut Context::from_waker(&waker)).is_ready();
228            self.tasks.borrow_mut()[id] = if done { Slot::Empty } else { Slot::Ready(task) };
229        }
230    }
231
232    /// Waits for whatever comes first: a completion, a signal or a timer.
233    fn wait(&self) {
234        let now = now_ms();
235        let (timeout, any) = {
236            let mut reactor = self.reactor.borrow_mut();
237            reactor.fire_timers(now);
238            let next = reactor.timers.keys().next().map(|(deadline, _)| *deadline);
239            (next.map_or(-1, |d| d.saturating_sub(now) as i64), reactor.has_waiters())
240        };
241        if self.ready.lock().is_ok_and(|r| !r.is_empty()) {
242            return; // a timer just fired
243        }
244        if !any {
245            panic!("task::run: every task is waiting, but nothing can wake them (a task awaits itself?)");
246        }
247        let status = unsafe { sys::wait_ms(timeout) };
248        if status == sys::STATUS_OK {
249            if let Some(Value::Array(mut items)) = Value::decode(&sys::response())
250                && !items.is_empty()
251                && let Some(name) = items.remove(0).as_str().map(str::to_owned)
252            {
253                self.reactor.borrow_mut().deliver(Signal::parse(name, items));
254            }
255        }
256        self.drain_completions();
257        self.reactor.borrow_mut().fire_timers(now_ms());
258    }
259
260    fn drain_completions(&self) {
261        while unsafe { sys::completion_next() } == sys::STATUS_OK {
262            let Some(Value::Array(items)) = Value::decode(&sys::response()) else { continue };
263            let ticket = items.first().and_then(Value::as_i64);
264            let status = items.get(1).and_then(Value::as_i64).unwrap_or(-1) as i32;
265            let payload = items.get(2).and_then(Value::as_bytes).map(<[u8]>::to_vec).unwrap_or_default();
266            let Some(ticket) = ticket else { continue };
267            let mut reactor = self.reactor.borrow_mut();
268            if let Some(slot) = reactor.calls.get_mut(&ticket) {
269                let previous = std::mem::replace(slot, CallSlot::Done(component::decode_reply(status, payload)));
270                if let CallSlot::Waiting(Some(waker)) = previous {
271                    waker.wake();
272                }
273            }
274        }
275    }
276}
277
278/// Runs `future` to completion, along with any tasks it [`spawn`]s, and
279/// returns its output. Tasks still running when it finishes are dropped.
280///
281/// # Panics
282///
283/// If called inside another `run`, or if every task waits on something that
284/// can never happen.
285pub fn run<F: Future + 'static>(future: F) -> F::Output
286where
287    F::Output: 'static,
288{
289    let rt = Rc::new(Runtime {
290        tasks: RefCell::new(Vec::new()),
291        ready: Arc::new(Mutex::new(VecDeque::new())),
292        reactor: RefCell::new(Reactor::default()),
293    });
294    RUNTIME.with(|r| {
295        let mut r = r.borrow_mut();
296        assert!(r.is_none(), "task::run can't be nested");
297        *r = Some(rt.clone());
298    });
299    // Uninstall even if a task panics (with panic = "unwind").
300    struct Uninstall;
301    impl Drop for Uninstall {
302        fn drop(&mut self) {
303            RUNTIME.with(|r| *r.borrow_mut() = None);
304        }
305    }
306    let _uninstall = Uninstall;
307
308    let output = Rc::new(RefCell::new(None));
309    let slot = output.clone();
310    rt.spawn(Box::pin(async move {
311        *slot.borrow_mut() = Some(future.await);
312    }));
313    loop {
314        rt.poll_ready();
315        if let Some(value) = output.borrow_mut().take() {
316            // Cancel what is left, so its calls don't run for nobody.
317            rt.tasks.borrow_mut().clear();
318            return value;
319        }
320        rt.wait();
321    }
322}
323
324struct JoinState<T> {
325    output: Option<T>,
326    waker: Option<Waker>,
327}
328
329/// A spawned task's output. Awaiting it waits for the task; dropping it
330/// lets the task run on without anyone collecting the output.
331pub struct JoinHandle<T> {
332    state: Rc<RefCell<JoinState<T>>>,
333}
334
335impl<T> Future for JoinHandle<T> {
336    type Output = T;
337
338    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
339        let mut state = self.state.borrow_mut();
340        match state.output.take() {
341            Some(output) => Poll::Ready(output),
342            None => {
343                state.waker = Some(cx.waker().clone());
344                Poll::Pending
345            }
346        }
347    }
348}
349
350/// Starts `future` as a separate task, which runs while this one waits.
351pub fn spawn<F: Future + 'static>(future: F) -> JoinHandle<F::Output>
352where
353    F::Output: 'static,
354{
355    let state = Rc::new(RefCell::new(JoinState { output: None, waker: None }));
356    let task_state = state.clone();
357    runtime().spawn(Box::pin(async move {
358        let output = future.await;
359        let mut state = task_state.borrow_mut();
360        state.output = Some(output);
361        if let Some(waker) = state.waker.take() {
362            waker.wake();
363        }
364    }));
365    JoinHandle { state }
366}
367
368/// Waits for both futures, running them at the same time.
369pub async fn join<A: Future, B: Future>(a: A, b: B) -> (A::Output, B::Output) {
370    let (mut a, mut b) = (Box::pin(a), Box::pin(b));
371    let (mut ra, mut rb) = (None, None);
372    std::future::poll_fn(|cx| {
373        if ra.is_none()
374            && let Poll::Ready(v) = a.as_mut().poll(cx)
375        {
376            ra = Some(v);
377        }
378        if rb.is_none()
379            && let Poll::Ready(v) = b.as_mut().poll(cx)
380        {
381            rb = Some(v);
382        }
383        if ra.is_some() && rb.is_some() {
384            Poll::Ready((ra.take().unwrap(), rb.take().unwrap()))
385        } else {
386            Poll::Pending
387        }
388    })
389    .await
390}
391
392/// Waits for every future, running them at the same time. The outputs are in
393/// the same order as the futures.
394pub async fn join_all<F: Future>(futures: impl IntoIterator<Item = F>) -> Vec<F::Output> {
395    let mut futures: Vec<Pin<Box<F>>> = futures.into_iter().map(Box::pin).collect();
396    let mut outputs: Vec<Option<F::Output>> = futures.iter().map(|_| None).collect();
397    std::future::poll_fn(|cx| {
398        let mut pending = false;
399        for (future, output) in futures.iter_mut().zip(outputs.iter_mut()) {
400            if output.is_none() {
401                match future.as_mut().poll(cx) {
402                    Poll::Ready(v) => *output = Some(v),
403                    Poll::Pending => pending = true,
404                }
405            }
406        }
407        if pending { Poll::Pending } else { Poll::Ready(outputs.iter_mut().map(|o| o.take().unwrap()).collect()) }
408    })
409    .await
410}
411
412/// Lets other tasks run before continuing.
413pub async fn yield_now() {
414    let mut yielded = false;
415    std::future::poll_fn(|cx| {
416        if yielded {
417            Poll::Ready(())
418        } else {
419            yielded = true;
420            cx.waker().wake_by_ref();
421            Poll::Pending
422        }
423    })
424    .await
425}
426
427/// Waits for `duration` of game time without holding up other tasks.
428pub fn sleep(duration: Duration) -> Sleep {
429    Sleep { deadline: now_ms().saturating_add(duration.as_millis().min(u64::MAX as u128) as u64), key: None }
430}
431
432/// The future [`sleep`] returns.
433pub struct Sleep {
434    deadline: u64,
435    key: Option<(u64, u64)>,
436}
437
438impl Future for Sleep {
439    type Output = ();
440
441    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
442        if now_ms() >= self.deadline {
443            if let Some(key) = self.key.take() {
444                with_reactor(|r| r.timers.remove(&key));
445            }
446            return Poll::Ready(());
447        }
448        let deadline = self.deadline;
449        let key = *self.key.get_or_insert_with(|| (deadline, with_reactor(Reactor::next_id)));
450        with_reactor(|r| r.timers.insert(key, cx.waker().clone()));
451        Poll::Pending
452    }
453}
454
455impl Drop for Sleep {
456    fn drop(&mut self) {
457        if let Some(key) = self.key.take() {
458            let _ = RUNTIME.with(|rt| rt.borrow().as_ref().map(|rt| rt.reactor.borrow_mut().timers.remove(&key)));
459        }
460    }
461}
462
463/// `future`'s output, or `Err(Error::Failed("timed out"))` if `duration`
464/// passes first (`future` is then dropped, cancelling its calls).
465pub async fn timeout<F: Future>(duration: Duration, future: F) -> Result<F::Output> {
466    let mut future = Box::pin(future);
467    let mut timer = Box::pin(sleep(duration));
468    std::future::poll_fn(|cx| {
469        if let Poll::Ready(v) = future.as_mut().poll(cx) {
470            return Poll::Ready(Ok(v));
471        }
472        match timer.as_mut().poll(cx) {
473            Poll::Ready(()) => Poll::Ready(Err(Error::Failed("timed out".into()))),
474            Poll::Pending => Poll::Pending,
475        }
476    })
477    .await
478}
479
480/// The next signal that `filter` accepts. Signals that arrived earlier and
481/// that no task was waiting for count too, oldest first.
482pub fn signal(filter: impl Fn(&Signal) -> bool + 'static) -> NextSignal {
483    NextSignal { filter: Some(Box::new(filter)), id: None }
484}
485
486/// The next signal of any kind.
487pub fn next_signal() -> NextSignal {
488    signal(|_| true)
489}
490
491/// The future [`signal`] returns.
492pub struct NextSignal {
493    filter: Option<Box<dyn Fn(&Signal) -> bool>>,
494    id: Option<u64>,
495}
496
497impl Future for NextSignal {
498    type Output = Signal;
499
500    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Signal> {
501        let this = &mut *self;
502        with_reactor(|r| {
503            if let Some(id) = this.id {
504                if let Some(signal) = r.delivered.remove(&id) {
505                    this.id = None;
506                    return Poll::Ready(signal);
507                }
508                if let Some(waiter) = r.signal_waiters.iter_mut().find(|w| w.id == id) {
509                    waiter.waker = Some(cx.waker().clone());
510                }
511                return Poll::Pending;
512            }
513            let filter = this.filter.take().expect("NextSignal polled after completion");
514            if let Some(i) = r.unclaimed.iter().position(|s| filter(s)) {
515                return Poll::Ready(r.unclaimed.remove(i).unwrap());
516            }
517            let id = r.next_id();
518            r.signal_waiters.push(SignalWaiter { id, filter, waker: Some(cx.waker().clone()) });
519            this.id = Some(id);
520            Poll::Pending
521        })
522    }
523}
524
525impl Drop for NextSignal {
526    fn drop(&mut self) {
527        let Some(id) = self.id.take() else { return };
528        let _ = RUNTIME.with(|rt| {
529            rt.borrow().as_ref().map(|rt| {
530                let mut r = rt.reactor.borrow_mut();
531                r.signal_waiters.retain(|w| w.id != id);
532                // Delivered but never collected: give it to someone else.
533                if let Some(signal) = r.delivered.remove(&id) {
534                    r.deliver(signal);
535                }
536            })
537        });
538    }
539}
540
541/// What an async call is made on.
542pub(crate) enum Target {
543    Component(String),
544    Value(u32),
545}
546
547/// A component call in flight; see [`component::invoke_async`].
548///
549/// The call is queued when the future is first polled. Dropping the future
550/// before it completes cancels the call.
551#[must_use = "the call is only made when the future is awaited"]
552pub struct Call {
553    state: CallState,
554}
555
556enum CallState {
557    Start { target: Target, method: String, args: Vec<Value> },
558    Queued(i64),
559    Done,
560}
561
562impl Call {
563    pub(crate) fn new(target: Target, method: &str, args: Vec<Value>) -> Call {
564        Call { state: CallState::Start { target, method: method.to_owned(), args } }
565    }
566}
567
568impl Future for Call {
569    type Output = Result<Vec<Value>>;
570
571    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
572        match std::mem::replace(&mut self.state, CallState::Done) {
573            CallState::Start { target, method, args } => {
574                let rt = runtime(); // panics outside `run`, before queuing anything
575                let args = Value::Array(args).encode();
576                let ticket = unsafe {
577                    match &target {
578                        Target::Component(address) => sys::invoke_async(
579                            address.as_ptr(),
580                            address.len(),
581                            method.as_ptr(),
582                            method.len(),
583                            args.as_ptr(),
584                            args.len(),
585                        ),
586                        Target::Value(id) => {
587                            sys::invoke_value_async(*id, method.as_ptr(), method.len(), args.as_ptr(), args.len())
588                        }
589                    }
590                };
591                if ticket < 0 {
592                    let message = String::from_utf8_lossy(&sys::response()).into_owned();
593                    return Poll::Ready(Err(Error::Failed(message)));
594                }
595                rt.reactor.borrow_mut().calls.insert(ticket, CallSlot::Waiting(Some(cx.waker().clone())));
596                self.state = CallState::Queued(ticket);
597                Poll::Pending
598            }
599            CallState::Queued(ticket) => with_reactor(|r| match r.calls.remove(&ticket) {
600                Some(CallSlot::Done(result)) => Poll::Ready(result),
601                Some(CallSlot::Waiting(_)) | None => {
602                    r.calls.insert(ticket, CallSlot::Waiting(Some(cx.waker().clone())));
603                    self.state = CallState::Queued(ticket);
604                    Poll::Pending
605                }
606            }),
607            CallState::Done => panic!("component call polled after completion"),
608        }
609    }
610}
611
612impl Drop for Call {
613    fn drop(&mut self) {
614        if let CallState::Queued(ticket) = self.state {
615            let _ = RUNTIME.with(|rt| rt.borrow().as_ref().map(|rt| rt.reactor.borrow_mut().calls.remove(&ticket)));
616            unsafe { sys::cancel(ticket) };
617        }
618    }
619}