eventful_rs/
local_task.rs1use 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#[derive(Default)]
22pub(crate) struct LocalSpawner {
23 queue: RefCell<Vec<LocalFuture>>,
25 waker: RefCell<Option<Waker>>,
27 closed: Cell<bool>,
29}
30
31impl LocalSpawner {
32 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 let waker = self.waker.borrow().clone();
40 if let Some(waker) = waker {
41 waker.wake();
42 }
43 Ok(())
44 }
45
46 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 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
70struct Finish(Arc<AtomicBool>);
72impl Finish {
73 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
84pub(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 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#[must_use = "dropping a LocalTask aborts it; call detach() to let it run"]
139pub struct LocalTask<T = ()> {
140 handle: TaskHandle,
142 result: oneshot::Receiver<Result<T, InvokeError>>,
144 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 self.result
162 .poll_unpin(cx)
163 .map(|result| result.unwrap_or(Err(InvokeError::Canceled)))
164 }
165}
166
167impl<T> LocalTask<T> {
168 pub fn abort(&self) {
170 self.handle.abort();
171 }
172
173 pub fn is_finished(&self) -> bool {
175 self.handle.is_finished()
176 }
177
178 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#[derive(Clone, Debug)]
197pub struct TaskHandle {
198 abort: AbortHandle,
200 finished: Arc<AtomicBool>,
202}
203
204impl TaskHandle {
205 pub fn abort(&self) {
208 self.abort.abort();
209 }
210
211 pub fn is_finished(&self) -> bool {
214 self.finished.load(Ordering::Acquire)
215 }
216}