use o3::mem::slot;
use std::{
mem::{self, MaybeUninit},
ops::ControlFlow,
pin, task, time,
};
use crate::driver::{self, result::poll, route, route::indices, schedule, schedule::ready};
use drive::{clock, clock::Time as _, turn};
use schedule::clock::Moment;
use turn::{routes, scope};
use crate::executor::{self, boot, drive, root};
#[must_use = "fixed-point evidence and its root output must be observed"]
pub struct Fixed<'d, T> {
output: T,
now: Moment<'d>,
}
impl<'d, T> Fixed<'d, T> {
pub(crate) const fn new(output: T, now: Moment<'d>) -> Self {
Self { output, now }
}
pub const fn output(&self) -> &T {
&self.output
}
pub fn into_output(self) -> T {
self.output
}
pub const fn now(&self) -> Moment<'d> {
self.now
}
}
const _: () = {
assert!(mem::size_of::<Fixed<'_, ()>>() == mem::size_of::<Moment<'_>>());
assert!(mem::align_of::<Fixed<'_, ()>>() == mem::align_of::<Moment<'_>>());
};
enum Attempt<R, O> {
Complete(Result<O, drive::Error>),
Cancel(R, drive::Error),
}
enum Outcome<O, P> {
Complete(O, P),
Shutdown(Option<O>),
}
impl<O, P> Outcome<O, P> {
fn complete(self) -> Result<(O, P), drive::Error> {
match self {
Self::Complete(output, proof) => Ok((output, proof)),
Self::Shutdown(_) => Err(drive::Error::Shutdown),
}
}
}
impl<R, O> Attempt<R, O> {
fn finish<'d>(self) -> Result<O, drive::Error>
where
R: boot::Root<'d, Output = O>,
{
match self {
Self::Complete(result) => result,
Self::Cancel(root, source) => {
R::cancel(root);
Err(source)
}
}
}
}
pub(crate) fn run_boot<'run, 'd, R, Q, Report: crate::io::Report>(
state: Result<scope::Boot<'run, 'd, Report>, drive::Error>,
mut root: R,
observer: &Q,
) -> Result<R::Output, drive::Error>
where
R: boot::Root<'d>,
Q: executor::Startup,
{
'run: {
let mut state = match state {
Ok(state) => state,
Err(error) => break 'run Attempt::Cancel(root, error),
};
let slot = match make_slot(state.driver_ref()) {
Ok(slot) => slot,
Err(error) => break 'run Attempt::Cancel(root, error),
};
let source = clock::wall();
let wake = slot.target();
let driver = state.driver_ref();
let mut cause = boot::Cause::Start;
loop {
let tick = source.start();
let mut core = state.begin(tick);
let (events, status) = match core.dispatch_native::<Q, Q>((), observer) {
Ok(result) => result,
Err(source) => break 'run Attempt::Cancel(root, source),
};
let observed = slot.take();
if matches!(cause, boot::Cause::Start) || matches!(observed, ready::Readiness::Ready) {
let context = boot::Context::new(wake, core.turn.turn().app(), cause);
match R::poll(root, context) {
boot::Poll::Pending(next) => root = next,
boot::Poll::Ready(output) => {
let mut events = events;
let mut status = status;
break 'run Attempt::Complete('finish: loop {
let idle = match core.park(events, status) {
Ok(ControlFlow::Continue(idle)) => idle,
Ok(ControlFlow::Break(())) => break Err(drive::Error::Shutdown),
Err(error) => break Err(error.into()),
};
if idle {
'wait: {
let span = if driver.has_deferred() {
Some(time::Duration::ZERO)
} else {
let Some(deadline) = driver.timer().earliest() else {
match core.sync() {
Ok(poll::Commit::Drained) => {
break 'finish Ok(output);
}
Ok(poll::Commit::Pending) => break 'wait,
Err(error) => break 'finish Err(error.into()),
}
};
if core.quiet() {
Some(source.timeout(deadline))
} else {
Some(time::Duration::ZERO)
}
};
if let Err(error) = core.wait_for(span, source) {
break 'finish Err(error.into());
}
}
}
drop(core);
core = state.begin(source.start());
(events, status) = match core.dispatch_native::<Q, Q>((), observer) {
Ok(result) => result,
Err(error) => break Err(error),
};
let _ready = slot.take();
});
}
}
}
cause = boot::Cause::Wake;
let idle = match core.park(events, status) {
Ok(ControlFlow::Continue(idle)) => idle,
Ok(ControlFlow::Break(())) => {
break 'run Attempt::Cancel(root, drive::Error::Shutdown);
}
Err(error) => break 'run Attempt::Cancel(root, error.into()),
};
if !idle {
continue;
}
let span = if core.quiet() && !driver.has_deferred() {
driver.timer().earliest().map(|due| source.timeout(due))
} else {
Some(time::Duration::ZERO)
};
if let Err(error) = core.wait_for(span, source) {
break 'run Attempt::Cancel(root, error.into());
}
}
}
.finish()
}
fn make_slot<'d>(
driver: driver::Reference<'d>,
) -> Result<ready::Slot<'d, routes::Wake>, drive::Error> {
let target = driver
.targets::<routes::Wake>()
.bind(indices::SlotIndex::ZERO, route::Epoch::INITIAL);
Ok(driver.ready().make_slot(target.dispatch())?)
}
impl<'run, 'app, 'd: 'app, D, S, Report: crate::io::Report>
scope::Scope<'run, 'app, 'd, D, S, Report>
where
D: executor::raw::App<'d>,
{
pub(crate) fn run<R, C, Q, O>(
self,
source: C,
root: R,
observer: &O,
) -> Result<R::Output, drive::Error>
where
R: root::Root<'d>,
C: clock::Time,
O: executor::Startup<Q>,
{
let (output, _) = self
.drive::<R, C, Q, O>(source, root, observer)?
.complete()?;
Ok(output)
}
pub(crate) fn run_until<R, C, Q>(
self,
source: C,
root: R,
observer: &Q,
) -> Result<ControlFlow<R::Output>, drive::Error>
where
R: root::Root<'d>,
C: clock::Time,
Q: executor::Startup,
{
Ok(match self.drive::<R, C, Q, Q>(source, root, observer)? {
Outcome::Complete(output, _) | Outcome::Shutdown(Some(output)) => {
ControlFlow::Break(output)
}
Outcome::Shutdown(None) => ControlFlow::Continue(()),
})
}
pub(crate) fn run_fixed<R, C, Q>(
self,
source: C,
root: R,
observer: &Q,
) -> Result<Fixed<'d, R::Output>, drive::Error>
where
R: root::Root<'d>,
Q: executor::Startup,
C: clock::Time<Proof<'d> = Moment<'d>>,
{
let (output, now) = self
.drive::<R, C, Q, Q>(source, root, observer)?
.complete()?;
Ok(Fixed::new(output, now))
}
fn drive<R, C, Q, O>(
mut self,
source: C,
root: R,
observer: &O,
) -> Result<Outcome<R::Output, C::Proof<'d>>, drive::Error>
where
R: root::Root<'d>,
C: clock::Time,
O: executor::Startup<Q>,
{
let slot = make_slot(self.driver_ref())?;
let wake = slot.target();
let mut place = MaybeUninit::uninit();
let mut root = slot::Vacant::new(&mut place).insert(root);
let mut first = true;
loop {
let tick = source.tick()?;
let (mut core, pending) = self.begin(tick);
let admission = core.turn.turn().app().lease();
let (events, status) = core.dispatch_native::<Q, O>(pending, observer)?;
let mut observed = slot.take();
core.activate(Some((&slot, &mut observed)));
drop(admission);
let output = if first || matches!(observed, ready::Readiness::Ready) {
root::Root::poll(root::Context::new(
pin::Pin::new(&mut root),
wake,
core.turn.turn().app(),
core.driver.context(),
))
} else {
task::Poll::Pending
};
first = false;
match output {
task::Poll::Ready(output) => {
drop(root);
let mut events = events;
let mut status = status;
loop {
match core.complete(source, events, status)? {
ControlFlow::Break(()) => return Ok(Outcome::Shutdown(Some(output))),
ControlFlow::Continue(Some(proof)) => {
return Ok(Outcome::Complete(output, proof));
}
ControlFlow::Continue(None) => {}
}
drop(core);
let tick = source.tick()?;
let (next, pending) = self.begin(tick);
core = next;
(events, status) = core.dispatch_native::<Q, O>(pending, observer)?;
core.activate(None);
}
}
task::Poll::Pending => match core.park(events, status)? {
ControlFlow::Break(()) => return Ok(Outcome::Shutdown(None)),
ControlFlow::Continue(true) => core.wait(source)?,
ControlFlow::Continue(false) => {}
},
}
}
}
}