zc2 0.0.48

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! `zc agent install | uninstall` on Linux (ADR ZC-0019 ยง8): a systemd
//! **user** unit, the counterpart of the macOS LaunchAgent (`launchd.rs`).
//! Rendering is a pure function tested everywhere; installing and
//! uninstalling take an injected `systemctl --user` runner, so the logic is
//! tested on every platform. `agent.json` and the API guards are identical to
//! macOS.

use std::io;
use std::path::{Path, PathBuf};
use std::process::ExitStatus;

/// Named like the LaunchAgent label (`ai.zakuro.agent`).
pub const UNIT: &str = "zakuro-agent.service";

/// A `systemctl --user <args>` invocation, injected so tests never shell out.
pub type Systemctl<'a> = &'a dyn Fn(&[&str]) -> io::Result<ExitStatus>;

/// `~/.config/systemd/user/zakuro-agent.service`, or under
/// `$XDG_CONFIG_HOME` when the caller passes it.
pub fn unit_path(home: &Path, xdg_config_home: Option<&str>) -> PathBuf {
    let base = match xdg_config_home.filter(|x| !x.is_empty() && x.starts_with('/')) {
        Some(x) => PathBuf::from(x),
        None => home.join(".config"),
    };
    base.join("systemd").join("user").join(UNIT)
}

/// Quote one value for a unit file: systemd expands `%` specifiers and
/// C-style escapes inside double quotes, so those are escaped. `ExecStart=`
/// also expands `$VAR` (`Environment=` does not), so `exec` escapes `$` too.
pub fn quote(v: &str, exec: bool) -> String {
    let mut escaped = v
        .replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('%', "%%");
    if exec {
        escaped = escaped.replace('$', "$$");
    }
    format!("\"{escaped}\"")
}

/// The unit: run `<zc> agent run`, restart it when it exits, give it 60 s to
/// stop its children (the LaunchAgent's `ExitTimeOut`), a PATH on which `uv`
/// resolves, the carried settings (`launchd::carried_env`), and a log file.
///
/// `KillMode=process`: systemd signals only the agent. The agent stops its
/// own children on SIGTERM, and after a crash it re-adopts the ones still
/// running (`children.json`) -- which `control-group` would have killed.
pub fn render_unit(zc_path: &str, home: &str, env: &[(&str, String)], log_path: &str) -> String {
    let path = format!("{home}/.local/bin:{home}/.cargo/bin:/usr/local/bin:/usr/bin:/bin");
    let mut vars = format!("Environment={}\n", quote(&format!("PATH={path}"), false));
    for (key, value) in env {
        vars.push_str(&format!(
            "Environment={}\n",
            quote(&format!("{key}={value}"), false)
        ));
    }
    let log = log_path.replace('%', "%%");
    format!(
        "# Written by `zc agent install`; `zc agent uninstall` removes it.\n\
[Unit]\n\
Description=Zakuro agent (zc agent run)\n\
After=network-online.target\n\
\n\
[Service]\n\
Type=simple\n\
ExecStart={zc} agent run\n\
Restart=always\n\
RestartSec=2\n\
TimeoutStopSec=60\n\
KillMode=process\n\
{vars}\
StandardOutput=append:{log}\n\
StandardError=append:{log}\n\
\n\
[Install]\n\
WantedBy=default.target\n",
        zc = quote(zc_path, true),
    )
}

fn run(systemctl: Systemctl, args: &[&str]) -> Result<(), String> {
    match systemctl(args) {
        Ok(s) if s.success() => Ok(()),
        Ok(s) => Err(format!(
            "`systemctl --user {}` failed ({s}). Is there a user systemd session? \
             Over SSH or in a container, log in as this user (or run \
             `loginctl enable-linger $USER` as root) and check that \
             XDG_RUNTIME_DIR is set.",
            args.join(" ")
        )),
        Err(e) => Err(format!("cannot run systemctl: {e}")),
    }
}

/// Rotate the agent token, write the unit, then (re)start it: `daemon-reload`,
/// `enable`, `restart` (which starts a stopped unit, and replaces a running
/// agent with the new token).
pub fn install(
    systemctl: Systemctl,
    unit: &Path,
    zc_path: &Path,
    home: &Path,
    env: &[(&str, String)],
    agent_dir: &Path,
    port: u16,
) -> Result<(), String> {
    crate::agent::files::load_or_init_agent_file(agent_dir, port, true)
        .map_err(|e| e.to_string())?;
    std::fs::create_dir_all(unit.parent().expect("the unit dir has a parent"))
        .map_err(|e| e.to_string())?;
    let log = agent_dir.join(crate::agent::files::LOG_FILE);
    std::fs::write(
        unit,
        render_unit(
            &zc_path.to_string_lossy(),
            &home.to_string_lossy(),
            env,
            &log.to_string_lossy(),
        ),
    )
    .map_err(|e| e.to_string())?;
    run(systemctl, &["daemon-reload"])?;
    run(systemctl, &["enable", UNIT])?;
    run(systemctl, &["restart", UNIT])
}

/// Stop and disable the unit (errors ignored: it may not be loaded), remove
/// the file, `daemon-reload`. `~/.zakuro/agent/` is kept.
pub fn uninstall(systemctl: Systemctl, unit: &Path) -> Result<(), String> {
    let _ = systemctl(&["disable", "--now", UNIT]);
    match std::fs::remove_file(unit) {
        Ok(()) => {}
        Err(e) if e.kind() == io::ErrorKind::NotFound => {}
        Err(e) => return Err(e.to_string()),
    }
    run(systemctl, &["daemon-reload"])
}

/// Without lingering, a user unit stops when the user's last session ends
/// (an SSH logout): systemd-logind records lingering users as files here.
pub fn lingering(user: &str, linger_dir: &Path) -> bool {
    !user.is_empty() && linger_dir.join(user).exists()
}

/// The real `systemctl --user`, its output discarded except on failure.
#[cfg(target_os = "linux")]
pub fn run_systemctl(args: &[&str]) -> io::Result<ExitStatus> {
    std::process::Command::new("systemctl")
        .arg("--user")
        .args(args)
        .stdout(std::process::Stdio::null())
        .status()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::files::tests::tmp;
    use std::cell::RefCell;

    #[cfg(unix)]
    fn status(code: i32) -> ExitStatus {
        use std::os::unix::process::ExitStatusExt;
        ExitStatus::from_raw(code << 8)
    }

    #[test]
    fn the_unit_runs_the_agent_with_its_settings_and_a_log() {
        let u = render_unit(
            "/home/jean/.local/bin/zc",
            "/home/jean",
            &[("ZAKURO_HOME", "/home/jean/.zk 100%".to_string())],
            "/home/jean/.zakuro/agent/agent.log",
        );
        assert!(
            u.contains("ExecStart=\"/home/jean/.local/bin/zc\" agent run\n"),
            "{u}"
        );
        assert!(u.contains("Restart=always\n") && u.contains("TimeoutStopSec=60\n"));
        assert!(u.contains("KillMode=process\n"));
        assert!(u.contains("Environment=\"PATH=/home/jean/.local/bin:/home/jean/.cargo/bin:"));
        assert!(
            u.contains("Environment=\"ZAKURO_HOME=/home/jean/.zk 100%%\"\n"),
            "{u}"
        );
        assert!(u.contains("StandardOutput=append:/home/jean/.zakuro/agent/agent.log\n"));
        assert!(u.contains("[Install]\nWantedBy=default.target\n"));
        assert_eq!(quote(r#"a"b\c$d"#, true), r#""a\"b\\c$$d""#);
        assert_eq!(quote("a$b", false), r#""a$b""#);
    }

    #[test]
    fn the_unit_lives_in_the_user_config_dir() {
        let home = Path::new("/home/jean");
        assert_eq!(
            unit_path(home, None),
            PathBuf::from("/home/jean/.config/systemd/user/zakuro-agent.service")
        );
        assert_eq!(
            unit_path(home, Some("/xdg")),
            PathBuf::from("/xdg/systemd/user/zakuro-agent.service")
        );
        assert_eq!(unit_path(home, Some("relative")), unit_path(home, None));
    }

    #[cfg(unix)]
    #[test]
    fn install_writes_the_unit_and_restarts_it_and_uninstall_removes_it() {
        let d = tmp("systemd");
        let unit = d.join("cfg/systemd/user").join(UNIT);
        let agent_dir = d.join("agent");
        let calls = RefCell::new(vec![]);
        let ok = |args: &[&str]| {
            calls.borrow_mut().push(args.join(" "));
            Ok(status(0))
        };
        install(&ok, &unit, Path::new("/bin/zc"), &d, &[], &agent_dir, 4720).unwrap();
        assert!(std::fs::read_to_string(&unit)
            .unwrap()
            .contains("agent run"));
        let first = crate::agent::files::load_json::<crate::agent::files::AgentFile>(
            &agent_dir.join(crate::agent::files::AGENT_FILE),
        )
        .unwrap();
        assert_eq!(
            calls.take(),
            vec![
                "daemon-reload".to_string(),
                format!("enable {UNIT}"),
                format!("restart {UNIT}")
            ]
        );
        install(&ok, &unit, Path::new("/bin/zc"), &d, &[], &agent_dir, 4720).unwrap();
        let second = crate::agent::files::load_json::<crate::agent::files::AgentFile>(
            &agent_dir.join(crate::agent::files::AGENT_FILE),
        )
        .unwrap();
        assert_ne!(first.token, second.token, "install re-mints the token");
        assert!(second.rev > first.rev);
        calls.take();

        uninstall(&ok, &unit).unwrap();
        assert!(!unit.exists());
        assert_eq!(
            calls.take(),
            vec![format!("disable --now {UNIT}"), "daemon-reload".to_string()]
        );
        uninstall(&ok, &unit).unwrap(); // idempotent
        assert!(
            agent_dir.join(crate::agent::files::AGENT_FILE).exists(),
            "agent dir kept"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_failing_systemctl_says_how_to_get_a_user_session() {
        let d = tmp("systemd-fail");
        let unit = d.join(UNIT);
        let fail = |_: &[&str]| Ok(status(1));
        let e = install(
            &fail,
            &unit,
            Path::new("/bin/zc"),
            &d,
            &[],
            &d.join("agent"),
            4720,
        )
        .unwrap_err();
        assert!(
            e.contains("daemon-reload") && e.contains("enable-linger"),
            "{e}"
        );
    }

    #[test]
    fn lingering_is_a_file_per_user() {
        let d = tmp("linger");
        std::fs::create_dir_all(&d).unwrap();
        assert!(!lingering("jean", &d));
        std::fs::write(d.join("jean"), "").unwrap();
        assert!(lingering("jean", &d));
        assert!(!lingering("", &d));
    }
}