Skip to main content

dope_core/executor/task/time/
budget.rs

1//! One absolute time budget backed by one reusable driver timer slot.
2
3use core::{pin, task};
4use std::{mem, time};
5
6use crate::{
7    driver::schedule::clock::{self, timer},
8    executor::task::{Fiber, context},
9};
10
11/// Failure to construct an absolute budget in one driver time domain.
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13pub enum Error {
14    /// The absolute deadline is outside the monotonic clock range.
15    Range(clock::Range),
16    /// The fixed timer store has no slot for this logical budget.
17    Capacity(timer::Exhausted),
18}
19
20/// The bound that elapsed before an operation completed.
21#[derive(Clone, Copy, Debug, Eq, PartialEq)]
22#[repr(u8)]
23pub enum Elapsed {
24    /// The enclosing absolute budget elapsed.
25    Budget,
26    /// A narrower operation limit elapsed.
27    Limit,
28}
29
30/// One absolute multi-operation budget tied to an exact driver generation.
31pub struct Budget<'d> {
32    deadline: clock::Deadline<'d>,
33    alarm: timer::Alarm<'d>,
34}
35
36/// One narrowed deadline borrowing its enclosing budget's timer slot.
37pub struct Scope<'budget, 'd: 'budget> {
38    deadline: clock::Deadline<'d>,
39    alarm: &'budget mut timer::Alarm<'d>,
40    elapsed: Elapsed,
41}
42
43#[pin_project::pin_project(PinnedDrop)]
44#[doc(hidden)]
45#[must_use = "a fiber does nothing unless it is driven"]
46pub struct Timeout<'scope, 'd, F> {
47    alarm: &'scope mut timer::Alarm<'d>,
48    deadline: clock::Deadline<'d>,
49    state: State,
50    limit: Option<time::Duration>,
51    #[pin]
52    fiber: F,
53}
54
55enum State {
56    Idle(Elapsed),
57    Armed(Elapsed),
58    Settled,
59}
60
61#[doc(hidden)]
62#[must_use = "a fiber does nothing unless it is driven"]
63pub struct Sleep<'scope, 'd> {
64    alarm: &'scope timer::Alarm<'d>,
65    deadline: clock::Deadline<'d>,
66    state: SleepState,
67}
68
69enum SleepState {
70    New(time::Duration, Elapsed),
71    Armed(Result<(), Elapsed>),
72    Settled,
73}
74
75impl Elapsed {
76    fn narrow<'d>(
77        self,
78        deadline: clock::Deadline<'d>,
79        now: clock::Moment<'d>,
80        duration: time::Duration,
81    ) -> (clock::Deadline<'d>, Self) {
82        let limit = now.try_add(duration).unwrap_or(deadline);
83        if limit < deadline {
84            (limit, Self::Limit)
85        } else {
86            (deadline, self)
87        }
88    }
89}
90
91impl<'d> Budget<'d> {
92    /// Constructs one absolute budget and reserves its timer slot once.
93    pub fn try_new(
94        timer: timer::Timer<'d>,
95        started: clock::Moment<'d>,
96        duration: time::Duration,
97    ) -> Result<Self, Error> {
98        let deadline = started.try_add(duration).map_err(Error::Range)?;
99        let alarm = timer.try_alarm().map_err(Error::Capacity)?;
100        Ok(Self { deadline, alarm })
101    }
102
103    /// Samples a finite operation limit once without changing the driver clock.
104    /// `Duration::MAX` keeps the enclosing bound without sampling.
105    pub fn scope(&mut self, sample: clock::Moment<'d>, duration: time::Duration) -> Scope<'_, 'd> {
106        if duration == time::Duration::MAX {
107            return Scope {
108                deadline: self.deadline,
109                alarm: &mut self.alarm,
110                elapsed: Elapsed::Budget,
111            };
112        }
113        self.limit(sample.moment_at(time::Instant::now()), duration)
114    }
115
116    /// Narrows this budget without reserving another timer slot.
117    pub fn limit(&mut self, now: clock::Moment<'d>, duration: time::Duration) -> Scope<'_, 'd> {
118        let (deadline, elapsed) = Elapsed::Budget.narrow(self.deadline, now, duration);
119        Scope {
120            deadline,
121            alarm: &mut self.alarm,
122            elapsed,
123        }
124    }
125
126    /// Runs one fiber under this budget's absolute deadline.
127    pub fn timeout<'scope, F>(&'scope mut self, fiber: F) -> Timeout<'scope, 'd, F>
128    where
129        F: Fiber<'d> + 'scope,
130    {
131        Timeout::new(&mut self.alarm, self.deadline, Elapsed::Budget, None, fiber)
132    }
133
134    /// Runs one fiber under the earlier of this budget and a relative limit.
135    pub fn timeout_for<'scope, F>(
136        &'scope mut self,
137        duration: time::Duration,
138        fiber: F,
139    ) -> Timeout<'scope, 'd, F>
140    where
141        F: Fiber<'d> + 'scope,
142    {
143        Timeout::new(
144            &mut self.alarm,
145            self.deadline,
146            Elapsed::Budget,
147            Some(duration),
148            fiber,
149        )
150    }
151
152    /// Waits without reserving another timer slot.
153    pub fn sleep(&mut self, duration: time::Duration) -> Sleep<'_, 'd> {
154        Sleep::new(&mut self.alarm, self.deadline, Elapsed::Budget, duration)
155    }
156}
157
158impl<'budget, 'd: 'budget> Scope<'budget, 'd> {
159    /// Copies this scope's selected deadline and exact elapsed cause.
160    pub const fn checkpoint(&self) -> clock::Check<'d, Elapsed> {
161        clock::Check::new(self.deadline, self.elapsed)
162    }
163
164    /// Runs one fiber under this scope's absolute deadline.
165    pub fn timeout<'scope, F>(&'scope mut self, fiber: F) -> Timeout<'scope, 'd, F>
166    where
167        F: Fiber<'d> + 'scope,
168    {
169        Timeout::new(&mut *self.alarm, self.deadline, self.elapsed, None, fiber)
170    }
171
172    /// Waits without reserving another timer slot.
173    pub fn sleep(&mut self, duration: time::Duration) -> Sleep<'_, 'd> {
174        Sleep::new(&mut *self.alarm, self.deadline, self.elapsed, duration)
175    }
176}
177
178impl<'scope, 'd> Sleep<'scope, 'd> {
179    fn new(
180        alarm: &'scope mut timer::Alarm<'d>,
181        deadline: clock::Deadline<'d>,
182        elapsed: Elapsed,
183        duration: time::Duration,
184    ) -> Self {
185        Self {
186            alarm,
187            deadline,
188            state: SleepState::New(duration, elapsed),
189        }
190    }
191}
192
193impl<'d> Fiber<'d> for Sleep<'_, 'd> {
194    type Output = Result<(), Elapsed>;
195
196    fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> task::Poll<Self::Output> {
197        let (this, context) = call.into_parts();
198        let this = this.get_mut();
199        let now = context.driver().driver_ref().clock().now();
200        let wake = context.completion();
201        let (outcome, polled) = match this.state {
202            SleepState::New(duration, elapsed) => {
203                let limited = now.try_add(duration).unwrap_or(this.deadline);
204                let (next, outcome) = if limited < this.deadline {
205                    (limited, Ok(()))
206                } else {
207                    (this.deadline, Err(elapsed))
208                };
209                this.state = SleepState::Armed(outcome);
210                (outcome, this.alarm.arm_and_poll(next, now, wake))
211            }
212            SleepState::Armed(outcome) => (outcome, this.alarm.poll(now, wake)),
213            SleepState::Settled => return task::Poll::Pending,
214        };
215        if polled.is_pending() {
216            task::Poll::Pending
217        } else {
218            this.state = SleepState::Settled;
219            task::Poll::Ready(outcome)
220        }
221    }
222}
223
224impl Drop for Sleep<'_, '_> {
225    fn drop(&mut self) {
226        if matches!(self.state, SleepState::Armed(_)) {
227            self.alarm.clear();
228        }
229    }
230}
231
232impl<'scope, 'd, F> Timeout<'scope, 'd, F> {
233    fn new(
234        alarm: &'scope mut timer::Alarm<'d>,
235        deadline: clock::Deadline<'d>,
236        elapsed: Elapsed,
237        limit: Option<time::Duration>,
238        fiber: F,
239    ) -> Self {
240        Self {
241            alarm,
242            deadline,
243            state: State::Idle(elapsed),
244            limit,
245            fiber,
246        }
247    }
248}
249
250impl<'d, F> Fiber<'d> for Timeout<'_, 'd, F>
251where
252    F: Fiber<'d>,
253{
254    type Output = Result<F::Output, Elapsed>;
255
256    fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> task::Poll<Self::Output> {
257        use core::task::Poll;
258
259        let (this, context) = call.into_parts();
260        let this = this.project();
261        let now = context.driver().driver_ref().clock().now();
262        let wake = context.completion();
263        match *this.state {
264            State::Idle(elapsed) => {
265                let (due, elapsed) = match *this.limit {
266                    Some(duration) => elapsed.narrow(*this.deadline, now, duration),
267                    None => (*this.deadline, elapsed),
268                };
269                if this.alarm.arm_and_poll(due, now, wake).is_ready() {
270                    *this.state = State::Settled;
271                    return Poll::Ready(Err(elapsed));
272                }
273                *this.state = State::Armed(elapsed);
274            }
275            State::Armed(elapsed) => {
276                if this.alarm.poll(now, wake).is_ready() {
277                    *this.state = State::Settled;
278                    return Poll::Ready(Err(elapsed));
279                }
280            }
281            State::Settled => return Poll::Pending,
282        }
283        match F::poll(context::PollCall {
284            fiber: this.fiber,
285            context,
286        }) {
287            Poll::Ready(output) => {
288                this.alarm.clear();
289                *this.state = State::Settled;
290                Poll::Ready(Ok(output))
291            }
292            Poll::Pending => Poll::Pending,
293        }
294    }
295}
296
297#[pin_project::pinned_drop]
298impl<F> PinnedDrop for Timeout<'_, '_, F> {
299    fn drop(self: pin::Pin<&mut Self>) {
300        let this = self.project();
301        if matches!(*this.state, State::Armed(_)) {
302            this.alarm.clear();
303        }
304    }
305}
306
307const _: () = {
308    assert!(mem::size_of::<Error>() <= mem::size_of::<clock::Range>() + mem::size_of::<usize>());
309    assert!(mem::size_of::<Elapsed>() == 1);
310    assert!(mem::size_of::<State>() <= 2);
311    assert!(
312        mem::size_of::<Budget<'static>>()
313            == mem::size_of::<time::Instant>() + mem::size_of::<timer::Alarm<'static>>()
314    );
315    assert!(mem::size_of::<Scope<'static, 'static>>() == 2 * mem::size_of::<time::Instant>());
316};