| 1 | //! A futures executor as an event source |
| 2 | //! |
| 3 | //! Only available with the `executor` cargo feature of `calloop`. |
| 4 | //! |
| 5 | //! This executor is intended for light futures, which will be polled as part of your |
| 6 | //! event loop. Such futures may be waiting for IO, or for some external computation on an |
| 7 | //! other thread for example. |
| 8 | //! |
| 9 | //! You can create a new executor using the `executor` function, which creates a pair |
| 10 | //! `(Executor<T>, Scheduler<T>)` to handle futures that all evaluate to type `T`. The |
| 11 | //! executor should be inserted into your event loop, and will yield the return values of |
| 12 | //! the futures as they finish into your callback. The scheduler can be cloned and used |
| 13 | //! to send futures to be executed into the executor. A generic executor can be obtained |
| 14 | //! by choosing `T = ()` and letting futures handle the forwarding of their return values |
| 15 | //! (if any) by their own means. |
| 16 | //! |
| 17 | //! **Note:** The futures must have their own means of being woken up, as this executor is, |
| 18 | //! by itself, not I/O aware. See [`LoopHandle::adapt_io`](crate::LoopHandle#method.adapt_io) |
| 19 | //! for that, or you can use some other mechanism if you prefer. |
| 20 | use std::{future::Future, pin::Pin, sync::Arc}; |
| 21 | |
| 22 | use futures_util::{ |
| 23 | stream::{FuturesUnordered, Stream}, |
| 24 | task::{waker_ref, ArcWake, Context, LocalFutureObj, Poll as FutPoll}, |
| 25 | }; |
| 26 | |
| 27 | use crate::{ |
| 28 | sources::{ |
| 29 | channel::{channel, Channel, ChannelError, Event, Sender}, |
| 30 | ping::{make_ping, Ping, PingError, PingSource}, |
| 31 | EventSource, |
| 32 | }, |
| 33 | Poll, PostAction, Readiness, Token, TokenFactory, |
| 34 | }; |
| 35 | |
| 36 | /// A future executor as an event source |
| 37 | #[derive(Debug)] |
| 38 | pub struct Executor<T> { |
| 39 | futures: FuturesUnordered<LocalFutureObj<'static, T>>, |
| 40 | new_futures: Channel<LocalFutureObj<'static, T>>, |
| 41 | ready_futures: PingSource, |
| 42 | waker: Arc<ExecWaker>, |
| 43 | } |
| 44 | |
| 45 | /// A scheduler to send futures to an executor |
| 46 | #[derive(Clone, Debug)] |
| 47 | pub struct Scheduler<T> { |
| 48 | sender: Sender<LocalFutureObj<'static, T>>, |
| 49 | } |
| 50 | |
| 51 | impl<T> Scheduler<T> { |
| 52 | /// Sends the given future to the executor associated to this scheduler |
| 53 | /// |
| 54 | /// Returns an error if the the executor not longer exists. |
| 55 | pub fn schedule<Fut: 'static>(&self, future: Fut) -> Result<(), ExecutorDestroyed> |
| 56 | where |
| 57 | Fut: Future<Output = T>, |
| 58 | { |
| 59 | let obj = LocalFutureObj::new(Box::new(future)); |
| 60 | self.sender.send(obj).map_err(|_| ExecutorDestroyed) |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | /// Error generated when trying to schedule a future after the |
| 65 | /// executor was destroyed. |
| 66 | #[derive(thiserror::Error, Debug)] |
| 67 | #[error("the executor was destroyed")] |
| 68 | pub struct ExecutorDestroyed; |
| 69 | |
| 70 | #[derive(Debug)] |
| 71 | struct ExecWaker { |
| 72 | ping: Ping, |
| 73 | } |
| 74 | |
| 75 | impl ArcWake for ExecWaker { |
| 76 | fn wake_by_ref(arc_self: &Arc<ExecWaker>) { |
| 77 | arc_self.ping.ping(); |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// Create a new executor, and its associated scheduler |
| 82 | /// |
| 83 | /// May fail due to OS errors preventing calloop to setup its internal pipes (if your |
| 84 | /// process has reatched its file descriptor limit for example). |
| 85 | pub fn executor<T>() -> crate::Result<(Executor<T>, Scheduler<T>)> { |
| 86 | let (ping, ready_futures) = make_ping()?; |
| 87 | let (sender, new_futures) = channel(); |
| 88 | Ok(( |
| 89 | Executor { |
| 90 | futures: FuturesUnordered::new(), |
| 91 | new_futures, |
| 92 | ready_futures, |
| 93 | waker: Arc::new(ExecWaker { ping }), |
| 94 | }, |
| 95 | Scheduler { sender }, |
| 96 | )) |
| 97 | } |
| 98 | |
| 99 | impl<T> EventSource for Executor<T> { |
| 100 | type Event = T; |
| 101 | type Metadata = (); |
| 102 | type Ret = (); |
| 103 | type Error = ExecutorError; |
| 104 | |
| 105 | fn process_events<F>( |
| 106 | &mut self, |
| 107 | readiness: Readiness, |
| 108 | token: Token, |
| 109 | mut callback: F, |
| 110 | ) -> Result<PostAction, Self::Error> |
| 111 | where |
| 112 | F: FnMut(T, &mut ()), |
| 113 | { |
| 114 | // fetch all newly inserted futures and push them to the container |
| 115 | let futures = &mut self.futures; |
| 116 | self.new_futures |
| 117 | .process_events(readiness, token, |evt, _| { |
| 118 | if let Event::Msg(fut) = evt { |
| 119 | futures.push(fut); |
| 120 | } |
| 121 | }) |
| 122 | .map_err(ExecutorError::NewFutureError)?; |
| 123 | |
| 124 | // process ping events to make it non-ready again |
| 125 | self.ready_futures |
| 126 | .process_events(readiness, token, |(), _| {}) |
| 127 | .map_err(ExecutorError::WakeError)?; |
| 128 | |
| 129 | // advance all available futures as much as possible |
| 130 | let waker = waker_ref(&self.waker); |
| 131 | let mut cx = Context::from_waker(&waker); |
| 132 | |
| 133 | while let FutPoll::Ready(Some(ret)) = Pin::new(&mut self.futures).poll_next(&mut cx) { |
| 134 | callback(ret, &mut ()); |
| 135 | } |
| 136 | Ok(PostAction::Continue) |
| 137 | } |
| 138 | |
| 139 | fn register(&mut self, poll: &mut Poll, token_factory: &mut TokenFactory) -> crate::Result<()> { |
| 140 | self.new_futures.register(poll, token_factory)?; |
| 141 | self.ready_futures.register(poll, token_factory)?; |
| 142 | Ok(()) |
| 143 | } |
| 144 | |
| 145 | fn reregister( |
| 146 | &mut self, |
| 147 | poll: &mut Poll, |
| 148 | token_factory: &mut TokenFactory, |
| 149 | ) -> crate::Result<()> { |
| 150 | self.new_futures.reregister(poll, token_factory)?; |
| 151 | self.ready_futures.reregister(poll, token_factory)?; |
| 152 | Ok(()) |
| 153 | } |
| 154 | |
| 155 | fn unregister(&mut self, poll: &mut Poll) -> crate::Result<()> { |
| 156 | self.new_futures.unregister(poll)?; |
| 157 | self.ready_futures.unregister(poll)?; |
| 158 | Ok(()) |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | /// An error arising from processing events in an async executor event source. |
| 163 | #[derive(thiserror::Error, Debug)] |
| 164 | pub enum ExecutorError { |
| 165 | /// Error while reading new futures added via [`Scheduler::schedule()`]. |
| 166 | #[error("error adding new futures")] |
| 167 | NewFutureError(ChannelError), |
| 168 | |
| 169 | /// Error while processing wake events from existing futures. |
| 170 | #[error("error processing wake events")] |
| 171 | WakeError(PingError), |
| 172 | } |
| 173 | |
| 174 | #[cfg(test)] |
| 175 | mod tests { |
| 176 | use super::*; |
| 177 | |
| 178 | #[test] |
| 179 | fn ready() { |
| 180 | let mut event_loop = crate::EventLoop::<u32>::try_new().unwrap(); |
| 181 | |
| 182 | let handle = event_loop.handle(); |
| 183 | |
| 184 | let (exec, sched) = executor::<u32>().unwrap(); |
| 185 | |
| 186 | handle |
| 187 | .insert_source(exec, move |ret, &mut (), got| { |
| 188 | *got = ret; |
| 189 | }) |
| 190 | .unwrap(); |
| 191 | |
| 192 | let mut got = 0; |
| 193 | |
| 194 | let fut = async { 42 }; |
| 195 | |
| 196 | event_loop |
| 197 | .dispatch(Some(::std::time::Duration::ZERO), &mut got) |
| 198 | .unwrap(); |
| 199 | |
| 200 | // the future is not yet inserted, and thus has not yet run |
| 201 | assert_eq!(got, 0); |
| 202 | |
| 203 | sched.schedule(fut).unwrap(); |
| 204 | |
| 205 | event_loop |
| 206 | .dispatch(Some(::std::time::Duration::ZERO), &mut got) |
| 207 | .unwrap(); |
| 208 | |
| 209 | // the future has run |
| 210 | assert_eq!(got, 42); |
| 211 | } |
| 212 | } |