mt_sea 0.17.1

Primitives for a Minot network.
Documentation
//! Where a node runs, and how its liveness is known.
//!
//! A node that runs elsewhere is alive only as far as its heartbeats tell.
//! Silence there is all there is, so a timeout decides. On the same machine the
//! kernel knows for certain whether a process exists, so a paused or busy node
//! is never mistaken for a dead one. Within one process a part that fails
//! closes its channels, and nothing needs watching at all.
//!
//! Nodes exchange their [`Presence`] when they meet and pick the [`Relation`]
//! that decides how they watch each other.

use rkyv::{Archive, Deserialize, Serialize};
use std::sync::OnceLock;

/// Where a node runs.
#[derive(Archive, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
pub struct Presence {
    /// The machine and PID namespace, zero where it is unknown. Containers on
    /// one machine share its boot but number their processes apart, so a PID
    /// means the same process only within one namespace.
    pub host: u64,
    /// The process ID within that namespace.
    pub pid: u32,
    /// Random per process, which tells two processes apart that share a PID
    /// on different machines.
    pub process: u64,
}

/// How two nodes are placed relative to each other.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Relation {
    /// One process. Nothing to watch.
    SameProcess,
    /// One machine and PID namespace. The kernel tells when the process exits.
    SameHost { pid: u32 },
    /// Only heartbeats tell.
    Remote,
}

/// Size of [`Presence::to_bytes`].
pub const PRESENCE_BYTES: usize = 20;

impl Presence {
    /// The presence of this process.
    pub fn current() -> Self {
        static CURRENT: OnceLock<Presence> = OnceLock::new();
        *CURRENT.get_or_init(|| Self {
            host: host_identity(),
            pid: std::process::id(),
            process: rand::random::<u64>() | 1,
        })
    }

    /// How a node at `other` is placed relative to this one.
    pub fn relation(&self, other: &Presence) -> Relation {
        if self.process == other.process {
            Relation::SameProcess
        } else if self.host != 0 && self.host == other.host {
            Relation::SameHost { pid: other.pid }
        } else {
            Relation::Remote
        }
    }

    /// How a node at `other` is placed relative to this process. A peer that
    /// did not say where it runs is remote.
    pub fn relation_to(other: Option<&Presence>) -> Relation {
        other.map_or(Relation::Remote, |other| Self::current().relation(other))
    }

    pub fn to_bytes(&self) -> [u8; PRESENCE_BYTES] {
        let mut bytes = [0u8; PRESENCE_BYTES];
        bytes[..8].copy_from_slice(&self.host.to_le_bytes());
        bytes[8..12].copy_from_slice(&self.pid.to_le_bytes());
        bytes[12..].copy_from_slice(&self.process.to_le_bytes());
        bytes
    }

    /// The presence in `bytes`, `None` for anything else, such as the single
    /// byte that a heartbeat reply of an older node carries.
    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
        let bytes: &[u8; PRESENCE_BYTES] = bytes.try_into().ok()?;
        Some(Self {
            host: u64::from_le_bytes(bytes[..8].try_into().unwrap()),
            pid: u32::from_le_bytes(bytes[8..12].try_into().unwrap()),
            process: u64::from_le_bytes(bytes[12..].try_into().unwrap()),
        })
    }
}

impl From<&ArchivedPresence> for Presence {
    fn from(archived: &ArchivedPresence) -> Self {
        Self {
            host: archived.host.to_native(),
            pid: archived.pid.to_native(),
            process: archived.process.to_native(),
        }
    }
}

/// The machine's boot and the PID namespace of this process, hashed. Zero
/// where either is unknown, which makes every other process remote.
fn host_identity() -> u64 {
    #[cfg(target_os = "linux")]
    {
        let boot = std::fs::read_to_string("/proc/sys/kernel/random/boot_id");
        let namespace = std::fs::read_link("/proc/self/ns/pid");
        if let (Ok(boot), Ok(namespace)) = (boot, namespace) {
            let identity = format!("{}|{}", boot.trim(), namespace.display());
            return fnv1a(identity.as_bytes()).max(1);
        }
    }
    0
}

#[cfg(target_os = "linux")]
fn fnv1a(bytes: &[u8]) -> u64 {
    bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
        (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3)
    })
}

/// Tells whether a peer is gone, by the means its [`Relation`] allows.
pub struct Liveness {
    relation: Relation,
    /// How long a remote peer stays silent before it counts as gone.
    timeout: std::time::Duration,
    /// Cancelled when the process of a peer on this machine exits.
    exited: tokio_util::sync::CancellationToken,
    watch: Option<tokio::task::JoinHandle<()>>,
}

impl Liveness {
    /// Must be called within a Tokio runtime for a `SameHost` relation.
    pub fn new(relation: Relation, timeout: std::time::Duration) -> Self {
        let exited = tokio_util::sync::CancellationToken::new();
        let watch = match relation {
            Relation::SameHost { pid } => {
                let exited = exited.clone();
                Some(tokio::spawn(async move {
                    self::exited(pid).await;
                    exited.cancel();
                }))
            }
            Relation::SameProcess | Relation::Remote => None,
        };
        Self {
            relation,
            timeout,
            exited,
            watch,
        }
    }

    pub fn relation(&self) -> Relation {
        self.relation
    }

    /// Wait for the peer's next `message`. `None` means the peer is gone:
    /// silent for the timeout when it is remote, its process exited when it
    /// runs on this machine. A peer in this process is never gone this way,
    /// its closed channel tells instead. A message that is ready wins over the
    /// deadline, as after a stalled executor that wakes both at once.
    pub async fn next<F: std::future::Future>(&self, message: F) -> Option<F::Output> {
        match self.relation {
            Relation::Remote => tokio::select! {
                biased;
                output = message => Some(output),
                _ = tokio::time::sleep(self.timeout) => None,
            },
            Relation::SameHost { .. } => tokio::select! {
                biased;
                output = message => Some(output),
                _ = self.exited.cancelled() => None,
            },
            Relation::SameProcess => Some(message.await),
        }
    }

    /// Resolves once the peer is known to be gone without any message
    /// arriving: when the process of a peer on this machine exits. Never for
    /// the other relations, whose silence only [`Liveness::next`] can judge.
    pub async fn exited(&self) {
        match self.relation {
            Relation::SameHost { .. } => self.exited.cancelled().await,
            Relation::SameProcess | Relation::Remote => std::future::pending().await,
        }
    }
}

impl Drop for Liveness {
    fn drop(&mut self) {
        if let Some(watch) = self.watch.take() {
            watch.abort();
        }
    }
}

/// Resolves once the process `pid` of this machine has exited.
///
/// The kernel reports it, so a process that is paused, swapped out or busy
/// is still there. Only `SameHost` relations call this.
pub async fn exited(pid: u32) {
    #[cfg(target_os = "linux")]
    {
        use std::os::fd::{FromRawFd, OwnedFd};
        // SAFETY: pidfd_open takes a PID and flags and returns a new file
        // descriptor or -1.
        let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid as libc::pid_t, 0) };
        if fd >= 0 {
            // SAFETY: the descriptor was just opened and is owned here.
            let fd = unsafe { OwnedFd::from_raw_fd(fd as i32) };
            // A pidfd becomes readable when the process exits.
            match tokio::io::unix::AsyncFd::with_interest(fd, tokio::io::Interest::READABLE) {
                Ok(fd) => {
                    let _ = fd.readable().await;
                    return;
                }
                Err(error) => log::debug!("Cannot watch process {pid} by pidfd: {error}"),
            }
        } else if std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) {
            return;
        }
    }
    poll_exited(pid).await;
}

/// Asks the kernel whether `pid` still exists, for systems without pidfd.
async fn poll_exited(pid: u32) {
    #[cfg(unix)]
    loop {
        // SAFETY: signal 0 only checks that the process exists.
        let alive = unsafe { libc::kill(pid as libc::pid_t, 0) } == 0
            || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM);
        if !alive {
            return;
        }
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    }
    #[cfg(not(unix))]
    {
        let _ = pid;
        std::future::pending::<()>().await;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn a_queued_message_wins_a_simultaneously_expired_deadline() {
        let (tx, mut rx) = tokio::sync::broadcast::channel(1);
        tx.send("heartbeat").unwrap();
        let liveness = Liveness::new(Relation::Remote, std::time::Duration::ZERO);
        let received = liveness.next(rx.recv()).await;
        assert!(matches!(received, Some(Ok("heartbeat"))));
    }

    #[tokio::test]
    async fn only_a_remote_peer_is_gone_by_silence() {
        let silent = std::future::pending::<()>;
        let timeout = std::time::Duration::from_millis(50);
        let remote = Liveness::new(Relation::Remote, timeout);
        assert!(remote.next(silent()).await.is_none());
        let local = Liveness::new(Relation::SameProcess, timeout);
        assert!(
            tokio::time::timeout(timeout * 6, local.next(silent()))
                .await
                .is_err()
        );
        let host = Liveness::new(
            Relation::SameHost {
                pid: std::process::id(),
            },
            timeout,
        );
        assert!(
            tokio::time::timeout(timeout * 6, host.next(silent()))
                .await
                .is_err()
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_peer_on_this_machine_is_gone_when_its_process_exits() {
        let mut child = std::process::Command::new("sleep")
            .arg("0.3")
            .spawn()
            .unwrap();
        let liveness = Liveness::new(Relation::SameHost { pid: child.id() }, Default::default());
        let gone = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            liveness.next(std::future::pending::<()>()),
        )
        .await
        .unwrap();
        assert!(gone.is_none());
        child.wait().unwrap();
    }
}