allot-cli 0.5.0

CLI for Allot: status, leases, history, daemon control, install, and the PreToolUse hook
//! `allot daemon start|stop|status`.

use std::{
    thread,
    time::{Duration, Instant},
};

use allot_client::{BlockingClient, DaemonStart};
use anyhow::bail;
use serde::Serialize;

use crate::output::print_json;

const STOP_WAIT: Duration = Duration::from_secs(10);
const STOP_POLL: Duration = Duration::from_millis(100);

/// What `allot daemon status --json` prints when allotd is not running, in place of its health
/// response, which has no `running` field.
#[derive(Debug, Default, Serialize)]
struct NotRunning {
    running: bool,
}

/// Starts allotd in the background unless it is already running.
///
/// # Errors
///
/// Fails when allotd cannot be started or does not become ready.
pub fn start() -> anyhow::Result<()> {
    let client = BlockingClient::discover(true)?;
    let started = client.ensure_running()?;
    let health = client.health()?;
    let verb = match started {
        DaemonStart::AlreadyRunning => "already running",
        DaemonStart::Started => "started",
    };
    println!(
        "allotd {verb} at {} (pid {})",
        client.base_url(),
        health.pid
    );
    Ok(())
}

/// Asks allotd to shut down and waits until it stops answering.
///
/// # Errors
///
/// Fails when allotd refuses the request or keeps answering after the wait.
pub fn stop() -> anyhow::Result<()> {
    let client = BlockingClient::discover(false)?;
    match shutdown(&client)? {
        Some(_) => println!("allotd stopped"),
        None => println!("allotd is not running"),
    }
    Ok(())
}

/// Asks the allotd behind `client` to shut down and waits until it stops answering. Returns its
/// pid, or `None` when it was not running.
///
/// # Errors
///
/// Fails when allotd refuses the request or keeps answering after the wait.
pub fn shutdown(client: &BlockingClient) -> anyhow::Result<Option<u32>> {
    let pid = match client.health() {
        Ok(health) => health.pid,
        Err(error) if error.is_unsent() => return Ok(None),
        Err(error) => return Err(error.into()),
    };
    match client.shutdown() {
        Err(error) if error.is_unsent() => return Ok(None),
        other => other?,
    }
    let deadline = Instant::now() + STOP_WAIT;
    // A session may start a new allotd the moment the old one exits; only the old one counts.
    while client.health().is_ok_and(|health| health.pid == pid) {
        if Instant::now() >= deadline {
            bail!(
                "allotd is still answering {} s after the shutdown request",
                STOP_WAIT.as_secs()
            );
        }
        thread::sleep(STOP_POLL);
    }
    Ok(Some(pid))
}

/// Reports whether allotd is running, without starting it. With `json`, prints its health
/// response, or `{"running": false}` when it is not running.
///
/// # Errors
///
/// Fails when the local configuration cannot be read.
pub fn status(json: bool) -> anyhow::Result<()> {
    let client = BlockingClient::discover(false)?;
    match client.health() {
        Ok(health) if json => print_json(&health)?,
        Err(error) if json && error.is_unreachable() => print_json(&NotRunning::default())?,
        Ok(health) => {
            println!(
                "allotd {} running at {} (pid {}, up {} s)",
                health.version,
                client.base_url(),
                health.pid,
                health.uptime_secs
            );
            if let Some(error) = health.config_error {
                println!("config rejected, allotd keeps the previous one: {error}");
            }
        }
        Err(error) if error.is_unreachable() => {
            println!("allotd is not running at {}", client.base_url());
        }
        Err(error) => return Err(error.into()),
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_not_running_json_has_only_the_running_flag() {
        assert_eq!(
            serde_json::to_string(&NotRunning::default()).unwrap(),
            r#"{"running":false}"#
        );
    }
}