1use core::{future::Future, time::Duration};
2
3use crate::{
4 Either2, NotEnoughResources,
5 claimed::Claimed,
6 select2,
7 selector::{EVENTS_PER_CALL, Selector, SelectorEvent},
8 storage::LoopStorage,
9 tasks::{SlotWaiterTakenError, TaskReservation},
10};
11
12#[must_use]
21pub struct Context<
22 'a,
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: &'a Selector,
34 pub(crate) claimed: Claimed<'a>,
35}
36
37impl<
38 'a,
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<'a, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
47{
48 pub fn dispatch(&self, event: E) -> Result<(), E> {
55 self.storage.events.push(event)
56 }
57
58 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 = ()> + 'a,
81 {
82 self.storage.tasks.spawn(self.claimed, f(*self))
83 }
84
85 pub fn reserve_task(
101 &self,
102 ) -> impl Future<
103 Output = Result<
104 TaskReservation<'a, TASKS, TASK_SIZE, ROOT_TASK_SIZE>,
105 SlotWaiterTakenError,
106 >,
107 > + use<'a, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS> {
108 self.storage.tasks.reserve(self.claimed)
109 }
110
111 pub fn sleep(
121 &self,
122 duration: Duration,
123 ) -> impl Future<Output = Result<(), NotEnoughResources>>
124 + use<'a, 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 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 pub fn notified(
164 &self,
165 ) -> impl Future<Output = ()> + use<'a, 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 process_selector_events(&self) -> rustix::io::Result<()> {
179 let mut events = [None; EVENTS_PER_CALL];
180 loop {
181 let full = self.selector.poll_nonblocking(&mut events)?;
182 for event in events.iter().map_while(|event| *event) {
183 match event {
184 SelectorEvent::Io { fd, ready } => {
185 self.storage.io_waiters.wake_ready(fd, ready);
186 }
187 SelectorEvent::Notify => self.storage.notification.fire(),
188 SelectorEvent::Timer => {
189 let now = self.storage.timers.now();
190 while let Some(waker) = self.storage.timers.take_expired(now) {
191 waker.wake();
192 }
193 }
194 }
195 }
196 if !full {
197 return Ok(());
198 }
199 }
200 }
201
202 pub(crate) fn flush(&self) -> rustix::io::Result<()> {
203 self.selector.flush(
204 self.storage.io_waiters.pending_changes(),
205 self.storage.timers.next_deadline(),
206 self.storage.timers.now(),
207 )?;
208 self.storage.io_waiters.mark_flushed();
209 Ok(())
210 }
211}
212
213impl<
214 E: 'static,
215 const EVENTS: usize,
216 const TASKS: usize,
217 const TASK_SIZE: usize,
218 const ROOT_TASK_SIZE: usize,
219 const TIMERS: usize,
220 const FDS: usize,
221> Clone for Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
222{
223 fn clone(&self) -> Self {
224 *self
225 }
226}
227
228impl<
229 E: 'static,
230 const EVENTS: usize,
231 const TASKS: usize,
232 const TASK_SIZE: usize,
233 const ROOT_TASK_SIZE: usize,
234 const TIMERS: usize,
235 const FDS: usize,
236> Copy for Context<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
237{
238}
239
240#[derive(Debug, Clone, Copy, PartialEq, Eq)]
242pub enum MaybeTimedOut<T> {
243 Timeout,
245 Completed(T),
247}
248
249#[cfg(test)]
250mod tests {
251 use core::{
252 future::{Future, pending},
253 pin::pin,
254 sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed},
255 task::{Context, Poll, Waker},
256 time::Duration,
257 };
258
259 use super::MaybeTimedOut;
260 use crate::{
261 LoopStorage, Selector,
262 testing::{FlagOnDrop, assert_yields, fake_instant, wake_expired_timers},
263 time::Instant,
264 };
265
266 type Storage = LoopStorage<u32, 3, 3, 128, 512, 3, 1>;
267
268 #[test]
269 fn future_finishing_first_wins() {
270 static STORAGE: Storage = Storage::new();
271 let selector = Selector::new().unwrap();
272 let (ctx, root) = STORAGE.claim(&selector).unwrap();
273 ctx.storage.tasks.spawn_root(root, ctx.claimed, async move {
274 let result = ctx
275 .timeout(Duration::from_secs(60), ctx.notified())
276 .await
277 .unwrap();
278 let event = match result {
279 MaybeTimedOut::Timeout => 0,
280 MaybeTimedOut::Completed(()) => 1,
281 };
282 ctx.dispatch(event).unwrap();
283 pending::<()>().await;
284 });
285 assert_eq!(ctx.storage.tasks.run_ready(), Poll::Pending);
286 assert!(ctx.storage.timers.next_deadline().is_some());
287 ctx.storage.notification.fire();
288 assert_eq!(ctx.storage.tasks.run_ready(), Poll::Pending);
289 assert_yields!(ctx.storage.events.iter_removing(), [1]);
290 assert_eq!(ctx.storage.timers.next_deadline(), None);
291 ctx.clear();
292 }
293
294 #[test]
295 fn elapsing_drops_the_future() {
296 static DROPPED: AtomicBool = AtomicBool::new(false);
297 static NOW: AtomicU64 = AtomicU64::new(0);
298 fn now() -> Instant {
299 fake_instant(&NOW)
300 }
301 static STORAGE: Storage = Storage::with_clock(now);
302 let selector = Selector::new().unwrap();
303 let (ctx, root) = STORAGE.claim(&selector).unwrap();
304 ctx.storage.tasks.spawn_root(root, ctx.claimed, async move {
305 let result = ctx
306 .timeout(Duration::from_millis(10), async {
307 let _flag = FlagOnDrop::new(&DROPPED);
308 pending::<()>().await;
309 })
310 .await
311 .unwrap();
312 let event = match result {
313 MaybeTimedOut::Timeout => 0,
314 MaybeTimedOut::Completed(()) => 1,
315 };
316 ctx.dispatch(event).unwrap();
317 pending::<()>().await;
318 });
319 assert_eq!(ctx.storage.tasks.run_ready(), Poll::Pending);
320 assert!(!DROPPED.load(Relaxed));
321 NOW.store(10, Relaxed);
322 wake_expired_timers(&ctx.storage.timers);
323 assert_eq!(ctx.storage.tasks.run_ready(), Poll::Pending);
324 assert_yields!(ctx.storage.events.iter_removing(), [0]);
325 assert!(DROPPED.load(Relaxed));
326 assert_eq!(ctx.storage.timers.next_deadline(), None);
327 ctx.clear();
328 }
329
330 #[test]
331 fn ready_future_beats_a_zero_timeout() {
332 static STORAGE: Storage = Storage::new();
333 let selector = Selector::new().unwrap();
334 let ctx = STORAGE.claim(&selector).unwrap().0;
335 let mut cx = Context::from_waker(Waker::noop());
336 let mut timeout = pin!(ctx.timeout(Duration::ZERO, async {
337 let value = 1;
338 let borrowed = &value;
339 core::future::ready(()).await;
340 *borrowed
341 }));
342 assert_eq!(
343 timeout.as_mut().poll(&mut cx),
344 Poll::Ready(Ok(MaybeTimedOut::Completed(1)))
345 );
346 assert_eq!(ctx.storage.timers.next_deadline(), None);
347 }
348
349 #[test]
350 fn pending_pinned_future_keeps_its_timer_until_dropped() {
351 static STORAGE: Storage = Storage::new();
352 let selector = Selector::new().unwrap();
353 let ctx = STORAGE.claim(&selector).unwrap().0;
354 let mut cx = Context::from_waker(Waker::noop());
355 {
356 let mut timeout = pin!(ctx.timeout(Duration::from_secs(60), async {
357 let value = 1;
358 let borrowed = &value;
359 pending::<()>().await;
360 *borrowed
361 }));
362 assert_eq!(timeout.as_mut().poll(&mut cx), Poll::Pending);
363 assert_eq!(timeout.as_mut().poll(&mut cx), Poll::Pending);
364 assert!(ctx.storage.timers.next_deadline().is_some());
365 }
366 assert_eq!(ctx.storage.timers.next_deadline(), None);
367 }
368
369 #[test]
370 fn sleeps_complete_in_deadline_order() {
371 static NOW: AtomicU64 = AtomicU64::new(0);
372 fn now() -> Instant {
373 fake_instant(&NOW)
374 }
375 static STORAGE: Storage = Storage::with_clock(now);
376 let selector = Selector::new().unwrap();
377 let (ctx, root) = STORAGE.claim(&selector).unwrap();
378 ctx.storage.tasks.spawn_root(root, ctx.claimed, async move {
379 let handles = [300, 100, 200].map(|ms| {
380 ctx.spawn(async move |ctx| {
381 ctx.sleep(Duration::from_millis(ms)).await.unwrap();
382 ctx.dispatch(u32::try_from(ms).unwrap()).unwrap();
383 })
384 .unwrap()
385 });
386 for handle in handles {
387 handle.await;
388 }
389 });
390 assert_eq!(ctx.storage.tasks.run_ready(), Poll::Pending);
391 NOW.store(300, Relaxed);
392 wake_expired_timers(&ctx.storage.timers);
393 assert_eq!(ctx.storage.tasks.run_ready(), Poll::Ready(()));
394 assert_yields!(ctx.storage.events.iter_removing(), [100, 200, 300]);
395 ctx.clear();
396 }
397}