externally-driven-async-rt 0.5.0

Async runtime that is meant to be embedded
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use core::{future::Future, time::Duration};

use crate::{
    Either2, EventLoopError, NotEnoughResources,
    claimed::Claimed,
    select2,
    selector::{EVENTS_PER_CALL, Selector, SelectorEvent},
    storage::LoopStorage,
    tasks::{SlotWaiterTakenError, TaskReservation},
};

/// A handle of the event loop that you are currently in.
///
/// Used to spawn tasks, sleep, dispatch events to the external world and start IO operations.
///
/// # Panics
///
/// Wakers can only be woken on the same thread that created an
/// [`EventLoop`](crate::EventLoop), otherwise waking panics.
#[must_use]
pub struct Context<
    'sel,
    E: 'static,
    const EVENTS: usize,
    const TASKS: usize,
    const TASK_SIZE: usize,
    const ROOT_TASK_SIZE: usize,
    const TIMERS: usize,
    const FDS: usize,
> {
    pub(crate) storage:
        &'static LoopStorage<E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
    pub(crate) selector: &'sel Selector,
    pub(crate) claimed: Claimed<'sel>,
}

impl<
    'sel,
    E: 'static,
    const EVENTS: usize,
    const TASKS: usize,
    const TASK_SIZE: usize,
    const ROOT_TASK_SIZE: usize,
    const TIMERS: usize,
    const FDS: usize,
> Context<'sel, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
{
    /// Pushes given `event` into the queue that [`EventLoop::events`](crate::EventLoop::events)
    /// pops from.
    ///
    /// # Errors
    ///
    /// Returns `event` back if the queue already holds `EVENTS` events.
    pub fn dispatch(&self, event: E) -> Result<(), E> {
        self.storage.events.push(event)
    }

    /// Spawns a task with a given async closure.
    ///
    /// The future must fit `TASK_SIZE` bytes and be aligned to at most 16 bytes, otherwise the
    /// program doesn't compile.
    ///
    /// Returns a join handle, a future that resolves once the task is finished. Dropping it
    /// detaches the task, which keeps running until it finishes.
    ///
    /// # Errors
    ///
    /// Returns an error if all `TASKS` task slots are taken, the future returned by `f` is dropped
    /// without being polled then. Use [`reserve_task`](Self::reserve_task) to wait for a free
    /// slot instead.
    pub fn spawn<F, Fut>(
        &self,
        f: F,
    ) -> Result<
        impl Future<Output = ()> + use<E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS, F, Fut>,
        NotEnoughResources,
    >
    where
        F: FnOnce(Self) -> Fut,
        Fut: Future<Output = ()> + 'sel,
    {
        self.storage.tasks.spawn(self.claimed, f(*self))
    }

    /// Reserves a task slot.
    ///
    /// This method returns a future that is resolved once a slot in the internal
    /// pool of tasks is available.
    ///
    /// The future stays pending until some other task finishes and frees a slot.
    ///
    /// # Errors
    ///
    /// Only one task can wait for a free slot at a time. The future resolves to
    /// [`SlotWaiterTakenError`](crate::SlotWaiterTakenError) if all `TASKS` slots are taken and another task already waits.
    ///
    /// # Cancel safety
    ///
    /// This method is cancel safe.
    pub fn reserve_task(
        &self,
    ) -> impl Future<
        Output = Result<
            TaskReservation<'sel, TASKS, TASK_SIZE, ROOT_TASK_SIZE>,
            SlotWaiterTakenError,
        >,
    > + use<'sel, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS> {
        self.storage.tasks.reserve(self.claimed)
    }

    /// Sleeps for `duration`.
    ///
    /// # Errors
    ///
    /// The returned future resolves to an error if all `TIMERS` timer slots are taken.
    ///
    /// # Cancel safety
    ///
    /// This method is cancel safe.
    pub fn sleep(
        &self,
        duration: Duration,
    ) -> impl Future<Output = Result<(), NotEnoughResources>>
    + use<'sel, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS> {
        let timers = &self.storage.timers;
        timers.sleep_until(timers.now().saturating_add(duration))
    }

    /// Runs `future` with a timeout of `duration`, resolves to `Ok(MaybeTimedOut::Timeout)` in case of a timeout.
    ///
    /// # Errors
    ///
    /// The returned future resolves to an error if all `TIMERS` timer slots are taken.
    ///
    /// # Cancel safety
    ///
    /// This method is cancel safe if `future` is.
    pub fn timeout<F: Future>(
        &self,
        duration: Duration,
        future: F,
    ) -> impl Future<Output = Result<MaybeTimedOut<F::Output>, NotEnoughResources>> {
        let sleep = self.sleep(duration);
        async move {
            match select2(future, sleep).await {
                Either2::Left(output) => Ok(MaybeTimedOut::Completed(output)),
                Either2::Right(Ok(())) => Ok(MaybeTimedOut::Timeout),
                Either2::Right(Err(err)) => Err(err),
            }
        }
    }

    /// Waits until [`EventLoop::notify`](crate::EventLoop::notify) is called.
    ///
    /// Notifications don't queue up: any number of `notify()` calls made before the future is
    /// polled resolve it only once.
    ///
    /// Only one task can wait for a notification at a time.
    ///
    /// # Cancel safety
    ///
    /// This method is cancel safe.
    pub fn notified(
        &self,
    ) -> impl Future<Output = ()> + use<'sel, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
    {
        self.storage.notification.notified()
    }

    pub(crate) fn clear(&self) {
        self.storage.tasks.drop_all();
        self.storage.timers.drop_wakers();
        self.storage.io_waiters.drop_wakers();
        self.storage.notification.clear();
        self.storage.events.clear();
    }

    pub(crate) fn drain(&self) -> Result<(), EventLoopError> {
        if !self.storage.tasks.has_root() {
            return Err(EventLoopError::RootFinished);
        }
        loop {
            self.process_selector_events()?;
            if !self.storage.tasks.has_woken() {
                break;
            }
            if self.storage.tasks.run_ready().is_ready() {
                self.storage.tasks.drop_all();
                self.flush()?;
                return Err(EventLoopError::RootFinished);
            }
        }
        self.flush()?;
        Ok(())
    }

    fn process_selector_events(&self) -> rustix::io::Result<()> {
        let mut events = [None; EVENTS_PER_CALL];
        loop {
            let full = self.selector.poll_nonblocking(&mut events)?;
            for event in events.iter().map_while(|event| *event) {
                match event {
                    SelectorEvent::Io { fd, ready } => {
                        self.storage.io_waiters.wake_ready(fd, ready);
                    }
                    SelectorEvent::Notify => self.storage.notification.fire(),
                    SelectorEvent::Timer => {
                        let now = self.storage.timers.now();
                        while let Some(waker) = self.storage.timers.take_expired(now) {
                            waker.wake();
                        }
                    }
                }
            }
            if !full {
                return Ok(());
            }
        }
    }

    pub(crate) fn flush(&self) -> rustix::io::Result<()> {
        self.selector.flush(
            self.storage.timers.next_deadline(),
            self.storage.timers.now(),
        )
    }
}

impl<
    E: 'static,
    const EVENTS: usize,
    const TASKS: usize,
    const TASK_SIZE: usize,
    const ROOT_TASK_SIZE: usize,
    const TIMERS: usize,
    const FDS: usize,
> Clone for Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
{
    fn clone(&self) -> Self {
        *self
    }
}

impl<
    E: 'static,
    const EVENTS: usize,
    const TASKS: usize,
    const TASK_SIZE: usize,
    const ROOT_TASK_SIZE: usize,
    const TIMERS: usize,
    const FDS: usize,
> Copy for Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
{
}

/// Result of the [`Context::timeout`]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MaybeTimedOut<T> {
    /// Operation has timed out.
    Timeout,
    /// Operation has completed.
    Completed(T),
}

#[cfg(test)]
mod tests {
    use core::{
        future::{Future, pending},
        pin::pin,
        sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed},
        task::{Context, Poll, Waker},
        time::Duration,
    };

    use super::MaybeTimedOut;
    use crate::{
        LoopStorage, Selector,
        testing::{FlagOnDrop, assert_yields, fake_instant, wake_expired_timers},
        time::Instant,
    };

    type Storage = LoopStorage<u32, 3, 3, 128, 512, 3, 1>;

    #[test]
    fn future_finishing_first_wins() {
        static STORAGE: Storage = Storage::new();
        let selector = Selector::new().unwrap();
        let (ctx, root) = STORAGE.claim(&selector).unwrap();
        ctx.storage.tasks.spawn_root(root, ctx.claimed, async move {
            let result = ctx
                .timeout(Duration::from_secs(60), ctx.notified())
                .await
                .unwrap();
            let event = match result {
                MaybeTimedOut::Timeout => 0,
                MaybeTimedOut::Completed(()) => 1,
            };
            ctx.dispatch(event).unwrap();
            pending::<()>().await;
        });
        assert_eq!(ctx.storage.tasks.run_ready(), Poll::Pending);
        assert!(ctx.storage.timers.next_deadline().is_some());
        ctx.storage.notification.fire();
        assert_eq!(ctx.storage.tasks.run_ready(), Poll::Pending);
        assert_yields!(ctx.storage.events.iter_removing(), [1]);
        assert_eq!(ctx.storage.timers.next_deadline(), None);
        ctx.clear();
    }

    #[test]
    fn elapsing_drops_the_future() {
        static DROPPED: AtomicBool = AtomicBool::new(false);
        static NOW: AtomicU64 = AtomicU64::new(0);
        fn now() -> Instant {
            fake_instant(&NOW)
        }
        static STORAGE: Storage = Storage::with_clock(now);
        let selector = Selector::new().unwrap();
        let (ctx, root) = STORAGE.claim(&selector).unwrap();
        ctx.storage.tasks.spawn_root(root, ctx.claimed, async move {
            let result = ctx
                .timeout(Duration::from_millis(10), async {
                    let _flag = FlagOnDrop::new(&DROPPED);
                    pending::<()>().await;
                })
                .await
                .unwrap();
            let event = match result {
                MaybeTimedOut::Timeout => 0,
                MaybeTimedOut::Completed(()) => 1,
            };
            ctx.dispatch(event).unwrap();
            pending::<()>().await;
        });
        assert_eq!(ctx.storage.tasks.run_ready(), Poll::Pending);
        assert!(!DROPPED.load(Relaxed));
        NOW.store(10, Relaxed);
        wake_expired_timers(&ctx.storage.timers);
        assert_eq!(ctx.storage.tasks.run_ready(), Poll::Pending);
        assert_yields!(ctx.storage.events.iter_removing(), [0]);
        assert!(DROPPED.load(Relaxed));
        assert_eq!(ctx.storage.timers.next_deadline(), None);
        ctx.clear();
    }

    #[test]
    fn ready_future_beats_a_zero_timeout() {
        static STORAGE: Storage = Storage::new();
        let selector = Selector::new().unwrap();
        let ctx = STORAGE.claim(&selector).unwrap().0;
        let mut cx = Context::from_waker(Waker::noop());
        let mut timeout = pin!(ctx.timeout(Duration::ZERO, async {
            let value = 1;
            let borrowed = &value;
            core::future::ready(()).await;
            *borrowed
        }));
        assert_eq!(
            timeout.as_mut().poll(&mut cx),
            Poll::Ready(Ok(MaybeTimedOut::Completed(1)))
        );
        assert_eq!(ctx.storage.timers.next_deadline(), None);
    }

    #[test]
    fn pending_pinned_future_keeps_its_timer_until_dropped() {
        static STORAGE: Storage = Storage::new();
        let selector = Selector::new().unwrap();
        let ctx = STORAGE.claim(&selector).unwrap().0;
        let mut cx = Context::from_waker(Waker::noop());
        {
            let mut timeout = pin!(ctx.timeout(Duration::from_secs(60), async {
                let value = 1;
                let borrowed = &value;
                pending::<()>().await;
                *borrowed
            }));
            assert_eq!(timeout.as_mut().poll(&mut cx), Poll::Pending);
            assert_eq!(timeout.as_mut().poll(&mut cx), Poll::Pending);
            assert!(ctx.storage.timers.next_deadline().is_some());
        }
        assert_eq!(ctx.storage.timers.next_deadline(), None);
    }

    #[test]
    fn sleeps_complete_in_deadline_order() {
        static NOW: AtomicU64 = AtomicU64::new(0);
        fn now() -> Instant {
            fake_instant(&NOW)
        }
        static STORAGE: Storage = Storage::with_clock(now);
        let selector = Selector::new().unwrap();
        let (ctx, root) = STORAGE.claim(&selector).unwrap();
        ctx.storage.tasks.spawn_root(root, ctx.claimed, async move {
            let handles = [300, 100, 200].map(|ms| {
                ctx.spawn(async move |ctx| {
                    ctx.sleep(Duration::from_millis(ms)).await.unwrap();
                    ctx.dispatch(u32::try_from(ms).unwrap()).unwrap();
                })
                .unwrap()
            });
            for handle in handles {
                handle.await;
            }
        });
        assert_eq!(ctx.storage.tasks.run_ready(), Poll::Pending);
        NOW.store(300, Relaxed);
        wake_expired_timers(&ctx.storage.timers);
        assert_eq!(ctx.storage.tasks.run_ready(), Poll::Ready(()));
        assert_yields!(ctx.storage.events.iter_removing(), [100, 200, 300]);
        ctx.clear();
    }
}