Skip to main content

dope_core/executor/drive/
block.rs

1use o3::mem::slot;
2use std::{
3    mem::{self, MaybeUninit},
4    ops::ControlFlow,
5    pin, task, time,
6};
7
8use crate::driver::{self, result::poll, route, route::indices, schedule, schedule::ready};
9use drive::{clock, clock::Time as _, turn};
10use schedule::clock::Moment;
11use turn::{routes, scope};
12
13use crate::executor::{self, boot, drive, root};
14
15/// Evidence that one root and its installed application reached a fixed point.
16#[must_use = "fixed-point evidence and its root output must be observed"]
17pub struct Fixed<'d, T> {
18    output: T,
19    now: Moment<'d>,
20}
21
22impl<'d, T> Fixed<'d, T> {
23    pub(crate) const fn new(output: T, now: Moment<'d>) -> Self {
24        Self { output, now }
25    }
26
27    pub const fn output(&self) -> &T {
28        &self.output
29    }
30
31    pub fn into_output(self) -> T {
32        self.output
33    }
34
35    pub const fn now(&self) -> Moment<'d> {
36        self.now
37    }
38}
39
40const _: () = {
41    assert!(mem::size_of::<Fixed<'_, ()>>() == mem::size_of::<Moment<'_>>());
42    assert!(mem::align_of::<Fixed<'_, ()>>() == mem::align_of::<Moment<'_>>());
43};
44
45enum Attempt<R, O> {
46    Complete(Result<O, drive::Error>),
47    Cancel(R, drive::Error),
48}
49
50enum Outcome<O, P> {
51    Complete(O, P),
52    Shutdown(Option<O>),
53}
54
55impl<O, P> Outcome<O, P> {
56    fn complete(self) -> Result<(O, P), drive::Error> {
57        match self {
58            Self::Complete(output, proof) => Ok((output, proof)),
59            Self::Shutdown(_) => Err(drive::Error::Shutdown),
60        }
61    }
62}
63
64impl<R, O> Attempt<R, O> {
65    fn finish<'d>(self) -> Result<O, drive::Error>
66    where
67        R: boot::Root<'d, Output = O>,
68    {
69        match self {
70            Self::Complete(result) => result,
71            Self::Cancel(root, source) => {
72                R::cancel(root);
73                Err(source)
74            }
75        }
76    }
77}
78
79pub(crate) fn run_boot<'run, 'd, R, Q, Report: crate::io::Report>(
80    state: Result<scope::Boot<'run, 'd, Report>, drive::Error>,
81    mut root: R,
82    observer: &Q,
83) -> Result<R::Output, drive::Error>
84where
85    R: boot::Root<'d>,
86    Q: executor::Startup,
87{
88    'run: {
89        let mut state = match state {
90            Ok(state) => state,
91            Err(error) => break 'run Attempt::Cancel(root, error),
92        };
93        let slot = match make_slot(state.driver_ref()) {
94            Ok(slot) => slot,
95            Err(error) => break 'run Attempt::Cancel(root, error),
96        };
97        let source = clock::wall();
98        let wake = slot.target();
99        let driver = state.driver_ref();
100        let mut cause = boot::Cause::Start;
101        loop {
102            let tick = source.start();
103            let mut core = state.begin(tick);
104            let (events, status) = match core.dispatch_native::<Q, Q>((), observer) {
105                Ok(result) => result,
106                Err(source) => break 'run Attempt::Cancel(root, source),
107            };
108            let observed = slot.take();
109            if matches!(cause, boot::Cause::Start) || matches!(observed, ready::Readiness::Ready) {
110                let context = boot::Context::new(wake, core.turn.turn().app(), cause);
111                match R::poll(root, context) {
112                    boot::Poll::Pending(next) => root = next,
113                    boot::Poll::Ready(output) => {
114                        let mut events = events;
115                        let mut status = status;
116                        break 'run Attempt::Complete('finish: loop {
117                            let idle = match core.park(events, status) {
118                                Ok(ControlFlow::Continue(idle)) => idle,
119                                Ok(ControlFlow::Break(())) => break Err(drive::Error::Shutdown),
120                                Err(error) => break Err(error.into()),
121                            };
122                            if idle {
123                                'wait: {
124                                    let span = if driver.has_deferred() {
125                                        Some(time::Duration::ZERO)
126                                    } else {
127                                        let Some(deadline) = driver.timer().earliest() else {
128                                            match core.sync() {
129                                                Ok(poll::Commit::Drained) => {
130                                                    break 'finish Ok(output);
131                                                }
132                                                Ok(poll::Commit::Pending) => break 'wait,
133                                                Err(error) => break 'finish Err(error.into()),
134                                            }
135                                        };
136                                        if core.quiet() {
137                                            Some(source.timeout(deadline))
138                                        } else {
139                                            Some(time::Duration::ZERO)
140                                        }
141                                    };
142                                    if let Err(error) = core.wait_for(span, source) {
143                                        break 'finish Err(error.into());
144                                    }
145                                }
146                            }
147                            drop(core);
148                            core = state.begin(source.start());
149                            (events, status) = match core.dispatch_native::<Q, Q>((), observer) {
150                                Ok(result) => result,
151                                Err(error) => break Err(error),
152                            };
153                            // Clear late readiness without polling the completed root again.
154                            let _ready = slot.take();
155                        });
156                    }
157                }
158            }
159            cause = boot::Cause::Wake;
160            let idle = match core.park(events, status) {
161                Ok(ControlFlow::Continue(idle)) => idle,
162                Ok(ControlFlow::Break(())) => {
163                    break 'run Attempt::Cancel(root, drive::Error::Shutdown);
164                }
165                Err(error) => break 'run Attempt::Cancel(root, error.into()),
166            };
167            if !idle {
168                continue;
169            }
170            let span = if core.quiet() && !driver.has_deferred() {
171                driver.timer().earliest().map(|due| source.timeout(due))
172            } else {
173                Some(time::Duration::ZERO)
174            };
175            if let Err(error) = core.wait_for(span, source) {
176                break 'run Attempt::Cancel(root, error.into());
177            }
178        }
179    }
180    .finish()
181}
182
183fn make_slot<'d>(
184    driver: driver::Reference<'d>,
185) -> Result<ready::Slot<'d, routes::Wake>, drive::Error> {
186    let target = driver
187        .targets::<routes::Wake>()
188        .bind(indices::SlotIndex::ZERO, route::Epoch::INITIAL);
189    Ok(driver.ready().make_slot(target.dispatch())?)
190}
191
192impl<'run, 'app, 'd: 'app, D, S, Report: crate::io::Report>
193    scope::Scope<'run, 'app, 'd, D, S, Report>
194where
195    D: executor::raw::App<'d>,
196{
197    pub(crate) fn run<R, C, Q, O>(
198        self,
199        source: C,
200        root: R,
201        observer: &O,
202    ) -> Result<R::Output, drive::Error>
203    where
204        R: root::Root<'d>,
205        C: clock::Time,
206        O: executor::Startup<Q>,
207    {
208        let (output, _) = self
209            .drive::<R, C, Q, O>(source, root, observer)?
210            .complete()?;
211        Ok(output)
212    }
213
214    pub(crate) fn run_until<R, C, Q>(
215        self,
216        source: C,
217        root: R,
218        observer: &Q,
219    ) -> Result<ControlFlow<R::Output>, drive::Error>
220    where
221        R: root::Root<'d>,
222        C: clock::Time,
223        Q: executor::Startup,
224    {
225        Ok(match self.drive::<R, C, Q, Q>(source, root, observer)? {
226            Outcome::Complete(output, _) | Outcome::Shutdown(Some(output)) => {
227                ControlFlow::Break(output)
228            }
229            Outcome::Shutdown(None) => ControlFlow::Continue(()),
230        })
231    }
232
233    pub(crate) fn run_fixed<R, C, Q>(
234        self,
235        source: C,
236        root: R,
237        observer: &Q,
238    ) -> Result<Fixed<'d, R::Output>, drive::Error>
239    where
240        R: root::Root<'d>,
241        Q: executor::Startup,
242        C: clock::Time<Proof<'d> = Moment<'d>>,
243    {
244        let (output, now) = self
245            .drive::<R, C, Q, Q>(source, root, observer)?
246            .complete()?;
247        Ok(Fixed::new(output, now))
248    }
249
250    fn drive<R, C, Q, O>(
251        mut self,
252        source: C,
253        root: R,
254        observer: &O,
255    ) -> Result<Outcome<R::Output, C::Proof<'d>>, drive::Error>
256    where
257        R: root::Root<'d>,
258        C: clock::Time,
259        O: executor::Startup<Q>,
260    {
261        let slot = make_slot(self.driver_ref())?;
262        let wake = slot.target();
263        let mut place = MaybeUninit::uninit();
264        let mut root = slot::Vacant::new(&mut place).insert(root);
265        let mut first = true;
266        loop {
267            let tick = source.tick()?;
268            let (mut core, pending) = self.begin(tick);
269            let admission = core.turn.turn().app().lease();
270            let (events, status) = core.dispatch_native::<Q, O>(pending, observer)?;
271            let mut observed = slot.take();
272            core.activate(Some((&slot, &mut observed)));
273            drop(admission);
274            let output = if first || matches!(observed, ready::Readiness::Ready) {
275                root::Root::poll(root::Context::new(
276                    pin::Pin::new(&mut root),
277                    wake,
278                    core.turn.turn().app(),
279                    core.driver.context(),
280                ))
281            } else {
282                task::Poll::Pending
283            };
284            first = false;
285            match output {
286                task::Poll::Ready(output) => {
287                    drop(root);
288                    let mut events = events;
289                    let mut status = status;
290                    loop {
291                        match core.complete(source, events, status)? {
292                            ControlFlow::Break(()) => return Ok(Outcome::Shutdown(Some(output))),
293                            ControlFlow::Continue(Some(proof)) => {
294                                return Ok(Outcome::Complete(output, proof));
295                            }
296                            ControlFlow::Continue(None) => {}
297                        }
298                        drop(core);
299                        let tick = source.tick()?;
300                        let (next, pending) = self.begin(tick);
301                        core = next;
302                        (events, status) = core.dispatch_native::<Q, O>(pending, observer)?;
303                        core.activate(None);
304                    }
305                }
306                task::Poll::Pending => match core.park(events, status)? {
307                    ControlFlow::Break(()) => return Ok(Outcome::Shutdown(None)),
308                    ControlFlow::Continue(true) => core.wait(source)?,
309                    ControlFlow::Continue(false) => {}
310                },
311            }
312        }
313    }
314}