use std::{convert::Infallible, marker, mem, ops::ControlFlow, pin, time};
use dope_sys::io::reactor::event;
use crate::{
Errno,
driver::{
self, life,
life::domain,
schedule::clock::{Deadline, Sample},
settings::claim::Needs,
},
executor::{
self, InstallError,
drive::{self, clock},
root,
},
topology::lending,
};
mod app;
mod error;
pub(crate) mod run;
pub use app::App;
pub use error::Error;
#[derive(Debug)]
pub struct Shutdown {
pub drive: drive::Error,
pub disarm: Option<Errno>,
}
impl Shutdown {
pub fn cause<X>(&self) -> Cause<'_, X> {
Cause::Quiesce {
drive: &self.drive,
disarm: self.disarm,
}
}
fn after(drive: Option<drive::Error>, disarm: Option<Errno>) -> Option<Self> {
match drive {
Some(drive) => Some(Self { drive, disarm }),
None => disarm.map(|errno| Self {
drive: drive::Error::TimerDisarm(errno),
disarm: None,
}),
}
}
}
mod sealed;
pub(in crate::executor::session) use sealed::Sealed;
pub trait Returned: Sealed + Sized {
type Value<R>;
type Retained<R>;
fn closed<R, X>(output: R, shutdown: Option<Shutdown>) -> Outcome<R, X, Self>;
}
impl Returned for Mode<false> {
type Value<R> = R;
type Retained<R> = R;
fn closed<R, X>(output: R, shutdown: Option<Shutdown>) -> Outcome<R, X, Self> {
match shutdown {
Some(Shutdown { drive, disarm }) => Err(Error::Quiesce {
output,
drive,
disarm,
}),
None => Ok(output),
}
}
}
impl Returned for Mode<true> {
type Value<R> = (R, Option<Shutdown>);
type Retained<R> = Infallible;
fn closed<R, X>(output: R, shutdown: Option<Shutdown>) -> Outcome<R, X, Self> {
Ok((output, shutdown))
}
}
#[derive(Debug)]
pub enum Cause<'a, X = Infallible> {
Drive(&'a drive::Error),
Quiesce {
drive: &'a drive::Error,
disarm: Option<Errno>,
},
Install {
cause: &'a InstallError<X>,
disarm: Option<Errno>,
},
}
pub struct Session<'i, 'env: 'd, 'd: 'i, Q: 'd, Report, H = ()> {
core: &'i mut life::Core<'env, 'd, Q, Report>,
head: H,
start: Sample,
}
impl<'i, 'env, 'd, Q: executor::Startup, H, Report: event::Report<Event = crate::Reported>>
Session<'i, 'env, 'd, Q, Report, H>
where
H: lending::raw::Head<'d>,
{
pub fn admit<E, R, C>(
core: &'i mut life::Core<'env, 'd, Q, Report>,
head: H,
start: Option<Deadline<'d>>,
) -> Result<Self, Retired<'i, 'd, H, E, R, C, Q>> {
Self::start(core, head, start).map_err(|error| Completed {
state: State::Clock(error),
source: marker::PhantomData,
})
}
fn start(
core: &'i mut life::Core<'env, 'd, Q, Report>,
head: H,
start: Option<Deadline<'d>>,
) -> Result<Self, drive::Error> {
let start = clock::sample(core.driver_ref().clock(), start)?;
Ok(Self { core, head, start })
}
pub fn driver(&mut self) -> &mut driver::Local<'d> {
self.core.driver()
}
pub fn reject<E, R, C>(self, error: E) -> Retired<'i, 'd, H, E, R, C, Q> {
Completed {
state: State::Rejected(error),
source: marker::PhantomData,
}
}
pub fn drive_until<A, W, E, T>(
self,
app: A,
wait: W,
) -> Retired<'i, 'd, H, E, Driven<T, Q>, H::Time<clock::Wall>, Q>
where
A: executor::raw::App<'d>,
W: root::Root<'d>,
W::Output: Into<T>,
{
self.with_app::<clock::Wall, _, _, _, _>(app, clock::wall(), |app| {
app.drive_until(wait).map(|exit| exit.map_break(Into::into))
})
}
pub fn with_at_for<A, E, R>(
self,
app: A,
timeout: time::Duration,
run: impl for<'run> FnOnce(&mut App<'run, 'env, 'd, H::Joined<A>, Report, Q>) -> R,
) -> Retired<'i, 'd, H, E, R, H::Time<Bound<'d>>, Q>
where
A: executor::raw::App<'d>,
{
let clock = self.core.driver_ref().clock();
self.with_app::<Bound<'d>, _, _, _, _>(app, (clock, timeout), run)
}
pub fn with_app<C, T, E, R, B>(
self,
app: T,
timeout: impl Into<C>,
run: impl for<'app> FnOnce(&mut App<'app, 'env, 'd, H::Joined<T>, Report, Q>) -> R,
) -> Retired<'i, 'd, H, E, R, H::Time<C>, Q, B>
where
T: executor::raw::App<'d>,
C: clock::Time,
Q: executor::Startup,
{
let Self {
core, head, start, ..
} = self;
let backing = pin::pin!(executor::raw::Backing::new(&core.token, head.join(app),));
let mut app = core.install(start, backing.as_ref());
let admitted = {
let result = 'admit: {
let stored = app.core.token.pin_mut(app.stored).project();
let owner = lending::raw::Project::exclusive(stored.app);
if let Err(error) = executor::raw::App::admit(owner.as_ref(), &mut Needs::new()) {
break 'admit Err(error.into());
}
if <H::Joined<T> as executor::raw::App<'d>>::PARK {
let count = match executor::raw::Plan::prepare::<H::Joined<T>>(
stored.park,
owner.as_ref(),
) {
Ok(count) => count,
Err(_) => {
break 'admit Err(executor::InstallError::CoordinatorCountOverflow);
}
};
if let Err(error) = count.admit() {
break 'admit Err(error);
}
}
match Q::installed(app.core.source) {
Ok(()) => Ok(()),
Err(error) => Err(executor::InstallError::Startup(error)),
}
};
if result.is_err() {
executor::failed(app.core.source);
}
result
};
let state = match admitted {
Err(cause) => {
let now = app.core.driver_ref().clock().now().into_raw();
domain::raw::shutdown(&mut app, Sample::new(now));
let (head, _, disarm) = domain::raw::finish::<H, T, _>(app, true, ());
State::Installed {
head,
result: Err(cause),
disarm,
}
}
Ok(()) => {
let output = run(&mut app);
let source = timeout.into();
domain::raw::shutdown(&mut app, source.start());
let (head, quiesce, disarm) = match run::quiesce(&mut app, source) {
Ok(()) => {
let (head, source, disarm) =
domain::raw::finish::<H, T, _>(app, false, source);
(head, Ok(source), disarm)
}
Err(cause) => {
let (head, _, disarm) = domain::raw::finish::<H, T, _>(app, true, ());
(head, Err(cause), disarm)
}
};
State::Installed {
head,
result: Ok((output, quiesce)),
disarm,
}
}
};
Completed {
state,
source: marker::PhantomData,
}
}
}
impl<const OBSERVE: bool> Mode<OBSERVE>
where
Self: Returned,
{
pub fn run<'env: 'd, 'd, Q, Report, D, R>(
self,
core: &mut life::Core<'env, 'd, Q, Report>,
app: D,
run: impl for<'app> FnOnce(&mut App<'app, 'env, 'd, D, Report, Q>) -> R,
) -> Outcome<R, Q::Error, Self>
where
D: executor::raw::App<'d>,
Q: executor::Startup,
Report: event::Report<Event = crate::Reported>,
{
Session::start(core, (), None)?
.with_app::<clock::Wall, _, Infallible, _, Infallible>(app, clock::wall(), run)
.finish(self)
.map_err(Error::from)
}
pub fn run_for<'env: 'd, 'd, Q, Report, D, R>(
self,
core: &mut life::Core<'env, 'd, Q, Report>,
app: D,
timeout: time::Duration,
run: impl for<'app> FnOnce(&mut App<'app, 'env, 'd, D, Report, Q>) -> R,
) -> Outcome<R, Q::Error, Self>
where
D: executor::raw::App<'d>,
Q: executor::Startup,
Report: event::Report<Event = crate::Reported>,
{
Session::start(core, (), None)?
.with_app::<clock::Bound<clock::Span>, _, Infallible, _, Infallible>(app, timeout, run)
.finish(self)
.map_err(Error::from)
}
pub fn run_at<'env: 'd, 'd, Q, Report, D, R>(
self,
core: &mut life::Core<'env, 'd, Q, Report>,
app: D,
start: Deadline<'d>,
timeout: time::Duration,
run: impl for<'app> FnOnce(&mut App<'app, 'env, 'd, D, Report, Q>) -> R,
) -> Outcome<R, Q::Error, Self>
where
D: executor::raw::App<'d>,
Q: executor::Startup,
Report: event::Report<Event = crate::Reported>,
{
let session = Session::start(core, (), Some(start))?;
let clock = session.core.driver_ref().clock();
session
.with_app::<Bound<'d>, _, Infallible, _, Infallible>(app, (clock, timeout), run)
.finish(self)
.map_err(Error::from)
}
pub fn lend<'env: 'd, 'd, Q, Report, O, E, R, D, C>(
self,
core: &mut life::Core<'env, 'd, Q, Report>,
owner: O,
body: impl for<'loan> FnOnce(
&'loan mut life::Core<'env, 'd, Q, Report>,
lending::raw::Borrowed<'loan, O>,
) -> (Completed<'loan, O::ParkPlan, E, R, C, Q::Error>, D),
) -> (LoanResult<E, R, Q::Error, Self>, D)
where
O: lending::Root<'d> + lending::raw::Resume<'d>,
C: clock::Time,
Q: executor::Startup,
Report: event::Report<Event = crate::Reported>,
{
let mut owner = pin::pin!(mem::ManuallyDrop::new(owner));
let head = lending::raw::Borrowed::new(lending::raw::Project::exclusive(owner.as_mut()));
let (Completed { state, .. }, data) = body(core, head);
(
sealed::finish::<Self, _, _, _, _, _, _, _>(core, owner.as_mut(), state),
data,
)
}
}
pub struct Mode<const OBSERVE: bool>;
pub const PROPAGATE: Mode<false> = Mode;
pub const OBSERVE: Mode<true> = Mode;
enum State<H, E, B, R, C, X> {
Rejected(E),
Clock(B),
Installed {
head: H,
result: Result<(R, Result<C, drive::Error>), InstallError<X>>,
disarm: Option<Errno>,
},
}
#[must_use]
#[repr(transparent)]
pub struct Completed<'i, H, E, R, C = clock::Wall, X = Infallible, B = drive::Error> {
state: State<H, E, B, R, C, X>,
source: marker::PhantomData<*mut &'i ()>,
}
type Retired<'i, 'd, H, E, R, C, Q, B = drive::Error> = Completed<
'i,
<H as lending::raw::Head<'d>>::Retired,
E,
R,
C,
<Q as executor::Startup>::Error,
B,
>;
type Driven<T, Q> = Result<ControlFlow<T, executor::Requested<Q>>, drive::Error>;
type Outcome<R, X, M> = Result<<M as Returned>::Value<R>, Error<<M as Returned>::Retained<R>, X>>;
type LoanResult<E, R, X, M> =
Result<<M as Returned>::Value<R>, lending::Error<E, <M as Returned>::Retained<R>, X>>;
type Bound<'d> = clock::Bound<clock::Span, Deadline<'d>>;
impl<E, R, C, X, B: Into<drive::Error>> Completed<'_, (), E, R, C, X, B> {
pub fn finish<M: Returned>(self, _mode: M) -> LoanResult<E, R, X, M> {
match self.state {
State::Rejected(error) => Err(lending::Error::Build(error)),
State::Clock(error) => Err(lending::Error::Run(Error::Drive(error.into()))),
State::Installed {
result: Ok((output, quiesce)),
disarm,
..
} => M::closed(output, Shutdown::after(quiesce.err(), disarm))
.map_err(lending::Error::Run),
State::Installed {
result: Err(cause),
disarm,
..
} => Err(lending::Error::Run(Error::Install { cause, disarm })),
}
}
}
impl<'i, H, E, R, C, X> Completed<'i, H, E, R, C, X> {
pub fn reject<'env: 'd, 'd: 'i, Q, Report, T>(
_core: &'i mut life::Core<'env, 'd, Q, Report>,
_head: T,
error: E,
) -> Self
where
T: lending::raw::Head<'d, Retired = H>,
Q: executor::Startup<Error = X>,
{
Self {
state: State::Rejected(error),
source: marker::PhantomData,
}
}
}