dope-runtime 0.75.0

Thread-per-core execution and process lifecycle for dope
Documentation
use std::convert;

use dope_core::{
    dope_sys::thread::signal::Signal as _,
    platform::{affinity, signal},
};

use crate::process::{
    failure::{
        bus::{Drain, DrainCause, Event, Shutdown, Startup, State},
        execute,
    },
    runtime::worker::{self, bound},
    watch,
};

mod clock;
pub(in crate::process) mod set;

use clock::Clock;

type Observation<N, F> = Result<
    Option<Clock<<N as watch::Notify>::Heartbeat>>,
    execute::Cause<<N as watch::Notify>::Error, F>,
>;

pub(super) struct Control<'process> {
    source: signal::Source<'process>,
}

impl<'process> Control<'process> {
    pub(super) const fn signal(source: signal::Source<'process>) -> Self {
        Self { source }
    }

    fn wait_ready<'signal, 'id, S, F, I, E, W>(
        workers: usize,
        running: &bound::Bound<'id, I, E, W>,
        poll: &mut set::Set<'id, 'signal, set::Both<'signal, 'process>>,
    ) -> Result<bool, execute::Cause<S, F>>
    where
        E: worker::Entry<I, W>,
    {
        let mut installs = workers;
        let mut ready = if E::GATED { workers } else { 0 };
        while installs != 0 || ready != 0 {
            let index = match poll.wait()? {
                set::Ready::Signal(source) => {
                    source.wait().map_err(execute::Cause::TerminationWait)?;
                    return Ok(false);
                }
                set::Ready::Worker(index) => index,
            };
            match execute::Cause::<S, F>::received(running.main(index).recv(), running.cpu(index))? {
                Event::Installed if installs != 0 => installs -= 1,
                Event::Ready if ready != 0 => ready -= 1,
                event => {
                    let cpu = running.cpu(index);
                    return Err(execute::Cause::BusState(State::StartupEvent(Startup {
                        cpu,
                        event,
                        workers,
                        installed: installs,
                        ready,
                        gated: E::GATED,
                    })));
                }
            }
        }
        Ok(true)
    }

    fn observe<'id, S, F, I, E, W>(
        running: &bound::Bound<'id, I, E, W>,
        ready: set::Ready<'_, 'process, 'id>,
    ) -> Result<(), execute::Cause<S, F>> {
        let index = match ready {
            set::Ready::Signal(source) => {
                source.wait().map_err(execute::Cause::TerminationWait)?;
                return Ok(());
            }
            set::Ready::Worker(index) => index,
        };
        let result = running.main(index).recv();
        let cpu = running.cpu(index);
        let event = execute::Cause::received(result, cpu)?;
        Err(execute::Cause::BusState(State::RuntimeEvent { cpu, event }))
    }

    pub(super) fn ready<I, E, W, F>(
        &self,
        workers: usize,
        running: &worker::Running<'_, I, E, W>,
    ) -> Result<(), execute::Cause<convert::Infallible, F>>
    where
        E: worker::Entry<I, W>,
    {
        running.scope(|running| {
            let mut poll = set::Set::both(&self.source, &running)?;
            if Self::wait_ready(workers, &running, &mut poll)? {
                let ready = poll.wait();
                drop(poll);
                Self::observe(&running, ready?)
            } else {
                Ok(())
            }
        })
    }

    pub(super) fn watch<N, I, E, W, F>(
        &self,
        workers: usize,
        notify: N,
        running: &worker::Running<'_, I, E, W>,
    ) -> Observation<N, F>
    where
        N: watch::Notify,
        E: worker::Entry<I, W>,
    {
        running.scope(|running| {
            let mut poll = set::Set::both(&self.source, &running)?;
            if !Self::wait_ready(workers, &running, &mut poll)? {
                return Ok(None);
            }
            let beat = notify.ready().map_err(execute::Cause::WatchReady)?;
            let mut clock = Clock::new(beat)?;
            let result = loop {
                match clock.poll(&mut poll) {
                    Ok(Some((entry, ready))) => {
                        drop(entry);
                        break Self::observe(&running, ready);
                    }
                    Ok(None) => {}
                    Err(error) => break Err(error),
                }
            };
            drop(poll);
            result?;
            Ok(Some(clock))
        })
    }
}

#[derive(Default)]
struct Counts {
    drained: usize,
    done: usize,
}

impl Counts {
    fn record<S, F>(
        &mut self,
        event: Event,
        cpu: affinity::Cpu,
        workers: usize,
    ) -> Result<(), execute::Cause<S, F>> {
        match event {
            Event::Drain => self.drained += 1,
            Event::Done => self.done += 1,
            event => {
                return Err(execute::Cause::BusState(State::DrainEvent(Drain {
                    cause: DrainCause::Event { cpu, event },
                    workers,
                    drained: self.drained,
                    done: self.done,
                })));
            }
        }
        if self.done == workers && self.drained != workers {
            return Err(execute::Cause::BusState(State::DrainOrder(Drain {
                cause: DrainCause::Order,
                workers,
                drained: self.drained,
                done: self.done,
            })));
        }
        Ok(())
    }
}

pub(super) fn drain<S, F, H, I, E, W>(
    running: &worker::Stopping<'_, I, E, W>,
    workers: usize,
    mut clock: Clock<H>,
) -> Result<(), execute::Cause<S, F>>
where
    H: watch::Heartbeat<S>,
    E: worker::Entry<I, W>,
{
    running
        .try_scope(|running| {
            let mut poll = set::Set::bus(&running)?;
            let mut count = Counts::default();
            while E::GATED && count.drained != workers {
                let Some((entry, index)) = clock.poll(&mut poll)? else { continue };
                let (cpu, event) = running.receive(index, entry);
                count.record(execute::Cause::<S, F>::received(event, cpu)?, cpu, workers)?;
            }
            clock.draining()?;
            while count.done != workers {
                let Some((entry, index)) = clock.poll(&mut poll)? else { continue };
                let (cpu, event) = running.receive(index, entry);
                match execute::Cause::<S, F>::received(event, cpu)? {
                    Event::Done => count.done += 1,
                    event => {
                        return Err(execute::Cause::BusState(State::ShutdownEvent(Shutdown {
                            cpu,
                            event,
                            workers,
                            done: count.done,
                        })));
                    }
                }
            }
            Ok(())
        })
        .unwrap_or(Ok(()))
}