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