dope-core 0.76.0

Owned native I/O and completion driver for dope
Documentation
//! Raw application boundary. [`App`] owns complete lifecycle traversal;
//! runtime-owned session roots choose when it may run.
use dope_sys::io::reactor::event::Report;
use std::{
    convert::Infallible,
    num::NonZero,
    ops::{self, ControlFlow},
    pin,
};

use crate::{
    driver::{
        life::{self, finish},
        route::{self, kind::Any},
        schedule,
        settings::{self, claim, errors},
    },
    executor,
    io::event::Dispatch,
};
use o3::{
    alloc,
    base::{cell::region, num::bounded},
};

mod progress;
mod sealed;
mod stored;

pub(in crate::executor::raw) use sealed::Sealed;

pub use progress::Progress;
pub(crate) use stored::{Backing, Stored};

/// Application storage metadata independent of lifecycle eligibility.
pub trait Layout<'d> {
    type Scope: route::Selection;
    /// Pre-park state selected once and retained with this pinned application.
    type ParkPlan: Plan;
}

/// # Safety
/// Visit each unchanged pinned owner once, admitting its fixed Scope route and operation authority.
/// Shutdown retains clients; finish destroys dependents first. Unit plans park; Flat preserves census order.
pub unsafe trait App<'d>: Sized + Layout<'d> {
    const ROUTES: settings::Routes;

    /// Routes on which a nested application may observe a completion.
    const DISPATCH_ROUTES: settings::Routes = Self::ROUTES;

    /// Routes whose installed owners may receive activation.
    const WAKE_ROUTES: settings::Routes = settings::Routes::EMPTY;

    /// Upper bound on idle coordinator probes, including delegated probes.
    const COORDS: usize = 0;

    const PARK: bool = false;

    /// The unchanged pinned child that receives this owner's default lifecycle traversal.
    fn child(_: pin::Pin<&mut Self>) -> Option<pin::Pin<&mut impl App<'d>>> {
        None::<pin::Pin<&mut ()>>
    }

    fn census(_: pin::Pin<&Self>, counts: &mut Census) -> Result<(), alloc::Overflow> {
        if Self::PARK {
            counts.include_leaf(Self::COORDS)?;
        }
        Ok(())
    }

    /// # Safety
    /// Traverse the same admitted pinned owners in their census order.
    unsafe fn sweep<'app, 'driver, 'turn>(
        app: pin::Pin<&'app mut Self>,
        sweep: &mut schedule::raw::Sweep<'driver, 'turn, 'd, impl Report<Event = crate::Reported>>,
    ) where
        'd: 'driver + 'turn,
    {
        if Self::PARK {
            // SAFETY: this leaf retains the census-admitted root and turn.
            unsafe { sweep.leaf(app) };
        }
    }

    /// # Safety
    /// The exact pinned root is installed and admitted. Run this leaf's work
    /// or this aggregate's own coordinator with the same driver and turn.
    unsafe fn park<'app, 'driver, 'turn>(
        app: pin::Pin<&'app mut Self>,
        turn: schedule::Turn<'turn, 'd>,
        driver: &'driver mut life::Lifecycle<'d, impl Report<Event = crate::Reported>>,
    ) where
        'd: 'driver + 'turn,
    {
        if let Some(child) = Self::child(app) {
            // SAFETY: this child shares the installed root's turn and park authority.
            unsafe { App::park(child, turn, driver) };
        }
    }

    /// Accumulates the routes of the owners actually present in this pinned root.
    fn admit(_: pin::Pin<&Self>, needs: &mut claim::Needs) -> Result<(), errors::Claim> {
        *needs = needs.include(claim::Claim::new(Self::ROUTES))?;
        Ok(())
    }

    /// # Safety
    /// All external clients of this exact pinned owner have ended.
    unsafe fn released(app: pin::Pin<&mut Self>) {
        if let Some(child) = Self::child(app) {
            // SAFETY: the same ended client loans cover this pinned child.
            unsafe { App::<'d>::released(child) };
        }
    }

    fn install(app: pin::Pin<&mut Self>, install: life::Install<'_, 'd>) {
        if let Some(child) = Self::child(app) {
            App::install(child, install);
        }
    }

    /// # Safety
    /// Use this installed root, driver and turn with a target admitted by WAKE_ROUTES.
    /// Break only when a present owner consumed this activation.
    unsafe fn activate<'app, 'driver, 'turn>(
        _: pin::Pin<&'app mut Self>,
        _: route::Erased<'d, Any>,
        _: schedule::Turn<'turn, 'd>,
        _: &'driver mut life::Lifecycle<'d, impl Report<Event = crate::Reported>>,
    ) -> ControlFlow<()>
    where
        'd: 'driver + 'turn,
    {
        ControlFlow::Continue(())
    }

    /// Resolves overlapping candidate routes against the receivers actually installed in this root.
    fn has_receiver(_: pin::Pin<&Self>, route: route::Route) -> bool {
        Self::DISPATCH_ROUTES.has_route(route)
    }

    /// A selected receiver consumes the completion or returns it to the driver.
    fn dispatch<'event>(
        _: pin::Pin<&mut Self>,
        event: Dispatch<'event, 'd, Self::Scope>,
        _: schedule::Turn<'_, 'd>,
        _: &mut life::Lifecycle<'d, impl Report<Event = crate::Reported>>,
    ) -> ops::ControlFlow<Dispatch<'event, 'd, Self::Scope>> {
        ops::ControlFlow::Break(event)
    }

    /// Reports waits into the same traversal until an owner can run immediately.
    fn progress<const STOP: bool>(
        _: pin::Pin<&Self>,
        _: Progress<'_, '_, 'd>,
        _: Option<&mut schedule::Waits<'d>>,
    ) -> ops::ControlFlow<()> {
        ops::ControlFlow::Continue(())
    }

    fn shutdown(
        app: pin::Pin<&mut Self>,
        turn: schedule::Turn<'_, 'd>,
        driver: &mut life::Lifecycle<'d, impl Report<Event = crate::Reported>>,
    ) {
        if let Some(child) = Self::child(app) {
            App::shutdown(child, turn, driver);
        }
    }

    fn finish(
        app: pin::Pin<&mut Self>,
        install: life::Install<'_, 'd>,
        finish: &mut finish::Finish<'_, 'd, impl Report<Event = crate::Reported>>,
    ) {
        if let Some(child) = Self::child(app) {
            App::finish(child, install, finish);
        }
    }
}

impl<'d> Layout<'d> for () {
    type Scope = Infallible;
    type ParkPlan = ();
}

// SAFETY: the empty root has no routes, retained owners, or lifecycle work.
unsafe impl<'d> App<'d> for () {
    const ROUTES: settings::Routes = settings::Routes::EMPTY;
}

#[derive(Default)]
pub struct Census {
    parks: usize,
    groups: usize,
    coords: usize,
}

impl Census {
    pub fn coordinate(&mut self) -> Result<(), alloc::Overflow> {
        self.groups = self.groups.checked_add(1).ok_or(alloc::Overflow)?;
        self.coords = self.coords.checked_add(1).ok_or(alloc::Overflow)?;
        Ok(())
    }

    fn include_leaf(&mut self, coords: usize) -> Result<(), alloc::Overflow> {
        self.parks = self.parks.checked_add(1).ok_or(alloc::Overflow)?;
        self.groups = self
            .groups
            .checked_add(usize::from(coords != 0))
            .ok_or(alloc::Overflow)?;
        self.coords = self.coords.checked_add(coords).ok_or(alloc::Overflow)?;
        Ok(())
    }
}

#[derive(Default)]
pub struct Flat {
    parks: usize,
    next: [usize; 2],
    groups: u32,
    coord: u32,
}

pub trait Plan: Sealed + Default {
    fn flat(&mut self) -> Option<&mut Flat>;

    fn prepare<'d, D: App<'d, ParkPlan = Self>>(
        &mut self,
        app: pin::Pin<&D>,
    ) -> Result<Count, alloc::Overflow> {
        Flat::census(self.flat(), app)
    }
}

impl Plan for () {
    fn flat(&mut self) -> Option<&mut Flat> {
        None
    }
}

impl Plan for Flat {
    fn flat(&mut self) -> Option<&mut Flat> {
        Some(self)
    }
}

impl Flat {
    fn census<'d, D: App<'d>>(
        flat: Option<&mut Self>,
        app: pin::Pin<&D>,
    ) -> Result<Count, alloc::Overflow> {
        let mut count = Census::default();
        D::census(app, &mut count)?;
        if let Some(flat) = flat {
            flat.parks = count.parks;
            flat.groups = count.groups as u32;
        }
        Ok(Count::new(count.coords))
    }

    /// # Safety
    /// Run the same admitted pinned root with its unchanged census and turn.
    pub(crate) unsafe fn run<'app, 'driver, 'turn, 'd: 'driver + 'turn, D: App<'d>>(
        stored: &mut D::ParkPlan,
        app: pin::Pin<&'app mut D>,
        turn: schedule::Turn<'turn, 'd>,
        driver: &'driver mut life::Lifecycle<'d, impl Report<Event = crate::Reported>>,
    ) {
        let Some(plan) = stored.flat() else {
            // SAFETY: the installed owner carries this root's admitted turn.
            unsafe { D::park(app, turn, driver) };
            return;
        };
        let ahead = [
            start(&mut plan.next[0], turn.app().remaining(), plan.parks),
            start(&mut plan.next[1], turn.maint().remaining(), plan.parks),
        ];
        let mut next = plan.coord as usize;
        let coord = start(&mut next, turn.coord().remaining(), plan.groups as usize);
        plan.coord = next as u32;
        let mut sweep = schedule::raw::Sweep {
            turn,
            driver,
            parks: plan.parks,
            ahead,
            groups: plan.groups,
            coord: coord as u32,
        };
        // SAFETY: preparation admitted the same pinned traversal and its counts.
        unsafe { D::sweep(app, &mut sweep) };
    }

    /// # Safety
    /// Resume the unchanged head after native finish. An unadmitted root cannot run.
    pub(crate) unsafe fn resume<'d, D: App<'d>>(&self, app: pin::Pin<&D>) -> D::ParkPlan {
        let mut resumed = D::ParkPlan::default();
        if let Some(plan) = resumed.flat() {
            let _ = Self::census(Some(plan), app);
            for (next, prior) in plan.next.iter_mut().zip(self.next) {
                if prior < plan.parks {
                    *next = prior;
                }
            }
            if self.coord < plan.groups {
                plan.coord = self.coord;
            }
        }
        resumed
    }
}

fn start(next: &mut usize, credits: usize, count: usize) -> usize {
    if credits == 0 || count <= 1 {
        return 0;
    }
    let at = *next;
    let next_at = at.wrapping_add(1);
    *next = if next_at == count { 0 } else { next_at };
    at
}

/// # Safety
/// Keep admitted owner identities, presence, addresses and routes fixed through finish.
/// Neither method replaces owners or reclaims storage before native shutdown and drain.
pub unsafe trait Drain<'d>: App<'d> {
    fn begin(
        self: pin::Pin<&mut Self>,
        turn: schedule::Turn<'_, 'd>,
        driver: &mut life::Lifecycle<'d, impl Report<Event = crate::Reported>>,
    );

    /// Reports drain work after the application's pre-park traversal.
    /// Completion does not authorize reclaiming retained native owners.
    fn progress(
        self: pin::Pin<&Self>,
        region: &region::Token<region::Identity<'d>>,
        state: Option<&mut schedule::Waits<'d>>,
    ) -> ControlFlow<()>;

    fn force(
        self: pin::Pin<&mut Self>,
        turn: schedule::Turn<'_, 'd>,
        driver: &mut life::Lifecycle<'d, impl Report<Event = crate::Reported>>,
    );
}

/// One complete coordinator count classified at installation.
#[derive(Clone, Copy, Debug)]
pub enum Count {
    Bounded(bounded::raw::U32<0, { schedule::LIMIT as u32 }>),
    Excess(NonZero<usize>),
}

impl Count {
    pub const fn new(value: usize) -> Self {
        match bounded::raw::U32::from_usize(value) {
            Some(value) => Self::Bounded(value),
            None => Self::Excess(NonZero::<usize>::MIN.saturating_add(value - 1)),
        }
    }

    pub const fn get(self) -> usize {
        match self {
            Self::Bounded(value) => value.into_usize(),
            Self::Excess(value) => value.get(),
        }
    }

    pub(in crate::executor) fn admit<E>(self) -> Result<(), executor::InstallError<E>> {
        match self {
            Self::Bounded(_) => Ok(()),
            Self::Excess(count) => Err(executor::InstallError::Coordinators {
                count,
                limit: schedule::LIMIT,
            }),
        }
    }
}