rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Single-instance lock and the info file that names the running daemon.
//!
//! The daemon holds an exclusive file lock on [`DaemonPaths::lock`] for its
//! whole lifetime; the kernel releases it when the process exits, however it
//! exits. Holding the lock therefore proves no other daemon is alive, which
//! is what makes removing a leftover socket safe.
//!
//! The lock and the info file live in the rho home's state directory, not the
//! runtime directory, so they guard the home's daemon state whichever runtime
//! directory a daemon resolved. A home's runtime directory is its own (see
//! [`DaemonPaths::resolve`]), so the lock also covers the socket.

use std::{
    fs::{self, File},
    io::{self, Write},
    path::{Path, PathBuf},
    time::{Duration, Instant},
};

use fs2::FileExt;
use rho_protocol::ProtocolVersion;
use serde::{Deserialize, Serialize};

use super::{
    login_session::LoginSession,
    paths::DaemonPaths,
    platform::{self, DaemonPathError},
};

/// Proof that this process is the only daemon for its rho home.
/// Dropping it releases the lock, at once (see its `Drop`).
#[derive(Debug)]
pub(crate) struct DaemonLock {
    file: File,
}

/// The contents of [`DaemonPaths::info_file`]: who holds the lock.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct DaemonRecord {
    pub(crate) pid: u32,
    /// The daemon's rho version.
    pub(crate) version: String,
    pub(crate) protocol: ProtocolVersion,
    /// Unix time, in seconds, when the daemon started.
    pub(crate) started_at: u64,
    pub(crate) socket: PathBuf,
    /// The login session the daemon runs in, where the platform has more
    /// than one kind (macOS). `rho doctor` and `rho daemon restart` read it
    /// ([`super::restart_moves_into_gui`]); no request carries it.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "known_session"
    )]
    pub(crate) session: Option<LoginSession>,
}

/// A session this rho does not know, as a later one might record, reads as
/// none: an unreadable record would hide the running daemon altogether.
fn known_session<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<LoginSession>, D::Error> {
    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
    Ok(value.and_then(|value| serde_json::from_value(value).ok()))
}

#[derive(Debug, thiserror::Error)]
pub(crate) enum LockError {
    /// Another daemon holds the lock. `record` is `None` while that daemon is
    /// between taking the lock and writing its info file.
    #[error("{}", already_running_message(.record.as_ref()))]
    AlreadyRunning { record: Option<DaemonRecord> },
    #[error("could not open rho daemon lock {path}: {source}")]
    Io { path: PathBuf, source: io::Error },
    #[error(transparent)]
    StateDir(#[from] DaemonPathError),
}

fn already_running_message(record: Option<&DaemonRecord>) -> String {
    match record {
        Some(DaemonRecord {
            pid,
            version,
            socket,
            ..
        }) => format!(
            "rho daemon is already running (pid {pid}, version {version}, socket {})",
            socket.display()
        ),
        None => "rho daemon is already running (it is still starting)".to_owned(),
    }
}

/// Takes the daemon lock, after creating or verifying the private state
/// directory that holds it. A lock still held after [`FORK_HOLD_WAIT`] is
/// another daemon's.
///
/// The lock is contended for a moment by what is not a daemon: another
/// process's [`is_held`] probe, as a client's that polls for a daemon
/// to let go, takes it shared while it looks; and a lock belongs to an
/// open file description, which a fork shares until the child execs, so
/// a process's fork may hold a lock it closed without unlocking. Only
/// taking the lock waits those out, since its caller takes
/// `AlreadyRunning` as final; [`is_held`] reports the lock as it finds it,
/// and the callers that wait for it to free poll again.
pub(crate) fn acquire(paths: &DaemonPaths) -> Result<DaemonLock, LockError> {
    paths.prepare_state_dir()?;
    let file = open_lock_file(&paths.lock)?;
    match past_forks(|| FileExt::try_lock_exclusive(&file)) {
        Ok(()) => Ok(DaemonLock { file }),
        Err(error) if is_contended(&error) => Err(LockError::AlreadyRunning {
            record: read_record(paths),
        }),
        Err(source) => Err(LockError::Io {
            path: paths.lock.clone(),
            source,
        }),
    }
}

/// Tries `lock` again while it is contended, until [`FORK_HOLD_WAIT`]
/// passed, then returns how it went (see [`acquire`]).
fn past_forks(mut lock: impl FnMut() -> io::Result<()>) -> io::Result<()> {
    let started = Instant::now();
    loop {
        match lock() {
            Err(error) if is_contended(&error) && started.elapsed() < FORK_HOLD_WAIT => {
                std::thread::sleep(FORK_HOLD_POLL);
            }
            tried => return tried,
        }
    }
}

/// How long taking the lock waits out a contention that is no daemon's.
/// Measured for a fork's hold: with 8 threads starting processes (`true`,
/// by `posix_spawn`) back to back, a lock closed without unlocking stayed
/// held 0.2 ms at the median and 0.43 ms at most over 15,000 releases (24
/// cores). A fork of a large process, or one with a `pre_exec` hook, takes
/// longer, and an `is_held` probe holds it for an open and a lock attempt;
/// so a tripwire, about 100 times the measured hold. Only a lock another
/// daemon really holds pays it, its refusal coming that much later; a
/// daemon takes the lock once, as it starts, before it serves.
const FORK_HOLD_WAIT: Duration = Duration::from_millis(50);

/// Interval between [`past_forks`]'s tries.
const FORK_HOLD_POLL: Duration = Duration::from_millis(1);

impl DaemonLock {
    /// Takes over the lock the daemon this process restarted from handed
    /// it as `file`, its open lock file (see [`platform::take_handoff`]).
    pub(super) fn adopt(file: File) -> io::Result<Self> {
        // Where the handoff kept the lock, it belongs to the open file
        // description, so locking it again succeeds at once. Where it
        // released the lock, this takes it as a new daemon does. Either
        // way it would block only if another daemon had taken the lock
        // meanwhile; a probe's, or a fork's, it waits out (see `acquire`).
        past_forks(|| FileExt::try_lock_exclusive(&file))?;
        Ok(Self { file })
    }
}

/// Unlocks before the file closes: a fork shares the lock's open file
/// description until its child execs, so closing alone would leave the lock
/// held by any child a thread was starting meanwhile. Unlocking releases it
/// for every handle of that description. A restart in place never drops
/// it: the binary it runs inherits the lock.
impl Drop for DaemonLock {
    fn drop(&mut self) {
        let _ = FileExt::unlock(&self.file);
    }
}

/// The open lock file, which a restart in place hands to the binary it runs.
impl AsRef<File> for DaemonLock {
    fn as_ref(&self) -> &File {
        &self.file
    }
}

/// Whether taking a lock failed because another handle holds it. `fs2`
/// reports that as `WouldBlock` on Unix and as the raw lock-violation error
/// on Windows.
fn is_contended(error: &io::Error) -> bool {
    error.kind() == io::ErrorKind::WouldBlock
        || error.raw_os_error() == fs2::lock_contended_error().raw_os_error()
}

/// Whether a daemon currently holds the lock. Probes with a shared lock, so
/// it never blocks a daemon that is starting for longer than the probe.
pub(crate) fn is_held(paths: &DaemonPaths) -> Result<bool, LockError> {
    let file = match open_lock_file(&paths.lock) {
        Ok(file) => file,
        Err(LockError::Io { source, .. }) if source.kind() == io::ErrorKind::NotFound => {
            return Ok(false)
        }
        Err(error) => return Err(error),
    };
    match FileExt::try_lock_shared(&file) {
        Ok(()) => {
            // Unlocked before the file closes, as a daemon's lock is (see
            // `DaemonLock`'s `Drop`), so no fork keeps the probe's lock.
            let _ = FileExt::unlock(&file);
            Ok(false)
        }
        Err(error) if is_contended(&error) => Ok(true),
        Err(source) => Err(LockError::Io {
            path: paths.lock.clone(),
            source,
        }),
    }
}

/// Polls until no daemon holds the lock. Returns the time waited, or `None`
/// if the lock was still held at `timeout`.
pub(crate) async fn wait_until_released(
    paths: &DaemonPaths,
    timeout: Duration,
) -> Result<Option<Duration>, LockError> {
    let started = Instant::now();
    loop {
        if !is_held(paths)? {
            return Ok(Some(started.elapsed()));
        }
        if started.elapsed() >= timeout {
            return Ok(None);
        }
        tokio::time::sleep(LOCK_POLL_INTERVAL).await;
    }
}

/// Interval between lock probes while waiting for a daemon to exit. Each probe
/// is an open and a lock attempt on a local file; shutdown removes two files.
const LOCK_POLL_INTERVAL: Duration = Duration::from_millis(10);

/// Writes the info file atomically, private to this user, so readers never
/// see a partial one.
pub(crate) fn write_record(paths: &DaemonPaths, record: &DaemonRecord) -> io::Result<()> {
    // `tempfile` creates the file private to this user.
    let mut file = tempfile::NamedTempFile::new_in(&paths.state_dir)?;
    serde_json::to_writer(&mut file, record)?;
    file.write_all(b"\n")?;
    file.persist(&paths.info_file)
        .map_err(|error| error.error)?;
    Ok(())
}

/// The info file, if it exists and parses.
pub(crate) fn read_record(paths: &DaemonPaths) -> Option<DaemonRecord> {
    let contents = fs::read(&paths.info_file).ok()?;
    serde_json::from_slice(&contents).ok()
}

/// Who holds the daemon lock now.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum LockHolder {
    /// No daemon runs.
    Nobody,
    /// A daemon with no record: one still starting, before it wrote it,
    /// or one stopping, which removes it while its turns save.
    Unrecorded,
    Daemon(DaemonRecord),
}

impl LockHolder {
    /// The running daemon's record, once it wrote one.
    pub(crate) fn record(self) -> Option<DaemonRecord> {
        match self {
            Self::Daemon(record) => Some(record),
            Self::Nobody | Self::Unrecorded => None,
        }
    }
}

/// Who holds the daemon lock now. The record is read only while the lock is
/// held: a record alone may be a crashed daemon's, whose pid may have been
/// reused. A lock that cannot be probed counts as held by nobody.
pub(crate) fn holder(paths: &DaemonPaths) -> LockHolder {
    if !is_held(paths).unwrap_or(false) {
        return LockHolder::Nobody;
    }
    read_record(paths).map_or(LockHolder::Unrecorded, LockHolder::Daemon)
}

/// Asks the recorded daemon to stop outside the protocol, for a daemon that
/// cannot take a `rho/daemon/stop` request because it speaks an incompatible
/// protocol. That triggers the same graceful shutdown. Returns the pid
/// asked, or `None` when no daemon holds the lock.
pub(crate) fn terminate_recorded_daemon(paths: &DaemonPaths) -> anyhow::Result<Option<u32>> {
    // Only ask while the lock is held: the record then names a live
    // daemon rather than a crashed one whose pid may have been reused.
    if !is_held(paths)? {
        return Ok(None);
    }
    let record = read_record(paths)
        .ok_or_else(|| anyhow::anyhow!("rho daemon is still starting; retry in a moment"))?;
    platform::request_stop(paths, record.pid)?;
    Ok(Some(record.pid))
}

fn open_lock_file(path: &Path) -> Result<File, LockError> {
    platform::open_lock_file(path).map_err(|source| LockError::Io {
        path: path.to_path_buf(),
        source,
    })
}

#[cfg(test)]
#[path = "lock_tests.rs"]
mod tests;