dope-runtime 0.75.0

Thread-per-core execution and process lifecycle for dope
Documentation
use dope_core::executor::drive::clock;
use std::{mem, time};

use o3::base::time::Positive;

use crate::process::{
    failure::{config, execute},
    runtime::control::set,
    watch,
};

pub(in crate::process) struct Clock<H> {
    heartbeat: H,
    period: Positive,
    next: time::Instant,
}

impl<H> Clock<H> {
    pub(in crate::process) fn new<S, F>(beat: H) -> Result<Self, execute::Cause<S, F>>
    where
        H: watch::Heartbeat<S>,
    {
        let period = beat.period();
        let now = time::Instant::now();
        let next = clock::Range::try_add(now, period.get())
            .map_err(config::Error::HeartbeatDeadline)
            .map_err(execute::Cause::Config)?;
        Ok(Self {
            heartbeat: beat,
            period,
            next,
        })
    }

    pub(in crate::process) fn poll<'poll, 'worker, 'signal, S, F, M>(
        &mut self,
        poll: &'poll mut set::Set<'worker, 'signal, M>,
    ) -> Result<
        Option<(dope_core::platform::poll::Ready<'poll, 'signal>, M::Ready<'worker>)>,
        execute::Cause<S, F>,
    >
    where
        H: watch::Heartbeat<S>,
        M: set::Mode,
    {
        let left = self.next.saturating_duration_since(time::Instant::now());
        let whole = left.as_millis();
        let partial = u128::from(!left.subsec_nanos().is_multiple_of(1_000_000));
        let millis = (whole + partial).min(i32::MAX as u128) as i32;
        match poll.poll(millis).map_err(execute::Cause::Poll)? {
            Some(ready) => Ok(Some(ready)),
            None => {
                if time::Instant::now() >= self.next {
                    self.pulse(time::Instant::now())?;
                }
                Ok(None)
            }
        }
    }

    pub(in crate::process) fn draining<S, F>(&self) -> Result<(), execute::Cause<S, F>>
    where
        H: watch::Heartbeat<S>,
    {
        self.heartbeat
            .draining()
            .map_err(execute::Cause::WatchDrain)
    }

    fn pulse<S, F>(&mut self, now: time::Instant) -> Result<(), execute::Cause<S, F>>
    where
        H: watch::Heartbeat<S>,
    {
        let deadline = clock::Range::try_add(now, self.period.get())
            .map_err(config::Error::HeartbeatDeadline)
            .map_err(execute::Cause::Config)?;
        self.heartbeat.pulse().map_err(execute::Cause::WatchPulse)?;
        self.next = deadline;
        Ok(())
    }
}

const _: () = {
    assert!(
        mem::size_of::<Clock<()>>()
            == mem::size_of::<time::Duration>() + mem::size_of::<time::Instant>()
    );
};