Skip to main content

dope_core/executor/raw/
mod.rs

1//! Raw application boundary. [`App`] owns complete lifecycle traversal;
2//! runtime-owned session roots choose when it may run.
3use dope_sys::io::reactor::event::Report;
4use std::{
5    convert::Infallible,
6    num::NonZero,
7    ops::{self, ControlFlow},
8    pin,
9};
10
11use crate::{
12    driver::{
13        life::{self, finish},
14        route::{self, kind::Any},
15        schedule,
16        settings::{self, claim, errors},
17    },
18    executor::{
19        self,
20        drive::turn::{modes, scope},
21    },
22    io::event::Dispatch,
23    topology::lending,
24};
25use o3::{
26    alloc,
27    base::{cell::region, num::bounded},
28};
29
30mod progress;
31mod sealed;
32mod stored;
33
34pub(in crate::executor::raw) use sealed::Sealed;
35
36pub use progress::Progress;
37pub(crate) use stored::{Backing, Stored};
38
39/// Application storage metadata independent of lifecycle eligibility.
40pub trait Layout<'d> {
41    type Scope: route::Selection;
42    /// Pre-park state selected once and retained with this pinned application.
43    type ParkPlan: Plan;
44}
45
46/// # Safety
47/// Visit each unchanged pinned owner once, admitting its fixed Scope route and operation authority.
48/// Shutdown retains clients; finish destroys dependents first. Unit plans park; Flat preserves census order.
49pub unsafe trait App<'d>: Sized + Layout<'d> {
50    const ROUTES: settings::Routes;
51
52    /// Routes on which a nested application may observe a completion.
53    const DISPATCH_ROUTES: settings::Routes = Self::ROUTES;
54
55    /// Routes whose installed owners may receive activation.
56    const WAKE_ROUTES: settings::Routes = settings::Routes::EMPTY;
57
58    /// Upper bound on idle coordinator probes, including delegated probes.
59    const COORDS: usize = 0;
60
61    const PARK: bool = false;
62
63    /// The unchanged pinned child that receives this owner's default lifecycle traversal.
64    fn child(_: pin::Pin<&mut Self>) -> Option<pin::Pin<&mut impl App<'d>>> {
65        None::<pin::Pin<&mut ()>>
66    }
67
68    fn census(_: pin::Pin<&Self>, counts: &mut Census) -> Result<(), alloc::Overflow> {
69        if Self::PARK {
70            counts.include_leaf(Self::COORDS)?;
71        }
72        Ok(())
73    }
74
75    /// # Safety
76    /// Traverse the same admitted pinned owners in their census order.
77    unsafe fn sweep<'app, 'driver, 'turn>(
78        app: pin::Pin<&'app mut Self>,
79        sweep: &mut schedule::raw::Sweep<'driver, 'turn, 'd, impl Report<Event = crate::Reported>>,
80    ) where
81        'd: 'driver + 'turn,
82    {
83        if Self::PARK {
84            // SAFETY: this leaf retains the census-admitted root and turn.
85            unsafe { sweep.leaf(app) };
86        }
87    }
88
89    /// # Safety
90    /// The exact pinned root is installed and admitted. Run this leaf's work
91    /// or this aggregate's own coordinator with the same driver and turn.
92    unsafe fn park<'app, 'driver, 'turn>(
93        app: pin::Pin<&'app mut Self>,
94        turn: schedule::Turn<'turn, 'd>,
95        driver: &'driver mut life::Lifecycle<'d, impl Report<Event = crate::Reported>>,
96    ) where
97        'd: 'driver + 'turn,
98    {
99        if let Some(child) = Self::child(app) {
100            // SAFETY: this child shares the installed root's turn and park authority.
101            unsafe { App::park(child, turn, driver) };
102        }
103    }
104
105    /// Accumulates the routes of the owners actually present in this pinned root.
106    fn admit(_: pin::Pin<&Self>, needs: &mut claim::Needs) -> Result<(), errors::Claim> {
107        *needs = needs.include(claim::Claim::new(Self::ROUTES))?;
108        Ok(())
109    }
110
111    /// # Safety
112    /// All external clients of this exact pinned owner have ended.
113    unsafe fn released(app: pin::Pin<&mut Self>) {
114        if let Some(child) = Self::child(app) {
115            // SAFETY: the same ended client loans cover this pinned child.
116            unsafe { App::<'d>::released(child) };
117        }
118    }
119
120    fn install(app: pin::Pin<&mut Self>, install: life::Install<'_, 'd>) {
121        if let Some(child) = Self::child(app) {
122            App::install(child, install);
123        }
124    }
125
126    /// # Safety
127    /// Use this installed root, driver and turn with a target admitted by WAKE_ROUTES.
128    /// Break only when a present owner consumed this activation.
129    unsafe fn activate<'app, 'driver, 'turn>(
130        _: pin::Pin<&'app mut Self>,
131        _: route::Erased<'d, Any>,
132        _: schedule::Turn<'turn, 'd>,
133        _: &'driver mut life::Lifecycle<'d, impl Report<Event = crate::Reported>>,
134    ) -> ControlFlow<()>
135    where
136        'd: 'driver + 'turn,
137    {
138        ControlFlow::Continue(())
139    }
140
141    /// Resolves overlapping candidate routes against the receivers actually installed in this root.
142    fn has_receiver(_: pin::Pin<&Self>, route: route::Route) -> bool {
143        Self::DISPATCH_ROUTES.has_route(route)
144    }
145
146    /// A selected receiver consumes the completion or returns it to the driver.
147    fn dispatch<'event>(
148        _: pin::Pin<&mut Self>,
149        event: Dispatch<'event, 'd, Self::Scope>,
150        _: schedule::Turn<'_, 'd>,
151        _: &mut life::Lifecycle<'d, impl Report<Event = crate::Reported>>,
152    ) -> ops::ControlFlow<Dispatch<'event, 'd, Self::Scope>> {
153        ops::ControlFlow::Break(event)
154    }
155
156    /// Reports waits into the same traversal until an owner can run immediately.
157    fn progress<const STOP: bool>(
158        _: pin::Pin<&Self>,
159        _: Progress<'_, '_, 'd>,
160        _: Option<&mut schedule::Waits<'d>>,
161    ) -> ops::ControlFlow<()> {
162        ops::ControlFlow::Continue(())
163    }
164
165    fn shutdown(
166        app: pin::Pin<&mut Self>,
167        turn: schedule::Turn<'_, 'd>,
168        driver: &mut life::Lifecycle<'d, impl Report<Event = crate::Reported>>,
169    ) {
170        if let Some(child) = Self::child(app) {
171            App::shutdown(child, turn, driver);
172        }
173    }
174
175    fn finish(
176        app: pin::Pin<&mut Self>,
177        install: life::Install<'_, 'd>,
178        finish: &mut finish::Finish<'_, 'd, impl Report<Event = crate::Reported>>,
179    ) {
180        if let Some(child) = Self::child(app) {
181            App::finish(child, install, finish);
182        }
183    }
184}
185
186impl<'d> Layout<'d> for () {
187    type Scope = Infallible;
188    type ParkPlan = ();
189}
190
191// SAFETY: the empty root has no routes, retained owners, or lifecycle work.
192unsafe impl<'d> App<'d> for () {
193    const ROUTES: settings::Routes = settings::Routes::EMPTY;
194}
195
196#[derive(Default)]
197pub struct Census {
198    parks: usize,
199    groups: usize,
200    coords: usize,
201}
202
203impl Census {
204    pub fn coordinate(&mut self) -> Result<(), alloc::Overflow> {
205        self.groups = self.groups.checked_add(1).ok_or(alloc::Overflow)?;
206        self.coords = self.coords.checked_add(1).ok_or(alloc::Overflow)?;
207        Ok(())
208    }
209
210    fn include_leaf(&mut self, coords: usize) -> Result<(), alloc::Overflow> {
211        self.parks = self.parks.checked_add(1).ok_or(alloc::Overflow)?;
212        self.groups = self
213            .groups
214            .checked_add(usize::from(coords != 0))
215            .ok_or(alloc::Overflow)?;
216        self.coords = self.coords.checked_add(coords).ok_or(alloc::Overflow)?;
217        Ok(())
218    }
219}
220
221#[derive(Default)]
222pub struct Flat {
223    parks: usize,
224    next: [usize; 2],
225    groups: u32,
226    coord: u32,
227}
228
229pub trait Plan: Sealed + Default {
230    fn flat(&mut self) -> Option<&mut Flat>;
231
232    fn prepare<'d, D: App<'d, ParkPlan = Self>>(
233        &mut self,
234        app: pin::Pin<&D>,
235    ) -> Result<Count, alloc::Overflow> {
236        Flat::census(self.flat(), app)
237    }
238}
239
240impl Plan for () {
241    fn flat(&mut self) -> Option<&mut Flat> {
242        None
243    }
244}
245
246impl Plan for Flat {
247    fn flat(&mut self) -> Option<&mut Flat> {
248        Some(self)
249    }
250}
251
252impl Flat {
253    fn census<'d, D: App<'d>>(
254        flat: Option<&mut Self>,
255        app: pin::Pin<&D>,
256    ) -> Result<Count, alloc::Overflow> {
257        let mut count = Census::default();
258        D::census(app, &mut count)?;
259        if let Some(flat) = flat {
260            flat.parks = count.parks;
261            flat.groups = count.groups as u32;
262        }
263        Ok(Count::new(count.coords))
264    }
265
266    pub(crate) fn run<'d, D, P, S, R>(
267        core: &mut scope::Core<'_, 'd, modes::App<'_, '_, 'd, D, P, S>, R>,
268    ) where
269        D: App<'d>,
270        P: lending::raw::Project<App = D>,
271        R: Report<Event = crate::Reported>,
272    {
273        if !D::PARK {
274            return;
275        }
276        let stored = core.mode.token.pin_mut(core.mode.stored).project();
277        let app = lending::raw::Project::exclusive(stored.app);
278        let turn = core.turn.turn();
279        let driver = &mut *core.driver;
280        let Some(plan) = stored.park.flat() else {
281            // SAFETY: the executing turn owns this installed root and its driver.
282            unsafe { D::park(app, turn, driver) };
283            return;
284        };
285        let ahead = [
286            start(&mut plan.next[0], turn.app().remaining(), plan.parks),
287            start(&mut plan.next[1], turn.maint().remaining(), plan.parks),
288        ];
289        let mut next = plan.coord as usize;
290        let coord = start(&mut next, turn.coord().remaining(), plan.groups as usize);
291        plan.coord = next as u32;
292        let mut sweep = schedule::raw::Sweep {
293            turn,
294            driver,
295            parks: plan.parks,
296            ahead,
297            groups: plan.groups,
298            coord: coord as u32,
299        };
300        // SAFETY: preparation admitted the same pinned traversal and its counts.
301        unsafe { D::sweep(app, &mut sweep) };
302    }
303
304    /// # Safety
305    /// Resume the unchanged head after native finish. An unadmitted root cannot run.
306    pub(crate) unsafe fn resume<'d, D: App<'d>>(&self, app: pin::Pin<&D>) -> D::ParkPlan {
307        let mut resumed = D::ParkPlan::default();
308        if let Some(plan) = resumed.flat() {
309            let _ = Self::census(Some(plan), app);
310            for (next, prior) in plan.next.iter_mut().zip(self.next) {
311                if prior < plan.parks {
312                    *next = prior;
313                }
314            }
315            if self.coord < plan.groups {
316                plan.coord = self.coord;
317            }
318        }
319        resumed
320    }
321}
322
323fn start(next: &mut usize, credits: usize, count: usize) -> usize {
324    if credits == 0 || count <= 1 {
325        return 0;
326    }
327    let at = *next;
328    let next_at = at.wrapping_add(1);
329    *next = if next_at == count { 0 } else { next_at };
330    at
331}
332
333/// # Safety
334/// Keep admitted owner identities, presence, addresses and routes fixed through finish.
335/// Neither method replaces owners or reclaims storage before native shutdown and drain.
336pub unsafe trait Drain<'d>: App<'d> {
337    fn begin(
338        self: pin::Pin<&mut Self>,
339        turn: schedule::Turn<'_, 'd>,
340        driver: &mut life::Lifecycle<'d, impl Report<Event = crate::Reported>>,
341    );
342
343    /// Reports drain work after the application's pre-park traversal.
344    /// Completion does not authorize reclaiming retained native owners.
345    fn progress(
346        self: pin::Pin<&Self>,
347        region: &region::Token<region::Identity<'d>>,
348        state: Option<&mut schedule::Waits<'d>>,
349    ) -> ControlFlow<()>;
350
351    fn force(
352        self: pin::Pin<&mut Self>,
353        turn: schedule::Turn<'_, 'd>,
354        driver: &mut life::Lifecycle<'d, impl Report<Event = crate::Reported>>,
355    );
356}
357
358/// One complete coordinator count classified at installation.
359#[derive(Clone, Copy, Debug)]
360pub enum Count {
361    Bounded(bounded::raw::U32<0, { schedule::LIMIT as u32 }>),
362    Excess(NonZero<usize>),
363}
364
365impl Count {
366    pub const fn new(value: usize) -> Self {
367        match bounded::raw::U32::from_usize(value) {
368            Some(value) => Self::Bounded(value),
369            None => Self::Excess(NonZero::<usize>::MIN.saturating_add(value - 1)),
370        }
371    }
372
373    pub const fn get(self) -> usize {
374        match self {
375            Self::Bounded(value) => value.into_usize(),
376            Self::Excess(value) => value.get(),
377        }
378    }
379
380    pub(in crate::executor) fn admit<E>(self) -> Result<(), executor::InstallError<E>> {
381        match self {
382            Self::Bounded(_) => Ok(()),
383            Self::Excess(count) => Err(executor::InstallError::Coordinators {
384                count,
385                limit: schedule::LIMIT,
386            }),
387        }
388    }
389}