rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Asking the service manager that runs a saved `rho mcp serve --http` or
//! `rho daemon serve --http` service to start or stop it: systemd's user
//! manager, or launchd on macOS; and running a request to a service
//! manager, which `user_scope` shares.

use std::{
    io,
    path::Path,
    process::{Command, Stdio},
    time::{Duration, Instant},
};

use crate::daemon::service::ServiceManager;

/// How long a stop waits for launchd to finish tearing down an agent that
/// `launchctl bootout` already returned for.
//
// Tripwire, not measured (no macOS here): a teardown takes as long as the
// agent's exit, which for the bridge is its drain of open WebSockets.
const BOOTOUT_TIMEOUT: Duration = Duration::from_secs(10);

const BOOTOUT_POLL_INTERVAL: Duration = Duration::from_millis(100);

/// Stops the saved service `unit` and keeps its manager from starting it
/// again. Returns once the manager has let go of it, so its port is free
/// and it can be loaded again. The error carries what the manager printed,
/// as when no user manager answers in this login or the service was never
/// loaded.
pub(in crate::daemon) fn stop_service(manager: ServiceManager, unit: &str) -> io::Result<()> {
    match manager {
        ServiceManager::Systemd => {
            // `disable --now` waits for the stop job.
            run_manager_command("systemctl", &["--user", "disable", "--now", unit])
        }
        ServiceManager::Launchd => {
            let target = format!("{}/{unit}", launchd_domain());
            bootout(&target, &|args| run_manager_command("launchctl", args))
        }
    }
}

/// Has launchd stop and unload the agent `target` (`<domain>/<label>`),
/// asking it through `launchctl`, which runs one `launchctl` command.
/// Returns once launchd has let go of it.
pub(super) fn bootout(
    target: &str,
    launchctl: &dyn Fn(&[&str]) -> io::Result<()>,
) -> io::Result<()> {
    launchctl(&["bootout", target])?;
    // `bootout` returns before launchd has torn the agent down; until then
    // its port is taken and `bootstrap` fails ("5: Input/output error").
    // `print` fails once the agent is gone.
    wait_until_gone(
        || launchctl(&["print", target]).is_err(),
        BOOTOUT_TIMEOUT,
        BOOTOUT_POLL_INTERVAL,
    )
    .map_err(|waited| {
        io::Error::new(
            io::ErrorKind::TimedOut,
            format!(
                "launchd still had {target} after BOOTOUT_TIMEOUT ({BOOTOUT_TIMEOUT:?}; waited {waited:?})"
            ),
        )
    })
}

/// Polls `gone` every `interval` until it holds, or fails with how long it
/// waited once `timeout` has passed.
fn wait_until_gone(
    mut gone: impl FnMut() -> bool,
    timeout: Duration,
    interval: Duration,
) -> Result<(), Duration> {
    let started = Instant::now();
    loop {
        if gone() {
            return Ok(());
        }
        let waited = started.elapsed();
        if waited >= timeout {
            return Err(waited);
        }
        std::thread::sleep(interval);
    }
}

/// Has the manager read its definitions again, after one was written or
/// deleted, so it neither runs a stale copy nor lists a deleted one as
/// `not-found`.
pub(in crate::daemon) fn reload_services(manager: ServiceManager) -> io::Result<()> {
    match manager {
        ServiceManager::Systemd => run_manager_command("systemctl", &["--user", "daemon-reload"]),
        // launchd reads an agent's file as `start_service` loads it.
        ServiceManager::Launchd => Ok(()),
    }
}

/// Starts the saved service `unit`, defined in `definition`, now and at
/// every login, unless it runs already.
pub(in crate::daemon) fn start_service(
    manager: ServiceManager,
    unit: &str,
    definition: &Path,
) -> io::Result<()> {
    match manager {
        ServiceManager::Systemd => {
            run_manager_command("systemctl", &["--user", "enable", "--now", unit])
        }
        ServiceManager::Launchd => {
            let target = format!("{}/{unit}", launchd_domain());
            // `print` succeeds only for a loaded agent; `kickstart` without
            // `-k` leaves a running one alone.
            if run_manager_command("launchctl", &["print", &target]).is_ok() {
                return run_manager_command("launchctl", &["kickstart", &target]);
            }
            let definition = definition.to_str().ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "a launchd agent path is not UTF-8",
                )
            })?;
            run_manager_command("launchctl", &["bootstrap", &launchd_domain(), definition])
        }
    }
}

/// Has systemd keep this user's services running while they are logged
/// out, and start them at boot (linger): `Ok(true)` when it already did,
/// `Ok(false)` when this call turned it on.
pub(crate) fn keep_user_services_running() -> io::Result<bool> {
    // SAFETY: getuid has no arguments or memory-safety preconditions.
    let uid = unsafe { libc::getuid() }.to_string();
    let output = Command::new("loginctl")
        .args(["show-user", &uid, "--property=Linger", "--value"])
        .stdin(Stdio::null())
        .output()?;
    if output.status.success() && String::from_utf8_lossy(&output.stdout).trim() == "yes" {
        return Ok(true);
    }
    // Without a password prompt: polkit lets a user turn it on for
    // themselves on most distributions, and refuses at once otherwise.
    run_manager_command("loginctl", &["--no-ask-password", "enable-linger"])?;
    Ok(false)
}

/// The launchd domain of this user's agents, their GUI login's.
pub(super) fn launchd_domain() -> String {
    // SAFETY: geteuid has no arguments or memory-safety preconditions.
    format!("gui/{}", unsafe { libc::geteuid() })
}

/// Runs `program` with `args`, a request to a service manager. The error
/// names the command and carries what it printed.
pub(super) fn run_manager_command(program: &str, args: &[&str]) -> io::Result<()> {
    let ran = format!("{program} {}", args.join(" "));
    let output = Command::new(program)
        .args(args)
        .stdin(Stdio::null())
        .output()
        .map_err(|error| io::Error::new(error.kind(), format!("could not run `{ran}`: {error}")))?;
    if output.status.success() {
        return Ok(());
    }
    Err(io::Error::other(format!(
        "`{ran}` failed with {}: {}",
        output.status,
        String::from_utf8_lossy(&output.stderr).trim()
    )))
}

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