dope-core 0.75.0

Owned native I/O and completion driver for dope
Documentation
use std::{marker, mem, ops::ControlFlow, task};

use dope_sys::{engine, engine::life, engine::life::Quiesced as _, probe::Stopped, table::Retire};

use crate::{
    Engine,
    driver::{
        life::{Final, Lifecycle, Local},
        result::poll::{self, fault},
        retained::flight,
    },
    io::{self, fd::domain::retire},
};

/// Completion authority borrowed from one exact driver-local root.
/// Consuming zero-sized phases make terminal progress linear; the `Local`
/// borrow keeps backend, flight-arena, and driver identities inseparable.
#[repr(transparent)]
pub(crate) struct Resolver<'a, 'd, Report, State = Running> {
    pub(crate) lifecycle: &'a mut Lifecycle<'d, Report>,
    state: marker::PhantomData<State>,
}

pub(crate) struct Running;
pub(crate) struct Cancelling;
pub(crate) struct Closing;

/// Final census and source borrowed separately from the exact native backend.
pub(crate) struct Terminal<'s, 'd> {
    descriptors: retire::View<'d>,
    flights: &'s flight::Arena,
    source: &'s Option<dope_sys::engine::register::Source<'d>>,
}

pub(crate) trait Reclaim {}

impl<'a, 'd, Report> Resolver<'a, 'd, Report, Running> {
    pub(crate) fn new(lifecycle: &'a mut Lifecycle<'d, Report>) -> Self {
        Self {
            lifecycle,
            state: marker::PhantomData,
        }
    }
}

impl<'a, 'd, Report: io::Report>
    From<<crate::Backend as life::Finish<'a, Resolver<'a, 'd, Report, Closing>>>::Quiesced>
    for Resolver<'a, 'd, Report, Final>
{
    fn from(
        done: <crate::Backend as life::Finish<'a, Resolver<'a, 'd, Report, Closing>>>::Quiesced,
    ) -> Self {
        let resolver = done.into_inner();
        resolver.lifecycle.local.flights.finish();
        Self {
            lifecycle: resolver.lifecycle,
            state: marker::PhantomData,
        }
    }
}

impl<'a, 'd, Report: io::Report, State> Resolver<'a, 'd, Report, State> {
    /// Consumes the head selected from this local domain without intervening mutation.
    pub(super) fn release(&mut self, pending: retire::Pending<'d>) -> life::Step {
        let retire = self.lifecycle.local.driver.descriptors().retirement();
        match Retire::retire(
            &mut *self.lifecycle.local.backend,
            pending.classify(),
            retire,
        ) {
            task::Poll::Ready(done) => {
                #[cfg(target_os = "linux")]
                let dope_sys::table::closed::Submitted {} = done;
                #[cfg(target_os = "macos")]
                {
                    use dope_sys::table::closed::{Completed, File};
                    let Completed {
                        slot,
                        file,
                        reactor,
                    } = done;
                    let file = match file {
                        File::Missing(cause) => poll::Close::Missing(cause.into()),
                        File::Closed(result) => poll::Close::Closed(result),
                    };
                    self.lifecycle.report.report(io::Reclaimed::Close {
                        slot: slot.into(),
                        file,
                        reactor: reactor.map_err(poll::Cause::from),
                    });
                }
                life::Step::Advanced
            }
            task::Poll::Pending => life::Step::Blocked,
        }
    }
}

impl<'a, 'd, Report: io::Report> life::Cancel for Resolver<'a, 'd, Report, Running> {
    type Cancelling = Resolver<'a, 'd, Report, Cancelling>;

    fn cancel(self) -> Self::Cancelling {
        Resolver {
            lifecycle: self.lifecycle,
            state: marker::PhantomData,
        }
    }
}

impl<'a, 'd, Report: io::Report> life::Close for Resolver<'a, 'd, Report, Running> {
    type Closing = Resolver<'a, 'd, Report, Closing>;

    fn into_closing(self) -> Self::Closing {
        Resolver {
            lifecycle: self.lifecycle,
            state: marker::PhantomData,
        }
    }
}

impl<'a, 'd, Report: io::Report> life::Close for Resolver<'a, 'd, Report, Cancelling> {
    type Closing = Resolver<'a, 'd, Report, Closing>;

    fn into_closing(self) -> Self::Closing {
        Resolver {
            lifecycle: self.lifecycle,
            state: marker::PhantomData,
        }
    }
}

impl<Report: io::Report, State> life::Resolver for Resolver<'_, '_, Report, State> {
    type Backend = Engine;
    type Fault = fault::Fault;

    fn backend(&mut self) -> &mut Self::Backend {
        &mut self.lifecycle.local.backend
    }

    fn retire_one(&mut self) -> life::Step {
        let Some(pending) = self
            .lifecycle
            .local
            .driver
            .descriptors()
            .retirement()
            .pending()
        else {
            return life::Step::Empty;
        };
        self.release(pending)
    }

    fn has_pending(&self) -> bool {
        self.lifecycle
            .local
            .driver
            .descriptors()
            .retirement()
            .has_pending()
    }

    fn has_flights(&self) -> bool {
        self.lifecycle.local.flights.is_pending()
    }

    fn has_inflight(&self) -> bool {
        self.lifecycle
            .local
            .driver
            .descriptors()
            .retirement()
            .has_inflight()
    }
}

impl<'a, 'd, Report: io::Report> life::Resume for Resolver<'a, 'd, Report, Final> {
    type Terminal<'s>
        = Terminal<'s, 'd>
    where
        Self: 's;

    fn terminal(&mut self) -> (&mut Engine, Self::Terminal<'_>) {
        let Local {
            driver,
            backend,
            flights,
            ..
        } = &mut self.lifecycle.local;
        (
            &mut **backend,
            Terminal {
                descriptors: driver.descriptors().retirement(),
                flights,
                source: &self.lifecycle.source,
            },
        )
    }
}

impl life::Terminal for Terminal<'_, '_> {
    fn has_flights(&self) -> bool {
        self.flights.is_pending()
    }

    fn has_inflight(&self) -> bool {
        self.descriptors.has_inflight()
    }

    fn has_pending(&self) -> bool {
        self.descriptors.has_pending()
    }

    fn source(&self) -> Option<dope_sys::engine::register::Source<'_>> {
        *self.source
    }
}

impl<'a, 'd, Report: io::Report, State: Reclaim> life::Reclaim for Resolver<'a, 'd, Report, State> {
    fn reclaim(mut self) -> Result<ControlFlow<Self, Self>, Stopped<Self, fault::Fault>> {
        #[cfg(target_os = "linux")]
        let result = {
            let mut storage = mem::MaybeUninit::uninit();
            let mut packet = match crate::ring::cqe::Envelope::next(
                o3::mem::slot::Vacant::new(&mut storage),
                &mut self.lifecycle.local,
            ) {
                Some(Some(packet)) => packet,
                Some(None) => return Ok(ControlFlow::Continue(self)),
                None => return Ok(ControlFlow::Break(self)),
            };
            crate::completion::reclaim(&mut self, packet.get_mut())
        };
        #[cfg(target_os = "macos")]
        let result = {
            let Some(entry) = self.lifecycle.local.backend.next() else {
                return Ok(ControlFlow::Break(self));
            };
            crate::completion::reclaim(&mut self, entry)
        };
        match result {
            Ok(()) => Ok(ControlFlow::Continue(self)),
            Err(cause) => Err(Stopped { state: self, cause }),
        }
    }

    fn fault(failure: Stopped<Self, fault::Fault>) -> Self {
        failure
            .state
            .lifecycle
            .report
            .report(io::Reclaimed::Fault(failure.cause));
        failure.state
    }

    fn reactor(&mut self, failure: <Engine as engine::raw::Poll>::Error) {
        self.lifecycle
            .report
            .report(io::Reclaimed::Reactor(poll::Cause::from(failure)));
    }
}

impl Reclaim for Cancelling {}

impl Reclaim for Closing {}

const _: () = {
    assert!(mem::size_of::<Resolver<'static, 'static, ()>>() == mem::size_of::<usize>());
    assert!(
        mem::size_of::<Resolver<'static, 'static, (), Cancelling>>() == mem::size_of::<usize>()
    );
    assert!(mem::size_of::<Resolver<'static, 'static, (), Closing>>() == mem::size_of::<usize>());
    assert!(mem::size_of::<Resolver<'static, 'static, (), Final>>() == mem::size_of::<usize>());
};