use rkyv::{Archive, Deserialize, Serialize};
use std::sync::OnceLock;
#[derive(Archive, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
pub struct Presence {
pub host: u64,
pub pid: u32,
pub process: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Relation {
SameProcess,
SameHost { pid: u32 },
Remote,
}
pub const PRESENCE_BYTES: usize = 20;
impl Presence {
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,
})
}
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
}
}
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
}
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(),
}
}
}
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)
})
}
pub struct Liveness {
relation: Relation,
timeout: std::time::Duration,
exited: tokio_util::sync::CancellationToken,
watch: Option<tokio::task::JoinHandle<()>>,
}
impl Liveness {
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
}
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),
}
}
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();
}
}
}
pub async fn exited(pid: u32) {
#[cfg(target_os = "linux")]
{
use std::os::fd::{FromRawFd, OwnedFd};
let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid as libc::pid_t, 0) };
if fd >= 0 {
let fd = unsafe { OwnedFd::from_raw_fd(fd as i32) };
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;
}
async fn poll_exited(pid: u32) {
#[cfg(unix)]
loop {
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();
}
}