rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The service file `rho daemon bridge setup` writes to keep
//! `rho daemon serve --http` running across logouts and reboots: a systemd
//! user unit on Linux, a launchd agent on macOS, as `docs/daemon.md` shows
//! them. Pure: `daemon::ServiceFiles` installs it.

use std::{
    fmt::Write as _,
    net::SocketAddr,
    path::{Path, PathBuf},
};

use anyhow::Context as _;
use rho_protocol::BridgeUrl;
use serde::{Deserialize, Serialize};

use crate::daemon::{xml_escape, ServiceFiles, ServiceManager};

/// What every file setup writes says first, so setup and remove tell it
/// from a service saved by hand, which they leave alone.
const WRITTEN_BY_SETUP: &str =
    "Written by `rho daemon bridge setup`, which rewrites it; `rho daemon bridge remove` removes it.";

/// What is saved under the bridge's service name.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Installed {
    Absent,
    /// A file setup did not write, which setup, pair and remove leave alone.
    ByHand,
    /// The file setup wrote, as saved.
    BySetup(String),
}

impl Installed {
    /// What is saved at `service`'s definition. A file that cannot be read
    /// is an error, not an absent one.
    pub(super) fn of(service: &ServiceFiles) -> anyhow::Result<Self> {
        match std::fs::read_to_string(&service.definition) {
            Ok(text) if text.contains(WRITTEN_BY_SETUP) => Ok(Self::BySetup(text)),
            Ok(_) => Ok(Self::ByHand),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::Absent),
            Err(error) => Err(error)
                .with_context(|| format!("could not read {}", service.definition.display())),
        }
    }

    /// Where `rho daemon bridge pair` pairs with the bridge: refused, as an
    /// [`Unpairable`], unless setup installed it and recorded where.
    pub(super) fn pair_with(&self) -> anyhow::Result<PairWith> {
        match self {
            Self::Absent => Err(Unpairable::NotInstalled.into()),
            Self::ByHand => Err(Unpairable::ByHand.into()),
            Self::BySetup(text) => Ok(PairWith::read(text)?.ok_or(Unpairable::Unrecorded)?),
        }
    }
}

/// Why `rho daemon bridge pair` cannot pair with what is installed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub(super) enum Unpairable {
    #[error("no bridge is installed; set one up with `rho daemon bridge setup`")]
    NotInstalled,
    #[error(
        "the bridge's service was saved by hand, so pair cannot tell where clients reach it; pair by hand with `rho daemon token rotate <name>`"
    )]
    ByHand,
    #[error(
        "the bridge was set up by an earlier rho, which did not record where clients reach it; run `rho daemon bridge setup` again"
    )]
    Unrecorded,
}

/// Where a client pairs with the bridge setup installed, and where the
/// bridge listens, so `rho daemon bridge pair` can check it accepts a new
/// token. Setup records it in the service file, which pair reads it from.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct PairWith {
    pub(super) url: BridgeUrl,
    pub(super) listen: SocketAddr,
}

/// What starts the comment that holds a [`PairWith`].
const PAIR_WITH: &str = "rho-bridge-pair ";

/// A [`PairWith`] as its comment holds it.
#[derive(Serialize, Deserialize)]
struct PairWithRecord {
    url: String,
    listen: SocketAddr,
}

impl PairWith {
    /// The comment's text: JSON with every `-` escaped, so an XML comment,
    /// which may not hold `--`, can carry any address.
    fn record(&self) -> String {
        let record = PairWithRecord {
            url: self.url.to_string(),
            listen: self.listen,
        };
        let json = serde_json::to_string(&record).expect("strings and an address encode");
        // Only strings hold a `-`: the record has no numbers.
        format!("{PAIR_WITH}{}", json.replace('-', "\\u002d"))
    }

    /// What setup recorded in `text`, a service file it wrote; `None` for
    /// one written before setup recorded it.
    pub(super) fn read(text: &str) -> anyhow::Result<Option<Self>> {
        let Some(json) = text.lines().find_map(|line| {
            let line = line.trim();
            let comment = line
                .strip_prefix('#')
                .or_else(|| line.strip_prefix("<!--")?.strip_suffix("-->"))?;
            comment.trim().strip_prefix(PAIR_WITH)
        }) else {
            return Ok(None);
        };
        let record: PairWithRecord = serde_json::from_str(json)
            .context("the bridge's service file has a damaged pairing record")?;
        Ok(Some(Self {
            url: record
                .url
                .parse()
                .context("the bridge's service file has a damaged pairing record")?,
            listen: record.listen,
        }))
    }
}

/// What the service runs: the `rho` program, its arguments, and the
/// variables it runs with, and where clients pair with it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct ServiceSpec {
    pub(super) program: PathBuf,
    pub(super) args: Vec<String>,
    pub(super) environment: Vec<(String, String)>,
    pub(super) pair_with: PairWith,
}

/// The text of `service`'s definition file, which runs `spec`.
pub(super) fn render(
    service: &ServiceFiles,
    spec: &ServiceSpec,
    home: &Path,
) -> anyhow::Result<String> {
    match service.manager {
        ServiceManager::Systemd => systemd_unit(spec),
        ServiceManager::Launchd => launchd_plist(service.unit, spec, &launchd_log(home)),
    }
}

/// Where `service` logs, for a person to read.
pub(super) fn log_location(service: &ServiceFiles, home: &Path) -> String {
    match service.manager {
        ServiceManager::Systemd => format!("`journalctl --user -u {}`", service.unit),
        ServiceManager::Launchd => launchd_log(home).display().to_string(),
    }
}

/// The command that starts the installed bridge as it is, unlike setup,
/// which also rotates its token.
pub(super) fn start_command(service: &ServiceFiles) -> String {
    match service.manager {
        ServiceManager::Systemd => format!("`systemctl --user start {}`", service.unit),
        ServiceManager::Launchd => format!("`launchctl kickstart gui/$UID/{}`", service.unit),
    }
}

fn launchd_log(home: &Path) -> PathBuf {
    home.join("Library/Logs/rho-daemon-http.log")
}

/// A systemd user unit, as `docs/daemon.md` shows it, with every value
/// quoted so systemd reads it back as written.
fn systemd_unit(spec: &ServiceSpec) -> anyhow::Result<String> {
    let program = utf8(&spec.program)?;
    // systemd refuses these in the executable's path, escaped or not, and
    // expands no variables there (checked against systemd 249).
    if program.contains(['"', '\'', '\\']) {
        anyhow::bail!(
            "systemd cannot run {program}: its path holds a quote or a backslash; install rho elsewhere"
        );
    }
    let exec: Vec<String> = std::iter::once(program.replace('%', "%%"))
        .chain(
            spec.args
                .iter()
                .map(|arg| systemd_escape(arg, /*expands_variables*/ true)),
        )
        .map(|arg| format!("\"{arg}\""))
        .collect();
    let mut unit = format!(
        "# {WRITTEN_BY_SETUP}\n\
         # {}\n\
         [Unit]\n\
         Description=rho daemon HTTP WebSocket bridge\n\
         After=network.target\n\
         \n\
         [Service]\n",
        spec.pair_with.record()
    );
    let _ = writeln!(unit, "ExecStart={}", exec.join(" "));
    for (name, value) in &spec.environment {
        let assignment =
            systemd_escape(&format!("{name}={value}"), /*expands_variables*/ false);
        let _ = writeln!(unit, "Environment=\"{assignment}\"");
    }
    // `RestartSec`: an overlay's address can come up after `network.target`,
    // and systemd's default 100 ms reaches the start limit within a second
    // (`docs/daemon.md`, Running as a service).
    unit.push_str(
        "# Stop only the bridge. The daemon keeps running its turns.\n\
         KillMode=process\n\
         Restart=always\n\
         RestartSec=10\n\
         \n\
         [Install]\n\
         WantedBy=default.target\n",
    );
    Ok(unit)
}

/// Escapes `value` for a double-quoted systemd setting: backslashes and
/// quotes, `%` specifiers, and, where the setting expands them, `$`
/// variables.
fn systemd_escape(value: &str, expands_variables: bool) -> String {
    let mut escaped = String::with_capacity(value.len());
    for c in value.chars() {
        match c {
            '\\' => escaped.push_str("\\\\"),
            '"' => escaped.push_str("\\\""),
            '%' => escaped.push_str("%%"),
            '$' if expands_variables => escaped.push_str("$$"),
            '\n' => escaped.push_str("\\n"),
            c => escaped.push(c),
        }
    }
    escaped
}

/// The launchd agent `label`, as `docs/daemon.md` shows it, logging to `log`.
fn launchd_plist(label: &str, spec: &ServiceSpec, log: &Path) -> anyhow::Result<String> {
    let mut plist = format!(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
         <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
         <!-- {WRITTEN_BY_SETUP} -->\n\
         <!-- {} -->\n\
         <plist version=\"1.0\">\n\
         <dict>\n",
        spec.pair_with.record()
    );
    let _ = writeln!(plist, "  <key>Label</key>\n  <string>{label}</string>");
    plist.push_str("  <key>ProgramArguments</key>\n  <array>\n");
    for arg in std::iter::once(utf8(&spec.program)?).chain(spec.args.iter().map(String::as_str)) {
        let _ = writeln!(plist, "    <string>{}</string>", xml_escape(arg));
    }
    plist.push_str("  </array>\n  <key>EnvironmentVariables</key>\n  <dict>\n");
    for (name, value) in &spec.environment {
        let _ = writeln!(
            plist,
            "    <key>{}</key>\n    <string>{}</string>",
            xml_escape(name),
            xml_escape(value)
        );
    }
    plist.push_str(
        "  </dict>\n\
         \x20 <!-- Stop only the bridge. The daemon keeps running its turns. -->\n\
         \x20 <key>AbandonProcessGroup</key>\n  <true/>\n\
         \x20 <key>RunAtLoad</key>\n  <true/>\n\
         \x20 <key>KeepAlive</key>\n  <true/>\n",
    );
    let _ = writeln!(
        plist,
        "  <key>StandardErrorPath</key>\n  <string>{}</string>\n</dict>\n</plist>",
        xml_escape(utf8(log)?)
    );
    Ok(plist)
}

fn utf8(path: &Path) -> anyhow::Result<&str> {
    path.to_str().with_context(|| {
        format!(
            "{} is not UTF-8, which a service file cannot hold",
            path.display()
        )
    })
}

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