Skip to main content

externally_driven_async_rt/
context.rs

1use core::{future::Future, time::Duration};
2
3use crate::{
4    Either2, EventLoopError, NotEnoughResources,
5    claimed::Claimed,
6    select2,
7    selector::{EVENTS_PER_CALL, Selector, SelectorEvent},
8    storage::LoopStorage,
9    tasks::{SlotWaiterTakenError, TaskReservation},
10};
11
12/// A handle of the event loop that you are currently in.
13///
14/// Used to spawn tasks, sleep, dispatch events to the external world and start IO operations.
15///
16/// # Panics
17///
18/// Wakers can only be woken on the same thread that created an
19/// [`EventLoop`](crate::EventLoop), otherwise waking panics.
20#[must_use]
21pub struct Context<
22    'sel,
23    E: 'static,
24    const EVENTS: usize,
25    const TASKS: usize,
26    const TASK_SIZE: usize,
27    const ROOT_TASK_SIZE: usize,
28    const TIMERS: usize,
29    const FDS: usize,
30> {
31    pub(crate) storage:
32        &'static LoopStorage<E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
33    pub(crate) selector: &'sel Selector,
34    pub(crate) claimed: Claimed<'sel>,
35}
36
37impl<
38    'sel,
39    E: 'static,
40    const EVENTS: usize,
41    const TASKS: usize,
42    const TASK_SIZE: usize,
43    const ROOT_TASK_SIZE: usize,
44    const TIMERS: usize,
45    const FDS: usize,
46> Context<'sel, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
47{
48    /// Pushes given `event` into the queue that [`EventLoop::events`](crate::EventLoop::events)
49    /// pops from.
50    ///
51    /// # Errors
52    ///
53    /// Returns `event` back if the queue already holds `EVENTS` events.
54    pub fn dispatch(&self, event: E) -> Result<(), E> {
55        self.storage.events.push(event)
56    }
57
58    /// Spawns a task with a given async closure.
59    ///
60    /// The future must fit `TASK_SIZE` bytes and be aligned to at most 16 bytes, otherwise the
61    /// program doesn't compile.
62    ///
63    /// Returns a join handle, a future that resolves once the task is finished. Dropping it
64    /// detaches the task, which keeps running until it finishes.
65    ///
66    /// # Errors
67    ///
68    /// Returns an error if all `TASKS` task slots are taken, the future returned by `f` is dropped
69    /// without being polled then. Use [`reserve_task`](Self::reserve_task) to wait for a free
70    /// slot instead.
71    pub fn spawn<F, Fut>(
72        &self,
73        f: F,
74    ) -> Result<
75        impl Future<Output = ()> + use<E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS, F, Fut>,
76        NotEnoughResources,
77    >
78    where
79        F: FnOnce(Self) -> Fut,
80        Fut: Future<Output = ()> + 'sel,
81    {
82        self.storage.tasks.spawn(self.claimed, f(*self))
83    }
84
85    /// Reserves a task slot.
86    ///
87    /// This method returns a future that is resolved once a slot in the internal
88    /// pool of tasks is available.
89    ///
90    /// The future stays pending until some other task finishes and frees a slot.
91    ///
92    /// # Errors
93    ///
94    /// Only one task can wait for a free slot at a time. The future resolves to
95    /// [`SlotWaiterTakenError`](crate::SlotWaiterTakenError) if all `TASKS` slots are taken and another task already waits.
96    ///
97    /// # Cancel safety
98    ///
99    /// This method is cancel safe.
100    pub fn reserve_task(
101        &self,
102    ) -> impl Future<
103        Output = Result<
104            TaskReservation<'sel, TASKS, TASK_SIZE, ROOT_TASK_SIZE>,
105            SlotWaiterTakenError,
106        >,
107    > + use<'sel, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS> {
108        self.storage.tasks.reserve(self.claimed)
109    }
110
111    /// Sleeps for `duration`.
112    ///
113    /// # Errors
114    ///
115    /// The returned future resolves to an error if all `TIMERS` timer slots are taken.
116    ///
117    /// # Cancel safety
118    ///
119    /// This method is cancel safe.
120    pub fn sleep(
121        &self,
122        duration: Duration,
123    ) -> impl Future<Output = Result<(), NotEnoughResources>>
124    + use<'sel, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS> {
125        let timers = &self.storage.timers;
126        timers.sleep_until(timers.now().saturating_add(duration))
127    }
128
129    /// Runs `future` with a timeout of `duration`, resolves to `Ok(MaybeTimedOut::Timeout)` in case of a timeout.
130    ///
131    /// # Errors
132    ///
133    /// The returned future resolves to an error if all `TIMERS` timer slots are taken.
134    ///
135    /// # Cancel safety
136    ///
137    /// This method is cancel safe if `future` is.
138    pub fn timeout<F: Future>(
139        &self,
140        duration: Duration,
141        future: F,
142    ) -> impl Future<Output = Result<MaybeTimedOut<F::Output>, NotEnoughResources>> {
143        let sleep = self.sleep(duration);
144        async move {
145            match select2(future, sleep).await {
146                Either2::Left(output) => Ok(MaybeTimedOut::Completed(output)),
147                Either2::Right(Ok(())) => Ok(MaybeTimedOut::Timeout),
148                Either2::Right(Err(err)) => Err(err),
149            }
150        }
151    }
152
153    /// Waits until [`EventLoop::notify`](crate::EventLoop::notify) is called.
154    ///
155    /// Notifications don't queue up: any number of `notify()` calls made before the future is
156    /// polled resolve it only once.
157    ///
158    /// Only one task can wait for a notification at a time.
159    ///
160    /// # Cancel safety
161    ///
162    /// This method is cancel safe.
163    pub fn notified(
164        &self,
165    ) -> impl Future<Output = ()> + use<'sel, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
166    {
167        self.storage.notification.notified()
168    }
169
170    pub(crate) fn clear(&self) {
171        self.storage.tasks.drop_all();
172        self.storage.timers.drop_wakers();
173        self.storage.io_waiters.drop_wakers();
174        self.storage.notification.clear();
175        self.storage.events.clear();
176    }
177
178    pub(crate) fn drain(&self) -> Result<(), EventLoopError> {
179        if !self.storage.tasks.has_root() {
180            return Err(EventLoopError::RootFinished);
181        }
182        loop {
183            self.process_selector_events()?;
184            if !self.storage.tasks.has_woken() {
185                break;
186            }
187            if self.storage.tasks.run_ready().is_ready() {
188                self.storage.tasks.drop_all();
189                self.flush()?;
190                return Err(EventLoopError::RootFinished);
191            }
192        }
193        self.flush()?;
194        Ok(())
195    }
196
197    fn process_selector_events(&self) -> rustix::io::Result<()> {
198        let mut events = [None; EVENTS_PER_CALL];
199        loop {
200            let full = self.selector.poll_nonblocking(&mut events)?;
201            for event in events.iter().map_while(|event| *event) {
202                match event {
203                    SelectorEvent::Io { fd, ready } => {
204                        self.storage.io_waiters.wake_ready(fd, ready);
205                    }
206                    SelectorEvent::Notify => self.storage.notification.fire(),
207                    SelectorEvent::Timer => {
208                        let now = self.storage.timers.now();
209                        while let Some(waker) = self.storage.timers.take_expired(now) {
210                            waker.wake();
211                        }
212                    }
213                }
214            }
215            if !full {
216                return Ok(());
217            }
218        }
219    }
220
221    pub(crate) fn flush(&self) -> rustix::io::Result<()> {
222        self.selector.flush(
223            self.storage.timers.next_deadline(),
224            self.storage.timers.now(),
225        )
226    }
227}
228
229impl<
230    E: 'static,
231    const EVENTS: usize,
232    const TASKS: usize,
233    const TASK_SIZE: usize,
234    const ROOT_TASK_SIZE: usize,
235    const TIMERS: usize,
236    const FDS: usize,
237> Clone for Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
238{
239    fn clone(&self) -> Self {
240        *self
241    }
242}
243
244impl<
245    E: 'static,
246    const EVENTS: usize,
247    const TASKS: usize,
248    const TASK_SIZE: usize,
249    const ROOT_TASK_SIZE: usize,
250    const TIMERS: usize,
251    const FDS: usize,
252> Copy for Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
253{
254}
255
256/// Result of the [`Context::timeout`]
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub enum MaybeTimedOut<T> {
259    /// Operation has timed out.
260    Timeout,
261    /// Operation has completed.
262    Completed(T),
263}
264
265#[cfg(test)]
266mod tests {
267    use core::{
268        future::{Future, pending},
269        pin::pin,
270        sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed},
271        task::{Context, Poll, Waker},
272        time::Duration,
273    };
274
275    use super::MaybeTimedOut;
276    use crate::{
277        LoopStorage, Selector,
278        testing::{FlagOnDrop, assert_yields, fake_instant, wake_expired_timers},
279        time::Instant,
280    };
281
282    type Storage = LoopStorage<u32, 3, 3, 128, 512, 3, 1>;
283
284    #[test]
285    fn future_finishing_first_wins() {
286        static STORAGE: Storage = Storage::new();
287        let selector = Selector::new().unwrap();
288        let (ctx, root) = STORAGE.claim(&selector).unwrap();
289        ctx.storage.tasks.spawn_root(root, ctx.claimed, async move {
290            let result = ctx
291                .timeout(Duration::from_secs(60), ctx.notified())
292                .await
293                .unwrap();
294            let event = match result {
295                MaybeTimedOut::Timeout => 0,
296                MaybeTimedOut::Completed(()) => 1,
297            };
298            ctx.dispatch(event).unwrap();
299            pending::<()>().await;
300        });
301        assert_eq!(ctx.storage.tasks.run_ready(), Poll::Pending);
302        assert!(ctx.storage.timers.next_deadline().is_some());
303        ctx.storage.notification.fire();
304        assert_eq!(ctx.storage.tasks.run_ready(), Poll::Pending);
305        assert_yields!(ctx.storage.events.iter_removing(), [1]);
306        assert_eq!(ctx.storage.timers.next_deadline(), None);
307        ctx.clear();
308    }
309
310    #[test]
311    fn elapsing_drops_the_future() {
312        static DROPPED: AtomicBool = AtomicBool::new(false);
313        static NOW: AtomicU64 = AtomicU64::new(0);
314        fn now() -> Instant {
315            fake_instant(&NOW)
316        }
317        static STORAGE: Storage = Storage::with_clock(now);
318        let selector = Selector::new().unwrap();
319        let (ctx, root) = STORAGE.claim(&selector).unwrap();
320        ctx.storage.tasks.spawn_root(root, ctx.claimed, async move {
321            let result = ctx
322                .timeout(Duration::from_millis(10), async {
323                    let _flag = FlagOnDrop::new(&DROPPED);
324                    pending::<()>().await;
325                })
326                .await
327                .unwrap();
328            let event = match result {
329                MaybeTimedOut::Timeout => 0,
330                MaybeTimedOut::Completed(()) => 1,
331            };
332            ctx.dispatch(event).unwrap();
333            pending::<()>().await;
334        });
335        assert_eq!(ctx.storage.tasks.run_ready(), Poll::Pending);
336        assert!(!DROPPED.load(Relaxed));
337        NOW.store(10, Relaxed);
338        wake_expired_timers(&ctx.storage.timers);
339        assert_eq!(ctx.storage.tasks.run_ready(), Poll::Pending);
340        assert_yields!(ctx.storage.events.iter_removing(), [0]);
341        assert!(DROPPED.load(Relaxed));
342        assert_eq!(ctx.storage.timers.next_deadline(), None);
343        ctx.clear();
344    }
345
346    #[test]
347    fn ready_future_beats_a_zero_timeout() {
348        static STORAGE: Storage = Storage::new();
349        let selector = Selector::new().unwrap();
350        let ctx = STORAGE.claim(&selector).unwrap().0;
351        let mut cx = Context::from_waker(Waker::noop());
352        let mut timeout = pin!(ctx.timeout(Duration::ZERO, async {
353            let value = 1;
354            let borrowed = &value;
355            core::future::ready(()).await;
356            *borrowed
357        }));
358        assert_eq!(
359            timeout.as_mut().poll(&mut cx),
360            Poll::Ready(Ok(MaybeTimedOut::Completed(1)))
361        );
362        assert_eq!(ctx.storage.timers.next_deadline(), None);
363    }
364
365    #[test]
366    fn pending_pinned_future_keeps_its_timer_until_dropped() {
367        static STORAGE: Storage = Storage::new();
368        let selector = Selector::new().unwrap();
369        let ctx = STORAGE.claim(&selector).unwrap().0;
370        let mut cx = Context::from_waker(Waker::noop());
371        {
372            let mut timeout = pin!(ctx.timeout(Duration::from_secs(60), async {
373                let value = 1;
374                let borrowed = &value;
375                pending::<()>().await;
376                *borrowed
377            }));
378            assert_eq!(timeout.as_mut().poll(&mut cx), Poll::Pending);
379            assert_eq!(timeout.as_mut().poll(&mut cx), Poll::Pending);
380            assert!(ctx.storage.timers.next_deadline().is_some());
381        }
382        assert_eq!(ctx.storage.timers.next_deadline(), None);
383    }
384
385    #[test]
386    fn sleeps_complete_in_deadline_order() {
387        static NOW: AtomicU64 = AtomicU64::new(0);
388        fn now() -> Instant {
389            fake_instant(&NOW)
390        }
391        static STORAGE: Storage = Storage::with_clock(now);
392        let selector = Selector::new().unwrap();
393        let (ctx, root) = STORAGE.claim(&selector).unwrap();
394        ctx.storage.tasks.spawn_root(root, ctx.claimed, async move {
395            let handles = [300, 100, 200].map(|ms| {
396                ctx.spawn(async move |ctx| {
397                    ctx.sleep(Duration::from_millis(ms)).await.unwrap();
398                    ctx.dispatch(u32::try_from(ms).unwrap()).unwrap();
399                })
400                .unwrap()
401            });
402            for handle in handles {
403                handle.await;
404            }
405        });
406        assert_eq!(ctx.storage.tasks.run_ready(), Poll::Pending);
407        NOW.store(300, Relaxed);
408        wake_expired_timers(&ctx.storage.timers);
409        assert_eq!(ctx.storage.tasks.run_ready(), Poll::Ready(()));
410        assert_yields!(ctx.storage.events.iter_removing(), [100, 200, 300]);
411        ctx.clear();
412    }
413}