Skip to main content

eventful_rs/
local_task.rs

1//! Non-Send futures polled by a shard's own driver, with explicit ownership.
2use crate::{InvokeError, ShardEventHandle, engine::LocalFuture};
3use futures::{
4    FutureExt,
5    channel::oneshot,
6    future::{AbortHandle, Aborted},
7};
8use std::{
9    cell::{Cell, RefCell},
10    future::Future,
11    panic::AssertUnwindSafe,
12    pin::Pin,
13    sync::{
14        Arc,
15        atomic::{AtomicBool, Ordering},
16    },
17    task::{Context, Poll, Waker},
18};
19
20/// Per-shard queue of spawned futures awaiting their first poll by the driver.
21#[derive(Default)]
22pub(crate) struct LocalSpawner {
23    /// Futures spawned since the driver last took the queue.
24    queue: RefCell<Vec<LocalFuture>>,
25    /// The driver's waker, registered when it last checked the queue.
26    waker: RefCell<Option<Waker>>,
27    /// Set when the shard stops; later spawns are rejected.
28    closed: Cell<bool>,
29}
30
31impl LocalSpawner {
32    /// Queue a future and wake the driver; the future is not polled here.
33    fn push(&self, future: LocalFuture) -> Result<(), InvokeError> {
34        if self.closed.get() {
35            return Err(InvokeError::Closed);
36        }
37        self.queue.borrow_mut().push(future);
38        // Wake outside the borrow in case the waker re-enters.
39        let waker = self.waker.borrow().clone();
40        if let Some(waker) = waker {
41            waker.wake();
42        }
43        Ok(())
44    }
45
46    /// Ready with every queued future; registers the driver for later spawns.
47    pub(crate) fn poll_queued(&self, cx: &mut Context<'_>) -> Poll<Vec<LocalFuture>> {
48        {
49            let mut waker = self.waker.borrow_mut();
50            if !waker.as_ref().is_some_and(|w| w.will_wake(cx.waker())) {
51                *waker = Some(cx.waker().clone());
52            }
53        }
54        let queued = std::mem::take(&mut *self.queue.borrow_mut());
55        if queued.is_empty() {
56            Poll::Pending
57        } else {
58            Poll::Ready(queued)
59        }
60    }
61
62    /// Reject later spawns and return queued futures for dropping outside the borrow.
63    pub(crate) fn close(&self) -> Vec<LocalFuture> {
64        self.closed.set(true);
65        self.waker.borrow_mut().take();
66        std::mem::take(&mut *self.queue.borrow_mut())
67    }
68}
69
70/// Marks a task finished when its future completes, unwinds, or is dropped.
71struct Finish(Arc<AtomicBool>);
72impl Finish {
73    /// Mark the task finished before its outcome becomes observable.
74    fn set(&self) {
75        self.0.store(true, Ordering::Release);
76    }
77}
78impl Drop for Finish {
79    fn drop(&mut self) {
80        self.set();
81    }
82}
83
84/// Spawn a future on the handle's shard; the caller must be on that shard's thread.
85pub(crate) fn spawn<F>(
86    handle: &ShardEventHandle,
87    future: F,
88) -> Result<LocalTask<F::Output>, InvokeError>
89where
90    F: Future + 'static,
91    F::Output: 'static,
92{
93    let Some(spawner) = crate::engine::local_spawner(handle.shard_id) else {
94        return Err(if handle.is_closed() {
95            InvokeError::Closed
96        } else {
97            InvokeError::WrongShard
98        });
99    };
100    if handle.is_closed() {
101        return Err(InvokeError::Closed);
102    }
103    let (future, abort) = futures::future::abortable(AssertUnwindSafe(future).catch_unwind());
104    let finished = Arc::new(AtomicBool::new(false));
105    let finish = Finish(finished.clone());
106    let (tx, result) = oneshot::channel();
107    spawner.push(Box::pin(async move {
108        let outcome = future.await;
109        finish.set();
110        match outcome {
111            Ok(Ok(value)) => drop(tx.send(Ok(value))),
112            Ok(Err(panic)) => {
113                let _ = tx.send(Err(InvokeError::Panicked));
114                // Let the driver report it like any other callback panic.
115                std::panic::resume_unwind(panic);
116            }
117            Err(Aborted) => drop(tx.send(Err(InvokeError::Canceled))),
118        }
119    }))?;
120    Ok(LocalTask {
121        handle: TaskHandle { abort, finished },
122        result,
123        detached: false,
124    })
125}
126
127/// Owning guard for a task running on a shard's thread.
128/// Dropping it aborts the task, like dropping a [`crate::ScopedConnection`]
129/// disconnects. Use [`Self::detach`] to let the task run on its own.
130///
131/// Awaiting the guard yields the task's output, or
132/// [`InvokeError::Canceled`] if it was aborted (including by shard shutdown)
133/// and [`InvokeError::Panicked`] if it panicked. Only another future on the
134/// same shard may await it, since the shard's driver is what makes progress.
135///
136/// Spawn with [`crate::ShardBinding::spawn_local`] or [`crate::ShardRc::spawn_local`];
137/// [`crate::ShardRc::spawn_owned`] returns a [`TaskHandle`] directly.
138#[must_use = "dropping a LocalTask aborts it; call detach() to let it run"]
139pub struct LocalTask<T = ()> {
140    /// Control handle shared with detached copies.
141    handle: TaskHandle,
142    /// The task's outcome, sent once its future completes, panics, or is aborted.
143    result: oneshot::Receiver<Result<T, InvokeError>>,
144    /// Set by `detach` so dropping the guard leaves the task running.
145    detached: bool,
146}
147
148impl<T> std::fmt::Debug for LocalTask<T> {
149    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150        f.debug_struct("LocalTask")
151            .field("handle", &self.handle)
152            .field("detached", &self.detached)
153            .finish_non_exhaustive()
154    }
155}
156
157impl<T> Future for LocalTask<T> {
158    type Output = Result<T, InvokeError>;
159    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
160        // A dropped sender means the shard dropped the task unfinished.
161        self.result
162            .poll_unpin(cx)
163            .map(|result| result.unwrap_or(Err(InvokeError::Canceled)))
164    }
165}
166
167impl<T> LocalTask<T> {
168    /// Stop the task at its next suspension point.
169    pub fn abort(&self) {
170        self.handle.abort();
171    }
172
173    /// Whether the task completed, panicked, or was dropped after an abort.
174    pub fn is_finished(&self) -> bool {
175        self.handle.is_finished()
176    }
177
178    /// Stop owning the task. It runs until it completes, is aborted through the
179    /// returned handle, or its shard shuts down. Its output is discarded.
180    pub fn detach(mut self) -> TaskHandle {
181        self.detached = true;
182        self.handle.clone()
183    }
184}
185
186impl<T> Drop for LocalTask<T> {
187    fn drop(&mut self) {
188        if !self.detached {
189            self.handle.abort();
190        }
191    }
192}
193
194/// Non-owning, cloneable control handle for a local task. It can be used from
195/// any thread; dropping it does not affect the task.
196#[derive(Clone, Debug)]
197pub struct TaskHandle {
198    /// Stops the task at its next suspension point.
199    abort: AbortHandle,
200    /// Set once the task's future has been dropped, for any reason.
201    finished: Arc<AtomicBool>,
202}
203
204impl TaskHandle {
205    /// Stop the task at its next suspension point. The future is dropped on its
206    /// shard's thread; a running synchronous section is never interrupted.
207    pub fn abort(&self) {
208        self.abort.abort();
209    }
210
211    /// Whether the task completed, panicked, or was dropped after an abort.
212    /// An aborted task counts as finished once its shard has dropped it.
213    pub fn is_finished(&self) -> bool {
214        self.finished.load(Ordering::Acquire)
215    }
216}