subc-daemon 0.55.0

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
Documentation
//! Isolate native peer inspection from the async runtime. A native call may
//! wait for a system permission prompt and cannot be cancelled by Rust.

use crate::operator_apps::{Admission, EVIDENCE_BUDGET as BUDGET};
use std::{
    collections::VecDeque,
    panic::{catch_unwind, AssertUnwindSafe},
    sync::{Arc, Condvar, Mutex},
    time::Instant,
};
use tokio::sync::{oneshot, Notify};

const WORKERS: usize = 2;
const QUEUE: usize = 2;

type Work = Box<dyn FnOnce() + Send>;

struct Job {
    deadline: Instant,
    work: Work,
    #[cfg(test)]
    after_pop: Option<Work>,
}

#[derive(Default)]
struct State {
    queue: VecDeque<Job>,
    active: [Option<Instant>; WORKERS],
    closed: bool,
}

type Shared = (Mutex<State>, Condvar, Notify);

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PeerIdentityError {
    Busy,
    Deadline,
    CheckFailed,
}

#[cfg(all(test, target_os = "macos"))]
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum CheckPoint {
    RecognitionStarted,
    RecognitionReturned,
    RecognitionRetrying,
    RevalidationStarted,
    RevalidationChecked,
}

pub(crate) struct PeerIdentityLane {
    shared: Arc<Shared>,
    #[cfg(test)]
    probe: Option<Arc<dyn Fn() + Send + Sync>>,
    #[cfg(all(test, target_os = "macos"))]
    check_probe: Option<Arc<dyn Fn(CheckPoint) + Send + Sync>>,
    #[cfg(all(test, target_os = "macos"))]
    pub(crate) waiting_for_capacity: Notify,
}

impl std::fmt::Debug for PeerIdentityLane {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PeerIdentityLane").finish_non_exhaustive()
    }
}

impl PeerIdentityLane {
    #[cfg(target_os = "macos")]
    pub(crate) fn native() -> &'static Self {
        static LANE: std::sync::OnceLock<PeerIdentityLane> = std::sync::OnceLock::new();
        LANE.get_or_init(Self::start)
    }

    pub(crate) fn start() -> Self {
        let shared = Arc::new(Shared::default());
        let lane = Self {
            shared,
            #[cfg(test)]
            probe: None,
            #[cfg(all(test, target_os = "macos"))]
            check_probe: None,
            #[cfg(all(test, target_os = "macos"))]
            waiting_for_capacity: Notify::new(),
        };
        for index in 0..WORKERS {
            let shared = lane.shared.clone();
            if std::thread::Builder::new()
                .name(format!("subc-peer-identity-{index}"))
                .spawn(move || {
                    subc_os::protect_current_thread().expect("protect peer identity worker thread");
                    worker(&shared, index);
                })
                .is_err()
            {
                lane.close();
                break;
            }
        }
        lane
    }

    #[cfg(test)]
    pub(crate) fn with_probe(mut self, probe: impl Fn() + Send + Sync + 'static) -> Self {
        self.probe = Some(Arc::new(probe));
        self
    }

    #[cfg(all(test, target_os = "macos"))]
    pub(crate) fn with_check_probe(
        mut self,
        probe: impl Fn(CheckPoint) + Send + Sync + 'static,
    ) -> Self {
        self.check_probe = Some(Arc::new(probe));
        self
    }

    #[cfg(all(test, target_os = "macos"))]
    pub(crate) fn probe_check(&self, point: CheckPoint) {
        if let Some(probe) = &self.check_probe {
            probe(point);
        }
    }

    pub(crate) async fn run<T: Send + 'static>(
        &self,
        work: impl FnOnce() -> T + Send + 'static,
    ) -> Option<T> {
        self.run_until(Instant::now() + BUDGET, work).await
    }

    pub(crate) async fn run_until<T: Send + 'static>(
        &self,
        deadline: Instant,
        work: impl FnOnce() -> T + Send + 'static,
    ) -> Option<T> {
        self.run_with_admission(deadline, Admission::Immediate, work)
            .await
            .ok()
    }

    pub(crate) async fn run_with_admission<T: Send + 'static>(
        &self,
        deadline: Instant,
        admission: Admission,
        work: impl FnOnce() -> T + Send + 'static,
    ) -> Result<T, PeerIdentityError> {
        let (tx, rx) = oneshot::channel();
        #[cfg(test)]
        let probe = self.probe.clone();
        let job = Job {
            deadline,
            #[cfg(test)]
            after_pop: None,
            work: Box::new(move || {
                if tx.is_closed() || Instant::now() >= deadline {
                    return;
                }
                #[cfg(test)]
                if let Some(probe) = probe {
                    probe();
                }
                let result = work();
                if Instant::now() < deadline {
                    let _ = tx.send(result);
                }
            }),
        };
        let (state, ready, capacity) = &*self.shared;
        loop {
            // Register before inspecting the queue so a worker cannot free a
            // slot between the capacity check and the start of the wait.
            let changed = capacity.notified();
            {
                let mut state = state.lock().unwrap_or_else(|p| p.into_inner());
                let now = Instant::now();
                if now >= deadline {
                    return Err(PeerIdentityError::Deadline);
                }
                if state.closed || stuck(&state, now) == WORKERS {
                    return Err(PeerIdentityError::Busy);
                }
                if state.queue.len() < QUEUE {
                    state.queue.push_back(job);
                    ready.notify_one();
                    break;
                }
            }
            if admission == Admission::Immediate {
                return Err(PeerIdentityError::Busy);
            }
            #[cfg(all(test, target_os = "macos"))]
            self.waiting_for_capacity.notify_one();
            tokio::time::timeout_at(deadline.into(), changed)
                .await
                .map_err(|_| PeerIdentityError::Deadline)?;
        }
        let result = tokio::time::timeout_at(deadline.into(), rx).await;
        if Instant::now() >= deadline {
            return Err(PeerIdentityError::Deadline);
        }
        result
            .map_err(|_| PeerIdentityError::Deadline)?
            .map_err(|_| PeerIdentityError::CheckFailed)
    }

    #[cfg(test)]
    pub(crate) fn stuck_slots(&self) -> usize {
        let state = self.shared.0.lock().unwrap_or_else(|p| p.into_inner());
        stuck(&state, Instant::now())
    }

    fn close(&self) {
        let (state, ready, capacity) = &*self.shared;
        let mut state = state.lock().unwrap_or_else(|p| p.into_inner());
        state.closed = true;
        state.queue.clear();
        ready.notify_all();
        capacity.notify_waiters();
    }
}

impl Drop for PeerIdentityLane {
    fn drop(&mut self) {
        // Do not join threads: a native call may never come back.
        self.close();
    }
}

fn stuck(state: &State, now: Instant) -> usize {
    state
        .active
        .iter()
        .flatten()
        .filter(|&&end| end <= now)
        .count()
}

fn worker((state, ready, capacity): &Shared, index: usize) {
    loop {
        let (job, expired) = {
            let mut state = state.lock().unwrap_or_else(|p| p.into_inner());
            state.active[index] = None;
            while state.queue.is_empty() && !state.closed {
                state = ready.wait(state).unwrap_or_else(|p| p.into_inner());
            }
            let Some(job) = state.queue.pop_front() else {
                return;
            };
            let expired = Instant::now() >= job.deadline;
            if !expired {
                state.active[index] = Some(job.deadline);
            }
            capacity.notify_waiters();
            (job, expired)
        };
        #[cfg(test)]
        if let Some(after_pop) = job.after_pop {
            after_pop();
        }
        if expired {
            continue;
        }
        // A failed check drops its reply, but must not take capacity out of
        // the lane permanently. The next iteration clears its active slot.
        let _ = catch_unwind(AssertUnwindSafe(job.work));
    }
}

#[cfg(test)]
#[path = "operator_apps/lane_tests.rs"]
mod tests;