dope-core 0.77.0

Owned native I/O and completion driver for dope
Documentation
use std::{cell, mem::size_of};

use dope_sys::io::reactor::event::Report;
use o3::mem::{self, quota};

use crate::{
    driver,
    driver::{
        life::{
            self,
            native::{drain, sealed},
        },
        schedule,
        schedule::{
            clock::{self, timer},
            ready,
        },
    },
};

pub(crate) mod lanes;

pub(super) enum ReactorLane {}
pub(super) enum CoordLane {}
pub(super) enum AppLane {}
pub(super) enum MaintLane {}

#[derive(Clone, Copy)]
pub(super) enum Cursor {
    First,
    Second,
}

impl Cursor {
    const fn next(self) -> Self {
        match self {
            Self::First => Self::Second,
            Self::Second => Self::First,
        }
    }

    const fn index(self) -> usize {
        match self {
            Self::First => 0,
            Self::Second => 1,
        }
    }
}

pub(super) struct Lanes {
    pub(super) ready: quota::Ledger<ready::Lane>,
    pub(super) coord: quota::Ledger<CoordLane>,
    pub(super) app: quota::Ledger<AppLane>,
    pub(super) timers: quota::Ledger<timer::Tag>,
    pub(super) maint: quota::Ledger<MaintLane>,
}

pub struct Core<'d> {
    pub(super) driver: driver::Reference<'d>,
    pub(super) reactor: quota::Ledger<ReactorLane>,
    cursor: cell::Cell<Cursor>,
    pub(super) lanes: Lanes,
    pub(super) deferred: cell::Cell<bool>,
}

impl<'d> Core<'d> {
    pub(in crate::driver) fn new(driver: driver::Reference<'d>) -> Self {
        Self {
            driver,
            reactor: quota::Ledger::new(schedule::LIMIT),
            cursor: cell::Cell::new(Cursor::First),
            lanes: Lanes {
                ready: quota::Ledger::new(schedule::LIMIT),
                coord: quota::Ledger::new(schedule::LIMIT),
                app: quota::Ledger::new(schedule::LIMIT),
                timers: quota::Ledger::new(schedule::LIMIT),
                maint: quota::Ledger::new(schedule::LIMIT),
            },
            deferred: cell::Cell::new(false),
        }
    }

    pub(super) fn reset(&mut self) {
        self.deferred.set(false);
        self.reactor.reset(schedule::LIMIT);
        self.lanes.ready.reset(schedule::LIMIT);
        self.lanes.coord.reset(schedule::LIMIT);
        self.lanes.app.reset(schedule::LIMIT);
        self.lanes.timers.reset(schedule::LIMIT);
        self.lanes.maint.reset(schedule::LIMIT);
    }

    pub(super) fn is_exhausted(&self) -> bool {
        self.deferred.get()
            || self.reactor.remaining() == 0
            || self.lanes.ready.remaining() == 0
            || self.lanes.app.remaining() == 0
            || self.lanes.timers.remaining() == 0
            || self.lanes.maint.remaining() == 0
    }
}

pub(in crate::driver) const REACTORS: usize = 2;

#[must_use = "the active turn must remain live for the complete driver cycle"]
pub struct Guard<'turn, 'd> {
    state: &'turn Core<'d>,
}

#[must_use = "reactor authority must be consumed by Poll or Source"]
pub struct Reactor<'turn, 'd> {
    pub(crate) quota: mem::raw::Shared<'turn, schedule::Domain<'d>>,
    pub(in crate::driver::schedule) cursor: Cursor,
}

pub struct Coord<'turn, 'd> {
    state: &'turn Core<'d>,
}

impl<'d> Core<'d> {
    pub fn begin_at(&mut self, sample: clock::Sample) -> Guard<'_, 'd> {
        self.sample(sample);
        self.begin()
    }

    /// Installs the clock sample for work that opens no driver cycle.
    pub fn sample(&mut self, sample: clock::Sample) {
        self.driver.scheduler().set_turn_now(sample.into_raw());
    }

    pub fn begin(&mut self) -> Guard<'_, 'd> {
        self.reset();
        Guard { state: self }
    }
}

impl<'turn, 'd> Guard<'turn, 'd> {
    pub fn turn(&self) -> schedule::Turn<'turn, 'd> {
        schedule::Turn::new(self.state)
    }

    pub fn reactor(&mut self) -> Reactor<'_, 'd> {
        self.split().0
    }

    pub fn split(&mut self) -> (Reactor<'turn, 'd>, schedule::Turn<'turn, 'd>) {
        let state = self.state;
        let cursor = state.cursor.get();
        state.cursor.set(cursor.next());
        (
            Reactor {
                quota: mem::raw::Shared::reserve_all(&state.reactor),
                cursor,
            },
            schedule::Turn::new(state),
        )
    }

    /// Runs every timer that has expired at the current turn sample.
    pub fn expire(&mut self) {
        let state = self.state;
        state.driver.timer().expire(&state.lanes.timers);
    }

    pub fn is_exhausted(&self) -> bool {
        self.state.is_exhausted()
    }

    pub(in crate::driver::schedule) fn ready_budget(
        &self,
    ) -> quota::Lease<'_, schedule::Domain<'d, ready::Lane>> {
        quota::Lease::reserve_all(&self.state.lanes.ready)
    }
}

impl<'d> Reactor<'_, 'd> {
    /// Returns native buffers and notifies current receive waiters.
    pub(crate) fn reclaim(
        &self,
        ctx: &mut life::Lifecycle<'d, impl Report<Event = crate::Reported>>,
    ) {
        const {
            assert!(REACTORS != 0);
            assert!(1 < REACTORS);
            assert!(REACTORS < usize::MAX);
        }
        sealed::reclaim(&mut ctx.local, schedule::LIMIT);
        let total = self.quota.remaining();
        let base = total / REACTORS;
        let extra = total % REACTORS;
        let span = (1 + REACTORS - (self.cursor() % REACTORS)) % REACTORS;
        let keep = base + usize::from(span < extra);
        let mut budget = self.budget::<drain::Lane>(total.saturating_sub(keep));
        drain::Drain::reclaim(ctx, &mut budget);
    }

    pub(crate) const fn cursor(&self) -> usize {
        self.cursor.index()
    }

    pub(crate) fn budget<'budget, Lane>(
        &'budget self,
        limit: usize,
    ) -> quota::Lease<'budget, schedule::Domain<'d, Lane>> {
        self.quota.lease_up_to(limit)
    }
}

impl<'turn, 'd> Coord<'turn, 'd> {
    pub(in crate::driver::schedule) fn new(state: &'turn Core<'d>) -> Self {
        Self { state }
    }

    pub fn take(&mut self) -> Result<(), quota::Exhausted> {
        let taken = self.state.lanes.coord.take();
        if taken.is_err() {
            self.state.deferred.set(true);
        }
        taken
    }

    pub fn remaining(&self) -> usize {
        self.state.lanes.coord.remaining()
    }
}

const _: () = {
    let word = size_of::<usize>();
    assert!(size_of::<Guard<'static, 'static>>() == word);
};