dope-core 0.77.0

Owned native I/O and completion driver for dope
Documentation
use std::{convert::Infallible, mem, os::fd};

use dope_sys::{
    engine::{register, shutdown},
    io::{Close as _, reactor::event},
    probe::Stopped,
};
use o3::mem::slot::Occupied;

use crate::{
    Engine,
    driver::{
        self, Seed, life,
        result::{self, Kernel},
        retained::flight,
        settings, storage,
        storage::resident::Arena,
    },
    executor,
};

/// The unstarted generation: one driver with the single source it retains.
pub struct Generation<'place, Q = ()>(Occupied<'place, Parts<Q>>);

type Parts<Q> = (
    Engine,
    (
        (Arena, flight::Arena),
        (driver::ReceiveArena, raw::Source<Q>),
    ),
);

/// Uninitialized storage for one generation or its unfinished native recovery.
pub union Place<Q = ()> {
    ready: mem::ManuallyDrop<mem::MaybeUninit<Parts<Q>>>,
    cleanup: mem::ManuallyDrop<mem::MaybeUninit<crate::Resources>>,
    release: mem::ManuallyDrop<mem::MaybeUninit<crate::Released>>,
}

impl<Q> Default for Place<Q> {
    fn default() -> Self {
        Self {
            ready: mem::ManuallyDrop::new(mem::MaybeUninit::uninit()),
        }
    }
}

pub(crate) mod raw;

type Outcome<T, E, Q = ()> = Result<T, Error<E, T, Q>>;

impl<Q> Generation<'_, Q> {
    pub fn run<'env, S, I, F, R, Report>(
        self,
        plan: S,
        input: I,
        body: F,
        report: &mut Report,
    ) -> Outcome<R, Infallible, Q>
    where
        S: storage::Build<Error = Infallible> + 'env,
        Q: 'env,
        I: 'env,
        F: 'env
            + for<'life, 'p, 'd> FnOnce(
                I,
                storage::Loan<'life, 'p, 'd, S>,
                &mut life::Core<'env, 'd, Q, Report>,
            ) -> R,
        Report: event::Report<Event = crate::Reported>,
    {
        raw::run(self, plan, input, body, report, infallible)
    }

    pub fn try_run<'env, S, I, F, R, Report>(
        self,
        plan: S,
        input: I,
        body: F,
        report: &mut Report,
    ) -> Outcome<R, Rejected<S::Error, (I, F)>, Q>
    where
        S: storage::Build + 'env,
        Q: executor::Startup + 'env,
        I: 'env,
        F: 'env
            + for<'life, 'p, 'd> FnOnce(
                I,
                storage::Loan<'life, 'p, 'd, S>,
                &mut life::Core<'env, 'd, Q, Report>,
            ) -> R,
        Report: event::Report<Event = crate::Reported>,
    {
        raw::run(self, plan, input, body, report, Rejected::before_run)
    }

    /// Finishes at the worker's report while a failed native shutdown still owns its result.
    pub fn observe<'env, S, I, F, R, Report, T>(
        self,
        plan: S,
        input: I,
        body: F,
        report: &mut Report,
        finish: impl FnOnce(&mut Report, Result<R, (Unmap, &R)>) -> T,
    ) -> T
    where
        S: storage::Build<Error = Infallible> + 'env,
        Q: 'env,
        I: 'env,
        F: 'env
            + for<'life, 'p, 'd> FnOnce(
                I,
                storage::Loan<'life, 'p, 'd, S>,
                &mut life::Core<'env, 'd, Q, Report>,
            ) -> R,
        Report: event::Report<Event = crate::Reported>,
    {
        match self.run(plan, input, body, report) {
            Ok(value) => finish(report, Ok(value)),
            Err(Error::Close(closing)) => match &closing.result {
                Ok(value) => finish(report, Err((closing.failure(), value))),
                Err(never) => match *never {},
            },
            Err(Error::Storage(never)) => match never {},
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Register {
    Full(result::SubmitError),
    Register(crate::Errno),
}

impl Register {
    pub(crate) fn native(error: register::Error) -> Self {
        match error {
            register::Error::Full(full) => Self::Full(result::SubmitError::from(full)),
            register::Error::Register(error) => Self::Register(error),
        }
    }
}

/// Storage and generation-finalization failures preserved without erasure.
pub enum Error<E, T, Q = ()> {
    Storage(E),
    Close(Closing<E, T, Q>),
}

/// Exact preflight failure paired with the operation that has not run.
pub struct Rejected<E, O> {
    pub cause: E,
    pub operation: O,
}

impl<E, I, F> Rejected<E, (I, F)> {
    fn before_run<Q: executor::Startup>(source: &Q, cause: E, input: I, body: F) -> Self {
        executor::failed(source);
        Self {
            cause,
            operation: (input, body),
        }
    }
}

impl<E, T, Q> Error<E, T, Q> {
    /// Borrows all failures while retaining the application output and retry ownership.
    pub fn cause(&self) -> Cause<&E> {
        match self {
            Self::Storage(error) => Cause::Storage(error),
            Self::Close(state) => Cause::Close {
                storage: state.result.as_ref().err(),
                failure: state.failure(),
            },
        }
    }

    pub fn map_storage<F>(self, map: impl FnOnce(E) -> F) -> Error<F, T, Q> {
        match self {
            Self::Storage(error) => Error::Storage(map(error)),
            Self::Close(state) => Error::Close(state.map_storage(map)),
        }
    }
}

/// Generation result and source retained until backend teardown completes.
pub struct Closing<E, T, Q> {
    result: Result<T, E>,
    stopped: Stopped<Q, <Engine as shutdown::Shutdown>::State>,
}

#[derive(Clone, Copy, Debug)]
pub enum Unmap {
    Backend(storage::Mapping),
    Context(storage::Mapping),
}

impl Unmap {
    fn native<E>(error: shutdown::Failure<E>) -> Self
    where
        Kernel: From<E>,
    {
        match error {
            shutdown::Failure::Backend(error) => Self::Backend(storage::Mapping::from(error)),
            shutdown::Failure::Context(error) => Self::Context(storage::Mapping::from(error)),
        }
    }
}

impl<'p> Generation<'p> {
    pub fn try_new(
        config: settings::Config,
        place: &'p mut Place,
    ) -> Result<Self, executor::Error<'p>> {
        raw::open(&config, (), (), (), place)
    }

    pub fn try_seed(
        config: settings::Config,
        seed: Seed,
        place: &'p mut Place,
    ) -> Result<Self, executor::Error<'p>> {
        raw::open(&config, seed, (), (), place)
    }
}

impl<'p, Q: fd::AsFd> Generation<'p, Q> {
    /// Registers the source. Pass an existing seed or `()` to acquire OS entropy.
    pub fn try_bind(
        config: settings::Config,
        seed: impl TryInto<Seed, Error: Into<Kernel>>,
        source: Q,
        interest: register::Interest,
        place: &'p mut Place<Q>,
    ) -> Result<Self, executor::Error<'p>> {
        raw::open(&config, seed, source, interest, place)
    }
}

fn infallible<Q, I, F>(_: &Q, never: Infallible, _: I, _: F) -> Infallible {
    match never {}
}

trait Registration<Q> {
    fn source(self, owner: &Q) -> Option<register::Source<'_>>;
}

impl Registration<()> for () {
    fn source(self, _: &()) -> Option<register::Source<'_>> {
        None
    }
}

impl<Q: fd::AsFd> Registration<Q> for register::Interest {
    fn source(self, owner: &Q) -> Option<register::Source<'_>> {
        Some(register::Source {
            fd: owner.as_fd(),
            interest: self,
        })
    }
}

impl<E, T, Q> Closing<E, T, Q> {
    fn finish<C>(result: Result<T, E>, source: Q, closed: Result<(), C>) -> Outcome<T, E, Q>
    where
        Engine: shutdown::Shutdown<State = C>,
    {
        match closed {
            Ok(()) => result.map_err(Error::Storage),
            Err(cause) => Err(Error::Close(Self {
                result,
                stopped: Stopped {
                    state: source,
                    cause,
                },
            })),
        }
    }

    pub fn map_storage<F>(self, map: impl FnOnce(E) -> F) -> Closing<F, T, Q> {
        Closing {
            result: self.result.map_err(map),
            stopped: self.stopped,
        }
    }

    pub fn result(&self) -> &Result<T, E> {
        &self.result
    }

    pub fn failure(&self) -> Unmap {
        Unmap::native(shutdown::Cleanup::failure(&self.stopped.cause))
    }

    /// Reports the previous failure before retrying its native owner.
    pub fn try_close(self, report: impl FnMut(Unmap)) -> Outcome<T, E, Q> {
        let (source, closed) = retry(self.stopped, report);
        Self::finish(self.result, source, closed)
    }
}

fn retry<Q, C: shutdown::Cleanup>(
    stopped: Stopped<Q, C>,
    mut report: impl FnMut(Unmap),
) -> (Q, Result<(), C>)
where
    Kernel: From<C::Error>,
{
    let (owner, error) = stopped.cause.recover().into_parts();
    report(Unmap::native(error.into()));
    (stopped.state, owner.try_close())
}

/// Every native cause borrowed without taking the stored application output or source.
#[derive(Debug)]
pub enum Cause<E> {
    Storage(E),
    Close { storage: Option<E>, failure: Unmap },
}

impl<E> Cause<E> {
    /// Projects only the storage cause; generation output and retry owners stay borrowed.
    pub fn map_storage<F>(self, map: impl FnOnce(E) -> F) -> Cause<F> {
        match self {
            Self::Storage(error) => Cause::Storage(map(error)),
            Self::Close { storage, failure } => Cause::Close {
                storage: storage.map(map),
                failure,
            },
        }
    }
}