use dope_sys::io::reactor::event;
use std::{convert::Infallible, marker, mem, ops::ControlFlow, pin, time};
use crate::{
Errno,
driver::{
self, life,
schedule::clock::{Deadline, Sample},
settings::claim::Needs,
},
};
use crate::{
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, Returned, 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 type Session<'i, 'env, 'd, Q, Report, H = ()> = Running<'i, 'env, 'd, Q, Report, H, ()>;
pub type Observed<'i, 'env, 'd, Q, Report> = Running<'i, 'env, 'd, Q, Report, (), Shutdown>;
pub struct Running<'i, 'env: 'd, 'd: 'i, Q: 'd, Report, H, M> {
core: &'i mut life::Core<'env, 'd, Q, Report>,
head: H,
start: Sample,
mode: marker::PhantomData<fn() -> M>,
}
enum State<H, E, B, R, C, X> {
Rejected(E),
Clock(B),
Ran {
head: H,
output: R,
quiesce: Result<C, drive::Error>,
disarm: Option<Errno>,
},
Install {
head: H,
cause: 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>;
pub type Outcome<R, X = Infallible, M = Shutdown> =
Result<<M as Returned>::Value<R>, Error<<M as Returned>::Retained<R>, X>>;
pub type LoanResult<E, R, X = Infallible, M = Shutdown> =
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<'i, 'env: 'd, 'd: 'i, 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,
mode: marker::PhantomData,
})
}
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();
life::Core::shutdown(&mut app, Sample::new(now));
let (head, _, disarm) = life::Core::finish::<H, T, _>(app, true, ());
State::Install {
head,
cause,
disarm,
}
}
Ok(()) => {
let output = run(&mut app);
let source = timeout.into();
life::Core::shutdown(&mut app, source.start());
let (head, quiesce, disarm) = match run::quiesce(&mut app, source) {
Ok(()) => {
let (head, source, disarm) =
life::Core::finish::<H, T, _>(app, false, source);
(head, Ok(source), disarm)
}
Err(cause) => {
let (head, _, disarm) = life::Core::finish::<H, T, _>(app, true, ());
(head, Err(cause), disarm)
}
};
State::Ran {
head,
output,
quiesce,
disarm,
}
}
};
Completed {
state,
source: marker::PhantomData,
}
}
}
impl<'i, E, R, C, X> Completed<'i, (), E, R, C, X> {
pub fn finish(self) -> LoanResult<E, R, X, ()> {
self.close::<()>()
}
}
impl<E, R, C, X, B: Into<drive::Error>> Completed<'_, (), E, R, C, X, B> {
fn close<M: Returned>(self) -> 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::Ran {
output,
quiesce,
disarm,
..
} => M::closed(output, Shutdown::after(quiesce.err(), disarm))
.map_err(lending::Error::Run),
State::Install { cause, disarm, .. } => {
Err(lending::Error::Run(Error::Install { cause, disarm }))
}
}
}
}
impl<
'i,
'env: 'd,
'd: 'i,
Q: executor::Startup,
Report: event::Report<Event = crate::Reported>,
M: Returned,
> Running<'i, 'env, 'd, Q, Report, (), M>
{
pub fn run<D, R>(
core: &'i 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, M>
where
D: executor::raw::App<'d>,
{
Session::start(core, (), None)?
.with_app::<clock::Wall, _, Infallible, _, Infallible>(app, clock::wall(), run)
.close::<M>()
.map_err(Error::from)
}
pub fn run_for<D, R>(
core: &'i 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, M>
where
D: executor::raw::App<'d>,
{
Session::start(core, (), None)?
.with_app::<clock::Bound<clock::Span>, _, Infallible, _, Infallible>(app, timeout, run)
.close::<M>()
.map_err(Error::from)
}
pub fn run_at<D, R>(
core: &'i 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, M>
where
D: executor::raw::App<'d>,
{
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)
.close::<M>()
.map_err(Error::from)
}
pub fn lend<O, E, R, D, C>(
core: &'i 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, M>, D)
where
O: lending::Root<'d> + lending::raw::Resume<'d>,
C: clock::Time,
Q: executor::Startup,
{
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);
let result = match state {
State::Rejected(error) => {
unsafe { lending::raw::Project::release(owner.as_mut()) };
Err(lending::Error::Build(error))
}
State::Clock(error) => {
unsafe { lending::raw::Project::release(owner.as_mut()) };
Err(lending::Error::Run(Error::Drive(error)))
}
State::Ran {
head: park,
output,
quiesce,
disarm,
} => {
let backing = pin::pin!(executor::raw::Backing::prepared(
&core.token,
lending::raw::Project::exclusive(owner.as_mut()),
park,
));
let mut app = unsafe { core.resume(backing.as_ref()) };
let failure = match quiesce {
Ok(source) => run::quiesce(&mut app, source).err(),
Err(cause) => Some(cause),
};
let ((), (), cleanup) = life::Core::finish::<(), _, _>(app, failure.is_some(), ());
M::closed(output, Shutdown::after(failure, disarm.or(cleanup)))
.map_err(lending::Error::Run)
}
State::Install {
head: park,
cause,
disarm,
} => {
let backing = pin::pin!(executor::raw::Backing::prepared(
&core.token,
lending::raw::Project::exclusive(owner.as_mut()),
park,
));
let app = unsafe { core.resume(backing.as_ref()) };
let ((), (), cleanup) = life::Core::finish::<(), _, _>(app, true, ());
Err(lending::Error::Run(Error::Install {
cause,
disarm: disarm.or(cleanup),
}))
}
};
(result, data)
}
}
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,
}
}
}