Skip to main content

dope_core/executor/session/
mod.rs

1use std::{convert::Infallible, marker, mem, ops::ControlFlow, pin, time};
2
3use dope_sys::io::reactor::event;
4
5use crate::{
6    Errno,
7    driver::{
8        self, life,
9        life::domain,
10        schedule::clock::{Deadline, Sample},
11        settings::claim::Needs,
12    },
13    executor::{
14        self, InstallError,
15        drive::{self, clock},
16        root,
17    },
18    topology::lending,
19};
20
21mod app;
22mod error;
23pub(crate) mod run;
24
25pub use app::App;
26pub use error::Error;
27
28#[derive(Debug)]
29pub struct Shutdown {
30    pub drive: drive::Error,
31    pub disarm: Option<Errno>,
32}
33
34impl Shutdown {
35    pub fn cause<X>(&self) -> Cause<'_, X> {
36        Cause::Quiesce {
37            drive: &self.drive,
38            disarm: self.disarm,
39        }
40    }
41
42    fn after(drive: Option<drive::Error>, disarm: Option<Errno>) -> Option<Self> {
43        match drive {
44            Some(drive) => Some(Self { drive, disarm }),
45            None => disarm.map(|errno| Self {
46                drive: drive::Error::TimerDisarm(errno),
47                disarm: None,
48            }),
49        }
50    }
51}
52
53mod sealed;
54pub(in crate::executor::session) use sealed::Sealed;
55
56pub trait Returned: Sealed + Sized {
57    type Value<R>;
58    type Retained<R>;
59
60    fn closed<R, X>(output: R, shutdown: Option<Shutdown>) -> Outcome<R, X, Self>;
61}
62
63impl Returned for Mode<false> {
64    type Value<R> = R;
65    type Retained<R> = R;
66
67    fn closed<R, X>(output: R, shutdown: Option<Shutdown>) -> Outcome<R, X, Self> {
68        match shutdown {
69            Some(Shutdown { drive, disarm }) => Err(Error::Quiesce {
70                output,
71                drive,
72                disarm,
73            }),
74            None => Ok(output),
75        }
76    }
77}
78
79impl Returned for Mode<true> {
80    type Value<R> = (R, Option<Shutdown>);
81    type Retained<R> = Infallible;
82
83    fn closed<R, X>(output: R, shutdown: Option<Shutdown>) -> Outcome<R, X, Self> {
84        Ok((output, shutdown))
85    }
86}
87
88/// Exact runtime failures borrowed independently of retained application output.
89#[derive(Debug)]
90pub enum Cause<'a, X = Infallible> {
91    Drive(&'a drive::Error),
92    Quiesce {
93        drive: &'a drive::Error,
94        disarm: Option<Errno>,
95    },
96    Install {
97        cause: &'a InstallError<X>,
98        disarm: Option<Errno>,
99    },
100}
101
102pub struct Session<'i, 'env: 'd, 'd: 'i, Q: 'd, Report, H = ()> {
103    core: &'i mut life::Core<'env, 'd, Q, Report>,
104    head: H,
105    start: Sample,
106}
107
108impl<'i, 'env, 'd, Q: executor::Startup, H, Report: event::Report<Event = crate::Reported>>
109    Session<'i, 'env, 'd, Q, Report, H>
110where
111    H: lending::raw::Head<'d>,
112{
113    pub fn admit<E, R, C>(
114        core: &'i mut life::Core<'env, 'd, Q, Report>,
115        head: H,
116        start: Option<Deadline<'d>>,
117    ) -> Result<Self, Retired<'i, 'd, H, E, R, C, Q>> {
118        Self::start(core, head, start).map_err(|error| Completed {
119            state: State::Clock(error),
120            source: marker::PhantomData,
121        })
122    }
123
124    fn start(
125        core: &'i mut life::Core<'env, 'd, Q, Report>,
126        head: H,
127        start: Option<Deadline<'d>>,
128    ) -> Result<Self, drive::Error> {
129        let start = clock::sample(core.driver_ref().clock(), start)?;
130        Ok(Self { core, head, start })
131    }
132
133    pub fn driver(&mut self) -> &mut driver::Local<'d> {
134        self.core.driver()
135    }
136
137    pub fn reject<E, R, C>(self, error: E) -> Retired<'i, 'd, H, E, R, C, Q> {
138        Completed {
139            state: State::Rejected(error),
140            source: marker::PhantomData,
141        }
142    }
143
144    pub fn drive_until<A, W, E, T>(
145        self,
146        app: A,
147        wait: W,
148    ) -> Retired<'i, 'd, H, E, Driven<T, Q>, H::Time<clock::Wall>, Q>
149    where
150        A: executor::raw::App<'d>,
151        W: root::Root<'d>,
152        W::Output: Into<T>,
153    {
154        self.with_app::<clock::Wall, _, _, _, _>(app, clock::wall(), |app| {
155            app.drive_until(wait).map(|exit| exit.map_break(Into::into))
156        })
157    }
158
159    pub fn with_at_for<A, E, R>(
160        self,
161        app: A,
162        timeout: time::Duration,
163        run: impl for<'run> FnOnce(&mut App<'run, 'env, 'd, H::Joined<A>, Report, Q>) -> R,
164    ) -> Retired<'i, 'd, H, E, R, H::Time<Bound<'d>>, Q>
165    where
166        A: executor::raw::App<'d>,
167    {
168        let clock = self.core.driver_ref().clock();
169        self.with_app::<Bound<'d>, _, _, _, _>(app, (clock, timeout), run)
170    }
171
172    pub fn with_app<C, T, E, R, B>(
173        self,
174        app: T,
175        timeout: impl Into<C>,
176        run: impl for<'app> FnOnce(&mut App<'app, 'env, 'd, H::Joined<T>, Report, Q>) -> R,
177    ) -> Retired<'i, 'd, H, E, R, H::Time<C>, Q, B>
178    where
179        T: executor::raw::App<'d>,
180        C: clock::Time,
181        Q: executor::Startup,
182    {
183        let Self {
184            core, head, start, ..
185        } = self;
186        let backing = pin::pin!(executor::raw::Backing::new(&core.token, head.join(app),));
187        let mut app = core.install(start, backing.as_ref());
188        let admitted = {
189            let result = 'admit: {
190                let stored = app.core.token.pin_mut(app.stored).project();
191                let owner = lending::raw::Project::exclusive(stored.app);
192                if let Err(error) = executor::raw::App::admit(owner.as_ref(), &mut Needs::new()) {
193                    break 'admit Err(error.into());
194                }
195                if <H::Joined<T> as executor::raw::App<'d>>::PARK {
196                    let count = match executor::raw::Plan::prepare::<H::Joined<T>>(
197                        stored.park,
198                        owner.as_ref(),
199                    ) {
200                        Ok(count) => count,
201                        Err(_) => {
202                            break 'admit Err(executor::InstallError::CoordinatorCountOverflow);
203                        }
204                    };
205                    if let Err(error) = count.admit() {
206                        break 'admit Err(error);
207                    }
208                }
209                match Q::installed(app.core.source) {
210                    Ok(()) => Ok(()),
211                    Err(error) => Err(executor::InstallError::Startup(error)),
212                }
213            };
214            if result.is_err() {
215                executor::failed(app.core.source);
216            }
217            result
218        };
219        let state = match admitted {
220            Err(cause) => {
221                let now = app.core.driver_ref().clock().now().into_raw();
222                domain::raw::shutdown(&mut app, Sample::new(now));
223                let (head, _, disarm) = domain::raw::finish::<H, T, _>(app, true, ());
224                State::Installed {
225                    head,
226                    result: Err(cause),
227                    disarm,
228                }
229            }
230            Ok(()) => {
231                let output = run(&mut app);
232                let source = timeout.into();
233                domain::raw::shutdown(&mut app, source.start());
234                let (head, quiesce, disarm) = match run::quiesce(&mut app, source) {
235                    Ok(()) => {
236                        let (head, source, disarm) =
237                            domain::raw::finish::<H, T, _>(app, false, source);
238                        (head, Ok(source), disarm)
239                    }
240                    Err(cause) => {
241                        let (head, _, disarm) = domain::raw::finish::<H, T, _>(app, true, ());
242                        (head, Err(cause), disarm)
243                    }
244                };
245                State::Installed {
246                    head,
247                    result: Ok((output, quiesce)),
248                    disarm,
249                }
250            }
251        };
252        Completed {
253            state,
254            source: marker::PhantomData,
255        }
256    }
257}
258
259impl<const OBSERVE: bool> Mode<OBSERVE>
260where
261    Self: Returned,
262{
263    pub fn run<'env: 'd, 'd, Q, Report, D, R>(
264        self,
265        core: &mut life::Core<'env, 'd, Q, Report>,
266        app: D,
267        run: impl for<'app> FnOnce(&mut App<'app, 'env, 'd, D, Report, Q>) -> R,
268    ) -> Outcome<R, Q::Error, Self>
269    where
270        D: executor::raw::App<'d>,
271        Q: executor::Startup,
272        Report: event::Report<Event = crate::Reported>,
273    {
274        Session::start(core, (), None)?
275            .with_app::<clock::Wall, _, Infallible, _, Infallible>(app, clock::wall(), run)
276            .finish(self)
277            .map_err(Error::from)
278    }
279
280    pub fn run_for<'env: 'd, 'd, Q, Report, D, R>(
281        self,
282        core: &mut life::Core<'env, 'd, Q, Report>,
283        app: D,
284        timeout: time::Duration,
285        run: impl for<'app> FnOnce(&mut App<'app, 'env, 'd, D, Report, Q>) -> R,
286    ) -> Outcome<R, Q::Error, Self>
287    where
288        D: executor::raw::App<'d>,
289        Q: executor::Startup,
290        Report: event::Report<Event = crate::Reported>,
291    {
292        Session::start(core, (), None)?
293            .with_app::<clock::Bound<clock::Span>, _, Infallible, _, Infallible>(app, timeout, run)
294            .finish(self)
295            .map_err(Error::from)
296    }
297
298    pub fn run_at<'env: 'd, 'd, Q, Report, D, R>(
299        self,
300        core: &mut life::Core<'env, 'd, Q, Report>,
301        app: D,
302        start: Deadline<'d>,
303        timeout: time::Duration,
304        run: impl for<'app> FnOnce(&mut App<'app, 'env, 'd, D, Report, Q>) -> R,
305    ) -> Outcome<R, Q::Error, Self>
306    where
307        D: executor::raw::App<'d>,
308        Q: executor::Startup,
309        Report: event::Report<Event = crate::Reported>,
310    {
311        let session = Session::start(core, (), Some(start))?;
312        let clock = session.core.driver_ref().clock();
313        session
314            .with_app::<Bound<'d>, _, Infallible, _, Infallible>(app, (clock, timeout), run)
315            .finish(self)
316            .map_err(Error::from)
317    }
318
319    pub fn lend<'env: 'd, 'd, Q, Report, O, E, R, D, C>(
320        self,
321        core: &mut life::Core<'env, 'd, Q, Report>,
322        owner: O,
323        body: impl for<'loan> FnOnce(
324            &'loan mut life::Core<'env, 'd, Q, Report>,
325            lending::raw::Borrowed<'loan, O>,
326        ) -> (Completed<'loan, O::ParkPlan, E, R, C, Q::Error>, D),
327    ) -> (LoanResult<E, R, Q::Error, Self>, D)
328    where
329        O: lending::Root<'d> + lending::raw::Resume<'d>,
330        C: clock::Time,
331        Q: executor::Startup,
332        Report: event::Report<Event = crate::Reported>,
333    {
334        let mut owner = pin::pin!(mem::ManuallyDrop::new(owner));
335        let head = lending::raw::Borrowed::new(lending::raw::Project::exclusive(owner.as_mut()));
336        let (Completed { state, .. }, data) = body(core, head);
337        (
338            sealed::finish::<Self, _, _, _, _, _, _, _>(core, owner.as_mut(), state),
339            data,
340        )
341    }
342}
343
344pub struct Mode<const OBSERVE: bool>;
345
346pub const PROPAGATE: Mode<false> = Mode;
347pub const OBSERVE: Mode<true> = Mode;
348
349enum State<H, E, B, R, C, X> {
350    Rejected(E),
351    Clock(B),
352    Installed {
353        head: H,
354        result: Result<(R, Result<C, drive::Error>), InstallError<X>>,
355        disarm: Option<Errno>,
356    },
357}
358
359#[must_use]
360#[repr(transparent)]
361pub struct Completed<'i, H, E, R, C = clock::Wall, X = Infallible, B = drive::Error> {
362    state: State<H, E, B, R, C, X>,
363    source: marker::PhantomData<*mut &'i ()>,
364}
365
366type Retired<'i, 'd, H, E, R, C, Q, B = drive::Error> = Completed<
367    'i,
368    <H as lending::raw::Head<'d>>::Retired,
369    E,
370    R,
371    C,
372    <Q as executor::Startup>::Error,
373    B,
374>;
375type Driven<T, Q> = Result<ControlFlow<T, executor::Requested<Q>>, drive::Error>;
376type Outcome<R, X, M> = Result<<M as Returned>::Value<R>, Error<<M as Returned>::Retained<R>, X>>;
377type LoanResult<E, R, X, M> =
378    Result<<M as Returned>::Value<R>, lending::Error<E, <M as Returned>::Retained<R>, X>>;
379type Bound<'d> = clock::Bound<clock::Span, Deadline<'d>>;
380
381impl<E, R, C, X, B: Into<drive::Error>> Completed<'_, (), E, R, C, X, B> {
382    pub fn finish<M: Returned>(self, _mode: M) -> LoanResult<E, R, X, M> {
383        match self.state {
384            State::Rejected(error) => Err(lending::Error::Build(error)),
385            State::Clock(error) => Err(lending::Error::Run(Error::Drive(error.into()))),
386            State::Installed {
387                result: Ok((output, quiesce)),
388                disarm,
389                ..
390            } => M::closed(output, Shutdown::after(quiesce.err(), disarm))
391                .map_err(lending::Error::Run),
392            State::Installed {
393                result: Err(cause),
394                disarm,
395                ..
396            } => Err(lending::Error::Run(Error::Install { cause, disarm })),
397        }
398    }
399}
400
401impl<'i, H, E, R, C, X> Completed<'i, H, E, R, C, X> {
402    pub fn reject<'env: 'd, 'd: 'i, Q, Report, T>(
403        _core: &'i mut life::Core<'env, 'd, Q, Report>,
404        _head: T,
405        error: E,
406    ) -> Self
407    where
408        T: lending::raw::Head<'d, Retired = H>,
409        Q: executor::Startup<Error = X>,
410    {
411        Self {
412            state: State::Rejected(error),
413            source: marker::PhantomData,
414        }
415    }
416}