dope-core 0.77.0

Owned native I/O and completion driver for dope
Documentation
use dope_sys::io::reactor::{
    complete::flags::Flow,
    event::{self, Reclaimed, kind},
};
use std::{marker, mem, pin, time};

use dope_sys::table::{self, Slots as _, reclaim::Queue as _};
use dope_sys::{
    engine::{self, register},
    kernel::Fatal,
};
use native::{drain, sealed};
use o3::base::cell::{brand, region};

use crate::{
    Engine, Reported,
    driver::{
        self, Local, Native,
        result::poll,
        retained::flight,
        route::{self, lease::Registry},
        schedule::{clock, state},
        storage::{self, resident},
    },
    executor::{
        self, boot,
        drive::{self, block, turn::scope::Boot},
        session,
    },
    io::{event::net::accept, fd::access::Access, transfer},
    topology::lending,
};

pub mod creation;
pub mod domain;
pub mod finish;
pub mod native;

/// Application completions still require ordinary driver dispatch before startup.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Busy;

/// Generation-owned source and the policy responsible for its transitions.
pub struct Lifecycle<'d, Report> {
    pub(crate) local: Local<'d>,
    pub(crate) source: Option<register::Source<'d>>,
    pub(crate) pending: bool,
    pub(crate) report: &'d mut Report,
}

impl<'d, Report: event::Report<Event = Reported>> Lifecycle<'d, Report> {
    pub fn context(&mut self) -> &mut driver::Local<'d> {
        &mut self.local
    }

    pub fn driver_ref(&self) -> driver::Reference<'d> {
        self.local.driver
    }

    /// Reports one exact cancellation rejection to this scope's mandatory observer.
    pub fn rejected(&mut self, failure: &crate::CancelRejection) {
        self.report.report(failure.into());
    }

    /// Reports a consumed accept failure with its original driver-bound target.
    pub fn accept_error(
        &mut self,
        target: route::Erased<'d, kind::Accept>,
        cause: accept::Failure,
        flow: Flow,
    ) {
        self.report.report(Reclaimed::AcceptRoute {
            target: target.into_token(),
            cause,
            flow,
        });
    }

    /// Reports one already classified receive control or released data prefix.
    pub fn received(
        &mut self,
        target: route::Erased<'d, kind::Recv, impl route::Selection>,
        flow: Flow,
        result: Result<transfer::Len, crate::Errno>,
    ) {
        self.report.report(Reclaimed::RecvRoute {
            target: target.into_token(),
            result,
            flow,
        });
    }

    pub fn commit(&mut self, work: state::Reactor<'_, 'd>) -> Result<poll::Commit, poll::Error> {
        work.reclaim(self);
        let retry = self.local.retry;
        let pending =
            crate::Engine::commit(self, work.quota, retry).map_err(poll::Error::from_backend)?;
        self.local.retry = false;
        Ok(if pending {
            poll::Commit::Pending
        } else {
            poll::Commit::Drained
        })
    }

    pub fn wait(
        &mut self,
        work: state::Reactor<'_, 'd>,
        timeout: Option<time::Duration>,
    ) -> Result<(), poll::Error> {
        work.reclaim(self);
        sealed::wait(&mut self.local, work, timeout, self.pending)
    }

    pub fn release<T>(&mut self, owner: T) {
        drop(owner);
        self.retire();
    }

    pub(crate) fn retire(&mut self) {
        let view = self.local.driver.descriptors().retirement();
        table::Retire::drain(
            &mut *self.local.backend,
            view,
            view.pending(),
            &mut *self.report,
        );
    }

    fn finish<const STOP: bool, const RESUME: bool>(&mut self) {
        sealed::reclaim(&mut self.local, usize::MAX);
        drain::routes(&mut self.local);
        if let Err(cause) =
            crate::Engine::finish::<STOP, RESUME, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _>(self)
        {
            Fatal::Retirement(&cause).terminate();
        }
        if STOP || !RESUME {
            self.local.flights.finish();
        }
    }
}

// SAFETY: Root::enter lends the same engine, flight arena and descriptor domain.
unsafe impl<'d, R> engine::raw::Owner<'d, Engine, flight::Arena, Access<'d>> for Lifecycle<'d, R>
where
    R: event::Report<Event = Reported>,
{
    type Report = R;

    unsafe fn parts(
        &mut self,
    ) -> (
        &mut Engine,
        &'d flight::Arena,
        Access<'d>,
        &mut R,
        &mut Option<register::Source<'d>>,
        &mut bool,
    ) {
        (
            &mut *self.local.backend,
            self.local.flights,
            self.local.driver.descriptors(),
            &mut *self.report,
            &mut self.source,
            &mut self.pending,
        )
    }
}

/// Owns one native generation and every authority lent while it is running.
pub struct Core<'env: 'd, 'd, Q, Report> {
    pub(crate) lifecycle: Lifecycle<'d, Report>,
    pub(crate) work: state::Core<'d>,
    pub(crate) token: region::Token<brand::Identity<'d>>,
    pub(crate) pending: Option<event::raw::Completion<'d, flight::Complete<'d>>>,
    pub(crate) source: &'d Q,
    environment: marker::PhantomData<&'env mut &'env ()>,
}

impl<'env, 'd, Q, Report: event::Report<Event = Reported>> Core<'env, 'd, Q, Report> {
    pub(crate) fn install<'app, D>(
        &'app mut self,
        start: clock::Sample,
        backing: pin::Pin<&'app executor::raw::Backing<'d, D>>,
    ) -> session::App<'app, 'env, 'd, D, Report, Q>
    where
        'd: 'app,
        D: executor::raw::App<'d>,
    {
        let (token, driver, schedule) = self.split();
        schedule.sample(start);
        let stored = backing.pin();
        let mut install = Install::new(backing, driver.driver_ref());
        D::install(
            lending::raw::Project::exclusive(token.pin_mut(stored).project().app),
            install.reborrow(),
        );
        session::App {
            core: self,
            stored,
            install,
        }
    }

    pub fn drive<R>(&mut self, root: R) -> Result<R::Output, drive::Error>
    where
        R: boot::Root<'d>,
        Q: executor::Startup,
    {
        let observer = self.source;
        let state = Boot::try_new(self).map_err(drive::Error::from);
        block::run_boot(state, root, observer)
    }

    pub fn driver(&mut self) -> &mut Local<'d> {
        &mut self.lifecycle.local
    }

    pub fn driver_ref(&self) -> driver::Reference<'d> {
        self.lifecycle.driver_ref()
    }

    pub fn source(&self) -> &'d Q {
        self.source
    }

    pub fn split(
        &mut self,
    ) -> (
        &mut region::Token<brand::Identity<'d>>,
        &mut Lifecycle<'d, Report>,
        &mut state::Core<'d>,
    ) {
        (&mut self.token, &mut self.lifecycle, &mut self.work)
    }

    pub fn try_boot(&self) -> Result<(), Busy> {
        use dope_sys::table::token::host::raw;

        if raw::Drain::is_pending(self.lifecycle.local.flights) {
            Err(Busy)
        } else {
            Ok(())
        }
    }

    pub fn quiesce(&mut self) {
        self.lifecycle.finish::<true, true>();
        self.lifecycle.finish::<false, true>();
    }

    fn run_storage<S, I, F, R, E, Reject>(
        &mut self,
        plan: S,
        input: I,
        body: F,
        rejected: Reject,
    ) -> (Result<R, E>, epochs::Closed)
    where
        S: storage::Build + 'd,
        Reject: FnOnce(&Q, S::Error, I, F) -> E,
        I: 'd,
        F: for<'life, 'p> FnOnce(I, storage::Loan<'life, 'p, 'd, S>, &mut Self) -> R,
    {
        let (mut backing, owned) = match plan.try_store() {
            Ok(storage) => storage,
            Err(cause) => {
                let error = rejected(self.source, cause, input, body);
                let proof = self.retire();
                return (Err(error), proof);
            }
        };
        match plan.try_build(
            owned,
            &mut backing,
            storage::Context::new(&mut self.lifecycle.local),
        ) {
            Ok(value) => {
                let store = pin::pin!(value);
                let output = body(input, storage::Loan::new(store.as_ref()), self);
                let proof = self.retire();
                (Ok(output), proof)
            }
            Err(cause) => {
                let error = rejected(self.source, cause, input, body);
                let proof = self.retire();
                (Err(error), proof)
            }
        }
    }

    fn retire(&mut self) -> epochs::Closed {
        self.pending = None;
        if mem::take(&mut self.lifecycle.pending) {
            self.lifecycle.report.report(Reclaimed::Shutdown);
        }
        self.lifecycle.finish::<true, false>();
        epochs::Closed { _seal: () }
    }
}

mod epochs;

struct Root<'native, 'env, Q, Report> {
    flights: &'native mut flight::Arena,
    resident: &'native mut resident::Arena,
    source: &'native domain::raw::Source<Q>,
    report: &'native mut Report,
    environment: marker::PhantomData<&'env mut &'env ()>,
}

impl<'env, Q, Report: event::Report<Event = Reported>> Root<'_, 'env, Q, Report> {
    fn enter<'d>(
        &'d mut self,
        shared: driver::ReceiveRoot<'d>,
        token: region::Token<brand::Identity<'d>>,
        regions: (
            region::Token<region::Identity<'d>>,
            region::Token<region::Identity<'d, 1>>,
        ),
        backend: Native<'d>,
    ) -> Core<'env, 'd, Q, Report>
    where
        'env: 'd,
    {
        let alloc = self.resident.enter(&regions.0);
        let local = Local {
            driver: driver::Reference::new(shared, regions.0.proof()),
            backend,
            retry: false,
            flights: &*self.flights,
            resident: alloc,
            routes: Registry::new(),
            region: regions,
        };
        Core {
            work: state::Core::new(local.driver),
            lifecycle: Lifecycle {
                local,
                source: self.source.descriptor(),
                pending: false,
                report: &mut *self.report,
            },
            token,
            pending: None,
            source: self.source.owner(),
            environment: self.environment,
        }
    }
}

/// Proof that nested resources are installed beneath their pinned owner.
#[must_use]
pub struct Install<'a, 'd> {
    owner: marker::PhantomData<&'a mut &'a ()>,
    _driver: driver::Invariant<'d>,
}

impl<'a, 'd> Install<'a, 'd> {
    fn new<D, S>(
        _: pin::Pin<&'a executor::raw::Backing<'d, D, S>>,
        driver: driver::Reference<'d>,
    ) -> Self
    where
        D: executor::raw::Layout<'d>,
        S: lending::raw::Project<App = D>,
    {
        Self {
            owner: marker::PhantomData,
            _driver: driver.brand,
        }
    }

    pub fn reborrow(&mut self) -> Install<'_, 'd> {
        Install {
            owner: marker::PhantomData,
            _driver: self._driver,
        }
    }
}

const _: () = {
    assert!(mem::size_of::<Install<'static, 'static>>() == 0);
    assert!(mem::align_of::<Install<'static, 'static>>() == 1);
};